text
stringlengths
3
1.05M
exports.nature = ['๐Ÿถ', '๐Ÿฑ', '๐Ÿญ', '๐Ÿน', '๐Ÿฐ', '๐Ÿป', '๐Ÿผ', '๐Ÿจ', '๐Ÿฏ', '๐Ÿฆ', '๐Ÿฎ', '๐Ÿท', '๐Ÿฝ', '๐Ÿธ', '๐Ÿ™', '๐Ÿต', '๐Ÿ™ˆ', '๐Ÿ™‰', '๐Ÿ™Š', '๐Ÿ’', '๐Ÿ”', '๐Ÿง', '๐Ÿฆ', '๐Ÿค', '๐Ÿฃ', '๐Ÿฅ', '๐Ÿบ', '๐Ÿ—', '๐Ÿด', '๐Ÿฆ„', '๐Ÿ', '๐Ÿ›', '๐ŸŒ', '๐Ÿž', '๐Ÿœ', '๐Ÿ•ท', '๐Ÿฆ‚', '๐Ÿฆ€', '๐Ÿ', '๐Ÿข', '๐Ÿ ', '๐ŸŸ', '๐Ÿก', '๐Ÿฌ', '๐Ÿณ', '๐Ÿ‹', '๐ŸŠ', '๐Ÿ†', '๐Ÿ…', '๐Ÿƒ', '๐Ÿ‚', '๐Ÿ„', '๐Ÿช', '๐Ÿซ', '๐Ÿ˜', '๐Ÿ', '๐Ÿ', '๐Ÿ‘', '๐ŸŽ', '๐Ÿ–', '๐Ÿ€', '๐Ÿ', '๐Ÿ“', '๐Ÿฆƒ', '๐Ÿ•Š', '๐Ÿ•', '๐Ÿฉ', '๐Ÿˆ', '๐Ÿ‡', '๐Ÿฟ', '๐Ÿพ', '๐Ÿ‰', '๐Ÿฒ', '๐ŸŒต', '๐ŸŽ„', '๐ŸŒฒ', '๐ŸŒณ', '๐ŸŒด', '๐ŸŒฑ', '๐ŸŒฟ', ' โ˜˜ ', '๐Ÿ€', '๐ŸŽ', '๐ŸŽ‹', '๐Ÿƒ', '๐Ÿ‚', '๐Ÿ', '๐ŸŒพ', '๐ŸŒบ', '๐ŸŒป', '๐ŸŒน', '๐ŸŒท', '๐ŸŒผ', '๐ŸŒธ', '๐Ÿ’', '๐Ÿ„', '๐ŸŒฐ', '๐ŸŽƒ', '๐Ÿš', '๐Ÿ•ธ', '๐ŸŒŽ', '๐ŸŒ', '๐ŸŒ', '๐ŸŒ•', '๐ŸŒ–', '๐ŸŒ—', '๐ŸŒ˜', '๐ŸŒ‘', '๐ŸŒ’', '๐ŸŒ“', '๐ŸŒ”', '๐ŸŒš', '๐ŸŒ', '๐ŸŒ›', '๐ŸŒœ', '๐ŸŒž', '๐ŸŒ™', ' โญ๏ธ ', '๐ŸŒŸ', '๐Ÿ’ซ', ' โœจ โ˜„ โ˜€๏ธ ', '๐ŸŒค', ' โ›…๏ธ ', '๐ŸŒฅ', '๐ŸŒฆ', ' โ˜๏ธ ', '๐ŸŒง', ' โ›ˆ ', '๐ŸŒฉ', ' โšก๏ธ ', '๐Ÿ”ฅ', '๐Ÿ’ฅ', ' โ„๏ธ ', '๐ŸŒจ', '๐Ÿ”ฅ', '๐Ÿ’ฅ', ' โ„๏ธ ', '๐ŸŒจ', ' โ˜ƒ๏ธ โ›„๏ธ ', '๐ŸŒฌ', '๐Ÿ’จ', '๐ŸŒช', '๐ŸŒซ', ' โ˜‚๏ธ โ˜”๏ธ ', '๐Ÿ’ง', '๐Ÿ’ฆ'] exports.moons = [ '๐ŸŒ•', '๐ŸŒ–', '๐ŸŒ—', '๐ŸŒ˜', '๐ŸŒ‘', '๐ŸŒ’', '๐ŸŒ“', '๐ŸŒ”' ]
import styled from 'styled-components'; export const Wrapper = styled.section` padding-top: 2.35714em; padding-bottom: 0.64286em; text-align: center; display: flex; align-content: center; justify-content: center; `; export const Content = styled.p` @media (min-width: 64em) { width: 86%; } @media (min-width: 80em) { width: 75%; } font-size: 1.4em; font-weight: 300; `;
# -*- coding: utf-8 -*- # Generated by Django 1.9 on 2017-08-06 13:40 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('courses', '0004_course_category'), ] operations = [ migrations.AddField( model_name='course', name='tag', field=models.CharField(default='', max_length=10, verbose_name='\u8bfe\u7a0b\u6807\u7b7e'), ), ]
'use strict'; const sortBy = require('../util/sort-by'); /* Kruskal's algorithm https://en.wikipedia.org/wiki/Kruskal%27s_algorithm Given graph = { vertex: [names of each node], edge: [{ vertex: [names of an edge's two vertexes], distance }, ...] } Return another graph with same vertexes but fewer edges. The new graph is a tree with possibly minimized total distances. */ module.exports = graph => { // The new graph to be returned. const forest = { vertex: graph.vertex, edge: [] }; // All trees in the forest defined above. Initially, each tree has only one vertex. const trees = graph.vertex.map(vertex => [vertex]); // Find the index of the tree that one vertex belongs to. const indexOfTree = vertex => trees.findIndex(tree => tree.indexOf(vertex) >= 0); // Loop over all edges from short to long. sortBy(edge => edge.distance, Array.apply(null, graph.edge)).forEach(edge => { // We are already done if the forest has only one tree. if (trees.length === 1) { return; } const treesIndex = edge.vertex.map(indexOfTree); // The current edge is unnecessary if its vertexes belongs to one same tree. if (treesIndex[0] === treesIndex[1]) { return; } // Otherwise, add this edge to the forest. forest.edge.push(edge); // Now combine two trees of each vertex. trees[treesIndex[0]] = trees[treesIndex[0]].concat(trees[treesIndex[1]]); trees.splice(treesIndex[1], 1); }); return forest; };
export const getWarn = res => { switch (res) { case "auth/email-already-in-use": return "There already exists an account with the given email address"; case "auth/invalid-email": return "the email address is not valid"; case "auth/operation-not-allowed": return "email/password accounts are not enabled"; case "auth/weak-password": return "the password is not strong enough"; case "auth/user-disabled": return "the user corresponding to the given email has been disabled!"; case "auth/user-not-found": return "there is no user corresponding to the given email!"; case "auth/wrong-password": return "Wrong Password, Please check your Password!"; case "auth/no-uid": return "there is no user corresponding to this uid!"; case "auth/no-id": return "there is no data corresponding to this id!"; case "auth/not-object": return "Invalid Data Format, Please check your data!"; case "auth/invalid-keypair": return "Invalid Key pairs, Please check your data!"; case "auth/empty-field": return "Please fill all the input!"; case "auth/invalid-youtube": return "Please provide a valid YouTube Link!"; case "auth/invalid-money": return "Please provide a valid money amount!"; case "auth/database-error": return "Oops, Something failed in the server, please tye again!"; default: return ""; } };
def sp_eng(sentence: str) -> bool: return "english" in sentence.lower()
(window["webpackJsonp"] = window["webpackJsonp"] || []).push([[5],{ /***/ "./node_modules/babel-loader/lib/index.js?!./node_modules/vue-loader/lib/index.js?!./resources/js/admin/pages/BookCreate.vue?vue&type=script&lang=js&": /*!**********************************************************************************************************************************************************************!*\ !*** ./node_modules/babel-loader/lib??ref--4-0!./node_modules/vue-loader/lib??vue-loader-options!./resources/js/admin/pages/BookCreate.vue?vue&type=script&lang=js& ***! \**********************************************************************************************************************************************************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; eval("__webpack_require__.r(__webpack_exports__);\n/* harmony import */ var vform__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! vform */ \"./node_modules/vform/dist/vform.common.js\");\n/* harmony import */ var vform__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(vform__WEBPACK_IMPORTED_MODULE_0__);\n/* harmony import */ var axios__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! axios */ \"./node_modules/axios/index.js\");\n/* harmony import */ var axios__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(axios__WEBPACK_IMPORTED_MODULE_1__);\n/* harmony import */ var vuex__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! vuex */ \"./node_modules/vuex/dist/vuex.esm.js\");\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n\n\n\n/* harmony default export */ __webpack_exports__[\"default\"] = ({\n el: '#announcementForm',\n data: function data() {\n return {\n title: '',\n isbn: ''\n };\n },\n methods: {\n processForm: function processForm() {\n var _this2 = this;\n\n var _this = this;\n\n axios__WEBPACK_IMPORTED_MODULE_1___default.a.post('/apiadmin/v1/book/create', {\n title: this.title,\n isbn: this.isbn\n }).then(function (response) {\n _this.items = response.data.data;\n console.log(_this.items);\n\n _this2.$bvToast.toast('Book has been added', {\n title: 'Upload',\n variant: 'success',\n noAutoHide: false,\n solid: true\n });\n\n _this2.$router.push('/books');\n });\n }\n }\n});//# sourceURL=[module]\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIndlYnBhY2s6Ly8vcmVzb3VyY2VzL2pzL2FkbWluL3BhZ2VzL0Jvb2tDcmVhdGUudnVlPzUxMmYiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7OztBQTBCQTtBQUNBO0FBQ0E7QUFFQTtBQUNBLHlCQURBO0FBRUEsTUFGQSxrQkFFQTtBQUNBO0FBQ0EsZUFEQTtBQUVBO0FBRkE7QUFJQSxHQVBBO0FBU0E7QUFDQTtBQUFBOztBQUNBOztBQUNBO0FBQUE7QUFBQTtBQUFBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBLHlCQURBO0FBRUEsNEJBRkE7QUFHQSwyQkFIQTtBQUlBO0FBSkE7O0FBTUE7QUFDQSxPQVhBO0FBWUE7QUFmQTtBQVRBIiwiZmlsZSI6Ii4vbm9kZV9tb2R1bGVzL2JhYmVsLWxvYWRlci9saWIvaW5kZXguanM/IS4vbm9kZV9tb2R1bGVzL3Z1ZS1sb2FkZXIvbGliL2luZGV4LmpzPyEuL3Jlc291cmNlcy9qcy9hZG1pbi9wYWdlcy9Cb29rQ3JlYXRlLnZ1ZT92dWUmdHlwZT1zY3JpcHQmbGFuZz1qcyYuanMiLCJzb3VyY2VzQ29udGVudCI6WyI8dGVtcGxhdGU+XHJcbiAgICA8IS0tIEJFR0lOICNjb250ZW50IC0tPlxyXG4gICAgPGRpdiBpZD1cImNvbnRlbnRcIiBjbGFzcz1cImFwcC1jb250ZW50XCI+XHJcbiAgICAgICAgPGgxIGNsYXNzPVwicGFnZS1oZWFkZXJcIj5cclxuICAgICAgICAgICAgQ3JlYXRlIDxzbWFsbD5Cb29rPC9zbWFsbD5cclxuICAgICAgICA8L2gxPlxyXG5cclxuICAgICAgICA8aHIgY2xhc3M9XCJtYi00XCI+XHJcbiAgICAgICAgPGZvcm0gaWQ9XCJhbm5vdW5jZW1lbnRGb3JtXCIgQHN1Ym1pdC5wcmV2ZW50PVwicHJvY2Vzc0Zvcm1cIj5cclxuICAgICAgICA8Yi1jYXJkIHRpdGxlPVwiQm9vayBEZXRhaWxzXCI+XHJcbiAgICAgICAgPGxhYmVsIGZvcj1cInRpdGxlXCIgY2xhc3M9XCJmb3JtLWxhYmVsXCI+VGl0bGU8L2xhYmVsPlxyXG4gICAgICAgIDxiLWZvcm0taW5wdXQgIHR5cGU9XCJ0ZXh0XCIgbmFtZT1cInRpdGxlXCIgcGxhY2Vob2xkZXI9XCJFbnRlciBUaXRsZSBOYW1lXCIgdi1tb2RlbD1cIm5hbWVcIj48L2ItZm9ybS1pbnB1dD5cclxuXHJcbiAgICAgICAgPGhyIGNsYXNzPVwibWItMlwiPlxyXG5cclxuICAgICAgICA8bGFiZWwgZm9yPVwiaXNiblwiIGNsYXNzPVwiZm9ybS1sYWJlbFwiID5JU0JOPC9sYWJlbD5cclxuICAgICAgICA8Yi1mb3JtLWlucHV0ICB0eXBlPVwidGV4dFwiIG5hbWU9XCJpc2JuXCIgcGxhY2Vob2xkZXI9XCJFbnRlciBJU0JOXCIgdi1tb2RlbD1cImlzYm5cIj48L2ItZm9ybS1pbnB1dD5cclxuICAgICAgICA8L2ItY2FyZD5cclxuICAgICAgICA8aHIgY2xhc3M9XCJtYi00XCI+XHJcbiAgICAgICAgPGItYnV0dG9uIHR5cGU9XCJzdWJtaXRcIiB2YXJpYW50PVwicHJpbWFyeVwiIGFjdGl2ZSBzaXplPVwibGdcIj5TdWJtaXQ8L2ItYnV0dG9uPlxyXG4gICAgICAgIDwvZm9ybT5cclxuICAgIDwvZGl2PlxyXG4gICAgPCEtLSBFTkQgI2NvbnRlbnQgLS0+XHJcbjwvdGVtcGxhdGU+XHJcblxyXG48c2NyaXB0PlxyXG5pbXBvcnQgRm9ybSBmcm9tICd2Zm9ybSdcclxuaW1wb3J0IGF4aW9zIGZyb20gJ2F4aW9zJ1xyXG5pbXBvcnQgeyBtYXBHZXR0ZXJzIH0gZnJvbSAndnVleCdcclxuXHJcbmV4cG9ydCBkZWZhdWx0IHtcclxuICBlbDogJyNhbm5vdW5jZW1lbnRGb3JtJyxcclxuICBkYXRhKCkge1xyXG4gICAgcmV0dXJuIHtcclxuXHRcdHRpdGxlOiAnJyxcclxuICAgIGlzYm46ICcnLFxyXG4gICAgfVxyXG4gIH0sXHJcblxyXG4gIG1ldGhvZHM6e1xyXG4gICAgcHJvY2Vzc0Zvcm06IGZ1bmN0aW9uKCl7XHJcbiAgICAgIGxldCBfdGhpcyA9IHRoaXM7XHJcbiAgICAgICAgYXhpb3MucG9zdCgnL2FwaWFkbWluL3YxL2Jvb2svY3JlYXRlJywge3RpdGxlOiB0aGlzLnRpdGxlLGlzYm46IHRoaXMuaXNibn0pLnRoZW4ocmVzcG9uc2UgPT4ge1xyXG5cdFx0XHRcdFx0X3RoaXMuaXRlbXMgPSByZXNwb25zZS5kYXRhLmRhdGE7XHJcblx0XHRcdFx0XHRjb25zb2xlLmxvZyhfdGhpcy5pdGVtcyk7XHJcbiAgICAgICAgICBcclxuICAgICAgICAgIHRoaXMuJGJ2VG9hc3QudG9hc3QoJ0Jvb2sgaGFzIGJlZW4gYWRkZWQnLCB7XHJcbiAgICAgICAgICAgICAgdGl0bGU6ICdVcGxvYWQnLFxyXG4gICAgICAgICAgICAgIHZhcmlhbnQ6ICdzdWNjZXNzJyxcclxuICAgICAgICAgICAgICBub0F1dG9IaWRlOiBmYWxzZSxcclxuICAgICAgICAgICAgICBzb2xpZDogdHJ1ZVxyXG4gICAgICAgICAgfSlcclxuICAgICAgICAgIHRoaXMuJHJvdXRlci5wdXNoKCcvYm9va3MnKTtcclxuXHQgICAgICB9KTtcclxuICAgICAgICB9XHJcbiAgfVxyXG59XHJcbjwvc2NyaXB0PlxyXG4iXSwic291cmNlUm9vdCI6IiJ9\n//# sourceURL=webpack-internal:///./node_modules/babel-loader/lib/index.js?!./node_modules/vue-loader/lib/index.js?!./resources/js/admin/pages/BookCreate.vue?vue&type=script&lang=js&\n"); /***/ }), /***/ "./node_modules/vue-loader/lib/loaders/templateLoader.js?!./node_modules/vue-loader/lib/index.js?!./resources/js/admin/pages/BookCreate.vue?vue&type=template&id=5468df4e&": /*!**************************************************************************************************************************************************************************************************************!*\ !*** ./node_modules/vue-loader/lib/loaders/templateLoader.js??vue-loader-options!./node_modules/vue-loader/lib??vue-loader-options!./resources/js/admin/pages/BookCreate.vue?vue&type=template&id=5468df4e& ***! \**************************************************************************************************************************************************************************************************************/ /*! exports provided: render, staticRenderFns */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"render\", function() { return render; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"staticRenderFns\", function() { return staticRenderFns; });\nvar render = function () {\n var _vm = this\n var _h = _vm.$createElement\n var _c = _vm._self._c || _h\n return _c(\"div\", { staticClass: \"app-content\", attrs: { id: \"content\" } }, [\n _vm._m(0),\n _vm._v(\" \"),\n _c(\"hr\", { staticClass: \"mb-4\" }),\n _vm._v(\" \"),\n _c(\n \"form\",\n {\n attrs: { id: \"announcementForm\" },\n on: {\n submit: function ($event) {\n $event.preventDefault()\n return _vm.processForm.apply(null, arguments)\n },\n },\n },\n [\n _c(\n \"b-card\",\n { attrs: { title: \"Book Details\" } },\n [\n _c(\n \"label\",\n { staticClass: \"form-label\", attrs: { for: \"title\" } },\n [_vm._v(\"Title\")]\n ),\n _vm._v(\" \"),\n _c(\"b-form-input\", {\n attrs: {\n type: \"text\",\n name: \"title\",\n placeholder: \"Enter Title Name\",\n },\n model: {\n value: _vm.name,\n callback: function ($$v) {\n _vm.name = $$v\n },\n expression: \"name\",\n },\n }),\n _vm._v(\" \"),\n _c(\"hr\", { staticClass: \"mb-2\" }),\n _vm._v(\" \"),\n _c(\"label\", { staticClass: \"form-label\", attrs: { for: \"isbn\" } }, [\n _vm._v(\"ISBN\"),\n ]),\n _vm._v(\" \"),\n _c(\"b-form-input\", {\n attrs: { type: \"text\", name: \"isbn\", placeholder: \"Enter ISBN\" },\n model: {\n value: _vm.isbn,\n callback: function ($$v) {\n _vm.isbn = $$v\n },\n expression: \"isbn\",\n },\n }),\n ],\n 1\n ),\n _vm._v(\" \"),\n _c(\"hr\", { staticClass: \"mb-4\" }),\n _vm._v(\" \"),\n _c(\n \"b-button\",\n {\n attrs: {\n type: \"submit\",\n variant: \"primary\",\n active: \"\",\n size: \"lg\",\n },\n },\n [_vm._v(\"Submit\")]\n ),\n ],\n 1\n ),\n ])\n}\nvar staticRenderFns = [\n function () {\n var _vm = this\n var _h = _vm.$createElement\n var _c = _vm._self._c || _h\n return _c(\"h1\", { staticClass: \"page-header\" }, [\n _vm._v(\"\\n Create \"),\n _c(\"small\", [_vm._v(\"Book\")]),\n ])\n },\n]\nrender._withStripped = true\n\n//# sourceURL=[module]\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIndlYnBhY2s6Ly8vLi9yZXNvdXJjZXMvanMvYWRtaW4vcGFnZXMvQm9va0NyZWF0ZS52dWU/ZWI4ZCJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiQUFBQTtBQUFBO0FBQUE7QUFBQTtBQUNBO0FBQ0E7QUFDQTtBQUNBLG9CQUFvQixxQ0FBcUMsZ0JBQWdCLEVBQUU7QUFDM0U7QUFDQTtBQUNBLGNBQWMsc0JBQXNCO0FBQ3BDO0FBQ0E7QUFDQTtBQUNBO0FBQ0EsZ0JBQWdCLHlCQUF5QjtBQUN6QztBQUNBO0FBQ0E7QUFDQTtBQUNBLFdBQVc7QUFDWCxTQUFTO0FBQ1QsT0FBTztBQUNQO0FBQ0E7QUFDQTtBQUNBLFdBQVcsU0FBUyx3QkFBd0IsRUFBRTtBQUM5QztBQUNBO0FBQ0E7QUFDQSxlQUFlLG9DQUFvQyxlQUFlLEVBQUU7QUFDcEU7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBLGVBQWU7QUFDZjtBQUNBO0FBQ0E7QUFDQTtBQUNBLGlCQUFpQjtBQUNqQjtBQUNBLGVBQWU7QUFDZixhQUFhO0FBQ2I7QUFDQSxzQkFBc0Isc0JBQXNCO0FBQzVDO0FBQ0EseUJBQXlCLG9DQUFvQyxjQUFjLEVBQUU7QUFDN0U7QUFDQTtBQUNBO0FBQ0E7QUFDQSxzQkFBc0Isd0RBQXdEO0FBQzlFO0FBQ0E7QUFDQTtBQUNBO0FBQ0EsaUJBQWlCO0FBQ2pCO0FBQ0EsZUFBZTtBQUNmLGFBQWE7QUFDYjtBQUNBO0FBQ0E7QUFDQTtBQUNBLGtCQUFrQixzQkFBc0I7QUFDeEM7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0EsYUFBYTtBQUNiLFdBQVc7QUFDWDtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQSxxQkFBcUIsNkJBQTZCO0FBQ2xEO0FBQ0E7QUFDQTtBQUNBLEdBQUc7QUFDSDtBQUNBIiwiZmlsZSI6Ii4vbm9kZV9tb2R1bGVzL3Z1ZS1sb2FkZXIvbGliL2xvYWRlcnMvdGVtcGxhdGVMb2FkZXIuanM/IS4vbm9kZV9tb2R1bGVzL3Z1ZS1sb2FkZXIvbGliL2luZGV4LmpzPyEuL3Jlc291cmNlcy9qcy9hZG1pbi9wYWdlcy9Cb29rQ3JlYXRlLnZ1ZT92dWUmdHlwZT10ZW1wbGF0ZSZpZD01NDY4ZGY0ZSYuanMiLCJzb3VyY2VzQ29udGVudCI6WyJ2YXIgcmVuZGVyID0gZnVuY3Rpb24gKCkge1xuICB2YXIgX3ZtID0gdGhpc1xuICB2YXIgX2ggPSBfdm0uJGNyZWF0ZUVsZW1lbnRcbiAgdmFyIF9jID0gX3ZtLl9zZWxmLl9jIHx8IF9oXG4gIHJldHVybiBfYyhcImRpdlwiLCB7IHN0YXRpY0NsYXNzOiBcImFwcC1jb250ZW50XCIsIGF0dHJzOiB7IGlkOiBcImNvbnRlbnRcIiB9IH0sIFtcbiAgICBfdm0uX20oMCksXG4gICAgX3ZtLl92KFwiIFwiKSxcbiAgICBfYyhcImhyXCIsIHsgc3RhdGljQ2xhc3M6IFwibWItNFwiIH0pLFxuICAgIF92bS5fdihcIiBcIiksXG4gICAgX2MoXG4gICAgICBcImZvcm1cIixcbiAgICAgIHtcbiAgICAgICAgYXR0cnM6IHsgaWQ6IFwiYW5ub3VuY2VtZW50Rm9ybVwiIH0sXG4gICAgICAgIG9uOiB7XG4gICAgICAgICAgc3VibWl0OiBmdW5jdGlvbiAoJGV2ZW50KSB7XG4gICAgICAgICAgICAkZXZlbnQucHJldmVudERlZmF1bHQoKVxuICAgICAgICAgICAgcmV0dXJuIF92bS5wcm9jZXNzRm9ybS5hcHBseShudWxsLCBhcmd1bWVudHMpXG4gICAgICAgICAgfSxcbiAgICAgICAgfSxcbiAgICAgIH0sXG4gICAgICBbXG4gICAgICAgIF9jKFxuICAgICAgICAgIFwiYi1jYXJkXCIsXG4gICAgICAgICAgeyBhdHRyczogeyB0aXRsZTogXCJCb29rIERldGFpbHNcIiB9IH0sXG4gICAgICAgICAgW1xuICAgICAgICAgICAgX2MoXG4gICAgICAgICAgICAgIFwibGFiZWxcIixcbiAgICAgICAgICAgICAgeyBzdGF0aWNDbGFzczogXCJmb3JtLWxhYmVsXCIsIGF0dHJzOiB7IGZvcjogXCJ0aXRsZVwiIH0gfSxcbiAgICAgICAgICAgICAgW192bS5fdihcIlRpdGxlXCIpXVxuICAgICAgICAgICAgKSxcbiAgICAgICAgICAgIF92bS5fdihcIiBcIiksXG4gICAgICAgICAgICBfYyhcImItZm9ybS1pbnB1dFwiLCB7XG4gICAgICAgICAgICAgIGF0dHJzOiB7XG4gICAgICAgICAgICAgICAgdHlwZTogXCJ0ZXh0XCIsXG4gICAgICAgICAgICAgICAgbmFtZTogXCJ0aXRsZVwiLFxuICAgICAgICAgICAgICAgIHBsYWNlaG9sZGVyOiBcIkVudGVyIFRpdGxlIE5hbWVcIixcbiAgICAgICAgICAgICAgfSxcbiAgICAgICAgICAgICAgbW9kZWw6IHtcbiAgICAgICAgICAgICAgICB2YWx1ZTogX3ZtLm5hbWUsXG4gICAgICAgICAgICAgICAgY2FsbGJhY2s6IGZ1bmN0aW9uICgkJHYpIHtcbiAgICAgICAgICAgICAgICAgIF92bS5uYW1lID0gJCR2XG4gICAgICAgICAgICAgICAgfSxcbiAgICAgICAgICAgICAgICBleHByZXNzaW9uOiBcIm5hbWVcIixcbiAgICAgICAgICAgICAgfSxcbiAgICAgICAgICAgIH0pLFxuICAgICAgICAgICAgX3ZtLl92KFwiIFwiKSxcbiAgICAgICAgICAgIF9jKFwiaHJcIiwgeyBzdGF0aWNDbGFzczogXCJtYi0yXCIgfSksXG4gICAgICAgICAgICBfdm0uX3YoXCIgXCIpLFxuICAgICAgICAgICAgX2MoXCJsYWJlbFwiLCB7IHN0YXRpY0NsYXNzOiBcImZvcm0tbGFiZWxcIiwgYXR0cnM6IHsgZm9yOiBcImlzYm5cIiB9IH0sIFtcbiAgICAgICAgICAgICAgX3ZtLl92KFwiSVNCTlwiKSxcbiAgICAgICAgICAgIF0pLFxuICAgICAgICAgICAgX3ZtLl92KFwiIFwiKSxcbiAgICAgICAgICAgIF9jKFwiYi1mb3JtLWlucHV0XCIsIHtcbiAgICAgICAgICAgICAgYXR0cnM6IHsgdHlwZTogXCJ0ZXh0XCIsIG5hbWU6IFwiaXNiblwiLCBwbGFjZWhvbGRlcjogXCJFbnRlciBJU0JOXCIgfSxcbiAgICAgICAgICAgICAgbW9kZWw6IHtcbiAgICAgICAgICAgICAgICB2YWx1ZTogX3ZtLmlzYm4sXG4gICAgICAgICAgICAgICAgY2FsbGJhY2s6IGZ1bmN0aW9uICgkJHYpIHtcbiAgICAgICAgICAgICAgICAgIF92bS5pc2JuID0gJCR2XG4gICAgICAgICAgICAgICAgfSxcbiAgICAgICAgICAgICAgICBleHByZXNzaW9uOiBcImlzYm5cIixcbiAgICAgICAgICAgICAgfSxcbiAgICAgICAgICAgIH0pLFxuICAgICAgICAgIF0sXG4gICAgICAgICAgMVxuICAgICAgICApLFxuICAgICAgICBfdm0uX3YoXCIgXCIpLFxuICAgICAgICBfYyhcImhyXCIsIHsgc3RhdGljQ2xhc3M6IFwibWItNFwiIH0pLFxuICAgICAgICBfdm0uX3YoXCIgXCIpLFxuICAgICAgICBfYyhcbiAgICAgICAgICBcImItYnV0dG9uXCIsXG4gICAgICAgICAge1xuICAgICAgICAgICAgYXR0cnM6IHtcbiAgICAgICAgICAgICAgdHlwZTogXCJzdWJtaXRcIixcbiAgICAgICAgICAgICAgdmFyaWFudDogXCJwcmltYXJ5XCIsXG4gICAgICAgICAgICAgIGFjdGl2ZTogXCJcIixcbiAgICAgICAgICAgICAgc2l6ZTogXCJsZ1wiLFxuICAgICAgICAgICAgfSxcbiAgICAgICAgICB9LFxuICAgICAgICAgIFtfdm0uX3YoXCJTdWJtaXRcIildXG4gICAgICAgICksXG4gICAgICBdLFxuICAgICAgMVxuICAgICksXG4gIF0pXG59XG52YXIgc3RhdGljUmVuZGVyRm5zID0gW1xuICBmdW5jdGlvbiAoKSB7XG4gICAgdmFyIF92bSA9IHRoaXNcbiAgICB2YXIgX2ggPSBfdm0uJGNyZWF0ZUVsZW1lbnRcbiAgICB2YXIgX2MgPSBfdm0uX3NlbGYuX2MgfHwgX2hcbiAgICByZXR1cm4gX2MoXCJoMVwiLCB7IHN0YXRpY0NsYXNzOiBcInBhZ2UtaGVhZGVyXCIgfSwgW1xuICAgICAgX3ZtLl92KFwiXFxuICAgICAgICBDcmVhdGUgXCIpLFxuICAgICAgX2MoXCJzbWFsbFwiLCBbX3ZtLl92KFwiQm9va1wiKV0pLFxuICAgIF0pXG4gIH0sXG5dXG5yZW5kZXIuX3dpdGhTdHJpcHBlZCA9IHRydWVcblxuZXhwb3J0IHsgcmVuZGVyLCBzdGF0aWNSZW5kZXJGbnMgfSJdLCJzb3VyY2VSb290IjoiIn0=\n//# sourceURL=webpack-internal:///./node_modules/vue-loader/lib/loaders/templateLoader.js?!./node_modules/vue-loader/lib/index.js?!./resources/js/admin/pages/BookCreate.vue?vue&type=template&id=5468df4e&\n"); /***/ }), /***/ "./resources/js/admin/pages/BookCreate.vue": /*!*************************************************!*\ !*** ./resources/js/admin/pages/BookCreate.vue ***! \*************************************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; eval("__webpack_require__.r(__webpack_exports__);\n/* harmony import */ var _BookCreate_vue_vue_type_template_id_5468df4e___WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./BookCreate.vue?vue&type=template&id=5468df4e& */ \"./resources/js/admin/pages/BookCreate.vue?vue&type=template&id=5468df4e&\");\n/* harmony import */ var _BookCreate_vue_vue_type_script_lang_js___WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./BookCreate.vue?vue&type=script&lang=js& */ \"./resources/js/admin/pages/BookCreate.vue?vue&type=script&lang=js&\");\n/* empty/unused harmony star reexport *//* harmony import */ var _node_modules_vue_loader_lib_runtime_componentNormalizer_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../../../node_modules/vue-loader/lib/runtime/componentNormalizer.js */ \"./node_modules/vue-loader/lib/runtime/componentNormalizer.js\");\n\n\n\n\n\n/* normalize component */\n\nvar component = Object(_node_modules_vue_loader_lib_runtime_componentNormalizer_js__WEBPACK_IMPORTED_MODULE_2__[\"default\"])(\n _BookCreate_vue_vue_type_script_lang_js___WEBPACK_IMPORTED_MODULE_1__[\"default\"],\n _BookCreate_vue_vue_type_template_id_5468df4e___WEBPACK_IMPORTED_MODULE_0__[\"render\"],\n _BookCreate_vue_vue_type_template_id_5468df4e___WEBPACK_IMPORTED_MODULE_0__[\"staticRenderFns\"],\n false,\n null,\n null,\n null\n \n)\n\n/* hot reload */\nif (false) { var api; }\ncomponent.options.__file = \"resources/js/admin/pages/BookCreate.vue\"\n/* harmony default export */ __webpack_exports__[\"default\"] = (component.exports);//# sourceURL=[module]\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIndlYnBhY2s6Ly8vLi9yZXNvdXJjZXMvanMvYWRtaW4vcGFnZXMvQm9va0NyZWF0ZS52dWU/MzFjZSJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiQUFBQTtBQUFBO0FBQUE7QUFBQTtBQUF5RjtBQUMzQjtBQUNMOzs7QUFHekQ7QUFDZ0c7QUFDaEcsZ0JBQWdCLDJHQUFVO0FBQzFCLEVBQUUsZ0ZBQU07QUFDUixFQUFFLHFGQUFNO0FBQ1IsRUFBRSw4RkFBZTtBQUNqQjtBQUNBO0FBQ0E7QUFDQTs7QUFFQTs7QUFFQTtBQUNBLElBQUksS0FBVSxFQUFFLFlBaUJmO0FBQ0Q7QUFDZSxnRiIsImZpbGUiOiIuL3Jlc291cmNlcy9qcy9hZG1pbi9wYWdlcy9Cb29rQ3JlYXRlLnZ1ZS5qcyIsInNvdXJjZXNDb250ZW50IjpbImltcG9ydCB7IHJlbmRlciwgc3RhdGljUmVuZGVyRm5zIH0gZnJvbSBcIi4vQm9va0NyZWF0ZS52dWU/dnVlJnR5cGU9dGVtcGxhdGUmaWQ9NTQ2OGRmNGUmXCJcbmltcG9ydCBzY3JpcHQgZnJvbSBcIi4vQm9va0NyZWF0ZS52dWU/dnVlJnR5cGU9c2NyaXB0Jmxhbmc9anMmXCJcbmV4cG9ydCAqIGZyb20gXCIuL0Jvb2tDcmVhdGUudnVlP3Z1ZSZ0eXBlPXNjcmlwdCZsYW5nPWpzJlwiXG5cblxuLyogbm9ybWFsaXplIGNvbXBvbmVudCAqL1xuaW1wb3J0IG5vcm1hbGl6ZXIgZnJvbSBcIiEuLi8uLi8uLi8uLi9ub2RlX21vZHVsZXMvdnVlLWxvYWRlci9saWIvcnVudGltZS9jb21wb25lbnROb3JtYWxpemVyLmpzXCJcbnZhciBjb21wb25lbnQgPSBub3JtYWxpemVyKFxuICBzY3JpcHQsXG4gIHJlbmRlcixcbiAgc3RhdGljUmVuZGVyRm5zLFxuICBmYWxzZSxcbiAgbnVsbCxcbiAgbnVsbCxcbiAgbnVsbFxuICBcbilcblxuLyogaG90IHJlbG9hZCAqL1xuaWYgKG1vZHVsZS5ob3QpIHtcbiAgdmFyIGFwaSA9IHJlcXVpcmUoXCJEOlxcXFx4YW1wcFxcXFxodGRvY3NcXFxccHJvamVjdFxcXFxub2RlX21vZHVsZXNcXFxcdnVlLWhvdC1yZWxvYWQtYXBpXFxcXGRpc3RcXFxcaW5kZXguanNcIilcbiAgYXBpLmluc3RhbGwocmVxdWlyZSgndnVlJykpXG4gIGlmIChhcGkuY29tcGF0aWJsZSkge1xuICAgIG1vZHVsZS5ob3QuYWNjZXB0KClcbiAgICBpZiAoIWFwaS5pc1JlY29yZGVkKCc1NDY4ZGY0ZScpKSB7XG4gICAgICBhcGkuY3JlYXRlUmVjb3JkKCc1NDY4ZGY0ZScsIGNvbXBvbmVudC5vcHRpb25zKVxuICAgIH0gZWxzZSB7XG4gICAgICBhcGkucmVsb2FkKCc1NDY4ZGY0ZScsIGNvbXBvbmVudC5vcHRpb25zKVxuICAgIH1cbiAgICBtb2R1bGUuaG90LmFjY2VwdChcIi4vQm9va0NyZWF0ZS52dWU/dnVlJnR5cGU9dGVtcGxhdGUmaWQ9NTQ2OGRmNGUmXCIsIGZ1bmN0aW9uICgpIHtcbiAgICAgIGFwaS5yZXJlbmRlcignNTQ2OGRmNGUnLCB7XG4gICAgICAgIHJlbmRlcjogcmVuZGVyLFxuICAgICAgICBzdGF0aWNSZW5kZXJGbnM6IHN0YXRpY1JlbmRlckZuc1xuICAgICAgfSlcbiAgICB9KVxuICB9XG59XG5jb21wb25lbnQub3B0aW9ucy5fX2ZpbGUgPSBcInJlc291cmNlcy9qcy9hZG1pbi9wYWdlcy9Cb29rQ3JlYXRlLnZ1ZVwiXG5leHBvcnQgZGVmYXVsdCBjb21wb25lbnQuZXhwb3J0cyJdLCJzb3VyY2VSb290IjoiIn0=\n//# sourceURL=webpack-internal:///./resources/js/admin/pages/BookCreate.vue\n"); /***/ }), /***/ "./resources/js/admin/pages/BookCreate.vue?vue&type=script&lang=js&": /*!**************************************************************************!*\ !*** ./resources/js/admin/pages/BookCreate.vue?vue&type=script&lang=js& ***! \**************************************************************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; eval("__webpack_require__.r(__webpack_exports__);\n/* harmony import */ var _node_modules_babel_loader_lib_index_js_ref_4_0_node_modules_vue_loader_lib_index_js_vue_loader_options_BookCreate_vue_vue_type_script_lang_js___WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! -!../../../../node_modules/babel-loader/lib??ref--4-0!../../../../node_modules/vue-loader/lib??vue-loader-options!./BookCreate.vue?vue&type=script&lang=js& */ \"./node_modules/babel-loader/lib/index.js?!./node_modules/vue-loader/lib/index.js?!./resources/js/admin/pages/BookCreate.vue?vue&type=script&lang=js&\");\n/* empty/unused harmony star reexport */ /* harmony default export */ __webpack_exports__[\"default\"] = (_node_modules_babel_loader_lib_index_js_ref_4_0_node_modules_vue_loader_lib_index_js_vue_loader_options_BookCreate_vue_vue_type_script_lang_js___WEBPACK_IMPORTED_MODULE_0__[\"default\"]); //# sourceURL=[module]\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIndlYnBhY2s6Ly8vLi9yZXNvdXJjZXMvanMvYWRtaW4vcGFnZXMvQm9va0NyZWF0ZS52dWU/YTA4YiJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiQUFBQTtBQUFBO0FBQUEsd0NBQWdNLENBQWdCLHNQQUFHLEVBQUMiLCJmaWxlIjoiLi9yZXNvdXJjZXMvanMvYWRtaW4vcGFnZXMvQm9va0NyZWF0ZS52dWU/dnVlJnR5cGU9c2NyaXB0Jmxhbmc9anMmLmpzIiwic291cmNlc0NvbnRlbnQiOlsiaW1wb3J0IG1vZCBmcm9tIFwiLSEuLi8uLi8uLi8uLi9ub2RlX21vZHVsZXMvYmFiZWwtbG9hZGVyL2xpYi9pbmRleC5qcz8/cmVmLS00LTAhLi4vLi4vLi4vLi4vbm9kZV9tb2R1bGVzL3Z1ZS1sb2FkZXIvbGliL2luZGV4LmpzPz92dWUtbG9hZGVyLW9wdGlvbnMhLi9Cb29rQ3JlYXRlLnZ1ZT92dWUmdHlwZT1zY3JpcHQmbGFuZz1qcyZcIjsgZXhwb3J0IGRlZmF1bHQgbW9kOyBleHBvcnQgKiBmcm9tIFwiLSEuLi8uLi8uLi8uLi9ub2RlX21vZHVsZXMvYmFiZWwtbG9hZGVyL2xpYi9pbmRleC5qcz8/cmVmLS00LTAhLi4vLi4vLi4vLi4vbm9kZV9tb2R1bGVzL3Z1ZS1sb2FkZXIvbGliL2luZGV4LmpzPz92dWUtbG9hZGVyLW9wdGlvbnMhLi9Cb29rQ3JlYXRlLnZ1ZT92dWUmdHlwZT1zY3JpcHQmbGFuZz1qcyZcIiJdLCJzb3VyY2VSb290IjoiIn0=\n//# sourceURL=webpack-internal:///./resources/js/admin/pages/BookCreate.vue?vue&type=script&lang=js&\n"); /***/ }), /***/ "./resources/js/admin/pages/BookCreate.vue?vue&type=template&id=5468df4e&": /*!********************************************************************************!*\ !*** ./resources/js/admin/pages/BookCreate.vue?vue&type=template&id=5468df4e& ***! \********************************************************************************/ /*! exports provided: render, staticRenderFns */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; eval("__webpack_require__.r(__webpack_exports__);\n/* harmony import */ var _node_modules_vue_loader_lib_loaders_templateLoader_js_vue_loader_options_node_modules_vue_loader_lib_index_js_vue_loader_options_BookCreate_vue_vue_type_template_id_5468df4e___WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! -!../../../../node_modules/vue-loader/lib/loaders/templateLoader.js??vue-loader-options!../../../../node_modules/vue-loader/lib??vue-loader-options!./BookCreate.vue?vue&type=template&id=5468df4e& */ \"./node_modules/vue-loader/lib/loaders/templateLoader.js?!./node_modules/vue-loader/lib/index.js?!./resources/js/admin/pages/BookCreate.vue?vue&type=template&id=5468df4e&\");\n/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, \"render\", function() { return _node_modules_vue_loader_lib_loaders_templateLoader_js_vue_loader_options_node_modules_vue_loader_lib_index_js_vue_loader_options_BookCreate_vue_vue_type_template_id_5468df4e___WEBPACK_IMPORTED_MODULE_0__[\"render\"]; });\n\n/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, \"staticRenderFns\", function() { return _node_modules_vue_loader_lib_loaders_templateLoader_js_vue_loader_options_node_modules_vue_loader_lib_index_js_vue_loader_options_BookCreate_vue_vue_type_template_id_5468df4e___WEBPACK_IMPORTED_MODULE_0__[\"staticRenderFns\"]; });\n\n//# sourceURL=[module]\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIndlYnBhY2s6Ly8vLi9yZXNvdXJjZXMvanMvYWRtaW4vcGFnZXMvQm9va0NyZWF0ZS52dWU/MmY3MSJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiQUFBQTtBQUFBO0FBQUE7QUFBQTtBQUFBO0FBQUEiLCJmaWxlIjoiLi9yZXNvdXJjZXMvanMvYWRtaW4vcGFnZXMvQm9va0NyZWF0ZS52dWU/dnVlJnR5cGU9dGVtcGxhdGUmaWQ9NTQ2OGRmNGUmLmpzIiwic291cmNlc0NvbnRlbnQiOlsiZXhwb3J0ICogZnJvbSBcIi0hLi4vLi4vLi4vLi4vbm9kZV9tb2R1bGVzL3Z1ZS1sb2FkZXIvbGliL2xvYWRlcnMvdGVtcGxhdGVMb2FkZXIuanM/P3Z1ZS1sb2FkZXItb3B0aW9ucyEuLi8uLi8uLi8uLi9ub2RlX21vZHVsZXMvdnVlLWxvYWRlci9saWIvaW5kZXguanM/P3Z1ZS1sb2FkZXItb3B0aW9ucyEuL0Jvb2tDcmVhdGUudnVlP3Z1ZSZ0eXBlPXRlbXBsYXRlJmlkPTU0NjhkZjRlJlwiIl0sInNvdXJjZVJvb3QiOiIifQ==\n//# sourceURL=webpack-internal:///./resources/js/admin/pages/BookCreate.vue?vue&type=template&id=5468df4e&\n"); /***/ }) }]);
'use strict'; let name = 'Alexander'; const YEAR_OF_BIRTH = 2019; const greeting = name => console.log(`Hello, ${name}`); greeting('Alexander'); greeting(name);
import { hexToRgb, whiteColor } from "Admin/assets/jss/material-dashboard-react.js"; const customTabsStyle = { cardTitle: { float: "left", padding: "10px 10px 10px 0px", lineHeight: "24px" }, cardTitleRTL: { float: "right", padding: "10px 0px 10px 10px !important" }, displayNone: { display: "none !important" }, tabsRoot: { minHeight: "unset !important", overflowX: "visible", "& $tabRootButton": { fontSize: "0.875rem" } }, tabRootButton: { minHeight: "unset !important", minWidth: "unset !important", width: "unset !important", height: "unset !important", maxWidth: "unset !important", maxHeight: "unset !important", padding: "10px 15px", borderRadius: "3px", lineHeight: "24px", border: "0 !important", color: whiteColor + " !important", marginLeft: "4px", "&:last-child": { marginLeft: "0px" } }, tabSelected: { backgroundColor: "rgba(" + hexToRgb(whiteColor) + ", 0.2)", transition: "0.2s background-color 0.1s" }, tabWrapper: { display: "inline-block", minHeight: "unset !important", minWidth: "unset !important", width: "unset !important", height: "unset !important", maxWidth: "unset !important", maxHeight: "unset !important", fontWeight: "500", fontSize: "12px", marginTop: "1px", "& > svg,& > .material-icons": { verticalAlign: "middle", margin: "-1px 5px 0 0 !important" } } }; export default customTabsStyle;
/* Transitive closure (pointer chasing) in JavaScript. tc(list,start) The list is a graph where the indices points to the next node. tc(list,start) returns the transitive closure with start node <start>. This was inspired by K:s transitive closure function "over until fixed" (\) i.e. list\start (2 1 0 4 5 3)\4 4 5 3 which is here written as: tc([2,1,0,4,5,3],4] => [ 4, 5, 3 ] This JavaScript program was created by Hakan Kjellerstrand, [email protected] See also my JavaScript page: http://www.hakank.org/javascript_progs/ */ 'use strict'; const utils = require('./js_utils.js'); // // transitive closure on list a with start start // function tc(a,start) { let t = [start]; let next = a[t]; while (!t.includes(next)) { t.push(next); next = a[next]; } return t; } // // Show the transitive closure for all (unique) elements in a. // function tc_all(a) { console.log("a: " + a); const a2 = [...a].sort(); // sorted list let h = []; for(let s of a2) { if (!h[s]) { console.log(s + ": " + tc(a,s)); h[s]=1; } } } function test() { /* [ 'a: 1,2,3,4,0', 'start: 0' ] [ 0, 1, 2, 3, 4 ] [ 'a: 2,1,0,4,5,3', 'start: 4' ] [ 4, 5 ] [ 'a: 5,2,3,0,1,4', 'start: 5' ] [ 5, 4, 1, 2, 3, 0 ] */ const check = [ // list, start [[1,2,3,4,0],0], [[2,1,0,4,5,3],4], [[5,2,3,0,1,4],5], ]; for (const [a,start] of check) { console.log(["a: "+ a, "start: "+start]); console.log(tc(a,start)); console.log() } /* a: 5,2,3,0,1,4 0: 0,5,4,1,2,3 1: 1,2,3,0,5,4 2: 2,3,0,5,4,1 3: 3,0,5,4,1,2 4: 4,1,2,3,0,5 5: 5,4,1,2,3,0 */ tc_all([5,2,3,0,1,4]); console.log(); /* a: 2,1,0,4,5,4 0: 0,2 1: 1 2: 2,0 4: 4,5 4: 4,5 5: 5,4 */ tc_all([2,1,0,4,5,4]); } test();
/** * Progress Bar */ export * from './pageProgressBar'
ace.define("ace/snippets/javascript",["require","exports","module"], function(require, exports, module) { "use strict"; exports.snippetText = "# Tokens\n\ # Inputs\n\ snippet {input}\n\ {type: 'input', idx: ${1:idx}}\n\ snippet {dropdown}\n\ {type: 'dropdown', idx: ${1:idx}, options: [${2}], displayStatic: false}\n\ snippet {fractionInput}\n\ {type: 'fractionInput', idx: ${1:idx}}\n\ snippet {specificFractionInput}\n\ {type: 'specificFractionInput', idx: ${1:idx}}\n\ snippet {mixedFractionInput}\n\ {type: 'mixedFractionInput', idx: ${1:idx}}\n\ snippet {specificMixedFractionInput}\n\ {type: 'specificMixedFractionInput', idx: ${1:idx}}\n\ snippet {inputSelector}\n\ {type: 'inputSelector', idx: ${1:idx}}\n\ snippet {tileSlot}\n\ {type: 'tileSlot', idx: ${1:idx}}\n\ # Tables\n\ snippet {msTable}\n\ {\n\ type: 'msTable',\n\ rows: [\n\ [${1}]\n\ ],\n\ }\n\ snippet {msTableWithArrows}\n\ {\n\ type: 'msTable',\n\ rows: [\n\ [${1}]\n\ ],\n\ leftArrows: [ [] ],\n\ leftArrowLabels: [ [] ],\n\ rightArrows: [ [] ],\n\ rightArrowLabels: [ [] ]\n\ }\n\ # Hints\n\ snippet {hintPopup}\n\ {\n\ type: 'hintPopup',\n\ value: ['${1}'],\n\ position: '${2:top}'\n\ }\n\ # Fractions\n\ snippet {fraction}\n\ {type: 'fraction', numerator: ${1:1}, denominator: ${2:2}}\n\ snippet {fractionSmall}\n\ {type: 'fraction', numerator: ${1:1}, denominator: ${2:2}, cssClass: 'small'}\n\ snippet {fractionTrailer}\n\ {type: 'fraction', numerator: ${1:1}, denominator: ${2:2}, trailer: ''}\n\ snippet {reducedFraction}\n\ {type: 'reducedFraction', reduced: [${1}], text: '${2}', inputLocation: '${3:top-left}'}\n\ snippet {div}\n\ {type: 'div', cssClass: '${1}', inner: ['${2}']}\n\ # Other\n\ snippet {br}\n\ {type: 'br'}\n\ snippet {image}\n\ {type: 'image', value: '${1}', altText: '${2}'}\n\ snippet {listItem}\n\ {type: 'listItem', bulletLabel: '${1:โ€ข}', bulletText: '${2}'}\n\ # Helpers\n\ snippet TextHelper.metricUnitsToWords()\n\ TextHelper.metricUnitsToWords(${1:10}, ${2:'cm'}, ${3:true})\n\ snippet TextHelper.capitalize()\n\ TextHelper.capitalize(${1})\n\ snippet TextHelper.numToWords()\n\ TextHelper.numToWords(${1})\n\ snippet TextHelper.numToFractionName()\n\ TextHelper.numToFractionName(${1})\n\ snippet TextHelper.addCommas()\n\ TextHelper.addCommas(${1})\n\ snippet TextHelper.pluralize()\n\ TextHelper.pluralize(${1:'mouse'}, ${2:3})\n\ snippet TextHelper.tokensToString()\n\ TextHelper.tokensToString([${1}])\n\ snippet TextHelper.expandedForm()\n\ TextHelper.expandedForm(${1:12.34})\n\ snippet TextHelper.expandedFormMult()\n\ TextHelper.expandedFormMult(${1:12.34})\n\ snippet TextHelper.expandedFormFrac()\n\ TextHelper.expandedFormFrac(${1:12.34})\n\ # MathHelpers\n\ snippet MathHelper.digitsToNumber()\n\ MathHelper.digitsToNumber(${1:[7,2,4,5]}, ${2: 2})\n\ # Code Snippets\n\ snippet if\n\ if (${1:true}) {\n\ ${0}\n\ }\n\ snippet ifelse\n\ if (${1:true}) {\n\ ${2}\n\ } else {\n\ ${0}\n\ }\n\ snippet for\n\ for (let ${1:i} = 0; $1 < ${2:Things}.length; $1++) {\n\ ${3:$2[$1]}$0\n\ }\n\ "; exports.scope = "javascript"; }); (function() { ace.require(["ace/snippets/javascript"], function(m) { if (typeof module == "object" && typeof exports == "object" && module) { module.exports = m; } }); })();
text_array = [0x9257e4, 0x925852, 0x9258ce, 0x925be2, 0x925bfa, 0x925ca0, 0x925ccd, 0x925d0b, 0x925fa4, 0x9272bc, 0x9272da, 0x927354, 0x9273d5, 0x927406, 0x92743c, 0x927474, 0x927476, 0x9274b3, 0x9274b5, 0x9274ea, 0x9274ec, 0x927517, 0x927544, 0x927548, 0x927565, 0x927567, 0x9275d8, 0x9275ed, 0x92763f, 0x927648, 0x927678, 0x9276d8, 0x92772e, 0x927793, 0x92780a, 0x927870, 0x927b7c, 0x927b9e, 0x927c10, 0x927c4b, 0x927c91, 0x927cf1, 0x92c5e8, 0x92c650, 0x92c658, 0x92c6dc, 0x92c75e, 0x92c780, 0x92c798, 0x92c801, 0x92c840, 0x92c8c0, 0x92c904, 0x92c98b, 0x92c9d4, 0x92ca2a, 0x92ca78, 0x92cc24, 0x92cc45, 0x92cc5c, 0x92cc95, 0x92ccd6, 0x92cd24, 0x92cd54, 0x92cd95, 0x92cdd2, 0x92cdfe, 0x92cdff, 0x92ce09, 0x92ce0a, 0x92ce0c, 0x92ce44, 0x92cea2, 0x92cee8, 0x92cf45, 0x92cf70, 0x92cfac, 0x92cfb2, 0x92cff8, 0x92d000, 0x92d022, 0x92d084, 0x92d0c3, 0x92d0f0, 0x92d110, 0x92d178, 0x92d19b, 0x92d1d8, 0x92d217, 0x92d266, 0x92d27c, 0x92d2a5, 0x92d2dc, 0x92d31d, 0x92d344, 0x92d392, 0x92d3a8, 0x92d3c3, 0x92d418, 0x92d457, 0x92d494, 0x92d4d7, 0x92d514, 0x92d553, 0x92d590, 0x92d5d6, 0x92d63d, 0x92d6ba, 0x92d72e, 0x92d7a1, 0x92d809, 0x92d878, 0x92d8f2, 0x92d968, 0x92da2c, 0x92da2d, 0x92da35, 0x92da36, 0x92daad, 0x92db19, 0x92dbfa, 0x92dc87, 0x92dcab, 0x92dd58, 0x92dfb4, 0x92e24c, 0x92e2a2, 0x92e3a9, 0x92e467, 0x92e59c, 0x92e5c2, 0x92e60f, 0x92e690, 0x92e708, 0x92e728, 0x92e775, 0x92e815, 0x92e8ef, 0x92e9c6, 0x92ea60, 0x92ea80, 0x92eacd, 0x92eb04, 0x92eb23, 0x92eb66, 0x92ebcf, 0x92ec38, 0x92ed24, 0x92ed49, 0x92eda8, 0x92edcc, 0x92ee2d, 0x92eeb0, 0x92eed6, 0x92ef94, 0x92efbc, 0x92eff8, 0x92f021, 0x92f058, 0x92f082, 0x92f0bc, 0x92f0e6, 0x92f120, 0x92f149, 0x92f174, 0x92f19e, 0x92f1d4, 0x92f1f4, 0x92f270, 0x92f336, 0x92f3f9, 0x92f462, 0x92f572, 0x92f658, 0x92f761, 0x92f764, 0x92f78b, 0x92f7e0, 0x92f85b, 0x92f905, 0x92f989, 0x92fa73, 0x92fad0, 0x92faf4, 0x92fb48, 0x92fb67, 0x92fbc1, 0x92fc44, 0x92fcc1, 0x92fce0, 0x92fcff, 0x92fd38, 0x92fd58, 0x92fdb1, 0x92fe46, 0x92fe68, 0x92fe99, 0x92fecc, 0x92ff03, 0x92ff44, 0x92ff61, 0x92ff9c, 0x92ffbe, 0x930008, 0x930027, 0x930064, 0x93008a, 0x9300b4, 0x9300db, 0x93013c, 0x9301b4, 0x9301db, 0x930267, 0x9302a8, 0x9302ca, 0x930328, 0x930349, 0x9303a9, 0x930464, 0x93047f, 0x9304af, 0x930530, 0x93059c, 0x9305c1, 0x9306d1, 0x930718, 0x930740, 0x930784, 0x9307a8, 0x930803, 0x930899, 0x9308e6, 0x930929, 0x930a71, 0x930a74, 0x930a93, 0x930af8, 0x930b16, 0x930b75, 0x930bf0, 0x930c10, 0x930c6c, 0x930c9c, 0x930ccc, 0x930d00, 0x930d34, 0x930d68, 0x930d9c, 0x930dc1, 0x930e3b, 0x930ea4, 0x930ed7, 0x930f38, 0x930f6d, 0x930f96, 0x930fcd, 0x930fe4, 0x931009, 0x931068, 0x93108e, 0x9310d0, 0x9310f5, 0x931184, 0x931196, 0x9311ba, 0x9311d8, 0x9311fd, 0x931234, 0x931264, 0x93129a, 0x9312cc, 0x931304, 0x931387, 0x9313b9, 0x9313d0, 0x931422, 0x931424, 0x93147b, 0x93149a, 0x9314c9, 0x9314f8, 0x93152b, 0x931591, 0x9315b8, 0x9315f4, 0x93170c, 0x93172c, 0x931784, 0x9317a0, 0x9317f5, 0x931883, 0x931973, 0x9319dd, 0x931a4c, 0x931ad5, 0x931b52, 0x931bde, 0x931be4, 0x931c05, 0x931c5a, 0x931d3a, 0x931d9c, 0x931da0, 0x931de9, 0x931dec, 0x931e3d, 0x931ec4, 0x931f28, 0x931f92, 0x931fe7, 0x931fec, 0x932007, 0x932054, 0x932072, 0x9320be, 0x932126, 0x93219c, 0x9321b9, 0x932281, 0x932308, 0x932380, 0x9323d1, 0x932490, 0x932510, 0x93252c, 0x9325ad, 0x9325c7, 0x932649, 0x9326bc, 0x9326f1, 0x932737, 0x932747, 0x9327c1, 0x9327e4, 0x932868, 0x9328e8, 0x932968, 0x9329dd, 0x932a5c, 0x932ada, 0x932b35, 0x932bd1, 0x932c06, 0x932c08, 0x932c29, 0x932c7c, 0x932c9d, 0x932d2e, 0x932d43, 0x932d48, 0x932d6c, 0x932d90, 0x932db8, 0x932de0, 0x932e08, 0x932e30, 0x932e5b, 0x932e8a, 0x932e9c, 0x932ec8, 0x932ef5, 0x932f08, 0x932f35, 0x932f66, 0x932ffa, 0x933049, 0x933089, 0x93308b, 0x9330e8, 0x933193, 0x933231, 0x933314, 0x933337, 0x93333c, 0x933363, 0x933368, 0x933389, 0x93338c, 0x933401, 0x933440, 0x9334ac, 0x9334d8, 0x93352c, 0x933590, 0x9335bb, 0x93361f, 0x933624, 0x93366c, 0x9336d4, 0x933793, 0x9337cd, 0x933821, 0x93383e, 0x9338e1, 0x93392b, 0x933997, 0x9339e3, 0x933a15, 0x933a8a, 0x933b1e, 0x933bae, 0x933c3a, 0x933d44, 0x933d8c, 0x933df4, 0x933e40, 0x933eac, 0x933ef8, 0x933f40, 0x933f80, 0x933ffd, 0x93408c, 0x93411c, 0x93418c, 0x93420c, 0x93425c, 0x934314, 0x934343, 0x93437c, 0x9343d0, 0x93444c, 0x93449a, 0x93452c, 0x934570, 0x9345b0, 0x9345e8, 0x934634, 0x934672, 0x934704, 0x93475c, 0x9347b4, 0x934818, 0x934870, 0x9348bc, 0x934908, 0x934980, 0x934a08, 0x934a34, 0x934a8c, 0x934a9c, 0x935ca8, 0x935cd2, 0x935d08, 0x935d30, 0x935d84, 0x935dec, 0x935e3c, 0x935e74, 0x935edc, 0x935f30, 0x935f88, 0x935fbc, 0x935fe4, 0x93602c, 0x93605c, 0x9360b4, 0x9360e8, 0x936108, 0x936188, 0x9361c0, 0x93621c, 0x936260, 0x93628c, 0x936432, 0x9365d6, 0x9365ff, 0x93664f, 0x9366b8, 0x9366e9, 0x9368b7, 0x936a29, 0x936aa7, 0x936b13, 0x936bac, 0x936bb7, 0x936dbd, 0x936e2b, 0x936e8c, 0x936eba, 0x936ef4, 0x936f26, 0x936f5f, 0x936fc4, 0x936ffd, 0x937041, 0x937043, 0x937044, 0x937056, 0x937057, 0x9371b0, 0x9371f5, 0x937237, 0x937296, 0x937318, 0x9373a1, 0x9376cf, 0x937748, 0x937767, 0x937785, 0x9377a1, 0x9377b3, 0x9377f7, 0x93781d, 0x937854, 0x937894, 0x9378b3, 0x9378f1, 0x93791a, 0x937965, 0x9379c8, 0x9379e0, 0x937a2d, 0x937a83, 0x937add, 0x937af5, 0x937b25, 0x937b3c, 0x937b55, 0x937b80, 0x937ba8, 0x937bbd, 0x937c33, 0x937c4c, 0x937cad, 0x937cf6, 0x937d61, 0x937d78, 0x937daf, 0x937dc0, 0x937df9, 0x937e66, 0x937ea4, 0x937efd, 0x937f74, 0x937fd5, 0x938046, 0x93808f, 0x9380e6, 0x93815d, 0x9381b8, 0x938217, 0x93825a, 0x9382a6, 0x9382e0, 0x938322, 0x938376, 0x9383a7, 0x9383e4, 0x938414, 0x93843e, 0x9384a4, 0x938534, 0x9385b5, 0x9385ea, 0x93866f, 0x9386a1, 0x938736, 0x938760, 0x9387a6, 0x9387ea, 0x93881f, 0x938848, 0x93885d, 0x938874, 0x9388e2, 0x938945, 0x9389a0, 0x9389f2, 0x938a6b, 0x938ae1, 0x938b1b, 0x938b56, 0x938bb5, 0x938c18, 0x938c95, 0x938d1d, 0x938d5d, 0x938d73, 0x938dbb, 0x938e2b, 0x9399f5, 0x939a64, 0x939aa9, 0x939ae3, 0x939b1c, 0x939b58, 0x939b8c, 0x939c00, 0x939c78, 0x939cc6, 0x939d2f, 0x939db1, 0x939e00, 0x939e5c, 0x939eaf, 0x939f03, 0x939f78, 0x939fe6, 0x93a019, 0x93a087, 0x93a103, 0x93a148, 0x93a180, 0x93a1b9, 0x93a1ed, 0x93a286, 0x93a2ef, 0x93a338, 0x93a367, 0x93a3aa, 0x93a3da, 0x93a44f, 0x93a4bc, 0x93a4fe, 0x93a56b, 0x93a5af, 0x93a626, 0x93a645, 0x93a688, 0x93a6be, 0x93a729, 0x93a783, 0x93a788, 0x93a7f2, 0x93a851, 0x93a89a, 0x93a8de, 0x93a94c, 0x93a99f, 0x93aa16, 0x93aa8a, 0x93aad3, 0x93ab37, 0x93abab, 0x93ac1d, 0x93ac88, 0x93acb4, 0x93ad12, 0x93ad5f, 0x93ad9c, 0x93ae14, 0x93ae84, 0x93aef8, 0x93af30, 0x93af8d, 0x93afd7, 0x93b01c, 0x93b068, 0x93b0a5, 0x93b0d4, 0x93b106, 0x93b17f, 0x93b1c8, 0x93b215, 0x93b28c, 0x93b31c, 0x93b362, 0x93b3a4, 0x93b3e7, 0x93b44c, 0x93b49b, 0x93b4d3, 0x93b545, 0x93b576, 0x93b59b, 0x93b5fe, 0x93b666, 0x93b6c8, 0x93b97b, 0x93b99c, 0x93b9d4, 0x93b9fc, 0x93ba2d, 0x93ba57, 0x93ba88, 0x93bac2, 0x93baec, 0x93bb19, 0x93bb47, 0x93bb74, 0x93bba2, 0x93bbc6, 0x93bbea, 0x93bc11, 0x93bc38, 0x93bc62, 0x93bc8c, 0x93bcba, 0x93bcbc, 0x93bcee, 0x93bd48, 0x93bd5c, 0x93bd6c, 0x93be60, 0x93be91, 0x93be98, 0x93bed7, 0x93bf01, 0x93c1f4, 0x93c278, 0x93c2b9, 0x93c3a0, 0x93c3cb, 0x93c405, 0x93c558, 0x93c57e, 0x93c5a0, 0x93c5bc, 0x93c5d4, 0x93c5f8, 0x93c630, 0x93c668, 0x93c680, 0x93c6c0, 0x93c760, 0x93c785, 0x93c796, 0x93c7df, 0x93c831, 0x93c8ac, 0x93c8ca, 0x93c998, 0x93c9c6, 0x93c9ee, 0x93cb80, 0x93cb8e, 0x93cba4, 0x93cbd1, 0x93cc5d, 0x93ccb7, 0x93cced, 0x93ce0c, 0x93ce66, 0x93d040, 0x93d184, 0x93d2e9, 0x93d2ec, 0x93d34e, 0x93d3b1, 0x93d3fa, 0x93d424, 0x93d48a, 0x93d4a9, 0x93d4c6, 0x93d503, 0x93d524, 0x93d55f, 0x93d592, 0x93d593, 0x93d594, 0x93d5ac, 0x93d5ad, 0x93d5af, 0x93d5b0, 0x93d5be, 0x93d5bf, 0x93d5c4, 0x93d5e8, 0x93d5e9, 0x93d5ea, 0x93d5fa, 0x93d5fb, 0x93d654, 0x93d6a1, 0x93d73c, 0x93d749, 0x93d74b, 0x93d7f0, 0x93e6c4, 0x93e6df, 0x93e705, 0x93e74a, 0x93e770, 0x93e9b8, 0x93e9fb, 0x93ed0c, 0x93ed5d, 0x93edb9, 0x93ee34, 0x93ee59, 0x93eeac, 0x93ef00, 0x93efd8, 0x93f060, 0x93f08a, 0x93f0e5, 0x93f0f4, 0x93f159, 0x93f1b4, 0x93f1e7, 0x93f247, 0x93f4e0, 0x93f523, 0x93f575, 0x93f5a9, 0x93f5f8, 0x93f609, 0x93f648, 0x93f656, 0x93f6cc, 0x93f740, 0x93f77a, 0x93f7ac, 0x93f7dc, 0x93f849, 0x93f88f, 0x93f8d4, 0x93f934, 0x93f94c, 0x93f95b, 0x93f97a, 0x93f9a3, 0x93f9f9, 0x93fa02, 0x93fa03, 0x93fa1e, 0x93fa1f, 0x93fd1c, 0x93fd48, 0x93fdc5, 0x93fe82, 0x93fecf, 0x93fef3, 0x93ff1a, 0x93ff44, 0x93ff51, 0x93ffaf, 0x93ffbf, 0x940014, 0x940024, 0x940074, 0x9400cb, 0x94012c, 0x940188, 0x9401d7, 0x9402ec, 0x94032b, 0x94035a, 0x9403a0, 0x9403d5, 0x940400, 0x94042f, 0x9404b0, 0x9404d1, 0x94050e, 0x940570, 0x9405b0, 0x9405ec, 0x9405fb, 0x940609, 0x940645, 0x94064c, 0x94065e, 0x940662, 0x9406fc, 0x94074c, 0x940784, 0x9407d6, 0x94081e, 0x940868, 0x9408f9, 0x940943, 0x940999, 0x9409ec, 0x940a2d, 0x940a4c, 0x940a98, 0x940b01, 0x940b5c, 0x940b6f, 0x940b70, 0x940b7c, 0x940b7d, 0x940b9f, 0x940ba1, 0x940bc4, 0x940bf6, 0x940bf8, 0x940c48, 0x940cb6, 0x940cdb, 0x940f7a, 0x940f87, 0x941012, 0x941018, 0x941037, 0x941082, 0x9410d2, 0x941168, 0x9411b0, 0x9411d8, 0x9411ec, 0x9412a4, 0x9412e3, 0x9413d0, 0x941411, 0x941421, 0x941422, 0x941423, 0x94142b, 0x94142c, 0x94144e, 0x94145e, 0x94147d, 0x941535, 0x94156b, 0x9415f4, 0x941612, 0x941644, 0x941758, 0x941804, 0x94184c, 0x9418a0, 0x9418bb, 0x941a28, 0x941a71, 0x941ac8, 0x941ad3, 0x941afe, 0x941b30, 0x941cb8, 0x941d30, 0x941d74, 0x941d98, 0x941dd8, 0x942078, 0x9420d0, 0x9420de, 0x942114, 0x942129, 0x942162, 0x942210, 0x942225, 0x942248, 0x94225b, 0x94227b, 0x94228c, 0x9423b3, 0x9427b8, 0x94280d, 0x94280e, 0x94280f, 0x942818, 0x942819, 0x94281b, 0x942827, 0x94283f, 0x94288f, 0x9428cc, 0x9428fa, 0x942961, 0x9429b1, 0x942a08, 0x942a35, 0x942afc, 0x942e9c, 0x942f04, 0x942f40, 0x942f47, 0x942f9c, 0x943070, 0x9430a1, 0x9430a8, 0x9430c1, 0x9430fe, 0x943210, 0x94326f, 0x9432b7, 0x943306, 0x943349, 0x94334a, 0x94334f, 0x943355, 0x94335a, 0x94335f, 0x943366, 0x943367, 0x943368, 0x943399, 0x94339a, 0x94339f, 0x9433a4, 0x9433a9, 0x9433af, 0x9433b0, 0x9433b1, 0x9434b0, 0x9434c9, 0x94353e, 0x9435b2, 0x9435f5, 0x943634, 0x9436bb, 0x943736, 0x94378a, 0x943802, 0x94382e, 0x9438c0, 0x9438cc, 0x9438dc, 0x9438ff, 0x943904, 0x943907, 0x943908, 0x94390d, 0x943913, 0x943919, 0x94391d, 0x94391e, 0x943964, 0x94397d, 0x9439b0, 0x9439ea, 0x9439ec, 0x943a52, 0x943ae0, 0x943b2f, 0x943c67, 0x943dd8, 0x943e34, 0x944128, 0x944192, 0x9441dc, 0x944228, 0x94428a, 0x9442a2, 0x9442a4, 0x944304, 0x944347, 0x9443a0, 0x9443ea, 0x9448ec, 0x9448fb, 0x9448fd, 0x94496c, 0x94498c, 0x9449bc, 0x9449f4, 0x944a60, 0x944a6f, 0x944a9e, 0x944aac, 0x944b70, 0x944bb4, 0x944bd9, 0x944c25, 0x944c7b, 0x944cd4, 0x944d27, 0x944d28, 0x944d29, 0x944d33, 0x944d34, 0x944d3e, 0x944dec, 0x944e38, 0x944ea0, 0x944eda, 0x944f88, 0x944fd9, 0x94507c, 0x9450fa, 0x945135, 0x945170, 0x945258, 0x945259, 0x945277, 0x945278, 0x9454b4, 0x9454b5, 0x9454cf, 0x9454d0, 0x945508, 0x9455c4, 0x9455ee, 0x94562d, 0x94566f, 0x945ad8, 0x945b1c, 0x945b64, 0x945bd1, 0x945c24, 0x945c96, 0x945cdf, 0x945d4c, 0x945d57, 0x945d6d, 0x945dbb, 0x945ff4, 0x946030, 0x946044, 0x9461d0, 0x9462ca, 0x94631c, 0x946488, 0x946658, 0x946670, 0x946688, 0x946689, 0x94668a, 0x946690, 0x946691, 0x946693, 0x94669d, 0x9466cc, 0x9466db, 0x9467a4, 0x9467d2, 0x946870, 0x946871, 0x946872, 0x94687b, 0x94687c, 0x946882, 0x9468a6, 0x9468d7, 0x946908, 0x946963, 0x94698e, 0x9469cc, 0x946a08, 0x946a35, 0x946a87, 0x946ab8, 0x946b00, 0x946b50, 0x946b7c, 0x946b83, 0x946bec, 0x946c2f, 0x946c96, 0x946cd4, 0x946d1e, 0x947274, 0x9472e2, 0x94735e, 0x947672, 0x94768a, 0x947730, 0x94775d, 0x94779b, 0x947a34, 0x947ab0, 0x947ba4, 0x947bb6, 0x947be5, 0x947c92, 0x947cb2, 0x947cbd, 0x947cec, 0x947cfa, 0x947cfc, 0x947d4d, 0x947d74, 0x947de0, 0x947e45, 0x947f0e, 0x948354, 0x948359, 0x948396, 0x9483a3, 0x9483b7, 0x9483bc, 0x9483ed, 0x948445, 0x94847a, 0x948628, 0x9486a0, 0x9486b9, 0x948728, 0x94876f, 0x948796, 0x94881b, 0x9488bc, 0x9488c2, 0x948914, 0x948974, 0x948997, 0x948a0e, 0x948a93, 0x948ab6, 0x948b64, 0x948b9f, 0x948bca, 0x948c22, 0x948c36, 0x948d4c, 0x948d6a, 0x948de4, 0x948e65, 0x948e96, 0x948ecc, 0x948f04, 0x948f06, 0x948f43, 0x948f45, 0x948f7a, 0x948f7c, 0x948fa7, 0x948fd4, 0x948fd8, 0x948ff5, 0x948ff7, 0x949068, 0x94907d, 0x9490cf, 0x9490d8, 0x949108, 0x949168, 0x9491be, 0x949223, 0x94929a, 0x949300, 0x94960c, 0x94962e, 0x9496a0, 0x9496db, 0x949721, 0x949781, 0x949ce8, 0x949d27, 0x949d42, 0x949d64, 0x949d6b, 0x949d81, 0x949dbe, 0x949ded, 0x949e22, 0x949e47, 0x949e82, 0x949ed0, 0x949ed7, 0x949f22, 0x949f65, 0x94a068, 0x94a0bf, 0x94a0eb, 0x94a122, 0x94a16f, 0x94a1a8, 0x94a1d8, 0x94a228, 0x94a254, 0x94a285, 0x94a2e3, 0x94a32b, 0x94a36c, 0x94a3ae, 0x94a3cf, 0x94a425, 0x94a49c, 0x94a4be, 0x94a4d3, 0x94a4fe, 0x94a542, 0x94a5ab, 0x94a623, 0x94a68c, 0x94a6c5, 0x94a720, 0x94a756, 0x94a798, 0x94a810, 0x94a84c, 0x94a860, 0x94a8c7, 0x94a940, 0x94a9bc, 0x94aa32, 0x94aa8c, 0x94aade, 0x94aae4, 0x94ab09, 0x94abb0, 0x94ac02, 0x94ac49, 0x94ac8c, 0x94ad44, 0x94ad80, 0x94adcd, 0x94adf6, 0x94ae44, 0x94ae9b, 0x94b21c, 0x94b24e, 0x94b276, 0x94b2c4, 0x94b440, 0x94b4a8, 0x94b4c0, 0x94b4f2, 0x94b671, 0x94b6a5, 0x94b6fd, 0x94b704, 0x94b76e, 0x94b7f1, 0x94b85f, 0x94b8e3, 0x94bbd0, 0x94bc18, 0x94bc63, 0x94bcbb, 0x94bce8, 0x94bd0f, 0x94bd8d, 0x94bdd4, 0x94be0c, 0x94be7c, 0x94be9b, 0x94bf15, 0x94bf74, 0x94bf9b, 0x94c020, 0x94c047, 0x94c0a4, 0x94c0cb, 0x94c13e, 0x94c180, 0x94c1a7, 0x94c1eb, 0x94c240, 0x94c260, 0x94c320, 0x94c3a0, 0x94c3e4, 0x94c45c, 0x94c475, 0x94c4cc, 0x94c50c, 0x94c542, 0x94c57a, 0x94c604, 0x94c680, 0x94c6d2, 0x94c788, 0x94c791, 0x94c7e2, 0x94c847, 0x94c849, 0x94c86b, 0x94c870, 0x94c87e, 0x94c8af, 0x94c9b4, 0x94cca4, 0x94ce04, 0x94ce21, 0x94ce4d, 0x94ce87, 0x94cf58, 0x94cf94, 0x94cfe7, 0x94d04d, 0x94d124, 0x94d131, 0x94d180, 0x94d1c0, 0x94d2e9, 0x94d2eb, 0x94d38c, 0x94d3bd, 0x94d404, 0x94d452, 0x94d4c2, 0x94d538, 0x94d61e, 0x94d635, 0x94d638, 0x94d67c, 0x94d6db, 0x94d71a, 0x94d770, 0x94d860, 0x94d874, 0x94d88d, 0x94d89f, 0x94d8a1, 0x94d8d4, 0x94d8e5, 0x94d8f1, 0x94d904, 0x94d90c, 0x94d912, 0x94d962, 0x94d964, 0x94d99e, 0x94d9f8, 0x94da44, 0x94dacf, 0x94dadd, 0x94dadf, 0x94db38, 0x94db54, 0x94dd0c, 0x94dd67, 0x94ddb1, 0x94de14, 0x94de21, 0x94de88, 0x94ded4, 0x94df17, 0x94df85, 0x94dfe9, 0x94e078, 0x94e0e0, 0x94e0e8, 0x94e16c, 0x94e1ee, 0x94e210, 0x94e228, 0x94e291, 0x94e2d0, 0x94e350, 0x94e394, 0x94e41b, 0x94e464, 0x94e4ba, 0x94e508, 0x94e6b4, 0x94e6d5, 0x94e6ec, 0x94e725, 0x94e766, 0x94e7b4, 0x94e7e4, 0x94e825, 0x94e862, 0x94e88e, 0x94e88f, 0x94e899, 0x94e89a, 0x94e89c, 0x94e8d4, 0x94e932, 0x94e978, 0x94e9d5, 0x94ea00, 0x94ea3c, 0x94ea42, 0x94ea88, 0x94ead8, 0x94eb10, 0x94eb2c, 0x94eb37, 0x94ebbc, 0x94ebec, 0x94ec38, 0x94ecb0, 0x94ecb4, 0x94ecf3, 0x94ed2d, 0x94ed54, 0x94ede0, 0x94edf4, 0x94ee1b, 0x94ee23, 0x94ee62, 0x94ee6d, 0x94ee8e, 0x94eeb5, 0x94eed2, 0x94eef2, 0x94ef01, 0x94ef03, 0x94ef43, 0x94ef52, 0x94ef54, 0x94ef8f, 0x94efe1, 0x94f00b, 0x94f048, 0x94f097, 0x94f0a3, 0x94f0b6, 0x94f0c5, 0x94f0c8, 0x94f0e7, 0x94f117, 0x94f120, 0x94f18b, 0x94f1e4, 0x94f1f0, 0x94f23c, 0x94f269, 0x94f26b, 0x94f26c, 0x94f270, 0x94f271, 0x94f288, 0x94f2c2, 0x94f2f9, 0x94f358, 0x94f3f8, 0x94f4a0, 0x94f4b8, 0x94f4f4, 0x94f522, 0x94f57c, 0x94f5c8, 0x94f600, 0x94f614, 0x94f652, 0x94f6a9, 0x94f72c, 0x94f730, 0x94f7c0, 0x94f850, 0x94f8e8, 0x94f960, 0x94fa04, 0x94fab4, 0x94fb4c, 0x94fbe0, 0x94fc8c, 0x9501ac, 0x950b16, 0x950d6e, 0x950dae, 0x950dc9, 0x950e80, 0x950eb5, 0x950f09, 0x950f4b, 0x950f67, 0x950f82, 0x95157c, 0x951f93, 0x952185, 0x952280, 0x952282, 0x952283, 0x952288, 0x952291, 0x952298, 0x952299, 0x95229a, 0x95241b, 0x9524d2, 0x9524f1, 0x952511, 0x9525cc, 0x952611, 0x952613, 0x952637, 0x952639, 0x952665, 0x952667, 0x9526ec, 0x9526f0, 0x95271d, 0x952804, 0x95280e, 0x95280f, 0x952814, 0x95281d, 0x952825, 0x952826, 0x952827, 0x952836, 0x952838, 0x952870, 0x9528b5, 0x952bb0, 0x952bba, 0x952bbc, 0x952bbd, 0x952bc2, 0x952bc9, 0x952bcd, 0x952bd4, 0x952bd5, 0x952bd6, 0x952be9, 0x952c19, 0x952c86, 0x952ce7, 0x952d12, 0x952d5f, 0x952db3, 0x952df4, 0x952dfe, 0x952e00, 0x952e01, 0x952e06, 0x952e0d, 0x952e11, 0x952e18, 0x952e19, 0x952e1a, 0x952e2d, 0x952e58, 0x9531a0, 0x9531aa, 0x9531d0, 0x95321f, 0x953259, 0x95329c, 0x953360, 0x953370, 0x9533c4, 0x95342f, 0x95349c, 0x95350a, 0x953543, 0x95355e, 0x953560, 0x9535be, 0x9535c4, 0x95360e, 0x953688, 0x9536b0, 0x9536be, 0x95373b, 0x953783, 0x9537c4, 0x95382b, 0x95389a, 0x953917, 0x953952, 0x9539a6, 0x9539d8, 0x953a30, 0x953ac0, 0x953b2e, 0x953b81, 0x953bea, 0x953c38, 0x953d68, 0x953da8, 0x953dfb, 0x953e58, 0x953ea9, 0x953ef8, 0x953f76, 0x953fc3, 0x95406c, 0x954090, 0x954104, 0x954154, 0x9541ac, 0x954210, 0x954490, 0x9544b0, 0x9544c0, 0x9544f0, 0x954730, 0x95478d, 0x954860, 0x9548d1, 0x954938, 0x95496c, 0x9549a1, 0x9549d7, 0x954a10, 0x954bac, 0x954bfe, 0x954c59, 0x954ccb, 0x954fdb, 0x954fdc, 0x954fe2, 0x954fe3, 0x95503c, 0x955099, 0x9552f0, 0x95536c, 0x9553e2, 0x9553ee, 0x955437, 0x95548c, 0x9554ff, 0x955568, 0x9555dd, 0x9555e9, 0x95562a, 0x955682, 0x9556cc, 0x955727, 0x955733, 0x95580c, 0x95584a, 0x95590c, 0x955a20, 0x955a70, 0x955ad4, 0x955b4f, 0x955bb8, 0x955c90, 0x955cd5, 0x955d34, 0x9560b0, 0x9560c3, 0x956159, 0x9561c2, 0x9563f4, 0x956448, 0x956c94, 0x956ede, 0x956f4a, 0x956f4c, 0x956faa, 0x95702d, 0x957077, 0x9570ce, 0x957121, 0x957177, 0x957290, 0x9572b0, 0x957322, 0x957361, 0x9573a0, 0x9573e2, 0x9573e3, 0x9573eb, 0x9573f2, 0x9573f7, 0x9573f8, 0x9573fa, 0x957400, 0x95740d, 0x95742b, 0x95744e, 0x95746d, 0x9574f8, 0x957512, 0x957577, 0x9575ab, 0x957618, 0x9577b0, 0x95798a, 0x95798c, 0x95799a, 0x9579de, 0x957b70, 0x957c90, 0x957d60, 0x957da9, 0x957e40, 0x957e7b, 0x957eb8, 0x957edc, 0x957ee5, 0x957f10, 0x957f6f, 0x957f88, 0x957fce, 0x958021, 0x95809d, 0x958111, 0x958137, 0x95813c, 0x95816c, 0x95818a, 0x9581d0, 0x95823f, 0x95828c, 0x95830f, 0x958355, 0x95839e, 0x95841c, 0x95842a, 0x958514, 0x958534, 0x958564, 0x95858c, 0x9585e4, 0x958624, 0x95863c, 0x958664, 0x958690, 0x9586ac, 0x9586e8, 0x958744, 0x9587a0, 0x9587d4, 0x9587ec, 0x9588bc, 0x958920, 0x958934, 0x958943, 0x95895a, 0x9589af, 0x958a07, 0x958a4d, 0x958a84, 0x958a8c, 0x958aa8, 0x958af9, 0x958b04, 0x958b11, 0x958b20, 0x958b34, 0x958b50, 0x958b56, 0x958b70, 0x9592da, 0x9592fd, 0x959350, 0x95937d, 0x959392, 0x9593ad, 0x9593d4, 0x9593ed, 0x959408, 0x95942b, 0x959453, 0x959469, 0x959475, 0x959483, 0x95948e, 0x9594a1, 0x9594a8, 0x9594fd, 0x959575, 0x9595b0, 0x959608, 0x95965b, 0x9596a5, 0x95972c, 0x95976c, 0x9597d2, 0x9597d4, 0x959818, 0x95987d, 0x9598f0, 0x95997f, 0x959ad0, 0x959be4, 0x959df8, 0x959e47, 0x959e7b, 0x95a024, 0x95a042, 0x95a141, 0x95a537, 0x95a538, 0x95a545, 0x95a546, 0x95a5b8, 0x95a5e1, 0x95a62d, 0x95a697, 0x95a7f4, 0x95a828, 0x95a88a, 0x95a8b5, 0x95a90c, 0x95aa59, 0x95aa5a, 0x95aa64, 0x95aa65, 0x95ab99, 0x95ab9a, 0x95aba4, 0x95aba5, 0x95ac6b, 0x95ac70, 0x95ac71, 0x95ac7a, 0x95ac83, 0x95ac8c, 0x95ac8d, 0x95ac8e, 0x95ad65, 0x95b15c, 0x95b16b, 0x95b1eb, 0x95b1f0, 0x95b21f, 0x95b264, 0x95b2a5, 0x95b2fe, 0x95b33a, 0x95b3af, 0x95b3d7, 0x95b3d8, 0x95b3df, 0x95b3ea, 0x95b3f2, 0x95b3f7, 0x95b3fc, 0x95b408, 0x95b409, 0x95b428, 0x95b452, 0x95b4b2, 0x95b4fc, 0x95b608, 0x95ba74, 0x95ba9f, 0x95bb8c, 0x95bbb1, 0x95bbca, 0x95bbe4, 0x95bc9b, 0x95bce4, 0x95bcf4, 0x95bcf6, 0x95bd3c, 0x95bd46, 0x95bd48, 0x95bd78, 0x95bde0, 0x95be9c, 0x95beba, 0x95bf78, 0x95bf90, 0x95c028, 0x95c1b0, 0x95c1e1, 0x95c219, 0x95c26d, 0x95c2bf, 0x95c39c, 0x95c3af, 0x95c450, 0x95c466, 0x95c468, 0x95c49c, 0x95c4ba, 0x95c4ec, 0x95c552, 0x95c59a, 0x95c5d1, 0x95c621, 0x95c624, 0x95c62a, 0x95c633, 0x95c638, 0x95c648, 0x95c700, 0x95c774, 0x95c794, 0x95c7fb, 0x95c84f, 0x95c8bd, 0x95c93e, 0x95cb5c, 0x95cb6c, 0x95cb7e, 0x95cb8c, 0x95cbc4, 0x95cbec, 0x95ce2c, 0x95d164, 0x95d16c, 0x95d194, 0x95d1c1, 0x95d226, 0x95d26c, 0x95d2ed, 0x95d374, 0x95d3a4, 0x95d3e4, 0x95d42c, 0x95d48f, 0x95d4c8, 0x95d502, 0x95d5f0, 0x95d602, 0x95d63f, 0x95d69a, 0x95d705, 0x95d784, 0x95d7cb, 0x95d7eb, 0x95d807, 0x95d828, 0x95d85c, 0x95d8af, 0x95d8d8, 0x95d926, 0x95d955, 0x95d9bc, 0x95da15, 0x95da77, 0x95dadc, 0x95db0c, 0x95db94, 0x95dbb1, 0x95dbd0, 0x95dbee, 0x95dc17, 0x95dc40, 0x95dcb5, 0x95dd4c, 0x95dd8c, 0x95ddb0, 0x95ddc8, 0x95de03, 0x95de5c, 0x95de98, 0x95df10, 0x95df9d, 0x95e016, 0x95e0a8, 0x95e126, 0x95e1ac, 0x95e200, 0x95e288, 0x95e309, 0x95e34c, 0x95e38c, 0x95e3c5, 0x95e40c, 0x95e43c, 0x95e500, 0x95e575, 0x95e5a4, 0x95e5c8, 0x95e5f0, 0x95e630, 0x95e664, 0x95e690, 0x95e6e9, 0x95e747, 0x95e828, 0x95e868, 0x95e8d0, 0x95e8e1, 0x95e922, 0x95e964, 0x95e97c, 0x95ea58, 0x95eaad, 0x95eae2, 0x95eb2f, 0x95eb7c, 0x95ebc3, 0x95ebea, 0x95ec70, 0x95eca0, 0x95ed1c, 0x95ed94, 0x95ee06, 0x95ee6c, 0x95eec0, 0x95ef12, 0x95ef8c, 0x95efd5, 0x95f030, 0x95f098, 0x95f118, 0x95f1a4, 0x95f1e8, 0x95f248, 0x95f2d1, 0x95f34e, 0x95f3b0, 0x95f404, 0x95f45c, 0x95f4d4, 0x95f531, 0x95f59e, 0x95f5c4, 0x95f620, 0x95f668, 0x95f6c4, 0x95f71d, 0x95f7ae, 0x95f890, 0x95f8f4, 0x95f934, 0x95f9ab, 0x95f9fc, 0x95fafe, 0x95fb04, 0x95fb5b, 0x95fbb2, 0x95fbf3, 0x95fc4a, 0x95fc76, 0x95fc90, 0x95fcca, 0x95fd2c, 0x95fd49, 0x95fd7f, 0x95fdc8, 0x95fe0c, 0x95fe2a, 0x95fe68, 0x95fe89, 0x95feb8, 0x95fee1, 0x95ff36, 0x95ff3d, 0x9601b6, 0x96020f, 0x9604c1, 0x960733, 0x96075d, 0x9607dc, 0x96080f, 0x960864, 0x9608b6, 0x9608c8, 0x9609ed, 0x960b14, 0x960b4f, 0x960b8b, 0x960bd2, 0x960c15, 0x960c4e, 0x960c8a, 0x960cd1, 0x960d10, 0x960d62, 0x960dc6, 0x960e28, 0x960e82, 0x960eb3, 0x960ef0, 0x960f2c, 0x960f67, 0x960fa3, 0x960fde, 0x961018, 0x961056, 0x9611ec, 0x961238, 0x961289, 0x9612c0, 0x961300, 0x961324, 0x96134c, 0x96139e, 0x9613b4, 0x9613ec, 0x9613f4, 0x961410, 0x961468, 0x961499, 0x961508, 0x96151c, 0x961540, 0x961580, 0x961598, 0x9615f3, 0x9615f8, 0x961623, 0x961628, 0x961684, 0x96169c, 0x9616a0, 0x9616a1, 0x9616a2, 0x9616a9, 0x9616aa, 0x9616b0, 0x9616b1, 0x9616b2, 0x9616c6, 0x9616c7, 0x9616db, 0x9616dc, 0x9616e0, 0x9616f0, 0x9616f4, 0x96171e, 0x961754, 0x96178c, 0x96178d, 0x961794, 0x961795, 0x96195d, 0x961960, 0x961c54, 0x961ca0, 0x961cc9, 0x961d06, 0x961d5d, 0x961d8c, 0x961deb, 0x961e1d, 0x961e9f, 0x961f80, 0x961f9e, 0x961f9f, 0x961fa0, 0x961fa9, 0x961faa, 0x961fac, 0x961fb5, 0x961fd4, 0x961ffd, 0x962008, 0x962026, 0x96202e, 0x962058, 0x9620ae, 0x9620f0, 0x962105, 0x962128, 0x962158, 0x96218b, 0x9621f6, 0x962252, 0x962284, 0x962296, 0x962297, 0x962298, 0x96229c, 0x9622a3, 0x9622a7, 0x9622a8, 0x9622b8, 0x9622bc, 0x9622e8, 0x96236c, 0x9623c7, 0x962428, 0x96248c, 0x9624d6, 0x962500, 0x962512, 0x962564, 0x962662, 0x962753, 0x962812, 0x9629c3, 0x962cf8, 0x962d42, 0x962d61, 0x96508a, 0x9650b8, 0x9602EB]
import chess import random from utils.score_basic import evaluate def scoreboard(board, depthleft, maximising_player): """ https://youtu.be/l-hh51ncgDI """ if depthleft == 0: # Return end leaf score = evaluate(board) return_score = score if maximising_player else -score return return_score if maximising_player: max_eval = -999999 for move in board.legal_moves: # Get score for each possible move board.push(move) # Recurssive depth-first search. This will follow one path down the # search tree until depthleft == 0. score = scoreboard(board, depthleft - 1, maximising_player=False ) # Restore the previous position. board.pop() # Record new best score if discovered if score > max_eval: max_eval = score # Return best score from the starting position given to alphabeta search return max_eval else: min_eval = 999999 for move in board.legal_moves: # Get score for each possible move board.push(move) # Recurssive depth-first search. This will follow one path down the # search tree until depthleft == 0. score = scoreboard(board, depthleft - 1, maximising_player=True ) # Restore the previous position. board.pop() # Record new best score if discovered if score < min_eval: min_eval = score # Return best score from the starting position given to alphabeta search return min_eval def selectmove(board, depth): # Return random choice if depth = 0 if depth == 0: return random.choice(list(board.legal_moves)) bestMove = chess.Move.null() bestValue = -99999 # Iterate through legal moves for move in board.legal_moves: # Play move board.push(move) # Get value of move (reduce depth by 1, as 1 move already made) # Returned value is best value for black. More negative better for black boardValue = scoreboard(board, depth-1, maximising_player=False) # Strore move and value if best discovered so far if boardValue > bestValue: bestValue = boardValue bestMove = move # Restore the previous position board.pop() return bestMove
import Component from '@ember/component'; import layout from '../templates/components/ui-tribute'; import Tribute from "tributejs"; import { run } from '@ember/runloop'; import { get, set } from '@ember/object'; import { assert } from '@ember/debug'; import { isPresent } from '@ember/utils'; export default Component.extend({ layout, init() { this._super(...arguments); assert('Pass Tribure collections object as options attribute to the component', isPresent(get(this, 'options'))); }, didInsertElement() { this._super(...arguments); run(() => { let tribute = new Tribute(get(this, 'options')); let targetDom = this.getTargetDom(); tribute.attach(targetDom); set(this, 'tribute', tribute); this.registerTributeInstance(tribute); targetDom.addEventListener('tribute-replaced', (e) => { if (this.tributeReplaced) { this.tributeReplaced(e); } }); targetDom.addEventListener('tribute-no-match', (e) => { if (this.tributeNoMatch) { this.tributeNoMatch(e); } }); }); }, willDestroyElement() { this._super(...arguments); let targetDom = this.getTargetDom(); run(() => { let tribute = get(this, 'tribute'); tribute.hideMenu(); tribute.detach(targetDom); }); }, getTargetDom() { if (this.target && typeof (this.target) === 'string') { return this.element.querySelector(`${this.target}`); } else { return this.element.querySelector(':first-child'); } }, registerTributeInstance(tribute) { let action = get(this, 'getTributeInstance'); if (action) { action(tribute); } } });
'use strict'; describe('jsonEditorAddProperty', function() { var isolateScope; var elm; var testArray = [ 1, 'string' ]; var testObject = { id: 1, name: 'Test' }; var testScope; describe('addProperty', function() { describe('when scope.object is an object', function() { beforeEach(function() { bard.appModule('angular-json-edit'); bard.inject(function($window, $rootScope, $compile) { testScope = $rootScope; elm = angular.element('<json-editor-add-property object="newConfig" newProperty="{}">'); testScope.newConfig = angular.copy(testObject); $compile(elm)(testScope); testScope.$digest(); isolateScope = elm.isolateScope(); }); }); it('should add an empty array to the scope object when new type is array', function() { isolateScope.newProperty = { type: 'array', name: 'newArray' }; isolateScope.addProperty(); expect(isolateScope.object.newArray).toEqual([]); }); it('should add an empty object to the scope object when new type is object', function() { isolateScope.newProperty = { type: 'object', name: 'newObject' }; isolateScope.addProperty(); expect(isolateScope.object.newObject).toEqual({}); }); it('should add an empty string to the scope object when new type is string', function() { isolateScope.newProperty = { type: 'string', name: 'newString' }; isolateScope.addProperty(); expect(isolateScope.object.newString).toEqual(''); }); it('should add an number to the scope object when new type is number', function() { isolateScope.newProperty = { type: 'number', name: 'newNumber' }; isolateScope.addProperty(); expect(isolateScope.object.newNumber).toEqual(0); }); it('should add an boolean to the scope object when new type is boolean', function() { isolateScope.newProperty = { type: 'boolean', name: 'newBoolean' }; isolateScope.addProperty(); expect(typeof isolateScope.object.newBoolean).toEqual('boolean'); }); describe('getInputType', function() { it('should return "text" for a string', function() { isolateScope.newProperty = { type: 'string' }; expect(isolateScope.getInputType()).toEqual('text'); }); it('should return "number" for a number', function() { isolateScope.newProperty = { type: 'number' }; expect(isolateScope.getInputType()).toEqual('number'); }); }); }); describe('when scope.object is an array', function() { beforeEach(function() { bard.appModule('angular-json-edit'); bard.inject(function($window, $rootScope, $compile) { testScope = $rootScope; elm = angular.element('<json-editor-add-property object="newConfig" newProperty="{}">'); testScope.newConfig = angular.copy(testArray); $compile(elm)(testScope); testScope.$digest(); isolateScope = elm.isolateScope(); }); }); it('should push an empty array onto the scope object when new type is array', function() { isolateScope.newProperty = { type: 'array', name: 'newArray' }; isolateScope.addProperty(); expect(isolateScope.object[2]).toEqual([]); }); it('should push an empty object onto the scope object when new type is object', function() { isolateScope.newProperty = { type: 'object', name: 'newObject' }; isolateScope.addProperty(); expect(isolateScope.object[2]).toEqual({}); }); it('should push an empty string onto the scope object when new type is string', function() { isolateScope.newProperty = { type: 'string', name: 'newString' }; isolateScope.addProperty(); expect(isolateScope.object[2]).toEqual(''); }); it('should push a number onto the scope object when new type is number', function() { isolateScope.newProperty = { type: 'number', name: 'newNumber' }; isolateScope.addProperty(); expect(isolateScope.object[2]).toEqual(0); }); it('should push a boolean onto the scope object when new type is boolean', function() { isolateScope.newProperty = { type: 'boolean', name: 'newNumber' }; isolateScope.addProperty(); expect(typeof isolateScope.object[2]).toEqual('boolean'); }); }); }); describe('other functions', function() { beforeEach(function() { bard.appModule('angular-json-edit'); bard.inject(function($window, $rootScope, $compile) { testScope = $rootScope; elm = angular.element('<json-editor-add-property object="newConfig" newProperty="{}">'); testScope.newConfig = angular.copy(testArray); $compile(elm)(testScope); testScope.$digest(); isolateScope = elm.isolateScope(); }); }); describe('checkKeydown', function() { it('should call addProperty if enter pressed', function() { var testEvent = { keyCode: 13 }; isolateScope.addProperty = sinon.spy(); isolateScope.checkKeydown(testEvent); expect(isolateScope.addProperty.calledOnce).toEqual(true); }); }); describe('showValueField', function() { it('should return true for strings', function() { isolateScope.newProperty = { type: 'string' }; var testResult = isolateScope.showValueField(); expect(testResult).toEqual(true); }); it('should return true for numbers', function() { isolateScope.newProperty = { type: 'number' }; var testResult = isolateScope.showValueField(); expect(testResult).toEqual(true); }); it('should return false for objects', function() { isolateScope.newProperty = { type: 'object' }; var testResult = isolateScope.showValueField(); expect(testResult).toEqual(false); }); it('should return false for arrays', function() { isolateScope.newProperty = { type: 'array' }; var testResult = isolateScope.showValueField(); expect(testResult).toEqual(false); }); }); }); });
''' Use mitsuba renderer to obtain a depth and a reflectance image, given the camera's rotation parameters and the file path of the object to be rendered. ''' import numpy as np import uuid import os import cv2 import subprocess import shutil from scipy.signal import medfilt2d # import config from pytorch.utils.utils import makedir_if_not_exist render_template = \ r'''<?xml version="1.0" encoding="UTF-8"?> <scene version="0.5.0"> <integrator type="multichannel"> <integrator type="field"> <string name="field" value="{field}"/> <spectrum name="undefined" value="{undefined}"/> </integrator> </integrator> <sensor type="orthographic"> <transform name="toWorld"> <scale x="{sensor_scale}" y="{sensor_scale}"/> <lookat origin="{origin_str}" target="{target_str}" up="{up_str}"/> </transform> <sampler type="halton"> <integer name="sampleCount" value="{sample_count}"/> </sampler> <film type="mfilm"> <integer name="height" value="{height}"/> <integer name="width" value="{width}"/> <string name="fileFormat" value="numpy"/> <string name="pixelFormat" value="{pixel_format}"/> </film> </sensor> <shape type="shapenet"> <string name="filename" value="{obj_path}"/> <float name="maxSmoothAngle" value="30"/> </shape> <!--<shape type="sphere"> <float name="radius" value="0.08"/> </shape>--> </scene> ''' def render_depth_refl(obj_path, theta, phi, psi, sample_count=16, height=128, width=128, focal_length=128, sensor_scale=1, cache_dir='./', cleanup=True): ''' Render the depth and reflectance given those parameters. Axis: y | | / |/ theta /--------- x / / z :param obj_path: the path to the shape in wavefront obj format. :param theta: azimuth, in degrees :param phi: elevation, in degrees :param psi: in-plane rotation, in degrees :param sample_count: the halton samples for each pixel. :param height: image height :param width: image width :param focal_length: the distance between the camera and the origin :param sensor_scale: the scale of the screen space. :param cache_dir: the intermetiate files reside in this directory. :param cleanup: whether clean up the temporary files :return: depth - height x width numpy array reflectance - height x width x 3 numpy array mask - height x width numpy array, indicating whether the pixel is valid ''' # Convert to radians th = theta * np.pi / 180 ph = phi * np.pi / 180 ps = psi * np.pi / 180 # Compute the camera lookat parameters from Euler angles ox = focal_length * np.cos(th) * np.cos(ph) oy = focal_length * np.sin(ph) oz = - focal_length * np.sin(th) * np.cos(ph) origin = np.array([ox, oy, oz]) target = np.array([0, 0, 0]) n1 = np.array([-np.sin(ph) * np.cos(th), np.cos(ph), np.sin(ph) * np.sin(th)]) n2 = -np.array([np.sin(th), 0, np.cos(th)]) up = np.cos(ps) * n1 + np.sin(ps) * n2 # Generate the scene configuration shared_args = dict( sample_count=sample_count, sensor_scale=sensor_scale, height=height, width=width, origin_str=','.join(map(str, origin)), target_str=','.join(map(str, target)), up_str=','.join(map(str, up)), obj_path=obj_path ) depth_xml = render_template.format(field='distance', undefined='nan', pixel_format='luminance', **shared_args) refl_xml = render_template.format(field='albedo', undefined='nan,nan,nan', pixel_format='rgb', **shared_args) norm_xml = render_template.format(field='shNormal', undefined='nan,nan,nan', pixel_format='rgb', **shared_args) # pos_xml = render_template.format(field='relPosition', # undefined='nan,nan,nan', pixel_format='xyz', **shared_args) # Save to a file and call the mitsuba renderer cache_dir = makedir_if_not_exist(os.path.realpath(os.path.join(cache_dir, uuid.uuid4().hex))) depth_xml_path = os.path.join(cache_dir, 'depth.xml') refl_xml_path = os.path.join(cache_dir, 'refl.xml') # pos_xml_path = os.path.join(cache_dir, 'pos.xml') norm_xml_path = os.path.join(cache_dir, 'norm.xml') with open(depth_xml_path, 'w') as f: f.write(depth_xml) with open(refl_xml_path, 'w') as f: f.write(refl_xml) with open(norm_xml_path, 'w') as f: f.write(norm_xml) # with open(pos_xml_path, 'w') as f: # f.write(pos_xml) depth_bin_path = os.path.join(cache_dir, 'depth.npy') refl_bin_path = os.path.join(cache_dir, 'refl.npy') norm_bin_path = os.path.join(cache_dir, 'norm.npy') # pos_bin_path = os.path.join(cache_dir, 'pos.npy') env = os.environ.copy() MITSUBA_APPEND_PATH = None for k, v in MITSUBA_APPEND_PATH.items(): if env.get(k): env[k] += ':' + v else: env[k] = v try: owd = os.getcwd() os.chdir(cache_dir) subprocess.check_output(None + ['depth.xml', '-o', 'depth.npy'], env=env, stderr=subprocess.STDOUT ) subprocess.check_output(None + ['refl.xml', '-o', 'refl.npy'], env=env, stderr=subprocess.STDOUT ) subprocess.check_output(None + ['norm.xml', '-o', 'norm.npy'], env=env, stderr=subprocess.STDOUT ) # subprocess.check_output(config.MITSUBA_COMMAND + ['pos.xml', '-o', # 'pos.npy']) os.chdir(owd) distance = np.load(depth_bin_path) refl = np.load(refl_bin_path) norm = np.load(norm_bin_path) # pos = np.load(pos_bin_path) assert distance is not None, depth_bin_path assert refl is not None, refl_bin_path assert norm is not None, norm_bin_path depth = -distance # Compute the mask umask_depth = np.isnan(depth) umask_refl = np.logical_or.reduce(np.isnan(refl), axis=2) umask_norm = np.logical_or.reduce(np.isnan(norm), axis=2) # umask = np.logical_or(np.logical_or(umask_depth, umask_refl), umask_norm) umask = np.logical_or(umask_depth, umask_refl) mask = np.logical_not(umask) umask_3 = np.stack((umask,) * 3, axis=2) depth[umask] = depth[mask].min() # Calibrate the depth so that each pixel has size (1, 1) depth *= width / 2 / sensor_scale depth_min = depth.min() depth -= depth.min() depth = medfilt2d(depth) refl[umask_3] = 0 norm[umask_3] = 0 # Compute the norm in camera space cam_right = n2 cam_up = n1 cam_towards = -origin / focal_length world_to_cam = np.stack((cam_right, cam_towards, cam_up)) norm = np.einsum('ij,rcj->rci', world_to_cam, norm) # The axes used in mitsuba are different from our axes norm = norm[:, :, [0, 2, 1]]# swap y and z norm[:, :, 2] = -norm[:, :, 2] # flip z zmask = norm[:, :, 2] < 0 zmask_3 = np.stack((zmask,) * 3, axis=2) norm[zmask_3] = -norm[zmask_3] norm = norm.astype(np.float32) except subprocess.CalledProcessError as e: print(e.output.decode()) finally: if cleanup: shutil.rmtree(cache_dir) return depth, norm, refl, mask
/*! * jQuery UI Core @VERSION * http://jqueryui.com * * Copyright 2014 jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license * */ //>>label: Core //>>group: UI Core //>>description: The core of jQuery UI, required for all interactions and widgets. //>>docs: http://api.jqueryui.com/category/ui-core/ //>>demos: http://jqueryui.com/ (function( factory ) { if ( typeof define === "function" && define.amd ) { // AMD. Register as an anonymous module. define( [ "jquery" ], factory ); } else { // Browser globals factory( jQuery ); } }(function( $ ) { // $.ui might exist from components with no dependencies, e.g., $.ui.position $.ui = $.ui || {}; $.extend( $.ui, { version: "@VERSION", keyCode: { BACKSPACE: 8, COMMA: 188, DELETE: 46, DOWN: 40, END: 35, ENTER: 13, ESCAPE: 27, HOME: 36, LEFT: 37, PAGE_DOWN: 34, PAGE_UP: 33, PERIOD: 190, RIGHT: 39, SPACE: 32, TAB: 9, UP: 38 } }); // plugins $.fn.extend({ scrollParent: function( includeHidden ) { var position = this.css( "position" ), excludeStaticParent = position === "absolute", overflowRegex = includeHidden ? /(auto|scroll|hidden)/ : /(auto|scroll)/, scrollParent = this.parents().filter( function() { var parent = $( this ); if ( excludeStaticParent && parent.css( "position" ) === "static" ) { return false; } return overflowRegex.test( parent.css( "overflow" ) + parent.css( "overflow-y" ) + parent.css( "overflow-x" ) ); }).eq( 0 ); return position === "fixed" || !scrollParent.length ? $( this[ 0 ].ownerDocument || document ) : scrollParent; }, uniqueId: (function() { var uuid = 0; return function() { return this.each(function() { if ( !this.id ) { this.id = "ui-id-" + ( ++uuid ); } }); }; })(), removeUniqueId: function() { return this.each(function() { if ( /^ui-id-\d+$/.test( this.id ) ) { $( this ).removeAttr( "id" ); } }); } }); // selectors function focusable( element, isTabIndexNotNaN ) { var map, mapName, img, nodeName = element.nodeName.toLowerCase(); if ( "area" === nodeName ) { map = element.parentNode; mapName = map.name; if ( !element.href || !mapName || map.nodeName.toLowerCase() !== "map" ) { return false; } img = $( "img[usemap='#" + mapName + "']" )[ 0 ]; return !!img && visible( img ); } return ( /input|select|textarea|button|object/.test( nodeName ) ? !element.disabled : "a" === nodeName ? element.href || isTabIndexNotNaN : isTabIndexNotNaN) && // the element and all of its ancestors must be visible visible( element ); } function visible( element ) { return $.expr.filters.visible( element ) && !$( element ).parents().addBack().filter(function() { return $.css( this, "visibility" ) === "hidden"; }).length; } $.extend( $.expr[ ":" ], { data: $.expr.createPseudo ? $.expr.createPseudo(function( dataName ) { return function( elem ) { return !!$.data( elem, dataName ); }; }) : // support: jQuery <1.8 function( elem, i, match ) { return !!$.data( elem, match[ 3 ] ); }, focusable: function( element ) { return focusable( element, !isNaN( $.attr( element, "tabindex" ) ) ); }, tabbable: function( element ) { var tabIndex = $.attr( element, "tabindex" ), isTabIndexNaN = isNaN( tabIndex ); return ( isTabIndexNaN || tabIndex >= 0 ) && focusable( element, !isTabIndexNaN ); } }); // support: jQuery <1.8 if ( !$( "<a>" ).outerWidth( 1 ).jquery ) { $.each( [ "Width", "Height" ], function( i, name ) { var side = name === "Width" ? [ "Left", "Right" ] : [ "Top", "Bottom" ], type = name.toLowerCase(), orig = { innerWidth: $.fn.innerWidth, innerHeight: $.fn.innerHeight, outerWidth: $.fn.outerWidth, outerHeight: $.fn.outerHeight }; function reduce( elem, size, border, margin ) { $.each( side, function() { size -= parseFloat( $.css( elem, "padding" + this ) ) || 0; if ( border ) { size -= parseFloat( $.css( elem, "border" + this + "Width" ) ) || 0; } if ( margin ) { size -= parseFloat( $.css( elem, "margin" + this ) ) || 0; } }); return size; } $.fn[ "inner" + name ] = function( size ) { if ( size === undefined ) { return orig[ "inner" + name ].call( this ); } return this.each(function() { $( this ).css( type, reduce( this, size ) + "px" ); }); }; $.fn[ "outer" + name] = function( size, margin ) { if ( typeof size !== "number" ) { return orig[ "outer" + name ].call( this, size ); } return this.each(function() { $( this).css( type, reduce( this, size, true, margin ) + "px" ); }); }; }); } // support: jQuery <1.8 if ( !$.fn.addBack ) { $.fn.addBack = function( selector ) { return this.add( selector == null ? this.prevObject : this.prevObject.filter( selector ) ); }; } // support: jQuery 1.6.1, 1.6.2 (http://bugs.jquery.com/ticket/9413) if ( $( "<a>" ).data( "a-b", "a" ).removeData( "a-b" ).data( "a-b" ) ) { $.fn.removeData = (function( removeData ) { return function( key ) { if ( arguments.length ) { return removeData.call( this, $.camelCase( key ) ); } else { return removeData.call( this ); } }; })( $.fn.removeData ); } // deprecated $.ui.ie = !!/msie [\w.]+/.exec( navigator.userAgent.toLowerCase() ); $.fn.extend({ disableSelection: (function() { var eventType = "onselectstart" in document.createElement( "div" ) ? "selectstart" : "mousedown"; return function() { return this.bind( eventType + ".ui-disableSelection", function( event ) { event.preventDefault(); }); }; })(), enableSelection: function() { return this.unbind( ".ui-disableSelection" ); } }); // $.ui.plugin is deprecated. Use $.widget() extensions instead. $.ui.plugin = { add: function( module, option, set ) { var i, proto = $.ui[ module ].prototype; for ( i in set ) { proto.plugins[ i ] = proto.plugins[ i ] || []; proto.plugins[ i ].push( [ option, set[ i ] ] ); } }, call: function( instance, name, args, allowDisconnected ) { var i, set = instance.plugins[ name ]; if ( !set ) { return; } if ( !allowDisconnected && ( !instance.element[ 0 ].parentNode || instance.element[ 0 ].parentNode.nodeType === 11 ) ) { return; } for ( i = 0; i < set.length; i++ ) { if ( instance.options[ set[ i ][ 0 ] ] ) { set[ i ][ 1 ].apply( instance.element, args ); } } } }; }));
module.exports = async (d) => { const code = d.command.code; const r = code.split("$clear").length - 1; const inside = code.split("$clear")[r].after(); const err = d.inside(inside); if (err) return d.error(err); const [ amount, filter = "everyone", channelID = d.message.channel.id, returnCount = "no", ] = inside.splits; const channel = d.message.guild.channels.cache.get(channelID); if (!channel) return d.error(`:x: Invalid channel ID in \`$clear${inside}\``); let input = Number(amount); let deleteds = 0; while (input > 0) { const data = Math.min(input, 100); input -= data; const messages = await channel.messages .fetch({ limit: data, cache: false, }) .catch((err) => null); if (!messages) return d.error(":x: Failed to fetch messages"); if (messages.size <= 0) break; const deleted = await channel .bulkDelete( filter === "everyone" ? messages : messages.filter((m) => m.author.id === filter), true ) .catch((err) => null); if (!deleted) return d.error(":x: Failed to delete messages"); if (deleted.size <= 0) break; deleteds += deleted.size; if (input > 0) await new Promise((res) => setTimeout(res, 3000)); } return { code: code.replaceLast( `$clear${inside}`, returnCount === "yes" ? deleteds : "" ), }; };
const { GraphQLString, GraphQLList, GraphQLNonNull, GraphQLInt, GraphQLInputObjectType, } = require('graphql'); /** * @name exports * @summary GraphDefinitionlink Input Schema */ module.exports = new GraphQLInputObjectType({ name: 'GraphDefinitionlink_Input', description: '', fields: () => ({ _id: { type: require('./element.input.js'), description: 'unique id for the element within a resource (for internal references). This may be any string value that does not contain spaces.', }, id: { type: GraphQLString, description: 'unique id for the element within a resource (for internal references). This may be any string value that does not contain spaces.', }, extension: { type: new GraphQLList(require('./extension.input.js')), description: 'May be used to represent additional information that is not part of the basic definition of the element. In order to make the use of extensions safe and manageable, there is a strict set of governance applied to the definition and use of extensions. Though any implementer is allowed to define an extension, there is a set of requirements that SHALL be met as part of the definition of the extension.', }, modifierExtension: { type: new GraphQLList(require('./extension.input.js')), description: 'May be used to represent additional information that is not part of the basic definition of the element, and that modifies the understanding of the element that contains it. Usually modifier elements provide negation or qualification. In order to make the use of extensions safe and manageable, there is a strict set of governance applied to the definition and use of extensions. Though any implementer is allowed to define an extension, there is a set of requirements that SHALL be met as part of the definition of the extension. Applications processing a resource are required to check for modifier extensions.', }, _path: { type: require('./element.input.js'), description: 'Path in the resource that contains the link.', }, path: { type: new GraphQLNonNull(GraphQLString), description: 'Path in the resource that contains the link.', }, _sliceName: { type: require('./element.input.js'), description: 'Which slice (if profiled).', }, sliceName: { type: GraphQLString, description: 'Which slice (if profiled).', }, _min: { type: require('./element.input.js'), description: 'Minimum occurrences for this link.', }, min: { type: GraphQLInt, description: 'Minimum occurrences for this link.', }, _max: { type: require('./element.input.js'), description: 'Maximum occurrences for this link.', }, max: { type: GraphQLString, description: 'Maximum occurrences for this link.', }, _description: { type: require('./element.input.js'), description: 'Information about why this link is of interest in this graph definition.', }, description: { type: GraphQLString, description: 'Information about why this link is of interest in this graph definition.', }, target: { type: new GraphQLList( new GraphQLNonNull(require('./graphdefinitionlinktarget.input.js')), ), description: 'Potential target for the link.', }, }), });
a = [] for i in range(0,5): b = int(input()) a.append(b) n = len(a) for i in range(1,n): key = a[i] j = i-1 while(j>=0 and key< a[j]): a[j+1] = a[j] j=j-1 a[j+1] = key print(a)
import React from "react"; import '../../assets/styles/_index.scss'; import '../../assets/styles/_custom.scss'; import Container from 'react-bootstrap/Container'; import Row from 'react-bootstrap/Row'; import Col from 'react-bootstrap/Col'; import ScrollAnimation from 'react-animate-on-scroll'; import "animate.css/animate.min.css"; import { graphql } from 'gatsby' import get from 'lodash/get' import Helmet from 'react-helmet' import HeaderNavbar from '../../components/header-navbar/HeaderNavbar'; import MultiForm from '../../components/multi-form/FormSuccess'; import Footer from '../../components/footer/Footer'; const logo = require('../../assets/img/logo1.svg'); class MembershipformPage extends React.Component { render() { const CookiePolicyPage = get(this, 'props.data.allContentfulPages.edges') const seoMetaTitle = get(this, 'props.data.contentfulPages.seoMetaTitle') const seometaDescription = get(this, 'props.data.contentfulPages.seometaDescription') const seoMetaKeywords = get(this, 'props.data.contentfulPages.seoMetaKeywords') const url = typeof window !== 'undefined' ? window.location.href : '' return ( <> <Helmet> <title>{seoMetaTitle}</title> <meta name="description" content={seometaDescription} /> <meta name="keywords" content={seoMetaKeywords} /> <link rel="canonical" href={url} /> <meta property="og:site_name" content="thefoxclub" /> <meta property="og:url" content={url} /> <meta property="og:title" content="Mermbership Form" /> <meta property="og:type" content="article" /> <meta property="og:description" content="thefoxclub" /> <script type="application/ld+json"> {`{ "@context": "http://schema.org", "@type": "Organization", "name": "thefoxclub", "sameAs": [], "url": "${url}", "logo": "https://www.foxclublondon.com${logo}" }`} </script> </Helmet> <HeaderNavbar /> <section className="layout-findus contactus"> <div className="find-form"> <div className="container-fluid"> <Row className="mb-4 px-lg-5"> <Col lg={12}> <ScrollAnimation animateIn="fadeInUp"> <h1>Apply for Membership</h1> </ScrollAnimation> </Col> </Row> <Row className="px-lg-5"> <Col lg={12} className="mb-5"> <div className="form py-5"> <MultiForm /> </div> </Col> </Row> </div> </div> </section> <Footer /> </> ) } } export default MembershipformPage export const pageQuery = graphql` query membershipformPageAndMembershipformPage { allContentfulPages(filter: {id: {eq: "1f52096c-cec1-5ee9-ac3e-05c8d38d83f6"}}) { edges { node { bannerContent bannerLink bannerLinkText id content { childMarkdownRemark { html } } pageContent { childMarkdownRemark { html } } bannerImage { fluid( quality: 100, maxWidth: 1500) { base64 srcWebp src aspectRatio srcSetWebp } } } } } contentfulPages(id: {eq: "1f52096c-cec1-5ee9-ac3e-05c8d38d83f6"}) { seoMetaKeywords seoMetaTitle seometaDescription } } `
/* This file is generated by createIcons.js any changes will be lost. */ import createIcon from '../createIcon'; export const ChalkboardTeacherIconConfig = { name: 'ChalkboardTeacherIcon', height: 512, width: 640, svgPath: 'M208 352c-2.39 0-4.78.35-7.06 1.09C187.98 357.3 174.35 360 160 360c-14.35 0-27.98-2.7-40.95-6.91-2.28-.74-4.66-1.09-7.05-1.09C49.94 352-.33 402.48 0 464.62.14 490.88 21.73 512 48 512h224c26.27 0 47.86-21.12 48-47.38.33-62.14-49.94-112.62-112-112.62zm-48-32c53.02 0 96-42.98 96-96s-42.98-96-96-96-96 42.98-96 96 42.98 96 96 96zM592 0H208c-26.47 0-48 22.25-48 49.59V96c23.42 0 45.1 6.78 64 17.8V64h352v288h-64v-64H384v64h-76.24c19.1 16.69 33.12 38.73 39.69 64H592c26.47 0 48-22.25 48-49.59V49.59C640 22.25 618.47 0 592 0z', yOffset: '', xOffset: '', transform: '' }; export default createIcon(ChalkboardTeacherIconConfig); //# sourceMappingURL=chalkboard-teacher-icon.js.map
var classarm__compute_1_1_c_l_pyramid = [ [ "CLPyramid", "classarm__compute_1_1_c_l_pyramid.xhtml#a24edddb8cac90e092ecbd4a2d2a1ce59", null ], [ "allocate", "classarm__compute_1_1_c_l_pyramid.xhtml#acaefe811b78a2fdc4a0dba0c4029c3ef", null ], [ "get_pyramid_level", "classarm__compute_1_1_c_l_pyramid.xhtml#af07bb423a5c0df8018b67c0e94fada02", null ], [ "info", "classarm__compute_1_1_c_l_pyramid.xhtml#ac1b010c3c67886aa4add531ed3bbceac", null ], [ "init", "classarm__compute_1_1_c_l_pyramid.xhtml#ae4e11cca76492d63009564d1ea466dff", null ], [ "init_auto_padding", "classarm__compute_1_1_c_l_pyramid.xhtml#a0dd473fd109df68b4747ebf0f586a115", null ] ];
// Copyright 2010 The Emscripten Authors. All rights reserved. // Emscripten is available under two separate licenses, the MIT license and the // University of Illinois/NCSA Open Source License. Both these licenses can be // found in the LICENSE file. //"use strict"; // An implementation of basic necessary libraries for the web. This integrates // with a compiled libc and with the rest of the JS runtime. // // We search the Library object when there is an external function. If the // entry in the Library is a function, we insert it. If it is a string, we // do another lookup in the library (a simple way to write a function once, // if it can be called by different names). We also allow dependencies, // using __deps. Initialization code to be run after allocating all // global constants can be defined by __postset. // // Note that the full function name will be '_' + the name in the Library // object. For convenience, the short name appears here. Note that if you add a // new function with an '_', it will not be found. // Memory allocated during startup, in postsets, should only be static // (using makeStaticAlloc) LibraryManager.library = { // keep this low in memory, because we flatten arrays with them in them #if USE_PTHREADS _impure_ptr: '; if (ENVIRONMENT_IS_PTHREAD) __impure_ptr = PthreadWorkerInit.__impure_ptr; else PthreadWorkerInit.__impure_ptr __impure_ptr = {{{ makeStaticAlloc(4) }}}', __dso_handle: '; if (ENVIRONMENT_IS_PTHREAD) ___dso_handle = PthreadWorkerInit.___dso_handle; else PthreadWorkerInit.___dso_handle = ___dso_handle = {{{ makeStaticAlloc(4) }}}', #else _impure_ptr: '{{{ makeStaticAlloc(1) }}}', __dso_handle: '{{{ makeStaticAlloc(1) }}}', #endif $PROCINFO: { // permissions /* uid: 0, gid: 0, euid: 0, egid: 0, suid: 0, sgid: 0, fsuid: 0, fsgid: 0, */ // process identification ppid: 1, pid: 42, sid: 42, pgid: 42 }, // ========================================================================== // getTempRet0/setTempRet0: scratch space handling i64 return // ========================================================================== getTempRet0__sig: 'i', getTempRet0: function() { return {{{ makeGetTempRet0() }}}; }, setTempRet0__sig: 'vi', setTempRet0: function($i) { {{{ makeSetTempRet0('$i') }}}; }, // ========================================================================== // JavaScript <-> C string interop // ========================================================================== $stringToNewUTF8: function(jsString) { var length = lengthBytesUTF8(jsString)+1; var cString = _malloc(length); stringToUTF8(jsString, cString, length); return cString; }, // ========================================================================== // utime.h // ========================================================================== utime__deps: ['$FS', '__setErrNo'], utime__proxy: 'sync', utime__sig: 'iii', utime: function(path, times) { // int utime(const char *path, const struct utimbuf *times); // http://pubs.opengroup.org/onlinepubs/009695399/basedefs/utime.h.html var time; if (times) { // NOTE: We don't keep track of access timestamps. var offset = {{{ C_STRUCTS.utimbuf.modtime }}}; time = {{{ makeGetValue('times', 'offset', 'i32') }}}; time *= 1000; } else { time = Date.now(); } path = UTF8ToString(path); try { FS.utime(path, time, time); return 0; } catch (e) { FS.handleFSError(e); return -1; } }, utimes__deps: ['$FS', '__setErrNo'], utimes__proxy: 'sync', utimes__sig: 'iii', utimes: function(path, times) { var time; if (times) { var offset = {{{ C_STRUCTS.timeval.__size__ }}} + {{{ C_STRUCTS.timeval.tv_sec }}}; time = {{{ makeGetValue('times', 'offset', 'i32') }}} * 1000; offset = {{{ C_STRUCTS.timeval.__size__ }}} + {{{ C_STRUCTS.timeval.tv_usec }}}; time += {{{ makeGetValue('times', 'offset', 'i32') }}} / 1000; } else { time = Date.now(); } path = UTF8ToString(path); try { FS.utime(path, time, time); return 0; } catch (e) { FS.handleFSError(e); return -1; } }, // ========================================================================== // sys/file.h // ========================================================================== flock: function(fd, operation) { // int flock(int fd, int operation); // Pretend to succeed return 0; }, chroot__deps: ['__setErrNo'], chroot__proxy: 'sync', chroot__sig: 'ii', chroot: function(path) { // int chroot(const char *path); // http://pubs.opengroup.org/onlinepubs/7908799/xsh/chroot.html ___setErrNo({{{ cDefine('EACCES') }}}); return -1; }, fpathconf__deps: ['__setErrNo'], fpathconf__proxy: 'sync', fpathconf__sig: 'iii', fpathconf: function(fildes, name) { // long fpathconf(int fildes, int name); // http://pubs.opengroup.org/onlinepubs/000095399/functions/encrypt.html // NOTE: The first parameter is ignored, so pathconf == fpathconf. // The constants here aren't real values. Just mimicking glibc. switch (name) { case {{{ cDefine('_PC_LINK_MAX') }}}: return 32000; case {{{ cDefine('_PC_MAX_CANON') }}}: case {{{ cDefine('_PC_MAX_INPUT') }}}: case {{{ cDefine('_PC_NAME_MAX') }}}: return 255; case {{{ cDefine('_PC_PATH_MAX') }}}: case {{{ cDefine('_PC_PIPE_BUF') }}}: case {{{ cDefine('_PC_REC_MIN_XFER_SIZE') }}}: case {{{ cDefine('_PC_REC_XFER_ALIGN') }}}: case {{{ cDefine('_PC_ALLOC_SIZE_MIN') }}}: return 4096; case {{{ cDefine('_PC_CHOWN_RESTRICTED') }}}: case {{{ cDefine('_PC_NO_TRUNC') }}}: case {{{ cDefine('_PC_2_SYMLINKS') }}}: return 1; case {{{ cDefine('_PC_VDISABLE') }}}: return 0; case {{{ cDefine('_PC_SYNC_IO') }}}: case {{{ cDefine('_PC_ASYNC_IO') }}}: case {{{ cDefine('_PC_PRIO_IO') }}}: case {{{ cDefine('_PC_SOCK_MAXBUF') }}}: case {{{ cDefine('_PC_REC_INCR_XFER_SIZE') }}}: case {{{ cDefine('_PC_REC_MAX_XFER_SIZE') }}}: case {{{ cDefine('_PC_SYMLINK_MAX') }}}: return -1; case {{{ cDefine('_PC_FILESIZEBITS') }}}: return 64; } ___setErrNo({{{ cDefine('EINVAL') }}}); return -1; }, pathconf: 'fpathconf', confstr__deps: ['__setErrNo', '$ENV'], confstr__proxy: 'sync', confstr__sig: 'iiii', confstr: function(name, buf, len) { // size_t confstr(int name, char *buf, size_t len); // http://pubs.opengroup.org/onlinepubs/000095399/functions/confstr.html var value; switch (name) { case {{{ cDefine('_CS_PATH') }}}: value = ENV['PATH'] || '/'; break; case {{{ cDefine('_CS_POSIX_V6_WIDTH_RESTRICTED_ENVS') }}}: // Mimicking glibc. value = 'POSIX_V6_ILP32_OFF32\nPOSIX_V6_ILP32_OFFBIG'; break; case {{{ cDefine('_CS_GNU_LIBC_VERSION') }}}: // This JS implementation was tested against this glibc version. value = 'glibc 2.14'; break; case {{{ cDefine('_CS_GNU_LIBPTHREAD_VERSION') }}}: // We don't support pthreads. value = ''; break; case {{{ cDefine('_CS_POSIX_V6_ILP32_OFF32_LIBS') }}}: case {{{ cDefine('_CS_POSIX_V6_ILP32_OFFBIG_LIBS') }}}: case {{{ cDefine('_CS_POSIX_V6_LP64_OFF64_CFLAGS') }}}: case {{{ cDefine('_CS_POSIX_V6_LP64_OFF64_LDFLAGS') }}}: case {{{ cDefine('_CS_POSIX_V6_LP64_OFF64_LIBS') }}}: case {{{ cDefine('_CS_POSIX_V6_LPBIG_OFFBIG_CFLAGS') }}}: case {{{ cDefine('_CS_POSIX_V6_LPBIG_OFFBIG_LDFLAGS') }}}: case {{{ cDefine('_CS_POSIX_V6_LPBIG_OFFBIG_LIBS') }}}: value = ''; break; case {{{ cDefine('_CS_POSIX_V6_ILP32_OFF32_CFLAGS') }}}: case {{{ cDefine('_CS_POSIX_V6_ILP32_OFF32_LDFLAGS') }}}: case {{{ cDefine('_CS_POSIX_V6_ILP32_OFFBIG_LDFLAGS') }}}: value = '-m32'; break; case {{{ cDefine('_CS_POSIX_V6_ILP32_OFFBIG_CFLAGS') }}}: value = '-m32 -D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64'; break; default: ___setErrNo({{{ cDefine('EINVAL') }}}); return 0; } if (len == 0 || buf == 0) { return value.length + 1; } else { var length = Math.min(len, value.length); for (var i = 0; i < length; i++) { {{{ makeSetValue('buf', 'i', 'value.charCodeAt(i)', 'i8') }}}; } if (len > length) {{{ makeSetValue('buf', 'i++', '0', 'i8') }}}; return i; } }, execl__deps: ['__setErrNo'], execl: function(/* ... */) { // int execl(const char *path, const char *arg0, ... /*, (char *)0 */); // http://pubs.opengroup.org/onlinepubs/009695399/functions/exec.html // We don't support executing external code. ___setErrNo({{{ cDefine('ENOEXEC') }}}); return -1; }, execle: 'execl', execlp: 'execl', execv: 'execl', execve: 'execl', execvp: 'execl', __execvpe: 'execl', fexecve: 'execl', exit: function(status) { #if MINIMAL_RUNTIME throw 'exit(' + status + ')'; #else // void _exit(int status); // http://pubs.opengroup.org/onlinepubs/000095399/functions/exit.html exit(status); #endif }, _exit__sig: 'vi', _exit: 'exit', _Exit__sig: 'vi', _Exit: 'exit', fork__deps: ['__setErrNo'], fork: function() { // pid_t fork(void); // http://pubs.opengroup.org/onlinepubs/000095399/functions/fork.html // We don't support multiple processes. ___setErrNo({{{ cDefine('EAGAIN') }}}); return -1; }, vfork: 'fork', posix_spawn: 'fork', posix_spawnp: 'fork', setgroups__deps: ['__setErrNo', 'sysconf'], setgroups: function(ngroups, gidset) { // int setgroups(int ngroups, const gid_t *gidset); // https://developer.apple.com/library/mac/#documentation/Darwin/Reference/ManPages/man2/setgroups.2.html if (ngroups < 1 || ngroups > _sysconf({{{ cDefine('_SC_NGROUPS_MAX') }}})) { ___setErrNo({{{ cDefine('EINVAL') }}}); return -1; } else { // We have just one process/user/group, so it makes no sense to set groups. ___setErrNo({{{ cDefine('EPERM') }}}); return -1; } }, getpagesize: function() { // int getpagesize(void); return PAGE_SIZE; }, sysconf__deps: ['__setErrNo'], sysconf__proxy: 'sync', sysconf__sig: 'ii', sysconf: function(name) { // long sysconf(int name); // http://pubs.opengroup.org/onlinepubs/009695399/functions/sysconf.html switch(name) { case {{{ cDefine('_SC_PAGE_SIZE') }}}: return PAGE_SIZE; case {{{ cDefine('_SC_PHYS_PAGES') }}}: #if WASM var maxHeapSize = 2*1024*1024*1024 - 65536; #else var maxHeapSize = 2*1024*1024*1024 - 16777216; #endif #if WASM_MEM_MAX != -1 maxHeapSize = {{{ WASM_MEM_MAX }}}; #endif #if !ALLOW_MEMORY_GROWTH maxHeapSize = HEAPU8.length; #endif return maxHeapSize / PAGE_SIZE; case {{{ cDefine('_SC_ADVISORY_INFO') }}}: case {{{ cDefine('_SC_BARRIERS') }}}: case {{{ cDefine('_SC_ASYNCHRONOUS_IO') }}}: case {{{ cDefine('_SC_CLOCK_SELECTION') }}}: case {{{ cDefine('_SC_CPUTIME') }}}: case {{{ cDefine('_SC_FSYNC') }}}: case {{{ cDefine('_SC_IPV6') }}}: case {{{ cDefine('_SC_MAPPED_FILES') }}}: case {{{ cDefine('_SC_MEMLOCK') }}}: case {{{ cDefine('_SC_MEMLOCK_RANGE') }}}: case {{{ cDefine('_SC_MEMORY_PROTECTION') }}}: case {{{ cDefine('_SC_MESSAGE_PASSING') }}}: case {{{ cDefine('_SC_MONOTONIC_CLOCK') }}}: case {{{ cDefine('_SC_PRIORITIZED_IO') }}}: case {{{ cDefine('_SC_PRIORITY_SCHEDULING') }}}: case {{{ cDefine('_SC_RAW_SOCKETS') }}}: case {{{ cDefine('_SC_READER_WRITER_LOCKS') }}}: case {{{ cDefine('_SC_REALTIME_SIGNALS') }}}: case {{{ cDefine('_SC_SEMAPHORES') }}}: case {{{ cDefine('_SC_SHARED_MEMORY_OBJECTS') }}}: case {{{ cDefine('_SC_SPAWN') }}}: case {{{ cDefine('_SC_SPIN_LOCKS') }}}: case {{{ cDefine('_SC_SYNCHRONIZED_IO') }}}: case {{{ cDefine('_SC_THREAD_ATTR_STACKADDR') }}}: case {{{ cDefine('_SC_THREAD_ATTR_STACKSIZE') }}}: case {{{ cDefine('_SC_THREAD_CPUTIME') }}}: case {{{ cDefine('_SC_THREAD_PRIO_INHERIT') }}}: case {{{ cDefine('_SC_THREAD_PRIO_PROTECT') }}}: case {{{ cDefine('_SC_THREAD_PROCESS_SHARED') }}}: case {{{ cDefine('_SC_THREAD_SAFE_FUNCTIONS') }}}: case {{{ cDefine('_SC_THREADS') }}}: case {{{ cDefine('_SC_TIMEOUTS') }}}: case {{{ cDefine('_SC_TIMERS') }}}: case {{{ cDefine('_SC_VERSION') }}}: case {{{ cDefine('_SC_2_C_BIND') }}}: case {{{ cDefine('_SC_2_C_DEV') }}}: case {{{ cDefine('_SC_2_CHAR_TERM') }}}: case {{{ cDefine('_SC_2_LOCALEDEF') }}}: case {{{ cDefine('_SC_2_SW_DEV') }}}: case {{{ cDefine('_SC_2_VERSION') }}}: return 200809; case {{{ cDefine('_SC_THREAD_PRIORITY_SCHEDULING') }}}: return 0; case {{{ cDefine('_SC_MQ_OPEN_MAX') }}}: case {{{ cDefine('_SC_XOPEN_STREAMS') }}}: case {{{ cDefine('_SC_XBS5_LP64_OFF64') }}}: case {{{ cDefine('_SC_XBS5_LPBIG_OFFBIG') }}}: case {{{ cDefine('_SC_AIO_LISTIO_MAX') }}}: case {{{ cDefine('_SC_AIO_MAX') }}}: case {{{ cDefine('_SC_SPORADIC_SERVER') }}}: case {{{ cDefine('_SC_THREAD_SPORADIC_SERVER') }}}: case {{{ cDefine('_SC_TRACE') }}}: case {{{ cDefine('_SC_TRACE_EVENT_FILTER') }}}: case {{{ cDefine('_SC_TRACE_EVENT_NAME_MAX') }}}: case {{{ cDefine('_SC_TRACE_INHERIT') }}}: case {{{ cDefine('_SC_TRACE_LOG') }}}: case {{{ cDefine('_SC_TRACE_NAME_MAX') }}}: case {{{ cDefine('_SC_TRACE_SYS_MAX') }}}: case {{{ cDefine('_SC_TRACE_USER_EVENT_MAX') }}}: case {{{ cDefine('_SC_TYPED_MEMORY_OBJECTS') }}}: case {{{ cDefine('_SC_V6_LP64_OFF64') }}}: case {{{ cDefine('_SC_V6_LPBIG_OFFBIG') }}}: case {{{ cDefine('_SC_2_FORT_DEV') }}}: case {{{ cDefine('_SC_2_FORT_RUN') }}}: case {{{ cDefine('_SC_2_PBS') }}}: case {{{ cDefine('_SC_2_PBS_ACCOUNTING') }}}: case {{{ cDefine('_SC_2_PBS_CHECKPOINT') }}}: case {{{ cDefine('_SC_2_PBS_LOCATE') }}}: case {{{ cDefine('_SC_2_PBS_MESSAGE') }}}: case {{{ cDefine('_SC_2_PBS_TRACK') }}}: case {{{ cDefine('_SC_2_UPE') }}}: case {{{ cDefine('_SC_THREAD_THREADS_MAX') }}}: case {{{ cDefine('_SC_SEM_NSEMS_MAX') }}}: case {{{ cDefine('_SC_SYMLOOP_MAX') }}}: case {{{ cDefine('_SC_TIMER_MAX') }}}: return -1; case {{{ cDefine('_SC_V6_ILP32_OFF32') }}}: case {{{ cDefine('_SC_V6_ILP32_OFFBIG') }}}: case {{{ cDefine('_SC_JOB_CONTROL') }}}: case {{{ cDefine('_SC_REGEXP') }}}: case {{{ cDefine('_SC_SAVED_IDS') }}}: case {{{ cDefine('_SC_SHELL') }}}: case {{{ cDefine('_SC_XBS5_ILP32_OFF32') }}}: case {{{ cDefine('_SC_XBS5_ILP32_OFFBIG') }}}: case {{{ cDefine('_SC_XOPEN_CRYPT') }}}: case {{{ cDefine('_SC_XOPEN_ENH_I18N') }}}: case {{{ cDefine('_SC_XOPEN_LEGACY') }}}: case {{{ cDefine('_SC_XOPEN_REALTIME') }}}: case {{{ cDefine('_SC_XOPEN_REALTIME_THREADS') }}}: case {{{ cDefine('_SC_XOPEN_SHM') }}}: case {{{ cDefine('_SC_XOPEN_UNIX') }}}: return 1; case {{{ cDefine('_SC_THREAD_KEYS_MAX') }}}: case {{{ cDefine('_SC_IOV_MAX') }}}: case {{{ cDefine('_SC_GETGR_R_SIZE_MAX') }}}: case {{{ cDefine('_SC_GETPW_R_SIZE_MAX') }}}: case {{{ cDefine('_SC_OPEN_MAX') }}}: return 1024; case {{{ cDefine('_SC_RTSIG_MAX') }}}: case {{{ cDefine('_SC_EXPR_NEST_MAX') }}}: case {{{ cDefine('_SC_TTY_NAME_MAX') }}}: return 32; case {{{ cDefine('_SC_ATEXIT_MAX') }}}: case {{{ cDefine('_SC_DELAYTIMER_MAX') }}}: case {{{ cDefine('_SC_SEM_VALUE_MAX') }}}: return 2147483647; case {{{ cDefine('_SC_SIGQUEUE_MAX') }}}: case {{{ cDefine('_SC_CHILD_MAX') }}}: return 47839; case {{{ cDefine('_SC_BC_SCALE_MAX') }}}: case {{{ cDefine('_SC_BC_BASE_MAX') }}}: return 99; case {{{ cDefine('_SC_LINE_MAX') }}}: case {{{ cDefine('_SC_BC_DIM_MAX') }}}: return 2048; case {{{ cDefine('_SC_ARG_MAX') }}}: return 2097152; case {{{ cDefine('_SC_NGROUPS_MAX') }}}: return 65536; case {{{ cDefine('_SC_MQ_PRIO_MAX') }}}: return 32768; case {{{ cDefine('_SC_RE_DUP_MAX') }}}: return 32767; case {{{ cDefine('_SC_THREAD_STACK_MIN') }}}: return 16384; case {{{ cDefine('_SC_BC_STRING_MAX') }}}: return 1000; case {{{ cDefine('_SC_XOPEN_VERSION') }}}: return 700; case {{{ cDefine('_SC_LOGIN_NAME_MAX') }}}: return 256; case {{{ cDefine('_SC_COLL_WEIGHTS_MAX') }}}: return 255; case {{{ cDefine('_SC_CLK_TCK') }}}: return 100; case {{{ cDefine('_SC_HOST_NAME_MAX') }}}: return 64; case {{{ cDefine('_SC_AIO_PRIO_DELTA_MAX') }}}: return 20; case {{{ cDefine('_SC_STREAM_MAX') }}}: return 16; case {{{ cDefine('_SC_TZNAME_MAX') }}}: return 6; case {{{ cDefine('_SC_THREAD_DESTRUCTOR_ITERATIONS') }}}: return 4; case {{{ cDefine('_SC_NPROCESSORS_ONLN') }}}: { if (typeof navigator === 'object') return navigator['hardwareConcurrency'] || 1; return 1; } } ___setErrNo({{{ cDefine('EINVAL') }}}); return -1; }, emscripten_get_heap_size: function() { return HEAP8.length; }, #if ABORTING_MALLOC $abortOnCannotGrowMemory: function(requestedSize) { #if ASSERTIONS #if WASM abort('Cannot enlarge memory arrays to size ' + requestedSize + ' bytes (OOM). Either (1) compile with -s TOTAL_MEMORY=X with X higher than the current value ' + HEAP8.length + ', (2) compile with -s ALLOW_MEMORY_GROWTH=1 which allows increasing the size at runtime, or (3) if you want malloc to return NULL (0) instead of this abort, compile with -s ABORTING_MALLOC=0 '); #else abort('Cannot enlarge memory arrays to size ' + requestedSize + ' bytes (OOM). Either (1) compile with -s TOTAL_MEMORY=X with X higher than the current value ' + HEAP8.length + ', (2) compile with -s ALLOW_MEMORY_GROWTH=1 which allows increasing the size at runtime but prevents some optimizations, (3) set Module.TOTAL_MEMORY to a higher value before the program runs, or (4) if you want malloc to return NULL (0) instead of this abort, compile with -s ABORTING_MALLOC=0 '); #endif #else abort('OOM'); #endif }, #endif #if TEST_MEMORY_GROWTH_FAILS $emscripten_realloc_buffer: function(size) { return false; }, #else // Grows the asm.js/wasm heap to the given byte size, and updates both JS and asm.js/wasm side views to the buffer. // Returns 1 on success, or undefined if growing failed. $emscripten_realloc_buffer: function(size) { try { #if WASM // round size grow request up to wasm page size (fixed 64KB per spec) wasmMemory.grow((size - buffer.byteLength + 65535) >> 16); // .grow() takes a delta compared to the previous size updateGlobalBufferAndViews(wasmMemory.buffer); #else // asm.js: var newBuffer = new ArrayBuffer(size); if (newBuffer.byteLength != size) return /*undefined, allocation did not succeed*/; new Int8Array(newBuffer).set(HEAP8); _emscripten_replace_memory(newBuffer); updateGlobalBufferAndViews(newBuffer); #endif return 1 /*success*/; } catch(e) { #if ASSERTIONS console.error('emscripten_realloc_buffer: Attempted to grow heap from ' + buffer.byteLength + ' bytes to ' + size + ' bytes, but got error: ' + e); #endif } }, #endif // ~TEST_MEMORY_GROWTH_FAILS emscripten_resize_heap__deps: ['emscripten_get_heap_size' #if ABORTING_MALLOC , '$abortOnCannotGrowMemory' #endif #if ALLOW_MEMORY_GROWTH , '$emscripten_realloc_buffer' #endif ], emscripten_resize_heap: function(requestedSize) { #if ALLOW_MEMORY_GROWTH == 0 #if ABORTING_MALLOC abortOnCannotGrowMemory(requestedSize); #else return false; // malloc will report failure #endif // ABORTING_MALLOC #else // ALLOW_MEMORY_GROWTH == 0 var oldSize = _emscripten_get_heap_size(); // With pthreads, races can happen (another thread might increase the size in between), so return a failure, and let the caller retry. #if USE_PTHREADS if (requestedSize <= oldSize) { return false; } #endif // USE_PTHREADS #if ASSERTIONS && !USE_PTHREADS assert(requestedSize > oldSize); #endif #if EMSCRIPTEN_TRACING // Report old layout one last time _emscripten_trace_report_memory_layout(); #endif var PAGE_MULTIPLE = {{{ getPageSize() }}}; var LIMIT = 2147483648 - PAGE_MULTIPLE; // We can do one page short of 2GB as theoretical maximum. if (requestedSize > LIMIT) { #if ASSERTIONS err('Cannot enlarge memory, asked to go up to ' + requestedSize + ' bytes, but the limit is ' + LIMIT + ' bytes!'); #endif return false; } var MIN_TOTAL_MEMORY = 16777216; var newSize = Math.max(oldSize, MIN_TOTAL_MEMORY); // So the loop below will not be infinite, and minimum asm.js memory size is 16MB. // TODO: see realloc_buffer - for PTHREADS we may want to decrease these jumps while (newSize < requestedSize) { // Keep incrementing the heap size as long as it's less than what is requested. #if MEMORY_GROWTH_STEP != -1 // Memory growth is fixed to a multiple of the WASM page size of 64KB (eg. 16MB) set by the user. newSize = Math.min(alignUp(newSize + {{{ MEMORY_GROWTH_STEP }}}, PAGE_MULTIPLE), LIMIT); #else if (newSize <= 536870912) { newSize = alignUp(2 * newSize, PAGE_MULTIPLE); // Simple heuristic: double until 1GB... } else { // ..., but after that, add smaller increments towards 2GB, which we cannot reach newSize = Math.min(alignUp((3 * newSize + 2147483648) / 4, PAGE_MULTIPLE), LIMIT); } #endif // MEMORY_GROWTH_STEP #if ASSERTIONS if (newSize === oldSize) { warnOnce('Cannot ask for more memory since we reached the practical limit in browsers (which is just below 2GB), so the request would have failed. Requesting only ' + HEAP8.length); } #endif } #if WASM_MEM_MAX != -1 // A limit was set for how much we can grow. We should not exceed that // (the wasm binary specifies it, so if we tried, we'd fail anyhow). That is, // if we are at say 64MB, and the max is 100MB, then we should *not* try to // grow 64->128MB which is the default behavior (doubling), as 128MB will // fail because of the max limit. Instead, we should only try to grow // 64->100MB in this example, which has a chance of succeeding (but may // still fail for another reason, of actually running out of memory). newSize = Math.min(newSize, {{{ WASM_MEM_MAX }}}); if (newSize == oldSize) { #if ASSERTIONS err('Failed to grow the heap from ' + oldSize + ', as we reached the WASM_MEM_MAX limit (' + {{{ WASM_MEM_MAX }}} + ') set during compilation'); #endif return false; } #endif // WASM_MEM_MAX #if USE_ASAN // One byte of ASan's shadow memory shadows 8 bytes of real memory. // If we increase the memory beyond 8 * ASAN_SHADOW_SIZE, then the shadow memory overflows. // This causes real memory to be corrupted. newSize = Math.min(newSize, {{{ 8 * ASAN_SHADOW_SIZE }}}); if (newSize == oldSize) { #if ASSERTIONS err('Failed to grow the heap from ' + oldSize + ', as we reached the limit of our shadow memory. Increase ASAN_SHADOW_SIZE.'); #endif return false; } #endif var replacement = emscripten_realloc_buffer(newSize); if (!replacement) { #if ASSERTIONS err('Failed to grow the heap from ' + oldSize + ' bytes to ' + newSize + ' bytes, not enough memory!'); #endif return false; } #if ASSERTIONS && (!WASM || WASM2JS) err('Warning: Enlarging memory arrays, this is not fast! ' + [oldSize, newSize]); #endif #if EMSCRIPTEN_TRACING _emscripten_trace_js_log_message("Emscripten", "Enlarging memory arrays from " + oldSize + " to " + newSize); // And now report the new layout _emscripten_trace_report_memory_layout(); #endif return true; #endif // ALLOW_MEMORY_GROWTH }, #if MINIMAL_RUNTIME && !ASSERTIONS && !ALLOW_MEMORY_GROWTH // If USES_DYNAMIC_ALLOC is not defined, do not compile in sbrk() or brk(), so that user gets a linker error if they attempt // to call into malloc() that would sbrk(). #if USES_DYNAMIC_ALLOC // If building with minimal runtime in release mode, where malloc() failures are not expected to throw and memory growth // is not allowed, use a really small stub for sbrk() and brk() that return failure. sbrk__asm: true, sbrk__sig: ['ii'], #if USES_DYNAMIC_ALLOC == 1 sbrk__deps: ['emscripten_get_heap_size'], #endif sbrk: function(increment) { increment = increment|0; var oldDynamicTop = 0; var newDynamicTop = 0; oldDynamicTop = HEAP32[DYNAMICTOP_PTR>>2]|0; newDynamicTop = oldDynamicTop + increment | 0; #if USES_DYNAMIC_ALLOC == 1 if ((newDynamicTop|0) > (_emscripten_get_heap_size()|0)) { return -1; } #endif HEAP32[DYNAMICTOP_PTR>>2] = newDynamicTop | 0; return oldDynamicTop | 0; }, brk__asm: true, brk__sig: ['ii'], #if USES_DYNAMIC_ALLOC == 1 brk__deps: ['emscripten_get_heap_size'], #endif brk: function(newDynamicTop) { newDynamicTop = newDynamicTop|0; #if USES_DYNAMIC_ALLOC == 1 if ((newDynamicTop|0) > (_emscripten_get_heap_size()|0)) { return -1; } #endif HEAP32[DYNAMICTOP_PTR>>2] = newDynamicTop | 0; return 0; }, #endif // USES_DYNAMIC_ALLOC #else // Implement a Linux-like 'memory area' for our 'process'. // Changes the size of the memory area by |bytes|; returns the // address of the previous top ('break') of the memory area // We control the "dynamic" memory - DYNAMIC_BASE to DYNAMICTOP sbrk__asm: true, sbrk__sig: ['ii'], sbrk__deps: ['__setErrNo', 'emscripten_get_heap_size', 'emscripten_resize_heap' #if ABORTING_MALLOC , '$abortOnCannotGrowMemory' #endif ], sbrk: function(increment) { increment = increment|0; var oldDynamicTop = 0; var oldDynamicTopOnChange = 0; var newDynamicTop = 0; var totalMemory = 0; totalMemory = _emscripten_get_heap_size()|0; #if USE_PTHREADS // Perform a compare-and-swap loop to update the new dynamic top value. This is because // this function can be called simultaneously in multiple threads. do { #endif #if !USE_PTHREADS oldDynamicTop = HEAP32[DYNAMICTOP_PTR>>2]|0; #else oldDynamicTop = Atomics_load(HEAP32, DYNAMICTOP_PTR>>2)|0; #endif newDynamicTop = oldDynamicTop + increment | 0; if (((increment|0) > 0 & (newDynamicTop|0) < (oldDynamicTop|0)) // Detect and fail if we would wrap around signed 32-bit int. | (newDynamicTop|0) < 0) { // Also underflow, sbrk() should be able to be used to subtract. #if ABORTING_MALLOC abortOnCannotGrowMemory(newDynamicTop|0)|0; #endif ___setErrNo({{{ cDefine('ENOMEM') }}}); return -1; } if ((newDynamicTop|0) > (totalMemory|0)) { if (_emscripten_resize_heap(newDynamicTop|0)|0) { // We resized the heap. Start another loop iteration if we need to. #if USE_PTHREADS totalMemory = _emscripten_get_heap_size()|0; continue; #endif } else { // We failed to resize the heap. #if USE_PTHREADS // Possibly another thread has grown memory meanwhile, if we race with them. If memory grew, // start another loop iteration. if ((_emscripten_get_heap_size()|0) > totalMemory) { totalMemory = _emscripten_get_heap_size()|0; continue; } #endif ___setErrNo({{{ cDefine('ENOMEM') }}}); return -1; } } #if !USE_PTHREADS HEAP32[DYNAMICTOP_PTR>>2] = newDynamicTop|0; #else // Attempt to update the dynamic top to new value. Another thread may have beat this thread to the update, // in which case we will need to start over by iterating the loop body again. oldDynamicTopOnChange = Atomics_compareExchange(HEAP32, DYNAMICTOP_PTR>>2, oldDynamicTop|0, newDynamicTop|0)|0; } while((oldDynamicTopOnChange|0) != (oldDynamicTop|0)); #endif return oldDynamicTop|0; }, brk__deps: ['sbrk'], brk__asm: true, brk__sig: ['ii'], brk__deps: ['__setErrNo', 'emscripten_get_heap_size', 'emscripten_resize_heap' #if ABORTING_MALLOC , '$abortOnCannotGrowMemory' #endif ], brk: function(newDynamicTop) { newDynamicTop = newDynamicTop|0; var diff = 0; diff = newDynamicTop - (_sbrk(0) | 0) | 0; if ((_sbrk(diff | 0) | 0) == -1) { return -1; } return 0; }, #endif // ~ (MINIMAL_RUNTIME && !ASSERTIONS && !ALLOW_MEMORY_GROWTH) system__deps: ['__setErrNo'], system: function(command) { // int system(const char *command); // http://pubs.opengroup.org/onlinepubs/000095399/functions/system.html // Can't call external programs. ___setErrNo({{{ cDefine('EAGAIN') }}}); return -1; }, // ========================================================================== // stdlib.h // ========================================================================== #if !MINIMAL_RUNTIME && MALLOC != 'none' // tiny, fake malloc/free implementation. If the program actually uses malloc, // a compiled version will be used; this will only be used if the runtime // needs to allocate something, for which this is good enough if otherwise // no malloc is needed. malloc: function(bytes) { /* Over-allocate to make sure it is byte-aligned by 8. * This will leak memory, but this is only the dummy * implementation (replaced by dlmalloc normally) so * not an issue. */ #if ASSERTIONS == 2 warnOnce('using stub malloc (reference it from C to have the real one included)'); #endif var ptr = dynamicAlloc(bytes + 8); return (ptr+8) & 0xFFFFFFF8; }, free: function() { #if ASSERTIONS == 2 warnOnce('using stub free (reference it from C to have the real one included)'); #endif }, #endif abs: 'Math_abs', labs: 'Math_abs', _ZSt9terminatev__deps: ['exit'], _ZSt9terminatev: function() { _exit(-1234); }, #if MINIMAL_RUNTIME atexit: function(){}, __cxa_atexit: function(){}, __cxa_thread_atexit: function(){}, __cxa_thread_atexit_impl: function(){}, #else atexit__proxy: 'sync', atexit__sig: 'ii', atexit: function(func, arg) { #if ASSERTIONS #if EXIT_RUNTIME == 0 warnOnce('atexit() called, but EXIT_RUNTIME is not set, so atexits() will not be called. set EXIT_RUNTIME to 1 (see the FAQ)'); #endif #endif __ATEXIT__.unshift({ func: func, arg: arg }); }, __cxa_atexit: 'atexit', // used in rust, clang when doing thread_local statics __cxa_thread_atexit: 'atexit', __cxa_thread_atexit_impl: 'atexit', #endif // TODO: There are currently two abort() functions that get imported to asm module scope: the built-in runtime function abort(), // and this function _abort(). Remove one of these, importing two functions for the same purpose is wasteful. abort: function() { #if MINIMAL_RUNTIME // In MINIMAL_RUNTIME the module object does not exist, so its behavior to abort is to throw directly. throw 'abort'; #else Module['abort'](); #endif }, __buildEnvironment__deps: ['$ENV'], __buildEnvironment: function(environ) { // WARNING: Arbitrary limit! var MAX_ENV_VALUES = 64; var TOTAL_ENV_SIZE = 1024; // Statically allocate memory for the environment. var poolPtr; var envPtr; if (!___buildEnvironment.called) { ___buildEnvironment.called = true; // Set default values. Use string keys for Closure Compiler compatibility. ENV['USER'] = ENV['LOGNAME'] = 'web_user'; ENV['PATH'] = '/'; ENV['PWD'] = '/'; ENV['HOME'] = '/home/web_user'; // Browser language detection #8751 ENV['LANG'] = ((typeof navigator === 'object' && navigator.languages && navigator.languages[0]) || 'C').replace('-', '_') + '.UTF-8'; ENV['_'] = thisProgram; // Allocate memory. #if !MINIMAL_RUNTIME // TODO: environment support in MINIMAL_RUNTIME poolPtr = getMemory(TOTAL_ENV_SIZE); envPtr = getMemory(MAX_ENV_VALUES * {{{ Runtime.POINTER_SIZE }}}); {{{ makeSetValue('envPtr', '0', 'poolPtr', 'i8*') }}}; {{{ makeSetValue('environ', 0, 'envPtr', 'i8*') }}}; #endif } else { envPtr = {{{ makeGetValue('environ', '0', 'i8**') }}}; poolPtr = {{{ makeGetValue('envPtr', '0', 'i8*') }}}; } // Collect key=value lines. var strings = []; var totalSize = 0; for (var key in ENV) { if (typeof ENV[key] === 'string') { var line = key + '=' + ENV[key]; strings.push(line); totalSize += line.length; } } if (totalSize > TOTAL_ENV_SIZE) { throw new Error('Environment size exceeded TOTAL_ENV_SIZE!'); } // Make new. var ptrSize = {{{ Runtime.getNativeTypeSize('i8*') }}}; for (var i = 0; i < strings.length; i++) { var line = strings[i]; writeAsciiToMemory(line, poolPtr); {{{ makeSetValue('envPtr', 'i * ptrSize', 'poolPtr', 'i8*') }}}; poolPtr += line.length + 1; } {{{ makeSetValue('envPtr', 'strings.length * ptrSize', '0', 'i8*') }}}; }, $ENV: {}, getenv__deps: ['$ENV'], getenv__proxy: 'sync', getenv__sig: 'ii', getenv: function(name) { // char *getenv(const char *name); // http://pubs.opengroup.org/onlinepubs/009695399/functions/getenv.html if (name === 0) return 0; name = UTF8ToString(name); if (!ENV.hasOwnProperty(name)) return 0; if (_getenv.ret) _free(_getenv.ret); _getenv.ret = allocateUTF8(ENV[name]); return _getenv.ret; }, // Alias for sanitizers which intercept getenv. emscripten_get_env: 'getenv', clearenv__deps: ['$ENV', '__buildEnvironment'], clearenv__proxy: 'sync', clearenv__sig: 'i', clearenv: function() { // int clearenv (void); // http://www.gnu.org/s/hello/manual/libc/Environment-Access.html#index-clearenv-3107 ENV = {}; ___buildEnvironment(__get_environ()); return 0; }, setenv__deps: ['$ENV', '__buildEnvironment', '__setErrNo'], setenv__proxy: 'sync', setenv__sig: 'iiii', setenv: function(envname, envval, overwrite) { // int setenv(const char *envname, const char *envval, int overwrite); // http://pubs.opengroup.org/onlinepubs/009695399/functions/setenv.html if (envname === 0) { ___setErrNo({{{ cDefine('EINVAL') }}}); return -1; } var name = UTF8ToString(envname); var val = UTF8ToString(envval); if (name === '' || name.indexOf('=') !== -1) { ___setErrNo({{{ cDefine('EINVAL') }}}); return -1; } if (ENV.hasOwnProperty(name) && !overwrite) return 0; ENV[name] = val; ___buildEnvironment(__get_environ()); return 0; }, unsetenv__deps: ['$ENV', '__buildEnvironment', '__setErrNo'], unsetenv__proxy: 'sync', unsetenv__sig: 'ii', unsetenv: function(name) { // int unsetenv(const char *name); // http://pubs.opengroup.org/onlinepubs/009695399/functions/unsetenv.html if (name === 0) { ___setErrNo({{{ cDefine('EINVAL') }}}); return -1; } name = UTF8ToString(name); if (name === '' || name.indexOf('=') !== -1) { ___setErrNo({{{ cDefine('EINVAL') }}}); return -1; } if (ENV.hasOwnProperty(name)) { delete ENV[name]; ___buildEnvironment(__get_environ()); } return 0; }, putenv__deps: ['$ENV', '__buildEnvironment', '__setErrNo'], putenv__proxy: 'sync', putenv__sig: 'ii', putenv: function(string) { // int putenv(char *string); // http://pubs.opengroup.org/onlinepubs/009695399/functions/putenv.html // WARNING: According to the standard (and the glibc implementation), the // string is taken by reference so future changes are reflected. // We copy it instead, possibly breaking some uses. if (string === 0) { ___setErrNo({{{ cDefine('EINVAL') }}}); return -1; } string = UTF8ToString(string); var splitPoint = string.indexOf('=') if (string === '' || string.indexOf('=') === -1) { ___setErrNo({{{ cDefine('EINVAL') }}}); return -1; } var name = string.slice(0, splitPoint); var value = string.slice(splitPoint + 1); if (!(name in ENV) || ENV[name] !== value) { ENV[name] = value; ___buildEnvironment(__get_environ()); } return 0; }, getloadavg: function(loadavg, nelem) { // int getloadavg(double loadavg[], int nelem); // http://linux.die.net/man/3/getloadavg var limit = Math.min(nelem, 3); var doubleSize = {{{ Runtime.getNativeTypeSize('double') }}}; for (var i = 0; i < limit; i++) { {{{ makeSetValue('loadavg', 'i * doubleSize', '0.1', 'double') }}}; } return limit; }, // For compatibility, call to rand() when code requests arc4random(), although this is *not* at all // as strong as rc4 is. See https://developer.apple.com/library/mac/documentation/Darwin/Reference/ManPages/man3/arc4random.3.html arc4random: 'rand', // ========================================================================== // string.h // ========================================================================== memcpy__inline: function(dest, src, num, align) { var ret = ''; ret += makeCopyValues(dest, src, num, 'null', null, align); return ret; }, emscripten_memcpy_big: function(dest, src, num) { HEAPU8.set(HEAPU8.subarray(src, src+num), dest); }, memcpy__asm: true, memcpy__sig: 'iiii', memcpy__deps: ['emscripten_memcpy_big', 'Int8Array', 'Int32Array'], memcpy: function(dest, src, num) { dest = dest|0; src = src|0; num = num|0; var ret = 0; var aligned_dest_end = 0; var block_aligned_dest_end = 0; var dest_end = 0; // Test against a benchmarked cutoff limit for when HEAPU8.set() becomes faster to use. if ((num|0) >= 8192) { _emscripten_memcpy_big(dest|0, src|0, num|0)|0; return dest|0; } ret = dest|0; dest_end = (dest + num)|0; if ((dest&3) == (src&3)) { // The initial unaligned < 4-byte front. while (dest & 3) { if ((num|0) == 0) return ret|0; {{{ makeSetValueAsm('dest', 0, makeGetValueAsm('src', 0, 'i8'), 'i8') }}}; dest = (dest+1)|0; src = (src+1)|0; num = (num-1)|0; } aligned_dest_end = (dest_end & -4)|0; #if FAST_UNROLLED_MEMCPY_AND_MEMSET block_aligned_dest_end = (aligned_dest_end - 64)|0; while ((dest|0) <= (block_aligned_dest_end|0) ) { {{{ makeSetValueAsm('dest', 0, makeGetValueAsm('src', 0, 'i32'), 'i32') }}}; {{{ makeSetValueAsm('dest', 4, makeGetValueAsm('src', 4, 'i32'), 'i32') }}}; {{{ makeSetValueAsm('dest', 8, makeGetValueAsm('src', 8, 'i32'), 'i32') }}}; {{{ makeSetValueAsm('dest', 12, makeGetValueAsm('src', 12, 'i32'), 'i32') }}}; {{{ makeSetValueAsm('dest', 16, makeGetValueAsm('src', 16, 'i32'), 'i32') }}}; {{{ makeSetValueAsm('dest', 20, makeGetValueAsm('src', 20, 'i32'), 'i32') }}}; {{{ makeSetValueAsm('dest', 24, makeGetValueAsm('src', 24, 'i32'), 'i32') }}}; {{{ makeSetValueAsm('dest', 28, makeGetValueAsm('src', 28, 'i32'), 'i32') }}}; {{{ makeSetValueAsm('dest', 32, makeGetValueAsm('src', 32, 'i32'), 'i32') }}}; {{{ makeSetValueAsm('dest', 36, makeGetValueAsm('src', 36, 'i32'), 'i32') }}}; {{{ makeSetValueAsm('dest', 40, makeGetValueAsm('src', 40, 'i32'), 'i32') }}}; {{{ makeSetValueAsm('dest', 44, makeGetValueAsm('src', 44, 'i32'), 'i32') }}}; {{{ makeSetValueAsm('dest', 48, makeGetValueAsm('src', 48, 'i32'), 'i32') }}}; {{{ makeSetValueAsm('dest', 52, makeGetValueAsm('src', 52, 'i32'), 'i32') }}}; {{{ makeSetValueAsm('dest', 56, makeGetValueAsm('src', 56, 'i32'), 'i32') }}}; {{{ makeSetValueAsm('dest', 60, makeGetValueAsm('src', 60, 'i32'), 'i32') }}}; dest = (dest+64)|0; src = (src+64)|0; } #endif while ((dest|0) < (aligned_dest_end|0) ) { {{{ makeSetValueAsm('dest', 0, makeGetValueAsm('src', 0, 'i32'), 'i32') }}}; dest = (dest+4)|0; src = (src+4)|0; } } else { // In the unaligned copy case, unroll a bit as well. aligned_dest_end = (dest_end - 4)|0; while ((dest|0) < (aligned_dest_end|0) ) { {{{ makeSetValueAsm('dest', 0, makeGetValueAsm('src', 0, 'i8'), 'i8') }}}; {{{ makeSetValueAsm('dest', 1, makeGetValueAsm('src', 1, 'i8'), 'i8') }}}; {{{ makeSetValueAsm('dest', 2, makeGetValueAsm('src', 2, 'i8'), 'i8') }}}; {{{ makeSetValueAsm('dest', 3, makeGetValueAsm('src', 3, 'i8'), 'i8') }}}; dest = (dest+4)|0; src = (src+4)|0; } } // The remaining unaligned < 4 byte tail. while ((dest|0) < (dest_end|0)) { {{{ makeSetValueAsm('dest', 0, makeGetValueAsm('src', 0, 'i8'), 'i8') }}}; dest = (dest+1)|0; src = (src+1)|0; } return ret|0; }, memmove__sig: 'iiii', memmove__asm: true, memmove__deps: ['memcpy'], memmove: function(dest, src, num) { dest = dest|0; src = src|0; num = num|0; var ret = 0; if (((src|0) < (dest|0)) & ((dest|0) < ((src + num)|0))) { // Unlikely case: Copy backwards in a safe manner ret = dest; src = (src + num)|0; dest = (dest + num)|0; while ((num|0) > 0) { dest = (dest - 1)|0; src = (src - 1)|0; num = (num - 1)|0; {{{ makeSetValueAsm('dest', 0, makeGetValueAsm('src', 0, 'i8'), 'i8') }}}; } dest = ret; } else { _memcpy(dest, src, num) | 0; } return dest | 0; }, memset__inline: function(ptr, value, num, align) { return makeSetValues(ptr, 0, value, 'null', num, align); }, memset__sig: 'iiii', memset__asm: true, memset__deps: ['Int8Array', 'Int32Array'], memset: function(ptr, value, num) { ptr = ptr|0; value = value|0; num = num|0; var end = 0, aligned_end = 0, block_aligned_end = 0, value4 = 0; end = (ptr + num)|0; value = value & 0xff; if ((num|0) >= 67 /* 64 bytes for an unrolled loop + 3 bytes for unaligned head*/) { while ((ptr&3) != 0) { {{{ makeSetValueAsm('ptr', 0, 'value', 'i8') }}}; ptr = (ptr+1)|0; } aligned_end = (end & -4)|0; value4 = value | (value << 8) | (value << 16) | (value << 24); #if FAST_UNROLLED_MEMCPY_AND_MEMSET block_aligned_end = (aligned_end - 64)|0; while((ptr|0) <= (block_aligned_end|0)) { {{{ makeSetValueAsm('ptr', 0, 'value4', 'i32') }}}; {{{ makeSetValueAsm('ptr', 4, 'value4', 'i32') }}}; {{{ makeSetValueAsm('ptr', 8, 'value4', 'i32') }}}; {{{ makeSetValueAsm('ptr', 12, 'value4', 'i32') }}}; {{{ makeSetValueAsm('ptr', 16, 'value4', 'i32') }}}; {{{ makeSetValueAsm('ptr', 20, 'value4', 'i32') }}}; {{{ makeSetValueAsm('ptr', 24, 'value4', 'i32') }}}; {{{ makeSetValueAsm('ptr', 28, 'value4', 'i32') }}}; {{{ makeSetValueAsm('ptr', 32, 'value4', 'i32') }}}; {{{ makeSetValueAsm('ptr', 36, 'value4', 'i32') }}}; {{{ makeSetValueAsm('ptr', 40, 'value4', 'i32') }}}; {{{ makeSetValueAsm('ptr', 44, 'value4', 'i32') }}}; {{{ makeSetValueAsm('ptr', 48, 'value4', 'i32') }}}; {{{ makeSetValueAsm('ptr', 52, 'value4', 'i32') }}}; {{{ makeSetValueAsm('ptr', 56, 'value4', 'i32') }}}; {{{ makeSetValueAsm('ptr', 60, 'value4', 'i32') }}}; ptr = (ptr + 64)|0; } #endif while ((ptr|0) < (aligned_end|0) ) { {{{ makeSetValueAsm('ptr', 0, 'value4', 'i32') }}}; ptr = (ptr+4)|0; } } // The remaining bytes. while ((ptr|0) < (end|0)) { {{{ makeSetValueAsm('ptr', 0, 'value', 'i8') }}}; ptr = (ptr+1)|0; } return (end-num)|0; }, #if DECLARE_ASM_MODULE_EXPORTS llvm_memcpy_i32: 'memcpy', llvm_memcpy_i64: 'memcpy', llvm_memcpy_p0i8_p0i8_i32: 'memcpy', llvm_memcpy_p0i8_p0i8_i64: 'memcpy', llvm_memmove_i32: 'memmove', llvm_memmove_i64: 'memmove', llvm_memmove_p0i8_p0i8_i32: 'memmove', llvm_memmove_p0i8_p0i8_i64: 'memmove', llvm_memset_i32: 'memset', llvm_memset_p0i8_i32: 'memset', llvm_memset_p0i8_i64: 'memset', #else // When DECLARE_ASM_MODULE_EXPORTS==0, cannot alias asm.js functions from non-asm.js // functions, so use an intermediate function as a pass-through. _memcpy_js__deps: ['memcpy'], _memcpy_js: function(dst, src, num) { return _memcpy(dst, src, num); }, _memmove_js__deps: ['memmove'], _memmove_js: function(dst, src, num) { return _memmove(dst, src, num); }, _memset_js__deps: ['memset'], _memset_js: function(ptr, value, num) { return _memset(ptr, value, num); }, llvm_memcpy_i32: '_memcpy_js', llvm_memcpy_i64: '_memcpy_js', llvm_memcpy_p0i8_p0i8_i32: '_memcpy_js', llvm_memcpy_p0i8_p0i8_i64: '_memcpy_js', llvm_memmove_i32: '_memmove_js', llvm_memmove_i64: '_memmove_js', llvm_memmove_p0i8_p0i8_i32: '_memmove_js', llvm_memmove_p0i8_p0i8_i64: '_memmove_js', llvm_memset_i32: '_memset_js', llvm_memset_p0i8_i32: '_memset_js', llvm_memset_p0i8_i64: '_memset_js', #endif // ~DECLARE_ASM_MODULE_EXPORTS // ========================================================================== // GCC/LLVM specifics // ========================================================================== __builtin_prefetch: function(){}, // ========================================================================== // LLVM specifics // ========================================================================== llvm_va_start__inline: function(ptr) { // varargs - we received a pointer to the varargs as a final 'extra' parameter called 'varrp' // 2-word structure: struct { void* start; void* currentOffset; } return makeSetValue(ptr, 0, 'varrp', 'void*') + ';' + makeSetValue(ptr, Runtime.QUANTUM_SIZE, 0, 'void*'); }, llvm_va_end: function() {}, llvm_va_copy: function(ppdest, ppsrc) { // copy the list start {{{ makeCopyValues('ppdest', 'ppsrc', Runtime.QUANTUM_SIZE, 'null', null, 1) }}}; // copy the list's current offset (will be advanced with each call to va_arg) {{{ makeCopyValues('(ppdest+'+Runtime.QUANTUM_SIZE+')', '(ppsrc+'+Runtime.QUANTUM_SIZE+')', Runtime.QUANTUM_SIZE, 'null', null, 1) }}}; }, llvm_bswap_i16__asm: true, llvm_bswap_i16__sig: 'ii', llvm_bswap_i16: function(x) { x = x|0; return (((x&0xff)<<8) | ((x>>8)&0xff))|0; }, llvm_bswap_i32__asm: true, llvm_bswap_i32__sig: 'ii', llvm_bswap_i32: function(x) { x = x|0; return (((x&0xff)<<24) | (((x>>8)&0xff)<<16) | (((x>>16)&0xff)<<8) | (x>>>24))|0; }, llvm_bswap_i64__deps: ['llvm_bswap_i32'], llvm_bswap_i64: function(l, h) { var retl = _llvm_bswap_i32(h)>>>0; var reth = _llvm_bswap_i32(l)>>>0; {{{ makeStructuralReturn(['retl', 'reth']) }}}; }, llvm_ctlz_i8__asm: true, llvm_ctlz_i8__sig: 'ii', llvm_ctlz_i8__deps: ['Math_clz32'], llvm_ctlz_i8: function(x, isZeroUndef) { x = x | 0; isZeroUndef = isZeroUndef | 0; return (Math_clz32(x & 0xff) | 0) - 24 | 0; }, llvm_ctlz_i16__asm: true, llvm_ctlz_i16__sig: 'ii', llvm_ctlz_i16__deps: ['Math_clz32'], llvm_ctlz_i16: function(x, isZeroUndef) { x = x | 0; isZeroUndef = isZeroUndef | 0; return (Math_clz32(x & 0xffff) | 0) - 16 | 0 }, llvm_ctlz_i64__asm: true, llvm_ctlz_i64__sig: 'iii', llvm_ctlz_i64__deps: ['Math_clz32'], llvm_ctlz_i64: function(l, h, isZeroUndef) { l = l | 0; h = h | 0; isZeroUndef = isZeroUndef | 0; var ret = 0; ret = Math_clz32(h) | 0; if ((ret | 0) == 32) ret = ret + (Math_clz32(l) | 0) | 0; {{{ makeSetTempRet0('0') }}}; return ret | 0; }, #if WASM == 0 // binaryen will convert these calls to wasm anyhow llvm_cttz_i32__asm: true, #endif llvm_cttz_i32__sig: 'ii', llvm_cttz_i32__deps: ['Math_clz32'], llvm_cttz_i32: function(x) { // Note: Currently doesn't take isZeroUndef() x = x | 0; return (x ? (31 - (Math_clz32((x ^ (x - 1))) | 0) | 0) : 32) | 0; }, llvm_cttz_i64__deps: ['llvm_cttz_i32'], llvm_cttz_i64: function(l, h) { var ret = _llvm_cttz_i32(l); if (ret == 32) ret += _llvm_cttz_i32(h); {{{ makeStructuralReturn(['ret', '0']) }}}; }, llvm_ctpop_i32__asm: true, llvm_ctpop_i32__sig: 'ii', llvm_ctpop_i32__deps: ['Math_imul'], llvm_ctpop_i32: function(x) { // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel // http://bits.stephan-brumme.com/countBits.html x = x | 0; x = x - ((x >>> 1) & 0x55555555) | 0; x = (x & 0x33333333) + ((x >>> 2) & 0x33333333) | 0; return (Math_imul((x + (x >>> 4) & 252645135 /* 0xF0F0F0F, but hits uglify parse bug? */), 0x1010101) >>> 24) | 0; }, llvm_ctpop_i64__deps: ['llvm_ctpop_i32'], llvm_ctpop_i64__asm: true, llvm_ctpop_i64__sig: 'iii', llvm_ctpop_i64: function(l, h) { l = l | 0; h = h | 0; return (_llvm_ctpop_i32(l) | 0) + (_llvm_ctpop_i32(h) | 0) | 0; }, llvm_trap: function() { abort('trap!'); }, llvm_prefetch: function(){}, __assert_fail: function(condition, filename, line, func) { abort('Assertion failed: ' + UTF8ToString(condition) + ', at: ' + [filename ? UTF8ToString(filename) : 'unknown filename', line, func ? UTF8ToString(func) : 'unknown function']); }, __assert_func: function(filename, line, func, condition) { abort('Assertion failed: ' + (condition ? UTF8ToString(condition) : 'unknown condition') + ', at: ' + [filename ? UTF8ToString(filename) : 'unknown filename', line, func ? UTF8ToString(func) : 'unknown function']); }, #if WASM_BACKEND == 0 setThrew__asm: true, setThrew__sig: 'vii', setThrew: function(threw, value) { threw = threw|0; value = value|0; if ((__THREW__|0) == 0) { __THREW__ = threw; threwValue = value; } }, #endif terminate: '__cxa_call_unexpected', __gxx_personality_v0: function() { }, __gcc_personality_v0: function() { }, llvm_stacksave: function() { var self = _llvm_stacksave; if (!self.LLVM_SAVEDSTACKS) { self.LLVM_SAVEDSTACKS = []; } self.LLVM_SAVEDSTACKS.push(stackSave()); return self.LLVM_SAVEDSTACKS.length-1; }, llvm_stackrestore: function(p) { var self = _llvm_stacksave; var ret = self.LLVM_SAVEDSTACKS[p]; self.LLVM_SAVEDSTACKS.splice(p, 1); stackRestore(ret); }, #if MINIMAL_RUNTIME $abortStackOverflow: function(allocSize) { abort('Stack overflow! Attempted to allocate ' + allocSize + ' bytes on the stack, but stack has only ' + (STACK_MAX - stackSave() + allocSize) + ' bytes available!'); }, $stackAlloc__asm: true, $stackAlloc__sig: 'ii', $stackAlloc__deps: ['$abortStackOverflow'], $stackAlloc: function(size) { size = size|0; var ret = 0; ret = STACKTOP; STACKTOP = (STACKTOP + size)|0; STACKTOP = (STACKTOP + 15)&-16; #if ASSERTIONS || STACK_OVERFLOW_CHECK >= 2 if ((STACKTOP|0) >= (STACK_MAX|0)) abortStackOverflow(size|0); #endif return ret|0; }, $stackSave__asm: true, $stackSave__sig: 'i', $stackSave: function() { return STACKTOP|0; }, $stackRestore__asm: true, $stackRestore__sig: 'vi', $stackRestore: function(top) { top = top|0; STACKTOP = top; }, $establishStackSpace__asm: true, $establishStackSpace__sig: 'vii', $establishStackSpace: function(stackBase, stackMax) { stackBase = stackBase|0; stackMax = stackMax|0; STACKTOP = stackBase; STACK_MAX = stackMax; }, #if WASM_BACKEND == 0 $setThrew__asm: true, $setThrew__sig: 'vii', $setThrew: function(threw, value) { threw = threw|0; value = value|0; if ((__THREW__|0) == 0) { __THREW__ = threw; threwValue = value; } }, #endif #endif #if MINIMAL_RUNTIME && !ASSERTIONS __cxa_pure_virtual__sig: 'v', __cxa_pure_virtual: 'abort', #else __cxa_pure_virtual: function() { #if !MINIMAL_RUNTIME ABORT = true; #endif throw 'Pure virtual function called!'; }, #endif llvm_flt_rounds: function() { return -1; // 'indeterminable' for FLT_ROUNDS }, llvm_expect_i32__inline: function(val, expected) { return '(' + val + ')'; }, llvm_objectsize_i32: function() { return -1 }, // TODO: support this llvm_dbg_declare__inline: function() { throw 'llvm_debug_declare' }, // avoid warning llvm_bitreverse_i32__asm: true, llvm_bitreverse_i32__sig: 'ii', llvm_bitreverse_i32: function(x) { x = x|0; x = ((x & 0xaaaaaaaa) >>> 1) | ((x & 0x55555555) << 1); x = ((x & 0xcccccccc) >>> 2) | ((x & 0x33333333) << 2); x = ((x & 0xf0f0f0f0) >>> 4) | ((x & 0x0f0f0f0f) << 4); x = ((x & 0xff00ff00) >>> 8) | ((x & 0x00ff00ff) << 8); return (x >>> 16) | (x << 16); }, // llvm-nacl llvm_nacl_atomic_store_i32__inline: true, llvm_nacl_atomic_cmpxchg_i8__inline: true, llvm_nacl_atomic_cmpxchg_i16__inline: true, llvm_nacl_atomic_cmpxchg_i32__inline: true, // ========================================================================== // llvm-mono integration // ========================================================================== llvm_mono_load_i8_p0i8: function(ptr) { return {{{ makeGetValue('ptr', 0, 'i8') }}}; }, llvm_mono_store_i8_p0i8: function(value, ptr) { {{{ makeSetValue('ptr', 0, 'value', 'i8') }}}; }, llvm_mono_load_i16_p0i16: function(ptr) { return {{{ makeGetValue('ptr', 0, 'i16') }}}; }, llvm_mono_store_i16_p0i16: function(value, ptr) { {{{ makeSetValue('ptr', 0, 'value', 'i16') }}}; }, llvm_mono_load_i32_p0i32: function(ptr) { return {{{ makeGetValue('ptr', 0, 'i32') }}}; }, llvm_mono_store_i32_p0i32: function(value, ptr) { {{{ makeSetValue('ptr', 0, 'value', 'i32') }}}; }, // ========================================================================== // math.h // ========================================================================== cos: 'Math_cos', cosf: 'Math_cos', cosl: 'Math_cos', sin: 'Math_sin', sinf: 'Math_sin', sinl: 'Math_sin', tan: 'Math_tan', tanf: 'Math_tan', tanl: 'Math_tan', acos: 'Math_acos', acosf: 'Math_acos', acosl: 'Math_acos', asin: 'Math_asin', asinf: 'Math_asin', asinl: 'Math_asin', atan: 'Math_atan', atanf: 'Math_atan', atanl: 'Math_atan', atan2: 'Math_atan2', atan2f: 'Math_atan2', atan2l: 'Math_atan2', exp: 'Math_exp', expf: 'Math_exp', expl: 'Math_exp', log: 'Math_log', logf: 'Math_log', logl: 'Math_log', sqrt: 'Math_sqrt', sqrtf: 'Math_sqrt', sqrtl: 'Math_sqrt', fabs: 'Math_abs', fabsf: 'Math_abs', fabsl: 'Math_abs', llvm_fabs_f32: 'Math_abs', llvm_fabs_f64: 'Math_abs', ceil: 'Math_ceil', ceilf: 'Math_ceil', ceill: 'Math_ceil', floor: 'Math_floor', floorf: 'Math_floor', floorl: 'Math_floor', pow: 'Math_pow', powf: 'Math_pow', powl: 'Math_pow', llvm_sqrt_f32: 'Math_sqrt', llvm_sqrt_f64: 'Math_sqrt', llvm_pow_f32: 'Math_pow', llvm_pow_f64: 'Math_pow', llvm_powi_f32: 'Math_pow', llvm_powi_f64: 'Math_pow', llvm_log_f32: 'Math_log', llvm_log_f64: 'Math_log', llvm_exp_f32: 'Math_exp', llvm_exp_f64: 'Math_exp', llvm_cos_f32: 'Math_cos', llvm_cos_f64: 'Math_cos', llvm_sin_f32: 'Math_sin', llvm_sin_f64: 'Math_sin', llvm_trunc_f32: 'Math_trunc', llvm_trunc_f64: 'Math_trunc', llvm_ceil_f32: 'Math_ceil', llvm_ceil_f64: 'Math_ceil', llvm_floor_f32: 'Math_floor', llvm_floor_f64: 'Math_floor', llvm_exp2_f32: function(x) { return Math.pow(2, x); }, llvm_exp2_f64__sig: 'dd', llvm_exp2_f64: 'llvm_exp2_f32', llvm_log2_f32: function(x) { return Math.log(x) / Math.LN2; // TODO: Math.log2, when browser support is there }, llvm_log2_f64__sig: 'dd', llvm_log2_f64: 'llvm_log2_f32', llvm_log10_f32: function(x) { return Math.log(x) / Math.LN10; // TODO: Math.log10, when browser support is there }, llvm_log10_f64__sig: 'dd', llvm_log10_f64: 'llvm_log10_f32', llvm_copysign_f32: function(x, y) { return y < 0 || (y === 0 && 1/y < 0) ? -Math_abs(x) : Math_abs(x); }, llvm_copysign_f64: function(x, y) { return y < 0 || (y === 0 && 1/y < 0) ? -Math_abs(x) : Math_abs(x); }, round__asm: true, round__sig: 'dd', round__deps: ['Math_floor', 'Math_ceil'], round: function(d) { d = +d; return d >= +0 ? +Math_floor(d + +0.5) : +Math_ceil(d - +0.5); }, roundf__asm: true, roundf__sig: 'ff', roundf__deps: ['Math_floor', 'Math_ceil'], roundf: function(d) { d = +d; return d >= +0 ? +Math_floor(d + +0.5) : +Math_ceil(d - +0.5); }, llvm_round_f64__asm: true, llvm_round_f64__sig: 'dd', llvm_round_f64__deps: ['Math_floor', 'Math_ceil'], llvm_round_f64: function(d) { d = +d; return d >= +0 ? +Math_floor(d + +0.5) : +Math_ceil(d - +0.5); }, llvm_round_f32__asm: true, llvm_round_f32__sig: 'ff', llvm_round_f32__deps: ['Math_floor', 'Math_ceil'], llvm_round_f32: function(f) { f = +f; return f >= +0 ? +Math_floor(f + +0.5) : +Math_ceil(f - +0.5); // TODO: use fround? }, rintf__asm: true, rintf__sig: 'ff', rintf__deps: ['round', 'Math_floor'], rintf: function(f) { f = +f; return (f - +Math_floor(f) != .5) ? +_round(f) : +_round(f / +2) * +2; }, // TODO: fround? llvm_rint_f32__asm: true, llvm_rint_f32__sig: 'ff', llvm_rint_f32__deps: ['roundf', 'Math_floor'], llvm_rint_f32: function(f) { f = +f; return (f - +Math_floor(f) != .5) ? +_roundf(f) : +_roundf(f / +2) * +2; }, llvm_rint_f64__asm: true, llvm_rint_f64__sig: 'dd', llvm_rint_f64__deps: ['round', 'Math_floor'], llvm_rint_f64: function(f) { f = +f; return (f - +Math_floor(f) != .5) ? +_round(f) : +_round(f / +2) * +2; }, // TODO: fround? llvm_nearbyint_f32__asm: true, llvm_nearbyint_f32__sig: 'ff', llvm_nearbyint_f32__deps: ['roundf', 'Math_floor'], llvm_nearbyint_f32: function(f) { f = +f; return (f - +Math_floor(f) != .5) ? +_roundf(f) : +_roundf(f / +2) * +2; }, llvm_nearbyint_f64__asm: true, llvm_nearbyint_f64__sig: 'dd', llvm_nearbyint_f64__deps: ['round', 'Math_floor'], llvm_nearbyint_f64: function(f) { f = +f; return (f - +Math_floor(f) != .5) ? +_round(f) : +_round(f / +2) * +2; }, // min/max num do not quite match the behavior of JS and wasm min/max: // llvm and libc return the non-NaN if one is NaN, while JS and wasm // return the NaN :( // see also https://github.com/WebAssembly/design/issues/214 llvm_minnum_f32__asm: true, llvm_minnum_f32__sig: 'ff', llvm_minnum_f32__deps: ['Math_min'], llvm_minnum_f32: function(x, y) { x = +x; y = +y; if (x != x) return +y; if (y != y) return +x; return +Math_min(+x, +y); }, llvm_minnum_f64__asm: true, llvm_minnum_f64__sig: 'dd', llvm_minnum_f64__deps: ['Math_min'], llvm_minnum_f64: function(x, y) { x = +x; y = +y; if (x != x) return +y; if (y != y) return +x; return +Math_min(+x, +y); }, llvm_maxnum_f32__asm: true, llvm_maxnum_f32__sig: 'ff', llvm_maxnum_f32__deps: ['Math_max'], llvm_maxnum_f32: function(x, y) { x = +x; y = +y; if (x != x) return +y; if (y != y) return +x; return +Math_max(+x, +y); }, llvm_maxnum_f64__asm: true, llvm_maxnum_f64__sig: 'dd', llvm_maxnum_f64__deps: ['Math_max'], llvm_maxnum_f64: function(x, y) { x = +x; y = +y; if (x != x) return +y; if (y != y) return +x; return +Math_max(+x, +y); }, _reallyNegative: function(x) { return x < 0 || (x === 0 && (1/x) === -Infinity); }, // ========================================================================== // dlfcn.h - Dynamic library loading // // Some limitations: // // * Minification on each file separately may not work, as they will // have different shortened names. You can in theory combine them, then // minify, then split... perhaps. // // * LLVM optimizations may fail. If the child wants to access a function // in the parent, LLVM opts may remove it from the parent when it is // being compiled. Not sure how to tell LLVM to not do so. // ========================================================================== #if MAIN_MODULE == 0 dlopen: function(/* ... */) { abort("To use dlopen, you need to use Emscripten's linking support, see https://github.com/emscripten-core/emscripten/wiki/Linking"); }, dlclose: 'dlopen', dlsym: 'dlopen', dlerror: 'dlopen', dladdr: 'dlopen', #else // MAIN_MODULE != 0 $DLFCN: { error: null, errorMsg: null, }, // void* dlopen(const char* filename, int flag); dlopen__deps: ['$DLFCN', '$FS', '$ENV'], dlopen__proxy: 'sync', dlopen__sig: 'iii', dlopen: function(filenameAddr, flag) { // void *dlopen(const char *file, int mode); // http://pubs.opengroup.org/onlinepubs/009695399/functions/dlopen.html var searchpaths = []; var filename; if (filenameAddr === 0) { filename = '__self__'; } else { filename = UTF8ToString(filenameAddr); var isValidFile = function (filename) { var target = FS.findObject(filename); return target && !target.isFolder && !target.isDevice; }; if (!isValidFile(filename)) { if (ENV['LD_LIBRARY_PATH']) { searchpaths = ENV['LD_LIBRARY_PATH'].split(':'); } for (var ident in searchpaths) { var searchfile = PATH.join2(searchpaths[ident], filename); if (isValidFile(searchfile)) { filename = searchfile; break; } } } } // We don't care about RTLD_NOW and RTLD_LAZY. var flags = { global: Boolean(flag & 256), // RTLD_GLOBAL nodelete: Boolean(flag & 4096), // RTLD_NODELETE fs: FS, // load libraries from provided filesystem } try { handle = loadDynamicLibrary(filename, flags) } catch (e) { #if ASSERTIONS err('Error in loading dynamic library ' + filename + ": " + e); #endif DLFCN.errorMsg = 'Could not load dynamic lib: ' + filename + '\n' + e; return 0; } return handle; }, // int dlclose(void* handle); dlclose__deps: ['$DLFCN'], dlclose__proxy: 'sync', dlclose__sig: 'ii', dlclose: function(handle) { // int dlclose(void *handle); // http://pubs.opengroup.org/onlinepubs/009695399/functions/dlclose.html if (!LDSO.loadedLibs[handle]) { DLFCN.errorMsg = 'Tried to dlclose() unopened handle: ' + handle; return 1; } else { var lib_record = LDSO.loadedLibs[handle]; if (--lib_record.refcount == 0) { if (lib_record.module.cleanups) { lib_record.module.cleanups.forEach(function(cleanup) { cleanup() }); } delete LDSO.loadedLibNames[lib_record.name]; delete LDSO.loadedLibs[handle]; } return 0; } }, // void* dlsym(void* handle, const char* symbol); dlsym__deps: ['$DLFCN'], dlsym__proxy: 'sync', dlsym__sig: 'iii', dlsym: function(handle, symbol) { // void *dlsym(void *restrict handle, const char *restrict name); // http://pubs.opengroup.org/onlinepubs/009695399/functions/dlsym.html symbol = UTF8ToString(symbol); if (!LDSO.loadedLibs[handle]) { DLFCN.errorMsg = 'Tried to dlsym() from an unopened handle: ' + handle; return 0; } var lib = LDSO.loadedLibs[handle]; var isMainModule = lib.module == Module; var mangled = '_' + symbol; var modSymbol = mangled; #if WASM_BACKEND if (!isMainModule) { modSymbol = symbol; } #endif if (!lib.module.hasOwnProperty(modSymbol)) { DLFCN.errorMsg = ('Tried to lookup unknown symbol "' + modSymbol + '" in dynamic lib: ' + lib.name); return 0; } var result = lib.module[modSymbol]; #if WASM // Attempt to get the real "unwrapped" symbol so we have more chance of // getting wasm function which can be added to a table. if (isMainModule) { #if WASM_BACKEND var asmSymbol = symbol; #else var asmSymbol = mangled; #endif if (lib.module["asm"][asmSymbol]) { result = lib.module["asm"][asmSymbol]; } } #endif if (typeof result !== 'function') return result; #if WASM && EMULATE_FUNCTION_POINTER_CASTS // for wasm with emulated function pointers, the i64 ABI is used for all // function calls, so we can't just call addFunction on something JS // can call (which does not use that ABI), as the function pointer would // not be usable from wasm. instead, the wasm has exported function pointers // for everything we need, with prefix fp$, use those result = lib.module['fp$' + symbol]; if (typeof result === 'object') { // a breaking change in the wasm spec, globals are now objects // https://github.com/WebAssembly/mutable-global/issues/1 result = result.value; } #if ASSERTIONS assert(typeof result === 'number', 'could not find function pointer for ' + symbol); #endif // ASSERTIONS return result; #else // WASM && EMULATE_FUNCTION_POINTER_CASTS #if WASM // Insert the function into the wasm table. Since we know the function // comes directly from the loaded wasm module we can insert it directly // into the table, avoiding any JS interaction. return addFunctionWasm(result); #else // convert the exported function into a function pointer using our generic // JS mechanism. return addFunction(result); #endif // WASM #endif // WASM && EMULATE_FUNCTION_POINTER_CASTS }, // char* dlerror(void); dlerror__deps: ['$DLFCN', '$stringToNewUTF8'], dlerror__proxy: 'sync', dlerror__sig: 'i', dlerror: function() { // char *dlerror(void); // http://pubs.opengroup.org/onlinepubs/009695399/functions/dlerror.html if (DLFCN.errorMsg === null) { return 0; } else { if (DLFCN.error) _free(DLFCN.error); DLFCN.error = stringToNewUTF8(DLFCN.errorMsg); DLFCN.errorMsg = null; return DLFCN.error; } }, dladdr__deps: ['$stringToNewUTF8'], dladdr__proxy: 'sync', dladdr__sig: 'iii', dladdr: function(addr, info) { // report all function pointers as coming from this program itself XXX not really correct in any way var fname = stringToNewUTF8(thisProgram || './this.program'); // XXX leak {{{ makeSetValue('info', 0, 'fname', 'i32') }}}; {{{ makeSetValue('info', Runtime.QUANTUM_SIZE, '0', 'i32') }}}; {{{ makeSetValue('info', Runtime.QUANTUM_SIZE*2, '0', 'i32') }}}; {{{ makeSetValue('info', Runtime.QUANTUM_SIZE*3, '0', 'i32') }}}; return 1; }, #endif // MAIN_MODULE != 0 // ========================================================================== // pwd.h // ========================================================================== // TODO: Implement. // http://pubs.opengroup.org/onlinepubs/009695399/basedefs/pwd.h.html getpwuid: function(uid) { return 0; // NULL }, // ========================================================================== // time.h // ========================================================================== clock: function() { if (_clock.start === undefined) _clock.start = Date.now(); return ((Date.now() - _clock.start) * ({{{ cDefine('CLOCKS_PER_SEC') }}} / 1000))|0; }, time: function(ptr) { var ret = (Date.now()/1000)|0; if (ptr) { {{{ makeSetValue('ptr', 0, 'ret', 'i32') }}}; } return ret; }, difftime: function(time1, time0) { return time1 - time0; }, // Statically allocated time struct. #if USE_PTHREADS __tm_current: '; if (ENVIRONMENT_IS_PTHREAD) ___tm_current = PthreadWorkerInit.___tm_current; else PthreadWorkerInit.___tm_current = ___tm_current = {{{ makeStaticAlloc(C_STRUCTS.tm.__size__) }}}', __tm_timezone: '; if (ENVIRONMENT_IS_PTHREAD) ___tm_timezone = PthreadWorkerInit.___tm_timezone; else PthreadWorkerInit.___tm_timezone = ___tm_timezone = {{{ makeStaticString("GMT") }}}', __tm_formatted: '; if (ENVIRONMENT_IS_PTHREAD) ___tm_formatted = PthreadWorkerInit.___tm_formatted; else PthreadWorkerInit.___tm_formatted = ___tm_formatted = {{{ makeStaticAlloc(C_STRUCTS.tm.__size__) }}}', #else __tm_current: '{{{ makeStaticAlloc(C_STRUCTS.tm.__size__) }}}', // Statically allocated copy of the string "GMT" for gmtime() to point to __tm_timezone: '{{{ makeStaticString("GMT") }}}', // Statically allocated time strings. __tm_formatted: '{{{ makeStaticAlloc(C_STRUCTS.tm.__size__) }}}', #endif mktime__deps: ['tzset'], mktime: function(tmPtr) { _tzset(); var date = new Date({{{ makeGetValue('tmPtr', C_STRUCTS.tm.tm_year, 'i32') }}} + 1900, {{{ makeGetValue('tmPtr', C_STRUCTS.tm.tm_mon, 'i32') }}}, {{{ makeGetValue('tmPtr', C_STRUCTS.tm.tm_mday, 'i32') }}}, {{{ makeGetValue('tmPtr', C_STRUCTS.tm.tm_hour, 'i32') }}}, {{{ makeGetValue('tmPtr', C_STRUCTS.tm.tm_min, 'i32') }}}, {{{ makeGetValue('tmPtr', C_STRUCTS.tm.tm_sec, 'i32') }}}, 0); // There's an ambiguous hour when the time goes back; the tm_isdst field is // used to disambiguate it. Date() basically guesses, so we fix it up if it // guessed wrong, or fill in tm_isdst with the guess if it's -1. var dst = {{{ makeGetValue('tmPtr', C_STRUCTS.tm.tm_isdst, 'i32') }}}; var guessedOffset = date.getTimezoneOffset(); var start = new Date(date.getFullYear(), 0, 1); var summerOffset = new Date(2000, 6, 1).getTimezoneOffset(); var winterOffset = start.getTimezoneOffset(); var dstOffset = Math.min(winterOffset, summerOffset); // DST is in December in South if (dst < 0) { // Attention: some regions don't have DST at all. {{{ makeSetValue('tmPtr', C_STRUCTS.tm.tm_isdst, 'Number(summerOffset != winterOffset && dstOffset == guessedOffset)', 'i32') }}}; } else if ((dst > 0) != (dstOffset == guessedOffset)) { var nonDstOffset = Math.max(winterOffset, summerOffset); var trueOffset = dst > 0 ? dstOffset : nonDstOffset; // Don't try setMinutes(date.getMinutes() + ...) -- it's messed up. date.setTime(date.getTime() + (trueOffset - guessedOffset)*60000); } {{{ makeSetValue('tmPtr', C_STRUCTS.tm.tm_wday, 'date.getDay()', 'i32') }}}; var yday = ((date.getTime() - start.getTime()) / (1000 * 60 * 60 * 24))|0; {{{ makeSetValue('tmPtr', C_STRUCTS.tm.tm_yday, 'yday', 'i32') }}}; return (date.getTime() / 1000)|0; }, timelocal: 'mktime', gmtime__deps: ['__tm_current', 'gmtime_r'], gmtime: function(time) { return _gmtime_r(time, ___tm_current); }, gmtime_r__deps: ['__tm_timezone'], gmtime_r: function(time, tmPtr) { var date = new Date({{{ makeGetValue('time', 0, 'i32') }}}*1000); {{{ makeSetValue('tmPtr', C_STRUCTS.tm.tm_sec, 'date.getUTCSeconds()', 'i32') }}}; {{{ makeSetValue('tmPtr', C_STRUCTS.tm.tm_min, 'date.getUTCMinutes()', 'i32') }}}; {{{ makeSetValue('tmPtr', C_STRUCTS.tm.tm_hour, 'date.getUTCHours()', 'i32') }}}; {{{ makeSetValue('tmPtr', C_STRUCTS.tm.tm_mday, 'date.getUTCDate()', 'i32') }}}; {{{ makeSetValue('tmPtr', C_STRUCTS.tm.tm_mon, 'date.getUTCMonth()', 'i32') }}}; {{{ makeSetValue('tmPtr', C_STRUCTS.tm.tm_year, 'date.getUTCFullYear()-1900', 'i32') }}}; {{{ makeSetValue('tmPtr', C_STRUCTS.tm.tm_wday, 'date.getUTCDay()', 'i32') }}}; {{{ makeSetValue('tmPtr', C_STRUCTS.tm.tm_gmtoff, '0', 'i32') }}}; {{{ makeSetValue('tmPtr', C_STRUCTS.tm.tm_isdst, '0', 'i32') }}}; var start = Date.UTC(date.getUTCFullYear(), 0, 1, 0, 0, 0, 0); var yday = ((date.getTime() - start) / (1000 * 60 * 60 * 24))|0; {{{ makeSetValue('tmPtr', C_STRUCTS.tm.tm_yday, 'yday', 'i32') }}}; {{{ makeSetValue('tmPtr', C_STRUCTS.tm.tm_zone, '___tm_timezone', 'i32') }}}; return tmPtr; }, timegm__deps: ['tzset'], timegm: function(tmPtr) { _tzset(); var time = Date.UTC({{{ makeGetValue('tmPtr', C_STRUCTS.tm.tm_year, 'i32') }}} + 1900, {{{ makeGetValue('tmPtr', C_STRUCTS.tm.tm_mon, 'i32') }}}, {{{ makeGetValue('tmPtr', C_STRUCTS.tm.tm_mday, 'i32') }}}, {{{ makeGetValue('tmPtr', C_STRUCTS.tm.tm_hour, 'i32') }}}, {{{ makeGetValue('tmPtr', C_STRUCTS.tm.tm_min, 'i32') }}}, {{{ makeGetValue('tmPtr', C_STRUCTS.tm.tm_sec, 'i32') }}}, 0); var date = new Date(time); {{{ makeSetValue('tmPtr', C_STRUCTS.tm.tm_wday, 'date.getUTCDay()', 'i32') }}}; var start = Date.UTC(date.getUTCFullYear(), 0, 1, 0, 0, 0, 0); var yday = ((date.getTime() - start) / (1000 * 60 * 60 * 24))|0; {{{ makeSetValue('tmPtr', C_STRUCTS.tm.tm_yday, 'yday', 'i32') }}}; return (date.getTime() / 1000)|0; }, localtime__deps: ['__tm_current', 'localtime_r'], localtime: function(time) { return _localtime_r(time, ___tm_current); }, localtime_r__deps: ['__tm_timezone', 'tzset'], localtime_r: function(time, tmPtr) { _tzset(); var date = new Date({{{ makeGetValue('time', 0, 'i32') }}}*1000); {{{ makeSetValue('tmPtr', C_STRUCTS.tm.tm_sec, 'date.getSeconds()', 'i32') }}}; {{{ makeSetValue('tmPtr', C_STRUCTS.tm.tm_min, 'date.getMinutes()', 'i32') }}}; {{{ makeSetValue('tmPtr', C_STRUCTS.tm.tm_hour, 'date.getHours()', 'i32') }}}; {{{ makeSetValue('tmPtr', C_STRUCTS.tm.tm_mday, 'date.getDate()', 'i32') }}}; {{{ makeSetValue('tmPtr', C_STRUCTS.tm.tm_mon, 'date.getMonth()', 'i32') }}}; {{{ makeSetValue('tmPtr', C_STRUCTS.tm.tm_year, 'date.getFullYear()-1900', 'i32') }}}; {{{ makeSetValue('tmPtr', C_STRUCTS.tm.tm_wday, 'date.getDay()', 'i32') }}}; var start = new Date(date.getFullYear(), 0, 1); var yday = ((date.getTime() - start.getTime()) / (1000 * 60 * 60 * 24))|0; {{{ makeSetValue('tmPtr', C_STRUCTS.tm.tm_yday, 'yday', 'i32') }}}; {{{ makeSetValue('tmPtr', C_STRUCTS.tm.tm_gmtoff, '-(date.getTimezoneOffset() * 60)', 'i32') }}}; // Attention: DST is in December in South, and some regions don't have DST at all. var summerOffset = new Date(2000, 6, 1).getTimezoneOffset(); var winterOffset = start.getTimezoneOffset(); var dst = (summerOffset != winterOffset && date.getTimezoneOffset() == Math.min(winterOffset, summerOffset))|0; {{{ makeSetValue('tmPtr', C_STRUCTS.tm.tm_isdst, 'dst', 'i32') }}}; var zonePtr = {{{ makeGetValue('__get_tzname()', 'dst ? ' + Runtime.QUANTUM_SIZE + ' : 0', 'i32') }}}; {{{ makeSetValue('tmPtr', C_STRUCTS.tm.tm_zone, 'zonePtr', 'i32') }}}; return tmPtr; }, asctime__deps: ['__tm_formatted', 'asctime_r'], asctime: function(tmPtr) { return _asctime_r(tmPtr, ___tm_formatted); }, asctime_r__deps: ['__tm_formatted', 'mktime'], asctime_r: function(tmPtr, buf) { var date = { tm_sec: {{{ makeGetValue('tmPtr', C_STRUCTS.tm.tm_sec, 'i32') }}}, tm_min: {{{ makeGetValue('tmPtr', C_STRUCTS.tm.tm_min, 'i32') }}}, tm_hour: {{{ makeGetValue('tmPtr', C_STRUCTS.tm.tm_hour, 'i32') }}}, tm_mday: {{{ makeGetValue('tmPtr', C_STRUCTS.tm.tm_mday, 'i32') }}}, tm_mon: {{{ makeGetValue('tmPtr', C_STRUCTS.tm.tm_mon, 'i32') }}}, tm_year: {{{ makeGetValue('tmPtr', C_STRUCTS.tm.tm_year, 'i32') }}}, tm_wday: {{{ makeGetValue('tmPtr', C_STRUCTS.tm.tm_wday, 'i32') }}} }; var days = [ "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" ]; var months = [ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" ]; var s = days[date.tm_wday] + ' ' + months[date.tm_mon] + (date.tm_mday < 10 ? ' ' : ' ') + date.tm_mday + (date.tm_hour < 10 ? ' 0' : ' ') + date.tm_hour + (date.tm_min < 10 ? ':0' : ':') + date.tm_min + (date.tm_sec < 10 ? ':0' : ':') + date.tm_sec + ' ' + (1900 + date.tm_year) + "\n"; // asctime_r is specced to behave in an undefined manner if the algorithm would attempt // to write out more than 26 bytes (including the null terminator). // See http://pubs.opengroup.org/onlinepubs/9699919799/functions/asctime.html // Our undefined behavior is to truncate the write to at most 26 bytes, including null terminator. stringToUTF8(s, buf, 26); return buf; }, ctime__deps: ['__tm_current', 'ctime_r'], ctime: function(timer) { return _ctime_r(timer, ___tm_current); }, ctime_r__deps: ['localtime_r', 'asctime_r'], ctime_r: function(time, buf) { var stack = stackSave(); var rv = _asctime_r(_localtime_r(time, stackAlloc({{{ C_STRUCTS.tm.__size__ }}})), buf); stackRestore(stack); return rv; }, dysize: function(year) { var leap = ((year % 4 == 0) && ((year % 100 != 0) || (year % 400 == 0))); return leap ? 366 : 365; }, // TODO: Initialize these to defaults on startup from system settings. // Note: glibc has one fewer underscore for all of these. Also used in other related functions (timegm) tzset__proxy: 'sync', tzset__sig: 'v', tzset: function() { // TODO: Use (malleable) environment variables instead of system settings. if (_tzset.called) return; _tzset.called = true; // timezone is specified as seconds west of UTC ("The external variable // `timezone` shall be set to the difference, in seconds, between // Coordinated Universal Time (UTC) and local standard time."), the same // as returned by getTimezoneOffset(). // See http://pubs.opengroup.org/onlinepubs/009695399/functions/tzset.html {{{ makeSetValue('__get_timezone()', '0', '(new Date()).getTimezoneOffset() * 60', 'i32') }}}; var winter = new Date(2000, 0, 1); var summer = new Date(2000, 6, 1); {{{ makeSetValue('__get_daylight()', '0', 'Number(winter.getTimezoneOffset() != summer.getTimezoneOffset())', 'i32') }}}; function extractZone(date) { var match = date.toTimeString().match(/\(([A-Za-z ]+)\)$/); return match ? match[1] : "GMT"; }; var winterName = extractZone(winter); var summerName = extractZone(summer); var winterNamePtr = allocate(intArrayFromString(winterName), 'i8', ALLOC_NORMAL); var summerNamePtr = allocate(intArrayFromString(summerName), 'i8', ALLOC_NORMAL); if (summer.getTimezoneOffset() < winter.getTimezoneOffset()) { // Northern hemisphere {{{ makeSetValue('__get_tzname()', '0', 'winterNamePtr', 'i32') }}}; {{{ makeSetValue('__get_tzname()', Runtime.QUANTUM_SIZE, 'summerNamePtr', 'i32') }}}; } else { {{{ makeSetValue('__get_tzname()', '0', 'summerNamePtr', 'i32') }}}; {{{ makeSetValue('__get_tzname()', Runtime.QUANTUM_SIZE, 'winterNamePtr', 'i32') }}}; } }, stime__deps: ['__setErrNo'], stime: function(when) { ___setErrNo({{{ cDefine('EPERM') }}}); return -1; }, __map_file__deps: ['__setErrNo'], __map_file: function(pathname, size) { ___setErrNo({{{ cDefine('EPERM') }}}); return -1; }, _MONTH_DAYS_REGULAR: [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31], _MONTH_DAYS_LEAP: [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31], _isLeapYear: function(year) { return year%4 === 0 && (year%100 !== 0 || year%400 === 0); }, _arraySum: function(array, index) { var sum = 0; for (var i = 0; i <= index; sum += array[i++]); return sum; }, _addDays__deps: ['_isLeapYear', '_MONTH_DAYS_LEAP', '_MONTH_DAYS_REGULAR'], _addDays: function(date, days) { var newDate = new Date(date.getTime()); while(days > 0) { var leap = __isLeapYear(newDate.getFullYear()); var currentMonth = newDate.getMonth(); var daysInCurrentMonth = (leap ? __MONTH_DAYS_LEAP : __MONTH_DAYS_REGULAR)[currentMonth]; if (days > daysInCurrentMonth-newDate.getDate()) { // we spill over to next month days -= (daysInCurrentMonth-newDate.getDate()+1); newDate.setDate(1); if (currentMonth < 11) { newDate.setMonth(currentMonth+1) } else { newDate.setMonth(0); newDate.setFullYear(newDate.getFullYear()+1); } } else { // we stay in current month newDate.setDate(newDate.getDate()+days); return newDate; } } return newDate; }, strftime__deps: ['_isLeapYear', '_arraySum', '_addDays', '_MONTH_DAYS_REGULAR', '_MONTH_DAYS_LEAP'], strftime: function(s, maxsize, format, tm) { // size_t strftime(char *restrict s, size_t maxsize, const char *restrict format, const struct tm *restrict timeptr); // http://pubs.opengroup.org/onlinepubs/009695399/functions/strftime.html var tm_zone = {{{ makeGetValue('tm', C_STRUCTS.tm.tm_zone, 'i32') }}}; var date = { tm_sec: {{{ makeGetValue('tm', C_STRUCTS.tm.tm_sec, 'i32') }}}, tm_min: {{{ makeGetValue('tm', C_STRUCTS.tm.tm_min, 'i32') }}}, tm_hour: {{{ makeGetValue('tm', C_STRUCTS.tm.tm_hour, 'i32') }}}, tm_mday: {{{ makeGetValue('tm', C_STRUCTS.tm.tm_mday, 'i32') }}}, tm_mon: {{{ makeGetValue('tm', C_STRUCTS.tm.tm_mon, 'i32') }}}, tm_year: {{{ makeGetValue('tm', C_STRUCTS.tm.tm_year, 'i32') }}}, tm_wday: {{{ makeGetValue('tm', C_STRUCTS.tm.tm_wday, 'i32') }}}, tm_yday: {{{ makeGetValue('tm', C_STRUCTS.tm.tm_yday, 'i32') }}}, tm_isdst: {{{ makeGetValue('tm', C_STRUCTS.tm.tm_isdst, 'i32') }}}, tm_gmtoff: {{{ makeGetValue('tm', C_STRUCTS.tm.tm_gmtoff, 'i32') }}}, tm_zone: tm_zone ? UTF8ToString(tm_zone) : '' }; var pattern = UTF8ToString(format); // expand format var EXPANSION_RULES_1 = { '%c': '%a %b %d %H:%M:%S %Y', // Replaced by the locale's appropriate date and time representation - e.g., Mon Aug 3 14:02:01 2013 '%D': '%m/%d/%y', // Equivalent to %m / %d / %y '%F': '%Y-%m-%d', // Equivalent to %Y - %m - %d '%h': '%b', // Equivalent to %b '%r': '%I:%M:%S %p', // Replaced by the time in a.m. and p.m. notation '%R': '%H:%M', // Replaced by the time in 24-hour notation '%T': '%H:%M:%S', // Replaced by the time '%x': '%m/%d/%y', // Replaced by the locale's appropriate date representation '%X': '%H:%M:%S', // Replaced by the locale's appropriate time representation // Modified Conversion Specifiers '%Ec': '%c', // Replaced by the locale's alternative appropriate date and time representation. '%EC': '%C', // Replaced by the name of the base year (period) in the locale's alternative representation. '%Ex': '%m/%d/%y', // Replaced by the locale's alternative date representation. '%EX': '%H:%M:%S', // Replaced by the locale's alternative time representation. '%Ey': '%y', // Replaced by the offset from %EC (year only) in the locale's alternative representation. '%EY': '%Y', // Replaced by the full alternative year representation. '%Od': '%d', // Replaced by the day of the month, using the locale's alternative numeric symbols, filled as needed with leading zeros if there is any alternative symbol for zero; otherwise, with leading <space> characters. '%Oe': '%e', // Replaced by the day of the month, using the locale's alternative numeric symbols, filled as needed with leading <space> characters. '%OH': '%H', // Replaced by the hour (24-hour clock) using the locale's alternative numeric symbols. '%OI': '%I', // Replaced by the hour (12-hour clock) using the locale's alternative numeric symbols. '%Om': '%m', // Replaced by the month using the locale's alternative numeric symbols. '%OM': '%M', // Replaced by the minutes using the locale's alternative numeric symbols. '%OS': '%S', // Replaced by the seconds using the locale's alternative numeric symbols. '%Ou': '%u', // Replaced by the weekday as a number in the locale's alternative representation (Monday=1). '%OU': '%U', // Replaced by the week number of the year (Sunday as the first day of the week, rules corresponding to %U ) using the locale's alternative numeric symbols. '%OV': '%V', // Replaced by the week number of the year (Monday as the first day of the week, rules corresponding to %V ) using the locale's alternative numeric symbols. '%Ow': '%w', // Replaced by the number of the weekday (Sunday=0) using the locale's alternative numeric symbols. '%OW': '%W', // Replaced by the week number of the year (Monday as the first day of the week) using the locale's alternative numeric symbols. '%Oy': '%y', // Replaced by the year (offset from %C ) using the locale's alternative numeric symbols. }; for (var rule in EXPANSION_RULES_1) { pattern = pattern.replace(new RegExp(rule, 'g'), EXPANSION_RULES_1[rule]); } var WEEKDAYS = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']; var MONTHS = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']; function leadingSomething(value, digits, character) { var str = typeof value === 'number' ? value.toString() : (value || ''); while (str.length < digits) { str = character[0]+str; } return str; } function leadingNulls(value, digits) { return leadingSomething(value, digits, '0'); } function compareByDay(date1, date2) { function sgn(value) { return value < 0 ? -1 : (value > 0 ? 1 : 0); } var compare; if ((compare = sgn(date1.getFullYear()-date2.getFullYear())) === 0) { if ((compare = sgn(date1.getMonth()-date2.getMonth())) === 0) { compare = sgn(date1.getDate()-date2.getDate()); } } return compare; } function getFirstWeekStartDate(janFourth) { switch (janFourth.getDay()) { case 0: // Sunday return new Date(janFourth.getFullYear()-1, 11, 29); case 1: // Monday return janFourth; case 2: // Tuesday return new Date(janFourth.getFullYear(), 0, 3); case 3: // Wednesday return new Date(janFourth.getFullYear(), 0, 2); case 4: // Thursday return new Date(janFourth.getFullYear(), 0, 1); case 5: // Friday return new Date(janFourth.getFullYear()-1, 11, 31); case 6: // Saturday return new Date(janFourth.getFullYear()-1, 11, 30); } } function getWeekBasedYear(date) { var thisDate = __addDays(new Date(date.tm_year+1900, 0, 1), date.tm_yday); var janFourthThisYear = new Date(thisDate.getFullYear(), 0, 4); var janFourthNextYear = new Date(thisDate.getFullYear()+1, 0, 4); var firstWeekStartThisYear = getFirstWeekStartDate(janFourthThisYear); var firstWeekStartNextYear = getFirstWeekStartDate(janFourthNextYear); if (compareByDay(firstWeekStartThisYear, thisDate) <= 0) { // this date is after the start of the first week of this year if (compareByDay(firstWeekStartNextYear, thisDate) <= 0) { return thisDate.getFullYear()+1; } else { return thisDate.getFullYear(); } } else { return thisDate.getFullYear()-1; } } var EXPANSION_RULES_2 = { '%a': function(date) { return WEEKDAYS[date.tm_wday].substring(0,3); }, '%A': function(date) { return WEEKDAYS[date.tm_wday]; }, '%b': function(date) { return MONTHS[date.tm_mon].substring(0,3); }, '%B': function(date) { return MONTHS[date.tm_mon]; }, '%C': function(date) { var year = date.tm_year+1900; return leadingNulls((year/100)|0,2); }, '%d': function(date) { return leadingNulls(date.tm_mday, 2); }, '%e': function(date) { return leadingSomething(date.tm_mday, 2, ' '); }, '%g': function(date) { // %g, %G, and %V give values according to the ISO 8601:2000 standard week-based year. // In this system, weeks begin on a Monday and week 1 of the year is the week that includes // January 4th, which is also the week that includes the first Thursday of the year, and // is also the first week that contains at least four days in the year. // If the first Monday of January is the 2nd, 3rd, or 4th, the preceding days are part of // the last week of the preceding year; thus, for Saturday 2nd January 1999, // %G is replaced by 1998 and %V is replaced by 53. If December 29th, 30th, // or 31st is a Monday, it and any following days are part of week 1 of the following year. // Thus, for Tuesday 30th December 1997, %G is replaced by 1998 and %V is replaced by 01. return getWeekBasedYear(date).toString().substring(2); }, '%G': function(date) { return getWeekBasedYear(date); }, '%H': function(date) { return leadingNulls(date.tm_hour, 2); }, '%I': function(date) { var twelveHour = date.tm_hour; if (twelveHour == 0) twelveHour = 12; else if (twelveHour > 12) twelveHour -= 12; return leadingNulls(twelveHour, 2); }, '%j': function(date) { // Day of the year (001-366) return leadingNulls(date.tm_mday+__arraySum(__isLeapYear(date.tm_year+1900) ? __MONTH_DAYS_LEAP : __MONTH_DAYS_REGULAR, date.tm_mon-1), 3); }, '%m': function(date) { return leadingNulls(date.tm_mon+1, 2); }, '%M': function(date) { return leadingNulls(date.tm_min, 2); }, '%n': function() { return '\n'; }, '%p': function(date) { if (date.tm_hour >= 0 && date.tm_hour < 12) { return 'AM'; } else { return 'PM'; } }, '%S': function(date) { return leadingNulls(date.tm_sec, 2); }, '%t': function() { return '\t'; }, '%u': function(date) { return date.tm_wday || 7; }, '%U': function(date) { // Replaced by the week number of the year as a decimal number [00,53]. // The first Sunday of January is the first day of week 1; // days in the new year before this are in week 0. [ tm_year, tm_wday, tm_yday] var janFirst = new Date(date.tm_year+1900, 0, 1); var firstSunday = janFirst.getDay() === 0 ? janFirst : __addDays(janFirst, 7-janFirst.getDay()); var endDate = new Date(date.tm_year+1900, date.tm_mon, date.tm_mday); // is target date after the first Sunday? if (compareByDay(firstSunday, endDate) < 0) { // calculate difference in days between first Sunday and endDate var februaryFirstUntilEndMonth = __arraySum(__isLeapYear(endDate.getFullYear()) ? __MONTH_DAYS_LEAP : __MONTH_DAYS_REGULAR, endDate.getMonth()-1)-31; var firstSundayUntilEndJanuary = 31-firstSunday.getDate(); var days = firstSundayUntilEndJanuary+februaryFirstUntilEndMonth+endDate.getDate(); return leadingNulls(Math.ceil(days/7), 2); } return compareByDay(firstSunday, janFirst) === 0 ? '01': '00'; }, '%V': function(date) { // Replaced by the week number of the year (Monday as the first day of the week) // as a decimal number [01,53]. If the week containing 1 January has four // or more days in the new year, then it is considered week 1. // Otherwise, it is the last week of the previous year, and the next week is week 1. // Both January 4th and the first Thursday of January are always in week 1. [ tm_year, tm_wday, tm_yday] var janFourthThisYear = new Date(date.tm_year+1900, 0, 4); var janFourthNextYear = new Date(date.tm_year+1901, 0, 4); var firstWeekStartThisYear = getFirstWeekStartDate(janFourthThisYear); var firstWeekStartNextYear = getFirstWeekStartDate(janFourthNextYear); var endDate = __addDays(new Date(date.tm_year+1900, 0, 1), date.tm_yday); if (compareByDay(endDate, firstWeekStartThisYear) < 0) { // if given date is before this years first week, then it belongs to the 53rd week of last year return '53'; } if (compareByDay(firstWeekStartNextYear, endDate) <= 0) { // if given date is after next years first week, then it belongs to the 01th week of next year return '01'; } // given date is in between CW 01..53 of this calendar year var daysDifference; if (firstWeekStartThisYear.getFullYear() < date.tm_year+1900) { // first CW of this year starts last year daysDifference = date.tm_yday+32-firstWeekStartThisYear.getDate() } else { // first CW of this year starts this year daysDifference = date.tm_yday+1-firstWeekStartThisYear.getDate(); } return leadingNulls(Math.ceil(daysDifference/7), 2); }, '%w': function(date) { return date.tm_wday; }, '%W': function(date) { // Replaced by the week number of the year as a decimal number [00,53]. // The first Monday of January is the first day of week 1; // days in the new year before this are in week 0. [ tm_year, tm_wday, tm_yday] var janFirst = new Date(date.tm_year, 0, 1); var firstMonday = janFirst.getDay() === 1 ? janFirst : __addDays(janFirst, janFirst.getDay() === 0 ? 1 : 7-janFirst.getDay()+1); var endDate = new Date(date.tm_year+1900, date.tm_mon, date.tm_mday); // is target date after the first Monday? if (compareByDay(firstMonday, endDate) < 0) { var februaryFirstUntilEndMonth = __arraySum(__isLeapYear(endDate.getFullYear()) ? __MONTH_DAYS_LEAP : __MONTH_DAYS_REGULAR, endDate.getMonth()-1)-31; var firstMondayUntilEndJanuary = 31-firstMonday.getDate(); var days = firstMondayUntilEndJanuary+februaryFirstUntilEndMonth+endDate.getDate(); return leadingNulls(Math.ceil(days/7), 2); } return compareByDay(firstMonday, janFirst) === 0 ? '01': '00'; }, '%y': function(date) { // Replaced by the last two digits of the year as a decimal number [00,99]. [ tm_year] return (date.tm_year+1900).toString().substring(2); }, '%Y': function(date) { // Replaced by the year as a decimal number (for example, 1997). [ tm_year] return date.tm_year+1900; }, '%z': function(date) { // Replaced by the offset from UTC in the ISO 8601:2000 standard format ( +hhmm or -hhmm ). // For example, "-0430" means 4 hours 30 minutes behind UTC (west of Greenwich). var off = date.tm_gmtoff; var ahead = off >= 0; off = Math.abs(off) / 60; // convert from minutes into hhmm format (which means 60 minutes = 100 units) off = (off / 60)*100 + (off % 60); return (ahead ? '+' : '-') + String("0000" + off).slice(-4); }, '%Z': function(date) { return date.tm_zone; }, '%%': function() { return '%'; } }; for (var rule in EXPANSION_RULES_2) { if (pattern.indexOf(rule) >= 0) { pattern = pattern.replace(new RegExp(rule, 'g'), EXPANSION_RULES_2[rule](date)); } } var bytes = intArrayFromString(pattern, false); if (bytes.length > maxsize) { return 0; } writeArrayToMemory(bytes, s); return bytes.length-1; }, strftime_l__deps: ['strftime'], strftime_l: function(s, maxsize, format, tm) { return _strftime(s, maxsize, format, tm); // no locale support yet }, strptime__deps: ['_isLeapYear', '_arraySum', '_addDays', '_MONTH_DAYS_REGULAR', '_MONTH_DAYS_LEAP'], strptime: function(buf, format, tm) { // char *strptime(const char *restrict buf, const char *restrict format, struct tm *restrict tm); // http://pubs.opengroup.org/onlinepubs/009695399/functions/strptime.html var pattern = UTF8ToString(format); // escape special characters // TODO: not sure we really need to escape all of these in JS regexps var SPECIAL_CHARS = '\\!@#$^&*()+=-[]/{}|:<>?,.'; for (var i=0, ii=SPECIAL_CHARS.length; i<ii; ++i) { pattern = pattern.replace(new RegExp('\\'+SPECIAL_CHARS[i], 'g'), '\\'+SPECIAL_CHARS[i]); } // reduce number of matchers var EQUIVALENT_MATCHERS = { '%A': '%a', '%B': '%b', '%c': '%a %b %d %H:%M:%S %Y', '%D': '%m\\/%d\\/%y', '%e': '%d', '%F': '%Y-%m-%d', '%h': '%b', '%R': '%H\\:%M', '%r': '%I\\:%M\\:%S\\s%p', '%T': '%H\\:%M\\:%S', '%x': '%m\\/%d\\/(?:%y|%Y)', '%X': '%H\\:%M\\:%S' }; for (var matcher in EQUIVALENT_MATCHERS) { pattern = pattern.replace(matcher, EQUIVALENT_MATCHERS[matcher]); } // TODO: take care of locale var DATE_PATTERNS = { /* weeday name */ '%a': '(?:Sun(?:day)?)|(?:Mon(?:day)?)|(?:Tue(?:sday)?)|(?:Wed(?:nesday)?)|(?:Thu(?:rsday)?)|(?:Fri(?:day)?)|(?:Sat(?:urday)?)', /* month name */ '%b': '(?:Jan(?:uary)?)|(?:Feb(?:ruary)?)|(?:Mar(?:ch)?)|(?:Apr(?:il)?)|May|(?:Jun(?:e)?)|(?:Jul(?:y)?)|(?:Aug(?:ust)?)|(?:Sep(?:tember)?)|(?:Oct(?:ober)?)|(?:Nov(?:ember)?)|(?:Dec(?:ember)?)', /* century */ '%C': '\\d\\d', /* day of month */ '%d': '0[1-9]|[1-9](?!\\d)|1\\d|2\\d|30|31', /* hour (24hr) */ '%H': '\\d(?!\\d)|[0,1]\\d|20|21|22|23', /* hour (12hr) */ '%I': '\\d(?!\\d)|0\\d|10|11|12', /* day of year */ '%j': '00[1-9]|0?[1-9](?!\\d)|0?[1-9]\\d(?!\\d)|[1,2]\\d\\d|3[0-6]\\d', /* month */ '%m': '0[1-9]|[1-9](?!\\d)|10|11|12', /* minutes */ '%M': '0\\d|\\d(?!\\d)|[1-5]\\d', /* whitespace */ '%n': '\\s', /* AM/PM */ '%p': 'AM|am|PM|pm|A\\.M\\.|a\\.m\\.|P\\.M\\.|p\\.m\\.', /* seconds */ '%S': '0\\d|\\d(?!\\d)|[1-5]\\d|60', /* week number */ '%U': '0\\d|\\d(?!\\d)|[1-4]\\d|50|51|52|53', /* week number */ '%W': '0\\d|\\d(?!\\d)|[1-4]\\d|50|51|52|53', /* weekday number */ '%w': '[0-6]', /* 2-digit year */ '%y': '\\d\\d', /* 4-digit year */ '%Y': '\\d\\d\\d\\d', /* % */ '%%': '%', /* whitespace */ '%t': '\\s', }; var MONTH_NUMBERS = {JAN: 0, FEB: 1, MAR: 2, APR: 3, MAY: 4, JUN: 5, JUL: 6, AUG: 7, SEP: 8, OCT: 9, NOV: 10, DEC: 11}; var DAY_NUMBERS_SUN_FIRST = {SUN: 0, MON: 1, TUE: 2, WED: 3, THU: 4, FRI: 5, SAT: 6}; var DAY_NUMBERS_MON_FIRST = {MON: 0, TUE: 1, WED: 2, THU: 3, FRI: 4, SAT: 5, SUN: 6}; for (var datePattern in DATE_PATTERNS) { pattern = pattern.replace(datePattern, '('+datePattern+DATE_PATTERNS[datePattern]+')'); } // take care of capturing groups var capture = []; for (var i=pattern.indexOf('%'); i>=0; i=pattern.indexOf('%')) { capture.push(pattern[i+1]); pattern = pattern.replace(new RegExp('\\%'+pattern[i+1], 'g'), ''); } var matches = new RegExp('^'+pattern, "i").exec(UTF8ToString(buf)) // out(UTF8ToString(buf)+ ' is matched by '+((new RegExp('^'+pattern)).source)+' into: '+JSON.stringify(matches)); function initDate() { function fixup(value, min, max) { return (typeof value !== 'number' || isNaN(value)) ? min : (value>=min ? (value<=max ? value: max): min); }; return { year: fixup({{{ makeGetValue('tm', C_STRUCTS.tm.tm_year, 'i32', 0, 0, 1) }}} + 1900 , 1970, 9999), month: fixup({{{ makeGetValue('tm', C_STRUCTS.tm.tm_mon, 'i32', 0, 0, 1) }}}, 0, 11), day: fixup({{{ makeGetValue('tm', C_STRUCTS.tm.tm_mday, 'i32', 0, 0, 1) }}}, 1, 31), hour: fixup({{{ makeGetValue('tm', C_STRUCTS.tm.tm_hour, 'i32', 0, 0, 1) }}}, 0, 23), min: fixup({{{ makeGetValue('tm', C_STRUCTS.tm.tm_min, 'i32', 0, 0, 1) }}}, 0, 59), sec: fixup({{{ makeGetValue('tm', C_STRUCTS.tm.tm_sec, 'i32', 0, 0, 1) }}}, 0, 59) }; }; if (matches) { var date = initDate(); var value; var getMatch = function(symbol) { var pos = capture.indexOf(symbol); // check if symbol appears in regexp if (pos >= 0) { // return matched value or null (falsy!) for non-matches return matches[pos+1]; } return; }; // seconds if ((value=getMatch('S'))) { date.sec = parseInt(value); } // minutes if ((value=getMatch('M'))) { date.min = parseInt(value); } // hours if ((value=getMatch('H'))) { // 24h clock date.hour = parseInt(value); } else if ((value = getMatch('I'))) { // AM/PM clock var hour = parseInt(value); if ((value=getMatch('p'))) { hour += value.toUpperCase()[0] === 'P' ? 12 : 0; } date.hour = hour; } // year if ((value=getMatch('Y'))) { // parse from four-digit year date.year = parseInt(value); } else if ((value=getMatch('y'))) { // parse from two-digit year... var year = parseInt(value); if ((value=getMatch('C'))) { // ...and century year += parseInt(value)*100; } else { // ...and rule-of-thumb year += year<69 ? 2000 : 1900; } date.year = year; } // month if ((value=getMatch('m'))) { // parse from month number date.month = parseInt(value)-1; } else if ((value=getMatch('b'))) { // parse from month name date.month = MONTH_NUMBERS[value.substring(0,3).toUpperCase()] || 0; // TODO: derive month from day in year+year, week number+day of week+year } // day if ((value=getMatch('d'))) { // get day of month directly date.day = parseInt(value); } else if ((value=getMatch('j'))) { // get day of month from day of year ... var day = parseInt(value); var leapYear = __isLeapYear(date.year); for (var month=0; month<12; ++month) { var daysUntilMonth = __arraySum(leapYear ? __MONTH_DAYS_LEAP : __MONTH_DAYS_REGULAR, month-1); if (day<=daysUntilMonth+(leapYear ? __MONTH_DAYS_LEAP : __MONTH_DAYS_REGULAR)[month]) { date.day = day-daysUntilMonth; } } } else if ((value=getMatch('a'))) { // get day of month from weekday ... var weekDay = value.substring(0,3).toUpperCase(); if ((value=getMatch('U'))) { // ... and week number (Sunday being first day of week) // Week number of the year (Sunday as the first day of the week) as a decimal number [00,53]. // All days in a new year preceding the first Sunday are considered to be in week 0. var weekDayNumber = DAY_NUMBERS_SUN_FIRST[weekDay]; var weekNumber = parseInt(value); // January 1st var janFirst = new Date(date.year, 0, 1); var endDate; if (janFirst.getDay() === 0) { // Jan 1st is a Sunday, and, hence in the 1st CW endDate = __addDays(janFirst, weekDayNumber+7*(weekNumber-1)); } else { // Jan 1st is not a Sunday, and, hence still in the 0th CW endDate = __addDays(janFirst, 7-janFirst.getDay()+weekDayNumber+7*(weekNumber-1)); } date.day = endDate.getDate(); date.month = endDate.getMonth(); } else if ((value=getMatch('W'))) { // ... and week number (Monday being first day of week) // Week number of the year (Monday as the first day of the week) as a decimal number [00,53]. // All days in a new year preceding the first Monday are considered to be in week 0. var weekDayNumber = DAY_NUMBERS_MON_FIRST[weekDay]; var weekNumber = parseInt(value); // January 1st var janFirst = new Date(date.year, 0, 1); var endDate; if (janFirst.getDay()===1) { // Jan 1st is a Monday, and, hence in the 1st CW endDate = __addDays(janFirst, weekDayNumber+7*(weekNumber-1)); } else { // Jan 1st is not a Monday, and, hence still in the 0th CW endDate = __addDays(janFirst, 7-janFirst.getDay()+1+weekDayNumber+7*(weekNumber-1)); } date.day = endDate.getDate(); date.month = endDate.getMonth(); } } /* tm_sec int seconds after the minute 0-61* tm_min int minutes after the hour 0-59 tm_hour int hours since midnight 0-23 tm_mday int day of the month 1-31 tm_mon int months since January 0-11 tm_year int years since 1900 tm_wday int days since Sunday 0-6 tm_yday int days since January 1 0-365 tm_isdst int Daylight Saving Time flag */ var fullDate = new Date(date.year, date.month, date.day, date.hour, date.min, date.sec, 0); {{{ makeSetValue('tm', C_STRUCTS.tm.tm_sec, 'fullDate.getSeconds()', 'i32') }}}; {{{ makeSetValue('tm', C_STRUCTS.tm.tm_min, 'fullDate.getMinutes()', 'i32') }}}; {{{ makeSetValue('tm', C_STRUCTS.tm.tm_hour, 'fullDate.getHours()', 'i32') }}}; {{{ makeSetValue('tm', C_STRUCTS.tm.tm_mday, 'fullDate.getDate()', 'i32') }}}; {{{ makeSetValue('tm', C_STRUCTS.tm.tm_mon, 'fullDate.getMonth()', 'i32') }}}; {{{ makeSetValue('tm', C_STRUCTS.tm.tm_year, 'fullDate.getFullYear()-1900', 'i32') }}}; {{{ makeSetValue('tm', C_STRUCTS.tm.tm_wday, 'fullDate.getDay()', 'i32') }}}; {{{ makeSetValue('tm', C_STRUCTS.tm.tm_yday, '__arraySum(__isLeapYear(fullDate.getFullYear()) ? __MONTH_DAYS_LEAP : __MONTH_DAYS_REGULAR, fullDate.getMonth()-1)+fullDate.getDate()-1', 'i32') }}}; {{{ makeSetValue('tm', C_STRUCTS.tm.tm_isdst, '0', 'i32') }}}; // we need to convert the matched sequence into an integer array to take care of UTF-8 characters > 0x7F // TODO: not sure that intArrayFromString handles all unicode characters correctly return buf+intArrayFromString(matches[0]).length-1; } return 0; }, strptime_l__deps: ['strptime'], strptime_l: function(buf, format, tm) { return _strptime(buf, format, tm); // no locale support yet }, getdate: function(string) { // struct tm *getdate(const char *string); // http://pubs.opengroup.org/onlinepubs/009695399/functions/getdate.html // TODO: Implement. return 0; }, timespec_get__deps: ['clock_gettime', '__setErrNo'], timespec_get: function(ts, base) { //int timespec_get(struct timespec *ts, int base); if (base !== {{{ cDefine('TIME_UTC') }}}) { // There is no other implemented value than TIME_UTC; all other values are considered erroneous. ___setErrNo({{{ cDefine('EINVAL') }}}); return 0; } var ret = _clock_gettime({{{ cDefine('CLOCK_REALTIME') }}}, ts); return ret < 0 ? 0 : base; }, // ========================================================================== // sys/time.h // ========================================================================== clock_gettime__deps: ['emscripten_get_now', 'emscripten_get_now_is_monotonic', '__setErrNo'], clock_gettime: function(clk_id, tp) { // int clock_gettime(clockid_t clk_id, struct timespec *tp); var now; if (clk_id === {{{ cDefine('CLOCK_REALTIME') }}}) { now = Date.now(); } else if (clk_id === {{{ cDefine('CLOCK_MONOTONIC') }}} && _emscripten_get_now_is_monotonic()) { now = _emscripten_get_now(); } else { ___setErrNo({{{ cDefine('EINVAL') }}}); return -1; } {{{ makeSetValue('tp', C_STRUCTS.timespec.tv_sec, '(now/1000)|0', 'i32') }}}; // seconds {{{ makeSetValue('tp', C_STRUCTS.timespec.tv_nsec, '((now % 1000)*1000*1000)|0', 'i32') }}}; // nanoseconds return 0; }, __clock_gettime__sig: 'iii', __clock_gettime: 'clock_gettime', // musl internal alias clock_settime__deps: ['__setErrNo'], clock_settime: function(clk_id, tp) { // int clock_settime(clockid_t clk_id, const struct timespec *tp); // Nothing. ___setErrNo(clk_id === {{{ cDefine('CLOCK_REALTIME') }}} ? {{{ cDefine('EPERM') }}} : {{{ cDefine('EINVAL') }}}); return -1; }, clock_getres__deps: ['emscripten_get_now_res', 'emscripten_get_now_is_monotonic', '__setErrNo'], clock_getres: function(clk_id, res) { // int clock_getres(clockid_t clk_id, struct timespec *res); var nsec; if (clk_id === {{{ cDefine('CLOCK_REALTIME') }}}) { nsec = 1000 * 1000; // educated guess that it's milliseconds } else if (clk_id === {{{ cDefine('CLOCK_MONOTONIC') }}} && _emscripten_get_now_is_monotonic()) { nsec = _emscripten_get_now_res(); } else { ___setErrNo({{{ cDefine('EINVAL') }}}); return -1; } {{{ makeSetValue('res', C_STRUCTS.timespec.tv_sec, '(nsec/1000000000)|0', 'i32') }}}; {{{ makeSetValue('res', C_STRUCTS.timespec.tv_nsec, 'nsec', 'i32') }}} // resolution is nanoseconds return 0; }, clock_getcpuclockid__deps: ['$PROCINFO'], clock_getcpuclockid: function(pid, clk_id) { if (pid < 0) return {{{ cDefine('ESRCH') }}}; if (pid !== 0 && pid !== PROCINFO.pid) return {{{ cDefine('ENOSYS') }}}; if (clk_id) {{{ makeSetValue('clk_id', 0, 2/*CLOCK_PROCESS_CPUTIME_ID*/, 'i32') }}}; return 0; }, // http://pubs.opengroup.org/onlinepubs/000095399/basedefs/sys/time.h.html gettimeofday: function(ptr) { var now = Date.now(); {{{ makeSetValue('ptr', C_STRUCTS.timeval.tv_sec, '(now/1000)|0', 'i32') }}}; // seconds {{{ makeSetValue('ptr', C_STRUCTS.timeval.tv_usec, '((now % 1000)*1000)|0', 'i32') }}}; // microseconds return 0; }, // ========================================================================== // sys/timeb.h // ========================================================================== ftime: function(p) { var millis = Date.now(); {{{ makeSetValue('p', C_STRUCTS.timeb.time, '(millis/1000)|0', 'i32') }}}; {{{ makeSetValue('p', C_STRUCTS.timeb.millitm, 'millis % 1000', 'i16') }}}; {{{ makeSetValue('p', C_STRUCTS.timeb.timezone, '0', 'i16') }}}; // Obsolete field {{{ makeSetValue('p', C_STRUCTS.timeb.dstflag, '0', 'i16') }}}; // Obsolete field return 0; }, // ========================================================================== // sys/times.h // ========================================================================== times__deps: ['memset'], times: function(buffer) { // clock_t times(struct tms *buffer); // http://pubs.opengroup.org/onlinepubs/009695399/functions/times.html // NOTE: This is fake, since we can't calculate real CPU time usage in JS. if (buffer !== 0) { _memset(buffer, 0, {{{ C_STRUCTS.tms.__size__ }}}); } return 0; }, // ========================================================================== // sys/types.h // ========================================================================== // http://www.kernel.org/doc/man-pages/online/pages/man3/minor.3.html makedev: function(maj, min) { return ((maj) << 8 | (min)); }, gnu_dev_makedev: 'makedev', major: function(dev) { return ((dev) >> 8); }, gnu_dev_major: 'major', minor: function(dev) { return ((dev) & 0xff); }, gnu_dev_minor: 'minor', // ========================================================================== // setjmp.h // ========================================================================== #if SUPPORT_LONGJMP // asm.js-style setjmp/longjmp support for wasm binaryen backend. // In asm.js compilation, various variables including setjmpId will be // generated within 'var asm' in emscripten.py, while in wasm compilation, // wasm side is considered as 'asm' so they are not generated. But // saveSetjmp() needs setjmpId and no other functions in wasm side needs it. // So we declare it here if WASM_BACKEND=1. #if WASM_BACKEND == 1 $setjmpId: 0, #endif saveSetjmp__asm: true, saveSetjmp__sig: 'iii', #if WASM_BACKEND == 1 saveSetjmp__deps: ['realloc', '$setjmpId'], #else saveSetjmp__deps: ['realloc'], #endif saveSetjmp: function(env, label, table, size) { // Not particularly fast: slow table lookup of setjmpId to label. But setjmp // prevents relooping anyhow, so slowness is to be expected. And typical case // is 1 setjmp per invocation, or less. env = env|0; label = label|0; table = table|0; size = size|0; var i = 0; setjmpId = (setjmpId+1)|0; {{{ makeSetValueAsm('env', '0', 'setjmpId', 'i32') }}}; while ((i|0) < (size|0)) { if ({{{ makeGetValueAsm('table', '(i<<3)', 'i32') }}} == 0) { {{{ makeSetValueAsm('table', '(i<<3)', 'setjmpId', 'i32') }}}; {{{ makeSetValueAsm('table', '(i<<3)+4', 'label', 'i32') }}}; // prepare next slot {{{ makeSetValueAsm('table', '(i<<3)+8', '0', 'i32') }}}; {{{ makeSetTempRet0('size') }}}; return table | 0; } i = i+1|0; } // grow the table size = (size*2)|0; table = _realloc(table|0, 8*(size+1|0)|0) | 0; table = _saveSetjmp(env|0, label|0, table|0, size|0) | 0; {{{ makeSetTempRet0('size') }}}; return table | 0; }, testSetjmp__asm: true, testSetjmp__sig: 'iii', testSetjmp: function(id, table, size) { id = id|0; table = table|0; size = size|0; var i = 0, curr = 0; while ((i|0) < (size|0)) { curr = {{{ makeGetValueAsm('table', '(i<<3)', 'i32') }}}; if ((curr|0) == 0) break; if ((curr|0) == (id|0)) { return {{{ makeGetValueAsm('table', '(i<<3)+4', 'i32') }}}; } i = i+1|0; } return 0; }, setjmp__deps: ['saveSetjmp', 'testSetjmp'], setjmp__inline: function(env) { // Save the label return '_saveSetjmp(' + env + ', label, setjmpTable)|0'; }, longjmp__deps: ['saveSetjmp', 'testSetjmp', 'setThrew'], longjmp: function(env, value) { _setThrew(env, value || 1); throw 'longjmp'; }, emscripten_longjmp__deps: ['longjmp'], emscripten_longjmp: function(env, value) { _longjmp(env, value); }, #endif // ========================================================================== // sys/wait.h // ========================================================================== wait__deps: ['__setErrNo'], wait: function(stat_loc) { // pid_t wait(int *stat_loc); // http://pubs.opengroup.org/onlinepubs/009695399/functions/wait.html // Makes no sense in a single-process environment. ___setErrNo({{{ cDefine('ECHILD') }}}); return -1; }, // NOTE: These aren't really the same, but we use the same stub for them all. waitid: 'wait', waitpid: 'wait', wait3: 'wait', wait4: 'wait', // ========================================================================== // errno.h // ========================================================================== $ERRNO_CODES: { EPERM: {{{ cDefine('EPERM') }}}, ENOENT: {{{ cDefine('ENOENT') }}}, ESRCH: {{{ cDefine('ESRCH') }}}, EINTR: {{{ cDefine('EINTR') }}}, EIO: {{{ cDefine('EIO') }}}, ENXIO: {{{ cDefine('ENXIO') }}}, E2BIG: {{{ cDefine('E2BIG') }}}, ENOEXEC: {{{ cDefine('ENOEXEC') }}}, EBADF: {{{ cDefine('EBADF') }}}, ECHILD: {{{ cDefine('ECHILD') }}}, EAGAIN: {{{ cDefine('EAGAIN') }}}, EWOULDBLOCK: {{{ cDefine('EWOULDBLOCK') }}}, ENOMEM: {{{ cDefine('ENOMEM') }}}, EACCES: {{{ cDefine('EACCES') }}}, EFAULT: {{{ cDefine('EFAULT') }}}, ENOTBLK: {{{ cDefine('ENOTBLK') }}}, EBUSY: {{{ cDefine('EBUSY') }}}, EEXIST: {{{ cDefine('EEXIST') }}}, EXDEV: {{{ cDefine('EXDEV') }}}, ENODEV: {{{ cDefine('ENODEV') }}}, ENOTDIR: {{{ cDefine('ENOTDIR') }}}, EISDIR: {{{ cDefine('EISDIR') }}}, EINVAL: {{{ cDefine('EINVAL') }}}, ENFILE: {{{ cDefine('ENFILE') }}}, EMFILE: {{{ cDefine('EMFILE') }}}, ENOTTY: {{{ cDefine('ENOTTY') }}}, ETXTBSY: {{{ cDefine('ETXTBSY') }}}, EFBIG: {{{ cDefine('EFBIG') }}}, ENOSPC: {{{ cDefine('ENOSPC') }}}, ESPIPE: {{{ cDefine('ESPIPE') }}}, EROFS: {{{ cDefine('EROFS') }}}, EMLINK: {{{ cDefine('EMLINK') }}}, EPIPE: {{{ cDefine('EPIPE') }}}, EDOM: {{{ cDefine('EDOM') }}}, ERANGE: {{{ cDefine('ERANGE') }}}, ENOMSG: {{{ cDefine('ENOMSG') }}}, EIDRM: {{{ cDefine('EIDRM') }}}, ECHRNG: {{{ cDefine('ECHRNG') }}}, EL2NSYNC: {{{ cDefine('EL2NSYNC') }}}, EL3HLT: {{{ cDefine('EL3HLT') }}}, EL3RST: {{{ cDefine('EL3RST') }}}, ELNRNG: {{{ cDefine('ELNRNG') }}}, EUNATCH: {{{ cDefine('EUNATCH') }}}, ENOCSI: {{{ cDefine('ENOCSI') }}}, EL2HLT: {{{ cDefine('EL2HLT') }}}, EDEADLK: {{{ cDefine('EDEADLK') }}}, ENOLCK: {{{ cDefine('ENOLCK') }}}, EBADE: {{{ cDefine('EBADE') }}}, EBADR: {{{ cDefine('EBADR') }}}, EXFULL: {{{ cDefine('EXFULL') }}}, ENOANO: {{{ cDefine('ENOANO') }}}, EBADRQC: {{{ cDefine('EBADRQC') }}}, EBADSLT: {{{ cDefine('EBADSLT') }}}, EDEADLOCK: {{{ cDefine('EDEADLOCK') }}}, EBFONT: {{{ cDefine('EBFONT') }}}, ENOSTR: {{{ cDefine('ENOSTR') }}}, ENODATA: {{{ cDefine('ENODATA') }}}, ETIME: {{{ cDefine('ETIME') }}}, ENOSR: {{{ cDefine('ENOSR') }}}, ENONET: {{{ cDefine('ENONET') }}}, ENOPKG: {{{ cDefine('ENOPKG') }}}, EREMOTE: {{{ cDefine('EREMOTE') }}}, ENOLINK: {{{ cDefine('ENOLINK') }}}, EADV: {{{ cDefine('EADV') }}}, ESRMNT: {{{ cDefine('ESRMNT') }}}, ECOMM: {{{ cDefine('ECOMM') }}}, EPROTO: {{{ cDefine('EPROTO') }}}, EMULTIHOP: {{{ cDefine('EMULTIHOP') }}}, EDOTDOT: {{{ cDefine('EDOTDOT') }}}, EBADMSG: {{{ cDefine('EBADMSG') }}}, ENOTUNIQ: {{{ cDefine('ENOTUNIQ') }}}, EBADFD: {{{ cDefine('EBADFD') }}}, EREMCHG: {{{ cDefine('EREMCHG') }}}, ELIBACC: {{{ cDefine('ELIBACC') }}}, ELIBBAD: {{{ cDefine('ELIBBAD') }}}, ELIBSCN: {{{ cDefine('ELIBSCN') }}}, ELIBMAX: {{{ cDefine('ELIBMAX') }}}, ELIBEXEC: {{{ cDefine('ELIBEXEC') }}}, ENOSYS: {{{ cDefine('ENOSYS') }}}, ENOTEMPTY: {{{ cDefine('ENOTEMPTY') }}}, ENAMETOOLONG: {{{ cDefine('ENAMETOOLONG') }}}, ELOOP: {{{ cDefine('ELOOP') }}}, EOPNOTSUPP: {{{ cDefine('EOPNOTSUPP') }}}, EPFNOSUPPORT: {{{ cDefine('EPFNOSUPPORT') }}}, ECONNRESET: {{{ cDefine('ECONNRESET') }}}, ENOBUFS: {{{ cDefine('ENOBUFS') }}}, EAFNOSUPPORT: {{{ cDefine('EAFNOSUPPORT') }}}, EPROTOTYPE: {{{ cDefine('EPROTOTYPE') }}}, ENOTSOCK: {{{ cDefine('ENOTSOCK') }}}, ENOPROTOOPT: {{{ cDefine('ENOPROTOOPT') }}}, ESHUTDOWN: {{{ cDefine('ESHUTDOWN') }}}, ECONNREFUSED: {{{ cDefine('ECONNREFUSED') }}}, EADDRINUSE: {{{ cDefine('EADDRINUSE') }}}, ECONNABORTED: {{{ cDefine('ECONNABORTED') }}}, ENETUNREACH: {{{ cDefine('ENETUNREACH') }}}, ENETDOWN: {{{ cDefine('ENETDOWN') }}}, ETIMEDOUT: {{{ cDefine('ETIMEDOUT') }}}, EHOSTDOWN: {{{ cDefine('EHOSTDOWN') }}}, EHOSTUNREACH: {{{ cDefine('EHOSTUNREACH') }}}, EINPROGRESS: {{{ cDefine('EINPROGRESS') }}}, EALREADY: {{{ cDefine('EALREADY') }}}, EDESTADDRREQ: {{{ cDefine('EDESTADDRREQ') }}}, EMSGSIZE: {{{ cDefine('EMSGSIZE') }}}, EPROTONOSUPPORT: {{{ cDefine('EPROTONOSUPPORT') }}}, ESOCKTNOSUPPORT: {{{ cDefine('ESOCKTNOSUPPORT') }}}, EADDRNOTAVAIL: {{{ cDefine('EADDRNOTAVAIL') }}}, ENETRESET: {{{ cDefine('ENETRESET') }}}, EISCONN: {{{ cDefine('EISCONN') }}}, ENOTCONN: {{{ cDefine('ENOTCONN') }}}, ETOOMANYREFS: {{{ cDefine('ETOOMANYREFS') }}}, EUSERS: {{{ cDefine('EUSERS') }}}, EDQUOT: {{{ cDefine('EDQUOT') }}}, ESTALE: {{{ cDefine('ESTALE') }}}, ENOTSUP: {{{ cDefine('ENOTSUP') }}}, ENOMEDIUM: {{{ cDefine('ENOMEDIUM') }}}, EILSEQ: {{{ cDefine('EILSEQ') }}}, EOVERFLOW: {{{ cDefine('EOVERFLOW') }}}, ECANCELED: {{{ cDefine('ECANCELED') }}}, ENOTRECOVERABLE: {{{ cDefine('ENOTRECOVERABLE') }}}, EOWNERDEAD: {{{ cDefine('EOWNERDEAD') }}}, ESTRPIPE: {{{ cDefine('ESTRPIPE') }}}, }, $ERRNO_MESSAGES: { 0: 'Success', {{{ cDefine('EPERM') }}}: 'Not super-user', {{{ cDefine('ENOENT') }}}: 'No such file or directory', {{{ cDefine('ESRCH') }}}: 'No such process', {{{ cDefine('EINTR') }}}: 'Interrupted system call', {{{ cDefine('EIO') }}}: 'I/O error', {{{ cDefine('ENXIO') }}}: 'No such device or address', {{{ cDefine('E2BIG') }}}: 'Arg list too long', {{{ cDefine('ENOEXEC') }}}: 'Exec format error', {{{ cDefine('EBADF') }}}: 'Bad file number', {{{ cDefine('ECHILD') }}}: 'No children', {{{ cDefine('EWOULDBLOCK') }}}: 'No more processes', {{{ cDefine('ENOMEM') }}}: 'Not enough core', {{{ cDefine('EACCES') }}}: 'Permission denied', {{{ cDefine('EFAULT') }}}: 'Bad address', {{{ cDefine('ENOTBLK') }}}: 'Block device required', {{{ cDefine('EBUSY') }}}: 'Mount device busy', {{{ cDefine('EEXIST') }}}: 'File exists', {{{ cDefine('EXDEV') }}}: 'Cross-device link', {{{ cDefine('ENODEV') }}}: 'No such device', {{{ cDefine('ENOTDIR') }}}: 'Not a directory', {{{ cDefine('EISDIR') }}}: 'Is a directory', {{{ cDefine('EINVAL') }}}: 'Invalid argument', {{{ cDefine('ENFILE') }}}: 'Too many open files in system', {{{ cDefine('EMFILE') }}}: 'Too many open files', {{{ cDefine('ENOTTY') }}}: 'Not a typewriter', {{{ cDefine('ETXTBSY') }}}: 'Text file busy', {{{ cDefine('EFBIG') }}}: 'File too large', {{{ cDefine('ENOSPC') }}}: 'No space left on device', {{{ cDefine('ESPIPE') }}}: 'Illegal seek', {{{ cDefine('EROFS') }}}: 'Read only file system', {{{ cDefine('EMLINK') }}}: 'Too many links', {{{ cDefine('EPIPE') }}}: 'Broken pipe', {{{ cDefine('EDOM') }}}: 'Math arg out of domain of func', {{{ cDefine('ERANGE') }}}: 'Math result not representable', {{{ cDefine('ENOMSG') }}}: 'No message of desired type', {{{ cDefine('EIDRM') }}}: 'Identifier removed', {{{ cDefine('ECHRNG') }}}: 'Channel number out of range', {{{ cDefine('EL2NSYNC') }}}: 'Level 2 not synchronized', {{{ cDefine('EL3HLT') }}}: 'Level 3 halted', {{{ cDefine('EL3RST') }}}: 'Level 3 reset', {{{ cDefine('ELNRNG') }}}: 'Link number out of range', {{{ cDefine('EUNATCH') }}}: 'Protocol driver not attached', {{{ cDefine('ENOCSI') }}}: 'No CSI structure available', {{{ cDefine('EL2HLT') }}}: 'Level 2 halted', {{{ cDefine('EDEADLK') }}}: 'Deadlock condition', {{{ cDefine('ENOLCK') }}}: 'No record locks available', {{{ cDefine('EBADE') }}}: 'Invalid exchange', {{{ cDefine('EBADR') }}}: 'Invalid request descriptor', {{{ cDefine('EXFULL') }}}: 'Exchange full', {{{ cDefine('ENOANO') }}}: 'No anode', {{{ cDefine('EBADRQC') }}}: 'Invalid request code', {{{ cDefine('EBADSLT') }}}: 'Invalid slot', {{{ cDefine('EDEADLOCK') }}}: 'File locking deadlock error', {{{ cDefine('EBFONT') }}}: 'Bad font file fmt', {{{ cDefine('ENOSTR') }}}: 'Device not a stream', {{{ cDefine('ENODATA') }}}: 'No data (for no delay io)', {{{ cDefine('ETIME') }}}: 'Timer expired', {{{ cDefine('ENOSR') }}}: 'Out of streams resources', {{{ cDefine('ENONET') }}}: 'Machine is not on the network', {{{ cDefine('ENOPKG') }}}: 'Package not installed', {{{ cDefine('EREMOTE') }}}: 'The object is remote', {{{ cDefine('ENOLINK') }}}: 'The link has been severed', {{{ cDefine('EADV') }}}: 'Advertise error', {{{ cDefine('ESRMNT') }}}: 'Srmount error', {{{ cDefine('ECOMM') }}}: 'Communication error on send', {{{ cDefine('EPROTO') }}}: 'Protocol error', {{{ cDefine('EMULTIHOP') }}}: 'Multihop attempted', {{{ cDefine('EDOTDOT') }}}: 'Cross mount point (not really error)', {{{ cDefine('EBADMSG') }}}: 'Trying to read unreadable message', {{{ cDefine('ENOTUNIQ') }}}: 'Given log. name not unique', {{{ cDefine('EBADFD') }}}: 'f.d. invalid for this operation', {{{ cDefine('EREMCHG') }}}: 'Remote address changed', {{{ cDefine('ELIBACC') }}}: 'Can access a needed shared lib', {{{ cDefine('ELIBBAD') }}}: 'Accessing a corrupted shared lib', {{{ cDefine('ELIBSCN') }}}: '.lib section in a.out corrupted', {{{ cDefine('ELIBMAX') }}}: 'Attempting to link in too many libs', {{{ cDefine('ELIBEXEC') }}}: 'Attempting to exec a shared library', {{{ cDefine('ENOSYS') }}}: 'Function not implemented', {{{ cDefine('ENOTEMPTY') }}}: 'Directory not empty', {{{ cDefine('ENAMETOOLONG') }}}: 'File or path name too long', {{{ cDefine('ELOOP') }}}: 'Too many symbolic links', {{{ cDefine('EOPNOTSUPP') }}}: 'Operation not supported on transport endpoint', {{{ cDefine('EPFNOSUPPORT') }}}: 'Protocol family not supported', {{{ cDefine('ECONNRESET') }}}: 'Connection reset by peer', {{{ cDefine('ENOBUFS') }}}: 'No buffer space available', {{{ cDefine('EAFNOSUPPORT') }}}: 'Address family not supported by protocol family', {{{ cDefine('EPROTOTYPE') }}}: 'Protocol wrong type for socket', {{{ cDefine('ENOTSOCK') }}}: 'Socket operation on non-socket', {{{ cDefine('ENOPROTOOPT') }}}: 'Protocol not available', {{{ cDefine('ESHUTDOWN') }}}: 'Can\'t send after socket shutdown', {{{ cDefine('ECONNREFUSED') }}}: 'Connection refused', {{{ cDefine('EADDRINUSE') }}}: 'Address already in use', {{{ cDefine('ECONNABORTED') }}}: 'Connection aborted', {{{ cDefine('ENETUNREACH') }}}: 'Network is unreachable', {{{ cDefine('ENETDOWN') }}}: 'Network interface is not configured', {{{ cDefine('ETIMEDOUT') }}}: 'Connection timed out', {{{ cDefine('EHOSTDOWN') }}}: 'Host is down', {{{ cDefine('EHOSTUNREACH') }}}: 'Host is unreachable', {{{ cDefine('EINPROGRESS') }}}: 'Connection already in progress', {{{ cDefine('EALREADY') }}}: 'Socket already connected', {{{ cDefine('EDESTADDRREQ') }}}: 'Destination address required', {{{ cDefine('EMSGSIZE') }}}: 'Message too long', {{{ cDefine('EPROTONOSUPPORT') }}}: 'Unknown protocol', {{{ cDefine('ESOCKTNOSUPPORT') }}}: 'Socket type not supported', {{{ cDefine('EADDRNOTAVAIL') }}}: 'Address not available', {{{ cDefine('ENETRESET') }}}: 'Connection reset by network', {{{ cDefine('EISCONN') }}}: 'Socket is already connected', {{{ cDefine('ENOTCONN') }}}: 'Socket is not connected', {{{ cDefine('ETOOMANYREFS') }}}: 'Too many references', {{{ cDefine('EUSERS') }}}: 'Too many users', {{{ cDefine('EDQUOT') }}}: 'Quota exceeded', {{{ cDefine('ESTALE') }}}: 'Stale file handle', {{{ cDefine('ENOTSUP') }}}: 'Not supported', {{{ cDefine('ENOMEDIUM') }}}: 'No medium (in tape drive)', {{{ cDefine('EILSEQ') }}}: 'Illegal byte sequence', {{{ cDefine('EOVERFLOW') }}}: 'Value too large for defined data type', {{{ cDefine('ECANCELED') }}}: 'Operation canceled', {{{ cDefine('ENOTRECOVERABLE') }}}: 'State not recoverable', {{{ cDefine('EOWNERDEAD') }}}: 'Previous owner died', {{{ cDefine('ESTRPIPE') }}}: 'Streams pipe error', }, __setErrNo: function(value) { #if SUPPORT_ERRNO if (Module['___errno_location']) {{{ makeSetValue("Module['___errno_location']()", 0, 'value', 'i32') }}}; #if ASSERTIONS else err('failed to set errno from JS'); #endif return value; #else return 0; #endif }, // ========================================================================== // sched.h (stubs only - no thread support yet!) // ========================================================================== sched_yield: function() { return 0; }, // ========================================================================== // arpa/inet.h // ========================================================================== // old ipv4 only functions inet_addr__deps: ['_inet_pton4_raw'], inet_addr: function(ptr) { var addr = __inet_pton4_raw(UTF8ToString(ptr)); if (addr === null) { return -1; } return addr; }, // ========================================================================== // netinet/in.h // ========================================================================== #if USE_PTHREADS in6addr_any: '; if (ENVIRONMENT_IS_PTHREAD) _in6addr_any = PthreadWorkerInit._in6addr_any; else PthreadWorkerInit._in6addr_any = _in6addr_any = {{{ makeStaticAlloc(16) }}}', in6addr_loopback: '; if (ENVIRONMENT_IS_PTHREAD) _in6addr_loopback = PthreadWorkerInit._in6addr_loopback; else PthreadWorkerInit._in6addr_loopback = _in6addr_loopback = {{{ makeStaticAlloc(16) }}}', #else in6addr_any: '{{{ makeStaticAlloc(16) }}}', in6addr_loopback: '{{{ makeStaticAlloc(16) }}}', #endif // ========================================================================== // netdb.h // ========================================================================== _inet_pton4_raw: function(str) { var b = str.split('.'); for (var i = 0; i < 4; i++) { var tmp = Number(b[i]); if (isNaN(tmp)) return null; b[i] = tmp; } return (b[0] | (b[1] << 8) | (b[2] << 16) | (b[3] << 24)) >>> 0; }, _inet_ntop4_raw: function(addr) { return (addr & 0xff) + '.' + ((addr >> 8) & 0xff) + '.' + ((addr >> 16) & 0xff) + '.' + ((addr >> 24) & 0xff) }, _inet_pton6_raw__deps: ['htons', 'ntohs'], _inet_pton6_raw: function(str) { var words; var w, offset, z, i; /* http://home.deds.nl/~aeron/regex/ */ var valid6regx = /^((?=.*::)(?!.*::.+::)(::)?([\dA-F]{1,4}:(:|\b)|){5}|([\dA-F]{1,4}:){6})((([\dA-F]{1,4}((?!\3)::|:\b|$))|(?!\2\3)){2}|(((2[0-4]|1\d|[1-9])?\d|25[0-5])\.?\b){4})$/i var parts = []; if (!valid6regx.test(str)) { return null; } if (str === "::") { return [0, 0, 0, 0, 0, 0, 0, 0]; } // Z placeholder to keep track of zeros when splitting the string on ":" if (str.indexOf("::") === 0) { str = str.replace("::", "Z:"); // leading zeros case } else { str = str.replace("::", ":Z:"); } if (str.indexOf(".") > 0) { // parse IPv4 embedded stress str = str.replace(new RegExp('[.]', 'g'), ":"); words = str.split(":"); words[words.length-4] = parseInt(words[words.length-4]) + parseInt(words[words.length-3])*256; words[words.length-3] = parseInt(words[words.length-2]) + parseInt(words[words.length-1])*256; words = words.slice(0, words.length-2); } else { words = str.split(":"); } offset = 0; z = 0; for (w=0; w < words.length; w++) { if (typeof words[w] === 'string') { if (words[w] === 'Z') { // compressed zeros - write appropriate number of zero words for (z = 0; z < (8 - words.length+1); z++) { parts[w+z] = 0; } offset = z-1; } else { // parse hex to field to 16-bit value and write it in network byte-order parts[w+offset] = _htons(parseInt(words[w],16)); } } else { // parsed IPv4 words parts[w+offset] = words[w]; } } return [ (parts[1] << 16) | parts[0], (parts[3] << 16) | parts[2], (parts[5] << 16) | parts[4], (parts[7] << 16) | parts[6] ]; }, _inet_pton6__deps: ['_inet_pton6_raw'], _inet_pton6: function(src, dst) { var ints = __inet_pton6_raw(UTF8ToString(src)); if (ints === null) { return 0; } for (var i = 0; i < 4; i++) { {{{ makeSetValue('dst', 'i*4', 'ints[i]', 'i32') }}}; } return 1; }, _inet_ntop6_raw__deps: ['_inet_ntop4_raw'], _inet_ntop6_raw: function(ints) { // ref: http://www.ietf.org/rfc/rfc2373.txt - section 2.5.4 // Format for IPv4 compatible and mapped 128-bit IPv6 Addresses // 128-bits are split into eight 16-bit words // stored in network byte order (big-endian) // | 80 bits | 16 | 32 bits | // +-----------------------------------------------------------------+ // | 10 bytes | 2 | 4 bytes | // +--------------------------------------+--------------------------+ // + 5 words | 1 | 2 words | // +--------------------------------------+--------------------------+ // |0000..............................0000|0000| IPv4 ADDRESS | (compatible) // +--------------------------------------+----+---------------------+ // |0000..............................0000|FFFF| IPv4 ADDRESS | (mapped) // +--------------------------------------+----+---------------------+ var str = ""; var word = 0; var longest = 0; var lastzero = 0; var zstart = 0; var len = 0; var i = 0; var parts = [ ints[0] & 0xffff, (ints[0] >> 16), ints[1] & 0xffff, (ints[1] >> 16), ints[2] & 0xffff, (ints[2] >> 16), ints[3] & 0xffff, (ints[3] >> 16) ]; // Handle IPv4-compatible, IPv4-mapped, loopback and any/unspecified addresses var hasipv4 = true; var v4part = ""; // check if the 10 high-order bytes are all zeros (first 5 words) for (i = 0; i < 5; i++) { if (parts[i] !== 0) { hasipv4 = false; break; } } if (hasipv4) { // low-order 32-bits store an IPv4 address (bytes 13 to 16) (last 2 words) v4part = __inet_ntop4_raw(parts[6] | (parts[7] << 16)); // IPv4-mapped IPv6 address if 16-bit value (bytes 11 and 12) == 0xFFFF (6th word) if (parts[5] === -1) { str = "::ffff:"; str += v4part; return str; } // IPv4-compatible IPv6 address if 16-bit value (bytes 11 and 12) == 0x0000 (6th word) if (parts[5] === 0) { str = "::"; //special case IPv6 addresses if(v4part === "0.0.0.0") v4part = ""; // any/unspecified address if(v4part === "0.0.0.1") v4part = "1";// loopback address str += v4part; return str; } } // Handle all other IPv6 addresses // first run to find the longest contiguous zero words for (word = 0; word < 8; word++) { if (parts[word] === 0) { if (word - lastzero > 1) { len = 0; } lastzero = word; len++; } if (len > longest) { longest = len; zstart = word - longest + 1; } } for (word = 0; word < 8; word++) { if (longest > 1) { // compress contiguous zeros - to produce "::" if (parts[word] === 0 && word >= zstart && word < (zstart + longest) ) { if (word === zstart) { str += ":"; if (zstart === 0) str += ":"; //leading zeros case } continue; } } // converts 16-bit words from big-endian to little-endian before converting to hex string str += Number(_ntohs(parts[word] & 0xffff)).toString(16); str += word < 7 ? ":" : ""; } return str; }, _read_sockaddr__deps: ['$Sockets', '_inet_ntop4_raw', '_inet_ntop6_raw', 'ntohs'], _read_sockaddr: function (sa, salen) { // family / port offsets are common to both sockaddr_in and sockaddr_in6 var family = {{{ makeGetValue('sa', C_STRUCTS.sockaddr_in.sin_family, 'i16') }}}; var port = _ntohs({{{ makeGetValue('sa', C_STRUCTS.sockaddr_in.sin_port, 'i16') }}}); var addr; switch (family) { case {{{ cDefine('AF_INET') }}}: if (salen !== {{{ C_STRUCTS.sockaddr_in.__size__ }}}) { return { errno: {{{ cDefine('EINVAL') }}} }; } addr = {{{ makeGetValue('sa', C_STRUCTS.sockaddr_in.sin_addr.s_addr, 'i32') }}}; addr = __inet_ntop4_raw(addr); break; case {{{ cDefine('AF_INET6') }}}: if (salen !== {{{ C_STRUCTS.sockaddr_in6.__size__ }}}) { return { errno: {{{ cDefine('EINVAL') }}} }; } addr = [ {{{ makeGetValue('sa', C_STRUCTS.sockaddr_in6.sin6_addr.__in6_union.__s6_addr+0, 'i32') }}}, {{{ makeGetValue('sa', C_STRUCTS.sockaddr_in6.sin6_addr.__in6_union.__s6_addr+4, 'i32') }}}, {{{ makeGetValue('sa', C_STRUCTS.sockaddr_in6.sin6_addr.__in6_union.__s6_addr+8, 'i32') }}}, {{{ makeGetValue('sa', C_STRUCTS.sockaddr_in6.sin6_addr.__in6_union.__s6_addr+12, 'i32') }}} ]; addr = __inet_ntop6_raw(addr); break; default: return { errno: {{{ cDefine('EAFNOSUPPORT') }}} }; } return { family: family, addr: addr, port: port }; }, _write_sockaddr__deps: ['$Sockets', '_inet_pton4_raw', '_inet_pton6_raw'], _write_sockaddr: function (sa, family, addr, port) { switch (family) { case {{{ cDefine('AF_INET') }}}: addr = __inet_pton4_raw(addr); {{{ makeSetValue('sa', C_STRUCTS.sockaddr_in.sin_family, 'family', 'i16') }}}; {{{ makeSetValue('sa', C_STRUCTS.sockaddr_in.sin_addr.s_addr, 'addr', 'i32') }}}; {{{ makeSetValue('sa', C_STRUCTS.sockaddr_in.sin_port, '_htons(port)', 'i16') }}}; break; case {{{ cDefine('AF_INET6') }}}: addr = __inet_pton6_raw(addr); {{{ makeSetValue('sa', C_STRUCTS.sockaddr_in6.sin6_family, 'family', 'i32') }}}; {{{ makeSetValue('sa', C_STRUCTS.sockaddr_in6.sin6_addr.__in6_union.__s6_addr+0, 'addr[0]', 'i32') }}}; {{{ makeSetValue('sa', C_STRUCTS.sockaddr_in6.sin6_addr.__in6_union.__s6_addr+4, 'addr[1]', 'i32') }}}; {{{ makeSetValue('sa', C_STRUCTS.sockaddr_in6.sin6_addr.__in6_union.__s6_addr+8, 'addr[2]', 'i32') }}}; {{{ makeSetValue('sa', C_STRUCTS.sockaddr_in6.sin6_addr.__in6_union.__s6_addr+12, 'addr[3]', 'i32') }}}; {{{ makeSetValue('sa', C_STRUCTS.sockaddr_in6.sin6_port, '_htons(port)', 'i16') }}}; {{{ makeSetValue('sa', C_STRUCTS.sockaddr_in6.sin6_flowinfo, '0', 'i32') }}}; {{{ makeSetValue('sa', C_STRUCTS.sockaddr_in6.sin6_scope_id, '0', 'i32') }}}; break; default: return { errno: {{{ cDefine('EAFNOSUPPORT') }}} }; } // kind of lame, but let's match _read_sockaddr's interface return {}; }, // We can't actually resolve hostnames in the browser, so instead // we're generating fake IP addresses with lookup_name that we can // resolve later on with lookup_addr. // We do the aliasing in 172.29.*.*, giving us 65536 possibilities. $DNS__deps: ['_inet_pton4_raw', '_inet_pton6_raw'], $DNS: { address_map: { id: 1, addrs: {}, names: {} }, lookup_name: function (name) { // If the name is already a valid ipv4 / ipv6 address, don't generate a fake one. var res = __inet_pton4_raw(name); if (res !== null) { return name; } res = __inet_pton6_raw(name); if (res !== null) { return name; } // See if this name is already mapped. var addr; if (DNS.address_map.addrs[name]) { addr = DNS.address_map.addrs[name]; } else { var id = DNS.address_map.id++; assert(id < 65535, 'exceeded max address mappings of 65535'); addr = '172.29.' + (id & 0xff) + '.' + (id & 0xff00); DNS.address_map.names[addr] = name; DNS.address_map.addrs[name] = addr; } return addr; }, lookup_addr: function (addr) { if (DNS.address_map.names[addr]) { return DNS.address_map.names[addr]; } return null; } }, // note: lots of leaking here! gethostbyaddr__deps: ['$DNS', 'gethostbyname', '_inet_ntop4_raw'], gethostbyaddr__proxy: 'sync', gethostbyaddr__sig: 'iiii', gethostbyaddr: function (addr, addrlen, type) { if (type !== {{{ cDefine('AF_INET') }}}) { ___setErrNo({{{ cDefine('EAFNOSUPPORT') }}}); // TODO: set h_errno return null; } addr = {{{ makeGetValue('addr', '0', 'i32') }}}; // addr is in_addr var host = __inet_ntop4_raw(addr); var lookup = DNS.lookup_addr(host); if (lookup) { host = lookup; } var hostp = allocate(intArrayFromString(host), 'i8', ALLOC_STACK); return _gethostbyname(hostp); }, gethostbyname__deps: ['$DNS', '_inet_pton4_raw'], gethostbyname__proxy: 'sync', gethostbyname__sig: 'ii', gethostbyname: function(name) { name = UTF8ToString(name); // generate hostent var ret = _malloc({{{ C_STRUCTS.hostent.__size__ }}}); // XXX possibly leaked, as are others here var nameBuf = _malloc(name.length+1); stringToUTF8(name, nameBuf, name.length+1); {{{ makeSetValue('ret', C_STRUCTS.hostent.h_name, 'nameBuf', 'i8*') }}}; var aliasesBuf = _malloc(4); {{{ makeSetValue('aliasesBuf', '0', '0', 'i8*') }}}; {{{ makeSetValue('ret', C_STRUCTS.hostent.h_aliases, 'aliasesBuf', 'i8**') }}}; var afinet = {{{ cDefine('AF_INET') }}}; {{{ makeSetValue('ret', C_STRUCTS.hostent.h_addrtype, 'afinet', 'i32') }}}; {{{ makeSetValue('ret', C_STRUCTS.hostent.h_length, '4', 'i32') }}}; var addrListBuf = _malloc(12); {{{ makeSetValue('addrListBuf', '0', 'addrListBuf+8', 'i32*') }}}; {{{ makeSetValue('addrListBuf', '4', '0', 'i32*') }}}; {{{ makeSetValue('addrListBuf', '8', '__inet_pton4_raw(DNS.lookup_name(name))', 'i32') }}}; {{{ makeSetValue('ret', C_STRUCTS.hostent.h_addr_list, 'addrListBuf', 'i8**') }}}; return ret; }, gethostbyname_r__deps: ['gethostbyname'], gethostbyname_r__proxy: 'sync', gethostbyname_r__sig: 'iiiiiii', gethostbyname_r: function(name, ret, buf, buflen, out, err) { var data = _gethostbyname(name); _memcpy(ret, data, {{{ C_STRUCTS.hostent.__size__ }}}); _free(data); {{{ makeSetValue('err', '0', '0', 'i32') }}}; {{{ makeSetValue('out', '0', 'ret', '*') }}}; return 0; }, getaddrinfo__deps: ['$Sockets', '$DNS', '_inet_pton4_raw', '_inet_ntop4_raw', '_inet_pton6_raw', '_inet_ntop6_raw', '_write_sockaddr'], getaddrinfo__proxy: 'sync', getaddrinfo__sig: 'iiiii', getaddrinfo: function(node, service, hint, out) { // Note getaddrinfo currently only returns a single addrinfo with ai_next defaulting to NULL. When NULL // hints are specified or ai_family set to AF_UNSPEC or ai_socktype or ai_protocol set to 0 then we // really should provide a linked list of suitable addrinfo values. var addrs = []; var canon = null; var addr = 0; var port = 0; var flags = 0; var family = {{{ cDefine('AF_UNSPEC') }}}; var type = 0; var proto = 0; var ai, last; function allocaddrinfo(family, type, proto, canon, addr, port) { var sa, salen, ai; var res; salen = family === {{{ cDefine('AF_INET6') }}} ? {{{ C_STRUCTS.sockaddr_in6.__size__ }}} : {{{ C_STRUCTS.sockaddr_in.__size__ }}}; addr = family === {{{ cDefine('AF_INET6') }}} ? __inet_ntop6_raw(addr) : __inet_ntop4_raw(addr); sa = _malloc(salen); res = __write_sockaddr(sa, family, addr, port); assert(!res.errno); ai = _malloc({{{ C_STRUCTS.addrinfo.__size__ }}}); {{{ makeSetValue('ai', C_STRUCTS.addrinfo.ai_family, 'family', 'i32') }}}; {{{ makeSetValue('ai', C_STRUCTS.addrinfo.ai_socktype, 'type', 'i32') }}}; {{{ makeSetValue('ai', C_STRUCTS.addrinfo.ai_protocol, 'proto', 'i32') }}}; {{{ makeSetValue('ai', C_STRUCTS.addrinfo.ai_canonname, 'canon', 'i32') }}}; {{{ makeSetValue('ai', C_STRUCTS.addrinfo.ai_addr, 'sa', '*') }}}; if (family === {{{ cDefine('AF_INET6') }}}) { {{{ makeSetValue('ai', C_STRUCTS.addrinfo.ai_addrlen, C_STRUCTS.sockaddr_in6.__size__, 'i32') }}}; } else { {{{ makeSetValue('ai', C_STRUCTS.addrinfo.ai_addrlen, C_STRUCTS.sockaddr_in.__size__, 'i32') }}}; } {{{ makeSetValue('ai', C_STRUCTS.addrinfo.ai_next, '0', 'i32') }}}; return ai; } if (hint) { flags = {{{ makeGetValue('hint', C_STRUCTS.addrinfo.ai_flags, 'i32') }}}; family = {{{ makeGetValue('hint', C_STRUCTS.addrinfo.ai_family, 'i32') }}}; type = {{{ makeGetValue('hint', C_STRUCTS.addrinfo.ai_socktype, 'i32') }}}; proto = {{{ makeGetValue('hint', C_STRUCTS.addrinfo.ai_protocol, 'i32') }}}; } if (type && !proto) { proto = type === {{{ cDefine('SOCK_DGRAM') }}} ? {{{ cDefine('IPPROTO_UDP') }}} : {{{ cDefine('IPPROTO_TCP') }}}; } if (!type && proto) { type = proto === {{{ cDefine('IPPROTO_UDP') }}} ? {{{ cDefine('SOCK_DGRAM') }}} : {{{ cDefine('SOCK_STREAM') }}}; } // If type or proto are set to zero in hints we should really be returning multiple addrinfo values, but for // now default to a TCP STREAM socket so we can at least return a sensible addrinfo given NULL hints. if (proto === 0) { proto = {{{ cDefine('IPPROTO_TCP') }}}; } if (type === 0) { type = {{{ cDefine('SOCK_STREAM') }}}; } if (!node && !service) { return {{{ cDefine('EAI_NONAME') }}}; } if (flags & ~({{{ cDefine('AI_PASSIVE') }}}|{{{ cDefine('AI_CANONNAME') }}}|{{{ cDefine('AI_NUMERICHOST') }}}| {{{ cDefine('AI_NUMERICSERV') }}}|{{{ cDefine('AI_V4MAPPED') }}}|{{{ cDefine('AI_ALL') }}}|{{{ cDefine('AI_ADDRCONFIG') }}})) { return {{{ cDefine('EAI_BADFLAGS') }}}; } if (hint !== 0 && ({{{ makeGetValue('hint', C_STRUCTS.addrinfo.ai_flags, 'i32') }}} & {{{ cDefine('AI_CANONNAME') }}}) && !node) { return {{{ cDefine('EAI_BADFLAGS') }}}; } if (flags & {{{ cDefine('AI_ADDRCONFIG') }}}) { // TODO return {{{ cDefine('EAI_NONAME') }}}; } if (type !== 0 && type !== {{{ cDefine('SOCK_STREAM') }}} && type !== {{{ cDefine('SOCK_DGRAM') }}}) { return {{{ cDefine('EAI_SOCKTYPE') }}}; } if (family !== {{{ cDefine('AF_UNSPEC') }}} && family !== {{{ cDefine('AF_INET') }}} && family !== {{{ cDefine('AF_INET6') }}}) { return {{{ cDefine('EAI_FAMILY') }}}; } if (service) { service = UTF8ToString(service); port = parseInt(service, 10); if (isNaN(port)) { if (flags & {{{ cDefine('AI_NUMERICSERV') }}}) { return {{{ cDefine('EAI_NONAME') }}}; } // TODO support resolving well-known service names from: // http://www.iana.org/assignments/service-names-port-numbers/service-names-port-numbers.txt return {{{ cDefine('EAI_SERVICE') }}}; } } if (!node) { if (family === {{{ cDefine('AF_UNSPEC') }}}) { family = {{{ cDefine('AF_INET') }}}; } if ((flags & {{{ cDefine('AI_PASSIVE') }}}) === 0) { if (family === {{{ cDefine('AF_INET') }}}) { addr = _htonl({{{ cDefine('INADDR_LOOPBACK') }}}); } else { addr = [0, 0, 0, 1]; } } ai = allocaddrinfo(family, type, proto, null, addr, port); {{{ makeSetValue('out', '0', 'ai', '*') }}}; return 0; } // // try as a numeric address // node = UTF8ToString(node); addr = __inet_pton4_raw(node); if (addr !== null) { // incoming node is a valid ipv4 address if (family === {{{ cDefine('AF_UNSPEC') }}} || family === {{{ cDefine('AF_INET') }}}) { family = {{{ cDefine('AF_INET') }}}; } else if (family === {{{ cDefine('AF_INET6') }}} && (flags & {{{ cDefine('AI_V4MAPPED') }}})) { addr = [0, 0, _htonl(0xffff), addr]; family = {{{ cDefine('AF_INET6') }}}; } else { return {{{ cDefine('EAI_NONAME') }}}; } } else { addr = __inet_pton6_raw(node); if (addr !== null) { // incoming node is a valid ipv6 address if (family === {{{ cDefine('AF_UNSPEC') }}} || family === {{{ cDefine('AF_INET6') }}}) { family = {{{ cDefine('AF_INET6') }}}; } else { return {{{ cDefine('EAI_NONAME') }}}; } } } if (addr != null) { ai = allocaddrinfo(family, type, proto, node, addr, port); {{{ makeSetValue('out', '0', 'ai', '*') }}}; return 0; } if (flags & {{{ cDefine('AI_NUMERICHOST') }}}) { return {{{ cDefine('EAI_NONAME') }}}; } // // try as a hostname // // resolve the hostname to a temporary fake address node = DNS.lookup_name(node); addr = __inet_pton4_raw(node); if (family === {{{ cDefine('AF_UNSPEC') }}}) { family = {{{ cDefine('AF_INET') }}}; } else if (family === {{{ cDefine('AF_INET6') }}}) { addr = [0, 0, _htonl(0xffff), addr]; } ai = allocaddrinfo(family, type, proto, null, addr, port); {{{ makeSetValue('out', '0', 'ai', '*') }}}; return 0; }, getnameinfo__deps: ['$Sockets', '$DNS', '_read_sockaddr'], getnameinfo: function (sa, salen, node, nodelen, serv, servlen, flags) { var info = __read_sockaddr(sa, salen); if (info.errno) { return {{{ cDefine('EAI_FAMILY') }}}; } var port = info.port; var addr = info.addr; var overflowed = false; if (node && nodelen) { var lookup; if ((flags & {{{ cDefine('NI_NUMERICHOST') }}}) || !(lookup = DNS.lookup_addr(addr))) { if (flags & {{{ cDefine('NI_NAMEREQD') }}}) { return {{{ cDefine('EAI_NONAME') }}}; } } else { addr = lookup; } var numBytesWrittenExclNull = stringToUTF8(addr, node, nodelen); if (numBytesWrittenExclNull+1 >= nodelen) { overflowed = true; } } if (serv && servlen) { port = '' + port; var numBytesWrittenExclNull = stringToUTF8(port, serv, servlen); if (numBytesWrittenExclNull+1 >= servlen) { overflowed = true; } } if (overflowed) { // Note: even when we overflow, getnameinfo() is specced to write out the truncated results. return {{{ cDefine('EAI_OVERFLOW') }}}; } return 0; }, // Can't use a literal for $GAI_ERRNO_MESSAGES as was done for $ERRNO_MESSAGES as the keys (e.g. EAI_BADFLAGS) // are actually negative numbers and you can't have expressions as keys in JavaScript literals. $GAI_ERRNO_MESSAGES: {}, gai_strerror__deps: ['$GAI_ERRNO_MESSAGES'], gai_strerror: function(val) { var buflen = 256; // On first call to gai_strerror we initialise the buffer and populate the error messages. if (!_gai_strerror.buffer) { _gai_strerror.buffer = _malloc(buflen); GAI_ERRNO_MESSAGES['0'] = 'Success'; GAI_ERRNO_MESSAGES['' + {{{ cDefine('EAI_BADFLAGS') }}}] = 'Invalid value for \'ai_flags\' field'; GAI_ERRNO_MESSAGES['' + {{{ cDefine('EAI_NONAME') }}}] = 'NAME or SERVICE is unknown'; GAI_ERRNO_MESSAGES['' + {{{ cDefine('EAI_AGAIN') }}}] = 'Temporary failure in name resolution'; GAI_ERRNO_MESSAGES['' + {{{ cDefine('EAI_FAIL') }}}] = 'Non-recoverable failure in name res'; GAI_ERRNO_MESSAGES['' + {{{ cDefine('EAI_FAMILY') }}}] = '\'ai_family\' not supported'; GAI_ERRNO_MESSAGES['' + {{{ cDefine('EAI_SOCKTYPE') }}}] = '\'ai_socktype\' not supported'; GAI_ERRNO_MESSAGES['' + {{{ cDefine('EAI_SERVICE') }}}] = 'SERVICE not supported for \'ai_socktype\''; GAI_ERRNO_MESSAGES['' + {{{ cDefine('EAI_MEMORY') }}}] = 'Memory allocation failure'; GAI_ERRNO_MESSAGES['' + {{{ cDefine('EAI_SYSTEM') }}}] = 'System error returned in \'errno\''; GAI_ERRNO_MESSAGES['' + {{{ cDefine('EAI_OVERFLOW') }}}] = 'Argument buffer overflow'; } var msg = 'Unknown error'; if (val in GAI_ERRNO_MESSAGES) { if (GAI_ERRNO_MESSAGES[val].length > buflen - 1) { msg = 'Message too long'; // EMSGSIZE message. This should never occur given the GAI_ERRNO_MESSAGES above. } else { msg = GAI_ERRNO_MESSAGES[val]; } } writeAsciiToMemory(msg, _gai_strerror.buffer); return _gai_strerror.buffer; }, // Implement netdb.h protocol entry (getprotoent, getprotobyname, getprotobynumber, setprotoent, endprotoent) // http://pubs.opengroup.org/onlinepubs/9699919799/functions/getprotobyname.html // The Protocols object holds our 'fake' protocols 'database'. $Protocols: { list: [], map: {} }, setprotoent__deps: ['$Protocols'], setprotoent: function(stayopen) { // void setprotoent(int stayopen); // Allocate and populate a protoent structure given a name, protocol number and array of aliases function allocprotoent(name, proto, aliases) { // write name into buffer var nameBuf = _malloc(name.length + 1); writeAsciiToMemory(name, nameBuf); // write aliases into buffer var j = 0; var length = aliases.length; var aliasListBuf = _malloc((length + 1) * 4); // Use length + 1 so we have space for the terminating NULL ptr. for (var i = 0; i < length; i++, j += 4) { var alias = aliases[i]; var aliasBuf = _malloc(alias.length + 1); writeAsciiToMemory(alias, aliasBuf); {{{ makeSetValue('aliasListBuf', 'j', 'aliasBuf', 'i8*') }}}; } {{{ makeSetValue('aliasListBuf', 'j', '0', 'i8*') }}}; // Terminating NULL pointer. // generate protoent var pe = _malloc({{{ C_STRUCTS.protoent.__size__ }}}); {{{ makeSetValue('pe', C_STRUCTS.protoent.p_name, 'nameBuf', 'i8*') }}}; {{{ makeSetValue('pe', C_STRUCTS.protoent.p_aliases, 'aliasListBuf', 'i8**') }}}; {{{ makeSetValue('pe', C_STRUCTS.protoent.p_proto, 'proto', 'i32') }}}; return pe; }; // Populate the protocol 'database'. The entries are limited to tcp and udp, though it is fairly trivial // to add extra entries from /etc/protocols if desired - though not sure if that'd actually be useful. var list = Protocols.list; var map = Protocols.map; if (list.length === 0) { var entry = allocprotoent('tcp', 6, ['TCP']); list.push(entry); map['tcp'] = map['6'] = entry; entry = allocprotoent('udp', 17, ['UDP']); list.push(entry); map['udp'] = map['17'] = entry; } _setprotoent.index = 0; }, endprotoent: function() { // void endprotoent(void); // We're not using a real protocol database so we don't do a real close. }, getprotoent__deps: ['setprotoent', '$Protocols'], getprotoent: function(number) { // struct protoent *getprotoent(void); // reads the next entry from the protocols 'database' or return NULL if 'eof' if (_setprotoent.index === Protocols.list.length) { return 0; } else { var result = Protocols.list[_setprotoent.index++]; return result; } }, getprotobyname__deps: ['setprotoent', '$Protocols'], getprotobyname: function(name) { // struct protoent *getprotobyname(const char *); name = UTF8ToString(name); _setprotoent(true); var result = Protocols.map[name]; return result; }, getprotobynumber__deps: ['setprotoent', '$Protocols'], getprotobynumber: function(number) { // struct protoent *getprotobynumber(int proto); _setprotoent(true); var result = Protocols.map[number]; return result; }, // ========================================================================== // sockets. Note that the implementation assumes all sockets are always // nonblocking // ========================================================================== #if SOCKET_WEBRTC $Sockets__deps: ['__setErrNo', function() { return 'var SocketIO = ' + read('socket.io.js') + ';\n' }, function() { return 'var Peer = ' + read('wrtcp.js') + ';\n' }], #else $Sockets__deps: ['__setErrNo'], #endif $Sockets: { BUFFER_SIZE: 10*1024, // initial size MAX_BUFFER_SIZE: 10*1024*1024, // maximum size we will grow the buffer nextFd: 1, fds: {}, nextport: 1, maxport: 65535, peer: null, connections: {}, portmap: {}, localAddr: 0xfe00000a, // Local address is always 10.0.0.254 addrPool: [ 0x0200000a, 0x0300000a, 0x0400000a, 0x0500000a, 0x0600000a, 0x0700000a, 0x0800000a, 0x0900000a, 0x0a00000a, 0x0b00000a, 0x0c00000a, 0x0d00000a, 0x0e00000a] /* 0x0100000a is reserved */ }, // pwd.h getpwnam: function() { throw 'getpwnam: TODO' }, setpwent: function() { throw 'setpwent: TODO' }, getpwent: function() { throw 'getpwent: TODO' }, endpwent: function() { throw 'endpwent: TODO' }, // ========================================================================== // emscripten.h // ========================================================================== emscripten_run_script: function(ptr) { {{{ makeEval('eval(UTF8ToString(ptr));') }}} }, emscripten_run_script_int: function(ptr) { {{{ makeEval('return eval(UTF8ToString(ptr))|0;') }}} }, emscripten_run_script_string: function(ptr) { {{{ makeEval("var s = eval(UTF8ToString(ptr));") }}} if (s == null) { return 0; } s += ''; var me = _emscripten_run_script_string; var len = lengthBytesUTF8(s); if (!me.bufferSize || me.bufferSize < len+1) { if (me.bufferSize) _free(me.buffer); me.bufferSize = len+1; me.buffer = _malloc(me.bufferSize); } stringToUTF8(s, me.buffer, me.bufferSize); return me.buffer; }, emscripten_random: function() { return Math.random(); }, emscripten_get_now: function() { abort() }, // replaced by the postset at startup time emscripten_get_now__postset: #if ENVIRONMENT_MAY_BE_NODE "if (ENVIRONMENT_IS_NODE) {\n" + " _emscripten_get_now = function _emscripten_get_now_actual() {\n" + " var t = process['hrtime']();\n" + " return t[0] * 1e3 + t[1] / 1e6;\n" + " };\n" + "} else " + #endif #if USE_PTHREADS // Pthreads need their clocks synchronized to the execution of the main thread, so give them a special form of the function. "if (ENVIRONMENT_IS_PTHREAD) {\n" + " _emscripten_get_now = function() { return performance['now']() - __performance_now_clock_drift; };\n" + "} else " + #endif "if (typeof dateNow !== 'undefined') {\n" + " _emscripten_get_now = dateNow;\n" + "} else if (typeof performance === 'object' && performance && typeof performance['now'] === 'function') {\n" + " _emscripten_get_now = function() { return performance['now'](); };\n" + "} else {\n" + " _emscripten_get_now = Date.now;\n" + "}", emscripten_get_now_res: function() { // return resolution of get_now, in nanoseconds #if ENVIRONMENT_MAY_BE_NODE if (ENVIRONMENT_IS_NODE) { return 1; // nanoseconds } else #endif #if ENVIRONMENT_MAY_BE_SHELL if (typeof dateNow !== 'undefined') { return 1000; // microseconds (1/1000 of a millisecond) } else #endif if (typeof performance === 'object' && performance && typeof performance['now'] === 'function') { return 1000; // microseconds (1/1000 of a millisecond) } else { return 1000*1000; // milliseconds } }, emscripten_get_now_is_monotonic__deps: ['emscripten_get_now'], emscripten_get_now_is_monotonic: function() { // return whether emscripten_get_now is guaranteed monotonic; the Date.now // implementation is not :( return (0 #if ENVIRONMENT_MAY_BE_NODE || ENVIRONMENT_IS_NODE #endif #if ENVIRONMENT_MAY_BE_SHELL || (typeof dateNow !== 'undefined') #endif #if ENVIRONMENT_MAY_BE_WEB || ENVIRONMENT_MAY_BE_WORKER || (typeof performance === 'object' && performance && typeof performance['now'] === 'function') #endif ); }, #if MINIMAL_RUNTIME $warnOnce: function(text) { if (!warnOnce.shown) warnOnce.shown = {}; if (!warnOnce.shown[text]) { warnOnce.shown[text] = 1; err(text); } }, #endif // Returns [parentFuncArguments, functionName, paramListName] _emscripten_traverse_stack: function(args) { if (!args || !args.callee || !args.callee.name) { return [null, '', '']; } var funstr = args.callee.toString(); var funcname = args.callee.name; var str = '('; var first = true; for (var i in args) { var a = args[i]; if (!first) { str += ", "; } first = false; if (typeof a === 'number' || typeof a === 'string') { str += a; } else { str += '(' + typeof a + ')'; } } str += ')'; var caller = args.callee.caller; args = caller ? caller.arguments : []; if (first) str = ''; return [args, funcname, str]; }, emscripten_get_callstack_js__deps: ['_emscripten_traverse_stack', '$jsStackTrace', '$demangle' #if MINIMAL_RUNTIME , '$warnOnce' #endif ], emscripten_get_callstack_js: function(flags) { var callstack = jsStackTrace(); // Find the symbols in the callstack that corresponds to the functions that report callstack information, and remove everyhing up to these from the output. var iThisFunc = callstack.lastIndexOf('_emscripten_log'); var iThisFunc2 = callstack.lastIndexOf('_emscripten_get_callstack'); var iNextLine = callstack.indexOf('\n', Math.max(iThisFunc, iThisFunc2))+1; callstack = callstack.slice(iNextLine); // If user requested to see the original source stack, but no source map information is available, just fall back to showing the JS stack. if (flags & 8/*EM_LOG_C_STACK*/ && typeof emscripten_source_map === 'undefined') { warnOnce('Source map information is not available, emscripten_log with EM_LOG_C_STACK will be ignored. Build with "--pre-js $EMSCRIPTEN/src/emscripten-source-map.min.js" linker flag to add source map loading to code.'); flags ^= 8/*EM_LOG_C_STACK*/; flags |= 16/*EM_LOG_JS_STACK*/; } var stack_args = null; if (flags & 128 /*EM_LOG_FUNC_PARAMS*/) { // To get the actual parameters to the functions, traverse the stack via the unfortunately deprecated 'arguments.callee' method, if it works: stack_args = __emscripten_traverse_stack(arguments); while (stack_args[1].indexOf('_emscripten_') >= 0) stack_args = __emscripten_traverse_stack(stack_args[0]); } // Process all lines: var lines = callstack.split('\n'); callstack = ''; var newFirefoxRe = new RegExp('\\s*(.*?)@(.*?):([0-9]+):([0-9]+)'); // New FF30 with column info: extract components of form ' Object._main@http://server.com:4324:12' var firefoxRe = new RegExp('\\s*(.*?)@(.*):(.*)(:(.*))?'); // Old FF without column info: extract components of form ' Object._main@http://server.com:4324' var chromeRe = new RegExp('\\s*at (.*?) \\\((.*):(.*):(.*)\\\)'); // Extract components of form ' at Object._main (http://server.com/file.html:4324:12)' for (var l in lines) { var line = lines[l]; var jsSymbolName = ''; var file = ''; var lineno = 0; var column = 0; var parts = chromeRe.exec(line); if (parts && parts.length == 5) { jsSymbolName = parts[1]; file = parts[2]; lineno = parts[3]; column = parts[4]; } else { parts = newFirefoxRe.exec(line); if (!parts) parts = firefoxRe.exec(line); if (parts && parts.length >= 4) { jsSymbolName = parts[1]; file = parts[2]; lineno = parts[3]; column = parts[4]|0; // Old Firefox doesn't carry column information, but in new FF30, it is present. See https://bugzilla.mozilla.org/show_bug.cgi?id=762556 } else { // Was not able to extract this line for demangling/sourcemapping purposes. Output it as-is. callstack += line + '\n'; continue; } } // Try to demangle the symbol, but fall back to showing the original JS symbol name if not available. var cSymbolName = (flags & 32/*EM_LOG_DEMANGLE*/) ? demangle(jsSymbolName) : jsSymbolName; if (!cSymbolName) { cSymbolName = jsSymbolName; } var haveSourceMap = false; if (flags & 8/*EM_LOG_C_STACK*/) { var orig = emscripten_source_map.originalPositionFor({line: lineno, column: column}); haveSourceMap = (orig && orig.source); if (haveSourceMap) { if (flags & 64/*EM_LOG_NO_PATHS*/) { orig.source = orig.source.substring(orig.source.replace(/\\/g, "/").lastIndexOf('/')+1); } callstack += ' at ' + cSymbolName + ' (' + orig.source + ':' + orig.line + ':' + orig.column + ')\n'; } } if ((flags & 16/*EM_LOG_JS_STACK*/) || !haveSourceMap) { if (flags & 64/*EM_LOG_NO_PATHS*/) { file = file.substring(file.replace(/\\/g, "/").lastIndexOf('/')+1); } callstack += (haveSourceMap ? (' = '+jsSymbolName) : (' at '+cSymbolName)) + ' (' + file + ':' + lineno + ':' + column + ')\n'; } // If we are still keeping track with the callstack by traversing via 'arguments.callee', print the function parameters as well. if (flags & 128 /*EM_LOG_FUNC_PARAMS*/ && stack_args[0]) { if (stack_args[1] == jsSymbolName && stack_args[2].length > 0) { callstack = callstack.replace(/\s+$/, ''); callstack += ' with values: ' + stack_args[1] + stack_args[2] + '\n'; } stack_args = __emscripten_traverse_stack(stack_args[0]); } } // Trim extra whitespace at the end of the output. callstack = callstack.replace(/\s+$/, ''); return callstack; }, emscripten_get_callstack__deps: ['emscripten_get_callstack_js'], emscripten_get_callstack: function(flags, str, maxbytes) { var callstack = _emscripten_get_callstack_js(flags); // User can query the required amount of bytes to hold the callstack. if (!str || maxbytes <= 0) { return lengthBytesUTF8(callstack)+1; } // Output callstack string as C string to HEAP. var bytesWrittenExcludingNull = stringToUTF8(callstack, str, maxbytes); // Return number of bytes written, including null. return bytesWrittenExcludingNull+1; }, emscripten_log_js__deps: ['emscripten_get_callstack_js'], emscripten_log_js: function(flags, str) { if (flags & 24/*EM_LOG_C_STACK | EM_LOG_JS_STACK*/) { str = str.replace(/\s+$/, ''); // Ensure the message and the callstack are joined cleanly with exactly one newline. str += (str.length > 0 ? '\n' : '') + _emscripten_get_callstack_js(flags); } if (flags & 1 /*EM_LOG_CONSOLE*/) { if (flags & 4 /*EM_LOG_ERROR*/) { console.error(str); } else if (flags & 2 /*EM_LOG_WARN*/) { console.warn(str); } else { console.log(str); } } else if (flags & 6 /*EM_LOG_ERROR|EM_LOG_WARN*/) { err(str); } else { out(str); } }, emscripten_log__deps: ['_formatString', 'emscripten_log_js'], emscripten_log: function(flags, varargs) { // Extract the (optionally-existing) printf format specifier field from varargs. var format = {{{ makeGetValue('varargs', '0', 'i32', undefined, undefined, true) }}}; varargs += {{{ Math.max(Runtime.getNativeFieldSize('i32'), Runtime.getAlignSize('i32', null, true)) }}}; var str = ''; if (format) { var result = __formatString(format, varargs); for(var i = 0 ; i < result.length; ++i) { str += String.fromCharCode(result[i]); } } _emscripten_log_js(flags, str); }, emscripten_get_compiler_setting: function(name) { name = UTF8ToString(name); var ret = getCompilerSetting(name); if (typeof ret === 'number') return ret; if (!_emscripten_get_compiler_setting.cache) _emscripten_get_compiler_setting.cache = {}; var cache = _emscripten_get_compiler_setting.cache; var fullname = name + '__str'; var fullret = cache[fullname]; if (fullret) return fullret; return cache[fullname] = allocate(intArrayFromString(ret + ''), 'i8', ALLOC_NORMAL); }, emscripten_debugger: function() { debugger; }, emscripten_print_double: function(x, to, max) { var str = x + ''; if (to) return stringToUTF8(str, to, max); else return lengthBytesUTF8(str); }, // Generates a representation of the program counter from a line of stack trace. // The exact return value depends in whether we are running WASM or JS, and whether // the engine supports offsets into WASM. See the function body for details. emscripten_generate_pc: function(frame) { #if !USE_OFFSET_CONVERTER abort('Cannot use emscripten_generate_pc (needed by __builtin_return_address) without -s USE_OFFSET_CONVERTER'); #endif var match; if (match = /\bwasm-function\[\d+\]:(0x[0-9a-f]+)/.exec(frame)) { // some engines give the binary offset directly, so we use that as return address return +match[1]; } else if (match = /\bwasm-function\[(\d+)\]:(\d+)/.exec(frame)) { // other engines only give function index and offset in the function, // so we try using the offset converter. If that doesn't work, // we pack index and offset into a "return address" return wasmOffsetConverter.convert(+match[1], +match[2]); } else if (match = /:(\d+):\d+(?:\)|$)/.exec(frame)) { // if we are in js, we can use the js line number as the "return address" // this should work for wasm2js and fastcomp // we tag the high bit to distinguish this from wasm addresses return 0x80000000 | +match[1]; } else { // return 0 if we can't find any return 0; } }, // Returns a representation of a call site of the caller of this function, in a manner // similar to __builtin_return_address. If level is 0, we return the call site of the // caller of this function. emscripten_return_address__deps: ['emscripten_generate_pc'], emscripten_return_address: function(level) { var callstack = new Error().stack.split('\n'); if (callstack[0] == 'Error') { callstack.shift(); } // skip this function and the caller to get caller's return address return _emscripten_generate_pc(callstack[level + 2]); }, $UNWIND_CACHE: {}, // This function pulls the JavaScript stack trace and updates UNWIND_CACHE so that // our representation of the program counter is mapped to the line of the stack trace // for every line in the stack trace. This allows emscripten_pc_get_* to lookup the // line of the stack trace from the PC and return meaningful information. // // Additionally, it saves a copy of the entire stack trace and the return address of // the caller. This is because there are two common forms of a stack trace. // The first form starts the stack trace at the caller of the function requesting a stack // trace. In this case, the function can simply walk down the stack from the return address // using emscripten_return_address with increasing values for level. // The second form starts the stack trace at the current function. This requires a helper // function to get the program counter. This helper function will return the return address. // This is the program counter at the call site. But there is a problem: when calling into // code that performs stack unwinding, the program counter has changed since execution // continued from calling the helper function. So we can't just walk down the stack and expect // to see.the PC value we got. By caching the call stack, we can call emscripten_stack_unwind // with the PC value and use that to unwind the cached stack. Naturally, the PC helper function // will have to call emscripten_stack_snapshot to cache the stack. We also return the return // address of the caller so the PC helper function does not need to call // emscripten_return_address, saving a lot of time. // // One might expect that a sensible solution is to call the stack unwinder and explicitly tell it // how many functions to skip from the stack. However, existing libraries do not work this way. // For example, compiler-rt's sanitizer_common library has macros GET_CALLER_PC_BP_SP and // GET_CURRENT_PC_BP_SP, which obtains the PC value for the two common cases stated above, // respectively. Then, it passes the PC, BP, SP values along until some other function uses them // to unwind. On standard machines, the stack can be unwound by treating BP as a linked list. // This makes PC unnecessary to walk the stack, since walking is done with BP, which remains // valid until the function returns. But on Emscripten, BP does not exist, at least in // JavaScript frames, so we have to rely on PC values. Therefore, we must be able to unwind from // a PC value that may no longer be on the execution stack, and so we are forced to cache the // entire call stack. emscripten_stack_snapshot__deps: ['emscripten_generate_pc', '$UNWIND_CACHE', '_emscripten_save_in_unwind_cache'], emscripten_stack_snapshot: function () { var callstack = new Error().stack.split('\n'); if (callstack[0] == 'Error') { callstack.shift(); } __emscripten_save_in_unwind_cache(callstack); // Caches the stack snapshot so that emscripten_stack_unwind_buffer() can unwind from this spot. UNWIND_CACHE.last_addr = _emscripten_generate_pc(callstack[2]); UNWIND_CACHE.last_stack = callstack; return UNWIND_CACHE.last_addr; }, _emscripten_save_in_unwind_cache__deps: ['$UNWIND_CACHE', 'emscripten_generate_pc'], _emscripten_save_in_unwind_cache: function (callstack) { callstack.forEach(function (frame) { var pc = _emscripten_generate_pc(frame); if (pc) { UNWIND_CACHE[pc] = frame; } }); }, // Unwinds the stack from a cached PC value. See emscripten_stack_snapshot for how this is used. // addr must be the return address of the last call to emscripten_stack_snapshot, or this // function will instead use the current call stack. emscripten_stack_unwind_buffer__deps: ['$UNWIND_CACHE', '_emscripten_save_in_unwind_cache', 'emscripten_generate_pc'], emscripten_stack_unwind_buffer: function (addr, buffer, count) { var stack; if (UNWIND_CACHE.last_addr == addr) { stack = UNWIND_CACHE.last_stack; } else { stack = new Error().stack.split('\n'); if (stack[0] == 'Error') { stack.shift(); } __emscripten_save_in_unwind_cache(stack); } var offset = 2; while (stack[offset] && _emscripten_generate_pc(stack[offset]) != addr) { ++offset; } for (var i = 0; i < count && stack[i+offset]; ++i) { {{{ makeSetValue('buffer', 'i*4', '_emscripten_generate_pc(stack[i + offset])', 'i32', 0, true) }}}; } return i; }, // Look up the function name from our stack frame cache with our PC representation. emscripten_pc_get_function__deps: ['$UNWIND_CACHE', 'emscripten_with_builtin_malloc'], emscripten_pc_get_function: function (pc) { #if !USE_OFFSET_CONVERTER abort('Cannot use emscripten_pc_get_function without -s USE_OFFSET_CONVERTER'); #endif var name; if (pc & 0x80000000) { // If this is a JavaScript function, try looking it up in the unwind cache. var frame = UNWIND_CACHE[pc]; if (!frame) return 0; var match; if (match = /^\s+at (.*) \(.*\)$/.exec(frame)) { name = match[1]; } else if (match = /^(.+?)@/.exec(frame)) { name = match[1]; } else { return 0; } } else { name = wasmOffsetConverter.getName(pc); } _emscripten_with_builtin_malloc(function () { if (_emscripten_pc_get_function.ret) _free(_emscripten_pc_get_function.ret); _emscripten_pc_get_function.ret = allocateUTF8(name); }); return _emscripten_pc_get_function.ret; }, emscripten_pc_get_source_js__deps: ['$UNWIND_CACHE', 'emscripten_generate_pc'], emscripten_pc_get_source_js: function (pc) { if (UNWIND_CACHE.last_get_source_pc == pc) return UNWIND_CACHE.last_source; var match; var source; #if LOAD_SOURCE_MAP if (wasmSourceMap) { var info = wasmSourceMap.lookup(pc); if (info) { source = {file: info.source, line: info.line, column: info.column}; } } #endif if (!source) { var frame = UNWIND_CACHE[pc]; if (!frame) return null; // Example: at callMain (a.out.js:6335:22) if (match = /\((.*):(\d+):(\d+)\)$/.exec(frame)) { source = {file: match[1], line: match[2], column: match[3]}; // Example: [email protected]:1337:42 } else if (match = /@(.*):(\d+):(\d+)/.exec(frame)) { source = {file: match[1], line: match[2], column: match[3]}; } } UNWIND_CACHE.last_get_source_pc = pc; UNWIND_CACHE.last_source = source; return source; }, // Look up the file name from our stack frame cache with our PC representation. emscripten_pc_get_file__deps: ['emscripten_pc_get_source_js', 'emscripten_with_builtin_malloc'], emscripten_pc_get_file: function (pc) { var result = _emscripten_pc_get_source_js(pc); if (!result) return 0; _emscripten_with_builtin_malloc(function () { if (_emscripten_pc_get_file.ret) _free(_emscripten_pc_get_file.ret); _emscripten_pc_get_file.ret = allocateUTF8(result.file); }); return _emscripten_pc_get_file.ret; }, // Look up the line number from our stack frame cache with our PC representation. emscripten_pc_get_line__deps: ['emscripten_pc_get_source_js'], emscripten_pc_get_line: function (pc) { var result = _emscripten_pc_get_source_js(pc); return result ? result.line : 0; }, // Look up the column number from our stack frame cache with our PC representation. emscripten_pc_get_column__deps: ['emscripten_pc_get_source_js'], emscripten_pc_get_column: function (pc) { var result = _emscripten_pc_get_source_js(pc); return result ? result.column || 0 : 0; }, emscripten_get_module_name: function(buf, length) { return stringToUTF8(wasmBinaryFile, buf, length); }, emscripten_with_builtin_malloc__deps: ['emscripten_builtin_malloc', 'emscripten_builtin_free', 'emscripten_builtin_memalign'], emscripten_with_builtin_malloc: function (func) { var prev_malloc = _malloc; var prev_memalign = _memalign; var prev_free = _free; _malloc = _emscripten_builtin_malloc; _memalign = _emscripten_builtin_memalign; _free = _emscripten_builtin_free; try { return func(); } finally { _malloc = prev_malloc; _memalign = prev_memalign; _free = prev_free; } }, emscripten_builtin_mmap2__deps: ['emscripten_with_builtin_malloc', '_emscripten_syscall_mmap2'], emscripten_builtin_mmap2: function (addr, len, prot, flags, fd, off) { return _emscripten_with_builtin_malloc(function () { return __emscripten_syscall_mmap2(addr, len, prot, flags, fd, off); }); }, emscripten_builtin_munmap__deps: ['emscripten_with_builtin_malloc', '_emscripten_syscall_munmap'], emscripten_builtin_munmap: function (addr, len) { return _emscripten_with_builtin_malloc(function () { return __emscripten_syscall_munmap(addr, len); }); }, emscripten_get_stack_top: function() { return STACKTOP; }, emscripten_get_stack_base: function() { return STACK_BASE; }, //============================ // i64 math //============================ i64Add__asm: true, i64Add__sig: 'iiiii', i64Add: function(a, b, c, d) { /* x = a + b*2^32 y = c + d*2^32 result = l + h*2^32 */ a = a|0; b = b|0; c = c|0; d = d|0; var l = 0, h = 0; l = (a + c)>>>0; h = (b + d + (((l>>>0) < (a>>>0))|0))>>>0; // Add carry from low word to high word on overflow. {{{ makeStructuralReturn(['l|0', 'h'], true) }}}; }, i64Subtract__asm: true, i64Subtract__sig: 'iiiii', i64Subtract: function(a, b, c, d) { a = a|0; b = b|0; c = c|0; d = d|0; var l = 0, h = 0; l = (a - c)>>>0; h = (b - d)>>>0; h = (b - d - (((c>>>0) > (a>>>0))|0))>>>0; // Borrow one from high word to low word on underflow. {{{ makeStructuralReturn(['l|0', 'h'], true) }}}; }, bitshift64Shl__asm: true, bitshift64Shl__sig: 'iiii', bitshift64Shl: function(low, high, bits) { low = low|0; high = high|0; bits = bits|0; var ander = 0; if ((bits|0) < 32) { ander = ((1 << bits) - 1)|0; {{{ makeSetTempRet0('(high << bits) | ((low&(ander << (32 - bits))) >>> (32 - bits))') }}}; return low << bits; } {{{ makeSetTempRet0('low << (bits - 32)') }}}; return 0; }, bitshift64Ashr__asm: true, bitshift64Ashr__sig: 'iiii', bitshift64Ashr: function(low, high, bits) { low = low|0; high = high|0; bits = bits|0; var ander = 0; if ((bits|0) < 32) { ander = ((1 << bits) - 1)|0; {{{ makeSetTempRet0('high >> bits') }}}; return (low >>> bits) | ((high&ander) << (32 - bits)); } {{{ makeSetTempRet0('(high|0) < 0 ? -1 : 0') }}}; return (high >> (bits - 32))|0; }, bitshift64Lshr__asm: true, bitshift64Lshr__sig: 'iiii', bitshift64Lshr: function(low, high, bits) { low = low|0; high = high|0; bits = bits|0; var ander = 0; if ((bits|0) < 32) { ander = ((1 << bits) - 1)|0; {{{ makeSetTempRet0('high >>> bits') }}}; return (low >>> bits) | ((high&ander) << (32 - bits)); } {{{ makeSetTempRet0('0') }}}; return (high >>> (bits - 32))|0; }, // misc shims for musl __lock: function() {}, __unlock: function() {}, __lockfile: function() { return 1 }, __unlockfile: function(){}, // USE_FULL_LIBRARY hacks realloc: function() { throw 'bad realloc called' }, // libunwind _Unwind_Backtrace__deps: ['emscripten_get_callstack_js'], _Unwind_Backtrace: function(func, arg) { var trace = _emscripten_get_callstack_js(); var parts = trace.split('\n'); for (var i = 0; i < parts.length; i++) { var ret = {{{ makeDynCall('iii') }}}(func, 0, arg); if (ret !== 0) return; } }, _Unwind_GetIPInfo: function() { abort('Unwind_GetIPInfo'); }, _Unwind_FindEnclosingFunction: function() { return 0; // we cannot succeed }, _Unwind_RaiseException__deps: ['__cxa_throw'], _Unwind_RaiseException: function(ex) { err('Warning: _Unwind_RaiseException is not correctly implemented'); return ___cxa_throw(ex, 0, 0); }, _Unwind_DeleteException: function(ex) { err('TODO: Unwind_DeleteException'); }, // error handling $runAndAbortIfError: function(func) { try { return func(); } catch (e) { abort(e); } }, // autodebugging emscripten_autodebug_i64: function(line, valuel, valueh) { out('AD:' + [line, valuel, valueh]); }, emscripten_autodebug_i32: function(line, value) { out('AD:' + [line, value]); }, emscripten_autodebug_i16: function(line, value) { out('AD:' + [line, value]); }, emscripten_autodebug_i8: function(line, value) { out('AD:' + [line, value]); }, emscripten_autodebug_float: function(line, value) { out('AD:' + [line, value]); }, emscripten_autodebug_double: function(line, value) { out('AD:' + [line, value]); }, // special runtime support emscripten_scan_stack: function(func) { var base = STACK_BASE; // TODO verify this is right on pthreads var end = stackSave(); {{{ makeDynCall('vii') }}}(func, Math.min(base, end), Math.max(base, end)); }, // misc definitions to avoid unnecessary unresolved symbols from fastcomp #if SUPPORT_LONGJMP emscripten_prep_setjmp: true, emscripten_cleanup_setjmp: true, emscripten_check_longjmp: true, emscripten_get_longjmp_result: true, emscripten_setjmp: true, #endif emscripten_preinvoke: true, emscripten_postinvoke: true, emscripten_resume: true, emscripten_landingpad: true, getHigh32: true, setHigh32: true, FtoILow: true, FtoIHigh: true, DtoILow: true, DtoIHigh: true, BDtoILow: true, BDtoIHigh: true, SItoF: true, UItoF: true, SItoD: true, UItoD: true, BItoD: true, llvm_dbg_value: true, llvm_debugtrap: true, llvm_ctlz_i32: true, emscripten_asm_const: true, emscripten_asm_const_int: true, emscripten_asm_const_double: true, emscripten_asm_const_int_sync_on_main_thread: true, emscripten_asm_const_double_sync_on_main_thread: true, emscripten_asm_const_async_on_main_thread: true, // ======== compiled code from system/lib/compiler-rt , see readme therein __muldsi3__asm: true, __muldsi3__sig: 'iii', __muldsi3__deps: ['Math_imul'], __muldsi3: function($a, $b) { $a = $a | 0; $b = $b | 0; var $1 = 0, $2 = 0, $3 = 0, $6 = 0, $8 = 0, $11 = 0, $12 = 0; $1 = $a & 65535; $2 = $b & 65535; $3 = Math_imul($2, $1) | 0; $6 = $a >>> 16; $8 = ($3 >>> 16) + (Math_imul($2, $6) | 0) | 0; $11 = $b >>> 16; $12 = Math_imul($11, $1) | 0; return ({{{ makeSetTempRet0('(($8 >>> 16) + (Math_imul($11, $6) | 0) | 0) + ((($8 & 65535) + $12 | 0) >>> 16) | 0') }}}, 0 | ($8 + $12 << 16 | $3 & 65535)) | 0; }, __divdi3__sig: 'iiiii', __divdi3__asm: true, __divdi3__deps: ['__udivmoddi4', 'i64Subtract'], __divdi3: function($a$0, $a$1, $b$0, $b$1) { $a$0 = $a$0 | 0; $a$1 = $a$1 | 0; $b$0 = $b$0 | 0; $b$1 = $b$1 | 0; var $1$0 = 0, $1$1 = 0, $2$0 = 0, $2$1 = 0, $4$0 = 0, $4$1 = 0, $6$0 = 0, $7$0 = 0, $7$1 = 0, $8$0 = 0, $10$0 = 0; $1$0 = $a$1 >> 31 | (($a$1 | 0) < 0 ? -1 : 0) << 1; $1$1 = (($a$1 | 0) < 0 ? -1 : 0) >> 31 | (($a$1 | 0) < 0 ? -1 : 0) << 1; $2$0 = $b$1 >> 31 | (($b$1 | 0) < 0 ? -1 : 0) << 1; $2$1 = (($b$1 | 0) < 0 ? -1 : 0) >> 31 | (($b$1 | 0) < 0 ? -1 : 0) << 1; $4$0 = _i64Subtract($1$0 ^ $a$0 | 0, $1$1 ^ $a$1 | 0, $1$0 | 0, $1$1 | 0) | 0; $4$1 = {{{ makeGetTempRet0() }}}; $6$0 = _i64Subtract($2$0 ^ $b$0 | 0, $2$1 ^ $b$1 | 0, $2$0 | 0, $2$1 | 0) | 0; $7$0 = $2$0 ^ $1$0; $7$1 = $2$1 ^ $1$1; $8$0 = ___udivmoddi4($4$0, $4$1, $6$0, {{{ makeGetTempRet0() }}}, 0) | 0; $10$0 = _i64Subtract($8$0 ^ $7$0 | 0, {{{ makeGetTempRet0() }}} ^ $7$1 | 0, $7$0 | 0, $7$1 | 0) | 0; return $10$0 | 0; }, __remdi3__sig: 'iiiii', __remdi3__asm: true, __remdi3__deps: ['__udivmoddi4', 'i64Subtract'], __remdi3: function($a$0, $a$1, $b$0, $b$1) { $a$0 = $a$0 | 0; $a$1 = $a$1 | 0; $b$0 = $b$0 | 0; $b$1 = $b$1 | 0; var $rem = 0, $1$0 = 0, $1$1 = 0, $2$0 = 0, $2$1 = 0, $4$0 = 0, $4$1 = 0, $6$0 = 0, $10$0 = 0, $10$1 = 0, __stackBase__ = 0; __stackBase__ = STACKTOP; STACKTOP = STACKTOP + 16 | 0; $rem = __stackBase__ | 0; $1$0 = $a$1 >> 31 | (($a$1 | 0) < 0 ? -1 : 0) << 1; $1$1 = (($a$1 | 0) < 0 ? -1 : 0) >> 31 | (($a$1 | 0) < 0 ? -1 : 0) << 1; $2$0 = $b$1 >> 31 | (($b$1 | 0) < 0 ? -1 : 0) << 1; $2$1 = (($b$1 | 0) < 0 ? -1 : 0) >> 31 | (($b$1 | 0) < 0 ? -1 : 0) << 1; $4$0 = _i64Subtract($1$0 ^ $a$0 | 0, $1$1 ^ $a$1 | 0, $1$0 | 0, $1$1 | 0) | 0; $4$1 = {{{ makeGetTempRet0() }}}; $6$0 = _i64Subtract($2$0 ^ $b$0 | 0, $2$1 ^ $b$1 | 0, $2$0 | 0, $2$1 | 0) | 0; ___udivmoddi4($4$0, $4$1, $6$0, {{{ makeGetTempRet0() }}}, $rem) | 0; $10$0 = _i64Subtract(HEAP32[$rem >> 2] ^ $1$0 | 0, HEAP32[$rem + 4 >> 2] ^ $1$1 | 0, $1$0 | 0, $1$1 | 0) | 0; $10$1 = {{{ makeGetTempRet0() }}}; STACKTOP = __stackBase__; return ({{{ makeSetTempRet0('$10$1') }}}, $10$0) | 0; }, __muldi3__sig: 'iiiii', __muldi3__asm: true, __muldi3__deps: ['__muldsi3', 'Math_imul'], __muldi3: function($a$0, $a$1, $b$0, $b$1) { $a$0 = $a$0 | 0; $a$1 = $a$1 | 0; $b$0 = $b$0 | 0; $b$1 = $b$1 | 0; var $x_sroa_0_0_extract_trunc = 0, $y_sroa_0_0_extract_trunc = 0, $1$0 = 0, $1$1 = 0, $2 = 0; $x_sroa_0_0_extract_trunc = $a$0; $y_sroa_0_0_extract_trunc = $b$0; $1$0 = ___muldsi3($x_sroa_0_0_extract_trunc, $y_sroa_0_0_extract_trunc) | 0; $1$1 = {{{ makeGetTempRet0() }}}; $2 = Math_imul($a$1, $y_sroa_0_0_extract_trunc) | 0; return ({{{ makeSetTempRet0('((Math_imul($b$1, $x_sroa_0_0_extract_trunc) | 0) + $2 | 0) + $1$1 | $1$1 & 0') }}}, 0 | $1$0 & -1) | 0; }, __udivdi3__sig: 'iiiii', __udivdi3__asm: true, __udivdi3__deps: ['__udivmoddi4'], __udivdi3: function($a$0, $a$1, $b$0, $b$1) { $a$0 = $a$0 | 0; $a$1 = $a$1 | 0; $b$0 = $b$0 | 0; $b$1 = $b$1 | 0; var $1$0 = 0; $1$0 = ___udivmoddi4($a$0, $a$1, $b$0, $b$1, 0) | 0; return $1$0 | 0; }, __uremdi3__sig: 'iiiii', __uremdi3__asm: true, __uremdi3__deps: ['__udivmoddi4'], __uremdi3: function($a$0, $a$1, $b$0, $b$1) { $a$0 = $a$0 | 0; $a$1 = $a$1 | 0; $b$0 = $b$0 | 0; $b$1 = $b$1 | 0; var $rem = 0, __stackBase__ = 0; __stackBase__ = STACKTOP; STACKTOP = STACKTOP + 16 | 0; $rem = __stackBase__ | 0; ___udivmoddi4($a$0, $a$1, $b$0, $b$1, $rem) | 0; STACKTOP = __stackBase__; return ({{{ makeSetTempRet0('HEAP32[$rem + 4 >> 2] | 0') }}}, HEAP32[$rem >> 2] | 0) | 0; }, __udivmoddi4__sig: 'iiiiii', __udivmoddi4__asm: true, __udivmoddi4__deps: ['i64Add', 'i64Subtract', 'llvm_cttz_i32', 'Math_clz32'], __udivmoddi4: function($a$0, $a$1, $b$0, $b$1, $rem) { $a$0 = $a$0 | 0; $a$1 = $a$1 | 0; $b$0 = $b$0 | 0; $b$1 = $b$1 | 0; $rem = $rem | 0; var $n_sroa_0_0_extract_trunc = 0, $n_sroa_1_4_extract_shift$0 = 0, $n_sroa_1_4_extract_trunc = 0, $d_sroa_0_0_extract_trunc = 0, $d_sroa_1_4_extract_shift$0 = 0, $d_sroa_1_4_extract_trunc = 0, $4 = 0, $17 = 0, $37 = 0, $49 = 0, $51 = 0, $57 = 0, $58 = 0, $66 = 0, $78 = 0, $86 = 0, $88 = 0, $89 = 0, $91 = 0, $92 = 0, $95 = 0, $105 = 0, $117 = 0, $119 = 0, $125 = 0, $126 = 0, $130 = 0, $q_sroa_1_1_ph = 0, $q_sroa_0_1_ph = 0, $r_sroa_1_1_ph = 0, $r_sroa_0_1_ph = 0, $sr_1_ph = 0, $d_sroa_0_0_insert_insert99$0 = 0, $d_sroa_0_0_insert_insert99$1 = 0, $137$0 = 0, $137$1 = 0, $carry_0203 = 0, $sr_1202 = 0, $r_sroa_0_1201 = 0, $r_sroa_1_1200 = 0, $q_sroa_0_1199 = 0, $q_sroa_1_1198 = 0, $147 = 0, $149 = 0, $r_sroa_0_0_insert_insert42$0 = 0, $r_sroa_0_0_insert_insert42$1 = 0, $150$1 = 0, $151$0 = 0, $152 = 0, $154$0 = 0, $r_sroa_0_0_extract_trunc = 0, $r_sroa_1_4_extract_trunc = 0, $155 = 0, $carry_0_lcssa$0 = 0, $carry_0_lcssa$1 = 0, $r_sroa_0_1_lcssa = 0, $r_sroa_1_1_lcssa = 0, $q_sroa_0_1_lcssa = 0, $q_sroa_1_1_lcssa = 0, $q_sroa_0_0_insert_ext75$0 = 0, $q_sroa_0_0_insert_ext75$1 = 0, $q_sroa_0_0_insert_insert77$1 = 0, $_0$0 = 0, $_0$1 = 0; $n_sroa_0_0_extract_trunc = $a$0; $n_sroa_1_4_extract_shift$0 = $a$1; $n_sroa_1_4_extract_trunc = $n_sroa_1_4_extract_shift$0; $d_sroa_0_0_extract_trunc = $b$0; $d_sroa_1_4_extract_shift$0 = $b$1; $d_sroa_1_4_extract_trunc = $d_sroa_1_4_extract_shift$0; if (($n_sroa_1_4_extract_trunc | 0) == 0) { $4 = ($rem | 0) != 0; if (($d_sroa_1_4_extract_trunc | 0) == 0) { if ($4) { HEAP32[$rem >> 2] = ($n_sroa_0_0_extract_trunc >>> 0) % ($d_sroa_0_0_extract_trunc >>> 0); HEAP32[$rem + 4 >> 2] = 0; } $_0$1 = 0; $_0$0 = ($n_sroa_0_0_extract_trunc >>> 0) / ($d_sroa_0_0_extract_trunc >>> 0) >>> 0; return ({{{ makeSetTempRet0('$_0$1') }}}, $_0$0) | 0; } else { if (!$4) { $_0$1 = 0; $_0$0 = 0; return ({{{ makeSetTempRet0('$_0$1') }}}, $_0$0) | 0; } HEAP32[$rem >> 2] = $a$0 & -1; HEAP32[$rem + 4 >> 2] = $a$1 & 0; $_0$1 = 0; $_0$0 = 0; return ({{{ makeSetTempRet0('$_0$1') }}}, $_0$0) | 0; } } $17 = ($d_sroa_1_4_extract_trunc | 0) == 0; do { if (($d_sroa_0_0_extract_trunc | 0) == 0) { if ($17) { if (($rem | 0) != 0) { HEAP32[$rem >> 2] = ($n_sroa_1_4_extract_trunc >>> 0) % ($d_sroa_0_0_extract_trunc >>> 0); HEAP32[$rem + 4 >> 2] = 0; } $_0$1 = 0; $_0$0 = ($n_sroa_1_4_extract_trunc >>> 0) / ($d_sroa_0_0_extract_trunc >>> 0) >>> 0; return ({{{ makeSetTempRet0('$_0$1') }}}, $_0$0) | 0; } if (($n_sroa_0_0_extract_trunc | 0) == 0) { if (($rem | 0) != 0) { HEAP32[$rem >> 2] = 0; HEAP32[$rem + 4 >> 2] = ($n_sroa_1_4_extract_trunc >>> 0) % ($d_sroa_1_4_extract_trunc >>> 0); } $_0$1 = 0; $_0$0 = ($n_sroa_1_4_extract_trunc >>> 0) / ($d_sroa_1_4_extract_trunc >>> 0) >>> 0; return ({{{ makeSetTempRet0('$_0$1') }}}, $_0$0) | 0; } $37 = $d_sroa_1_4_extract_trunc - 1 | 0; if (($37 & $d_sroa_1_4_extract_trunc | 0) == 0) { if (($rem | 0) != 0) { HEAP32[$rem >> 2] = 0 | $a$0 & -1; HEAP32[$rem + 4 >> 2] = $37 & $n_sroa_1_4_extract_trunc | $a$1 & 0; } $_0$1 = 0; $_0$0 = $n_sroa_1_4_extract_trunc >>> ((_llvm_cttz_i32($d_sroa_1_4_extract_trunc | 0) | 0) >>> 0); return ({{{ makeSetTempRet0('$_0$1') }}}, $_0$0) | 0; } $49 = Math_clz32($d_sroa_1_4_extract_trunc | 0) | 0; $51 = $49 - (Math_clz32($n_sroa_1_4_extract_trunc | 0) | 0) | 0; if ($51 >>> 0 <= 30) { $57 = $51 + 1 | 0; $58 = 31 - $51 | 0; $sr_1_ph = $57; $r_sroa_0_1_ph = $n_sroa_1_4_extract_trunc << $58 | $n_sroa_0_0_extract_trunc >>> ($57 >>> 0); $r_sroa_1_1_ph = $n_sroa_1_4_extract_trunc >>> ($57 >>> 0); $q_sroa_0_1_ph = 0; $q_sroa_1_1_ph = $n_sroa_0_0_extract_trunc << $58; break; } if (($rem | 0) == 0) { $_0$1 = 0; $_0$0 = 0; return ({{{ makeSetTempRet0('$_0$1') }}}, $_0$0) | 0; } HEAP32[$rem >> 2] = 0 | $a$0 & -1; HEAP32[$rem + 4 >> 2] = $n_sroa_1_4_extract_shift$0 | $a$1 & 0; $_0$1 = 0; $_0$0 = 0; return ({{{ makeSetTempRet0('$_0$1') }}}, $_0$0) | 0; } else { if (!$17) { $117 = Math_clz32($d_sroa_1_4_extract_trunc | 0) | 0; $119 = $117 - (Math_clz32($n_sroa_1_4_extract_trunc | 0) | 0) | 0; if ($119 >>> 0 <= 31) { $125 = $119 + 1 | 0; $126 = 31 - $119 | 0; $130 = $119 - 31 >> 31; $sr_1_ph = $125; $r_sroa_0_1_ph = $n_sroa_0_0_extract_trunc >>> ($125 >>> 0) & $130 | $n_sroa_1_4_extract_trunc << $126; $r_sroa_1_1_ph = $n_sroa_1_4_extract_trunc >>> ($125 >>> 0) & $130; $q_sroa_0_1_ph = 0; $q_sroa_1_1_ph = $n_sroa_0_0_extract_trunc << $126; break; } if (($rem | 0) == 0) { $_0$1 = 0; $_0$0 = 0; return ({{{ makeSetTempRet0('$_0$1') }}}, $_0$0) | 0; } HEAP32[$rem >> 2] = 0 | $a$0 & -1; HEAP32[$rem + 4 >> 2] = $n_sroa_1_4_extract_shift$0 | $a$1 & 0; $_0$1 = 0; $_0$0 = 0; return ({{{ makeSetTempRet0('$_0$1') }}}, $_0$0) | 0; } $66 = $d_sroa_0_0_extract_trunc - 1 | 0; if (($66 & $d_sroa_0_0_extract_trunc | 0) != 0) { $86 = (Math_clz32($d_sroa_0_0_extract_trunc | 0) | 0) + 33 | 0; $88 = $86 - (Math_clz32($n_sroa_1_4_extract_trunc | 0) | 0) | 0; $89 = 64 - $88 | 0; $91 = 32 - $88 | 0; $92 = $91 >> 31; $95 = $88 - 32 | 0; $105 = $95 >> 31; $sr_1_ph = $88; $r_sroa_0_1_ph = $91 - 1 >> 31 & $n_sroa_1_4_extract_trunc >>> ($95 >>> 0) | ($n_sroa_1_4_extract_trunc << $91 | $n_sroa_0_0_extract_trunc >>> ($88 >>> 0)) & $105; $r_sroa_1_1_ph = $105 & $n_sroa_1_4_extract_trunc >>> ($88 >>> 0); $q_sroa_0_1_ph = $n_sroa_0_0_extract_trunc << $89 & $92; $q_sroa_1_1_ph = ($n_sroa_1_4_extract_trunc << $89 | $n_sroa_0_0_extract_trunc >>> ($95 >>> 0)) & $92 | $n_sroa_0_0_extract_trunc << $91 & $88 - 33 >> 31; break; } if (($rem | 0) != 0) { HEAP32[$rem >> 2] = $66 & $n_sroa_0_0_extract_trunc; HEAP32[$rem + 4 >> 2] = 0; } if (($d_sroa_0_0_extract_trunc | 0) == 1) { $_0$1 = $n_sroa_1_4_extract_shift$0 | $a$1 & 0; $_0$0 = 0 | $a$0 & -1; return ({{{ makeSetTempRet0('$_0$1') }}}, $_0$0) | 0; } else { $78 = _llvm_cttz_i32($d_sroa_0_0_extract_trunc | 0) | 0; $_0$1 = 0 | $n_sroa_1_4_extract_trunc >>> ($78 >>> 0); $_0$0 = $n_sroa_1_4_extract_trunc << 32 - $78 | $n_sroa_0_0_extract_trunc >>> ($78 >>> 0) | 0; return ({{{ makeSetTempRet0('$_0$1') }}}, $_0$0) | 0; } } } while (0); if (($sr_1_ph | 0) == 0) { $q_sroa_1_1_lcssa = $q_sroa_1_1_ph; $q_sroa_0_1_lcssa = $q_sroa_0_1_ph; $r_sroa_1_1_lcssa = $r_sroa_1_1_ph; $r_sroa_0_1_lcssa = $r_sroa_0_1_ph; $carry_0_lcssa$1 = 0; $carry_0_lcssa$0 = 0; } else { $d_sroa_0_0_insert_insert99$0 = 0 | $b$0 & -1; $d_sroa_0_0_insert_insert99$1 = $d_sroa_1_4_extract_shift$0 | $b$1 & 0; $137$0 = _i64Add($d_sroa_0_0_insert_insert99$0 | 0, $d_sroa_0_0_insert_insert99$1 | 0, -1, -1) | 0; $137$1 = {{{ makeGetTempRet0() }}}; $q_sroa_1_1198 = $q_sroa_1_1_ph; $q_sroa_0_1199 = $q_sroa_0_1_ph; $r_sroa_1_1200 = $r_sroa_1_1_ph; $r_sroa_0_1201 = $r_sroa_0_1_ph; $sr_1202 = $sr_1_ph; $carry_0203 = 0; while (1) { $147 = $q_sroa_0_1199 >>> 31 | $q_sroa_1_1198 << 1; $149 = $carry_0203 | $q_sroa_0_1199 << 1; $r_sroa_0_0_insert_insert42$0 = 0 | ($r_sroa_0_1201 << 1 | $q_sroa_1_1198 >>> 31); $r_sroa_0_0_insert_insert42$1 = $r_sroa_0_1201 >>> 31 | $r_sroa_1_1200 << 1 | 0; _i64Subtract($137$0 | 0, $137$1 | 0, $r_sroa_0_0_insert_insert42$0 | 0, $r_sroa_0_0_insert_insert42$1 | 0) | 0; $150$1 = {{{ makeGetTempRet0() }}}; $151$0 = $150$1 >> 31 | (($150$1 | 0) < 0 ? -1 : 0) << 1; $152 = $151$0 & 1; $154$0 = _i64Subtract($r_sroa_0_0_insert_insert42$0 | 0, $r_sroa_0_0_insert_insert42$1 | 0, $151$0 & $d_sroa_0_0_insert_insert99$0 | 0, ((($150$1 | 0) < 0 ? -1 : 0) >> 31 | (($150$1 | 0) < 0 ? -1 : 0) << 1) & $d_sroa_0_0_insert_insert99$1 | 0) | 0; $r_sroa_0_0_extract_trunc = $154$0; $r_sroa_1_4_extract_trunc = {{{ makeGetTempRet0() }}}; $155 = $sr_1202 - 1 | 0; if (($155 | 0) == 0) { break; } else { $q_sroa_1_1198 = $147; $q_sroa_0_1199 = $149; $r_sroa_1_1200 = $r_sroa_1_4_extract_trunc; $r_sroa_0_1201 = $r_sroa_0_0_extract_trunc; $sr_1202 = $155; $carry_0203 = $152; } } $q_sroa_1_1_lcssa = $147; $q_sroa_0_1_lcssa = $149; $r_sroa_1_1_lcssa = $r_sroa_1_4_extract_trunc; $r_sroa_0_1_lcssa = $r_sroa_0_0_extract_trunc; $carry_0_lcssa$1 = 0; $carry_0_lcssa$0 = $152; } $q_sroa_0_0_insert_ext75$0 = $q_sroa_0_1_lcssa; $q_sroa_0_0_insert_ext75$1 = 0; $q_sroa_0_0_insert_insert77$1 = $q_sroa_1_1_lcssa | $q_sroa_0_0_insert_ext75$1; if (($rem | 0) != 0) { HEAP32[$rem >> 2] = 0 | $r_sroa_0_1_lcssa; HEAP32[$rem + 4 >> 2] = $r_sroa_1_1_lcssa | 0; } $_0$1 = (0 | $q_sroa_0_0_insert_ext75$0) >>> 31 | $q_sroa_0_0_insert_insert77$1 << 1 | ($q_sroa_0_0_insert_ext75$1 << 1 | $q_sroa_0_0_insert_ext75$0 >>> 31) & 0 | $carry_0_lcssa$1; $_0$0 = ($q_sroa_0_0_insert_ext75$0 << 1 | 0 >>> 31) & -2 | $carry_0_lcssa$0; return ({{{ makeSetTempRet0('$_0$1') }}}, $_0$0) | 0; }, // ======================================================================= __handle_stack_overflow: function() { abort('stack overflow') }, }; function autoAddDeps(object, name) { for (var item in object) { if (item.substr(-6) != '__deps') { if (!object[item + '__deps']) { object[item + '__deps'] = [name]; } else { object[item + '__deps'].push(name); // add to existing list } } } }
/*! For license information please see 014d626450f83784e9083200e171de600c3fc5a1-7ace7e7deb1e0e430a4d.js.LICENSE.txt */ (window.webpackJsonp=window.webpackJsonp||[]).push([[5],{"/kpp":function(t,e,o){"use strict";var n=o("YEIV"),r=o.n(n),i=o("QbLZ"),s=o.n(i),f=o("EJiy"),l=o.n(f),c=o("iCc5"),u=o.n(c),a=o("V7oC"),p=o.n(a),d=o("FYw3"),h=o.n(d),y=o("mRg0"),m=o.n(y),v=o("q1tI"),w=o("eHJ2"),b=o.n(w),g=function(t,e){var o={};for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&e.indexOf(n)<0&&(o[n]=t[n]);if(null!=t&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(n=Object.getOwnPropertySymbols(t);r<n.length;r++)e.indexOf(n[r])<0&&(o[n[r]]=t[n[r]])}return o},S=function(t){function e(){return u()(this,e),h()(this,(e.__proto__||Object.getPrototypeOf(e)).apply(this,arguments))}return m()(e,t),p()(e,[{key:"render",value:function(){var t,e=this.props,o=e.span,n=e.order,i=e.offset,f=e.push,c=e.pull,u=e.className,a=e.children,p=e.prefixCls,d=void 0===p?"ant-col":p,h=g(e,["span","order","offset","push","pull","className","children","prefixCls"]),y={};["xs","sm","md","lg","xl","xxl"].forEach((function(t){var o,n={};"number"==typeof e[t]?n.span=e[t]:"object"===l()(e[t])&&(n=e[t]||{}),delete h[t],y=s()({},y,(o={},r()(o,d+"-"+t+"-"+n.span,void 0!==n.span),r()(o,d+"-"+t+"-order-"+n.order,n.order||0===n.order),r()(o,d+"-"+t+"-offset-"+n.offset,n.offset||0===n.offset),r()(o,d+"-"+t+"-push-"+n.push,n.push||0===n.push),r()(o,d+"-"+t+"-pull-"+n.pull,n.pull||0===n.pull),o))}));var m=b()((t={},r()(t,d+"-"+o,void 0!==o),r()(t,d+"-order-"+n,n),r()(t,d+"-offset-"+i,i),r()(t,d+"-push-"+f,f),r()(t,d+"-pull-"+c,c),t),u,y);return v.createElement("div",s()({},h,{className:m}),a)}}]),e}(v.Component);e.a=S},"9Do8":function(t,e,o){"use strict";t.exports=o("zt9T")},"BGR+":function(t,e,o){"use strict";var n=o("QbLZ"),r=o.n(n);e.a=function(t,e){for(var o=r()({},t),n=0;n<e.length;n++){delete o[e[n]]}return o}},IX3V:function(t,e){t.exports={isFunction:function(t){return"function"==typeof t},isArray:function(t){return"[object Array]"===Object.prototype.toString.apply(t)},each:function(t,e){for(var o=0,n=t.length;o<n&&!1!==e(t[o],o);o++);}}},TOwV:function(t,e,o){"use strict";t.exports=o("qT12")},jB5C:function(t,e,o){"use strict";var n=Object.assign||function(t){for(var e=1;e<arguments.length;e++){var o=arguments[e];for(var n in o)Object.prototype.hasOwnProperty.call(o,n)&&(t[n]=o[n])}return t},r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol?"symbol":typeof t};function i(t,e){var o=t["page"+(e?"Y":"X")+"Offset"],n="scroll"+(e?"Top":"Left");if("number"!=typeof o){var r=t.document;"number"!=typeof(o=r.documentElement[n])&&(o=r.body[n])}return o}function s(t){return i(t)}function f(t){return i(t,!0)}function l(t){var e=function(t){var e,o=void 0,n=void 0,r=t.ownerDocument,i=r.body,s=r&&r.documentElement;return o=(e=t.getBoundingClientRect()).left,n=e.top,{left:o-=s.clientLeft||i.clientLeft||0,top:n-=s.clientTop||i.clientTop||0}}(t),o=t.ownerDocument,n=o.defaultView||o.parentWindow;return e.left+=s(n),e.top+=f(n),e}var c=new RegExp("^("+/[\-+]?(?:\d*\.|)\d+(?:[eE][\-+]?\d+|)/.source+")(?!px)[a-z%]+$","i"),u=/^(top|right|bottom|left)$/,a="left";var p=void 0;function d(t,e){for(var o=0;o<t.length;o++)e(t[o])}function h(t){return"border-box"===p(t,"boxSizing")}"undefined"!=typeof window&&(p=window.getComputedStyle?function(t,e,o){var n="",r=t.ownerDocument,i=o||r.defaultView.getComputedStyle(t,null);return i&&(n=i.getPropertyValue(e)||i[e]),n}:function(t,e){var o=t.currentStyle&&t.currentStyle[e];if(c.test(o)&&!u.test(e)){var n=t.style,r=n[a],i=t.runtimeStyle[a];t.runtimeStyle[a]=t.currentStyle[a],n[a]="fontSize"===e?"1em":o||0,o=n.pixelLeft+"px",n[a]=r,t.runtimeStyle[a]=i}return""===o?"auto":o});var y=["margin","border","padding"];function m(t,e,o){var n={},r=t.style,i=void 0;for(i in e)e.hasOwnProperty(i)&&(n[i]=r[i],r[i]=e[i]);for(i in o.call(t),e)e.hasOwnProperty(i)&&(r[i]=n[i])}function v(t,e,o){var n=0,r=void 0,i=void 0,s=void 0;for(i=0;i<e.length;i++)if(r=e[i])for(s=0;s<o.length;s++){var f=void 0;f="border"===r?r+o[s]+"Width":r+o[s],n+=parseFloat(p(t,f))||0}return n}function w(t){return null!=t&&t==t.window}var b={};function g(t,e,o){if(w(t))return"width"===e?b.viewportWidth(t):b.viewportHeight(t);if(9===t.nodeType)return"width"===e?b.docWidth(t):b.docHeight(t);var n="width"===e?["Left","Right"]:["Top","Bottom"],r="width"===e?t.offsetWidth:t.offsetHeight,i=(p(t),h(t)),s=0;(null==r||r<=0)&&(r=void 0,(null==(s=p(t,e))||Number(s)<0)&&(s=t.style[e]||0),s=parseFloat(s)||0),void 0===o&&(o=i?1:-1);var f=void 0!==r||i,l=r||s;if(-1===o)return f?l-v(t,["border","padding"],n):s;if(f){var c=2===o?-v(t,["border"],n):v(t,["margin"],n);return l+(1===o?0:c)}return s+v(t,y.slice(o),n)}d(["Width","Height"],(function(t){b["doc"+t]=function(e){var o=e.document;return Math.max(o.documentElement["scroll"+t],o.body["scroll"+t],b["viewport"+t](o))},b["viewport"+t]=function(e){var o="client"+t,n=e.document,r=n.body,i=n.documentElement[o];return"CSS1Compat"===n.compatMode&&i||r&&r[o]||i}}));var S={position:"absolute",visibility:"hidden",display:"block"};function x(t){var e=void 0,o=arguments;return 0!==t.offsetWidth?e=g.apply(void 0,o):m(t,S,(function(){e=g.apply(void 0,o)})),e}function O(t,e,o){var n=o;if("object"!==(void 0===e?"undefined":r(e)))return void 0!==n?("number"==typeof n&&(n+="px"),void(t.style[e]=n)):p(t,e);for(var i in e)e.hasOwnProperty(i)&&O(t,i,e[i])}d(["width","height"],(function(t){var e=t.charAt(0).toUpperCase()+t.slice(1);b["outer"+e]=function(e,o){return e&&x(e,t,o?0:1)};var o="width"===t?["Left","Right"]:["Top","Bottom"];b[t]=function(e,n){if(void 0===n)return e&&x(e,t,-1);if(e){p(e);return h(e)&&(n+=v(e,["padding","border"],o)),O(e,t,n)}}})),t.exports=n({getWindow:function(t){var e=t.ownerDocument||t;return e.defaultView||e.parentWindow},offset:function(t,e){if(void 0===e)return l(t);!function(t,e){"static"===O(t,"position")&&(t.style.position="relative");var o=l(t),n={},r=void 0,i=void 0;for(i in e)e.hasOwnProperty(i)&&(r=parseFloat(O(t,i))||0,n[i]=r+e[i]-o[i]);O(t,n)}(t,e)},isWindow:w,each:d,css:O,clone:function(t){var e={};for(var o in t)t.hasOwnProperty(o)&&(e[o]=t[o]);if(t.overflow)for(var o in t)t.hasOwnProperty(o)&&(e.overflow[o]=t.overflow[o]);return e},scrollLeft:function(t,e){if(w(t)){if(void 0===e)return s(t);window.scrollTo(e,f(t))}else{if(void 0===e)return t.scrollLeft;t.scrollLeft=e}},scrollTop:function(t,e){if(w(t)){if(void 0===e)return f(t);window.scrollTo(s(t),e)}else{if(void 0===e)return t.scrollTop;t.scrollTop=e}},viewportWidth:0,viewportHeight:0},b)},jpXb:function(t,e,o){var n=o("wZXL");t.exports=new n},kCCV:function(t,e){function o(t){this.options=t,!t.deferSetup&&this.setup()}o.prototype={constructor:o,setup:function(){this.options.setup&&this.options.setup(),this.initialised=!0},on:function(){!this.initialised&&this.setup(),this.options.match&&this.options.match()},off:function(){this.options.unmatch&&this.options.unmatch()},destroy:function(){this.options.destroy?this.options.destroy():this.off()},equals:function(t){return this.options===t||this.options.match===t}},t.exports=o},qT12:function(t,e,o){"use strict";var n="function"==typeof Symbol&&Symbol.for,r=n?Symbol.for("react.element"):60103,i=n?Symbol.for("react.portal"):60106,s=n?Symbol.for("react.fragment"):60107,f=n?Symbol.for("react.strict_mode"):60108,l=n?Symbol.for("react.profiler"):60114,c=n?Symbol.for("react.provider"):60109,u=n?Symbol.for("react.context"):60110,a=n?Symbol.for("react.async_mode"):60111,p=n?Symbol.for("react.concurrent_mode"):60111,d=n?Symbol.for("react.forward_ref"):60112,h=n?Symbol.for("react.suspense"):60113,y=n?Symbol.for("react.suspense_list"):60120,m=n?Symbol.for("react.memo"):60115,v=n?Symbol.for("react.lazy"):60116,w=n?Symbol.for("react.block"):60121,b=n?Symbol.for("react.fundamental"):60117,g=n?Symbol.for("react.responder"):60118,S=n?Symbol.for("react.scope"):60119;function x(t){if("object"==typeof t&&null!==t){var e=t.$$typeof;switch(e){case r:switch(t=t.type){case a:case p:case s:case l:case f:case h:return t;default:switch(t=t&&t.$$typeof){case u:case d:case v:case m:case c:return t;default:return e}}case i:return e}}}function O(t){return x(t)===p}e.AsyncMode=a,e.ConcurrentMode=p,e.ContextConsumer=u,e.ContextProvider=c,e.Element=r,e.ForwardRef=d,e.Fragment=s,e.Lazy=v,e.Memo=m,e.Portal=i,e.Profiler=l,e.StrictMode=f,e.Suspense=h,e.isAsyncMode=function(t){return O(t)||x(t)===a},e.isConcurrentMode=O,e.isContextConsumer=function(t){return x(t)===u},e.isContextProvider=function(t){return x(t)===c},e.isElement=function(t){return"object"==typeof t&&null!==t&&t.$$typeof===r},e.isForwardRef=function(t){return x(t)===d},e.isFragment=function(t){return x(t)===s},e.isLazy=function(t){return x(t)===v},e.isMemo=function(t){return x(t)===m},e.isPortal=function(t){return x(t)===i},e.isProfiler=function(t){return x(t)===l},e.isStrictMode=function(t){return x(t)===f},e.isSuspense=function(t){return x(t)===h},e.isValidElementType=function(t){return"string"==typeof t||"function"==typeof t||t===s||t===p||t===l||t===f||t===h||t===y||"object"==typeof t&&null!==t&&(t.$$typeof===v||t.$$typeof===m||t.$$typeof===c||t.$$typeof===u||t.$$typeof===d||t.$$typeof===b||t.$$typeof===g||t.$$typeof===S||t.$$typeof===w)},e.typeOf=x},qrJ5:function(t,e,o){"use strict";var n=o("YEIV"),r=o.n(n),i=o("QbLZ"),s=o.n(i),f=o("EJiy"),l=o.n(f),c=o("iCc5"),u=o.n(c),a=o("V7oC"),p=o.n(a),d=o("FYw3"),h=o.n(d),y=o("mRg0"),m=o.n(y),v=o("q1tI"),w=o("eHJ2"),b=o.n(w),g=function(t,e){var o={};for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&e.indexOf(n)<0&&(o[n]=t[n]);if(null!=t&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(n=Object.getOwnPropertySymbols(t);r<n.length;r++)e.indexOf(n[r])<0&&(o[n[r]]=t[n[r]])}return o},S=void 0;if("undefined"!=typeof window){window.matchMedia=window.matchMedia||function(t){return{media:t,matches:!1,addListener:function(){},removeListener:function(){}}},S=o("jpXb")}var x=["xxl","xl","lg","md","sm","xs"],O={xs:"(max-width: 575px)",sm:"(min-width: 576px)",md:"(min-width: 768px)",lg:"(min-width: 992px)",xl:"(min-width: 1200px)",xxl:"(min-width: 1600px)"},L=function(t){function e(){u()(this,e);var t=h()(this,(e.__proto__||Object.getPrototypeOf(e)).apply(this,arguments));return t.state={screens:{}},t}return m()(e,t),p()(e,[{key:"componentDidMount",value:function(){var t=this;Object.keys(O).map((function(e){return S.register(O[e],{match:function(){"object"===l()(t.props.gutter)&&t.setState((function(t){return{screens:s()({},t.screens,r()({},e,!0))}}))},unmatch:function(){"object"===l()(t.props.gutter)&&t.setState((function(t){return{screens:s()({},t.screens,r()({},e,!1))}}))},destroy:function(){}})}))}},{key:"componentWillUnmount",value:function(){Object.keys(O).map((function(t){return S.unregister(O[t])}))}},{key:"getGutter",value:function(){var t=this.props.gutter;if("object"===(void 0===t?"undefined":l()(t)))for(var e=0;e<=x.length;e++){var o=x[e];if(this.state.screens[o]&&void 0!==t[o])return t[o]}return t}},{key:"render",value:function(){var t,e=this.props,o=e.type,n=e.justify,i=e.align,f=e.className,l=e.style,c=e.children,u=e.prefixCls,a=void 0===u?"ant-row":u,p=g(e,["type","justify","align","className","style","children","prefixCls"]),d=this.getGutter(),h=b()((t={},r()(t,a,!o),r()(t,a+"-"+o,o),r()(t,a+"-"+o+"-"+n,o&&n),r()(t,a+"-"+o+"-"+i,o&&i),t),f),y=d>0?s()({marginLeft:d/-2,marginRight:d/-2},l):l,m=v.Children.map(c,(function(t){return t?t.props&&d>0?Object(v.cloneElement)(t,{style:s()({paddingLeft:d/2,paddingRight:d/2},t.props.style)}):t:null})),w=s()({},p);return delete w.gutter,v.createElement("div",s()({},w,{className:h,style:y}),m)}}]),e}(v.Component);e.a=L,L.defaultProps={gutter:0}},"vPd/":function(t,e,o){var n=o("kCCV"),r=o("IX3V").each;function i(t,e){this.query=t,this.isUnconditional=e,this.handlers=[],this.mql=window.matchMedia(t);var o=this;this.listener=function(t){o.mql=t.currentTarget||t,o.assess()},this.mql.addListener(this.listener)}i.prototype={constuctor:i,addHandler:function(t){var e=new n(t);this.handlers.push(e),this.matches()&&e.on()},removeHandler:function(t){var e=this.handlers;r(e,(function(o,n){if(o.equals(t))return o.destroy(),!e.splice(n,1)}))},matches:function(){return this.mql.matches||this.isUnconditional},clear:function(){r(this.handlers,(function(t){t.destroy()})),this.mql.removeListener(this.listener),this.handlers.length=0},assess:function(){var t=this.matches()?"on":"off";r(this.handlers,(function(e){e[t]()}))}},t.exports=i},wZXL:function(t,e,o){var n=o("vPd/"),r=o("IX3V"),i=r.each,s=r.isFunction,f=r.isArray;function l(){if(!window.matchMedia)throw new Error("matchMedia not present, legacy browsers require a polyfill");this.queries={},this.browserIsIncapable=!window.matchMedia("only all").matches}l.prototype={constructor:l,register:function(t,e,o){var r=this.queries,l=o&&this.browserIsIncapable;return r[t]||(r[t]=new n(t,l)),s(e)&&(e={match:e}),f(e)||(e=[e]),i(e,(function(e){s(e)&&(e={match:e}),r[t].addHandler(e)})),this},unregister:function(t,e){var o=this.queries[t];return o&&(e?o.removeHandler(e):(o.clear(),delete this.queries[t])),this}},t.exports=l},zt9T:function(t,e,o){"use strict";var n=o("jB5C");t.exports=function(t,e,o){o=o||{},9===e.nodeType&&(e=n.getWindow(e));var r=o.allowHorizontalScroll,i=o.onlyScrollIfNeeded,s=o.alignWithTop,f=o.alignWithLeft,l=o.offsetTop||0,c=o.offsetLeft||0,u=o.offsetBottom||0,a=o.offsetRight||0;r=void 0===r||r;var p=n.isWindow(e),d=n.offset(t),h=n.outerHeight(t),y=n.outerWidth(t),m=void 0,v=void 0,w=void 0,b=void 0,g=void 0,S=void 0,x=void 0,O=void 0,L=void 0,C=void 0;p?(x=e,C=n.height(x),L=n.width(x),O={left:n.scrollLeft(x),top:n.scrollTop(x)},g={left:d.left-O.left-c,top:d.top-O.top-l},S={left:d.left+y-(O.left+L)+a,top:d.top+h-(O.top+C)+u},b=O):(m=n.offset(e),v=e.clientHeight,w=e.clientWidth,b={left:e.scrollLeft,top:e.scrollTop},g={left:d.left-(m.left+(parseFloat(n.css(e,"borderLeftWidth"))||0))-c,top:d.top-(m.top+(parseFloat(n.css(e,"borderTopWidth"))||0))-l},S={left:d.left+y-(m.left+w+(parseFloat(n.css(e,"borderRightWidth"))||0))+a,top:d.top+h-(m.top+v+(parseFloat(n.css(e,"borderBottomWidth"))||0))+u}),g.top<0||S.top>0?!0===s?n.scrollTop(e,b.top+g.top):!1===s?n.scrollTop(e,b.top+S.top):g.top<0?n.scrollTop(e,b.top+g.top):n.scrollTop(e,b.top+S.top):i||((s=void 0===s||!!s)?n.scrollTop(e,b.top+g.top):n.scrollTop(e,b.top+S.top)),r&&(g.left<0||S.left>0?!0===f?n.scrollLeft(e,b.left+g.left):!1===f?n.scrollLeft(e,b.left+S.left):g.left<0?n.scrollLeft(e,b.left+g.left):n.scrollLeft(e,b.left+S.left):i||((f=void 0===f||!!f)?n.scrollLeft(e,b.left+g.left):n.scrollLeft(e,b.left+S.left)))}}}]); //# sourceMappingURL=014d626450f83784e9083200e171de600c3fc5a1-7ace7e7deb1e0e430a4d.js.map
export default { 'zh': { 'days': ['ๆ—ฅ', 'ไธ€', 'ไบŒ', 'ไธ‰', 'ๅ››', 'ไบ”', 'ๅ…ญ'], 'months': ['1ๆœˆ', '2ๆœˆ', '3ๆœˆ', '4ๆœˆ', '5ๆœˆ', '6ๆœˆ', '7ๆœˆ', '8ๆœˆ', '9ๆœˆ', '10ๆœˆ', '11ๆœˆ', '12ๆœˆ'], 'pickers': ['ๆœชๆฅ7ๅคฉ', 'ๆœชๆฅ30ๅคฉ', 'ๆœ€่ฟ‘7ๅคฉ', 'ๆœ€่ฟ‘30ๅคฉ'], 'placeholder': { 'date': '่ฏท้€‰ๆ‹ฉๆ—ฅๆœŸ', 'dateRange': '่ฏท้€‰ๆ‹ฉๆ—ฅๆœŸ่Œƒๅ›ด' } }, 'en': { 'days': ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'], 'months': ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'], 'pickers': ['next 7 days', 'next 30 days', 'previous 7 days', 'previous 30 days'], 'placeholder': { 'date': 'Select Date', 'dateRange': 'Select Date Range' } }, 'ro': { 'days': ['Lun', 'Mar', 'Mie', 'Joi', 'Vin', 'Sรขm', 'Dum'], 'months': ['Ian', 'Feb', 'Mar', 'Apr', 'Mai', 'Iun', 'Iul', 'Aug', 'Sep', 'Oct', 'Noi', 'Dec'], 'pickers': ['urmatoarele 7 zile', 'urmatoarele 30 zile', 'ultimele 7 zile', 'ultimele 30 zile'], 'placeholder': { 'date': 'Selectaศ›i Data', 'dateRange': 'Selectaศ›i Intervalul De Date' } }, 'fr': { 'days': ['Dim', 'Lun', 'Mar', 'Mer', 'Jeu', 'Ven', 'Sam'], 'months': ['Jan', 'Fev', 'Mar', 'Avr', 'Mai', 'Juin', 'Juil', 'Aout', 'Sep', 'Oct', 'Nov', 'Dec'], 'pickers': ['7 jours suivants', '30 jours suivants', '7 jours prรฉcรฉdents', '30 jours prรฉcรฉdents'], 'placeholder': { 'date': 'Sรฉlectionnez une date', 'dateRange': 'Sรฉlectionnez une pรฉriode' } }, 'es': { 'days': ['Dom', 'Lun', 'mar', 'Mie', 'Jue', 'Vie', 'Sab'], 'months': ['Ene', 'Feb', 'Mar', 'Abr', 'May', 'Jun', 'Jul', 'Ago', 'Sep', 'Oct', 'Nov', 'Dic'], 'pickers': ['prรณximos 7 dรญas', 'prรณximos 30 dรญas', '7 dรญas anteriores', '30 dรญas anteriores'], 'placeholder': { 'date': 'Seleccionar fecha', 'dateRange': 'Seleccionar un rango de fechas' } }, 'pt-br': { 'days': ['Dom', 'Seg', 'Ter', 'Qua', 'Quin', 'Sex', 'Sรกb'], 'months': ['Jan', 'Fev', 'Mar', 'Abr', 'Maio', 'Jun', 'Jul', 'Ago', 'Set', 'Out', 'Nov', 'Dez'], 'pickers': ['prรณximos 7 dias', 'prรณximos 30 dias', '7 dias anteriores', ' 30 dias anteriores'], 'placeholder': { 'date': 'Selecione uma data', 'dateRange': 'Selecione um perรญodo' } }, 'ru': { 'days': ['ะ’ั', 'ะŸะฝ', 'ะ’ั‚', 'ะกั€', 'ะงั‚', 'ะŸั‚', 'ะกะฑ'], 'months': ['ะฏะฝะฒ', 'ะคะตะฒ', 'ะœะฐั€', 'ะะฟั€', 'ะœะฐะน', 'ะ˜ัŽะฝ', 'ะ˜ัŽะป', 'ะะฒะณ', 'ะกะตะฝ', 'ะžะบั‚', 'ะะพั', 'ะ”ะตะบ'], 'pickers': ['ัะปะตะด. 7 ะดะฝะตะน', 'ัะปะตะด. 30 ะดะฝะตะน', 'ะฟั€ะพัˆ. 7 ะดะฝะตะน', 'ะฟั€ะพัˆ. 30 ะดะฝะตะน'], 'placeholder': { 'date': 'ะ’ั‹ะฑะตั€ะธั‚ะต ะดะฐั‚ัƒ', 'dateRange': 'ะ’ั‹ะฑะตั€ะธั‚ะต ะฟะตั€ะธะพะด' } }, 'de': { 'days': ['So', 'Mo', 'Di', 'Mi', 'Do', 'Fr', 'Sa'], 'months': ['Januar', 'Februar', 'Mรคrz', 'April', 'Mai', 'Juni', 'Juli', 'August', 'September', 'Oktober', 'November', 'Dezember'], 'pickers': ['nรคchsten 7 Tage', 'nรคchsten 30 Tage', 'vorigen 7 Tage', 'vorigen 30 Tage'], 'placeholder': { 'date': 'Datum auswรคhlen', 'dateRange': 'Zeitraum auswรคhlen' } }, 'it': { 'days': ['Dom', 'Lun', 'Mar', 'Mer', 'Gio', 'Ven', 'Sab'], 'months': ['Gen', 'Feb', 'Mar', 'Apr', 'Mag', 'Giu', 'Lug', 'Ago', 'Set', 'Ott', 'Nov', 'Dic'], 'pickers': ['successivi 7 giorni', 'successivi 30 giorni', 'precedenti 7 giorni', 'precedenti 30 giorni'], 'placeholder': { 'date': 'Seleziona una data', 'dateRange': 'Seleziona un intervallo date' } }, 'cs': { 'days': ['Ned', 'Pon', 'รšte', 'Stล™', 'ฤŒtv', 'Pรกt', 'Sob'], 'months': ['Led', 'รšno', 'Bล™e', 'Dub', 'Kvฤ›', 'ฤŒer', 'ฤŒerc', 'Srp', 'Zรกล™', 'ล˜รญj', 'Lis', 'Pro'], 'pickers': ['pล™รญลกtรญch 7 dnรญ', 'pล™รญลกtรญch 30 dnรญ', 'pล™edchozรญch 7 dnรญ', 'pล™edchozรญch 30 dnรญ'], 'placeholder': { 'date': 'Vyberte datum', 'dateRange': 'Vyberte ฤasovรฉ rozmezรญ' } }, 'sl': { 'days': ['Ned', 'Pon', 'Tor', 'Sre', 'ฤŒet', 'Pet', 'Sob'], 'months': ['Jan', 'Feb', 'Mar', 'Apr', 'Maj', 'Jun', 'Jul', 'Avg', 'Sep', 'Okt', 'Nov', 'Dec'], 'pickers': ['naslednjih 7 dni', 'naslednjih 30 dni', 'prejลกnjih 7 dni', 'prejลกnjih 30 dni'], 'placeholder': { 'date': 'Izberite datum', 'dateRange': 'Izberite razpon med 2 datumoma' } } }
module.exports = function(dir) { const path = require("path"); return path.basename(path.resolve(dir)); };
# 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. from aliyunsdkcore.request import RpcRequest from aliyunsdkoutboundbot.endpoint import endpoint_data class DeleteScriptRequest(RpcRequest): def __init__(self): RpcRequest.__init__(self, 'OutboundBot', '2019-12-26', 'DeleteScript','outboundbot') self.set_method('POST') if hasattr(self, "endpoint_map"): setattr(self, "endpoint_map", endpoint_data.getEndpointMap()) if hasattr(self, "endpoint_regional"): setattr(self, "endpoint_regional", endpoint_data.getEndpointRegional()) def get_ScriptId(self): return self.get_query_params().get('ScriptId') def set_ScriptId(self,ScriptId): self.add_query_param('ScriptId',ScriptId) def get_InstanceId(self): return self.get_query_params().get('InstanceId') def set_InstanceId(self,InstanceId): self.add_query_param('InstanceId',InstanceId)
module.exports = { zh: { TY_Basic: '้€š็”จไธšๅŠก็ป„ไปถ(Basic)', TY_Lamp: '็ฏ(Lamp)', TY_Standard: 'ๅ…ฌ็‰ˆ(Standard)', TY_SweepRobot: 'ๆ‰ซๅœฐๆœบ(SweepRobot)', TY_Sensor: 'ไผ ๆ„Ÿๅ™จ(Sensor)', TY_Szos: 'ๆทฑๅœณOS(Szos)', TY_dp_switch_1: 'ๅผ€ๅ…ณ1', TY_dp_switch_1_on: 'ๅผ€', TY_dp_switch_1_off: 'ๅ…ณ', TYLamp_am: 'ไธŠๅˆ', TYLamp_pm: 'ไธ‹ๅˆ', TYLamp_mode: 'ๆจกๅผ', TYLamp_unSelected: 'ๆœช้€‰ไธญ็Šถๆ€', TYLamp_selected: '้€‰ไธญ็Šถๆ€', TYLamp_customizeStyle: '่‡ชๅฎšไน‰ๆ ทๅผ', TYLamp_customizeContent: '่‡ชๅฎšไน‰ๅ†…ๅฎน', TYLamp_drawerContent: 'ไธ‹ๆ‹‰ๅ†…ๅฎน', TYLamp_subTitle: 'ๅญๆ ‡้ข˜', TYLamp_customizeDescription: 'ๆฒกๆœ‰ๅทฆ่พนๆŒ‰้’ฎ๏ผŒๆœ‰ๅญๆ ‡้ข˜๏ผŒๆŒ‰้’ฎๅ›บๅฎš', TYLamp_average: 'ๅนณๅ‡ๅˆ†้…', TYLamp_percent: 'ๆŒ‰็™พๅˆ†ๆฏ”ๅˆ†้…', TYLamp_hour: 'ๆ—ถ', TYLamp_minute: 'ๅˆ†', TYLamp_second: '็ง’', TYLamp_confirm: '็กฎ่ฎค', TYLamp_cancel: 'ๅ–ๆถˆ', TYLamp_resetCountdown: '้‡็ฝฎๅฎšๆ—ถ', TYLamp_onCountdown: 'ๅ€’่ฎกๆ—ถ็ป“ๆŸๅŽ็ฏๅธฆๅฐ†่‡ชๅŠจๆ‰“ๅผ€', TYLamp_offCountdown: 'ๅ€’่ฎกๆ—ถ็ป“ๆŸๅŽ็ฏๅธฆๅฐ†่‡ชๅŠจๅ…ณ้—ญ', TYLamp_loop: 'ๅพช็Žฏ', TYLamp_vertical: '็ซ–็›ด', TYLamp_horizontal: 'ๆฐดๅนณ', TYLamp_animatedModal_customRender: '่‡ชๅฎšไน‰ๆธฒๆŸ“ๅŠจ็”ปๅŒบๅŸŸๅ†…ๅฎน', TYLamp_animatedModal_customRenderForControl: '่‡ชๅฎšไน‰ๆธฒๆŸ“ๅ†…ๅฎน็”จไบŽๅ†…้ƒจๆŽงๅˆถๅŠจ็”ป', TYLamp_animatedModal_light: 'ๆต…่‰ฒๆจกๅผๆ•ˆๆžœ', TYLamp_animatedModal_dark: 'ๆทฑ่‰ฒๆจกๅผๆ•ˆๆžœ', TYLamp_animatedModal_lightHeaderTitle: 'ๆต…่‰ฒๆจกๅผไธ‹ๅคด้ƒจๆ ', TYLamp_animatedModal_darkHeaderTitle: 'ๆทฑ่‰ฒๆจกๅผไธ‹ๅคด้ƒจๆ ', TYLamp_animatedModal_cancelText: 'ๅ–ๆถˆ', TYLamp_animatedModal_confirmText: '็กฎ่ฎค', TYLamp_rhythms_tip: '่Š‚็‚นไธ่ƒฝ่ถ…่ฟ‡', TYLamp_rhythms_tip1: '่Š‚็‚นๅฏไปฅ่ถ…่ฟ‡', }, en: { TY_Basic: '้€š็”จไธšๅŠก็ป„ไปถ(Basic)', TY_Lamp: '็ฏ(Lamp)', TY_Standard: 'ๅ…ฌ็‰ˆ(Standard)', TY_SweepRobot: 'ๆ‰ซๅœฐๆœบ(SweepRobot)', TY_Sensor: 'ไผ ๆ„Ÿๅ™จ(Sensor)', TY_Szos: 'ๆทฑๅœณOS(Szos)', TYLamp_am: 'AM', TYLamp_pm: 'PM', TYLamp_mode: 'mode', TYLamp_unSelected: 'Unselected State', TYLamp_selected: 'Selected State', TYLamp_customizeStyle: 'Customize', TYLamp_customizeContent: 'Customize Content', TYLamp_drawerContent: 'Drawer Content', TYLamp_subTitle: 'Subtitle', TYLamp_customizeDescription: 'Has no left icon,but has subtitle,only one button image', TYLamp_average: 'Equally Calculate', TYLamp_percent: 'Calculate by percentage', TYLamp_hour: 'H', TYLamp_minute: 'Min', TYLamp_second: 'Sec', TYLamp_confirm: 'confirm', TYLamp_cancel: 'cancel', TYLamp_resetCountdown: 'reset', TYLamp_onCountdown: 'The light will turn on automatically after the countdown', TYLamp_offCountdown: 'The light will turn off automatically after the countdown', TYLamp_loop: 'loop', TYLamp_vertical: 'Vertical', TYLamp_horizontal: 'Horizontal', TYLamp_animatedModal_customRender: 'Custom rendering animation', TYLamp_animatedModal_customRenderForControl: 'Custom rendering content for control', TYLamp_animatedModal_light: 'Light mode effect', TYLamp_animatedModal_dark: 'Dark mode effect', TYLamp_animatedModal_lightHeaderTitle: 'light header', TYLamp_animatedModal_darkHeaderTitle: 'dark header', TYLamp_animatedModal_cancelText: 'cancel', TYLamp_animatedModal_confirmText: 'confirm', TYLamp_rhythms_tip: 'Node no more than', TYLamp_rhythms_tip1: 'Node can more than', }, };
#pylint: disable=too-many-lines from logging.config import dictConfig from functools import wraps from subprocess import call import datetime import base64 import datetime import glob import io import json import os import re import shutil import tempfile import subprocess import zipfile import waitress from werkzeug.utils import secure_filename from flask import ( Flask, jsonify, render_template, redirect, request, send_file, send_from_directory, make_response, url_for ) from flask.logging import create_logger from flask_swagger_ui import get_swaggerui_blueprint from flask_jwt_extended import ( JWTManager, jwt_required, create_access_token, create_refresh_token, current_user, get_jwt_identity, verify_jwt_in_request, jwt_refresh_token_required, get_raw_jwt, set_access_cookies, set_refresh_cookies, unset_jwt_cookies, verify_jwt_refresh_token_in_request ) dictConfig({ 'version': 1, 'formatters': {'default': { 'format': '[%(levelname)s] %(pathname)s:%(lineno)d %(message)s', }}, 'handlers': {'wsgi': { 'class': 'logging.StreamHandler', 'stream': 'ext://flask.logging.wsgi_errors_stream', 'formatter': 'default' }}, 'root': { 'level': 'INFO', 'handlers': ['wsgi'] } }) class UserAccess: """Object used for determining roles""" def __init__(self, username, roles): """ :param username: username :param roles: roles """ self.username = username self.roles = roles def get_username(self): return self.username def get_roles(self): return self.roles def __str__(self): return self.__class__.__name__ app = Flask(__name__) #pylint: disable=invalid-name LOGGER = create_logger(app) app.config['JWT_SECRET_KEY'] = os.urandom(16) app.config['SEND_FILE_MAX_AGE_DEFAULT'] = 0 app.config['JWT_BLACKLIST_ENABLED'] = True app.config['JWT_BLACKLIST_TOKEN_CHECKS'] = ['access', 'refresh'] app.config['JWT_TOKEN_LOCATION'] = ['cookies'] app.config['JWT_COOKIE_CSRF_PROTECT'] = True app.config['JWT_REFRESH_TOKEN_EXPIRES'] = False DEV_MODE = 0 HOST = '0.0.0.0' PORT = os.environ['PORT'] THREADS = 7 URL_SCHEME = 'http' URL_PREFIX = '' OPTIMIZE_STORAGE = 0 ENABLE_SECURITY_LOGIN = False MAKE_VIEWER_ENDPOINTS_PUBLIC = False SECURITY_USER = None SECURITY_PASS = None SECURITY_VIEWER_USER = None SECURITY_VIEWER_PASS = None USERS_INFO = {} ADMIN_ROLE_NAME = 'admin' VIEWER_ROLE_NAME = 'viewer' PROTECTED_ENDPOINTS = [ { "method": "post", "path": "/refresh", "endpoint": "refresh_endpoint" }, { "method": "delete", "path": "/logout", "endpoint": "logout_endpoint" }, { "method": "delete", "path": "/logout-refresh-token", "endpoint": "logout_refresh_token_endpoint" }, { "method": "post", "path": "/send-results", "endpoint": "send_results_endpoint" }, { "method": "get", "path": "/generate-report", "endpoint": "generate_report_endpoint" }, { "method": "get", "path": "/clean-results", "endpoint": "clean_results_endpoint" }, { "method": "get", "path": "/clean-history", "endpoint": "clean_history_endpoint" }, { "method": "post", "path": "/projects", "endpoint": "create_project_endpoint" }, { "method": "delete", "path": "/projects/{id}", "endpoint": "delete_project_endpoint" } ] GENERATE_REPORT_PROCESS = '{}/generateAllureReport.sh'.format(os.environ['ROOT']) KEEP_HISTORY_PROCESS = '{}/keepAllureHistory.sh'.format(os.environ['ROOT']) CLEAN_HISTORY_PROCESS = '{}/cleanAllureHistory.sh'.format(os.environ['ROOT']) CLEAN_RESULTS_PROCESS = '{}/cleanAllureResults.sh'.format(os.environ['ROOT']) RENDER_EMAIL_REPORT_PROCESS = '{}/renderEmailableReport.sh'.format(os.environ['ROOT']) ALLURE_VERSION = os.environ['ALLURE_VERSION'] STATIC_CONTENT = os.environ['STATIC_CONTENT'] PROJECTS_DIRECTORY = os.environ['STATIC_CONTENT_PROJECTS'] EMAILABLE_REPORT_FILE_NAME = os.environ['EMAILABLE_REPORT_FILE_NAME'] ORIGIN = 'api' SECURITY_SPECS_PATH = 'swagger/security_specs' REPORT_INDEX_FILE = 'index.html' DEFAULT_TEMPLATE = 'default.html' LANGUAGE_TEMPLATE = 'select_language.html' LANGUAGES = ["en", "ru", "zh", "de", "nl", "he", "br", "pl", "ja", "es", "kr", "fr"] GLOBAL_CSS = "https://stackpath.bootstrapcdn.com/bootswatch/4.3.1/cosmo/bootstrap.css" EMAILABLE_REPORT_CSS = GLOBAL_CSS EMAILABLE_REPORT_TITLE = "Emailable Report" API_RESPONSE_LESS_VERBOSE = 0 if "EMAILABLE_REPORT_CSS_CDN" in os.environ: EMAILABLE_REPORT_CSS = os.environ['EMAILABLE_REPORT_CSS_CDN'] LOGGER.info('Overriding CSS for Emailable Report. EMAILABLE_REPORT_CSS_CDN=%s', EMAILABLE_REPORT_CSS) if "EMAILABLE_REPORT_TITLE" in os.environ: EMAILABLE_REPORT_TITLE = os.environ['EMAILABLE_REPORT_TITLE'] LOGGER.info('Overriding Title for Emailable Report. EMAILABLE_REPORT_TITLE=%s', EMAILABLE_REPORT_TITLE) if "API_RESPONSE_LESS_VERBOSE" in os.environ: try: API_RESPONSE_LESS_VERBOSE_TMP = int(os.environ['API_RESPONSE_LESS_VERBOSE']) if API_RESPONSE_LESS_VERBOSE_TMP in (1, 0): API_RESPONSE_LESS_VERBOSE = API_RESPONSE_LESS_VERBOSE_TMP LOGGER.info('Overriding API_RESPONSE_LESS_VERBOSE=%s', API_RESPONSE_LESS_VERBOSE) else: LOGGER.error('Wrong env var value. Setting API_RESPONSE_LESS_VERBOSE=0 by default') except Exception as ex: LOGGER.error('Wrong env var value. Setting API_RESPONSE_LESS_VERBOSE=0 by default') if "DEV_MODE" in os.environ: try: DEV_MODE_TMP = int(os.environ['DEV_MODE']) if DEV_MODE_TMP in (1, 0): DEV_MODE = DEV_MODE_TMP LOGGER.info('Overriding DEV_MODE=%s', DEV_MODE) else: LOGGER.error('Wrong env var value. Setting DEV_MODE=0 by default') except Exception as ex: LOGGER.error('Wrong env var value. Setting DEV_MODE=0 by default') if "TLS" in os.environ: try: IS_ITLS = int(os.environ['TLS']) if IS_ITLS == 1: URL_SCHEME = 'https' app.config['JWT_COOKIE_SECURE'] = True LOGGER.info('Enabling TLS=%s', IS_ITLS) except Exception as ex: LOGGER.error('Wrong env var value. Setting TLS=0 by default') if "URL_PREFIX" in os.environ: PREFIX = str(os.environ['URL_PREFIX']) if DEV_MODE == 1: LOGGER.warning('URL_PREFIX is not supported when DEV_MODE is enabled') else: if PREFIX and PREFIX.strip(): if PREFIX.startswith('/') is False: LOGGER.info('Adding slash at the beginning of URL_PREFIX') PREFIX = '/{}'.format(''.join(PREFIX)) URL_PREFIX = PREFIX LOGGER.info('Setting URL_PREFIX=%s', URL_PREFIX) else: LOGGER.info("URL_PREFIX is empty. It won't be applied") if "OPTIMIZE_STORAGE" in os.environ: try: OPTIMIZE_STORAGE_TMP = int(os.environ['OPTIMIZE_STORAGE']) if OPTIMIZE_STORAGE_TMP in (1, 0): OPTIMIZE_STORAGE = OPTIMIZE_STORAGE_TMP LOGGER.info('Overriding OPTIMIZE_STORAGE=%s', OPTIMIZE_STORAGE) else: LOGGER.error('Wrong env var value. Setting OPTIMIZE_STORAGE=0 by default') except Exception as ex: LOGGER.error('Wrong env var value. Setting OPTIMIZE_STORAGE=0 by default') if "MAKE_VIEWER_ENDPOINTS_PUBLIC" in os.environ: try: VIEWER_ENDPOINTS_PUBLIC_TMP = int(os.environ['MAKE_VIEWER_ENDPOINTS_PUBLIC']) if VIEWER_ENDPOINTS_PUBLIC_TMP == 1: MAKE_VIEWER_ENDPOINTS_PUBLIC = True LOGGER.info('Overriding MAKE_VIEWER_ENDPOINTS_PUBLIC=%s', VIEWER_ENDPOINTS_PUBLIC_TMP) except Exception as ex: LOGGER.error('Wrong env var value. Setting VIEWER_ENDPOINTS_PUBLIC=0 by default') if "SECURITY_USER" in os.environ: SECURITY_USER_TMP = os.environ['SECURITY_USER'] if SECURITY_USER_TMP and SECURITY_USER_TMP.strip(): SECURITY_USER = SECURITY_USER_TMP.lower() LOGGER.info('Setting SECURITY_USER') if "SECURITY_PASS" in os.environ: SECURITY_PASS_TMP = os.environ['SECURITY_PASS'] if SECURITY_PASS_TMP and SECURITY_PASS_TMP.strip(): SECURITY_PASS = SECURITY_PASS_TMP LOGGER.info('Setting SECURITY_PASS') if MAKE_VIEWER_ENDPOINTS_PUBLIC is False: if "SECURITY_VIEWER_USER" in os.environ: SECURITY_VIEWER_USER_TMP = os.environ['SECURITY_VIEWER_USER'] if SECURITY_VIEWER_USER_TMP and SECURITY_VIEWER_USER_TMP.strip(): SECURITY_VIEWER_USER = SECURITY_VIEWER_USER_TMP.lower() LOGGER.info('Setting SECURITY_VIEWER_USER') if "SECURITY_VIEWER_PASS" in os.environ: SECURITY_VIEWER_PASS_TMP = os.environ['SECURITY_VIEWER_PASS'] if SECURITY_VIEWER_PASS_TMP and SECURITY_VIEWER_PASS_TMP.strip(): SECURITY_VIEWER_PASS = SECURITY_VIEWER_PASS_TMP LOGGER.info('Setting SECURITY_VIEWER_PASS') if "SECURITY_ENABLED" in os.environ: try: ENABLE_SECURITY_LOGIN_TMP = int(os.environ['SECURITY_ENABLED']) if SECURITY_USER and SECURITY_PASS: if SECURITY_USER != SECURITY_VIEWER_USER: if ENABLE_SECURITY_LOGIN_TMP == 1: ENABLE_SECURITY_LOGIN = True LOGGER.info('Enabling Security Login. SECURITY_ENABLED=1') USERS_INFO[SECURITY_USER] = { 'pass': SECURITY_PASS, 'roles': [ADMIN_ROLE_NAME] } if SECURITY_VIEWER_USER is not None and SECURITY_VIEWER_PASS is not None: USERS_INFO[SECURITY_VIEWER_USER] = { 'pass': SECURITY_VIEWER_PASS, 'roles': [VIEWER_ROLE_NAME] } else: LOGGER.info('Setting SECURITY_ENABLED=0 by default') else: LOGGER.info('SECURITY_USER and SECURITY_VIEWER_USER should be different') LOGGER.info('Setting SECURITY_ENABLED=0 by default') else: LOGGER.info("To enable security you need SECURITY_USER' & 'SECURITY_PASS' env vars") LOGGER.info('Setting SECURITY_ENABLED=0 by default') except Exception as ex: LOGGER.error('Wrong env var value. Setting SECURITY_ENABLED=0 by default') else: LOGGER.info('Setting SECURITY_ENABLED=0 by default') # For development purposes if "ACCESS_TOKEN_EXPIRES_IN_SECONDS" in os.environ: try: ACCESS_TOKEN_EXPIRES_IN_SECONDS = int(os.environ['ACCESS_TOKEN_EXPIRES_IN_SECONDS']) if ACCESS_TOKEN_EXPIRES_IN_SECONDS > 0: SECONDS = datetime.timedelta(seconds=ACCESS_TOKEN_EXPIRES_IN_SECONDS) app.config['JWT_ACCESS_TOKEN_EXPIRES'] = SECONDS LOGGER.info('Setting ACCESS_TOKEN_EXPIRES_IN_SECONDS=%s', ACCESS_TOKEN_EXPIRES_IN_SECONDS) else: app.config['JWT_ACCESS_TOKEN_EXPIRES'] = False LOGGER.info('Disabling ACCESS_TOKEN expiration') except Exception as ex: LOGGER.error('Wrong env var value. Setting ACCESS_TOKEN_EXPIRES_IN_DAYS by default 15 mins') # For development purposes if "REFRESH_TOKEN_EXPIRES_IN_SECONDS" in os.environ: try: REFRESH_TOKEN_EXPIRES_IN_SECONDS = int(os.environ['REFRESH_TOKEN_EXPIRES_IN_SECONDS']) if REFRESH_TOKEN_EXPIRES_IN_SECONDS > 0: SECONDS = datetime.timedelta(seconds=REFRESH_TOKEN_EXPIRES_IN_SECONDS) app.config['JWT_REFRESH_TOKEN_EXPIRES'] = SECONDS LOGGER.info('Setting REFRESH_TOKEN_EXPIRES_IN_SECONDS=%s', REFRESH_TOKEN_EXPIRES_IN_SECONDS) else: app.config['JWT_REFRESH_TOKEN_EXPIRES'] = False LOGGER.info('Disabling REFRESH_TOKEN expiration') except Exception as ex: LOGGER.error('Wrong env var value. Setting REFRESH_TOKEN_EXPIRES_IN_SECONDS keeps disabled') if "ACCESS_TOKEN_EXPIRES_IN_MINS" in os.environ: try: ACCESS_TOKEN_EXPIRES_IN_MINS = int(os.environ['ACCESS_TOKEN_EXPIRES_IN_MINS']) if ACCESS_TOKEN_EXPIRES_IN_MINS > 0: MINS = datetime.timedelta(minutes=ACCESS_TOKEN_EXPIRES_IN_MINS) app.config['JWT_ACCESS_TOKEN_EXPIRES'] = MINS LOGGER.info('Setting ACCESS_TOKEN_EXPIRES_IN_MINS=%s', ACCESS_TOKEN_EXPIRES_IN_MINS) else: app.config['JWT_ACCESS_TOKEN_EXPIRES'] = False LOGGER.info('Disabling ACCESS_TOKEN expiration') except Exception as ex: LOGGER.error('Wrong env var value. Setting ACCESS_TOKEN_EXPIRES_IN_MINS by default 15 mins') if "REFRESH_TOKEN_EXPIRES_IN_DAYS" in os.environ: try: REFRESH_TOKEN_EXPIRES_IN_DAYS = int(os.environ['REFRESH_TOKEN_EXPIRES_IN_DAYS']) if REFRESH_TOKEN_EXPIRES_IN_DAYS > 0: DAYS = datetime.timedelta(days=REFRESH_TOKEN_EXPIRES_IN_DAYS) app.config['JWT_REFRESH_TOKEN_EXPIRES'] = DAYS LOGGER.info('Setting REFRESH_TOKEN_EXPIRES_IN_DAYS=%s', REFRESH_TOKEN_EXPIRES_IN_DAYS) else: app.config['JWT_REFRESH_TOKEN_EXPIRES'] = False LOGGER.info('Disabling REFRESH_TOKEN expiration') except Exception as ex: LOGGER.error('Wrong env var value. Setting REFRESH_TOKEN_EXPIRES_IN_DAYS keeps disabled') def get_file_as_string(path_file): file = None content = None try: file = open(path_file, "r") content = file.read() finally: if file is not None: file.close() return content def get_security_specs(): security_specs = {} for file in os.listdir("{}/{}/".format(STATIC_CONTENT, SECURITY_SPECS_PATH)): file_path = "{}/{}/{}".format(STATIC_CONTENT, SECURITY_SPECS_PATH, file) security_specs[file] = eval(get_file_as_string(file_path)) #pylint: disable=eval-used return security_specs def is_endpoint_protected(endpoint): if MAKE_VIEWER_ENDPOINTS_PUBLIC is False: return True for info in PROTECTED_ENDPOINTS: if endpoint == info['endpoint']: return True return False def is_endpoint_swagger_protected(method, path): if MAKE_VIEWER_ENDPOINTS_PUBLIC is False: return True for info in PROTECTED_ENDPOINTS: if info['method'] == method and path == info['path']: return True return False def generate_security_swagger_spec(): try: security_specs = get_security_specs() with open("{}/swagger/swagger.json".format(STATIC_CONTENT)) as json_file: data = json.load(json_file) data['tags'].insert(1, security_specs['security_tags.json']) data['paths']['/login'] = security_specs['login_spec.json'] data['paths']['/refresh'] = security_specs['refresh_spec.json'] data['paths']['/logout'] = security_specs['logout_spec.json'] data['paths']['/logout-refresh-token'] = security_specs['logout_refresh_spec.json'] data['components']['schemas']['login'] = security_specs['login_scheme.json'] ensure_tags = ['Action', 'Project'] security_type = security_specs['security_type.json'] security_401_response = security_specs['security_unauthorized_response.json'] security_403_response = security_specs['security_forbidden_response.json'] security_crsf = security_specs['security_csrf.json'] for path in data['paths']: #pylint: disable=too-many-nested-blocks for method in data['paths'][path]: if is_endpoint_swagger_protected(method, path): if set(ensure_tags) & set(data['paths'][path][method]['tags']): data['paths'][path][method]['security'] = security_type data['paths'][path][method]['responses']['401'] = security_401_response data['paths'][path][method]['responses']['403'] = security_403_response if method in ['post', 'put', 'patch', 'delete']: if 'parameters' in data['paths'][path][method]: params = data['paths'][path][method]['parameters'] params.append(security_crsf) data['paths'][path][method]['parameters'] = params else: data['paths'][path][method]['parameters'] = [security_crsf] with open("{}/swagger/swagger_security.json".format(STATIC_CONTENT), 'w') as outfile: json.dump(data, outfile) except Exception as ex: LOGGER.error(str(ex)) ### swagger specific ### NATIVE_PREFIX = '/allure-docker-service' SWAGGER_ENDPOINT = '/swagger' SWAGGER_SPEC_FILE = '/swagger.json' SWAGGER_ENDPOINT_PATH = '{}{}'.format(NATIVE_PREFIX, SWAGGER_ENDPOINT) SWAGGER_SPEC = '{}{}'.format(NATIVE_PREFIX, SWAGGER_SPEC_FILE) if URL_PREFIX: SWAGGER_ENDPOINT_PATH = '{}{}{}'.format(URL_PREFIX, NATIVE_PREFIX, SWAGGER_ENDPOINT) SWAGGER_SPEC = '{}{}{}'.format(URL_PREFIX, NATIVE_PREFIX, SWAGGER_SPEC_FILE) SWAGGERUI_BLUEPRINT = get_swaggerui_blueprint( base_url=SWAGGER_ENDPOINT_PATH, api_url=SWAGGER_SPEC, config={ 'app_name': "Allure Docker Service" } ) app.register_blueprint(SWAGGERUI_BLUEPRINT, url_prefix="/") app.register_blueprint(SWAGGERUI_BLUEPRINT, url_prefix=NATIVE_PREFIX) app.register_blueprint(SWAGGERUI_BLUEPRINT, url_prefix=SWAGGER_ENDPOINT) app.register_blueprint(SWAGGERUI_BLUEPRINT, url_prefix=SWAGGER_ENDPOINT_PATH) if URL_PREFIX: app.register_blueprint(SWAGGERUI_BLUEPRINT, url_prefix='{}{}'.format(NATIVE_PREFIX, SWAGGER_ENDPOINT)) ### end swagger specific ### ### Security Section if ENABLE_SECURITY_LOGIN: generate_security_swagger_spec() blacklist = set() #pylint: disable=invalid-name jwt = JWTManager(app) #pylint: disable=invalid-name @jwt.token_in_blacklist_loader def check_if_token_in_blacklist(decrypted_token): jti = decrypted_token['jti'] return jti in blacklist @jwt.invalid_token_loader def invalid_token_loader(msg): return jsonify({ 'meta_data': { 'message': 'Invalid Token - {}'.format(msg) } }), 401 @jwt.unauthorized_loader def unauthorized_loader(msg): return jsonify({ 'meta_data': { 'message': msg } }), 401 @jwt.expired_token_loader def my_expired_token_callback(expired_token): token_type = expired_token['type'] return jsonify({ 'meta_data': { 'message': 'The {} token has expired'.format(token_type), 'sub_status': 42, } }), 401 @jwt.revoked_token_loader def revoked_token_loader(): return jsonify({ 'meta_data': { 'message': 'Revoked Token' } }), 401 def jwt_required(fn): #pylint: disable=invalid-name, function-redefined @wraps(fn) def wrapper(*args, **kwargs): if ENABLE_SECURITY_LOGIN: if is_endpoint_protected(request.endpoint): verify_jwt_in_request() return fn(*args, **kwargs) return wrapper def jwt_refresh_token_required(fn): #pylint: disable=invalid-name, function-redefined @wraps(fn) def wrapper(*args, **kwargs): if ENABLE_SECURITY_LOGIN: if is_endpoint_protected(request.endpoint): verify_jwt_refresh_token_in_request() return fn(*args, **kwargs) return wrapper @jwt.user_loader_callback_loader def user_loader_callback(identity): if identity not in USERS_INFO: return None return UserAccess( username=identity, roles=USERS_INFO[identity]['roles'] ) ### end Security Section ### CORS section @app.after_request def after_request_func(response): origin = request.headers.get('Origin') if request.method == 'OPTIONS': response = make_response() response.headers.add('Access-Control-Allow-Credentials', 'true') response.headers.add('Access-Control-Allow-Headers', 'Content-Type') response.headers.add('Access-Control-Allow-Headers', 'x-csrf-token') response.headers.add('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE') if origin: response.headers.add('Access-Control-Allow-Origin', origin) else: response.headers.add('Access-Control-Allow-Credentials', 'true') if origin: response.headers.add('Access-Control-Allow-Origin', origin) return response ### end CORS section ### Security Endpoints Section @app.route('/login', methods=['POST'], strict_slashes=False) @app.route('/allure-docker-service/login', methods=['POST'], strict_slashes=False) def login_endpoint(): try: if ENABLE_SECURITY_LOGIN is False: body = { 'meta_data': { 'message' : 'SECURITY is not enabled' } } resp = jsonify(body) return resp, 404 content_type = str(request.content_type) if content_type is None and content_type.startswith('application/json') is False: raise Exception("Header 'Content-Type' must be 'application/json'") if not request.is_json: raise Exception("Missing JSON in body request") username = request.json.get('username', None) if not username: raise Exception("Missing 'username' attribute") username = username.lower() if username not in USERS_INFO: return jsonify({'meta_data': {'message' : 'Invalid username/password'}}), 401 password = request.json.get('password', None) if not password: raise Exception("Missing 'password' attribute") if USERS_INFO[username]['pass'] != password: return jsonify({'meta_data': {'message' : 'Invalid username/password'}}), 401 access_token = create_access_token(identity=username) refresh_token = create_refresh_token(identity=username) access_token_expires = app.config['JWT_ACCESS_TOKEN_EXPIRES'] expires_in = access_token_expires.total_seconds() if access_token_expires else 0 json_body = { 'data': { 'access_token': access_token, 'refresh_token': refresh_token, 'expires_in': expires_in, 'roles': USERS_INFO[username]['roles'] }, 'meta_data': {'message' : 'Successfully logged'} } resp = jsonify(json_body) set_access_cookies(resp, access_token) set_refresh_cookies(resp, refresh_token) return resp, 200 except Exception as ex: body = { 'meta_data': { 'message' : str(ex) } } resp = jsonify(body) return resp, 400 @app.route('/logout', methods=['DELETE'], strict_slashes=False) @app.route('/allure-docker-service/logout', methods=['DELETE'], strict_slashes=False) @jwt_required def logout_endpoint(): if ENABLE_SECURITY_LOGIN is False: body = { 'meta_data': { 'message' : 'SECURITY is not enabled' } } resp = jsonify(body) return resp, 404 try: jti = get_raw_jwt()['jti'] blacklist.add(jti) return jsonify({'meta_data': {'message' : 'Successfully logged out'}}), 200 except Exception as ex: body = { 'meta_data': { 'message' : str(ex) } } resp = jsonify(body) return resp, 400 @app.route('/logout-refresh-token', methods=['DELETE'], strict_slashes=False) @app.route('/allure-docker-service/logout-refresh-token', methods=['DELETE'], strict_slashes=False) @jwt_refresh_token_required def logout_refresh_token_endpoint(): if ENABLE_SECURITY_LOGIN is False: body = { 'meta_data': { 'message' : 'SECURITY is not enabled' } } resp = jsonify(body) return resp, 404 try: jti = get_raw_jwt()['jti'] blacklist.add(jti) resp = jsonify({'meta_data': {'message' : 'Successfully logged out'}}) unset_jwt_cookies(resp) return resp, 200 except Exception as ex: body = { 'meta_data': { 'message' : str(ex) } } resp = jsonify(body) return resp, 400 @app.route('/refresh', methods=['POST'], strict_slashes=False) @app.route('/allure-docker-service/refresh', methods=['POST'], strict_slashes=False) @jwt_refresh_token_required def refresh_endpoint(): if ENABLE_SECURITY_LOGIN is False: body = { 'meta_data': { 'message' : 'SECURITY is not enabled' } } resp = jsonify(body) return resp, 404 try: username = get_jwt_identity() access_token = create_access_token(identity=username) access_token_expires = app.config['JWT_ACCESS_TOKEN_EXPIRES'] expires_in = access_token_expires.total_seconds() if access_token_expires else 0 json_body = { 'data': { 'access_token': access_token, 'expires_in': expires_in, 'roles': USERS_INFO[username]['roles'] }, 'meta_data': { 'message' : 'Successfully token obtained' } } resp = jsonify(json_body) set_access_cookies(resp, access_token) return resp, 200 except Exception as ex: body = { 'meta_data': { 'message' : str(ex) } } resp = jsonify(body) return resp, 400 ### end Security Endpoints Section @app.route("/swagger.json") @app.route("/allure-docker-service/swagger.json", strict_slashes=False) def swagger_json_endpoint(): try: specification_file = 'swagger.json' if ENABLE_SECURITY_LOGIN: specification_file = 'swagger_security.json' if URL_PREFIX: spec = get_file_as_string("{}/swagger/{}".format(STATIC_CONTENT, specification_file)) spec_json = eval(spec) #pylint: disable=eval-used server_url = spec_json['servers'][0]['url'] spec_json['servers'][0]['url'] = '{}{}'.format(URL_PREFIX, server_url) return jsonify(spec_json) return send_file("{}/swagger/{}" .format(STATIC_CONTENT, specification_file), mimetype='application/json') except Exception as ex: body = { 'meta_data': { 'message' : str(ex) } } resp = jsonify(body) resp.status_code = 400 return resp @app.route("/version", strict_slashes=False) @app.route("/allure-docker-service/version", strict_slashes=False) def version_endpoint(): try: version = get_file_as_string(ALLURE_VERSION).strip() except Exception as ex: body = { 'meta_data': { 'message' : str(ex) } } resp = jsonify(body) resp.status_code = 400 else: body = { 'data': { 'version': version }, 'meta_data': { 'message' : "Version successfully obtained" } } resp = jsonify(body) resp.status_code = 200 return resp @app.route("/config", strict_slashes=False) @app.route("/allure-docker-service/config", strict_slashes=False) @jwt_required def config_endpoint(): try: version = get_file_as_string(ALLURE_VERSION).strip() check_results_every_seconds = os.getenv('CHECK_RESULTS_EVERY_SECONDS', '1') keep_history = os.getenv('KEEP_HISTORY', '0') keep_history_latest = os.getenv('KEEP_HISTORY_LATEST', '20') tls = int(app.config['JWT_COOKIE_SECURE']) security_enabled = int(ENABLE_SECURITY_LOGIN) make_viewer_endpoints_public = int(MAKE_VIEWER_ENDPOINTS_PUBLIC) body = { 'data': { 'version': version, 'dev_mode': DEV_MODE, 'check_results_every_seconds': check_results_every_seconds, 'keep_history': keep_history, 'keep_history_latest': keep_history_latest, 'tls': tls, 'security_enabled': security_enabled, 'url_prefix': URL_PREFIX, 'api_response_less_verbose': API_RESPONSE_LESS_VERBOSE, 'optimize_storage': OPTIMIZE_STORAGE, "make_viewer_endpoints_public": make_viewer_endpoints_public }, 'meta_data': { 'message' : "Config successfully obtained" } } resp = jsonify(body) resp.status_code = 200 return resp except Exception as ex: body = { 'meta_data': { 'message' : str(ex) } } resp = jsonify(body) resp.status_code = 400 return resp @app.route("/select-language", strict_slashes=False) @app.route("/allure-docker-service/select-language", strict_slashes=False) @jwt_required def select_language_endpoint(): try: code = request.args.get('code') if code is None: raise Exception("'code' query parameter is required") code = code.lower() if code not in LANGUAGES: raise Exception("'code' not supported. Use values: {}".format(LANGUAGES)) return render_template(LANGUAGE_TEMPLATE, languageCode=code, css=GLOBAL_CSS) except Exception as ex: body = { 'meta_data': { 'message' : str(ex) } } resp = jsonify(body) resp.status_code = 400 return resp @app.route("/latest-report", strict_slashes=False) @app.route("/allure-docker-service/latest-report", strict_slashes=False) @jwt_required def latest_report_endpoint(): try: project_id = resolve_project(request.args.get('project_id')) if is_existent_project(project_id) is False: body = { 'meta_data': { 'message' : "project_id '{}' not found".format(project_id) } } resp = jsonify(body) resp.status_code = 404 return resp project_report_latest_path = '/latest/{}'.format(REPORT_INDEX_FILE) url = url_for('get_reports_endpoint', project_id=project_id, path=project_report_latest_path, redirect='false', _external=True) return redirect(url) except Exception as ex: body = { 'meta_data': { 'message' : str(ex) } } resp = jsonify(body) resp.status_code = 400 return resp @app.route("/latest-report-time", strict_slashes=False) @app.route("/allure-docker-service/latest-report-time", strict_slashes=False) @jwt_required def latest_report_time_endpoint(): try: project_id = resolve_project(request.args.get('project_id')) if is_existent_project(project_id) is False: body = { 'meta_data': { 'message' : "project_id '{}' not found".format(project_id) } } resp = jsonify(body) resp.status_code = 404 return resp with open('projects/{}/reports/latest/data/behaviors.json'.format(project_id)) as f: json_content = json.load(f) timestamp = int(str(json_content['children'][0]['children'][0]['children'][0]['time']['start'])[0:10]) start_time = datetime.datetime.fromtimestamp(timestamp) except Exception as ex: body = { 'meta_data': { 'message' : str(ex) } } resp = jsonify(body) resp.status_code = 400 return resp else: body = { 'meta_data': { 'latest_report_start_time': start_time } } resp = jsonify(body) resp.status_code = 200 return resp @app.route("/send-results", methods=['POST'], strict_slashes=False) @app.route("/allure-docker-service/send-results", methods=['POST'], strict_slashes=False) @jwt_required def send_results_endpoint(): #pylint: disable=too-many-branches try: if check_admin_access(current_user) is False: return jsonify({ 'meta_data': { 'message': 'Access Forbidden' } }), 403 content_type = str(request.content_type) if content_type is None: raise Exception("Header 'Content-Type' should start with 'application/json' or 'multipart/form-data'") #pylint: disable=line-too-long if ( content_type.startswith('application/json') is False and content_type.startswith('multipart/form-data') is False ): raise Exception("Header 'Content-Type' should start with 'application/json' or 'multipart/form-data'") #pylint: disable=line-too-long project_id = resolve_project(request.args.get('project_id')) if is_existent_project(project_id) is False: if request.args.get('force_project_creation') == 'true': project_id = create_project({ "id": project_id }) else: body = { 'meta_data': { 'message' : "project_id '{}' not found".format(project_id) } } resp = jsonify(body) resp.status_code = 404 return resp validated_results = [] processed_files = [] failed_files = [] results_project = '{}/results'.format(get_project_path(project_id)) if content_type.startswith('application/json') is True: json_body = request.get_json() if 'results' not in json_body: raise Exception("'results' array is required in the body") validated_results = validate_json_results(json_body['results']) send_json_results(results_project, validated_results, processed_files, failed_files) if content_type.startswith('multipart/form-data') is True: validated_results = validate_files_array(request.files.getlist('files[]')) send_files_results(results_project, validated_results, processed_files, failed_files) failed_files_count = len(failed_files) if failed_files_count > 0: raise Exception('Problems with files: {}'.format(failed_files)) if API_RESPONSE_LESS_VERBOSE != 1: files = os.listdir(results_project) current_files_count = len(files) sent_files_count = len(validated_results) processed_files_count = len(processed_files) except Exception as ex: body = { 'meta_data': { 'message' : str(ex) } } resp = jsonify(body) resp.status_code = 400 else: if API_RESPONSE_LESS_VERBOSE != 1: body = { 'data': { 'current_files': files, 'current_files_count': current_files_count, 'failed_files': failed_files, 'failed_files_count': failed_files_count, 'processed_files': processed_files, 'processed_files_count': processed_files_count, 'sent_files_count': sent_files_count }, 'meta_data': { 'message' : "Results successfully sent for project_id '{}'".format(project_id) } } else: body = { 'meta_data': { 'message' : "Results successfully sent for project_id '{}'".format(project_id) } } resp = jsonify(body) resp.status_code = 200 return resp @app.route("/generate-report", strict_slashes=False) @app.route("/allure-docker-service/generate-report", strict_slashes=False) @jwt_required def generate_report_endpoint(): try: if check_admin_access(current_user) is False: return jsonify({ 'meta_data': { 'message': 'Access Forbidden' } }), 403 project_id = resolve_project(request.args.get('project_id')) if is_existent_project(project_id) is False: body = { 'meta_data': { 'message' : "project_id '{}' not found".format(project_id) } } resp = jsonify(body) resp.status_code = 404 return resp files = None project_path = get_project_path(project_id) results_project = '{}/results'.format(project_path) if API_RESPONSE_LESS_VERBOSE != 1: files = os.listdir(results_project) execution_name = request.args.get('execution_name') if execution_name is None or not execution_name: execution_name = 'Execution On Demand' execution_from = request.args.get('execution_from') if execution_from is None or not execution_from: execution_from = '' execution_type = request.args.get('execution_type') if execution_type is None or not execution_type: execution_type = '' check_process(KEEP_HISTORY_PROCESS, project_id) check_process(GENERATE_REPORT_PROCESS, project_id) exec_store_results_process = '1' call([KEEP_HISTORY_PROCESS, project_id, ORIGIN]) response = subprocess.Popen([ GENERATE_REPORT_PROCESS, exec_store_results_process, project_id, ORIGIN, execution_name, execution_from, execution_type], stdout=subprocess.PIPE).communicate()[0] call([RENDER_EMAIL_REPORT_PROCESS, project_id, ORIGIN]) build_order = 'latest' for line in response.decode("utf-8").split("\n"): if line.startswith("BUILD_ORDER"): build_order = line[line.index(':') + 1: len(line)] report_url = url_for('get_reports_endpoint', project_id=project_id, path='{}/index.html'.format(build_order), _external=True) except Exception as ex: body = { 'meta_data': { 'message' : str(ex) } } resp = jsonify(body) resp.status_code = 400 else: if files is not None: body = { 'data': { 'report_url': report_url, 'allure_results_files': files }, 'meta_data': { 'message' : "Report successfully generated for project_id '{}'" .format(project_id) } } else: body = { 'data': { 'report_url': report_url }, 'meta_data': { 'message' : "Report successfully generated for project_id '{}'" .format(project_id) } } resp = jsonify(body) resp.status_code = 200 return resp @app.route("/clean-history", strict_slashes=False) @app.route("/allure-docker-service/clean-history", strict_slashes=False) @jwt_required def clean_history_endpoint(): try: if check_admin_access(current_user) is False: return jsonify({ 'meta_data': { 'message': 'Access Forbidden' } }), 403 project_id = resolve_project(request.args.get('project_id')) if is_existent_project(project_id) is False: body = { 'meta_data': { 'message' : "project_id '{}' not found".format(project_id) } } resp = jsonify(body) resp.status_code = 404 return resp check_process(CLEAN_HISTORY_PROCESS, project_id) call([CLEAN_HISTORY_PROCESS, project_id, ORIGIN]) except Exception as ex: body = { 'meta_data': { 'message' : str(ex) } } resp = jsonify(body) resp.status_code = 400 else: body = { 'meta_data': { 'message' : "History successfully cleaned for project_id '{}'".format(project_id) } } resp = jsonify(body) resp.status_code = 200 return resp @app.route("/clean-results", strict_slashes=False) @app.route("/allure-docker-service/clean-results", strict_slashes=False) @jwt_required def clean_results_endpoint(): try: if check_admin_access(current_user) is False: return jsonify({ 'meta_data': { 'message': 'Access Forbidden' } }), 403 project_id = resolve_project(request.args.get('project_id')) if is_existent_project(project_id) is False: body = { 'meta_data': { 'message' : "project_id '{}' not found".format(project_id) } } resp = jsonify(body) resp.status_code = 404 return resp check_process(GENERATE_REPORT_PROCESS, project_id) check_process(CLEAN_RESULTS_PROCESS, project_id) call([CLEAN_RESULTS_PROCESS, project_id, ORIGIN]) except Exception as ex: body = { 'meta_data': { 'message' : str(ex) } } resp = jsonify(body) resp.status_code = 400 else: body = { 'meta_data': { 'message' : "Results successfully cleaned for project_id '{}'".format(project_id) } } resp = jsonify(body) resp.status_code = 200 return resp @app.route("/emailable-report/render", strict_slashes=False) @app.route("/allure-docker-service/emailable-report/render", strict_slashes=False) @jwt_required def emailable_report_render_endpoint(): try: project_id = resolve_project(request.args.get('project_id')) if is_existent_project(project_id) is False: body = { 'meta_data': { 'message' : "project_id '{}' not found".format(project_id) } } resp = jsonify(body) resp.status_code = 404 return resp check_process(GENERATE_REPORT_PROCESS, project_id) project_path = get_project_path(project_id) tcs_latest_report_project = "{}/reports/latest/data/test-cases/*.json".format(project_path) files = glob.glob(tcs_latest_report_project) files.sort(key=os.path.getmtime, reverse=True) test_cases = [] for file_name in files: with open(file_name) as file: json_string = file.read() LOGGER.debug("----TestCase-JSON----") LOGGER.debug(json_string) test_case = json.loads(json_string) if test_case["hidden"] is False: test_cases.append(test_case) server_url = url_for('latest_report_endpoint', project_id=project_id, _external=True) if "SERVER_URL" in os.environ: server_url = os.environ['SERVER_URL'] report = render_template(DEFAULT_TEMPLATE, css=EMAILABLE_REPORT_CSS, title=EMAILABLE_REPORT_TITLE, projectId=project_id, serverUrl=server_url, testCases=test_cases) emailable_report_path = '{}/reports/{}'.format(project_path, EMAILABLE_REPORT_FILE_NAME) file = None try: file = open(emailable_report_path, "w") file.write(report) finally: if file is not None: file.close() except Exception as ex: body = { 'meta_data': { 'message' : str(ex) } } resp = jsonify(body) resp.status_code = 400 return resp else: return report @app.route("/emailable-report/export", strict_slashes=False) @app.route("/allure-docker-service/emailable-report/export", strict_slashes=False) @jwt_required def emailable_report_export_endpoint(): try: project_id = resolve_project(request.args.get('project_id')) if is_existent_project(project_id) is False: body = { 'meta_data': { 'message' : "project_id '{}' not found".format(project_id) } } resp = jsonify(body) resp.status_code = 404 return resp check_process(GENERATE_REPORT_PROCESS, project_id) project_path = get_project_path(project_id) emailable_report_path = '{}/reports/{}'.format(project_path, EMAILABLE_REPORT_FILE_NAME) report = send_file(emailable_report_path, as_attachment=True) except Exception as ex: message = str(ex) body = { 'meta_data': { 'message' : message } } resp = jsonify(body) resp.status_code = 400 return resp else: return report @app.route("/report/export", strict_slashes=False) @app.route("/allure-docker-service/report/export", strict_slashes=False) @jwt_required def report_export_endpoint(): try: project_id = resolve_project(request.args.get('project_id')) if is_existent_project(project_id) is False: body = { 'meta_data': { 'message' : "project_id '{}' not found".format(project_id) } } resp = jsonify(body) resp.status_code = 404 return resp check_process(GENERATE_REPORT_PROCESS, project_id) project_path = get_project_path(project_id) tmp_report = '{}/allure-report'.format(tempfile.mkdtemp()) shutil.copytree('{}/reports/latest'.format(project_path), tmp_report) data = io.BytesIO() with zipfile.ZipFile(data, 'w', zipfile.ZIP_DEFLATED) as zipf: root_dir = os.path.basename(tmp_report) for dirpath, dirnames, files in os.walk(tmp_report): #pylint: disable=unused-variable for file in files: file_path = os.path.join(dirpath, file) parent_path = os.path.relpath(file_path, tmp_report) zipf.write(file_path, os.path.join(root_dir, parent_path)) data.seek(0) shutil.rmtree(tmp_report, ignore_errors=True) return send_file( data, mimetype='application/zip', as_attachment=True, attachment_filename='allure-docker-service-report.zip' ) except Exception as ex: body = { 'meta_data': { 'message' : str(ex) } } resp = jsonify(body) resp.status_code = 400 return resp @app.route("/projects", methods=['POST'], strict_slashes=False) @app.route("/allure-docker-service/projects", methods=['POST'], strict_slashes=False) @jwt_required def create_project_endpoint(): try: if check_admin_access(current_user) is False: return jsonify({ 'meta_data': { 'message': 'Access Forbidden' } }), 403 if not request.is_json: raise Exception("Header 'Content-Type' is not 'application/json'") project_id = create_project(request.get_json()) except Exception as ex: body = { 'meta_data': { 'message' : str(ex) } } resp = jsonify(body) resp.status_code = 400 else: body = { 'data': { 'id': project_id, }, 'meta_data': { 'message' : "Project successfully created" } } resp = jsonify(body) resp.status_code = 201 return resp @app.route('/projects/<project_id>', methods=['DELETE'], strict_slashes=False) @app.route("/allure-docker-service/projects/<project_id>", methods=['DELETE'], strict_slashes=False) @jwt_required def delete_project_endpoint(project_id): try: if check_admin_access(current_user) is False: return jsonify({ 'meta_data': { 'message': 'Access Forbidden' } }), 403 if project_id == 'default': raise Exception("You must not remove project_id 'default'. Try with other projects") if is_existent_project(project_id) is False: body = { 'meta_data': { 'message' : "project_id '{}' not found".format(project_id) } } resp = jsonify(body) resp.status_code = 404 return resp project_path = get_project_path(project_id) shutil.rmtree(project_path) except Exception as ex: body = { 'meta_data': { 'message' : str(ex) } } resp = jsonify(body) resp.status_code = 400 else: body = { 'meta_data': { 'message' : "project_id: '{}' successfully removed".format(project_id) } } resp = jsonify(body) resp.status_code = 200 return resp @app.route('/projects/<project_id>', strict_slashes=False) @app.route("/allure-docker-service/projects/<project_id>", strict_slashes=False) @jwt_required def get_project_endpoint(project_id): try: if is_existent_project(project_id) is False: body = { 'meta_data': { 'message' : "project_id '{}' not found".format(project_id) } } resp = jsonify(body) resp.status_code = 404 return resp project_reports_path = '{}/reports'.format(get_project_path(project_id)) reports_entity = [] for file in os.listdir(project_reports_path): file_path = '{}/{}/index.html'.format(project_reports_path, file) is_file = os.path.isfile(file_path) if is_file is True: report = url_for('get_reports_endpoint', project_id=project_id, path='{}/index.html'.format(file), _external=True) reports_entity.append([report, os.path.getmtime(file_path), file]) reports_entity.sort(key=lambda reports_entity: reports_entity[1], reverse=True) reports = [] reports_id = [] latest_report = None for report_entity in reports_entity: link = report_entity[0] if report_entity[2].lower() != 'latest': reports.append(link) reports_id.append(report_entity[2]) else: latest_report = link if latest_report is not None: reports.insert(0, latest_report) reports_id.insert(0, 'latest') body = { 'data': { 'project': { 'id': project_id, 'reports': reports, 'reports_id': reports_id }, }, 'meta_data': { 'message' : "Project successfully obtained" } } resp = jsonify(body) resp.status_code = 200 return resp except Exception as ex: body = { 'meta_data': { 'message' : str(ex) } } resp = jsonify(body) resp.status_code = 400 return resp @app.route('/projects', strict_slashes=False) @app.route("/allure-docker-service/projects", strict_slashes=False) @jwt_required def get_projects_endpoint(): try: projects_dirs = os.listdir(PROJECTS_DIRECTORY) projects = get_projects(projects_dirs) body = { 'data': { 'projects': projects, }, 'meta_data': { 'message' : "Projects successfully obtained" } } resp = jsonify(body) resp.status_code = 200 return resp except Exception as ex: body = { 'meta_data': { 'message' : str(ex) } } resp = jsonify(body) resp.status_code = 400 return resp @app.route('/projects/search', strict_slashes=False) @app.route("/allure-docker-service/projects/search", strict_slashes=False) @jwt_required def get_projects_search_endpoint(): try: project_id = request.args.get('id') if project_id is None: raise Exception("'id' query parameter is required") project_id = project_id.lower() projects_filtered = get_projects_filtered_by_id(project_id, os.listdir(PROJECTS_DIRECTORY)) projects = get_projects(projects_filtered) if len(projects) == 0: return jsonify({'meta_data': {'message': 'Project not found'}}), 404 body = { 'data': { 'projects': projects, }, 'meta_data': { 'message' : "Project/s successfully obtained" } } resp = jsonify(body) resp.status_code = 200 return resp except Exception as ex: body = { 'meta_data': { 'message' : str(ex) } } resp = jsonify(body) resp.status_code = 400 return resp @app.route('/projects/<project_id>/reports/<path:path>') @app.route("/allure-docker-service/projects/<project_id>/reports/<path:path>") @jwt_required def get_reports_endpoint(project_id, path): try: project_path = '{}/reports/{}'.format(project_id, path) return send_from_directory(PROJECTS_DIRECTORY, project_path) except Exception: if request.args.get('redirect') == 'false': return send_from_directory(PROJECTS_DIRECTORY, project_path) return redirect(url_for('get_project_endpoint', project_id=project_id, _external=True)) def validate_files_array(files): if not files: raise Exception("'files[]' array is empty") return files def validate_json_results(results): if isinstance(results, list) is False: raise Exception("'results' should be an array") if not results: raise Exception("'results' array is empty") map_results = {} for result in results: if 'file_name' not in result or not result['file_name'].strip(): raise Exception("'file_name' attribute is required for all results") file_name = result.get('file_name') map_results[file_name] = '' if len(results) != len(map_results): raise Exception("Duplicated file names in 'results'") validated_results = [] for result in results: file_name = result.get('file_name') validated_result = {} validated_result['file_name'] = file_name if 'content_base64' not in result or not result['content_base64'].strip(): raise Exception("'content_base64' attribute is required for '{}' file" .format(file_name)) content_base64 = result.get('content_base64') try: validated_result['content_base64'] = base64.b64decode(content_base64) except Exception as ex: raise Exception( "'content_base64' attribute content for '{}' file should be encoded to base64" .format(file_name), ex) validated_results.append(validated_result) return validated_results def send_files_results(results_project, validated_results, processed_files, failed_files): for file in validated_results: try: file_name = secure_filename(file.filename) file.save("{}/{}".format(results_project, file_name)) except Exception as ex: error = {} error['message'] = str(ex) error['file_name'] = file_name failed_files.append(error) else: processed_files.append(file_name) def send_json_results(results_project, validated_results, processed_files, failed_files): for result in validated_results: file_name = secure_filename(result.get('file_name')) content_base64 = result.get('content_base64') file = None try: file = open("%s/%s" % (results_project, file_name), "wb") file.write(content_base64) except Exception as ex: error = {} error['message'] = str(ex) error['file_name'] = file_name failed_files.append(error) else: processed_files.append(file_name) finally: if file is not None: file.close() def create_project(json_body): if 'id' not in json_body: raise Exception("'id' is required in the body") if isinstance(json_body['id'], str) is False: raise Exception("'id' should be string") if not json_body['id'].strip(): raise Exception("'id' should not be empty") if len(json_body['id']) > 100: raise Exception("'id' should not contains more than 100 characters.") project_id_pattern = re.compile('^[a-z\\d]([a-z\\d -]*[a-z\\d])?$') match = project_id_pattern.match(json_body['id']) if match is None: raise Exception("'id' should contains alphanumeric lowercase characters or hyphens. For example: 'my-project-id'") #pylint: disable=line-too-long project_id = json_body['id'] if is_existent_project(project_id) is True: raise Exception("project_id '{}' is existent".format(project_id)) if project_id == 'default': raise Exception("The id 'default' is not allowed. Try with another project_id") project_path = get_project_path(project_id) latest_report_project = '{}/reports/latest'.format(project_path) results_project = '{}/results'.format(project_path) if not os.path.exists(latest_report_project): os.makedirs(latest_report_project) if not os.path.exists(results_project): os.makedirs(results_project) return project_id def is_existent_project(project_id): if not project_id.strip(): return False return os.path.isdir(get_project_path(project_id)) def get_projects(projects_dirs): projects = {} for project_name in projects_dirs: is_dir = os.path.isdir('{}/{}'.format(PROJECTS_DIRECTORY, project_name)) if is_dir is True: project = {} project['uri'] = url_for('get_project_endpoint', project_id=project_name, _external=True) projects[project_name] = project return projects def get_projects_filtered_by_id(project_id, projects): filtered_projects = [] for project_name in projects: if project_id in project_name: filtered_projects.append(project_name) return filtered_projects def get_project_path(project_id): return '{}/{}'.format(PROJECTS_DIRECTORY, project_id) def resolve_project(project_id_param): project_id = 'default' if project_id_param is not None: project_id = project_id_param return project_id def check_admin_access(user): if ENABLE_SECURITY_LOGIN is False: return True return check_access(ADMIN_ROLE_NAME, user) def check_access(role, user): if user.roles is None: return False if role in user.roles: return True return False def check_process(process_file, project_id): tmp = os.popen('ps -Af | grep -w {}'.format(project_id)).read() proccount = tmp.count(process_file) if proccount > 0: raise Exception("Processing files for project_id '{}'. Try later!".format(project_id)) if __name__ == '__main__': if DEV_MODE == 1: LOGGER.info('Starting in DEV_MODE') app.run(host=HOST, port=PORT) else: waitress.serve(app, threads=THREADS, host=HOST, port=PORT, url_scheme=URL_SCHEME, url_prefix=URL_PREFIX)
# -*- coding: utf-8 -*- __author__ = """J.R. Powers-Luhn""" __email__ = '[email protected]' __version__ = '0.1.1'
# String Formatting # String formatting is how we can use variables (which store information including numbers, strings, and other types of data) inside of strings # We can do this by using the .format() string method. # Here's how it works: # First, we'll need a variable: name = "Shannon" # Now, let's insert it into the print statement: print("My name is {0}".format(name)) # This will print "My name is Shannon" # We'll analyze each part of the syntax in a moment. For now, why is this preferable to doing a print "My name is Shannon"? # Using .format() is more flexible and allows your strings to change as your variables change. # So let's give the name variable a new value. name = "Pumpkin" # Now, let's print it again print("My name is {0}".format(name)) # This will print "My name is Pumpkin" # Remember that Python runs commands from top to bottom, left to right. # The two new parts of this print statement are the {0} and the .format(name) # The {0} is a placeholder for the 0th variable in the list that appears inside the parentheses of .format() -- remember Python starts counting at 0, not 1 # So it really just keeps the spot warm. # To see why it's {0}, let's define a few more variables. age = 100 location = "The Pumpkin Patch" # Now if we want to include those variables, we'll need to put placeholders in the string as well. print("My name is {0} and my age is {1} and I live in {2}".format(name, age, location)) # Note how we put the placeholders exactly in the string where we want them; and the variables go inside the parentheses of the .format() # Remember how Python counts. # So {0} is a placeholder for name; # {1} is a placeholder for age; # and {2} is a placeholder for location # If we had more variables to include, we'd continue in the same way. # But there's more than one way to do this: print("My name is {name} and my age is {age} and I live in {location}".format(name=name, age=age, location=location)) # This way feels more explicit # Only some of the ways string formatting is used are covered here. If you'd like to continue to learn all of the ways to use it: # This is a great guide for lots of different string formatting options: http://ebeab.com/2012/10/10/python-string-format/
import React from 'react'; import PropTypes from 'prop-types'; import Button from '@material-ui/core/Button'; import { makeStyles } from '@material-ui/core/styles'; import HotTub from '@material-ui/icons/HotTub'; import History from '@material-ui/icons/History'; import classnames from 'classnames'; import { useTranslate, Authenticated } from 'ra-core'; import Title from './Title'; const useStyles = makeStyles( theme => ({ container: { display: 'flex', flexDirection: 'column', justifyContent: 'center', [theme.breakpoints.up('md')]: { height: '100%', }, [theme.breakpoints.down('sm')]: { height: '100vh', marginTop: '-3em', }, }, icon: { width: '9em', height: '9em', }, message: { textAlign: 'center', fontFamily: 'Roboto, sans-serif', opacity: 0.5, margin: '0 1em', }, toolbar: { textAlign: 'center', marginTop: '2em', }, }), { name: 'RaNotFound' } ); function goBack() { window.history.go(-1); } const NotFound = ({ className, classes: classesOverride, title, location, ...rest }) => { const classes = useStyles({ classes: classesOverride }); const translate = useTranslate(); return ( <Authenticated location={location}> <div className={classnames(classes.container, className)} {...rest}> <Title defaultTitle={title} /> <div className={classes.message}> <HotTub className={classes.icon} /> <h1>{translate('ra.page.not_found')}</h1> <div>{translate('ra.message.not_found')}.</div> </div> <div className={classes.toolbar}> <Button variant="contained" icon={<History />} onClick={goBack} > {translate('ra.action.back')} </Button> </div> </div> </Authenticated> ); }; NotFound.propTypes = { className: PropTypes.string, classes: PropTypes.object, title: PropTypes.string, location: PropTypes.object, }; export default NotFound;
// COPYRIGHT ยฉ 201 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: [email protected] // // See http://js.arcgis.com/3.34/esri/copyright.txt for details. define(["dojo/_base/declare","dojo/_base/lang","dojo/_base/array","dojo/Evented","./when","dojo/store/util/QueryResults","dojo/store/util/SimpleQueryEngine","dstore/QueryResults"],(function(t,e,n,i,r,s,o,d){var h=function(t,e){this.storage=t,this.data=e};return h.prototype={storage:null,data:null,filter:function(t){return this.storage._filter(this.data,t)},sort:function(t,e){return this.storage._sort(this.data,t,e)},fetch:function(){return this.storage._fetchRange(this.data)},fetchRange:function(t){return this.storage._fetchRange(this.data,t)},mayHaveChildren:function(t){return this.storage.mayHaveChildren(t)},getChildren:function(t){return this.storage.getChildren(t,{returnCollection:!0})}},t(i,{idProperty:"id",bindingProperty:null,autoIdentify:!0,queryEngine:o,isDstoreTree:!1,root:null,data:null,_hash:null,_autoId:null,storage:null,constructor:function(t,n){e.mixin(this,n),this.storage=this,this.root={children:t||[]},e.mixin(this._provideBinding(this.root),{deepness:-1,selectCount:0,leafCount:0}),this._hash={},this.idProperty&&this.autoIdentify&&(this._autoId=1),this._initializeNode(this.root,0),this.data=this.root.children},_provideBinding:function(t){var e=this._getBinding(t);return e||(t[this.bindingProperty]=e={}),e},_getBinding:function(t){return this.bindingProperty?t[this.bindingProperty]:t},_initializeNode:function(t,e){var i=this._provideBinding(t);if(i.selected=!!i.selected,!t.children)return"number"!=typeof i.leafCount&&(i.leafCount=1),void(i.selectCount=i.selected?i.leafCount:0);i.selectCount=0,i.leafCount=0,n.forEach(t.children,(function(n){this._registerNode(n);var r=this._provideBinding(n);r.parent=t,r.deepness=e,this._initializeNode(n,e+1),i.selectCount+=r.selectCount,i.leafCount+=r.leafCount}),this),i.selectCount?i.selectCount===i.leafCount&&(i.selected=!0):i.selected=!1},isOwned:function(t,e){return!e&&t===this.root||this.get(this.getIdentity(t))===t},_registerNode:function(t){this._autoId&&void 0===t[this.idProperty]&&(t[this.idProperty]=this._autoId++),this.idProperty&&(this._hash[t[this.idProperty]]=t)},_unregisterNode:function(t){this.isOwned(t,!0)&&delete this._hash[t[this.idProperty]]},clear:function(){this.root.children.length&&(n.forEach(this.root.children,(function(t){this._unbindNode(t)}),this),this.data=this.root.children=[])},destroy:function(){this.clear()},_unbindNode:function(t){t.children&&n.forEach(t.children,(function(t){delete this._getBinding(t).parent,this._unbindNode(t)}),this),this._unregisterNode(t);var e=this._getBinding(t);e.parent&&(this._incrementCounts(e.parent,-e.selectCount,-e.leafCount),delete e.parent),e!==t&&delete t[this.bindingProperty]},removeNodes:function(t,e){n.forEach(t&&t.slice(),(function(t){if(this.isOwned(t,!0)){var e=this._getBinding(t).parent,i=n.indexOf(e.children,t);i>=0&&e.children.splice(i,1),this._unbindNode(t)}}),this),!e&&this.emit("updated")},addNodes:function(t,e,i){if(e){if(!this.isOwned(e)||!e.children)return!1}else e=this.root;var r=this._getBinding(e).deepness+1,s=0,o=0;return n.forEach(t,(function(t){if(!this.isOwned(t)){e.children.push(t),this._registerNode(t);var n=this._provideBinding(t);n.parent=e,n.deepness=r,this._initializeNode(t,r+1),s+=n.selectCount,o+=n.leafCount}}),this),this._incrementCounts(e,s,o),!i&&this.emit("updated"),!0},select:function(t,e){return this.changeSelect(t,!0,e)},deselect:function(t){this.changeSelect(t,!1)},changeSelect:function(t,e,i){i=i||this.root.leafCount;var r=t&&this._getBinding(t);if(r){var s=((e=!!e)?r.leafCount:0)-r.selectCount,o=s<0||this.root.selectCount+s<=i;return t.children?(o&&(r.selected=e),n.forEach(t.children,(function(t){this.changeSelect(t,e,i)}),this),o):(o&&(r.selected=e,s&&this._incrementCounts(t,s)),o)}},_incrementCounts:function(t,e,n){var i=this._getBinding(t);i.selectCount+=e,n&&(i.leafCount+=n),i.selectCount?i.selectCount==i.leafCount&&(i.selected=!0):i.selected=!1,i.parent&&this._incrementCounts(i.parent,e,n)},getSelectionState:function(t){if(!this.isOwned(t))return!1;var e=this._getBinding(t);return e.selectCount&&e.selectCount!=e.leafCount?"mixed":e.selected=!!e.selectCount},getSelectedNodes:function(t){return this.getDescendingNodes(this.root,!0,t)},getDescendingNodes:function(t,e,n){if(!this.isOwned(t))return[];var i=[];return this._collectNodes(t.children,i,e,n),i},_collectNodes:function(t,e,i,r){n.forEach(t,(function(t){var n=this._getBinding(t),s=null==i?n.leafCount:i?n.selectCount:n.leafCount-n.selectCount;s&&(!t.children||!r&&s==n.leafCount?e.push(t):this._collectNodes(t.children,e,i,r))}),this)},inspectChildren:function(t,i,r,s){s&&(i=e.hitch(s,i));var o=(t=t||this.root).children;return o&&r&&(o=o.slice()).sort(r),n.every(o,(function(t){var e=i(t);return null!==e&&(!1===e||!t.children||this.inspectChildren(t,i,r))}),this)},updateExpandedNodes:function(t,e){for(var n in this._hash){var i=this._hash[n];this.updateExpand(i,!!t[n])}this._updateOddEven(null,e)},updateExpand:function(t,e,n,i){if(t){var r=!1;if(t.children){var s=this._getBinding(t);s.expanded!==e&&(r=!0,s.expanded=e)}var o={};return r&&n&&this._updateOddEven(o,i),o}},_updateOddEven:function(t,e){var n=1;this.inspectChildren(null,(function(e){!1!==e.visible&&(n=1-n);var i=this._getBinding(e);return t&&i.isOdd!==n&&(t[this.getIdentity(e)]=n),i.isOdd=n,!(!e.children||!i.expanded)}),e,this)},isOdd:function(t){var e=this._getBinding(t);return e&&e.isOdd},get:function(t){return this._hash[t]},getIdentity:function(t){return this.idProperty?t[this.idProperty]:null},query:function(t,e){return s(this._query(this.data,t,e))},_query:function(t,e,n){return this.queryEngine(e,n)(t)},filter:function(t){return this._filter(this.data,t)},_filter:function(t,e){var n=this._query(t,e);return new h(this.storage,n)},sort:function(t,e){return this._sort(this.data,t,e)},_sort:function(t,e,n){var i,r;"function"==typeof e?(i=t.slice()).sort(e):(r=Array.isArray(e)?e.map((function(t){return{attribute:t.property,descending:t.descending}})):[{attribute:e,descending:n}],i=this._query(t,{},{sort:r}));return new h(this.storage,i)},mayHaveChildren:function(t){return!!t.children},getChildren:function(t,e){var n=this.isOwned(t,!0)?t.children:null,i=this.isDstoreTree||e&&e.returnCollection,r=this.queryEngine({},i?null:e)(n||[]);return i?new h(this.storage,r):s(r)},fetch:function(){return this._fetchRange(this.data)},fetchRange:function(t){return this._fetchRange(this.data,t)},_fetchRange:function(t,e){return d(r(e?t.slice(e.start,e.end):t.slice()),{totalLength:r(t.length)})}})}));
# # Created on March 2022 # # Copyright (c) 2022 Meitar Ronen # import os import torch import torch.nn as nn import argparse from src import datasets from tqdm import tqdm from src.get_embbedings.imagenet import ImageNetSubset, ImageNet data_to_class_dict = { "MNIST": datasets.MNIST, "MNIST_TEST": datasets.MNIST_TEST, "CIFAR10": datasets.CIFAR10, "CIFAR100-20": datasets.CIFAR100_20, "CIFAR20": datasets.CIFAR100_20, "STL10": datasets.STL10, "STL10_unlabeled_train": datasets.STL10, "imagenet_50": ImageNetSubset(subset_file="./src/get_embbedings/imagenet_subsets/imagenet_50.txt"), "imagenet_50_test": ImageNetSubset(subset_file="./src/get_embbedings/imagenet_subsets/imagenet_50.txt", split='test'), "imagenet": ImageNet() } def parse_args(): parser = argparse.ArgumentParser() # Dataset parameters parser.add_argument("--dir", default="/path/to/Datasets", help="datasets directory") parser.add_argument("--dataset", default="mnist", help="current dataset") # Pretrained weights parameters parser.add_argument("--pretrain_path", default='/path/to/pretrained/weights.pth.tar', help="pretrained weights path") # Feature extraction parameters parser.add_argument("--batch_size", type=int, default=128) parser.add_argument("--feature_extractor", type=str, default="simclr", choices=["simclr", "moco", "scan_simclr"]) parser.add_argument("--outdir", type=str, default='./embeddings_results', help="location to save the pretrained embeddings") parser.add_argument("--features_dim", type=int, default=128, help="The resulting embbedings dim") args = parser.parse_args() return args def load_feature_extractor(args): # Load backbofne if "simclr" in args.feature_extractor: from models.resnet_cifar import resnet18 backbone = resnet18() elif "moco" in args.feature_extractor: from models.resnet import resnet50 backbone = resnet50() # Load model and pretrained weights if args.feature_extractor in ('simclr', 'moco'): from models.models import ContrastiveModel model = ContrastiveModel(backbone) state = torch.load(args.pretrain_path, map_location='cpu') if args.feature_extractor == "moco": new_state_dict = {} state = state['state_dict'] for k in list(state.keys()): # Copy backbone weights if k.startswith('module.encoder_q') and not k.startswith('module.encoder_q.fc'): new_k = 'backbone.' + k[len('module.encoder_q.'):] new_state_dict[new_k] = state[k] # Copy mlp weights elif k.startswith('module.encoder_q.fc'): new_k = 'contrastive_head.' + k[len('module.encoder_q.fc.'):] new_state_dict[new_k] = state[k] else: raise ValueError('Unexpected key {}'.format(k)) state = new_state_dict missing = model.load_state_dict(state, strict=False) print("Finished loading weights.") print(f"Mismatched keys: {missing}") return model def load_data(args): if "imagenet" in args.dataset: train_loader = data_to_class_dict[args.dataset].get_loader() test_loader = data_to_class_dict[args.dataset+"_test"].get_loader() else: if "unlabeled_train" in args.dataset: dataset = data_to_class_dict[args.dataset](args, split="train+unlabeled") else: dataset = data_to_class_dict[args.dataset](args) train_loader, test_loader = dataset.get_loaders() return train_loader, test_loader def extract_features(args, model, train_loader, test_loader): model.eval() device = torch.device("cuda" if torch.cuda.is_available() and args.gpus is not None else "cpu") model.to(device=device) train_codes, train_labels = [], [] test_codes, test_labels = [], [] for i, data in enumerate(tqdm(train_loader)): with torch.no_grad(): inputs, labels = data[0].to(device), data[1].to(device) codes = model(inputs) train_codes.append(codes.view(codes.shape[0], -1)) train_labels.append(labels) train_codes = torch.cat(train_codes).cpu() train_labels = torch.cat(train_labels).cpu() D = train_codes.shape[1] # if path does not exist, create it save_location = os.path.join(args.outdir, args.feature_extractor.upper(), args.dataset.upper()+ f"_{D}D") from pathlib import Path Path(save_location).mkdir(parents=True, exist_ok=True) print("Saving train embeddings...") print(f"train codes dims = {train_codes.shape}") D = train_codes.shape[1] # if path does not exist, create it save_location = os.path.join(args.outdir, args.feature_extractor.upper(), args.dataset.upper()+ f"_{D}D") from pathlib import Path Path(save_location).mkdir(parents=True, exist_ok=True) torch.save(train_codes, os.path.join(save_location, "train_codes.pt")) torch.save(train_labels, os.path.join(save_location, "train_labels.pt")) print("Saved train embeddings!") del train_codes, train_labels for i, data in enumerate(tqdm(test_loader)): with torch.no_grad(): inputs, labels = data[0].to(device), data[1].to(device) codes = model(inputs) test_codes.append(codes.view(codes.shape[0], -1)) test_labels.append(labels) test_codes = torch.cat(test_codes).cpu() test_labels = torch.cat(test_labels).cpu() print("Saving test embeddings...") print(f"test codes dims = {test_codes.shape}") torch.save(test_codes, os.path.join(save_location, "test_codes.pt")) torch.save(test_labels, os.path.join(save_location, "test_labels.pt")) print("Saved test embeddings!") def main(): args = parse_args() model = load_feature_extractor(args) train_loader, test_loader = load_data(args) extract_features(args, model, train_loader, test_loader) if __name__ == "__main__": main()
var searchData= [ ['y',['Y',['../class_bone_orientations_constraint.html#a1f4aa21ffa8dbc27a16143698d71e63da57cec4137b614c87cb4e24a3d003a3e0',1,'BoneOrientationsConstraint']]] ];
from . import rnn # noqa: F401 from .clip_grad import clip_grad_norm, clip_grad_norm_, clip_grad_value_ # noqa: F401 from .weight_norm import weight_norm, remove_weight_norm # noqa: F401 from .convert_parameters import parameters_to_vector, vector_to_parameters # noqa: F401 from .spectral_norm import spectral_norm, remove_spectral_norm # noqa: F401 from .fusion import fuse_conv_bn_eval, fuse_conv_bn_weights # noqa: F401
/*! * The MIT License * * Copyright (c) 2018-present Liquid Carrot Corporation <[email protected]> https://liquidcarrot.io. * * Copyright for portions of Carrot are held by the following parties as a part of project Carrot: * - Copyright 2017 Thomas Wagenaar <[email protected]> * - Copyright 2017 Juan Cazala - cazala.com * * 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. */ !function(t,n){"object"==typeof exports&&"object"==typeof module?module.exports=n(require("child_process"),require("os")):"function"==typeof define&&define.amd?define(["child_process","os"],n):"object"==typeof exports?exports.carrot=n(require("child_process"),require("os")):t.carrot=n(t.child_process,t.os)}(window,function(t,n){return function(t){var n={};function e(o){if(n[o])return n[o].exports;var i=n[o]={i:o,l:!1,exports:{}};return t[o].call(i.exports,i,i.exports,e),i.l=!0,i.exports}return e.m=t,e.c=n,e.d=function(t,n,o){e.o(t,n)||Object.defineProperty(t,n,{enumerable:!0,get:o})},e.r=function(t){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})},e.t=function(t,n){if(1&n&&(t=e(t)),8&n)return t;if(4&n&&"object"==typeof t&&t&&t.__esModule)return t;var o=Object.create(null);if(e.r(o),Object.defineProperty(o,"default",{enumerable:!0,value:t}),2&n&&"string"!=typeof t)for(var i in t)e.d(o,i,function(n){return t[n]}.bind(null,i));return o},e.n=function(t){var n=t&&t.__esModule?function(){return t.default}:function(){return t};return e.d(n,"a",n),n},e.o=function(t,n){return Object.prototype.hasOwnProperty.call(t,n)},e.p="",e(e.s=9)}([function(t,n,e){var o={activation:e(8),mutation:e(10),selection:e(11),crossover:e(12),cost:e(13),gating:e(14),connection:e(15),rate:e(16)};t.exports=o},function(t,n){t.exports={warnings:!1}},function(t,n,e){var o=e(0),i=e(3),s=e(1);function r(t){this.bias="input"===t?0:.2*Math.random()-.1,this.squash=o.activation.LOGISTIC,this.type=t||"hidden",this.activation=0,this.state=0,this.old=0,this.mask=1,this.previousDeltaBias=0,this.totalDeltaBias=0,this.connections={in:[],out:[],gated:[],self:new i(this,this,0)},this.error={responsibility:0,projected:0,gated:0}}r.prototype={activate:function(t){if(void 0!==t)return this.activation=t,this.activation;var n;for(this.old=this.state,this.state=this.connections.self.gain*this.connections.self.weight*this.state+this.bias,n=0;n<this.connections.in.length;n++){var e=this.connections.in[n];this.state+=e.from.activation*e.weight*e.gain}this.activation=this.squash(this.state)*this.mask,this.derivative=this.squash(this.state,!0);var o=[],i=[];for(n=0;n<this.connections.gated.length;n++){let t=this.connections.gated[n],e=t.to,s=o.indexOf(e);s>-1?i[s]+=t.weight*t.from.activation:(o.push(e),i.push(t.weight*t.from.activation+(e.connections.self.gater===this?e.old:0))),t.gain=this.activation}for(n=0;n<this.connections.in.length;n++){let t=this.connections.in[n];t.elegibility=this.connections.self.gain*this.connections.self.weight*t.elegibility+t.from.activation*t.gain;for(var s=0;s<o.length;s++){let n=o[s],e=i[s],r=t.xtrace.nodes.indexOf(n);r>-1?t.xtrace.values[r]=n.connections.self.gain*n.connections.self.weight*t.xtrace.values[r]+this.derivative*t.elegibility*e:(t.xtrace.nodes.push(n),t.xtrace.values.push(this.derivative*t.elegibility*e))}}return this.activation},noTraceActivate:function(t){if(void 0!==t)return this.activation=t,this.activation;var n;for(this.state=this.connections.self.gain*this.connections.self.weight*this.state+this.bias,n=0;n<this.connections.in.length;n++){var e=this.connections.in[n];this.state+=e.from.activation*e.weight*e.gain}for(this.activation=this.squash(this.state),n=0;n<this.connections.gated.length;n++)this.connections.gated[n].gain=this.activation;return this.activation},propagate:function(t,n,e,o){n=n||0,t=t||.3;var i=0;if("output"===this.type)this.error.responsibility=this.error.projected=o-this.activation;else{var s;for(s=0;s<this.connections.out.length;s++){let t=this.connections.out[s];i+=t.to.error.responsibility*t.weight*t.gain}for(this.error.projected=this.derivative*i,i=0,s=0;s<this.connections.gated.length;s++){let t=this.connections.gated[s],n=t.to,e=n.connections.self.gater===this?n.old:0;e+=t.weight*t.from.activation,i+=n.error.responsibility*e}this.error.gated=this.derivative*i,this.error.responsibility=this.error.projected+this.error.gated}if("constant"!==this.type){for(s=0;s<this.connections.in.length;s++){let o=this.connections.in[s],i=this.error.projected*o.elegibility;for(var r=0;r<o.xtrace.nodes.length;r++){let t=o.xtrace.nodes[r],n=o.xtrace.values[r];i+=t.error.responsibility*n}let a=t*i*this.mask;o.totalDeltaWeight+=a,e&&(o.totalDeltaWeight+=n*o.previousDeltaWeight,o.weight+=o.totalDeltaWeight,o.previousDeltaWeight=o.totalDeltaWeight,o.totalDeltaWeight=0)}var a=t*this.error.responsibility;this.totalDeltaBias+=a,e&&(this.totalDeltaBias+=n*this.previousDeltaBias,this.bias+=this.totalDeltaBias,this.previousDeltaBias=this.totalDeltaBias,this.totalDeltaBias=0)}},connect:function(t,n){var e=[];if(void 0!==t.bias)if(t===this)0!==this.connections.self.weight?s.warnings&&console.warn("This connection already exists!"):this.connections.self.weight=n||1,e.push(this.connections.self);else{if(this.isProjectingTo(t))throw new Error("Already projecting a connection to this node!");{let o=new i(this,t,n);t.connections.in.push(o),this.connections.out.push(o),e.push(o)}}else for(var o=0;o<t.nodes.length;o++){let s=new i(this,t.nodes[o],n);t.nodes[o].connections.in.push(s),this.connections.out.push(s),t.connections.in.push(s),e.push(s)}return e},disconnect:function(t,n){if(this!==t){for(var e=0;e<this.connections.out.length;e++){let n=this.connections.out[e];if(n.to===t){this.connections.out.splice(e,1);let t=n.to.connections.in.indexOf(n);n.to.connections.in.splice(t,1),null!==n.gater&&n.gater.ungate(n);break}}n&&t.disconnect(this)}else this.connections.self.weight=0},gate:function(t){Array.isArray(t)||(t=[t]);for(var n=0;n<t.length;n++){var e=t[n];this.connections.gated.push(e),e.gater=this}},ungate:function(t){Array.isArray(t)||(t=[t]);for(var n=t.length-1;n>=0;n--){var e=t[n],o=this.connections.gated.indexOf(e);this.connections.gated.splice(o,1),e.gater=null,e.gain=1}},clear:function(){for(var t=0;t<this.connections.in.length;t++){var n=this.connections.in[t];n.elegibility=0,n.xtrace={nodes:[],values:[]}}for(t=0;t<this.connections.gated.length;t++){this.connections.gated[t].gain=0}this.error.responsibility=this.error.projected=this.error.gated=0,this.old=this.state=this.activation=0},mutate:function(t){if(void 0===t)throw new Error("No mutate method given!");if(!(t.name in o.mutation))throw new Error("This method does not exist!");switch(t){case o.mutation.MOD_ACTIVATION:var n=t.allowed[(t.allowed.indexOf(this.squash)+Math.floor(Math.random()*(t.allowed.length-1))+1)%t.allowed.length];this.squash=n;break;case o.mutation.MOD_BIAS:var e=Math.random()*(t.max-t.min)+t.min;this.bias+=e}},isProjectingTo:function(t){if(t===this&&0!==this.connections.self.weight)return!0;for(var n=0;n<this.connections.out.length;n++){if(this.connections.out[n].to===t)return!0}return!1},isProjectedBy:function(t){if(t===this&&0!==this.connections.self.weight)return!0;for(var n=0;n<this.connections.in.length;n++){if(this.connections.in[n].from===t)return!0}return!1},toJSON:function(){return{bias:this.bias,type:this.type,squash:this.squash.name,mask:this.mask}}},r.fromJSON=function(t){var n=new r;return n.bias=t.bias,n.type=t.type,n.mask=t.mask,n.squash=o.activation[t.squash],n},t.exports=r},function(t,n){function e(t,n,e){this.from=t,this.to=n,this.gain=1,this.weight=void 0===e?.2*Math.random()-.1:e,this.gater=null,this.elegibility=0,this.previousDeltaWeight=0,this.totalDeltaWeight=0,this.xtrace={nodes:[],values:[]}}e.prototype={toJSON:function(){return{weight:this.weight}}},e.innovationID=function(t,n){return.5*(t+n)*(t+n+1)+n},t.exports=e},function(t,n,e){var o=e(5),i=e(0),s=e(3),r=e(1),a=e(2),h=i.mutation;function c(t,n){if(void 0===t||void 0===n)throw new Error("No input or output size given");var e;for(this.input=t,this.output=n,this.nodes=[],this.connections=[],this.gates=[],this.selfconns=[],this.dropout=0,e=0;e<this.input+this.output;e++){var o=e<this.input?"input":"output";this.nodes.push(new a(o))}for(e=0;e<this.input;e++)for(var i=this.input;i<this.output+this.input;i++){var s=Math.random()*this.input*Math.sqrt(2/this.input);this.connect(this.nodes[e],this.nodes[i],s)}}c.prototype={activate:function(t,n){for(var e=[],o=0;o<this.nodes.length;o++)if("input"===this.nodes[o].type)this.nodes[o].activate(t[o]);else if("output"===this.nodes[o].type){var i=this.nodes[o].activate();e.push(i)}else n&&(this.nodes[o].mask=Math.random()<this.dropout?0:1),this.nodes[o].activate();return e},noTraceActivate:function(t){for(var n=[],e=0;e<this.nodes.length;e++)if("input"===this.nodes[e].type)this.nodes[e].noTraceActivate(t[e]);else if("output"===this.nodes[e].type){var o=this.nodes[e].noTraceActivate();n.push(o)}else this.nodes[e].noTraceActivate();return n},propagate:function(t,n,e,o){if(void 0===o||o.length!==this.output)throw new Error("Output target length should match network output length");var i,s=o.length;for(i=this.nodes.length-1;i>=this.nodes.length-this.output;i--)this.nodes[i].propagate(t,n,e,o[--s]);for(i=this.nodes.length-this.output-1;i>=this.input;i--)this.nodes[i].propagate(t,n,e)},clear:function(){for(var t=0;t<this.nodes.length;t++)this.nodes[t].clear()},connect:function(t,n,e){for(var o=t.connect(n,e),i=0;i<o.length;i++){var s=o[i];t!==n?this.connections.push(s):this.selfconns.push(s)}return o},disconnect:function(t,n){for(var e=t===n?this.selfconns:this.connections,o=0;o<e.length;o++){var i=e[o];if(i.from===t&&i.to===n){null!==i.gater&&this.ungate(i),e.splice(o,1);break}}t.disconnect(n)},gate:function(t,n){if(-1===this.nodes.indexOf(t))throw new Error("This node is not part of the network!");null==n.gater?(t.gate(n),this.gates.push(n)):r.warnings&&console.warn("This connection is already gated!")},ungate:function(t){var n=this.gates.indexOf(t);if(-1===n)throw new Error("This connection is not gated!");this.gates.splice(n,1),t.gater.ungate(t)},remove:function(t){var n=this.nodes.indexOf(t);if(-1===n)throw new Error("This node does not exist in the network!");var e=[];this.disconnect(t,t);for(var o=[],i=t.connections.in.length-1;i>=0;i--){let n=t.connections.in[i];h.SUB_NODE.keep_gates&&null!==n.gater&&n.gater!==t&&e.push(n.gater),o.push(n.from),this.disconnect(n.from,t)}var s=[];for(i=t.connections.out.length-1;i>=0;i--){let n=t.connections.out[i];h.SUB_NODE.keep_gates&&null!==n.gater&&n.gater!==t&&e.push(n.gater),s.push(n.to),this.disconnect(t,n.to)}var r=[];for(i=0;i<o.length;i++){let t=o[i];for(var a=0;a<s.length;a++){let n=s[a];if(!t.isProjectingTo(n)){var c=this.connect(t,n);r.push(c[0])}}}for(i=0;i<e.length&&0!==r.length;i++){let t=e[i],n=Math.floor(Math.random()*r.length);this.gate(t,r[n]),r.splice(n,1)}for(i=t.connections.gated.length-1;i>=0;i--){let n=t.connections.gated[i];this.ungate(n)}this.disconnect(t,t),this.nodes.splice(n,1)},getPossibleMutations:function(t){for(var n,e,o=[],i=0;i<t.length;i++){var s=t[i];switch(s){case h.SUB_NODE:if(this.nodes.length===this.input+this.output)continue;break;case h.ADD_CONN:var r=[];for(n=0;n<this.nodes.length-this.output;n++){let t=this.nodes[n];for(e=Math.max(n+1,this.input);e<this.nodes.length;e++){let n=this.nodes[e];t.isProjectingTo(n)||r.push([t,n])}}if(0===r.length)continue;break;case h.SUB_CONN:var a=[];for(n=0;n<this.connections.length;n++){let t=this.connections[n];t.from.connections.out.length>1&&t.to.connections.in.length>1&&this.nodes.indexOf(t.to)>this.nodes.indexOf(t.from)&&a.push(t)}if(0===a.length)continue;break;case h.MOD_ACTIVATION:if(!s.mutateOutput&&this.input+this.output===this.nodes.length)continue;break;case h.ADD_SELF_CONN:a=[];for(n=this.input;n<this.nodes.length;n++){let t=this.nodes[n];0===t.connections.self.weight&&a.push(t)}if(0===a.length)continue;break;case h.SUB_SELF_CONN:if(0===this.selfconns.length)continue;break;case h.ADD_GATE:var c=this.connections.concat(this.selfconns);a=[];for(n=0;n<c.length;n++){let t=c[n];null===t.gater&&a.push(t)}if(0===a.length)continue;break;case h.SUB_GATE:if(0===this.gates.length)continue;break;case h.ADD_BACK_CONN:r=[];for(n=this.input;n<this.nodes.length;n++){let t=this.nodes[n];for(e=this.input;e<n;e++){let n=this.nodes[e];t.isProjectingTo(n)||r.push([t,n])}}if(0===r.length)continue;break;case h.SUB_BACK_CONN:a=[];for(n=0;n<this.connections.length;n++){let t=this.connections[n];t.from.connections.out.length>1&&t.to.connections.in.length>1&&this.nodes.indexOf(t.from)>this.nodes.indexOf(t.to)&&a.push(t)}if(0===a.length)continue;break;case h.SWAP_NODES:if(s.mutateOutput&&this.nodes.length-this.input<2||!s.mutateOutput&&this.nodes.length-this.input-this.output<2)continue}o.push(s)}return o},mutate:function(t){if(void 0===t)throw new Error("No (correct) mutate method given!");var n,e;switch(t){case h.ADD_NODE:var o=(m=this.connections[Math.floor(Math.random()*this.connections.length)]).gater;this.disconnect(m.from,m.to);var i=this.nodes.indexOf(m.to),s=new a("hidden");h.ADD_NODE.randomActivation&&s.mutate(h.MOD_ACTIVATION);var c=Math.min(i,this.nodes.length-this.output);this.nodes.splice(c,0,s);var u=this.connect(m.from,s)[0],l=this.connect(s,m.to)[0];null!=o&&this.gate(o,Math.random()>=.5?u:l);break;case h.SUB_NODE:if(this.nodes.length===this.input+this.output){r.warnings&&console.warn("No more nodes left to remove!");break}var f=Math.floor(Math.random()*(this.nodes.length-this.output-this.input)+this.input);this.remove(this.nodes[f]);break;case h.ADD_CONN:var p=[];for(n=0;n<this.nodes.length-this.output;n++){let t=this.nodes[n];for(e=Math.max(n+1,this.input);e<this.nodes.length;e++){let n=this.nodes[e];t.isProjectingTo(n)||p.push([t,n])}}if(0===p.length){r.warnings&&console.warn("No more connections to be made!");break}var g=p[Math.floor(Math.random()*p.length)];this.connect(g[0],g[1]);break;case h.SUB_CONN:var d=[];for(n=0;n<this.connections.length;n++){let t=this.connections[n];t.from.connections.out.length>1&&t.to.connections.in.length>1&&this.nodes.indexOf(t.to)>this.nodes.indexOf(t.from)&&d.push(t)}if(0===d.length){r.warnings&&console.warn("No connections to remove!");break}var v=d[Math.floor(Math.random()*d.length)];this.disconnect(v.from,v.to);break;case h.MOD_WEIGHT:var m=(A=this.connections.concat(this.selfconns))[Math.floor(Math.random()*A.length)],w=Math.random()*(t.max-t.min)+t.min;m.weight+=w;break;case h.MOD_BIAS:f=Math.floor(Math.random()*(this.nodes.length-this.input)+this.input);(s=this.nodes[f]).mutate(t);break;case h.MOD_ACTIVATION:if(!t.mutateOutput&&this.input+this.output===this.nodes.length){r.warnings&&console.warn("No nodes that allow mutation of activation function");break}f=Math.floor(Math.random()*(this.nodes.length-(t.mutateOutput?0:this.output)-this.input)+this.input);(s=this.nodes[f]).mutate(t);break;case h.ADD_SELF_CONN:d=[];for(n=this.input;n<this.nodes.length;n++){let t=this.nodes[n];0===t.connections.self.weight&&d.push(t)}if(0===d.length){r.warnings&&console.warn("No more self-connections to add!");break}s=d[Math.floor(Math.random()*d.length)];this.connect(s,s);break;case h.SUB_SELF_CONN:if(0===this.selfconns.length){r.warnings&&console.warn("No more self-connections to remove!");break}var O=this.selfconns[Math.floor(Math.random()*this.selfconns.length)];this.disconnect(O.from,O.to);break;case h.ADD_GATE:var A=this.connections.concat(this.selfconns);d=[];for(n=0;n<A.length;n++){let t=A[n];null===t.gater&&d.push(t)}if(0===d.length){r.warnings&&console.warn("No more connections to gate!");break}f=Math.floor(Math.random()*(this.nodes.length-this.input)+this.input),s=this.nodes[f],O=d[Math.floor(Math.random()*d.length)];this.gate(s,O);break;case h.SUB_GATE:if(0===this.gates.length){r.warnings&&console.warn("No more connections to ungate!");break}f=Math.floor(Math.random()*this.gates.length);var N=this.gates[f];this.ungate(N);break;case h.ADD_BACK_CONN:p=[];for(n=this.input;n<this.nodes.length;n++){let t=this.nodes[n];for(e=this.input;e<n;e++){let n=this.nodes[e];t.isProjectingTo(n)||p.push([t,n])}}if(0===p.length){r.warnings&&console.warn("No more connections to be made!");break}g=p[Math.floor(Math.random()*p.length)];this.connect(g[0],g[1]);break;case h.SUB_BACK_CONN:d=[];for(n=0;n<this.connections.length;n++){let t=this.connections[n];t.from.connections.out.length>1&&t.to.connections.in.length>1&&this.nodes.indexOf(t.from)>this.nodes.indexOf(t.to)&&d.push(t)}if(0===d.length){r.warnings&&console.warn("No connections to remove!");break}v=d[Math.floor(Math.random()*d.length)];this.disconnect(v.from,v.to);break;case h.SWAP_NODES:if(t.mutateOutput&&this.nodes.length-this.input<2||!t.mutateOutput&&this.nodes.length-this.input-this.output<2){r.warnings&&console.warn("No nodes that allow swapping of bias and activation function");break}f=Math.floor(Math.random()*(this.nodes.length-(t.mutateOutput?0:this.output)-this.input)+this.input);var _=this.nodes[f];f=Math.floor(Math.random()*(this.nodes.length-(t.mutateOutput?0:this.output)-this.input)+this.input);var T=this.nodes[f],L=_.bias,M=_.squash;_.bias=T.bias,_.squash=T.squash,T.bias=L,T.squash=M}},train:function(t,n){if(t[0].input.length!==this.input||t[0].output.length!==this.output)throw new Error("Dataset input/output size should be same as network input/output size!");void 0===(n=n||{}).rate&&r.warnings&&console.warn("Using default learning rate, please define a rate!"),void 0===n.iterations&&r.warnings&&console.warn("No target iterations given, running until error is reached!");var e=n.error||.05,o=n.cost||i.cost.MSE,s=n.rate||.3,a=n.dropout||0,h=n.momentum||0,c=n.batchSize||1,u=n.ratePolicy||i.rate.FIXED(),l=Date.now();if(c>t.length)throw new Error("Batch size must be smaller or equal to dataset length!");if(void 0===n.iterations&&void 0===n.error)throw new Error("At least one of the following options must be specified: error, iterations");if(void 0===n.error?e=-1:void 0===n.iterations&&(n.iterations=0),this.dropout=a,n.crossValidate){let e=Math.ceil((1-n.crossValidate.testSize)*t.length);var f=t.slice(0,e),p=t.slice(e)}for(var g,d,v,m=s,w=0,O=1;O>e&&(0===n.iterations||w<n.iterations)&&!(n.crossValidate&&O<=n.crossValidate.testError);){if(m=u(s,++w),n.crossValidate?(this._trainSet(f,c,m,h,o),n.clear&&this.clear(),O=this.test(p,o).error,n.clear&&this.clear()):(O=this._trainSet(t,c,m,h,o),n.clear&&this.clear()),n.shuffle)for(g=t.length;g;d=Math.floor(Math.random()*g),v=t[--g],t[g]=t[d],t[d]=v);n.log&&w%n.log==0&&console.log("iteration",w,"error",O,"rate",m),n.schedule&&w%n.schedule.iterations==0&&n.schedule.function({error:O,iteration:w})}if(n.clear&&this.clear(),a)for(g=0;g<this.nodes.length;g++)"hidden"!==this.nodes[g].type&&"constant"!==this.nodes[g].type||(this.nodes[g].mask=1-this.dropout);return{error:O,iterations:w,time:Date.now()-l}},_trainSet:function(t,n,e,o,i){for(var s=0,r=0;r<t.length;r++){var a=t[r].input,h=t[r].output,c=!((r+1)%n!=0&&r+1!==t.length),u=this.activate(a,!0);this.propagate(e,o,c,h),s+=i(h,u)}return s/t.length},test:function(t,n=i.cost.MSE){var e;if(this.dropout)for(e=0;e<this.nodes.length;e++)"hidden"!==this.nodes[e].type&&"constant"!==this.nodes[e].type||(this.nodes[e].mask=1-this.dropout);var o=0,s=Date.now();for(e=0;e<t.length;e++){let i=t[e].input;o+=n(t[e].output,this.noTraceActivate(i))}return{error:o/=t.length,time:Date.now()-s}},graph:function(t,n){var e,o=0,i=0,s={nodes:[],links:[],constraints:[{type:"alignment",axis:"x",offsets:[]},{type:"alignment",axis:"y",offsets:[]}]};for(e=0;e<this.nodes.length;e++){var r=this.nodes[e];"input"===r.type?(1===this.input?s.constraints[0].offsets.push({node:e,offset:0}):s.constraints[0].offsets.push({node:e,offset:.8*t/(this.input-1)*o++}),s.constraints[1].offsets.push({node:e,offset:0})):"output"===r.type&&(1===this.output?s.constraints[0].offsets.push({node:e,offset:0}):s.constraints[0].offsets.push({node:e,offset:.8*t/(this.output-1)*i++}),s.constraints[1].offsets.push({node:e,offset:-.8*n})),s.nodes.push({id:e,name:"hidden"===r.type?r.squash.name:r.type.toUpperCase(),activation:r.activation,bias:r.bias})}var a=this.connections.concat(this.selfconns);for(e=0;e<a.length;e++){var h=a[e];if(null==h.gater)s.links.push({source:this.nodes.indexOf(h.from),target:this.nodes.indexOf(h.to),weight:h.weight});else{var c=s.nodes.length;s.nodes.push({id:c,activation:h.gater.activation,name:"GATE"}),s.links.push({source:this.nodes.indexOf(h.from),target:c,weight:.5*h.weight}),s.links.push({source:c,target:this.nodes.indexOf(h.to),weight:.5*h.weight}),s.links.push({source:this.nodes.indexOf(h.gater),target:c,weight:h.gater.activation,gate:!0})}}return s},toJSON:function(){var t,n={nodes:[],connections:[],input:this.input,output:this.output,dropout:this.dropout};for(t=0;t<this.nodes.length;t++)this.nodes[t].index=t;for(t=0;t<this.nodes.length;t++){let e=this.nodes[t],o=e.toJSON();if(o.index=t,n.nodes.push(o),0!==e.connections.self.weight){let o=e.connections.self.toJSON();o.from=t,o.to=t,o.gater=null!=e.connections.self.gater?e.connections.self.gater.index:null,n.connections.push(o)}}for(t=0;t<this.connections.length;t++){let e=this.connections[t],o=e.toJSON();o.from=e.from.index,o.to=e.to.index,o.gater=null!=e.gater?e.gater.index:null,n.connections.push(o)}return n},set:function(t){for(var n=0;n<this.nodes.length;n++)this.nodes[n].bias=t.bias||this.nodes[n].bias,this.nodes[n].squash=t.squash||this.nodes[n].squash},evolve:async function(t,n){if(t[0].input.length!==this.input||t[0].output.length!==this.output)throw new Error("Dataset input/output size should be same as network input/output size!");let s;void 0===(n=n||{}).iterations&&void 0===n.error?(n.iterations=1e4,s=.05):n.iterations?s=-1:n.error&&(s=n.error,n.iterations=0);var r=void 0!==n.growth?n.growth:1e-4,a=n.cost||i.cost.MSE,h=n.amount||1,c=n.threads;void 0===c&&(c="undefined"==typeof window?e(24).cpus().length:navigator.hardwareConcurrency);var u,f=Date.now();if(1===c)u=function(n){for(var e=0,o=0;o<h;o++)e-=n.test(t,a).error;return e-=(n.nodes.length-n.input-n.output+n.connections.length+n.gates.length)*r,(e=isNaN(e)?-1/0:e)/h};else{var p=o.serializeDataSet(t),g=[];if("undefined"==typeof window)for(var d=0;d<c;d++)g.push(new o.workers.node.TestWorker(p,a));else for(d=0;d<c;d++)g.push(new o.workers.browser.TestWorker(p,a));u=function(t){return new Promise((n,e)=>{for(var o=t.slice(),i=0,s=function(t){if(o.length){var e=o.shift();t.evaluate(e).then(function(n){e.score=-n,e.score-=(e.nodes.length-e.input-e.output+e.connections.length+e.gates.length)*r,e.score=isNaN(parseFloat(n))?-1/0:e.score,s(t)})}else++i===c&&n()},a=0;a<g.length;a++)s(g[a])})},n.fitnessPopulation=!0}n.network=this;for(var v,m=new l(this.input,this.output,u,n),w=-1/0,O=-1/0;w<-s&&(0===n.iterations||m.generation<n.iterations);){let t=await m.evolve(),e=t.score;w=e+(t.nodes.length-t.input-t.output+t.connections.length+t.gates.length)*r,e>O&&(O=e,v=t),n.log&&m.generation%n.log==0&&console.log("iteration",m.generation,"fitness",e,"error",-w),n.schedule&&m.generation%n.schedule.iterations==0&&n.schedule.function({fitness:e,error:-w,iteration:m.generation})}if(c>1)for(d=0;d<g.length;d++)g[d].terminate();return void 0!==v&&(this.nodes=v.nodes,this.connections=v.connections,this.selfconns=v.selfconns,this.gates=v.gates,n.clear&&this.clear()),{error:-w,iterations:m.generation,time:Date.now()-f}},standalone:function(){var t,n=[],e=[],o=[],i=[],s=[];for(t=0;t<this.input;t++){var r=this.nodes[t];e.push(r.activation),o.push(r.state)}for(i.push("for(var i = 0; i < input.length; i++) A[i] = input[i];"),t=0;t<this.nodes.length;t++)this.nodes[t].index=t;for(t=this.input;t<this.nodes.length;t++){let r=this.nodes[t];e.push(r.activation),o.push(r.state);var a=n.indexOf(r.squash.name);-1===a&&(a=n.length,n.push(r.squash.name),s.push(r.squash.toString()));for(var h=[],c=0;c<r.connections.in.length;c++){var u=r.connections.in[c],l=`A[${u.from.index}] * ${u.weight}`;null!=u.gater&&(l+=` * A[${u.gater.index}]`),h.push(l)}if(r.connections.self.weight){let n=r.connections.self,e=`S[${t}] * ${n.weight}`;null!=n.gater&&(e+=` * A[${n.gater.index}]`),h.push(e)}var f=`S[${t}] = ${h.join(" + ")} + ${r.bias};`,p=`A[${t}] = F[${a}](S[${t}])${r.mask?"":" * "+r.mask};`;i.push(f),i.push(p)}var g=[];for(t=this.nodes.length-this.output;t<this.nodes.length;t++)g.push(`A[${t}]`);g=`return [${g.join(",")}];`,i.push(g);var d="";return d+=`var F = [${s.toString()}];\r\n`,d+=`var A = [${e.toString()}];\r\n`,d+=`var S = [${o.toString()}];\r\n`,d+=`function activate(input){\r\n${i.join("\r\n")}\r\n}`},serialize:function(){var t,n=[],e=[],o=[],i=["LOGISTIC","TANH","IDENTITY","STEP","RELU","SOFTSIGN","SINUSOID","GAUSSIAN","BENT_IDENTITY","BIPOLAR","BIPOLAR_SIGMOID","HARD_TANH","ABSOLUTE","INVERSE","SELU"];for(o.push(this.input),o.push(this.output),t=0;t<this.nodes.length;t++){let o=this.nodes[t];o.index=t,n.push(o.activation),e.push(o.state)}for(t=this.input;t<this.nodes.length;t++){let n=this.nodes[t];o.push(n.index),o.push(n.bias),o.push(i.indexOf(n.squash.name)),o.push(n.connections.self.weight),o.push(null==n.connections.self.gater?-1:n.connections.self.gater.index);for(var s=0;s<n.connections.in.length;s++){let t=n.connections.in[s];o.push(t.from.index),o.push(t.weight),o.push(null==t.gater?-1:t.gater.index)}o.push(-2)}return[n,e,o]}},c.fromJSON=function(t){var n,e=new c(t.input,t.output);for(e.dropout=t.dropout,e.nodes=[],e.connections=[],n=0;n<t.nodes.length;n++)e.nodes.push(a.fromJSON(t.nodes[n]));for(n=0;n<t.connections.length;n++){var o=t.connections[n],i=e.connect(e.nodes[o.from],e.nodes[o.to])[0];i.weight=o.weight,null!=o.gater&&e.gate(e.nodes[o.gater],i)}return e},c.merge=function(t,n){if(t=c.fromJSON(t.toJSON()),n=c.fromJSON(n.toJSON()),t.output!==n.input)throw new Error("Output size of network1 should be the same as the input size of network2!");var e;for(e=0;e<n.connections.length;e++){let o=n.connections[e];if("input"===o.from.type){let e=n.nodes.indexOf(o.from);o.from=t.nodes[t.nodes.length-1-e]}}for(e=n.input-1;e>=0;e--)n.nodes.splice(e,1);for(e=t.nodes.length-t.output;e<t.nodes.length;e++)t.nodes[e].type="hidden";return t.connections=t.connections.concat(n.connections),t.nodes=t.nodes.concat(n.nodes),t},c.crossOver=function(t,n,e){if(t.input!==n.input||t.output!==n.output)throw new Error("Networks don't have the same input/output size!");var o=new c(t.input,t.output);o.connections=[],o.nodes=[];var i,r=t.score||0,h=n.score||0;if(e||r===h){let e=Math.max(t.nodes.length,n.nodes.length),o=Math.min(t.nodes.length,n.nodes.length);i=Math.floor(Math.random()*(e-o+1)+o)}else i=r>h?t.nodes.length:n.nodes.length;var u,l=t.output;for(u=0;u<t.nodes.length;u++)t.nodes[u].index=u;for(u=0;u<n.nodes.length;u++)n.nodes[u].index=u;for(u=0;u<i;u++){var f;if(u<i-l){let e=Math.random();f=e>=.5?t.nodes[u]:n.nodes[u];let o=e<.5?t.nodes[u]:n.nodes[u];void 0!==f&&"output"!==f.type||(f=o)}else f=Math.random()>=.5?t.nodes[t.nodes.length+u-i]:n.nodes[n.nodes.length+u-i];var p=new a;p.bias=f.bias,p.squash=f.squash,p.type=f.type,o.nodes.push(p)}var g={},d={};for(u=0;u<t.connections.length;u++){let n=t.connections[u],e={weight:n.weight,from:n.from.index,to:n.to.index,gater:null!=n.gater?n.gater.index:-1};g[s.innovationID(e.from,e.to)]=e}for(u=0;u<t.selfconns.length;u++){let n=t.selfconns[u],e={weight:n.weight,from:n.from.index,to:n.to.index,gater:null!=n.gater?n.gater.index:-1};g[s.innovationID(e.from,e.to)]=e}for(u=0;u<n.connections.length;u++){let t=n.connections[u],e={weight:t.weight,from:t.from.index,to:t.to.index,gater:null!=t.gater?t.gater.index:-1};d[s.innovationID(e.from,e.to)]=e}for(u=0;u<n.selfconns.length;u++){let t=n.selfconns[u],e={weight:t.weight,from:t.from.index,to:t.to.index,gater:null!=t.gater?t.gater.index:-1};d[s.innovationID(e.from,e.to)]=e}var v=[],m=Object.keys(g),w=Object.keys(d);for(u=m.length-1;u>=0;u--)if(void 0!==d[m[u]]){let t=Math.random()>=.5?g[m[u]]:d[m[u]];v.push(t),d[m[u]]=void 0}else(r>=h||e)&&v.push(g[m[u]]);if(h>=r||e)for(u=0;u<w.length;u++)void 0!==d[w[u]]&&v.push(d[w[u]]);for(u=0;u<v.length;u++){let t=v[u];if(t.to<i&&t.from<i){let n=o.nodes[t.from],e=o.nodes[t.to],s=o.connect(n,e)[0];s.weight=t.weight,-1!==t.gater&&t.gater<i&&o.gate(o.nodes[t.gater],s)}}return o},t.exports=c;var u=i.selection;function l(t,n,e,o){this.input=t,this.output=n,this.fitness=e,o=o||{},this.equal=o.equal||!1,this.clear=o.clear||!1,this.popsize=o.popsize||50,this.elitism=o.elitism||0,this.provenance=o.provenance||0,this.mutationRate=o.mutationRate||.3,this.mutationAmount=o.mutationAmount||1,this.fitnessPopulation=o.fitnessPopulation||!1,this.selection=o.selection||i.selection.POWER,this.crossover=o.crossover||[i.crossover.SINGLE_POINT,i.crossover.TWO_POINT,i.crossover.UNIFORM,i.crossover.AVERAGE],this.mutation=o.mutation||i.mutation.FFW,this.efficientMutation=o.efficientMutation||!1,this.template=o.network||!1,this.maxNodes=o.maxNodes||1/0,this.maxConns=o.maxConns||1/0,this.maxGates=o.maxGates||1/0,this.selectMutationMethod="function"==typeof o.mutationSelection?o.mutationSelection.bind(this):this.selectMutationMethod,this.generation=0,this.createPool(this.template)}l.prototype={createPool:function(t){this.population=[];for(var n=0;n<this.popsize;n++){var e;(e=this.template?c.fromJSON(t.toJSON()):new c(this.input,this.output)).score=void 0,this.population.push(e)}},evolve:async function(){void 0===this.population[this.population.length-1].score&&await this.evaluate(),this.sort();var t=c.fromJSON(this.population[0].toJSON());t.score=this.population[0].score;for(var n=[],e=[],o=0;o<this.elitism;o++)e.push(this.population[o]);for(o=0;o<this.provenance;o++)n.push(c.fromJSON(this.template.toJSON()));for(o=0;o<this.popsize-this.elitism-this.provenance;o++)n.push(this.getOffspring());for(this.population=n,this.mutate(),this.population.push(...e),o=0;o<this.population.length;o++)this.population[o].score=void 0;return this.generation++,t},getOffspring:function(){var t=this.getParent(),n=this.getParent();return c.crossOver(t,n,this.equal)},selectMutationMethod:function(t){var n=this.efficientMutation?t.getPossibleMutations(this.mutation):this.mutation,e=n[Math.floor(Math.random()*n.length)];if(e===i.mutation.ADD_NODE&&t.nodes.length>=this.maxNodes)r.warnings&&console.warn("maxNodes exceeded!");else if(e===i.mutation.ADD_CONN&&t.connections.length>=this.maxConns)r.warnings&&console.warn("maxConns exceeded!");else{if(!(e===i.mutation.ADD_GATE&&t.gates.length>=this.maxGates))return e;r.warnings&&console.warn("maxGates exceeded!")}},mutate:function(){for(var t=0;t<this.population.length;t++)if(Math.random()<=this.mutationRate)for(var n=0;n<this.mutationAmount;n++){var e=this.selectMutationMethod(this.population[t]);this.population[t].mutate(e)}},evaluate:async function(){var t;if(this.fitnessPopulation){if(this.clear)for(t=0;t<this.population.length;t++)this.population[t].clear();await this.fitness(this.population)}else for(t=0;t<this.population.length;t++){var n=this.population[t];this.clear&&n.clear(),n.score=await this.fitness(n)}},sort:function(){this.population.sort(function(t,n){return n.score-t.score})},getFittest:function(){return void 0===this.population[this.population.length-1].score&&this.evaluate(),this.population[0].score<this.population[1].score&&this.sort(),this.population[0]},getAverage:function(){void 0===this.population[this.population.length-1].score&&this.evaluate();for(var t=0,n=0;n<this.population.length;n++)t+=this.population[n].score;return t/this.population.length},getParent:function(){var t;switch(this.selection){case u.POWER:this.population[0].score<this.population[1].score&&this.sort();var n=Math.floor(Math.pow(Math.random(),this.selection.power)*this.population.length);return this.population[n];case u.FITNESS_PROPORTIONATE:var e=0,o=0;for(t=0;t<this.population.length;t++){var i=this.population[t].score;o=i<o?i:o,e+=i}e+=(o=Math.abs(o))*this.population.length;var s=Math.random()*e,r=0;for(t=0;t<this.population.length;t++){let n=this.population[t];if(s<(r+=n.score+o))return n}return this.population[Math.floor(Math.random()*this.population.length)];case u.TOURNAMENT:if(this.selection.size>this.popsize)throw new Error("Your tournament size should be lower than the population size, please change methods.selection.TOURNAMENT.size");var a=[];for(t=0;t<this.selection.size;t++){let t=this.population[Math.floor(Math.random()*this.population.length)];a.push(t)}for(a.sort(function(t,n){return n.score-t.score}),t=0;t<this.selection.size;t++)if(Math.random()<this.selection.probability||t===this.selection.size-1)return a[t]}},export:function(){for(var t=[],n=0;n<this.population.length;n++){var e=this.population[n];t.push(e.toJSON())}return t},import:function(t){for(var n=[],e=0;e<t.length;e++){var o=t[e];n.push(c.fromJSON(o))}this.population=n,this.popsize=n.length}}},function(t,n,e){var o={workers:e(18),serializeDataSet:function(t){for(var n=[t[0].input.length,t[0].output.length],e=0;e<t.length;e++){var o;for(o=0;o<n[0];o++)n.push(t[e].input[o]);for(o=0;o<n[1];o++)n.push(t[e].output[o])}return n},activateSerializedNetwork:function(t,n,e,o,i){for(var s=0;s<o[0];s++)n[s]=t[s];for(s=2;s<o.length;s++){let t=o[s++],r=o[s++],a=o[s++],h=o[s++],c=o[s++];for(e[t]=(-1===c?1:n[c])*h*e[t]+r;-2!==o[s];)e[t]+=n[o[s++]]*o[s++]*(-1===o[s++]?1:n[o[s-1]]);n[t]=i[a](e[t])}var r=[];for(s=n.length-o[1];s<n.length;s++)r.push(n[s]);return r},deserializeDataSet:function(t){for(var n=[],e=t[0]+t[1],o=0;o<(t.length-2)/e;o++){let s=[];for(var i=2+o*e;i<2+o*e+t[0];i++)s.push(t[i]);let r=[];for(i=2+o*e+t[0];i<2+o*e+e;i++)r.push(t[i]);n.push(s),n.push(r)}return n},testSerializedSet:function(t,n,e,o,i,s){for(var r=0,a=0;a<t.length;a+=2){let h=this.activateSerializedNetwork(t[a],e,o,i,s);r+=n(t[a+1],h)}return r/(t.length/2)},activations:[function(t){return 1/(1+Math.exp(-t))},function(t){return Math.tanh(t)},function(t){return t},function(t){return t>0?1:0},function(t){return t>0?t:0},function(t){return t/(1+Math.abs(t))},function(t){return Math.sin(t)},function(t){return Math.exp(-Math.pow(t,2))},function(t){return(Math.sqrt(Math.pow(t,2)+1)-1)/2+t},function(t){return t>0?1:-1},function(t){return 2/(1+Math.exp(-t))-1},function(t){return Math.max(-1,Math.min(1,t))},function(t){return Math.abs(t)},function(t){return 1-t},function(t){var n=1.6732632423543772;return 1.0507009873554805*(t>0?t:n*Math.exp(t)-n)}]};for(var i in o)t.exports[i]=o[i]},function(t,n,e){t.exports=a;var o=e(0),i=e(1),s=e(7),r=e(2);function a(t){this.nodes=[],this.connections={in:[],out:[],self:[]};for(var n=0;n<t;n++)this.nodes.push(new r)}a.prototype={activate:function(t){var n=[];if(void 0!==t&&t.length!==this.nodes.length)throw new Error("Array with values should be same as the amount of nodes!");for(var e=0;e<this.nodes.length;e++){var o;o=void 0===t?this.nodes[e].activate():this.nodes[e].activate(t[e]),n.push(o)}return n},propagate:function(t,n,e){if(void 0!==e&&e.length!==this.nodes.length)throw new Error("Array with values should be same as the amount of nodes!");for(var o=this.nodes.length-1;o>=0;o--)void 0===e?this.nodes[o].propagate(t,n,!0):this.nodes[o].propagate(t,n,!0,e[o])},connect:function(t,n,e){var h,c,u=[];if(t instanceof a){if(void 0===n&&(this!==t?(i.warnings&&console.warn("No group connection specified, using ALL_TO_ALL"),n=o.connection.ALL_TO_ALL):(i.warnings&&console.warn("No group connection specified, using ONE_TO_ONE"),n=o.connection.ONE_TO_ONE)),n===o.connection.ALL_TO_ALL||n===o.connection.ALL_TO_ELSE)for(h=0;h<this.nodes.length;h++)for(c=0;c<t.nodes.length;c++){if(n===o.connection.ALL_TO_ELSE&&this.nodes[h]===t.nodes[c])continue;let i=this.nodes[h].connect(t.nodes[c],e);this.connections.out.push(i[0]),t.connections.in.push(i[0]),u.push(i[0])}else if(n===o.connection.ONE_TO_ONE){if(this.nodes.length!==t.nodes.length)throw new Error("From and To group must be the same size!");for(h=0;h<this.nodes.length;h++){let n=this.nodes[h].connect(t.nodes[h],e);this.connections.self.push(n[0]),u.push(n[0])}}}else if(t instanceof s)u=t.input(this,n,e);else if(t instanceof r)for(h=0;h<this.nodes.length;h++){let n=this.nodes[h].connect(t,e);this.connections.out.push(n[0]),u.push(n[0])}return u},gate:function(t,n){if(void 0===n)throw new Error("Please specify Gating.INPUT, Gating.OUTPUT");Array.isArray(t)||(t=[t]);var e,i,s=[],r=[];for(e=0;e<t.length;e++){var a=t[e];s.includes(a.from)||s.push(a.from),r.includes(a.to)||r.push(a.to)}switch(n){case o.gating.INPUT:for(e=0;e<r.length;e++){let n=r[e],o=this.nodes[e%this.nodes.length];for(i=0;i<n.connections.in.length;i++){let e=n.connections.in[i];t.includes(e)&&o.gate(e)}}break;case o.gating.OUTPUT:for(e=0;e<s.length;e++){let n=s[e],o=this.nodes[e%this.nodes.length];for(i=0;i<n.connections.out.length;i++){let e=n.connections.out[i];t.includes(e)&&o.gate(e)}}break;case o.gating.SELF:for(e=0;e<s.length;e++){let n=s[e],o=this.nodes[e%this.nodes.length];t.includes(n.connections.self)&&o.gate(n.connections.self)}}},set:function(t){for(var n=0;n<this.nodes.length;n++)void 0!==t.bias&&(this.nodes[n].bias=t.bias),this.nodes[n].squash=t.squash||this.nodes[n].squash,this.nodes[n].type=t.type||this.nodes[n].type},disconnect:function(t,n){var e,o,i;if(n=n||!1,t instanceof a)for(e=0;e<this.nodes.length;e++)for(o=0;o<t.nodes.length;o++){for(this.nodes[e].disconnect(t.nodes[o],n),i=this.connections.out.length-1;i>=0;i--){let n=this.connections.out[i];if(n.from===this.nodes[e]&&n.to===t.nodes[o]){this.connections.out.splice(i,1);break}}if(n)for(i=this.connections.in.length-1;i>=0;i--){let n=this.connections.in[i];if(n.from===t.nodes[o]&&n.to===this.nodes[e]){this.connections.in.splice(i,1);break}}}else if(t instanceof r)for(e=0;e<this.nodes.length;e++){for(this.nodes[e].disconnect(t,n),o=this.connections.out.length-1;o>=0;o--){let n=this.connections.out[o];if(n.from===this.nodes[e]&&n.to===t){this.connections.out.splice(o,1);break}}if(n)for(o=this.connections.in.length-1;o>=0;o--){var s=this.connections.in[o];if(s.from===t&&s.to===this.nodes[e]){this.connections.in.splice(o,1);break}}}},clear:function(){for(var t=0;t<this.nodes.length;t++)this.nodes[t].clear()}}},function(t,n,e){var o=e(0),i=e(6),s=e(2);function r(){this.output=null,this.nodes=[],this.connections={in:[],out:[],self:[]}}r.prototype={activate:function(t){var n=[];if(void 0!==t&&t.length!==this.nodes.length)throw new Error("Array with values should be same as the amount of nodes!");for(var e=0;e<this.nodes.length;e++){var o;o=void 0===t?this.nodes[e].activate():this.nodes[e].activate(t[e]),n.push(o)}return n},propagate:function(t,n,e){if(void 0!==e&&e.length!==this.nodes.length)throw new Error("Array with values should be same as the amount of nodes!");for(var o=this.nodes.length-1;o>=0;o--)void 0===e?this.nodes[o].propagate(t,n,!0):this.nodes[o].propagate(t,n,!0,e[o])},connect:function(t,n,e){var o;return t instanceof i||t instanceof s?o=this.output.connect(t,n,e):t instanceof r&&(o=t.input(this,n,e)),o},gate:function(t,n){this.output.gate(t,n)},set:function(t){for(var n=0;n<this.nodes.length;n++){var e=this.nodes[n];e instanceof s?(void 0!==t.bias&&(e.bias=t.bias),e.squash=t.squash||e.squash,e.type=t.type||e.type):e instanceof i&&e.set(t)}},disconnect:function(t,n){var e,o,r;if(n=n||!1,t instanceof i)for(e=0;e<this.nodes.length;e++)for(o=0;o<t.nodes.length;o++){for(this.nodes[e].disconnect(t.nodes[o],n),r=this.connections.out.length-1;r>=0;r--){let n=this.connections.out[r];if(n.from===this.nodes[e]&&n.to===t.nodes[o]){this.connections.out.splice(r,1);break}}if(n)for(r=this.connections.in.length-1;r>=0;r--){let n=this.connections.in[r];if(n.from===t.nodes[o]&&n.to===this.nodes[e]){this.connections.in.splice(r,1);break}}}else if(t instanceof s)for(e=0;e<this.nodes.length;e++){for(this.nodes[e].disconnect(t,n),o=this.connections.out.length-1;o>=0;o--){let n=this.connections.out[o];if(n.from===this.nodes[e]&&n.to===t){this.connections.out.splice(o,1);break}}if(n)for(r=this.connections.in.length-1;r>=0;r--){let n=this.connections.in[r];if(n.from===t&&n.to===this.nodes[e]){this.connections.in.splice(r,1);break}}}},clear:function(){for(var t=0;t<this.nodes.length;t++)this.nodes[t].clear()}},r.Dense=function(t){var n=new r,e=new i(t);return n.nodes.push(e),n.output=e,n.input=function(t,n,i){return t instanceof r&&(t=t.output),n=n||o.connection.ALL_TO_ALL,t.connect(e,n,i)},n},r.LSTM=function(t){var n=new r,e=new i(t),s=new i(t),a=new i(t),h=new i(t),c=new i(t);e.set({bias:1}),s.set({bias:1}),h.set({bias:1}),a.connect(e,o.connection.ALL_TO_ALL),a.connect(s,o.connection.ALL_TO_ALL),a.connect(h,o.connection.ALL_TO_ALL);var u=a.connect(a,o.connection.ONE_TO_ONE),l=a.connect(c,o.connection.ALL_TO_ALL);return s.gate(u,o.gating.SELF),h.gate(l,o.gating.OUTPUT),n.nodes=[e,s,a,h,c],n.output=c,n.input=function(t,n,i){t instanceof r&&(t=t.output),n=n||o.connection.ALL_TO_ALL;var c=[],u=t.connect(a,n,i);return c=(c=(c=(c=c.concat(u)).concat(t.connect(e,n,i))).concat(t.connect(h,n,i))).concat(t.connect(s,n,i)),e.gate(u,o.gating.INPUT),c},n},r.GRU=function(t){var n=new r,e=new i(t),s=new i(t),a=new i(t),h=new i(t),c=new i(t),u=new i(t);u.set({bias:0,squash:o.activation.IDENTITY,type:"constant"}),h.set({squash:o.activation.TANH}),s.set({bias:0,squash:o.activation.INVERSE,type:"constant"}),e.set({bias:1}),a.set({bias:0}),u.connect(e,o.connection.ALL_TO_ALL),e.connect(s,o.connection.ONE_TO_ONE,1),u.connect(a,o.connection.ALL_TO_ALL);var l=u.connect(h,o.connection.ALL_TO_ALL);a.gate(l,o.gating.OUTPUT);var f=u.connect(c,o.connection.ALL_TO_ALL),p=h.connect(c,o.connection.ALL_TO_ALL);return e.gate(f,o.gating.OUTPUT),s.gate(p,o.gating.OUTPUT),c.connect(u,o.connection.ONE_TO_ONE,1),n.nodes=[e,s,a,h,c,u],n.output=c,n.input=function(t,n,i){t instanceof r&&(t=t.output),n=n||o.connection.ALL_TO_ALL;var s=[];return s=(s=(s=s.concat(t.connect(e,n,i))).concat(t.connect(a,n,i))).concat(t.connect(h,n,i))},n},r.Memory=function(t,n){var e,s=new r,a=null;for(e=0;e<n;e++){var h=new i(t);h.set({squash:o.activation.IDENTITY,bias:0,type:"constant"}),null!=a&&a.connect(h,o.connection.ONE_TO_ONE,1),s.nodes.push(h),a=h}for(s.nodes.reverse(),e=0;e<s.nodes.length;e++)s.nodes[e].nodes.reverse();var c=new i(0);for(var u in s.nodes)c.nodes=c.nodes.concat(s.nodes[u].nodes);return s.output=c,s.input=function(t,n,e){if(t instanceof r&&(t=t.output),n=n||o.connection.ALL_TO_ALL,t.nodes.length!==s.nodes[s.nodes.length-1].nodes.length)throw new Error("Previous layer size must be same as memory size");return t.connect(s.nodes[s.nodes.length-1],o.connection.ONE_TO_ONE,1)},s},t.exports=r},function(t,n){var e={LOGISTIC:function(t,n){var e=1/(1+Math.exp(-t));return n?e*(1-e):e},TANH:function(t,n){return n?1-Math.pow(Math.tanh(t),2):Math.tanh(t)},IDENTITY:function(t,n){return n?1:t},STEP:function(t,n){return n?0:t>0?1:0},RELU:function(t,n){return n?t>0?1:0:t>0?t:0},SOFTSIGN:function(t,n){var e=1+Math.abs(t);return n?t/Math.pow(e,2):t/e},SINUSOID:function(t,n){return n?Math.cos(t):Math.sin(t)},GAUSSIAN:function(t,n){var e=Math.exp(-Math.pow(t,2));return n?-2*t*e:e},BENT_IDENTITY:function(t,n){var e=Math.sqrt(Math.pow(t,2)+1);return n?t/(2*e)+1:(e-1)/2+t},BIPOLAR:function(t,n){return n?0:t>0?1:-1},BIPOLAR_SIGMOID:function(t,n){var e=2/(1+Math.exp(-t))-1;return n?.5*(1+e)*(1-e):e},HARD_TANH:function(t,n){return n?t>-1&&t<1?1:0:Math.max(-1,Math.min(1,t))},ABSOLUTE:function(t,n){return n?t<0?-1:1:Math.abs(t)},INVERSE:function(t,n){return n?-1:1-t},SELU:function(t,n){var e=1.6732632423543772,o=1.0507009873554805,i=t>0?t:e*Math.exp(t)-e;return n?t>0?o:(i+e)*o:i*o}};t.exports=e},function(t,n,e){var o,i,s={methods:e(0),Connection:e(3),architect:e(17),Network:e(4),config:e(1),Group:e(6),Layer:e(7),Node:e(2),Neat:e(25),multi:e(5)};void 0===(o=function(){return s}.apply(n,[]))||(t.exports=o),t.exports&&(t.exports=s),"object"==typeof window&&(i=window.carrot,s.ninja=function(){return window.carrot=i,s},window.carrot=s)},function(t,n,e){var o=e(8),i={ADD_NODE:{name:"ADD_NODE",randomActivation:!0},SUB_NODE:{name:"SUB_NODE",keep_gates:!0},ADD_CONN:{name:"ADD_CONN"},SUB_CONN:{name:"REMOVE_CONN"},MOD_WEIGHT:{name:"MOD_WEIGHT",min:-1,max:1},MOD_BIAS:{name:"MOD_BIAS",min:-1,max:1},MOD_ACTIVATION:{name:"MOD_ACTIVATION",mutateOutput:!1,allowed:[o.LOGISTIC,o.TANH,o.RELU,o.IDENTITY,o.STEP,o.SOFTSIGN,o.SINUSOID,o.GAUSSIAN,o.BENT_IDENTITY,o.BIPOLAR,o.BIPOLAR_SIGMOID,o.HARD_TANH,o.ABSOLUTE,o.INVERSE,o.SELU]},ADD_SELF_CONN:{name:"ADD_SELF_CONN"},SUB_SELF_CONN:{name:"SUB_SELF_CONN"},ADD_GATE:{name:"ADD_GATE"},SUB_GATE:{name:"SUB_GATE"},ADD_BACK_CONN:{name:"ADD_BACK_CONN"},SUB_BACK_CONN:{name:"SUB_BACK_CONN"},SWAP_NODES:{name:"SWAP_NODES",mutateOutput:!0}};i.ALL=[i.ADD_NODE,i.SUB_NODE,i.ADD_CONN,i.SUB_CONN,i.MOD_WEIGHT,i.MOD_BIAS,i.MOD_ACTIVATION,i.ADD_GATE,i.SUB_GATE,i.ADD_SELF_CONN,i.SUB_SELF_CONN,i.ADD_BACK_CONN,i.SUB_BACK_CONN,i.SWAP_NODES],i.FFW=[i.ADD_NODE,i.SUB_NODE,i.ADD_CONN,i.SUB_CONN,i.MOD_WEIGHT,i.MOD_BIAS,i.MOD_ACTIVATION,i.SWAP_NODES],t.exports=i},function(t,n){t.exports={FITNESS_PROPORTIONATE:{name:"FITNESS_PROPORTIONATE"},POWER:{name:"POWER",power:4},TOURNAMENT:{name:"TOURNAMENT",size:5,probability:.5}}},function(t,n){t.exports={SINGLE_POINT:{name:"SINGLE_POINT",config:[.4]},TWO_POINT:{name:"TWO_POINT",config:[.4,.9]},UNIFORM:{name:"UNIFORM"},AVERAGE:{name:"AVERAGE"}}},function(t,n){var e={CROSS_ENTROPY:function(t,n){for(var e=0,o=0;o<n.length;o++)e-=t[o]*Math.log(Math.max(n[o],1e-15))+(1-t[o])*Math.log(1-Math.max(n[o],1e-15));return e/n.length},MSE:function(t,n){for(var e=0,o=0;o<n.length;o++)e+=Math.pow(t[o]-n[o],2);return e/n.length},BINARY:function(t,n){for(var e=0,o=0;o<n.length;o++)e+=Math.round(2*t[o])!==Math.round(2*n[o]);return e},MAE:function(t,n){for(var e=0,o=0;o<n.length;o++)e+=Math.abs(t[o]-n[o]);return e/n.length},MAPE:function(t,n){for(var e=0,o=0;o<n.length;o++)e+=Math.abs((n[o]-t[o])/Math.max(t[o],1e-15));return e/n.length},WAPE:function(t,n){for(var e=0,o=0,i=0;i<n.length;i++)e+=Math.abs(t[i]-n[i]),o+=t[i];return e/o},MSLE:function(t,n){for(var e=0,o=0;o<n.length;o++)e+=Math.log(Math.max(t[o],1e-15))-Math.log(Math.max(n[o],1e-15));return e},HINGE:function(t,n){for(var e=0,o=0;o<n.length;o++)e+=Math.max(0,1-t[o]*n[o]);return e}};t.exports=e},function(t,n){t.exports={OUTPUT:{name:"OUTPUT"},INPUT:{name:"INPUT"},SELF:{name:"SELF"}}},function(t,n){t.exports={ALL_TO_ALL:{name:"OUTPUT"},ALL_TO_ELSE:{name:"INPUT"},ONE_TO_ONE:{name:"SELF"}}},function(t,n){var e={FIXED:function(){return function(t,n){return t}},STEP:function(t,n){t=t||.9,n=n||100;return function(e,o){return e*Math.pow(t,Math.floor(o/n))}},EXP:function(t){t=t||.999;return function(n,e){return n*Math.pow(t,e)}},INV:function(t,n){t=t||.001,n=n||2;return function(e,o){return e*Math.pow(1+t*o,-n)}}};t.exports=e},function(t,n,e){var o=e(0),i=e(4),s=e(6),r=e(7),a=e(2),h={Construct:function(t){var n,e=new i(0,0),o=[];for(n=0;n<t.length;n++){let e;if(t[n]instanceof s)for(e=0;e<t[n].nodes.length;e++)o.push(t[n].nodes[e]);else if(t[n]instanceof r)for(e=0;e<t[n].nodes.length;e++)for(var h=0;h<t[n].nodes[e].nodes.length;h++)o.push(t[n].nodes[e].nodes[h]);else t[n]instanceof a&&o.push(t[n])}var c=[],u=[];for(n=o.length-1;n>=0;n--)"output"===o[n].type||o[n].connections.out.length+o[n].connections.gated.length===0?(o[n].type="output",e.output++,u.push(o[n]),o.splice(n,1)):"input"!==o[n].type&&o[n].connections.in.length||(o[n].type="input",e.input++,c.push(o[n]),o.splice(n,1));if(o=c.concat(o).concat(u),0===e.input||0===e.output)throw new Error("Given nodes have no clear input/output node!");for(n=0;n<o.length;n++){let t;for(t=0;t<o[n].connections.out.length;t++)e.connections.push(o[n].connections.out[t]);for(t=0;t<o[n].connections.gated.length;t++)e.gates.push(o[n].connections.gated[t]);0!==o[n].connections.self.weight&&e.selfconns.push(o[n].connections.self)}return e.nodes=o,e},Perceptron:function(){var t=Array.prototype.slice.call(arguments);if(t.length<3)throw new Error("You have to specify at least 3 layers");var n=[];n.push(new s(t[0]));for(var e=1;e<t.length;e++){var i=t[e];i=new s(i),n.push(i),n[e-1].connect(n[e],o.connection.ALL_TO_ALL)}return h.Construct(n)},Random:function(t,n,e,s){var r,a=(s=s||{}).connections||2*n,h=s.backconnections||0,c=s.selfconnections||0,u=s.gates||0,l=new i(t,e);for(r=0;r<n;r++)l.mutate(o.mutation.ADD_NODE);for(r=0;r<a-n;r++)l.mutate(o.mutation.ADD_CONN);for(r=0;r<h;r++)l.mutate(o.mutation.ADD_BACK_CONN);for(r=0;r<c;r++)l.mutate(o.mutation.ADD_SELF_CONN);for(r=0;r<u;r++)l.mutate(o.mutation.ADD_GATE);return l},LSTM:function(){var t=Array.prototype.slice.call(arguments);if(t.length<3)throw new Error("You have to specify at least 3 layers");var n,e=t.pop();"number"==typeof e?(n=new s(e),e={}):n=new s(t.pop()),n.set({type:"output"});var i={};i.memoryToMemory=e.memoryToMemory||!1,i.outputToMemory=e.outputToMemory||!1,i.outputToGates=e.outputToGates||!1,i.inputToOutput=void 0===e.inputToOutput||e.inputToOutput,i.inputToDeep=void 0===e.inputToDeep||e.inputToDeep;var r=new s(t.shift());r.set({type:"input"});var a=t,c=[];c.push(r);for(var u=r,l=0;l<a.length;l++){var f=a[l],p=new s(f),g=new s(f),d=new s(f),v=new s(f),m=l===a.length-1?n:new s(f);p.set({bias:1}),g.set({bias:1}),v.set({bias:1});var w=u.connect(d,o.connection.ALL_TO_ALL);u.connect(p,o.connection.ALL_TO_ALL),u.connect(v,o.connection.ALL_TO_ALL),u.connect(g,o.connection.ALL_TO_ALL),d.connect(p,o.connection.ALL_TO_ALL),d.connect(g,o.connection.ALL_TO_ALL),d.connect(v,o.connection.ALL_TO_ALL);var O=d.connect(d,o.connection.ONE_TO_ONE),A=d.connect(m,o.connection.ALL_TO_ALL);if(p.gate(w,o.gating.INPUT),g.gate(O,o.gating.SELF),v.gate(A,o.gating.OUTPUT),i.inputToDeep&&l>0){let t=r.connect(d,o.connection.ALL_TO_ALL);p.gate(t,o.gating.INPUT)}if(i.memoryToMemory){let t=d.connect(d,o.connection.ALL_TO_ELSE);p.gate(t,o.gating.INPUT)}if(i.outputToMemory){let t=n.connect(d,o.connection.ALL_TO_ALL);p.gate(t,o.gating.INPUT)}i.outputToGates&&(n.connect(p,o.connection.ALL_TO_ALL),n.connect(g,o.connection.ALL_TO_ALL),n.connect(v,o.connection.ALL_TO_ALL)),c.push(p),c.push(g),c.push(d),c.push(v),l!==a.length-1&&c.push(m),u=m}return i.inputToOutput&&r.connect(n,o.connection.ALL_TO_ALL),c.push(n),h.Construct(c)},GRU:function(){var t=Array.prototype.slice.call(arguments);if(t.length<3)throw new Error("not enough layers (minimum 3) !!");var n=new s(t.shift()),e=new s(t.pop()),o=t,i=[];i.push(n);for(var a=n,c=0;c<o.length;c++){var u=new r.GRU(o[c]);a.connect(u),a=u,i.push(u)}return a.connect(e),i.push(e),h.Construct(i)},Hopfield:function(t){var n=new s(t),e=new s(t);return n.connect(e,o.connection.ALL_TO_ALL),n.set({type:"input"}),e.set({squash:o.activation.STEP,type:"output"}),new h.Construct([n,e])},NARX:function(t,n,e,i,s){Array.isArray(n)||(n=[n]);var a=[],c=new r.Dense(t),u=new r.Memory(t,i),l=[],f=new r.Dense(e),p=new r.Memory(e,s);a.push(c),a.push(p);for(var g=0;g<n.length;g++){var d=new r.Dense(n[g]);l.push(d),a.push(d),void 0!==l[g-1]&&l[g-1].connect(d,o.connection.ALL_TO_ALL)}return a.push(u),a.push(f),c.connect(l[0],o.connection.ALL_TO_ALL),c.connect(u,o.connection.ONE_TO_ONE,1),u.connect(l[0],o.connection.ALL_TO_ALL),l[l.length-1].connect(f,o.connection.ALL_TO_ALL),f.connect(p,o.connection.ONE_TO_ONE,1),p.connect(l[0],o.connection.ALL_TO_ALL),c.set({type:"input"}),f.set({type:"output"}),h.Construct(a)}};t.exports=h},function(t,n,e){var o={node:{TestWorker:e(19)},browser:{TestWorker:e(23)}};t.exports=o},function(t,n,e){t.exports=s;var o=e(20),i=e(21);function s(t,n){this.worker=o.fork(i.join(__dirname,"/worker")),this.worker.send({set:t,cost:n.name})}s.prototype={evaluate:function(t){return new Promise((n,e)=>{var o=t.serialize(),i={activations:o[0],states:o[1],conns:o[2]},s=this.worker;this.worker.on("message",function t(e){s.removeListener("message",t),n(e)}),this.worker.send(i)})},terminate:function(){this.worker.kill()}}},function(n,e){n.exports=t},function(t,n,e){(function(t){function e(t,n){for(var e=0,o=t.length-1;o>=0;o--){var i=t[o];"."===i?t.splice(o,1):".."===i?(t.splice(o,1),e++):e&&(t.splice(o,1),e--)}if(n)for(;e--;e)t.unshift("..");return t}var o=/^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/,i=function(t){return o.exec(t).slice(1)};function s(t,n){if(t.filter)return t.filter(n);for(var e=[],o=0;o<t.length;o++)n(t[o],o,t)&&e.push(t[o]);return e}n.resolve=function(){for(var n="",o=!1,i=arguments.length-1;i>=-1&&!o;i--){var r=i>=0?arguments[i]:t.cwd();if("string"!=typeof r)throw new TypeError("Arguments to path.resolve must be strings");r&&(n=r+"/"+n,o="/"===r.charAt(0))}return(o?"/":"")+(n=e(s(n.split("/"),function(t){return!!t}),!o).join("/"))||"."},n.normalize=function(t){var o=n.isAbsolute(t),i="/"===r(t,-1);return(t=e(s(t.split("/"),function(t){return!!t}),!o).join("/"))||o||(t="."),t&&i&&(t+="/"),(o?"/":"")+t},n.isAbsolute=function(t){return"/"===t.charAt(0)},n.join=function(){var t=Array.prototype.slice.call(arguments,0);return n.normalize(s(t,function(t,n){if("string"!=typeof t)throw new TypeError("Arguments to path.join must be strings");return t}).join("/"))},n.relative=function(t,e){function o(t){for(var n=0;n<t.length&&""===t[n];n++);for(var e=t.length-1;e>=0&&""===t[e];e--);return n>e?[]:t.slice(n,e-n+1)}t=n.resolve(t).substr(1),e=n.resolve(e).substr(1);for(var i=o(t.split("/")),s=o(e.split("/")),r=Math.min(i.length,s.length),a=r,h=0;h<r;h++)if(i[h]!==s[h]){a=h;break}var c=[];for(h=a;h<i.length;h++)c.push("..");return(c=c.concat(s.slice(a))).join("/")},n.sep="/",n.delimiter=":",n.dirname=function(t){var n=i(t),e=n[0],o=n[1];return e||o?(o&&(o=o.substr(0,o.length-1)),e+o):"."},n.basename=function(t,n){var e=i(t)[2];return n&&e.substr(-1*n.length)===n&&(e=e.substr(0,e.length-n.length)),e},n.extname=function(t){return i(t)[3]};var r="b"==="ab".substr(-1)?function(t,n,e){return t.substr(n,e)}:function(t,n,e){return n<0&&(n=t.length+n),t.substr(n,e)}}).call(this,e(22))},function(t,n){var e,o,i=t.exports={};function s(){throw new Error("setTimeout has not been defined")}function r(){throw new Error("clearTimeout has not been defined")}function a(t){if(e===setTimeout)return setTimeout(t,0);if((e===s||!e)&&setTimeout)return e=setTimeout,setTimeout(t,0);try{return e(t,0)}catch(n){try{return e.call(null,t,0)}catch(n){return e.call(this,t,0)}}}!function(){try{e="function"==typeof setTimeout?setTimeout:s}catch(t){e=s}try{o="function"==typeof clearTimeout?clearTimeout:r}catch(t){o=r}}();var h,c=[],u=!1,l=-1;function f(){u&&h&&(u=!1,h.length?c=h.concat(c):l=-1,c.length&&p())}function p(){if(!u){var t=a(f);u=!0;for(var n=c.length;n;){for(h=c,c=[];++l<n;)h&&h[l].run();l=-1,n=c.length}h=null,u=!1,function(t){if(o===clearTimeout)return clearTimeout(t);if((o===r||!o)&&clearTimeout)return o=clearTimeout,clearTimeout(t);try{o(t)}catch(n){try{return o.call(null,t)}catch(n){return o.call(this,t)}}}(t)}}function g(t,n){this.fun=t,this.array=n}function d(){}i.nextTick=function(t){var n=new Array(arguments.length-1);if(arguments.length>1)for(var e=1;e<arguments.length;e++)n[e-1]=arguments[e];c.push(new g(t,n)),1!==c.length||u||a(p)},g.prototype.run=function(){this.fun.apply(null,this.array)},i.title="browser",i.browser=!0,i.env={},i.argv=[],i.version="",i.versions={},i.on=d,i.addListener=d,i.once=d,i.off=d,i.removeListener=d,i.removeAllListeners=d,i.emit=d,i.prependListener=d,i.prependOnceListener=d,i.listeners=function(t){return[]},i.binding=function(t){throw new Error("process.binding is not supported")},i.cwd=function(){return"/"},i.chdir=function(t){throw new Error("process.chdir is not supported")},i.umask=function(){return 0}},function(t,n,e){t.exports=i;var o=e(5);function i(t,n){var e=new Blob([this._createBlobString(n)]);this.url=window.URL.createObjectURL(e),this.worker=new Worker(this.url);var o={set:new Float64Array(t).buffer};this.worker.postMessage(o,[o.set])}i.prototype={evaluate:function(t){return new Promise((n,e)=>{var o=t.serialize(),i={activations:new Float64Array(o[0]).buffer,states:new Float64Array(o[1]).buffer,conns:new Float64Array(o[2]).buffer};this.worker.onmessage=function(t){var e=new Float64Array(t.data.buffer)[0];n(e)},this.worker.postMessage(i,[i.activations,i.states,i.conns])})},terminate:function(){this.worker.terminate(),window.URL.revokeObjectURL(this.url)},_createBlobString:function(t){return`\n var F = [${o.activations.toString()}];\n var cost = ${t.toString()};\n var multi = {\n deserializeDataSet: ${o.deserializeDataSet.toString()},\n testSerializedSet: ${o.testSerializedSet.toString()},\n activateSerializedNetwork: ${o.activateSerializedNetwork.toString()}\n };\n\n this.onmessage = function (e) {\n if(typeof e.data.set === 'undefined'){\n var A = new Float64Array(e.data.activations);\n var S = new Float64Array(e.data.states);\n var data = new Float64Array(e.data.conns);\n\n var error = multi.testSerializedSet(set, cost, A, S, data, F);\n\n var answer = { buffer: new Float64Array([error ]).buffer };\n postMessage(answer, [answer.buffer]);\n } else {\n set = multi.deserializeDataSet(new Float64Array(e.data.set));\n }\n };`}}},function(t,e){t.exports=n},function(t,n,e){var o=e(4),i=e(0),s=e(1),r=i.selection;function a(t,n,e,o){this.input=t,this.output=n,this.fitness=e,o=o||{},this.equal=o.equal||!1,this.clear=o.clear||!1,this.popsize=o.popsize||50,this.elitism=o.elitism||0,this.provenance=o.provenance||0,this.mutationRate=o.mutationRate||.3,this.mutationAmount=o.mutationAmount||1,this.fitnessPopulation=o.fitnessPopulation||!1,this.selection=o.selection||i.selection.POWER,this.crossover=o.crossover||[i.crossover.SINGLE_POINT,i.crossover.TWO_POINT,i.crossover.UNIFORM,i.crossover.AVERAGE],this.mutation=o.mutation||i.mutation.FFW,this.efficientMutation=o.efficientMutation||!1,this.template=o.network||!1,this.maxNodes=o.maxNodes||1/0,this.maxConns=o.maxConns||1/0,this.maxGates=o.maxGates||1/0,this.selectMutationMethod="function"==typeof o.mutationSelection?o.mutationSelection.bind(this):this.selectMutationMethod,this.generation=0,this.createPool(this.template)}a.prototype={createPool:function(t){this.population=[];for(var n=0;n<this.popsize;n++){var e;(e=this.template?o.fromJSON(t.toJSON()):new o(this.input,this.output)).score=void 0,this.population.push(e)}},evolve:async function(){void 0===this.population[this.population.length-1].score&&await this.evaluate(),this.sort();var t=o.fromJSON(this.population[0].toJSON());t.score=this.population[0].score;for(var n=[],e=[],i=0;i<this.elitism;i++)e.push(this.population[i]);for(i=0;i<this.provenance;i++)n.push(o.fromJSON(this.template.toJSON()));for(i=0;i<this.popsize-this.elitism-this.provenance;i++)n.push(this.getOffspring());for(this.population=n,this.mutate(),this.population.push(...e),i=0;i<this.population.length;i++)this.population[i].score=void 0;return this.generation++,t},getOffspring:function(){var t=this.getParent(),n=this.getParent();return o.crossOver(t,n,this.equal)},selectMutationMethod:function(t){var n=this.efficientMutation?t.getPossibleMutations(this.mutation):this.mutation,e=n[Math.floor(Math.random()*n.length)];return e===i.mutation.ADD_NODE&&t.nodes.length>=this.maxNodes?(s.warnings&&console.warn("maxNodes exceeded!"),null):e===i.mutation.ADD_CONN&&t.connections.length>=this.maxConns?(s.warnings&&console.warn("maxConns exceeded!"),null):e===i.mutation.ADD_GATE&&t.gates.length>=this.maxGates?(s.warnings&&console.warn("maxGates exceeded!"),null):e},mutate:function(){for(var t=0;t<this.population.length;t++)if(Math.random()<=this.mutationRate)for(var n=0;n<this.mutationAmount;n++){var e=this.selectMutationMethod(this.population[t]);this.population[t].mutate(e)}},evaluate:async function(){var t;if(this.fitnessPopulation){if(this.clear)for(t=0;t<this.population.length;t++)this.population[t].clear();await this.fitness(this.population)}else for(t=0;t<this.population.length;t++){var n=this.population[t];this.clear&&n.clear(),n.score=await this.fitness(n)}},sort:function(){this.population.sort(function(t,n){return n.score-t.score})},getFittest:function(){return void 0===this.population[this.population.length-1].score&&this.evaluate(),this.population[0].score<this.population[1].score&&this.sort(),this.population[0]},getAverage:function(){void 0===this.population[this.population.length-1].score&&this.evaluate();for(var t=0,n=0;n<this.population.length;n++)t+=this.population[n].score;return t/this.population.length},getParent:function(){var t;switch(this.selection){case r.POWER:this.population[0].score<this.population[1].score&&this.sort();var n=Math.floor(Math.pow(Math.random(),this.selection.power)*this.population.length);return this.population[n];case r.FITNESS_PROPORTIONATE:var e=0,o=0;for(t=0;t<this.population.length;t++){var i=this.population[t].score;o=i<o?i:o,e+=i}e+=(o=Math.abs(o))*this.population.length;var s=Math.random()*e,a=0;for(t=0;t<this.population.length;t++){let n=this.population[t];if(s<(a+=n.score+o))return n}return this.population[Math.floor(Math.random()*this.population.length)];case r.TOURNAMENT:if(this.selection.size>this.popsize)throw new Error("Your tournament size should be lower than the population size, please change methods.selection.TOURNAMENT.size");var h=[];for(t=0;t<this.selection.size;t++){let t=this.population[Math.floor(Math.random()*this.population.length)];h.push(t)}for(h.sort(function(t,n){return n.score-t.score}),t=0;t<this.selection.size;t++)if(Math.random()<this.selection.probability||t===this.selection.size-1)return h[t]}},export:function(){for(var t=[],n=0;n<this.population.length;n++){var e=this.population[n];t.push(e.toJSON())}return t},import:function(t){for(var n=[],e=0;e<t.length;e++){var i=t[e];n.push(o.fromJSON(i))}this.population=n,this.popsize=n.length}},t.exports=a}])});
import React, { useState } from 'react'; import MoviesList from './components/MoviesList'; import './App.css'; function App() { const [movies, setMovies] = useState([]); const [isLoading, setIsLoading] = useState(false); async function fetchMoviesHandler() { setIsLoading(true); const response = await fetch('https://swapi.dev/api/films/'); const data = await response.json(); const transformedMovies = data.results.map((movieData) => { return { id: movieData.episode_id, title: movieData.title, openingText: movieData.opening_crawl, releaseDate: movieData.release_date, }; }); setMovies(transformedMovies); setIsLoading(false); }; return ( <React.Fragment> <section> <button onClick={fetchMoviesHandler}>Fetch Movies</button> </section> <section> {!isLoading && movies.length > 0 && <MoviesList movies={movies} />} {!isLoading && movies.length === 0 && <p>Found no movies.</p>} {isLoading && <p>Loading...</p>} </section> </React.Fragment> ); } export default App;
import pygame from gamestate import * class Button(pygame.sprite.Sprite): def __init__(self, image, image_alt, x, y, rescale_factor=None): super().__init__() self.image = pygame.image.load(os.path.join(ASSETS_PATH, 'Misc', image)) self.image_alt = pygame.image.load(os.path.join(ASSETS_PATH, 'Misc', image_alt)) if rescale_factor: self.image = pygame.transform.scale(self.image, rescale_factor) self.image_alt = pygame.transform.scale(self.image_alt, rescale_factor) self.rect = self.image.get_rect(topleft = (x, y)) def draw(self, screen, alt=None): if alt: screen.blit(self.image_alt, self.rect) else: screen.blit(self.image, self.rect) def _draw_box(self, screen): pygame.draw.rect(screen, WHITE, self.rect, 1) def collision(self, position): return self.rect.collidepoint(position) class GameBoard: def __init__(self, bg_img): pygame.font.init() self.font = pygame.font.Font(None, ICON_SIZE) self.background = pygame.transform.scale(pygame.image.load( os.path.join(ASSETS_PATH, "Background", bg_img)), (SCREEN_WIDTH, SCREEN_HEIGHT)) self.end_turn = Button('end_turn.png', 'end_turn_alt.png', SCREEN_WIDTH - ICON_SIZE, SCREEN_HEIGHT - ICON_SIZE, (ICON_SIZE, ICON_SIZE)) self.deck = Button('deck_icon.png', 'deck_icon_alt.png', 24, SCREEN_HEIGHT - 72 - ICON_SIZE, (ICON_SIZE, ICON_SIZE)) self.graveyard = Button('pirate-grave.png', 'pirate-grave_alt.png', 24, SCREEN_HEIGHT - 72, (ICON_SIZE, ICON_SIZE)) self.power = Button('battery-pack.png', 'battery-pack-alt.png', 24, SCREEN_HEIGHT - 72 - ICON_SIZE - ICON_SIZE, (ICON_SIZE, ICON_SIZE)) def draw(self, screen, cur_power, max_power): screen.blit(self.background, (0,0)) self.end_turn.draw(screen) self.deck.draw(screen) self.graveyard.draw(screen) self.power.draw(screen, cur_power == 0) power = self.font.render("{} / {}".format(cur_power, max_power), False, CYAN) prect = power.get_rect(center=self.power.rect.center) screen.blit(power, ((prect.x + ICON_SIZE) * 1.2, prect.y)) def _show_boxes(self, screen): self.end_turn._draw_box(screen) self.graveyard._draw_box(screen) self.deck._draw_box(screen) def highlight(self, screen, position, alwayson): if alwayson or self.end_turn.rect.collidepoint(position): self.end_turn.draw(screen, True) elif self.deck.rect.collidepoint(position): self.deck.draw(screen, True) elif self.graveyard.rect.collidepoint(position): self.graveyard.draw(screen, True)
import { Action } from '../constants' export default (state = {}, action) => { switch (action.type) { case Action.PLUGIN_LOADED: return handlePluginLoaded(state, action) default: return state } } function handlePluginLoaded(state, action) { const { palette } = action.payload return { ...state, ...palette } }
$(function() { $('#flash').delay(500).fadeIn('normal', function() { $(this).delay(2000).fadeOut(); }); }); $(document).ready(function(){ var clip = new ZeroClipboard($(".clip_button")); $(".clip_button").click(function() { clip = new ZeroClipboard($(".clip_button")); }); });
import React from "react"; import { useForm } from "react-hook-form"; import { Form } from "react-bootstrap"; import Field from "@app/common/forms/Field"; import fetch from "isomorphic-unfetch"; import Router from "next/router"; // import Button from "@app/ondrejsika-theme/components/FormButton"; import ReCAPTCHA from "react-google-recaptcha"; import Translate from "@app/common/components/Translate"; const recaptchaRef = React.createRef(); const CourseInquiryForm = (props) => { const { handleSubmit, register, errors } = useForm(); const onSubmit = (values) => { let data = { course_slug: props.course_slug, recaptcha: recaptchaRef.current.getValue(), name: values.name, company: values.company, email: values.email, phone: values.phone }; console.log(recaptchaRef.current.getValue()); console.log(data); console.log(JSON.stringify(data)); fetch(props.site.trainingcrm_url + "/api/inquiry/", { method: "post", headers: { Accept: "application/json", "Content-Type": "application/json" }, body: JSON.stringify(data) }).then((res) => { console.log(res); if (res.status == 200) Router.push("/odeslano"); else Router.push("/odeslano-chyba"); }); }; return ( <Form onSubmit={handleSubmit(onSubmit)}> <h2> <Translate lang={props.site.lang} cs="Nezรกvaznรก poptรกvka" en="Non-binding Inquiry" de="Non-binding Inquiry" /> </h2> <Field name="name" label="Name" validation_required="You name is requires" register={register} errors={errors} /> <Field name="company" label="Company" register={register} errors={errors} /> <Field name="email" label="Email" register={register} errors={errors} validation_required="Your email is required" validation_pattern={/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i} validation_pattern_message="Your email is not valid" /> <Field name="phone" label="Phone Number" register={register} errors={errors} /> <ReCAPTCHA ref={recaptchaRef} sitekey={props.site.recaptcha_site_key} /> <div className="pt-5"> <button site={props.site}> <Translate lang={props.site.lang} cs="Odeslat" en="Submit" /> </button> </div> </Form> ); }; export default CourseInquiryForm;
const _ = require('underscore'); const socketio = require('socket.io'); const jwt = require('jsonwebtoken'); const Raven = require('raven'); const http = require('http'); const https = require('https'); const fs = require('fs'); const config = require('./nodeconfig.js'); const { detectBinary } = require('../util'); const logger = require('../log.js'); const ZmqSocket = require('./zmqsocket.js'); const Game = require('../game/game.js'); const Socket = require('../socket.js'); const version = require('../../version.js'); if(config.sentryDsn) { Raven.config(config.sentryDsn, { release: version.build }).install(); } class GameServer { constructor() { this.games = {}; this.protocol = 'https'; try { var privateKey = fs.readFileSync(config.keyPath).toString(); var certificate = fs.readFileSync(config.certPath).toString(); } catch(e) { this.protocol = 'http'; } this.host = process.env.HOST || config.host; this.zmqSocket = new ZmqSocket(this.host, this.protocol, version.build); this.zmqSocket.on('onStartGame', this.onStartGame.bind(this)); this.zmqSocket.on('onSpectator', this.onSpectator.bind(this)); this.zmqSocket.on('onGameSync', this.onGameSync.bind(this)); this.zmqSocket.on('onFailedConnect', this.onFailedConnect.bind(this)); this.zmqSocket.on('onCloseGame', this.onCloseGame.bind(this)); this.zmqSocket.on('onCardData', this.onCardData.bind(this)); var server = undefined; if(!privateKey || !certificate) { server = http.createServer(); } else { server = https.createServer({ key: privateKey, cert: certificate }); } server.listen(process.env.PORT || config.socketioPort); var options = { perMessageDeflate: false }; if(process.env.NODE_ENV !== 'production') { options.path = '/' + (process.env.SERVER || config.nodeIdentity) + '/socket.io'; } this.io = socketio(server, options); this.io.set('heartbeat timeout', 30000); this.io.use(this.handshake.bind(this)); if(process.env.NODE_ENV === 'production') { this.io.set('origins', 'http://www.throneteki.net:* https://www.throneteki.net:* http://www.theironthrone.net:* https://www.theironthrone.net:*'); } this.io.on('connection', this.onConnection.bind(this)); setInterval(() => this.clearStaleFinishedGames(), 60 * 1000); } debugDump() { var games = _.map(this.games, game => { var players = _.map(game.playersAndSpectators, player => { return { name: player.name, left: player.left, disconnected: player.disconnected, id: player.id, spectator: player.isSpectator() }; }); return { name: game.name, players: players, id: game.id, started: game.started, startedAt: game.startedAt }; }); return { games: games, gameCount: _.size(this.games) }; } handleError(game, e) { logger.error(e); let gameState = game.getState(); let debugData = {}; if(e.message.includes('Maximum call stack')) { debugData.badSerializaton = detectBinary(gameState); } else { debugData.game = gameState; debugData.game.players = undefined; debugData.messages = game.getPlainTextLog(); debugData.game.messages = undefined; _.each(game.getPlayers(), player => { debugData[player.name] = player.getState(player); }); } Raven.captureException(e, { extra: debugData }); if(game) { game.addMessage('A Server error has occured processing your game state, apologies. Your game may now be in an inconsistent state, or you may be able to continue. The error has been logged.'); } } clearStaleFinishedGames() { const timeout = 20 * 60 * 1000; let staleGames = _.filter(this.games, game => game.finishedAt && (Date.now() - game.finishedAt > timeout)); for(let game of staleGames) { logger.info('closed finished game', game.id, 'due to inactivity'); for(let player of Object.values(game.getPlayersAndSpectators())) { if(player.socket) { player.socket.tIsClosing = true; player.socket.disconnect(); } } delete this.games[game.id]; this.zmqSocket.send('GAMECLOSED', { game: game.id }); } } runAndCatchErrors(game, func) { try { func(); } catch(e) { this.handleError(game, e); this.sendGameState(game); } } findGameForUser(username) { return _.find(this.games, game => { var player = game.playersAndSpectators[username]; if(!player || player.left) { return false; } return true; }); } sendGameState(game) { _.each(game.getPlayersAndSpectators(), player => { if(player.left || player.disconnected || !player.socket) { return; } player.socket.send('gamestate', game.getState(player.name)); }); } handshake(socket, next) { if(socket.handshake.query.token && socket.handshake.query.token !== 'undefined') { jwt.verify(socket.handshake.query.token, config.secret, function(err, user) { if(err) { return; } socket.request.user = user; }); } next(); } gameWon(game, reason, winner) { this.zmqSocket.send('GAMEWIN', { game: game.getSaveState(), winner: winner.name, reason: reason }); } rematch(game) { this.zmqSocket.send('REMATCH', { game: game.getSaveState() }); for(let player of Object.values(game.getPlayersAndSpectators())) { if(player.left || player.disconnected || !player.socket) { continue; } player.socket.send('cleargamestate'); player.socket.leaveChannel(game.id); player.left = true; // So they don't get game state sent after the /rematch command is issued } delete this.games[game.id]; } onStartGame(pendingGame) { let game = new Game(pendingGame, { router: this, titleCardData: this.titleCardData, cardData: this.cardData, packData: this.packData, restrictedListData: this.restrictedListData }); this.games[pendingGame.id] = game; game.started = true; for(let player of Object.values(pendingGame.players)) { game.selectDeck(player.name, player.deck); } game.initialise(); if(pendingGame.rematch) { game.addAlert('info', 'The rematch is ready'); } } onSpectator(pendingGame, user) { var game = this.games[pendingGame.id]; if(!game) { return; } game.watch('TBA', user); this.sendGameState(game); } onGameSync(callback) { var gameSummaries = _.map(this.games, game => { var retGame = game.getSummary(undefined, { fullData: true }); retGame.password = game.password; return retGame; }); logger.info('syncing', _.size(gameSummaries), ' games'); callback(gameSummaries); } onFailedConnect(gameId, username) { var game = this.findGameForUser(username); if(!game || game.id !== gameId) { return; } game.failedConnect(username); if(game.isEmpty()) { delete this.games[game.id]; this.zmqSocket.send('GAMECLOSED', { game: game.id }); } this.sendGameState(game); } onCloseGame(gameId) { let game = this.games[gameId]; if(!game) { return; } for(let player of Object.values(game.getPlayersAndSpectators())) { player.socket.send('cleargamestate'); player.socket.leaveChannel(game.id); } delete this.games[gameId]; this.zmqSocket.send('GAMECLOSED', { game: game.id }); } onCardData(cardData) { this.titleCardData = cardData.titleCardData; this.cardData = cardData.cardData; this.packData = cardData.packData; this.restrictedListData = cardData.restrictedListData; } onConnection(ioSocket) { if(!ioSocket.request.user) { logger.info('socket connected with no user, disconnecting'); ioSocket.disconnect(); return; } var game = this.findGameForUser(ioSocket.request.user.username); if(!game) { logger.info('No game for', ioSocket.request.user.username, 'disconnecting'); ioSocket.disconnect(); return; } var socket = new Socket(ioSocket, { config: config }); var player = game.playersAndSpectators[socket.user.username]; if(!player) { return; } player.lobbyId = player.id; player.id = socket.id; player.connectionSucceeded = true; if(player.disconnected) { logger.info('user \'%s\' reconnected to game', socket.user.username); game.reconnect(socket, player.name); } socket.joinChannel(game.id); player.socket = socket; if(!player.isSpectator()) { game.addMessage('{0} has connected to the game server', player); } this.sendGameState(game); socket.registerEvent('game', this.onGameMessage.bind(this)); socket.on('disconnect', this.onSocketDisconnected.bind(this)); } onSocketDisconnected(socket, reason) { let game = this.findGameForUser(socket.user.username); if(!game) { return; } logger.info('user \'%s\' disconnected from a game: %s', socket.user.username, reason); let player = game.playersAndSpectators[socket.user.username]; if(player.id !== socket.id) { return; } let isSpectator = player && player.isSpectator(); game.disconnect(socket.user.username); if(!socket.tIsClosing) { if(game.isEmpty()) { delete this.games[game.id]; this.zmqSocket.send('GAMECLOSED', { game: game.id }); } else if(isSpectator) { this.zmqSocket.send('PLAYERLEFT', { gameId: game.id, game: game.getSaveState(), player: socket.user.username, spectator: true }); } } this.sendGameState(game); } onLeaveGame(socket) { var game = this.findGameForUser(socket.user.username); if(!game) { return; } let player = game.playersAndSpectators[socket.user.username]; let isSpectator = player.isSpectator(); game.leave(socket.user.username); this.zmqSocket.send('PLAYERLEFT', { gameId: game.id, game: game.getSaveState(), player: socket.user.username, spectator: isSpectator }); socket.send('cleargamestate'); socket.leaveChannel(game.id); if(game.isEmpty()) { delete this.games[game.id]; this.zmqSocket.send('GAMECLOSED', { game: game.id }); } this.sendGameState(game); } onGameMessage(socket, command, ...args) { var game = this.findGameForUser(socket.user.username); if(!game) { return; } if(command === 'leavegame') { return this.onLeaveGame(socket); } if(!game[command] || !_.isFunction(game[command])) { return; } this.runAndCatchErrors(game, () => { game[command](socket.user.username, ...args); game.continue(); this.sendGameState(game); }); } } module.exports = GameServer;
module.exports = { presets: [ [ '@babel/preset-env', { modules: false, targets: { ie: 9 }, }, ], ], plugins: ['@babel/plugin-transform-runtime'], env: { test: { presets: [ [ '@babel/preset-env', { targets: { node: true }, }, ], ], }, }, }
import mongoose, { Schema } from 'mongoose'; // sample schema definition for DAHObject - replace with your data model export const ObjectSchema = new Schema({ id: { type: String, required: true }, // define your schema }); export const DAHObject = mongoose.model('Object', ObjectSchema);
// @flow import { updateTypes } from 'lib/types/update-types'; import { createUpdates } from '../creators/update-creator'; import { dbQuery, SQL } from '../database/database'; import { fetchKnownUserInfos } from '../fetchers/user-fetchers'; import { createScriptViewer } from '../session/scripts'; import { main } from './utils'; const userID = '518252'; const newUsername = 'atul'; async function renameUser() { const [adjacentUsers] = await Promise.all([ fetchKnownUserInfos(createScriptViewer(userID)), dbQuery( SQL`UPDATE users SET username = ${newUsername} WHERE id = ${userID}`, ), ]); const updateDatas = []; const time = Date.now(); updateDatas.push({ type: updateTypes.UPDATE_CURRENT_USER, userID, time, }); for (const adjacentUserID in adjacentUsers) { updateDatas.push({ type: updateTypes.UPDATE_USER, userID: adjacentUserID, time, updatedUserID: userID, }); } await createUpdates(updateDatas); } main([renameUser]);
var sgmm2_acc_stats_8cc = [ [ "main", "sgmm2-acc-stats_8cc.html#a0ddf1224851353fc92bfbff6f499fa97", null ] ];
/** * @fileoverview Validates spacing before and after semicolon * @author Mathias Schreck */ "use strict"; const astUtils = require("./utils/ast-utils"); //------------------------------------------------------------------------------ // Rule Definition //------------------------------------------------------------------------------ module.exports = { meta: { type: "layout", docs: { description: "enforce consistent spacing before and after semicolons", category: "Stylistic Issues", recommended: false, url: "https://eslint.org/docs/rules/semi-spacing" }, fixable: "whitespace", schema: [ { type: "object", properties: { before: { type: "boolean", default: false }, after: { type: "boolean", default: true } }, additionalProperties: false } ], messages: { unexpectedWhitespaceBefore: "Unexpected whitespace before semicolon.", unexpectedWhitespaceAfter: "Unexpected whitespace after semicolon.", missingWhitespaceBefore: "Missing whitespace before semicolon.", missingWhitespaceAfter: "Missing whitespace after semicolon." } }, create(context) { const config = context.options[0], sourceCode = context.getSourceCode(); let requireSpaceBefore = false, requireSpaceAfter = true; if (typeof config === "object") { requireSpaceBefore = config.before; requireSpaceAfter = config.after; } /** * Checks if a given token has leading whitespace. * @param {Object} token The token to check. * @returns {boolean} True if the given token has leading space, false if not. */ function hasLeadingSpace(token) { const tokenBefore = sourceCode.getTokenBefore(token); return tokenBefore && astUtils.isTokenOnSameLine(tokenBefore, token) && sourceCode.isSpaceBetweenTokens(tokenBefore, token); } /** * Checks if a given token has trailing whitespace. * @param {Object} token The token to check. * @returns {boolean} True if the given token has trailing space, false if not. */ function hasTrailingSpace(token) { const tokenAfter = sourceCode.getTokenAfter(token); return tokenAfter && astUtils.isTokenOnSameLine(token, tokenAfter) && sourceCode.isSpaceBetweenTokens(token, tokenAfter); } /** * Checks if the given token is the last token in its line. * @param {Token} token The token to check. * @returns {boolean} Whether or not the token is the last in its line. */ function isLastTokenInCurrentLine(token) { const tokenAfter = sourceCode.getTokenAfter(token); return !(tokenAfter && astUtils.isTokenOnSameLine(token, tokenAfter)); } /** * Checks if the given token is the first token in its line * @param {Token} token The token to check. * @returns {boolean} Whether or not the token is the first in its line. */ function isFirstTokenInCurrentLine(token) { const tokenBefore = sourceCode.getTokenBefore(token); return !(tokenBefore && astUtils.isTokenOnSameLine(token, tokenBefore)); } /** * Checks if the next token of a given token is a closing parenthesis. * @param {Token} token The token to check. * @returns {boolean} Whether or not the next token of a given token is a closing parenthesis. */ function isBeforeClosingParen(token) { const nextToken = sourceCode.getTokenAfter(token); return (nextToken && astUtils.isClosingBraceToken(nextToken) || astUtils.isClosingParenToken(nextToken)); } /** * Report location example : * * for unexpected space `before` * * var a = 'b' ; * ^^^ * * for unexpected space `after` * * var a = 'b'; c = 10; * ^^ * * Reports if the given token has invalid spacing. * @param {Token} token The semicolon token to check. * @param {ASTNode} node The corresponding node of the token. * @returns {void} */ function checkSemicolonSpacing(token, node) { if (astUtils.isSemicolonToken(token)) { if (hasLeadingSpace(token)) { if (!requireSpaceBefore) { const tokenBefore = sourceCode.getTokenBefore(token); const loc = { start: tokenBefore.loc.end, end: token.loc.start }; context.report({ node, loc, messageId: "unexpectedWhitespaceBefore", fix(fixer) { return fixer.removeRange([tokenBefore.range[1], token.range[0]]); } }); } } else { if (requireSpaceBefore) { const loc = token.loc; context.report({ node, loc, messageId: "missingWhitespaceBefore", fix(fixer) { return fixer.insertTextBefore(token, " "); } }); } } if (!isFirstTokenInCurrentLine(token) && !isLastTokenInCurrentLine(token) && !isBeforeClosingParen(token)) { if (hasTrailingSpace(token)) { if (!requireSpaceAfter) { const tokenAfter = sourceCode.getTokenAfter(token); const loc = { start: token.loc.end, end: tokenAfter.loc.start }; context.report({ node, loc, messageId: "unexpectedWhitespaceAfter", fix(fixer) { return fixer.removeRange([token.range[1], tokenAfter.range[0]]); } }); } } else { if (requireSpaceAfter) { const loc = token.loc; context.report({ node, loc, messageId: "missingWhitespaceAfter", fix(fixer) { return fixer.insertTextAfter(token, " "); } }); } } } } } /** * Checks the spacing of the semicolon with the assumption that the last token is the semicolon. * @param {ASTNode} node The node to check. * @returns {void} */ function checkNode(node) { const token = sourceCode.getLastToken(node); checkSemicolonSpacing(token, node); } return { VariableDeclaration: checkNode, ExpressionStatement: checkNode, BreakStatement: checkNode, ContinueStatement: checkNode, DebuggerStatement: checkNode, ReturnStatement: checkNode, ThrowStatement: checkNode, ImportDeclaration: checkNode, ExportNamedDeclaration: checkNode, ExportAllDeclaration: checkNode, ExportDefaultDeclaration: checkNode, ForStatement(node) { if (node.init) { checkSemicolonSpacing(sourceCode.getTokenAfter(node.init), node); } if (node.test) { checkSemicolonSpacing(sourceCode.getTokenAfter(node.test), node); } } }; } };
(function(d){d['az']=Object.assign(d['az']||{},{a:"Image toolbar",b:"Table toolbar",c:"Sitat bloku",d:"ฦlaqษ™lษ™ndir",e:"BaลŸlฤฑqฤฑ seรง",f:"BaลŸlฤฑq",g:"media vidgeti",h:"Yarฤฑqalฤฑn",i:"Altdan xษ™tt",j:"Media ษ™lavษ™ ed",k:"URL boลŸ olmamalฤฑdฤฑr.",l:"Bu media URL dษ™stษ™klษ™nmir.",m:"Maili",n:"Nรถmrษ™lษ™nmiลŸ siyahฤฑ",o:"Markerlษ™nmiลŸ siyahฤฑ",p:"ลžษ™kil vidgetฤฑ",q:"ลžษ™kili ษ™lavษ™ et",r:"ลžษ™kili serverษ™ yรผklษ™",s:"Tam รถlรงรผlรผ ลŸษ™kili",t:"Yan ลŸษ™kil",u:"Soldan dรผzlษ™ndir",v:"Mษ™rkษ™zษ™ dรผzlษ™ndir",w:"SaฤŸdan dรผzlษ™ndir",x:"ลžษ™kil baลŸlฤฑฤŸฤฑ daxil edin",y:"Soldan dรผzlษ™ndir",z:"SaฤŸdan dรผzlษ™ndir",aa:"Mษ™rkษ™zษ™ dรผzlษ™ndir",ab:"Eninษ™ gรถrษ™",ac:"Mษ™tn dรผzlษ™ndirmษ™si",ad:"Text alignment toolbar",ae:"Cษ™dvษ™li ษ™lavษ™ et",af:"BaลŸlฤฑqlฤฑ sรผtun",ag:"Sola sรผtun ษ™lavษ™ et",ah:"SaฤŸa sรผtun ษ™lavษ™ et",ai:"Sรผtunlarฤฑ sil",aj:"Sรผtun",ak:"BaลŸlฤฑqlฤฑ sษ™tir",al:"Yuxarฤฑya sษ™tir ษ™lavษ™ et",am:"AลŸaฤŸฤฑya sษ™tir ษ™lavษ™ et",an:"Sษ™tirlษ™ri sil",ao:"Sษ™tir",ap:"Xanalarฤฑ yuxarฤฑ birlษ™ลŸdir",aq:"Xanalarฤฑ saฤŸa birlษ™ลŸdir",ar:"Xanalarฤฑ aลŸaฤŸฤฑ birlษ™ลŸdir",as:"Xanalarฤฑ sola birlษ™ลŸdir",at:"Xanalarฤฑ ลŸaquli bรถl",au:"Xanalarฤฑ รผfรผqi bรถl",av:"Xanalarฤฑ birlษ™ลŸdir",aw:"Formatฤฑ Lษ™ฤŸv Et",ax:"Increase indent",ay:"Decrease indent",az:"Widget toolbar",ba:"Yรผklษ™nir",bb:"Open in a new tab",bc:"Downloadable",bd:"Alternativ mษ™tni redaktษ™ et",be:"ลžrift ailษ™si",bf:"Default",bg:"ลžrift Rษ™ngi",bh:"ลžrift รถlรงรผsรผ",bi:"Miniatรผr",bj:"Kiรงik",bk:"Bรถyรผk",bl:"Nษ™hษ™ng",bm:"ลžrift Fonunun Rษ™ngi",bn:"Linki sil",bo:"Linki redaktษ™ et",bp:"Linki yeni pษ™ncษ™rษ™dษ™ aรง",bq:"Bu linkdษ™ URL yoxdur",br:"Yadda saxla",bs:"ฤฐmtina et",bt:"Linkin URL",bu:"Rich Text Redaktoru",bv:"Dropdown toolbar",bw:"%0 (Cษ™mi %1)",bx:"ฦvvษ™lki",by:"Nรถvbษ™ti",bz:"Qara",ca:"Tรผnd boz",cb:"Boz",cc:"Aรงฤฑq boz",cd:"AฤŸ",ce:"Qฤฑrmฤฑzฤฑ",cf:"Narฤฑncฤฑ",cg:"Sarฤฑ",ch:"Aรงฤฑq yaลŸฤฑl",ci:"YaลŸฤฑl",cj:"Akvamarin",ck:"Firuzษ™yi",cl:"Aรงฤฑq mavi",cm:"Mavi",cn:"Bษ™nรถvลŸษ™yi",co:"Rษ™ngi lษ™ฤŸv et",cp:"Document colors",cq:"Editor toolbar",cr:"Alternativ mษ™tn",cs:"ฤฐmtina et",ct:"Tษ™krar et",cu:"Abzas",cv:"BaลŸlฤฑq 1",cw:"BaลŸlฤฑq 2",cx:"BaลŸlฤฑq 3",cy:"BaลŸlฤฑq 4",cz:"BaลŸlฤฑq 5",da:"BaลŸlฤฑq 6",db:"Media URL-ni xanaya ษ™lavษ™ edin",dc:"Mษ™slษ™hษ™t: Sรผrษ™tli qoลŸma รผรงรผn URL-i kontentษ™ ษ™lavษ™ edin",dd:"Media URL",de:"Rich Text Redaktoru, %0"})})(window.CKEDITOR_TRANSLATIONS||(window.CKEDITOR_TRANSLATIONS={}));
# -*- coding: utf-8 -*- """ Tencent is pleased to support the open source community by making GameAISDK available. This source code file is licensed under the GNU General Public License Version 3. For full details, please refer to the file "LICENSE.txt" which is provided as part of this source code package. Copyright (C) 2020 THL A29 Limited, a Tencent company. All rights reserved. """ import json import logging LOG = logging.getLogger('IOService') def load_json_file(file_name): try: with open(file_name, 'r') as f: content = json.load(f) return content except Exception as err: LOG.error("read the file err, file_name:{}, err:{}".format(file_name, err)) return {}
import imp heap = imp.load_source('heap.py', './../../heap/python/heap.py') class HuffmanNode(object): # main properties in a node is the character and its frequency def __init__(self, char=None, freq=None, left=None, right=None): self.char = char self.freq = freq self.left = left self.right = right # returns the list of HuffmanNode def get_char_list(string): # count the frequency of each character mapp = dict() for s in string: if s in mapp: val = mapp.get(s) val += 1 mapp[s] = val # first occurrence else: mapp[s] = 1 # get the list chars_list = list() # iterate over the mapp and construct the listof HuffmanNode for key in mapp: chars_list.append(HuffmanNode(key, mapp[key])) # return the chars_list return chars_list def construct_huffman_tree(chars_list): # construct the huffman tree for prefix code # make a min-heap chars_list.sort(key=lambda x: x.freq) print [i.char for i in chars_list] print [i.freq for i in chars_list] # appending an extra object in beginnig coz my lib works so temp = ['empty'] + chars_list # constructing the minheap using the temp list min_heap = heap.MinHeap(len(temp)-1, temp) min_heap.build_minheap('freq') # now, iterate over the minheap and construct the huffman tree # we need to iterate n-1 times coz in each step we are merging two nodes # and thus at end 1 node will be left and we need to stop merging there # for i in xrange(1, len(temp)-1): min_heap.print_heap('char') while min_heap.get_heap_size() > 1: # allocate a space for a new node z = HuffmanNode() # make left child of tree node by extracting the minimum from the heap z.left = min_heap.extract_min() # print 'x.char:', x.char min_heap.print_heap('char') # make the right clid z.right = min_heap.extract_min() # print 'y.char:', y.char # add the above two node into the heap i.e. update the frequency z.freq = z.left.freq + z.right.freq # now insert the updated z into the heap min_heap.insert_key(z, 'freq') # now there will be just one object in minheap, so return it as it will be # the root in the huffman tree print 'heap:', min_heap.print_heap('freq') return min_heap.extract_min() def inorder(root): if root is not None: inorder(root.left) print root.char, inorder(root.right) def preorder(root): if root is not None: print root.char, preorder(root.left) preorder(root.right) def postorder(root): if root is not None: postorder(root.left) postorder(root.right) print root.char, # if you don't understand below code snippet then you need to study recursion # and backtracking def print_code(root, prefix): # base case if root.left is None and root.right is None and root.char.isalpha(): print root.char + ' : ' + prefix return # forming two branches, assigning left child to 0 and right child to 1 print_code(root.left, prefix+'0') print_code(root.right, prefix+'1') if __name__ == '__main__': string = 'a'*45+'b'*13+'c'*12+'d'*16+'e'*9+'f'*5 chars_list = get_char_list(string) root_node = construct_huffman_tree(chars_list) print 'amit:', root_node.freq inorder(root_node) print preorder(root_node) print postorder(root_node) print print_code(root_node, '')
function solve(area, vol, input) { const shapes = JSON.parse(input); const result = []; for (const shape of shapes) { const shapeArea = area.apply(shape); const shapeVol = vol.apply(shape); result.push({ area: shapeArea, volume: shapeVol }); } return result; } function area() { return Math.abs(this.x * this.y); }; function vol() { return Math.abs(this.x * this.y * this.z); }; console.log(solve(area, vol, `[ {"x":"1","y":"2","z":"10"}, {"x":"7","y":"7","z":"10"}, {"x":"5","y":"2","z":"10"}]`)); console.log(solve(area, vol, `[ {"x":"10","y":"-22","z":"10"}, {"x":"47","y":"7","z":"-5"}, {"x":"55","y":"8","z":"0"}, {"x":"100","y":"100","z":"100"}, {"x":"55","y":"80","z":"250"}]`));
import Maybe from '../maybe'; /** * @ignore */ export default x => x instanceof Maybe;
export default { path: 'lecturer', component: () => import(/* webpackChunkName: "lecturer-list" */ '@/pages/lecturer/LecturerList'), meta: {title:'่ฎฒๅธˆ็ฎก็†'} }
'use strict'; var blacklist = ['and', 'or', 'so', 'as', 'if', 'the', 'a', 'an', 'at', 'by', 'in', 'of', 'on', 'to']; // Given a string, returns a set of words that aren't in the blacklist of articles/prepositions/conjunctions exports.importantWords = function(str, removePunctuation) { var words = str.split(/[ -]/); var wordList = []; for (var i = 0; i < words.length; i++ ) { // remove punctuation to prevent double counting of words like fire's and fire,s if (removePunctuation) { words[i] = words[i].replace(/[\W_]/g, ''); } if ((words[i].length <= 3 && blacklist.indexOf(words[i]) !== -1) || // ignore if blacklisted wordList.indexOf(words[i]) !== -1) { // or already in word list continue; } wordList.push(words[i]); } return wordList; }; // Shuffle the topic list in-place using Knuth shuffle exports.shuffleWords = function (words) { for (var i = words.length - 2; i > 0; i--) { var j = Math.floor(Math.random() * i); var temp = words[j]; words[j] = words[i]; words[i] = temp; } return words; };
from django.urls import path from . import views as users_views urlpatterns = [ path('edit_profile/', users_views.edit_profile, name='edit-user-profile'), path('profile/', users_views.profile, name='user-profile'), path('add_money/', users_views.add_money, name='add-money'), path('send_money/', users_views.transfer_money, name='transfer-money'), path('transfers/', users_views.transfer_history, name='user-transfers'), path('payments/', users_views.add_to_wallet_history, name='user-payments'), ]
import sqlite3 import os import sys from pathlib import Path from hashlib import sha256 sys.path.append(os.path.dirname(__file__) + '/library') def saveimg(id, dataURL, parent_id, script_by): db_path = Path(os.path.dirname(__file__) + '/../../store/database/images.db') script_by = os.path.basename(script_by) hash = sha256(dataURL.encode('utf-8')).hexdigest() con = sqlite3.connect(db_path) cur = con.cursor() cur.execute('SELECT id, hash FROM Image WHERE hash = ?', [hash]) img = cur.fetchone() if img == None: cur.execute('INSERT INTO Image (id, dataURL, hash, parent_id, script_by) VALUES (?, ?, ?, ?, ?)', [id, dataURL, hash, parent_id, script_by]) con.commit() else: print(img[0]) con.close()
import {createRequire as __cjsCompatRequire} from 'module'; const require = __cjsCompatRequire(import.meta.url); const __ESM_IMPORT_META_URL__ = import.meta.url; import { ConsoleLogger, LogLevel } from "../chunk-LX5Q27EF.js"; import { SourceFile, SourceFileLoader } from "../chunk-EIFOOEXQ.js"; import { LogicalFileSystem, LogicalProjectPath, NgtscCompilerHost, NodeJSFileSystem, absoluteFrom, absoluteFromSourceFile, basename, dirname, getFileSystem, getSourceFileOrError, isLocalRelativePath, isRoot, isRooted, join, relative, relativeFrom, resolve, setFileSystem, toRelativeImport } from "../chunk-CLV7JFJQ.js"; import "../chunk-GMSUYBZP.js"; export { ConsoleLogger, LogLevel, LogicalFileSystem, LogicalProjectPath, NgtscCompilerHost, NodeJSFileSystem, SourceFile, SourceFileLoader, absoluteFrom, absoluteFromSourceFile, basename, dirname, getFileSystem, getSourceFileOrError, isLocalRelativePath, isRoot, isRooted, join, relative, relativeFrom, resolve, setFileSystem, toRelativeImport }; /** * @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 */ //# sourceMappingURL=localize.js.map
const router = require('express').Router(); let Exercise = require('../models/exercise.model'); // route to get all router.route('/').get((req, res) => { Exercise.find() .then(exercises => res.json(exercises)) .catch(err => res.status(400).json('Error: ' + err)); }); // route to add new router.route('/add').post((req, res) => { const username = req.body.username; const description = req.body.description; const duration = Number(req.body.duration); const date = Date.parse(req.body.date); const newExercise = new Exercise({ username, description, duration, date, }); newExercise.save() .then(() => res.json('Exercise added!')) .catch(err => res.status(400).json('Error: ' + err)); }); // route to get by id router.route('/:id').get((req, res) => { Exercise.findById(req.params.id) .then(exercise => res.json(exercise)) .catch(err => res.status(400).json('Error: ' + err)); }); // route to delete by id router.route('/:id').delete((req, res) => { Exercise.findByIdAndDelete(req.params.id) .then(() => res.json('Exercise deleted.')) .catch(err => res.status(400).json('Error: ' + err)); }); // route to update by id router.route('/update/:id').post((req, res) => { Exercise.findById(req.params.id) .then(exercise => { exercise.username = req.body.username; exercise.description = req.body.description; exercise.duration = Number(req.body.duration); exercise.date = Date.parse(req.body.date); exercise.save() .then(() => res.json('Exercise updated!')) .catch(err => res.status(400).json('Error: ' + err)); }) .catch(err => res.status(400).json('Error: ' + err)); }); module.exports = router;
"use strict"; /** * -------------------------------------------------------------------------------------------------------------------------------------- * Utility methods used by TurboBuilder * -------------------------------------------------------------------------------------------------------------------------------------- */ /** * Check that the specified value is found inside an array */ function inArray(value, array){ for(var i = 0; i < array.length; i++){ if(array[i] === value){ return true; } } return false; } /** * Check if the specified file or folder exists or not */ function fileExists(path){ try{ var f = new java.io.File(path); return f.exists(); }catch(e){ // Nothing to do } return false; } /** * Load all the file contents and return it as a string */ function loadFileAsString(path, replaceWhiteSpaces){ var file = new java.io.File(path); var fr = new java.io.FileReader(file); var br = new java.io.BufferedReader(fr); var line; var lines = ""; while((line = br.readLine()) != null){ if(replaceWhiteSpaces){ lines = lines + line.replace(" ", ""); }else{ lines = lines + line; } } return lines; } /** * Get a list with all the first level folders inside the specified path. * * @param path A full file system path from which we want to get the list of first level folders * * @returns An array containing all the first level folders inside the given path. Each array element will be * relative to the provided path. For example, if we provide "src/main" as path, * resulting folders may be like "php", "css", ... and so. */ function getFoldersList(path){ var ds = project.createDataType("dirset"); ds.setDir(new java.io.File(path)); ds.setIncludes("*"); var srcFolders = ds.getDirectoryScanner(project).getIncludedDirectories(); var result = []; for(var i = 0; i < srcFolders.length; i++){ result.push(srcFolders[i]); } return result; } /** * Get a list with all the files inside the specified path and all of its subfolders. * * @param path A full file system path from which we want to get the list of files * @param includes comma- or space-separated list of patterns of files that must be included; all files are included when omitted. * @param excludes comma- or space-separated list of patterns of files that must be excluded; no files (except default excludes) are excluded when omitted. * * @returns An array containing all the matching files inside the given path and subfolders. Each array element will be * the full filename plus the relative path to the provided path. For example, if we provide "src/main" as path, * resulting files may be like "php/managers/BigManager.php", ... and so. */ function getFilesList(path, includes, excludes){ // Init default vars values includes = (includes === undefined || includes == null || includes == '') ? "**" : includes; excludes = (excludes === undefined || excludes == null || excludes == '') ? "" : excludes; var fs = project.createDataType("fileset"); fs.setDir(new java.io.File(path)); if(includes != ""){ fs.setIncludes(includes); } if(excludes != ""){ fs.setExcludes(excludes); } var srcFiles = fs.getDirectoryScanner(project).getIncludedFiles(); var result = []; for(var i = 0; i < srcFiles.length; i++){ result.push(srcFiles[i]); } return result; } /** * Copy all the contents from the given folder to another specified folder. * * @param source A file system path where the files and folders to copy are found. * @param dest A file system path where the source files and folders will be copied. * * @returns void */ function copyFolderTo(source, dest){ var fs = project.createDataType("fileset"); fs.setDir(new java.io.File(source)); var copy = project.createTask("copy"); copy.setTodir(new java.io.File(dest)); copy.setOverwrite(true); copy.addFileset(fs); copy.perform(); } /** * Copy the specified file to the specified folder. * * @param source A file system path including the filename that will be copied * @param dest A file system path where the file will be copied. * * @returns void */ function copyFileTo(source, dest){ var copy = project.createTask("copy"); copy.setFile(new java.io.File(source)); copy.setTodir(new java.io.File(dest)); copy.setOverwrite(true); copy.perform(); } /** * Create a file with the specified content * * @param path Full path including the file name to be created * @param contents String containing the text to be written to the file * * @returns void */ function createFile(path, contents){ var touch = project.createTask("touch"); touch.setFile(new java.io.File(path)); touch.perform(); var echo = project.createTask("echo"); echo.setFile(new java.io.File(path)); echo.setMessage(contents); echo.perform(); } /** * change the name of a file * * @param from Full path including the file name to be renamed * @param to Full path including the file name that will be assigned * * @returns void */ function renameFile(from, to){ var move = project.createTask("move"); move.setFile(new java.io.File(from)); move.setTofile(new java.io.File(to)); move.perform(); } /** * Open an url with the specified browser * * @param url Url to open * @param browserExecutable Full path to the browser executable * * @returns void */ function launchOnBrowser(url, browserExecutable){ var exec = project.createTask("exec"); exec.setExecutable(browserExecutable); exec.setSpawn(true); exec.createArg().setLine(encodeURI(url)); exec.perform(); }
const http = require("http"); const server = http.createServer(); const url = require("url"); const rp=require('request-promise'); const remoteUrl = "http://news-at.zhihu.com" server.on('request', function(req, res) { var urlOption = url.parse(req.url); var pathName = urlOption.pathname; if (/^\/api/.test(pathName)) { proxyServer(remoteUrl+pathName,(data)=>{ res.setHeader("Access-Control-Allow-Origin", "*"); res.setHeader('Content-Type','text/javascript;charset=UTF-8'); res.end(data); }) } else if (/\.(jpg|png)$/.test(pathName)) { const remoteImage = "pic1.zhimg.com"; let headers = { "Referer": "https://daily.zhihu.com/" }; let opt = { hostname: remoteImage, port: '80', path: pathName, headers: headers } let request = http.request(opt); request.on('response', function(response) { var c = ""; response.setEncoding('binary'); response.on('data', function(chunk) { c += chunk; }); response.on('end', function() { res.writeHead(200, response.headers); res.write(c, "binary"); res.end(""); }) }); request.on("error", function(err) { console.error(err); }) request.end(); } }); server.listen(8080, function() { console.log("server on port 8080"); }); function proxyServer(url,callback){ rp(url).then(res=>{ callback(res); }) }
export { SegmentsData as default } from './segments-data'
import os from tqdm import tqdm import torch from torch import nn from network import C3D_model from glob import glob import cv2 import numpy as np device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") def center_crop(frame): frame = frame[8:120, 30:142, :] return np.array(frame).astype(np.uint8) def load_annos(annos_file): gts = [] with open(annos_file, 'r') as f: for line in f.readlines(): line = line.strip() for bin in line: gts.append(int(bin)) print(len(gts)) for i in range(15): gts.pop(0) print(len(gts)) return gts num_classes = 2 dataset = 'ucf101' load_from = 'run/run_29/models/C3D-ucf101_epoch-199.pth.tar' data_dirs = 'data/test_videos' model = C3D_model.C3D(num_classes=num_classes) checkpoint = torch.load(load_from) model.load_state_dict(checkpoint['state_dict']) model.to(device) model.eval() running_corrects = 0.0 results = [] video = 'test_recall_acc/test.mp4' annos_file = 'test_recall_acc/list_.txt' cap = cv2.VideoCapture(video) retaining = True gts = load_annos(annos_file) clip = [] index = 0 while retaining: retaining, frame = cap.read() if not retaining and frame is None: continue tmp_ = center_crop(cv2.resize(frame, (171, 128))) tmp = tmp_ - np.array([[[90.0, 98.0, 102.0]]]) clip.append(tmp) if len(clip) == 16: inputs = np.array(clip).astype(np.float32) inputs = np.expand_dims(inputs, axis=0) inputs = np.transpose(inputs, (0, 4, 1, 2, 3)) inputs = torch.from_numpy(inputs) inputs = torch.autograd.Variable(inputs, requires_grad=False).to(device) with torch.no_grad(): outputs = model.forward(inputs) probs = torch.nn.Softmax(dim=1)(outputs) # print(probs) label = torch.max(probs, 1)[1].detach().cpu().numpy()[0] results.append(label) clip.pop(0) print(index, label, gts[index]) index += 1 gts = np.array(gts) results = np.array(results) l = min(len(gts), len(results)) gts = gts[:l] results = results[:l] file = open('./test_recall_acc/list_results.txt','w'); file.write(str(results)); file.close(); print("[test] Acc: {}".format(np.mean((results+gts==2)+(results+gts==0)))) print('recall: ', np.sum(results+gts==2)/np.sum(gts==1))
from cc3d.core.PySteppables import * class diffusion_steady_state_ext_potential_3DSteppable(SteppableBasePy): def __init__(self,frequency=1): SteppableBasePy.__init__(self,frequency) def start(self): """ any code in the start function runs before MCS=0 """ def step(self,mcs): """ type here the code that will run every frequency MCS :param mcs: current Monte Carlo step """ def finish(self): """ Finish Function is called after the last MCS """
import sys import logging from os.path import dirname from xmediusmailrelayserver import server def install_service(argv): new_argv = [dirname(__file__)] for arg in argv: new_argv.append(arg) from xmediusmailrelayserver.servicehelpers import handle_command_line handle_command_line(new_argv) def main(): stdout_handler = logging.StreamHandler(sys.stdout) logging.getLogger('').setLevel(logging.INFO) logging.getLogger('mail.log').addHandler(stdout_handler) logging.getLogger('XMediusMailRelayServer').addHandler(stdout_handler) server.start_server() if __name__ == "__main__": main() input("Press Enter to quit")
import math import itertools import time from MatrixOperations import convert_coo_to_csc_and_csr from scipy import sparse class BaselineRecommendations: def __init__(self, dataset): # Load the sparse matrix from a file self.training_filepath = 'matrices/{}_training.npz'.format(dataset) self.testing_filepath = 'matrices/{}_test.npz'.format(dataset) self.training_matrix_coo = self.load_sparse_matrix(self.training_filepath) self.test_matrix_coo = self.load_sparse_matrix(self.testing_filepath) self.training_matrix_csr = None self.test_matrix_csr = None self.training_matrix_csc = None self.test_matrix_csc = None self.baseline_rating = {} self.movie_centered = {} self.user_centered = {} self.global_mean = 0.0 def load_sparse_matrix(self, file_name): return sparse.load_npz(file_name) def calculate_baseline_RMSE(self): summed_error = 0 # Loop through each entry in the test dataset for movie, user, true_rating in itertools.izip(self.test_matrix_coo.row, self.test_matrix_coo.col, self.test_matrix_coo.data): # Get the baseline rating for this movie in the test set movie_baseline = self.movie_centered[movie] # Get the baseline rating for this user in the test set user_baseline = self.user_centered[user] estimated_rating = movie_baseline + user_baseline + self.global_mean self.baseline_rating[(movie, user)] = estimated_rating # Calculate the error between the predicted rating and the true rating summed_error = summed_error + self.calculate_error_test(estimated_rating, true_rating) # Calculate the number of entries in the test set test_dataset_size = self.test_matrix_coo.nnz # Compute the RMSE on the test set rmse = math.sqrt(float(summed_error) / test_dataset_size) return rmse def calculate_error_test(self, estimated_rating, true_rating): error = math.pow(true_rating - estimated_rating, 2) return error def calculate_global_baseline_rating(self): summed_movie_rating = 0 for i, j, v in itertools.izip(self.training_matrix_coo.row, self.training_matrix_coo.col, self.training_matrix_coo.data): summed_movie_rating = summed_movie_rating + v number_of_ratings = self.training_matrix_coo.nnz self.global_mean = float(summed_movie_rating) / number_of_ratings def calculate_relative_mean_movie_rating(self): # Calculate the mean of each movie movie_sums = self.training_matrix_csr.sum(axis=1) # Calculate the number of ratings for each movie movie_rating_counts = self.training_matrix_csr.getnnz(axis=1) # Loop through each movie number_of_movies = self.training_matrix_csr.shape[0] for index in xrange(1, number_of_movies): # Check to see if the movie has not been rated if movie_sums[index] != 0: movie_average = float(movie_sums[index]) / movie_rating_counts[index] self.movie_centered[index] = movie_average - self.global_mean else: self.movie_centered[index] = 0 def calculate_mean_user_rating(self): # Calculate the mean of each user user_sums = self.training_matrix_csc.sum(axis=0) # Reshape the matrix to array form for proper indexing user_sums = user_sums.reshape((user_sums.size, 1)) # Calculate the number of ratings for each user user_rating_counts = self.training_matrix_csc.getnnz(axis=0) # Loop through each user number_of_users = self.training_matrix_csc.shape[1] for index in xrange(1, number_of_users): # Check to see if the user has not rated if user_sums[index] != 0: user_average = float(user_sums[index]) / user_rating_counts[index] self.user_centered[index] = user_average - self.global_mean else: self.user_centered[index] = 0 def calculate_baseline_error(self): start = time.time() self.calculate_global_baseline_rating() end = time.time() print "Time to calculate global movie mean: " + str((end - start)) start = time.time() self.calculate_relative_mean_movie_rating() end = time.time() print "Time to calculate mean movie ratings: " + str((end - start)) start = time.time() self.calculate_mean_user_rating() end = time.time() print "Time to calculate mean user ratings: " + str((end - start)) start = time.time() rmse = self.calculate_baseline_RMSE() end = time.time() print "Time to calculate RMSE: " + str((end - start)) return rmse def run_baseline(self): self.training_matrix_csc, self.training_matrix_csr = convert_coo_to_csc_and_csr(self.training_matrix_coo) self.test_matrix_csc, self.test_matrix_csr = convert_coo_to_csc_and_csr(self.test_matrix_coo) print "Finished converting to csc and csr" rmse = self.calculate_baseline_error() print "RMSE Baseline: " + str(rmse) if __name__ == '__main__': start_time = time.time() print "Running Baseline Estimate on Random Dataset" dataset = 'random' random_training_filepath = 'matrices/{}_training.npz'.format(dataset) random_testing_filepath = 'matrices/{}_test.npz'.format(dataset) random_test = sparse.load_npz(random_testing_filepath) random_training = sparse.load_npz(random_training_filepath) random_baseline = BaselineRecommendations(random_training,random_test) random_baseline.run_baseline() print "Baseline Estimate on Random Dataset done in {} seconds".format(time.time() - start_time) start_time = time.time() print "Running Baseline Estimate on Arbitrary Dataset" dataset = 'arbitrary' arbitrary_training_filepath = 'matrices/{}_training.npz'.format(dataset) arbitrary_testing_filepath = 'matrices/{}_test.npz'.format(dataset) arbitrary_test = sparse.load_npz(arbitrary_testing_filepath) arbitrary_training = sparse.load_npz(arbitrary_training_filepath) arbitrary_baseline = BaselineRecommendations(arbitrary_training, arbitrary_test) arbitrary_baseline.run_baseline() print "Baseline Estimate on Random Dataset done in {} seconds".format(time.time() - start_time)
""" ANTLR 4.x listener and visitor implementation for intermediate code generation (Three addresses code) @author: Morteza Zakeri, (http://webpages.iust.ac.ir/morteza_zakeri/) @date: 20201017 - Compiler generator: ANTRL4.x - Target language(s): Python3.x, -Changelog: -- v2.1.0 --- Add support for AST intermediate representation using module `ast_pass` --- Change `compiler_pass` module to `three_address_code_pass` -- v2.0.0 --- Add attributes for grammar rules which are used to hold type and intermediate language_apps of rules. - Reference: Compiler book by Dr. Saeed Parsa (http://parsa.iust.ac.ir/) - Course website: http://parsa.iust.ac.ir/courses/compilers/ - Laboratory website: http://reverse.iust.ac.ir/ """ __version__ = '0.1.0' __author__ = 'Morteza' from language_apps.assignment_statement_v2.gen.AssignmentStatement2Listener import AssignmentStatement2Listener from language_apps.assignment_statement_v2.gen.AssignmentStatement2Visitor import AssignmentStatement2Visitor from language_apps.assignment_statement_v2.gen.AssignmentStatement2Parser import AssignmentStatement2Parser # ---------------------- # Listener pattern class ThreeAddressCodeGeneratorListener(AssignmentStatement2Listener): """ Type checking and generating three address language_apps (not optimized) """ def __init__(self): print('Listener call!') self.temp_counter = 0 def create_temp(self): self.temp_counter += 1 return 'T' + str(self.temp_counter) # ------------------ # Rule number def exitNumber_float(self, ctx: AssignmentStatement2Parser.Number_floatContext): ctx.type_attr = 'float' ctx.value_attr = float(ctx.getText()) def exitNumber_int(self, ctx: AssignmentStatement2Parser.Number_intContext): ctx.type_attr = 'int' ctx.value_attr = int(ctx.getText()) # ------------------ # Rule factor def exitFact_expr(self, ctx: AssignmentStatement2Parser.Fact_exprContext): ctx.type_attr = ctx.expr().type_attr ctx.value_attr = ctx.expr().value_attr def exitFact_id(self, ctx: AssignmentStatement2Parser.Fact_idContext): ctx.type_attr = 'string' ctx.value_attr = str(ctx.getText()) def exitFact_number(self, ctx: AssignmentStatement2Parser.Fact_numberContext): ctx.type_attr = ctx.number().type_attr ctx.value_attr = ctx.number().value_attr # ------------------ # Rule term def exitTerm_fact_mutiply(self, ctx: AssignmentStatement2Parser.Term_fact_mutiplyContext): if ctx.term().type_attr != ctx.factor().type_attr: print('Semantic error: Cannot multiply {0} and {1}'.format(ctx.term().type_attr, ctx.factor().type_attr)) quit(-1) else: if ctx.term().type_attr == 'float': ctx.type_attr = 'float' ctx.value_attr = ctx.term().value_attr * ctx.factor().value_attr elif ctx.term().type_attr == 'int': ctx.type_attr = 'int' ctx.value_attr = ctx.term().value_attr * ctx.factor().value_attr else: ctx.type_attr = 'string' ctx.value_attr = self.create_temp() print('{0} = {1} * {2}'.format(ctx.value_attr, ctx.term().value_attr, ctx.factor().value_attr)) def exitTerm_fact_divide(self, ctx: AssignmentStatement2Parser.Term_fact_mutiplyContext): if ctx.term().type_attr != ctx.factor().type_attr: print('Semantic error: Cannot divide {0} and {1}'.format(ctx.term().type_attr, ctx.factor().type_attr)) quit(-1) else: if ctx.term().type_attr == 'float': ctx.type_attr = 'float' ctx.value_attr = ctx.term().value_attr / ctx.factor().value_attr elif ctx.term().type_attr == 'int': ctx.type_attr = 'int' ctx.value_attr = int(ctx.term().value_attr / ctx.factor().value_attr) else: ctx.type_attr = 'string' ctx.value_attr = self.create_temp() print('{0} = {1} / {2}'.format(ctx.value_attr, ctx.term().value_attr, ctx.factor().value_attr)) def exitFactor3(self, ctx: AssignmentStatement2Parser.Factor3Context): ctx.type_attr = ctx.factor().type_attr ctx.value_attr = ctx.factor().value_attr # ------------------ # Rule expr def exitExpr_term_plus(self, ctx: AssignmentStatement2Parser.Expr_term_plusContext): if ctx.expr().type_attr != ctx.term().type_attr: print('Semantic error: Cannot plus {0} and {1}'.format(ctx.expr().type_attr, ctx.term().type_attr)) quit(-1) else: if ctx.term().type_attr == 'float': ctx.type_attr = 'float' ctx.value_attr = ctx.expr().value_attr + ctx.term().value_attr elif ctx.term().type_attr == 'int': ctx.type_attr = 'int' ctx.value_attr = ctx.expr().value_attr + ctx.term().value_attr else: ctx.type_attr = 'string' ctx.value_attr = self.create_temp() print('{0} = {1} + {2}'.format(ctx.value_attr, ctx.expr().value_attr, ctx.term().value_attr)) def exitExpr_term_minus(self, ctx: AssignmentStatement2Parser.Expr_term_minusContext): if ctx.expr().type_attr != ctx.term().type_attr: print('Semantic error: Cannot subtract {0} and {1}'.format(ctx.expr().type_attr, ctx.term().type_attr)) quit(-1) else: if ctx.term().type_attr == 'float': ctx.type_attr = 'float' ctx.value_attr = ctx.expr().value_attr - ctx.term().value_attr elif ctx.term().type_attr == 'int': ctx.type_attr = 'int' ctx.value_attr = ctx.expr().value_attr - ctx.term().value_attr else: ctx.type_attr = 'string' ctx.value_attr = self.create_temp() print('{0} = {1} - {2}'.format(ctx.value_attr, ctx.expr().value_attr, ctx.term().value_attr)) def exitTerm4(self, ctx: AssignmentStatement2Parser.Term4Context): ctx.type_attr = ctx.term().type_attr ctx.value_attr = ctx.term().value_attr # ------------------ # Rule expr def exitAssign(self, ctx: AssignmentStatement2Parser.AssignContext): ctx.type_attr = ctx.expr().type_attr ctx.value_attr = ctx.expr().value_attr print('Assign statement: "{0} = {1}"\nAssign type: "{2}"'.format(ctx.ID().getText(), ctx.value_attr, ctx.type_attr)) # ----- # Listener 2 class ThreeAddressCodeGenerator2Listener(AssignmentStatement2Listener): """ Type checking and generating three address language_apps (optimizing number of temporary variables) """ def __init__(self): print('Listener2 call!') self.temp_counter = 0 def create_temp(self): self.temp_counter += 1 return 'T' + str(self.temp_counter) def remove_temp(self): self.temp_counter -= 1 def get_temp(self): return 'T' + str(self.temp_counter) @classmethod def is_temp(cls, variable): if variable[0] == 'T': return True return False # ------------------ # Rule number def exitNumber_float(self, ctx: AssignmentStatement2Parser.Number_floatContext): ctx.type_attr = 'float' ctx.value_attr = float(ctx.getText()) def exitNumber_int(self, ctx: AssignmentStatement2Parser.Number_intContext): ctx.type_attr = 'int' ctx.value_attr = int(ctx.getText()) # ------------------ # Rule factor def exitFact_expr(self, ctx: AssignmentStatement2Parser.Fact_exprContext): ctx.type_attr = ctx.expr().type_attr ctx.value_attr = ctx.expr().value_attr def exitFact_id(self, ctx: AssignmentStatement2Parser.Fact_idContext): ctx.type_attr = 'string' ctx.value_attr = ctx.getText() def exitFact_number(self, ctx: AssignmentStatement2Parser.Fact_numberContext): ctx.type_attr = ctx.number().type_attr ctx.value_attr = ctx.number().value_attr # ------------------ # Rule term def exitTerm_fact_mutiply(self, ctx: AssignmentStatement2Parser.Term_fact_mutiplyContext): if ctx.term().type_attr != ctx.factor().type_attr: print('Semantic error: Cannot multiply {0} and {1}'.format(ctx.term().type_attr, ctx.factor().type_attr)) quit(-1) else: if ctx.term().type_attr == 'float': ctx.type_attr = 'float' ctx.value_attr = ctx.term().value_attr * ctx.factor().value_attr elif ctx.term().type_attr == 'int': ctx.type_attr = 'int' ctx.value_attr = ctx.term().value_attr * ctx.factor().value_attr else: ctx.type_attr = 'string' if self.is_temp(ctx.term().value_attr): ctx.value_attr = ctx.term().value_attr if self.is_temp(ctx.factor().value_attr): self.remove_temp() elif self.is_temp(ctx.factor().value_attr): ctx.value_attr = ctx.factor().value_attr else: ctx.value_attr = self.create_temp() print('{0} = {1} * {2}'.format(ctx.value_attr, ctx.term().value_attr, ctx.factor().value_attr)) def exitTerm_fact_divide(self, ctx: AssignmentStatement2Parser.Term_fact_mutiplyContext): if ctx.term().type_attr != ctx.factor().type_attr: print('Semantic error: Cannot divide {0} and {1}'.format(ctx.term().type_attr, ctx.factor().type_attr)) quit(-1) else: if ctx.term().type_attr == 'float': ctx.type_attr = 'float' ctx.value_attr = ctx.term().value_attr / ctx.factor().value_attr elif ctx.term().type_attr == 'int': ctx.type_attr = 'int' ctx.value_attr = int(ctx.term().value_attr / ctx.factor().value_attr) else: ctx.type_attr = 'string' if self.is_temp(ctx.term().value_attr): ctx.value_attr = ctx.term().value_attr if self.is_temp(ctx.factor().value_attr): self.remove_temp() elif self.is_temp(ctx.factor().value_attr): ctx.value_attr = ctx.factor().value_attr else: ctx.value_attr = self.create_temp() print('{0} = {1} / {2}'.format(ctx.value_attr, ctx.term().value_attr, ctx.factor().value_attr)) def exitFactor3(self, ctx: AssignmentStatement2Parser.Factor3Context): ctx.type_attr = ctx.factor().type_attr ctx.value_attr = ctx.factor().value_attr # ------------------ # Rule expr def exitExpr_term_plus(self, ctx: AssignmentStatement2Parser.Expr_term_plusContext): if ctx.expr().type_attr != ctx.term().type_attr: print('Semantic error: Cannot plus {0} and {1}'.format(ctx.expr().type_attr, ctx.term().type_attr)) quit(-1) else: if ctx.term().type_attr == 'float': ctx.type_attr = 'float' ctx.value_attr = ctx.expr().value_attr + ctx.term().value_attr elif ctx.term().type_attr == 'int': ctx.type_attr = 'int' ctx.value_attr = ctx.expr().value_attr + ctx.term().value_attr else: ctx.type_attr = 'string' if self.is_temp(ctx.expr().value_attr): ctx.value_attr = ctx.expr().value_attr if self.is_temp(ctx.term().value_attr): self.remove_temp() elif self.is_temp(ctx.term().value_attr): ctx.value_attr = ctx.term().value_attr else: ctx.value_attr = self.create_temp() print('{0} = {1} + {2}'.format(ctx.value_attr, ctx.expr().value_attr, ctx.term().value_attr)) def exitExpr_term_minus(self, ctx: AssignmentStatement2Parser.Expr_term_minusContext): if ctx.expr().type_attr != ctx.term().type_attr: print('Semantic error: Cannot subtract {0} and {1}'.format(ctx.expr().type_attr, ctx.term().type_attr)) quit(-1) else: if ctx.term().type_attr == 'float': ctx.type_attr = 'float' ctx.value_attr = ctx.expr().value_attr - ctx.term().value_attr elif ctx.term().type_attr == 'int': ctx.type_attr = 'int' ctx.value_attr = ctx.expr().value_attr - ctx.term().value_attr else: ctx.type_attr = 'string' if self.is_temp(ctx.expr().value_attr): ctx.value_attr = ctx.expr().value_attr if self.is_temp(ctx.term().value_attr): self.remove_temp() elif self.is_temp(ctx.term().value_attr): ctx.value_attr = ctx.term().value_attr else: ctx.value_attr = self.create_temp() print('{0} = {1} - {2}'.format(ctx.value_attr, ctx.expr().value_attr, ctx.term().value_attr)) def exitTerm4(self, ctx: AssignmentStatement2Parser.Term4Context): ctx.type_attr = ctx.term().type_attr ctx.value_attr = ctx.term().value_attr # ------------------ # Rule expr def exitAssign(self, ctx: AssignmentStatement2Parser.AssignContext): ctx.type_attr = ctx.expr().type_attr ctx.value_attr = ctx.expr().value_attr print('Assign statement: "{0} = {1}"\nAssign type: "{2}"'.format(ctx.ID().getText(), ctx.value_attr, ctx.type_attr)) # ------------------------------------------------------------------------ # Visitor pattern class ThreeAddressCodeGeneratorVisitor(AssignmentStatement2Visitor): """ Type checking and generating three address language_apps (not optimized regarding to the number of temporary variables) Utilizing ANTLR 4.x Visitor mechanism """ def __init__(self): print('Visitor call!') self.temp_counter = 0 def create_temp(self): self.temp_counter += 1 return 'T' + str(self.temp_counter) def visitStart(self, ctx: AssignmentStatement2Parser.StartContext): self.visit(tree=ctx.prog()) def visitProg(self, ctx: AssignmentStatement2Parser.ProgContext): if ctx.getChildCount() == 2: self.visit(tree=ctx.prog()) ctx.type_attr, ctx.value_attr = self.visit(tree=ctx.assign()) return ctx.type_attr, ctx.value_attr def visitAssign(self, ctx: AssignmentStatement2Parser.AssignContext): ctx.type_attr, ctx.value_attr = self.visit(tree=ctx.expr()) print('Assign statement: "{0} = {1}"\nAssign type: "{2}"'.format(ctx.ID().getText(), ctx.value_attr, ctx.type_attr)) return ctx.type_attr, ctx.value_attr # ------------------ # Rule expr def visitExpr_term_plus(self, ctx: AssignmentStatement2Parser.Expr_term_plusContext): ctx.expr().type_attr, ctx.expr().value_attr = self.visit(tree=ctx.expr()) ctx.term().type_attr, ctx.term().value_attr = self.visit(tree=ctx.term()) if ctx.expr().type_attr != ctx.term().type_attr: print('Semantic error: Cannot plus {0} and {1}'.format(ctx.expr().type_attr, ctx.term().type_attr)) quit(-1) else: if ctx.term().type_attr == 'float': ctx.type_attr = 'float' ctx.value_attr = ctx.expr().value_attr + ctx.term().value_attr elif ctx.term().type_attr == 'int': ctx.type_attr = 'int' ctx.value_attr = ctx.expr().value_attr + ctx.term().value_attr else: ctx.type_attr = 'string' ctx.value_attr = self.create_temp() print('{0} = {1} + {2}'.format(ctx.value_attr, ctx.expr().value_attr, ctx.term().value_attr)) return ctx.type_attr, ctx.value_attr def visitExpr_term_minus(self, ctx: AssignmentStatement2Parser.Expr_term_minusContext): ctx.expr().type_attr, ctx.expr().value_attr = self.visit(tree=ctx.expr()) ctx.term().type_attr, ctx.term().value_attr = self.visit(tree=ctx.term()) if ctx.expr().type_attr != ctx.term().type_attr: print('Semantic error: Cannot plus {0} and {1}'.format(ctx.expr().type_attr, ctx.term().type_attr)) quit(-1) else: if ctx.term().type_attr == 'float': ctx.type_attr = 'float' ctx.value_attr = ctx.expr().value_attr - ctx.term().value_attr elif ctx.term().type_attr == 'int': ctx.type_attr = 'int' ctx.value_attr = ctx.expr().value_attr - ctx.term().value_attr else: ctx.type_attr = 'string' ctx.value_attr = self.create_temp() print('{0} = {1} - {2}'.format(ctx.value_attr, ctx.expr().value_attr, ctx.term().value_attr)) return ctx.type_attr, ctx.value_attr def visitTerm4(self, ctx: AssignmentStatement2Parser.Term4Context): ctx.type_attr, ctx.value_attr = self.visit(ctx.term()) return ctx.type_attr, ctx.value_attr # ------------------ # Rule term def visitTerm_fact_mutiply(self, ctx: AssignmentStatement2Parser.Term_fact_mutiplyContext): ctx.term().type_attr, ctx.term().value_attr = self.visit(tree=ctx.term()) ctx.factor().type_attr, ctx.factor().value_attr = self.visit(tree=ctx.factor()) if ctx.term().type_attr != ctx.factor().type_attr: print('Semantic error: Cannot multiply {0} and {1}'.format(ctx.term().type_attr, ctx.factor().type_attr)) quit(-1) else: if ctx.term().type_attr == 'float': ctx.type_attr = 'float' ctx.value_attr = ctx.term().value_attr * ctx.factor().value_attr elif ctx.term().type_attr == 'int': ctx.type_attr = 'int' ctx.value_attr = ctx.term().value_attr * ctx.factor().value_attr else: ctx.type_attr = 'string' ctx.value_attr = self.create_temp() print('{0} = {1} * {2}'.format(ctx.value_attr, ctx.term().value_attr, ctx.factor().value_attr)) return ctx.type_attr, ctx.value_attr def visitTerm_fact_divide(self, ctx: AssignmentStatement2Parser.Term_fact_divideContext): ctx.term().type_attr, ctx.term().value_attr = self.visit(tree=ctx.term()) ctx.factor().type_attr, ctx.factor().value_attr = self.visit(tree=ctx.factor()) if ctx.term().type_attr != ctx.factor().type_attr: print('Semantic error: Cannot multiply {0} and {1}'.format(ctx.term().type_attr, ctx.factor().type_attr)) quit(-1) else: if ctx.term().type_attr == 'float': ctx.type_attr = 'float' ctx.value_attr = ctx.term().value_attr / ctx.factor().value_attr elif ctx.term().type_attr == 'int': ctx.type_attr = 'int' ctx.value_attr = int(ctx.term().value_attr / ctx.factor().value_attr) else: ctx.type_attr = 'string' ctx.value_attr = self.create_temp() print('{0} = {1} / {2}'.format(ctx.value_attr, ctx.term().value_attr, ctx.factor().value_attr)) return ctx.type_attr, ctx.value_attr def visitFactor3(self, ctx: AssignmentStatement2Parser.Factor3Context): ctx.type_attr, ctx.value_attr = self.visit(tree=ctx.factor()) return ctx.type_attr, ctx.value_attr # ------------------ # Rule factor def visitFact_expr(self, ctx: AssignmentStatement2Parser.Fact_exprContext): return self.visit(tree=ctx.expr()) def visitFact_id(self, ctx: AssignmentStatement2Parser.Fact_idContext): return 'string', ctx.ID().getText() def visitFact_number(self, ctx: AssignmentStatement2Parser.Fact_numberContext): return self.visit(tree=ctx.number()) # ------------------ # Rule number def visitNumber_float(self, ctx: AssignmentStatement2Parser.Number_floatContext): return 'float', float(ctx.FLOAT().getText()) def visitNumber_int(self, ctx: AssignmentStatement2Parser.Number_intContext): return 'int', int(ctx.INT().getText()) # Visitor pattern 2 class ThreeAddressCodeGenerator2Visitor(AssignmentStatement2Visitor): """ Type checking and generating three address language_apps (optimizing number of temporary variables) Utilizing ANTLR 4.x Visitor mechanism """ def __init__(self): print('Visitor2 call!') self.temp_counter = 0 def create_temp(self): self.temp_counter += 1 return 'T' + str(self.temp_counter) def remove_temp(self): self.temp_counter -= 1 def get_temp(self): return 'T' + str(self.temp_counter) @classmethod def is_temp(cls, variable): if variable[0] == 'T': return True return False def visitStart(self, ctx: AssignmentStatement2Parser.StartContext): self.visit(tree=ctx.prog()) def visitProg(self, ctx: AssignmentStatement2Parser.ProgContext): if ctx.getChildCount() == 2: self.visit(tree=ctx.prog()) ctx.type_attr, ctx.value_attr = self.visit(tree=ctx.assign()) return ctx.type_attr, ctx.value_attr def visitAssign(self, ctx: AssignmentStatement2Parser.AssignContext): ctx.type_attr, ctx.value_attr = self.visit(tree=ctx.expr()) print('Assign statement: "{0} = {1}"\nAssign type: "{2}"'.format(ctx.ID().getText(), ctx.value_attr, ctx.type_attr)) return ctx.type_attr, ctx.value_attr # ------------------ # Rule expr def visitExpr_term_plus(self, ctx: AssignmentStatement2Parser.Expr_term_plusContext): ctx.expr().type_attr, ctx.expr().value_attr = self.visit(tree=ctx.expr()) ctx.term().type_attr, ctx.term().value_attr = self.visit(tree=ctx.term()) if ctx.expr().type_attr != ctx.term().type_attr: print('Semantic error: Cannot plus {0} and {1}'.format(ctx.expr().type_attr, ctx.term().type_attr)) quit(-1) else: if ctx.term().type_attr == 'float': ctx.type_attr = 'float' ctx.value_attr = ctx.expr().value_attr + ctx.term().value_attr elif ctx.term().type_attr == 'int': ctx.type_attr = 'int' ctx.value_attr = ctx.expr().value_attr + ctx.term().value_attr else: ctx.type_attr = 'string' if self.is_temp(ctx.expr().value_attr): ctx.value_attr = ctx.expr().value_attr if self.is_temp(ctx.term().value_attr): self.remove_temp() elif self.is_temp(ctx.term().value_attr): ctx.value_attr = ctx.term().value_attr else: ctx.value_attr = self.create_temp() print('{0} = {1} + {2}'.format(ctx.value_attr, ctx.expr().value_attr, ctx.term().value_attr)) return ctx.type_attr, ctx.value_attr def visitExpr_term_minus(self, ctx: AssignmentStatement2Parser.Expr_term_minusContext): ctx.expr().type_attr, ctx.expr().value_attr = self.visit(tree=ctx.expr()) ctx.term().type_attr, ctx.term().value_attr = self.visit(tree=ctx.term()) if ctx.expr().type_attr != ctx.term().type_attr: print('Semantic error: Cannot plus {0} and {1}'.format(ctx.expr().type_attr, ctx.term().type_attr)) quit(-1) else: if ctx.term().type_attr == 'float': ctx.type_attr = 'float' ctx.value_attr = ctx.expr().value_attr - ctx.term().value_attr elif ctx.term().type_attr == 'int': ctx.type_attr = 'int' ctx.value_attr = ctx.expr().value_attr - ctx.term().value_attr else: ctx.type_attr = 'string' if self.is_temp(ctx.expr().value_attr): ctx.value_attr = ctx.expr().value_attr if self.is_temp(ctx.term().value_attr): self.remove_temp() elif self.is_temp(ctx.term().value_attr): ctx.value_attr = ctx.term().value_attr else: ctx.value_attr = self.create_temp() print('{0} = {1} - {2}'.format(ctx.value_attr, ctx.expr().value_attr, ctx.term().value_attr)) return ctx.type_attr, ctx.value_attr def visitTerm4(self, ctx: AssignmentStatement2Parser.Term4Context): ctx.type_attr, ctx.value_attr = self.visit(ctx.term()) return ctx.type_attr, ctx.value_attr # ------------------ # Rule term def visitTerm_fact_mutiply(self, ctx: AssignmentStatement2Parser.Term_fact_mutiplyContext): ctx.term().type_attr, ctx.term().value_attr = self.visit(tree=ctx.term()) ctx.factor().type_attr, ctx.factor().value_attr = self.visit(tree=ctx.factor()) if ctx.term().type_attr != ctx.factor().type_attr: print('Semantic error: Cannot multiply {0} and {1}'.format(ctx.term().type_attr, ctx.factor().type_attr)) quit(-1) else: if ctx.term().type_attr == 'float': ctx.type_attr = 'float' ctx.value_attr = ctx.term().value_attr * ctx.factor().value_attr elif ctx.term().type_attr == 'int': ctx.type_attr = 'int' ctx.value_attr = ctx.term().value_attr * ctx.factor().value_attr else: ctx.type_attr = 'string' if self.is_temp(ctx.term().value_attr): ctx.value_attr = ctx.term().value_attr if self.is_temp(ctx.factor().value_attr): self.remove_temp() elif self.is_temp(ctx.factor().value_attr): ctx.value_attr = ctx.factor().value_attr else: ctx.value_attr = self.create_temp() print('{0} = {1} * {2}'.format(ctx.value_attr, ctx.term().value_attr, ctx.factor().value_attr)) return ctx.type_attr, ctx.value_attr def visitTerm_fact_divide(self, ctx: AssignmentStatement2Parser.Term_fact_divideContext): ctx.term().type_attr, ctx.term().value_attr = self.visit(tree=ctx.term()) ctx.factor().type_attr, ctx.factor().value_attr = self.visit(tree=ctx.factor()) if ctx.term().type_attr != ctx.factor().type_attr: print('Semantic error: Cannot multiply {0} and {1}'.format(ctx.term().type_attr, ctx.factor().type_attr)) quit(-1) else: if ctx.term().type_attr == 'float': ctx.type_attr = 'float' ctx.value_attr = ctx.term().value_attr / ctx.factor().value_attr elif ctx.term().type_attr == 'int': ctx.type_attr = 'int' ctx.value_attr = int(ctx.term().value_attr / ctx.factor().value_attr) else: ctx.type_attr = 'string' if self.is_temp(ctx.term().value_attr): ctx.value_attr = ctx.term().value_attr if self.is_temp(ctx.factor().value_attr): self.remove_temp() elif self.is_temp(ctx.factor().value_attr): ctx.value_attr = ctx.factor().value_attr else: ctx.value_attr = self.create_temp() print('{0} = {1} / {2}'.format(ctx.value_attr, ctx.term().value_attr, ctx.factor().value_attr)) return ctx.type_attr, ctx.value_attr def visitFactor3(self, ctx: AssignmentStatement2Parser.Factor3Context): ctx.type_attr, ctx.value_attr = self.visit(tree=ctx.factor()) return ctx.type_attr, ctx.value_attr # ------------------ # Rule factor def visitFact_expr(self, ctx: AssignmentStatement2Parser.Fact_exprContext): return self.visit(tree=ctx.expr()) def visitFact_id(self, ctx: AssignmentStatement2Parser.Fact_idContext): return 'string', ctx.ID().getText() def visitFact_number(self, ctx: AssignmentStatement2Parser.Fact_numberContext): return self.visit(tree=ctx.number()) # ------------------ # Rule number def visitNumber_float(self, ctx: AssignmentStatement2Parser.Number_floatContext): return 'float', float(ctx.FLOAT().getText()) def visitNumber_int(self, ctx: AssignmentStatement2Parser.Number_intContext): return 'int', int(ctx.INT().getText())
from __future__ import unicode_literals from __future__ import print_function from __future__ import division from __future__ import absolute_import import argparse import logging import os import warnings import io from typing import Text from mynlu.config.mynluconfig import MyNLUConfig from tqdm import tqdm import requests logger = logging.getLogger(__name__) def create_argparser(): parser = argparse.ArgumentParser(description='parse download commands') parser.add_argument('-c', '--config', help="config file, all the command line options can also be passed via a (json-formatted) " + "config file. NB command line args take precedence") parser.add_argument('-p', '--package', help='package to be downloaded', choices=['mitie'], required=True) return parser def download_mitie_fe_file(fe_file): # pragma: no cover # type: (Text) -> None """Download the mitie feature extractor needed to run & train mitie classifiers. See https://github.com/mit-nlp/MITIE#initial-setup """ logger.info("Downloading MITIE feature extractor files") _fe_file_url = "https://s3-eu-west-1.amazonaws.com/mitie/total_word_feature_extractor.dat" logger.info("Downloading from {}".format(_fe_file_url)) response = requests.get(_fe_file_url, stream=True) with io.open(fe_file, "wb") as output: for data in tqdm(response.iter_content(chunk_size=1024*1024), unit='MB', unit_scale=True): output.write(data) logger.debug("file written! {0}, {1}".format(fe_file, os.path.exists(fe_file))) def download(config, pkg="mitie"): # pragma: no cover # type: (MyNLUConfig, Text) -> None if pkg == "mitie": download_mitie_fe_file(config.mitie_file) else: warnings.warn("Error. Package {0} not available for download.".format(pkg)) if __name__ == '__main__': logging.basicConfig(level=logging.INFO) parser = create_argparser() cmdline_args = {key: val for key, val in list(vars(parser.parse_args()).items()) if val is not None} config = MyNLUConfig(cmdline_args.get("config"), os.environ, cmdline_args) download(config, cmdline_args["package"])
import asyncio import logging from typing import Any, Dict, List, Tuple import aiohttp # from src.core.backends.poeofficial import PoeOfficial from src.core.backends.poetrade import PoeTrade from src.core.backends.task import Task from src.core.offer import Offer from src.trading.items import ItemList, UnsupportedItemException class BackendPoolWorker: backend: Any loop: asyncio.AbstractEventLoop results: List[Any] just_failed: bool work_index: Dict[int, Task] def __init__(self, backend: Any, loop: asyncio.AbstractEventLoop): self.backend = backend self.loop = loop self.results = [] self.counter = 0 self.just_failed = False self.work_index = dict() def pick_tasks(self, queue: asyncio.Queue, n_tasks: int) -> List[Task]: tasks: List[Task] = [] for i in range(n_tasks): try: task: Task = queue.get_nowait() self.backend.item_list.map_item(task.have, self.backend.name()) self.backend.item_list.map_item(task.want, self.backend.name()) tasks.append(task) except UnsupportedItemException: continue except asyncio.QueueEmpty: break if len(tasks) != n_tasks and not queue.empty(): tasks += self.pick_tasks(queue, n_tasks - len(tasks)) return tasks async def handle_error(self): if self.just_failed is True: logging.debug("Backend {} failed".format(self.backend.name())) self.just_failed = False async def work(self, queue: asyncio.Queue) -> List[Any]: client_session = aiohttp.ClientSession() while not queue.empty(): tasks = self.pick_tasks(queue, 10) futures = [] for i, task in enumerate(tasks): future = self.backend.fetch_offer_async(client_session, task) futures.append(future) self.work_index[i] = task self.counter = self.counter + 1 done = await asyncio.gather(*futures, return_exceptions=True) for idx, result in enumerate(done): if isinstance(result, Exception): failed_task = self.work_index[idx] if isinstance(result, UnsupportedItemException): logging.debug(result) else: logging.debug("{}: Reschedule task: {} -> {}".format( self.backend.name(), failed_task.have, failed_task.want)) logging.debug(result) queue.put_nowait(failed_task) self.counter = self.counter - 1 self.just_failed = True else: self.results.extend(result) self.work_index.clear() await self.handle_error() await client_session.close() return self.results class BackendPool: backends: List[BackendPoolWorker] item_list: ItemList queue: asyncio.Queue event_loop: asyncio.AbstractEventLoop def __init__(self, item_list: ItemList): self.queue = asyncio.Queue() self.event_loop = asyncio.get_event_loop() self.item_list = item_list self.backends = [ BackendPoolWorker( PoeTrade(item_list), self.event_loop, ), # BackendPoolWorker( # PoeOfficial(item_list), # self.event_loop, # ), ] def schedule(self, league: str, item_pairs: List[Tuple[str, str]], item_list: ItemList, limit: int = 10) -> List[Offer]: for p in item_pairs: new_task = Task(league, p[0], p[1], limit, False) self.queue.put_nowait(new_task) coroutines = [backend.work(self.queue) for backend in self.backends] (done, _pending) = self.event_loop.run_until_complete( asyncio.wait(coroutines)) results: List[List[Dict]] = [x.result() for x in done] for worker in self.backends: logging.debug("Worker {} finished {} tasks".format( worker.backend.name(), worker.counter)) offers: List[Offer] = [] for r in results: offers.extend(r) return offers
const express = require("express"); const routes = require("./routes"); // import sequelize connection const sequelize = require("./config/connection"); const app = express(); const PORT = process.env.PORT || 3006; app.use(express.json()); app.use(express.urlencoded({ extended: true })); app.use(routes); // sync sequelize models to the database, then turn on the server sequelize.sync({ force: false }).then(() => { app.listen(PORT, () => { console.log(`App listening on port ${PORT}!`); }); });
import React, { useEffect } from "react"; import { connect } from "react-redux"; import ScenarioBenView from "./ScenarioBenView"; import { benchmarkOperations, entitySelectors } from "ducks"; import EmptyPage from "shared/EmptyPage"; import Loader from "shared/Loader"; import { FaVimeo } from "react-icons/fa"; function ScenarioBenContainer({ isLoadingBenScenario, scenarioBenchmarks, featureBenId, getScenarioBen, }) { useEffect(() => { if (featureBenId) { getScenarioBen(featureBenId); } }, [featureBenId]); if (isLoadingBenScenario) { return <Loader />; } else { if (scenarioBenchmarks && scenarioBenchmarks.length > 0) { return <ScenarioBenView benchmark={scenarioBenchmarks} />; } else { return ( <EmptyPage icon={FaVimeo} message="You haven't any Benchmark Scenario yet!" subMessage="Please contact your administrator." /> ); } } } function mapStateToProps(state, props) { const featureBenId = props.match.params.featureBenId; const scenarioBenchmarks = entitySelectors.getCollection( state, "benScenario", ); return { featureBenId, scenarioBenchmarks, isLoadingBenScenario: entitySelectors.getFetchingStatus( state, "benScenario", ).isLoading, }; } function mapDispatchToProps(dispatch) { return { getScenarioBen: featureBenId => dispatch( benchmarkOperations.getBenchmarkScenariosByBenFeatureId(featureBenId), ), }; } export default connect( mapStateToProps, mapDispatchToProps, )(ScenarioBenContainer);
export default [ // ๅ’จ่ฏข่€…้ฆ–้กต { path: '/consumer/index', component: () => import('@/views/consumer/index'), }, // ่ฎขๅ•ไธญๅฟƒ { path: '/consumer/order/:status', component: () => import('@/views/consumer/order'), }, // ่ฎขๅ•็กฎ่ฎค { path: '/consumer/order-confirm/:id', component: () => import('@/views/consumer/order/confirm'), }, // ๅ’จ่ฏขๅธˆๆœ็ดข { path: '/consumer/search', component: () => import('@/views/consumer/search'), }, // ๅ’จ่ฏขๅธˆ่ฏฆๆƒ… { path: '/consumer/consultant-detail/:id', component: () => import('@/views/consumer/consultant-detail'), }, // ๅฅฝๅ‹ๆŽจ่ { path: '/consumer/recommend', component: () => import('@/views/consumer/recommend'), }, { path: '/consumer/howto', component: () => import('@/views/howto'), }, // ๅ’จ่ฏขๆˆฟ้—ด { path: '/consumer/room/:id', component: () => import('@/views/consumer/room'), }, // ไธชไบบไธญๅฟƒ-ๅŸบๆœฌไฟกๆฏ { path: '/consumer/baseinfo', component: () => import('@/views/consumer/baseinfo'), }, // ไธชไบบไธญๅฟƒ-ๅฎžๅ่ฎค่ฏ { path: '/consumer/verified', component: () => import('@/views/consumer/center/verified'), }, // ไธชไบบไธญๅฟƒ-่กฅๅ……ไฟกๆฏ { path: '/consumer/perfect', component: () => import('@/views/consumer/center/perfect'), }, // ไธชไบบไธญๅฟƒ-ๆˆ‘็š„ๆ”ถ่— { path: '/consumer/favorites', component: () => import('@/views/consumer/center/favorites'), }, // ไธชไบบไธญๅฟƒ-ๆถˆๆฏ้€š็Ÿฅ { path: '/consumer/message', component: () => import('@/views/consumer/center/message'), }, ]
import pytest import copy from utils import * from hamcrest import * from vinyldns_python import VinylDNSClient from test_data import TestData from vinyldns_context import VinylDNSTestContext import time import json from requests.compat import urljoin def test_update_a_with_same_name_as_cname(shared_zone_test_context): """ Test that updating a A record fails if the name change conflicts with an existing CNAME name """ client = shared_zone_test_context.ok_vinyldns_client try: cname_rs = { 'zoneId': shared_zone_test_context.system_test_zone['id'], 'name': 'duplicate-test-name', 'type': 'CNAME', 'ttl': 500, 'records': [ { 'cname': 'cname1.' } ] } a_rs = { 'zoneId': shared_zone_test_context.system_test_zone['id'], 'name': 'unique-test-name', 'type': 'A', 'ttl': 500, 'records': [ { 'address': '10.1.1.1' } ] } cname_create = client.create_recordset(cname_rs, status=202) cname_record = client.wait_until_recordset_change_status(cname_create, 'Complete')['recordSet'] a_create = client.create_recordset(a_rs, status=202) a_record = client.wait_until_recordset_change_status(a_create, 'Complete')['recordSet'] a_rs_update = copy.deepcopy(a_record) a_rs_update['name'] = 'duplicate-test-name' error = client.update_recordset(a_rs_update, status=409) assert_that(error, is_('RecordSet with name duplicate-test-name and type CNAME already exists in zone system-test.')) finally: delete_result_cname = client.delete_recordset(cname_record['zoneId'], cname_record['id'], status=202) client.wait_until_recordset_change_status(delete_result_cname, 'Complete') delete_result_a = client.delete_recordset(a_record['zoneId'], a_record['id'], status=202) client.wait_until_recordset_change_status(delete_result_a, 'Complete') def test_update_cname_with_same_name_as_another_record(shared_zone_test_context): """ Test that updating a CNAME record fails if the name change conflicts with an existing record name """ client = shared_zone_test_context.ok_vinyldns_client try: cname_rs = { 'zoneId': shared_zone_test_context.system_test_zone['id'], 'name': 'unique-test-name', 'type': 'CNAME', 'ttl': 500, 'records': [ { 'cname': 'cname1.' } ] } a_rs = { 'zoneId': shared_zone_test_context.system_test_zone['id'], 'name': 'duplicate-test-name', 'type': 'A', 'ttl': 500, 'records': [ { 'address': '10.1.1.1' } ] } cname_create = client.create_recordset(cname_rs, status=202) cname_record = client.wait_until_recordset_change_status(cname_create, 'Complete')['recordSet'] a_create = client.create_recordset(a_rs, status=202) a_record = client.wait_until_recordset_change_status(a_create, 'Complete')['recordSet'] cname_rs_update = copy.deepcopy(cname_record) cname_rs_update['name'] = 'duplicate-test-name' error = client.update_recordset(cname_rs_update, status=409) assert_that(error, is_('RecordSet with name duplicate-test-name already exists in zone system-test., CNAME record cannot use duplicate name')) finally: delete_result_cname = client.delete_recordset(cname_record['zoneId'], cname_record['id'], status=202) client.wait_until_recordset_change_status(delete_result_cname, 'Complete') delete_result_a = client.delete_recordset(a_record['zoneId'], a_record['id'], status=202) client.wait_until_recordset_change_status(delete_result_a, 'Complete') def test_update_cname_with_multiple_records(shared_zone_test_context): """ Test that creating a CNAME record set and then updating with multiple records returns an error """ client = shared_zone_test_context.ok_vinyldns_client result_rs = None try: new_rs = { 'zoneId': shared_zone_test_context.system_test_zone['id'], 'name': 'test_update_cname_with_multiple_records', 'type': 'CNAME', 'ttl': 500, 'records': [ { 'cname': 'cname1.' } ] } result = client.create_recordset(new_rs, status=202) result_rs = result['recordSet'] result_rs = client.wait_until_recordset_change_status(result, 'Complete')['recordSet'] # update the record set, adding another cname record so there are multiple updated_rs = copy.deepcopy(result_rs) updated_rs['records'] = [ { 'cname': 'cname1.' }, { 'cname': 'cname2.' } ] errors = client.update_recordset(updated_rs, status=400)['errors'] assert_that(errors[0], is_("CNAME record sets cannot contain multiple records")) finally: if result_rs: result = client.delete_recordset(result_rs['zoneId'], result_rs['id'], status=(202, 404)) if result: client.wait_until_recordset_change_status(result, 'Complete') def test_update_cname_with_multiple_records(shared_zone_test_context): """ Test that creating a CNAME record set and then updating with multiple records returns an error """ client = shared_zone_test_context.ok_vinyldns_client result_rs = None try: new_rs = { 'zoneId': shared_zone_test_context.system_test_zone['id'], 'name': 'test_update_cname_with_multiple_records', 'type': 'CNAME', 'ttl': 500, 'records': [ { 'cname': 'cname1.' } ] } result = client.create_recordset(new_rs, status=202) result_rs = result['recordSet'] result_rs = client.wait_until_recordset_change_status(result, 'Complete')['recordSet'] # update the record set, adding another cname record so there are multiple updated_rs = copy.deepcopy(result_rs) updated_rs['records'] = [ { 'cname': 'cname1.' }, { 'cname': 'cname2.' } ] errors = client.update_recordset(updated_rs, status=400)['errors'] assert_that(errors[0], is_("CNAME record sets cannot contain multiple records")) finally: if result_rs: result = client.delete_recordset(result_rs['zoneId'], result_rs['id'], status=(202, 404)) if result: client.wait_until_recordset_change_status(result, 'Complete') def test_update_change_name_success(shared_zone_test_context): """ Tests updating a record set and changing the name works """ client = shared_zone_test_context.ok_vinyldns_client result_rs = None try: new_rs = { 'zoneId': shared_zone_test_context.system_test_zone['id'], 'name': 'test-update-change-name-success-1', 'type': 'A', 'ttl': 500, 'records': [ { 'address': '1.1.1.1' }, { 'address': '1.1.1.2' } ] } result = client.create_recordset(new_rs, status=202) result_rs = result['recordSet'] result_rs = client.wait_until_recordset_change_status(result, 'Complete')['recordSet'] # update the record set, changing the name updated_rs = copy.deepcopy(result_rs) updated_rs['name'] = 'test-update-change-name-success-2' updated_rs['ttl'] = 600 updated_rs['records'] = [ { 'address': '2.2.2.2' } ] result = client.update_recordset(updated_rs, status=202) result_rs = client.wait_until_recordset_change_status(result, 'Complete')['recordSet'] assert_that(result_rs['ttl'], is_(600)) assert_that(result_rs['name'], is_('test-update-change-name-success-2')) assert_that(result_rs['records'][0]['address'], is_('2.2.2.2')) assert_that(result_rs['records'], has_length(1)) finally: if result_rs: result = client.delete_recordset(result_rs['zoneId'], result_rs['id'], status=(202, 404)) if result: client.wait_until_recordset_change_status(result, 'Complete') @pytest.mark.parametrize('record_name,test_rs', TestData.FORWARD_RECORDS) def test_update_recordset_forward_record_types(shared_zone_test_context, record_name, test_rs): """ Test updating a record set in a forward zone """ client = shared_zone_test_context.ok_vinyldns_client result_rs = None try: new_rs = dict(test_rs, zoneId=shared_zone_test_context.system_test_zone['id']) result = client.create_recordset(new_rs, status=202) assert_that(result['status'], is_('Pending')) print str(result) result_rs = result['recordSet'] verify_recordset(result_rs, new_rs) records = result_rs['records'] for record in new_rs['records']: assert_that(records, has_item(has_entries(record))) result_rs = client.wait_until_recordset_change_status(result, 'Complete')['recordSet'] # now update update_rs = result_rs update_rs['ttl'] = 1000 result = client.update_recordset(update_rs, status=202) assert_that(result['status'], is_('Pending')) result_rs = result['recordSet'] result_rs = client.wait_until_recordset_change_status(result, 'Complete')['recordSet'] assert_that(result_rs['ttl'], is_(1000)) finally: if result_rs: result = client.delete_recordset(result_rs['zoneId'], result_rs['id'], status=(202, 404)) if result: client.wait_until_recordset_change_status(result, 'Complete') @pytest.mark.parametrize('record_name,test_rs', TestData.REVERSE_RECORDS) def test_reverse_update_reverse_record_types(shared_zone_test_context, record_name, test_rs): """ Test updating a record set in a reverse zone """ client = shared_zone_test_context.ok_vinyldns_client result_rs = None try: new_rs = dict(test_rs, zoneId=shared_zone_test_context.ip4_reverse_zone['id']) result = client.create_recordset(new_rs, status=202) assert_that(result['status'], is_('Pending')) print str(result) result_rs = result['recordSet'] verify_recordset(result_rs, new_rs) records = result_rs['records'] for record in new_rs['records']: assert_that(records, has_item(has_entries(record))) result_rs = client.wait_until_recordset_change_status(result, 'Complete')['recordSet'] # now update update_rs = result_rs update_rs['ttl'] = 1000 result = client.update_recordset(update_rs, status=202) assert_that(result['status'], is_('Pending')) result_rs = result['recordSet'] result_rs = client.wait_until_recordset_change_status(result, 'Complete')['recordSet'] assert_that(result_rs['ttl'], is_(1000)) finally: if result_rs: result = client.delete_recordset(result_rs['zoneId'], result_rs['id'], status=(202, 404)) if result: client.wait_until_recordset_change_status(result, 'Complete') def test_update_recordset_long_name(shared_zone_test_context): """ Test updating a record set where the name is too long """ client = shared_zone_test_context.ok_vinyldns_client result_rs = None try: new_rs = { 'id': 'abc', 'zoneId': shared_zone_test_context.system_test_zone['id'], 'name': 'a', 'type': 'A', 'ttl': 100, 'records': [ { 'address': '10.1.1.1' } ] } result = client.create_recordset(new_rs, status=202) result_rs = result['recordSet'] verify_recordset(result_rs, new_rs) result_rs = client.wait_until_recordset_change_status(result, 'Complete')['recordSet'] update_rs = { 'id': 'abc', 'zoneId': shared_zone_test_context.system_test_zone['id'], 'name': 'a'*256, 'type': 'A', 'ttl': 100, 'records': [ { 'address': '10.1.1.1' } ] } client.update_recordset(update_rs, status=400) finally: if result_rs: result = client.delete_recordset(result_rs['zoneId'], result_rs['id'], status=(202, 404)) if result: client.wait_until_recordset_change_status(result, 'Complete') def test_user_can_update_record_in_zone_it_owns(shared_zone_test_context): """ Test user can update a record that it owns """ client = shared_zone_test_context.ok_vinyldns_client rs = None try: rs = client.create_recordset( { 'zoneId': shared_zone_test_context.ok_zone['id'], 'name': 'test_user_can_update_record_in_zone_it_owns', 'type': 'A', 'ttl': 100, 'records': [ { 'address': '10.1.1.1' } ] }, status=202 )['recordSet'] client.wait_until_recordset_exists(rs['zoneId'], rs['id']) rs['ttl'] = rs['ttl'] + 1000 result = client.update_recordset(rs, status=202, retries=3) result_rs = client.wait_until_recordset_change_status(result, 'Complete')['recordSet'] assert_that(result_rs['ttl'], is_(rs['ttl'])) finally: if rs: try: client.delete_recordset(rs['zoneId'], rs['id'], status=(202, 404)) client.wait_until_recordset_deleted(rs['zoneId'], rs['id']) finally: pass def test_update_recordset_no_authorization(shared_zone_test_context): """ Test updating a record set without authorization """ client = shared_zone_test_context.ok_vinyldns_client rs = { 'id': '12345', 'zoneId': shared_zone_test_context.ok_zone['id'], 'name': 'test_update_recordset_no_authorization', 'type': 'A', 'ttl': 100, 'records': [ { 'address': '10.1.1.1' }, { 'address': '10.2.2.2' } ] } client.update_recordset(rs, sign_request=False, status=401) def test_update_recordset_replace_2_records_with_1_different_record(shared_zone_test_context): """ Test creating a new record set in an existing zone and then updating that record set to replace the existing records with one new one """ client = shared_zone_test_context.ok_vinyldns_client ok_zone = shared_zone_test_context.ok_zone result_rs = None try: new_rs = { 'zoneId': ok_zone['id'], 'name': 'test_update_recordset_replace_2_records_with_1_different_record', 'type': 'A', 'ttl': 100, 'records': [ { 'address': '10.1.1.1' }, { 'address': '10.2.2.2' } ] } result = client.create_recordset(new_rs, status=202) print str(result) assert_that(result['changeType'], is_('Create')) assert_that(result['status'], is_('Pending')) assert_that(result['created'], is_not(none())) assert_that(result['userId'], is_not(none())) result_rs = result['recordSet'] result_rs = client.wait_until_recordset_change_status(result, 'Complete')['recordSet'] verify_recordset(result_rs, new_rs) records = [x['address'] for x in result_rs['records']] assert_that(records, has_length(2)) assert_that('10.1.1.1', is_in(records)) assert_that('10.2.2.2', is_in(records)) result_rs['ttl'] = 200 modified_records = [ { 'address': '1.1.1.1' } ] result_rs['records'] = modified_records result = client.update_recordset(result_rs, status=202) assert_that(result['status'], is_('Pending')) result = client.wait_until_recordset_change_status(result, 'Complete') assert_that(result['changeType'], is_('Update')) assert_that(result['status'], is_('Complete')) assert_that(result['created'], is_not(none())) assert_that(result['userId'], is_not(none())) # make sure the update was applied result_rs = result['recordSet'] records = [x['address'] for x in result_rs['records']] assert_that(records, has_length(1)) assert_that(records[0], is_('1.1.1.1')) # verify that the record exists in the backend dns server answers = dns_resolve(ok_zone, result_rs['name'], result_rs['type']) rdata_strings = rdata(answers) assert_that(rdata_strings, has_length(1)) assert_that('1.1.1.1', is_in(rdata_strings)) finally: if result_rs: delete_result = client.delete_recordset(result_rs['zoneId'], result_rs['id'], status=202) client.wait_until_recordset_change_status(delete_result, 'Complete') def test_update_existing_record_set_add_record(shared_zone_test_context): """ Test creating a new record set in an existing zone and then updating that record set to add a record """ client = shared_zone_test_context.ok_vinyldns_client ok_zone = shared_zone_test_context.ok_zone result_rs = None try: new_rs = { 'zoneId': ok_zone['id'], 'name': 'test_update_existing_record_set_add_record', 'type': 'A', 'ttl': 100, 'records': [ { 'address': '10.2.2.2' } ] } result = client.create_recordset(new_rs, status=202) print str(result) assert_that(result['changeType'], is_('Create')) assert_that(result['status'], is_('Pending')) assert_that(result['created'], is_not(none())) assert_that(result['userId'], is_not(none())) result_rs = result['recordSet'] result_rs = client.wait_until_recordset_change_status(result, 'Complete')['recordSet'] verify_recordset(result_rs, new_rs) records = [x['address'] for x in result_rs['records']] assert_that(records, has_length(1)) assert_that(records[0], is_('10.2.2.2')) answers = dns_resolve(ok_zone, result_rs['name'], result_rs['type']) rdata_strings = rdata(answers) print "GOT ANSWERS BACK FOR INITIAL CREATE:" print str(rdata_strings) # Update the record set, adding a new record to the existing one modified_records = [ { 'address': '4.4.4.8' }, { 'address': '10.2.2.2' } ] result_rs['records'] = modified_records import json print "UPDATING RECORD SET, NEW RECORD SET IS..." print json.dumps(result_rs, indent=3) result = client.update_recordset(result_rs, status=202) assert_that(result['status'], is_('Pending')) result = client.wait_until_recordset_change_status(result, 'Complete') assert_that(result['changeType'], is_('Update')) assert_that(result['status'], is_('Complete')) assert_that(result['created'], is_not(none())) assert_that(result['userId'], is_not(none())) # make sure the update was applied result_rs = result['recordSet'] records = [x['address'] for x in result_rs['records']] assert_that(records, has_length(2)) assert_that('10.2.2.2', is_in(records)) assert_that('4.4.4.8', is_in(records)) answers = dns_resolve(ok_zone, result_rs['name'], result_rs['type']) rdata_strings = rdata(answers) print "GOT BACK ANSWERS FOR UPDATE" print str(rdata_strings) assert_that(rdata_strings, has_length(2)) assert_that('10.2.2.2', is_in(rdata_strings)) assert_that('4.4.4.8', is_in(rdata_strings)) finally: if result_rs: delete_result = client.delete_recordset(result_rs['zoneId'], result_rs['id'], status=202) client.wait_until_recordset_change_status(delete_result, 'Complete') def test_update_existing_record_set_delete_record(shared_zone_test_context): """ Test creating a new record set in an existing zone and then updating that record set to delete a record """ client = shared_zone_test_context.ok_vinyldns_client ok_zone = shared_zone_test_context.ok_zone result_rs = None try: new_rs = { 'zoneId': ok_zone['id'], 'name': 'test_update_existing_record_set_delete_record', 'type': 'A', 'ttl': 100, 'records': [ { 'address': '10.1.1.1' }, { 'address': '10.2.2.2' }, { 'address': '10.3.3.3' }, { 'address': '10.4.4.4' } ] } result = client.create_recordset(new_rs, status=202) assert_that(result['changeType'], is_('Create')) assert_that(result['status'], is_('Pending')) assert_that(result['created'], is_not(none())) assert_that(result['userId'], is_not(none())) result_rs = result['recordSet'] result_rs = client.wait_until_recordset_change_status(result, 'Complete')['recordSet'] verify_recordset(result_rs, new_rs) records = [x['address'] for x in result_rs['records']] assert_that(records, has_length(4)) assert_that(records[0], is_('10.1.1.1')) assert_that(records[1], is_('10.2.2.2')) assert_that(records[2], is_('10.3.3.3')) assert_that(records[3], is_('10.4.4.4')) answers = dns_resolve(ok_zone, result_rs['name'], result_rs['type']) rdata_strings = rdata(answers) assert_that(rdata_strings, has_length(4)) # Update the record set, delete three records and leave one modified_records = [ { 'address': '10.2.2.2' } ] result_rs['records'] = modified_records result = client.update_recordset(result_rs, status=202) result = client.wait_until_recordset_change_status(result, 'Complete') # make sure the update was applied result_rs = result['recordSet'] records = [x['address'] for x in result_rs['records']] assert_that(records, has_length(1)) assert_that('10.2.2.2', is_in(records)) # do a DNS query answers = dns_resolve(ok_zone, result_rs['name'], result_rs['type']) rdata_strings = rdata(answers) assert_that(rdata_strings, has_length(1)) assert_that('10.2.2.2', is_in(rdata_strings)) finally: if result_rs: delete_result = client.delete_recordset(result_rs['zoneId'], result_rs['id'], status=202) client.wait_until_recordset_change_status(delete_result, 'Complete') def test_update_ipv4_ptr_recordset_with_verify(shared_zone_test_context): """ Test updating an IPv4 PTR record set returns the updated values after complete """ client = shared_zone_test_context.ok_vinyldns_client reverse4_zone = shared_zone_test_context.ip4_reverse_zone result_rs = None try: orig_rs = { 'zoneId': reverse4_zone['id'], 'name': '30.0', 'type': 'PTR', 'ttl': 100, 'records': [ { 'ptrdname': 'ftp.vinyldns.' } ] } result = client.create_recordset(orig_rs, status=202) result_rs = result['recordSet'] result_rs = client.wait_until_recordset_change_status(result, 'Complete')['recordSet'] print "\r\n\r\n!!!recordset is active! Updating..." new_ptr_target = 'www.vinyldns.' new_rs = result_rs print new_rs new_rs['records'][0]['ptrdname'] = new_ptr_target print new_rs result = client.update_recordset(new_rs, status=202) result_rs = result['recordSet'] result_rs = client.wait_until_recordset_change_status(result, 'Complete')['recordSet'] print "\r\n\r\n!!!updated recordset is active! Verifying..." verify_recordset(result_rs, new_rs) print "\r\n\r\n!!!recordset verified..." print result_rs records = result_rs['records'] assert_that(records[0]['ptrdname'], is_(new_ptr_target)) print "\r\n\r\n!!!verifying recordset in dns backend" # verify that the record exists in the backend dns server answers = dns_resolve(reverse4_zone, result_rs['name'], result_rs['type']) rdata_strings = rdata(answers) assert_that(rdata_strings, has_length(1)) assert_that(rdata_strings[0], is_(new_ptr_target)) finally: if result_rs: delete_result = client.delete_recordset(result_rs['zoneId'], result_rs['id'], status=202) client.wait_until_recordset_change_status(delete_result, 'Complete') def test_update_ipv6_ptr_recordset(shared_zone_test_context): """ Test updating an IPv6 PTR record set returns the updated values after complete """ client = shared_zone_test_context.ok_vinyldns_client reverse6_zone = shared_zone_test_context.ip6_reverse_zone result_rs = None try: orig_rs = { 'zoneId': reverse6_zone['id'], 'name': '0.6.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0', 'type': 'PTR', 'ttl': 100, 'records': [ { 'ptrdname': 'ftp.vinyldns.' } ] } result = client.create_recordset(orig_rs, status=202) result_rs = result['recordSet'] result_rs = client.wait_until_recordset_change_status(result, 'Complete')['recordSet'] print "\r\n\r\n!!!recordset is active! Updating..." new_ptr_target = 'www.vinyldns.' new_rs = result_rs print new_rs new_rs['records'][0]['ptrdname'] = new_ptr_target print new_rs result = client.update_recordset(new_rs, status=202) result_rs = result['recordSet'] result_rs = client.wait_until_recordset_change_status(result, 'Complete')['recordSet'] print "\r\n\r\n!!!updated recordset is active! Verifying..." verify_recordset(result_rs, new_rs) print "\r\n\r\n!!!recordset verified..." print result_rs records = result_rs['records'] assert_that(records[0]['ptrdname'], is_(new_ptr_target)) print "\r\n\r\n!!!verifying recordset in dns backend" answers = dns_resolve(reverse6_zone, result_rs['name'], result_rs['type']) rdata_strings = rdata(answers) assert_that(rdata_strings, has_length(1)) assert_that(rdata_strings[0], is_(new_ptr_target)) finally: if result_rs: delete_result = client.delete_recordset(result_rs['zoneId'], result_rs['id'], status=202) client.wait_until_recordset_change_status(delete_result, 'Complete') def test_update_recordset_fails_when_changing_name_to_an_existing_name(shared_zone_test_context): """ Test creating a new record set fails when an update attempts to change the name of one recordset to the name of another that already exists """ client = shared_zone_test_context.ok_vinyldns_client ok_zone = shared_zone_test_context.ok_zone result_rs_1 = None result_rs_2 = None try: new_rs_1 = { 'zoneId': ok_zone['id'], 'name': 'update_recordset_fails_when_changing_name_to_an_existing_name', 'type': 'A', 'ttl': 100, 'records': [ { 'address': '10.1.1.1' }, { 'address': '10.2.2.2' } ] } result = client.create_recordset(new_rs_1, status=202) result_rs_1 = result['recordSet'] result_rs_1 = client.wait_until_recordset_change_status(result, 'Complete')['recordSet'] new_rs_2 = { 'zoneId': ok_zone['id'], 'name': 'update_recordset_fails_when_changing_name_to_an_existing_name_2', 'type': 'A', 'ttl': 100, 'records': [ { 'address': '2.2.2.2' }, { 'address': '3.3.3.3' } ] } result = client.create_recordset(new_rs_2, status=202) result_rs_2 = result['recordSet'] result_rs_2 = client.wait_until_recordset_change_status(result, 'Complete')['recordSet'] # attempt to change the name of the second to the name of the first result_rs_2['name'] = result_rs_1['name'] client.update_recordset(result_rs_2, status=409) finally: if result_rs_1: delete_result = client.delete_recordset(result_rs_1['zoneId'], result_rs_1['id'], status=202) client.wait_until_recordset_change_status(delete_result, 'Complete') if result_rs_2: delete_result = client.delete_recordset(result_rs_2['zoneId'], result_rs_2['id'], status=202) client.wait_until_recordset_change_status(delete_result, 'Complete') def test_update_recordset_zone_not_found(shared_zone_test_context): """ Test updating a record set in a zone that doesn't exist should return a 404 """ client = shared_zone_test_context.ok_vinyldns_client new_rs = None try: new_rs = { 'zoneId': shared_zone_test_context.ok_zone['id'], 'name': 'test_update_recordset_zone_not_found', 'type': 'A', 'ttl': 100, 'records': [ { 'address': '10.1.1.1' }, { 'address': '10.2.2.2' } ] } result = client.create_recordset(new_rs, status=202) new_rs = result['recordSet'] client.wait_until_recordset_exists(new_rs['zoneId'], new_rs['id']) new_rs['zoneId'] = '1234' client.update_recordset(new_rs, status=404) finally: if new_rs: try: client.delete_recordset(shared_zone_test_context.ok_zone['id'], new_rs['id'], status=(202, 404)) client.wait_until_recordset_deleted(shared_zone_test_context.ok_zone['id'], new_rs['id']) finally: pass def test_update_recordset_not_found(shared_zone_test_context): """ Test updating a record set that doesn't exist should return a 404 """ client = shared_zone_test_context.ok_vinyldns_client new_rs = { 'id': 'nothere', 'zoneId': shared_zone_test_context.ok_zone['id'], 'name': 'test_update_recordset_not_found', 'type': 'A', 'ttl': 100, 'records': [ { 'address': '10.1.1.1' }, { 'address': '10.2.2.2' } ] } client.update_recordset(new_rs, status=404) def test_at_update_recordset(shared_zone_test_context): """ Test creating a new record set with name @ in an existing zone and then updating that recordset with name @ """ client = shared_zone_test_context.ok_vinyldns_client ok_zone = shared_zone_test_context.ok_zone result_rs = None try: new_rs = { 'zoneId': ok_zone['id'], 'name': '@', 'type': 'TXT', 'ttl': 100, 'records': [ { 'text': 'someText' } ] } result = client.create_recordset(new_rs, status=202) print str(result) assert_that(result['changeType'], is_('Create')) assert_that(result['status'], is_('Pending')) assert_that(result['created'], is_not(none())) assert_that(result['userId'], is_not(none())) result_rs = result['recordSet'] result_rs = client.wait_until_recordset_change_status(result, 'Complete')['recordSet'] expected_rs = new_rs expected_rs['name'] = ok_zone['name'] verify_recordset(result_rs, expected_rs) records = result_rs['records'] assert_that(records, has_length(1)) assert_that(records[0]['text'], is_('someText')) result_rs['ttl'] = 200 result_rs['records'][0]['text'] = 'differentText' result = client.update_recordset(result_rs, status=202) assert_that(result['status'], is_('Pending')) result = client.wait_until_recordset_change_status(result, 'Complete') assert_that(result['changeType'], is_('Update')) assert_that(result['status'], is_('Complete')) assert_that(result['created'], is_not(none())) assert_that(result['userId'], is_not(none())) # make sure the update was applied result_rs = result['recordSet'] records = result_rs['records'] assert_that(records, has_length(1)) assert_that(records[0]['text'], is_('differentText')) finally: if result_rs: delete_result = client.delete_recordset(result_rs['zoneId'], result_rs['id'], status=202) client.wait_until_recordset_change_status(delete_result, 'Complete') def test_user_can_update_record_via_user_acl_rule(shared_zone_test_context): """ Test user WRITE ACL rule - update """ result_rs = None ok_zone = shared_zone_test_context.ok_zone client = shared_zone_test_context.ok_vinyldns_client try: acl_rule = generate_acl_rule('Write', userId='dummy') result_rs = seed_text_recordset(client, "test_user_can_update_record_via_user_acl_rule", ok_zone) expected_ttl = result_rs['ttl'] + 1000 result_rs['ttl'] = result_rs['ttl'] + 1000 # Dummy user cannot update record in zone shared_zone_test_context.dummy_vinyldns_client.update_recordset(result_rs, status=403, retries=3) # add rule add_ok_acl_rules(shared_zone_test_context, [acl_rule]) # Dummy user can update record result = shared_zone_test_context.dummy_vinyldns_client.update_recordset(result_rs, status=202) result_rs = shared_zone_test_context.ok_vinyldns_client.wait_until_recordset_change_status(result, 'Complete')['recordSet'] assert_that(result_rs['ttl'], is_(expected_ttl)) finally: clear_ok_acl_rules(shared_zone_test_context) if result_rs: delete_result = client.delete_recordset(result_rs['zoneId'], result_rs['id'], status=202) client.wait_until_recordset_change_status(delete_result, 'Complete') def test_user_can_update_record_via_group_acl_rule(shared_zone_test_context): """ Test group WRITE ACL rule - update """ result_rs = None ok_zone = shared_zone_test_context.ok_zone client = shared_zone_test_context.ok_vinyldns_client acl_rule = generate_acl_rule('Write', groupId=shared_zone_test_context.dummy_group['id']) try: result_rs = seed_text_recordset(client, "test_user_can_update_record_via_group_acl_rule", ok_zone) expected_ttl = result_rs['ttl'] + 1000 result_rs['ttl'] = result_rs['ttl'] + 1000 # Dummy user cannot update record in zone shared_zone_test_context.dummy_vinyldns_client.update_recordset(result_rs, status=403) # add rule add_ok_acl_rules(shared_zone_test_context, [acl_rule]) # Dummy user can update record result = shared_zone_test_context.dummy_vinyldns_client.update_recordset(result_rs, status=202) result_rs = shared_zone_test_context.ok_vinyldns_client.wait_until_recordset_change_status(result, 'Complete')['recordSet'] assert_that(result_rs['ttl'], is_(expected_ttl)) finally: clear_ok_acl_rules(shared_zone_test_context) if result_rs: delete_result = client.delete_recordset(result_rs['zoneId'], result_rs['id'], status=202) client.wait_until_recordset_change_status(delete_result, 'Complete') def test_user_rule_priority_over_group_acl_rule(shared_zone_test_context): """ Test user rule takes priority over group rule """ result_rs = None ok_zone = shared_zone_test_context.ok_zone client = shared_zone_test_context.ok_vinyldns_client try: group_acl_rule = generate_acl_rule('Read', groupId=shared_zone_test_context.dummy_group['id']) user_acl_rule = generate_acl_rule('Write', userId='dummy') result_rs = seed_text_recordset(client, "test_user_rule_priority_over_group_acl_rule", ok_zone) expected_ttl = result_rs['ttl'] + 1000 result_rs['ttl'] = result_rs['ttl'] + 1000 #add rules add_ok_acl_rules(shared_zone_test_context, [group_acl_rule, user_acl_rule]) #Dummy user can update record result = shared_zone_test_context.dummy_vinyldns_client.update_recordset(result_rs, status=202) result_rs = shared_zone_test_context.ok_vinyldns_client.wait_until_recordset_change_status(result, 'Complete')['recordSet'] assert_that(result_rs['ttl'], is_(expected_ttl)) finally: clear_ok_acl_rules(shared_zone_test_context) if result_rs: client.delete_recordset(result_rs['zoneId'], result_rs['id'], status=(202, 404)) client.wait_until_recordset_deleted(result_rs['zoneId'], result_rs['id']) def test_more_restrictive_acl_rule_priority(shared_zone_test_context): """ Test more restrictive rule takes priority """ ok_zone = shared_zone_test_context.ok_zone client = shared_zone_test_context.ok_vinyldns_client result_rs = None try: read_rule = generate_acl_rule('Read', userId='dummy') write_rule = generate_acl_rule('Write', userId='dummy') result_rs = seed_text_recordset(client, "test_more_restrictive_acl_rule_priority", ok_zone) result_rs['ttl'] = result_rs['ttl'] + 1000 #add rules add_ok_acl_rules(shared_zone_test_context, [read_rule, write_rule]) #Dummy user cannot update record shared_zone_test_context.dummy_vinyldns_client.update_recordset(result_rs, status=403) finally: clear_ok_acl_rules(shared_zone_test_context) if result_rs: delete_result = client.delete_recordset(result_rs['zoneId'], result_rs['id'], status=202) client.wait_until_recordset_change_status(delete_result, 'Complete') def test_acl_rule_with_record_type_success(shared_zone_test_context): """ Test a rule on a specific record type applies to that type """ result_rs = None ok_zone = shared_zone_test_context.ok_zone client = shared_zone_test_context.ok_vinyldns_client try: acl_rule = generate_acl_rule('Write', userId='dummy', recordTypes=['TXT']) result_rs = seed_text_recordset(client, "test_acl_rule_with_record_type_success", ok_zone) expected_ttl = result_rs['ttl'] + 1000 result_rs['ttl'] = result_rs['ttl'] + 1000 z = client.get_zone(ok_zone['id']) print "this is the zone before we try an update..." print json.dumps(z, indent=3) #Dummy user cannot update record in zone shared_zone_test_context.dummy_vinyldns_client.update_recordset(result_rs, status=403, retries=3) #add rule add_ok_acl_rules(shared_zone_test_context, [acl_rule]) #Dummy user can update record result = shared_zone_test_context.dummy_vinyldns_client.update_recordset(result_rs, status=202) result_rs = shared_zone_test_context.ok_vinyldns_client.wait_until_recordset_change_status(result, 'Complete')['recordSet'] assert_that(result_rs['ttl'], is_(expected_ttl)) finally: clear_ok_acl_rules(shared_zone_test_context) if result_rs: delete_result = client.delete_recordset(result_rs['zoneId'], result_rs['id'], status=202) client.wait_until_recordset_change_status(delete_result, 'Complete') def test_acl_rule_with_cidr_ip4_success(shared_zone_test_context): """ Test a rule on a specific record type applies to that type """ result_rs = None ip4_zone = shared_zone_test_context.ip4_reverse_zone client = shared_zone_test_context.ok_vinyldns_client try: acl_rule = generate_acl_rule('Write', userId='dummy', recordTypes=['PTR'], recordMask="10.10.0.0/32") result_rs = seed_ptr_recordset(client, "0.0", ip4_zone) expected_ttl = result_rs['ttl'] + 1000 result_rs['ttl'] = result_rs['ttl'] + 1000 #Dummy user cannot update record in zone shared_zone_test_context.dummy_vinyldns_client.update_recordset(result_rs, status=403, retries=3) #add rule add_ip4_acl_rules(shared_zone_test_context, [acl_rule]) #Dummy user can update record result = shared_zone_test_context.dummy_vinyldns_client.update_recordset(result_rs, status=202) result_rs = shared_zone_test_context.ok_vinyldns_client.wait_until_recordset_change_status(result, 'Complete')['recordSet'] assert_that(result_rs['ttl'], is_(expected_ttl)) finally: clear_ip4_acl_rules(shared_zone_test_context) if result_rs: delete_result = client.delete_recordset(result_rs['zoneId'], result_rs['id'], status=202) client.wait_until_recordset_change_status(delete_result, 'Complete') def test_acl_rule_with_cidr_ip4_failure(shared_zone_test_context): """ Test a rule on a specific record type applies to that type """ result_rs = None ip4_zone = shared_zone_test_context.ip4_reverse_zone client = shared_zone_test_context.ok_vinyldns_client try: acl_rule = generate_acl_rule('Write', userId='dummy', recordTypes=['PTR'], recordMask="172.30.0.0/32") result_rs = seed_ptr_recordset(client, "0.1", ip4_zone) #Dummy user cannot update record in zone shared_zone_test_context.dummy_vinyldns_client.update_recordset(result_rs, status=403, retries=3) #add rule add_ip4_acl_rules(shared_zone_test_context, [acl_rule]) #Dummy user still cant update record shared_zone_test_context.dummy_vinyldns_client.update_recordset(result_rs, status=403) finally: clear_ip4_acl_rules(shared_zone_test_context) if result_rs: delete_result = client.delete_recordset(result_rs['zoneId'], result_rs['id'], status=202) client.wait_until_recordset_change_status(delete_result, 'Complete') def test_acl_rule_with_cidr_ip6_success(shared_zone_test_context): """ Test a rule on a specific record type applies to that type """ result_rs = None ip6_zone = shared_zone_test_context.ip6_reverse_zone client = shared_zone_test_context.ok_vinyldns_client try: acl_rule = generate_acl_rule('Write', userId='dummy', recordTypes=['PTR'], recordMask="fd69:27cc:fe91:0000:0000:0000:0000:0000/127") result_rs = seed_ptr_recordset(client, "0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0", ip6_zone) expected_ttl = result_rs['ttl'] + 1000 result_rs['ttl'] = result_rs['ttl'] + 1000 #Dummy user cannot update record in zone shared_zone_test_context.dummy_vinyldns_client.update_recordset(result_rs, status=403, retries=3) #add rule add_ip6_acl_rules(shared_zone_test_context, [acl_rule]) #Dummy user can update record result = shared_zone_test_context.dummy_vinyldns_client.update_recordset(result_rs, status=202) result_rs = shared_zone_test_context.ok_vinyldns_client.wait_until_recordset_change_status(result, 'Complete')['recordSet'] assert_that(result_rs['ttl'], is_(expected_ttl)) finally: clear_ip6_acl_rules(shared_zone_test_context) if result_rs: delete_result = client.delete_recordset(result_rs['zoneId'], result_rs['id'], status=202) client.wait_until_recordset_change_status(delete_result, 'Complete') def test_acl_rule_with_cidr_ip6_failure(shared_zone_test_context): """ Test a rule on a specific record type applies to that type """ result_rs = None ip6_zone = shared_zone_test_context.ip6_reverse_zone client = shared_zone_test_context.ok_vinyldns_client try: acl_rule = generate_acl_rule('Write', userId='dummy', recordTypes=['PTR'], recordMask="fd69:27cc:fe91:0000:0000:0000:0000:0000/127") result_rs = seed_ptr_recordset(client, "0.0.0.0.0.0.0.0.0.0.0.0.0.0.5.0.0.0.0.0", ip6_zone) #Dummy user cannot update record in zone shared_zone_test_context.dummy_vinyldns_client.update_recordset(result_rs, status=403, retries=3) #add rule add_ip6_acl_rules(shared_zone_test_context, [acl_rule]) #Dummy user still cant update record result = shared_zone_test_context.dummy_vinyldns_client.update_recordset(result_rs, status=403) finally: clear_ip6_acl_rules(shared_zone_test_context) if result_rs: delete_result = client.delete_recordset(result_rs['zoneId'], result_rs['id'], status=202) client.wait_until_recordset_change_status(delete_result, 'Complete') def test_more_restrictive_cidr_ip4_rule_priority(shared_zone_test_context): """ Test more restrictive cidr rule takes priority """ ip4_zone = shared_zone_test_context.ip4_reverse_zone client = shared_zone_test_context.ok_vinyldns_client result_rs = None try: slash16_rule = generate_acl_rule('Read', userId='dummy', recordTypes=['PTR'], recordMask="10.10.0.0/16") slash32_rule = generate_acl_rule('Write', userId='dummy', recordTypes=['PTR'], recordMask="10.10.0.0/32") result_rs = seed_ptr_recordset(client, "0.0", ip4_zone) result_rs['ttl'] = result_rs['ttl'] + 1000 #add rules add_ip4_acl_rules(shared_zone_test_context, [slash16_rule, slash32_rule]) #Dummy user can update record shared_zone_test_context.dummy_vinyldns_client.update_recordset(result_rs, status=202) finally: clear_ip4_acl_rules(shared_zone_test_context) if result_rs: delete_result = client.delete_recordset(result_rs['zoneId'], result_rs['id'], status=202) client.wait_until_recordset_change_status(delete_result, 'Complete') def test_more_restrictive_cidr_ip6_rule_priority(shared_zone_test_context): """ Test more restrictive cidr rule takes priority """ ip6_zone = shared_zone_test_context.ip6_reverse_zone client = shared_zone_test_context.ok_vinyldns_client result_rs = None try: slash50_rule = generate_acl_rule('Read', userId='dummy', recordTypes=['PTR'], recordMask="fd69:27cc:fe91:0000:0000:0000:0000:0000/50") slash100_rule = generate_acl_rule('Write', userId='dummy', recordTypes=['PTR'], recordMask="fd69:27cc:fe91:0000:0000:0000:0000:0000/100") result_rs = seed_ptr_recordset(client, "0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0", ip6_zone) result_rs['ttl'] = result_rs['ttl'] + 1000 #add rules add_ip6_acl_rules(shared_zone_test_context, [slash50_rule, slash100_rule]) #Dummy user can update record shared_zone_test_context.dummy_vinyldns_client.update_recordset(result_rs, status=202) finally: clear_ip6_acl_rules(shared_zone_test_context) if result_rs: delete_result = client.delete_recordset(result_rs['zoneId'], result_rs['id'], status=202) client.wait_until_recordset_change_status(delete_result, 'Complete') def test_mix_of_cidr_ip6_and_acl_rules_priority(shared_zone_test_context): """ A and AAAA should have read from mixed rule, PTR should have Write from rule with mask """ ip6_zone = shared_zone_test_context.ip6_reverse_zone ok_zone = shared_zone_test_context.ok_zone client = shared_zone_test_context.ok_vinyldns_client result_rs_PTR = None result_rs_A = None result_rs_AAAA = None try: mixed_type_rule_no_mask = generate_acl_rule('Read', userId='dummy', recordTypes=['PTR','AAAA','A']) ptr_rule_with_mask = generate_acl_rule('Write', userId='dummy', recordTypes=['PTR'], recordMask="fd69:27cc:fe91:0000:0000:0000:0000:0000/50") result_rs_PTR = seed_ptr_recordset(client, "0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0", ip6_zone) result_rs_PTR['ttl'] = result_rs_PTR['ttl'] + 1000 result_rs_A = seed_text_recordset(client, "test_more_restrictive_acl_rule_priority_1", ok_zone) result_rs_A['ttl'] = result_rs_A['ttl'] + 1000 result_rs_AAAA = seed_text_recordset(client, "test_more_restrictive_acl_rule_priority_2", ok_zone) result_rs_AAAA['ttl'] = result_rs_AAAA['ttl'] + 1000 #add rules add_ip6_acl_rules(shared_zone_test_context, [mixed_type_rule_no_mask, ptr_rule_with_mask]) add_ok_acl_rules(shared_zone_test_context, [mixed_type_rule_no_mask, ptr_rule_with_mask]) #Dummy user cannot update record for A,AAAA, but can for PTR shared_zone_test_context.dummy_vinyldns_client.update_recordset(result_rs_PTR, status=202) shared_zone_test_context.dummy_vinyldns_client.update_recordset(result_rs_A, status=403) shared_zone_test_context.dummy_vinyldns_client.update_recordset(result_rs_AAAA, status=403) finally: clear_ip6_acl_rules(shared_zone_test_context) clear_ok_acl_rules(shared_zone_test_context) if result_rs_A: delete_result = client.delete_recordset(result_rs_A['zoneId'], result_rs_A['id'], status=202) client.wait_until_recordset_change_status(delete_result, 'Complete') if result_rs_AAAA: delete_result = client.delete_recordset(result_rs_AAAA['zoneId'], result_rs_AAAA['id'], status=202) client.wait_until_recordset_change_status(delete_result, 'Complete') if result_rs_PTR: delete_result = client.delete_recordset(result_rs_PTR['zoneId'], result_rs_PTR['id'], status=202) client.wait_until_recordset_change_status(delete_result, 'Complete') def test_acl_rule_with_wrong_record_type(shared_zone_test_context): """ Test a rule on a specific record type does not apply to other types """ result_rs = None ok_zone = shared_zone_test_context.ok_zone client = shared_zone_test_context.ok_vinyldns_client try: acl_rule = generate_acl_rule('Write', userId='dummy', recordTypes=['CNAME']) result_rs = seed_text_recordset(client, "test_acl_rule_with_wrong_record_type", ok_zone) result_rs['ttl'] = result_rs['ttl'] + 1000 #Dummy user cannot update record in zone shared_zone_test_context.dummy_vinyldns_client.update_recordset(result_rs, status=403, retries=3) #add rule add_ok_acl_rules(shared_zone_test_context, [acl_rule]) #Dummy user cannot update record shared_zone_test_context.dummy_vinyldns_client.update_recordset(result_rs, status=403, retries=3) finally: clear_ok_acl_rules(shared_zone_test_context) if result_rs: delete_result = client.delete_recordset(result_rs['zoneId'], result_rs['id'], status=202) client.wait_until_recordset_change_status(delete_result, 'Complete') def test_empty_acl_record_type_applies_to_all(shared_zone_test_context): """ Test an empty record set rule applies to all types """ result_rs = None ok_zone = shared_zone_test_context.ok_zone client = shared_zone_test_context.ok_vinyldns_client try: acl_rule = generate_acl_rule('Write', userId='dummy', recordTypes=[]) result_rs = seed_text_recordset(client, "test_empty_acl_record_type_applies_to_all", ok_zone) expected_ttl = result_rs['ttl'] + 1000 result_rs['ttl'] = expected_ttl #Dummy user cannot update record in zone shared_zone_test_context.dummy_vinyldns_client.update_recordset(result_rs, status=403, retries=3) #add rule add_ok_acl_rules(shared_zone_test_context, [acl_rule]) #Dummy user can update record result = shared_zone_test_context.dummy_vinyldns_client.update_recordset(result_rs, status=202) result_rs = shared_zone_test_context.ok_vinyldns_client.wait_until_recordset_change_status(result, 'Complete')['recordSet'] assert_that(result_rs['ttl'], is_(expected_ttl)) finally: clear_ok_acl_rules(shared_zone_test_context) if result_rs: delete_result = client.delete_recordset(result_rs['zoneId'], result_rs['id'], status=202) client.wait_until_recordset_change_status(delete_result, 'Complete') def test_acl_rule_with_fewer_record_types_prioritized(shared_zone_test_context): """ Test a rule on a specific record type takes priority over a group of types """ result_rs = None ok_zone = shared_zone_test_context.ok_zone client = shared_zone_test_context.ok_vinyldns_client try: acl_rule_base = generate_acl_rule('Write', userId='dummy') acl_rule1 = generate_acl_rule('Write', userId='dummy', recordTypes=['TXT', 'CNAME']) acl_rule2 = generate_acl_rule('Read', userId='dummy', recordTypes=['TXT']) result_rs = seed_text_recordset(client, "test_acl_rule_with_fewer_record_types_prioritized", ok_zone) result_rs['ttl'] = result_rs['ttl'] + 1000 add_ok_acl_rules(shared_zone_test_context, [acl_rule_base]) #Dummy user can update record in zone with base rule result = shared_zone_test_context.dummy_vinyldns_client.update_recordset(result_rs, status=202) result_rs = shared_zone_test_context.ok_vinyldns_client.wait_until_recordset_change_status(result, 'Complete')['recordSet'] #add rule add_ok_acl_rules(shared_zone_test_context, [acl_rule1, acl_rule2]) #Dummy user cannot update record result_rs['ttl'] = result_rs['ttl'] + 1000 shared_zone_test_context.dummy_vinyldns_client.update_recordset(result_rs, status=403) finally: clear_ok_acl_rules(shared_zone_test_context) if result_rs: delete_result = client.delete_recordset(result_rs['zoneId'], result_rs['id'], status=202) client.wait_until_recordset_change_status(delete_result, 'Complete') def test_acl_rule_user_over_record_type_priority(shared_zone_test_context): """ Test the user priority takes precedence over record type priority """ result_rs = None ok_zone = shared_zone_test_context.ok_zone client = shared_zone_test_context.ok_vinyldns_client try: acl_rule_base = generate_acl_rule('Write', userId='dummy') acl_rule1 = generate_acl_rule('Write', groupId=shared_zone_test_context.dummy_group['id'], recordTypes=['TXT']) acl_rule2 = generate_acl_rule('Read', userId='dummy', recordTypes=['TXT', 'CNAME']) result_rs = seed_text_recordset(client, "test_acl_rule_user_over_record_type_priority", ok_zone) result_rs['ttl'] = result_rs['ttl'] + 1000 add_ok_acl_rules(shared_zone_test_context, [acl_rule_base]) #Dummy user can update record in zone with base rule result = shared_zone_test_context.dummy_vinyldns_client.update_recordset(result_rs, status=202) result_rs = shared_zone_test_context.ok_vinyldns_client.wait_until_recordset_change_status(result, 'Complete')['recordSet'] #add rule add_ok_acl_rules(shared_zone_test_context, [acl_rule1, acl_rule2]) #Dummy user cannot update record result_rs['ttl'] = result_rs['ttl'] + 1000 shared_zone_test_context.dummy_vinyldns_client.update_recordset(result_rs, status=403) finally: clear_ok_acl_rules(shared_zone_test_context) if result_rs: delete_result = client.delete_recordset(result_rs['zoneId'], result_rs['id'], status=202) client.wait_until_recordset_change_status(delete_result, 'Complete') def test_acl_rule_with_record_mask_success(shared_zone_test_context): """ Test rule with record mask allows user to update record """ result_rs = None ok_zone = shared_zone_test_context.ok_zone client = shared_zone_test_context.ok_vinyldns_client try: acl_rule = generate_acl_rule('Write', groupId=shared_zone_test_context.dummy_group['id'], recordMask='test.*') result_rs = seed_text_recordset(client, "test_acl_rule_with_record_mask_success", ok_zone) expected_ttl = result_rs['ttl'] + 1000 result_rs['ttl'] = expected_ttl #Dummy user cannot update record in zone shared_zone_test_context.dummy_vinyldns_client.update_recordset(result_rs, status=403) #add rule add_ok_acl_rules(shared_zone_test_context, [acl_rule]) #Dummy user can update record result = shared_zone_test_context.dummy_vinyldns_client.update_recordset(result_rs, status=202) result_rs = shared_zone_test_context.ok_vinyldns_client.wait_until_recordset_change_status(result, 'Complete')['recordSet'] assert_that(result_rs['ttl'], is_(expected_ttl)) finally: clear_ok_acl_rules(shared_zone_test_context) if result_rs: delete_result = client.delete_recordset(result_rs['zoneId'], result_rs['id'], status=202) client.wait_until_recordset_change_status(delete_result, 'Complete') def test_acl_rule_with_record_mask_failure(shared_zone_test_context): """ Test rule with unmatching record mask is not applied """ result_rs = None ok_zone = shared_zone_test_context.ok_zone client = shared_zone_test_context.ok_vinyldns_client try: acl_rule = generate_acl_rule('Write', groupId=shared_zone_test_context.dummy_group['id'], recordMask='bad.*') result_rs = seed_text_recordset(client, "test_acl_rule_with_record_mask_failure", ok_zone) result_rs['ttl'] = result_rs['ttl'] + 1000 #add rule add_ok_acl_rules(shared_zone_test_context, [acl_rule]) #Dummy user cannot update record shared_zone_test_context.dummy_vinyldns_client.update_recordset(result_rs, status=403) finally: clear_ok_acl_rules(shared_zone_test_context) if result_rs: delete_result = client.delete_recordset(result_rs['zoneId'], result_rs['id'], status=202) client.wait_until_recordset_change_status(delete_result, 'Complete') def test_acl_rule_with_defined_mask_prioritized(shared_zone_test_context): """ Test a rule on a specific record mask takes priority over All """ result_rs = None ok_zone = shared_zone_test_context.ok_zone client = shared_zone_test_context.ok_vinyldns_client try: acl_rule_base = generate_acl_rule('Write', userId='dummy') acl_rule1 = generate_acl_rule('Write', userId='dummy', recordMask='.*') acl_rule2 = generate_acl_rule('Read', userId='dummy', recordMask='test.*') result_rs = seed_text_recordset(client, "test_acl_rule_with_defined_mask_prioritized", ok_zone) result_rs['ttl'] = result_rs['ttl'] + 1000 add_ok_acl_rules(shared_zone_test_context, [acl_rule_base]) #Dummy user can update record in zone with base rule result = shared_zone_test_context.dummy_vinyldns_client.update_recordset(result_rs, status=202) result_rs = shared_zone_test_context.ok_vinyldns_client.wait_until_recordset_change_status(result, 'Complete')['recordSet'] #add rule add_ok_acl_rules(shared_zone_test_context, [acl_rule1, acl_rule2]) #Dummy user cannot update record result_rs['ttl'] = result_rs['ttl'] + 1000 shared_zone_test_context.dummy_vinyldns_client.update_recordset(result_rs, status=403) finally: clear_ok_acl_rules(shared_zone_test_context) if result_rs: delete_result = client.delete_recordset(result_rs['zoneId'], result_rs['id'], status=202) client.wait_until_recordset_change_status(delete_result, 'Complete') def test_user_rule_over_mask_prioritized(shared_zone_test_context): """ Test user/group logic priority over record mask """ result_rs = None ok_zone = shared_zone_test_context.ok_zone client = shared_zone_test_context.ok_vinyldns_client try: acl_rule_base = generate_acl_rule('Write', userId='dummy') acl_rule1 = generate_acl_rule('Write', groupId=shared_zone_test_context.dummy_group['id'], recordMask='test.*') acl_rule2 = generate_acl_rule('Read', userId='dummy', recordMask='.*') result_rs = seed_text_recordset(client, "test_user_rule_over_mask_prioritized", ok_zone) result_rs['ttl'] = result_rs['ttl'] + 1000 add_ok_acl_rules(shared_zone_test_context, [acl_rule_base]) #Dummy user can update record in zone with base rule result = shared_zone_test_context.dummy_vinyldns_client.update_recordset(result_rs, status=202) result_rs = shared_zone_test_context.ok_vinyldns_client.wait_until_recordset_change_status(result, 'Complete')['recordSet'] #add rule add_ok_acl_rules(shared_zone_test_context, [acl_rule1, acl_rule2]) #Dummy user cannot update record result_rs['ttl'] = result_rs['ttl'] + 1000 shared_zone_test_context.dummy_vinyldns_client.update_recordset(result_rs, status=403) finally: clear_ok_acl_rules(shared_zone_test_context) if result_rs: delete_result = client.delete_recordset(result_rs['zoneId'], result_rs['id'], status=202) client.wait_until_recordset_change_status(delete_result, 'Complete') def test_ns_update_passes(shared_zone_test_context): """ Tests that someone in the admin group can update ns record """ client = shared_zone_test_context.ok_vinyldns_client zone = shared_zone_test_context.parent_zone ns_rs = None try: new_rs = { 'zoneId': zone['id'], 'name': 'someNS', 'type': 'NS', 'ttl': 38400, 'records': [ { 'nsdname': 'ns1.parent.com.' } ] } result = client.create_recordset(new_rs, status=202) ns_rs = client.wait_until_recordset_change_status(result, 'Complete')['recordSet'] changed_rs = ns_rs changed_rs['ttl'] = changed_rs['ttl'] + 100 change_result = client.update_recordset(changed_rs, status=202) client.wait_until_recordset_change_status(change_result, 'Complete') finally: if ns_rs: client.delete_recordset(ns_rs['zoneId'], ns_rs['id'], status=(202,404)) client.wait_until_recordset_deleted(ns_rs['zoneId'], ns_rs['id']) def test_ns_update_for_unapproved_server_fails(shared_zone_test_context): """ Tests that an ns update fails if one of the servers isnt approved """ client = shared_zone_test_context.ok_vinyldns_client zone = shared_zone_test_context.parent_zone ns_rs = None try: new_rs = { 'zoneId': zone['id'], 'name': 'badNSupdate', 'type': 'NS', 'ttl': 38400, 'records': [ { 'nsdname': 'ns1.parent.com.' } ] } result = client.create_recordset(new_rs, status=202) ns_rs = client.wait_until_recordset_change_status(result, 'Complete')['recordSet'] changed_rs = ns_rs bad_records = [ { 'nsdname': 'ns1.parent.com.' }, { 'nsdname': 'this.is.bad.' } ] changed_rs['records'] = bad_records client.update_recordset(changed_rs, status=422) finally: if ns_rs: client.delete_recordset(ns_rs['zoneId'], ns_rs['id'], status=(202,404)) client.wait_until_recordset_deleted(ns_rs['zoneId'], ns_rs['id']) def test_update_to_txt_dotted_host_succeeds(shared_zone_test_context): """ Tests that a TXT dotted host record set update succeeds """ result_rs = None ok_zone = shared_zone_test_context.ok_zone client = shared_zone_test_context.ok_vinyldns_client try: result_rs = seed_text_recordset(client, "update_with_dots", ok_zone) result_rs['name'] = "update_with.dots" update_rs = client.update_recordset(result_rs, status=202) result_rs = client.wait_until_recordset_change_status(update_rs, 'Complete')['recordSet'] finally: if result_rs: delete_result = client.delete_recordset(result_rs['zoneId'], result_rs['id'], status=202) client.wait_until_recordset_change_status(delete_result, 'Complete') def test_ns_update_change_ns_name_to_origin_fails(shared_zone_test_context): """ Tests that an ns update for origin fails """ client = shared_zone_test_context.ok_vinyldns_client zone = shared_zone_test_context.parent_zone ns_rs = None try: new_rs = { 'zoneId': zone['id'], 'name': 'update-change-ns-name-to-origin', 'type': 'NS', 'ttl': 38400, 'records': [ { 'nsdname': 'ns1.parent.com.' } ] } result = client.create_recordset(new_rs, status=202) ns_rs = client.wait_until_recordset_change_status(result, 'Complete')['recordSet'] changed_rs = ns_rs changed_rs['name'] = "@" client.update_recordset(changed_rs, status=409) finally: if ns_rs: client.delete_recordset(ns_rs['zoneId'], ns_rs['id'], status=(202,404)) client.wait_until_recordset_deleted(ns_rs['zoneId'], ns_rs['id']) def test_ns_update_existing_ns_origin_fails(shared_zone_test_context): """ Tests that an ns update for existing ns origin fails """ client = shared_zone_test_context.ok_vinyldns_client zone = shared_zone_test_context.parent_zone list_results_page = client.list_recordsets(zone['id'], status=200)['recordSets'] apex_ns = [item for item in list_results_page if item['type'] == 'NS' and item['name'] in zone['name']][0] apex_ns['ttl'] = apex_ns['ttl'] + 100 client.update_recordset(apex_ns, status=422) def test_update_dotted_a_record_not_apex_fails(shared_zone_test_context): """ Test that updating a dotted host name A record set fails. """ client = shared_zone_test_context.ok_vinyldns_client zone = shared_zone_test_context.parent_zone dotted_host_rs = { 'zoneId': zone['id'], 'name': 'fubu', 'type': 'A', 'ttl': 500, 'records': [{'address': '127.0.0.1'}] } create_response = client.create_recordset(dotted_host_rs, status=202) create_rs = client.wait_until_recordset_change_status(create_response, 'Complete')['recordSet'] create_rs['name'] = 'foo.bar' try: error = client.update_recordset(create_rs, status=422) assert_that(error, is_("Record with name " + create_rs['name'] + " and type A is a dotted host which is " "not allowed in zone " + zone['name'])) finally: delete_result = client.delete_recordset(zone['id'], create_rs['id'], status=202) client.wait_until_recordset_change_status(delete_result, 'Complete') def test_update_dotted_a_record_apex_succeeds(shared_zone_test_context): """ Test that updating an apex A record set containing dots succeeds. """ client = shared_zone_test_context.ok_vinyldns_client zone = shared_zone_test_context.parent_zone zone_name = zone['name'] apex_rs = { 'zoneId': zone['id'], 'name': 'fubu', 'type': 'A', 'ttl': 500, 'records': [{'address': '127.0.0.1'}] } create_response = client.create_recordset(apex_rs, status=202) create_rs = client.wait_until_recordset_change_status(create_response, 'Complete')['recordSet'] create_rs['name'] = zone_name try: update_response = client.update_recordset(create_rs, status=202) update_rs = client.wait_until_recordset_change_status(update_response, 'Complete')['recordSet'] assert_that(update_rs['name'], is_(zone_name)) finally: delete_result = client.delete_recordset(zone['id'], create_rs['id'], status=202) client.wait_until_recordset_change_status(delete_result, 'Complete') def test_update_dotted_a_record_apex_adds_trailing_dot_to_name(shared_zone_test_context): """ Test that updating an A record set to apex adds a trailing dot to the name if it is not already in the name. """ client = shared_zone_test_context.ok_vinyldns_client zone = shared_zone_test_context.parent_zone zone_name = zone['name'] recordset = { 'zoneId': zone['id'], 'name': 'silly', 'type': 'A', 'ttl': 500, 'records': [{'address': '127.0.0.1'}] } create_response = client.create_recordset(recordset, status=202) create_rs = client.wait_until_recordset_change_status(create_response, 'Complete')['recordSet'] update_rs = create_rs update_rs['name'] = zone['name'].rstrip('.') try: update_response = client.update_recordset(update_rs, status=202) updated_rs = client.wait_until_recordset_change_status(update_response, 'Complete')['recordSet'] assert_that(updated_rs['name'], is_(zone_name)) finally: delete_result = client.delete_recordset(zone['id'], create_rs['id'], status=202) client.wait_until_recordset_change_status(delete_result, 'Complete') def test_update_existing_dotted_a_record_succeeds(shared_zone_test_context): """ Test that updating an existing A record with dotted host name succeeds """ client = shared_zone_test_context.ok_vinyldns_client zone = shared_zone_test_context.ok_zone recordsets = client.list_recordsets(zone['id'], record_name_filter="dotted.a", status=200)['recordSets'] update_rs = recordsets[0] update_rs['records'] = [{'address': '1.1.1.1'}] try: update_response = client.update_recordset(update_rs, status=202) updated_rs = client.wait_until_recordset_change_status(update_response, 'Complete')['recordSet'] assert_that(updated_rs['records'], is_([{'address': '1.1.1.1'}])) finally: update_rs['records'] = [{'address': '7.7.7.7'}] revert_rs_update = client.update_recordset(update_rs, status=202) client.wait_until_recordset_change_status(revert_rs_update, 'Complete') def test_update_dotted_cname_record_apex_fails(shared_zone_test_context): """ Test that updating a CNAME record set with record name matching dotted apex returns an error. """ client = shared_zone_test_context.ok_vinyldns_client zone = shared_zone_test_context.parent_zone zone_name = zone['name'].rstrip('.') apex_cname_rs = { 'zoneId': zone['id'], 'name': 'ygritte', 'type': 'CNAME', 'ttl': 500, 'records': [{'cname': 'got.reference'}] } create_response = client.create_recordset(apex_cname_rs, status=202) create_rs = client.wait_until_recordset_change_status(create_response, 'Complete')['recordSet'] create_rs['name'] = zone_name try: error = client.update_recordset(create_rs, status=422) assert_that(error,is_("CNAME RecordSet cannot have name '@' because it points to zone origin")) finally: delete_response = client.delete_recordset(zone['id'],create_rs['id'], status=202)['status'] client.wait_until_recordset_deleted(delete_response, 'Complete') def test_update_cname_to_dotted_host_fails(shared_zone_test_context): """ Test that updating a CNAME record set to record name being a dotted host fails. """ client = shared_zone_test_context.ok_vinyldns_client zone = shared_zone_test_context.parent_zone zone_name = zone['name'].rstrip('.') apex_cname_rs = { 'zoneId': zone['id'], 'name': 'link', 'type': 'CNAME', 'ttl': 500, 'records': [{'cname': 'got.reference'}] } create_response = client.create_recordset(apex_cname_rs, status=202) create_rs = client.wait_until_recordset_change_status(create_response, 'Complete')['recordSet'] create_rs['name'] = 'dotted.name' try: error = client.update_recordset(create_rs, status=422) assert_that(error,is_("Record with name dotted.name and type CNAME is a dotted host which is not allowed in zone parent.com.")) finally: delete_response = client.delete_recordset(zone['id'],create_rs['id'], status=202)['status'] client.wait_until_recordset_deleted(delete_response, 'Complete') def test_update_existing_dotted_cname_record_succeeds(shared_zone_test_context): """ Test that updating an existing CNAME record with dotted host name succeeds """ client = shared_zone_test_context.ok_vinyldns_client zone = shared_zone_test_context.ok_zone recordsets = client.list_recordsets(zone['id'], record_name_filter="dottedc.name", status=200)['recordSets'] update_rs = recordsets[0] update_rs['records'] = [{'cname': 'got.reference'}] try: update_response = client.update_recordset(update_rs, status=202) updated_rs = client.wait_until_recordset_change_status(update_response, 'Complete')['recordSet'] assert_that(updated_rs['records'], is_([{'cname': 'got.reference.'}])) finally: update_rs['records'] = [{'cname': 'test.example.com'}] revert_rs_update = client.update_recordset(update_rs, status=202) client.wait_until_recordset_change_status(revert_rs_update, 'Complete') def test_update_succeeds_for_applied_unsynced_record_change(shared_zone_test_context): """ Update should succeed if record change is not synced with DNS backend, but has already been applied """ client = shared_zone_test_context.ok_vinyldns_client zone = shared_zone_test_context.parent_zone a_rs = get_recordset_json(zone, 'already-applied-unsynced-update', 'A', [{'address': '1.1.1.1'}, {'address': '2.2.2.2'}]) create_rs = {} try: create_response = client.create_recordset(a_rs, status=202) create_rs = client.wait_until_recordset_change_status(create_response, 'Complete')['recordSet'] dns_update(zone, 'already-applied-unsynced-update', 550, 'A', '8.8.8.8') updates = create_rs updates['ttl'] = 550 updates['records'] = [ { 'address': '8.8.8.8' } ] update_response = client.update_recordset(updates, status=202) update_rs = client.wait_until_recordset_change_status(update_response, 'Complete')['recordSet'] retrieved_rs = client.get_recordset(zone['id'], update_rs['id'])['recordSet'] verify_recordset(retrieved_rs, updates) finally: try: delete_result = client.delete_recordset(zone['id'], create_rs['id'], status=202) client.wait_until_recordset_change_status(delete_result, 'Complete') except: pass def test_update_fails_for_unapplied_unsynced_record_change(shared_zone_test_context): """ Update should fail if record change is not synced with DNS backend """ client = shared_zone_test_context.ok_vinyldns_client zone = shared_zone_test_context.parent_zone a_rs = get_recordset_json(zone, 'unapplied-unsynced-update', 'A', [{'address': '1.1.1.1'}, {'address': '2.2.2.2'}]) create_rs = {} try: create_response = client.create_recordset(a_rs, status=202) create_rs = client.wait_until_recordset_change_status(create_response, 'Complete')['recordSet'] dns_update(zone, 'unapplied-unsynced-update', 550, 'A', '8.8.8.8') update_rs = create_rs update_rs['records'] = [ { 'address': '5.5.5.5' } ] update_response = client.update_recordset(update_rs, status=202) response = client.wait_until_recordset_change_status(update_response, 'Failed') assert_that(response['systemMessage'], is_("Failed validating update to DNS for change " + response['id'] + ":" + a_rs['name'] + ": This record set is out of sync with the DNS backend; sync this zone before attempting to update this record set.")) finally: try: delete_result = client.delete_recordset(zone['id'], create_rs['id'], status=202) client.wait_until_recordset_change_status(delete_result, 'Complete') except: pass def test_update_high_value_domain_fails(shared_zone_test_context): """ Test that updating a high value domain fails """ client = shared_zone_test_context.ok_vinyldns_client zone_system = shared_zone_test_context.system_test_zone list_results_page_system = client.list_recordsets(zone_system['id'], status=200)['recordSets'] record_system = [item for item in list_results_page_system if item['name'] == 'high-value-domain'][0] record_system['ttl'] = record_system['ttl'] + 100 errors_system = client.update_recordset(record_system, status=422) assert_that(errors_system, is_('Record name "high-value-domain.system-test." is configured as a High Value Domain, so it cannot be modified.')) def test_update_high_value_domain_fails_case_insensitive(shared_zone_test_context): """ Test that updating a high value domain fails regardless of case """ client = shared_zone_test_context.ok_vinyldns_client zone_system = shared_zone_test_context.system_test_zone list_results_page_system = client.list_recordsets(zone_system['id'], status=200)['recordSets'] record_system = [item for item in list_results_page_system if item['name'] == 'high-VALUE-domain-UPPER-CASE'][0] record_system['ttl'] = record_system['ttl'] + 100 errors_system = client.update_recordset(record_system, status=422) assert_that(errors_system, is_('Record name "high-VALUE-domain-UPPER-CASE.system-test." is configured as a High Value Domain, so it cannot be modified.')) def test_update_high_value_domain_fails_ip4_ptr(shared_zone_test_context): """ Test that updating a high value domain fails for ip4 ptr """ client = shared_zone_test_context.ok_vinyldns_client zone_ip4 = shared_zone_test_context.classless_base_zone list_results_page_ip4 = client.list_recordsets(zone_ip4['id'], status=200)['recordSets'] record_ip4 = [item for item in list_results_page_ip4 if item['name'] == '253'][0] record_ip4['ttl'] = record_ip4['ttl'] + 100 errors_ip4 = client.update_recordset(record_ip4, status=422) assert_that(errors_ip4, is_('Record name "192.0.2.253" is configured as a High Value Domain, so it cannot be modified.')) def test_update_high_value_domain_fails_ip6_ptr(shared_zone_test_context): """ Test that updating a high value domain fails for ip6 ptr """ client = shared_zone_test_context.ok_vinyldns_client zone_ip6 = shared_zone_test_context.ip6_reverse_zone list_results_page_ip6 = client.list_recordsets(zone_ip6['id'], status=200)['recordSets'] record_ip6 = [item for item in list_results_page_ip6 if item['name'] == '0.0.0.0.f.f.f.f.0.0.0.0.0.0.0.0.0.0.0.0'][0] record_ip6['ttl'] = record_ip6['ttl'] + 100 errors_ip6 = client.update_recordset(record_ip6, status=422) assert_that(errors_ip6, is_('Record name "fd69:27cc:fe91:0000:0000:0000:ffff:0000" is configured as a High Value Domain, so it cannot be modified.')) def test_no_update_access_non_test_zone(shared_zone_test_context): """ Test that a test user cannot update a record in a non-test zone (even if admin) """ client = shared_zone_test_context.shared_zone_vinyldns_client zone_id = shared_zone_test_context.non_test_shared_zone['id'] list_results = client.list_recordsets(zone_id, status=200)['recordSets'] record_update = [item for item in list_results if item['name'] == 'update-test'][0] record_update['ttl'] = record_update['ttl'] + 100 client.update_recordset(record_update, status=403) def test_update_from_user_in_record_owner_group_for_private_zone_fails(shared_zone_test_context): """ Test that updating with a user in the record owner group fails when the zone is not set to shared """ ok_client = shared_zone_test_context.ok_vinyldns_client shared_record_group = shared_zone_test_context.shared_record_group shared_zone_client = shared_zone_test_context.shared_zone_vinyldns_client zone = shared_zone_test_context.ok_zone create_rs = None try: record_json = get_recordset_json(zone, 'test_shared_failure', 'A', [{'address': '1.1.1.1'}]) record_json['ownerGroupId'] = shared_record_group['id'] create_response = ok_client.create_recordset(record_json, status=202) create_rs = ok_client.wait_until_recordset_change_status(create_response, 'Complete')['recordSet'] assert_that(create_rs['ownerGroupId'], is_(shared_record_group['id'])) update = create_rs update['ttl'] = update['ttl'] + 100 error = shared_zone_client.update_recordset(update, status=403) assert_that(error, is_('User sharedZoneUser does not have access to update test-shared-failure.ok.')) finally: if create_rs: delete_result = ok_client.delete_recordset(zone['id'], create_rs['id'], status=202) ok_client.wait_until_recordset_change_status(delete_result, 'Complete') def test_update_owner_group_from_user_in_record_owner_group_for_shared_zone_passes(shared_zone_test_context): """ Test that updating with a user in the record owner group passes when the zone is set to shared """ ok_client = shared_zone_test_context.ok_vinyldns_client shared_record_group = shared_zone_test_context.shared_record_group shared_client = shared_zone_test_context.shared_zone_vinyldns_client shared_zone = shared_zone_test_context.shared_zone update_rs = None try: record_json = get_recordset_json(shared_zone, 'test_shared_success', 'A', [{'address': '1.1.1.1'}]) record_json['ownerGroupId'] = shared_record_group['id'] create_response = shared_client.create_recordset(record_json, status=202) update = shared_client.wait_until_recordset_change_status(create_response, 'Complete')['recordSet'] assert_that(update['ownerGroupId'], is_(shared_record_group['id'])) update['ttl'] = update['ttl'] + 100 update_response = ok_client.update_recordset(update, status=202) update_rs = shared_client.wait_until_recordset_change_status(update_response, 'Complete')['recordSet'] assert_that(update_rs['ownerGroupId'], is_(shared_record_group['id'])) finally: if update_rs: delete_result = shared_client.delete_recordset(shared_zone['id'], update_rs['id'], status=202) shared_client.wait_until_recordset_change_status(delete_result, 'Complete') def test_update_owner_group_from_admin_in_shared_zone_passes(shared_zone_test_context): """ Test that updating with a zone admin user when the zone is set to shared passes """ shared_client = shared_zone_test_context.shared_zone_vinyldns_client zone = shared_zone_test_context.shared_zone group = shared_zone_test_context.shared_record_group update_rs = None try: record_json = get_recordset_json(zone, 'test_shared_admin_update_success', 'A', [{'address': '1.1.1.1'}]) create_response = shared_client.create_recordset(record_json, status=202) update = shared_client.wait_until_recordset_change_status(create_response, 'Complete')['recordSet'] assert_that(update, is_not(has_key('ownerGroupId'))) update['ownerGroupId'] = group['id'] update['ttl'] = update['ttl'] + 100 update_response = shared_client.update_recordset(update, status=202) update_rs = shared_client.wait_until_recordset_change_status(update_response, 'Complete')['recordSet'] assert_that(update_rs['ownerGroupId'], is_(group['id'])) finally: if update_rs: delete_result = shared_client.delete_recordset(zone['id'], update_rs['id'], status=202) shared_client.wait_until_recordset_change_status(delete_result, 'Complete') def test_update_from_unassociated_user_in_shared_zone_passes_when_record_type_is_approved(shared_zone_test_context): """ Test that updating with a user that does not have write access succeeds in a shared zone if the record type is approved """ ok_client = shared_zone_test_context.ok_vinyldns_client shared_client = shared_zone_test_context.shared_zone_vinyldns_client zone = shared_zone_test_context.shared_zone update_rs = None try: record_json = get_recordset_json(zone, 'test_shared_approved_record_type', 'A', [{'address': '1.1.1.1'}]) create_response = shared_client.create_recordset(record_json, status=202) create_rs = shared_client.wait_until_recordset_change_status(create_response, 'Complete')['recordSet'] assert_that(create_rs, is_not(has_key('ownerGroupId'))) update = create_rs update['ttl'] = update['ttl'] + 100 update_response = ok_client.update_recordset(update, status=202) update_rs = shared_client.wait_until_recordset_change_status(update_response, 'Complete')['recordSet'] finally: if update_rs: delete_result = shared_client.delete_recordset(zone['id'], update_rs['id'], status=202) shared_client.wait_until_recordset_change_status(delete_result, 'Complete') def test_update_from_unassociated_user_in_shared_zone_fails(shared_zone_test_context): """ Test that updating with a user that does not have write access fails in a shared zone """ ok_client = shared_zone_test_context.ok_vinyldns_client shared_client = shared_zone_test_context.shared_zone_vinyldns_client zone = shared_zone_test_context.shared_zone create_rs = None try: record_json = get_recordset_json(zone, 'test_shared_unapproved_record_type', 'MX', [{'preference': 3, 'exchange': 'mx'}]) create_response = shared_client.create_recordset(record_json, status=202) create_rs = shared_client.wait_until_recordset_change_status(create_response, 'Complete')['recordSet'] assert_that(create_rs, is_not(has_key('ownerGroupId'))) update = create_rs update['ttl'] = update['ttl'] + 100 error = ok_client.update_recordset(update, status=403) assert_that(error, is_('User ok does not have access to update test-shared-unapproved-record-type.shared.')) finally: if create_rs: delete_result = shared_client.delete_recordset(zone['id'], create_rs['id'], status=202) shared_client.wait_until_recordset_change_status(delete_result, 'Complete') def test_update_from_acl_for_shared_zone_passes(shared_zone_test_context): """ Test that updating with a user that has an acl passes when the zone is set to shared """ dummy_client = shared_zone_test_context.dummy_vinyldns_client shared_client = shared_zone_test_context.shared_zone_vinyldns_client acl_rule = generate_acl_rule('Write', userId='dummy') zone = shared_zone_test_context.shared_zone update_rs = None try: add_shared_zone_acl_rules(shared_zone_test_context, [acl_rule]) record_json = get_recordset_json(zone, 'test_shared_acl', 'A', [{'address': '1.1.1.1'}]) create_response = shared_client.create_recordset(record_json, status=202) update = shared_client.wait_until_recordset_change_status(create_response, 'Complete')['recordSet'] assert_that(update, is_not(has_key('ownerGroupId'))) update['ttl'] = update['ttl'] + 100 update_response = dummy_client.update_recordset(update, status=202) update_rs = dummy_client.wait_until_recordset_change_status(update_response, 'Complete')['recordSet'] assert_that(update, is_not(has_key('ownerGroupId'))) finally: clear_shared_zone_acl_rules(shared_zone_test_context) if update_rs: delete_result = shared_client.delete_recordset(zone['id'], update_rs['id'], status=202) shared_client.wait_until_recordset_change_status(delete_result, 'Complete') def test_update_to_no_group_owner_passes(shared_zone_test_context): """ Test that updating to have no record owner group passes """ shared_record_group = shared_zone_test_context.shared_record_group shared_client = shared_zone_test_context.shared_zone_vinyldns_client zone = shared_zone_test_context.shared_zone update_rs = None try: record_json = get_recordset_json(zone, 'test_shared_success_no_owner', 'A', [{'address': '1.1.1.1'}]) record_json['ownerGroupId'] = shared_record_group['id'] create_response = shared_client.create_recordset(record_json, status=202) update = shared_client.wait_until_recordset_change_status(create_response, 'Complete')['recordSet'] assert_that(update['ownerGroupId'], is_(shared_record_group['id'])) update['ownerGroupId'] = None update_response = shared_client.update_recordset(update, status=202) update_rs = shared_client.wait_until_recordset_change_status(update_response, 'Complete')['recordSet'] assert_that(update_rs, is_not(has_key('ownerGroupId'))) finally: if update_rs: delete_result = shared_client.delete_recordset(zone['id'], update_rs['id'], status=202) shared_client.wait_until_recordset_change_status(delete_result, 'Complete') def test_update_to_invalid_record_owner_group_fails(shared_zone_test_context): """ Test that updating to a record owner group that does not exist fails """ shared_record_group = shared_zone_test_context.shared_record_group shared_client = shared_zone_test_context.shared_zone_vinyldns_client zone = shared_zone_test_context.shared_zone create_rs = None try: record_json = get_recordset_json(zone, 'test_shared_fail_no_owner', 'A', [{'address': '1.1.1.1'}]) record_json['ownerGroupId'] = shared_record_group['id'] create_response = shared_client.create_recordset(record_json, status=202) create_rs = shared_client.wait_until_recordset_change_status(create_response, 'Complete')['recordSet'] update = create_rs update['ownerGroupId'] = 'no-existo' error = shared_client.update_recordset(update, status=422) assert_that(error, is_('Record owner group with id "no-existo" not found')) finally: if create_rs: delete_result = shared_client.delete_recordset(zone['id'], create_rs['id'], status=202) shared_client.wait_until_recordset_change_status(delete_result, 'Complete') def test_update_to_group_a_user_is_not_in_fails(shared_zone_test_context): """ Test that updating to a record owner group that the user is not in fails """ dummy_group = shared_zone_test_context.dummy_group shared_client = shared_zone_test_context.shared_zone_vinyldns_client zone = shared_zone_test_context.shared_zone create_rs = None try: record_json = get_recordset_json(zone, 'test_shared_fail_no_owner', 'A', [{'address': '1.1.1.1'}]) create_response = shared_client.create_recordset(record_json, status=202) create_rs = shared_client.wait_until_recordset_change_status(create_response, 'Complete')['recordSet'] update = create_rs update['ownerGroupId'] = dummy_group['id'] error = shared_client.update_recordset(update, status=422) assert_that(error, is_('User not in record owner group with id "' + dummy_group['id'] + '"')) finally: if create_rs: delete_result = shared_client.delete_recordset(zone['id'], create_rs['id'], status=202) shared_client.wait_until_recordset_change_status(delete_result, 'Complete') def test_update_with_global_acl_rule_only_fails(shared_zone_test_context): """ Test that updating an owned recordset fails if the user has a global acl rule but is not in the record owner group """ shared_client = shared_zone_test_context.shared_zone_vinyldns_client dummy_client = shared_zone_test_context.dummy_vinyldns_client zone = shared_zone_test_context.shared_zone create_rs = None try: record_json = get_recordset_json(zone, 'test-global-acl', 'A', [{'address': '1.1.1.1'}], 200, 'shared-zone-group') create_response = shared_client.create_recordset(record_json, status=202) create_rs = shared_client.wait_until_recordset_change_status(create_response, 'Complete')['recordSet'] update = create_rs update['ttl'] = 400 error = dummy_client.update_recordset(update, status=403) assert_that(error, is_('User dummy does not have access to update test-global-acl.shared.')) finally: if create_rs: delete_result = shared_client.delete_recordset(zone['id'], create_rs['id'], status=202) shared_client.wait_until_recordset_change_status(delete_result, 'Complete') def test_update_ds_success(shared_zone_test_context): """ Test that creating a valid DS record succeeds """ client = shared_zone_test_context.ok_vinyldns_client zone = shared_zone_test_context.ds_zone record_data_create = [ {'keytag': 60485, 'algorithm': 5, 'digesttype': 1, 'digest': '2BB183AF5F22588179A53B0A98631FAD1A292118'} ] record_data_update = [ {'keytag': 60485, 'algorithm': 5, 'digesttype': 1, 'digest': '2BB183AF5F22588179A53B0A98631FAD1A292118'}, {'keytag': 60485, 'algorithm': 5, 'digesttype': 2, 'digest': 'D4B7D520E7BB5F0F67674A0CCEB1E3E0614B93C4F9E99B8383F6A1E4469DA50A'} ] record_json = get_recordset_json(zone, 'dskey', 'DS', record_data_create, ttl=3600) result_rs = None try: create_call = client.create_recordset(record_json, status=202) result_rs = client.wait_until_recordset_change_status(create_call, 'Complete')['recordSet'] update_json = result_rs update_json['records'] = record_data_update update_call = client.update_recordset(update_json, status=202) result_rs = client.wait_until_recordset_change_status(update_call, 'Complete')['recordSet'] # get result get_result = client.get_recordset(result_rs['zoneId'], result_rs['id'])['recordSet'] verify_recordset(get_result, update_json) finally: if result_rs: client.delete_recordset(result_rs['zoneId'], result_rs['id'], status=(202,404)) client.wait_until_recordset_deleted(result_rs['zoneId'], result_rs['id']) def test_update_ds_data_failures(shared_zone_test_context): """ Test that updating a DS record fails with bad hex, digest, algorithm """ client = shared_zone_test_context.ok_vinyldns_client zone = shared_zone_test_context.ds_zone record_data_create = [ {'keytag': 60485, 'algorithm': 5, 'digesttype': 1, 'digest': '2BB183AF5F22588179A53B0A98631FAD1A292118'} ] record_json = get_recordset_json(zone, 'dskey', 'DS', record_data_create, ttl=3600) result_rs = None try: create_call = client.create_recordset(record_json, status=202) result_rs = client.wait_until_recordset_change_status(create_call, 'Complete')['recordSet'] update_json_bad_hex = result_rs record_data_update = [ {'keytag': 60485, 'algorithm': 5, 'digesttype': 1, 'digest': 'BADWWW'} ] update_json_bad_hex['records'] = record_data_update client.update_recordset(update_json_bad_hex, status=400) update_json_bad_alg = result_rs record_data_update = [ {'keytag': 60485, 'algorithm': 0, 'digesttype': 1, 'digest': '2BB183AF5F22588179A53B0A98631FAD1A292118'} ] update_json_bad_alg['records'] = record_data_update client.update_recordset(update_json_bad_alg, status=400) update_json_bad_dig = result_rs record_data_update = [ {'keytag': 60485, 'algorithm': 5, 'digesttype': 0, 'digest': '2BB183AF5F22588179A53B0A98631FAD1A292118'} ] update_json_bad_dig['records'] = record_data_update client.update_recordset(update_json_bad_dig, status=400) finally: if result_rs: client.delete_recordset(result_rs['zoneId'], result_rs['id'], status=(202,404)) client.wait_until_recordset_deleted(result_rs['zoneId'], result_rs['id']) def test_update_ds_bad_ttl(shared_zone_test_context): """ Test that updating a DS record with unmatching TTL fails """ client = shared_zone_test_context.ok_vinyldns_client zone = shared_zone_test_context.ds_zone record_data_create = [ {'keytag': 60485, 'algorithm': 5, 'digesttype': 1, 'digest': '2BB183AF5F22588179A53B0A98631FAD1A292118'} ] record_json = get_recordset_json(zone, 'dskey', 'DS', record_data_create, ttl=3600) result_rs = None try: create_call = client.create_recordset(record_json, status=202) result_rs = client.wait_until_recordset_change_status(create_call, 'Complete')['recordSet'] update_json = result_rs update_json['ttl'] = 100 client.update_recordset(update_json, status=422) finally: if result_rs: client.delete_recordset(result_rs['zoneId'], result_rs['id'], status=(202,404)) client.wait_until_recordset_deleted(result_rs['zoneId'], result_rs['id']) def test_update_fails_when_payload_and_route_zone_id_does_not_match(shared_zone_test_context): """ Test that a 422 is returned if the zoneId in the body and route do not match """ client = shared_zone_test_context.ok_vinyldns_client zone = shared_zone_test_context.ok_zone created = None try: record_json = get_recordset_json(zone, 'test_update_zone_id', 'A', [{'address': '1.1.1.1'}]) create_response = client.create_recordset(record_json, status=202) created = client.wait_until_recordset_change_status(create_response, 'Complete')['recordSet'] update = created update['ttl'] = update['ttl'] + 100 update['zoneId'] = shared_zone_test_context.dummy_zone['id'] url = urljoin(client.index_url, u'/zones/{0}/recordsets/{1}'.format(zone[u'id'], update[u'id'])) response, error = client.make_request(url, u'PUT', client.headers, json.dumps(update), not_found_ok=True, status=422) assert_that(error, is_("Cannot update RecordSet's zoneId attribute")) finally: if created: delete_result = client.delete_recordset(zone['id'], created['id'], status=202) client.wait_until_recordset_change_status(delete_result, 'Complete') def test_update_fails_when_payload_and_actual_zone_id_do_not_match(shared_zone_test_context): """ Test that a 422 is returned if the zoneId in the body and the recordSets actual zoneId do not match """ client = shared_zone_test_context.ok_vinyldns_client zone = shared_zone_test_context.ok_zone created = None try: record_json = get_recordset_json(zone, 'test_update_zone_id', 'A', [{'address': '1.1.1.1'}]) create_response = client.create_recordset(record_json, status=202) created = client.wait_until_recordset_change_status(create_response, 'Complete')['recordSet'] update = created update['zoneId'] = shared_zone_test_context.dummy_zone['id'] error = client.update_recordset(update, status=422) assert_that(error, is_("Cannot update RecordSet's zoneId attribute")) finally: if created: delete_result = client.delete_recordset(zone['id'], created['id'], status=202) client.wait_until_recordset_change_status(delete_result, 'Complete')
var express = require('express'); var app = express(); const http = require('http').Server(app); const io = require('socket.io')(http, { cors: { origin: "http://localhost:4200", methods: ["GET", "POST"] } }); io.on("connection", socket => { socket.on("userSubmittedPlayerName", async (character) => { console.log("\x1b[37m", new Date().toLocaleTimeString() + " : " + character.Name + " logged in..."); character.SocketId = socket.id; if(characters.includes(character)) { //Check login details } else { characters.push(character); } io.emit("updateCharacterConnectionString", socket.id); io.emit("currentOnlineCharacters", characters); console.log("\x1b[37m", "Current players online: " + characters.length); }); socket.on("chatMessage", (message) => { console.log('\x1b[36m%s\x1b[0m', " " + message); io.emit("postChatMessage", " " + message); }) socket.on("GetMarketData", () => { io.emit("UpdateMarket", JSON.stringify(market)); }) socket.on("AddMarketItem", (marketItem) => { var marketItemObj = JSON.parse(marketItem); console.log('\x1b[35m%s\x1b[0m', " " + new Date().toLocaleTimeString() + " : " + marketItemObj.ListingOwner.Name + " added (" + marketItemObj.Count + ") " + marketItemObj.Item.Name + " for " + marketItemObj.Price + " on the market "); market.push(marketItemObj); io.emit("UpdateMarket", JSON.stringify(market)); }); socket.on("disconnect", () => { var loggedOutCharacter = characters.filter(i => i.SocketId == socket.id); if(loggedOutCharacter.length == 1) { console.log('\x1b[37m%s\x1b[0m', " " + new Date().toLocaleTimeString() + " : " + loggedOutCharacter[0].Name + " logging out..."); } characters = characters.filter(i => i.SocketId != socket.id); io.emit("currentOnlineCharacters", characters); }) }); http.listen(5000, () => { console.clear(); console.log("\x1b[31m", 'Server starting up.... App listening on PORT 5000.\n'); }); //TODO Persist character data somewhere var characters = []; //TODO Persist market data somewhere var market = [];
import React from 'react' import Header from './header' import Footer from './footer' import '../styles/index.scss' import layoutStyles from './layout.module.scss' const Layout = (props) => { return( <div className={layoutStyles.container}> <div className={layoutStyles.content}> <Header className={layoutStyles.hr}/> {props.children} </div> <Footer /> </div> ) } export default Layout
class TextFinder { find (text) {} } class MegaFinder extends TextFinder { find (text) { console.log(`${text} was mega found`) } } class SuperFinder extends TextFinder { find (text) { console.log(`${text} was super found`) } } const megaFinder = new MegaFinder() const superFinder = new SuperFinder() megaFinder.find('ABC') superFinder.find('ABC')
(window.webpackJsonp=window.webpackJsonp||[]).push([[8],{141:function(e,t,a){"use strict";a.r(t),a.d(t,"pageQuery",function(){return f});a(348),a(51);var n=a(7),r=a.n(n),o=a(187),i=a.n(o),l=a(0),c=a.n(l),u=a(189),s=a.n(u),m=a(210),d=a(157),h=function(e){function t(){return e.apply(this,arguments)||this}return r()(t,e),t.prototype.render=function(){var e=s()(this,"props.data.site.siteMetadata.title"),t=s()(this,"props.data.site.siteMetadata.description");console.log("This is trouble");var a=s()(this,"props.data.allMdx.edges");return a.map(function(e){var t=e.node;console.log("/"+t.parent.sourceInstanceName+"/"+t.parent.name),t.fields={slug:"/"+t.parent.sourceInstanceName+"/"+t.parent.name}}),c.a.createElement(d.a,{location:this.props.location},c.a.createElement(i.a,{htmlAttributes:{lang:"en"},meta:[{name:"description",content:t}],title:e}),c.a.createElement("main",null,a.map(function(e){var t=e.node,a=s()(t,"frontmatter.title")||t.fields.slug;return c.a.createElement("div",{key:t.fields.slug},null===t.frontmatter.cover?c.a.createElement(m.a,{link:t.fields.slug,cover:"",title:a,date:t.frontmatter.date,htmlExcerpt:{__html:t.excerpt}}):c.a.createElement(m.a,{link:t.fields.slug,cover:t.frontmatter.cover.childImageSharp.fluid.src,title:a,date:t.frontmatter.date,htmlExcerpt:{__html:t.excerpt}}))})))},t}(l.Component);t.default=h;var f="2386920561"},147:function(e,t){e.exports={title:"Choice of Energy",description:"This is an attempt to share knowledge about energy",siteUrl:"https://choiceofenergy.com",footerText:"**Choice of Energy**<br><br>trying to share energy knowledge",author:"Nikhil Kondabala",authorImage:"./src/componenets/biopic.jpg",authorBio:"Hello, I'm Nikhil Kondabala I work in the advanced energy economy. This is space where I try to explore open datasets about the energy and share the knowledge from them.",social:{twitter:"codenamenikky",github:"codenamenikky",reddit:""},googleAnalyticsTrackingId:"ADD YOUR TRACKING ID HERE",font:"Roboto",fontHeadings:"Merriweather",brandColor:"#7eafab",backgroundColor:"#fff"}},151:function(e,t,a){var n;e.exports=(n=a(154))&&n.default||n},152:function(e,t,a){"use strict";a.r(t),a.d(t,"graphql",function(){return f}),a.d(t,"StaticQueryContext",function(){return d}),a.d(t,"StaticQuery",function(){return h});var n=a(0),r=a.n(n),o=a(4),i=a.n(o),l=a(146),c=a.n(l);a.d(t,"Link",function(){return c.a}),a.d(t,"withPrefix",function(){return l.withPrefix}),a.d(t,"navigate",function(){return l.navigate}),a.d(t,"push",function(){return l.push}),a.d(t,"replace",function(){return l.replace}),a.d(t,"navigateTo",function(){return l.navigateTo});var u=a(151),s=a.n(u);a.d(t,"PageRenderer",function(){return s.a});var m=a(34);a.d(t,"parsePath",function(){return m.a});var d=r.a.createContext({}),h=function(e){return r.a.createElement(d.Consumer,null,function(t){return e.data||t[e.query]&&t[e.query].data?(e.render||e.children)(e.data?e.data.data:t[e.query].data):r.a.createElement("div",null,"Loading (StaticQuery)")})};function f(){throw new Error("It appears like Gatsby is misconfigured. Gatsby related `graphql` calls are supposed to only be evaluated at compile time, and then compiled away,. Unfortunately, something went wrong and the query was left in the compiled code.\n\n.Unless your site has a complex or custom babel/Gatsby configuration this is likely a bug in Gatsby.")}h.propTypes={data:i.a.object,query:i.a.string.isRequired,render:i.a.func,children:i.a.func}},154:function(e,t,a){"use strict";a.r(t);var n=a(10),r=a.n(n),o=a(0),i=a.n(o),l=a(4),c=a.n(l),u=a(49),s=a(2),m=function(e){var t=e.location,a=s.default.getResourcesForPathnameSync(t.pathname);return i.a.createElement(u.a,r()({location:t,pageResources:a},a.json))};m.propTypes={location:c.a.shape({pathname:c.a.string.isRequired}).isRequired},t.default=m},155:function(e,t,a){e.exports=a.p+"static/biopic-540297b09e86ab9e4ac8c3c9856f1231.jpg"},157:function(e,t,a){"use strict";var n=a(173),r=a.n(n),o=a(364),i=a(365),l=a(149),c=a(0),u=a.n(c),s=a(147),m=a.n(s),d={global:{font:{family:m.a.font},colors:{brand:m.a.brandColor}},heading:{font:{family:m.a.fontHeadings}}},h=a(366),f=a(367),p=a(368),g=a(363),b=a(360),E=a(361),y=a(362),v=a(155),w=a.n(v),x=function(){return u.a.createElement("section",null,u.a.createElement(i.a,{round:"small",pad:"medium",margin:"small",background:"light-2"},u.a.createElement(i.a,{direction:"row"},u.a.createElement(i.a,{pad:{top:"none",bottom:"medium",right:"medium",left:"none"},round:"large",height:"xsmall",width:"xsmall"},u.a.createElement(h.a,{fit:"contain",title:m.a.author,alt:m.a.author,src:w.a})),u.a.createElement(i.a,null,u.a.createElement(f.a,{weight:"bold",size:"large",margin:{left:"small"}},m.a.author),u.a.createElement(i.a,{direction:"row"},m.a.social.twitter.length>1?u.a.createElement(p.a,{href:"https://twitter.com/"+m.a.social.twitter,icon:u.a.createElement(b.a,{size:"small"})}):"",m.a.social.github.length>1?u.a.createElement(p.a,{href:"https://github.com/"+m.a.social.github,icon:u.a.createElement(E.a,{size:"small"})}):"",m.a.social.reddit.length>1?u.a.createElement(p.a,{href:"https://reddit.com/user/"+m.a.social.reddit,icon:u.a.createElement(y.a,{size:"small"})}):""))),u.a.createElement(f.a,{size:"small"},u.a.createElement(g.a,null,m.a.authorBio))))},k=function(){return u.a.createElement("footer",null,u.a.createElement(i.a,{background:"light-2",pad:"large",align:"center"},u.a.createElement(g.a,null,m.a.footerText)))},C=a(369),I=a(152),T=function(){return u.a.createElement("header",null,u.a.createElement(i.a,{margin:"small"},u.a.createElement(I.Link,{style:{boxShadow:"none",textDecoration:"none"},to:"/"},u.a.createElement(C.a,{textAlign:"center",color:"brand",margin:"small"},m.a.title)),u.a.createElement(f.a,{textAlign:"center",color:"brand"},m.a.description)))};function q(){var e=r()(["\n img {\n border-radius: 14px;\n max-width: 100%;\n }\n body {\n margin: 0;\n }\n a:hover {\n opacity: 0.9;\n }\n"]);return q=function(){return e},e}Object(l.c)(q());t.a=function(e){return u.a.createElement("div",null,u.a.createElement(o.a,{theme:d},u.a.createElement(i.a,{background:m.a.backgroundColor,style:{minHeight:"100vh"},responsive:!0,margin:"small",align:"center"},u.a.createElement(T,null),u.a.createElement(i.a,{direction:"row-responsive"},u.a.createElement(i.a,{width:"large"},e.children),u.a.createElement("aside",null,u.a.createElement(i.a,{width:"medium"},u.a.createElement(x,null))))),u.a.createElement(k,null)))}},210:function(e,t,a){"use strict";a(211);var n=a(365),r=a(369),o=a(367),i=a(152),l=a(0),c=a.n(l),u=a(149),s=u.b.div.withConfig({displayName:"CardPost__CardHover",componentId:"sc-1nlywk7-0"})([":hover{opacity:0.8;}"]),m=Object(u.b)(n.a).withConfig({displayName:"CardPost__BoxCover",componentId:"sc-1nlywk7-1"})(["border-top-left-radius:12px;border-top-right-radius:12px;border-bottom-right-radius:0px;border-bottom-left-radius:0px;"]);t.a=function(e){return c.a.createElement("article",null,c.a.createElement(s,null,c.a.createElement(i.Link,{to:e.link,style:{boxShadow:"none",textDecoration:"none",textColor:"none"}},c.a.createElement(n.a,{round:"small",elevation:"small",background:"light-1",margin:{top:"small",bottom:"medium",right:"small",left:"small"}},e.cover<1?"":c.a.createElement(m,{basis:"medium",fill:"true",background:{image:"url("+e.cover+")"}}),c.a.createElement(n.a,{pad:"medium"},c.a.createElement(r.a,{margin:"xsmall",level:"2"},e.title),c.a.createElement(o.a,{dangerouslySetInnerHTML:e.htmlExcerpt}),c.a.createElement(o.a,{margin:{top:"small"},size:"small"},e.date))))))}},211:function(e,t,a){"use strict";a(212)("link",function(e){return function(t){return e(this,"a","href",t)}})},212:function(e,t,a){var n=a(6),r=a(17),o=a(26),i=/"/g,l=function(e,t,a,n){var r=String(o(e)),l="<"+t;return""!==a&&(l+=" "+a+'="'+String(n).replace(i,"&quot;")+'"'),l+">"+r+"</"+t+">"};e.exports=function(e,t){var a={};a[e]=t(l),n(n.P+n.F*r(function(){var t=""[e]('"');return t!==t.toLowerCase()||t.split('"').length>3}),"String",a)}},348:function(e,t,a){var n=a(27).f,r=Function.prototype,o=/^\s*function ([^ (]*)/;"name"in r||a(18)&&n(r,"name",{configurable:!0,get:function(){try{return(""+this).match(o)[1]}catch(e){return""}}})}}]); //# sourceMappingURL=component---src-pages-index-js-07c514ac2248364bf91f.js.map
import * as _vue from "vue"; function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? Object(arguments[i]) : {}; var ownKeys = Object.keys(source); if (typeof Object.getOwnPropertySymbols === 'function') { ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) { return Object.getOwnPropertyDescriptor(source, sym).enumerable; })); } ownKeys.forEach(function (key) { _defineProperty(target, key, source[key]); }); } return target; } function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } // GENERATE BY ./scripts/generate.ts // DON NOT EDIT IT MANUALLY import ShrinkOutlinedSvg from "@ant-design/icons-svg/es/asn/ShrinkOutlined"; import AntdIcon from '../components/AntdIcon'; var ShrinkOutlined = function ShrinkOutlined(props, context) { var p = _objectSpread({}, props, context.attrs); return _vue.createVNode(AntdIcon, _vue.mergeProps(p, { "icon": ShrinkOutlinedSvg }), null); }; ShrinkOutlined.displayName = 'ShrinkOutlined'; ShrinkOutlined.inheritAttrs = false; export default ShrinkOutlined;
// JavaScript Document $(document).ready(function() { "use strict"; $(".contact-form").submit(function(e) { e.preventDefault(); var name = $(".name"); var email = $(".email"); var subject = $(".subject"); var msg = $(".message"); var flag = false; if (name.val() == "") { name.closest(".form-control").addClass("error"); name.focus(); flag = false; return false; } else { name.closest(".form-control").removeClass("error").addClass("success"); } if (email.val() == "") { email.closest(".form-control").addClass("error"); email.focus(); flag = false; return false; } else { email.closest(".form-control").removeClass("error").addClass("success"); } if (msg.val() == "") { msg.closest(".form-control").addClass("error"); msg.focus(); flag = false; return false; } else { msg.closest(".form-control").removeClass("error").addClass("success"); flag = true; } var dataString = "name=" + name.val() + "&email=" + email.val() + "&subject=" + subject.val() + "&msg=" + msg.val(); $(".loading").fadeIn("slow").html("Loading..."); $.ajax({ type: "POST", data: dataString, url: "php/contactForm.php", cache: false, success: function (d) { $(".form-control").removeClass("success"); if(d == 'success') // Message Sent? Show the 'Thank You' message and hide the form $('.loading').fadeIn('slow').html('<font color="#48af4b">Mail sent Successfully.</font>').delay(3000).fadeOut('slow'); else $('.loading').fadeIn('slow').html('<font color="#ff5607">Mail not sent.</font>').delay(3000).fadeOut('slow'); } }); return false; }); $("#reset").on('click', function() { $(".form-control").removeClass("success").removeClass("error"); }); })
typeSearchIndex = [{"l":"All Classes","u":"allclasses-index.html"},{"p":"collections_editor","l":"Selector.ChangeWindow"},{"p":"collections_editor","l":"EditorLoader"},{"p":"collections_editor","l":"EditorManager"},{"p":"collections_editor","l":"EditorLoader.MyFileFilter"},{"p":"collections_editor","l":"EditorLoader.MyFolderFilter"},{"p":"collections_editor","l":"Selector.OnClose"},{"p":"collections_editor","l":"Selector.OnFetch"},{"p":"collections_editor","l":"EditorLoader.OnImportFile"},{"p":"collections_editor","l":"EditorLoader.OnImportFolder"},{"p":"collections_editor","l":"EditorLoader.OnPushEdits"},{"p":"collections_editor","l":"EditorLoader.OnRemove"},{"p":"collections_editor","l":"EditorLoader.OnRename"},{"p":"collections_editor","l":"EditorLoader.OnReset"},{"p":"collections_editor","l":"EditorLoader.Selection"},{"p":"collections_editor","l":"Selector.Selection"},{"p":"collections_editor","l":"Selector"},{"p":"collections_editor","l":"EditorLoader.ShowCollectionInformations"},{"p":"collections_editor","l":"StartEditor"}];updateSearchResults();
/// Copyright (c) 2012 Ecma International. All rights reserved. /// Ecma International makes this code available under the terms and conditions set /// forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the /// "Use Terms"). Any redistribution of this code must retain the above /// copyright and this notice and otherwise comply with the Use Terms. /** * @path ch15/15.4/15.4.4/15.4.4.20/15.4.4.20-9-c-iii-18.js * @description Array.prototype.filter return value of callbackfn is a String object */ function testcase() { function callbackfn(val, idx, obj) { return new String(); } var newArr = [11].filter(callbackfn); return newArr.length === 1 && newArr[0] === 11; } runTestCase(testcase);
import Vue from 'vue'; import Vuetify from 'vuetify/lib'; import colors from 'vuetify/lib/util/colors'; Vue.use(Vuetify) const opts = { theme: { themes: { light: { primary: colors.indigo.darken3, // #E53935 secondary: colors.green.darken1, // #FFCDD2 accent: colors.indigo.base, }, }, }, } export default new Vuetify(opts);
# -*- coding: utf-8 -*- """Documentation Builder Environments.""" from __future__ import ( absolute_import, division, print_function, unicode_literals) import logging import os import re import socket import subprocess import sys import traceback from datetime import datetime import six from builtins import object, str from django.conf import settings from django.utils.translation import ugettext_lazy as _ from docker import APIClient from docker.errors import APIError as DockerAPIError from docker.errors import DockerException from requests.exceptions import ConnectionError from slumber.exceptions import HttpClientError from readthedocs.builds.constants import BUILD_STATE_FINISHED from readthedocs.builds.models import BuildCommandResultMixin from readthedocs.core.utils import slugify from readthedocs.projects.constants import LOG_TEMPLATE from readthedocs.restapi.client import api as api_v2 from .constants import ( DOCKER_HOSTNAME_MAX_LEN, DOCKER_IMAGE, DOCKER_LIMITS, DOCKER_OOM_EXIT_CODE, DOCKER_SOCKET, DOCKER_TIMEOUT_EXIT_CODE, DOCKER_VERSION, MKDOCS_TEMPLATE_DIR, SPHINX_TEMPLATE_DIR) from .exceptions import ( BuildEnvironmentCreationFailed, BuildEnvironmentError, BuildEnvironmentException, BuildEnvironmentWarning, BuildTimeoutError, ProjectBuildsSkippedError, VersionLockedError, YAMLParseError) log = logging.getLogger(__name__) __all__ = ( 'api_v2', 'BuildCommand', 'DockerBuildCommand', 'LocalEnvironment', 'LocalBuildEnvironment', 'DockerBuildEnvironment', ) class BuildCommand(BuildCommandResultMixin): """ Wrap command execution for execution in build environments. This wraps subprocess commands with some logic to handle exceptions, logging, and setting up the env for the build command. This acts a mapping of sorts to the API representation of the :py:class:`readthedocs.builds.models.BuildCommandResult` model. :param command: string or array of command parameters :param cwd: current working path for the command :param shell: execute command in shell, default=False :param environment: environment variables to add to environment :type environment: dict :param combine_output: combine stdout/stderr, default=True :param input_data: data to pass in on stdin :type input_data: str :param build_env: build environment to use to execute commands :param bin_path: binary path to add to PATH resolution :param description: a more grokable description of the command being run """ def __init__(self, command, cwd=None, shell=False, environment=None, combine_output=True, input_data=None, build_env=None, bin_path=None, description=None, record_as_success=False): self.command = command self.shell = shell if cwd is None: cwd = os.getcwd() self.cwd = cwd self.environment = os.environ.copy() if environment is not None: assert 'PATH' not in environment, "PATH can't be set" self.environment.update(environment) self.combine_output = combine_output self.input_data = input_data self.build_env = build_env self.output = None self.error = None self.start_time = None self.end_time = None self.bin_path = bin_path self.description = '' if description is not None: self.description = description self.record_as_success = record_as_success self.exit_code = None def __str__(self): # TODO do we want to expose the full command here? output = u'' if self.output is not None: output = self.output.encode('utf-8') return '\n'.join([self.get_command(), output]) def run(self): """ Set up subprocess and execute command. :param cmd_input: input to pass to command in STDIN :type cmd_input: str :param combine_output: combine STDERR into STDOUT """ log.info("Running: '%s' [%s]", self.get_command(), self.cwd) self.start_time = datetime.utcnow() stdout = subprocess.PIPE stderr = subprocess.PIPE stdin = None if self.input_data is not None: stdin = subprocess.PIPE if self.combine_output: stderr = subprocess.STDOUT environment = {} environment.update(self.environment) environment['READTHEDOCS'] = 'True' if self.build_env is not None: environment['READTHEDOCS_VERSION'] = self.build_env.version.slug environment['READTHEDOCS_PROJECT'] = self.build_env.project.slug if 'DJANGO_SETTINGS_MODULE' in environment: del environment['DJANGO_SETTINGS_MODULE'] if 'PYTHONPATH' in environment: del environment['PYTHONPATH'] if self.bin_path is not None: env_paths = environment.get('PATH', '').split(':') env_paths.insert(0, self.bin_path) environment['PATH'] = ':'.join(env_paths) try: proc = subprocess.Popen( self.command, shell=self.shell, cwd=self.cwd, stdin=stdin, stdout=stdout, stderr=stderr, env=environment, ) cmd_input = None if self.input_data is not None: cmd_input = self.input_data if isinstance(cmd_input, six.string_types): cmd_input_bytes = cmd_input.encode('utf-8') else: cmd_input_bytes = cmd_input cmd_output = proc.communicate(input=cmd_input_bytes) (cmd_stdout, cmd_stderr) = cmd_output self.output = self.sanitize_output(cmd_stdout) self.error = self.sanitize_output(cmd_stderr) self.exit_code = proc.returncode except OSError: self.error = traceback.format_exc() self.output = self.error self.exit_code = -1 finally: self.end_time = datetime.utcnow() def sanitize_output(self, output): r""" Sanitize ``output`` to be saved into the DB. 1. Decodes to UTF-8 2. Replaces NULL (\x00) characters with ``''`` (empty string) to avoid PostgreSQL db to fail: https://code.djangoproject.com/ticket/28201 :param output: stdout/stderr to be sanitized :type output: bytes :returns: sanitized output as string or ``None`` if it fails """ try: sanitized = output.decode('utf-8', 'replace') # Replace NULL (\x00) character to avoid PostgreSQL db to fail # https://code.djangoproject.com/ticket/28201 sanitized = sanitized.replace('\x00', '') except (TypeError, AttributeError): sanitized = None return sanitized def get_command(self): """Flatten command.""" if hasattr(self.command, '__iter__') and not isinstance(self.command, str): return ' '.join(self.command) return self.command def save(self): """Save this command and result via the API.""" # Force record this command as success to avoid Build reporting errors # on commands that are just for checking purposes and do not interferes # in the Build if self.record_as_success: log.warning('Recording command exit_code as success') self.exit_code = 0 data = { 'build': self.build_env.build.get('id'), 'command': self.get_command(), 'description': self.description, 'output': self.output, 'exit_code': self.exit_code, 'start_time': self.start_time, 'end_time': self.end_time, } api_v2.command.post(data) class DockerBuildCommand(BuildCommand): """ Create a docker container and run a command inside the container. Build command to execute in docker container """ def run(self): """ Execute command in existing Docker container. :param cmd_input: input to pass to command in STDIN :type cmd_input: str :param combine_output: combine STDERR into STDOUT """ log.info( "Running in container %s: '%s' [%s]", self.build_env.container_id, self.get_command(), self.cwd, ) self.start_time = datetime.utcnow() client = self.build_env.get_client() try: exec_cmd = client.exec_create( container=self.build_env.container_id, cmd=self.get_wrapped_command(), stdout=True, stderr=True, ) cmd_output = client.exec_start(exec_id=exec_cmd['Id'], stream=False) self.output = self.sanitize_output(cmd_output) cmd_ret = client.exec_inspect(exec_id=exec_cmd['Id']) self.exit_code = cmd_ret['ExitCode'] # Docker will exit with a special exit code to signify the command # was killed due to memory usage, make the error code # nicer. Sometimes the kernel kills the command and Docker doesn't # not use the specific exit code, so we check if the word `Killed` # is in the last 15 lines of the command's output killed_in_output = 'Killed' in '\n'.join(self.output.splitlines()[-15:]) if self.exit_code == DOCKER_OOM_EXIT_CODE or (self.exit_code == 1 and killed_in_output): self.output = _('Command killed due to excessive memory ' 'consumption\n') except DockerAPIError: self.exit_code = -1 if self.output is None or not self.output: self.output = _('Command exited abnormally') finally: self.end_time = datetime.utcnow() def get_wrapped_command(self): """ Escape special bash characters in command to wrap in shell. In order to set the current working path inside a docker container, we need to wrap the command in a shell call manually. Some characters will be interpreted as shell characters without escaping, such as: ``pip install requests<0.8``. This escapes a good majority of those characters. """ bash_escape_re = re.compile(r"([\t\ \!\"\#\$\&\'\(\)\*\:\;\<\>\?\@" r"\[\\\]\^\`\{\|\}\~])") prefix = '' if self.bin_path: prefix += 'PATH={0}:$PATH '.format(self.bin_path) return ("/bin/sh -c 'cd {cwd} && {prefix}{cmd}'" .format( cwd=self.cwd, prefix=prefix, cmd=(' '.join([bash_escape_re.sub(r'\\\1', part) for part in self.command])))) class BaseEnvironment(object): """ Base environment class. Used to run arbitrary commands outside a build. """ def __init__(self, project, environment=None): # TODO: maybe we can remove this Project dependency also self.project = project self.environment = environment or {} self.commands = [] def record_command(self, command): pass def run(self, *cmd, **kwargs): """Shortcut to run command from environment.""" return self.run_command_class(cls=self.command_class, cmd=cmd, **kwargs) def run_command_class( self, cls, cmd, record=None, warn_only=False, record_as_success=False, **kwargs): """ Run command from this environment. :param cls: command class to instantiate a command :param cmd: command (as a list) to execute in this environment :param record: whether or not to record this particular command (``False`` implies ``warn_only=True``) :param warn_only: don't raise an exception on command failure :param record_as_success: force command ``exit_code`` to be saved as ``0`` (``True`` implies ``warn_only=True`` and ``record=True``) """ if record is None: # ``self.record`` only exists when called from ``*BuildEnvironment`` record = getattr(self, 'record', False) if not record: warn_only = True if record_as_success: record = True warn_only = True # ``record_as_success`` is needed to instantiate the BuildCommand kwargs.update({'record_as_success': record_as_success}) # Remove PATH from env, and set it to bin_path if it isn't passed in env_path = self.environment.pop('BIN_PATH', None) if 'bin_path' not in kwargs and env_path: kwargs['bin_path'] = env_path assert 'environment' not in kwargs, "environment can't be passed in via commands." kwargs['environment'] = self.environment # ``build_env`` is passed as ``kwargs`` when it's called from a # ``*BuildEnvironment`` build_cmd = cls(cmd, **kwargs) build_cmd.run() if record: # TODO: I don't like how it's handled this entry point here since # this class should know nothing about a BuildCommand (which are the # only ones that can be saved/recorded) self.record_command(build_cmd) # We want append this command to the list of commands only if it has # to be recorded in the database (to keep consistency) and also, it # has to be added after ``self.record_command`` since its # ``exit_code`` can be altered because of ``record_as_success`` self.commands.append(build_cmd) if build_cmd.failed: msg = u'Command {cmd} failed'.format(cmd=build_cmd.get_command()) if build_cmd.output: msg += u':\n{out}'.format(out=build_cmd.output) if warn_only: log.warning(LOG_TEMPLATE.format( project=self.project.slug, version='latest', msg=msg, )) else: raise BuildEnvironmentWarning(msg) return build_cmd class LocalEnvironment(BaseEnvironment): # TODO: BuildCommand name doesn't make sense here, should be just Command command_class = BuildCommand class BuildEnvironment(BaseEnvironment): """ Base build environment. Base class for wrapping command execution for build steps. This provides a context for command execution and reporting, and eventually performs updates on the build object itself, reporting success/failure, as well as failures during the context manager enter and exit. Any exceptions raised inside this context and handled by the eventual :py:meth:`__exit__` method, specifically, inside :py:meth:`handle_exception` and :py:meth:`update_build`. If the exception is a subclass of :py:class:`BuildEnvironmentError`, then this error message is added to the build object and is shown to the user as the top-level failure reason for why the build failed. Other exceptions raise a general failure warning on the build. We only update the build through the API in one of three cases: * The build is not done and needs an additional build step to follow * The build failed and we should always report this change * The build was successful and ``update_on_success`` is ``True`` :param project: Project that is being built :param version: Project version that is being built :param build: Build instance :param record: Record status of build object :param environment: shell environment variables :param update_on_success: update the build object via API if the build was successful """ # Exceptions considered ERROR from a Build perspective but as a WARNING for # the application itself. These exception are logged as warning and not sent # to Sentry. WARNING_EXCEPTIONS = ( VersionLockedError, ProjectBuildsSkippedError, YAMLParseError, BuildTimeoutError, ) def __init__(self, project=None, version=None, build=None, config=None, record=True, environment=None, update_on_success=True): super(BuildEnvironment, self).__init__(project, environment) self.version = version self.build = build self.config = config self.record = record self.update_on_success = update_on_success self.failure = None self.start_time = datetime.utcnow() def __enter__(self): return self def __exit__(self, exc_type, exc_value, tb): ret = self.handle_exception(exc_type, exc_value, tb) self.update_build(BUILD_STATE_FINISHED) log.info( LOG_TEMPLATE.format( project=self.project.slug, version=self.version.slug, msg='Build finished', ) ) return ret def handle_exception(self, exc_type, exc_value, _): """ Exception handling for __enter__ and __exit__. This reports on the exception we're handling and special cases subclasses of BuildEnvironmentException. For :py:class:`BuildEnvironmentWarning`, exit this context gracefully, but don't mark the build as a failure. For all other exception classes, including :py:class:`BuildEnvironmentError`, the build will be marked as a failure and the context will be gracefully exited. If the exception's type is :py:class:`BuildEnvironmentWarning` or it's an exception marked as ``WARNING_EXCEPTIONS`` we log the problem as a WARNING, otherwise we log it as an ERROR. """ if exc_type is not None: log_level_function = None if issubclass(exc_type, BuildEnvironmentWarning): log_level_function = log.warning elif exc_type in self.WARNING_EXCEPTIONS: log_level_function = log.warning self.failure = exc_value else: log_level_function = log.error self.failure = exc_value log_level_function( LOG_TEMPLATE.format( project=self.project.slug, version=self.version.slug, msg=exc_value, ), exc_info=True, extra={ 'stack': True, 'tags': { 'build': self.build.get('id'), 'project': self.project.slug, 'version': self.version.slug, }, }, ) return True def record_command(self, command): command.save() def run(self, *cmd, **kwargs): kwargs.update({ 'build_env': self, }) return super(BuildEnvironment, self).run(*cmd, **kwargs) def run_command_class(self, *cmd, **kwargs): # pylint: disable=arguments-differ kwargs.update({ 'build_env': self, }) return super(BuildEnvironment, self).run_command_class(*cmd, **kwargs) @property def successful(self): """Is build completed, without top level failures or failing commands.""" # noqa return (self.done and self.failure is None and all(cmd.successful for cmd in self.commands)) @property def failed(self): """Is build completed, but has top level failure or failing commands.""" return (self.done and ( self.failure is not None or any(cmd.failed for cmd in self.commands) )) @property def done(self): """Is build in finished state.""" return (self.build is not None and self.build['state'] == BUILD_STATE_FINISHED) def update_build(self, state=None): """ Record a build by hitting the API. This step is skipped if we aren't recording the build. To avoid recording successful builds yet (for instance, running setup commands for the build), set the ``update_on_success`` argument to False on environment instantiation. If there was an error on the build, update the build regardless of whether ``update_on_success`` is ``True`` or not. """ if not self.record: return None self.build['project'] = self.project.pk self.build['version'] = self.version.pk self.build['builder'] = socket.gethostname() self.build['state'] = state if self.done: self.build['success'] = self.successful # TODO drop exit_code and provide a more meaningful UX for error # reporting if self.failure and isinstance( self.failure, BuildEnvironmentException, ): self.build['exit_code'] = self.failure.status_code elif self.commands: self.build['exit_code'] = max([ cmd.exit_code for cmd in self.commands ]) self.build['setup'] = self.build['setup_error'] = '' self.build['output'] = self.build['error'] = '' if self.start_time: build_length = (datetime.utcnow() - self.start_time) self.build['length'] = int(build_length.total_seconds()) if self.failure is not None: # Surface a generic error if the class is not a # BuildEnvironmentError if not isinstance( self.failure, ( BuildEnvironmentException, BuildEnvironmentWarning, ), ): log.error( 'Build failed with unhandled exception: %s', str(self.failure), extra={ 'stack': True, 'tags': { 'build': self.build.get('id'), 'project': self.project.slug, 'version': self.version.slug, }, }, ) self.failure = BuildEnvironmentError( BuildEnvironmentError.GENERIC_WITH_BUILD_ID.format( build_id=self.build['id'], ), ) self.build['error'] = str(self.failure) # Attempt to stop unicode errors on build reporting for key, val in list(self.build.items()): if isinstance(val, six.binary_type): self.build[key] = val.decode('utf-8', 'ignore') # We are selective about when we update the build object here update_build = ( # Build isn't done yet, we unconditionally update in this state not self.done # Build is done, but isn't successful, always update or (self.done and not self.successful) # Otherwise, are we explicitly to not update? or self.update_on_success ) if update_build: try: api_v2.build(self.build['id']).put(self.build) except HttpClientError as e: log.exception( 'Unable to update build: id=%d', self.build['id'], ) except Exception: log.exception('Unknown build exception') class LocalBuildEnvironment(BuildEnvironment): """Local execution build environment.""" command_class = BuildCommand class DockerBuildEnvironment(BuildEnvironment): """ Docker build environment, uses docker to contain builds. If :py:data:`settings.DOCKER_ENABLE` is true, build documentation inside a docker container, instead of the host system, using this build environment class. The build command creates a docker container from a pre-built image, defined by :py:data:`settings.DOCKER_IMAGE`. This container is started with a mount to the project's build path under ``user_builds`` on the host machine, walling off project builds from reading/writing other projects' data. :param docker_socket: Override to Docker socket URI """ command_class = DockerBuildCommand container_image = DOCKER_IMAGE container_mem_limit = DOCKER_LIMITS.get('memory') container_time_limit = DOCKER_LIMITS.get('time') def __init__(self, *args, **kwargs): self.docker_socket = kwargs.pop('docker_socket', DOCKER_SOCKET) super(DockerBuildEnvironment, self).__init__(*args, **kwargs) self.client = None self.container = None self.container_name = slugify( 'build-{build}-project-{project_id}-{project_name}'.format( build=self.build.get('id'), project_id=self.project.pk, project_name=self.project.slug, )[:DOCKER_HOSTNAME_MAX_LEN], ) if self.config and self.config.build.image: self.container_image = self.config.build.image if self.project.container_image: self.container_image = self.project.container_image if self.project.container_mem_limit: self.container_mem_limit = self.project.container_mem_limit if self.project.container_time_limit: self.container_time_limit = self.project.container_time_limit def __enter__(self): """Start of environment context.""" try: # Test for existing container. We remove any stale containers that # are no longer running here if there is a collision. If the # container is still running, this would be a failure of the version # locking code, so we throw an exception. state = self.container_state() if state is not None: if state.get('Running') is True: exc = BuildEnvironmentError( _( 'A build environment is currently ' 'running for this version', ), ) self.failure = exc self.build['state'] = BUILD_STATE_FINISHED raise exc else: log.warning( LOG_TEMPLATE.format( project=self.project.slug, version=self.version.slug, msg=( 'Removing stale container {0}' .format(self.container_id) ), ) ) client = self.get_client() client.remove_container(self.container_id) except (DockerAPIError, ConnectionError): # If there is an exception here, we swallow the exception as this # was just during a sanity check anyways. pass except BuildEnvironmentError: # There may have been a problem connecting to Docker altogether, or # some other handled exception here. self.__exit__(*sys.exc_info()) raise # Create the checkout path if it doesn't exist to avoid Docker creation if not os.path.exists(self.project.doc_path): os.makedirs(self.project.doc_path) try: self.create_container() except: # noqa self.__exit__(*sys.exc_info()) raise return self def __exit__(self, exc_type, exc_value, tb): """End of environment context.""" try: # Update buildenv state given any container error states first self.update_build_from_container_state() client = self.get_client() try: client.kill(self.container_id) except DockerAPIError: log.exception( 'Unable to kill container: id=%s', self.container_id, ) try: log.info('Removing container: id=%s', self.container_id) client.remove_container(self.container_id) # Catch direct failures from Docker API or with a requests HTTP # request. These errors should not surface to the user. except (DockerAPIError, ConnectionError): log.exception( LOG_TEMPLATE.format( project=self.project.slug, version=self.version.slug, msg="Couldn't remove container", ), ) self.container = None except BuildEnvironmentError: # Several interactions with Docker can result in a top level failure # here. We'll catch this and report if there were no reported errors # already. These errors are not as important as a failure at deeper # code if not all([exc_type, exc_value, tb]): exc_type, exc_value, tb = sys.exc_info() return super(DockerBuildEnvironment, self).__exit__(exc_type, exc_value, tb) def get_client(self): """Create Docker client connection.""" try: if self.client is None: self.client = APIClient( base_url=self.docker_socket, version=DOCKER_VERSION, ) return self.client except DockerException as e: log.exception( LOG_TEMPLATE.format( project=self.project.slug, version=self.version.slug, msg='Could not connect to Docker API', ), ) # We don't raise an error here mentioning Docker, that is a # technical detail that the user can't resolve on their own. # Instead, give the user a generic failure raise BuildEnvironmentError( BuildEnvironmentError.GENERIC_WITH_BUILD_ID.format( build_id=self.build['id'], ), ) def get_container_host_config(self): """ Create the ``host_config`` settings for the container. It mainly generates the proper path bindings between the Docker container and the Host by mounting them with the proper permissions. Besides, it mounts the ``GLOBAL_PIP_CACHE`` if it's set and we are under ``DEBUG``. The object returned is passed to Docker function ``client.create_container``. """ binds = { SPHINX_TEMPLATE_DIR: { 'bind': SPHINX_TEMPLATE_DIR, 'mode': 'ro', }, MKDOCS_TEMPLATE_DIR: { 'bind': MKDOCS_TEMPLATE_DIR, 'mode': 'ro', }, self.project.doc_path: { 'bind': self.project.doc_path, 'mode': 'rw', }, } if getattr(settings, 'GLOBAL_PIP_CACHE', False) and settings.DEBUG: binds.update({ self.project.pip_cache_path: { 'bind': self.project.pip_cache_path, 'mode': 'rw', }, }) return self.get_client().create_host_config( binds=binds, mem_limit=self.container_mem_limit, ) @property def image_hash(self): """Return the hash of the Docker image.""" client = self.get_client() image_metadata = client.inspect_image(self.container_image) return image_metadata.get('Id') @property def container_id(self): """Return id of container if it is valid.""" if self.container_name: return self.container_name if self.container: return self.container.get('Id') def container_state(self): """Get container state.""" client = self.get_client() try: info = client.inspect_container(self.container_id) return info.get('State', {}) except DockerAPIError: return None def update_build_from_container_state(self): """ Update buildenv state from container state. In the case of the parent command exiting before the exec commands finish and the container is destroyed, or in the case of OOM on the container, set a failure state and error message explaining the failure on the buildenv. """ state = self.container_state() if state is not None and state.get('Running') is False: if state.get('ExitCode') == DOCKER_TIMEOUT_EXIT_CODE: self.failure = BuildEnvironmentError( _('Build exited due to time out'), ) elif state.get('OOMKilled', False): self.failure = BuildEnvironmentError( _('Build exited due to excessive memory consumption'), ) elif state.get('Error'): self.failure = BuildEnvironmentError(( _('Build exited due to unknown error: {0}') .format(state.get('Error')) ), ) def create_container(self): """Create docker container.""" client = self.get_client() try: log.info( 'Creating Docker container: image=%s', self.container_image, ) self.container = client.create_container( image=self.container_image, command=( '/bin/sh -c "sleep {time}; exit {exit}"'.format( time=self.container_time_limit, exit=DOCKER_TIMEOUT_EXIT_CODE, ) ), name=self.container_id, hostname=self.container_id, host_config=self.get_container_host_config(), detach=True, environment=self.environment, ) client.start(container=self.container_id) except ConnectionError as e: log.exception( LOG_TEMPLATE.format( project=self.project.slug, version=self.version.slug, msg=( 'Could not connect to the Docker API, ' 'make sure Docker is running' ), ), ) # We don't raise an error here mentioning Docker, that is a # technical detail that the user can't resolve on their own. # Instead, give the user a generic failure raise BuildEnvironmentError( BuildEnvironmentError.GENERIC_WITH_BUILD_ID.format( build_id=self.build['id'], ), ) except DockerAPIError as e: log.exception( LOG_TEMPLATE.format( project=self.project.slug, version=self.version.slug, msg=e.explanation, ), ) raise BuildEnvironmentCreationFailed
# Copyright (c) 2017-2019 Dell Inc. or its subsidiaries. # 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 ast from copy import deepcopy import mock import six from cinder import exception from cinder import objects from cinder.objects import fields from cinder.objects import group from cinder import test from cinder.tests.unit.volume.drivers.dell_emc.powermax import ( powermax_data as tpd) from cinder.tests.unit.volume.drivers.dell_emc.powermax import ( powermax_fake_objects as tpfo) from cinder.volume.drivers.dell_emc.powermax import common from cinder.volume.drivers.dell_emc.powermax import fc from cinder.volume.drivers.dell_emc.powermax import iscsi from cinder.volume.drivers.dell_emc.powermax import masking from cinder.volume.drivers.dell_emc.powermax import metadata from cinder.volume.drivers.dell_emc.powermax import provision from cinder.volume.drivers.dell_emc.powermax import rest from cinder.volume.drivers.dell_emc.powermax import utils from cinder.volume import volume_utils class PowerMaxReplicationTest(test.TestCase): def setUp(self): self.data = tpd.PowerMaxData() super(PowerMaxReplicationTest, self).setUp() self.replication_device = { 'target_device_id': self.data.remote_array, 'remote_port_group': self.data.port_group_name_f, 'remote_pool': self.data.srp2, 'rdf_group_label': self.data.rdf_group_name, 'allow_extend': 'True'} volume_utils.get_max_over_subscription_ratio = mock.Mock() configuration = tpfo.FakeConfiguration( None, 'CommonReplicationTests', 1, 1, san_ip='1.1.1.1', san_login='smc', vmax_array=self.data.array, vmax_srp='SRP_1', san_password='smc', san_api_port=8443, vmax_port_groups=[self.data.port_group_name_f], replication_device=self.replication_device) rest.PowerMaxRest._establish_rest_session = mock.Mock( return_value=tpfo.FakeRequestsSession()) driver = fc.PowerMaxFCDriver(configuration=configuration) iscsi_config = tpfo.FakeConfiguration( None, 'CommonReplicationTests', 1, 1, san_ip='1.1.1.1', san_login='smc', vmax_array=self.data.array, vmax_srp='SRP_1', san_password='smc', san_api_port=8443, vmax_port_groups=[self.data.port_group_name_i], replication_device=self.replication_device) iscsi_driver = iscsi.PowerMaxISCSIDriver(configuration=iscsi_config) self.iscsi_common = iscsi_driver.common self.driver = driver self.common = self.driver.common self.masking = self.common.masking self.provision = self.common.provision self.rest = self.common.rest self.utils = self.common.utils self.utils.get_volumetype_extra_specs = ( mock.Mock( return_value=self.data.vol_type_extra_specs_rep_enabled)) self.extra_specs = deepcopy(self.data.extra_specs_rep_enabled) self.extra_specs['retries'] = 1 self.extra_specs['interval'] = 1 self.extra_specs['rep_mode'] = 'Synchronous' self.async_rep_device = { 'target_device_id': self.data.remote_array, 'remote_port_group': self.data.port_group_name_f, 'remote_pool': self.data.srp2, 'rdf_group_label': self.data.rdf_group_name, 'allow_extend': 'True', 'mode': 'async'} async_configuration = tpfo.FakeConfiguration( None, 'CommonReplicationTests', 1, 1, san_ip='1.1.1.1', san_login='smc', vmax_array=self.data.array, vmax_srp='SRP_1', san_password='smc', san_api_port=8443, vmax_port_groups=[self.data.port_group_name_f], replication_device=self.async_rep_device) self.async_driver = fc.PowerMaxFCDriver( configuration=async_configuration) self.metro_rep_device = { 'target_device_id': self.data.remote_array, 'remote_port_group': self.data.port_group_name_f, 'remote_pool': self.data.srp2, 'rdf_group_label': self.data.rdf_group_name, 'allow_extend': 'True', 'mode': 'metro'} metro_configuration = tpfo.FakeConfiguration( None, 'CommonReplicationTests', 1, 1, san_ip='1.1.1.1', san_login='smc', vmax_array=self.data.array, vmax_srp='SRP_1', san_password='smc', san_api_port=8443, vmax_port_groups=[self.data.port_group_name_f], replication_device=self.metro_rep_device) self.metro_driver = fc.PowerMaxFCDriver( configuration=metro_configuration) def test_get_replication_info(self): self.common._get_replication_info() self.assertTrue(self.common.replication_enabled) @mock.patch.object(volume_utils, 'is_group_a_cg_snapshot_type', return_value=False) @mock.patch.object(objects.group.Group, 'get_by_id', return_value=tpd.PowerMaxData.test_rep_group) @mock.patch.object(volume_utils, 'is_group_a_type', return_value=True) @mock.patch.object(utils.PowerMaxUtils, 'check_replication_matched', return_value=True) @mock.patch.object(masking.PowerMaxMasking, 'add_volume_to_storage_group') @mock.patch.object( common.PowerMaxCommon, '_replicate_volume', return_value=({ 'replication_driver_data': tpd.PowerMaxData.test_volume.replication_driver_data}, {})) @mock.patch.object(common.PowerMaxCommon, 'get_volume_metadata', return_value='') def test_create_replicated_volume( self, mck_meta, mock_rep, mock_add, mock_match, mock_check, mock_get, mock_cg): extra_specs = deepcopy(self.extra_specs) extra_specs[utils.PORTGROUPNAME] = self.data.port_group_name_f vol_identifier = self.utils.get_volume_element_name( self.data.test_volume.id) self.common.create_volume(self.data.test_volume) volume_dict = self.data.provider_location mock_rep.assert_called_once_with( self.data.test_volume, vol_identifier, volume_dict, extra_specs) # Add volume to replication group self.common.create_volume(self.data.test_volume_group_member) mock_add.assert_called_once() @mock.patch.object( common.PowerMaxCommon, '_replicate_volume', return_value=({ 'replication_driver_data': tpd.PowerMaxData.test_volume.replication_driver_data}, {})) @mock.patch.object(utils.PowerMaxUtils, 'is_replication_enabled', return_value=True) @mock.patch.object(rest.PowerMaxRest, 'get_rdf_group_number', side_effect=['4', None]) @mock.patch.object(common.PowerMaxCommon, 'get_volume_metadata', return_value='') def test_create_replicated_vol_side_effect( self, mck_meta, mock_rdf_no, mock_rep_enabled, mock_rep_vol): self.common.rep_config = self.utils.get_replication_config( [self.replication_device]) ref_rep_data = {'array': six.text_type(self.data.remote_array), 'device_id': self.data.device_id2} ref_model_update = { 'provider_location': six.text_type( self.data.test_volume.provider_location), 'replication_driver_data': six.text_type(ref_rep_data), 'metadata': ''} model_update = self.common.create_volume(self.data.test_volume) self.assertEqual(ref_model_update, model_update) self.assertRaises(exception.VolumeBackendAPIException, self.common.create_volume, self.data.test_volume) @mock.patch.object(common.PowerMaxCommon, '_clone_check') @mock.patch.object(common.PowerMaxCommon, 'get_volume_metadata', return_value='') def test_create_cloned_replicated_volume(self, mck_meta, mck_clone): extra_specs = deepcopy(self.extra_specs) extra_specs[utils.PORTGROUPNAME] = self.data.port_group_name_f with mock.patch.object(self.common, '_replicate_volume', return_value=({}, {})) as mock_rep: self.common.create_cloned_volume( self.data.test_clone_volume, self.data.test_volume) volume_dict = self.data.provider_location_clone mock_rep.assert_called_once_with( self.data.test_clone_volume, self.data.test_clone_volume.name, volume_dict, extra_specs) @mock.patch.object(common.PowerMaxCommon, '_clone_check') @mock.patch.object(common.PowerMaxCommon, 'get_volume_metadata', return_value='') def test_create_replicated_volume_from_snap(self, mck_meta, mck_clone): extra_specs = deepcopy(self.extra_specs) extra_specs[utils.PORTGROUPNAME] = self.data.port_group_name_f with mock.patch.object(self.common, '_replicate_volume', return_value=({}, {})) as mock_rep: self.common.create_volume_from_snapshot( self.data.test_clone_volume, self.data.test_snapshot) volume_dict = self.data.provider_location_snapshot mock_rep.assert_called_once_with( self.data.test_clone_volume, 'snapshot-%s' % self.data.snapshot_id, volume_dict, extra_specs) def test_replicate_volume(self): volume_dict = self.data.provider_location rs_enabled = fields.ReplicationStatus.ENABLED with mock.patch.object( self.common, 'setup_volume_replication', return_value=(rs_enabled, {}, {})) as mock_setup: self.common._replicate_volume( self.data.test_volume, '1', volume_dict, self.extra_specs) mock_setup.assert_called_once_with( self.data.array, self.data.test_volume, self.data.device_id, self.extra_specs) def test_replicate_volume_exception(self): volume_dict = self.data.provider_location with mock.patch.object( self.common, 'setup_volume_replication', side_effect=exception.VolumeBackendAPIException(data='')): with mock.patch.object( self.common, '_cleanup_replication_source') as mock_clean: self.assertRaises( exception.VolumeBackendAPIException, self.common._replicate_volume, self.data.test_volume, '1', volume_dict, self.extra_specs) mock_clean.assert_called_once_with( self.data.array, self.data.test_volume, '1', volume_dict, self.extra_specs) @mock.patch.object(common.PowerMaxCommon, '_remove_members') @mock.patch.object( common.PowerMaxCommon, '_get_replication_extra_specs', return_value=tpd.PowerMaxData.rep_extra_specs2) @mock.patch.object( utils.PowerMaxUtils, 'is_volume_failed_over', return_value=True) def test_unmap_lun_volume_failed_over(self, mock_fo, mock_es, mock_rm): extra_specs = deepcopy(self.extra_specs) extra_specs[utils.PORTGROUPNAME] = self.data.port_group_name_f extra_specs[utils.IS_RE] = True rep_config = self.utils.get_replication_config( [self.replication_device]) self.common._unmap_lun(self.data.test_volume, self.data.connector) mock_es.assert_called_once_with(extra_specs, rep_config) @mock.patch.object(common.PowerMaxCommon, '_remove_members') @mock.patch.object( common.PowerMaxCommon, '_get_replication_extra_specs', return_value=tpd.PowerMaxData.rep_extra_specs) @mock.patch.object( utils.PowerMaxUtils, 'is_metro_device', return_value=True) def test_unmap_lun_metro(self, mock_md, mock_es, mock_rm): extra_specs = deepcopy(self.extra_specs) extra_specs[utils.PORTGROUPNAME] = self.data.port_group_name_f self.common._unmap_lun(self.data.test_volume, self.data.connector) self.assertEqual(2, mock_rm.call_count) @mock.patch.object( utils.PowerMaxUtils, 'is_volume_failed_over', return_value=True) def test_initialize_connection_vol_failed_over(self, mock_fo): extra_specs = deepcopy(self.extra_specs) extra_specs[utils.PORTGROUPNAME] = self.data.port_group_name_f rep_extra_specs = deepcopy(tpd.PowerMaxData.rep_extra_specs) rep_extra_specs[utils.PORTGROUPNAME] = self.data.port_group_name_f rep_config = self.utils.get_replication_config( [self.replication_device]) with mock.patch.object(self.common, '_get_replication_extra_specs', return_value=rep_extra_specs) as mock_es: self.common.initialize_connection( self.data.test_volume, self.data.connector) mock_es.assert_called_once_with(extra_specs, rep_config) @mock.patch.object(utils.PowerMaxUtils, 'is_metro_device', return_value=True) @mock.patch.object(rest.PowerMaxRest, 'get_array_model_info', return_value=('VMAX250F', False)) def test_initialize_connection_vol_metro(self, mock_model, mock_md): metro_connector = deepcopy(self.data.connector) metro_connector['multipath'] = True info_dict = self.common.initialize_connection( self.data.test_volume, metro_connector) ref_dict = {'array': self.data.array, 'device_id': self.data.device_id, 'hostlunid': 3, 'maskingview': self.data.masking_view_name_f, 'metro_hostlunid': 3} self.assertEqual(ref_dict, info_dict) @mock.patch.object(rest.PowerMaxRest, 'get_iscsi_ip_address_and_iqn', return_value=([tpd.PowerMaxData.ip], tpd.PowerMaxData.initiator)) @mock.patch.object(common.PowerMaxCommon, '_get_replication_extra_specs', return_value=tpd.PowerMaxData.rep_extra_specs) @mock.patch.object(utils.PowerMaxUtils, 'is_metro_device', return_value=True) def test_initialize_connection_vol_metro_iscsi(self, mock_md, mock_es, mock_ip): metro_connector = deepcopy(self.data.connector) metro_connector['multipath'] = True info_dict = self.iscsi_common.initialize_connection( self.data.test_volume, metro_connector) ref_dict = {'array': self.data.array, 'device_id': self.data.device_id, 'hostlunid': 3, 'maskingview': self.data.masking_view_name_f, 'ip_and_iqn': [{'ip': self.data.ip, 'iqn': self.data.initiator}], 'metro_hostlunid': 3, 'is_multipath': True, 'metro_ip_and_iqn': [{'ip': self.data.ip, 'iqn': self.data.initiator}]} self.assertEqual(ref_dict, info_dict) @mock.patch.object(utils.PowerMaxUtils, 'is_metro_device', return_value=True) def test_initialize_connection_no_multipath_iscsi(self, mock_md): info_dict = self.iscsi_common.initialize_connection( self.data.test_volume, self.data.connector) self.assertIsNone(info_dict) @mock.patch.object( masking.PowerMaxMasking, 'pre_multiattach', return_value=tpd.PowerMaxData.masking_view_dict_multiattach) def test_attach_metro_volume(self, mock_pre): rep_extra_specs = deepcopy(tpd.PowerMaxData.rep_extra_specs) rep_extra_specs[utils.PORTGROUPNAME] = self.data.port_group_name_f hostlunid, remote_port_group = self.common._attach_metro_volume( self.data.test_volume, self.data.connector, False, self.data.extra_specs, rep_extra_specs) self.assertEqual(self.data.port_group_name_f, remote_port_group) # Multiattach case self.common._attach_metro_volume( self.data.test_volume, self.data.connector, True, self.data.extra_specs, rep_extra_specs) mock_pre.assert_called_once() def test_set_config_file_get_extra_specs_rep_enabled(self): extra_specs, _ = self.common._set_config_file_and_get_extra_specs( self.data.test_volume) self.assertTrue(extra_specs['replication_enabled']) def test_populate_masking_dict_is_re(self): extra_specs = deepcopy(self.extra_specs) extra_specs[utils.PORTGROUPNAME] = self.data.port_group_name_f masking_dict = self.common._populate_masking_dict( self.data.test_volume, self.data.connector, extra_specs) self.assertTrue(masking_dict['replication_enabled']) self.assertEqual('OS-HostX-SRP_1-DiamondDSS-OS-fibre-PG-RE', masking_dict[utils.SG_NAME]) @mock.patch.object(common.PowerMaxCommon, '_replicate_volume', return_value=({}, {})) @mock.patch.object(rest.PowerMaxRest, 'get_array_model_info', return_value=('VMAX250F', False)) @mock.patch.object(common.PowerMaxCommon, 'get_volume_metadata', return_value='') def test_manage_existing_is_replicated(self, mck_meta, mock_model, mock_rep): extra_specs = deepcopy(self.extra_specs) extra_specs[utils.PORTGROUPNAME] = self.data.port_group_name_f external_ref = {u'source-name': u'00002'} volume_name = self.utils.get_volume_element_name( self.data.test_volume.id) provider_location = {'device_id': u'00002', 'array': self.data.array} with mock.patch.object( self.common, '_check_lun_valid_for_cinder_management', return_value=(volume_name, 'test_sg')): self.common.manage_existing( self.data.test_volume, external_ref) mock_rep.assert_called_once_with( self.data.test_volume, volume_name, provider_location, extra_specs, delete_src=False) @mock.patch.object(common.PowerMaxCommon, '_sync_check') @mock.patch.object(masking.PowerMaxMasking, 'remove_and_reset_members') @mock.patch.object(rest.PowerMaxRest, 'get_array_model_info', return_value=('VMAX250F', False)) def test_setup_volume_replication(self, mock_model, mock_rm, mck_sync): rep_status, rep_data, __ = self.common.setup_volume_replication( self.data.array, self.data.test_volume, self.data.device_id, self.extra_specs) self.assertEqual(fields.ReplicationStatus.ENABLED, rep_status) self.assertEqual({'array': self.data.remote_array, 'device_id': self.data.device_id}, rep_data) @mock.patch.object(common.PowerMaxCommon, '_sync_check') @mock.patch.object(masking.PowerMaxMasking, 'remove_and_reset_members') @mock.patch.object(common.PowerMaxCommon, '_create_volume') @mock.patch.object(rest.PowerMaxRest, 'get_array_model_info', return_value=('VMAX250F', False)) def test_setup_volume_replication_target( self, mock_model, mock_create, mock_rm, mck_sync): rep_status, rep_data, __ = self.common.setup_volume_replication( self.data.array, self.data.test_volume, self.data.device_id, self.extra_specs, self.data.device_id2) self.assertEqual(fields.ReplicationStatus.ENABLED, rep_status) self.assertEqual({'array': self.data.remote_array, 'device_id': self.data.device_id2}, rep_data) mock_create.assert_not_called() @mock.patch.object(rest.PowerMaxRest, 'get_rdf_group', return_value={ 'numDevices': 1}) @mock.patch.object(rest.PowerMaxRest, 'get_size_of_device_on_array') @mock.patch.object(common.PowerMaxCommon, '_get_replication_extra_specs', return_value=tpd.PowerMaxData.rep_extra_specs6) @mock.patch.object(common.PowerMaxCommon, '_create_volume', return_value={ 'device_id': tpd.PowerMaxData.device_id2}) @mock.patch.object(rest.PowerMaxRest, 'get_storage_group', return_value=None) @mock.patch.object(rest.PowerMaxRest, 'create_storage_group') @mock.patch.object(masking.PowerMaxMasking, 'add_volume_to_storage_group') @mock.patch.object(common.PowerMaxCommon, '_sync_check') @mock.patch.object(rest.PowerMaxRest, 'create_rdf_device_pair', return_value={'rdf_dict'}) @mock.patch.object(metadata.PowerMaxVolumeMetadata, 'gather_replication_info', return_value={'rep_info_dict'}) def test_setup_inuse_volume_replication( self, mck_gather_rep_info, mck_create_rdf_pair, mck_sync_check, mck_add_vol_to_sg, mck_create_sg, mck_get_sg, mck_create_vol, mck_get_rep_specs, mck_get_size, mck_get_rdf_grp): array = self.data.array volume = self.data.test_attached_volume volume_id = volume.id target_name = self.common.utils.get_volume_element_name(volume_id) target_device_id = tpd.PowerMaxData.device_id2 device_id = self.data.device_id extra_specs = self.data.extra_specs_rep_enabled self.common.rep_config['mode'] = utils.REP_METRO rdf_group_no, remote_array = self.common.get_rdf_details(array) rep_extra_specs = self.common._get_replication_extra_specs( extra_specs, self.common.rep_config) async_sg = self.common.utils.get_async_rdf_managed_grp_name( self.common.rep_config) status, driver_data, info_dict = ( self.common.setup_inuse_volume_replication( array, volume, device_id, extra_specs)) self.assertEqual(status, common.REPLICATION_ENABLED) self.assertEqual(driver_data, {'rdf_dict'}) self.assertEqual(info_dict, {'rep_info_dict'}) mck_get_rdf_grp.assert_called_with(array, rdf_group_no) mck_get_size.assert_called_once_with(array, device_id) mck_get_rep_specs.assert_called_with( extra_specs, self.common.rep_config) mck_create_vol.assert_called_once() mck_get_sg.assert_called_once_with(remote_array, async_sg) mck_create_sg.assert_called_once_with( remote_array, async_sg, extra_specs['srp'], extra_specs['slo'], extra_specs['workload'], rep_extra_specs) mck_sync_check.assert_called_once_with(array, device_id, extra_specs, tgt_only=True) mck_add_vol_to_sg.assert_called_once_with( remote_array, target_device_id, async_sg, target_name, rep_extra_specs, True) mck_create_rdf_pair.assert_called_once_with( array, device_id, rdf_group_no, target_device_id, remote_array, extra_specs) mck_gather_rep_info.assert_called_with( volume_id, 'replication', False, rdf_group_no=rdf_group_no, target_name=target_name, remote_array=remote_array, target_device_id=target_device_id, replication_status=common.REPLICATION_ENABLED, rep_mode=rep_extra_specs['rep_mode'], rdf_group_label=self.common.rep_config['rdf_group_label'], target_array_model=rep_extra_specs['target_array_model']) @mock.patch.object(rest.PowerMaxRest, 'get_array_model_info', return_value=('VMAX250F', False)) @mock.patch.object(common.PowerMaxCommon, '_cleanup_remote_target') def test_cleanup_lun_replication_success(self, mock_clean, mock_model): rep_extra_specs = deepcopy(self.data.rep_extra_specs) rep_extra_specs[utils.PORTGROUPNAME] = self.data.port_group_name_f rep_extra_specs['target_array_model'] = 'VMAX250F' self.common.cleanup_lun_replication( self.data.test_volume, '1', self.data.device_id, self.extra_specs) mock_clean.assert_called_once_with( self.data.array, self.data.test_volume, self.data.remote_array, self.data.device_id, self.data.device_id2, self.data.rdf_group_no, '1', rep_extra_specs) # Cleanup legacy replication self.common.cleanup_lun_replication( self.data.test_legacy_vol, '1', self.data.device_id, self.extra_specs) mock_clean.assert_called_once_with( self.data.array, self.data.test_volume, self.data.remote_array, self.data.device_id, self.data.device_id2, self.data.rdf_group_no, '1', rep_extra_specs) @mock.patch.object(rest.PowerMaxRest, 'get_array_model_info', return_value=('VMAX250F', False)) @mock.patch.object(common.PowerMaxCommon, '_cleanup_remote_target') def test_cleanup_lun_replication_no_target(self, mock_clean, mock_model): with mock.patch.object(self.common, 'get_remote_target_device', return_value=(None, '', '', '', '')): self.common.cleanup_lun_replication( self.data.test_volume, '1', self.data.device_id, self.extra_specs) mock_clean.assert_not_called() @mock.patch.object(rest.PowerMaxRest, 'get_array_model_info', return_value=('VMAX250F', False)) @mock.patch.object(common.PowerMaxCommon, '_cleanup_remote_target') @mock.patch.object(utils.PowerMaxUtils, 'get_rdf_managed_storage_group', return_value=( tpd.PowerMaxData.rdf_managed_async_grp, {})) @mock.patch.object(rest.PowerMaxRest, 'remove_vol_from_sg') def test_cleanup_lun_replication_async( self, mock_rm_sg, mock_get_rdf_sg, mock_clean, mock_model): rep_extra_specs = deepcopy(self.data.rep_extra_specs) rep_extra_specs[utils.PORTGROUPNAME] = self.data.port_group_name_f rep_extra_specs['target_array_model'] = 'VMAX250F' self.common.cleanup_lun_replication( self.data.test_volume, '1', self.data.device_id, self.extra_specs) mock_rm_sg.assert_called_once_with( self.data.array, self.data.rdf_managed_async_grp, self.data.device_id, self.extra_specs) @mock.patch.object(common.PowerMaxCommon, '_cleanup_metro_target') @mock.patch.object(masking.PowerMaxMasking, 'remove_vol_from_storage_group') @mock.patch.object(common.PowerMaxCommon, '_delete_from_srp') @mock.patch.object(provision.PowerMaxProvision, 'break_rdf_relationship') def test_cleanup_remote_target(self, mock_break, mock_del, mock_rm, mock_clean_metro): with mock.patch.object(self.rest, 'are_vols_rdf_paired', return_value=(False, '', '')): self.common._cleanup_remote_target( self.data.array, self.data.test_volume, self.data.remote_array, self.data.device_id, self.data.device_id2, self.data.rdf_group_name, 'vol1', self.data.rep_extra_specs) mock_break.assert_not_called() self.common._cleanup_remote_target( self.data.array, self.data.test_volume, self.data.remote_array, self.data.device_id, self.data.device_id2, self.data.rdf_group_name, 'vol1', self.data.rep_extra_specs) mock_break.assert_called_once_with( self.data.array, self.data.device_id, self.data.device_id2, self.data.rdf_group_name, self.data.rep_extra_specs, 'Synchronized') # is metro volume with mock.patch.object(self.utils, 'is_metro_device', return_value=True): self.common._cleanup_remote_target( self.data.array, self.data.test_volume, self.data.remote_array, self.data.device_id, self.data.device_id2, self.data.rdf_group_name, 'vol1', self.data.rep_extra_specs) mock_clean_metro.assert_called_once() def test_cleanup_remote_target_exception(self): extra_specs = deepcopy(self.data.rep_extra_specs) extra_specs['mode'] = utils.REP_METRO self.assertRaises(exception.VolumeBackendAPIException, self.metro_driver.common._cleanup_remote_target, self.data.array, self.data.test_volume, self.data.remote_array, self.data.device_id, self.data.device_id2, self.data.rdf_group_name, 'vol1', extra_specs) @mock.patch.object(provision.PowerMaxProvision, 'enable_group_replication') @mock.patch.object(rest.PowerMaxRest, 'get_num_vols_in_sg', side_effect=[2, 0]) def test_cleanup_metro_target(self, mock_vols, mock_enable): # allow delete is True specs = {'allow_del_metro': True} for x in range(0, 2): self.common._cleanup_metro_target( self.data.array, self.data.device_id, self.data.device_id2, self.data.rdf_group_no, specs) mock_enable.assert_called_once() # allow delete is False specs['allow_del_metro'] = False self.assertRaises(exception.VolumeBackendAPIException, self.common._cleanup_metro_target, self.data.array, self.data.device_id, self.data.device_id2, self.data.rdf_group_no, specs) @mock.patch.object(common.PowerMaxCommon, '_remove_vol_and_cleanup_replication') @mock.patch.object(masking.PowerMaxMasking, 'remove_vol_from_storage_group') @mock.patch.object(common.PowerMaxCommon, '_delete_from_srp') @mock.patch.object(common.PowerMaxCommon, '_sync_check') def test_cleanup_replication_source( self, mck_sync, mock_del, mock_rm, mock_clean): self.common._cleanup_replication_source( self.data.array, self.data.test_volume, 'vol1', {'device_id': self.data.device_id}, self.extra_specs) mock_del.assert_called_once_with( self.data.array, self.data.device_id, 'vol1', self.extra_specs) def test_get_rdf_details(self): rdf_group_no, remote_array = self.common.get_rdf_details( self.data.array) self.assertEqual(self.data.rdf_group_no, rdf_group_no) self.assertEqual(self.data.remote_array, remote_array) def test_get_rdf_details_exception(self): with mock.patch.object(self.rest, 'get_rdf_group_number', return_value=None): self.assertRaises(exception.VolumeBackendAPIException, self.common.get_rdf_details, self.data.array) @mock.patch.object(common.PowerMaxCommon, '_sync_check') def test_failover_host(self, mck_sync): volumes = [self.data.test_volume, self.data.test_clone_volume] with mock.patch.object(self.common, '_failover_replication', return_value=(None, {})) as mock_fo: self.common.failover_host(volumes) mock_fo.assert_called_once() @mock.patch.object(common.PowerMaxCommon, 'failover_replication', return_value=({}, {})) def test_failover_host_groups(self, mock_fg): volumes = [self.data.test_volume_group_member] group1 = self.data.test_group self.common.failover_host(volumes, None, [group1]) mock_fg.assert_called_once() def test_get_remote_target_device(self): target_device1, _, _, _, _ = ( self.common.get_remote_target_device( self.data.array, self.data.test_volume, self.data.device_id)) self.assertEqual(self.data.device_id2, target_device1) target_device2, _, _, _, _ = ( self.common.get_remote_target_device( self.data.array, self.data.test_clone_volume, self.data.device_id)) self.assertIsNone(target_device2) with mock.patch.object(self.rest, 'are_vols_rdf_paired', return_value=(False, '')): target_device3, _, _, _, _ = ( self.common.get_remote_target_device( self.data.array, self.data.test_volume, self.data.device_id)) self.assertIsNone(target_device3) with mock.patch.object(self.rest, 'get_volume', return_value=None): target_device4, _, _, _, _ = ( self.common.get_remote_target_device( self.data.array, self.data.test_volume, self.data.device_id)) self.assertIsNone(target_device4) @mock.patch.object(common.PowerMaxCommon, 'get_rdf_details', return_value=(tpd.PowerMaxData.rdf_group_name, tpd.PowerMaxData.remote_array)) @mock.patch.object(rest.PowerMaxRest, 'get_volume', side_effect=exception.VolumeBackendAPIException( data='')) def test_get_remote_target_device_no_target( self, mock_get_vol, mock_get_rdf): target_device, remote_array, rdf_group, local_vol_state, pair_state = ( self.common.get_remote_target_device( self.data.array, self.data.test_volume, self.data.device_id)) self.assertIsNone(target_device) self.assertEqual('', local_vol_state) self.assertEqual('', pair_state) @mock.patch.object(rest.PowerMaxRest, 'get_array_model_info', return_value=('VMAX250F', False)) @mock.patch.object(common.PowerMaxCommon, 'add_volume_to_replication_group') @mock.patch.object(common.PowerMaxCommon, '_sync_check') @mock.patch.object(masking.PowerMaxMasking, 'remove_and_reset_members') def test_enable_rdf(self, mock_remove, mck_sync, mock_add, mock_model): rep_config = self.utils.get_replication_config( [self.replication_device]) self.common.enable_rdf( self.data.array, self.data.test_volume, self.data.device_id, self.data.rdf_group_no, rep_config, 'OS-1', self.data.remote_array, self.data.device_id2, self.extra_specs) self.assertEqual(2, mock_remove.call_count) self.assertEqual(2, mock_add.call_count) @mock.patch.object(rest.PowerMaxRest, 'get_array_model_info', return_value=('VMAX250F', False)) @mock.patch.object(masking.PowerMaxMasking, 'remove_vol_from_storage_group') @mock.patch.object(common.PowerMaxCommon, '_cleanup_remote_target') def test_enable_rdf_exception(self, mock_cleanup, mock_rm, mock_model): rep_config = self.utils.get_replication_config( [self.replication_device]) self.assertRaises( exception.VolumeBackendAPIException, self.common.enable_rdf, self.data.array, self.data.test_volume, self.data.device_id, self.data.failed_resource, rep_config, 'OS-1', self.data.remote_array, self.data.device_id2, self.extra_specs) self.assertEqual(1, mock_cleanup.call_count) def test_add_volume_to_replication_group(self): sg_name = self.common.add_volume_to_replication_group( self.data.array, self.data.device_id, 'vol1', self.extra_specs) self.assertEqual(self.data.default_sg_re_enabled, sg_name) @mock.patch.object(masking.PowerMaxMasking, 'get_or_create_default_storage_group', side_effect=exception.VolumeBackendAPIException) def test_add_volume_to_replication_group_exception(self, mock_get): self.assertRaises( exception.VolumeBackendAPIException, self.common.add_volume_to_replication_group, self.data.array, self.data.device_id, 'vol1', self.extra_specs) @mock.patch.object(rest.PowerMaxRest, 'get_array_model_info', return_value=('VMAX250F', False)) def test_get_replication_extra_specs(self, mock_model): rep_config = self.utils.get_replication_config( [self.replication_device]) # Path one - disable compression extra_specs1 = deepcopy(self.extra_specs) extra_specs1[utils.DISABLECOMPRESSION] = 'true' ref_specs1 = deepcopy(self.data.rep_extra_specs5) rep_extra_specs1 = self.common._get_replication_extra_specs( extra_specs1, rep_config) self.assertEqual(ref_specs1, rep_extra_specs1) # Path two - disable compression, not all flash ref_specs2 = deepcopy(self.data.rep_extra_specs5) with mock.patch.object(self.rest, 'is_compression_capable', return_value=False): rep_extra_specs2 = self.common._get_replication_extra_specs( extra_specs1, rep_config) self.assertEqual(ref_specs2, rep_extra_specs2) @mock.patch.object(rest.PowerMaxRest, 'get_array_model_info', return_value=('PowerMax 2000', True)) def test_get_replication_extra_specs_powermax(self, mock_model): rep_config = self.utils.get_replication_config( [self.replication_device]) rep_specs = deepcopy(self.data.rep_extra_specs2) extra_specs = deepcopy(self.extra_specs) # SLO not valid, both SLO and Workload set to NONE rep_specs['slo'] = None rep_specs['workload'] = None rep_specs['target_array_model'] = 'PowerMax 2000' with mock.patch.object(self.provision, 'verify_slo_workload', return_value=(False, False)): rep_extra_specs = self.common._get_replication_extra_specs( extra_specs, rep_config) self.assertEqual(rep_specs, rep_extra_specs) # SL valid, workload invalid, only workload set to NONE rep_specs['slo'] = 'Diamond' rep_specs['workload'] = None rep_specs['target_array_model'] = 'PowerMax 2000' with mock.patch.object(self.provision, 'verify_slo_workload', return_value=(True, False)): rep_extra_specs = self.common._get_replication_extra_specs( extra_specs, rep_config) self.assertEqual(rep_specs, rep_extra_specs) def test_get_secondary_stats(self): rep_config = self.utils.get_replication_config( [self.replication_device]) array_map = self.common.get_attributes_from_cinder_config() finalarrayinfolist = self.common._get_slo_workload_combinations( array_map) array_info = finalarrayinfolist[0] ref_info = deepcopy(array_info) ref_info['SerialNumber'] = six.text_type(rep_config['array']) ref_info['srpName'] = rep_config['srp'] secondary_info = self.common.get_secondary_stats_info( rep_config, array_info) self.assertEqual(ref_info, secondary_info) @mock.patch.object(common.PowerMaxCommon, 'get_volume_metadata', return_value='') def test_replicate_group(self, mck_meta): volume_model_update = { 'id': self.data.test_volume.id, 'provider_location': self.data.test_volume.provider_location} vols_model_update = self.common._replicate_group( self.data.array, [volume_model_update], self.data.test_vol_grp_name, self.extra_specs) ref_rep_data = {'array': self.data.remote_array, 'device_id': self.data.device_id2} ref_vol_update = { 'id': self.data.test_volume.id, 'provider_location': self.data.test_volume.provider_location, 'replication_driver_data': ref_rep_data, 'replication_status': fields.ReplicationStatus.ENABLED, 'metadata': ''} # Decode string representations of dicts into dicts, because # the string representations are randomly ordered and therefore # hard to compare. vols_model_update[0]['replication_driver_data'] = ast.literal_eval( vols_model_update[0]['replication_driver_data']) self.assertEqual(ref_vol_update, vols_model_update[0]) @mock.patch.object(volume_utils, 'is_group_a_cg_snapshot_type', return_value=False) @mock.patch.object(volume_utils, 'is_group_a_type', return_value=True) def test_create_replicaton_group(self, mock_type, mock_cg_type): ref_model_update = { 'status': fields.GroupStatus.AVAILABLE, 'replication_status': fields.ReplicationStatus.ENABLED} model_update = self.common.create_group(None, self.data.test_group_1) self.assertEqual(ref_model_update, model_update) # Replication mode is async self.assertRaises(exception.InvalidInput, self.async_driver.common.create_group, None, self.data.test_group_1) def test_enable_replication(self): # Case 1: Group not replicated with mock.patch.object(volume_utils, 'is_group_a_type', return_value=False): self.assertRaises(NotImplementedError, self.common.enable_replication, None, self.data.test_group, [self.data.test_volume]) with mock.patch.object(volume_utils, 'is_group_a_type', return_value=True): # Case 2: Empty group model_update, __ = self.common.enable_replication( None, self.data.test_group, []) self.assertEqual({}, model_update) # Case 3: Successfully enabled model_update, __ = self.common.enable_replication( None, self.data.test_group, [self.data.test_volume]) self.assertEqual(fields.ReplicationStatus.ENABLED, model_update['replication_status']) # Case 4: Exception model_update, __ = self.common.enable_replication( None, self.data.test_group_failed, [self.data.test_volume]) self.assertEqual(fields.ReplicationStatus.ERROR, model_update['replication_status']) def test_disable_replication(self): # Case 1: Group not replicated with mock.patch.object(volume_utils, 'is_group_a_type', return_value=False): self.assertRaises(NotImplementedError, self.common.disable_replication, None, self.data.test_group, [self.data.test_volume]) with mock.patch.object(volume_utils, 'is_group_a_type', return_value=True): # Case 2: Empty group model_update, __ = self.common.disable_replication( None, self.data.test_group, []) self.assertEqual({}, model_update) # Case 3: Successfully disabled model_update, __ = self.common.disable_replication( None, self.data.test_group, [self.data.test_volume]) self.assertEqual(fields.ReplicationStatus.DISABLED, model_update['replication_status']) # Case 4: Exception model_update, __ = self.common.disable_replication( None, self.data.test_group_failed, [self.data.test_volume]) self.assertEqual(fields.ReplicationStatus.ERROR, model_update['replication_status']) def test_failover_replication(self): with mock.patch.object(volume_utils, 'is_group_a_type', return_value=True): # Case 1: Empty group model_update, __ = self.common.failover_replication( None, self.data.test_group, []) self.assertEqual({}, model_update) # Case 2: Successfully failed over model_update, __ = self.common.failover_replication( None, self.data.test_group, [self.data.test_volume]) self.assertEqual(fields.ReplicationStatus.FAILED_OVER, model_update['replication_status']) # Case 3: Successfully failed back model_update, __ = self.common.failover_replication( None, self.data.test_group, [self.data.test_volume], secondary_backend_id='default') self.assertEqual(fields.ReplicationStatus.ENABLED, model_update['replication_status']) # Case 4: Exception model_update, __ = self.common.failover_replication( None, self.data.test_group_failed, [self.data.test_volume]) self.assertEqual(fields.ReplicationStatus.ERROR, model_update['replication_status']) @mock.patch.object(provision.PowerMaxProvision, 'failover_group') def test_failover_replication_metro(self, mock_fo): volumes = [self.data.test_volume] _, vol_model_updates = self.common._failover_replication( volumes, group, None, host=True, is_metro=True) mock_fo.assert_not_called() @mock.patch.object(utils.PowerMaxUtils, 'get_volume_group_utils', return_value=(tpd.PowerMaxData.array, {})) @mock.patch.object(common.PowerMaxCommon, '_cleanup_group_replication') @mock.patch.object(volume_utils, 'is_group_a_type', return_value=True) def test_delete_replication_group(self, mock_check, mock_cleanup, mock_utils): self.common._delete_group(self.data.test_rep_group, []) mock_cleanup.assert_called_once() @mock.patch.object(masking.PowerMaxMasking, 'remove_volumes_from_storage_group') @mock.patch.object(utils.PowerMaxUtils, 'check_rep_status_enabled') @mock.patch.object(common.PowerMaxCommon, '_remove_remote_vols_from_volume_group') @mock.patch.object(masking.PowerMaxMasking, 'add_remote_vols_to_volume_group') @mock.patch.object(volume_utils, 'is_group_a_type', return_value=True) @mock.patch.object(volume_utils, 'is_group_a_cg_snapshot_type', return_value=True) def test_update_replicated_group(self, mock_cg_type, mock_type_check, mock_add, mock_remove, mock_check, mock_rm): add_vols = [self.data.test_volume] remove_vols = [self.data.test_clone_volume] self.common.update_group( self.data.test_group_1, add_vols, remove_vols) mock_add.assert_called_once() mock_remove.assert_called_once() @mock.patch.object(masking.PowerMaxMasking, 'remove_volumes_from_storage_group') def test_remove_remote_vols_from_volume_group(self, mock_rm): self.common._remove_remote_vols_from_volume_group( self.data.remote_array, [self.data.test_volume], self.data.test_rep_group, self.data.rep_extra_specs) mock_rm.assert_called_once() @mock.patch.object(masking.PowerMaxMasking, 'remove_and_reset_members') @mock.patch.object(masking.PowerMaxMasking, 'remove_volumes_from_storage_group') def test_cleanup_group_replication(self, mock_rm, mock_rm_reset): self.common._cleanup_group_replication( self.data.array, self.data.test_vol_grp_name, [self.data.device_id], self.extra_specs) mock_rm.assert_called_once() @mock.patch.object(masking.PowerMaxMasking, 'add_volume_to_storage_group') def test_add_volume_to_async_group(self, mock_add): extra_specs = deepcopy(self.extra_specs) extra_specs['rep_mode'] = utils.REP_ASYNC self.async_driver.common._add_volume_to_async_rdf_managed_grp( self.data.array, self.data.device_id, 'name', self.data.remote_array, self.data.device_id2, extra_specs) self.assertEqual(2, mock_add.call_count) def test_add_volume_to_async_group_exception(self): extra_specs = deepcopy(self.extra_specs) extra_specs['rep_mode'] = utils.REP_ASYNC self.assertRaises( exception.VolumeBackendAPIException, self.async_driver.common._add_volume_to_async_rdf_managed_grp, self.data.failed_resource, self.data.device_id, 'name', self.data.remote_array, self.data.device_id2, extra_specs) @mock.patch.object(common.PowerMaxCommon, '_sync_check') @mock.patch.object(rest.PowerMaxRest, 'get_array_model_info', return_value=('VMAX250F', False)) @mock.patch.object(common.PowerMaxCommon, '_add_volume_to_async_rdf_managed_grp') @mock.patch.object(masking.PowerMaxMasking, 'remove_and_reset_members') def test_setup_volume_replication_async( self, mock_rm, mock_add, mock_model, mck_sync): extra_specs = deepcopy(self.extra_specs) extra_specs['rep_mode'] = utils.REP_ASYNC rep_status, rep_data, __ = ( self.async_driver.common.setup_volume_replication( self.data.array, self.data.test_volume, self.data.device_id, extra_specs)) self.assertEqual(fields.ReplicationStatus.ENABLED, rep_status) self.assertEqual({'array': self.data.remote_array, 'device_id': self.data.device_id}, rep_data) mock_add.assert_called_once() @mock.patch.object(common.PowerMaxCommon, '_failover_replication', return_value=({}, {})) @mock.patch.object(common.PowerMaxCommon, '_sync_check') def test_failover_host_async(self, mck_sync, mock_fg): volumes = [self.data.test_volume] extra_specs = deepcopy(self.extra_specs) extra_specs['rep_mode'] = utils.REP_ASYNC with mock.patch.object(common.PowerMaxCommon, '_initial_setup', return_value=extra_specs): self.async_driver.common.failover_host(volumes, None, []) mock_fg.assert_called_once() @mock.patch.object(common.PowerMaxCommon, '_retype_volume', return_value=True) @mock.patch.object(masking.PowerMaxMasking, 'remove_vol_from_storage_group') @mock.patch.object(common.PowerMaxCommon, '_retype_remote_volume', return_value=True) @mock.patch.object( common.PowerMaxCommon, 'setup_volume_replication', return_value=('', tpd.PowerMaxData.provider_location2, '')) @mock.patch.object(common.PowerMaxCommon, '_remove_vol_and_cleanup_replication') @mock.patch.object(utils.PowerMaxUtils, 'is_replication_enabled', side_effect=[False, True, True, False, True, True]) @mock.patch.object(common.PowerMaxCommon, 'get_volume_metadata', return_value='') def test_migrate_volume_replication( self, mck_meta, mock_re, mock_rm_rep, mock_setup, mock_retype, mock_rm, mock_rt): new_type = {'extra_specs': {}} for x in range(0, 3): success, model_update = self.common._migrate_volume( self.data.array, self.data.test_volume, self.data.device_id, self.data.srp, 'OLTP', 'Silver', self.data.test_volume.name, new_type, self.data.extra_specs) self.assertTrue(success) mock_rm_rep.assert_called_once() mock_setup.assert_called_once() mock_retype.assert_called_once() @mock.patch.object( common.PowerMaxCommon, '_get_replication_extra_specs', return_value=tpd.PowerMaxData.extra_specs_rep_enabled) @mock.patch.object(rest.PowerMaxRest, 'get_storage_groups_from_volume', side_effect=[tpd.PowerMaxData.storagegroup_list, ['OS-SRP_1-Diamond-DSS-RE-SG']]) @mock.patch.object(common.PowerMaxCommon, '_retype_volume', return_value=True) def test_retype_volume_replication(self, mock_retype, mock_sg, mock_es): for x in range(0, 2): self.common._retype_remote_volume( self.data.array, self.data.test_volume, self.data.device_id, self.data.test_volume.name, utils.REP_SYNC, True, self.data.extra_specs) mock_retype.assert_called_once() class PowerMaxReplicationDebugTest(test.TestCase): def setUp(self): self.data = tpd.PowerMaxData() super(PowerMaxReplicationDebugTest, self).setUp() mock_logging = self.mock_object(common, 'LOG') mock_log = mock.Mock() mock_log.isEnabledFor = True mock_logging.getLogger = mock.Mock(return_value=mock_log) self.replication_device = { 'target_device_id': self.data.remote_array, 'remote_port_group': self.data.port_group_name_f, 'remote_pool': self.data.srp2, 'rdf_group_label': self.data.rdf_group_name, 'allow_extend': 'True'} volume_utils.get_max_over_subscription_ratio = mock.Mock() configuration = tpfo.FakeConfiguration( None, 'CommonReplicationDebugTests', 1, 1, san_ip='1.1.1.1', san_login='smc', vmax_array=self.data.array, vmax_srp='SRP_1', san_password='smc', san_api_port=8443, vmax_port_groups=[self.data.port_group_name_f], replication_device=self.replication_device, debug=True) rest.PowerMaxRest._establish_rest_session = mock.Mock( return_value=tpfo.FakeRequestsSession()) driver = fc.PowerMaxFCDriver(configuration=configuration) self.driver = driver self.common = self.driver.common self.masking = self.common.masking self.provision = self.common.provision self.rest = self.common.rest self.utils = self.common.utils self.utils.get_volumetype_extra_specs = ( mock.Mock( return_value=self.data.vol_type_extra_specs_rep_enabled)) self.extra_specs = deepcopy(self.data.extra_specs_rep_enabled) self.extra_specs['retries'] = 1 self.extra_specs['interval'] = 1 self.extra_specs['rep_mode'] = 'Synchronous' @mock.patch.object(common.PowerMaxCommon, '_sync_check') @mock.patch.object(masking.PowerMaxMasking, 'remove_and_reset_members') @mock.patch.object(common.PowerMaxCommon, '_create_volume') @mock.patch.object(rest.PowerMaxRest, 'get_array_model_info', return_value=('VMAX250F', False)) def test_setup_volume_replication_target_debug( self, mock_model, mock_create, mock_rm, mck_sync): rep_status, rep_data, rep_info_dict = ( self.common.setup_volume_replication( self.data.array, self.data.test_volume, self.data.device_id, self.extra_specs, self.data.device_id2)) self.assertEqual(fields.ReplicationStatus.ENABLED, rep_status) self.assertEqual({'array': self.data.remote_array, 'device_id': self.data.device_id2}, rep_data) self.assertEqual('VMAX250F', rep_info_dict['target_array_model']) mock_create.assert_not_called() @mock.patch.object(common.PowerMaxCommon, '_sync_check') @mock.patch.object(masking.PowerMaxMasking, 'remove_and_reset_members') @mock.patch.object(rest.PowerMaxRest, 'get_array_model_info', return_value=('VMAX250F', False)) def test_setup_volume_replication_no_target_debug( self, mock_model, mock_rm, mck_sync): rep_status, rep_data, rep_info_dict = ( self.common.setup_volume_replication( self.data.array, self.data.test_volume, self.data.device_id, self.extra_specs)) self.assertEqual(fields.ReplicationStatus.ENABLED, rep_status) self.assertEqual({'array': self.data.remote_array, 'device_id': self.data.device_id}, rep_data) self.assertEqual('VMAX250F', rep_info_dict['target_array_model'])
import { interactor, scoped, } from '@bigtest/interactor'; import ConfirmationModalInteractor from '@folio/stripes-components/lib/ConfirmationModal/tests/interactor'; import { ActionMenuInteractor } from '../action-menu-interactor'; @interactor class FileExtensionDetailsInteractor { actionMenu = new ActionMenuInteractor(); headline = scoped('[data-test-headline]'); extension = scoped('[data-test-extension]'); description = scoped('[data-test-description]'); dataTypes = scoped('[data-test-data-types]'); importBlocked = scoped('[data-test-import-blocked]'); confirmationModal = new ConfirmationModalInteractor('#delete-file-extension-modal'); } export const fileExtensionDetails = new FileExtensionDetailsInteractor('[data-test-pane-file-extension-details]');
var firebaseConfig = { apiKey: "AIzaSyC1BCYOage1fSiIRVXN8TfvaSLEg8JKWVg", authDomain: "justcare-1569097818908.firebaseapp.com", databaseURL: "https://justcare-1569097818908.firebaseio.com", projectId: "justcare-1569097818908", storageBucket: "justcare-1569097818908.appspot.com", messagingSenderId: "402416346671", appId: "1:402416346671:web:cd922f242c03429dca08da", measurementId: "G-T7K2J4G22X" }; firebase.initializeApp(firebaseConfig); function createAccount() { var email = document.getElementById('inputEmail').value; var password = document.getElementById('inputPassword').value; firebase.auth().createUserWithEmailAndPassword(email, password).catch(function(error) { var errorCode = error.code; var errorMessage = error.message; if (errorCode == "auth/weak-password") { alert("Password should be longer than 6 characters."); } else { console.log(errorMessage); } }); } function signIn() { var email = document.getElementById('inputEmail').value; var password = document.getElementById('inputPassword').value; firebase.auth().signInWithEmailAndPassword(email, password).then(() => {window.location.href="landing.html"}).catch(function(error) { var errorMessage = error.message; alert(errorMessage); }); }
import EvaluationRubricForm from "./../../components/form/EvaluationRubricForm" import {MODULES_PERMISSIONS, DEACTIVATE,} from "../../../../../../constants" const {ASSESSMENT_TOOL} = MODULES_PERMISSIONS export const associateEvaluationRubricForm = { path: "/associate/skill", component: EvaluationRubricForm, can: ASSESSMENT_TOOL.permissions[DEACTIVATE] }
(function(){var t,e=[].indexOf||function(t){for(var e=0,n=this.length;e<n;e++)if(e in this&&this[e]===t)return e;return-1},n=[].slice,r=function(t,e){return function(){return t.apply(e,arguments)}},a={}.hasOwnProperty;(t=function(t){return"object"==typeof exports&&"object"==typeof module?t(require("jquery")):"function"==typeof define&&define.amd?define(["jquery"],t):t(jQueryITG)})(function(t){var o,i,l,s,u,c,h,d,p,f,m,g,v,b,C,y,w,A,x,S,N;return i=function(t,e,n){var r,a,o,i;for(t+="",a=t.split("."),o=a[0],i=a.length>1?n+a[1]:"",r=/(\d+)(\d{3})/;r.test(o);)o=o.replace(r,"$1"+e+"$2");return o+i},m=function(e){var n;return n={digitsAfterDecimal:2,scaler:1,thousandsSep:",",decimalSep:".",prefix:"",suffix:""},e=t.extend({},n,e),function(t){var n;return isNaN(t)||!isFinite(t)?"":(n=i((e.scaler*t).toFixed(e.digitsAfterDecimal),e.thousandsSep,e.decimalSep),""+e.prefix+n+e.suffix)}},A=m(),x=m({digitsAfterDecimal:0}),S=m({digitsAfterDecimal:1,scaler:100,suffix:"%"}),l={count:function(t){return null==t&&(t=x),function(){return function(e,n,r){return{count:0,push:function(){return this.count++},value:function(){return this.count},format:t}}}},uniques:function(t,n){return null==n&&(n=x),function(r){var a;return a=r[0],function(r,o,i){return{uniq:[],push:function(t){var n;if(n=t[a],e.call(this.uniq,n)<0)return this.uniq.push(t[a])},value:function(){return t(this.uniq)},format:n,numInputs:null!=a?0:1}}}},sum:function(t){return null==t&&(t=A),function(e){var n;return n=e[0],function(e,r,a){return{sum:0,push:function(t){if(!isNaN(parseFloat(t[n])))return this.sum+=parseFloat(t[n])},value:function(){return this.sum},format:t,numInputs:null!=n?0:1}}}},extremes:function(t,e){return null==e&&(e=A),function(n){var r;return r=n[0],function(n,a,o){return{val:null,sorter:h(null!=n?n.sorters:void 0,r),push:function(e){var n,a,o,i;if(i=e[r],"min"!==t&&"max"!==t||(i=parseFloat(i),isNaN(i)||(this.val=Math[t](i,null!=(n=this.val)?n:i))),"first"===t&&this.sorter(i,null!=(a=this.val)?a:i)<=0&&(this.val=i),"last"===t&&this.sorter(i,null!=(o=this.val)?o:i)>=0)return this.val=i},value:function(){return this.val},format:function(t){return isNaN(t)?t:e(t)},numInputs:null!=r?0:1}}}},quantile:function(t,e){return null==e&&(e=A),function(n){var r;return r=n[0],function(n,a,o){return{vals:[],push:function(t){var e;if(e=parseFloat(t[r]),!isNaN(e))return this.vals.push(e)},value:function(){var e;return 0===this.vals.length?null:(this.vals.sort(function(t,e){return t-e}),e=(this.vals.length-1)*t,(this.vals[Math.floor(e)]+this.vals[Math.ceil(e)])/2)},format:e,numInputs:null!=r?0:1}}}},runningStat:function(t,e,n){return null==t&&(t="mean"),null==e&&(e=1),null==n&&(n=A),function(r){var a;return a=r[0],function(r,o,i){return{n:0,m:0,s:0,push:function(t){var e,n;if(n=parseFloat(t[a]),!isNaN(n))return this.n+=1,1===this.n?this.m=n:(e=this.m+(n-this.m)/this.n,this.s=this.s+(n-this.m)*(n-e),this.m=e)},value:function(){if("mean"===t)return 0===this.n?NaN:this.m;if(this.n<=e)return 0;switch(t){case"var":return this.s/(this.n-e);case"stdev":return Math.sqrt(this.s/(this.n-e))}},format:n,numInputs:null!=a?0:1}}}},sumOverSum:function(t){return null==t&&(t=A),function(e){var n,r;return r=e[0],n=e[1],function(e,a,o){return{sumNum:0,sumDenom:0,push:function(t){if(isNaN(parseFloat(t[r]))||(this.sumNum+=parseFloat(t[r])),!isNaN(parseFloat(t[n])))return this.sumDenom+=parseFloat(t[n])},value:function(){return this.sumNum/this.sumDenom},format:t,numInputs:null!=r&&null!=n?0:2}}}},sumOverSumBound80:function(t,e){return null==t&&(t=!0),null==e&&(e=A),function(n){var r,a;return a=n[0],r=n[1],function(n,o,i){return{sumNum:0,sumDenom:0,push:function(t){if(isNaN(parseFloat(t[a]))||(this.sumNum+=parseFloat(t[a])),!isNaN(parseFloat(t[r])))return this.sumDenom+=parseFloat(t[r])},value:function(){var e;return e=t?1:-1,(.821187207574908/this.sumDenom+this.sumNum/this.sumDenom+1.2815515655446004*e*Math.sqrt(.410593603787454/(this.sumDenom*this.sumDenom)+this.sumNum*(1-this.sumNum/this.sumDenom)/(this.sumDenom*this.sumDenom)))/(1+1.642374415149816/this.sumDenom)},format:e,numInputs:null!=a&&null!=r?0:2}}}},fractionOf:function(t,e,r){return null==e&&(e="total"),null==r&&(r=S),function(){var a;return a=1<=arguments.length?n.call(arguments,0):[],function(n,o,i){return{selector:{total:[[],[]],row:[o,[]],col:[[],i]}[e],inner:t.apply(null,a)(n,o,i),push:function(t){return this.inner.push(t)},format:r,value:function(){return this.inner.value()/n.getAggregator.apply(n,this.selector).inner.value()},numInputs:t.apply(null,a)().numInputs}}}}},l.countUnique=function(t){return l.uniques(function(t){return t.length},t)},l.listUnique=function(t){return l.uniques(function(e){return e.sort(f).join(t)},function(t){return t})},l.max=function(t){return l.extremes("max",t)},l.min=function(t){return l.extremes("min",t)},l.first=function(t){return l.extremes("first",t)},l.last=function(t){return l.extremes("last",t)},l.median=function(t){return l.quantile(.5,t)},l.average=function(t){return l.runningStat("mean",1,t)},l["var"]=function(t,e){return l.runningStat("var",t,e)},l.stdev=function(t,e){return l.runningStat("stdev",t,e)},s=function(t){return{Count:t.count(x),"Count Unique Values":t.countUnique(x),"List Unique Values":t.listUnique(", "),Sum:t.sum(A),"Integer Sum":t.sum(x),Average:t.average(A),Median:t.median(A),"Sample Variance":t["var"](1,A),"Sample Standard Deviation":t.stdev(1,A),Minimum:t.min(A),Maximum:t.max(A),First:t.first(A),Last:t.last(A),"Sum over Sum":t.sumOverSum(A),"80% Upper Bound":t.sumOverSumBound80(!0,A),"80% Lower Bound":t.sumOverSumBound80(!1,A),"Sum as Fraction of Total":t.fractionOf(t.sum(),"total",S),"Sum as Fraction of Rows":t.fractionOf(t.sum(),"row",S),"Sum as Fraction of Columns":t.fractionOf(t.sum(),"col",S),"Count as Fraction of Total":t.fractionOf(t.count(),"total",S),"Count as Fraction of Rows":t.fractionOf(t.count(),"row",S),"Count as Fraction of Columns":t.fractionOf(t.count(),"col",S)}}(l),b={Table:function(t,e){return g(t,e)},"Table Barchart":function(e,n){return t(g(e,n)).barchart()},Heatmap:function(e,n){return t(g(e,n)).heatmap("heatmap",n)},"Row Heatmap":function(e,n){return t(g(e,n)).heatmap("rowheatmap",n)},"Col Heatmap":function(e,n){return t(g(e,n)).heatmap("colheatmap",n)}},d={en:{aggregators:s,renderers:b,localeStrings:{renderError:"An error occurred rendering the PivotTable results.",computeError:"An error occurred computing the PivotTable results.",uiRenderError:"An error occurred rendering the PivotTable UI.",selectAll:"Select All",selectNone:"Select None",tooMany:"(too many to list)",filterResults:"Filter values",apply:"Apply",cancel:"Cancel",totals:"Totals",vs:"vs",by:"by"}}},p=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],u=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],N=function(t){return("0"+t).substr(-2,2)},c={bin:function(t,e){return function(n){return n[t]-n[t]%e}},dateFormat:function(t,e,n,r,a){var o;return null==n&&(n=!1),null==r&&(r=p),null==a&&(a=u),o=n?"UTC":"",function(n){var i;return i=new Date(Date.parse(n[t])),isNaN(i)?"":e.replace(/%(.)/g,function(t,e){switch(e){case"y":return i["get"+o+"FullYear"]();case"m":return N(i["get"+o+"Month"]()+1);case"n":return r[i["get"+o+"Month"]()];case"d":return N(i["get"+o+"Date"]());case"w":return a[i["get"+o+"Day"]()];case"x":return i["get"+o+"Day"]();case"H":return N(i["get"+o+"Hours"]());case"M":return N(i["get"+o+"Minutes"]());case"S":return N(i["get"+o+"Seconds"]());default:return"%"+e}})}}},C=/(\d+)|(\D+)/g,v=/\d/,y=/^0/,f=function(t){return function(t,e){var n,r,a,o,i,l;if(null!=e&&null==t)return-1;if(null!=t&&null==e)return 1;if("number"==typeof t&&isNaN(t))return-1;if("number"==typeof e&&isNaN(e))return 1;if(i=+t,l=+e,i<l)return-1;if(i>l)return 1;if("number"==typeof t&&"number"!=typeof e)return-1;if("number"==typeof e&&"number"!=typeof t)return 1;if("number"==typeof t&&"number"==typeof e)return 0;if(isNaN(l)&&!isNaN(i))return-1;if(isNaN(i)&&!isNaN(l))return 1;if(n=String(t),a=String(e),n===a)return 0;if(!v.test(n)||!v.test(a))return n>a?1:-1;for(n=n.match(C),a=a.match(C);n.length&&a.length;)if(r=n.shift(),o=a.shift(),r!==o)return v.test(r)&&v.test(o)?r.replace(y,".0")-o.replace(y,".0"):r>o?1:-1;return n.length-a.length}}(this),w=function(t){var e,n,r,a;r={},n={};for(e in t)a=t[e],r[a]=e,"string"==typeof a&&(n[a.toLowerCase()]=e);return function(t,e){return null!=r[t]&&null!=r[e]?r[t]-r[e]:null!=r[t]?-1:null!=r[e]?1:null!=n[t]&&null!=n[e]?n[t]-n[e]:null!=n[t]?-1:null!=n[e]?1:f(t,e)}},h=function(e,n){var r;if(null!=e)if(t.isFunction(e)){if(r=e(n),t.isFunction(r))return r}else if(null!=e[n])return e[n];return f},o=function(){function e(t,n){var a,o,i,s,u,c,h,d,p,f;null==n&&(n={}),this.getAggregator=r(this.getAggregator,this),this.getRowKeys=r(this.getRowKeys,this),this.getColKeys=r(this.getColKeys,this),this.sortKeys=r(this.sortKeys,this),this.arrSort=r(this.arrSort,this),this.input=t,this.aggregator=null!=(a=n.aggregator)?a:l.count()(),this.aggregatorName=null!=(o=n.aggregatorName)?o:"Count",this.colAttrs=null!=(i=n.cols)?i:[],this.rowAttrs=null!=(s=n.rows)?s:[],this.valAttrs=null!=(u=n.vals)?u:[],this.sorters=null!=(c=n.sorters)?c:{},this.rowOrder=null!=(h=n.rowOrder)?h:"key_a_to_z",this.colOrder=null!=(d=n.colOrder)?d:"key_a_to_z",this.derivedAttributes=null!=(p=n.derivedAttributes)?p:{},this.filter=null!=(f=n.filter)?f:function(){return!0},this.tree={},this.rowKeys=[],this.colKeys=[],this.rowTotals={},this.colTotals={},this.allTotal=this.aggregator(this,[],[]),this.sorted=!1,e.forEachRecord(this.input,this.derivedAttributes,function(t){return function(e){if(t.filter(e))return t.processRecord(e)}}(this))}return e.forEachRecord=function(e,n,r){var o,i,l,s,u,c,h,d,p,f,m,g;if(o=t.isEmptyObject(n)?r:function(t){var e,a,o;for(e in n)o=n[e],t[e]=null!=(a=o(t))?a:t[e];return r(t)},t.isFunction(e))return e(o);if(t.isArray(e)){if(t.isArray(e[0])){f=[];for(l in e)if(a.call(e,l)&&(i=e[l],l>0)){d={},p=e[0];for(s in p)a.call(p,s)&&(u=p[s],d[u]=i[s]);f.push(o(d))}return f}for(m=[],c=0,h=e.length;c<h;c++)d=e[c],m.push(o(d));return m}if(e instanceof t)return g=[],t("thead > tr > th",e).each(function(e){return g.push(t(this).text())}),t("tbody > tr",e).each(function(e){return d={},t("td",this).each(function(e){return d[g[e]]=t(this).text()}),o(d)});throw new Error("unknown input format")},e.prototype.forEachMatchingRecord=function(t,n){return e.forEachRecord(this.input,this.derivedAttributes,function(e){return function(r){var a,o,i;if(e.filter(r)){for(a in t)if(i=t[a],i!==(null!=(o=r[a])?o:"null"))return;return n(r)}}}(this))},e.prototype.arrSort=function(t){var e,n;return n=function(){var n,r,a;for(a=[],n=0,r=t.length;n<r;n++)e=t[n],a.push(h(this.sorters,e));return a}.call(this),function(t,e){var r,o,i;for(o in n)if(a.call(n,o)&&(i=n[o],r=i(t[o],e[o]),0!==r))return r;return 0}},e.prototype.sortKeys=function(){var t;if(!this.sorted){switch(this.sorted=!0,t=function(t){return function(e,n){return t.getAggregator(e,n).value()}}(this),this.rowOrder){case"value_a_to_z":this.rowKeys.sort(function(e){return function(e,n){return f(t(e,[]),t(n,[]))}}(this));break;case"value_z_to_a":this.rowKeys.sort(function(e){return function(e,n){return-f(t(e,[]),t(n,[]))}}(this));break;default:this.rowKeys.sort(this.arrSort(this.rowAttrs))}switch(this.colOrder){case"value_a_to_z":return this.colKeys.sort(function(e){return function(e,n){return f(t([],e),t([],n))}}(this));case"value_z_to_a":return this.colKeys.sort(function(e){return function(e,n){return-f(t([],e),t([],n))}}(this));default:return this.colKeys.sort(this.arrSort(this.colAttrs))}}},e.prototype.getColKeys=function(){return this.sortKeys(),this.colKeys},e.prototype.getRowKeys=function(){return this.sortKeys(),this.rowKeys},e.prototype.processRecord=function(t){var e,n,r,a,o,i,l,s,u,c,h,d,p;for(e=[],d=[],s=this.colAttrs,a=0,o=s.length;a<o;a++)p=s[a],e.push(null!=(u=t[p])?u:"null");for(c=this.rowAttrs,l=0,i=c.length;l<i;l++)p=c[l],d.push(null!=(h=t[p])?h:"null");if(r=d.join(String.fromCharCode(0)),n=e.join(String.fromCharCode(0)),this.allTotal.push(t),0!==d.length&&(this.rowTotals[r]||(this.rowKeys.push(d),this.rowTotals[r]=this.aggregator(this,d,[])),this.rowTotals[r].push(t)),0!==e.length&&(this.colTotals[n]||(this.colKeys.push(e),this.colTotals[n]=this.aggregator(this,[],e)),this.colTotals[n].push(t)),0!==e.length&&0!==d.length)return this.tree[r]||(this.tree[r]={}),this.tree[r][n]||(this.tree[r][n]=this.aggregator(this,d,e)),this.tree[r][n].push(t)},e.prototype.getAggregator=function(t,e){var n,r,a;return a=t.join(String.fromCharCode(0)),r=e.join(String.fromCharCode(0)),n=0===t.length&&0===e.length?this.allTotal:0===t.length?this.colTotals[r]:0===e.length?this.rowTotals[a]:this.tree[a][r],null!=n?n:{value:function(){return null},format:function(){return""}}},e}(),t.pivotUtilities={aggregatorTemplates:l,aggregators:s,renderers:b,derivers:c,locales:d,naturalSort:f,numberFormat:m,sortAs:w,PivotData:o},g=function(e,n){var r,o,i,l,s,u,c,h,d,p,f,m,g,v,b,C,y,w,A,x,S,N,T,k;u={table:{clickCallback:null,rowTotals:!0,colTotals:!0},localeStrings:{totals:"Totals"}},n=t.extend(!0,{},u,n),i=e.colAttrs,m=e.rowAttrs,v=e.getRowKeys(),s=e.getColKeys(),n.table.clickCallback&&(c=function(t,r,o){var l,s,u;s={};for(u in i)a.call(i,u)&&(l=i[u],null!=o[u]&&(s[l]=o[u]));for(u in m)a.call(m,u)&&(l=m[u],null!=r[u]&&(s[l]=r[u]));return function(r){return n.table.clickCallback(r,t,s,e)}}),f=document.createElement("table"),f.className="pvtTable",b=function(t,e,n){var r,a,o,i,l,s,u,c;if(0!==e){for(i=!0,c=r=0,l=n;0<=l?r<=l:r>=l;c=0<=l?++r:--r)t[e-1][c]!==t[e][c]&&(i=!1);if(i)return-1}for(a=0;e+a<t.length;){for(u=!1,c=o=0,s=n;0<=s?o<=s:o>=s;c=0<=s?++o:--o)t[e][c]!==t[e+a][c]&&(u=!0);if(u)break;a++}return a},A=document.createElement("thead");for(d in i)if(a.call(i,d)){o=i[d],S=document.createElement("tr"),0===parseInt(d)&&0!==m.length&&(w=document.createElement("th"),w.setAttribute("colspan",m.length),w.setAttribute("rowspan",i.length),S.appendChild(w)),w=document.createElement("th"),w.className="pvtAxisLabel",w.textContent=o,S.appendChild(w);for(h in s)a.call(s,h)&&(l=s[h],k=b(s,parseInt(h),parseInt(d)),k!==-1&&(w=document.createElement("th"),w.className="pvtColLabel",w.textContent=l[d],w.setAttribute("colspan",k),parseInt(d)===i.length-1&&0!==m.length&&w.setAttribute("rowspan",2),S.appendChild(w)));0===parseInt(d)&&n.table.rowTotals&&(w=document.createElement("th"),w.className="pvtTotalLabel pvtRowTotalLabel",w.innerHTML=n.localeStrings.totals,w.setAttribute("rowspan",i.length+(0===m.length?0:1)),S.appendChild(w)),A.appendChild(S)}if(0!==m.length){S=document.createElement("tr");for(h in m)a.call(m,h)&&(p=m[h],w=document.createElement("th"),w.className="pvtAxisLabel",w.textContent=p,S.appendChild(w));w=document.createElement("th"),0===i.length&&(w.className="pvtTotalLabel pvtRowTotalLabel",w.innerHTML=n.localeStrings.totals),S.appendChild(w),A.appendChild(S)}f.appendChild(A),C=document.createElement("tbody");for(h in v)if(a.call(v,h)){g=v[h],S=document.createElement("tr");for(d in g)a.call(g,d)&&(N=g[d],k=b(v,parseInt(h),parseInt(d)),k!==-1&&(w=document.createElement("th"),w.className="pvtRowLabel",w.textContent=N,w.setAttribute("rowspan",k),parseInt(d)===m.length-1&&0!==i.length&&w.setAttribute("colspan",2),S.appendChild(w)));for(d in s)a.call(s,d)&&(l=s[d],r=e.getAggregator(g,l),T=r.value(),y=document.createElement("td"),y.className="pvtVal row"+h+" col"+d,y.textContent=r.format(T),y.setAttribute("data-value",T),null!=c&&(y.onclick=c(T,g,l)),S.appendChild(y));(n.table.rowTotals||0===i.length)&&(x=e.getAggregator(g,[]),T=x.value(),y=document.createElement("td"),y.className="pvtTotal rowTotal",y.textContent=x.format(T),y.setAttribute("data-value",T),null!=c&&(y.onclick=c(T,g,[])),y.setAttribute("data-for","row"+h),S.appendChild(y)),C.appendChild(S)}if(n.table.colTotals||0===m.length){S=document.createElement("tr"),(n.table.colTotals||0===m.length)&&(w=document.createElement("th"),w.className="pvtTotalLabel pvtColTotalLabel",w.innerHTML=n.localeStrings.totals,w.setAttribute("colspan",m.length+(0===i.length?0:1)),S.appendChild(w));for(d in s)a.call(s,d)&&(l=s[d],x=e.getAggregator([],l),T=x.value(),y=document.createElement("td"),y.className="pvtTotal colTotal",y.textContent=x.format(T),y.setAttribute("data-value",T),null!=c&&(y.onclick=c(T,[],l)),y.setAttribute("data-for","col"+d),S.appendChild(y));(n.table.rowTotals||0===i.length)&&(x=e.getAggregator([],[]),T=x.value(),y=document.createElement("td"),y.className="pvtGrandTotal",y.textContent=x.format(T),y.setAttribute("data-value",T),null!=c&&(y.onclick=c(T,[],[])),S.appendChild(y)),C.appendChild(S)}return f.appendChild(C),f.setAttribute("data-numrows",v.length),f.setAttribute("data-numcols",s.length),f},t.fn.pivot=function(e,n,r){var a,i,s,u,c,h,p,f;null==r&&(r="en"),null==d[r]&&(r="en"),a={cols:[],rows:[],vals:[],rowOrder:"key_a_to_z",colOrder:"key_a_to_z",dataClass:o,filter:function(){return!0},aggregator:l.count()(),aggregatorName:"Count",sorters:{},derivedAttributes:{},renderer:g},u=t.extend(!0,{},d.en.localeStrings,d[r].localeStrings),s={rendererOptions:{localeStrings:u},localeStrings:u},c=t.extend(!0,{},s,t.extend({},a,n)),p=null;try{h=new c.dataClass(e,c);try{p=c.renderer(h,c.rendererOptions)}catch(m){i=m,"undefined"!=typeof console&&null!==console&&console.error(i.stack),p=t("<span>").html(c.localeStrings.renderError)}}catch(m){i=m,"undefined"!=typeof console&&null!==console&&console.error(i.stack),p=t("<span>").html(c.localeStrings.computeError)}for(f=this[0];f.hasChildNodes();)f.removeChild(f.lastChild);return this.append(p)},t.fn.pivotUI=function(n,r,i,l){var s,u,c,p,m,g,v,b,C,y,w,A,x,S,N,T,k,O,_,F,D,E,M,R,I,L,U,K,q,z,V,j,H,B,P,J,G,W,$,Q,Y,X,Z,tt,et;null==i&&(i=!1),null==l&&(l="en"),null==d[l]&&(l="en"),b={derivedAttributes:{},aggregators:d[l].aggregators,renderers:d[l].renderers,hiddenAttributes:[],hiddenFromAggregators:[],hiddenFromDragDrop:[],menuLimit:500,cols:[],rows:[],vals:[],rowOrder:"key_a_to_z",colOrder:"key_a_to_z",dataClass:o,exclusions:{},inclusions:{},unusedAttrsVertical:85,autoSortUnusedAttrs:!1,onRefresh:null,showUI:!0,filter:function(){return!0},sorters:{}},_=t.extend(!0,{},d.en.localeStrings,d[l].localeStrings),O={rendererOptions:{localeStrings:_},localeStrings:_},y=this.data("pivotUIOptions"),M=null==y||i?t.extend(!0,{},O,t.extend({},b,r)):y;try{m={},F=[],L=0,o.forEachRecord(n,M.derivedAttributes,function(t){var e,n,r,o;if(M.filter(t)){F.push(t);for(e in t)a.call(t,e)&&null==m[e]&&(m[e]={},L>0&&(m[e]["null"]=L));for(e in m)o=null!=(r=t[e])?r:"null",null==(n=m[e])[o]&&(n[o]=0),m[e][o]++;return L++}}),Y=t("<table>",{"class":"pvtUi"}).attr("cellpadding",5),B=t("<td>").addClass("pvtUiCell"),H=t("<select>").addClass("pvtRenderer").appendTo(B).bind("change",function(){return V()}),U=M.renderers;for(et in U)a.call(U,et)&&t("<option>").val(et).html(et).appendTo(H);if(X=t("<td>").addClass("pvtAxisContainer pvtUnused pvtUiCell"),J=function(){var t;t=[];for(s in m)e.call(M.hiddenAttributes,s)<0&&t.push(s);return t}(),G=function(){var t,n,r;for(r=[],t=0,n=J.length;t<n;t++)g=J[t],e.call(M.hiddenFromAggregators,g)<0&&r.push(g);return r}(),W=function(){var t,n,r;for(r=[],t=0,n=J.length;t<n;t++)g=J[t],e.call(M.hiddenFromDragDrop,g)<0&&r.push(g);return r}(),tt=!1,Z="auto"===M.unusedAttrsVertical?120:parseInt(M.unusedAttrsVertical),!isNaN(Z)){for(p=0,S=0,N=W.length;S<N;S++)s=W[S],p+=s.length;tt=p>Z}M.unusedAttrsVertical===!0||tt?X.addClass("pvtVertList"):X.addClass("pvtHorizList"),w=function(n){var r,a,o,i,l,s,u,c,d,p,f,g,v,b,C,y,w,x,S;if(S=function(){var t;t=[];for(C in m[n])t.push(C);return t}(),c=!1,x=t("<div>").addClass("pvtFilterBox").hide(),x.append(t("<h4>").append(t("<span>").text(n),t("<span>").addClass("count").text("("+S.length+")"))),S.length>M.menuLimit)x.append(t("<p>").html(M.localeStrings.tooMany));else for(S.length>5&&(i=t("<p>").appendTo(x),v=h(M.sorters,n),f=M.localeStrings.filterResults,t("<input>",{type:"text"}).appendTo(i).attr({placeholder:f,"class":"pvtSearch"}).bind("keyup",function(){var n,r,a;return a=t(this).val().toLowerCase().trim(),r=function(t,n){return function(r){var o,i;return o=a.substring(t.length).trim(),0===o.length||(i=Math.sign(v(r.toLowerCase(),o)),e.call(n,i)>=0)}},n=0===a.indexOf(">=")?r(">=",[1,0]):0===a.indexOf("<=")?r("<=",[-1,0]):0===a.indexOf(">")?r(">",[1]):0===a.indexOf("<")?r("<",[-1]):0===a.indexOf("~")?function(t){return 0===a.substring(1).trim().length||t.toLowerCase().match(a.substring(1))}:function(t){return t.toLowerCase().indexOf(a)!==-1},x.find(".pvtCheckContainer p label span.value").each(function(){return n(t(this).text())?t(this).parent().parent().show():t(this).parent().parent().hide()})}),i.append(t("<br>")),t("<button>",{type:"button"}).appendTo(i).html(M.localeStrings.selectAll).bind("click",function(){return x.find("input:visible:not(:checked)").prop("checked",!0).toggleClass("changed"),!1}),t("<button>",{type:"button"}).appendTo(i).html(M.localeStrings.selectNone).bind("click",function(){return x.find("input:visible:checked").prop("checked",!1).toggleClass("changed"),!1})),a=t("<div>").addClass("pvtCheckContainer").appendTo(x),g=S.sort(h(M.sorters,n)),p=0,d=g.length;p<d;p++)y=g[p],w=m[n][y],l=t("<label>"),s=!1,M.inclusions[n]?s=e.call(M.inclusions[n],y)<0:M.exclusions[n]&&(s=e.call(M.exclusions[n],y)>=0),c||(c=s),t("<input>").attr("type","checkbox").addClass("pvtFilter").attr("checked",!s).data("filter",[n,y]).appendTo(l).bind("change",function(){return t(this).toggleClass("changed")}),l.append(t("<span>").addClass("value").text(y)),l.append(t("<span>").addClass("count").text("("+w+")")),a.append(t("<p>").append(l));return o=function(){return x.find("[type='checkbox']").length>x.find("[type='checkbox']:checked").length?r.addClass("pvtFilteredAttribute"):r.removeClass("pvtFilteredAttribute"),x.find(".pvtSearch").val(""),x.find(".pvtCheckContainer p").show(),x.hide()},u=t("<p>").appendTo(x),S.length<=M.menuLimit&&t("<button>",{type:"button"}).text(M.localeStrings.apply).appendTo(u).bind("click",function(){return x.find(".changed").removeClass("changed").length&&V(),o()}),t("<button>",{type:"button"}).text(M.localeStrings.cancel).appendTo(u).bind("click",function(){return x.find(".changed:checked").removeClass("changed").prop("checked",!1),x.find(".changed:not(:checked)").removeClass("changed").prop("checked",!0),o()}),b=t("<span>").addClass("pvtTriangle").html(" &#x25BE;").bind("click",function(e){var n,r,a;return r=t(e.currentTarget).position(),n=r.left,a=r.top,x.css({left:n+10,top:a+10}).show()}),r=t("<li>").addClass("axis_"+A).append(t("<span>").addClass("pvtAttr").text(n).data("attrName",n).append(b)),c&&r.addClass("pvtFilteredAttribute"),X.append(r).append(x)};for(A in W)a.call(W,A)&&(c=W[A],w(c));$=t("<tr>").appendTo(Y),u=t("<select>").addClass("pvtAggregator").bind("change",function(){return V()}),K=M.aggregators;for(et in K)a.call(K,et)&&u.append(t("<option>").val(et).html(et));for(R={key_a_to_z:{rowSymbol:"&varr;",colSymbol:"&harr;",next:"value_a_to_z"},value_a_to_z:{rowSymbol:"&darr;",colSymbol:"&rarr;",next:"value_z_to_a"},value_z_to_a:{rowSymbol:"&uarr;",colSymbol:"&larr;",next:"key_a_to_z"}},P=t("<a>",{role:"button"}).addClass("pvtRowOrder").data("order",M.rowOrder).html(R[M.rowOrder].rowSymbol).bind("click",function(){return t(this).data("order",R[t(this).data("order")].next),t(this).html(R[t(this).data("order")].rowSymbol),V()}),v=t("<a>",{role:"button"}).addClass("pvtColOrder").data("order",M.colOrder).html(R[M.colOrder].colSymbol).bind("click",function(){return t(this).data("order",R[t(this).data("order")].next),t(this).html(R[t(this).data("order")].colSymbol),V()}),t("<td>").addClass("pvtVals pvtUiCell").appendTo($).append(u).append(P).append(v).append(t("<br>")),t("<td>").addClass("pvtAxisContainer pvtHorizList pvtCols pvtUiCell").appendTo($),Q=t("<tr>").appendTo(Y),Q.append(t("<td>").addClass("pvtAxisContainer pvtRows pvtUiCell").attr("valign","top")),I=t("<td>").attr("valign","top").addClass("pvtRendererArea").appendTo(Q),M.unusedAttrsVertical===!0||tt?(Y.find("tr:nth-child(1)").prepend(B),Y.find("tr:nth-child(2)").prepend(X)):Y.prepend(t("<tr>").append(B).append(X)),this.html(Y),q=M.cols,D=0,T=q.length;D<T;D++)et=q[D],this.find(".pvtCols").append(this.find(".axis_"+t.inArray(et,W)));for(z=M.rows,E=0,k=z.length;E<k;E++)et=z[E],this.find(".pvtRows").append(this.find(".axis_"+t.inArray(et,W)));null!=M.aggregatorName&&this.find(".pvtAggregator").val(M.aggregatorName),null!=M.rendererName&&this.find(".pvtRenderer").val(M.rendererName),M.showUI||this.find(".pvtUiCell").hide(),x=!0,j=function(n){return function(){var r,a,o,i,l,s,h,d,p,m,g,b,C,y;if(m={derivedAttributes:M.derivedAttributes,localeStrings:M.localeStrings,rendererOptions:M.rendererOptions,sorters:M.sorters,cols:[],rows:[],dataClass:M.dataClass},l=null!=(d=M.aggregators[u.val()]([])().numInputs)?d:0,y=[],n.find(".pvtRows li span.pvtAttr").each(function(){return m.rows.push(t(this).data("attrName"))}),n.find(".pvtCols li span.pvtAttr").each(function(){return m.cols.push(t(this).data("attrName"))}),n.find(".pvtVals select.pvtAttrDropdown").each(function(){return 0===l?t(this).remove():(l--,""!==t(this).val()?y.push(t(this).val()):void 0)}),0!==l)for(h=n.find(".pvtVals"),et=g=0,p=l;0<=p?g<p:g>p;et=0<=p?++g:--g){for(i=t("<select>").addClass("pvtAttrDropdown").append(t("<option>")).bind("change",function(){return V()}),b=0,o=G.length;b<o;b++)c=G[b],i.append(t("<option>").val(c).text(c));h.append(i)}if(x&&(y=M.vals,A=0,n.find(".pvtVals select.pvtAttrDropdown").each(function(){return t(this).val(y[A]),A++}),x=!1),m.aggregatorName=u.val(),m.vals=y,m.aggregator=M.aggregators[u.val()](y),m.renderer=M.renderers[H.val()],m.rowOrder=P.data("order"),m.colOrder=v.data("order"),r={},n.find("input.pvtFilter").not(":checked").each(function(){var e;return e=t(this).data("filter"),null!=r[e[0]]?r[e[0]].push(e[1]):r[e[0]]=[e[1]]}),a={},n.find("input.pvtFilter:checked").each(function(){var e;if(e=t(this).data("filter"),null!=r[e[0]])return null!=a[e[0]]?a[e[0]].push(e[1]):a[e[0]]=[e[1]]}),m.filter=function(t){var n,a,o,i;if(!M.filter(t))return!1;for(a in r)if(n=r[a],o=""+(null!=(i=t[a])?i:"null"),e.call(n,o)>=0)return!1;return!0},I.pivot(F,m),s=t.extend({},M,{cols:m.cols,rows:m.rows,colOrder:m.colOrder,rowOrder:m.rowOrder,vals:y,exclusions:r,inclusions:a,inclusionsInfo:a,aggregatorName:u.val(),rendererName:H.val()}),n.data("pivotUIOptions",s),M.autoSortUnusedAttrs&&(C=n.find("td.pvtUnused.pvtAxisContainer"),t(C).children("li").sort(function(e,n){return f(t(e).text(),t(n).text())}).appendTo(C)),I.css("opacity",1),null!=M.onRefresh)return M.onRefresh(s)}}(this),V=function(t){return function(){return I.css("opacity",.5),setTimeout(j,10)}}(this),V(),this.find(".pvtAxisContainer").sortable({update:function(t,e){if(null==e.sender)return V()},connectWith:this.find(".pvtAxisContainer"),items:"li",placeholder:"pvtPlaceholder"})}catch(nt){C=nt,"undefined"!=typeof console&&null!==console&&console.error(C.stack),this.html(M.localeStrings.uiRenderError)}return this},t.fn.heatmap=function(e,n){var r,a,o,i,l,s,u,c,h,d,p;switch(null==e&&(e="heatmap"),c=this.data("numrows"),u=this.data("numcols"),r=null!=n&&null!=(h=n.heatmap)?h.colorScaleGenerator:void 0,null==r&&(r=function(t){var e,n;return n=Math.min.apply(Math,t),e=Math.max.apply(Math,t),function(t){var r;return r=255-Math.round(255*(t-n)/(e-n)),"rgb(255,"+r+","+r+")"}}),a=function(e){return function(n){var a,o,i;return o=function(r){return e.find(n).each(function(){var e;if(e=t(this).data("value"),null!=e&&isFinite(e))return r(e,t(this))})},i=[],o(function(t){return i.push(t)}),a=r(i),o(function(t,e){return e.css("background-color",a(t))})}}(this),e){case"heatmap":a(".pvtVal");break;case"rowheatmap":for(o=l=0,d=c;0<=d?l<d:l>d;o=0<=d?++l:--l)a(".pvtVal.row"+o);break;case"colheatmap":for(i=s=0,p=u;0<=p?s<p:s>p;i=0<=p?++s:--s)a(".pvtVal.col"+i)}return a(".pvtTotal.rowTotal"),a(".pvtTotal.colTotal"),this},t.fn.barchart=function(e){var n,r,a,o,i,l;for(i=this.data("numrows"),o=this.data("numcols"),n=function(e){return function(n){var r,a,o,i,l,s;return r=function(r){return e.find(n).each(function(){var e;if(e=t(this).data("value"),null!=e&&isFinite(e))return r(e,t(this))})},s=[],r(function(t){return s.push(t)}),a=Math.max.apply(Math,s),a<0&&(a=0),i=a,o=Math.min.apply(Math,s),o<0&&(i=a-o),l=function(t){return 100*t/(1.4*i)},r(function(e,n){var r,a,i,s;return i=n.text(),s=t("<div>").css({position:"relative",height:"55px"}),a="gray",r=0,o<0&&(r=l(-o)),e<0&&(r+=l(e),a="darkred",e=-e),s.append(t("<div>").css({position:"absolute",bottom:r+"%",left:0,right:0,height:l(e)+"%","background-color":a})),s.append(t("<div>").text(i).css({position:"relative","padding-left":"5px","padding-right":"5px"})),n.css({padding:0,"padding-top":"5px","text-align":"center"}).html(s)})}}(this),r=a=0,l=i;0<=l?a<l:a>l;r=0<=l?++a:--a)n(".pvtVal.row"+r);return n(".pvtTotal.colTotal"),this}})}).call(this);
import attachUrlMix from './attachUrlMix'; import attrInit from './attrInit'; import eventInit from './eventInit'; import playMix from './playMix'; import pauseMin from './pauseMin'; import toggleMix from './toggleMix'; import seekMix from './seekMix'; import volumeMix from './volumeMix'; import currentTimeMix from './currentTimeMix'; import durationMix from './durationMix'; import switchMix from './switchMix'; import playbackRateMix from './playbackRateMix'; import aspectRatioMix from './aspectRatioMix'; import screenshotMix from './screenshotMix'; import fullscreenMix from './fullscreenMix'; import fullscreenWebMix from './fullscreenWebMix'; import pipMix from './pipMix'; import loadedMix from './loadedMix'; import playedMix from './playedMix'; import playingMix from './playingMix'; import autoSizeMix from './autoSizeMix'; import rectMix from './rectMix'; import flipMix from './flipMix'; import { proxyPropertys } from '../utils'; export default class Player { constructor(art) { attachUrlMix(art, this); eventInit(art, this); attrInit(art, this); playMix(art, this); pauseMin(art, this); toggleMix(art, this); seekMix(art, this); volumeMix(art, this); currentTimeMix(art, this); durationMix(art, this); switchMix(art, this); playbackRateMix(art, this); aspectRatioMix(art, this); screenshotMix(art, this); fullscreenMix(art, this); fullscreenWebMix(art, this); pipMix(art, this); loadedMix(art, this); playedMix(art, this); playingMix(art, this); autoSizeMix(art, this); rectMix(art, this); flipMix(art, this); proxyPropertys(art, this); } }
const config = require('../../config/support.json') const Discord = require("discord.js") class TicketsManager{ create(message, reason){ message.guild.createChannel(`โ–ถ๏ธticket-${message.author.id}`, { type: 'text', permissionOverwrites: [{ id: message.guild.id, deny: ['READ_MESSAGES'] }] }).then(c => { c.setParent(config.category) let e = new Discord.RichEmbed() .setColor("#0yrsz") .setTitle("Ticket") .setDescription("Ticket crรฉe par " + message.author.username + "." + " \n la raison de ce ticket est " + reason + ".") .setFooter("Location-serv.eu", message.author.displayAvatarURL) .setTimestamp(); c.send(e); c.setTopic(`Crรฉateur du ticket : ${message.author.username}\n Raison : ${reason} \n \n /close : ferme le ticket \n /add : ajoute quelq'un au ticket \n /remove : retire quelq'un du ticket`); var support = message.guild.roles.find(r => r.id === config.role) c.overwritePermissions(support, {SEND_MESSAGES: true, READ_MESSAGE_HISTORY: true, READ_MESSAGES: true}); c.overwritePermissions(message.author, {SEND_MESSAGES: true, READ_MESSAGE_HISTORY: true, READ_MESSAGES: true, EMBED_LINKS:true, ATTACH_FILES:true}) message.channel.send(":white_check_mark: Votre ticket est crรฉรฉ !") }) } verify(message){ var chan = message.guild.channels.find(c => c.name == `โ–ถ๏ธticket-${message.author.id}`) if(chan) { message.delete() message.channel.send(":x: Impossible de rรฉcrรฉer un ticket. Veuillez fermer l'autre") return false; } return true; } async close(message){ const base = await message.channel.send(":warning: รŠtes vous sur de vouloir supprimer votre ticket ? Vous ne pourrez plus retrouver les message. \n :white_check_mark: Oui \n <:x:597060657279402004> non") await base.react("โœ…") await base.react("โŒ") const collector = base.createReactionCollector((reaction, user) => user.id === message.author.id); collector.on('collect', async(reaction) => { if (reaction.emoji.name === "โœ…") { var response = new Discord.RichEmbed() .setColor(replay['color']) .setDescription(":arrow_forward: Fermeture de ticket") .addField("Par ", user) var channel = bot.channels.get(config.channels.logs) channel.send(response) message.channel.delete() } if (reaction.emoji.name === "โŒ") { base.delete().catch() message.channel.send(":x: Action annulรฉe. ") } }); } add(message){ let channel = message.guild.channels.find(c => c.name == `โ–ถ๏ธticket-${message.author.id}`) let membre = message.guild.member(message.mentions.users.first()) if(!channel) return message.channel.send(":x: Vous avez aucun ticket de ouvert !") if(!membre) return message.channel.send(":x: Vous devez mentionner quelqu'un ร  ajouter au ticket !") channel.overwritePermissions(membre, {SEND_MESSAGES: true, READ_MESSAGE_HISTORY: true, READ_MESSAGES: true}) message.delete() message.channel.send(`${membre} a bien รฉtรฉ ajoutรฉ au ticket ${channel} par ${message.author.username}.`) } remove(message){ let channel = message.guild.channels.find(c => c.name == `โ–ถ๏ธticket-${message.author.id}`) let membre = message.guild.member(message.mentions.users.first()) if(!channel) return message.channel.send(":x: Vous avez aucun ticket de ouvert !") if(!membre) return message.channel.send(":x: Vous devez mentionner quelqu'un ร  enlรฉver au ticket !") message.channel.overwritePermissions(membre, {SEND_MESSAGES: false, READ_MESSAGE_HISTORY: false, READ_MESSAGES: false}) message.delete() message.channel.send(`${membre} a bien รฉtรฉ retirรฉ du ticket ${message.channel} par ${message.author.username}.`) } } module.exports = TicketsManager;
from __future__ import print_function from molml.features import CoulombMatrix from molml.features import LocalCoulombMatrix from molml.kernel import AtomKernel from molml.utils import LazyValues # Define some base data H2_ELES = ['H', 'H'] H2_NUMS = [1, 1] H2_COORDS = [ [0.0, 0.0, 0.0], [1.0, 0.0, 0.0], ] H2_CONNS = { 0: {1: '1'}, 1: {0: '1'}, } HCN_ELES = ['H', 'C', 'N'] HCN_NUMS = [1, 6, 7] HCN_COORDS = [ [-1.0, 0.0, 0.0], [0.0, 0.0, 0.0], [1.0, 0.0, 0.0], ] HCN_CONNS = { 0: {1: '1'}, 1: {0: '1', 2: '3'}, 2: {1: '3'}, } if __name__ == "__main__": # Example of generating the Coulomb matrix with just elements and coords # for a single example molecule. feat = CoulombMatrix() H2 = (H2_ELES, H2_COORDS) feat.fit([H2]) print("Transformed H2") print(feat.transform([H2])) print() # Example of generating the Coulomb matrix with just elements and coords # for multiple molecules. feat = CoulombMatrix() HCN = (HCN_ELES, HCN_COORDS) feat.fit([H2, HCN]) print("Transformed H2") print(feat.transform([H2])) print("H2 and HCN transformed") print(feat.transform([H2, HCN])) print() # Example of generating the Coulomb matrix with elements, coords, and # connections. feat = CoulombMatrix() H2_conn = (H2_ELES, H2_COORDS, H2_CONNS) HCN_conn = (HCN_ELES, HCN_COORDS, HCN_CONNS) print(feat.fit_transform([H2_conn, HCN_conn])) print() # Example of generating the Coulomb matrix using a specified input_type print("User specified input_type") feat = CoulombMatrix(input_type=("coords", "numbers")) H2_spec = (H2_COORDS, H2_NUMS) HCN_spec = (HCN_COORDS, HCN_NUMS) print(feat.fit_transform([H2_spec, HCN_spec])) print() # Example of generating the Local Coulomb matrix (atom-wise # representation) print("Atom feature") feat = LocalCoulombMatrix() print(feat.fit_transform([H2, HCN])) # Example of generating AtomKernel print("Atom Kernel") feat = AtomKernel(transformer=LocalCoulombMatrix()) print(feat.fit_transform([H2, HCN])) # Example of using arbitrary function to load data # This example is useless, but it shows the possibility feat = CoulombMatrix(input_type=lambda x: LazyValues(elements=HCN_ELES, coords=HCN_COORDS)) feat.fit_transform(list(range(10)))
"use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard"); Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; var React = _interopRequireWildcard(require("react")); var _createSvgIcon = _interopRequireDefault(require("./utils/createSvgIcon")); var _default = (0, _createSvgIcon.default)( /*#__PURE__*/React.createElement("path", { d: "M2.5 4v3h5v12h3V7h5V4h-13zm19 5h-9v3h3v7h3v-7h3V9z" }), 'TextFieldsOutlined'); exports.default = _default;
import _mergeJSXProps from "babel-helper-vue-jsx-merge-props"; export default { name: 'BookmarksIcon', props: { size: { type: String, default: '24' } }, functional: true, render: function render(h, ctx) { var size = parseInt(ctx.props.size) + 'px'; var attrs = ctx.data.attrs || {}; attrs.width = attrs.width || size; attrs.height = attrs.height || size; ctx.data.attrs = attrs; return h("svg", _mergeJSXProps([{ attrs: { xmlns: "http://www.w3.org/2000/svg", width: "24", height: "24", viewBox: "0 0 24 24", "stroke-width": "2", stroke: "currentColor", fill: "none", "stroke-linecap": "round", "stroke-linejoin": "round" }, "class": "icon icon-tabler icon-tabler-bookmarks" }, ctx.data]), [" ", h("path", { attrs: { stroke: "none", d: "M0 0h24v24H0z", fill: "none" } }), " ", h("path", { attrs: { d: "M13 7a2 2 0 0 1 2 2v12l-5 -3l-5 3v-12a2 2 0 0 1 2 -2h6z" } }), " ", h("path", { attrs: { d: "M9.265 4a2 2 0 0 1 1.735 -1h6a2 2 0 0 1 2 2v12l-1 -.6" } }), " "]); } };
/* * Created by Rama41222 on 3/31/18 2:50 AM * Copyright(c) 2018 All rights reserved * Last Modified: 2/19/18 2:36 PM by Rama41222 */ import jwt from 'jsonwebtoken' import _ from 'lodash' import HTTP_STATUS from 'http-status' import constants from './../../config/constants' import User from './user.model' export function fbLogin(req, res, next) { const authToken = `bearer ${req.user.createToken()}` res.set('token', authToken) res.status(HTTP_STATUS.OK).json(req.user.toJSON()) return next() } export async function profile(req, res) { try{ const authToken = `bearer ${req.user.createToken()}` res.set('token', authToken) res.status(HTTP_STATUS.OK).json(req.user.toJSON()) } catch(e) { console.log(e.message) res.status(HTTP_STATUS.BAD_REQUEST).send() } } export async function getSkills(req, res) { try{ const token = req.headers.authorization.split(' ')[1] const decoded = await jwt.verify(token, constants.JWT_SECRET) const uuid = req.params.id || null if(!uuid) { return res.status(HTTP_STATUS.UNAUTHORIZED).send() } let user = await User.findById(uuid) .select('skills') .populate('skills') if(!user) { return res.status(HTTP_STATUS.NO_CONTENT).send() } let skills = await user.toJSONSkills() res.status(HTTP_STATUS.OK).json(skills) } catch(e) { res.status(HTTP_STATUS.BAD_REQUEST).send() } } export async function createSkills(req, res) { try{ const token = req.headers.authorization.split(' ')[1] const decoded = await jwt.verify(token, constants.JWT_SECRET) const uuid = req.params.id || null if(!uuid || uuid !== decoded._id) { return res.status(HTTP_STATUS.UNAUTHORIZED).send() } const newSkill = req.body.skill let user = await User.findById(decoded._id) let skillArray = user.skills let newSkillSet = { skill: newSkill } newSkillSet = [newSkillSet] skillArray.push(newSkillSet) let newSkillArray = _.unionBy(newSkillSet, skillArray, 'skill'); let newUser = await User.findByIdAndUpdate(user._id, { skills: newSkillArray}) if(!newUser) { return res.status(HTTP_STATUS.NO_CONTENT).send() } res.status(HTTP_STATUS.OK).send() } catch(e) { console.log(e.message) res.status(HTTP_STATUS.BAD_REQUEST).send() } } export async function rateSkill(req, res) { try{ const token = req.headers.authorization.split(' ')[1] const decoded = await jwt.verify(token, constants.JWT_SECRET) const newRating = req.body.rating const sid = req.params.sid const uuid = req.params.id || null if(!uuid) { return res.status(HTTP_STATUS.UNAUTHORIZED).send() } let user = await User.findById(uuid) let skillArray = user.skills console.log(skillArray) let skill = await _.find(skillArray, function(o) { console.log(o) console.log(`sid ${sid} === > ${o._id}`) return o._id == sid }); skill.rating.push(newRating) skill = [skill] let newSkillArray = _.unionBy(skill, skillArray, 'skill'); console.log(newSkillArray) let newUser = await User.findByIdAndUpdate(user._id, { skills: newSkillArray}) if(!user) { return res.status(HTTP_STATUS.NO_CONTENT).send() } res.status(HTTP_STATUS.OK).send() } catch(e) { console.log(e.message) res.status(HTTP_STATUS.BAD_REQUEST).send() } } export async function getAllUserRating(req, res) { try{ const token = req.headers.authorization.split(' ')[1] const decoded = await jwt.verify(token, constants.JWT_SECRET) let users = await User.find().select({token:0,email:0}).limit(50) let modUsers = [] for(let user of users) { let featuredskill = user.skills[_.random(0, user.skills.length-1)] user.skills = featuredskill modUsers.push(user) } res.status(HTTP_STATUS.OK).send(modUsers) } catch(e) { console.log(e.message) res.status(HTTP_STATUS.BAD_REQUEST).send() } }
exports.seed = function(knex, Promise) { // Deletes ALL existing entries return knex("buttons").del() .then(function () { // Inserts seed entries return knex("buttons").insert([ {id: 1, group_id: 1, row1col1: true, row1col2: false, row1col3: false, row1col4: false, row1col5: false, row2col1: true, row2col2: false, row2col3: false, row2col4: false, row2col5: false, row3col1: false, row3col2: false, row3col3: false, row3col4: false, row3col5: false, row4col1: false, row4col2: false, row4col3: false, row4col4: false, row4col5: false, row5col1: false, row5col2: false, row5col3: false, row5col4: false, row5col5: false, row6col1: false, row6col2: false, row6col3: false, row6col4: false, row6col5: false}, {id: 2, group_id: 2, row1col1: true, row1col2: true, row1col3: false, row1col4: false, row1col5: false, row2col1: true, row2col2: false, row2col3: false, row2col4: false, row2col5: false, row3col1: false, row3col2: false, row3col3: false, row3col4: false, row3col5: false, row4col1: false, row4col2: false, row4col3: false, row4col4: false, row4col5: false, row5col1: false, row5col2: false, row5col3: false, row5col4: false, row5col5: false, row6col1: false, row6col2: false, row6col3: false, row6col4: false, row6col5: false}, {id: 3, group_id: 2, row1col1: true, row1col2: false, row1col3: false, row1col4: false, row1col5: false, row2col1: true, row2col2: true, row2col3: false, row2col4: false, row2col5:false, row3col1: false, row3col2: false, row3col3: false, row3col4: false, row3col5: false, row4col1: false, row4col2: false, row4col3: false, row4col4: false, row4col5: false, row5col1: false, row5col2: false, row5col3: false, row5col4: false, row5col5: false, row6col1: false, row6col2: false, row6col3: false, row6col4: false, row6col5: false} ]); }) .then(() => { return knex.raw("ALTER SEQUENCE buttons_id_seq RESTART WITH 4;"); }); };
module.exports = { preset: "ts-jest", testEnvironment: "node", collectCoverageFrom: ["dist/**/*.js"], }
import React, { Component } from 'react'; import AppNavbar from './components/AppNavbar' import ShoppingList from './components/ShoppingList' import ItemModal from './components/itemModal'; import {Container} from 'reactstrap' import {Provider} from 'react-redux'; import store from './store'; import 'bootstrap/dist/css/bootstrap.min.css' import './App.css'; class App extends Component { render() { return ( <Provider store={store}> <div className="App"> <AppNavbar/> <Container> <ItemModal/> <ShoppingList/> </Container> </div> </Provider> ); } } export default App;
webpackJsonp([110],{68:function(e,r){e.exports="## Linear Progress\n\nLinear Progress component is a spec-aligned linear progress indicator component adhering to the Material Design progress & activity requirements.\n\n## Usage\n\n```html\n<m-linear-progress value='0.3' buffer='0.5'></m-linear-progress>\n<m-linear-progress value='0.1'> </m-linear-progress>\n<m-linear-progress indeterminate > </m-linear-progress>\n<m-linear-progress reversed value=\"0.2\"> </m-linear-progress>\n```\n\n## Usage in Omi\n\nJSX:\n\n```jsx\n<m-linear-progress value={0.1} buffer={0.5}> </m-linear-progress>\n<m-linear-progress value={0.2} > </m-linear-progress>\n<m-linear-progress indeterminate > </m-linear-progress>\n<m-linear-progress reversed value={0.3}> </m-linear-progress>\n```\n\n## API\n\n### Props\n\n| **Name** | **Type** | **Defaults** | **Details** |\n| ------------- |:-------------:|:-----:|:-------------:|\n| buffer | number | 1 | Buffer progress value |\n| value | number | 0 | The main progress values |\n| indeterminate | boolean | -- | Animation of unknown progress |\n| reversed | boolean | -- | Negative direction progress |\n"}}); //# sourceMappingURL=110.e90931c3.chunk.js.map