text
stringlengths
3
1.05M
#!/usr/bin/env python # -*- coding: utf-8 -*- from lib import Tk from lib.login import Login from lib.client import Client class PyChat(object): def __init__(self): self.root = Tk() self.root.geometry("300x275+400+100") def login(self): self.login = Login(self.root, self.create_client) def run(self): self.root.mainloop() def create_client(self): credentials = self.login.login_credentials() credentials['root'] = self.root credentials['port'] = int(credentials['port']) self.reset() self.client = Client(**credentials) def reset(self): for element in self.root.winfo_children(): element.destroy() if __name__ == '__main__': pychat = PyChat() pychat.login() pychat.run()
// COPYRIGHT © 2018 Esri // // All rights reserved under the copyright laws of the United States // and applicable international laws, treaties, and conventions. // // This material is licensed for use under the Esri Master License // Agreement (MLA), and is bound by the terms of that agreement. // You may redistribute and use this code without modification, // provided you adhere to the terms of the MLA and include this // copyright notice. // // See use restrictions at http://www.esri.com/legal/pdfs/mla_e204_e300/english // // For additional information, contact: // Environmental Systems Research Institute, Inc. // Attn: Contracts and Legal Services Department // 380 New York Street // Redlands, California, USA 92373 // USA // // email: contracts@esri.com // // See http://js.arcgis.com/4.10/esri/copyright.txt for details. define(["require","exports","../../core/tsSupport/declareExtendsHelper","../../core/tsSupport/decorateHelper","../../core/accessorSupport/decorators","./Domain"],function(e,r,n,t,a,o){return function(e){function r(r){var n=e.call(this,r)||this;return n.maxValue=null,n.minValue=null,n.type="range",n}n(r,e),o=r,r.prototype.clone=function(){return new o({maxValue:this.maxValue,minValue:this.minValue,name:this.name})};var o;return t([a.property({json:{read:{source:"range",reader:function(e,r){return r.range&&r.range[1]}},write:{target:"range",writer:function(e,r,n){r[n]=[this.minValue,e]}}}})],r.prototype,"maxValue",void 0),t([a.property({json:{read:{source:"range",reader:function(e,r){return r.range&&r.range[0]}},write:{target:"range",writer:function(e,r,n){r[n]=[e,this.maxValue]}}}})],r.prototype,"minValue",void 0),t([a.enumeration.serializable()({range:"range"})],r.prototype,"type",void 0),r=o=t([a.subclass("esri.layers.support.RangeDomain")],r)}(a.declared(o))});
import Component from '@ember/component'; import layout from '../../templates/components/tr-table/tr-table-column-header-presenter'; export default Component.extend({ layout, columnDefinition: null, filterValue: '', toggleSorting: null, columnState: null, applyColumnFilter: null });
const express = require('express'); const app = express(); app.use(express.json()); app.get('/courses', (request, response) => { const query = request.query; console.log(query); return response.json(["Curso 1", "Curso 2", "Curso 3"]); }); app.post('/courses', (request, response) => { const body = request.body; console.log(body); return response.json(["Curso 1", "Curso 2", "Curso 3"]); }); app.get('/courses', (request, response) => { return response.json(["Curso 1", "Curso 2", "Curso 3", "Curso 4"]); }); app.put('/courses/:id', (request, response) => { const { id } = request.params; console.log(id); return response.json(["Curso 6", "Curso 2", "Curso 3", "Curso 4"]); }); app.patch('/courses/:id', (request, response) => { return response.json(["Curso 6", "Curso 7", "Curso 3", "Curso 4"]); }); app.delete('/courses/:id', (request, response) => { return response.json(["Curso 6", "Curso 2", "Curso 4"]); }); app.listen(3333)
self["webpackHotUpdate_N_E"]("pages/index",{ /***/ "./src/components/Acomplishments/AcomplishmentsStyles.js": /*!***************************************************************!*\ !*** ./src/components/Acomplishments/AcomplishmentsStyles.js ***! \***************************************************************/ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ "Boxes": function() { return /* binding */ Boxes; }, /* harmony export */ "Box": function() { return /* binding */ Box; }, /* harmony export */ "BoxNum": function() { return /* binding */ BoxNum; }, /* harmony export */ "BoxText": function() { return /* binding */ BoxText; }, /* harmony export */ "Join": function() { return /* binding */ Join; }, /* harmony export */ "JoinText": function() { return /* binding */ JoinText; }, /* harmony export */ "IconContainer": function() { return /* binding */ IconContainer; }, /* harmony export */ "SocialIcons": function() { return /* binding */ SocialIcons; } /* harmony export */ }); /* harmony import */ var styled_components__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! styled-components */ "./node_modules/styled-components/dist/styled-components.browser.esm.js"); /* module decorator */ module = __webpack_require__.hmd(module); var Boxes = styled_components__WEBPACK_IMPORTED_MODULE_0__.default.div.withConfig({ displayName: "AcomplishmentsStyles__Boxes", componentId: "vuq5bz-0" })(["width:100%;display:grid;grid-template-columns:repeat(4,1fr);gap:24px;margin:24px 0 40px;@media ", "{gap:16px;margin:20px 0 32px;grid-template-columns:repeat(auto-fit,minmax(140px,1fr));}@media ", "{display:grid;grid-template-columns:repeat(2,1fr);gap:10px;max-width:500px;margin:24px auto;}"], function (props) { return props.theme.breakpoints.md; }, function (props) { return props.theme.breakpoints.sm; }); var Box = styled_components__WEBPACK_IMPORTED_MODULE_0__.default.div.withConfig({ displayName: "AcomplishmentsStyles__Box", componentId: "vuq5bz-1" })(["background:#212D45;border-radius:12px;height:224px;padding:24px;display:flex;align-items:center;@media ", "{height:210px;}@media ", "{height:135px;padding:16px;}@media ", "{height:110px;padding:12px;&:nth-child(2n){grid-row:2;}}"], function (props) { return props.theme.breakpoints.lg; }, function (props) { return props.theme.breakpoints.md; }, function (props) { return props.theme.breakpoints.sm; }); var BoxNum = styled_components__WEBPACK_IMPORTED_MODULE_0__.default.h5.withConfig({ displayName: "AcomplishmentsStyles__BoxNum", componentId: "vuq5bz-2" })(["font-style:normal;font-weight:600;font-size:36px;line-height:40px;letter-spacing:0.01em;color:#FFFFFF;margin-bottom:8px;@media ", "{font-size:28px;line-height:32px;}@media ", "{font-size:24px;line-height:26px;}"], function (props) { return props.theme.breakpoints.md; }, function (props) { return props.theme.breakpoints.sm; }); var BoxText = styled_components__WEBPACK_IMPORTED_MODULE_0__.default.p.withConfig({ displayName: "AcomplishmentsStyles__BoxText", componentId: "vuq5bz-3" })(["font-style:normal;font-weight:normal;font-size:18px;line-height:24px;letter-spacing:0.02em;color:rgba(255,255,255,0.75);@media ", "{font-size:16px;line-height:20px;};@media ", "{font-size:10px;line-height:14px;}"], function (props) { return props.theme.breakpoints.md; }, function (props) { return props.theme.breakpoints.sm; }); var Join = styled_components__WEBPACK_IMPORTED_MODULE_0__.default.div.withConfig({ displayName: "AcomplishmentsStyles__Join", componentId: "vuq5bz-4" })(["display:flex;max-width:1040px;justify-content:center;align-items:center;padding-bottom:80px;@media ", "{display:flex;justify-content:center;padding-bottom:64px;}@media ", "{display:flex;flex-direction:column;align-items:center;padding-bottom:32px;}"], function (props) { return props.theme.breakpoints.md; }, function (props) { return props.theme.breakpoints.sm; }); var JoinText = styled_components__WEBPACK_IMPORTED_MODULE_0__.default.h5.withConfig({ displayName: "AcomplishmentsStyles__JoinText", componentId: "vuq5bz-5" })(["display:flex;font-size:24px;line-height:40px;letter-spacing:0.02em;color:rgba(255,255,255,0.5);@media ", "{line-height:32px;font-size:20px;};@media ", "{font-size:16px;line-height:24px;margin:0 0 16px;}"], function (props) { return props.theme.breakpoints.md; }, function (props) { return props.theme.breakpoints.sm; }); var IconContainer = styled_components__WEBPACK_IMPORTED_MODULE_0__.default.div.withConfig({ displayName: "AcomplishmentsStyles__IconContainer", componentId: "vuq5bz-6" })(["flex:none;transition:fill 0.25s;width:48px;height:48px;@media ", "{width:160px;justify-content:space-between;}"], function (props) { return props.theme.breakpoints.sm; }); var SocialIcons = styled_components__WEBPACK_IMPORTED_MODULE_0__.default.a.withConfig({ displayName: "AcomplishmentsStyles__SocialIcons", componentId: "vuq5bz-7" })(["transition:0.3s ease;color:white;border-radius:50px;padding:8px;&:hover{background-color:#212d45;transform:scale(1.2);cursor:pointer;}"]); ; var _a, _b; // Legacy CSS implementations will `eval` browser code in a Node.js context // to extract CSS. For backwards compatibility, we need to check we're in a // browser context before continuing. if (typeof self !== 'undefined' && // AMP / No-JS mode does not inject these helpers: '$RefreshHelpers$' in self) { var currentExports = module.__proto__.exports; var prevExports = (_b = (_a = module.hot.data) === null || _a === void 0 ? void 0 : _a.prevExports) !== null && _b !== void 0 ? _b : null; // This cannot happen in MainTemplate because the exports mismatch between // templating and execution. self.$RefreshHelpers$.registerExportsForReactRefresh(currentExports, module.id); // A module can be accepted automatically based on its exports, e.g. when // it is a Refresh Boundary. if (self.$RefreshHelpers$.isReactRefreshBoundary(currentExports)) { // Save the previous exports on update so we can compare the boundary // signatures. module.hot.dispose(function (data) { data.prevExports = currentExports; }); // Unconditionally accept an update to this module, we'll check if it's // still a Refresh Boundary later. module.hot.accept(); // This field is set when the previous version of this module was a // Refresh Boundary, letting us know we need to check for invalidation or // enqueue an update. if (prevExports !== null) { // A boundary can become ineligible if its exports are incompatible // with the previous exports. // // For example, if you add/remove/change exports, we'll want to // re-execute the importing modules, and force those components to // re-render. Similarly, if you convert a class component to a // function, we want to invalidate the boundary. if (self.$RefreshHelpers$.shouldInvalidateReactRefreshBoundary(prevExports, currentExports)) { module.hot.invalidate(); } else { self.$RefreshHelpers$.scheduleUpdate(); } } } else { // Since we just executed the code for the module, it's possible that the // new exports made it ineligible for being a boundary. // We only care about the case when we were _previously_ a boundary, // because we already accepted this update (accidental side effect). var isNoLongerABoundary = prevExports !== null; if (isNoLongerABoundary) { module.hot.invalidate(); } } } /***/ }) }); //# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIndlYnBhY2s6Ly9fTl9FLy4vc3JjL2NvbXBvbmVudHMvQWNvbXBsaXNobWVudHMvQWNvbXBsaXNobWVudHNTdHlsZXMuanMiXSwibmFtZXMiOlsiQm94ZXMiLCJzdHlsZWQiLCJwcm9wcyIsInRoZW1lIiwiYnJlYWtwb2ludHMiLCJtZCIsInNtIiwiQm94IiwibGciLCJCb3hOdW0iLCJCb3hUZXh0IiwiSm9pbiIsIkpvaW5UZXh0IiwiSWNvbkNvbnRhaW5lciIsIlNvY2lhbEljb25zIl0sIm1hcHBpbmdzIjoiOzs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7O0FBQUE7QUFFTyxJQUFNQSxLQUFLLEdBQUdDLHFFQUFIO0FBQUE7QUFBQTtBQUFBLDJTQU9QLFVBQUFDLEtBQUs7QUFBQSxTQUFJQSxLQUFLLENBQUNDLEtBQU4sQ0FBWUMsV0FBWixDQUF3QkMsRUFBNUI7QUFBQSxDQVBFLEVBYVAsVUFBQUgsS0FBSztBQUFBLFNBQUlBLEtBQUssQ0FBQ0MsS0FBTixDQUFZQyxXQUFaLENBQXdCRSxFQUE1QjtBQUFBLENBYkUsQ0FBWDtBQXNCQSxJQUFNQyxHQUFHLEdBQUdOLHFFQUFIO0FBQUE7QUFBQTtBQUFBLDZPQU9MLFVBQUFDLEtBQUs7QUFBQSxTQUFJQSxLQUFLLENBQUNDLEtBQU4sQ0FBWUMsV0FBWixDQUF3QkksRUFBNUI7QUFBQSxDQVBBLEVBWUwsVUFBQU4sS0FBSztBQUFBLFNBQUlBLEtBQUssQ0FBQ0MsS0FBTixDQUFZQyxXQUFaLENBQXdCQyxFQUE1QjtBQUFBLENBWkEsRUFpQkwsVUFBQUgsS0FBSztBQUFBLFNBQUlBLEtBQUssQ0FBQ0MsS0FBTixDQUFZQyxXQUFaLENBQXdCRSxFQUE1QjtBQUFBLENBakJBLENBQVQ7QUEwQkEsSUFBTUcsTUFBTSxHQUFHUixvRUFBSDtBQUFBO0FBQUE7QUFBQSwyTkFTUixVQUFBQyxLQUFLO0FBQUEsU0FBSUEsS0FBSyxDQUFDQyxLQUFOLENBQVlDLFdBQVosQ0FBd0JDLEVBQTVCO0FBQUEsQ0FURyxFQWFSLFVBQUFILEtBQUs7QUFBQSxTQUFJQSxLQUFLLENBQUNDLEtBQU4sQ0FBWUMsV0FBWixDQUF3QkUsRUFBNUI7QUFBQSxDQWJHLENBQVo7QUFtQkEsSUFBTUksT0FBTyxHQUFHVCxtRUFBSDtBQUFBO0FBQUE7QUFBQSw0TkFRVCxVQUFBQyxLQUFLO0FBQUEsU0FBSUEsS0FBSyxDQUFDQyxLQUFOLENBQVlDLFdBQVosQ0FBd0JDLEVBQTVCO0FBQUEsQ0FSSSxFQWFULFVBQUFILEtBQUs7QUFBQSxTQUFJQSxLQUFLLENBQUNDLEtBQU4sQ0FBWUMsV0FBWixDQUF3QkUsRUFBNUI7QUFBQSxDQWJJLENBQWI7QUFtQkEsSUFBTUssSUFBSSxHQUFHVixxRUFBSDtBQUFBO0FBQUE7QUFBQSxpUUFPTixVQUFBQyxLQUFLO0FBQUEsU0FBSUEsS0FBSyxDQUFDQyxLQUFOLENBQVlDLFdBQVosQ0FBd0JDLEVBQTVCO0FBQUEsQ0FQQyxFQWFOLFVBQUFILEtBQUs7QUFBQSxTQUFJQSxLQUFLLENBQUNDLEtBQU4sQ0FBWUMsV0FBWixDQUF3QkUsRUFBNUI7QUFBQSxDQWJDLENBQVY7QUFxQkEsSUFBTU0sUUFBUSxHQUFHWCxvRUFBSDtBQUFBO0FBQUE7QUFBQSxtTkFPWixVQUFBQyxLQUFLO0FBQUEsU0FBSUEsS0FBSyxDQUFDQyxLQUFOLENBQVlDLFdBQVosQ0FBd0JDLEVBQTVCO0FBQUEsQ0FQTyxFQVlaLFVBQUFILEtBQUs7QUFBQSxTQUFJQSxLQUFLLENBQUNDLEtBQU4sQ0FBWUMsV0FBWixDQUF3QkUsRUFBNUI7QUFBQSxDQVpPLENBQWQ7QUFtQkEsSUFBTU8sYUFBYSxHQUFHWixxRUFBSDtBQUFBO0FBQUE7QUFBQSx1SEFNZixVQUFBQyxLQUFLO0FBQUEsU0FBSUEsS0FBSyxDQUFDQyxLQUFOLENBQVlDLFdBQVosQ0FBd0JFLEVBQTVCO0FBQUEsQ0FOVSxDQUFuQjtBQVlBLElBQU1RLFdBQVcsR0FBR2IsbUVBQUg7QUFBQTtBQUFBO0FBQUEsOElBQWpCIiwiZmlsZSI6InN0YXRpYy93ZWJwYWNrL3BhZ2VzL2luZGV4LjM4ODE0NzI1MGJmYmQxMThiZmIxLmhvdC11cGRhdGUuanMiLCJzb3VyY2VzQ29udGVudCI6WyJpbXBvcnQgc3R5bGVkIGZyb20gXCJzdHlsZWQtY29tcG9uZW50c1wiXG5cbmV4cG9ydCBjb25zdCBCb3hlcyA9IHN0eWxlZC5kaXZgXG4gIHdpZHRoOiAxMDAlO1xuICBkaXNwbGF5OiBncmlkO1xuICBncmlkLXRlbXBsYXRlLWNvbHVtbnM6IHJlcGVhdCg0LCAxZnIpO1xuICBnYXA6IDI0cHg7XG4gIG1hcmdpbjogMjRweCAwIDQwcHg7XG5cbiAgQG1lZGlhICR7cHJvcHMgPT4gcHJvcHMudGhlbWUuYnJlYWtwb2ludHMubWR9e1xuICAgIGdhcDogMTZweDtcbiAgICBtYXJnaW46IDIwcHggMCAzMnB4O1xuICAgIGdyaWQtdGVtcGxhdGUtY29sdW1uczogcmVwZWF0KGF1dG8tZml0LCBtaW5tYXgoMTQwcHgsIDFmcikpO1xuICB9XG5cbiAgQG1lZGlhICR7cHJvcHMgPT4gcHJvcHMudGhlbWUuYnJlYWtwb2ludHMuc219e1xuICAgIGRpc3BsYXk6IGdyaWQ7XG4gICAgZ3JpZC10ZW1wbGF0ZS1jb2x1bW5zOiByZXBlYXQoMiwgMWZyKTtcbiAgICBnYXA6IDEwcHg7XG4gICAgbWF4LXdpZHRoOiA1MDBweDtcbiAgICBtYXJnaW46IDI0cHggYXV0bztcbiAgfVxuYFxuXG5leHBvcnQgY29uc3QgQm94ID0gc3R5bGVkLmRpdmBcbiAgYmFja2dyb3VuZDogIzIxMkQ0NTtcbiAgYm9yZGVyLXJhZGl1czogMTJweDtcbiAgaGVpZ2h0OiAyMjRweDtcbiAgcGFkZGluZzogMjRweDtcbiAgZGlzcGxheTogZmxleDtcbiAgYWxpZ24taXRlbXM6IGNlbnRlcjtcbiAgQG1lZGlhICR7cHJvcHMgPT4gcHJvcHMudGhlbWUuYnJlYWtwb2ludHMubGd9IHtcbiAgICBoZWlnaHQ6IDIxMHB4O1xuXG4gIH1cblxuICBAbWVkaWEgJHtwcm9wcyA9PiBwcm9wcy50aGVtZS5icmVha3BvaW50cy5tZH0ge1xuICAgIGhlaWdodDogMTM1cHg7XG4gICAgcGFkZGluZzogMTZweDtcbiAgfVxuXG4gIEBtZWRpYSAke3Byb3BzID0+IHByb3BzLnRoZW1lLmJyZWFrcG9pbnRzLnNtfSB7XG4gICAgaGVpZ2h0OiAxMTBweDtcbiAgICBwYWRkaW5nOiAxMnB4O1xuICAgIFxuICAgICY6bnRoLWNoaWxkKDJuKXtcbiAgICAgIGdyaWQtcm93OjI7XG4gICAgfVxuICB9XG5gXG5leHBvcnQgY29uc3QgQm94TnVtID0gc3R5bGVkLmg1YFxuICBmb250LXN0eWxlOiBub3JtYWw7XG4gIGZvbnQtd2VpZ2h0OiA2MDA7XG4gIGZvbnQtc2l6ZTogMzZweDtcbiAgbGluZS1oZWlnaHQ6IDQwcHg7XG4gIGxldHRlci1zcGFjaW5nOiAwLjAxZW07XG4gIGNvbG9yOiAjRkZGRkZGO1xuICBtYXJnaW4tYm90dG9tOiA4cHg7XG5cbiAgQG1lZGlhICR7cHJvcHMgPT4gcHJvcHMudGhlbWUuYnJlYWtwb2ludHMubWR9IHtcbiAgICBmb250LXNpemU6IDI4cHg7XG4gICAgbGluZS1oZWlnaHQ6IDMycHg7XG4gIH1cbiAgQG1lZGlhICR7cHJvcHMgPT4gcHJvcHMudGhlbWUuYnJlYWtwb2ludHMuc219IHtcbiAgICBmb250LXNpemU6IDI0cHg7XG4gICAgbGluZS1oZWlnaHQ6IDI2cHg7XG59XG5gXG5cbmV4cG9ydCBjb25zdCBCb3hUZXh0ID0gc3R5bGVkLnBgXG4gIGZvbnQtc3R5bGU6IG5vcm1hbDtcbiAgZm9udC13ZWlnaHQ6IG5vcm1hbDtcbiAgZm9udC1zaXplOiAxOHB4O1xuICBsaW5lLWhlaWdodDogMjRweDtcbiAgbGV0dGVyLXNwYWNpbmc6IDAuMDJlbTtcbiAgY29sb3I6IHJnYmEoMjU1LCAyNTUsIDI1NSwgMC43NSk7XG5cbiAgQG1lZGlhICR7cHJvcHMgPT4gcHJvcHMudGhlbWUuYnJlYWtwb2ludHMubWR9e1xuICAgIGZvbnQtc2l6ZTogMTZweDtcbiAgICBsaW5lLWhlaWdodDogMjBweDtcbiAgfTtcblxuICBAbWVkaWEgJHtwcm9wcyA9PiBwcm9wcy50aGVtZS5icmVha3BvaW50cy5zbX0ge1xuICAgIGZvbnQtc2l6ZTogMTBweDtcbiAgICBsaW5lLWhlaWdodDogMTRweDtcbiAgfVxuYFxuXG5leHBvcnQgY29uc3QgSm9pbiA9IHN0eWxlZC5kaXZgXG4gIGRpc3BsYXk6IGZsZXg7XG4gIG1heC13aWR0aDogMTA0MHB4O1xuICBqdXN0aWZ5LWNvbnRlbnQ6IGNlbnRlcjtcbiAgYWxpZ24taXRlbXM6IGNlbnRlcjtcbiAgcGFkZGluZy1ib3R0b206IDgwcHg7XG5cbiAgQG1lZGlhICR7cHJvcHMgPT4gcHJvcHMudGhlbWUuYnJlYWtwb2ludHMubWR9e1xuICAgIGRpc3BsYXk6IGZsZXg7XG4gICAganVzdGlmeS1jb250ZW50OiBjZW50ZXI7XG4gICAgcGFkZGluZy1ib3R0b206IDY0cHg7XG4gIH1cblxuICBAbWVkaWEgJHtwcm9wcyA9PiBwcm9wcy50aGVtZS5icmVha3BvaW50cy5zbX17XG4gICAgZGlzcGxheTogZmxleDtcbiAgICBmbGV4LWRpcmVjdGlvbjogY29sdW1uO1xuICAgIGFsaWduLWl0ZW1zOiBjZW50ZXI7XG4gICAgcGFkZGluZy1ib3R0b206IDMycHg7XG4gIH1cbmBcblxuZXhwb3J0IGNvbnN0IEpvaW5UZXh0ID0gc3R5bGVkLmg1YFxuICBkaXNwbGF5OiBmbGV4O1xuICBmb250LXNpemU6IDI0cHg7XG4gIGxpbmUtaGVpZ2h0OiA0MHB4O1xuICBsZXR0ZXItc3BhY2luZzogMC4wMmVtO1xuICBjb2xvcjogcmdiYSgyNTUsIDI1NSwgMjU1LCAwLjUpO1xuXG5AbWVkaWEgJHtwcm9wcyA9PiBwcm9wcy50aGVtZS5icmVha3BvaW50cy5tZH17XG4gIGxpbmUtaGVpZ2h0OiAzMnB4O1xuICBmb250LXNpemU6IDIwcHg7XG59O1xuXG5AbWVkaWEgJHtwcm9wcyA9PiBwcm9wcy50aGVtZS5icmVha3BvaW50cy5zbX17XG4gIGZvbnQtc2l6ZTogMTZweDtcbiAgbGluZS1oZWlnaHQ6IDI0cHg7XG4gIG1hcmdpbjogMCAwIDE2cHg7XG59XG5gXG5cbmV4cG9ydCBjb25zdCBJY29uQ29udGFpbmVyID0gc3R5bGVkLmRpdmBcbiAgZmxleDogbm9uZTtcbiAgdHJhbnNpdGlvbjogZmlsbCAwLjI1cztcbiAgd2lkdGg6IDQ4cHg7XG4gIGhlaWdodDogNDhweDtcblxuICBAbWVkaWEgJHtwcm9wcyA9PiBwcm9wcy50aGVtZS5icmVha3BvaW50cy5zbX17XG4gICAgd2lkdGg6IDE2MHB4O1xuICAgIGp1c3RpZnktY29udGVudDogc3BhY2UtYmV0d2VlbjtcbiAgfVxuYFxuXG5leHBvcnQgY29uc3QgU29jaWFsSWNvbnMgPSBzdHlsZWQuYWBcbnRyYW5zaXRpb246IDAuM3MgZWFzZTtcbmNvbG9yOiB3aGl0ZTtcbmJvcmRlci1yYWRpdXM6IDUwcHg7XG4gIHBhZGRpbmc6IDhweDtcbiY6aG92ZXIge1xuICAgIGJhY2tncm91bmQtY29sb3I6ICMyMTJkNDU7XG4gICAgdHJhbnNmb3JtOiBzY2FsZSgxLjIpO1xuICAgIGN1cnNvcjogcG9pbnRlcjtcbiAgICBcbiAgfVxuYCJdLCJzb3VyY2VSb290IjoiIn0=
import json import logging import os from cate.conf import USER_PREFERENCES_FILE, DEFAULT_DATA_PATH _DEFAULT_USER_PREFS = { "reopenLastWorkspace": True, "lastWorkspacePath": "", "autoUpdateSoftware": True, "autoShowNewFigures": True, "offlineMode": False, "showSelectedVariableLayer": True, "savedLayers": {}, "selectedDataStoreId": "", "selectedDataSourceId": None, "dataSourceFilterExpr": "", "selectedOperationName": None, "operationFilterTags": [], "operationFilterExpr": "", "dataSourceListHeight": 200, "showDataSourceDetails": True, "resourceListHeight": 100, "showResourceDetails": True, "workflowStepListHeight": 100, "showWorkflowStepDetails": True, "operationListHeight": 200, "showOperationDetails": True, "variableListHeight": 200, "showVariableDetails": True, "layerListHeight": 160, "showLayerDetails": True, "panelContainerUndockedMode": False, "leftPanelContainerLayout": { "horPos": 300, "verPos": 400 }, "rightPanelContainerLayout": { "horPos": 300, "verPos": 400 }, "selectedLeftTopPanelId": "dataSources", "selectedLeftBottomPanelId": "operations", "selectedRightTopPanelId": "workspace", "selectedRightBottomPanelId": "variables", "placemarkCollection": { "type": "FeatureCollection", "features": [] }, "selectedPlacemarkId": None, "placemarkListHeight": 160, "showPlacemarkDetails": True, "defaultPlacemarkStyle": { "markerSize": "small", "markerColor": "#ff0000", "markerSymbol": "", "fill": "#0000ff", "fillOpacity": 0.5, "stroke": "#ffff00", "strokeOpacity": 0.5, "strokeWidth": 1 }, "workspacePanelMode": "steps", "showDataStoreDescription": False, "showDataStoreNotices": True, "showDataSourceIDs": True, "showLayerTextOverlay": True, "debugWorldView": False, "styleContext": "entity", "backendConfig": { "dataStoresPath": "~/.cate/data_stores", "useWorkspaceImageryCache": False, "resourceNamePattern": "res_{index}", "proxyUrl": None } } _LOG = logging.getLogger('cate') def _write_user_prefs_file(user_prefs_file: str, user_prefs: dict): try: with open(user_prefs_file, 'w') as fp: json.dump(user_prefs, fp) except Exception as error: _LOG.warning('failed writing %s: %s' % (user_prefs_file, str(error))) def _read_user_prefs(user_prefs_file: str) -> dict: user_prefs = dict() if user_prefs_file and os.path.isfile(user_prefs_file): with open(user_prefs_file, 'r') as pfile: user_prefs = json.load(pfile) return user_prefs def set_user_prefs(prefs: dict, user_prefs_file: str = None): if not user_prefs_file: user_prefs_file = os.path.join(DEFAULT_DATA_PATH, USER_PREFERENCES_FILE) if not os.path.isfile(user_prefs_file): _write_user_prefs_file(user_prefs_file, _DEFAULT_USER_PREFS) else: _prefs = get_user_prefs(user_prefs_file) _prefs.update(prefs) _write_user_prefs_file(user_prefs_file, _prefs) def get_user_prefs(user_prefs_file: str = None) -> dict: if not user_prefs_file: user_prefs_file = os.path.join(DEFAULT_DATA_PATH, USER_PREFERENCES_FILE) if not os.path.isfile(user_prefs_file): _write_user_prefs_file(user_prefs_file, _DEFAULT_USER_PREFS) return _read_user_prefs(user_prefs_file)
#ifdef __OBJC__ #import <UIKit/UIKit.h> #endif FOUNDATION_EXPORT double Pods_TJPYingKeVersionNumber; FOUNDATION_EXPORT const unsigned char Pods_TJPYingKeVersionString[];
import collections import gzip import tempfile import pytest from galaxy.tool_util.verify import ( files_contains, files_delta, files_diff, files_re_match, files_re_match_multiline, ) F1 = b"A\nB\nC" F2 = b"A\nB\nD\nE" * 61 F3 = b"A\nB\n\xfc" F4 = b"A\r\nB\nC" MULTILINE_MATCH = b".*" TestFile = collections.namedtuple('TestFile', 'value path') def test_file_list(): files = [] for b, ext in [(F1, '.txt'), (F2, '.txt'), (F3, '.pdf'), (F4, '.txt'), (MULTILINE_MATCH, '.txt'), (F1, '.txt.gz')]: with tempfile.NamedTemporaryFile(mode='wb', suffix=ext, delete=False) as out: if ext == '.txt.gz': b = gzip.compress(b) out.write(b) files.append(TestFile(b, out.name)) return files def generate_tests(multiline=False): f1, f2, f3, f4, multiline_match, f5 = test_file_list() if multiline: tests = [(multiline_match, f1, {'lines_diff': 0, 'sort': True}, None)] else: tests = [(f1, f1, {'lines_diff': 0, 'sort': True}, None)] tests.extend([ (f1, f2, {'lines_diff': 0, 'sort': True}, AssertionError), (f1, f3, None, AssertionError), (f1, f4, None, None), (f1, f5, {'decompress': True}, None), ]) return tests def generate_tests_sim_size(): f1, f2, f3, f4, multiline_match, f5 = test_file_list() # tests for equal files tests = [(f1, f1, None, None), # pass default values (f1, f1, {'delta': 0}, None), # pass for values that should always pass (f1, f1, {'delta_frac': 0.0}, None)] # tests for two different file (diff is 422 lines, 0.011709602) tests += [(f1, f2, None, None), # pass default values (f1, f2, {'delta': 422}, None), # test around the actual difference of two different (f1, f2, {'delta_frac': 84.4}, None), (f1, f2, {'delta': 421}, AssertionError), (f1, f2, {'delta_frac': 84.3}, AssertionError), (f1, f2, {'delta': 422, 'delta_frac': 84.3}, AssertionError), # test with combination where at least one leads to an assertion (f1, f2, {'delta': 421, 'delta_frac': 84.4}, AssertionError)] return tests @pytest.mark.parametrize('file1,file2,attributes,expect', generate_tests()) def test_files_contains(file1, file2, attributes, expect): if expect is not None: with pytest.raises(expect): files_contains(file1.path, file2.path, attributes) else: files_contains(file2.path, file2.path, attributes) @pytest.mark.parametrize('file1,file2,attributes,expect', generate_tests_sim_size()) def test_files_delta(file1, file2, attributes, expect): if expect is not None: with pytest.raises(expect): files_delta(file1.path, file2.path, attributes) else: files_delta(file1.path, file2.path, attributes) @pytest.mark.parametrize('file1,file2,attributes,expect', generate_tests()) def test_files_diff(file1, file2, attributes, expect): if expect is not None: with pytest.raises(expect): files_diff(file1.path, file2.path, attributes) else: files_diff(file1.path, file2.path, attributes) @pytest.mark.parametrize('file1,file2,attributes,expect', generate_tests()) def test_files_re_match(file1, file2, attributes, expect): if expect is not None: with pytest.raises(expect): files_re_match(file1.path, file2.path, attributes) else: files_re_match(file1.path, file2.path, attributes) @pytest.mark.parametrize('file1,file2,attributes,expect', generate_tests(multiline=True)) def test_files_re_match_multiline(file1, file2, attributes, expect): if expect is not None: with pytest.raises(expect): files_re_match_multiline(file1.path, file2.path, attributes) else: files_re_match_multiline(file1.path, file2.path, attributes)
#ifndef SERVO_H #define SERVO_H #include <avr/io.h> class Servo { public: /** * Aktiviert das Servo Signal */ void enable(void) volatile; /** * Deaktiviert das Servo Signal */ void disable(void) const volatile; /** * Setzt die Pulselänge und damit die Servo Position */ void setPosition(uint16_t pos) const volatile; /** * Beendet den aktuellen Impuls. Wird von der zugehörigen Interrupt-Routine aufgerufen. */ void handleTimer1(void) const volatile; /** * Inkrementiert die Frequenzsteuerung und löst gegebenenfalls einen neuen Impuls aus. */ void handleTimer2(void) volatile; private: uint8_t repetition_counter; static constexpr uint8_t PRESCALER_IMPULSE = _BV(CS11); // prescaler 8 }; #endif // SERVO_H
Clazz.declarePackage ("J.jvxl.readers"); Clazz.load (["JU.P3", "$.V3"], "J.jvxl.readers.SurfaceGenerator", ["java.lang.Float", "java.util.Map", "JU.AU", "$.BS", "$.Measure", "$.P4", "$.PT", "$.Rdr", "J.jvxl.data.JvxlData", "$.MeshData", "$.VolumeData", "J.jvxl.readers.Parameters", "$.SurfaceReader", "JU.Logger", "JV.FileManager"], function () { c$ = Clazz.decorateAsClass (function () { this.params = null; this.jvxlData = null; this.meshData = null; this.volumeDataTemp = null; this.meshDataServer = null; this.atomDataServer = null; this.marchingSquares = null; this.version = null; this.isValid = true; this.fileType = null; this.bsVdw = null; this.colorPtr = 0; this.surfaceReader = null; this.out = null; this.readerData = null; this.vAB = null; this.vNorm = null; this.ptRef = null; Clazz.instantialize (this, arguments); }, J.jvxl.readers, "SurfaceGenerator"); Clazz.prepareFields (c$, function () { this.vAB = new JU.V3 (); this.vNorm = new JU.V3 (); this.ptRef = JU.P3.new3 (0, 0, 1e15); }); Clazz.makeConstructor (c$, function (atomDataServer, meshDataServer, meshData, jvxlData) { this.atomDataServer = atomDataServer; this.meshDataServer = meshDataServer; this.params = new J.jvxl.readers.Parameters (); this.meshData = (meshData == null ? new J.jvxl.data.MeshData () : meshData); this.jvxlData = (jvxlData == null ? new J.jvxl.data.JvxlData () : jvxlData); this.volumeDataTemp = new J.jvxl.data.VolumeData (); this.initializeIsosurface (); }, "J.atomdata.AtomDataServer,J.jvxl.api.MeshDataServer,J.jvxl.data.MeshData,J.jvxl.data.JvxlData"); Clazz.defineMethod (c$, "setJvxlData", function (jvxlData) { this.jvxlData = jvxlData; if (jvxlData != null) jvxlData.version = this.version; }, "J.jvxl.data.JvxlData"); Clazz.defineMethod (c$, "setProp", function (propertyName, value, bs) { if ("debug" === propertyName) { var TF = (value).booleanValue (); this.params.logMessages = TF; this.params.logCube = TF; return true; }if ("init" === propertyName) { this.initializeIsosurface (); if (Clazz.instanceOf (value, J.jvxl.readers.Parameters)) { this.params = value; } else { this.params.script = value; if (this.params.script != null && this.params.script.indexOf (";#") >= 0) { this.params.script = JU.PT.rep (this.params.script, ";#", "; #"); }}return false; }if ("silent" === propertyName) { this.params.isSilent = true; return true; }if ("map" === propertyName) { this.params.resetForMapping ((value).booleanValue ()); if (this.surfaceReader != null) this.surfaceReader.minMax = null; return true; }if ("finalize" === propertyName) { this.initializeIsosurface (); return true; }if ("clear" === propertyName) { if (this.surfaceReader != null) this.surfaceReader.discardTempData (true); return false; }if ("fileIndex" === propertyName) { this.params.fileIndex = (value).intValue (); if (this.params.fileIndex < 0) this.params.fileIndex = 0; this.params.readAllData = false; return true; }if ("blockData" === propertyName) { this.params.blockCubeData = (value).booleanValue (); return true; }if ("withinPoints" === propertyName) { this.params.boundingBox = (value)[1]; return true; }if ("boundingBox" === propertyName) { var pts = value; this.params.boundingBox = Clazz.newArray (-1, [JU.P3.newP (pts[0]), JU.P3.newP (pts[pts.length - 1])]); return true; }if ("func" === propertyName) { this.params.func = value; return true; }if ("intersection" === propertyName) { this.params.intersection = value; return true; }if ("bsSolvent" === propertyName) { this.params.bsSolvent = value; return true; }if ("select" === propertyName) { this.params.bsSelected = value; return true; }if ("ignore" === propertyName) { this.params.bsIgnore = value; return true; }if ("propertySmoothing" === propertyName) { this.params.propertySmoothing = (value).booleanValue (); return true; }if ("propertyDistanceMax" === propertyName) { this.params.propertyDistanceMax = (value).floatValue (); return true; }if ("propertySmoothingPower" === propertyName) { this.params.propertySmoothingPower = (value).intValue (); return true; }if ("title" === propertyName) { if (value == null) { this.params.title = null; return true; } else if (JU.AU.isAS (value)) { this.params.title = value; if (JU.Logger.debugging) for (var i = 0; i < this.params.title.length; i++) if (this.params.title[i].length > 0) JU.Logger.info (this.params.title[i]); }return true; }if ("sigma" === propertyName) { this.params.cutoff = this.params.sigma = (value).floatValue (); this.params.isPositiveOnly = false; this.params.cutoffAutomatic = false; return true; }if ("cutoff" === propertyName) { this.params.cutoff = (value).floatValue (); this.params.isPositiveOnly = false; this.params.cutoffAutomatic = false; return true; }if ("parameters" === propertyName) { this.params.parameters = JU.AU.ensureLengthA (value, 2); if (this.params.parameters.length > 0 && this.params.parameters[0] != 0) this.params.cutoff = this.params.parameters[0]; return true; }if ("cutoffPositive" === propertyName) { this.params.cutoff = (value).floatValue (); this.params.isPositiveOnly = true; return true; }if ("cap" === propertyName || "slab" === propertyName) { if (value != null) this.params.addSlabInfo (value); return true; }if ("scale" === propertyName) { this.params.scale = (value).floatValue (); return true; }if ("scale3d" === propertyName) { this.params.scale3d = (value).floatValue (); return true; }if ("angstroms" === propertyName) { this.params.isAngstroms = true; return true; }if ("resolution" === propertyName) { var resolution = (value).floatValue (); this.params.resolution = (resolution > 0 ? resolution : 3.4028235E38); return true; }if ("downsample" === propertyName) { var rate = (value).intValue (); this.params.downsampleFactor = (rate >= 0 ? rate : 0); return true; }if ("anisotropy" === propertyName) { if ((this.params.dataType & 32) == 0) this.params.setAnisotropy (value); return true; }if ("eccentricity" === propertyName) { this.params.setEccentricity (value); return true; }if ("addHydrogens" === propertyName) { this.params.addHydrogens = (value).booleanValue (); return true; }if ("squareData" === propertyName) { this.params.isSquared = (value == null ? false : (value).booleanValue ()); return true; }if ("squareLinear" === propertyName) { this.params.isSquaredLinear = (value == null ? false : (value).booleanValue ()); return true; }if ("gridPoints" === propertyName) { this.params.iAddGridPoints = true; return true; }if ("atomIndex" === propertyName) { this.params.atomIndex = (value).intValue (); return true; }if ("insideOut" === propertyName) { this.params.insideOut = true; return true; }if ("sign" === propertyName) { this.params.isCutoffAbsolute = true; this.params.colorBySign = true; this.colorPtr = 0; return true; }if ("colorRGB" === propertyName) { var rgb = (value).intValue (); this.params.colorRgb = this.params.colorPos = this.params.colorPosLCAO = rgb; if (this.colorPtr++ == 0) { this.params.colorNeg = this.params.colorNegLCAO = rgb; } else { this.params.colorRgb = 2147483647; }return true; }if ("monteCarloCount" === propertyName) { this.params.psi_monteCarloCount = (value).intValue (); return true; }if ("rangeAll" === propertyName) { this.params.rangeAll = true; return true; }if ("rangeSelected" === propertyName) { this.params.rangeSelected = true; return true; }if ("red" === propertyName) { this.params.valueMappedToRed = (value).floatValue (); return true; }if ("blue" === propertyName) { this.params.valueMappedToBlue = (value).floatValue (); if (this.params.valueMappedToRed > this.params.valueMappedToBlue) { var f = this.params.valueMappedToRed; this.params.valueMappedToRed = this.params.valueMappedToBlue; this.params.valueMappedToBlue = f; this.params.isColorReversed = !this.params.isColorReversed; }this.params.rangeDefined = true; this.params.rangeAll = false; return true; }if ("reverseColor" === propertyName) { this.params.isColorReversed = true; return true; }if ("setColorScheme" === propertyName) { this.getSurfaceSets (); this.params.colorBySets = true; this.mapSurface (); return true; }if ("center" === propertyName) { this.params.center.setT (value); return true; }if ("origin" === propertyName) { this.params.origin = value; return true; }if ("step" === propertyName) { this.params.steps = value; return true; }if ("modelInvRotation" === propertyName) { this.params.modelInvRotation = value; return true; }if ("point" === propertyName) { this.params.points = value; return true; }if ("withinDistance" === propertyName) { this.params.distance = (value).floatValue (); return true; }if ("withinPoint" === propertyName) { this.params.point = value; return true; }if ("progressive" === propertyName) { this.params.isXLowToHigh = true; return true; }if ("phase" === propertyName) { var color = value; this.params.isCutoffAbsolute = true; this.params.colorBySign = true; this.params.colorByPhase = true; this.params.colorPhase = J.jvxl.readers.SurfaceReader.getColorPhaseIndex (color); if (this.params.colorPhase < 0) { JU.Logger.warn (" invalid color phase: " + color); this.params.colorPhase = 0; }this.params.colorByPhase = this.params.colorPhase != 0; if (this.params.state >= 2) { this.params.dataType = this.params.surfaceType; this.params.state = 3; this.params.isBicolorMap = true; this.surfaceReader.applyColorScale (); }return true; }if ("radius" === propertyName) { JU.Logger.info ("solvent probe radius set to " + value); this.params.atomRadiusData = value; return true; }if ("envelopeRadius" === propertyName) { this.params.envelopeRadius = (value).floatValue (); return true; }if ("cavityRadius" === propertyName) { this.params.cavityRadius = (value).floatValue (); return true; }if ("cavity" === propertyName) { this.params.isCavity = true; return true; }if ("doFullMolecular" === propertyName) { this.params.doFullMolecular = true; return true; }if ("pocket" === propertyName) { this.params.pocket = value; this.params.fullyLit = this.params.pocket.booleanValue (); return true; }if ("minset" === propertyName) { this.params.minSet = (value).intValue (); return true; }if ("maxset" === propertyName) { this.params.maxSet = (value).intValue (); return true; }if ("plane" === propertyName) { this.params.setPlane (value); return true; }if ("contour" === propertyName) { this.params.isContoured = true; var n; if (JU.AU.isAF (value)) { this.params.contoursDiscrete = value; this.params.nContours = this.params.contoursDiscrete.length; } else if (Clazz.instanceOf (value, JU.P3)) { var pt = this.params.contourIncrements = value; var from = pt.x; var to = pt.y; var step = pt.z; if (step <= 0) step = 1; n = 0; for (var p = from; p <= to + step / 10; p += step, n++) { } this.params.contoursDiscrete = Clazz.newFloatArray (n, 0); var p = from; for (var i = 0; i < n; i++, p += step) { this.params.contoursDiscrete[i] = p; } this.params.nContours = n; } else { n = (value).intValue (); this.params.thisContour = 0; if (n == 0) this.params.nContours = 9; else if (n > 0) this.params.nContours = n; else this.params.thisContour = -n; }return true; }if ("colorDiscrete" === propertyName) { this.params.contourColixes = value; return true; }if ("colorDensity" === propertyName) { this.params.colorDensity = true; if (value != null) this.params.pointSize = (value).floatValue (); return false; }if ("fullPlane" === propertyName) { this.params.contourFromZero = !(value).booleanValue (); return true; }if ("mapLattice" === propertyName) { this.params.mapLattice = value; return true; }if ("extendGrid" === propertyName) { this.params.extendGrid = (value).floatValue (); return true; }if ("property" === propertyName) { this.params.dataType = 1206; this.params.theProperty = value; this.mapSurface (); return true; }if ("sphere" === propertyName) { this.params.setSphere ((value).floatValue (), false); this.readerData = Float.$valueOf (this.params.distance); this.surfaceReader = this.newReader ("IsoShapeReader"); this.generateSurface (); return true; }if ("geodesic" === propertyName) { this.params.setSphere ((value).floatValue (), true); this.readerData = Float.$valueOf (this.params.distance); this.surfaceReader = this.newReader ("IsoShapeReader"); this.generateSurface (); return true; }if ("ellipsoid" === propertyName) { if (Clazz.instanceOf (value, JU.P4)) this.params.setEllipsoidP4 (value); else if (JU.AU.isAF (value)) this.params.setEllipsoidAF (value); else return true; this.readerData = Float.$valueOf (this.params.distance); this.surfaceReader = this.newReader ("IsoShapeReader"); this.generateSurface (); return true; }if ("ellipsoid3" === propertyName) { this.params.setEllipsoidAF (value); this.readerData = Float.$valueOf (this.params.distance); this.surfaceReader = this.newReader ("IsoShapeReader"); this.generateSurface (); return true; }if ("lp" === propertyName) { this.params.setLp (value); this.readerData = Clazz.newFloatArray (-1, [3, 2, 0, 15, 0]); this.surfaceReader = this.newReader ("IsoShapeReader"); this.generateSurface (); return true; }if ("rad" === propertyName) { this.params.setRadical (value); this.readerData = Clazz.newFloatArray (-1, [3, 2, 0, 15, 0]); this.surfaceReader = this.newReader ("IsoShapeReader"); this.generateSurface (); return true; }if ("lobe" === propertyName) { this.params.setLobe (value); this.readerData = Clazz.newFloatArray (-1, [3, 2, 0, 15, 0]); this.surfaceReader = this.newReader ("IsoShapeReader"); this.generateSurface (); return true; }if ("hydrogenOrbital" === propertyName) { if (!this.params.setAtomicOrbital (value)) { this.isValid = false; return true; }this.readerData = Clazz.newFloatArray (-1, [this.params.psi_n, this.params.psi_l, this.params.psi_m, this.params.psi_Znuc, this.params.psi_monteCarloCount]); this.surfaceReader = this.newReader ("IsoShapeReader"); this.processState (); return true; }if ("functionXY" === propertyName) { this.params.setFunctionXY (value); if (this.params.isContoured) this.volumeDataTemp.setPlaneParameters (this.params.thePlane == null ? this.params.thePlane = JU.P4.new4 (0, 0, 1, 0) : this.params.thePlane); if ((this.params.functionInfo.get (0)).indexOf ("_xyz") >= 0) this.getFunctionZfromXY (); this.processState (); return true; }if ("functionXYZ" === propertyName) { this.params.setFunctionXYZ (value); this.processState (); return true; }if ("lcaoType" === propertyName) { this.params.setLcao (value, this.colorPtr); return true; }if ("lcaoCartoonCenter" === propertyName) { if (++this.params.state != 2) return true; if (Float.isNaN (this.params.center.x)) this.params.center.setT (value); return false; }if ("molecular" === propertyName || "solvent" === propertyName || "sasurface" === propertyName || "nomap" === propertyName) { this.params.setSolvent (propertyName, (value).floatValue ()); if (!this.params.isSilent) JU.Logger.info (this.params.calculationType); this.processState (); return true; }if ("moData" === propertyName) { this.params.moData = value; return true; }if ("mepCalcType" === propertyName) { this.params.mep_calcType = (value).intValue (); return true; }if ("mep" === propertyName) { this.params.setMep (value, false); this.processState (); return true; }if ("mlp" === propertyName) { this.params.setMep (value, true); this.processState (); return true; }if ("nci" === propertyName) { var isPromolecular = (value).booleanValue (); this.params.setNci (isPromolecular); if (isPromolecular) this.processState (); return true; }if ("calculationType" === propertyName) { this.params.calculationType = value; return true; }if ("charges" === propertyName) { this.params.theProperty = value; return true; }if ("randomSeed" === propertyName) { this.params.randomSeed = (value).intValue (); return true; }if ("molecularOrbital" === propertyName) { var iMo = 0; var linearCombination = null; if (Clazz.instanceOf (value, Integer)) { iMo = (value).intValue (); } else { linearCombination = value; }this.params.setMO (iMo, linearCombination); JU.Logger.info (this.params.calculationType); this.processState (); return true; }if ("fileType" === propertyName) { this.fileType = value; return true; }if ("fileName" === propertyName) { this.params.fileName = value; return true; }if ("outputChannel" === propertyName) { this.out = value; return true; }if ("readFile" === propertyName) { if ((this.surfaceReader = this.setFileData (this.atomDataServer, value)) == null) { JU.Logger.error ("Could not set the surface data"); return true; }this.surfaceReader.setOutputChannel (this.out); this.generateSurface (); return true; }if ("mapColor" === propertyName) { if ((this.surfaceReader = this.setFileData (this.atomDataServer, value)) == null) { JU.Logger.error ("Could not set the mapping data"); return true; }this.surfaceReader.setOutputChannel (this.out); this.mapSurface (); return true; }if ("getSurfaceSets" === propertyName) { this.getSurfaceSets (); return true; }if ("periodic" === propertyName) { this.params.isPeriodic = true; }return false; }, "~S,~O,JU.BS"); Clazz.defineMethod (c$, "newReader", function (name) { var sr = J.jvxl.readers.SurfaceGenerator.getInterface (name); if (sr != null) sr.init (this); return sr; }, "~S"); Clazz.defineMethod (c$, "newReaderBr", function (name, br) { var sr = J.jvxl.readers.SurfaceGenerator.getInterface (name); if (sr != null) sr.init2 (this, br); return sr; }, "~S,java.io.BufferedReader"); c$.getInterface = Clazz.defineMethod (c$, "getInterface", function (name) { try { var x = Clazz._4Name ("J.jvxl.readers." + name); return (x == null ? null : x.newInstance ()); } catch (e) { if (Clazz.exceptionOf (e, Exception)) { JU.Logger.error ("Interface.java Error creating instance for " + name + ": \n" + e.toString ()); return null; } else { throw e; } } }, "~S"); Clazz.defineMethod (c$, "getSurfaceSets", function () { if (this.meshDataServer == null) { this.meshData.getSurfaceSet (); } else { this.meshDataServer.fillMeshData (this.meshData, 1, null); this.meshData.getSurfaceSet (); this.meshDataServer.fillMeshData (this.meshData, 3, null); }}); Clazz.defineMethod (c$, "processState", function () { if (this.params.state == 1 && this.params.thePlane != null) this.params.state++; if (this.params.state >= 2) { this.mapSurface (); } else { this.generateSurface (); }}); Clazz.defineMethod (c$, "setReader", function () { this.readerData = null; if (this.surfaceReader != null) return !this.surfaceReader.vertexDataOnly; switch (this.params.dataType) { case 1205: this.surfaceReader = this.newReader ("IsoPlaneReader"); break; case 1206: this.surfaceReader = this.newReader ("AtomPropertyMapper"); break; case 1328: case 1329: this.readerData = (this.params.dataType == 1328 ? "Mep" : "Mlp"); if (this.params.state == 3) { this.surfaceReader = this.newReader ("AtomPropertyMapper"); } else { this.surfaceReader = this.newReader ("Iso" + this.readerData + "Reader"); }break; case 1333: this.surfaceReader = this.newReader ("IsoIntersectReader"); break; case 1195: case 1203: case 1196: this.surfaceReader = this.newReader ("IsoSolventReader"); break; case 1844: case 1837: this.surfaceReader = this.newReader ("IsoMOReader"); break; case 8: this.surfaceReader = this.newReader ("IsoFxyReader"); break; case 9: this.surfaceReader = this.newReader ("IsoFxyzReader"); break; } if (JU.Logger.debugging) JU.Logger.info ("Using surface reader " + this.surfaceReader); if (this.params.isSilent && this.surfaceReader != null) this.surfaceReader.isQuiet = true; return true; }); Clazz.defineMethod (c$, "generateSurface", function () { if (++this.params.state != 2) return; this.setReader (); var haveMeshDataServer = (this.meshDataServer != null); if (this.params.colorBySign) this.params.isBicolorMap = true; if (this.surfaceReader == null) { JU.Logger.error ("surfaceReader is null for " + this.params.dataType); return; }if (!this.surfaceReader.createIsosurface (false)) { JU.Logger.error ("Could not create isosurface"); this.params.cutoff = NaN; this.surfaceReader.closeReader (); return; }if (this.params.pocket != null && haveMeshDataServer) this.surfaceReader.selectPocket (!this.params.pocket.booleanValue ()); if (this.params.minSet > 0) this.surfaceReader.excludeMinimumSet (); if (this.params.maxSet > 0) this.surfaceReader.excludeMaximumSet (); if (this.params.slabInfo != null) this.surfaceReader.slabIsosurface (this.params.slabInfo); if (haveMeshDataServer && this.meshDataServer.notifySurfaceGenerationCompleted ()) this.surfaceReader.hasColorData = false; if (this.jvxlData.thisSet >= 0) this.getSurfaceSets (); if (this.jvxlData.jvxlDataIs2dContour) { this.surfaceReader.colorIsosurface (); this.params.state = 3; }if (this.jvxlData.jvxlDataIsColorDensity) { this.params.state = 3; }if (this.params.colorBySign || this.params.isBicolorMap) { this.params.state = 3; this.surfaceReader.applyColorScale (); }if (this.jvxlData.vertexColorMap != null) { this.jvxlData.vertexColorMap = null; this.surfaceReader.hasColorData = false; }this.surfaceReader.jvxlUpdateInfo (); this.marchingSquares = this.surfaceReader.marchingSquares; this.surfaceReader.discardTempData (false); this.params.mappedDataMin = 3.4028235E38; this.surfaceReader.closeReader (); if (this.params.state != 3 && (this.surfaceReader.hasColorData || this.params.colorDensity)) { this.params.state = 3; this.colorIsosurface (); }this.surfaceReader = null; }); Clazz.defineMethod (c$, "mapSurface", function () { if (this.params.state == 1 && this.params.thePlane != null) this.params.state++; if (++this.params.state < 3) return; if (!this.setReader ()) return; if (this.params.isPeriodic) this.surfaceReader.volumeData.isPeriodic = true; if (this.params.thePlane != null) { var isSquared = this.params.isSquared; this.params.isSquared = false; this.params.cutoff = 0; this.surfaceReader.volumeData.setMappingPlane (this.params.thePlane); this.surfaceReader.createIsosurface (!this.params.isPeriodic); this.surfaceReader.volumeData.setMappingPlane (null); if (this.meshDataServer != null) this.meshDataServer.notifySurfaceGenerationCompleted (); if (this.params.dataType == 1205) { this.surfaceReader.discardTempData (true); return; }this.params.isSquared = isSquared; this.params.mappedDataMin = 3.4028235E38; this.surfaceReader.readVolumeData (true); if (this.params.mapLattice != null) this.surfaceReader.volumeData.isPeriodic = true; } else if (!this.params.colorBySets && !this.params.colorDensity) { this.surfaceReader.readAndSetVolumeParameters (true); this.params.mappedDataMin = 3.4028235E38; this.surfaceReader.readVolumeData (true); }this.colorIsosurface (); this.surfaceReader.closeReader (); this.surfaceReader = null; }); Clazz.defineMethod (c$, "colorIsosurface", function () { this.surfaceReader.colorIsosurface (); this.surfaceReader.jvxlUpdateInfo (); this.surfaceReader.updateTriangles (); this.surfaceReader.discardTempData (true); if (this.meshDataServer != null) this.meshDataServer.notifySurfaceMappingCompleted (); }); Clazz.defineMethod (c$, "setFileData", function (vwr, value) { var fileType = this.fileType; this.fileType = null; if (Clazz.instanceOf (value, java.util.Map)) { var map = value; if (map.containsKey ("__pymolSurfaceData__")) { this.readerData = map; return this.newReaderBr ("PyMOLMeshReader", null); }value = map.get ("volumeData"); }if (Clazz.instanceOf (value, J.jvxl.data.VolumeData)) { this.volumeDataTemp = value; return this.newReader ("VolumeDataReader"); }var data = null; if (Clazz.instanceOf (value, String)) { data = value; value = JU.Rdr.getBR (value); }var br = value; if (fileType == null) fileType = JV.FileManager.determineSurfaceFileType (br); if (fileType != null && fileType.startsWith ("UPPSALA")) { var fname = this.params.fileName; fname = fname.substring (0, fname.indexOf ("/", 10)); fname += JU.PT.getQuotedStringAt (fileType, fileType.indexOf ("A HREF") + 1); this.params.fileName = fname; value = this.atomDataServer.getBufferedInputStream (fname); if (value == null) { JU.Logger.error ("Isosurface: could not open file " + fname); return null; }try { br = JU.Rdr.getBufferedReader (value, null); } catch (e) { if (Clazz.exceptionOf (e, Exception)) { } else { throw e; } } fileType = JV.FileManager.determineSurfaceFileType (br); }if (fileType == null) fileType = "UNKNOWN"; JU.Logger.info ("data file type was determined to be " + fileType); if (fileType.equals ("Jvxl+")) return this.newReaderBr ("JvxlReader", br); this.readerData = Clazz.newArray (-1, [this.params.fileName, data]); if ("MRC DELPHI DSN6".indexOf (fileType.toUpperCase ()) >= 0) { fileType += "Binary"; }return this.newReaderBr (fileType + "Reader", br); }, "JV.Viewer,~O"); Clazz.defineMethod (c$, "getReaderData", function () { var o = this.readerData; this.readerData = null; return o; }); Clazz.defineMethod (c$, "initializeIsosurface", function () { this.params.initialize (); this.colorPtr = 0; this.surfaceReader = null; this.marchingSquares = null; this.initState (); }); Clazz.defineMethod (c$, "initState", function () { this.params.state = 1; this.params.dataType = this.params.surfaceType = 0; }); Clazz.defineMethod (c$, "setLcao", function () { this.params.colorPos = this.params.colorPosLCAO; this.params.colorNeg = this.params.colorNegLCAO; return this.params.lcaoType; }); Clazz.defineMethod (c$, "getFunctionZfromXY", function () { var origin = this.params.functionInfo.get (1); var counts = Clazz.newIntArray (3, 0); var nearest = Clazz.newIntArray (3, 0); var vectors = new Array (3); for (var i = 0; i < 3; i++) { var info = this.params.functionInfo.get (i + 2); counts[i] = Math.abs (Clazz.floatToInt (info.x)); vectors[i] = JU.V3.new3 (info.y, info.z, info.w); } var nx = counts[0]; var ny = counts[1]; var pt = new JU.P3 (); var pta = new JU.P3 (); var ptb = new JU.P3 (); var ptc = new JU.P3 (); var data = this.params.functionInfo.get (5); var data2 = Clazz.newFloatArray (nx, ny, 0); var d; for (var i = 0; i < nx; i++) for (var j = 0; j < ny; j++) { pt.scaleAdd2 (i, vectors[0], origin); pt.scaleAdd2 (j, vectors[1], pt); var dist = J.jvxl.readers.SurfaceGenerator.findNearestThreePoints (pt.x, pt.y, data, nearest); pta.set ((d = data[nearest[0]])[0], d[1], d[2]); if (dist < 0.00001) { pt.z = d[2]; } else { ptb.set ((d = data[nearest[1]])[0], d[1], d[2]); ptc.set ((d = data[nearest[2]])[0], d[1], d[2]); pt.z = this.distanceVerticalToPlane (pt.x, pt.y, pta, ptb, ptc); }data2[i][j] = pt.z; } this.params.functionInfo.set (5, data2); }); Clazz.defineMethod (c$, "distanceVerticalToPlane", function (x, y, pta, ptb, ptc) { var d = JU.Measure.getDirectedNormalThroughPoints (pta, ptb, ptc, this.ptRef, this.vNorm, this.vAB); return (this.vNorm.x * x + this.vNorm.y * y + d) / -this.vNorm.z; }, "~N,~N,JU.P3,JU.P3,JU.P3"); c$.findNearestThreePoints = Clazz.defineMethod (c$, "findNearestThreePoints", function (x, y, xyz, result) { var d; var dist1; var dist2; var dist3; var i1; var i2; var i3; i1 = i2 = i3 = -1; dist1 = dist2 = dist3 = 3.4028235E38; for (var i = xyz.length; --i >= 0; ) { d = (d = xyz[i][0] - x) * d + (d = xyz[i][1] - y) * d; if (d < dist1) { dist3 = dist2; dist2 = dist1; dist1 = d; i3 = i2; i2 = i1; i1 = i; } else if (d < dist2) { dist3 = dist2; dist2 = d; i3 = i2; i2 = i; } else if (d < dist3) { dist3 = d; i3 = i; }} result[0] = i1; result[1] = i2; result[2] = i3; return dist1; }, "~N,~N,~A,~A"); Clazz.defineMethod (c$, "addRequiredFile", function (fileName) { if (this.meshDataServer == null) return; this.meshDataServer.addRequiredFile (fileName); }, "~S"); Clazz.defineMethod (c$, "setRequiredFile", function (oldName, fileName) { if (this.meshDataServer == null) return; this.meshDataServer.setRequiredFile (oldName, fileName); }, "~S,~S"); Clazz.defineMethod (c$, "log", function (msg) { if (this.atomDataServer == null) System.out.println (msg); else this.atomDataServer.log (msg); }, "~S"); Clazz.defineMethod (c$, "setOutputChannel", function (binaryDoc, out) { if (this.meshDataServer == null) return; this.meshDataServer.setOutputChannel (binaryDoc, out); }, "javajs.api.GenericBinaryDocument,JU.OC"); Clazz.defineMethod (c$, "fillAtomData", function (atomData, mode) { if ((mode & 2) != 0 && atomData.bsSelected != null) { if (this.bsVdw == null) this.bsVdw = new JU.BS (); this.bsVdw.or (atomData.bsSelected); }this.atomDataServer.fillAtomData (atomData, mode); }, "J.atomdata.AtomData,~N"); Clazz.defineMethod (c$, "getOriginVaVbVc", function () { return (this.surfaceReader.volumeData == null ? null : this.surfaceReader.volumeData.oabc); }); });
/* ----------------------------------------------------------------------------- This source file is part of OGRE (Object-oriented Graphics Rendering Engine) For the latest info, see http://www.ogre3d.org/ Copyright (c) 2000-2014 Torus Knot Software Ltd Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ----------------------------------------------------------------------------- */ #ifndef __D3D11GpuProgramManager_H__ #define __D3D11GpuProgramManager_H__ #include "OgreD3D11Prerequisites.h" #include "OgreGpuProgramManager.h" namespace Ogre { class D3D11GpuProgramManager : public GpuProgramManager { protected: D3D11Device & mDevice; /// @copydoc ResourceManager::createImpl Resource* createImpl(const String& name, ResourceHandle handle, const String& group, bool isManual, ManualResourceLoader* loader, const NameValuePairList* createParams); /// Specialised create method with specific parameters Resource* createImpl(const String& name, ResourceHandle handle, const String& group, bool isManual, ManualResourceLoader* loader, GpuProgramType gptype, const String& syntaxCode); public: D3D11GpuProgramManager(D3D11Device & device); ~D3D11GpuProgramManager(); }; } #endif
import React, { useMemo, useLayoutEffect } from 'react' import { observer } from 'startupjs' import parsePropTypes from 'parse-prop-types' import { Text, Platform } from 'react-native' import Table from './Table' import Tbody from './Tbody' import Thead from './Thead' import Tr from './Tr' import Td from './Td' import { Span, themed, Input } from '@startupjs/ui' import './index.styl' export default observer(themed(function Constructor ({ Component, $props, style, theme }) { const entries = useMemo(() => { return parseEntries(Object.entries(parsePropTypes(Component))) }, [Component]) useLayoutEffect(() => { for (const prop of entries) { if (prop.defaultValue) { // FIXME: All logic is broken when default value is function // this is due to a racer patch $props.set(prop.name, prop.defaultValue) } } }, entries) return pug` Table.table(style=style) Thead.thead Tr Td: Text.header(styleName=[theme]) PROP Td: Text.header(styleName=[theme]) TYPE Td: Text.header(styleName=[theme]) DEFAULT Td: Text.header.right(styleName=[theme]) VALUE Tbody each entry, index in entries - const { name, type, defaultValue, possibleValues, possibleTypes } = entry Tr(key=index) Td: Span.name( style={ fontFamily: Platform.OS === 'ios' ? 'Menlo-Regular' : 'monospace' } )= name Td if type === 'oneOf' Span.possibleValue - let first = true each value, index in possibleValues React.Fragment(key=index) if !first Span.separator #{' | '} Span.value(styleName=[theme])= JSON.stringify(value) - first = false else if type === 'oneOfType' Span.possibleType - let first = true each value, index in possibleTypes React.Fragment(key=index) if !first Span.separator #{' | '} Span.type(styleName=[theme])= value && value.name - first = false else Span.type(styleName=[theme])= type Td: Span.value(styleName=[theme])= JSON.stringify(defaultValue) Td.vCenter if type === 'string' Input( type='text' size='s' value=$props.get(name) || '' onChangeText=value => $props.set(name, value) ) else if type === 'number' - const aValue = parseFloat($props.get(name)) Input( type='text' size='s' value='' + (isNaN(aValue) ? '' : aValue) onChangeText=value => { value = parseFloat(value) if (isNaN(value)) value = undefined $props.set(name, value) } ) else if type === 'node' Input( type='text' size='s' value=$props.get(name) || '' onChangeText=value => $props.set(name, value) ) else if type === 'oneOf' Input( type='select' size='s' value=$props.get(name) onChange=value => $props.set(name, value) options=possibleValues ) else if type === 'bool' Input.checkbox( type='checkbox' value=$props.get(name) onChange=value => $props.set(name, value) ) else Span.unsupported - ` })) function parseEntries (entries) { return entries.map(entry => { let meta = entry[1] return { name: entry[0], type: meta.type.name, defaultValue: meta.defaultValue && meta.defaultValue.value, possibleValues: meta.type.value, possibleTypes: meta.type.value } }) }
from rb.processings.gec.gec_correct import GecCorrector if __name__ == "__main__": corrector = GecCorrector(d_model=768) decoded_senntence = corrector.correct_sentence('Am meers l-a magaazin sa cuumper s leegume si fructe de mancaat.') print(decoded_senntence)
# Mat07.py import matplotlib.pyplot as plt import numpy as np a = np.random.normal(loc=0,scale=1,size=1000) b = np.random.normal(loc=5,scale=0.5,size=1000) c = np.random.normal(loc=10,scale=2,size=1000) plt.figure(figsize=(10,6)) plt.plot(a,label='a') plt.plot(b,label='b') plt.plot(c,label='c') plt.legend() plt.show()
#!/usr/bin/env python """ package_container functions for building the initial docker container templates for docker-image command """ import sys import os import json import pystache from cirrus.logger import get_logger from cirrus.templates import find_template from cirrus.utils import working_dir from cirrus.configuration import load_configuration from cirrus.git_tools import ( commit_files_optional_push, checkout_and_pull, has_unstaged_changes ) LOGGER = get_logger() def make_executable(path, repo): mode = os.stat(path).st_mode mode |= (mode & 0o444) >> 2 # copy R bits to X os.chmod(path, mode) def write_basic_dockerfile(opts, config, path): """ write the basic dockerfile for the example/template """ LOGGER.info("writing Dockerfile {}".format(path)) template = find_template("Dockerfile.mustache") context = { 'open_brace': '{{', 'close_brace': '}}', 'package': config.package_name(), 'container': opts.container, 'entrypoint': opts.entrypoint, 'maintainer': config.author_email() } renderer = pystache.Renderer() result = renderer.render_path(template, context) with open(path, 'w') as handle: handle.write(result) def write_json_file(path, data): """write json data to a file""" LOGGER.info("writing JSON {}".format(path)) with open(path, 'w') as handle: json.dump(data, handle) def write_script(repo, path, content, **extras): """write script content to a file""" LOGGER.info("writing script {}".format(path)) script = content.format(**extras) with open(path, 'w') as handle: handle.write(script) # run chmod +x on new script make_executable(path, repo) def edit_cirrus_conf(opts, config): """ add docker settings to cirrus conf """ LOGGER.info("updating cirrus.conf docker section...") config.add_docker_settings( opts.template_dir, opts.context_file, opts.image_dir, opts.docker_registry ) def init_container(opts): """ Initialise a basic container-template setup for this package """ cirrus_conf = os.path.join(opts.repo, 'cirrus.conf') if not os.path.exists(cirrus_conf): msg = "No cirrus.conf found, need to init repo first?" LOGGER.error(msg) sys.exit(1) config = load_configuration(opts.repo) template_dir = os.path.join(opts.repo, opts.template_dir) if not os.path.exists(template_dir): LOGGER.info("Creating Template in {}".format(template_dir)) os.makedirs(template_dir) docker_file = os.path.join(template_dir, 'Dockerfile.mustache') dotfile = os.path.join(template_dir, '.dockerstache') pre_script = os.path.join(template_dir, 'pre_script.sh') post_script = os.path.join(template_dir, 'post_script.sh') context = os.path.join(template_dir, 'context.json') installer_script = os.path.join(template_dir, 'install_script.sh.mustache') opts.context_file = os.path.join(opts.template_dir, 'context.json') # make sure repo is clean if has_unstaged_changes(opts.repo): msg = ( "Error: Unstaged changes are present on the branch " "Please commit them or clean up before proceeding" ) LOGGER.error(msg) raise RuntimeError(msg) main_branch = config.gitflow_branch_name() LOGGER.info("checking out latest {} branch...".format(main_branch)) checkout_and_pull(opts.repo, main_branch, not opts.no_remote) venv_option = "" if opts.virtualenv: venv_option = ". {}/bin/activate".format(opts.virtualenv) with working_dir(template_dir): write_basic_dockerfile(opts, config, docker_file) write_json_file(dotfile, { "post_script": "post_script.sh", "pre_script": "pre_script.sh", "inclusive": True, "excludes": ["post_script.sh", "post_script.sh", ".dockerstache"] }) write_json_file(context, {}) # render templates for container scripts template_context = { 'open_brace': '{{', 'close_brace': '}}', 'package': config.package_name(), 'virtualenv': venv_option, 'pip_options': config.pip_options() if config.pip_options() else "" } install_template = find_template('install_script.sh.mustache') pre_template = find_template('pre_script.sh.mustache') post_template = find_template('post_script.sh.mustache') renderer = pystache.Renderer() install_result = renderer.render_path(install_template, template_context) with open(installer_script, 'w') as handle: handle.write(install_result) post_result = renderer.render_path(post_template, template_context) with open(post_script, 'w') as handle: handle.write(post_result) pre_result = renderer.render_path(pre_template, template_context) with open(pre_script, 'w') as handle: handle.write(pre_result) make_executable(pre_script, opts.repo) make_executable(post_script, opts.repo) make_executable(installer_script, opts.repo) edit_cirrus_conf(opts, config) modified = [ cirrus_conf, docker_file, dotfile, pre_script, post_script, installer_script, context ] LOGGER.info("commiting changes...") commit_files_optional_push( opts.repo, "git cirrus package container-init", not opts.no_remote, *modified )
import "../wpt-env.js"; /* Delete created databases * * Go through each finished test, see if it has an associated database. Close * that and delete the database. */ add_completion_callback(function (tests) { for (var i in tests) { if (tests[i].db) { tests[i].db.close(); self.indexedDB.deleteDatabase(tests[i].db.name); } } }); function fail(test, desc) { return test.step_func(function (e) { if (e && e.message && e.target.error) assert_unreached( desc + " (" + e.target.error.name + ": " + e.message + ")", ); else if (e && e.message) assert_unreached(desc + " (" + e.message + ")"); else if (e && e.target.readyState === "done" && e.target.error) assert_unreached(desc + " (" + e.target.error.name + ")"); else assert_unreached(desc); }); } function createdb(test, dbname, version) { var rq_open = createdb_for_multiple_tests(dbname, version); return rq_open.setTest(test); } function createdb_for_multiple_tests(dbname, version) { var rq_open, fake_open = {}, test = null, dbname = dbname ? dbname : "testdb-" + new Date().getTime() + Math.random(); if (version) rq_open = self.indexedDB.open(dbname, version); else rq_open = self.indexedDB.open(dbname); function auto_fail(evt, current_test) { /* Fail handlers, if we haven't set on/whatever/, don't * expect to get event whatever. */ rq_open.manually_handled = {}; rq_open.addEventListener(evt, function (e) { if (current_test !== test) { return; } test.step(function () { if (!rq_open.manually_handled[evt]) { assert_unreached("unexpected open." + evt + " event"); } if ( e.target.result + "" == "[object IDBDatabase]" && !this.db ) { this.db = e.target.result; this.db.onerror = fail(test, "unexpected db.error"); this.db.onabort = fail(test, "unexpected db.abort"); this.db.onversionchange = fail( test, "unexpected db.versionchange", ); } }); }); rq_open.__defineSetter__("on" + evt, function (h) { rq_open.manually_handled[evt] = true; if (!h) rq_open.addEventListener(evt, function () {}); else rq_open.addEventListener(evt, test.step_func(h)); }); } // add a .setTest method to the IDBOpenDBRequest object Object.defineProperty(rq_open, "setTest", { enumerable: false, value: function (t) { test = t; auto_fail("upgradeneeded", test); auto_fail("success", test); auto_fail("blocked", test); auto_fail("error", test); return this; }, }); return rq_open; } function assert_key_equals(actual, expected, description) { assert_equals(indexedDB.cmp(actual, expected), 0, description); } function indexeddb_test(upgrade_func, open_func, description, options) { async_test(function (t) { options = Object.assign({ upgrade_will_abort: false }, options); var dbname = location + "-" + t.name; var del = indexedDB.deleteDatabase(dbname); del.onerror = t.unreached_func("deleteDatabase should succeed"); var open = indexedDB.open(dbname, 1); open.onupgradeneeded = t.step_func(function () { var db = open.result; t.add_cleanup(function () { // If open didn't succeed already, ignore the error. open.onerror = function (e) { e.preventDefault(); }; db.close(); indexedDB.deleteDatabase(db.name); }); var tx = open.transaction; upgrade_func(t, db, tx, open); }); if (options.upgrade_will_abort) { open.onsuccess = t.unreached_func("open should not succeed"); } else { open.onerror = t.unreached_func("open should succeed"); open.onsuccess = t.step_func(function () { var db = open.result; if (open_func) open_func(t, db, open); }); } }, description); } // Call with a Test and an array of expected results in order. Returns // a function; call the function when a result arrives and when the // expected number appear the order will be asserted and test // completed. function expect(t, expected) { var results = []; return (result) => { results.push(result); if (results.length === expected.length) { assert_array_equals(results, expected); t.done(); } }; } // Checks to see if the passed transaction is active (by making // requests against the named store). function is_transaction_active(tx, store_name) { try { const request = tx.objectStore(store_name).get(0); request.onerror = (e) => { e.preventDefault(); e.stopPropagation(); }; return true; } catch (ex) { assert_equals( ex.name, "TransactionInactiveError", "Active check should either not throw anything, or throw " + "TransactionInactiveError", ); return false; } } // Keeps the passed transaction alive indefinitely (by making requests // against the named store). Returns a function that asserts that the // transaction has not already completed and then ends the request loop so that // the transaction may autocommit and complete. function keep_alive(tx, store_name) { let completed = false; tx.addEventListener("complete", () => { completed = true; }); let keepSpinning = true; function spin() { if (!keepSpinning) return; tx.objectStore(store_name).get(0).onsuccess = spin; } spin(); return () => { assert_false(completed, "Transaction completed while kept alive"); keepSpinning = false; }; } var db, t = async_test(); var open_rq = createdb(t); open_rq.onupgradeneeded = function (event) { db = event.target.result; db.createObjectStore("store", { keyPath: "pKey" }); }; open_rq.onsuccess = function (event) { var txn = db.transaction("store"); var ostore = txn.objectStore("store"); t.step(function () { assert_throws("ReadOnlyError", function () { ostore.add({ pKey: "primaryKey_0" }); }); }); t.done(); };
/** * @param {number[][]} buildings * @return {number[][]} */ var getSkyline = function (buildings) { let xSet = new Set(); for (const [l, r] of buildings) { xSet.add(l); xSet.add(r); } let priorityQueue = Array.from(xSet).sort((a, b) => a - b); let results = []; for (const p of priorityQueue) { let height = 0; for (const [l, r, h] of buildings) { if (l > p) break; if (r > p) { height = Math.max(height, h); } } if (results.length !== 0 && results[results.length - 1][1] === height) continue; // 合并 results.push([p, height]); } return results; }; // TEST: console.log(getSkyline([ [2, 9, 10], [3, 7, 15], [5, 12, 12], [15, 20, 10], [19, 24, 8] ]))
!(function (t) { 'use strict'; 'function' == typeof define && define.amd ? define(['jquery'], t) : 'object' == typeof exports ? (module.exports = t(require('jquery'))) : t(jQuery); })(function (t) { 'use strict'; var n = 'animsition', i = { init: function (a) { (a = t.extend( { inClass: 'fade-in', outClass: 'fade-out', inDuration: 500, outDuration: 500, linkElement: '.animsition-link', loading: !0, loadingParentElement: 'body', loadingClass: 'animsition-loading', loadingInner: '', timeout: !1, timeoutCountdown: 5e3, onLoadEvent: !0, browser: [ 'animation-duration', '-webkit-animation-duration', ], overlay: !1, overlayClass: 'animsition-overlay-slide', overlayParentElement: 'body', transition: function (t) { window.location.href = t; }, }, a )), (i.settings = { timer: !1, data: { inClass: 'animsition-in-class', inDuration: 'animsition-in-duration', outClass: 'animsition-out-class', outDuration: 'animsition-out-duration', overlay: 'animsition-overlay', }, events: { inStart: 'animsition.inStart', inEnd: 'animsition.inEnd', outStart: 'animsition.outStart', outEnd: 'animsition.outEnd', }, }); var o = i.supportCheck.call(this, a); if (!o && a.browser.length > 0 && (!o || !this.length)) return ( 'console' in window || ((window.console = {}), (window.console.log = function (t) { return t; })), this.length || console.log( 'Animsition: Element does not exist on page.' ), o || console.log( 'Animsition: Does not support this browser.' ), i.destroy.call(this) ); var e = i.optionCheck.call(this, a); return ( e && t('.' + a.overlayClass).length <= 0 && i.addOverlay.call(this, a), a.loading && t('.' + a.loadingClass).length <= 0 && i.addLoading.call(this, a), this.each(function () { var o = this, e = t(this), s = t(window), r = t(document), l = e.data(n); l || ((a = t.extend({}, a)), e.data(n, { options: a }), a.timeout && i.addTimer.call(o), a.onLoadEvent && s.on('load.' + n, function () { i.settings.timer && clearTimeout(i.settings.timer), i['in'].call(o); }), s.on('pageshow.' + n, function (t) { t.originalEvent.persisted && i['in'].call(o); }), s.on('unload.' + n, function () {}), r.on('click.' + n, a.linkElement, function (n) { n.preventDefault(); var a = t(this), e = a.attr('href'); 2 === n.which || n.metaKey || n.shiftKey || (-1 !== navigator.platform .toUpperCase() .indexOf('WIN') && n.ctrlKey) ? window.open(e, '_blank') : i.out.call(o, a, e); })); }) ); }, addOverlay: function (n) { t(n.overlayParentElement).prepend( '<div class="' + n.overlayClass + '"></div>' ); }, addLoading: function (n) { t(n.loadingParentElement).append( '<div class="' + n.loadingClass + '">' + n.loadingInner + '</div>' ); }, removeLoading: function () { var i = t(this), a = i.data(n).options, o = t(a.loadingParentElement).children( '.' + a.loadingClass ); o.fadeOut().remove(); }, addTimer: function () { var a = this, o = t(this), e = o.data(n).options; i.settings.timer = setTimeout(function () { i['in'].call(a), t(window).off('load.' + n); }, e.timeoutCountdown); }, supportCheck: function (n) { var i = t(this), a = n.browser, o = a.length, e = !1; 0 === o && (e = !0); for (var s = 0; o > s; s++) if ('string' == typeof i.css(a[s])) { e = !0; break; } return e; }, optionCheck: function (n) { var a, o = t(this); return (a = n.overlay || o.data(i.settings.data.overlay) ? !0 : !1); }, animationCheck: function (i, a, o) { var e = t(this), s = e.data(n).options, r = typeof i, l = !a && 'number' === r, d = a && 'string' === r && i.length > 0; return ( l || d ? (i = i) : a && o ? (i = s.inClass) : !a && o ? (i = s.inDuration) : a && !o ? (i = s.outClass) : a || o || (i = s.outDuration), i ); }, in: function () { var a = this, o = t(this), e = o.data(n).options, s = o.data(i.settings.data.inDuration), r = o.data(i.settings.data.inClass), l = i.animationCheck.call(a, s, !1, !0), d = i.animationCheck.call(a, r, !0, !0), u = i.optionCheck.call(a, e), c = o.data(n).outClass; e.loading && i.removeLoading.call(a), c && o.removeClass(c), u ? i.inOverlay.call(a, d, l) : i.inDefault.call(a, d, l); }, inDefault: function (n, a) { var o = t(this); o.css({ 'animation-duration': a + 'ms' }) .addClass(n) .trigger(i.settings.events.inStart) .animateCallback(function () { o.removeClass(n) .css({ opacity: 1 }) .trigger(i.settings.events.inEnd); }); }, inOverlay: function (a, o) { var e = t(this), s = e.data(n).options; e.css({ opacity: 1 }).trigger(i.settings.events.inStart), t(s.overlayParentElement) .children('.' + s.overlayClass) .css({ 'animation-duration': o + 'ms' }) .addClass(a) .animateCallback(function () { e.trigger(i.settings.events.inEnd); }); }, out: function (a, o) { var e = this, s = t(this), r = s.data(n).options, l = a.data(i.settings.data.outClass), d = s.data(i.settings.data.outClass), u = a.data(i.settings.data.outDuration), c = s.data(i.settings.data.outDuration), m = l ? l : d, g = u ? u : c, f = i.animationCheck.call(e, m, !0, !1), v = i.animationCheck.call(e, g, !1, !1), h = i.optionCheck.call(e, r); (s.data(n).outClass = f), h ? i.outOverlay.call(e, f, v, o) : i.outDefault.call(e, f, v, o); }, outDefault: function (a, o, e) { var s = t(this), r = s.data(n).options; s.css({ 'animation-duration': o + 1 + 'ms' }) .addClass(a) .trigger(i.settings.events.outStart) .animateCallback(function () { s.trigger(i.settings.events.outEnd), r.transition(e); }); }, outOverlay: function (a, o, e) { var s = this, r = t(this), l = r.data(n).options, d = r.data(i.settings.data.inClass), u = i.animationCheck.call(s, d, !0, !0); t(l.overlayParentElement) .children('.' + l.overlayClass) .css({ 'animation-duration': o + 1 + 'ms' }) .removeClass(u) .addClass(a) .trigger(i.settings.events.outStart) .animateCallback(function () { r.trigger(i.settings.events.outEnd), l.transition(e); }); }, destroy: function () { return this.each(function () { var i = t(this); t(window).off('.' + n), i.css({ opacity: 1 }).removeData(n); }); }, }; (t.fn.animateCallback = function (n) { var i = 'animationend webkitAnimationEnd'; return this.each(function () { var a = t(this); a.on(i, function () { return a.off(i), n.call(this); }); }); }), (t.fn.animsition = function (a) { return i[a] ? i[a].apply(this, Array.prototype.slice.call(arguments, 1)) : 'object' != typeof a && a ? void t.error('Method ' + a + ' does not exist on jQuery.' + n) : i.init.apply(this, arguments); }); }); function opacityHeaderImage() { var header = $('.opacity-box'); var range = $('.header-content').height() / 4; var el_range = $(".section-gallery-slider").height() / 4; var pageheight = $(window).height(); $(window).on('scroll', function() { var scrollTop = $(this).scrollTop(), height = header.outerHeight(), offset = height / 2, calc = 1 - (scrollTop - offset + range) / range; header.css({ 'opacity': calc }); if (calc > '1') { header.css({ 'opacity': 1 }); } else if (calc < '0') { header.css({ 'opacity': 0 }); } if (scrollTop > pageheight) { $(".head-menu").addClass('big-gradient'); } else { $(".head-menu").removeClass('big-gradient'); } if (scrollTop > height + 5) { $(".scroll-single-gallery").addClass('scroll-single-gallery-hidden'); } else { $(".scroll-single-gallery").removeClass('scroll-single-gallery-hidden'); } }); } $('.range-modal-form-btn').click(function () { $('.tonirovka-form-modal').addClass('active-modal'); }); $('.close-modal').click(function () { $('.tonirovka-form-modal').removeClass('active-modal'); $('.wpcf7-mail-sent-ok').text(''); }); var controller = new ScrollMagic.Controller(); var pageheight = $(window).height(); $('.section-main-page-3').each(function () { var fadeOutTimeline = new TimelineMax(); var thisData = $(this).attr('data-block'); var fadeOutFrom = TweenMax.from('#background-id-' + thisData, 1, { autoAlpha: 0, }); var fadeOutTo = TweenMax.to('#background-id-' + thisData, 1, { autoAlpha: -1, }); fadeOutTimeline.add(fadeOutFrom).add(fadeOutTo); new ScrollMagic.Scene({ triggerElement: this, offset: 100, }) .setTween(fadeOutTimeline) .duration(pageheight * 1.3) .addTo(controller); }); $('.reveal_box').each(function () { new ScrollMagic.Scene({ triggerElement: '#section-id-1', offset: 100, }) .setTween(fadeOutTimeline1) .duration(pageheight * 1.3) .addTo(controller); }); opacityHeaderImage(); if ($(window).width() < 1100) { console.log($(window).width()); $('.main-page-video-background').remove(); } else { $('.parallax').paroller(); } $(document).ready(function () { $('.animsition').animsition({ inClass: 'fade-in', outClass: 'fade-out', inDuration: 200, outDuration: 200, linkElement: 'a', linkElement: 'a:not([target="_blank"]):not([href^="#"]):not([class="link-footer"]):not([class="link-gallery"]):not([class="swiper-slide activate-info-box-gallery swiper-slide-active"]):not([id="bingc-phone-button"]):not([id="bingc-passive-close-button"]):not([id="bingc-active-close-button"])', loading: true, loadingParentElement: 'body', //animsition wrapper element loadingClass: 'animsition-loading', loadingInner: '', // e.g '<img src="loading.svg" />' timeout: false, timeoutCountdown: 0, onLoadEvent: true, browser: ['animation-duration', '-webkit-animation-duration'], // "browser" option allows you to disable the "animsition" in case the css property in the array is not supported by your browser. // The default setting is to disable the "animsition" in a browser that does not support "animation-duration". overlay: false, overlayClass: 'animsition-overlay-slide', overlayParentElement: 'body', transition: function (url) { window.location.href = url; }, }); }); setTimeout(() => { $('.load-anim').addClass('disable'); $('body').addClass('animate-body'); }, 1500);
AR = 'arm-none-eabi-ar' ARFLAGS = 'rcs' AS = 'arm-none-eabi-gcc' BINDIR = '/usr/local/bin' BLOCK_MESSAGE_KEYS = [] BUILD_DIR = 'diorite' BUILD_TYPE = 'app' BUNDLE_BIN_DIR = 'diorite' BUNDLE_NAME = 'TimeStylePebble.pbw' CC = ['arm-none-eabi-gcc'] CCLNK_SRC_F = [] CCLNK_TGT_F = ['-o'] CC_NAME = 'gcc' CC_SRC_F = [] CC_TGT_F = ['-c', '-o'] CC_VERSION = ('4', '7', '2') CFLAGS = ['-std=c99', '-mcpu=cortex-m3', '-mthumb', '-ffunction-sections', '-fdata-sections', '-g', '-fPIE', '-Os', '-D_TIME_H_', '-Wall', '-Wextra', '-Werror', '-Wno-unused-parameter', '-Wno-error=unused-function', '-Wno-error=unused-variable'] CFLAGS_MACBUNDLE = ['-fPIC'] CFLAGS_cshlib = ['-fPIC'] CPPPATH_ST = '-I%s' DEFINES = ['RELEASE', 'PBL_PLATFORM_DIORITE', 'PBL_BW', 'PBL_RECT', 'PBL_MICROPHONE', 'PBL_HEALTH', 'PBL_SMARTSTRAP', 'PBL_DISPLAY_WIDTH=144', 'PBL_DISPLAY_HEIGHT=168', 'PBL_SDK_3'] DEFINES_ST = '-D%s' DEST_BINFMT = 'elf' DEST_CPU = 'arm' DEST_OS = 'darwin' INCLUDES = ['diorite'] LD = 'arm-none-eabi-ld' LIBDIR = '/usr/local/lib' LIBPATH_ST = '-L%s' LIB_DIR = 'node_modules' LIB_JSON = [{u'files': [u'dist.zip'], u'license': u'MIT', u'name': u'pebble-fctx', u'repository': {u'url': u'https://github.com/jrmobley/pebble-fctx.git', u'type': u'git'}, u'author': u'JR Mobley', u'version': u'1.6.2', u'dependencies': {u'pebble-utf8': u'^1.0.1'}, u'keywords': [u'pebble-package'], 'path': 'node_modules/pebble-fctx/dist', u'pebble': {u'sdkVersion': u'3', u'projectType': u'package', u'targetPlatforms': [u'aplite', u'basalt', u'chalk', u'diorite', u'emery'], u'resources': {u'media': []}}}, {u'files': [u'dist.zip'], u'license': u'MIT', u'name': u'pebble-utf8', u'repository': {u'url': u'https://github.com/jrmobley/pebble-utf8.git', u'type': u'git'}, u'author': u'JR Mobley', u'version': u'1.0.1', u'dependencies': {}, u'keywords': [u'pebble-package'], 'path': 'node_modules/pebble-utf8/dist', u'pebble': {u'sdkVersion': u'3', u'projectType': u'package', u'targetPlatforms': [u'aplite', u'basalt', u'chalk', u'diorite', u'emery'], u'resources': {u'media': []}}}] LIB_RESOURCES_JSON = {u'pebble-fctx': [], u'pebble-utf8': []} LIB_ST = '-l%s' LINKFLAGS = ['-mcpu=cortex-m3', '-mthumb', '-Wl,--gc-sections', '-Wl,--warn-common', '-fPIE', '-Os'] LINKFLAGS_MACBUNDLE = ['-bundle', '-undefined', 'dynamic_lookup'] LINKFLAGS_cshlib = ['-shared'] LINKFLAGS_cstlib = ['-Wl,-Bstatic'] LINK_CC = ['arm-none-eabi-gcc'] MESSAGE_KEYS = {u'WeatherTemperature': 10001, u'SettingBluetoothVibe': 10008, u'SettingAltClockName': 10005, u'SettingWidget2ID': 10029, u'SettingDisableWeather': 10015, u'SettingClockFontId': 10010, u'WeatherForecastLowTemp': 10004, u'SettingDisableAutobattery': 10007, u'SettingHealthUseDistance': 10016, u'SettingUseMetric': 10025, u'SettingLanguageID': 10019, u'WeatherUseNightIcon': 10026, u'SettingWidget1ID': 10028, u'SettingAltClockOffset': 10006, u'SettingColorTime': 10013, u'SettingWidget0ID': 10027, u'SettingSidebarOnLeft': 10022, u'WeatherCondition': 10000, u'SettingDecimalSep': 10014, u'SettingShowLeadingZero': 10021, u'WeatherForecastCondition': 10002, u'SettingSidebarTextColor': 10023, u'SettingColorBG': 10011, u'SettingUseLargeFonts': 10024, u'SettingHourlyVibe': 10018, u'SettingDisconnectIcon': 10009, u'SettingShowBatteryPct': 10020, u'SettingHealthUseRestfulSleep': 10017, u'SettingColorSidebar': 10012, u'WeatherForecastHighTemp': 10003} MESSAGE_KEYS_DEFINITION = '/Users/shawn/pebble-dev/pebble-sdk-4.5-mac/TimeStylePebble/build/src/message_keys.auto.c' MESSAGE_KEYS_HEADER = '/Users/shawn/pebble-dev/pebble-sdk-4.5-mac/TimeStylePebble/build/include/message_keys.auto.h' MESSAGE_KEYS_JSON = '/Users/shawn/pebble-dev/pebble-sdk-4.5-mac/TimeStylePebble/build/js/message_keys.json' NODE_PATH = '/Users/shawn/Library/Application Support/Pebble SDK/SDKs/current/node_modules' PEBBLE_SDK_COMMON = '/Users/shawn/Library/Application Support/Pebble SDK/SDKs/current/sdk-core/pebble/common' PEBBLE_SDK_PLATFORM = '/Users/shawn/Library/Application Support/Pebble SDK/SDKs/current/sdk-core/pebble/diorite' PEBBLE_SDK_ROOT = '/Users/shawn/Library/Application Support/Pebble SDK/SDKs/current/sdk-core/pebble' PLATFORM = {'TAGS': ['diorite', 'bw', 'rect', 'mic', 'strap', 'health', '144w', '168h'], 'MAX_FONT_GLYPH_SIZE': 256, 'ADDITIONAL_TEXT_LINES_FOR_PEBBLE_H': [], 'MAX_APP_BINARY_SIZE': 65536, 'MAX_RESOURCES_SIZE': 1048576, 'MAX_APP_MEMORY_SIZE': 65536, 'MAX_WORKER_MEMORY_SIZE': 10240, 'NAME': 'diorite', 'BUNDLE_BIN_DIR': 'diorite', 'BUILD_DIR': 'diorite', 'MAX_RESOURCES_SIZE_APPSTORE': 262144, 'DEFINES': ['PBL_PLATFORM_DIORITE', 'PBL_BW', 'PBL_RECT', 'PBL_MICROPHONE', 'PBL_HEALTH', 'PBL_SMARTSTRAP', 'PBL_DISPLAY_WIDTH=144', 'PBL_DISPLAY_HEIGHT=168']} PLATFORM_NAME = 'diorite' PREFIX = '/usr/local' PROJECT_INFO = {'appKeys': {u'WeatherTemperature': 10001, u'SettingBluetoothVibe': 10008, u'SettingAltClockName': 10005, u'SettingWidget2ID': 10029, u'SettingDisableWeather': 10015, u'SettingClockFontId': 10010, u'WeatherForecastLowTemp': 10004, u'SettingDisableAutobattery': 10007, u'SettingHealthUseDistance': 10016, u'SettingUseMetric': 10025, u'SettingLanguageID': 10019, u'WeatherUseNightIcon': 10026, u'SettingWidget1ID': 10028, u'SettingAltClockOffset': 10006, u'SettingColorTime': 10013, u'SettingWidget0ID': 10027, u'SettingSidebarOnLeft': 10022, u'WeatherCondition': 10000, u'SettingDecimalSep': 10014, u'SettingShowLeadingZero': 10021, u'WeatherForecastCondition': 10002, u'SettingSidebarTextColor': 10023, u'SettingColorBG': 10011, u'SettingUseLargeFonts': 10024, u'SettingHourlyVibe': 10018, u'SettingDisconnectIcon': 10009, u'SettingShowBatteryPct': 10020, u'SettingHealthUseRestfulSleep': 10017, u'SettingColorSidebar': 10012, u'WeatherForecastHighTemp': 10003}, u'sdkVersion': u'3', u'displayName': u'TimeStyle', u'uuid': u'4368ffa4-f0fb-4823-90be-f754b076bdaa', u'messageKeys': {u'WeatherTemperature': 10001, u'SettingBluetoothVibe': 10008, u'SettingAltClockName': 10005, u'SettingWidget2ID': 10029, u'SettingDisableWeather': 10015, u'SettingClockFontId': 10010, u'WeatherForecastLowTemp': 10004, u'SettingDisableAutobattery': 10007, u'SettingHealthUseDistance': 10016, u'SettingUseMetric': 10025, u'SettingLanguageID': 10019, u'WeatherUseNightIcon': 10026, u'SettingWidget1ID': 10028, u'SettingAltClockOffset': 10006, u'SettingColorTime': 10013, u'SettingWidget0ID': 10027, u'SettingSidebarOnLeft': 10022, u'WeatherCondition': 10000, u'SettingDecimalSep': 10014, u'SettingShowLeadingZero': 10021, u'WeatherForecastCondition': 10002, u'SettingSidebarTextColor': 10023, u'SettingColorBG': 10011, u'SettingUseLargeFonts': 10024, u'SettingHourlyVibe': 10018, u'SettingDisconnectIcon': 10009, u'SettingShowBatteryPct': 10020, u'SettingHealthUseRestfulSleep': 10017, u'SettingColorSidebar': 10012, u'WeatherForecastHighTemp': 10003}, 'companyName': u'Freakified', u'enableMultiJS': True, u'targetPlatforms': [u'basalt', u'chalk', u'diorite', u'emery'], u'capabilities': [u'location', u'health', u'configurable'], 'versionLabel': u'7.1', 'longName': u'TimeStyle', 'shortName': u'TimeStyle', u'watchapp': {u'onlyShownOnCommunication': False, u'hiddenApp': False, u'watchface': True}, u'resources': {u'media': [{u'menuIcon': True, u'type': u'bitmap', u'name': u'MENU_ICON', u'file': u'images/menuicon.png'}, {u'type': u'raw', u'name': u'LECO_REGULAR_FFONT', u'file': u'fonts/LECO1976-Regular.ffont'}, {u'type': u'raw', u'name': u'AVENIR_REGULAR_FFONT', u'file': u'fonts/AvenirNextRegular.ffont'}, {u'type': u'raw', u'name': u'AVENIR_BOLD_FFONT', u'file': u'fonts/AvenirNextDemiBold.ffont'}, {u'type': u'raw', u'name': u'WEATHER_GENERIC', u'file': u'data/WEATHER_GENERIC.pdc'}, {u'type': u'raw', u'name': u'WEATHER_THUNDERSTORM', u'file': u'data/THUNDERSTORM.pdc'}, {u'type': u'raw', u'name': u'WEATHER_RAINING_AND_SNOWING', u'file': u'data/RAINING_AND_SNOWING.pdc'}, {u'type': u'raw', u'name': u'WEATHER_PARTLY_CLOUDY_NIGHT', u'file': u'data/PARTLY_CLOUDY_NIGHT.pdc'}, {u'type': u'raw', u'name': u'WEATHER_PARTLY_CLOUDY', u'file': u'data/PARTLY_CLOUDY.pdc'}, {u'type': u'raw', u'name': u'WEATHER_LIGHT_SNOW', u'file': u'data/LIGHT_SNOW.pdc'}, {u'type': u'raw', u'name': u'WEATHER_LIGHT_RAIN', u'file': u'data/LIGHT_RAIN.pdc'}, {u'type': u'raw', u'name': u'WEATHER_HEAVY_SNOW', u'file': u'data/HEAVY_SNOW.pdc'}, {u'type': u'raw', u'name': u'WEATHER_HEAVY_RAIN', u'file': u'data/HEAVY_RAIN.pdc'}, {u'type': u'raw', u'name': u'DISCONNECTED', u'file': u'data/DISCONNECTED.pdc'}, {u'type': u'raw', u'name': u'DATE_BG', u'file': u'data/DATE_BG.pdc'}, {u'type': u'raw', u'name': u'WEATHER_CLOUDY', u'file': u'data/CLOUDY_DAY.pdc'}, {u'type': u'raw', u'name': u'WEATHER_CLEAR_NIGHT', u'file': u'data/CLEAR_NIGHT.pdc'}, {u'type': u'raw', u'name': u'WEATHER_CLEAR_DAY', u'file': u'data/CLEAR_DAY.pdc'}, {u'type': u'raw', u'name': u'BATTERY_CHARGE', u'file': u'data/BATTERY_CHARGE.pdc'}, {u'type': u'raw', u'name': u'BATTERY_BG', u'file': u'data/BATTERY_BG.pdc'}, {u'type': u'raw', u'name': u'HEALTH_SLEEP', u'file': u'data/HEALTH_SLEEP.pdc'}, {u'type': u'raw', u'name': u'HEALTH_STEPS', u'file': u'data/HEALTH_STEPS.pdc'}, {u'type': u'raw', u'name': u'HEALTH_HEART', u'file': u'data/HEALTH_HEART.pdc'}]}, 'name': u'timestyle-pebble'} REQUESTED_PLATFORMS = [u'basalt', u'chalk', u'diorite', u'emery'] RESOURCES_JSON = [{u'menuIcon': True, u'type': u'bitmap', u'name': u'MENU_ICON', u'file': u'images/menuicon.png'}, {u'type': u'raw', u'name': u'LECO_REGULAR_FFONT', u'file': u'fonts/LECO1976-Regular.ffont'}, {u'type': u'raw', u'name': u'AVENIR_REGULAR_FFONT', u'file': u'fonts/AvenirNextRegular.ffont'}, {u'type': u'raw', u'name': u'AVENIR_BOLD_FFONT', u'file': u'fonts/AvenirNextDemiBold.ffont'}, {u'type': u'raw', u'name': u'WEATHER_GENERIC', u'file': u'data/WEATHER_GENERIC.pdc'}, {u'type': u'raw', u'name': u'WEATHER_THUNDERSTORM', u'file': u'data/THUNDERSTORM.pdc'}, {u'type': u'raw', u'name': u'WEATHER_RAINING_AND_SNOWING', u'file': u'data/RAINING_AND_SNOWING.pdc'}, {u'type': u'raw', u'name': u'WEATHER_PARTLY_CLOUDY_NIGHT', u'file': u'data/PARTLY_CLOUDY_NIGHT.pdc'}, {u'type': u'raw', u'name': u'WEATHER_PARTLY_CLOUDY', u'file': u'data/PARTLY_CLOUDY.pdc'}, {u'type': u'raw', u'name': u'WEATHER_LIGHT_SNOW', u'file': u'data/LIGHT_SNOW.pdc'}, {u'type': u'raw', u'name': u'WEATHER_LIGHT_RAIN', u'file': u'data/LIGHT_RAIN.pdc'}, {u'type': u'raw', u'name': u'WEATHER_HEAVY_SNOW', u'file': u'data/HEAVY_SNOW.pdc'}, {u'type': u'raw', u'name': u'WEATHER_HEAVY_RAIN', u'file': u'data/HEAVY_RAIN.pdc'}, {u'type': u'raw', u'name': u'DISCONNECTED', u'file': u'data/DISCONNECTED.pdc'}, {u'type': u'raw', u'name': u'DATE_BG', u'file': u'data/DATE_BG.pdc'}, {u'type': u'raw', u'name': u'WEATHER_CLOUDY', u'file': u'data/CLOUDY_DAY.pdc'}, {u'type': u'raw', u'name': u'WEATHER_CLEAR_NIGHT', u'file': u'data/CLEAR_NIGHT.pdc'}, {u'type': u'raw', u'name': u'WEATHER_CLEAR_DAY', u'file': u'data/CLEAR_DAY.pdc'}, {u'type': u'raw', u'name': u'BATTERY_CHARGE', u'file': u'data/BATTERY_CHARGE.pdc'}, {u'type': u'raw', u'name': u'BATTERY_BG', u'file': u'data/BATTERY_BG.pdc'}, {u'type': u'raw', u'name': u'HEALTH_SLEEP', u'file': u'data/HEALTH_SLEEP.pdc'}, {u'type': u'raw', u'name': u'HEALTH_STEPS', u'file': u'data/HEALTH_STEPS.pdc'}, {u'type': u'raw', u'name': u'HEALTH_HEART', u'file': u'data/HEALTH_HEART.pdc'}] RPATH_ST = '-Wl,-rpath,%s' SANDBOX = False SDK_VERSION_MAJOR = 5 SDK_VERSION_MINOR = 86 SHLIB_MARKER = None SIZE = 'arm-none-eabi-size' SONAME_ST = '-Wl,-h,%s' STLIBPATH_ST = '-L%s' STLIB_MARKER = None STLIB_ST = '-l%s' SUPPORTED_PLATFORMS = ['basalt', 'aplite', 'diorite', 'chalk', 'emery'] TARGET_PLATFORMS = ['emery', 'diorite', 'chalk', 'basalt'] TIMESTAMP = 1608804524 USE_GROUPS = True VERBOSE = 0 WEBPACK = '/Users/shawn/Library/Application Support/Pebble SDK/SDKs/current/node_modules/.bin/webpack' cprogram_PATTERN = '%s' cshlib_PATTERN = 'lib%s.so' cstlib_PATTERN = 'lib%s.a' macbundle_PATTERN = '%s.bundle'
# Copyright The PyTorch Lightning team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import Optional import torch from torch import Tensor from torchmetrics.functional.classification.confusion_matrix import _confusion_matrix_compute, _confusion_matrix_update _cohen_kappa_update = _confusion_matrix_update def _cohen_kappa_compute(confmat: Tensor, weights: Optional[str] = None) -> Tensor: confmat = _confusion_matrix_compute(confmat) confmat = confmat.float() if not confmat.is_floating_point() else confmat n_classes = confmat.shape[0] sum0 = confmat.sum(dim=0, keepdim=True) sum1 = confmat.sum(dim=1, keepdim=True) expected = sum1 @ sum0 / sum0.sum() # outer product if weights is None: w_mat = torch.ones_like(confmat).flatten() w_mat[::n_classes + 1] = 0 w_mat = w_mat.reshape(n_classes, n_classes) elif weights == "linear" or weights == "quadratic": w_mat = torch.zeros_like(confmat) w_mat += torch.arange(n_classes, dtype=w_mat.dtype, device=w_mat.device) if weights == "linear": w_mat = torch.abs(w_mat - w_mat.T) else: w_mat = torch.pow(w_mat - w_mat.T, 2.0) else: raise ValueError( f"Received {weights} for argument ``weights`` but should be either" " None, 'linear' or 'quadratic'" ) k = torch.sum(w_mat * confmat) / torch.sum(w_mat * expected) return 1 - k def cohen_kappa( preds: Tensor, target: Tensor, num_classes: int, weights: Optional[str] = None, threshold: float = 0.5, ) -> Tensor: r""" Calculates `Cohen's kappa score <https://en.wikipedia.org/wiki/Cohen%27s_kappa>`_ that measures inter-annotator agreement. It is defined as .. math:: \kappa = (p_o - p_e) / (1 - p_e) where :math:`p_o` is the empirical probability of agreement and :math:`p_e` isg the expected agreement when both annotators assign labels randomly. Note that :math:`p_e` is estimated using a per-annotator empirical prior over the class labels. Args: preds: (float or long tensor), Either a ``(N, ...)`` tensor with labels or ``(N, C, ...)`` where C is the number of classes, tensor with labels/probabilities target: ``target`` (long tensor), tensor with shape ``(N, ...)`` with ground true labels num_classes: Number of classes in the dataset. weights: Weighting type to calculate the score. Choose from - ``None`` or ``'none'``: no weighting - ``'linear'``: linear weighting - ``'quadratic'``: quadratic weighting threshold: Threshold value for binary or multi-label probabilities. default: 0.5 Example: >>> from torchmetrics.functional import cohen_kappa >>> target = torch.tensor([1, 1, 0, 0]) >>> preds = torch.tensor([0, 1, 0, 0]) >>> cohen_kappa(preds, target, num_classes=2) tensor(0.5000) """ confmat = _cohen_kappa_update(preds, target, num_classes, threshold) return _cohen_kappa_compute(confmat, weights)
""" setup Gap-ML Copyright, 2018(c), Andrew Ferlitsch Autor: David Molina @virtualdvid """ from setuptools import setup, find_packages #setup components with open('README.md', 'r', encoding="utf-8") as f: long_description = f.read() install_requires=[ 'beautifulsoup4==4.6.3', 'numpy==1.14.5', 'h5py==2.8.0', 'imutils==0.5.1', 'Unidecode==1.0.22', 'nltk==3.3', 'pandas==0.23.4', 'requests==2.19.1', 'opencv-python==3.4.3.18', 'Pillow==5.2.0', 'matplotlib==2.2.3'] tests_require=[ 'pytest', 'pytest-cov'] package_data={'gapnlp':['tools/*', 'train/*']} project_urls={"Documentation": "https://gapml.github.io/NLP/", "Source Code": "https://github.com/gapml/NLP"} #https://pypi.org/pypi?%3Aaction=list_classifiers classifiers=[ 'Development Status :: 3 - Alpha', 'Topic :: Text Processing', 'License :: OSI Approved :: Apache Software License', 'Operating System :: Microsoft :: Windows', 'Operating System :: MacOS', 'Operating System :: POSIX :: Linux', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.0', 'Programming Language :: Python :: 3.1', 'Programming Language :: Python :: 3.2', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7'] setup( name='gapnlp', version='0.9.4', description='NLP and CV Data Engineering Framework', author='Andrew Ferlitsch', author_email='aferlitsch@gmail.com', license='Apache 2.0', url='https://github.com/gapml/NLP', project_urls=project_urls, long_description=long_description, packages=find_packages(exclude=["*.tests", "*.tests.*", "tests.*", "tests"]), install_requires=install_requires, tests_require=tests_require, package_data=package_data, classifiers=classifiers )
var fs = require('fs') const dataStoreFile = './dataStore.json' let dataStore = {} if (fs.existsSync(dataStoreFile)) { const str = fs.readFileSync(dataStoreFile) dataStore = str.length ? JSON.parse(str) : {} } exports.getStore = function () { return dataStore } exports.updateStore = function () { fs.writeFileSync(dataStoreFile, JSON.stringify(dataStore, null, 2)) }
const Cache = require('./cache') function openDB () { return new Promise(rs => { // Open (or create) the database const open = indexedDB.open('cachestorage', 4) // Create the schema open.onupgradeneeded = function () { const db = open.result // cointains all storage containsers db.createObjectStore('storages', { keyPath: 'cacheName' }) // contains all cache of request and responses db.createObjectStore('caches', { autoIncrement: true }) .createIndex('cacheName', 'cacheName', { unique: false }) } open.onsuccess = () => { // Start a new transaction rs(open.result) } }) } class CacheStorage { /** * [delete description] * @return {[type]} [description] */ async delete (cacheName) { // Should resolve to false if there is nothing to delete const keys = await this.keys() if (!keys.includes(cacheName)) { return false } const db = await openDB() // Start a new transaction const tx = db.transaction(['storages', 'caches'], 'readwrite') tx.objectStore('storages').delete(cacheName) const caches = tx.objectStore('caches') const index = caches.index('cacheName') const request = index.getAllKeys(IDBKeyRange.only(cacheName)) request.onsuccess = function (tx) { for (let key of this.result) { caches.delete(key) } } return new Promise((rs, rj) => { tx.oncomplete = () => rs(true) tx.onerror = () => rj(false) }) } /** * [has description] * @return {Boolean} [description] */ has (cacheName) { return this.keys().then(keys => keys.includes(cacheName)) } /** * resolves with an array containing strings corresponding to all of the named * Cache objects tracked by the CacheStorage. * Use this method to iterate over a list of all the Cache objects. * * @return <Promise>Array keyList */ async keys () { const db = await openDB() // Start a new transaction const keys = db.transaction('storages', 'readonly').objectStore('storages').getAllKeys() return new Promise(rs => keys.onsuccess = () => rs(keys.result) ) } /** * Checks if a given Request is a key in any of the Cache objects * that the CacheStorage object tracks and returns a Promise that * resolves to that match. * * @return Promise */ async match (...args) { let keys = await this.keys() for (let key of keys) { let cache = await this.open(key) let result = await cache.match(...args) if (result) return result } } /** * Resolves to the Cache object matching the cacheName * (a new cache is created if it doesn't exist.) * * @return {[type]} [description] */ async open (cacheName) { if (arguments.length < 1) { throw new TypeError(`${arguments.length} argument required, but only ${arguments.length} present.`) } const db = await openDB() await new Promise((rs, rj) => { const tx = db.transaction('storages', 'readwrite') const store = tx.objectStore('storages') // Add some data store.put({ cacheName }) tx.oncomplete = () => rs() tx.onerror = () => rj(tx.error) }) return new Cache(cacheName) } /** * [description] * @return {[type]} [description] */ [Symbol.toStringTag] () { return 'CacheStorage' } } module.exports = { Cache, CacheStorage, caches: window.caches || new CacheStorage(), }
# Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import unittest import paddle import os class TestStrategyConfig(unittest.TestCase): def test_amp(self): strategy = paddle.distributed.fleet.DistributedStrategy() strategy.amp = True self.assertEqual(strategy.amp, True) strategy.amp = False self.assertEqual(strategy.amp, False) strategy.amp = "True" self.assertEqual(strategy.amp, False) def test_amp_configs(self): strategy = paddle.distributed.fleet.DistributedStrategy() configs = { "init_loss_scaling": 32768, "decr_every_n_nan_or_inf": 2, "incr_every_n_steps": 1000, "incr_ratio": 2.0, "use_dynamic_loss_scaling": True, "decr_ratio": 0.5 } strategy.amp_configs = configs self.assertEqual(strategy.amp_configs["init_loss_scaling"], 32768) def test_recompute(self): strategy = paddle.distributed.fleet.DistributedStrategy() strategy.recompute = True self.assertEqual(strategy.recompute, True) strategy.recompute = False self.assertEqual(strategy.recompute, False) strategy.recompute = "True" self.assertEqual(strategy.recompute, False) def test_recompute_configs(self): strategy = paddle.distributed.fleet.DistributedStrategy() configs = {"checkpoints": ["x", "y"]} strategy.recompute_configs = configs self.assertEqual(len(strategy.recompute_configs["checkpoints"]), 2) def test_pipeline(self): strategy = paddle.distributed.fleet.DistributedStrategy() strategy.pipeline = True self.assertEqual(strategy.pipeline, True) strategy.pipeline = False self.assertEqual(strategy.pipeline, False) strategy.pipeline = "True" self.assertEqual(strategy.pipeline, False) def test_pipeline_configs(self): strategy = paddle.distributed.fleet.DistributedStrategy() configs = {"micro_batch": 4} strategy.pipeline_configs = configs self.assertEqual(strategy.pipeline_configs["micro_batch"], 4) def test_localsgd(self): strategy = paddle.distributed.fleet.DistributedStrategy() strategy.localsgd = True self.assertEqual(strategy.localsgd, True) strategy.localsgd = False self.assertEqual(strategy.localsgd, False) strategy.localsgd = "True" self.assertEqual(strategy.localsgd, False) def test_localsgd_configs(self): strategy = paddle.distributed.fleet.DistributedStrategy() configs = {"k_steps": 4, "begin_step": 120} strategy.localsgd_configs = configs self.assertEqual(strategy.localsgd_configs["k_steps"], 4) self.assertEqual(strategy.localsgd_configs["begin_step"], 120) def test_adaptive_localsgd_configs(self): strategy = paddle.distributed.fleet.DistributedStrategy() configs = {"init_k_steps": 1, "begin_step": 120} strategy.adaptive_localsgd_configs = configs self.assertEqual(strategy.adaptive_localsgd_configs["init_k_steps"], 1) self.assertEqual(strategy.adaptive_localsgd_configs["begin_step"], 120) def test_dgc(self): strategy = paddle.distributed.fleet.DistributedStrategy() strategy.dgc = True self.assertEqual(strategy.dgc, True) strategy.dgc = False self.assertEqual(strategy.dgc, False) strategy.dgc = "True" self.assertEqual(strategy.dgc, False) def test_fp16_allreduce(self): strategy = paddle.distributed.fleet.DistributedStrategy() strategy.fp16_allreduce = True self.assertEqual(strategy.fp16_allreduce, True) strategy.fp16_allreduce = False self.assertEqual(strategy.fp16_allreduce, False) with self.assertRaises(TypeError): strategy.fp16_allreduce = "True" self.assertEqual(strategy.fp16_allreduce, False) def test_sync_nccl_allreduce(self): strategy = paddle.distributed.fleet.DistributedStrategy() strategy.sync_nccl_allreduce = True self.assertEqual(strategy.sync_nccl_allreduce, True) strategy.sync_nccl_allreduce = False self.assertEqual(strategy.sync_nccl_allreduce, False) strategy.sync_nccl_allreduce = "True" self.assertEqual(strategy.sync_nccl_allreduce, False) def test_nccl_comm_num(self): strategy = paddle.distributed.fleet.DistributedStrategy() strategy.nccl_comm_num = 1 self.assertEqual(strategy.nccl_comm_num, 1) strategy.nccl_comm_num = "2" self.assertEqual(strategy.nccl_comm_num, 1) def test_use_hierarchical_allreduce(self): strategy = paddle.distributed.fleet.DistributedStrategy() strategy.use_hierarchical_allreduce = True self.assertEqual(strategy.use_hierarchical_allreduce, True) strategy.use_hierarchical_allreduce = False self.assertEqual(strategy.use_hierarchical_allreduce, False) strategy.use_hierarchical_allreduce = "True" self.assertEqual(strategy.use_hierarchical_allreduce, False) def test_hierarchical_allreduce_inter_nranks(self): strategy = paddle.distributed.fleet.DistributedStrategy() strategy.hierarchical_allreduce_inter_nranks = 8 self.assertEqual(strategy.hierarchical_allreduce_inter_nranks, 8) strategy.hierarchical_allreduce_inter_nranks = "4" self.assertEqual(strategy.hierarchical_allreduce_inter_nranks, 8) def test_sync_batch_norm(self): strategy = paddle.distributed.fleet.DistributedStrategy() strategy.sync_batch_norm = True self.assertEqual(strategy.sync_batch_norm, True) strategy.sync_batch_norm = False self.assertEqual(strategy.sync_batch_norm, False) strategy.sync_batch_norm = "True" self.assertEqual(strategy.sync_batch_norm, False) def test_fuse_all_reduce_ops(self): strategy = paddle.distributed.fleet.DistributedStrategy() strategy.fuse_all_reduce_ops = True self.assertEqual(strategy.fuse_all_reduce_ops, True) strategy.fuse_all_reduce_ops = False self.assertEqual(strategy.fuse_all_reduce_ops, False) strategy.fuse_all_reduce_ops = "True" self.assertEqual(strategy.fuse_all_reduce_ops, False) def test_fuse_grad_size_in_MB(self): strategy = paddle.distributed.fleet.DistributedStrategy() strategy.fuse_grad_size_in_MB = 50 self.assertEqual(strategy.fuse_grad_size_in_MB, 50) strategy.fuse_grad_size_in_MB = "40" self.assertEqual(strategy.fuse_grad_size_in_MB, 50) def test_fuse_grad_size_in_TFLOPS(self): strategy = paddle.distributed.fleet.DistributedStrategy() strategy._fuse_grad_size_in_TFLOPS = 0.1 self.assertGreater(strategy._fuse_grad_size_in_TFLOPS, 0.09) strategy._fuse_grad_size_in_TFLOPS = "0.3" self.assertGreater(strategy._fuse_grad_size_in_TFLOPS, 0.09) def test_gradient_merge(self): strategy = paddle.distributed.fleet.DistributedStrategy() strategy.gradient_merge = True self.assertEqual(strategy.gradient_merge, True) strategy.gradient_merge = False self.assertEqual(strategy.gradient_merge, False) strategy.gradient_merge = "True" self.assertEqual(strategy.gradient_merge, False) def test_gradient_merge_configs(self): strategy = paddle.distributed.fleet.DistributedStrategy() configs = {"k_steps": 4} strategy.gradient_merge_configs = configs self.assertEqual(strategy.gradient_merge_configs["k_steps"], 4) def test_lars(self): strategy = paddle.distributed.fleet.DistributedStrategy() strategy.lars = True self.assertEqual(strategy.lars, True) strategy.lars = False self.assertEqual(strategy.lars, False) strategy.lars = "True" self.assertEqual(strategy.lars, False) def test_lamb(self): strategy = paddle.distributed.fleet.DistributedStrategy() strategy.lamb = True self.assertEqual(strategy.lamb, True) strategy.lamb = False self.assertEqual(strategy.lamb, False) strategy.lamb = "True" self.assertEqual(strategy.lamb, False) def test_a_sync(self): strategy = paddle.distributed.fleet.DistributedStrategy() strategy.a_sync = True self.assertEqual(strategy.a_sync, True) strategy.a_sync = False self.assertEqual(strategy.a_sync, False) with self.assertRaises(ValueError): strategy.a_sync = "True" def test_a_sync_configs(self): strategy = paddle.distributed.fleet.DistributedStrategy() configs = {"k_steps": 1000} strategy.a_sync_configs = configs self.assertEqual(strategy.a_sync_configs["k_steps"], 1000) def test_elastic(self): strategy = paddle.distributed.fleet.DistributedStrategy() strategy.elastic = True self.assertEqual(strategy.elastic, True) strategy.elastic = False self.assertEqual(strategy.elastic, False) strategy.elastic = "True" self.assertEqual(strategy.elastic, False) def test_auto(self): strategy = paddle.distributed.fleet.DistributedStrategy() strategy.auto = True self.assertEqual(strategy.auto, True) strategy.auto = False self.assertEqual(strategy.auto, False) strategy.auto = "True" self.assertEqual(strategy.auto, False) def test_strategy_prototxt(self): strategy = paddle.distributed.fleet.DistributedStrategy() strategy.a_sync = True strategy.localsgd = True strategy.dgc = True localsgd_configs = {"k_steps": 5, "begin_step": 1} strategy.localsgd_configs = localsgd_configs build_strategy = paddle.fluid.BuildStrategy() build_strategy.enable_sequential_execution = True build_strategy.nccl_comm_num = 10 build_strategy.use_hierarchical_allreduce = True build_strategy.hierarchical_allreduce_inter_nranks = 1 build_strategy.fuse_elewise_add_act_ops = True build_strategy.fuse_bn_act_ops = True build_strategy.enable_auto_fusion = True build_strategy.fuse_relu_depthwise_conv = True build_strategy.fuse_broadcast_ops = True build_strategy.fuse_all_optimizer_ops = True build_strategy.sync_batch_norm = True build_strategy.enable_inplace = True build_strategy.fuse_all_reduce_ops = True build_strategy.enable_backward_optimizer_op_deps = True build_strategy.trainers_endpoints = ["1", "2"] strategy.build_strategy = build_strategy exe_strategy = paddle.fluid.ExecutionStrategy() exe_strategy.num_threads = 10 exe_strategy.num_iteration_per_drop_scope = 10 exe_strategy.num_iteration_per_run = 10 strategy.execution_strategy = exe_strategy strategy.save_to_prototxt("dist_strategy.prototxt") strategy2 = paddle.distributed.fleet.DistributedStrategy() strategy2.load_from_prototxt("dist_strategy.prototxt") self.assertEqual(strategy.dgc, strategy2.dgc) def test_build_strategy(self): build_strategy = paddle.fluid.BuildStrategy() build_strategy.enable_sequential_execution = True build_strategy.nccl_comm_num = 10 build_strategy.use_hierarchical_allreduce = True build_strategy.hierarchical_allreduce_inter_nranks = 1 build_strategy.fuse_elewise_add_act_ops = True build_strategy.fuse_bn_act_ops = True build_strategy.enable_auto_fusion = True build_strategy.fuse_relu_depthwise_conv = True build_strategy.fuse_broadcast_ops = True build_strategy.fuse_all_optimizer_ops = True build_strategy.sync_batch_norm = True build_strategy.enable_inplace = True build_strategy.fuse_all_reduce_ops = True build_strategy.enable_backward_optimizer_op_deps = True build_strategy.trainers_endpoints = ["1", "2"] strategy = paddle.distributed.fleet.DistributedStrategy() strategy.build_strategy = build_strategy def test_execution_strategy(self): exe_strategy = paddle.fluid.ExecutionStrategy() exe_strategy.num_threads = 10 exe_strategy.num_iteration_per_drop_scope = 10 exe_strategy.num_iteration_per_run = 10 strategy = paddle.distributed.fleet.DistributedStrategy() strategy.execution_strategy = exe_strategy def test_unknown_strategy(self): strategy = paddle.distributed.fleet.DistributedStrategy() with self.assertRaises(TypeError): strategy.unknown_key = 'UNK' def test_cudnn_exhaustive_search(self): strategy = paddle.distributed.fleet.DistributedStrategy() strategy.cudnn_exhaustive_search = False self.assertEqual(strategy.cudnn_exhaustive_search, False) strategy.cudnn_exhaustive_search = "True" self.assertEqual(strategy.cudnn_exhaustive_search, False) def test_cudnn_batchnorm_spatial_persistent(self): strategy = paddle.distributed.fleet.DistributedStrategy() strategy.cudnn_batchnorm_spatial_persistent = False self.assertEqual(strategy.cudnn_batchnorm_spatial_persistent, False) strategy.cudnn_batchnorm_spatial_persistent = "True" self.assertEqual(strategy.cudnn_batchnorm_spatial_persistent, False) def test_conv_workspace_size_limit(self): strategy = paddle.distributed.fleet.DistributedStrategy() strategy.conv_workspace_size_limit = 1000 self.assertEqual(strategy.conv_workspace_size_limit, 1000) strategy.conv_workspace_size_limit = "400" self.assertEqual(strategy.conv_workspace_size_limit, 1000) strategy._enable_env() def test_distributed_strategy_repr(self): strategy = paddle.distributed.fleet.DistributedStrategy() strategy.recompute = True strategy.recompute_configs = {"checkpoints": ["a1", "a2", "a3"]} strategy.amp = True strategy.localsgd = True print(str(strategy)) if __name__ == '__main__': unittest.main()
#!/usr/bin/env python ''' Created on 18 gru 2014 @author: ghalajko ''' from lvstop.screen import Screen from lvstop import loop if __name__ == '__main__': with Screen() as scr: try: scr.main_loop(loop) except KeyboardInterrupt: pass except: raise
"""Dilated_ResNetV0s, implemented in Gluon.""" # pylint: disable=arguments-differ,unused-argument,missing-docstring from __future__ import division from mxnet.context import cpu from mxnet.gluon.block import HybridBlock from mxnet.gluon import nn from mxnet.gluon.nn import BatchNorm __all__ = ['DilatedResNetV0', 'dilated_resnet18', 'dilated_resnet34', 'dilated_resnet50', 'dilated_resnet101', 'dilated_resnet152', 'DilatedBasicBlockV0', 'DilatedBottleneckV0'] class DilatedBasicBlockV0(HybridBlock): """DilatedResNetV0 DilatedBasicBlockV0 """ expansion = 1 def __init__(self, inplanes, planes, strides=1, dilation=1, downsample=None, previous_dilation=1, norm_layer=None, **kwargs): super(DilatedBasicBlockV0, self).__init__() self.conv1 = nn.Conv2D(in_channels=inplanes, channels=planes, kernel_size=3, strides=strides, padding=dilation, dilation=dilation, use_bias=False) self.bn1 = nn.BatchNorm(in_channels=planes) self.relu = nn.Activation('relu') self.conv2 = nn.Conv2D(in_channels=planes, channels=planes, kernel_size=3, strides=1, padding=previous_dilation, dilation=previous_dilation, use_bias=False) self.bn2 = nn.BatchNorm(in_channels=planes) self.downsample = downsample self.strides = strides def hybrid_forward(self, F, x): #def forward(self, x): residual = x out = self.conv1(x) out = self.bn1(out) out = self.relu(out) out = self.conv2(out) out = self.bn2(out) if self.downsample is not None: residual = self.downsample(x) out = out + residual out = self.relu(out) return out class DilatedBottleneckV0(HybridBlock): """DilatedResNetV0 DilatedBottleneckV0 """ # pylint: disable=unused-argument expansion = 4 def __init__(self, inplanes, planes, strides=1, dilation=1, downsample=None, previous_dilation=1, norm_layer=None, **kwargs): super(DilatedBottleneckV0, self).__init__() self.conv1 = nn.Conv2D(in_channels=inplanes, channels=planes, kernel_size=1, use_bias=False) self.bn1 = nn.BatchNorm(in_channels=planes) self.conv2 = nn.Conv2D( in_channels=planes, channels=planes, kernel_size=3, strides=strides, padding=dilation, dilation=dilation, use_bias=False) self.bn2 = nn.BatchNorm(in_channels=planes) self.conv3 = nn.Conv2D( in_channels=planes, channels=planes * 4, kernel_size=1, use_bias=False) self.bn3 = nn.BatchNorm(in_channels=planes * 4) self.relu = nn.Activation('relu') self.downsample = downsample self.dilation = dilation self.strides = strides def hybrid_forward(self, F, x): #def forward(self, x): residual = x out = self.conv1(x) out = self.bn1(out) out = self.relu(out) out = self.conv2(out) out = self.bn2(out) out = self.relu(out) out = self.conv3(out) out = self.bn3(out) if self.downsample is not None: residual = self.downsample(x) out = out + residual out = self.relu(out) return out class DilatedResNetV0(HybridBlock): """Dilated Pre-trained DilatedResNetV0 Model, which preduces the strides of 8 featuremaps at conv5. Parameters ---------- block : Block Class for the residual block. Options are BasicBlockV1, BottleneckV1. layers : list of int Numbers of layers in each block num_classes : int, default 1000 Number of classification classes. norm_layer : object Normalization layer used in backbone network (default: :class:`mxnet.gluon.nn.BatchNorm`; for Synchronized Cross-GPU BachNormalization). Reference: - He, Kaiming, et al. "Deep residual learning for image recognition." Proceedings of the IEEE conference on computer vision and pattern recognition. 2016. - Yu, Fisher, and Vladlen Koltun. "Multi-scale context aggregation by dilated convolutions." """ # pylint: disable=unused-variable def __init__(self, block, layers, num_classes=1000, norm_layer=BatchNorm, **kwargs): self.inplanes = 64 super(DilatedResNetV0, self).__init__() with self.name_scope(): self.conv1 = nn.Conv2D(in_channels=3, channels=64, kernel_size=7, strides=2, padding=3, use_bias=False) self.bn1 = norm_layer(in_channels=64) self.relu = nn.Activation('relu') self.maxpool = nn.MaxPool2D(pool_size=3, strides=2, padding=1) self.layer1 = self._make_layer(1, block, 64, layers[0], norm_layer=norm_layer) self.layer2 = self._make_layer(2, block, 128, layers[1], strides=2, norm_layer=norm_layer) self.layer3 = self._make_layer(3, block, 256, layers[2], strides=1, dilation=2, norm_layer=norm_layer) self.layer4 = self._make_layer(4, block, 512, layers[3], strides=1, dilation=4, norm_layer=norm_layer) self.avgpool = nn.AvgPool2D(7) self.flat = nn.Flatten() self.fc = nn.Dense(in_units=512 * block.expansion, units=num_classes) def _make_layer(self, stage_index, block, planes, blocks, strides=1, dilation=1, norm_layer=None): downsample = None if strides != 1 or self.inplanes != planes * block.expansion: downsample = nn.HybridSequential(prefix='down%d_'%stage_index) with downsample.name_scope(): downsample.add(nn.Conv2D(in_channels=self.inplanes, channels=planes * block.expansion, kernel_size=1, strides=strides, use_bias=False)) downsample.add(norm_layer(in_channels=planes * block.expansion)) layers = nn.HybridSequential(prefix='layers%d_'%stage_index) with layers.name_scope(): if dilation == 1 or dilation == 2: layers.add(block(self.inplanes, planes, strides, dilation=1, downsample=downsample, previous_dilation=dilation, norm_layer=norm_layer)) elif dilation == 4: layers.add(block(self.inplanes, planes, strides, dilation=2, downsample=downsample, previous_dilation=dilation, norm_layer=norm_layer)) else: raise RuntimeError("=> unknown dilation size: {}".format(dilation)) self.inplanes = planes * block.expansion for i in range(1, blocks): layers.add(block(self.inplanes, planes, dilation=dilation, previous_dilation=dilation, norm_layer=norm_layer)) return layers def hybrid_forward(self, F, x): #def forward(self, x): x = self.conv1(x) x = self.bn1(x) x = self.relu(x) x = self.maxpool(x) x = self.layer1(x) x = self.layer2(x) x = self.layer3(x) x = self.layer4(x) x = self.avgpool(x) x = self.flat(x) x = self.fc(x) return x def dilated_resnet18(pretrained=False, root='~/.mxnet/models', ctx=cpu(0), **kwargs): """Constructs a DilatedResNetV0-18 model. Parameters ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.mxnet/models' Location for keeping the model parameters. ctx : Context, default CPU The context in which to load the pretrained weights. norm_layer : object Normalization layer used in backbone network (default: :class:`mxnet.gluon.nn.BatchNorm`; for Synchronized Cross-GPU BachNormalization). """ model = DilatedResNetV0(DilatedBasicBlockV0, [2, 2, 2, 2], **kwargs) if pretrained: from ..model_store import get_model_file model.load_params(get_model_file('resnet%d_v%d'%(18, 0), root=root), ctx=ctx) return model def dilated_resnet34(pretrained=False, root='~/.mxnet/models', ctx=cpu(0), **kwargs): """Constructs a DilatedResNetV0-34 model. Parameters ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.mxnet/models' Location for keeping the model parameters. ctx : Context, default CPU The context in which to load the pretrained weights. norm_layer : object Normalization layer used in backbone network (default: :class:`mxnet.gluon.nn.BatchNorm`; """ model = DilatedResNetV0(DilatedBasicBlockV0, [3, 4, 6, 3], **kwargs) if pretrained: from ..model_store import get_model_file model.load_params(get_model_file('resnet%d_v%d'%(34, 0), root=root), ctx=ctx) return model def dilated_resnet50(pretrained=False, root='~/.mxnet/models', ctx=cpu(0), **kwargs): """Constructs a DilatedResNetV0-50 model. Parameters ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.mxnet/models' Location for keeping the model parameters. ctx : Context, default CPU The context in which to load the pretrained weights. norm_layer : object Normalization layer used in backbone network (default: :class:`mxnet.gluon.nn.BatchNorm`; """ model = DilatedResNetV0(DilatedBottleneckV0, [3, 4, 6, 3], **kwargs) if pretrained: from ..model_store import get_model_file model.load_params(get_model_file('resnet%d_v%d'%(50, 0), root=root), ctx=ctx) return model def dilated_resnet101(pretrained=False, root='~/.mxnet/models', ctx=cpu(0), **kwargs): """Constructs a DilatedResNetV0-101 model. Parameters ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.mxnet/models' Location for keeping the model parameters. ctx : Context, default CPU The context in which to load the pretrained weights. norm_layer : object Normalization layer used in backbone network (default: :class:`mxnet.gluon.nn.BatchNorm`; """ model = DilatedResNetV0(DilatedBottleneckV0, [3, 4, 23, 3], **kwargs) if pretrained: from ..model_store import get_model_file model.load_params(get_model_file('resnet%d_v%d'%(101, 0), root=root), ctx=ctx) return model def dilated_resnet152(pretrained=False, root='~/.mxnet/models', ctx=cpu(0), **kwargs): """Constructs a DilatedResNetV0-152 model. Parameters ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.mxnet/models' Location for keeping the model parameters. ctx : Context, default CPU The context in which to load the pretrained weights. norm_layer : object Normalization layer used in backbone network (default: :class:`mxnet.gluon.nn.BatchNorm`; """ model = DilatedResNetV0(DilatedBottleneckV0, [3, 8, 36, 3], **kwargs) if pretrained: from ..model_store import get_model_file model.load_params(get_model_file('resnet%d_v%d'%(152, 0), root=root), ctx=ctx) return model
#!/usr/bin/env python # Copyright 2014-2018 The PySCF Developers. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import unittest import numpy from pyscf import gto, scf, lib from pyscf import grad mol = gto.Mole() mol.verbose = 5 mol.output = '/dev/null' mol.atom.extend([ ["O" , (0. , 0. , 0.)], [1 , (0. , -0.757 , 0.587)], [1 , (0. , 0.757 , 0.587)] ]) mol.basis = '6-31g' mol.charge = -1 mol.spin = 1 mol.build() def tearDownModule(): global mol mol.stdout.close() del mol def make_mol(atom_id, coords): mol1 = mol.copy() mol1.atom[atom_id] = [mol1.atom[atom_id][0], coords] mol1.build(0, 0) return mol1 class KnownValues(unittest.TestCase): def test_finite_diff_uhf_grad(self): mf = scf.UHF(mol) mf.conv_tol = 1e-14 e0 = mf.kernel() g = grad.UHF(mf).kernel() mf_scanner = mf.as_scanner() e1 = mf_scanner(make_mol(0, (0, 0, 1e-4))) self.assertAlmostEqual(g[0,2], (e1-e0)/1e-4*lib.param.BOHR, 4) e1 = mf_scanner(make_mol(0, (0, 1e-5, 0))) self.assertAlmostEqual(g[0,1], (e1-e0)/1e-5*lib.param.BOHR, 4) e1 = mf_scanner(make_mol(1, (0. , -0.7571 , 0.587))) self.assertAlmostEqual(g[1,1], (e0-e1)/1e-4*lib.param.BOHR, 4) e1 = mf_scanner(make_mol(1, (0. , -0.757 , 0.5871))) self.assertAlmostEqual(g[1,2], (e1-e0)/1e-4*lib.param.BOHR, 4) if __name__ == "__main__": print("Full Tests for UHF Gradients") unittest.main()
import csv from collections import defaultdict #import pandas as pd #import seaborn as sns #import matplotlib.pyplot as plt #matplotlib inline #from sklearn.naive_bayes import MultinomialNB #from sklearn.cross_validation import train_test_split import numpy as np #from numpy import genfromtxt, savetxt from globalData import * # with open("nodetable.csv","r") as csvfile: # reader = csv.reader(csvfile) # symp = [] # dise = [] # for row in reader: # if row[2] == 'symptom': # symp.append(row[1]) # if row[2] == 'disease': # dise.append(row[1]) #data = pd.read_csv('data_pivoted.csv') #print data.shape #data = data.fillna(0) #data.head(5) #print data.info() #cols = data.columns.tolist() #cols.remove('disease') # dataset = genfromtxt(open('dataset1.csv','r'), delimiter=',', dtype='f8')[1:] # target = [int(x[407])-1 for x in dataset] # train = [x[0:405] for x in dataset] # x = train # y = target # #print x # #print y # #print dataset[0] # #z = raw_input() # #x = data[cols] # #print type(x) # #y = data.disease # #x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.33, random_state=42) # mnb_tot = MultinomialNB() # mnb_tot = mnb_tot.fit(x, y) # disease_pred = mnb_tot.predict(x) # disease_pred_probab = mnb_tot.predict_proba(x) # a = np.argsort(disease_pred_probab[0]) # #print a # print dise[a[len(a)-1]] # print disease_pred_probab[0] # #print np.sort(disease_pred_probab[0]) # print dise[disease_pred[0]] def predict_disease(symptoms): #print "dsf" nsymp = len(symp) check = [0 for col in range(nsymp)] for i in symptoms: check[symp.index(i)] = 1 disease_pred_probab = mnb_classifier.predict_proba(check)[0] sorted_probabs_indexes = np.argsort(disease_pred_probab) disease_top_3 = [] disease_top_3.append([dise[sorted_probabs_indexes[len(sorted_probabs_indexes)-1]],disease_pred_probab[sorted_probabs_indexes[len(sorted_probabs_indexes)-1]]]) disease_top_3.append([dise[sorted_probabs_indexes[len(sorted_probabs_indexes)-2]],disease_pred_probab[sorted_probabs_indexes[len(sorted_probabs_indexes)-2]]]) disease_top_3.append([dise[sorted_probabs_indexes[len(sorted_probabs_indexes)-3]],disease_pred_probab[sorted_probabs_indexes[len(sorted_probabs_indexes)-3]]]) return disease_top_3
#include "mefrec.h" /********************************** show_record() ********************************/ void show_record(RECORD_HEADER *record_header, ui4 record_number, PASSWORD_DATA *pwd) { si4 i, decryption_blocks; ui4 type_code, *type_string_int; ui1 *ui1_p, *decryption_key; si1 time_str[TIME_STRING_BYTES], hex_str[HEX_STRING_BYTES(CRC_BYTES)]; // display record header fields printf("Record Number: %u\n", record_number); printf("---------------- Record Header - START ----------------\n"); if (record_header->record_CRC == RECORD_HEADER_RECORD_CRC_NO_ENTRY) { printf("Record CRC: no entry\n"); } else { generate_hex_string((ui1 *) &record_header->record_CRC, CRC_BYTES, hex_str); printf("Record CRC: %s\n", hex_str); } if (strlen(record_header->type_string)) { type_string_int = (ui4 *) record_header->type_string; type_code = *type_string_int; generate_hex_string((ui1 *) record_header->type_string, CRC_BYTES, hex_str); printf("Record Type String: %s (%s)\n", record_header->type_string, hex_str); } else { type_code = MEFREC_UnRc_TYPE_CODE; printf("Record Type String: no entry\n"); } if (record_header->version_major == RECORD_HEADER_VERSION_MAJOR_NO_ENTRY || record_header->version_minor == RECORD_HEADER_VERSION_MINOR_NO_ENTRY) { if (record_header->version_major == RECORD_HEADER_VERSION_MAJOR_NO_ENTRY) printf("Record Version Major: no entry\n"); else printf("Record Version Major: %u\n", record_header->version_major); if (record_header->version_minor == RECORD_HEADER_VERSION_MINOR_NO_ENTRY) printf("Record Version Minor: no entry\n"); else printf("Record Version Minor: %u\n", record_header->version_minor); } else { printf("Record Version: %u.%u\n", record_header->version_major, record_header->version_minor); printf("Record Encryption: %d ", record_header->encryption); } if (record_header->encryption == NO_ENCRYPTION) printf("(none)\n"); else if (record_header->encryption == LEVEL_1_ENCRYPTION) printf("(level 1, currently encrypted)\n"); else if (record_header->encryption == LEVEL_2_ENCRYPTION) printf("(level 2, currently encrypted)\n"); else if (record_header->encryption == LEVEL_1_ENCRYPTION_DECRYPTED) printf("(level 1, currently decrypted)\n"); else if (record_header->encryption == LEVEL_2_ENCRYPTION_DECRYPTED) printf("(level 2, currently decrypted)\n"); else printf("(unrecognized code)\n"); if (record_header->bytes == RECORD_HEADER_BYTES_NO_ENTRY) printf("Record Bytes: no entry\n"); else printf("Record Bytes: %u\n", record_header->bytes); if (record_header->time == RECORD_HEADER_TIME_NO_ENTRY) printf("Record Time: no entry\n"); else { local_date_time_string(record_header->time, time_str); #ifdef _WIN32 printf("Record Time: %lld (uUTC), %s (ascii, local)\n", ABS(record_header->time), time_str); #else printf("Record Time: %ld (uUTC), %s (ascii, local)\n", ABS(record_header->time), time_str); #endif } printf("----------------- Record Header - END -----------------\n\n"); // decrypt record body if necesary & access level is sufficient printf("----------------- Record Body - START -----------------\n"); if (record_header->encryption > NO_ENCRYPTION) { if (pwd->access_level >= record_header->encryption) { if (record_header->encryption == LEVEL_1_ENCRYPTION) decryption_key = pwd->level_1_encryption_key; else decryption_key = pwd->level_2_encryption_key; decryption_blocks = record_header->bytes / ENCRYPTION_BLOCK_BYTES; ui1_p = (ui1 *) record_header + RECORD_HEADER_BYTES; for (i = decryption_blocks; i--;) { AES_decrypt(ui1_p, ui1_p, NULL, decryption_key); ui1_p += ENCRYPTION_BLOCK_BYTES; } record_header->encryption = -record_header->encryption; // mark as currently decrypted printf(" (record now decrypted)\n"); } else { printf("No access to this record\n"); printf("------------------ Record Body - END ------------------\n\n"); return; } } // pass the display off to custom functions - new records types should be added here (maintain alphabetical order of record types) switch (type_code) { case MEFREC_Note_TYPE_CODE: show_mefrec_Note_type(record_header); break; case MEFREC_EDFA_TYPE_CODE: show_mefrec_EDFA_type(record_header); break; case MEFREC_Seiz_TYPE_CODE: show_mefrec_Seiz_type(record_header); break; case MEFREC_SyLg_TYPE_CODE: show_mefrec_SyLg_type(record_header); break; case MEFREC_CSti_TYPE_CODE: show_mefrec_CSti_type(record_header); break; case MEFREC_Curs_TYPE_CODE: show_mefrec_Curs_type(record_header); break; case MEFREC_Epoc_TYPE_CODE: show_mefrec_Epoc_type(record_header); break; case MEFREC_UnRc_TYPE_CODE: printf("\"%s\" (0x%x) is an unrecognized record type\n", record_header->type_string, type_code); break; default: printf("\"%s\" (0x%x) is an unrecognized record type\n", record_header->type_string, type_code); break; } printf("------------------ Record Body - END ------------------\n\n"); return; } /*************************************************************************************/ /************************** check_record_alignments() *****************************/ si1 check_record_structure_alignments(ui1 *bytes) { si4 return_value; si4 free_flag = MEF_FALSE; extern MEF_GLOBALS *MEF_globals; // see if already checked if (MEF_globals->all_record_structures_aligned != MEF_UNKNOWN) return(MEF_globals->all_record_structures_aligned); return_value = MEF_TRUE; if (bytes == NULL) { bytes = (ui1 *) e_malloc(LARGEST_RECORD_BYTES, __FUNCTION__, __LINE__, USE_GLOBAL_BEHAVIOR); free_flag = MEF_TRUE; } // check all structures - add new functions here if ((check_mefrec_Note_type_alignment(bytes)) == MEF_FALSE) return_value = MEF_FALSE; if ((check_mefrec_EDFA_type_alignment(bytes)) == MEF_FALSE) return_value = MEF_FALSE; if ((check_mefrec_LNTP_type_alignment(bytes)) == MEF_FALSE) return_value = MEF_FALSE; if ((check_mefrec_Seiz_type_alignment(bytes)) == MEF_FALSE) return_value = MEF_FALSE; if ((check_mefrec_SyLg_type_alignment(bytes)) == MEF_FALSE) return_value = MEF_FALSE; if ((check_mefrec_CSti_type_alignment(bytes)) == MEF_FALSE) return_value = MEF_FALSE; if (free_flag == MEF_TRUE) free(bytes); if (return_value == MEF_TRUE) { MEF_globals->all_record_structures_aligned = MEF_TRUE; if (MEF_globals->verbose == MEF_TRUE) (void) printf("%s(): All Record structures are aligned\n", __FUNCTION__); } else { MEF_globals->all_record_structures_aligned = MEF_FALSE; if (MEF_globals->verbose == MEF_TRUE) (void) printf("%s(): One or more Record structures are not aligned\n", __FUNCTION__); } return(return_value); } /*************************************************************************************/ /******************************** Note: Note Record ******************************/ void show_mefrec_Note_type(RECORD_HEADER *record_header) { si1 *Note; // Version 1.0 if (record_header->version_major == 1 && record_header->version_minor == 0) { Note = (si1 *) record_header + MEFREC_Note_1_0_TEXT_OFFSET; UTF8_printf("Note text: %s\n", Note); } // Unrecognized record version else { printf("Unrecognized Note version\n"); } return; } si4 check_mefrec_Note_type_alignment(ui1 *bytes) { // no structures to check return(MEF_TRUE); } /*************************************************************************************/ /******************************** EDFA: EDF Annotation Record ******************************/ void show_mefrec_EDFA_type(RECORD_HEADER *record_header) { MEFREC_EDFA_1_0 *edfa; si1 *annotation; // Version 1.0 if (record_header->version_major == 1 && record_header->version_minor == 0) { edfa = (MEFREC_EDFA_1_0 *) ((ui1 *) record_header + MEFREC_EDFA_1_0_OFFSET); annotation = (si1 *) record_header + MEFREC_EDFA_1_0_ANNOTATION_OFFSET; #ifdef _WIN32 UTF8_printf("Annotation: %s\nDuration %lld microseconds\n", annotation, edfa->duration); #else UTF8_printf("Annotation: %s\nDuration %ld microseconds\n", annotation, edfa->duration); #endif } // Unrecognized record version else { printf("Unrecognized Note version\n"); } return; } si4 check_mefrec_EDFA_type_alignment(ui1 *bytes) { MEFREC_EDFA_1_0 *edfa; si4 free_flag = MEF_FALSE; extern MEF_GLOBALS *MEF_globals; // check overall size if (sizeof(MEFREC_EDFA_1_0) != MEFREC_EDFA_1_0_BYTES) goto MEFREC_EDFA_1_0_NOT_ALIGNED; // check fields if (bytes == NULL) { bytes = (ui1 *) e_malloc(LARGEST_RECORD_BYTES, __FUNCTION__, __LINE__, USE_GLOBAL_BEHAVIOR); free_flag = MEF_TRUE; } edfa = (MEFREC_EDFA_1_0 *) (bytes + MEFREC_EDFA_1_0_OFFSET); if (&edfa->duration != (si8 *) (bytes + MEFREC_EDFA_1_0_DURATION_OFFSET)) goto MEFREC_EDFA_1_0_NOT_ALIGNED; // aligned if (free_flag == MEF_TRUE) free(bytes); if (MEF_globals->verbose == MEF_TRUE) (void) printf("%s(): MEFREC_EDFA_1_0 structure is aligned\n", __FUNCTION__); return(MEF_TRUE); // not aligned MEFREC_EDFA_1_0_NOT_ALIGNED: if (free_flag == MEF_TRUE) free(bytes); (void) fprintf(stderr, "%c%s(): MEFREC_EDFA_1_0 structure is not aligned\n", 7, __FUNCTION__); return(MEF_FALSE); } /*************************************************************************************/ /************************* LNTP: Line Noise Template Record **********************/ void show_mefrec_LNTP_type(RECORD_HEADER *record_header) { MEFREC_LNTP_1_0 *lntp; si4 *template; si8 i; // Version 1.0 if (record_header->version_major == 1 && record_header->version_minor == 0) { lntp = (MEFREC_LNTP_1_0 *) ((ui1 *) record_header + MEFREC_LNTP_1_0_OFFSET); template = (si4 *) record_header + MEFREC_LNTP_1_0_TEMPLATE_OFFSET; printf("Line Noise Template:\n"); for (i = 0; i < lntp->length; ++i) printf("%d\n", template[i]); } // Unrecognized record version else { printf("Unrecognized LNTP version\n"); } return; } si4 check_mefrec_LNTP_type_alignment(ui1 *bytes) { MEFREC_LNTP_1_0 *lntp; si4 free_flag = MEF_FALSE; extern MEF_GLOBALS *MEF_globals; // check overall size if (sizeof(MEFREC_LNTP_1_0) != MEFREC_LNTP_1_0_BYTES) goto MEFREC_LNTP_1_0_NOT_ALIGNED; // check fields if (bytes == NULL) { bytes = (ui1 *) e_malloc(LARGEST_RECORD_BYTES, __FUNCTION__, __LINE__, USE_GLOBAL_BEHAVIOR); free_flag = MEF_TRUE; } lntp = (MEFREC_LNTP_1_0 *) (bytes + MEFREC_LNTP_1_0_OFFSET); if (&lntp->length != (si8 *) (bytes + MEFREC_LNTP_1_0_LENGTH_OFFSET)) goto MEFREC_LNTP_1_0_NOT_ALIGNED; // aligned if (free_flag == MEF_TRUE) free(bytes); if (MEF_globals->verbose == MEF_TRUE) (void) printf("%s(): MEFREC_LNTP_1_0 structure is aligned\n", __FUNCTION__); return(MEF_TRUE); // not aligned MEFREC_LNTP_1_0_NOT_ALIGNED: if (free_flag == MEF_TRUE) free(bytes); (void) fprintf(stderr, "%c%s(): MEFREC_LNTP_1_0 structure is not aligned\n", 7, __FUNCTION__); return(MEF_FALSE); } /*************************************************************************************/ /******************************* Seiz: Seizure Record ****************************/ void show_mefrec_Seiz_type(RECORD_HEADER *record_header) { si4 i, mn1 = MEF_FALSE, mn2 = MEF_FALSE; MEFREC_Seiz_1_0 *seizure; MEFREC_Seiz_1_0_CHANNEL *channels; si1 time_str[32]; // Version 1.0 if (record_header->version_major == 1 && record_header->version_minor == 0) { seizure = (MEFREC_Seiz_1_0 *) ((ui1 *) record_header + MEFREC_Seiz_1_0_OFFSET); local_date_time_string(seizure->earliest_onset, time_str); #ifdef _WIN32 printf("Earliest Onset: %lld (uUTC), %s (ascii, local)\n", ABS(seizure->earliest_onset), time_str); #else printf("Earliest Onset: %ld (uUTC), %s (ascii, local)\n", ABS(seizure->earliest_onset), time_str); #endif local_date_time_string(seizure->latest_offset, time_str); #ifdef _WIN32 printf("Latest Offset: %lld (uUTC), %s (ascii, local)\n", ABS(seizure->latest_offset), time_str); printf("Duration: %lld (microseconds)\n", seizure->duration); #else printf("Latest Offset: %ld (uUTC), %s (ascii, local)\n", ABS(seizure->latest_offset), time_str); printf("Duration: %ld (microseconds)\n", seizure->duration); #endif printf("Number of Channels: %d\n", seizure->number_of_channels); printf("Onset Code: %d ", seizure->onset_code); switch (seizure->onset_code) { case MEFREC_Seiz_1_0_ONSET_NO_ENTRY: printf("(no entry)\n"); break; case MEFREC_Seiz_1_0_ONSET_UNKNOWN: printf("(unknown)\n"); break; case MEFREC_Seiz_1_0_ONSET_FOCAL: printf("(focal)\n"); break; case MEFREC_Seiz_1_0_ONSET_GENERALIZED: printf("(generalized)\n"); break; case MEFREC_Seiz_1_0_ONSET_PROPAGATED: printf("(propagated)\n"); break; case MEFREC_Seiz_1_0_ONSET_MIXED: printf("(mixed)\n"); break; default: printf("(unrecognized code)\n"); break; } if (strlen(seizure->marker_name_1)) mn1 = MEF_TRUE; if (strlen(seizure->marker_name_2)) mn2 = MEF_TRUE; if (mn1 == MEF_TRUE && mn2 == MEF_TRUE) UTF8_printf("Marker Name: %s %s\n", seizure->marker_name_1, seizure->marker_name_2); else if (mn1 == MEF_TRUE) UTF8_printf("Marker Name 1: %s\nMarker Name 2: no entry\n", seizure->marker_name_1); else if (mn2 == MEF_TRUE) UTF8_printf("Marker Name 1: no_entry\nMarker Name 2: %s\n", seizure->marker_name_2); else printf("Marker Name: no_entry\n"); if (strlen(seizure->annotation)) UTF8_printf("Annotation: %s\n", seizure->annotation); else printf("Annotation: no entry\n"); channels = (MEFREC_Seiz_1_0_CHANNEL *) ((ui1 *) record_header + MEFREC_Seiz_1_0_CHANNELS_OFFSET); for (i = 0; i < seizure->number_of_channels; ++i) { if (strlen(channels[i].name)) UTF8_printf("Channel Name: %s\n", channels[i].name); else printf("Channel Name: no entry\n"); local_date_time_string(channels[i].onset, time_str); #ifdef _WIN32 printf("\tOnset: %lld (uUTC), %s (ascii, local)\n", ABS(channels[i].onset), time_str); #else printf("\tOnset: %ld (uUTC), %s (ascii, local)\n", ABS(channels[i].onset), time_str); #endif local_date_time_string(channels[i].offset, time_str); #ifdef _WIN32 printf("\tOffset: %lld (uUTC), %s (ascii, local)\n", ABS(channels[i].offset), time_str); #else printf("\tOffset: %ld (uUTC), %s (ascii, local)\n", ABS(channels[i].offset), time_str); #endif } } // Unrecognized record version else { printf("Unrecognized Seiz version\n"); } return; } si4 check_mefrec_Seiz_type_alignment(ui1 *bytes) { MEFREC_Seiz_1_0 *seiz; MEFREC_Seiz_1_0_CHANNEL *chan; si4 free_flag = MEF_FALSE; ui1 *chan_bytes; extern MEF_GLOBALS *MEF_globals; // check overall sizes if (sizeof(MEFREC_Seiz_1_0) != MEFREC_Seiz_1_0_BYTES) goto MEFREC_Seiz_1_0_NOT_ALIGNED; if (sizeof(MEFREC_Seiz_1_0_CHANNEL) != MEFREC_Seiz_1_0_CHANNEL_BYTES) goto MEFREC_Seiz_1_0_NOT_ALIGNED; // check fields - base structure if (bytes == NULL) { bytes = (ui1 *) e_malloc(LARGEST_RECORD_BYTES, __FUNCTION__, __LINE__, USE_GLOBAL_BEHAVIOR); free_flag = MEF_TRUE; } seiz = (MEFREC_Seiz_1_0 *) (bytes + MEFREC_Seiz_1_0_OFFSET); if (&seiz->earliest_onset != (si8 *) (bytes + MEFREC_Seiz_1_0_EARLIEST_ONSET_OFFSET)) goto MEFREC_Seiz_1_0_NOT_ALIGNED; if (&seiz->latest_offset != (si8 *) (bytes + MEFREC_Seiz_1_0_LATEST_OFFSET_OFFSET)) goto MEFREC_Seiz_1_0_NOT_ALIGNED; if (&seiz->duration != (si8 *) (bytes + MEFREC_Seiz_1_0_DURATION_OFFSET)) goto MEFREC_Seiz_1_0_NOT_ALIGNED; if (&seiz->number_of_channels != (si4 *) (bytes + MEFREC_Seiz_1_0_NUMBER_OF_CHANNELS_OFFSET)) goto MEFREC_Seiz_1_0_NOT_ALIGNED; if (&seiz->onset_code != (si4 *) (bytes + MEFREC_Seiz_1_0_ONSET_CODE_OFFSET)) goto MEFREC_Seiz_1_0_NOT_ALIGNED; if (seiz->marker_name_1 != (si1 *) (bytes + MEFREC_Seiz_1_0_MARKER_NAME_1_OFFSET)) goto MEFREC_Seiz_1_0_NOT_ALIGNED; if (seiz->marker_name_2 != (si1 *) (bytes + MEFREC_Seiz_1_0_MARKER_NAME_2_OFFSET)) goto MEFREC_Seiz_1_0_NOT_ALIGNED; if (seiz->annotation != (si1 *) (bytes + MEFREC_Seiz_1_0_ANNOTATION_OFFSET)) goto MEFREC_Seiz_1_0_NOT_ALIGNED; // check fields - channel structures chan_bytes = bytes + MEFREC_Seiz_1_0_CHANNELS_OFFSET; chan = (MEFREC_Seiz_1_0_CHANNEL *) chan_bytes; if (chan->name != (si1 *) (chan_bytes + MEFREC_Seiz_1_0_CHANNEL_NAME_OFFSET)) goto MEFREC_Seiz_1_0_NOT_ALIGNED; if (&chan->onset != (si8 *) (chan_bytes + MEFREC_Seiz_1_0_CHANNEL_ONSET_OFFSET)) goto MEFREC_Seiz_1_0_NOT_ALIGNED; if (&chan->offset != (si8 *) (chan_bytes + MEFREC_Seiz_1_0_CHANNEL_OFFSET_OFFSET)) goto MEFREC_Seiz_1_0_NOT_ALIGNED; // aligned if (free_flag == MEF_TRUE) free(bytes); if (MEF_globals->verbose == MEF_TRUE) (void) printf("%s(): MEFREC_Seiz_1_0 structure is aligned\n", __FUNCTION__); return(MEF_TRUE); // not aligned MEFREC_Seiz_1_0_NOT_ALIGNED: if (free_flag == MEF_TRUE) free(bytes); (void) fprintf(stderr, "%c%s(): MEFREC_Seiz_1_0 structure is not aligned\n", 7, __FUNCTION__); return(MEF_FALSE); } /*************************************************************************************/ /***************************** SyLg: System Log Record ***************************/ void show_mefrec_SyLg_type(RECORD_HEADER *record_header) { si1 *log_entry; // Version 1.0 if (record_header->version_major == 1 && record_header->version_minor == 0) { log_entry = (si1 *) record_header + MEFREC_SyLg_1_0_TEXT_OFFSET; UTF8_printf("System Log text: %s\n", log_entry); } // Unrecognized record version else { printf("Unrecognized SyLg version\n"); } return; } si4 check_mefrec_SyLg_type_alignment(ui1 *bytes) { // no structures to check return(MEF_TRUE); } /*************************************************************************************/ //show_mefrec_CSti_type not tested!!! /******************************** CSti: Cognitive stimulation ******************************/ void show_mefrec_CSti_type(RECORD_HEADER *record_header) { MEFREC_CSti_1_0 *cog_stim; // Version 1.0 if (record_header->version_major == 1 && record_header->version_minor == 0) { cog_stim = (MEFREC_CSti_1_0 *) ((ui1 *) record_header + MEFREC_CSti_1_0_OFFSET); if (strlen(cog_stim->task_type)) UTF8_printf("Task type: %s\n", cog_stim->task_type); else printf("Task type: no_entry\n"); #ifdef _WIN32 printf("Duration: %lld (microseconds)\n", cog_stim->stimulus_duration); #else printf("Duration: %ld (microseconds)\n", cog_stim->stimulus_duration); #endif if (strlen(cog_stim->stimulus_type)) UTF8_printf("Stimulation type: %s\n", cog_stim->stimulus_type); else printf("Stimulation type: no_entry\n"); if (strlen(cog_stim->patient_response)) UTF8_printf("Patient response: %s\n", cog_stim->patient_response); else printf("Patient response: no entry\n"); } // Unrecognized record version else { printf("Unrecognized Note version\n"); } return; } si4 check_mefrec_CSti_type_alignment(ui1 *bytes) { MEFREC_CSti_1_0 *cog_stim; si4 free_flag = MEF_FALSE; extern MEF_GLOBALS *MEF_globals; // check overall sizes if (sizeof(MEFREC_CSti_1_0) != MEFREC_CSti_1_0_BYTES) goto MEFREC_CSti_1_0_NOT_ALIGNED; // check fields - base structure if (bytes == NULL) { bytes = (ui1 *) e_malloc(LARGEST_RECORD_BYTES, __FUNCTION__, __LINE__, USE_GLOBAL_BEHAVIOR); free_flag = MEF_TRUE; } cog_stim = (MEFREC_CSti_1_0 *) (bytes + MEFREC_CSti_1_0_OFFSET); if (cog_stim->task_type != (si1 *) (bytes + MEFREC_CSti_1_0_TASK_TYPE_OFFSET)) goto MEFREC_CSti_1_0_NOT_ALIGNED; if (&cog_stim->stimulus_duration != (si8 *) (bytes + MEFREC_CSti_1_0_STIMULUS_DURATION_OFFSET)) goto MEFREC_CSti_1_0_NOT_ALIGNED; if (cog_stim->stimulus_type != (si1 *) (bytes + MEFREC_CSti_1_0_STIMULUS_TYPE_OFFSET)) goto MEFREC_CSti_1_0_NOT_ALIGNED; if (cog_stim->patient_response != (si1 *) (bytes + MEFREC_CSti_1_0_PATIENT_RESPONSE_OFFSET)) goto MEFREC_CSti_1_0_NOT_ALIGNED; // aligned if (free_flag == MEF_TRUE) free(bytes); if (MEF_globals->verbose == MEF_TRUE) (void) printf("%s(): MEFREC_CSti_1_0 structure is aligned\n", __FUNCTION__); return(MEF_TRUE); // not aligned MEFREC_CSti_1_0_NOT_ALIGNED: if (free_flag == MEF_TRUE) free(bytes); (void) fprintf(stderr, "%c%s(): MEFREC_Csti_1_0 structure is not aligned\n", 7, __FUNCTION__); return(MEF_FALSE); } /*************************************************************************************/ //show_mefrec_ESti_type not tested!!! /******************************** ESti: Electrical stimulation ******************************/ void show_mefrec_ESti_type(RECORD_HEADER *record_header) { MEFREC_ESti_1_0 *el_stim; // Version 1.0 if (record_header->version_major == 1 && record_header->version_minor == 0) { el_stim = (MEFREC_ESti_1_0 *) ((ui1 *) record_header + MEFREC_ESti_1_0_OFFSET); printf("Amplitude: %f ", el_stim->amplitude); switch (el_stim->ampunit_code) { case MEFREC_ESti_1_0_AMPUNIT_NO_ENTRY: printf("(no entry)\n"); break; case MEFREC_ESti_1_0_AMPUNIT_UNKNOWN: printf("(unknown)\n"); break; case MEFREC_ESti_1_0_AMPUNIT_MA: printf("(mA)\n"); break; case MEFREC_ESti_1_0_AMPUNIT_V: printf("(V)\n"); break; default: printf("(unrecognized code)\n"); break; } printf("Frequency: %f (Hz)\n", el_stim->frequency); #ifdef _WIN32 printf("Pulse width: %lld (microseconds)\n", el_stim->pulse_width); #else printf("Pulse width: %ld (microseconds)\n", el_stim->pulse_width); #endif printf("Operating mode: "); switch(el_stim->mode_code){ case MEFREC_ESti_1_0_MODE_NO_ENTRY: printf("(no entry)\n"); break; case MEFREC_ESti_1_0_MODE_UNKNOWN: printf("(unknown)\n"); break; case MEFREC_ESti_1_0_MODE_CURRENT: printf("(current)\n"); break; case MEFREC_ESti_1_0_MODE_VOLTAGE: printf("(voltage)\n"); break; default: printf("(unrecognized code)\n"); break; } if (strlen(el_stim->waveform)) UTF8_printf("Waveform: %s\n", el_stim->waveform); else printf("Waveform: no_entry\n"); if (strlen(el_stim->anode)) UTF8_printf("Anode: %s\n", el_stim->anode); else printf("Anode: no entry\n"); if (strlen(el_stim->catode)) UTF8_printf("Catode: %s\n", el_stim->catode); else printf("Catode: no entry\n"); } // Unrecognized record version else { printf("Unrecognized Note version\n"); } return; } si4 check_mefrec_ESti_type_alignment(ui1 *bytes) { MEFREC_ESti_1_0 *el_stim; si4 free_flag = MEF_FALSE; extern MEF_GLOBALS *MEF_globals; // check overall sizes if (sizeof(MEFREC_ESti_1_0) != MEFREC_ESti_1_0_BYTES) goto MEFREC_ESti_1_0_NOT_ALIGNED; // check fields - base structure if (bytes == NULL) { bytes = (ui1 *) e_malloc(LARGEST_RECORD_BYTES, __FUNCTION__, __LINE__, USE_GLOBAL_BEHAVIOR); free_flag = MEF_TRUE; } el_stim = (MEFREC_ESti_1_0 *) (bytes + MEFREC_ESti_1_0_OFFSET); if (&el_stim->amplitude != (sf8 *) (bytes + MEFREC_ESti_1_0_AMPLITUDE_OFFSET)) goto MEFREC_ESti_1_0_NOT_ALIGNED; if (&el_stim->frequency != (sf8 *) (bytes + MEFREC_ESti_1_0_FREQUENCY_OFFSET)) goto MEFREC_ESti_1_0_NOT_ALIGNED; if (&el_stim->pulse_width != (si8 *) (bytes + MEFREC_ESti_1_0_PULSE_WIDTH_OFFSET)) goto MEFREC_ESti_1_0_NOT_ALIGNED; if (&el_stim->ampunit_code != (si4 *) (bytes + MEFREC_ESti_1_0_AMPUNIT_CODE_OFFSET)) goto MEFREC_ESti_1_0_NOT_ALIGNED; if (&el_stim->mode_code != (si4 *) (bytes + MEFREC_ESti_1_0_MODE_CODE_OFFSET)) goto MEFREC_ESti_1_0_NOT_ALIGNED; if (el_stim->waveform != (si1 *) (bytes + MEFREC_ESti_1_0_WAVEFORM_OFFSET)) goto MEFREC_ESti_1_0_NOT_ALIGNED; if (el_stim->anode != (si1 *) (bytes + MEFREC_ESti_1_0_ANODE_OFFSET)) goto MEFREC_ESti_1_0_NOT_ALIGNED; if (el_stim->catode != (si1 *) (bytes + MEFREC_ESti_1_0_CATODE_OFFSET)) goto MEFREC_ESti_1_0_NOT_ALIGNED; // aligned if (free_flag == MEF_TRUE) free(bytes); if (MEF_globals->verbose == MEF_TRUE) (void) printf("%s(): MEFREC_ESti_1_0 structure is aligned\n", __FUNCTION__); return(MEF_TRUE); // not aligned MEFREC_ESti_1_0_NOT_ALIGNED: if (free_flag == MEF_TRUE) free(bytes); (void) fprintf(stderr, "%c%s(): MEFREC_Esti_1_0 structure is not aligned\n", 7, __FUNCTION__); return(MEF_FALSE); } /*************************************************************************************/ /******************************** Curs: Cursor ******************************/ void show_mefrec_Curs_type(RECORD_HEADER *record_header) { MEFREC_Curs_1_0 *cursor; si1 time_str[TIME_STRING_BYTES]; // Version 1.0 if (record_header->version_major == 1 && record_header->version_minor == 0) { cursor = (MEFREC_Curs_1_0 *) ((ui1 *) record_header + MEFREC_Curs_1_0_OFFSET); #ifdef _WIN32 printf("ID number: %lld\n", cursor->id_number); #else printf("ID number: %ld\n", cursor->id_number); #endif local_date_time_string(cursor->trace_timestamp, time_str); #ifdef _WIN32 printf("Trace timestamp: %lld (uUTC), %s (ascii, local)\n", ABS(cursor->trace_timestamp), time_str); #else printf("Trace timestamp: %ld (uUTC), %s (ascii, local)\n", ABS(cursor->trace_timestamp), time_str); #endif #ifdef _WIN32 printf("Latency: %lld (microseconds)\n", cursor->latency); #else printf("Latency: %ld (microseconds)\n", cursor->latency); #endif printf("Value: %f\n", cursor->value); printf("Name: %s\n", cursor->name); } // Unrecognized record version else { printf("Unrecognized Cursor version\n"); } return; } si4 check_mefrec_Curs_type_alignment(ui1 *bytes) { MEFREC_Curs_1_0 *cursor; si4 free_flag = MEF_FALSE; extern MEF_GLOBALS *MEF_globals; // check overall sizes if (sizeof(MEFREC_Curs_1_0) != MEFREC_Curs_1_0_BYTES) goto MEFREC_Curs_1_0_NOT_ALIGNED; // check fields - base structure if (bytes == NULL) { bytes = (ui1 *) e_malloc(LARGEST_RECORD_BYTES, __FUNCTION__, __LINE__, USE_GLOBAL_BEHAVIOR); free_flag = MEF_TRUE; } cursor = (MEFREC_Curs_1_0 *) (bytes + MEFREC_Curs_1_0_OFFSET); if (&cursor->id_number != (si8 *) (bytes + MEFREC_Curs_1_0_ID_NUMBER_OFFSET)) goto MEFREC_Curs_1_0_NOT_ALIGNED; if (&cursor->trace_timestamp != (si8 *) (bytes + MEFREC_Curs_1_0_TRACE_TIMESTAMP_OFFSET)) goto MEFREC_Curs_1_0_NOT_ALIGNED; if (&cursor->latency != (si8 *) (bytes + MEFREC_Curs_1_0_LATENCY_OFFSET)) goto MEFREC_Curs_1_0_NOT_ALIGNED; if (&cursor->value != (sf8 *) (bytes + MEFREC_Curs_1_0_VALUE_OFFSET)) goto MEFREC_Curs_1_0_NOT_ALIGNED; if (cursor->name != (si1 *) (bytes + MEFREC_Curs_1_0_NAME_OFFSET)) goto MEFREC_Curs_1_0_NOT_ALIGNED; // aligned if (free_flag == MEF_TRUE) free(bytes); if (MEF_globals->verbose == MEF_TRUE) (void) printf("%s(): MEFREC_Curs_1_0 structure is aligned\n", __FUNCTION__); return(MEF_TRUE); // not aligned MEFREC_Curs_1_0_NOT_ALIGNED: if (free_flag == MEF_TRUE) free(bytes); (void) fprintf(stderr, "%c%s(): MEFREC_Curs_1_0 structure is not aligned\n", 7, __FUNCTION__); return(MEF_FALSE); } /*************************************************************************************/ /******************************** Epoc: Epoch ******************************/ void show_mefrec_Epoc_type(RECORD_HEADER *record_header) { MEFREC_Epoc_1_0 *epoch; si1 time_str[TIME_STRING_BYTES]; // Version 1.0 if (record_header->version_major == 1 && record_header->version_minor == 0) { epoch = (MEFREC_Epoc_1_0 *) ((ui1 *) record_header + MEFREC_Epoc_1_0_OFFSET); #ifdef _WIN32 printf("ID number: %lld\n", epoch->id_number); #else printf("ID number: %ld\n", epoch->id_number); #endif local_date_time_string(epoch->timestamp, time_str); #ifdef _WIN32 printf("Timestamp: %lld (uUTC), %s (ascii, local)\n", ABS(epoch->timestamp), time_str); #else printf("Timestamp: %ld (uUTC), %s (ascii, local)\n", ABS(epoch->timestamp), time_str); #endif local_date_time_string(epoch->end_timestamp, time_str); #ifdef _WIN32 printf("End Timestamp: %lld (uUTC), %s (ascii, local)\n", ABS(epoch->timestamp), time_str); #else printf("End Timestamp: %ld (uUTC), %s (ascii, local)\n", ABS(epoch->timestamp), time_str); #endif #ifdef _WIN32 printf("Duration: %lld (microseconds)\n", epoch->duration); #else printf("Duration: %ld (microseconds)\n", epoch->duration); #endif printf("Epoch type: %s\n", epoch->epoch_type); printf("Text: %s\n", epoch->text); } // Unrecognized record version else { printf("Unrecognized Epoch version\n"); } return; } si4 check_mefrec_Epoc_type_alignment(ui1 *bytes) { MEFREC_Epoc_1_0 *epoch; si4 free_flag = MEF_FALSE; extern MEF_GLOBALS *MEF_globals; // check overall sizes if (sizeof(MEFREC_Epoc_1_0) != MEFREC_Epoc_1_0_BYTES) goto MEFREC_Epoc_1_0_NOT_ALIGNED; // check fields - base structure if (bytes == NULL) { bytes = (ui1 *) e_malloc(LARGEST_RECORD_BYTES, __FUNCTION__, __LINE__, USE_GLOBAL_BEHAVIOR); free_flag = MEF_TRUE; } epoch = (MEFREC_Epoc_1_0 *) (bytes + MEFREC_Epoc_1_0_OFFSET); if (&epoch->id_number != (si8 *) (bytes + MEFREC_Epoc_1_0_ID_NUMBER_OFFSET)) goto MEFREC_Epoc_1_0_NOT_ALIGNED; if (&epoch->timestamp != (si8 *) (bytes + MEFREC_Epoc_1_0_TIMESTAMP_OFFSET)) goto MEFREC_Epoc_1_0_NOT_ALIGNED; if (&epoch->end_timestamp != (si8 *) (bytes + MEFREC_Epoc_1_0_END_TIMESTAMP_OFFSET)) goto MEFREC_Epoc_1_0_NOT_ALIGNED; if (&epoch->duration != (si8 *) (bytes + MEFREC_Epoc_1_0_DURATION_OFFSET)) goto MEFREC_Epoc_1_0_NOT_ALIGNED; if (epoch->epoch_type != (si1 *) (bytes + MEFREC_Epoc_1_0_EPOCH_TYPE_OFFSET)) goto MEFREC_Epoc_1_0_NOT_ALIGNED; if (epoch->text != (si1 *) (bytes + MEFREC_Epoc_1_0_TEXT_OFFSET)) goto MEFREC_Epoc_1_0_NOT_ALIGNED; // aligned if (free_flag == MEF_TRUE) free(bytes); if (MEF_globals->verbose == MEF_TRUE) (void) printf("%s(): MEFREC_Epoc_1_0 structure is aligned\n", __FUNCTION__); return(MEF_TRUE); // not aligned MEFREC_Epoc_1_0_NOT_ALIGNED: if (free_flag == MEF_TRUE) free(bytes); (void) fprintf(stderr, "%c%s(): MEFREC_Epoc_1_0 structure is not aligned\n", 7, __FUNCTION__); return(MEF_FALSE); } /*************************************************************************************/
from collections import Counter from itertools import product import pickle from statistics import mean, mode, median import matplotlib.pyplot as plt import nltk from nltk.tokenize import TweetTokenizer, word_tokenize import pandas as pd from sklearn.metrics import classification_report, f1_score from sklearn.model_selection import train_test_split import torch import torch.nn as nn from torch import optim from tqdm.auto import tqdm from transformers import BertModel, BertTokenizerFast nltk.download('punkt') nltk.download('stopwords') class Dataset(torch.utils.data.Dataset): """ A class for creating a dataset for training a model Attributes: texts : iterable - texts used for training labels : iterable - lables of the texts used for training maxlen : int - maximum length of a sentence for training word2token : dict - a dictionary to convert words into digits for training a model device : str - device to use for training (gpu or cpu) """ def __init__(self, texts, labels, maxlen, word2token, device): self.texts = texts self.labels = labels self.device = device self.maxlen = maxlen self.word2token = word2token def __getitem__(self, item): text = self.texts[item] label = self.labels[item] transformed_text = [self.word2token.get(word, 1) for word in text][:self.maxlen] transformed_text = torch.tensor( transformed_text + [self.word2token['PAD'] for _ in range(self.maxlen - len(transformed_text))], dtype=torch.long, device=self.device) attention_ids = torch.tensor( [1 for _ in range(len(transformed_text))] + [0 for _ in range(self.maxlen - len(transformed_text))], dtype=torch.long, device=self.device) return transformed_text, len(transformed_text), attention_ids, label def __len__(self): return len(self.texts) class RNNclassifier(nn.Module): """ A class for training an RNN-based classifier Attributes: device : str - device to use for training (gpu or cpu) emb_size : int - size of the word embedding layer num_classes : int - number of classes to train on dropout : float - ratio of dropout level during the training hidden_size : int - size of the hidden layer of the LSTM """ def __init__(self, device, emb_size, num_classes=1, dropout=0.4, hidden_size=100): super(RNNclassifier, self).__init__() self.device = device self.hidden_size = hidden_size self.emb_size = emb_size self.dropout = nn.Dropout(dropout).to(self.device) self.num_classes = num_classes self.embedding = nn.Embedding(self.emb_size, self.hidden_size).to(self.device) self.rnn = nn.LSTM(self.hidden_size, self.hidden_size, num_layers=2, bidirectional=True, batch_first=True).to( self.device) self.linear = nn.Linear(self.hidden_size * 2, self.num_classes).to(self.device) def forward(self, tokens, attention_ids, length): embs = self.embedding(tokens) rnn_out, hidden = self.rnn(embs) drop_out = self.dropout(rnn_out) output_zero_padding = drop_out.permute([2, 0, 1]) * attention_ids output_zero_padding = output_zero_padding.permute([1, 2, 0]) out = torch.sum(output_zero_padding, 1).T / length # out = torch.sum(drop_out, 1).T / length out = out.T out = self.linear(out) return out def train_model(model, dataloader, dev_dataloader, epoches, optim=optim.RMSprop, lr=0.01): """ A function to train a torch model Parameters: model : torch model - a model that will be trained dataloader : torch dataloader - a dataloader that contains the data for training dev_dataloader : torch dataloader - a dataloader that contains the data for validating epoches : int - number of epochs during which the training will last optim : torch optimizer - an optimizer to use for the network weights update lr : float - a learning rate to use for the weights update """ optimizer = optim(model.parameters(), lr=lr) # Adam, AdamW, Adadelta, Adagrad, SGD, RMSProp binary = nn.BCEWithLogitsLoss() best_f = 0 for epoch in range(epoches): print(epoch + 1, "epoch") t = tqdm(dataloader) i = 0 for sentence, length, attention_ids, label in t: pred = model(sentence, attention_ids, length) loss = binary(pred.view(-1), label.type(torch.float32)) if i % 10 == 0: torch.save(model.state_dict(), 'model.pt') predicted = [] true = [] with torch.no_grad(): model.eval() for sentence, length, attention_ids, label in dev_dataloader: pred = model(sentence, attention_ids, length) idx = (torch.sigmoid(pred) > 0.5).type(torch.int).item() predicted.append(idx) true.append(label.item()) model.train() f1 = f1_score(true, predicted, average='macro') if f1 > best_f: model.eval() torch.save(model.state_dict(), f"{round(f1, 3)}model.pt") model.train() best_f = f1 print("Saving with score", best_f) i += 1 t.set_description(f"loss: {round(float(loss), 3)}, f-macro: {round(f1, 3)}") t.refresh() loss.backward() optimizer.step() model.zero_grad() return best_f def evaluate(model, test_dataloader): """ A function to evaluate a torch model Parameters: model : torch model - a model that will be evaluated test_dataloader : torch dataloader - a dataloader that contains the data for evaluating """ predicted = [] true = [] with torch.no_grad(): for sentence, length, attention_ids, label in test_dataloader: pred = model(sentence, attention_ids, length) idx = (torch.sigmoid(pred) > 0.5).type(torch.int).item() predicted.append(idx) true.append(label.item()) print(classification_report(true, predicted)) class NeuralNetwork: """ A class for training and evaluating a neural network model Attributes: nn_type : str - an NN architecture to use for training (currently only LSTM is supported) device : str - device to use for training (gpu or cpu) """ def __init__(self, nn_type, device): self.nn_type = nn_type self.word2token = {'PAD': 0, 'UNK': 1} self.device = device self.model = None self.tokenize = TweetTokenizer() def fit(self, X_train=None, y_train=None, X_val=None, y_val=None, ckpt=None, w2t=None): if ckpt: with open(w2t, 'rb') as handle: self.word2token = pickle.load(handle) self.model = RNNclassifier(self.device, len(self.word2token), hidden_size=25) self.model.load_state_dict(torch.load(ckpt)) else: self.fill_dict(X_train) trainds = Dataset(X_train, y_train, 50, self.word2token, self.device) devds = Dataset(X_val, y_val, 50, self.word2token, self.device) train_dataloader = torch.utils.data.DataLoader(trainds, batch_size=128) dev_dataloader = torch.utils.data.DataLoader(devds, batch_size=1) self.model = RNNclassifier(self.device, len(self.word2token), 1, 0.4, 25) self.model.train() train_model(self.model, train_dataloader, dev_dataloader, epoches=20, lr=0.01, optim=optim.Adam) with open('word2token.pkl', 'wb') as handle: pickle.dump(self.word2token, handle, protocol=pickle.HIGHEST_PROTOCOL) return self.model def evaluate(self, X_test, y_test): testds = Dataset(X_test, y_test, 50, self.word2token, self.device) test_dataloader = torch.utils.data.DataLoader(testds, batch_size=1) evaluate(self.model, test_dataloader) def predict(self, sent): testds = Dataset([self.tokenize.tokenize(sent)], [0], 50, self.word2token, self.device) test_dataloader = torch.utils.data.DataLoader(testds, batch_size=1) with torch.no_grad(): for sentence, length, attention_ids, label in test_dataloader: pred = self.model(sentence, attention_ids, length) idx = (torch.sigmoid(pred) > 0.5).type(torch.int).item() return idx, torch.sigmoid(pred).item() def fill_dict(self, X_train): all_words = set() for text in X_train: for word in text: all_words.add(word) for word in all_words: self.word2token[word] = len(self.word2token)
from .Pipe import Pipe class UnfreezeOnPlateau(Pipe): ''' This pipe allows you to unfreeze optimizers one by one when the plateau is reached. If used together with ReduceLROnPlateau, should be listed after it. It temporarily turns off LR reducing and, instead of it, performs unfreezing. Args: metric (str) : name of the metric to monitor. cooldown (int) : minimal amount of epochs between two learning rate changes. limit (int) : amount of epochs since the last improvement of maximum of the monitored metric before the learning rate change. max_mode (bool) : if True then the higher is the metric the better. Otherwise the lower is the metric the better. ''' def __init__(self, metric, subset='valid', cooldown=5, patience=5, tolerance=1.0e-3, max_mode=False): self.cooldown = cooldown self.patience = patience self.tolerance = tolerance self.since_last = 0 self.since_best = 0 self.best_metric = None self.subset = subset self.metric = metric self.max_mode = max_mode self.optimizer_index = 1 def on_init(self): if hasattr(self.trainer, '_lr_reduce'): self.trainer._lr_reduce = False self.complete = False def before_epoch(self): if "OnPlateau" in self.trainer.status: del(self.trainer.status["OnPlateau"]) def after_epoch(self): if (self.trainer._mode == 'valid' and self.trainer._subset == self.subset): if self.best_metric is None: self.best_metric = ( self.trainer._metrics[self.subset][self.metric]) self.since_best = 0 else: new_metric = self.trainer._metrics[self.subset][self.metric] if ((new_metric >= self.best_metric + self.tolerance and self.max_mode) or (new_metric < self.best_metric - self.tolerance and not self.max_mode)): self.best_metric = new_metric self.since_best = 0 if self.since_last >= self.cooldown and self.since_best >= self.patience and not self.complete: if "OnPlateau" not in self.trainer.status: self.trainer.status["OnPlateau"] = "" self.trainer.status["OnPlateau"] += " Unfreezing (optimizer " + str(self.optimizer_index) + ") *** " self.trainer._optimizers[self.optimizer_index].active = True self.since_last = 0 self.optimizer_index += 1 if self.optimizer_index >= len(self.trainer._optimizers): self.trainer._lr_reduce = True self.complete = True self.since_best += 1 self.since_last += 1
#!/usr/bin/env python # -*- coding: utf-8 -*- """ CLF utility """ from __future__ import division import os import io import pathlib import sys import array import optparse import re import xml.etree.ElementTree as et __copyright__ = 'Copyright (C) 2021 Pekka Riikonen' __email__ = 'priikone@iki.fi' __major_version__ = '0' __minor_version__ = '2' __change_version__ = '0' __version__ = '.'.join((__major_version__, __minor_version__, __change_version__)) __all__ = [ 'clfprint', 'clf2dctl', 'clf2ocio', 'main' ] def clfprint(filename): """ Parse and pretty-print CLF file to a buffer and return it. """ tree = et.parse(filename) root = tree.getroot() buf = '' desc = 'No description' idesc = '' odesc = '' revision = '' name = root.attrib['name'] if 'name' in root.attrib else '' acesname = '' acestrid = '' copyr = '' # Parse the general information before printing, stripping out # the namespace which ET always includes in the tag. for child in root: tag = re.sub(r'^{.*}', '', child.tag) if tag == 'Description': desc = child.text elif tag == 'InputDescriptor': idesc = child.text elif tag == 'OutputDescriptor': odesc = child.text elif tag == 'Info': for sub in child: stag = re.sub(r'^{.*}', '', sub.tag) if stag == 'Revision': revision = sub.text elif stag == 'ACESuserName': acesname = sub.text elif stag == 'ACEStransformID': acestrid = sub.text elif stag == 'Copyright': copyr = sub.text if acesname: buf += "%15s: %s\n" % ('Name', acesname) elif name: buf += "%15s: %s\n" % ('Name', name) buf += "%15s: %s\n" % ('Description', desc) if revision: buf += "%15s: %s\n" % ('Revision', revision) if acestrid: buf += "%15s: %s\n" % ('ACESTransformID', acestrid) if copyr: buf += "%15s: %s\n" % ('Copyright', copyr) if idesc: buf += "%15s: %s\n" % ('Input', idesc) for child in root: tag = re.sub(r'^{.*}', '', child.tag) if tag == 'Description' or tag == 'InputDescriptor' or tag == 'OutputDescriptor' or tag == 'Info': continue for sub in child: stag = re.sub(r'^{.*}', '', sub.tag) if stag != 'Description': buf += "%15s: %s\n" % (tag, 'No description') else: buf += "%15s: %s\n" % (tag, sub.text) break if odesc: buf += "%15s: %s" % ('Output', odesc) buf += "\n" return buf def clf2ocio(filename): """ Print OCIO config Look entry from the CLF file and return it. """ tree = et.parse(filename) root = tree.getroot() filename = os.path.basename(filename) buf = ' - !<Look>\n' name = root.attrib['name'] if 'name' in root.attrib else '' acesname = '' desc = '' # Parse the general information before printing, stripping out # the namespace which ET always includes in the tag. for child in root: tag = re.sub(r'^{.*}', '', child.tag) if tag == 'Description': desc = child.text elif tag == 'Info': for sub in child: stag = re.sub(r'^{.*}', '', sub.tag) if stag == 'ACESuserName': acesname = sub.text if acesname: buf += " %s: %s\n" % ('name', acesname) elif name: buf += " %s: %s\n" % ('name', name) if desc: buf += ' description: |\n' buf += ' %s\n' % desc buf += ' process_space: ACES2065-1\n' buf += ' transform: !<FileTransform> {src: ACESLooks/CLF/%s}\n' % filename return buf def clf2dctl(filename, lut_scaling=False): """ Generate Davinci CTL (DCTL) file from CLF file. Creates a new DCTL file and any possible LUT files. """ clfbuf = clfprint(filename) buf = ( "/* This file is automagically generated by clfutil %s from %s */\n" "/*\n" " Source: https://github.com/priikone/aces-looks\n\n" "%s" "*/\n\n") % (__version__, os.path.basename(filename), clfbuf) # Append DCTL template f = open(pathlib.Path(__file__).parent / 'lmt.tmpl', "r") buf += f.read() tree = et.parse(filename) root = tree.getroot() fname = os.path.basename(filename).split('.')[0] # Generate LUT files (.cube) and define them in DCTL prevtag = None prevchild = None min_in = max_in = '' num_1d = 0 num_3d = 0 for child in root: tag = re.sub(r'^{.*}', '', child.tag) if lut_scaling == False and tag == 'Range' and ('style' not in child.attrib or child.attrib['style'] != 'Clamp'): # If <Range> precedes a LUT assume it's for scaling for the LUT and the scale instead is # used in the LUT. User must know what to do and can use --lut-scaling option to override. for sub in child: stag = re.sub(r'^{.*}', '', sub.tag) if stag == 'minInValue': min_in = sub.text elif stag == 'maxInValue': max_in = sub.text elif tag == 'LUT1D' or tag == 'LUT3D': # halfDomain LUT1D not supported right now for sub in child: stag = re.sub(r'^{.*}', '', sub.tag) if stag != 'Array': continue size = sub.attrib['dim'].split(' ')[0] dim = sub.attrib['dim'].split(' ')[1] lutbuf = "# This file is automagically generated by clfutil %s from %s\n" % (__version__, os.path.basename(filename)) if tag == 'LUT1D': lutbuf += "LUT_1D_SIZE %s\n" % size if prevtag == 'Range' and min_in and max_in: lutbuf += "LUT_1D_INPUT_RANGE %s %s\n" % (min_in, max_in) root.remove(prevchild) if num_1d > 0: name = "%s_%s_%d.cube" % (fname, tag, num_1d) else: name = "%s_%s.cube" % (fname, tag) buf += "DEFINE_LUT(%s%d" % (tag, num_1d) + ', ../ACEScct_LUT/%s)\n' % name num_1d += 1 else: lutbuf += "LUT_3D_SIZE %s\n" % size if prevtag == 'Range' and min_in and max_in: lutbuf += "LUT_3D_INPUT_RANGE %s %s\n" % (min_in, max_in) root.remove(prevchild) if num_3d > 0: name = "%s_%s_%d.cube" % (fname, tag, num_3d) else: name = "%s_%s.cube" % (fname, tag) buf += "DEFINE_LUT(%s%d" % (tag, num_3d) + ', ../ACEScct_LUT/%s)\n' % name num_3d += 1 if dim == '3' or tag == 'LUT3D': lutbuf += sub.text else: f = io.StringIO(sub.text) for line in f: line = re.sub(r'\t', ' ', line) line = re.sub(r'\n', '', line) lutbuf += "%s %s %s\n" % (line, line, line) f = open(name, "w") f.write(lutbuf) prevtag = tag prevchild = child buf += "\n" buf += ( "__DEVICE__ float3 transform(int p_Width, int p_Height, int p_X, int p_Y, float p_R, float p_G, float p_B)\n" "{\n" " float3 rgb = make_float3(p_R, p_G, p_B);\n\n") # Generate the code (NOTE: full CLF spec not supported as of yet) min_in = max_in = min_out = max_out = 0.0 num_1d = 0 num_3d = 0 for child in root: tag = re.sub(r'^{.*}', '', child.tag) if tag == 'Range': if 'style' not in child.attrib or child.attrib['style'] == 'NoClamp': clamp = 0 elif 'style' in child.attrib and child.attrib['style'] == 'Clamp': clamp = 1 else: clamp = 0 for sub in child: stag = re.sub(r'^{.*}', '', sub.tag) if stag == 'minInValue': min_in = sub.text elif stag == 'maxInValue': max_in = sub.text elif stag == 'minOutValue': min_out = sub.text elif stag == 'maxOutValue': max_out = sub.text # Some of this could be pre-computed into constants buf += " rgb = range(rgb, %sf, %sf, %sf, %sf, %d);\n" % (min_in, max_in, min_out, max_out, clamp) elif tag == 'LUT1D': buf += " rgb = APPLY_LUT(rgb.x, rgb.y, rgb.z, LUT1D%d);\n" % num_1d num_1d += 1 elif tag == 'LUT3D': buf += " rgb = APPLY_LUT(rgb.x, rgb.y, rgb.z, LUT3D%d);\n" % num_3d num_3d += 1 elif tag == 'Log': # For now this only detects ACEScct and doesn't actually implement the different log formulas for sub in child: stag = re.sub(r'^{.*}', '', sub.tag) if stag == 'LogParams': if ('logSideSlope' in sub.attrib and 'logSideOffset' in sub.attrib and 'linSideBreak' in sub.attrib and sub.attrib['logSideSlope'] == "0.05707762557" and sub.attrib['logSideOffset'] == "0.5547945205" and sub.attrib['linSideBreak'] == "0.0078125"): if child.attrib['style'] == 'cameraLinToLog': buf += " rgb = lin2ACEScct(rgb);\n" else: buf += " rgb = ACEScct2lin(rgb);\n" else: print("Error: Unsupported Log formula, DCTL will not work") elif tag == 'Matrix': # For now 3x4 matrix not supported for sub in child: stag = re.sub(r'^{.*}', '', sub.tag) if stag != 'Array': continue buf += " rgb = mult_f3_f33(rgb, make_float3x3(" count = 0 f = io.StringIO(sub.text) for line in f: line = line.strip() if line == '': continue m = [x for x in line.split(' ') if x.strip()] buf += "make_float3(%sf, %sf, %sf)" % (m[0], m[1], m[2]) if count < 2: buf += ", " count += 1 buf += "));\n" elif tag == 'Description' or tag == 'InputDescriptor' or tag == 'OutputDescriptor' or tag == 'Info': continue else: print("Error: Unsupported node %s, DCTL will not work" % tag) buf += ( "\n" " return rgb;\n" "}\n") f = open(fname + ".dctl", "w") f.write(buf) def main(): """ CLF utility main function """ p = optparse.OptionParser( description='', prog='clfutil', version='0.1.0', usage='clfutil [options] [info|dctl|ocio] <clf-file>') p.add_option('--lut-scaling', '-s', nargs=0, default=False) options, arguments = p.parse_args() if len(arguments) < 2: print('clfutil: missing argument') sys.exit() cmd = arguments[0]; filename = arguments[1]; if not os.path.exists(filename): print('%s: No such file or directory' % filename) sys.exit() if cmd == 'info': buf = clfprint(filename) print(buf, end = "") elif cmd == 'ocio': buf = clf2ocio(filename) print(buf, end = "") elif cmd == 'dctl': clf2dctl(filename, options.lut_scaling) else: print('clfutil: Unknown command: %s' % cmd) sys.exit() if __name__ == '__main__': main()
# The contents of this file are automatically written by # tools/generate_schema_wrapper.py. Do not modify directly. # 2018-02-24 22:43 from altair.utils.schemapi import SchemaBase, Undefined import os import json def load_schema(): """Load the json schema associated with this module's functions""" directory = os.path.dirname(__file__) with open(os.path.join(directory, '..', 'vega-schema.json')) as f: return json.load(f) class Root(SchemaBase): """Root schema wrapper""" _schema = load_schema() _rootschema = _schema def __init__(self, autosize=Undefined, axes=Undefined, background=Undefined, config=Undefined, data=Undefined, description=Undefined, encode=Undefined, height=Undefined, layout=Undefined, legends=Undefined, marks=Undefined, padding=Undefined, projections=Undefined, scales=Undefined, signals=Undefined, title=Undefined, usermeta=Undefined, width=Undefined, **kwds): super(Root, self).__init__(autosize=autosize, axes=axes, background=background, config=config, data=data, description=description, encode=encode, height=height, layout=layout, legends=legends, marks=marks, padding=padding, projections=projections, scales=scales, signals=signals, title=title, usermeta=usermeta, width=width, **kwds) class autosize(SchemaBase): """autosize schema wrapper""" _schema = {'$ref': '#/defs/autosize'} _rootschema = Root._schema def __init__(self, *args, **kwds): super(autosize, self).__init__(*args, **kwds) class axis(SchemaBase): """axis schema wrapper Attributes ---------- orient : any scale : string title : stringOrSignal zindex : float ticks : boolean labels : boolean domain : boolean grid : boolean gridScale : string tickSize : float labelPadding : float labelFlush : oneOf(boolean, float) labelFlushOffset : float labelOverlap : oneOf(boolean, string) labelBound : oneOf(boolean, float) tickCount : tickCount format : stringOrSignal values : oneOf(list, signal) offset : oneOf(float, numberValue) position : oneOf(float, numberValue) titlePadding : oneOf(float, numberValue) minExtent : oneOf(float, numberValue) maxExtent : oneOf(float, numberValue) encode : mapping """ _schema = {'$ref': '#/defs/axis'} _rootschema = Root._schema def __init__(self, orient=Undefined, scale=Undefined, domain=Undefined, encode=Undefined, format=Undefined, grid=Undefined, gridScale=Undefined, labelBound=Undefined, labelFlush=Undefined, labelFlushOffset=Undefined, labelOverlap=Undefined, labelPadding=Undefined, labels=Undefined, maxExtent=Undefined, minExtent=Undefined, offset=Undefined, position=Undefined, tickCount=Undefined, tickSize=Undefined, ticks=Undefined, title=Undefined, titlePadding=Undefined, values=Undefined, zindex=Undefined, **kwds): super(axis, self).__init__(orient=orient, scale=scale, domain=domain, encode=encode, format=format, grid=grid, gridScale=gridScale, labelBound=labelBound, labelFlush=labelFlush, labelFlushOffset=labelFlushOffset, labelOverlap=labelOverlap, labelPadding=labelPadding, labels=labels, maxExtent=maxExtent, minExtent=minExtent, offset=offset, position=position, tickCount=tickCount, tickSize=tickSize, ticks=ticks, title=title, titlePadding=titlePadding, values=values, zindex=zindex, **kwds) class background(SchemaBase): """background schema wrapper""" _schema = {'$ref': '#/defs/background'} _rootschema = Root._schema def __init__(self, *args): super(background, self).__init__(*args) class bind(SchemaBase): """bind schema wrapper""" _schema = {'$ref': '#/defs/bind'} _rootschema = Root._schema def __init__(self, *args, **kwds): super(bind, self).__init__(*args, **kwds) class data(SchemaBase): """data schema wrapper""" _schema = {'$ref': '#/defs/data'} _rootschema = Root._schema def __init__(self, name=Undefined, format=Undefined, on=Undefined, transform=Undefined, **kwds): super(data, self).__init__(name=name, format=format, on=on, transform=transform, **kwds) class rule(SchemaBase): """rule schema wrapper Attributes ---------- test : string """ _schema = {'$ref': '#/defs/rule'} _rootschema = Root._schema def __init__(self, test=Undefined, **kwds): super(rule, self).__init__(test=test, **kwds) class encodeEntry(SchemaBase): """encodeEntry schema wrapper Attributes ---------- x : numberValue x2 : numberValue xc : numberValue width : numberValue y : numberValue y2 : numberValue yc : numberValue height : numberValue opacity : numberValue fill : colorValue fillOpacity : numberValue stroke : colorValue strokeWidth : numberValue strokeOpacity : numberValue strokeDash : arrayValue strokeDashOffset : numberValue cursor : stringValue clip : booleanValue size : numberValue shape : anyOf(string, stringValue) path : stringValue innerRadius : numberValue outerRadius : numberValue startAngle : numberValue endAngle : numberValue interpolate : stringValue tension : numberValue orient : oneOf(list, allOf(stringModifiers, anyOf(oneOf(signal, any, any, any), any, any, any))) url : stringValue align : oneOf(list, allOf(stringModifiers, anyOf(oneOf(signal, any, any, any), any, any, any))) baseline : oneOf(list, allOf(stringModifiers, anyOf(oneOf(signal, any, any, any), any, any, any))) text : stringValue dir : stringValue ellipsis : stringValue limit : numberValue dx : numberValue dy : numberValue radius : numberValue theta : numberValue angle : numberValue font : stringValue fontSize : numberValue fontWeight : nullableStringValue fontStyle : stringValue """ _schema = {'$ref': '#/defs/encodeEntry'} _rootschema = Root._schema def __init__(self, align=Undefined, angle=Undefined, baseline=Undefined, clip=Undefined, cursor=Undefined, dir=Undefined, dx=Undefined, dy=Undefined, ellipsis=Undefined, endAngle=Undefined, fill=Undefined, fillOpacity=Undefined, font=Undefined, fontSize=Undefined, fontStyle=Undefined, fontWeight=Undefined, height=Undefined, innerRadius=Undefined, interpolate=Undefined, limit=Undefined, opacity=Undefined, orient=Undefined, outerRadius=Undefined, path=Undefined, radius=Undefined, shape=Undefined, size=Undefined, startAngle=Undefined, stroke=Undefined, strokeDash=Undefined, strokeDashOffset=Undefined, strokeOpacity=Undefined, strokeWidth=Undefined, tension=Undefined, text=Undefined, theta=Undefined, url=Undefined, width=Undefined, x=Undefined, x2=Undefined, xc=Undefined, y=Undefined, y2=Undefined, yc=Undefined, **kwds): super(encodeEntry, self).__init__(align=align, angle=angle, baseline=baseline, clip=clip, cursor=cursor, dir=dir, dx=dx, dy=dy, ellipsis=ellipsis, endAngle=endAngle, fill=fill, fillOpacity=fillOpacity, font=font, fontSize=fontSize, fontStyle=fontStyle, fontWeight=fontWeight, height=height, innerRadius=innerRadius, interpolate=interpolate, limit=limit, opacity=opacity, orient=orient, outerRadius=outerRadius, path=path, radius=radius, shape=shape, size=size, startAngle=startAngle, stroke=stroke, strokeDash=strokeDash, strokeDashOffset=strokeDashOffset, strokeOpacity=strokeOpacity, strokeWidth=strokeWidth, tension=tension, text=text, theta=theta, url=url, width=width, x=x, x2=x2, xc=xc, y=y, y2=y2, yc=yc, **kwds) class encode(SchemaBase): """encode schema wrapper""" _schema = {'$ref': '#/defs/encode'} _rootschema = Root._schema def __init__(self, **kwds): super(encode, self).__init__(**kwds) class layout(SchemaBase): """layout schema wrapper""" _schema = {'$ref': '#/defs/layout'} _rootschema = Root._schema def __init__(self, *args, **kwds): super(layout, self).__init__(*args, **kwds) class guideEncode(SchemaBase): """guideEncode schema wrapper Attributes ---------- name : string interactive : boolean style : style """ _schema = {'$ref': '#/defs/guideEncode'} _rootschema = Root._schema def __init__(self, interactive=Undefined, name=Undefined, style=Undefined, **kwds): super(guideEncode, self).__init__(interactive=interactive, name=name, style=style, **kwds) class legend(SchemaBase): """legend schema wrapper Attributes ---------- size : string shape : string fill : string stroke : string opacity : string strokeDash : string type : any orient : any title : stringOrSignal zindex : float offset : oneOf(float, numberValue) padding : oneOf(float, numberValue) titlePadding : oneOf(float, numberValue) entryPadding : oneOf(float, numberValue) tickCount : tickCount format : stringOrSignal values : oneOf(list, signal) encode : mapping """ _schema = {'$ref': '#/defs/legend'} _rootschema = Root._schema def __init__(self, *args, **kwds): super(legend, self).__init__(*args, **kwds) class mark(SchemaBase): """mark schema wrapper Attributes ---------- type : marktype role : string name : string style : style key : string clip : boolean sort : compare interactive : boolean encode : encode transform : list on : onMarkTrigger """ _schema = {'$ref': '#/defs/mark'} _rootschema = Root._schema def __init__(self, type=Undefined, clip=Undefined, encode=Undefined, interactive=Undefined, key=Undefined, name=Undefined, on=Undefined, role=Undefined, sort=Undefined, style=Undefined, transform=Undefined, **kwds): super(mark, self).__init__(type=type, clip=clip, encode=encode, interactive=interactive, key=key, name=name, on=on, role=role, sort=sort, style=style, transform=transform, **kwds) class markGroup(SchemaBase): """markGroup schema wrapper""" _schema = {'$ref': '#/defs/markGroup'} _rootschema = Root._schema def __init__(self, type=Undefined, axes=Undefined, clip=Undefined, data=Undefined, encode=Undefined, interactive=Undefined, key=Undefined, layout=Undefined, legends=Undefined, marks=Undefined, name=Undefined, on=Undefined, projections=Undefined, role=Undefined, scales=Undefined, signals=Undefined, sort=Undefined, style=Undefined, title=Undefined, transform=Undefined, **kwds): super(markGroup, self).__init__(type=type, axes=axes, clip=clip, data=data, encode=encode, interactive=interactive, key=key, layout=layout, legends=legends, marks=marks, name=name, on=on, projections=projections, role=role, scales=scales, signals=signals, sort=sort, style=style, title=title, transform=transform, **kwds) class markVisual(SchemaBase): """markVisual schema wrapper""" _schema = {'$ref': '#/defs/markVisual'} _rootschema = Root._schema def __init__(self, type=Undefined, clip=Undefined, encode=Undefined, interactive=Undefined, key=Undefined, name=Undefined, on=Undefined, role=Undefined, sort=Undefined, style=Undefined, transform=Undefined, **kwds): super(markVisual, self).__init__(type=type, clip=clip, encode=encode, interactive=interactive, key=key, name=name, on=on, role=role, sort=sort, style=style, transform=transform, **kwds) class listener(SchemaBase): """listener schema wrapper""" _schema = {'$ref': '#/defs/listener'} _rootschema = Root._schema def __init__(self, *args, **kwds): super(listener, self).__init__(*args, **kwds) class onEvents(SchemaBase): """onEvents schema wrapper""" _schema = {'$ref': '#/defs/onEvents'} _rootschema = Root._schema def __init__(self, *args): super(onEvents, self).__init__(*args) class onTrigger(SchemaBase): """onTrigger schema wrapper""" _schema = {'$ref': '#/defs/onTrigger'} _rootschema = Root._schema def __init__(self, *args): super(onTrigger, self).__init__(*args) class onMarkTrigger(SchemaBase): """onMarkTrigger schema wrapper""" _schema = {'$ref': '#/defs/onMarkTrigger'} _rootschema = Root._schema def __init__(self, *args): super(onMarkTrigger, self).__init__(*args) class padding(SchemaBase): """padding schema wrapper""" _schema = {'$ref': '#/defs/padding'} _rootschema = Root._schema def __init__(self, *args, **kwds): super(padding, self).__init__(*args, **kwds) class projection(SchemaBase): """projection schema wrapper Attributes ---------- name : string type : stringOrSignal clipAngle : numberOrSignal clipExtent : oneOf(signal, list) scale : numberOrSignal translate : oneOf(signal, list) center : oneOf(signal, list) rotate : oneOf(signal, list) parallels : oneOf(signal, list) precision : numberOrSignal pointRadius : numberOrSignal fit : oneOf(mapping, list) extent : oneOf(signal, list) size : oneOf(signal, list) """ _schema = {'$ref': '#/defs/projection'} _rootschema = Root._schema def __init__(self, name=Undefined, type=Undefined, center=Undefined, clipAngle=Undefined, clipExtent=Undefined, extent=Undefined, fit=Undefined, parallels=Undefined, pointRadius=Undefined, precision=Undefined, rotate=Undefined, scale=Undefined, size=Undefined, translate=Undefined, **kwds): super(projection, self).__init__(name=name, type=type, center=center, clipAngle=clipAngle, clipExtent=clipExtent, extent=extent, fit=fit, parallels=parallels, pointRadius=pointRadius, precision=precision, rotate=rotate, scale=scale, size=size, translate=translate, **kwds) class scale(SchemaBase): """scale schema wrapper""" _schema = {'$ref': '#/defs/scale'} _rootschema = Root._schema def __init__(self, name=Undefined, domain=Undefined, domainMax=Undefined, domainMid=Undefined, domainMin=Undefined, domainRaw=Undefined, reverse=Undefined, round=Undefined, type=Undefined, **kwds): super(scale, self).__init__(name=name, domain=domain, domainMax=domainMax, domainMid=domainMid, domainMin=domainMin, domainRaw=domainRaw, reverse=reverse, round=round, type=type, **kwds) class scope(SchemaBase): """scope schema wrapper Attributes ---------- encode : encode layout : layout signals : list data : list scales : list projections : list axes : list legends : list title : title marks : list """ _schema = {'$ref': '#/defs/scope'} _rootschema = Root._schema def __init__(self, axes=Undefined, data=Undefined, encode=Undefined, layout=Undefined, legends=Undefined, marks=Undefined, projections=Undefined, scales=Undefined, signals=Undefined, title=Undefined, **kwds): super(scope, self).__init__(axes=axes, data=data, encode=encode, layout=layout, legends=legends, marks=marks, projections=projections, scales=scales, signals=signals, title=title, **kwds) class signal(SchemaBase): """signal schema wrapper""" _schema = {'$ref': '#/defs/signal'} _rootschema = Root._schema def __init__(self, *args, **kwds): super(signal, self).__init__(*args, **kwds) class signalName(SchemaBase): """signalName schema wrapper""" _schema = {'$ref': '#/defs/signalName'} _rootschema = Root._schema def __init__(self, *args): super(signalName, self).__init__(*args) class signalNew(SchemaBase): """signalNew schema wrapper Attributes ---------- name : signalName description : string value : any react : boolean update : exprString on : onEvents bind : bind """ _schema = {'$ref': '#/defs/signalNew'} _rootschema = Root._schema def __init__(self, name=Undefined, bind=Undefined, description=Undefined, on=Undefined, react=Undefined, update=Undefined, value=Undefined, **kwds): super(signalNew, self).__init__(name=name, bind=bind, description=description, on=on, react=react, update=update, value=value, **kwds) class signalPush(SchemaBase): """signalPush schema wrapper Attributes ---------- name : signalName push : any description : string on : onEvents """ _schema = {'$ref': '#/defs/signalPush'} _rootschema = Root._schema def __init__(self, name=Undefined, push=Undefined, description=Undefined, on=Undefined, **kwds): super(signalPush, self).__init__(name=name, push=push, description=description, on=on, **kwds) class streamParams(SchemaBase): """streamParams schema wrapper Attributes ---------- between : list marktype : string markname : string filter : oneOf(exprString, list) throttle : float debounce : float consume : boolean """ _schema = {'$ref': '#/defs/streamParams'} _rootschema = Root._schema def __init__(self, between=Undefined, consume=Undefined, debounce=Undefined, filter=Undefined, markname=Undefined, marktype=Undefined, throttle=Undefined, **kwds): super(streamParams, self).__init__(between=between, consume=consume, debounce=debounce, filter=filter, markname=markname, marktype=marktype, throttle=throttle, **kwds) class streamEvents(SchemaBase): """streamEvents schema wrapper Attributes ---------- source : string type : string """ _schema = {'$ref': '#/defs/streamEvents'} _rootschema = Root._schema def __init__(self, type=Undefined, source=Undefined, **kwds): super(streamEvents, self).__init__(type=type, source=source, **kwds) class stream(SchemaBase): """stream schema wrapper""" _schema = {'$ref': '#/defs/stream'} _rootschema = Root._schema def __init__(self, between=Undefined, consume=Undefined, debounce=Undefined, filter=Undefined, markname=Undefined, marktype=Undefined, throttle=Undefined, **kwds): super(stream, self).__init__(between=between, consume=consume, debounce=debounce, filter=filter, markname=markname, marktype=marktype, throttle=throttle, **kwds) class titleEncode(SchemaBase): """titleEncode schema wrapper""" _schema = {'$ref': '#/defs/titleEncode'} _rootschema = Root._schema def __init__(self, **kwds): super(titleEncode, self).__init__(**kwds) class title(SchemaBase): """title schema wrapper""" _schema = {'$ref': '#/defs/title'} _rootschema = Root._schema def __init__(self, *args, **kwds): super(title, self).__init__(*args, **kwds) class transform(SchemaBase): """transform schema wrapper""" _schema = {'$ref': '#/defs/transform'} _rootschema = Root._schema def __init__(self, *args, **kwds): super(transform, self).__init__(*args, **kwds) class transformMark(SchemaBase): """transformMark schema wrapper""" _schema = {'$ref': '#/defs/transformMark'} _rootschema = Root._schema def __init__(self, *args, **kwds): super(transformMark, self).__init__(*args, **kwds) class aggregateTransform(SchemaBase): """aggregateTransform schema wrapper Attributes ---------- type : any signal : string groupby : oneOf(list, signal) ops : oneOf(list, signal) fields : oneOf(list, signal) as : oneOf(list, signal) drop : anyOf(boolean, signal) cross : anyOf(boolean, signal) key : oneOf(scaleField, paramField, expr) """ _schema = {'$ref': '#/defs/aggregateTransform'} _rootschema = Root._schema def __init__(self, type=Undefined, cross=Undefined, drop=Undefined, fields=Undefined, groupby=Undefined, key=Undefined, ops=Undefined, signal=Undefined, **kwds): super(aggregateTransform, self).__init__(type=type, cross=cross, drop=drop, fields=fields, groupby=groupby, key=key, ops=ops, signal=signal, **kwds) class binTransform(SchemaBase): """binTransform schema wrapper Attributes ---------- type : any signal : string field : oneOf(scaleField, paramField, expr) anchor : anyOf(float, signal) maxbins : anyOf(float, signal) base : anyOf(float, signal) divide : oneOf(list, signal) extent : oneOf(list, signal) step : anyOf(float, signal) steps : oneOf(list, signal) minstep : anyOf(float, signal) nice : anyOf(boolean, signal) name : anyOf(string, signal) as : oneOf(list, signal) """ _schema = {'$ref': '#/defs/binTransform'} _rootschema = Root._schema def __init__(self, extent=Undefined, field=Undefined, type=Undefined, anchor=Undefined, base=Undefined, divide=Undefined, maxbins=Undefined, minstep=Undefined, name=Undefined, nice=Undefined, signal=Undefined, step=Undefined, steps=Undefined, **kwds): super(binTransform, self).__init__(extent=extent, field=field, type=type, anchor=anchor, base=base, divide=divide, maxbins=maxbins, minstep=minstep, name=name, nice=nice, signal=signal, step=step, steps=steps, **kwds) class collectTransform(SchemaBase): """collectTransform schema wrapper Attributes ---------- type : any signal : string sort : compare """ _schema = {'$ref': '#/defs/collectTransform'} _rootschema = Root._schema def __init__(self, type=Undefined, signal=Undefined, sort=Undefined, **kwds): super(collectTransform, self).__init__(type=type, signal=signal, sort=sort, **kwds) class countpatternTransform(SchemaBase): """countpatternTransform schema wrapper Attributes ---------- type : any signal : string field : oneOf(scaleField, paramField, expr) case : anyOf(any, signal) pattern : anyOf(string, signal) stopwords : anyOf(string, signal) as : oneOf(list, signal) """ _schema = {'$ref': '#/defs/countpatternTransform'} _rootschema = Root._schema def __init__(self, field=Undefined, type=Undefined, case=Undefined, pattern=Undefined, signal=Undefined, stopwords=Undefined, **kwds): super(countpatternTransform, self).__init__(field=field, type=type, case=case, pattern=pattern, signal=signal, stopwords=stopwords, **kwds) class crossTransform(SchemaBase): """crossTransform schema wrapper Attributes ---------- type : any signal : string filter : exprString as : oneOf(list, signal) """ _schema = {'$ref': '#/defs/crossTransform'} _rootschema = Root._schema def __init__(self, type=Undefined, filter=Undefined, signal=Undefined, **kwds): super(crossTransform, self).__init__(type=type, filter=filter, signal=signal, **kwds) class densityTransform(SchemaBase): """densityTransform schema wrapper Attributes ---------- type : any signal : string extent : oneOf(list, signal) steps : anyOf(float, signal) method : anyOf(string, signal) distribution : oneOf(mapping, mapping, mapping, mapping) as : oneOf(list, signal) """ _schema = {'$ref': '#/defs/densityTransform'} _rootschema = Root._schema def __init__(self, type=Undefined, distribution=Undefined, extent=Undefined, method=Undefined, signal=Undefined, steps=Undefined, **kwds): super(densityTransform, self).__init__(type=type, distribution=distribution, extent=extent, method=method, signal=signal, steps=steps, **kwds) class extentTransform(SchemaBase): """extentTransform schema wrapper Attributes ---------- type : any signal : string field : oneOf(scaleField, paramField, expr) """ _schema = {'$ref': '#/defs/extentTransform'} _rootschema = Root._schema def __init__(self, field=Undefined, type=Undefined, signal=Undefined, **kwds): super(extentTransform, self).__init__(field=field, type=type, signal=signal, **kwds) class filterTransform(SchemaBase): """filterTransform schema wrapper Attributes ---------- type : any signal : string expr : exprString """ _schema = {'$ref': '#/defs/filterTransform'} _rootschema = Root._schema def __init__(self, expr=Undefined, type=Undefined, signal=Undefined, **kwds): super(filterTransform, self).__init__(expr=expr, type=type, signal=signal, **kwds) class foldTransform(SchemaBase): """foldTransform schema wrapper Attributes ---------- type : any signal : string fields : oneOf(list, signal) as : oneOf(list, signal) """ _schema = {'$ref': '#/defs/foldTransform'} _rootschema = Root._schema def __init__(self, fields=Undefined, type=Undefined, signal=Undefined, **kwds): super(foldTransform, self).__init__(fields=fields, type=type, signal=signal, **kwds) class formulaTransform(SchemaBase): """formulaTransform schema wrapper Attributes ---------- type : any signal : string expr : exprString as : anyOf(string, signal) initonly : anyOf(boolean, signal) """ _schema = {'$ref': '#/defs/formulaTransform'} _rootschema = Root._schema def __init__(self, expr=Undefined, type=Undefined, initonly=Undefined, signal=Undefined, **kwds): super(formulaTransform, self).__init__(expr=expr, type=type, initonly=initonly, signal=signal, **kwds) class imputeTransform(SchemaBase): """imputeTransform schema wrapper Attributes ---------- type : any signal : string field : oneOf(scaleField, paramField, expr) key : oneOf(scaleField, paramField, expr) keyvals : oneOf(list, signal) groupby : oneOf(list, signal) method : anyOf(any, signal) value : any """ _schema = {'$ref': '#/defs/imputeTransform'} _rootschema = Root._schema def __init__(self, field=Undefined, key=Undefined, type=Undefined, groupby=Undefined, keyvals=Undefined, method=Undefined, signal=Undefined, value=Undefined, **kwds): super(imputeTransform, self).__init__(field=field, key=key, type=type, groupby=groupby, keyvals=keyvals, method=method, signal=signal, value=value, **kwds) class joinaggregateTransform(SchemaBase): """joinaggregateTransform schema wrapper Attributes ---------- type : any signal : string groupby : oneOf(list, signal) fields : oneOf(list, signal) ops : oneOf(list, signal) as : oneOf(list, signal) key : oneOf(scaleField, paramField, expr) """ _schema = {'$ref': '#/defs/joinaggregateTransform'} _rootschema = Root._schema def __init__(self, type=Undefined, fields=Undefined, groupby=Undefined, key=Undefined, ops=Undefined, signal=Undefined, **kwds): super(joinaggregateTransform, self).__init__(type=type, fields=fields, groupby=groupby, key=key, ops=ops, signal=signal, **kwds) class lookupTransform(SchemaBase): """lookupTransform schema wrapper Attributes ---------- type : any signal : string from : string key : oneOf(scaleField, paramField, expr) values : oneOf(list, signal) fields : oneOf(list, signal) as : oneOf(list, signal) default : any """ _schema = {'$ref': '#/defs/lookupTransform'} _rootschema = Root._schema def __init__(self, fields=Undefined, key=Undefined, type=Undefined, default=Undefined, signal=Undefined, values=Undefined, **kwds): super(lookupTransform, self).__init__(fields=fields, key=key, type=type, default=default, signal=signal, values=values, **kwds) class projectTransform(SchemaBase): """projectTransform schema wrapper Attributes ---------- type : any signal : string fields : oneOf(list, signal) as : oneOf(list, signal) """ _schema = {'$ref': '#/defs/projectTransform'} _rootschema = Root._schema def __init__(self, type=Undefined, fields=Undefined, signal=Undefined, **kwds): super(projectTransform, self).__init__(type=type, fields=fields, signal=signal, **kwds) class sampleTransform(SchemaBase): """sampleTransform schema wrapper Attributes ---------- type : any signal : string size : anyOf(float, signal) """ _schema = {'$ref': '#/defs/sampleTransform'} _rootschema = Root._schema def __init__(self, type=Undefined, signal=Undefined, size=Undefined, **kwds): super(sampleTransform, self).__init__(type=type, signal=signal, size=size, **kwds) class sequenceTransform(SchemaBase): """sequenceTransform schema wrapper Attributes ---------- type : any signal : string start : anyOf(float, signal) stop : anyOf(float, signal) step : anyOf(float, signal) """ _schema = {'$ref': '#/defs/sequenceTransform'} _rootschema = Root._schema def __init__(self, start=Undefined, stop=Undefined, type=Undefined, signal=Undefined, step=Undefined, **kwds): super(sequenceTransform, self).__init__(start=start, stop=stop, type=type, signal=signal, step=step, **kwds) class windowTransform(SchemaBase): """windowTransform schema wrapper Attributes ---------- type : any signal : string sort : compare groupby : oneOf(list, signal) ops : oneOf(list, signal) params : oneOf(list, signal) fields : oneOf(list, signal) as : oneOf(list, signal) frame : oneOf(list, signal) ignorePeers : anyOf(boolean, signal) """ _schema = {'$ref': '#/defs/windowTransform'} _rootschema = Root._schema def __init__(self, type=Undefined, fields=Undefined, frame=Undefined, groupby=Undefined, ignorePeers=Undefined, ops=Undefined, params=Undefined, signal=Undefined, sort=Undefined, **kwds): super(windowTransform, self).__init__(type=type, fields=fields, frame=frame, groupby=groupby, ignorePeers=ignorePeers, ops=ops, params=params, signal=signal, sort=sort, **kwds) class identifierTransform(SchemaBase): """identifierTransform schema wrapper Attributes ---------- type : any signal : string as : anyOf(string, signal) """ _schema = {'$ref': '#/defs/identifierTransform'} _rootschema = Root._schema def __init__(self, type=Undefined, signal=Undefined, **kwds): super(identifierTransform, self).__init__(type=type, signal=signal, **kwds) class linkpathTransform(SchemaBase): """linkpathTransform schema wrapper Attributes ---------- type : any signal : string sourceX : oneOf(scaleField, paramField, expr) sourceY : oneOf(scaleField, paramField, expr) targetX : oneOf(scaleField, paramField, expr) targetY : oneOf(scaleField, paramField, expr) orient : anyOf(any, signal) shape : anyOf(any, signal) as : anyOf(string, signal) """ _schema = {'$ref': '#/defs/linkpathTransform'} _rootschema = Root._schema def __init__(self, type=Undefined, orient=Undefined, shape=Undefined, signal=Undefined, sourceX=Undefined, sourceY=Undefined, targetX=Undefined, targetY=Undefined, **kwds): super(linkpathTransform, self).__init__(type=type, orient=orient, shape=shape, signal=signal, sourceX=sourceX, sourceY=sourceY, targetX=targetX, targetY=targetY, **kwds) class pieTransform(SchemaBase): """pieTransform schema wrapper Attributes ---------- type : any signal : string field : oneOf(scaleField, paramField, expr) startAngle : anyOf(float, signal) endAngle : anyOf(float, signal) sort : anyOf(boolean, signal) as : oneOf(list, signal) """ _schema = {'$ref': '#/defs/pieTransform'} _rootschema = Root._schema def __init__(self, type=Undefined, endAngle=Undefined, field=Undefined, signal=Undefined, sort=Undefined, startAngle=Undefined, **kwds): super(pieTransform, self).__init__(type=type, endAngle=endAngle, field=field, signal=signal, sort=sort, startAngle=startAngle, **kwds) class stackTransform(SchemaBase): """stackTransform schema wrapper Attributes ---------- type : any signal : string field : oneOf(scaleField, paramField, expr) groupby : oneOf(list, signal) sort : compare offset : anyOf(any, signal) as : oneOf(list, signal) """ _schema = {'$ref': '#/defs/stackTransform'} _rootschema = Root._schema def __init__(self, type=Undefined, field=Undefined, groupby=Undefined, offset=Undefined, signal=Undefined, sort=Undefined, **kwds): super(stackTransform, self).__init__(type=type, field=field, groupby=groupby, offset=offset, signal=signal, sort=sort, **kwds) class contourTransform(SchemaBase): """contourTransform schema wrapper Attributes ---------- type : any signal : string size : oneOf(list, signal) values : oneOf(list, signal) x : oneOf(scaleField, paramField, expr) y : oneOf(scaleField, paramField, expr) cellSize : anyOf(float, signal) bandwidth : anyOf(float, signal) count : anyOf(float, signal) nice : anyOf(float, signal) thresholds : oneOf(list, signal) """ _schema = {'$ref': '#/defs/contourTransform'} _rootschema = Root._schema def __init__(self, size=Undefined, type=Undefined, bandwidth=Undefined, cellSize=Undefined, count=Undefined, nice=Undefined, signal=Undefined, thresholds=Undefined, values=Undefined, x=Undefined, y=Undefined, **kwds): super(contourTransform, self).__init__(size=size, type=type, bandwidth=bandwidth, cellSize=cellSize, count=count, nice=nice, signal=signal, thresholds=thresholds, values=values, x=x, y=y, **kwds) class geojsonTransform(SchemaBase): """geojsonTransform schema wrapper Attributes ---------- type : any signal : string fields : oneOf(list, signal) geojson : oneOf(scaleField, paramField, expr) """ _schema = {'$ref': '#/defs/geojsonTransform'} _rootschema = Root._schema def __init__(self, type=Undefined, fields=Undefined, geojson=Undefined, signal=Undefined, **kwds): super(geojsonTransform, self).__init__(type=type, fields=fields, geojson=geojson, signal=signal, **kwds) class geopathTransform(SchemaBase): """geopathTransform schema wrapper Attributes ---------- type : any signal : string projection : string field : oneOf(scaleField, paramField, expr) as : anyOf(string, signal) """ _schema = {'$ref': '#/defs/geopathTransform'} _rootschema = Root._schema def __init__(self, type=Undefined, field=Undefined, projection=Undefined, signal=Undefined, **kwds): super(geopathTransform, self).__init__(type=type, field=field, projection=projection, signal=signal, **kwds) class geopointTransform(SchemaBase): """geopointTransform schema wrapper Attributes ---------- type : any signal : string projection : string fields : oneOf(list, signal) as : oneOf(list, signal) """ _schema = {'$ref': '#/defs/geopointTransform'} _rootschema = Root._schema def __init__(self, fields=Undefined, projection=Undefined, type=Undefined, signal=Undefined, **kwds): super(geopointTransform, self).__init__(fields=fields, projection=projection, type=type, signal=signal, **kwds) class geoshapeTransform(SchemaBase): """geoshapeTransform schema wrapper Attributes ---------- type : any signal : string projection : string field : oneOf(scaleField, paramField, expr) as : anyOf(string, signal) """ _schema = {'$ref': '#/defs/geoshapeTransform'} _rootschema = Root._schema def __init__(self, type=Undefined, field=Undefined, projection=Undefined, signal=Undefined, **kwds): super(geoshapeTransform, self).__init__(type=type, field=field, projection=projection, signal=signal, **kwds) class graticuleTransform(SchemaBase): """graticuleTransform schema wrapper Attributes ---------- type : any signal : string extent : oneOf(list, signal) extentMajor : oneOf(list, signal) extentMinor : oneOf(list, signal) step : oneOf(list, signal) stepMajor : oneOf(list, signal) stepMinor : oneOf(list, signal) precision : anyOf(float, signal) """ _schema = {'$ref': '#/defs/graticuleTransform'} _rootschema = Root._schema def __init__(self, type=Undefined, extent=Undefined, extentMajor=Undefined, extentMinor=Undefined, precision=Undefined, signal=Undefined, step=Undefined, stepMajor=Undefined, stepMinor=Undefined, **kwds): super(graticuleTransform, self).__init__(type=type, extent=extent, extentMajor=extentMajor, extentMinor=extentMinor, precision=precision, signal=signal, step=step, stepMajor=stepMajor, stepMinor=stepMinor, **kwds) class forceTransform(SchemaBase): """forceTransform schema wrapper Attributes ---------- type : any signal : string static : anyOf(boolean, signal) restart : anyOf(boolean, signal) iterations : anyOf(float, signal) alpha : anyOf(float, signal) alphaMin : anyOf(float, signal) alphaTarget : anyOf(float, signal) velocityDecay : anyOf(float, signal) forces : list as : oneOf(list, signal) """ _schema = {'$ref': '#/defs/forceTransform'} _rootschema = Root._schema def __init__(self, type=Undefined, alpha=Undefined, alphaMin=Undefined, alphaTarget=Undefined, forces=Undefined, iterations=Undefined, restart=Undefined, signal=Undefined, static=Undefined, velocityDecay=Undefined, **kwds): super(forceTransform, self).__init__(type=type, alpha=alpha, alphaMin=alphaMin, alphaTarget=alphaTarget, forces=forces, iterations=iterations, restart=restart, signal=signal, static=static, velocityDecay=velocityDecay, **kwds) class nestTransform(SchemaBase): """nestTransform schema wrapper Attributes ---------- type : any signal : string keys : oneOf(list, signal) key : oneOf(scaleField, paramField, expr) generate : anyOf(boolean, signal) """ _schema = {'$ref': '#/defs/nestTransform'} _rootschema = Root._schema def __init__(self, type=Undefined, generate=Undefined, key=Undefined, keys=Undefined, signal=Undefined, **kwds): super(nestTransform, self).__init__(type=type, generate=generate, key=key, keys=keys, signal=signal, **kwds) class packTransform(SchemaBase): """packTransform schema wrapper Attributes ---------- type : any signal : string field : oneOf(scaleField, paramField, expr) sort : compare padding : anyOf(float, signal) radius : oneOf(scaleField, paramField, expr) size : oneOf(list, signal) as : oneOf(list, signal) """ _schema = {'$ref': '#/defs/packTransform'} _rootschema = Root._schema def __init__(self, type=Undefined, field=Undefined, padding=Undefined, radius=Undefined, signal=Undefined, size=Undefined, sort=Undefined, **kwds): super(packTransform, self).__init__(type=type, field=field, padding=padding, radius=radius, signal=signal, size=size, sort=sort, **kwds) class partitionTransform(SchemaBase): """partitionTransform schema wrapper Attributes ---------- type : any signal : string field : oneOf(scaleField, paramField, expr) sort : compare padding : anyOf(float, signal) round : anyOf(boolean, signal) size : oneOf(list, signal) as : oneOf(list, signal) """ _schema = {'$ref': '#/defs/partitionTransform'} _rootschema = Root._schema def __init__(self, type=Undefined, field=Undefined, padding=Undefined, round=Undefined, signal=Undefined, size=Undefined, sort=Undefined, **kwds): super(partitionTransform, self).__init__(type=type, field=field, padding=padding, round=round, signal=signal, size=size, sort=sort, **kwds) class stratifyTransform(SchemaBase): """stratifyTransform schema wrapper Attributes ---------- type : any signal : string key : oneOf(scaleField, paramField, expr) parentKey : oneOf(scaleField, paramField, expr) """ _schema = {'$ref': '#/defs/stratifyTransform'} _rootschema = Root._schema def __init__(self, key=Undefined, parentKey=Undefined, type=Undefined, signal=Undefined, **kwds): super(stratifyTransform, self).__init__(key=key, parentKey=parentKey, type=type, signal=signal, **kwds) class treeTransform(SchemaBase): """treeTransform schema wrapper Attributes ---------- type : any signal : string field : oneOf(scaleField, paramField, expr) sort : compare method : anyOf(any, signal) size : oneOf(list, signal) nodeSize : oneOf(list, signal) as : oneOf(list, signal) """ _schema = {'$ref': '#/defs/treeTransform'} _rootschema = Root._schema def __init__(self, type=Undefined, field=Undefined, method=Undefined, nodeSize=Undefined, signal=Undefined, size=Undefined, sort=Undefined, **kwds): super(treeTransform, self).__init__(type=type, field=field, method=method, nodeSize=nodeSize, signal=signal, size=size, sort=sort, **kwds) class treelinksTransform(SchemaBase): """treelinksTransform schema wrapper Attributes ---------- type : any signal : string key : oneOf(scaleField, paramField, expr) """ _schema = {'$ref': '#/defs/treelinksTransform'} _rootschema = Root._schema def __init__(self, type=Undefined, key=Undefined, signal=Undefined, **kwds): super(treelinksTransform, self).__init__(type=type, key=key, signal=signal, **kwds) class treemapTransform(SchemaBase): """treemapTransform schema wrapper Attributes ---------- type : any signal : string field : oneOf(scaleField, paramField, expr) sort : compare method : anyOf(any, signal) padding : anyOf(float, signal) paddingInner : anyOf(float, signal) paddingOuter : anyOf(float, signal) paddingTop : anyOf(float, signal) paddingRight : anyOf(float, signal) paddingBottom : anyOf(float, signal) paddingLeft : anyOf(float, signal) ratio : anyOf(float, signal) round : anyOf(boolean, signal) size : oneOf(list, signal) as : oneOf(list, signal) """ _schema = {'$ref': '#/defs/treemapTransform'} _rootschema = Root._schema def __init__(self, type=Undefined, field=Undefined, method=Undefined, padding=Undefined, paddingBottom=Undefined, paddingInner=Undefined, paddingLeft=Undefined, paddingOuter=Undefined, paddingRight=Undefined, paddingTop=Undefined, ratio=Undefined, round=Undefined, signal=Undefined, size=Undefined, sort=Undefined, **kwds): super(treemapTransform, self).__init__(type=type, field=field, method=method, padding=padding, paddingBottom=paddingBottom, paddingInner=paddingInner, paddingLeft=paddingLeft, paddingOuter=paddingOuter, paddingRight=paddingRight, paddingTop=paddingTop, ratio=ratio, round=round, signal=signal, size=size, sort=sort, **kwds) class voronoiTransform(SchemaBase): """voronoiTransform schema wrapper Attributes ---------- type : any signal : string x : oneOf(scaleField, paramField, expr) y : oneOf(scaleField, paramField, expr) size : oneOf(list, signal) extent : oneOf(list, signal) as : anyOf(string, signal) """ _schema = {'$ref': '#/defs/voronoiTransform'} _rootschema = Root._schema def __init__(self, type=Undefined, x=Undefined, y=Undefined, extent=Undefined, signal=Undefined, size=Undefined, **kwds): super(voronoiTransform, self).__init__(type=type, x=x, y=y, extent=extent, signal=signal, size=size, **kwds) class wordcloudTransform(SchemaBase): """wordcloudTransform schema wrapper Attributes ---------- type : any signal : string size : oneOf(list, signal) font : anyOf(string, signal, expr, paramField) fontStyle : anyOf(string, signal, expr, paramField) fontWeight : anyOf(string, signal, expr, paramField) fontSize : anyOf(float, signal, expr, paramField) fontSizeRange : oneOf(list, signal, None) rotate : anyOf(float, signal, expr, paramField) text : oneOf(scaleField, paramField, expr) spiral : anyOf(string, signal) padding : anyOf(float, signal, expr, paramField) as : oneOf(list, signal) """ _schema = {'$ref': '#/defs/wordcloudTransform'} _rootschema = Root._schema def __init__(self, type=Undefined, font=Undefined, fontSize=Undefined, fontSizeRange=Undefined, fontStyle=Undefined, fontWeight=Undefined, padding=Undefined, rotate=Undefined, signal=Undefined, size=Undefined, spiral=Undefined, text=Undefined, **kwds): super(wordcloudTransform, self).__init__(type=type, font=font, fontSize=fontSize, fontSizeRange=fontSizeRange, fontStyle=fontStyle, fontWeight=fontWeight, padding=padding, rotate=rotate, signal=signal, size=size, spiral=spiral, text=text, **kwds) class crossfilterTransform(SchemaBase): """crossfilterTransform schema wrapper Attributes ---------- type : any signal : string fields : oneOf(list, signal) query : oneOf(list, signal) """ _schema = {'$ref': '#/defs/crossfilterTransform'} _rootschema = Root._schema def __init__(self, fields=Undefined, query=Undefined, type=Undefined, signal=Undefined, **kwds): super(crossfilterTransform, self).__init__(fields=fields, query=query, type=type, signal=signal, **kwds) class resolvefilterTransform(SchemaBase): """resolvefilterTransform schema wrapper Attributes ---------- type : any signal : string ignore : anyOf(float, signal) filter : any """ _schema = {'$ref': '#/defs/resolvefilterTransform'} _rootschema = Root._schema def __init__(self, filter=Undefined, ignore=Undefined, type=Undefined, signal=Undefined, **kwds): super(resolvefilterTransform, self).__init__(filter=filter, ignore=ignore, type=type, signal=signal, **kwds) class tickCount(SchemaBase): """tickCount schema wrapper""" _schema = {'$ref': '#/refs/tickCount'} _rootschema = Root._schema def __init__(self, *args, **kwds): super(tickCount, self).__init__(*args, **kwds) class element(SchemaBase): """element schema wrapper""" _schema = {'$ref': '#/refs/element'} _rootschema = Root._schema def __init__(self, *args): super(element, self).__init__(*args) class paramField(SchemaBase): """paramField schema wrapper Attributes ---------- field : string """ _schema = {'$ref': '#/refs/paramField'} _rootschema = Root._schema def __init__(self, field=Undefined, **kwds): super(paramField, self).__init__(field=field, **kwds) class field(SchemaBase): """field schema wrapper""" _schema = {'$ref': '#/refs/field'} _rootschema = Root._schema def __init__(self, *args, **kwds): super(field, self).__init__(*args, **kwds) class scale(SchemaBase): """scale schema wrapper""" _schema = {'$ref': '#/refs/scale'} _rootschema = Root._schema def __init__(self, *args, **kwds): super(scale, self).__init__(*args, **kwds) class stringModifiers(SchemaBase): """stringModifiers schema wrapper Attributes ---------- scale : scale """ _schema = {'$ref': '#/refs/stringModifiers'} _rootschema = Root._schema def __init__(self, scale=Undefined, **kwds): super(stringModifiers, self).__init__(scale=scale, **kwds) class numberModifiers(SchemaBase): """numberModifiers schema wrapper Attributes ---------- exponent : oneOf(float, numberValue) mult : oneOf(float, numberValue) offset : oneOf(float, numberValue) round : boolean scale : scale band : anyOf(float, boolean) extra : boolean """ _schema = {'$ref': '#/refs/numberModifiers'} _rootschema = Root._schema def __init__(self, band=Undefined, exponent=Undefined, extra=Undefined, mult=Undefined, offset=Undefined, round=Undefined, scale=Undefined, **kwds): super(numberModifiers, self).__init__(band=band, exponent=exponent, extra=extra, mult=mult, offset=offset, round=round, scale=scale, **kwds) class value(SchemaBase): """value schema wrapper""" _schema = {'$ref': '#/refs/value'} _rootschema = Root._schema def __init__(self, *args, **kwds): super(value, self).__init__(*args, **kwds) class numberValue(SchemaBase): """numberValue schema wrapper""" _schema = {'$ref': '#/refs/numberValue'} _rootschema = Root._schema def __init__(self, *args, **kwds): super(numberValue, self).__init__(*args, **kwds) class stringValue(SchemaBase): """stringValue schema wrapper""" _schema = {'$ref': '#/refs/stringValue'} _rootschema = Root._schema def __init__(self, *args, **kwds): super(stringValue, self).__init__(*args, **kwds) class booleanValue(SchemaBase): """booleanValue schema wrapper""" _schema = {'$ref': '#/refs/booleanValue'} _rootschema = Root._schema def __init__(self, *args, **kwds): super(booleanValue, self).__init__(*args, **kwds) class arrayValue(SchemaBase): """arrayValue schema wrapper""" _schema = {'$ref': '#/refs/arrayValue'} _rootschema = Root._schema def __init__(self, *args, **kwds): super(arrayValue, self).__init__(*args, **kwds) class nullableStringValue(SchemaBase): """nullableStringValue schema wrapper""" _schema = {'$ref': '#/refs/nullableStringValue'} _rootschema = Root._schema def __init__(self, *args, **kwds): super(nullableStringValue, self).__init__(*args, **kwds) class colorRGB(SchemaBase): """colorRGB schema wrapper Attributes ---------- r : numberValue g : numberValue b : numberValue """ _schema = {'$ref': '#/refs/colorRGB'} _rootschema = Root._schema def __init__(self, b=Undefined, g=Undefined, r=Undefined, **kwds): super(colorRGB, self).__init__(b=b, g=g, r=r, **kwds) class colorHSL(SchemaBase): """colorHSL schema wrapper Attributes ---------- h : numberValue s : numberValue l : numberValue """ _schema = {'$ref': '#/refs/colorHSL'} _rootschema = Root._schema def __init__(self, h=Undefined, l=Undefined, s=Undefined, **kwds): super(colorHSL, self).__init__(h=h, l=l, s=s, **kwds) class colorLAB(SchemaBase): """colorLAB schema wrapper Attributes ---------- l : numberValue a : numberValue b : numberValue """ _schema = {'$ref': '#/refs/colorLAB'} _rootschema = Root._schema def __init__(self, a=Undefined, b=Undefined, l=Undefined, **kwds): super(colorLAB, self).__init__(a=a, b=b, l=l, **kwds) class colorHCL(SchemaBase): """colorHCL schema wrapper Attributes ---------- h : numberValue c : numberValue l : numberValue """ _schema = {'$ref': '#/refs/colorHCL'} _rootschema = Root._schema def __init__(self, c=Undefined, h=Undefined, l=Undefined, **kwds): super(colorHCL, self).__init__(c=c, h=h, l=l, **kwds) class colorValue(SchemaBase): """colorValue schema wrapper""" _schema = {'$ref': '#/refs/colorValue'} _rootschema = Root._schema def __init__(self, *args, **kwds): super(colorValue, self).__init__(*args, **kwds) class expr(SchemaBase): """expr schema wrapper Attributes ---------- expr : string """ _schema = {'$ref': '#/refs/expr'} _rootschema = Root._schema def __init__(self, expr=Undefined, **kwds): super(expr, self).__init__(expr=expr, **kwds) class exprString(SchemaBase): """exprString schema wrapper""" _schema = {'$ref': '#/refs/exprString'} _rootschema = Root._schema def __init__(self, *args): super(exprString, self).__init__(*args) class compare(SchemaBase): """compare schema wrapper""" _schema = {'$ref': '#/refs/compare'} _rootschema = Root._schema def __init__(self, *args, **kwds): super(compare, self).__init__(*args, **kwds) class from_(SchemaBase): """from_ schema wrapper Attributes ---------- data : string """ _schema = {'$ref': '#/refs/from'} _rootschema = Root._schema def __init__(self, data=Undefined, **kwds): super(from_, self).__init__(data=data, **kwds) class facet(SchemaBase): """facet schema wrapper Attributes ---------- data : string facet : oneOf(mapping, mapping) """ _schema = {'$ref': '#/refs/facet'} _rootschema = Root._schema def __init__(self, facet=Undefined, data=Undefined, **kwds): super(facet, self).__init__(facet=facet, data=data, **kwds) class style(SchemaBase): """style schema wrapper""" _schema = {'$ref': '#/refs/style'} _rootschema = Root._schema def __init__(self, *args, **kwds): super(style, self).__init__(*args, **kwds) class marktype(SchemaBase): """marktype schema wrapper""" _schema = {'$ref': '#/refs/marktype'} _rootschema = Root._schema def __init__(self, *args): super(marktype, self).__init__(*args) class sortOrder(SchemaBase): """sortOrder schema wrapper""" _schema = {'$ref': '#/refs/sortOrder'} _rootschema = Root._schema def __init__(self, *args, **kwds): super(sortOrder, self).__init__(*args, **kwds) class scaleField(SchemaBase): """scaleField schema wrapper""" _schema = {'$ref': '#/refs/scaleField'} _rootschema = Root._schema def __init__(self, *args, **kwds): super(scaleField, self).__init__(*args, **kwds) class scaleInterpolate(SchemaBase): """scaleInterpolate schema wrapper""" _schema = {'$ref': '#/refs/scaleInterpolate'} _rootschema = Root._schema def __init__(self, *args, **kwds): super(scaleInterpolate, self).__init__(*args, **kwds) class scaleData(SchemaBase): """scaleData schema wrapper""" _schema = {'$ref': '#/refs/scaleData'} _rootschema = Root._schema def __init__(self, *args, **kwds): super(scaleData, self).__init__(*args, **kwds) class selector(SchemaBase): """selector schema wrapper""" _schema = {'$ref': '#/refs/selector'} _rootschema = Root._schema def __init__(self, *args): super(selector, self).__init__(*args) class signal(SchemaBase): """signal schema wrapper Attributes ---------- signal : string """ _schema = {'$ref': '#/refs/signal'} _rootschema = Root._schema def __init__(self, signal=Undefined, **kwds): super(signal, self).__init__(signal=signal, **kwds) class booleanOrSignal(SchemaBase): """booleanOrSignal schema wrapper""" _schema = {'$ref': '#/refs/booleanOrSignal'} _rootschema = Root._schema def __init__(self, *args, **kwds): super(booleanOrSignal, self).__init__(*args, **kwds) class numberOrSignal(SchemaBase): """numberOrSignal schema wrapper""" _schema = {'$ref': '#/refs/numberOrSignal'} _rootschema = Root._schema def __init__(self, *args, **kwds): super(numberOrSignal, self).__init__(*args, **kwds) class stringOrSignal(SchemaBase): """stringOrSignal schema wrapper""" _schema = {'$ref': '#/refs/stringOrSignal'} _rootschema = Root._schema def __init__(self, *args, **kwds): super(stringOrSignal, self).__init__(*args, **kwds)
#!/usr/bin/env python """Django's command-line utility for administrative tasks.""" import os import sys def main(): os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'hakathon.settings') try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv) if __name__ == '__main__': main()
import os import sys import pickle import argparse import numpy as np import yaml import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from torch.utils.data import DataLoader, Subset from torchvision import datasets, transforms # from torch.optim.lr_scheduler import StepLR from models.BaseModel import BaseModel # from models.LogisticRegression import SKLRModel from models.LR import LRModel from models.LDA import LDAModel from models.PCA import PCAModel from models.SVM import SVMModel from models.LRRidge import LRRidgeModel from models.LRLasso import LRLassoModel from models.LeNet5 import LeNet5 from models.CNN import CNNModel from models.GAN import GAN from models.GMM import GMMModel class dict2obj(dict): def __init__(self, d, default=None): self.__d = d self.__default = default super(self.__class__, self).__init__(d) def __getattr__(self, k): if k in self.__d: v = self.__d[k] if isinstance(v, dict): v = self.__class__(v) setattr(self, k, v) return v else: raise KeyError def get_dataset(batch_size: int, test_batch_size: int, train_set_size: int, shuffle: bool=True): if not os.path.exists('./data/'): os.mkdir('./data/') split_location = './data/mnist_train_split_%d.pl' % train_set_size if os.path.exists(split_location): with open(split_location, 'rb') as f: split_set: np.ndarray = pickle.load(f) else: import warnings warnings.warn('Creating MNIST Training Subset') import random mnist_trainset_index = list(range(60000)) if 0 < train_set_size < 60000: split_set = np.array(random.choices(mnist_trainset_index, k=train_set_size)) with open(split_location, 'wb') as f: pickle.dump(split_set, f) else: print('Using the whole training set') split_set = mnist_trainset_index transform = transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.5,), (0.5,))]) train_dataset = datasets.MNIST('./data', train=True, download=False, transform=transform) train_dataset.data = train_dataset.data[split_set] train_dataset.targets = train_dataset.targets[split_set] train_loader = DataLoader(train_dataset, batch_size=batch_size, shuffle=shuffle) test_loader = DataLoader( datasets.MNIST('./data', train=False, transform=transform), batch_size=test_batch_size, shuffle=False) return train_loader, test_loader if __name__ == "__main__": pass args = sys.argv assert args[1] in ('train', 'debug') if args[1] == 'train' or args[1] == 'debug': yaml_path = args[2] assert os.path.exists(yaml_path) with open(yaml_path, 'r') as f: configs = yaml.load(f, Loader=yaml.SafeLoader) print(configs) configs = dict2obj(configs) else: exit() use_cuda = configs['model']['use_cuda'] and torch.cuda.is_available() configs.device = torch.device("cuda" if use_cuda else "cpu") torch.manual_seed(configs.train.seed) shuffle = 'GAN' not in configs.model.model_name train_loader, test_loader = get_dataset(configs.train.batch_size, configs.train.test_batch_size, configs.train.subset_size, shuffle) model_abs :BaseModel = globals()[configs.model.model_name] if args[1] == 'debug': configs.model.model_name = '' else: configs.model.model_name = configs.model.log_name model = model_abs(configs) # model = LRModel('NNLogisticRegression', lr=1e-1, device=device).to(device) # model = SKLRModel('', lr=1e-1, device=device).to(device) # model = LDAModel('', lr=2e-1, device=device).to(device) # model = SVMModel('', lr=2e-1, device=device).to(device) # model = LRRidgeModel('NN+LR+Ridge', lr=1e-1, device=device).to(device) # model = LeNet5('LeNet5', lr=1e-3, device=device).to(device) # print(train_loader.dataset.data.shape) # print(test_loader.dataset.data.shape) model.run_epochs(epochs=configs.train.epochs, train_loader=train_loader, test_loader=test_loader) # if len(configs.model.save_path) > 0: # torch.save(model.state_dict(), configs.model.save_path)
import cv2 img = cv2.imread("image.jpg") gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) edges = cv2.Canny(gray, 100, 200, 3) cv2.imwrite("canny_edges.jpg", edges) cv2.imshow("canny_edges", edges)
/* @(#)s_ilogb.c 5.1 93/09/24 */ /* * ==================================================== * Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved. * * Developed at SunPro, a Sun Microsystems, Inc. business. * Permission to use, copy, modify, and distribute this * software is freely granted, provided that this notice * is preserved. * ==================================================== */ #include <sys/cdefs.h> __FBSDID("$FreeBSD: src/lib/msun/src/s_ilogb.c,v 1.10.2.1.6.1 2010/12/21 17:09:25 kensmith Exp $"); /* ilogb(double x) * return the binary exponent of non-zero x * ilogb(0) = FP_ILOGB0 * ilogb(NaN) = FP_ILOGBNAN (no signal is raised) * ilogb(inf) = INT_MAX (no signal is raised) */ #include <limits.h> #include "math.h" #include "math_private.h" int ilogb(double x) { int32_t hx,lx,ix; EXTRACT_WORDS(hx,lx,x); hx &= 0x7fffffff; if(hx<0x00100000) { if((hx|lx)==0) return FP_ILOGB0; else /* subnormal x */ if(hx==0) { for (ix = -1043; lx>0; lx<<=1) ix -=1; } else { for (ix = -1022,hx<<=11; hx>0; hx<<=1) ix -=1; } return ix; } else if (hx<0x7ff00000) return (hx>>20)-1023; else if (hx>0x7ff00000 || lx!=0) return FP_ILOGBNAN; else return INT_MAX; }
""" Django settings for mute_butterfly_29508 project. Generated by 'django-admin startproject' using Django 2.2.2. For more information on this file, see https://docs.djangoproject.com/en/2.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.2/ref/settings/ """ import os import environ import logging from modules.manifest import get_modules env = environ.Env() # SECURITY WARNING: don't run with debug turned on in production! DEBUG = env.bool("DEBUG", default=False) # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = env.str("SECRET_KEY") ALLOWED_HOSTS = env.list("HOST", default=["*"]) SITE_ID = 1 SECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTO", "https") SECURE_SSL_REDIRECT = env.bool("SECURE_REDIRECT", default=False) # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites' ] LOCAL_APPS = [ 'home', 'users.apps.UsersConfig', ] THIRD_PARTY_APPS = [ 'rest_framework', 'rest_framework.authtoken', 'rest_auth', 'rest_auth.registration', 'bootstrap4', 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.google', 'django_extensions', 'drf_yasg', 'storages', ] MODULES_APPS = get_modules() INSTALLED_APPS += LOCAL_APPS + THIRD_PARTY_APPS + MODULES_APPS MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'mute_butterfly_29508.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'web_build')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'mute_butterfly_29508.wsgi.application' # Database # https://docs.djangoproject.com/en/2.2/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } if env.str("DATABASE_URL", default=None): DATABASES = { 'default': env.db() } # Password validation # https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/2.2/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/2.2/howto/static-files/ STATIC_URL = '/static/' MIDDLEWARE += ['whitenoise.middleware.WhiteNoiseMiddleware'] AUTHENTICATION_BACKENDS = ( 'django.contrib.auth.backends.ModelBackend', 'allauth.account.auth_backends.AuthenticationBackend' ) STATIC_ROOT = os.path.join(BASE_DIR, "staticfiles") STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static'), os.path.join(BASE_DIR, 'web_build/static')] STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' # allauth / users ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_AUTHENTICATION_METHOD = 'email' ACCOUNT_USERNAME_REQUIRED = False ACCOUNT_EMAIL_VERIFICATION = "optional" ACCOUNT_CONFIRM_EMAIL_ON_GET = True ACCOUNT_LOGIN_ON_EMAIL_CONFIRMATION = True ACCOUNT_UNIQUE_EMAIL = True LOGIN_REDIRECT_URL = "users:redirect" ACCOUNT_ADAPTER = "users.adapters.AccountAdapter" SOCIALACCOUNT_ADAPTER = "users.adapters.SocialAccountAdapter" ACCOUNT_ALLOW_REGISTRATION = env.bool("ACCOUNT_ALLOW_REGISTRATION", True) SOCIALACCOUNT_ALLOW_REGISTRATION = env.bool("SOCIALACCOUNT_ALLOW_REGISTRATION", True) REST_AUTH_SERIALIZERS = { # Replace password reset serializer to fix 500 error "PASSWORD_RESET_SERIALIZER": "home.api.v1.serializers.PasswordSerializer", } REST_AUTH_REGISTER_SERIALIZERS = { # Use custom serializer that has no username and matches web signup "REGISTER_SERIALIZER": "home.api.v1.serializers.SignupSerializer", } # Custom user model AUTH_USER_MODEL = "users.User" EMAIL_HOST = env.str("EMAIL_HOST", "smtp.sendgrid.net") EMAIL_HOST_USER = env.str("SENDGRID_USERNAME", "") EMAIL_HOST_PASSWORD = env.str("SENDGRID_PASSWORD", "") EMAIL_PORT = 587 EMAIL_USE_TLS = True # AWS S3 config AWS_ACCESS_KEY_ID = env.str("AWS_ACCESS_KEY_ID", "") AWS_SECRET_ACCESS_KEY = env.str("AWS_SECRET_ACCESS_KEY", "") AWS_STORAGE_BUCKET_NAME = env.str("AWS_STORAGE_BUCKET_NAME", "") AWS_STORAGE_REGION = env.str("AWS_STORAGE_REGION", "") USE_S3 = ( AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY and AWS_STORAGE_BUCKET_NAME and AWS_STORAGE_REGION ) if USE_S3: AWS_S3_CUSTOM_DOMAIN = env.str("AWS_S3_CUSTOM_DOMAIN", "") AWS_S3_OBJECT_PARAMETERS = {"CacheControl": "max-age=86400"} AWS_DEFAULT_ACL = env.str("AWS_DEFAULT_ACL", "public-read") AWS_MEDIA_LOCATION = env.str("AWS_MEDIA_LOCATION", "media") AWS_AUTO_CREATE_BUCKET = env.bool("AWS_AUTO_CREATE_BUCKET", True) DEFAULT_FILE_STORAGE = env.str( "DEFAULT_FILE_STORAGE", "home.storage_backends.MediaStorage" ) MEDIA_URL = '/mediafiles/' MEDIA_ROOT = os.path.join(BASE_DIR, 'mediafiles') # Swagger settings for api docs SWAGGER_SETTINGS = { "DEFAULT_INFO": f"{ROOT_URLCONF}.api_info", } if DEBUG or not (EMAIL_HOST_USER and EMAIL_HOST_PASSWORD): # output email to console instead of sending if not DEBUG: logging.warning("You should setup `SENDGRID_USERNAME` and `SENDGRID_PASSWORD` env vars to send emails.") EMAIL_BACKEND = "django.core.mail.backends.console.EmailBackend"
import Vue from 'vue' import App from './App.vue' import 'phoenix-styles/less/phoenix-styles.less' // 第一种:全局引入 import SwanUI from 'swan-ui' Vue.use(SwanUI) //第二种:按需引入 // import {Button,Image,ImageList} from 'swan-ui' // Vue.component(Button.name,Button) // Vue.component(Image.name,Image) // Vue.component(ImageList.name,ImageList) //第三种:按需引入 // import Button from 'swan-ui/lib/Button' // import Image from 'swan-ui/lib/Image' // import ImageList from 'swan-ui/lib/ImageList' // Vue.component(Button.name,Button) // Vue.component(Image.name,Image) // Vue.component(ImageList.name,ImageList) //第四种:App.vue中局部注册 new Vue({ el: '#app', render: h => h(App) })
var utils = require('./utils'); var tableLayout = require('./layout-manager'); var _ = require('lodash'); function Table(options){ this.options = utils.mergeOptions(options); } Table.prototype.__proto__ = Array.prototype; Table.prototype.toString = function(){ var array = this; var headersPresent = this.options.head && this.options.head.length; if(headersPresent){ array = [this.options.head]; if(this.length){ array.push.apply(array,this); } } else { this.options.style.head=[]; } var cells = tableLayout.makeTableLayout(array); _.forEach(cells,function(row){ _.forEach(row,function(cell){ cell.mergeTableOptions(this.options,cells); },this); },this); tableLayout.computeWidths(this.options.colWidths,cells); tableLayout.computeHeights(this.options.rowHeights,cells); _.forEach(cells,function(row,rowIndex){ _.forEach(row,function(cell,cellIndex){ cell.init(this.options); },this); },this); var result = []; for(var rowIndex = 0; rowIndex < cells.length; rowIndex++){ var row = cells[rowIndex]; var heightOfRow = this.options.rowHeights[rowIndex]; if(rowIndex === 0 || !this.options.style.compact || (rowIndex == 1 && headersPresent)){ doDraw(row,'top',result); } for(var lineNum = 0; lineNum < heightOfRow; lineNum++){ doDraw(row,lineNum,result); } if(rowIndex + 1 == cells.length){ doDraw(row,'bottom',result); } } return result.join('\n'); }; function doDraw(row,lineNum,result){ var line = []; _.forEach(row,function(cell){ line.push(cell.draw(lineNum)); }); var str = line.join(''); if(str.length) result.push(str); } Table.prototype.__defineGetter__('width', function (){ var str = this.toString().split("\n"); return str[0].length; }); module.exports = Table;
"use strict"; var Backbone = require("backbone").noConflict(); Backbone._ = require("lodash"); module.exports = Backbone; // ---------------------------------------------------------------------------- // Copyright (C) 2015 Bloomberg Finance L.P. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // ----------------------------- END-OF-FILE ----------------------------------
// // ZYBTPrinterTool.h // JuniuHD // // Created by ZYSu on 2016/12/6. // Copyright © 2016年 ZYSu. All rights reserved. // 蓝牙4.0通用 #import <Foundation/Foundation.h> #import "ZYPrinterProtocol.h" @interface ZYBTPrinterTool : NSObject<ZYPrinterProtocol> @end
/* http://keith-wood.name/keypad.html Keypad field entry extension for jQuery v1.4.2. Written by Keith Wood (kbwood{at}iinet.com.au) August 2008. Dual licensed under the GPL (http://dev.jquery.com/browser/trunk/jquery/GPL-LICENSE.txt) and MIT (http://dev.jquery.com/browser/trunk/jquery/MIT-LICENSE.txt) licenses. Please attribute the author if you use it. */ (function($) { // hide the namespace var PROP_NAME = 'keypad'; /* Keypad manager. Use the singleton instance of this class, $.keypad, to interact with the plugin. Settings for keypad fields are maintained in instance objects, allowing multiple different settings on the same page. */ function Keypad() { this._curInst = null; // The current instance in use this._disabledFields = []; // List of keypad fields that have been disabled this._keypadShowing = false; // True if the popup panel is showing , false if not this._keyCode = 0; this._specialKeys = []; this.addKeyDef('CLOSE', 'close', function(inst) { $.keypad._curInst = (inst._inline ? inst : $.keypad._curInst); $.keypad._hideKeypad(); }); this.addKeyDef('CLEAR', 'clear', function(inst) { $.keypad._clearValue(inst); }); this.addKeyDef('BACK', 'back', function(inst) { $.keypad._backValue(inst); }); this.addKeyDef('SHIFT', 'shift', function(inst) { $.keypad._shiftKeypad(inst); }); this.addKeyDef('SPACE_BAR', 'spacebar', function(inst) { $.keypad._selectValue(inst, ' '); }, true); this.addKeyDef('SPACE', 'space'); this.addKeyDef('HALF_SPACE', 'half-space'); this.addKeyDef('ENTER', 'enter', function(inst) { $.keypad._selectValue(inst, '\x0D'); }, true); this.addKeyDef('TAB', 'tab', function(inst) { $.keypad._selectValue(inst, '\x09'); }, true); // Standard US keyboard alphabetic layout this.qwertyAlphabetic = ['qwertyuiop', 'asdfghjkl', 'zxcvbnm']; // Standard US keyboard layout this.qwertyLayout = ['!@#$%^&*()_=' + this.HALF_SPACE + this.SPACE + this.CLOSE, this.HALF_SPACE + '`~[]{}<>\\|/' + this.SPACE + '789', 'qwertyuiop\'"' + this.HALF_SPACE + '456', this.HALF_SPACE + 'asdfghjkl;:' + this.SPACE + '123', this.SPACE + 'zxcvbnm,.?' + this.SPACE + this.HALF_SPACE + '-0+', '' + this.TAB + this.ENTER + this.SPACE_BAR + this.SHIFT + this.HALF_SPACE + this.BACK + this.CLEAR]; this.regional = []; // Available regional settings, indexed by language code this.regional[''] = { // Default regional settings buttonText: '...', // Display text for trigger button buttonStatus: 'Open the keypad', // Status text for trigger button closeText: 'Close', // Display text for close link closeStatus: 'Close the keypad', // Status text for close link clearText: 'Clear', // Display text for clear link clearStatus: 'Erase all the text', // Status text for clear link backText: 'Back', // Display text for back link backStatus: 'Erase the previous character', // Status text for back link spacebarText: '&nbsp;', // Display text for space bar spacebarStatus: 'Space', // Status text for space bar enterText: 'Enter', // Display text for carriage return enterStatus: 'Carriage return', // Status text for carriage return tabText: '→', // Display text for tab tabStatus: 'Horizontal tab', // Status text for tab shiftText: 'Shift', // Display text for shift link shiftStatus: 'Toggle upper/lower case characters', // Status text for shift link alphabeticLayout: this.qwertyAlphabetic, // Default layout for alphabetic characters fullLayout: this.qwertyLayout, // Default layout for full keyboard isAlphabetic: this.isAlphabetic, // Function to determine if character is alphabetic isNumeric: this.isNumeric, // Function to determine if character is numeric isRTL: false // True if right-to-left language, false if left-to-right }; this._defaults = { // Global defaults for all the keypad instances showOn: 'focus', // 'focus' for popup on focus, // 'button' for trigger button, or 'both' for either buttonImage: '', // URL for trigger button image buttonImageOnly: false, // True if the image appears alone, false if it appears on a button showAnim: 'show', // Name of jQuery animation for popup showOptions: {}, // Options for enhanced animations duration: 'normal', // Duration of display/closure appendText: '', // Display text following the text field, e.g. showing the format useThemeRoller: false, // True to add ThemeRoller classes keypadClass: '', // Additional CSS class for the keypad for an instance prompt: '', // Display text at the top of the keypad layout: ['123' + this.CLOSE, '456' + this.CLEAR, '789' + this.BACK, this.SPACE + '0'], // Layout of keys separator: '', // Separator character between keys target: null, // Input target for an inline keypad keypadOnly: true, // True for entry only via the keypad, false for real keyboard too randomiseAlphabetic: false, // True to randomise the alphabetic key positions, false to keep in order randomiseNumeric: false, // True to randomise the numeric key positions, false to keep in order randomiseOther: false, // True to randomise the other key positions, false to keep in order randomiseAll: false, // True to randomise all key positions, false to keep in order beforeShow: null, // Callback before showing the keypad onKeypress: null, // Callback when a key is selected onClose: null // Callback when the panel is closed }; $.extend(this._defaults, this.regional['']); this.mainDiv = $('<div class="' + this._mainDivClass + '" style="display: none;"></div>'); } $.extend(Keypad.prototype, { /* Class name added to elements to indicate already configured with keypad. */ markerClassName: 'hasKeypad', _mainDivClass: 'keypad-popup', // The name of the main keypad division class _inlineClass: 'keypad-inline', // The name of the inline marker class _appendClass: 'keypad-append', // The name of the append marker class _triggerClass: 'keypad-trigger', // The name of the trigger marker class _disableClass: 'keypad-disabled', // The name of the disabled covering marker class _inlineEntryClass: 'keypad-keyentry', // The name of the inline entry marker class _coverClass: 'keypad-cover', // The name of the IE select cover marker class /* Override the default settings for all instances of keypad. @param settings (object) the new settings to use as defaults @return (object) the manager object */ setDefaults: function(settings) { extendRemove(this._defaults, settings || {}); return this; }, /* Add the definition of a special key. @param id (string) the identifier for this key - access via $.keypad.<id> @param name (string) the prefix for localisation strings and the suffix for a class name @param action (function) the action performed for this key - receives inst as a parameter @param noHighlight (boolean) true to suppress highlight when using ThemeRoller @return (object) the manager object */ addKeyDef: function(id, name, action, noHighlight) { if (this._keyCode == 32) { throw 'Only 32 special keys allowed'; } this[id] = String.fromCharCode(this._keyCode++); this._specialKeys.push({code: this[id], id: id, name: name, action: action, noHighlight: noHighlight}); return this; }, /* Attach the keypad to a jQuery selection. @param target (element) the target control @param settings (object) the new settings to use for this instance */ _attachKeypad: function(target, settings) { var inline = (target.nodeName.toLowerCase() != 'input' && target.nodeName.toLowerCase() != 'textarea'); var inst = {_inline: inline, _mainDiv: (inline ? $('<div class="' + this._inlineClass + '"></div>') : $.keypad.mainDiv), ucase: false}; inst.settings = $.extend({}, settings || {}); this._setInput(target, inst); this._connectKeypad(target, inst); if (inline) { $(target).append(inst._mainDiv). bind('click.keypad', function() { inst._input.focus(); }); this._updateKeypad(inst); } else if ($(target).is(':disabled')) { this._disableKeypad(target); } }, /* Determine the input field for the keypad. @param target (jQuery) the target control @param inst (object) the instance settings */ _setInput: function(target, inst) { inst._input = $(!inst._inline ? target : this._get(inst, 'target') || '<input type="text" class="' + this._inlineEntryClass + '" disabled="disabled"/>'); if (inst._inline) { target = $(target); target.find('input').remove(); if (!this._get(inst, 'target')) { target.append(inst._input); } } }, /* Attach the keypad to a text field. @param target (element) the target text field @param inst (object) the instance settings */ _connectKeypad: function(target, inst) { var field = $(target); if (field.hasClass(this.markerClassName)) { return; } var appendText = this._get(inst, 'appendText'); var isRTL = this._get(inst, 'isRTL'); if (appendText) { field[isRTL ? 'before' : 'after']( '<span class="' + this._appendClass + '">' + appendText + '</span>'); } if (!inst._inline) { var showOn = this._get(inst, 'showOn'); if (showOn == 'focus' || showOn == 'both') { // pop-up keypad when in the marked field field.focus(this._showKeypad).keydown(this._doKeyDown); } if (showOn == 'button' || showOn == 'both') { // pop-up keypad when button clicked var buttonText = this._get(inst, 'buttonText'); var buttonStatus = this._get(inst, 'buttonStatus'); var buttonImage = this._get(inst, 'buttonImage'); var trigger = $(this._get(inst, 'buttonImageOnly') ? $('<img src="' + buttonImage + '" alt="' + buttonStatus + '" title="' + buttonStatus + '"/>') : $('<button type="button" title="' + buttonStatus + '"></button>'). html(buttonImage == '' ? buttonText : $('<img src="' + buttonImage + '" alt="' + buttonStatus + '" title="' + buttonStatus + '"/>'))); field[isRTL ? 'before' : 'after'](trigger); trigger.addClass(this._triggerClass).click(function() { if ($.keypad._keypadShowing && $.keypad._lastField == target) { $.keypad._hideKeypad(); } else { $.keypad._showKeypad(target); } return false; }); } } inst.saveReadonly = field.attr('readonly'); field.addClass(this.markerClassName) [this._get(inst, 'keypadOnly') ? 'attr' : 'removeAttr']('readonly', true). bind('setData.keypad', function(event, key, value) { inst.settings[key] = value; }).bind('getData.keypad', function(event, key) { return this._get(inst, key); }); $.data(target, PROP_NAME, inst); }, /* Detach keypad from its control. @param target (element) the target text field */ _destroyKeypad: function(target) { var $target = $(target); if (!$target.hasClass(this.markerClassName)) { return; } var inst = $.data(target, PROP_NAME); if (this._curInst == inst) { this._hideKeypad(); } $target.siblings('.' + this._appendClass).remove().end(). siblings('.' + this._triggerClass).remove().end(). prev('.' + this._inlineEntryClass).remove(); $target.empty().unbind('focus', this._showKeypad). removeClass(this.markerClassName) [inst.saveReadonly ? 'attr' : 'removeAttr']('readonly', true); $.removeData(inst._input[0], PROP_NAME); $.removeData(target, PROP_NAME); }, /* Enable the keypad for a jQuery selection. @param target (element) the target text field */ _enableKeypad: function(target) { var control = $(target); if (!control.hasClass(this.markerClassName)) { return; } var nodeName = target.nodeName.toLowerCase(); if (nodeName == 'input' || nodeName == 'textarea') { target.disabled = false; control.siblings('button.' + this._triggerClass). each(function() { this.disabled = false; }).end(). siblings('img.' + this._triggerClass). css({opacity: '1.0', cursor: ''}); } else if (nodeName == 'div' || nodeName == 'span') { control.children('.' + this._disableClass).remove(); var inst = $.data(target, PROP_NAME); inst._mainDiv.find('button').attr('disabled', ''); } this._disabledFields = $.map(this._disabledFields, function(value) { return (value == target ? null : value); }); // delete entry }, /* Disable the keypad for a jQuery selection. @param target (element) the target text field */ _disableKeypad: function(target) { var control = $(target); if (!control.hasClass(this.markerClassName)) { return; } var nodeName = target.nodeName.toLowerCase(); if (nodeName == 'input' || nodeName == 'textarea') { target.disabled = true; control.siblings('button.' + this._triggerClass). each(function() { this.disabled = true; }).end(). siblings('img.' + this._triggerClass). css({opacity: '0.5', cursor: 'default'}); } else if (nodeName == 'div' || nodeName == 'span') { var inline = control.children('.' + this._inlineClass); var offset = inline.offset(); var relOffset = {left: 0, top: 0}; inline.parents().each(function() { if ($(this).css('position') == 'relative') { relOffset = $(this).offset(); return false; } }); control.prepend('<div class="' + this._disableClass + '" style="width: ' + inline.outerWidth() + 'px; height: ' + inline.outerHeight() + 'px; left: ' + (offset.left - relOffset.left) + 'px; top: ' + (offset.top - relOffset.top) + 'px;"></div>'); var inst = $.data(target, PROP_NAME); inst._mainDiv.find('button').attr('disabled', 'disabled'); } this._disabledFields = $.map(this._disabledFields, function(value) { return (value == target ? null : value); }); // delete entry this._disabledFields[this._disabledFields.length] = target; }, /* Is the text field disabled as a keypad? @param target (element) the target text field @return (boolean) true if disabled, false if enabled */ _isDisabledKeypad: function(target) { return (target && $.inArray(target, this._disabledFields) > -1); }, /* Update the settings for keypad attached to a text field @param target (element) the target text field @param name (object) the new settings to update or (string) the name of the setting to change @param value (any) the new value for the setting (omit if above is an object) */ _changeKeypad: function(target, name, value) { var settings = name || {}; if (typeof name == 'string') { settings = {}; settings[name] = value; } var inst = $.data(target, PROP_NAME); if (inst) { if (this._curInst == inst) { this._hideKeypad(); } extendRemove(inst.settings, settings); this._setInput($(target), inst); this._updateKeypad(inst); } }, /* Pop-up the keypad for a given text field. @param field (element) the text field attached to the keypad or (event) if triggered by focus */ _showKeypad: function(field) { field = field.target || field; if ($.keypad._isDisabledKeypad(field) || $.keypad._lastField == field) { // already here return; } var inst = $.data(field, PROP_NAME); $.keypad._hideKeypad(null, ''); $.keypad._lastField = field; $.keypad._pos = $.keypad._findPos(field); $.keypad._pos[1] += field.offsetHeight; // add the height var isFixed = false; $(field).parents().each(function() { isFixed |= $(this).css('position') == 'fixed'; return !isFixed; }); if (isFixed && $.browser.opera) { // correction for Opera when fixed and scrolled $.keypad._pos[0] -= document.documentElement.scrollLeft; $.keypad._pos[1] -= document.documentElement.scrollTop; } var offset = {left: $.keypad._pos[0], top: $.keypad._pos[1]}; $.keypad._pos = null; // determine sizing offscreen inst._mainDiv.css({position: 'absolute', display: 'block', top: '-1000px', width: ($.browser.opera ? '1000px' : 'auto')}); $.keypad._updateKeypad(inst); // and adjust position before showing offset = $.keypad._checkOffset(inst, offset, isFixed); inst._mainDiv.css({position: (isFixed ? 'fixed' : 'absolute'), display: 'none', left: offset.left + 'px', top: offset.top + 'px'}); var showAnim = $.keypad._get(inst, 'showAnim'); var duration = $.keypad._get(inst, 'duration'); duration = (duration == 'normal' && $.ui && $.ui.version >= '1.8' ? '_default' : duration); var postProcess = function() { $.keypad._keypadShowing = true; var borders = $.keypad._getBorders(inst._mainDiv); inst._mainDiv.find('iframe.' + $.keypad._coverClass). // IE6- only css({left: -borders[0], top: -borders[1], width: inst._mainDiv.outerWidth(), height: inst._mainDiv.outerHeight()}); }; if ($.effects && $.effects[showAnim]) { var data = inst._mainDiv.data(); // Update old effects data for (var key in data) { if (key.match(/^ec\.storage\./)) { data[key] = inst._mainDiv.css(key.replace(/ec\.storage\./, '')); } } inst._mainDiv.data(data).show(showAnim, $.keypad._get(inst, 'showOptions'), duration, postProcess); } else { inst._mainDiv[showAnim || 'show']((showAnim ? duration : ''), postProcess); } if (!showAnim) { postProcess(); } if (inst._input[0].type != 'hidden') { inst._input[0].focus(); } $.keypad._curInst = inst; }, /* Generate the keypad content. @param inst (object) the instance settings */ _updateKeypad: function(inst) { var borders = this._getBorders(inst._mainDiv); inst._mainDiv.empty().append(this._generateHTML(inst)). find('iframe.' + this._coverClass). // IE6- only css({left: -borders[0], top: -borders[1], width: inst._mainDiv.outerWidth(), height: inst._mainDiv.outerHeight()}); inst._mainDiv.removeClass().addClass(this._get(inst, 'keypadClass') + (this._get(inst, 'useThemeRoller') ? ' ui-widget ui-widget-content' : '') + (this._get(inst, 'isRTL') ? ' keypad-rtl' : '') + ' ' + (inst._inline ? this._inlineClass : this._mainDivClass)); var beforeShow = this._get(inst, 'beforeShow'); if (beforeShow) { beforeShow.apply((inst._input ? inst._input[0] : null), [inst._mainDiv, inst]); } }, /* Retrieve the size of left and top borders for an element. @param elem (jQuery object) the element of interest @return (number[2]) the left and top borders */ _getBorders: function(elem) { var convert = function(value) { var extra = ($.browser.msie ? 1 : 0); return {thin: 1 + extra, medium: 3 + extra, thick: 5 + extra}[value] || value; }; return [parseFloat(convert(elem.css('border-left-width'))), parseFloat(convert(elem.css('border-top-width')))]; }, /* Check positioning to remain on screen. @param inst (object) the instance settings @param offset (object) the current offset @param isFixed (boolean) true if the text field is fixed in position @return (object) the updated offset */ _checkOffset: function(inst, offset, isFixed) { var pos = inst._input ? this._findPos(inst._input[0]) : null; var browserWidth = window.innerWidth || document.documentElement.clientWidth; var browserHeight = window.innerHeight || document.documentElement.clientHeight; var scrollX = document.documentElement.scrollLeft || document.body.scrollLeft; var scrollY = document.documentElement.scrollTop || document.body.scrollTop; if (($.browser.msie && parseInt($.browser.version, 10) < 7) || $.browser.opera) { // recalculate width as otherwise set to 100% var width = 0; inst._mainDiv.find(':not(div,iframe)').each(function() { width = Math.max(width, this.offsetLeft + $(this).outerWidth() + parseInt($(this).css('margin-right'), 10)); }); inst._mainDiv.css('width', width); } // reposition keypad panel horizontally if outside the browser window if (this._get(inst, 'isRTL') || (offset.left + inst._mainDiv.outerWidth() - scrollX) > browserWidth) { offset.left = Math.max((isFixed ? 0 : scrollX), pos[0] + (inst._input ? inst._input.outerWidth() : 0) - (isFixed ? scrollX : 0) - inst._mainDiv.outerWidth() - (isFixed && $.browser.opera ? document.documentElement.scrollLeft : 0)); } else { offset.left -= (isFixed ? scrollX : 0); } // reposition keypad panel vertically if outside the browser window if ((offset.top + inst._mainDiv.outerHeight() - scrollY) > browserHeight) { offset.top = Math.max((isFixed ? 0 : scrollY), pos[1] - (isFixed ? scrollY : 0) - inst._mainDiv.outerHeight() - (isFixed && $.browser.opera ? document.documentElement.scrollTop : 0)); } else { offset.top -= (isFixed ? scrollY : 0); } return offset; }, /* Find an object's position on the screen. @param obj (element) the element to find the position for @return (int[2]) the element's position */ _findPos: function(obj) { while (obj && (obj.type == 'hidden' || obj.nodeType != 1)) { obj = obj.nextSibling; } var position = $(obj).offset(); return [position.left, position.top]; }, /* Hide the keypad from view. @param field (element) the text field attached to the keypad @param duration (string) the duration over which to close the keypad */ _hideKeypad: function(field, duration) { var inst = this._curInst; if (!inst || (field && inst != $.data(field, PROP_NAME))) { return; } if (this._keypadShowing) { duration = (duration != null ? duration : this._get(inst, 'duration')); duration = (duration == 'normal' && $.ui && $.ui.version >= '1.8' ? '_default' : duration); var showAnim = this._get(inst, 'showAnim'); if ($.effects && $.effects[showAnim]) { inst._mainDiv.hide(showAnim, this._get(inst, 'showOptions'), duration); } else { inst._mainDiv[(showAnim == 'slideDown' ? 'slideUp' : (showAnim == 'fadeIn' ? 'fadeOut' : 'hide'))](showAnim ? duration : ''); } } var onClose = this._get(inst, 'onClose'); if (onClose) { onClose.apply((inst._input ? inst._input[0] : null), // trigger custom callback [inst._input.val(), inst]); } if (this._keypadShowing) { this._keypadShowing = false; this._lastField = null; } if (inst._inline) { inst._input.val(''); } this._curInst = null; }, /* Handle keystrokes. @param e (event) the key event */ _doKeyDown: function(e) { if (e.keyCode == 9) { // Tab out $.keypad.mainDiv.stop(true, true); $.keypad._hideKeypad(); } }, /* Close keypad if clicked elsewhere. @param event (event) the mouseclick details */ _checkExternalClick: function(event) { if (!$.keypad._curInst) { return; } var target = $(event.target); if (!target.parents().andSelf().is('.' + $.keypad._mainDivClass) && !target.hasClass($.keypad.markerClassName) && !target.parents().andSelf().hasClass($.keypad._triggerClass) && $.keypad._keypadShowing) { $.keypad._hideKeypad(); } }, /* Toggle between upper and lower case. @param inst (object) the instance settings */ _shiftKeypad: function(inst) { inst.ucase = !inst.ucase; this._updateKeypad(inst); inst._input.focus(); // for further typing }, /* Erase the text field. @param inst (object) the instance settings */ _clearValue: function(inst) { this._setValue(inst, '', 0); this._notifyKeypress(inst, $.keypad.DEL); }, /* Erase the last character. @param inst (object) the instance settings */ _backValue: function(inst) { var field = inst._input[0]; var value = inst._input.val(); var range = [value.length, value.length]; if (field.setSelectionRange) { // Mozilla range = (inst._input.attr('readonly') || inst._input.attr('disabled') ? range : [field.selectionStart, field.selectionEnd]); } else if (field.createTextRange) { // IE range = (inst._input.attr('readonly') || inst._input.attr('disabled') ? range : this._getIERange(field)); } this._setValue(inst, (value.length == 0 ? '' : value.substr(0, range[0] - 1) + value.substr(range[1])), range[0] - 1); this._notifyKeypress(inst, $.keypad.BS); }, /* Update the text field with the selected value. @param inst (object) the instance settings @param value (string) the new character to add */ _selectValue: function(inst, value) { this.insertValue(inst._input[0], value); this._setValue(inst, inst._input.val()); this._notifyKeypress(inst, value); }, /* Update the text field with the selected value. @param input (element) the input field or (jQuery) jQuery collection @param value (string) the new character to add */ insertValue: function(input, value) { input = (input.jquery ? input : $(input)); var field = input[0]; var newValue = input.val(); var range = [newValue.length, newValue.length]; if (field.setSelectionRange) { // Mozilla range = (input.attr('readonly') || input.attr('disabled') ? range : [field.selectionStart, field.selectionEnd]); } else if (field.createTextRange) { // IE range = (input.attr('readonly') || input.attr('disabled') ? range : this._getIERange(field)); } input.val(newValue.substr(0, range[0]) + value + newValue.substr(range[1])); pos = range[0] + value.length; if (input.is(':visible')) { input.focus(); // for further typing } if (field.setSelectionRange) { // Mozilla if (input.is(':visible')) { field.setSelectionRange(pos, pos); } } else if (field.createTextRange) { // IE range = field.createTextRange(); range.move('character', pos); range.select(); } }, /* Get the coordinates for the selected area in the text field in IE. @param field (element) the target text field @return (int[2]) the start and end positions of the selection */ _getIERange: function(field) { field.focus(); var selectionRange = document.selection.createRange().duplicate(); // Use two ranges: before and selection var beforeRange = this._getIETextRange(field); beforeRange.setEndPoint('EndToStart', selectionRange); // Check each range for trimmed newlines by shrinking the range by one // character and seeing if the text property has changed. If it has not // changed then we know that IE has trimmed a \r\n from the end. var checkCRLF = function(range) { var origText = range.text; var text = origText; var finished = false; while (true) { if (range.compareEndPoints('StartToEnd', range) == 0) { break; } else { range.moveEnd('character', -1); if (range.text == origText) { text += '\r\n'; } else { break; } } } return text; }; var beforeText = checkCRLF(beforeRange); var selectionText = checkCRLF(selectionRange); return [beforeText.length, beforeText.length + selectionText.length]; }, /* Create an IE text range for the text field. @param field (element) the target text field @return (object) the corresponding text range */ _getIETextRange: function(field) { var isInput = (field.nodeName.toLowerCase() == 'input'); var range = (isInput ? field.createTextRange() : document.body.createTextRange()); if (!isInput) { range.moveToElementText(field); // Selects all the text for a textarea } return range; }, /* Set the text field to the selected value, and trigger any on change event. @param inst (object) the instance settings @param value (string) the new value for the text field */ _setValue: function(inst, value) { var maxlen = inst._input.attr('maxlength'); if (maxlen > -1) { value = value.substr(0, maxlen); } inst._input.val(value); if (!this._get(inst, 'onKeypress')) { inst._input.trigger('change'); // fire the change event } }, _notifyKeypress: function(inst, key) { var onKeypress = this._get(inst, 'onKeypress'); if (onKeypress) { // trigger custom callback onKeypress.apply((inst._input ? inst._input[0] : null), [key, inst._input.val(), inst]); } }, /* Get a setting value, defaulting if necessary. @param inst (object) the instance settings @param name (string) the name of the setting @return (any) the value of the setting, or its default if not set explicitly */ _get: function(inst, name) { return inst.settings[name] !== undefined ? inst.settings[name] : this._defaults[name]; }, /* Generate the HTML for the current state of the keypad. @param inst (object) the instance settings @return (jQuery) the HTML for this keypad */ _generateHTML: function(inst) { var useTR = this._get(inst, 'useThemeRoller'); var isRTL = this._get(inst, 'isRTL'); var prompt = this._get(inst, 'prompt'); var separator = this._get(inst, 'separator'); var html = (!prompt ? '' : '<div class="keypad-prompt' + (useTR ? ' ui-widget-header ui-corner-all' : '') + '">' + prompt + '</div>'); var layout = this._randomiseLayout(inst); for (var i = 0; i < layout.length; i++) { html += '<div class="keypad-row">'; var keys = layout[i].split(separator); for (var j = 0; j < keys.length; j++) { if (inst.ucase) { keys[j] = keys[j].toUpperCase(); } var keyDef = this._specialKeys[keys[j].charCodeAt(0)]; if (keyDef) { html += (keyDef.action ? '<button type="button" class="keypad-special keypad-' + keyDef.name + (useTR ? ' ui-corner-all ui-state-default' + (keyDef.noHighlight ? '' : ' ui-state-highlight') : '') + '" title="' + this._get(inst, keyDef.name + 'Status') + '">' + (this._get(inst, keyDef.name + 'Text') || '&nbsp;') + '</button>' : '<div class="keypad-' + keyDef.name + '"></div>'); } else { html += '<button type="button" ' + 'class="keypad-key' + (useTR ? ' ui-corner-all ui-state-default' : '') + '">' + (keys[j] == ' ' ? '&nbsp;' : keys[j]) + '</button>'; } } html += '</div>'; } html += '<div style="clear: both;"></div>' + (!inst._inline && $.browser.msie && parseInt($.browser.version, 10) < 7 ? '<iframe src="javascript:false;" class="' + $.keypad._coverClass + '"></iframe>' : ''); html = $(html); var thisInst = inst; var activeClasses = 'keypad-key-down' + (useTR ? ' ui-state-active' : ''); html.find('button').mousedown(function() { $(this).addClass(activeClasses); }). mouseup(function() { $(this).removeClass(activeClasses); }). mouseout(function() { $(this).removeClass(activeClasses); }). filter('.keypad-key').click(function() { $.keypad._selectValue(thisInst, $(this).text()); }); $.each(this._specialKeys, function(i, keyDef) { html.find('.keypad-' + keyDef.name).click(function() { keyDef.action.apply(thisInst._input, [thisInst]); }); }); return html; }, /* Check whether characters should be randomised, and, if so, produce the randomised layout. @param inst (object) the instance settings @return (string[]) the layout with any requested randomisations applied */ _randomiseLayout: function(inst) { var randomiseNumeric = this._get(inst, 'randomiseNumeric'); var randomiseAlpha = this._get(inst, 'randomiseAlphabetic'); var randomiseOther = this._get(inst, 'randomiseOther'); var randomiseAll = this._get(inst, 'randomiseAll'); var layout = this._get(inst, 'layout'); if (!randomiseNumeric && !randomiseAlpha && !randomiseOther && !randomiseAll) { return layout; } var isNumeric = this._get(inst, 'isNumeric'); var isAlphabetic = this._get(inst, 'isAlphabetic'); var separator = this._get(inst, 'separator'); var numerics = []; var alphas = []; var others = []; var newLayout = []; // Find characters of different types for (var i = 0; i < layout.length; i++) { newLayout[i] = ''; var keys = layout[i].split(separator); for (var j = 0; j < keys.length; j++) { if (this._isControl(keys[j])) { continue; } if (randomiseAll) { others.push(keys[j]); } else if (isNumeric(keys[j])) { numerics.push(keys[j]); } else if (isAlphabetic(keys[j])) { alphas.push(keys[j]); } else { others.push(keys[j]); } } } // Shuffle them if (randomiseNumeric) { this._shuffle(numerics); } if (randomiseAlpha) { this._shuffle(alphas); } if (randomiseOther || randomiseAll) { this._shuffle(others); } var n = 0; var a = 0; var o = 0; // And replace them in the layout for (var i = 0; i < layout.length; i++) { var keys = layout[i].split(separator); for (var j = 0; j < keys.length; j++) { newLayout[i] += (this._isControl(keys[j]) ? keys[j] : (randomiseAll ? others[o++] : (isNumeric(keys[j]) ? numerics[n++] : (isAlphabetic(keys[j]) ? alphas[a++] : others[o++])))) + separator; } } return newLayout; }, /* Is a given character a control character? @param ch (char) the character to test @return (boolean) true if a control character, false if not */ _isControl: function(ch) { return ch < ' '; }, /* Is a given character alphabetic? @param ch (char) the character to test @return (boolean) true if alphabetic, false if not */ isAlphabetic: function(ch) { return (ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z'); }, /* Is a given character numeric? @param ch (char) the character to test @return (boolean) true if numeric, false if not */ isNumeric: function(ch) { return (ch >= '0' && ch <= '9'); }, /* Randomise the contents of an array. @param values (string[]) the array to rearrange */ _shuffle: function(values) { for (var i = values.length - 1; i > 0; i--) { var j = Math.floor(Math.random() * values.length); var ch = values[i]; values[i] = values[j]; values[j] = ch; } } }); /* jQuery extend now ignores nulls! @param target (object) the object to extend @param props (object) the new settings @return (object) the updated target */ function extendRemove(target, props) { $.extend(target, props); for (var name in props) { if (props[name] == null || props[name] == undefined) { target[name] = props[name]; } } return target; }; /* Invoke the keypad functionality. @param options (string) a command, optionally followed by additional parameters or (object) settings for attaching new keypad functionality @return (object) the jQuery object */ $.fn.keypad = function(options) { var otherArgs = Array.prototype.slice.call(arguments, 1); if (options == 'isDisabled') { return $.keypad['_' + options + 'Keypad']. apply($.keypad, [this[0]].concat(otherArgs)); } return this.each(function() { typeof options == 'string' ? $.keypad['_' + options + 'Keypad']. apply($.keypad, [this].concat(otherArgs)) : $.keypad._attachKeypad(this, options); }); }; $.keypad = new Keypad(); // singleton instance // Add the keypad division and external click check $(function() { $(document.body).append($.keypad.mainDiv). mousedown($.keypad._checkExternalClick); }); })(jQuery);
from pypy.rpython.lltypesystem.rffi import CConstant, CExternVariable, INT from pypy.rpython.lltypesystem import lltype, ll2ctypes from pypy.translator.tool.cbuild import ExternalCompilationInfo from pypy.rlib.rarithmetic import intmask class CConstantErrno(CConstant): # these accessors are used when calling get_errno() or set_errno() # on top of CPython def __getitem__(self, index): assert index == 0 try: return ll2ctypes.TLS.errno except AttributeError: raise ValueError("no C function call occurred so far, " "errno is undefined") def __setitem__(self, index, value): assert index == 0 ll2ctypes.TLS.errno = value errno_eci = ExternalCompilationInfo( includes=['errno.h'] ) _get_errno, set_errno = CExternVariable(INT, 'errno', errno_eci, CConstantErrno, sandboxsafe=True) def get_errno(): return intmask(_get_errno())
/*! Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. SPDX-License-Identifier: Apache-2.0 */ /** * @author Solution Builders */ 'use strict'; angular.module('serverlessVideoTranscode.profile', ['serverlessVideoTranscode.main', 'serverlessVideoTranscode.utils', 'serverlessVideoTranscode.factory.profile', 'serverlessVideoTranscode.service.auth' ]) .config(['$stateProvider', '$urlRouterProvider', function($stateProvider, $urlRouterProvider) { $stateProvider.state('profile', { url: '/profile', views: { '': { templateUrl: 'main/main.html', controller: 'MainCtrl' }, '@profile': { templateUrl: 'profile/profile.html', controller: 'ProfileCtrl' } }, authenticate: true, activeWithFederation: true }); }]) .controller('ProfileCtrl', function($scope, $state, $stateParams, $blockUI, authService, profileFactory) { $scope.title = ''; $scope.user = {}; $scope.profile = {}; $scope.secret = ''; $scope.awsUiAlert = {} $scope.awsUiAlert.show = false; $scope.awsUiAlert.criticalError = false; $scope.awsUiAlert.type = ""; $scope.awsUiAlert.header = ""; $scope.awsUiAlert.content = ""; $scope.showChangePassword = false; var getUserDetails = function() { $blockUI.start(); $scope.dismissAwsUiAlert(); authService.getUserInfo().then(function(result) { profileFactory.getProfile(function(err, profile) { if (err) { showErrorAlert(err.data.message, true); return; } $scope.profile = profile; $scope.user = result; $scope.showChangePassword = !FEDERATED_LOGIN; $blockUI.stop(); }); }, function(msg) { $blockUI.stop(); console.log('Unable to retrieve the user session.'); $state.go('signin', {}); }); }; $scope.closeSecretModal = function() { $scope.secret = ''; $scope.showSecretModal = false; }; $scope.changePassword = function() { $state.go('changePassword', {}); }; $scope.generateSecretKey = function() { profileFactory.getApiKey(function(err, secret) { if (err) { console.log('error', err); $blockUI.stop(); return; } $scope.secret = secret; $scope.showSecretModal = true; $blockUI.stop(); }); }; $scope.dismissAwsUiAlert = function() { $scope.awsUiAlert.show = false; $scope.awsUiAlert.criticalError = false; $scope.awsUiAlert.type = ""; $scope.awsUiAlert.header = ""; $scope.awsUiAlert.content = ""; }; var showSuccessAlert = function(message) { $scope.awsUiAlert.type = "success"; $scope.awsUiAlert.header = "Success"; $scope.awsUiAlert.content = message; $scope.awsUiAlert.show = true; $scope.awsUiAlert.criticalError = false; $blockUI.stop(); }; var showErrorAlert = function(message, critical = false) { $scope.awsUiAlert.type = "error"; $scope.awsUiAlert.header = "Error"; $scope.awsUiAlert.content = message; $scope.awsUiAlert.show = true; $scope.awsUiAlert.criticalError = critical; $blockUI.stop(); }; getUserDetails(); });
/* Copyright Statement: * * This software/firmware and related documentation ("MediaTek Software") are * protected under relevant copyright laws. The information contained herein * is confidential and proprietary to MediaTek Inc. and/or its licensors. * Without the prior written permission of MediaTek inc. and/or its licensors, * any reproduction, modification, use or disclosure of MediaTek Software, * and information contained herein, in whole or in part, shall be strictly prohibited. */ /* MediaTek Inc. (C) 2010. All rights reserved. * * BY OPENING THIS FILE, RECEIVER HEREBY UNEQUIVOCALLY ACKNOWLEDGES AND AGREES * THAT THE SOFTWARE/FIRMWARE AND ITS DOCUMENTATIONS ("MEDIATEK SOFTWARE") * RECEIVED FROM MEDIATEK AND/OR ITS REPRESENTATIVES ARE PROVIDED TO RECEIVER ON * AN "AS-IS" BASIS ONLY. MEDIATEK EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR NONINFRINGEMENT. * NEITHER DOES MEDIATEK PROVIDE ANY WARRANTY WHATSOEVER WITH RESPECT TO THE * SOFTWARE OF ANY THIRD PARTY WHICH MAY BE USED BY, INCORPORATED IN, OR * SUPPLIED WITH THE MEDIATEK SOFTWARE, AND RECEIVER AGREES TO LOOK ONLY TO SUCH * THIRD PARTY FOR ANY WARRANTY CLAIM RELATING THERETO. RECEIVER EXPRESSLY ACKNOWLEDGES * THAT IT IS RECEIVER'S SOLE RESPONSIBILITY TO OBTAIN FROM ANY THIRD PARTY ALL PROPER LICENSES * CONTAINED IN MEDIATEK SOFTWARE. MEDIATEK SHALL ALSO NOT BE RESPONSIBLE FOR ANY MEDIATEK * SOFTWARE RELEASES MADE TO RECEIVER'S SPECIFICATION OR TO CONFORM TO A PARTICULAR * STANDARD OR OPEN FORUM. RECEIVER'S SOLE AND EXCLUSIVE REMEDY AND MEDIATEK'S ENTIRE AND * CUMULATIVE LIABILITY WITH RESPECT TO THE MEDIATEK SOFTWARE RELEASED HEREUNDER WILL BE, * AT MEDIATEK'S OPTION, TO REVISE OR REPLACE THE MEDIATEK SOFTWARE AT ISSUE, * OR REFUND ANY SOFTWARE LICENSE FEES OR SERVICE CHARGE PAID BY RECEIVER TO * MEDIATEK FOR SUCH MEDIATEK SOFTWARE AT ISSUE. * * The following software/firmware and/or related documentation ("MediaTek Software") * have been modified by MediaTek Inc. All revisions are subject to any receiver's * applicable license agreements with MediaTek Inc. */ /* ** ** Copyright 2008, The Android Open Source Project ** ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ #ifndef _MTK_WARP_TYPE_H #define _MTK_WARP_TYPE_H //#include "MediaTypes.h" #ifndef true #define true 1 #endif #ifndef false #define false 0 #endif #ifndef NULL #define NULL 0 #endif typedef unsigned int MUINT32; typedef unsigned short MUINT16; typedef unsigned char MUINT8; typedef signed int MINT32; typedef signed short MINT16; typedef signed char MINT8; typedef int MBOOL; typedef float MFLOAT; #endif
module.exports = { "parserOptions": { "ecmaVersion": 6 }, "env": { "browser": true, "commonjs": true }, "extends": [ "./possible-errors.js", "./best-practices.js", "./variables.js", "./stylistic-issues.js" ], "plugins": [ ], "rules": { /* Strict Mode */ "strict": [ /** * I think, you should run in strict mode, but your bundler or whatever can take care of inserting the statement. */ "off" ], /* Node.js and Common.js */ "callback-return": [ "off" ], "global-require": [ "error" ], "no-mixed-requires": [ "error", { "grouping": true, "allowCall": true } ], "no-new-require": [ "error" ], "no-path-concat": [ "error" ], "no-process-env": [ "error" ], "no-process-exit": [ "error" ], "no-restricted-modules": [ "off" ], "no-sync": [ "off" ] } };
class Number: def __init__(self, value): self.value = value def __repr__(self): return f'{self.value}' class OpNode(): def __init__(self, a, b): self.a = a self.b = b self.op = None def __repr__(self): return f'({self.a}{self.op}{self.b})' class Addition(OpNode): def __init__(self, a, b): super() self.a = a self.b = b self.op = '+' class Substraction(OpNode): def __init__(self, a, b): super() self.a = a self.b = b self.op = '-' class Multiplication(OpNode): def __init__(self, a, b): super() self.a = a self.b = b self.op = '*' class Division(OpNode): def __init__(self, a, b): super() self.a = a self.b = b self.op = '/' class Power(OpNode): def __init__(self, a, b): super() self.a = a self.b = b self.op = '^'
/* * This header is generated by classdump-dyld 1.5 * on Wednesday, April 28, 2021 at 9:01:31 PM Mountain Standard Time * Operating System: Version 14.5 (Build 18L204) * Image Source: /System/Library/Frameworks/Foundation.framework/Foundation * classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by Elias Limneos. Updated by Kevin Bradley. */ #import <Foundation/Foundation-Structs.h> #import <Foundation/NSDirectoryEnumerator.h> @interface NSURLDirectoryEnumerator : NSDirectoryEnumerator { CFURLEnumeratorRef _enumerator; /*^block*/id _errorHandler; BOOL shouldContinue; BOOL isPostOrderDirectory; } @property (copy) id errorHandler; //@synthesize errorHandler=_errorHandler - In the implementation block -(void)dealloc; -(id)nextObject; -(id)fileAttributes; -(id)directoryAttributes; -(unsigned long long)level; -(void)skipDescendents; -(void)skipDescendants; -(BOOL)isEnumeratingDirectoryPostOrder; -(void)setErrorHandler:(id)arg1 ; -(id)initWithURL:(id)arg1 includingPropertiesForKeys:(id)arg2 options:(unsigned long long)arg3 errorHandler:(/*^block*/id)arg4 ; -(id)errorHandler; @end
// @flow import React from 'react'; import { capitalize } from 'lodash'; import { Helmet } from 'react-helmet'; import biomMassFavicon from '@ncigdc/theme/images/biom-mass-server-favicon.png'; export default ({ title }) => ( <Helmet> <meta name="description" content="BIOM-Mass Portal" /> <title>{'BIOM-Mass'}</title> <link rel="icon" href={biomMassFavicon} /> <script async src="https://www.googletagmanager.com/gtag/js?id=UA-139875427-1"></script> <script> {` window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);} gtag('js', new Date()); gtag('config', 'UA-139875427-1'); `} </script> </Helmet> );
#n = int(input()) #s = input() n, q = map(int, input().split()) # = list(map(int, input().split())) #ab = [list(map(int, input().split())) for _ in range(n-1)] from collections import deque graph = [[] for _ in range(n + 1)] for i in range(n - 1): a, b = map(int, input().split()) graph[a].append(b) graph[b].append(a) dist = [-1] * (n + 1) dist[0] = 0 dist[1] = 0 d = deque() d.append(1) while d: v = d.popleft() for i in graph[v]: if dist[i] != -1: continue dist[i] = dist[v] + 1 d.append(i) ans = dist[1:] #print(ans) cd = [list(map(int, input().split())) for _ in range(q)] for i in range(q): c = cd[i][0] - 1 d = cd[i][1] - 1 if ans[c] % 2 == ans[d] % 2: print('Town') else: print('Road')
export default Ext.define('KitchenSink.reader.Salary', { extend: 'Ext.data.reader.Json', alias: 'reader.salary', getResponseData: function(...args) { const data = KitchenSink.reader.Salary.superclass.getResponseData.call(this, ...args) return this.addTreeHierarchy(data); }, addTreeHierarchy: function (data) { data = this.addTreeLevel(data, 'industry_type', ['salary', 'state'], 'industry'); return this.addTreeLevel(data, 'state', [], 'state'); }, addTreeLevel: function (data, fieldName, fieldsToCopy, notBlank) { var tree = [], currentValue, parentItem; Ext.Array.each(data, function (item) { if (item[fieldName] != currentValue) { currentValue = item[fieldName]; parentItem = {}; parentItem[fieldName] = currentValue; parentItem.text = currentValue; Ext.Array.each(fieldsToCopy, function (field) { parentItem[field] = item[field]; }); parentItem.children = []; tree.push(Ext.apply(parentItem)); } if (item[notBlank]) { if (Ext.isEmpty(item.children)) { item.leaf = true; } if (Ext.isEmpty(item.text)) { item.text = item[notBlank]; } tree[tree.length - 1].children.push(item); } }); return tree; } });
#!/usr/bin/env python import jinja2 import tempfile import os import json import pdb import string import random import re # XXX hardcoded path # is there any reason why we aren't importing xos.config ? XOS_DIR="/opt/xos" try: step_dir = Config().observer_steps_dir sys_dir = Config().observer_sys_dir except: step_dir = XOS_DIR + '/observer/steps' sys_dir = '/opt/opencloud' os_template_loader = jinja2.FileSystemLoader( searchpath=step_dir) os_template_env = jinja2.Environment(loader=os_template_loader) def parse_output(msg): lines = msg.splitlines() results = [] print msg for l in lines: magic_str = 'ok: [127.0.0.1] => ' magic_str2 = 'changed: [127.0.0.1] => ' if (l.startswith(magic_str)): w = len(magic_str) str = l[w:] d = json.loads(str) results.append(d) elif (l.startswith(magic_str2)): w = len(magic_str2) str = l[w:] d = json.loads(str) results.append(d) return results def id_generator(size=6, chars=string.ascii_uppercase + string.digits): return ''.join(random.choice(chars) for _ in range(size)) def shellquote(s): return "'" + s.replace("'", "'\\''") + "'" def run_template(name, opts,path='', expected_num=None): template = os_template_env.get_template(name) buffer = template.render(opts) try: objname = opts['ansible_tag'] except: objname= id_generator() os.system('mkdir -p %s'%'/'.join([sys_dir,path])) fqp = '/'.join([sys_dir,path,objname]) f = open(fqp,'w') f.write(buffer) f.flush() run = os.popen(XOS_DIR + '/observer/run_ansible %s'%shellquote(fqp)) #run = os.popen('ansible-playbook -v %s'%shellquote(fqp)) msg = run.read() status = run.close() try: ok_results = parse_output(msg) if (len(ok_results) != expected_num): raise ValueError('Unexpected num') except ValueError,e: all_fatal = re.findall(r'^msg: (.*)',msg,re.MULTILINE) all_fatal2 = re.findall(r'^ERROR: (.*)',msg,re.MULTILINE) all_fatal.extend(all_fatal2) try: error = ' // '.join(all_fatal) except: pass raise Exception(error) return ok_results def main(): run_template('ansible/sync_user_deployments.yaml',{ "endpoint" : "http://172.31.38.128:5000/v2.0/", "name" : "Sapan Bhatia", "email": "gwsapan@gmail.com", "password": "foobar", "admin_user":"admin", "admin_password":"6a789bf69dd647e2", "admin_tenant":"admin", "tenant":"demo", "roles":['user','admin'] })
from fcrepo_verify.utils import get_data_dir, replace_strings_in_file from fcrepo_verify.constants import BAG_DATA_DIR import os import tempfile class MockConfig(dict): pass config = MockConfig({}) config.dir = "/tmp" def test_get_data_dir(): config.bag = False data_dir = get_data_dir(config) assert data_dir == "/tmp" def test_get_data_dir_for_bag(): config.bag = True data_dir = get_data_dir(config) assert data_dir == "/tmp" + BAG_DATA_DIR def test_replace_strings_in_file(): tmp = tempfile.mkstemp() filename = tmp[1] with open(filename, "w") as source: source.write("test y\n") source.write("test z") newfile = replace_strings_in_file(filename, "test", "confirm") os.remove(filename) with open(newfile, "r") as dest: assert dest.readline().startswith("confirm y") assert dest.readline() == "confirm z" os.remove(newfile)
def read_data(): import pandas as pd global mu_liver mu_liver=pd.read_csv("./mu_values_tissues/mu_liver_complete.csv", header=0) global mu_fat mu_fat = pd.read_csv("./mu_values_tissues/mu_fat_complete.csv", header=0) global mu_air mu_air = pd.read_csv("./mu_values_tissues/mu_air_complete.csv", header=0) global KV_quant_factor KV_quant_factor = pd.read_csv("./KV_mAs_5_PercentRule/data_KV_mAs.csv", header = 0) read_data()
/* * This header is generated by classdump-dyld 1.0 * on Sunday, September 27, 2020 at 11:42:11 AM Mountain Standard Time * Operating System: Version 14.0 (Build 18A373) * Image Source: /System/Library/PrivateFrameworks/Translation.framework/Translation * classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by Elias Limneos. */ #import <Translation/Translation-Structs.h> #import <Translation/FTUserAcousticProfile.h> @class NSString, NSData; @interface FTMutableUserAcousticProfile : FTUserAcousticProfile @property (nonatomic,copy) NSString * acoustic_profile_version; @property (nonatomic,copy) NSData * acoustic_profile_blob; @property (nonatomic,copy) NSString * profile_checksum; -(id)copyWithZone:(NSZone*)arg1 ; -(NSString *)profile_checksum; -(void)setProfile_checksum:(NSString *)arg1 ; -(NSData *)acoustic_profile_blob; -(NSString *)acoustic_profile_version; -(void)setAcoustic_profile_version:(NSString *)arg1 ; -(void)setAcoustic_profile_blob:(NSData *)arg1 ; -(void)acoustic_profile_blob:(/*^block*/id)arg1 ; -(id)init; @end
#ifndef TESTMAPLOADER_H #define TESTMAPLOADER_H #include "Test.h" #include <MapLoader.h> class Test_MapLoader: public Test { private: public: Test_MapLoader(): Test("MAPLOADER") { } void setup() { MapLoader loader; newEntry(TestData("Missing File", loader.parseMap("../Maps/invalid.txt", NULL, NULL, NULL) == GAME_FAIL)); newEntry(TestData("Missing Factory", loader.parseMap("../Maps/1.txt", NULL, NULL, NULL) == GAME_FAIL)); } }; #endif
//Theme initialize if (!localStorage.getItem("theme")) { localStorage.setItem("theme", "light"); } // Theme toggle const toggle = () => { if (localStorage.getItem("theme") === "light") localStorage.setItem("theme", "dark"); else if (localStorage.getItem("theme") === "dark") { localStorage.setItem("theme", "light"); } themer(); }; const changeUtterancesTheme = (isDarkTheme, isRetry = false) => { const utterances = document.querySelector("iframe.utterances-frame"); if (utterances) { const utterancesTheme = isDarkTheme ? "github-dark" : "github-light"; utterances.contentWindow.postMessage({ type: "set-theme", theme: utterancesTheme }, "https://utteranc.es"); return; } if (isRetry) return; setTimeout(() => { changeUtterancesTheme(isDarkTheme, true); }, 1000); }; // Theme set const themer = () => { const isDarkTheme = localStorage.getItem("theme") === "dark"; changeUtterancesTheme(isDarkTheme); const dark = document.getElementById("dark"); isDarkTheme ? dark.removeAttribute("disabled") : dark.setAttribute("disabled", "true"); }; themer(); document.getElementById("toggleBtn").addEventListener("click", toggle);
!function(e){const t=e.de=e.de||{};t.dictionary=Object.assign(t.dictionary||{},{"%0 of %1":"%0 von %1","Align cell text to the bottom":"Zellentext unten ausrichten","Align cell text to the center":"Zellentext zentriert ausrichten","Align cell text to the left":"Zellentext linksbündig ausrichten","Align cell text to the middle":"Zellentext mittig ausrichten","Align cell text to the right":"Zellentext rechtsbündig ausrichten","Align cell text to the top":"Zellentext oben ausrichten","Align center":"Zentriert","Align left":"Linksbündig","Align right":"Rechtsbündig","Align table to the left":"Tabelle links ausrichten","Align table to the right":"Tabelle rechts ausrichten",Alignment:"Ausrichtung",Aquamarine:"Aquamarinblau",Background:"Hintergrund",Big:"Groß",Black:"Schwarz","Block quote":"Blockzitat",Blue:"Blau","Blue marker":"Blauer Marker",Bold:"Fett",Border:"Rahmen","Bulleted List":"Aufzählungsliste","Bulleted list styles toolbar":"Darstellung der ungeordneten Liste",Cancel:"Abbrechen","Cell properties":"Zelleneigenschaften","Center table":"Tabelle zentrieren","Choose heading":"Überschrift auswählen",Circle:"Leerer Kreis",Color:"Farbe","Color picker":"Farbwähler",Column:"Spalte",Dashed:"Gestrichelt",Decimal:"Dezimalzahlen","Decimal with leading zero":"Dezimalzahlen mit vorangestellten Nullen","Decrease indent":"Einzug verkleinern",Default:"Standard","Delete column":"Spalte löschen","Delete row":"Zeile löschen","Dim grey":"Dunkelgrau",Dimensions:"Größe",Disc:"Gefüllter Kreis","Document colors":"Dokumentfarben",Dotted:"Gepunktet",Double:"Doppelt",Downloadable:"Herunterladbar","Dropdown toolbar":"Dropdown-Liste Werkzeugleiste","Edit block":"Absatz bearbeiten","Edit link":"Link bearbeiten","Editor toolbar":"Editor Werkzeugleiste","Enter table caption":"Tabellenüberschrift eingeben","Font Background Color":"Hintergrundfarbe","Font Color":"Schriftfarbe","Font Family":"Schriftart","Font Size":"Schriftgröße",Green:"Grün","Green marker":"Grüner Marker","Green pen":"Grüne Schriftfarbe",Grey:"Grau",Groove:"Eingeritzt","Header column":"Kopfspalte","Header row":"Kopfzeile",Heading:"Überschrift","Heading 1":"Überschrift 1","Heading 2":"Überschrift 2","Heading 3":"Überschrift 3","Heading 4":"Überschrift 4","Heading 5":"Überschrift 5","Heading 6":"Überschrift 6",Height:"Höhe",Highlight:"Texthervorhebung","Horizontal line":"Horizontale Linie","Horizontal text alignment toolbar":"Werkzeugleiste für die horizontale Zellentext-Ausrichtung",Huge:"Sehr groß","Increase indent":"Einzug vergrößern","Insert column left":"Spalte links einfügen","Insert column right":"Spalte rechts einfügen","Insert paragraph after block":"Absatz nach Block einfügen","Insert paragraph before block":"Absatz vor Block einfügen","Insert row above":"Zeile oben einfügen","Insert row below":"Zeile unten einfügen","Insert table":"Tabelle einfügen",Inset:"Eingelassen",Italic:"Kursiv",Justify:"Blocksatz","Justify cell text":"Zellentext als Blocksatz ausrichten","Light blue":"Hellblau","Light green":"Hellgrün","Light grey":"Hellgrau",Link:"Link","Link URL":"Link Adresse","Lower-latin":"Kleingeschriebene lateinische Buchstaben","Lower–roman":"Kleingeschriebene römische Zahlen","Merge cell down":"Zelle unten verbinden","Merge cell left":"Zelle links verbinden","Merge cell right":"Zelle rechts verbinden","Merge cell up":"Zelle verbinden","Merge cells":"Zellen verbinden",Next:"Nächste",None:"Kein Rahmen","Numbered List":"Nummerierte Liste","Numbered list styles toolbar":"Darstellung der geordneten Liste","Open in a new tab":"In neuem Tab öffnen","Open link in new tab":"Link im neuen Tab öffnen",Orange:"Orange",Outset:"Geprägt",Padding:"Innenabstand",Paragraph:"Absatz","Pink marker":"Pinker Marker",Previous:"vorherige",Purple:"Violett",Red:"Rot","Red pen":"Rote Schriftfarbe",Redo:"Wiederherstellen","Remove color":"Farbe entfernen","Remove Format":"Formatierung entfernen","Remove highlight":"Texthervorhebung entfernen","Restore default":"Standard wiederherstellen","Rich Text Editor":"Rich Text Editor","Rich Text Editor, %0":"Rich-Text-Editor, %0",Ridge:"Hervorgehoben",Row:"Zeile",Save:"Speichern","Select all":"Alles auswählen","Select column":"Spalte auswählen","Select row":"Zeile auswählen","Show more items":"Mehr anzeigen",Small:"Klein",Solid:"Durchgezogen","Split cell horizontally":"Zelle horizontal teilen","Split cell vertically":"Zelle vertikal teilen",Square:"Quadrat",Style:"Rahmenart","Table alignment toolbar":"Werkzeugleiste für die Tabellen-Ausrichtung","Table cell text alignment":"Ausrichtung des Zellentextes","Table properties":"Tabelleneigenschaften","Table toolbar":"Tabelle Werkzeugleiste","Text alignment":"Textausrichtung","Text alignment toolbar":"Text-Ausrichtung Toolbar","Text highlight toolbar":"Text hervorheben Werkzeugleiste",'The color is invalid. Try "#FF0000" or "rgb(255,0,0)" or "red".':"Die Farbe ist ungültig. Probieren Sie „#FF0000“ oder „rgb(255,0,0)“ oder „red“.",'The value is invalid. Try "10px" or "2em" or simply "2".':"Der Wert ist ungültig. Probieren Sie „10px“ oder „2em“ oder „2“.","This link has no URL":"Dieser Link hat keine Adresse",Tiny:"Sehr klein","Toggle caption off":"Tabellenüberschrift deaktivieren","Toggle caption on":"Tabellenüberschrift aktivieren","Toggle the circle list style":"Leeren Kreis einstellen","Toggle the decimal list style":"Dezimalzahlen einstellen","Toggle the decimal with leading zero list style":"Dezimalzahlen mit vorangestellten Nullen einstellen","Toggle the disc list style":"Gefüllten Kreis einstellen","Toggle the lower–latin list style":"Kleingeschriebene lateinische Buchstaben einstellen","Toggle the lower–roman list style":"Kleingeschriebene römische Zahlen einstellen","Toggle the square list style":"Quadrat einstellen","Toggle the upper–latin list style":"Großgeschriebene lateinische Buchstaben einstellen","Toggle the upper–roman list style":"Großgeschriebene römische Zahlen einstellen",Turquoise:"Türkis",Underline:"Unterstrichen",Undo:"Rückgängig",Unlink:"Link entfernen","Upper-latin":"Großgeschriebene lateinische Buchstaben","Upper-roman":"Großgeschriebene römische Zahlen","Vertical text alignment toolbar":"Werkzeugleiste für die vertikale Zellentext-Ausrichtung",White:"Weiß","Widget toolbar":"Widget Werkzeugleiste",Width:"Breite",Yellow:"Gelb","Yellow marker":"Gelber Marker"}),t.getPluralForm=function(e){return 1!=e}}(window.CKEDITOR_TRANSLATIONS||(window.CKEDITOR_TRANSLATIONS={}));
""" This module handles all the phishing related operations for Wifiphisher.py """ import os from shutil import copyfile import wifiphisher.common.constants as constants try: from configparser import ConfigParser, RawConfigParser except ImportError: from configparser import ConfigParser, RawConfigParser def config_section_map(config_file, section): """ Map the values of a config file to a dictionary. """ config = ConfigParser() config.read(config_file) dict1 = {} if section not in config.sections(): return dict1 options = config.options(section) for option in options: try: dict1[option] = config.get(section, option) except KeyError: dict1[option] = None return dict1 class InvalidTemplate(Exception): """ Exception class to raise in case of a invalid template """ def __init__(self): Exception.__init__(self, "The given template is either invalid or " + "not available locally!") class PhishingTemplate(object): """ This class represents phishing templates """ def __init__(self, name): """ Construct object. :param self: A PhishingTemplate object :type self: PhishingTemplate :return: None :rtype: None .. todo:: Maybe add a category field """ # setup all the variables config_path = os.path.join(constants.phishing_pages_dir, name, 'config.ini') info = config_section_map(config_path, 'info') self._name = name self._display_name = info['name'] self._description = info['description'] self._payload = False self._config_path = os.path.join(constants.phishing_pages_dir, self._name, 'config.ini') if 'payloadpath' in info: self._payload = info['payloadpath'] self._path = os.path.join(constants.phishing_pages_dir, self._name.lower(), constants.SCENARIO_HTML_DIR) self._path_static = os.path.join(constants.phishing_pages_dir, self._name.lower(), constants.SCENARIO_HTML_DIR, 'static') self._context = config_section_map(config_path, 'context') self._extra_files = [] @staticmethod def update_config_file(payload_filename, config_path): """ Update the configuration file :param self: A PhishingTemplate object :param payload_filename: the filename for the payload :param config_path: the file path for the configuration :type self: PhishingTemplate :type payload_filename: str :type config_path: str :return: None :rtype: None """ original_config = ConfigParser() original_config.read(config_path) # new config file object config = RawConfigParser() # update the info section config.add_section('info') options = original_config.options('info') for option in options: if option != "payloadpath": config.set('info', option, original_config.get('info', option)) else: dirname = os.path.dirname( original_config.get('info', 'payloadpath')) filepath = os.path.join(dirname, payload_filename) config.set('info', option, filepath) # update the context section config.add_section('context') dirname = os.path.dirname( original_config.get('context', 'update_path')) filepath = os.path.join(dirname, payload_filename) config.set('context', 'update_path', filepath) with open(config_path, 'w') as configfile: config.write(configfile) def update_payload_path(self, filename): """ :param self: A PhishingTemplate object :filename: the filename for the payload :type self: PhishingTemplate :type filename: str :return: None :rtype: None """ config_path = self._config_path self.update_config_file(filename, config_path) # update payload attribute info = config_section_map(config_path, 'info') self._payload = False if 'payloadpath' in info: self._payload = info['payloadpath'] self._context = config_section_map(config_path, 'context') self._extra_files = [] def merge_context(self, context): """ Merge dict context with current one In case of confict always keep current values """ context.update(self._context) self._context = context def get_context(self): """ Return the context of the template. :param self: A PhishingTemplate object :type self: PhishingTemplate :return: the context of the template :rtype: dict """ return self._context def get_display_name(self): """ Return the display name of the template. :param self: A PhishingTemplate object :type self: PhishingTemplate :return: the display name of the template :rtype: str """ return self._display_name def get_payload_path(self): """ Return the payload path of the template. :param self: A PhishingTemplate object :type self: PhishingTemplate :return: The path of the template :rtype: bool """ return self._payload def has_payload(self): """ Return whether the template has a payload. :param self: A PhishingTemplate object :type self: PhishingTemplate :return: boolean if it needs payload :rtype: bool """ if self._payload: return True return False def get_description(self): """ Return the description of the template. :param self: A PhishingTemplate object :type self: PhishingTemplate :return: the description of the template :rtype: str """ return self._description def get_path(self): """ Return the path of the template files. :param self: A PhishingTemplate object :type self: PhishingTemplate :return: the path of template files :rtype: str """ return self._path def get_path_static(self): """ Return the path of the static template files. JS, CSS, Image files lie there. :param self: A PhishingTemplate object :type self: PhishingTemplate :return: the path of static template files :rtype: str """ return self._path_static def use_file(self, path): """ Copies a file in the filesystem to the path of the template files. :param self: A PhishingTemplate object :type self: PhishingTemplate :param path: path of the file that is to be copied :type self: str :return: the path of the file under the template files :rtype: str """ if path is not None and os.path.isfile(path): filename = os.path.basename(path) copyfile(path, self.get_path_static() + filename) self._extra_files.append(self.get_path_static() + filename) return filename def remove_extra_files(self): """ Removes extra used files (if any) :param self: A PhishingTemplate object :type self: PhishingTemplate :return: None :rtype: None """ for filename in self._extra_files: if os.path.isfile(filename): os.remove(filename) def __str__(self): """ Return a string representation of the template. :param self: A PhishingTemplate object :type self: PhishingTemplate :return: the name followed by the description of the template :rtype: str """ return self._display_name + "\n\t" + self._description + "\n" class TemplateManager(object): """ This class handles all the template management operations """ def __init__(self, data_pages=None): """ Construct object. :param self: A TemplateManager object :param data_pages: The directory containing the templates :type self: TemplateManager :return: None :rtype: None """ # setup the templates self._template_directory = data_pages or constants.phishing_pages_dir if data_pages: constants.phishing_pages_dir = data_pages page_dirs = os.listdir(self._template_directory) self._templates = {} for page in page_dirs: if os.path.isdir(page) and self.is_valid_template(page)[0]: self._templates[page] = PhishingTemplate(page) # add all the user templates to the database self.add_user_templates() def get_templates(self): """ Return all the available templates. :param self: A TemplateManager object :type self: TemplateManager :return: all the available templates :rtype: dict """ return self._templates def is_valid_template(self, name): """ Validate the template :param self: A TemplateManager object :param name: A directory name :type self: A TemplateManager object :return: tuple of is_valid and output string :rtype: tuple """ html = False dir_path = os.path.join(self._template_directory, name) # check config file... if not "config.ini" in os.listdir(dir_path): return False, "Configuration file not found in: " try: tdir = os.listdir(os.path.join(dir_path, constants.SCENARIO_HTML_DIR)) except OSError: return False, "No " + constants.SCENARIO_HTML_DIR + " directory found in: " # Check HTML files... for tfile in tdir: if tfile.endswith(".html"): html = True break if not html: return False, "No HTML files found in: " # and if we found them all return true and template directory name return True, name def find_user_templates(self): """ Return all the user's templates available. :param self: A TemplateManager object :type self: TemplateManager :return: all the local templates available :rtype: list """ # a list to store file names in local_templates = [] # loop through the directory content for name in os.listdir(self._template_directory): # check to see if it is a directory and not in the database if (os.path.isdir(os.path.join(self._template_directory, name)) and name not in self._templates): # check template is_valid, output = self.is_valid_template(name) # if template successfully validated, then... if is_valid: # just add it to the list local_templates.append(name) else: # TODO: We should throw an exception instead here. # but if not then display which problem occurred print("[" + constants.R + "!" + constants.W + "] " + output + name) return local_templates def add_user_templates(self): """ Add all the user templates to the database. :param self: A TemplateManager object :type: self: TemplateManager :return: None :rtype: None """ # get all the user's templates user_templates = self.find_user_templates() # loop through the templates for template in user_templates: # create a template object and add it to the database local_template = PhishingTemplate(template) self._templates[template] = local_template @property def template_directory(self): return self._template_directory def on_exit(self): """ Delete any extra files on exit :param self: A TemplateManager object :type: self: TemplateManager :return: None :rtype: None """ for templ_obj in list(self._templates.values()): templ_obj.remove_extra_files()
/////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// #include "gsCommon.h" #include "gsDebug.h" //#include <stdio.h> //#include <stdarg.h> // THIS FILE ONLY INCLUDED WHEN USING GAMESPY DEBUG FUNCTIONS // (don't put this above the header includes or VC will whine #ifdef GSI_COMMON_DEBUG #if defined(_NITRO) #include "../../common/nitro/screen.h" #define printf Printf #define vprintf VPrintf #endif /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// // Static debug data static struct GSIDebugInstance gGSIDebugInstance; // simple singleton "class" // Line prefixes, e.g. "[ cat][type][ lev] text" char* gGSIDebugCatStrings[GSIDebugCat_Count] = { " APP", " GP ", "PEER", " QR2", " SB", " V2", " AD", " NN", "HTTP", "CDKY", " CMN" }; char* gGSIDebugTypeStrings[GSIDebugType_Count] = { " NET", "FILE", " MEM", "STAT", "MISC" }; char* gGSIDebugLevelStrings[GSIDebugLevel_Count] = { "*ERR", "****", "----", " ", " ", " ", " ->" }; char* gGSIDebugLevelDescriptionStrings[8] = { "None", "<None+1>", "<Normal>", "<Debug>", "<Verbose>", "<Verbose+1>", "<Verbose+2>", "<Hardcore>" }; /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// // utility to convert bit flag back to base (e.g. 1<<2 returns 2) static gsi_u32 gsiDebugLog2(gsi_u32 theInt) { gsi_u32 total = 0; while (theInt > 1) { theInt = theInt >> 1; total++; } return total; } // default supplied debug function, will receive debug text // this is platform specific static void gsiDebugCallback(GSIDebugCategory category, GSIDebugType type, GSIDebugLevel level, const char * format, va_list params) { #if defined(_PSP) // Output line prefix vprintf(format, params); //gsDebugTTyPrint(string); #elif defined(_PS2) // Output line prefix vprintf(format, params); #elif defined(_PS3) // Output line prefix vprintf(format, params); #elif defined(_WIN32) static char string[256]; vsprintf(string, format, params); OutputDebugStringA(string); #elif defined(_LINUX) || defined(_MACOSX) //static char string[256]; //vsprintf(string, format, params); vprintf(format, params); #elif defined(_NITRO) VPrintf(format, params); #elif defined(_REVOLUTION) static char string[256]; vsprintf(string, format, params); OSReport(string); #else va_list argptr; static char string[256]; va_start(argptr, format); vsprintf(string, format, argptr); va_end(argptr); gsDebugTTyPrint(string); #endif GSI_UNUSED(category); GSI_UNUSED(type); GSI_UNUSED(level); } /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// // process debug output void gsDebugVaList(GSIDebugCategory theCat, GSIDebugType theType, GSIDebugLevel theLevel, const char* theTokenStr, va_list theParamList) { // Retrieve the current debug level GSIDebugLevel aCurLevel; // Verify Parameters assert(theCat <= GSIDebugCat_Count); assert(theType <= GSIDebugType_Count); assert(theLevel <= (1<<GSIDebugLevel_Count)); assert(theTokenStr); // Make thread safe if (gGSIDebugInstance.mInitialized == 0) { // Warning: Slight race condition risk here the first time // gsDebug functions are used. // The risk is minimal since you usually set // debug levels and targets at program startup gGSIDebugInstance.mInitialized = 1; gsiInitializeCriticalSection(&gGSIDebugInstance.mDebugCrit); } gsiEnterCriticalSection(&gGSIDebugInstance.mDebugCrit); // Are we currently logging this type and level? aCurLevel = gGSIDebugInstance.mGSIDebugLevel[theCat][theType]; if (aCurLevel & theLevel) // check the flag { #if !defined(_NITRO) // Output line prefix if (gGSIDebugInstance.mGSIDebugFile) { fprintf(gGSIDebugInstance.mGSIDebugFile, "[%s][%s][%s] ", gGSIDebugCatStrings[theCat], gGSIDebugTypeStrings[theType], gGSIDebugLevelStrings[gsiDebugLog2(theLevel)]); // Output to file vfprintf(gGSIDebugInstance.mGSIDebugFile, theTokenStr, theParamList); } #endif // Output to developer function if provided if (gGSIDebugInstance.mDebugCallback != NULL) { (*gGSIDebugInstance.mDebugCallback)(theCat, theType, theLevel, theTokenStr, theParamList); } else { gsiDebugCallback(theCat, theType, theLevel, theTokenStr, theParamList); } } gsiLeaveCriticalSection(&gGSIDebugInstance.mDebugCrit); } /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// // process debug output void gsDebugFormat(GSIDebugCategory theCat, GSIDebugType theType, GSIDebugLevel theLevel, const char* theTokenStr, ...) { va_list aParameterList; // Verify Parameters assert(theCat <= GSIDebugCat_Count); assert(theType <= GSIDebugType_Count); assert(theLevel <= (1<<GSIDebugLevel_Count)); assert(theTokenStr); // Find start of var arg list va_start(aParameterList, theTokenStr); // Pass to VA version gsDebugVaList(theCat, theType, theLevel, theTokenStr, aParameterList); } /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// // Converts binary buffer to memory view form: // 0000 0000 0000 0000 0000 0000 0000 0000 ................ static void HexEncode16(const char* theInStream, char* theOutStream, unsigned int theInLen) { const int aRowWidth = 64; // width of the output const char aReplaceChar = '.'; // Replace non print characters const int aTextOffSet = 41; // text comes after hex bytes char* aTextOutStream = (theOutStream+aTextOffSet); // set the write ptr const unsigned int aWriteBit = theInLen & 1; // write on odd or even bytes? assert(theInLen <= 16); // Set buffer to ' ' memset(theOutStream, ' ', aRowWidth); // Convert characters one at a time while(theInLen--) { // Read the next byte unsigned char aChar = (unsigned char)(*theInStream++); // Write one byte in hex form sprintf(theOutStream, "%02X", aChar); // Write the printable character if (isgraph(aChar)) *(aTextOutStream++) = (char)aChar; else *(aTextOutStream++) = aReplaceChar; // Move to next hex byte theOutStream += 2; // Insert a space every other byte if ((theInLen & 1) == aWriteBit) *theOutStream++ = ' '; } // Remove NULL terminator from last sprintf *theOutStream = ' '; // NULL terminate the full string *(aTextOutStream) = '\0'; } /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// // Write binary data as B64 bytes (40 bytes per line) void gsDebugBinary(GSIDebugCategory theCat, GSIDebugType theType, GSIDebugLevel theLevel, const char* theBuffer, gsi_i32 theLength) { int aBytesLeft = theLength; const char* aReadPos = theBuffer; char aHexStr[80]; // convert and display in 40 byte segments while(aBytesLeft > 0) { gsi_i32 aBytesToRead = min(aBytesLeft, 16); HexEncode16(aReadPos, aHexStr, (unsigned int)aBytesToRead); gsDebugFormat(theCat, theType, theLevel, " %s\r\n", aHexStr); aReadPos += aBytesToRead; aBytesLeft -= aBytesToRead; }; } /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// void gsSetDebugLevel(GSIDebugCategory theCat, GSIDebugType theType, GSIDebugLevel theLevel) { // Verify Parameters assert(theCat <= GSIDebugCat_Count); assert(theType <= GSIDebugType_Count); // Set for all categories? if (theCat == GSIDebugCat_Count) { int i=0; for (; i<GSIDebugCat_Count; i++) gsSetDebugLevel((GSIDebugCategory)i, theType, theLevel); gsDebugFormat(GSIDebugCat_Common, GSIDebugType_Misc, GSIDebugLevel_Debug, "Debug level set to %s for all categories (SDKs)\r\n", gGSIDebugLevelDescriptionStrings[gsiDebugLog2(theLevel)]); return; } // Set for all types? if (theType == GSIDebugType_Count) { int i=0; for (; i<GSIDebugType_Count; i++) gsSetDebugLevel(theCat, (GSIDebugType)i, theLevel); gsDebugFormat(GSIDebugCat_Common, GSIDebugType_Misc, GSIDebugLevel_Debug, "Debug level set to %s for all types\r\n", gGSIDebugLevelDescriptionStrings[gsiDebugLog2(theLevel)]); return; } // Is the new level different from the old? if (gGSIDebugInstance.mGSIDebugLevel[theCat][theType] != theLevel) { // Notify of the change gsDebugFormat(GSIDebugCat_Common, GSIDebugType_Misc, GSIDebugLevel_Comment, "Changing debug level: [%s][%s][%02X]\r\n", gGSIDebugCatStrings[theCat], gGSIDebugTypeStrings[theType], theLevel ); gGSIDebugInstance.mGSIDebugLevel[theCat][theType] = theLevel; } } #if !defined(_NITRO) /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// // Set the debug output file to an already open file // Set to "stdout" for console output void gsSetDebugFile(FILE* theFile) { if (theFile != gGSIDebugInstance.mGSIDebugFile) { // If the old file is valid, notify it of the closing if (gGSIDebugInstance.mGSIDebugFile != NULL) { gsDebugFormat(GSIDebugCat_Common, GSIDebugType_Misc, GSIDebugLevel_Comment, "Debug disabled in this file\r\n"); } // If the new file is valid, notify it of the opening { gsDebugFormat(GSIDebugCat_Common, GSIDebugType_Misc, GSIDebugLevel_Comment, "Debug enabled in this file\r\n"); } gGSIDebugInstance.mGSIDebugFile = theFile; } } /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// // Opens and sets the debug output file FILE* gsOpenDebugFile(const char* theFileName) { // The new file FILE* aFile = NULL; // Verify parameters assert(theFileName != NULL); // Open the new file (clear contents) fopen_s(&aFile, theFileName, "w+"); if (aFile != NULL) gsSetDebugFile(aFile); return aFile; } /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// // Retrieve the current debug file (if any) FILE* gsGetDebugFile() { return gGSIDebugInstance.mGSIDebugFile; } #endif /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// // Set the developer callback void gsSetDebugCallback(GSIDebugCallback theCallback) { gGSIDebugInstance.mDebugCallback = theCallback; } /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// #endif // GSI_COMMON_DEBUG
/* Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ /* global angular d3 */ import { QDRFolder, QDRLeaf, QDRCore, QDRLogger, QDRTemplatePath, QDRRedirectWhenConnected } from './qdrGlobals.js'; export class OverviewController { constructor(QDRService, $scope, $log, $location, $timeout, $uibModal) { this.controllerName = 'QDR.OverviewController'; let QDRLog = new QDRLogger($log, 'OverviewController'); QDRLog.debug('QDR.OverviewControll started with location of ' + $location.path() + ' and connection of ' + QDRService.management.connection.is_connected()); let updateIntervalHandle = undefined; const updateInterval = 5000; const COLUMNSTATEKEY = 'QDRColumnKey.'; const OVERVIEWEXPANDEDKEY = 'QDROverviewExpanded'; const OVERVIEWACTIVATEDKEY = 'QDROverviewActivated'; const FILTERKEY = 'QDROverviewFilters'; const OVERVIEWMODEIDS = 'QDROverviewModeIds'; let treeRoot; // the fancytree root node. initialized once log data is received // we want attributes to be listed first, so add it at index 0 $scope.subLevelTabs = [{ content: '<i class="icon-list"></i> Attributes', title: 'View the attribute values on your selection', isValid: function () { return true; }, href: function () { return '#/attributes'; }, index: 0 }, { content: '<i class="icon-leaf"></i> Operations', title: 'Execute operations on your selection', isValid: function () { return true; }, href: function () { return '#/operations'; }, index: 1 }]; $scope.activeTab = $scope.subLevelTabs[0]; $scope.setActive = function (nav) { $scope.activeTab = nav; }; $scope.isValid = function (nav) { return nav.isValid(); }; $scope.isActive = function (nav) { return nav == $scope.activeTab; }; $scope.linkFields = []; $scope.link = null; $scope.modes = [ { title: 'Overview', name: 'Overview', right: false } ]; $scope.tmplOverviewTree = QDRTemplatePath + 'tmplOverviewTree.html'; $scope.templates = [ { name: 'Charts', url: 'overviewCharts.html' }, { name: 'Routers', url: 'routers.html' }, { name: 'Router', url: 'router.html' }, { name: 'Addresses', url: 'addresses.html' }, { name: 'Address', url: 'address.html' }, { name: 'Links', url: 'links.html' }, { name: 'Link', url: 'link.html' }, { name: 'Connections', url: 'connections.html' }, { name: 'Connection', url: 'connection.html' }, { name: 'Logs', url: 'logs.html' }, { name: 'Log', url: 'logModule.html' } ]; let topLevelChildren = []; var selectRow = function (gridApi) { if (!gridApi.selection) return; gridApi.selection.on.rowSelectionChanged($scope, function (row) { let treeKey = row.grid.options.treeKey; if (treeKey && row.entity[treeKey]) { let key = row.entity[treeKey]; $('#overtree').fancytree('getTree').activateKey(key); } }); }; $scope.routerPagingOptions = { pageSizes: [50, 100, 500], pageSize: 50, currentPage: 1 }; var getPagedData = function (pageSize, page) { $scope.totalRouters = $scope.allRouterFields.length; $scope.allRouters.showFooter = $scope.totalRouters > 50; $scope.pagedRouterFields = $scope.allRouterFields.slice((page - 1) * pageSize, page * pageSize); }; $scope.$watch('pagingOptions', function (newVal, oldVal) { if (newVal !== oldVal && newVal.currentPage !== oldVal.currentPage) { getPagedData($scope.routerPagingOptions.pageSize, $scope.routerPagingOptions.currentPage); } }, true); $scope.totalRouters = 0; $scope.allRouterFields = []; $scope.pagedRouterFields = []; $scope.allRouters = { saveKey: 'allRouters', treeKey: 'nodeId', data: 'pagedRouterFields', columnDefs: [ { field: 'id', saveKey: 'allRouters', displayName: 'Router' }, { field: 'area', displayName: 'Area' }, { field: 'mode', displayName: 'Mode' }, { field: 'connections', displayName: 'External connections' }, { field: 'addrCount', displayName: 'Address count' }, { field: 'linkCount', displayName: 'Link count' } ], enableColumnResize: true, enableHorizontalScrollbar: 0, enableVerticalScrollbar: 0, jqueryUIDraggable: true, enablePaging: true, showFooter: $scope.totalRouters > 50, totalServerItems: 'totalRouters', pagingOptions: $scope.routerPagingOptions, multiSelect: false, enableSelectAll: false, onRegisterApi: selectRow, enableSelectionBatchEvent: false, enableRowHeaderSelection: false, minRowsToShow: Math.min(QDRService.management.topology.nodeIdList().length, 50), noUnselect: true, }; // get info for all routers var allRouterInfo = function (node, callback) { let nodes = {}; // gets called each node/entity response var gotNode = function (nodeName, entity, response) { if (!nodes[nodeName]) nodes[angular.copy(nodeName)] = {}; nodes[nodeName][entity] = response; }; // send the requests for all connection and router info for all routers QDRService.management.topology.fetchAllEntities([ { entity: 'connection', attrs: ['role'] }, { entity: 'router' }], function () { // we have all the data now in the nodes object let allRouterFields = []; for (let node in nodes) { let connections = 0; for (let i = 0; i < nodes[node]['connection'].results.length; ++i) { // we only requested "role" so it will be at [0] if (nodes[node]['connection'].results[i][0] === 'inter-router') ++connections; } let routerRow = { connections: connections, nodeId: node, id: QDRService.utilities.nameFromId(node) }; nodes[node]['router'].attributeNames.forEach(function (routerAttr, i) { if (routerAttr !== 'routerId' && routerAttr !== 'id') routerRow[routerAttr] = nodes[node]['router'].results[0][i]; }); allRouterFields.push(routerRow); } $scope.allRouterFields = allRouterFields; expandGridToContent('Routers', $scope.allRouterFields.length); getPagedData($scope.routerPagingOptions.pageSize, $scope.routerPagingOptions.currentPage); updateRouterTree(nodeIds); callback(null); }, gotNode); }; $scope.routerFields = []; $scope.routerGrid = { saveKey: 'routerGrid', data: 'routerFields', columnDefs: [ { field: 'attribute', displayName: 'Attribute', saveKey: 'routerGrid', }, { field: 'value', displayName: 'Value', } ], jqueryUIDraggable: true, enableColumnResize: true, enableHorizontalScrollbar: 0, enableVerticalScrollbar: 0, minRowsToShow: 25, multiSelect: false }; $scope.router = null; // get info for a single router var routerInfo = function (node, callback) { $scope.router = node; let routerFields = []; $scope.allRouterFields.some(function (field) { if (field.id === node.title) { Object.keys(field).forEach(function (key) { let attr = (key === 'connections') ? 'External connections' : key; routerFields.push({ attribute: attr, value: field[key] }); }); return true; } }); $scope.routerFields = routerFields; expandGridToContent('Router', $scope.routerFields.length); callback(null); }; $scope.addressPagingOptions = { pageSizes: [50, 100, 500], pageSize: 50, currentPage: 1 }; var getAddressPagedData = function (pageSize, page) { $scope.totalAddresses = $scope.addressesData.length; $scope.addressesGrid.showFooter = $scope.totalAddresses > 50; $scope.pagedAddressesData = $scope.addressesData.slice((page - 1) * pageSize, page * pageSize); }; $scope.$watch('addressPagingOptions', function (newVal, oldVal) { if (newVal !== oldVal && newVal.currentPage !== oldVal.currentPage) { getAddressPagedData($scope.addressPagingOptions.pageSize, $scope.addressPagingOptions.currentPage); } }, true); $scope.totalAddresses = 0; $scope.pagedAddressesData = []; $scope.addressesData = []; $scope.selectedAddresses = []; $scope.addressesGrid = { saveKey: 'addressesGrid', treeKey: 'uid', data: 'pagedAddressesData', columnDefs: [ { field: 'address', saveKey: 'addressesGrid', displayName: 'address' }, { field: 'class', displayName: 'class' }, { field: 'phase', displayName: 'phase', cellClass: 'grid-align-value' }, { field: 'inproc', displayName: 'in-proc' }, { field: 'local', displayName: 'local', cellClass: 'grid-align-value' }, { field: 'remote', displayName: 'remote', cellClass: 'grid-align-value' }, { field: 'in', displayName: 'in', cellClass: 'grid-align-value' }, { field: 'out', displayName: 'out', cellClass: 'grid-align-value' } ], enablePaging: true, showFooter: $scope.totalAddresses > 50, totalServerItems: 'totalAddresses', pagingOptions: $scope.addressPagingOptions, enableColumnResize: true, enableHorizontalScrollbar: 0, enableVerticalScrollbar: 0, multiSelect: false, enableSelectAll: false, onRegisterApi: selectRow, enableSelectionBatchEvent: false, enableRowHeaderSelection: false, noUnselect: true }; // get info for all addresses var allAddressInfo = function (address, callback) { let nodes = {}; // gets called each node/entity response var gotNode = function (nodeName, entity, response) { if (!nodes[nodeName]) nodes[nodeName] = {}; nodes[nodeName][entity] = angular.copy(response); }; var addr_phase = function (addr) { if (!addr) return '-'; if (addr[0] == 'M') return addr[1]; return ''; }; var prettyVal = function (val) { return QDRService.utilities.pretty(val || '-'); }; let addressFields = []; let addressObjs = {}; // send the requests for all connection and router info for all routers QDRService.management.topology.fetchAllEntities({ entity: 'router.address' }, function () { for (let node in nodes) { let response = nodes[node]['router.address']; response.results.forEach(function (result) { let address = QDRService.utilities.flatten(response.attributeNames, result); var addNull = function (oldVal, newVal) { if (oldVal != null && newVal != null) return oldVal + newVal; if (oldVal != null) return oldVal; return newVal; }; let uid = address.identity; let identity = QDRService.utilities.identity_clean(uid); if (!addressObjs[QDRService.utilities.addr_text(identity) + QDRService.utilities.addr_class(identity)]) addressObjs[QDRService.utilities.addr_text(identity) + QDRService.utilities.addr_class(identity)] = { address: QDRService.utilities.addr_text(identity), 'class': QDRService.utilities.addr_class(identity), phase: addr_phase(identity), inproc: address.inProcess, local: address.subscriberCount, remote: address.remoteCount, 'in': address.deliveriesIngress, out: address.deliveriesEgress, thru: address.deliveriesTransit, toproc: address.deliveriesToContainer, fromproc: address.deliveriesFromContainer, uid: uid }; else { let sumObj = addressObjs[QDRService.utilities.addr_text(identity) + QDRService.utilities.addr_class(identity)]; sumObj.inproc = addNull(sumObj.inproc, address.inProcess); sumObj.local = addNull(sumObj.local, address.subscriberCount); sumObj.remote = addNull(sumObj.remote, address.remoteCount); sumObj['in'] = addNull(sumObj['in'], address.deliveriesIngress); sumObj.out = addNull(sumObj.out, address.deliveriesEgress); sumObj.thru = addNull(sumObj.thru, address.deliveriesTransit); sumObj.toproc = addNull(sumObj.toproc, address.deliveriesToContainer); sumObj.fromproc = addNull(sumObj.fromproc, address.deliveriesFromContainer); } }); } for (let obj in addressObjs) { addressObjs[obj].inproc = prettyVal(addressObjs[obj].inproc); addressObjs[obj].local = prettyVal(addressObjs[obj].local); addressObjs[obj].remote = prettyVal(addressObjs[obj].remote); addressObjs[obj]['in'] = prettyVal(addressObjs[obj]['in']); addressObjs[obj].out = prettyVal(addressObjs[obj].out); addressObjs[obj].thru = prettyVal(addressObjs[obj].thru); addressObjs[obj].toproc = prettyVal(addressObjs[obj].toproc); addressObjs[obj].fromproc = prettyVal(addressObjs[obj].fromproc); addressFields.push(addressObjs[obj]); } if (addressFields.length === 0) return; // update the grid's data addressFields.sort(function (a, b) { return a.address + a['class'] < b.address + b['class'] ? -1 : a.address + a['class'] > b.address + b['class'] ? 1 : 0; } ); addressFields[0].title = addressFields[0].address; for (let i = 1; i < addressFields.length; ++i) { // if this address is the same as the previous address, add a class to the display titles if (addressFields[i].address === addressFields[i - 1].address) { addressFields[i - 1].title = addressFields[i - 1].address + ' (' + addressFields[i - 1]['class'] + ')'; addressFields[i].title = addressFields[i].address + ' (' + addressFields[i]['class'] + ')'; } else addressFields[i].title = addressFields[i].address; } $scope.addressesData = addressFields; expandGridToContent('Addresses', $scope.addressesData.length); getAddressPagedData($scope.addressPagingOptions.pageSize, $scope.addressPagingOptions.currentPage); // repopulate the tree's child nodes updateAddressTree(addressFields); callback(null); }, gotNode); }; var updateLinkGrid = function (linkFields) { // apply the filter let filteredLinks = linkFields.filter(function (link) { let include = true; if ($scope.filter.endpointsOnly === 'true') { if (link.linkType !== 'endpoint') include = false; } if ($scope.filter.hideConsoles) { if (QDRService.utilities.isConsole(QDRService.management.topology.getConnForLink(link))) include = false; } return include; }); QDRLog.info('setting linkFields in updateLinkGrid'); $scope.linkFields = filteredLinks; expandGridToContent('Links', $scope.linkFields.length); getLinkPagedData($scope.linkPagingOptions.pageSize, $scope.linkPagingOptions.currentPage); // if we have a selected link if ($scope.link) { // find the selected link in the array of all links let links = $scope.linkFields.filter(function (link) { return link.name === $scope.link.data.fields.name; }); if (links.length > 0) { // linkInfo() is the function that is called by fancytree when a link is selected // It is passed a fancytree node. We need to simulate that node type to update the link grid linkInfo({ data: { title: links[0].title, fields: links[0] } }, function () { $timeout(function () { }); }); } } }; // get info for a all links $scope.linkPagingOptions = { pageSizes: [50, 100, 500], pageSize: 50, currentPage: 1 }; var getLinkPagedData = function (pageSize, page) { $scope.totalLinks = $scope.linkFields.length; $scope.linksGrid.showFooter = $scope.totalLinks > 50; $scope.pagedLinkData = $scope.linkFields.slice((page - 1) * pageSize, page * pageSize); }; $scope.$watch('linkPagingOptions', function (newVal, oldVal) { if (newVal !== oldVal && newVal.currentPage !== oldVal.currentPage) { getLinkPagedData($scope.linkPagingOptions.pageSize, $scope.linkPagingOptions.currentPage); } }, true); $scope.totalLinks = 0; $scope.pagedLinkData = []; $scope.selectedLinks = []; $scope.linksGrid = { saveKey: 'linksGrid', treeKey: 'uid', data: 'pagedLinkData', columnDefs: [ { field: 'link', displayName: 'Link', groupable: false, saveKey: 'linksGrid', width: '12%' }, { field: 'linkType', displayName: 'Link type', groupable: false, width: '8%' }, { field: 'linkDir', displayName: 'Link dir', groupable: false, width: '7%' }, { field: 'adminStatus', displayName: 'Admin status', groupable: false, width: '8%' }, { field: 'operStatus', displayName: 'Oper status', groupable: false, width: '8%' }, { field: 'deliveryCount', displayName: 'Delivery Count', groupable: false, cellClass: 'grid-align-value', width: '10%' }, { field: 'rate', displayName: 'Rate', groupable: false, cellClass: 'grid-align-value', width: '8%' }, { field: 'deliveriesDelayed10Sec', displayName: 'Delayed 10 sec', groupable: false, cellClass: 'grid-align-value', width: '8%' }, { field: 'deliveriesDelayed1Sec', displayName: 'Delayed 1 sec', groupable: false, cellClass: 'grid-align-value', width: '8%' }, { field: 'uncounts', displayName: 'Outstanding', groupable: false, cellClass: 'grid-align-value', width: '8%' }, { field: 'owningAddr', displayName: 'Address', groupable: false, width: '15%' } /*, { displayName: 'Quiesce', cellClass: 'gridCellButton', cellTemplate: '<button title="{{quiesceLinkText(row)}} this link" type="button" ng-class="quiesceLinkClass(row)" class="btn" ng-click="quiesceLink(row, $event)" ng-disabled="quiesceLinkDisabled(row)">{{quiesceLinkText(row)}}</button>', width: '10%' }*/ ], enablePaging: true, showFooter: $scope.totalLinks > 50, totalServerItems: 'totalLinks', pagingOptions: $scope.linkPagingOptions, enableColumnResize: true, enableHorizontalScrollbar: 0, enableVerticalScrollbar: 0, enableColumnReordering: true, showColumnMenu: true, rowTemplate: 'linkRowTemplate.html', minRowsToShow: 15, multiSelect: false, enableSelectAll: false, onRegisterApi: selectRow, enableSelectionBatchEvent: false, enableRowHeaderSelection: false, noUnselect: true }; $scope.$on('ngGridEventColumns', function (e, columns) { let saveInfo = columns.map(function (col) { return [col.width, col.visible]; }); let saveKey = columns[0].colDef.saveKey; if (saveKey) localStorage.setItem(COLUMNSTATEKEY + saveKey, JSON.stringify(saveInfo)); }); var allLinkInfo = function (node, callback) { var gridCallback = function (linkFields) { QDRService.management.topology.ensureAllEntities({ entity: 'connection', force: true }, function () { // only update the grid with these fields if the List tree node is selected // this is becuase we are using the link grid in other places and we don't want to overwrite it if ($scope.template.name === 'Links') updateLinkGrid(linkFields); updateLinkTree(linkFields); callback(null); }); }; getAllLinkFields([gridCallback]); }; var getAllLinkFields = function (completionCallbacks, selectionCallback) { if (!$scope.linkFields) { QDRLog.debug('$scope.linkFields was not defined!'); return; } let nodeIds = QDRService.management.topology.nodeIdList(); let linkFields = []; let now = Date.now(); var rate = function (linkName, response, result) { if (!$scope.linkFields) return 0; let oldname = $scope.linkFields.filter(function (link) { return link.link === linkName; }); if (oldname.length === 1) { let elapsed = (now - oldname[0].timestamp) / 1000; if (elapsed < 0) return 0; let delivered = QDRService.utilities.valFor(response.attributeNames, result, 'deliveryCount') - oldname[0].rawDeliveryCount; //QDRLog.debug("elapsed " + elapsed + " delivered " + delivered) return elapsed > 0 ? parseFloat(Math.round((delivered / elapsed) * 100) / 100).toFixed(2) : 0; } else { //QDRLog.debug("unable to find old linkName") return 0; } }; let expected = nodeIds.length; let received = 0; var gotLinkInfo = function (nodeName, entity, response) { if (response.results) response.results.forEach(function (result) { var prettyVal = function (field) { let fieldIndex = response.attributeNames.indexOf(field); if (fieldIndex < 0) { return '-'; } let val = result[fieldIndex]; return QDRService.utilities.pretty(val); }; var uncounts = function () { let und = QDRService.utilities.valFor(response.attributeNames, result, 'undeliveredCount'); let uns = QDRService.utilities.valFor(response.attributeNames, result, 'unsettledCount'); return QDRService.utilities.pretty(und + uns); }; var getLinkName = function () { let namestr = QDRService.utilities.nameFromId(nodeName); return namestr + ':' + QDRService.utilities.valFor(response.attributeNames, result, 'identity'); }; var fixAddress = function () { let addresses = []; let owningAddr = QDRService.utilities.valFor(response.attributeNames, result, 'owningAddr') || ''; let rawAddress = owningAddr; /* - "L*" => "* (local)" - "M0*" => "* (direct)" - "M1*" => "* (dequeue)" - "MX*" => "* (phase X)" */ let address = undefined; let starts = { 'L': '(local)', 'M0': '(direct)', 'M1': '(dequeue)' }; for (let start in starts) { if (owningAddr.startsWith(start)) { let ends = owningAddr.substr(start.length); address = ends + ' ' + starts[start]; rawAddress = ends; break; } } if (!address) { // check for MX* if (owningAddr.length > 3) { if (owningAddr[0] === 'M') { let phase = parseInt(owningAddr.substr(1)); if (phase && !isNaN(phase)) { let phaseStr = phase + ''; let star = owningAddr.substr(2 + phaseStr.length); address = star + ' ' + '(phase ' + phaseStr + ')'; } } } } addresses[0] = address || owningAddr; addresses[1] = rawAddress; return addresses; }; if (!selectionCallback || selectionCallback(response, result)) { let adminStatus = QDRService.utilities.valFor(response.attributeNames, result, 'adminStatus'); let operStatus = QDRService.utilities.valFor(response.attributeNames, result, 'operStatus'); let linkName = getLinkName(); let linkType = QDRService.utilities.valFor(response.attributeNames, result, 'linkType'); let addresses = fixAddress(); let link = QDRService.utilities.flatten(response.attributeNames, result); // rate: QDRService.utilities.pretty(rate(linkName, response, result)), linkFields.push({ link: linkName, title: linkName, uncounts: uncounts(), operStatus: operStatus, adminStatus: adminStatus, owningAddr: addresses[0], acceptedCount: prettyVal('acceptedCount'), modifiedCount: prettyVal('modifiedCount'), presettledCount: prettyVal('presettledCount'), rejectedCount: prettyVal('rejectedCount'), releasedCount: prettyVal('releasedCount'), deliveryCount: prettyVal('deliveryCount') + ' ', rate: prettyVal('settleRate'), deliveriesDelayed10Sec: prettyVal('deliveriesDelayed10Sec'), deliveriesDelayed1Sec: prettyVal('deliveriesDelayed1Sec'), capacity: link.capacity, undeliveredCount: link.undeliveredCount, unsettledCount: link.unsettledCount, rawAddress: addresses[1], rawDeliveryCount: link.deliveryCount, name: link.name, linkName: link.linkName, connectionId: link.connectionId, linkDir: link.linkDir, linkType: linkType, peer: link.peer, type: link.type, uid: linkName, timestamp: now, nodeId: nodeName, identity: link.identity, }); } }); if (expected === ++received) { linkFields.sort(function (a, b) { return a.link < b.link ? -1 : a.link > b.link ? 1 : 0; }); completionCallbacks.forEach(function (cb) { cb(linkFields); }); } }; nodeIds.forEach(function (nodeId) { QDRService.management.topology.fetchEntity(nodeId, 'router.link', [], gotLinkInfo); }); }; $scope.connectionPagingOptions = { pageSizes: [50, 100, 500], pageSize: 50, currentPage: 1 }; var getConnectionPagedData = function (pageSize, page) { $scope.totalConnections = $scope.allConnectionFields.length; $scope.allConnectionGrid.showFooter = $scope.totalConnections > 50; $scope.pagedConnectionsData = $scope.allConnectionFields.slice((page - 1) * pageSize, page * pageSize); }; $scope.$watch('connectionPagingOptions', function (newVal, oldVal) { if (newVal !== oldVal && newVal.currentPage !== oldVal.currentPage) { getConnectionPagedData($scope.connectionPagingOptions.pageSize, $scope.connectionPagingOptions.currentPage); } }, true); $scope.totalConnections = 0; $scope.pagedConnectionsData = []; $scope.allConnectionFields = []; $scope.allConnectionSelections = []; $scope.allConnectionGrid = { saveKey: 'allConnGrid', treeKey: 'uid', data: 'pagedConnectionsData', columnDefs: [ { field: 'host', saveKey: 'allConnGrid', displayName: 'host' }, { field: 'container', displayName: 'container' }, { field: 'role', displayName: 'role' }, { field: 'dir', displayName: 'dir' }, { field: 'security', displayName: 'security' }, { field: 'authentication', displayName: 'authentication' }, ], enablePaging: true, showFooter: $scope.totalConnections > 50, totalServerItems: 'totalConnections', pagingOptions: $scope.connectionPagingOptions, enableColumnResize: true, enableHorizontalScrollbar: 0, enableVerticalScrollbar: 0, multiSelect: false, enableSelectAll: false, onRegisterApi: selectRow, enableSelectionBatchEvent: false, enableRowHeaderSelection: false, noUnselect: true }; // get info for a all connections var allConnectionInfo = function (connection, callback) { getAllConnectionFields([updateConnectionGrid, updateConnectionTree, function () { callback(null); }]); }; // called after conection data is available var updateConnectionGrid = function (connectionFields) { $scope.allConnectionFields = connectionFields; expandGridToContent('Connections', $scope.allConnectionFields.length); getConnectionPagedData($scope.connectionPagingOptions.pageSize, $scope.connectionPagingOptions.currentPage); }; // get the connection data for all nodes // called periodically // creates a connectionFields array and calls the callbacks (updateTree and updateGrid) var getAllConnectionFields = function (callbacks) { let nodeIds = QDRService.management.topology.nodeIdList(); let connectionFields = []; let expected = nodeIds.length; let received = 0; let gotConnectionInfo = function (nodeName, entity, response) { response.results.forEach(function (result) { let auth = 'no_auth'; let connection = QDRService.utilities.flatten(response.attributeNames, result); let sasl = connection.sasl; if (connection.isAuthenticated) { auth = sasl; if (sasl === 'ANONYMOUS') auth = 'anonymous-user'; else { if (sasl === 'GSSAPI') sasl = 'Kerberos'; if (sasl === 'EXTERNAL') sasl = 'x.509'; auth = connection.user + '(' + connection.sslCipher + ')'; } } let sec = 'no-security'; if (connection.isEncrypted) { if (sasl === 'GSSAPI') sec = 'Kerberos'; else sec = connection.sslProto + '(' + connection.sslCipher + ')'; } let host = connection.host; let connField = { host: host, security: sec, authentication: auth, routerId: nodeName, uid: host + connection.container + connection.identity }; response.attributeNames.forEach(function (attribute, i) { connField[attribute] = result[i]; }); connectionFields.push(connField); }); if (expected === ++received) { connectionFields.sort(function (a, b) { return a.host + a.container + a.identity < b.host + b.container + b.identity ? -1 : a.host + a.container + a.identity > b.host + b.container + b.identity ? 1 : 0; }); callbacks.forEach(function (cb) { cb(connectionFields); }); } }; nodeIds.forEach(function (nodeId) { QDRService.management.topology.fetchEntity(nodeId, 'connection', [], gotConnectionInfo); }); }; $scope.addressFields = []; $scope.addressGrid = { saveKey: 'addGrid', data: 'addressFields', columnDefs: [ { field: 'attribute', displayName: 'Attribute', saveKey: 'addGrid', width: '40%' }, { field: 'value', displayName: 'Value', width: '40%' } ], enableColumnResize: true, enableHorizontalScrollbar: 0, enableVerticalScrollbar: 0, minRowsToShow: 11, jqueryUIDraggable: true, multiSelect: false }; // get info for a single address var addressInfo = function (address, callback) { $scope.address = address; let currentEntity = getCurrentLinksEntity(); // we are viewing the addressLinks page if (currentEntity === 'Address' && entityModes[currentEntity].currentModeId === 'links') { updateModeLinks(); callback(null); return; } $scope.addressFields = []; let fields = Object.keys(address.data.fields); fields.forEach(function (field) { if (field != 'title' && field != 'uid') $scope.addressFields.push({ attribute: field, value: address.data.fields[field] }); }); expandGridToContent('Address', $scope.addressFields.length); callback(null); }; $scope.singleLinkFields = []; $scope.linkGrid = { saveKey: 'linkGrid', data: 'singleLinkFields', columnDefs: [ { field: 'attribute', displayName: 'Attribute', width: '40%' }, { field: 'value', displayName: 'Value', width: '40%' } ], enableColumnResize: true, enableHorizontalScrollbar: 0, enableVerticalScrollbar: 0, minRowsToShow: 24, jqueryUIDraggable: true, multiSelect: false }; // display the grid detail info for a single link var linkInfo = function (link, callback) { if (!link) { callback(null); return; } $scope.link = link; $scope.singleLinkFields = []; let fields = Object.keys(link.data.fields); let excludeFields = ['title', 'uid', 'uncounts', 'rawDeliveryCount', 'timestamp', 'rawAddress']; fields.forEach(function (field) { if (excludeFields.indexOf(field) == -1) $scope.singleLinkFields.push({ attribute: field, value: link.data.fields[field] }); }); expandGridToContent('Link', $scope.singleLinkFields.length); callback(null); }; // get info for a single connection $scope.gridModes = [{ content: '<a><i class="icon-list"></i> Attributes</a>', id: 'attributes', title: 'View attributes' }, { content: '<a><i class="icon-link"></i> Links</a>', id: 'links', title: 'Show links' } ]; var saveModeIds = function () { let modeIds = { Address: entityModes.Address.currentModeId, Connection: entityModes.Connection.currentModeId }; localStorage[OVERVIEWMODEIDS] = JSON.stringify(modeIds); }; var loadModeIds = function () { return angular.fromJson(localStorage[OVERVIEWMODEIDS]) || { Address: 'attributes', Connection: 'attributes' }; }; var savedModeIds = loadModeIds(); let entityModes = { Address: { currentModeId: savedModeIds.Address, filter: function (response, result) { let owningAddr = QDRService.utilities.valFor(response.attributeNames, result, 'owningAddr'); return (owningAddr === $scope.address.data.fields.uid); } }, Connection: { currentModeId: savedModeIds.Connection, filter: function (response, result) { let connectionId = QDRService.utilities.valFor(response.attributeNames, result, 'connectionId'); return (connectionId === $scope.connection.data.fields.identity); } } }; $scope.selectMode = function (mode, entity) { if (!mode || !entity) return; entityModes[entity].currentModeId = mode.id; saveModeIds(); if (mode.id === 'links') { $scope.linkFields = []; getLinkPagedData($scope.linkPagingOptions.pageSize, $scope.linkPagingOptions.currentPage); updateModeLinks(); } updateExpanded(); }; $scope.isModeSelected = function (mode, entity) { return mode.id === entityModes[entity].currentModeId; }; $scope.isModeVisible = function (entity, id) { return entityModes[entity].currentModeId === id; }; var updateEntityLinkGrid = function (linkFields) { $scope.linkFields = linkFields; expandGridToContent('Link', $scope.linkFields.length); getLinkPagedData($scope.linkPagingOptions.pageSize, $scope.linkPagingOptions.currentPage); }; // based on which entity is selected, get and filter the links var updateModeLinks = function () { let currentEntity = getCurrentLinksEntity(); if (!currentEntity) return; getAllLinkFields([updateEntityLinkGrid], entityModes[currentEntity].filter); }; var getCurrentLinksEntity = function () { let currentEntity; let active = $('#overtree').fancytree('getActiveNode'); if (active) { currentEntity = active.type ? active.type : active.data.fields.type; } return currentEntity; }; $scope.quiesceLinkClass = function (row) { let stateClassMap = { enabled: 'btn-primary', disabled: 'btn-danger' }; return stateClassMap[row.entity.adminStatus]; }; $scope.quiesceLink = function (row, $event) { $event.stopPropagation(); QDRService.management.topology.quiesceLink(row.entity.nodeId, row.entity.name) .then(function (results, context) { let statusCode = context.message.application_properties.statusCode; if (statusCode < 200 || statusCode >= 300) { QDRCore.notification('error', context.message.statusDescription); QDRLog.error('Error ' + context.message.statusDescription); } }); }; $scope.quiesceLinkDisabled = function (row) { return (row.entity.operStatus !== 'up' && row.entity.operStatus !== 'down'); }; $scope.quiesceLinkText = function (row) { return row.entity.adminStatus === 'disabled' ? 'Revive' : 'Quiesce'; }; $scope.expandAll = function () { $('#overtree').fancytree('getRoot').visit(function (node) { node.expand(true); }); }; $scope.contractAll = function () { $('#overtree').fancytree('getRoot').visit(function (node) { node.expand(false); }); }; $scope.connectionFields = []; $scope.connectionGrid = { saveKey: 'connGrid', data: 'connectionFields', columnDefs: [ { field: 'attribute', displayName: 'Attribute', saveKey: 'connGrid', width: '40%' }, { field: 'value', displayName: 'Value', width: '40%' } ], enableColumnResize: true, enableHorizontalScrollbar: 0, enableVerticalScrollbar: 0, minRowsToShow: 21, jqueryUIDraggable: true, multiSelect: false }; var connectionInfo = function (connection, callback) { if (!connection) { callback(null); return; } $scope.connection = connection; let currentEntity = getCurrentLinksEntity(); // we are viewing the connectionLinks page if (currentEntity === 'Connection' && entityModes[currentEntity].currentModeId === 'links') { updateModeLinks(); callback(null); return; } $scope.connectionFields = []; for (let field in connection.data.fields) { if (field != 'title' && field != 'uid') $scope.connectionFields.push({ attribute: field, value: connection.data.fields[field] }); } expandGridToContent('Connection', $scope.connectionFields.length); callback(null); }; const logModuleCellTemplate = '<div class="ui-grid-cell-contents" ng-click="grid.appScope.logInfoFor(row, col)">{{COL_FIELD CUSTOM_FILTERS | pretty}}</div>'; $scope.logModule = {}; $scope.logModuleSelected = []; $scope.logModuleData = []; $scope.logModuleGrid = { data: 'logModuleData', columnDefs: [ { field: 'nodeName', displayName: 'Router', }, { field: 'enable', displayName: 'Enable level', }, { field: 'noticeCount', displayName: 'Notice', cellTemplate: logModuleCellTemplate, cellClass: 'grid-align-value', }, { field: 'infoCount', displayName: 'Info', cellTemplate: logModuleCellTemplate, cellClass: 'grid-align-value', }, { field: 'traceCount', displayName: 'Trace', cellTemplate: logModuleCellTemplate, cellClass: 'grid-align-value', }, { field: 'debugCount', displayName: 'Debug', cellTemplate: logModuleCellTemplate, cellClass: 'grid-align-value', }, { field: 'warningCount', displayName: 'Warning', cellTemplate: logModuleCellTemplate, cellClass: 'grid-align-value', }, { field: 'errorCount', displayName: 'Error', cellTemplate: logModuleCellTemplate, cellClass: 'grid-align-value', }, { field: 'criticalCount', displayName: 'Critical', cellTemplate: logModuleCellTemplate, cellClass: 'grid-align-value', }, ], enableColumnResize: true, enableHorizontalScrollbar: 0, enableVerticalScrollbar: 0, jqueryUIDraggable: true, multiSelect: false, enableSelectAll: false, onRegisterApi: selectRow, enableSelectionBatchEvent: false, enableRowHeaderSelection: false, minRowsToShow: Math.min(QDRService.management.topology.nodeIdList().length, 50), noUnselect: true }; $scope.logInfoFor = function (row, col) { logDialog(row, col); }; function logDialog(row, col) { let d = $uibModal.open({ animation: true, templateUrl: 'viewLogs.html', controller: 'QDR.OverviewLogsController', resolve: { nodeName: function () { return row.entity.nodeName; }, module: function () { return row.entity.name; }, level: function () { return col.displayName; }, nodeId: function () { return row.entity.nodeId; }, } }); d.result.then(function () { QDRLog.debug('d.open().then'); }, function () { QDRLog.debug('Modal dismissed at: ' + new Date()); }); } const numberTemplate = '<div class="ngCellText" ng-class="col.colIndex()"><span ng-cell-text>{{COL_FIELD | pretty}}</span></div>'; $scope.allLogFields = []; $scope.allLogSelections = []; $scope.allLogGrid = { saveKey: 'allLogGrid', treeKey: 'name', data: 'allLogFields', columnDefs: [ { field: 'name', saveKey: 'allLogGrid', displayName: 'Module' }, { field: 'noticeCount', displayName: 'Notice', cellTemplate: numberTemplate, cellClass: 'grid-align-value', }, { field: 'infoCount', displayName: 'Info', cellTemplate: numberTemplate, cellClass: 'grid-align-value', }, { field: 'traceCount', displayName: 'Trace', cellTemplate: numberTemplate, cellClass: 'grid-align-value', }, { field: 'debugCount', displayName: 'Debug', cellTemplate: numberTemplate, cellClass: 'grid-align-value', }, { field: 'warningCount', displayName: 'Warning', cellTemplate: numberTemplate, cellClass: 'grid-align-value', }, { field: 'errorCount', displayName: 'Error', cellTemplate: numberTemplate, cellClass: 'grid-align-value', }, { field: 'criticalCount', displayName: 'Critical', cellTemplate: numberTemplate, cellClass: 'grid-align-value', }, ], //enableCellSelection: true, enableColumnResize: true, enableHorizontalScrollbar: 0, enableVerticalScrollbar: 0, minRowsToShow: 17, multiSelect: false, enableSelectAll: false, onRegisterApi: selectRow, enableSelectionBatchEvent: false, enableRowHeaderSelection: false, noUnselect: true }; let allLogEntries = {}; var allLogInfo = function (log, callback) { // update the count of entries for each module $scope.allLogFields = []; let logResults = {}; let logDetails = {}; var gotLogStats = function (node, entity, response) { logDetails[node] = []; response.results.forEach(function (result) { let oresult = QDRService.utilities.flatten(response.attributeNames, result); // make a copy for the details grid since logResults has the same object reference logDetails[node].push(angular.copy(oresult)); if (!(oresult.name in logResults)) { logResults[oresult.name] = oresult; } else { response.attributeNames.forEach(function (attr, i) { if (attr.substr(attr.length - 5) === 'Count') { logResults[oresult.name][attr] += result[i]; } }); } }); }; var gotAllLogStats = function () { let sortedModules = Object.keys(logResults); sortedModules.sort(function (a, b) { return a < b ? -1 : a > b ? 1 : 0; }); $scope.allLogFields = []; sortedModules.forEach(function (module) { $scope.allLogFields.push(logResults[module]); }); expandGridToContent('Logs', $scope.allLogFields.length); allLogEntries = logDetails; updateLogTree($scope.allLogFields); callback(null); }; QDRService.management.topology.fetchAllEntities({ entity: 'logStats' }, gotAllLogStats, gotLogStats); }; var expandGridToContent = function (type, rows) { let tree = $('#overtree').fancytree('getTree'); let node = null; if (tree && tree.getActiveNode) node = tree.getActiveNode(); if (node) { if (node.type === type || node.data.type === type) { let height = (rows + 1) * 30 + 46; // header is 40px let gridDetails = $('#overview-controller .grid'); gridDetails.css('height', height + 'px'); } } }; $scope.logFields = []; // get info for a single log var logInfo = function (node, callback) { var gotLogInfo = function (responses) { $scope.logModuleData = []; $scope.logModule.module = node.key; for (let n in responses) { let moduleIndex = responses[n]['log'].attributeNames.indexOf('module'); let result = responses[n]['log'].results.filter(function (r) { return r[moduleIndex] === node.key; })[0]; let logInfo = QDRService.utilities.flatten(responses[n]['log'].attributeNames, result); let entry = allLogEntries[n]; entry.forEach(function (module) { if (module.name === node.key) { module.nodeName = QDRService.utilities.nameFromId(n); module.nodeId = n; module.enable = logInfo.enable; $scope.logModuleData.push(module); } }); } $scope.logModuleData.sort(function (a, b) { return a.nodeName < b.nodeName ? -1 : a.nodeName > b.nodeName ? 1 : 0; }); expandGridToContent('Log', $scope.logModuleData.length); callback(null); }; QDRService.management.topology.fetchAllEntities({ entity: 'log', attrs: ['module', 'enable'] }, gotLogInfo); }; var getExpandedList = function () { if (!treeRoot) return; let list = []; if (treeRoot.visit) { treeRoot.visit(function (node) { if (node.isExpanded()) { list.push(node.data.parentKey); } }); } return list; }; // loads the tree node name that was last selected var loadActivatedNode = function () { return localStorage[OVERVIEWACTIVATEDKEY] || 'Routers'; }; // saved the tree node name that is currently selected var saveActivated = function (key) { localStorage[OVERVIEWACTIVATEDKEY] = key; }; // loads list that was saved var loadExpandedNodeList = function () { return angular.fromJson(localStorage[OVERVIEWEXPANDEDKEY]) || []; }; // called when a node is expanded // here we save the expanded node so it can be restored when the page reloads var saveExpanded = function () { let list = getExpandedList(); localStorage[OVERVIEWEXPANDEDKEY] = JSON.stringify(list); expandedNodeList = list; }; var setTemplate = function (node) { let type = node.type; let template = $scope.templates.filter(function (tpl) { return tpl.name == type; }); $timeout(function () { $scope.template = template[0]; }); }; // activated is called each time a tree node is clicked // based on which node is clicked, load the correct data grid template and start getting the data var onTreeNodeActivated = function (event, data) { saveExpanded(); saveActivated(data.node.key); $scope.ActivatedKey = data.node.key; setTemplate(data.node); updateExpanded(); }; var onTreeNodeExpanded = function () { saveExpanded(); updateExpanded(); }; var onTreeNodeCollapsed = function () { saveExpanded(); }; if (!QDRService.management.connection.is_connected()) { QDRRedirectWhenConnected($location, 'overview'); return; } $scope.template = $scope.templates[0]; /* -------------------------------------------------- * * setup the tree on the left * * ------------------------------------------------- */ var getActiveChild = function (node) { let active = node.children.filter(function (child) { return child.isActive(); }); if (active.length > 0) return active[0].key; return null; }; // utility function called by each top level tree node when it needs to populate its child nodes var updateLeaves = function (leaves, entity, worker) { let tree = $('#overtree').fancytree('getTree'), node; if (tree && tree.getNodeByKey) { node = tree.getNodeByKey(entity); } if (!tree || !node) { return; } let wasActive = node.isActive(); let wasExpanded = node.isExpanded(); let activeChildKey = getActiveChild(node); node.removeChildren(); let children = []; leaves.forEach(function (leaf) { children.push(worker(leaf)); }); node.addNode(children); // top level node was expanded if (wasExpanded) node.setExpanded(true, { noAnimation: true, noEvents: true }); if (wasActive) { node.setActive(true, { noAnimation: true, noEvents: true }); } else { // re-active the previously active child node if (activeChildKey) { let newNode = tree.getNodeByKey(activeChildKey); // the node may not be there after the update if (newNode) newNode.setActive(true, { noAnimation: true, noEvents: true }); // fires the onTreeNodeActivated event for this node } } resizer(); }; var resizer = function () { // this forces the tree and the grid to be the size of the browser window. // the effect is that the tree and the grid will have vertical scroll bars if needed. // the alternative is to let the tree and grid determine the size of the page and have // the scroll bar on the window //let viewport = $('#overview-controller .pane-viewport'); //viewport.height( window.innerHeight - viewport.offset().top); // don't allow HTML in the tree titles $('.fancytree-title').each(function () { let unsafe = $(this).html(); $(this).html(unsafe.replace(/</g, '&lt;').replace(/>/g, '&gt;')); }); // remove the comments to allow the tree to take all the height it needs let gridDetails = $('#overview-controller .grid'); if (gridDetails.offset()) gridDetails.height(window.innerHeight - gridDetails.offset().top); let gridViewport = $('#overview-controller .ui-grid-viewport'); if (gridViewport.offset()) gridViewport.height(window.innerHeight - gridViewport.offset().top); //gridViewport. }; $(window).resize(resizer); // get saved tree state $scope.ActivatedKey = loadActivatedNode(); let expandedNodeList = loadExpandedNodeList(); var showCharts = function () { }; let charts = new QDRFolder('Charts'); charts.info = { fn: showCharts }; charts.type = 'Charts'; // for the charts template charts.key = 'Charts'; charts.extraClasses = 'charts'; topLevelChildren.push(charts); // create a routers tree branch let routers = new QDRFolder('Routers'); routers.type = 'Routers'; routers.info = { fn: allRouterInfo }; routers.expanded = (expandedNodeList.indexOf('Routers') > -1); routers.key = 'Routers'; routers.parentKey = 'Routers'; routers.extraClasses = 'routers'; topLevelChildren.push(routers); // called when the list of routers changes var updateRouterTree = function (nodes) { var worker = function (node) { let name = QDRService.utilities.nameFromId(node); let router = new QDRLeaf(name); router.type = 'Router'; router.info = { fn: routerInfo }; router.nodeId = node; router.key = node; router.extraClasses = 'router'; router.parentKey = 'Routers'; return router; }; updateLeaves(nodes, 'Routers', worker); }; // create an addresses tree branch let addresses = new QDRFolder('Addresses'); addresses.type = 'Addresses'; addresses.info = { fn: allAddressInfo }; addresses.expanded = (expandedNodeList.indexOf('Addresses') > -1); addresses.key = 'Addresses'; addresses.parentKey = 'Addresses'; addresses.extraClasses = 'addresses'; topLevelChildren.push(addresses); var updateAddressTree = function (addressFields) { var worker = function (address) { let a = new QDRLeaf(address.title); a.info = { fn: addressInfo }; a.key = address.uid; a.fields = address; a.type = 'Address'; a.tooltip = address['class'] + ' address'; if (address.address === '$management') a.tooltip = 'internal ' + a.tooltip; a.extraClasses = a.tooltip; a.parentKey = 'Addresses'; return a; }; updateLeaves(addressFields, 'Addresses', worker); }; $scope.$watch('filter', function (newValue, oldValue) { if (newValue !== oldValue) { allLinkInfo(null, function () { $timeout(function () { }); }); localStorage[FILTERKEY] = JSON.stringify($scope.filter); } }, true); $scope.filterToggle = function () { let filter = $('#linkFilter'); filter.toggle(); }; $scope.filter = angular.fromJson(localStorage[FILTERKEY]) || { endpointsOnly: 'true', hideConsoles: true }; let links = new QDRFolder('Links'); links.type = 'Links'; links.info = { fn: allLinkInfo }; links.expanded = (expandedNodeList.indexOf('Links') > -1); links.key = 'Links'; links.parentKey = 'Links'; links.extraClasses = 'links'; topLevelChildren.push(links); // called both before the tree is created and whenever a background update is done var updateLinkTree = function (linkFields) { var worker = function (link) { let l = new QDRLeaf(link.title); let isConsole = QDRService.utilities.isConsole(QDRService.management.topology.getConnForLink(link)); l.info = { fn: linkInfo }; l.key = link.uid; l.fields = link; l.type = 'Link'; l.parentKey = 'Links'; if (isConsole) l.tooltip = 'console link'; else l.tooltip = link.linkType + ' link'; l.extraClasses = l.tooltip; return l; }; updateLeaves(linkFields, 'Links', worker); }; let connections = new QDRFolder('Connections'); connections.type = 'Connections'; connections.info = { fn: allConnectionInfo }; connections.expanded = (expandedNodeList.indexOf('Connections') > -1); connections.key = 'Connections'; connections.parentKey = 'Connections'; connections.extraClasses = 'connections'; topLevelChildren.push(connections); var updateConnectionTree = function (connectionFields) { var worker = function (connection) { let host = connection.host; if (connection.name === 'connection/' && connection.role === 'inter-router' && connection.host === '') host = connection.container + ':' + connection.identity; let c = new QDRLeaf(host); let isConsole = QDRService.utilities.isAConsole(connection.properties, connection.identity, connection.role, connection.routerId); c.type = 'Connection'; c.info = { fn: connectionInfo }; c.key = connection.uid; c.fields = connection; if (isConsole) c.tooltip = 'console connection'; else c.tooltip = connection.role === 'inter-router' ? 'inter-router connection' : 'external connection'; c.extraClasses = c.tooltip; c.parentKey = 'Connections'; return c; }; updateLeaves(connectionFields, 'Connections', worker); }; var updateLogTree = function (logFields) { var worker = function (log) { let l = new QDRLeaf(log.name); l.type = 'Log'; l.info = { fn: logInfo }; l.key = log.name; l.parentKey = 'Logs'; l.extraClasses = 'log'; return l; }; updateLeaves(logFields, 'Logs', worker); }; let htmlReady = false; let dataReady = false; $scope.largeNetwork = QDRService.management.topology.isLargeNetwork(); let logs = new QDRFolder('Logs'); logs.type = 'Logs'; logs.info = { fn: allLogInfo }; logs.expanded = (expandedNodeList.indexOf('Logs') > -1); logs.key = 'Logs'; logs.parentKey = 'Logs'; if (QDRService.management.connection.versionCheck('0.8.0')) topLevelChildren.push(logs); var onTreeInitialized = function (event, data) { treeRoot = data.tree; let activeNode = treeRoot.getNodeByKey($scope.ActivatedKey); if (activeNode) activeNode.setActive(true); updateExpanded(); }; var initTreeAndGrid = function () { if (!htmlReady || !dataReady) return; let div = angular.element('#overtree'); if (!div.width()) { setTimeout(initTreeAndGrid, 100); return; } $('#overtree').fancytree({ activate: onTreeNodeActivated, expand: onTreeNodeExpanded, collapse: onTreeNodeCollapsed, init: onTreeInitialized, autoCollapse: $scope.largeNetwork, activeVisible: !$scope.largeNetwork, clickFolderMode: 1, source: topLevelChildren }); }; $scope.overviewLoaded = function () { htmlReady = true; initTreeAndGrid(); }; let nodeIds = QDRService.management.topology.nodeIdList(); // add placeholders for the top level tree nodes let topLevelTreeNodes = [routers, addresses, links, connections, logs]; topLevelTreeNodes.forEach(function (parent) { let placeHolder = new QDRLeaf('loading...'); placeHolder.extraClasses = 'loading'; parent.children = [placeHolder]; }); var updateExpanded = function () { QDRLog.debug('updateExpandedEntities'); clearTimeout(updateIntervalHandle); let tree = $('#overtree').fancytree('getTree'); if (tree && tree.visit) { let q = d3.queue(10); tree.visit(function (node) { if (node.isActive() || node.isExpanded()) { q.defer(node.data.info.fn, node); } }); q.await(function (error) { if (error) QDRLog.error(error.message); // if there are no active nodes, activate the saved one let tree = $('#overtree').fancytree('getTree'); if (!tree.getActiveNode()) { let active = tree.getNodeByKey($scope.ActivatedKey); if (active) { active.setActive(true); } else { tree.getNodeByKey('Routers').setActive(true); } } // fancytree animations sometimes stop short of shrinking its placeholder spans d3.selectAll('.ui-effects-placeholder').style('height', '0px'); // once all expanded tree nodes have been update, schedule another update $timeout(function () { updateIntervalHandle = setTimeout(updateExpanded, updateInterval); }); }); } }; dataReady = true; initTreeAndGrid(); $scope.$on('$destroy', function () { clearTimeout(updateIntervalHandle); $(window).off('resize', resizer); }); } } OverviewController.$inject = ['QDRService', '$scope', '$log', '$location', '$timeout', '$uibModal'];
/***************************************************************************** * * Copyright Next-Generation System Software Research Group, All rights reserved. * Future Computing Research Division, Artificial Intelligence Reserch Laboratory * Electronics and Telecommunications Research Institute (ETRI) * * THESE DOCUMENTS CONTAIN CONFIDENTIAL INFORMATION AND KNOWLEDGE * WHICH IS THE PROPERTY OF ETRI. NO PART OF THIS PUBLICATION IS * TO BE USED FOR ANY OTHER PURPOSE, AND THESE ARE NOT TO BE * REPRODUCED, COPIED, DISCLOSED, TRANSMITTED, STORED IN A RETRIEVAL * SYSTEM OR TRANSLATED INTO ANY OTHER HUMAN OR COMPUTER LANGUAGE, * IN ANY FORM, BY ANY MEANS, IN WHOLE OR IN PART, WITHOUT THE * COMPLETE PRIOR WRITTEN PERMISSION OF ETRI. * * LICENSE file : README_LICENSE_ETRI located in the top directory * *****************************************************************************/ #include <stdio.h> #include <stdlib.h> #include "os_sched.h" #include "task.h" #include "queue.h" /* management of tables */ const unsigned int map_table[16] = {0x0001, 0x0002, 0x0004, 0x0008, 0x0010, 0x0020, 0x0040, 0x0080, 0x0100, 0x0200, 0x0400, 0x0800, 0x1000, 0x2000, 0x4000, 0x8000}; const unsigned int unmap_table[256] = {0,0,1,1,2,2,2,2,3,3,3,3,3,3,3,3, 4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4, 5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5, 5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5, 6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6, 6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6, 6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6, 6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6, 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7}; static void cal_highest_task(OsSched *sched) { unsigned int x, y; // find y y = sched->ready_group; if (y>>8) // upper nibble { y = (unsigned int)(unmap_table[y>>8] + 8); } else { y = unmap_table[y & 0xff]; // lower nibble } // find x x = sched->ready_table[y]; if (x>>8) // upper nibble { x = (unsigned int)(unmap_table[x>>8] + 8); } else { x = unmap_table[x & 0xff]; // lower nibble } unsigned int prio; prio = (y << 4) + x; sched->highest = (Task *) sched->ready_queue[prio].head; } static void sched_qpush(OsSched *sched, Task *task) { pthread_mutex_lock(&sched->lock); unsigned int prio = task->priority; Queue *q = &sched->ready_queue[prio]; if (q->is_empty(q)) { sched->ready_group |= map_table[prio >> 4]; sched->ready_table[prio >> 4] |= map_table[prio & 0x0f]; } /* enqueue error cannot occur already queue is checked if it is full */ q->push(q, task); task->state = TS_READY; cal_highest_task(sched); //sched->num_ready_tasks++; pthread_mutex_unlock(&sched->lock); } static void sched_qremove(OsSched *sched, Task *task) { pthread_mutex_lock(&sched->lock); unsigned int prio = task->priority; Queue *q = &sched->ready_queue[prio]; q->delete(q, task); if (q->is_empty(q)) { if ((sched->ready_table[prio >> 4] &= (unsigned int)(~map_table[prio & 0x0f])) == 0) { sched->ready_group &= (unsigned int)(~map_table[prio >> 4]); } } task->state = TS_DORMANT; cal_highest_task(sched); //sched->num_ready_tasks--; pthread_mutex_unlock(&sched->lock); } OsSched *os_sched_create(void) { OsSched *sched; sched = (OsSched *) malloc(sizeof(OsSched)); if (!sched) { printf("Error: os_sched object cannot be created\n"); exit(1); } // init included sched->highest = NULL; sched->current = NULL; sched->ready_group = 0; for (int i=0; i<16; i++) { sched->ready_table[i] = 0; } for (int i=0; i<256; i++) { queue_init(&sched->ready_queue[i]); } sched->push = sched_qpush; sched->remove = sched_qremove; pthread_mutex_init(&sched->lock, NULL); return sched; }
""" Functions to calculate stats/hists of the relative energy resolution. The relative energy resolution is defined as (Reco - True) / True. """ from cafplot.rhist import RHist1D from .stats import calc_all_stats def calc_fom_hist(pred, true, weights, bins, range): """Calculate relative energy resolution histogram. Parameters ---------- pred : ndarray, shape (N,) Array of predicted energies. true : ndarray, shape (N,) Array of true energies. weights : ndarray, shape (N,) Array of sample weights. bins : int or ndarray If int then defined the number of bins in a histogram. If ndarray then `bins` defines edges of the histogram. C.f. `np.histogram` range : (float, float) or None Range of a histogram (lower, upper). If None, range will be determined according to the `np.histogram` rules. Returns ------- cafplot.RHist1D `Rhist1D` object containing the relative energy resolution histogram. """ # pylint: disable=redefined-builtin fom = (pred - true) / true return RHist1D.from_data(fom, bins, weights, range) def calc_fom_stats(pred, true, weights, range = (-1, 1)): """Calculate relative energy resolution statistics. Parameters ---------- pred : ndarray, shape (N,) Array of predicted energies. true : ndarray, shape (N,) Array of true energies. weights : ndarray, shape (N,) Array of sample weights. range : (float, float) Range of energy resolution values that will be used in calculation of statistics. Useful to remove outliers. Returns ------- dict Dictionary where keys are the names of various statistics and values are the values of corresponding stats. See Also -------- calc_all_stats """ # pylint: disable=redefined-builtin fom = (pred - true) / true mask = ((fom > range[0]) & (fom < range[1])) return calc_all_stats(fom[mask], weights[mask])
/*----------------------------------------------------------------------------*/ /* Copyright (c) 2017-2018 FIRST. All Rights Reserved. */ /* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ /* the project. */ /*----------------------------------------------------------------------------*/ #pragma once #include <Commands/Command.h> #include <Commands/Scheduler.h> #include <IterativeRobot.h> #include <LiveWindow/LiveWindow.h> #include <SmartDashboard/SmartDashboard.h> #include "Commands/Autonomous.h" #include "OI.h" #include "Subsystems/Claw.h" #include "Subsystems/DriveTrain.h" #include "Subsystems/Elevator.h" #include "Subsystems/Wrist.h" class Robot : public frc::IterativeRobot { public: static DriveTrain drivetrain; static Elevator elevator; static Wrist wrist; static Claw claw; static OI oi; private: Autonomous m_autonomousCommand; frc::LiveWindow& m_lw = *frc::LiveWindow::GetInstance(); void RobotInit() override; void AutonomousInit() override; void AutonomousPeriodic() override; void TeleopInit() override; void TeleopPeriodic() override; void TestPeriodic() override; };
# Copyright 2020 Jacob Glueck # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from tako.core.types import * from tako.ptypes import Ptypes, make_optional class PtypesTestTypes(Protocol): MaybeNum = make_optional(Ptypes.Lu32) Optional = Struct(maybe_num=MaybeNum)
# Copyright 2019-present NAVER Corp. # Apache License v2.0 # Wonseok Hwang # wp = word piece import os, json import random as rd from copy import deepcopy from matplotlib.pylab import * import torch import torchvision.datasets as dsets import torch.nn as nn import torch.nn.functional as F from .utils import generate_perm_inv from .utils import json_default_type_checker from .wikisql_formatter import get_squad_style_ans device = torch.device("cuda" if torch.cuda.is_available() else "cpu") # Load data ----------------------------------------------------------------------------------------------- def load_wikisql(path_wikisql, toy_model, toy_size, bert=False, no_w2i=False, no_hs_tok=False, aug=False): # Get data train_data, train_table = load_wikisql_data(path_wikisql, mode='train', toy_model=toy_model, toy_size=toy_size, no_hs_tok=no_hs_tok, aug=aug) dev_data, dev_table = load_wikisql_data(path_wikisql, mode='dev', toy_model=toy_model, toy_size=toy_size, no_hs_tok=no_hs_tok) # Get word vector if no_w2i: w2i, wemb = None, None else: w2i, wemb = load_w2i_wemb(path_wikisql, bert) return train_data, train_table, dev_data, dev_table, w2i, wemb def load_wikisql_v2(path_wikisql, toy_model, toy_size, bert=False, no_w2i=False, no_hs_tok=False, aug=False): # Get data train_data, train_table = load_wikisql_data_v2(path_wikisql, mode='train', toy_model=toy_model, toy_size=toy_size, no_hs_tok=no_hs_tok, aug=aug) dev_data, dev_table = load_wikisql_data_v2(path_wikisql, mode='dev', toy_model=toy_model, toy_size=toy_size, no_hs_tok=no_hs_tok) # Get word vector if no_w2i: w2i, wemb = None, None else: w2i, wemb = load_w2i_wemb(path_wikisql, bert) return train_data, train_table, dev_data, dev_table, w2i, wemb def load_wikisql_data_v2(path_wikisql, mode='train', toy_model=False, toy_size=10, no_hs_tok=False, aug=False): """ Load training sets """ if aug: mode = f"aug.{mode}" print('Augmented data is loaded!') path_sql = os.path.join(path_wikisql, mode+'_with_answer.jsonl') if no_hs_tok: path_table = os.path.join(path_wikisql, mode + '.tables.jsonl') else: path_table = os.path.join(path_wikisql, mode+'_tok.tables.jsonl') data = [] table = {} with open(path_sql) as f: for idx, line in enumerate(f): if toy_model and idx >= toy_size: break t1 = json.loads(line.strip()) data.append(t1) with open(path_table) as f: for idx, line in enumerate(f): if toy_model and idx > toy_size: break t1 = json.loads(line.strip()) table[t1['id']] = t1 return data, table def load_wikisql_data(path_wikisql, mode='train', toy_model=False, toy_size=10, no_hs_tok=False, aug=False): """ Load training sets """ if aug: mode = f"aug.{mode}" print('Augmented data is loaded!') path_sql = os.path.join(path_wikisql, mode+'_tok.jsonl') if no_hs_tok: path_table = os.path.join(path_wikisql, mode + '.tables.jsonl') else: path_table = os.path.join(path_wikisql, mode+'_tok.tables.jsonl') data = [] table = {} with open(path_sql) as f: for idx, line in enumerate(f): if toy_model and idx >= toy_size: break t1 = json.loads(line.strip()) data.append(t1) with open(path_table) as f: for idx, line in enumerate(f): if toy_model and idx > toy_size: break t1 = json.loads(line.strip()) table[t1['id']] = t1 return data, table def load_w2i_wemb(path_wikisql, bert=False): """ Load pre-made subset of TAPI. """ if bert: with open(os.path.join(path_wikisql, 'w2i_bert.json'), 'r') as f_w2i: w2i = json.load(f_w2i) wemb = load(os.path.join(path_wikisql, 'wemb_bert.npy'), ) else: with open(os.path.join(path_wikisql, 'w2i.json'), 'r') as f_w2i: w2i = json.load(f_w2i) wemb = load(os.path.join(path_wikisql, 'wemb.npy'), ) return w2i, wemb def get_loader_wikisql(data_train, data_dev, bS, shuffle_train=True, shuffle_dev=False): train_loader = torch.utils.data.DataLoader( batch_size=bS, dataset=data_train, shuffle=shuffle_train, num_workers=4, collate_fn=lambda x: x # now dictionary values are not merged! ) dev_loader = torch.utils.data.DataLoader( batch_size=bS, dataset=data_dev, shuffle=shuffle_dev, num_workers=4, collate_fn=lambda x: x # now dictionary values are not merged! ) return train_loader, dev_loader def get_fields_1(t1, tables, no_hs_t=False, no_sql_t=False): nlu1 = t1['question'] nlu_t1 = t1['question_tok'] tid1 = t1['table_id'] sql_i1 = t1['sql'] sql_q1 = t1['query'] if no_sql_t: sql_t1 = None else: sql_t1 = t1['query_tok'] tb1 = tables[tid1] if not no_hs_t: hs_t1 = tb1['header_tok'] else: hs_t1 = [] hs1 = tb1['header'] return nlu1, nlu_t1, tid1, sql_i1, sql_q1, sql_t1, tb1, hs_t1, hs1 def get_fields(t1s, tables, no_hs_t=False, no_sql_t=False): nlu, nlu_t, tid, sql_i, sql_q, sql_t, tb, hs_t, hs = [], [], [], [], [], [], [], [], [] for t1 in t1s: if no_hs_t: nlu1, nlu_t1, tid1, sql_i1, sql_q1, sql_t1, tb1, hs_t1, hs1 = get_fields_1(t1, tables, no_hs_t, no_sql_t) else: nlu1, nlu_t1, tid1, sql_i1, sql_q1, sql_t1, tb1, hs_t1, hs1 = get_fields_1(t1, tables, no_hs_t, no_sql_t) nlu.append(nlu1) nlu_t.append(nlu_t1) tid.append(tid1) sql_i.append(sql_i1) sql_q.append(sql_q1) sql_t.append(sql_t1) tb.append(tb1) hs_t.append(hs_t1) hs.append(hs1) return nlu, nlu_t, sql_i, sql_q, sql_t, tb, hs_t, hs # Embedding ------------------------------------------------------------------------- def word_to_idx1(words1, w2i, no_BE): w2i_l1 = [] l1 = len(words1) # +2 because of <BEG>, <END> for w in words1: idx = w2i.get(w, 0) w2i_l1.append(idx) if not no_BE: l1 += 2 w2i_l1 = [1] + w2i_l1 + [2] return w2i_l1, l1 def words_to_idx(words, w2i, no_BE=False): """ Input: [ ['I', 'am', 'hero'], ['You', 'are 'geneus'] ] output: w2i = [ B x max_seq_len, 1] wemb = [B x max_seq_len, dim] - Zero-padded when word is not available (teated as <UNK>) """ bS = len(words) l = torch.zeros(bS, dtype=torch.long).to(device) # length of the seq. of words. w2i_l_list = [] # shall be replaced to arr # wemb_NLq_batch = [] for i, words1 in enumerate(words): w2i_l1, l1 = word_to_idx1(words1, w2i, no_BE) w2i_l_list.append(w2i_l1) l[i] = l1 # Prepare tensor of wemb # overwrite w2i_l w2i_l = torch.zeros([bS, int(max(l))], dtype=torch.long).to(device) for b in range(bS): w2i_l[b, :l[b]] = torch.LongTensor(w2i_l_list[b]).to(device) return w2i_l, l def hs_to_idx(hs_t, w2i, no_BE=False): """ Zero-padded when word is not available (teated as <UNK>) Treat each "header tokens" as if they are NL-utterance tokens. """ bS = len(hs_t) # now, B = B_NLq hpu_t = [] # header pseudo-utterance l_hs = [] for hs_t1 in hs_t: hpu_t += hs_t1 l_hs1 = len(hs_t1) l_hs.append(l_hs1) w2i_hpu, l_hpu = words_to_idx(hpu_t, w2i, no_BE=no_BE) return w2i_hpu, l_hpu, l_hs # Encoding --------------------------------------------------------------------- def encode(lstm, wemb_l, l, return_hidden=False, hc0=None, last_only=False): """ [batch_size, max token length, dim_emb] """ bS, mL, eS = wemb_l.shape # sort before packking l = array(l) perm_idx = argsort(-l) perm_idx_inv = generate_perm_inv(perm_idx) # pack sequence packed_wemb_l = nn.utils.rnn.pack_padded_sequence(wemb_l[perm_idx, :, :], l[perm_idx], batch_first=True) # Time to encode if hc0 is not None: hc0 = (hc0[0][:, perm_idx], hc0[1][:, perm_idx]) # ipdb.set_trace() packed_wemb_l = packed_wemb_l.float() # I don't know why.. packed_wenc, hc_out = lstm(packed_wemb_l, hc0) hout, cout = hc_out # unpack wenc, _l = nn.utils.rnn.pad_packed_sequence(packed_wenc, batch_first=True) if last_only: # Take only final outputs for each columns. wenc = wenc[tuple(range(bS)), l[perm_idx] - 1] # [batch_size, dim_emb] wenc.unsqueeze_(1) # [batch_size, 1, dim_emb] wenc = wenc[perm_idx_inv] if return_hidden: # hout.shape = [number_of_directoin * num_of_layer, seq_len(=batch size), dim * number_of_direction ] w/ batch_first.. w/o batch_first? I need to see. hout = hout[:, perm_idx_inv].to(device) cout = cout[:, perm_idx_inv].to(device) # Is this correct operation? return wenc, hout, cout else: return wenc def encode_header(lstm, wemb_hpu, l_hpu, l_hs): wenc_hpu, hout, cout = encode( lstm, wemb_hpu, l_hpu, return_hidden=True, hc0=None, last_only=True ) wenc_hpu = wenc_hpu.squeeze(1) bS_hpu, mL_hpu, eS = wemb_hpu.shape hS = wenc_hpu.size(-1) wenc_hs = wenc_hpu.new_zeros(len(l_hs), max(l_hs), hS) wenc_hs = wenc_hs.to(device) # Re-pack according to batch. # ret = [B_NLq, max_len_headers_all, dim_lstm] st = 0 for i, l_hs1 in enumerate(l_hs): wenc_hs[i, :l_hs1] = wenc_hpu[st:(st + l_hs1)] st += l_hs1 return wenc_hs # Statistics ------------------------------------------------------------------------------------------------------------------- def get_wc1(conds): """ [ [wc, wo, wv], [wc, wo, wv], ... ] """ wc1 = [] for cond in conds: wc1.append(cond[0]) return wc1 def get_wo1(conds): """ [ [wc, wo, wv], [wc, wo, wv], ... ] """ wo1 = [] for cond in conds: wo1.append(cond[1]) return wo1 def get_wv1(conds): """ [ [wc, wo, wv], [wc, wo, wv], ... ] """ wv1 = [] for cond in conds: wv1.append(cond[2]) return wv1 def get_gt(sql_i): """ for backward compatibility, separated with get_g""" g_sc = [] g_sa = [] g_wn = [] g_wc = [] g_wo = [] g_wv = [] for b, psql_i1 in enumerate(sql_i): g_sc.append( psql_i1["sel"] ) g_sa.append( psql_i1["agg"]) conds = psql_i1['conds'] if not psql_i1["agg"] < 0: g_wn.append( len( conds ) ) g_wc.append( get_wc1(conds) ) g_wo.append( get_wo1(conds) ) g_wv.append( get_wv1(conds) ) else: raise EnvironmentError return g_sc, g_sa, g_wn, g_wc, g_wo, g_wv def get_gt_wherevalueindex_corenlp(t): g_wvi_corenlp = [] for t1 in t: g_wvi_corenlp.append( t1['wvi_corenlp'] ) return g_wvi_corenlp def update_w2i_wemb(word, wv, idx_w2i, n_total, w2i, wemb): """ Follow same approach from SQLNet author's code. Used inside of generaet_w2i_wemb. """ # global idx_w2i, w2i, wemb # idx, word2vec, word to idx dictionary, list of embedding vec, n_total: total number of words if (word in wv) and (word not in w2i): idx_w2i += 1 w2i[word] = idx_w2i wemb.append(wv[word]) n_total += 1 return idx_w2i, n_total def make_w2i_wemb(args, path_save_w2i_wemb, wv, data_train, data_dev, data_test, table_train, table_dev, table_test): w2i = {'<UNK>': 0, '<BEG>': 1, '<END>': 2} # to use it when embeds NL query. idx_w2i = 2 n_total = 3 wemb = [np.zeros(300, dtype=np.float32) for _ in range(3)] # 128 is of TAPI vector. idx_w2i, n_total = generate_w2i_wemb(data_train, wv, idx_w2i, n_total, w2i, wemb) idx_w2i, n_total = generate_w2i_wemb_table(table_train, wv, idx_w2i, n_total, w2i, wemb) idx_w2i, n_total = generate_w2i_wemb(data_dev, wv, idx_w2i, n_total, w2i, wemb) idx_w2i, n_total = generate_w2i_wemb_table(table_dev, wv, idx_w2i, n_total, w2i, wemb) idx_w2i, n_total = generate_w2i_wemb(data_test, wv, idx_w2i, n_total, w2i, wemb) idx_w2i, n_total = generate_w2i_wemb_table(table_test, wv, idx_w2i, n_total, w2i, wemb) path_w2i = os.path.join(path_save_w2i_wemb, 'w2i.json') path_wemb = os.path.join(path_save_w2i_wemb, 'wemb.npy') wemb = np.stack(wemb, axis=0) with open(path_w2i, 'w') as f_w2i: json.dump(w2i, f_w2i) np.save(path_wemb, wemb) return w2i, wemb def generate_w2i_wemb_table(tables, wv, idx_w2i, n_total, w2i, wemb): """ Generate subset of GloVe update_w2i_wemb. It uses wv, w2i, wemb, idx_w2i as global variables. To do 1. What should we do with the numeric? """ # word_set from NL query for table_id, table_contents in tables.items(): # NLq = t1['question'] # word_tokens = NLq.rstrip().replace('?', '').split(' ') headers = table_contents['header_tok'] # [ ['state/terriotry'], ['current', 'slogan'], [], for header_tokens in headers: for token in header_tokens: idx_w2i, n_total = update_w2i_wemb(token, wv, idx_w2i, n_total, w2i, wemb) # WikiSQL generaets unbelivable query... using state/territory in the NLq. Unnatural.. but as is # when there is slash, unlike original SQLNet which treats them as single token, we use # both tokens. e.g. 'state/terriotry' -> 'state' # token_spl = token.split('/') # for token_spl1 in token_spl: # idx_w2i, n_total = update_w2i_wemb(token_spl1, wv, idx_w2i, n_total, w2i, wemb) return idx_w2i, n_total def generate_w2i_wemb(train_data, wv, idx_w2i, n_total, w2i, wemb): """ Generate subset of GloVe update_w2i_wemb. It uses wv, w2i, wemb, idx_w2i as global variables. To do 1. What should we do with the numeric? """ # word_set from NL query for i, t1 in enumerate(train_data): # NLq = t1['question'] # word_tokens = NLq.rstrip().replace('?', '').split(' ') word_tokens = t1['question_tok'] # Currently, TAPI does not use "?". So, it is removed. for word in word_tokens: idx_w2i, n_total = update_w2i_wemb(word, wv, idx_w2i, n_total, w2i, wemb) n_total += 1 return idx_w2i, n_total def generate_w2i_wemb_e2k_headers(e2k_dicts, wv, idx_w2i, n_total, w2i, wemb): """ Generate subset of TAPI from english-to-korean dict of table headers etc.. update_w2i_wemb. It uses wv, w2i, wemb, idx_w2i as global variables. To do 1. What should we do with the numeric? Current version do not treat them specially. But this would be modified later so that we can use tags. """ # word_set from NL query for table_name, e2k_dict in e2k_dicts.items(): word_tokens_list = list(e2k_dict.values()) # Currently, TAPI does not use "?". So, it is removed. for word_tokens in word_tokens_list: for word in word_tokens: idx_w2i, n_total = update_w2i_wemb(word, wv, idx_w2i, n_total, w2i, wemb) n_total += 1 return idx_w2i, n_total # BERT ================================================================================================================= def tokenize_nlu1(tokenizer, nlu1): nlu1_tok = tokenizer.tokenize(nlu1) return nlu1_tok def tokenize_hds1(tokenizer, hds1): hds_all_tok = [] for hds11 in hds1: sub_tok = tokenizer.tokenize(hds11) hds_all_tok.append(sub_tok) def generate_inputs(tokenizer, nlu1_tok, hds1): tokens = [] segment_ids = [] tokens.append("[CLS]") i_st_nlu = len(tokens) # to use it later segment_ids.append(0) for token in nlu1_tok: tokens.append(token) segment_ids.append(0) i_ed_nlu = len(tokens) tokens.append("[SEP]") segment_ids.append(0) i_hds = [] # for doc for i, hds11 in enumerate(hds1): i_st_hd = len(tokens) sub_tok = tokenizer.tokenize(hds11) tokens += sub_tok i_ed_hd = len(tokens) i_hds.append((i_st_hd, i_ed_hd)) segment_ids += [1] * len(sub_tok) if i < len(hds1)-1: tokens.append("[SEP]") segment_ids.append(0) elif i == len(hds1)-1: tokens.append("[SEP]") segment_ids.append(1) else: raise EnvironmentError i_nlu = (i_st_nlu, i_ed_nlu) return tokens, segment_ids, i_nlu, i_hds def gen_l_hpu(i_hds): """ # Treat columns as if it is a batch of natural language utterance with batch-size = # of columns * # of batch_size i_hds = [(17, 18), (19, 21), (22, 23), (24, 25), (26, 29), (30, 34)]) """ l_hpu = [] for i_hds1 in i_hds: for i_hds11 in i_hds1: l_hpu.append(i_hds11[1] - i_hds11[0]) return l_hpu def get_bert_output_s2s(model_bert, tokenizer, nlu_t, hds, sql_vocab, max_seq_length): """ s2s version. Treat SQL-tokens as pseudo-headers sql_vocab = ("sql select", "sql where", "sql and", "sql equal", "sql greater than", "sql less than") e.g.) Q: What is the name of the player with score greater than 15? H: Name of the player, score Input: [CLS], what, is, ..., [SEP], name, of, the, player, [SEP], score, [SEP] sql, select, [SEP], sql, where, [SEP], sql, and, [SEP], ... Here, input is tokenized further by WordPiece (WP) tokenizer and fed into BERT. INPUT :param model_bert: :param tokenizer: WordPiece toknizer :param nlu: Question :param nlu_t: CoreNLP tokenized nlu. :param hds: Headers :param hs_t: None or 1st-level tokenized headers :param max_seq_length: max input token length OUTPUT tokens: BERT input tokens nlu_tt: WP-tokenized input natural language questions orig_to_tok_index: map the index of 1st-level-token to the index of 2nd-level-token tok_to_orig_index: inverse map. """ l_n = [] l_hs = [] # The length of columns for each batch l_input = [] input_ids = [] tokens = [] segment_ids = [] input_mask = [] i_nlu = [] # index to retreive the position of contextual vector later. i_hds = [] i_sql_vocab = [] doc_tokens = [] nlu_tt = [] t_to_tt_idx = [] tt_to_t_idx = [] for b, nlu_t1 in enumerate(nlu_t): hds1 = hds[b] l_hs.append(len(hds1)) # 1. 2nd tokenization using WordPiece tt_to_t_idx1 = [] # number indicates where sub-token belongs to in 1st-level-tokens (here, CoreNLP). t_to_tt_idx1 = [] # orig_to_tok_idx[i] = start index of i-th-1st-level-token in all_tokens. nlu_tt1 = [] # all_doc_tokens[ orig_to_tok_idx[i] ] returns first sub-token segement of i-th-1st-level-token for (i, token) in enumerate(nlu_t1): t_to_tt_idx1.append( len(nlu_tt1)) # all_doc_tokens[ indicate the start position of original 'white-space' tokens. sub_tokens = tokenizer.tokenize(token) for sub_token in sub_tokens: tt_to_t_idx1.append(i) nlu_tt1.append(sub_token) # all_doc_tokens are further tokenized using WordPiece tokenizer nlu_tt.append(nlu_tt1) tt_to_t_idx.append(tt_to_t_idx1) t_to_tt_idx.append(t_to_tt_idx1) l_n.append(len(nlu_tt1)) # hds1_all_tok = tokenize_hds1(tokenizer, hds1) # [CLS] nlu [SEP] col1 [SEP] col2 [SEP] ...col-n [SEP] # 2. Generate BERT inputs & indices. # Combine hds1 and sql_vocab tokens1, segment_ids1, i_sql_vocab1, i_nlu1, i_hds1 = generate_inputs_s2s(tokenizer, nlu_tt1, hds1, sql_vocab) # i_hds1 input_ids1 = tokenizer.convert_tokens_to_ids(tokens1) # Input masks # The mask has 1 for real tokens and 0 for padding tokens. Only real # tokens are attended to. input_mask1 = [1] * len(input_ids1) # 3. Zero-pad up to the sequence length. l_input.append( len(input_ids1) ) while len(input_ids1) < max_seq_length: input_ids1.append(0) input_mask1.append(0) segment_ids1.append(0) assert len(input_ids1) == max_seq_length assert len(input_mask1) == max_seq_length assert len(segment_ids1) == max_seq_length input_ids.append(input_ids1) tokens.append(tokens1) segment_ids.append(segment_ids1) input_mask.append(input_mask1) i_nlu.append(i_nlu1) i_hds.append(i_hds1) i_sql_vocab.append(i_sql_vocab1) # Convert to tensor all_input_ids = torch.tensor(input_ids, dtype=torch.long).to(device) all_input_mask = torch.tensor(input_mask, dtype=torch.long).to(device) all_segment_ids = torch.tensor(segment_ids, dtype=torch.long).to(device) # 4. Generate BERT output. all_encoder_layer, pooled_output = model_bert(all_input_ids, all_segment_ids, all_input_mask) # 5. generate l_hpu from i_hds l_hpu = gen_l_hpu(i_hds) return all_encoder_layer, pooled_output, tokens, i_nlu, i_hds, i_sql_vocab, \ l_n, l_hpu, l_hs, l_input, \ nlu_tt, t_to_tt_idx, tt_to_t_idx def get_bert_output_v2(model_bert, tokenizer, nlu_t, hds, max_seq_length): """ Here, input is toknized further by WordPiece (WP) tokenizer and fed into BERT. INPUT :param model_bert: :param tokenizer: WordPiece toknizer :param nlu: Question :param nlu_t: CoreNLP tokenized nlu. :param hds: Headers :param hs_t: None or 1st-level tokenized headers :param max_seq_length: max input token length OUTPUT tokens: BERT input tokens nlu_tt: WP-tokenized input natural language questions orig_to_tok_index: map the index of 1st-level-token to the index of 2nd-level-token tok_to_orig_index: inverse map. """ l_n = [] l_hs = [] # The length of columns for each batch input_ids = [] tokens = [] segment_ids = [] input_mask = [] i_nlu = [] # index to retreive the position of contextual vector later. i_hds = [] doc_tokens = [] nlu_tt = [] t_to_tt_idx = [] tt_to_t_idx = [] for b, nlu_t1 in enumerate(nlu_t): hds1 = hds[b] l_hs.append(len(hds1)) # 1. 2nd tokenization using WordPiece tt_to_t_idx1 = [] # number indicates where sub-token belongs to in 1st-level-tokens (here, CoreNLP). t_to_tt_idx1 = [] # orig_to_tok_idx[i] = start index of i-th-1st-level-token in all_tokens. nlu_tt1 = [] # all_doc_tokens[ orig_to_tok_idx[i] ] returns first sub-token segement of i-th-1st-level-token for (i, token) in enumerate(nlu_t1): t_to_tt_idx1.append( len(nlu_tt1)) # all_doc_tokens[ indicate the start position of original 'white-space' tokens. sub_tokens = tokenizer.tokenize(token) for sub_token in sub_tokens: tt_to_t_idx1.append(i) nlu_tt1.append(sub_token) # all_doc_tokens are further tokenized using WordPiece tokenizer nlu_tt.append(nlu_tt1) tt_to_t_idx.append(tt_to_t_idx1) t_to_tt_idx.append(t_to_tt_idx1) l_n.append(len(nlu_tt1)) # hds1_all_tok = tokenize_hds1(tokenizer, hds1) # [CLS] nlu [SEP] col1 [SEP] col2 [SEP] ...col-n [SEP] # 2. Generate BERT inputs & indices. tokens1, segment_ids1, i_nlu1, i_hds1 = generate_inputs(tokenizer, nlu_tt1, hds1) input_ids1 = tokenizer.convert_tokens_to_ids(tokens1) # Input masks # The mask has 1 for real tokens and 0 for padding tokens. Only real # tokens are attended to. input_mask1 = [1] * len(input_ids1) # 3. Zero-pad up to the sequence length. while len(input_ids1) < max_seq_length: input_ids1.append(0) input_mask1.append(0) segment_ids1.append(0) assert len(input_ids1) == max_seq_length assert len(input_mask1) == max_seq_length assert len(segment_ids1) == max_seq_length input_ids.append(input_ids1) tokens.append(tokens1) segment_ids.append(segment_ids1) input_mask.append(input_mask1) i_nlu.append(i_nlu1) i_hds.append(i_hds1) # Convert to tensor all_input_ids = torch.tensor(input_ids, dtype=torch.long).to(device) all_input_mask = torch.tensor(input_mask, dtype=torch.long).to(device) all_segment_ids = torch.tensor(segment_ids, dtype=torch.long).to(device) # 4. Generate BERT output. # all_encoder_layer, pooled_output = model_bert(all_input_ids, all_segment_ids, all_input_mask) # 5. generate l_hpu from i_hds l_hpu = gen_l_hpu(i_hds) return tokens, i_nlu, i_hds, \ l_n, l_hpu, l_hs, \ nlu_tt, t_to_tt_idx, tt_to_t_idx def get_bert_output(model_bert, tokenizer, nlu_t, hds, max_seq_length): """ Here, input is toknized further by WordPiece (WP) tokenizer and fed into BERT. INPUT :param model_bert: :param tokenizer: WordPiece toknizer :param nlu: Question :param nlu_t: CoreNLP tokenized nlu. :param hds: Headers :param hs_t: None or 1st-level tokenized headers :param max_seq_length: max input token length OUTPUT tokens: BERT input tokens nlu_tt: WP-tokenized input natural language questions orig_to_tok_index: map the index of 1st-level-token to the index of 2nd-level-token tok_to_orig_index: inverse map. """ l_n = [] l_hs = [] # The length of columns for each batch input_ids = [] tokens = [] segment_ids = [] input_mask = [] i_nlu = [] # index to retreive the position of contextual vector later. i_hds = [] doc_tokens = [] nlu_tt = [] t_to_tt_idx = [] tt_to_t_idx = [] for b, nlu_t1 in enumerate(nlu_t): hds1 = hds[b] l_hs.append(len(hds1)) # 1. 2nd tokenization using WordPiece tt_to_t_idx1 = [] # number indicates where sub-token belongs to in 1st-level-tokens (here, CoreNLP). t_to_tt_idx1 = [] # orig_to_tok_idx[i] = start index of i-th-1st-level-token in all_tokens. nlu_tt1 = [] # all_doc_tokens[ orig_to_tok_idx[i] ] returns first sub-token segement of i-th-1st-level-token for (i, token) in enumerate(nlu_t1): t_to_tt_idx1.append( len(nlu_tt1)) # all_doc_tokens[ indicate the start position of original 'white-space' tokens. sub_tokens = tokenizer.tokenize(token) for sub_token in sub_tokens: tt_to_t_idx1.append(i) nlu_tt1.append(sub_token) # all_doc_tokens are further tokenized using WordPiece tokenizer nlu_tt.append(nlu_tt1) tt_to_t_idx.append(tt_to_t_idx1) t_to_tt_idx.append(t_to_tt_idx1) l_n.append(len(nlu_tt1)) # hds1_all_tok = tokenize_hds1(tokenizer, hds1) # [CLS] nlu [SEP] col1 [SEP] col2 [SEP] ...col-n [SEP] # 2. Generate BERT inputs & indices. tokens1, segment_ids1, i_nlu1, i_hds1 = generate_inputs(tokenizer, nlu_tt1, hds1) input_ids1 = tokenizer.convert_tokens_to_ids(tokens1) # Input masks # The mask has 1 for real tokens and 0 for padding tokens. Only real # tokens are attended to. input_mask1 = [1] * len(input_ids1) # 3. Zero-pad up to the sequence length. while len(input_ids1) < max_seq_length: input_ids1.append(0) input_mask1.append(0) segment_ids1.append(0) assert len(input_ids1) == max_seq_length assert len(input_mask1) == max_seq_length assert len(segment_ids1) == max_seq_length input_ids.append(input_ids1) tokens.append(tokens1) segment_ids.append(segment_ids1) input_mask.append(input_mask1) i_nlu.append(i_nlu1) i_hds.append(i_hds1) # Convert to tensor all_input_ids = torch.tensor(input_ids, dtype=torch.long).to(device) all_input_mask = torch.tensor(input_mask, dtype=torch.long).to(device) all_segment_ids = torch.tensor(segment_ids, dtype=torch.long).to(device) # 4. Generate BERT output. all_encoder_layer, pooled_output = model_bert(all_input_ids, all_segment_ids, all_input_mask) # 5. generate l_hpu from i_hds l_hpu = gen_l_hpu(i_hds) return all_encoder_layer, pooled_output, tokens, i_nlu, i_hds, \ l_n, l_hpu, l_hs, \ nlu_tt, t_to_tt_idx, tt_to_t_idx def get_wemb_n(i_nlu, l_n, hS, num_hidden_layers=12, all_encoder_layer=None, num_out_layers_n=2): """ Get the representation of each tokens. """ bS = len(l_n) l_n_max = max(l_n) wemb_n = torch.zeros([bS, l_n_max, hS * num_out_layers_n]).to(device) for b in range(bS): # [B, max_len, dim] # Fill zero for non-exist part. l_n1 = l_n[b] i_nlu1 = i_nlu[b] for i_noln in range(num_out_layers_n): i_layer = num_hidden_layers - 1 - i_noln st = i_noln * hS ed = (i_noln + 1) * hS wemb_n[b, 0:(i_nlu1[1] - i_nlu1[0]), st:ed] = all_encoder_layer[i_layer][b, i_nlu1[0]:i_nlu1[1], :] return wemb_n # def get_wemb_h(i_hds, l_hpu, l_hs, hS, num_hidden_layers, all_encoder_layer, num_out_layers_h): """ As if [ [table-1-col-1-tok1, t1-c1-t2, ...], [t1-c2-t1, t1-c2-t2, ...]. ... [t2-c1-t1, ...,] ] """ bS = len(l_hs) l_hpu_max = max(l_hpu) num_of_all_hds = sum(l_hs) wemb_h = torch.zeros([num_of_all_hds, l_hpu_max, hS * num_out_layers_h]).to(device) b_pu = -1 for b, i_hds1 in enumerate(i_hds): for b1, i_hds11 in enumerate(i_hds1): b_pu += 1 for i_nolh in range(num_out_layers_h): i_layer = num_hidden_layers - 1 - i_nolh st = i_nolh * hS ed = (i_nolh + 1) * hS wemb_h[b_pu, 0:(i_hds11[1] - i_hds11[0]), st:ed] \ = all_encoder_layer[i_layer][b, i_hds11[0]:i_hds11[1],:] return wemb_h def get_wemb_bert_v2(bert_config, model_bert, tokenizer, nlu_t, headers, max_seq_length, num_out_layers_n=1, num_out_layers_h=1): # get contextual output of all tokens from bert tokens, i_nlu, i_hds,\ l_n, l_hpu, l_hs, \ nlu_tt, t_to_tt_idx, tt_to_t_idx = get_bert_output_v2(model_bert, tokenizer, nlu_t, headers, max_seq_length) # all_encoder_layer: BERT outputs from all layers. # pooled_output: output of [CLS] vec. # tokens: BERT intput tokens # i_nlu: start and end indices of question in tokens # i_hds: start and end indices of headers return l_n, l_hpu, l_hs, \ nlu_tt, t_to_tt_idx, tt_to_t_idx def get_wemb_bert(bert_config, model_bert, tokenizer, nlu_t, headers, max_seq_length, num_out_layers_n=1, num_out_layers_h=1): # get contextual output of all tokens from bert all_encoder_layer, pooled_output, tokens, i_nlu, i_hds,\ l_n, l_hpu, l_hs, \ nlu_tt, t_to_tt_idx, tt_to_t_idx = get_bert_output(model_bert, tokenizer, nlu_t, headers, max_seq_length) # all_encoder_layer: BERT outputs from all layers. # pooled_output: output of [CLS] vec. # tokens: BERT intput tokens # i_nlu: start and end indices of question in tokens # i_hds: start and end indices of headers # get the wemb wemb_n = get_wemb_n(i_nlu, l_n, bert_config.hidden_size, bert_config.num_hidden_layers, all_encoder_layer, num_out_layers_n) wemb_h = get_wemb_h(i_hds, l_hpu, l_hs, bert_config.hidden_size, bert_config.num_hidden_layers, all_encoder_layer, num_out_layers_h) return wemb_n, wemb_h, l_n, l_hpu, l_hs, \ nlu_tt, t_to_tt_idx, tt_to_t_idx def gen_pnt_n(g_wvi, mL_w, mL_nt): """ Generate one-hot idx indicating vectors with their lenghts. :param g_wvi: e.g. [[[0, 6, 7, 8, 15], [0, 1, 2, 3, 4, 15]], [[0, 1, 2, 3, 16], [0, 7, 8, 9, 16]]] where_val idx in nlu_t. 0 = <BEG>, -1 = <END>. :param mL_w: 4 :param mL_nt: 200 :return: """ bS = len(g_wvi) for g_wvi1 in g_wvi: for g_wvi11 in g_wvi1: l11 = len(g_wvi11) mL_g_wvi = max([max([0] + [len(tok) for tok in gwsi]) for gwsi in g_wvi]) - 1 # zero because of '' case. # -1 because we already have <BEG> if mL_g_wvi < 1: mL_g_wvi = 1 # NLq_token_pos = torch.zeros(bS, 5 - 1, mL_g_wvi, self.max_NLq_token_num) # l_g_wvi = torch.zeros(bS, 5 - 1) pnt_n = torch.zeros(bS, mL_w, mL_g_wvi, mL_nt).to(device) # one hot l_g_wvi = torch.zeros(bS, mL_w).to(device) for b, g_wvi1 in enumerate(g_wvi): i_wn = 0 # To prevent error from zero number of condition. for i_wn, g_wvi11 in enumerate(g_wvi1): # g_wvi11: [0, where_conds pos in NLq, end] g_wvi11_n1 = g_wvi11[:-1] # doesn't count <END> idx. l_g_wvi[b, i_wn] = len(g_wvi11_n1) for t, idx in enumerate(g_wvi11_n1): pnt_n[b, i_wn, t, idx] = 1 # Pad if i_wn < (mL_w - 1): # maximum number of conidtions is 4 pnt_n[b, i_wn + 1:, 0, 1] = 1 # # cannot understand... [<BEG>, <END>]?? l_g_wvi[b, i_wn + 1:] = 1 # it means there is only <BEG>. return pnt_n, l_g_wvi def pred_selectcolumn_random(s_sc): """ return: [ pr_wc1_i, pr_wc2_i, ...] """ # get g_num pr_sc = torch.squeeze(s_sc.multinomial(1),dim=-1) return pr_sc def pred_sc(s_sc): """ return: [ pr_wc1_i, pr_wc2_i, ...] """ # get g_num pr_sc = [] for s_sc1 in s_sc: pr_sc.append(s_sc1.argmax().item()) return pr_sc def pred_sc_beam(s_sc, beam_size): """ return: [ pr_wc1_i, pr_wc2_i, ...] """ # get g_num pr_sc_beam = [] for s_sc1 in s_sc: val, idxes = s_sc1.topk(k=beam_size) pr_sc_beam.append(idxes.tolist()) return pr_sc_beam def pred_sa(s_sa): """ return: [ pr_wc1_i, pr_wc2_i, ...] """ # get g_num pr_sa = [] for s_sa1 in s_sa: pr_sa.append(s_sa1.argmax().item()) return pr_sa def pred_selectagg_random(s_sa): """ return: [ pr_wc1_i, pr_wc2_i, ...] """ # get g_num pr_sa = torch.squeeze(s_sa.multinomial(1),dim=-1) return pr_sa def pred_wherenumber_random(s_wn): """ return: [ pr_wc1_i, pr_wc2_i, ...] """ # get g_num pr_wn = torch.squeeze(s_wn.multinomial(1),dim=-1) # print(pr_wn, s_wn1) # if s_wn1.argmax().item() == 3: # input('') return pr_wn def pred_wn(s_wn): """ return: [ pr_wc1_i, pr_wc2_i, ...] """ # get g_num pr_wn = [] for s_wn1 in s_wn: pr_wn.append(s_wn1.argmax().item()) # print(pr_wn, s_wn1) # if s_wn1.argmax().item() == 3: # input('') return pr_wn def pred_wc_old(sql_i, s_wc): """ return: [ pr_wc1_i, pr_wc2_i, ...] """ # get g_num pr_wc = [] for b, sql_i1 in enumerate(sql_i): wn = len(sql_i1['conds']) s_wc1 = s_wc[b] pr_wc1 = argsort(-s_wc1.data.cpu().numpy())[:wn] pr_wc1.sort() pr_wc.append(list(pr_wc1)) return pr_wc def pred_wherecolumn_random(wn, s_wc): """ return: [ pr_wc1_i, pr_wc2_i, ...] ! Returned index is sorted! """ # get g_num pr_wc = torch.squeeze(s_wc.multinomial(4),dim=-1) result = [] for i, wn1 in enumerate(wn): if wn1<0.1: result.append([]) else: t = pr_wc[i][:wn1] result.append(t) return result def pred_wherecolumn(wn, s_wc): """ return: [ pr_wc1_i, pr_wc2_i, ...] ! Returned index is sorted! """ # get g_num pr_wc = [] for b, wn1 in enumerate(wn): s_wc1 = s_wc[b] pr_wc1 = argsort(-s_wc1.data.cpu().numpy())[:wn1] pr_wc1.sort() pr_wc.append(list(pr_wc1)) return pr_wc def pred_wc_sorted_by_prob(s_wc): """ return: [ pr_wc1_i, pr_wc2_i, ...] ! Returned index is sorted by prob. All colume-indexes are returned here. """ # get g_num bS = len(s_wc) pr_wc = [] for b in range(bS): s_wc1 = s_wc[b] pr_wc1 = argsort(-s_wc1.data.cpu().numpy()) pr_wc.append(list(pr_wc1)) return pr_wc def pred_whereop_random(wn, s_wo): """ return: [ pr_wc1_i, pr_wc2_i, ...] """ # s_wo = [B, 4, n_op] tmp = [] for item in s_wo: tmp.append(torch.squeeze(item.multinomial(1),dim=-1)) # get g_num pr_wo = [] for b, pr_wo_a1 in enumerate(tmp): wn1 = wn[b] pr_wo.append(list(pr_wo_a1.data.cpu().numpy()[:wn1])) return pr_wo def pred_wo(wn, s_wo): """ return: [ pr_wc1_i, pr_wc2_i, ...] """ # s_wo = [B, 4, n_op] pr_wo_a = s_wo.argmax(dim=2) # [B, 4] # get g_num pr_wo = [] for b, pr_wo_a1 in enumerate(pr_wo_a): wn1 = wn[b] pr_wo.append(list(pr_wo_a1.data.cpu().numpy()[:wn1])) return pr_wo def pred_wvi_startend_random(where_number, s_wv): """ s_wv: [B, 4, mL, 2] - predict best st-idx & ed-idx """ s_wv_start, s_wv_end = s_wv.split(1, dim=3) # [B, 4, mL, 2] -> [B, 4, mL, 1], [B, 4, mL, 1] s_wv_start = s_wv_start.squeeze(3) # [B, 4, mL, 1] -> [B, 4, mL] s_wv_end = s_wv_end.squeeze(3) tmp_start = [] for item in s_wv_start: tmp_start.append(torch.squeeze(item.multinomial(1), dim=-1)) tmp_end = [] for item in s_wv_end: tmp_end.append(torch.squeeze(item.multinomial(1), dim=-1)) pred_wvi = [] for b, wn1 in enumerate(where_number): pred_wvi1 = [] for i_wn in range(wn1): pred_wvi_start_idx11 = tmp_start[b][i_wn] pred_wvi_end_idx11 = tmp_end[b][i_wn] pred_wvi1.append([pred_wvi_start_idx11.item(), pred_wvi_end_idx11.item()]) pred_wvi.append(pred_wvi1) return pred_wvi def pred_wvi_startend(where_number, s_wv): """ s_wv: [B, 4, mL, 2] - predict best st-idx & ed-idx """ s_wv_start, s_wv_end = s_wv.split(1, dim=3) # [B, 4, mL, 2] -> [B, 4, mL, 1], [B, 4, mL, 1] s_wv_start = s_wv_start.squeeze(3) # [B, 4, mL, 1] -> [B, 4, mL] s_wv_end = s_wv_end.squeeze(3) pred_wvi_start_idx = s_wv_start.argmax(dim=2) # [B, 4, mL] -> [B, 4, 1] pred_wvi_end_idx = s_wv_end.argmax(dim=2) pred_wvi = [] for b, wn1 in enumerate(where_number): pred_wvi1 = [] for i_wn in range(wn1): pred_wvi_start_idx11 = pred_wvi_start_idx[b][i_wn] pred_wvi_end_idx11 = pred_wvi_end_idx[b][i_wn] pred_wvi1.append([pred_wvi_start_idx11.item(), pred_wvi_end_idx11.item()]) pred_wvi.append(pred_wvi1) return pred_wvi def pred_wvi_se_beam(max_wn, s_wv, beam_size): """ s_wv: [B, 4, mL, 2] - predict best st-idx & ed-idx output: pr_wvi_beam = [B, max_wn, n_pairs, 2]. 2 means [st, ed]. prob_wvi_beam = [B, max_wn, n_pairs] """ bS = s_wv.shape[0] s_wv_st, s_wv_ed = s_wv.split(1, dim=3) # [B, 4, mL, 2] -> [B, 4, mL, 1], [B, 4, mL, 1] s_wv_st = s_wv_st.squeeze(3) # [B, 4, mL, 1] -> [B, 4, mL] s_wv_ed = s_wv_ed.squeeze(3) prob_wv_st = F.softmax(s_wv_st, dim=-1).detach().to('cpu').numpy() prob_wv_ed = F.softmax(s_wv_ed, dim=-1).detach().to('cpu').numpy() k_logit = int(ceil(sqrt(beam_size))) n_pairs = k_logit**2 assert n_pairs >= beam_size values_st, idxs_st = s_wv_st.topk(k_logit) # [B, 4, mL] -> [B, 4, k_logit] values_ed, idxs_ed = s_wv_ed.topk(k_logit) # [B, 4, mL] -> [B, 4, k_logit] # idxs = [B, k_logit, 2] # Generate all possible combination of st, ed indices & prob pr_wvi_beam = [] # [B, max_wn, k_logit**2 [st, ed] paris] prob_wvi_beam = zeros([bS, max_wn, n_pairs]) for b in range(bS): pr_wvi_beam1 = [] idxs_st1 = idxs_st[b] idxs_ed1 = idxs_ed[b] for i_wn in range(max_wn): idxs_st11 = idxs_st1[i_wn] idxs_ed11 = idxs_ed1[i_wn] pr_wvi_beam11 = [] pair_idx = -1 for i_k in range(k_logit): for j_k in range(k_logit): pair_idx += 1 st = idxs_st11[i_k].item() ed = idxs_ed11[j_k].item() pr_wvi_beam11.append([st, ed]) p1 = prob_wv_st[b, i_wn, st] p2 = prob_wv_ed[b, i_wn, ed] prob_wvi_beam[b, i_wn, pair_idx] = p1*p2 pr_wvi_beam1.append(pr_wvi_beam11) pr_wvi_beam.append(pr_wvi_beam1) # prob return pr_wvi_beam, prob_wvi_beam def is_whitespace_g_wvi(c): # if c == " " or c == "\t" or c == "\r" or c == "\n" or ord(c) == 0x202F: if c == " ": return True return False def convert_pred_wvi_to_string(pr_wvi, question_token, question_token_bert, wp_to_wh_index, nlu): """ - Convert to the string in whilte-space-separated tokens - Add-hoc addition. """ pr_wv_str_wp = [] # word-piece version pr_wv_str = [] for b, pr_wvi1 in enumerate(pr_wvi): pr_wv_str_wp1 = [] pr_wv_str1 = [] wp_to_wh_index1 = wp_to_wh_index[b] nlu_wp_t1 = question_token_bert[b] nlu_t1 = question_token[b] for i_wn, pr_wvi11 in enumerate(pr_wvi1): st_idx, ed_idx = pr_wvi11 # Ad-hoc modification of ed_idx to deal with wp-tokenization effect. # e.g.) to convert "butler cc (" ->"butler cc (ks)" (dev set 1st question). pr_wv_str_wp11 = nlu_wp_t1[st_idx:ed_idx+1] pr_wv_str_wp1.append(pr_wv_str_wp11) st_wh_idx = wp_to_wh_index1[st_idx] # TODO reward start > end ed_wh_idx = wp_to_wh_index1[ed_idx] # TODO reward start > end pr_wv_str11 = nlu_t1[st_wh_idx:ed_wh_idx+1] # TODO reward start > end pr_wv_str1.append(pr_wv_str11) pr_wv_str_wp.append(pr_wv_str_wp1) pr_wv_str.append(pr_wv_str1) return pr_wv_str, pr_wv_str_wp def pred_selectwhere_startend(s_sc, s_sa, s_wn, s_wc, s_wo, s_wv): pr_sc = pred_sc(s_sc) pr_sa = pred_sa(s_sa) pr_wn = pred_wn(s_wn) pr_wc = pred_wherecolumn(pr_wn, s_wc) pr_wo = pred_wo(pr_wn, s_wo) pr_wvi = pred_wvi_startend(pr_wn, s_wv) return pr_sc, pr_sa, pr_wn, pr_wc, pr_wo, pr_wvi def pred_selectwhere_startend_random(s_sc, s_sa, s_wn, s_wc, s_wo, s_wv): pr_sc = pred_selectcolumn_random(s_sc) pr_sa = pred_selectagg_random(s_sa) pr_wn = pred_wherenumber_random(s_wn) pr_wc = pred_wherecolumn_random(pr_wn, s_wc) pr_wo = pred_whereop_random(pr_wn, s_wo) pr_wvi = pred_wvi_startend_random(pr_wn, s_wv) return pr_sc, pr_sa, pr_wn, pr_wc, pr_wo, pr_wvi def merge_wv_t1_eng(where_str_tokens, NLq): """ Almost copied of SQLNet. The main purpose is pad blank line while combining tokens. """ nlq = NLq.lower() where_str_tokens = [tok.lower() for tok in where_str_tokens] alphabet = 'abcdefghijklmnopqrstuvwxyz0123456789$' special = {'-LRB-': '(', '-RRB-': ')', '-LSB-': '[', '-RSB-': ']', '``': '"', '\'\'': '"', } # '--': '\u2013'} # this generate error for test 5661 case. ret = '' double_quote_appear = 0 for raw_w_token in where_str_tokens: # if '' (empty string) of None, continue if not raw_w_token: continue # Change the special characters w_token = special.get(raw_w_token, raw_w_token) # maybe necessary for some case? # check the double quote if w_token == '"': double_quote_appear = 1 - double_quote_appear # Check whether ret is empty. ret is selected where condition. if len(ret) == 0: pass # Check blank character. elif len(ret) > 0 and ret + ' ' + w_token in nlq: # Pad ' ' if ret + ' ' is part of nlq. ret = ret + ' ' elif len(ret) > 0 and ret + w_token in nlq: pass # already in good form. Later, ret + w_token will performed. # Below for unnatural question I guess. Is it likely to appear? elif w_token == '"': if double_quote_appear: ret = ret + ' ' # pad blank line between next token when " because in this case, it is of closing apperas # for the case of opening, no blank line. elif w_token[0] not in alphabet: pass # non alphabet one does not pad blank line. # when previous character is the special case. elif (ret[-1] not in ['(', '/', '\u2013', '#', '$', '&']) and (ret[-1] != '"' or not double_quote_appear): ret = ret + ' ' ret = ret + w_token return ret.strip() def find_sql_where_op(gt_sql_tokens_part): """ gt_sql_tokens_part: Between 'WHERE' and 'AND'(if exists). """ # sql_where_op = ['=', 'EQL', '<', 'LT', '>', 'GT'] sql_where_op = ['EQL','LT','GT'] # wv sometimes contains =, < or >. for sql_where_op in sql_where_op: if sql_where_op in gt_sql_tokens_part: found_sql_where_op = sql_where_op break return found_sql_where_op def find_sub_list(sl, l): # from stack overflow. results = [] sll = len(sl) for ind in (i for i, e in enumerate(l) if e == sl[0]): if l[ind:ind + sll] == sl: results.append((ind, ind + sll - 1)) return results def get_g_wvi_bert(nlu, nlu_t, wh_to_wp_index, sql_i, sql_t, tokenizer, nlu_wp_t): """ Generate SQuAD style start and end index of wv in nlu. Index is for of after WordPiece tokenization. Assumption: where_str always presents in the nlu. """ g_wvi = [] for b, sql_i1 in enumerate(sql_i): nlu1 = nlu[b] nlu_t1 = nlu_t[b] nlu_wp_t1 = nlu_wp_t[b] sql_t1 = sql_t[b] wh_to_wp_index1 = wh_to_wp_index[b] st = sql_t1.index('WHERE') + 1 if 'WHERE' in sql_t1 else len(sql_t1) g_wvi1 = [] while st < len(sql_t1): if 'AND' not in sql_t1[st:]: ed = len(sql_t1) else: ed = sql_t1[st:].index('AND') + st sql_wop = find_sql_where_op(sql_t1[st:ed]) # sql where operator st_wop = st + sql_t1[st:ed].index(sql_wop) wv_str11_t = sql_t1[st_wop + 1:ed] results = find_sub_list(wv_str11_t, nlu_t1) st_idx, ed_idx = results[0] st_wp_idx = wh_to_wp_index1[st_idx] ed_wp_idx = wh_to_wp_index1[ed_idx] g_wvi11 = [st_wp_idx, ed_wp_idx] g_wvi1.append(g_wvi11) st = ed + 1 g_wvi.append(g_wvi1) return g_wvi def get_gt_wherevalueindex_bert_from_gt_wherevalueindex_corenlp(wh_to_wp_index, g_wvi_corenlp): """ Generate SQuAD style start and end index of wv in nlu. Index is for of after WordPiece tokenization. Assumption: where_str always presents in the nlu. """ g_wvi = [] for b, g_wvi_corenlp1 in enumerate(g_wvi_corenlp): wh_to_wp_index1 = wh_to_wp_index[b] g_wvi1 = [] for i_wn, g_wvi_corenlp11 in enumerate(g_wvi_corenlp1): st_idx, ed_idx = g_wvi_corenlp11 st_wp_idx = wh_to_wp_index1[st_idx] ed_wp_idx = wh_to_wp_index1[ed_idx] g_wvi11 = [st_wp_idx, ed_wp_idx] g_wvi1.append(g_wvi11) g_wvi.append(g_wvi1) return g_wvi def get_gt_wvi_bert_from_sql_i(nlu, nlu_t, wh_to_wp_index, sql_i, sql_t, tokenizer, nlu_wp_t): """ Generate SQuAD style start and end index of wv in nlu. Index is for of after WordPiece tokenization. Assumption: where_str always presents in the nlu. """ g_wvi = [] for b, sql_i1 in enumerate(sql_i): nlu1 = nlu[b] nlu_t1 = nlu_t[b] nlu_wp_t1 = nlu_wp_t[b] sql_t1 = sql_t[b] wh_to_wp_index1 = wh_to_wp_index[b] st = sql_t1.index('WHERE') + 1 if 'WHERE' in sql_t1 else len(sql_t1) g_wvi1 = [] while st < len(sql_t1): if 'AND' not in sql_t1[st:]: ed = len(sql_t1) else: ed = sql_t1[st:].index('AND') + st sql_wop = find_sql_where_op(sql_t1[st:ed]) # sql where operator st_wop = st + sql_t1[st:ed].index(sql_wop) wv_str11_t = sql_t1[st_wop + 1:ed] results = find_sub_list(wv_str11_t, nlu_t1) st_idx, ed_idx = results[0] st_wp_idx = wh_to_wp_index1[st_idx] ed_wp_idx = wh_to_wp_index1[ed_idx] g_wvi11 = [st_wp_idx, ed_wp_idx] g_wvi1.append(g_wvi11) st = ed + 1 g_wvi.append(g_wvi1) return g_wvi def get_count_sc(g_sc, pr_sc): count = 0 for b, g_sc1 in enumerate(g_sc): pr_sc1 = pr_sc[b] if pr_sc1 == g_sc1: count += 1 return count def get_count_sc_list(g_sc, pr_sc): count_list = [] for b, g_sc1 in enumerate(g_sc): pr_sc1 = pr_sc[b] if pr_sc1 == g_sc1: count_list.append(1) else: count_list.append(0) return count_list def get_count_sa(g_sa, pr_sa): count = 0 for b, g_sa1 in enumerate(g_sa): pr_sa1 = pr_sa[b] if pr_sa1 == g_sa1: count += 1 return count def get_count_wn(g_wn, pr_wn): count = 0 for b, g_wn1 in enumerate(g_wn): pr_wn1 = pr_wn[b] if pr_wn1 == g_wn1: count += 1 return count def get_count_wc(g_wc, pr_wc): count = 0 for b, g_wc1 in enumerate(g_wc): pr_wc1 = pr_wc[b] pr_wn1 = len(pr_wc1) g_wn1 = len(g_wc1) if pr_wn1 != g_wn1: continue else: wc1 = array(g_wc1) wc1.sort() if array_equal(pr_wc1, wc1): count += 1 return count def get_count_wc_list(g_wc, pr_wc): count_list= [] for b, g_wc1 in enumerate(g_wc): pr_wc1 = pr_wc[b] pr_wn1 = len(pr_wc1) g_wn1 = len(g_wc1) if pr_wn1 != g_wn1: count_list.append(0) continue else: wc1 = array(g_wc1) wc1.sort() if array_equal(pr_wc1, wc1): count_list.append(1) else: count_list.append(0) return count_list def get_count_wo(g_wn, g_wc, g_wo, pr_wc, pr_wo, mode): """ pr's are all sorted as pr_wc are sorted in increasing order (in column idx) However, g's are not sorted. Sort g's in increasing order (in column idx) """ count = 0 for b, g_wo1 in enumerate(g_wo): g_wc1 = g_wc[b] pr_wc1 = pr_wc[b] pr_wo1 = pr_wo[b] pr_wn1 = len(pr_wo1) g_wn1 = g_wn[b] if g_wn1 != pr_wn1: continue else: # Sort based on wc sequence. if mode == 'test': idx = argsort(array(g_wc1)) g_wo1_s = array(g_wo1)[idx] g_wo1_s = list(g_wo1_s) elif mode == 'train': # due to teacher forcing, no need to sort. g_wo1_s = g_wo1 else: raise ValueError if type(pr_wo1) != list: raise TypeError if g_wo1_s == pr_wo1: count += 1 return count def get_count_wo_list(g_wn, g_wc, g_wo, pr_wc, pr_wo, mode): """ pr's are all sorted as pr_wc are sorted in increasing order (in column idx) However, g's are not sorted. Sort g's in increasing order (in column idx) """ count_list=[] for b, g_wo1 in enumerate(g_wo): g_wc1 = g_wc[b] pr_wc1 = pr_wc[b] pr_wo1 = pr_wo[b] pr_wn1 = len(pr_wo1) g_wn1 = g_wn[b] if g_wn1 != pr_wn1: count_list.append(0) continue else: # Sort based wc sequence. if mode == 'test': idx = argsort(array(g_wc1)) g_wo1_s = array(g_wo1)[idx] g_wo1_s = list(g_wo1_s) elif mode == 'train': # due to tearch forcing, no need to sort. g_wo1_s = g_wo1 else: raise ValueError if type(pr_wo1) != list: raise TypeError if g_wo1_s == pr_wo1: count_list.append(1) else: count_list.append(0) return count_list def get_count_wv(g_wn, g_wc, g_wvi, pr_wvi, mode): """ usalbe only when g_wc was used to find pr_wv g_wvi """ count = 0 for b, g_wvi1 in enumerate(g_wvi): pr_wvi1 = pr_wvi[b] g_wc1 = g_wc[b] pr_wn1 = len(pr_wvi1) g_wn1 = g_wn[b] # Now sorting. # Sort based wc sequence. if mode == 'test': idx1 = argsort(array(g_wc1)) elif mode == 'train': idx1 = list( range( g_wn1) ) else: raise ValueError if g_wn1 != pr_wn1: continue else: flag = True for i_wn, idx11 in enumerate(idx1): g_wvi11 = g_wvi1[idx11] pr_wvi11 = pr_wvi1[i_wn] if g_wvi11 != pr_wvi11: flag = False # print(g_wv1, g_wv11) # print(pr_wv1, pr_wv11) # input('') break if flag: count += 1 return count def get_count_wvi_list(g_wn, g_wc, g_wvi, pr_wvi, mode): """ usalbe only when g_wc was used to find pr_wv """ count_list =[] for b, g_wvi1 in enumerate(g_wvi): g_wc1 = g_wc[b] pr_wvi1 = pr_wvi[b] pr_wn1 = len(pr_wvi1) g_wn1 = g_wn[b] # Now sorting. # Sort based wc sequence. if mode == 'test': idx1 = argsort(array(g_wc1)) elif mode == 'train': idx1 = list( range( g_wn1) ) else: raise ValueError if g_wn1 != pr_wn1: count_list.append(0) continue else: flag = True for i_wn, idx11 in enumerate(idx1): if idx11<len(g_wvi1): g_wvi11 = g_wvi1[idx11] pr_wvi11 = pr_wvi1[i_wn] if g_wvi11 != pr_wvi11: flag = False # print(g_wv1, g_wv11) # print(pr_wv1, pr_wv11) # input('') break if flag: count_list.append(1) else: count_list.append(0) return count_list def get_count_wv_list(g_wn, g_wc, g_sql_i, pr_sql_i, mode): """ usalbe only when g_wc was used to find pr_wv """ count_list =[] for b, g_wc1 in enumerate(g_wc): pr_wn1 = len(pr_sql_i[b]["conds"]) g_wn1 = g_wn[b] # Now sorting. # Sort based wc sequence. if mode == 'test': idx1 = argsort(array(g_wc1)) elif mode == 'train': idx1 = list( range( g_wn1) ) else: raise ValueError if g_wn1 != pr_wn1: count_list.append(0) continue else: flag = True for i_wn, idx11 in enumerate(idx1): g_wvi_str11 = str(g_sql_i[b]["conds"][idx11][2]).lower() pr_wvi_str11 = str(pr_sql_i[b]["conds"][i_wn][2]).lower() # print(g_wvi_str11) # print(pr_wvi_str11) # print(g_wvi_str11==pr_wvi_str11) if g_wvi_str11 != pr_wvi_str11: flag = False # print(g_wv1, g_wv11) # print(pr_wv1, pr_wv11) # input('') break if flag: count_list.append(1) else: count_list.append(0) return count_list def get_count_sw(g_sc, g_sa, g_wn, g_wc, g_wo, g_wvi, pr_sc, pr_sa, pr_wn, pr_wc, pr_wo, pr_wvi, mode): """ usalbe only when g_wc was used to find pr_wv """ count_sc = get_count_sc(g_sc, pr_sc) count_sa = get_count_sa(g_sa, pr_sa) count_wn = get_count_wn(g_wn, pr_wn) count_wc = get_count_wc(g_wc, pr_wc) count_wo = get_count_wo(g_wn, g_wc, g_wo, pr_wc, pr_wo, mode) count_wv = get_count_wv(g_wn, g_wc, g_wvi, pr_wvi, mode) return count_sc, count_sa, count_wn, count_wc, count_wo, count_wv def get_count_sw_list(g_sc, g_sa, g_wn, g_wc, g_wo, g_wvi, pr_sc, pr_sa, pr_wn, pr_wc, pr_wo, pr_wvi, g_sql_i, pr_sql_i, mode): """ usalbe only when g_wc was used to find pr_wv """ count_sc = get_count_sc_list(g_sc, pr_sc) count_sa = get_count_sc_list(g_sa, pr_sa) count_wn = get_count_sc_list(g_wn, pr_wn) count_wc = get_count_wc_list(g_wc, pr_wc) count_wo = get_count_wo_list(g_wn, g_wc, g_wo, pr_wc, pr_wo, mode) if pr_wvi: count_wvi = get_count_wvi_list(g_wn, g_wc, g_wvi, pr_wvi, mode) else: count_wvi = [0]*len(count_sc) count_wv = get_count_wv_list(g_wn, g_wc, g_sql_i, pr_sql_i, mode) # compare using wv-str which presented in original data. return count_sc, count_sa, count_wn, count_wc, count_wo, count_wvi, count_wv def get_count_lx_list(count_sc1, count_sa1, count_wn1, count_wc1, count_wo1, count_wv1): # all count are list here. count_list = [] count_lx = 0 for csc, csa, cwn, cwc, cwo, cwv in zip(count_sc1, count_sa1, count_wn1, count_wc1, count_wo1, count_wv1): if csc and csa and cwn and cwc and cwo and cwv: count_list.append(1) else: count_list.append(0) return count_list def get_count_x_list(engine, tb, gt_select_column, g_sa, g_sql_i, pred_select_column, pr_sa, pr_sql_i): count_x1_list = [] g_ans = [] pr_ans = [] for b in range(len(gt_select_column)): g_ans1 = engine.execute(tb[b]['id'], gt_select_column[b], g_sa[b], g_sql_i[b]['conds']) # print(f'count: {count}') # print(f"pr_sql_i: {pr_sql_i[b]['conds']}") try: pr_ans1 = engine.execute(tb[b]['id'], pred_select_column[b], pr_sa[b], pr_sql_i[b]['conds']) if bool(pr_ans1): # not empty due to lack of the data from incorretly generated sql if g_ans1 == pr_ans1: count_x1 = 1 else: count_x1 = 0 else: count_x1 = 0 except: # type error etc... Execution-guided decoding may be used here. pr_ans1 = None count_x1 = 0 count_x1_list.append(count_x1) g_ans.append(g_ans1) pr_ans.append(pr_ans1) return count_x1_list, g_ans, pr_ans def get_mean_grad(named_parameters): """ Get list of mean, std of grad of each parameters Code based on web searched result.. """ mu_list = [] sig_list = [] for name, param in named_parameters: if param.requires_grad: # and ("bias" not in name) : # bias makes std = nan as it is of single parameters magnitude = param.grad.abs() mu_list.append(magnitude.mean()) if len(magnitude) == 1: # why nan for single param? Anyway to avoid that.. sig_list.append(torch.tensor(0)) else: sig_list.append(magnitude.std()) # if "svp_se" return mu_list, sig_list def generate_sql_i_v2(pr_sc, pr_sa, pr_wn, pr_wc, pr_wo, pr_wv_str, nlu): pr_sql_i = [] for b, nlu1 in enumerate(nlu): conds = [] for i_wn in range(pr_wn[b]): conds1 = [] conds1.append(pr_wc[b][i_wn]) conds1.append(pr_wo[b][i_wn]) merged_wv11 = merge_wv_t1_eng(pr_wv_str[b][i_wn], nlu[b]) conds1.append(merged_wv11) conds.append(conds1) pr_sql_i1 = {'agg': pr_sa[b].data.cpu().numpy().tolist(), 'sel': pr_sc[b].data.cpu().numpy().tolist(), 'conds': conds} pr_sql_i.append(pr_sql_i1) return pr_sql_i def generate_sql_i(pr_sc, pr_sa, pr_wn, pr_wc, pr_wo, pr_wv_str, nlu): pr_sql_i = [] for b, nlu1 in enumerate(nlu): conds = [] for i_wn in range(pr_wn[b]): conds1 = [] conds1.append(pr_wc[b][i_wn]) conds1.append(pr_wo[b][i_wn]) merged_wv11 = merge_wv_t1_eng(pr_wv_str[b][i_wn], nlu[b]) conds1.append(merged_wv11) conds.append(conds1) pr_sql_i1 = {'agg': pr_sa[b], 'sel': pr_sc[b], 'conds': conds} pr_sql_i.append(pr_sql_i1) return pr_sql_i def save_for_evaluation(path_save, results, dset_name, ): path_save_file = os.path.join(path_save, f'results_{dset_name}.jsonl') with open(path_save_file, 'w', encoding='utf-8') as f: for i, r1 in enumerate(results): json_str = json.dumps(r1, ensure_ascii=False, default=json_default_type_checker) json_str += '\n' f.writelines(json_str) def save_for_evaluation_aux(path_save, results, dset_name, ): path_save_file = os.path.join(path_save, f'results_aux_{dset_name}.jsonl') with open(path_save_file, 'w', encoding='utf-8') as f: for i, r1 in enumerate(results): json_str = json.dumps(r1, ensure_ascii=False, default=json_default_type_checker) json_str += '\n' f.writelines(json_str) def check_sc_sa_pairs(tb, pr_sc, pr_sa, ): """ Check whether pr_sc, pr_sa are allowed pairs or not. agg_ops = ['', 'MAX', 'MIN', 'COUNT', 'SUM', 'AVG'] """ bS = len(pr_sc) check = [False] * bS for b, pr_sc1 in enumerate(pr_sc): pr_sa1 = pr_sa[b] hd_types1 = tb[b]['types'] hd_types11 = hd_types1[pr_sc1] if hd_types11 == 'text': if pr_sa1 == 0 or pr_sa1 == 3: # '' check[b] = True else: check[b] = False elif hd_types11 == 'real': check[b] = True else: raise Exception("New TYPE!!") return check def remap_sc_idx(idxs, pr_sc_beam): for b, idxs1 in enumerate(idxs): for i_beam, idxs11 in enumerate(idxs1): sc_beam_idx = idxs[b][i_beam][0] sc_idx = pr_sc_beam[b][sc_beam_idx] idxs[b][i_beam][0] = sc_idx return idxs def sort_and_generate_pr_w(pr_sql_i): pr_wc = [] pr_wo = [] pr_wv = [] for b, pr_sql_i1 in enumerate(pr_sql_i): conds1 = pr_sql_i1["conds"] pr_wc1 = [] pr_wo1 = [] pr_wv1 = [] # Generate for i_wn, conds11 in enumerate(conds1): pr_wc1.append( conds11[0]) pr_wo1.append( conds11[1]) pr_wv1.append( conds11[2]) # sort based on pr_wc1 idx = argsort(pr_wc1) pr_wc1 = array(pr_wc1)[idx].tolist() pr_wo1 = array(pr_wo1)[idx].tolist() pr_wv1 = array(pr_wv1)[idx].tolist() conds1_sorted = [] for i, idx1 in enumerate(idx): conds1_sorted.append( conds1[idx1] ) pr_wc.append(pr_wc1) pr_wo.append(pr_wo1) pr_wv.append(pr_wv1) pr_sql_i1['conds'] = conds1_sorted return pr_wc, pr_wo, pr_wv, pr_sql_i def generate_sql_q(sql_i, tb): sql_q = [] for b, sql_i1 in enumerate(sql_i): tb1 = tb[b] sql_q1 = generate_sql_q1(sql_i1, tb1) sql_q.append(sql_q1) return sql_q def generate_sql_q1(sql_i1, tb1): """ sql = {'sel': 5, 'agg': 4, 'conds': [[3, 0, '59']]} agg_ops = ['', 'max', 'min', 'count', 'sum', 'avg'] cond_ops = ['=', '>', '<', 'OP'] Temporal as it can show only one-time conditioned case. sql_query: real sql_query sql_plus_query: More redable sql_query "PLUS" indicates, it deals with the some of db specific facts like PCODE <-> NAME """ agg_ops = ['', 'max', 'min', 'count', 'sum', 'avg'] cond_ops = ['=', '>', '<', 'OP'] headers = tb1["header"] # select_header = headers[sql['sel']].lower() # try: # select_table = tb1["name"] # except: # print(f"No table name while headers are {headers}") select_table = tb1["id"] select_agg = agg_ops[sql_i1['agg']] select_header = headers[sql_i1['sel']] sql_query_part1 = f'SELECT {select_agg}({select_header}) ' where_num = len(sql_i1['conds']) if where_num == 0: sql_query_part2 = f'FROM {select_table}' # sql_plus_query_part2 = f'FROM {select_table}' else: sql_query_part2 = f'FROM {select_table} WHERE' # sql_plus_query_part2 = f'FROM {select_table_refined} WHERE' # ---------------------------------------------------------------------------------------------------------- for i in range(where_num): # check 'OR' # number_of_sub_conds = len(sql['conds'][i]) where_header_idx, where_op_idx, where_str = sql_i1['conds'][i] where_header = headers[where_header_idx] where_op = cond_ops[where_op_idx] if i > 0: sql_query_part2 += ' AND' # sql_plus_query_part2 += ' AND' sql_query_part2 += f" {where_header} {where_op} {where_str}" sql_query = sql_query_part1 + sql_query_part2 # sql_plus_query = sql_plus_query_part1 + sql_plus_query_part2 return sql_query def get_pnt_idx1(col_pool_type, st_ed): st, ed = st_ed if col_pool_type == 'start_tok': pnt_idx1 = st elif col_pool_type == 'end_tok': pnt_idx1 = ed elif col_pool_type == 'avg': pnt_idx1 = arange(st, ed, 1) return pnt_idx1 def gen_g_pnt_idx(g_wvi, sql_i, i_hds, i_sql_vocab, col_pool_type): """ sql_vocab = ( 0.. "sql none", "sql max", "sql min", "sql count", "sql sum", "sql average", ..5 6.. "sql select", "sql where", "sql and", .. 8 9.. "sql equal", "sql greater than", "sql less than", .. 11 12.. "sql start", "sql end" .. 13 ) """ g_pnt_idxs = [] for b, sql_i1 in enumerate(sql_i): i_sql_vocab1 = i_sql_vocab[b] i_hds1 = i_hds[b] g_pnt_idxs1 = [] # start token pnt_idx1 = get_pnt_idx1(col_pool_type, i_sql_vocab1[-2]) g_pnt_idxs1.append(pnt_idx1) # select token pnt_idx1 = get_pnt_idx1(col_pool_type, i_sql_vocab1[6]) g_pnt_idxs1.append(pnt_idx1) # select agg idx_agg = sql_i1["agg"] pnt_idx1 = get_pnt_idx1(col_pool_type, i_sql_vocab1[idx_agg]) g_pnt_idxs1.append(pnt_idx1) # select column idx_sc = sql_i1["sel"] pnt_idx1 = get_pnt_idx1(col_pool_type, i_hds1[idx_sc]) g_pnt_idxs1.append(pnt_idx1) conds = sql_i1["conds"] wn = len(conds) if wn <= 0: pass else: # select where pnt_idx1 = get_pnt_idx1(col_pool_type, i_sql_vocab1[7]) g_pnt_idxs1.append(pnt_idx1) for i_wn, conds1 in enumerate(conds): # where column idx_wc = conds1[0] pnt_idx1 = get_pnt_idx1(col_pool_type, i_hds1[idx_wc]) g_pnt_idxs1.append(pnt_idx1) # where op idx_wo = conds1[1] pnt_idx1 = get_pnt_idx1(col_pool_type, i_sql_vocab1[idx_wo + 9]) g_pnt_idxs1.append(pnt_idx1) # where val st, ed = g_wvi[b][i_wn] end_pos_of_sql_vocab = i_sql_vocab1[-1][-1] g_pnt_idxs1.append(st + 1 + end_pos_of_sql_vocab) # due to inital [CLS] token in BERT-input vector g_pnt_idxs1.append(ed + 1 + end_pos_of_sql_vocab) # due to inital [CLS] token in BERT-input vector # and token if i_wn < wn - 1: pnt_idx1 = get_pnt_idx1(col_pool_type, i_sql_vocab1[8]) g_pnt_idxs1.append(pnt_idx1) # end token pnt_idx1 = get_pnt_idx1(col_pool_type, i_sql_vocab1[-1]) g_pnt_idxs1.append(pnt_idx1) g_pnt_idxs.append(g_pnt_idxs1) return g_pnt_idxs def pred_pnt_idxs(score, pnt_start_tok, pnt_end_tok): pr_pnt_idxs = [] for b, score1 in enumerate(score): # score1 = [T, max_seq_length] pr_pnt_idxs1 = [pnt_start_tok] for t, score11 in enumerate(score1): pnt = score11.argmax().item() pr_pnt_idxs1.append(pnt) if pnt == pnt_end_tok: break pr_pnt_idxs.append(pr_pnt_idxs1) return pr_pnt_idxs def generate_sql_q_s2s(pnt_idxs, tokens, tb): sql_q = [] for b, pnt_idxs1 in enumerate(pnt_idxs): tb1 = tb[b] sql_q1 = generate_sql_q1_s2s(pnt_idxs1, tokens[b], tb1) sql_q.append(sql_q1) return sql_q def generate_sql_q1_s2s(pnt_idxs1, tokens1, tb1): """ agg_ops = ['', 'max', 'min', 'count', 'sum', 'avg'] cond_ops = ['=', '>', '<', 'OP'] Temporal as it can show only one-time conditioned case. sql_query: real sql_query sql_plus_query: More redable sql_query "PLUS" indicates, it deals with the some of db specific facts like PCODE <-> NAME """ sql_query = "" for t, pnt_idxs11 in enumerate(pnt_idxs1): tok = tokens1[pnt_idxs11] sql_query += tok if t < len(pnt_idxs1)-1: sql_query += " " return sql_query # Generate sql_i from pnt_idxs def find_where_pnt_belong(pnt, vg): idx_sub = -1 for i, st_ed in enumerate(vg): st, ed = st_ed if pnt < ed and pnt >= st: idx_sub = i return idx_sub def gen_pnt_i_from_pnt(pnt, i_sql_vocab1, i_nlu1, i_hds1): # Find where it belong vg_list = [i_sql_vocab1, [i_nlu1], i_hds1] # as i_nlu has only single st and ed i_vg = -1 i_vg_sub = -1 for i, vg in enumerate(vg_list): idx_sub = find_where_pnt_belong(pnt, vg) if idx_sub > -1: i_vg = i i_vg_sub = idx_sub break return i_vg, i_vg_sub def gen_i_vg_from_pnt_idxs(pnt_idxs, i_sql_vocab, i_nlu, i_hds): i_vg_list = [] i_vg_sub_list = [] for b, pnt_idxs1 in enumerate(pnt_idxs): # if properly generated, sql_q1_list = [] i_vg_list1 = [] # index of (sql_vocab, nlu, hds) i_vg_sub_list1 = [] # index inside of each vocab group for t, pnt in enumerate(pnt_idxs1): i_vg, i_vg_sub = gen_pnt_i_from_pnt(pnt, i_sql_vocab[b], i_nlu[b], i_hds[b]) i_vg_list1.append(i_vg) i_vg_sub_list1.append(i_vg_sub) # sql_q1 = sql_q1.join(' ') # sql_q.append(sql_q1) i_vg_list.append(i_vg_list1) i_vg_sub_list.append(i_vg_sub_list1) return i_vg_list, i_vg_sub_list def gen_sql_q_from_i_vg(tokens, nlu, nlu_t, hds, tt_to_t_idx, pnt_start_tok, pnt_end_tok, pnt_idxs, i_vg_list, i_vg_sub_list): """ ( "none", "max", "min", "count", "sum", "average", "select", "where", "and", "equal", "greater than", "less than", "start", "end" ), """ sql_q = [] sql_i = [] for b, nlu_t1 in enumerate(nlu_t): sql_q1_list = [] sql_i1 = {} tt_to_t_idx1 = tt_to_t_idx[b] nlu_st_observed = False agg_observed = False wc_obs = False wo_obs = False conds = [] for t, i_vg in enumerate(i_vg_list[b]): i_vg_sub = i_vg_sub_list[b][t] pnt = pnt_idxs[b][t] if i_vg == 0: # sql_vocab if pnt == pnt_start_tok or pnt == pnt_end_tok: pass else: tok = tokens[b][pnt] if tok in ["none", "max", "min", "count", "sum", "average"]: agg_observed = True if tok == "none": pass sql_i1["agg"] = ["none", "max", "min", "count", "sum", "average"].index(tok) else: if tok in ["greater", "less", "equal"]: if tok == 'greater': tok = '>' elif tok == 'less': tok = '<' elif tok == 'equal': tok = '=' # gen conds1 if wc_obs: conds1.append( ['=','>','<'].index(tok) ) wo_obs = True sql_q1_list.append(tok) elif i_vg == 1: # nlu case if not nlu_st_observed: idx_nlu_st = pnt nlu_st_observed = True else: # now to wrap up idx_nlu_ed = pnt st_wh_idx = tt_to_t_idx1[idx_nlu_st - pnt_end_tok - 2] ed_wh_idx = tt_to_t_idx1[idx_nlu_ed - pnt_end_tok - 2] pr_wv_str11 = nlu_t1[st_wh_idx:ed_wh_idx + 1] merged_wv11 = merge_wv_t1_eng(pr_wv_str11, nlu[b]) sql_q1_list.append(merged_wv11) nlu_st_observed = False if wc_obs and wo_obs: conds1.append(merged_wv11) conds.append(conds1) wc_obs = False wo_obs = False elif i_vg == 2: # headers tok = hds[b][i_vg_sub] if agg_observed: sql_q1_list.append(f"({tok})") sql_i1["sel"] = i_vg_sub agg_observed = False else: wc_obs = True conds1 = [i_vg_sub] sql_q1_list.append(tok) # insert table name between. sql_i1["conds"] = conds sql_i.append(sql_i1) sql_q1 = ' '.join(sql_q1_list) sql_q.append(sql_q1) return sql_q, sql_i def get_count_lx_list_s2s(g_pnt_idxs, pr_pnt_idxs): # all count are list here. count_list = [] for b, g_pnt_idxs1 in enumerate(g_pnt_idxs): pr_pnt_idxs1 = pr_pnt_idxs[b] if g_pnt_idxs1 == pr_pnt_idxs1: count_list.append(1) else: count_list.append(0) return count_list def get_wemb_h_FT_Scalar_1(i_hds, l_hs, hS, all_encoder_layer, col_pool_type='start_tok'): """ As if [ [table-1-col-1-tok1, t1-c1-t2, ...], [t1-c2-t1, t1-c2-t2, ...]. ... [t2-c1-t1, ...,] ] # i_hds = [ [ Batch 1 ] [ Batch 2 ] ] # [Batch 1] = [ (col1_st_idx, col1_ed_idx), (col2_st_idx, col2_ed_idx), ...] # i_hds = [[(11, 14), (15, 19), (20, 21), (22, 24), (25, 27), (28, 29)], # [(16, 19), (20, 24), (25, 26), (27, 29), (30, 32), (33, 34)]] pool_type = 'start_tok', 'end_tok', 'avg' """ bS = len(l_hs) l_hs_max = max(l_hs) wemb_h = torch.zeros([bS, l_hs_max, hS]).to(device) for b, i_hds1 in enumerate(i_hds): for i_hd, st_ed_pair in enumerate(i_hds1): st, ed = st_ed_pair if col_pool_type == 'start_tok': vec = all_encoder_layer[-1][b, st,:] elif col_pool_type == 'end_tok': vec = all_encoder_layer[-1][b, ed, :] elif col_pool_type == 'avg': vecs = all_encoder_layer[-1][b, st:ed,:] vec = vecs.mean(dim=1, keepdim=True) else: raise ValueError wemb_h[b, i_hd, :] = vec return wemb_h def cal_prob(s_sc, s_sa, s_wn, s_wc, s_wo, s_wv, pr_sc, pr_sa, pr_wn, pr_wc, pr_wo, pr_wvi): """ :param s_sc: [B, l_h] :param s_sa: [B, l_a] # 16 :param s_wn: [B, 5] :param s_wc: [B, l_h] :param s_wo: [B, 4, l_o] # :param s_wv: [B, 4, 22] :return: """ # First get selected index # # Predict prob p_sc = cal_prob_sc(s_sc, pr_sc) p_sa = cal_prob_sa(s_sa, pr_sa) p_wn = cal_prob_wn(s_wn, pr_wn) p_wc = cal_prob_wc(s_wc, pr_wc) p_wo = cal_prob_wo(s_wo, pr_wo) p_wvi = cal_prob_wvi_se(s_wv, pr_wvi) # calculate select-clause probability p_select = cal_prob_select(p_sc, p_sa) # calculate where-clause probability p_where = cal_prob_where(p_wn, p_wc, p_wo, p_wvi) # calculate total probability p_tot = cal_prob_tot(p_select, p_where) return p_tot, p_select, p_where, p_sc, p_sa, p_wn, p_wc, p_wo, p_wvi def cal_prob_tot(p_select, p_where): p_tot = [] for b, p_select1 in enumerate(p_select): p_where1 = p_where[b] p_tot.append( p_select1 * p_where1 ) return p_tot def cal_prob_select(p_sc, p_sa): p_select = [] for b, p_sc1 in enumerate(p_sc): p1 = 1.0 p1 *= p_sc1 p1 *= p_sa[b] p_select.append(p1) return p_select def cal_prob_where(p_wn, p_wc, p_wo, p_wvi): p_where = [] for b, p_wn1 in enumerate(p_wn): p1 = 1.0 p1 *= p_wn1 p_wc1 = p_wc[b] for i_wn, p_wc11 in enumerate(p_wc1): p_wo11 = p_wo[b][i_wn] p_wv11_st, p_wv11_ed = p_wvi[b][i_wn] p1 *= p_wc11 p1 *= p_wo11 p1 *= p_wv11_st p1 *= p_wv11_ed p_where.append(p1) return p_where def cal_prob_sc(s_sc, pr_sc): ps = F.softmax(s_sc, dim=1) p = [] for b, ps1 in enumerate(ps): pr_sc1 = pr_sc[b] p1 = ps1[pr_sc1] p.append(p1.item()) return p def cal_prob_sa(s_sa, pr_sa): ps = F.softmax(s_sa, dim=1) p = [] for b, ps1 in enumerate(ps): pr_sa1 = pr_sa[b] p1 = ps1[pr_sa1] p.append(p1.item()) return p def cal_prob_wn(s_wn, pr_wn): ps = F.softmax(s_wn, dim=1) p = [] for b, ps1 in enumerate(ps): pr_wn1 = pr_wn[b] p1 = ps1[pr_wn1] p.append(p1.item()) return p def cal_prob_wc(s_wc, pr_wc): ps = torch.sigmoid(s_wc) ps_out = [] for b, pr_wc1 in enumerate(pr_wc): ps1 = array(ps[b].cpu()) ps_out1 = ps1[pr_wc1] ps_out.append(list(ps_out1)) return ps_out def cal_prob_wo(s_wo, pr_wo): # assume there is always at least single condition. ps = F.softmax(s_wo, dim=2) ps_out = [] for b, pr_wo1 in enumerate(pr_wo): ps_out1 = [] for n, pr_wo11 in enumerate(pr_wo1): ps11 = ps[b][n] ps_out1.append( ps11[pr_wo11].item() ) ps_out.append(ps_out1) return ps_out def cal_prob_wvi_se(s_wv, pr_wvi): prob_wv = F.softmax(s_wv, dim=-2).detach().to('cpu').numpy() p_wv = [] for b, pr_wvi1 in enumerate(pr_wvi): p_wv1 = [] for i_wn, pr_wvi11 in enumerate(pr_wvi1): st, ed = pr_wvi11 p_st = prob_wv[b, i_wn, st, 0] p_ed = prob_wv[b, i_wn, ed, 1] p_wv1.append([p_st, p_ed]) p_wv.append(p_wv1) return p_wv def generate_inputs_s2s(tokenizer, nlu1_tt, hds1, sql_vocab1): """ [CLS] sql_vocab [SEP] question [SEP] headers To make sql_vocab in a fixed position. """ tokens = [] segment_ids = [] tokens.append("[CLS]") # sql_vocab i_sql_vocab = [] # for doc for i, sql_vocab11 in enumerate(sql_vocab1): i_st_sql = len(tokens) sub_tok = tokenizer.tokenize(sql_vocab11) tokens += sub_tok i_ed_sql = len(tokens) i_sql_vocab.append((i_st_sql, i_ed_sql)) segment_ids += [1] * len(sub_tok) if i < len(sql_vocab1) - 1: tokens.append("[SEP]") segment_ids.append(0) elif i == len(sql_vocab1) - 1: tokens.append("[SEP]") segment_ids.append(1) else: raise EnvironmentError # question i_st_nlu = len(tokens) # to use it later segment_ids.append(0) for token in nlu1_tt: tokens.append(token) segment_ids.append(0) i_ed_nlu = len(tokens) tokens.append("[SEP]") segment_ids.append(0) i_nlu = (i_st_nlu, i_ed_nlu) # headers i_hds = [] # for doc for i, hds11 in enumerate(hds1): i_st_hd = len(tokens) sub_tok = tokenizer.tokenize(hds11) tokens += sub_tok i_ed_hd = len(tokens) i_hds.append((i_st_hd, i_ed_hd)) segment_ids += [1] * len(sub_tok) if i < len(hds1)-1: tokens.append("[SEP]") segment_ids.append(0) elif i == len(hds1)-1: tokens.append("[SEP]") segment_ids.append(1) else: raise EnvironmentError return tokens, segment_ids, i_sql_vocab, i_nlu, i_hds def sort_pred_wherecolumn(pr_wc, g_wc): """ Input: list pr_wc = [B, n_conds] g_wc = [B, n_conds] Return: list pr_wc_sorted = [B, n_conds] """ pr_wc_sorted = [] for b, pr_wc1 in enumerate(pr_wc): g_wc1 = g_wc[b] pr_wc1_sorted = [] if set(g_wc1) == set(pr_wc1): pr_wc1_sorted = deepcopy(g_wc1) else: # no sorting when g_wc1 and pr_wc1 are different. pr_wc1_sorted = deepcopy(pr_wc1) pr_wc_sorted.append(pr_wc1_sorted) return pr_wc_sorted
from GPIOLibrary import GPIOProcessor from CharacterLibrary import Alphabet as AL import time class LEDBlock: global OP_OP NO_OP = 0x0000 global OP_0 OP_0 = 0x0100 global OP_1 OP_1 = 0x0200 global OP_2 OP_2 = 0x0300 global OP_3 OP_3 = 0x0400 global OP_4 OP_4 = 0x0500 global OP_5 OP_5 = 0x0600 global OP_6 OP_6 = 0x0700 global OP_7 OP_7 = 0x0800 global OP_DECODEMODE OP_DECODEMODE = 0x0900 global OP_INTENSITY OP_INTENSITY = 0x0A00 global OP_SCANLIMIT OP_SCANLIMIT = 0x0B00 global OP_SHUTDOWN OP_SHUTDOWN = 0x0C00 global OP_DISPLAYTEST OP_DISPLAYTEST = 0x0F00 global numOfDevices global status status = [[0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0]] global intensityStatus intensityStatus = [0, 0, 0, 0, 0, 0, 0, 0] global shutdownStatus shutdownStatus = [0, 0, 0, 0, 0, 0, 0, 0] global scanStatus scanStatus = [0, 0, 0, 0, 0, 0, 0, 0] global testStatus testStatus = [0, 0, 0, 0, 0, 0, 0, 0] global Data Data = [0, 0, 0, 0, 0, 0, 0, 0] global Code global TOTAL TOTAL = 0xFF def __init__(self, devices=1, intensity=5, scanlimit=7): '''Constructor ScanLimit set to 7 Intensity set to 5 out of 0:15 Uses GPIOs 23, 24 25 as DIN, CS, and CLK respectively''' GP = GPIOProcessor() global DIN global CS global CLK DIN = GP.getPin34() # Gpio CS = GP.getPin33() # Gpio CLK = GP.getPin32() # Gpio DIN.out() CS.out() CLK.out() global numOfDevices numOfDevices = devices for i in range(0,numOfDevices): self.shutDown(False,i+1) for i in range(0,numOfDevices): self.setScanLimit(scanlimit,i+1) for i in range(0,numOfDevices): self.setIntensity(intensity,i+1) self.clearDisplays() global Characters Characters = AL() def getStatus(self, choice=None): '''Returns current status''' if choice=="intensity": return intensityStatus elif choice=="scan": return scanStatus elif choice=="test": return testStatus elif choice=="shutdown": return shutdownStatus else: return status def createInstruction(self, device, opCode, data): '''Create an instruction''' global Data for i in range(0,device): Data[numOfDevices-i-1] = opCode | data[i] def transferInstruction(self, device, instruction): '''Shifts in the instructions''' DIN.low() CLK.low() CS.low() for j in range(0, numOfDevices): bitmask = 0x8000 for i in range(0, 16): CLK.low() if instruction[j] & bitmask == bitmask: DIN.high() else: DIN.low() CLK.high() bitmask = bitmask >> 1 CS.high() def setRow(self, row, data, device=1): '''Choose row 1-8 and send data for LEDs in that row''' global status status[row-1][device-1] = data rowOp = row*256 self.createInstruction(device, rowOp, status[row-1][0:device]) self.transferInstruction(device, Data) # def setColumn(self, col, data): '''Choose column 1-8 and send data for LEDs in that column''' cdata = 2**(8-col) bitmask = 0x01 for i in range(1,9): if data & bitmask == bitmask: self.setRow(i, cdata) bitmask = bitmask << 1 # def setLED(self, row, col, value,device=1): '''Choose row and column of LED to turn on or off, with TRUE or FALSE''' cdata = 2**(8-col) if value == 1: cdata |= status[row-1][device-1] elif value == 0: cdata = TOTAL - cdata cdata &= status[row-1][device-1] else: print "On or Off?" self.setRow(row, cdata) def printLetter(self, letter, rotate, device=1): '''Displays the given letter''' letter = letter.upper() global data if rotate == True: let = Characters.setLetterR(letter) else: let = Characters.setLetter(letter) for i in range(0,8): data = let[i] self.setRow(i+1,data,device) def printNumber(self, number, device=1): '''Displays the given number''' global data num = Characters.setNumber(number) for i in range(0,8): data = num[i] self.setRow(i+1,data,device) def printDice(self, number, device=1): '''Displays the given number''' global data num = Characters.setDiceNumber(number) for i in range(0,8): data = num[i] self.setRow(i+1,data,device) def printWord(self, word): '''Prints the word given one letter at a time''' Time = 0.5 for i in range(0,len(word)): if word[i].isdigit() == False: self.printLetter(word[i],True) else: num = word[i] self.printNumber(num) time.sleep(Time) def clearDisplay(self, device=1): '''Clears the Display choosen''' for i in range(1, 9): self.setRow(i,0x00,device) def clearDisplays(self): '''Clears all of the Displays''' for k in range(0,numOfDevices): self.clearDisplay(k+1) def setIntensity(self, intensity, device): '''Sets intensity of LED. min: 0 --- max : 15''' global intensityStatus intensityStatus[device-1] = intensity self.createInstruction(device, OP_INTENSITY, intensityStatus[0:device]) self.transferInstruction(device, Data) def setScanLimit(self, limit, device): '''The limit shoud be an integer: 0-7.''' global scanStatus scanStatus[device-1] = limit self.createInstruction(device, OP_SCANLIMIT, scanStatus[0:device]) self.transferInstruction(device, Data) def shutDown(self, boolean, device): '''Brings the block into power saving mode.''' global shutdownStatus if boolean: shutdownStatus[device-1] = 0 self.createInstruction(device, OP_SHUTDOWN, shutdownStatus[0:device]) self.transferInstruction(device, Data) else: shutdownStatus[device-1] = 1 self.createInstruction(device, OP_SHUTDOWN, shutdownStatus[0:device]) self.transferInstruction(device, Data) def displayTest(self, duration, device): '''Turn on all LEDs to test the display for the duration specified.''' global testStatus testStatus[device-1] = 1 self.createInstruction(device, OP_DISPLAYTEST, testStatus[0:device]) self.transferInstruction(device, Data) time.sleep(duration) self.exitTest(device) def exitTest(self, device): '''If the LED block is in Test Mode this will exit.''' global testStatus testStatus[device-1] = 0 self.createInstruction(device, OP_DISPLAYTEST, testStatus[0:device]) self.transferInstruction(device, Data) def cleanup(self): DIN.closePin() CS.closePin() CLK.closePin() ## DEMOS ############ def sixtyFour(self): '''Lights up each of the 64 LEDs individually''' for i in range(1, 9): for j in range(0, 8): data = 2**(7-j) self.setRow(i, data) time.sleep(0.05) self.setRow(i, 0) def diagonal(self, device=1): '''Lights up a wave around the diagonal''' for j in range(0, 1): a = 0B1 for i in range(1, 9): self.setRow(i, a, device) time.sleep(0.025) self.setRow(i, 0, device) a = a << 1 a += 1 a = 0B10000000 for i in range(1, 9): self.setRow(9-i, a, device) time.sleep(0.025) self.setRow(9-i, 0, device) a = a >> 1 a += 0B10000000 def swirl(self): '''Lights up the Leds in a clockwise swirl pattern''' Time = 0.025 for i in range(1,5): for j in range(i,10-i): self.setLED(i, j, True) time.sleep(Time) if i < 4: for j in range(i+1,9-i): self.setLED(j, 9-i, True) time.sleep(Time) for j in range(i,10-i): self.setLED(9-i, 9-j, True) time.sleep(Time) if i < 4: for j in range(i+1,9-i): self.setLED(9-j, i, True) time.sleep(Time) time.sleep(0.5) self.clearDisplay() def allOnOff(self): '''Turns all LEDs on one by one and then off''' ListValue = [True, False] for k in ListValue: for i in range(1,9): for j in range(1,9): self.setLED(i,j,k) time.sleep(0.025) def showAlphabet(self): '''Displays all characters of the alphabet''' self.printWord("abcdefghijklmnopqrstuvwxyz") self.clearDisplay() def showDigits(self): '''Displays all digits''' self.printWord("1234567890") self.clearDisplay() def helloWorld(self): '''Classic Hello World''' self.printWord("Hello World!") self.clearDisplay(1)
# Copyright 2016 The Kubernetes Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import unittest from datetime import datetime from .dateutil import UTC, TimezoneInfo, format_rfc3339, parse_rfc3339 class DateUtilTest(unittest.TestCase): def _parse_rfc3339_test(self, st, y, m, d, h, mn, s): actual = parse_rfc3339(st) expected = datetime(y, m, d, h, mn, s, 0, UTC) self.assertEqual(expected, actual) def test_parse_rfc3339(self): self._parse_rfc3339_test("2017-07-25T04:44:21Z", 2017, 7, 25, 4, 44, 21) self._parse_rfc3339_test("2017-07-25 04:44:21Z", 2017, 7, 25, 4, 44, 21) self._parse_rfc3339_test("2017-07-25T04:44:21", 2017, 7, 25, 4, 44, 21) self._parse_rfc3339_test("2017-07-25T04:44:21z", 2017, 7, 25, 4, 44, 21) self._parse_rfc3339_test("2017-07-25T04:44:21+03:00", 2017, 7, 25, 1, 44, 21) self._parse_rfc3339_test("2017-07-25T04:44:21-03:00", 2017, 7, 25, 7, 44, 21) def test_format_rfc3339(self): self.assertEqual( format_rfc3339(datetime(2017, 7, 25, 4, 44, 21, 0, UTC)), "2017-07-25T04:44:21Z") self.assertEqual( format_rfc3339(datetime(2017, 7, 25, 4, 44, 21, 0, TimezoneInfo(2, 0))), "2017-07-25T02:44:21Z") self.assertEqual( format_rfc3339(datetime(2017, 7, 25, 4, 44, 21, 0, TimezoneInfo(-2, 30))), "2017-07-25T07:14:21Z")
import datetime from money import Money from api.config import Configuration from api.circulation_exceptions import * from core.model.patron import Patron from core.util import MoneyUtility class PatronUtility(object): """Apply circulation-specific logic to Patron model objects.""" @classmethod def needs_external_sync(cls, patron): """Could this patron stand to have their metadata synced with the remote? By default, all patrons get synced once every twelve hours. Patrons who lack borrowing privileges can always stand to be synced, since their privileges may have just been restored. """ if not patron.last_external_sync: # This patron has never been synced. return True now = datetime.datetime.utcnow() if cls.has_borrowing_privileges(patron): # A patron who has borrowing privileges gets synced every twelve # hours. Their account is unlikely to change rapidly. check_every = Patron.MAX_SYNC_TIME else: # A patron without borrowing privileges might get synced # every time they make a request. It's likely they are # taking action to get their account reinstated and we # don't want to make them wait twelve hours to get access. check_every = datetime.timedelta(seconds=5) expired_at = patron.last_external_sync + check_every if now > expired_at: return True return False @classmethod def has_borrowing_privileges(cls, patron): """Is the given patron allowed to check out books? :return: A boolean """ try: cls.assert_borrowing_privileges(patron) return True except CannotLoan, e: return False @classmethod def assert_borrowing_privileges(cls, patron): """Raise an exception unless the patron currently has borrowing privileges. :raises AuthorizationExpired: If the patron's authorization has expired. :raises OutstandingFines: If the patron has too many outstanding fines. """ now = datetime.datetime.utcnow() if not cls.authorization_is_active(patron): # The patron's card has expired. raise AuthorizationExpired() if cls.has_excess_fines(patron): raise OutstandingFines() from api.authenticator import PatronData if patron.block_reason is not None: if patron.block_reason is PatronData.EXCESSIVE_FINES: # The authentication mechanism itself may know that # the patron has outstanding fines, even if the circulation # manager is not configured to make that deduction. raise OutstandingFines() raise AuthorizationBlocked() @classmethod def has_excess_fines(cls, patron): """Does this patron have fines in excess of the maximum fine amount set for their library? :param a Patron: :return: A boolean """ if not patron.fines: return False if isinstance(patron.fines, Money): patron_fines = patron.fines else: patron_fines = MoneyUtility.parse(patron.fines) actual_fines = patron_fines.amount max_fines = Configuration.max_outstanding_fines(patron.library) if max_fines is not None and actual_fines > max_fines.amount: return True return False @classmethod def authorization_is_active(cls, patron): """Return True unless the patron's authorization has expired.""" # Unlike pretty much every other place in this app, we use # (server) local time here instead of UTC. This is to make it # less likely that a patron's authorization will expire before # they think it should. now = datetime.datetime.now() if (patron.authorization_expires and cls._to_date(patron.authorization_expires) < cls._to_date(now)): return False return True @classmethod def _to_date(cls, x): """Convert a datetime into a date. Leave a date alone.""" if isinstance(x, datetime.datetime): return x.date() return x
from __future__ import absolute_import from __future__ import unicode_literals import django from django.db import connections from django.db.models.sql import DeleteQuery, Query, UpdateQuery from django.db.models.sql.compiler import ( SQLCompiler, SQLDeleteCompiler, SQLUpdateCompiler, ) from .expressions import CTESubqueryResolver class CTEQuery(Query): """A Query which processes SQL compilation through the CTE compiler""" def __init__(self, *args, **kwargs): super(CTEQuery, self).__init__(*args, **kwargs) self._with_ctes = [] def combine(self, other, connector): if other._with_ctes: if self._with_ctes: raise TypeError("cannot merge queries with CTEs on both sides") self._with_ctes = other._with_ctes[:] return super(CTEQuery, self).combine(other, connector) def get_compiler(self, using=None, connection=None): """ Overrides the Query method get_compiler in order to return a CTECompiler. """ # Copy the body of this method from Django except the final # return statement. We will ignore code coverage for this. if using is None and connection is None: # pragma: no cover raise ValueError("Need either using or connection") if using: connection = connections[using] # Check that the compiler will be able to execute the query for alias, aggregate in self.annotation_select.items(): connection.ops.check_expression_support(aggregate) # Instantiate the custom compiler. klass = COMPILER_TYPES.get(self.__class__, CTEQueryCompiler) return klass(self, connection, using) def add_annotation(self, annotation, *args, **kw): annotation = CTESubqueryResolver(annotation) super(CTEQuery, self).add_annotation(annotation, *args, **kw) def __chain(self, _name, klass=None, *args, **kwargs): klass = QUERY_TYPES.get(klass, self.__class__) clone = getattr(super(CTEQuery, self), _name)(klass, *args, **kwargs) clone._with_ctes = self._with_ctes[:] return clone if django.VERSION < (2, 0): def clone(self, klass=None, *args, **kwargs): return self.__chain("clone", klass, *args, **kwargs) else: def chain(self, klass=None): return self.__chain("chain", klass) class CTECompiler(object): TEMPLATE = "{name} AS ({query})" @classmethod def generate_sql(cls, connection, query, as_sql): if query.combinator: return as_sql() ctes = [] params = [] for cte in query._with_ctes: compiler = cte.query.get_compiler(connection=connection) qn = compiler.quote_name_unless_alias cte_sql, cte_params = compiler.as_sql() ctes.append(cls.TEMPLATE.format(name=qn(cte.name), query=cte_sql)) params.extend(cte_params) # Always use WITH RECURSIVE # https://www.postgresql.org/message-id/13122.1339829536%40sss.pgh.pa.us sql = ["WITH RECURSIVE", ", ".join(ctes)] if ctes else [] base_sql, base_params = as_sql() sql.append(base_sql) params.extend(base_params) return " ".join(sql), tuple(params) class CTEUpdateQuery(UpdateQuery, CTEQuery): pass class CTEDeleteQuery(DeleteQuery, CTEQuery): pass QUERY_TYPES = { UpdateQuery: CTEUpdateQuery, DeleteQuery: CTEDeleteQuery, } class CTEQueryCompiler(SQLCompiler): def as_sql(self, *args, **kwargs): def _as_sql(): return super(CTEQueryCompiler, self).as_sql(*args, **kwargs) return CTECompiler.generate_sql(self.connection, self.query, _as_sql) class CTEUpdateQueryCompiler(SQLUpdateCompiler): def as_sql(self, *args, **kwargs): def _as_sql(): return super(CTEUpdateQueryCompiler, self).as_sql(*args, **kwargs) return CTECompiler.generate_sql(self.connection, self.query, _as_sql) class CTEDeleteQueryCompiler(SQLDeleteCompiler): # NOTE: it is currently not possible to execute delete queries that # reference CTEs without patching `QuerySet.delete` (Django method) # to call `self.query.chain(sql.DeleteQuery)` instead of # `sql.DeleteQuery(self.model)` def as_sql(self, *args, **kwargs): def _as_sql(): return super(CTEDeleteQueryCompiler, self).as_sql(*args, **kwargs) return CTECompiler.generate_sql(self.connection, self.query, _as_sql) COMPILER_TYPES = { CTEUpdateQuery: CTEUpdateQueryCompiler, CTEDeleteQuery: CTEDeleteQueryCompiler, }
# -*- coding: utf-8 -*- # Define your item pipelines here # # Don't forget to add your pipeline to the ITEM_PIPELINES setting # See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html from base.pipelines import BaseUrlPipeline, BaseDetailPipeline class ManongchangPipeline(BaseUrlPipeline): def __init__(self) -> None: super().__init__() class ManongchangDetailPipeline(BaseDetailPipeline): def __init__(self) -> None: super().__init__('monongchang')
(window.webpackJsonp=window.webpackJsonp||[]).push([[16,5],{112:function(t,e,n){"use strict";var r=n(135),i=(n(136),n(137)),o=(n(138),function(t){var e={exports:{}};t(e,e.exports);var n=e.exports.__esModule&&e.exports.default||e.exports;return"function"==typeof n?n:function(){return r.createElement("div",{},"Code snippet should export a component!")}}),s=o(function(t,e){var r=n(9);e.__esModule=!0,e.default=function(){return i.default.createElement(a,null)};var i=r(n(0)),o=(r(n(2)),n(151),n(149)),s=(n(68),r(n(132)));n(152);var a=function(){return i.default.createElement(s.default,null,i.default.createElement(o.SchemaForm,{labelCol:6,wrapperCol:6},i.default.createElement(o.Field,{type:"string",name:"name",title:"姓名",required:!0}),i.default.createElement(o.Field,{type:"string",name:"nickname",title:"昵称",required:!0}),i.default.createElement(o.Field,{type:"date",name:"birthday",title:"生日",description:"试试选择2018-11-30","x-rules":[function(t){return new Promise(function(e){setTimeout(function(){"2018-11-30"===t?e("不允许输入2018-11-30"):e()},1e3)})}],required:!0}),i.default.createElement(o.Field,{type:"string",name:"phone","x-rules":"phone",title:"手机号",required:!0}),i.default.createElement(o.Field,{type:"string",name:"qq","x-rules":"qq",title:"QQ号",required:!0}),i.default.createElement(o.Field,{type:"string",name:"email","x-rules":"email",title:"邮箱",required:!0}),i.default.createElement(o.Field,{type:"string",name:"home","x-rules":"url",title:"个人主页地址",required:!0}),i.default.createElement(o.Field,{type:"string",name:"money","x-rules":"money",title:"月薪","x-props":{placeholder:"¥100,000",addonAfter:"元"},required:!0}),i.default.createElement(o.Field,{type:"string",name:"idcard","x-rules":"idcard",title:"身份证",required:!0}),i.default.createElement(o.Field,{type:"string",name:"zip","x-rules":"zip",title:"邮政编码",required:!0}),i.default.createElement(o.Field,{type:"string",name:"custom","x-rules":function(t){return new Promise(function(e){setTimeout(function(){"123"===t?e("不允许输入123"):e()},1e3)})},title:"自定义校验规则",required:!0}),i.default.createElement(o.FormButtonGroup,{offset:6},i.default.createElement(o.Submit,null),i.default.createElement(o.Reset,null))))}}),a=o(function(t,e){var r=n(9);e.__esModule=!0,e.default=function(){return i.default.createElement(a,null)};var i=r(n(0)),o=(r(n(2)),n(151),n(149)),s=(n(68),r(n(132)));n(152);var a=function(){return i.default.createElement(s.default,null,i.default.createElement(o.SchemaForm,{labelCol:6,wrapperCol:6,effects:function(t,e){var n=e.setFieldState,r=e.getFieldState;t("onFieldChange","*(password,confirm)").subscribe(function(t){var e=t.name,i=t.value,o="password"==e?"confirm":"password",s=r(o,function(t){return t.value});n(o,function(t){t.errors=i&&s&&i!==s?"两次密码输入不一致":""}),n(e,function(t){t.errors=i&&s&&i!==s?"两次密码输入不一致":""})})}},i.default.createElement(o.Field,{type:"string",name:"username",title:"用户名",required:!0}),i.default.createElement(o.Field,{type:"password",name:"password",title:"密码","x-props":{checkStrength:!0},description:i.default.createElement("ul",null,i.default.createElement("li",null,"1. 长度不小于8个"),i.default.createElement("li",null,"2. 必须包含大小写数字符号")),required:!0}),i.default.createElement(o.Field,{type:"password",name:"confirm",title:"确认密码","x-props":{checkStrength:!0},required:!0}),i.default.createElement(o.FormButtonGroup,{offset:6},i.default.createElement(o.Submit,null),i.default.createElement(o.Reset,null))))}}),c=function(){return r.createElement(r.Fragment,{},r.createElement("h1",{id:"校验",className:"react-demo-h1"},"校验"),r.createElement("blockquote",{className:"react-demo-blockquote"},r.createElement("p",{className:"react-demo-p"},"校验和联动往往是相辅相成的,联动负责提升用户体验,引导用户一步步的完成数据输入\n,校验则是阻止用户输入任何非法数据"),r.createElement("p",{className:"react-demo-p"},"联动规则和校验规则的复杂度都会根据业务场景的复杂度而线性提升"),r.createElement("p",{className:"react-demo-p"},"还是借助 effects,我们可以方便的来处理各种场景的校验逻辑")),r.createElement("h3",{id:"简单数据校验",className:"react-demo-h3"},"简单数据校验"),r.createElement("blockquote",{className:"react-demo-blockquote"},r.createElement("p",{className:"react-demo-p"},"当前例子涉及基本的字符格式校验与自定义校验")),r.createElement("h4",{id:"demo-示例",className:"react-demo-h4"},"Demo 示例"),r.createElement(i,{code:'import React from \'react\'\nimport ReactDOM from \'react-dom\'\nimport { filter, withLatestFrom, map } from \'rxjs/operators\'\nimport {\n SchemaForm,\n Field,\n FormButtonGroup,\n Submit,\n Reset,\n FormItemGrid,\n FormCard,\n FormPath,\n FormBlock,\n FormLayout,\n createFormActions\n} from \'@uform/antd\'\nimport { Button } from \'antd\'\nimport Printer from \'@uform/printer\'\nimport \'antd/dist/antd.css\'\n\nconst App = () => (\n <Printer>\n <SchemaForm labelCol={6} wrapperCol={6}>\n <Field type="string" name="name" title="姓名" required />\n <Field type="string" name="nickname" title="昵称" required />\n <Field\n type="date"\n name="birthday"\n title="生日"\n description="试试选择2018-11-30"\n x-rules={[\n val =>\n new Promise(resolve => {\n setTimeout(() => {\n if (val === \'2018-11-30\') {\n resolve(\'不允许输入2018-11-30\')\n } else {\n resolve()\n }\n }, 1000)\n })\n ]}\n required\n />\n <Field\n type="string"\n name="phone"\n x-rules="phone"\n title="手机号"\n required\n />\n <Field type="string" name="qq" x-rules="qq" title="QQ号" required />\n <Field type="string" name="email" x-rules="email" title="邮箱" required />\n <Field\n type="string"\n name="home"\n x-rules="url"\n title="个人主页地址"\n required\n />\n <Field\n type="string"\n name="money"\n x-rules="money"\n title="月薪"\n x-props={{ placeholder: \'¥100,000\', addonAfter: \'元\' }}\n required\n />\n <Field\n type="string"\n name="idcard"\n x-rules="idcard"\n title="身份证"\n required\n />\n <Field type="string" name="zip" x-rules="zip" title="邮政编码" required />\n <Field\n type="string"\n name="custom"\n x-rules={val =>\n new Promise(resolve => {\n setTimeout(() => {\n if (val === \'123\') {\n resolve(\'不允许输入123\')\n } else {\n resolve()\n }\n }, 1000)\n })\n }\n title="自定义校验规则"\n required\n />\n <FormButtonGroup offset={6}>\n <Submit />\n <Reset />\n </FormButtonGroup>\n </SchemaForm>\n </Printer>\n)\nReactDOM.render(<App />, document.getElementById(\'root\'))\n',justCode:!1,lang:"jsx"},r.createElement(s,{})),r.createElement("h3",{id:"联动数据校验",className:"react-demo-h3"},"联动数据校验"),r.createElement("h4",{id:"demo-示例-1",className:"react-demo-h4"},"Demo 示例"),r.createElement(i,{code:"import React from 'react'\nimport ReactDOM from 'react-dom'\nimport { filter, withLatestFrom, map } from 'rxjs/operators'\nimport {\n SchemaForm,\n Field,\n FormButtonGroup,\n Submit,\n Reset,\n FormItemGrid,\n FormCard,\n FormPath,\n FormBlock,\n FormLayout,\n createFormActions\n} from '@uform/antd'\nimport { Button } from 'antd'\nimport Printer from '@uform/printer'\nimport 'antd/dist/antd.css'\n\nconst App = () => (\n <Printer>\n <SchemaForm\n labelCol={6}\n wrapperCol={6}\n effects={($, { setFieldState, getFieldState }) => {\n $('onFieldChange', '*(password,confirm)').subscribe(fieldState => {\n const selfName = fieldState.name\n const selfValue = fieldState.value\n const otherName = selfName == 'password' ? 'confirm' : 'password'\n const otherValue = getFieldState(otherName, state => state.value)\n setFieldState(otherName, state => {\n if (selfValue && otherValue && selfValue !== otherValue) {\n state.errors = '两次密码输入不一致'\n } else {\n state.errors = ''\n }\n })\n setFieldState(selfName, state => {\n if (selfValue && otherValue && selfValue !== otherValue) {\n state.errors = '两次密码输入不一致'\n } else {\n state.errors = ''\n }\n })\n })\n }}\n >\n <Field type=\"string\" name=\"username\" title=\"用户名\" required />\n <Field\n type=\"password\"\n name=\"password\"\n title=\"密码\"\n x-props={{ checkStrength: true }}\n description={\n <ul>\n <li>1. 长度不小于8个</li>\n <li>2. 必须包含大小写数字符号</li>\n </ul>\n }\n required\n />\n <Field\n type=\"password\"\n name=\"confirm\"\n title=\"确认密码\"\n x-props={{ checkStrength: true }}\n required\n />\n <FormButtonGroup offset={6}>\n <Submit />\n <Reset />\n </FormButtonGroup>\n </SchemaForm>\n </Printer>\n)\nReactDOM.render(<App />, document.getElementById('root'))\n",justCode:!1,lang:"jsx"},r.createElement(a,{})))};c.meta={username:"zhili.wzl",email:"wangzhili56@126.com"},t.exports=c},115:function(t,e,n){"use strict";n.r(e);var r={};n.r(r),n.d(r,"url",function(){return X}),n.d(r,"email",function(){return H}),n.d(r,"ipv6",function(){return U}),n.d(r,"ipv4",function(){return L}),n.d(r,"number",function(){return K}),n.d(r,"integer",function(){return G}),n.d(r,"qq",function(){return Q}),n.d(r,"phone",function(){return J}),n.d(r,"idcard",function(){return Z}),n.d(r,"taodomain",function(){return tt}),n.d(r,"money",function(){return et}),n.d(r,"zh",function(){return nt}),n.d(r,"date",function(){return rt}),n.d(r,"zip",function(){return it});var i=n(129),o=n.n(i),s=n(0),a=n.n(s),c=n(117),u=n.n(c),l=n(140),h=n.n(l),d=n(116);const p=(t,e,n)=>Object(d.t)(e,(t,e)=>Object(d.o)(e)?e(t):t,t,n),f=t=>e=>n=>t({...e},n),m=(t,e)=>"properties"!==e&&"items"!==e,b=(t,e)=>"properties"!==e&&"items"!==e&&"children"!==e;let y,v,g,x,w;const S=()=>{var t,e;y=[],v={},g={},x=void 0,e=t=class extends a.a.Component{render(){const{formRef:t,component:e,...n}=this.props;return a.a.createElement(e,{...n,ref:t})}},u()(t,"defaultProps",{component:"form"}),(w=e).displayName="Form"},j=(t,e,n)=>{Object(d.r)(t)&&t&&(Object(d.o)(e)||"string"==typeof e.styledComponentId)&&(n?(v[Object(d.s)(t)]=e,v[Object(d.s)(t)].registerMiddlewares=[]):(v[Object(d.s)(t)]=p(e,y,!0),v[Object(d.s)(t)].registerMiddlewares=y),v[Object(d.s)(t)].displayName=h()(t))},O=t=>{Object(d.g)(t,(t,e)=>{j(e,t)})},_=(...t)=>{y=y.concat(t),Object(d.g)(v,(e,n)=>{e.registerMiddlewares.some(e=>t.indexOf(e)>-1)||(v[n]=p(v[n],t,!0),v[n].registerMiddlewares=y)})},E=(...t)=>{w=t.reduce((t,e,n)=>{let r=Object(d.o)(e)?e(t):t;return r.displayName=`FormWrapperLevel${n}`,r},w)},F=(t,e)=>{Object(d.o)(e)&&(g[t]=e)},C=t=>g[t],N=t=>v[t],V=a.a.forwardRef((t,e)=>a.a.createElement(w,{...t,ref:e})),k=t=>t.reduce((t,e)=>Object(d.k)(e)?t.concat(k(e)):t.concat(e),[]),T=t=>({change(e){t.form.setValue(t.name,e)},dispatch(e,n){t.form.triggerEffect(e,{name:t.name,path:t.path,payload:n})},errors(e,...n){t.form.setErrors(t.name,k(Object(d.x)(e)),...n)},push(e){const n=Object(d.x)(t.form.getValue(t.name));t.form.setValue(t.name,n.concat(e))},pop(){const e=[].concat(Object(d.x)(t.form.getValue(t.name)));e.pop(),t.form.setValue(t.name,e)},insert(e,n){const r=[].concat(Object(d.x)(t.form.getValue(t.name)));r.splice(e,0,n),t.form.setValue(t.name,r)},remove(e){let n=t.form.getValue(t.name);(t=>"number"==typeof t)(e)&&Object(d.k)(n)?((n=[].concat(n)).splice(e,1),t.form.setValue(t.name,n)):t.form.removeValue(t.name)},unshift(e){const n=[].concat(Object(d.x)(t.form.getValue(t.name)));n.unshift(e),t.form.setValue(t.name,n)},shift(){const e=[].concat(Object(d.x)(t.form.getValue(t.name)));e.shift(),t.form.setValue(t.name,e)},move(e,n){const r=[].concat(Object(d.x)(t.form.getValue(t.name))),i=r[e];r.splice(e,1),r.splice(n,0,i),t.form.setValue(t.name,r)}}),I=a.a.createContext(),A=a.a.createContext(),P=a.a.createContext(),q=f((t,e)=>{class n extends s.Component{constructor(t){super(t),u()(this,"renderField",(t,e)=>{const n=this.props.path.concat(t),r=this.props.schemaPath.concat(t),i=n.join(".");return a.a.createElement(q,{key:e?i:void 0,path:n,name:i,schemaPath:r})}),u()(this,"getOrderProperties",t=>{const{schema:e,path:n}=this.props;if(!e&&!t)return[];const r=[];return Object(d.g)((t||e||{}).properties,(t,e)=>{let i=t["x-index"],o=n.concat(e),s=o.join(".");"number"==typeof i?r[i]={schema:t,key:e,path:o,name:s}:r.push({schema:t,key:e,path:o,name:s})}),r}),this.initialized=!1,this.state={},this.field=t.form.registerField(t.name||t.schemaPath.join("."),{path:t.schemaPath,onChange:this.onChangeHandler(t),props:t.schema}),this.initialized=!0,this.mutators=T(t)}onChangeHandler(){return t=>{if(this.initialized){if(this.unmounted)return;this.setState(t)}else this.state=t}}componentWillUnmount(){this.unmounted=!0,this.field.remove()}componentDidMount(){this.unmounted=!1,this.field.restore()}componentDidUpdate(t){Object(d.n)(this.props.schema,t.schema,m)||this.field.changeProps(this.props.schema)}render(){const{name:t,path:n,schemaPath:r,locale:i,getSchema:o}=this.props,{value:s,visible:c,props:u,errors:l,loading:h,editable:p,required:f}=this.state,m=Object(d.v)(u,"object")?s||{}:Object(d.v)(u,"array")?s||[]:s;return!1===c?a.a.createElement(a.a.Fragment,null):a.a.createElement(e,{name:t,value:m,errors:l,required:f,path:n,editable:p,locale:i,loading:h,schemaPath:r,getSchema:o,renderField:this.renderField,getOrderProperties:this.getOrderProperties,mutators:this.mutators,schema:u})}}return u()(n,"displayName","StateField"),t=>{const{name:e,path:r,schemaPath:i}=t,{form:o,getSchema:c,locale:u}=Object(s.useContext)(A);return a.a.createElement(n,{name:e,path:r,form:o,schema:c(i||r),locale:u,getSchema:c,schemaPath:i})}})()(t=>{const e=t.schema,n=Object(d.s)(e["x-component"]||e.type),r=e["x-render"]?r=>a.a.createElement(N(n),{...t,...r,schema:e,path:t.path,name:t.name}):void 0,i=e["x-render"]?(()=>x)():N(n);return i?a.a.createElement(i,{...t,renderComponent:r}):(console&&console.error&&(n?console.error(`The schema field \`${n}\`'s component is not found.`):console.error("The schema field's component is not found, or field's schema is not defined.")),a.a.createElement(a.a.Fragment,null))});var z=n(2);let B=0;const M=(t,e)=>{const n=Object(s.useContext)(I);if(Object(d.v)(n,"object")){let e=t.name||(()=>`UFORM_NO_NAME_FIELD_$${B++}`)();return n.properties=n.properties||{},n.properties[e]=Object(d.d)(t,b),a.a.createElement(I.Provider,{value:n.properties[e]},t.children)}return Object(d.v)(n,"array")?(n.items=Object(d.d)(t,b),a.a.createElement(I.Provider,{value:n.items},t.children)):t.children||a.a.createElement(a.a.Fragment,null)},R=f((t,e)=>{var n,r;return r=n=class extends s.Component{constructor(...t){super(...t),u()(this,"portalRoot",document.createElement("div"))}render(){let{children:t,initialValues:n,defaultValue:r,value:i,schema:s,...c}=this.props,u=!1;return s?u=!0:s={type:"object"},B=0,a.a.createElement(a.a.Fragment,null,!u&&Object(z.createPortal)(a.a.createElement(I.Provider,{value:s},t),this.portalRoot),a.a.createElement(e,o()({},c,{defaultValue:i||r,value:i,initialValues:n,schema:s}),t))}},u()(n,"displayName","SchemaMarkupParser"),r});M.__docgenInfo={description:"",methods:[],displayName:"SchemaField"};var D=n(119),$=n(120);const Y=(t,e,n)=>{if(Object(D.f)(e))return"";return Object(D.j)(t)&&(t.lastIndex=0),(Object(D.h)(t)?t(e):Object(D.j)(t)?t.test(String(e)):new RegExp(String(t)).test(String(e)))?"":n};var W=(t,e,n,r)=>{if(e.pattern)return Y(e.pattern,t,Object(D.c)(e.message||Object($.a)("pattern"),r,t,e.pattern))};const X=new RegExp("^(?:(?:(?:https?|ftp):)?//)(?:\\S+(?::\\S*)?@)?(?:(?!(?:10|127)(?:\\.\\d{1,3}){3})(?!(?:169\\.254|192\\.168)(?:\\.\\d{1,3}){2})(?!172\\.(?:1[6-9]|2\\d|3[0-1])(?:\\.\\d{1,3}){2})(?:22[0-3]|2[01]\\d|[1-9]\\d?|1\\d\\d)(?:\\.(?:25[0-5]|2[0-4]\\d|1?\\d{1,2})){2}(?:\\.(?:25[0-4]|2[0-4]\\d|1\\d\\d|[1-9]\\d?))|(?:(?:[a-z\\u00a1-\\uffff0-9]-*)*[a-z\\u00a1-\\uffff0-9]+)(?:\\.(?:[a-z\\u00a1-\\uffff0-9]-*)*[a-z\\u00a1-\\uffff0-9]+)*(?:\\.(?:[a-z\\u00a1-\\uffff]{2,})))(?::\\d{2,5})?(?:/\\S*)?$"),H=/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/,U=/^\s*((([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|(([0-9A-Fa-f]{1,4}:){6}(:[0-9A-Fa-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){5}(((:[0-9A-Fa-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){4}(((:[0-9A-Fa-f]{1,4}){1,3})|((:[0-9A-Fa-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){3}(((:[0-9A-Fa-f]{1,4}){1,4})|((:[0-9A-Fa-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){2}(((:[0-9A-Fa-f]{1,4}){1,5})|((:[0-9A-Fa-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){1}(((:[0-9A-Fa-f]{1,4}){1,6})|((:[0-9A-Fa-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9A-Fa-f]{1,4}){1,7})|((:[0-9A-Fa-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(%.+)?\s*$/,L=/^((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){3}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})$/,K=/^[+-]?\d+(\.\d+)?$/,G=/^[+-]?\d+$/,Q=/^(\+?[1-9]\d*|0)$/,J=/^\d{3}-\d{8}$|^\d{4}-\d{7}$|^\d{11}$/,Z=/^\d{15}$|^\d{18}$/,tt=/^(https?\:)?\/\/[a-zA-Z0-9\.\-]+\.(taobao|tmall|alitrip|yao\.95095)(\.daily)?\.(com|net|hk(\/hk)?)/,et=/^([\u0024\u00A2\u00A3\u00A4\u20AC\u00A5\u20B1\20B9\uFFE5]\s*)(\d+,?)+\.?\d*\s*$/,nt=/^[\u4e00-\u9fa5]+$/,rt=/^(?:(?:1[6-9]|[2-9][0-9])[0-9]{2}([-\/.]?)(?:(?:0?[1-9]|1[0-2])\1(?:0?[1-9]|1[0-9]|2[0-8])|(?:0?[13-9]|1[0-2])\1(?:29|30)|(?:0?[13578]|1[02])\1(?:31))|(?:(?:1[6-9]|[2-9][0-9])(?:0[48]|[2468][048]|[13579][26])|(?:16|[2468][048]|[3579][26])00)([-\/.]?)0?2\2(?:29))(\s+([01][0-9]:|2[0-3]:)?[0-5][0-9]:[0-5][0-9])?$/,it=/^[0-9]{6}$/,ot=Object.keys(r);var st=(t,e,n,i)=>((t,e,n,i)=>{for(let n=0;n<ot.length;n++)if(ot[n]===e.format)return Y(r[ot[n]],t,Object(D.c)(e.message||Object($.a)(e.format),i,t))})(t,e,0,i),at=(t,e,n,r)=>{if(e.required)return Object(D.f)(t)?Object(D.c)(e.message||Object($.a)("required"),r):""},ct=(t,e,n,r)=>{if(Object(D.h)(e.validator))return e.validator(t,e,n,r)};const ut=(t,e,n,r)=>Promise.all(((...t)=>(...e)=>t.map(t=>Promise.resolve(t(...e))))(st,at,W,ct)(t,e,n,r)),lt=t=>Object(D.l)(t,(t,e)=>Object(D.e)(e)?t.concat(lt(e)):e?t.concat(e):t,[]),ht=(t,e,n,r)=>{const i=[];return Object(D.h)(n)&&(r=n,n=!1),Object(D.b)(e,(e,r)=>{const o=Object(D.d)(t,r);if(!1===e.visible||!1===e.editable)return;if(Object(D.g)(e.__lastValidateValue,o)&&!n)return;const s=e.props&&e.props.title;let a=setTimeout(()=>{e.loading=!0,e.dirty=!0,e.notify&&e.notify()},100);i.push(Promise.all(Object(D.m)(e.rules).map(e=>((t,e,n,r)=>{const i=Object(D.i)(e)?e:Object(D.k)(e)?{format:e}:Object(D.h)(e)?{validator:e}:{};return ut(t,i,n,r)})(o,e,t,s||r))).then(t=>{clearTimeout(a);let i=e.errors;const s=e.valid,c=e.loading;return e.loading=!1,n?(t&&(e.errors=lt(Object(D.m)(t))),e.errors.length?(e.valid=!1,e.invalid=!0):(e.valid=!0,e.invalid=!1),e.errors&&e.errors.length&&(e.dirty=!0)):e.pristine||(t&&(e.errors=lt(Object(D.m)(t))),e.errors.length?(e.valid=!1,e.invalid=!0):(e.valid=!0,e.invalid=!1),Object(D.g)(s,e.valid)&&Object(D.g)(i,e.errors)||(e.dirty=!0)),e.loading!==c&&(e.dirty=!0),e.dirty&&e.notify&&e.notify(),e.__lastValidateValue=Object(D.a)(o),{name:r,value:o,field:e,invalid:e.invalid,valid:e.valid,errors:e.errors}}))}),Promise.all(i).then(t=>(Object(D.h)(r)&&r(t),t))};var dt=n(141),pt=n.n(dt),ft=n(121);const mt=(t,e)=>"properties"!==e&&"items"!==e;class bt{constructor(t,e){this.fieldbrd=new ft.a,this.context=t,this.dirty=!1,this.pristine=!0,this.valid=!0,this.removed=!1,this.invalid=!1,this.visible=!0,this.editable=!0,this.destructed=!1,this.loading=!1,this.errors=[],this.effectErrors=[],this.initialized=!1,this.initialize(e),this.initialized=!0}initialize(t){const e=this.getEditableFromProps(t.props),n=this.getRulesFromProps(t.props);this.value=Object(ft.o)(t.value)?this.value:Object(ft.e)(t.value),this.initialValue=Object(ft.o)(t.initialValue)?Object(ft.o)(this.initialValue)?this.getInitialValueFromProps(t.props):this.initialValue:t.initialValue,this.name=Object(ft.o)(t.name)?this.name||"":t.name,this.namePath=Object(ft.w)(this.name),this.editable=Object(ft.o)(e)?this.editable:e,this.path=Object(ft.w)(Object(ft.o)(t.path)?this.path||[]:t.path),this.rules=Object(ft.o)(n)?this.rules:n,this.required=Object(ft.k)(this.rules),this.props=Object(ft.o)(t.props)?this.props||{}:Object(ft.o)(this.props)?Object(ft.e)(t.props):{...this.props,...Object(ft.e)(t.props)},this.removed&&(this.removed=!1,this.visible=!0),this.initialized||Object(ft.o)(this.value)&&!Object(ft.o)(this.initialValue)&&(this.value=Object(ft.e)(this.initialValue),this.context.setIn(this.name,this.value),this.context.setInitialValueIn(this.name,this.initialValue)),Object(ft.q)(t.onChange)&&this.onChange(t.onChange)}getInitialValueFromProps(t){if(t&&!Object(ft.o)(t.default))return t.default}getEditableFromProps(t){if(t){if(!Object(ft.o)(t.editable))return this.getEditable(t.editable);if(t["x-props"]&&!Object(ft.o)(t["x-props"].editable))return this.getEditable(t["x-props"].editable)}return this.getEditable(this.context.editable)}getRulesFromProps(t){if(t){const e=Object(ft.y)(t["x-rules"]);return t.required&&!e.some(t=>t.required)&&e.push({required:!0}),Object(ft.e)(e)}return this.rules}getRequiredFromProps(t){if(!Object(ft.o)(t.required))return t.required}getEditable(t){return Object(ft.q)(t)?t(this.name):Object(ft.m)(t)?t:this.editable}onChange(t){Object(ft.q)(t)&&(this.unSubscribeOnChange&&this.unSubscribeOnChange(),t(this.publishState()),this.unSubscribeOnChange=this.subscribe(t))}pathEqual(t){if(Object(ft.r)(t)&&t===this.name)return!0;if((t=Object(ft.w)(t)).length===this.path.length){for(let e=0;e<t.length;e++)if(t[e]!==this.path[e])return!1;return!0}if(t.length===this.namePath.length){for(let e=0;e<t.length;e++)if(t[e]!==this.namePath[e])return!1;return!0}return!1}publishState(){return Object(ft.s)(this)}subscribe(t){return this.fieldbrd.subscribe(t)}notify(t){(this.dirty||t)&&(this.fieldbrd.notify(this.publishState()),this.dirty=!1,this.dirtyType="")}unsubscribe(){this.fieldbrd.unsubscribe()}changeProps(t,e){let n=this.props;Object(ft.o)(t)||!e&&Object(ft.p)(n,t,mt)||(this.props=Object(ft.e)(t,mt),this.editable=this.getEditableFromProps(this.props),this.rules=this.getRulesFromProps(this.props),this.dirty=!0,this.notify())}changeEditable(t){this.props&&Object(ft.o)(this.props.editable)&&(this.props["x-props"]&&!Object(ft.o)(this.props["x-props"].editable)||(this.editable=this.getEditable(t),this.dirty=!0,this.notify()))}restore(){this.removed&&(this.visible=!0,this.removed=!1)}remove(){this.value=void 0,this.initialValue=void 0,this.visible=!1,this.removed=!0,this.context&&(this.context.deleteIn(this.name),this.context.deleteInitialValues(this.name),"object"==typeof this.value&&this.context.updateChildrenVisible(this,!1))}checkState(t=this.publishState()){Object(ft.p)(t.value,this.value)||(this.value=t.value,this.pristine=!1,this.context.setIn(this.name,this.value),this.context.updateChildrenValue(this),this.dirtyType="value",this.dirty=!0),Object(ft.p)(t.initialValue,this.initialValue)||(this.initialValue=t.initialValue,this.context.setInitialValueIn(this.name,this.value),this.context.updateChildrenInitalValue(this),this.dirtyType="initialValue",this.dirty=!0);const e=this.getEditable(t.editable);if(Object(ft.p)(e,this.editable)){const e=this.getEditableFromProps(t.props);Object(ft.o)(e)||Object(ft.p)(e,this.editable)||(this.editable=e,this.dirtyType="editable",this.dirty=!0)}else this.editable=e,this.dirtyType="editable",this.dirty=!0;if(t.errors=Object(ft.y)(t.errors).filter(t=>!!t),Object(ft.p)(t.errors,this.effectErrors)||(this.effectErrors=t.errors,this.valid=this.effectErrors.length>0&&this.errors.length>0,this.invalid=!this.valid,this.dirtyType="errors",this.dirty=!0),Object(ft.p)(t.rules,this.rules)){const e=this.getRulesFromProps(this.props),n=this.getRulesFromProps(t.props);Object(ft.o)(n)||Object(ft.p)(e,n)||Object(ft.p)(n,this.rules)||(this.rules=n,this.errors=[],Object(ft.k)(this.rules)&&(this.required=!0,t.required=!0),this.valid=!0,this.invalid=!1,this.dirtyType="rules",this.dirty=!0)}else this.rules=t.rules,this.errors=[],this.valid=!0,Object(ft.k)(this.rules)&&(this.required=!0,t.required=!0),this.invalid=!1,this.dirtyType="rules",this.dirty=!0;if(Object(ft.p)(t.required,this.required)){const e=this.getRequiredFromProps(t.props);Object(ft.o)(e)||Object(ft.p)(e,this.required)||(this.required=e,this.errors=[],this.required?Object(ft.k)(this.rules)||(this.rules=Object(ft.y)(this.rules).concat({required:!0}),this.errors=[],this.valid=!0,this.invalid=!1):(this.rules=Object(ft.y)(this.rules).filter(t=>!t||!t.required),this.errors=[],this.valid=!0,this.invalid=!1),this.dirty=!0)}else this.required=t.required,this.required?Object(ft.k)(this.rules)||(this.rules=Object(ft.y)(this.rules).concat({required:!0}),this.errors=[],this.valid=!0,this.invalid=!1):(this.rules=Object(ft.y)(this.rules).filter(t=>!t||!t.required),this.errors=[],this.valid=!0,this.invalid=!1),this.dirty=!0;t.loading!==this.loading&&(this.loading=t.loading,this.dirtyType="loading",this.dirty=!0),Object(ft.p)(t.visible,this.visible)||(this.visible=t.visible,this.visible?(this.value=void 0!==this.value?this.value:Object(ft.e)(this.initialValue),void 0!==this.value&&this.context.setIn(this.name,this.value),this.context.updateChildrenVisible(this,!0)):(this.context.deleteIn(this.name),this.context.updateChildrenVisible(this,!1)),this.dirtyType="visible",this.dirty=!0),Object(ft.p)(t.props,this.props,mt)||(this.props=Object(ft.e)(t.props,mt),this.dirtyType="props",this.dirty=!0)}updateState(t){if(!Object(ft.q)(t))return;const e={name:this.name,path:this.path,props:Object(ft.e)(this.props,mt),value:Object(ft.e)(this.value),initialValue:Object(ft.e)(this.initialValue),valid:this.valid,loading:this.loading,editable:this.editable,invalid:this.invalid,pristine:this.pristine,rules:Object(ft.e)(this.rules),errors:Object(ft.e)(this.effectErrors),visible:this.visible,required:this.required};t(e),this.checkState(e)}destructor(){this.destructed||(this.destructed=!0,void 0!==this.value&&(this.value=void 0,this.context.deleteIn(this.name)),this.context.updateChildrenVisible(this,!1),delete this.context,this.unsubscribe(),delete this.fieldbrd)}}var yt=n(157),vt=n(158),gt=n(156),xt=n.n(gt);const wt=(t,e,n)=>Object(ft.q)(e)?t&&e(n):t,St=/\*/,jt={match(t,e,n){t+="";const r=xt()(t);Object(ft.q)(e)&&(n=e,e=!1);const i=t=>t&&t.fieldState?wt(r(Object(ft.w)(e?t.fieldState.path:t.fieldState.name)),n,t.fieldState):t&&t.name&&t.path?wt(r(Object(ft.w)(e?t.path:t.name)),n,t):Object(ft.r)(t)?wt(r(Object(ft.w)(t)),n,{name:t}):!!Object(ft.l)(t)&&wt(r(t),n,{path:t});return i.hasWildcard=St.test(t),i.string=t,i},exclude:t=>e=>Object(ft.q)(t)?!t(e):!!Object(ft.r)(t)&&!jt.match(t)(e),transform:(t,e,n)=>n(...Object(ft.v)(Object(ft.w)(t),(t,n)=>new RegExp(e).test(n)?t.concat(n):t,[]))},Ot=t=>({initialValues:{},onSubmit:t=>{},effects:t=>{},...t});class _t{constructor(t){pt()(this,"triggerEffect",(t,...e)=>{this.subscribes[t]&&this.subscribes[t].next(...e)}),pt()(this,"setFieldState",(t,e,n)=>{if(!this.destructed)return Object(ft.q)(e)&&(n=e,e=!1),(Object(ft.r)(t)||Object(ft.l)(t)||Object(ft.q)(t))&&this.updateQueue.push({path:t,callback:n}),new Promise(t=>{this.syncUpdateMode&&(this.updateFieldStateFromQueue(e),t()),this.updateQueue.length>0&&(this.updateRafId&&Object(ft.d)(this.updateRafId),this.updateRafId=Object(ft.u)(()=>{this.destructed||(this.updateFieldStateFromQueue(e),t())}))})}),pt()(this,"getFieldState",(t,e)=>{let n;if(Object(ft.h)(this.fields,e=>{if(e.pathEqual(t))return n=e,!1}),n)return Object(ft.q)(e)?e(n.publishState()):n.publishState()}),pt()(this,"getFormState",t=>Object(ft.q)(t)?t(this.publishState()):this.publishState()),pt()(this,"setFormState",t=>{if(!Object(ft.q)(t))return;const e=this.publishState();return t(e,t),Promise.resolve(this.checkState(e))}),this.options=Ot(t),this.formbrd=new ft.a,this.initialized=!1,this.state={},this.fields={},this.subscribes=t.subscribes||{},this.updateQueue=[],this.updateBuffer=new ft.b,this.editable=t.editable,this.schema=t.schema||{},this.initialize(this.options.initialValues),this.initializeEffects(),this.initialized=!0,this.destructed=!1,this.fieldSize=0}initialize(t=this.state.initialValues){const e=this.state.values,n=this.state.dirty;this.state={valid:!0,invalid:!1,errors:[],pristine:!0,initialValues:Object(ft.e)(t)||{},values:Object(ft.e)(t)||{},dirty:n||!!this.initialized&&!Object(ft.p)(t,e)},this.options.onFormChange&&!this.initialized&&(this.subscribe(this.options.onFormChange),this.options.onFormChange({formState:this.publishState()})),this.updateFieldsValue(!1)}changeValues(t){const e=this.state.values,n=this.state.dirty;this.state.values=t||{},this.state.dirty=n||!!this.initialized&&!Object(ft.p)(t,e),this.updateFieldsValue()}changeEditable(t){this.editable=t,Object(ft.h)(this.fields,(e,n)=>{e.changeEditable(t)})}initializeEffects(){const{effects:t}=this.options;Object(ft.q)(t)&&t((t,e)=>(this.subscribes[t]||(this.subscribes[t]=new yt.Subject),Object(ft.r)(e)||Object(ft.q)(e)?this.subscribes[t].pipe(Object(vt.filter)(Object(ft.r)(e)?jt.match(e):e)):this.subscribes[t]),{setFieldState:this.setFieldState,getFieldState:this.getFieldState,getFormState:this.getFormState,setFormState:this.setFormState})}checkState(t){return Object(ft.p)(this.state.values,t.values)?Object(ft.p)(this.state.initialValues,t.initialValues)?void 0:(this.state.initialValues=t.initialValues,this.state.dirty=!0,this.updateFieldInitialValue()):(this.state.values=t.values,this.state.dirty=!0,this.updateFieldsValue())}syncUpdate(t){Object(ft.q)(t)&&(this.syncUpdateMode=!0,t(),this.syncUpdateMode=!1)}asyncUpdate(t){Object(ft.q)(t)&&(this.syncUpdateMode?(this.syncUpdateMode=!1,t(),this.syncUpdateMode=!0):t())}updateFieldStateFromQueue(t){const e={},n={};Object(ft.h)(this.updateQueue,({path:r,callback:i},o)=>{Object(ft.h)(this.fields,s=>{if(r&&(Object(ft.q)(r)||Object(ft.l)(r)||Object(ft.r)(r)))if(Object(ft.q)(r)?r(s):s.pathEqual(r)){if(s.updateState(i),this.syncUpdateMode&&(s.dirty=!1),r.hasWildcard&&this.updateBuffer.push(r.string,i,{path:r}),s.dirty){const t=s.dirtyType;s.notify(),n[s.name]&&Object(ft.d)(n[s.name]),n[s.name]=Object(ft.u)(()=>{"value"===t?this.internalValidate().then(()=>{this.formNotify(s.publishState())}):this.formNotify(s.publishState())})}}else e[o]=e[o]||0,e[o]++,this.fieldSize<=e[o]&&(t||r.hasWildcard)&&(Object(ft.r)(r)?this.updateBuffer.push(r,i,{path:r}):Object(ft.q)(r)&&r.hasWildcard&&this.updateBuffer.push(r.string,i,{path:r}))})}),this.updateQueue=[]}updateFieldStateFromBuffer(t){const e={};this.updateBuffer.forEach(({path:n,values:r,key:i})=>{if(Object(ft.q)(n)?n(t):t.pathEqual(n)){if(r.forEach(e=>t.updateState(e)),this.syncUpdateMode&&(t.dirty=!1),t.dirty){const n=t.dirtyType;t.notify(),e[t.name]&&Object(ft.d)(e[t.name]),e[t.name]=Object(ft.u)(()=>{"value"===n?this.internalValidate().then(()=>{this.formNotify(t.publishState())}):this.formNotify(t.publishState())})}n.hasWildcard||this.updateBuffer.remove(i)}})}internalValidate(t=this.state.values,e){if(!this.destructed)return new Promise(n=>{this.rafValidateId&&Object(ft.d)(this.rafValidateId),this.rafValidateId=Object(ft.u)(()=>this.destructed?n():ht(t||this.state.values,this.fields,e).then(t=>{const e=this.state.valid;let n=Object(ft.v)(t,(t,{name:e,errors:n})=>n.length?t.concat({name:e,errors:n}):t,[]);this.state.valid=0===n.length,this.state.invalid=!this.state.valid,this.state.errors=n,this.state.valid!==e&&(this.state.dirty=!0);const r=this.state.pristine;return Object(ft.p)(this.state.values,this.state.initialValues)?this.state.pristine=!0:this.state.pristine=!1,r!==this.state.pristine&&(this.state.dirty=!0),t}).then(n))})}registerField(t,e){const n=this.getValue(t),r=this.getInitialValue(t,e.path),i=this.fields[t];if(i)i.initialize({...e,value:Object(ft.o)(n)?r:n,initialValue:r}),this.asyncUpdate(()=>{this.updateFieldStateFromBuffer(i)}),this.triggerEffect("onFieldChange",i.publishState());else{this.fields[t]=new bt(this,{name:t,value:Object(ft.o)(n)?r:n,path:e.path,initialValue:r,props:e.props});let i=this.fields[t];e.onChange&&(this.asyncUpdate(()=>{this.updateFieldStateFromBuffer(i),i.onChange(e.onChange)}),this.triggerEffect("onFieldChange",i.publishState())),this.fieldSize++}return this.fields[t]}setIn(t,e){Object(ft.x)(this.state.values,t,e)}setInitialValueIn(t,e){Object(ft.x)(this.state.initialValues,t,e)}setValue(t,e){const n=this.fields[t];n&&(n.updateState(t=>{t.value=e}),n.pristine=!1,n.dirty&&(n.notify(),this.internalValidate(this.state.values).then(()=>{this.formNotify(n.publishState())})))}setErrors(t,e,...n){e=Object(ft.y)(e);const r=this.fields[t];if(r){const t=r.errors;Object(ft.p)(t,e)||(r.errors=e.map(t=>Object(D.c)(t,...n)),e.length?(r.invalid=!0,r.valid=!1):(r.invalid=!1,r.valid=!0),r.dirty=!0,r.notify())}}updateChildrenValue(t){t.path&&!this.batchUpdateField&&Object(ft.h)(this.fields,(e,n)=>{if(Object(ft.n)(e,t)){let t=this.getValue(n);Object(ft.p)(e.value,t)||(e.dirty=!0,e.value=t,e.notify(),this.triggerEffect("onFieldChange",e.publishState()))}})}updateChildrenInitalValue(t){t.path&&Object(ft.h)(this.fields,(e,n)=>{if(Object(ft.n)(e,t)){let t=this.getInitialValue(n);Object(ft.p)(e.initialValue,t)||(e.dirty=!0,e.initialValue=t)}})}updateFieldInitialValue(){this.state.dirty&&this.initialized&&Object(ft.h)(this.fields,(t,e)=>{let n=this.getInitialValue(e);t.initialValue=n})}updateFieldsValue(t=!0){const{promise:e,resolve:n}=Object(ft.f)(),r=()=>{const t=[];this.batchUpdateField=!0,Object(ft.h)(this.fields,(e,n)=>{let r=this.getValue(n);e.updateState(t=>{t.value=r}),e.dirty&&t.push(new Promise(t=>{Object(ft.u)(()=>{this.destructed||(e.notify(),this.triggerEffect("onFieldChange",e.publishState()),t())})}))}),this.batchUpdateField=!1,n(Promise.all(t))};return this.state.dirty&&this.initialized&&(t?this.internalValidate(this.state.values,!0).then(()=>{this.formNotify(),r()}):r()),e}updateChildrenVisible(t,e){t.path&&Object(ft.h)(this.fields,(n,r)=>{if(r!==t.name&&Object(ft.n)(n,t)){if(e){let t=void 0!==n.value?n.value:Object(ft.e)(n.initialValue);void 0!==n.value&&this.setIn(r,t)}else this.deleteIn(r);n.visible!==e&&(n.visible=e,n.dirty=!0)}})}getInitialValue(t,e){const n=Object(ft.i)(this.state.initialValues,t);let r,i;return void 0===n&&void 0!==(i=(r=e?Object(ft.j)(this.schema,e):void 0)&&r.default)&&this.setIn(t,i),void 0!==n?n:i}getValue(t,e){return e?Object(ft.e)(Object(ft.i)(this.state.values,t)):Object(ft.i)(this.state.values,t)}deleteIn(t){Object(ft.g)(this.state.values,t)}deleteInitialValues(t){Object(ft.g)(this.state.initialValues,t)}reset(t){Object(ft.h)(this.fields,(e,n)=>{const r=this.getValue(n),i=this.getInitialValue(n,e.path);Object(ft.o)(r)&&Object(ft.o)(i)||(e.updateState(e=>{e.value=t?void 0:i}),e.dirty&&Object(ft.u)(()=>{this.destructed||e.notify()}))}),this.internalValidate(this.state.values,!0).then(()=>{this.formNotify(),Object(ft.u)(()=>{const t=this.publishState();this.triggerEffect("onFormReset",t),Object(ft.q)(this.options.onReset)&&this.options.onReset({formState:t})})})}publishState(){return Object(ft.t)(this.state)}formNotify(t){const e=this.publishState();return Object(ft.q)(this.options.onFieldChange)&&this.options.onFieldChange({formState:e,fieldState:t}),t&&this.triggerEffect("onFieldChange",t),this.state.dirty&&this.formbrd.notify({formState:e,fieldState:t}),this.state.dirty=!1,e}validate(){return this.internalValidate(this.state.values,!0).then(()=>new Promise((t,e)=>{this.formNotify(),Object(ft.u)(()=>{this.state.valid?t(this.publishState()):(this.options.onValidateFailed&&this.options.onValidateFailed(this.state.errors),e(this.state.errors))})}))}submit(){return this.validate().then(t=>(this.triggerEffect("onFormSubmit",t),Object(ft.q)(this.options.onSubmit)&&this.options.onSubmit({formState:t}),t))}subscribe(t){return this.formbrd.subscribe(t)}destructor(){this.destructed||(this.destructed=!0,this.formbrd.unsubscribe(),Object(ft.h)(this.subscribes,t=>{t.unsubscribe()}),Object(ft.h)(this.fields,(t,e)=>{t.destructor(),delete this.fields[e]}),this.fieldSize=0,delete this.fields,delete this.formbrd)}}const Et=({initialValues:t,onSubmit:e,onReset:n,schema:r,onFormChange:i,onFieldChange:o,onFormWillInit:s,subscribes:a,editable:c,effects:u,onValidateFailed:l})=>{let h=[];t=Object(ft.c)(r,t,({name:t,path:e,schemaPath:n},r,i)=>{h.push({name:t,path:e,schemaPath:n,schema:r,value:i})});const d=new _t({initialValues:t,onSubmit:e,onReset:n,subscribes:a,onFormChange:i,onFieldChange:o,editable:c,effects:u,onValidateFailed:l,schema:r});return Object(ft.q)(s)&&s(d),h=h.map(({name:t,path:e,schemaPath:n,schema:r,value:i})=>d.registerField(t||n.join("."),{path:n,props:r})),d.syncUpdate(()=>{d.triggerEffect("onFormInit",d.publishState())}),d};var Ft=n(142);const Ct=()=>t=>{const e=e=>{const n=Object(s.useContext)(P);return n?a.a.createElement(t,o()({},e,{broadcast:n})):a.a.createElement(Nt,null,n=>a.a.createElement(t,o()({},e,{broadcast:n})))};return e.displayName="FormBroadcast",e};class Nt extends s.Component{constructor(...t){super(...t),u()(this,"broadcast",new d.a)}componentWillUnmount(){this.broadcast.unsubscribe()}render(){const{children:t}=this.props;return a.a.createElement(P.Provider,{value:this.broadcast},Object(d.o)(t)?t(this.broadcast):t)}}u()(Nt,"displayName","FormProvider");const Vt=({testingAct:t}={})=>{let[e,n]=Object(s.useState)({}),r=Object(s.useContext)(P),i=!1;Object(s.useMemo)(()=>{r&&(r.subscribe(({type:r,state:o,schema:s})=>{"submit"!==r&&"reset"!==r&&(i?t?t(()=>n({status:r,state:o,schema:s})):n({status:r,state:o,schema:s}):e={status:r,state:o,schema:s})}),i=!0)},[r]);const{status:o,state:a,schema:c}=e;return{status:o,state:a,schema:c,submit:()=>{r&&r.notify({type:"submit"})},reset:()=>{r&&r.notify({type:"reset"})},dispatch:(t,e)=>{r&&r.notify({type:"dispatch",name:t,payload:e})}}},kt=({children:t,testingAct:e})=>{const n=Vt({testingAct:e});return n?Object(d.o)(t)?t(n):t||a.a.createElement(a.a.Fragment,null):a.a.createElement(a.a.Fragment,null)};Nt.__docgenInfo={description:"",methods:[],displayName:"FormProvider"},kt.__docgenInfo={description:"",methods:[],displayName:"FormConsumer"};const Tt=f((t,e)=>{class n extends s.Component{constructor(t){super(t),u()(this,"getSchema",t=>{const{schema:e}=this.props,n=Object(d.j)(e,t),r=n&&C(n["x-component"]||n.type);return r?r(n):n}),u()(this,"onNativeSubmitHandler",t=>{t.preventDefault&&(t.stopPropagation(),t.preventDefault()),this.form.submit().catch(t=>{console&&console.error&&console.error(t)})}),u()(this,"getValues",()=>this.form.getValue()),u()(this,"submit",()=>this.form.submit()),u()(this,"reset",t=>{this.form.reset(t)}),u()(this,"validate",()=>this.form.validate()),u()(this,"dispatch",(t,e)=>{this.form.triggerEffect(t,e)}),this.initialized=!1,this.form=Et({initialValues:t.defaultValue||t.initialValues,effects:t.effects,subscribes:t.subscribes,schema:t.schema,editable:t.editable,onSubmit:this.onSubmitHandler(t),onFormChange:this.onFormChangeHandler(t),onFieldChange:this.onFieldChangeHandler(t),onValidateFailed:t.onValidateFailed,onReset:this.onResetHandler(t),onFormWillInit:e=>{t.implementActions({setFormState:e.setFormState,getFormState:e.getFormState,setFieldState:e.setFieldState,getFieldState:e.getFieldState,reset:this.reset,submit:this.submit,validate:this.validate,getSchema:this.getSchema,dispatch:this.dispatch})}}),this.state={},this.initialized=!0}notify(t){const{broadcast:e,schema:n}=this.props;e&&(t.schema=n,e.notify(t))}onFormChangeHandler(t){let e=this.state;return({formState:t})=>{this.unmounted||(e&&e.pristine!==t.pristine&&(e.pristine?this.notify({type:"changed",state:t}):this.notify({type:"reseted",state:t})),e=t,this.initialized?t.dirty&&(clearTimeout(this.timerId),this.timerId=setTimeout(()=>{clearTimeout(this.timerId),this.setState(t)},60)):(this.state=t,this.notify({type:"initialize",state:t})))}}onFieldChangeHandler(t){return({formState:e})=>{if(t.onChange){const n=e.values;Object(d.n)(this.lastFormValues,n)||(t.onChange(n),this.lastFormValues=Object(d.d)(n))}}}onSubmitHandler(t){return({formState:e})=>{if(t.onSubmit){const n=t.onSubmit(Object(d.d)(e.values));n&&n.then&&(this.notify({type:"submitting",state:this.state}),n.then(()=>{this.notify({type:"submitted",state:this.state})},t=>{throw this.notify({type:"submitted",state:this.state}),t}))}}}onResetHandler(t){return({formState:e})=>{t.onReset&&t.onReset(Object(d.d)(e.values))}}shouldComponentUpdate(t){return!Object(d.n)(t,this.props)}componentDidUpdate(t){const{value:e,editable:n,initialValues:r}=this.props;Object(d.m)(e)||Object(d.n)(e,t.value)||this.form.changeValues(e),Object(d.m)(r)||Object(d.n)(r,t.initialValues)||this.form.initialize(r),Object(d.m)(n)||Object(d.n)(n,t.editable)||this.form.changeEditable(n)}componentDidMount(){this.unmounted=!1,this.form.triggerEffect("onFormMount",this.form.publishState()),this.unsubscribe=this.props.broadcast.subscribe(({type:t,name:e,payload:n})=>{"submit"===t?this.submit():"reset"===t?this.reset():"dispatch"===t&&this.form.triggerEffect(e,n)})}componentWillUnmount(){this.unmounted=!0,this.form&&(this.form.destructor(),this.unsubscribe(),delete this.form)}render(){const{onSubmit:t,onChange:n,onReset:r,onValidateFailed:i,initialValues:s,defaultValue:c,actions:u,effects:l,implementActions:h,dispatch:d,editable:p,createEvents:f,subscribes:m,subscription:b,children:y,schema:v,broadcast:g,locale:x,value:w,...S}=this.props;return a.a.createElement(A.Provider,{value:{form:this.form,getSchema:this.getSchema,locale:x,broadcast:this.broadcast}},a.a.createElement(e,o()({},S,{onSubmit:this.onNativeSubmitHandler}),y))}}return u()(n,"displayName","StateForm"),u()(n,"defaultProps",{locale:{}}),Object(Ft.connect)({autoRun:!1})(Ct()(n))});var It=()=>j("object",class extends a.a.Component{renderProperties(){const{renderField:t,getOrderProperties:e}=this.props,n=e(),r=[];return Object(d.g)(n,({key:e}={})=>{e&&r.push(t(e,!0))}),r}render(){return this.renderProperties()}}),At=()=>{var t,e;return(t=>{x=t})((e=t=class extends a.a.Component{render(){return Object(d.o)(this.props.schema["x-render"])?this.props.schema["x-render"](this.props):a.a.createElement(a.a.Fragment,null)}},u()(t,"displayName","FieldXRenderer"),e))},Pt=()=>{var t,e;Object(d.u)("slot"),j("slot",(e=t=class extends a.a.Component{render(){const{schema:t}=this.props;return a.a.createElement(a.a.Fragment,null,t.renderChildren)}},u()(t,"displayName","FormSlot"),e))};const qt=(t,e)=>{var n,r;Object(d.u)(t),j(t,(r=n=class extends a.a.PureComponent{render(){const{schema:t,schemaPath:n,path:r,getOrderProperties:i}=this.props,o=r.slice(0,r.length-1),s=i(t).map(({key:t})=>{const e=o.concat(t),r=e.join("."),i=n.concat(t);return a.a.createElement(q,{key:i,name:r,path:e,schemaPath:i})});return a.a.createElement(e,t["x-props"],s)}},u()(n,"displayName","VirtualBoxWrapper"),r),!0);const i=({children:e,name:n,render:r,...i})=>a.a.createElement(M,{type:"object",name:n,"x-component":t,"x-props":i,"x-render":r},e);return e.defaultProps&&(i.defaultProps=e.defaultProps),i.displayName=h()(t),i},zt=({name:t,children:e})=>a.a.createElement(M,{type:"object",name:t,"x-component":"slot",renderChildren:e});zt.__docgenInfo={description:"",methods:[],displayName:"FormSlot"};const Bt="undefined"!=typeof window&&window.navigator&&window.navigator.product&&"ReactNative"===window.navigator.product,Mt=t=>e=>(t={valueName:"value",eventName:"onChange",...t},class extends s.PureComponent{render(){const{value:n,name:r,mutators:i,schema:o,editable:s}=this.props;let c={...t.defaultProps,...o["x-props"],[t.valueName]:n,[t.eventName]:(e,...n)=>{i.change(t.getValueFromEvent?t.getValueFromEvent.call({props:o["x-props"]||{}},e,...n):((t,e)=>{if((t=>!!(t&&t.stopPropagation&&t.preventDefault))(t)){if(!e&&t.nativeEvent&&void 0!==t.nativeEvent.text)return t.nativeEvent.text;if(e&&void 0!==t.nativeEvent)return t.nativeEvent.text;const n=t,{target:{type:r,value:i,checked:o,files:s},dataTransfer:a}=n;return"checkbox"===r?!!o:"file"===r?s||a&&a.files:"select-multiple"===r?(t=>{const e=[];if(t)for(let n=0;n<t.length;n++){const r=t[n];r.selected&&e.push(r.value)}return e})(t.target.options):i}return t})(e,Bt))}};if(void 0!==s&&(Object(d.o)(s)?s(r)||(c.disabled=!0,c.readOnly=!0):!1===s&&(c.disabled=!0,c.readOnly=!0)),Object(d.o)(o["x-effect"])&&(c=((t,e,n)=>(Object(d.g)(e(n,{...t}),(e,n)=>{const r="onChange"===n?t[n]:void 0;t[n]=((...t)=>{if(Object(d.o)(r)&&r(...t),Object(d.o)(e))return e(...t)})}),t))(c,o["x-effect"],i.dispatch)),Object(d.o)(t.getProps)){let e=t.getProps(c,this.props);void 0!==e&&(c=e)}return Object(d.k)(o.enum)&&!c.dataSource&&(c.dataSource=((t,e)=>Object(d.k)(t)?t.map((t,n)=>"object"==typeof t?{...t}:{...t,label:Object(d.k)(e)&&e[n]||t,value:t}):[])(o.enum,o.enumNames)),void 0!==c.editable&&delete c.editable,a.a.createElement(Object(d.o)(t.getComponent)?t.getComponent(e,c,this.props):e,c)}}),Rt=t=>{const{TextButton:e,CircleButton:n,AddIcon:r,RemoveIcon:i,MoveDownIcon:o,MoveUpIcon:s}={TextButton:()=>a.a.createElement("div",null,"You Should Pass The TextButton."),CircleButton:()=>a.a.createElement("div",null,"You Should Pass The CircleButton."),AddIcon:()=>a.a.createElement("div",null,"You Should Pass The AddIcon."),RemoveIcon:()=>a.a.createElement("div",null,"You Should Pass The RemoveIcon."),MoveDownIcon:()=>a.a.createElement("div",null,"You Should Pass The MoveDownIcon."),MoveUpIcon:()=>a.a.createElement("div",null,"You Should Pass The MoveUpIcon."),...t};return class extends a.a.Component{constructor(...t){super(...t),u()(this,"isActive",(t,e)=>{const n=this.getProps("readOnly"),r=this.getDisabled();return Object(d.o)(r)?r(t,e):Object(d.o)(n)?n(t,e):!n&&!r})}getApi(t){const{value:e}=this.props;return{index:t,isActive:this.isActive,dataSource:e,record:e[t],add:this.onAddHandler(),remove:this.onRemoveHandler(t),moveDown:n=>this.onMoveHandler(t,t+1>e.length-1?0:t+1)(n),moveUp:n=>this.onMoveHandler(t,t-1<0?e.length-1:t-1)(n)}}getProps(t){return Object(d.h)(this.props.schema,`x-props${t?"."+t:""}`)}renderWith(t,e,n){const r=this.getProps(Object(d.c)(`render-${t}`));return Object(d.o)(e)&&(n=e,e=0),Object(d.o)(r)?r(this.getApi(e)):n?Object(d.o)(n)?n(this.getApi(e),r):n:void 0}renderAddition(){const{locale:t}=this.props,{value:n}=this.props;return this.isActive("addition",n)&&this.renderWith("addition",({add:n},i)=>a.a.createElement("div",{className:"array-item-addition",onClick:n},a.a.createElement(e,null,a.a.createElement(r,null),i||t.addItem||"添加")))}renderEmpty(t){const{locale:n,value:i}=this.props;return 0===i.length&&this.renderWith("empty",({add:t,isActive:o},s)=>{const c=o("empty",i);return a.a.createElement("div",{className:`array-empty-wrapper ${c?"":"disabled"}`,onClick:c?t:void 0},a.a.createElement("div",{className:"array-empty"},a.a.createElement("img",{style:{backgroundColor:"transparent"},src:"//img.alicdn.com/tfs/TB1cVncKAzoK1RjSZFlXXai4VXa-184-152.svg"}),c&&a.a.createElement(e,null,a.a.createElement(r,null),s||n.addItem||"添加")))})}renderRemove(t,e){return this.isActive(`${t}.remove`,e)&&this.renderWith("remove",t,({remove:t},e)=>a.a.createElement(n,{onClick:t,hasText:!!e},a.a.createElement(i,null),e&&a.a.createElement("span",{className:"op-name"},e)))}renderMoveDown(t,e){const{value:r}=this.props;return r.length>1&&this.isActive(`${t}.moveDown`,e)&&this.renderWith("moveDown",t,({moveDown:t},e)=>a.a.createElement(n,{onClick:t,hasText:!!e},a.a.createElement(o,null),a.a.createElement("span",{className:"op-name"},e)))}renderMoveUp(t,e){const{value:r}=this.props;return r.length>1&&this.isActive(`${t}.moveUp`,r)&&this.renderWith("moveUp",t,({moveUp:t},e)=>a.a.createElement(n,{onClick:t,hasText:!!e},a.a.createElement(s,null),a.a.createElement("span",{className:"op-name"},e)))}renderExtraOperations(t){return this.renderWith("extraOperations",t)}getDisabled(){const{editable:t,name:e}=this.props,n=this.getProps("disabled");if(void 0!==t)if(Object(d.o)(t)){if(!t(e))return!0}else if(!1===t)return!0;return n}onRemoveHandler(t){const{value:e,mutators:n,schema:r,locale:i}=this.props,{minItems:o}=r;return r=>{r.stopPropagation(),o>=0&&e.length-1<o?n.errors(i.array_invalid_minItems,o):n.remove(t)}}onMoveHandler(t,e){const{mutators:n}=this.props;return r=>{r.stopPropagation(),n.move(t,e)}}onAddHandler(){const{value:t,mutators:e,schema:n,locale:r}=this.props,{maxItems:i}=n;return n=>{n.stopPropagation(),i>=0&&t.length+1>i?e.errors(r.array_invalid_maxItems,i):e.push()}}onClearErrorHandler(){return()=>{const{value:t,mutators:e,schema:n}=this.props,{maxItems:r,minItems:i}=n;(r>=0&&t.length<=r||i>=0&&t.length>=i)&&e.errors()}}validate(){const{value:t,mutators:e,schema:n,locale:r}=this.props,{maxItems:i,minItems:o}=n;t.length>i?e.errors(r.array_invalid_maxItems,i):t.length<o?e.errors(r.array_invalid_minItems,o):e.errors()}componentDidUpdate(t){Object(d.n)(t.value,this.props.value)||this.validate()}componentDidMount(){this.validate()}}};n.d(e,"SchemaForm",function(){return Dt}),n.d(e,"Field",function(){return $t}),n.d(e,"setValidationLocale",function(){return Yt}),n.d(e,"setValidationLanguage",function(){return Wt}),n.d(e,"createFormActions",function(){return Xt}),n.d(e,"createAsyncFormActions",function(){return Ht}),n.d(e,"createVirtualBox",function(){return qt}),n.d(e,"FormSlot",function(){return zt}),n.d(e,"connect",function(){return Mt}),n.d(e,"FormBridge",function(){return Ct}),n.d(e,"FormProvider",function(){return Nt}),n.d(e,"useForm",function(){return Vt}),n.d(e,"FormConsumer",function(){return kt}),n.d(e,"createArrayField",function(){return Rt}),n.d(e,"registerFormField",function(){return j}),n.d(e,"registerFormFields",function(){return O}),n.d(e,"registerFormWrapper",function(){return E}),n.d(e,"registerFieldMiddleware",function(){return _}),n.d(e,"registerFormFieldPropsTransformer",function(){return F}),n.d(e,"caculateSchemaInitialValues",function(){return d.b}),n.d(e,"FormPath",function(){return jt}),S(),E(Tt()),It(),At(),Pt();const Dt=R()(a.a.forwardRef((t,e)=>{const{children:n,className:r,...i}=t;return a.a.createElement(V,o()({className:`rs-uform ${r||""}`},i,{ref:e}),a.a.createElement("div",{className:"rs-uform-content"},a.a.createElement(q,{name:"",path:[],schemaPath:[]})),n)})),$t=M,Yt=$.c,Wt=$.b,Xt=()=>Object(Ft.createActions)("getFormState","getFieldState","setFormState","setFieldState","getSchema","reset","submit","validate","dispatch"),Ht=()=>Object(Ft.createAsyncActions)("getFormState","getFieldState","setFormState","setFieldState","getSchema","reset","submit","validate","dispatch");Dt.displayName="SchemaForm";e.default=Dt},116:function(t,e,n){"use strict";var r=n(118);const i=t=>Object(r.a)(t)?t:t?[t]:[],o=(t,e,n)=>{if(Object(r.a)(t)){if(n){for(let n=t.length-1;n>=0;n--)if(!1===e(t[n],n))return}else for(let n=0,r=t.length;n<r;n++)if(!1===e(t[n],n))return}else for(let n in t)if(Object.hasOwnProperty.call(t,n)&&!1===e(t[n],n))return},s=(t,e,n,r)=>{let i=n;return o(t,(t,n)=>{i=e(i,t,n)},r),i},a=Symbol("newer"),c=Symbol("older");function u(t,e){"number"!=typeof t&&(e=t,t=0),this.size=0,this.limit=t,this.oldest=this.newest=void 0,this._keymap=new Map,e&&(this.assign(e),t<1&&(this.limit=this.size))}function l(t,e){this.key=t,this.value=e,this[a]=void 0,this[c]=void 0}function h(t){this.entry=t}function d(t){this.entry=t}function p(t){this.entry=t}function f(t){return" "===t||"\n"===t||"\t"===t||"\f"===t||"\r"===t}function m(t){return t?Object(r.a)(t)?t.join("."):Object(r.h)(t)?t:"":""}u.prototype._markEntryAsUsed=function(t){t!==this.newest&&(t[a]&&(t===this.oldest&&(this.oldest=t[a]),t[a][c]=t[c]),t[c]&&(t[c][a]=t[a]),t[a]=void 0,t[c]=this.newest,this.newest&&(this.newest[a]=t),this.newest=t)},u.prototype.assign=function(t){let e,n=this.limit||Number.MAX_VALUE;this._keymap.clear();let r=t[Symbol.iterator]();for(let t=r.next();!t.done;t=r.next()){let r=new l(t.value[0],t.value[1]);if(this._keymap.set(r.key,r),e?(e[a]=r,r[c]=e):this.oldest=r,e=r,0==n--)throw new Error("overflow")}this.newest=e,this.size=this._keymap.size},u.prototype.get=function(t){var e=this._keymap.get(t);if(e)return this._markEntryAsUsed(e),e.value},u.prototype.set=function(t,e){var n=this._keymap.get(t);return n?(n.value=e,this._markEntryAsUsed(n),this):(this._keymap.set(t,n=new l(t,e)),this.newest?(this.newest[a]=n,n[c]=this.newest):this.oldest=n,this.newest=n,++this.size,this.size>this.limit&&this.shift(),this)},u.prototype.shift=function(){var t=this.oldest;if(t)return this.oldest[a]?(this.oldest=this.oldest[a],this.oldest[c]=void 0):(this.oldest=void 0,this.newest=void 0),t[a]=t[c]=void 0,this._keymap.delete(t.key),--this.size,[t.key,t.value]},u.prototype.find=function(t){let e=this._keymap.get(t);return e?e.value:void 0},u.prototype.has=function(t){return this._keymap.has(t)},u.prototype.delete=function(t){var e=this._keymap.get(t);if(e)return this._keymap.delete(e.key),e[a]&&e[c]?(e[c][a]=e[a],e[a][c]=e[c]):e[a]?(e[a][c]=void 0,this.oldest=e[a]):e[c]?(e[c][a]=void 0,this.newest=e[c]):this.oldest=this.newest=void 0,this.size--,e.value},u.prototype.clear=function(){this.oldest=this.newest=void 0,this.size=0,this._keymap.clear()},h.prototype[Symbol.iterator]=function(){return this},h.prototype.next=function(){let t=this.entry;return t?(this.entry=t[a],{done:!1,value:[t.key,t.value]}):{done:!0,value:void 0}},d.prototype[Symbol.iterator]=function(){return this},d.prototype.next=function(){let t=this.entry;return t?(this.entry=t[a],{done:!1,value:t.key}):{done:!0,value:void 0}},p.prototype[Symbol.iterator]=function(){return this},p.prototype.next=function(){let t=this.entry;return t?(this.entry=t[a],{done:!1,value:t.value}):{done:!0,value:void 0}},u.prototype.keys=function(){return new d(this.oldest)},u.prototype.values=function(){return new p(this.oldest)},u.prototype.entries=function(){return this},u.prototype[Symbol.iterator]=function(){return new h(this.oldest)},u.prototype.forEach=function(t,e){"object"!=typeof e&&(e=this);let n=this.oldest;for(;n;)t.call(e,n.value,n.key,this),n=n[a]},u.prototype.toJSON=function(){for(var t=new Array(this.size),e=0,n=this.oldest;n;)t[e++]={key:n.key,value:n.value},n=n[a];return t},u.prototype.toString=function(){for(var t="",e=this.oldest;e;)t+=String(e.key)+":"+e.value,(e=e[a])&&(t+=" < ");return t};const b=new u(1e3);function y(t){if(Object(r.a)(t))return t;if(Object(r.h)(t)&&t){const e=b.get(t);if(e)return e;const n=t.split("."),r=[];for(let t=0;t<n.length;t++){let e=n[t];for(;"\\"===e[e.length-1]&&void 0!==n[t+1];)e=e.slice(0,-1)+".",e+=n[++t];r.push(e)}return b.set(t,r),r}return Object(r.d)(t)?[t]:[]}class v{constructor(t,e){this.text=t,this.index=0,this.cbs=e,this.state=this.processNameStart,this.declareNameStart=0,this.declareNameEnd=0,this.nbraceCount=0,this.nbracketCount=0}goto(t){this.state=this.StateMap[t]}parse(){let t="",e="",n=this.text.length;for(;this.index<n;this.index++)t=this.text.charAt(this.index),this.EOF=n-1===this.index,this.state(t,e),e=t}processNameStart(t){"{"===t||"["===t?(this.state=this.processDestructStart,this.index--):f(t)||(this.declareNameStart=this.index,this.state=this.processName)}processName(t,e){f(t)?(this.declareNameEnd=this.index,this.cbs.name(this.getName())):this.EOF&&(this.declareNameEnd=this.index+1,this.cbs.name(this.getName()))}processDestructStart(t){"{"===t?(this.nbraceCount++,this.cbs.destructObjectStart()):"["===t?(this.nbracketCount++,this.cbs.destructArrayStart()):f(t)||(this.state=this.processDestructKey,this.destructKeyStart=this.index,this.index--)}processDestructKey(t,e){"}"===t?(this.nbraceCount--,(this.nbraceCount||this.nbracketCount)&&(this.state=this.processDestructStart),f(e)||(this.destructKey=this.text.substring(this.destructKeyStart,this.index)),this.cbs.destructKey(this.destructKey),this.cbs.destructObjectEnd(),this.nbraceCount||this.nbracketCount||(this.index=this.text.length)):"]"===t?(this.nbracketCount--,(this.nbraceCount||this.nbracketCount)&&(this.state=this.processDestructStart),f(e)||(this.destructKey=this.text.substring(this.destructKeyStart,this.index)),this.cbs.destructKey(this.destructKey),this.cbs.destructArrayEnd(),this.nbraceCount||this.nbracketCount||(this.index=this.text.length)):(f(t)||":"===t||","===t)&&(f(e)||(this.destructKey=this.text.substring(this.destructKeyStart,this.index)),f(t)||(this.state=this.processDestructStart,this.cbs.destructKey(this.destructKey,":"===t)))}getName(){return this.text.substring(this.declareNameStart,this.declareNameEnd)}}const g=(t,e)=>{const n=(t,e,i)=>((t,e,n)=>{let i=Object(r.a)(t)?[]:{};return o(t,(t,n)=>{const o=e(t,n);Object(r.a)(i)?i.push(o):i[n]=o},n),i})(t,(t,o)=>{const s=e.concat(o);return Object(r.a)(t)||Object(r.f)(t)?n(t,s,i):i(s,s.slice(0,s.length-1).concat(t))});return n(t,[],e)},x=t=>{const e=y(t),n=e[e.length-1],i=e.slice(0,e.length-1);return{path:e,lastKey:n,startPath:i,destruct:(t=>{if(!Object(r.h)(t))return t;let e,n,i,o=[],s="",a="";return new v(t,{name(t){i=t},destructKey(t,i){if(t){if(s=t,i)return a=t,void(n=e);Object(r.a)(e)?e.push(t):Object(r.f)(e)&&(e[a&&n===e?a:t]=t),a="",n=e}},destructArrayStart(){e=e?[]:i=[];const t=o[o.length-1];Object(r.f)(t)?t[s]=e:Object(r.a)(t)&&t.push(e),o.push(e)},destructObjectStart(){e=e?{}:i={};const t=o[o.length-1];Object(r.f)(t)?t[s]=e:Object(r.a)(t)&&t.push(e),o.push(e)},destructArrayEnd(){o.pop(),e=o[o.length-1]},destructObjectEnd(){o.pop(),e=o[o.length-1]}}).parse(),i})(n)}},w=t=>{const e=[],n=x(t);return Object(r.h)(n.destruct)?t:n.destruct?(((t,e)=>{const n=(t,e,i)=>{if(Object(r.h)(t))return i(t,t);o(t,(t,o)=>{const s=e.concat(o);Object(r.a)(t)||Object(r.f)(t)?n(t,s,i):i(s,t)})};n(t,[],e)})(n.destruct,(t,r)=>{e.push({path:n.startPath.concat(t),startPath:n.startPath,endPath:t,key:r})}),e):t},S=(t,e)=>{const n=new Map;return(i,s,a)=>{let c=[];return(c=n.get(s))||(c=w(s),n.set(s,c)),Object(r.a)(c)?(c&&c.length&&o(c,({path:n,key:r,startPath:o,endPath:s})=>{t(i,o.concat(r),e(a,s))}),i):t(i,s,a)}};const j=(t=>{const e=new Map;return(n,i,o)=>{let s=null;return(s=e.get(i))||(s=x(i),e.set(i,s)),Object(r.a)(s.destruct)||Object(r.f)(s.destruct)?g(s.destruct,(e,r)=>t(n,s.startPath.concat(r))):t(n,i,o)}})(function(t,e,n){if(!Object(r.e)(t)||!e)return t;if((e=m(e))in t)return t[e];const i=y(e);for(let e=0;e<i.length;e++){if(!Object.prototype.propertyIsEnumerable.call(t,i[e]))return n;if(null==(t=t[i[e]])){if(e!==i.length-1)return n;break}}return t}),O=S(function(t,e,n){if(!Object(r.e)(t)||!e)return;if((e=m(e))in t)return void(t[e]=n);const i=y(e);for(let e=0;e<i.length;e++){const o=i[e];Object(r.e)(t[o])||(t[o]={}),e===i.length-1&&(t[o]=n),t=t[o]}},j),_=S(function(t,e){if(!Object(r.e)(t)||!e)return;if((e=m(e))in t)return void delete t[e];const n=y(e);for(let e=0;e<n.length;e++){const i=n[e];if(e===n.length-1)return void(Object(r.a)(t)?t.splice(i,1):delete t[i]);if(t=t[i],!Object(r.e)(t))return}},j);(t=>{const e=new Map})(function(t,e){if(!Object(r.e)(t)||!e)return!1;if((e=m(e))in t)return!0;const n=y(e);for(let e=0;e<n.length;e++){if(!Object(r.e)(t))return!1;if(!(n[e]in t))return!1;t=t[n[e]]}return!0});var E=r.a,F=Object.keys,C=Object.prototype.hasOwnProperty;const N=function(t,e,n){try{return function t(e,n,i){if(e===n)return!0;if(e&&n&&"object"==typeof e&&"object"==typeof n){var o,s,a,c=E(e),u=E(n);if(c&&u){if((s=e.length)!==n.length)return!1;for(o=s;0!=o--;)if(!t(e[o],n[o],i))return!1;return!0}if(c!=u)return!1;var l=e instanceof Date,h=n instanceof Date;if(l!=h)return!1;if(l&&h)return e.getTime()==n.getTime();var d=e instanceof RegExp,p=n instanceof RegExp;if(d!=p)return!1;if(d&&p)return e.toString()==n.toString();var f=e instanceof URL,m=n instanceof URL;if(f&&m)return f.href==m.href;var b=F(e);if((s=b.length)!==F(n).length)return!1;for(o=s;0!=o--;)if(!C.call(n,b[o]))return!1;for(o=s;0!=o--;)if("_owner"!==(a=b[o])||!e.$$typeof)if(Object(r.c)(i)){if(i({a:e[a],b:n[a]},a)&&!t(e[a],n[a],i))return!1}else if(!t(e[a],n[a],i))return!1;return!0}return e&&n&&"function"==typeof e&&"function"==typeof n?e.toString()===n.toString():e!=e&&n!=n}(t,e,n)}catch(t){if(t.message&&t.message.match(/stack|recursion/i)||-2146828260===t.number)return console.warn("Warning: react-fast-compare does not handle circular references.",t.name,t.message),!1;throw t}};var V=n(153),k=n.n(V);class T{constructor(){k()(this,"entries",[]),k()(this,"buffer",[])}subscribe(t,e){if(!Object(r.c)(t))return()=>{};let n=this.entries.length;return this.entries.push({subscriber:t,subscription:e}),this.flushBuffer(this.entries[n]),()=>{this.entries.splice(n,1)}}unsubscribe(){this.entries.length=0,this.buffer.length=0}flushBuffer({subscriber:t,subscription:e}){o(this.buffer,({payload:n,filter:i})=>{if(Object(r.c)(i)){let r;(r=i(n,e))&&t(r)}else t(n,e)})}notify(t,e){0!==this.length?(o(this.entries,({subscriber:n,subscription:i})=>{if(Object(r.c)(e)){let r;(r=e(t,i))&&n(r)}else n(t,i)}),this.buffer.length=0):this.buffer.push({payload:t,filter:e})}}var I=n(134),A=Object.prototype.hasOwnProperty,P=Object.prototype.toString;function q(t){if(null==t)return!0;if("boolean"==typeof t)return!1;if("number"==typeof t)return!1;if("string"==typeof t)return 0===t.length;if("function"==typeof t)return 0===t.length;if(Array.isArray(t)){if(0===t.length)return!0;for(let e=0;e<t.length;e++)if(void 0!==t[e]&&null!==t[e]&&""!==t[e]&&0!==t[e])return!1;return!0}if(t instanceof Error)return""===t.message;if(t.toString===P)switch(t.toString()){case"[object File]":case"[object Map]":case"[object Set]":return 0===t.size;case"[object Object]":for(var e in t)if(A.call(t,e))return!1;return!0}return!1}const z=/^\d+$/,B={},M=(t,e)=>{let n=t,r=0;e=i(e);for(let t=0;t<e.length;t++){var o=e[t];n&&!q(n.properties)?(n=n.properties[o],r++):n&&!q(n.items)&&z.test(o)&&(n=n.items,r++)}return r===e.length?n:void 0},R=(t,e)=>t&&t.type===e,D=t=>!!B[t],$=t=>{B[t]=!0},Y=t=>D(t.type)||D(t["x-component"]),W=(t,e,n=[],r=[])=>{t&&(Y(t)&&(n=n.slice(0,n.length-1)),e(t,{path:n,schemaPath:r}),R(t,"object")||t.properties?o(t.properties,(t,i)=>{W(t,e,n.concat(i),r.concat(i))}):(R(t,"array")||t.items)&&t.items&&e(t.items,i=>{W(t.items,e,n.concat(i),r.concat(i))},n))},X=(t,e,n)=>(e=e||t.default||{},W(t,(t,s,a)=>{const c=t.default;if(Object(r.c)(s)&&a)o(i(j(e,a)),function(t,e){s(e)});else if(s){const i=Y(t),o=i?s.schemaPath.join("."):s.path.join("."),a=i?s.schemaPath:s.path,u=s.schemaPath,l=j(e,o);let h=q(l)?c:l;if(q(h)||O(e,o,h),Object(r.c)(n)){n({name:o,path:a,schemaPath:u},t,h)}}}),e),H=n(154),U=t=>String(t||"").toLowerCase(),L=()=>{let t,e;return{promise:new Promise((n,r)=>{t=n,e=r}),resolve:t,reject:e}};n.d(e,"i",function(){return y}),n.d(e,"h",function(){return j}),n.d(e,"w",function(){return O}),n.d(e,"f",function(){return _}),n.d(e,"x",function(){return i}),n.d(e,"g",function(){return o}),n.d(e,"t",function(){return s}),n.d(e,"n",function(){return N}),n.d(e,"a",function(){return T}),n.d(e,"o",function(){return r.c}),n.d(e,"k",function(){return r.a}),n.d(e,"r",function(){return r.h}),n.d(e,"l",function(){return r.b}),n.d(e,"p",function(){return r.e}),n.d(e,"q",function(){return r.g}),n.d(e,"d",function(){return I.a}),n.d(e,"j",function(){return M}),n.d(e,"v",function(){return R}),n.d(e,"u",function(){return $}),n.d(e,"b",function(){return X}),n.d(e,"m",function(){return q}),n.d(e,"c",function(){return H}),n.d(e,"s",function(){return U}),n.d(e,"e",function(){return L})},118:function(t,e,n){"use strict";n.d(e,"c",function(){return i}),n.d(e,"a",function(){return o}),n.d(e,"f",function(){return s}),n.d(e,"h",function(){return a}),n.d(e,"b",function(){return c}),n.d(e,"d",function(){return u}),n.d(e,"e",function(){return l}),n.d(e,"g",function(){return h});const r=t=>e=>null!=e&&Object.prototype.toString.call(e)===`[object ${t}]`,i=r("Function"),o=Array.isArray||r("Array"),s=r("Object"),a=r("String"),c=r("Boolean"),u=r("Number"),l=t=>"object"==typeof t,h=r("RegExp")},119:function(t,e,n){"use strict";n.d(e,"c",function(){return o});var r=n(116);n.d(e,"a",function(){return r.d}),n.d(e,"b",function(){return r.g}),n.d(e,"d",function(){return r.h}),n.d(e,"e",function(){return r.k}),n.d(e,"f",function(){return r.m}),n.d(e,"g",function(){return r.n}),n.d(e,"h",function(){return r.o}),n.d(e,"i",function(){return r.p}),n.d(e,"j",function(){return r.q}),n.d(e,"k",function(){return r.r}),n.d(e,"l",function(){return r.t}),n.d(e,"m",function(){return r.x});const i=/%[sdj%]/g;function o(...t){let e=1;const n=t[0],r=t.length;if("function"==typeof n)return n.apply(null,t.slice(1));if("string"==typeof n){return String(n).replace(i,n=>{if("%%"===n)return"%";if(e>=r)return n;switch(n){case"%s":return String(t[e++]);case"%d":return Number(t[e++]);case"%j":try{return JSON.stringify(t[e++])}catch(t){return"[Circular]"}default:return n}})}return n}},120:function(t,e,n){"use strict";(function(t){n.d(e,"c",function(){return a}),n.d(e,"b",function(){return c}),n.d(e,"a",function(){return u});var r=n(119),i=n(144);const o=t||window,s={messages:{},lang:(()=>o.navigator&&(o.navigator.browserlanguage||o.navigator.language)||"en")()},a=t=>{Object.assign(s.messages,t)},c=t=>{s.lang=t},u=t=>Object(r.d)(s.messages,`${(t=>{let e=s.lang;return Object(r.b)(s.messages,(n,r)=>{if(r.indexOf(t)>-1||String(t).indexOf(r)>-1)return e=r,!1}),e})(s.lang)}.${t}`)||"field is not valid,but not found error message.";a(i.a)}).call(this,n(36))},121:function(t,e,n){"use strict";(function(t){n.d(e,"u",function(){return c}),n.d(e,"d",function(){return u}),n.d(e,"w",function(){return l}),n.d(e,"n",function(){return h}),n.d(e,"k",function(){return d}),n.d(e,"t",function(){return p}),n.d(e,"s",function(){return f}),n.d(e,"b",function(){return m});var r=n(141),i=n.n(r),o=n(155),s=n(116);n.d(e,"a",function(){return s.a}),n.d(e,"c",function(){return s.b}),n.d(e,"e",function(){return s.d}),n.d(e,"f",function(){return s.e}),n.d(e,"g",function(){return s.f}),n.d(e,"h",function(){return s.g}),n.d(e,"i",function(){return s.h}),n.d(e,"j",function(){return s.j}),n.d(e,"l",function(){return s.k}),n.d(e,"m",function(){return s.l}),n.d(e,"o",function(){return s.m}),n.d(e,"p",function(){return s.n}),n.d(e,"q",function(){return s.o}),n.d(e,"r",function(){return s.r}),n.d(e,"v",function(){return s.t}),n.d(e,"x",function(){return s.w}),n.d(e,"y",function(){return s.x});const a=t||window,c=a.requestAnimationFrame&&(o.scheduleCallback||o.unstable_scheduleCallback||a.requestAnimationFrame)||a.setTimeout,u=a.requestAnimationFrame&&(o.cancelCallback||o.unstable_cancelCallback||a.cancelAnimationFrame)||a.clearTimeout,l=t=>Object(s.k)(t)?t.reduce((t,e)=>t.concat(Object(s.i)(e)),[]):Object(s.r)(t)?l(Object(s.i)(t)):void 0,h=(t,e)=>{if(t&&e&&t.path&&e.path){for(let n=0;n<e.path.length;n++)if(t.path[n]!==e.path[n])return!1;return e.path.length<t.path.length}return!1},d=t=>Object(s.x)(t).some(t=>t&&t.required),p=t=>{const{values:e,valid:n,invalid:r,errors:i,pristine:o,dirty:s}=t;return{values:e,valid:n,invalid:r,errors:i,pristine:o,dirty:s}},f=t=>{const{value:e,valid:n,invalid:r,errors:i,visible:o,editable:a,initialValue:c,name:u,path:l,props:h,effectErrors:d,loading:p,pristine:f,required:m,rules:b}=t;return{value:Object(s.d)(e),valid:n,invalid:r,editable:a,visible:o,loading:p,errors:i.concat(d),pristine:f,initialValue:c,name:u,path:l,props:h,required:m,rules:b}};class m{constructor(){i()(this,"data",[]),i()(this,"indexes",{})}push(t,e,n){if(this.indexes[t]){let n=this.data[this.indexes[t]];-1===n.values.indexOf(e)&&n.values.push(e)}else{let r=this.data.length;this.data.push({...n,key:t,values:[e]}),this.indexes[t]=r}}forEach(t){for(let e=0;e<this.data.length;e++)Object(s.o)(t)&&t(this.data[e],this.data[e].key)}remove(t,e){this.data=this.data.reduce((e,n,r)=>n.key===t?(delete this.indexes[t],e):(this.indexes[t]=e.length,e.concat(n)),[])}}}).call(this,n(36))},132:function(t,e,n){"use strict";n.r(e);var r=n(159),i=n.n(r),o=n(160),s=n.n(o),a=n(0),c=n.n(a),u=n(2),l=n.n(u),h=n(115),d=n(1),p=n.n(d),f=n(161),m=n.n(f);const b=p()(t=>{const[e,n]=Object(a.useState)(!0);return c.a.createElement(m.a,s()({},t,{style:{overlay:{zIndex:99999}},isOpen:e,onRequestClose:()=>{n(!1)}}),c.a.createElement("div",{className:"close-btn",onClick:()=>{n(!1)}},c.a.createElement("img",{src:"//img.alicdn.com/tfs/TB1KikcO5rpK1RjSZFhXXXSdXXa-200-200.svg"})),c.a.createElement("div",{className:"dialog-content",style:{overflow:"auto"}},t.children))})` position: relative; margin: 100px; padding: 30px; height: calc(100% - 200px); overflow: auto; border: 1px solid #eee; background: #fff; outline: none; .close-btn { position: absolute; top: 15px; right: 10px; width: 25px; height: 25px; cursor: pointer; img { width: 100%; } } .dialog-content { overflow: auto; height: 100%; } `,y=t=>{if(t)return{type:t.type,"x-props":t["x-props"],"x-component":t["x-component"],"x-index":t["x-index"],"x-rules":t["x-rules"],maxItems:t.maxItems,minItems:t.minItems,default:t.default,enum:t.enum,title:t.title,required:t.required,properties:Object.keys(t.properties||{}).reduce((e,n)=>(e[n]=y(t.properties[n]),e),{}),items:y(t.items)}};e.default=class extends c.a.Component{constructor(...t){super(...t),i()(this,"actions",Object(h.createFormActions)()),i()(this,"onClickHandler",async t=>{t.preventDefault();const e=await this.actions.getSchema("");((t={})=>{const e=document.createElement("div");("string"==typeof t||c.a.isValidElement(t))&&(t={content:t}),document.body.appendChild(e),l.a.render(c.a.createElement(b,s()({},t,{appElement:e,afterClose:()=>{l.a.unmountComponentAtNode(e),e.parentNode.removeChild(e)}}),t.content),e)})(c.a.createElement("pre",null,c.a.createElement("code",null,(t=>JSON.stringify(y(t),null,2))(e))))})}render(){const{children:t,className:e}=this.props;return t&&t.props&&t.props.actions&&(this.actions=t.props.actions),c.a.createElement("div",{className:e},c.a.cloneElement(t,{actions:this.actions}),c.a.createElement("a",{href:"",style:{fontSize:12,textDecoration:"none",margin:"20px 0",display:"block",textAlign:"center"},onClick:this.onClickHandler},"Print JSON Schema"))}}},134:function(t,e,n){"use strict";(function(t){n.d(e,"a",function(){return s});var r=n(118);const i=t||window,o=[["Map",t=>new Map(t)],["WeakMap",t=>new WeakMap(t)],["WeakSet",t=>new WeakSet(t)],["Set",t=>new Set(t)],"FileList","File","URL","RegExp",["Promise",t=>new Promise((e,n)=>t.then(e,n))]],s=(t,e)=>{let n;if(Array.isArray(t))return t.map(t=>s(t,e));if(n=(t=>{for(let e=0;e<o.length;e++){let n=o[e];if(Array.isArray(n)&&n[0]){if(i[n[0]]&&t instanceof i[n[0]])return n[1]?n[1]:n[0]}else if(i[n]&&t instanceof i[n])return n}})(t))return Object(r.c)(n)?n(t):t;if("object"==typeof t&&t){if("$$typeof"in t&&"_owner"in t)return t;let n={};for(let i in t)Object.hasOwnProperty.call(t,i)&&(Object(r.c)(e)?e(t[i],i)?n[i]=s(t[i],e):n[i]=t[i]:n[i]=s(t[i],e));return n}return t}}).call(this,n(36))},139:function(t,e,n){var r={"./bash":123,"./bash.js":123,"./css":124,"./css.js":124,"./htmlbars":125,"./htmlbars.js":125,"./javascript":126,"./javascript.js":126,"./scss":127,"./scss.js":127,"./typescript":128,"./typescript.js":128};function i(t){var e=o(t);return n(e)}function o(t){if(!n.o(r,t)){var e=new Error("Cannot find module '"+t+"'");throw e.code="MODULE_NOT_FOUND",e}return r[t]}i.keys=function(){return Object.keys(r)},i.resolve=o,t.exports=i,i.id=139},144:function(t,e,n){"use strict";e.a={en:{pattern:"%s value %s does not match pattern %s",required:"%s is required",number:"%s is not a number",integer:"%s is not an integer number",url:"%s is a invalid url",email:"%s is not a email format",ipv6:"%s is not a ipv6 format",ipv4:"%s is not a ipv4 format",idcard:"%s is not an idcard format",taodomain:"%s is not a taobao domain format",qq:"%s is not a qq number format",phone:"%s is not a phone number format",money:"%s is not a currency format",zh:"%s is not a chinese string",date:"%s is not a valid date format",zip:"%s is not a zip format"},zh:{pattern:"该字段不是一个合法的字段",required:"该字段是必填字段",number:"该字段不是合法的数字",integer:"该字段不是合法的整型数字",url:"该字段不是合法的url",email:"该字段不是合法的邮箱格式",ipv6:"该字段不是合法的ipv6格式",ipv4:"该字段不是合法的ipv4格式",idcard:"该字段不是合法的身份证格式",taodomain:"该字段不符合淘系域名规则",qq:"该字段不符合QQ号格式",phone:"该字段不是有效的手机号",money:"该字段不是有效货币格式",zh:"该字段不是合法的中文字符串",date:"该字段不是合法的日期格式",zip:"该字段不是合法的邮编格式"}}},149:function(t,e,n){"use strict";n.r(e);var r=n(122),i=n.n(r),o=n(131),s=n.n(o),a=n(0),c=n.n(a),u=n(115),l=n(145),h=n.n(l),d=n(68),p={addItem:"添加",array_invalid_minItems:"条目数不允许小于%s条",array_invalid_maxItems:"条目数不允许大于%s条",operations:"操作"},f=n(1),m=n.n(f),b=n(2),y=n.n(b),v=n(172),g=n.n(v),x=n(116);const w=m()(class extends c.a.Component{render(){const{dataSource:t=[],...e}=this.props,n=t.map(t=>{const{label:e,value:n,...r}=t;return c.a.createElement(d.Select.Option,i()({key:n},r,{label:e,value:n}),e)});return c.a.createElement(d.Select,i()({className:this.props.className},e),n)}})` min-width: 200px; max-width: 300px; `,S=m()(t=>{let e;if(t.dataSource&&t.dataSource.length){e=t.dataSource.filter(({value:e})=>Array.isArray(t.value)?t.value.indexOf(e)>-1:t.value===e).map(t=>t.label).join(" , ")}else e=Array.isArray(t.value)?t.value.join(" ~ "):String(void 0===t.value||null===t.value?"":t.value);return c.a.createElement("div",{className:`${t.className} ${t.size||""} text-field`},e||"N/A",t.addonAfter?" "+t.addonAfter:"")})` height: 32px; line-height: 32px; vertical-align: middle; font-size: 13px; color: #333; &.small { height: 24px; line-height: 24px; } &.large { height: 40px; line-height: 40px; } `,j=t=>(class extends c.a.Component{componentDidMount(){this.wrapper&&(this.wrapperDOM=y.a.findDOMNode(this.wrapper),this.mapState())}componentDidUpdate(){this.mapState()}mapState(){const{state:t}=this.props,e=["xxs","xs","small","medium","large","xl","xxl","xxxl"];if(this.classList=this.classList||[],this.wrapperDOM){const n=this.wrapperDOM.querySelector(".anticon");if(!n||!n.classList)return;"loading"===t?(n.classList.forEach(t=>{t.indexOf("anticon-")>-1&&"anticon-spin"!==t&&e.every(e=>`anticon-${e}`!==t)&&(n.classList.remove(t),this.classList.push(t))}),n.classList.contains("anticon-spin")||n.classList.add("anticon-spin")):(n.classList.remove("anticon-spin"),this.classList.forEach(t=>{n.classList.add(t)}),this.classList=[])}}render(){return c.a.createElement(t,i()({ref:t=>{t&&(this.wrapper=t)}},this.props))}}),O=j(w),_=t=>({dataSource:e,...n})=>e||n.showSearch?c.a.createElement(O,{dataSource:e,...n}):c.a.createElement(t,n),E=(t,{loading:e,size:n})=>{e&&(t.state=t.state||"loading"),n&&(t.size=n)},F=(t,e,{editable:n,name:r})=>{if(void 0!==n)if(Object(x.o)(n)){if(!n(r))return S}else if(!1===n)return S;return t},C=(t,e)=>({dataSource:n,...r})=>c.a.createElement(t,{[e]:n,...r}),N=t=>{t&&(t.scrollIntoView?t.scrollIntoView({behavior:"smooth",inline:"start",block:"start"}):(new g.a).move(t.getBoundingClientRect().top))};var V,k;const{Provider:T,Consumer:I}=c.a.createContext(),A=t=>"object"==typeof t?t:{span:t},P=(t,e)=>{if(t&&(!t||t.matches))return t.matches(e)?t:P(t.parentNode||t.parentElement,e)},q=m()((k=V=class extends c.a.Component{getItemLabel(){const{id:t,required:e,label:n,labelCol:r,wrapperCol:o,prefix:s,extra:a,labelAlign:u,labelTextAlign:l,autoAddColon:p,isTableColItem:f}=this.props;if(!n||f)return null;const m=c.a.createElement("label",{htmlFor:t,required:e,key:"label"},n," "===n?"":p?":":""),b=h()({[`${s}form-item-label`]:!0,[`${s}${l}`]:!!l});return(o||r)&&"top"!==u?c.a.createElement(d.Col,i()({},A(r),{className:b}),m,(a&&a.length>20||c.a.isValidElement(a))&&this.renderHelper()):c.a.createElement("div",{className:b},m,(a&&a.length>20||c.a.isValidElement(a))&&this.renderHelper())}getItemWrapper(){const{labelCol:t,wrapperCol:e,children:n,extra:r,label:o,labelAlign:s,help:a,prefix:u,noMinHeight:l,size:h,isTableColItem:p}=this.props,f=c.a.createElement("div",{className:`${u}form-item-msg ${l?"":`${u}form-item-space`}`},a&&c.a.createElement("div",{className:`${u}form-item-help`},a),!a&&r&&r.length<=20&&c.a.createElement("div",{className:`${u}form-item-extra`},r));return(e||t)&&"top"!==s&&!p&&o?c.a.createElement(d.Col,i()({},A(e),{className:`${u}form-item-control`,key:"item"}),c.a.cloneElement(n,{size:h}),f):c.a.createElement("div",{className:`${u}form-item-control`},c.a.cloneElement(n,{size:h}),f)}renderHelper(){return c.a.createElement(d.Popover,{closable:!1,placement:"top",content:this.props.extra},c.a.createElement(d.Icon,{type:"question-circle",size:"small"}))}render(){const{className:t,labelAlign:e,labelTextAlign:n,style:r,prefix:o,wrapperCol:s,labelCol:a,size:u,help:l,extra:p,noMinHeight:f,isTableColItem:m,validateState:b,autoAddColon:y,required:v,type:g,schema:x,...w}=this.props,S=h()({[`${o}form-item`]:!0,[`${o}${e}`]:e,[`has-${b}`]:!!b,[`${o}${u}`]:!!u,[`${t}`]:!!t,[`field-${g}`]:!!g}),j=(s||a)&&"top"!==e?d.Row:"div",O="inset"===e?null:this.getItemLabel();return c.a.createElement(j,i()({},w,{gutter:0,className:S,style:r}),O,this.getItemWrapper())}},s()(V,"defaultProps",{prefix:"ant-"}),k))` margin-bottom: 0 !important; .ant-form-item-control { display: block; line-height: 32px; } &.field-table { .ant-form-item-control { overflow: auto; } } .antd-uploader { display: block; } .ant-form-item-msg { &.ant-form-item-space { min-height: 24px; .ant-form-item-help, .ant-form-item-extra { margin-top: 0; line-height: 1.5; } } } .ant-form-item-extra { color: #888; font-size: 12px; line-height: 1.7; } &.ant-form-item.ant-row { display: flex; } .ant-col { padding-right: 0; } .ant-card-head { background: none; } .ant-form-item-label label:after { content: ''; } .ant-form-item-label label { color: #666; font-size: 12px; } ul { padding: 0; li { margin: 0; & + li { margin: 0; } } } .ant-left { text-align: left; } .ant-right { text-align: right; } .ant-center { text-align: center; } `,z=t=>Array.isArray(t)?t:t?[t]:[];Object(u.registerFormWrapper)(t=>{t=m()(t)` &.ant-inline, .ant-inline { display: flex; .rs-uform-content { margin-right: 15px; } .ant-form-item { display: inline-block; vertical-align: top; } .ant-form-item:not(:last-child) { margin-right: 20px; } .ant-form-item.ant-left .ant-form-item-control { display: inline-block; display: table-cell\0; vertical-align: top; line-height: 0; } } .ant-form-item-label { line-height: 32px; padding-right: 12px; text-align: right; } .ant-small { .ant-form-item-label { line-height: 24px; } .ant-radio-group, .ant-checkbox-group { line-height: 24px; min-height: 24px; } } .ant-large { .ant-form-item-label { line-height: 40px; } .ant-radio-group, .ant-checkbox-group { line-height: 40px; min-height: 40px; } } .ant-form-item-label label[required]:before { margin-right: 4px; content: '*'; color: #ff3000; } .ant-form-item-help { margin-top: 4px; font-size: 12px; line-height: 1.5; color: #999; } .ant-form-item.has-error .ant-form-item-help { color: #ff3000; } .ant-radio-group, .ant-checkbox-group { line-height: 32px; & > label { margin-right: 15px; } } .ant-range { margin-top: 10px; } .ant-number-picker-normal { min-width: 62px; width: 100px; .ant-number-picker-input-wrap { width: calc(100% - 22px); .ant-number-picker-input { width: 100%; input { text-align: left; padding: 0 8px; } } } } .ant-table { table { table-layout: auto; } } .ant-rating-default { min-height: 30px; line-height: 30px; } .ant-rating-small { min-height: 24px; line-height: 24px; } .ant-rating-large { min-height: 40px; line-height: 40px; } `;class e extends c.a.Component{constructor(...t){super(...t),s()(this,"FormRef",c.a.createRef())}validateFailedHandler(t){return(...e)=>{Object(x.o)(t)&&t(...e);const n=this.FormRef.current;if(n){const t=n.querySelectorAll(".ant-form-item-help");if(t&&t.length){const e=P(t[0],".ant-form-item");e&&N(e)}}}}render(){const{className:e,inline:n,size:r,labelAlign:o,labelTextAlign:s,autoAddColon:a,children:u,component:l,labelCol:d,wrapperCol:p,style:f,prefix:m,...b}=this.props,y=h()({[`${m}form`]:!0,[`${m}inline`]:n,[`${m}${r}`]:r,[`${m}form-${o}`]:!!o,[e]:!!e});return c.a.createElement(T,{value:{labelAlign:o,labelTextAlign:s,labelCol:d,wrapperCol:p,inline:n,size:r,autoAddColon:a,FormRef:this.FormRef}},c.a.createElement(t,i()({},b,{formRef:this.FormRef,onValidateFailed:this.validateFailedHandler(b.onValidateFailed),className:y,style:f}),u))}}return s()(e,"defaultProps",{component:"form",prefix:"ant-",size:"default",labelAlign:"left",locale:p,autoAddColon:!0}),s()(e,"displayName","SchemaForm"),e.LOCALE=p,e});const B=(t,e)=>{const n=e(t);return n&&"array"===n.type&&"table"===n["x-component"]};Object(u.registerFieldMiddleware)(t=>e=>{const{name:n,errors:r,editable:i,path:o,required:s,schema:a,getSchema:u}=e;return 0===o.length?c.a.createElement(t,e):c.a.createElement(I,{},({labelAlign:l,labelTextAlign:h,labelCol:d,wrapperCol:p,size:f,autoAddColon:m})=>c.a.createElement(q,{labelAlign:l,labelTextAlign:h,labelCol:d,wrapperCol:p,autoAddColon:m,size:f,...a["x-item-props"],label:a.title,noMinHeight:"object"===a.type&&!a["x-component"],isTableColItem:B(o.slice(0,o.length-2),u),type:a["x-component"]||a.type,id:n,validateState:z(r).length?"error":void 0,required:!1!==i&&s,extra:a.description,help:z(r).join(" , ")||a["x-item-props"]&&a["x-item-props"].help},c.a.createElement(t,e)))}),Object(u.registerFormField)("string",Object(u.connect)({getProps:E,getComponent:F})(_(d.Input))),Object(u.registerFormField)("number",Object(u.connect)({getProps:E,getComponent:F})(_(d.InputNumber))),Object(u.registerFormField)("boolean",Object(u.connect)({valueName:"checked",getProps:E})(_(d.Switch)));var M=n(69),R=n.n(M);const{RangePicker:D,MonthPicker:$}=d.DatePicker;const Y=j(d.DatePicker),W=j(D),X=j($),H=j(class extends c.a.Component{render(){return c.a.createElement(d.DatePicker,i()({},this.props,{mode:"year"}))}}),U=(t,e="YYYY-MM-DD HH:mm:ss")=>t&&t.format?t.format(e):t;var L,K;Object(u.registerFormField)("date",Object(u.connect)({getValueFromEvent(t,e){const n=this.props||{};return U(e,n.showTime?"YYYY-MM-DD HH:mm:ss":"YYYY-MM-DD")},getProps:t=>{const{value:e,showTime:n=!1,disabled:r=!1,...i}=t;try{!r&&e&&(t.value=R()(e,n?"YYYY-MM-DD HH:mm:ss":"YYYY-MM-DD"))}catch(t){throw new Error(t)}E(t,i)},getComponent:F})(Y)),Object(u.registerFormField)("daterange",Object(u.connect)({getValueFromEvent(t,[e,n]){const r=(this.props||{}).showTime?"YYYY-MM-DD HH:mm:ss":"YYYY-MM-DD";return[U(e,r),U(n,r)]},getProps:t=>{const{value:e=[],showTime:n=!1,disabled:r=!1,...i}=t;try{!r&&e.length&&(t.value=e.map(t=>t&&R()(t,n?"YYYY-MM-DD HH:mm:ss":"YYYY-MM-DD")||""))}catch(t){throw new Error(t)}E(t,i)},getComponent:F})(W)),Object(u.registerFormField)("month",Object(u.connect)({getValueFromEvent:(t,e)=>U(e),getProps:t=>{const{value:e,showTime:n=!1,disabled:r=!1,...i}=t;try{!r&&e&&(t.value=R()(e,n?"YYYY-MM-DD HH:mm:ss":"YYYY-MM"))}catch(t){throw new Error(t)}E(t,i)},getComponent:F})(X)),Object(u.registerFormField)("year",Object(u.connect)({getValueFromEvent:(t,e)=>(console.log(t,e),U(e)),getProps:t=>{const{value:e,showTime:n=!1,disabled:r=!1,...i}=t;try{!r&&e&&(t.value=R()(e,n?"YYYY-MM-DD HH:mm:ss":"YYYY-MM"))}catch(t){throw new Error(t)}E(t,i)},getComponent:F})(H)),Object(u.registerFormField)("time",Object(u.connect)({getValueFromEvent:(t,e)=>e,getProps:t=>{const{value:e,disabled:n=!1,...r}=t;try{!n&&e&&(t.value=R()(e,"HH:mm:ss"))}catch(t){throw new Error(t)}E(t,r)},getComponent:F})(d.TimePicker)),Object(u.registerFormField)("range",Object(u.connect)({defaultProps:{style:{width:320}},getProps:E})(class extends c.a.Component{render(){const{onChange:t,value:e,min:n,max:r,marks:i}=this.props;let o={};return Array.isArray(i)?i.forEach(t=>{o[t]=t}):o=i,c.a.createElement(d.Slider,{onChange:t,value:e,min:n,max:r,marks:o})}}));const{Dragger:G}=d.Upload,Q=[{ext:/\.docx?/i,icon:"//img.alicdn.com/tfs/TB1n8jfr1uSBuNjy1XcXXcYjFXa-200-200.png"},{ext:/\.pptx?/i,icon:"//img.alicdn.com/tfs/TB1ItgWr_tYBeNjy1XdXXXXyVXa-200-200.png"},{ext:/\.jpe?g/i,icon:"//img.alicdn.com/tfs/TB1wrT5r9BYBeNjy0FeXXbnmFXa-200-200.png"},{ext:/pdf/i,icon:"//img.alicdn.com/tfs/TB1GwD8r9BYBeNjy0FeXXbnmFXa-200-200.png"},{ext:/\.png/i,icon:"//img.alicdn.com/tfs/TB1BHT5r9BYBeNjy0FeXXbnmFXa-200-200.png"},{ext:/\.eps/i,icon:"//img.alicdn.com/tfs/TB1G_iGrVOWBuNjy0FiXXXFxVXa-200-200.png"},{ext:/\.ai/i,icon:"//img.alicdn.com/tfs/TB1B2cVr_tYBeNjy1XdXXXXyVXa-200-200.png"},{ext:/\.gif/i,icon:"//img.alicdn.com/tfs/TB1DTiGrVOWBuNjy0FiXXXFxVXa-200-200.png"},{ext:/\.svg/i,icon:"//img.alicdn.com/tfs/TB1uUm9rY9YBuNjy0FgXXcxcXXa-200-200.png"},{ext:/\.xlsx?/i,icon:"//img.alicdn.com/tfs/TB1any1r1OSBuNjy0FdXXbDnVXa-200-200.png"},{ext:/\.psd?/i,icon:"//img.alicdn.com/tfs/TB1_nu1r1OSBuNjy0FdXXbDnVXa-200-200.png"},{ext:/\.(wav|aif|aiff|au|mp1|mp2|mp3|ra|rm|ram|mid|rmi)/i,icon:"//img.alicdn.com/tfs/TB1jPvwr49YBuNjy0FfXXXIsVXa-200-200.png"},{ext:/\.(avi|wmv|mpg|mpeg|vob|dat|3gp|mp4|mkv|rm|rmvb|mov|flv)/i,icon:"//img.alicdn.com/tfs/TB1FrT5r9BYBeNjy0FeXXbnmFXa-200-200.png"},{ext:/\.(zip|rar|arj|z|gz|iso|jar|ace|tar|uue|dmg|pkg|lzh|cab)/i,icon:"//img.alicdn.com/tfs/TB10jmfr29TBuNjy0FcXXbeiFXa-200-200.png"},{ext:/\..+/i,icon:"//img.alicdn.com/tfs/TB10.R4r3mTBuNjy1XbXXaMrVXa-200-200.png"}],J=m()(t=>c.a.createElement("div",null,c.a.createElement(d.Icon,{type:t.loading?"loading":"plus"}),c.a.createElement("div",{className:"ant-upload-text"},"上传")))``,Z=(t,e)=>e&&Object(x.k)(e.include)?e.include.some(e=>t.test(e)):!e||!Object(x.k)(e.exclude)||!e.exclude.some(e=>t.test(e)),tt=(t,e)=>{for(let n=0;n<Q.length;n++)if(Q[n].ext.test(t)&&Z(Q[n].ext,e))return Q[n].icon||t;return t},et=t=>{let e=Object(x.k)(t)?[...t]:"object"==typeof t?{...t}:t;return Object(x.k)(e)&&(e=e.map(t=>({...t,uid:t.uid||Math.random().toFixed(16).slice(2,10)}))),e};Object(u.registerFormField)("upload",Object(u.connect)({getProps:E})((K=L=class extends c.a.Component{constructor(t){super(t),s()(this,"onRemoveHandler",t=>{const{value:e}=this.state,n=[];e.forEach(e=>{e.uid!==t.uid&&n.push(e)}),this.props.onChange(n)}),s()(this,"onChangeHandler",({fileList:t,file:e})=>{const{onChange:n}=this.props;(t=Object(x.x)(t)).every(t=>"done"===t.status||t.imgURL||t.downloadURL)&&t.length?(t=(t=>t&&t.length?t.map(t=>({uid:t.uid,status:t.status,name:t.name,url:t.downloadURL||t.imgURL||t.url,...t.response,thumbUrl:tt(t.imgURL||t.downloadURL||t.url,{exclude:[".png",".jpg",".jpeg",".gif"]})})):[])(t),this.setState({value:t},()=>{n(t.length>0?t:void 0)})):this.setState({value:t})}),this.state={value:et(Object(x.x)(t.value))}}componentDidUpdate(t){this.props.value&&!Object(x.n)(this.props.value,t.value)&&this.setState({value:et(this.props.value)})}render(){const{listType:t,locale:e,onChange:n,value:r,...o}=this.props;return t.indexOf("card")>-1?c.a.createElement(d.Upload,i()({},o,{fileList:this.state.value,onChange:this.onChangeHandler,onRemove:this.onRemoveHandler,listType:"picture-card"}),c.a.createElement(J,null)):t.indexOf("dragger")>-1?c.a.createElement(G,i()({},o,{fileList:this.state.value,onChange:this.onChangeHandler,onRemove:this.onRemoveHandler,listType:t.indexOf("image")>-1?"image":"text"}),c.a.createElement("p",{className:"ant-upload-drag-icon"},c.a.createElement(d.Icon,{type:"inbox"})),c.a.createElement("p",{className:"ant-upload-text"},"拖拽上传")):c.a.createElement(d.Upload,i()({},o,{fileList:this.state.value,onChange:this.onChangeHandler,onRemove:this.onRemoveHandler,listType:t}),c.a.createElement(d.Button,{style:{margin:"0 0 10px"}},c.a.createElement(d.Icon,{type:"upload"}),e&&e.uploadText||"上传文件"))}},s()(L,"defaultProps",{action:"https://www.easy-mock.com/mock/5b713974309d0d7d107a74a3/alifd/upload",listType:"text",multiple:!0,className:"antd-uploader"}),K)));const{Group:nt}=d.Checkbox;Object(u.registerFormField)("checkbox",Object(u.connect)({getProps:E,getComponent:F})(C(nt,"options")));const{Group:rt}=d.Radio;Object(u.registerFormField)("radio",Object(u.connect)({getProps:E,getComponent:F})(C(rt,"options"))),Object(u.registerFormField)("rating",Object(u.connect)({getProps:E})(d.Rate)),Object(u.registerFormField)("transfer",Object(u.connect)({getProps:E})(d.Transfer));const it=m.a.div.attrs({className:"cricle-btn"})` ${t=>t.hasText?"":"width:30px;\n height:30px;"} margin-right:10px; border-radius: ${t=>t.hasText?"none":"100px"}; border: ${t=>t.hasText?"none":"1px solid #eee"}; margin-bottom:20px; cursor:pointer; display: flex; align-items: center; justify-content: center; ${t=>t.hasText?"":"&:hover{\n background:#f7f4f4;\n }"} .op-name{ margin-left:3px; } } `,ot=m.a.div.attrs({className:"ant-btn-text"})` display: inline-block; height:20px; line-height: 20px; cursor: pointer; .op-name { margin-left: 4px; } ${t=>t.inline&&f.css` display: inline-block; width: auto; `} `,st=Object(u.createArrayField)({CircleButton:it,TextButton:ot,AddIcon:()=>c.a.createElement(d.Icon,{type:"plus"}),RemoveIcon:()=>c.a.createElement(d.Icon,{type:"delete"}),MoveDownIcon:()=>c.a.createElement(d.Icon,{type:"down"}),MoveUpIcon:()=>c.a.createElement(d.Icon,{type:"up"})});Object(u.registerFormField)("array",m()(class extends st{render(){const{className:t,name:e,schema:n,value:r,renderField:i}=this.props,o=n["x-props"]&&n["x-props"].style||{};return c.a.createElement("div",{className:t,style:o,onClick:this.onClearErrorHandler()},r.map((t,n)=>c.a.createElement("div",{className:"array-item",key:`${e}.${n}`},c.a.createElement("div",{className:"array-index"},c.a.createElement("span",null,n+1)),c.a.createElement("div",{className:"array-item-wrapper"},i(n)),c.a.createElement("div",{className:"array-item-operator"},this.renderRemove(n,t),this.renderMoveDown(n,t),this.renderMoveUp(n,t),this.renderExtraOperations(n)))),this.renderEmpty(),r.length>0&&this.renderAddition())}})` border: 1px solid #eee; min-width: 400px; .array-item { padding: 20px; padding-bottom: 0; padding-top: 30px; border-bottom: 1px solid #eee; position: relative; &:nth-child(even) { background: #fafafa; } .array-index { position: absolute; top: 0; left: 0; display: block; span { position: absolute; color: rgb(255, 255, 255); z-index: 1; font-size: 12px; top: 3px; left: 3px; line-height: initial; } &::after { content: ''; display: block; border-top: 20px solid transparent; border-left: 20px solid transparent; border-bottom: 20px solid transparent; border-right: 20px solid #888; transform: rotate(45deg); position: absolute; z-index: 0; top: -20px; left: -20px; } } .array-item-operator { display: flex; border-top: 1px solid #eee; padding-top: 20px; } } .array-empty-wrapper { display: flex; align-items: center; justify-content: center; cursor: pointer; &.disabled { cursor: default; } .array-empty { display: flex; flex-direction: column; justify-content: center; align-items: center; margin: 20px; img { display: block; height: 80px; } .ant-btn-text { color: #999; i { margin-right: 3px; } } } } .array-item-wrapper { margin: 0 -20px; } .array-item-addition { padding: 10px 20px; line-height: normal !important; background: #fbfbfb; .ant-btn-text { color: #888; i { margin-right: 3px; } } } `);const at=m()(class extends a.Component{renderCell({record:t,col:e,rowIndex:n,colIndex:r}){return c.a.createElement("div",{className:"ant-table-cell-wrapper"},Object(x.o)(e.cell)?e.cell(t?t[e.dataIndex]:void 0,n,t):t?t[e.dataIndex]:void 0)}renderTable(t,e){return c.a.createElement("div",{className:"ant-table-body"},c.a.createElement("table",null,c.a.createElement("colgroup",null,t.map((t,e)=>c.a.createElement("col",{key:e,style:{width:t.width}}))),c.a.createElement("thead",null,c.a.createElement("tr",null,t.map((t,e)=>c.a.createElement("th",{key:e,className:"ant-table-header-node"},c.a.createElement("div",{className:"ant-table-cell-wrapper"},t.title))))),c.a.createElement("tbody",null,e.map((e,n)=>c.a.createElement("tr",{key:n,className:"ant-table-row"},t.map((t,r)=>c.a.createElement("td",{key:r,className:"ant-table-cell"},this.renderCell({record:e,col:t,rowIndex:n,colIndex:r}))))),this.renderPlacehodler(e,t))))}renderPlacehodler(t,e){if(0===t.length)return c.a.createElement("tr",{className:"ant-table-row"},c.a.createElement("td",{className:"ant-table-cell",colSpan:e.length},c.a.createElement("div",{className:"ant-table-empty",style:{padding:10}},c.a.createElement("img",{src:"//img.alicdn.com/tfs/TB1cVncKAzoK1RjSZFlXXai4VXa-184-152.svg",style:{height:60}}))))}getColumns(t){const e=[];return c.a.Children.forEach(t,t=>{c.a.isValidElement(t)&&(t.type!==ct&&"@schema-table-column"!==t.type.displayName||e.push(t.props))}),e}render(){const t=this.getColumns(this.props.children),e=Object(x.x)(this.props.dataSource);return c.a.createElement("div",{className:this.props.className},c.a.createElement("div",{className:"ant-table zebra"},c.a.createElement("div",{className:"ant-table-inner"},this.renderTable(t,e))))}})` .ant-table { position: relative; } .ant-table, .ant-table *, .ant-table :after, .ant-table :before { -webkit-box-sizing: border-box; box-sizing: border-box; } .ant-table table { border-collapse: collapse; border-spacing: 0; width: 100%; background: #fff; display: table !important; margin: 0 !important; } .ant-table table tr:first-child td { border-top-width: 0; } .ant-table th { padding: 0; background: #ebecf0; color: #333; text-align: left; font-weight: 400; min-width: 200px; border: 1px solid #dcdee3; } .ant-table th .ant-table-cell-wrapper { padding: 12px 16px; overflow: hidden; text-overflow: ellipsis; word-break: break-all; } .ant-table td { padding: 0; border: 1px solid #dcdee3; } .ant-table td .ant-table-cell-wrapper { padding: 12px 16px; overflow: hidden; text-overflow: ellipsis; word-break: break-all; display: flex; } .ant-table.zebra tr:nth-child(odd) td { background: #fff; } .ant-table.zebra tr:nth-child(2n) td { background: #f7f8fa; } .ant-table-empty { color: #a0a2ad; padding: 32px 0; text-align: center; } .ant-table-row { -webkit-transition: all 0.3s ease; transition: all 0.3s ease; background: #fff; color: #333; border: none !important; } .ant-table-row.hidden { display: none; } .ant-table-row.hovered, .ant-table-row.selected { background: #f2f3f7; color: #333; } .ant-table-body, .ant-table-header { overflow: auto; font-size: 12px; } .ant-table-body { font-size: 12px; } `;class ct extends a.Component{render(){return this.props.children}}var ut;s()(ct,"displayName","@schema-table-column"),Object(u.registerFormField)("table",m()(class extends st{createFilter(t,e){const{schema:n}=this.props,r=n["x-props"]&&n["x-props"].columnFilter;return(n,i)=>Object(x.o)(r)?r(t,e)?Object(x.o)(n)?n():n:Object(x.o)(i)?i():i:n()}render(){const{value:t,schema:e,locale:n,className:r,renderField:o,getOrderProperties:s}=this.props,a=e["x-props"]&&e["x-props"].style,u=this.createFilter("addition",e);return c.a.createElement("div",{className:r,style:a,onClick:this.onClearErrorHandler()},c.a.createElement("div",null,c.a.createElement(at,{dataSource:t},s(e.items).reduce((t,{key:e,schema:n})=>{return this.createFilter(e,n)(()=>t.concat(c.a.createElement(ct,i()({},n,{key:e,title:n.title,dataIndex:e,cell:(t,n)=>o([n,e])}))),()=>t)},[]),u(()=>c.a.createElement(ct,{key:"operations",title:n.operations,dataIndex:"operations",width:180,cell:(t,e)=>c.a.createElement("div",{className:"array-item-operator"},this.renderRemove(e,t),this.renderMoveDown(e,t),this.renderMoveUp(e,t),this.renderExtraOperations(e))}))),this.renderAddition()))}})` display: inline-block; .array-item-addition { line-height: normal !important; padding: 10px; background: #fbfbfb; border-left: 1px solid #dcdee3; border-right: 1px solid #dcdee3; border-bottom: 1px solid #dcdee3; .ant-btn-text { color: #888; i { margin-right: 3px; } } } .ant-table-cell-wrapper > .ant-form-item { margin-bottom: 0; } .array-item-operator { display: flex; } `);var lt=function(t){return t>=48&&t<=57},ht=function(t){return t>=97&&t<=122},dt=function(t){return t>=65&&t<=90},pt=function(t){return!(ht(t)||dt(t)||lt(t))},ft=function(t){return ht(t)||dt(t)};const mt=t=>{if(!t)return 0;let e=0,n=0,r=0,i=0,o=0,s=0,a=0,c=0,u=0;const l=()=>e+n+r+i;for(var h=0;h<t.length;h++){var d=t.charCodeAt(h);lt(d)?(e++,0!==h&&h!==t.length-1&&o++,h>0&&lt(t.charCodeAt(h-1))&&c++):ht(d)?(n++,h>0&&ht(t.charCodeAt(h-1))&&c++):dt(d)?(r++,h>0&&dt(t.charCodeAt(h-1))&&c++):(i++,0!==h&&h!==t.length-1&&o++);for(var p=!1,f=0;f<t.length;f++)t[h]===t[f]&&h!==f&&(p=!0,a+=Math.abs(t.length/(f-h)));if(p){s++;var m=t.length-s;a=m?Math.ceil(a/m):Math.ceil(a)}if(h>1){var b=t.charCodeAt(h-1),y=t.charCodeAt(h-2);if(ft(d)){if(ft(b)&&ft(y)){var v=t.toLowerCase(),g=v.charCodeAt(h),x=v.charCodeAt(h-1);g-x==x-v.charCodeAt(h-2)&&1===Math.abs(g-x)&&u++}}else lt(d)?lt(b)&&lt(y)&&d-b==b-y&&1===Math.abs(d-b)&&u++:pt(b)&&pt(y)&&d-b==b-y&&1===Math.abs(d-b)&&u++}}let w=0,S=l();return w+=4*S,n>0&&(w+=2*(S-n)),r>0&&(w+=2*(S-r)),e!==S&&(w+=4*e),w+=6*i,w+=2*o,w+=2*(()=>{var t=e>0?1:0;return t+=n>0?1:0,t+=r>0?1:0,(t+=i>0?1:0)>2&&l()>=8?t+1:0})(),S===n+r&&(w-=S),S===e&&(w-=e),w-=a,w-=2*c,(w=(w=(w-=3*u)<0?0:w)>100?100:w)>=80?100:w>=60?80:w>=40?60:w>=20?40:20},bt=m()((ut=class extends c.a.Component{constructor(...t){super(...t),s()(this,"state",{value:this.props.value||this.props.defaultValue,strength:0,eye:!1}),s()(this,"onChangeHandler",t=>{const e=t.target.value;this.setState({value:e,strength:mt(e)},()=>{this.props.onChange&&this.props.onChange(e)})})}componentDidUpdate(t,e){t.value!==this.props.value&&this.props.value!==this.state.value&&this.setState({value:this.props.value,strength:mt(this.props.value)})}renderStrength(){const{strength:t}=this.state;return c.a.createElement("div",{className:"password-strength-wrapper"},c.a.createElement("div",{className:"div-1 div"}),c.a.createElement("div",{className:"div-2 div"}),c.a.createElement("div",{className:"div-3 div"}),c.a.createElement("div",{className:"div-4 div"}),c.a.createElement("div",{className:"password-strength-bar",style:{clipPath:`polygon(0 0,${t}% 0,${t}% 100%,0 100%)`}}))}switchEye(){return()=>{this.setState({eye:!this.state.eye})}}renderEye(){return this.state.eye?c.a.createElement("img",{className:"eye",onClick:this.switchEye(),src:"//img.alicdn.com/tfs/TB1xiXlsVzqK1RjSZFvXXcB7VXa-200-200.svg"}):c.a.createElement("img",{className:"eye",onClick:this.switchEye(),src:"//img.alicdn.com/tfs/TB1wyXlsVzqK1RjSZFvXXcB7VXa-200-200.svg"})}render(){const{className:t,checkStrength:e,value:n,onChange:r,htmlType:o,innerAfter:s,...a}=this.props;return c.a.createElement("div",{className:t},c.a.createElement(d.Input,i()({type:this.state.eye?"text":"password",className:`input-${this.state.eye?"text":"password"}`,value:this.state.value,onChange:this.onChangeHandler,suffix:this.renderEye()},a)),e&&this.renderStrength())}},ut))` .ant-input-prefix, .ant-input-suffix { z-index: 10; right:20px !important; .eye { position: absolute; max-width: initial; width: 20px; height: 20px; top: 50%; left: -5px; transform: translate(0, -50%); opacity: 0.3; cursor: pointer; transition: all 0.15s ease-in-out; &:hover { opacity: 0.6; } } } .ant-input { width: 100%; position: relative; &.input-password input { font-size: 16px; letter-spacing: 2px; } input { padding-right: 25px; } } .password-strength-wrapper { background: #e0e0e0; margin-bottom: 3px; position: relative; .div { position: absolute; z-index: 1; height: 8px; top: 0; background: #fff; width: 1px; transform: translate(-50%, 0); } .div-1 { left: 20%; } .div-2 { left: 40%; } .div-3 { left: 60%; } .div-4 { left: 80%; } .password-strength-bar { position: relative; background-image: -webkit-linear-gradient(left, #ff5500, #ff9300); transition: all 0.35s ease-in-out; height: 8px; width: 100%; margin-top: 5px; } } `;Object(u.registerFormField)("password",Object(u.connect)()(bt));const yt=m()(class extends st{renderOperations(t,e){return c.a.createElement(a.Fragment,null,this.renderRemove(e,t),this.renderMoveDown(e,t),this.renderMoveUp(e,t),this.renderExtraOperations(e))}renderEmpty(t){return c.a.createElement(d.Card,{title:t,className:"card-list"},super.renderEmpty())}render(){const{value:t,className:e,schema:n,renderField:r}=this.props,{title:o,renderAddition:s,renderRemove:a,renderEmpty:u,renderMoveDown:l,renderMoveUp:h,renderOperations:p,...f}=this.getProps()||{};return c.a.createElement("div",{className:e,onClick:this.onClearErrorHandler()},Object(x.x)(t).map((t,e)=>c.a.createElement(d.Card,i()({},f,{title:c.a.createElement("span",null,e+1,". ",o||n.title),className:"card-list",key:e,extra:this.renderOperations(t,e)}),r(e))),0===t.length&&this.renderEmpty(o),c.a.createElement("div",{className:"addition-wrapper"},t.length>0&&this.renderAddition()))}})` .ant-card-body { padding-top: 30px; padding-bottom: 0 !important; } .ant-card-head-main { display: flex; justify-content: space-between; align-items: center; } .ant-card { display: block; margin-bottom: 0px; background: #fff; .array-empty-wrapper { display: flex; justify-content: center; cursor: pointer; margin-bottom: 0px; &.disabled { cursor: default; } .array-empty { display: flex; flex-direction: column; margin-bottom: 20px; align-items: center; img { margin-bottom: 16px; height: 85px; } .next-btn-text { color: #888; } .next-icon:before { width: 16px !important; font-size: 16px !important; margin-right: 5px; } } } .next-card { box-shadow: none; } .card-list { box-shadow: none; border: 1px solid #eee; } .array-item-addition { box-shadow: none; border: 1px solid #eee; transition: all 0.35s ease-in-out; &:hover { border: 1px solid #ccc; } } } .ant-card.card-list { margin-top: 20px; } .addition-wrapper .array-item-addition { margin-top: 20px; margin-bottom: 3px; } .cricle-btn { margin-bottom: 0; } .ant-card-extra { display: flex; } .array-item-addition { background: #fff; display: flex; cursor: pointer; padding: 10px 0; justify-content: center; box-shadow: 1px 1px 4px 0 rgba(0, 0, 0, 0.1); .next-btn-text { color: #888; } .next-icon:before { width: 16px !important; font-size: 16px !important; margin-right: 5px; } } .card-list:first-child { margin-top: 0 !important; } `;Object(u.registerFormField)("cards",yt);class vt extends a.Component{render(){const{prefix:t,pure:e,wrap:n,fixed:r,gutter:o,fixedWidth:s,align:u,justify:l,hidden:d,className:p,component:f,children:m,...b}=this.props;let y;!0===d?y={[`${t}row-hidden`]:!0}:"string"==typeof d?y={[`${t}row-${d}-hidden`]:!!d}:Array.isArray(d)&&(y=d.reduce((e,n)=>(e[`${t}row-${n}-hidden`]=!!n,e),{}));const v=h()({[`${t}row`]:!0,[`${t}row-wrap`]:n,[`${t}row-fixed`]:r,[`${t}row-fixed-${s}`]:!!s,[`${t}row-justify-${l}`]:!!l,[`${t}row-align-${u}`]:!!u,...y,[p]:!!p});let g=Object(x.x)(m);const w=parseInt(o,10);if(0!==w){const t=`${w/2}px`;b.style={marginLeft:`-${t}`,marginRight:`-${t}`,...b.style||{}},g=a.Children.map(m,(e,n)=>{if(e&&e.type&&"function"==typeof e.type&&e.type.isNextCol){return Object(a.cloneElement)(e,{style:{paddingLeft:t,paddingRight:t,...e.style||{}}})}return e})}return c.a.createElement(f,i()({role:"row",className:v},b),g)}}s()(vt,"defaultProps",{prefix:"ant-",pure:!1,fixed:!1,gutter:0,wrap:!1,component:"div"});const gt=["xxs","xs","s","m","l","xl"];class xt extends a.Component{render(){const{prefix:t,pure:e,span:n,offset:r,fixedSpan:o,fixedOffset:s,hidden:a,align:u,xxs:l,xs:d,s:p,m:f,l:m,xl:b,component:y,className:v,children:g,...x}=this.props,w=gt.reduce((e,n)=>{let r={};return"object"==typeof this.props[n]?r=this.props[n]:r.span=this.props[n],e[`${t}col-${n}-${r.span}`]=!!r.span,e[`${t}col-${n}-offset-${r.offset}`]=!!r.offset,e},{});let S;!0===a?S={[`${t}col-hidden`]:!0}:"string"==typeof a?S={[`${t}col-${a}-hidden`]:!!a}:Array.isArray(a)&&(S=a.reduce((e,n)=>(e[`${t}col-${n}-hidden`]=!!n,e),{}));const j=h()({[`${t}col`]:!0,[`${t}col-${n}`]:!!n,[`${t}col-fixed-${o}`]:!!o,[`${t}col-offset-${r}`]:!!r,[`${t}col-offset-fixed-${s}`]:!!s,[`${t}col-${u}`]:!!u,...w,...S,[v]:v});return c.a.createElement(y,i()({role:"gridcell",className:j},x),g)}}s()(xt,"isNextCol",!0),s()(xt,"defaultProps",{prefix:"ant-",pure:!1,component:"div"}),vt.__docgenInfo={description:"",methods:[],displayName:"Row",props:{prefix:{defaultValue:{value:"'ant-'",computed:!1},required:!1},pure:{defaultValue:{value:"false",computed:!1},required:!1},fixed:{defaultValue:{value:"false",computed:!1},required:!1},gutter:{defaultValue:{value:"0",computed:!1},required:!1},wrap:{defaultValue:{value:"false",computed:!1},required:!1},component:{defaultValue:{value:"'div'",computed:!1},required:!1}}},xt.__docgenInfo={description:"",methods:[],displayName:"Col",props:{prefix:{defaultValue:{value:"'ant-'",computed:!1},required:!1},pure:{defaultValue:{value:"false",computed:!1},required:!1},component:{defaultValue:{value:"'div'",computed:!1},required:!1}}};var wt,St,jt=n(173),Ot=n.n(jt);const _t=m()((St=wt=class extends a.Component{renderChildren(){const{children:t,itemStyle:e,offset:n,span:r}=this.props;return c.a.createElement("div",{className:"button-group"},c.a.createElement(vt,null,c.a.createElement(xt,{span:r},c.a.createElement(xt,{offset:n,className:"inline"},c.a.createElement("div",{className:"inline-view",style:e},t)))))}getStickyBoundaryHandler(t){return()=>(this.formNode=this.formNode||y.a.findDOMNode(t.current),!this.formNode||((t,{offset:e=0,threshold:n=0}={})=>{const{top:r,right:i,bottom:o,left:s,width:a,height:c}=t,u=o,l=window.innerWidth-s,h=window.innerHeight-r,d=i,p=n*a,f=n*c;return u>=(e.top||e+f)&&l>=(e.right||e+p)&&h>=(e.bottom||e+f)&&d>=(e.left||e+p)})(this.formNode.getBoundingClientRect()))}render(){const{sticky:t,style:e,className:n}=this.props,r=c.a.createElement(I,null,({inline:t}={})=>c.a.createElement("div",{className:h()(n,{"is-inline":!!t}),style:e},this.renderChildren()));return t?c.a.createElement("div",null,c.a.createElement(I,null,({inline:t,FormRef:i}={})=>{if(i)return c.a.createElement(Ot.a,{edge:"bottom",triggerDistance:this.props.triggerDistance,offsetDistance:this.props.offsetDistance,zIndex:this.props.zIndex,getStickyBoundary:this.getStickyBoundaryHandler(i),style:{borderTop:"1px solid #eee",background:e&&e.background||"#fff",padding:e&&e.padding||"8px 0"}},c.a.createElement("div",{className:n,style:e},r))})):r}},s()(wt,"defaultProps",{span:24}),St))` ${t=>t.align?`display:flex;justify-content: ${(t=>"start"===t||"end"===t?t:"left"===t||"top"===t?"flex-start":"right"===t||"bottom"===t?"flex-end":t)(t.align)}`:""} &.is-inline { display: inline-block; flex-grow: 3; } .button-group { .inline { display: inline-block; .inline-view { & > * { margin-right: 10px; margin-left: 0px; display: inline-block; } & > *:last-child { margin-right: 0 !important; } } } } `,Et=({showLoading:t,...e})=>c.a.createElement(u.FormConsumer,null,({status:n,schema:r})=>c.a.createElement(d.Button,i()({type:"primary",htmlType:"submit"},e,{loading:t?"submitting"===n:void 0}),e.children||"提交")),Ft=t=>c.a.createElement(u.FormConsumer,null,({status:e,reset:n})=>c.a.createElement(d.Button,i()({},t,{onClick:n}),t.children||"重置"));var Ct,Nt,Vt,kt;Et.__docgenInfo={description:"",methods:[],displayName:"Submit"},Ft.__docgenInfo={description:"",methods:[],displayName:"Reset"};const Tt=(t,e=0)=>t?"object"==typeof t?t:{span:t}:e,It=Object(u.createVirtualBox)("layout",({children:t,...e})=>c.a.createElement(I,null,n=>{let r={...n,...e},i=r.inline||r.className||r.style?c.a.createElement("div",{className:h()(r.className,{"ant-form ant-inline":!!r.inline}),style:r.style},t):t;return c.a.createElement(T,{value:r},i)})),At=Object(u.createVirtualBox)("grid",class extends a.Component{renderFormItem(t){const{title:e,description:n,name:r,help:i,extra:o,...s}=this.props;return c.a.createElement(I,{},({labelAlign:o,labelTextAlign:a,labelCol:u,wrapperCol:l,size:h,autoAddColon:d})=>c.a.createElement(q,{labelAlign:o,labelTextAlign:a,labelCol:u,wrapperCol:l,autoAddColon:d,size:h,...s,label:e,noMinHeight:!0,id:r,extra:n,help:i},t))}renderGrid(){let{children:t,cols:e,title:n,description:r,help:o,extra:s,...a}=this.props;t=Object(x.x)(t),e=Object(x.x)(e).map(t=>Tt(t));const u=t.length;if(e.length<u){let t=u-e.length,n=24-e.reduce((t,e)=>t+Number(e.span?e.span:0)+Number(e.offset?e.offset:0),0);for(let r=0;r<t;r++)e.push(parseInt(n/t))}return e=Object(x.x)(e).map(t=>Tt(t)),c.a.createElement(d.Row,a,t.reduce((t,n,r)=>n?t.concat(c.a.createElement(d.Col,i()({key:r},e[r]),n)):t,[]))}render(){const{title:t}=this.props;return t?this.renderFormItem(this.renderGrid()):this.renderGrid()}}),Pt=Object(u.createVirtualBox)("card",m()((Nt=Ct=class extends a.Component{render(){const{children:t,className:e,...n}=this.props;return c.a.createElement(d.Card,i()({className:e},n),t)}},s()(Ct,"defaultProps",{}),Nt))` margin-bottom: 30px; .ant-card-body { padding-top: 30px; padding-bottom: 0 !important; } &.ant-card { display: block; margin-bottom: 30px; } `),qt=Object(u.createVirtualBox)("block",m()((kt=Vt=class extends a.Component{render(){const{children:t,className:e,...n}=this.props;return c.a.createElement(d.Card,i()({className:e},n),t)}},s()(Vt,"defaultProps",{}),kt))` margin-bottom: 0px; .ant-card-body { padding-top: 20px; padding-bottom: 0 !important; } &.ant-card { border: none; padding: 0 15px; padding-bottom: 15px; display: block; box-shadow: none; } .ant-card-head { padding: 0 !important; min-height: 24px; font-weight: normal; } .ant-card-head-title { padding: 0; } `);At.__docgenInfo={description:"",methods:[{name:"renderFormItem",docblock:null,modifiers:[],params:[{name:"children",optional:!1,type:null}],returns:null},{name:"renderGrid",docblock:null,modifiers:[],params:[],returns:null}]},n.d(e,"SchemaForm",function(){return u.SchemaForm}),n.d(e,"Field",function(){return u.Field}),n.d(e,"setValidationLocale",function(){return u.setValidationLocale}),n.d(e,"setValidationLanguage",function(){return u.setValidationLanguage}),n.d(e,"createFormActions",function(){return u.createFormActions}),n.d(e,"createAsyncFormActions",function(){return u.createAsyncFormActions}),n.d(e,"registerFormField",function(){return u.registerFormField}),n.d(e,"registerFormFields",function(){return u.registerFormFields}),n.d(e,"registerFormWrapper",function(){return u.registerFormWrapper}),n.d(e,"registerFieldMiddleware",function(){return u.registerFieldMiddleware}),n.d(e,"registerFormFieldPropsTransformer",function(){return u.registerFormFieldPropsTransformer}),n.d(e,"caculateSchemaInitialValues",function(){return u.caculateSchemaInitialValues}),n.d(e,"FormPath",function(){return u.FormPath}),n.d(e,"createVirtualBox",function(){return u.createVirtualBox}),n.d(e,"FormSlot",function(){return u.FormSlot}),n.d(e,"connect",function(){return u.connect}),n.d(e,"FormBridge",function(){return u.FormBridge}),n.d(e,"FormProvider",function(){return u.FormProvider}),n.d(e,"useForm",function(){return u.useForm}),n.d(e,"FormConsumer",function(){return u.FormConsumer}),n.d(e,"createArrayField",function(){return u.createArrayField}),n.d(e,"FormButtonGroup",function(){return _t}),n.d(e,"Submit",function(){return Et}),n.d(e,"Reset",function(){return Ft}),n.d(e,"FormLayout",function(){return It}),n.d(e,"FormItemGrid",function(){return At}),n.d(e,"FormCard",function(){return Pt}),n.d(e,"FormBlock",function(){return qt}),n.d(e,"mapStyledProps",function(){return E}),n.d(e,"mapTextComponent",function(){return F});e.default=u.SchemaForm},151:function(t,e,n){"use strict";n.r(e); /*! ***************************************************************************** Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT. See the Apache Version 2.0 License for specific language governing permissions and limitations under the License. ***************************************************************************** */ var r=function(t,e){return(r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)e.hasOwnProperty(n)&&(t[n]=e[n])})(t,e)};function i(t,e){function n(){this.constructor=t}r(t,e),t.prototype=null===e?Object.create(e):(n.prototype=e.prototype,new n)}function o(t){return"function"==typeof t}var s=!1,a={Promise:void 0,set useDeprecatedSynchronousErrorHandling(t){t&&(new Error).stack;s=t},get useDeprecatedSynchronousErrorHandling(){return s}};function c(t){setTimeout(function(){throw t},0)}var u={closed:!0,next:function(t){},error:function(t){if(a.useDeprecatedSynchronousErrorHandling)throw t;c(t)},complete:function(){}},l=Array.isArray||function(t){return t&&"number"==typeof t.length};function h(t){return null!==t&&"object"==typeof t}function d(t){return Error.call(this),this.message=t?t.length+" errors occurred during unsubscription:\n"+t.map(function(t,e){return e+1+") "+t.toString()}).join("\n "):"",this.name="UnsubscriptionError",this.errors=t,this}d.prototype=Object.create(Error.prototype);var p=d,f=function(){function t(t){this.closed=!1,this._parentOrParents=null,this._subscriptions=null,t&&(this._unsubscribe=t)}var e;return t.prototype.unsubscribe=function(){var e;if(!this.closed){var n=this._parentOrParents,r=this._unsubscribe,i=this._subscriptions;if(this.closed=!0,this._parentOrParents=null,this._subscriptions=null,n instanceof t)n.remove(this);else if(null!==n)for(var s=0;s<n.length;++s){n[s].remove(this)}if(o(r))try{r.call(this)}catch(t){e=t instanceof p?m(t.errors):[t]}if(l(i)){s=-1;for(var a=i.length;++s<a;){var c=i[s];if(h(c))try{c.unsubscribe()}catch(t){e=e||[],t instanceof p?e=e.concat(m(t.errors)):e.push(t)}}}if(e)throw new p(e)}},t.prototype.add=function(e){var n=e;switch(typeof e){case"function":n=new t(e);case"object":if(n===this||n.closed||"function"!=typeof n.unsubscribe)return n;if(this.closed)return n.unsubscribe(),n;if(!(n instanceof t)){var r=n;(n=new t)._subscriptions=[r]}break;default:if(!e)return t.EMPTY;throw new Error("unrecognized teardown "+e+" added to Subscription.")}var i=n._parentOrParents;if(null===i)n._parentOrParents=this;else if(i instanceof t){if(i===this)return n;n._parentOrParents=[i,this]}else{if(-1!==i.indexOf(this))return n;i.push(this)}var o=this._subscriptions;return null===o?this._subscriptions=[n]:o.push(n),n},t.prototype.remove=function(t){var e=this._subscriptions;if(e){var n=e.indexOf(t);-1!==n&&e.splice(n,1)}},t.EMPTY=((e=new t).closed=!0,e),t}();function m(t){return t.reduce(function(t,e){return t.concat(e instanceof p?e.errors:e)},[])}var b="function"==typeof Symbol?Symbol("rxSubscriber"):"@@rxSubscriber_"+Math.random(),y=function(t){function e(n,r,i){var o=t.call(this)||this;switch(o.syncErrorValue=null,o.syncErrorThrown=!1,o.syncErrorThrowable=!1,o.isStopped=!1,arguments.length){case 0:o.destination=u;break;case 1:if(!n){o.destination=u;break}if("object"==typeof n){n instanceof e?(o.syncErrorThrowable=n.syncErrorThrowable,o.destination=n,n.add(o)):(o.syncErrorThrowable=!0,o.destination=new v(o,n));break}default:o.syncErrorThrowable=!0,o.destination=new v(o,n,r,i)}return o}return i(e,t),e.prototype[b]=function(){return this},e.create=function(t,n,r){var i=new e(t,n,r);return i.syncErrorThrowable=!1,i},e.prototype.next=function(t){this.isStopped||this._next(t)},e.prototype.error=function(t){this.isStopped||(this.isStopped=!0,this._error(t))},e.prototype.complete=function(){this.isStopped||(this.isStopped=!0,this._complete())},e.prototype.unsubscribe=function(){this.closed||(this.isStopped=!0,t.prototype.unsubscribe.call(this))},e.prototype._next=function(t){this.destination.next(t)},e.prototype._error=function(t){this.destination.error(t),this.unsubscribe()},e.prototype._complete=function(){this.destination.complete(),this.unsubscribe()},e.prototype._unsubscribeAndRecycle=function(){var t=this._parentOrParents;return this._parentOrParents=null,this.unsubscribe(),this.closed=!1,this.isStopped=!1,this._parentOrParents=t,this},e}(f),v=function(t){function e(e,n,r,i){var s,a=t.call(this)||this;a._parentSubscriber=e;var c=a;return o(n)?s=n:n&&(s=n.next,r=n.error,i=n.complete,n!==u&&(o((c=Object.create(n)).unsubscribe)&&a.add(c.unsubscribe.bind(c)),c.unsubscribe=a.unsubscribe.bind(a))),a._context=c,a._next=s,a._error=r,a._complete=i,a}return i(e,t),e.prototype.next=function(t){if(!this.isStopped&&this._next){var e=this._parentSubscriber;a.useDeprecatedSynchronousErrorHandling&&e.syncErrorThrowable?this.__tryOrSetError(e,this._next,t)&&this.unsubscribe():this.__tryOrUnsub(this._next,t)}},e.prototype.error=function(t){if(!this.isStopped){var e=this._parentSubscriber,n=a.useDeprecatedSynchronousErrorHandling;if(this._error)n&&e.syncErrorThrowable?(this.__tryOrSetError(e,this._error,t),this.unsubscribe()):(this.__tryOrUnsub(this._error,t),this.unsubscribe());else if(e.syncErrorThrowable)n?(e.syncErrorValue=t,e.syncErrorThrown=!0):c(t),this.unsubscribe();else{if(this.unsubscribe(),n)throw t;c(t)}}},e.prototype.complete=function(){var t=this;if(!this.isStopped){var e=this._parentSubscriber;if(this._complete){var n=function(){return t._complete.call(t._context)};a.useDeprecatedSynchronousErrorHandling&&e.syncErrorThrowable?(this.__tryOrSetError(e,n),this.unsubscribe()):(this.__tryOrUnsub(n),this.unsubscribe())}else this.unsubscribe()}},e.prototype.__tryOrUnsub=function(t,e){try{t.call(this._context,e)}catch(t){if(this.unsubscribe(),a.useDeprecatedSynchronousErrorHandling)throw t;c(t)}},e.prototype.__tryOrSetError=function(t,e,n){if(!a.useDeprecatedSynchronousErrorHandling)throw new Error("bad call");try{e.call(this._context,n)}catch(e){return a.useDeprecatedSynchronousErrorHandling?(t.syncErrorValue=e,t.syncErrorThrown=!0,!0):(c(e),!0)}return!1},e.prototype._unsubscribe=function(){var t=this._parentSubscriber;this._context=null,this._parentSubscriber=null,t.unsubscribe()},e}(y),g=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return i(e,t),e.prototype.notifyNext=function(t,e,n,r,i){this.destination.next(e)},e.prototype.notifyError=function(t,e){this.destination.error(t)},e.prototype.notifyComplete=function(t){this.destination.complete()},e}(y),x=function(t){function e(e,n,r){var i=t.call(this)||this;return i.parent=e,i.outerValue=n,i.outerIndex=r,i.index=0,i}return i(e,t),e.prototype._next=function(t){this.parent.notifyNext(this.outerValue,t,this.outerIndex,this.index++,this)},e.prototype._error=function(t){this.parent.notifyError(t,this),this.unsubscribe()},e.prototype._complete=function(){this.parent.notifyComplete(this),this.unsubscribe()},e}(y),w=function(t){return function(e){for(var n=0,r=t.length;n<r&&!e.closed;n++)e.next(t[n]);e.complete()}};function S(){return"function"==typeof Symbol&&Symbol.iterator?Symbol.iterator:"@@iterator"}var j=S(),O="function"==typeof Symbol&&Symbol.observable||"@@observable",_=function(t){return t&&"number"==typeof t.length&&"function"!=typeof t};function E(t){return!!t&&"function"!=typeof t.subscribe&&"function"==typeof t.then}var F=function(t){if(t&&"function"==typeof t[O])return r=t,function(t){var e=r[O]();if("function"!=typeof e.subscribe)throw new TypeError("Provided object does not correctly implement Symbol.observable");return e.subscribe(t)};if(_(t))return w(t);if(E(t))return n=t,function(t){return n.then(function(e){t.closed||(t.next(e),t.complete())},function(e){return t.error(e)}).then(null,c),t};if(t&&"function"==typeof t[j])return e=t,function(t){for(var n=e[j]();;){var r=n.next();if(r.done){t.complete();break}if(t.next(r.value),t.closed)break}return"function"==typeof n.return&&t.add(function(){n.return&&n.return()}),t};var e,n,r,i=h(t)?"an invalid object":"'"+t+"'";throw new TypeError("You provided "+i+" where a stream was expected. You can provide an Observable, Promise, Array, or Iterable.")};function C(){}function N(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];return V(t)}function V(t){return t?1===t.length?t[0]:function(e){return t.reduce(function(t,e){return e(t)},e)}:C}var k=function(){function t(t){this._isScalar=!1,t&&(this._subscribe=t)}return t.prototype.lift=function(e){var n=new t;return n.source=this,n.operator=e,n},t.prototype.subscribe=function(t,e,n){var r=this.operator,i=function(t,e,n){if(t){if(t instanceof y)return t;if(t[b])return t[b]()}return t||e||n?new y(t,e,n):new y(u)}(t,e,n);if(r?i.add(r.call(i,this.source)):i.add(this.source||a.useDeprecatedSynchronousErrorHandling&&!i.syncErrorThrowable?this._subscribe(i):this._trySubscribe(i)),a.useDeprecatedSynchronousErrorHandling&&i.syncErrorThrowable&&(i.syncErrorThrowable=!1,i.syncErrorThrown))throw i.syncErrorValue;return i},t.prototype._trySubscribe=function(t){try{return this._subscribe(t)}catch(e){a.useDeprecatedSynchronousErrorHandling&&(t.syncErrorThrown=!0,t.syncErrorValue=e),!function(t){for(;t;){var e=t,n=e.closed,r=e.destination,i=e.isStopped;if(n||i)return!1;t=r&&r instanceof y?r:null}return!0}(t)?console.warn(e):t.error(e)}},t.prototype.forEach=function(t,e){var n=this;return new(e=T(e))(function(e,r){var i;i=n.subscribe(function(e){try{t(e)}catch(t){r(t),i&&i.unsubscribe()}},r,e)})},t.prototype._subscribe=function(t){var e=this.source;return e&&e.subscribe(t)},t.prototype[O]=function(){return this},t.prototype.pipe=function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];return 0===t.length?this:V(t)(this)},t.prototype.toPromise=function(t){var e=this;return new(t=T(t))(function(t,n){var r;e.subscribe(function(t){return r=t},function(t){return n(t)},function(){return t(r)})})},t.create=function(e){return new t(e)},t}();function T(t){if(t||(t=a.Promise||Promise),!t)throw new Error("no Promise impl found");return t}function I(t,e,n,r,i){if(void 0===i&&(i=new x(t,n,r)),!i.closed)return e instanceof k?e.subscribe(i):F(e)(i)}function A(t){return function(e){return e.lift(new P(t))}}var P=function(){function t(t){this.durationSelector=t}return t.prototype.call=function(t,e){return e.subscribe(new q(t,this.durationSelector))},t}(),q=function(t){function e(e,n){var r=t.call(this,e)||this;return r.durationSelector=n,r.hasValue=!1,r}return i(e,t),e.prototype._next=function(t){if(this.value=t,this.hasValue=!0,!this.throttled){var e=void 0;try{e=(0,this.durationSelector)(t)}catch(t){return this.destination.error(t)}var n=I(this,e);!n||n.closed?this.clearThrottle():this.add(this.throttled=n)}},e.prototype.clearThrottle=function(){var t=this.value,e=this.hasValue,n=this.throttled;n&&(this.remove(n),this.throttled=null,n.unsubscribe()),e&&(this.value=null,this.hasValue=!1,this.destination.next(t))},e.prototype.notifyNext=function(t,e,n,r){this.clearThrottle()},e.prototype.notifyComplete=function(){this.clearThrottle()},e}(g),z=function(t){function e(e,n){var r=t.call(this,e,n)||this;return r.scheduler=e,r.work=n,r.pending=!1,r}return i(e,t),e.prototype.schedule=function(t,e){if(void 0===e&&(e=0),this.closed)return this;this.state=t;var n=this.id,r=this.scheduler;return null!=n&&(this.id=this.recycleAsyncId(r,n,e)),this.pending=!0,this.delay=e,this.id=this.id||this.requestAsyncId(r,this.id,e),this},e.prototype.requestAsyncId=function(t,e,n){return void 0===n&&(n=0),setInterval(t.flush.bind(t,this),n)},e.prototype.recycleAsyncId=function(t,e,n){if(void 0===n&&(n=0),null!==n&&this.delay===n&&!1===this.pending)return e;clearInterval(e)},e.prototype.execute=function(t,e){if(this.closed)return new Error("executing a cancelled action");this.pending=!1;var n=this._execute(t,e);if(n)return n;!1===this.pending&&null!=this.id&&(this.id=this.recycleAsyncId(this.scheduler,this.id,null))},e.prototype._execute=function(t,e){var n=!1,r=void 0;try{this.work(t)}catch(t){n=!0,r=!!t&&t||new Error(t)}if(n)return this.unsubscribe(),r},e.prototype._unsubscribe=function(){var t=this.id,e=this.scheduler,n=e.actions,r=n.indexOf(this);this.work=null,this.state=null,this.pending=!1,this.scheduler=null,-1!==r&&n.splice(r,1),null!=t&&(this.id=this.recycleAsyncId(e,t,null)),this.delay=null},e}(function(t){function e(e,n){return t.call(this)||this}return i(e,t),e.prototype.schedule=function(t,e){return void 0===e&&(e=0),this},e}(f)),B=function(){function t(e,n){void 0===n&&(n=t.now),this.SchedulerAction=e,this.now=n}return t.prototype.schedule=function(t,e,n){return void 0===e&&(e=0),new this.SchedulerAction(this,t).schedule(n,e)},t.now=function(){return Date.now()},t}(),M=function(t){function e(n,r){void 0===r&&(r=B.now);var i=t.call(this,n,function(){return e.delegate&&e.delegate!==i?e.delegate.now():r()})||this;return i.actions=[],i.active=!1,i.scheduled=void 0,i}return i(e,t),e.prototype.schedule=function(n,r,i){return void 0===r&&(r=0),e.delegate&&e.delegate!==this?e.delegate.schedule(n,r,i):t.prototype.schedule.call(this,n,r,i)},e.prototype.flush=function(t){var e=this.actions;if(this.active)e.push(t);else{var n;this.active=!0;do{if(n=t.execute(t.state,t.delay))break}while(t=e.shift());if(this.active=!1,n){for(;t=e.shift();)t.unsubscribe();throw n}}},e}(B),R=new M(z);function D(t){return!l(t)&&t-parseFloat(t)+1>=0}function $(t){return t&&"function"==typeof t.schedule}function Y(t){var e=t.index,n=t.period,r=t.subscriber;if(r.next(e),!r.closed){if(-1===n)return r.complete();t.index=e+1,this.schedule(t,n)}}function W(t,e){return void 0===e&&(e=R),A(function(){return function(t,e,n){void 0===t&&(t=0);var r=-1;return D(e)?r=Number(e)<1?1:Number(e):$(e)&&(n=e),$(n)||(n=R),new k(function(e){var i=D(t)?t:+t-n.now();return n.schedule(Y,i,{index:0,period:r,subscriber:e})})}(t,e)})}function X(t){return function(e){return e.lift(new H(t))}}var H=function(){function t(t){this.closingNotifier=t}return t.prototype.call=function(t,e){return e.subscribe(new U(t,this.closingNotifier))},t}(),U=function(t){function e(e,n){var r=t.call(this,e)||this;return r.buffer=[],r.add(I(r,n)),r}return i(e,t),e.prototype._next=function(t){this.buffer.push(t)},e.prototype.notifyNext=function(t,e,n,r,i){var o=this.buffer;this.buffer=[],this.destination.next(o)},e}(g);function L(t,e){return void 0===e&&(e=null),function(n){return n.lift(new K(t,e))}}var K=function(){function t(t,e){this.bufferSize=t,this.startBufferEvery=e,this.subscriberClass=e&&t!==e?Q:G}return t.prototype.call=function(t,e){return e.subscribe(new this.subscriberClass(t,this.bufferSize,this.startBufferEvery))},t}(),G=function(t){function e(e,n){var r=t.call(this,e)||this;return r.bufferSize=n,r.buffer=[],r}return i(e,t),e.prototype._next=function(t){var e=this.buffer;e.push(t),e.length==this.bufferSize&&(this.destination.next(e),this.buffer=[])},e.prototype._complete=function(){var e=this.buffer;e.length>0&&this.destination.next(e),t.prototype._complete.call(this)},e}(y),Q=function(t){function e(e,n,r){var i=t.call(this,e)||this;return i.bufferSize=n,i.startBufferEvery=r,i.buffers=[],i.count=0,i}return i(e,t),e.prototype._next=function(t){var e=this.bufferSize,n=this.startBufferEvery,r=this.buffers,i=this.count;this.count++,i%n==0&&r.push([]);for(var o=r.length;o--;){var s=r[o];s.push(t),s.length===e&&(r.splice(o,1),this.destination.next(s))}},e.prototype._complete=function(){for(var e=this.buffers,n=this.destination;e.length>0;){var r=e.shift();r.length>0&&n.next(r)}t.prototype._complete.call(this)},e}(y);function J(t){var e=arguments.length,n=R;$(arguments[arguments.length-1])&&(n=arguments[arguments.length-1],e--);var r=null;e>=2&&(r=arguments[1]);var i=Number.POSITIVE_INFINITY;return e>=3&&(i=arguments[2]),function(e){return e.lift(new Z(t,r,i,n))}}var Z=function(){function t(t,e,n,r){this.bufferTimeSpan=t,this.bufferCreationInterval=e,this.maxBufferSize=n,this.scheduler=r}return t.prototype.call=function(t,e){return e.subscribe(new et(t,this.bufferTimeSpan,this.bufferCreationInterval,this.maxBufferSize,this.scheduler))},t}(),tt=function(){return function(){this.buffer=[]}}(),et=function(t){function e(e,n,r,i,o){var s=t.call(this,e)||this;s.bufferTimeSpan=n,s.bufferCreationInterval=r,s.maxBufferSize=i,s.scheduler=o,s.contexts=[];var a=s.openContext();if(s.timespanOnly=null==r||r<0,s.timespanOnly){var c={subscriber:s,context:a,bufferTimeSpan:n};s.add(a.closeAction=o.schedule(nt,n,c))}else{var u={subscriber:s,context:a},l={bufferTimeSpan:n,bufferCreationInterval:r,subscriber:s,scheduler:o};s.add(a.closeAction=o.schedule(it,n,u)),s.add(o.schedule(rt,r,l))}return s}return i(e,t),e.prototype._next=function(t){for(var e,n=this.contexts,r=n.length,i=0;i<r;i++){var o=n[i],s=o.buffer;s.push(t),s.length==this.maxBufferSize&&(e=o)}e&&this.onBufferFull(e)},e.prototype._error=function(e){this.contexts.length=0,t.prototype._error.call(this,e)},e.prototype._complete=function(){for(var e=this.contexts,n=this.destination;e.length>0;){var r=e.shift();n.next(r.buffer)}t.prototype._complete.call(this)},e.prototype._unsubscribe=function(){this.contexts=null},e.prototype.onBufferFull=function(t){this.closeContext(t);var e=t.closeAction;if(e.unsubscribe(),this.remove(e),!this.closed&&this.timespanOnly){t=this.openContext();var n=this.bufferTimeSpan,r={subscriber:this,context:t,bufferTimeSpan:n};this.add(t.closeAction=this.scheduler.schedule(nt,n,r))}},e.prototype.openContext=function(){var t=new tt;return this.contexts.push(t),t},e.prototype.closeContext=function(t){this.destination.next(t.buffer);var e=this.contexts;(e?e.indexOf(t):-1)>=0&&e.splice(e.indexOf(t),1)},e}(y);function nt(t){var e=t.subscriber,n=t.context;n&&e.closeContext(n),e.closed||(t.context=e.openContext(),t.context.closeAction=this.schedule(t,t.bufferTimeSpan))}function rt(t){var e=t.bufferCreationInterval,n=t.bufferTimeSpan,r=t.subscriber,i=t.scheduler,o=r.openContext();r.closed||(r.add(o.closeAction=i.schedule(it,n,{subscriber:r,context:o})),this.schedule(t,e))}function it(t){var e=t.subscriber,n=t.context;e.closeContext(n)}function ot(t,e){return function(n){return n.lift(new st(t,e))}}var st=function(){function t(t,e){this.openings=t,this.closingSelector=e}return t.prototype.call=function(t,e){return e.subscribe(new at(t,this.openings,this.closingSelector))},t}(),at=function(t){function e(e,n,r){var i=t.call(this,e)||this;return i.openings=n,i.closingSelector=r,i.contexts=[],i.add(I(i,n)),i}return i(e,t),e.prototype._next=function(t){for(var e=this.contexts,n=e.length,r=0;r<n;r++)e[r].buffer.push(t)},e.prototype._error=function(e){for(var n=this.contexts;n.length>0;){var r=n.shift();r.subscription.unsubscribe(),r.buffer=null,r.subscription=null}this.contexts=null,t.prototype._error.call(this,e)},e.prototype._complete=function(){for(var e=this.contexts;e.length>0;){var n=e.shift();this.destination.next(n.buffer),n.subscription.unsubscribe(),n.buffer=null,n.subscription=null}this.contexts=null,t.prototype._complete.call(this)},e.prototype.notifyNext=function(t,e,n,r,i){t?this.closeBuffer(t):this.openBuffer(e)},e.prototype.notifyComplete=function(t){this.closeBuffer(t.context)},e.prototype.openBuffer=function(t){try{var e=this.closingSelector.call(this,t);e&&this.trySubscribe(e)}catch(t){this._error(t)}},e.prototype.closeBuffer=function(t){var e=this.contexts;if(e&&t){var n=t.buffer,r=t.subscription;this.destination.next(n),e.splice(e.indexOf(t),1),this.remove(r),r.unsubscribe()}},e.prototype.trySubscribe=function(t){var e=this.contexts,n=new f,r={buffer:[],subscription:n};e.push(r);var i=I(this,t,r);!i||i.closed?this.closeBuffer(r):(i.context=r,this.add(i),n.add(i))},e}(g);function ct(t){return function(e){return e.lift(new ut(t))}}var ut=function(){function t(t){this.closingSelector=t}return t.prototype.call=function(t,e){return e.subscribe(new lt(t,this.closingSelector))},t}(),lt=function(t){function e(e,n){var r=t.call(this,e)||this;return r.closingSelector=n,r.subscribing=!1,r.openBuffer(),r}return i(e,t),e.prototype._next=function(t){this.buffer.push(t)},e.prototype._complete=function(){var e=this.buffer;e&&this.destination.next(e),t.prototype._complete.call(this)},e.prototype._unsubscribe=function(){this.buffer=null,this.subscribing=!1},e.prototype.notifyNext=function(t,e,n,r,i){this.openBuffer()},e.prototype.notifyComplete=function(){this.subscribing?this.complete():this.openBuffer()},e.prototype.openBuffer=function(){var t=this.closingSubscription;t&&(this.remove(t),t.unsubscribe());var e,n=this.buffer;this.buffer&&this.destination.next(n),this.buffer=[];try{e=(0,this.closingSelector)()}catch(t){return this.error(t)}t=new f,this.closingSubscription=t,this.add(t),this.subscribing=!0,t.add(I(this,e)),this.subscribing=!1},e}(g);function ht(t){return function(e){var n=new dt(t),r=e.lift(n);return n.caught=r}}var dt=function(){function t(t){this.selector=t}return t.prototype.call=function(t,e){return e.subscribe(new pt(t,this.selector,this.caught))},t}(),pt=function(t){function e(e,n,r){var i=t.call(this,e)||this;return i.selector=n,i.caught=r,i}return i(e,t),e.prototype.error=function(e){if(!this.isStopped){var n=void 0;try{n=this.selector(e,this.caught)}catch(e){return void t.prototype.error.call(this,e)}this._unsubscribeAndRecycle();var r=new x(this,void 0,void 0);this.add(r),I(this,n,void 0,void 0,r)}},e}(g);function ft(t,e){return new k(function(n){var r=new f,i=0;return r.add(e.schedule(function(){i!==t.length?(n.next(t[i++]),n.closed||r.add(this.schedule())):n.complete()})),r})}function mt(t,e){return e?ft(t,e):new k(w(t))}var bt={};var yt=function(){function t(t){this.resultSelector=t}return t.prototype.call=function(t,e){return e.subscribe(new vt(t,this.resultSelector))},t}(),vt=function(t){function e(e,n){var r=t.call(this,e)||this;return r.resultSelector=n,r.active=0,r.values=[],r.observables=[],r}return i(e,t),e.prototype._next=function(t){this.values.push(bt),this.observables.push(t)},e.prototype._complete=function(){var t=this.observables,e=t.length;if(0===e)this.destination.complete();else{this.active=e,this.toRespond=e;for(var n=0;n<e;n++){var r=t[n];this.add(I(this,r,r,n))}}},e.prototype.notifyComplete=function(t){0==(this.active-=1)&&this.destination.complete()},e.prototype.notifyNext=function(t,e,n,r,i){var o=this.values,s=o[n],a=this.toRespond?s===bt?--this.toRespond:this.toRespond:0;o[n]=e,0===a&&(this.resultSelector?this._tryResultSelector(o):this.destination.next(o.slice()))},e.prototype._tryResultSelector=function(t){var e;try{e=this.resultSelector.apply(this,t)}catch(t){return void this.destination.error(t)}this.destination.next(e)},e}(g);function gt(t){return function(e){return e.lift(new yt(t))}}function xt(t,e){if(null!=t){if(function(t){return t&&"function"==typeof t[O]}(t))return function(t,e){return new k(function(n){var r=new f;return r.add(e.schedule(function(){var i=t[O]();r.add(i.subscribe({next:function(t){r.add(e.schedule(function(){return n.next(t)}))},error:function(t){r.add(e.schedule(function(){return n.error(t)}))},complete:function(){r.add(e.schedule(function(){return n.complete()}))}}))})),r})}(t,e);if(E(t))return function(t,e){return new k(function(n){var r=new f;return r.add(e.schedule(function(){return t.then(function(t){r.add(e.schedule(function(){n.next(t),r.add(e.schedule(function(){return n.complete()}))}))},function(t){r.add(e.schedule(function(){return n.error(t)}))})})),r})}(t,e);if(_(t))return ft(t,e);if(function(t){return t&&"function"==typeof t[j]}(t)||"string"==typeof t)return function(t,e){if(!t)throw new Error("Iterable cannot be null");return new k(function(n){var r,i=new f;return i.add(function(){r&&"function"==typeof r.return&&r.return()}),i.add(e.schedule(function(){r=t[j](),i.add(e.schedule(function(){if(!n.closed){var t,e;try{var i=r.next();t=i.value,e=i.done}catch(t){return void n.error(t)}e?n.complete():(n.next(t),this.schedule())}}))})),i})}(t,e)}throw new TypeError((null!==t&&typeof t||t)+" is not observable")}function wt(t,e){return e?xt(t,e):t instanceof k?t:new k(F(t))}function St(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];var n=null;return"function"==typeof t[t.length-1]&&(n=t.pop()),1===t.length&&l(t[0])&&(t=t[0].slice()),function(e){return e.lift.call(wt([e].concat(t)),new yt(n))}}function jt(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];var n=t[t.length-1];return $(n)?(t.pop(),ft(t,n)):mt(t)}function Ot(t,e){return function(n){if("function"!=typeof t)throw new TypeError("argument is not a function. Are you looking for `mapTo()`?");return n.lift(new _t(t,e))}}var _t=function(){function t(t,e){this.project=t,this.thisArg=e}return t.prototype.call=function(t,e){return e.subscribe(new Et(t,this.project,this.thisArg))},t}(),Et=function(t){function e(e,n,r){var i=t.call(this,e)||this;return i.project=n,i.count=0,i.thisArg=r||i,i}return i(e,t),e.prototype._next=function(t){var e;try{e=this.project.call(this.thisArg,t,this.count++)}catch(t){return void this.destination.error(t)}this.destination.next(e)},e}(y);function Ft(t,e,n){return void 0===n&&(n=Number.POSITIVE_INFINITY),"function"==typeof e?function(r){return r.pipe(Ft(function(n,r){return wt(t(n,r)).pipe(Ot(function(t,i){return e(n,t,r,i)}))},n))}:("number"==typeof e&&(n=e),function(e){return e.lift(new Ct(t,n))})}var Ct=function(){function t(t,e){void 0===e&&(e=Number.POSITIVE_INFINITY),this.project=t,this.concurrent=e}return t.prototype.call=function(t,e){return e.subscribe(new Nt(t,this.project,this.concurrent))},t}(),Nt=function(t){function e(e,n,r){void 0===r&&(r=Number.POSITIVE_INFINITY);var i=t.call(this,e)||this;return i.project=n,i.concurrent=r,i.hasCompleted=!1,i.buffer=[],i.active=0,i.index=0,i}return i(e,t),e.prototype._next=function(t){this.active<this.concurrent?this._tryNext(t):this.buffer.push(t)},e.prototype._tryNext=function(t){var e,n=this.index++;try{e=this.project(t,n)}catch(t){return void this.destination.error(t)}this.active++,this._innerSub(e,t,n)},e.prototype._innerSub=function(t,e,n){var r=new x(this,void 0,void 0);this.destination.add(r),I(this,t,e,n,r)},e.prototype._complete=function(){this.hasCompleted=!0,0===this.active&&0===this.buffer.length&&this.destination.complete(),this.unsubscribe()},e.prototype.notifyNext=function(t,e,n,r,i){this.destination.next(e)},e.prototype.notifyComplete=function(t){var e=this.buffer;this.remove(t),this.active--,e.length>0?this._next(e.shift()):0===this.active&&this.hasCompleted&&this.destination.complete()},e}(g);function Vt(t){return t}function kt(t){return void 0===t&&(t=Number.POSITIVE_INFINITY),Ft(Vt,t)}function Tt(){return kt(1)}function It(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];return Tt()(jt.apply(void 0,t))}function At(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];return function(e){return e.lift.call(It.apply(void 0,[e].concat(t)))}}function Pt(t,e){return Ft(t,e,1)}function qt(t,e){return Pt(function(){return t},e)}function zt(t){return function(e){return e.lift(new Bt(t,e))}}var Bt=function(){function t(t,e){this.predicate=t,this.source=e}return t.prototype.call=function(t,e){return e.subscribe(new Mt(t,this.predicate,this.source))},t}(),Mt=function(t){function e(e,n,r){var i=t.call(this,e)||this;return i.predicate=n,i.source=r,i.count=0,i.index=0,i}return i(e,t),e.prototype._next=function(t){this.predicate?this._tryPredicate(t):this.count++},e.prototype._tryPredicate=function(t){var e;try{e=this.predicate(t,this.index++,this.source)}catch(t){return void this.destination.error(t)}e&&this.count++},e.prototype._complete=function(){this.destination.next(this.count),this.destination.complete()},e}(y);function Rt(t){return function(e){return e.lift(new Dt(t))}}var Dt=function(){function t(t){this.durationSelector=t}return t.prototype.call=function(t,e){return e.subscribe(new $t(t,this.durationSelector))},t}(),$t=function(t){function e(e,n){var r=t.call(this,e)||this;return r.durationSelector=n,r.hasValue=!1,r.durationSubscription=null,r}return i(e,t),e.prototype._next=function(t){try{var e=this.durationSelector.call(this,t);e&&this._tryNext(t,e)}catch(t){this.destination.error(t)}},e.prototype._complete=function(){this.emitValue(),this.destination.complete()},e.prototype._tryNext=function(t,e){var n=this.durationSubscription;this.value=t,this.hasValue=!0,n&&(n.unsubscribe(),this.remove(n)),(n=I(this,e))&&!n.closed&&this.add(this.durationSubscription=n)},e.prototype.notifyNext=function(t,e,n,r,i){this.emitValue()},e.prototype.notifyComplete=function(){this.emitValue()},e.prototype.emitValue=function(){if(this.hasValue){var e=this.value,n=this.durationSubscription;n&&(this.durationSubscription=null,n.unsubscribe(),this.remove(n)),this.value=null,this.hasValue=!1,t.prototype._next.call(this,e)}},e}(g);function Yt(t,e){return void 0===e&&(e=R),function(n){return n.lift(new Wt(t,e))}}var Wt=function(){function t(t,e){this.dueTime=t,this.scheduler=e}return t.prototype.call=function(t,e){return e.subscribe(new Xt(t,this.dueTime,this.scheduler))},t}(),Xt=function(t){function e(e,n,r){var i=t.call(this,e)||this;return i.dueTime=n,i.scheduler=r,i.debouncedSubscription=null,i.lastValue=null,i.hasValue=!1,i}return i(e,t),e.prototype._next=function(t){this.clearDebounce(),this.lastValue=t,this.hasValue=!0,this.add(this.debouncedSubscription=this.scheduler.schedule(Ht,this.dueTime,this))},e.prototype._complete=function(){this.debouncedNext(),this.destination.complete()},e.prototype.debouncedNext=function(){if(this.clearDebounce(),this.hasValue){var t=this.lastValue;this.lastValue=null,this.hasValue=!1,this.destination.next(t)}},e.prototype.clearDebounce=function(){var t=this.debouncedSubscription;null!==t&&(this.remove(t),t.unsubscribe(),this.debouncedSubscription=null)},e}(y);function Ht(t){t.debouncedNext()}function Ut(t){return void 0===t&&(t=null),function(e){return e.lift(new Lt(t))}}var Lt=function(){function t(t){this.defaultValue=t}return t.prototype.call=function(t,e){return e.subscribe(new Kt(t,this.defaultValue))},t}(),Kt=function(t){function e(e,n){var r=t.call(this,e)||this;return r.defaultValue=n,r.isEmpty=!0,r}return i(e,t),e.prototype._next=function(t){this.isEmpty=!1,this.destination.next(t)},e.prototype._complete=function(){this.isEmpty&&this.destination.next(this.defaultValue),this.destination.complete()},e}(y);function Gt(t){return t instanceof Date&&!isNaN(+t)}var Qt,Jt=new k(function(t){return t.complete()});function Zt(t){return t?function(t){return new k(function(e){return t.schedule(function(){return e.complete()})})}(t):Jt}function te(t,e){return new k(e?function(n){return e.schedule(ee,0,{error:t,subscriber:n})}:function(e){return e.error(t)})}function ee(t){var e=t.error;t.subscriber.error(e)}Qt||(Qt={});var ne=function(){function t(t,e,n){this.kind=t,this.value=e,this.error=n,this.hasValue="N"===t}return t.prototype.observe=function(t){switch(this.kind){case"N":return t.next&&t.next(this.value);case"E":return t.error&&t.error(this.error);case"C":return t.complete&&t.complete()}},t.prototype.do=function(t,e,n){switch(this.kind){case"N":return t&&t(this.value);case"E":return e&&e(this.error);case"C":return n&&n()}},t.prototype.accept=function(t,e,n){return t&&"function"==typeof t.next?this.observe(t):this.do(t,e,n)},t.prototype.toObservable=function(){switch(this.kind){case"N":return jt(this.value);case"E":return te(this.error);case"C":return Zt()}throw new Error("unexpected notification kind value")},t.createNext=function(e){return void 0!==e?new t("N",e):t.undefinedValueNotification},t.createError=function(e){return new t("E",void 0,e)},t.createComplete=function(){return t.completeNotification},t.completeNotification=new t("C"),t.undefinedValueNotification=new t("N",void 0),t}();function re(t,e){void 0===e&&(e=R);var n=Gt(t)?+t-e.now():Math.abs(t);return function(t){return t.lift(new ie(n,e))}}var ie=function(){function t(t,e){this.delay=t,this.scheduler=e}return t.prototype.call=function(t,e){return e.subscribe(new oe(t,this.delay,this.scheduler))},t}(),oe=function(t){function e(e,n,r){var i=t.call(this,e)||this;return i.delay=n,i.scheduler=r,i.queue=[],i.active=!1,i.errored=!1,i}return i(e,t),e.dispatch=function(t){for(var e=t.source,n=e.queue,r=t.scheduler,i=t.destination;n.length>0&&n[0].time-r.now()<=0;)n.shift().notification.observe(i);if(n.length>0){var o=Math.max(0,n[0].time-r.now());this.schedule(t,o)}else this.unsubscribe(),e.active=!1},e.prototype._schedule=function(t){this.active=!0,this.destination.add(t.schedule(e.dispatch,this.delay,{source:this,destination:this.destination,scheduler:t}))},e.prototype.scheduleNotification=function(t){if(!0!==this.errored){var e=this.scheduler,n=new se(e.now()+this.delay,t);this.queue.push(n),!1===this.active&&this._schedule(e)}},e.prototype._next=function(t){this.scheduleNotification(ne.createNext(t))},e.prototype._error=function(t){this.errored=!0,this.queue=[],this.destination.error(t),this.unsubscribe()},e.prototype._complete=function(){this.scheduleNotification(ne.createComplete()),this.unsubscribe()},e}(y),se=function(){return function(t,e){this.time=t,this.notification=e}}();function ae(t,e){return e?function(n){return new le(n,e).lift(new ce(t))}:function(e){return e.lift(new ce(t))}}var ce=function(){function t(t){this.delayDurationSelector=t}return t.prototype.call=function(t,e){return e.subscribe(new ue(t,this.delayDurationSelector))},t}(),ue=function(t){function e(e,n){var r=t.call(this,e)||this;return r.delayDurationSelector=n,r.completed=!1,r.delayNotifierSubscriptions=[],r.index=0,r}return i(e,t),e.prototype.notifyNext=function(t,e,n,r,i){this.destination.next(t),this.removeSubscription(i),this.tryComplete()},e.prototype.notifyError=function(t,e){this._error(t)},e.prototype.notifyComplete=function(t){var e=this.removeSubscription(t);e&&this.destination.next(e),this.tryComplete()},e.prototype._next=function(t){var e=this.index++;try{var n=this.delayDurationSelector(t,e);n&&this.tryDelay(n,t)}catch(t){this.destination.error(t)}},e.prototype._complete=function(){this.completed=!0,this.tryComplete(),this.unsubscribe()},e.prototype.removeSubscription=function(t){t.unsubscribe();var e=this.delayNotifierSubscriptions.indexOf(t);return-1!==e&&this.delayNotifierSubscriptions.splice(e,1),t.outerValue},e.prototype.tryDelay=function(t,e){var n=I(this,t,e);n&&!n.closed&&(this.destination.add(n),this.delayNotifierSubscriptions.push(n))},e.prototype.tryComplete=function(){this.completed&&0===this.delayNotifierSubscriptions.length&&this.destination.complete()},e}(g),le=function(t){function e(e,n){var r=t.call(this)||this;return r.source=e,r.subscriptionDelay=n,r}return i(e,t),e.prototype._subscribe=function(t){this.subscriptionDelay.subscribe(new he(t,this.source))},e}(k),he=function(t){function e(e,n){var r=t.call(this)||this;return r.parent=e,r.source=n,r.sourceSubscribed=!1,r}return i(e,t),e.prototype._next=function(t){this.subscribeToSource()},e.prototype._error=function(t){this.unsubscribe(),this.parent.error(t)},e.prototype._complete=function(){this.unsubscribe(),this.subscribeToSource()},e.prototype.subscribeToSource=function(){this.sourceSubscribed||(this.sourceSubscribed=!0,this.unsubscribe(),this.source.subscribe(this.parent))},e}(y);function de(){return function(t){return t.lift(new pe)}}var pe=function(){function t(){}return t.prototype.call=function(t,e){return e.subscribe(new fe(t))},t}(),fe=function(t){function e(e){return t.call(this,e)||this}return i(e,t),e.prototype._next=function(t){t.observe(this.destination)},e}(y);function me(t,e){return function(n){return n.lift(new be(t,e))}}var be=function(){function t(t,e){this.keySelector=t,this.flushes=e}return t.prototype.call=function(t,e){return e.subscribe(new ye(t,this.keySelector,this.flushes))},t}(),ye=function(t){function e(e,n,r){var i=t.call(this,e)||this;return i.keySelector=n,i.values=new Set,r&&i.add(I(i,r)),i}return i(e,t),e.prototype.notifyNext=function(t,e,n,r,i){this.values.clear()},e.prototype.notifyError=function(t,e){this._error(t)},e.prototype._next=function(t){this.keySelector?this._useKeySelector(t):this._finalizeNext(t,t)},e.prototype._useKeySelector=function(t){var e,n=this.destination;try{e=this.keySelector(t)}catch(t){return void n.error(t)}this._finalizeNext(e,t)},e.prototype._finalizeNext=function(t,e){var n=this.values;n.has(t)||(n.add(t),this.destination.next(e))},e}(g);function ve(t,e){return function(n){return n.lift(new ge(t,e))}}var ge=function(){function t(t,e){this.compare=t,this.keySelector=e}return t.prototype.call=function(t,e){return e.subscribe(new xe(t,this.compare,this.keySelector))},t}(),xe=function(t){function e(e,n,r){var i=t.call(this,e)||this;return i.keySelector=r,i.hasKey=!1,"function"==typeof n&&(i.compare=n),i}return i(e,t),e.prototype.compare=function(t,e){return t===e},e.prototype._next=function(t){var e;try{var n=this.keySelector;e=n?n(t):t}catch(t){return this.destination.error(t)}var r=!1;if(this.hasKey)try{r=(0,this.compare)(this.key,e)}catch(t){return this.destination.error(t)}else this.hasKey=!0;r||(this.key=e,this.destination.next(t))},e}(y);function we(t,e){return ve(function(n,r){return e?e(n[t],r[t]):n[t]===r[t]})}function Se(){return Error.call(this),this.message="argument out of range",this.name="ArgumentOutOfRangeError",this}Se.prototype=Object.create(Error.prototype);var je=Se;function Oe(t,e){return function(n){return n.lift(new _e(t,e))}}var _e=function(){function t(t,e){this.predicate=t,this.thisArg=e}return t.prototype.call=function(t,e){return e.subscribe(new Ee(t,this.predicate,this.thisArg))},t}(),Ee=function(t){function e(e,n,r){var i=t.call(this,e)||this;return i.predicate=n,i.thisArg=r,i.count=0,i}return i(e,t),e.prototype._next=function(t){var e;try{e=this.predicate.call(this.thisArg,t,this.count++)}catch(t){return void this.destination.error(t)}e&&this.destination.next(t)},e}(y);function Fe(){return Error.call(this),this.message="no elements in sequence",this.name="EmptyError",this}Fe.prototype=Object.create(Error.prototype);var Ce=Fe;function Ne(t){return void 0===t&&(t=Te),function(e){return e.lift(new Ve(t))}}var Ve=function(){function t(t){this.errorFactory=t}return t.prototype.call=function(t,e){return e.subscribe(new ke(t,this.errorFactory))},t}(),ke=function(t){function e(e,n){var r=t.call(this,e)||this;return r.errorFactory=n,r.hasValue=!1,r}return i(e,t),e.prototype._next=function(t){this.hasValue=!0,this.destination.next(t)},e.prototype._complete=function(){if(this.hasValue)return this.destination.complete();var t=void 0;try{t=this.errorFactory()}catch(e){t=e}this.destination.error(t)},e}(y);function Te(){return new Ce}function Ie(t){return function(e){return 0===t?Zt():e.lift(new Ae(t))}}var Ae=function(){function t(t){if(this.total=t,this.total<0)throw new je}return t.prototype.call=function(t,e){return e.subscribe(new Pe(t,this.total))},t}(),Pe=function(t){function e(e,n){var r=t.call(this,e)||this;return r.total=n,r.count=0,r}return i(e,t),e.prototype._next=function(t){var e=this.total,n=++this.count;n<=e&&(this.destination.next(t),n===e&&(this.destination.complete(),this.unsubscribe()))},e}(y);function qe(t,e){if(t<0)throw new je;var n=arguments.length>=2;return function(r){return r.pipe(Oe(function(e,n){return n===t}),Ie(1),n?Ut(e):Ne(function(){return new je}))}}function ze(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];return function(e){return It.apply(void 0,[e].concat(t))}}function Be(t,e){return function(n){return n.lift(new Me(t,e,n))}}var Me=function(){function t(t,e,n){this.predicate=t,this.thisArg=e,this.source=n}return t.prototype.call=function(t,e){return e.subscribe(new Re(t,this.predicate,this.thisArg,this.source))},t}(),Re=function(t){function e(e,n,r,i){var o=t.call(this,e)||this;return o.predicate=n,o.thisArg=r,o.source=i,o.index=0,o.thisArg=r||o,o}return i(e,t),e.prototype.notifyComplete=function(t){this.destination.next(t),this.destination.complete()},e.prototype._next=function(t){var e=!1;try{e=this.predicate.call(this.thisArg,t,this.index++,this.source)}catch(t){return void this.destination.error(t)}e||this.notifyComplete(!1)},e.prototype._complete=function(){this.notifyComplete(!0)},e}(y);function De(){return function(t){return t.lift(new $e)}}var $e=function(){function t(){}return t.prototype.call=function(t,e){return e.subscribe(new Ye(t))},t}(),Ye=function(t){function e(e){var n=t.call(this,e)||this;return n.hasCompleted=!1,n.hasSubscription=!1,n}return i(e,t),e.prototype._next=function(t){this.hasSubscription||(this.hasSubscription=!0,this.add(I(this,t)))},e.prototype._complete=function(){this.hasCompleted=!0,this.hasSubscription||this.destination.complete()},e.prototype.notifyComplete=function(t){this.remove(t),this.hasSubscription=!1,this.hasCompleted&&this.destination.complete()},e}(g);function We(t,e){return e?function(n){return n.pipe(We(function(n,r){return wt(t(n,r)).pipe(Ot(function(t,i){return e(n,t,r,i)}))}))}:function(e){return e.lift(new Xe(t))}}var Xe=function(){function t(t){this.project=t}return t.prototype.call=function(t,e){return e.subscribe(new He(t,this.project))},t}(),He=function(t){function e(e,n){var r=t.call(this,e)||this;return r.project=n,r.hasSubscription=!1,r.hasCompleted=!1,r.index=0,r}return i(e,t),e.prototype._next=function(t){this.hasSubscription||this.tryNext(t)},e.prototype.tryNext=function(t){var e,n=this.index++;try{e=this.project(t,n)}catch(t){return void this.destination.error(t)}this.hasSubscription=!0,this._innerSub(e,t,n)},e.prototype._innerSub=function(t,e,n){var r=new x(this,void 0,void 0);this.destination.add(r),I(this,t,e,n,r)},e.prototype._complete=function(){this.hasCompleted=!0,this.hasSubscription||this.destination.complete(),this.unsubscribe()},e.prototype.notifyNext=function(t,e,n,r,i){this.destination.next(e)},e.prototype.notifyError=function(t){this.destination.error(t)},e.prototype.notifyComplete=function(t){this.destination.remove(t),this.hasSubscription=!1,this.hasCompleted&&this.destination.complete()},e}(g);function Ue(t,e,n){return void 0===e&&(e=Number.POSITIVE_INFINITY),void 0===n&&(n=void 0),e=(e||0)<1?Number.POSITIVE_INFINITY:e,function(r){return r.lift(new Le(t,e,n))}}var Le=function(){function t(t,e,n){this.project=t,this.concurrent=e,this.scheduler=n}return t.prototype.call=function(t,e){return e.subscribe(new Ke(t,this.project,this.concurrent,this.scheduler))},t}(),Ke=function(t){function e(e,n,r,i){var o=t.call(this,e)||this;return o.project=n,o.concurrent=r,o.scheduler=i,o.index=0,o.active=0,o.hasCompleted=!1,r<Number.POSITIVE_INFINITY&&(o.buffer=[]),o}return i(e,t),e.dispatch=function(t){var e=t.subscriber,n=t.result,r=t.value,i=t.index;e.subscribeToProjection(n,r,i)},e.prototype._next=function(t){var n=this.destination;if(n.closed)this._complete();else{var r=this.index++;if(this.active<this.concurrent){n.next(t);try{var i=(0,this.project)(t,r);if(this.scheduler){var o={subscriber:this,result:i,value:t,index:r};this.destination.add(this.scheduler.schedule(e.dispatch,0,o))}else this.subscribeToProjection(i,t,r)}catch(t){n.error(t)}}else this.buffer.push(t)}},e.prototype.subscribeToProjection=function(t,e,n){this.active++,this.destination.add(I(this,t,e,n))},e.prototype._complete=function(){this.hasCompleted=!0,this.hasCompleted&&0===this.active&&this.destination.complete(),this.unsubscribe()},e.prototype.notifyNext=function(t,e,n,r,i){this._next(e)},e.prototype.notifyComplete=function(t){var e=this.buffer;this.destination.remove(t),this.active--,e&&e.length>0&&this._next(e.shift()),this.hasCompleted&&0===this.active&&this.destination.complete()},e}(g);function Ge(t){return function(e){return e.lift(new Qe(t))}}var Qe=function(){function t(t){this.callback=t}return t.prototype.call=function(t,e){return e.subscribe(new Je(t,this.callback))},t}(),Je=function(t){function e(e,n){var r=t.call(this,e)||this;return r.add(new f(n)),r}return i(e,t),e}(y);function Ze(t,e){if("function"!=typeof t)throw new TypeError("predicate is not a function");return function(n){return n.lift(new tn(t,n,!1,e))}}var tn=function(){function t(t,e,n,r){this.predicate=t,this.source=e,this.yieldIndex=n,this.thisArg=r}return t.prototype.call=function(t,e){return e.subscribe(new en(t,this.predicate,this.source,this.yieldIndex,this.thisArg))},t}(),en=function(t){function e(e,n,r,i,o){var s=t.call(this,e)||this;return s.predicate=n,s.source=r,s.yieldIndex=i,s.thisArg=o,s.index=0,s}return i(e,t),e.prototype.notifyComplete=function(t){var e=this.destination;e.next(t),e.complete(),this.unsubscribe()},e.prototype._next=function(t){var e=this.predicate,n=this.thisArg,r=this.index++;try{e.call(n||this,t,r,this.source)&&this.notifyComplete(this.yieldIndex?r:t)}catch(t){this.destination.error(t)}},e.prototype._complete=function(){this.notifyComplete(this.yieldIndex?-1:void 0)},e}(y);function nn(t,e){return function(n){return n.lift(new tn(t,n,!0,e))}}function rn(t,e){var n=arguments.length>=2;return function(r){return r.pipe(t?Oe(function(e,n){return t(e,n,r)}):Vt,Ie(1),n?Ut(e):Ne(function(){return new Ce}))}}function on(){return Error.call(this),this.message="object unsubscribed",this.name="ObjectUnsubscribedError",this}on.prototype=Object.create(Error.prototype);var sn=on,an=function(t){function e(e,n){var r=t.call(this)||this;return r.subject=e,r.subscriber=n,r.closed=!1,r}return i(e,t),e.prototype.unsubscribe=function(){if(!this.closed){this.closed=!0;var t=this.subject,e=t.observers;if(this.subject=null,e&&0!==e.length&&!t.isStopped&&!t.closed){var n=e.indexOf(this.subscriber);-1!==n&&e.splice(n,1)}}},e}(f),cn=function(t){function e(e){var n=t.call(this,e)||this;return n.destination=e,n}return i(e,t),e}(y),un=function(t){function e(){var e=t.call(this)||this;return e.observers=[],e.closed=!1,e.isStopped=!1,e.hasError=!1,e.thrownError=null,e}return i(e,t),e.prototype[b]=function(){return new cn(this)},e.prototype.lift=function(t){var e=new ln(this,this);return e.operator=t,e},e.prototype.next=function(t){if(this.closed)throw new sn;if(!this.isStopped)for(var e=this.observers,n=e.length,r=e.slice(),i=0;i<n;i++)r[i].next(t)},e.prototype.error=function(t){if(this.closed)throw new sn;this.hasError=!0,this.thrownError=t,this.isStopped=!0;for(var e=this.observers,n=e.length,r=e.slice(),i=0;i<n;i++)r[i].error(t);this.observers.length=0},e.prototype.complete=function(){if(this.closed)throw new sn;this.isStopped=!0;for(var t=this.observers,e=t.length,n=t.slice(),r=0;r<e;r++)n[r].complete();this.observers.length=0},e.prototype.unsubscribe=function(){this.isStopped=!0,this.closed=!0,this.observers=null},e.prototype._trySubscribe=function(e){if(this.closed)throw new sn;return t.prototype._trySubscribe.call(this,e)},e.prototype._subscribe=function(t){if(this.closed)throw new sn;return this.hasError?(t.error(this.thrownError),f.EMPTY):this.isStopped?(t.complete(),f.EMPTY):(this.observers.push(t),new an(this,t))},e.prototype.asObservable=function(){var t=new k;return t.source=this,t},e.create=function(t,e){return new ln(t,e)},e}(k),ln=function(t){function e(e,n){var r=t.call(this)||this;return r.destination=e,r.source=n,r}return i(e,t),e.prototype.next=function(t){var e=this.destination;e&&e.next&&e.next(t)},e.prototype.error=function(t){var e=this.destination;e&&e.error&&this.destination.error(t)},e.prototype.complete=function(){var t=this.destination;t&&t.complete&&this.destination.complete()},e.prototype._subscribe=function(t){return this.source?this.source.subscribe(t):f.EMPTY},e}(un);function hn(t,e,n,r){return function(i){return i.lift(new dn(t,e,n,r))}}var dn=function(){function t(t,e,n,r){this.keySelector=t,this.elementSelector=e,this.durationSelector=n,this.subjectSelector=r}return t.prototype.call=function(t,e){return e.subscribe(new pn(t,this.keySelector,this.elementSelector,this.durationSelector,this.subjectSelector))},t}(),pn=function(t){function e(e,n,r,i,o){var s=t.call(this,e)||this;return s.keySelector=n,s.elementSelector=r,s.durationSelector=i,s.subjectSelector=o,s.groups=null,s.attemptedToUnsubscribe=!1,s.count=0,s}return i(e,t),e.prototype._next=function(t){var e;try{e=this.keySelector(t)}catch(t){return void this.error(t)}this._group(t,e)},e.prototype._group=function(t,e){var n=this.groups;n||(n=this.groups=new Map);var r,i=n.get(e);if(this.elementSelector)try{r=this.elementSelector(t)}catch(t){this.error(t)}else r=t;if(!i){i=this.subjectSelector?this.subjectSelector():new un,n.set(e,i);var o=new mn(e,i,this);if(this.destination.next(o),this.durationSelector){var s=void 0;try{s=this.durationSelector(new mn(e,i))}catch(t){return void this.error(t)}this.add(s.subscribe(new fn(e,i,this)))}}i.closed||i.next(r)},e.prototype._error=function(t){var e=this.groups;e&&(e.forEach(function(e,n){e.error(t)}),e.clear()),this.destination.error(t)},e.prototype._complete=function(){var t=this.groups;t&&(t.forEach(function(t,e){t.complete()}),t.clear()),this.destination.complete()},e.prototype.removeGroup=function(t){this.groups.delete(t)},e.prototype.unsubscribe=function(){this.closed||(this.attemptedToUnsubscribe=!0,0===this.count&&t.prototype.unsubscribe.call(this))},e}(y),fn=function(t){function e(e,n,r){var i=t.call(this,n)||this;return i.key=e,i.group=n,i.parent=r,i}return i(e,t),e.prototype._next=function(t){this.complete()},e.prototype._unsubscribe=function(){var t=this.parent,e=this.key;this.key=this.parent=null,t&&t.removeGroup(e)},e}(y),mn=function(t){function e(e,n,r){var i=t.call(this)||this;return i.key=e,i.groupSubject=n,i.refCountSubscription=r,i}return i(e,t),e.prototype._subscribe=function(t){var e=new f,n=this.refCountSubscription,r=this.groupSubject;return n&&!n.closed&&e.add(new bn(n)),e.add(r.subscribe(t)),e},e}(k),bn=function(t){function e(e){var n=t.call(this)||this;return n.parent=e,e.count++,n}return i(e,t),e.prototype.unsubscribe=function(){var e=this.parent;e.closed||this.closed||(t.prototype.unsubscribe.call(this),e.count-=1,0===e.count&&e.attemptedToUnsubscribe&&e.unsubscribe())},e}(f);function yn(){return function(t){return t.lift(new vn)}}var vn=function(){function t(){}return t.prototype.call=function(t,e){return e.subscribe(new gn(t))},t}(),gn=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return i(e,t),e.prototype._next=function(t){},e}(y);function xn(){return function(t){return t.lift(new wn)}}var wn=function(){function t(){}return t.prototype.call=function(t,e){return e.subscribe(new Sn(t))},t}(),Sn=function(t){function e(e){return t.call(this,e)||this}return i(e,t),e.prototype.notifyComplete=function(t){var e=this.destination;e.next(t),e.complete()},e.prototype._next=function(t){this.notifyComplete(!1)},e.prototype._complete=function(){this.notifyComplete(!0)},e}(y);function jn(t){return function(e){return 0===t?Zt():e.lift(new On(t))}}var On=function(){function t(t){if(this.total=t,this.total<0)throw new je}return t.prototype.call=function(t,e){return e.subscribe(new _n(t,this.total))},t}(),_n=function(t){function e(e,n){var r=t.call(this,e)||this;return r.total=n,r.ring=new Array,r.count=0,r}return i(e,t),e.prototype._next=function(t){var e=this.ring,n=this.total,r=this.count++;e.length<n?e.push(t):e[r%n]=t},e.prototype._complete=function(){var t=this.destination,e=this.count;if(e>0)for(var n=this.count>=this.total?this.total:this.count,r=this.ring,i=0;i<n;i++){var o=e++%n;t.next(r[o])}t.complete()},e}(y);function En(t,e){var n=arguments.length>=2;return function(r){return r.pipe(t?Oe(function(e,n){return t(e,n,r)}):Vt,jn(1),n?Ut(e):Ne(function(){return new Ce}))}}function Fn(t){return function(e){return e.lift(new Cn(t))}}var Cn=function(){function t(t){this.value=t}return t.prototype.call=function(t,e){return e.subscribe(new Nn(t,this.value))},t}(),Nn=function(t){function e(e,n){var r=t.call(this,e)||this;return r.value=n,r}return i(e,t),e.prototype._next=function(t){this.destination.next(this.value)},e}(y);function Vn(){return function(t){return t.lift(new kn)}}var kn=function(){function t(){}return t.prototype.call=function(t,e){return e.subscribe(new Tn(t))},t}(),Tn=function(t){function e(e){return t.call(this,e)||this}return i(e,t),e.prototype._next=function(t){this.destination.next(ne.createNext(t))},e.prototype._error=function(t){var e=this.destination;e.next(ne.createError(t)),e.complete()},e.prototype._complete=function(){var t=this.destination;t.next(ne.createComplete()),t.complete()},e}(y);function In(t,e){var n=!1;return arguments.length>=2&&(n=!0),function(r){return r.lift(new An(t,e,n))}}var An=function(){function t(t,e,n){void 0===n&&(n=!1),this.accumulator=t,this.seed=e,this.hasSeed=n}return t.prototype.call=function(t,e){return e.subscribe(new Pn(t,this.accumulator,this.seed,this.hasSeed))},t}(),Pn=function(t){function e(e,n,r,i){var o=t.call(this,e)||this;return o.accumulator=n,o._seed=r,o.hasSeed=i,o.index=0,o}return i(e,t),Object.defineProperty(e.prototype,"seed",{get:function(){return this._seed},set:function(t){this.hasSeed=!0,this._seed=t},enumerable:!0,configurable:!0}),e.prototype._next=function(t){if(this.hasSeed)return this._tryNext(t);this.seed=t,this.destination.next(t)},e.prototype._tryNext=function(t){var e,n=this.index++;try{e=this.accumulator(this.seed,t,n)}catch(t){this.destination.error(t)}this.seed=e,this.destination.next(e)},e}(y);function qn(t,e){return arguments.length>=2?function(n){return N(In(t,e),jn(1),Ut(e))(n)}:function(e){return N(In(function(e,n,r){return t(e,n,r+1)}),jn(1))(e)}}function zn(t){return qn("function"==typeof t?function(e,n){return t(e,n)>0?e:n}:function(t,e){return t>e?t:e})}function Bn(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];return function(e){return e.lift.call(function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];var n=Number.POSITIVE_INFINITY,r=null,i=t[t.length-1];return $(i)?(r=t.pop(),t.length>1&&"number"==typeof t[t.length-1]&&(n=t.pop())):"number"==typeof i&&(n=t.pop()),null===r&&1===t.length&&t[0]instanceof k?t[0]:kt(n)(mt(t,r))}.apply(void 0,[e].concat(t)))}}function Mn(t,e,n){return void 0===n&&(n=Number.POSITIVE_INFINITY),"function"==typeof e?Ft(function(){return t},e,n):("number"==typeof e&&(n=e),Ft(function(){return t},n))}function Rn(t,e,n){return void 0===n&&(n=Number.POSITIVE_INFINITY),function(r){return r.lift(new Dn(t,e,n))}}var Dn=function(){function t(t,e,n){this.accumulator=t,this.seed=e,this.concurrent=n}return t.prototype.call=function(t,e){return e.subscribe(new $n(t,this.accumulator,this.seed,this.concurrent))},t}(),$n=function(t){function e(e,n,r,i){var o=t.call(this,e)||this;return o.accumulator=n,o.acc=r,o.concurrent=i,o.hasValue=!1,o.hasCompleted=!1,o.buffer=[],o.active=0,o.index=0,o}return i(e,t),e.prototype._next=function(t){if(this.active<this.concurrent){var e=this.index++,n=this.destination,r=void 0;try{r=(0,this.accumulator)(this.acc,t,e)}catch(t){return n.error(t)}this.active++,this._innerSub(r,t,e)}else this.buffer.push(t)},e.prototype._innerSub=function(t,e,n){var r=new x(this,void 0,void 0);this.destination.add(r),I(this,t,e,n,r)},e.prototype._complete=function(){this.hasCompleted=!0,0===this.active&&0===this.buffer.length&&(!1===this.hasValue&&this.destination.next(this.acc),this.destination.complete()),this.unsubscribe()},e.prototype.notifyNext=function(t,e,n,r,i){var o=this.destination;this.acc=e,this.hasValue=!0,o.next(e)},e.prototype.notifyComplete=function(t){var e=this.buffer;this.destination.remove(t),this.active--,e.length>0?this._next(e.shift()):0===this.active&&this.hasCompleted&&(!1===this.hasValue&&this.destination.next(this.acc),this.destination.complete())},e}(g);function Yn(t){return qn("function"==typeof t?function(e,n){return t(e,n)<0?e:n}:function(t,e){return t<e?t:e})}function Wn(){return function(t){return t.lift(new Xn(t))}}var Xn=function(){function t(t){this.connectable=t}return t.prototype.call=function(t,e){var n=this.connectable;n._refCount++;var r=new Hn(t,n),i=e.subscribe(r);return r.closed||(r.connection=n.connect()),i},t}(),Hn=function(t){function e(e,n){var r=t.call(this,e)||this;return r.connectable=n,r}return i(e,t),e.prototype._unsubscribe=function(){var t=this.connectable;if(t){this.connectable=null;var e=t._refCount;if(e<=0)this.connection=null;else if(t._refCount=e-1,e>1)this.connection=null;else{var n=this.connection,r=t._connection;this.connection=null,!r||n&&r!==n||r.unsubscribe()}}else this.connection=null},e}(y),Un=function(t){function e(e,n){var r=t.call(this)||this;return r.source=e,r.subjectFactory=n,r._refCount=0,r._isComplete=!1,r}return i(e,t),e.prototype._subscribe=function(t){return this.getSubject().subscribe(t)},e.prototype.getSubject=function(){var t=this._subject;return t&&!t.isStopped||(this._subject=this.subjectFactory()),this._subject},e.prototype.connect=function(){var t=this._connection;return t||(this._isComplete=!1,(t=this._connection=new f).add(this.source.subscribe(new Kn(this.getSubject(),this))),t.closed&&(this._connection=null,t=f.EMPTY)),t},e.prototype.refCount=function(){return Wn()(this)},e}(k).prototype,Ln={operator:{value:null},_refCount:{value:0,writable:!0},_subject:{value:null,writable:!0},_connection:{value:null,writable:!0},_subscribe:{value:Un._subscribe},_isComplete:{value:Un._isComplete,writable:!0},getSubject:{value:Un.getSubject},connect:{value:Un.connect},refCount:{value:Un.refCount}},Kn=function(t){function e(e,n){var r=t.call(this,e)||this;return r.connectable=n,r}return i(e,t),e.prototype._error=function(e){this._unsubscribe(),t.prototype._error.call(this,e)},e.prototype._complete=function(){this.connectable._isComplete=!0,this._unsubscribe(),t.prototype._complete.call(this)},e.prototype._unsubscribe=function(){var t=this.connectable;if(t){this.connectable=null;var e=t._connection;t._refCount=0,t._subject=null,t._connection=null,e&&e.unsubscribe()}},e}(cn);function Gn(t,e){return function(n){var r;if(r="function"==typeof t?t:function(){return t},"function"==typeof e)return n.lift(new Qn(r,e));var i=Object.create(n,Ln);return i.source=n,i.subjectFactory=r,i}}var Qn=function(){function t(t,e){this.subjectFactory=t,this.selector=e}return t.prototype.call=function(t,e){var n=this.selector,r=this.subjectFactory(),i=n(r).subscribe(t);return i.add(e.subscribe(r)),i},t}();function Jn(t,e){return void 0===e&&(e=0),function(n){return n.lift(new Zn(t,e))}}var Zn=function(){function t(t,e){void 0===e&&(e=0),this.scheduler=t,this.delay=e}return t.prototype.call=function(t,e){return e.subscribe(new tr(t,this.scheduler,this.delay))},t}(),tr=function(t){function e(e,n,r){void 0===r&&(r=0);var i=t.call(this,e)||this;return i.scheduler=n,i.delay=r,i}return i(e,t),e.dispatch=function(t){var e=t.notification,n=t.destination;e.observe(n),this.unsubscribe()},e.prototype.scheduleMessage=function(t){this.destination.add(this.scheduler.schedule(e.dispatch,this.delay,new er(t,this.destination)))},e.prototype._next=function(t){this.scheduleMessage(ne.createNext(t))},e.prototype._error=function(t){this.scheduleMessage(ne.createError(t)),this.unsubscribe()},e.prototype._complete=function(){this.scheduleMessage(ne.createComplete()),this.unsubscribe()},e}(y),er=function(){return function(t,e){this.notification=t,this.destination=e}}();function nr(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];return 1===t.length&&l(t[0])&&(t=t[0]),function(e){return e.lift(new rr(t))}}var rr=function(){function t(t){this.nextSources=t}return t.prototype.call=function(t,e){return e.subscribe(new ir(t,this.nextSources))},t}(),ir=function(t){function e(e,n){var r=t.call(this,e)||this;return r.destination=e,r.nextSources=n,r}return i(e,t),e.prototype.notifyError=function(t,e){this.subscribeToNextSource()},e.prototype.notifyComplete=function(t){this.subscribeToNextSource()},e.prototype._error=function(t){this.subscribeToNextSource(),this.unsubscribe()},e.prototype._complete=function(){this.subscribeToNextSource(),this.unsubscribe()},e.prototype.subscribeToNextSource=function(){var t=this.nextSources.shift();if(t){var e=new x(this,void 0,void 0);this.destination.add(e),I(this,t,void 0,void 0,e)}else this.destination.complete()},e}(g);function or(){return function(t){return t.lift(new sr)}}var sr=function(){function t(){}return t.prototype.call=function(t,e){return e.subscribe(new ar(t))},t}(),ar=function(t){function e(e){var n=t.call(this,e)||this;return n.hasPrev=!1,n}return i(e,t),e.prototype._next=function(t){this.hasPrev?this.destination.next([this.prev,t]):this.hasPrev=!0,this.prev=t},e}(y);function cr(t,e){function n(){return!n.pred.apply(n.thisArg,arguments)}return n.pred=t,n.thisArg=e,n}function ur(t,e){return function(n){return[Oe(t,e)(n),Oe(cr(t,e))(n)]}}function lr(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];var n=t.length;if(0===n)throw new Error("list of properties cannot be empty.");return function(e){return Ot(function(t,e){return function(n){for(var r=n,i=0;i<e;i++){var o=r[t[i]];if(void 0===o)return;r=o}return r}}(t,n))(e)}}function hr(t){return t?Gn(function(){return new un},t):Gn(new un)}var dr=function(t){function e(e){var n=t.call(this)||this;return n._value=e,n}return i(e,t),Object.defineProperty(e.prototype,"value",{get:function(){return this.getValue()},enumerable:!0,configurable:!0}),e.prototype._subscribe=function(e){var n=t.prototype._subscribe.call(this,e);return n&&!n.closed&&e.next(this._value),n},e.prototype.getValue=function(){if(this.hasError)throw this.thrownError;if(this.closed)throw new sn;return this._value},e.prototype.next=function(e){t.prototype.next.call(this,this._value=e)},e}(un);function pr(t){return function(e){return Gn(new dr(t))(e)}}var fr=function(t){function e(){var e=null!==t&&t.apply(this,arguments)||this;return e.value=null,e.hasNext=!1,e.hasCompleted=!1,e}return i(e,t),e.prototype._subscribe=function(e){return this.hasError?(e.error(this.thrownError),f.EMPTY):this.hasCompleted&&this.hasNext?(e.next(this.value),e.complete(),f.EMPTY):t.prototype._subscribe.call(this,e)},e.prototype.next=function(t){this.hasCompleted||(this.value=t,this.hasNext=!0)},e.prototype.error=function(e){this.hasCompleted||t.prototype.error.call(this,e)},e.prototype.complete=function(){this.hasCompleted=!0,this.hasNext&&t.prototype.next.call(this,this.value),t.prototype.complete.call(this)},e}(un);function mr(){return function(t){return Gn(new fr)(t)}}var br=function(t){function e(e,n){var r=t.call(this,e,n)||this;return r.scheduler=e,r.work=n,r}return i(e,t),e.prototype.schedule=function(e,n){return void 0===n&&(n=0),n>0?t.prototype.schedule.call(this,e,n):(this.delay=n,this.state=e,this.scheduler.flush(this),this)},e.prototype.execute=function(e,n){return n>0||this.closed?t.prototype.execute.call(this,e,n):this._execute(e,n)},e.prototype.requestAsyncId=function(e,n,r){return void 0===r&&(r=0),null!==r&&r>0||null===r&&this.delay>0?t.prototype.requestAsyncId.call(this,e,n,r):e.flush(this)},e}(z),yr=new(function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return i(e,t),e}(M))(br),vr=function(t){function e(e,n,r){void 0===e&&(e=Number.POSITIVE_INFINITY),void 0===n&&(n=Number.POSITIVE_INFINITY);var i=t.call(this)||this;return i.scheduler=r,i._events=[],i._infiniteTimeWindow=!1,i._bufferSize=e<1?1:e,i._windowTime=n<1?1:n,n===Number.POSITIVE_INFINITY?(i._infiniteTimeWindow=!0,i.next=i.nextInfiniteTimeWindow):i.next=i.nextTimeWindow,i}return i(e,t),e.prototype.nextInfiniteTimeWindow=function(e){var n=this._events;n.push(e),n.length>this._bufferSize&&n.shift(),t.prototype.next.call(this,e)},e.prototype.nextTimeWindow=function(e){this._events.push(new gr(this._getNow(),e)),this._trimBufferThenGetEvents(),t.prototype.next.call(this,e)},e.prototype._subscribe=function(t){var e,n=this._infiniteTimeWindow,r=n?this._events:this._trimBufferThenGetEvents(),i=this.scheduler,o=r.length;if(this.closed)throw new sn;if(this.isStopped||this.hasError?e=f.EMPTY:(this.observers.push(t),e=new an(this,t)),i&&t.add(t=new tr(t,i)),n)for(var s=0;s<o&&!t.closed;s++)t.next(r[s]);else for(s=0;s<o&&!t.closed;s++)t.next(r[s].value);return this.hasError?t.error(this.thrownError):this.isStopped&&t.complete(),e},e.prototype._getNow=function(){return(this.scheduler||yr).now()},e.prototype._trimBufferThenGetEvents=function(){for(var t=this._getNow(),e=this._bufferSize,n=this._windowTime,r=this._events,i=r.length,o=0;o<i&&!(t-r[o].time<n);)o++;return i>e&&(o=Math.max(o,i-e)),o>0&&r.splice(0,o),r},e}(un),gr=function(){return function(t,e){this.time=t,this.value=e}}();function xr(t,e,n,r){n&&"function"!=typeof n&&(r=n);var i="function"==typeof n?n:void 0,o=new vr(t,e,r);return function(t){return Gn(function(){return o},i)(t)}}var wr=function(){function t(){}return t.prototype.call=function(t,e){return e.subscribe(new Sr(t))},t}(),Sr=function(t){function e(e){var n=t.call(this,e)||this;return n.hasFirst=!1,n.observables=[],n.subscriptions=[],n}return i(e,t),e.prototype._next=function(t){this.observables.push(t)},e.prototype._complete=function(){var t=this.observables,e=t.length;if(0===e)this.destination.complete();else{for(var n=0;n<e&&!this.hasFirst;n++){var r=t[n],i=I(this,r,r,n);this.subscriptions&&this.subscriptions.push(i),this.add(i)}this.observables=null}},e.prototype.notifyNext=function(t,e,n,r,i){if(!this.hasFirst){this.hasFirst=!0;for(var o=0;o<this.subscriptions.length;o++)if(o!==n){var s=this.subscriptions[o];s.unsubscribe(),this.remove(s)}this.subscriptions=null}this.destination.next(e)},e}(g);function jr(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];return function(e){return 1===t.length&&l(t[0])&&(t=t[0]),e.lift.call(function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];if(1===t.length){if(!l(t[0]))return t[0];t=t[0]}return mt(t,void 0).lift(new wr)}.apply(void 0,[e].concat(t)))}}function Or(t){return void 0===t&&(t=-1),function(e){return 0===t?Zt():t<0?e.lift(new _r(-1,e)):e.lift(new _r(t-1,e))}}var _r=function(){function t(t,e){this.count=t,this.source=e}return t.prototype.call=function(t,e){return e.subscribe(new Er(t,this.count,this.source))},t}(),Er=function(t){function e(e,n,r){var i=t.call(this,e)||this;return i.count=n,i.source=r,i}return i(e,t),e.prototype.complete=function(){if(!this.isStopped){var e=this.source,n=this.count;if(0===n)return t.prototype.complete.call(this);n>-1&&(this.count=n-1),e.subscribe(this._unsubscribeAndRecycle())}},e}(y);function Fr(t){return function(e){return e.lift(new Cr(t))}}var Cr=function(){function t(t){this.notifier=t}return t.prototype.call=function(t,e){return e.subscribe(new Nr(t,this.notifier,e))},t}(),Nr=function(t){function e(e,n,r){var i=t.call(this,e)||this;return i.notifier=n,i.source=r,i.sourceIsBeingSubscribedTo=!0,i}return i(e,t),e.prototype.notifyNext=function(t,e,n,r,i){this.sourceIsBeingSubscribedTo=!0,this.source.subscribe(this)},e.prototype.notifyComplete=function(e){if(!1===this.sourceIsBeingSubscribedTo)return t.prototype.complete.call(this)},e.prototype.complete=function(){if(this.sourceIsBeingSubscribedTo=!1,!this.isStopped){if(this.retries||this.subscribeToRetries(),!this.retriesSubscription||this.retriesSubscription.closed)return t.prototype.complete.call(this);this._unsubscribeAndRecycle(),this.notifications.next()}},e.prototype._unsubscribe=function(){var t=this.notifications,e=this.retriesSubscription;t&&(t.unsubscribe(),this.notifications=null),e&&(e.unsubscribe(),this.retriesSubscription=null),this.retries=null},e.prototype._unsubscribeAndRecycle=function(){var e=this._unsubscribe;return this._unsubscribe=null,t.prototype._unsubscribeAndRecycle.call(this),this._unsubscribe=e,this},e.prototype.subscribeToRetries=function(){var e;this.notifications=new un;try{e=(0,this.notifier)(this.notifications)}catch(e){return t.prototype.complete.call(this)}this.retries=e,this.retriesSubscription=I(this,e)},e}(g);function Vr(t){return void 0===t&&(t=-1),function(e){return e.lift(new kr(t,e))}}var kr=function(){function t(t,e){this.count=t,this.source=e}return t.prototype.call=function(t,e){return e.subscribe(new Tr(t,this.count,this.source))},t}(),Tr=function(t){function e(e,n,r){var i=t.call(this,e)||this;return i.count=n,i.source=r,i}return i(e,t),e.prototype.error=function(e){if(!this.isStopped){var n=this.source,r=this.count;if(0===r)return t.prototype.error.call(this,e);r>-1&&(this.count=r-1),n.subscribe(this._unsubscribeAndRecycle())}},e}(y);function Ir(t){return function(e){return e.lift(new Ar(t,e))}}var Ar=function(){function t(t,e){this.notifier=t,this.source=e}return t.prototype.call=function(t,e){return e.subscribe(new Pr(t,this.notifier,this.source))},t}(),Pr=function(t){function e(e,n,r){var i=t.call(this,e)||this;return i.notifier=n,i.source=r,i}return i(e,t),e.prototype.error=function(e){if(!this.isStopped){var n=this.errors,r=this.retries,i=this.retriesSubscription;if(r)this.errors=null,this.retriesSubscription=null;else{n=new un;try{r=(0,this.notifier)(n)}catch(e){return t.prototype.error.call(this,e)}i=I(this,r)}this._unsubscribeAndRecycle(),this.errors=n,this.retries=r,this.retriesSubscription=i,n.next(e)}},e.prototype._unsubscribe=function(){var t=this.errors,e=this.retriesSubscription;t&&(t.unsubscribe(),this.errors=null),e&&(e.unsubscribe(),this.retriesSubscription=null),this.retries=null},e.prototype.notifyNext=function(t,e,n,r,i){var o=this._unsubscribe;this._unsubscribe=null,this._unsubscribeAndRecycle(),this._unsubscribe=o,this.source.subscribe(this)},e}(g);function qr(t){return function(e){return e.lift(new zr(t))}}var zr=function(){function t(t){this.notifier=t}return t.prototype.call=function(t,e){var n=new Br(t),r=e.subscribe(n);return r.add(I(n,this.notifier)),r},t}(),Br=function(t){function e(){var e=null!==t&&t.apply(this,arguments)||this;return e.hasValue=!1,e}return i(e,t),e.prototype._next=function(t){this.value=t,this.hasValue=!0},e.prototype.notifyNext=function(t,e,n,r,i){this.emitValue()},e.prototype.notifyComplete=function(){this.emitValue()},e.prototype.emitValue=function(){this.hasValue&&(this.hasValue=!1,this.destination.next(this.value))},e}(g);function Mr(t,e){return void 0===e&&(e=R),function(n){return n.lift(new Rr(t,e))}}var Rr=function(){function t(t,e){this.period=t,this.scheduler=e}return t.prototype.call=function(t,e){return e.subscribe(new Dr(t,this.period,this.scheduler))},t}(),Dr=function(t){function e(e,n,r){var i=t.call(this,e)||this;return i.period=n,i.scheduler=r,i.hasValue=!1,i.add(r.schedule($r,n,{subscriber:i,period:n})),i}return i(e,t),e.prototype._next=function(t){this.lastValue=t,this.hasValue=!0},e.prototype.notifyNext=function(){this.hasValue&&(this.hasValue=!1,this.destination.next(this.lastValue))},e}(y);function $r(t){var e=t.subscriber,n=t.period;e.notifyNext(),this.schedule(t,n)}function Yr(t,e){return function(n){return n.lift(new Wr(t,e))}}var Wr=function(){function t(t,e){this.compareTo=t,this.comparator=e}return t.prototype.call=function(t,e){return e.subscribe(new Xr(t,this.compareTo,this.comparator))},t}(),Xr=function(t){function e(e,n,r){var i=t.call(this,e)||this;return i.compareTo=n,i.comparator=r,i._a=[],i._b=[],i._oneComplete=!1,i.destination.add(n.subscribe(new Hr(e,i))),i}return i(e,t),e.prototype._next=function(t){this._oneComplete&&0===this._b.length?this.emit(!1):(this._a.push(t),this.checkValues())},e.prototype._complete=function(){this._oneComplete?this.emit(0===this._a.length&&0===this._b.length):this._oneComplete=!0,this.unsubscribe()},e.prototype.checkValues=function(){for(var t=this._a,e=this._b,n=this.comparator;t.length>0&&e.length>0;){var r=t.shift(),i=e.shift(),o=!1;try{o=n?n(r,i):r===i}catch(t){this.destination.error(t)}o||this.emit(!1)}},e.prototype.emit=function(t){var e=this.destination;e.next(t),e.complete()},e.prototype.nextB=function(t){this._oneComplete&&0===this._a.length?this.emit(!1):(this._b.push(t),this.checkValues())},e.prototype.completeB=function(){this._oneComplete?this.emit(0===this._a.length&&0===this._b.length):this._oneComplete=!0},e}(y),Hr=function(t){function e(e,n){var r=t.call(this,e)||this;return r.parent=n,r}return i(e,t),e.prototype._next=function(t){this.parent.nextB(t)},e.prototype._error=function(t){this.parent.error(t),this.unsubscribe()},e.prototype._complete=function(){this.parent.completeB(),this.unsubscribe()},e}(y);function Ur(){return new un}function Lr(){return function(t){return Wn()(Gn(Ur)(t))}}function Kr(t,e,n){var r;return r=t&&"object"==typeof t?t:{bufferSize:t,windowTime:e,refCount:!1,scheduler:n},function(t){return t.lift((o=(e=r).bufferSize,s=void 0===o?Number.POSITIVE_INFINITY:o,a=e.windowTime,c=void 0===a?Number.POSITIVE_INFINITY:a,u=e.refCount,l=e.scheduler,h=0,d=!1,p=!1,function(t){h++,n&&!d||(d=!1,n=new vr(s,c,l),i=t.subscribe({next:function(t){n.next(t)},error:function(t){d=!0,n.error(t)},complete:function(){p=!0,n.complete()}}));var e=n.subscribe(this);this.add(function(){h--,e.unsubscribe(),i&&!p&&u&&0===h&&(i.unsubscribe(),i=void 0,n=void 0)})}));var e,n,i,o,s,a,c,u,l,h,d,p}}function Gr(t){return function(e){return e.lift(new Qr(t,e))}}var Qr=function(){function t(t,e){this.predicate=t,this.source=e}return t.prototype.call=function(t,e){return e.subscribe(new Jr(t,this.predicate,this.source))},t}(),Jr=function(t){function e(e,n,r){var i=t.call(this,e)||this;return i.predicate=n,i.source=r,i.seenValue=!1,i.index=0,i}return i(e,t),e.prototype.applySingleValue=function(t){this.seenValue?this.destination.error("Sequence contains more than one element"):(this.seenValue=!0,this.singleValue=t)},e.prototype._next=function(t){var e=this.index++;this.predicate?this.tryNext(t,e):this.applySingleValue(t)},e.prototype.tryNext=function(t,e){try{this.predicate(t,e,this.source)&&this.applySingleValue(t)}catch(t){this.destination.error(t)}},e.prototype._complete=function(){var t=this.destination;this.index>0?(t.next(this.seenValue?this.singleValue:void 0),t.complete()):t.error(new Ce)},e}(y);function Zr(t){return function(e){return e.lift(new ti(t))}}var ti=function(){function t(t){this.total=t}return t.prototype.call=function(t,e){return e.subscribe(new ei(t,this.total))},t}(),ei=function(t){function e(e,n){var r=t.call(this,e)||this;return r.total=n,r.count=0,r}return i(e,t),e.prototype._next=function(t){++this.count>this.total&&this.destination.next(t)},e}(y);function ni(t){return function(e){return e.lift(new ri(t))}}var ri=function(){function t(t){if(this._skipCount=t,this._skipCount<0)throw new je}return t.prototype.call=function(t,e){return 0===this._skipCount?e.subscribe(new y(t)):e.subscribe(new ii(t,this._skipCount))},t}(),ii=function(t){function e(e,n){var r=t.call(this,e)||this;return r._skipCount=n,r._count=0,r._ring=new Array(n),r}return i(e,t),e.prototype._next=function(t){var e=this._skipCount,n=this._count++;if(n<e)this._ring[n]=t;else{var r=n%e,i=this._ring,o=i[r];i[r]=t,this.destination.next(o)}},e}(y);function oi(t){return function(e){return e.lift(new si(t))}}var si=function(){function t(t){this.notifier=t}return t.prototype.call=function(t,e){return e.subscribe(new ai(t,this.notifier))},t}(),ai=function(t){function e(e,n){var r=t.call(this,e)||this;r.hasValue=!1;var i=new x(r,void 0,void 0);return r.add(i),r.innerSubscription=i,I(r,n,void 0,void 0,i),r}return i(e,t),e.prototype._next=function(e){this.hasValue&&t.prototype._next.call(this,e)},e.prototype.notifyNext=function(t,e,n,r,i){this.hasValue=!0,this.innerSubscription&&this.innerSubscription.unsubscribe()},e.prototype.notifyComplete=function(){},e}(g);function ci(t){return function(e){return e.lift(new ui(t))}}var ui=function(){function t(t){this.predicate=t}return t.prototype.call=function(t,e){return e.subscribe(new li(t,this.predicate))},t}(),li=function(t){function e(e,n){var r=t.call(this,e)||this;return r.predicate=n,r.skipping=!0,r.index=0,r}return i(e,t),e.prototype._next=function(t){var e=this.destination;this.skipping&&this.tryCallPredicate(t),this.skipping||e.next(t)},e.prototype.tryCallPredicate=function(t){try{var e=this.predicate(t,this.index++);this.skipping=Boolean(e)}catch(t){this.destination.error(t)}},e}(y);function hi(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];var n=t[t.length-1];return $(n)?(t.pop(),function(e){return It(t,e,n)}):function(e){return It(t,e)}}var di=1,pi={};var fi=function(t){var e=di++;return pi[e]=t,Promise.resolve().then(function(){return function(t){var e=pi[t];e&&e()}(e)}),e},mi=function(t){delete pi[t]},bi=function(t){function e(e,n){var r=t.call(this,e,n)||this;return r.scheduler=e,r.work=n,r}return i(e,t),e.prototype.requestAsyncId=function(e,n,r){return void 0===r&&(r=0),null!==r&&r>0?t.prototype.requestAsyncId.call(this,e,n,r):(e.actions.push(this),e.scheduled||(e.scheduled=fi(e.flush.bind(e,null))))},e.prototype.recycleAsyncId=function(e,n,r){if(void 0===r&&(r=0),null!==r&&r>0||null===r&&this.delay>0)return t.prototype.recycleAsyncId.call(this,e,n,r);0===e.actions.length&&(mi(n),e.scheduled=void 0)},e}(z),yi=new(function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return i(e,t),e.prototype.flush=function(t){this.active=!0,this.scheduled=void 0;var e,n=this.actions,r=-1,i=n.length;t=t||n.shift();do{if(e=t.execute(t.state,t.delay))break}while(++r<i&&(t=n.shift()));if(this.active=!1,e){for(;++r<i&&(t=n.shift());)t.unsubscribe();throw e}},e}(M))(bi),vi=function(t){function e(e,n,r){void 0===n&&(n=0),void 0===r&&(r=yi);var i=t.call(this)||this;return i.source=e,i.delayTime=n,i.scheduler=r,(!D(n)||n<0)&&(i.delayTime=0),r&&"function"==typeof r.schedule||(i.scheduler=yi),i}return i(e,t),e.create=function(t,n,r){return void 0===n&&(n=0),void 0===r&&(r=yi),new e(t,n,r)},e.dispatch=function(t){var e=t.source,n=t.subscriber;return this.add(e.subscribe(n))},e.prototype._subscribe=function(t){var n=this.delayTime,r=this.source;return this.scheduler.schedule(e.dispatch,n,{source:r,subscriber:t})},e}(k);function gi(t,e){return void 0===e&&(e=0),function(n){return n.lift(new xi(t,e))}}var xi=function(){function t(t,e){this.scheduler=t,this.delay=e}return t.prototype.call=function(t,e){return new vi(e,this.delay,this.scheduler).subscribe(t)},t}();function wi(t,e){return"function"==typeof e?function(n){return n.pipe(wi(function(n,r){return wt(t(n,r)).pipe(Ot(function(t,i){return e(n,t,r,i)}))}))}:function(e){return e.lift(new Si(t))}}var Si=function(){function t(t){this.project=t}return t.prototype.call=function(t,e){return e.subscribe(new ji(t,this.project))},t}(),ji=function(t){function e(e,n){var r=t.call(this,e)||this;return r.project=n,r.index=0,r}return i(e,t),e.prototype._next=function(t){var e,n=this.index++;try{e=this.project(t,n)}catch(t){return void this.destination.error(t)}this._innerSub(e,t,n)},e.prototype._innerSub=function(t,e,n){var r=this.innerSubscription;r&&r.unsubscribe();var i=new x(this,void 0,void 0);this.destination.add(i),this.innerSubscription=I(this,t,e,n,i)},e.prototype._complete=function(){var e=this.innerSubscription;e&&!e.closed||t.prototype._complete.call(this),this.unsubscribe()},e.prototype._unsubscribe=function(){this.innerSubscription=null},e.prototype.notifyComplete=function(e){this.destination.remove(e),this.innerSubscription=null,this.isStopped&&t.prototype._complete.call(this)},e.prototype.notifyNext=function(t,e,n,r,i){this.destination.next(e)},e}(g);function Oi(){return wi(Vt)}function _i(t,e){return e?wi(function(){return t},e):wi(function(){return t})}function Ei(t){return function(e){return e.lift(new Fi(t))}}var Fi=function(){function t(t){this.notifier=t}return t.prototype.call=function(t,e){var n=new Ci(t),r=I(n,this.notifier);return r&&!n.seenValue?(n.add(r),e.subscribe(n)):n},t}(),Ci=function(t){function e(e){var n=t.call(this,e)||this;return n.seenValue=!1,n}return i(e,t),e.prototype.notifyNext=function(t,e,n,r,i){this.seenValue=!0,this.complete()},e.prototype.notifyComplete=function(){},e}(g);function Ni(t,e){return void 0===e&&(e=!1),function(n){return n.lift(new Vi(t,e))}}var Vi=function(){function t(t,e){this.predicate=t,this.inclusive=e}return t.prototype.call=function(t,e){return e.subscribe(new ki(t,this.predicate,this.inclusive))},t}(),ki=function(t){function e(e,n,r){var i=t.call(this,e)||this;return i.predicate=n,i.inclusive=r,i.index=0,i}return i(e,t),e.prototype._next=function(t){var e,n=this.destination;try{e=this.predicate(t,this.index++)}catch(t){return void n.error(t)}this.nextOrComplete(t,e)},e.prototype.nextOrComplete=function(t,e){var n=this.destination;Boolean(e)?n.next(t):(this.inclusive&&n.next(t),n.complete())},e}(y);function Ti(t,e,n){return function(r){return r.lift(new Ii(t,e,n))}}var Ii=function(){function t(t,e,n){this.nextOrObserver=t,this.error=e,this.complete=n}return t.prototype.call=function(t,e){return e.subscribe(new Ai(t,this.nextOrObserver,this.error,this.complete))},t}(),Ai=function(t){function e(e,n,r,i){var s=t.call(this,e)||this;return s._tapNext=C,s._tapError=C,s._tapComplete=C,s._tapError=r||C,s._tapComplete=i||C,o(n)?(s._context=s,s._tapNext=n):n&&(s._context=n,s._tapNext=n.next||C,s._tapError=n.error||C,s._tapComplete=n.complete||C),s}return i(e,t),e.prototype._next=function(t){try{this._tapNext.call(this._context,t)}catch(t){return void this.destination.error(t)}this.destination.next(t)},e.prototype._error=function(t){try{this._tapError.call(this._context,t)}catch(t){return void this.destination.error(t)}this.destination.error(t)},e.prototype._complete=function(){try{this._tapComplete.call(this._context)}catch(t){return void this.destination.error(t)}return this.destination.complete()},e}(y),Pi={leading:!0,trailing:!1};function qi(t,e){return void 0===e&&(e=Pi),function(n){return n.lift(new zi(t,e.leading,e.trailing))}}var zi=function(){function t(t,e,n){this.durationSelector=t,this.leading=e,this.trailing=n}return t.prototype.call=function(t,e){return e.subscribe(new Bi(t,this.durationSelector,this.leading,this.trailing))},t}(),Bi=function(t){function e(e,n,r,i){var o=t.call(this,e)||this;return o.destination=e,o.durationSelector=n,o._leading=r,o._trailing=i,o._hasValue=!1,o}return i(e,t),e.prototype._next=function(t){this._hasValue=!0,this._sendValue=t,this._throttled||(this._leading?this.send():this.throttle(t))},e.prototype.send=function(){var t=this._hasValue,e=this._sendValue;t&&(this.destination.next(e),this.throttle(e)),this._hasValue=!1,this._sendValue=null},e.prototype.throttle=function(t){var e=this.tryDurationSelector(t);e&&this.add(this._throttled=I(this,e))},e.prototype.tryDurationSelector=function(t){try{return this.durationSelector(t)}catch(t){return this.destination.error(t),null}},e.prototype.throttlingDone=function(){var t=this._throttled,e=this._trailing;t&&t.unsubscribe(),this._throttled=null,e&&this.send()},e.prototype.notifyNext=function(t,e,n,r,i){this.throttlingDone()},e.prototype.notifyComplete=function(){this.throttlingDone()},e}(g);function Mi(t,e,n){return void 0===e&&(e=R),void 0===n&&(n=Pi),function(r){return r.lift(new Ri(t,e,n.leading,n.trailing))}}var Ri=function(){function t(t,e,n,r){this.duration=t,this.scheduler=e,this.leading=n,this.trailing=r}return t.prototype.call=function(t,e){return e.subscribe(new Di(t,this.duration,this.scheduler,this.leading,this.trailing))},t}(),Di=function(t){function e(e,n,r,i,o){var s=t.call(this,e)||this;return s.duration=n,s.scheduler=r,s.leading=i,s.trailing=o,s._hasTrailingValue=!1,s._trailingValue=null,s}return i(e,t),e.prototype._next=function(t){this.throttled?this.trailing&&(this._trailingValue=t,this._hasTrailingValue=!0):(this.add(this.throttled=this.scheduler.schedule($i,this.duration,{subscriber:this})),this.leading?this.destination.next(t):this.trailing&&(this._trailingValue=t,this._hasTrailingValue=!0))},e.prototype._complete=function(){this._hasTrailingValue?(this.destination.next(this._trailingValue),this.destination.complete()):this.destination.complete()},e.prototype.clearThrottle=function(){var t=this.throttled;t&&(this.trailing&&this._hasTrailingValue&&(this.destination.next(this._trailingValue),this._trailingValue=null,this._hasTrailingValue=!1),t.unsubscribe(),this.remove(t),this.throttled=null)},e}(y);function $i(t){t.subscriber.clearThrottle()}function Yi(t){return void 0===t&&(t=R),function(e){return n=function(){return e.pipe(In(function(e,n){var r=e.current;return{value:n,current:t.now(),last:r}},{current:t.now(),value:void 0,last:void 0}),Ot(function(t){var e=t.current,n=t.last,r=t.value;return new Wi(r,e-n)}))},new k(function(t){var e;try{e=n()}catch(e){return void t.error(e)}return(e?wt(e):Zt()).subscribe(t)});var n}}var Wi=function(){return function(t,e){this.value=t,this.interval=e}}();function Xi(){return Error.call(this),this.message="Timeout has occurred",this.name="TimeoutError",this}Xi.prototype=Object.create(Error.prototype);var Hi=Xi;function Ui(t,e,n){return void 0===n&&(n=R),function(r){var i=Gt(t),o=i?+t-n.now():Math.abs(t);return r.lift(new Li(o,i,e,n))}}var Li=function(){function t(t,e,n,r){this.waitFor=t,this.absoluteTimeout=e,this.withObservable=n,this.scheduler=r}return t.prototype.call=function(t,e){return e.subscribe(new Ki(t,this.absoluteTimeout,this.waitFor,this.withObservable,this.scheduler))},t}(),Ki=function(t){function e(e,n,r,i,o){var s=t.call(this,e)||this;return s.absoluteTimeout=n,s.waitFor=r,s.withObservable=i,s.scheduler=o,s.action=null,s.scheduleTimeout(),s}return i(e,t),e.dispatchTimeout=function(t){var e=t.withObservable;t._unsubscribeAndRecycle(),t.add(I(t,e))},e.prototype.scheduleTimeout=function(){var t=this.action;t?this.action=t.schedule(this,this.waitFor):this.add(this.action=this.scheduler.schedule(e.dispatchTimeout,this.waitFor,this))},e.prototype._next=function(e){this.absoluteTimeout||this.scheduleTimeout(),t.prototype._next.call(this,e)},e.prototype._unsubscribe=function(){this.action=null,this.scheduler=null,this.withObservable=null},e}(g);function Gi(t,e){return void 0===e&&(e=R),Ui(t,te(new Hi),e)}function Qi(t){return void 0===t&&(t=R),Ot(function(e){return new Ji(e,t.now())})}var Ji=function(){return function(t,e){this.value=t,this.timestamp=e}}();function Zi(t,e,n){return 0===n?[e]:(t.push(e),t)}function to(){return qn(Zi,[])}function eo(t){return function(e){return e.lift(new no(t))}}var no=function(){function t(t){this.windowBoundaries=t}return t.prototype.call=function(t,e){var n=new ro(t),r=e.subscribe(n);return r.closed||n.add(I(n,this.windowBoundaries)),r},t}(),ro=function(t){function e(e){var n=t.call(this,e)||this;return n.window=new un,e.next(n.window),n}return i(e,t),e.prototype.notifyNext=function(t,e,n,r,i){this.openWindow()},e.prototype.notifyError=function(t,e){this._error(t)},e.prototype.notifyComplete=function(t){this._complete()},e.prototype._next=function(t){this.window.next(t)},e.prototype._error=function(t){this.window.error(t),this.destination.error(t)},e.prototype._complete=function(){this.window.complete(),this.destination.complete()},e.prototype._unsubscribe=function(){this.window=null},e.prototype.openWindow=function(){var t=this.window;t&&t.complete();var e=this.destination,n=this.window=new un;e.next(n)},e}(g);function io(t,e){return void 0===e&&(e=0),function(n){return n.lift(new oo(t,e))}}var oo=function(){function t(t,e){this.windowSize=t,this.startWindowEvery=e}return t.prototype.call=function(t,e){return e.subscribe(new so(t,this.windowSize,this.startWindowEvery))},t}(),so=function(t){function e(e,n,r){var i=t.call(this,e)||this;return i.destination=e,i.windowSize=n,i.startWindowEvery=r,i.windows=[new un],i.count=0,e.next(i.windows[0]),i}return i(e,t),e.prototype._next=function(t){for(var e=this.startWindowEvery>0?this.startWindowEvery:this.windowSize,n=this.destination,r=this.windowSize,i=this.windows,o=i.length,s=0;s<o&&!this.closed;s++)i[s].next(t);var a=this.count-r+1;if(a>=0&&a%e==0&&!this.closed&&i.shift().complete(),++this.count%e==0&&!this.closed){var c=new un;i.push(c),n.next(c)}},e.prototype._error=function(t){var e=this.windows;if(e)for(;e.length>0&&!this.closed;)e.shift().error(t);this.destination.error(t)},e.prototype._complete=function(){var t=this.windows;if(t)for(;t.length>0&&!this.closed;)t.shift().complete();this.destination.complete()},e.prototype._unsubscribe=function(){this.count=0,this.windows=null},e}(y);function ao(t){var e=R,n=null,r=Number.POSITIVE_INFINITY;return $(arguments[3])&&(e=arguments[3]),$(arguments[2])?e=arguments[2]:D(arguments[2])&&(r=arguments[2]),$(arguments[1])?e=arguments[1]:D(arguments[1])&&(n=arguments[1]),function(i){return i.lift(new co(t,n,r,e))}}var co=function(){function t(t,e,n,r){this.windowTimeSpan=t,this.windowCreationInterval=e,this.maxWindowSize=n,this.scheduler=r}return t.prototype.call=function(t,e){return e.subscribe(new lo(t,this.windowTimeSpan,this.windowCreationInterval,this.maxWindowSize,this.scheduler))},t}(),uo=function(t){function e(){var e=null!==t&&t.apply(this,arguments)||this;return e._numberOfNextedValues=0,e}return i(e,t),e.prototype.next=function(e){this._numberOfNextedValues++,t.prototype.next.call(this,e)},Object.defineProperty(e.prototype,"numberOfNextedValues",{get:function(){return this._numberOfNextedValues},enumerable:!0,configurable:!0}),e}(un),lo=function(t){function e(e,n,r,i,o){var s=t.call(this,e)||this;s.destination=e,s.windowTimeSpan=n,s.windowCreationInterval=r,s.maxWindowSize=i,s.scheduler=o,s.windows=[];var a=s.openWindow();if(null!==r&&r>=0){var c={subscriber:s,window:a,context:null},u={windowTimeSpan:n,windowCreationInterval:r,subscriber:s,scheduler:o};s.add(o.schedule(fo,n,c)),s.add(o.schedule(po,r,u))}else{var l={subscriber:s,window:a,windowTimeSpan:n};s.add(o.schedule(ho,n,l))}return s}return i(e,t),e.prototype._next=function(t){for(var e=this.windows,n=e.length,r=0;r<n;r++){var i=e[r];i.closed||(i.next(t),i.numberOfNextedValues>=this.maxWindowSize&&this.closeWindow(i))}},e.prototype._error=function(t){for(var e=this.windows;e.length>0;)e.shift().error(t);this.destination.error(t)},e.prototype._complete=function(){for(var t=this.windows;t.length>0;){var e=t.shift();e.closed||e.complete()}this.destination.complete()},e.prototype.openWindow=function(){var t=new uo;return this.windows.push(t),this.destination.next(t),t},e.prototype.closeWindow=function(t){t.complete();var e=this.windows;e.splice(e.indexOf(t),1)},e}(y);function ho(t){var e=t.subscriber,n=t.windowTimeSpan,r=t.window;r&&e.closeWindow(r),t.window=e.openWindow(),this.schedule(t,n)}function po(t){var e=t.windowTimeSpan,n=t.subscriber,r=t.scheduler,i=t.windowCreationInterval,o=n.openWindow(),s={action:this,subscription:null},a={subscriber:n,window:o,context:s};s.subscription=r.schedule(fo,e,a),this.add(s.subscription),this.schedule(t,i)}function fo(t){var e=t.subscriber,n=t.window,r=t.context;r&&r.action&&r.subscription&&r.action.remove(r.subscription),e.closeWindow(n)}function mo(t,e){return function(n){return n.lift(new bo(t,e))}}var bo=function(){function t(t,e){this.openings=t,this.closingSelector=e}return t.prototype.call=function(t,e){return e.subscribe(new yo(t,this.openings,this.closingSelector))},t}(),yo=function(t){function e(e,n,r){var i=t.call(this,e)||this;return i.openings=n,i.closingSelector=r,i.contexts=[],i.add(i.openSubscription=I(i,n,n)),i}return i(e,t),e.prototype._next=function(t){var e=this.contexts;if(e)for(var n=e.length,r=0;r<n;r++)e[r].window.next(t)},e.prototype._error=function(e){var n=this.contexts;if(this.contexts=null,n)for(var r=n.length,i=-1;++i<r;){var o=n[i];o.window.error(e),o.subscription.unsubscribe()}t.prototype._error.call(this,e)},e.prototype._complete=function(){var e=this.contexts;if(this.contexts=null,e)for(var n=e.length,r=-1;++r<n;){var i=e[r];i.window.complete(),i.subscription.unsubscribe()}t.prototype._complete.call(this)},e.prototype._unsubscribe=function(){var t=this.contexts;if(this.contexts=null,t)for(var e=t.length,n=-1;++n<e;){var r=t[n];r.window.unsubscribe(),r.subscription.unsubscribe()}},e.prototype.notifyNext=function(t,e,n,r,i){if(t===this.openings){var o=void 0;try{o=(0,this.closingSelector)(e)}catch(t){return this.error(t)}var s=new un,a=new f,c={window:s,subscription:a};this.contexts.push(c);var u=I(this,o,c);u.closed?this.closeWindow(this.contexts.length-1):(u.context=c,a.add(u)),this.destination.next(s)}else this.closeWindow(this.contexts.indexOf(t))},e.prototype.notifyError=function(t){this.error(t)},e.prototype.notifyComplete=function(t){t!==this.openSubscription&&this.closeWindow(this.contexts.indexOf(t.context))},e.prototype.closeWindow=function(t){if(-1!==t){var e=this.contexts,n=e[t],r=n.window,i=n.subscription;e.splice(t,1),r.complete(),i.unsubscribe()}},e}(g);function vo(t){return function(e){return e.lift(new go(t))}}var go=function(){function t(t){this.closingSelector=t}return t.prototype.call=function(t,e){return e.subscribe(new xo(t,this.closingSelector))},t}(),xo=function(t){function e(e,n){var r=t.call(this,e)||this;return r.destination=e,r.closingSelector=n,r.openWindow(),r}return i(e,t),e.prototype.notifyNext=function(t,e,n,r,i){this.openWindow(i)},e.prototype.notifyError=function(t,e){this._error(t)},e.prototype.notifyComplete=function(t){this.openWindow(t)},e.prototype._next=function(t){this.window.next(t)},e.prototype._error=function(t){this.window.error(t),this.destination.error(t),this.unsubscribeClosingNotification()},e.prototype._complete=function(){this.window.complete(),this.destination.complete(),this.unsubscribeClosingNotification()},e.prototype.unsubscribeClosingNotification=function(){this.closingNotification&&this.closingNotification.unsubscribe()},e.prototype.openWindow=function(t){void 0===t&&(t=null),t&&(this.remove(t),t.unsubscribe());var e=this.window;e&&e.complete();var n,r=this.window=new un;this.destination.next(r);try{n=(0,this.closingSelector)()}catch(t){return this.destination.error(t),void this.window.error(t)}this.add(this.closingNotification=I(this,n))},e}(g);function wo(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];return function(e){var n;"function"==typeof t[t.length-1]&&(n=t.pop());var r=t;return e.lift(new So(r,n))}}var So=function(){function t(t,e){this.observables=t,this.project=e}return t.prototype.call=function(t,e){return e.subscribe(new jo(t,this.observables,this.project))},t}(),jo=function(t){function e(e,n,r){var i=t.call(this,e)||this;i.observables=n,i.project=r,i.toRespond=[];var o=n.length;i.values=new Array(o);for(var s=0;s<o;s++)i.toRespond.push(s);for(s=0;s<o;s++){var a=n[s];i.add(I(i,a,a,s))}return i}return i(e,t),e.prototype.notifyNext=function(t,e,n,r,i){this.values[n]=e;var o=this.toRespond;if(o.length>0){var s=o.indexOf(n);-1!==s&&o.splice(s,1)}},e.prototype.notifyComplete=function(){},e.prototype._next=function(t){if(0===this.toRespond.length){var e=[t].concat(this.values);this.project?this._tryProject(e):this.destination.next(e)}},e.prototype._tryProject=function(t){var e;try{e=this.project.apply(this,t)}catch(t){return void this.destination.error(t)}this.destination.next(e)},e}(g);var Oo=function(){function t(t){this.resultSelector=t}return t.prototype.call=function(t,e){return e.subscribe(new _o(t,this.resultSelector))},t}(),_o=function(t){function e(e,n,r){void 0===r&&(r=Object.create(null));var i=t.call(this,e)||this;return i.iterators=[],i.active=0,i.resultSelector="function"==typeof n?n:null,i.values=r,i}return i(e,t),e.prototype._next=function(t){var e=this.iterators;l(t)?e.push(new Fo(t)):"function"==typeof t[j]?e.push(new Eo(t[j]())):e.push(new Co(this.destination,this,t))},e.prototype._complete=function(){var t=this.iterators,e=t.length;if(this.unsubscribe(),0!==e){this.active=e;for(var n=0;n<e;n++){var r=t[n];if(r.stillUnsubscribed)this.destination.add(r.subscribe(r,n));else this.active--}}else this.destination.complete()},e.prototype.notifyInactive=function(){this.active--,0===this.active&&this.destination.complete()},e.prototype.checkIterators=function(){for(var t=this.iterators,e=t.length,n=this.destination,r=0;r<e;r++){if("function"==typeof(s=t[r]).hasValue&&!s.hasValue())return}var i=!1,o=[];for(r=0;r<e;r++){var s,a=(s=t[r]).next();if(s.hasCompleted()&&(i=!0),a.done)return void n.complete();o.push(a.value)}this.resultSelector?this._tryresultSelector(o):n.next(o),i&&n.complete()},e.prototype._tryresultSelector=function(t){var e;try{e=this.resultSelector.apply(this,t)}catch(t){return void this.destination.error(t)}this.destination.next(e)},e}(y),Eo=function(){function t(t){this.iterator=t,this.nextResult=t.next()}return t.prototype.hasValue=function(){return!0},t.prototype.next=function(){var t=this.nextResult;return this.nextResult=this.iterator.next(),t},t.prototype.hasCompleted=function(){var t=this.nextResult;return t&&t.done},t}(),Fo=function(){function t(t){this.array=t,this.index=0,this.length=0,this.length=t.length}return t.prototype[j]=function(){return this},t.prototype.next=function(t){var e=this.index++,n=this.array;return e<this.length?{value:n[e],done:!1}:{value:null,done:!0}},t.prototype.hasValue=function(){return this.array.length>this.index},t.prototype.hasCompleted=function(){return this.array.length===this.index},t}(),Co=function(t){function e(e,n,r){var i=t.call(this,e)||this;return i.parent=n,i.observable=r,i.stillUnsubscribed=!0,i.buffer=[],i.isComplete=!1,i}return i(e,t),e.prototype[j]=function(){return this},e.prototype.next=function(){var t=this.buffer;return 0===t.length&&this.isComplete?{value:null,done:!0}:{value:t.shift(),done:!1}},e.prototype.hasValue=function(){return this.buffer.length>0},e.prototype.hasCompleted=function(){return 0===this.buffer.length&&this.isComplete},e.prototype.notifyComplete=function(){this.buffer.length>0?(this.isComplete=!0,this.parent.notifyInactive()):this.destination.complete()},e.prototype.notifyNext=function(t,e,n,r,i){this.buffer.push(e),this.parent.checkIterators()},e.prototype.subscribe=function(t,e){return I(this,this.observable,this,e)},e}(g);function No(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];return function(e){return e.lift.call(function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];var n=t[t.length-1];return"function"==typeof n&&t.pop(),mt(t,void 0).lift(new Oo(n))}.apply(void 0,[e].concat(t)))}}function Vo(t){return function(e){return e.lift(new Oo(t))}}n.d(e,"audit",function(){return A}),n.d(e,"auditTime",function(){return W}),n.d(e,"buffer",function(){return X}),n.d(e,"bufferCount",function(){return L}),n.d(e,"bufferTime",function(){return J}),n.d(e,"bufferToggle",function(){return ot}),n.d(e,"bufferWhen",function(){return ct}),n.d(e,"catchError",function(){return ht}),n.d(e,"combineAll",function(){return gt}),n.d(e,"combineLatest",function(){return St}),n.d(e,"concat",function(){return At}),n.d(e,"concatAll",function(){return Tt}),n.d(e,"concatMap",function(){return Pt}),n.d(e,"concatMapTo",function(){return qt}),n.d(e,"count",function(){return zt}),n.d(e,"debounce",function(){return Rt}),n.d(e,"debounceTime",function(){return Yt}),n.d(e,"defaultIfEmpty",function(){return Ut}),n.d(e,"delay",function(){return re}),n.d(e,"delayWhen",function(){return ae}),n.d(e,"dematerialize",function(){return de}),n.d(e,"distinct",function(){return me}),n.d(e,"distinctUntilChanged",function(){return ve}),n.d(e,"distinctUntilKeyChanged",function(){return we}),n.d(e,"elementAt",function(){return qe}),n.d(e,"endWith",function(){return ze}),n.d(e,"every",function(){return Be}),n.d(e,"exhaust",function(){return De}),n.d(e,"exhaustMap",function(){return We}),n.d(e,"expand",function(){return Ue}),n.d(e,"filter",function(){return Oe}),n.d(e,"finalize",function(){return Ge}),n.d(e,"find",function(){return Ze}),n.d(e,"findIndex",function(){return nn}),n.d(e,"first",function(){return rn}),n.d(e,"groupBy",function(){return hn}),n.d(e,"ignoreElements",function(){return yn}),n.d(e,"isEmpty",function(){return xn}),n.d(e,"last",function(){return En}),n.d(e,"map",function(){return Ot}),n.d(e,"mapTo",function(){return Fn}),n.d(e,"materialize",function(){return Vn}),n.d(e,"max",function(){return zn}),n.d(e,"merge",function(){return Bn}),n.d(e,"mergeAll",function(){return kt}),n.d(e,"mergeMap",function(){return Ft}),n.d(e,"flatMap",function(){return Ft}),n.d(e,"mergeMapTo",function(){return Mn}),n.d(e,"mergeScan",function(){return Rn}),n.d(e,"min",function(){return Yn}),n.d(e,"multicast",function(){return Gn}),n.d(e,"observeOn",function(){return Jn}),n.d(e,"onErrorResumeNext",function(){return nr}),n.d(e,"pairwise",function(){return or}),n.d(e,"partition",function(){return ur}),n.d(e,"pluck",function(){return lr}),n.d(e,"publish",function(){return hr}),n.d(e,"publishBehavior",function(){return pr}),n.d(e,"publishLast",function(){return mr}),n.d(e,"publishReplay",function(){return xr}),n.d(e,"race",function(){return jr}),n.d(e,"reduce",function(){return qn}),n.d(e,"repeat",function(){return Or}),n.d(e,"repeatWhen",function(){return Fr}),n.d(e,"retry",function(){return Vr}),n.d(e,"retryWhen",function(){return Ir}),n.d(e,"refCount",function(){return Wn}),n.d(e,"sample",function(){return qr}),n.d(e,"sampleTime",function(){return Mr}),n.d(e,"scan",function(){return In}),n.d(e,"sequenceEqual",function(){return Yr}),n.d(e,"share",function(){return Lr}),n.d(e,"shareReplay",function(){return Kr}),n.d(e,"single",function(){return Gr}),n.d(e,"skip",function(){return Zr}),n.d(e,"skipLast",function(){return ni}),n.d(e,"skipUntil",function(){return oi}),n.d(e,"skipWhile",function(){return ci}),n.d(e,"startWith",function(){return hi}),n.d(e,"subscribeOn",function(){return gi}),n.d(e,"switchAll",function(){return Oi}),n.d(e,"switchMap",function(){return wi}),n.d(e,"switchMapTo",function(){return _i}),n.d(e,"take",function(){return Ie}),n.d(e,"takeLast",function(){return jn}),n.d(e,"takeUntil",function(){return Ei}),n.d(e,"takeWhile",function(){return Ni}),n.d(e,"tap",function(){return Ti}),n.d(e,"throttle",function(){return qi}),n.d(e,"throttleTime",function(){return Mi}),n.d(e,"throwIfEmpty",function(){return Ne}),n.d(e,"timeInterval",function(){return Yi}),n.d(e,"timeout",function(){return Gi}),n.d(e,"timeoutWith",function(){return Ui}),n.d(e,"timestamp",function(){return Qi}),n.d(e,"toArray",function(){return to}),n.d(e,"window",function(){return eo}),n.d(e,"windowCount",function(){return io}),n.d(e,"windowTime",function(){return ao}),n.d(e,"windowToggle",function(){return mo}),n.d(e,"windowWhen",function(){return vo}),n.d(e,"withLatestFrom",function(){return wo}),n.d(e,"zip",function(){return No}),n.d(e,"zipAll",function(){return Vo})}}]);
from __future__ import unicode_literals from moto.core.responses import BaseResponse from .models import support_backends import json class SupportResponse(BaseResponse): SERVICE_NAME = "support" @property def support_backend(self): return support_backends[self.region] def describe_trusted_advisor_checks(self): language = self._get_param("language") checks = self.support_backend.describe_trusted_advisor_checks( language=language, ) return json.dumps({"checks": checks}) def refresh_trusted_advisor_check(self): check_id = self._get_param("checkId") status = self.support_backend.refresh_trusted_advisor_check(check_id=check_id,) return json.dumps(status)
const fs = require('fs') const path = require('path') const loader = async dir => { const result = await require(dir) return result } const checkDirectory = dir => { let result = false try { const state = fs.statSync(dir) if (state && state.isDirectory()) { result = true } } catch (err) { console.error(`"${dir}" is not a directory!`) } return result } const folder = dir => { let vessel = [] let result = [] const stat = checkDirectory(dir) if (stat) { vessel = fs.readdirSync(dir) } vessel.forEach(name => { const file = path.join(dir, name) const stat = checkDirectory(file) if (stat) { result = result.concat(folder(file)) } else { result.push({ name: name.split('.')[0], module: file }) } }) return result } module.exports = (config) => { const { app } = config if (typeof app !== 'object') { throw new Error(`'app' object is not callable`) } const defaults = { paths: '../../server/routers' } const option = Object.assign({}, defaults, config || {}) const gather = folder(path.join(__dirname, option.paths)) gather.forEach(async crl => { const pass = /\.js$/gi.test(crl.module) if (!pass) { return false } const res = await loader(crl.module) app.use(res.routes()).use(res.allowedMethods()) }) }
"use strict"; /// <reference types="homeworks" /> 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); }; Object.defineProperty(exports, "__esModule", { value: true }); var core_1 = require("@angular/core"); var forms_1 = require("@angular/forms"); var manager_1 = require("./src/core/manager"); var main_1 = require("./src/components/spinner/main"); var main_2 = require("./src/components/dropdown/main"); var main_3 = require("./src/components/checkbox/main"); var main_4 = require("./src/components/toggle/main"); var main_5 = require("./src/components/tab/main"); var main_6 = require("./src/components/step/main"); var main_7 = require("./src/components/input/main"); var main_8 = require("./src/components/ripple/main"); var HomeworksModule = /** @class */ (function () { function HomeworksModule() { manager_1.HomeworksManager.disableHook(); } HomeworksModule = __decorate([ core_1.NgModule({ imports: [ forms_1.FormsModule ], exports: [ forms_1.FormsModule, main_1.WorksSpinner, main_1.WorksOption, main_2.WorksDropdown, main_3.WorksCheckbox, main_4.WorksToggle, main_5.WorksTab, main_5.WorksTabItem, main_5.WorksTabTitle, main_6.WorksStep, main_6.WorksStepItem, main_6.WorksStepTitle, main_7.WorksInput, main_8.WorksRipple ], providers: [], declarations: [ main_1.WorksSpinner, main_1.WorksOption, main_2.WorksDropdown, main_3.WorksCheckbox, main_4.WorksToggle, main_5.WorksTab, main_5.WorksTabItem, main_5.WorksTabTitle, main_6.WorksStep, main_6.WorksStepItem, main_6.WorksStepTitle, main_7.WorksInput, main_8.WorksRipple ] }), __metadata("design:paramtypes", []) ], HomeworksModule); return HomeworksModule; }()); exports.HomeworksModule = HomeworksModule; //# sourceMappingURL=index.js.map
import day2in class Entry: def __init__(self, strIn): self.m_strPass = None self.m_ch = None self.m_cChMin = 0 self.m_cChMax = 0 self.ParseLine(strIn) def ParseLine(self, strIn): # line looks like this: min-max letter: password lStr = strIn.split(':') self.m_strPass = lStr[1].strip() strRule = lStr[0].strip() lStr = strRule.split(' ') self.m_ch = lStr[1] strRange = lStr[0] lStr = strRange.split('-') self.m_cChMin = int(lStr[0]) self.m_cChMax = int(lStr[1]) def FIsValid(self): # calculate the count of letters we care about cCh = 0 for ch in self.m_strPass: if ch == self.m_ch: cCh += 1 # check if the count of letters is invalid if cCh < self.m_cChMin: return False if cCh > self.m_cChMax: return False return True def FIsValid2(self): cChMatch = 0 # check characters for iCh in [self.m_cChMin, self.m_cChMax]: if iCh <= len(self.m_strPass): if self.m_strPass[iCh - 1] == self.m_ch: cChMatch += 1 return cChMatch == 1 def Day2Part1(): # split apart the lines into rules and password lEntry = [] for strLine in day2in.lStr: lEntry.append(Entry(strLine)) # check if the password matches the rules cEntryValid = 0 for entry in lEntry: if entry.FIsValid2(): cEntryValid += 1 print(cEntryValid) if __name__ == '__main__': Day2Part1()
#! /usr/bin/env python # # Deployment script to set up containers locally import docker import re import os import time import sys import socket import stat from plumbum import SshMachine # --- The role instances to deploy locally --- # roleInstances = \ [ { "Name": "frontEnd1", "Role": "frontEnd" }, { "Name": "frontEnd2", "Role": "frontEnd" } ] # -------------------------------------------- # if os.name != "nt": import fcntl import struct def get_interface_ip(ifname): s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) return socket.inet_ntoa(fcntl.ioctl(s.fileno(), 0x8915, struct.pack('256s', ifname[:15]))[20:24]) def getLocalIp(): if len(sys.argv) > 1: return sys.argv[1] ip = socket.gethostbyname(socket.gethostname()) if ip.startswith("127.") and os.name != "nt": interfaces = [ "eth0", "eth1", "eth2", "wlan0", "wlan1", "wifi0", "ath0", "ath1", "ppp0", ] for ifname in interfaces: try: ip = get_interface_ip(ifname) break except IOError: pass return ip print '--- Starting local Jade deployment on local machine[{}] ---'.format(getLocalIp()) with docker.Client(base_url = 'unix://var/run/docker.sock') as dockerClient: def removeAllLocalContainers(): print 'Removing all existing local containers' existingContainers = filter(lambda c: re.search(r'local_', c['Names'][0]), dockerClient.containers(all = True)) if existingContainers: for container in existingContainers: if re.search(r'^Up', container['Status']): print '>>> Container {} is running, stopping it...'.format(container['Id']) dockerClient.stop(container['Id']) print '>>> Removing existing container: ', container['Id'] dockerClient.remove_container(container['Id']) def bootstrapCloudMama(): print 'Bootstrapping CloudMama...' cmContainer = dockerClient.create_container( image = 'jade_cloudmama', name = 'local_cmInstance', command = '/bin/bash /opt/jade/startup.sh', ports = [22]) dockerClient.start(cmContainer, publish_all_ports = True) print 'CM instance id = ', cmContainer['Id'] return dockerClient.port(cmContainer, 22)[0]['HostPort'] def createRemoteManagementShell(sshPort): print 'Creating remote management shell...' rmsFile = './rmsConnect.sh' with open(rmsFile, 'w') as f: lines = \ [ "#!/bin/bash\n", "ssh -i /home/jade/.ssh/id_rsa -o 'StrictHostKeyChecking no' -p {} jade@localhost\n".format(sshPort) ] f.writelines(lines) os.chmod(rmsFile, stat.S_IRWXU | stat.S_IRWXG | stat.S_IRWXO) def deployInstance(remote, instance): print 'Deploying instance local_' + instance['Name'] python = remote['python'] python['/opt/jade/remoteScripts/deployInstance.py', str(getLocalIp()), instance['Role'], instance['Name']]() removeAllLocalContainers() cmSshPort = bootstrapCloudMama() createRemoteManagementShell(cmSshPort) print 'Connecting to CM instance at localhost:{} to deploy other roles...'.format(cmSshPort) attempt = 0 while True: try: if attempt >= 5: 'Failed to connect to CM instance!' sys.exit(1) time.sleep(10) attempt += 1 with SshMachine('localhost', port = cmSshPort, user = 'jade', keyfile = '/home/jade/.ssh/id_rsa', ssh_opts = ['-o StrictHostKeyChecking=no']) as remote: for instance in roleInstances: deployInstance(remote, instance) break; except Exception as e: print 'Connection attempt failed:' print e print 'Sleeping before a retry...' print 'CM public SSH endpoint is localhost:', cmSshPort print '--- Deployment is complete. Use the remote management shell to control the environment ---'
// Jobs service used to communicate Jobs REST endpoints (function () { 'use strict'; angular .module('jobs') .factory('JobsService', JobsService); JobsService.$inject = ['$resource']; function JobsService($resource) { return $resource('api/jobs/:jobId', { jobId: '@_id' }, { update: { method: 'PUT' } }); } }());
define([ '../Core/BoundingSphere', '../Core/Cartesian2', '../Core/Cartesian3', '../Core/Cartesian4', '../Core/Cartographic', '../Core/Check', '../Core/clone', '../Core/Color', '../Core/combine', '../Core/createGuid', '../Core/defaultValue', '../Core/defined', '../Core/defineProperties', '../Core/destroyObject', '../Core/DeveloperError', '../Core/DistanceDisplayCondition', '../Core/FeatureDetection', '../Core/getAbsoluteUri', '../Core/getMagic', '../Core/getStringFromTypedArray', '../Core/IndexDatatype', '../Core/isArray', '../Core/loadCRN', '../Core/loadImageFromTypedArray', '../Core/loadKTX', '../Core/Math', '../Core/Matrix3', '../Core/Matrix4', '../Core/PixelFormat', '../Core/PrimitiveType', '../Core/Quaternion', '../Core/Resource', '../Core/Transforms', '../Core/WebGLConstants', '../Renderer/Buffer', '../Renderer/BufferUsage', '../Renderer/DrawCommand', '../Renderer/Pass', '../Renderer/RenderState', '../Renderer/Sampler', '../Renderer/ShaderProgram', '../Renderer/ShaderSource', '../Renderer/Texture', '../Renderer/TextureMinificationFilter', '../Renderer/TextureWrap', '../Renderer/VertexArray', '../ThirdParty/GltfPipeline/addDefaults', '../ThirdParty/GltfPipeline/addPipelineExtras', '../ThirdParty/GltfPipeline/ForEach', '../ThirdParty/GltfPipeline/getAccessorByteStride', '../ThirdParty/GltfPipeline/hasExtension', '../ThirdParty/GltfPipeline/numberOfComponentsForType', '../ThirdParty/GltfPipeline/parseGlb', '../ThirdParty/GltfPipeline/removePipelineExtras', '../ThirdParty/GltfPipeline/updateVersion', '../ThirdParty/when', './Axis', './BlendingState', './ClippingPlaneCollection', './ColorBlendMode', './DracoLoader', './getClipAndStyleCode', './getClippingFunction', './HeightReference', './JobType', './ModelAnimationCache', './ModelAnimationCollection', './ModelLoadResources', './ModelMaterial', './ModelMesh', './ModelNode', './ModelUtility', './OctahedralProjectedCubeMap', './processModelMaterialsCommon', './processPbrMaterials', './SceneMode', './ShadowMode' ], function( BoundingSphere, Cartesian2, Cartesian3, Cartesian4, Cartographic, Check, clone, Color, combine, createGuid, defaultValue, defined, defineProperties, destroyObject, DeveloperError, DistanceDisplayCondition, FeatureDetection, getAbsoluteUri, getMagic, getStringFromTypedArray, IndexDatatype, isArray, loadCRN, loadImageFromTypedArray, loadKTX, CesiumMath, Matrix3, Matrix4, PixelFormat, PrimitiveType, Quaternion, Resource, Transforms, WebGLConstants, Buffer, BufferUsage, DrawCommand, Pass, RenderState, Sampler, ShaderProgram, ShaderSource, Texture, TextureMinificationFilter, TextureWrap, VertexArray, addDefaults, addPipelineExtras, ForEach, getAccessorByteStride, hasExtension, numberOfComponentsForType, parseGlb, removePipelineExtras, updateVersion, when, Axis, BlendingState, ClippingPlaneCollection, ColorBlendMode, DracoLoader, getClipAndStyleCode, getClippingFunction, HeightReference, JobType, ModelAnimationCache, ModelAnimationCollection, ModelLoadResources, ModelMaterial, ModelMesh, ModelNode, ModelUtility, OctahedralProjectedCubeMap, processModelMaterialsCommon, processPbrMaterials, SceneMode, ShadowMode) { 'use strict'; // Bail out if the browser doesn't support typed arrays, to prevent the setup function // from failing, since we won't be able to create a WebGL context anyway. if (!FeatureDetection.supportsTypedArrays()) { return {}; } var boundingSphereCartesian3Scratch = new Cartesian3(); var ModelState = ModelUtility.ModelState; // glTF MIME types discussed in https://github.com/KhronosGroup/glTF/issues/412 and https://github.com/KhronosGroup/glTF/issues/943 var defaultModelAccept = 'model/gltf-binary,model/gltf+json;q=0.8,application/json;q=0.2,*/*;q=0.01'; /////////////////////////////////////////////////////////////////////////// function setCachedGltf(model, cachedGltf) { model._cachedGltf = cachedGltf; } // glTF JSON can be big given embedded geometry, textures, and animations, so we // cache it across all models using the same url/cache-key. This also reduces the // slight overhead in assigning defaults to missing values. // // Note that this is a global cache, compared to renderer resources, which // are cached per context. function CachedGltf(options) { this._gltf = options.gltf; this.ready = options.ready; this.modelsToLoad = []; this.count = 0; } defineProperties(CachedGltf.prototype, { gltf : { set : function(value) { this._gltf = value; }, get : function() { return this._gltf; } } }); CachedGltf.prototype.makeReady = function(gltfJson) { this.gltf = gltfJson; var models = this.modelsToLoad; var length = models.length; for (var i = 0; i < length; ++i) { var m = models[i]; if (!m.isDestroyed()) { setCachedGltf(m, this); } } this.modelsToLoad = undefined; this.ready = true; }; var gltfCache = {}; var uriToGuid = {}; /////////////////////////////////////////////////////////////////////////// /** * A 3D model based on glTF, the runtime asset format for WebGL, OpenGL ES, and OpenGL. * <p> * Cesium includes support for geometry and materials, glTF animations, and glTF skinning. * In addition, individual glTF nodes are pickable with {@link Scene#pick} and animatable * with {@link Model#getNode}. glTF cameras and lights are not currently supported. * </p> * <p> * An external glTF asset is created with {@link Model.fromGltf}. glTF JSON can also be * created at runtime and passed to this constructor function. In either case, the * {@link Model#readyPromise} is resolved when the model is ready to render, i.e., * when the external binary, image, and shader files are downloaded and the WebGL * resources are created. * </p> * <p> * Cesium supports glTF assets with the following extensions: * <ul> * <li> * {@link https://github.com/KhronosGroup/glTF/blob/master/extensions/1.0/Khronos/KHR_binary_glTF/README.md|KHR_binary_glTF} * </li><li> * {@link https://github.com/KhronosGroup/glTF/blob/master/extensions/1.0/Khronos/KHR_materials_common/README.md|KHR_materials_common} * </li><li> * {@link https://github.com/KhronosGroup/glTF/blob/master/extensions/1.0/Vendor/WEB3D_quantized_attributes/README.md|WEB3D_quantized_attributes} * </li><li> * {@link https://github.com/KhronosGroup/glTF/blob/master/extensions/2.0/Khronos/KHR_draco_mesh_compression/README.md|KHR_draco_mesh_compression} * </li><li> * {@link https://github.com/KhronosGroup/glTF/blob/master/extensions/2.0/Khronos/KHR_techniques_webgl/README.md|KHR_techniques_webgl} * </li><li> * {@link https://github.com/KhronosGroup/glTF/blob/master/extensions/2.0/Khronos/KHR_blend/README.md|KHR_blend} * </li><li> * {@link https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_unlit/README.md|KHR_materials_unlit} * </li><li> * {@link https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_pbrSpecularGlossiness/README.md|KHR_materials_pbrSpecularGlossiness} * </li> * </ul> * </p> * <p> * For high-precision rendering, Cesium supports the {@link https://github.com/KhronosGroup/glTF/blob/master/extensions/1.0/Vendor/CESIUM_RTC/README.md|CESIUM_RTC} extension, which introduces the * CESIUM_RTC_MODELVIEW parameter semantic that says the node is in WGS84 coordinates translated * relative to a local origin. * </p> * * @alias Model * @constructor * * @param {Object} [options] Object with the following properties: * @param {Object|ArrayBuffer|Uint8Array} [options.gltf] A glTF JSON object, or a binary glTF buffer. * @param {Resource|String} [options.basePath=''] The base path that paths in the glTF JSON are relative to. * @param {Boolean} [options.show=true] Determines if the model primitive will be shown. * @param {Matrix4} [options.modelMatrix=Matrix4.IDENTITY] The 4x4 transformation matrix that transforms the model from model to world coordinates. * @param {Number} [options.scale=1.0] A uniform scale applied to this model. * @param {Number} [options.minimumPixelSize=0.0] The approximate minimum pixel size of the model regardless of zoom. * @param {Number} [options.maximumScale] The maximum scale size of a model. An upper limit for minimumPixelSize. * @param {Object} [options.id] A user-defined object to return when the model is picked with {@link Scene#pick}. * @param {Boolean} [options.allowPicking=true] When <code>true</code>, each glTF mesh and primitive is pickable with {@link Scene#pick}. * @param {Boolean} [options.incrementallyLoadTextures=true] Determine if textures may continue to stream in after the model is loaded. * @param {Boolean} [options.asynchronous=true] Determines if model WebGL resource creation will be spread out over several frames or block until completion once all glTF files are loaded. * @param {Boolean} [options.clampAnimations=true] Determines if the model's animations should hold a pose over frames where no keyframes are specified. * @param {ShadowMode} [options.shadows=ShadowMode.ENABLED] Determines whether the model casts or receives shadows from each light source. * @param {Boolean} [options.debugShowBoundingVolume=false] For debugging only. Draws the bounding sphere for each draw command in the model. * @param {Boolean} [options.debugWireframe=false] For debugging only. Draws the model in wireframe. * @param {HeightReference} [options.heightReference] Determines how the model is drawn relative to terrain. * @param {Scene} [options.scene] Must be passed in for models that use the height reference property. * @param {DistanceDisplayCondition} [options.distanceDisplayCondition] The condition specifying at what distance from the camera that this model will be displayed. * @param {Color} [options.color=Color.WHITE] A color that blends with the model's rendered color. * @param {ColorBlendMode} [options.colorBlendMode=ColorBlendMode.HIGHLIGHT] Defines how the color blends with the model. * @param {Number} [options.colorBlendAmount=0.5] Value used to determine the color strength when the <code>colorBlendMode</code> is <code>MIX</code>. A value of 0.0 results in the model's rendered color while a value of 1.0 results in a solid color, with any value in-between resulting in a mix of the two. * @param {Color} [options.silhouetteColor=Color.RED] The silhouette color. If more than 256 models have silhouettes enabled, there is a small chance that overlapping models will have minor artifacts. * @param {Number} [options.silhouetteSize=0.0] The size of the silhouette in pixels. * @param {ClippingPlaneCollection} [options.clippingPlanes] The {@link ClippingPlaneCollection} used to selectively disable rendering the model. * @param {Boolean} [options.dequantizeInShader=true] Determines if a {@link https://github.com/google/draco|Draco} encoded model is dequantized on the GPU. This decreases total memory usage for encoded models. * @param {Cartesian2} [options.imageBasedLightingFactor=Cartesian2(1.0, 1.0)] Scales diffuse and specular image-based lighting from the earth, sky, atmosphere and star skybox. * @param {Cartesian3} [options.lightColor] The color and intensity of the sunlight used to shade the model. * @param {Number} [options.luminanceAtZenith=0.5] The sun's luminance at the zenith in kilo candela per meter squared to use for this model's procedural environment map. * @param {Cartesian3[]} [options.sphericalHarmonicCoefficients] The third order spherical harmonic coefficients used for the diffuse color of image-based lighting. * @param {String} [options.specularEnvironmentMaps] A URL to a KTX file that contains a cube map of the specular lighting and the convoluted specular mipmaps. * * @see Model.fromGltf * * @demo {@link https://cesiumjs.org/Cesium/Apps/Sandcastle/index.html?src=3D%20Models.html|Cesium Sandcastle Models Demo} */ function Model(options) { options = defaultValue(options, defaultValue.EMPTY_OBJECT); var cacheKey = options.cacheKey; this._cacheKey = cacheKey; this._cachedGltf = undefined; this._releaseGltfJson = defaultValue(options.releaseGltfJson, false); var cachedGltf; if (defined(cacheKey) && defined(gltfCache[cacheKey]) && gltfCache[cacheKey].ready) { // glTF JSON is in cache and ready cachedGltf = gltfCache[cacheKey]; ++cachedGltf.count; } else { // glTF was explicitly provided, e.g., when a user uses the Model constructor directly var gltf = options.gltf; if (defined(gltf)) { if (gltf instanceof ArrayBuffer) { gltf = new Uint8Array(gltf); } if (gltf instanceof Uint8Array) { // Binary glTF var parsedGltf = parseGlb(gltf); cachedGltf = new CachedGltf({ gltf : parsedGltf, ready : true }); } else { // Normal glTF (JSON) cachedGltf = new CachedGltf({ gltf : options.gltf, ready : true }); } cachedGltf.count = 1; if (defined(cacheKey)) { gltfCache[cacheKey] = cachedGltf; } } } setCachedGltf(this, cachedGltf); var basePath = defaultValue(options.basePath, ''); this._resource = Resource.createIfNeeded(basePath); /** * Determines if the model primitive will be shown. * * @type {Boolean} * * @default true */ this.show = defaultValue(options.show, true); /** * The silhouette color. * * @type {Color} * * @default Color.RED */ this.silhouetteColor = defaultValue(options.silhouetteColor, Color.RED); this._silhouetteColor = new Color(); this._silhouetteColorPreviousAlpha = 1.0; this._normalAttributeName = undefined; /** * The size of the silhouette in pixels. * * @type {Number} * * @default 0.0 */ this.silhouetteSize = defaultValue(options.silhouetteSize, 0.0); /** * The 4x4 transformation matrix that transforms the model from model to world coordinates. * When this is the identity matrix, the model is drawn in world coordinates, i.e., Earth's WGS84 coordinates. * Local reference frames can be used by providing a different transformation matrix, like that returned * by {@link Transforms.eastNorthUpToFixedFrame}. * * @type {Matrix4} * * @default {@link Matrix4.IDENTITY} * * @example * var origin = Cesium.Cartesian3.fromDegrees(-95.0, 40.0, 200000.0); * m.modelMatrix = Cesium.Transforms.eastNorthUpToFixedFrame(origin); */ this.modelMatrix = Matrix4.clone(defaultValue(options.modelMatrix, Matrix4.IDENTITY)); this._modelMatrix = Matrix4.clone(this.modelMatrix); this._clampedModelMatrix = undefined; /** * A uniform scale applied to this model before the {@link Model#modelMatrix}. * Values greater than <code>1.0</code> increase the size of the model; values * less than <code>1.0</code> decrease. * * @type {Number} * * @default 1.0 */ this.scale = defaultValue(options.scale, 1.0); this._scale = this.scale; /** * The approximate minimum pixel size of the model regardless of zoom. * This can be used to ensure that a model is visible even when the viewer * zooms out. When <code>0.0</code>, no minimum size is enforced. * * @type {Number} * * @default 0.0 */ this.minimumPixelSize = defaultValue(options.minimumPixelSize, 0.0); this._minimumPixelSize = this.minimumPixelSize; /** * The maximum scale size for a model. This can be used to give * an upper limit to the {@link Model#minimumPixelSize}, ensuring that the model * is never an unreasonable scale. * * @type {Number} */ this.maximumScale = options.maximumScale; this._maximumScale = this.maximumScale; /** * User-defined object returned when the model is picked. * * @type Object * * @default undefined * * @see Scene#pick */ this.id = options.id; this._id = options.id; /** * Returns the height reference of the model * * @type {HeightReference} * * @default HeightReference.NONE */ this.heightReference = defaultValue(options.heightReference, HeightReference.NONE); this._heightReference = this.heightReference; this._heightChanged = false; this._removeUpdateHeightCallback = undefined; var scene = options.scene; this._scene = scene; if (defined(scene) && defined(scene.terrainProviderChanged)) { this._terrainProviderChangedCallback = scene.terrainProviderChanged.addEventListener(function() { this._heightChanged = true; }, this); } /** * Used for picking primitives that wrap a model. * * @private */ this._pickObject = options.pickObject; this._allowPicking = defaultValue(options.allowPicking, true); this._ready = false; this._readyPromise = when.defer(); /** * The currently playing glTF animations. * * @type {ModelAnimationCollection} */ this.activeAnimations = new ModelAnimationCollection(this); /** * Determines if the model's animations should hold a pose over frames where no keyframes are specified. * * @type {Boolean} */ this.clampAnimations = defaultValue(options.clampAnimations, true); this._defaultTexture = undefined; this._incrementallyLoadTextures = defaultValue(options.incrementallyLoadTextures, true); this._asynchronous = defaultValue(options.asynchronous, true); /** * Determines whether the model casts or receives shadows from each light source. * * @type {ShadowMode} * * @default ShadowMode.ENABLED */ this.shadows = defaultValue(options.shadows, ShadowMode.ENABLED); this._shadows = this.shadows; /** * A color that blends with the model's rendered color. * * @type {Color} * * @default Color.WHITE */ this.color = defaultValue(options.color, Color.WHITE); this._color = new Color(); this._colorPreviousAlpha = 1.0; /** * Defines how the color blends with the model. * * @type {ColorBlendMode} * * @default ColorBlendMode.HIGHLIGHT */ this.colorBlendMode = defaultValue(options.colorBlendMode, ColorBlendMode.HIGHLIGHT); /** * Value used to determine the color strength when the <code>colorBlendMode</code> is <code>MIX</code>. * A value of 0.0 results in the model's rendered color while a value of 1.0 results in a solid color, with * any value in-between resulting in a mix of the two. * * @type {Number} * * @default 0.5 */ this.colorBlendAmount = defaultValue(options.colorBlendAmount, 0.5); this._colorShadingEnabled = false; this._clippingPlanes = undefined; this.clippingPlanes = options.clippingPlanes; // Used for checking if shaders need to be regenerated due to clipping plane changes. this._clippingPlanesState = 0; // If defined, use this matrix to position the clipping planes instead of the modelMatrix. // This is so that when models are part of a tileset they all get clipped relative // to the root tile. this.clippingPlanesOriginMatrix = undefined; /** * This property is for debugging only; it is not for production use nor is it optimized. * <p> * Draws the bounding sphere for each draw command in the model. A glTF primitive corresponds * to one draw command. A glTF mesh has an array of primitives, often of length one. * </p> * * @type {Boolean} * * @default false */ this.debugShowBoundingVolume = defaultValue(options.debugShowBoundingVolume, false); this._debugShowBoundingVolume = false; /** * This property is for debugging only; it is not for production use nor is it optimized. * <p> * Draws the model in wireframe. * </p> * * @type {Boolean} * * @default false */ this.debugWireframe = defaultValue(options.debugWireframe, false); this._debugWireframe = false; this._distanceDisplayCondition = options.distanceDisplayCondition; // Undocumented options this._addBatchIdToGeneratedShaders = options.addBatchIdToGeneratedShaders; this._precreatedAttributes = options.precreatedAttributes; this._vertexShaderLoaded = options.vertexShaderLoaded; this._fragmentShaderLoaded = options.fragmentShaderLoaded; this._uniformMapLoaded = options.uniformMapLoaded; this._pickIdLoaded = options.pickIdLoaded; this._ignoreCommands = defaultValue(options.ignoreCommands, false); this._requestType = options.requestType; this._upAxis = defaultValue(options.upAxis, Axis.Y); this._gltfForwardAxis = Axis.Z; this._forwardAxis = options.forwardAxis; /** * @private * @readonly */ this.cull = defaultValue(options.cull, true); /** * @private * @readonly */ this.opaquePass = defaultValue(options.opaquePass, Pass.OPAQUE); this._computedModelMatrix = new Matrix4(); // Derived from modelMatrix and scale this._clippingPlaneModelViewMatrix = Matrix4.clone(Matrix4.IDENTITY); // Derived from modelMatrix, scale, and the current view matrix this._initialRadius = undefined; // Radius without model's scale property, model-matrix scale, animations, or skins this._boundingSphere = undefined; this._scaledBoundingSphere = new BoundingSphere(); this._state = ModelState.NEEDS_LOAD; this._loadResources = undefined; this._mode = undefined; this._perNodeShowDirty = false; // true when the Cesium API was used to change a node's show property this._cesiumAnimationsDirty = false; // true when the Cesium API, not a glTF animation, changed a node transform this._dirty = false; // true when the model was transformed this frame this._maxDirtyNumber = 0; // Used in place of a dirty boolean flag to avoid an extra graph traversal this._runtime = { animations : undefined, rootNodes : undefined, nodes : undefined, // Indexed with the node's index nodesByName : undefined, // Indexed with name property in the node skinnedNodes : undefined, meshesByName : undefined, // Indexed with the name property in the mesh materialsByName : undefined, // Indexed with the name property in the material materialsById : undefined // Indexed with the material's index }; this._uniformMaps = {}; // Not cached since it can be targeted by glTF animation this._extensionsUsed = undefined; // Cached used glTF extensions this._extensionsRequired = undefined; // Cached required glTF extensions this._quantizedUniforms = {}; // Quantized uniforms for each program for WEB3D_quantized_attributes this._programPrimitives = {}; this._rendererResources = { // Cached between models with the same url/cache-key buffers : {}, vertexArrays : {}, programs : {}, sourceShaders : {}, silhouettePrograms : {}, textures : {}, samplers : {}, renderStates : {} }; this._cachedRendererResources = undefined; this._loadRendererResourcesFromCache = false; this._dequantizeInShader = defaultValue(options.dequantizeInShader, true); this._decodedData = {}; this._cachedGeometryByteLength = 0; this._cachedTexturesByteLength = 0; this._geometryByteLength = 0; this._texturesByteLength = 0; this._trianglesLength = 0; // Hold references for shader reconstruction. // Hold these separately because _cachedGltf may get released (this.releaseGltfJson) this._sourceTechniques = {}; this._sourcePrograms = {}; this._quantizedVertexShaders = {}; this._nodeCommands = []; this._pickIds = []; // CESIUM_RTC extension this._rtcCenter = undefined; // reference to either 3D or 2D this._rtcCenterEye = undefined; // in eye coordinates this._rtcCenter3D = undefined; // in world coordinates this._rtcCenter2D = undefined; // in projected world coordinates this._keepPipelineExtras = options.keepPipelineExtras; // keep the buffers in memory for use in other applications this._sourceVersion = undefined; this._sourceKHRTechniquesWebGL = undefined; this._imageBasedLightingFactor = new Cartesian2(1.0, 1.0); Cartesian2.clone(options.imageBasedLightingFactor, this._imageBasedLightingFactor); this._lightColor = Cartesian3.clone(options.lightColor); this._luminanceAtZenith = undefined; this.luminanceAtZenith = defaultValue(options.luminanceAtZenith, 0.5); this._sphericalHarmonicCoefficients = options.sphericalHarmonicCoefficients; this._specularEnvironmentMaps = options.specularEnvironmentMaps; this._shouldUpdateSpecularMapAtlas = true; this._specularEnvironmentMapAtlas = undefined; this._useDefaultSphericalHarmonics = false; this._useDefaultSpecularMaps = false; this._shouldRegenerateShaders = false; } defineProperties(Model.prototype, { /** * The object for the glTF JSON, including properties with default values omitted * from the JSON provided to this model. * * @memberof Model.prototype * * @type {Object} * @readonly * * @default undefined */ gltf : { get : function() { return defined(this._cachedGltf) ? this._cachedGltf.gltf : undefined; } }, /** * When <code>true</code>, the glTF JSON is not stored with the model once the model is * loaded (when {@link Model#ready} is <code>true</code>). This saves memory when * geometry, textures, and animations are embedded in the .gltf file, which is the * default for the {@link https://cesiumjs.org/convertmodel.html|Cesium model converter}. * This is especially useful for cases like 3D buildings, where each .gltf model is unique * and caching the glTF JSON is not effective. * * @memberof Model.prototype * * @type {Boolean} * @readonly * * @default false * * @private */ releaseGltfJson : { get : function() { return this._releaseGltfJson; } }, /** * The key identifying this model in the model cache for glTF JSON, renderer resources, and animations. * Caching saves memory and improves loading speed when several models with the same url are created. * <p> * This key is automatically generated when the model is created with {@link Model.fromGltf}. If the model * is created directly from glTF JSON using the {@link Model} constructor, this key can be manually * provided; otherwise, the model will not be changed. * </p> * * @memberof Model.prototype * * @type {String} * @readonly * * @private */ cacheKey : { get : function() { return this._cacheKey; } }, /** * The base path that paths in the glTF JSON are relative to. The base * path is the same path as the path containing the .gltf file * minus the .gltf file, when binary, image, and shader files are * in the same directory as the .gltf. When this is <code>''</code>, * the app's base path is used. * * @memberof Model.prototype * * @type {String} * @readonly * * @default '' */ basePath : { get : function() { return this._resource.url; } }, /** * The model's bounding sphere in its local coordinate system. This does not take into * account glTF animations and skins nor does it take into account {@link Model#minimumPixelSize}. * * @memberof Model.prototype * * @type {BoundingSphere} * @readonly * * @default undefined * * @exception {DeveloperError} The model is not loaded. Use Model.readyPromise or wait for Model.ready to be true. * * @example * // Center in WGS84 coordinates * var center = Cesium.Matrix4.multiplyByPoint(model.modelMatrix, model.boundingSphere.center, new Cesium.Cartesian3()); */ boundingSphere : { get : function() { //>>includeStart('debug', pragmas.debug); if (this._state !== ModelState.LOADED) { throw new DeveloperError('The model is not loaded. Use Model.readyPromise or wait for Model.ready to be true.'); } //>>includeEnd('debug'); var modelMatrix = this.modelMatrix; if ((this.heightReference !== HeightReference.NONE) && this._clampedModelMatrix) { modelMatrix = this._clampedModelMatrix; } var nonUniformScale = Matrix4.getScale(modelMatrix, boundingSphereCartesian3Scratch); var scale = defined(this.maximumScale) ? Math.min(this.maximumScale, this.scale) : this.scale; Cartesian3.multiplyByScalar(nonUniformScale, scale, nonUniformScale); var scaledBoundingSphere = this._scaledBoundingSphere; scaledBoundingSphere.center = Cartesian3.multiplyComponents(this._boundingSphere.center, nonUniformScale, scaledBoundingSphere.center); scaledBoundingSphere.radius = Cartesian3.maximumComponent(nonUniformScale) * this._initialRadius; if (defined(this._rtcCenter)) { Cartesian3.add(this._rtcCenter, scaledBoundingSphere.center, scaledBoundingSphere.center); } return scaledBoundingSphere; } }, /** * When <code>true</code>, this model is ready to render, i.e., the external binary, image, * and shader files were downloaded and the WebGL resources were created. This is set to * <code>true</code> right before {@link Model#readyPromise} is resolved. * * @memberof Model.prototype * * @type {Boolean} * @readonly * * @default false */ ready : { get : function() { return this._ready; } }, /** * Gets the promise that will be resolved when this model is ready to render, i.e., when the external binary, image, * and shader files were downloaded and the WebGL resources were created. * <p> * This promise is resolved at the end of the frame before the first frame the model is rendered in. * </p> * * @memberof Model.prototype * @type {Promise.<Model>} * @readonly * * @example * // Play all animations at half-speed when the model is ready to render * Cesium.when(model.readyPromise).then(function(model) { * model.activeAnimations.addAll({ * multiplier : 0.5 * }); * }).otherwise(function(error){ * window.alert(error); * }); * * @see Model#ready */ readyPromise : { get : function() { return this._readyPromise.promise; } }, /** * Determines if model WebGL resource creation will be spread out over several frames or * block until completion once all glTF files are loaded. * * @memberof Model.prototype * * @type {Boolean} * @readonly * * @default true */ asynchronous : { get : function() { return this._asynchronous; } }, /** * When <code>true</code>, each glTF mesh and primitive is pickable with {@link Scene#pick}. When <code>false</code>, GPU memory is saved. * * @memberof Model.prototype * * @type {Boolean} * @readonly * * @default true */ allowPicking : { get : function() { return this._allowPicking; } }, /** * Determine if textures may continue to stream in after the model is loaded. * * @memberof Model.prototype * * @type {Boolean} * @readonly * * @default true */ incrementallyLoadTextures : { get : function() { return this._incrementallyLoadTextures; } }, /** * Return the number of pending texture loads. * * @memberof Model.prototype * * @type {Number} * @readonly */ pendingTextureLoads : { get : function() { return defined(this._loadResources) ? this._loadResources.pendingTextureLoads : 0; } }, /** * Returns true if the model was transformed this frame * * @memberof Model.prototype * * @type {Boolean} * @readonly * * @private */ dirty : { get : function() { return this._dirty; } }, /** * Gets or sets the condition specifying at what distance from the camera that this model will be displayed. * @memberof Model.prototype * @type {DistanceDisplayCondition} * @default undefined */ distanceDisplayCondition : { get : function() { return this._distanceDisplayCondition; }, set : function(value) { //>>includeStart('debug', pragmas.debug); if (defined(value) && value.far <= value.near) { throw new DeveloperError('far must be greater than near'); } //>>includeEnd('debug'); this._distanceDisplayCondition = DistanceDisplayCondition.clone(value, this._distanceDisplayCondition); } }, extensionsUsed : { get : function() { if (!defined(this._extensionsUsed)) { this._extensionsUsed = ModelUtility.getUsedExtensions(this.gltf); } return this._extensionsUsed; } }, extensionsRequired : { get : function() { if (!defined(this._extensionsRequired)) { this._extensionsRequired = ModelUtility.getRequiredExtensions(this.gltf); } return this._extensionsRequired; } }, /** * Gets the model's up-axis. * By default models are y-up according to the glTF spec, however geo-referenced models will typically be z-up. * * @memberof Model.prototype * * @type {Number} * @default Axis.Y * @readonly * * @private */ upAxis : { get : function() { return this._upAxis; } }, /** * Gets the model's forward axis. * By default, glTF 2.0 models are z-forward according to the glTF spec, however older * glTF (1.0, 0.8) models used x-forward. Note that only Axis.X and Axis.Z are supported. * * @memberof Model.prototype * * @type {Number} * @default Axis.Z * @readonly * * @private */ forwardAxis : { get : function() { if (defined(this._forwardAxis)) { return this._forwardAxis; } return this._gltfForwardAxis; } }, /** * Gets the model's triangle count. * * @private */ trianglesLength : { get : function() { return this._trianglesLength; } }, /** * Gets the model's geometry memory in bytes. This includes all vertex and index buffers. * * @private */ geometryByteLength : { get : function() { return this._geometryByteLength; } }, /** * Gets the model's texture memory in bytes. * * @private */ texturesByteLength : { get : function() { return this._texturesByteLength; } }, /** * Gets the model's cached geometry memory in bytes. This includes all vertex and index buffers. * * @private */ cachedGeometryByteLength : { get : function() { return this._cachedGeometryByteLength; } }, /** * Gets the model's cached texture memory in bytes. * * @private */ cachedTexturesByteLength : { get : function() { return this._cachedTexturesByteLength; } }, /** * The {@link ClippingPlaneCollection} used to selectively disable rendering the model. * * @memberof Model.prototype * * @type {ClippingPlaneCollection} */ clippingPlanes : { get : function() { return this._clippingPlanes; }, set : function(value) { if (value === this._clippingPlanes) { return; } // Handle destroying, checking of unknown, checking for existing ownership ClippingPlaneCollection.setOwner(value, this, '_clippingPlanes'); } }, /** * @private */ pickIds : { get : function() { return this._pickIds; } }, /** * Cesium adds lighting from the earth, sky, atmosphere, and star skybox. This cartesian is used to scale the final * diffuse and specular lighting contribution from those sources to the final color. A value of 0.0 will disable those light sources. * * @memberof Model.prototype * * @type {Cartesian2} * @default Cartesian2(1.0, 1.0) */ imageBasedLightingFactor : { get : function() { return this._imageBasedLightingFactor; }, set : function(value) { //>>includeStart('debug', pragmas.debug); Check.typeOf.object('imageBasedLightingFactor', value); Check.typeOf.number.greaterThanOrEquals('imageBasedLightingFactor.x', value.x, 0.0); Check.typeOf.number.lessThanOrEquals('imageBasedLightingFactor.x', value.x, 1.0); Check.typeOf.number.greaterThanOrEquals('imageBasedLightingFactor.y', value.y, 0.0); Check.typeOf.number.lessThanOrEquals('imageBasedLightingFactor.y', value.y, 1.0); //>>includeEnd('debug'); var imageBasedLightingFactor = this._imageBasedLightingFactor; if ((value === imageBasedLightingFactor) || Cartesian2.equals(value, imageBasedLightingFactor)) { return; } this._shouldRegenerateShaders = this._shouldRegenerateShaders || (this._imageBasedLightingFactor.x > 0.0 && value.x === 0.0) || (this._imageBasedLightingFactor.x === 0.0 && value.x > 0.0); this._shouldRegenerateShaders = this._shouldRegenerateShaders || (this._imageBasedLightingFactor.y > 0.0 && value.y === 0.0) || (this._imageBasedLightingFactor.y === 0.0 && value.y > 0.0); Cartesian2.clone(value, this._imageBasedLightingFactor); } }, /** * The color and intensity of the sunlight used to shade the model. * <p> * For example, disabling additional light sources by setting <code>model.imageBasedLightingFactor = new Cesium.Cartesian2(0.0, 0.0)</code> will make the * model much darker. Here, increasing the intensity of the light source will make the model brighter. * </p> * * @memberof Model.prototype * * @type {Cartesian3} * @default undefined */ lightColor : { get : function() { return this._lightColor; }, set : function(value) { var lightColor = this._lightColor; if (value === lightColor || Cartesian3.equals(value, lightColor)) { return; } this._shouldRegenerateShaders = this._shouldRegenerateShaders || (defined(lightColor) && !defined(value)) || (defined(value) && !defined(lightColor)); this._lightColor = Cartesian3.clone(value, lightColor); } }, /** * The sun's luminance at the zenith in kilo candela per meter squared to use for this model's procedural environment map. * This is used when {@link Model#specularEnvironmentMaps} and {@link Model#sphericalHarmonicCoefficients} are not defined. * * @memberof Model.prototype * * @demo {@link https://cesiumjs.org/Cesium/Apps/Sandcastle/index.html?src=Image-Based Lighting.html|Sandcastle Image Based Lighting Demo} * @type {Number} * @default 0.5 */ luminanceAtZenith : { get : function() { return this._luminanceAtZenith; }, set : function(value) { var lum = this._luminanceAtZenith; if (value === lum) { return; } this._shouldRegenerateShaders = this._shouldRegenerateShaders || (defined(lum) && !defined(value)) || (defined(value) && !defined(lum)); this._luminanceAtZenith = value; } }, /** * The third order spherical harmonic coefficients used for the diffuse color of image-based lighting. When <code>undefined</code>, a diffuse irradiance * computed from the atmosphere color is used. * <p> * There are nine <code>Cartesian3</code> coefficients. * The order of the coefficients is: L<sub>00</sub>, L<sub>1-1</sub>, L<sub>10</sub>, L<sub>11</sub>, L<sub>2-2</sub>, L<sub>2-1</sub>, L<sub>20</sub>, L<sub>21</sub>, L<sub>22</sub> * </p> * * These values can be obtained by preprocessing the environment map using the <code>cmgen</code> tool of * {@link https://github.com/google/filament/releases | Google's Filament project}. This will also generate a KTX file that can be * supplied to {@link Model#specularEnvironmentMaps}. * * @memberof Model.prototype * * @type {Cartesian3[]} * @demo {@link https://cesiumjs.org/Cesium/Apps/Sandcastle/index.html?src=Image-Based Lighting.html|Sandcastle Image Based Lighting Demo} * @see {@link https://graphics.stanford.edu/papers/envmap/envmap.pdf|An Efficient Representation for Irradiance Environment Maps} */ sphericalHarmonicCoefficients : { get : function() { return this._sphericalHarmonicCoefficients; }, set : function(value) { //>>includeStart('debug', pragmas.debug); if (defined(value) && (!isArray(value) || value.length !== 9)) { throw new DeveloperError('sphericalHarmonicCoefficients must be an array of 9 Cartesian3 values.'); } //>>includeEnd('debug'); if (value === this._sphericalHarmonicCoefficients) { return; } this._sphericalHarmonicCoefficients = value; this._shouldRegenerateShaders = true; } }, /** * A URL to a KTX file that contains a cube map of the specular lighting and the convoluted specular mipmaps. * * @memberof Model.prototype * @demo {@link https://cesiumjs.org/Cesium/Apps/Sandcastle/index.html?src=Image-Based Lighting.html|Sandcastle Image Based Lighting Demo} * @type {String} * @see Model#sphericalHarmonicCoefficients */ specularEnvironmentMaps : { get : function() { return this._specularEnvironmentMaps; }, set : function(value) { this._shouldUpdateSpecularMapAtlas = this._shouldUpdateSpecularMapAtlas || value !== this._specularEnvironmentMaps; this._specularEnvironmentMaps = value; } } }); function silhouetteSupported(context) { return context.stencilBuffer; } function isColorShadingEnabled(model) { return !Color.equals(model.color, Color.WHITE) || (model.colorBlendMode !== ColorBlendMode.HIGHLIGHT); } function isClippingEnabled(model) { var clippingPlanes = model._clippingPlanes; return defined(clippingPlanes) && clippingPlanes.enabled && clippingPlanes.length !== 0; } /** * Determines if silhouettes are supported. * * @param {Scene} scene The scene. * @returns {Boolean} <code>true</code> if silhouettes are supported; otherwise, returns <code>false</code> */ Model.silhouetteSupported = function(scene) { return silhouetteSupported(scene.context); }; function containsGltfMagic(uint8Array) { var magic = getMagic(uint8Array); return magic === 'glTF'; } /** * <p> * Creates a model from a glTF asset. When the model is ready to render, i.e., when the external binary, image, * and shader files are downloaded and the WebGL resources are created, the {@link Model#readyPromise} is resolved. * </p> * <p> * The model can be a traditional glTF asset with a .gltf extension or a Binary glTF using the .glb extension. * </p> * <p> * Cesium supports glTF assets with the following extensions: * <ul> * <li> * {@link https://github.com/KhronosGroup/glTF/blob/master/extensions/1.0/Khronos/KHR_binary_glTF/README.md|KHR_binary_glTF} * </li><li> * {@link https://github.com/KhronosGroup/glTF/blob/master/extensions/1.0/Khronos/KHR_materials_common/README.md|KHR_materials_common} * </li><li> * {@link https://github.com/KhronosGroup/glTF/blob/master/extensions/1.0/Vendor/WEB3D_quantized_attributes/README.md|WEB3D_quantized_attributes} * </li><li> * {@link https://github.com/KhronosGroup/glTF/blob/master/extensions/2.0/Khronos/KHR_draco_mesh_compression/README.md|KHR_draco_mesh_compression} * </li><li> * {@link https://github.com/KhronosGroup/glTF/blob/master/extensions/2.0/Khronos/KHR_techniques_webgl/README.md|KHR_techniques_webgl} * </li><li> * {@link https://github.com/KhronosGroup/glTF/blob/master/extensions/2.0/Khronos/KHR_blend/README.md|KHR_blend} * </li><li> * {@link https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_unlit/README.md|KHR_materials_unlit} * </li><li> * {@link https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_pbrSpecularGlossiness/README.md|KHR_materials_pbrSpecularGlossiness} * </li> * </ul> * </p> * <p> * For high-precision rendering, Cesium supports the {@link https://github.com/KhronosGroup/glTF/blob/master/extensions/1.0/Vendor/CESIUM_RTC/README.md|CESIUM_RTC} extension, which introduces the * CESIUM_RTC_MODELVIEW parameter semantic that says the node is in WGS84 coordinates translated * relative to a local origin. * </p> * * @param {Object} options Object with the following properties: * @param {Resource|String} options.url The url to the .gltf file. * @param {Resource|String} [options.basePath] The base path that paths in the glTF JSON are relative to. * @param {Boolean} [options.show=true] Determines if the model primitive will be shown. * @param {Matrix4} [options.modelMatrix=Matrix4.IDENTITY] The 4x4 transformation matrix that transforms the model from model to world coordinates. * @param {Number} [options.scale=1.0] A uniform scale applied to this model. * @param {Number} [options.minimumPixelSize=0.0] The approximate minimum pixel size of the model regardless of zoom. * @param {Number} [options.maximumScale] The maximum scale for the model. * @param {Object} [options.id] A user-defined object to return when the model is picked with {@link Scene#pick}. * @param {Boolean} [options.allowPicking=true] When <code>true</code>, each glTF mesh and primitive is pickable with {@link Scene#pick}. * @param {Boolean} [options.incrementallyLoadTextures=true] Determine if textures may continue to stream in after the model is loaded. * @param {Boolean} [options.asynchronous=true] Determines if model WebGL resource creation will be spread out over several frames or block until completion once all glTF files are loaded. * @param {Boolean} [options.clampAnimations=true] Determines if the model's animations should hold a pose over frames where no keyframes are specified. * @param {ShadowMode} [options.shadows=ShadowMode.ENABLED] Determines whether the model casts or receives shadows from each light source. * @param {Boolean} [options.debugShowBoundingVolume=false] For debugging only. Draws the bounding sphere for each {@link DrawCommand} in the model. * @param {Boolean} [options.debugWireframe=false] For debugging only. Draws the model in wireframe. * @param {HeightReference} [options.heightReference] Determines how the model is drawn relative to terrain. * @param {Scene} [options.scene] Must be passed in for models that use the height reference property. * @param {DistanceDisplayCondition} [options.distanceDisplayCondition] The condition specifying at what distance from the camera that this model will be displayed. * @param {Color} [options.color=Color.WHITE] A color that blends with the model's rendered color. * @param {ColorBlendMode} [options.colorBlendMode=ColorBlendMode.HIGHLIGHT] Defines how the color blends with the model. * @param {Number} [options.colorBlendAmount=0.5] Value used to determine the color strength when the <code>colorBlendMode</code> is <code>MIX</code>. A value of 0.0 results in the model's rendered color while a value of 1.0 results in a solid color, with any value in-between resulting in a mix of the two. * @param {Color} [options.silhouetteColor=Color.RED] The silhouette color. If more than 256 models have silhouettes enabled, there is a small chance that overlapping models will have minor artifacts. * @param {Number} [options.silhouetteSize=0.0] The size of the silhouette in pixels. * @param {ClippingPlaneCollection} [options.clippingPlanes] The {@link ClippingPlaneCollection} used to selectively disable rendering the model. * @param {Boolean} [options.dequantizeInShader=true] Determines if a {@link https://github.com/google/draco|Draco} encoded model is dequantized on the GPU. This decreases total memory usage for encoded models. * * @returns {Model} The newly created model. * * @example * // Example 1. Create a model from a glTF asset * var model = scene.primitives.add(Cesium.Model.fromGltf({ * url : './duck/duck.gltf' * })); * * @example * // Example 2. Create model and provide all properties and events * var origin = Cesium.Cartesian3.fromDegrees(-95.0, 40.0, 200000.0); * var modelMatrix = Cesium.Transforms.eastNorthUpToFixedFrame(origin); * * var model = scene.primitives.add(Cesium.Model.fromGltf({ * url : './duck/duck.gltf', * show : true, // default * modelMatrix : modelMatrix, * scale : 2.0, // double size * minimumPixelSize : 128, // never smaller than 128 pixels * maximumScale: 20000, // never larger than 20000 * model size (overrides minimumPixelSize) * allowPicking : false, // not pickable * debugShowBoundingVolume : false, // default * debugWireframe : false * })); * * model.readyPromise.then(function(model) { * // Play all animations when the model is ready to render * model.activeAnimations.addAll(); * }); */ Model.fromGltf = function(options) { //>>includeStart('debug', pragmas.debug); if (!defined(options) || !defined(options.url)) { throw new DeveloperError('options.url is required'); } //>>includeEnd('debug'); var url = options.url; options = clone(options); // Create resource for the model file var modelResource = Resource.createIfNeeded(url); // Setup basePath to get dependent files var basePath = defaultValue(options.basePath, modelResource.clone()); var resource = Resource.createIfNeeded(basePath); // If no cache key is provided, use a GUID. // Check using a URI to GUID dictionary that we have not already added this model. var cacheKey = defaultValue(options.cacheKey, uriToGuid[getAbsoluteUri(modelResource.url)]); if (!defined(cacheKey)) { cacheKey = createGuid(); uriToGuid[getAbsoluteUri(modelResource.url)] = cacheKey; } if (defined(options.basePath) && !defined(options.cacheKey)) { cacheKey += resource.url; } options.cacheKey = cacheKey; options.basePath = resource; var model = new Model(options); var cachedGltf = gltfCache[cacheKey]; if (!defined(cachedGltf)) { cachedGltf = new CachedGltf({ ready : false }); cachedGltf.count = 1; cachedGltf.modelsToLoad.push(model); setCachedGltf(model, cachedGltf); gltfCache[cacheKey] = cachedGltf; // Add Accept header if we need it if (!defined(modelResource.headers.Accept)) { modelResource.headers.Accept = defaultModelAccept; } modelResource.fetchArrayBuffer().then(function(arrayBuffer) { var array = new Uint8Array(arrayBuffer); if (containsGltfMagic(array)) { // Load binary glTF var parsedGltf = parseGlb(array); cachedGltf.makeReady(parsedGltf); } else { // Load text (JSON) glTF var json = getStringFromTypedArray(array); cachedGltf.makeReady(JSON.parse(json)); } }).otherwise(ModelUtility.getFailedLoadFunction(model, 'model', modelResource.url)); } else if (!cachedGltf.ready) { // Cache hit but the fetchArrayBuffer() or fetchText() request is still pending ++cachedGltf.count; cachedGltf.modelsToLoad.push(model); } // else if the cached glTF is defined and ready, the // model constructor will pick it up using the cache key. return model; }; /** * For the unit tests to verify model caching. * * @private */ Model._gltfCache = gltfCache; function getRuntime(model, runtimeName, name) { //>>includeStart('debug', pragmas.debug); if (model._state !== ModelState.LOADED) { throw new DeveloperError('The model is not loaded. Use Model.readyPromise or wait for Model.ready to be true.'); } if (!defined(name)) { throw new DeveloperError('name is required.'); } //>>includeEnd('debug'); return (model._runtime[runtimeName])[name]; } /** * Returns the glTF node with the given <code>name</code> property. This is used to * modify a node's transform for animation outside of glTF animations. * * @param {String} name The glTF name of the node. * @returns {ModelNode} The node or <code>undefined</code> if no node with <code>name</code> exists. * * @exception {DeveloperError} The model is not loaded. Use Model.readyPromise or wait for Model.ready to be true. * * @example * // Apply non-uniform scale to node LOD3sp * var node = model.getNode('LOD3sp'); * node.matrix = Cesium.Matrix4.fromScale(new Cesium.Cartesian3(5.0, 1.0, 1.0), node.matrix); */ Model.prototype.getNode = function(name) { var node = getRuntime(this, 'nodesByName', name); return defined(node) ? node.publicNode : undefined; }; /** * Returns the glTF mesh with the given <code>name</code> property. * * @param {String} name The glTF name of the mesh. * * @returns {ModelMesh} The mesh or <code>undefined</code> if no mesh with <code>name</code> exists. * * @exception {DeveloperError} The model is not loaded. Use Model.readyPromise or wait for Model.ready to be true. */ Model.prototype.getMesh = function(name) { return getRuntime(this, 'meshesByName', name); }; /** * Returns the glTF material with the given <code>name</code> property. * * @param {String} name The glTF name of the material. * @returns {ModelMaterial} The material or <code>undefined</code> if no material with <code>name</code> exists. * * @exception {DeveloperError} The model is not loaded. Use Model.readyPromise or wait for Model.ready to be true. */ Model.prototype.getMaterial = function(name) { return getRuntime(this, 'materialsByName', name); }; /////////////////////////////////////////////////////////////////////////// function addBuffersToLoadResources(model) { var gltf = model.gltf; var loadResources = model._loadResources; ForEach.buffer(gltf, function(buffer, id) { loadResources.buffers[id] = buffer.extras._pipeline.source; }); } function bufferLoad(model, id) { return function(arrayBuffer) { var loadResources = model._loadResources; var buffer = new Uint8Array(arrayBuffer); --loadResources.pendingBufferLoads; model.gltf.buffers[id].extras._pipeline.source = buffer; }; } function parseBufferViews(model) { var bufferViews = model.gltf.bufferViews; var vertexBuffersToCreate = model._loadResources.vertexBuffersToCreate; // Only ARRAY_BUFFER here. ELEMENT_ARRAY_BUFFER created below. ForEach.bufferView(model.gltf, function(bufferView, id) { if (bufferView.target === WebGLConstants.ARRAY_BUFFER) { vertexBuffersToCreate.enqueue(id); } }); var indexBuffersToCreate = model._loadResources.indexBuffersToCreate; var indexBufferIds = {}; // The Cesium Renderer requires knowing the datatype for an index buffer // at creation type, which is not part of the glTF bufferview so loop // through glTF accessors to create the bufferview's index buffer. ForEach.accessor(model.gltf, function(accessor) { var bufferViewId = accessor.bufferView; if (!defined(bufferViewId)) { return; } var bufferView = bufferViews[bufferViewId]; if ((bufferView.target === WebGLConstants.ELEMENT_ARRAY_BUFFER) && !defined(indexBufferIds[bufferViewId])) { indexBufferIds[bufferViewId] = true; indexBuffersToCreate.enqueue({ id : bufferViewId, componentType : accessor.componentType }); } }); } function parseTechniques(model) { // retain references to gltf techniques var gltf = model.gltf; if (!hasExtension(gltf, 'KHR_techniques_webgl')) { return; } var sourcePrograms = model._sourcePrograms; var sourceTechniques = model._sourceTechniques; var programs = gltf.extensions.KHR_techniques_webgl.programs; ForEach.technique(gltf, function(technique, techniqueId) { sourceTechniques[techniqueId] = clone(technique); var programId = technique.program; if (!defined(sourcePrograms[programId])) { sourcePrograms[programId] = clone(programs[programId]); } }); } function shaderLoad(model, type, id) { return function(source) { var loadResources = model._loadResources; loadResources.shaders[id] = { source : source, type : type, bufferView : undefined }; --loadResources.pendingShaderLoads; model._rendererResources.sourceShaders[id] = source; }; } function parseShaders(model) { var gltf = model.gltf; var buffers = gltf.buffers; var bufferViews = gltf.bufferViews; var sourceShaders = model._rendererResources.sourceShaders; ForEach.shader(gltf, function(shader, id) { // Shader references either uri (external or base64-encoded) or bufferView if (defined(shader.bufferView)) { var bufferViewId = shader.bufferView; var bufferView = bufferViews[bufferViewId]; var bufferId = bufferView.buffer; var buffer = buffers[bufferId]; var source = getStringFromTypedArray(buffer.extras._pipeline.source, bufferView.byteOffset, bufferView.byteLength); sourceShaders[id] = source; } else if (defined(shader.extras._pipeline.source)) { sourceShaders[id] = shader.extras._pipeline.source; } else { ++model._loadResources.pendingShaderLoads; var shaderResource = model._resource.getDerivedResource({ url: shader.uri }); shaderResource.fetchText() .then(shaderLoad(model, shader.type, id)) .otherwise(ModelUtility.getFailedLoadFunction(model, 'shader', shaderResource.url)); } }); } function parsePrograms(model) { var sourceTechniques = model._sourceTechniques; for (var techniqueId in sourceTechniques) { if (sourceTechniques.hasOwnProperty(techniqueId)) { var technique = sourceTechniques[techniqueId]; model._loadResources.programsToCreate.enqueue({ programId: technique.program, techniqueId: techniqueId }); } } } function imageLoad(model, textureId) { return function(image) { var loadResources = model._loadResources; --loadResources.pendingTextureLoads; loadResources.texturesToCreate.enqueue({ id : textureId, image : image, bufferView : image.bufferView, width : image.width, height : image.height, internalFormat : image.internalFormat }); }; } var ktxRegex = /(^data:image\/ktx)|(\.ktx$)/i; var crnRegex = /(^data:image\/crn)|(\.crn$)/i; function parseTextures(model, context, supportsWebP) { var gltf = model.gltf; var images = gltf.images; var uri; ForEach.texture(gltf, function(texture, id) { var imageId = texture.source; if (defined(texture.extensions) && defined(texture.extensions.EXT_texture_webp) && supportsWebP) { imageId = texture.extensions.EXT_texture_webp.source; } var gltfImage = images[imageId]; var extras = gltfImage.extras; var bufferViewId = gltfImage.bufferView; var mimeType = gltfImage.mimeType; uri = gltfImage.uri; // First check for a compressed texture if (defined(extras) && defined(extras.compressedImage3DTiles)) { var crunch = extras.compressedImage3DTiles.crunch; var s3tc = extras.compressedImage3DTiles.s3tc; var pvrtc = extras.compressedImage3DTiles.pvrtc1; var etc1 = extras.compressedImage3DTiles.etc1; if (context.s3tc && defined(crunch)) { mimeType = crunch.mimeType; if (defined(crunch.bufferView)) { bufferViewId = crunch.bufferView; } else { uri = crunch.uri; } } else if (context.s3tc && defined(s3tc)) { mimeType = s3tc.mimeType; if (defined(s3tc.bufferView)) { bufferViewId = s3tc.bufferView; } else { uri = s3tc.uri; } } else if (context.pvrtc && defined(pvrtc)) { mimeType = pvrtc.mimeType; if (defined(pvrtc.bufferView)) { bufferViewId = pvrtc.bufferView; } else { uri = pvrtc.uri; } } else if (context.etc1 && defined(etc1)) { mimeType = etc1.mimeType; if (defined(etc1.bufferView)) { bufferViewId = etc1.bufferView; } else { uri = etc1.uri; } } } // Image references either uri (external or base64-encoded) or bufferView if (defined(bufferViewId)) { model._loadResources.texturesToCreateFromBufferView.enqueue({ id : id, image : undefined, bufferView : bufferViewId, mimeType : mimeType }); } else { ++model._loadResources.pendingTextureLoads; var imageResource = model._resource.getDerivedResource({ url : uri }); var promise; if (ktxRegex.test(uri)) { promise = loadKTX(imageResource); } else if (crnRegex.test(uri)) { promise = loadCRN(imageResource); } else { promise = imageResource.fetchImage(); } promise.then(imageLoad(model, id, imageId)).otherwise(ModelUtility.getFailedLoadFunction(model, 'image', imageResource.url)); } }); } function parseNodes(model) { var runtimeNodes = {}; var runtimeNodesByName = {}; var skinnedNodes = []; var skinnedNodesIds = model._loadResources.skinnedNodesIds; ForEach.node(model.gltf, function(node, id) { var runtimeNode = { // Animation targets matrix : undefined, translation : undefined, rotation : undefined, scale : undefined, // Per-node show inherited from parent computedShow : true, // Computed transforms transformToRoot : new Matrix4(), computedMatrix : new Matrix4(), dirtyNumber : 0, // The frame this node was made dirty by an animation; for graph traversal // Rendering commands : [], // empty for transform, light, and camera nodes // Skinned node inverseBindMatrices : undefined, // undefined when node is not skinned bindShapeMatrix : undefined, // undefined when node is not skinned or identity joints : [], // empty when node is not skinned computedJointMatrices : [], // empty when node is not skinned // Joint node jointName : node.jointName, // undefined when node is not a joint weights : [], // Graph pointers children : [], // empty for leaf nodes parents : [], // empty for root nodes // Publicly-accessible ModelNode instance to modify animation targets publicNode : undefined }; runtimeNode.publicNode = new ModelNode(model, node, runtimeNode, id, ModelUtility.getTransform(node)); runtimeNodes[id] = runtimeNode; runtimeNodesByName[node.name] = runtimeNode; if (defined(node.skin)) { skinnedNodesIds.push(id); skinnedNodes.push(runtimeNode); } }); model._runtime.nodes = runtimeNodes; model._runtime.nodesByName = runtimeNodesByName; model._runtime.skinnedNodes = skinnedNodes; } function parseMaterials(model) { var gltf = model.gltf; var techniques = model._sourceTechniques; var runtimeMaterialsByName = {}; var runtimeMaterialsById = {}; var uniformMaps = model._uniformMaps; ForEach.material(gltf, function(material, materialId) { // Allocated now so ModelMaterial can keep a reference to it. uniformMaps[materialId] = { uniformMap : undefined, values : undefined, jointMatrixUniformName : undefined, morphWeightsUniformName : undefined }; var modelMaterial = new ModelMaterial(model, material, materialId); if (defined(material.extensions) && defined(material.extensions.KHR_techniques_webgl)) { var techniqueId = material.extensions.KHR_techniques_webgl.technique; modelMaterial._technique = techniqueId; modelMaterial._program = techniques[techniqueId].program; ForEach.materialValue(material, function(value, uniformName) { if (!defined(modelMaterial._values)) { modelMaterial._values = {}; } modelMaterial._values[uniformName] = clone(value); }); } runtimeMaterialsByName[material.name] = modelMaterial; runtimeMaterialsById[materialId] = modelMaterial; }); model._runtime.materialsByName = runtimeMaterialsByName; model._runtime.materialsById = runtimeMaterialsById; } function parseMeshes(model) { var runtimeMeshesByName = {}; var runtimeMaterialsById = model._runtime.materialsById; ForEach.mesh(model.gltf, function(mesh, meshId) { runtimeMeshesByName[mesh.name] = new ModelMesh(mesh, runtimeMaterialsById, meshId); if (defined(model.extensionsUsed.WEB3D_quantized_attributes) || model._dequantizeInShader) { // Cache primitives according to their program ForEach.meshPrimitive(mesh, function(primitive, primitiveId) { var programId = getProgramForPrimitive(model, primitive); var programPrimitives = model._programPrimitives[programId]; if (!defined(programPrimitives)) { programPrimitives = {}; model._programPrimitives[programId] = programPrimitives; } programPrimitives[meshId + '.primitive.' + primitiveId] = primitive; }); } }); model._runtime.meshesByName = runtimeMeshesByName; } /////////////////////////////////////////////////////////////////////////// var CreateVertexBufferJob = function() { this.id = undefined; this.model = undefined; this.context = undefined; }; CreateVertexBufferJob.prototype.set = function(id, model, context) { this.id = id; this.model = model; this.context = context; }; CreateVertexBufferJob.prototype.execute = function() { createVertexBuffer(this.id, this.model, this.context); }; /////////////////////////////////////////////////////////////////////////// function createVertexBuffer(bufferViewId, model, context) { var loadResources = model._loadResources; var bufferViews = model.gltf.bufferViews; var bufferView = bufferViews[bufferViewId]; // Use bufferView created at runtime if (!defined(bufferView)) { bufferView = loadResources.createdBufferViews[bufferViewId]; } var vertexBuffer = Buffer.createVertexBuffer({ context : context, typedArray : loadResources.getBuffer(bufferView), usage : BufferUsage.STATIC_DRAW }); vertexBuffer.vertexArrayDestroyable = false; model._rendererResources.buffers[bufferViewId] = vertexBuffer; model._geometryByteLength += vertexBuffer.sizeInBytes; } /////////////////////////////////////////////////////////////////////////// var CreateIndexBufferJob = function() { this.id = undefined; this.componentType = undefined; this.model = undefined; this.context = undefined; }; CreateIndexBufferJob.prototype.set = function(id, componentType, model, context) { this.id = id; this.componentType = componentType; this.model = model; this.context = context; }; CreateIndexBufferJob.prototype.execute = function() { createIndexBuffer(this.id, this.componentType, this.model, this.context); }; /////////////////////////////////////////////////////////////////////////// function createIndexBuffer(bufferViewId, componentType, model, context) { var loadResources = model._loadResources; var bufferViews = model.gltf.bufferViews; var bufferView = bufferViews[bufferViewId]; // Use bufferView created at runtime if (!defined(bufferView)) { bufferView = loadResources.createdBufferViews[bufferViewId]; } var indexBuffer = Buffer.createIndexBuffer({ context : context, typedArray : loadResources.getBuffer(bufferView), usage : BufferUsage.STATIC_DRAW, indexDatatype : componentType }); indexBuffer.vertexArrayDestroyable = false; model._rendererResources.buffers[bufferViewId] = indexBuffer; model._geometryByteLength += indexBuffer.sizeInBytes; } var scratchVertexBufferJob = new CreateVertexBufferJob(); var scratchIndexBufferJob = new CreateIndexBufferJob(); function createBuffers(model, frameState) { var loadResources = model._loadResources; if (loadResources.pendingBufferLoads !== 0) { return; } var context = frameState.context; var vertexBuffersToCreate = loadResources.vertexBuffersToCreate; var indexBuffersToCreate = loadResources.indexBuffersToCreate; var i; if (model.asynchronous) { while (vertexBuffersToCreate.length > 0) { scratchVertexBufferJob.set(vertexBuffersToCreate.peek(), model, context); if (!frameState.jobScheduler.execute(scratchVertexBufferJob, JobType.BUFFER)) { break; } vertexBuffersToCreate.dequeue(); } while (indexBuffersToCreate.length > 0) { i = indexBuffersToCreate.peek(); scratchIndexBufferJob.set(i.id, i.componentType, model, context); if (!frameState.jobScheduler.execute(scratchIndexBufferJob, JobType.BUFFER)) { break; } indexBuffersToCreate.dequeue(); } } else { while (vertexBuffersToCreate.length > 0) { createVertexBuffer(vertexBuffersToCreate.dequeue(), model, context); } while (indexBuffersToCreate.length > 0) { i = indexBuffersToCreate.dequeue(); createIndexBuffer(i.id, i.componentType, model, context); } } } function getProgramForPrimitive(model, primitive) { var material = model._runtime.materialsById[primitive.material]; if (!defined(material)) { return; } return material._program; } function modifyShaderForQuantizedAttributes(shader, programName, model) { var primitive; var primitives = model._programPrimitives[programName]; // If no primitives were cached for this program, there's no need to modify the shader if (!defined(primitives)) { return shader; } var primitiveId; for (primitiveId in primitives) { if (primitives.hasOwnProperty(primitiveId)) { primitive = primitives[primitiveId]; if (getProgramForPrimitive(model, primitive) === programName) { break; } } } // This is not needed after the program is processed, free the memory model._programPrimitives[programName] = undefined; var result; if (model.extensionsUsed.WEB3D_quantized_attributes) { result = ModelUtility.modifyShaderForQuantizedAttributes(model.gltf, primitive, shader); model._quantizedUniforms[programName] = result.uniforms; } else { var decodedData = model._decodedData[primitiveId]; if (defined(decodedData)) { result = ModelUtility.modifyShaderForDracoQuantizedAttributes(model.gltf, primitive, shader, decodedData.attributes); } else { return shader; } } return result.shader; } function modifyShaderForColor(shader) { shader = ShaderSource.replaceMain(shader, 'gltf_blend_main'); shader += 'uniform vec4 gltf_color; \n' + 'uniform float gltf_colorBlend; \n' + 'void main() \n' + '{ \n' + ' gltf_blend_main(); \n' + ' gl_FragColor.rgb = mix(gl_FragColor.rgb, gltf_color.rgb, gltf_colorBlend); \n' + ' float highlight = ceil(gltf_colorBlend); \n' + ' gl_FragColor.rgb *= mix(gltf_color.rgb, vec3(1.0), highlight); \n' + ' gl_FragColor.a *= gltf_color.a; \n' + '} \n'; return shader; } function modifyShader(shader, programName, callback) { if (defined(callback)) { shader = callback(shader, programName); } return shader; } var CreateProgramJob = function() { this.programToCreate = undefined; this.model = undefined; this.context = undefined; }; CreateProgramJob.prototype.set = function(programToCreate, model, context) { this.programToCreate = programToCreate; this.model = model; this.context = context; }; CreateProgramJob.prototype.execute = function() { createProgram(this.programToCreate, this.model, this.context); }; /////////////////////////////////////////////////////////////////////////// // When building programs for the first time, do not include modifiers for clipping planes and color // since this is the version of the program that will be cached for use with other Models. function createProgram(programToCreate, model, context) { var programId = programToCreate.programId; var techniqueId = programToCreate.techniqueId; var program = model._sourcePrograms[programId]; var shaders = model._rendererResources.sourceShaders; var vs = shaders[program.vertexShader]; var fs = shaders[program.fragmentShader]; var quantizedVertexShaders = model._quantizedVertexShaders; var toClipCoordinatesGLSL = model._toClipCoordinatesGLSL[programId]; if (model.extensionsUsed.WEB3D_quantized_attributes || model._dequantizeInShader) { var quantizedVS = quantizedVertexShaders[programId]; if (!defined(quantizedVS)) { quantizedVS = modifyShaderForQuantizedAttributes(vs, programId, model); quantizedVertexShaders[programId] = quantizedVS; } vs = quantizedVS; } var drawVS = modifyShader(vs, programId, model._vertexShaderLoaded); var drawFS = modifyShader(fs, programId, model._fragmentShaderLoaded); // Internet Explorer seems to have problems with discard (for clipping planes) after too many levels of indirection: // https://github.com/AnalyticalGraphicsInc/cesium/issues/6575. // For IE log depth code is defined out anyway due to unsupported WebGL extensions, so the wrappers can be omitted. if (!FeatureDetection.isInternetExplorer()) { drawVS = ModelUtility.modifyVertexShaderForLogDepth(drawVS, toClipCoordinatesGLSL); drawFS = ModelUtility.modifyFragmentShaderForLogDepth(drawFS); } if (!defined(model._uniformMapLoaded)) { drawFS = 'uniform vec4 czm_pickColor;\n' + drawFS; } var useIBL = model._imageBasedLightingFactor.x > 0.0 || model._imageBasedLightingFactor.y > 0.0; if (useIBL) { drawFS = '#define USE_IBL_LIGHTING \n\n' + drawFS; } if (defined(model._lightColor)) { drawFS = '#define USE_CUSTOM_LIGHT_COLOR \n\n' + drawFS; } if (model._sourceVersion !== '2.0' || model._sourceKHRTechniquesWebGL) { drawFS = ShaderSource.replaceMain(drawFS, 'non_gamma_corrected_main'); drawFS = drawFS + '\n' + 'void main() { \n' + ' non_gamma_corrected_main(); \n' + ' gl_FragColor = czm_gammaCorrect(gl_FragColor); \n' + '} \n'; } if (OctahedralProjectedCubeMap.isSupported(context)) { var usesSH = defined(model._sphericalHarmonicCoefficients) || model._useDefaultSphericalHarmonics; var usesSM = (defined(model._specularEnvironmentMapAtlas) && model._specularEnvironmentMapAtlas.ready) || model._useDefaultSpecularMaps; var addMatrix = usesSH || usesSM || useIBL; if (addMatrix) { drawFS = 'uniform mat4 gltf_clippingPlanesMatrix; \n' + drawFS; } if (defined(model._sphericalHarmonicCoefficients)) { drawFS = '#define DIFFUSE_IBL \n' + '#define CUSTOM_SPHERICAL_HARMONICS \n' + 'uniform vec3 gltf_sphericalHarmonicCoefficients[9]; \n' + drawFS; } else if (model._useDefaultSphericalHarmonics) { drawFS = '#define DIFFUSE_IBL \n' + drawFS; } if (defined(model._specularEnvironmentMapAtlas) && model._specularEnvironmentMapAtlas.ready) { drawFS = '#define SPECULAR_IBL \n' + '#define CUSTOM_SPECULAR_IBL \n' + 'uniform sampler2D gltf_specularMap; \n' + 'uniform vec2 gltf_specularMapSize; \n' + 'uniform float gltf_maxSpecularLOD; \n' + drawFS; } else if (model._useDefaultSpecularMaps) { drawFS = '#define SPECULAR_IBL \n' + drawFS; } } if (defined(model._luminanceAtZenith)) { drawFS = '#define USE_SUN_LUMINANCE \n' + 'uniform float gltf_luminanceAtZenith;\n' + drawFS; } createAttributesAndProgram(programId, techniqueId, drawFS, drawVS, model, context); } function recreateProgram(programToCreate, model, context) { var programId = programToCreate.programId; var techniqueId = programToCreate.techniqueId; var program = model._sourcePrograms[programId]; var shaders = model._rendererResources.sourceShaders; var quantizedVertexShaders = model._quantizedVertexShaders; var toClipCoordinatesGLSL = model._toClipCoordinatesGLSL[programId]; var clippingPlaneCollection = model.clippingPlanes; var addClippingPlaneCode = isClippingEnabled(model); var vs = shaders[program.vertexShader]; var fs = shaders[program.fragmentShader]; if (model.extensionsUsed.WEB3D_quantized_attributes || model._dequantizeInShader) { vs = quantizedVertexShaders[programId]; } var finalFS = fs; if (isColorShadingEnabled(model)) { finalFS = Model._modifyShaderForColor(finalFS); } if (addClippingPlaneCode) { finalFS = modifyShaderForClippingPlanes(finalFS, clippingPlaneCollection, context); } var drawVS = modifyShader(vs, programId, model._vertexShaderLoaded); var drawFS = modifyShader(finalFS, programId, model._fragmentShaderLoaded); if (!FeatureDetection.isInternetExplorer()) { drawVS = ModelUtility.modifyVertexShaderForLogDepth(drawVS, toClipCoordinatesGLSL); drawFS = ModelUtility.modifyFragmentShaderForLogDepth(drawFS); } if (!defined(model._uniformMapLoaded)) { drawFS = 'uniform vec4 czm_pickColor;\n' + drawFS; } var useIBL = model._imageBasedLightingFactor.x > 0.0 || model._imageBasedLightingFactor.y > 0.0; if (useIBL) { drawFS = '#define USE_IBL_LIGHTING \n\n' + drawFS; } if (defined(model._lightColor)) { drawFS = '#define USE_CUSTOM_LIGHT_COLOR \n\n' + drawFS; } if (model._sourceVersion !== '2.0' || model._sourceKHRTechniquesWebGL) { drawFS = ShaderSource.replaceMain(drawFS, 'non_gamma_corrected_main'); drawFS = drawFS + '\n' + 'void main() { \n' + ' non_gamma_corrected_main(); \n' + ' gl_FragColor = czm_gammaCorrect(gl_FragColor); \n' + '} \n'; } if (OctahedralProjectedCubeMap.isSupported(context)) { var usesSH = defined(model._sphericalHarmonicCoefficients) || model._useDefaultSphericalHarmonics; var usesSM = (defined(model._specularEnvironmentMapAtlas) && model._specularEnvironmentMapAtlas.ready) || model._useDefaultSpecularMaps; var addMatrix = !addClippingPlaneCode && (usesSH || usesSM || useIBL); if (addMatrix) { drawFS = 'uniform mat4 gltf_clippingPlanesMatrix; \n' + drawFS; } if (defined(model._sphericalHarmonicCoefficients)) { drawFS = '#define DIFFUSE_IBL \n' + '#define CUSTOM_SPHERICAL_HARMONICS \n' + 'uniform vec3 gltf_sphericalHarmonicCoefficients[9]; \n' + drawFS; } else if (model._useDefaultSphericalHarmonics) { drawFS = '#define DIFFUSE_IBL \n' + drawFS; } if (defined(model._specularEnvironmentMapAtlas) && model._specularEnvironmentMapAtlas.ready) { drawFS = '#define SPECULAR_IBL \n' + '#define CUSTOM_SPECULAR_IBL \n' + 'uniform sampler2D gltf_specularMap; \n' + 'uniform vec2 gltf_specularMapSize; \n' + 'uniform float gltf_maxSpecularLOD; \n' + drawFS; } else if (model._useDefaultSpecularMaps) { drawFS = '#define SPECULAR_IBL \n' + drawFS; } } if (defined(model._luminanceAtZenith)) { drawFS = '#define USE_SUN_LUMINANCE \n' + 'uniform float gltf_luminanceAtZenith;\n' + drawFS; } createAttributesAndProgram(programId, techniqueId, drawFS, drawVS, model, context); } function createAttributesAndProgram(programId, techniqueId, drawFS, drawVS, model, context) { var technique = model._sourceTechniques[techniqueId]; var attributeLocations = ModelUtility.createAttributeLocations(technique, model._precreatedAttributes); model._rendererResources.programs[programId] = ShaderProgram.fromCache({ context : context, vertexShaderSource : drawVS, fragmentShaderSource : drawFS, attributeLocations : attributeLocations }); } var scratchCreateProgramJob = new CreateProgramJob(); function createPrograms(model, frameState) { var loadResources = model._loadResources; var programsToCreate = loadResources.programsToCreate; if (loadResources.pendingShaderLoads !== 0) { return; } // PERFORMANCE_IDEA: this could be more fine-grained by looking // at the shader's bufferView's to determine the buffer dependencies. if (loadResources.pendingBufferLoads !== 0) { return; } var context = frameState.context; if (model.asynchronous) { while (programsToCreate.length > 0) { scratchCreateProgramJob.set(programsToCreate.peek(), model, context); if (!frameState.jobScheduler.execute(scratchCreateProgramJob, JobType.PROGRAM)) { break; } programsToCreate.dequeue(); } } else { // Create all loaded programs this frame while (programsToCreate.length > 0) { createProgram(programsToCreate.dequeue(), model, context); } } } function getOnImageCreatedFromTypedArray(loadResources, gltfTexture) { return function(image) { loadResources.texturesToCreate.enqueue({ id : gltfTexture.id, image : image, bufferView : undefined }); --loadResources.pendingBufferViewToImage; }; } function loadTexturesFromBufferViews(model) { var loadResources = model._loadResources; if (loadResources.pendingBufferLoads !== 0) { return; } while (loadResources.texturesToCreateFromBufferView.length > 0) { var gltfTexture = loadResources.texturesToCreateFromBufferView.dequeue(); var gltf = model.gltf; var bufferView = gltf.bufferViews[gltfTexture.bufferView]; var imageId = gltf.textures[gltfTexture.id].source; var onerror = ModelUtility.getFailedLoadFunction(model, 'image', 'id: ' + gltfTexture.id + ', bufferView: ' + gltfTexture.bufferView); if (gltfTexture.mimeType === 'image/ktx') { loadKTX(loadResources.getBuffer(bufferView)).then(imageLoad(model, gltfTexture.id, imageId)).otherwise(onerror); ++model._loadResources.pendingTextureLoads; } else if (gltfTexture.mimeType === 'image/crn') { loadCRN(loadResources.getBuffer(bufferView)).then(imageLoad(model, gltfTexture.id, imageId)).otherwise(onerror); ++model._loadResources.pendingTextureLoads; } else { var onload = getOnImageCreatedFromTypedArray(loadResources, gltfTexture); loadImageFromTypedArray({ uint8Array: loadResources.getBuffer(bufferView), format: gltfTexture.mimeType, flipY: false }) .then(onload).otherwise(onerror); ++loadResources.pendingBufferViewToImage; } } } function createSamplers(model) { var loadResources = model._loadResources; if (loadResources.createSamplers) { loadResources.createSamplers = false; var rendererSamplers = model._rendererResources.samplers; ForEach.sampler(model.gltf, function(sampler, samplerId) { rendererSamplers[samplerId] = new Sampler({ wrapS: sampler.wrapS, wrapT: sampler.wrapT, minificationFilter: sampler.minFilter, magnificationFilter: sampler.magFilter }); }); } } /////////////////////////////////////////////////////////////////////////// var CreateTextureJob = function() { this.gltfTexture = undefined; this.model = undefined; this.context = undefined; }; CreateTextureJob.prototype.set = function(gltfTexture, model, context) { this.gltfTexture = gltfTexture; this.model = model; this.context = context; }; CreateTextureJob.prototype.execute = function() { createTexture(this.gltfTexture, this.model, this.context); }; /////////////////////////////////////////////////////////////////////////// function createTexture(gltfTexture, model, context) { var textures = model.gltf.textures; var texture = textures[gltfTexture.id]; var rendererSamplers = model._rendererResources.samplers; var sampler = rendererSamplers[texture.sampler]; sampler = defaultValue(sampler, new Sampler({ wrapS : TextureWrap.REPEAT, wrapT : TextureWrap.REPEAT })); var internalFormat = gltfTexture.internalFormat; var mipmap = (!(defined(internalFormat) && PixelFormat.isCompressedFormat(internalFormat))) && ((sampler.minificationFilter === TextureMinificationFilter.NEAREST_MIPMAP_NEAREST) || (sampler.minificationFilter === TextureMinificationFilter.NEAREST_MIPMAP_LINEAR) || (sampler.minificationFilter === TextureMinificationFilter.LINEAR_MIPMAP_NEAREST) || (sampler.minificationFilter === TextureMinificationFilter.LINEAR_MIPMAP_LINEAR)); var requiresNpot = mipmap || (sampler.wrapS === TextureWrap.REPEAT) || (sampler.wrapS === TextureWrap.MIRRORED_REPEAT) || (sampler.wrapT === TextureWrap.REPEAT) || (sampler.wrapT === TextureWrap.MIRRORED_REPEAT); var tx; var source = gltfTexture.image; if (defined(internalFormat)) { tx = new Texture({ context : context, source : { arrayBufferView : gltfTexture.bufferView }, width : gltfTexture.width, height : gltfTexture.height, pixelFormat : internalFormat, sampler : sampler }); } else if (defined(source)) { var npot = !CesiumMath.isPowerOfTwo(source.width) || !CesiumMath.isPowerOfTwo(source.height); if (requiresNpot && npot) { // WebGL requires power-of-two texture dimensions for mipmapping and REPEAT/MIRRORED_REPEAT wrap modes. var canvas = document.createElement('canvas'); canvas.width = CesiumMath.nextPowerOfTwo(source.width); canvas.height = CesiumMath.nextPowerOfTwo(source.height); var canvasContext = canvas.getContext('2d'); canvasContext.drawImage(source, 0, 0, source.width, source.height, 0, 0, canvas.width, canvas.height); source = canvas; } tx = new Texture({ context : context, source : source, pixelFormat : texture.internalFormat, pixelDatatype : texture.type, sampler : sampler, flipY : false }); // GLTF_SPEC: Support TEXTURE_CUBE_MAP. https://github.com/KhronosGroup/glTF/issues/40 if (mipmap) { tx.generateMipmap(); } } if (defined(tx)) { model._rendererResources.textures[gltfTexture.id] = tx; model._texturesByteLength += tx.sizeInBytes; } } var scratchCreateTextureJob = new CreateTextureJob(); function createTextures(model, frameState) { var context = frameState.context; var texturesToCreate = model._loadResources.texturesToCreate; if (model.asynchronous) { while (texturesToCreate.length > 0) { scratchCreateTextureJob.set(texturesToCreate.peek(), model, context); if (!frameState.jobScheduler.execute(scratchCreateTextureJob, JobType.TEXTURE)) { break; } texturesToCreate.dequeue(); } } else { // Create all loaded textures this frame while (texturesToCreate.length > 0) { createTexture(texturesToCreate.dequeue(), model, context); } } } function getAttributeLocations(model, primitive) { var techniques = model._sourceTechniques; // Retrieve the compiled shader program to assign index values to attributes var attributeLocations = {}; var location; var index; var material = model._runtime.materialsById[primitive.material]; if (!defined(material)) { return attributeLocations; } var technique = techniques[material._technique]; if (!defined(technique)) { return attributeLocations; } var attributes = technique.attributes; var program = model._rendererResources.programs[technique.program]; var programVertexAttributes = program.vertexAttributes; var programAttributeLocations = program._attributeLocations; // Note: WebGL shader compiler may have optimized and removed some attributes from programVertexAttributes for (location in programVertexAttributes) { if (programVertexAttributes.hasOwnProperty(location)) { var attribute = attributes[location]; if (defined(attribute)) { index = programAttributeLocations[location]; attributeLocations[attribute.semantic] = index; } } } // Always add pre-created attributes. // Some pre-created attributes, like per-instance pickIds, may be compiled out of the draw program // but should be included in the list of attribute locations for the pick program. // This is safe to do since programVertexAttributes and programAttributeLocations are equivalent except // that programVertexAttributes optimizes out unused attributes. var precreatedAttributes = model._precreatedAttributes; if (defined(precreatedAttributes)) { for (location in precreatedAttributes) { if (precreatedAttributes.hasOwnProperty(location)) { index = programAttributeLocations[location]; attributeLocations[location] = index; } } } return attributeLocations; } function mapJointNames(forest, nodes) { var length = forest.length; var jointNodes = {}; for (var i = 0; i < length; ++i) { var stack = [forest[i]]; // Push root node of tree while (stack.length > 0) { var id = stack.pop(); var n = nodes[id]; if (defined(n)) { jointNodes[id] = id; } var children = n.children; if (defined(children)) { var childrenLength = children.length; for (var k = 0; k < childrenLength; ++k) { stack.push(children[k]); } } } } return jointNodes; } function createJoints(model, runtimeSkins) { var gltf = model.gltf; var skins = gltf.skins; var nodes = gltf.nodes; var runtimeNodes = model._runtime.nodes; var skinnedNodesIds = model._loadResources.skinnedNodesIds; var length = skinnedNodesIds.length; for (var j = 0; j < length; ++j) { var id = skinnedNodesIds[j]; var skinnedNode = runtimeNodes[id]; var node = nodes[id]; var runtimeSkin = runtimeSkins[node.skin]; skinnedNode.inverseBindMatrices = runtimeSkin.inverseBindMatrices; skinnedNode.bindShapeMatrix = runtimeSkin.bindShapeMatrix; // 1. Find nodes with the names in node.skeletons (the node's skeletons) // 2. These nodes form the root nodes of the forest to search for each joint in skin.jointNames. This search uses jointName, not the node's name. // 3. Search for the joint name among the gltf node hierarchy instead of the runtime node hierarchy. Child links aren't set up yet for runtime nodes. var forest = []; var skin = skins[node.skin]; if (defined(skin.skeleton)) { forest.push(skin.skeleton); } var mappedJointNames = mapJointNames(forest, nodes); var gltfJointNames = skins[node.skin].joints; var jointNamesLength = gltfJointNames.length; for (var i = 0; i < jointNamesLength; ++i) { var jointName = gltfJointNames[i]; var nodeId = mappedJointNames[jointName]; var jointNode = runtimeNodes[nodeId]; skinnedNode.joints.push(jointNode); } } } function createSkins(model) { var loadResources = model._loadResources; if (loadResources.pendingBufferLoads !== 0) { return; } if (!loadResources.createSkins) { return; } loadResources.createSkins = false; var gltf = model.gltf; var accessors = gltf.accessors; var runtimeSkins = {}; ForEach.skin(gltf, function(skin, id) { var accessor = accessors[skin.inverseBindMatrices]; var bindShapeMatrix; if (!Matrix4.equals(skin.bindShapeMatrix, Matrix4.IDENTITY)) { bindShapeMatrix = Matrix4.clone(skin.bindShapeMatrix); } runtimeSkins[id] = { inverseBindMatrices : ModelAnimationCache.getSkinInverseBindMatrices(model, accessor), bindShapeMatrix : bindShapeMatrix // not used when undefined }; }); createJoints(model, runtimeSkins); } function getChannelEvaluator(model, runtimeNode, targetPath, spline) { return function(localAnimationTime) { // Workaround for https://github.com/KhronosGroup/glTF/issues/219 //if (targetPath === 'translation') { // return; //} if (defined(spline)) { localAnimationTime = model.clampAnimations ? spline.clampTime(localAnimationTime) : spline.wrapTime(localAnimationTime); runtimeNode[targetPath] = spline.evaluate(localAnimationTime, runtimeNode[targetPath]); runtimeNode.dirtyNumber = model._maxDirtyNumber; } }; } function createRuntimeAnimations(model) { var loadResources = model._loadResources; if (!loadResources.finishedPendingBufferLoads()) { return; } if (!loadResources.createRuntimeAnimations) { return; } loadResources.createRuntimeAnimations = false; model._runtime.animations = []; var runtimeNodes = model._runtime.nodes; var accessors = model.gltf.accessors; ForEach.animation(model.gltf, function (animation, i) { var channels = animation.channels; var samplers = animation.samplers; // Find start and stop time for the entire animation var startTime = Number.MAX_VALUE; var stopTime = -Number.MAX_VALUE; var channelsLength = channels.length; var channelEvaluators = new Array(channelsLength); for (var j = 0; j < channelsLength; ++j) { var channel = channels[j]; var target = channel.target; var path = target.path; var sampler = samplers[channel.sampler]; var input = ModelAnimationCache.getAnimationParameterValues(model, accessors[sampler.input]); var output = ModelAnimationCache.getAnimationParameterValues(model, accessors[sampler.output]); startTime = Math.min(startTime, input[0]); stopTime = Math.max(stopTime, input[input.length - 1]); var spline = ModelAnimationCache.getAnimationSpline(model, i, animation, channel.sampler, sampler, input, path, output); // GLTF_SPEC: Support more targets like materials. https://github.com/KhronosGroup/glTF/issues/142 channelEvaluators[j] = getChannelEvaluator(model, runtimeNodes[target.node], target.path, spline); } model._runtime.animations[i] = { name : animation.name, startTime : startTime, stopTime : stopTime, channelEvaluators : channelEvaluators }; }); } function createVertexArrays(model, context) { var loadResources = model._loadResources; if (!loadResources.finishedBuffersCreation() || !loadResources.finishedProgramCreation() || !loadResources.createVertexArrays) { return; } loadResources.createVertexArrays = false; var rendererBuffers = model._rendererResources.buffers; var rendererVertexArrays = model._rendererResources.vertexArrays; var gltf = model.gltf; var accessors = gltf.accessors; ForEach.mesh(gltf, function(mesh, meshId) { ForEach.meshPrimitive(mesh, function(primitive, primitiveId) { var attributes = []; var attributeLocation; var attributeLocations = getAttributeLocations(model, primitive); var decodedData = model._decodedData[meshId + '.primitive.' + primitiveId]; ForEach.meshPrimitiveAttribute(primitive, function(accessorId, attributeName) { // Skip if the attribute is not used by the material, e.g., because the asset // was exported with an attribute that wasn't used and the asset wasn't optimized. attributeLocation = attributeLocations[attributeName]; if (defined(attributeLocation)) { // Use attributes of previously decoded draco geometry if (defined(decodedData)) { var decodedAttributes = decodedData.attributes; if (decodedAttributes.hasOwnProperty(attributeName)) { var decodedAttribute = decodedAttributes[attributeName]; attributes.push({ index: attributeLocation, vertexBuffer: rendererBuffers[decodedAttribute.bufferView], componentsPerAttribute: decodedAttribute.componentsPerAttribute, componentDatatype: decodedAttribute.componentDatatype, normalize: decodedAttribute.normalized, offsetInBytes: decodedAttribute.byteOffset, strideInBytes: decodedAttribute.byteStride }); return; } } var a = accessors[accessorId]; var normalize = defined(a.normalized) && a.normalized; attributes.push({ index: attributeLocation, vertexBuffer: rendererBuffers[a.bufferView], componentsPerAttribute: numberOfComponentsForType(a.type), componentDatatype: a.componentType, normalize: normalize, offsetInBytes: a.byteOffset, strideInBytes: getAccessorByteStride(gltf, a) }); } }); // Add pre-created attributes var attribute; var attributeName; var precreatedAttributes = model._precreatedAttributes; if (defined(precreatedAttributes)) { for (attributeName in precreatedAttributes) { if (precreatedAttributes.hasOwnProperty(attributeName)) { attributeLocation = attributeLocations[attributeName]; if (defined(attributeLocation)) { attribute = precreatedAttributes[attributeName]; attribute.index = attributeLocation; attributes.push(attribute); } } } } var indexBuffer; if (defined(primitive.indices)) { var accessor = accessors[primitive.indices]; var bufferView = accessor.bufferView; // Use buffer of previously decoded draco geometry if (defined(decodedData)) { bufferView = decodedData.bufferView; } indexBuffer = rendererBuffers[bufferView]; } rendererVertexArrays[meshId + '.primitive.' + primitiveId] = new VertexArray({ context: context, attributes: attributes, indexBuffer: indexBuffer }); }); }); } function createRenderStates(model) { var loadResources = model._loadResources; if (loadResources.createRenderStates) { loadResources.createRenderStates = false; ForEach.material(model.gltf, function (material, materialId) { createRenderStateForMaterial(model, material, materialId); }); } } function createRenderStateForMaterial(model, material, materialId) { var rendererRenderStates = model._rendererResources.renderStates; var blendEquationSeparate = [ WebGLConstants.FUNC_ADD, WebGLConstants.FUNC_ADD ]; var blendFuncSeparate = [ WebGLConstants.ONE, WebGLConstants.ONE_MINUS_SRC_ALPHA, WebGLConstants.ONE, WebGLConstants.ONE_MINUS_SRC_ALPHA ]; if (defined(material.extensions) && defined(material.extensions.KHR_blend)) { blendEquationSeparate = material.extensions.KHR_blend.blendEquation; blendFuncSeparate = material.extensions.KHR_blend.blendFactors; } var enableCulling = !material.doubleSided; var blendingEnabled = (material.alphaMode === 'BLEND'); rendererRenderStates[materialId] = RenderState.fromCache({ cull : { enabled : enableCulling }, depthTest : { enabled : true }, depthMask : !blendingEnabled, blending : { enabled : blendingEnabled, equationRgb : blendEquationSeparate[0], equationAlpha : blendEquationSeparate[1], functionSourceRgb : blendFuncSeparate[0], functionDestinationRgb : blendFuncSeparate[1], functionSourceAlpha : blendFuncSeparate[2], functionDestinationAlpha : blendFuncSeparate[3] } }); } /////////////////////////////////////////////////////////////////////////// var gltfUniformsFromNode = { MODEL : function(uniformState, model, runtimeNode) { return function() { return runtimeNode.computedMatrix; }; }, VIEW : function(uniformState, model, runtimeNode) { return function() { return uniformState.view; }; }, PROJECTION : function(uniformState, model, runtimeNode) { return function() { return uniformState.projection; }; }, MODELVIEW : function(uniformState, model, runtimeNode) { var mv = new Matrix4(); return function() { return Matrix4.multiplyTransformation(uniformState.view, runtimeNode.computedMatrix, mv); }; }, CESIUM_RTC_MODELVIEW : function(uniformState, model, runtimeNode) { // CESIUM_RTC extension var mvRtc = new Matrix4(); return function() { Matrix4.multiplyTransformation(uniformState.view, runtimeNode.computedMatrix, mvRtc); return Matrix4.setTranslation(mvRtc, model._rtcCenterEye, mvRtc); }; }, MODELVIEWPROJECTION : function(uniformState, model, runtimeNode) { var mvp = new Matrix4(); return function() { Matrix4.multiplyTransformation(uniformState.view, runtimeNode.computedMatrix, mvp); return Matrix4.multiply(uniformState._projection, mvp, mvp); }; }, MODELINVERSE : function(uniformState, model, runtimeNode) { var mInverse = new Matrix4(); return function() { return Matrix4.inverse(runtimeNode.computedMatrix, mInverse); }; }, VIEWINVERSE : function(uniformState, model) { return function() { return uniformState.inverseView; }; }, PROJECTIONINVERSE : function(uniformState, model, runtimeNode) { return function() { return uniformState.inverseProjection; }; }, MODELVIEWINVERSE : function(uniformState, model, runtimeNode) { var mv = new Matrix4(); var mvInverse = new Matrix4(); return function() { Matrix4.multiplyTransformation(uniformState.view, runtimeNode.computedMatrix, mv); return Matrix4.inverse(mv, mvInverse); }; }, MODELVIEWPROJECTIONINVERSE : function(uniformState, model, runtimeNode) { var mvp = new Matrix4(); var mvpInverse = new Matrix4(); return function() { Matrix4.multiplyTransformation(uniformState.view, runtimeNode.computedMatrix, mvp); Matrix4.multiply(uniformState._projection, mvp, mvp); return Matrix4.inverse(mvp, mvpInverse); }; }, MODELINVERSETRANSPOSE : function(uniformState, model, runtimeNode) { var mInverse = new Matrix4(); var mInverseTranspose = new Matrix3(); return function() { Matrix4.inverse(runtimeNode.computedMatrix, mInverse); Matrix4.getRotation(mInverse, mInverseTranspose); return Matrix3.transpose(mInverseTranspose, mInverseTranspose); }; }, MODELVIEWINVERSETRANSPOSE : function(uniformState, model, runtimeNode) { var mv = new Matrix4(); var mvInverse = new Matrix4(); var mvInverseTranspose = new Matrix3(); return function() { Matrix4.multiplyTransformation(uniformState.view, runtimeNode.computedMatrix, mv); Matrix4.inverse(mv, mvInverse); Matrix4.getRotation(mvInverse, mvInverseTranspose); return Matrix3.transpose(mvInverseTranspose, mvInverseTranspose); }; }, VIEWPORT : function(uniformState, model, runtimeNode) { return function() { return uniformState.viewportCartesian4; }; } }; function getUniformFunctionFromSource(source, model, semantic, uniformState) { var runtimeNode = model._runtime.nodes[source]; return gltfUniformsFromNode[semantic](uniformState, model, runtimeNode); } function createUniformsForMaterial(model, material, technique, instanceValues, context, textures, defaultTexture) { var uniformMap = {}; var uniformValues = {}; var jointMatrixUniformName; var morphWeightsUniformName; ForEach.techniqueUniform(technique, function(uniform, uniformName) { // GLTF_SPEC: This does not take into account uniform arrays, // indicated by uniforms with a count property. // // https://github.com/KhronosGroup/glTF/issues/258 // GLTF_SPEC: In this implementation, material parameters with a // semantic or targeted via a source (for animation) are not // targetable for material animations. Is this too strict? // // https://github.com/KhronosGroup/glTF/issues/142 var uv; if (defined(instanceValues) && defined(instanceValues[uniformName])) { // Parameter overrides by the instance technique uv = ModelUtility.createUniformFunction(uniform.type, instanceValues[uniformName], textures, defaultTexture); uniformMap[uniformName] = uv.func; uniformValues[uniformName] = uv; } else if (defined(uniform.node)) { uniformMap[uniformName] = getUniformFunctionFromSource(uniform.node, model, uniform.semantic, context.uniformState); } else if (defined(uniform.semantic)) { if (uniform.semantic === 'JOINTMATRIX') { jointMatrixUniformName = uniformName; } else if (uniform.semantic === 'MORPHWEIGHTS') { morphWeightsUniformName = uniformName; } else if (uniform.semantic === 'ALPHACUTOFF') { // The material's alphaCutoff value uses a uniform with semantic ALPHACUTOFF. // A uniform with this semantic will ignore the instance or default values. var alphaMode = material.alphaMode; if (defined(alphaMode) && alphaMode === 'MASK') { var alphaCutoffValue = defaultValue(material.alphaCutoff, 0.5); uv = ModelUtility.createUniformFunction(uniform.type, alphaCutoffValue, textures, defaultTexture); uniformMap[uniformName] = uv.func; uniformValues[uniformName] = uv; } } else { // Map glTF semantic to Cesium automatic uniform uniformMap[uniformName] = ModelUtility.getGltfSemanticUniforms()[uniform.semantic](context.uniformState, model); } } else if (defined(uniform.value)) { // Technique value that isn't overridden by a material var uv2 = ModelUtility.createUniformFunction(uniform.type, uniform.value, textures, defaultTexture); uniformMap[uniformName] = uv2.func; uniformValues[uniformName] = uv2; } }); return { map : uniformMap, values : uniformValues, jointMatrixUniformName : jointMatrixUniformName, morphWeightsUniformName : morphWeightsUniformName }; } function createUniformMaps(model, context) { var loadResources = model._loadResources; if (!loadResources.finishedProgramCreation()) { return; } if (!loadResources.createUniformMaps) { return; } loadResources.createUniformMaps = false; var gltf = model.gltf; var techniques = model._sourceTechniques; var uniformMaps = model._uniformMaps; var textures = model._rendererResources.textures; var defaultTexture = model._defaultTexture; ForEach.material(gltf, function (material, materialId) { var modelMaterial = model._runtime.materialsById[materialId]; var technique = techniques[modelMaterial._technique]; var instanceValues = modelMaterial._values; var uniforms = createUniformsForMaterial(model, material, technique, instanceValues, context, textures, defaultTexture); var u = uniformMaps[materialId]; u.uniformMap = uniforms.map; // uniform name -> function for the renderer u.values = uniforms.values; // material parameter name -> ModelMaterial for modifying the parameter at runtime u.jointMatrixUniformName = uniforms.jointMatrixUniformName; u.morphWeightsUniformName = uniforms.morphWeightsUniformName; }); } function createUniformsForDracoQuantizedAttributes(decodedData) { return ModelUtility.createUniformsForDracoQuantizedAttributes(decodedData.attributes); } function createUniformsForQuantizedAttributes(model, primitive) { var programId = getProgramForPrimitive(model, primitive); var quantizedUniforms = model._quantizedUniforms[programId]; return ModelUtility.createUniformsForQuantizedAttributes(model.gltf, primitive, quantizedUniforms); } function createPickColorFunction(color) { return function() { return color; }; } function createJointMatricesFunction(runtimeNode) { return function() { return runtimeNode.computedJointMatrices; }; } function createMorphWeightsFunction(runtimeNode) { return function() { return runtimeNode.weights; }; } function createSilhouetteColorFunction(model) { return function() { return model.silhouetteColor; }; } function createSilhouetteSizeFunction(model) { return function() { return model.silhouetteSize; }; } function createColorFunction(model) { return function() { return model.color; }; } var scratchClippingPlaneMatrix = new Matrix4(); function createClippingPlanesMatrixFunction(model) { return function() { var clippingPlanes = model.clippingPlanes; if (!defined(clippingPlanes) && !defined(model._sphericalHarmonicCoefficients) && !defined(model._specularEnvironmentMaps)) { return Matrix4.IDENTITY; } var modelMatrix = defined(clippingPlanes) ? clippingPlanes.modelMatrix : Matrix4.IDENTITY; return Matrix4.multiply(model._clippingPlaneModelViewMatrix, modelMatrix, scratchClippingPlaneMatrix); }; } function createClippingPlanesFunction(model) { return function() { var clippingPlanes = model.clippingPlanes; return (!defined(clippingPlanes) || !clippingPlanes.enabled) ? model._defaultTexture : clippingPlanes.texture; }; } function createClippingPlanesEdgeStyleFunction(model) { return function() { var clippingPlanes = model.clippingPlanes; if (!defined(clippingPlanes)) { return Color.WHITE.withAlpha(0.0); } var style = Color.clone(clippingPlanes.edgeColor); style.alpha = clippingPlanes.edgeWidth; return style; }; } function createColorBlendFunction(model) { return function() { return ColorBlendMode.getColorBlend(model.colorBlendMode, model.colorBlendAmount); }; } function createIBLFactorFunction(model) { return function() { return model._imageBasedLightingFactor; }; } function createLightColorFunction(model) { return function() { return model._lightColor; }; } function createLuminanceAtZenithFunction(model) { return function() { return model.luminanceAtZenith; }; } function createSphericalHarmonicCoefficientsFunction(model) { return function() { return model._sphericalHarmonicCoefficients; }; } function createSpecularEnvironmentMapFunction(model) { return function() { return model._specularEnvironmentMapAtlas.texture; }; } function createSpecularEnvironmentMapSizeFunction(model) { return function() { return model._specularEnvironmentMapAtlas.texture.dimensions; }; } function createSpecularEnvironmentMapLOD(model) { return function() { return model._specularEnvironmentMapAtlas.maximumMipmapLevel; }; } function triangleCountFromPrimitiveIndices(primitive, indicesCount) { switch (primitive.mode) { case PrimitiveType.TRIANGLES: return (indicesCount / 3); case PrimitiveType.TRIANGLE_STRIP: case PrimitiveType.TRIANGLE_FAN: return Math.max(indicesCount - 2, 0); default: return 0; } } function createCommand(model, gltfNode, runtimeNode, context, scene3DOnly) { var nodeCommands = model._nodeCommands; var pickIds = model._pickIds; var allowPicking = model.allowPicking; var runtimeMeshesByName = model._runtime.meshesByName; var resources = model._rendererResources; var rendererVertexArrays = resources.vertexArrays; var rendererPrograms = resources.programs; var rendererRenderStates = resources.renderStates; var uniformMaps = model._uniformMaps; var gltf = model.gltf; var accessors = gltf.accessors; var gltfMeshes = gltf.meshes; var id = gltfNode.mesh; var mesh = gltfMeshes[id]; var primitives = mesh.primitives; var length = primitives.length; // The glTF node hierarchy is a DAG so a node can have more than one // parent, so a node may already have commands. If so, append more // since they will have a different model matrix. for (var i = 0; i < length; ++i) { var primitive = primitives[i]; var ix = accessors[primitive.indices]; var material = model._runtime.materialsById[primitive.material]; var programId = material._program; var decodedData = model._decodedData[id + '.primitive.' + i]; var boundingSphere; var positionAccessor = primitive.attributes.POSITION; if (defined(positionAccessor)) { var minMax = ModelUtility.getAccessorMinMax(gltf, positionAccessor); boundingSphere = BoundingSphere.fromCornerPoints(Cartesian3.fromArray(minMax.min), Cartesian3.fromArray(minMax.max)); } var vertexArray = rendererVertexArrays[id + '.primitive.' + i]; var offset; var count; // Use indices of the previously decoded Draco geometry. if (defined(decodedData)) { count = decodedData.numberOfIndices; offset = 0; } else if (defined(ix)) { count = ix.count; offset = (ix.byteOffset / IndexDatatype.getSizeInBytes(ix.componentType)); // glTF has offset in bytes. Cesium has offsets in indices } else { var positions = accessors[primitive.attributes.POSITION]; count = positions.count; offset = 0; } // Update model triangle count using number of indices model._trianglesLength += triangleCountFromPrimitiveIndices(primitive, count); var um = uniformMaps[primitive.material]; var uniformMap = um.uniformMap; if (defined(um.jointMatrixUniformName)) { var jointUniformMap = {}; jointUniformMap[um.jointMatrixUniformName] = createJointMatricesFunction(runtimeNode); uniformMap = combine(uniformMap, jointUniformMap); } if (defined(um.morphWeightsUniformName)) { var morphWeightsUniformMap = {}; morphWeightsUniformMap[um.morphWeightsUniformName] = createMorphWeightsFunction(runtimeNode); uniformMap = combine(uniformMap, morphWeightsUniformMap); } uniformMap = combine(uniformMap, { gltf_color : createColorFunction(model), gltf_colorBlend : createColorBlendFunction(model), gltf_clippingPlanes : createClippingPlanesFunction(model), gltf_clippingPlanesEdgeStyle : createClippingPlanesEdgeStyleFunction(model), gltf_clippingPlanesMatrix : createClippingPlanesMatrixFunction(model), gltf_iblFactor : createIBLFactorFunction(model), gltf_lightColor : createLightColorFunction(model), gltf_sphericalHarmonicCoefficients : createSphericalHarmonicCoefficientsFunction(model), gltf_specularMap : createSpecularEnvironmentMapFunction(model), gltf_specularMapSize : createSpecularEnvironmentMapSizeFunction(model), gltf_maxSpecularLOD : createSpecularEnvironmentMapLOD(model), gltf_luminanceAtZenith : createLuminanceAtZenithFunction(model) }); // Allow callback to modify the uniformMap if (defined(model._uniformMapLoaded)) { uniformMap = model._uniformMapLoaded(uniformMap, programId, runtimeNode); } // Add uniforms for decoding quantized attributes if used var quantizedUniformMap = {}; if (model.extensionsUsed.WEB3D_quantized_attributes) { quantizedUniformMap = createUniformsForQuantizedAttributes(model, primitive); } else if (model._dequantizeInShader && defined(decodedData)) { quantizedUniformMap = createUniformsForDracoQuantizedAttributes(decodedData); } uniformMap = combine(uniformMap, quantizedUniformMap); var rs = rendererRenderStates[primitive.material]; var isTranslucent = rs.blending.enabled; var owner = model._pickObject; if (!defined(owner)) { owner = { primitive : model, id : model.id, node : runtimeNode.publicNode, mesh : runtimeMeshesByName[mesh.name] }; } var castShadows = ShadowMode.castShadows(model._shadows); var receiveShadows = ShadowMode.receiveShadows(model._shadows); var pickId; if (allowPicking && !defined(model._uniformMapLoaded)) { pickId = context.createPickId(owner); pickIds.push(pickId); var pickUniforms = { czm_pickColor : createPickColorFunction(pickId.color) }; uniformMap = combine(uniformMap, pickUniforms); } if (allowPicking) { if (defined(model._pickIdLoaded) && defined(model._uniformMapLoaded)) { pickId = model._pickIdLoaded(); } else { pickId = 'czm_pickColor'; } } var command = new DrawCommand({ boundingVolume : new BoundingSphere(), // updated in update() cull : model.cull, modelMatrix : new Matrix4(), // computed in update() primitiveType : primitive.mode, vertexArray : vertexArray, count : count, offset : offset, shaderProgram : rendererPrograms[programId], castShadows : castShadows, receiveShadows : receiveShadows, uniformMap : uniformMap, renderState : rs, owner : owner, pass : isTranslucent ? Pass.TRANSLUCENT : model.opaquePass, pickId : pickId }); var command2D; if (!scene3DOnly) { command2D = DrawCommand.shallowClone(command); command2D.boundingVolume = new BoundingSphere(); // updated in update() command2D.modelMatrix = new Matrix4(); // updated in update() } var nodeCommand = { show : true, boundingSphere : boundingSphere, command : command, command2D : command2D, // Generated on demand when silhouette size is greater than 0.0 and silhouette alpha is greater than 0.0 silhouetteModelCommand : undefined, silhouetteModelCommand2D : undefined, silhouetteColorCommand : undefined, silhouetteColorCommand2D : undefined, // Generated on demand when color alpha is less than 1.0 translucentCommand : undefined, translucentCommand2D : undefined, // For updating node commands on shader reconstruction programId : programId }; runtimeNode.commands.push(nodeCommand); nodeCommands.push(nodeCommand); } } function createRuntimeNodes(model, context, scene3DOnly) { var loadResources = model._loadResources; if (!loadResources.finishedEverythingButTextureCreation()) { return; } if (!loadResources.createRuntimeNodes) { return; } loadResources.createRuntimeNodes = false; var rootNodes = []; var runtimeNodes = model._runtime.nodes; var gltf = model.gltf; var nodes = gltf.nodes; var skins = gltf.skins; var scene = gltf.scenes[gltf.scene]; var sceneNodes = scene.nodes; var length = sceneNodes.length; var stack = []; var seen = {}; for (var i = 0; i < length; ++i) { stack.push({ parentRuntimeNode : undefined, gltfNode : nodes[sceneNodes[i]], id : sceneNodes[i] }); var skeletonIds = []; while (stack.length > 0) { var n = stack.pop(); seen[n.id] = true; var parentRuntimeNode = n.parentRuntimeNode; var gltfNode = n.gltfNode; // Node hierarchy is a DAG so a node can have more than one parent so it may already exist var runtimeNode = runtimeNodes[n.id]; if (runtimeNode.parents.length === 0) { if (defined(gltfNode.matrix)) { runtimeNode.matrix = Matrix4.fromColumnMajorArray(gltfNode.matrix); } else { // TRS converted to Cesium types var rotation = gltfNode.rotation; runtimeNode.translation = Cartesian3.fromArray(gltfNode.translation); runtimeNode.rotation = Quaternion.unpack(rotation); runtimeNode.scale = Cartesian3.fromArray(gltfNode.scale); } } if (defined(parentRuntimeNode)) { parentRuntimeNode.children.push(runtimeNode); runtimeNode.parents.push(parentRuntimeNode); } else { rootNodes.push(runtimeNode); } if (defined(gltfNode.mesh)) { createCommand(model, gltfNode, runtimeNode, context, scene3DOnly); } var children = gltfNode.children; if (defined(children)) { var childrenLength = children.length; for (var j = 0; j < childrenLength; j++) { var childId = children[j]; if (!seen[childId]) { stack.push({ parentRuntimeNode : runtimeNode, gltfNode : nodes[childId], id : children[j] }); } } } var skin = gltfNode.skin; if (defined(skin)) { skeletonIds.push(skins[skin].skeleton); } if (stack.length === 0) { for (var k = 0; k < skeletonIds.length; k++) { var skeleton = skeletonIds[k]; if (!seen[skeleton]) { stack.push({ parentRuntimeNode : undefined, gltfNode : nodes[skeleton], id : skeleton }); } } } } } model._runtime.rootNodes = rootNodes; model._runtime.nodes = runtimeNodes; } function getGeometryByteLength(buffers) { var memory = 0; for (var id in buffers) { if (buffers.hasOwnProperty(id)) { memory += buffers[id].sizeInBytes; } } return memory; } function getTexturesByteLength(textures) { var memory = 0; for (var id in textures) { if (textures.hasOwnProperty(id)) { memory += textures[id].sizeInBytes; } } return memory; } function createResources(model, frameState) { var context = frameState.context; var scene3DOnly = frameState.scene3DOnly; var quantizedVertexShaders = model._quantizedVertexShaders; var toClipCoordinates = model._toClipCoordinatesGLSL = {}; var techniques = model._sourceTechniques; var programs = model._sourcePrograms; var resources = model._rendererResources; var shaders = resources.sourceShaders; if (model._loadRendererResourcesFromCache) { shaders = resources.sourceShaders = model._cachedRendererResources.sourceShaders; } for (var techniqueId in techniques) { if (techniques.hasOwnProperty(techniqueId)) { var programId = techniques[techniqueId].program; var program = programs[programId]; var shader = shaders[program.vertexShader]; ModelUtility.checkSupportedGlExtensions(program.glExtensions, context); if (model.extensionsUsed.WEB3D_quantized_attributes || model._dequantizeInShader) { var quantizedVS = quantizedVertexShaders[programId]; if (!defined(quantizedVS)) { quantizedVS = modifyShaderForQuantizedAttributes(shader, programId, model); quantizedVertexShaders[programId] = quantizedVS; } shader = quantizedVS; } shader = modifyShader(shader, programId, model._vertexShaderLoaded); toClipCoordinates[programId] = ModelUtility.toClipCoordinatesGLSL(model.gltf, shader); } } if (model._loadRendererResourcesFromCache) { var cachedResources = model._cachedRendererResources; resources.buffers = cachedResources.buffers; resources.vertexArrays = cachedResources.vertexArrays; resources.programs = cachedResources.programs; resources.silhouettePrograms = cachedResources.silhouettePrograms; resources.textures = cachedResources.textures; resources.samplers = cachedResources.samplers; resources.renderStates = cachedResources.renderStates; // Vertex arrays are unique to this model, create instead of using the cache. if (defined(model._precreatedAttributes)) { createVertexArrays(model, context); } model._cachedGeometryByteLength += getGeometryByteLength(cachedResources.buffers); model._cachedTexturesByteLength += getTexturesByteLength(cachedResources.textures); } else { createBuffers(model, frameState); // using glTF bufferViews createPrograms(model, frameState); createSamplers(model, context); loadTexturesFromBufferViews(model); createTextures(model, frameState); } createSkins(model); createRuntimeAnimations(model); if (!model._loadRendererResourcesFromCache) { createVertexArrays(model, context); // using glTF meshes createRenderStates(model); // using glTF materials/techniques/states // Long-term, we might not cache render states if they could change // due to an animation, e.g., a uniform going from opaque to transparent. // Could use copy-on-write if it is worth it. Probably overkill. } createUniformMaps(model, context); // using glTF materials/techniques createRuntimeNodes(model, context, scene3DOnly); // using glTF scene } /////////////////////////////////////////////////////////////////////////// function getNodeMatrix(node, result) { var publicNode = node.publicNode; var publicMatrix = publicNode.matrix; if (publicNode.useMatrix && defined(publicMatrix)) { // Public matrix overrides original glTF matrix and glTF animations Matrix4.clone(publicMatrix, result); } else if (defined(node.matrix)) { Matrix4.clone(node.matrix, result); } else { Matrix4.fromTranslationQuaternionRotationScale(node.translation, node.rotation, node.scale, result); // Keep matrix returned by the node in-sync if the node is targeted by an animation. Only TRS nodes can be targeted. publicNode.setMatrix(result); } } var scratchNodeStack = []; var scratchComputedTranslation = new Cartesian4(); var scratchComputedMatrixIn2D = new Matrix4(); function updateNodeHierarchyModelMatrix(model, modelTransformChanged, justLoaded, projection) { var maxDirtyNumber = model._maxDirtyNumber; var rootNodes = model._runtime.rootNodes; var length = rootNodes.length; var nodeStack = scratchNodeStack; var computedModelMatrix = model._computedModelMatrix; if ((model._mode !== SceneMode.SCENE3D) && !model._ignoreCommands) { var translation = Matrix4.getColumn(computedModelMatrix, 3, scratchComputedTranslation); if (!Cartesian4.equals(translation, Cartesian4.UNIT_W)) { computedModelMatrix = Transforms.basisTo2D(projection, computedModelMatrix, scratchComputedMatrixIn2D); model._rtcCenter = model._rtcCenter3D; } else { var center = model.boundingSphere.center; var to2D = Transforms.wgs84To2DModelMatrix(projection, center, scratchComputedMatrixIn2D); computedModelMatrix = Matrix4.multiply(to2D, computedModelMatrix, scratchComputedMatrixIn2D); if (defined(model._rtcCenter)) { Matrix4.setTranslation(computedModelMatrix, Cartesian4.UNIT_W, computedModelMatrix); model._rtcCenter = model._rtcCenter2D; } } } for (var i = 0; i < length; ++i) { var n = rootNodes[i]; getNodeMatrix(n, n.transformToRoot); nodeStack.push(n); while (nodeStack.length > 0) { n = nodeStack.pop(); var transformToRoot = n.transformToRoot; var commands = n.commands; if ((n.dirtyNumber === maxDirtyNumber) || modelTransformChanged || justLoaded) { var nodeMatrix = Matrix4.multiplyTransformation(computedModelMatrix, transformToRoot, n.computedMatrix); var commandsLength = commands.length; if (commandsLength > 0) { // Node has meshes, which has primitives. Update their commands. for (var j = 0; j < commandsLength; ++j) { var primitiveCommand = commands[j]; var command = primitiveCommand.command; Matrix4.clone(nodeMatrix, command.modelMatrix); // PERFORMANCE_IDEA: Can use transformWithoutScale if no node up to the root has scale (including animation) BoundingSphere.transform(primitiveCommand.boundingSphere, command.modelMatrix, command.boundingVolume); if (defined(model._rtcCenter)) { Cartesian3.add(model._rtcCenter, command.boundingVolume.center, command.boundingVolume.center); } // If the model crosses the IDL in 2D, it will be drawn in one viewport, but part of it // will be clipped by the viewport. We create a second command that translates the model // model matrix to the opposite side of the map so the part that was clipped in one viewport // is drawn in the other. command = primitiveCommand.command2D; if (defined(command) && model._mode === SceneMode.SCENE2D) { Matrix4.clone(nodeMatrix, command.modelMatrix); command.modelMatrix[13] -= CesiumMath.sign(command.modelMatrix[13]) * 2.0 * CesiumMath.PI * projection.ellipsoid.maximumRadius; BoundingSphere.transform(primitiveCommand.boundingSphere, command.modelMatrix, command.boundingVolume); } } } } var children = n.children; if (defined(children)) { var childrenLength = children.length; for (var k = 0; k < childrenLength; ++k) { var child = children[k]; // A node's transform needs to be updated if // - It was targeted for animation this frame, or // - Any of its ancestors were targeted for animation this frame // PERFORMANCE_IDEA: if a child has multiple parents and only one of the parents // is dirty, all the subtrees for each child instance will be dirty; we probably // won't see this in the wild often. child.dirtyNumber = Math.max(child.dirtyNumber, n.dirtyNumber); if ((child.dirtyNumber === maxDirtyNumber) || justLoaded) { // Don't check for modelTransformChanged since if only the model's model matrix changed, // we do not need to rebuild the local transform-to-root, only the final // [model's-model-matrix][transform-to-root] above. getNodeMatrix(child, child.transformToRoot); Matrix4.multiplyTransformation(transformToRoot, child.transformToRoot, child.transformToRoot); } nodeStack.push(child); } } } } ++model._maxDirtyNumber; } var scratchObjectSpace = new Matrix4(); function applySkins(model) { var skinnedNodes = model._runtime.skinnedNodes; var length = skinnedNodes.length; for (var i = 0; i < length; ++i) { var node = skinnedNodes[i]; scratchObjectSpace = Matrix4.inverseTransformation(node.transformToRoot, scratchObjectSpace); var computedJointMatrices = node.computedJointMatrices; var joints = node.joints; var bindShapeMatrix = node.bindShapeMatrix; var inverseBindMatrices = node.inverseBindMatrices; var inverseBindMatricesLength = inverseBindMatrices.length; for (var m = 0; m < inverseBindMatricesLength; ++m) { // [joint-matrix] = [node-to-root^-1][joint-to-root][inverse-bind][bind-shape] if (!defined(computedJointMatrices[m])) { computedJointMatrices[m] = new Matrix4(); } computedJointMatrices[m] = Matrix4.multiplyTransformation(scratchObjectSpace, joints[m].transformToRoot, computedJointMatrices[m]); computedJointMatrices[m] = Matrix4.multiplyTransformation(computedJointMatrices[m], inverseBindMatrices[m], computedJointMatrices[m]); if (defined(bindShapeMatrix)) { // Optimization for when bind shape matrix is the identity. computedJointMatrices[m] = Matrix4.multiplyTransformation(computedJointMatrices[m], bindShapeMatrix, computedJointMatrices[m]); } } } } function updatePerNodeShow(model) { // Totally not worth it, but we could optimize this: // http://blogs.agi.com/insight3d/index.php/2008/02/13/deletion-in-bounding-volume-hierarchies/ var rootNodes = model._runtime.rootNodes; var length = rootNodes.length; var nodeStack = scratchNodeStack; for (var i = 0; i < length; ++i) { var n = rootNodes[i]; n.computedShow = n.publicNode.show; nodeStack.push(n); while (nodeStack.length > 0) { n = nodeStack.pop(); var show = n.computedShow; var nodeCommands = n.commands; var nodeCommandsLength = nodeCommands.length; for (var j = 0; j < nodeCommandsLength; ++j) { nodeCommands[j].show = show; } // if commandsLength is zero, the node has a light or camera var children = n.children; if (defined(children)) { var childrenLength = children.length; for (var k = 0; k < childrenLength; ++k) { var child = children[k]; // Parent needs to be shown for child to be shown. child.computedShow = show && child.publicNode.show; nodeStack.push(child); } } } } } function updatePickIds(model, context) { var id = model.id; if (model._id !== id) { model._id = id; var pickIds = model._pickIds; var length = pickIds.length; for (var i = 0; i < length; ++i) { pickIds[i].object.id = id; } } } function updateWireframe(model) { if (model._debugWireframe !== model.debugWireframe) { model._debugWireframe = model.debugWireframe; // This assumes the original primitive was TRIANGLES and that the triangles // are connected for the wireframe to look perfect. var primitiveType = model.debugWireframe ? PrimitiveType.LINES : PrimitiveType.TRIANGLES; var nodeCommands = model._nodeCommands; var length = nodeCommands.length; for (var i = 0; i < length; ++i) { nodeCommands[i].command.primitiveType = primitiveType; } } } function updateShowBoundingVolume(model) { if (model.debugShowBoundingVolume !== model._debugShowBoundingVolume) { model._debugShowBoundingVolume = model.debugShowBoundingVolume; var debugShowBoundingVolume = model.debugShowBoundingVolume; var nodeCommands = model._nodeCommands; var length = nodeCommands.length; for (var i = 0; i < length; ++i) { nodeCommands[i].command.debugShowBoundingVolume = debugShowBoundingVolume; } } } function updateShadows(model) { if (model.shadows !== model._shadows) { model._shadows = model.shadows; var castShadows = ShadowMode.castShadows(model.shadows); var receiveShadows = ShadowMode.receiveShadows(model.shadows); var nodeCommands = model._nodeCommands; var length = nodeCommands.length; for (var i = 0; i < length; i++) { var nodeCommand = nodeCommands[i]; nodeCommand.command.castShadows = castShadows; nodeCommand.command.receiveShadows = receiveShadows; } } } function getTranslucentRenderState(renderState) { var rs = clone(renderState, true); rs.cull.enabled = false; rs.depthTest.enabled = true; rs.depthMask = false; rs.blending = BlendingState.ALPHA_BLEND; return RenderState.fromCache(rs); } function deriveTranslucentCommand(command) { var translucentCommand = DrawCommand.shallowClone(command); translucentCommand.pass = Pass.TRANSLUCENT; translucentCommand.renderState = getTranslucentRenderState(command.renderState); return translucentCommand; } function updateColor(model, frameState, forceDerive) { // Generate translucent commands when the blend color has an alpha in the range (0.0, 1.0) exclusive var scene3DOnly = frameState.scene3DOnly; var alpha = model.color.alpha; if ((alpha > 0.0) && (alpha < 1.0)) { var nodeCommands = model._nodeCommands; var length = nodeCommands.length; if (!defined(nodeCommands[0].translucentCommand) || forceDerive) { for (var i = 0; i < length; ++i) { var nodeCommand = nodeCommands[i]; var command = nodeCommand.command; nodeCommand.translucentCommand = deriveTranslucentCommand(command); if (!scene3DOnly) { var command2D = nodeCommand.command2D; nodeCommand.translucentCommand2D = deriveTranslucentCommand(command2D); } } } } } function getProgramId(model, program) { var programs = model._rendererResources.programs; for (var id in programs) { if (programs.hasOwnProperty(id)) { if (programs[id] === program) { return id; } } } } function createSilhouetteProgram(model, program, frameState) { var vs = program.vertexShaderSource.sources[0]; var attributeLocations = program._attributeLocations; var normalAttributeName = model._normalAttributeName; // Modified from http://forum.unity3d.com/threads/toon-outline-but-with-diffuse-surface.24668/ vs = ShaderSource.replaceMain(vs, 'gltf_silhouette_main'); vs += 'uniform float gltf_silhouetteSize; \n' + 'void main() \n' + '{ \n' + ' gltf_silhouette_main(); \n' + ' vec3 n = normalize(czm_normal3D * ' + normalAttributeName + '); \n' + ' n.x *= czm_projection[0][0]; \n' + ' n.y *= czm_projection[1][1]; \n' + ' vec4 clip = gl_Position; \n' + ' clip.xy += n.xy * clip.w * gltf_silhouetteSize / czm_viewport.z; \n' + ' gl_Position = clip; \n' + '}'; var fs = 'uniform vec4 gltf_silhouetteColor; \n' + 'void main() \n' + '{ \n' + ' gl_FragColor = czm_gammaCorrect(gltf_silhouetteColor); \n' + '}'; return ShaderProgram.fromCache({ context : frameState.context, vertexShaderSource : vs, fragmentShaderSource : fs, attributeLocations : attributeLocations }); } function hasSilhouette(model, frameState) { return silhouetteSupported(frameState.context) && (model.silhouetteSize > 0.0) && (model.silhouetteColor.alpha > 0.0) && defined(model._normalAttributeName); } function hasTranslucentCommands(model) { var nodeCommands = model._nodeCommands; var length = nodeCommands.length; for (var i = 0; i < length; ++i) { var nodeCommand = nodeCommands[i]; var command = nodeCommand.command; if (command.pass === Pass.TRANSLUCENT) { return true; } } return false; } function isTranslucent(model) { return (model.color.alpha > 0.0) && (model.color.alpha < 1.0); } function isInvisible(model) { return (model.color.alpha === 0.0); } function alphaDirty(currAlpha, prevAlpha) { // Returns whether the alpha state has changed between invisible, translucent, or opaque return (Math.floor(currAlpha) !== Math.floor(prevAlpha)) || (Math.ceil(currAlpha) !== Math.ceil(prevAlpha)); } var silhouettesLength = 0; function createSilhouetteCommands(model, frameState) { // Wrap around after exceeding the 8-bit stencil limit. // The reference is unique to each model until this point. var stencilReference = (++silhouettesLength) % 255; // If the model is translucent the silhouette needs to be in the translucent pass. // Otherwise the silhouette would be rendered before the model. var silhouetteTranslucent = hasTranslucentCommands(model) || isTranslucent(model) || (model.silhouetteColor.alpha < 1.0); var silhouettePrograms = model._rendererResources.silhouettePrograms; var scene3DOnly = frameState.scene3DOnly; var nodeCommands = model._nodeCommands; var length = nodeCommands.length; for (var i = 0; i < length; ++i) { var nodeCommand = nodeCommands[i]; var command = nodeCommand.command; // Create model command var modelCommand = isTranslucent(model) ? nodeCommand.translucentCommand : command; var silhouetteModelCommand = DrawCommand.shallowClone(modelCommand); var renderState = clone(modelCommand.renderState); // Write the reference value into the stencil buffer. renderState.stencilTest = { enabled : true, frontFunction : WebGLConstants.ALWAYS, backFunction : WebGLConstants.ALWAYS, reference : stencilReference, mask : ~0, frontOperation : { fail : WebGLConstants.KEEP, zFail : WebGLConstants.KEEP, zPass : WebGLConstants.REPLACE }, backOperation : { fail : WebGLConstants.KEEP, zFail : WebGLConstants.KEEP, zPass : WebGLConstants.REPLACE } }; if (isInvisible(model)) { // When the model is invisible disable color and depth writes but still write into the stencil buffer renderState.colorMask = { red : false, green : false, blue : false, alpha : false }; renderState.depthMask = false; } renderState = RenderState.fromCache(renderState); silhouetteModelCommand.renderState = renderState; nodeCommand.silhouetteModelCommand = silhouetteModelCommand; // Create color command var silhouetteColorCommand = DrawCommand.shallowClone(command); renderState = clone(command.renderState, true); renderState.depthTest.enabled = true; renderState.cull.enabled = false; if (silhouetteTranslucent) { silhouetteColorCommand.pass = Pass.TRANSLUCENT; renderState.depthMask = false; renderState.blending = BlendingState.ALPHA_BLEND; } // Only render silhouette if the value in the stencil buffer equals the reference renderState.stencilTest = { enabled : true, frontFunction : WebGLConstants.NOTEQUAL, backFunction : WebGLConstants.NOTEQUAL, reference : stencilReference, mask : ~0, frontOperation : { fail : WebGLConstants.KEEP, zFail : WebGLConstants.KEEP, zPass : WebGLConstants.KEEP }, backOperation : { fail : WebGLConstants.KEEP, zFail : WebGLConstants.KEEP, zPass : WebGLConstants.KEEP } }; renderState = RenderState.fromCache(renderState); // If the silhouette program has already been cached use it var program = command.shaderProgram; var id = getProgramId(model, program); var silhouetteProgram = silhouettePrograms[id]; if (!defined(silhouetteProgram)) { silhouetteProgram = createSilhouetteProgram(model, program, frameState); silhouettePrograms[id] = silhouetteProgram; } var silhouetteUniformMap = combine(command.uniformMap, { gltf_silhouetteColor : createSilhouetteColorFunction(model), gltf_silhouetteSize : createSilhouetteSizeFunction(model) }); silhouetteColorCommand.renderState = renderState; silhouetteColorCommand.shaderProgram = silhouetteProgram; silhouetteColorCommand.uniformMap = silhouetteUniformMap; silhouetteColorCommand.castShadows = false; silhouetteColorCommand.receiveShadows = false; nodeCommand.silhouetteColorCommand = silhouetteColorCommand; if (!scene3DOnly) { var command2D = nodeCommand.command2D; var silhouetteModelCommand2D = DrawCommand.shallowClone(silhouetteModelCommand); silhouetteModelCommand2D.boundingVolume = command2D.boundingVolume; silhouetteModelCommand2D.modelMatrix = command2D.modelMatrix; nodeCommand.silhouetteModelCommand2D = silhouetteModelCommand2D; var silhouetteColorCommand2D = DrawCommand.shallowClone(silhouetteColorCommand); silhouetteModelCommand2D.boundingVolume = command2D.boundingVolume; silhouetteModelCommand2D.modelMatrix = command2D.modelMatrix; nodeCommand.silhouetteColorCommand2D = silhouetteColorCommand2D; } } } function modifyShaderForClippingPlanes(shader, clippingPlaneCollection, context) { shader = ShaderSource.replaceMain(shader, 'gltf_clip_main'); shader += Model._getClippingFunction(clippingPlaneCollection, context) + '\n'; shader += 'uniform sampler2D gltf_clippingPlanes; \n' + 'uniform mat4 gltf_clippingPlanesMatrix; \n' + 'uniform vec4 gltf_clippingPlanesEdgeStyle; \n' + 'void main() \n' + '{ \n' + ' gltf_clip_main(); \n' + getClipAndStyleCode('gltf_clippingPlanes', 'gltf_clippingPlanesMatrix', 'gltf_clippingPlanesEdgeStyle') + '} \n'; return shader; } function updateSilhouette(model, frameState, force) { // Generate silhouette commands when the silhouette size is greater than 0.0 and the alpha is greater than 0.0 // There are two silhouette commands: // 1. silhouetteModelCommand : render model normally while enabling stencil mask // 2. silhouetteColorCommand : render enlarged model with a solid color while enabling stencil tests if (!hasSilhouette(model, frameState)) { return; } var nodeCommands = model._nodeCommands; var dirty = alphaDirty(model.color.alpha, model._colorPreviousAlpha) || alphaDirty(model.silhouetteColor.alpha, model._silhouetteColorPreviousAlpha) || !defined(nodeCommands[0].silhouetteModelCommand); model._colorPreviousAlpha = model.color.alpha; model._silhouetteColorPreviousAlpha = model.silhouetteColor.alpha; if (dirty || force) { createSilhouetteCommands(model, frameState); } } function updateClippingPlanes(model, frameState) { var clippingPlanes = model._clippingPlanes; if (defined(clippingPlanes) && clippingPlanes.owner === model) { if (clippingPlanes.enabled) { clippingPlanes.update(frameState); } } } var scratchBoundingSphere = new BoundingSphere(); function scaleInPixels(positionWC, radius, frameState) { scratchBoundingSphere.center = positionWC; scratchBoundingSphere.radius = radius; return frameState.camera.getPixelSize(scratchBoundingSphere, frameState.context.drawingBufferWidth, frameState.context.drawingBufferHeight); } var scratchPosition = new Cartesian3(); var scratchCartographic = new Cartographic(); function getScale(model, frameState) { var scale = model.scale; if (model.minimumPixelSize !== 0.0) { // Compute size of bounding sphere in pixels var context = frameState.context; var maxPixelSize = Math.max(context.drawingBufferWidth, context.drawingBufferHeight); var m = defined(model._clampedModelMatrix) ? model._clampedModelMatrix : model.modelMatrix; scratchPosition.x = m[12]; scratchPosition.y = m[13]; scratchPosition.z = m[14]; if (defined(model._rtcCenter)) { Cartesian3.add(model._rtcCenter, scratchPosition, scratchPosition); } if (model._mode !== SceneMode.SCENE3D) { var projection = frameState.mapProjection; var cartographic = projection.ellipsoid.cartesianToCartographic(scratchPosition, scratchCartographic); projection.project(cartographic, scratchPosition); Cartesian3.fromElements(scratchPosition.z, scratchPosition.x, scratchPosition.y, scratchPosition); } var radius = model.boundingSphere.radius; var metersPerPixel = scaleInPixels(scratchPosition, radius, frameState); // metersPerPixel is always > 0.0 var pixelsPerMeter = 1.0 / metersPerPixel; var diameterInPixels = Math.min(pixelsPerMeter * (2.0 * radius), maxPixelSize); // Maintain model's minimum pixel size if (diameterInPixels < model.minimumPixelSize) { scale = (model.minimumPixelSize * metersPerPixel) / (2.0 * model._initialRadius); } } return defined(model.maximumScale) ? Math.min(model.maximumScale, scale) : scale; } function releaseCachedGltf(model) { if (defined(model._cacheKey) && defined(model._cachedGltf) && (--model._cachedGltf.count === 0)) { delete gltfCache[model._cacheKey]; } model._cachedGltf = undefined; } /////////////////////////////////////////////////////////////////////////// function CachedRendererResources(context, cacheKey) { this.buffers = undefined; this.vertexArrays = undefined; this.programs = undefined; this.sourceShaders = undefined; this.silhouettePrograms = undefined; this.textures = undefined; this.samplers = undefined; this.renderStates = undefined; this.ready = false; this.context = context; this.cacheKey = cacheKey; this.count = 0; } function destroy(property) { for (var name in property) { if (property.hasOwnProperty(name)) { property[name].destroy(); } } } function destroyCachedRendererResources(resources) { destroy(resources.buffers); destroy(resources.vertexArrays); destroy(resources.programs); destroy(resources.silhouettePrograms); destroy(resources.textures); } CachedRendererResources.prototype.release = function() { if (--this.count === 0) { if (defined(this.cacheKey)) { // Remove if this was cached delete this.context.cache.modelRendererResourceCache[this.cacheKey]; } destroyCachedRendererResources(this); return destroyObject(this); } return undefined; }; /////////////////////////////////////////////////////////////////////////// function getUpdateHeightCallback(model, ellipsoid, cartoPosition) { return function(clampedPosition) { if (model.heightReference === HeightReference.RELATIVE_TO_GROUND) { var clampedCart = ellipsoid.cartesianToCartographic(clampedPosition, scratchCartographic); clampedCart.height += cartoPosition.height; ellipsoid.cartographicToCartesian(clampedCart, clampedPosition); } var clampedModelMatrix = model._clampedModelMatrix; // Modify clamped model matrix to use new height Matrix4.clone(model.modelMatrix, clampedModelMatrix); clampedModelMatrix[12] = clampedPosition.x; clampedModelMatrix[13] = clampedPosition.y; clampedModelMatrix[14] = clampedPosition.z; model._heightChanged = true; }; } function updateClamping(model) { if (defined(model._removeUpdateHeightCallback)) { model._removeUpdateHeightCallback(); model._removeUpdateHeightCallback = undefined; } var scene = model._scene; if (!defined(scene) || !defined(scene.globe) || (model.heightReference === HeightReference.NONE)) { //>>includeStart('debug', pragmas.debug); if (model.heightReference !== HeightReference.NONE) { throw new DeveloperError('Height reference is not supported without a scene and globe.'); } //>>includeEnd('debug'); model._clampedModelMatrix = undefined; return; } var globe = scene.globe; var ellipsoid = globe.ellipsoid; // Compute cartographic position so we don't recompute every update var modelMatrix = model.modelMatrix; scratchPosition.x = modelMatrix[12]; scratchPosition.y = modelMatrix[13]; scratchPosition.z = modelMatrix[14]; var cartoPosition = ellipsoid.cartesianToCartographic(scratchPosition); if (!defined(model._clampedModelMatrix)) { model._clampedModelMatrix = Matrix4.clone(modelMatrix, new Matrix4()); } // Install callback to handle updating of terrain tiles var surface = globe._surface; model._removeUpdateHeightCallback = surface.updateHeight(cartoPosition, getUpdateHeightCallback(model, ellipsoid, cartoPosition)); // Set the correct height now var height = globe.getHeight(cartoPosition); if (defined(height)) { // Get callback with cartoPosition being the non-clamped position var cb = getUpdateHeightCallback(model, ellipsoid, cartoPosition); // Compute the clamped cartesian and call updateHeight callback Cartographic.clone(cartoPosition, scratchCartographic); scratchCartographic.height = height; ellipsoid.cartographicToCartesian(scratchCartographic, scratchPosition); cb(scratchPosition); } } var scratchDisplayConditionCartesian = new Cartesian3(); var scratchDistanceDisplayConditionCartographic = new Cartographic(); function distanceDisplayConditionVisible(model, frameState) { var distance2; var ddc = model.distanceDisplayCondition; var nearSquared = ddc.near * ddc.near; var farSquared = ddc.far * ddc.far; if (frameState.mode === SceneMode.SCENE2D) { var frustum2DWidth = frameState.camera.frustum.right - frameState.camera.frustum.left; distance2 = frustum2DWidth * 0.5; distance2 = distance2 * distance2; } else { // Distance to center of primitive's reference frame var position = Matrix4.getTranslation(model.modelMatrix, scratchDisplayConditionCartesian); if (frameState.mode === SceneMode.COLUMBUS_VIEW) { var projection = frameState.mapProjection; var ellipsoid = projection.ellipsoid; var cartographic = ellipsoid.cartesianToCartographic(position, scratchDistanceDisplayConditionCartographic); position = projection.project(cartographic, position); Cartesian3.fromElements(position.z, position.x, position.y, position); } distance2 = Cartesian3.distanceSquared(position, frameState.camera.positionWC); } return (distance2 >= nearSquared) && (distance2 <= farSquared); } /** * Called when {@link Viewer} or {@link CesiumWidget} render the scene to * get the draw commands needed to render this primitive. * <p> * Do not call this function directly. This is documented just to * list the exceptions that may be propagated when the scene is rendered: * </p> * * @exception {RuntimeError} Failed to load external reference. */ Model.prototype.update = function(frameState) { if (frameState.mode === SceneMode.MORPHING) { return; } if (!FeatureDetection.supportsWebP.initialized) { FeatureDetection.supportsWebP.initialize(); return; } var supportsWebP = FeatureDetection.supportsWebP(); var context = frameState.context; this._defaultTexture = context.defaultTexture; if ((this._state === ModelState.NEEDS_LOAD) && defined(this.gltf)) { // Use renderer resources from cache instead of loading/creating them? var cachedRendererResources; var cacheKey = this.cacheKey; if (defined(cacheKey)) { // cache key given? this model will pull from or contribute to context level cache context.cache.modelRendererResourceCache = defaultValue(context.cache.modelRendererResourceCache, {}); var modelCaches = context.cache.modelRendererResourceCache; cachedRendererResources = modelCaches[this.cacheKey]; if (defined(cachedRendererResources)) { if (!cachedRendererResources.ready) { // Cached resources for the model are not loaded yet. We'll // try again every frame until they are. return; } ++cachedRendererResources.count; this._loadRendererResourcesFromCache = true; } else { cachedRendererResources = new CachedRendererResources(context, cacheKey); cachedRendererResources.count = 1; modelCaches[this.cacheKey] = cachedRendererResources; } this._cachedRendererResources = cachedRendererResources; } else { // cache key not given? this model doesn't care about context level cache at all. Cache is here to simplify freeing on destroy. cachedRendererResources = new CachedRendererResources(context); cachedRendererResources.count = 1; this._cachedRendererResources = cachedRendererResources; } this._state = ModelState.LOADING; if (this._state !== ModelState.FAILED) { var extensions = this.gltf.extensions; if (defined(extensions) && defined(extensions.CESIUM_RTC)) { var center = Cartesian3.fromArray(extensions.CESIUM_RTC.center); if (!Cartesian3.equals(center, Cartesian3.ZERO)) { this._rtcCenter3D = center; var projection = frameState.mapProjection; var ellipsoid = projection.ellipsoid; var cartographic = ellipsoid.cartesianToCartographic(this._rtcCenter3D); var projectedCart = projection.project(cartographic); Cartesian3.fromElements(projectedCart.z, projectedCart.x, projectedCart.y, projectedCart); this._rtcCenter2D = projectedCart; this._rtcCenterEye = new Cartesian3(); this._rtcCenter = this._rtcCenter3D; } } addPipelineExtras(this.gltf); this._loadResources = new ModelLoadResources(); if (!this._loadRendererResourcesFromCache) { // Buffers are required to updateVersion ModelUtility.parseBuffers(this, bufferLoad); } } } var loadResources = this._loadResources; var incrementallyLoadTextures = this._incrementallyLoadTextures; var justLoaded = false; if (this._state === ModelState.LOADING) { // Transition from LOADING -> LOADED once resources are downloaded and created. // Textures may continue to stream in while in the LOADED state. if (loadResources.pendingBufferLoads === 0) { if (!loadResources.initialized) { frameState.brdfLutGenerator.update(frameState); ModelUtility.checkSupportedExtensions(this.extensionsRequired, supportsWebP); ModelUtility.updateForwardAxis(this); // glTF pipeline updates, not needed if loading from cache if (!this._loadRendererResourcesFromCache) { var gltf = this.gltf; // Add the original version so it remains cached gltf.extras.sourceVersion = ModelUtility.getAssetVersion(gltf); gltf.extras.sourceKHRTechniquesWebGL = defined(ModelUtility.getUsedExtensions(gltf).KHR_techniques_webgl); this._sourceVersion = gltf.extras.sourceVersion; this._sourceKHRTechniquesWebGL = gltf.extras.sourceKHRTechniquesWebGL; updateVersion(gltf); addDefaults(gltf); var options = { addBatchIdToGeneratedShaders: this._addBatchIdToGeneratedShaders }; processModelMaterialsCommon(gltf, options); processPbrMaterials(gltf, options); } this._sourceVersion = this.gltf.extras.sourceVersion; this._sourceKHRTechniquesWebGL = this.gltf.extras.sourceKHRTechniquesWebGL; // Skip dequantizing in the shader if not encoded this._dequantizeInShader = this._dequantizeInShader && DracoLoader.hasExtension(this); // We do this after to make sure that the ids don't change addBuffersToLoadResources(this); parseTechniques(this); if (!this._loadRendererResourcesFromCache) { parseBufferViews(this); parseShaders(this); parsePrograms(this); parseTextures(this, context, supportsWebP); } parseMaterials(this); parseMeshes(this); parseNodes(this); // Start draco decoding DracoLoader.parse(this, context); loadResources.initialized = true; } if (!loadResources.finishedDecoding()) { DracoLoader.decodeModel(this, context) .otherwise(ModelUtility.getFailedLoadFunction(this, 'model', this.basePath)); } if (loadResources.finishedDecoding() && !loadResources.resourcesParsed) { this._boundingSphere = ModelUtility.computeBoundingSphere(this); this._initialRadius = this._boundingSphere.radius; DracoLoader.cacheDataForModel(this); loadResources.resourcesParsed = true; } if (loadResources.resourcesParsed && loadResources.pendingShaderLoads === 0) { createResources(this, frameState); } } if (loadResources.finished() || (incrementallyLoadTextures && loadResources.finishedEverythingButTextureCreation())) { this._state = ModelState.LOADED; justLoaded = true; } } // Incrementally stream textures. if (defined(loadResources) && (this._state === ModelState.LOADED)) { if (incrementallyLoadTextures && !justLoaded) { createResources(this, frameState); } if (loadResources.finished()) { if (!this._keepPipelineExtras) { removePipelineExtras(this.gltf); } this._loadResources = undefined; // Clear CPU memory since WebGL resources were created. var resources = this._rendererResources; var cachedResources = this._cachedRendererResources; cachedResources.buffers = resources.buffers; cachedResources.vertexArrays = resources.vertexArrays; cachedResources.programs = resources.programs; cachedResources.sourceShaders = resources.sourceShaders; cachedResources.silhouettePrograms = resources.silhouettePrograms; cachedResources.textures = resources.textures; cachedResources.samplers = resources.samplers; cachedResources.renderStates = resources.renderStates; cachedResources.ready = true; // The normal attribute name is required for silhouettes, so get it before the gltf JSON is released this._normalAttributeName = ModelUtility.getAttributeOrUniformBySemantic(this.gltf, 'NORMAL'); // Vertex arrays are unique to this model, do not store in cache. if (defined(this._precreatedAttributes)) { cachedResources.vertexArrays = {}; } if (this.releaseGltfJson) { releaseCachedGltf(this); } } } var iblSupported = OctahedralProjectedCubeMap.isSupported(context); if (this._shouldUpdateSpecularMapAtlas && iblSupported) { this._shouldUpdateSpecularMapAtlas = false; this._specularEnvironmentMapAtlas = this._specularEnvironmentMapAtlas && this._specularEnvironmentMapAtlas.destroy(); this._specularEnvironmentMapAtlas = undefined; if (defined(this._specularEnvironmentMaps)) { this._specularEnvironmentMapAtlas = new OctahedralProjectedCubeMap(this._specularEnvironmentMaps); var that = this; this._specularEnvironmentMapAtlas.readyPromise.then(function() { that._shouldRegenerateShaders = true; }); } // Regenerate shaders to not use an environment map. Will be set to true again if there was a new environment map and it is ready. this._shouldRegenerateShaders = true; } if (defined(this._specularEnvironmentMapAtlas)) { this._specularEnvironmentMapAtlas.update(frameState); } var recompileWithDefaultAtlas = !defined(this._specularEnvironmentMapAtlas) && defined(frameState.specularEnvironmentMaps) && !this._useDefaultSpecularMaps; var recompileWithoutDefaultAtlas = !defined(frameState.specularEnvironmentMaps) && this._useDefaultSpecularMaps; var recompileWithDefaultSHCoeffs = !defined(this._sphericalHarmonicCoefficients) && defined(frameState.sphericalHarmonicCoefficients) && !this._useDefaultSphericalHarmonics; var recompileWithoutDefaultSHCoeffs = !defined(frameState.sphericalHarmonicCoefficients) && this._useDefaultSphericalHarmonics; this._shouldRegenerateShaders = this._shouldRegenerateShaders || recompileWithDefaultAtlas || recompileWithoutDefaultAtlas || recompileWithDefaultSHCoeffs || recompileWithoutDefaultSHCoeffs; this._useDefaultSpecularMaps = !defined(this._specularEnvironmentMapAtlas) && defined(frameState.specularEnvironmentMaps); this._useDefaultSphericalHarmonics = !defined(this._sphericalHarmonicCoefficients) && defined(frameState.sphericalHarmonicCoefficients); var silhouette = hasSilhouette(this, frameState); var translucent = isTranslucent(this); var invisible = isInvisible(this); var displayConditionPassed = defined(this.distanceDisplayCondition) ? distanceDisplayConditionVisible(this, frameState) : true; var show = this.show && displayConditionPassed && (this.scale !== 0.0) && (!invisible || silhouette); if ((show && this._state === ModelState.LOADED) || justLoaded) { var animated = this.activeAnimations.update(frameState) || this._cesiumAnimationsDirty; this._cesiumAnimationsDirty = false; this._dirty = false; var modelMatrix = this.modelMatrix; var modeChanged = frameState.mode !== this._mode; this._mode = frameState.mode; // Model's model matrix needs to be updated var modelTransformChanged = !Matrix4.equals(this._modelMatrix, modelMatrix) || (this._scale !== this.scale) || (this._minimumPixelSize !== this.minimumPixelSize) || (this.minimumPixelSize !== 0.0) || // Minimum pixel size changed or is enabled (this._maximumScale !== this.maximumScale) || (this._heightReference !== this.heightReference) || this._heightChanged || modeChanged; if (modelTransformChanged || justLoaded) { Matrix4.clone(modelMatrix, this._modelMatrix); updateClamping(this); if (defined(this._clampedModelMatrix)) { modelMatrix = this._clampedModelMatrix; } this._scale = this.scale; this._minimumPixelSize = this.minimumPixelSize; this._maximumScale = this.maximumScale; this._heightReference = this.heightReference; this._heightChanged = false; var scale = getScale(this, frameState); var computedModelMatrix = this._computedModelMatrix; Matrix4.multiplyByUniformScale(modelMatrix, scale, computedModelMatrix); if (this._upAxis === Axis.Y) { Matrix4.multiplyTransformation(computedModelMatrix, Axis.Y_UP_TO_Z_UP, computedModelMatrix); } else if (this._upAxis === Axis.X) { Matrix4.multiplyTransformation(computedModelMatrix, Axis.X_UP_TO_Z_UP, computedModelMatrix); } if (this.forwardAxis === Axis.Z) { // glTF 2.0 has a Z-forward convention that must be adapted here to X-forward. Matrix4.multiplyTransformation(computedModelMatrix, Axis.Z_UP_TO_X_UP, computedModelMatrix); } } // Update modelMatrix throughout the graph as needed if (animated || modelTransformChanged || justLoaded) { updateNodeHierarchyModelMatrix(this, modelTransformChanged, justLoaded, frameState.mapProjection); this._dirty = true; if (animated || justLoaded) { // Apply skins if animation changed any node transforms applySkins(this); } } if (this._perNodeShowDirty) { this._perNodeShowDirty = false; updatePerNodeShow(this); } updatePickIds(this, context); updateWireframe(this); updateShowBoundingVolume(this); updateShadows(this); updateClippingPlanes(this, frameState); // Regenerate shaders if ClippingPlaneCollection state changed or it was removed var clippingPlanes = this._clippingPlanes; var currentClippingPlanesState = 0; var useClippingPlanes = defined(clippingPlanes) && clippingPlanes.enabled && clippingPlanes.length > 0; var usesSH = defined(this._sphericalHarmonicCoefficients) || this._useDefaultSphericalHarmonics; var usesSM = (defined(this._specularEnvironmentMapAtlas) && this._specularEnvironmentMapAtlas.ready) || this._useDefaultSpecularMaps; if (useClippingPlanes || usesSH || usesSM) { var clippingPlanesOriginMatrix = defaultValue(this.clippingPlanesOriginMatrix, modelMatrix); Matrix4.multiply(context.uniformState.view3D, clippingPlanesOriginMatrix, this._clippingPlaneModelViewMatrix); } if (useClippingPlanes) { currentClippingPlanesState = clippingPlanes.clippingPlanesState; } var shouldRegenerateShaders = this._shouldRegenerateShaders; shouldRegenerateShaders = shouldRegenerateShaders || this._clippingPlanesState !== currentClippingPlanesState; this._clippingPlanesState = currentClippingPlanesState; // Regenerate shaders if color shading changed from last update var currentlyColorShadingEnabled = isColorShadingEnabled(this); if (currentlyColorShadingEnabled !== this._colorShadingEnabled) { this._colorShadingEnabled = currentlyColorShadingEnabled; shouldRegenerateShaders = true; } if (shouldRegenerateShaders) { regenerateShaders(this, frameState); } else { updateColor(this, frameState, false); updateSilhouette(this, frameState, false); } } if (justLoaded) { // Called after modelMatrix update. var model = this; frameState.afterRender.push(function() { model._ready = true; model._readyPromise.resolve(model); }); return; } // We don't check show at the top of the function since we // want to be able to progressively load models when they are not shown, // and then have them visible immediately when show is set to true. if (show && !this._ignoreCommands) { // PERFORMANCE_IDEA: This is terrible var commandList = frameState.commandList; var passes = frameState.passes; var nodeCommands = this._nodeCommands; var length = nodeCommands.length; var i; var nc; var idl2D = frameState.mapProjection.ellipsoid.maximumRadius * CesiumMath.PI; var boundingVolume; if (passes.render || (passes.pick && this.allowPicking)) { for (i = 0; i < length; ++i) { nc = nodeCommands[i]; if (nc.show) { var command = translucent ? nc.translucentCommand : nc.command; command = silhouette ? nc.silhouetteModelCommand : command; commandList.push(command); boundingVolume = nc.command.boundingVolume; if (frameState.mode === SceneMode.SCENE2D && (boundingVolume.center.y + boundingVolume.radius > idl2D || boundingVolume.center.y - boundingVolume.radius < idl2D)) { var command2D = translucent ? nc.translucentCommand2D : nc.command2D; command2D = silhouette ? nc.silhouetteModelCommand2D : command2D; commandList.push(command2D); } } } if (silhouette && !passes.pick) { // Render second silhouette pass for (i = 0; i < length; ++i) { nc = nodeCommands[i]; if (nc.show) { commandList.push(nc.silhouetteColorCommand); boundingVolume = nc.command.boundingVolume; if (frameState.mode === SceneMode.SCENE2D && (boundingVolume.center.y + boundingVolume.radius > idl2D || boundingVolume.center.y - boundingVolume.radius < idl2D)) { commandList.push(nc.silhouetteColorCommand2D); } } } } } } }; function destroyIfNotCached(rendererResources, cachedRendererResources) { if (rendererResources.programs !== cachedRendererResources.programs) { destroy(rendererResources.programs); } if (rendererResources.silhouettePrograms !== cachedRendererResources.silhouettePrograms) { destroy(rendererResources.silhouettePrograms); } } // Run from update iff: // - everything is loaded // - clipping planes state change OR color state set // Run this from destructor after removing color state and clipping plane state function regenerateShaders(model, frameState) { // In regards to _cachedRendererResources: // Fair to assume that this is data that should just never get modified due to clipping planes or model color. // So if clipping planes or model color active: // - delink _rendererResources.*programs and create new dictionaries. // - do NOT destroy any programs - might be used by copies of the model or by might be needed in the future if clipping planes/model color is deactivated // If clipping planes and model color inactive: // - destroy _rendererResources.*programs // - relink _rendererResources.*programs to _cachedRendererResources // In both cases, need to mark commands as dirty, re-run derived commands (elsewhere) var rendererResources = model._rendererResources; var cachedRendererResources = model._cachedRendererResources; destroyIfNotCached(rendererResources, cachedRendererResources); var programId; if (isClippingEnabled(model) || isColorShadingEnabled(model) || model._shouldRegenerateShaders) { model._shouldRegenerateShaders = false; rendererResources.programs = {}; rendererResources.silhouettePrograms = {}; var visitedPrograms = {}; var techniques = model._sourceTechniques; var technique; for (var techniqueId in techniques) { if (techniques.hasOwnProperty(techniqueId)) { technique = techniques[techniqueId]; programId = technique.program; if (!visitedPrograms[programId]) { visitedPrograms[programId] = true; recreateProgram({ programId: programId, techniqueId: techniqueId }, model, frameState.context); } } } } else { rendererResources.programs = cachedRendererResources.programs; rendererResources.silhouettePrograms = cachedRendererResources.silhouettePrograms; } // Fix all the commands, marking them as dirty so everything that derives will re-derive var rendererPrograms = rendererResources.programs; var nodeCommands = model._nodeCommands; var commandCount = nodeCommands.length; for (var i = 0; i < commandCount; ++i) { var nodeCommand = nodeCommands[i]; programId = nodeCommand.programId; var renderProgram = rendererPrograms[programId]; nodeCommand.command.shaderProgram = renderProgram; if (defined(nodeCommand.command2D)) { nodeCommand.command2D.shaderProgram = renderProgram; } } // Force update silhouette commands/shaders updateColor(model, frameState, true); updateSilhouette(model, frameState, true); } /** * Returns true if this object was destroyed; otherwise, false. * <br /><br /> * If this object was destroyed, it should not be used; calling any function other than * <code>isDestroyed</code> will result in a {@link DeveloperError} exception. * * @returns {Boolean} <code>true</code> if this object was destroyed; otherwise, <code>false</code>. * * @see Model#destroy */ Model.prototype.isDestroyed = function() { return false; }; /** * Destroys the WebGL resources held by this object. Destroying an object allows for deterministic * release of WebGL resources, instead of relying on the garbage collector to destroy this object. * <br /><br /> * Once an object is destroyed, it should not be used; calling any function other than * <code>isDestroyed</code> will result in a {@link DeveloperError} exception. Therefore, * assign the return value (<code>undefined</code>) to the object as done in the example. * * @exception {DeveloperError} This object was destroyed, i.e., destroy() was called. * * * @example * model = model && model.destroy(); * * @see Model#isDestroyed */ Model.prototype.destroy = function() { // Vertex arrays are unique to this model, destroy here. if (defined(this._precreatedAttributes)) { destroy(this._rendererResources.vertexArrays); } if (defined(this._removeUpdateHeightCallback)) { this._removeUpdateHeightCallback(); this._removeUpdateHeightCallback = undefined; } if (defined(this._terrainProviderChangedCallback)) { this._terrainProviderChangedCallback(); this._terrainProviderChangedCallback = undefined; } // Shaders modified for clipping and for color don't get cached, so destroy these manually if (defined(this._cachedRendererResources)) { destroyIfNotCached(this._rendererResources, this._cachedRendererResources); } this._rendererResources = undefined; this._cachedRendererResources = this._cachedRendererResources && this._cachedRendererResources.release(); DracoLoader.destroyCachedDataForModel(this); var pickIds = this._pickIds; var length = pickIds.length; for (var i = 0; i < length; ++i) { pickIds[i].destroy(); } releaseCachedGltf(this); this._quantizedVertexShaders = undefined; // Only destroy the ClippingPlaneCollection if this is the owner - if this model is part of a Cesium3DTileset, // _clippingPlanes references a ClippingPlaneCollection that this model does not own. var clippingPlaneCollection = this._clippingPlanes; if (defined(clippingPlaneCollection) && !clippingPlaneCollection.isDestroyed() && clippingPlaneCollection.owner === this) { clippingPlaneCollection.destroy(); } this._clippingPlanes = undefined; this._specularEnvironmentMapAtlas = this._specularEnvironmentMapAtlas && this._specularEnvironmentMapAtlas.destroy(); return destroyObject(this); }; // exposed for testing Model._getClippingFunction = getClippingFunction; Model._modifyShaderForColor = modifyShaderForColor; return Model; });
import collections.abc import functools import os import pickle import socket import time import typing import uuid import warnings from abc import abstractmethod from dataclasses import dataclass from typing import Iterator import cloudpickle import mlflow import mlflow.entities import mlflow.exceptions import mlflow.store.tracking import mlflow.utils.mlflow_tags from mlflow.store.tracking import SEARCH_MAX_RESULTS_THRESHOLD import mlflowhelper.tracking.artifactmanager DICT_IDENTIFIER = "mlflow.tracking.collections.MlflowDict" @dataclass class MetaValue: value: typing.Any = None tags: typing.Union[list, dict, tuple] = None params: typing.Union[list, dict, tuple] = None metrics: typing.Union[list, dict, tuple] = None artifacts: typing.Union[list, dict, tuple] = None status: typing.Union[dict, tuple, str] = None update: bool = False def cached(_func=None, overwrite=False, *, cache, key): def decorator_cached(func): @functools.wraps(func) def wrapper_cached(*args, **kwargs): if key not in cache or overwrite: value = func(*args, **kwargs) cache[key] = value else: return cache[key] return value return wrapper_cached if _func is None: return decorator_cached else: return decorator_cached(_func) class MlflowDict(collections.abc.MutableMapping): """ Dict like class that persists elements to an Mlflow tracking server. WARNING: You need to explicitly set values again when you change them since the local cache is not automatically synchronized. """ # TODO: Fix race conditions for synchronous access: # We might be able to fix this by not deleting runs straight away. # Instead we can manually select the most recent run when retrieving values. # For clean-up we sweep through all runs every now and the and delete every run # except the most recent ones for each key. # # TODO: Don't interpret runs with no value as valid keys. # Or maybe it makes more sense to not interpret runs with `state!=FINISHED` as runs. class Pickler: """Abstract Pickler class which can be used for custom pickling.""" @abstractmethod def dump(self, value, path): pass @abstractmethod def load(self, path): pass class DefaultPickler(Pickler): """Pickler using `pickle` as default""" def dump(self, value, path): with open(path, "wb") as f: pickle.dump(value, f) def load(self, path): with open(path, "rb") as f: return pickle.load(f) class CloudPickler(Pickler): """Pickler using `pickle` as default""" def dump(self, value, path): with open(path, "wb") as f: cloudpickle.dump(value, f) def load(self, path): with open(path, "rb") as f: return cloudpickle.load(f) class Logger: """Class for custom logging.""" @abstractmethod def log(self, mlflow_client, artifact_manager, run, key, value) -> bool: """If you want to log a file, the artifact manager is used like this: >>> import matplotlib.pyplot as plt >>> with artifact_manager.managed_artifact("plot.png", dst_run_id=run.info.run_id) as a: >>> plt.plot([1,2,3], [1,2,3]) >>> plt.savefig(a.get_path()) """ pass def __init__( self, mlflow_client: typing.Union[mlflow.tracking.client.MlflowClient, str] = None, mlflow_experiment_name="dict_db", mlflow_tag_dict_name="default", mlflow_tag_user=None, mlflow_tag_defaults=None, mlflow_tag_name_separator=": ", mlflow_tag_prefix="_mlflowdict", mlflow_custom_logger=None, mlflow_pickler: typing.Union[Pickler, str] = 'cloudpickle', sync_mode=None, local_value_cache=True, lazy_value_cache=True, read_only=False, only_load_finished_runs=False): """ Dictionaries are identified by 1) `mlflow_experiment_name` and 2) the `mlflow_tag_dict_name` in MLflow. The other tags are optional. :param mlflow_client: MlflowClient or str representing the tracking uri of MLflow. :param mlflow_experiment_name: Name of the MLflow experiment :param mlflow_tag_dict_name: Dictionary name set as `mlflow_tag_prefix`._name tag :param mlflow_tag_user: User name set as mlflow user tag :param mlflow_tag_defaults: Other default tags :param mlflow_tag_name_separator: The separator used to name runs which represent dict entries. Example: `{mlflow_tag_dict_name}{mlflow_tag_name_separator}{key_name}` :param mlflow_tag_prefix: Prefix for tags used by MlflowDict. You probably don't need to change this ever. :param mlflow_custom_logger: By default values are pickled and saved and that's it. If you want to log additional details about the value it can be done with a custom logger specified via this parameter. This can be a function or a class of type `MlflowDict.Logger`. :param mlflow_pickler: By default MlflowDict uses `pickle` to serialize values. You can provide a custom pickler here. See `MlflowDict.Pickler` for the interface. If set to `None`, no value will be logged and the result upon retrieving an element from the dict will be `None`. :param sync_mode: Specifies the synchronization mode of keys and items. WARNING: Any sync mode will trigger rather expensive database queries slowing down item retrieval and key listings considerably. This particularly heavily influences iterators over keys and items. Available modes: * None: no active synchronization. * "keys": will keep keys synchronized. This means that we do not cache keys, but update them every time this dict is accessed. This may slow down the dict operations a lot depending on access frequency, dict size and network latency. * "full": will keep keys (see "keys" mode) and locally cached values in sync. Caching values will only take effect if local value caching is activated (`local_value_cache=True`). If a value is in the local cache but the synchronized key has a newer timestamp then the value is updated. :param local_value_cache: Whether to keep a local cache of values. :param lazy_value_cache: Whether to download and cache all values on initialization (`lazy_cache=False`) or not. """ self.lock_uuid = uuid.uuid4() # init client if mlflow_client is None: self.client = mlflow.tracking.MlflowClient() elif isinstance(mlflow_client, str): self.client = mlflow.tracking.MlflowClient(tracking_uri=mlflow_client) else: self.client = mlflow_client # create experiment if it does not exist exp = self.client.get_experiment_by_name(mlflow_experiment_name) if exp is None: self.client.create_experiment(mlflow_experiment_name) exp = self.client.get_experiment_by_name(mlflow_experiment_name) self.experiment = exp # tags self.mlflow_tag_dict_name = mlflow_tag_dict_name self.mlflow_tag_user = mlflow_tag_user self.mlflow_tag_defaults = mlflow_tag_defaults self.mlflow_tag_prefix = mlflow_tag_prefix self.mlflow_tag_name_separator = mlflow_tag_name_separator self.mlflow_custom_logger = mlflow_custom_logger if mlflow_pickler == "pickle": self.mlflow_pickler = MlflowDict.DefaultPickler() if mlflow_pickler == "cloudpickle": self.mlflow_pickler = MlflowDict.CloudPickler() else: self.mlflow_pickler = mlflow_pickler self.only_load_finished_runs = only_load_finished_runs # sync self.sync_mode = sync_mode # caching self.local_cache = local_value_cache self.lazy_cache = lazy_value_cache self.local_values = dict() self.local_all_keys = self.update_keys() if not lazy_value_cache: self._init_values() # read only self.read_only = read_only # check whether dict exists if len(self.local_all_keys) > 0: warnings.warn("Dict already exists") def _init_values(self): self.local_values = {key: (value, int(run.data.tags[f"{self.mlflow_tag_prefix}._timestamp"])) for key, value, run in self._get_items(return_runs=True)} def _log_value(self, key, value): timestamp = int(round(time.time() * 1000)) # compile tags tags = dict() # required tags tags[f"{self.mlflow_tag_prefix}._class"] = DICT_IDENTIFIER tags[f"{self.mlflow_tag_prefix}._name"] = self.mlflow_tag_dict_name tags[f"{self.mlflow_tag_prefix}._key"] = key tags[f"{self.mlflow_tag_prefix}._timestamp"] = str(timestamp) # set optional tags tags[f"{self.mlflow_tag_prefix}._item_source"] = f"{socket.gethostname()}___{os.getpid()}" tags[mlflow.utils.mlflow_tags.MLFLOW_RUN_NAME] = \ f"{self.mlflow_tag_dict_name}{self.mlflow_tag_name_separator}{key}" tags[mlflow.utils.mlflow_tags.MLFLOW_USER] = f"{self.mlflow_tag_user}" if self.mlflow_tag_defaults is not None: for tag, value in self.mlflow_tag_defaults: tags[tag] = value if self.mlflow_tag_defaults is not None: for tag, value in self.mlflow_tag_defaults: tags[tag] = value # delete existing value / run before setting it, if update is not requested if not isinstance(value, MetaValue) or not value.update: for run in self._get_runs_with_name(key): # catching possibility that another process has already deleted the run # after we retrieved the corresponding runs try: self.client.delete_run(run.info.run_id) except mlflow.exceptions.RestException as e: if "Current state is deleted." in e.message: warnings.warn("Run was already deleted: {run.info.run_id}") else: raise e # get run; the run exists if # * this happens if MetaValue.update=True # * OR when some other process created that run in the mean time run: mlflow.entities.Run = self.get_run(key) # TODO: race condition: what if someone deletes the run before we can finish with it? if run is None: # create run if the run is not there run = self.client.create_run(self.experiment.experiment_id, tags=tags) # noinspection PyBroadException try: # set meta data if applicable def set_run(func, values): if values is not None: if not isinstance(values, list): values = [values] for args in values: if isinstance(args, dict): func(run.info.run_id, **args) else: if not isinstance(args, tuple): args = (args, ) func(run.info.run_id, *args) if isinstance(value, MetaValue): if value.update: set_run(self.client.set_tag, list(tags.items())) set_run(self.client.set_tag, value.tags) set_run(self.client.log_param, value.params) set_run(self.client.log_metric, value.metrics) set_run(self.client.log_artifact, value.artifacts) set_run(self.client.set_terminated, value.status) else: # set finished by default self.client.set_terminated(run.info.run_id, "FINISHED") # custom logging value = value.value if isinstance(value, MetaValue) else value with mlflowhelper.tracking.artifactmanager.ArtifactManager(self.client) as afm: self._custom_logging(self.mlflow_custom_logger, afm, run, key, value) if self.mlflow_pickler is not None: with afm.managed_artifact("value.pickle", dst_run_id=run.info.run_id) as a: self.mlflow_pickler.dump(value, a.get_path()) return value, timestamp except Exception as e: # clean up run in case of error try: self.client.delete_run(run.info.run_id) except Exception as e2: warnings.warn(f"Clean-up failed: {e2}") raise e def _custom_logging(self, logger, artifact_manager, run, key, value): if logger is not None: if callable(logger): logger(self.client, artifact_manager, run, key, value) else: logger.log(self.client, artifact_manager, run, key, value) def _del_runs_with_name(self, name): for run in self._get_runs_with_name(name): self.client.delete_run(run.info.run_id) def _get_runs_with_name(self, name): select_only_finished_runs = "AND attributes.status = 'FINISHED'" if self.only_load_finished_runs else "" return self.client.search_runs( self.experiment.experiment_id, filter_string=f"tags.`{self.mlflow_tag_prefix}._class` = '{DICT_IDENTIFIER}' " f"AND tags.`{self.mlflow_tag_prefix}._name`='{self.mlflow_tag_dict_name}' " f"AND tags.`{self.mlflow_tag_prefix}._key`='{name}' " f"{select_only_finished_runs}", max_results=SEARCH_MAX_RESULTS_THRESHOLD) def _get_all_runs(self): select_only_finished_runs = "AND attributes.status = 'FINISHED'" if self.only_load_finished_runs else "" return self.client.search_runs( self.experiment.experiment_id, filter_string=f"tags.`{self.mlflow_tag_prefix}._class` = '{DICT_IDENTIFIER}' " f"AND tags.`{self.mlflow_tag_prefix}._name`='{self.mlflow_tag_dict_name}' " f"{select_only_finished_runs}", max_results=SEARCH_MAX_RESULTS_THRESHOLD) def _load_artifact(self, run_id): with mlflowhelper.tracking.artifactmanager.ArtifactManager(self.client) as afm: with afm.managed_artifact("value.pickle", src_run_id=run_id, skip_log=True) as a: value = self.mlflow_pickler.load(a.get_path()) return value def _get_items(self, return_runs=False): """Loads all items directly from MlFlow skipping any local cache.""" for r in self._get_all_runs(): key = r.data.tags[f"{self.mlflow_tag_prefix}._key"] value = self._load_artifact(r.info.run_id) if return_runs: yield key, value, r else: yield key, value def search(self, regexp=None, tags=None): """Searches for values. NOT IMPLEMENTED YET""" # TODO: implement search raise NotImplementedError("Not implemented yet") def apply_logging(self, logging): """Applies logging to elements. This allows to add additional metrics, parameters, tags, etc. to values even after they have been set.""" for key, value, run in self._get_items(return_runs=True): with mlflowhelper.tracking.artifactmanager.ArtifactManager(self.client) as afm: self._custom_logging(logging, afm, run, key, value) def get_run(self, k): runs = self._get_runs_with_name(k) if len(runs) == 0: return None elif len(runs) == 1: return runs[0] else: raise KeyError(f"Too many entries for key `{k}`: {len(runs)}") def update_keys(self): """Fetches keys from MlFlow. Call this when you suspect that the dict might have been updated from elsewhere.""" self.local_all_keys = set(v.data.tags[f"{self.mlflow_tag_prefix}._key"] for v in self._get_all_runs()) # clean up mising values if self.local_cache: for k in list(self.local_values.keys()): if k not in self.local_all_keys: del self.local_values[k] return self.local_all_keys def reset_cache(self): """ Empty/reset cache. """ self.local_values = dict() def fill_cache(self, reset_cache=False, drop_none=False, mode="silent"): """ Convenience method to update cache. Note that existing values will not be updated unless the whole cache is reset (`reset_cache`). """ if mode not in ["tqdm", "print", "silent"]: raise ValueError(f"Invalid mode: {mode}") if not self.local_cache: raise ValueError("Local cache is not enabled.") else: if reset_cache: self.reset_cache() sync_mode_backup = self.sync_mode self.sync_mode = None try: self.update_keys() if mode == "tqdm": import tqdm for k in tqdm.tqdm(list(self.keys())): v = self[k] if drop_none and v is None: warnings.warn(f"Dropping `None` entry: {k}") del self[k] elif mode == "print" or mode == "silent": for k in list(self.keys()): if mode == "print": print("Loading:", k) v = self[k] if drop_none and v is None: warnings.warn(f"Dropping `None` entry: {k}") del self[k] finally: self.sync_mode = sync_mode_backup def runs(self, include_values=False): """ :param include_values: :return: * include_values=True -> yield key, value, run * include_values=False -> yield key, run """ if include_values: yield from self._get_items(return_runs=True) else: yield from self._get_all_runs() def delete_all(self, verbose=False): if verbose: import tqdm it = tqdm.tqdm(list(self.keys())) else: it = list(self.keys()) for k in it: del self[k] # @contextmanager # def _acquire_run(self, key, create=False, timeout=3000, delay=200): # """Attempt to avoid inconsistent states caused by race conditions. Probably still doesn't solve all of them: # lock1 check # lock2 check # lock1 start > # lock2 start > # let this be slow for some reason # > lock1 set # lock1 read > # < lock1 send # lock1 acquired < # > lock2 set # this is the issue: MlFlow server does not recognize locks ;) # lock2 read > # < lock2 send # lock2 acquired < # # * lock2 should have failed # * if can happens if read and write are asynchronous on server # TODO: Better ideas without an external lock service? # YES! We can basically always only return the most recent entry for each key. # That way we never have concurrent access on each key and even have a kind of version control. # The old keys then need to be purged every now and then to keep the queries efficient ( # check indices in database to make sure that we are doing the most efficient thing). # """ # # start = time.time() # # lock_tag = f"{self.mlflow_tag_prefix}._lock" # lock_value = self.lock_uuid # # run: typing.Union[str, mlflow.entities.Run, None] = "undefined" # while run == "undefined": # # # check timeout # if time.time() - start > timeout / 1000: # raise RuntimeError( # f"Acquiring run with name '{key}' took too long (> {timeout}). " \ # f"Possible deadlock while acquiring run.") # # # get run and acquire lock # existing_runs = sorted(self._get_runs_with_name(key), key=lambda r: r.info.run_id) # if len(existing_runs) == 0: # if create: # # created_run = self.client.create_run( # self.experiment.experiment_id, # tags={lock_tag: lock_value}) # # updated_runs = sorted(self._get_runs_with_name(key), key=lambda r: r.info.run_id) # # if lock_tag in updated_runs[0].data.tags and updated_runs[0].data.tags[lock_tag] == lock_value: # run = updated_runs[0] # else: # self.client.delete_run(created_run.info.run_id) # else: # run = None # # elif len(existing_runs) > 0: # # if lock_tag not in existing_runs[0].data.tags: # # # try to lock run # # noinspection PyBroadException # try: # self.client.set_tag(existing_runs[0].info.run_id, lock_tag, lock_value) # except Exception: # # run may have been deleted in the meantime # pass # # # check whether locking worked # updated_runs = sorted(self._get_runs_with_name(key), key=lambda r: r.info.run_id) # # if len(updated_runs) > 0 \ # and lock_tag in updated_runs[0].data.tags \ # and updated_runs[0].data.tags[lock_tag] == lock_value: # run = existing_runs[0] # # else: # raise RuntimeError(f"More than one run with key: {key}") # # # check if lock is acquired # if run is not None: # run = self.client.get_run(run.info.run_id) # if run.data.tags[lock_tag] != lock_value: # run = "undefined" # # time.sleep(np.random.randint(delay)) # # yield run # # if run is not None: # self.client.delete_tag(run.info.run_id, "lock") def __setitem__(self, k, v) -> None: # TODO: race conditions (acquire lock on run) if self.read_only: raise RuntimeError("Dict is in 'read only' mode.") """Sets a value, optionally with additional tags.""" if len(self.local_all_keys) >= SEARCH_MAX_RESULTS_THRESHOLD: raise MemoryError( f"Exceeding size limit for retrieval ({SEARCH_MAX_RESULTS_THRESHOLD}). " "This may result in missing values. " "This is a known limitation and will have to be fixed " "if it becomes an issue in practice.") value, timestamp = self._log_value(k, v) self.local_all_keys.add(k) if self.local_cache: self.local_values[k] = (value, timestamp) def __delitem__(self, k) -> None: # TODO: race conditions (acquire lock on run) if self.read_only: raise RuntimeError("Dict is in 'read only' mode.") self._del_runs_with_name(k) self.local_all_keys.remove(k) if self.local_cache: if k in self.local_values: del self.local_values[k] def __getitem__(self, k): # check value cache first depending on settings if k in self and self.local_cache and k in self.local_values: local_value, local_timestamp = self.local_values[k] if self.sync_mode == "full": # get remote value and timestamp run: mlflow.entities.Run = self.get_run(k) remote_timestamp = int(run.data.tags.get(f"{self.mlflow_tag_prefix}._timestamp", "0")) # choose value to return based on timestamp if remote_timestamp > local_timestamp: remote_value = self._load_artifact(run.info.run_id) self.local_values[k] = (remote_value, remote_timestamp) return remote_value else: return local_value else: return local_value else: # TODO: maybe limit get run to key that we know exists? # TODO: We could also cache run ids together with keys for less requests. run: mlflow.entities.Run = self.get_run(k) if run is None: if hasattr(self.__class__, "__missing__"): # noinspection PyUnresolvedReferences return self.__class__.__missing__(self, k) else: raise KeyError(f"Key does not exist: {k}") else: value = self._load_artifact(run.info.run_id) timestamp = int(run.data.tags.get(f"{self.mlflow_tag_prefix}._timestamp", "0")) if self.local_cache: self.local_values[k] = value, timestamp return value def __len__(self) -> int: if self.sync_mode is not None: self.update_keys() return len(self.local_all_keys) def __iter__(self) -> Iterator: if self.sync_mode is not None: self.update_keys() return iter(self.local_all_keys) # TODO: Modify __contains__ to work correctly when __missing__ is present def __contains__(self, key): if self.sync_mode is not None: self.update_keys() return key in self.local_all_keys # Now, add the methods in dicts but not in MutableMapping def __repr__(self): return repr(self.local_all_keys) # def items(self): # return MlflowDict.ItemsView(self) # class ItemsView(typing.MappingView, typing.Set): # # __slots__ = () # # @classmethod # def _from_iterable(self, it): # return set(it) # # def __contains__(self, item): # key, value = item # try: # v = self._mapping[key] # except KeyError: # return False # else: # return v is value or v == value # # def __iter__(self): # for key in self._mapping: # yield (key, self._mapping[key])
from django.http import HttpResponse from django.views.decorators.csrf import csrf_exempt from rest_framework.renderers import JSONRenderer from rest_framework.parsers import JSONParser from home.models import Ebill from apis.serializers import EbillSerializer class JSONResponse(HttpResponse): """ An HttpResponse that renders its content into JSON. """ def __init__(self, data, **kwargs): content = JSONRenderer().render(data) kwargs['content_type'] = 'application/json' super(JSONResponse, self).__init__(content, **kwargs) @csrf_exempt def ebills_list(request): """ List all code snippets, or create a new snippet. """ if request.method == 'GET': ebills = Ebill.objects.all() serializer = EbillSerializer(ebills, many=True) return JSONResponse(serializer.data) @csrf_exempt def mobile_records(request, number): query = "this.number == {}".format(number) try: record = Ebill.objects.where(query) except Ebill.DoesNotExist: return HttpResponse(status=404) if request.method == 'GET': serializer = EbillSerializer(list(record), many=True) return JSONResponse(serializer.data) @csrf_exempt def books(request): if request.method == 'POST': data = { 'success': True } return JSONResponse(data) data = [ { "id": "978-0641723445", "cat": ["book", "hardcover"], "name": "The Lightning Thief", "author": "Rick Riordan", "series_t": "Percy Jackson and the Olympians", "genre_s": "fantasy", "inStock": True, "price": 12.50, "pages": 384 } , { "id": "978-1423103349", "cat": ["book", "paperback"], "name": "The Sea of Monsters", "author": "Rick Riordan", "series_t": "Percy Jackson and the Olympians", "genre_s": "fantasy", "inStock": True, "price": 6.49, "pages": 304 } , { "id": "978-1857995879", "cat": ["book", "paperback"], "name": "Sophie's World : The Greek Philosophers", "author": "Jostein Gaarder", "genre_s": "fantasy", "inStock": True, "price": 3.07, "pages": 64 } , { "id": "978-1933988177", "cat": ["book", "paperback"], "name": "Lucene in Action, Second Edition", "author": "Michael McCandless", "genre_s": "IT", "inStock": True, "price": 30.50, "pages": 475 } ] return JSONResponse(data) @csrf_exempt def order(request): data = [{ "ID": "1234", "Buyer": "Kasun", "Price": "13.40$" }, { "ID": "1235", "Buyer": "Thennakoon", "Price": "26.75$" }] return JSONResponse(data)
from mock import Mock, patch, call from tests.helpers.testbase import TestBase from cerami.response import SaveResponse from cerami.request import PutRequest from cerami.request.search_attribute import DictAttribute class TestPutRequest(TestBase): def setUp(self): self.mocked_client = Mock() self.request = PutRequest( tablename="test", client=self.mocked_client) def test_execute(self): """it calls put_item with the build it returns a SaveResponse """ self.request.build = Mock() expected = {"fake": True} self.mocked_client.put_item.return_value = {'Test': True} self.request.build.return_value = expected res = self.request.execute() self.mocked_client.put_item.assert_called_with(fake=True) assert isinstance(res, SaveResponse) def test_item(self): """it calls adds the Item attribute with the item_dict""" self.request.add_attribute = Mock() fake_data = {} self.request.item(fake_data) calls = [call(DictAttribute, 'Item', fake_data)] self.request.add_attribute.assert_has_calls(calls)
# Ref: http://andreinc.net/2010/10/05/converting-infix-to-rpn-shunting-yard-algorithm/ LEFT_ASSOC = 0 RIGHT_ASSOC = 1 operators = { '+': (0, LEFT_ASSOC), '-': (0, LEFT_ASSOC), '*' : (5, LEFT_ASSOC), '/' : (5, LEFT_ASSOC), '%' : (5, LEFT_ASSOC), '^' : (10, RIGHT_ASSOC) } def isOperator(c): return c in operators.keys() def isDigit(c): return '0' <= c <= '9' def isAssociative(token, assoc): return token in operators and operators[token][1] == assoc def cmpPrecedence(t1, t2): return operators[t1][0] - operators[t2][0] class LexError(Exception): pass class ParseError(Exception): pass def lex(exp): i = 0 tokens = [] while i < len(exp): if isOperator(exp[i]): tokens.append(exp[i]) i += 1 elif isDigit(exp[i]): j = i+1 while j < len(exp) and isDigit(exp[j]): j += 1 tokens.append(int(exp[i:j])) i = j elif exp[i] in ['(', ')']: tokens.append(exp[i]) i += 1 else: raise LexError("lex failed") return tokens # parse infix and return a rpn # Key Point: when to pop stack def parseInfix(exp): tokens = lex(exp) op_stack = [] out = [] for token in tokens: if isOperator(token): while op_stack and isOperator(op_stack[-1]): if ((isAssociative(token, LEFT_ASSOC) and cmpPrecedence(token, op_stack[-1]) <= 0) or (isAssociative(token, RIGHT_ASSOC) and cmpPrecedence(token, op_stack[-1]) < 0)): out.append(op_stack.pop()) else: break op_stack.append(token) elif token == '(': op_stack.append(token) elif token == ')': while op_stack and op_stack[-1] != '(': out.append(op_stack.pop()) if op_stack: op_stack.pop() else: raise ParseError("parenthesis mismatch") else: out.append(token) while op_stack: out.append(op_stack.pop()) return out # evaluate rpn def evalRPN(exp): pass def evalBinOp(op, v1, v2): if op == '-': return v1 - v2 elif op == '+': return v1 + v2 elif op == '*': return v1 * v2 elif op == '/': return v1 / v2 def evalOp(op, value_stack): v2 = value_stack.pop() v1 = value_stack.pop() value_stack.append(evalBinOp(op, v1, v2)) # evaluate infix without parsing it into rpn # Key Point: evaluate when pop stack def evalInfix(exp): tokens = lex(exp) op_stack = [] value_stack = [] for token in tokens: if isOperator(token): while op_stack and isOperator(op_stack[-1]): if ((isAssociative(token, LEFT_ASSOC) and cmpPrecedence(token, op_stack[-1]) <= 0) or (isAssociative(token, RIGHT_ASSOC) and cmpPrecedence(token, op_stack[-1])) < 0): op = op_stack.pop() evalOp(op,value_stack) else: break op_stack.append(token) elif token == '(': op_stack.append(token) elif token == ')': while op_stack and op_stack[-1] != '(': op = op_stack.pop() evalOp(op, value_stack) if op_stack: op_stack.pop() else: raise ParseError("parenthesis mismatch") else: value_stack.append(token) while op_stack: op = op_stack.pop() evalOp(op, value_stack) return value_stack[0] print parseInfix('1*(21+3)-2+4/2') print evalInfix('1*(21+3)-2+4/2')
// // UIScrollView+JKPages.h // JKCategories (https://github.com/shaojiankui/JKCategories) // // Created by Jakey on 14/12/30. // Copyright (c) 2014年 www.skyfox.org. All rights reserved. // #import <UIKit/UIKit.h> @interface UIScrollView (JKPages) - (NSInteger)jk_pages; - (NSInteger)jk_currentPage; - (CGFloat)jk_scrollPercent; - (CGFloat)jk_pagesY; - (CGFloat)jk_pagesX; - (CGFloat)jk_currentPageY; - (CGFloat)jk_currentPageX; - (void)jk_setPageY:(CGFloat)page; - (void)jk_setPageX:(CGFloat)page; - (void)jk_setPageY:(CGFloat)page animated:(BOOL)animated; - (void)jk_setPageX:(CGFloat)page animated:(BOOL)animated; @end
from PIL import Image, ImageGrab import mss import mss.tools import time import cv2 as cv import pyautogui import matplotlib.pyplot as plt import numpy as np import os import PIL import tensorflow as tf from tensorflow import keras from tensorflow.keras import layers from tensorflow.keras.models import Sequential import pathlib from setting import android_x0 from setting import android_y0 from setting import android_x1 from setting import android_y1 model = tf.keras.models.load_model('models/my_model') batch_size = 32 img_width = android_x1 - android_x0 img_height = android_y1 - android_y0 def get_android_img(): starttime = time.time() with mss.mss() as sct: region = { "top":android_y0, "left":android_x0, "width":android_x1 - android_x0, "height":android_y1 - android_y0, } img = sct.grab(region) path_temp = "./hotpoor_autoclick_cache/record_temp.png" mss.tools.to_png(img.rgb,img.size,output=path_temp) endtime = time.time() return path_temp def get_check_result(img_now): path_temp = "./hotpoor_autoclick_cache/record_temp.png" sunflower_path = pathlib.Path(path_temp) img = keras.preprocessing.image.load_img( sunflower_path, target_size=(img_height, img_width) ) img_array = keras.preprocessing.image.img_to_array(img) img_array = tf.expand_dims(img_array, 0) # Create a batch predictions = model.predict(img_array) score = tf.nn.softmax(predictions[0]) class_names=['black', 'close', 'desktop', 'home', 'list', 'news', 'search', 'shop', 'video'] k = "None" if 100 * np.max(score)>=70: k = class_names[np.argmax(score)] print("当前页面为:",class_names[np.argmax(score)],100 * np.max(score)) else: k = class_names[np.argmax(score)] print("80分以下当前页面为:",class_names[np.argmax(score)],100 * np.max(score)) result = k actions = ["news","video","shop","list"] if result not in actions: result = "no action" return result is_debug = True is_debug = False is_doing = False is_left = True action_now = "None" # rem open xhs if not is_debug: os.system("adb shell monkey -p com.xingin.xhs -c android.intent.category.LAUNCHER 1") os.system("sleep 4") os.system("adb shell input tap 1000 150") os.system("sleep 2") os.system("adb shell input text PUCO") os.system("sleep 2") os.system("adb shell input tap 1000 150") os.system("sleep 2") os.system("adb shell input tap 380 360") os.system("sleep 2") is_browser_count_max = 5 is_browser_count = 0 while True: base_img = cv.imread(get_android_img(), 0) action_now = get_check_result(base_img) print(action_now) cv.imshow("img", base_img) # if is_debug: # base_img = cv.imread(get_android_img(),0) # action_now = get_check_result(base_img) # print(action_now) # cv.imshow("img",base_img) # key = cv.waitKey(1) # if key == ord("q"): # break # else: # if not is_doing: # base_img = cv.imread(get_android_img(),0) # action_now = get_check_result(base_img) # if action_now in ["news","video","shop","list"]: # is_doing = True # cv.imshow("img",base_img) # key = cv.waitKey(1) # if key == ord("q"): # break # else: # if action_now in ["list"]: # if is_left: # os.system("adb shell input swipe 340 800 340 500 1000") # os.system("adb shell input tap 340 500") # is_left = False # else: # os.system("adb shell input tap 800 500") # is_left = True # os.system("sleep 2") # elif action_now in ["shop"]: # os.system("adb shell input tap 55 150") # os.system("sleep 1") # elif action_now in ["news"]: # os.system("adb shell input tap 1000 155") # os.system("sleep 1") # os.system("adb shell input tap 380 1876") # os.system("sleep 2") # os.system("adb shell monkey -p com.android.browser -c android.intent.category.LAUNCHER 1") # if is_browser_count == 0: # is_browser_count += 1 # os.system("adb shell input tap 970 146") # os.system("sleep 4") # elif is_browser_count > is_browser_count_max: # is_browser_count = 0 # os.system("adb shell input tap 970 146") # os.system("sleep 4") # else: # is_browser_count += 1 # os.system("sleep 2") # # os.system("adb shell input swipe 330 780 330 780 1000") # os.system("adb shell input tap 330 780") # os.system("sleep 2") # os.system("adb shell input tap 398 1520") # os.system("sleep 2") # os.system("adb shell input tap 680 400") # os.system("sleep 1") # os.system("adb shell input tap 300 940") # os.system("sleep 2") # os.system("adb shell monkey -p com.xingin.xhs -c android.intent.category.LAUNCHER 1") # os.system("adb shell input tap 55 150") # elif action_now in ["video"]: # os.system("adb shell input tap 1000 155") # os.system("sleep 1") # os.system("adb shell input tap 523 1876") # os.system("sleep 2") # os.system("adb shell monkey -p com.android.browser -c android.intent.category.LAUNCHER 1") # if is_browser_count == 0: # is_browser_count += 1 # os.system("adb shell input tap 970 146") # os.system("sleep 4") # elif is_browser_count > is_browser_count_max: # is_browser_count = 0 # os.system("adb shell input tap 970 146") # os.system("sleep 4") # else: # is_browser_count += 1 # os.system("sleep 2") # # os.system("adb shell input swipe 330 780 330 780 1000") # os.system("adb shell input tap 750 780") # os.system("sleep 2") # os.system("adb shell input tap 398 1520") # os.system("sleep 2") # os.system("adb shell input tap 680 400") # os.system("sleep 1") # os.system("adb shell input tap 730 940") # os.system("sleep 2") # os.system("adb shell monkey -p com.xingin.xhs -c android.intent.category.LAUNCHER 1") # os.system("adb shell input tap 55 150") # is_doing = False cv.destroyAllWindows()
# -*- coding: utf-8 -*- """ requests.models ~~~~~~~~~~~~~~~ This module contains the primary objects that power Requests. """ import datetime import sys # Import encoding now, to avoid implicit import later. # Implicit import within threads may cause LookupError when standard library is in a ZIP, # such as in Embedded Python. See https://github.com/psf/requests/issues/3578. import encodings.idna from pip._vendor.urllib3.fields import RequestField from pip._vendor.urllib3.filepost import encode_multipart_formdata from pip._vendor.urllib3.util import parse_url from pip._vendor.urllib3.exceptions import ( DecodeError, ReadTimeoutError, ProtocolError, LocationParseError, ) from io import UnsupportedOperation from .hooks import default_hooks from .structures import CaseInsensitiveDict from .auth import HTTPBasicAuth from .cookies import cookiejar_from_dict, get_cookie_header, _copy_cookie_jar from .exceptions import ( HTTPError, MissingSchema, InvalidURL, ChunkedEncodingError, ContentDecodingError, ConnectionError, StreamConsumedError, ) from ._internal_utils import to_native_string, unicode_is_ascii from .utils import ( guess_filename, get_auth_from_url, requote_uri, stream_decode_response_unicode, to_key_val_list, parse_header_links, iter_slices, guess_json_utf, super_len, check_header_validity, ) from .compat import ( Callable, Mapping, cookielib, urlunparse, urlsplit, urlencode, str, bytes, is_py2, chardet, builtin_str, basestring, ) from .compat import json as complexjson from .status_codes import codes #: The set of HTTP status codes that indicate an automatically #: processable redirect. REDIRECT_STATI = ( codes.moved, # 301 codes.found, # 302 codes.other, # 303 codes.temporary_redirect, # 307 codes.permanent_redirect, # 308 ) DEFAULT_REDIRECT_LIMIT = 30 CONTENT_CHUNK_SIZE = 10 * 1024 ITER_CHUNK_SIZE = 512 class RequestEncodingMixin(object): @property def path_url(self): """Build the path URL to use.""" url = [] p = urlsplit(self.url) path = p.path if not path: path = "/" url.append(path) query = p.query if query: url.append("?") url.append(query) return "".join(url) @staticmethod def _encode_params(data): """Encode parameters in a piece of data. Will successfully encode parameters when passed as a dict or a list of 2-tuples. Order is retained if data is a list of 2-tuples but arbitrary if parameters are supplied as a dict. """ if isinstance(data, (str, bytes)): return data elif hasattr(data, "read"): return data elif hasattr(data, "__iter__"): result = [] for k, vs in to_key_val_list(data): if isinstance(vs, basestring) or not hasattr(vs, "__iter__"): vs = [vs] for v in vs: if v is not None: result.append( ( k.encode("utf-8") if isinstance(k, str) else k, v.encode("utf-8") if isinstance(v, str) else v, ) ) return urlencode(result, doseq=True) else: return data @staticmethod def _encode_files(files, data): """Build the body for a multipart/form-data request. Will successfully encode files when passed as a dict or a list of tuples. Order is retained if data is a list of tuples but arbitrary if parameters are supplied as a dict. The tuples may be 2-tuples (filename, fileobj), 3-tuples (filename, fileobj, contentype) or 4-tuples (filename, fileobj, contentype, custom_headers). """ if not files: raise ValueError("Files must be provided.") elif isinstance(data, basestring): raise ValueError("Data must not be a string.") new_fields = [] fields = to_key_val_list(data or {}) files = to_key_val_list(files or {}) for field, val in fields: if isinstance(val, basestring) or not hasattr(val, "__iter__"): val = [val] for v in val: if v is not None: # Don't call str() on bytestrings: in Py3 it all goes wrong. if not isinstance(v, bytes): v = str(v) new_fields.append( ( field.decode("utf-8") if isinstance(field, bytes) else field, v.encode("utf-8") if isinstance(v, str) else v, ) ) for (k, v) in files: # support for explicit filename ft = None fh = None if isinstance(v, (tuple, list)): if len(v) == 2: fn, fp = v elif len(v) == 3: fn, fp, ft = v else: fn, fp, ft, fh = v else: fn = guess_filename(v) or k fp = v if isinstance(fp, (str, bytes, bytearray)): fdata = fp elif hasattr(fp, "read"): fdata = fp.read() elif fp is None: continue else: fdata = fp rf = RequestField(name=k, data=fdata, filename=fn, headers=fh) rf.make_multipart(content_type=ft) new_fields.append(rf) body, content_type = encode_multipart_formdata(new_fields) return body, content_type class RequestHooksMixin(object): def register_hook(self, event, hook): """Properly register a hook.""" if event not in self.hooks: raise ValueError( 'Unsupported event specified, with event name "%s"' % (event) ) if isinstance(hook, Callable): self.hooks[event].append(hook) elif hasattr(hook, "__iter__"): self.hooks[event].extend(h for h in hook if isinstance(h, Callable)) def deregister_hook(self, event, hook): """Deregister a previously registered hook. Returns True if the hook existed, False if not. """ try: self.hooks[event].remove(hook) return True except ValueError: return False class Request(RequestHooksMixin): """A user-created :class:`Request <Request>` object. Used to prepare a :class:`PreparedRequest <PreparedRequest>`, which is sent to the server. :param method: HTTP method to use. :param url: URL to send. :param headers: dictionary of headers to send. :param files: dictionary of {filename: fileobject} files to multipart upload. :param data: the body to attach to the request. If a dictionary or list of tuples ``[(key, value)]`` is provided, form-encoding will take place. :param json: json for the body to attach to the request (if files or data is not specified). :param params: URL parameters to append to the URL. If a dictionary or list of tuples ``[(key, value)]`` is provided, form-encoding will take place. :param auth: Auth handler or (user, pass) tuple. :param cookies: dictionary or CookieJar of cookies to attach to this request. :param hooks: dictionary of callback hooks, for internal usage. Usage:: >>> import requests >>> req = requests.Request('GET', 'https://httpbin.org/get') >>> req.prepare() <PreparedRequest [GET]> """ def __init__( self, method=None, url=None, headers=None, files=None, data=None, params=None, auth=None, cookies=None, hooks=None, json=None, ): # Default empty dicts for dict params. data = [] if data is None else data files = [] if files is None else files headers = {} if headers is None else headers params = {} if params is None else params hooks = {} if hooks is None else hooks self.hooks = default_hooks() for (k, v) in list(hooks.items()): self.register_hook(event=k, hook=v) self.method = method self.url = url self.headers = headers self.files = files self.data = data self.json = json self.params = params self.auth = auth self.cookies = cookies def __repr__(self): return "<Request [%s]>" % (self.method) def prepare(self): """Constructs a :class:`PreparedRequest <PreparedRequest>` for transmission and returns it.""" p = PreparedRequest() p.prepare( method=self.method, url=self.url, headers=self.headers, files=self.files, data=self.data, json=self.json, params=self.params, auth=self.auth, cookies=self.cookies, hooks=self.hooks, ) return p class PreparedRequest(RequestEncodingMixin, RequestHooksMixin): """The fully mutable :class:`PreparedRequest <PreparedRequest>` object, containing the exact bytes that will be sent to the server. Generated from either a :class:`Request <Request>` object or manually. Usage:: >>> import requests >>> req = requests.Request('GET', 'https://httpbin.org/get') >>> r = req.prepare() >>> r <PreparedRequest [GET]> >>> s = requests.Session() >>> s.send(r) <Response [200]> """ def __init__(self): #: HTTP verb to send to the server. self.method = None #: HTTP URL to send the request to. self.url = None #: dictionary of HTTP headers. self.headers = None # The `CookieJar` used to create the Cookie header will be stored here # after prepare_cookies is called self._cookies = None #: request body to send to the server. self.body = None #: dictionary of callback hooks, for internal usage. self.hooks = default_hooks() #: integer denoting starting position of a readable file-like body. self._body_position = None def prepare( self, method=None, url=None, headers=None, files=None, data=None, params=None, auth=None, cookies=None, hooks=None, json=None, ): """Prepares the entire request with the given parameters.""" self.prepare_method(method) self.prepare_url(url, params) self.prepare_headers(headers) self.prepare_cookies(cookies) self.prepare_body(data, files, json) self.prepare_auth(auth, url) # Note that prepare_auth must be last to enable authentication schemes # such as OAuth to work on a fully prepared request. # This MUST go after prepare_auth. Authenticators could add a hook self.prepare_hooks(hooks) def __repr__(self): return "<PreparedRequest [%s]>" % (self.method) def copy(self): p = PreparedRequest() p.method = self.method p.url = self.url p.headers = self.headers.copy() if self.headers is not None else None p._cookies = _copy_cookie_jar(self._cookies) p.body = self.body p.hooks = self.hooks p._body_position = self._body_position return p def prepare_method(self, method): """Prepares the given HTTP method.""" self.method = method if self.method is not None: self.method = to_native_string(self.method.upper()) @staticmethod def _get_idna_encoded_host(host): from pip._vendor import idna try: host = idna.encode(host, uts46=True).decode("utf-8") except idna.IDNAError: raise UnicodeError return host def prepare_url(self, url, params): """Prepares the given HTTP URL.""" #: Accept objects that have string representations. #: We're unable to blindly call unicode/str functions #: as this will include the bytestring indicator (b'') #: on python 3.x. #: https://github.com/psf/requests/pull/2238 if isinstance(url, bytes): url = url.decode("utf8") else: url = unicode(url) if is_py2 else str(url) # Remove leading whitespaces from url url = url.lstrip() # Don't do any URL preparation for non-HTTP schemes like `mailto`, # `data` etc to work around exceptions from `url_parse`, which # handles RFC 3986 only. if ":" in url and not url.lower().startswith("http"): self.url = url return # Support for unicode domain names and paths. try: scheme, auth, host, port, path, query, fragment = parse_url(url) except LocationParseError as e: raise InvalidURL(*e.args) if not scheme: error = ( "Invalid URL {0!r}: No schema supplied. Perhaps you meant http://{0}?" ) error = error.format(to_native_string(url, "utf8")) raise MissingSchema(error) if not host: raise InvalidURL("Invalid URL %r: No host supplied" % url) # In general, we want to try IDNA encoding the hostname if the string contains # non-ASCII characters. This allows users to automatically get the correct IDNA # behaviour. For strings containing only ASCII characters, we need to also verify # it doesn't start with a wildcard (*), before allowing the unencoded hostname. if not unicode_is_ascii(host): try: host = self._get_idna_encoded_host(host) except UnicodeError: raise InvalidURL("URL has an invalid label.") elif host.startswith(u"*"): raise InvalidURL("URL has an invalid label.") # Carefully reconstruct the network location netloc = auth or "" if netloc: netloc += "@" netloc += host if port: netloc += ":" + str(port) # Bare domains aren't valid URLs. if not path: path = "/" if is_py2: if isinstance(scheme, str): scheme = scheme.encode("utf-8") if isinstance(netloc, str): netloc = netloc.encode("utf-8") if isinstance(path, str): path = path.encode("utf-8") if isinstance(query, str): query = query.encode("utf-8") if isinstance(fragment, str): fragment = fragment.encode("utf-8") if isinstance(params, (str, bytes)): params = to_native_string(params) enc_params = self._encode_params(params) if enc_params: if query: query = "%s&%s" % (query, enc_params) else: query = enc_params url = requote_uri(urlunparse([scheme, netloc, path, None, query, fragment])) self.url = url def prepare_headers(self, headers): """Prepares the given HTTP headers.""" self.headers = CaseInsensitiveDict() if headers: for header in headers.items(): # Raise exception on invalid header value. check_header_validity(header) name, value = header self.headers[to_native_string(name)] = value def prepare_body(self, data, files, json=None): """Prepares the given HTTP body data.""" # Check if file, fo, generator, iterator. # If not, run through normal process. # Nottin' on you. body = None content_type = None if not data and json is not None: # urllib3 requires a bytes-like body. Python 2's json.dumps # provides this natively, but Python 3 gives a Unicode string. content_type = "application/json" body = complexjson.dumps(json) if not isinstance(body, bytes): body = body.encode("utf-8") is_stream = all( [ hasattr(data, "__iter__"), not isinstance(data, (basestring, list, tuple, Mapping)), ] ) try: length = super_len(data) except (TypeError, AttributeError, UnsupportedOperation): length = None if is_stream: body = data if getattr(body, "tell", None) is not None: # Record the current file position before reading. # This will allow us to rewind a file in the event # of a redirect. try: self._body_position = body.tell() except (IOError, OSError): # This differentiates from None, allowing us to catch # a failed `tell()` later when trying to rewind the body self._body_position = object() if files: raise NotImplementedError( "Streamed bodies and files are mutually exclusive." ) if length: self.headers["Content-Length"] = builtin_str(length) else: self.headers["Transfer-Encoding"] = "chunked" else: # Multi-part file uploads. if files: (body, content_type) = self._encode_files(files, data) else: if data: body = self._encode_params(data) if isinstance(data, basestring) or hasattr(data, "read"): content_type = None else: content_type = "application/x-www-form-urlencoded" self.prepare_content_length(body) # Add content-type if it wasn't explicitly provided. if content_type and ("content-type" not in self.headers): self.headers["Content-Type"] = content_type self.body = body def prepare_content_length(self, body): """Prepare Content-Length header based on request method and body""" if body is not None: length = super_len(body) if length: # If length exists, set it. Otherwise, we fallback # to Transfer-Encoding: chunked. self.headers["Content-Length"] = builtin_str(length) elif ( self.method not in ("GET", "HEAD") and self.headers.get("Content-Length") is None ): # Set Content-Length to 0 for methods that can have a body # but don't provide one. (i.e. not GET or HEAD) self.headers["Content-Length"] = "0" def prepare_auth(self, auth, url=""): """Prepares the given HTTP auth data.""" # If no Auth is explicitly provided, extract it from the URL first. if auth is None: url_auth = get_auth_from_url(self.url) auth = url_auth if any(url_auth) else None if auth: if isinstance(auth, tuple) and len(auth) == 2: # special-case basic HTTP auth auth = HTTPBasicAuth(*auth) # Allow auth to make its changes. r = auth(self) # Update self to reflect the auth changes. self.__dict__.update(r.__dict__) # Recompute Content-Length self.prepare_content_length(self.body) def prepare_cookies(self, cookies): """Prepares the given HTTP cookie data. This function eventually generates a ``Cookie`` header from the given cookies using cookielib. Due to cookielib's design, the header will not be regenerated if it already exists, meaning this function can only be called once for the life of the :class:`PreparedRequest <PreparedRequest>` object. Any subsequent calls to ``prepare_cookies`` will have no actual effect, unless the "Cookie" header is removed beforehand. """ if isinstance(cookies, cookielib.CookieJar): self._cookies = cookies else: self._cookies = cookiejar_from_dict(cookies) cookie_header = get_cookie_header(self._cookies, self) if cookie_header is not None: self.headers["Cookie"] = cookie_header def prepare_hooks(self, hooks): """Prepares the given hooks.""" # hooks can be passed as None to the prepare method and to this # method. To prevent iterating over None, simply use an empty list # if hooks is False-y hooks = hooks or [] for event in hooks: self.register_hook(event, hooks[event]) class Response(object): """The :class:`Response <Response>` object, which contains a server's response to an HTTP request. """ __attrs__ = [ "_content", "status_code", "headers", "url", "history", "encoding", "reason", "cookies", "elapsed", "request", ] def __init__(self): self._content = False self._content_consumed = False self._next = None #: Integer Code of responded HTTP Status, e.g. 404 or 200. self.status_code = None #: Case-insensitive Dictionary of Response Headers. #: For example, ``headers['content-encoding']`` will return the #: value of a ``'Content-Encoding'`` response header. self.headers = CaseInsensitiveDict() #: File-like object representation of response (for advanced usage). #: Use of ``raw`` requires that ``stream=True`` be set on the request. #: This requirement does not apply for use internally to Requests. self.raw = None #: Final URL location of Response. self.url = None #: Encoding to decode with when accessing r.text. self.encoding = None #: A list of :class:`Response <Response>` objects from #: the history of the Request. Any redirect responses will end #: up here. The list is sorted from the oldest to the most recent request. self.history = [] #: Textual reason of responded HTTP Status, e.g. "Not Found" or "OK". self.reason = None #: A CookieJar of Cookies the server sent back. self.cookies = cookiejar_from_dict({}) #: The amount of time elapsed between sending the request #: and the arrival of the response (as a timedelta). #: This property specifically measures the time taken between sending #: the first byte of the request and finishing parsing the headers. It #: is therefore unaffected by consuming the response content or the #: value of the ``stream`` keyword argument. self.elapsed = datetime.timedelta(0) #: The :class:`PreparedRequest <PreparedRequest>` object to which this #: is a response. self.request = None def __enter__(self): return self def __exit__(self, *args): self.close() def __getstate__(self): # Consume everything; accessing the content attribute makes # sure the content has been fully read. if not self._content_consumed: self.content return {attr: getattr(self, attr, None) for attr in self.__attrs__} def __setstate__(self, state): for name, value in state.items(): setattr(self, name, value) # pickled objects do not have .raw setattr(self, "_content_consumed", True) setattr(self, "raw", None) def __repr__(self): return "<Response [%s]>" % (self.status_code) def __bool__(self): """Returns True if :attr:`status_code` is less than 400. This attribute checks if the status code of the response is between 400 and 600 to see if there was a client error or a server error. If the status code, is between 200 and 400, this will return True. This is **not** a check to see if the response code is ``200 OK``. """ return self.ok def __nonzero__(self): """Returns True if :attr:`status_code` is less than 400. This attribute checks if the status code of the response is between 400 and 600 to see if there was a client error or a server error. If the status code, is between 200 and 400, this will return True. This is **not** a check to see if the response code is ``200 OK``. """ return self.ok def __iter__(self): """Allows you to use a response as an iterator.""" return self.iter_content(128) @property def ok(self): """Returns True if :attr:`status_code` is less than 400, False if not. This attribute checks if the status code of the response is between 400 and 600 to see if there was a client error or a server error. If the status code is between 200 and 400, this will return True. This is **not** a check to see if the response code is ``200 OK``. """ try: self.raise_for_status() except HTTPError: return False return True @property def is_redirect(self): """True if this Response is a well-formed HTTP redirect that could have been processed automatically (by :meth:`Session.resolve_redirects`). """ return "location" in self.headers and self.status_code in REDIRECT_STATI @property def is_permanent_redirect(self): """True if this Response one of the permanent versions of redirect.""" return "location" in self.headers and self.status_code in ( codes.moved_permanently, codes.permanent_redirect, ) @property def next(self): """Returns a PreparedRequest for the next request in a redirect chain, if there is one.""" return self._next @property def apparent_encoding(self): """The apparent encoding, provided by the chardet library.""" return chardet.detect(self.content)["encoding"] def iter_content(self, chunk_size=1, decode_unicode=False): """Iterates over the response data. When stream=True is set on the request, this avoids reading the content at once into memory for large responses. The chunk size is the number of bytes it should read into memory. This is not necessarily the length of each item returned as decoding can take place. chunk_size must be of type int or None. A value of None will function differently depending on the value of `stream`. stream=True will read data as it arrives in whatever size the chunks are received. If stream=False, data is returned as a single chunk. If decode_unicode is True, content will be decoded using the best available encoding based on the response. """ def generate(): # Special case for urllib3. if hasattr(self.raw, "stream"): try: for chunk in self.raw.stream(chunk_size, decode_content=True): yield chunk except ProtocolError as e: raise ChunkedEncodingError(e) except DecodeError as e: raise ContentDecodingError(e) except ReadTimeoutError as e: raise ConnectionError(e) else: # Standard file-like object. while True: chunk = self.raw.read(chunk_size) if not chunk: break yield chunk self._content_consumed = True if self._content_consumed and isinstance(self._content, bool): raise StreamConsumedError() elif chunk_size is not None and not isinstance(chunk_size, int): raise TypeError( "chunk_size must be an int, it is instead a %s." % type(chunk_size) ) # simulate reading small chunks of the content reused_chunks = iter_slices(self._content, chunk_size) stream_chunks = generate() chunks = reused_chunks if self._content_consumed else stream_chunks if decode_unicode: chunks = stream_decode_response_unicode(chunks, self) return chunks def iter_lines( self, chunk_size=ITER_CHUNK_SIZE, decode_unicode=False, delimiter=None ): """Iterates over the response data, one line at a time. When stream=True is set on the request, this avoids reading the content at once into memory for large responses. .. note:: This method is not reentrant safe. """ pending = None for chunk in self.iter_content( chunk_size=chunk_size, decode_unicode=decode_unicode ): if pending is not None: chunk = pending + chunk if delimiter: lines = chunk.split(delimiter) else: lines = chunk.splitlines() if lines and lines[-1] and chunk and lines[-1][-1] == chunk[-1]: pending = lines.pop() else: pending = None for line in lines: yield line if pending is not None: yield pending @property def content(self): """Content of the response, in bytes.""" if self._content is False: # Read the contents. if self._content_consumed: raise RuntimeError("The content for this response was already consumed") if self.status_code == 0 or self.raw is None: self._content = None else: self._content = b"".join(self.iter_content(CONTENT_CHUNK_SIZE)) or b"" self._content_consumed = True # don't need to release the connection; that's been handled by urllib3 # since we exhausted the data. return self._content @property def text(self): """Content of the response, in unicode. If Response.encoding is None, encoding will be guessed using ``chardet``. The encoding of the response content is determined based solely on HTTP headers, following RFC 2616 to the letter. If you can take advantage of non-HTTP knowledge to make a better guess at the encoding, you should set ``r.encoding`` appropriately before accessing this property. """ # Try charset from content-type content = None encoding = self.encoding if not self.content: return str("") # Fallback to auto-detected encoding. if self.encoding is None: encoding = self.apparent_encoding # Decode unicode from given encoding. try: content = str(self.content, encoding, errors="replace") except (LookupError, TypeError): # A LookupError is raised if the encoding was not found which could # indicate a misspelling or similar mistake. # # A TypeError can be raised if encoding is None # # So we try blindly encoding. content = str(self.content, errors="replace") return content def json(self, **kwargs): r"""Returns the json-encoded content of a response, if any. :param \*\*kwargs: Optional arguments that ``json.loads`` takes. :raises ValueError: If the response body does not contain valid json. """ if not self.encoding and self.content and len(self.content) > 3: # No encoding set. JSON RFC 4627 section 3 states we should expect # UTF-8, -16 or -32. Detect which one to use; If the detection or # decoding fails, fall back to `self.text` (using chardet to make # a best guess). encoding = guess_json_utf(self.content) if encoding is not None: try: return complexjson.loads(self.content.decode(encoding), **kwargs) except UnicodeDecodeError: # Wrong UTF codec detected; usually because it's not UTF-8 # but some other 8-bit codec. This is an RFC violation, # and the server didn't bother to tell us what codec *was* # used. pass return complexjson.loads(self.text, **kwargs) @property def links(self): """Returns the parsed header links of the response, if any.""" header = self.headers.get("link") # l = MultiDict() l = {} if header: links = parse_header_links(header) for link in links: key = link.get("rel") or link.get("url") l[key] = link return l def raise_for_status(self): """Raises stored :class:`HTTPError`, if one occurred.""" http_error_msg = "" if isinstance(self.reason, bytes): # We attempt to decode utf-8 first because some servers # choose to localize their reason strings. If the string # isn't utf-8, we fall back to iso-8859-1 for all other # encodings. (See PR #3538) try: reason = self.reason.decode("utf-8") except UnicodeDecodeError: reason = self.reason.decode("iso-8859-1") else: reason = self.reason if 400 <= self.status_code < 500: http_error_msg = u"%s Client Error: %s for url: %s" % ( self.status_code, reason, self.url, ) elif 500 <= self.status_code < 600: http_error_msg = u"%s Server Error: %s for url: %s" % ( self.status_code, reason, self.url, ) if http_error_msg: raise HTTPError(http_error_msg, response=self) def close(self): """Releases the connection back to the pool. Once this method has been called the underlying ``raw`` object must not be accessed again. *Note: Should not normally need to be called explicitly.* """ if not self._content_consumed: self.raw.close() release_conn = getattr(self.raw, "release_conn", None) if release_conn is not None: release_conn()
/** * Copyright IBM Corp. 2019, 2020 * * This source code is licensed under the Apache-2.0 license found in the * LICENSE file in the root directory of this source tree. * * Code generated by @carbon/icon-build-helpers. DO NOT EDIT. */ 'use strict'; var Icon = require('../Icon-399ca71f.js'); var React = require('react'); require('@carbon/icon-helpers'); require('prop-types'); function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; } var React__default = /*#__PURE__*/_interopDefaultLegacy(React); var _path; var UserProfileAlt24 = /*#__PURE__*/React__default['default'].forwardRef(function UserProfileAlt24(_ref, ref) { var children = _ref.children, rest = Icon._objectWithoutProperties(_ref, ["children"]); return /*#__PURE__*/React__default['default'].createElement(Icon.Icon, Icon._extends({ width: 24, height: 24, viewBox: "0 0 32 32", xmlns: "http://www.w3.org/2000/svg", fill: "currentColor", ref: ref }, rest), _path || (_path = /*#__PURE__*/React__default['default'].createElement("path", { d: "M19 13H26V15H19zM19 8H30V10H19zM19 3H30V5H19zM11 30H7a2.0059 2.0059 0 01-2-2V21a2.0059 2.0059 0 01-2-2V13a2.9465 2.9465 0 013-3h6a2.9465 2.9465 0 013 3v6a2.0059 2.0059 0 01-2 2v7A2.0059 2.0059 0 0111 30zM6 12a.9448.9448 0 00-1 1v6H7v9h4V19h2V13a.9448.9448 0 00-1-1zM9 9a4 4 0 114-4h0A4.0118 4.0118 0 019 9zM9 3a2 2 0 102 2h0A2.0059 2.0059 0 009 3z" })), children); }); module.exports = UserProfileAlt24;
#!/usr/bin/env python # IPFIX support for Scapy (RFC7011) from scapy.all import * # IPFIX Information Elements http://www.iana.org/assignments/ipfix/ipfix.xhtml information_elements = { 1: "octetDeltaCount", 2: "packetDeltaCount", 3: "deltaFlowCount", 4: "protocolIdentifier", 5: "ipClassOfService", 6: "tcpControlBits", 7: "sourceTransportPort", 8: "sourceIPv4Address", 9: "sourceIPv4PrefixLength", 10: "ingressInterface", 11: "destinationTransportPort", 12: "destinationIPv4Address", 13: "destinationIPv4PrefixLength", 14: "egressInterface", 15: "ipNextHopIPv4Address", 16: "bgpSourceAsNumber", 17: "bgpDestinationAsNumber", 18: "bgpNextHopIPv4Address", 19: "postMCastPacketDeltaCount", 20: "postMCastOctetDeltaCount", 21: "flowEndSysUpTime", 22: "flowStartSysUpTime", 23: "postOctetDeltaCount", 24: "postPacketDeltaCount", 25: "minimumIpTotalLength", 26: "maximumIpTotalLength", 27: "sourceIPv6Address", 28: "destinationIPv6Address", 29: "sourceIPv6PrefixLength", 30: "destinationIPv6PrefixLength", 31: "flowLabelIPv6", 32: "icmpTypeCodeIPv4", 33: "igmpType", 34: "samplingInterval", 35: "samplingAlgorithm", 36: "flowActiveTimeout", 37: "flowIdleTimeout", 38: "engineType", 39: "engineId", 40: "exportedOctetTotalCount", 41: "exportedMessageTotalCount", 42: "exportedFlowRecordTotalCount", 43: "ipv4RouterSc", 44: "sourceIPv4Prefix", 45: "destinationIPv4Prefix", 46: "mplsTopLabelType", 47: "mplsTopLabelIPv4Address", 48: "samplerId", 49: "samplerMode", 50: "samplerRandomInterval", 51: "classId", 52: "minimumTTL", 53: "maximumTTL", 54: "fragmentIdentification", 55: "postIpClassOfService", 56: "sourceMacAddress", 57: "postDestinationMacAddress", 58: "vlanId", 59: "postVlanId", 60: "ipVersion", 61: "flowDirection", 62: "ipNextHopIPv6Address", 63: "bgpNextHopIPv6Address", 64: "ipv6ExtensionHeaders", 70: "mplsTopLabelStackSection", 71: "mplsLabelStackSection2", 72: "mplsLabelStackSection3", 73: "mplsLabelStackSection4", 74: "mplsLabelStackSection5", 75: "mplsLabelStackSection6", 76: "mplsLabelStackSection7", 77: "mplsLabelStackSection8", 78: "mplsLabelStackSection9", 79: "mplsLabelStackSection10", 80: "destinationMacAddress", 81: "postSourceMacAddress", 82: "interfaceName", 83: "interfaceDescription", 84: "samplerName", 85: "octetTotalCount", 86: "packetTotalCount", 87: "flagsAndSamplerId", 88: "fragmentOffset", 89: "forwardingStatus", 90: "mplsVpnRouteDistinguisher", 91: "mplsTopLabelPrefixLength", 92: "srcTrafficIndex", 93: "dstTrafficIndex", 94: "applicationDescription", 95: "applicationId", 96: "applicationName", 98: "postIpDiffServCodePoint", 99: "multicastReplicationFactor", 100: "className", 101: "classificationEngineId", 102: "layer2packetSectionOffset", 103: "layer2packetSectionSize", 104: "layer2packetSectionData", 128: "bgpNextAdjacentAsNumber", 129: "bgpPrevAdjacentAsNumber", 130: "exporterIPv4Address", 131: "exporterIPv6Address", 132: "droppedOctetDeltaCount", 133: "droppedPacketDeltaCount", 134: "droppedOctetTotalCount", 135: "droppedPacketTotalCount", 136: "flowEndReason", 137: "commonPropertiesId", 138: "observationPointId", 139: "icmpTypeCodeIPv6", 140: "mplsTopLabelIPv6Address", 141: "lineCardId", 142: "portId", 143: "meteringProcessId", 144: "exportingProcessId", 145: "templateId", 146: "wlanChannelId", 147: "wlanSSID", 148: "flowId", 149: "observationDomainId", 150: "flowStartSeconds", 151: "flowEndSeconds", 152: "flowStartMilliseconds", 153: "flowEndMilliseconds", 154: "flowStartMicroseconds", 155: "flowEndMicroseconds", 156: "flowStartNanoseconds", 157: "flowEndNanoseconds", 158: "flowStartDeltaMicroseconds", 159: "flowEndDeltaMicroseconds", 160: "systemInitTimeMilliseconds", 161: "flowDurationMilliseconds", 162: "flowDurationMicroseconds", 163: "observedFlowTotalCount", 164: "ignoredPacketTotalCount", 165: "ignoredOctetTotalCount", 166: "notSentFlowTotalCount", 167: "notSentPacketTotalCount", 168: "notSentOctetTotalCount", 169: "destinationIPv6Prefix", 170: "sourceIPv6Prefix", 171: "postOctetTotalCount", 172: "postPacketTotalCount", 173: "flowKeyIndicator", 174: "postMCastPacketTotalCount", 175: "postMCastOctetTotalCount", 176: "icmpTypeIPv4", 177: "icmpCodeIPv4", 178: "icmpTypeIPv6", 179: "icmpCodeIPv6", 180: "udpSourcePort", 181: "udpDestinationPort", 182: "tcpSourcePort", 183: "tcpDestinationPort", 184: "tcpSequenceNumber", 185: "tcpAcknowledgementNumber", 186: "tcpWindowSize", 187: "tcpUrgentPointer", 188: "tcpHeaderLength", 189: "ipHeaderLength", 190: "totalLengthIPv4", 191: "payloadLengthIPv6", 192: "ipTTL", 193: "nextHeaderIPv6", 194: "mplsPayloadLength", 195: "ipDiffServCodePoint", 196: "ipPrecedence", 197: "fragmentFlags", 198: "octetDeltaSumOfSquares", 199: "octetTotalSumOfSquares", 200: "mplsTopLabelTTL", 201: "mplsLabelStackLength", 202: "mplsLabelStackDepth", 203: "mplsTopLabelExp", 204: "ipPayloadLength", 205: "udpMessageLength", 206: "isMulticast", 207: "ipv4IHL", 208: "ipv4Options", 209: "tcpOptions", 210: "paddingOctets", 211: "collectorIPv4Address", 212: "collectorIPv6Address", 213: "exportInterface", 214: "exportProtocolVersion", 215: "exportTransportProtocol", 216: "collectorTransportPort", 217: "exporterTransportPort", 218: "tcpSynTotalCount", 219: "tcpFinTotalCount", 220: "tcpRstTotalCount", 221: "tcpPshTotalCount", 222: "tcpAckTotalCount", 223: "tcpUrgTotalCount", 224: "ipTotalLength", 225: "postNATSourceIPv4Address", 226: "postNATDestinationIPv4Address", 227: "postNAPTSourceTransportPort", 228: "postNAPTDestinationTransportPort", 229: "natOriginatingAddressRealm", 230: "natEvent", 231: "initiatorOctets", 232: "responderOctets", 233: "firewallEvent", 234: "ingressVRFID", 235: "egressVRFID", 236: "VRFname", 237: "postMplsTopLabelExp", 238: "tcpWindowScale", 239: "biflowDirection", 240: "ethernetHeaderLength", 241: "ethernetPayloadLength", 242: "ethernetTotalLength", 243: "dot1qVlanId", 244: "dot1qPriority", 245: "dot1qCustomerVlanId", 246: "dot1qCustomerPriority", 247: "metroEvcId", 248: "metroEvcType", 249: "pseudoWireId", 250: "pseudoWireType", 251: "pseudoWireControlWord", 252: "ingressPhysicalInterface", 253: "egressPhysicalInterface", 254: "postDot1qVlanId", 255: "postDot1qCustomerVlanId", 256: "ethernetType", 257: "postIpPrecedence", 258: "collectionTimeMilliseconds", 259: "exportSctpStreamId", 260: "maxExportSeconds", 261: "maxFlowEndSeconds", 262: "messageMD5Checksum", 263: "messageScope", 264: "minExportSeconds", 265: "minFlowStartSeconds", 266: "opaqueOctets", 267: "sessionScope", 268: "maxFlowEndMicroseconds", 269: "maxFlowEndMilliseconds", 270: "maxFlowEndNanoseconds", 271: "minFlowStartMicroseconds", 272: "minFlowStartMilliseconds", 273: "minFlowStartNanoseconds", 274: "collectorCertificate", 275: "exporterCertificate", 276: "dataRecordsReliability", 277: "observationPointType", 278: "newConnectionDeltaCount", 279: "connectionSumDurationSeconds", 280: "connectionTransactionId", 281: "postNATSourceIPv6Address", 282: "postNATDestinationIPv6Address", 283: "natPoolId", 284: "natPoolName", 285: "anonymizationFlags", 286: "anonymizationTechnique", 287: "informationElementIndex", 288: "p2pTechnology", 289: "tunnelTechnology", 290: "encryptedTechnology", 291: "basicList", 292: "subTemplateList", 293: "subTemplateMultiList", 294: "bgpValidityState", 295: "IPSecSPI", 296: "greKey", 297: "natType", 298: "initiatorPackets", 299: "responderPackets", 300: "observationDomainName", 301: "selectionSequenceId", 302: "selectorId", 303: "informationElementId", 304: "selectorAlgorithm", 305: "samplingPacketInterval", 306: "samplingPacketSpace", 307: "samplingTimeInterval", 308: "samplingTimeSpace", 309: "samplingSize", 310: "samplingPopulation", 311: "samplingProbability", 312: "dataLinkFrameSize", 313: "ipHeaderPacketSection", 314: "ipPayloadPacketSection", 315: "dataLinkFrameSection", 316: "mplsLabelStackSection", 317: "mplsPayloadPacketSection", 318: "selectorIdTotalPktsObserved", 319: "selectorIdTotalPktsSelected", 320: "absoluteError", 321: "relativeError", 322: "observationTimeSeconds", 323: "observationTimeMilliseconds", 324: "observationTimeMicroseconds", 325: "observationTimeNanoseconds", 326: "digestHashValue", 327: "hashIPPayloadOffset", 328: "hashIPPayloadSize", 329: "hashOutputRangeMin", 330: "hashOutputRangeMax", 331: "hashSelectedRangeMin", 332: "hashSelectedRangeMax", 333: "hashDigestOutput", 334: "hashInitialiserValue", 335: "selectorName", 336: "upperCILimit", 337: "lowerCILimit", 338: "confidenceLevel", 339: "informationElementDataType", 340: "informationElementDescription", 341: "informationElementName", 342: "informationElementRangeBegin", 343: "informationElementRangeEnd", 344: "informationElementSemantics", 345: "informationElementUnits", 346: "privateEnterpriseNumber", 347: "virtualStationInterfaceId", 348: "virtualStationInterfaceName", 349: "virtualStationUUID", 350: "virtualStationName", 351: "layer2SegmentId", 352: "layer2OctetDeltaCount", 353: "layer2OctetTotalCount", 354: "ingressUnicastPacketTotalCount", 355: "ingressMulticastPacketTotalCount", 356: "ingressBroadcastPacketTotalCount", 357: "egressUnicastPacketTotalCount", 358: "egressBroadcastPacketTotalCount", 359: "monitoringIntervalStartMilliSeconds", 360: "monitoringIntervalEndMilliSeconds", 361: "portRangeStart", 362: "portRangeEnd", 363: "portRangeStepSize", 364: "portRangeNumPorts", 365: "staMacAddress", 366: "staIPv4Address", 367: "wtpMacAddress", 368: "ingressInterfaceType", 369: "egressInterfaceType", 370: "rtpSequenceNumber", 371: "userName", 372: "applicationCategoryName", 373: "applicationSubCategoryName", 374: "applicationGroupName", 375: "originalFlowsPresent", 376: "originalFlowsInitiated", 377: "originalFlowsCompleted", 378: "distinctCountOfSourceIPAddress", 379: "distinctCountOfDestinationIPAddress", 380: "distinctCountOfSourceIPv4Address", 381: "distinctCountOfDestinationIPv4Address", 382: "distinctCountOfSourceIPv6Address", 383: "distinctCountOfDestinationIPv6Address", 384: "valueDistributionMethod", 385: "rfc3550JitterMilliseconds", 386: "rfc3550JitterMicroseconds", 387: "rfc3550JitterNanoseconds", 388: "dot1qDEI", 389: "dot1qCustomerDEI", 390: "flowSelectorAlgorithm", 391: "flowSelectedOctetDeltaCount", 392: "flowSelectedPacketDeltaCount", 393: "flowSelectedFlowDeltaCount", 394: "selectorIDTotalFlowsObserved", 395: "selectorIDTotalFlowsSelected", 396: "samplingFlowInterval", 397: "samplingFlowSpacing", 398: "flowSamplingTimeInterval", 399: "flowSamplingTimeSpacing", 400: "hashFlowDomain", 401: "transportOctetDeltaCount", 402: "transportPacketDeltaCount", 403: "originalExporterIPv4Address", 404: "originalExporterIPv6Address", 405: "originalObservationDomainId", 406: "intermediateProcessId", 407: "ignoredDataRecordTotalCount", 408: "dataLinkFrameType", 409: "sectionOffset", 410: "sectionExportedOctets", 411: "dot1qServiceInstanceTag", 412: "dot1qServiceInstanceId", 413: "dot1qServiceInstancePriority", 414: "dot1qCustomerSourceMacAddress", 415: "dot1qCustomerDestinationMacAddress", 417: "postLayer2OctetDeltaCount", 418: "postMCastLayer2OctetDeltaCount", 420: "postLayer2OctetTotalCount", 421: "postMCastLayer2OctetTotalCount", 422: "minimumLayer2TotalLength", 423: "maximumLayer2TotalLength", 424: "droppedLayer2OctetDeltaCount", 425: "droppedLayer2OctetTotalCount", 426: "ignoredLayer2OctetTotalCount", 427: "notSentLayer2OctetTotalCount", 428: "layer2OctetDeltaSumOfSquares", 429: "layer2OctetTotalSumOfSquares", 430: "layer2FrameDeltaCount", 431: "layer2FrameTotalCount", 432: "pseudoWireDestinationIPv4Address", 433: "ignoredLayer2FrameTotalCount", 434: "mibObjectValueInteger", 435: "mibObjectValueOctetString", 436: "mibObjectValueOID", 437: "mibObjectValueBits", 438: "mibObjectValueIPAddress", 439: "mibObjectValueCounter", 440: "mibObjectValueGauge", 441: "mibObjectValueTimeTicks", 442: "mibObjectValueUnsigned", 443: "mibObjectValueTable", 444: "mibObjectValueRow", 445: "mibObjectIdentifier", 446: "mibSubIdentifier", 447: "mibIndexIndicator", 448: "mibCaptureTimeSemantics", 449: "mibContextEngineID", 450: "mibContextName", 451: "mibObjectName", 452: "mibObjectDescription", 453: "mibObjectSyntax", 454: "mibModuleName", 455: "mobileIMSI", 456: "mobileMSISDN", 457: "httpStatusCode", 458: "sourceTransportPortsLimit", 459: "httpRequestMethod", 460: "httpRequestHost", 461: "httpRequestTarget", 462: "httpMessageVersion" } class IPFIX(Packet): name = "IPFIX" fields_desc = [ShortField("version", 10), ShortField("length", None), IntField("exportTime", None), IntField("sequenceNumber", 1), IntField("observationDomainID", 1)] class FieldSpecifier(Packet): name = "Field Specifier" fields_desc = [ShortEnumField( "informationElement", None, information_elements), ShortField("fieldLength", None)] def extract_padding(self, s): return "", s class Template(Packet): name = "Template" fields_desc = [ShortField("templateID", 256), FieldLenField("fieldCount", None, count_of="fields"), PacketListField("templateFields", [], FieldSpecifier, count_from=lambda p: p.fieldCount)] class Data(Packet): name = "Data" fields_desc = [ StrLenField("data", "", length_from=lambda p: p.underlayer.length - 4)] def extract_padding(self, s): return "", s class Set(Packet): name = "Set" fields_desc = [ShortField("setID", 256), ShortField("length", None)] def guess_payload_class(self, payload): if self.setID == 2: return Template elif self.setID > 255: return Data else: return Packet.guess_payload_class(self, payload) bind_layers(IPFIX, Set) bind_layers(UDP, IPFIX, dport=4739) class IPFIXDecoder(object): """ IPFIX data set decoder """ def __init__(self): self._templates = [] def add_template(self, template): """ Add IPFIX tempalte :param template: IPFIX template """ templateID = template.templateID fields = [] rec_len = 0 for field in template.templateFields: fields.append( {'name': field.informationElement, 'len': field.fieldLength}) rec_len += field.fieldLength self._templates.append( {'id': templateID, 'fields': fields, 'rec_len': rec_len}) def decode_data_set(self, data_set): """ Decode IPFIX data :param data_set: IPFIX data set :returns: List of decoded data records. """ data = [] for template in self._templates: if template['id'] == data_set.setID: offset = 0 d = data_set[Data].data for i in range(len(d) / template['rec_len']): record = {} for field in template['fields']: f = d[offset:offset + field['len']] offset += field['len'] record.update({field['name']: f}) data.append(record) break return data
(this.webpackJsonpinvoid=this.webpackJsonpinvoid||[]).push([[0],{50:function(e,t,c){},60:function(e,t,c){},61:function(e,t,c){"use strict";c.r(t);var n=c(2),s=c.n(n),i=c(25),r=c.n(i),a=(c(50),c(23)),j=c(33),o=c(13),l=c(82),d=c(88),b=c(84),h=c(87),u=c(86),x=c(85),O=c.p+"static/media/gg.b79d6914.png",p=c.p+"static/media/v.dce1ae79.gif",g=c(3),f=Object(l.a)((function(e){return{root:{width:"100%"},backButton:{marginRight:e.spacing(1)},instructions:{marginTop:e.spacing(1),marginBottom:e.spacing(1)}}}));function m(e){switch(e){case 0:return Object(g.jsxs)("div",{className:"steper",children:[Object(g.jsx)("center",{children:Object(g.jsx)("h2",{children:"Enter Your Details"})}),Object(g.jsxs)("div",{children:[Object(g.jsx)("label",{children:"Enter Full Name"}),Object(g.jsx)("input",{type:"text",autoFocus:!0,placeholder:"Enter Your Full Name"})]}),Object(g.jsxs)("div",{children:[Object(g.jsx)("label",{children:"Select id Proof"}),Object(g.jsxs)("select",{class:"form-field",formControlName:"gender",id:"gender",required:!0,children:[Object(g.jsx)("option",{value:"",disabled:!0,selected:!0,children:"Select your option"}),Object(g.jsx)("option",{value:"",children:"Aadhar card"}),Object(g.jsx)("option",{children:" Pan Card "}),Object(g.jsx)("option",{children:" Passport "})]})]}),Object(g.jsxs)("div",{children:[Object(g.jsx)("label",{children:"Enter your ID"}),Object(g.jsx)("input",{type:"text",autoFocus:!0,placeholder:"Enter Id Proof no"})]}),Object(g.jsxs)("div",{children:[Object(g.jsx)("label",{children:"Enter Phone no"}),Object(g.jsx)("input",{type:"text",autoFocus:!0,placeholder:"Enter Phone no"})]})]});case 1:return Object(g.jsxs)("div",{className:"steper",children:[Object(g.jsx)("center",{children:Object(g.jsx)("h2",{children:"Confirm Your Details"})}),Object(g.jsx)("br",{}),Object(g.jsx)("div",{children:Object(g.jsx)("center",{children:Object(g.jsx)("img",{src:O,alt:"fireSpot",width:"450px"})})}),Object(g.jsxs)("div",{children:[Object(g.jsx)("label",{children:"Enter OTP"}),Object(g.jsx)("input",{type:"text",autoFocus:!0,placeholder:"A OTP has been sent to xxxxxxx789"})]}),Object(g.jsxs)("div",{children:[Object(g.jsx)("label",{children:"Upload your own document"}),Object(g.jsx)("input",{type:"file",autoFocus:!0,placeholder:"Enter Phone number"})]})]});case 2:return"This is the bit I really care about!";default:return"Unknown stepIndex"}}function A(){var e=f(),t=s.a.useState(0),c=Object(a.a)(t,2),n=c[0],i=c[1],r=["General Details","Verification of details"];return Object(g.jsxs)("div",{className:e.root,children:[Object(g.jsx)(d.a,{activeStep:n,alternativeLabel:!0,children:r.map((function(e){return Object(g.jsx)(b.a,{children:Object(g.jsx)(h.a,{children:e})},e)}))}),Object(g.jsx)("div",{children:n===r.length?Object(g.jsxs)("div",{children:[Object(g.jsxs)(x.a,{className:e.instructions,children:[Object(g.jsxs)("div",{className:"steper",children:[Object(g.jsxs)("center",{children:[" ",Object(g.jsx)("h2",{children:"e-KYC Verified "})]}),Object(g.jsx)("br",{}),Object(g.jsx)("div",{children:Object(g.jsx)("img",{src:p,alt:"fireSpot",width:"350px"})})]}),";"]}),Object(g.jsx)(u.a,{onClick:function(){i(0)},children:"Reset"})]}):Object(g.jsxs)("div",{children:[Object(g.jsx)(x.a,{className:e.instructions,children:m(n)}),Object(g.jsxs)("div",{children:[Object(g.jsx)(u.a,{disabled:0===n,onClick:function(){i((function(e){return e-1}))},className:e.backButton,children:"Back"}),Object(g.jsx)(u.a,{variant:"contained",color:"primary",onClick:function(){i((function(e){return e+1}))},children:n===r.length-1?"Finish":"Next"})]})]})})]})}var w=c(39),E=w.a.initializeApp({apiKey:"AIzaSyBtGq4W37Su8E30Q1KtDGX9TfEx067pIWo",authDomain:"invoid-f98c2.firebaseapp.com",projectId:"invoid-f98c2",storageBucket:"invoid-f98c2.appspot.com",messagingSenderId:"485272512217",appId:"1:485272512217:web:6cc8431c5ffc26869940c8",measurementId:"G-MF8LPNCYS5"});w.a.analytics();var v=E,C="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAQsAAAA+CAYAAAA8lT74AAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAC61JREFUeNrsnT924zgShyE9b7yedJOmg41bOoGpeAPLwcRNnsDWCWSfQNIJRKezgeVgYtMnsCadDcxNJlY8G3hRcnEeh02iCn9ISZ76vce22xJJEEB9KAAFcPD+/q5EIpGI0lCyQCQSCSxEIpHAQiQS9auz8pfBYHDUCf3Hv17P9Y8R/jeufZzDP7/9PM6lSEWiMKqPZw7KPxwbLBAOU31cIhwi5qkFwuMJfmqA7KTYRaJPCAsNCQDDN30kAS4HoNjoY6WhsZXiF4k+ASwQEvOGLkYogbcxE2iIREr97Z8/gqe+Nnwl/f3Xn4rqH86OpLuxxi5HlwIIver7LfXPe+meiP7iioiGOcIu/R866GyINlwAxFsPoKjqFqExkvoiEvF1MFhoY73TPx71cX4gqgIwEqkCItERw0IbKXQ75kfw/GuElkgkOjZYICiOqUWfCzBEIlq9DnCiUbqColAf06D/1Ud9RiPWxxdlF49RB0bx28/jTKqESHRgWOD4gG3XA2YswIAhTqIwfC+v3AcGLm8coARdkq1MrYpEB+yGICjWlqfd6+NCG++MAMWfBMaujxTORdDY6BGnckUiUd+eBU6P2oACWvbUt4VHwKT6/g+KP+sSofcz83xmmJ6FKNSJxHOIxLPgGc3IARSTkF0BXFw2Vt+Pc7Tp1icGAwdwF+pj0dtCqphIYMEDxbPix1Fsu2qJ0cuYWABj4QGKpPKnBP8mEgksjh0UFWDAta/Vx6AppdjWuzBMCQswRDJm0WI05VoPm4HCtI++PXgYOn0pjmFQghmV1BMUVWAoHHi1Ei74iVo+3v3vP//eNpwTGy5Z6HOK2vfPMf2X2H0q77dDkMNy/039PIf0Nt7fIU9Mz6f09XPL601rz15NP1wL0vsCv7umHfN4FCrNlWtC2q8wzaNaAwzHi752FsJ+gq46RVA8mzKlQbCo6455/Qgz52ulQMuC3HCBo6/zqOj1KDt9vR+YYOSubYGZnaVlhYD8jA2VbNBwjmkX5nt9zl3lu3cIRg7cMzy/MKT3lujGASwuPEAB6TVNwW/19cdMqM2x7Gwatv2WBw5AotI94V4TITFHwHPSDnax0sdS32NXAe6zKT2///pT3kk3xBEUkPAl59r6gAr4hhUxQQOK8Xcw2DeLSEzObMc5zuRQz2uzCG6OwDu4wFj08YqVjmsskNev+ryEMCaT4L4+i/i+EZ8/MA33zcLYqoLyfgaII3D6Lrdy8eWtRdpLuLz65H3IMYu1JShAK8obqIx/3HIyRH//lYqVwAFPjmt2FRiME5uYkQ4rHKT71aG8ynxetwEDvQ4KGDce6aYMNGMC0lcxGt+0x3K7U36LLyMG7LuFBfbZXTItY7r5NpV6RLhX7Bao6b6eoDiG6NC/O4wpNTYOhrEDKm9dDYyCzKZ0swMD0gTOR1fjswTFQoVbfLlwyYdhIFC4ZFbOaGUXjoU7orokGH+xs4HFJwCFQg8tlMGsW7yLjaptnFI3MscWmTrnwQAKm9k5F3AmHYIiYXjWtpBb9AoLz4VhL8S1I+W3OvWGEbqdM54xrnSHbFum7ZGBIrQig5FQXZFvDgZjKs8CIVU/z2V2zhUYow5AEakjCe4beoAi8XSLKAPyJfU5oyX6hfmsZcsUfWJQADj3Ww5yIFpRWx1YUV4CGjJXV47dyrkF4Df4/BM8UsyTgnn+o+Uzcb23c8t6t6mUY7CQhDMPUPgGGlEPcRng+b56AquspIlDgZ3CupDvptRqLfKc4f7uZzfq8R4w0Kn/DpU1JhoEcjasEk9gUtZwXsx03/eQbBvv0JqhZ7Mg6kGE97sL5FXEir+BNcAha5rWxi6fDTTDeBYOC8Na3cYejGHEMBZOH/8zggLSeQExF01GAn/Tx0zxAtOmlq29bVeE8jLbAsY4sy4pPKcBFGV+AIw4a4xuAnoXnPyBdI+xHIu2MSSMPcl6g4XDwrC/mrIT8igmlIFUjIQaf/hqONd0jxGzn08ZzVNLX5/yRmY20Y1ojBPimc5VuJ3gpsxy3DLTn/oAY2gJipAjylEPRkF5LyH7lxmEc5/IkvQZBxQ1F9c1H70GOhEmJqDsWgyeMjQI3V7aZhzmW+rzTBZdEKp+plxQ1ICRdwYLnJkIPfVEXeslwD2oa4xCguJEvJ+d7VoBrJCuEKQGOhNPw2t7livPdJnyg5oaHgXoilBjFdum2R9uY9EJLHD60SZqDCrWdYDxhCyAYTi5z58YFErxl+kHOQ9BYzqXirlIHI0+JoC58czHlWf9pvSlQ9htXcpzyACFTRBS2acrGN81znZgwJZPgS4ZXQLfAk1PDBShPLbQhnXV4opTi7y2LaP/VMMWYjqbukbseX2qm557Xv8pGCwcQLHfLwIMlBlbEDOCplJH93dL9bNxDCbyBEWmRCE8vKTFwKkuyMqxEXjpARZddyULz2sUwWCh7EKtm0KaOeRLCO9ip+jR56ZC5MxI3Ago+hEOClL5NW3wDqZEndsc+JlOrSsZHhaW6z3a1j5w3BzSYPG63J26lxxQeISS7wQUznqwrAtU+WwOabAdRGr2Lf+FZA4Lw9p24uZQP+LsQYFdm3J7/zKMtTzgPjC6W742gFOB5o6gmAgonFviXNEzCFGALkhfXYQQAX9djWdw9MX2hLMaKG4dQLFpMXDYwg4qSEy1KPp7GWefB/zOnU8O4cKwxBEU8gIiP62UeVEUeBczhIbJGAtTfAF4HPoaUGZtrX+IpQTU1KxvXTHZA4TYR57jFtarfoc113xhCQqqleXsGbGfmu3j5T6VaWABxWG0YVbgGwZ0KOWGz+IAu1xNO4YFtcjReREnBnxFzrAoX8rDPG/GccfxOxz6df6Ojcrsjss6DwFFmK5IQQAjwulS60VjDaJmPBYexnZLGFuI8ZSc+DyhNi42jLU4LdkYNhj3mOhvZZabznKjxfZb5nfhYThuWiOg6EYPDCM2GWLGNEQKKFM0eltj4zRsT76ZhN0sqqF9tNlDowKKyBsWCIy9kbQAwzpaEcc0ci4wwKh93gjWMkbx5ggKefVgeO9iQzRGUQhDZE7XLnC7Oq6xJYresrEItfU+A6z7RpCz6xh2u2w3mDbDogaMwgcU1fENxR8dHiEw7ny8jMqO4K5dDwFFd3I1psIyTPueUe9utSG9mbbFw41+HxVvI5r7nvOp3Af0uekZMO1gB977j54ZPIKtNrZxhaTOLwvGmZGZRV+p3HgFZkpWCKqCCQkg6I1y2+Y9w/EYAUW3gjJ12VPywebLuAHPPaPbAHVmjUYFXnA5uAibG8cWRpYH9Cqq6ecMZkI6YeB2jQ3eDtMdrFt/Rhj5ThvfpPzd50YwHqKvdanspi1LaMAW/+WbsYqGvhwU9lfLgvXuYom8jCBX9usnMod7LfW9Lpnudxk16uKql6/HDC0YH/xmOc4w6qLczhhGHqyVBWOE1/gpt+jJUVeZIKA4iB4sYbHxiCtI1fev9wsp9mZCDrCDmJFr7EaETrOV1zHsu4agUWZHVGkFFIcRNdBZ15OPwamPMbhth6DobNYMr50GTvOFslxbMzxELTkiYMwEFAfritgsBNv5jgXgnqJjxdgg2EJgxOMuQVFJf6bcV2G3eUGpDUCHh6osaKQhHt45w2xfUiwKLu4GLllAo5sp/p4rpvoDWxOOAywVtwWGj4eUq49Nmrc1j6s4alggMODhx8p/Iw9b9/cC30h2Cto5fnYK3sWWWfarwPfN8U3u15auOBjVDA1uGbAc2WUJeYYeko1XsN+9Tp/33bgK/v+aA4zB+/v7xy+DwUErDr5igIre8xFUyvsTgoSoJ2FkY6w+BkC/1OrgCxpS3qcXYZF2SOsU0z2qgQ2mgJ0Hhks2HB0sKtBI1MdUURzQk1gJJESiTwaLCjRKYl4iOLjTPDv0ImD0fCMBViLRJ4dFAzzKaLSmqLQd9ssKbqSnSCRyhIVIJBKZNJQsEIlEAguRSCSwEIlEAguRSCSwEIlEp6r/CzAAfvheFpor81UAAAAASUVORK5CYII=",I=function(e){var t=e.email,c=e.setEmail,n=e.password,s=e.setPassword,i=e.handleLogin,r=e.handleSignup,a=e.hasAccount,j=e.setHasAccount,o=e.emailError,l=e.passwordError;return Object(g.jsx)("section",{className:"login",children:Object(g.jsxs)("div",{className:"loginContainer",children:[Object(g.jsx)("div",{children:Object(g.jsx)("center",{children:Object(g.jsx)("img",{src:C,alt:"fireSpot",width:"250px"})})}),Object(g.jsx)("br",{}),Object(g.jsx)("br",{}),Object(g.jsx)("center",{children:Object(g.jsx)("label",{children:"Enter your E-mail"})}),Object(g.jsx)("input",{type:"text",autoFocus:!0,required:!0,value:t,onChange:function(e){return c(e.target.value)}}),Object(g.jsxs)("p",{className:"errorMsg",children:[o," "]}),Object(g.jsx)("center",{children:Object(g.jsx)("label",{children:"Enter the Password atleast 6 characters"})}),Object(g.jsx)("input",{type:"Password",required:!0,value:n,onChange:function(e){return s(e.target.value)}}),Object(g.jsxs)("p",{className:"errorMsg",children:[l," "]}),Object(g.jsx)("div",{className:"btnContainer",children:a?Object(g.jsxs)(g.Fragment,{children:[Object(g.jsx)("button",{onClick:i,children:"Sign in"}),Object(g.jsxs)("p",{children:[" Dont't have An Account? ",Object(g.jsx)("span",{onClick:function(){return j(!a)},children:" Sign up"})]})]}):Object(g.jsxs)(g.Fragment,{children:[Object(g.jsx)("button",{onClick:r,children:"Sign up"}),Object(g.jsxs)("p",{children:["Already have an account?",Object(g.jsx)("span",{onClick:function(){return j(!a)},children:"Sign in"})]})]})})]})})},F=c.p+"static/media/img2.1419ce58.gif",P=function(e){var t=e.handleLogout;return Object(g.jsxs)("section",{className:"hero",children:[Object(g.jsx)("nav",{children:Object(g.jsx)("div",{children:Object(g.jsx)("img",{src:C,alt:"fireSpot",width:"100 px"})})}),Object(g.jsx)("br",{}),Object(g.jsx)("br",{}),Object(g.jsxs)("div",{class:"column",children:[Object(g.jsx)("tab",{children:" "})," ",Object(g.jsx)("tab",{})," ",Object(g.jsx)("br",{}),Object(g.jsx)("br",{}),Object(g.jsx)("br",{}),Object(g.jsx)("br",{}),Object(g.jsx)("br",{}),Object(g.jsx)("div",{children:Object(g.jsx)("img",{src:F,alt:"fireSpot"})})]}),Object(g.jsxs)("div",{class:"col",children:[Object(g.jsx)("div",{children:Object(g.jsx)("center",{children:Object(g.jsx)("img",{src:C,alt:"fireSpot",width:"100 px"})})}),Object(g.jsx)("br",{}),Object(g.jsx)("h4",{children:"In today\u2019s age, with numerous cyber frauds and identity thefts, efficient and dependable customer verification before onboarding has become a prerequisite for many businesses. Many businesses like matrimonial, car rental, insurance, trading need identity verification. However, the manual verification of thousands of customers can become a tedious and cumbersome task for both businesses and customers. Even the digital methods present are slow and inefficient. Also, identity verification is not user-friendly and degrades the user experience."}),Object(g.jsx)("br",{}),Object(g.jsxs)("center",{children:[Object(g.jsx)(j.b,{to:"/Verification",children:Object(g.jsx)("button",{type:"button",className:"btn btn-info",children:"Ready to Verify!"})}),Object(g.jsx)("center",{children:Object(g.jsx)("h3",{children:" Or, "})}),Object(g.jsx)("button",{onClick:t,children:"Logout"})]})]})]})},Y=(c(60),function(){var e=Object(n.useState)(""),t=Object(a.a)(e,2),c=t[0],s=t[1],i=Object(n.useState)(""),r=Object(a.a)(i,2),l=r[0],d=r[1],b=Object(n.useState)(""),h=Object(a.a)(b,2),u=h[0],x=h[1],O=Object(n.useState)(""),p=Object(a.a)(O,2),f=p[0],m=p[1],w=Object(n.useState)(""),E=Object(a.a)(w,2),C=E[0],F=E[1],Y=Object(n.useState)(!1),S=Object(a.a)(Y,2),G=S[0],y=S[1],D=function(){m(""),F("")},L=function(){v.auth().signOut()},B=function(){v.auth().onAuthStateChanged((function(e){e?(m(""),x(""),s(e)):s("")}))};return Object(n.useEffect)((function(){B()}),[]),Object(g.jsx)("div",{className:"App",children:c?Object(g.jsx)(j.a,{children:Object(g.jsx)(n.Suspense,{fallback:Object(g.jsx)("div",{children:"Loading..."}),children:Object(g.jsxs)(o.c,{children:[Object(g.jsx)(o.a,{exact:!0,path:"/",component:function(){return Object(g.jsx)(P,{handleLogout:L})}}),Object(g.jsx)(o.a,{path:"/Verification",component:A})]})})}):Object(g.jsx)(I,{email:l,setEmail:d,password:u,setPassword:x,handleLogin:function(){D(),v.auth().signInWithEmailAndPassword(l,u).catch((function(e){switch(e.code){case"auth/invalid-email":case"auth/user-disabled":case"auth/user-not-found":m(e.messafe);break;case"auth/wrong-password":F(e.message)}}))},handleSignup:function(){D(),v.auth().createUserWithEmailAndPassword(l,u).catch((function(e){switch(e.code){case"auth/email-already-in-use":case"auth/invalid-email":m(e.messafe);break;case"auth/weak-password":F(e.message)}}))},hasAccount:G,setHasAccount:y,emailError:f,passwordError:C})})}),S=function(e){e&&e instanceof Function&&c.e(3).then(c.bind(null,90)).then((function(t){var c=t.getCLS,n=t.getFID,s=t.getFCP,i=t.getLCP,r=t.getTTFB;c(e),n(e),s(e),i(e),r(e)}))};r.a.render(Object(g.jsx)(s.a.StrictMode,{children:Object(g.jsx)(Y,{})}),document.getElementById("root")),S()}},[[61,1,2]]]); //# sourceMappingURL=main.985fe351.chunk.js.map
import fs from 'fs' import pug from 'pug' import path from 'path' import express from 'express' import request from 'superagent' import l10n from '../client/l10n' import render from '../client/run-server' const themes = [ 'light', 'dark' ] , langs = Object.keys(l10n) , baseHref = process.env.BASE_HREF || '/' , canonBase = process.env.CANONICAL_URL ? process.env.CANONICAL_URL.replace(/\/$/, '') : null , apiUrl = process.env.API_URL.replace(/\/$/, '') const rpath = p => path.join(__dirname, p) const indexView = rpath('../../client/index.pug') const app = express() app.engine('pug', pug.__express) if (app.settings.env == 'development') app.use(require('morgan')('dev')) app.use(require('cookie-parser')()) app.use(require('body-parser').urlencoded({ extended: false })) app.use((req, res, next) => { // TODO: optimize /block-height/nnn (no need to render the whole app just to get the redirect) let theme = req.query.theme || req.cookies.theme || 'dark' if (!themes.includes(theme)) theme = 'light' if (req.query.theme && req.cookies.theme !== theme) res.cookie('theme', theme) let lang = req.query.lang || req.cookies.lang || 'en' if (!langs.includes(lang)) lang = 'en' if (req.query.lang && req.cookies.lang !== lang) res.cookie('lang', lang) render(req._parsedUrl.pathname, req._parsedUrl.query || '', req.body, { theme, lang }, (err, resp) => { if (err) return next(err) if (resp.redirect) return res.redirect(301, baseHref + resp.redirect.substr(1)) if (resp.errorCode) return res.sendStatus(resp.errorCode) res.status(resp.status || 200) res.render(indexView, { prerender_title: resp.title , prerender_html: resp.html , canon_url: canonBase ? canonBase + req.url : null , noscript: true , theme , t: l10n[lang] }) }) }) // Cleanup socket file from previous executions if (process.env.SOCKET_PATH) { try { if (fs.statSync(process.env.SOCKET_PATH).isSocket()) { fs.unlinkSync(process.env.SOCKET_PATH) } } catch (_) {} } app.listen(process.env.SOCKET_PATH || process.env.PORT || 5001, function(){ let addr = this.address() if (addr.address) addr = `${addr.address}:${addr.port}` console.log(`HTTP server running on ${addr}`) })
"""An Application for launching a kernel Authors ------- * MinRK """ #----------------------------------------------------------------------------- # Copyright (C) 2011 The IPython Development Team # # Distributed under the terms of the BSD License. The full license is in # the file COPYING.txt, distributed as part of this software. #----------------------------------------------------------------------------- #----------------------------------------------------------------------------- # Imports #----------------------------------------------------------------------------- from __future__ import print_function # Standard library imports import atexit import json import os import sys import signal # System library imports import zmq from zmq.eventloop import ioloop from zmq.eventloop.zmqstream import ZMQStream # IPython imports from IPython.core.ultratb import FormattedTB from IPython.core.application import ( BaseIPythonApplication, base_flags, base_aliases, catch_config_error ) from IPython.core.profiledir import ProfileDir from IPython.core.shellapp import ( InteractiveShellApp, shell_flags, shell_aliases ) from IPython.utils import io from IPython.utils.localinterfaces import LOCALHOST from IPython.utils.path import filefind from IPython.utils.py3compat import str_to_bytes from IPython.utils.traitlets import ( Any, Instance, Dict, Unicode, Integer, Bool, CaselessStrEnum, DottedObjectName, ) from IPython.utils.importstring import import_item from IPython.kernel import write_connection_file # local imports from heartbeat import Heartbeat from ipkernel import Kernel from parentpoller import ParentPollerUnix, ParentPollerWindows from session import ( Session, session_flags, session_aliases, default_secure, ) from zmqshell import ZMQInteractiveShell #----------------------------------------------------------------------------- # Flags and Aliases #----------------------------------------------------------------------------- kernel_aliases = dict(base_aliases) kernel_aliases.update({ 'ip' : 'IPKernelApp.ip', 'hb' : 'IPKernelApp.hb_port', 'shell' : 'IPKernelApp.shell_port', 'iopub' : 'IPKernelApp.iopub_port', 'stdin' : 'IPKernelApp.stdin_port', 'control' : 'IPKernelApp.control_port', 'f' : 'IPKernelApp.connection_file', 'parent': 'IPKernelApp.parent', 'transport': 'IPKernelApp.transport', }) if sys.platform.startswith('win'): kernel_aliases['interrupt'] = 'IPKernelApp.interrupt' kernel_flags = dict(base_flags) kernel_flags.update({ 'no-stdout' : ( {'IPKernelApp' : {'no_stdout' : True}}, "redirect stdout to the null device"), 'no-stderr' : ( {'IPKernelApp' : {'no_stderr' : True}}, "redirect stderr to the null device"), 'pylab' : ( {'IPKernelApp' : {'pylab' : 'auto'}}, """Pre-load matplotlib and numpy for interactive use with the default matplotlib backend."""), }) # inherit flags&aliases for any IPython shell apps kernel_aliases.update(shell_aliases) kernel_flags.update(shell_flags) # inherit flags&aliases for Sessions kernel_aliases.update(session_aliases) kernel_flags.update(session_flags) #----------------------------------------------------------------------------- # Application class for starting an IPython Kernel #----------------------------------------------------------------------------- class IPKernelApp(BaseIPythonApplication, InteractiveShellApp): name='ipkernel' aliases = Dict(kernel_aliases) flags = Dict(kernel_flags) classes = [Kernel, ZMQInteractiveShell, ProfileDir, Session] # the kernel class, as an importstring kernel_class = DottedObjectName('IPython.kernel.zmq.ipkernel.Kernel', config=True, help="""The Kernel subclass to be used. This should allow easy re-use of the IPKernelApp entry point to configure and launch kernels other than IPython's own. """) kernel = Any() poller = Any() # don't restrict this even though current pollers are all Threads heartbeat = Instance(Heartbeat) session = Instance('IPython.kernel.zmq.session.Session') ports = Dict() # inherit config file name from parent: parent_appname = Unicode(config=True) def _parent_appname_changed(self, name, old, new): if self.config_file_specified: # it was manually specified, ignore return self.config_file_name = new.replace('-','_') + u'_config.py' # don't let this count as specifying the config file self.config_file_specified = False # connection info: transport = CaselessStrEnum(['tcp', 'ipc'], default_value='tcp', config=True) ip = Unicode(config=True, help="Set the IP or interface on which the kernel will listen.") def _ip_default(self): if self.transport == 'ipc': if self.connection_file: return os.path.splitext(self.abs_connection_file)[0] + '-ipc' else: return 'kernel-ipc' else: return LOCALHOST hb_port = Integer(0, config=True, help="set the heartbeat port [default: random]") shell_port = Integer(0, config=True, help="set the shell (ROUTER) port [default: random]") iopub_port = Integer(0, config=True, help="set the iopub (PUB) port [default: random]") stdin_port = Integer(0, config=True, help="set the stdin (ROUTER) port [default: random]") control_port = Integer(0, config=True, help="set the control (ROUTER) port [default: random]") connection_file = Unicode('', config=True, help="""JSON file in which to store connection info [default: kernel-<pid>.json] This file will contain the IP, ports, and authentication key needed to connect clients to this kernel. By default, this file will be created in the security dir of the current profile, but can be specified by absolute path. """) @property def abs_connection_file(self): if os.path.basename(self.connection_file) == self.connection_file: return os.path.join(self.profile_dir.security_dir, self.connection_file) else: return self.connection_file # streams, etc. no_stdout = Bool(False, config=True, help="redirect stdout to the null device") no_stderr = Bool(False, config=True, help="redirect stderr to the null device") outstream_class = DottedObjectName('IPython.kernel.zmq.iostream.OutStream', config=True, help="The importstring for the OutStream factory") displayhook_class = DottedObjectName('IPython.kernel.zmq.displayhook.ZMQDisplayHook', config=True, help="The importstring for the DisplayHook factory") # polling parent = Integer(0, config=True, help="""kill this process if its parent dies. On Windows, the argument specifies the HANDLE of the parent process, otherwise it is simply boolean. """) interrupt = Integer(0, config=True, help="""ONLY USED ON WINDOWS Interrupt this process when the parent is signaled. """) def init_crash_handler(self): # Install minimal exception handling sys.excepthook = FormattedTB(mode='Verbose', color_scheme='NoColor', ostream=sys.__stdout__) def init_poller(self): if sys.platform == 'win32': if self.interrupt or self.parent: self.poller = ParentPollerWindows(self.interrupt, self.parent) elif self.parent: self.poller = ParentPollerUnix() def _bind_socket(self, s, port): iface = '%s://%s' % (self.transport, self.ip) if self.transport == 'tcp': if port <= 0: port = s.bind_to_random_port(iface) else: s.bind("tcp://%s:%i" % (self.ip, port)) elif self.transport == 'ipc': if port <= 0: port = 1 path = "%s-%i" % (self.ip, port) while os.path.exists(path): port = port + 1 path = "%s-%i" % (self.ip, port) else: path = "%s-%i" % (self.ip, port) s.bind("ipc://%s" % path) return port def load_connection_file(self): """load ip/port/hmac config from JSON connection file""" try: fname = filefind(self.connection_file, ['.', self.profile_dir.security_dir]) except IOError: self.log.debug("Connection file not found: %s", self.connection_file) # This means I own it, so I will clean it up: atexit.register(self.cleanup_connection_file) return self.log.debug(u"Loading connection file %s", fname) with open(fname) as f: s = f.read() cfg = json.loads(s) self.transport = cfg.get('transport', self.transport) if self.ip == self._ip_default() and 'ip' in cfg: # not overridden by config or cl_args self.ip = cfg['ip'] for channel in ('hb', 'shell', 'iopub', 'stdin', 'control'): name = channel + '_port' if getattr(self, name) == 0 and name in cfg: # not overridden by config or cl_args setattr(self, name, cfg[name]) if 'key' in cfg: self.config.Session.key = str_to_bytes(cfg['key']) def write_connection_file(self): """write connection info to JSON file""" cf = self.abs_connection_file self.log.debug("Writing connection file: %s", cf) write_connection_file(cf, ip=self.ip, key=self.session.key, transport=self.transport, shell_port=self.shell_port, stdin_port=self.stdin_port, hb_port=self.hb_port, iopub_port=self.iopub_port, control_port=self.control_port) def cleanup_connection_file(self): cf = self.abs_connection_file self.log.debug("Cleaning up connection file: %s", cf) try: os.remove(cf) except (IOError, OSError): pass self.cleanup_ipc_files() def cleanup_ipc_files(self): """cleanup ipc files if we wrote them""" if self.transport != 'ipc': return for port in (self.shell_port, self.iopub_port, self.stdin_port, self.hb_port, self.control_port): ipcfile = "%s-%i" % (self.ip, port) try: os.remove(ipcfile) except (IOError, OSError): pass def init_connection_file(self): if not self.connection_file: self.connection_file = "kernel-%s.json"%os.getpid() try: self.load_connection_file() except Exception: self.log.error("Failed to load connection file: %r", self.connection_file, exc_info=True) self.exit(1) def init_sockets(self): # Create a context, a session, and the kernel sockets. self.log.info("Starting the kernel at pid: %i", os.getpid()) context = zmq.Context.instance() # Uncomment this to try closing the context. # atexit.register(context.term) self.shell_socket = context.socket(zmq.ROUTER) self.shell_port = self._bind_socket(self.shell_socket, self.shell_port) self.log.debug("shell ROUTER Channel on port: %i" % self.shell_port) self.iopub_socket = context.socket(zmq.PUB) self.iopub_port = self._bind_socket(self.iopub_socket, self.iopub_port) self.log.debug("iopub PUB Channel on port: %i" % self.iopub_port) self.stdin_socket = context.socket(zmq.ROUTER) self.stdin_port = self._bind_socket(self.stdin_socket, self.stdin_port) self.log.debug("stdin ROUTER Channel on port: %i" % self.stdin_port) self.control_socket = context.socket(zmq.ROUTER) self.control_port = self._bind_socket(self.control_socket, self.control_port) self.log.debug("control ROUTER Channel on port: %i" % self.control_port) def init_heartbeat(self): """start the heart beating""" # heartbeat doesn't share context, because it mustn't be blocked # by the GIL, which is accessed by libzmq when freeing zero-copy messages hb_ctx = zmq.Context() self.heartbeat = Heartbeat(hb_ctx, (self.transport, self.ip, self.hb_port)) self.hb_port = self.heartbeat.port self.log.debug("Heartbeat REP Channel on port: %i" % self.hb_port) self.heartbeat.start() def log_connection_info(self): """display connection info, and store ports""" basename = os.path.basename(self.connection_file) if basename == self.connection_file or \ os.path.dirname(self.connection_file) == self.profile_dir.security_dir: # use shortname tail = basename if self.profile != 'default': tail += " --profile %s" % self.profile else: tail = self.connection_file lines = [ "To connect another client to this kernel, use:", " --existing %s" % tail, ] # log connection info # info-level, so often not shown. # frontends should use the %connect_info magic # to see the connection info for line in lines: self.log.info(line) # also raw print to the terminal if no parent (`ipython kernel`) if not self.parent: for line in lines: io.rprint(line) self.ports = dict(shell=self.shell_port, iopub=self.iopub_port, stdin=self.stdin_port, hb=self.hb_port, control=self.control_port) def init_session(self): """create our session object""" default_secure(self.config) self.session = Session(config=self.config, username=u'kernel') def init_blackhole(self): """redirects stdout/stderr to devnull if necessary""" if self.no_stdout or self.no_stderr: blackhole = open(os.devnull, 'w') if self.no_stdout: sys.stdout = sys.__stdout__ = blackhole if self.no_stderr: sys.stderr = sys.__stderr__ = blackhole def init_io(self): """Redirect input streams and set a display hook.""" if self.outstream_class: outstream_factory = import_item(str(self.outstream_class)) sys.stdout = outstream_factory(self.session, self.iopub_socket, u'stdout') sys.stderr = outstream_factory(self.session, self.iopub_socket, u'stderr') if self.displayhook_class: displayhook_factory = import_item(str(self.displayhook_class)) sys.displayhook = displayhook_factory(self.session, self.iopub_socket) def init_signal(self): signal.signal(signal.SIGINT, signal.SIG_IGN) def init_kernel(self): """Create the Kernel object itself""" shell_stream = ZMQStream(self.shell_socket) control_stream = ZMQStream(self.control_socket) kernel_factory = import_item(str(self.kernel_class)) kernel = kernel_factory(config=self.config, session=self.session, shell_streams=[shell_stream, control_stream], iopub_socket=self.iopub_socket, stdin_socket=self.stdin_socket, log=self.log, profile_dir=self.profile_dir, ) kernel.record_ports(self.ports) self.kernel = kernel def init_gui_pylab(self): """Enable GUI event loop integration, taking pylab into account.""" # Provide a wrapper for :meth:`InteractiveShellApp.init_gui_pylab` # to ensure that any exception is printed straight to stderr. # Normally _showtraceback associates the reply with an execution, # which means frontends will never draw it, as this exception # is not associated with any execute request. shell = self.shell _showtraceback = shell._showtraceback try: # replace pyerr-sending traceback with stderr def print_tb(etype, evalue, stb): print ("GUI event loop or pylab initialization failed", file=io.stderr) print (shell.InteractiveTB.stb2text(stb), file=io.stderr) shell._showtraceback = print_tb InteractiveShellApp.init_gui_pylab(self) finally: shell._showtraceback = _showtraceback def init_shell(self): self.shell = self.kernel.shell self.shell.configurables.append(self) @catch_config_error def initialize(self, argv=None): super(IPKernelApp, self).initialize(argv) self.init_blackhole() self.init_connection_file() self.init_session() self.init_poller() self.init_sockets() self.init_heartbeat() # writing/displaying connection info must be *after* init_sockets/heartbeat self.log_connection_info() self.write_connection_file() self.init_io() self.init_signal() self.init_kernel() # shell init steps self.init_path() self.init_shell() self.init_gui_pylab() self.init_extensions() self.init_code() # flush stdout/stderr, so that anything written to these streams during # initialization do not get associated with the first execution request sys.stdout.flush() sys.stderr.flush() def start(self): if self.poller is not None: self.poller.start() self.kernel.start() try: ioloop.IOLoop.instance().start() except KeyboardInterrupt: pass def main(): """Run an IPKernel as an application""" app = IPKernelApp.instance() app.initialize() app.start() if __name__ == '__main__': main()
# encoding: utf-8 # # Copyright (c) 2013 Dariusz Dwornikowski. All rights reserved. # # Adapted from https://github.com/tdi/sphinxcontrib-manpage # License: Apache 2 # import re from docutils import nodes, utils from docutils.parsers.rst.roles import set_classes from string import Template def make_link_node(rawtext, app, name, manpage_num, options): ref = app.config.man_url_regex if not ref: ref = "http://linux.die.net/man/%s/%s" % (manpage_num, name) else: s = Template(ref) ref = s.substitute(num=manpage_num, topic=name) set_classes(options) node = nodes.reference(rawtext, "%s(%s)" % (name, manpage_num), refuri=ref, **options) return node def man_role(name, rawtext, text, lineno, inliner, options={}, content=[]): app = inliner.document.settings.env.app p = re.compile("([a-zA-Z0-9_\.-_]+)\((\d)\)") m = p.match(text) manpage_num = m.group(2) name = m.group(1) node = make_link_node(rawtext, app, name, manpage_num, options) return [node], [] def setup(app): app.add_role('man', man_role) app.add_config_value('man_url_regex', None, 'env') return
let fetch = require('node-fetch') let handler = async (m, { conn, args }) => { response = args.join(' ') if (!args) throw 'Masukkan Parameter' m.reply('Bentar Kak...') let res = `https://ariarestapii.herokuapp.com/api/darkjokes?apikey=aria` conn.sendFile(m.chat, res, 'darkjokes.jpg', `Pemuda Tersesat Dasar`, m, false) } handler.help = ['darkjokes'].map(v => v + ' ') handler.tags = ['image'] handler.command = /^(darkjokes)$/i handler.owner = false handler.mods = false handler.premium = false handler.group = false handler.private = false handler.register = true handler.admin = false handler.botAdmin = false handler.fail = null handler.limit = true module.exports = handler
/* * JFFS2 -- Journalling Flash File System, Version 2. * * Copyright (C) 2001-2003 Red Hat, Inc. * * Created by Dominic Ostrowski <dominic.ostrowski@3glab.com> * Contributors: David Woodhouse, Nick Garnett, Richard Panton. * * For licensing information, see the file 'LICENCE' in this directory. * * $Id: flashio.c,v 1.1 2003/11/26 14:09:29 dwmw2 Exp $ * */ #include <linux/kernel.h> #include "nodelist.h" #include <rtdevice.h> int jffs2_flash_read(struct jffs2_sb_info * c, uint32_t offset, const size_t size, size_t * return_size, unsigned char *buffer) { uint32_t len; struct super_block *sb = OFNI_BS_2SFFJ(c); len = rt_mtd_nor_read(RT_MTD_NOR_DEVICE(sb->s_dev), offset, buffer, size); if (len != size) return -EIO; * return_size = len; return ENOERR; } int jffs2_flash_write(struct jffs2_sb_info * c, uint32_t offset, const size_t size, size_t * return_size, unsigned char *buffer) { uint32_t len; struct super_block *sb = OFNI_BS_2SFFJ(c); len = rt_mtd_nor_write(RT_MTD_NOR_DEVICE(sb->s_dev), offset, buffer, size); if (len != size) return -EIO; * return_size = len; return ENOERR; } int jffs2_flash_erase(struct jffs2_sb_info * c, struct jffs2_eraseblock * jeb) { rt_err_t result; struct super_block *sb = OFNI_BS_2SFFJ(c); result = rt_mtd_nor_erase_block(RT_MTD_NOR_DEVICE(sb->s_dev), jeb->offset, c->sector_size); if (result != RT_EOK) return -EIO; return ENOERR; } int jffs2_flash_direct_writev(struct jffs2_sb_info *c, const struct iovec *vecs, unsigned long count, loff_t to, size_t * retlen) { unsigned long i; size_t totlen = 0, thislen; int ret = 0; for (i = 0; i < count; i++) { // writes need to be aligned but the data we're passed may not be // Observation suggests most unaligned writes are small, so we // optimize for that case. if (((vecs[i].iov_len & (sizeof(int) - 1))) || (((unsigned long) vecs[i].iov_base & (sizeof(unsigned long) - 1)))) { // are there iov's after this one? Or is it so much we'd need // to do multiple writes anyway? if ((i + 1) < count || vecs[i].iov_len > 256) { // cop out and malloc unsigned long j; ssize_t sizetomalloc = 0, totvecsize = 0; char *cbuf, *cbufptr; for (j = i; j < count; j++) totvecsize += vecs[j].iov_len; // pad up in case unaligned sizetomalloc = totvecsize + sizeof(int) - 1; sizetomalloc &= ~(sizeof(int) - 1); cbuf = (char *) rt_malloc(sizetomalloc); // malloc returns aligned memory if (!cbuf) { ret = -ENOMEM; goto writev_out; } cbufptr = cbuf; for (j = i; j < count; j++) { memcpy(cbufptr, vecs[j].iov_base, vecs[j].iov_len); cbufptr += vecs[j].iov_len; } //rt_kprintf("direct_write: offset %d, size %d\n", to, sizetomalloc); ret = jffs2_flash_write(c, to, sizetomalloc, &thislen, (unsigned char *) cbuf); if (thislen > totvecsize) // in case it was aligned up thislen = totvecsize; totlen += thislen; rt_free(cbuf); goto writev_out; } else { // otherwise optimize for the common case int buf[256/sizeof(int)]; // int, so int aligned size_t lentowrite; lentowrite = vecs[i].iov_len; // pad up in case its unaligned lentowrite += sizeof(int) - 1; lentowrite &= ~(sizeof(int) - 1); memcpy(buf, vecs[i].iov_base, lentowrite); //rt_kprintf("direct_write: offset %d, size %d\n", to, lentowrite); ret = jffs2_flash_write(c, to, lentowrite, &thislen, (unsigned char *) &buf); if (thislen > vecs[i].iov_len) thislen = vecs[i].iov_len; } } else { //rt_kprintf("direct_writev: offset %d, size %d\n", to, vecs[i].iov_len); ret = jffs2_flash_write(c, to, vecs[i].iov_len, &thislen, vecs[i].iov_base); } totlen += thislen; if (ret || thislen != vecs[i].iov_len) break; to += vecs[i].iov_len; } writev_out: if (retlen) *retlen = totlen; return ret; }
import browser from "./browser.js"; import dom from "./domObjects.js"; import * as domUtils from "./domUtils.js"; import hypot from "./hypot.js"; import is from "./is.js"; import pointerExtend from "./pointerExtend.js"; export function copyCoords(dest, src) { dest.page = dest.page || {}; dest.page.x = src.page.x; dest.page.y = src.page.y; dest.client = dest.client || {}; dest.client.x = src.client.x; dest.client.y = src.client.y; dest.timeStamp = src.timeStamp; } export function setCoordDeltas(targetObj, prev, cur) { targetObj.page.x = cur.page.x - prev.page.x; targetObj.page.y = cur.page.y - prev.page.y; targetObj.client.x = cur.client.x - prev.client.x; targetObj.client.y = cur.client.y - prev.client.y; targetObj.timeStamp = cur.timeStamp - prev.timeStamp; } export function setCoordVelocity(targetObj, delta) { const dt = Math.max(delta.timeStamp / 1000, 0.001); targetObj.page.x = delta.page.x / dt; targetObj.page.y = delta.page.y / dt; targetObj.client.x = delta.client.x / dt; targetObj.client.y = delta.client.y / dt; targetObj.timeStamp = dt; } export function setZeroCoords(targetObj) { targetObj.page.x = 0; targetObj.page.y = 0; targetObj.client.x = 0; targetObj.client.y = 0; } export function isNativePointer(pointer) { return pointer instanceof dom.Event || pointer instanceof dom.Touch; } // Get specified X/Y coords for mouse or event.touches[0] export function getXY(type, pointer, xy) { xy = xy || {}; type = type || 'page'; xy.x = pointer[type + 'X']; xy.y = pointer[type + 'Y']; return xy; } export function getPageXY(pointer, page) { page = page || { x: 0, y: 0 }; // Opera Mobile handles the viewport and scrolling oddly if (browser.isOperaMobile && isNativePointer(pointer)) { getXY('screen', pointer, page); page.x += window.scrollX; page.y += window.scrollY; } else { getXY('page', pointer, page); } return page; } export function getClientXY(pointer, client) { client = client || {}; if (browser.isOperaMobile && isNativePointer(pointer)) { // Opera Mobile handles the viewport and scrolling oddly getXY('screen', pointer, client); } else { getXY('client', pointer, client); } return client; } export function getPointerId(pointer) { return is.number(pointer.pointerId) ? pointer.pointerId : pointer.identifier; } export function setCoords(dest, pointers, timeStamp) { const pointer = pointers.length > 1 ? pointerAverage(pointers) : pointers[0]; getPageXY(pointer, dest.page); getClientXY(pointer, dest.client); dest.timeStamp = timeStamp; } export function getTouchPair(event) { const touches = []; // array of touches is supplied if (is.array(event)) { touches[0] = event[0]; touches[1] = event[1]; } // an event else { if (event.type === 'touchend') { if (event.touches.length === 1) { touches[0] = event.touches[0]; touches[1] = event.changedTouches[0]; } else if (event.touches.length === 0) { touches[0] = event.changedTouches[0]; touches[1] = event.changedTouches[1]; } } else { touches[0] = event.touches[0]; touches[1] = event.touches[1]; } } return touches; } export function pointerAverage(pointers) { const average = { pageX: 0, pageY: 0, clientX: 0, clientY: 0, screenX: 0, screenY: 0 }; for (const pointer of pointers) { for (const prop in average) { average[prop] += pointer[prop]; } } for (const prop in average) { average[prop] /= pointers.length; } return average; } export function touchBBox(event) { if (!event.length) { return null; } const touches = getTouchPair(event); const minX = Math.min(touches[0].pageX, touches[1].pageX); const minY = Math.min(touches[0].pageY, touches[1].pageY); const maxX = Math.max(touches[0].pageX, touches[1].pageX); const maxY = Math.max(touches[0].pageY, touches[1].pageY); return { x: minX, y: minY, left: minX, top: minY, right: maxX, bottom: maxY, width: maxX - minX, height: maxY - minY }; } export function touchDistance(event, deltaSource) { const sourceX = deltaSource + 'X'; const sourceY = deltaSource + 'Y'; const touches = getTouchPair(event); const dx = touches[0][sourceX] - touches[1][sourceX]; const dy = touches[0][sourceY] - touches[1][sourceY]; return hypot(dx, dy); } export function touchAngle(event, deltaSource) { const sourceX = deltaSource + 'X'; const sourceY = deltaSource + 'Y'; const touches = getTouchPair(event); const dx = touches[1][sourceX] - touches[0][sourceX]; const dy = touches[1][sourceY] - touches[0][sourceY]; const angle = 180 * Math.atan2(dy, dx) / Math.PI; return angle; } export function getPointerType(pointer) { return is.string(pointer.pointerType) ? pointer.pointerType : is.number(pointer.pointerType) ? [undefined, undefined, 'touch', 'pen', 'mouse'][pointer.pointerType] : // if the PointerEvent API isn't available, then the "pointer" must // be either a MouseEvent, TouchEvent, or Touch object /touch/.test(pointer.type || '') || pointer instanceof dom.Touch ? 'touch' : 'mouse'; } // [ event.target, event.currentTarget ] export function getEventTargets(event) { const path = is.func(event.composedPath) ? event.composedPath() : event.path; return [domUtils.getActualElement(path ? path[0] : event.target), domUtils.getActualElement(event.currentTarget)]; } export function newCoords() { return { page: { x: 0, y: 0 }, client: { x: 0, y: 0 }, timeStamp: 0 }; } export function coordsToEvent(coords) { const event = { coords, get page() { return this.coords.page; }, get client() { return this.coords.client; }, get timeStamp() { return this.coords.timeStamp; }, get pageX() { return this.coords.page.x; }, get pageY() { return this.coords.page.y; }, get clientX() { return this.coords.client.x; }, get clientY() { return this.coords.client.y; }, get pointerId() { return this.coords.pointerId; }, get target() { return this.coords.target; }, get type() { return this.coords.type; }, get pointerType() { return this.coords.pointerType; }, get buttons() { return this.coords.buttons; }, preventDefault() {} }; return event; } export { pointerExtend }; //# sourceMappingURL=pointerUtils.js.map
$(function() { $('.slider-vn').slick({ dots: true, arrows: true, infinite: true, speed: 500, slidesToShow: 1, slidesToScroll: 1, swipeToSlide: true }); });
# Copyright 2019 The Cirq Developers # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import ( Any, Callable, Dict, Optional, Sequence, TYPE_CHECKING, ) from dataclasses import dataclass from google.protobuf import json_format from cirq.api.google import v2 from cirq.google.api import v2 as api_v2 from cirq.google import arg_func_langs if TYPE_CHECKING: import cirq @dataclass(frozen=True) class DeserializingArg: """Specification of the arguments to deserialize an argument to a gate. Args: serialized_name: The serialized name of the gate that is being deserialized. constructor_arg_name: The name of the argument in the constructor of the gate corresponding to this serialized argument. value_func: Sometimes a value from the serialized proto needs to converted to an appropriate type or form. This function takes the serialized value and returns the appropriate type. Defaults to None. required: Whether a value must be specified when constructing the deserialized gate. Defaults to True. """ serialized_name: str constructor_arg_name: str value_func: Optional[Callable[[arg_func_langs.ARG_LIKE], Any]] = None required: bool = True class GateOpDeserializer: """Describes how to deserialize a proto to a given Gate type. Attributes: serialized_gate_id: The id used when serializing the gate. """ def __init__(self, serialized_gate_id: str, gate_constructor: Callable, args: Sequence[DeserializingArg], num_qubits_param: Optional[str] = None): """Constructs a deserializer. Args: serialized_gate_id: The serialized id of the gate that is being deserialized. gate_constructor: A function that produces the deserialized gate given arguments from args. args: A list of the arguments to be read from the serialized gate and the information required to use this to construct the gate using the gate_constructor above. num_qubits_param: Some gate constructors require that the number of qubits be passed to their constructor. This is the name of the parameter in the constructor for this value. If None, no number of qubits is passed to the constructor. """ self.serialized_gate_id = serialized_gate_id self.gate_constructor = gate_constructor self.args = args self.num_qubits_param = num_qubits_param def from_proto_dict(self, proto: Dict, *, arg_function_language: str = '' ) -> 'cirq.GateOperation': """Turns a cirq.api.google.v2.Operation proto into a GateOperation.""" msg = v2.program_pb2.Operation() json_format.ParseDict(proto, msg) return self.from_proto(msg, arg_function_language=arg_function_language) def from_proto(self, proto: v2.program_pb2.Operation, *, arg_function_language: str = '') -> 'cirq.GateOperation': """Turns a cirq.api.google.v2.Operation proto into a GateOperation.""" qubits = [api_v2.grid_qubit_from_proto_id(q.id) for q in proto.qubits] args = self._args_from_proto( proto, arg_function_language=arg_function_language) if self.num_qubits_param is not None: args[self.num_qubits_param] = len(qubits) gate = self.gate_constructor(**args) return gate.on(*qubits) def _args_from_proto(self, proto: v2.program_pb2.Operation, *, arg_function_language: str ) -> Dict[str, arg_func_langs.ARG_LIKE]: return_args = {} for arg in self.args: if arg.serialized_name not in proto.args and arg.required: raise ValueError( 'Argument {} not in deserializing args, but is required.'. format(arg.serialized_name)) value = arg_func_langs._arg_from_proto( proto.args[arg.serialized_name], arg_function_language=arg_function_language, required_arg_name=None if not arg.required else arg.serialized_name) if arg.value_func is not None: value = arg.value_func(value) if value is not None: return_args[arg.constructor_arg_name] = value return return_args
/** * @license Angular v11.0.0-next.6+37.sha-a38293d.with-local-changes * (c) 2010-2020 Google LLC. https://angular.io/ * License: MIT */ !function(t){"function"==typeof define&&define.amd?define(t):t()}((function(){"use strict"; /** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */Zone.__load_patch("notification",(function(t,o,e){var n=t.Notification;if(n&&n.prototype){var i=Object.getOwnPropertyDescriptor(n.prototype,"onerror");i&&i.configurable&&e.patchOnProperties(n.prototype,null)}}))}));
# -*- coding: utf-8 -*- # CCP in Tomographic Imaging (CCPi) Core Imaging Library (CIL). # Copyright 2017-2020 UKRI-STFC # Copyright 2017-2020 University of Manchester # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np from ccpi.framework import ImageData from ccpi.optimisation.operators import LinearOperator from ccpi.framework import ImageGeometry, AcquisitionGeometry, BlockGeometry class ChannelwiseOperator(LinearOperator): r'''ChannelwiseOperator: takes in a single-channel operator op and the number of channels to be used, and creates a new multi-channel ChannelwiseOperator, which will apply the operator op independently on each channel for the number of channels specified. ChannelwiseOperator supports simple operators as input but not BlockOperators. Typically if such behaviour is desired, it can be achieved by creating instead a BlockOperator of ChannelwiseOperators. :param op: Single-channel operator :param channels: Number of channels :param dimension: 'prepend' (default) or 'append' channel dimension onto existing dimensions ''' def __init__(self, op, channels, dimension='prepend'): dom_op = op.domain_geometry() ran_op = op.range_geometry() geom_mc = [] # Create multi-channel domain and range geometries: Clones of the # input single-channel geometries but with the specified number of # channels and additional dimension_label 'channel'. for geom in [dom_op,ran_op]: if dimension == 'prepend': new_dimension_labels = ['channel']+geom.dimension_labels elif dimension == 'append': new_dimension_labels = geom.dimension_labels+['channel'] else: raise Exception("dimension must be either 'prepend' or 'append'") if isinstance(geom, ImageGeometry): geom_mc.append( ImageGeometry( geom.voxel_num_x, geom.voxel_num_y, geom.voxel_num_z, geom.voxel_size_x, geom.voxel_size_y, geom.voxel_size_z, geom.center_x, geom.center_y, geom.center_z, channels, dimension_labels=new_dimension_labels)) elif isinstance(geom, AcquisitionGeometry): geom_mc.append( AcquisitionGeometry( geom.geom_type, geom.dimension, geom.angles, geom.pixel_num_h, geom.pixel_size_h, geom.pixel_num_v, geom.pixel_size_v, geom.dist_source_center, geom.dist_center_detector, channels, dimension_labels=new_dimension_labels )) elif isinstance(geom,BlockGeometry): raise Exception("ChannelwiseOperator does not support BlockOperator as input. Consider making a BlockOperator of ChannelwiseOperators instead.") else: pass super(ChannelwiseOperator, self).__init__(domain_geometry=geom_mc[0], range_geometry=geom_mc[1]) self.op = op self.channels = channels def direct(self,x,out=None): '''Returns D(x)''' # Loop over channels, extract single-channel data, apply single-channel # operator's direct method and fill into multi-channel output data set. if out is None: output = self.range_geometry().allocate() cury = self.op.range_geometry().allocate() for k in range(self.channels): self.op.direct(x.subset(channel=k),cury) output.fill(cury.as_array(),channel=k) return output else: cury = self.op.range_geometry().allocate() for k in range(self.channels): self.op.direct(x.subset(channel=k),cury) out.fill(cury.as_array(),channel=k) def adjoint(self,x, out=None): '''Returns D^{*}(y)''' # Loop over channels, extract single-channel data, apply single-channel # operator's adjoint method and fill into multi-channel output data set. if out is None: output = self.domain_geometry().allocate() cury = self.op.domain_geometry().allocate() for k in range(self.channels): self.op.adjoint(x.subset(channel=k),cury) output.fill(cury.as_array(),channel=k) return output else: cury = self.op.domain_geometry().allocate() for k in range(self.channels): self.op.adjoint(x.subset(channel=k),cury) out.fill(cury.as_array(),channel=k) def calculate_norm(self, **kwargs): '''Evaluates operator norm of DiagonalOperator''' return self.op.norm() if __name__ == '__main__': from ccpi.optimisation.operators import DiagonalOperator M = 3 channels = 4 ig = ImageGeometry(M, M, channels=channels) igs = ImageGeometry(M, M) x = ig.allocate('random',seed=100) diag = igs.allocate('random',seed=101) D = DiagonalOperator(diag) C = ChannelwiseOperator(D,channels) y = C.direct(x) y2 = ig.allocate() C.direct(x,y2) print(y.subset(channel=2).as_array()) print(y2.subset(channel=2).as_array()) print((diag*x.subset(channel=2)).as_array()) z = C.adjoint(y) z2 = ig.allocate() C.adjoint(y,z2) print(z.subset(channel=2).as_array()) print(z2.subset(channel=2).as_array()) print((diag*(diag*x.subset(channel=2))).as_array())