text
stringlengths 3
1.05M
|
|---|
const COLLAPSE_UNL = new ExpantaNum(50 * DISTANCES.Mpc);
const ESSENCE_MILESTONES = {
1: {
req: new ExpantaNum(1),
desc: "Time goes by 100x faster, but this gets weaker the further you go (minimum 2x, at 50Mpc).",
disp: function () {
return showNum(collapseMile1Eff()) + "x";
}
},
2: { req: new ExpantaNum(2), desc: "Time goes by 5x faster." },
3: { req: new ExpantaNum(3), desc: "Start with 10 Rockets on reset." },
4: { req: new ExpantaNum(5), desc: "Start with 1 Rocket Fuel on reset." },
5: {
req: new ExpantaNum(10),
desc: "Unlock Fuelbot, and Cadaver gain is boosted by Time Cubes.",
disp: function () {
return showNum(collapseMile5Eff()) + "x";
}
},
6: { req: new ExpantaNum(15), desc: "Gain 10x more Rockets." },
7: { req: new ExpantaNum(25), desc: "Keep Time Reversal upgrades on reset." },
8: {
req: new ExpantaNum(50),
desc: "Time Speed multiplies Rocket gain at a reduced rate.",
disp: function () {
return showNum(collapseMile8Eff()) + "x";
}
},
9: {
req: new ExpantaNum(75),
desc: "Gain 1% of Rocket gain every second (does nothing when Time is Reversed, but unaffected by Time Speed)."
},
10: {
req: new ExpantaNum(100),
desc: "Life Essence boosts Cadaver gain.",
disp: function () {
return showNum(collapseMile10Eff()) + "x";
}
},
11: { req: new ExpantaNum(1000), desc: "Tiers do not reset Ranks." },
12: { req: new ExpantaNum(10000), desc: "Ranks do not reset anything." }
};
const EM_AMT = Object.keys(ESSENCE_MILESTONES).length;
|
module.exports = Math.imul || function(a, b) {
var ah = (a >>> 16) & 0xffff;
var al = a & 0xffff;
var bh = (b >>> 16) & 0xffff;
var bl = b & 0xffff;
// the shift by 0 fixes the sign on the high part
// the final |0 converts the unsigned value into a signed value
return ((al * bl) + (((ah * bl + al * bh) << 16) >>> 0)|0);
};
|
(function webpackUniversalModuleDefinition(root, factory) {
if(typeof exports === 'object' && typeof module === 'object')
module.exports = factory(require("vue"), require("agGrid"));
else if(typeof define === 'function' && define.amd)
define([, "agGrid"], factory);
else if(typeof exports === 'object')
exports["ag-grid-vue"] = factory(require("vue"), require("agGrid"));
else
root["ag-grid-vue"] = factory(root["Vue"], root["agGrid"]);
})((typeof self !== 'undefined' ? self : this), function(__WEBPACK_EXTERNAL_MODULE__8bbf__, __WEBPACK_EXTERNAL_MODULE__8bd4__) {
return /******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId]) {
/******/ return installedModules[moduleId].exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ i: moduleId,
/******/ l: false,
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded
/******/ module.l = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/
/******/ // define getter function for harmony exports
/******/ __webpack_require__.d = function(exports, name, getter) {
/******/ if(!__webpack_require__.o(exports, name)) {
/******/ Object.defineProperty(exports, name, { enumerable: true, get: getter });
/******/ }
/******/ };
/******/
/******/ // define __esModule on exports
/******/ __webpack_require__.r = function(exports) {
/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
/******/ }
/******/ Object.defineProperty(exports, '__esModule', { value: true });
/******/ };
/******/
/******/ // create a fake namespace object
/******/ // mode & 1: value is a module id, require it
/******/ // mode & 2: merge all properties of value into the ns
/******/ // mode & 4: return value when already ns object
/******/ // mode & 8|1: behave like require
/******/ __webpack_require__.t = function(value, mode) {
/******/ if(mode & 1) value = __webpack_require__(value);
/******/ if(mode & 8) return value;
/******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;
/******/ var ns = Object.create(null);
/******/ __webpack_require__.r(ns);
/******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value });
/******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));
/******/ return ns;
/******/ };
/******/
/******/ // getDefaultExport function for compatibility with non-harmony modules
/******/ __webpack_require__.n = function(module) {
/******/ var getter = module && module.__esModule ?
/******/ function getDefault() { return module['default']; } :
/******/ function getModuleExports() { return module; };
/******/ __webpack_require__.d(getter, 'a', getter);
/******/ return getter;
/******/ };
/******/
/******/ // Object.prototype.hasOwnProperty.call
/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/
/******/
/******/ // Load entry module and return exports
/******/ return __webpack_require__(__webpack_require__.s = "fae3");
/******/ })
/************************************************************************/
/******/ ({
/***/ "65d9":
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/**
* vue-class-component v6.3.2
* (c) 2015-present Evan You
* @license MIT
*/
Object.defineProperty(exports, '__esModule', { value: true });
function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
var Vue = _interopDefault(__webpack_require__("8bbf"));
var reflectionIsSupported = typeof Reflect !== 'undefined' && Reflect.defineMetadata;
function copyReflectionMetadata(to, from) {
forwardMetadata(to, from);
Object.getOwnPropertyNames(from.prototype).forEach(function (key) {
forwardMetadata(to.prototype, from.prototype, key);
});
Object.getOwnPropertyNames(from).forEach(function (key) {
forwardMetadata(to, from, key);
});
}
function forwardMetadata(to, from, propertyKey) {
var metaKeys = propertyKey
? Reflect.getOwnMetadataKeys(from, propertyKey)
: Reflect.getOwnMetadataKeys(from);
metaKeys.forEach(function (metaKey) {
var metadata = propertyKey
? Reflect.getOwnMetadata(metaKey, from, propertyKey)
: Reflect.getOwnMetadata(metaKey, from);
if (propertyKey) {
Reflect.defineMetadata(metaKey, metadata, to, propertyKey);
}
else {
Reflect.defineMetadata(metaKey, metadata, to);
}
});
}
var fakeArray = { __proto__: [] };
var hasProto = fakeArray instanceof Array;
function createDecorator(factory) {
return function (target, key, index) {
var Ctor = typeof target === 'function'
? target
: target.constructor;
if (!Ctor.__decorators__) {
Ctor.__decorators__ = [];
}
if (typeof index !== 'number') {
index = undefined;
}
Ctor.__decorators__.push(function (options) { return factory(options, key, index); });
};
}
function mixins() {
var Ctors = [];
for (var _i = 0; _i < arguments.length; _i++) {
Ctors[_i] = arguments[_i];
}
return Vue.extend({ mixins: Ctors });
}
function isPrimitive(value) {
var type = typeof value;
return value == null || (type !== 'object' && type !== 'function');
}
function warn(message) {
if (typeof console !== 'undefined') {
console.warn('[vue-class-component] ' + message);
}
}
function collectDataFromConstructor(vm, Component) {
// override _init to prevent to init as Vue instance
var originalInit = Component.prototype._init;
Component.prototype._init = function () {
var _this = this;
// proxy to actual vm
var keys = Object.getOwnPropertyNames(vm);
// 2.2.0 compat (props are no longer exposed as self properties)
if (vm.$options.props) {
for (var key in vm.$options.props) {
if (!vm.hasOwnProperty(key)) {
keys.push(key);
}
}
}
keys.forEach(function (key) {
if (key.charAt(0) !== '_') {
Object.defineProperty(_this, key, {
get: function () { return vm[key]; },
set: function (value) { vm[key] = value; },
configurable: true
});
}
});
};
// should be acquired class property values
var data = new Component();
// restore original _init to avoid memory leak (#209)
Component.prototype._init = originalInit;
// create plain data object
var plainData = {};
Object.keys(data).forEach(function (key) {
if (data[key] !== undefined) {
plainData[key] = data[key];
}
});
if (false) {}
return plainData;
}
var $internalHooks = [
'data',
'beforeCreate',
'created',
'beforeMount',
'mounted',
'beforeDestroy',
'destroyed',
'beforeUpdate',
'updated',
'activated',
'deactivated',
'render',
'errorCaptured' // 2.5
];
function componentFactory(Component, options) {
if (options === void 0) { options = {}; }
options.name = options.name || Component._componentTag || Component.name;
// prototype props.
var proto = Component.prototype;
Object.getOwnPropertyNames(proto).forEach(function (key) {
if (key === 'constructor') {
return;
}
// hooks
if ($internalHooks.indexOf(key) > -1) {
options[key] = proto[key];
return;
}
var descriptor = Object.getOwnPropertyDescriptor(proto, key);
if (descriptor.value !== void 0) {
// methods
if (typeof descriptor.value === 'function') {
(options.methods || (options.methods = {}))[key] = descriptor.value;
}
else {
// typescript decorated data
(options.mixins || (options.mixins = [])).push({
data: function () {
var _a;
return _a = {}, _a[key] = descriptor.value, _a;
}
});
}
}
else if (descriptor.get || descriptor.set) {
// computed properties
(options.computed || (options.computed = {}))[key] = {
get: descriptor.get,
set: descriptor.set
};
}
});
(options.mixins || (options.mixins = [])).push({
data: function () {
return collectDataFromConstructor(this, Component);
}
});
// decorate options
var decorators = Component.__decorators__;
if (decorators) {
decorators.forEach(function (fn) { return fn(options); });
delete Component.__decorators__;
}
// find super
var superProto = Object.getPrototypeOf(Component.prototype);
var Super = superProto instanceof Vue
? superProto.constructor
: Vue;
var Extended = Super.extend(options);
forwardStaticMembers(Extended, Component, Super);
if (reflectionIsSupported) {
copyReflectionMetadata(Extended, Component);
}
return Extended;
}
var reservedPropertyNames = [
// Unique id
'cid',
// Super Vue constructor
'super',
// Component options that will be used by the component
'options',
'superOptions',
'extendOptions',
'sealedOptions',
// Private assets
'component',
'directive',
'filter'
];
function forwardStaticMembers(Extended, Original, Super) {
// We have to use getOwnPropertyNames since Babel registers methods as non-enumerable
Object.getOwnPropertyNames(Original).forEach(function (key) {
// `prototype` should not be overwritten
if (key === 'prototype') {
return;
}
// Some browsers does not allow reconfigure built-in properties
var extendedDescriptor = Object.getOwnPropertyDescriptor(Extended, key);
if (extendedDescriptor && !extendedDescriptor.configurable) {
return;
}
var descriptor = Object.getOwnPropertyDescriptor(Original, key);
// If the user agent does not support `__proto__` or its family (IE <= 10),
// the sub class properties may be inherited properties from the super class in TypeScript.
// We need to exclude such properties to prevent to overwrite
// the component options object which stored on the extended constructor (See #192).
// If the value is a referenced value (object or function),
// we can check equality of them and exclude it if they have the same reference.
// If it is a primitive value, it will be forwarded for safety.
if (!hasProto) {
// Only `cid` is explicitly exluded from property forwarding
// because we cannot detect whether it is a inherited property or not
// on the no `__proto__` environment even though the property is reserved.
if (key === 'cid') {
return;
}
var superDescriptor = Object.getOwnPropertyDescriptor(Super, key);
if (!isPrimitive(descriptor.value) &&
superDescriptor &&
superDescriptor.value === descriptor.value) {
return;
}
}
// Warn if the users manually declare reserved properties
if (false) {}
Object.defineProperty(Extended, key, descriptor);
});
}
function Component(options) {
if (typeof options === 'function') {
return componentFactory(options);
}
return function (Component) {
return componentFactory(Component, options);
};
}
Component.registerHooks = function registerHooks(keys) {
$internalHooks.push.apply($internalHooks, keys);
};
exports.default = Component;
exports.createDecorator = createDecorator;
exports.mixins = mixins;
/***/ }),
/***/ "8bbf":
/***/ (function(module, exports) {
module.exports = __WEBPACK_EXTERNAL_MODULE__8bbf__;
/***/ }),
/***/ "8bd4":
/***/ (function(module, exports) {
module.exports = __WEBPACK_EXTERNAL_MODULE__8bd4__;
/***/ }),
/***/ "fae3":
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
// CONCATENATED MODULE: ./node_modules/@vue/cli-service/lib/commands/build/setPublicPath.js
// This file is imported into lib/wc client bundles.
if (typeof window !== 'undefined') {
var i
if ((i = window.document.currentScript) && (i = i.src.match(/(.+\/)[^/]+\.js(\?.*)?$/))) {
__webpack_require__.p = i[1] // eslint-disable-line
}
}
// Indicate to webpack that this file can be concatenated
/* harmony default export */ var setPublicPath = (null);
// CONCATENATED MODULE: ./node_modules/tslib/tslib.es6.js
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at http://www.apache.org/licenses/LICENSE-2.0
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/* global Reflect, Promise */
var extendStatics = function(d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return extendStatics(d, b);
};
function __extends(d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
}
var __assign = function() {
__assign = Object.assign || function __assign(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
}
return t;
}
return __assign.apply(this, arguments);
}
function __rest(s, e) {
var t = {};
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
t[p] = s[p];
if (s != null && typeof Object.getOwnPropertySymbols === "function")
for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) if (e.indexOf(p[i]) < 0)
t[p[i]] = s[p[i]];
return t;
}
function __decorate(decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
}
function __param(paramIndex, decorator) {
return function (target, key) { decorator(target, key, paramIndex); }
}
function __metadata(metadataKey, metadataValue) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue);
}
function __awaiter(thisArg, _arguments, P, generator) {
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
}
function __generator(thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
}
function __exportStar(m, exports) {
for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
}
function __values(o) {
var m = typeof Symbol === "function" && o[Symbol.iterator], i = 0;
if (m) return m.call(o);
return {
next: function () {
if (o && i >= o.length) o = void 0;
return { value: o && o[i++], done: !o };
}
};
}
function __read(o, n) {
var m = typeof Symbol === "function" && o[Symbol.iterator];
if (!m) return o;
var i = m.call(o), r, ar = [], e;
try {
while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
}
catch (error) { e = { error: error }; }
finally {
try {
if (r && !r.done && (m = i["return"])) m.call(i);
}
finally { if (e) throw e.error; }
}
return ar;
}
function __spread() {
for (var ar = [], i = 0; i < arguments.length; i++)
ar = ar.concat(__read(arguments[i]));
return ar;
}
function __await(v) {
return this instanceof __await ? (this.v = v, this) : new __await(v);
}
function __asyncGenerator(thisArg, _arguments, generator) {
if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
var g = generator.apply(thisArg, _arguments || []), i, q = [];
return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i;
function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }
function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }
function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }
function fulfill(value) { resume("next", value); }
function reject(value) { resume("throw", value); }
function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }
}
function __asyncDelegator(o) {
var i, p;
return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i;
function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; } : f; }
}
function __asyncValues(o) {
if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
var m = o[Symbol.asyncIterator], i;
return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
}
function __makeTemplateObject(cooked, raw) {
if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; }
return cooked;
};
function __importStar(mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
result.default = mod;
return result;
}
function __importDefault(mod) {
return (mod && mod.__esModule) ? mod : { default: mod };
}
// EXTERNAL MODULE: external {"commonjs":"vue","commonjs2":"vue","root":"Vue"}
var external_commonjs_vue_commonjs2_vue_root_Vue_ = __webpack_require__("8bbf");
var external_commonjs_vue_commonjs2_vue_root_Vue_default = /*#__PURE__*/__webpack_require__.n(external_commonjs_vue_commonjs2_vue_root_Vue_);
// EXTERNAL MODULE: ./node_modules/vue-class-component/dist/vue-class-component.common.js
var vue_class_component_common = __webpack_require__("65d9");
var vue_class_component_common_default = /*#__PURE__*/__webpack_require__.n(vue_class_component_common);
// CONCATENATED MODULE: ./node_modules/vue-property-decorator/lib/vue-property-decorator.js
/** vue-property-decorator verson 7.2.0 MIT LICENSE copyright 2018 kaorun343 */
/**
* decorator of an inject
* @param from key
* @return PropertyDecorator
*/
function Inject(options) {
return Object(vue_class_component_common["createDecorator"])(function (componentOptions, key) {
if (typeof componentOptions.inject === 'undefined') {
componentOptions.inject = {};
}
if (!Array.isArray(componentOptions.inject)) {
componentOptions.inject[key] = options || key;
}
});
}
/**
* decorator of a provide
* @param key key
* @return PropertyDecorator | void
*/
function Provide(key) {
return Object(vue_class_component_common["createDecorator"])(function (componentOptions, k) {
var provide = componentOptions.provide;
if (typeof provide !== 'function' || !provide.managed) {
var original_1 = componentOptions.provide;
provide = componentOptions.provide = function () {
var rv = Object.create((typeof original_1 === 'function' ? original_1.call(this) : original_1) || null);
for (var i in provide.managed)
rv[provide.managed[i]] = this[i];
return rv;
};
provide.managed = {};
}
provide.managed[k] = key || k;
});
}
/**
* decorator of model
* @param event event name
* @param options options
* @return PropertyDecorator
*/
function Model(event, options) {
if (options === void 0) { options = {}; }
return Object(vue_class_component_common["createDecorator"])(function (componentOptions, k) {
(componentOptions.props || (componentOptions.props = {}))[k] = options;
componentOptions.model = { prop: k, event: event || k };
});
}
/**
* decorator of a prop
* @param options the options for the prop
* @return PropertyDecorator | void
*/
function Prop(options) {
if (options === void 0) { options = {}; }
return Object(vue_class_component_common["createDecorator"])(function (componentOptions, k) {
(componentOptions.props || (componentOptions.props = {}))[k] = options;
});
}
/**
* decorator of a watch function
* @param path the path or the expression to observe
* @param WatchOption
* @return MethodDecorator
*/
function Watch(path, options) {
if (options === void 0) { options = {}; }
var _a = options.deep, deep = _a === void 0 ? false : _a, _b = options.immediate, immediate = _b === void 0 ? false : _b;
return Object(vue_class_component_common["createDecorator"])(function (componentOptions, handler) {
if (typeof componentOptions.watch !== 'object') {
componentOptions.watch = Object.create(null);
}
componentOptions.watch[path] = { handler: handler, deep: deep, immediate: immediate };
});
}
// Code copied from Vue/src/shared/util.js
var hyphenateRE = /\B([A-Z])/g;
var hyphenate = function (str) { return str.replace(hyphenateRE, '-$1').toLowerCase(); };
/**
* decorator of an event-emitter function
* @param event The name of the event
* @return MethodDecorator
*/
function Emit(event) {
return function (_target, key, descriptor) {
key = hyphenate(key);
var original = descriptor.value;
descriptor.value = function emitter() {
var _this = this;
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
var emit = function (returnValue) {
if (returnValue !== undefined)
args.unshift(returnValue);
_this.$emit.apply(_this, [event || key].concat(args));
};
var returnValue = original.apply(this, args);
if (isPromise(returnValue)) {
returnValue.then(function (returnValue) {
emit(returnValue);
});
}
else {
emit(returnValue);
}
};
};
}
function isPromise(obj) {
return obj instanceof Promise || (obj && typeof obj.then === 'function');
}
// EXTERNAL MODULE: external "agGrid"
var external_agGrid_ = __webpack_require__("8bd4");
// CONCATENATED MODULE: ./src/VueComponentFactory.ts
var VueComponentFactory_VueComponentFactory = /** @class */ (function () {
function VueComponentFactory() {
}
VueComponentFactory.getComponentType = function (parent, component) {
if (typeof component === 'string') {
var componentInstance = parent.$parent.$options.components[component];
if (!componentInstance) {
console.error("Could not find component with name of " + component + ". Is it in Vue.components?");
return null;
}
return external_commonjs_vue_commonjs2_vue_root_Vue_default.a.extend(componentInstance);
}
else {
// assume a type
return component;
}
};
VueComponentFactory.createAndMountComponent = function (params, componentType, parent) {
var details = {
data: {
params: Object.freeze(params),
},
parent: parent,
};
if (parent.componentDependencies) {
parent.componentDependencies.forEach(function (dependency) {
return details[dependency] = parent[dependency];
});
}
var component = new componentType(details);
component.$mount();
return component;
};
return VueComponentFactory;
}());
// CONCATENATED MODULE: ./src/VueFrameworkComponentWrapper.ts
var VueFrameworkComponentWrapper_VueFrameworkComponentWrapper = /** @class */ (function (_super) {
__extends(VueFrameworkComponentWrapper, _super);
function VueFrameworkComponentWrapper(parent) {
var _this = _super.call(this) || this;
_this.parent = parent;
return _this;
}
VueFrameworkComponentWrapper.prototype.createWrapper = function (component) {
var that = this;
var DynamicComponent = /** @class */ (function (_super) {
__extends(DynamicComponent, _super);
function DynamicComponent() {
return _super !== null && _super.apply(this, arguments) || this;
}
DynamicComponent.prototype.init = function (params) {
_super.prototype.init.call(this, params);
};
DynamicComponent.prototype.hasMethod = function (name) {
return wrapper.getFrameworkComponentInstance()[name] != null;
};
DynamicComponent.prototype.callMethod = function (name, args) {
var componentInstance = this.getFrameworkComponentInstance();
var frameworkComponentInstance = wrapper.getFrameworkComponentInstance();
return frameworkComponentInstance[name].apply(componentInstance, args);
};
DynamicComponent.prototype.addMethod = function (name, callback) {
wrapper[name] = callback;
};
DynamicComponent.prototype.overrideProcessing = function (methodName) {
return that.parent.autoParamsRefresh && methodName === 'refresh';
};
DynamicComponent.prototype.processMethod = function (methodName, args) {
if (methodName === 'refresh') {
this.getFrameworkComponentInstance().params = args[0];
}
if (this.hasMethod(methodName)) {
return this.callMethod(methodName, args);
}
return methodName === 'refresh';
};
DynamicComponent.prototype.createComponent = function (params) {
return that.createComponent(component, params);
};
return DynamicComponent;
}(VueComponent));
var wrapper = new DynamicComponent();
return wrapper;
};
VueFrameworkComponentWrapper.prototype.createComponent = function (component, params) {
var componentType = VueComponentFactory_VueComponentFactory.getComponentType(this.parent, component);
if (!componentType) {
return;
}
return VueComponentFactory_VueComponentFactory.createAndMountComponent(params, componentType, this.parent);
};
VueFrameworkComponentWrapper.prototype.createMethodProxy = function (wrapper, methodName, mandatory) {
return function () {
if (wrapper.overrideProcessing(methodName)) {
return wrapper.processMethod(methodName, arguments);
}
if (wrapper.hasMethod(methodName)) {
return wrapper.callMethod(methodName, arguments);
}
if (mandatory) {
console.warn('ag-Grid: Framework component is missing the method ' + methodName + '()');
}
return null;
};
};
VueFrameworkComponentWrapper.prototype.destroy = function () {
this.parent = null;
};
VueFrameworkComponentWrapper = __decorate([
Object(external_agGrid_["Bean"])('frameworkComponentWrapper')
], VueFrameworkComponentWrapper);
return VueFrameworkComponentWrapper;
}(external_agGrid_["BaseComponentWrapper"]));
var VueComponent = /** @class */ (function () {
function VueComponent() {
}
VueComponent.prototype.getGui = function () {
return this.component.$el;
};
VueComponent.prototype.destroy = function () {
this.component.$destroy();
};
VueComponent.prototype.getFrameworkComponentInstance = function () {
return this.component;
};
VueComponent.prototype.init = function (params) {
this.component = this.createComponent(params);
};
return VueComponent;
}());
// CONCATENATED MODULE: ./src/Utils.ts
var getAgGridProperties = function () {
var props = {
gridOptions: {
default: function () {
return {};
},
},
rowDataModel: undefined,
};
var watch = {
rowDataModel: function (currentValue, previousValue) {
this.processChanges('rowData', currentValue, previousValue);
},
};
external_agGrid_["ComponentUtil"].ALL_PROPERTIES.forEach(function (propertyName) {
props[propertyName] = {};
watch[propertyName] = function (currentValue, previousValue) {
this.processChanges(propertyName, currentValue, previousValue);
};
});
var model = {
prop: 'rowDataModel',
event: 'data-model-changed',
};
return [props, watch, model];
};
// CONCATENATED MODULE: ./src/AgGridColumn.ts
var AgGridColumn_AgGridColumn = /** @class */ (function () {
function AgGridColumn() {
}
AgGridColumn.hasChildColumns = function (slots) {
return slots && slots.default && slots.default.length > 0;
};
AgGridColumn.mapChildColumnDefs = function (slots) {
return slots.default.map(function (column) {
return AgGridColumn.toColDef(column);
});
};
AgGridColumn.toColDef = function (column) {
var colDef = AgGridColumn.createColDefFromGridColumn(column);
if (column.children && column.children.length > 0) {
colDef.children = AgGridColumn.getChildColDefs(column.children);
}
return colDef;
};
AgGridColumn.getChildColDefs = function (columnChildren) {
return columnChildren.map(function (column) {
return AgGridColumn.createColDefFromGridColumn(column);
});
};
AgGridColumn.createColDefFromGridColumn = function (column) {
var colDef = {};
AgGridColumn.assign(colDef, column.data.attrs);
delete colDef.children;
// booleans passed down just as is are here as property=""
// convert boolean props to a boolean here
external_agGrid_["ColDefUtil"].BOOLEAN_PROPERTIES.forEach(function (property) {
var colDefAsAny = colDef;
if (colDefAsAny[property] === '') {
colDefAsAny[property] = true;
}
});
return colDef;
};
AgGridColumn.assign = function (colDef, from) {
// effectively Object.assign - here for IE compatibility
return [from].reduce(function (r, o) {
Object.keys(o).forEach(function (k) {
r[k] = o[k];
});
return r;
}, colDef);
};
return AgGridColumn;
}());
// CONCATENATED MODULE: ./src/AgGridVue.ts
var AgGridVue_a = getAgGridProperties(), AgGridVue_props = AgGridVue_a[0], AgGridVue_watch = AgGridVue_a[1], AgGridVue_model = AgGridVue_a[2];
var AgGridVue_AgGridVue = /** @class */ (function (_super) {
__extends(AgGridVue, _super);
function AgGridVue() {
var _this = _super !== null && _super.apply(this, arguments) || this;
_this.gridCreated = false;
_this.isDestroyed = false;
_this.gridReadyFired = false;
_this.emitRowModel = null;
return _this;
}
AgGridVue_1 = AgGridVue;
AgGridVue.kebabProperty = function (property) {
return property.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase();
};
// noinspection JSUnusedGlobalSymbols, JSMethodCanBeStatic
AgGridVue.prototype.render = function (h) {
return h('div');
};
AgGridVue.prototype.globalEventListener = function (eventType, event) {
if (this.isDestroyed) {
return;
}
if (eventType === 'gridReady') {
this.gridReadyFired = true;
}
this.updateModelIfUsed(eventType);
// only emit if someone is listening
// we allow both kebab and camelCase event listeners, so check for both
var kebabName = AgGridVue_1.kebabProperty(eventType);
if (this.$listeners[kebabName]) {
this.$emit(kebabName, event);
}
else if (this.$listeners[eventType]) {
this.$emit(eventType, event);
}
};
AgGridVue.prototype.processChanges = function (propertyName, currentValue, previousValue) {
if (this.gridCreated) {
if (this.skipChange(propertyName, currentValue, previousValue)) {
return;
}
var changes = {};
changes[propertyName] = {
currentValue: currentValue,
previousValue: previousValue,
};
external_agGrid_["ComponentUtil"].processOnChange(changes, this.gridOptions, this.gridOptions.api, this.gridOptions.columnApi);
}
};
// noinspection JSUnusedGlobalSymbols
AgGridVue.prototype.mounted = function () {
var _this = this;
// we debounce the model update to prevent a flood of updates in the event there are many individual
// cell/row updates
this.emitRowModel = this.debounce(function () {
_this.$emit('data-model-changed', Object.freeze(_this.getRowData()));
}, 20);
var frameworkComponentWrapper = new VueFrameworkComponentWrapper_VueFrameworkComponentWrapper(this);
var gridOptions = external_agGrid_["ComponentUtil"].copyAttributesToGridOptions(this.gridOptions, this);
this.checkForBindingConflicts();
gridOptions.rowData = this.getRowDataBasedOnBindings();
if (AgGridColumn_AgGridColumn.hasChildColumns(this.$slots)) {
gridOptions.columnDefs = AgGridColumn_AgGridColumn.mapChildColumnDefs(this.$slots);
}
var gridParams = {
globalEventListener: this.globalEventListener.bind(this),
seedBeanInstances: {
frameworkComponentWrapper: frameworkComponentWrapper,
},
};
new external_agGrid_["Grid"](this.$el, gridOptions, gridParams);
this.gridCreated = true;
};
// noinspection JSUnusedGlobalSymbols
AgGridVue.prototype.destroyed = function () {
if (this.gridCreated) {
if (this.gridOptions.api) {
this.gridOptions.api.destroy();
}
this.isDestroyed = true;
}
};
AgGridVue.prototype.checkForBindingConflicts = function () {
var thisAsAny = this;
if ((thisAsAny.rowData || this.gridOptions.rowData) &&
thisAsAny.rowDataModel) {
console.warn('ag-grid: Using both rowData and rowDataModel. rowData will be ignored.');
}
};
AgGridVue.prototype.getRowData = function () {
var rowData = [];
this.gridOptions.api.forEachNode(function (rowNode) {
rowData.push(rowNode.data);
});
return rowData;
};
AgGridVue.prototype.updateModelIfUsed = function (eventType) {
if (this.gridReadyFired &&
this.$listeners['data-model-changed'] &&
AgGridVue_1.ROW_DATA_EVENTS.indexOf(eventType) !== -1) {
if (this.emitRowModel) {
this.emitRowModel();
}
}
};
AgGridVue.prototype.getRowDataBasedOnBindings = function () {
var thisAsAny = this;
var rowDataModel = thisAsAny.rowDataModel;
return rowDataModel ? rowDataModel :
thisAsAny.rowData ? thisAsAny.rowData : thisAsAny.gridOptions.rowData;
};
/*
* Prevents an infinite loop when using v-model for the rowData
*/
AgGridVue.prototype.skipChange = function (propertyName, currentValue, previousValue) {
if (this.gridReadyFired &&
propertyName === 'rowData' &&
this.$listeners['data-model-changed']) {
if (currentValue === previousValue) {
return true;
}
if (currentValue && previousValue) {
var currentRowData = currentValue;
var previousRowData = previousValue;
if (currentRowData.length === previousRowData.length) {
for (var i = 0; i < currentRowData.length; i++) {
if (currentRowData[i] !== previousRowData[i]) {
return false;
}
}
return true;
}
}
}
return false;
};
AgGridVue.prototype.debounce = function (func, delay) {
var timeout;
return function () {
var later = function () {
func();
};
window.clearTimeout(timeout);
timeout = window.setTimeout(later, delay);
};
};
var AgGridVue_1;
AgGridVue.ROW_DATA_EVENTS = ['rowDataChanged', 'rowDataUpdated', 'cellValueChanged', 'rowValueChanged'];
__decorate([
Prop(Boolean)
], AgGridVue.prototype, "autoParamsRefresh", void 0);
__decorate([
Prop({ default: function () { return []; } })
], AgGridVue.prototype, "componentDependencies", void 0);
AgGridVue = AgGridVue_1 = __decorate([
Object(external_agGrid_["Bean"])('agGridVue'),
vue_class_component_common_default()({
props: AgGridVue_props,
watch: AgGridVue_watch,
model: AgGridVue_model,
})
], AgGridVue);
return AgGridVue;
}(external_commonjs_vue_commonjs2_vue_root_Vue_default.a));
// CONCATENATED MODULE: ./node_modules/@vue/cli-service/lib/commands/build/entry-lib-no-default.js
/* concated harmony reexport AgGridVue */__webpack_require__.d(__webpack_exports__, "AgGridVue", function() { return AgGridVue_AgGridVue; });
/***/ })
/******/ });
});
//# sourceMappingURL=ag-grid-vue.umd.js.map
|
import os
from glob import glob
import argparse
import cv2
import xml.etree.ElementTree as ET
from coco_format_utils import Coco_Annotation_Set, Coco_Annotation_Object
def read_label_map(label_map_path):
item_id = None
item_name = None
categories = []
category = {}
category_name_to_category_id_relation_dict = {}
with open(label_map_path, "r") as file:
for line in file:
line=line.replace(" ", "")
if line == "item{":
pass
elif line == "}":
pass
elif "id:" in line:
item_id = int(line.split(":", 1)[1].strip())
elif "name" in line:
item_name = line.split(":", 1)[1].replace("'", "").strip()
if item_id is not None and item_name is not None:
category_name_to_category_id_relation_dict[item_name] = item_id
category['id'] = item_id
category['name'] = item_name
category['supercategory'] = ""
categories.append(category)
category = {}
item_id = None
item_name = None
return categories, category_name_to_category_id_relation_dict
def insert_images_into_coco_ann_obj(images_format, coco_annotations):
img_name_relation_to_img_id = {}
for img_idx, image_path in enumerate(sorted(glob(images_format))):
filename = os.path.basename(image_path)
img = cv2.imread(image_path)
height, width, _ = img.shape
coco_annotations.insert_image(img_idx+1, width, height, file_name = filename)
img_name_relation_to_img_id[filename] = img_idx+1
return coco_annotations, img_name_relation_to_img_id
def xml_to_coco_ann_obj(path, coco_annotations, img_name_relation_to_img_id, category_name_to_category_id_relation_dict):
"""Iterates through all .xml files (generated by labelImg) in a given directory and combines them in a single Pandas datagrame.
Parameters:
----------
path : {str}
The path containing the .xml files
Returns
-------
Pandas DataFrame
The produced dataframe
"""
obj_counter = 0
for xml_file in sorted(glob(path + '/*.xml')):
tree = ET.parse(xml_file)
root = tree.getroot()
for member in root.findall('object'):
img_filename = root.find('filename').text
width = int(root.find('size')[0].text)
height = int(root.find('size')[1].text)
class_name = member[0].text
xmin = int(member[4][0].text)
ymin = int(member[4][1].text)
xmax = int(member[4][2].text)
ymax = int(member[4][3].text)
bbox_xmin = xmin
bbox_ymin = ymin
bbox_width = xmax-xmin
bbox_height = ymax-ymin
class_id = category_name_to_category_id_relation_dict[class_name]
image_id = img_name_relation_to_img_id[img_filename]
coco_object = Coco_Annotation_Object(bbox=[bbox_xmin,bbox_ymin,bbox_width,bbox_height], category_id=class_id, id=obj_counter, image_id=image_id, area=bbox_width*bbox_height, score=1)
coco_annotations.insert_coco_annotation_object(coco_object)
obj_counter += 1
return coco_annotations
def main(args):
if args.xml_input_folder is None or not os.path.isdir(args.xml_input_folder):
print("ERROR: No input folder to get .xml from.")
quit()
if args.xml_input_folder is None:
args.xml_input_folder = args.xml_input_folder
print(f"WARNING: No output path provided. {args.output_path} will be used.")
if args.output_path is None:
args.output_path = os.path.join(args.xml_input_folder, "annotations.json")
print(f"WARNING: No output path provided. {args.output_path} will be used.")
categories, category_name_to_category_id_relation_dict = read_label_map(args.labelmap_path)
coco_annotations = Coco_Annotation_Set(categories=categories)
coco_annotations, img_name_relation_to_img_id = insert_images_into_coco_ann_obj(args.images_input_format, coco_annotations)
coco_annotations = xml_to_coco_ann_obj(args.xml_input_folder, coco_annotations, img_name_relation_to_img_id, category_name_to_category_id_relation_dict)
coco_annotations.to_json(args.output_path, only_annotations = False, only_essential_data = False)
if __name__ == '__main__':
# Initiate argument parser
parser = argparse.ArgumentParser(
description="TensorFlow XML to coco json converter")
parser.add_argument("-xi",
"--xml_input_folder",
help="Path to the folder where the input .xml files are stored",
default=None,
type=str)
parser.add_argument("-ii",
"--images_input_format",
help="Path to the format to find the dataset images.",
default=None,
type=str)
parser.add_argument("-o",
"--output_path",
help="Name of output .json file (including path)", default=None, type=str)
parser.add_argument('-l',
'--labelmap_path',
help='The path to save the label map. If not provided, will be saved in image_dir.',
default=None,
type=str)
args = parser.parse_args()
main(args)
|
var searchData=
[
['ead',['Ead',['../class_ead.html',1,'Ead'],['../class_ead.html#a4862282805c2ac3255a34a99a31564d5',1,'Ead::Ead()']]],
['eventdelay',['EventDelay',['../class_event_delay.html',1,'EventDelay'],['../class_event_delay.html#acd7b63341732ac4c23bce04d81316017',1,'EventDelay::EventDelay()']]]
];
|
require('../../lib/feature-flags')
const { getDOM, getJSON } = require('../helpers/supertest')
const enterpriseServerReleases = require('../../lib/enterprise-server-releases')
const japaneseCharacters = require('japanese-characters')
describe('featuredLinks', () => {
jest.setTimeout(3 * 60 * 1000)
describe('rendering', () => {
test('non-TOC pages do not have intro links', async () => {
const $ = await getDOM('/en/github/getting-started-with-github/set-up-git')
expect($('.featured-links')).toHaveLength(0)
})
test('landing page intro links have expected properties', async () => {
const $ = await getDOM('/en')
const $featuredLinks = $('[data-testid=article-list] a')
expect($featuredLinks).toHaveLength(9)
expect($featuredLinks.eq(0).attr('href')).toBe('/en/github/getting-started-with-github/set-up-git')
expect($featuredLinks.eq(0).children('h4').text().startsWith('Set up Git')).toBe(true)
expect($featuredLinks.eq(0).children('p').text().startsWith('At the heart of GitHub')).toBe(true)
expect($featuredLinks.eq(8).attr('href')).toBe('/en/github/working-with-github-pages')
expect($featuredLinks.eq(8).children('h4').text().startsWith('GitHub Pages')).toBe(true)
expect($featuredLinks.eq(8).children('p').text().startsWith('You can create a website')).toBe(true)
})
test('localized intro links link to localized pages', async () => {
const $ = await getDOM('/ja')
const $featuredLinks = $('.featured-links a')
expect($featuredLinks).toHaveLength(9)
expect($featuredLinks.eq(0).attr('href').startsWith('/ja')).toBe(true)
expect(japaneseCharacters.presentIn($featuredLinks.eq(1).children('h4').text())).toBe(true)
expect(japaneseCharacters.presentIn($featuredLinks.eq(1).children('p').text())).toBe(true)
})
test('Enterprise user intro links have expected values', async () => {
const $ = await getDOM(`/en/enterprise/${enterpriseServerReleases.latest}/user/insights`)
const $featuredLinks = $('[data-testid=article-list] a')
expect($featuredLinks).toHaveLength(6)
expect($featuredLinks.eq(0).attr('href')).toBe(`/en/enterprise-server@${enterpriseServerReleases.latest}/insights/installing-and-configuring-github-insights/about-github-insights`)
expect($featuredLinks.eq(0).children('h4').text().startsWith('About GitHub Insights')).toBe(true)
expect($featuredLinks.eq(0).children('p').text().startsWith('GitHub Insights provides metrics')).toBe(true)
})
// If any of these tests fail, check to see if the content has changed and update text if needed.
test('product articles links respect versioning', async () => {
const enterpriseVersionedLandingPage = `/en/enterprise-server@${enterpriseServerReleases.latest}/packages`
const $ = await getDOM(enterpriseVersionedLandingPage)
const $productArticlesLinks = $('[data-testid=product-articles-list] a')
let msg = `Product article links are not rendered as expected on ${enterpriseVersionedLandingPage}`
expect($productArticlesLinks.length, msg).toBeGreaterThan(2)
// Confirm that the following Enterprise link IS included on this Enterprise page.
msg = `Enterprise article link is not rendered as expected on ${enterpriseVersionedLandingPage}`
expect($productArticlesLinks.text().includes('Working with a GitHub Packages registry'), msg).toBe(true)
// Confirm that the following Dotcom-only links are NOT included on this Enterprise page.
msg = `Dotcom-only article link is rendered, but should not be, on ${enterpriseVersionedLandingPage}`
expect($productArticlesLinks.text().includes('Enabling improved container support with the Container registry')).toBe(false)
expect($productArticlesLinks.text().includes('Migrating to the Container registry from the Docker registry'), msg).toBe(false)
})
})
describe('context.page object', () => {
test('returns modified array of links', async () => {
const gettingStartedLinks = await getJSON('/en?json=featuredLinks.gettingStarted')
const expectedFirstLink = {
href: '/en/github/getting-started-with-github/set-up-git',
title: 'Set up Git'
}
expect(gettingStartedLinks[0].href).toEqual(expectedFirstLink.href)
expect(gettingStartedLinks[0].title).toEqual(expectedFirstLink.title)
expect(gettingStartedLinks[0].intro.startsWith('At the heart of GitHub')).toBe(true)
})
test('returns raw array of links on the page object', async () => {
const rawGettingStartedLinks = await getJSON('/en?json=page.featuredLinks.gettingStarted')
expect(rawGettingStartedLinks[0]).toEqual('/github/getting-started-with-github/set-up-git')
})
})
})
|
var searchData=
[
['cachedlog_22784',['CachedLog',['../classoperations__research_1_1_cached_log.html',1,'operations_research']]],
['callbackrangeconstraint_22785',['CallbackRangeConstraint',['../structoperations__research_1_1_callback_range_constraint.html',1,'operations_research']]],
['callbacksetup_22786',['CallbackSetup',['../structoperations__research_1_1_callback_setup.html',1,'operations_research']]],
['callmethod0_22787',['CallMethod0',['../classoperations__research_1_1_call_method0.html',1,'operations_research']]],
['callmethod1_22788',['CallMethod1',['../classoperations__research_1_1_call_method1.html',1,'operations_research']]],
['callmethod2_22789',['CallMethod2',['../classoperations__research_1_1_call_method2.html',1,'operations_research']]],
['callmethod3_22790',['CallMethod3',['../classoperations__research_1_1_call_method3.html',1,'operations_research']]],
['canonicalbooleanlinearproblem_22791',['CanonicalBooleanLinearProblem',['../classoperations__research_1_1sat_1_1_canonical_boolean_linear_problem.html',1,'operations_research::sat']]],
['castconstraint_22792',['CastConstraint',['../classoperations__research_1_1_cast_constraint.html',1,'operations_research']]],
['cbcinterface_22793',['CBCInterface',['../classoperations__research_1_1_c_b_c_interface.html',1,'operations_research']]],
['chain_22794',['Chain',['../classoperations__research_1_1_path_state_1_1_chain.html',1,'operations_research::PathState']]],
['chainrange_22795',['ChainRange',['../classoperations__research_1_1_path_state_1_1_chain_range.html',1,'operations_research::PathState']]],
['changevalue_22796',['ChangeValue',['../classoperations__research_1_1_change_value.html',1,'operations_research']]],
['cheapestadditionfilteredheuristic_22797',['CheapestAdditionFilteredHeuristic',['../classoperations__research_1_1_cheapest_addition_filtered_heuristic.html',1,'operations_research']]],
['cheapestinsertionfilteredheuristic_22798',['CheapestInsertionFilteredHeuristic',['../classoperations__research_1_1_cheapest_insertion_filtered_heuristic.html',1,'operations_research']]],
['checkopmessagebuilder_22799',['CheckOpMessageBuilder',['../classgoogle_1_1base_1_1_check_op_message_builder.html',1,'google::base']]],
['checkopstring_22800',['CheckOpString',['../structgoogle_1_1_check_op_string.html',1,'google']]],
['christofidesfilteredheuristic_22801',['ChristofidesFilteredHeuristic',['../classoperations__research_1_1_christofides_filtered_heuristic.html',1,'operations_research']]],
['christofidespathsolver_22802',['ChristofidesPathSolver',['../classoperations__research_1_1_christofides_path_solver.html',1,'operations_research']]],
['circuitconstraint_22803',['CircuitConstraint',['../classoperations__research_1_1sat_1_1_circuit_constraint.html',1,'operations_research::sat']]],
['circuitconstraintprotodefaulttypeinternal_22804',['CircuitConstraintProtoDefaultTypeInternal',['../classoperations__research_1_1sat_1_1_circuit_constraint_proto_default_type_internal.html',1,'operations_research::sat']]],
['circuitcoveringpropagator_22805',['CircuitCoveringPropagator',['../classoperations__research_1_1sat_1_1_circuit_covering_propagator.html',1,'operations_research::sat']]],
['circuitpropagator_22806',['CircuitPropagator',['../classoperations__research_1_1sat_1_1_circuit_propagator.html',1,'operations_research::sat']]],
['clauseinfo_22807',['ClauseInfo',['../structoperations__research_1_1sat_1_1_clause_info.html',1,'operations_research::sat']]],
['cleanup_22808',['Cleanup',['../classabsl_1_1_cleanup.html',1,'absl']]],
['closedinterval_22809',['ClosedInterval',['../structoperations__research_1_1_closed_interval.html',1,'operations_research']]],
['clpinterface_22810',['CLPInterface',['../classoperations__research_1_1_c_l_p_interface.html',1,'operations_research']]],
['colchoiceandstatus_22811',['ColChoiceAndStatus',['../structoperations__research_1_1glop_1_1_doubleton_equality_row_preprocessor_1_1_restore_info_1_1_col_choice_and_status.html',1,'operations_research::glop::DoubletonEqualityRowPreprocessor::RestoreInfo']]],
['columndeletionhelper_22812',['ColumnDeletionHelper',['../classoperations__research_1_1glop_1_1_column_deletion_helper.html',1,'operations_research::glop']]],
['columnpriorityqueue_22813',['ColumnPriorityQueue',['../classoperations__research_1_1glop_1_1_column_priority_queue.html',1,'operations_research::glop']]],
['columnview_22814',['ColumnView',['../classoperations__research_1_1glop_1_1_column_view.html',1,'operations_research::glop']]],
['combinationofrows_22815',['CombinationOfRows',['../structoperations__research_1_1sat_1_1_zero_half_cut_helper_1_1_combination_of_rows.html',1,'operations_research::sat::ZeroHalfCutHelper']]],
['combineddisjunctive_22816',['CombinedDisjunctive',['../classoperations__research_1_1sat_1_1_combined_disjunctive.html',1,'operations_research::sat']]],
['compactsparsematrix_22817',['CompactSparseMatrix',['../classoperations__research_1_1glop_1_1_compact_sparse_matrix.html',1,'operations_research::glop']]],
['compactsparsematrixview_22818',['CompactSparseMatrixView',['../classoperations__research_1_1glop_1_1_compact_sparse_matrix_view.html',1,'operations_research::glop']]],
['comparatorcheapestadditionfilteredheuristic_22819',['ComparatorCheapestAdditionFilteredHeuristic',['../classoperations__research_1_1_comparator_cheapest_addition_filtered_heuristic.html',1,'operations_research']]],
['compileassert_22820',['CompileAssert',['../structgoogle_1_1logging__internal_1_1_compile_assert.html',1,'google::logging_internal']]],
['completebipartitegraph_22821',['CompleteBipartiteGraph',['../classutil_1_1_complete_bipartite_graph.html',1,'util']]],
['completegraph_22822',['CompleteGraph',['../classutil_1_1_complete_graph.html',1,'util']]],
['connectedcomponentsfinder_22823',['ConnectedComponentsFinder',['../class_connected_components_finder.html',1,'']]],
['connectedcomponentstypehelper_22824',['ConnectedComponentsTypeHelper',['../structinternal_1_1_connected_components_type_helper.html',1,'internal']]],
['connectedcomponentstypehelper_3c_20t_2c_20std_3a_3aless_3c_20t_20_3e_20_3e_22825',['ConnectedComponentsTypeHelper< T, std::less< T > >',['../structinternal_1_1_connected_components_type_helper.html',1,'internal']]],
['consecutiveconstraintsrelaxationneighborhoodgenerator_22826',['ConsecutiveConstraintsRelaxationNeighborhoodGenerator',['../classoperations__research_1_1sat_1_1_consecutive_constraints_relaxation_neighborhood_generator.html',1,'operations_research::sat']]],
['constraint_22827',['Constraint',['../classoperations__research_1_1_constraint.html',1,'Constraint'],['../classoperations__research_1_1sat_1_1_constraint.html',1,'Constraint'],['../structoperations__research_1_1fz_1_1_constraint.html',1,'Constraint']]],
['constraintbasedneighborhood_22828',['ConstraintBasedNeighborhood',['../classoperations__research_1_1bop_1_1_constraint_based_neighborhood.html',1,'operations_research::bop']]],
['constraintgraphneighborhoodgenerator_22829',['ConstraintGraphNeighborhoodGenerator',['../classoperations__research_1_1sat_1_1_constraint_graph_neighborhood_generator.html',1,'operations_research::sat']]],
['constraintinfo_22830',['ConstraintInfo',['../structoperations__research_1_1sat_1_1_linear_constraint_manager_1_1_constraint_info.html',1,'operations_research::sat::LinearConstraintManager']]],
['constraintprotodefaulttypeinternal_22831',['ConstraintProtoDefaultTypeInternal',['../classoperations__research_1_1sat_1_1_constraint_proto_default_type_internal.html',1,'operations_research::sat']]],
['constraintrunsdefaulttypeinternal_22832',['ConstraintRunsDefaultTypeInternal',['../classoperations__research_1_1_constraint_runs_default_type_internal.html',1,'operations_research']]],
['constraintsolverparametersdefaulttypeinternal_22833',['ConstraintSolverParametersDefaultTypeInternal',['../classoperations__research_1_1_constraint_solver_parameters_default_type_internal.html',1,'operations_research']]],
['constraintsolverstatisticsdefaulttypeinternal_22834',['ConstraintSolverStatisticsDefaultTypeInternal',['../classoperations__research_1_1_constraint_solver_statistics_default_type_internal.html',1,'operations_research']]],
['constraintterm_22835',['ConstraintTerm',['../structoperations__research_1_1bop_1_1_one_flip_constraint_repairer_1_1_constraint_term.html',1,'operations_research::bop::OneFlipConstraintRepairer']]],
['corebasedoptimizer_22836',['CoreBasedOptimizer',['../classoperations__research_1_1sat_1_1_core_based_optimizer.html',1,'operations_research::sat']]],
['costclass_22837',['CostClass',['../structoperations__research_1_1_routing_model_1_1_cost_class.html',1,'operations_research::RoutingModel']]],
['costvaluecyclehandler_22838',['CostValueCycleHandler',['../classoperations__research_1_1_cost_value_cycle_handler.html',1,'operations_research']]],
['covercuthelper_22839',['CoverCutHelper',['../classoperations__research_1_1sat_1_1_cover_cut_helper.html',1,'operations_research::sat']]],
['cpfeasibilityfilter_22840',['CPFeasibilityFilter',['../classoperations__research_1_1_c_p_feasibility_filter.html',1,'operations_research']]],
['cpmodelbuilder_22841',['CpModelBuilder',['../classoperations__research_1_1sat_1_1_cp_model_builder.html',1,'operations_research::sat']]],
['cpmodelmapping_22842',['CpModelMapping',['../classoperations__research_1_1sat_1_1_cp_model_mapping.html',1,'operations_research::sat']]],
['cpmodelpresolver_22843',['CpModelPresolver',['../classoperations__research_1_1sat_1_1_cp_model_presolver.html',1,'operations_research::sat']]],
['cpmodelprotodefaulttypeinternal_22844',['CpModelProtoDefaultTypeInternal',['../classoperations__research_1_1sat_1_1_cp_model_proto_default_type_internal.html',1,'operations_research::sat']]],
['cpobjectiveprotodefaulttypeinternal_22845',['CpObjectiveProtoDefaultTypeInternal',['../classoperations__research_1_1sat_1_1_cp_objective_proto_default_type_internal.html',1,'operations_research::sat']]],
['cpsolverresponsedefaulttypeinternal_22846',['CpSolverResponseDefaultTypeInternal',['../classoperations__research_1_1sat_1_1_cp_solver_response_default_type_internal.html',1,'operations_research::sat']]],
['crashreason_22847',['CrashReason',['../structgoogle_1_1logging__internal_1_1_crash_reason.html',1,'google::logging_internal']]],
['cross_22848',['Cross',['../classoperations__research_1_1_cross.html',1,'operations_research']]],
['cumulativeconstraint_22849',['CumulativeConstraint',['../classoperations__research_1_1sat_1_1_cumulative_constraint.html',1,'operations_research::sat']]],
['cumulativeconstraintprotodefaulttypeinternal_22850',['CumulativeConstraintProtoDefaultTypeInternal',['../classoperations__research_1_1sat_1_1_cumulative_constraint_proto_default_type_internal.html',1,'operations_research::sat']]],
['cumulativeenergyconstraint_22851',['CumulativeEnergyConstraint',['../classoperations__research_1_1sat_1_1_cumulative_energy_constraint.html',1,'operations_research::sat']]],
['cumulboundspropagator_22852',['CumulBoundsPropagator',['../classoperations__research_1_1_cumul_bounds_propagator.html',1,'operations_research']]],
['cutgenerator_22853',['CutGenerator',['../structoperations__research_1_1sat_1_1_cut_generator.html',1,'operations_research::sat']]],
['cyclehandlerforannotatedarcs_22854',['CycleHandlerForAnnotatedArcs',['../classoperations__research_1_1_forward_static_graph_1_1_cycle_handler_for_annotated_arcs.html',1,'ForwardStaticGraph< NodeIndexType, ArcIndexType >::CycleHandlerForAnnotatedArcs'],['../classoperations__research_1_1_ebert_graph_base_1_1_cycle_handler_for_annotated_arcs.html',1,'EbertGraphBase< NodeIndexType, ArcIndexType, DerivedGraph >::CycleHandlerForAnnotatedArcs']]],
['cycletimer_22855',['CycleTimer',['../class_cycle_timer.html',1,'']]],
['cycletimerbase_22856',['CycleTimerBase',['../class_cycle_timer_base.html',1,'']]]
];
|
if (condition1) statement1 else if (condition2) statement2 else statement3
|
# -*- coding: utf-8 -*-
###########################################################################
# Copyright (c), The AiiDA team. All rights reserved. #
# This file is part of the AiiDA code. #
# #
# The code is hosted on GitHub at https://github.com/aiidateam/aiida-core #
# For further information on the license, see the LICENSE.txt file #
# For further information please visit http://www.aiida.net #
###########################################################################
"""A utility module with a factory of standard QueryBuilder instances for Calculation nodes."""
from __future__ import division
from __future__ import print_function
from __future__ import absolute_import
from aiida.common.lang import classproperty
from aiida.cmdline.utils.query.mapping import CalculationProjectionMapper
class CalculationQueryBuilder(object):
"""Utility class to construct a QueryBuilder instance for Calculation nodes and project the query set."""
# This tuple serves to mark compound projections that cannot explicitly be projected in the QueryBuilder, but will
# have to be manually projected from composing its individual projection constituents
_compound_projections = ('state',)
_default_projections = ('pk', 'ctime', 'process_label', 'state', 'process_status')
_valid_projections = (
'pk', 'uuid', 'ctime', 'mtime', 'state', 'process_state', 'process_status', 'exit_status', 'sealed',
'process_label', 'label', 'description', 'node_type', 'paused', 'process_type', 'job_state', 'scheduler_state'
)
def __init__(self, mapper=None):
if mapper is None:
self._mapper = CalculationProjectionMapper(self._valid_projections)
else:
self._mapper = mapper
@property
def mapper(self):
return self._mapper
@classproperty
def default_projections(self):
return self._default_projections
@classproperty
def valid_projections(self):
return self._valid_projections
def get_filters(
self,
all_entries=False,
process_state=None,
process_label=None,
exit_status=None,
failed=False,
node_types=None
):
"""
Return a set of QueryBuilder filters based on typical command line options.
:param node_types: a tuple of node classes to filter for (must be sub classes of Calculation)
:param all_entries: boolean to negate filtering for process state
:param process_state: filter for this process state attribute
:param process_label: filter for this process label attribute
:param exit_status: filter for this exit status
:param failed: boolean to filter only failed processes
:return: dictionary of filters suitable for a QueryBuilder.append() call
"""
# pylint: disable=too-many-arguments
from aiida.engine import ProcessState
exit_status_attribute = self.mapper.get_attribute('exit_status')
process_label_attribute = self.mapper.get_attribute('process_label')
process_state_attribute = self.mapper.get_attribute('process_state')
filters = {}
if node_types is not None:
filters['or'] = []
for node_class in node_types:
filters['or'].append({'type': node_class.class_node_type})
if process_state and not all_entries:
filters[process_state_attribute] = {'in': process_state}
if process_label is not None:
if '%' in process_label or '_' in process_label:
filters[process_label_attribute] = {'like': process_label}
else:
filters[process_label_attribute] = process_label
if failed:
filters[process_state_attribute] = {'==': ProcessState.FINISHED.value}
filters[exit_status_attribute] = {'>': 0}
if exit_status is not None:
filters[process_state_attribute] = {'==': ProcessState.FINISHED.value}
filters[exit_status_attribute] = {'==': exit_status}
return filters
def get_query_set(self, relationships=None, filters=None, order_by=None, past_days=None, limit=None):
"""
Return the query set of calculations for the given filters and query parameters
:param relationships: a mapping of relationships to join on, e.g. {'with_node': Group} to join on a Group. The
keys in this dictionary should be the keyword used in the `append` method of the `QueryBuilder` to join the
entity on that is defined as the value.
:param filters: rules to filter query results with
:param order_by: order the query set by this criterion
:param past_days: only include entries from the last past days
:param limit: limit the query set to this number of entries
:return: the query set, a list of dictionaries
"""
import datetime
from aiida import orm
from aiida.common import timezone
# Define the list of projections for the QueryBuilder, which are all valid minus the compound projections
projected_attributes = [
self.mapper.get_attribute(projection)
for projection in self._valid_projections
if projection not in self._compound_projections
]
if filters is None:
filters = {}
if past_days is not None:
filters['ctime'] = {'>': timezone.now() - datetime.timedelta(days=past_days)}
builder = orm.QueryBuilder()
builder.append(cls=orm.ProcessNode, filters=filters, project=projected_attributes, tag='process')
if relationships is not None:
for tag, entity in relationships.items():
builder.append(cls=type(entity), filters={'id': entity.id}, **{tag: 'process'})
if order_by is not None:
builder.order_by({'process': order_by})
else:
builder.order_by({'process': {'ctime': 'asc'}})
if limit is not None:
builder.limit(limit)
return builder.iterdict()
def get_projected(self, query_set, projections):
"""
Project the query set for the given set of projections
"""
header = [self.mapper.get_label(projection) for projection in projections]
result = [header]
for query_result in query_set:
result_row = [self.mapper.format(projection, query_result['process']) for projection in projections]
result.append(result_row)
return result
|
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
from .. import _utilities
import typing
# Export this package's modules as members:
from ._enums import *
from .acl import *
from .cluster import *
from .get_acl import *
from .get_cluster import *
from .get_parameter_group import *
from .get_subnet_group import *
from .get_user import *
from .parameter_group import *
from .subnet_group import *
from .user import *
from ._inputs import *
from . import outputs
|
'use strict';
module.exports = function(grunt) {
var CI = grunt.option('ci');
grunt.initConfig({
env: {
coverage: {
APP_DIR_FOR_CODE_COVERAGE: '../test/coverage/instrument/app/'
}
},
instrument: {
files: 'lib/*.js',
options: {
lazy: true,
basePath: 'test/coverage/instrument'
}
},
mochaTest: {
test: {
options: {
reporter: 'spec',
timeout: process.env.TEST_TIMEOUT || 3000
},
src: ['test/test.js']
}
},
storeCoverage: {
options: {
dir: 'test/coverage/reports'
}
},
makeReport: {
src: 'test/coverage/reports/**/*.json',
options: {
type: 'lcov',
dir: 'test/coverage/reports',
print: 'detail'
}
},
jshint: {
options: {
jshintrc: '.jshintrc',
reporter: CI && 'checkstyle',
reporterOutput: CI && 'jshint.xml'
},
all: {
src: [
'Gruntfile.js',
'lib/*.js',
]
},
quick: {
// You must run the prepare-quick-lint target before jshint:quick,
// files are filled in dynamically.
src: []
}
},
gjslint: {
options: {
flags: [
'--disable 0110',
'--nojsdoc',
'-e test/karma-include'
],
reporter: {
name: CI ? 'gjslint_xml' : 'console',
dest: CI ? 'gjslint.xml' : undefined
}
},
all: {
src: ['<%= jshint.all.src %>']
},
quick: {
src: ['<%= jshint.quick.src %>']
}
},
lint_pattern: {
options: {
rules: [
{ pattern: /(describe|it)\.only/, message: 'Must not use .only in tests' }
]
},
all: {
src: ['<%= jshint.all.src %>']
},
quick: {
src: ['<%= jshint.quick.src %>']
}
},
browserify: {
main: {
src: 'lib/rbtree_by_index.js',
dest: 'dist/rbtree_by_index.js'
},
options: {
browserifyOptions: {
standalone: 'RBTreeByIndex'
}
}
},
uglify: {
main: {
src: 'dist/rbtree_by_index.js',
dest: 'dist/rbtree_by_index.min.js'
}
}
});
grunt.loadNpmTasks('grunt-mocha-test');
grunt.loadNpmTasks('grunt-browserify');
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.loadNpmTasks('grunt-gjslint');
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-lint-pattern');
grunt.loadNpmTasks('grunt-env');
grunt.loadNpmTasks('grunt-istanbul');
grunt.registerTask('linters', 'Check code for lint', ['jshint:all', 'gjslint:all', 'lint_pattern:all']);
grunt.registerTask('build', ['browserify', 'uglify']);
grunt.registerTask('test', ['env:coverage', 'instrument', 'mochaTest', 'storeCoverage', 'makeReport']);
grunt.registerTask('default', ['linters', 'test', 'build']);
};
|
import SortAnimation, {defaultOptions} from './SortAnimation';
export default SortAnimation;
export {defaultOptions};
|
var fs = require('fs');
var request = require('request');
var iconv = require('iconv-lite');
fs.createReadStream('../zdroje/volby/p/2018/perk.xml')
.pipe(iconv.decodeStream('windows1250'))
.pipe(iconv.encodeStream('utf8'))
.pipe(fs.createWriteStream('../zdroje/volby/p/2018/perk-utf8.xml'));
request.get('https://volby.cz/pls/prez2018/vysledky')
.pipe(iconv.decodeStream('iso-8859-2'))
.pipe(iconv.encodeStream('utf8'))
.pipe(fs.createWriteStream('../zdroje/volby/p/2018/vysledky.xml'));
request.get('https://volby.cz/pls/prez2018/vysledky_zahranici')
.pipe(iconv.decodeStream('iso-8859-2'))
.pipe(iconv.encodeStream('utf8'))
.pipe(fs.createWriteStream('../zdroje/volby/p/2018/vysledky-zahranici.xml'));
function readXML (nuts) {
request.get('https://volby.cz/pls/prez2018/vysledky_kraj?kolo=1&nuts=' + nuts)
.pipe(iconv.decodeStream('iso-8859-2'))
.pipe(iconv.encodeStream('utf8'))
.pipe(fs.createWriteStream('../zdroje/volby/p/2018/data/1/' + nuts + ".xml"));
request.get('https://volby.cz/pls/prez2018/vysledky_kraj?kolo=2&nuts=' + nuts)
.pipe(iconv.decodeStream('iso-8859-2'))
.pipe(iconv.encodeStream('utf8'))
.pipe(fs.createWriteStream('../zdroje/volby/p/2018/data/2/' + nuts + ".xml"));
}
var hierarchyFile = new Promise (function (resolve, reject) {
fs.readFile('../data/obecne/obce-struktura.json', function(err, content) {
resolve(JSON.parse(content));
});
});
Promise.all([hierarchyFile]).then(function (values) {
var cz = values[0].hierarchy.list;
cz.forEach(reg => {
reg.list.forEach(kraj => {
var nuts = kraj.nuts;
if (nuts) readXML(nuts);
})
})
// readXML("CZ0201");
});
|
/* global process */
import React from "react";
import ReactDOM from "react-dom";
import bindMethods from "yaab";
import io from "socket.io-client";
import Header from "./components/Header";
import Footer from "./components/Footer";
import PullRequestList from "./components/PullRequestList";
const translate = data =>
data
.map(pr => {
const item = {};
item.project = pr.toRef.repository.project.key;
item.repo = pr.toRef.repository.slug;
item.updated = pr.updatedDate;
item.author = {
name: pr.author.user.displayName,
username: pr.author.user.name,
photo: pr.author.user.links.self[0].href + "/avatar.png",
};
item.title = pr.title;
item.reviewers = pr.reviewers
.map(r => ({
name: r.user.displayName,
username: r.user.name,
photo: r.user.links.self[0].href + "/avatar.png",
approval: r.status,
}))
.sort((a, b) => a.username.localeCompare(b.username));
item.branches = {
from: pr.fromRef.displayId,
to: pr.toRef.displayId,
};
item.href = pr.links.self[0].href;
item.builds = pr.builds;
return item;
})
.sort((a, b) => b.updated - a.updated);
class App extends React.Component {
constructor(props) {
super(props);
this.state = { PRs: [], lastUpdated: 0, loading: false };
bindMethods(this);
}
componentDidMount() {
if (this.socket) return;
this.socket = io();
this.socket.on("loading", () => this.setState({ loading: true }));
this.socket.on("prs", ({ PRs, lastUpdated }) =>
this.setState({ PRs, lastUpdated, loading: false }),
);
}
get lastUpdatedTime() {
const { lastUpdated } = this.state;
const d = new Date(lastUpdated);
const hours = `${d.getHours()}`.padStart(2, "0");
const minutes = `${d.getMinutes()}`.padStart(2, "0");
return `${hours}:${minutes}`;
}
render() {
const { PRs } = this.state;
const { lastUpdatedTime } = this;
return (
<React.Fragment>
<Header>
<h1>Pull requests ({PRs.length})</h1>
<span>Last updated: {lastUpdatedTime}</span>
</Header>
<PullRequestList PRs={translate(PRs)} />
<Footer>
<p>
<a href="https://github.com/ShaunBulbrook">
Please address feature requests to Shaun Bulbrook
</a>
</p>
</Footer>
</React.Fragment>
);
}
}
ReactDOM.render(<App />, document.getElementById("app"));
|
# -*- coding: utf-8 -*-
# Copyright (c) 2020, GreyCube Technologies and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
# import frappe
from frappe.model.document import Document
class ServiceNoteItemCT(Document):
pass
|
import React, { memo, useContext, useState } from 'react'
import { TouchableOpacity,Image, View, Text } from 'react-native'
import styles from './Styles/CardProduct'
import { NavigationContext } from "react-navigation"
import Format from '../Lib/NumberFormat'
const CardProduct = (props) => {
const [width, setWidth] = useState(0)
const [height, setHeight] = useState(0)
const {item, ...restProps} = props
const navigation = useContext(NavigationContext)
return (
<TouchableOpacity activeOpacity={0.9} style={styles.card} {...restProps}>
<Image source={{ uri: item?.thumbnail }} style={styles.thumb} resizeMode="cover" />
<View style={styles.content}>
<Text style={styles.price}>{'Rp' + new Format().formatMoney(item?.price ?? 0)}</Text>
<Text style={styles.title}>{item?.title}</Text>
</View>
</TouchableOpacity>
)
}
export default memo(CardProduct)
|
$(function() {
//Tooltip
$('[data-toggle="tooltip"]').tooltip({
container: 'body'
});
$('#type_price').change(function() {
if (this.value != 1) {
$('#precio').hide();
} else {
show();
}
});
show();
btnUpdate();
btnSave();
});
const show = () => {
return $('#precio').show();
}
const save = () => {
let form = $('#form_create');
$.ajax({
data: form.serialize(),
url: form.attr('action'),
type: form.attr('method'),
dataType: 'json',
success: function(data) {
if (data.success) {
success(data.success);
$('#form_create')[0].reset();
} else {
warning(data.warning);
}
},
error: function(data) {
if (data.status === 422) {
let errors = $.parseJSON(data.responseText);
addErrorMessage(errors);
}
}
});
}
const update = () => {
let form = $('#form_update');
$.ajax({
data: form.serialize(),
url: form.attr('action'),
type: form.attr('method'),
dataType: 'json',
success: function(data) {
if (data.success) {
success(data.success);
setTimeout(function() {
window.location.href = '../../product';
}, 2000);
} else {
warning(data.warning);
}
},
error: function(data) {
if (data.status === 422) {
let errors = $.parseJSON(data.responseText);
addErrorMessage(errors);
}
}
});
}
const btnSave = () => {
$('#btnsave').click(function(e) {
e.preventDefault();
save();
});
}
const btnUpdate = () => {
$('#btnUpdate').click(function(e) {
e.preventDefault();
update();
});
}
const success = (mensaje) => {
let success = swal("Exito!", `${mensaje}`, "success");
return success;
}
const warning = (mensaje) => {
let warning = swal("Error!", `${mensaje}`, "warning");
return warning;
}
const addErrorMessage = (errors) => {
let messages = "";
$.each(errors, function(key, value) {
if ($.isPlainObject(value)) {
$.each(value, function(key, value) {
messages = messages + "<li><span class='font-bold col-pink'>" + value + "</span></li><br/>";
});
}
});
showErrorMessage(messages);
}
const showErrorMessage = (messages) => {
swal({
title: "<strong>Error: Datos Incorrectos</strong>!",
text: messages,
html: true
});
}
const ajaxHeader = () => {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
}
|
# coding: utf-8
"""
Kubernetes
No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501
OpenAPI spec version: v1.14.7
Generated by: https://openapi-generator.tech
"""
import pprint
import re # noqa: F401
import six
class PolicyV1beta1AllowedFlexVolume(object):
"""NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
openapi_types = {
'driver': 'str'
}
attribute_map = {
'driver': 'driver'
}
def __init__(self, driver=None): # noqa: E501
"""PolicyV1beta1AllowedFlexVolume - a model defined in OpenAPI""" # noqa: E501
self._driver = None
self.discriminator = None
self.driver = driver
@property
def driver(self):
"""Gets the driver of this PolicyV1beta1AllowedFlexVolume. # noqa: E501
driver is the name of the Flexvolume driver. # noqa: E501
:return: The driver of this PolicyV1beta1AllowedFlexVolume. # noqa: E501
:rtype: str
"""
return self._driver
@driver.setter
def driver(self, driver):
"""Sets the driver of this PolicyV1beta1AllowedFlexVolume.
driver is the name of the Flexvolume driver. # noqa: E501
:param driver: The driver of this PolicyV1beta1AllowedFlexVolume. # noqa: E501
:type: str
"""
if driver is None:
raise ValueError("Invalid value for `driver`, must not be `None`") # noqa: E501
self._driver = driver
def to_dict(self):
"""Returns the model properties as a dict"""
result = {}
for attr, _ in six.iteritems(self.openapi_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
return result
def to_str(self):
"""Returns the string representation of the model"""
return pprint.pformat(self.to_dict())
def __repr__(self):
"""For `print` and `pprint`"""
return self.to_str()
def __eq__(self, other):
"""Returns true if both objects are equal"""
if not isinstance(other, PolicyV1beta1AllowedFlexVolume):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
"""Returns true if both objects are not equal"""
return not self == other
|
import json
import os
import unittest
from unittest import mock
from pyramid import testing
from kinto.core.cache import postgresql as postgresql_cache
from kinto.core.permission import postgresql as postgresql_permission
from kinto.core.storage import postgresql as postgresql_storage
from kinto.core.storage.postgresql.migrator import MigratorMixin
from kinto.core.testing import skip_if_no_postgresql
@mock.patch.object(MigratorMixin, "_execute_sql_file")
class MigratorTest(unittest.TestCase):
def setUp(self):
self.migrator = MigratorMixin()
here = os.path.dirname(__file__)
migrations_directory = os.path.join(here, "migrations")
self.migrator.migrations_directory = migrations_directory
self.migrator.schema_version = 6
def test_schema_is_created_if_no_version(self, execute_sql):
with mock.patch.object(self.migrator, "create_schema") as create_schema:
with mock.patch.object(self.migrator, "get_installed_version") as installed_version:
installed_version.return_value = None
self.migrator.create_or_migrate_schema()
self.assertTrue(create_schema.called)
def test_schema_is_not_touched_if_already_current(self, execute_sql):
# Patch to keep track of SQL files executed.
with mock.patch.object(self.migrator, "get_installed_version") as installed_version:
installed_version.return_value = 6
self.migrator.create_or_migrate_schema()
self.assertFalse(execute_sql.called)
def _walk_from_3_to_6(self):
"""Helper method for simulating a migration from version 3 to version 6."""
versions = [6, 5, 4, 3, 3]
self.migrator.get_installed_version = lambda: versions.pop()
def test_migration_file_is_executed_for_every_intermediary_version(self, execute_sql):
self._walk_from_3_to_6()
self.migrator.create_or_migrate_schema()
sql_called = execute_sql.call_args_list[-3][0][0]
self.assertIn(os.path.join("migrations", "migration_003_004.sql"), sql_called)
sql_called = execute_sql.call_args_list[-2][0][0]
self.assertIn(os.path.join("migrations", "migration_004_005.sql"), sql_called)
sql_called = execute_sql.call_args_list[-1][0][0]
self.assertIn(os.path.join("migrations", "migration_005_006.sql"), sql_called)
def test_migration_files_are_listed_if_ran_with_dry_run(self, execute_sql):
self._walk_from_3_to_6()
with mock.patch("kinto.core.storage.postgresql.migrator.logger") as mocked:
self.migrator.create_or_migrate_schema(dry_run=True)
output = "".join([repr(call) for call in mocked.info.call_args_list]).replace("\\\\", "\\")
self.assertIn(os.path.join("migrations", "migration_003_004.sql"), output)
self.assertIn(os.path.join("migrations", "migration_004_005.sql"), output)
self.assertIn(os.path.join("migrations", "migration_005_006.sql"), output)
def test_migration_fails_if_intermediary_version_is_missing(self, execute_sql):
with mock.patch.object(self.migrator, "get_installed_version") as current:
current.return_value = -1
self.assertRaises(AssertionError, self.migrator.create_or_migrate_schema)
@skip_if_no_postgresql
class PostgresqlStorageMigrationTest(unittest.TestCase):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
from kinto.core.utils import sqlalchemy
if sqlalchemy is None:
return
from .test_storage import PostgreSQLStorageTest
self.settings = {**PostgreSQLStorageTest.settings}
self.config = testing.setUp()
self.config.add_settings(self.settings)
self.version = postgresql_storage.Storage.schema_version
# Usual storage object to manipulate the storage.
self.storage = postgresql_storage.load_from_config(self.config)
def setUp(self):
# Start empty.
self._delete_everything()
def tearDown(self):
postgresql_storage.Storage.schema_version = self.version
# Finish empty.
self._delete_everything()
def _delete_everything(self):
q = """
DROP TABLE IF EXISTS records CASCADE;
DROP TABLE IF EXISTS objects CASCADE;
DROP TABLE IF EXISTS deleted CASCADE;
DROP TABLE IF EXISTS timestamps CASCADE;
DROP TABLE IF EXISTS metadata CASCADE;
DROP FUNCTION IF EXISTS resource_timestamp(VARCHAR, VARCHAR);
DROP FUNCTION IF EXISTS collection_timestamp(VARCHAR, VARCHAR);
DROP FUNCTION IF EXISTS bump_timestamp();
"""
with self.storage.client.connect() as conn:
conn.execute(q)
def _load_schema(self, filepath):
with self.storage.client.connect() as conn:
here = os.path.dirname(__file__)
with open(os.path.join(here, filepath)) as f:
old_schema = f.read()
conn.execute(old_schema)
def test_does_not_execute_if_ran_with_dry(self):
self.storage.initialize_schema(dry_run=True)
query = """SELECT 1 FROM information_schema.tables
WHERE table_name = 'objects';"""
with self.storage.client.connect(readonly=True) as conn:
result = conn.execute(query)
self.assertEqual(result.rowcount, 0)
def test_schema_sets_the_current_version(self):
# Create schema in its last version
self.storage.initialize_schema()
version = self.storage.get_installed_version()
self.assertEqual(version, self.version)
def test_schema_is_considered_first_version_if_no_version_detected(self):
# Create schema in its last version
self.storage.initialize_schema()
with self.storage.client.connect() as conn:
q = "DELETE FROM metadata WHERE name = 'storage_schema_version';"
conn.execute(q)
self.assertEqual(self.storage.get_installed_version(), 1)
def test_schema_is_considered_20_if_server_is_wiped(self):
# Create schema in its last version
self.storage.initialize_schema()
with self.storage.client.connect() as conn:
q = "DELETE FROM metadata;"
conn.execute(q)
self.assertEqual(self.storage.get_installed_version(), 20)
def test_every_available_migration(self):
"""Test every migration available in kinto.core code base since
version 1.6.
Objects migration test is currently very naive, and should be
elaborated along future migrations.
"""
# Install old schema
self._load_schema("schema/postgresql-storage-1.6.sql")
# Create a sample object using some code that is compatible with the
# schema in place in cliquet 1.6.
with self.storage.client.connect() as conn:
before = {"drink": "cacao"}
query = """
INSERT INTO records (user_id, resource_name, data)
VALUES (:user_id, :resource_name, (:data)::JSON)
RETURNING id, as_epoch(last_modified) AS last_modified;
"""
placeholders = dict(
user_id="jean-louis", resource_name="test", data=json.dumps(before)
)
result = conn.execute(query, placeholders)
inserted = result.fetchone()
before["id"] = str(inserted["id"])
before["last_modified"] = inserted["last_modified"]
# In cliquet 1.6, version = 1.
version = self.storage.get_installed_version()
self.assertEqual(version, 1)
# Run every migrations available.
self.storage.initialize_schema()
# Version matches current one.
version = self.storage.get_installed_version()
self.assertEqual(version, self.version)
# Check that previously created object is still here
migrated = self.storage.list_all("test", "jean-louis")
self.assertEqual(migrated[0], before)
# Check that new objects can be created
r = self.storage.create("test", ",jean-louis", {"drink": "mate"})
# And deleted
self.storage.delete("test", ",jean-louis", r["id"])
def test_every_available_migration_succeeds_if_tables_were_flushed(self):
self.storage.initialize_schema()
# During tests, tables can be flushed.
self.storage.flush()
self.storage.initialize_schema()
# Version matches current one.
version = self.storage.get_installed_version()
self.assertEqual(version, self.version)
def test_migration_12_clean_tombstones(self):
last_version = postgresql_storage.Storage.schema_version
postgresql_storage.Storage.schema_version = 11
self._load_schema("schema/postgresql-storage-11.sql")
insert_query = """
INSERT INTO records (id, parent_id, collection_id, data, last_modified)
VALUES (:id, :parent_id, :collection_id, (:data)::JSONB, from_epoch(:last_modified))
"""
placeholders = dict(
id="rid",
parent_id="jean-louis",
collection_id="test",
data=json.dumps({"drink": "mate"}),
last_modified=123456,
)
with self.storage.client.connect() as conn:
conn.execute(insert_query, placeholders)
create_tombstone = """
INSERT INTO deleted (id, parent_id, collection_id, last_modified)
VALUES (:id, :parent_id, :collection_id, from_epoch(:last_modified))
"""
with self.storage.client.connect() as conn:
conn.execute(create_tombstone, placeholders)
# Execute the 011 to 012 migration (and others)
postgresql_storage.Storage.schema_version = last_version
self.storage.initialize_schema()
# Check that the rotted tombstone has been removed, but the
# original object remains.
objects = self.storage.list_all("test", "jean-louis")
# Only the object remains.
assert len(objects) == 1
def test_migration_18_merges_tombstones(self):
last_version = postgresql_storage.Storage.schema_version
self._load_schema("schema/postgresql-storage-11.sql")
# Schema 11 is essentially the same as schema 17
postgresql_storage.Storage.schema_version = 17
with self.storage.client.connect() as conn:
conn.execute(
"""
UPDATE metadata SET value = '17'
WHERE name = 'storage_schema_version';
"""
)
insert_query = """
INSERT INTO records (id, parent_id, collection_id, data, last_modified)
VALUES (:id, :parent_id, :collection_id, (:data)::JSONB, from_epoch(:last_modified))
"""
placeholders = dict(
id="rid",
parent_id="jean-louis",
collection_id="test",
data=json.dumps({"drink": "mate"}),
last_modified=123456,
)
with self.storage.client.connect() as conn:
conn.execute(insert_query, placeholders)
create_tombstone = """
INSERT INTO deleted (id, parent_id, collection_id, last_modified)
VALUES (:id, :parent_id, :collection_id, from_epoch(:last_modified))
"""
with self.storage.client.connect() as conn:
conn.execute(create_tombstone, placeholders)
# Execute the 017 to 018 migration (and others)
postgresql_storage.Storage.schema_version = last_version
self.storage.initialize_schema()
# Check that the object took precedence of over the tombstone.
objects = self.storage.list_all("test", "jean-louis", include_deleted=True)
count = self.storage.count_all("test", "jean-louis")
assert len(objects) == 1
assert count == 1
assert objects[0]["drink"] == "mate"
@skip_if_no_postgresql
class PostgresqlPermissionMigrationTest(unittest.TestCase):
def __init__(self, *args, **kw):
super().__init__(*args, **kw)
from kinto.core.utils import sqlalchemy
if sqlalchemy is None:
return
from .test_permission import PostgreSQLPermissionTest
settings = {**PostgreSQLPermissionTest.settings}
config = testing.setUp()
config.add_settings(settings)
self.permission = postgresql_permission.load_from_config(config)
def setUp(self):
q = """
DROP TABLE IF EXISTS access_control_entries CASCADE;
DROP TABLE IF EXISTS user_principals CASCADE;
DROP TABLE IF EXISTS metadata CASCADE;
"""
with self.permission.client.connect() as conn:
conn.execute(q)
def _load_schema(self, filepath):
with self.permission.client.connect() as conn:
here = os.path.dirname(__file__)
with open(os.path.join(here, filepath)) as f:
old_schema = f.read()
conn.execute(old_schema)
def test_assumes_schema_1_if_no_permission_schema_version(self):
self.permission.initialize_schema()
q = """
DELETE FROM metadata WHERE name = 'permission_schema_version';
"""
with self.permission.client.connect() as conn:
conn.execute(q)
self.assertEqual(self.permission.get_installed_version(), 1)
def test_assumes_schema_1_if_no_metadata_table(self):
self.permission.initialize_schema()
q = """
DROP TABLE metadata;
"""
with self.permission.client.connect() as conn:
conn.execute(q)
self.assertEqual(self.permission.get_installed_version(), 1)
def test_assumes_no_schema_if_no_user_principals_table(self):
# Verify that the permission migrations assume no schema if
# the user_principals table is missing, even if the metadata
# table is present from the storage migrations.
self.permission.initialize_schema()
q = """
DELETE FROM metadata WHERE name = 'permission_schema_version';
DROP TABLE user_principals;
"""
with self.permission.client.connect() as conn:
conn.execute(q)
self.assertEqual(self.permission.get_installed_version(), None)
def test_schema_creation_leaves_at_max_version(self):
self.permission.initialize_schema()
self.assertEqual(self.permission.get_installed_version(), self.permission.schema_version)
def test_runs_initialize_schema_if_using_it_fails(self):
self.permission.initialize_schema()
query = """SELECT 1 FROM information_schema.tables
WHERE table_name = 'user_principals';"""
with self.permission.client.connect(readonly=True) as conn:
result = conn.execute(query)
self.assertEqual(result.rowcount, 1)
def test_does_not_execute_if_ran_with_dry(self):
self.permission.initialize_schema(dry_run=True)
query = """SELECT 1 FROM information_schema.tables
WHERE table_name = 'user_principals';"""
with self.permission.client.connect(readonly=True) as conn:
result = conn.execute(query)
self.assertEqual(result.rowcount, 0)
def test_every_available_migration(self):
"""Test every permission migration available in code base.
Objects migration test is currently very naive, and should be
elaborated along future migrations.
"""
# Install old schema
self._load_schema("schema/postgresql-permission-1.sql")
# Create some permissions data using some code that is
# compatible with the schema in place.
with self.permission.client.connect() as conn:
query = """
INSERT INTO user_principals
VALUES ('remy', 'admin');
INSERT INTO access_control_entries VALUES
('sailboat', 'write', 'remy'),
('sailboat', 'read', 'ethan'),
('sailboat/log', 'read', 'system.Authenticated'),
('sailboat/log', 'write', 'admin');
"""
conn.execute(query)
version = self.permission.get_installed_version()
self.assertEqual(version, 1)
# Run every migrations available.
self.permission.initialize_schema()
# Version matches current one.
version = self.permission.get_installed_version()
self.assertEqual(version, self.permission.schema_version)
# Check that previously created data is still available
remy_principals = self.permission.get_user_principals("remy")
self.assertEqual(remy_principals, set(["admin"]))
remy_objects = self.permission.get_accessible_objects(
["remy", "admin", "system.Authenticated"]
)
self.assertEqual(
remy_objects, {"sailboat": set(["write"]), "sailboat/log": set(["read", "write"])}
)
# Check that new objects can be created
self.permission.add_user_principal("ethan", "crew")
# And deleted
self.permission.remove_principal_from_ace("sailboat/log", "read", "system.Authenticated")
@skip_if_no_postgresql
class PostgresqlCacheMigrationTest(unittest.TestCase):
def __init__(self, *args, **kw):
super().__init__(*args, **kw)
from kinto.core.utils import sqlalchemy
if sqlalchemy is None:
return
from .test_cache import PostgreSQLCacheTest
settings = {**PostgreSQLCacheTest.settings}
config = testing.setUp()
config.add_settings(settings)
self.cache = postgresql_cache.load_from_config(config)
def setUp(self):
q = """
DROP TABLE IF EXISTS cache CASCADE;
"""
with self.cache.client.connect() as conn:
conn.execute(q)
def test_runs_initialize_schema_if_using_it_fails(self):
self.cache.initialize_schema()
query = """SELECT 1 FROM information_schema.tables
WHERE table_name = 'cache';"""
with self.cache.client.connect(readonly=True) as conn:
result = conn.execute(query)
self.assertEqual(result.rowcount, 1)
def test_does_not_execute_if_ran_with_dry(self):
self.cache.initialize_schema(dry_run=True)
query = """SELECT 1 FROM information_schema.tables
WHERE table_name = 'cache';"""
with self.cache.client.connect(readonly=True) as conn:
result = conn.execute(query)
self.assertEqual(result.rowcount, 0)
class PostgresqlExceptionRaisedTest(unittest.TestCase):
def setUp(self):
self.sqlalchemy = postgresql_storage.client.sqlalchemy
def tearDown(self):
postgresql_storage.client.sqlalchemy = self.sqlalchemy
def test_postgresql_usage_raise_an_error_if_postgresql_not_installed(self):
postgresql_storage.client.sqlalchemy = None
with self.assertRaises(ImportWarning):
postgresql_storage.client.create_from_config(testing.setUp())
|
// Parses the `text`.
//
// Returns `{ value, caret }` where `caret` is
// the caret position inside `value`
// corresponding to the `caret_position` inside `text`.
//
// The `text` is parsed by feeding each character sequentially to
// `parse_character(character, value)` function
// and appending the result (if it's not `undefined`) to `value`.
//
// Example:
//
// `text` is `8 (800) 555-35-35`,
// `caret_position` is `4` (before the first `0`).
// `parse_character` is `(character, value) =>
// if (character >= '0' && character <= '9') { return character }`.
//
// then `parse()` outputs `{ value: '88005553535', caret: 2 }`.
//
export default function parse(text, caret_position, parse_character) {
var value = '';
var focused_input_character_index = 0;
var index = 0;
while (index < text.length) {
var character = parse_character(text[index], value);
if (character !== undefined) {
value += character;
if (caret_position !== undefined) {
if (caret_position === index) {
focused_input_character_index = value.length - 1;
} else if (caret_position > index) {
focused_input_character_index = value.length;
}
}
}
index++;
} // If caret position wasn't specified
if (caret_position === undefined) {
// Then set caret position to "after the last input character"
focused_input_character_index = value.length;
}
var result = {
value: value,
caret: focused_input_character_index
};
return result;
}
//# sourceMappingURL=parse.js.map
|
describe('Cypress Test 1', () => {
it('This is a placeholder test', () => {
cy.visit('http://localhost:3000/dashboard')
cy.contains('Login').click()
})
})
|
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
# Copyright 2016 Timothy Dozat
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from collections import defaultdict
#***************************************************************
class Tarjan:
"""
Computes Tarjan's algorithm for finding strongly connected components (cycles) of a graph
Attributes:
edges: dictionary of edges such that edges[dep] = head
vertices: set of dependents
SCCs: list of sets of strongly connected components. Non-singleton sets are cycles.
"""
#=============================================================
def __init__(self, prediction, tokens):
"""
Inputs:
prediction: a predicted dependency tree where
prediction[dep_idx] = head_idx
tokens: the tokens we care about (i.e. exclude _GO, _EOS, and _PAD)
"""
self._edges = defaultdict(set)
self._vertices = set((0,))
for dep, head in enumerate(prediction[tokens]):
self._vertices.add(dep+1)
self._edges[head].add(dep+1)
self._indices = {}
self._lowlinks = {}
self._onstack = defaultdict(lambda: False)
self._SCCs = []
index = 0
stack = []
for v in self.vertices:
if v not in self.indices:
self.strongconnect(v, index, stack)
#=============================================================
def strongconnect(self, v, index, stack):
""""""
self._indices[v] = index
self._lowlinks[v] = index
index += 1
stack.append(v)
self._onstack[v] = True
for w in self.edges[v]:
if w not in self.indices:
self.strongconnect(w, index, stack)
self._lowlinks[v] = min(self._lowlinks[v], self._lowlinks[w])
elif self._onstack[w]:
self._lowlinks[v] = min(self._lowlinks[v], self._indices[w])
if self._lowlinks[v] == self._indices[v]:
self._SCCs.append(set())
while stack[-1] != v:
w = stack.pop()
self._onstack[w] = False
self._SCCs[-1].add(w)
w = stack.pop()
self._onstack[w] = False
self._SCCs[-1].add(w)
return
#======================
@property
def edges(self):
return self._edges
@property
def vertices(self):
return self._vertices
@property
def indices(self):
return self._indices
@property
def SCCs(self):
return self._SCCs
|
import request from '@/utils/request'
export function add(data) {
return request({
url: 'api/title',
method: 'post',
data
})
}
export function edit(data) {
return request({
url: 'api/title',
method: 'put',
data
})
}
export function del(ids) {
return request({
url: 'api/title',
method: 'delete',
data: ids
})
}
export function getAllTitle() {
const params = {
page: 0,
size: 9999
}
return request({
url: 'api/title',
method: 'get',
params
})
}
export default { add, edit, del }
|
'use strict';
for (const i = 0; i < 1; i++) {
console.log(i);
}
// 0
// TypeError: Assignment to constant variable.
|
var MongoClient = require('mongodb').MongoClient;
MongoClient.connect('mongodb://localhost:27017/course', function(err, db) {
if(err) throw err;
var query = { 'assignment' : 'hw1' };
db.collection('grades').findOne(query, function(err, doc) {
if(err) throw err;
if(!doc) {
console.log('No documents for assignment ' + query.assignment + ' found!');
return db.close();
}
query['_id'] = doc['_id'];
doc['date_returned'] = new Date();
db.collection('grades').update(query, doc, function(err, updated) {
if(err) throw err;
console.dir("Successfully updated " + updated + " document!");
return db.close();
});
});
});
|
# -*- coding: utf-8 -*-
"""
services.payment
~~~~~~~~~~~~~~~~
Services for payments
"""
import falcon
import arrow
from .mongo import DService
from smpa.models.payment import Payment
class PaymentService(DService):
__model__ = Payment
def check(self, id):
"""Checks the status of a payment on GovPay
"""
from smpa.app import govpay
payment = _payments.get(str(id))
if payment.payment_id is None:
raise falcon.HTTPError(falcon.HTTP_404, 'Payment not found')
rv = govpay.check_payment(payment.payment_id)
j = rv.json()
if rv.status_code == 200:
payment = _payments.update(id=payment.id, json=j)
return payment
else:
response = {
"success": False
}
if j.get('description', None) is not None:
response["message"] = j.get('description')
if j.get('code', None) is not None:
response["code"] = j.get('code')
raise falcon.HTTPError(falcon.HTTP_422, response)
def create(self, req, application_id):
"""
Errors from GovPay look like this...
{
"field": "amount",
"code": "P0102",
"description": "Invalid attribute value: amount. Must be less than or equal to 10000000"
}
The create application payment method needs to...
1. Generate a unique reference number
2. Call govpay.create_payment
3. Create a Payment model
4. Return that Payment model
Args:
**kwargs: Description
"""
from smpa.app import config, govpay
from .application import _applications, _application_references
ref = _application_references.next()
application = _applications.get(application_id)
application.reference = ref
_applications.save(application)
amount = config.PAYMENT_AMOUNT
description = config.PAYMENT_DESCRIPTION
user = req.context['user']
user.export()
# Create a local payment object first so we have an ID
payment = self.new()
payment.owner_id = str(user.id)
payment.application_id = str(application_id)
payment = _payments.save(payment)
# Create the payment
rv = govpay.create_payment(
amount=amount,
description=description,
reference=ref,
application_id=application_id,
payment_id=str(payment.id)
)
j = rv.json()
if rv.status_code == 201:
payment = _payments.update(id=str(payment.id), json=j)
payment.next_url = j['_links']['next_url']['href']
payment = _payments.save(payment)
# Update the application with a reference
application = _applications.get(str(application_id))
application.reference = ref
_applications.save(application)
return payment
else:
response = {
"success": False
}
if j.get('description', None) is not None:
response["message"] = j.get('description')
if j.get('code', None) is not None:
response["code"] = j.get('code')
raise falcon.HTTPError(falcon.HTTP_422, response)
_payments = PaymentService()
|
(function ($) {
"use strict";
/*-------------------------------------
Contact Form initiating
-------------------------------------*/
var contactForm = $('#contact-form');
if (contactForm.length) {
contactForm.validator().on('submit', function (e) {
var $this = $(this),
$target = contactForm.find('.form-response');
if (e.isDefaultPrevented()) {
$target.html("<div class='alert alert-success'><p>Please select all required field.</p></div>");
} else {
$.ajax({
url: "vendor/php/contact-form-process.php",
type: "POST",
data: contactForm.serialize(),
beforeSend: function () {
$target.html("<div class='alert alert-info'><p>Loading ...</p></div>");
},
success: function (text) {
if (text === "success") {
$this[0].reset();
$target.html("<div class='alert alert-success'><p>Message has been sent successfully.</p></div>");
} else {
$target.html("<div class='alert alert-success'><p>" + text + "</p></div>");
}
}
});
return false;
}
});
}
/*-------------------------------------
Jquery Serch Box
-------------------------------------*/
$('a[href="#search"]').on("click", function (event) {
event.preventDefault();
var target = $("#search");
target.addClass("open");
setTimeout(function () {
target.find('input').focus();
}, 600);
return false;
});
$("#search, #search button.close").on("click keyup", function (event) {
if (
event.target === this ||
event.target.className === "close" ||
event.keyCode === 27
) {
$(this).removeClass("open");
}
});
/*-------------------------------------
Jquery Advance Serch Box
-------------------------------------*/
$("#adv-serch").on('click', function () {
var _self = $(this);
_self.parents('.adv-search-wrap').find(".advance-search-form").slideToggle();
_self.toggleClass('icon-alter');
});
/*-------------------------------------
Quantity Holder
-------------------------------------*/
$('#quantity-holder').on('click', '.quantity-plus', function () {
var $holder = $(this).parents('.quantity-holder');
var $target = $holder.find('input.quantity-input');
var $quantity = parseInt($target.val(), 10);
if ($.isNumeric($quantity) && $quantity > 0) {
$quantity = $quantity + 1;
$target.val($quantity);
} else {
$target.val($quantity);
}
}).on('click', '.quantity-minus', function () {
var $holder = $(this).parents('.quantity-holder');
var $target = $holder.find('input.quantity-input');
var $quantity = parseInt($target.val(), 10);
if ($.isNumeric($quantity) && $quantity >= 2) {
$quantity = $quantity - 1;
$target.val($quantity);
} else {
$target.val(1);
}
});
/*-------------------------------------
On Scroll
-------------------------------------*/
$(window).on('scroll', function () {
if ($(window).scrollTop() > 700) {
$('.scrollup').addClass('back-top');
} else {
$('.scrollup').removeClass('back-top');
}
});
/*-------------------------------------
Rating selection
-------------------------------------*/
$('.rate-wrapper').on('click', '.rate .rate-item', function () {
var self = $(this),
target = self.parent('.rate');
target.addClass('selected');
target.find('.rate-item').removeClass('active');
self.addClass('active');
});
/*-------------------------------------
Select2 activation code
-------------------------------------*/
if ($('select.select2').length) {
$('select.select2').select2({
theme: 'classic',
dropdownAutoWidth: true,
width: '100%'
});
$('.opening-hours-wrap select.select2').select2({
theme: 'classic',
width: '100%'
});
}
/*-------------------------------------
Google Map
-------------------------------------*/
if ($('#googleMap').length) {
var initialize = function () {
var mapOptions = {
zoom: 15,
scrollwheel: false,
center: new google.maps.LatLng(-37.81618, 144.95692),
styles: [{
stylers: [{
saturation: -100
}]
}]
};
var map = new google.maps.Map(document.getElementById("googleMap"), mapOptions);
var marker = new google.maps.Marker({
position: map.getCenter(),
animation: google.maps.Animation.BOUNCE,
icon: 'img/map-marker.png',
map: map
});
}
// Add the map initialize function to the window load function
google.maps.event.addDomListener(window, "load", initialize);
}
/*-------------------------------------
Active Menu
-------------------------------------*/
$('#site-menu li a').on('click', function () {
$('#site-menu').find('.current').removeClass('current');
$(this).parent().addClass('current');
});
$('.toggle-menu').on('click', function () {
$('#site-menu').slideToggle(500);
$(this).toggleClass('active');
})
/*-------------------------------------
Menu fixded
-------------------------------------*/
if ($('header .header-main-menu').length && $('header .header-main-menu').hasClass('header-sticky')) {
var header_position = $('header .header-main-menu').offset(),
lastScroll = 100;
$(window).on('scroll load', function (event) {
var st = $(this).scrollTop();
if (st > header_position.top) {
($(".header-table").length) ? $('header .header-table').addClass("header-fixed"): $('header .header-main-menu').addClass("header-fixed");
} else {
($(".header-table").length) ? $('header .header-table').removeClass("header-fixed"): $('header .header-main-menu').removeClass("header-fixed");
}
lastScroll = st;
if (st === 0) {
($(".header-table").length) ? $('header .header-table').removeClass("header-fixed"): $('header .header-main-menu').removeClass("header-fixed");
}
});
}
/*---------------------------------------
On Click Section Switch
--------------------------------------- */
$('[data-type="section-switch"]').on('click', function () {
if (location.pathname.replace(/^\//, '') === this.pathname.replace(/^\//, '') && location.hostname === this.hostname) {
var target = $(this.hash);
if (target.length > 0) {
target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
$('html,body').animate({
scrollTop: target.offset().top
}, 1000);
return false;
}
}
});
/*-------------------------------------
Carousel slider initiation
-------------------------------------*/
if ($.fn.owlCarousel) {
$('.rc-carousel').each(function () {
var carousel = $(this),
loop = carousel.data('loop'),
items = carousel.data('items'),
margin = carousel.data('margin'),
stagePadding = carousel.data('stage-padding'),
autoplay = carousel.data('autoplay'),
autoplayTimeout = carousel.data('autoplay-timeout'),
smartSpeed = carousel.data('smart-speed'),
dots = carousel.data('dots'),
nav = carousel.data('nav'),
navSpeed = carousel.data('nav-speed'),
rXsmall = carousel.data('r-x-small'),
rXsmallNav = carousel.data('r-x-small-nav'),
rXsmallDots = carousel.data('r-x-small-dots'),
rXmedium = carousel.data('r-x-medium'),
rXmediumNav = carousel.data('r-x-medium-nav'),
rXmediumDots = carousel.data('r-x-medium-dots'),
rSmall = carousel.data('r-small'),
rSmallNav = carousel.data('r-small-nav'),
rSmallDots = carousel.data('r-small-dots'),
rMedium = carousel.data('r-medium'),
rMediumNav = carousel.data('r-medium-nav'),
rMediumDots = carousel.data('r-medium-dots'),
rLarge = carousel.data('r-large'),
rLargeNav = carousel.data('r-large-nav'),
rLargeDots = carousel.data('r-large-dots'),
rExtraLarge = carousel.data('r-extra-large'),
rExtraLargeNav = carousel.data('r-extra-large-nav'),
rExtraLargeDots = carousel.data('r-extra-large-dots'),
center = carousel.data('center'),
custom_nav = carousel.data('custom-nav') || '';
carousel.addClass('owl-carousel');
var owl = carousel.owlCarousel({
loop: (loop ? true : false),
items: (items ? items : 4),
lazyLoad: true,
margin: (margin ? margin : 0),
autoplay: (autoplay ? true : false),
autoplayTimeout: (autoplayTimeout ? autoplayTimeout : 1000),
smartSpeed: (smartSpeed ? smartSpeed : 250),
dots: (dots ? true : false),
nav: (nav ? true : false),
navText: ['<i class="flaticon-back" aria-hidden="true"></i>', '<i class="flaticon-next" aria-hidden="true"></i>'],
navSpeed: (navSpeed ? true : false),
center: (center ? true : false),
responsiveClass: true,
responsive: {
0: {
items: (rXsmall ? rXsmall : 1),
nav: (rXsmallNav ? true : false),
dots: (rXsmallDots ? true : false)
},
576: {
items: (rXmedium ? rXmedium : 2),
nav: (rXmediumNav ? true : false),
dots: (rXmediumDots ? true : false)
},
768: {
items: (rSmall ? rSmall : 3),
nav: (rSmallNav ? true : false),
dots: (rSmallDots ? true : false)
},
992: {
items: (rMedium ? rMedium : 4),
nav: (rMediumNav ? true : false),
dots: (rMediumDots ? true : false)
},
1200: {
items: (rLarge ? rLarge : 5),
nav: (rLargeNav ? true : false),
dots: (rLargeDots ? true : false)
},
1400: {
items: (rExtraLarge ? rExtraLarge : 6),
nav: (rExtraLargeNav ? true : false),
dots: (rExtraLargeDots ? true : false)
}
}
});
if (custom_nav) {
var nav = $(custom_nav),
nav_next = $('.rt-next', nav),
nav_prev = $('.rt-prev', nav);
nav_next.on('click', function (e) {
e.preventDefault();
owl.trigger('next.owl.carousel');
return false;
});
nav_prev.on('click', function (e) {
e.preventDefault();
owl.trigger('prev.owl.carousel');
return false;
});
}
});
}
/*-------------------------------------
Window On Load Function
-------------------------------------*/
$(window).on('load', function () {
// Page Preloader
$('#preloader').fadeOut('slow', function () {
$(this).remove();
});
});
/*---------------------------------------
Summernote
--------------------------------------- */
if ($.fn.summernote !== undefined) {
$(document).ready(function () {
$('.summernote').summernote({
height: 300,
});
});
}
/*-------------------------------------
Section background image
-------------------------------------*/
imageFunction();
function imageFunction() {
$('[data-bg-image]').each(function () {
var img = $(this).data('bg-image');
$(this).css({
backgroundImage: 'url(' + img + ')',
});
});
}
})(jQuery);
|
/**
* DevExtreme (viz/tree_map/tiling.rotated_slice_and_dice.js)
* Version: 18.2.3
* Build date: Wed Nov 07 2018
*
* Copyright (c) 2012 - 2018 Developer Express Inc. ALL RIGHTS RESERVED
* Read about DevExtreme licensing here: https://js.devexpress.com/Licensing/
*/
"use strict";
var tiling = require("./tiling"),
sliceAndDiceAlgorithm = tiling.getAlgorithm("sliceanddice");
function rotatedSliceAndDice(data) {
data.isRotated = !data.isRotated;
return sliceAndDiceAlgorithm.call(this, data)
}
tiling.addAlgorithm("rotatedsliceanddice", rotatedSliceAndDice);
|
import sys
from collections import OrderedDict
from functools import partial
import torch.nn as nn
from ..modules import IdentityResidualBlock, ABN, GlobalAvgPool2d
class WiderResNet(nn.Module):
def __init__(self,
structure,
in_channels,
norm_act=ABN,
classes=0):
"""Wider ResNet with pre-activation (identity mapping) blocks
Parameters
----------
structure : list of int
Number of residual blocks in each of the six modules of the network.
norm_act : callable
Function to create normalization / activation Module.
classes : int
If not `0` also include global average pooling and a fully-connected layer with `classes` outputs at the end
of the network.
"""
super(WiderResNet, self).__init__()
self.structure = structure
if len(structure) != 6:
raise ValueError("Expected a structure with six values")
# Initial layers
self.mod1 = nn.Sequential(OrderedDict([
("conv1", nn.Conv2d(3, 64, 3, stride=1, padding=1, bias=False))
]))
# Groups of residual blocks
in_channels = 64
channels = [(128, 128), (256, 256), (512, 512), (512, 1024), (512, 1024, 2048), (1024, 2048, 4096)]
for mod_id, num in enumerate(structure):
# Create blocks for module
blocks = []
for block_id in range(num):
blocks.append((
"block%d" % (block_id + 1),
IdentityResidualBlock(in_channels, channels[mod_id], norm_act=norm_act)
))
# Update channels and p_keep
in_channels = channels[mod_id][-1]
# Create module
if mod_id <= 4:
self.add_module("pool%d" % (mod_id + 2), nn.MaxPool2d(3, stride=2, padding=1))
self.add_module("mod%d" % (mod_id + 2), nn.Sequential(OrderedDict(blocks)))
# Pooling and predictor
self.bn_out = norm_act(in_channels)
if classes != 0:
self.classifier = nn.Sequential(OrderedDict([
("avg_pool", GlobalAvgPool2d()),
("fc", nn.Linear(in_channels, classes))
]))
def forward(self, img):
out = self.mod1(img)
out = self.mod2(self.pool2(out))
out = self.mod3(self.pool3(out))
out = self.mod4(self.pool4(out))
out = self.mod5(self.pool5(out))
out = self.mod6(self.pool6(out))
out = self.mod7(out)
out = self.bn_out(out)
if hasattr(self, "classifier"):
out = self.classifier(out)
return out
_NETS = {
"38": {"structure": [3, 3, 6, 3, 1, 1]},
}
def init_wider_resnet(**kwargs):
return WiderResNet(_NETS['38']['structure'], **kwargs)
__all__ = []
for name, params in _NETS.items():
net_name = "net_wider_resnet" + name
setattr(sys.modules[__name__], net_name, partial(WiderResNet, **params))
__all__.append(net_name)
|
import React, { useEffect } from 'react';
import { connect } from 'react-redux';
import { fetchPosts } from '../middleware';
import PostContainer from '../containers/PostContainer';
// import axios from 'axios';
// import { parseJson } from '../helpers';
// todo: once Comment fetch is completed and render is completed for Posts and Comments, remove subreddit name from store to prevent false API calls during store/state changes
// another fix: call all dispatches for fetch using useEffect and exclude subreddit in dependancy
function SubredditContainer(props) {
// one good change is to also move the fetchPosts function here cause this is the only container that will ever call it
// this also makes it easier to remove subreddit from store which means no repetitive fetch requests for every state change
// Hardcoded post url and params (delete later)
// const url = "https://www.reddit.com/r/news/top/.json?";
// const params = "limit=10";
//const url = `https://www.reddit.com/r/${useSelector(state => state.subreddit)}/${useSelector(state => state.filter)}/.json?`;
const url = `https://www.reddit.com/r/${props.subreddit}/${props.filter}/.json?`;
//const params = "limit=10";
const params = `limit=${props.numPosts}`;
const fullUrl = url+params;
// useEffect is used to mimic ComponentDidMount lifecycle method
// It also prevents fetchPosts being called unnecessarily when other state values change
// the 2nd argument to useEffect contains the dependancies so it will be called whenever any value in it changes
//useEffect(() => props.fetchPosts(url+params), [])
// useEffect(() => props.fetchPosts(url+params), [props.fetchPosts])
const fetchPostsDispatch = fullUrl => props.fetchPosts(fullUrl);
// disable useEffect missing dependancies warning
// eslint-disable-next-line react-hooks/exhaustive-deps
useEffect(() => fetchPostsDispatch(fullUrl), [props.subreddit, props.filter, props.numPosts]);
let arrPosts = [];
for (let i=0; i < props.allPosts.length; i++) {
arrPosts.push(<PostContainer showAll={props.showAll} key={i} postId={props.allPosts[i].reddit_id} />)
}
return (
<div className="row align-content-center" style={{flexDirection: "column"}}>
{/*arrPosts.length > 0 && arrPosts[0]*/}
{arrPosts}
</div>
);
}
const mapStateToProps = function(state) {
let result = []
state.posts.data.forEach(element => {
result.push(element);
});
// console.log("I am in mapStatetoProps", result)
return {
data: state.data,
error: state.posts.error,
//logged: state.logged, //do not include logged here as using props in useEffect dependancies calls fetchPosts infinite times
subreddit: state.subreddit,
filter: state.filter,
numPosts: state.numPosts,
allPosts: result
}
}
const mapDispatchToProps = function(dispatch) {
return ({
fetchPosts: (fullUrl) => {dispatch(fetchPosts(fullUrl))}
})
}
export default connect(mapStateToProps, mapDispatchToProps)(SubredditContainer);
|
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var tslib_1 = require("tslib");
tslib_1.__exportStar(require("./EventStreamMarshaller"), exports);
tslib_1.__exportStar(require("./Int64"), exports);
//# sourceMappingURL=index.js.map
|
/*! modernizr 3.6.0 (Custom Build) | MIT *
* https://modernizr.com/download/?-setclasses-shiv !*/
!function(e,n,t){function a(e,n){return typeof e===n}function o(){var e,n,t,o,r,s,l;for(var f in c)if(c.hasOwnProperty(f)){if(e=[],n=c[f],n.name&&(e.push(n.name.toLowerCase()),n.options&&n.options.aliases&&n.options.aliases.length))for(t=0;t<n.options.aliases.length;t++)e.push(n.options.aliases[t].toLowerCase());for(o=a(n.fn,"function")?n.fn():n.fn,r=0;r<e.length;r++)s=e[r],l=s.split("."),1===l.length?Modernizr[l[0]]=o:(!Modernizr[l[0]]||Modernizr[l[0]]instanceof Boolean||(Modernizr[l[0]]=new Boolean(Modernizr[l[0]])),Modernizr[l[0]][l[1]]=o),i.push((o?"":"no-")+l.join("-"))}}function r(e){var n=s.className,t=Modernizr._config.classPrefix||"";if(f&&(n=n.baseVal),Modernizr._config.enableJSClass){var a=new RegExp("(^|\\s)"+t+"no-js(\\s|$)");n=n.replace(a,"$1"+t+"js$2")}Modernizr._config.enableClasses&&(n+=" "+t+e.join(" "+t),f?s.className.baseVal=n:s.className=n)}var i=[],s=n.documentElement,c=[],l={_version:"3.6.0",_config:{classPrefix:"",enableClasses:!0,enableJSClass:!0,usePrefixes:!0},_q:[],on:function(e,n){var t=this;setTimeout(function(){n(t[e])},0)},addTest:function(e,n,t){c.push({name:e,fn:n,options:t})},addAsyncTest:function(e){c.push({name:null,fn:e})}},Modernizr=function(){};Modernizr.prototype=l,Modernizr=new Modernizr;var f="svg"===s.nodeName.toLowerCase();f||!function(e,n){function t(e,n){var t=e.createElement("p"),a=e.getElementsByTagName("head")[0]||e.documentElement;return t.innerHTML="x<style>"+n+"</style>",a.insertBefore(t.lastChild,a.firstChild)}function a(){var e=E.elements;return"string"==typeof e?e.split(" "):e}function o(e,n){var t=E.elements;"string"!=typeof t&&(t=t.join(" ")),"string"!=typeof e&&(e=e.join(" ")),E.elements=t+" "+e,l(n)}function r(e){var n=y[e[g]];return n||(n={},v++,e[g]=v,y[v]=n),n}function i(e,t,a){if(t||(t=n),u)return t.createElement(e);a||(a=r(t));var o;return o=a.cache[e]?a.cache[e].cloneNode():p.test(e)?(a.cache[e]=a.createElem(e)).cloneNode():a.createElem(e),!o.canHaveChildren||h.test(e)||o.tagUrn?o:a.frag.appendChild(o)}function s(e,t){if(e||(e=n),u)return e.createDocumentFragment();t=t||r(e);for(var o=t.frag.cloneNode(),i=0,s=a(),c=s.length;c>i;i++)o.createElement(s[i]);return o}function c(e,n){n.cache||(n.cache={},n.createElem=e.createElement,n.createFrag=e.createDocumentFragment,n.frag=n.createFrag()),e.createElement=function(t){return E.shivMethods?i(t,e,n):n.createElem(t)},e.createDocumentFragment=Function("h,f","return function(){var n=f.cloneNode(),c=n.createElement;h.shivMethods&&("+a().join().replace(/[\w\-:]+/g,function(e){return n.createElem(e),n.frag.createElement(e),'c("'+e+'")'})+");return n}")(E,n.frag)}function l(e){e||(e=n);var a=r(e);return!E.shivCSS||f||a.hasCSS||(a.hasCSS=!!t(e,"article,aside,dialog,figcaption,figure,footer,header,hgroup,main,nav,section{display:block}mark{background:#FF0;color:#000}template{display:none}")),u||c(e,a),e}var f,u,d="3.7.3",m=e.html5||{},h=/^<|^(?:button|map|select|textarea|object|iframe|option|optgroup)$/i,p=/^(?:a|b|code|div|fieldset|h1|h2|h3|h4|h5|h6|i|label|li|ol|p|q|span|strong|style|table|tbody|td|th|tr|ul)$/i,g="_html5shiv",v=0,y={};!function(){try{var e=n.createElement("a");e.innerHTML="<xyz></xyz>",f="hidden"in e,u=1==e.childNodes.length||function(){n.createElement("a");var e=n.createDocumentFragment();return"undefined"==typeof e.cloneNode||"undefined"==typeof e.createDocumentFragment||"undefined"==typeof e.createElement}()}catch(t){f=!0,u=!0}}();var E={elements:m.elements||"abbr article aside audio bdi canvas data datalist details dialog figcaption figure footer header hgroup main mark meter nav output picture progress section summary template time video",version:d,shivCSS:m.shivCSS!==!1,supportsUnknownElements:u,shivMethods:m.shivMethods!==!1,type:"default",shivDocument:l,createElement:i,createDocumentFragment:s,addElements:o};e.html5=E,l(n),"object"==typeof module&&module.exports&&(module.exports=E)}("undefined"!=typeof e?e:this,n),o(),r(i),delete l.addTest,delete l.addAsyncTest;for(var u=0;u<Modernizr._q.length;u++)Modernizr._q[u]();e.Modernizr=Modernizr}(window,document);
|
import React from 'react';
import Definition from '../../components/Definition';
import { Link } from 'react-router-dom';
function Notification({ notification }) {
return (
<React.Fragment>
<h4>Info</h4>
<Definition
items={[
['Name', notification.name],
['Subject', notification.subject],
['Label', notification.labels],
[
'Path',
<a href={`${window.DATA_DIR_URL}${notification.path}`} target="_blank" rel="noopener noreferrer">
{notification.path}
</a>
],
[
'Related Users',
<div>
{notification.to.users && notification.to.users.map(o =>
<Link
to={{
pathname: '/users',
hash: o.path
}}
>
<p>
{o.name}
</p>
</Link>
)}
</div>
],
[
'Body',
<div>
{notification.body.split("\n").map((i,key) => {
return <div key={key}>{i}</div>;
})}
</div>
]
]}
/>
</React.Fragment>
);
}
export default Notification;
|
deepmacDetailCallback("8c1cda100000/28",[{"a":"Pfaelzer Ring 18 Hockenheim Baden-Wuerttemberg DE 68766","o":"GESAS GmbH","d":"2018-02-11","t":"add","s":"ieee","c":"DE"}]);
|
# 2. Exercício Treino -
# Crie um dicionário em que suas chaves correspondem
# a números inteiros entre [1, 10] e cada valor associado é
# o número ao quadrado.
# {1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81, 10: 100}
dicio = dict() or {1: None, 2: None, 3: None, 4: None, 5: None, 6: None, 7: None, 8: None, 9: None, 10: None}
for i in dicio:
dicio[i] = i ** 2
print(dicio)
|
"""
Copyright 2018-2020 Jakub Kuczys (https://github.com/jack1142)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
from __future__ import annotations
from abc import ABC
from pathlib import Path
from typing import Any, BinaryIO, Dict, NamedTuple, Optional, Tuple, Union
from PIL import Image, ImageDraw, ImageFont, ImageOps
from .figures import Point
from .player import PlayerWithAvatar
from .utils import natural_size
class CoordsInfo(NamedTuple):
point: Point
font_name: Optional[str] = None
class Mee6RankImageTemplate:
def __init__(
self,
*,
coords: Dict[str, CoordsInfo],
fonts: Dict[str, ImageFont.ImageFont],
avatar_mask: Path,
card_base: Path,
progressbar: Path,
progressbar_rounding_mask: Path,
) -> None:
self.coords = coords
self.fonts = fonts
self.avatar_mask = avatar_mask
self.card_base = card_base
self.progressbar = progressbar
self.progressbar_rounding_mask = progressbar_rounding_mask
def get_coords(self, coords_name: str) -> CoordsInfo:
"""Get coords for given element."""
return self.coords[coords_name]
def generate_image(self, player: PlayerWithAvatar) -> Mee6RankImage:
return Mee6RankImage(self, player)
class MixinMeta(ABC):
def __init__(self) -> None:
self._result: Image.Image
class Mee6RankImageMixin(MixinMeta):
def __init__(self) -> None:
super().__init__()
self._draw = ImageDraw.Draw(self._result)
@property
def size(self) -> Tuple[int, int]:
return self._result.size
def alpha_composite(
self,
im: Union[Image.Image, Mee6RankImageMixin],
dest: Tuple[int, int] = (0, 0),
source: Union[Tuple[int, int], Tuple[int, int, int, int]] = (0, 0),
) -> None:
image = getattr(im, "_result", im)
self._result.alpha_composite(image, dest, source)
def paste(
self,
im: Union[
Image.Image,
Union[
int,
float,
Tuple[int, int],
Tuple[int, int, int],
Tuple[int, int, int, int],
],
str,
Mee6RankImageMixin,
],
box: Optional[Union[Tuple[int, int], Tuple[int, int, int, int]]] = None,
mask: Optional[Image.Image] = None,
) -> None:
image = getattr(im, "_result", im)
self._result.paste(image, box, mask)
def thumbnail(self, size: Tuple[int, int], resample: int = 3) -> None:
self._result.thumbnail(size, resample)
def save(
self,
fp: Union[str, Path, BinaryIO],
format: Optional[str] = None,
**params: Any,
) -> None:
self._result.save(fp, format, **params)
class Mee6RankImage(Mee6RankImageMixin):
def __init__(
self, template: Mee6RankImageTemplate, player: PlayerWithAvatar
) -> None:
self.template = template
self.fonts = self.template.fonts
self.player = player
self._result = Image.open(self.template.card_base).convert("RGBA")
super().__init__()
self._generate_image()
def __del__(self) -> None:
self._result.close()
def _generate_image(self) -> None:
self._draw_level()
self._draw_username()
self._draw_progressbar()
self._draw_xp()
self._draw_avatar()
def _draw_level(self) -> None:
# why do I even use templates when I still do stuff like this...
parts = {
"level_number": (str(self.player.level), 0, "#62d3f5"),
"level_caption": ("LEVEL", 6, "#62d3f5"),
"rank_number": (f"#{self.player.rank}", 15, "#ffffff"),
"rank_caption": ("RANK", 6, "#ffffff"),
}
offset_x = 0
for part_name, (text, offset, fill) in parts.items():
coords, font_name = self.template.get_coords(part_name)
# all parts from dict above have font name defined
assert isinstance(font_name, str), "mypy"
font = self.fonts[font_name]
x, offset_y = font.getsize(text)
offset_x += x + offset
coords -= (offset_x, offset_y)
self._draw.text(xy=coords, text=text, fill=fill, font=font)
def _draw_username(self) -> None:
# Username
# TODO: fix the math here - cut long usernames,
# change font size for longer text, etc.
text = self.player.member.name
coords, font_name = self.template.get_coords("username")
assert isinstance(font_name, str), "mypy" # username has font name defined
font = self.fonts[font_name]
offset_x, offset_y = font.getsize(text)
coords -= (0, offset_y)
self._draw.text(xy=coords, text=text, fill="#fff", font=font)
# discriminator
text = f"#{self.player.member.discriminator}"
coords, font_name = self.template.get_coords("discriminator")
assert isinstance(font_name, str), "mypy" # discriminator has font name defined
font = self.fonts[font_name]
_, offset_y = font.getsize(text)
offset_x += 10
coords += (offset_x, -offset_y)
self._draw.text(xy=coords, text=text, fill="#7f8384", font=font)
def _draw_progressbar(self) -> None:
with Image.open(self.template.progressbar) as progressbar_top:
result = Image.new(mode="RGBA", size=progressbar_top.size, color="#484b4e")
# calculate progressbar width
width = int(
self.player.level_xp / self.player.level_total_xp * result.width
)
# progressbar should be either 0 or 36 when <36
# (taken from comments in Mee6's svg)
if width < 36 and width != 0:
width = 36
# make progressbar
progressbar = Image.new(mode="RGBA", size=result.size)
progressbar_draw = ImageDraw.Draw(progressbar)
progressbar_draw.rectangle(xy=(0, 0, width, result.height), fill="#62d3f5")
# make and apply rounding mask for end (right side) of the progressbar
with Image.open(self.template.progressbar_rounding_mask).convert(
"L"
) as rounding_mask:
mask = Image.new(mode="L", size=progressbar.size, color="#ffffff")
mask.paste(rounding_mask, (width - rounding_mask.width + 1, 0))
mask_draw = ImageDraw.Draw(mask)
mask_draw.rectangle(
xy=(width, 0, mask.width, mask.height), fill="#000000"
)
progressbar.putalpha(mask)
# join everything
result.alpha_composite(progressbar)
result.alpha_composite(progressbar_top)
coords, _ = self.template.get_coords("progressbar")
self._result.alpha_composite(result, coords.to_tuple())
def _draw_xp(self) -> None:
# why do I even use templates when I still do stuff like this...
parts = {
"needed_xp": (
f"/ {natural_size(self.player.level_total_xp)} XP",
0,
"#7f8384",
),
"current_xp": (natural_size(self.player.level_xp), 6, "#ffffff"),
}
offset_x = 0
for part_name, (text, offset, fill) in parts.items():
coords, font_name = self.template.get_coords(part_name)
# all parts from dict above have font name defined
assert isinstance(font_name, str), "mypy"
font = self.fonts[font_name]
x, offset_y = font.getsize(text)
offset_x += x + offset
coords -= (offset_x, offset_y)
self._draw.text(xy=coords, text=text, fill=fill, font=font)
def _draw_avatar(self) -> None:
with Image.open(self.template.avatar_mask).convert("L") as avatar_mask:
avatar_file = self.player.avatar
avatar_file.seek(0)
avatar = Image.open(avatar_file)
avatar_output = ImageOps.fit(avatar, avatar_mask.size, centering=(0.5, 0.5))
avatar_output.putalpha(avatar_mask)
self._result.alpha_composite(avatar_output, (40, 60))
|
//// [typeAliases.ts]
// Writing a reference to a type alias has exactly the same effect as writing the aliased type itself.
type T1 = number;
var x1: number;
var x1: T1;
type T2 = string;
var x2: string;
var x2: T2;
type T3 = boolean;
var x3: boolean;
var x3: T3;
type T4 = void;
var x4: void;
var x4: T4;
type T5 = any;
var x5: any;
var x5: T5;
interface I6 { x : string }
type T6 = I6;
var x6: I6;
var x6: T6;
class C7 { x: boolean }
type T7 = C7;
var x7: C7;
var x7: T7;
type T8 = string | boolean;
var x8: string | boolean;
var x8: T8;
type T9 = () => string;
var x9: () => string;
var x9: T9;
type T10 = { x: number };
var x10: { x: number };
var x10: T10;
type T11 = { new(): boolean };
var x11: { new(): boolean };
var x11: T11;
interface I13 { x: string };
type T13 = I13;
var x13_1: I13;
var x13_2: T13
declare function foo13<T1 extends I13, T2 extends T13>(t1: T1, t2: T13): void;
foo13(x13_1, x13_2);
foo13(x13_2, x13_1);
type T14 = string;
var x14: T14;
declare function foo14_1(x: T14): void;
declare function foo14_2(x: "click"): void;
declare function foo14_2(x: T14): void;
type Meters = number
enum E { x = 10 }
declare function f15(a: string): boolean;
declare function f15(a: Meters): string;
f15(E.x).toLowerCase();
type StringAndBoolean = [string, boolean]
declare function f16(s: StringAndBoolean): string;
var x: [string, boolean];
f16(x);
var y: StringAndBoolean = ["1", false];
y[0].toLowerCase();
//// [typeAliases.js]
// Writing a reference to a type alias has exactly the same effect as writing the aliased type itself.
var x1;
var x1;
var x2;
var x2;
var x3;
var x3;
var x4;
var x4;
var x5;
var x5;
var x6;
var x6;
var C7 = (function () {
function C7() {
}
return C7;
})();
var x7;
var x7;
var x8;
var x8;
var x9;
var x9;
var x10;
var x10;
var x11;
var x11;
;
var x13_1;
var x13_2;
foo13(x13_1, x13_2);
foo13(x13_2, x13_1);
var x14;
var E;
(function (E) {
E[E["x"] = 10] = "x";
})(E || (E = {}));
f15(E.x).toLowerCase();
var x;
f16(x);
var y = ["1", false];
y[0].toLowerCase();
|
/**
* Sample React Native App
* https://github.com/facebook/react-native
*/
'use strict';
var React = require('react-native');
var {
AppRegistry,
StyleSheet,
Text,
View,
Navigator,
NavigatorIOS,
} = React;
var TimerMixin = require('react-timer-mixin');
var SplashScreen = require('./SplashScreen');
var MainScreen = require('./MainScreen');
var _navigator;
var Day08DrawerDemo = React.createClass({
mixins: [TimerMixin],
getInitialState: function() {
return {
splashed: false,
};
},
componentDidMount: function() {
this.setTimeout(
() => {
this.setState({splashed: true});
},
2000
);
},
RouteMapper: function(route, navigationOperations, onComponentRef) {
_navigator = navigationOperations;
// return (
// <View style={styles.container}>
// <MainScreen navigator={navigationOperations}/>
// </View>
// );
if (route.name === 'home') {
return (
<View style={styles.container}>
<MainScreen navigator={navigationOperations}/>
</View>
);
} else if (route.name === 'story') {
return (
<View style={styles.container}>
<StoryScreen
style={{flex: 1}}
navigator={navigationOperations}
story={route.story} />
</View>
);
}
},
render: function() {
if (this.state.splashed) {
var initialRoute = {name: 'home'};
return (
// <NavigatorIOS
// style={styles.container}
// initialRoute={{
// title: '首页',
// component: MainScreen,
// }}
// />
<Navigator
style={styles.container}
initialRoute={initialRoute}
configureScene={() => Navigator.SceneConfigs.FadeAndroid}
renderScene={this.RouteMapper}
/>
);
// return (
// <View style={styles.container}>
// <MainScreen />
// </View>
// );
} else {
return (
<SplashScreen />
);
}
}
});
const styles = StyleSheet.create({
container: {
flex: 1,
},
});
AppRegistry.registerComponent('Day08DrawerDemo', () => Day08DrawerDemo);
|
from epynet import Network
from nose.tools import assert_equal, assert_almost_equal
import pandas as pd
class TestNetwork(object):
@classmethod
def setup_class(self):
self.network = Network(inputfile="tests/testnetwork.inp")
self.network.solve()
@classmethod
def teadown(self):
self.network.ep.ENclose()
def test01_network(self):
# test0 node count
assert_equal(len(self.network.nodes),11)
# test0 link count
assert_equal(len(self.network.links),12)
# test0 reservoir count
assert_equal(len(self.network.reservoirs),1)
# test0 valve count
assert_equal(len(self.network.valves),1)
# test0 pump count
assert_equal(len(self.network.pumps),1)
# test0 tank count
assert_equal(len(self.network.tanks),1)
def test02_link(self):
# test0 the properties of a single link
link = self.network.links["11"]
# pipe index and uid
assert_equal(link.index,9)
assert_equal(link.uid,"11")
# from/to node
assert_equal(link.from_node.uid,"4")
assert_equal(link.to_node.uid,"9")
def test03_pipe(self):
# test0 the properties of a single pipe
pipe = self.network.links["11"]
# check type
assert_equal(pipe.link_type,"pipe")
assert_almost_equal(pipe.length,100,2)
assert_almost_equal(pipe.diameter,150,2)
assert_almost_equal(pipe.roughness,0.1,2)
assert_almost_equal(pipe.minorloss,0.1,2)
# flow
assert_almost_equal(pipe.flow,87.92,2)
# direction
assert_almost_equal(pipe.velocity,1.38,2)
# status
assert_equal(pipe.status,1)
# headloss
assert_almost_equal(pipe.headloss,1.29,2)
# upstream/downstream node
assert_equal(pipe.upstream_node.uid,"4")
assert_equal(pipe.downstream_node.uid,"9")
def test04_pump(self):
pump = self.network.pumps["2"]
# check type
assert_equal(pump.link_type,"pump")
assert_equal(pump.speed,1.0)
assert_almost_equal(pump.flow,109.67,2)
# change speed
pump.speed = 1.5
assert_equal(pump.speed,1.5)
# resolve network
self.network.solve()
assert_almost_equal(pump.flow,164.5,2)
# revert speed
pump.speed = 1.0
self.network.solve()
def test05_valve(self):
valve = self.network.valves["9"]
# check type
assert_equal(valve.link_type,"valve")
# check valve type
assert_equal(valve.valve_type,"PRV")
# valve settings
assert_equal(valve.setting,5)
assert_almost_equal(valve.downstream_node.pressure,5,2)
# change setting
valve.setting = 10
assert_equal(valve.setting,10)
self.network.solve()
assert_almost_equal(valve.downstream_node.pressure,10,2)
def test06_node(self):
node = self.network.nodes["4"]
# uid
assert_equal(node.uid,"4")
# coordinates
coordinates = node.coordinates
assert_almost_equal(coordinates[0],2103.02,2)
assert_almost_equal(coordinates[1],5747.69,2)
# links
assert_equal(len(node.links),3)
# up and downstream links
assert_equal(len(node.downstream_links),2)
assert_equal(len(node.upstream_links),1)
# inflow
assert_equal(round(node.inflow,2),109.67)
# outflow
assert_equal(round(node.outflow,2),round(node.inflow,2)-node.demand)
# elevation
assert_equal(node.elevation,5)
# head
assert_equal(round(node.head,2),25.13)
def test07_junction(self):
junction = self.network.junctions["4"]
assert_equal(round(junction.basedemand,2),1)
assert_equal(round(junction.demand,2),1)
def test08_tank(self):
tank = self.network.tanks["11"]
assert_equal(round(tank.diameter,2),50)
assert_equal(round(tank.initvolume,2),19634.95)
assert_equal(tank.minvolume,0)
assert_equal(tank.minlevel,0)
assert_equal(tank.maxlevel,20)
assert_equal(round(tank.volume,2),19634.95)
assert_equal(round(tank.maxvolume),2*round(tank.volume))
def test09_time(self):
junction = self.network.junctions["4"]
self.network.solve(3600)
assert_equal(round(junction.demand,2),2)
self.network.solve(7200)
assert_equal(round(junction.demand,2),3)
def test10_collections(self):
# collection attributes as pandas Series
assert_almost_equal(self.network.pipes.flow.mean(),46.78,2)
assert_almost_equal(self.network.pipes.diameter.max(),150,2)
assert_almost_equal(self.network.pipes.velocity.min(),0.105,2)
assert_equal(self.network.valves.setting.mean(),10)
assert_almost_equal(self.network.junctions.demand.mean(),2.33,2)
# filtering and slicing collections
assert_equal(len(self.network.pipes[self.network.pipes.velocity > 3]),3)
assert_equal(len(self.network.nodes[self.network.nodes.pressure < 20]),5)
#increase the size of all pipes
self.network.pipes.diameter += 500
assert_almost_equal(self.network.pipes.diameter.mean(),605,2)
self.network.pipes.diameter -= 500
self.network.solve()
# resize pipes, and recalculate velocity
self.network.pipes[self.network.pipes.velocity > 3].diameter += 100
self.network.solve()
assert_equal(len(self.network.pipes[self.network.pipes.velocity > 3]),0)
def test11_timeseries(self):
# run network
self.network.run()
# check return types
# should return Series
assert(isinstance(self.network.pipes["1"].velocity, pd.Series))
# should return Dataframe
assert(isinstance(self.network.pipes.velocity, pd.DataFrame))
# timeseries operations
# pipe 1 max velocity
assert_almost_equal(self.network.pipes["1"].velocity.mean(),1.66,2)
# all day mean velocity
assert_almost_equal(self.network.pipes.velocity.mean().mean(),1.14,2)
# test revert to steady state calculation
self.network.solve()
assert(isinstance(self.network.pipes["1"].velocity, float))
assert(isinstance(self.network.pipes.velocity, pd.Series))
|
const isCustomer = (state = true, { type }) => {
switch (type) {
case 'TOGGLE USER':
return !state;
default:
return state;
}
};
export default isCustomer;
|
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('vega-util'), require('vega-loader')) :
typeof define === 'function' && define.amd ? define(['exports', 'vega-util', 'vega-loader'], factory) :
(global = global || self, factory(global.vega = {}, global.vega, global.vega));
}(this, (function (exports, vegaUtil, vegaLoader) { 'use strict';
function UniqueList(idFunc) {
var $ = idFunc || vegaUtil.identity,
list = [],
ids = {};
list.add = function(_) {
var id = $(_);
if (!ids[id]) {
ids[id] = 1;
list.push(_);
}
return list;
};
list.remove = function(_) {
var id = $(_), idx;
if (ids[id]) {
ids[id] = 0;
if ((idx = list.indexOf(_)) >= 0) {
list.splice(idx, 1);
}
}
return list;
};
return list;
}
/**
* Invoke and await a potentially async callback function. If
* an error occurs, trap it and route to Dataflow.error.
* @param {Dataflow} df - The dataflow instance
* @param {function} callback - A callback function to invoke
* and then await. The dataflow will be passed as the single
* argument to the function.
*/
async function asyncCallback(df, callback) {
try { await callback(df); } catch (err) { df.error(err); }
}
var TUPLE_ID_KEY = Symbol('vega_id'),
TUPLE_ID = 1;
/**
* Checks if an input value is a registered tuple.
* @param {*} t - The value to check.
* @return {boolean} True if the input is a tuple, false otherwise.
*/
function isTuple(t) {
return !!(t && tupleid(t));
}
/**
* Returns the id of a tuple.
* @param {object} t - The input tuple.
* @return {*} the tuple id.
*/
function tupleid(t) {
return t[TUPLE_ID_KEY];
}
/**
* Sets the id of a tuple.
* @param {object} t - The input tuple.
* @param {*} id - The id value to set.
* @return {object} the input tuple.
*/
function setid(t, id) {
t[TUPLE_ID_KEY] = id;
return t;
}
/**
* Ingest an object or value as a data tuple.
* If the input value is an object, an id field will be added to it. For
* efficiency, the input object is modified directly. A copy is not made.
* If the input value is a literal, it will be wrapped in a new object
* instance, with the value accessible as the 'data' property.
* @param datum - The value to ingest.
* @return {object} The ingested data tuple.
*/
function ingest(datum) {
var t = (datum === Object(datum)) ? datum : {data: datum};
return tupleid(t) ? t : setid(t, TUPLE_ID++);
}
/**
* Given a source tuple, return a derived copy.
* @param {object} t - The source tuple.
* @return {object} The derived tuple.
*/
function derive(t) {
return rederive(t, ingest({}));
}
/**
* Rederive a derived tuple by copying values from the source tuple.
* @param {object} t - The source tuple.
* @param {object} d - The derived tuple.
* @return {object} The derived tuple.
*/
function rederive(t, d) {
for (var k in t) d[k] = t[k];
return d;
}
/**
* Replace an existing tuple with a new tuple.
* @param {object} t - The existing data tuple.
* @param {object} d - The new tuple that replaces the old.
* @return {object} The new tuple.
*/
function replace(t, d) {
return setid(d, tupleid(t));
}
/**
* Generate an augmented comparator function that provides stable
* sorting by tuple id when the given comparator produces ties.
* @param {function} cmp - The comparator to augment.
* @param {function} [f] - Optional tuple accessor function.
* @return {function} An augmented comparator function.
*/
function stableCompare(cmp, f) {
return !cmp ? null
: f ? (a, b) => cmp(a, b) || (tupleid(f(a)) - tupleid(f(b)))
: (a, b) => cmp(a, b) || (tupleid(a) - tupleid(b));
}
function isChangeSet(v) {
return v && v.constructor === changeset;
}
function changeset() {
var add = [], // insert tuples
rem = [], // remove tuples
mod = [], // modify tuples
remp = [], // remove by predicate
modp = [], // modify by predicate
reflow = false;
return {
constructor: changeset,
insert: function(t) {
var d = vegaUtil.array(t), i = 0, n = d.length;
for (; i<n; ++i) add.push(d[i]);
return this;
},
remove: function(t) {
var a = vegaUtil.isFunction(t) ? remp : rem,
d = vegaUtil.array(t), i = 0, n = d.length;
for (; i<n; ++i) a.push(d[i]);
return this;
},
modify: function(t, field, value) {
var m = {field: field, value: vegaUtil.constant(value)};
if (vegaUtil.isFunction(t)) {
m.filter = t;
modp.push(m);
} else {
m.tuple = t;
mod.push(m);
}
return this;
},
encode: function(t, set) {
if (vegaUtil.isFunction(t)) modp.push({filter: t, field: set});
else mod.push({tuple: t, field: set});
return this;
},
reflow: function() {
reflow = true;
return this;
},
pulse: function(pulse, tuples) {
var cur = {}, out = {}, i, n, m, f, t, id;
// build lookup table of current tuples
for (i=0, n=tuples.length; i<n; ++i) {
cur[tupleid(tuples[i])] = 1;
}
// process individual tuples to remove
for (i=0, n=rem.length; i<n; ++i) {
t = rem[i];
cur[tupleid(t)] = -1;
}
// process predicate-based removals
for (i=0, n=remp.length; i<n; ++i) {
f = remp[i];
tuples.forEach(function(t) {
if (f(t)) cur[tupleid(t)] = -1;
});
}
// process all add tuples
for (i=0, n=add.length; i<n; ++i) {
t = add[i];
id = tupleid(t);
if (cur[id]) {
// tuple already resides in dataset
// if flagged for both add and remove, cancel
cur[id] = 1;
} else {
// tuple does not reside in dataset, add
pulse.add.push(ingest(add[i]));
}
}
// populate pulse rem list
for (i=0, n=tuples.length; i<n; ++i) {
t = tuples[i];
if (cur[tupleid(t)] < 0) pulse.rem.push(t);
}
// modify helper method
function modify(t, f, v) {
if (v) {
t[f] = v(t);
} else {
pulse.encode = f;
}
if (!reflow) out[tupleid(t)] = t;
}
// process individual tuples to modify
for (i=0, n=mod.length; i<n; ++i) {
m = mod[i];
t = m.tuple;
f = m.field;
id = cur[tupleid(t)];
if (id > 0) {
modify(t, f, m.value);
pulse.modifies(f);
}
}
// process predicate-based modifications
for (i=0, n=modp.length; i<n; ++i) {
m = modp[i];
f = m.filter;
tuples.forEach(function(t) {
if (f(t) && cur[tupleid(t)] > 0) {
modify(t, m.field, m.value);
}
});
pulse.modifies(m.field);
}
// upon reflow request, populate mod with all non-removed tuples
// otherwise, populate mod with modified tuples only
if (reflow) {
pulse.mod = rem.length || remp.length
? tuples.filter(function(t) { return cur[tupleid(t)] > 0; })
: tuples.slice();
} else {
for (id in out) pulse.mod.push(out[id]);
}
return pulse;
}
};
}
var CACHE = '_:mod:_';
/**
* Hash that tracks modifications to assigned values.
* Callers *must* use the set method to update values.
*/
function Parameters() {
Object.defineProperty(this, CACHE, {writable: true, value: {}});
}
var prototype = Parameters.prototype;
/**
* Set a parameter value. If the parameter value changes, the parameter
* will be recorded as modified.
* @param {string} name - The parameter name.
* @param {number} index - The index into an array-value parameter. Ignored if
* the argument is undefined, null or less than zero.
* @param {*} value - The parameter value to set.
* @param {boolean} [force=false] - If true, records the parameter as modified
* even if the value is unchanged.
* @return {Parameters} - This parameter object.
*/
prototype.set = function(name, index, value, force) {
var o = this,
v = o[name],
mod = o[CACHE];
if (index != null && index >= 0) {
if (v[index] !== value || force) {
v[index] = value;
mod[index + ':' + name] = -1;
mod[name] = -1;
}
} else if (v !== value || force) {
o[name] = value;
mod[name] = vegaUtil.isArray(value) ? 1 + value.length : -1;
}
return o;
};
/**
* Tests if one or more parameters has been modified. If invoked with no
* arguments, returns true if any parameter value has changed. If the first
* argument is array, returns trues if any parameter name in the array has
* changed. Otherwise, tests if the given name and optional array index has
* changed.
* @param {string} name - The parameter name to test.
* @param {number} [index=undefined] - The parameter array index to test.
* @return {boolean} - Returns true if a queried parameter was modified.
*/
prototype.modified = function(name, index) {
var mod = this[CACHE], k;
if (!arguments.length) {
for (k in mod) { if (mod[k]) return true; }
return false;
} else if (vegaUtil.isArray(name)) {
for (k=0; k<name.length; ++k) {
if (mod[name[k]]) return true;
}
return false;
}
return (index != null && index >= 0)
? (index + 1 < mod[name] || !!mod[index + ':' + name])
: !!mod[name];
};
/**
* Clears the modification records. After calling this method,
* all parameters are considered unmodified.
*/
prototype.clear = function() {
this[CACHE] = {};
return this;
};
var OP_ID = 0;
var PULSE = 'pulse';
var NO_PARAMS = new Parameters();
// Boolean Flags
var SKIP = 1,
MODIFIED = 2;
/**
* An Operator is a processing node in a dataflow graph.
* Each operator stores a value and an optional value update function.
* Operators can accept a hash of named parameters. Parameter values can
* either be direct (JavaScript literals, arrays, objects) or indirect
* (other operators whose values will be pulled dynamically). Operators
* included as parameters will have this operator added as a dependency.
* @constructor
* @param {*} [init] - The initial value for this operator.
* @param {function(object, Pulse)} [update] - An update function. Upon
* evaluation of this operator, the update function will be invoked and the
* return value will be used as the new value of this operator.
* @param {object} [params] - The parameters for this operator.
* @param {boolean} [react=true] - Flag indicating if this operator should
* listen for changes to upstream operators included as parameters.
* @see parameters
*/
function Operator(init, update, params, react) {
this.id = ++OP_ID;
this.value = init;
this.stamp = -1;
this.rank = -1;
this.qrank = -1;
this.flags = 0;
if (update) {
this._update = update;
}
if (params) this.parameters(params, react);
}
var prototype$1 = Operator.prototype;
/**
* Returns a list of target operators dependent on this operator.
* If this list does not exist, it is created and then returned.
* @return {UniqueList}
*/
prototype$1.targets = function() {
return this._targets || (this._targets = UniqueList(vegaUtil.id));
};
/**
* Sets the value of this operator.
* @param {*} value - the value to set.
* @return {Number} Returns 1 if the operator value has changed
* according to strict equality, returns 0 otherwise.
*/
prototype$1.set = function(value) {
if (this.value !== value) {
this.value = value;
return 1;
} else {
return 0;
}
};
function flag(bit) {
return function(state) {
var f = this.flags;
if (arguments.length === 0) return !!(f & bit);
this.flags = state ? (f | bit) : (f & ~bit);
return this;
};
}
/**
* Indicates that operator evaluation should be skipped on the next pulse.
* This operator will still propagate incoming pulses, but its update function
* will not be invoked. The skip flag is reset after every pulse, so calling
* this method will affect processing of the next pulse only.
*/
prototype$1.skip = flag(SKIP);
/**
* Indicates that this operator's value has been modified on its most recent
* pulse. Normally modification is checked via strict equality; however, in
* some cases it is more efficient to update the internal state of an object.
* In those cases, the modified flag can be used to trigger propagation. Once
* set, the modification flag persists across pulses until unset. The flag can
* be used with the last timestamp to test if a modification is recent.
*/
prototype$1.modified = flag(MODIFIED);
/**
* Sets the parameters for this operator. The parameter values are analyzed for
* operator instances. If found, this operator will be added as a dependency
* of the parameterizing operator. Operator values are dynamically marshalled
* from each operator parameter prior to evaluation. If a parameter value is
* an array, the array will also be searched for Operator instances. However,
* the search does not recurse into sub-arrays or object properties.
* @param {object} params - A hash of operator parameters.
* @param {boolean} [react=true] - A flag indicating if this operator should
* automatically update (react) when parameter values change. In other words,
* this flag determines if the operator registers itself as a listener on
* any upstream operators included in the parameters.
* @param {boolean} [initonly=false] - A flag indicating if this operator
* should calculate an update only upon its initiatal evaluation, then
* deregister dependencies and suppress all future update invocations.
* @return {Operator[]} - An array of upstream dependencies.
*/
prototype$1.parameters = function(params, react, initonly) {
react = react !== false;
var self = this,
argval = (self._argval = self._argval || new Parameters()),
argops = (self._argops = self._argops || []),
deps = [],
name, value, n, i;
function add(name, index, value) {
if (value instanceof Operator) {
if (value !== self) {
if (react) value.targets().add(self);
deps.push(value);
}
argops.push({op:value, name:name, index:index});
} else {
argval.set(name, index, value);
}
}
for (name in params) {
value = params[name];
if (name === PULSE) {
vegaUtil.array(value).forEach(function(op) {
if (!(op instanceof Operator)) {
vegaUtil.error('Pulse parameters must be operator instances.');
} else if (op !== self) {
op.targets().add(self);
deps.push(op);
}
});
self.source = value;
} else if (vegaUtil.isArray(value)) {
argval.set(name, -1, Array(n = value.length));
for (i=0; i<n; ++i) add(name, i, value[i]);
} else {
add(name, -1, value);
}
}
this.marshall().clear(); // initialize values
if (initonly) argops.initonly = true;
return deps;
};
/**
* Internal method for marshalling parameter values.
* Visits each operator dependency to pull the latest value.
* @return {Parameters} A Parameters object to pass to the update function.
*/
prototype$1.marshall = function(stamp) {
var argval = this._argval || NO_PARAMS,
argops = this._argops, item, i, n, op, mod;
if (argops) {
for (i=0, n=argops.length; i<n; ++i) {
item = argops[i];
op = item.op;
mod = op.modified() && op.stamp === stamp;
argval.set(item.name, item.index, op.value, mod);
}
if (argops.initonly) {
for (i=0; i<n; ++i) {
item = argops[i];
item.op.targets().remove(this);
}
this._argops = null;
this._update = null;
}
}
return argval;
};
/**
* Delegate method to perform operator processing.
* Subclasses can override this method to perform custom processing.
* By default, it marshalls parameters and calls the update function
* if that function is defined. If the update function does not
* change the operator value then StopPropagation is returned.
* If no update function is defined, this method does nothing.
* @param {Pulse} pulse - the current dataflow pulse.
* @return The output pulse or StopPropagation. A falsy return value
* (including undefined) will let the input pulse pass through.
*/
prototype$1.evaluate = function(pulse) {
var update = this._update;
if (update) {
var params = this.marshall(pulse.stamp),
v = update.call(this, params, pulse);
params.clear();
if (v !== this.value) {
this.value = v;
} else if (!this.modified()) {
return pulse.StopPropagation;
}
}
};
/**
* Run this operator for the current pulse. If this operator has already
* been run at (or after) the pulse timestamp, returns StopPropagation.
* Internally, this method calls {@link evaluate} to perform processing.
* If {@link evaluate} returns a falsy value, the input pulse is returned.
* This method should NOT be overridden, instead overrride {@link evaluate}.
* @param {Pulse} pulse - the current dataflow pulse.
* @return the output pulse for this operator (or StopPropagation)
*/
prototype$1.run = function(pulse) {
if (pulse.stamp < this.stamp) return pulse.StopPropagation;
var rv;
if (this.skip()) {
this.skip(false);
rv = 0;
} else {
rv = this.evaluate(pulse);
}
return (this.pulse = rv || pulse);
};
/**
* Add an operator to the dataflow graph. This function accepts a
* variety of input argument types. The basic signature supports an
* initial value, update function and parameters. If the first parameter
* is an Operator instance, it will be added directly. If it is a
* constructor for an Operator subclass, a new instance will be instantiated.
* Otherwise, if the first parameter is a function instance, it will be used
* as the update function and a null initial value is assumed.
* @param {*} init - One of: the operator to add, the initial value of
* the operator, an operator class to instantiate, or an update function.
* @param {function} [update] - The operator update function.
* @param {object} [params] - The operator parameters.
* @param {boolean} [react=true] - Flag indicating if this operator should
* listen for changes to upstream operators included as parameters.
* @return {Operator} - The added operator.
*/
function add(init, update, params, react) {
var shift = 1,
op;
if (init instanceof Operator) {
op = init;
} else if (init && init.prototype instanceof Operator) {
op = new init();
} else if (vegaUtil.isFunction(init)) {
op = new Operator(null, init);
} else {
shift = 0;
op = new Operator(init, update);
}
this.rank(op);
if (shift) {
react = params;
params = update;
}
if (params) this.connect(op, op.parameters(params, react));
this.touch(op);
return op;
}
/**
* Connect a target operator as a dependent of source operators.
* If necessary, this method will rerank the target operator and its
* dependents to ensure propagation proceeds in a topologically sorted order.
* @param {Operator} target - The target operator.
* @param {Array<Operator>} - The source operators that should propagate
* to the target operator.
*/
function connect(target, sources) {
var targetRank = target.rank, i, n;
for (i=0, n=sources.length; i<n; ++i) {
if (targetRank < sources[i].rank) {
this.rerank(target);
return;
}
}
}
var STREAM_ID = 0;
/**
* Models an event stream.
* @constructor
* @param {function(Object, number): boolean} [filter] - Filter predicate.
* Events pass through when truthy, events are suppressed when falsy.
* @param {function(Object): *} [apply] - Applied to input events to produce
* new event values.
* @param {function(Object)} [receive] - Event callback function to invoke
* upon receipt of a new event. Use to override standard event processing.
*/
function EventStream(filter, apply, receive) {
this.id = ++STREAM_ID;
this.value = null;
if (receive) this.receive = receive;
if (filter) this._filter = filter;
if (apply) this._apply = apply;
}
/**
* Creates a new event stream instance with the provided
* (optional) filter, apply and receive functions.
* @param {function(Object, number): boolean} [filter] - Filter predicate.
* Events pass through when truthy, events are suppressed when falsy.
* @param {function(Object): *} [apply] - Applied to input events to produce
* new event values.
* @see EventStream
*/
function stream(filter, apply, receive) {
return new EventStream(filter, apply, receive);
}
var prototype$2 = EventStream.prototype;
prototype$2._filter = vegaUtil.truthy;
prototype$2._apply = vegaUtil.identity;
prototype$2.targets = function() {
return this._targets || (this._targets = UniqueList(vegaUtil.id));
};
prototype$2.consume = function(_) {
if (!arguments.length) return !!this._consume;
this._consume = !!_;
return this;
};
prototype$2.receive = function(evt) {
if (this._filter(evt)) {
var val = (this.value = this._apply(evt)),
trg = this._targets,
n = trg ? trg.length : 0,
i = 0;
for (; i<n; ++i) trg[i].receive(val);
if (this._consume) {
evt.preventDefault();
evt.stopPropagation();
}
}
};
prototype$2.filter = function(filter) {
var s = stream(filter);
this.targets().add(s);
return s;
};
prototype$2.apply = function(apply) {
var s = stream(null, apply);
this.targets().add(s);
return s;
};
prototype$2.merge = function() {
var s = stream();
this.targets().add(s);
for (var i=0, n=arguments.length; i<n; ++i) {
arguments[i].targets().add(s);
}
return s;
};
prototype$2.throttle = function(pause) {
var t = -1;
return this.filter(function() {
var now = Date.now();
if ((now - t) > pause) {
t = now;
return 1;
} else {
return 0;
}
});
};
prototype$2.debounce = function(delay) {
var s = stream();
this.targets().add(stream(null, null,
vegaUtil.debounce(delay, function(e) {
var df = e.dataflow;
s.receive(e);
if (df && df.run) df.run();
})
));
return s;
};
prototype$2.between = function(a, b) {
var active = false;
a.targets().add(stream(null, null, function() { active = true; }));
b.targets().add(stream(null, null, function() { active = false; }));
return this.filter(function() { return active; });
};
/**
* Create a new event stream from an event source.
* @param {object} source - The event source to monitor. The input must
* support the addEventListener method.
* @param {string} type - The event type.
* @param {function(object): boolean} [filter] - Event filter function.
* @param {function(object): *} [apply] - Event application function.
* If provided, this function will be invoked and the result will be
* used as the downstream event value.
* @return {EventStream}
*/
function events(source, type, filter, apply) {
var df = this,
s = stream(filter, apply),
send = function(e) {
e.dataflow = df;
try {
s.receive(e);
} catch (error) {
df.error(error);
} finally {
df.run();
}
},
sources;
if (typeof source === 'string' && typeof document !== 'undefined') {
sources = document.querySelectorAll(source);
} else {
sources = vegaUtil.array(source);
}
for (var i=0, n=sources.length; i<n; ++i) {
sources[i].addEventListener(type, send);
}
return s;
}
const parse = vegaLoader.read;
/**
* Ingests new data into the dataflow. First parses the data using the
* vega-loader read method, then pulses a changeset to the target operator.
* @param {Operator} target - The Operator to target with ingested data,
* typically a Collect transform instance.
* @param {*} data - The input data, prior to parsing. For JSON this may
* be a string or an object. For CSV, TSV, etc should be a string.
* @param {object} format - The data format description for parsing
* loaded data. This object is passed to the vega-loader read method.
* @returns {Dataflow}
*/
function ingest$1(target, data, format) {
return this.pulse(target, this.changeset().insert(parse(data, format)));
}
/**
* Request data from an external source, parse it, and return a Promise.
* @param {string} url - The URL from which to load the data. This string
* is passed to the vega-loader load method.
* @param {object} [format] - The data format description for parsing
* loaded data. This object is passed to the vega-loader read method.
* @return {Promise} A Promise that resolves upon completion of the request.
* The resolved object contains the following properties:
* - data: an array of parsed data (or null upon error)
* - status: a code for success (0), load fail (-1), or parse fail (-2)
*/
async function request(url, format) {
const df = this;
let status = 0, data;
try {
data = await df.loader().load(url, {
context: 'dataflow',
response: vegaLoader.responseType(format && format.type)
});
try {
data = parse(data, format);
} catch (err) {
status = -2;
df.warn('Data ingestion failed', url, err);
}
} catch (err) {
status = -1;
df.warn('Loading failed', url, err);
}
return {data, status};
}
async function preload(target, url, format) {
const df = this,
pending = df._pending || loadPending(df);
pending.requests += 1;
const res = await df.request(url, format);
df.pulse(target, df.changeset().remove(vegaUtil.truthy).insert(res.data || []));
pending.done();
return res;
}
function loadPending(df) {
var pending = new Promise(function(a) { accept = a; }),
accept;
pending.requests = 0;
pending.done = function() {
if (--pending.requests === 0) {
df._pending = null;
accept(df);
}
};
return (df._pending = pending);
}
var SKIP$1 = {skip: true};
/**
* Perform operator updates in response to events. Applies an
* update function to compute a new operator value. If the update function
* returns a {@link ChangeSet}, the operator will be pulsed with those tuple
* changes. Otherwise, the operator value will be updated to the return value.
* @param {EventStream|Operator} source - The event source to react to.
* This argument can be either an EventStream or an Operator.
* @param {Operator|function(object):Operator} target - The operator to update.
* This argument can either be an Operator instance or (if the source
* argument is an EventStream), a function that accepts an event object as
* input and returns an Operator to target.
* @param {function(Parameters,Event): *} [update] - Optional update function
* to compute the new operator value, or a literal value to set. Update
* functions expect to receive a parameter object and event as arguments.
* This function can either return a new operator value or (if the source
* argument is an EventStream) a {@link ChangeSet} instance to pulse
* the target operator with tuple changes.
* @param {object} [params] - The update function parameters.
* @param {object} [options] - Additional options hash. If not overridden,
* updated operators will be skipped by default.
* @param {boolean} [options.skip] - If true, the operator will
* be skipped: it will not be evaluated, but its dependents will be.
* @param {boolean} [options.force] - If true, the operator will
* be re-evaluated even if its value has not changed.
* @return {Dataflow}
*/
function on(source, target, update, params, options) {
var fn = source instanceof Operator ? onOperator : onStream;
fn(this, source, target, update, params, options);
return this;
}
function onStream(df, stream, target, update, params, options) {
var opt = vegaUtil.extend({}, options, SKIP$1), func, op;
if (!vegaUtil.isFunction(target)) target = vegaUtil.constant(target);
if (update === undefined) {
func = e => df.touch(target(e));
} else if (vegaUtil.isFunction(update)) {
op = new Operator(null, update, params, false);
func = e => {
op.evaluate(e);
const t = target(e), v = op.value;
isChangeSet(v) ? df.pulse(t, v, options) : df.update(t, v, opt);
};
} else {
func = e => df.update(target(e), update, opt);
}
stream.apply(func);
}
function onOperator(df, source, target, update, params, options) {
if (update === undefined) {
source.targets().add(target);
} else {
const opt = options || {},
op = new Operator(null, updater(target, update), params, false);
op.modified(opt.force);
op.rank = source.rank; // immediately follow source
source.targets().add(op); // add dependency
if (target) {
op.skip(true); // skip first invocation
op.value = target.value; // initialize value
op.targets().add(target); // chain dependencies
df.connect(target, [op]); // rerank as needed, #1672
}
}
}
function updater(target, update) {
update = vegaUtil.isFunction(update) ? update : vegaUtil.constant(update);
return target
? function(_, pulse) {
const value = update(_, pulse);
if (!target.skip()) {
target.skip(value !== this.value).value = value;
}
return value;
}
: update;
}
/**
* Assigns a rank to an operator. Ranks are assigned in increasing order
* by incrementing an internal rank counter.
* @param {Operator} op - The operator to assign a rank.
*/
function rank(op) {
op.rank = ++this._rank;
}
/**
* Re-ranks an operator and all downstream target dependencies. This
* is necessary when upstream dependencies of higher rank are added to
* a target operator.
* @param {Operator} op - The operator to re-rank.
*/
function rerank(op) {
var queue = [op],
cur, list, i;
while (queue.length) {
this.rank(cur = queue.pop());
if (list = cur._targets) {
for (i=list.length; --i >= 0;) {
queue.push(cur = list[i]);
if (cur === op) vegaUtil.error('Cycle detected in dataflow graph.');
}
}
}
}
/**
* Sentinel value indicating pulse propagation should stop.
*/
var StopPropagation = {};
// Pulse visit type flags
var ADD = (1 << 0),
REM = (1 << 1),
MOD = (1 << 2),
ADD_REM = ADD | REM,
ADD_MOD = ADD | MOD,
ALL = ADD | REM | MOD,
REFLOW = (1 << 3),
SOURCE = (1 << 4),
NO_SOURCE = (1 << 5),
NO_FIELDS = (1 << 6);
/**
* A Pulse enables inter-operator communication during a run of the
* dataflow graph. In addition to the current timestamp, a pulse may also
* contain a change-set of added, removed or modified data tuples, as well as
* a pointer to a full backing data source. Tuple change sets may not
* be fully materialized; for example, to prevent needless array creation
* a change set may include larger arrays and corresponding filter functions.
* The pulse provides a {@link visit} method to enable proper and efficient
* iteration over requested data tuples.
*
* In addition, each pulse can track modification flags for data tuple fields.
* Responsible transform operators should call the {@link modifies} method to
* indicate changes to data fields. The {@link modified} method enables
* querying of this modification state.
*
* @constructor
* @param {Dataflow} dataflow - The backing dataflow instance.
* @param {number} stamp - The current propagation timestamp.
* @param {string} [encode] - An optional encoding set name, which is then
* accessible as Pulse.encode. Operators can respond to (or ignore) this
* setting as appropriate. This parameter can be used in conjunction with
* the Encode transform in the vega-encode module.
*/
function Pulse(dataflow, stamp, encode) {
this.dataflow = dataflow;
this.stamp = stamp == null ? -1 : stamp;
this.add = [];
this.rem = [];
this.mod = [];
this.fields = null;
this.encode = encode || null;
}
var prototype$3 = Pulse.prototype;
/**
* Sentinel value indicating pulse propagation should stop.
*/
prototype$3.StopPropagation = StopPropagation;
/**
* Boolean flag indicating ADD (added) tuples.
*/
prototype$3.ADD = ADD;
/**
* Boolean flag indicating REM (removed) tuples.
*/
prototype$3.REM = REM;
/**
* Boolean flag indicating MOD (modified) tuples.
*/
prototype$3.MOD = MOD;
/**
* Boolean flag indicating ADD (added) and REM (removed) tuples.
*/
prototype$3.ADD_REM = ADD_REM;
/**
* Boolean flag indicating ADD (added) and MOD (modified) tuples.
*/
prototype$3.ADD_MOD = ADD_MOD;
/**
* Boolean flag indicating ADD, REM and MOD tuples.
*/
prototype$3.ALL = ALL;
/**
* Boolean flag indicating all tuples in a data source
* except for the ADD, REM and MOD tuples.
*/
prototype$3.REFLOW = REFLOW;
/**
* Boolean flag indicating a 'pass-through' to a
* backing data source, ignoring ADD, REM and MOD tuples.
*/
prototype$3.SOURCE = SOURCE;
/**
* Boolean flag indicating that source data should be
* suppressed when creating a forked pulse.
*/
prototype$3.NO_SOURCE = NO_SOURCE;
/**
* Boolean flag indicating that field modifications should be
* suppressed when creating a forked pulse.
*/
prototype$3.NO_FIELDS = NO_FIELDS;
/**
* Creates a new pulse based on the values of this pulse.
* The dataflow, time stamp and field modification values are copied over.
* By default, new empty ADD, REM and MOD arrays are created.
* @param {number} flags - Integer of boolean flags indicating which (if any)
* tuple arrays should be copied to the new pulse. The supported flag values
* are ADD, REM and MOD. Array references are copied directly: new array
* instances are not created.
* @return {Pulse} - The forked pulse instance.
* @see init
*/
prototype$3.fork = function(flags) {
return new Pulse(this.dataflow).init(this, flags);
};
/**
* Creates a copy of this pulse with new materialized array
* instances for the ADD, REM, MOD, and SOURCE arrays.
* The dataflow, time stamp and field modification values are copied over.
* @return {Pulse} - The cloned pulse instance.
* @see init
*/
prototype$3.clone = function() {
var p = this.fork(ALL);
p.add = p.add.slice();
p.rem = p.rem.slice();
p.mod = p.mod.slice();
if (p.source) p.source = p.source.slice();
return p.materialize(ALL | SOURCE);
};
/**
* Returns a pulse that adds all tuples from a backing source. This is
* useful for cases where operators are added to a dataflow after an
* upstream data pipeline has already been processed, ensuring that
* new operators can observe all tuples within a stream.
* @return {Pulse} - A pulse instance with all source tuples included
* in the add array. If the current pulse already has all source
* tuples in its add array, it is returned directly. If the current
* pulse does not have a backing source, it is returned directly.
*/
prototype$3.addAll = function() {
var p = this;
if (!this.source || this.source.length === this.add.length) {
return p;
} else {
p = new Pulse(this.dataflow).init(this);
p.add = p.source;
return p;
}
};
/**
* Initialize this pulse based on the values of another pulse. This method
* is used internally by {@link fork} to initialize a new forked tuple.
* The dataflow, time stamp and field modification values are copied over.
* By default, new empty ADD, REM and MOD arrays are created.
* @param {Pulse} src - The source pulse to copy from.
* @param {number} flags - Integer of boolean flags indicating which (if any)
* tuple arrays should be copied to the new pulse. The supported flag values
* are ADD, REM and MOD. Array references are copied directly: new array
* instances are not created. By default, source data arrays are copied
* to the new pulse. Use the NO_SOURCE flag to enforce a null source.
* @return {Pulse} - Returns this Pulse instance.
*/
prototype$3.init = function(src, flags) {
var p = this;
p.stamp = src.stamp;
p.encode = src.encode;
if (src.fields && !(flags & NO_FIELDS)) {
p.fields = src.fields;
}
if (flags & ADD) {
p.addF = src.addF;
p.add = src.add;
} else {
p.addF = null;
p.add = [];
}
if (flags & REM) {
p.remF = src.remF;
p.rem = src.rem;
} else {
p.remF = null;
p.rem = [];
}
if (flags & MOD) {
p.modF = src.modF;
p.mod = src.mod;
} else {
p.modF = null;
p.mod = [];
}
if (flags & NO_SOURCE) {
p.srcF = null;
p.source = null;
} else {
p.srcF = src.srcF;
p.source = src.source;
}
return p;
};
/**
* Schedules a function to run after pulse propagation completes.
* @param {function} func - The function to run.
*/
prototype$3.runAfter = function(func) {
this.dataflow.runAfter(func);
};
/**
* Indicates if tuples have been added, removed or modified.
* @param {number} [flags] - The tuple types (ADD, REM or MOD) to query.
* Defaults to ALL, returning true if any tuple type has changed.
* @return {boolean} - Returns true if one or more queried tuple types have
* changed, false otherwise.
*/
prototype$3.changed = function(flags) {
var f = flags || ALL;
return ((f & ADD) && this.add.length)
|| ((f & REM) && this.rem.length)
|| ((f & MOD) && this.mod.length);
};
/**
* Forces a "reflow" of tuple values, such that all tuples in the backing
* source are added to the MOD set, unless already present in the ADD set.
* @param {boolean} [fork=false] - If true, returns a forked copy of this
* pulse, and invokes reflow on that derived pulse.
* @return {Pulse} - The reflowed pulse instance.
*/
prototype$3.reflow = function(fork) {
if (fork) return this.fork(ALL).reflow();
var len = this.add.length,
src = this.source && this.source.length;
if (src && src !== len) {
this.mod = this.source;
if (len) this.filter(MOD, filter(this, ADD));
}
return this;
};
/**
* Marks one or more data field names as modified to assist dependency
* tracking and incremental processing by transform operators.
* @param {string|Array<string>} _ - The field(s) to mark as modified.
* @return {Pulse} - This pulse instance.
*/
prototype$3.modifies = function(_) {
var hash = this.fields || (this.fields = {});
if (vegaUtil.isArray(_)) {
_.forEach(f => hash[f] = true);
} else {
hash[_] = true;
}
return this;
};
/**
* Checks if one or more data fields have been modified during this pulse
* propagation timestamp.
* @param {string|Array<string>} _ - The field(s) to check for modified.
* @param {boolean} nomod - If true, will check the modified flag even if
* no mod tuples exist. If false (default), mod tuples must be present.
* @return {boolean} - Returns true if any of the provided fields has been
* marked as modified, false otherwise.
*/
prototype$3.modified = function(_, nomod) {
var fields = this.fields;
return !((nomod || this.mod.length) && fields) ? false
: !arguments.length ? !!fields
: vegaUtil.isArray(_) ? _.some(function(f) { return fields[f]; })
: fields[_];
};
/**
* Adds a filter function to one more tuple sets. Filters are applied to
* backing tuple arrays, to determine the actual set of tuples considered
* added, removed or modified. They can be used to delay materialization of
* a tuple set in order to avoid expensive array copies. In addition, the
* filter functions can serve as value transformers: unlike standard predicate
* function (which return boolean values), Pulse filters should return the
* actual tuple value to process. If a tuple set is already filtered, the
* new filter function will be appended into a conjuntive ('and') query.
* @param {number} flags - Flags indicating the tuple set(s) to filter.
* @param {function(*):object} filter - Filter function that will be applied
* to the tuple set array, and should return a data tuple if the value
* should be included in the tuple set, and falsy (or null) otherwise.
* @return {Pulse} - Returns this pulse instance.
*/
prototype$3.filter = function(flags, filter) {
var p = this;
if (flags & ADD) p.addF = addFilter(p.addF, filter);
if (flags & REM) p.remF = addFilter(p.remF, filter);
if (flags & MOD) p.modF = addFilter(p.modF, filter);
if (flags & SOURCE) p.srcF = addFilter(p.srcF, filter);
return p;
};
function addFilter(a, b) {
return a ? function(t,i) { return a(t,i) && b(t,i); } : b;
}
/**
* Materialize one or more tuple sets in this pulse. If the tuple set(s) have
* a registered filter function, it will be applied and the tuple set(s) will
* be replaced with materialized tuple arrays.
* @param {number} flags - Flags indicating the tuple set(s) to materialize.
* @return {Pulse} - Returns this pulse instance.
*/
prototype$3.materialize = function(flags) {
flags = flags || ALL;
var p = this;
if ((flags & ADD) && p.addF) {
p.add = materialize(p.add, p.addF);
p.addF = null;
}
if ((flags & REM) && p.remF) {
p.rem = materialize(p.rem, p.remF);
p.remF = null;
}
if ((flags & MOD) && p.modF) {
p.mod = materialize(p.mod, p.modF);
p.modF = null;
}
if ((flags & SOURCE) && p.srcF) {
p.source = p.source.filter(p.srcF);
p.srcF = null;
}
return p;
};
function materialize(data, filter) {
var out = [];
vegaUtil.visitArray(data, filter, function(_) { out.push(_); });
return out;
}
function filter(pulse, flags) {
var map = {};
pulse.visit(flags, function(t) { map[tupleid(t)] = 1; });
return function(t) { return map[tupleid(t)] ? null : t; };
}
/**
* Visit one or more tuple sets in this pulse.
* @param {number} flags - Flags indicating the tuple set(s) to visit.
* Legal values are ADD, REM, MOD and SOURCE (if a backing data source
* has been set).
* @param {function(object):*} - Visitor function invoked per-tuple.
* @return {Pulse} - Returns this pulse instance.
*/
prototype$3.visit = function(flags, visitor) {
var p = this, v = visitor, src, sum;
if (flags & SOURCE) {
vegaUtil.visitArray(p.source, p.srcF, v);
return p;
}
if (flags & ADD) vegaUtil.visitArray(p.add, p.addF, v);
if (flags & REM) vegaUtil.visitArray(p.rem, p.remF, v);
if (flags & MOD) vegaUtil.visitArray(p.mod, p.modF, v);
if ((flags & REFLOW) && (src = p.source)) {
sum = p.add.length + p.mod.length;
if (sum === src.length) ; else if (sum) {
vegaUtil.visitArray(src, filter(p, ADD_MOD), v);
} else {
// if no add/rem/mod tuples, visit source
vegaUtil.visitArray(src, p.srcF, v);
}
}
return p;
};
/**
* Represents a set of multiple pulses. Used as input for operators
* that accept multiple pulses at a time. Contained pulses are
* accessible via the public "pulses" array property. This pulse doe
* not carry added, removed or modified tuples directly. However,
* the visit method can be used to traverse all such tuples contained
* in sub-pulses with a timestamp matching this parent multi-pulse.
* @constructor
* @param {Dataflow} dataflow - The backing dataflow instance.
* @param {number} stamp - The timestamp.
* @param {Array<Pulse>} pulses - The sub-pulses for this multi-pulse.
*/
function MultiPulse(dataflow, stamp, pulses, encode) {
var p = this,
c = 0,
pulse, hash, i, n, f;
this.dataflow = dataflow;
this.stamp = stamp;
this.fields = null;
this.encode = encode || null;
this.pulses = pulses;
for (i=0, n=pulses.length; i<n; ++i) {
pulse = pulses[i];
if (pulse.stamp !== stamp) continue;
if (pulse.fields) {
hash = p.fields || (p.fields = {});
for (f in pulse.fields) { hash[f] = 1; }
}
if (pulse.changed(p.ADD)) c |= p.ADD;
if (pulse.changed(p.REM)) c |= p.REM;
if (pulse.changed(p.MOD)) c |= p.MOD;
}
this.changes = c;
}
var prototype$4 = vegaUtil.inherits(MultiPulse, Pulse);
/**
* Creates a new pulse based on the values of this pulse.
* The dataflow, time stamp and field modification values are copied over.
* @return {Pulse}
*/
prototype$4.fork = function(flags) {
var p = new Pulse(this.dataflow).init(this, flags & this.NO_FIELDS);
if (flags !== undefined) {
if (flags & p.ADD) {
this.visit(p.ADD, function(t) { return p.add.push(t); });
}
if (flags & p.REM) {
this.visit(p.REM, function(t) { return p.rem.push(t); });
}
if (flags & p.MOD) {
this.visit(p.MOD, function(t) { return p.mod.push(t); });
}
}
return p;
};
prototype$4.changed = function(flags) {
return this.changes & flags;
};
prototype$4.modified = function(_) {
var p = this, fields = p.fields;
return !(fields && (p.changes & p.MOD)) ? 0
: vegaUtil.isArray(_) ? _.some(function(f) { return fields[f]; })
: fields[_];
};
prototype$4.filter = function() {
vegaUtil.error('MultiPulse does not support filtering.');
};
prototype$4.materialize = function() {
vegaUtil.error('MultiPulse does not support materialization.');
};
prototype$4.visit = function(flags, visitor) {
var p = this,
pulses = p.pulses,
n = pulses.length,
i = 0;
if (flags & p.SOURCE) {
for (; i<n; ++i) {
pulses[i].visit(flags, visitor);
}
} else {
for (; i<n; ++i) {
if (pulses[i].stamp === p.stamp) {
pulses[i].visit(flags, visitor);
}
}
}
return p;
};
/* eslint-disable require-atomic-updates */
/**
* Evaluates the dataflow and returns a Promise that resolves when pulse
* propagation completes. This method will increment the current timestamp
* and process all updated, pulsed and touched operators. When invoked for
* the first time, all registered operators will be processed. This method
* should not be invoked by third-party clients, use {@link runAsync} or
* {@link run} instead.
* @param {string} [encode] - The name of an encoding set to invoke during
* propagation. This value is added to generated Pulse instances;
* operators can then respond to (or ignore) this setting as appropriate.
* This parameter can be used in conjunction with the Encode transform in
* the vega-encode package.
* @param {function} [prerun] - An optional callback function to invoke
* immediately before dataflow evaluation commences.
* @param {function} [postrun] - An optional callback function to invoke
* after dataflow evaluation completes. The callback will be invoked
* after those registered via {@link runAfter}.
* @return {Promise} - A promise that resolves to this dataflow after
* evaluation completes.
*/
async function evaluate(encode, prerun, postrun) {
const df = this,
level = df.logLevel(),
async = [];
// if the pulse value is set, this is a re-entrant call
if (df._pulse) return reentrant(df);
// wait for pending datasets to load
if (df._pending) {
await df._pending;
}
// invoke prerun function, if provided
if (prerun) await asyncCallback(df, prerun);
// exit early if there are no updates
if (!df._touched.length) {
df.info('Dataflow invoked, but nothing to do.');
return df;
}
// increment timestamp clock
let stamp = ++df._clock,
count = 0, op, next, dt, error;
// set the current pulse
df._pulse = new Pulse(df, stamp, encode);
if (level >= vegaUtil.Info) {
dt = Date.now();
df.debug('-- START PROPAGATION (' + stamp + ') -----');
}
// initialize priority queue, reset touched operators
df._touched.forEach(op => df._enqueue(op, true));
df._touched = UniqueList(vegaUtil.id);
try {
while (df._heap.size() > 0) {
// dequeue operator with highest priority
op = df._heap.pop();
// re-queue if rank changed
if (op.rank !== op.qrank) { df._enqueue(op, true); continue; }
// otherwise, evaluate the operator
next = op.run(df._getPulse(op, encode));
if (next.then) {
// await if operator returns a promise directly
next = await next;
} else if (next.async) {
// queue parallel asynchronous execution
async.push(next.async);
next = StopPropagation;
}
if (level >= vegaUtil.Debug) {
df.debug(op.id, next === StopPropagation ? 'STOP' : next, op);
}
// propagate evaluation, enqueue dependent operators
if (next !== StopPropagation) {
if (op._targets) op._targets.forEach(op => df._enqueue(op));
}
// increment visit counter
++count;
}
} catch (err) {
df._heap.clear();
error = err;
}
// reset pulse map
df._input = {};
df._pulse = null;
if (level >= vegaUtil.Info) {
dt = Date.now() - dt;
df.info('> Pulse ' + stamp + ': ' + count + ' operators; ' + dt + 'ms');
}
if (error) {
df._postrun = [];
df.error(error);
}
// invoke callbacks queued via runAfter
if (df._postrun.length) {
const pr = df._postrun.sort((a, b) => b.priority - a.priority);
df._postrun = [];
for (let i=0; i<pr.length; ++i) {
await asyncCallback(df, pr[i].callback);
}
}
// invoke postrun function, if provided
if (postrun) await asyncCallback(df, postrun);
// handle non-blocking asynchronous callbacks
if (async.length) {
Promise.all(async).then(cb => df.runAsync(null, () => {
cb.forEach(f => { try { f(df); } catch (err) { df.error(err); } });
}));
}
return df;
}
/**
* Queues dataflow evaluation to run once any other queued evaluations have
* completed and returns a Promise that resolves when the queued pulse
* propagation completes. If provided, a callback function will be invoked
* immediately before evaluation commences. This method will ensure a
* separate evaluation is invoked for each time it is called.
* @param {string} [encode] - The name of an encoding set to invoke during
* propagation. This value is added to generated Pulse instances;
* operators can then respond to (or ignore) this setting as appropriate.
* This parameter can be used in conjunction with the Encode transform in
* the vega-encode package.
* @param {function} [prerun] - An optional callback function to invoke
* immediately before dataflow evaluation commences.
* @param {function} [postrun] - An optional callback function to invoke
* after dataflow evaluation completes. The callback will be invoked
* after those registered via {@link runAfter}.
* @return {Promise} - A promise that resolves to this dataflow after
* evaluation completes.
*/
async function runAsync(encode, prerun, postrun) {
// await previously queued functions
while (this._running) await this._running;
// run dataflow, manage running promise
const clear = () => this._running = null;
(this._running = this.evaluate(encode, prerun, postrun))
.then(clear, clear);
return this._running;
}
/**
* Requests dataflow evaluation and the immediately returns this dataflow
* instance. If there are pending data loading or other asynchronous
* operations, the dataflow will evaluate asynchronously after this method
* has been invoked. To track when dataflow evaluation completes, use the
* {@link runAsync} method instead. This method will raise an error if
* invoked while the dataflow is already in the midst of evaluation.
* @param {string} [encode] - The name of an encoding set to invoke during
* propagation. This value is added to generated Pulse instances;
* operators can then respond to (or ignore) this setting as appropriate.
* This parameter can be used in conjunction with the Encode transform in
* the vega-encode module.
* @param {function} [prerun] - An optional callback function to invoke
* immediately before dataflow evaluation commences.
* @param {function} [postrun] - An optional callback function to invoke
* after dataflow evaluation completes. The callback will be invoked
* after those registered via {@link runAfter}.
* @return {Dataflow} - This dataflow instance.
*/
function run(encode, prerun, postrun) {
return this._pulse ? reentrant(this)
: (this.evaluate(encode, prerun, postrun), this);
}
/**
* Schedules a callback function to be invoked after the current pulse
* propagation completes. If no propagation is currently occurring,
* the function is invoked immediately. Callbacks scheduled via runAfter
* are invoked immediately upon completion of the current cycle, before
* any request queued via runAsync. This method is primarily intended for
* internal use. Third-party callers using runAfter to schedule a callback
* that invokes {@link run} or {@link runAsync} should not use this method,
* but instead use {@link runAsync} with prerun or postrun arguments.
* @param {function(Dataflow)} callback - The callback function to run.
* The callback will be invoked with this Dataflow instance as its
* sole argument.
* @param {boolean} enqueue - A boolean flag indicating that the
* callback should be queued up to run after the next propagation
* cycle, suppressing immediate invocation when propagation is not
* currently occurring.
* @param {number} [priority] - A priority value used to sort registered
* callbacks to determine execution order. This argument is intended
* for internal Vega use only.
*/
function runAfter(callback, enqueue, priority) {
if (this._pulse || enqueue) {
// pulse propagation is currently running, queue to run after
this._postrun.push({
priority: priority || 0,
callback: callback
});
} else {
// pulse propagation already complete, invoke immediately
try { callback(this); } catch (err) { this.error(err); }
}
}
/**
* Raise an error for re-entrant dataflow evaluation.
*/
function reentrant(df) {
df.error('Dataflow already running. Use runAsync() to chain invocations.');
return df;
}
/**
* Enqueue an operator into the priority queue for evaluation. The operator
* will be enqueued if it has no registered pulse for the current cycle, or if
* the force argument is true. Upon enqueue, this method also sets the
* operator's qrank to the current rank value.
* @param {Operator} op - The operator to enqueue.
* @param {boolean} [force] - A flag indicating if the operator should be
* forceably added to the queue, even if it has already been previously
* enqueued during the current pulse propagation. This is useful when the
* dataflow graph is dynamically modified and the operator rank changes.
*/
function enqueue(op, force) {
var q = op.stamp < this._clock;
if (q) op.stamp = this._clock;
if (q || force) {
op.qrank = op.rank;
this._heap.push(op);
}
}
/**
* Provide a correct pulse for evaluating an operator. If the operator has an
* explicit source operator, we will try to pull the pulse(s) from it.
* If there is an array of source operators, we build a multi-pulse.
* Otherwise, we return a current pulse with correct source data.
* If the pulse is the pulse map has an explicit target set, we use that.
* Else if the pulse on the upstream source operator is current, we use that.
* Else we use the pulse from the pulse map, but copy the source tuple array.
* @param {Operator} op - The operator for which to get an input pulse.
* @param {string} [encode] - An (optional) encoding set name with which to
* annotate the returned pulse. See {@link run} for more information.
*/
function getPulse(op, encode) {
var s = op.source,
stamp = this._clock;
return s && vegaUtil.isArray(s)
? new MultiPulse(this, stamp, s.map(_ => _.pulse), encode)
: this._input[op.id] || singlePulse(this._pulse, s && s.pulse);
}
function singlePulse(p, s) {
if (s && s.stamp === p.stamp) {
return s;
}
p = p.fork();
if (s && s !== StopPropagation) {
p.source = s.source;
}
return p;
}
var NO_OPT = {skip: false, force: false};
/**
* Touches an operator, scheduling it to be evaluated. If invoked outside of
* a pulse propagation, the operator will be evaluated the next time this
* dataflow is run. If invoked in the midst of pulse propagation, the operator
* will be queued for evaluation if and only if the operator has not yet been
* evaluated on the current propagation timestamp.
* @param {Operator} op - The operator to touch.
* @param {object} [options] - Additional options hash.
* @param {boolean} [options.skip] - If true, the operator will
* be skipped: it will not be evaluated, but its dependents will be.
* @return {Dataflow}
*/
function touch(op, options) {
var opt = options || NO_OPT;
if (this._pulse) {
// if in midst of propagation, add to priority queue
this._enqueue(op);
} else {
// otherwise, queue for next propagation
this._touched.add(op);
}
if (opt.skip) op.skip(true);
return this;
}
/**
* Updates the value of the given operator.
* @param {Operator} op - The operator to update.
* @param {*} value - The value to set.
* @param {object} [options] - Additional options hash.
* @param {boolean} [options.force] - If true, the operator will
* be re-evaluated even if its value has not changed.
* @param {boolean} [options.skip] - If true, the operator will
* be skipped: it will not be evaluated, but its dependents will be.
* @return {Dataflow}
*/
function update(op, value, options) {
var opt = options || NO_OPT;
if (op.set(value) || opt.force) {
this.touch(op, opt);
}
return this;
}
/**
* Pulses an operator with a changeset of tuples. If invoked outside of
* a pulse propagation, the pulse will be applied the next time this
* dataflow is run. If invoked in the midst of pulse propagation, the pulse
* will be added to the set of active pulses and will be applied if and
* only if the target operator has not yet been evaluated on the current
* propagation timestamp.
* @param {Operator} op - The operator to pulse.
* @param {ChangeSet} value - The tuple changeset to apply.
* @param {object} [options] - Additional options hash.
* @param {boolean} [options.skip] - If true, the operator will
* be skipped: it will not be evaluated, but its dependents will be.
* @return {Dataflow}
*/
function pulse(op, changeset, options) {
this.touch(op, options || NO_OPT);
var p = new Pulse(this, this._clock + (this._pulse ? 0 : 1)),
t = op.pulse && op.pulse.source || [];
p.target = op;
this._input[op.id] = changeset.pulse(p, t);
return this;
}
function Heap(cmp) {
var nodes = [];
return {
clear: () => nodes = [],
size: () => nodes.length,
peek: () => nodes[0],
push: x => {
nodes.push(x);
return siftdown(nodes, 0, nodes.length - 1, cmp);
},
pop: () => {
var last = nodes.pop(), item;
if (nodes.length) {
item = nodes[0];
nodes[0] = last;
siftup(nodes, 0, cmp);
} else {
item = last;
}
return item;
}
};
}
function siftdown(array, start, idx, cmp) {
var item, parent, pidx;
item = array[idx];
while (idx > start) {
pidx = (idx - 1) >> 1;
parent = array[pidx];
if (cmp(item, parent) < 0) {
array[idx] = parent;
idx = pidx;
continue;
}
break;
}
return (array[idx] = item);
}
function siftup(array, idx, cmp) {
var start = idx,
end = array.length,
item = array[idx],
cidx = (idx << 1) + 1, ridx;
while (cidx < end) {
ridx = cidx + 1;
if (ridx < end && cmp(array[cidx], array[ridx]) >= 0) {
cidx = ridx;
}
array[idx] = array[cidx];
idx = cidx;
cidx = (idx << 1) + 1;
}
array[idx] = item;
return siftdown(array, start, idx, cmp);
}
/**
* A dataflow graph for reactive processing of data streams.
* @constructor
*/
function Dataflow() {
this.logger(vegaUtil.logger());
this.logLevel(vegaUtil.Error);
this._clock = 0;
this._rank = 0;
try {
this._loader = vegaLoader.loader();
} catch (e) {
// do nothing if loader module is unavailable
}
this._touched = UniqueList(vegaUtil.id);
this._input = {};
this._pulse = null;
this._heap = Heap((a, b) => a.qrank - b.qrank);
this._postrun = [];
}
var prototype$5 = Dataflow.prototype;
/**
* The current timestamp of this dataflow. This value reflects the
* timestamp of the previous dataflow run. The dataflow is initialized
* with a stamp value of 0. The initial run of the dataflow will have
* a timestap of 1, and so on. This value will match the
* {@link Pulse.stamp} property.
* @return {number} - The current timestamp value.
*/
prototype$5.stamp = function() {
return this._clock;
};
/**
* Gets or sets the loader instance to use for data file loading. A
* loader object must provide a "load" method for loading files and a
* "sanitize" method for checking URL/filename validity. Both methods
* should accept a URI and options hash as arguments, and return a Promise
* that resolves to the loaded file contents (load) or a hash containing
* sanitized URI data with the sanitized url assigned to the "href" property
* (sanitize).
* @param {object} _ - The loader instance to use.
* @return {object|Dataflow} - If no arguments are provided, returns
* the current loader instance. Otherwise returns this Dataflow instance.
*/
prototype$5.loader = function(_) {
if (arguments.length) {
this._loader = _;
return this;
} else {
return this._loader;
}
};
/**
* Empty entry threshold for garbage cleaning. Map data structures will
* perform cleaning once the number of empty entries exceeds this value.
*/
prototype$5.cleanThreshold = 1e4;
// OPERATOR REGISTRATION
prototype$5.add = add;
prototype$5.connect = connect;
prototype$5.rank = rank;
prototype$5.rerank = rerank;
// OPERATOR UPDATES
prototype$5.pulse = pulse;
prototype$5.touch = touch;
prototype$5.update = update;
prototype$5.changeset = changeset;
// DATA LOADING
prototype$5.ingest = ingest$1;
prototype$5.parse = parse;
prototype$5.preload = preload;
prototype$5.request = request;
// EVENT HANDLING
prototype$5.events = events;
prototype$5.on = on;
// PULSE PROPAGATION
prototype$5.evaluate = evaluate;
prototype$5.run = run;
prototype$5.runAsync = runAsync;
prototype$5.runAfter = runAfter;
prototype$5._enqueue = enqueue;
prototype$5._getPulse = getPulse;
// LOGGING AND ERROR HANDLING
function logMethod(method) {
return function() {
return this._log[method].apply(this, arguments);
};
}
/**
* Get or set the logger instance used to log messages. If no arguments are
* provided, returns the current logger instance. Otherwise, sets the logger
* and return this Dataflow instance. Provided loggers must support the full
* API of logger objects generated by the vega-util logger method. Note that
* by default the log level of the new logger will be used; use the logLevel
* method to adjust the log level as needed.
*/
prototype$5.logger = function(logger) {
if (arguments.length) {
this._log = logger;
return this;
} else {
return this._log;
}
};
/**
* Logs an error message. By default, logged messages are written to console
* output. The message will only be logged if the current log level is high
* enough to permit error messages.
*/
prototype$5.error = logMethod('error');
/**
* Logs a warning message. By default, logged messages are written to console
* output. The message will only be logged if the current log level is high
* enough to permit warning messages.
*/
prototype$5.warn = logMethod('warn');
/**
* Logs a information message. By default, logged messages are written to
* console output. The message will only be logged if the current log level is
* high enough to permit information messages.
*/
prototype$5.info = logMethod('info');
/**
* Logs a debug message. By default, logged messages are written to console
* output. The message will only be logged if the current log level is high
* enough to permit debug messages.
*/
prototype$5.debug = logMethod('debug');
/**
* Get or set the current log level. If an argument is provided, it
* will be used as the new log level.
* @param {number} [level] - Should be one of None, Warn, Info
* @return {number} - The current log level.
*/
prototype$5.logLevel = logMethod('level');
/**
* Abstract class for operators that process data tuples.
* Subclasses must provide a {@link transform} method for operator processing.
* @constructor
* @param {*} [init] - The initial value for this operator.
* @param {object} [params] - The parameters for this operator.
* @param {Operator} [source] - The operator from which to receive pulses.
*/
function Transform(init, params) {
Operator.call(this, init, null, params);
}
var prototype$6 = vegaUtil.inherits(Transform, Operator);
/**
* Overrides {@link Operator.evaluate} for transform operators.
* Internally, this method calls {@link evaluate} to perform processing.
* If {@link evaluate} returns a falsy value, the input pulse is returned.
* This method should NOT be overridden, instead overrride {@link evaluate}.
* @param {Pulse} pulse - the current dataflow pulse.
* @return the output pulse for this operator (or StopPropagation)
*/
prototype$6.run = function(pulse) {
if (pulse.stamp < this.stamp) return pulse.StopPropagation;
var rv;
if (this.skip()) {
this.skip(false);
} else {
rv = this.evaluate(pulse);
}
rv = rv || pulse;
if (rv.then) {
rv = rv.then(_ => this.pulse =_);
} else if (rv !== pulse.StopPropagation) {
this.pulse = rv;
}
return rv;
};
/**
* Overrides {@link Operator.evaluate} for transform operators.
* Marshalls parameter values and then invokes {@link transform}.
* @param {Pulse} pulse - the current dataflow pulse.
* @return {Pulse} The output pulse (or StopPropagation). A falsy return
value (including undefined) will let the input pulse pass through.
*/
prototype$6.evaluate = function(pulse) {
var params = this.marshall(pulse.stamp),
out = this.transform(params, pulse);
params.clear();
return out;
};
/**
* Process incoming pulses.
* Subclasses should override this method to implement transforms.
* @param {Parameters} _ - The operator parameter values.
* @param {Pulse} pulse - The current dataflow pulse.
* @return {Pulse} The output pulse (or StopPropagation). A falsy return
* value (including undefined) will let the input pulse pass through.
*/
prototype$6.transform = function() {};
var transforms = {};
function definition(type) {
var t = transform(type);
return t && t.Definition || null;
}
function transform(type) {
type = type && type.toLowerCase();
return vegaUtil.hasOwnProperty(transforms, type) ? transforms[type] : null;
}
exports.Dataflow = Dataflow;
exports.EventStream = EventStream;
exports.MultiPulse = MultiPulse;
exports.Operator = Operator;
exports.Parameters = Parameters;
exports.Pulse = Pulse;
exports.Transform = Transform;
exports.UniqueList = UniqueList;
exports.asyncCallback = asyncCallback;
exports.changeset = changeset;
exports.definition = definition;
exports.derive = derive;
exports.ingest = ingest;
exports.isChangeSet = isChangeSet;
exports.isTuple = isTuple;
exports.rederive = rederive;
exports.replace = replace;
exports.stableCompare = stableCompare;
exports.transform = transform;
exports.transforms = transforms;
exports.tupleid = tupleid;
Object.defineProperty(exports, '__esModule', { value: true });
})));
|
exports.strings = {
///////////////////////////////////////////////////////////////////////////
'finish-dialog-finished': {
'__desc__': 'One of the lines in the next level dialog',
'ja': '最後のレベルをクリアしました!すごい!!',
'en_US': 'Wow! You finished the last level, great!',
'de_DE': 'Wow! Du hast den letzten Level gelöst, super!',
'zh_CN': 'Wow!你通关了!',
'zh_TW': '我的天啊!您解開了最後一關,太強了!',
'es_AR': '¡Ea! Terminaste el último nivel, ¡genial!',
'es_ES': '¡Felicitaciones! Terminaste el último nivel!',
'pt_BR': 'Uia! Você terminou o último nível, massa!',
'gl' : '¡Yeeeha! Remataches o derradeiro nivel, ¡a tope!',
'fr_FR': 'Félicitations, vous avez réussi le dernier niveau !',
'ru_RU': 'Вау! Вы прошли последний уровень, отлично!',
'uk': 'Вау! Ти пройшов останній рівень, круто!',
'ko': '와우! 마지막 레벨까지 마쳤습니다. 멋지네요!',
'vi_VN': 'Wow! Bạn đã hoàn thành cấp độ cuối cùng, tuyệt vời!'
},
///////////////////////////////////////////////////////////////////////////
'finish-dialog-next': {
'__desc__': 'One of the lines in the next level dialog',
'en_US': 'Would you like to move on to *"{nextLevel}"*, the next level?',
'de_DE': 'Möchtest du mit *"{nextLevel}"* weitermachen, dem nächsten Level?',
'ja': '次の章 *"{nextLevel}"* へ進みますか?',
'zh_CN': '要不要试试下一关 *“{nextLevel}”*?',
'zh_TW': '下一關是*「{nextLevel}」*,您要繼續闖關嗎?',
'es_AR': '¿Querés seguir con *"{nextLevel}"*, el próximo nivel?',
'es_ES': '¿Quieres seguir al nivel *"{nextLevel}"*, el próximo nivel?',
'pt_BR': 'Você gostaria de ir para o próximo nível: *"{nextLevel}"*?',
'gl' : '¿Gustaríache ir o seguinte nivel: *"{nextLevel}"*?',
'fr_FR': 'Voulez-vous passer à *"{nextLevel}"*, le prochain niveau ?',
'ru_RU': 'Хотите перейти на следующий уровень: *"{nextLevel}"*?',
'uk': 'Хочеш перейти на наступний рівень -- *"{nextLevel}"*?',
'ko': '다음 레벨로 넘어갈까요? 레벨 *"{nextLevel}"*',
'vi_VN': 'Bạn có muốn chuyển sang cấp độ tiếp theo (*"{nextLevel}"*) không?'
},
///////////////////////////////////////////////////////////////////////////
'finish-dialog-win': {
'__desc__': 'One of the lines in the next level dialog',
'en_US': 'Awesome! You matched or exceeded our solution.',
'pt_BR': 'Maravilha! Você fez uma solução tão boa quanto ou melhor que a nossa.',
'de_DE': 'Wahnsinn! Du warst so gut wie unsere Lösung, oder sogar besser.',
'ja': '素晴らしい!このレベルをクリアしましたね',
'zh_CN': '太强了!你的答案符合标准答案甚至更好。',
'zh_TW': '太強了,您的答案符合我們的預期甚至更好!',
'es_AR': '¡Fabuloso! Igualaste o superaste nuestra solución.',
'es_ES': '¡Fabuloso! Igualaste o superaste nuestra solución.',
'gl' : '¡Fabuloso! Fixécholo igual ou mellor ca nosa solución.',
'fr_FR': 'Fabuleux ! Votre solution a égalé ou surpassé notre solution.',
'ru_RU': 'Отлично! Ваше решение соответствует или превосходит наше.',
'uk': 'Чудово! Твій розв’язок на рівні або кращий від нашого.',
'ko': '멋져요! 우리의 해답과 일치하거나 우리보다 좀 더 나은 해답입니다.',
'vi_VN': 'Tuyệt vời! Bạn đã hoàn thành cấp độ này rồi!'
},
///////////////////////////////////////////////////////////////////////////
'finish-dialog-lose': {
'__desc__': 'When the user entered more commands than our best, encourage them to do better',
'en_US': 'See if you can whittle it down to {best} :D',
'de_DE': 'Schau mal ob du es in {best} Schritten hinbekommst :D',
'ja': '模範解答の回数={best}回でクリアする方法も考えてみましょう :D',
'zh_CN': '试试看你能否在 {best} 步之内搞定 :D',
'zh_TW': '試試看您是否能在 {best} 步内搞定 :D',
'es_AR': 'Fijate si podés bajarlo a usar sólo {best} comandos :D',
'es_ES': 'Trata de usar sólo {best} comandos :D',
'pt_BR': 'Veja se consegue reduzir para somente {best} :D',
'gl' : 'Mira se consigues reducir a solo {best} :D',
'fr_FR': 'Voyons si vous pouvez descendre à {best} :D',
'ru_RU': 'Попробуйте, может вы сможете уложиться в {best} : D',
'uk': 'Спробуй, можливо ти зможеш вкластися в {best} кроків :D',
'ko': '{best}회로 줄일 수 있다면 해보세요. :D',
'vi_VN': 'Thử xem bạn có giảm bớt số câu lệnh xuống {best} được không nào :D'
},
///////////////////////////////////////////////////////////////////////////
'hg-prune-tree': {
'__desc__': 'warning when pruning tree',
'en_US': 'Warning! Mercurial does aggressive garbage collection and thus needs to prune your tree',
'zh_CN': '注意! Mercurial 会进行主动垃圾回收,需要将你的提交树縮小。',
'zh_TW': '注意! Mercurial 會積極地做垃圾收集,而且會因此把你的 tree 給縮小。',
'es_AR': '¡Cuidado! Mercurial hace garbage collection agresivamente y necesita eliminar tu árbol',
'es_ES': '¡Cuidado! Mercurial hace la colección de basura agresivamente (para administrar memoria) y necesita podar tu árbol.',
'pt_BR': 'Cuidado! O Mercurial faz coleção de lixo agressiva e precisa prunar sua árvore',
'gl' : '¡Coidado! Mercurial fai que recolección de lixo agresivamente (para limpar memoria) e precisa podar a túa árbore.',
'fr_FR': 'Attention, Mercurial supprime de façon agressive et nécessite un prune du repository',
'de_DE': 'Achtung! Mercurial macht aggressive Garbage Collection und muss daher deinen Baum reduzieren',
'ru_RU': 'Внимание! Mercurial использует агрессивный сборщик мусора и обрезает ваше дерево',
'uk': 'Увага! Mercurial агресивно збирає сміття й може обрізати твоє дерево ',
'ko': '주의! Mercurial은 공격적으로 가비지 컬렉션을 수행하므로 트리를 정리할 필요가 있습니다.',
'vi_VN': '__Warning! Mercurial does aggressive garbage collection and thus needs to prune your tree'
},
///////////////////////////////////////////////////////////////////////////
'hg-a-option': {
'__desc__': 'warning for when using -A option',
'en_US': 'The -A option is not needed for this app, just commit away!',
'zh_TW': '對於這個 app 來說,-A 選項並不是必須的,只需要 commit 就好!',
'zh_CN': '对本 App 而言,-A 选项并非必须项,直接 commit 就好!',
'es_AR': 'La opción -A no es necesaria para esta aplicación, simplemente hacé commit',
'es_ES': 'La opción -A no se necesita para este aplicación, sólo hace un commit!',
'pt_BR': 'A opção -A não é necessária para este aplicativo, simplesmente faça commit',
'gl' : 'A opción -A non se necesita para este aplicativo, ¡fai só un commit!',
'de_DE': 'Die Option -A wird in dieser Anwendung nicht benötigt, committe einfach!',
'fr_FR': 'L\'option -A n\'est pas nécessaire pour cette application, simplement commiter',
'ru_RU': 'Опция -A не требуется для этого приложения, просто сделайте коммит.',
'uk': 'Опція -A не потрібна для цього застосунку, можна просто комітити!',
'ko': '이 앱에선 -A 옵션은 필요 없습니다. 그냥 커밋하세요!',
'vi_VN': 'Tùy chọn -A không cần thiết khi sử dụng ứng dụng này, bạn cứ commit thôi!'
},
///////////////////////////////////////////////////////////////////////////
'hg-error-no-status': {
'__desc__': 'One of the errors for hg',
'en_US': 'There is no status command for this app, since there is no staging of files. Try hg summary instead',
'zh_CN': '本 App 没有 status 命令哦,因为根本没有 stage 缓存文件。可以用 hg summary 代替哦',
'zh_TW': '本 App 没有 status 命令哦,因为根本没有 stage 缓存文件。可以用 hg summary 代替哦',
'es_AR': 'No hay un comando status para esta aplicación, dado que no hay archivos que indexar. Probá hg summary, en cambio',
'es_ES': 'No hay un comando status para esta aplicación, porque que no hay archivos que indexar. Prueba el comando hg summary, en cambio',
'pt_BR': 'Não existe um comando status para este aplicativo, já que não há staging de arquivos. Tente hg summary',
'gl' : 'Non hai un comando status para esta aplicación, xa que non hai ficheiros que indexar. Proba hg summary',
'fr_FR': 'Il n\'y a pas de commande status pour cette application, car il n\'y a pas de fichier stagé. Essayez hg summary à la place.',
'de_DE': 'Es gibt keinen Befehl status in dieser Anwendung, da es kein Staging von Dateien gibt. Probier stattdessen hg summary',
'ru_RU': 'Команда status не поддерживается в этом приложении, так как здесь нет файлов. Попробуйте выполнить hg summary',
'uk': 'Команда status не підтримується в цьому застосунку, так як немає стейджингу(staging) файлів. Натомість спробуй hg summary ',
'ko': '이 앱을 위한 상태 명령어는 없습니다. 왜냐하면 파일들의 스테이징이 없기 때문입니다. 대신 hg summary를 시도해보세요.',
'vi_VN': 'Câu lệnh status sẽ không sử dụng được do ứng dụng không lưu trạng thái file. Thử chạy lệnh này nhé: hg log -f '
},
///////////////////////////////////////////////////////////////////////////
'hg-error-need-option': {
'__desc__': 'One of the errors for hg',
'en_US': 'I need the option {option} for that command!',
'zh_CN': '我需要该命令使用 {option} 选项呢。',
'zh_TW': '我需要該命令使用 {option} 選項呢。',
'es_AR': '¡Necesito la opción {opcion} para ese comando!',
'es_ES': '¡Necesito la opción {opcion} para ese comando!',
'pt_BR': 'Eu preciso da opção {option} para esse comando!',
'gl' : 'Preciso da opción {option} para ese comando!',
'fr_FR': 'J\'ai besoin de l\'option {option} pour cette commande',
'de_DE': 'Ich benötige die Option {option} für diesen Befehl!',
'ru_RU': 'Для этой команды требуется опция {option}',
'uk': 'Для цієї команди потрібна опція {option}',
'ko': '나는 그 명령어를 위한 {option} 옵션이 필요합니다.',
'vi_VN': 'Câu lệnh cần có tùy chọn {option}!'
},
///////////////////////////////////////////////////////////////////////////
'hg-error-log-no-follow': {
'__desc__': 'hg log without -f (--follow)',
'en_US': 'hg log without -f is currently not supported, use -f',
'zh_CN': '暂不支持没有-f 选项的 hg log 命令,请补充 -f 选项吧',
'zh_TW': '暫不支持沒有-f 選項的 hg log 命令,請補充 -f 選項吧',
'es_AR': 'hg log sin el parámetro -f no está soportado, usá -f',
'es_ES': 'Actualmente hg log sin -f no es compatible con esta aplicación. Usa -f.',
'pt_BR': 'hg log sem -f atualmente não é suportado, use -f',
'gl' : 'hg log sen -f actulamente non é soportado, usa -f',
'fr_FR': 'hg log sans -f n\'est pas supporté',
'de_DE': 'hg log ohne -f wird aktuell nicht unterstützt, benutze bitte -f',
'ru_RU': 'hg log без опции -f в настоящий момент не поддерживается, используйте -f',
'uk': 'hg log без опції -f в данний момент не підтримується, використовуй -f',
'ko': '-f가 없는 hg log는 현재 지원되지 않습니다. -f를 사용하세요.',
'vi_VN': 'hg log không có tùy chọn -f chưa được hỗ trợ, thử thêm -f vào nhé'
},
///////////////////////////////////////////////////////////////////////////
'git-status-detached': {
'__desc__': 'One of the lines for git status output',
'en_US': 'Detached head!',
'de_DE': 'Detached head!',
'zh_CN': '游离的 Head(Detached head)!',
'zh_TW': '分離 Head!',
'es_AR': '¡Detached HEAD!',
'es_ES': '¡HEAD separado! (Detached HEAD).',
'pt_BR': 'Detached HEAD!',
'gl' : '¡Detached HEAD!',
'fr_FR': 'head détaché !',
'ru_RU': 'Отделенный HEAD',
'uk': 'Відокремлений HEAD',
'ko': '분리된 HEAD!',
'vi_VN': 'Đã tách HEAD!'
},
///////////////////////////////////////////////////////////////////////////
'git-status-onbranch': {
'__desc__': 'One of the lines for git status output',
'en_US': 'On branch {branch}',
'de_DE': 'Auf Branch {branch}',
'zh_CN': '当前分支 {branch}',
'zh_TW': '切換到 branch {branch}',
'es_AR': 'En la rama {branch}',
'es_ES': 'En la rama {branch}',
'pt_BR': 'No ramo {branch}',
'gl' : 'Non na rama {branch}',
'fr_FR': 'Sur la branche {branch}',
'ru_RU': 'В ветке {branch}',
'uk': 'В гілці {branch}',
'ko': '분기 지점 {branch}에서'
},
///////////////////////////////////////////////////////////////////////////
'git-status-readytocommit': {
'__desc__': 'One of the lines for git status output',
'en_US': 'Ready to commit! (as always in this demo)',
'de_DE': 'Fertig zum committen! (Wie immer in dieser Demo)',
'zh_CN': '可以提交啦!(在这个程序中无须修改文件,一直可以提交)',
'zh_TW': '準備 commit!(在這個 demo 裡面可以一直 commit)',
'es_AR': '¡Listo para commitear! (como siempre en esta demo ;-) )',
'es_ES': '¡Listo para hacer un commit (como siempre en esta demo)!',
'pt_BR': 'Pronto para commitar! (como sempre neste demo ;-) )',
'gl' : '¡Praparado para facer un commit (como sempre nesta demo ;-) )!',
'fr_FR': 'Prêt à commit ! (comme toujours dans cette démo)',
'ru_RU': 'Готово к коммиту! (как и всегда в этом демо)',
'uk': 'Готово до коміту! (як завжди в цьому демо)',
'ko': '커밋을 준비하세요! (이 데모에서는 항상)'
},
///////////////////////////////////////////////////////////////////////////
'git-dummy-msg': {
'__desc__': 'The dummy commit message for all commits. Feel free to put in a ' +
'shoutout to your school / city / whatever!',
'en_US': 'Quick commit. Go Bears!',
'de_DE': 'Schneller Commit. Eff-Zeh!',
'zh_CN': '快速提交。Coding 4ever!',
'zh_TW': '快速 commit。上啊熊!',
'es_AR': 'Otro commit más, y van...',
'es_ES': 'Hagamos un commit. Atlanta, Georgia! Escucha WHATUPRG también.',
'pt_BR': 'Commitando.. Vai Timão!',
'gl' : 'Mesturando.. ¡Alá imos!',
'fr_FR': 'Commit rapide. NoMaN Sux!',
'ru_RU': 'Быстрый коммит. А надо!',
'uk': 'Швидкий коміт. Динамо!',
'ko': '빨리 커밋하세요!'
},
'git-error-origin-fetch-uptodate': {
'__desc__': 'One of the error messages for git',
'en_US': 'Already up to date!',
'de_DE': 'Bereits aktuell!',
'fr_FR': 'Déjà à jour',
'es_AR': 'Estás en la versión más reciente',
'es_ES': 'Ya actualizado con la versión más reciente.',
'pt_BR': 'Já estamos na versão mais recente!',
'gl' : 'Xa estamos actualizados ca versión máis recente',
'zh_TW': '已經是最新的了',
'zh_CN': '已经是最新的了',
'ru_RU': 'Уже обновлено!',
'uk': 'Вже оновлено!',
'ko': '이미 최신 상태입니다!'
},
'git-error-origin-fetch-no-ff': {
'__desc__': 'One of the error messages for git',
'en_US': 'Your origin branch is out of sync with the remote branch and fetch cannot be performed',
'zh_CN': '你的 origin 仓库中的分支与远程分支的不同步了,无法执行 fetch 命令',
'zh_TW': '你的 origin 分支已經失去了與 remote 遠端分支的同步,所以無法執行 fetch 命令',
'de_DE': 'Dein origin Branch ist nicht auf dem Stand des Remote Branch und fetch kann nicht ausgeführt werden',
'es_AR': 'Tu rama origin está desincronizada con la rama remota, por lo que no se puede hacer el fetch',
'es_ES': 'Tu rama origin no está sicronizada con la rama remota, así que un fetch no se puede realizar.',
'pt_BR': 'O fetch não pode ser realizado pois o ramo de origem está fora de sincronia com o ramo remoto',
'gl' : 'O fetch non pode ser realizado xa que a rama de orixe non está sincronizada ca rama remota',
'fr_FR': 'Votre branche origin n\'est plus synchronisée avec la branche distante et fetch ne peut pas être appliqué. Essayez avec l\'option --force',
'ru_RU': 'Ваша origin ветка не синхронизирована с удаленной веткой, невозможно выполнить fetch',
'uk': 'Твоя гілка origin не синхронізована з віддаленою гілкою, неможливо виконати fetch',
'ko': '당신의 오리진 브랜치가 원격 브랜치와 동기화되지 않았고, 패치를 실행할 수 없습니다.'
},
'git-error-origin-push-no-ff': {
'__desc__': 'One of the error messages for git',
'en_US': 'The remote repository has diverged from your local repository, so uploading your changes is not a simple fast forward (and thus your push was rejected). Please pull down the new changes in the remote repository, incorporate them into this branch, and try again. You can do so with git pull or git pull --rebase',
'zh_CN': '远程仓库与你的本地仓库产生了分歧,故此上传操作无法通过 Fast-forward 实现(因此你的 push 被拒绝了)。请 pull 下来远程仓库里最新的更改,与这个分支合并之后再试一次。你可以通过 git pull 或 git pull --rebase 实现。',
'zh_TW': '遠端倉庫與你的本地倉庫產生了分歧,故此上傳操作無法通過簡單地快進實現(因此你的 push 被拒絕了)。請 pull 下來遠端裡最新的更改,與本地合併之後再試一次。你可以通過 git pull 或 git pull --rebase 實現。',
'de_DE': 'Das entfernte Repository weicht von deinem lokalen Repository ab, daher können deine Änderungen nicht mit einem einfachen fast forward hochgeladen werden (und daher ist dein push abgelehnt worden). Bitte pull erst die neuen Änderungen in das lokale Repository, integriere sie in den Branch und versuch es nochmal. Das kannst du mit git pull oder git pull --rebase machen',
'es_AR': 'El repositorio remoto divergió de tu repositorio local, por lo que subir tus cambios no es un simple fast forward (y por eso se rechazó tu push). Por favor, hacé pull de los nuevos cambios en el repositorio remoto, incorporalos a esta rama y probá de nuevo. Podés hacerlo con git pull o git pull --rebase',
'es_ES': 'El depósito remoto se ha desviado del depósito local. Subir cambios no es un avance rápido sencillo (por eso fue rechazado tu push). Por favor haz pull para descaragar los cambios en el depósito remoto para que los incorpores en la rama actual. Los cambios se pueden hacer pull con el comando "git pull" o "git pull --rebase"',
'pt_BR': 'O repositório remoto divergiu do repositório local, então enviar suas mudanças não é um simples fast forward (e por isso seu push foi rejeitado). Por favor, faça pull das novas mudanças do repositório remoto, incorpore-os a este ramo, e tente novamente. Você pode fazê-lo com git pull ou git pull --rebase',
'gl' : 'O repositorio remoto diverxe do teu repositorio local. Subir os cambios non é un fast-forward (avance rápido) e por iso foi rechazado o teu push. Por favor, fai un pull dos novos cambios do repositorio remoto e inclúeos na túa rama actual. Os cambios pódense facer co comando "git pull" ou "git pull --rebase"',
'fr_FR': 'Le dépôt distant a divergé de votre référentiel local, donc l\'envoi de vos modifications n\'est pas en simple avance rapide (et donc votre envoi a été rejeté). Veuillez récupérer les nouveaux changements depuis le dépôt distant, les intégrer dans cette branche, et essayez à nouveau. Vous pouvez le faire avec git pull ou git pull --rebase',
'ru_RU': 'Удаленный репозиторий разошелся с вашим локальным репозиторием, поэтому выгрузка ваших изменений не может быть в режиме fast forward (и следовательно ваш push будет отклонён). Пожалуйста, удалите изменения в удаленном репозитории которые, объедините их в эту ветку и попробуйте еще раз. Вы можете сделать это с помощью git pull или git pull --rebase',
'uk': 'Віддалений репозиторій розбігся з твоїм локальним репозиторієм, тому відвантаження твоїх змін не є простим fast forward (і тому твій push був відхилений). Будь-ласка, витягни зміни з віддаленого репозиторію, включи їх в цю гілку, й спробуй ще. Ти можеш зробити це за допомогою git pull чи git pull --rebase',
'ko': '원격 레포지토리가 당신의 로컬 레포지토리에서 분기하므로, 변경 사항을 업데이트 하는것은 간단한 fast forward가 아닙니다(따라서 push가 거절될 것입니다.). 원격 레포지토리에서의 변경 사항을 내려 받아 이 브랜치에 합쳐라. 그리고 이걸 반복하라. 당신은 git pull 또는 git pull --rebase를 사용해 이를 수행할 수 있다.'
},
'git-error-remote-branch': {
'__desc__': 'One of the error messages for git',
'en_US': 'You cannot execute that command on a remote branch',
'zh_CN': '你不能在远程分支上执行这个命令。',
'zh_TW': '你不能在遠端分支上執行這個命令呀。',
'de_DE': 'Du kannst diesen Befehl nicht auf einem Remote Branch ausführen',
'es_AR': 'No podés ejecutar ese comando en una rama remota',
'es_ES': 'No puedes ejecutar ese comando en una rama remota',
'pt_BR': 'Você não pode executar esse comando em um ramo remoto',
'gl' : 'Non podes executar ese comando nunha rama remota',
'fr_FR': 'Vous ne pouvez exécuter cette commande sur une branche distante',
'ru_RU': 'Вы не можете выполнить эту команду на удаленной ветке',
'uk': 'Ти не можеш виконати цю команду на віддаленій гілці',
'ko': '당신은 원격 브랜치에서 그 명령어를 실행시킬 수 없다.'
},
'git-error-origin-required': {
'__desc__': 'One of the error messages for git',
'en_US': 'An origin is required for that command',
'zh_CN': '该命令需要一个 origin',
'zh_TW': '該命令需要一個 origin',
'de_DE': 'Für diesen Befehl wird origin benötigt',
'es_AR': 'Necesitás un origen para ese comando',
'es_ES': 'Se requiere un origen para ese comando.',
'pt_BR': 'É necessário informar uma origem para esse comando',
'gl' : 'É necesario informar unha orixe para ese comando',
'fr_FR': 'Une origine est requise pour cette commande',
'ru_RU': 'Origin требуется для этой команды',
'uk': 'Для цієї команди потрібний origin',
'ko': '그 명령어를 위한 오리진이 필요하다.'
},
'git-error-origin-exists': {
'__desc__': 'One of the error messages for git',
'en_US': 'An origin already exists! You cannot make a new one',
'zh_CN': 'origin 已存在。你不能重复创建',
'zh_TW': 'origin 遠端已存在。你不能重複創建',
'de_DE': 'origin existiert bereits! Du kannst es nicht nochmal anlegen',
'es_AR': '¡Ya existe el origen! No podés crear uno nuevo',
'es_ES': '¡Ya existe un origen! No puedes crearlo de nuevo.',
'pt_BR': 'A origem já existe! Você não pode criar uma nova',
'gl' : 'A orixe xa existe! Non podes crear unha nova',
'fr_FR': 'Une origine existe déjà ! Vous ne pouvez pas en créer une nouvelle',
'ru_RU': 'Origin уже существует! Невозможно создать еще один',
'uk': 'Origin вже існує! Неможливо створити ще один',
'ko': '오리진이 이미 존재합니다! 당신은 새로 만들 수 없습니다.'
},
///////////////////////////////////////////////////////////////////////////
'git-error-branch': {
'__desc__': 'One of the error messages for git',
'en_US': 'You can\'t delete the master branch, the branch you are on, or things that ' +
'aren\'t branches',
'de_DE': 'Du kannst nicht den Branch master, den Branch auf dem du gerade arbeitest oder Refs, die keine Branches sind, löschen',
'zh_CN': '你不能删除主分支(master),或者你当前所在的分支,或者其它连分支也不是的东西。',
'zh_TW': '你不能刪除 master branch,或者你當前所在的 branch,或者其它連 branch 都不是的東西。',
'es_AR': 'No podés borrar la rama master, la rama en la que estás, o cosas que no son ramas',
'es_ES': 'No puedes eliminar la rama master, la rama en que estás, o cosas que no son ramas.',
'pt_BR': 'Você não pode apagar o ramo master, nem o ramo em que você está, nem coisas que não sejam ramos',
'gl' : 'Non podes borrala rama master, nin a rama na que ti estás, nin cousas que non sexan ramas',
'fr_FR': 'Vous ne pouvez supprimer la branche master, la branche sur laquelle vous êtes, ou ce qui n\'est pas une branche',
'ru_RU' : 'Невозможно удалить ветку master, ветку на которой вы сейчас и то что не является веткой',
'uk': 'Неможливо видалити гілку master, гілку на якій ти зараз знаходишся чи штуки які не є гілкою',
'ko': '당신은 마스터 브랜치, 당신이 현재 사용중인 브랜치, 또는 브랜치가 아닌 것들을 삭제할 수 없습니다.'
},
///////////////////////////////////////////////////////////////////////////
'git-merge-msg': {
'__desc__': 'The commit message for a merge commit',
'en_US': 'Merge {target} into {current}',
'de_DE': 'Mergen von {target} in {current}',
'zh_CN': '合并 {target} 到 {current}',
'zh_TW': '將 {target} 併入 {current}',
'es_AR': 'Mergear {target} a {current}',
'es_ES': 'Incorporar {target} en {current}',
'pt_BR': 'Merge de {target} em {current}',
'gl' : 'Merge de {target} en {current}',
'fr_FR': 'Merge de {target} dans {current}',
'ru_RU': 'Слияние {target} в {current}',
'uk': 'Злиття {target} в {current}',
'ko': '{target}을 {current}에 병합하세요.'
},
///////////////////////////////////////////////////////////////////////////
'git-error-rebase-none': {
'__desc__': 'One of the error messages for git',
'en_US': 'No commits to rebase! Everything is a merge commit or changes already applied',
'de_DE': 'Keine Commits für Rebase gefunden! Alle Commits sind Merge Commits oder beinhalten nur schon vorhandene Änderungen',
'zh_CN': '没有可以 rebase 的提交记录!可能是合并提交,或者已经 rebase 过了。',
'zh_TW': '沒有需要 rebase 的 commit!每個都是一個 merge commit 或者修改已經被寫入了',
'es_AR': '¡No hay commits para rebasear! Son todos commits de merge o cambios ya aplicados',
'es_ES': '¡No hay commits para hacer rebase! Todo es un merge commit o cambios ya hecho.',
'pt_BR': 'Não há commits para o rebase! São todos commits de merge ou mudanças já aplicadas',
'gl' : '¡Non hai commits para o rebase! Son todos commits de merge ou cambios xa aplicados',
'fr_FR': 'Aucun commit à rebaser ! C\'est soit un commit de merge, soit des modifications déjà appliquées',
'ru_RU': 'Нет коммитов для rebase! Все в коммите слияния или изменения уже применены',
'uk': 'Нема комітів для rebase! Все в коміті злиття (merge commit) чи зміни вже застосовані',
'ko': 'rebase를 하기 위한 커밋이 없습니다! 모든 커밋과 변경 사항들의 병합은 이미 적용되었습니다.'
},
///////////////////////////////////////////////////////////////////////////
'git-result-nothing': {
'__desc__': 'The message that explains the result of a git command',
'en_US': 'Nothing to do...',
'de_DE': 'Nichts zu tun ...',
'zh_CN': '什么也没发生...',
'zh_TW': '沒什麼事情要做...',
'es_AR': 'Nada para hacer...',
'es_ES': 'Nada para hacer...',
'pt_BR': 'Nada a ser feito...',
'gl' : 'Nada para facer...',
'fr_FR': 'Rien à effectuer…',
'ru_RU': 'Нечего выполнять...',
'uk': 'Нічого виконувати...',
'ko': '할게 없습니다 ...'
},
///////////////////////////////////////////////////////////////////////////
'git-result-fastforward': {
'__desc__': 'The message that explains the result of a git command',
'en_US': 'Fast forwarding...',
'de_DE': 'Fast forward...',
'zh_CN': '快速前进...',
'zh_TW': '快速前進...',
'es_AR': 'Fast forwardeando...',
'es_ES': 'Avanzando rápidamente...',
'pt_BR': 'Fast forward...',
'gl' : 'Fast forward...',
'fr_FR': 'En avance rapide…',
'ru_RU': 'Выполняю Fast forward...',
'uk': 'Виконую Fast forward',
'ko': 'Fast forward 중입니다...'
},
///////////////////////////////////////////////////////////////////////////
'git-result-uptodate': {
'__desc__': 'The message that explains the result of a git command',
'en_US': 'Branch already up-to-date',
'de_DE': 'Branch ist bereits aktuell',
'zh_CN': '分支已经是最新啦',
'zh_TW': 'branch 已經是最新啦',
'es_AR': 'Rama actualmente actualizada',
'es_ES': 'La rama ya se ha actualizado.',
'pt_BR': 'Ramo já atualizado',
'gl' : 'Rama xa actualizada',
'fr_FR': 'Branche déjà à jour',
'ru_RU': 'Ветка уже обновлена',
'uk': 'Гілку вже оновлено',
'ko': '브랜치가 이미 최신 상태입니다.'
},
///////////////////////////////////////////////////////////////////////////
'git-error-exist': {
'__desc__': 'One of the error messages for git',
'en_US': 'The ref {ref} does not exist or is unknown',
'de_DE': 'Die Ref {ref} existiert nicht oder ist unbekannt',
'zh_CN': '引用 {ref} 不存在。',
'zh_TW': '索引 {ref} 不存在,或者找不到。',
'es_AR': 'La referencia {ref} no existe o es desconocida',
'es_ES': 'La referencia {ref} no existe o es desconocida',
'pt_BR': 'A referência {ref} não existe ou é desconhecida',
'gl' : 'A referencia {ref} non existe ou é descoñecida',
'fr_FR': 'La référence {ref} n\'existe pas ou est inconnue',
'ru_RU': 'Ссылка {ref} не существует или неизвестна',
'uk': 'Посилання {ref} не існує чи невідоме',
'ko': '{ref} 참조가 존재하지 않거나 알 수 없습니다.'
},
///////////////////////////////////////////////////////////////////////////
'git-error-relative-ref': {
'__desc__': 'One of the error messages for git',
'en_US': 'Commit {commit} does not have a {match}',
'de_DE': 'Commit {commit} hat kein {match}',
'zh_CN': '{commit} 提交并没有 {match}',
'zh_TW': 'commit {commit} 並沒有 {match}',
'es_AR': 'El commit {commit} no tiene un {match}',
'es_ES': 'El commit {commit} no tiene un {match}',
'pt_BR': 'O commit {commit} não tem um {match}',
'gl' : 'O commit {commit} non ten un {match}',
'fr_FR': 'Le commit {commit} n\'a pas de correspondance {match}',
'ru_RU': 'Коммит {commit} не содержит {match}',
'uk': 'Коміт {commit} не містить {match}',
'ko': '커밋 {commit}은 {match}를 가지고 있지 않습니다.'
},
///////////////////////////////////////////////////////////////////////////
'git-warning-detached': {
'__desc__': 'One of the warning messages for git',
'en_US': 'Warning!! Detached HEAD state',
'de_DE': 'Achtung! Detached HEAD Zustand',
'zh_CN': '警告!现在是分离 HEAD 状态',
'zh_TW': '注意喔!現在的狀態是分離 Head',
'es_AR': '¡Cuidado! Modo de detached HEAD',
'es_ES': '¡Cuidado! Modo de HEAD separado (detached HEAD)',
'pt_BR': 'Cuidado! Modo Detached HEAD',
'gl' : '¡Coidado! Modo Detached HEAD',
'fr_FR': 'Attention ! HEAD est détaché',
'ru_RU': 'Внимание! Репозиторий в состоянии detached HEAD, то есть не находится ни на какой ветке!',
'uk': 'Увага! Репозиторій в стані detached HEAD, тобто не знаходиться в жодній гілці!',
'ko': '주의! 분리된 HEAD 상태'
},
///////////////////////////////////////////////////////////////////////////
'git-warning-add': {
'__desc__': 'One of the warning messages for git',
'en_US': 'No need to add files in this demo',
'de_DE': 'In dieser Demo müssen keine Dateien hinzugefügt werden',
'zh_CN': '此程序中不需要添加文件',
'zh_TW': '此 demo 中不需要再加入檔案',
'es_AR': 'No es necesario hacer add a los archivos en esta demo',
'es_ES': 'No es necesario agregar los archivos en esta demo',
'pt_BR': 'Não é necessário adicionar arquivos neste demo',
'gl' : 'Non é necesario incluír arquivos nesta demo',
'fr_FR': 'Aucun besoin d\'ajouter des fichiers dans cette démo',
'ru_RU': 'Это демо не оперирует файлами',
'uk': 'Не потрібно додавати файли для цього демо',
'ko': '이 데모에서는 파일을 추가할 필요가 없습니다.'
},
///////////////////////////////////////////////////////////////////////////
'git-error-options': {
'__desc__': 'One of the error messages for git',
'en_US': 'Those options you specified are incompatible or incorrect',
'de_DE': 'Die angegebenen Optionen sind inkompatibel oder falsch',
'zh_CN': '你所指定的参数不兼容或者不准确',
'zh_TW': '您指定了不相容或錯誤的選項',
'es_ES': 'Las opciones que especificaste son incompatibles o incorrectas.',
'es_AR': 'No es necesario hacer add a los archivos en esta demo',
'pt_BR': 'As opções que você especificou são incompatíveis ou incorretas',
'gl' : 'As opcións que especificaches son incompatibles ou incorrectas',
'fr_FR': 'Les options que vous avez spécifiées sont incompatibles ou incorrectes',
'ru_RU': 'Неправильные опции',
'uk': 'Опції, які ти ввів, або некорректні або не підтримуються',
'ko': '당신이 지정한 그 옵션들은 호환되지 않거나 올바르지 않습니다.'
},
///////////////////////////////////////////////////////////////////////////
'git-error-already-exists': {
'__desc__': 'One of the error messages for git',
'en_US': 'The commit {commit} already exists in your changes set, aborting!',
'de_DE': 'Der Commit {commit} existiert bereit, Abbruch!',
'zh_CN': '{commit} 提交已经存在于你的改动集里,已忽略!',
'zh_TW': 'commit {commit} 已經在你的修改的集合裡,正在停止!',
'es_AR': 'El commit {commit} ya existe en tus cambios, ¡abortando!',
'es_ES': 'El commit {commit} ya existe en tus cambios, ¡abortando!',
'pt_BR': 'O commit {commit} já existe nas suas mudanças, abortando!',
'gl' : 'O commit {commit} xa existe nos seus cambios, ¡abortando!',
'fr_FR': 'Le commit {commit} existe déjà dans votre ensemble de modifications, opération avortée !',
'ru_RU': 'Коммит {commit} существует, отменяю!',
'uk': 'Коміт {commit} вже існує в твоєму change set, відміна!',
'ko': '커밋 {commit}은 이미 당신의 변경 내역에 존재합니다. 중단!'
},
///////////////////////////////////////////////////////////////////////////
'git-error-reset-detached': {
'__desc__': 'One of the error messages for git',
'en_US': 'Can\'t reset in detached head! Use checkout if you want to move',
'de_DE': 'Kann im Detached Head Zustand kein reset ausführen! Bitte checkout zum Bewegen benutzen',
'zh_CN': '不能在分离的 HEAD 里重置!用 checkout 吧',
'zh_TW': '不能在分離 HEAD 的狀態中重來!用 checkout 來移動吧',
'es_AR': 'No podés hacer reset en el modo detached. Usá checkout si querés moverte',
'es_ES': 'No puedes hacer reset en el modo separado. Usa checkout si quieres moverte.',
'pt_BR': 'Não se pode fazer reset no modo detached. Use checkout se quiser se mover',
'gl' : 'Non se pode facer reset no modo detached. Use checkout se te queres mover',
'fr_FR': 'On ne peut pas effectuer un reset quand HEAD est détaché. Utilisez checkout pour déplacer',
'ru_RU': 'Это невозможно в режиме detached HEAD! Используйте checkout!',
'uk': 'Неможливо зробити reset в стані detached head! Використовуй checkout якщо хочеш змінити розташування',
'ko': '분리된 HEAD에서 reset할 수 없습니다. 만약 이동시키기를 원한다면 checkout을 사용하세요.'
},
///////////////////////////////////////////////////////////////////////////
'git-warning-hard': {
'__desc__': 'One of the warning messages for git',
'en_US': 'The default behavior for resets on LearnGitBranching is a --hard, so feel free to omit ' +
'that option if you get tired of typing it out in our lessons. Just remember that the default ' +
'behavior on actual Git is --mixed.',
'de_DE': 'Das Standardverhalten in dieser Demo ist --hard, du kannst die Option auch weglassen!',
'zh_CN': '在本程序中默认的行为是 --hard 硬重置,可以尽情省略掉那个选项以避免麻烦!但是要记录 Git 中默认的是 --mixed。',
'zh_TW': '預設的行為是 --hard reset,儘量省略掉那個選項吧!',
'es_AR': 'El comportamiento default es un --hard reset, sentite libre de omitir esa opción!',
'es_ES': 'El comportamiento default para reajustes es --hard, pero siéntete libre de omitir esa ' +
'opción si te cansas de escribirla en nuestras lecciones. Recuerda quepor defecto el comportamiento en GitHub es --mixed.',
'pt_BR': 'O comportamento padrão é um reset --hard, fique livre para omitir essa opção!',
'gl' : 'O comportamente por defecto é un reset --hard, Lembra que por defecto en GitHub é --mixed.',
'fr_FR': 'Le comportement par défaut est un --hard reset, soyez libre d\'omettre cette option !',
'ru_RU': 'По умолчанию будет выполнен --hard reset, эту опцию можно опускать!',
'uk': 'На LearnGitBranching reset по замовчуванню використовує --hard, тому цю опцію ' +
'можна пропустити, якщо ти втомився її набирати щоразу. Тільки запам’ятай, що по замовчуванню ' +
'звичайний git reset використовує --mixed',
'ko': 'LearnGitBranching에서 reset의 기본 설정은 옵션은 --hard입니다. 우리 레슨에서는 이 옵션을 생략해도 됩니다. 다만 실제 Git의 기본 설정 옵션은 --mixed라는것만 기억하세요.'
},
///////////////////////////////////////////////////////////////////////////
'git-error-staging': {
'__desc__': 'One of the error messages for git',
'en_US': 'There is no concept of adding / staging files, so that option or ' +
'command is invalid!',
'de_DE': 'In dieser Demo gibt es kein Hinzufügen / Vormerken von Dateien, dieser Befehl ist daher ungültig!',
'zh_CN': '没有添加、缓存文件的必要,所以该选项或者命令是不合法的。',
'zh_TW': '沒有加入、或者暫存 (staging) 文件的必要,所以改選項或者命令是不合法的。',
'es_AR': 'No existe el concepto de agregar/indexar cambios, así que esa opción o comando es inválido',
'es_ES': 'No existe el concepto de agregar/indexar cambios, así que esa opción o comando es inválido.',
'pt_BR': 'Não existe o conceito de adicionar/indexar mudanças, de forma que essa opção ou comando é inválida',
'gl' : 'Non existe o concepto de agregar/indexar cambios, así que esa opción ou comando é inválido.',
'fr_FR': 'Il n\'y a pas le concept d\'ajouter / mettre en staging, donc cette option ou commande est invalide',
'ru_RU': 'Это демо не работает с файлами, так что git add не нужен!',
'uk': 'В цьому демо немає можливості додати файл до робочої копії чи до стейджингу, тому ця опція чи команда некоректна чи не підтримується',
'ko': '여기엔 파일을 추가하거나 스테이징한다는 개념이 없습니다. 따라서 그 옵션 또는 명령어는 유효하지 않습니다.'
},
///////////////////////////////////////////////////////////////////////////
'git-revert-msg': {
'__desc__': 'Message for reverting git command',
'en_US': 'Reverting {oldCommit}: {oldMsg}',
'de_DE': 'Reverte {oldCommit}: {oldMsg}',
'zh_CN': '撤销 {oldCommit}:{oldMsg}',
'zh_TW': '還原 {oldCommit}:{oldMsg}',
'es_AR': 'Revirtiendo {oldCommit}: {oldMsg}',
'es_ES': 'Volviendo a {oldCommit}: {oldMsg}',
'pt_BR': 'Revertendo {oldCommit}: {oldMsg}',
'gl' : 'Revertindo {oldCommit}: {oldMsg}',
'fr_FR': 'Revert {oldCommit}: {oldMsg}',
'ru_RU': 'Откатываю {oldCommit}: {oldMsg}',
'uk': 'Повертаю {oldCommit}: {oldMsg}',
'ko': '{oldCommit}:{oldMsg}를 복구중입니다.'
},
///////////////////////////////////////////////////////////////////////////
'git-error-args-many': {
'__desc__': 'One of the error messages for git',
'en_US': 'I expect at most {upper} argument(s) for {what}',
'de_DE': 'Ich benötige maximal {upper} Argument(e) für {what}',
'zh_CN': '{what} 期望最多 {upper} 个参数',
'zh_TW': '{what} 期望最多 {upper} 個參數',
'es_AR': 'Espero como máximo {upper} parámetros para {what}',
'es_ES': 'Espero al máximo {upper} parámetros para {what}.',
'pt_BR': 'Espero no máximo {upper} parâmetros para {what}',
'gl' : 'Espero ó máximo {upper} parámetros para {what}',
'fr_FR': 'J\'attends au plus {upper} argument(s) pour {what}',
'ru_RU': 'Ожидается максимум {upper} аргумент(ов) для {what}',
'uk': 'Я очікую максимум {upper} аргумент(ів) для {what}',
'ko': '{what}을 위해 최대 {upper}개의 인자를 받습니다.'
},
///////////////////////////////////////////////////////////////////////////
'git-error-args-few': {
'__desc__': 'One of the error messages for git',
'en_US': 'I expect at least {lower} argument(s) for {what}',
'de_DE': 'Ich benötige mindestens {lower} Argument(e) für {what}',
'zh_CN': '{what} 期望最少 {lower} 个参数',
'zh_TW': '{what} 期望最少 {lower} 個參數',
'es_AR': 'Espero al menos {lower} parámetros para {what}',
'es_ES': 'Espero al menos {lower} parámetros para {what}.',
'pt_BR': 'Espero pelo menos {lower} parâmetros para {what}',
'gl' : 'Agardo polo menos {lower} parámetros para {what}',
'fr_FR': 'J\'attends au moins {lower} argument(s) pour {what}',
'ru_RU': 'Ожидается как минимум {lower} аргументов для {what}',
'uk': 'Я очікую як мінімум {lower} аргумент(ів) для {what}',
'ko': '{what}을 위해 최소 {lower}개의 인자를 받습니다.'
},
///////////////////////////////////////////////////////////////////////////
'git-error-no-general-args': {
'__desc__': 'One of the error messages for git',
'en_US': 'That command accepts no general arguments',
'de_DE': 'Dieser Befehl akzeptiert keine allgemeinen Argumente',
'zh_CN': '该命令不接收参数',
'zh_TW': '該指令不接受一般參數',
'es_AR': 'Ese comando no acepta parámetros comunes',
'es_ES': 'Ese comando no acepta parámetros generales.',
'pt_BR': 'Este comando não aceita parâmetros gerais',
'gl' : 'Este comando non acepta parámetros xeráis',
'fr_FR': 'Cette commande n\'accepte aucun argument général',
'ru_RU': 'Это команда без аргументов',
'uk': 'Ця команда не приймає загальних аргументів',
'ko': '그 명령어는 일반적으로 인자를 받지 않습니다.'
},
///////////////////////////////////////////////////////////////////////////
'copy-tree-string': {
'__desc__': 'The prompt to copy the tree when sharing',
'en_US': 'Copy the tree string below',
'de_DE': 'Kopiere die folgende Baum-Zeichenkette',
'zh_CN': '拷贝下面的树字符串',
'zh_TW': '複製下方的樹狀字串',
'es_AR': 'Copiá el código de acá abajo',
'es_ES': 'Copia el código que sigue.',
'pt_BR': 'Copie o código abaixo',
'gl' : 'Copie o código abaixo',
'fr_FR': 'Copiez la chaîne d\'arbre ci-dessous',
'ru_RU': 'Скопируй текст ниже',
'uk': 'Скопіюй рядок дерева нижче',
'ko': '다음 트리 문자열을 복사하세요.'
},
///////////////////////////////////////////////////////////////////////////
'learn-git-branching': {
'__desc__': 'The title of the app, with spaces',
'en_US': 'Learn Git Branching',
'de_DE': 'Learn Git Branching',
'ja': '日本語版リポジトリ',
'zh_CN': '学习 Git 分支',
'zh_TW': '學習 git 分支',
'es_AR': 'Aprendé a Branchear en Git',
'es_ES': 'Aprende Git Branching',
'pt_BR': 'Learn Git Branching',
'gl' : 'Aprende Git Branching',
'fr_FR': 'Apprenez Git Branching',
'ru_RU': 'Изучаем ветвление в git',
'uk': 'Learn Git Branching',
'ko': '깃 브랜칭을 배워봅시다.'
},
///////////////////////////////////////////////////////////////////////////
'select-a-level': {
'__desc__': 'The prompt to select a level on the drop down view',
'en_US': 'Select a level',
'de_DE': 'Level auswählen',
'zh_CN': '选择一关',
'zh_TW': '選擇其中一關',
'es_AR': 'Seleccioná un nivel',
'es_ES': 'Selecciona un nivel',
'pt_BR': 'Selecione um nível',
'gl' : 'Selecciona un nivel',
'fr_FR': 'Choisissez un niveau',
'ru_RU': 'Выбери уровень',
'uk': 'Обери рівень',
'ko': '레벨을 선택하세요.'
},
///////////////////////////////////////////////////////////////////////////
'main-levels-tab': {
'__desc__': 'The name of main levels tab on the drop down view',
'en_US': 'Main',
'de_DE': 'Haupt',
'zh_CN': '主要',
'zh_TW': '主要',
'es_ES': 'Principal',
'gl' : 'Principal',
'ru_RU': 'Основы',
'uk' : 'Основи',
'ko': '메인'
},
///////////////////////////////////////////////////////////////////////////
'remote-levels-tab': {
'__desc__': 'The name of remote levels tab on the drop down view',
'en_US': 'Remote',
'de_DE': 'Remote',
'zh_CN': '远程',
'zh_TW': '遠端',
'es_ES': 'Remota',
'gl' : 'Remota',
'ru_RU': 'Удаленные репозитории',
'uk' : 'Віддалені репозиторії',
'ko' : '원격'
},
///////////////////////////////////////////////////////////////////////////
'branch-name-short': {
'__desc__': 'When branch names get too long, we need to truncate them. This is the warning for that',
'en_US': 'Sorry, we need to keep branch names short for the visuals. Your branch name was truncated to 9 characters, resulting in "{branch}"',
'de_DE': 'Tut mir leid, aber aus Gründen der Darstellung müssen wir die Branch-Namen kurz halten. Dein Branch-Name wurde auf 9 Zeichen gekürzt und heißt daher jetzt "{branch}"',
'zh_CN': '抱歉,为了显示的需要,我们需要一个短些的分支名称。您使用的名称将被截断到9个字符,即 "{branch}"',
'zh_TW': '抱歉,為了顯示的需要,我們需要一個短一點的 branch 名稱。您使用的將會被截斷到剩下9個字元,即"{branch}"',
'es_AR': 'Perdón, necesitamos mantener los nombres de los branches cortos para visualizarlos. El nombre de tu rama se truncó a 9 caracteres, resultando en "{branch}"',
'es_ES': 'Perdón, necesitamos mantener los nombres de los branches cortos para visualizarlos. El nombre de tu rama se truncó a 9 caracteres, resultando en "{branch}"',
'pt_BR': 'Desculpe, precisamos manter os nomes dos ramos curtos para visualizá-los. O nome do seu ramo foi truncado para 9 caracteres, resultando em "{branch}"',
'gl' : 'Desculpe, precisamos manter os nomes das ramas curtas para poder velas. O nome da súa rama foi truncada a 9 letras, resultado en "{branch}"',
'fr_FR': 'Désolé, nous devons garder les noms de branches courts pour la visualisation. Votre nom de branche a été tronqué à 9 caractères, devenant "{branch}"',
'ru_RU': 'Для наглядности нам нужно сохранять имена веток короткими. Твоё название сокращено до 9 символов и теперь это "{branch}"',
'uk': 'Вибач, нам потрібно щоб ім’я гілок було як можна коротше для наглядності. Твоє ім’я гілки було скорочене до 9 літер й тепер це "{branch}"',
'ko': '미안하지만, 우리는 시각적으로 더 좋게 보기위해 짧은 브랜치명이 필요합니다. 당신의 브랜치명은 9자리로 잘라 "{branch}"로 만들었습니다.'
},
///////////////////////////////////////////////////////////////////////////
'bad-branch-name': {
'__desc__': 'When the user enters a branch name thats not ok',
'en_US': 'That branch name "{branch}" is not allowed!',
'de_DE': 'Der Branch-Name "{branch}" ist nicht erlaubt!',
'zh_CN': '不能给分支起这个名字 "{branch}"',
'zh_TW': '不能给 branch 起這個名字 "{branch}"',
'es_AR': 'El nombre "{branch}" no está permitido para los branches',
'es_ES': 'El nombre "{branch}" es prohibido para nombrar una rama.',
'pt_BR': 'Um ramo não pode ser chamado de "{branch}"!',
'gl' : 'Unha rama non pode ser chamada "{branch}',
'fr_FR': 'Ce nom de branche "{branch}" n\'est pas autorisé',
'ru_RU': 'Название для ветки "{branch}" недопустимо!',
'uk': 'Назва гілки "{branch}" є недопустимою',
'ko': '"{branch}"라는 브랜치명은 사용할 수 없습니다.'
},
///////////////////////////////////////////////////////////////////////////
'bad-tag-name': {
'__desc__': 'When the user enters a tag name thats not ok',
'en_US': 'That tag name "{tag}" is not allowed!',
'zh_CN': '该标签名 “{tag}” 不被接受。',
'zh_TW': '該標籤名 “{tag}” 不被接受。',
'es_AR': 'El nombre "{tag}" no está permitido para los tags',
'es_ES': 'El nombre "{tag}" es prohibido para nombrar un tag.',
'pt_BR': 'Uma tag não pode ser chamada de "{tag}"!',
'gl' : 'Unha etiqueta non pode ser chamada "{tag}"',
'de_DE': 'Der Tag-Name "{tag}" ist nicht erlaubt!',
'fr_FR': 'Le nom de tag "{tag}" n\'est pas autorisé',
'ru_RU': 'Название для тега "{tag}" недопустимо!',
'uk': 'Назва тегу "{tag}" є недопустимою',
'ko': '"{tag}"라는 태그명은 사용할 수 없습니다.'
},
///////////////////////////////////////////////////////////////////////////
'option-not-supported': {
'__desc__': 'When the user specifies an option that is not supported by our demo',
'en_US': 'The option "{option}" is not supported!',
'de_DE': 'Die Option "{option}" wird nicht unterstützt!',
'zh_CN': '不支持选项 "{option}"',
'zh_TW': '不支援的選項 "{option}"',
'es_AR': 'La opción {option} no está soportada',
'es_ES': 'La opción {option} no compatible con esta demo.',
'pt_BR': 'A opção {option} não é suportada',
'gl' : 'A opción {option} non está soportada',
'fr_FR': 'L\'option "{option}" n\'est pas supportée',
'ru_RU': 'Опция "{option}" недопустима!',
'uk': 'Опція "{option}" не підтримується!',
'ko': '"{option}"(이)라는 옵션은 지원하지 않습니다.'
},
///////////////////////////////////////////////////////////////////////////
'git-usage-command': {
'__desc__': 'The line that shows how to format a git command',
'en_US': 'git <command> [<args>]',
'de_DE': 'git <Befehl> [<Argumente>]',
'zh_CN': 'git <命令> [<参数>]',
'zh_TW': 'git <指令> [<參數>]',
'es_AR': 'git <comando> [<parametros>]',
'es_ES': 'git <comando> [<parametros>]',
'pt_BR': 'git <comando> [<parâmetros>]',
'gl' : 'git <comando> [<parámetros>]',
'fr_FR': 'git <commande> [<arguments>]',
'ru_RU': 'git <команда> [<аргументы>]',
'uk': 'git <команда> [<аргументи>]',
'ko': 'git <명령어> [<인자들>]'
},
///////////////////////////////////////////////////////////////////////////
'git-supported-commands': {
'__desc__': 'In the git help command, the header above the supported commands',
'en_US': 'Supported commands:',
'de_DE': 'Unterstützte Befehle:',
'zh_CN': '支持的命令有:',
'zh_TW': '支援的指令有:',
'es_AR': 'Comandos soportados:',
'es_ES': 'Comandos compatibles:',
'pt_BR': 'Comandos suportados:',
'gl' : 'Comandos soportados:',
'fr_FR': 'Commandes supportées',
'ru_RU': 'Поддерживаемые команды',
'uk': 'Допустимі команди',
'ko': '지원되는 명령어들:'
},
///////////////////////////////////////////////////////////////////////////
'git-usage': {
'__desc__': 'In the dummy git output, the header before showing all the commands',
'en_US': 'Usage:',
'de_DE': 'Benutzung:',
'zh_CN': '使用:',
'zh_TW': '用法:',
'es_AR': 'Uso:',
'es_ES': 'Uso:',
'pt_BR': 'Uso:',
'gl' : 'Uso:',
'fr_FR': 'Utilisation :',
'ru_RU': 'Использование:',
'uk': 'Використання:',
'ko': '사용법'
},
///////////////////////////////////////////////////////////////////////////
'git-version': {
'__desc__': 'The git version dummy output, kind of silly. PCOTTLE is my unix name but feel free to put yours instead',
'en_US': 'Git Version PCOTTLE.1.0',
'de_DE': 'Git Version PCOTTLE.1.0.jbr',
'zh_CN': 'Git 版本 PCOTTLE.1.0',
'zh_TW': 'Git 版本 PCOTTLE.1.0',
'es_AR': 'Git Versión PCOTTLE.1.0',
'es_ES': 'Git Versión PCOTTLE.1.0',
'pt_BR': 'Git versão PCOTTLE.1.0',
'gl' : 'Git versión PCOTTLE.1.0',
'fr_FR': 'Git version PCOTTLE.1.0',
'ru_RU': 'Версия git PCOTTLE.1.0',
'uk': 'Версія git PCOTTLE.1.0',
'ko': 'Git Version PCOTILE.1.0'
},
///////////////////////////////////////////////////////////////////////////
'flip-tree-command': {
'__desc__': 'when the tree is being flipped',
'en_US': 'Flipping tree...',
'zh_CN': '翻转树中...',
'zh_TW': '翻轉樹中...',
'es_AR': 'Invirtiendo el árbol...',
'es_ES': 'Invirtiendo el árbol...',
'pt_BR': 'Invertendo a árvore...',
'gl' : 'Invirtindo a árbore...',
'fr_FR': 'Inversion de l\'arbre...',
'ru_RU': 'Переворачиваю дерево...',
'uk': 'Перевертаю дерево...',
'ko': '트리 뒤집는중...'
},
///////////////////////////////////////////////////////////////////////////
'refresh-tree-command': {
'__desc__': 'when the tree is visually refreshed',
'en_US': 'Refreshing tree...',
'de_DE': 'Aktualisiere Baum ...',
'zh_CN': '正在刷新树结构...',
'zh_TW': '正在更新樹狀結構...',
'es_AR': 'Refrezcando el árbol...',
'es_ES': 'Actualizando el árbol...',
'pt_BR': 'Atualizando a árvore...',
'gl' : 'Actualizando a árbore...',
'fr_FR': 'Actualisation de l\'arbre…',
'ru_RU': 'Обновляю дерево...',
'uk': 'Оновлюю дерево...',
'ko': '트리 다시 불러오는중...'
},
///////////////////////////////////////////////////////////////////////////
'locale-command': {
'__desc__': 'when the locale is set to something',
'en_US': 'Locale set to {locale}',
'de_DE': 'Locale auf {locale} gesetzt',
'zh_CN': '语言更改为 {locale}',
'zh_TW': '語系設為 {locale}',
'es_AR': 'Localización actualizada a {locale}',
'es_ES': 'Idioma puesto a {locale}',
'pt_BR': 'Língua trocada para {locale}',
'gl' : 'Cambiado o idioma a {locale}',
'fr_FR': 'Langue changée à {locale}',
'ru_RU': 'Локаль теперь равна {locale}',
'uk': 'Локаль тепер дорівнює {locale}',
'ko': '로케일이 {locale}로 설정되었습니다.'
},
///////////////////////////////////////////////////////////////////////////
'locale-reset-command': {
'__desc__': 'when the locale is reset',
'en_US': 'Locale reset to default, which is {locale}',
'de_DE': 'Locale auf Standard zurückgesetzt, also {locale}',
'zh_CN': '语言重置为默认的 {locale}',
'zh_TW': '還原為預設語系 {locale}',
'es_AR': 'Localización vuelta al default, que es {locale}',
'es_ES': 'Idioma reajustado a su valor por defecto ({locale})',
'pt_BR': 'Língua retornada para a padrão, que é {locale}',
'gl' : 'Lingua reaxustada ó seu valor por defecto {locale}',
'fr_FR': 'Langue remise par défaut, qui est {locale}',
'ru_RU': 'Локаль сброшена. Теперь она равна {locale}',
'uk': 'Локаль скинута. Тепер вона дорівнює {locale}',
'ko': '로케일이 {locale}로 초기화 되었습니다.'
},
///////////////////////////////////////////////////////////////////////////
'show-command': {
'__desc__': 'command output title from "show"',
'en_US': 'Please use one of the following commands for more info:',
'zh_TW': '請使用下列其中一個指令取得更多資訊:',
'zh_CN': '请使用以下命令以了解更多:',
'de_DE': 'Bitte benutze einen der folgenden Befehle um mehr Informationen zu bekommen:',
'es_AR': 'Usá alguno de estos comandos para tener más información:',
'es_ES': 'Por favor usa uno de los siguientes comandos para más información:',
'pt_BR': 'Use algum destes comandos para ter mais informações:',
'gl' : 'Usa algún destes comandos para ter máis información:',
'fr_FR': 'Merci d\'utiliser une des commandes suivantes pour obtenir plus d\'informations',
'ru_RU': 'Для получения большей информации используй следующие команды:',
'uk': 'Щоб отримати більше інформації використовуй наступні команди:',
'ko': '더 많은 정보를 위해 다음 명령어들중 하나를 사용하세요.'
},
///////////////////////////////////////////////////////////////////////////
'show-all-commands': {
'__desc__': 'command output title from "show commands"',
'en_US': 'Here is a list of all the commmands available:',
'zh_TW': '這份清單列出所有可用指令:',
'zh_CN': '该列表列出了所有可用的指令:',
'de_DE': 'Hier ist eine Liste aller verfügbarer Befehle:',
'es_AR': 'Esta es una lista de los comandos disponibles:',
'es_ES': 'Esta es una lista de todos los comandos disponibles:',
'pt_BR': 'Esta é uma lista dos comandos disponíveis:',
'gl' : 'Esta é unha lista dos comando dispoñibles:',
'fr_FR': 'Ci-dessous est la liste de toutes les commandes disponibles :',
'ru_RU': 'Вот все поддерживаемуе команды:',
'uk': 'Ось список всіх можливих команд:',
'ko': '여기에 사용 가능한 모든 명령어들의 리스트가 있습니다.'
},
///////////////////////////////////////////////////////////////////////////
'cd-command': {
'__desc__': 'dummy command output for the command in the key',
'en_US': 'Directory changed to "/directories/dont/matter/in/this/demo"',
'de_DE': 'Verzeichnis gewechselt zu "/verzeichnisse/sind/in/dieser/demo/latte"',
'zh_CN': '目录切换到 "/directories/dont/matter/in/this/demo"',
'zh_TW': '目錄切換到 "/directories/dont/matter/in/this/demo"',
'es_AR': 'Directorio cambiado a "/los/directorios/no/importan/en/esta/demo"',
'es_ES': 'Directorio cambiado a "/los/directorios/no/importan/en/esta/demo"',
'pt_BR': 'Diretório mudado para "/diretorios/nao/importam/neste/demo"',
'gl' : 'Directorio cambiado a "/os/directorios/non/importan/nesta/demo"',
'fr_FR': 'Répertoire changé à "/directories/dont/matter/in/this/demo" (les répertoires ne servent à rien dans cette démo)',
'ru_RU': 'Директория изменена на "/директории/не/важны/в/этом/демо"',
'uk': 'Директорія змінена на "/директорії/не/мають/значення/в/цьому/демо"',
'ko': '디렉토리가 "/directories/dont/matter/in/this/demo"로 변경되었습니다.'
},
///////////////////////////////////////////////////////////////////////////
'ls-command': {
'__desc__': 'Dummy command output for the command in the key',
'en_US': 'DontWorryAboutFilesInThisDemo.txt',
'de_DE': 'VergissDateienInDieserDemo.txt',
'zh_CN': '在本程序中无须考虑文件问题.txt',
'zh_TW': 'DontWorryAboutFilesInThisDemo.txt (譯註:在 demo 裡不用擔心檔案)',
'es_AR': 'NoTePreocupesPorLosArchivosEnEstaDemo.txt',
'es_ES': 'NoTePreocupesPorLosArchivosEnEstaDemo.txt',
'pt_BR': 'NaoSePreocupeComNomesDeArquivoNesteDemo.txt',
'gl' : 'NonTePreocupesPolosCambiosNestaDemo.txt',
'fr_FR': 'DontWorryAboutFilesInThisDemo.txt (ne vous préoccupez pas des noms de fichier dans cette démo)',
'ru_RU': 'НеНадоЗаботитьсяОФайлахВЭтомДемо.txt',
'uk': 'ЗабийНаФайлиВЦьомуДемо.txt',
'ko': 'DontWorryAboutFilesInThisDemo.txt (이_데모에서_파일에_대한_걱정은_하지마세요.txt)'
},
'mobile-alert': {
'__desc__': 'When someone comes to the site on a mobile device, they can not input commands so this is a nasty alert to tell them',
'en_US': 'LGB can\'t receive input on mobile, visit on desktop! it\'s worth it :D',
'de_DE': 'LGB ist nicht mit mobilen Endgeräten kompatibel, nutz es vom Desktop! Es lohnt sich :D',
'zh_CN': '无法在移动设备/平板上调出键盘 :( 请试试桌面版 :D',
'zh_TW': '無法在行動裝置上叫出鍵盤,請改用桌面版!',
'es_AR': 'LGB no puede recibir comandos en dispositivos móviles. Visitanos desde una desktop, ¡lo vale! :D',
'es_ES': 'LGB no puede recibir comandos en dispositivos móviles. Visítanos en una computadora de escritorio, ¡lo vale! :D',
'pt_BR': 'Provavelmente você não vai conseguir digitar comandos no celular, neste caso tente acessar de um computador',
'gl' : 'LGB non pode recibir os comandos nos dispositivos móbiles. Visítanos dende un ordenador de escritorio, ¡paga a pena! :D',
'fr_FR': 'Impossible de faire apparaître le clavier sur mobile / tablette :( Essayez de passer sur un ordinateur de bureau :D',
'ru_RU': 'Мобильные не поддерживаются, зайди с компьютера!',
'uk': 'LGB не підтримує ввід тексту з мобільного, зайди з компьютера! Це цього варте!',
'ko': 'LGB는 모바일에서 입력을 받을 수 없습니다. 데스크톱으로 접속하세요! 이것은 가치가 있습니다. :D'
},
///////////////////////////////////////////////////////////////////////////
'share-tree': {
'__desc__': 'When you export a tree, we want you to share the tree with friends',
'en_US': 'Share this tree with friends! They can load it with "import tree"',
'de_DE': 'Teile diesen git-Baum mit Freunden! Sie können ihn mit "import tree" laden',
'zh_CN': '与你的好友分享提交树!他们可以用 "import tree" 加载它',
'zh_TW': '與你的好友分享這棵樹!他們可以用 "import tree" 來載入它',
'es_AR': '¡Compartí este árbol con amigos! Pueden cargarlo con "import tree"',
'es_ES': '¡Comparte este árbol con amigos! Pueden cargarlo con "import tree"',
'pt_BR': 'Compartilhe esta árvore com seus amigos! Eles podem carregá-la com "import tree"',
'gl' : '¡Comparte esta árbore cos teus amigos! Eles poden cargalo con "import tree"',
'fr_FR': 'Partagez cet arbre avec vos amis ! Ils peuvent le charger avec "import tree"',
'ru_RU': 'Поделись деревом с друзьями! Они могут загрузить его при помощи "import tree"',
'uk': 'Поділись цим деревом з друзями! Вони зможуть його завантажити за допомогою "import tree"',
'ko': '친구들과 이 트리를 공유하세요! 그들은 "import tree"를 사용해 이를 로드할 수 있습니다.'
},
///////////////////////////////////////////////////////////////////////////
'paste-json': {
'__desc__': 'When you are importing a level or tree',
'en_US': 'Paste a JSON blob below!',
'de_DE': 'Füg einen JSON-Blob unten ein!',
'zh_CN': '在下边粘贴一个 JSON 串',
'zh_TW': '在下方貼上一串 JSON',
'es_AR': '¡Pegá un blob JSON abajo!',
'es_ES': '¡Pega un blob JSON abajo!',
'pt_BR': 'Cole o JSON abaixo!',
'gl' : 'Pega un JSON abaixo!',
'fr_FR': 'Collez un blob JSON ci-dessous !',
'ru_RU': 'Вставь JSON ниже!',
'uk': 'Встав JSON нижче!',
'ko': '아래에 JSON blob을 붙여넣으세요.'
},
///////////////////////////////////////////////////////////////////////////
'solved-map-reset': {
'__desc__': 'When you reset the solved map to clear your solved history, in case someone else wants to use your browser',
'en_US': 'Solved map was reset, you are starting from a clean slate!',
'de_DE': 'Gelöste Karte wurde zurückgesetzt, du fängst mit einem leeren Blatt an!',
'zh_CN': '解决列表已重置,您现在可以从头开始了',
'zh_TW': '過關地圖已經重新設置,您現在從零開始了',
'es_AR': 'El mapa resuelto fue eliminado, estás arrancando desde un estado limpio',
'es_ES': 'El mapa resuelto fue eliminado, estás empezando de un estado limpio.',
'pt_BR': 'Mapa de resolvidos descartado, você está começando com ficha limpa!',
'gl' : 'O mapa resolto foi eliminado, estás arrancando dende un estado limpo.',
'fr_FR': 'La carte des niveaux résolus a été effacée, vous repartez de zéro !',
'ru_RU': 'Всё сброшено! Можно начать с чистого листа!',
'uk': 'Все скинуте! Можна починати з чистого аркушу!',
'ko': '해결된 지도가 초기화 되었습니다. 당신은 깨끗한 상태에서 시작합니다.'
},
///////////////////////////////////////////////////////////////////////////
'level-cant-exit': {
'__desc__': 'When the user tries to exit a level when they are not in one',
'en_US': 'You are not in a level! You are in a sandbox, start a level with "levels"',
'de_DE': 'Du bist nicht in einem Level! Du bist im Sandkasten-Modus, starte einen Level mit "levels"',
'zh_CN': '您没在关卡中而是在沙盒中,要开始关卡请输入 "levels"',
'zh_TW': '您沒在關卡中!您在沙盒中,要開始關卡請輸入 "levels"',
'es_AR': '¡No estás en un nivel! Estás en el sandbox, comenzá un nivel usando "levels"',
'es_ES': '¡No estás en un nivel! Estás en el sandbox, comienza un nivel con "levels"',
'pt_BR': 'Você não está em um nível! Você está no sandbox, comece um nível com "levels"',
'gl' : '¡Non estás en ningún nivel! Estás nunha caixa de arena, comeza un nivel usando "levels"',
'fr_FR': 'Vous n\'êtes pas dans un niveau ! Vous êtes dans le mode bac à sable, commencez un niveau avec "levels"',
'ru_RU': 'Ты не проходишь уровень! Ты в песочнице! Чтобы начать уровень, используй команду "levels"!',
'uk': 'Ти не в рівні! Ти в пісочниці! Почни рівень з "levels"',
'ko': '당신은 샌드박스에 있습니다. "levels"를 사용하여 레벨을 시작하세요.'
},
///////////////////////////////////////////////////////////////////////////
'level-no-id': {
'__desc__': 'When you say an id but that level doesn\'t exist',
'en_US': 'A level for that id "{id}" was not found! Opening up a level selection view',
'de_DE': 'Konnte keinen Level mit der ID "{id}" finden! Öffne einen Level-Auswahldialog',
'zh_CN': '没找到 id 为 "{id}" 的关卡!打开关卡选择框',
'zh_TW': '找不到 id 為 "{id}" 的關卡!開啟關卡選擇視窗',
'es_AR': 'No se encontró ningún nivel {id}. Abriendo la vista de selección de niveles...',
'es_ES': 'No se encontró ningún nivel {id}. Abriendo la vista de selección de niveles...',
'pt_BR': 'O nível "{id}" não existe! Abrindo uma caixa de seleção de nível',
'gl' : 'O nivel "{id}" non existe! Abrindo unha caixa de seleción de nivel',
'fr_FR': 'Le niveau dont l\'identifiant est {id} n\'a pas été trouvé ! Ouverture de la vue de sélection des niveaux',
'ru_RU': 'Уровень с id "{id}" не найден! Открываю выбор уровней',
'uk': 'Рівень з id "{id}" не знайдений! Відкриваю вибір рівней',
'ko': 'id "{id}"에 대한 레벨이 존재하지 않습니다. 레벨 선택 화면을 열어보세요.'
},
///////////////////////////////////////////////////////////////////////////
'undo-stack-empty': {
'__desc__': 'The undo command can only undo back until the last time the level was reset or the beginning of the level',
'en_US': 'The undo stack is empty!',
'de_DE': 'Die Undo-Liste ist leer!',
'zh_CN': '还没有什么可以撤销',
'zh_TW': '還沒有什麼可以取消',
'es_AR': 'No hay comandos que deshacer',
'es_ES': 'No hay comandos que deshacer',
'pt_BR': 'Você já desfez tudo!',
'gl' : 'Nonn hai comandos que desfacer',
'fr_FR': 'La pile d\'annulation est vide !',
'ru_RU': 'Некуда откатывать!',
'uk': 'Нема куди відкатуватися',
'ko': '되돌리기 스택이 비었습니다!'
},
///////////////////////////////////////////////////////////////////////////
'already-solved': {
'__desc__': 'When you play in a level that is already solved',
'en_US': 'You have already solved this level, try other levels with "levels" or go back to sandbox with "sandbox"',
'de_DE': 'Du hast diesen Level bereits gelöst, probier einen anderen Level mit "levels" aus oder geh in den Sandkasten-Modus mit "sandbox"',
'zh_CN': '你已经解决了本关,输入 "levels" 尝试其他关卡,或者输入 "sandbox" 回到沙盒中',
'zh_TW': '你已經解决了本關,輸入 "levels" 嘗試其他關卡,或者輸入 "sandbox" 回到沙盒中',
'es_AR': 'Ya resolviste este nivel, probá otros usando "levels" o volvé al sandbox usando "sandbox"',
'es_ES': 'Ya resolviste este nivel, prueba otros usando "levels" o vuelve al sandbox usando "sandbox"',
'pt_BR': 'Você já resolveu este nível, tente outros com "levels" ou volte ao sandbox com "sandbox"',
'gl' : 'Xa resolviches este nivel, proba outros usando "levels" ou volve á caixa de area con "sandbox"',
'fr_FR': 'Vous avez déjà résolu ce niveau, essayez d\'autres niveaux avec "levels" ou revenez au bac à sable avec "sandbox"',
'ru_RU': 'Ты уже прошел этот уровень, попробуй пройти другие при помощи команды "levels" или иди в песочницу "sandbox"',
'uk': 'Ти вже пройшов цей рівень, спробуй інші рівні з "levels" чи повернись в пісочницю з "sandbox"',
'ko': '당신은 이미 이 레벨을 해결했습니다. "levels"를 사용하여 다른 레벨에 도전하거나 "sandbox"를 사용하여 샌드박스로 돌아가세요.'
},
///////////////////////////////////////////////////////////////////////////
'solved-level': {
'__desc__': 'When you solved a level',
'en_US': 'Solved!!\n:D',
'de_DE': 'Gelöst!\n:D',
'zh_CN': '恭喜过关!!',
'zh_TW': '恭喜,本關解決了!!',
'es_ES': '¡Resuelto!\n:D',
'gl' : '¡Resolto!',
'ru_RU': 'Решено!!\n:D',
'uk' : 'Вирішено!!\n:D',
'ko' : '해결 완료!!\n:D'
},
///////////////////////////////////////////////////////////////////////////
'command-disabled': {
'__desc__': 'When you try a command that is disabled',
'en_US': 'That git command is disabled for this level!',
'de_DE': 'Dieser git-Befehl ist für diesen Level deaktiviert!',
'zh_CN': '本关不允许使用该命令!',
'zh_TW': '本關禁止使用該 git 指令!',
'es_AR': '¡Ese comando de git está deshabilitado para este nivel!',
'es_ES': '¡Ese comando de git está deshabilitado para este nivel!',
'pt_BR': 'Achou que seria fácil assim? Desabilitamos esse comando durante este nível, só para dificultar ;-)',
'gl' : '¡Ese comando de git está deshabilitado para este nivel!',
'fr_FR': 'Cette commande git est désactivée pour ce niveau !',
'ru_RU': 'На этом уровне нельзя использовать эту команду!',
'uk': 'На цьому рівні не можна використовувати цю команду!',
'ko': '그 Git 명령어는 이 레벨에서 사용할 수 없습니다.'
},
///////////////////////////////////////////////////////////////////////////
'share-json': {
'__desc__': 'when you have made the level, prompt to share this',
'en_US': 'Here is the JSON for this level! Share it with someone or send it to me on Github',
'de_DE': 'Hier ist das JSON für diesen Level! Teil es mit jemandem or schick es mir über Github',
'zh_CN': '这是一个关卡定义 JSON !您可以分享它或者发到我的 Github 上',
'zh_TW': '這是本關的 JSON!您可以分享給別人,或是送到 Github 上給我',
'es_AR': 'Este es el JSON de este nivel. Compartilo con quien quieras o mandámelo por Github',
'es_ES': 'Este es el JSON de este nivel. Compártelo con quien quieras o mandámelo por Github.',
'pt_BR': 'Aqui está o JSON para este nível! Compartilhe com alguém ou me envie pelo Github',
'gl' : 'Este é o JSON deste nivel. Comparteo con quen queiras ou mándao por Github',
'fr_FR': 'Voici le JSON pour ce niveau ! Partagez-le avec quelqu\'un ou envoyez-le moi sur Github',
'ru_RU': 'Вот JSON для этого уровня! Поделись им с кем-нибудь или отправь его нам на GitHub',
'uk': 'Ось JSON для цього рівня! Поділись з кимось чи відправ мені його на Github',
'ko': '이 레벨을 위한 JSON 데이터가 있습니다! 이를 다른 사람들과 공유하거나 Github에서 제게 보내보세요.'
},
///////////////////////////////////////////////////////////////////////////
'want-start-dialog': {
'__desc__': 'prompt to add a start dialog',
'en_US': 'You have not specified a start dialog, would you like to add one?',
'de_DE': 'Du hast noch keinen Einführungs-Dialog geschrieben, willst du einen hinzufügen?',
'zh_CN': '您还没有定义一开始的介绍,是否添加一个?',
'zh_TW': '尚未指定開始對話視窗,是否立即新增?',
'es_AR': 'No especificaste un mensaje de inicio, ¿querés agregar uno?',
'es_ES': 'No especificaste un mensaje de inicio, ¿quieres agregar uno?',
'pt_BR': 'Você não especificou uma mensagem de início, quer colocar uma?',
'gl' : 'Non especificaches unha mensaxe de incio. ¿queres agregar un?',
'fr_FR': 'Vous n\'avez pas spécifié de dialogue de départ, voulez-vous en ajouter un ?',
'ru_RU': 'Не указано стартово сообщение! Точно продолжаем?',
'uk': 'Не вказано стартовий діалог, хочеш додати стартовий діалог?',
'ko': '당신은 시작 대화창을 지정하지 않았습니다. 추가 하시겠습니까?'
},
///////////////////////////////////////////////////////////////////////////
'want-hint': {
'__desc__': 'prompt to add a hint',
'en_US': 'You have not specified a hint, would you like to add one?',
'de_DE': 'Du hast noch keinen Hinweis geschrieben, magst du einen hinzufügen?',
'zh_CN': '您还没有定义提示,是否添加一个?',
'zh_TW': '尚未指定提示,是否立即新增?',
'es_AR': 'No especificaste ninguna pista, ¿querés agregar alguna?',
'es_ES': 'No especificaste ninguna pista, ¿quieres agregar alguna?',
'pt_BR': 'Você não especificou uma dica, quer colocar uma?',
'gl' : 'Ti non especificaches unha pista, ¿queres agregar algunha?',
'fr_FR': 'Vous n\'avez pas spécifié d\'indice, voulez-vous en ajouter un ?',
'ru_RU': 'Не указана подсказка для уровня! Пренебречь? Вальсируем?',
'uk': 'Не вказана підказка, хочеш додати підказку?',
'ko': '당신은 힌트를 지정하지 않았습니다. 추가 하시겠습니까?'
},
///////////////////////////////////////////////////////////////////////////
'prompt-hint': {
'__desc__': 'prompt for hint',
'en_US': 'Enter the hint for this level, or leave this blank if you do not want to include one',
'de_DE': 'Gib den Hinweis für diesen Level an, oder lass es leer wenn du keinen hinzufügen willst',
'zh_CN': '请输入关卡提示,如果没有请留空',
'zh_TW': '請輸入關卡提示,或者故意留空',
'es_AR': 'Ingresá una pista para este nivel, o dejalo en blanco si no querés incluir ninguna',
'es_ES': 'Ingresa una pista para este nivel, o déjalo en blanco si no quieres incluir ninguna.',
'pt_BR': 'Colocque uma dica para este nível, ou deixe em branco se não quiser incluir',
'gl' : 'Ingresa unha pista para este nivel, ou déixao en branco se non a queres incluír.',
'fr_FR': 'Entrez l\'indice pour ce niveau, ou laissez-le vide pour ne pas l\'inclure',
'ru_RU': 'Введи подсказку для уровня, если хочешь.',
'uk': 'Додай підказку для рівня, якщо хочеш',
'ko': '이 레벨을 위한 힌트를 입력하거나 만약 이를 포함시키고 싶지 않을 경우엔 비워두세요.'
},
///////////////////////////////////////////////////////////////////////////
'prompt-name': {
'__desc__': 'prompt for level name',
'en_US': 'Enter the name for the level',
'de_DE': 'Gib den Namen für diesen Level an',
'zh_CN': '请输入关卡名称',
'zh_TW': '請輸入關卡名稱',
'es_AR': 'Ingresá el nombre del nivel',
'es_ES': 'Ingresa el nombre del nivel.',
'pt_BR': 'Coloque o nome do nível',
'gl' : 'Coloque o nome do nivel',
'fr_FR': 'Entrez le nom pour ce niveau',
'ru_RU': 'Введи название уровня',
'uk': 'Введи назву рівня',
'ko': '레벨 이름을 입력하세요.'
},
///////////////////////////////////////////////////////////////////////////
'solution-empty': {
'__desc__': 'If you define a solution without any commands, aka a level that is solved without doing anything',
'en_US': 'Your solution is empty!! Something is amiss',
'de_DE': 'Deine Auflösung ist leer! Hier fehlt etwas',
'zh_CN': '你的解法是空的!! 可能是程序出错了',
'zh_TW': '您的解法是空的!這一定是哪裡出錯了',
'es_AR': '¡Tu solución está vacía! Algo hay que hacer',
'es_ES': '¡Tu solución está vacía! Algo hay que hacer.',
'pt_BR': 'Sua solução está vazia! O aprendiz deveria ter que fazer alguma coisa',
'gl' : '¡Su solución está vacía! Algo haberá que facer.',
'fr_FR': 'Votre solution est vide !! Quelque chose ne tourne pas rond',
'ru_RU': 'Решение не указано! Так не годится!',
'uk': 'Розв’язок порожній!! Щось не так',
'ko': '해답이 비어있습니다. 무언가 잘못되었습니다.'
},
///////////////////////////////////////////////////////////////////////////
'define-start-warning': {
'__desc__': 'When you define the start point again, it overwrites the solution and goal so we add a warning',
'en_US': 'Defining start point... solution and goal will be overwritten if they were defined earlier',
'de_DE': 'Lege Start fest ... Auflösung und Ziel werden gelößcht, falls sie schon festgelegt worden waren',
'zh_CN': '定义开始点... 解决方法和目标会被新的替代',
'zh_TW': '正在定義起始點...先前定義的解法和目標會被覆蓋掉',
'es_AR': 'Estableciendo el punto de inicio... La solución y el objetivo serán sobreescritos si ya habían sido definidos',
'es_ES': 'Estableciendo el punto de inicio... La solución y el objetivo serán sobreescritos si ya habían sido definidos.',
'pt_BR': 'Esbelecendo o ponto de início... a solução e o objetivo serão sobrescritos caso já existirem',
'gl' : 'Establecendo o punto de inicio... A solución e o obxectivo serán sobreescritos se xa foron definidos.',
'fr_FR': 'Redéfinition du point de départ… la solution et la cible seront écrasés s\'ils ont déjà été définis',
'ru_RU': 'Устанавливаю стартовую точку... Решение и итоговое состояние будут стёрты, если они указаны ранее',
'uk': 'Встановлюю стартову точку... розв’язок та ціль будуть переписані якщо вони були задані раніше',
'ko': '시작 지점을 정의하세요... 만약 그것이 먼저 정의된다면 해답과 목표가 덮어씌워질 것입니다.'
},
///////////////////////////////////////////////////////////////////////////
'help-vague-level': {
'__desc__': 'When you are in a level and you say help, its vague and you need to specify',
'en_US': 'You are in a level, so multiple forms of help are available. Please select either "help level" to learn more about this lesson, "help general" for using Learn GitBranching, or "objective" to learn about how to solve the level.',
'de_DE': 'Du befindest dich in einem Level, daher gibt es verschiedene Hilfen. Gib "help level" ein um mehr úber diesen Level zu erfahren, "help general" um zu sehen wie Learn Git Branching bedient wird, oder "objective" um das Ziel dieses Levels zu erfahren.',
'zh_CN': '您正在关卡中,这里有多种形式的帮助,请选择 "help level" (关卡帮助)或 "help general" (一般帮助)',
'zh_TW': '您正在進行關卡中,這裡有多種不同型式的幫助,請選擇 "help level" 來了解這個關卡,或者是選擇 "help general" 來學習如何使用 Learn GitBranching,或者是選擇 "objective" 來學習如何解決這個關卡',
'es_AR': 'Estás en un nivel, por lo que hay varios tipos de ayuda. Por favor elegí entre "help level" para aprender algo más sobre esta lección, "help general" para ayuda sobre el uso de Learn GitBranching, o "objective" para aprender a resolver este nivel.',
'es_ES': 'Estás en un nivel, por lo que hay varios tipos de ayuda. Por favor elige "help level" para aprender más sobre esta lección, "help general" para ayuda sobre el uso de Learn GitBranching, o "objective" para aprender a resolver este nivel.',
'pt_BR': 'Você está em um nível, então há vários tipos de ajuda. Selecione "help level" para aprender mais sobre esta lição, "help general" para aprender a usar o Learn GitBranching, ou "objective" ver como resolver o nível.',
'gl' : 'Estás nun nivel, entón hai varios tipos de axuda. Selecione "help level" para aprender máis sobre esta lección, "gelp general" para aprender a usar o Learn Git Branching, ou "objective" para ver como resolver o nivel.',
'fr_FR': 'Vous êtes dans un niveau, donc plusieurs formes d\'aide sont disponibles. Merci de sélectionner soit "help level" pour en apprendre plus sur cette leçon, "help general" pour l\'utilisation de Learn GitBranching, ou "objective" pour apprendre comment résoudre le niveau',
'ru_RU': 'При прохождении уровня доступны несколько видов помощи. Определить что нужно: "help level" чтобы получить информацию об этом уровне, "help general" для того, чтобы узнать о игре в целом или "objective" чтобы узнать что надо сделать в этом уровне.',
'uk': 'При проходженні рівня доступні декілька різновидів допомоги. Виберіть або "help level" щоб взнати більше про цей рівень, чи "help general" щоб взнати більше про Learn Git Branching, чи "objective" щоб дізнатись більше про проходження цього рівня',
'ko': '당신은 한 레벨에 들어가 있고, 여러가지 도움 양식들을 사용할 수 있습니다. 레슨에 대해 더 알고싶을 땐 "help level", LearnGitBranching을 사용하고 싶을 땐 "help general", 또는 레벨을 어떻게 해결해야할지 알고싶을 땐 "objective"를 선택하세요.'
},
///////////////////////////////////////////////////////////////////////////
'help-vague-builder': {
'__desc__': 'When you are in a level builder, the help command is vague so you need to specify what you mean',
'en_US': 'You are in a level builder, so multiple forms of help are available. Please select either "help general" or "help builder"',
'de_DE': 'Du befindest dich im Level-Editor, daher gibt es verschiedene Hilfen. Gib bitte "help general" oder "help builder" ein',
'zh_CN': '您正在进行关卡构建中,这里有多种形式的帮助,请选择 "help general" (一般帮助)或 "help builder" (关卡构建帮助)',
'zh_TW': '您正在進行關卡構建中,這裡有多種不同型式的幫助,請選擇 "help general" (一般幫助)或 "help builder" (製造關卡的幫助)',
'es_AR': 'Estás en el constructor de niveles, por lo que hay varios tipos de ayuda. Elegí entre "help general" para ayuda sobre Learn GitBranching y "help builder" para ayuda sobre el constructor de niveles',
'es_ES': 'Estás en un constructor de niveles, por lo que hay varios tipos de ayuda. Elige "help general" para ayuda sobre Learn GitBranching o "help builder" para ayuda sobre el constructor de niveles',
'pt_BR': 'Você está no construtor de nívels, então há vários tipos de ajuda. Selecione "help general" ou "help builder"',
'gl' : 'Estás no constructor de niveis, polo que hai varios tipos de axuda. Elixe "help general" ou "help builder"',
'fr_FR': 'Vous êtes dans l\'éditeur de niveaux, donc plusieurs formes d\'aide sont disponibles. Merci de sélectionner soit "help general" soit "help builder"',
'ru_RU': 'При создании уровней доступны несколько видов помощи. Выбери между "help general" и "help builder"',
'uk': 'При створенні рівня доступні декілька різновидів допомоги. Виберіть або "help general", чи "help builder"',
'ko': '당신은 한 레벨 생성기에 들어가 있고, 여러가지 도움 양식들을 사용할 수 있습니다. "help general" 또는 "help builder"를 선택해주세요.'
},
///////////////////////////////////////////////////////////////////////////
'show-goal-button': {
'__desc__': 'button label to show goal',
'en_US': 'Show Goal',
'de_DE': 'Ziel anzeigen',
'zh_TW': '顯示目標',
'zh_CN': '显示目标',
'fr_FR': 'Afficher les cibles',
'pt_BR': 'Mostrar objetivo',
'gl' : 'Amosar obxectivo',
'es_AR': 'Mostrar objetivo',
'es_ES': 'Mostrar objetivo',
'ja' : 'ゴールを表示',
'ru_RU': 'Цель уровня',
'uk': 'Ціль рівня',
'ko': '목표 보기'
},
///////////////////////////////////////////////////////////////////////////
'hide-goal-button': {
'__desc__': 'button label to hide goal',
'en_US': 'Hide Goal',
'de_DE': 'Ziel verstecken',
'fr_FR': 'Cacher les cibles',
'zh_TW': '隱藏目標',
'zh_CN': '隐藏目标',
'pt_BR': 'Ocultar objetivo',
'gl' : 'Ocultar obxectivo',
'es_AR': 'Ocultar objetivo',
'es_ES': 'Ocultar objetivo',
'ja' : 'ゴールを隠す',
'ru_RU': 'Спрятать цель',
'uk': 'Сховати ціль',
'ko': '목표 숨기기'
},
///////////////////////////////////////////////////////////////////////////
'objective-button': {
'__desc__': 'button label to show objective',
'en_US': 'Instructions',
'de_DE': 'Ziel',
'zh_TW': '提示',
'zh_CN': '提示',
'es_ES': 'Objetivo',
'gl' : 'Obxectivo',
'ru_RU': 'Задача',
'uk': 'Задача',
'ko': '목적'
},
///////////////////////////////////////////////////////////////////////////
'git-demonstration-title': {
'__desc__': 'title of git demonstration window',
'en_US': 'Git Demonstration',
'de_DE': 'Git Demonstration',
'zh_TW': 'Git示範',
'zh_CN': 'Git示范',
'es_ES': 'Demostración de Git',
'gl' : 'Demostración de Git',
'ru_RU': 'Git демо',
'uk' : 'Git демо',
'ko' : 'Git 데모'
},
///////////////////////////////////////////////////////////////////////////
'goal-to-reach': {
'__desc__': 'title of window that shoes the goal tree to reach',
'en_US': 'Goal To Reach',
'de_DE': 'Ziel',
'zh_CN': '目标',
'zh_TW': '目標',
'es_AR': 'Objetivo a cumplir',
'es_ES': 'Objetivo a cumplir',
'pt_BR': 'Objetivo a cumprir',
'gl' : 'Obxectivo a cumprir',
'fr_FR': 'Cible à atteindre',
'ja' : '到達目標',
'ru_RU': 'Цель уровня',
'uk': 'Ціль рівня',
'ko': '목표'
},
///////////////////////////////////////////////////////////////////////////
'goal-only-master': {
'__desc__': 'the helper message for the window that shows the goal tree when the goal will only be compared using the master branch',
'en_US': '<span class="fwber">Note:</span> Only the master branch will be checked in this level. The other branches are simply for reference (shown as dashed labels below). As always, you can hide this dialog with "hide goal"',
'fr_FR': '<span class="fwber">Note:</span> Dans ce niveau on ne doit faire de git checkout que sur la branche master. Les autres branches représentées ici (entourées d\'un cadre en tirets) doivent être utilisées uniquement comme références. Comme toujours, vous pouvez cacher cette fenêtre avec "Cacher les objectifs"',
'de_DE': '<span class="fwber">Hinweis:</span> In diesem Level wird nur der Branch master geprüft. Die anderen Branches dienen nur als Vergleichsbasis (als gestrichelte Bezeichner dargestellt). Wie immer kannst du diese Meldung mit "hide goal" ausblenden',
'es_AR': '<span class="fwber">Nota:</span> Sólo la rama master va a ser chequeada en este nivel. Las otras ramas sólo son para referencia. Como siempre, podés ocultar este mensaje con "hide goal"',
'es_ES': '<span class="fwber">Nota:</span> Sólo la rama master va a ser inspeccionado en este nivel. Las otras ramas sólo son para referencia (etiquetados abajo con guion). Siempre puedes ocultar este mensaje con "hide goal."',
'pt_BR': '<span class="fwber">Nota:</span> Apenas o ramo master será verificado neste nível. Os outros ramos (dentro das caixas clareadas) são somente para referência. Como sempre, você pode ocultar esta janela com "hide goal"',
'gl': '<span class="fwber">Nota:</span> Só a rama master será verificada neste nivel. As outras ramas (dentro das caixas clareadas) son soamente de referencia. Coma sempre, podes ocultar está ventá con "hide goal"',
'zh_CN': '<span class="fwber">注意:</span>本关卡中,只检查 master 分支,其他分支只是用作 reference 存在(以虚线标签表示)。照常,你可以用 “hide goal” 来隐藏此窗口。',
'zh_TW': '在這個關卡中,只有 master branch 會被檢查,別的 branch 只是用來做為 reference (下面用虛線符號表示)。一如往常,你可以利用 "hide goal" 來隱藏這個對話視窗',
'ja': '<span class="fwber">Note:</span> masterブランチだけをこのlevelではチェックします。その他のブランチ(以下では、破線で示されています)に関しては、参照のためにあります。また、いつでもこのウィンドウは"hide goal"と打つかクリックで閉じれます',
'ru_RU': '<span class="fwber">Важно:</span> В этом уровне проверяется только ветка master. Остальные ветки просто для наглядности. Как обычно, можно скрыть это сообщение при помощи "hide goal"',
'uk': '<span class="fwber">Важливо:</span> В цьому рівні буде перевірятися тільки гілка master. Решта гілок тільки для наглядності (показані пунктиром нижче). Як завжди, можна сховати цей діалог за допомогою "hide goal"',
'ko': '<span class="fwber">Note:</span> 이 레벨에선 오직 마스터 브랜치만이 검사될 것입니다.. 다른 브랜치들은 단순히 참고용입니다. (아래에 대시 라벨로 보여집니다.). "hide goal"을 사용하여 언제든지 창을 숨킬 수 있습니다.'
},
///////////////////////////////////////////////////////////////////////////
'hide-goal': {
'__desc__': 'the helper message for the window that shows the goal tree',
'en_US': 'You can hide this window with "hide goal"',
'de_DE': 'Du kannst diese Meldung mit "hide goal" ausblenden',
'zh_CN': '你可以通过 "hide goal" 命令关闭这个窗口',
'zh_TW': '你可以透過 "hide goal" 關閉這個視窗',
'es_AR': 'Podés ocultar esta ventana con "hide goal"',
'es_ES': 'Puedes ocultar esta ventana con "hide goal."',
'pt_BR': 'Você pode ocultar esta janela com "hide goal"',
'gl' : 'Podes ocultar esta ventá con "hide goal"',
'fr_FR': 'Vous pouvez masquer cette fenêtre avec "Cacher les cibles"',
'ja' : 'このウィンドウは"hide goal"と打つかクリックで閉じれます',
'ru_RU': 'Можно скрыть это окно при помощи "hide goal"',
'uk': 'Можна сховати це вікно за допомогою "hide goal"',
'ko': '"hide goal"을 사용하여 이 창을 숨길 수 있습니다.'
},
///////////////////////////////////////////////////////////////////////////
'hide-start': {
'__desc__': 'The helper message for the window that shows the start tree for a level',
'en_US': 'You can hide this window with "hide start"',
'de_DE': 'Du kannst diese Meldung mit "hide start" ausblenden',
'zh_CN': '你可以通过 "hide start" 命令关闭这个窗口',
'zh_TW': '你可以透過 "hide start" 關閉這個視窗',
'es_AR': 'Podés ocultar esta ventana con "hide start"',
'es_ES': 'Puedes ocultar esta ventana con "hide start."',
'pt_BR': 'Você pode ocultar esta janela com "hide start"',
'gl' : 'Podes ocultar esta ventá con "hide start"',
'fr_FR': 'Vous pouvez masquer cette fenêtre avec "hide start"',
'ja' : 'このウィンドウは"hide start"かクリックで閉じれます',
'ru_RU': 'Можно скрыть это окно при помощи "hide start"',
'uk': 'Можна сховати це вікно за допомогою "hide start"',
'ko': '"hide start"를 사용하여 이 창을 숨길 수 있습니다.'
},
///////////////////////////////////////////////////////////////////////////
'level-builder': {
'__desc__': 'The name for the environment where you build levels',
'en_US': 'Level Builder',
'de_DE': 'Level-Editor',
'zh_CN': '关卡生成器',
'zh_TW': '關卡產生器',
'es_AR': 'Constructor de niveles',
'es_ES': 'Constructor de niveles',
'pt_BR': 'Construtor de níveis',
'gl' : 'Constructor de nivéis',
'fr_FR': 'Éditeur de niveaux',
'ja' : 'Levelエディタ',
'ru_RU': 'Редактор уровней',
'uk': 'Редактор рівнів',
'ko': '레벨 생성기'
},
///////////////////////////////////////////////////////////////////////////
'no-start-dialog': {
'__desc__': 'when the user tries to open a start dialog for a level that does not have one',
'en_US': 'There is no start dialog to show for this level!',
'de_DE': 'Es gibt keinen Einführungs-Dialog für diesen Level!',
'zh_CN': '这个关卡没有介绍!',
'zh_TW': '這關沒有介紹!',
'es_AR': '¡No hay mensaje de inicio para este nivel!',
'es_ES': '¡No hay mensaje de inicio para este nivel!',
'pt_BR': 'Não há mensagem de início para este nível!',
'gl' : '¡Non hai mensaxe de inicio para este nivel!',
'fr_FR': 'Il n\'y a aucun dialogue de départ à afficher pour ce niveau !',
'ja' : 'このLevelにはスタートダイアログが存在しません',
'ru_RU': 'Нет стартового сообщение для уровня!',
'uk': 'Немає початкового діалогу для цього рівня!',
'ko': '이 레벨을 위한 시작 대화창이 없습니다.'
},
///////////////////////////////////////////////////////////////////////////
'no-hint': {
'__desc__': 'when no hint is available for a level',
'en_US': "Hmm, there doesn't seem to be a hint for this level :-/",
'de_DE': "Hm, es gibt anscheinend keinen Hinweis für diesen Level :-/",
'zh_CN': "呃……,这关好像没有提示 :-/",
'zh_TW': "嗯‧‧‧這關沒有提示 :-/",
'es_AR': 'Mmm... Pareciera no haber pistas para este nivel :-/',
'es_ES': 'Mmm... Parece que no hay pistas para este nivel. :-/',
'pt_BR': 'Hmm, não existe nenhuma pista para este nível :-/',
'gl' : 'Hmm, non existe ningunha pista para este nivel :-/',
'fr_FR': 'Hum, il ne semble pas y avoir d\'indice pour ce niveau :-/',
'ja' : 'あらら、このLevelでは、残念ながらヒントが存在しません :-/',
'ru_RU': "Милый мой, хороший, догадайся сам :-/ Подсказка не создана...",
'uk': 'Хм, схоже для цього рівня немає підказки :-/',
'ko': '흠, 이 레벨을 위한 힌트가 없어보이는군요.'
},
///////////////////////////////////////////////////////////////////////////
'error-untranslated-key': {
'__desc__': 'This error happens when we are trying to translate a specific key and the locale version is mission',
'en_US': 'The translation for {key} does not exist yet :( Please hop on github and offer up a translation!',
'de_DE': 'Die Übersetzung für {key} existiert noch nicht :( Falls du eine hast, bitte teil sie mit auf Github mit!',
'zh_CN': '还没翻译 {key} :( 请在 Github 上贡献您的翻译!',
'zh_TW': '還沒翻譯 {key} :( 請在 Github 上貢獻您的翻譯!',
'es_AR': 'Aún no hay traducción para {key} :( ¡Metete en Github y sugerí una! :)',
'es_ES': 'Aún no hay traducción para {key}. :( ¡Métete en Github y sugiere una! :)',
'pt_BR': 'Não existe tradução para {key} :( Pule no Github e sugira uma! :)',
'gl' : 'Non existe tradución para {key} :( Axúdanos en Github e suxire unha! :)',
'fr_FR': 'La traduction pour {key} n\'existe pas encore :( Venez sur Github pour en offrir une !',
'ja' : '{key}の翻訳がまだ存在しません :( GitHubでの、翻訳の協力をお願いします m(_)m',
'ru_RU': 'Перевода для {key} не создано :( Пожалуйста, предложи перевод на GitHub',
'uk': 'Немає перекладу для {key} :( Будь-ласка, запропонуй переклад на Github',
'ko': '{key}를 위한 번역은 아직 존재하지 않습니다 :( 번역에 참여해주세요!',
'vi_VN': 'Bản dịch cho {key} chưa tồn tại :( Vui lòng truy cập github và cung cấp bản dịch!'
},
///////////////////////////////////////////////////////////////////////////
'error-untranslated': {
'__desc__': 'The general error when we encounter a dialog that is not translated',
'en_US': 'This dialog or text is not yet translated in your locale :( Hop on github to aid in translation!',
'de_DE': 'Dieser Dialog oder Text ist noch nicht in deine Sprache übersetzt. :( Schau auf Github vorbei um bei der Übersetzung zu helfen!',
'zh_CN': '这段对话还没有被翻译成您的语言 :( 欢迎在 Github 上贡献您的翻译!',
'zh_TW': '這段對話尚未翻成您的語言 :( 歡迎到 Github 貢獻翻譯!',
'es_AR': 'Este mensaje o texto aún no fue traducido a tu idioma :( ¡Metete en Github y ayudanos a traducirlo!',
'es_ES': 'Este mensaje o texto aún no fue traducido a tu idioma. :( ¡Métete en Github y ayúdanos a traducirlo!',
'pt_BR': 'Esta mensagem ou texto não foi traduzida para Português :( Ajude-nos a traduzir no Github!',
'gl' : 'Esta mensaxe ou texto non foi traducida ó teu idioma :( Axúdanos a traducir a web en Github, é moi doado!',
'fr_FR': 'Ce message n\'a pas encore été traduit dans votre langue :( Venez sur Github aider à la traduction !',
'ja' : 'このダイアログ、またはテキストの翻訳がまだ存在しません :( GitHubでの、翻訳の協力をお願いします m(_)m',
'ru_RU': 'Для этого сообщения нет перевода :( Пожалуйста, предложи перевод на GitHub',
'uk': 'Для цього повідомлення ще немає перекладу :( Будь-ласка, запропонуй переклад на Github',
'ko': '이 대화창이나 텍스트는 아직 번역되지 않았습니다. :( 번역에 참여해주세요!',
'vi_VN': 'Hộp thoại hoặc văn bản này chưa được dịch sang ngôn ngữ của bạn :( Hy vọng sẽ có người sớm bổ sung bản dịch!'
}
};
|
import * as PhaserObjects from './phaserObjects';
/** Group with some added functionality for text overlays.
* @private
* @extends Phaser.Group
*/
class TextGroup extends PhaserObjects.Group {
/**
* @param {Object} game - Current game instance.
* @param {number} x - The x coordinate on screen where the sprite will be placed.
* @param {number} y - The y coordinate on screen where the sprite will be placed.
*/
constructor(game, x, y) {
super(game, x, y);
this.game = game;
this.x = x;
this.y = y;
game.add.existing(this);
}
/**
* @param {string} label - The text to place on top of the sprite.
* @param {Object} style - The style properties to be set on the Text.
*/
setText(label, style) {
if (this.text) {
this.text.destroy();
}
if (this.version === 3) {
this.text = this.game.add.text(0, 0, label, style);
this.text.setOrigin(0.5, 0.5);
} else {
this.text = this.game.add.text(this.width / 2, this.height / 2, label, style);
this.text.anchor.set(0.5, 0.5);
}
this.add(this.text);
this.text.wordWrap = true;
this.text.wordWrapWidth = this.width;
return this;
}
/** When setOrigin is called, align the text as well. */
setOrigin(x, y) {
this.sprite.setOrigin(x, y);
this.text.x = this.sprite.width / 2;
this.text.y = this.sprite.height / 2;
return this;
}
}
/** Sprite with text added as a child.
* @extends Phaser.Group
*/
export class TextSprite extends TextGroup {
/**
* @param {Object} game - Current game instance.
* @param {number} x - The x coordinate on screen where the textSprite will be placed.
* @param {number} y - The y coordinate on screen where the textSprite will be placed.
* @param {string} key - The image to create a sprite with.
*/
constructor(game, x, y, key) {
super(game, x, y);
this.sprite = new PhaserObjects.Sprite(game, 0, 0, key);
this.add(this.sprite);
this.width = this.sprite.width;
this.height = this.sprite.height;
}
}
/** Phaser Group containing a button with text anchored in the button's center.
* @extends Phaser.Group
*/
export class TextButton extends TextGroup {
/**
* @param {Object} game - Current game instance.
* @param {number} x - The x coordinate on screen where the textSprite will be placed.
* @param {number} y - The y coordinate on screen where the textSprite will be placed.
* @param {string} key - The image to create a sprite with.
* @param {Object} callback - Callback to use when the button is clicked.
* @param {Object} callbackContext - The context the callback is called in.
* @param {number} overKey - The frame to switch to when an over event is triggered.
* @param {number} outKey - The frame to switch to when an out event is triggered.
* @param {number} downKey - The frame to switch to when a down event is triggered.
* @param {number} upKey - The frame to switch to when an up event is triggered.
*/
constructor(game, x, y, key, callback, callbackContext, overKey, outKey, downKey, upKey) {
super(game, x, y);
this.button = new PhaserObjects.Button(
game,
0,
0,
key,
callback,
callbackContext,
overKey,
outKey,
downKey,
upKey,
);
this.add(this.button);
this.width = this.button.width;
this.height = this.button.height;
}
/** Adds an adjustment to the text on down/up events. */
eventTextYAdjustment(number) {
const startY = this.text.y;
this.button.addDownEvent(() => { this.text.y += number; });
this.button.addUpEvent(() => { this.text.y = startY; });
// A pointerout event should reset the text position too.
this.button.addOutEvent(() => { this.text.y = startY; });
return this;
}
}
|
import React, { PropTypes } from 'react';
const PlaybackToggle = (
{},
{ media }
) => (
<div onClick={media.togglePlayback}>{media.playing ? 'Stop' : 'Play'}</div>
);
PlaybackToggle.contextTypes = {
media: PropTypes.shape({
playing: PropTypes.bool.isRequired,
togglePlayback: PropTypes.func.isRequired,
}).isRequired,
};
export default PlaybackToggle;
|
import build from '../../rollup.config';
export default build('reactNexus');
|
import { asyncRoutes, constantRoutes } from '@/router'
/**
* 判断角色是否有权限显示该菜单
* Use meta.role to determine if the current user has permission
* @param roles
* @param route
*/
function hasPermission(roles, route) {
if (route.meta && route.meta.roles) {
return roles.some(role => route.meta.roles.includes(role))
} else {
return true
}
}
/**
* 动态路由过滤
* Filter asynchronous routing tables by recursion
* @param routes asyncRoutes
* @param roles
*/
export function filterAsyncRoutes(routes, roles) {
const res = []
routes.forEach(route => {
const tmp = { ...route }
if (hasPermission(roles, tmp)) {
if (tmp.children) {
tmp.children = filterAsyncRoutes(tmp.children, roles)
}
res.push(tmp)
}
})
return res
}
const state = {
routes: [],
addRoutes: []
}
const mutations = {
/**
* 将router/index.js 中的动态路由和静态路由合并
*/
SET_ROUTES: (state, routes) => {
state.addRoutes = routes
state.routes = constantRoutes.concat(routes)
}
}
const actions = {
// 根据Route中的动态路由进行过滤,生成对应角色路由
generateRoutes({ commit }, roles) {
return new Promise(resolve => {
let accessedRoutes
if (roles.includes('admin')) {
accessedRoutes = asyncRoutes || []
} else {
accessedRoutes = filterAsyncRoutes(asyncRoutes, roles)
}
commit('SET_ROUTES', accessedRoutes)
resolve(accessedRoutes)
})
}
}
export default {
namespaced: true,
state,
mutations,
actions
}
|
import React from 'react';
import PropTypes from 'prop-types';
import {
Field,
HelpMessage,
FieldInput,
FieldConstants,
FormClassManager,
} from '@axa-fr/react-toolkit-form-core';
import { InputManager } from '@axa-fr/react-toolkit-core';
import CustomDate from './CustomDate';
const propTypes = {
...FieldConstants.propTypes,
value: PropTypes.object,
viewValue: PropTypes.string,
locale: PropTypes.string,
};
const defaultProps = {
...FieldConstants.defaultProps,
value: null,
viewValue: null,
locale: 'fr-fr',
};
const DateInput = (props) => {
const {
classModifier,
message,
children,
helpMessage,
id,
disabled,
classNameContainerLabel,
classNameContainerInput,
label,
messageType,
placeholder,
isVisible,
forceDisplayMessage,
className,
name,
value,
locale,
viewValue,
onChange,
readOnly,
...otherProps
} = props;
if (!isVisible) {
return null;
}
const inputClassModifier = FormClassManager.getInputClassModifier(
classModifier,
children
);
const inputFieldClassModifier = FormClassManager.getFieldInputClassModifier(
classModifier,
disabled
);
const inputId = InputManager.getInputId(id);
return (
<Field
label={label}
id={inputId}
message={message}
messageType={messageType}
placeholder={placeholder}
isVisible={isVisible}
forceDisplayMessage={forceDisplayMessage}
className={className}
classModifier={classModifier}
classNameContainerLabel={classNameContainerLabel}
classNameContainerInput={classNameContainerInput}>
<FieldInput
helpMessage={helpMessage}
message={message}
messageType={messageType}
className="af-datepicker__container"
classModifier={inputFieldClassModifier}>
<CustomDate
name={name}
id={inputId}
value={value}
locale={locale}
viewValue={viewValue}
onChange={onChange}
readOnly={readOnly}
disabled={disabled}
placeholder={placeholder}
classModifier={inputClassModifier}
{...otherProps}
/>
<span className="glyphicon glyphicon-calendar" />
{children}
</FieldInput>
<HelpMessage message={helpMessage} isVisible={!message} />
</Field>
);
};
DateInput.propTypes = propTypes;
DateInput.defaultProps = defaultProps;
export default DateInput;
|
import * as fs from 'fs';
const saveGraphJSON = (path, graph) => {
const data = JSON.stringify(graph, null, 4);
try {
fs.writeFileSync(path, data, 'utf8');
} catch (err) {
console.log(err);
}
};
export default saveGraphJSON;
|
import filter from 'lodash/filter';
import find from 'lodash/find';
import findIndex from 'lodash/findIndex';
import forEach from 'lodash/forEach';
import isEmpty from 'lodash/isEmpty';
import keys from 'lodash/keys';
import some from 'lodash/some';
angular
.module('managerApp')
.controller(
'CloudProjectOpenstackUsersCtrl',
function CloudProjectOpenstackUsersCtrl(
OvhApiCloud,
$translate,
CucCloudMessage,
$stateParams,
Poller,
$scope,
OpenstackUsersPassword,
OpenstackUsersToken,
$filter,
$q,
CucControllerHelper,
$window,
REDIRECT_URLS,
) {
const self = this;
const orderBy = $filter('orderBy');
const pollingInterval = 5000;
self.projectId = $stateParams.projectId;
self.table = {
users: {},
selectableUsers: [],
selectableUsersCurrentPage: [],
selected: {},
autoSelected: {},
};
self.toggle = {
userGenerateTokenId: null,
};
self.order = {
by: 'username',
reverse: false,
};
self.loaders = {
table: {
user: false,
},
add: {
token: false,
},
remove: {
user: false,
userMulti: false,
},
regeneratePassword: false,
generateToken: false,
};
self.generateToken = {
pass: null,
};
function init() {
self.getUsers();
}
// ---------TOOLS---------
self.getSelectedCount = function getSelectedCount() {
return Object.keys(self.table.selected).length;
};
$scope.$watch(
'CloudProjectOpenstackUsersCtrl.table.selected',
() => {
// if some line were not removed => recheck or if polling happened.
if (!isEmpty(self.table.autoSelected)) {
// Selected (and autoselected) are represented as object: Not array of objects
// or array of arrays.
// Therefore, we have to loop through the keys (which represent a UserId)
// and then compare it to the
// userId in the user object. User.id is a number and userId a string
// (it is an object key) so the .ToString is mandatory in order to use === instead of ==.
forEach(keys(self.table.autoSelected), (userId) => {
const isInUserTable = some(
self.table.users,
(user) => user.id.toString() === userId,
);
if (isInUserTable) {
self.table.selected[userId] = true;
}
});
self.table.autoSelected = [];
}
},
true,
);
function getSelectableUserList(userList) {
return filter(userList, (user) => user.status !== 'disabled');
}
$scope.$watch(
'CloudProjectComputeSnapshotCtrl.table.usersCurrentPage',
(users) => {
self.table.selectableUsersCurrentPage = getSelectableUserList(users);
},
);
// ---------ORDER---------
self.orderBy = function orderByFn(by) {
if (by) {
if (self.order.by === by) {
self.order.reverse = !self.order.reverse;
} else {
self.order.by = by;
}
}
self.table.users = orderBy(
self.table.users,
self.order.by,
self.order.reverse,
);
self.table.selectableUsers = orderBy(
self.table.selectableUsers,
self.order.by,
self.order.reverse,
);
};
self.selectUser = function selectUser(id, active) {
if (active) {
setTimeout(() => {
const areaheight = $(`#user_${id}`).prop('scrollHeight');
$(`#user_${id}`)
.height(areaheight)
.select();
}, 0);
}
};
function updateUserList(userList) {
// We set autoSelected so the selected entries remain selected after polling.
self.table.autoSelected = self.table.selected;
self.table.users = userList;
self.table.selectableUsers = getSelectableUserList(userList);
self.orderBy();
self.loaders.table.user = false;
}
self.getUsers = function getUsers() {
if (!self.loaders.table.user) {
self.table.users = [];
self.loaders.table.user = true;
return Poller.poll(`/cloud/project/${self.projectId}/user`, null, {
namespace: 'cloud.users.query',
scope: $scope.$id,
interval: pollingInterval,
})
.then(
(userList) => {
updateUserList(userList);
},
(err) => {
if (err && err.status) {
self.table.user = null;
CucCloudMessage.error(
[
$translate.instant('openstackusers_users_userlist_error'),
(err.data && err.data.message) || '',
].join(' '),
);
}
},
(userList) => {
updateUserList(userList);
},
)
.finally(() => {
self.loaders.table.user = false;
});
}
return null;
};
$scope.$on('$destroy', () => {
Poller.kill({ namespace: 'cloud.users.query' });
});
self.regeneratePassword = function regeneratePassword(currentUser) {
if (!self.loaders.regeneratePassword) {
self.loaders.regeneratePassword = currentUser.id;
return OvhApiCloud.Project()
.User()
.v6()
.password(
{
serviceName: self.projectId,
userId: currentUser.id,
},
{},
)
.$promise.then(
(newUser) => {
const currentUserFound = find(
self.table.users,
(user) => user.username === currentUser.username,
);
OpenstackUsersPassword.put(
self.projectId,
currentUserFound.id,
newUser.password,
);
CucCloudMessage.success(
$translate.instant(
'openstackusers_users_regeneratepassword_success',
currentUser,
),
);
},
(err) => {
CucCloudMessage.error(
[
$translate.instant(
'openstackusers_users_regeneratepassword_error',
),
(err.data && err.data.message) || '',
].join(' '),
);
},
)
.finally(() => {
self.loaders.regeneratePassword = false;
});
}
return null;
};
self.downloadOpenrcFile = function downloadOpenrcFile(currentUser) {
CucControllerHelper.modal.showModal({
modalConfig: {
templateUrl:
'app/cloud/project/openstack/users/openrc/openstack-users-openrc.html',
controller: 'OpenstackUsersOpenrcCtrl',
controllerAs: 'OpenstackUsersOpenrcCtrl',
resolve: {
openstackUser: () => currentUser,
},
},
});
};
self.downloadRcloneFile = function downloadRcloneFile(currentUser) {
CucControllerHelper.modal.showModal({
modalConfig: {
templateUrl:
'app/cloud/project/openstack/users/rclone/openstack-users-rclone.modal.html',
controller: 'CloudProjectOpenstackUsersRcloneModalCtrl',
controllerAs: '$ctrl',
resolve: {
openstackUser() {
return currentUser;
},
},
},
});
};
self.generateToken = function generateToken(currentUser) {
CucControllerHelper.modal.showModal({
modalConfig: {
templateUrl:
'app/cloud/project/openstack/users/token/openstack-users-token.html',
controller: 'CloudProjectOpenstackUsersTokenCtrl',
controllerAs: 'CloudProjectOpenstackUsersTokenCtrl',
resolve: {
openstackUser: () => currentUser,
},
},
});
};
self.openAddUser = function openAddUser() {
CucControllerHelper.modal.showModal({
modalConfig: {
templateUrl:
'app/cloud/project/openstack/users/add/openstack-users-add.html',
controller: 'CloudProjectOpenStackUserAddCtrl',
controllerAs: '$ctrl',
resolve: {
serviceName: () => self.projectId,
},
},
successHandler: () => self.getUsers(),
});
};
self.openDeleteUser = function openDeleteUser(currentUser) {
CucControllerHelper.modal.showModal({
modalConfig: {
templateUrl:
'app/cloud/project/openstack/users/delete/openstack-users-delete.html',
controller: 'CloudProjectOpenStackUserDeleteCtrl',
controllerAs: 'CloudProjectOpenStackUserDeleteCtrl',
resolve: {
openstackUser: () => currentUser,
serviceName: () => self.projectId,
},
},
successHandler: () => {
self.removeFromList(currentUser);
CucCloudMessage.success(
$translate.instant(
'openstackusers_users_delete_success',
currentUser,
),
);
},
errorHandler: (err) =>
CucCloudMessage.error(
[
$translate.instant('openstackusers_users_delete_error'),
(err.data && err.data.message) || '',
].join(' '),
),
});
};
// Open Openstack Horizon in a new navigator window, pre-filling the user login
self.openHorizon = function openHorizon(user) {
$window.open(
REDIRECT_URLS.horizon.replace('{username}', user.username),
'_blank',
);
};
self.getPassword = function getPassword(currentUser) {
return OpenstackUsersPassword.get(self.projectId, currentUser.id);
};
self.removeFromList = function removeFromList(user) {
const index = findIndex(self.table.users, { id: user.id });
if (index !== -1) {
self.table.users.splice(index, 1);
}
};
init();
},
);
|
import { existsSync } from 'fs';
import sade from 'sade';
import colors from 'kleur';
import * as ports from 'port-authority';
import { load_config } from './core/config/index.js';
import { networkInterfaces, release } from 'os';
async function get_config() {
// TODO this is temporary, for the benefit of early adopters
if (existsSync('svelte.config.cjs')) {
// prettier-ignore
console.error(colors.bold().red(
'svelte.config.cjs should be renamed to svelte.config.js and converted to an ES module. See https://kit.svelte.dev/docs#configuration for an example'
));
}
if (existsSync('vite.config.js')) {
// prettier-ignore
console.error(colors.bold().red(
'Please remove vite.config.js and put Vite config in svelte.config.js: https://kit.svelte.dev/docs#configuration-vite'
));
}
try {
return await load_config();
} catch (error) {
let message = error.message;
if (
error.code === 'MODULE_NOT_FOUND' &&
/Cannot find module svelte\.config\./.test(error.message)
) {
message = 'Missing svelte.config.js';
} else if (error.name === 'SyntaxError') {
message = 'Malformed svelte.config.js';
}
console.error(colors.bold().red(message));
console.error(colors.grey(error.stack));
process.exit(1);
}
}
/** @param {Error} error */
function handle_error(error) {
console.log(colors.bold().red(`> ${error.message}`));
console.log(colors.gray(error.stack));
process.exit(1);
}
/**
* @param {number} port
* @param {boolean} https
*/
async function launch(port, https) {
const { exec } = await import('child_process');
let cmd = 'open';
if (process.platform == 'win32') {
cmd = 'start';
} else if (process.platform == 'linux') {
if (/microsoft/i.test(release())) {
cmd = 'cmd.exe /c start';
} else {
cmd = 'xdg-open';
}
}
exec(`${cmd} ${https ? 'https' : 'http'}://localhost:${port}`);
}
const prog = sade('svelte-kit').version('__VERSION__');
prog
.command('dev')
.describe('Start a development server')
.option('-p, --port', 'Port', 3000)
.option('-h, --host', 'Host (only use this on trusted networks)', 'localhost')
.option('-H, --https', 'Use self-signed HTTPS certificate', false)
.option('-o, --open', 'Open a browser tab', false)
.action(async ({ port, host, https, open }) => {
await check_port(port);
process.env.NODE_ENV = process.env.NODE_ENV || 'development';
const config = await get_config();
const { dev } = await import('./core/dev/index.js');
try {
const watcher = await dev({ port, host, https, config });
watcher.on('stdout', (data) => {
process.stdout.write(data);
});
watcher.on('stderr', (data) => {
process.stderr.write(data);
});
welcome({ port, host, https, open });
} catch (error) {
handle_error(error);
}
});
prog
.command('build')
.describe('Create a production build of your app')
.option('--verbose', 'Log more stuff', false)
.action(async ({ verbose }) => {
process.env.NODE_ENV = process.env.NODE_ENV || 'production';
const config = await get_config();
try {
const { build } = await import('./core/build/index.js');
const build_data = await build(config);
console.log(
`\nRun ${colors.bold().cyan('npm run preview')} to preview your production build locally.`
);
if (config.kit.adapter) {
const { adapt } = await import('./core/adapt/index.js');
await adapt(config, build_data, { verbose });
// this is necessary to close any open db connections, etc
process.exit(0);
}
console.log(colors.bold().yellow('\nNo adapter specified'));
// prettier-ignore
console.log(
`See ${colors.bold().cyan('https://kit.svelte.dev/docs#adapters')} to learn how to configure your app to run on the platform of your choosing`
);
} catch (error) {
handle_error(error);
}
});
prog
.command('preview')
.describe('Serve an already-built app')
.option('-p, --port', 'Port', 3000)
.option('-h, --host', 'Host (only use this on trusted networks)', 'localhost')
.option('-H, --https', 'Use self-signed HTTPS certificate', false)
.option('-o, --open', 'Open a browser tab', false)
.action(async ({ port, host, https, open }) => {
await check_port(port);
process.env.NODE_ENV = process.env.NODE_ENV || 'production';
const config = await get_config();
const { start } = await import('./core/start/index.js');
try {
await start({ port, host, config, https });
welcome({ port, host, https, open });
} catch (error) {
handle_error(error);
}
});
// TODO remove this after a few versions
prog
.command('start')
.describe('Deprecated — use svelte-kit preview instead')
.option('-p, --port', 'Port', 3000)
.option('-h, --host', 'Host (only use this on trusted networks)', 'localhost')
.option('-H, --https', 'Use self-signed HTTPS certificate', false)
.option('-o, --open', 'Open a browser tab', false)
.action(async () => {
console.log(
colors
.bold()
.red(
'"svelte-kit preview" will now preview your production build locally. Note: it is not intended for production use'
)
);
});
prog
.command('package')
.describe('Create a package')
.option('-d, --dir', 'Destination directory', 'package')
.action(async () => {
const config = await get_config();
const { make_package } = await import('./core/make_package/index.js');
try {
await make_package(config);
} catch (error) {
handle_error(error);
}
});
prog.parse(process.argv, { unknown: (arg) => `Unknown option: ${arg}` });
/** @param {number} port */
async function check_port(port) {
const n = await ports.blame(port);
if (n) {
console.log(colors.bold().red(`Port ${port} is occupied`));
// prettier-ignore
console.log(
`Terminate process ${colors.bold(n)} or specify a different port with ${colors.bold('--port')}\n`
);
process.exit(1);
}
}
/**
* @param {{
* open: boolean;
* host: string;
* https: boolean;
* port: number;
* }} param0
*/
function welcome({ port, host, https, open }) {
if (open) launch(port, https);
console.log(colors.bold().cyan(`\n SvelteKit v${'__VERSION__'}\n`));
const protocol = https ? 'https:' : 'http:';
const exposed = host !== 'localhost' && host !== '127.0.0.1';
Object.values(networkInterfaces()).forEach((interfaces) => {
interfaces.forEach((details) => {
if (details.family !== 'IPv4') return;
// prettier-ignore
if (details.internal) {
console.log(` ${colors.gray('local: ')} ${protocol}//${colors.bold(`localhost:${port}`)}`);
} else {
if (details.mac === '00:00:00:00:00:00') return;
if (exposed) {
console.log(` ${colors.gray('network:')} ${protocol}//${colors.bold(`${details.address}:${port}`)}`);
} else {
console.log(` ${colors.gray('network: not exposed')}`);
}
}
});
});
if (!exposed) {
console.log('\n Use --host to expose server to other devices on this network');
}
console.log('\n');
}
|
import Ember from 'ember';
import { STATUS, STATUS_INTL_KEY, classForStatus } from 'ui/components/accordion-list-item/component';
export default Ember.Component.extend({
intl: Ember.inject.service(),
service : null,
allCertificates : null,
lbConfig: Ember.computed.alias('service.lbConfig'),
alternates : null,
init() {
this._super(...arguments);
var alternates = (this.get('lbConfig.certificateIds')||[]).map((id) => {
return {value: id};
});
this.set('alternates', alternates);
},
didReceiveAttrs() {
if (!this.get('expandFn')) {
this.set('expandFn', function(item) {
item.toggleProperty('expanded');
});
}
},
actions: {
addAlternate() {
this.get('alternates').pushObject({value: null});
},
removeAlternate(alt) {
this.get('alternates').removeObject(alt);
},
},
alternateCertificates: function() {
var def = this.get('lbConfig.defaultCertificateId');
return this.get('allCertificates').slice().filter((obj) => {
return Ember.get(obj, 'id') !== def;
});
}.property('allCertificates.@each.id','lbConfig.defaultCertificateId'),
defaultDidChange: function() {
var def = this.get('lbConfig.defaultCertificateId');
this.get('alternates').forEach((obj) => {
if ( Ember.get(obj, 'value') === def )
{
Ember.set(obj,'value',null);
}
});
}.observes('lbConfig.defaultCertificateId'),
alternatesDidChange: function() {
this.set('lbConfig.certificateIds', this.get('alternates').map((obj) => {
return Ember.get(obj, 'value');
}).filter((id) => { return !!id; }).uniq());
}.observes('alternates.@each.value'),
updateLabels(labels) {
this.sendAction('setLabels', labels);
},
statusClass: null,
status: function() {
let k = STATUS.NONE;
let count = this.get('lbConfig.certificateIds.length')||0;
if ( !!this.get('lbConfig.defaultCertificateId') ) {
count++;
}
if ( this.get('lbConfig.needsCertificate') && !count ) {
k = STATUS.INCOMPLETE;
}
if ( count ) {
k = STATUS.COUNTCONFIGURED;
}
this.set('statusClass', classForStatus(k));
return this.get('intl').t(`${STATUS_INTL_KEY}.${k}`, {count: count});
}.property('lbConfig.certificateIds.[]','lbConfig.defaultCertificateId'),
});
|
module.exports = {
isAzStyle (peerId) {
if (peerId.charAt(0) !== '-') return false
if (peerId.charAt(7) === '-') return true
/**
* Hack for FlashGet - it doesn't use the trailing dash.
* Also, LH-ABC has strayed into "forgetting about the delimiter" territory.
*
* In fact, the code to generate a peer ID for LH-ABC is based on BitTornado's,
* yet tries to give an Az style peer ID... oh dear.
*
* BT Next Evolution seems to be in the same boat as well.
*
* KTorrent 3 appears to use a dash rather than a final character.
*/
if (['FG', 'LH', 'NE', 'KT', 'SP'].includes(peerId.substring(1, 3))) return true
return false
},
/**
* Checking whether a peer ID is Shadow style or not is a bit tricky.
*
* The BitTornado peer ID convention code is explained here:
* http://forums.degreez.net/viewtopic.php?t=7070
*
* The main thing we are interested in is the first six characters.
* Although the other characters are base64 characters, there's no
* guarantee that other clients which follow that style will follow
* that convention (though the fact that some of these clients use
* BitTornado in the core does blur the lines a bit between what is
* "style" and what is just common across clients).
*
* So if we base it on the version number information, there's another
* problem - there isn't the use of absolute delimiters (no fixed dash
* character, for example).
*
* There are various things we can do to determine how likely the peer
* ID is to be of that style, but for now, I'll keep it to a relatively
* simple check.
*
* We'll assume that no client uses the fifth version digit, so we'll
* expect a dash. We'll also assume that no client has reached version 10
* yet, so we expect the first two characters to be "letter,digit".
*
* We've seen some clients which don't appear to contain any version
* information, so we need to allow for that.
*/
isShadowStyle (peerId) {
if (peerId.charAt(5) !== '-') return false
if (!isLetter(peerId.charAt(0))) return false
if (!(isDigit(peerId.charAt(1)) || peerId.charAt(1) === '-')) return false
// Find where the version number string ends.
let lastVersionNumberIndex = 4
for (; lastVersionNumberIndex > 0; lastVersionNumberIndex--) {
if (peerId.charAt(lastVersionNumberIndex) !== '-') break
}
// For each digit in the version string, check if it is a valid version identifier.
for (let i = 1; i <= lastVersionNumberIndex; i++) {
const c = peerId.charAt(i)
if (c === '-') return false
if (isAlphaNumeric(c) === null) return false
}
return true
},
isMainlineStyle (peerId) {
/**
* One of the following styles will be used:
* Mx-y-z--
* Mx-yy-z-
*/
return peerId.charAt(2) === '-' && peerId.charAt(7) === '-' &&
(peerId.charAt(4) === '-' || peerId.charAt(5) === '-')
},
isPossibleSpoofClient (peerId) {
return peerId.endsWith('UDP0') || peerId.endsWith('HTTPBT')
},
decodeNumericValueOfByte,
getAzStyleVersionNumber (peerId, version) {
if (typeof version === 'function') {
return version(peerId)
}
return null
},
getShadowStyleVersionNumber (peerId) {
// TODO
return null
},
decodeBitSpiritClient (peerId, buffer) {
if (peerId.substring(2, 4) !== 'BS') return null
let version = `${buffer[1]}`
if (version === '0') version = 1
return {
client: 'BitSpirit',
version
}
},
decodeBitCometClient (peerId, buffer) {
let modName = ''
if (peerId.startsWith('exbc')) modName = ''
else if (peerId.startsWith('FUTB')) modName = '(Solidox Mod)'
else if (peerId.startsWith('xUTB')) modName = '(Mod 2)'
else return null
const isBitlord = (peerId.substring(6, 10) === 'LORD')
// Older versions of BitLord are of the form x.yy, whereas new versions (1 and onwards),
// are of the form x.y. BitComet is of the form x.yy
const clientName = (isBitlord) ? 'BitLord' : 'BitComet'
const majVersion = decodeNumericValueOfByte(buffer[4])
const minVersionLength = (isBitlord && majVersion !== '0' ? 1 : 2)
return {
client: clientName + (modName ? ` ${modName}` : ''),
version: `${majVersion}.${decodeNumericValueOfByte(buffer[5], minVersionLength)}`
}
},
identifyAwkwardClient (peerId, buffer) {
let firstNonZeroIndex = 20
let i
for (i = 0; i < 20; ++i) {
if (buffer[i] > 0) {
firstNonZeroIndex = i
break
}
}
// Shareaza check
if (firstNonZeroIndex === 0) {
let isShareaza = true
for (i = 0; i < 16; ++i) {
if (buffer[i] === 0) {
isShareaza = false
break
}
}
if (isShareaza) {
for (i = 16; i < 20; ++i) {
if (buffer[i] !== (buffer[i % 16] ^ buffer[15 - (i % 16)])) {
isShareaza = false
break
}
}
if (isShareaza) return { client: 'Shareaza' }
}
}
if (firstNonZeroIndex === 9 && buffer[9] === 3 && buffer[10] === 3 && buffer[11] === 3) { return { client: 'I2PSnark' } }
if (firstNonZeroIndex === 12 && buffer[12] === 97 && buffer[13] === 97) { return { client: 'Experimental', version: '3.2.1b2' } }
if (firstNonZeroIndex === 12 && buffer[12] === 0 && buffer[13] === 0) { return { client: 'Experimental', version: '3.1' } }
if (firstNonZeroIndex === 12) { return { client: 'Mainline' } }
return null
}
}
//
// Private helper functions for the public utility functions
//
function isDigit (s) {
const code = s.charCodeAt(0)
return code >= '0'.charCodeAt(0) && code <= '9'.charCodeAt(0)
}
function isLetter (s) {
const code = s.toLowerCase().charCodeAt(0)
return code >= 'a'.charCodeAt(0) && code <= 'z'.charCodeAt(0)
}
function isAlphaNumeric (s) {
return isDigit(s) || isLetter(s) || s === '.'
}
function decodeNumericValueOfByte (b, minDigits = 0) {
let result = `${b & 0xff}`
while (result.length < minDigits) { result = `0${result}` }
return result
}
|
"use strict";
// Native Node Imports
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var fs = require("fs");
var Logger_1 = require("../Logger");
var Add = function () {
function Add(queue) {
_classCallCheck(this, Add);
this.usage = "%cmd% <link>";
this.description = "Add a song to the dJ queue.";
this.args = 1;
this.staff = false;
this.queue = queue;
}
_createClass(Add, [{
key: "onCommand",
value: function onCommand(bot, message, args) {
bot.client.startTyping(message.channel);
this.queue.addRequest(require("valid-url").isUri(args[0]) ? args[0] : args.join(" "), message.author).then(function (data) {
Logger_1.default.announce(bot, "Added song `" + (data.request.shortTitle ? data.request.shortTitle : data.request.title) + " [" + data.request.durationAsString + "]`, position `" + data.position + "`.");
}).catch(function (error) {
if (error.message === "Invalid URL.") {
Logger_1.default.error(bot, "Invalid URL. Supported sites: https://rg3.github.io/youtube-dl/supportedsites.html");
} else if (error.message === "Playlists not supported.") {
Logger_1.default.error(bot, "Playlists are not currently supported due to how process-intensive they are.");
} else {
Logger_1.default.error(bot, "Unknown Error:\n\n```" + error.message + "```", error);
}
});
}
}]);
return Add;
}();
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = Add;
//# sourceMappingURL=Add.js.map
|
import axios from "axios";
import { logger } from "@/helpers.js";
const log = logger("[user]");
// const usersCol = "users";
const state = {
usersList: {},
loading: {
list: false
},
error: null
};
const getters = {
usersList: state => state.usersList,
loading: state => state.loading,
error: state => state.error
};
/**
* @param {firebase.functions.Functions} fireFunctions
*/
const actions = fireFunctions => {
const listUsersCallable = fireFunctions.httpsCallable("listUsers");
const makeKing = async ({ commit }, payload) => {
await axios
.post(process.env.VUE_APP_API + "/user/makeAdmin", payload)
.then(res => res.data)
.catch(error => {
throw error.response.data;
});
};
const listUsers = async ({ commit }) => {
try {
const users = await listUsersCallable();
log("woot", users.data);
commit("listUsersReceived", users);
} catch (error) {
commit("errorCatched", error, { root: true });
}
};
return Object.freeze({ listUsers, makeKing });
};
const mutations = {
loading(state, process) {
state.loading = { ...state.loading, ...process };
log("Loading", process);
},
listUsersReceived(state, users) {
state.usersList = users;
log("List users", users);
}
};
export default fireFunctions => ({
namespaced: true,
state,
getters,
actions: actions(fireFunctions),
mutations
});
|
import os
import sys
sys.path.append(".")
sys.path.append("..")
from utils import constants
def read_vocab_file(vocab_file):
token2index = {}
index2token = []
with open(vocab_file, 'r', encoding="utf-8") as f:
for line in f.readlines():
token = line.strip()
if token != '':
token2index[token] = len(index2token)
index2token.append(token)
return token2index, index2token
class SimpleVocab:
def __init__(self, vocab_file, **kwargs):
self.PAD_TOKEN = kwargs.pop("pad_token", constants.PAD_TOKEN)
self.UNK_TOKEN = kwargs.pop("unk_token", constants.UNK_TOKEN)
self.SOS_TOKEN = kwargs.pop("sos_token", constants.SOS_TOKEN)
self.EOS_TOKEN = kwargs.pop("eos_token", constants.EOS_TOKEN)
self.token2index, self.index2token = read_vocab_file(vocab_file)
keywords = [
("PAD_ID", self.PAD_TOKEN),
("UNK_ID", self.UNK_TOKEN),
("SOS_ID", self.SOS_TOKEN),
("EOS_ID", self.EOS_TOKEN),
]
for i, t in keywords:
try:
setattr(self, i, self.token2index[t])
print(self.token2index[t], i)
except KeyError:
self.token2index[t] = len(self.index2token)
self.index2token.append(t)
setattr(self, i, self.token2index[t])
print(self.token2index[t], i)
# self.UNK_ID = self.token2index[self.UNK_TOKEN]
# self.SOS_ID = self.token2index[self.SOS_TOKEN]
# self.EOS_ID = self.token2index[self.EOS_TOKEN]
def token_to_index(self, token_list):
index_list = []
for token in token_list:
index_list.append(self.token2index.get(token, self.UNK_ID))
return index_list
def index_to_token(self, index_list, include_sos_eos=True):
token_list = []
for index in index_list:
if include_sos_eos or (index != self.SOS_ID and index != self.EOS_ID):
token = self.index2token[index]
token_list.append(token)
if index == self.EOS_ID:
break
return token_list
def get_vocab_size(self):
return len(self.index2token)
class BasicTokenizer(SimpleVocab):
def __init__(self, vocab_file, lower_case=True, pad_token=constants.PAD_TOKEN,
unk_token=constants.UNK_TOKEN, sos_token=constants.SOS_TOKEN,
eos_token=constants.EOS_TOKEN):
super(BasicTokenizer, self).__init__(
vocab_file, pad_token=constants.PAD_TOKEN, unk_token=constants.UNK_TOKEN,
sos_token=constants.SOS_TOKEN, eos_token=constants.EOS_TOKEN
)
self.lower_case = lower_case
def tokenize(self, text):
_token_list = text.strip().split()
token_list = []
for token in _token_list:
if self.lower_case:
token = token.lower()
token_list.append(token)
return token_list
def encode(self, text):
"""
encode text into index list
"""
token_list = self.tokenize(text)
index_list = self.token_to_index(token_list)
return index_list
def decode(self, index_list, include_sos_eos=True):
"""
decode index list into text
"""
token_list = self.index_to_token(index_list, include_sos_eos)
text = ' '.join(token_list)
return text
|
const _ = require("the-lodash");
module.exports = {
target: {
path: ["ns"]
},
order: 10,
handler: ({scope, item, logger}) =>
{
logger.info("Polisher NS: %s", item.naming);
var namespaceScope = scope.getNamespaceScope(item.naming);
var properties = {
"Applications": _.keys(namespaceScope.apps).length,
"Ingresses": _.keys(namespaceScope.ingresses).length,
"Secrets": _.keys(namespaceScope.secrets).length
}
item.addProperties({
kind: "key-value",
id: "properties",
title: "Properties",
order: 5,
config: properties
});
}
}
|
(function(){/*
Copyright The Closure Library Authors.
SPDX-License-Identifier: Apache-2.0
*/
function aa(a){var b=0;return function(){return b<a.length?{done:!1,value:a[b++]}:{done:!0}}}function k(a){var b="undefined"!=typeof Symbol&&Symbol.iterator&&a[Symbol.iterator];return b?b.call(a):{next:aa(a)}}function ba(a){if(!(a instanceof Array)){a=k(a);for(var b,c=[];!(b=a.next()).done;)c.push(b.value);a=c}return a}var ca="function"==typeof Object.create?Object.create:function(a){function b(){}b.prototype=a;return new b},da;
if("function"==typeof Object.setPrototypeOf)da=Object.setPrototypeOf;else{var ea;a:{var fa={$:!0},ha={};try{ha.__proto__=fa;ea=ha.$;break a}catch(a){}ea=!1}da=ea?function(a,b){a.__proto__=b;if(a.__proto__!==b)throw new TypeError(a+" is not extensible");return a}:null}var ia=da,ka="function"==typeof Object.defineProperties?Object.defineProperty:function(a,b,c){a!=Array.prototype&&a!=Object.prototype&&(a[b]=c.value)};
function ma(a){a=["object"==typeof window&&window,"object"==typeof self&&self,"object"==typeof global&&global,a];for(var b=0;b<a.length;++b){var c=a[b];if(c&&c.Math==Math)return c}throw Error("Cannot find global object");}var na=ma(this);function oa(a,b){if(b){var c=na;a=a.split(".");for(var d=0;d<a.length-1;d++){var e=a[d];e in c||(c[e]={});c=c[e]}a=a[a.length-1];d=c[a];b=b(d);b!=d&&null!=b&&ka(c,a,{configurable:!0,writable:!0,value:b})}}
oa("Number.isFinite",function(a){return a?a:function(b){return"number"!==typeof b?!1:!isNaN(b)&&Infinity!==b&&-Infinity!==b}});oa("Number.isInteger",function(a){return a?a:function(b){return Number.isFinite(b)?b===Math.floor(b):!1}});oa("Object.is",function(a){return a?a:function(b,c){return b===c?0!==b||1/b===1/c:b!==b&&c!==c}});
oa("Array.prototype.includes",function(a){return a?a:function(b,c){var d=this;d instanceof String&&(d=String(d));var e=d.length;c=c||0;for(0>c&&(c=Math.max(c+e,0));c<e;c++){var f=d[c];if(f===b||Object.is(f,b))return!0}return!1}});var n=this||self,pa=/^[\w+/_-]+[=]{0,2}$/,qa=null;
function ra(a){var b=typeof a;if("object"==b)if(a){if(a instanceof Array)return"array";if(a instanceof Object)return b;var c=Object.prototype.toString.call(a);if("[object Window]"==c)return"object";if("[object Array]"==c||"number"==typeof a.length&&"undefined"!=typeof a.splice&&"undefined"!=typeof a.propertyIsEnumerable&&!a.propertyIsEnumerable("splice"))return"array";if("[object Function]"==c||"undefined"!=typeof a.call&&"undefined"!=typeof a.propertyIsEnumerable&&!a.propertyIsEnumerable("call"))return"function"}else return"null";
else if("function"==b&&"undefined"==typeof a.call)return"object";return b}function sa(a){var b=typeof a;return"object"==b&&null!=a||"function"==b}var ta="closure_uid_"+(1E9*Math.random()>>>0),xa=0;function q(a,b){function c(){}c.prototype=b.prototype;a.prototype=new c;a.prototype.constructor=a};var ya;function za(a,b){if("string"===typeof a)return"string"!==typeof b||1!=b.length?-1:a.indexOf(b,0);for(var c=0;c<a.length;c++)if(c in a&&a[c]===b)return c;return-1}function u(a,b){for(var c=a.length,d="string"===typeof a?a.split(""):a,e=0;e<c;e++)e in d&&b.call(void 0,d[e],e,a)}function Aa(a,b){for(var c=a.length,d=[],e=0,f="string"===typeof a?a.split(""):a,h=0;h<c;h++)if(h in f){var g=f[h];b.call(void 0,g,h,a)&&(d[e++]=g)}return d}
function Ba(a,b){for(var c=a.length,d=Array(c),e="string"===typeof a?a.split(""):a,f=0;f<c;f++)f in e&&(d[f]=b.call(void 0,e[f],f,a));return d}function Ca(a,b,c){var d=c;u(a,function(e,f){d=b.call(void 0,d,e,f,a)});return d}function Da(a,b){a:{for(var c=a.length,d="string"===typeof a?a.split(""):a,e=0;e<c;e++)if(e in d&&b.call(void 0,d[e],e,a)){b=e;break a}b=-1}return 0>b?null:"string"===typeof a?a.charAt(b):a[b]}
function Ea(a,b){for(var c=1;c<arguments.length;c++){var d=arguments[c],e=ra(d);if("array"==e||"object"==e&&"number"==typeof d.length){e=a.length||0;var f=d.length||0;a.length=e+f;for(var h=0;h<f;h++)a[e+h]=d[h]}else a.push(d)}}function Fa(a,b){a.sort(b||Ga)}function Ga(a,b){return a>b?1:a<b?-1:0};function Ha(a){var b=!1,c;return function(){b||(c=a(),b=!0);return c}}function Ia(a){function b(){d=n.setTimeout(c,1E3);a.apply(void 0,f)}function c(){d=0;e&&(e=!1,b())}var d=0,e=!1,f=[];return function(h){f=arguments;d?e=!0:b()}};function Ja(a,b){for(var c in a)if(b.call(void 0,a[c],c,a))return c}function Ka(a){for(var b in a)delete a[b]};function La(a,b){this.f=a===Ma&&b||"";this.a=Na}var Na={},Ma={};function Qa(a){return/^[\s\xa0]*([\s\S]*?)[\s\xa0]*$/.exec(a)[1]}function Ra(a,b){return a<b?-1:a>b?1:0};var Sa;a:{var Ta=n.navigator;if(Ta){var Ua=Ta.userAgent;if(Ua){Sa=Ua;break a}}Sa=""}function w(a){return-1!=Sa.indexOf(a)};function Va(a){Va[" "](a);return a}Va[" "]=function(){};function Wa(a,b){var c=Xa;return Object.prototype.hasOwnProperty.call(c,a)?c[a]:c[a]=b(a)};var Ya=w("Opera"),x=w("Trident")||w("MSIE"),Za=w("Edge"),$a=w("Gecko")&&!(-1!=Sa.toLowerCase().indexOf("webkit")&&!w("Edge"))&&!(w("Trident")||w("MSIE"))&&!w("Edge"),ab=-1!=Sa.toLowerCase().indexOf("webkit")&&!w("Edge");function bb(){var a=n.document;return a?a.documentMode:void 0}var cb;
a:{var db="",eb=function(){var a=Sa;if($a)return/rv:([^\);]+)(\)|;)/.exec(a);if(Za)return/Edge\/([\d\.]+)/.exec(a);if(x)return/\b(?:MSIE|rv)[: ]([^\);]+)(\)|;)/.exec(a);if(ab)return/WebKit\/(\S+)/.exec(a);if(Ya)return/(?:Version)[ \/]?(\S+)/.exec(a)}();eb&&(db=eb?eb[1]:"");if(x){var fb=bb();if(null!=fb&&fb>parseFloat(db)){cb=String(fb);break a}}cb=db}var hb=cb,Xa={};
function ib(a){return Wa(a,function(){for(var b=0,c=Qa(String(hb)).split("."),d=Qa(String(a)).split("."),e=Math.max(c.length,d.length),f=0;0==b&&f<e;f++){var h=c[f]||"",g=d[f]||"";do{h=/(\d*)(\D*)(.*)/.exec(h)||["","","",""];g=/(\d*)(\D*)(.*)/.exec(g)||["","","",""];if(0==h[0].length&&0==g[0].length)break;b=Ra(0==h[1].length?0:parseInt(h[1],10),0==g[1].length?0:parseInt(g[1],10))||Ra(0==h[2].length,0==g[2].length)||Ra(h[2],g[2]);h=h[3];g=g[3]}while(0==b)}return 0<=b})}var jb;
if(n.document&&x){var kb=bb();jb=kb?kb:parseInt(hb,10)||void 0}else jb=void 0;var lb=jb;var mb=w("Safari")&&!((w("Chrome")||w("CriOS"))&&!w("Edge")||w("Coast")||w("Opera")||w("Edge")||w("Edg/")||w("OPR")||w("Firefox")||w("FxiOS")||w("Silk")||w("Android"))&&!(w("iPhone")&&!w("iPod")&&!w("iPad")||w("iPad")||w("iPod"));var nb={},ob=null,pb=$a||ab&&!mb||Ya||!mb&&!x&&"function"==typeof n.atob;function qb(a){var b=4;void 0===b&&(b=0);rb();b=nb[b];for(var c=[],d=0;d<a.length;d+=3){var e=a[d],f=d+1<a.length,h=f?a[d+1]:0,g=d+2<a.length,p=g?a[d+2]:0,l=e>>2;e=(e&3)<<4|h>>4;h=(h&15)<<2|p>>6;p&=63;g||(p=64,f||(h=64));c.push(b[l],b[e],b[h]||"",b[p]||"")}return c.join("")}function sb(a){if(pb)return n.atob(a);var b="";tb(a,function(c){b+=String.fromCharCode(c)});return b}
function tb(a,b){function c(p){for(;d<a.length;){var l=a.charAt(d++),m=ob[l];if(null!=m)return m;if(!/^[\s\xa0]*$/.test(l))throw Error("Unknown base64 encoding at char: "+l);}return p}rb();for(var d=0;;){var e=c(-1),f=c(0),h=c(64),g=c(64);if(64===g&&-1===e)break;b(e<<2|f>>4);64!=h&&(b(f<<4&240|h>>2),64!=g&&b(h<<6&192|g))}}
function rb(){if(!ob){ob={};for(var a="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789".split(""),b=["+/=","+/","-_=","-_.","-_"],c=0;5>c;c++){var d=a.concat(b[c].split(""));nb[c]=d;for(var e=0;e<d.length;e++){var f=d[e];void 0===ob[f]&&(ob[f]=e)}}}};var ub=0,vb=0;function wb(){this.a=[]}wb.prototype.length=function(){return this.a.length};function xb(a){var b=a.a;a.a=[];return b}function yb(a,b){for(;127<b;)a.a.push(b&127|128),b>>>=7;a.a.push(b)};function zb(){this.g=[];this.f=0;this.a=new wb}function Ab(a,b){yb(a.a,8*b+2);b=xb(a.a);a.g.push(b);a.f+=b.length;b.push(a.f);return b}function Bb(a,b){var c=b.pop();for(c=a.f+a.a.length()-c;127<c;)b.push(c&127|128),c>>>=7,a.f++;b.push(c);a.f++}function Cb(a){for(var b=new Uint8Array(a.f+a.a.length()),c=a.g,d=c.length,e=0,f=0;f<d;f++){var h=c[f];b.set(h,e);e+=h.length}c=xb(a.a);b.set(c,e);a.g=[b];return b}
function y(a,b,c){if(null!=c&&null!=c){yb(a.a,8*b);a=a.a;var d=c;c=0>d;d=Math.abs(d);b=d>>>0;d=Math.floor((d-b)/4294967296);d>>>=0;c&&(d=~d>>>0,b=(~b>>>0)+1,4294967295<b&&(b=0,d++,4294967295<d&&(d=0)));ub=b;vb=d;c=ub;for(b=vb;0<b||127<c;)a.a.push(c&127|128),c=(c>>>7|b<<25)>>>0,b>>>=7;a.a.push(c)}}function Db(a,b,c){null!=c&&(yb(a.a,8*b),a.a.a.push(c?1:0))}function B(a,b,c){if(null!=c)if(yb(a.a,8*b),a=a.a,0<=c)yb(a,c);else{for(b=0;9>b;b++)a.a.push(c&127|128),c>>=7;a.a.push(1)}}
function Eb(a,b,c){if(null!=c){b=Ab(a,b);for(var d=a.a,e=0;e<c.length;e++){var f=c.charCodeAt(e);if(128>f)d.a.push(f);else if(2048>f)d.a.push(f>>6|192),d.a.push(f&63|128);else if(65536>f)if(55296<=f&&56319>=f&&e+1<c.length){var h=c.charCodeAt(e+1);56320<=h&&57343>=h&&(f=1024*(f-55296)+h-56320+65536,d.a.push(f>>18|240),d.a.push(f>>12&63|128),d.a.push(f>>6&63|128),d.a.push(f&63|128),e++)}else d.a.push(f>>12|224),d.a.push(f>>6&63|128),d.a.push(f&63|128)}Bb(a,b)}}
function Fb(a,b,c,d){if(null!=c)for(var e=0;e<c.length;e++){var f=Ab(a,b);d(c[e],a);Bb(a,f)}};function C(){}var Gb="function"==typeof Uint8Array;function G(a,b,c,d){a.a=null;b||(b=[]);a.j=void 0;a.g=-1;a.l=b;a:{if(b=a.l.length){--b;var e=a.l[b];if(!(null===e||"object"!=typeof e||Array.isArray(e)||Gb&&e instanceof Uint8Array)){a.h=b-a.g;a.f=e;break a}}a.h=Number.MAX_VALUE}a.i={};if(c)for(b=0;b<c.length;b++)e=c[b],e<a.h?(e+=a.g,a.l[e]=a.l[e]||Hb):(Ib(a),a.f[e]=a.f[e]||Hb);if(d&&d.length)for(b=0;b<d.length;b++)Jb(a,d[b])}var Hb=[];function Ib(a){var b=a.h+a.g;a.l[b]||(a.f=a.l[b]={})}
function H(a,b){if(b<a.h){b+=a.g;var c=a.l[b];return c===Hb?a.l[b]=[]:c}if(a.f)return c=a.f[b],c===Hb?a.f[b]=[]:c}function I(a,b,c){a=H(a,b);return null==a?c:a}function J(a,b){a=H(a,b);a=null==a?a:!!a;return null==a?!1:a}function Kb(a,b,c){b<a.h?a.l[b+a.g]=c:(Ib(a),a.f[b]=c);return a}function K(a,b,c){return M(a,b,c,0)}function M(a,b,c,d){c!==d?Kb(a,b,c):b<a.h?a.l[b+a.g]=null:(Ib(a),delete a.f[b]);return a}
function Jb(a,b){for(var c,d,e=0;e<b.length;e++){var f=b[e],h=H(a,f);null!=h&&(c=f,d=h,Kb(a,f,void 0))}return c?(Kb(a,c,d),c):0}function Lb(a,b,c){a.a||(a.a={});if(!a.a[c]){var d=H(a,c);d&&(a.a[c]=new b(d))}return a.a[c]}function Mb(a,b,c){Nb(a,b,c);b=a.a[c];b==Hb&&(b=a.a[c]=[]);return b}function Nb(a,b,c){a.a||(a.a={});if(!a.a[c]){for(var d=H(a,c),e=[],f=0;f<d.length;f++)e[f]=new b(d[f]);a.a[c]=e}}function Ob(a,b,c){a.a||(a.a={});var d=c?c.l:c;a.a[b]=c;Kb(a,b,d)}
function Pb(a,b){var c=Qb[0];a.a||(a.a={});var d=b?b.l:b;a.a[5]=b;(b=Jb(a,c))&&5!==b&&void 0!==d&&(a.a&&b in a.a&&(a.a[b]=void 0),Kb(a,b,void 0));Kb(a,5,d)}function Rb(a,b,c,d){Nb(a,d,b);var e=a.a[b];e||(e=a.a[b]=[]);c=c?c:new d;a=H(a,b);e.push(c);a.push(c.l)}C.prototype.toString=function(){return this.l.toString()};var Sb=document,Tb=window;var Vb=Ha(function(){var a=!1;try{var b=Object.defineProperty({},"passive",{get:function(){a=!0}});n.addEventListener("test",null,b)}catch(c){}return a});function Wb(a){return a?a.passive&&Vb()?a:a.capture||!1:!1}function N(a,b,c,d){a.addEventListener&&a.addEventListener(b,c,Wb(d))}function Xb(a,b,c){a.removeEventListener&&a.removeEventListener(b,c,Wb(void 0))}
function Yb(a){var b=void 0===b?{}:b;if("function"==ra(window.CustomEvent))var c=new CustomEvent("rum_blp",b);else c=document.createEvent("CustomEvent"),c.initCustomEvent("rum_blp",!!b.bubbles,!!b.cancelable,b.detail);a.dispatchEvent(c)};var Zb=x||Ya||ab;function $b(a){return Ca(arguments,function(b,c){return b+c},0)}function ac(a){return $b.apply(null,arguments)/arguments.length};function bc(a,b){this.a=void 0!==a?a:0;this.f=void 0!==b?b:0}bc.prototype.ceil=function(){this.a=Math.ceil(this.a);this.f=Math.ceil(this.f);return this};bc.prototype.floor=function(){this.a=Math.floor(this.a);this.f=Math.floor(this.f);return this};bc.prototype.round=function(){this.a=Math.round(this.a);this.f=Math.round(this.f);return this};function cc(a,b){this.width=a;this.height=b}cc.prototype.aspectRatio=function(){return this.width/this.height};cc.prototype.ceil=function(){this.width=Math.ceil(this.width);this.height=Math.ceil(this.height);return this};cc.prototype.floor=function(){this.width=Math.floor(this.width);this.height=Math.floor(this.height);return this};cc.prototype.round=function(){this.width=Math.round(this.width);this.height=Math.round(this.height);return this};function dc(a,b){for(;a&&1!=a.nodeType;)a=b?a.nextSibling:a.previousSibling;return a}function ec(a){var b;if(Zb&&!(x&&ib("9")&&!ib("10")&&n.SVGElement&&a instanceof n.SVGElement)&&(b=a.parentElement))return b;b=a.parentNode;return sa(b)&&1==b.nodeType?b:null}function fc(a){return 9==a.nodeType?a:a.ownerDocument||a.document}function gc(a){var b=hc;a&&(a=a.parentNode);for(var c=0;a&&6>=c;){if(b(a))return a;a=a.parentNode;c++}return null}function ic(a){this.a=a||n.document||document}
ic.prototype.contains=function(a,b){if(!a||!b)return!1;if(a.contains&&1==b.nodeType)return a==b||a.contains(b);if("undefined"!=typeof a.compareDocumentPosition)return a==b||!!(a.compareDocumentPosition(b)&16);for(;b&&a!=b;)b=b.parentNode;return b==a};var jc=/^(?:([^:/?#.]+):)?(?:\/\/(?:([^\\/?#]*)@)?([^\\/?#]*?)(?::([0-9]+))?(?=[\\/?#]|$))?([^?#]+)?(?:\?([^#]*))?(?:#([\s\S]*))?$/;function kc(a){return a?decodeURI(a):a};function lc(a){try{var b;if(b=!!a&&null!=a.location.href)a:{try{Va(a.foo);b=!0;break a}catch(c){}b=!1}return b}catch(c){return!1}}function mc(a){return lc(a.top)?a.top:null}function nc(a,b){if(a)for(var c in a)Object.prototype.hasOwnProperty.call(a,c)&&b.call(void 0,a[c],c,a)}function oc(a,b){return Ja(a,function(c,d){return Object.prototype.hasOwnProperty.call(a,d)&&b(c,d)})}
function pc(a){var b=a.length;if(0==b)return 0;for(var c=305419896,d=0;d<b;d++)c^=(c<<5)+(c>>2)+a.charCodeAt(d)&4294967295;return 0<c?c:4294967296+c}function qc(a){a=a&&a.toString&&a.toString();return"string"===typeof a&&-1!=a.indexOf("[native code]")}
function rc(a){var b="https://pagead2.googlesyndication.com/pagead/gen_204?id=reportingobserver";nc(a,function(c,d){c&&(b+="&"+d+"="+encodeURIComponent(c))});window.fetch(b,{keepalive:!0,credentials:"include",redirect:"follow",method:"get",mode:"no-cors"})};function sc(a,b,c,d){this.left=a;this.top=b;this.width=c;this.height=d}sc.prototype.contains=function(a){return a instanceof bc?a.a>=this.left&&a.a<=this.left+this.width&&a.f>=this.top&&a.f<=this.top+this.height:this.left<=a.left&&this.left+this.width>=a.left+a.width&&this.top<=a.top&&this.top+this.height>=a.top+a.height};sc.prototype.ceil=function(){this.left=Math.ceil(this.left);this.top=Math.ceil(this.top);this.width=Math.ceil(this.width);this.height=Math.ceil(this.height);return this};
sc.prototype.floor=function(){this.left=Math.floor(this.left);this.top=Math.floor(this.top);this.width=Math.floor(this.width);this.height=Math.floor(this.height);return this};sc.prototype.round=function(){this.left=Math.round(this.left);this.top=Math.round(this.top);this.width=Math.round(this.width);this.height=Math.round(this.height);return this};var tc;a:{var uc=void 0;uc=void 0===uc?n:uc;var vc=uc.context||uc.AMP_CONTEXT_DATA;if(!vc)try{vc=uc.parent.context||uc.parent.AMP_CONTEXT_DATA}catch(a){}try{if(vc&&vc.pageViewId&&vc.canonicalUrl){tc=vc;break a}}catch(a){}tc=null}var wc=!!tc&&n!=n.top;function xc(a,b,c){a.google_image_requests||(a.google_image_requests=[]);var d=a.document.createElement("img");if(c){var e=function(f){c&&c(f);Xb(d,"load",e);Xb(d,"error",e)};N(d,"load",e);N(d,"error",e)}d.src=b;a.google_image_requests.push(d)};function yc(a){try{var b=a.getBoundingClientRect()}catch(c){return{left:0,top:0,right:0,bottom:0}}x&&a.ownerDocument.body&&(a=a.ownerDocument,b.left-=a.documentElement.clientLeft+a.body.clientLeft,b.top-=a.documentElement.clientTop+a.body.clientTop);return b}function zc(a){var b=a.offsetWidth,c=a.offsetHeight,d=ab&&!b&&!c;return(void 0===b||d)&&a.getBoundingClientRect?(a=yc(a),new cc(a.right-a.left,a.bottom-a.top)):new cc(b,c)};var Ac=!!window.google_async_iframe_id,Bc=Ac&&window.parent||window;function Cc(a){return!(!a||!a.id)&&0===a.id.indexOf("aswift_")};function Dc(a,b){var c=void 0===c?{}:c;this.error=a;this.context=b.context;this.msg=b.message||"";this.id=b.id||"jserror";this.meta=c};function Ec(a){if(a=/[-\w]+\.[-\w]+$/.exec(a)){a=a[0].toLowerCase();for(var b=0,c=0;c<a.length;++c)b=31*b+a.charCodeAt(c)>>>0;switch(b){case 1967261364:return 0;case 3147493546:return 1;case 1567346461:return 2;case 2183041838:return 3;case 763236279:return 4;case 1342279801:return 5;case 526831769:return 6;case 352806002:return 7;case 2755048925:return 8;case 3306848407:return 9;case 2207000920:return 10;case 484037040:return 11;case 3506871055:return 12;case 672143848:return 13;case 2528751226:return 14;
case 2744854768:return 15;case 3703278665:return 16;case 2014749173:return 17;case 133063824:return 18;case 2749334602:return 19;case 3131239845:return 20;case 2074086763:return 21;case 795772493:return 22;case 290857819:return 23;case 3035947606:return 24;case 2983138003:return 25;case 2197138676:return 26;case 4216016165:return 27;case 239803524:return 28;case 975993579:return 29;case 1794940339:return 30;case 1314429186:return 31;case 1643618937:return 32;case 497159982:return 33;case 3882239661:return 34}}return-1}
;var Fc=/^https?:\/\/(\w|-)+\.cdn\.ampproject\.(net|org)(\?|\/|$)/;function Gc(a,b){this.a=a;this.f=b}function Hc(a,b){this.url=a;this.T=!!b;this.depth=null};function Ic(){this.g="&";this.h=!1;this.f={};this.i=0;this.a=[]}function Jc(a,b){var c={};c[a]=b;return[c]}function Kc(a,b,c,d,e){var f=[];nc(a,function(h,g){(h=Lc(h,b,c,d,e))&&f.push(g+"="+h)});return f.join(b)}
function Lc(a,b,c,d,e){if(null==a)return"";b=b||"&";c=c||",$";"string"==typeof c&&(c=c.split(""));if(Array.isArray(a)){if(d=d||0,d<c.length){for(var f=[],h=0;h<a.length;h++)f.push(Lc(a[h],b,c,d+1,e));return f.join(c[d])}}else if("object"==typeof a)return e=e||0,2>e?encodeURIComponent(Kc(a,b,c,d,e+1)):"...";return encodeURIComponent(String(a))}function Mc(a,b,c,d){a.a.push(b);a.f[b]=Jc(c,d)}
function Nc(a,b,c){b=b+"//pagead2.googlesyndication.com"+c;var d=Oc(a)-c.length;if(0>d)return"";a.a.sort(function(m,r){return m-r});c=null;for(var e="",f=0;f<a.a.length;f++)for(var h=a.a[f],g=a.f[h],p=0;p<g.length;p++){if(!d){c=null==c?h:c;break}var l=Kc(g[p],a.g,",$");if(l){l=e+l;if(d>=l.length){d-=l.length;b+=l;e=a.g;break}a.h&&(e=d,l[e-1]==a.g&&--e,b+=l.substr(0,e),e=a.g,d=0);c=null==c?h:c}}a="";null!=c&&(a=e+"trn="+c);return b+a}
function Oc(a){var b=1,c;for(c in a.f)b=c.length>b?c.length:b;return 3997-b-a.g.length-1};function Pc(){var a=void 0===a?Tb:a;this.f="http:"===a.location.protocol?"http:":"https:";this.a=Math.random()}function Qc(){var a=Rc,b=Sc.google_srt;0<=b&&1>=b&&(a.a=b)}function Tc(a,b,c,d,e,f){if((d?a.a:Math.random())<(e||.01))try{if(c instanceof Ic)var h=c;else h=new Ic,nc(c,function(p,l){var m=h,r=m.i++;p=Jc(l,p);m.a.push(r);m.f[r]=p});var g=Nc(h,a.f,"/pagead/gen_204?id="+b+"&");g&&("undefined"===typeof f?xc(n,g,null):xc(n,g,void 0===f?null:f))}catch(p){}};var Uc=null;function Vc(){var a=n.performance;return a&&a.now&&a.timing?Math.floor(a.now()+a.timing.navigationStart):+new Date}function Wc(){var a=void 0===a?n:a;return(a=a.performance)&&a.now?a.now():null};function Xc(a,b,c,d,e){this.label=a;this.type=b;this.value=c;this.duration=void 0===d?0:d;this.uniqueId=Math.random();this.slotId=e};var O=n.performance,Yc=!!(O&&O.mark&&O.measure&&O.clearMarks),Zc=Ha(function(){var a;if(a=Yc){var b;if(null===Uc){Uc="";try{a="";try{a=n.top.location.hash}catch(c){a=n.location.hash}a&&(Uc=(b=a.match(/\bdeid=([\d,]+)/))?b[1]:"")}catch(c){}}b=Uc;a=!!b.indexOf&&0<=b.indexOf("1337")}return a});
function P(a,b){this.j=[];this.a=b||n;var c=null;b&&(b.google_js_reporting_queue=b.google_js_reporting_queue||[],this.j=b.google_js_reporting_queue,c=b.google_measure_js_timing);this.f=Zc()||(null!=c?c:Math.random()<a)}P.prototype.w=function(){this.f=!1;this.j!=this.a.google_js_reporting_queue&&(Zc()&&u(this.j,$c),this.j.length=0)};P.prototype.A=function(a){!this.f||2048<this.j.length||this.j.push(a)};
function $c(a){a&&O&&Zc()&&(O.clearMarks("goog_"+a.label+"_"+a.uniqueId+"_start"),O.clearMarks("goog_"+a.label+"_"+a.uniqueId+"_end"))}function Q(a,b,c,d,e,f){a.f&&a.A(new Xc(b,c,d,void 0===e?0:e,f))}P.prototype.start=function(a,b){if(!this.f)return null;var c=Wc()||Vc();a=new Xc(a,b,c);b="goog_"+a.label+"_"+a.uniqueId+"_start";O&&Zc()&&O.mark(b);return a};
function ad(a,b){if(a.f&&"number"===typeof b.value){var c=Wc()||Vc();b.duration=c-b.value;c="goog_"+b.label+"_"+b.uniqueId+"_end";O&&Zc()&&O.mark(c);a.A(b)}}function bd(a,b){if(a.f){var c=a.start("243",3);try{b()}catch(d){throw $c(c),d;}ad(a,c)}else b()};function cd(){var a=dd;this.j=Rc;this.h=null;this.B=this.a;this.f=void 0===a?null:a;this.i=!1}cd.prototype.w=function(a){this.h=a};cd.prototype.A=function(a){this.i=a};cd.prototype.g=function(a,b,c){try{if(this.f&&this.f.f){var d=this.f.start(a.toString(),3);var e=b();ad(this.f,d)}else e=b()}catch(f){b=!0;try{$c(d),b=this.B(a,new Dc(f,{message:ed(f)}),void 0,c)}catch(h){this.a(217,h)}if(!b)throw f;}return e};
cd.prototype.m=function(a,b,c,d){var e=this;return function(f){for(var h=[],g=0;g<arguments.length;++g)h[g]=arguments[g];return e.g(a,function(){return b.apply(c,h)},d)}};
cd.prototype.a=function(a,b,c,d,e){e=e||"jserror";try{var f=new Ic;f.h=!0;Mc(f,1,"context",a);b.error&&b.meta&&b.id||(b=new Dc(b,{message:ed(b)}));b.msg&&Mc(f,2,"msg",b.msg.substring(0,512));var h=b.meta||{};if(this.h)try{this.h(h)}catch(ja){}if(d)try{d(h)}catch(ja){}b=[h];f.a.push(3);f.f[3]=b;d=n;b=[];h=null;do{var g=d;if(lc(g)){var p=g.location.href;h=g.document&&g.document.referrer||null}else p=h,h=null;b.push(new Hc(p||""));try{d=g.parent}catch(ja){d=null}}while(d&&g!=d);p=0;for(var l=b.length-
1;p<=l;++p)b[p].depth=l-p;g=n;if(g.location&&g.location.ancestorOrigins&&g.location.ancestorOrigins.length==b.length-1)for(l=1;l<b.length;++l){var m=b[l];m.url||(m.url=g.location.ancestorOrigins[l-1]||"",m.T=!0)}var r=new Hc(n.location.href,!1);g=null;var D=b.length-1;for(m=D;0<=m;--m){var E=b[m];!g&&Fc.test(E.url)&&(g=E);if(E.url&&!E.T){r=E;break}}E=null;var gb=b.length&&b[D].url;0!=r.depth&&gb&&(E=b[D]);var T=new Gc(r,E);T.f&&Mc(f,4,"top",T.f.url||"");Mc(f,5,"url",T.a.url||"");Tc(this.j,e,f,this.i,
c)}catch(ja){try{Tc(this.j,e,{context:"ecmserr",rctx:a,msg:ed(ja),url:T&&T.a.url},this.i,c)}catch(Ub){}}return!0};function ed(a){var b=a.toString();a.name&&-1==b.indexOf(a.name)&&(b+=": "+a.name);a.message&&-1==b.indexOf(a.message)&&(b+=": "+a.message);if(a.stack){a=a.stack;try{-1==a.indexOf(b)&&(a=b+"\n"+a);for(var c;a!=c;)c=a,a=a.replace(/((https?:\/..*\/)[^\/:]*:\d+(?:.|\n)*)\2/,"$1");b=a.replace(/\n */g,"\n")}catch(d){}}return b};function fd(){this.f=null;this.h=!1;this.j=Math.random();this.i=this.a}fd.prototype.w=function(a){this.f=a};fd.prototype.A=function(a){this.h=a};
fd.prototype.a=function(a,b,c,d,e){if((this.h?this.j:Math.random())>(void 0===c?.01:c))return!1;b.error&&b.meta&&b.id||(b=new Dc(b,{context:a,id:void 0===e?"jserror":e}));if(d||this.f)b.meta={},this.f&&this.f(b.meta),d&&d(b.meta);n.google_js_errors=n.google_js_errors||[];n.google_js_errors.push(b);if(!n.error_rep_loaded){b=n.document;a=b.createElement("script");c=new La(Ma,n.location.protocol+"//pagead2.googlesyndication.com/pagead/js/err_rep.js");a.src=c instanceof La&&c.constructor===La&&c.a===
Na?c.f:"type_error:TrustedResourceUrl";if(null===qa)b:{c=n.document;if((c=c.querySelector&&c.querySelector("script[nonce]"))&&(c=c.nonce||c.getAttribute("nonce"))&&pa.test(c)){qa=c;break b}qa=""}(c=qa)&&a.setAttribute("nonce",c);(b=b.getElementsByTagName("script")[0])&&b.parentNode&&b.parentNode.insertBefore(a,b);n.error_rep_loaded=!0}return!1};fd.prototype.g=function(a,b,c){try{var d=b()}catch(e){if(!this.i(a,e,.01,c,"jserror"))throw e;}return d};
fd.prototype.m=function(a,b,c,d){var e=this;return function(f){for(var h=[],g=0;g<arguments.length;++g)h[g]=arguments[g];return e.g(a,function(){return b.apply(c,h)},d)}};var Rc,gd,hd;if(Ac&&!lc(Bc)){var id="."+Sb.domain;try{for(;2<id.split(".").length&&!lc(Bc);)Sb.domain=id=id.substr(id.indexOf(".")+1),Bc=window.parent}catch(a){}lc(Bc)||(Bc=window)}var Sc=Bc,dd=new P(1,Sc);
(function(){Rc=new Pc;"number"!==typeof Sc.google_srt&&(Sc.google_srt=Math.random());Qc();gd=new cd;gd.w(function(b){var c=Tb.jerExpIds;if("array"==ra(c)&&0!==c.length){var d=b.eid;if(d){c=ba(d.split(",")).concat(ba(c));d={};for(var e=0,f=0;f<c.length;){var h=c[f++];var g=h;g=sa(g)?"o"+(Object.prototype.hasOwnProperty.call(g,ta)&&g[ta]||(g[ta]=++xa)):(typeof g).charAt(0)+g;Object.prototype.hasOwnProperty.call(d,g)||(d[g]=!0,c[e++]=h)}c.length=e;b.eid=c.join(",")}else b.eid=c.join(",")}hd&&(b.jc=hd);
(c=Tb.jerUserAgent)&&(b.useragent=c)});gd.A(!0);"complete"==Sc.document.readyState?Sc.google_measure_js_timing||dd.w():dd.f&&N(Sc,"load",function(){Sc.google_measure_js_timing||dd.w()});var a=Sb.currentScript;hd=a?a.dataset.jc:""})();function jd(a,b){return gd.m(a,b,void 0,void 0)};function kd(){return n.google_lt_queue=n.google_lt_queue||[]};function ld(a){G(this,a,null,null)}q(ld,C);function md(a,b){var c=I(a,1,0);0!==c&&B(b,1,c);c=I(a,2,0);0!==c&&B(b,2,c);c=I(a,3,"");0<c.length&&Eb(b,3,c);c=I(a,4,"");0<c.length&&Eb(b,4,c);c=I(a,5,"");0<c.length&&Eb(b,5,c);(c=J(a,6))&&Db(b,6,c)};function nd(a){G(this,a,od,null)}q(nd,C);var od=[2];function pd(a){G(this,a,null,Qb)}q(pd,C);var Qb=[[5]];function qd(a,b){var c=I(a,1,"");0<c.length&&Eb(b,1,c);c=I(a,2,0);0!==c&&B(b,2,c);c=I(a,3,0);0!==c&&y(b,3,c);c=I(a,4,0);0!==c&&y(b,4,c);c=Lb(a,nd,5);if(null!=c&&(a=c,null!=a)){c=Ab(b,5);var d=I(a,1,0);0!==d&&B(b,1,d);d=Mb(a,ld,2);0<d.length&&Fb(b,2,d,md);Bb(b,c)}};function rd(a){G(this,a,sd,null)}q(rd,C);var sd=[1];function td(a){G(this,a,null,null)}q(td,C);function ud(a,b){var c=I(a,1,"");0<c.length&&Eb(b,1,c);c=I(a,2,0);0!==c&&y(b,2,c)};function vd(a){G(this,a,wd,null)}q(vd,C);var wd=[3];function xd(a){var b;a.visibilityState?b="visibilitychange":a.mozVisibilityState?b="mozvisibilitychange":a.webkitVisibilityState&&(b="webkitvisibilitychange");return b};function yd(a){return a._google_rum_ns_=a._google_rum_ns_||{}}function zd(a){a=yd(a);return a.pq=a.pq||[]};function Dd(a,b,c){nc(b,function(d,e){var f=c&&c[e];!d&&0!==d||f||(a+="&"+encodeURIComponent(e)+"="+encodeURIComponent(String(d)),c&&(c[e]=!0))});return a}
function R(a,b,c,d,e,f,h,g){function p(m){var r=m[0];m=m[1];var D=r.length+m.length+2;8E3<l.h+l.g+D&&S(l);l.H.push([r,m]);l.g+=D;6E3<=l.h+l.g&&S(l);return 0}f=void 0===f?Infinity:f;h=void 0===h?!1:h;P.call(this,a,g);var l=this;this.C=-1;this.B=0;this.L=f;this.V=b;this.M=c;this.U=d;this.W=e;a=this.a.navigator;this.J=!("csi.gstatic.com"!==this.M||!a||!a.sendBeacon);this.i={};this.I={};this.a.performance&&this.a.performance.now||U(this,"dat",1);a&&a.deviceMemory&&U(this,"dmc",a.deviceMemory);this.X=
!h;this.G=0;this.N=function(){l.a.setTimeout(function(){return S(l)},1100)};this.K=[];this.P=function(){Ed(l,1)};this.O=function(){Ed(l,2)};this.Y=Ia(function(){S(l)});this.Z=function(){var m=l.a.document;(null!=m.hidden?m.hidden:null!=m.mozHidden?m.mozHidden:null!=m.webkitHidden&&m.webkitHidden)&&l.Y()};this.D=this.a.setTimeout(function(){return S(l)},5E3);this.m={};this.h=b.length+c.length+d.length+e.length+3;this.g=0;u(this.j,function(m){Fd(l,"met."+m.type,Gd(m),!0,"~")});this.H=[];b=zd(this.a);
u(b,function(m){return p(m)});b.length=0;b.push=p;U(this,"puid",(this.B+1).toString(36)+"~"+(+new Date).toString(36));Hd(this)}R.prototype=ca(P.prototype);R.prototype.constructor=R;if(ia)ia(R,P);else for(var Id in P)if("prototype"!=Id)if(Object.defineProperties){var Jd=Object.getOwnPropertyDescriptor(P,Id);Jd&&Object.defineProperty(R,Id,Jd)}else R[Id]=P[Id];
function Gd(a){var b=Math.round(a.duration);return a.label+(null!=a.slotId?"_"+a.slotId:"")+("."+("number"===typeof a.value?Math.round(a.value).toString(36):a.value))+(0<b?"_"+b.toString(36):"")}function Kd(a,b){a.K.push(b)}function Hd(a){"complete"===a.a.document.readyState?a.a.setTimeout(function(){return S(a)},0):N(a.a,"load",a.N);var b=xd(a.a.document);"undefined"!==typeof b&&N(a.a,b,a.Z);N(a.a,"unload",a.P);N(a.a,"pagehide",a.O)}
function U(a,b,c){c=String(c);a.h=null!=a.i[b]?a.h+(c.length-a.i[b].length):a.h+(b.length+c.length+2);a.i[b]=c}function Ld(a){null!=a.i.uet&&(a.h-=a.i.uet.length+5,delete a.i.uet)}function Md(a,b){var c="ec="+b;a.I[c]||(Fd(a,"ec",b,!1),1E3>c.length&&(a.I[c]=!0))}
function Nd(a){var b=Od(),c=a.a!==a.a.top,d=b.slice(a.G);b=d.splice(0,250-a.G);var e=a.i.qqid;if(c&&a.J&&e&&b){c=new vd;c=M(c,1,e,"");d=M(c,2,!!d.length,!1);d.a||(d.a={});c=b||[];e=[];for(var f=0;f<c.length;f++)e[f]=c[f].l;d.a[3]=c;d=Kb(d,3,e);c=new zb;e=I(d,1,"");0<e.length&&Eb(c,1,e);(e=J(d,2))&&Db(c,2,e);e=Mb(d,td,3);0<e.length&&Fb(c,3,e,ud);d=Cb(c);Pd(a,"https://pagead2.googlesyndication.com/pagead/gen_204?id=urind",qb(d));a.G+=b.length}}
function Fd(a,b,c,d,e){e=void 0===e?"":e;var f=null==a.m[b]?b.length+c.length+2:d?c.length+e.length:c.length-a.m[b].length;8E3<a.h+a.g+f&&(S(a),f=b.length+c.length+2);a.m[b]=d&&null!=a.m[b]?a.m[b]+(e+c):c;a.g+=f;6E3<=a.h+a.g&&S(a)}function S(a){if(a.f&&a.X){try{a.g&&(Qd(a,a.m),a.B===a.L&&a.w())}catch(b){(new fd).a(358,b)}a.m={};a.g=0;a.j.length=0;a.a.clearTimeout(a.D);a.D=0}}
function Rd(a,b){var c=a.V+"//"+a.M+a.U+a.W,d={};c=Dd(c,a.i,d);c=Dd(c,b,d);a.a.google_timing_params&&(c=Dd(c,a.a.google_timing_params,d),a.a.google_timing_params=void 0);u(a.H,function(e){var f=k(e);e=f.next().value;f=f.next().value;var h={};c=Dd(c,(h[e]=f,h))});a.H.length=0;return c}function Pd(a,b,c){var d=!1;try{d=!!(a.J&&a.a.navigator&&a.a.navigator.sendBeacon(b,c))}catch(e){a.J=!1}return d}
function Qd(a,b){a.B++;b=Rd(a,b);Pd(a,b,null)||xc(a.a,b,null);U(a,"puid",(a.B+1).toString(36)+"~"+(+new Date).toString(36))}function Sd(a,b,c,d,e){Fd(a,"met."+b,c,void 0===d?!1:d,void 0===e?"~":e)}function Td(a,b){var c=""+a;nc(b,function(d,e){null!=d&&(c+="."+e+"_"+d)});return c}function Ud(a,b,c){c=Td(b,c);var d={};b=(d["met."+b]=c,d);Qd(a,b)}R.prototype.A=function(a){this.f&&this.B<this.L&&(P.prototype.A.call(this,a),Fd(this,"met."+a.type,Gd(a),!0,"~"))};
R.prototype.w=function(){P.prototype.w.call(this);this.a.clearTimeout(this.D);this.g=this.D=0;this.m={};Ka(this.I);Ka(this.i);Xb(this.a,"load",this.N);Xb(this.a,"unload",this.P);Xb(this.a,"pagehide",this.O)};function Ed(a,b){U(a,"uet",b);u(a.K,function(c){try{c()}catch(d){}});Yb(a.a);S(a);Ld(a)};var Vd={self:1,"same-origin-ancestor":2,"same-origin-descendant":3,"same-origin":4,"cross-origin-ancestor":5,"cross-origin-descendant":6,"cross-origin-unreachable":7,"multiple-contexts":8},Wd={script:1,layout:2},Xd={iframe:1,embed:2,object:3};function Yd(a){var b=new nd;M(b,1,Vd[a.name],0);u(a.attribution,function(c){var d=new ld;M(d,1,Wd[c.name],0);M(d,2,Xd[c.containerType],0);"string"===typeof c.containerId&&M(d,6,0==c.containerId.lastIndexOf("google_ads_iframe",0),!1);Rb(b,2,d,ld)});return b}
function Zd(a,b){var c=new zb;b=Mb(b,pd,1);0<b.length&&Fb(c,1,b,qd);c=Cb(c);c=qb(c);b={};Ud(a,6,(b[1]=c,b))}function $d(a){if(n.PerformanceLongTaskTiming&&n.PerformanceObserver){var b=0;(new n.PerformanceObserver(jd(246,function(c,d){var e=new rd;u(c.getEntries(),function(f){var h=new pd;K(h,3,Math.round(f.startTime));K(h,4,Math.round(f.duration));f=Yd(f);Pb(h,f);Rb(e,1,h,pd)});Zd(a,e);10<=++b&&d.disconnect()}))).observe({entryTypes:["longtask"]})}}
function ae(a){function b(){var e=new rd;u(kd(),function(f){var h=new pd;var g=K(h,3,Math.round(f.startTime));g=K(g,4,Math.round(f.duration));f=Yd(f);Pb(g,f);Rb(e,1,h,pd)});Mb(e,pd,1).length&&Zd(a,e)}var c=0,d=n.setInterval(function(){if(12<=++c){n.clearInterval(d);var e=n.google_ltobserver;e&&(e.disconnect(),delete n.google_ltobserver);n.google_lt_queue&&delete n.google_lt_queue;Xb(n,"beforeunload",b)}b();kd().length=0},5E3);N(n,"beforeunload",b)};function be(a){G(this,a,ce,null)}q(be,C);var ce=[15];function de(a){G(this,a,null,null)}q(de,C);function ee(a){G(this,a,null,null)}q(ee,C);function fe(a){return Math.round(a.position).toString(36)+"."+Math.round(a.timestamp).toString(36)}function ge(a){var b=this;this.g=-1;this.h=-Infinity;this.a=[];this.f=a;this.i=0;this.j=jd(456,function(){return he(b)});this.m=function(){return ie(b)}}ge.prototype.install=function(){n.performance&&(he(this),N(n,"scroll",this.j,{passive:!0}),Kd(this.f,this.m))};
function he(a){var b=n.pageYOffset||0,c=Wc()||0;if(100<Math.abs(b-a.g)||200<c-a.h)a.g=b,a.h=c,400<=a.a.push({position:b,timestamp:c})&&(ie(a),8<=a.i&&(Xb(n,"scroll",a.j),b=a.f.K,a=za(b,a.m),0<=a&&Array.prototype.splice.call(b,a,1)))}function ie(a){a.a.length&&(Sd(a.f,12,Ba(a.a,fe).join("~")),a.a=[],a.i++)};function je(){try{return Aa(Ba(n.googletag.pubads().getSlots(),function(a){return n.document.getElementById(a.getSlotElementId())}),function(a){return null!=a})}catch(a){}return null}function V(a){a=n.document.querySelectorAll(a);var b=a.length;if(0<b){for(var c=Array(b),d=0;d<b;d++)c[d]=a[d];a=c}else a=[];return a}
function ke(a){var b=[];a=k(a);for(var c=a.next();!c.done;c=a.next()){c=c.value;for(var d=!0,e=0;e<b.length;e++){var f=b[e];if(f.contains(c)){d=!1;break}if(c.contains(f)){d=!1;b[e]=c;break}}d&&b.push(c)}return b};function le(a){a=a.document;var b={};a&&(b="CSS1Compat"==a.compatMode?a.documentElement:a.body);return b||{}};function me(a){this.g=n;this.a=a;this.f="633794002 633794005 44715380 44715381 21065713 21065714 21065715 21065716".split(" ")}
function ne(a){var b=n.location.hostname,c=!(w("iPad")||w("Android")&&!w("Mobile")||w("Silk"))&&(w("iPod")||w("iPhone")||w("Android")||w("IEMobile"))&&!(900<=le(a.g).clientWidth),d=Aa([],function(e){return 0<=za(a.f,e)}).join(",");return{wpc:"",su:b,eid:d,doc:a.a.ia,pg_h:W(a.a.sa),pg_w:W(a.a.ua),pg_hs:W(a.a.ta),c:W(a.a.na),aa_c:W(a.a.ca),av_h:W(a.a.ea),av_w:W(a.a.fa),av_a:W(a.a.da),s:W(a.a.ra),all_s:W(a.a.qa),b:W(a.a.pa),all_b:W(a.a.oa),d:W(a.a.ha),all_d:W(a.a.ga),ard:W(a.a.ba),all_ard:W(a.a.aa),
pd_h:W(a.a.va),dt:c?"m":"d"}}function oe(a){return ac.apply(null,Aa(a,function(b){return 0<b}))||null}function pe(a,b){return 0>=a?null:$b.apply(null,b)/a}function qe(a){for(var b=Infinity,c=0;c<a.length-1;c++)for(var d=c+1;d<a.length;d++){var e=a[c],f=a[d];e=Math.max(Math.max(0,e.left-f.right,f.left-e.right),Math.max(0,e.top-f.bottom,f.top-e.bottom));0<e&&(b=Math.min(e,b))}return Infinity!==b?b:null}function W(a){return null==a?null:Number.isInteger(a)?a.toString():a.toFixed(3)};function re(a,b){var c=navigator.getBattery&&navigator.getBattery();c&&c.then?c.then(function(d){var e=d.level,f=d.charging;setTimeout(function(){b(100*e|0,100*d.level|0,f||d.charging)},a)}):b()};var se=/^.+\.((googlesyndication|googletagservices)\.com|doubleclick\.net)$/,te=/^(aswift_\d+|google_ads_iframe_.+)$/,ue=/^div-gpt-ad-.+$/,ve=["ZGl2LnRhYm9vbGE=","ZGl2Lk9VVEJSQUlO"];function we(a){if(!a)return"";var b=Math.floor(Math.random()*a.length);return b.toString(36)+encodeURIComponent(a.charAt(b))+"."+pc(a).toString(36)}function xe(a){return(a=kc(Qa(a).match(jc)[3]||null))?a.toLowerCase():""}function ye(a){return 10<=a.offsetWidth&&10<=a.offsetHeight}
function hc(a){return a&&1==a.nodeType&&"DIV"==a.nodeName?ue.test(a.id)||a.hasAttribute("data-google-query-id"):!1}
function ze(a){var b=[];if(!a.body)return b;var c=a.body;a=c.getElementsByTagName("script");for(var d=a.length,e=0;e<d;e++){var f=a[e],h=f.src;h&&(f=(void 0!==f.nextElementSibling?f.nextElementSibling:dc(f.nextSibling,!0))||ec(f))&&"DIV"==f.nodeName&&ye(f)&&(h=xe(h))&&!se.test(h)&&b.push(new Ae(f,h))}if(!c.querySelectorAll)return b;u(ve,function(g){for(var p=c.querySelectorAll(sb(g)),l=p.length,m=0;m<l;m++){var r=p[m];ye(r)&&b.push(new Ae(r,g))}});return b}
function Ae(a,b,c){var d=fc(a);var e=new bc(0,0);var f=d?fc(d):document;f=!x||9<=Number(lb)||"CSS1Compat"==(f?new ic(fc(f)):ya||(ya=new ic)).a.compatMode?f.documentElement:f.body;if(a!=f){f=yc(a);var h=(d?new ic(fc(d)):ya||(ya=new ic)).a;d=h.scrollingElement?h.scrollingElement:ab||"CSS1Compat"!=h.compatMode?h.body||h.documentElement:h.documentElement;h=h.parentWindow||h.defaultView;d=x&&ib("10")&&h.pageYOffset!=d.scrollTop?new bc(d.scrollLeft,d.scrollTop):new bc(h.pageXOffset||d.scrollLeft,h.pageYOffset||
d.scrollTop);e.a=f.left+d.a;e.f=f.top+d.f}b:{f=fc(a);if(f.defaultView&&f.defaultView.getComputedStyle&&(f=f.defaultView.getComputedStyle(a,null))){f=f.display||f.getPropertyValue("display")||"";break b}f=""}f||(f=a.currentStyle?a.currentStyle.display:null);if("none"!=(f||a.style&&a.style.display))a=zc(a);else{f=a.style;d=f.display;h=f.visibility;var g=f.position;f.visibility="hidden";f.position="absolute";f.display="inline";a=zc(a);f.display=d;f.position=g;f.visibility=h}e=new sc(e.a,e.f,a.width,
a.height);this.id=b;this.a=c||null;this.top=e.top;this.left=e.left;this.width=e.width;this.height=e.height}
function Be(a){a=mc(a);if(!a)return null;var b=a.document;a=ze(b);var c=[];Ea(c,b.getElementsByTagName("iframe"));for(b=0;b<Math.min(c.length,50);b++){var d=c[b],e=d.src?Qa(d.src):"",f=d.id||d.name||"";if(!te.test(f))try{var h=d.contentDocument||d.contentWindow.document;if(e&&"about:blank"!=d.src)Ea(a,ze(h)),Ea(c,h.getElementsByTagName("iframe"));else{var g=null,p=void 0!==d.previousElementSibling?d.previousElementSibling:dc(d.previousSibling,!1);if(p&&"SCRIPT"==p.nodeName&&p.src){var l=xe(p.src);
g=se.test(l)?null:l}((g=g||f)||!gc(d))&&ye(d)&&a.push(new Ae(d,g))}}catch(r){g=xe(e),e=(e=kc(e.match(jc)[5]||null))&&"/"==e.charAt(0)?e.split("/",2)[1]:"",ye(d)&&!se.test(g)&&a.push(new Ae(d,g||f,e))}}Fa(a,function(r,D){return r.top!=D.top?r.top-D.top:r.left-D.left});var m=null;return Aa(a,function(r){if(null!=m&&r.top+r.height<=m.top+m.height&&r.left+r.width<=m.left+m.width)return!1;m=r;return!0})};var Ce=!1;function De(a,b,c){if(!Ce){Ce=!0;var d=a.requestAnimationFrame||a.webkitRequestAnimationFrame||a.msRequestAnimationFrame||a.mozRequestAnimationFrame||a.oRequestAnimationFrame;if(qc(d)){var e,f,h,g,p=a.requestIdleCallback;p&&(g=function(m){f=m.timeRemaining();h=0});var l=function(m){Ce&&(b.push(m-e),e=m,p&&(c.push(f||0),h||(f=0,h=p(g))),d(l))};d(function(m){e=m;p&&(h=p(g));d(l)})}}};function Ee(){var a=n;if(!a.performance||!a.performance.getEntriesByType)return null;a=a.performance.getEntriesByType("paint");if(!a.length)return null;var b=0,c=0;u(a,function(d){switch(d.name){case "first-paint":b=d.startTime;break;case "first-contentful-paint":c=d.startTime}});return{S:b,R:c}};function Fe(a){G(this,a,Ge,null)}q(Fe,C);var Ge=[1];function He(a){G(this,a,null,null)}q(He,C);var X={},Y={},Z={},Ie={},Je={},Ke={},Le={},Me={},Ne={},Oe={},Pe=[{v:/^https?:\/\/((tpc|pagead2)\.googlesyndication\.com|static\.googleadsserving\.cn)\/pagead\//,u:(X[1]=/adsbygoogle\.js/,X[2]=/show_ads\.js/,X[3]=/show_ads_impl\.js/,X[21]=/js\/r\d+\/r\d+\/osd\.js/,X[22]=/\/osd\.js/,X[7]=/activeview\/osd_listener\.js/,X[8]=/lidar\.js/,X[10]=/js\/r\d+\/r\d+\/client\/m_js_controller\.js/,X[4]=/imgad\?id=/,X[9]=/js\/r\d+\/r\d+\/abg_lite.js/,X[24]=/js\/r\d+\/r\d+\/rum\.js/,X[25]=/js\/rum\.js/,X[30]=/js\/r\d+\/r\d+\/client\/window_focus\.js/,
X[33]=/\/pagead\/adview\?ai=/,X),o:28},{v:/^https?:\/\/(tpc|pagead2)\.googlesyndication\.com\//,u:(Y[4]=/pageadimg(\/imgad)?\?id=/,Y[23]=/(daca_images\/)?simgad\/\d+/,Y[29]=/icore_images\/\d+/,Y[11]=/pub-config\/r\d+\/ca-pub-\d+\.js/,Y[16]=/\/safeframe\/\d+-\d+-\d+\/html\/container\.html/,Y[17]=/\/safeframe\/\d+-\d+-\d+\/js\/ext\.js/,Y[31]=/\/sadbundle\//,Y[32]=/(\/pcs)?\/activeview\?(xai|avi)=/,Y),o:39},{v:/^https?:\/\/\w+\.g\.doubleclick\.net/,u:(Z[59]=/\/tag\/js\/gpt\.js/,Z[14]=/\/gpt\/pubads_impl_\d+\.js/,
Z[43]=/\/gpt\/pubads_impl_core_\d+\.js/,Z[44]=/\/gpt\/pubads_impl_rendering_\d+\.js/,Z[15]=/\/gampad\/ads\?/,Z[34]=/\/pcs\/view\?xai=/,Z[36]=/^https?:\/\/cm\.g\./,Z[5]=/pagead\/ads\?/,Z[12]=/pagead\/html\/.*\/zrt_lookup\.html/,Z[33]=/\/pagead\/adview\?ai=/,Z),o:40},{v:/^https?:\/\/www\.googletagservices\.com/,u:(Ie[13]=/\/tag\/js\/gpt\.js/,Ie[37]=/\/dcmads\.js/,Ie[38]=/\/dcm\/impl_v\d+\.js/,Ie),o:42},{v:/^https?:\/\/fonts\.googleapis\.com\/css/,u:(Je[18]=/[?&]family=/,Je),o:27},{v:/^https?:\/\/fonts\.gstatic\.com/,
u:(Ke[19]=/\/s\//,Ke[20]=/\/l\//,Ke),o:27},{v:/^https:\/\/[\w.]+.2mdn.net/,u:(Le[31]=/\/sadbundle\//,Le),o:41},{v:/^https:\/\/adservice\.google\.(com?\.)?[a-z]{2,3}/,u:(Me[46]=/\/adsid\/integrator\.json/,Me[47]=/\/adsid\/integrator\.js/,Me[48]=/\/adsid\/integrator\.sync\.js/,Me),o:45},{v:/^https?:\/\/cdn\.ampproject\.org/,u:(Ne[49]=/\/rtv\/\d{15,20}\/amp4ads-host-v0\.js\b/,Ne[50]=/\.org\/amp4ads-host-v0\.js\b/,Ne),o:51},{v:/^https?:\/\/imasdk.googleapis.com/,u:(Oe[54]=/js\/sdkloader\/ima3.js/,Oe[55]=
/js\/core\/bridge3.*html/,Oe[56]=/js\/sdkloader\/loader.js/,Oe[57]=/js\/sdkloader\/vpaid_adapter.js/,Oe),o:58},{v:/./,u:{},o:27}],Qe={},Re=[{v:/^https?:\/\//,u:(Qe[26]=function(a){return wc&&!/^https:\/\/d-\d+\.ampproject\.net\/\d+\/frame\.html$/.test(a)},Qe),o:27}];function Se(a){return a.performance&&a.performance.getEntriesByType?a.performance.getEntriesByType("resource"):[]}
function Te(a){switch(a){case "beacon":return 1;case "css":return 2;case "fetch":return 4;case "iframe":return 5;case "img":return 6;case "link":return 7;case "navigation":return 8;case "object":return 9;case "script":return 10;case "subdocument":return 11;case "svg":return 12;case "xmlhttprequest":return 13;default:return 0}}var Ue={woff:1,woff2:2,eot:3,ttf:4},Ve=/^https?:\/\/[^/?#]*\b(google(adservices|tag(manager|services)|apis|usercontent|syndication)?|doubleclick|gstatic|2mdn|cdn.ampproject)\./;
function We(a,b,c,d,e,f){var h=new He;h=M(h,1,a,0);h=M(h,3,b,0);e=M(h,2,e,0);e=K(e,4,Math.round(c.startTime));e=K(e,7,Math.round(c.duration));h=c.name;try{if(f){f=125;var g=/[\?#;]/.exec(h);g&&-1!=g.index&&g.index<f&&(f=g.index);K(e,24,pc(h.substr(0,f)))}}catch(p){}if(1!=b&&26!=a)return e;a=K(e,5,Math.round(c.fetchStart));K(a,6,Math.round(c.responseEnd));a:{b=c.name;g=I(e,1,0);a=new Fe;switch(g){case 18:if(b=b.match(/[?&]family=([^&]+)/))b=n.decodeURIComponent(b[1]).split("|"),Kb(a,1,b||[]);break;
case 19:if(b=b.match(/\/s\/(\w+)\/v(\d+)\/[^.\/]+\.(\w+)$/))g=n.parseInt(b[2],10),g=K(a,2,g),g=M(g,3,Ue[b[3]]||0,0),b=b[1],H(g,1).push(b);break;case 20:if(g=b.match(/[?&]skey=([^&]+)/))g=g[1],H(a,1).push(g);if(b=b.match(/[?&]v=v(\d+)/))b=n.parseInt(b[1],10),K(a,2,b);break;default:break a}Ob(e,21,a)}if(!c.responseStart)return e;M(e,22,!0,!1);c.domainLookupStart!=c.domainLookupEnd&&(a=K(e,8,Math.round(c.domainLookupStart)),K(a,9,Math.round(c.domainLookupEnd)));c.connectStart!=c.connectEnd&&(a=K(e,10,
Math.round(c.connectStart)),K(a,11,Math.round(c.connectEnd)),c.secureConnectionStart&&K(e,12,Math.round(c.secureConnectionStart)));a=K(e,13,Math.round(c.requestStart));K(a,14,Math.round(c.responseStart));void 0!==c.transferSize&&(a=K(e,15,c.transferSize),a=K(a,17,c.decodedBodySize||0),K(a,16,c.encodedBodySize||0),0<c.transferSize?M(e,23,c.transferSize>(c.encodedBodySize||0)?3:2,0):M(e,23,1,0));c.redirectStart&&(a=K(e,18,Math.round(c.redirectStart)),K(a,19,Math.round(c.redirectEnd)));d&&window.performance.timing&&
K(e,20,d);return e}var Xe={},Ye=(Xe[1]=!0,Xe[4]=!0,Xe[13]=!0,Xe);function Ze(a,b,c,d){d=void 0===d?!1:d;var e=Ve.test(a)?1:0,f=1!=e,h=Da(f?Re:Pe,function(g){return g.v.test(a)});if(!h)return null;h=oc(h.u,function(g){return"function"==ra(g)?g(a):g.test(a)})||h.o;return!h||f&&2!=b&&Ye[c]&&(!d||13!=c)?null:{ja:e,id:parseInt(h,10)}}function $e(a,b,c,d,e,f,h){a.responseEnd<=f||(f=Te(a.initiatorType),(d=Ze((void 0===h?"":h)||a.name,d,f,e))&&b.push(We(d.id,d.ja,a,c,f,e)))}
function af(a,b,c,d){if(!a.performance||!a.performance.getEntriesByType)return[];var e=a.performance.getEntriesByType("resource"),f=0;a.performance.timing&&a!=n&&null!=n.performance&&null!=n.performance.timing&&(f=a.performance.timing.navigationStart-n.performance.timing.navigationStart);var h=[];u(e,function(g){return $e(g,h,f,b,c,d)});e=a.performance.getEntriesByType("navigation");1==e.length&&$e(e[0],h,f,b,c,d,a.location?a.location.href:"");return h}
function bf(a,b,c,d,e){c=af(b,c,d,e);b=0;d=k(c);for(e=d.next();!e.done;e=d.next())b=Math.max(b,I(e.value,6,0));c=Ba(c,function(f){var h=new zb;var g=I(f,1,0);0!==g&&B(h,1,g);g=I(f,2,0);0!==g&&B(h,2,g);g=I(f,3,0);0!==g&&B(h,3,g);g=I(f,4,0);0!==g&&y(h,4,g);g=I(f,5,0);0!==g&&y(h,5,g);g=I(f,6,0);0!==g&&y(h,6,g);g=I(f,7,0);0!==g&&y(h,7,g);g=I(f,8,0);0!==g&&y(h,8,g);g=I(f,9,0);0!==g&&y(h,9,g);g=I(f,10,0);0!==g&&y(h,10,g);g=I(f,11,0);0!==g&&y(h,11,g);g=I(f,12,0);0!==g&&y(h,12,g);g=I(f,13,0);0!==g&&y(h,13,
g);g=I(f,14,0);0!==g&&y(h,14,g);g=I(f,15,0);0!==g&&y(h,15,g);g=I(f,16,0);0!==g&&y(h,16,g);g=I(f,17,0);0!==g&&y(h,17,g);g=I(f,18,0);0!==g&&y(h,18,g);g=I(f,19,0);0!==g&&y(h,19,g);g=I(f,20,0);0!==g&&y(h,20,g);g=Lb(f,Fe,21);if(null!=g&&null!=g){var p=Ab(h,21);var l=H(g,1);if(0<l.length&&null!=l)for(var m=0;m<l.length;m++)Eb(h,1,l[m]);l=I(g,2,0);0!==l&&y(h,2,l);l=I(g,3,0);0!==l&&B(h,3,l);Bb(h,p)}(g=J(f,22))&&Db(h,22,g);g=I(f,23,0);0!==g&&B(h,23,g);g=I(f,24,0);0!==g&&y(h,24,g);(g=J(f,25))&&Db(h,25,g);f=
Cb(h);return qb(f)}).join("~");Sd(a,7,c,!0);return b}function Od(){return Ba(Se(n),function(a){var b=(a&&a.name||"").replace(/\?.*$/,""),c=new td;b=M(c,1,b,"");return K(b,2,a.startTime)})}
function cf(a){return Ca(Se(a),function(b,c){a:{switch(Te(c.initiatorType)){case 10:case 13:case 4:break;default:var d=!1;break a}d=(d=kc(c.name.match(jc)[3]||null))?d?0<=Ec(d):!1:!1}d&&(b.startTime=Math.min(b.F?b.startTime:Infinity,c.startTime),b.endTime=Math.max(b.endTime,c.startTime+c.duration),b.F++);return b},{F:0,startTime:0,endTime:0})};function df(){if(!n._google_rum_ns_)return!1;var a=yd(n);return!(!a.raf||!a.ric)}function ef(){var a=yd(n);a.raf=a.raf||[];a.ric=a.ric||[];return{ka:a.raf,la:a.ric}};function ff(a){G(this,a,null,null)}q(ff,C);ff.prototype.getTime=function(){return I(this,1,0)};var gf=window==window.top?32:16,hf={unloadEventStart:2,unloadEventEnd:3,redirectStart:4,redirectEnd:5,fetchStart:6,domainLookupStart:7,domainLookupEnd:8,connectStart:9,connectEnd:10,secureConnectionStart:11,requestStart:12,responseStart:13,responseEnd:14,domLoading:15,domInteractive:16,domContentLoadedEventStart:17,domContentLoadedEventEnd:18,domComplete:19,loadEventStart:20,loadEventEnd:21};function jf(a){return(a=Lb(a,de,1))?I(a,2,0):0}
function kf(a){var b=Lb(a,be,2);b||(b=new be,Ob(a,2,b));a=jf(a);if(2==a){var c=M(b,7,!0,!1);c=M(c,9,!0,!1);M(c,10,!0,!1)}2!==a&&3!==a||M(b,17,!0,!1);return b}function lf(a,b){2!==I(b,2,0)||yd(n).chp||U(a,"chm",1);I(b,1,0)&&U(a,"c",I(b,1,0));I(b,5,"")&&U(a,"e",I(b,5,""));U(a,"ctx",I(b,2,0));U(a,"gqid",I(b,3,""));U(a,"qqid",I(b,4,""))}
function mf(a){var b=new ee(n.google_rum_config||null),c=kf(b),d=H(c,15),e=Lb(b,de,1)||new de;d.length&&M(e,5,d.join(),"");lf(a,e);if(d=n.google_js_reporting_queue){var f=function(g){a.A(g);$c(g)};d.push=f;u(d,f);d.length=0}J(c,11)||J(c,12)?ae(a):J(c,9)&&.1>Math.random()&&$d(a);var h=jf(b);1==h&&nf(a);Kd(a,function(){var g=Wc();g&&Q(a,"24",1,g,0,void 0)});Kd(a,function(){J(c,7)&&(a.C=bf(a,n,h,J(c,13),a.C))});Kd(a,function(){J(c,18)&&Nd(a)});n==n.top&&J(c,14)&&(new ge(a)).install();of(a,c,jf(b));J(c,
17)&&pf(a,e)}
function of(a,b,c){var d=jd(113,function(){J(b,10)&&qf(a);rf(a);sf(a,b,c);if(1==c&&J(b,16)){var e=le(n);e=e.scrollHeight==le(n).clientHeight?e.offsetHeight:e.scrollHeight;var f=le(n).scrollWidth,h=le(n).scrollHeight,g="unknown";n&&n.document&&n.document.readyState&&(g=n.document.readyState);var p=void 0===n.pageYOffset?(n.document.documentElement||n.document.body.parentNode||n.document.body).scrollTop:n.pageYOffset,l=[],m=[],r=[],D=[],E=[],gb=[],T=[],ja=0,Ub=0,ua=Infinity,va=Infinity,Ad=null,t={ma:!1},
F=V(".google-auto-placed"),v=V('ins.adsbygoogle[data-anchor-shown="true"]'),z=V("ins.adsbygoogle[data-ad-format=autorelaxed]");var la=(je()||V("div[id^=div-gpt-ad]")).concat(V("iframe[id^=google_ads_iframe]"));var uf=V("div.trc_related_container,div.OUTBRAIN,div[id^=rcjsload],div[id^=ligatusframe],div[id^=crt-],iframe[id^=cto_iframe],div[id^=yandex_], div[id^=Ya_sync],iframe[src*=adnxs],div.advertisement--appnexus,div[id^=apn-ad],div[id^=amzn-native-ad],iframe[src*=amazon-adsystem],iframe[id^=ox_],iframe[src*=openx],img[src*=openx],div[class*=adtech],div[id^=adtech],iframe[src*=adtech],div[data-content-ad-placement=true],div.wpcnt div[id^=atatags-]"),
vf=V("ins.adsbygoogle-ablated-ad-slot"),wf=V("div.googlepublisherpluginad"),A=V("iframe[id^=aswift_],iframe[id^=google_ads_frame]").concat(V("ins.adsbygoogle")),L=[];t=k([[t.xa,F],[t.ma,v],[t.Aa,z],[t.ya,la],[t.Ba,uf],[t.wa,vf],[t.za,wf]]);for(F=t.next();!F.done;F=t.next())v=k(F.value),F=v.next().value,v=v.next().value,!1===F?L=L.concat(v):A=A.concat(v);A=ke(A);t=ke(L);L=A.slice(0);A=k(t);for(t=A.next();!t.done;t=A.next())for(t=t.value,F=0;F<L.length;F++)(t.contains(L[F])||L[F].contains(t))&&L.splice(F,
1);L=k(L);for(A=L.next();!A.done;A=L.next()){A=A.value;t=A.getBoundingClientRect();F=e-(t.bottom+p);if(A.className&&-1!=A.className.indexOf("adsbygoogle-ablated-ad-slot")){v=A.getAttribute("google_element_uid");z=n.google_sv_map;if(!v||!z||!z[v])continue;a:{v=z[v];z=Number(v.google_ad_width);la=Number(v.google_ad_height);if(!(0<z&&0<la)){b:{try{var Oa=String(v.google_ad_format);if(Oa&&Oa.match){var Pa=Oa.match(/(\d+)x(\d+)/i);if(Pa){var Bd=parseInt(Pa[1],10),Cd=parseInt(Pa[2],10);if(0<Bd&&0<Cd){var wa=
{width:Bd,height:Cd};break b}}}}catch(Df){}wa=null}if(!wa){v=null;break a}z=0<z?z:wa.width;la=0<la?la:wa.height}v={width:z,height:la}}v=(z=v)?z.height:0;z=z?z.width:0}else if(v=t.bottom-t.top,z=t.right-t.left,1>=v||1>=z)continue;l.push(v);r.push(z);D.push(v*z);A.className&&-1!=A.className.indexOf("google-auto-placed")?(Ub+=1,A.className&&-1!=A.className.indexOf("pedestal_container")&&(Ad=v)):(ua=Math.min(ua,F),gb.push(t),ja+=1,m.push(v),E.push(v*z));va=Math.min(va,F);T.push(t)}ua=Infinity===ua?null:
ua;va=Infinity===va?null:va;wa=qe(gb);T=qe(T);m=pe(e,m);Oa=pe(e,l);E=pe(e*f,E);Pa=pe(e*f,D);e=new me({ia:g,sa:e,ua:f,ta:h,na:ja,ca:Ub,ea:oe(l),fa:oe(r),da:oe(D),ra:wa,qa:T,pa:ua,oa:va,ha:m,ga:Oa,ba:E,aa:Pa,va:Ad});e=ne(e);Tc(Rc,"ama_stats",e,!0,1,void 0)}});"complete"!=n.document.readyState?N(n,"load",function(){n.setTimeout(d,0)}):d()}
function pf(a,b){if(n.ReportingObserver){var c=I(b,4,""),d=I(b,1,0),e=["HeavyAdIntervention"],f=function(g){var p=g.type,l=g.body;g=l.id;var m=l.message,r=l.anticipatedRemoval,D=l.sourceFile,E=l.lineNumber;l=l.columnNumber;!e.includes(g)&&.1<Math.random()||(p={qqid:String(c),c:String(d),t:p,rid:g,ar:void 0!=r?String(r.getTime()):null,ln:void 0!=E?String(E):null,cn:void 0!=l?String(l):null,src:D||null,msg:m},rc(p))},h=new n.ReportingObserver(function(g){u(g,f)},{buffered:!0});h.observe();Kd(a,function(){u(h.takeRecords(),
f);h.disconnect()})}}function rf(a){var b=n.google_rum_values||yd(n).rv;n.google_rum_values=void 0;yd(n).rv=void 0;if(b&&!(0>b.dt)){var c=n.performance&&n.performance.timing;if(c){var d=b.dt-c.navigationStart;nc(b,function(e,f){if(-1!=e&&"number"===typeof e){switch(f){case "dt":e=d;break;case "bdt":e=d-e;break;default:e=d+e}Q(a,f,4,e)}})}}}function sf(a,b,c){J(b,1)&&tf(a);J(b,2)&&0<I(b,3,0)&&xf(a,I(b,3,0));J(b,7)&&yf(a,b,c);J(b,8)&&.1>Math.random()&&bd(a,function(){return zf(a)});J(b,18)&&Nd(a)}
function Af(a,b){b=cf(b);b.F&&(Q(a,"19",2,b.F),Q(a,"17",2,b.startTime),Q(a,"18",2,b.endTime))}function yf(a,b,c){var d=n;a.C=bf(a,d,c,J(b,13),a.C);var e=Aa(d.document.getElementsByTagName("iframe"),Cc);u(e,function(f){if(f=f.contentWindow)try{bf(a,f,c,J(b,13),-1)}catch(h){}});1==c&&Af(a,d)}
function Bf(a,b,c){var d=Wc();if(d&&(b.length||c.length)){var e={};d=(e[3]=d.toString(36),e);b.length&&(d[1]=Ba(b,function(f){f=Math.min(Math.max(f,0),4095);return"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_."[f>>6]+"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_."[f&63]}).join(""));c.length&&(d[2]=Ba(c,function(f){return"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_."[Math.min(Math.max(f,0),63)|0]}).join(""));Sd(a,5,Td(5,d),!0,".")}}
function Cf(a){if(df()){var b=ef(),c=b.ka,d=b.la,e=jd(400,function(){c.length||d.length?(Bf(a,c,d),c.length=0,d.length=0,n.setTimeout(e,1E4)):(c.push=function(){return 0},d.push=function(){return 0})});n.setTimeout(e,1E4)}}function tf(a){var b=n,c=[],d=[];De(b,c,d);b.setTimeout(jd(400,function(){Ce=!1;Bf(a,c,d)}),1E4)}function xf(a,b){re(b,function(c,d,e){if(null!=c&&null!=d&&null!=e){var f={};f[1]=b;f[2]=c;f[3]=d;f[4]=e;Ud(a,8,f)}})}
function qf(a){var b=n.performance&&n.performance.timing;if(b){var c=b.navigationStart;0<c&&(Q(a,"1",1,c),nc(hf,function(e,f){f=b[f];0<f&&Q(a,String(e),1,f-c)}));var d=Ee();d&&(d.S&&Q(a,"22",1,d.S),d.R&&Q(a,"23",1,d.R))}}function zf(a){var b=Be(n);b&&(10<b.length&&(b.length=10),Md(a,Ba(b,function(c){return we(c.id)+(c.a?"_"+we(c.a):"")+"_"+Math.floor(c.top).toString(36)+"_"+Math.floor(c.left).toString(36)+"_"+Math.floor(c.width).toString(36)+"_"+Math.floor(c.height).toString(36)}).join("~")))}
function nf(a){var b=xd(n.document);b&&N(n,b,function(){var c=Wc();if(c){var d=n.document;d={visible:1,hidden:2,prerender:3,preview:4,unloaded:5}[d.visibilityState||d.webkitVisibilityState||d.mozVisibilityState||""]||0;if(1==d||2==d){var e=new ff;c=K(e,1,Math.round(c));c=M(c,2,d,0);d=new zb;e=c.getTime();0!==e&&y(d,1,e);e=I(c,2,0);0!==e&&B(d,2,e);c=Cb(d);c=qb(c);Q(a,"1",11,c)}}})};gd.g(112,function(){var a=new R(1,"https:","csi.gstatic.com","/csi?v=2&s=pagead&action=","csi_pagead",gf);a.f=!0;mf(a);Cf(a)},void 0);}).call(this);
|
'use strict';
const defaults = require('lodash/defaults');
const util = require('hexo-util');
const pathFn = require('path');
const Permalink = util.Permalink;
let permalink;
function postPermalinkFilter(data) {
const config = this.config;
const meta = {
id: data.id || data._id,
title: data.slug,
name: typeof data.slug === 'string' ? pathFn.basename(data.slug) : '',
post_title: util.slugize(data.title, {transform: 1}),
year: data.date.format('YYYY'),
month: data.date.format('MM'),
day: data.date.format('DD'),
i_month: data.date.format('M'),
i_day: data.date.format('D')
};
if (!permalink || permalink.rule !== config.permalink) {
permalink = new Permalink(config.permalink);
}
const categories = data.categories;
if (categories.length) {
meta.category = categories.last().slug;
} else {
meta.category = config.default_category;
}
const keys = Object.keys(data);
let key = '';
for (let i = 0, len = keys.length; i < len; i++) {
key = keys[i];
if (meta.hasOwnProperty(key)) continue;
// Use Object.getOwnPropertyDescriptor to copy getters to avoid "Maximum call
// stack size exceeded" error
Object.defineProperty(meta, key, Object.getOwnPropertyDescriptor(data, key));
}
return permalink.stringify(defaults(meta, config.permalink_defaults));
}
module.exports = postPermalinkFilter;
|
describe('EventStore', function() {
afterEach(function() {
localStorage.clear();
});
var assert = chai.assert,
adapter = new Osef.storage.LocalstorageEventStoreAdapter('test'),
store = new Osef.storage.EventStore(adapter),
bus = Osef.wires.EventBus;
describe('appendToStream', function() {
it('should publish each event on the EventBus', function(done) {
bus.subscribe('domain.test-123.dummyCreated', function(e) {
assert(true);
done();
});
store.appendToStream('test-123', 0, [{ name: 'dummyCreated', payload: { foo: 'bar' } }]);
});
});
describe('loadEventStream', function() {
it('should return an EventStream object', function() {
var stream = store.loadEventStream('test-123');
assert(stream instanceof Osef.storage.EventStream);
});
it('should contain a version number and an array of events', function() {
store.appendToStream('test-123', 0, [
{ name: 'dummyCreated', payload: { foo: 'bar' } },
{ name: 'dummyCreated', payload: { john: 'doe' } }
]);
var stream = store.loadEventStream('test-123');
assert.equal(stream.version, 2);
assert.equal(stream.events.length, 2);
});
});
});
|
import React from 'react';
import { nextSection, toCurrency } from '../lib/Utility.js';
/**
* Print-only component that lists out inputs without controls
*/
class BasicInfoData extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<div className="pre_calculate basic_info_data print_only card pre_calculate input">
<div>
<div className="print_banner">
Energy Innovation <span className="fancy_and">and</span> Carbon Dividend Act
</div>
<div className="row">
<div className="col-xs-12 bottom_buffer">
<span className="form_title">Household Summary</span>
</div>
</div>
<div className="print_result_row">
<div className="results_label">Number of Adults:</div>
<div>{this.props.adults}</div>
<div className="results_label">Number of Children:</div>
<div>{this.props.children}</div>
</div>
<div className="print_result_row">
<div className="results_label">Number of Vehicles:</div>
<div>{this.props.vehicles}</div>
</div>
<div className="print_result_row">
<div className="results_label">Zip Code:</div>
<div>{this.props.zip}</div>
</div>
<div className="print_result_row">
<div className="results_label">Income:</div>
<div>{toCurrency(this.props.income, '$0,0')}</div>
</div>
<div className="print_result_row">
<div className="results_label">Dwelling Type:</div>
<div>{this.props.dwelling_type}</div>
</div>
<div className="print_result_row">
<div className="results_label">Heating Fuel:</div>
<div>{this.props.heating_type}</div>
</div>
</div>
<div className="spending_summary">
<div className="print_result_row">
<div className="bottom_buffer top_buffer">
<span className="form_title">Spending Summary</span>
</div>
</div>
<div className="row bottom_buffer">
<div className="results_label">Average Monthly Electricity</div>
<div className="">{toCurrency(this.props.elec, '$0,0')}</div>
</div>
<div className="row bottom_buffer">
<div className="results_label">Average Monthly Gasoline</div>
<div>{toCurrency(this.props.gas, '$0,0')}</div>
</div>
<div className="row bottom_buffer">
<div className="results_label">Average monthly {this.props.heating_type} expenditure</div>
<div>{toCurrency(this.props.heat, '$0,0')}</div>
</div>
</div>
</div>
);
}
}
export default BasicInfoData;
|
import React from 'react';
import { StyledIcon } from '../StyledIcon';
export const CircleInformation = props => (
<StyledIcon viewBox='0 0 24 24' a11yTitle='CircleInformation' {...props}>
<path fill='none' stroke='#000' strokeWidth='2' d='M12,22 C17.5228475,22 22,17.5228475 22,12 C22,6.4771525 17.5228475,2 12,2 C6.4771525,2 2,6.4771525 2,12 C2,17.5228475 6.4771525,22 12,22 Z M12,10 L12,18 M12,6 L12,8' />
</StyledIcon>
);
|
import torch
import torch.nn as nn
import torch.nn.functional as F
from ptsemseg.utils import handle_input_target_mismatch
def cross_entropy2d(input, target, weight=None, reduction='sum', bkargs=None):
n, c, h, w = input.size()
input, target = handle_input_target_mismatch(input, target)
input = input.transpose(1, 2).transpose(2, 3).contiguous().view(-1, c)
target = target.view(-1)
loss = F.cross_entropy(
input, target, weight=weight, reduction=reduction, ignore_index=250
)
return loss
def DiceLoss(input, target):
# def __init__(self):
# super(DiceLoss, self).__init__()
# def forward(self, input, target):
N = target.size(0)
smooth = 1
input_flat = input.view(N, -1).float()
target_flat = target.view(N, -1).float()
intersection = input_flat * target_flat
loss = 2 * (intersection.sum(1) + smooth) / (input_flat.sum(1) + target_flat.sum(1) + smooth)
loss = 1 - loss.sum() / N
return loss
class multi_step_DiceLoss(nn.Module):
def __init__(self):
super(multi_step_DiceLoss, self).__init__()
def forward(self, input, target):
loss=(DiceLoss(F.sigmoid(input[0]), target)+2*DiceLoss(F.sigmoid(input[1]), target)+3*DiceLoss(F.sigmoid(input[2]), target)+3*DiceLoss(F.sigmoid(input[3]), target))/9
return loss
class my_cross_entropy2d(nn.Module):
def __init__(self, weight=None, reduction='sum', bkargs=None):
super(my_cross_entropy2d, self).__init__()
self.weight = weight
self.reduction = reduction
def forward(self, myinput, target):
n, c, h, w = myinput.size()
myinput = myinput.transpose(1, 2).transpose(2, 3).contiguous().view(-1, c)
target = target.view(-1)
# loss = F.cross_entropy(
# myinput, target, weight=self.weight, reduction=self.reduction, ignore_index=250
# )
loss = F.cross_entropy(
myinput, target, weight=self.weight, reduction=self.reduction
)
return loss
def multi_step_cross_entropy2d(input, target, weight=None, reduction='sum', scale_weight=None, bkargs=None):
if not isinstance(input, (tuple,list)):
return cross_entropy2d(input=input, target=target, weight=weight, reduction=reduction)
# Auxiliary training for PSPNet [1.0, 0.4] and ICNet [1.0, 0.4, 0.16]
scale = 1.0 if scale_weight is None else scale_weight
# if scale_weight == None: # scale_weight: torch tensor type
# scale = 1.0
# else:
# scale = scale_weight
# print('multi_step_cross_entropy2d scale weight is {}'.format(scale))
n_inp = len(input)
scale_weight = torch.pow(scale * torch.ones(n_inp), torch.arange(n_inp-1, -1, -1, out=torch.FloatTensor()))
scale_weight = scale_weight.to(input[0].device)
loss = 0.0
for i, inp in enumerate(input):
loss = loss + scale_weight[i] * cross_entropy2d(
input=inp, target=target, weight=weight, reduction=reduction
)
return loss
class my_multi_step_cross_entropy2d(nn.Module):
def __init__(self, scale_weight=None, n_inp=2, weight=None, reduction='sum', bkargs=None):
super(my_multi_step_cross_entropy2d, self).__init__()
# Auxiliary training for PSPNet [1.0, 0.4] and ICNet [1.0, 0.4, 0.16]
scale = 1.0 if scale_weight is None else scale_weight
print('my_multi_step_cross_entropy2d scale weight is {}'.format(scale))
scale_weight = torch.pow(scale * torch.ones(n_inp), torch.arange(n_inp-1, -1, -1, out=torch.FloatTensor()))
self.scale_weight = scale_weight.to(bkargs.device)
self.weight = weight
self.reduction = reduction
def forward(self, myinput, target):
loss = 0
for i, inp in enumerate(myinput):
loss = loss + self.scale_weight[i] * cross_entropy2d(
input=inp, target=target, weight=self.weight, reduction=self.reduction
)
return loss
def multi_scale_cross_entropy2d(
input, target, weight=None, reduction='sum', scale_weight=None, bkargs=None
):
if not isinstance(input, (tuple,list)):
return cross_entropy2d(input=input, target=target, weight=weight, reduction=reduction)
# Auxiliary training for PSPNet [1.0, 0.4] and ICNet [1.0, 0.4, 0.16]
scale = 1.0 if scale_weight is None else scale_weight
n_inp = len(input)
scale_weight = torch.pow(scale * torch.ones(n_inp), torch.arange(n_inp - 1, -1, -1, out=torch.FloatTensor()))
scale_weight = scale_weight.to(input[0].device)
loss = 0.0
for i, inp in enumerate(input):
loss = loss + scale_weight[i] * cross_entropy2d(
input=inp, target=target, weight=weight, reduction=reduction
)
return loss
def bootstrapped_cross_entropy2d(input,
target,
K,
weight=None,
reduction='sum',
bkargs=None):
batch_size = input.size()[0]
def _bootstrap_xentropy_single(input,
target,
K,
weight=None,
reduction=reduction):
n, c, h, w = input.size()
input = input.transpose(1, 2).transpose(2, 3).contiguous().view(-1, c)
target = target.view(-1)
loss = F.cross_entropy(input,
target,
weight=weight,
reduce=False,
reduction=reduction,
ignore_index=250)
topk_loss, _ = loss.topk(K)
reduced_topk_loss = topk_loss.sum() / K
return reduced_topk_loss
loss = 0.0
# Bootstrap from each image not entire batch
for i in range(batch_size):
loss += _bootstrap_xentropy_single(
input=torch.unsqueeze(input[i], 0),
target=torch.unsqueeze(target[i], 0),
K=K,
weight=weight,
reduction=reduction,
)
return loss / float(batch_size)
|
apikey = '7kQA3wxBMZe3lsDYyxdlrz83'
|
"""RAPID-ROS Interface to communicate with YuMi robot through RWS."""
# Copyright (c) 2022, ABB
# All rights reserved.
#
# Redistribution and use in source and binary forms, with
# or without modification, are permitted provided that
# the following conditions are met:
#
# * Redistributions of source code must retain the
# above copyright notice, this list of conditions
# and the following disclaimer.
# * Redistributions in binary form must reproduce the
# above copyright notice, this list of conditions
# and the following disclaimer in the documentation
# and/or other materials provided with the
# distribution.
# * Neither the name of ABB nor the names of its
# contributors may be used to endorse or promote
# products derived from this software without
# specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
# THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import time
from abb_rapid_sm_addin_msgs.srv import SetRAPIDRoutine, SetSGCommand
from abb_robot_msgs.srv import GetRAPIDBool, SetRAPIDSymbol, TriggerWithResultCode
import numpy as np
from rclpy.client import Client
import robot_interface.interface as wi
from scipy.spatial.transform import Rotation
class RAPIDTask(wi.Task):
"""General RAPID interface initializing ROS services."""
def __init__(
self,
rapid_stop: Client,
rapid_start: Client,
pp_to_main: Client,
rapid_set: Client,
rapid_run: Client,
rapid_symbol: Client,
rapid_bool: Client,
rob_task: str = 'T_ROB_R'
):
"""
Initialize a RAPID task with by linking the ROS clients.
Args:
----
rapid_stop: Client that stops the RAPID routine.
rapid_start: Client that starts the RAPID routine.
pp_to_main: : Client that resets the ProgramPointer in the RAPID routine.
rapid_set: Client that sets the routine to run.
rapid_run: Client that runs the RAPID routine.
rapid_symbol: Client that sets a RAPID symbol.
rapid_bool: Client that sets a RAPID bool.
rob_task: Left or Right arm of the robot in RAPID language.
"""
super().__init__()
self.rapid_stop = rapid_stop
self.rapid_start = rapid_start
self.pp_to_main = pp_to_main
self.rapid_set = rapid_set
self.rapid_run = rapid_run
self.rapid_symbol = rapid_symbol
self.rapid_bool = rapid_bool
self.rob_task = rob_task
self.preempted = False
self.rapid_status = 'INVALID'
def initialize(self):
"""Initialize RAPID with default symbols."""
self.rapid_status = 'RUNNING'
self.rapid_stop.call(TriggerWithResultCode.Request())
time.sleep(0.2)
self.pp_to_main.call(TriggerWithResultCode.Request())
time.sleep(0.2)
self.rapid_start.call(TriggerWithResultCode.Request())
time.sleep(0.3)
symbol_request = SetRAPIDSymbol.Request()
symbol_request.path.task = self.rob_task
symbol_request.path.module = 'TRobRAPID'
symbol_request.path.symbol = 'routine_completed'
symbol_request.value = 'FALSE'
response = self.rapid_symbol.call(symbol_request)
if response.result.message != '':
print(f'SetRAPIDSymbol returned message "{response.result.message}"\
and code "{response.result.code}"')
self.rapid_status = 'FAILURE'
def terminate(self):
self.preempted = True
def wait_for_rapid(self):
"""Wait for RAPID to complete the routine."""
while not self.preempted and not self.rapid_done():
self.rapid_status = 'RUNNING'
time.sleep(0.1)
if self.rapid_done():
self.rapid_status = 'SUCCESS'
def rapid_done(self) -> bool:
"""
Return whether RAPID has finished the execution.
Returns
-------
done: value of the request.
"""
request = GetRAPIDBool.Request()
request.path.task = self.rob_task
request.path.module = 'TRobRAPID'
request.path.symbol = 'routine_completed'
done = self.rapid_bool.call(request).value
return done
def get_rapid_status(self) -> str:
"""
Get the RAPID status according to Behavior Tree return statuses.
Returns
-------
return_msg: one of 'RUNNING', 'SUCCESS', 'FAILURE', 'INVALID'.
"""
return_msg = self.rapid_status
return return_msg
def set_rapid_tool(self, tool: str):
"""
Set the tool in RAPID.
Args:
----
tool: name of the tool to set, either gripper or suction_cup.
"""
symbol_request = SetRAPIDSymbol.Request()
symbol_request.path.task = self.rob_task
symbol_request.path.module = 'TRobUtility'
symbol_request.path.symbol = 'current_tool'
if tool == 'suction_cup':
symbol_request.value = '[TRUE, [[77, 20, 39], [1, 0, 0 ,0]],\
[0.248, [8.6, 11.7, 52.7], [1, 0, 0, 0], 0.00021, 0.00024, 0.00009]]'
else:
symbol_request.value = '[TRUE, [[0, 0, 138], [1, 0, 0 ,0]],\
[0.248, [8.6, 11.7, 52.7], [1, 0, 0, 0], 0.00021, 0.00024, 0.00009]]'
response = self.rapid_symbol.call(symbol_request)
if response.result.message != '':
print(f'SetRAPIDSymbol returned message "{response.result.message}"\
and code "{response.result.code}"')
self.rapid_status = 'FAILURE'
def set_robtarget(
self,
position: np.ndarray,
orientation: np.ndarray
):
"""
Set a pose target for the robot.
Args:
----
position: target position value in [m].
orientation: targert orientation value.
"""
position_str = str((position*1e3).tolist())
if self.tool == 'suction_cup':
if self.rob_task == 'T_ROB_R':
orientation_str = '[0.5, -0.5, 0.5, 0.5]'
else:
orientation_str = '[0.5, 0.5, 0.5, -0.5]'
else:
# get rotation around Y axis from quaternion
angle = Rotation.from_quat(orientation).as_euler('XYZ')[2]
print('Rotation angle: ' + str(angle))
if self.rob_task == 'T_ROB_R':
if angle > np.pi:
# bring angle to working range
angle -= 2*np.pi
# use symmetry
angle = -np.pi - angle
elif angle < -np.pi:
angle += 2*np.pi
# use symmetry
angle = np.pi - angle
# finally have it positive
angle = np.abs(angle)
else:
if angle > 1.5*np.pi:
angle -= 2*np.pi
elif angle < -0.5*np.pi:
angle += 2*np.pi
print('Normalized angle: ' + str(angle) + ' for ' + str(self.rob_task))
rotation_quaternion = Rotation.from_euler('z', angle)
print('Angle as quaternion: ' + str(rotation_quaternion.as_quat()))
yumi_gripper_rotation_x = -0.707107
yumi_gripper_rotation_y = 0.707107
yumi_gripper_rotation_z = 0.0
yumi_gripper_rotation_w = 0.0
rotation_YuMi = Rotation.from_quat(
[
yumi_gripper_rotation_x,
yumi_gripper_rotation_y,
yumi_gripper_rotation_z,
yumi_gripper_rotation_w
]
)
orientation = (rotation_quaternion*rotation_YuMi).as_quat()
print('YuMi Angle as quaternion: ' + str(orientation))
orientation_yumi_format = [
orientation[3], orientation[0], orientation[1], orientation[2]]
orientation_str = str(orientation_yumi_format)
if self.rob_task == 'T_ROB_R':
if self.tool == 'suction_cup':
config = '[1, 1, -1, 4]'
else:
config = '[1, -1, -1, 4]'
else:
if self.tool == 'suction_cup':
config = '[-1, 1, 1, 4]'
else:
config = '[-1, 1, -1, 4]'
print('Tool: ' + str(self.tool))
print('RobTask: ' + str(self.rob_task))
symbol_request = SetRAPIDSymbol.Request()
symbol_request.path.task = self.rob_task
symbol_request.path.module = 'TRobRAPID'
symbol_request.path.symbol = 'move_robtarget_input'
symbol_request.value = '[%s, %s, %s, [180, 9E9, 9E9, 9E9, 9E9, 9E9]]' %\
(position_str, orientation_str, config)
print('REQUEST', symbol_request.value)
response = self.rapid_symbol.call(symbol_request)
if response.result.message != '':
print(f'SetRAPIDSymbol for RobotTarget returned message "{response.result.message}"\
and code "{response.result.code}"')
self.rapid_status = 'FAILURE'
def set_jointtarget(self, joints: str):
"""
Set a joint target for the robot.
Args:
----
joints: target joint value.
"""
symbol_request = SetRAPIDSymbol.Request()
symbol_request.path.task = self.rob_task
symbol_request.path.module = 'TRobRAPID'
symbol_request.path.symbol = 'move_jointtarget_input'
symbol_request.value = joints
response = self.rapid_symbol.call(symbol_request)
if response.result.message != '':
print(f'SetRAPIDSymbol for JointTarget returned message "{response.result.message}"\
and code "{response.result.code}"')
self.rapid_status = 'FAILURE'
def execute_rapid(self, routine: str):
"""
Execute the target RAPID routine.
Args:
----
routine: name of the routine in RAPID.
"""
routine_request = SetRAPIDRoutine.Request()
routine_request.task = self.rob_task
routine_request.routine = routine
response = self.rapid_set.call(routine_request)
if response.result.message != '':
print(f'SetRAPIDRoutine returned message "{response.result.message}"\
and code "{response.result.code}"')
self.rapid_status = 'FAILURE'
response = self.rapid_run.call(TriggerWithResultCode.Request())
if response.result.message != '':
print(f'RunRAPIDRoutine returned message "{response.result.message}"\
and code "{response.result.code}"')
self.rapid_status = 'FAILURE'
class HomeTask(RAPIDTask):
"""Move arm to home position."""
def __init__(self, *args):
super().__init__(*args)
def run(self):
self.initialize()
symbol_request = SetRAPIDSymbol.Request()
symbol_request.path.task = self.rob_task
symbol_request.path.module = 'TRobRAPID'
symbol_request.path.symbol = 'move_jointtarget_input'
if self.rob_task == 'T_ROB_R':
symbol_request.value = '[[49, -66, 13, -94, 87, -90], [-34, 9E9, 9E9, 9E9, 9E9, 9E9]]'
else:
symbol_request.value = '[[-49, -66, 13, 94, 87, -90], [34, 9E9, 9E9, 9E9, 9E9, 9E9]]'
response = self.rapid_symbol.call(symbol_request)
if response.result.message != '':
print(f'SetRAPIDSymbol returned message "{response.result.message}"\
and code "{response.result.code}"')
self.rapid_status = 'FAILURE'
symbol_request = SetRAPIDSymbol.Request()
symbol_request.path.task = self.rob_task
symbol_request.path.module = 'TRobRAPID'
symbol_request.path.symbol = 'move_speed_input'
symbol_request.value = '[500, 500, 5000, 1000]'
response = self.rapid_symbol.call(symbol_request)
if response.result.message != '':
print(f'SetRAPIDSymbol returned message "{response.result.message}"\
and code "{response.result.code}"')
self.rapid_status = 'FAILURE'
self.execute_rapid('runMoveAbsJ')
self.wait_for_rapid()
class GripperTask(RAPIDTask):
"""Set target to the grippers."""
def __init__(
self,
state: str,
robot_state: 'State',
client_set: Client,
client_run: Client,
*args
):
"""
Initialize the gripper task setting the ROS services and states.
Args:
----
state: target state for the gripper (open/close).
robot_state: robot internal state defining if it's picking an object
or executing a blocking task.
client_set: name of the Client setting the gripper state.
client_run: name of the Client running the gripper task.
*args: other ROS clients for the RAPID class.
"""
super().__init__(*args)
self.state = state
self.robot_state = robot_state
self.client_set = client_set
self.client_run = client_run
def run(self):
self.initialize()
request = SetSGCommand.Request()
request.command = 6 if self.state == 'closed' else 7
request.task = self.rob_task
response = self.client_set.call(request)
if response.result.message != '':
print(f'SetSGCommand returned message "{response.result.message}"\
and code "{response.result.code}"')
self.rapid_status = 'FAILURE'
self.client_run.call(TriggerWithResultCode.Request())
if self.state == 'open':
self.robot_state.holding = ''
class MoveJTask(RAPIDTask):
"""Move robot Joints."""
def __init__(
self,
joints: str,
robot_state: 'State',
*args
):
"""
Initialize the task.
Args:
----
joints: joints to move.
robot_state: robot internal state defining if it's picking an object
or executing a blocking task.
*args: other ROS clients for the RAPID class.
"""
super().__init__(*args)
self.joints = joints
self.state = robot_state
def run(self):
print('Running')
self.initialize()
self.state.blocking = True
print('Moving to', self.joints)
self.set_jointtarget(self.joints)
self.execute_rapid('runMoveAbsJ')
self.wait_for_rapid()
print('Rapid done!')
self.state.holding = ''
self.state.blocking = False
self.state.blocked_conditions.clear()
class PlaceTask(RAPIDTask):
"""RAPID interface for the placing task."""
def __init__(
self,
position: np.ndarray,
orientation: np.ndarray,
tool: str,
robot_state: 'State',
*args
):
"""
Position and orientation are in base frame.
Args:
----
position: given by ROS in [m], it is converted in [mm] and sent to RAPID.
orientation: orientation of the object to pick.
tool: picking tool.
robot_state: robot internal state defining if it's picking an object
or executing a blocking task.
object: object to pick (defined by its frame).
*args: other ROS clients for the RAPID class.
"""
super().__init__(*args)
self.position = position
self.orientation = orientation
self.state = robot_state
self.tool = tool
def run(self):
self.initialize()
self.state.blocking = True
print('Placing at', self.position, '[m] orientation', self.orientation)
self.set_rapid_tool(self.tool)
self.set_robtarget(self.position, self.orientation)
routine = 'place_vacuum' if self.tool == 'suction_cup' else 'place_gripper'
self.execute_rapid(routine)
self.wait_for_rapid()
self.state.holding = ''
self.state.blocking = False
self.state.blocked_conditions.clear()
class PickTask(RAPIDTask):
"""RAPID interface for the picking task."""
def __init__(
self,
position: np.ndarray,
orientation: np.ndarray,
tool: str,
robot_state: 'State',
target_object: str,
*args
):
"""
Position and orientation are in base frame.
Args:
----
position: given by ROS in [m], it is converted in [mm] and sent to RAPID.
orientation: orientation of the object to pick.
tool: picking tool.
robot_state: robot internal state defining if it's picking an object
or executing a blocking task.
target_object: object to pick (defined by its frame).
*args: other ROS clients for the RAPID class.
"""
super().__init__(*args)
self.position = position
self.orientation = orientation
self.state = robot_state
self.object = target_object
self.tool = tool
def run(self):
print('Inside RAPID task')
self.initialize()
self.state.blocking = True
print('Picking', self.object, 'at', self.position, '[m] orientation', self.orientation)
self.set_rapid_tool(self.tool)
self.set_robtarget(self.position, self.orientation)
routine = 'pick_vacuum' if self.tool == 'suction_cup' else 'pick_gripper'
self.execute_rapid(routine)
self.wait_for_rapid()
self.state.holding = self.object
self.state.blocking = False
class State:
"""
Represent part of the robot's internal state that cannot be measured.
Access to the state is thread safe.
The state can only be accessed within a "with" statement.
"""
def __init__(self):
self.__holding = ''
self.__blocking = False
self.__blocked_conditions = []
@property
def holding(self):
return self.__holding
@holding.setter
def holding(self, value):
self.__holding = value
@property
def blocking(self):
return self.__blocking
@blocking.setter
def blocking(self, value):
self.__blocking = value
@property
def blocked_conditions(self):
return self.__blocked_conditions
@blocked_conditions.setter
def blocked_conditions(self, value):
self.__blocked_conditions = value
|
#!/usr/bin/env node
/* @ts-check */
/* eslint-disable no-console */
/* Copies dependency versions from Deck's root package.json (../../package.json) */
const fs = require(`fs`);
const path = require(`path`);
const yargs = require('yargs')
.usage(`$0 [--no-dev] [--no-peer] [package.json]`)
.option('source', {
description: 'The source package.json',
default: '../../package.json',
})
.option('dest', {
description: 'The destination package.json',
default: './package.json',
})
.option('no-dev', { type: 'boolean', description: 'do not sync devDependencies', default: false })
.option('no-peer', { type: 'boolean', description: 'do not sync peerDependencies', default: false });
const { argv } = yargs;
const targetPackageJson = path.resolve(argv.dest);
const getPath = (string) => path.resolve(__dirname, ...string.split('/'));
const parse = (path) => JSON.parse(fs.readFileSync(path).toString());
const sourcePackageJson = parse(getPath(argv.source));
// { [package]: version } from deck's package.json
const versionsFromDeck = {
...sourcePackageJson.peerDependencies,
...sourcePackageJson.devDependencies,
...sourcePackageJson.dependencies,
};
const getDesiredVersion = (pkgName) => {
switch (pkgName) {
case '@spinnaker/core':
return parse(getPath('../../app/scripts/modules/core/package.json')).version;
case '@spinnaker/eslint-plugin':
return parse(getPath('../eslint-plugin/package.json')).version;
case '@spinnaker/presentation':
return parse(getPath('../presentation/package.json')).version;
default:
return versionsFromDeck[pkgName];
}
};
const packageJson = parse(targetPackageJson);
const shouldSkip = (key) =>
(key === 'devDependencies' && argv['no-dev']) || (key === 'peerDependencies' && argv['no-peer']);
const keys = ['dependencies', 'peerDependencies', 'devDependencies'].filter((key) => !shouldSkip(key));
keys.forEach((key) => {
Object.keys(packageJson[key] || {}).forEach((pkgName) => {
packageJson[key][pkgName] = getDesiredVersion(pkgName) || packageJson[key][pkgName];
});
});
fs.writeFileSync(
targetPackageJson,
JSON.stringify(packageJson, null, 2).replace(/{\s*"dev": true\s*}/g, `{ "dev": true }`),
);
console.log(`Synchronized dependencies in ${targetPackageJson} from Deck`);
|
# -*- coding: utf-8 -*-
import numpy as np
from ThymeBoost.exogenous_models import (ols_exogenous,
decision_tree_exogenous,
glm_exogenous)
class FitExogenous:
def __init__(self,
exo_estimator='ols',
exogenous_lr=1,
**kwargs):
self.exo_estimator = exo_estimator
self.exogenous_lr = exogenous_lr
self.kwargs = kwargs
return
def set_estimator(self, trend_estimator):
if trend_estimator == 'ols':
fit_obj = ols_exogenous.OLS
elif trend_estimator == 'glm':
fit_obj = glm_exogenous.GLM
elif trend_estimator == 'decision_tree':
fit_obj = decision_tree_exogenous.DecisionTree
else:
raise NotImplementedError('That Exo estimation is not availale yet, add it to the road map!')
return fit_obj
def fit_exogenous_component(self, time_residual, exogenous):
self.model_obj = self.set_estimator(self.exo_estimator)()
exogenous = np.array(exogenous).reshape((-1, 1))
exo_fitted = self.model_obj.fit(time_residual, exogenous, **self.kwargs)
return self.exogenous_lr*np.array(exo_fitted)
|
import math
import torch
import torch.nn.functional as F
def psnr(gt, img):
"""
calculate psnr between two images
:param gt: groundtruth image
:param img: inference image
:return: psnr
"""
mse = torch.mean( (gt - img) ** 2 )
if mse < 1.0e-10:
return 100
PIXEL_MAX = 1.0
return 20 * torch.log10(PIXEL_MAX / torch.sqrt(mse))
def gaussian(window_size, sigma):
gauss = torch.Tensor([math.exp(-(x - window_size // 2) ** 2 / float(2 * sigma ** 2)) for x in range(window_size)])
return gauss / gauss.sum()
# create gaussian kernel by multiply two gaussian distribution
# extend to 3 channel
def create_window(window_size, channel=1):
_1D_window = gaussian(window_size, 1.5).unsqueeze(1)
_2D_window = _1D_window.mm(_1D_window.t()).float().unsqueeze(0).unsqueeze(0)
window = _2D_window.expand(channel, 1, window_size, window_size).contiguous()
return window
def ssim(img1, img2, window_size=11, window=None, size_average=True, full=False, val_range=None):
# Value range can be different from 255. Other common ranges are 1 (sigmoid) and 2 (tanh).
if val_range is None:
if torch.max(img1) > 128:
max_val = 255
else:
max_val = 1
if torch.min(img1) < -0.5:
min_val = -1
else:
min_val = 0
L = max_val - min_val
else:
L = val_range
padd = 0
(_, channel, height, width) = img1.size()
if window is None:
real_size = min(window_size, height, width)
window = create_window(real_size, channel=channel).to(img1.device)
mu1 = F.conv2d(img1, window, padding=padd, groups=channel)
mu2 = F.conv2d(img2, window, padding=padd, groups=channel)
mu1_sq = mu1.pow(2)
mu2_sq = mu2.pow(2)
mu1_mu2 = mu1 * mu2
sigma1_sq = F.conv2d(img1 * img1, window, padding=padd, groups=channel) - mu1_sq
sigma2_sq = F.conv2d(img2 * img2, window, padding=padd, groups=channel) - mu2_sq
sigma12 = F.conv2d(img1 * img2, window, padding=padd, groups=channel) - mu1_mu2
C1 = (0.01 * L) ** 2
C2 = (0.03 * L) ** 2
v1 = 2.0 * sigma12 + C2
v2 = sigma1_sq + sigma2_sq + C2
cs = torch.mean(v1 / v2) # contrast sensitivity
ssim_map = ((2 * mu1_mu2 + C1) * v1) / ((mu1_sq + mu2_sq + C1) * v2)
if size_average:
ret = ssim_map.mean()
else:
ret = ssim_map.mean(1).mean(1).mean(1)
if full:
return ret, cs
return ret
if __name__ == '__main__':
device = 'cuda'
img = torch.ones([5, 3, 64, 64]).to(device)*0.5
img_ = torch.ones([5, 3, 64, 64]).to(device)*0.5 +torch.randn([5, 3, 64, 64]).to(device)*0.005
PSNR = psnr(img,img_)
SSIM = ssim(img, img_)
print("finished")
|
// 创建
$.validator.setDefaults({
highlight: function(e) {
$(e).closest(".form-group").removeClass("has-success").addClass("has-error")
},
success: function(e) {
e.closest(".form-group").removeClass("has-error").addClass("has-success")
},
errorElement: "span",
errorPlacement: function(e, r) {
e.appendTo(r.is(":radio") || r.is(":checkbox") ? r.parent().parent().parent() : r.parent())
},
errorClass: "help-block m-b-none",
validClass: "help-block m-b-none"
}),
$().ready(function() {
$("#commentForm").validate();
var e = "<i class='fa fa-times-circle'></i> ";
$("#signupForm-add").validate({
rules: {
// firstname: "required",
// lastname: "required",
Name: {
required: !0,
minlength: 2
},
Desc: {
required: !0,
minlength: 5
}
},
messages: {
Name: {
required: e + "请输入角色名称",
minlength: e + "用户名必须两个字符以上"
},
Desc: {
required: e + "请输入描述信息",
minlength: e + "描述必须5个字符以上"
}
}
});
$("#signupForm-edit").validate({
rules: {
Name: {
required: !0,
minlength: 2
},
Desc: {
required: !0,
minlength: 5
}
},
messages: {
Name: {
required: e + "请输入角色名称",
minlength: e + "用户名必须两个字符以上"
},
Desc: {
required: e + "请输入描述信息",
minlength: e + "描述必须5个字符以上"
}
}
})
});
// 编辑
|
'use strict';
var express = require('express');
var routes = require('./app/routes/index.js');
var mongoose = require('mongoose');
var passport = require('passport');
var session = require('express-session');
var expressHbs = require("express-handlebars");
var bodyParser = require("body-parser");
var app = express();
require('dotenv').load();
require('./app/config/passport')(passport);
mongoose.connect(process.env.MONGO_URI);
mongoose.Promise = global.Promise;
app.use('/controllers', express.static(process.cwd() + '/app/controllers'));
app.use('/public', express.static(process.cwd() + '/public'));
app.use('/common', express.static(process.cwd() + '/app/common'));
app.use(session({
secret: 'secretClementine',
resave: false,
saveUninitialized: true
}));
app.use(passport.initialize());
app.use(passport.session());
app.engine('hbs', expressHbs.create({
extname:'hbs',
defaultLayout:'main.hbs',
helpers: {
toJSON : function(object) {
return JSON.stringify(object);
}
}
}).engine);
app.set('view engine', 'hbs');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
routes(app, passport);
var port = process.env.PORT || 8080;
app.listen(port, function () {
console.log('Node.js listening on port ' + port + '...');
});
|
{
jQuery.fn.creaTip = function(textoTip, opciones) {
let configuracion = {
velocidad: 500,
animacionMuestra: {width: "show"},
animacionOculta: {opacity: "hide"},
claseTip: "tip"
}
jQuery.extend(configuracion, opciones);
this.each(function(){
elem = $(this);
let miTip = $('<div class="' + configuracion.claseTip + '">' + textoTip + '</div>');
$(document.body).append(miTip);
elem.data("capatip", miTip);
elem.mouseenter(function(e){
let miTip = $(this).data("capatip");
miTip.css({
left: e.pageX + 10,
top: e.pageY + 5
});
miTip.animate(configuracion.animacionMuestra, configuracion.velocidad);
});
elem.mouseleave(function(e){
let miTip = $(this).data("capatip");
miTip.animate(configuracion.animacionOculta, configuracion.velocidad);
});
});
return this;
};
$(function(){
$("#elemento1").creaTip("todo bien...");
$("#elemento2").creaTip("Otra prueba...", {
velocidad: 1000,
claseTip: "otroestilotip",
animacionMuestra: {
opacity: "show",
padding: '25px',
'font-size': '2em'
},
animacionOculta: {
height: "hide",
padding: '5px',
'font-size': '1em'
}
});
})
}
|
#!/usr/bin/env python3
import os
import sys
import xlrd
import shutil
from pymongo import MongoClient
from fun import clean_str, split_pro
from dialogue import Dialogue
from qa import Qa
from greeting import Greeting
from sale import Sale
from sale_2 import Sale_2
from refuse2chat import Refuse2chat
from interaction import Interaction
from sentiment import Sentiment
import common
class Update_data():
def __init__(self, ip = '', port = '', db_name = ''):
self.ip = ip
self.port = port
self.db_name = db_name
self.client = MongoClient(ip, port)
self.db = self.client[db_name]
def update_dialogue(self):
print('--------dialogue starting--------')
d = Dialogue(self.ip, self.port, self.db_name)
d.update()
print('--------dialogue ok--------------')
def update_qa(self):
print('--------qa starting--------')
q = Qa(self.ip, self.port, self.db_name)
q.update()
print('--------qa ok--------------')
def update_greeting(self):
print('--------greeting starting--------')
g = Greeting(self.ip, self.port, self.db_name)
g.update()
print('--------greeting ok--------')
def update_sale(self):
print('--------sale starting--------')
s = Sale(self.ip, self.port, self.db_name)
s.update()
print('--------sale ok--------')
def update_sale_2(self):
print('--------sale_2 starting--------')
s = Sale_2(self.ip, self.port, self.db_name)
s.update()
print('--------sale_2 ok--------')
def update_refuse2chat(self):
print('--------refuse2chat starting--------')
s = Refuse2chat(self.ip, self.port, self.db_name)
s.update()
print('--------refuse2chat ok--------')
def update_interaction(self):
print('--------interaction starting--------')
i = Interaction(self.ip, self.port, self.db_name)
i.update()
print('--------interaction ok--------------')
def copy_mongodb(self):
print('--------copydb starting--------')
self.client.drop_database(self.db_name+'_test')
self.client.admin.command('copydb', fromdb=self.db_name,
todb=self.db_name+'_test')
print('--------copydb ok--------------')
def update(ip, port, mode):
up = Update_data(ip, port, mode)
Scene = {
'bank':[up.update_dialogue, up.update_qa,
up.update_greeting, up.update_sale,
up.update_sale_2, up.update_refuse2chat,
up.update_interaction],
'bank_ccb':[up.update_dialogue, up.update_qa,
up.update_greeting, up.update_sale,
up.update_sale_2, up.update_refuse2chat,
up.update_interaction],
'bank_psbc':[up.update_dialogue, up.update_qa,
up.update_greeting, up.update_sale,
up.update_sale_2, up.update_refuse2chat,
up.update_interaction],
'suning_biu':[up.update_dialogue, up.update_qa,
up.update_greeting,up.update_refuse2chat,
up.update_interaction],
'water':[up.update_dialogue, up.update_qa,
up.update_greeting, up.update_refuse2chat,
up.update_interaction],
'ecovacs':[up.update_dialogue, up.update_qa,
up.update_greeting, up.update_sale,
up.update_sale_2, up.update_refuse2chat,
up.update_interaction],
'ule':[up.update_dialogue, up.update_qa,
up.update_greeting, up.update_refuse2chat,
up.update_interaction],
'bookstore':[up.update_qa],
}
for f in Scene[mode]:
f()
#up.copy_mongodb()
def update_common(ip, port):
print('--------common starting--------')
interaction = common.Interaction(ip, port)
repeat = common.Repeat(ip, port)
#copydb = common.Copydb(ip, port)
interaction.update()
repeat.update()
#copydb.copy_mongodb()
print('--------common ok-----------')
def update_sentiment(ip, port):
print('--------sentiment starting-------')
sen = Sentiment(ip, port)
sen.update()
print('--------sentiment ok-----------')
if __name__ == '__main__':
ip = '127.0.0.1'
port = 27017
Mode = ['bank', 'bank_ccb', 'bank_psbc', 'suning_biu', 'ecovacs', 'bookstore']
if len(sys.argv) != 2:
print('!!!The number of args is wrong!!!')
assert(0)
if sys.argv[1] == 'all':
mode = Mode
elif sys.argv[1] not in Mode:
print('!!!error arg:', sys.argv[1])
assert(0)
else:
mode = [sys.argv[1]]
for m in mode:
print('########## '+m+' START ###########')
update(ip, port, m)
print('########## '+m+' END ###########')
if sys.argv[1] == 'all':
update_common(ip, port)
update_sentiment(ip, port)
print('(^_^) '+ str(mode) +' all ok...')
|
webshims.register('jme', function($, webshims, window, doc, undefined, options){
"use strict";
var props = {};
var fns = {};
var allowPreload = false;
$(window).on('load', function(){
allowPreload = true;
var scrollTimer;
var allow = function(){
allowPreload = true;
};
$(window).on('scroll', function(){
allowPreload = false;
clearTimeout(scrollTimer);
scrollTimer = setTimeout(allow, 999);
});
});
$.jme = {
version: '2.0.9',
classNS: '',
options: {},
plugins: {},
data: function(elem, name, value){
var data = $(elem).data(ns+'jme') || $.data(elem, ns+'jme', {});
if(value === undefined){
return (name) ? data[name] : data;
} else {
data[name] = value;
}
},
registerPlugin: function(name, plugin){
this.plugins[name] = plugin;
if(!plugin.nodeName){
plugin.nodeName = '';
}
if(!plugin.className){
plugin.className = name;
}
},
defineMethod: function(name, fn){
fns[name] = fn;
},
defineProp: function(name, desc){
if(!desc){
desc = {};
}
if(!desc.set){
if(desc.readonly){
desc.set = function(){
throw(name +' is readonly');
};
} else {
desc.set = $.noop;
}
}
if(!desc.get){
desc.get = function(elem){
return $.jme.data(elem, name);
};
}
props[name] = desc;
},
prop: function(elem, name, value){
if(!props[name]){
return $.prop(elem, name, value);
}
if(value === undefined){
return props[name].get( elem );
} else {
var setValue = props[name].set(elem, value);
if(setValue === undefined){
setValue = value;
}
if(setValue != 'noDataSet'){
$.jme.data(elem, name, setValue);
}
}
},
setText: function(name, text){
var obj = name;
if(name && text){
obj = {};
obj[name] = text;
}
$.each(obj, function(name, text){
if($.jme.plugins[name]){
$.jme.plugins[name].text = text;
}
});
}
};
$.fn.jmeProp = function(name, value){
return $.access( this, $.jme.prop, name, value, arguments.length > 1 );
};
$.fn.jmeFn = function(fn){
var args = Array.prototype.slice.call( arguments, 1 );
var ret;
this.each(function(){
ret = (fns[fn] || $.prop(this, fn)).apply(this, args);
if(ret !== undefined){
return false;
}
});
return (ret !== undefined) ? ret : this;
};
options = $.extend({selector: '.mediaplayer'}, webshims.cfg.mediaelement.jme);
webshims.cfg.mediaelement.jme = options;
var baseSelector = options.selector;
var pluginSelectors = [];
var ns = '';
$.jme.initJME = function(context, insertedElement){
$(baseSelector, context).add(insertedElement.filter(baseSelector)).jmePlayer();
};
var idlStates = {
emptied: 1,
pause: 1
};
$.jme.getDOMList = function(attr){
var list = [];
if(!attr){
attr = [];
}
if(typeof attr == 'string'){
attr = attr.split(' ');
}
$.each(attr, function(i, id){
if(id){
id = document.getElementById(id);
if(id){
list.push(id);
}
}
});
return list;
};
webshims.ready('dom-support', function(){
if($('<input />').prop('labels')){return;}
webshims.defineNodeNamesProperty('button, input, keygen, meter, output, progress, select, textarea', 'labels', {
prop: {
get: function(){
var labels = [];
var id = this.id;
if(id){
labels = $('label[for="'+ id +'"]');
}
if(!labels[0]) {
labels = $(this).closest('label', this.form);
}
return labels.get();
},
writeable: false
}
});
});
$.jme.getButtonText = function(button, classes){
var btnTextElem = $('span.jme-text, +label span.jme-text', button);
var btnLabelElem = button.prop('labels');
btnLabelElem = (btnLabelElem && btnLabelElem[0]) ? $(btnLabelElem).eq(0) : false;
if(!btnTextElem[0]){
btnTextElem = btnLabelElem || button;
}
var txt = btnTextElem.text().split('/');
var title = button.prop('title').split('/');
var isCheckbox;
var doText;
var doTitle;
var lastState;
var txtChangeFn = function(state){
if(lastState === state){return;}
lastState = state;
if(doText){
btnTextElem.text(txt[state || 0]);
}
if(doTitle){
button.prop('title', txt[state || 0]);
if (btnLabelElem) {
btnLabelElem.prop('title', txt[state || 0]);
}
}
if(classes){
button
.removeClass(classes[(state) ? 0 : 1])
.addClass(classes[state])
;
}
if(isCheckbox){
button.prop('checked', !!state);
(button.data('checkboxradio') || {refresh: $.noop}).refresh();
}
};
if(txt.length == 2){
txt[0] = txt[0].trim();
txt[1] = txt[1].trim();
doText = true;
}
if(title.length == 2){
title[0] = title[0].trim();
title[1] = title[1].trim();
doTitle = true;
}
if (button.is('[type="checkbox"], [type="radio"]')){
button.prop('checked', function(){
return this.defaultChecked;
});
isCheckbox = true;
} else if(button.is('a')){
button.on('click', function(e){
e.preventDefault();
});
}
return txtChangeFn;
};
$.fn.jmePlayer = function(opts){
return this.each(function(){
if(opts){
$.jme.data(this, $.extend(true, {}, opts));
}
var mediaUpdateFn, init, canPlay, removeCanPlay, canplayTimer, needPreload, playerSize;
var media = $('audio, video', this).filter(':first');
var base = $(this);
var jmeData = $.jme.data(this);
var mediaData = $.jme.data(media[0]);
base.addClass(media.prop('nodeName').toLowerCase()+'player');
mediaData.player = base;
mediaData.media = media;
if(!jmeData.media){
init = true;
needPreload = !media.prop('autoplay');
removeCanPlay = function(){
media.off('canplay', canPlay);
clearTimeout(canplayTimer);
};
canPlay = function(){
var state = ($.prop(this, 'paused')) ? 'idle' : 'playing';
base.attr('data-state', state);
};
mediaUpdateFn = function(e){
var state = e.type;
var readyState;
var paused;
removeCanPlay();
if(state == 'ended' || $.prop(this, 'ended')){
state = 'ended';
} else if(state == 'waiting'){
if($.prop(this, 'readyState') > 2){
state = '';
} else {
canplayTimer = setTimeout(function(){
if(media.prop('readyState') > 2){
canPlay();
}
}, 9);
media.on('canPlay', canPlay);
}
} else if(idlStates[state]){
state = 'idle';
} else {
readyState = $.prop(this, 'readyState');
paused = $.prop(this, 'paused');
if(!paused && readyState < 3){
state = 'waiting';
} else if(!paused && readyState > 2){
state = 'playing';
} else {
state = 'idle';
}
}
if(state == 'idle' && base._seekpause){
state = false;
}
if(state){
base.attr('data-state', state);
}
};
playerSize = (function(){
var lastSize;
var sizes = [
{size: 380, name: 'x-small'},
{size: 490, name: 'small'},
{size: 756, name: 'medium'},
{size: 1024, name: 'large'}
];
var len = sizes.length;
return function(){
var size = 'x-large';
var i = 0;
var width = base.outerWidth();
for(; i < len; i++){
if(sizes[i].size >= width){
size = sizes[i].name;
break;
}
}
if(lastSize != size){
lastSize = size;
base.attr('data-playersize', size);
}
};
})();
jmeData.media = media;
jmeData.player = base;
media
.on('ended', function(){
removeCanPlay();
media.jmeFn('pause');
if(!media.prop('autoplay') && !media.prop('loop') && !media.hasClass('no-reload')){
media.jmeFn('load');
}
})
.on('emptied waiting canplay canplaythrough playing ended pause mediaerror', mediaUpdateFn)
.on('volumechange updateJMEState', function(){
var volume = $.prop(this, 'volume');
base[!volume || $.prop(this, 'muted') ? 'addClass' : 'removeClass'](ns +'state-muted');
if(volume < 0.01){
volume = 'no';
} else if(volume < 0.36){
volume = 'low';
} else if(volume < 0.7){
volume = 'medium';
} else {
volume = 'high';
}
base.attr('data-volume', volume);
})
.on('emptied', function(e){
if(e.type == 'emptied'){
needPreload = !media.prop('autoplay');
}
})
;
base
.on({
useractive: function(){
base.attr('data-useractivity', 'true');
}
})
.on('userinactive', {idletime: 3500}, function(){
base.attr('data-useractivity', 'false');
})
.triggerHandler('userinactive')
;
playerSize();
webshims.ready('dom-support', function(){
base.onWSOff('updateshadowdom', playerSize);
webshims.addShadowDom();
});
if(mediaUpdateFn){
media.on('updateJMEState', mediaUpdateFn).triggerHandler('updateJMEState');
}
}
});
};
$.jme.defineProp('isPlaying', {
get: function(elem){
return (!$.prop(elem, 'ended') && !$.prop(elem, 'paused') && $.prop(elem, 'readyState') > 1 && !$.data(elem, 'mediaerror'));
},
readonly: true
});
$.jme.defineProp('player', {
readonly: true
});
$.jme.defineProp('media', {
readonly: true
});
$.jme.defineProp('srces', {
get: function(elem){
var srces;
var data = $.jme.data(elem);
var src = data.media.prop('src');
if(src){
return [{src: src}];
}
srces = $.map($('source', data.media).get(), function(source){
var src = {
src: $.prop(source, 'src')
};
var tmp = $.attr(source, 'media');
if(tmp){
src.media = tmp;
}
tmp = $.attr(source, 'type');
if(tmp){
src.type = tmp;
}
return src;
});
return srces;
},
set: function(elem, srces){
var data = $.jme.data(elem);
var setSrc = function(i, src){
if(typeof src == 'string'){
src = {src: src};
}
$(document.createElement('source')).attr(src).appendTo(data.media);
};
data.media.removeAttr('src').find('source').remove();
if($.isArray(srces)){
$.each(srces, setSrc);
} else {
setSrc(0, srces);
}
data.media.jmeFn('load');
return 'noDataSet';
}
});
$.jme.defineMethod('togglePlay', function(){
$(this).jmeFn( ( props.isPlaying.get(this) ) ? 'pause' : 'play' );
});
$.jme.defineMethod('addControls', function(controls){
var data = $.jme.data(this) || {};
if(!data.media){return;}
var oldControls = $.jme.data(data.player[0], 'controlElements') || $([]);
controls = $(controls);
$.each($.jme.plugins, function(name, plugin){
controls
.filter('.'+plugin.className)
.add(controls.find('.'+plugin.className))
.each(function(){
var control = $(this);
var options = $.jme.data(this);
options.player = data.player;
options.media = data.media;
if(options.rendered){return;}
options.rendered = true;
if(plugin.options){
$.each(plugin.options, function(option, value){
if(!(option in options)){
options[option] = value;
}
});
}
plugin._create(control, data.media, data.player, options);
control = null;
})
;
});
$.jme.data(data.player[0], 'controlElements', oldControls.add(controls));
data.player.triggerHandler('controlsadded');
});
(function(){
var activity = {
add: function(elem, cfg, name){
var data = $.data(elem, 'jmeuseractivity') || $.data(elem, 'jmeuseractivity', {idletime: 2500, idle: true, trigger: {}}),
jElm = $(elem),
setInactive = function(){
if(!data.idle){
data.idle = true;
if ( data.trigger.userinactive ) {
jElm.trigger('userinactive');
}
}
},
x, y,
setActive = function(e){
if(!e || (e.type === 'mousemove' && e.pageX === x && e.pageY === y)){return;}
if(e.type === 'mousemove'){
x = e.pageX;
y = e.pageY;
}
if(data.idleTimer){
clearTimeout(data.idleTimer);
}
data.idleTimer = setTimeout(setInactive, data.idletime);
if(data.idle){
data.idle = false;
if( data.trigger.useractive ){
jElm.trigger('useractive');
}
}
}
;
data.idletime = (cfg || {}).idletime || data.idletime;
if(cfg && 'idle' in cfg){
data.idle = cfg.idle;
}
data.trigger[name] = true;
if(!data.bound){
jElm
.on('mouseleave.jmeuseractivity', setInactive)
.on('mousemove.jmeuseractivity focusin.jmeuseractivity mouseenter.jmeuseractivity keydown.jmeuseractivity keyup.jmeuseractivity mousedown.jmeuseractivity', setActive)
;
data.bound = true;
}
if(!data.idle){
setActive({type: 'initunidled'});
}
},
remove: function(elem, name){
var data = $.data(elem, 'jmeuseractivity') || $.data(elem, 'jmeuseractivity', {idletime: 2500, idle: true, trigger: {}});
data.trigger[name] = false;
if(!data.trigger.useractive && !data.trigger.userinactive){
$(elem).off('.jmeuseractivity');
data.bound = false;
}
}
};
$.each(['useractive', 'userinactive'], function(i, name){
$.event.special[name] = {
setup: function(cfg){
activity.add(this, cfg, name);
},
teardown: function(){
activity.remove(this, name);
}
};
});
})();
webshims.ready('mediaelement', function(){
webshims.addReady($.jme.initJME);
});
});
;webshims.register('mediacontrols', function($, webshims, window, doc, undefined, options){
"use strict";
var pseudoClasses = 'pseudoClasses';
var baseSelector = webshims.cfg.mediaelement.jme.selector;
var playStates = {
play: 1,
playing: 1
};
var pauseStates = {
pause: 1,
ended: 1
};
var loadRange = function(){
webshims.loader.loadList(['range-ui']);
};
var onSliderReady = function(fn){
loadRange();
webshims.ready('range-ui', fn);
};
var btnStructure = '<button class="{%class%}" type="button" aria-label="{%text%}"></button>';
var defaultStructure = '<div class="{%class%}"></div>';
var slideStructure = '<div class="{%class%}"></div>';
var ns = $.jme.classNS;
var noVolumeClass = (function(){
var audio;
var ret = '';
if(typeof window.Audio == 'function'){
audio = new Audio();
audio.volume = 0.55;
ret = audio.volume = 0.55 ? '' : ' no-volume-api';
}
return ret;
})();
$.jme.defineProp('controlbar', {
set: function(elem, value){
value = !!value;
var data = $.jme.data(elem);
var controlBar = $('div.jme-mediaoverlay, div.jme-controlbar', data.player);
var mediaControls = $.jme.plugins["media-controls"] ;
var structure = '';
var controls;
if(value && !controlBar[0]){
if(data._controlbar){
data._controlbar.appendTo(data.player);
} else {
data.media.prop('controls', false);
$.each(mediaControls.pluginOrder, function(i, name){
var plugin = $.jme.plugins[name];
if(plugin && plugin.structure){
structure += plugin.structure.replace('{%class%}', ns+name).replace('{%text%}', plugin.text || '');
} else if(name){
structure += name;
}
});
data._controlbar = $( mediaControls.barStructure );
controlBar = data._controlbar.find('div.jme-cb-box').addClass(ns+'media-controls');
controls = data._controlbar.filter('.jme-media-overlay').addClass(ns+'play-pause');
controls = controls.add( controlBar );
controls = controls.add( $(structure).appendTo(controlBar) );
data._controlbar.appendTo(data.player);
data.player.jmeFn('addControls', controls);
}
} else if(!value) {
controlBar.detach();
}
controlBar = null;
controls = null;
return value;
}
});
$.jme.defineMethod('updateControlbar', function(){
var timeSlider = $('.'+ $.jme.classNS +'time-slider', this);
if(timeSlider[0] && timeSlider.css('position') !== 'absolute'){
var width;
var elemWidths = 0;
width = Math.floor(timeSlider.parent().width()) - 0.2;
timeSlider
.siblings()
.each(function(){
if(this !== timeSlider[0] && $.css(this, 'position') !== 'absolute' && $.css(this, 'display') !== 'none'){
elemWidths += Math.ceil($(this).outerWidth(true)) + 0.1;
}
})
;
timeSlider.width(Math.floor(width - elemWidths - Math.ceil(timeSlider.outerWidth(true) - timeSlider.width()) - 0.3));
}
});
$.jme.registerPlugin('media-controls', {
options: {
calculateTimerange: false
},
pluginOrder: ['<div class="play-pause-container">', 'play-pause', '</div>', '<div class="currenttime-container">', 'currenttime-display', '</div>', '<div class="progress-container">', 'time-slider', '</div>', '<div class="duration-container">', 'duration-display', '</div>', '<div class="mute-container">', 'mute-unmute', '</div>', '<div class="volume-container">', 'volume-slider', '</div>', '<div class="subtitle-container">', '<div class="subtitle-controls">', 'captions', '</div>', '</div>', '<div class="fullscreen-container">', 'fullscreen', '</div>'],
barStructure: '<div class="jme-media-overlay"></div><div class="jme-controlbar'+ noVolumeClass +'" tabindex="-1"><div class="jme-cb-box"></div></div>',
_create: function(control, media, base, options){
var timer;
var update = function(){
clearTimeout(timer);
control.jmeFn('updateControlbar');
timer = setTimeout(function(){
control.jmeFn('updateControlbar');
}, 9);
};
if(options.calculateTimerange){
setTimeout(function(){
media.on('loadedmetadata volumechange play pause ended emptied', update);
base.on('updatetimeformat controlsadded controlschanged playerdimensionchange', update);
$(window).on('resize emchange', update);
}, 1);
update();
}
}
});
$.jme.registerPlugin('play-pause', {
pseudoClasses: {
play: 'state-paused',
pause: 'state-playing'
},
structure: btnStructure,
text: 'play / pause',
_create: function(control, media){
var textFn = $.jme.getButtonText(control, [this[pseudoClasses].play, this[pseudoClasses].pause]);
media
.on('play playing ended pause updateJMEState', function(e){
var state = e.type;
if(playStates[state]){
state = 1;
} else if(pauseStates[state]) {
state = 0;
} else {
state = (media.jmeProp('isPlaying') )? 1 : 0;
}
textFn(state);
})
.triggerHandler('updateJMEState')
;
control.on((control.is('select')) ? 'change' : 'click', function(e){
media.jmeFn('togglePlay');
e.stopPropagation();
});
}
});
$.jme.registerPlugin('mute-unmute', {
pseudoClasses: {
mute: 'state-mute',
unmute: 'state-unmute'
},
structure: btnStructure,
text: 'mute / unmute',
_create: function(control, media, base){
var textFn = $.jme.getButtonText(control, [this[pseudoClasses].mute, this[pseudoClasses].unmute]);
media
.on('volumechange updateJMEState', function(e){
textFn(media.prop('muted') ? 1 : 0);
})
.triggerHandler('updateJMEState')
;
control.on((control.is('select')) ? 'change' : 'click', function(e){
media.prop('muted', !media.prop('muted'));
e.stopPropagation();
});
}
});
function createGetSetHandler(fns){
var throttleTimer;
var blocked;
if(fns.release === true){
fns.release = fns.set;
}
var getSetHelper = {
start: function(){
if(!blocked){
blocked = true;
if(fns.start){
fns.start();
}
}
},
release: function(){
if(blocked){
blocked = false;
if(fns.release){
fns.release();
}
}
},
get: function(){
if(blocked){return;}
return fns.get.apply(this, arguments);
},
set: function(){
var that = this;
var args = arguments;
getSetHelper.start();
clearTimeout(throttleTimer);
throttleTimer = setTimeout(function(){
fns.set.apply(that, args);
}, 33);
}
};
getSetHelper.fns = fns;
return getSetHelper;
}
$.jme.registerPlugin('volume-slider', {
structure: slideStructure,
_create: function(control, media, base){
var createFn = function(){
var api, volume;
volume = createGetSetHandler({
get: function(){
var volume = media.prop('volume');
if(volume !== undefined){
api.value(volume);
}
},
set: function(){
media.prop({
muted: false,
volume: api.options.value
});
},
release: true
});
api = control
.rangeUI({
min: 0,
max: 1,
//animate: true,
step: 'any',
input: volume.set,
change: volume.release,
baseClass: 'media-range'
})
.data('rangeUi')
;
media.on('volumechange', volume.get);
};
onSliderReady(createFn);
}
});
$.jme.registerPlugin('time-slider', {
structure: slideStructure,
pseudoClasses: {
no: 'no-duration'
},
options: {
format: ['mm', 'ss']
},
_create: function(control, media, base){
var module = this;
var createFn = function(){
var time, durationChange, api, timeShow, wasPaused;
var hasDuration = $.jme.classNS+'has-duration';
var duration = media.prop('duration');
time = createGetSetHandler({
get: function(){
var time = media.prop('currentTime');
if(!isNaN(time)){
try {
api.value(time);
} catch(er){}
}
},
set: function(){
try {
media.prop('currentTime', api.options.value).triggerHandler('timechanged', [api.options.value]);
} catch(er){}
},
start: function(){
if(wasPaused == null){
wasPaused = media.prop('paused');
if(!wasPaused){
base._seekpause = true;
media.pause();
} else {
base._seekpause = false;
}
}
},
release: function(){
time.fns.set();
if(wasPaused === false){
media.play();
}
if('_seekpause' in base){
delete base._seekpause;
}
wasPaused = null;
}
});
durationChange = function(){
duration = media.prop('duration');
hasDuration = duration && isFinite(duration) && !isNaN(duration);
if(hasDuration){
api.disabled(false);
api.max(duration);
base.removeClass(module[pseudoClasses].no);
} else {
api.disabled(true);
api.max(Number.MAX_VALUE);
base.addClass(module[pseudoClasses].no);
}
};
api = control
.rangeUI({
min: 0,
value: media.prop('currentTime') || 0,
step: 'any',
input: time.set,
change: time.release,
textValue: function(val){
return media.jmeFn('formatTime', val);
},
baseClass: 'media-range'
})
.data('rangeUi')
;
timeShow = $('<span class="'+ $.jme.classNS +'time-select" />').appendTo(control);
control
.on({
'mouseenter': function(e){
if(hasDuration){
var widgetLeft = (control.offset() || {left: 0}).left;
var widgetWidth = control.innerWidth();
var posLeft = function(x){
var perc = (x - widgetLeft) / widgetWidth * 100;
timeShow
.html(media.jmeFn('formatTime', duration * perc / 100))
.css({left: perc+'%'})
;
};
posLeft(e.pageX);
timeShow.addClass($.jme.classNS +'show-time-select');
control
.off('.jmetimeselect')
.on('mousemove.jmetimeselect', function(e){
posLeft(e.pageX);
})
;
}
},
mouseleave: function(){
timeShow.removeClass($.jme.classNS +'show-time-select');
control.off('.jmetimeselect');
}
})
;
media.on({
timeupdate: time.get,
emptied: function(){
durationChange();
api.value(0);
},
durationchange: durationChange
});
base.jmeFn('addControls', $('<div class="'+ $.jme.classNS +'buffer-progress" />').prependTo(control) );
durationChange();
};
onSliderReady(createFn);
}
});
$.jme.defineMethod('concerningRange', function(type, time){
var elem = this;
var ret = {start: 0, end: 0};
if(!type){
type = 'buffered';
}
type = $.prop(elem, type);
if(time == null){
time = $.prop(elem, 'currentTime');
}
if(!type || !('length' in type)){return ret;}
for(var i = 0, len = type.length; i < len; i++){
ret.start = type.start(i);
ret.end = type.end(i);
if(ret.start <= time && ret.end >= time){
break;
}
}
return ret;
});
$.jme.defineProp('progress', {
get: function(elem){
var data = $.jme.data(elem);
if(!data.media){return 0;}
var progress = data.media.jmeFn('concerningRange').end / data.media.prop('duration') * 100;
if(progress > 99.4){
progress = 100;
}
return progress || 0;
},
readonly: true
});
$.jme.registerPlugin('buffer-progress', {
_create: function(control, media, base, options){
var indicator = $('<div class="'+ $.jme.classNS +'buffer-progress-indicator" />').appendTo(control);
var drawBufferProgress = function(){
var progress = media.jmeProp('progress');
if(options.progress !== progress){
options.progress = progress;
indicator.css('width', progress +'%');
}
};
media.on({
progress: drawBufferProgress,
emptied: function(){
indicator.css('width', 0);
options.progress = 0;
},
playing: drawBufferProgress
});
drawBufferProgress();
}
});
var times = {
hh: 60000,
mm: 60,
ss: 1,
ms: 1/1000
};
var formatTime = function(sec, format){
var data;
if(!format){
format = ['mm', 'ss'];
}
if(sec == null){
data = $.jme.data(this);
sec = $.prop(data.media, 'duration');
}
if(!sec){
sec = 0;
}
var formated = [];
var frac;
for(var i = 0, len = format.length; i < len; i++){
if(format[i] == 'ms' && i == len -1 ){
frac = Math.round( (sec / times[format[i]]) / 10);
} else {
frac = parseInt(sec / times[format[i]], 10);
sec = sec % times[format[i]];
}
if(frac < 10){
frac = '0'+frac;
}
formated.push( frac );
}
return formated.join(':');
};
$.jme.defineMethod('formatTime', formatTime);
$.jme.defineProp('format', {
set: function(elem, format){
if(!$.isArray(format)){
format = format.split(':');
}
var data = $.jme.data(elem);
data.format = format;
$(elem).triggerHandler('updatetimeformat');
data.player.triggerHandler('updatetimeformat');
return 'noDataSet';
}
});
$.jme.registerPlugin('duration-display', {
structure: defaultStructure,
options: {
format: "mm:ss"
},
_create: function(control, media, base, options){
if(typeof options.format == 'string'){
options.format = options.format.split(':');
}
var showDuration = function(){
control.html(formatTime(media.prop('duration'), options.format));
};
media.on('durationchange emptied', showDuration);
control
.on('updatetimeformat', showDuration)
.jmeProp('format', options.format)
;
}
});
$.jme.defineProp('countdown', {
set: function(elem, value){
var data = $.jme.data(elem);
data.countdown = !!value;
$(elem).triggerHandler('updatetimeformat');
data.player.triggerHandler('updatetimeformat');
return 'noDataSet';
}
});
$.jme.registerPlugin('currenttime-display', {
structure: defaultStructure,
options: {
format: "mm:ss",
countdown: false
},
_create: function(control, media, base, options){
if(typeof options.format == 'string'){
options.format = options.format.split(':');
}
var showTime = function(e){
var currentTime = media.prop('currentTime');
if(options.countdown){
currentTime = (media.prop('duration') || 0) - currentTime;
if(currentTime < 0.7){
currentTime = 0;
}
}
control.html(formatTime(currentTime, options.format));
};
media.on('timeupdate emptied durationchange', showTime);
control
.on('updatetimeformat', showTime)
.jmeProp('format', options.format)
;
}
});
/**
* Added Poster Plugin
* @author mderting
*/
/*
* the old technique wasn't fully bullet proof
* beside this, jme2 adovactes to use the new improved state-classes to handle visual effect on specific state (see CSS change)
*/
$.jme.registerPlugin('poster-display', {
structure: '<div />',
options: {
},
_create: function(control, media, base, options){
/* Empty span element used for vertical centering in IE7 - thanks to Bruno Fassino.
* @see http://www.brunildo.org/test/img_center.html
*/
var updatePoster = function(){
var poster = media.prop('poster');
if(poster){
control.html('<span></span><img src="'+ poster +'" class="'+ $.jme.classNS +'poster-image" />');
} else {
control.empty();
}
};
media.on('emptied', updatePoster);
updatePoster();
}
});
//taken from http://johndyer.name/native-fullscreen-javascript-api-plus-jquery-plugin/
$.jme.fullscreen = (function() {
var parentData;
var frameData;
var doc = document.documentElement;
var fullScreenApi = {
supportsFullScreen: Modernizr.prefixed('fullscreenEnabled', document, false) || Modernizr.prefixed('fullScreenEnabled', document, false),
isFullScreen: function() { return false; },
requestFullScreen: function(elem){
var tmpData;
parentData = [];
$(elem).parentsUntil('body').each(function(){
var pos = $.css(this, 'position');
var left = this.scrollLeft;
var top = this.scrollTop;
var changed;
tmpData = {elemStyle: this.style, elem: this};
if(pos !== 'static'){
changed = true;
tmpData.pos = tmpData.elemStyle.position;
this.style.position = 'static';
}
if(left){
changed = true;
tmpData.left = left;
}
if(top){
changed = true;
tmpData.top = top;
}
if(changed){
parentData.push(tmpData);
}
});
frameData = false;
try {
frameData = {elemStyle: frameElement.style, elem: frameElement, css: {}};
frameData.css.position = frameData.elemStyle.position;
frameData.elemStyle.position = 'fixed';
$.each(['top', 'left', 'right', 'bottom'], function(i, name){
frameData.css[name] = frameData.elemStyle[name];
frameData.elemStyle[name] = '0px';
});
$.each(['height', 'width'], function(i, name){
frameData.css[name] = frameData.elemStyle[name];
frameData.elemStyle[name] = '100%';
});
} catch(er){
frameData = false;
}
tmpData = null;
},
cancelFullScreen: function(){
if(parentData){
$.each(parentData, function(i, data){
if('pos' in data){
data.elemStyle.position = data.pos;
}
if(data.left){
data.elem.scrollLeft = data.left;
}
if(data.top){
data.elem.scrollTop = data.top;
}
data = null;
});
parentData = [];
}
if(frameData){
$.each(frameData.css, function(name, value){
frameData.elemStyle[name] = value;
});
frameData = false;
}
},
eventName: 'fullscreenchange',
exitName: 'exitFullscreen',
requestName: 'requestFullscreen',
elementName: 'fullscreenElement',
enabledName: ''
};
fullScreenApi.cancelFullWindow = fullScreenApi.cancelFullScreen;
fullScreenApi.requestFullWindow = fullScreenApi.requestFullScreen;
// update methods to do something useful
if (fullScreenApi.supportsFullScreen) {
fullScreenApi.enabledName = fullScreenApi.supportsFullScreen;
fullScreenApi.exitName = Modernizr.prefixed("exitFullscreen", document, false) || Modernizr.prefixed("cancelFullScreen", document, false);
fullScreenApi.elementName = Modernizr.prefixed("fullscreenElement", document, false) || Modernizr.prefixed("fullScreenElement", document, false);
fullScreenApi.supportsFullScreen = !!fullScreenApi.supportsFullScreen;
if(fullScreenApi.elementName != 'fullscreenElement' || fullScreenApi.exitName != 'exitFullscreen' || fullScreenApi.enabledName != 'fullscreenEnabled'){
$.each(Modernizr._domPrefixes, function(i, prefix){
var requestName = prefix+'RequestFullscreen';
if((requestName in doc) || ((requestName = prefix+'RequestFullScreen') && (requestName in doc))){
fullScreenApi.eventName = prefix + 'fullscreenchange';
fullScreenApi.requestName = requestName;
return false;
}
});
}
fullScreenApi.isFullScreen = function() {
return document[fullScreenApi.elementName];
};
fullScreenApi.requestFullScreen = function(el) {
return el[fullScreenApi.requestName]();
};
fullScreenApi.cancelFullScreen = function() {
return document[fullScreenApi.exitName]();
};
}
if(!window.Modernizr || !('fullscreen' in Modernizr)){
$('html').addClass(fullScreenApi.supportsFullScreen ? 'fullscreen' : 'no-fullscreen');
}
if(window.parent != window){
(function(){
try{
var frame = window.frameElement;
if (fullScreenApi.supportsFullScreen) {
if('allowfullscreen' in frame && !frame.allowfullscreen) {
frame.allowfullscreen = true;
} else {
if(frame.getAttribute('webkitallowfullscreen') == null){
frame.setAttribute('webkitallowfullscreen', '');
}
if(frame.getAttribute('allowfullscreen') == null){
frame.setAttribute('allowfullscreen', 'allowfullscreen');
}
}
}
} catch(er){
if(!fullScreenApi.supportsFullScreen){
$('html').addClass('no-fullwindow');
}
}
})();
}
return fullScreenApi;
})();
$.jme.defineProp('fullscreen', {
set: function(elem, value){
var data = $.jme.data(elem);
if((!data || !data.player) && !$(elem).hasClass($.jme.classNS+'player-fullscreen')){return 'noDataSet';}
if(value){
if(data.player.hasClass($.jme.classNS+'player-fullscreen')){return 'noDataSet';}
data.scrollPos = {
top: $(window).scrollTop(),
left: $(window).scrollLeft()
};
$(document)
.off('.jmefullscreen')
.on('keydown.jmefullscreen', function(e){
if(e.keyCode == 27){
data.player.jmeProp('fullscreen', false);
return false;
}
if(e.keyCode === 32 && !('form' in e.target)){
data.media.jmeFn('togglePlay');
return false;
}
})
;
if(value == 'fullwindow'){
$.jme.fullscreen.requestFullWindow(data.player[0]);
} else {
try {
$.jme.fullscreen.requestFullScreen(data.player[0]);
} catch(er){}
}
$('html').addClass($.jme.classNS+'has-media-fullscreen');
data.player.addClass($.jme.classNS+'player-fullscreen');
data.media.addClass($.jme.classNS+'media-fullscreen');
$('button.play-pause', data.player).focus();
if($.jme.fullscreen.supportsFullScreen){
$(document)
.on($.jme.fullscreen.eventName+'.jmefullscreen', function(e){
var fullScreenElem = $.jme.fullscreen.isFullScreen();
if(fullScreenElem && elem == fullScreenElem){
data.media.trigger('playerdimensionchange', ['fullscreen']);
} else {
data.player.jmeProp('fullscreen', false);
}
})
;
}
data.media.trigger('playerdimensionchange', ['fullwindow']);
} else {
if(data.player && !data.player.hasClass($.jme.classNS+'player-fullscreen')){return 'noDataSet';}
$(document).off('.jmefullscreen');
$('html').removeClass($.jme.classNS+'has-media-fullscreen');
if(data.player && data.media){
data.player.removeClass($.jme.classNS+'player-fullscreen');
data.media.removeClass($.jme.classNS+'media-fullscreen');
}
if($.jme.fullscreen.isFullScreen()){
try {
$.jme.fullscreen.cancelFullScreen();
} catch(er){}
} else {
$.jme.fullscreen.cancelFullWindow();
}
if(data.scrollPos){
$(window).scrollTop(data.scrollPos.top);
$(window).scrollLeft(data.scrollPos.left);
delete data.scrollPos;
}
if(data.media){
data.media.trigger('playerdimensionchange');
}
}
return 'noDataSet';
},
get: function(elem){
var data = $.jme.data(elem);
if(!data || !data.player){return;}
var fs = data.player.hasClass($.jme.classNS+'player-fullscreen');
if(!fs){return false;}
return $.jme.fullscreen.isFullScreen() || 'fullwindow';
}
});
$.jme.defineProp('autoplayfs');
$.jme.registerPlugin('fullscreen', {
pseudoClasses: {
enter: 'state-enterfullscreen',
exit: 'state-exitfullscreen'
},
options: {
fullscreen: true,
autoplayfs: false
},
structure: btnStructure,
text: 'enter fullscreen / exit fullscreen',
_create: function(control, media, base){
var textFn = $.jme.getButtonText(control, [this[pseudoClasses].enter, this[pseudoClasses].exit]);
var updateControl = function(){
textFn(base.hasClass($.jme.classNS+'player-fullscreen') ? 1 : 0);
};
var options = this.options;
var addDoubbleClick = function(){
$(base.data('jme').controlElements)
.filter('.jme-media-overlay')
.off('.dblfullscreen')
.on('dblclick.dblfullscreen', function(e){
base.jmeProp('fullscreen', !base.jmeProp('fullscreen'));
})
;
};
base.on('controlsadded', addDoubbleClick);
base.on('playerdimensionchange', updateControl);
control.on((control.is('select')) ? 'change' : 'click', function(){
var value = base.hasClass($.jme.classNS+'player-fullscreen') ? false : options.fullscreen;
base.jmeProp('fullscreen', value);
if(value && options.autoplayfs){
media.jmeFn('play');
}
});
addDoubbleClick();
updateControl();
}
});
$.jme.ButtonMenu = function(button, menu, clickHandler){
this.button = $(button).attr({'aria-haspopup': 'true'});
this.clickHandler = clickHandler;
this.toggle = $.proxy(this, 'toggle');
this.keyIndex = $.proxy(this, 'keyIndex');
this._buttonClick = $.proxy(this, '_buttonClick');
this.addMenu(menu);
this._closeFocusOut();
this.button.on('click', this.toggle);
};
$.jme.ButtonMenu.prototype = {
addMenu: function(menu){
if(this.menu){
this.menu.remove();
}
this.menu = $(menu);
this.buttons = $('button', this.menu);
this.menu.insertAfter(this.button);
this.menu
.on('keydown', this.keyIndex)
.delegate('button', 'click', this._buttonClick)
;
},
_closeFocusOut: function(){
var that = this;
var timer;
var stopFocusOut = function(){
clearTimeout(timer);
setTimeout(function(){
clearTimeout(timer);
}, 9);
};
this.menu
.parent()
.on('focusin', stopFocusOut)
.on('mousedown', stopFocusOut)
.on('focusout', function(e){
timer = setTimeout(function(){
that.hide();
}, 40);
})
;
},
_buttonClick: function(e){
this.clickHandler(this.buttons.index(e.currentTarget), e.currentTarget);
this.hide();
},
keyIndex: function(e){
var dir = (e.keyCode == 40) ? 1 : (e.keyCode == 38) ? -1 : 0;
if(dir){
var buttons = this.buttons.not(':disabled');
var activeButton = buttons.filter(':focus');
activeButton = buttons[buttons.index(activeButton) + dir] || buttons.filter(dir > 0 ? ':first' : ':last');
activeButton.focus();
e.preventDefault();
}
},
show: function(){
if(this.isVisible){return;}
var buttons = this.buttons.not(':disabled');
this.isVisible = true;
this.menu.addClass('visible-menu');
try {
this.activeElement = document.activeElement || this.button[0];
} catch(er){
this.activeElement = this.button[0];
}
setTimeout(function(){
$(buttons.filter('[aria-checked="true"]')[0] || buttons[0]).focus();
}, 60);
},
toggle: function(){
this[this.isVisible ? 'hide' : 'show']();
},
hide: function(){
if(!this.isVisible){return;}
this.isVisible = false;
this.menu.removeClass('visible-menu');
if(this.activeElement){
try {
this.activeElement.focus();
} catch(er){}
}
this.activeElement = false;
}
};
var showKinds = {subtitles: 1, caption: 1};
var getTrackMenu = function(tracks){
var items = $.map(tracks, function(track){
var className = (track.kind == 'caption') ? 'caption-type' : 'subtitle-type';
var lang = track.language;
lang = (lang) ? ' <span class="track-lang">'+ lang +'</span>' : '';
return '<li class="'+ className +'" role="presentation"><button role="menuitemcheckbox">'+ track.label + lang +'</button></li>';
})
;
return '<div><ul>' + items.join('') +'</ul></div>';
};
$.jme.registerPlugin('captions', {
pseudoClasses: {
menu: 'subtitle-menu'
},
structure: btnStructure,
text: 'subtitles',
_create: function(control, media, base, options){
var that = this;
var trackElems = media.find('track');
var checkbox = $(control).clone().attr({role: 'checkbox'}).insertBefore(control);
base.attr('data-tracks', trackElems.length > 1 ? 'many' : trackElems.length);
control.attr('aria-haspopup', 'true');
webshims.ready('track', function(){
var menuObj, throttledUpdateMode;
var tracks = [];
var textTracks = media.prop('textTracks');
var throttledUpdate = (function(){
var timer;
var triggerTimer;
return function(e){
clearTimeout(timer);
clearTimeout(triggerTimer);
if(e.type == 'updatesubtitlestate'){
triggerTimer = setTimeout(function(){
media.trigger('updatetracklist');
}, 0);
}
timer = setTimeout(updateTrackMenu, 19);
};
})();
function createSubtitleMenu(menu){
var menuClick;
if(!menuObj){
menuClick = function(index, button){
if($.attr(button, 'aria-checked') == 'true'){
tracks[index].mode = 'disabled';
} else {
$.each(tracks, function(i, track){
track.mode = (i == index) ? 'showing' : 'disabled';
});
}
media.prop('textTracks');
updateMode();
};
menuObj = new $.jme.ButtonMenu(control, menu, menuClick);
checkbox.on('click', function(){
menuClick(0, this);
return false;
});
} else {
menuObj.addMenu(menu);
}
updateMode();
}
function updateMode(){
$('button', menuObj.menu).each(function(i){
var checked = (tracks[i].mode == 'showing') ? 'true' : 'false';
if(!i){
checkbox.attr('aria-checked', checked);
}
$.attr(this, 'aria-checked', checked);
});
}
function updateTrackMenu(){
tracks = [];
$.each(textTracks, function(i, track){
if(showKinds[track.kind] && track.readyState != 3){
tracks.push(track);
}
});
base.attr('data-tracks', tracks.length > 1 ? 'many' : tracks.length);
if(tracks.length){
createSubtitleMenu('<div class="'+that[pseudoClasses].menu +'" >'+ (getTrackMenu(tracks)) +'</div>');
$('span.jme-text, +label span.jme-text', checkbox).text((tracks[0].label || ' ') + (tracks[0].lang || ''));
if(!base.hasClass(that[pseudoClasses].hasTrack) || base.hasClass(that[pseudoClasses].noTrack)){
control.prop('disabled', false);
base.triggerHandler('controlschanged');
}
} else if(!base.hasClass(that[pseudoClasses].noTrack) || base.hasClass(that[pseudoClasses].hasTrack)){
control.prop('disabled', true);
base
.triggerHandler('controlschanged')
;
}
}
if(!textTracks){
textTracks = [];
updateTrackMenu();
} else {
throttledUpdateMode = (function(){
var timer;
return function(){
clearTimeout(timer);
timer = setTimeout(updateMode, 20);
};
})();
updateTrackMenu();
$([textTracks])
.on('addtrack removetrack', throttledUpdate)
.on('change', throttledUpdateMode)
;
base.on('updatesubtitlestate', throttledUpdate);
media.on('updatetrackdisplay', throttledUpdateMode);
}
});
}
});
$('.mediaplayer').each(function(){
if(($.data(this, 'jme')|| {}).controlbar){
$(this).jmeProp('controlbar', true);
}
});
webshims.ready('mediaelement', function(){
webshims.addReady(function(context, insertedElement){
$(baseSelector, context).add(insertedElement.filter(baseSelector)).jmeProp('controlbar', true);
});
});
webshims.ready('WINDOWLOAD', loadRange);
});
|
module.exports = function (api) {
api.cache(true);
return {
presets: ['babel-preset-expo'],
plugins: [
[
'module-resolver',
{
alias: {
'@react/cross-core': './_CrossBasement/CrossCore',
'@react/cross-page': './_CrossBasement/CrossPage',
},
},
],
require.resolve('react-native-reanimated/plugin'),
],
};
};
|
#!/usr/bin/env python
from setuptools import setup, find_packages
setup(
name = "ttr",
version = "0.1.1",
packages = find_packages(),
# metadata for upload to PyPI
author = "Andrey Volkov",
author_email = "amadev@mail.ru",
description = "Turbo test runner",
license = "MIT",
keywords = "test runner",
url = "https://github.com/amadev/ttr",
install_requires=[
'inotify',
'mock',
'extras',
'testtools'
],
classifiers=[
'Development Status :: 3 - Alpha',
'Environment :: Console',
'Intended Audience :: Developers',
'Intended Audience :: System Administrators',
'License :: OSI Approved :: MIT License',
'Operating System :: POSIX :: Linux',
'Programming Language :: Python :: 3',
'Topic :: Utilities'
],
scripts=['bin/ttr-start', 'bin/ttr'],
)
|
const Scene = require('../../scene');
const PromiseCondition = require('../../promise-condition');const CapitalOneJustClickAwareScene = require('./just-click-aware-scene');
class CapitalOneCreditWiseOpenAccountsScene extends CapitalOneJustClickAwareScene.WithSpinner {
constructor(args) {
super(Object.assign({
elementQueries: {
creditImpactHeader: {
selector: 'div.fcr-summary-view > accounts-list-component:nth-of-type(1) > div.fcr-view-wrapper > div.credit-report-list-header > h2',
match: e => /Open Accounts/.test(e.innerText),
},
accountsAndBalancesDetails: {
selector: '#credit-report-details-ui-view > accounts-and-balances-details-component > div',
visibility: 'optional',
},
},
extensions: [
new Scene.Extensions.Delay(12000),
],
}, args));
}
async match() {
return PromiseCondition.and(super.match());
}
async play() {
await super.play();
const accountsAndBalancesDetails = await this.elements.accountsAndBalancesDetails.innerText();
if (accountsAndBalancesDetails) {
this.log('Found open accounts: ', accountsAndBalancesDetails);
this.setContext('creditAccounts', accountsAndBalancesDetails);
}
const creditScore = await this.elements.creditScore.innerText();
if (creditScore) {
this.log('Found credit score: ', creditScore);
this.setContext('score', +creditScore);
}
await this.elements.summaryNavReport.click();
}
}
module.exports = CapitalOneCreditWiseOpenAccountsScene;
|
'''
Inspector
=========
.. versionadded:: 1.0.9
.. warning::
This module is highly experimental, use it with care.
The Inspector is a tool for finding a widget in the widget tree by clicking or
tapping on it.
Some keyboard shortcuts are activated:
* "Ctrl + e": activate / deactivate the inspector view
* "Escape": cancel widget lookup first, then hide the inspector view
Available inspector interactions:
* tap once on a widget to select it without leaving inspect mode
* double tap on a widget to select and leave inspect mode (then you can
manipulate the widget again)
Some properties can be edited live. However, due to the delayed usage of
some properties, it might crash if you don't handle all the cases.
Usage
-----
For normal module usage, please see the :mod:`~kivy.modules` documentation.
The Inspector, however, can also be imported and used just like a normal
python module. This has the added advantage of being able to activate and
deactivate the module programmatically::
from kivy.core.window import Window
from kivy.app import App
from kivy.uix.button import Button
from kivy.modules import inspector
class Demo(App):
def build(self):
button = Button(text="Test")
inspector.create_inspector(Window, button)
return button
Demo().run()
To remove the Inspector, you can do the following::
inspector.stop(Window, button)
'''
__all__ = ('start', 'stop', 'create_inspector')
import kivy
kivy.require('1.0.9')
import weakref
from functools import partial
from itertools import chain
from kivy.animation import Animation
from kivy.logger import Logger
from kivy.uix.widget import Widget
from kivy.uix.button import Button
from kivy.uix.label import Label
from kivy.uix.togglebutton import ToggleButton
from kivy.uix.textinput import TextInput
from kivy.uix.image import Image
from kivy.uix.treeview import TreeViewNode, TreeView
from kivy.uix.gridlayout import GridLayout
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.modalview import ModalView
from kivy.graphics import Color, Rectangle, PushMatrix, PopMatrix
from kivy.graphics.context_instructions import Transform
from kivy.graphics.transformation import Matrix
from kivy.properties import ObjectProperty, BooleanProperty, ListProperty, \
NumericProperty, StringProperty, OptionProperty, \
ReferenceListProperty, AliasProperty, VariableListProperty
from kivy.graphics.texture import Texture
from kivy.clock import Clock
from kivy.lang import Builder
Builder.load_string('''
<Inspector>:
layout: layout
widgettree: widgettree
treeview: treeview
content: content
BoxLayout:
orientation: 'vertical'
id: layout
size_hint_y: None
height: 250
padding: 5
spacing: 5
top: 0
canvas:
Color:
rgb: .4, .4, .4
Rectangle:
pos: self.x, self.top
size: self.width, 1
Color:
rgba: .185, .18, .18, .95
Rectangle:
pos: self.pos
size: self.size
# Top Bar
BoxLayout:
size_hint_y: None
height: 50
spacing: 5
Button:
text: 'Move to Top'
on_release: root.toggle_position(args[0])
size_hint_x: None
width: 120
ToggleButton:
text: 'Inspect'
on_state: root.inspect_enabled = args[1] == 'down'
size_hint_x: None
state: 'down' if root.inspect_enabled else 'normal'
width: 80
Button:
text: 'Parent'
on_release:
root.highlight_widget(root.widget.parent) if root.widget \
else None
size_hint_x: None
width: 80
Button:
text: '%r' % root.widget
on_release: root.show_widget_info()
Button:
text: 'X'
size_hint_x: None
width: 50
on_release: root.activated = False
# Bottom Bar
BoxLayout:
ScrollView:
scroll_type: ['bars', 'content']
bar_width: 10
size_hint_x: 0.0001
WidgetTree:
id: widgettree
hide_root: True
size_hint: None, None
height: self.minimum_height
width: max(self.parent.width, self.minimum_width)
selected_widget: root.widget
on_select_widget: root.highlight_widget(args[1])
Splitter:
sizeable_from: 'left'
min_size: self.parent.width / 2
max_size: self.parent.width
BoxLayout:
ScrollView:
scroll_type: ['bars', 'content']
bar_width: 10
TreeView:
id: treeview
size_hint_y: None
hide_root: True
height: self.minimum_height
Splitter:
sizeable_from: 'left'
keep_within_parent: True
rescale_with_parent: True
max_size: self.parent.width / 2
min_size: 0
ScrollView:
id: content
<TreeViewProperty>:
height: max(lkey.texture_size[1], ltext.texture_size[1])
Label:
id: lkey
text: root.key
text_size: (self.width, None)
width: 150
size_hint_x: None
Label:
id: ltext
text: [repr(getattr(root.widget, root.key, '')), root.refresh][0]\
if root.widget else ''
text_size: (self.width, None)
<-TreeViewWidget>:
height: self.texture_size[1] + sp(4)
size_hint_x: None
width: self.texture_size[0] + sp(4)
canvas.before:
Color:
rgba: self.color_selected if self.is_selected else (0, 0, 0, 0)
Rectangle:
pos: self.pos
size: self.size
Color:
rgba: 1, 1, 1, int(not self.is_leaf)
Rectangle:
source:
('atlas://data/images/defaulttheme/tree_%s' %
('opened' if self.is_open else 'closed'))
size: 16, 16
pos: self.x - 20, self.center_y - 8
canvas:
Color:
rgba:
(self.disabled_color if self.disabled else
(self.color if not self.markup else (1, 1, 1, 1)))
Rectangle:
texture: self.texture
size: self.texture_size
pos:
(int(self.center_x - self.texture_size[0] / 2.),
int(self.center_y - self.texture_size[1] / 2.))
''')
class TreeViewProperty(BoxLayout, TreeViewNode):
widget_ref = ObjectProperty(None, allownone=True)
def _get_widget(self):
wr = self.widget_ref
if wr is None:
return None
wr = wr()
if wr is None:
self.widget_ref = None
return None
return wr
widget = AliasProperty(_get_widget, None, bind=('widget_ref', ))
key = ObjectProperty(None, allownone=True)
inspector = ObjectProperty(None)
refresh = BooleanProperty(False)
class TreeViewWidget(Label, TreeViewNode):
widget = ObjectProperty(None)
class WidgetTree(TreeView):
selected_widget = ObjectProperty(None, allownone=True)
__events__ = ('on_select_widget',)
def __init__(self, **kwargs):
super(WidgetTree, self).__init__(**kwargs)
self.update_scroll = Clock.create_trigger(self._update_scroll)
def find_node_by_widget(self, widget):
for node in self.iterate_all_nodes():
if not node.parent_node:
continue
try:
if node.widget == widget:
return node
except ReferenceError:
pass
return None
def update_selected_widget(self, widget):
if widget:
node = self.find_node_by_widget(widget)
if node:
self.select_node(node, False)
while node and isinstance(node, TreeViewWidget):
if not node.is_open:
self.toggle_node(node)
node = node.parent_node
def on_selected_widget(self, inst, widget):
if widget:
self.update_selected_widget(widget)
self.update_scroll()
def select_node(self, node, select_widget=True):
super(WidgetTree, self).select_node(node)
if select_widget:
try:
self.dispatch('on_select_widget', node.widget.__self__)
except ReferenceError:
pass
def on_select_widget(self, widget):
pass
def _update_scroll(self, *args):
node = self._selected_node
if not node:
return
self.parent.scroll_to(node)
class Inspector(FloatLayout):
widget = ObjectProperty(None, allownone=True)
layout = ObjectProperty(None)
widgettree = ObjectProperty(None)
treeview = ObjectProperty(None)
inspect_enabled = BooleanProperty(False)
activated = BooleanProperty(False)
widget_info = BooleanProperty(False)
content = ObjectProperty(None)
at_bottom = BooleanProperty(True)
def __init__(self, **kwargs):
self.win = kwargs.pop('win', None)
super(Inspector, self).__init__(**kwargs)
self.avoid_bring_to_top = False
with self.canvas.before:
self.gcolor = Color(1, 0, 0, .25)
PushMatrix()
self.gtransform = Transform(Matrix())
self.grect = Rectangle(size=(0, 0))
PopMatrix()
Clock.schedule_interval(self.update_widget_graphics, 0)
def on_touch_down(self, touch):
ret = super(Inspector, self).on_touch_down(touch)
if (('button' not in touch.profile or touch.button == 'left')
and not ret and self.inspect_enabled):
self.highlight_at(*touch.pos)
if touch.is_double_tap:
self.inspect_enabled = False
self.show_widget_info()
ret = True
return ret
def on_touch_move(self, touch):
ret = super(Inspector, self).on_touch_move(touch)
if not ret and self.inspect_enabled:
self.highlight_at(*touch.pos)
ret = True
return ret
def on_touch_up(self, touch):
ret = super(Inspector, self).on_touch_up(touch)
if not ret and self.inspect_enabled:
ret = True
return ret
def on_window_children(self, win, children):
if self.avoid_bring_to_top:
return
self.avoid_bring_to_top = True
win.remove_widget(self)
win.add_widget(self)
self.avoid_bring_to_top = False
def highlight_at(self, x, y):
widget = None
# reverse the loop - look at children on top first and
# modalviews before others
win_children = self.win.children
children = chain(
(c for c in reversed(win_children) if isinstance(c, ModalView)),
(c for c in reversed(win_children) if not isinstance(c, ModalView))
)
for child in children:
if child is self:
continue
widget = self.pick(child, x, y)
if widget:
break
self.highlight_widget(widget)
def highlight_widget(self, widget, info=True, *largs):
# no widget to highlight, reduce rectangle to 0, 0
self.widget = widget
if not widget:
self.grect.size = 0, 0
if self.widget_info and info:
self.show_widget_info()
def update_widget_graphics(self, *l):
if not self.activated:
return
if self.widget is None:
self.grect.size = 0, 0
return
self.grect.size = self.widget.size
matrix = self.widget.get_window_matrix()
if self.gtransform.matrix.get() != matrix.get():
self.gtransform.matrix = matrix
def toggle_position(self, button):
to_bottom = button.text == 'Move to Bottom'
if to_bottom:
button.text = 'Move to Top'
if self.widget_info:
Animation(top=250, t='out_quad', d=.3).start(self.layout)
else:
Animation(top=60, t='out_quad', d=.3).start(self.layout)
bottom_bar = self.layout.children[1]
self.layout.remove_widget(bottom_bar)
self.layout.add_widget(bottom_bar)
else:
button.text = 'Move to Bottom'
if self.widget_info:
Animation(top=self.height, t='out_quad', d=.3).start(
self.layout)
else:
Animation(y=self.height - 60, t='out_quad', d=.3).start(
self.layout)
bottom_bar = self.layout.children[1]
self.layout.remove_widget(bottom_bar)
self.layout.add_widget(bottom_bar)
self.at_bottom = to_bottom
def pick(self, widget, x, y):
ret = None
# try to filter widgets that are not visible (invalid inspect target)
if (hasattr(widget, 'visible') and not widget.visible):
return ret
if widget.collide_point(x, y):
ret = widget
x2, y2 = widget.to_local(x, y)
# reverse the loop - look at children on top first
for child in reversed(widget.children):
ret = self.pick(child, x2, y2) or ret
return ret
def on_activated(self, instance, activated):
if not activated:
self.grect.size = 0, 0
if self.at_bottom:
anim = Animation(top=0, t='out_quad', d=.3)
else:
anim = Animation(y=self.height, t='out_quad', d=.3)
anim.bind(on_complete=self.animation_close)
anim.start(self.layout)
self.widget = None
self.widget_info = False
else:
self.win.add_widget(self)
Logger.info('Inspector: inspector activated')
if self.at_bottom:
Animation(top=60, t='out_quad', d=.3).start(self.layout)
else:
Animation(y=self.height - 60, t='out_quad', d=.3).start(
self.layout)
Clock.schedule_interval(self.update_widget_tree, 1)
self.update_widget_tree()
def animation_close(self, instance, value):
if not self.activated:
self.inspect_enabled = False
self.win.remove_widget(self)
self.content.clear_widgets()
treeview = self.treeview
for node in list(treeview.iterate_all_nodes()):
node.widget_ref = None
treeview.remove_node(node)
self._window_node = None
Clock.unschedule(self.update_widget_tree)
widgettree = self.widgettree
for node in list(widgettree.iterate_all_nodes()):
widgettree.remove_node(node)
Logger.info('Inspector: inspector deactivated')
def show_widget_info(self):
self.content.clear_widgets()
widget = self.widget
treeview = self.treeview
for node in list(treeview.iterate_all_nodes())[:]:
node.widget_ref = None
treeview.remove_node(node)
if not widget:
if self.at_bottom:
Animation(top=60, t='out_quad', d=.3).start(self.layout)
else:
Animation(y=self.height - 60, t='out_quad', d=.3).start(
self.layout)
self.widget_info = False
return
self.widget_info = True
if self.at_bottom:
Animation(top=250, t='out_quad', d=.3).start(self.layout)
else:
Animation(top=self.height, t='out_quad', d=.3).start(self.layout)
for node in list(treeview.iterate_all_nodes())[:]:
treeview.remove_node(node)
keys = list(widget.properties().keys())
keys.sort()
node = None
wk_widget = weakref.ref(widget)
for key in keys:
node = TreeViewProperty(key=key, widget_ref=wk_widget)
node.bind(is_selected=self.show_property)
try:
widget.bind(**{key: partial(
self.update_node_content, weakref.ref(node))})
except:
pass
treeview.add_node(node)
def update_node_content(self, node, *l):
node = node()
if node is None:
return
node.refresh = True
node.refresh = False
def keyboard_shortcut(self, win, scancode, *largs):
modifiers = largs[-1]
if scancode == 101 and modifiers == ['ctrl']:
self.activated = not self.activated
if self.activated:
self.inspect_enabled = True
return True
elif scancode == 27:
if self.inspect_enabled:
self.inspect_enabled = False
return True
if self.activated:
self.activated = False
return True
def show_property(self, instance, value, key=None, index=-1, *l):
# normal call: (tree node, focus, )
# nested call: (widget, prop value, prop key, index in dict/list)
if value is False:
return
content = None
if key is None:
# normal call
nested = False
widget = instance.widget
key = instance.key
prop = widget.property(key)
value = getattr(widget, key)
else:
# nested call, we might edit subvalue
nested = True
widget = instance
prop = None
dtype = None
if isinstance(prop, AliasProperty) or nested:
# trying to resolve type dynamicly
if type(value) in (str, str):
dtype = 'string'
elif type(value) in (int, float):
dtype = 'numeric'
elif type(value) in (tuple, list):
dtype = 'list'
if isinstance(prop, NumericProperty) or dtype == 'numeric':
content = TextInput(text=str(value) or '', multiline=False)
content.bind(text=partial(
self.save_property_numeric, widget, key, index))
elif isinstance(prop, StringProperty) or dtype == 'string':
content = TextInput(text=value or '', multiline=True)
content.bind(text=partial(
self.save_property_text, widget, key, index))
elif (isinstance(prop, ListProperty) or
isinstance(prop, ReferenceListProperty) or
isinstance(prop, VariableListProperty) or
dtype == 'list'):
content = GridLayout(cols=1, size_hint_y=None)
content.bind(minimum_height=content.setter('height'))
for i, item in enumerate(value):
button = Button(text=repr(item), size_hint_y=None, height=44)
if isinstance(item, Widget):
button.bind(on_release=partial(self.highlight_widget, item,
False))
else:
button.bind(on_release=partial(self.show_property, widget,
item, key, i))
content.add_widget(button)
elif isinstance(prop, OptionProperty):
content = GridLayout(cols=1, size_hint_y=None)
content.bind(minimum_height=content.setter('height'))
for option in prop.options:
button = ToggleButton(
text=option,
state='down' if option == value else 'normal',
group=repr(content.uid), size_hint_y=None,
height=44)
button.bind(on_press=partial(
self.save_property_option, widget, key))
content.add_widget(button)
elif isinstance(prop, ObjectProperty):
if isinstance(value, Widget):
content = Button(text=repr(value))
content.bind(on_release=partial(self.highlight_widget, value))
elif isinstance(value, Texture):
content = Image(texture=value)
else:
content = Label(text=repr(value))
elif isinstance(prop, BooleanProperty):
state = 'down' if value else 'normal'
content = ToggleButton(text=key, state=state)
content.bind(on_release=partial(self.save_property_boolean, widget,
key, index))
self.content.clear_widgets()
if content:
self.content.add_widget(content)
def save_property_numeric(self, widget, key, index, instance, value):
try:
if index >= 0:
getattr(widget, key)[index] = float(instance.text)
else:
setattr(widget, key, float(instance.text))
except:
pass
def save_property_text(self, widget, key, index, instance, value):
try:
if index >= 0:
getattr(widget, key)[index] = instance.text
else:
setattr(widget, key, instance.text)
except:
pass
def save_property_boolean(self, widget, key, index, instance, ):
try:
value = instance.state == 'down'
if index >= 0:
getattr(widget, key)[index] = value
else:
setattr(widget, key, value)
except:
pass
def save_property_option(self, widget, key, instance, *l):
try:
setattr(widget, key, instance.text)
except:
pass
def _update_widget_tree_node(self, node, widget, is_open=False):
tree = self.widgettree
update_nodes = []
nodes = {}
for cnode in node.nodes[:]:
try:
nodes[cnode.widget] = cnode
except ReferenceError:
# widget no longer exists, just remove it
pass
tree.remove_node(cnode)
for child in widget.children:
if child is self:
continue
if child in nodes:
cnode = tree.add_node(nodes[child], node)
else:
cnode = tree.add_node(TreeViewWidget(
text=child.__class__.__name__, widget=child.proxy_ref,
is_open=is_open), node)
update_nodes.append((cnode, child))
return update_nodes
def update_widget_tree(self, *args):
if not hasattr(self, '_window_node') or not self._window_node:
self._window_node = self.widgettree.add_node(
TreeViewWidget(text='Window', widget=self.win, is_open=True))
nodes = self._update_widget_tree_node(self._window_node, self.win,
is_open=True)
while nodes:
ntmp = nodes[:]
nodes = []
for node in ntmp:
nodes += self._update_widget_tree_node(*node)
self.widgettree.update_selected_widget(self.widget)
def create_inspector(win, ctx, *l):
'''Create an Inspector instance attached to the *ctx* and bound to the
Windows :meth:`~kivy.core.window.WindowBase.on_keyboard` event for
capturing the keyboard shortcut.
:Parameters:
`win`: A :class:`Window <kivy.core.window.WindowBase>`
The application Window to bind to.
`ctx`: A :class:`~kivy.uix.widget.Widget` or subclass
The Widget to be inspected.
'''
# Dunno why, but if we are creating inspector within the start(), no lang
# rules are applied.
ctx.inspector = Inspector(win=win)
win.bind(children=ctx.inspector.on_window_children,
on_keyboard=ctx.inspector.keyboard_shortcut)
def start(win, ctx):
Clock.schedule_once(partial(create_inspector, win, ctx))
def stop(win, ctx):
'''Stop and unload any active Inspectors for the given *ctx*.'''
if hasattr(ctx, 'inspector'):
win.unbind(children=ctx.inspector.on_window_children,
on_keyboard=ctx.inspector.keyboard_shortcut)
win.remove_widget(ctx.inspector)
del ctx.inspector
|
from pydantic import BaseModel
class BusinessDetailsOutput(BaseModel):
business_name: str
business_alias_name: str
address_line_1: str
address_line_2: str = None
city: str = None
state: str = None
zip: str = None
country: str = None
telephone: str = None
website: str = None
stock_symbol: str = None
year_founded: str = None
industry: str = None
contact_name: str = None
bsi_score: float = None
twitter_handle: str = None
|
'use strict';
APP.controller('HomeController', ["$scope", "$document", "$filter", "animals", "imagePath", "category", function($scope, $document, $filter, animals, imagePath, category) {
const LEFT = 37,
RIGHT = 39;
Array.prototype.max = function() {
return Math.max.apply(null, this);
};
var animalFilter = $filter('filter');
$scope.labels = category;
$scope.id = 0;
$scope.tab = 0;
$document.bind("keydown", function(e) {
$scope.$apply(function() {
if (e.keyCode === RIGHT) $scope.id++;
else if (e.keyCode === LEFT) $scope.id--;
$scope.id += $scope.num;
setUp($scope.target, $scope.id);
});
});
animals.$promise.then(function(res) {
$scope.target = res;
setUp($scope.target, $scope.id);
});
$scope.select = function(setTab) {
$scope.tab = setTab;
if (setTab != 0) {
animals.$promise.then(function(res) {
$scope.target = animalFilter(res, {
classname: category[setTab - 1]
}, true);
setUp($scope.target, $scope.id);
});
} else {
animals.$promise.then(function(res) {
console.log(res);
$scope.target = res;
setUp($scope.target, $scope.id);
});
};
};
var setUp = function(target, id) {
$scope.num = target.length;
var focusOn = target[id % $scope.num];
$scope.classname = focusOn['classname'];
$scope.img = imagePath + focusOn['path'];
$scope.values = $scope.labels.map(function(x) {
return focusOn[x];
});
$scope.maxItem = $scope.labels[$scope.values.indexOf($scope.values.max())];
draw();
}
//echarts
// console.log(echarts);
var draw = function() {
var myChart = echarts.init(document.getElementById('echarts'));
var option = {
title: {
text: 'Confidence'
},
tooltip: {},
yAxis: {
data: $scope.labels,
axisTick: {
alignWithLabel: true
},
type: 'category',
},
xAxis: {
max: 1,
min: 0
},
series: [{
type: 'bar',
markPoint: {
data: [{
name: "Max",
type: 'max'
}],
symbol: "triangle",
symbolSize: 10,
symbolRotate: 90,
symbolOffset: ["50%", 0],
label: {
normal: {
show: false
},
emphasis: {
show: false
}
}
},
data: $scope.values
}]
};
myChart.setOption(option);
}
}])
;
|
import { shallowMount, mount, createLocalVue } from '@vue/test-utils'
import OField from '@components/field/Field'
import OFieldBody from '@components/field/FieldBody'
import OInput from '@components/input/Input'
const localVue = createLocalVue()
localVue.component('o-field', OField)
localVue.component('o-field-horizontal-content', OFieldBody)
localVue.component('o-input', OInput)
describe('OField', () => {
it('is called', () => {
const wrapper = shallowMount(OField)
expect(wrapper.exists()).toBeTruthy()
})
it('render correctly', () => {
const wrapper = shallowMount(OField)
expect(wrapper.html()).toMatchSnapshot()
})
it('sets input class with type value when prop "variant" is changed dynamically', async () => {
const variant = { danger: true }
const wrapper = mount(OField, {
localVue,
slots: { default: [OInput] }
})
wrapper.setProps({ variant })
await wrapper.vm.$nextTick()
expect(wrapper.find('.o-control-input').classes()).toContain('o-control-input-icons-right')
expect(wrapper.find('.o-control-input').find('.o-icon').classes()).toContain('o-color-danger')
})
describe('Passing a message prop', () => {
const generateMountOptions = ({message}) => {
return {
propsData: {message},
localVue,
slots: {
default: [OInput, '<button class="button">Button</button>']
}
}
}
it('adds a help <p> element in the root div.field when "message" prop is passed', () => {
const message = 'Some string message'
const mountOptions = generateMountOptions({message})
const wrapper = shallowMount(OField, mountOptions)
expect(wrapper.find('.o-field').find('p.o-field-message').text()).toEqual(message)
})
it('changes the <p> element content in the root div.field when "message" prop is changed dynamically', async () => {
const message = 'Some string message'
const mountOptions = generateMountOptions({ message: 'initial message' })
const wrapper = shallowMount(OField, mountOptions)
wrapper.setProps({ message })
await wrapper.vm.$nextTick()
expect(wrapper.find('.o-field').find('p.o-field-message').text()).toEqual(message)
})
})
describe('managing groups', () => {
const mountOptions = {
propsData: {
grouped: true
},
localVue,
slots: {
default: [OInput, '<button class="button">Button</button>']
}
}
it('contains "o-field-grouped" when prop "grouped" is set', () => {
const {propsData} = mountOptions
const wrapper = mount(OField, {
...mountOptions,
propsData: {
...propsData,
grouped: true
}
})
const innerField = wrapper.find('.o-field-horizontal-content').find('.o-field')
expect(innerField.classes()).toContain('o-field-grouped')
})
it('contains "o-field-grouped-multiline" when prop "groupMultiline" is set', () => {
const {propsData} = mountOptions
const wrapper = mount(OField, {
...mountOptions,
propsData: {
...propsData,
groupMultiline: true
}
})
const innerField = wrapper.find('.o-field-horizontal-content').find('.o-field')
expect(innerField.classes()).toContain('o-field-grouped-multiline')
})
it('adds a label element under the root div.field when "label" prop is passed', () => {
const {propsData} = mountOptions
const wrapper = shallowMount(OField, {
...mountOptions,
propsData: {
...propsData,
label: 'Some label'
}
})
expect(wrapper.find('.o-field').find('label').isVisible()).toBe(true)
})
})
})
|
import React from "react";
import { View } from "react-native";
function Header(props) {
return (
<View>
<View></View>
</View>
);
}
export default Header;
|
/*
* Component for viewing the shape of a schema.
*/
import React from 'react'
import { PropTypes as Props } from './constants'
import PropTypes from 'prop-types'
import { HoverPopover } from './HoverPopover'
import * as R from 'ramda'
import { Box } from '@material-ui/core'
const SCHEMA_TYPE_IDENTIFIER = {
// "nested" schema types
shape: 'shape',
arrayOf: 'arrayOf',
// "primitive"/leaf schema types
any: 'any',
string: 'string',
boolean: 'boolean',
function: 'function',
number: 'number',
date: 'date',
array: 'array',
object: 'object',
}
// Assumes schema is already a valid Schema.
// Returns the corresponding type identifier (a string from the object above) for the schema.
export function getSchemaTypeIdentifier (schema) {
return schema._isSchemaType
? schema._type
: SCHEMA_TYPE_IDENTIFIER.shape
}
const monospace = { fontFamily: 'monospace' }
const keyName = { ...monospace, color: '#b966b1' }
export default class SchemaView extends React.Component {
static displayName = 'SchemaView'
static propTypes = {
schema: Props.Schema.isRequired,
keyName: PropTypes.string,
}
state = {
expanded: false,
}
toggleExpanded () {
this.setState({
expanded: !this.state.expanded,
})
}
render () {
const identifier = getSchemaTypeIdentifier(this.props.schema)
switch (identifier) {
case SCHEMA_TYPE_IDENTIFIER.any:
case SCHEMA_TYPE_IDENTIFIER.string:
case SCHEMA_TYPE_IDENTIFIER.boolean:
case SCHEMA_TYPE_IDENTIFIER.function:
case SCHEMA_TYPE_IDENTIFIER.number:
case SCHEMA_TYPE_IDENTIFIER.date:
case SCHEMA_TYPE_IDENTIFIER.array:
case SCHEMA_TYPE_IDENTIFIER.object:
if (typeof this.props.keyName === 'string') {
return <KeyValueSchemaView
preview={<LeafSchema schemaTypeName={identifier} />}
schemaElement={<LeafSchema schemaTypeName={identifier} />}
keyName={this.props.keyName}/>
}
return <LeafSchema schemaTypeName={identifier} />
case SCHEMA_TYPE_IDENTIFIER.shape:
if (typeof this.props.keyName === 'string') {
return <KeyValueSchemaView
schemaElement={<ShapeSchema schema={this.props.schema}/>}
keyName={this.props.keyName}
onToggleExpanded={this.toggleExpanded.bind(this)}
preview="Shape"
expanded={this.state.expanded}/>
}
return <ShapeSchema schema={this.props.schema}/>
case SCHEMA_TYPE_IDENTIFIER.arrayOf:
if (typeof this.props.keyName === 'string') {
return <KeyValueSchemaView
schemaElement={<SchemaView schema={this.props.schema._elementType}/>}
keyName={this.props.keyName}
onToggleExpanded={this.toggleExpanded.bind(this)}
preview="ArrayOf"
expanded={this.state.expanded}/>
}
return <Box display="flex" cursor="default">
<Box width={TRIANGLE_EXPANDER_WIDTH} />
<Box display="flex" flexDirection="column">
<Box css={monospace}>ArrayOf</Box>
<SchemaView schema={this.props.schema._elementType}/>
</Box>
</Box>
default:
throw new Error('invalid schema type identifier')
}
}
}
class LeafSchema extends React.Component {
static displayName = 'LeafSchema'
static propTypes = {
schemaTypeName: PropTypes.node.isRequired,
}
render () {
return <Box css={monospace}>{this.props.schemaTypeName}</Box>
}
}
class ShapeSchema extends React.Component {
static displayName = 'ShapeSchema'
static propTypes = {
schema: Props.Schema.isRequired,
}
render () {
return <div>
{
R.toPairs(this.props.schema).map(([ key, schema ]) =>
<SchemaView key={key} schema={schema} keyName={key} />
)
}
</div>
}
}
const TRIANGLE_RIGHT = '▶'
const TRIANGLE_DOWN = '▼'
const TRIANGLE_EXPANDER_WIDTH = "16px"
class KeyValueSchemaView extends React.Component {
static displayName = 'KeyValueSchemaView'
static propTypes = {
// Rendering of the actual schema
schemaElement: PropTypes.node.isRequired,
// For expandable schemas, the preview of the schema to show in line with the key
preview: PropTypes.node.isRequired,
keyName: PropTypes.string.isRequired,
expanded: PropTypes.bool,
onToggleExpanded: PropTypes.func,
}
render () {
const readableKeyName = this.props.keyName === ''
? `""`
: this.props.keyName
// Non-expandable key/value pairs
if (!this.props.onToggleExpanded) {
return (
<Box display="flex" cursor="default">
<Box width={TRIANGLE_EXPANDER_WIDTH} />
<Box display="flex" flexDirection="row">
<Box marginRight="10px" css={keyName}
onClick={this.props.onToggleExpanded}>{readableKeyName}:</Box>
<Box css={monospace}>{this.props.preview}</Box>
</Box>
</Box>
)
}
const arrow = this.props.expanded ? TRIANGLE_DOWN : TRIANGLE_RIGHT
return (
<Box display="flex" cursor="default">
<Box display="flex" width={TRIANGLE_EXPANDER_WIDTH} onClick={this.props.onToggleExpanded}>
<Box fontSize="9px" padding="2px">{ arrow }</Box>
</Box>
<Box display="flex" flexDirection="column">
<Box display="flex" flexDirection="row" onClick={this.props.onToggleExpanded}>
<Box marginRight="10px" css={keyName}>{readableKeyName}:</Box>
<Box css={monospace}>{this.props.preview}</Box>
</Box>
{ this.props.expanded && <Box>{ this.props.schemaElement }</Box> }
</Box>
</Box>
)
}
}
// A Popover with a SchemaView inside
export const SchemaPopover = props => {
const popoverContent = (
<Box padding="15px">
<SchemaView schema={props.schema}/>
</Box>
)
return (
<HoverPopover
hoverDurationMs={300}
popoverContent={popoverContent}
containerStyles={{ display: 'inline-flex' }}>
{props.children}
</HoverPopover>
)
}
SchemaPopover.propTypes = {
schema: Props.Schema.isRequired,
children: PropTypes.node.isRequired,
}
|
// Copyright (C) 2016 the V8 project authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/*---
es6id: 19.5.6.1.1
description: >
A new instance has the message property if created with a parameter
info: |
19.5.6.1.1 NativeError ( message )
...
4. If message is not undefined, then
a. Let msg be ToString(message).
b. Let msgDesc be the PropertyDescriptor{[[Value]]: msg, [[Writable]]: true,
[[Enumerable]]: false, [[Configurable]]: true}.
c. Let status be DefinePropertyOrThrow(O, "message", msgDesc).
...
includes: [propertyHelper.js]
---*/
class Err extends TypeError {}
Err.prototype.message = 'custom-type-error';
var err1 = new Err('foo 42');
assert.sameValue(err1.message, 'foo 42');
assert(err1.hasOwnProperty('message'));
verifyWritable(err1, 'message');
verifyNotEnumerable(err1, 'message');
verifyConfigurable(err1, 'message');
var err2 = new Err();
assert.sameValue(err2.hasOwnProperty('message'), false);
assert.sameValue(err2.message, 'custom-type-error');
|
import datetime
import functools
import math
from django.db.models import Count, StdDev, Avg
from django.db.utils import DatabaseError
from django.core.management.base import BaseCommand, CommandError
from apps.canvas_auth.models import User
from canvas.models import FollowCategory
from canvas.browse import frontpage_algorithms
def percentile(N, percent, key=lambda x:x):
"""
Find the percentile of a list of values.
@parameter N - is a list of values. Note N MUST BE already sorted.
@parameter percent - a float value from 0.0 to 1.0.
@parameter key - optional key function to compute value from each element of N.
@return - the percentile of the values
"""
if not N:
return None
k = (len(N)-1) * percent
f = math.floor(k)
c = math.ceil(k)
if f == c:
return key(N[int(k)])
d0 = key(N[int(f)]) * (c-k)
d1 = key(N[int(c)]) * (k-f)
return d0+d1
MONTHS = 6
class Command(BaseCommand):
args = ''
def handle(self, *args, **options):
cutoff_date = datetime.date.today() - datetime.timedelta(days=(30 * MONTHS))
counts = User.objects.filter(date_joined__gt=cutoff_date)
counts = counts.annotate(follow_count=Count('following')).order_by('follow_count')
avg = counts.aggregate(Avg('follow_count'))['follow_count__avg']
print
print 'Following counts for users who signed up in the last {} months'.format(MONTHS)
print '----------------'
print 'Average: {:.3} per user'.format(avg)
try:
std_dev = counts.aggregate(StdDev('follow_count'))['follow_count__stddev']
print 'StdDev: {:.3}'.format(std_dev)
except DatabaseError:
print "(can't get standard deviation with SQLite)"
counts = counts.values_list('follow_count', flat=True)
print 'Median: {}'.format(percentile(counts, 0.5))
print
|
const mongoose = require("mongoose");
const express = require("express");
const bodyparser = require("body-parser");
const hbs = require("express-handlebars");
const cookie = require("cookie-parser");
const session = require("express-session");
require("dotenv").config();
// const userModel = require('./models/userModel')
// const gameModel = require('./models/gameModel')
const app = express();
app.use(cookie())
app.use(session({
secret:"awjidioajodhau12312",
name:"cookie",
resave:true,
saveUninitialized:true,
cookie:{maxAge: 1000*60*60*24*30, httpOnly: false}
}))
app.use(bodyparser.urlencoded({ extended: true}))
app.use(bodyparser.json())
app.use(express.static(__dirname + '/'));
app.engine('hbs', hbs.create({
extname: 'hbs',
helpers: {
formatDate: function(string){
let date = new Date(string);
if (date.getDate() > 9) {
if((date.getMonth()+1) > 9)
return date.getDate()+' - '+(date.getMonth()+1)+' - '+date.getFullYear();
else
return date.getDate()+' - '+'0'+(date.getMonth()+1)+' - '+date.getFullYear();
}
else {
if((date.getMonth()+1) > 9)
return '0'+date.getDate()+' - '+(date.getMonth()+1)+' - '+date.getFullYear();
else
return '0'+date.getDate()+' - '+'0'+(date.getMonth()+1)+' - '+date.getFullYear();
}
}
},
partialsDir:'views/partials'
}).engine);
app.set('view engine', 'hbs');
mongoose.connect(`mongodb+srv://${process.env.DBUSER}:${process.env.DBPASS}@cluster0.h8ven.mongodb.net/Gamerist?retryWrites=true&w=majority`, {
useNewUrlParser: true,
useUnifiedTopology: true
}).then(() => console.log('connected'), err => console.log(err));
// mongoose.connect(
// 'mongodb://localhost/Gamerist', {
// useNewUrlParser: true,
// useUnifiedTopology: true
// }).then(() => console.log('connected'), err => console.log(err));
const router = require('./router/router');
app.use('/', router);
app.listen(process.env.PORT, function(){
console.log("I love you 3000")
})
// app.listen(3000, function(){
// console.log("I love you 3000")
// })
|
""" Module to access the Files endpoints """
# pylint: disable=too-many-lines,too-many-locals,too-many-public-methods,too-few-public-methods
from typing import Any, Dict, Optional, Union
from ...models import (
FileInfo,
FileInfoList,
GetFileLinkResponse200,
SearchFilesMultipartData,
UploadFileMultipartData,
UploadFileResponse201,
)
from ..base import ApiBaseClass
class FilesApi(ApiBaseClass):
"""Endpoints for uploading and interacting with files."""
async def upload_file(
self,
*,
multipart_data: Union[UploadFileMultipartData, Dict],
channel_id: Optional[str] = None,
filename: Optional[str] = None,
) -> UploadFileResponse201:
"""Upload a file
Uploads a file that can later be attached to a post.
This request can either be a multipart/form-data request with a
channel_id, files and optional
client_ids defined in the FormData, or it can be a request with the
channel_id and filename
defined as query parameters with the contents of a single file in the
body of the request.
Only multipart/form-data requests are supported by server versions up to
and including 4.7.
Server versions 4.8 and higher support both types of requests.
Permissions:
Must have `upload_file` permission.
Api Reference:
`UploadFile <https://api.mattermost.com/#operation/UploadFile>`_
"""
url = "/files"
params: Dict[str, Any] = {
"channel_id": channel_id,
"filename": filename,
}
params = {k: v for k, v in params.items() if v is not None}
multipart_body_data = UploadFileMultipartData.parse_obj(multipart_data)
request_kwargs = {
"url": url,
"data": multipart_body_data.get_data(),
"files": multipart_body_data.get_files(),
"params": params,
}
# pylint: disable-next=protected-access
async with self.client._get_httpx_client() as httpx_client:
response = await httpx_client.post(
**request_kwargs,
)
if self.skip_response_parsing:
return response
if response.status_code == 201:
response201 = UploadFileResponse201.parse_obj(response.json())
return response201
return response
async def get_file(
self,
file_id: str,
) -> None:
"""Get a file
Gets a file that has been uploaded previously.
Permissions:
Must have `read_channel` permission or be uploader of the
file.
Api Reference:
`GetFile <https://api.mattermost.com/#operation/GetFile>`_
"""
url = f"/files/{file_id}"
request_kwargs = {
"url": url,
}
# pylint: disable-next=protected-access
async with self.client._get_httpx_client() as httpx_client:
response = await httpx_client.get(
**request_kwargs,
)
if self.skip_response_parsing:
return response
return response
async def get_file_thumbnail(
self,
file_id: str,
) -> None:
"""Get a file's thumbnail
Gets a file's thumbnail.
Permissions:
Must have `read_channel` permission or be uploader of the
file.
Api Reference:
`GetFileThumbnail <https://api.mattermost.com/#operation/GetFileThumbnail>`_
"""
url = f"/files/{file_id}/thumbnail"
request_kwargs = {
"url": url,
}
# pylint: disable-next=protected-access
async with self.client._get_httpx_client() as httpx_client:
response = await httpx_client.get(
**request_kwargs,
)
if self.skip_response_parsing:
return response
return response
async def get_file_preview(
self,
file_id: str,
) -> None:
"""Get a file's preview
Gets a file's preview.
Permissions:
Must have `read_channel` permission or be uploader of the
file.
Api Reference:
`GetFilePreview <https://api.mattermost.com/#operation/GetFilePreview>`_
"""
url = f"/files/{file_id}/preview"
request_kwargs = {
"url": url,
}
# pylint: disable-next=protected-access
async with self.client._get_httpx_client() as httpx_client:
response = await httpx_client.get(
**request_kwargs,
)
if self.skip_response_parsing:
return response
return response
async def get_file_link(
self,
file_id: str,
) -> GetFileLinkResponse200:
"""Get a public file link
Gets a public link for a file that can be accessed without logging into
Mattermost.
Permissions:
Must have `read_channel` permission or be uploader of the
file.
Api Reference:
`GetFileLink <https://api.mattermost.com/#operation/GetFileLink>`_
"""
url = f"/files/{file_id}/link"
request_kwargs = {
"url": url,
}
# pylint: disable-next=protected-access
async with self.client._get_httpx_client() as httpx_client:
response = await httpx_client.get(
**request_kwargs,
)
if self.skip_response_parsing:
return response
if response.status_code == 200:
response200 = GetFileLinkResponse200.parse_obj(response.json())
return response200
return response
async def get_file_info(
self,
file_id: str,
) -> FileInfo:
"""Get metadata for a file
Gets a file's info.
Permissions:
Must have `read_channel` permission or be uploader of the
file.
Api Reference:
`GetFileInfo <https://api.mattermost.com/#operation/GetFileInfo>`_
"""
url = f"/files/{file_id}/info"
request_kwargs = {
"url": url,
}
# pylint: disable-next=protected-access
async with self.client._get_httpx_client() as httpx_client:
response = await httpx_client.get(
**request_kwargs,
)
if self.skip_response_parsing:
return response
if response.status_code == 200:
response200 = FileInfo.parse_obj(response.json())
return response200
return response
async def get_file_public(
self,
file_id: str,
*,
h: str,
) -> None:
"""Get a public file
Permissions:
No permissions required.
Api Reference:
`GetFilePublic <https://api.mattermost.com/#operation/GetFilePublic>`_
"""
url = f"/files/{file_id}/public"
params: Dict[str, Any] = {
"h": h,
}
params = {k: v for k, v in params.items() if v is not None}
request_kwargs = {
"url": url,
"params": params,
}
# pylint: disable-next=protected-access
async with self.client._get_httpx_client() as httpx_client:
response = await httpx_client.get(
**request_kwargs,
)
if self.skip_response_parsing:
return response
return response
async def search_files(
self,
team_id: str,
*,
multipart_data: Union[SearchFilesMultipartData, Dict],
) -> FileInfoList:
"""Search files in a team
Search for files in a team based on file name, extention and file
content (if file content extraction is enabled and supported for the
files).
Permissions:
Must be authenticated and have the `view_team` permission.
Minimum Server Version:
5.34
Api Reference:
`SearchFiles <https://api.mattermost.com/#operation/SearchFiles>`_
"""
url = f"/teams/{team_id}/files/search"
multipart_body_data = SearchFilesMultipartData.parse_obj(multipart_data)
request_kwargs = {
"url": url,
"data": multipart_body_data.get_data(),
}
# pylint: disable-next=protected-access
async with self.client._get_httpx_client() as httpx_client:
response = await httpx_client.post(
**request_kwargs,
)
if self.skip_response_parsing:
return response
if response.status_code == 200:
response200 = FileInfoList.parse_obj(response.json())
return response200
return response
|
/**
* kang
* 2021/10/12
*/
const {
vec2,
vec3,
vec4
} = glMatrix;
var canvas;
var gl;
var points = [];
var colors = [];
var xAxis = 0;
var yAxis = 1;
var zAxis = 2;
var axis = 0;
var theta = [0, 0, 0];
var thetaLoc;
//偏移量
var scale=vec3.fromValues(1, 1, 1);
var scaleLoc;
window.onload = function initCube() {
canvas = document.getElementById("webgl");
gl = WebGLUtils.setupWebGL(canvas);
if (!gl) {
alert("WebGL isn't available");
}
//得到立方体所需要的数据
makeCube();
gl.viewport(0, 0, canvas.width, canvas.height);
gl.clearColor(0.0, 0.0, 0.0, 0.5);
//激活深度比较,并且更新深度缓冲区
gl.enable(gl.DEPTH_TEST);
//
var program = initShaders(gl, "vertex-shader", "fragment-shader");
gl.useProgram(program);
//
var cBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, cBuffer);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(colors), gl.STATIC_DRAW);
var vColor = gl.getAttribLocation(program, "vColor");
gl.vertexAttribPointer(vColor, 4, gl.FLOAT, false, 0, 0);
gl.enableVertexAttribArray(vColor);
var vBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, vBuffer);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(points), gl.STATIC_DRAW);
var vPosition = gl.getAttribLocation(program, "vPosition");
gl.vertexAttribPointer(vPosition, 3, gl.FLOAT, false, 0, 0);
gl.enableVertexAttribArray(vPosition);
//这里是关键
//使用getUniformLocation得到一个着色器中某个变量的地址
//并将这个地址赋值给指定的变量名称
thetaLoc = gl.getUniformLocation(program, "theta");
/**
* WebGLRenderingContext.uniform[1234][fi][v]() 方法指定了uniform 变量的值。
* 参数
* location WebGLUniformLocation 对象包含了将要修改的uniform 属性位置.
* value, v0, v1, v2, v3
新的值将被用于uniform 变量. 可能的类型:
浮点值 Number(方法名跟"f").
浮点数组 (例如 Float32Array 或 Array 的数组) 用于浮点型向量方法 (方法名跟 "fv").
整型值 Number (方法名跟"i").
整型数组Int32Array 用于整型向量方法 (方法名跟 "iv").
*/
//theta是3维浮点型数组,所以是3fv
gl.uniform3fv(thetaLoc, theta);
//
scaleLoc = gl.getUniformLocation(program, "scale");
gl.uniform3fv(scaleLoc, scale);
/**
* 一下为添加事件
*/
addEvent();
render();
}
function makeCube() {
//顶点矩阵
var vertices = [
vec4.fromValues(-0.5, -0.5, 0.5, 1.0),
vec4.fromValues(-0.5, 0.5, 0.5, 1.0),
vec4.fromValues(0.5, 0.5, 0.5, 1.0),
vec4.fromValues(0.5, -0.5, 0.5, 1.0),
vec4.fromValues(-0.5, -0.5, -0.5, 1.0),
vec4.fromValues(-0.5, 0.5, -0.5, 1.0),
vec4.fromValues(0.5, 0.5, -0.5, 1.0),
vec4.fromValues(0.5, -0.5, -0.5, 1.0),
];
//顶点颜色矩阵
var vertexColors = [
vec4.fromValues(0.0, 0.0, 0.0, 1.0),
vec4.fromValues(1.0, 0.0, 0.0, 1.0),
vec4.fromValues(1.0, 1.0, 0.0, 1.0),
vec4.fromValues(0.0, 1.0, 0.0, 1.0),
vec4.fromValues(0.0, 0.0, 1.0, 1.0),
vec4.fromValues(1.0, 0.0, 1.0, 1.0),
vec4.fromValues(0.0, 1.0, 1.0, 1.0),
vec4.fromValues(1.0, 1.0, 1.0, 1.0)
];
// var faces = [
// 1, 0, 3, 1, 3, 2, //正
// 2, 3, 7, 2, 7, 6, //右
// 3, 0, 4, 3, 4, 7, //底
// 6, 5, 1, 6, 1, 2, //顶
// 4, 5, 6, 4, 6, 7, //背
// 5, 4, 0, 5, 0, 1 //左
// ];
var faces= [
1, 0, 3, 2,
2, 3, 7, 6,
3, 0, 4, 7,
6, 5, 1, 2,
4, 5, 6, 7,
5, 4, 0, 1,
];
//这里我使用TRIANGLE_FAN来绘制三角形
//一个面需要四个点
//整个立方体需要24个点
for (var i = 0; i < faces.length; i++) {
points.push(vertices[faces[i]][0], vertices[faces[i]][1], vertices[faces[i]][2]);
colors.push(vertexColors[Math.floor(i / 4)][0], vertexColors[Math.floor(i / 4)][1], vertexColors[Math.floor(i /
4)][2], vertexColors[Math.floor(i / 4)][3]);
}
}
function render() {
// console.log(points.length);
// console.log(colors.length);
gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
theta[axis] += 0.1;
gl.uniform3fv(thetaLoc, theta);
//更新偏移量
gl.uniform3fv(scaleLoc, scale);
for(var i=0; i<points.length/3; i+=4) {
gl.drawArrays(gl.TRIANGLE_FAN, i, 4);
}
requestAnimFrame(render);
}
function addEvent() {
document.getElementById("rotateX").onclick = function() {
axis = xAxis;
}
document.getElementById("rotateY").onclick = function() {
axis = yAxis;
}
document.getElementById("rotateZ").onclick = function() {
axis = zAxis;
}
document.getElementById("X_Scale").onchange=function(event) {
scale[0]=event.target.value/100;
// console.log(scale);
}
document.getElementById("Y_Scale").onchange=function(event) {
scale[1]=event.target.value/100;
// console.log(scale);
}
document.getElementById("Z_Scale").onchange=function(event) {
scale[2]=event.target.value/100;
// console.log(scale);
}
}
|
import Alert from './components-v4/alert-native';
import Button from './components-v4/button-native';
import Carousel from './components-v4/carousel-native';
import Collapse from './components-v4/collapse-native';
import Dropdown from './components-v4/dropdown-native';
import Modal from './components-v4/modal-native';
import Popover from './components-v4/popover-native';
import ScrollSpy from './components-v4/scrollspy-native';
import Tab from './components-v4/tab-native';
import Toast from './components-v4/toast-native';
import Tooltip from './components-v4/tooltip-native';
import './util/init-v4';
import initCallback from './util/initCallback-v4';
import removeDataAPI from './util/removeDataAPI-v4';
import componentsInit from './util/componentsInit-v4';
import Version from './version';
const BSN = {
Alert,
Button,
Carousel,
Collapse,
Dropdown,
Modal,
Popover,
ScrollSpy,
Tab,
Toast,
Tooltip,
initCallback,
removeDataAPI,
componentsInit,
Version,
};
export default BSN;
|
import React from 'react'
import {css} from '@emotion/core'
import {renderFragment} from 'test-utils'
import {Text} from './Text'
test('<Text> -> as prop', () => {
expect(renderFragment(<Text as="div" />)).toMatchSnapshot()
})
test('<Text> -> box properties', () => {
expect(renderFragment(<Text d="block" />)).toMatchSnapshot()
})
test('<Text> -> flex properties', () => {
expect(renderFragment(<Text row />)).toMatchSnapshot()
})
test('<Text> -> weight', () => {
const weights = [100, 200, 300, 400, 500, 600, 700, 800, 900]
for (let w of weights) {
expect(renderFragment(<Text weight={w} />)).toMatchSnapshot(w)
expect(renderFragment(<Text weight={String(w)} />)).toMatchSnapshot(
`String ${w}`
)
}
})
test('<Text> -> size', () => {
const sizes = ['xs', 'sm', 'md', 'lg', 'xl']
for (let size of sizes)
expect(renderFragment(<Text size={size} />)).toMatchSnapshot(size)
for (let size of sizes)
expect(
renderFragment(<Text size={size} />, {text: {sizeUnit: 'px'}})
).toMatchSnapshot(`${size} px`)
for (let size of sizes)
expect(
renderFragment(<Text size={size} />, {text: {legible: ['xl']}})
).toMatchSnapshot(`${size} legibility`)
expect(renderFragment(<Text size={null} />)).toMatchSnapshot(`null`)
expect(renderFragment(<Text size={false} />)).toMatchSnapshot(`false`)
})
test('<Text> -> scale', () => {
// numeric
let theme = {
text: {
scale: {
sm: 0.5,
md: 1,
lg: 2,
},
},
}
const sizes = ['sm', 'md', 'lg']
for (let size of sizes)
expect(renderFragment(<Text size={size} />, theme)).toMatchSnapshot(
`number.${size}`
)
// css
theme = {
text: {
scale: {
sm: css`
font-size: 0.5rem;
`,
md: css`
font-size: 1rem;
`,
lg: css`
font-size: 2rem;
`,
},
},
}
for (let size of sizes)
expect(renderFragment(<Text size={size} />, theme)).toMatchSnapshot(
`css.${size}`
)
// func
theme = {
text: {
scale: {
sm: () =>
css`
font-size: 0.5rem;
`,
md: () =>
css`
font-size: 1rem;
`,
lg: () =>
css`
font-size: 2rem;
`,
},
},
}
for (let size of sizes)
expect(renderFragment(<Text size={size} />, theme)).toMatchSnapshot(
`fn.${size}`
)
})
test('<Text> -> family', () => {
expect(renderFragment(<Text family="system" />)).toMatchSnapshot('default')
expect(
renderFragment(<Text family="system" />, {
text: {families: {system: 'Helvetica'}},
})
).toMatchSnapshot('custom')
expect(renderFragment(<Text family="Helvetica" />)).toMatchSnapshot(
'Helvetica'
)
})
test('<Text> -> alignment', () => {
const alignments = ['left', 'center', 'right', 'justified']
for (let a of alignments)
expect(renderFragment(<Text aligned={a} />)).toMatchSnapshot(a)
})
test('<Text> -> antialias', () => {
expect(renderFragment(<Text antialias />)).toMatchSnapshot('antialias')
})
test('<Text> -> ellipsis', () => {
expect(renderFragment(<Text ellipsis />)).toMatchSnapshot('ellipsis')
})
test('<Text> -> lineHeight', () => {
expect(renderFragment(<Text lineHeight="1.0" />)).toMatchSnapshot('1.0')
expect(renderFragment(<Text lineHeight="1px" />)).toMatchSnapshot('1px')
expect(renderFragment(<Text lineHeight="1em" />)).toMatchSnapshot('1em')
expect(renderFragment(<Text lineHeight="1rem" />)).toMatchSnapshot('1rem')
})
test('<Text> -> color', () => {
expect(renderFragment(<Text color="blue" />)).toMatchSnapshot('theme blue')
expect(renderFragment(<Text color="#000" />)).toMatchSnapshot('#000')
})
|
/// <reference types="Cypress" />
describe("Email assertion:", () => {
it("Look for an email with specific subject and link in email body", function() {
// debugger; //Uncomment for debugger to work...
cy.task("gmail:get-messages", {
options: {
include_body: true
}
}).then(emails => {
const found_email = emails.find(email => {
return (
email.from.indexOf("AccountSupport@ubi.com") >= 0 &&
email.subject.indexOf("Ubisoft Password Change Request") >= 0
);
});
assert.isNotNull(found_email, "Found email!");
const body = found_email.body.html;
assert.isTrue(
body.indexOf(
"https://account-uplay.ubi.com/en-GB/action/change-password?genomeid="
) >= 0,
"Found reset link!"
);
});
});
});
|
Prism.languages.warpscript={comment:/#.*|\/\/.*|\/\*[\s\S]*?\*\//,string:{pattern:/"(?:[^"\\\r\n]|\\.)*"|'(?:[^'\\\r\n]|\\.)*'|<'(?:[^\\']|'(?!>)|\\.)*'>/,greedy:!0},variable:/\$\S+/,macro:{pattern:/@\S+/,alias:"property"},keyword:/\b(?:BREAK|CHECKMACRO|CONTINUE|CUDF|DEFINED|DEFINEDMACRO|EVAL|FAIL|FOR|FOREACH|FORSTEP|IFT|IFTE|MSGFAIL|NRETURN|RETHROW|RETURN|SWITCH|TRY|UDF|UNTIL|WHILE)\b/,number:/[+-]?\b(?:NaN|Infinity|\d+(?:\.\d*)?(?:[Ee][+-]?\d+)?|0x[\da-fA-F]+|0b[01]+)\b/,boolean:/\b(?:false|true|F|T)\b/,punctuation:/<%|%>|[{}[\]()]/,operator:/==|&&?|\|\|?|\*\*?|>>>?|<<|[<>!~]=?|[-/%^]|\+!?|\b(?:AND|NOT|OR)\b/};
|
const mongoose = require('mongoose')
const businessSchema = new mongoose.Schema({
name: {
type: String,
required: [true, 'Name is required']
},
businessImg: {
type: String
},
createdAt: {
type: Number,
default: Date.now() // Get a timestamp :)
}
})
const businessModel = mongoose.model('business', businessSchema)
module.exports = businessModel
|
"""
Aqualink API documentation
The Aqualink public API documentation # noqa: E501
The version of the OpenAPI document: 1.0.0
Generated by: https://openapi-generator.tech
"""
import sys
import unittest
import aqualink_sdk
from aqualink_sdk.model.set_admin_level_dto import SetAdminLevelDto
class TestSetAdminLevelDto(unittest.TestCase):
"""SetAdminLevelDto unit test stubs"""
def setUp(self):
pass
def tearDown(self):
pass
def testSetAdminLevelDto(self):
"""Test SetAdminLevelDto"""
# FIXME: construct object with mandatory attributes with example values
# model = SetAdminLevelDto() # noqa: E501
pass
if __name__ == '__main__':
unittest.main()
|
import React from "react";
import { Modal } from "antd";
import VideoPlayer from "react-video-js-player";
function VideoModal({ isVisible, setVisible, videoUrl }) {
return (
<Modal
title="Demo"
visible={isVisible}
onCancel={() => {
setVisible(false);
}}
style={{
top: 30,
display: "flex",
alignItems: "center",
justifyContent: "center",
}}
footer={null}
>
<VideoPlayer src={videoUrl} width="720" height="340" />
</Modal>
);
}
export default VideoModal;
|
const expect = require('chai').expect;
const Quirk = require("../../index");
describe('add substitutions', function () {
it('should create a valid quirk from substitutions added via addSubstitution', function () {
let testSub = new Quirk();
testSub.addSubstitution('w', 'ww');
testSub.addSubstitution('v', 'vv');
expect(testSub.toPlain("wweh evveryone is mean")).to.equal('weh everyone is mean');
expect(testSub.toQuirk("weh everyone is mean")).to.equal('wweh evveryone is mean');
});
it('should create a valid case-insensitive quirk from substitutions added via addSubstitution', function () {
let testSub = new Quirk();
testSub.addSubstitution('i', 'ii', {ignoreCase: true});
testSub.addSubstitution('s', '2', {ignoreCase: true});
expect(testSub.toPlain("thii2 ii2 bee e22!")).to.equal('This is bee ess!');
expect(testSub.toQuirk("this IS BEE ESS!")).to.equal('thii2 ii2 BEE E22!');
});
it('should throw an error when given an invalid substitution to add', function () {
const badFn = () => {
let testSub = new Quirk();
testSub.addSubstitution('w');
}
expect(badFn).to.throw();
});
});
|
(function($){function findLine(sdpLines,prefix,substr){return findLineInRange(sdpLines,0,-1,prefix,substr);}
function findLineInRange(sdpLines,startLine,endLine,prefix,substr){var realEndLine=(endLine!=-1)?endLine:sdpLines.length;for(var i=startLine;i<realEndLine;++i){if(sdpLines[i].indexOf(prefix)===0){if(!substr||sdpLines[i].toLowerCase().indexOf(substr.toLowerCase())!==-1){return i;}}}
return null;}
function getCodecPayloadType(sdpLine){var pattern=new RegExp('a=rtpmap:(\\d+) \\w+\\/\\d+');var result=sdpLine.match(pattern);return(result&&result.length==2)?result[1]:null;}
function setDefaultCodec(mLine,payload){var elements=mLine.split(' ');var newLine=[];var index=0;for(var i=0;i<elements.length;i++){if(index===3){newLine[index++]=payload;}
if(elements[i]!==payload)newLine[index++]=elements[i];}
return newLine.join(' ');}
$.FSRTC=function(options){this.options=$.extend({useVideo:null,useStereo:false,userData:null,localVideo:null,screenShare:false,useCamera:"any",iceServers:false,videoParams:{},audioParams:{},callbacks:{onICEComplete:function(){},onICE:function(){},onOfferSDP:function(){}},},options);this.audioEnabled=true;this.videoEnabled=true;this.mediaData={SDP:null,profile:{},candidateList:[]};if(moz){this.constraints={offerToReceiveAudio:true,offerToReceiveVideo:this.options.useVideo?true:false,};}else{this.constraints={optional:[{'DtlsSrtpKeyAgreement':'true'}],mandatory:{OfferToReceiveAudio:true,OfferToReceiveVideo:this.options.useVideo?true:false,}};}
if(self.options.useVideo){self.options.useVideo.style.display='none';}
setCompat();checkCompat();};$.FSRTC.validRes=[];$.FSRTC.prototype.useVideo=function(obj,local){var self=this;if(obj){self.options.useVideo=obj;self.options.localVideo=local;if(moz){self.constraints.offerToReceiveVideo=true;}else{self.constraints.mandatory.OfferToReceiveVideo=true;}}else{self.options.useVideo=null;self.options.localVideo=null;if(moz){self.constraints.offerToReceiveVideo=false;}else{self.constraints.mandatory.OfferToReceiveVideo=false;}}
if(self.options.useVideo){self.options.useVideo.style.display='none';}};$.FSRTC.prototype.useStereo=function(on){var self=this;self.options.useStereo=on;};$.FSRTC.prototype.stereoHack=function(sdp){var self=this;if(!self.options.useStereo){return sdp;}
var sdpLines=sdp.split('\r\n');var opusIndex=findLine(sdpLines,'a=rtpmap','opus/48000'),opusPayload;if(!opusIndex){return sdp;}else{opusPayload=getCodecPayloadType(sdpLines[opusIndex]);}
var fmtpLineIndex=findLine(sdpLines,'a=fmtp:'+opusPayload.toString());if(fmtpLineIndex===null){sdpLines[opusIndex]=sdpLines[opusIndex]+'\r\na=fmtp:'+opusPayload.toString()+" stereo=1; sprop-stereo=1"}else{sdpLines[fmtpLineIndex]=sdpLines[fmtpLineIndex].concat('; stereo=1; sprop-stereo=1');}
sdp=sdpLines.join('\r\n');return sdp;};function setCompat(){$.FSRTC.moz=!!navigator.mozGetUserMedia;if(!navigator.getUserMedia){navigator.getUserMedia=navigator.mozGetUserMedia||navigator.webkitGetUserMedia||navigator.msGetUserMedia;}}
function checkCompat(){if(!navigator.getUserMedia){alert('This application cannot function in this browser.');return false;}
return true;}
function onStreamError(self,e){console.log('There has been a problem retrieving the streams - did you allow access? Check Device Resolution',e);doCallback(self,"onError",e);}
function onStreamSuccess(self,stream){console.log("Stream Success");doCallback(self,"onStream",stream);}
function onICE(self,candidate){self.mediaData.candidate=candidate;self.mediaData.candidateList.push(self.mediaData.candidate);doCallback(self,"onICE");}
function doCallback(self,func,arg){if(func in self.options.callbacks){self.options.callbacks[func](self,arg);}}
function onICEComplete(self,candidate){console.log("ICE Complete");doCallback(self,"onICEComplete");}
function onChannelError(self,e){console.error("Channel Error",e);doCallback(self,"onError",e);}
function onICESDP(self,sdp){self.mediaData.SDP=self.stereoHack(sdp.sdp);console.log("ICE SDP");doCallback(self,"onICESDP");}
function onAnswerSDP(self,sdp){self.answer.SDP=self.stereoHack(sdp.sdp);console.log("ICE ANSWER SDP");doCallback(self,"onAnswerSDP",self.answer.SDP);}
function onMessage(self,msg){console.log("Message");doCallback(self,"onICESDP",msg);}
function onRemoteStream(self,stream){if(self.options.useVideo){self.options.useVideo.style.display='block';}
var element=self.options.useAudio;console.log("REMOTE STREAM",stream,element);if(typeof element.srcObject!=='undefined'){element.srcObject=stream;}else if(typeof element.mozSrcObject!=='undefined'){element.mozSrcObject=stream;}else if(typeof element.src!=='undefined'){element.src=URL.createObjectURL(stream);}else{console.error('Error attaching stream to element.');}
self.options.useAudio.play();self.remoteStream=stream;}
function onOfferSDP(self,sdp){self.mediaData.SDP=self.stereoHack(sdp.sdp);console.log("Offer SDP");doCallback(self,"onOfferSDP");}
$.FSRTC.prototype.answer=function(sdp,onSuccess,onError){this.peer.addAnswerSDP({type:"answer",sdp:sdp},onSuccess,onError);};$.FSRTC.prototype.stopPeer=function(){if(self.peer){console.log("stopping peer");self.peer.stop();}}
$.FSRTC.prototype.stop=function(){var self=this;if(self.options.useVideo){self.options.useVideo.style.display='none';if(moz){self.options.useVideo['mozSrcObject']=null;}else{self.options.useVideo['src']='';}}
if(self.localStream){if(typeof self.localStream.stop=='function'){self.localStream.stop();}else{if(self.localStream.active){var tracks=self.localStream.getTracks();console.error(tracks);tracks.forEach(function(track,index){console.log(track);track.stop();})}}
self.localStream=null;}
if(self.options.localVideo){self.options.localVideo.style.display='none';if(moz){self.options.localVideo['mozSrcObject']=null;}else{self.options.localVideo['src']='';}}
if(self.options.localVideoStream){if(typeof self.options.localVideoStream.stop=='function'){self.options.localVideoStream.stop();}else{if(self.localVideoStream.active){var tracks=self.localVideoStream.getTracks();console.error(tracks);tracks.forEach(function(track,index){console.log(track);track.stop();})}}}
if(self.peer){console.log("stopping peer");self.peer.stop();}};$.FSRTC.prototype.getMute=function(){var self=this;return self.audioEnabled;}
$.FSRTC.prototype.setMute=function(what){var self=this;var audioTracks=self.localStream.getAudioTracks();for(var i=0,len=audioTracks.length;i<len;i++){switch(what){case"on":audioTracks[i].enabled=true;break;case"off":audioTracks[i].enabled=false;break;case"toggle":audioTracks[i].enabled=!audioTracks[i].enabled;default:break;}
self.audioEnabled=audioTracks[i].enabled;}
return!self.audioEnabled;}
$.FSRTC.prototype.getVideoMute=function(){var self=this;return self.videoEnabled;}
$.FSRTC.prototype.setVideoMute=function(what){var self=this;var videoTracks=self.localStream.getVideoTracks();for(var i=0,len=videoTracks.length;i<len;i++){switch(what){case"on":videoTracks[i].enabled=true;break;case"off":videoTracks[i].enabled=false;break;case"toggle":videoTracks[i].enabled=!videoTracks[i].enabled;default:break;}
self.videoEnabled=videoTracks[i].enabled;}
return!self.videoEnabled;}
$.FSRTC.prototype.createAnswer=function(params){var self=this;self.type="answer";self.remoteSDP=params.sdp;console.debug("inbound sdp: ",params.sdp);function onSuccess(stream){self.localStream=stream;self.peer=RTCPeerConnection({type:self.type,attachStream:self.localStream,onICE:function(candidate){return onICE(self,candidate);},onICEComplete:function(){return onICEComplete(self);},onRemoteStream:function(stream){return onRemoteStream(self,stream);},onICESDP:function(sdp){return onICESDP(self,sdp);},onChannelError:function(e){return onChannelError(self,e);},constraints:self.constraints,iceServers:self.options.iceServers,offerSDP:{type:"offer",sdp:self.remoteSDP}});onStreamSuccess(self);}
function onError(e){onStreamError(self,e);}
var mediaParams=getMediaParams(self);console.log("Audio constraints",mediaParams.audio);console.log("Video constraints",mediaParams.video);if(self.options.useVideo&&self.options.localVideo){getUserMedia({constraints:{audio:false,video:{mandatory:self.options.videoParams,optional:[]},},localVideo:self.options.localVideo,onsuccess:function(e){self.options.localVideoStream=e;console.log("local video ready");},onerror:function(e){console.error("local video error!");}});}
getUserMedia({constraints:{audio:mediaParams.audio,video:mediaParams.video},video:mediaParams.useVideo,onsuccess:onSuccess,onerror:onError});};function getMediaParams(obj){var audio;if(obj.options.useMic&&obj.options.useMic==="none"){console.log("Microphone Disabled");audio=false;}else if(obj.options.videoParams&&obj.options.screenShare){console.error("SCREEN SHARE");audio=false;}else{audio={mandatory:obj.options.audioParams,optional:[]};if(obj.options.useMic!=="any"){audio.optional=[{sourceId:obj.options.useMic}]}}
if(obj.options.useVideo&&obj.options.localVideo){getUserMedia({constraints:{audio:false,video:{mandatory:obj.options.videoParams,optional:[]},},localVideo:obj.options.localVideo,onsuccess:function(e){self.options.localVideoStream=e;console.log("local video ready");},onerror:function(e){console.error("local video error!");}});}
var video={};var bestFrameRate=obj.options.videoParams.vertoBestFrameRate;delete obj.options.videoParams.vertoBestFrameRate;video={mandatory:obj.options.videoParams,optional:[]}
var useVideo=obj.options.useVideo;if(useVideo&&obj.options.useCamera&&obj.options.useCamera!=="none"){if(!video.optional){video.optional=[];}
if(obj.options.useCamera!=="any"){video.optional.push({sourceId:obj.options.useCamera});}
if(bestFrameRate){video.optional.push({minFrameRate:bestFrameRate});video.optional.push({maxFrameRate:bestFrameRate});}}else{console.log("Camera Disabled");video=false;useVideo=false;}
return{audio:audio,video:video,useVideo:useVideo};}
$.FSRTC.prototype.call=function(profile){checkCompat();var self=this;var screen=false;self.type="offer";if(self.options.videoParams&&self.options.screenShare){screen=true;}
function onSuccess(stream){self.localStream=stream;if(screen){if(moz){self.constraints.OfferToReceiveVideo=false;}else{self.constraints.mandatory.OfferToReceiveVideo=false;}}
self.peer=RTCPeerConnection({type:self.type,attachStream:self.localStream,onICE:function(candidate){return onICE(self,candidate);},onICEComplete:function(){return onICEComplete(self);},onRemoteStream:screen?function(stream){}:function(stream){return onRemoteStream(self,stream);},onOfferSDP:function(sdp){return onOfferSDP(self,sdp);},onICESDP:function(sdp){return onICESDP(self,sdp);},onChannelError:function(e){return onChannelError(self,e);},constraints:self.constraints,iceServers:self.options.iceServers,});onStreamSuccess(self,stream);}
function onError(e){onStreamError(self,e);}
var mediaParams=getMediaParams(self);console.log("Audio constraints",mediaParams.audio);console.log("Video constraints",mediaParams.video);if(mediaParams.audio||mediaParams.video){getUserMedia({constraints:{audio:mediaParams.audio,video:mediaParams.video},video:mediaParams.useVideo,onsuccess:onSuccess,onerror:onError});}else{onSuccess(null);}};window.moz=!!navigator.mozGetUserMedia;function RTCPeerConnection(options){var gathering=false,done=false;var w=window,PeerConnection=w.mozRTCPeerConnection||w.webkitRTCPeerConnection,SessionDescription=w.mozRTCSessionDescription||w.RTCSessionDescription,IceCandidate=w.mozRTCIceCandidate||w.RTCIceCandidate;var STUN={url:!moz?'stun:stun.l.google.com:19302':'stun:23.21.150.121'};var iceServers=null;if(options.iceServers){var tmp=options.iceServers;if(typeof(tmp)==="boolean"){tmp=null;}
if(tmp&&!(typeof(tmp)=="object"&&tmp.constructor===Array)){console.warn("iceServers must be an array, reverting to default ice servers");tmp=null;}
iceServers={iceServers:tmp||[STUN]};if(!moz&&!tmp){iceServers.iceServers=[STUN];}}
var optional={optional:[]};if(!moz){optional.optional=[{DtlsSrtpKeyAgreement:true},{RtpDataChannels:options.onChannelMessage?true:false}];}
var peer=new PeerConnection(iceServers,optional);openOffererChannel();var x=0;function ice_handler(){done=true;gathering=null;if(options.onICEComplete){options.onICEComplete();}
if(options.type=="offer"){if((!moz||(!options.sentICESDP&&peer.localDescription.sdp.match(/a=candidate/))&&!x&&options.onICESDP)){options.onICESDP(peer.localDescription);}}else{if(!x&&options.onICESDP){options.onICESDP(peer.localDescription);}}}
peer.onicecandidate=function(event){if(done){return;}
if(!gathering){gathering=setTimeout(ice_handler,1000);}
if(event){if(event.candidate){options.onICE(event.candidate);}}else{done=true;if(gathering){clearTimeout(gathering);gathering=null;}
ice_handler();}};if(options.attachStream)peer.addStream(options.attachStream);if(options.attachStreams&&options.attachStream.length){var streams=options.attachStreams;for(var i=0;i<streams.length;i++){peer.addStream(streams[i]);}}
peer.onaddstream=function(event){var remoteMediaStream=event.stream;remoteMediaStream.onended=function(){if(options.onRemoteStreamEnded)options.onRemoteStreamEnded(remoteMediaStream);};if(options.onRemoteStream)options.onRemoteStream(remoteMediaStream);};var constraints=options.constraints||{offerToReceiveAudio:true,offerToReceiveVideo:true};function createOffer(){if(!options.onOfferSDP)return;peer.createOffer(function(sessionDescription){sessionDescription.sdp=serializeSdp(sessionDescription.sdp);peer.setLocalDescription(sessionDescription);options.onOfferSDP(sessionDescription);if(moz&&options.onICESDP&&sessionDescription.sdp.match(/a=candidate/)){options.onICESDP(sessionDescription);options.sentICESDP=1;}},onSdpError,constraints);}
function createAnswer(){if(options.type!="answer")return;peer.setRemoteDescription(new SessionDescription(options.offerSDP),onSdpSuccess,onSdpError);peer.createAnswer(function(sessionDescription){sessionDescription.sdp=serializeSdp(sessionDescription.sdp);peer.setLocalDescription(sessionDescription);if(options.onAnswerSDP){options.onAnswerSDP(sessionDescription);}},onSdpError,constraints);}
if((options.onChannelMessage&&!moz)||!options.onChannelMessage){createOffer();createAnswer();}
function setBandwidth(sdp){sdp=sdp.replace(/b=AS([^\r\n]+\r\n)/g,'');sdp=sdp.replace(/a=mid:data\r\n/g,'a=mid:data\r\nb=AS:1638400\r\n');return sdp;}
function getInteropSDP(sdp){var chars='ABCDEFGHIJKLMNOPQRSTUVWXYZ'.split(''),extractedChars='';function getChars(){extractedChars+=chars[parseInt(Math.random()*40)]||'';if(extractedChars.length<40)getChars();return extractedChars;}
if(options.onAnswerSDP)sdp=sdp.replace(/(a=crypto:0 AES_CM_128_HMAC_SHA1_32)(.*?)(\r\n)/g,'');var inline=getChars()+'\r\n'+(extractedChars='');sdp=sdp.indexOf('a=crypto')==-1?sdp.replace(/c=IN/g,'a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:'+inline+'c=IN'):sdp;return sdp;}
function serializeSdp(sdp){return sdp;}
var channel;function openOffererChannel(){if(!options.onChannelMessage||(moz&&!options.onOfferSDP))return;_openOffererChannel();if(!moz)return;navigator.mozGetUserMedia({audio:true,fake:true},function(stream){peer.addStream(stream);createOffer();},useless);}
function _openOffererChannel(){channel=peer.createDataChannel(options.channel||'RTCDataChannel',moz?{}:{reliable:false});if(moz)channel.binaryType='blob';setChannelEvents();}
function setChannelEvents(){channel.onmessage=function(event){if(options.onChannelMessage)options.onChannelMessage(event);};channel.onopen=function(){if(options.onChannelOpened)options.onChannelOpened(channel);};channel.onclose=function(event){if(options.onChannelClosed)options.onChannelClosed(event);console.warn('WebRTC DataChannel closed',event);};channel.onerror=function(event){if(options.onChannelError)options.onChannelError(event);console.error('WebRTC DataChannel error',event);};}
if(options.onAnswerSDP&&moz&&options.onChannelMessage)openAnswererChannel();function openAnswererChannel(){peer.ondatachannel=function(event){channel=event.channel;channel.binaryType='blob';setChannelEvents();};if(!moz)return;navigator.mozGetUserMedia({audio:true,fake:true},function(stream){peer.addStream(stream);createAnswer();},useless);}
function useless(){log('Error in fake:true');}
function onSdpSuccess(){}
function onSdpError(e){if(options.onChannelError){options.onChannelError(e);}
console.error('sdp error:',e);}
return{addAnswerSDP:function(sdp,cbSuccess,cbError){peer.setRemoteDescription(new SessionDescription(sdp),cbSuccess?cbSuccess:onSdpSuccess,cbError?cbError:onSdpError);},addICE:function(candidate){peer.addIceCandidate(new IceCandidate({sdpMLineIndex:candidate.sdpMLineIndex,candidate:candidate.candidate}));},peer:peer,channel:channel,sendData:function(message){if(channel){channel.send(message);}},stop:function(){peer.close();if(options.attachStream){if(typeof options.attachStream.stop=='function'){options.attachStream.stop();}else{options.attachStream.active=false;}}}};}
var video_constraints={mandatory:{},optional:[]};function getUserMedia(options){var n=navigator,media;n.getMedia=n.webkitGetUserMedia||n.mozGetUserMedia;n.getMedia(options.constraints||{audio:true,video:video_constraints},streaming,options.onerror||function(e){console.error(e);});function streaming(stream){if(options.localVideo){options.localVideo[moz?'mozSrcObject':'src']=moz?stream:window.webkitURL.createObjectURL(stream);options.localVideo.style.display='block';}
if(options.onsuccess){options.onsuccess(stream);}
media=stream;}
return media;}
$.FSRTC.resSupported=function(w,h){for(var i in $.FSRTC.validRes){if($.FSRTC.validRes[i][0]==w&&$.FSRTC.validRes[i][1]==h){return true;}}
return false;}
$.FSRTC.bestResSupported=function(){var w=0,h=0;for(var i in $.FSRTC.validRes){if($.FSRTC.validRes[i][0]>w&&$.FSRTC.validRes[i][1]>h){w=$.FSRTC.validRes[i][0];h=$.FSRTC.validRes[i][1];}}
return[w,h];}
var resList=[[320,180],[320,240],[640,360],[640,480],[1280,720],[1920,1080]];var resI=0;var ttl=0;var checkRes=function(cam,func){if(resI>=resList.length){var res={'validRes':$.FSRTC.validRes,'bestResSupported':$.FSRTC.bestResSupported()};localStorage.setItem("res_"+cam,$.toJSON(res));if(func)return func(res);return;}
var video={mandatory:{},optional:[]}
if(cam){video.optional=[{sourceId:cam}];}
w=resList[resI][0];h=resList[resI][1];resI++;video.mandatory={"minWidth":w,"minHeight":h,"maxWidth":w,"maxHeight":h};getUserMedia({constraints:{audio:ttl++==0,video:video},onsuccess:function(e){e.getTracks().forEach(function(track){track.stop();});console.info(w+"x"+h+" supported.");$.FSRTC.validRes.push([w,h]);checkRes(cam,func);},onerror:function(e){console.error(w+"x"+h+" not supported.");checkRes(cam,func);}});}
$.FSRTC.getValidRes=function(cam,func){var used=[];var cached=localStorage.getItem("res_"+cam);if(cached){var cache=$.parseJSON(cached);if(cache){$.FSRTC.validRes=cache.validRes;console.log("CACHED RES FOR CAM "+cam,cache);}else{console.error("INVALID CACHE");}
return func?func(cache):null;}
$.FSRTC.validRes=[];resI=0;checkRes(cam,func);}
$.FSRTC.checkPerms=function(runtime,check_audio,check_video){getUserMedia({constraints:{audio:check_audio,video:check_video,},onsuccess:function(e){e.getTracks().forEach(function(track){track.stop();});console.info("media perm init complete");if(runtime){setTimeout(runtime,100,true);}},onerror:function(e){if(check_video&&check_audio){console.error("error, retesting with audio params only");return $.FSRTC.checkPerms(runtime,check_audio,false);}
console.error("media perm init error");if(runtime){runtime(false)}}});}})(jQuery);(function($){$.JsonRpcClient=function(options){var self=this;this.options=$.extend({ajaxUrl:null,socketUrl:null,onmessage:null,login:null,passwd:null,sessid:null,loginParams:null,userVariables:null,getSocket:function(onmessage_cb){return self._getSocket(onmessage_cb);}},options);self.ws_cnt=0;this.wsOnMessage=function(event){self._wsOnMessage(event);};};$.JsonRpcClient.prototype._ws_socket=null;$.JsonRpcClient.prototype._ws_callbacks={};$.JsonRpcClient.prototype._current_id=1;$.JsonRpcClient.prototype.speedTest=function(bytes,cb){var socket=this.options.getSocket(this.wsOnMessage);if(socket!==null){this.speedCB=cb;this.speedBytes=bytes;socket.send("#SPU "+bytes);var loops=bytes/1024;var rem=bytes%1024;var i;var data=new Array(1024).join(".");for(i=0;i<loops;i++){socket.send("#SPB "+data);}
if(rem){socket.send("#SPB "+data);}
socket.send("#SPE");}};$.JsonRpcClient.prototype.call=function(method,params,success_cb,error_cb){if(!params){params={};}
if(this.options.sessid){params.sessid=this.options.sessid;}
var request={jsonrpc:'2.0',method:method,params:params,id:this._current_id++};if(!success_cb){success_cb=function(e){console.log("Success: ",e);};}
if(!error_cb){error_cb=function(e){console.log("Error: ",e);};}
var socket=this.options.getSocket(this.wsOnMessage);if(socket!==null){this._wsCall(socket,request,success_cb,error_cb);return;}
if(this.options.ajaxUrl===null){throw"$.JsonRpcClient.call used with no websocket and no http endpoint.";}
$.ajax({type:'POST',url:this.options.ajaxUrl,data:$.toJSON(request),dataType:'json',cache:false,success:function(data){if('error'in data)error_cb(data.error,this);success_cb(data.result,this);},error:function(jqXHR,textStatus,errorThrown){try{var response=$.parseJSON(jqXHR.responseText);if('console'in window)console.log(response);error_cb(response.error,this);}catch(err){error_cb({error:jqXHR.responseText},this);}}});};$.JsonRpcClient.prototype.notify=function(method,params){if(this.options.sessid){params.sessid=this.options.sessid;}
var request={jsonrpc:'2.0',method:method,params:params};var socket=this.options.getSocket(this.wsOnMessage);if(socket!==null){this._wsCall(socket,request);return;}
if(this.options.ajaxUrl===null){throw"$.JsonRpcClient.notify used with no websocket and no http endpoint.";}
$.ajax({type:'POST',url:this.options.ajaxUrl,data:$.toJSON(request),dataType:'json',cache:false});};$.JsonRpcClient.prototype.batch=function(callback,all_done_cb,error_cb){var batch=new $.JsonRpcClient._batchObject(this,all_done_cb,error_cb);callback(batch);batch._execute();};$.JsonRpcClient.prototype.socketReady=function(){if(this._ws_socket===null||this._ws_socket.readyState>1){return false;}
return true;};$.JsonRpcClient.prototype.closeSocket=function(){var self=this;if(self.socketReady()){self._ws_socket.onclose=function(w){console.log("Closing Socket");};self._ws_socket.close();}};$.JsonRpcClient.prototype.loginData=function(params){var self=this;self.options.login=params.login;self.options.passwd=params.passwd;self.options.loginParams=params.loginParams;self.options.userVariables=params.userVariables;};$.JsonRpcClient.prototype.connectSocket=function(onmessage_cb){var self=this;if(self.to){clearTimeout(self.to);}
if(!self.socketReady()){self.authing=false;if(self._ws_socket){delete self._ws_socket;}
self._ws_socket=new WebSocket(self.options.socketUrl);if(self._ws_socket){self._ws_socket.onmessage=onmessage_cb;self._ws_socket.onclose=function(w){if(!self.ws_sleep){self.ws_sleep=1000;}
if(self.options.onWSClose){self.options.onWSClose(self);}
console.error("Websocket Lost "+self.ws_cnt+" sleep: "+self.ws_sleep+"msec");self.to=setTimeout(function(){console.log("Attempting Reconnection....");self.connectSocket(onmessage_cb);},self.ws_sleep);self.ws_cnt++;if(self.ws_sleep<3000&&(self.ws_cnt%10)===0){self.ws_sleep+=1000;}};self._ws_socket.onopen=function(){if(self.to){clearTimeout(self.to);}
self.ws_sleep=1000;self.ws_cnt=0;if(self.options.onWSConnect){self.options.onWSConnect(self);}
var req;while((req=$.JsonRpcClient.q.pop())){self._ws_socket.send(req);}};}}
return self._ws_socket?true:false;};$.JsonRpcClient.prototype._getSocket=function(onmessage_cb){if(this.options.socketUrl===null||!("WebSocket"in window))return null;this.connectSocket(onmessage_cb);return this._ws_socket;};$.JsonRpcClient.q=[];$.JsonRpcClient.prototype._wsCall=function(socket,request,success_cb,error_cb){var request_json=$.toJSON(request);if(socket.readyState<1){self=this;$.JsonRpcClient.q.push(request_json);}else{socket.send(request_json);}
if('id'in request&&typeof success_cb!=='undefined'){this._ws_callbacks[request.id]={request:request_json,request_obj:request,success_cb:success_cb,error_cb:error_cb};}};$.JsonRpcClient.prototype._wsOnMessage=function(event){var response;if(event.data[0]=="#"&&event.data[1]=="S"&&event.data[2]=="P"){if(event.data[3]=="U"){this.up_dur=parseInt(event.data.substring(4));}else if(this.speedCB&&event.data[3]=="D"){this.down_dur=parseInt(event.data.substring(4));var up_kps=(((this.speedBytes*8)/(this.up_dur/1000))/1024).toFixed(0);var down_kps=(((this.speedBytes*8)/(this.down_dur/1000))/1024).toFixed(0);console.info("Speed Test: Up: "+up_kps+" Down: "+down_kps);this.speedCB(event,{upDur:this.up_dur,downDur:this.down_dur,upKPS:up_kps,downKPS:down_kps});this.speedCB=null;}
return;}
try{response=$.parseJSON(event.data);if(typeof response==='object'&&'jsonrpc'in response&&response.jsonrpc==='2.0'){if('result'in response&&this._ws_callbacks[response.id]){var success_cb=this._ws_callbacks[response.id].success_cb;delete this._ws_callbacks[response.id];success_cb(response.result,this);return;}else if('error'in response&&this._ws_callbacks[response.id]){var error_cb=this._ws_callbacks[response.id].error_cb;var orig_req=this._ws_callbacks[response.id].request;if(!self.authing&&response.error.code==-32000&&self.options.login&&self.options.passwd){self.authing=true;this.call("login",{login:self.options.login,passwd:self.options.passwd,loginParams:self.options.loginParams,userVariables:self.options.userVariables},this._ws_callbacks[response.id].request_obj.method=="login"?function(e){self.authing=false;console.log("logged in");delete self._ws_callbacks[response.id];if(self.options.onWSLogin){self.options.onWSLogin(true,self);}}:function(e){self.authing=false;console.log("logged in, resending request id: "+response.id);var socket=self.options.getSocket(self.wsOnMessage);if(socket!==null){socket.send(orig_req);}
if(self.options.onWSLogin){self.options.onWSLogin(true,self);}},function(e){console.log("error logging in, request id:",response.id);delete self._ws_callbacks[response.id];error_cb(response.error,this);if(self.options.onWSLogin){self.options.onWSLogin(false,self);}});return;}
delete this._ws_callbacks[response.id];error_cb(response.error,this);return;}}}catch(err){console.log("ERROR: "+err);return;}
if(typeof this.options.onmessage==='function'){event.eventData=response;if(!event.eventData){event.eventData={};}
var reply=this.options.onmessage(event);if(reply&&typeof reply==="object"&&event.eventData.id){var msg={jsonrpc:"2.0",id:event.eventData.id,result:reply};var socket=self.options.getSocket(self.wsOnMessage);if(socket!==null){socket.send($.toJSON(msg));}}}};$.JsonRpcClient._batchObject=function(jsonrpcclient,all_done_cb,error_cb){this._requests=[];this.jsonrpcclient=jsonrpcclient;this.all_done_cb=all_done_cb;this.error_cb=typeof error_cb==='function'?error_cb:function(){};};$.JsonRpcClient._batchObject.prototype.call=function(method,params,success_cb,error_cb){if(!params){params={};}
if(this.options.sessid){params.sessid=this.options.sessid;}
if(!success_cb){success_cb=function(e){console.log("Success: ",e);};}
if(!error_cb){error_cb=function(e){console.log("Error: ",e);};}
this._requests.push({request:{jsonrpc:'2.0',method:method,params:params,id:this.jsonrpcclient._current_id++},success_cb:success_cb,error_cb:error_cb});};$.JsonRpcClient._batchObject.prototype.notify=function(method,params){if(this.options.sessid){params.sessid=this.options.sessid;}
this._requests.push({request:{jsonrpc:'2.0',method:method,params:params}});};$.JsonRpcClient._batchObject.prototype._execute=function(){var self=this;if(this._requests.length===0)return;var batch_request=[];var handlers={};var i=0;var call;var success_cb;var error_cb;var socket=self.jsonrpcclient.options.getSocket(self.jsonrpcclient.wsOnMessage);if(socket!==null){for(i=0;i<this._requests.length;i++){call=this._requests[i];success_cb=('success_cb'in call)?call.success_cb:undefined;error_cb=('error_cb'in call)?call.error_cb:undefined;self.jsonrpcclient._wsCall(socket,call.request,success_cb,error_cb);}
if(typeof all_done_cb==='function')all_done_cb(result);return;}
for(i=0;i<this._requests.length;i++){call=this._requests[i];batch_request.push(call.request);if('id'in call.request){handlers[call.request.id]={success_cb:call.success_cb,error_cb:call.error_cb};}}
success_cb=function(data){self._batchCb(data,handlers,self.all_done_cb);};if(self.jsonrpcclient.options.ajaxUrl===null){throw"$.JsonRpcClient.batch used with no websocket and no http endpoint.";}
$.ajax({url:self.jsonrpcclient.options.ajaxUrl,data:$.toJSON(batch_request),dataType:'json',cache:false,type:'POST',error:function(jqXHR,textStatus,errorThrown){self.error_cb(jqXHR,textStatus,errorThrown);},success:success_cb});};$.JsonRpcClient._batchObject.prototype._batchCb=function(result,handlers,all_done_cb){for(var i=0;i<result.length;i++){var response=result[i];if('error'in response){if(response.id===null||!(response.id in handlers)){if('console'in window)console.log(response);}else{handlers[response.id].error_cb(response.error,this);}}else{if(!(response.id in handlers)&&'console'in window){console.log(response);}else{handlers[response.id].success_cb(response.result,this);}}}
if(typeof all_done_cb==='function')all_done_cb(result);};})(jQuery);(function($){var sources=[];var generateGUID=(typeof(window.crypto)!=='undefined'&&typeof(window.crypto.getRandomValues)!=='undefined')?function(){var buf=new Uint16Array(8);window.crypto.getRandomValues(buf);var S4=function(num){var ret=num.toString(16);while(ret.length<4){ret="0"+ret;}
return ret;};return(S4(buf[0])+S4(buf[1])+"-"+S4(buf[2])+"-"+S4(buf[3])+"-"+S4(buf[4])+"-"+S4(buf[5])+S4(buf[6])+S4(buf[7]));}:function(){return'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g,function(c){var r=Math.random()*16|0,v=c=='x'?r:(r&0x3|0x8);return v.toString(16);});};$.verto=function(options,callbacks){var verto=this;$.verto.saved.push(verto);verto.options=$.extend({login:null,passwd:null,socketUrl:null,tag:null,localTag:null,videoParams:{},audioParams:{},loginParams:{},deviceParams:{onResCheck:null},userVariables:{},iceServers:false,ringSleep:6000,sessid:null},options);if(verto.options.deviceParams.useCamera){$.FSRTC.getValidRes(verto.options.deviceParams.useCamera,verto.options.deviceParams.onResCheck);}
if(!verto.options.deviceParams.useMic){verto.options.deviceParams.useMic="any";}
if(!verto.options.deviceParams.useSpeak){verto.options.deviceParams.useSpeak="any";}
if(verto.options.sessid){verto.sessid=verto.options.sessid;}else{verto.sessid=localStorage.getItem("verto_session_uuid")||generateGUID();localStorage.setItem("verto_session_uuid",verto.sessid);}
verto.dialogs={};verto.callbacks=callbacks||{};verto.eventSUBS={};verto.rpcClient=new $.JsonRpcClient({login:verto.options.login,passwd:verto.options.passwd,socketUrl:verto.options.socketUrl,loginParams:verto.options.loginParams,userVariables:verto.options.userVariables,sessid:verto.sessid,onmessage:function(e){return verto.handleMessage(e.eventData);},onWSConnect:function(o){o.call('login',{});},onWSLogin:function(success){if(verto.callbacks.onWSLogin){verto.callbacks.onWSLogin(verto,success);}},onWSClose:function(success){if(verto.callbacks.onWSClose){verto.callbacks.onWSClose(verto,success);}
verto.purge();}});if(verto.options.ringFile&&verto.options.tag){verto.ringer=$("#"+verto.options.tag);}
verto.rpcClient.call('login',{});};$.verto.prototype.deviceParams=function(obj){var verto=this;for(var i in obj){verto.options.deviceParams[i]=obj[i];}
if(obj.useCamera){$.FSRTC.getValidRes(verto.options.deviceParams.useCamera,obj?obj.onResCheck:undefined);}};$.verto.prototype.videoParams=function(obj){var verto=this;for(var i in obj){verto.options.videoParams[i]=obj[i];}};$.verto.prototype.iceServers=function(obj){var verto=this;verto.options.iceServers=obj;};$.verto.prototype.loginData=function(params){var verto=this;verto.options.login=params.login;verto.options.passwd=params.passwd;verto.rpcClient.loginData(params);};$.verto.prototype.logout=function(msg){var verto=this;verto.rpcClient.closeSocket();if(verto.callbacks.onWSClose){verto.callbacks.onWSClose(verto,false);}
verto.purge();};$.verto.prototype.login=function(msg){var verto=this;verto.logout();verto.rpcClient.call('login',{});};$.verto.prototype.message=function(msg){var verto=this;var err=0;if(!msg.to){console.error("Missing To");err++;}
if(!msg.body){console.error("Missing Body");err++;}
if(err){return false;}
verto.sendMethod("verto.info",{msg:msg});return true;};$.verto.prototype.processReply=function(method,success,e){var verto=this;var i;switch(method){case"verto.subscribe":for(i in e.unauthorizedChannels){drop_bad(verto,e.unauthorizedChannels[i]);}
for(i in e.subscribedChannels){mark_ready(verto,e.subscribedChannels[i]);}
break;case"verto.unsubscribe":break;}};$.verto.prototype.sendMethod=function(method,params){var verto=this;verto.rpcClient.call(method,params,function(e){verto.processReply(method,true,e);},function(e){verto.processReply(method,false,e);});};function do_sub(verto,channel,obj){}
function drop_bad(verto,channel){console.error("drop unauthorized channel: "+channel);delete verto.eventSUBS[channel];}
function mark_ready(verto,channel){for(var j in verto.eventSUBS[channel]){verto.eventSUBS[channel][j].ready=true;console.log("subscribed to channel: "+channel);if(verto.eventSUBS[channel][j].readyHandler){verto.eventSUBS[channel][j].readyHandler(verto,channel);}}}
var SERNO=1;function do_subscribe(verto,channel,subChannels,sparams){var params=sparams||{};var local=params.local;var obj={eventChannel:channel,userData:params.userData,handler:params.handler,ready:false,readyHandler:params.readyHandler,serno:SERNO++};var isnew=false;if(!verto.eventSUBS[channel]){verto.eventSUBS[channel]=[];subChannels.push(channel);isnew=true;}
verto.eventSUBS[channel].push(obj);if(local){obj.ready=true;obj.local=true;}
if(!isnew&&verto.eventSUBS[channel][0].ready){obj.ready=true;if(obj.readyHandler){obj.readyHandler(verto,channel);}}
return{serno:obj.serno,eventChannel:channel};}
$.verto.prototype.subscribe=function(channel,sparams){var verto=this;var r=[];var subChannels=[];var params=sparams||{};if(typeof(channel)==="string"){r.push(do_subscribe(verto,channel,subChannels,params));}else{for(var i in channel){r.push(do_subscribe(verto,channel,subChannels,params));}}
if(subChannels.length){verto.sendMethod("verto.subscribe",{eventChannel:subChannels.length==1?subChannels[0]:subChannels,subParams:params.subParams});}
return r;};$.verto.prototype.unsubscribe=function(handle){var verto=this;var i;if(!handle){for(i in verto.eventSUBS){if(verto.eventSUBS[i]){verto.unsubscribe(verto.eventSUBS[i]);}}}else{var unsubChannels={};var sendChannels=[];var channel;if(typeof(handle)=="string"){delete verto.eventSUBS[handle];unsubChannels[handle]++;}else{for(i in handle){if(typeof(handle[i])=="string"){channel=handle[i];delete verto.eventSUBS[channel];unsubChannels[channel]++;}else{var repl=[];channel=handle[i].eventChannel;for(var j in verto.eventSUBS[channel]){if(verto.eventSUBS[channel][j].serno==handle[i].serno){}else{repl.push(verto.eventSUBS[channel][j]);}}
verto.eventSUBS[channel]=repl;if(verto.eventSUBS[channel].length===0){delete verto.eventSUBS[channel];unsubChannels[channel]++;}}}}
for(var u in unsubChannels){console.log("Sending Unsubscribe for: ",u);sendChannels.push(u);}
if(sendChannels.length){verto.sendMethod("verto.unsubscribe",{eventChannel:sendChannels.length==1?sendChannels[0]:sendChannels});}}};$.verto.prototype.broadcast=function(channel,params){var verto=this;var msg={eventChannel:channel,data:{}};for(var i in params){msg.data[i]=params[i];}
verto.sendMethod("verto.broadcast",msg);};$.verto.prototype.purge=function(callID){var verto=this;var x=0;var i;for(i in verto.dialogs){if(!x){console.log("purging dialogs");}
x++;verto.dialogs[i].setState($.verto.enum.state.purge);}
for(i in verto.eventSUBS){if(verto.eventSUBS[i]){console.log("purging subscription: "+i);delete verto.eventSUBS[i];}}};$.verto.prototype.hangup=function(callID){var verto=this;if(callID){var dialog=verto.dialogs[callID];if(dialog){dialog.hangup();}}else{for(var i in verto.dialogs){verto.dialogs[i].hangup();}}};$.verto.prototype.newCall=function(args,callbacks){var verto=this;if(!verto.rpcClient.socketReady()){console.error("Not Connected...");return;}
var dialog=new $.verto.dialog($.verto.enum.direction.outbound,this,args);dialog.invite();if(callbacks){dialog.callbacks=callbacks;}
return dialog;};$.verto.prototype.handleMessage=function(data){var verto=this;if(!(data&&data.method)){console.error("Invalid Data",data);return;}
if(data.params.callID){var dialog=verto.dialogs[data.params.callID];if(data.method==="verto.attach"&&dialog){delete dialog.verto.dialogs[dialog.callID];dialog.rtc.stop();dialog=null;}
if(dialog){switch(data.method){case'verto.bye':dialog.hangup(data.params);break;case'verto.answer':dialog.handleAnswer(data.params);break;case'verto.media':dialog.handleMedia(data.params);break;case'verto.display':dialog.handleDisplay(data.params);break;case'verto.info':dialog.handleInfo(data.params);break;default:console.debug("INVALID METHOD OR NON-EXISTANT CALL REFERENCE IGNORED",dialog,data.method);break;}}else{switch(data.method){case'verto.attach':data.params.attach=true;if(data.params.sdp&&data.params.sdp.indexOf("m=video")>0){data.params.useVideo=true;}
if(data.params.sdp&&data.params.sdp.indexOf("stereo=1")>0){data.params.useStereo=true;}
dialog=new $.verto.dialog($.verto.enum.direction.inbound,verto,data.params);dialog.setState($.verto.enum.state.recovering);break;case'verto.invite':if(data.params.sdp&&data.params.sdp.indexOf("m=video")>0){data.params.wantVideo=true;}
if(data.params.sdp&&data.params.sdp.indexOf("stereo=1")>0){data.params.useStereo=true;}
dialog=new $.verto.dialog($.verto.enum.direction.inbound,verto,data.params);break;default:console.debug("INVALID METHOD OR NON-EXISTANT CALL REFERENCE IGNORED");break;}}
return{method:data.method};}else{switch(data.method){case'verto.punt':verto.purge();verto.logout();break;case'verto.event':var list=null;var key=null;if(data.params){key=data.params.eventChannel;}
if(key){list=verto.eventSUBS[key];if(!list){list=verto.eventSUBS[key.split(".")[0]];}}
if(!list&&key&&key===verto.sessid){if(verto.callbacks.onMessage){verto.callbacks.onMessage(verto,null,$.verto.enum.message.pvtEvent,data.params);}}else if(!list&&key&&verto.dialogs[key]){verto.dialogs[key].sendMessage($.verto.enum.message.pvtEvent,data.params);}else if(!list){if(!key){key="UNDEFINED";}
console.error("UNSUBBED or invalid EVENT "+key+" IGNORED");}else{for(var i in list){var sub=list[i];if(!sub||!sub.ready){console.error("invalid EVENT for "+key+" IGNORED");}else if(sub.handler){sub.handler(verto,data.params,sub.userData);}else if(verto.callbacks.onEvent){verto.callbacks.onEvent(verto,data.params,sub.userData);}else{console.log("EVENT:",data.params);}}}
break;case"verto.info":if(verto.callbacks.onMessage){verto.callbacks.onMessage(verto,null,$.verto.enum.message.info,data.params.msg);}
console.debug("MESSAGE from: "+data.params.msg.from,data.params.msg.body);break;default:console.error("INVALID METHOD OR NON-EXISTANT CALL REFERENCE IGNORED",data.method);break;}}};var del_array=function(array,name){var r=[];var len=array.length;for(var i=0;i<len;i++){if(array[i]!=name){r.push(array[i]);}}
return r;};var hashArray=function(){var vha=this;var hash={};var array=[];vha.reorder=function(a){array=a;var h=hash;hash={};var len=array.length;for(var i=0;i<len;i++){var key=array[i];if(h[key]){hash[key]=h[key];delete h[key];}}
h=undefined;};vha.clear=function(){hash=undefined;array=undefined;hash={};array=[];};vha.add=function(name,val,insertAt){var redraw=false;if(!hash[name]){if(insertAt===undefined||insertAt<0||insertAt>=array.length){array.push(name);}else{var x=0;var n=[];var len=array.length;for(var i=0;i<len;i++){if(x++==insertAt){n.push(name);}
n.push(array[i]);}
array=undefined;array=n;n=undefined;redraw=true;}}
hash[name]=val;return redraw;};vha.del=function(name){var r=false;if(hash[name]){array=del_array(array,name);delete hash[name];r=true;}else{console.error("can't del nonexistant key "+name);}
return r;};vha.get=function(name){return hash[name];};vha.order=function(){return array;};vha.hash=function(){return hash;};vha.indexOf=function(name){var len=array.length;for(var i=0;i<len;i++){if(array[i]==name){return i;}}};vha.arrayLen=function(){return array.length;};vha.asArray=function(){var r=[];var len=array.length;for(var i=0;i<len;i++){var key=array[i];r.push(hash[key]);}
return r;};vha.each=function(cb){var len=array.length;for(var i=0;i<len;i++){cb(array[i],hash[array[i]]);}};vha.dump=function(html){var str="";vha.each(function(name,val){str+="name: "+name+" val: "+JSON.stringify(val)+(html?"<br>":"\n");});return str;};};$.verto.liveArray=function(verto,context,name,config){var la=this;var lastSerno=0;var binding=null;var user_obj=config.userObj;var local=false;hashArray.call(la);la._add=la.add;la._del=la.del;la._reorder=la.reorder;la._clear=la.clear;la.context=context;la.name=name;la.user_obj=user_obj;la.verto=verto;la.broadcast=function(channel,obj){verto.broadcast(channel,obj);};la.errs=0;la.clear=function(){la._clear();lastSerno=0;if(la.onChange){la.onChange(la,{action:"clear"});}};la.checkSerno=function(serno){if(serno<0){return true;}
if(lastSerno>0&&serno!=(lastSerno+1)){if(la.onErr){la.onErr(la,{lastSerno:lastSerno,serno:serno});}
la.errs++;console.debug(la.errs);if(la.errs<3){la.bootstrap(la.user_obj);}
return false;}else{lastSerno=serno;return true;}};la.reorder=function(serno,a){if(la.checkSerno(serno)){la._reorder(a);if(la.onChange){la.onChange(la,{serno:serno,action:"reorder"});}}};la.init=function(serno,val,key,index){if(key===null||key===undefined){key=serno;}
if(la.checkSerno(serno)){if(la.onChange){la.onChange(la,{serno:serno,action:"init",index:index,key:key,data:val});}}};la.bootObj=function(serno,val){if(la.checkSerno(serno)){for(var i in val){la._add(val[i][0],val[i][1]);}
if(la.onChange){la.onChange(la,{serno:serno,action:"bootObj",data:val,redraw:true});}}};la.add=function(serno,val,key,index){if(key===null||key===undefined){key=serno;}
if(la.checkSerno(serno)){var redraw=la._add(key,val,index);if(la.onChange){la.onChange(la,{serno:serno,action:"add",index:index,key:key,data:val,redraw:redraw});}}};la.modify=function(serno,val,key,index){if(key===null||key===undefined){key=serno;}
if(la.checkSerno(serno)){la._add(key,val,index);if(la.onChange){la.onChange(la,{serno:serno,action:"modify",key:key,data:val,index:index});}}};la.del=function(serno,key,index){if(key===null||key===undefined){key=serno;}
if(la.checkSerno(serno)){if(index===null||index<0||index===undefined){index=la.indexOf(key);}
var ok=la._del(key);if(ok&&la.onChange){la.onChange(la,{serno:serno,action:"del",key:key,index:index});}}};var eventHandler=function(v,e,la){var packet=e.data;if(packet.name!=la.name){return;}
switch(packet.action){case"init":la.init(packet.wireSerno,packet.data,packet.hashKey,packet.arrIndex);break;case"bootObj":la.bootObj(packet.wireSerno,packet.data);break;case"add":la.add(packet.wireSerno,packet.data,packet.hashKey,packet.arrIndex);break;case"modify":if(!(packet.arrIndex||packet.hashKey)){console.error("Invalid Packet",packet);}else{la.modify(packet.wireSerno,packet.data,packet.hashKey,packet.arrIndex);}
break;case"del":if(!(packet.arrIndex||packet.hashKey)){console.error("Invalid Packet",packet);}else{la.del(packet.wireSerno,packet.hashKey,packet.arrIndex);}
break;case"clear":la.clear();break;case"reorder":la.reorder(packet.wireSerno,packet.order);break;default:if(la.checkSerno(packet.wireSerno)){if(la.onChange){la.onChange(la,{serno:packet.wireSerno,action:packet.action,data:packet.data});}}
break;}};if(la.context){binding=la.verto.subscribe(la.context,{handler:eventHandler,userData:la,subParams:config.subParams});}
la.destroy=function(){la._clear();la.verto.unsubscribe(binding);};la.sendCommand=function(cmd,obj){var self=la;self.broadcast(self.context,{liveArray:{command:cmd,context:self.context,name:self.name,obj:obj}});};la.bootstrap=function(obj){var self=la;la.sendCommand("bootstrap",obj);};la.changepage=function(obj){var self=la;self.clear();self.broadcast(self.context,{liveArray:{command:"changepage",context:la.context,name:la.name,obj:obj}});};la.heartbeat=function(obj){var self=la;var callback=function(){self.heartbeat.call(self,obj);};self.broadcast(self.context,{liveArray:{command:"heartbeat",context:self.context,name:self.name,obj:obj}});self.hb_pid=setTimeout(callback,30000);};la.bootstrap(la.user_obj);};$.verto.liveTable=function(verto,context,name,jq,config){var dt;var la=new $.verto.liveArray(verto,context,name,{subParams:config.subParams});var lt=this;lt.liveArray=la;lt.dataTable=dt;lt.verto=verto;lt.destroy=function(){if(dt){dt.fnDestroy();}
if(la){la.destroy();}
dt=null;la=null;};la.onErr=function(obj,args){console.error("Error: ",obj,args);};function genRow(data){if(typeof(data[4])==="string"&&data[4].indexOf("{")>-1){var tmp=$.parseJSON(data[4]);data[4]=tmp.oldStatus;data[5]=null;}
return data;}
function genArray(obj){var data=obj.asArray();for(var i in data){data[i]=genRow(data[i]);}
return data;}
la.onChange=function(obj,args){var index=0;var iserr=0;if(!dt){if(!config.aoColumns){if(args.action!="init"){return;}
config.aoColumns=[];for(var i in args.data){config.aoColumns.push({"sTitle":args.data[i]});}}
dt=jq.dataTable(config);}
if(dt&&(args.action=="del"||args.action=="modify")){index=args.index;if(index===undefined&&args.key){index=la.indexOf(args.key);}
if(index===undefined){console.error("INVALID PACKET Missing INDEX\n",args);return;}}
if(config.onChange){config.onChange(obj,args);}
try{switch(args.action){case"bootObj":if(!args.data){console.error("missing data");return;}
dt.fnClearTable();dt.fnAddData(genArray(obj));dt.fnAdjustColumnSizing();break;case"add":if(!args.data){console.error("missing data");return;}
if(args.redraw>-1){dt.fnClearTable();dt.fnAddData(genArray(obj));}else{dt.fnAddData(genRow(args.data));}
dt.fnAdjustColumnSizing();break;case"modify":if(!args.data){return;}
dt.fnUpdate(genRow(args.data),index);dt.fnAdjustColumnSizing();break;case"del":dt.fnDeleteRow(index);dt.fnAdjustColumnSizing();break;case"clear":dt.fnClearTable();break;case"reorder":dt.fnClearTable();dt.fnAddData(genArray(obj));break;case"hide":jq.hide();break;case"show":jq.show();break;}}catch(err){console.error("ERROR: "+err);iserr++;}
if(iserr){obj.errs++;if(obj.errs<3){obj.bootstrap(obj.user_obj);}}else{obj.errs=0;}};la.onChange(la,{action:"init"});};var CONFMAN_SERNO=1;$.verto.conf=function(verto,params){var conf=this;conf.params=$.extend({dialog:null,hasVid:false,laData:null,onBroadcast:null,onLaChange:null,onLaRow:null},params);conf.verto=verto;conf.serno=CONFMAN_SERNO++;createMainModeratorMethods();verto.subscribe(conf.params.laData.modChannel,{handler:function(v,e){if(conf.params.onBroadcast){conf.params.onBroadcast(verto,conf,e.data);}}});verto.subscribe(conf.params.laData.chatChannel,{handler:function(v,e){if(typeof(conf.params.chatCallback)==="function"){conf.params.chatCallback(v,e);}}});};$.verto.conf.prototype.modCommand=function(cmd,id,value){var conf=this;conf.verto.rpcClient.call("verto.broadcast",{"eventChannel":conf.params.laData.modChannel,"data":{"application":"conf-control","command":cmd,"id":id,"value":value}});};$.verto.conf.prototype.destroy=function(){var conf=this;conf.destroyed=true;conf.params.onBroadcast(conf.verto,conf,'destroy');if(conf.params.laData.modChannel){conf.verto.unsubscribe(conf.params.laData.modChannel);}
if(conf.params.laData.chatChannel){conf.verto.unsubscribe(conf.params.laData.chatChannel);}};function createMainModeratorMethods(){$.verto.conf.prototype.listVideoLayouts=function(){this.modCommand("list-videoLayouts",null,null);};$.verto.conf.prototype.play=function(file){this.modCommand("play",null,file);};$.verto.conf.prototype.stop=function(){this.modCommand("stop",null,"all");};$.verto.conf.prototype.record=function(file){this.modCommand("recording",null,["start",file]);};$.verto.conf.prototype.stopRecord=function(){this.modCommand("recording",null,["stop","all"]);};$.verto.conf.prototype.snapshot=function(file){if(!this.params.hasVid){throw'Conference has no video';}
this.modCommand("vid-write-png",null,file);};$.verto.conf.prototype.setVideoLayout=function(layout){if(!this.params.hasVid){throw'Conference has no video';}
this.modCommand("vid-layout",null,layout);};$.verto.conf.prototype.kick=function(memberID){this.modCommand("kick",parseInt(memberID));};$.verto.conf.prototype.muteMic=function(memberID){this.modCommand("tmute",parseInt(memberID));};$.verto.conf.prototype.muteVideo=function(memberID){if(!this.params.hasVid){throw'Conference has no video';}
this.modCommand("tvmute",parseInt(memberID));};$.verto.conf.prototype.presenter=function(memberID){if(!this.params.hasVid){throw'Conference has no video';}
this.modCommand("vid-res-id",parseInt(memberID),"presenter");};$.verto.conf.prototype.videoFloor=function(memberID){if(!this.params.hasVid){throw'Conference has no video';}
this.modCommand("vid-floor",parseInt(memberID),"force");};$.verto.conf.prototype.banner=function(memberID,text){if(!this.params.hasVid){throw'Conference has no video';}
this.modCommand("vid-banner",parseInt(memberID),escape(text));};$.verto.conf.prototype.volumeDown=function(memberID){this.modCommand("volume_out",parseInt(memberID),"down");};$.verto.conf.prototype.volumeUp=function(memberID){this.modCommand("volume_out",parseInt(memberID),"up");};$.verto.conf.prototype.gainDown=function(memberID){this.modCommand("volume_in",parseInt(memberID),"down");};$.verto.conf.prototype.gainUp=function(memberID){this.modCommand("volume_in",parseInt(memberID),"up");};$.verto.conf.prototype.transfer=function(memberID,exten){this.modCommand("transfer",parseInt(memberID),exten);};$.verto.conf.prototype.sendChat=function(message,type){var conf=this;conf.verto.rpcClient.call("verto.broadcast",{"eventChannel":conf.params.laData.chatChannel,"data":{"action":"send","message":message,"type":type}});};}
$.verto.modfuncs={};$.verto.confMan=function(verto,params){var confMan=this;confMan.params=$.extend({tableID:null,statusID:null,mainModID:null,dialog:null,hasVid:false,laData:null,onBroadcast:null,onLaChange:null,onLaRow:null},params);confMan.verto=verto;confMan.serno=CONFMAN_SERNO++;confMan.canvasCount=confMan.params.laData.canvasCount;function genMainMod(jq){var play_id="play_"+confMan.serno;var stop_id="stop_"+confMan.serno;var recording_id="recording_"+confMan.serno;var snapshot_id="snapshot_"+confMan.serno;var rec_stop_id="recording_stop"+confMan.serno;var div_id="confman_"+confMan.serno;var html="<div id='"+div_id+"'><br>"+"<button class='ctlbtn' id='"+play_id+"'>Play</button>"+"<button class='ctlbtn' id='"+stop_id+"'>Stop</button>"+"<button class='ctlbtn' id='"+recording_id+"'>Record</button>"+"<button class='ctlbtn' id='"+rec_stop_id+"'>Record Stop</button>"+
(confMan.params.hasVid?"<button class='ctlbtn' id='"+snapshot_id+"'>PNG Snapshot</button>":"")+"<br><br></div>";jq.html(html);$.verto.modfuncs.change_video_layout=function(id,canvas_id){var val=$("#"+id+" option:selected").text();if(val!=="none"){confMan.modCommand("vid-layout",null,[val,canvas_id]);}};if(confMan.params.hasVid){for(var j=0;j<confMan.canvasCount;j++){var vlayout_id="confman_vid_layout_"+j+"_"+confMan.serno;var vlselect_id="confman_vl_select_"+j+"_"+confMan.serno;var vlhtml="<div id='"+vlayout_id+"'><br>"+"<b>Video Layout Canvas "+(j+1)+"</b> <select onChange='$.verto.modfuncs.change_video_layout(\""+vlayout_id+"\", \""+j+"\")' id='"+vlselect_id+"'></select> "+"<br><br></div>";jq.append(vlhtml);}
$("#"+snapshot_id).click(function(){var file=prompt("Please enter file name","");if(file){confMan.modCommand("vid-write-png",null,file);}});}
$("#"+play_id).click(function(){var file=prompt("Please enter file name","");if(file){confMan.modCommand("play",null,file);}});$("#"+stop_id).click(function(){confMan.modCommand("stop",null,"all");});$("#"+recording_id).click(function(){var file=prompt("Please enter file name","");if(file){confMan.modCommand("recording",null,["start",file]);}});$("#"+rec_stop_id).click(function(){confMan.modCommand("recording",null,["stop","all"]);});}
function genControls(jq,rowid){var x=parseInt(rowid);var kick_id="kick_"+x;var canvas_in_next_id="canvas_in_next_"+x;var canvas_in_prev_id="canvas_in_prev_"+x;var canvas_out_next_id="canvas_out_next_"+x;var canvas_out_prev_id="canvas_out_prev_"+x;var canvas_in_set_id="canvas_in_set_"+x;var canvas_out_set_id="canvas_out_set_"+x;var layer_set_id="layer_set_"+x;var layer_next_id="layer_next_"+x;var layer_prev_id="layer_prev_"+x;var tmute_id="tmute_"+x;var tvmute_id="tvmute_"+x;var vbanner_id="vbanner_"+x;var tvpresenter_id="tvpresenter_"+x;var tvfloor_id="tvfloor_"+x;var box_id="box_"+x;var gainup_id="gain_in_up"+x;var gaindn_id="gain_in_dn"+x;var volup_id="vol_in_up"+x;var voldn_id="vol_in_dn"+x;var transfer_id="transfer"+x;var html="<div id='"+box_id+"'>";html+="<b>General Controls</b><hr noshade>";html+="<button class='ctlbtn' id='"+kick_id+"'>Kick</button>"+"<button class='ctlbtn' id='"+tmute_id+"'>Mute</button>"+"<button class='ctlbtn' id='"+gainup_id+"'>Gain -</button>"+"<button class='ctlbtn' id='"+gaindn_id+"'>Gain +</button>"+"<button class='ctlbtn' id='"+voldn_id+"'>Vol -</button>"+"<button class='ctlbtn' id='"+volup_id+"'>Vol +</button>"+"<button class='ctlbtn' id='"+transfer_id+"'>Transfer</button>";if(confMan.params.hasVid){html+="<br><br><b>Video Controls</b><hr noshade>";html+="<button class='ctlbtn' id='"+tvmute_id+"'>VMute</button>"+"<button class='ctlbtn' id='"+tvpresenter_id+"'>Presenter</button>"+"<button class='ctlbtn' id='"+tvfloor_id+"'>Vid Floor</button>"+"<button class='ctlbtn' id='"+vbanner_id+"'>Banner</button>";if(confMan.canvasCount>1){html+="<br><br><b>Canvas Controls</b><hr noshade>"+"<button class='ctlbtn' id='"+canvas_in_set_id+"'>Set Input Canvas</button>"+"<button class='ctlbtn' id='"+canvas_in_prev_id+"'>Prev Input Canvas</button>"+"<button class='ctlbtn' id='"+canvas_in_next_id+"'>Next Input Canvas</button>"+"<br>"+"<button class='ctlbtn' id='"+canvas_out_set_id+"'>Set Watching Canvas</button>"+"<button class='ctlbtn' id='"+canvas_out_prev_id+"'>Prev Watching Canvas</button>"+"<button class='ctlbtn' id='"+canvas_out_next_id+"'>Next Watching Canvas</button>";}
html+="<br>"+"<button class='ctlbtn' id='"+layer_set_id+"'>Set Layer</button>"+"<button class='ctlbtn' id='"+layer_prev_id+"'>Prev Layer</button>"+"<button class='ctlbtn' id='"+layer_next_id+"'>Next Layer</button>"+"</div>";}
jq.html(html);if(!jq.data("mouse")){$("#"+box_id).hide();}
jq.mouseover(function(e){jq.data({"mouse":true});$("#"+box_id).show();});jq.mouseout(function(e){jq.data({"mouse":false});$("#"+box_id).hide();});$("#"+transfer_id).click(function(){var xten=prompt("Enter Extension");if(xten){confMan.modCommand("transfer",x,xten);}});$("#"+kick_id).click(function(){confMan.modCommand("kick",x);});$("#"+layer_set_id).click(function(){var cid=prompt("Please enter layer ID","");if(cid){confMan.modCommand("vid-layer",x,cid);}});$("#"+layer_next_id).click(function(){confMan.modCommand("vid-layer",x,"next");});$("#"+layer_prev_id).click(function(){confMan.modCommand("vid-layer",x,"prev");});$("#"+canvas_in_set_id).click(function(){var cid=prompt("Please enter canvas ID","");if(cid){confMan.modCommand("vid-canvas",x,cid);}});$("#"+canvas_out_set_id).click(function(){var cid=prompt("Please enter canvas ID","");if(cid){confMan.modCommand("vid-watching-canvas",x,cid);}});$("#"+canvas_in_next_id).click(function(){confMan.modCommand("vid-canvas",x,"next");});$("#"+canvas_in_prev_id).click(function(){confMan.modCommand("vid-canvas",x,"prev");});$("#"+canvas_out_next_id).click(function(){confMan.modCommand("vid-watching-canvas",x,"next");});$("#"+canvas_out_prev_id).click(function(){confMan.modCommand("vid-watching-canvas",x,"prev");});$("#"+tmute_id).click(function(){confMan.modCommand("tmute",x);});if(confMan.params.hasVid){$("#"+tvmute_id).click(function(){confMan.modCommand("tvmute",x);});$("#"+tvpresenter_id).click(function(){confMan.modCommand("vid-res-id",x,"presenter");});$("#"+tvfloor_id).click(function(){confMan.modCommand("vid-floor",x,"force");});$("#"+vbanner_id).click(function(){var text=prompt("Please enter text","");if(text){confMan.modCommand("vid-banner",x,escape(text));}});}
$("#"+gainup_id).click(function(){confMan.modCommand("volume_in",x,"up");});$("#"+gaindn_id).click(function(){confMan.modCommand("volume_in",x,"down");});$("#"+volup_id).click(function(){confMan.modCommand("volume_out",x,"up");});$("#"+voldn_id).click(function(){confMan.modCommand("volume_out",x,"down");});return html;}
var atitle="";var awidth=0;verto.subscribe(confMan.params.laData.chatChannel,{handler:function(v,e){if(typeof(confMan.params.chatCallback)==="function"){confMan.params.chatCallback(v,e);}}});if(confMan.params.laData.role==="moderator"){atitle="Action";awidth=600;if(confMan.params.mainModID){genMainMod($(confMan.params.mainModID));$(confMan.params.displayID).html("Moderator Controls Ready<br><br>");}else{$(confMan.params.mainModID).html("");}
verto.subscribe(confMan.params.laData.modChannel,{handler:function(v,e){if(confMan.params.onBroadcast){confMan.params.onBroadcast(verto,confMan,e.data);}
if(e.data["conf-command"]==="list-videoLayouts"){for(var j=0;j<confMan.canvasCount;j++){var vlselect_id="#confman_vl_select_"+j+"_"+confMan.serno;var vlayout_id="#confman_vid_layout_"+j+"_"+confMan.serno;var x=0;var options;$(vlselect_id).selectmenu({});$(vlselect_id).selectmenu("enable");$(vlselect_id).empty();$(vlselect_id).append(new Option("Choose a Layout","none"));if(e.data.responseData){var rdata=[];for(var i in e.data.responseData){rdata.push(e.data.responseData[i].name);}
options=rdata.sort(function(a,b){var ga=a.substring(0,6)=="group:"?true:false;var gb=b.substring(0,6)=="group:"?true:false;if((ga||gb)&&ga!=gb){return ga?-1:1;}
return((a==b)?0:((a>b)?1:-1));});for(var i in options){$(vlselect_id).append(new Option(options[i],options[i]));x++;}}
if(x){$(vlselect_id).selectmenu('refresh',true);}else{$(vlayout_id).hide();}}}else{if(!confMan.destroyed&&confMan.params.displayID){$(confMan.params.displayID).html(e.data.response+"<br><br>");if(confMan.lastTimeout){clearTimeout(confMan.lastTimeout);confMan.lastTimeout=0;}
confMan.lastTimeout=setTimeout(function(){$(confMan.params.displayID).html(confMan.destroyed?"":"Moderator Controls Ready<br><br>");},4000);}}}});if(confMan.params.hasVid){confMan.modCommand("list-videoLayouts",null,null);}}
var row_callback=null;if(confMan.params.laData.role==="moderator"){row_callback=function(nRow,aData,iDisplayIndex,iDisplayIndexFull){if(!aData[5]){var $row=$('td:eq(5)',nRow);genControls($row,aData);if(confMan.params.onLaRow){confMan.params.onLaRow(verto,confMan,$row,aData);}}};}
confMan.lt=new $.verto.liveTable(verto,confMan.params.laData.laChannel,confMan.params.laData.laName,$(confMan.params.tableID),{subParams:{callID:confMan.params.dialog?confMan.params.dialog.callID:null},"onChange":function(obj,args){$(confMan.params.statusID).text("Conference Members: "+" ("+obj.arrayLen()+" Total)");if(confMan.params.onLaChange){confMan.params.onLaChange(verto,confMan,$.verto.enum.confEvent.laChange,obj,args);}},"aaData":[],"aoColumns":[{"sTitle":"ID","sWidth":"50"},{"sTitle":"Number","sWidth":"250"},{"sTitle":"Name","sWidth":"250"},{"sTitle":"Codec","sWidth":"100"},{"sTitle":"Status","sWidth":confMan.params.hasVid?"200px":"150px"},{"sTitle":atitle,"sWidth":awidth,}],"bAutoWidth":true,"bDestroy":true,"bSort":false,"bInfo":false,"bFilter":false,"bLengthChange":false,"bPaginate":false,"iDisplayLength":1400,"oLanguage":{"sEmptyTable":"The Conference is Empty....."},"fnRowCallback":row_callback});};$.verto.confMan.prototype.modCommand=function(cmd,id,value){var confMan=this;confMan.verto.rpcClient.call("verto.broadcast",{"eventChannel":confMan.params.laData.modChannel,"data":{"application":"conf-control","command":cmd,"id":id,"value":value}});};$.verto.confMan.prototype.sendChat=function(message,type){var confMan=this;confMan.verto.rpcClient.call("verto.broadcast",{"eventChannel":confMan.params.laData.chatChannel,"data":{"action":"send","message":message,"type":type}});};$.verto.confMan.prototype.destroy=function(){var confMan=this;confMan.destroyed=true;if(confMan.lt){confMan.lt.destroy();}
if(confMan.params.laData.chatChannel){confMan.verto.unsubscribe(confMan.params.laData.chatChannel);}
if(confMan.params.laData.modChannel){confMan.verto.unsubscribe(confMan.params.laData.modChannel);}
if(confMan.params.mainModID){$(confMan.params.mainModID).html("");}};$.verto.dialog=function(direction,verto,params){var dialog=this;dialog.params=$.extend({useVideo:verto.options.useVideo,useStereo:verto.options.useStereo,screenShare:false,useCamera:verto.options.deviceParams.useCamera,useMic:verto.options.deviceParams.useMic,useSpeak:verto.options.deviceParams.useSpeak,tag:verto.options.tag,localTag:verto.options.localTag,login:verto.options.login,videoParams:verto.options.videoParams},params);dialog.verto=verto;dialog.direction=direction;dialog.lastState=null;dialog.state=dialog.lastState=$.verto.enum.state.new;dialog.callbacks=verto.callbacks;dialog.answered=false;dialog.attach=params.attach||false;dialog.screenShare=params.screenShare||false;dialog.useCamera=dialog.params.useCamera;dialog.useMic=dialog.params.useMic;dialog.useSpeak=dialog.params.useSpeak;if(dialog.params.callID){dialog.callID=dialog.params.callID;}else{dialog.callID=dialog.params.callID=generateGUID();}
if(dialog.params.tag){dialog.audioStream=document.getElementById(dialog.params.tag);if(dialog.params.useVideo){dialog.videoStream=dialog.audioStream;}}
if(dialog.params.localTag){dialog.localVideo=document.getElementById(dialog.params.localTag);}
dialog.verto.dialogs[dialog.callID]=dialog;var RTCcallbacks={};if(dialog.direction==$.verto.enum.direction.inbound){if(dialog.params.display_direction==="outbound"){dialog.params.remote_caller_id_name=dialog.params.caller_id_name;dialog.params.remote_caller_id_number=dialog.params.caller_id_number;}else{dialog.params.remote_caller_id_name=dialog.params.callee_id_name;dialog.params.remote_caller_id_number=dialog.params.callee_id_number;}
if(!dialog.params.remote_caller_id_name){dialog.params.remote_caller_id_name="Nobody";}
if(!dialog.params.remote_caller_id_number){dialog.params.remote_caller_id_number="UNKNOWN";}
RTCcallbacks.onMessage=function(rtc,msg){console.debug(msg);};RTCcallbacks.onAnswerSDP=function(rtc,sdp){console.error("answer sdp",sdp);};}else{dialog.params.remote_caller_id_name="Outbound Call";dialog.params.remote_caller_id_number=dialog.params.destination_number;}
RTCcallbacks.onICESDP=function(rtc){console.log("RECV "+rtc.type+" SDP",rtc.mediaData.SDP);if(dialog.state==$.verto.enum.state.requesting||dialog.state==$.verto.enum.state.answering||dialog.state==$.verto.enum.state.active){location.reload();return;}
if(rtc.type=="offer"){if(dialog.state==$.verto.enum.state.active){dialog.setState($.verto.enum.state.requesting);dialog.sendMethod("verto.attach",{sdp:rtc.mediaData.SDP});}else{dialog.setState($.verto.enum.state.requesting);dialog.sendMethod("verto.invite",{sdp:rtc.mediaData.SDP});}}else{dialog.setState($.verto.enum.state.answering);dialog.sendMethod(dialog.attach?"verto.attach":"verto.answer",{sdp:dialog.rtc.mediaData.SDP});}};RTCcallbacks.onICE=function(rtc){if(rtc.type=="offer"){console.log("offer",rtc.mediaData.candidate);return;}};RTCcallbacks.onStream=function(rtc,stream){console.log("stream started");};RTCcallbacks.onError=function(e){console.error("ERROR:",e);dialog.hangup({cause:"Device or Permission Error"});};dialog.rtc=new $.FSRTC({callbacks:RTCcallbacks,localVideo:dialog.screenShare?null:dialog.localVideo,useVideo:dialog.params.useVideo?dialog.videoStream:null,useAudio:dialog.audioStream,useStereo:dialog.params.useStereo,videoParams:dialog.params.videoParams,audioParams:verto.options.audioParams,iceServers:verto.options.iceServers,screenShare:dialog.screenShare,useCamera:dialog.useCamera,useMic:dialog.useMic,useSpeak:dialog.useSpeak});dialog.rtc.verto=dialog.verto;if(dialog.direction==$.verto.enum.direction.inbound){if(dialog.attach){dialog.answer();}else{dialog.ring();}}};$.verto.dialog.prototype.invite=function(){var dialog=this;dialog.rtc.call();};$.verto.dialog.prototype.sendMethod=function(method,obj){var dialog=this;obj.dialogParams={};for(var i in dialog.params){if(i=="sdp"&&method!="verto.invite"&&method!="verto.attach"){continue;}
obj.dialogParams[i]=dialog.params[i];}
dialog.verto.rpcClient.call(method,obj,function(e){dialog.processReply(method,true,e);},function(e){dialog.processReply(method,false,e);});};function checkStateChange(oldS,newS){if(newS==$.verto.enum.state.purge||$.verto.enum.states[oldS.name][newS.name]){return true;}
return false;}
function find_name(id){for(var i in $.verto.audioOutDevices){var source=$.verto.audioOutDevices[i];if(source.id===id){return(source.label);}}
return id;}
$.verto.dialog.prototype.setAudioPlaybackDevice=function(sinkId,callback,arg){var dialog=this;var element=dialog.audioStream;if(typeof element.sinkId!=='undefined'){var devname=find_name(sinkId);console.info("Dialog: "+dialog.callID+" Setting speaker:",element,devname);element.setSinkId(sinkId).then(function(){console.log("Dialog: "+dialog.callID+' Success, audio output device attached: '+sinkId);if(callback){callback(true,devname,arg);}}).catch(function(error){var errorMessage=error;if(error.name==='SecurityError'){errorMessage="Dialog: "+dialog.callID+' You need to use HTTPS for selecting audio output '+'device: '+error;}
if(callback){callback(false,null,arg);}
console.error(errorMessage);});}else{console.warn("Dialog: "+dialog.callID+' Browser does not support output device selection.');if(callback){callback(false,null,arg);}}}
$.verto.dialog.prototype.setState=function(state){var dialog=this;if(dialog.state==$.verto.enum.state.ringing){dialog.stopRinging();}
if(dialog.state==state||!checkStateChange(dialog.state,state)){console.error("Dialog "+dialog.callID+": INVALID state change from "+dialog.state.name+" to "+state.name);dialog.hangup();return false;}
console.log("Dialog "+dialog.callID+": state change from "+dialog.state.name+" to "+state.name);dialog.lastState=dialog.state;dialog.state=state;if(!dialog.causeCode){dialog.causeCode=16;}
if(!dialog.cause){dialog.cause="NORMAL CLEARING";}
if(dialog.callbacks.onDialogState){dialog.callbacks.onDialogState(this);}
switch(dialog.state){case $.verto.enum.state.early:case $.verto.enum.state.active:var speaker=dialog.useSpeak;console.info("Using Speaker: ",speaker);if(speaker&&speaker!=="any"){setTimeout(function(){dialog.setAudioPlaybackDevice(speaker);},500);}
break;case $.verto.enum.state.trying:setTimeout(function(){if(dialog.state==$.verto.enum.state.trying){dialog.setState($.verto.enum.state.hangup);}},30000);break;case $.verto.enum.state.purge:dialog.setState($.verto.enum.state.destroy);break;case $.verto.enum.state.hangup:if(dialog.lastState.val>$.verto.enum.state.requesting.val&&dialog.lastState.val<$.verto.enum.state.hangup.val){dialog.sendMethod("verto.bye",{});}
dialog.setState($.verto.enum.state.destroy);break;case $.verto.enum.state.destroy:delete dialog.verto.dialogs[dialog.callID];if(dialog.params.screenShare){dialog.rtc.stopPeer();}else{dialog.rtc.stop();}
break;}
return true;};$.verto.dialog.prototype.processReply=function(method,success,e){var dialog=this;switch(method){case"verto.answer":case"verto.attach":if(success){dialog.setState($.verto.enum.state.active);}else{dialog.hangup();}
break;case"verto.invite":if(success){dialog.setState($.verto.enum.state.trying);}else{dialog.setState($.verto.enum.state.destroy);}
break;case"verto.bye":dialog.hangup();break;case"verto.modify":if(e.holdState){if(e.holdState=="held"){if(dialog.state!=$.verto.enum.state.held){dialog.setState($.verto.enum.state.held);}}else if(e.holdState=="active"){if(dialog.state!=$.verto.enum.state.active){dialog.setState($.verto.enum.state.active);}}}
if(success){}
break;default:break;}};$.verto.dialog.prototype.hangup=function(params){var dialog=this;if(params){if(params.causeCode){dialog.causeCode=params.causeCode;}
if(params.cause){dialog.cause=params.cause;}}
if(dialog.state.val>=$.verto.enum.state.new.val&&dialog.state.val<$.verto.enum.state.hangup.val){dialog.setState($.verto.enum.state.hangup);}else if(dialog.state.val<$.verto.enum.state.destroy){dialog.setState($.verto.enum.state.destroy);}};$.verto.dialog.prototype.stopRinging=function(){var dialog=this;if(dialog.verto.ringer){dialog.verto.ringer.stop();}};$.verto.dialog.prototype.indicateRing=function(){var dialog=this;if(dialog.verto.ringer){dialog.verto.ringer.attr("src",dialog.verto.options.ringFile)[0].play();setTimeout(function(){dialog.stopRinging();if(dialog.state==$.verto.enum.state.ringing){dialog.indicateRing();}},dialog.verto.options.ringSleep);}};$.verto.dialog.prototype.ring=function(){var dialog=this;dialog.setState($.verto.enum.state.ringing);dialog.indicateRing();};$.verto.dialog.prototype.useVideo=function(on){var dialog=this;dialog.params.useVideo=on;if(on){dialog.videoStream=dialog.audioStream;}else{dialog.videoStream=null;}
dialog.rtc.useVideo(dialog.videoStream,dialog.localVideo);};$.verto.dialog.prototype.setMute=function(what){var dialog=this;return dialog.rtc.setMute(what);};$.verto.dialog.prototype.getMute=function(){var dialog=this;return dialog.rtc.getMute();};$.verto.dialog.prototype.setVideoMute=function(what){var dialog=this;return dialog.rtc.setVideoMute(what);};$.verto.dialog.prototype.getVideoMute=function(){var dialog=this;return dialog.rtc.getVideoMute();};$.verto.dialog.prototype.useStereo=function(on){var dialog=this;dialog.params.useStereo=on;dialog.rtc.useStereo(on);};$.verto.dialog.prototype.dtmf=function(digits){var dialog=this;if(digits){dialog.sendMethod("verto.info",{dtmf:digits});}};$.verto.dialog.prototype.transfer=function(dest,params){var dialog=this;if(dest){dialog.sendMethod("verto.modify",{action:"transfer",destination:dest,params:params});}};$.verto.dialog.prototype.hold=function(params){var dialog=this;dialog.sendMethod("verto.modify",{action:"hold",params:params});};$.verto.dialog.prototype.unhold=function(params){var dialog=this;dialog.sendMethod("verto.modify",{action:"unhold",params:params});};$.verto.dialog.prototype.toggleHold=function(params){var dialog=this;dialog.sendMethod("verto.modify",{action:"toggleHold",params:params});};$.verto.dialog.prototype.message=function(msg){var dialog=this;var err=0;msg.from=dialog.params.login;if(!msg.to){console.error("Missing To");err++;}
if(!msg.body){console.error("Missing Body");err++;}
if(err){return false;}
dialog.sendMethod("verto.info",{msg:msg});return true;};$.verto.dialog.prototype.answer=function(params){var dialog=this;if(!dialog.answered){if(!params){params={};}
params.sdp=dialog.params.sdp;if(params){if(params.useVideo){dialog.useVideo(true);}
dialog.params.callee_id_name=params.callee_id_name;dialog.params.callee_id_number=params.callee_id_number;if(params.useCamera){dialog.useCamera=params.useCamera;}
if(params.useMic){dialog.useMic=params.useMic;}
if(params.useSpeak){dialog.useSpeak=params.useSpeak;}}
dialog.rtc.createAnswer(params);dialog.answered=true;}};$.verto.dialog.prototype.handleAnswer=function(params){var dialog=this;dialog.gotAnswer=true;if(dialog.state.val>=$.verto.enum.state.active.val){return;}
if(dialog.state.val>=$.verto.enum.state.early.val){dialog.setState($.verto.enum.state.active);}else{if(dialog.gotEarly){console.log("Dialog "+dialog.callID+" Got answer while still establishing early media, delaying...");}else{console.log("Dialog "+dialog.callID+" Answering Channel");dialog.rtc.answer(params.sdp,function(){dialog.setState($.verto.enum.state.active);},function(e){console.error(e);dialog.hangup();});console.log("Dialog "+dialog.callID+"ANSWER SDP",params.sdp);}}};$.verto.dialog.prototype.cidString=function(enc){var dialog=this;var party=dialog.params.remote_caller_id_name+(enc?" <":" <")+dialog.params.remote_caller_id_number+(enc?">":">");return party;};$.verto.dialog.prototype.sendMessage=function(msg,params){var dialog=this;if(dialog.callbacks.onMessage){dialog.callbacks.onMessage(dialog.verto,dialog,msg,params);}};$.verto.dialog.prototype.handleInfo=function(params){var dialog=this;dialog.sendMessage($.verto.enum.message.info,params.msg);};$.verto.dialog.prototype.handleDisplay=function(params){var dialog=this;if(params.display_name){dialog.params.remote_caller_id_name=params.display_name;}
if(params.display_number){dialog.params.remote_caller_id_number=params.display_number;}
dialog.sendMessage($.verto.enum.message.display,{});};$.verto.dialog.prototype.handleMedia=function(params){var dialog=this;if(dialog.state.val>=$.verto.enum.state.early.val){return;}
dialog.gotEarly=true;dialog.rtc.answer(params.sdp,function(){console.log("Dialog "+dialog.callID+"Establishing early media");dialog.setState($.verto.enum.state.early);if(dialog.gotAnswer){console.log("Dialog "+dialog.callID+"Answering Channel");dialog.setState($.verto.enum.state.active);}},function(e){console.error(e);dialog.hangup();});console.log("Dialog "+dialog.callID+"EARLY SDP",params.sdp);};$.verto.ENUM=function(s){var i=0,o={};s.split(" ").map(function(x){o[x]={name:x,val:i++};});return Object.freeze(o);};$.verto.enum={};$.verto.enum.states=Object.freeze({new:{requesting:1,recovering:1,ringing:1,destroy:1,answering:1,hangup:1},requesting:{trying:1,hangup:1,active:1},recovering:{answering:1,hangup:1},trying:{active:1,early:1,hangup:1},ringing:{answering:1,hangup:1},answering:{active:1,hangup:1},active:{answering:1,requesting:1,hangup:1,held:1},held:{hangup:1,active:1},early:{hangup:1,active:1},hangup:{destroy:1},destroy:{},purge:{destroy:1}});$.verto.enum.state=$.verto.ENUM("new requesting trying recovering ringing answering early active held hangup destroy purge");$.verto.enum.direction=$.verto.ENUM("inbound outbound");$.verto.enum.message=$.verto.ENUM("display info pvtEvent");$.verto.enum=Object.freeze($.verto.enum);$.verto.saved=[];$.verto.unloadJobs=[];$(window).bind('beforeunload',function(){for(var f in $.verto.unloadJobs){$.verto.unloadJobs[f]();}
for(var i in $.verto.saved){var verto=$.verto.saved[i];if(verto){verto.purge();verto.logout();}}
return $.verto.warnOnUnload;});$.verto.videoDevices=[];$.verto.audioInDevices=[];$.verto.audioOutDevices=[];var checkDevices=function(runtime){console.info("enumerating devices");var aud_in=[],aud_out=[],vid=[];if((!navigator.mediaDevices||!navigator.mediaDevices.enumerateDevices)&&MediaStreamTrack.getSources){MediaStreamTrack.getSources(function(media_sources){for(var i=0;i<media_sources.length;i++){if(media_sources[i].kind=='video'){vid.push(media_sources[i]);}else{aud_in.push(media_sources[i]);}}
$.verto.videoDevices=vid;$.verto.audioInDevices=aud_in;console.info("Audio Devices",$.verto.audioInDevices);console.info("Video Devices",$.verto.videoDevices);runtime(true);});}else{if(!navigator.mediaDevices||!navigator.mediaDevices.enumerateDevices){console.log("enumerateDevices() not supported.");return;}
navigator.mediaDevices.enumerateDevices().then(function(devices){devices.forEach(function(device){console.log(device);console.log(device.kind+": "+device.label+" id = "+device.deviceId);if(device.kind==="videoinput"){vid.push({id:device.deviceId,kind:"video",label:device.label});}else if(device.kind==="audioinput"){aud_in.push({id:device.deviceId,kind:"audio_in",label:device.label});}else if(device.kind==="audiooutput"){aud_out.push({id:device.deviceId,kind:"audio_out",label:device.label});}});$.verto.videoDevices=vid;$.verto.audioInDevices=aud_in;$.verto.audioOutDevices=aud_out;console.info("Audio IN Devices",$.verto.audioInDevices);console.info("Audio Out Devices",$.verto.audioOutDevices);console.info("Video Devices",$.verto.videoDevices);runtime(true);}).catch(function(err){console.log(" Device Enumeration ERROR: "+err.name+": "+err.message);runtime(false);});}};$.verto.refreshDevices=function(runtime){checkDevices(runtime);}
$.verto.init=function(obj,runtime){if(!obj){obj={};}
if(!obj.skipPermCheck&&!obj.skipDeviceCheck){$.FSRTC.checkPerms(function(status){checkDevices(runtime);},true,true);}else if(obj.skipPermCheck&&!obj.skipDeviceCheck){checkDevices(runtime);}else if(!obj.skipPermCheck&&obj.skipDeviceCheck){$.FSRTC.checkPerms(function(status){runtime(status);},true,true);}else{runtime(null);}}
$.verto.genUUID=function(){return generateGUID();}})(jQuery);
|
import React from 'react';
import createSvg from './utils/createSvg';
export default createSvg(<path d="M6 19c0 1.1.9 2 2 2h8c1.1 0 2-.9 2-2V9c0-1.1-.9-2-2-2H8c-1.1 0-2 .9-2 2v10zM18 4h-2.5l-.71-.71c-.18-.18-.44-.29-.7-.29H9.91c-.26 0-.52.11-.7.29L8.5 4H6c-.55 0-1 .45-1 1s.45 1 1 1h12c.55 0 1-.45 1-1s-.45-1-1-1z" />, 'DeleteRound', '0 0 24 24');
|
import { apiURL, getTabla } from "../script.js";
const resource = "/clientes";
let container = document.querySelector("#tabla");
const drawTablaCliente = async ()=>
{
const btnModificar = document.createElement("button");
btnModificar.setAttribute("type", "button");
btnModificar.setAttribute("class", "btn btn-warning me-4 btn-modificar");
btnModificar.innerHTML = "Modificar";
const btnEliminar = document.createElement("button");
btnEliminar.setAttribute("type", "button");
btnEliminar.setAttribute("class", "btn btn-danger btn-eliminar");
btnEliminar.innerHTML = "Eliminar";
await getTabla(container,apiURL + resource,[btnModificar,btnEliminar]);
const botonesModificar = document.querySelectorAll(".btn-modificar")
botonesModificar.forEach(btn => {
btn.addEventListener("click", function (e) {
editarCliente(e.target.getAttributeNode("data-id").value)
})
})
const botonesEliminar = document.querySelectorAll(".btn-eliminar")
botonesEliminar.forEach(btn => {
btn.addEventListener("click", function (e) {
borrarCliente(e.target.getAttributeNode("data-id").value)
})
})
}
const borrarCliente = id => {
fetch(apiURL + resource + "/" + id, {
method: "DELETE",
mode: 'cors',
})
.then(r => {
if (r.ok) {
toastOK.show()
drawTablaCliente()
}
else {
toastNotOK.show()
}
return r.json()
})
.then(json => {
})
.catch(Exc => {
});
}
const toastOKLive = document.getElementById('eliminado')
const toastOKNotLive = document.getElementById('noEliminado')
const toastOK = new bootstrap.Toast(toastOKLive)
const toastNotOK = new bootstrap.Toast(toastOKNotLive)
document.addEventListener("DOMContentLoaded", drawTablaCliente);
let toEdit = {};
const editarCliente = id => {
fetch(apiURL + resource + "/" + id, {
method: "GET",
mode: 'cors',
})
.then(r => {
if (!r.ok) {
console.error("error")
}
return r.json()
})
.then(json => {
toEdit = json
openEditModal()
})
}
const modalToggle = new bootstrap.Modal(document.getElementById('editModal'), {
keyboard: false
})
const formNombre = document.querySelector("input[name='nombre']");
const formApellido = document.querySelector("input[name='apellido']");
const formDni = document.querySelector("input[name='dni']");
const openEditModal = () => {
formNombre.value = toEdit.nombre;
formApellido.value = toEdit.apellido;
formDni.value = toEdit.dni;
modalToggle.toggle()
}
const toastGuardado = document.getElementById('guardado')
const toastOkGuardado = new bootstrap.Toast(toastGuardado)
const updateCliente = () => {
toEdit.nombre = formNombre.value;
toEdit.apellido = formApellido.value;
toEdit.dni = formDni.value;
fetch(apiURL + resource + "/" + toEdit.id, {
"method": "PUT",
"mode": "cors",
"headers": { "Content-Type": "application/json" },
"body": JSON.stringify(toEdit)
})
.then(r => {
if (!r.ok) {
console.error("error")
}
return r.json()
})
.then(json => {
toastOkGuardado.show()
drawTablaCliente()
})
.catch(Exc => console.error(Exc));
}
const guardarbtn = document.querySelector("#guardar")
guardarbtn.addEventListener("click", updateCliente);
|
"use strict";
import Id from "./Id";
if ( __CLIENT__ ) {
var THREE = require( "three" );
}
/**
* Entity
*/
export default class Entity extends Id {
static ID = 0;
/**
* Config
* @type {{}}
* @protected
*/
_config = {};
/**
* Create an entity
* @param {String} name
* @param {Object} [config]
*/
constructor( name, config = {} ) {
super( name );
// Config
this._config = config;
// Physics
this._body = null;
// Object 3D
this._object3D = null;
// Components
this._components = [];
}
/**
* Config
* @returns {{}}
*/
get config() {
return this._config;
}
/**
* Scene
* @returns {Scene}
*/
get scene() {
return this._scene;
}
/**
* Scene
* @params {Scene} scene
*/
set scene( scene ) {
this._scene = scene;
}
/**
* Physics body
* @returns {CANNON.body}
*/
get body() {
return this._body;
}
/**
* Object 3D
* @returns {THREE.Object3D}
*/
get object3D() {
return this._object3D;
}
/**
* Components
* @returns {Array<Component>}
*/
get components() {
return this._components;
}
/*get position() {
return this._body ? this._body.position : this._object3D.position;
}
get rotation() {
return this._body ? this._body.position : this._object3D.rotation;
}
get quaternion() {
return this._body ? this._body.position : this._object3D.quaternion;
}*/
/**
* Add an component to the entity
* @param {Component} component
*/
addComponent( component ) {
if ( !component ) {
throw new Error( "You can't add a null component" );
}
component.entity = this;
this._components.push( component );
if ( this._scene && this._scene.initialized ) {
component.init();
}
}
/**
* Remove an component from the entity
* @param {Component} component
*/
removeComponent( component ) {
if ( !component ) {
throw new Error( "You can't remove a null component" );
}
if ( component.entity != this ) {
throw new Error( `You can't remove component ${component.name} from ${this.name} as this scene does not own the component` );
}
component.entity = null;
this._components.splice( this._components.indexOf( component ), 1 );
}
/**
* Add THREE.Object3D object to the stage (THREE.Scene)
* @param {THREE.Object3D} object3D
*/
addObject( object3D ) {
this._object3D.add( object3D );
}
/**
* Remove THREE.Object3D object from the stage (THREE.Scene)
* @param {THREE.Object3D} object3D
*/
removeObject( object3D ) {
this._object3D.remove( object3D );
}
init() {
if ( this._body ) {
this._body.__id = this._name;
this._scene.physics.addBody(this._body);
}
if ( __CLIENT__ ) {
this._object3D = new THREE.Object3D();
this._scene.stage.add( this._object3D );
}
this._components.forEach( component => component.init() );
}
/**
* Update the entity
* @param {number} dt - Time delta since last update
*/
update( dt ) {
// Entities update
this._components.forEach( component => component.update( dt ) );
if ( __CLIENT__ ) {
if ( this._body ) {
this._object3D.position.copy( this._body.position );
this._object3D.quaternion.copy( this._body.quaternion );
}
}
}
/**
* Destroy an entity
*/
dispose() {
if ( this._body ) {
this._scene.physics.removeBody(this.body);
}
this._components.forEach( components => components.dispose() );
if (__CLIENT__) {
this._scene.stage.remove( this._object3D );
this._object3D = null;
}
this._scene = null;
}
}
|
################################################################################
# The MIT License
#
# Copyright (c) 2019-2021, Prominence AI, Inc.
#
# 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.
################################################################################
#!/usr/bin/env python
import sys
import time
from dsl import *
uri_h265 = "/opt/nvidia/deepstream/deepstream/samples/streams/sample_1080p_h265.mp4"
# Filespecs for the Primary GIE
primary_infer_config_file = \
'/opt/nvidia/deepstream/deepstream/samples/configs/deepstream-app/config_infer_primary_nano.txt'
primary_model_engine_file = \
'/opt/nvidia/deepstream/deepstream/samples/models/Primary_Detector_Nano/resnet10.caffemodel_b8_gpu0_fp16.engine'
TILER_WIDTH = DSL_DEFAULT_STREAMMUX_WIDTH
TILER_HEIGHT = DSL_DEFAULT_STREAMMUX_HEIGHT
#WINDOW_WIDTH = TILER_WIDTH
#WINDOW_HEIGHT = TILER_HEIGHT
WINDOW_WIDTH = 1280
WINDOW_HEIGHT = 720
SHOW_SOURCE_TIMEOUT = 2
# Function to be called on End-of-Stream (EOS) event
def eos_event_listener(client_data):
print('Pipeline EOS event')
dsl_pipeline_stop('pipeline')
dsl_main_loop_quit()
##
# Function to be called on XWindow Delete event
##
def xwindow_delete_event_handler(client_data):
print('delete window event')
dsl_pipeline_stop('pipeline')
dsl_main_loop_quit()
##
# Function to be called on every change of Pipeline state
##
def state_change_listener(old_state, new_state, client_data):
print('previous state = ', old_state, ', new state = ', new_state)
if new_state == DSL_STATE_PLAYING:
dsl_pipeline_dump_to_dot('pipeline', "state-playing")
##
# Function to be called on XWindow KeyRelease event
##
def xwindow_key_event_handler(key_string, client_data):
print('key released = ', key_string)
global SHOW_SOURCE_TIMEOUT
# P = pause pipline
if key_string.upper() == 'P':
dsl_pipeline_pause('pipeline')
# R = resume pipeline, if paused
elif key_string.upper() == 'R':
dsl_pipeline_play('pipeline')
# Q or Esc = quit application
elif key_string.upper() == 'Q' or key_string == '':
dsl_pipeline_stop('pipeline')
dsl_main_loop_quit()
# if one of the unique soure Ids, show source
elif key_string >= '0' and key_string <= '3':
retval, source = dsl_source_name_get(int(key_string))
if retval == DSL_RETURN_SUCCESS:
dsl_tiler_source_show_set('tiler', source=source, timeout=SHOW_SOURCE_TIMEOUT, has_precedence=True)
# C = cycle All sources
elif key_string.upper() == 'C':
dsl_tiler_source_show_cycle('tiler', timeout=SHOW_SOURCE_TIMEOUT)
# A = show All sources
elif key_string.upper() == 'A':
dsl_tiler_source_show_all('tiler')
##
# Function to be called on XWindow Button Press event
##
def xwindow_button_event_handler(button, x_pos, y_pos, client_data):
print('button = ', button, ' pressed at x = ', x_pos, ' y = ', y_pos)
global SHOW_SOURCE_TIMEOUT
if (button == Button1):
# get the current XWindow dimensions - the XWindow was overlayed with our Window Sink
retval, width, height = dsl_pipeline_xwindow_dimensions_get('pipeline')
# call the Tiler to show the source based on the x and y button cooridantes
# and the current window dimensions obtained from the XWindow
dsl_tiler_source_show_select('tiler', x_pos, y_pos, width, height, timeout=SHOW_SOURCE_TIMEOUT)
def main(args):
# Since we're not using args, we can Let DSL initialize GST on first call
while True:
retval = dsl_display_type_rgba_color_new('full-white', red=1.0, green=1.0, blue=1.0, alpha = 1.0)
if retval != DSL_RETURN_SUCCESS:
return retval
retval = dsl_display_type_rgba_font_new('arial-14-white', font='arial', size=14, color='full-white')
if retval != DSL_RETURN_SUCCESS:
return retval
retval = dsl_display_type_source_number_new('source-number',
x_offset=15, y_offset=20, font='arial-14-white', has_bg_color=False, bg_color='full-white')
if retval != DSL_RETURN_SUCCESS:
return retval
# Create a new Action to display all the Source Info
retval = dsl_ode_action_display_meta_add_new('add-source-info', display_type='source-number')
if retval != DSL_RETURN_SUCCESS:
return retval
# Create an Always triger to overlay our Display Info on every frame
retval = dsl_ode_trigger_always_new('always-trigger', source=DSL_ODE_ANY_SOURCE, when=DSL_ODE_PRE_OCCURRENCE_CHECK)
if retval != DSL_RETURN_SUCCESS:
return retval
retval = dsl_ode_trigger_action_add('always-trigger', action='add-source-info')
if retval != DSL_RETURN_SUCCESS:
return retval
# New ODE Handler to handle all ODE Triggers with their Areas and Actions
retval = dsl_pph_ode_new('ode-handler')
if retval != DSL_RETURN_SUCCESS:
break
retval = dsl_pph_ode_trigger_add('ode-handler', trigger='always-trigger')
if retval != DSL_RETURN_SUCCESS:
break
# New URI File Source
retval = dsl_source_uri_new('uri-source-1', uri_h265, False, False, 1)
if retval != DSL_RETURN_SUCCESS:
break
dsl_source_uri_new('uri-source-2', uri_h265, False, False, 1)
dsl_source_uri_new('uri-source-3', uri_h265, False, False, 1)
dsl_source_uri_new('uri-source-4', uri_h265, False, False, 1)
# New Primary GIE using the filespecs above, with interval and Id
retval = dsl_infer_gie_primary_new('primary-gie',
primary_infer_config_file, primary_model_engine_file, 1)
if retval != DSL_RETURN_SUCCESS:
break
# New KTL Tracker, setting max width and height of input frame
retval = dsl_tracker_ktl_new('ktl-tracker', 480, 272)
if retval != DSL_RETURN_SUCCESS:
break
# New Tiler, setting width and height, use default cols/rows set by source count
retval = dsl_tiler_new('tiler', TILER_WIDTH, TILER_HEIGHT)
if retval != DSL_RETURN_SUCCESS:
break
# Add the ODE Pad Probe Handler to the Sink pad of the Tiler
retval = dsl_tiler_pph_add('tiler', 'ode-handler', DSL_PAD_SINK)
if retval != DSL_RETURN_SUCCESS:
break
# New OSD with text, clock and bbox display all enabled.
retval = dsl_osd_new('on-screen-display',
text_enabled=True, clock_enabled=True, bbox_enabled=True, mask_enabled=False)
if retval != DSL_RETURN_SUCCESS:
break
# New Overlay Sink, 0 x/y offsets and same dimensions as Tiled Display
retval = dsl_sink_window_new('window-sink', 0, 0, WINDOW_WIDTH, WINDOW_HEIGHT)
if retval != DSL_RETURN_SUCCESS:
break
# Add all the components to our pipeline
retval = dsl_pipeline_new_component_add_many('pipeline',
['uri-source-1', 'uri-source-2', 'uri-source-3', 'uri-source-4',
'primary-gie', 'ktl-tracker', 'tiler', 'on-screen-display', 'window-sink', None])
if retval != DSL_RETURN_SUCCESS:
break
# Enabled the XWindow for full-screen-mode
retval = dsl_pipeline_xwindow_fullscreen_enabled_set('pipeline', enabled=True)
if retval != DSL_RETURN_SUCCESS:
break
# Add the EOS listener and XWindow event handler functions defined above
retval = dsl_pipeline_eos_listener_add('pipeline', eos_event_listener, None)
if retval != DSL_RETURN_SUCCESS:
break
retval = dsl_pipeline_xwindow_key_event_handler_add('pipeline', xwindow_key_event_handler, None)
if retval != DSL_RETURN_SUCCESS:
break
retval = dsl_pipeline_xwindow_button_event_handler_add('pipeline', xwindow_button_event_handler, None)
if retval != DSL_RETURN_SUCCESS:
break
retval = dsl_pipeline_xwindow_delete_event_handler_add('pipeline', xwindow_delete_event_handler, None)
if retval != DSL_RETURN_SUCCESS:
break
# Play the pipeline
retval = dsl_pipeline_play('pipeline')
if retval != DSL_RETURN_SUCCESS:
break
dsl_main_loop_run()
break
# Print out the final result
print(dsl_return_value_to_string(retval))
dsl_pipeline_delete_all()
dsl_component_delete_all()
if __name__ == '__main__':
sys.exit(main(sys.argv))
|
from configparser import ConfigParser
from pathlib import Path
class PushoverConfigFile:
token = None
user = None
def __init__(self):
self.reader = ConfigParser()
self.reader.read(self.paths())
try:
self.token = self.reader['Pushover']['token']
self.user = self.reader['Pushover']['user']
except KeyError:
raise KeyError("Create ~/.pushover.ini file with section [Pushover] containing token and user keys")
def paths(self):
return [
'/etc/pushover.ini',
Path.home() / '.pushover.ini',
]
|