text
stringlengths 3
1.05M
|
---|
import 'settings/service/controller';
import 'settings/add/controller';
import 'settings/notifications/controller';
import 'settings/view/controller';
import 'settings/configuration/controller';
import 'settings/directives/sidebar/sidebar';
import 'settings/directives/topnav/topnav';
import angular from 'angular';
import app from 'settings/app';
import core from 'common/core';
export default app.controller('SettingsCtrl', ($scope, $route) => {
$scope.serviceId = null;
$scope.serviceTypeId = null;
const update = function() {
if ($scope.view === 'service') {
updateForExistingService();
} else if ($scope.view === 'new') {
updateForNewService();
}
};
const updateForExistingService = function() {
if ($scope.serviceTypes && $scope.serviceConfigs && $scope.serviceId) {
$scope.config = find($scope.serviceConfigs, 'name', $scope.serviceId) || {};
$scope.service = find($scope.serviceTypes, 'baseUrl', $scope.config.baseUrl);
}
};
const updateForNewService = function() {
if ($scope.serviceTypes && $scope.serviceId && $scope.serviceTypeId) {
$scope.service = find($scope.serviceTypes, 'baseUrl', $scope.serviceTypeId);
$scope.config = angular.copy($scope.service.defaultConfig);
$scope.config.name = $scope.serviceId;
} else {
$scope.config = null;
$scope.service = null;
}
};
var find = function(list, field, value) {
var item = list.filter(function(item) {
return item[field] === value;
})[0];
return item ? item : null;
};
core.configurations.subscribe(function(configs) {
$scope.$evalAsync(function() {
$scope.serviceConfigs = configs;
update();
});
});
core.availableServices(function(types) {
$scope.serviceTypes = types;
update();
});
$scope.$on('$routeChangeSuccess', function(event, routeData) {
$scope.serviceId = routeData.params.serviceName || null;
$scope.serviceTypeId = routeData.params.serviceTypeId || null;
$scope.view = $route.current.view;
update();
});
});
|
from logging import raiseExceptions
from django.shortcuts import render
from rest_framework.generics import CreateAPIView
from rest_framework import status
from .models import *
from .serializers import *
from rest_framework.response import Response
import sys
from .autograder.autograder.t5_autograder import *
from .autograder.autograder.svm import *
def myfunc(text,ref_ans1,model1):
score1=find_correctness(text,ref_ans1,model1)
score2=find_correctness_svm(text,ref_ans1)
avg_score=(score1+score2)/2
if score1 == 5.0:
return score1
else:
return avg_score
# Create your views here.
class EssayGradeView(CreateAPIView):
queryset=Essay
serializer_class=EssaySerializer
def post(self,request):
try:
text=request.data['text']
ref_ans1=request.data['ref_Ans1']
score=myfunc(text,ref_ans1,model)
request.data['score']=score
serializer=self.get_serializer(data=request.data)
#print(request.data['score'])
if serializer.is_valid():
self.perform_create(serializer)
return Response({'status':True,'score':score},status=status.HTTP_200_OK)
else:
return Response(serializer.errors,status=status.HTTP_200_OK)
except KeyError:
return Response({'status':False,'message':str(sys.exc_info()[1]) + " is missing in request."},status=status.HTTP_200_OK)
except Exception as e:
return Response({'status':False,'error':str(e)},status=status.HTTP_200_OK)
except ValueError:
return Response({'ValueError':str(sys.exc_info()[1])},status=status.HTTP_200_OK)
|
/*
* Copyright (c) 2016, Globo.com (https://github.com/globocom)
*
* License: MIT
*/
export default {
base: {
backgroundColor: "transparent",
border: "none",
fontSize: "14px",
color: "#fafafa",
width: "250px",
margin: "20px",
padding: 0,
":focus": {
outline: "none"
}
}
};
|
(function(){var loadHandler=window['sl_{969A703B-9AB9-40E7-AD41-0EA45B16039B}'];loadHandler&&loadHandler(1, '<div id="spr0_39e951"><div id="spr1_39e951" class="kern slide"><img id="img0_39e951" src="data/img0.png" width="960px" height="540px" alt="" style="left:0px;top:0px;"/></div><div id="spr2_39e951" class="kern slide"><div id="spr3_39e951" style="left:66px;top:28.75px;"><div style="width:0px;"><span id="txt0_39e951" data-width="422.748047" style="left:7.2px;top:18.23px;">Koliko ruku ima Dusan ?</span></div></div><div id="spr4_39e951" style="left:66px;top:143.75px;"><div style="width:0px;"><span id="txt1_39e951" class="nokern relpos" style="left:7.2px;top:1.055px;">•</span><span id="txt2_39e951" class="relpos" style="left:15.397px;top:-2.889px;">1</span></div><div style="width:0px;"><span id="txt3_39e951" data-width="13.398438" style="left:39.45px;top:-2.889px;">. </span></div><div style="width:0px;"><span id="txt4_39e951" style="left:52.95px;top:-2.889px;">2</span></div><div style="width:0px;"><span id="txt5_39e951" class="nokern relpos" style="left:7.2px;top:41.295px;">•</span><span id="txt6_39e951" class="relpos" style="left:15.397px;top:37.351px;">2</span></div><div style="width:0px;"><span id="txt7_39e951" data-width="13.398438" style="left:39.45px;top:37.351px;">. </span></div><div style="width:0px;"><span id="txt8_39e951" style="left:52.95px;top:37.351px;">3</span></div><div style="width:0px;"><span id="txt9_39e951" class="nokern relpos" style="left:7.2px;top:81.535px;">•</span><span id="txt10_39e951" class="relpos" style="left:15.397px;top:77.591px;">3</span></div><div style="width:0px;"><span id="txt11_39e951" data-width="13.398438" style="left:39.45px;top:77.591px;">. </span></div><div style="width:0px;"><span id="txt12_39e951" style="left:52.95px;top:77.591px;">4</span></div><div style="width:0px;"><span id="txt13_39e951" class="nokern relpos" style="left:7.2px;top:121.775px;">•</span><span id="txt14_39e951" class="relpos" style="left:15.397px;top:117.831px;">4</span></div><div style="width:0px;"><span id="txt15_39e951" data-width="13.398438" style="left:39.45px;top:117.831px;">. </span></div><div style="width:0px;"><span id="txt16_39e951" style="left:52.95px;top:117.831px;">7</span></div><div style="width:0px;"><span id="txt17_39e951" data-width="119.492188" style="left:7.2px;top:158.071px;">answer->1</span></div></div></div></div>');})(); |
Cufon.replace('h3, .list-2 .item', { fontFamily: 'NewsGoth', hover:true });
Cufon.replace('.menu li a, h1 strong, .pagination strong, .banner strong', { fontFamily: 'NewsGoth bold', hover:true });
Cufon.replace('h2', { fontFamily: 'Vegur', hover:true });
|
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports["default"] = void 0;
var _react = _interopRequireDefault(require("react"));
var _reactC3js = _interopRequireDefault(require("react-c3js"));
var _ChartConstants = require("./ChartConstants");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }
function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }
var PieChart = (0, _ChartConstants.getComposer)('PIE_CHART')(function (_ref) {
var className = _ref.className,
type = _ref.type,
data = _ref.data,
props = _objectWithoutProperties(_ref, ["className", "type", "data"]);
return _react["default"].createElement(_reactC3js["default"], _extends({
className: className,
type: type,
data: data
}, props));
});
var _default = PieChart;
exports["default"] = _default; |
import { matchFilter } from '@keystonejs/test-utils';
import Text from '../Text';
import DateTime from './';
export const name = 'DateTime';
export { DateTime as type };
export const exampleValue = '"1990-12-31T12:34:56.789+01:23"';
export const getTestFields = () => {
return {
name: { type: Text },
lastOnline: { type: DateTime },
};
};
export const initItems = () => {
return [
{ name: 'person1', lastOnline: '1990-12-31T12:34:56.789+01:23' },
{ name: 'person2', lastOnline: '2000-01-20T00:08:00.000+10:00' },
{ name: 'person3', lastOnline: '1950-10-01T23:59:59.999-10:00' },
{ name: 'person4', lastOnline: '1666-04-12T00:08:00.000+10:00' },
{ name: 'person5', lastOnline: null },
];
};
export const filterTests = withKeystone => {
const match = (keystone, filter, targets, forceSortBy = 'name') =>
matchFilter(keystone, filter, '{ name, lastOnline }', targets, forceSortBy);
test(
'No filter',
withKeystone(({ keystone }) =>
match(keystone, undefined, [
{ name: 'person1', lastOnline: '1990-12-31T12:34:56.789+01:23' },
{ name: 'person2', lastOnline: '2000-01-20T00:08:00.000+10:00' },
{ name: 'person3', lastOnline: '1950-10-01T23:59:59.999-10:00' },
{ name: 'person4', lastOnline: '1666-04-12T00:08:00.000+10:00' },
{ name: 'person5', lastOnline: null },
])
)
);
test(
'Empty filter',
withKeystone(({ keystone }) =>
match(keystone, 'where: { }', [
{ name: 'person1', lastOnline: '1990-12-31T12:34:56.789+01:23' },
{ name: 'person2', lastOnline: '2000-01-20T00:08:00.000+10:00' },
{ name: 'person3', lastOnline: '1950-10-01T23:59:59.999-10:00' },
{ name: 'person4', lastOnline: '1666-04-12T00:08:00.000+10:00' },
{ name: 'person5', lastOnline: null },
])
)
);
test(
'Filter: lastOnline',
withKeystone(({ keystone }) =>
match(keystone, 'where: { lastOnline: "2000-01-20T00:08:00.000+10:00" }', [
{ name: 'person2', lastOnline: '2000-01-20T00:08:00.000+10:00' },
])
)
);
test(
'Filter: lastOnline_not',
withKeystone(({ keystone }) =>
match(keystone, 'where: { lastOnline_not: "2000-01-20T00:08:00.000+10:00" }', [
{ name: 'person1', lastOnline: '1990-12-31T12:34:56.789+01:23' },
{ name: 'person3', lastOnline: '1950-10-01T23:59:59.999-10:00' },
{ name: 'person4', lastOnline: '1666-04-12T00:08:00.000+10:00' },
{ name: 'person5', lastOnline: null },
])
)
);
test(
'Filter: lastOnline_not null',
withKeystone(({ keystone }) =>
match(keystone, 'where: { lastOnline_not: null }', [
{ name: 'person1', lastOnline: '1990-12-31T12:34:56.789+01:23' },
{ name: 'person2', lastOnline: '2000-01-20T00:08:00.000+10:00' },
{ name: 'person3', lastOnline: '1950-10-01T23:59:59.999-10:00' },
{ name: 'person4', lastOnline: '1666-04-12T00:08:00.000+10:00' },
])
)
);
test(
'Filter: lastOnline_lt',
withKeystone(({ keystone }) =>
match(keystone, 'where: { lastOnline_lt: "1950-10-01T23:59:59.999-10:00" }', [
{ name: 'person4', lastOnline: '1666-04-12T00:08:00.000+10:00' },
])
)
);
test(
'Filter: lastOnline_lte',
withKeystone(({ keystone }) =>
match(keystone, 'where: { lastOnline_lte: "1950-10-01T23:59:59.999-10:00" }', [
{ name: 'person3', lastOnline: '1950-10-01T23:59:59.999-10:00' },
{ name: 'person4', lastOnline: '1666-04-12T00:08:00.000+10:00' },
])
)
);
test(
'Filter: lastOnline_gt',
withKeystone(({ keystone }) =>
match(keystone, 'where: { lastOnline_gt: "1950-10-01T23:59:59.999-10:00" }', [
{ name: 'person1', lastOnline: '1990-12-31T12:34:56.789+01:23' },
{ name: 'person2', lastOnline: '2000-01-20T00:08:00.000+10:00' },
])
)
);
test(
'Filter: lastOnline_gte',
withKeystone(({ keystone }) =>
match(keystone, 'where: { lastOnline_gte: "1950-10-01T23:59:59.999-10:00" }', [
{ name: 'person1', lastOnline: '1990-12-31T12:34:56.789+01:23' },
{ name: 'person2', lastOnline: '2000-01-20T00:08:00.000+10:00' },
{ name: 'person3', lastOnline: '1950-10-01T23:59:59.999-10:00' },
])
)
);
test(
'Filter: lastOnline_in (empty list)',
withKeystone(({ keystone }) => match(keystone, 'where: { lastOnline_in: [] }', []))
);
test(
'Filter: lastOnline_not_in (empty list)',
withKeystone(({ keystone }) =>
match(keystone, 'where: { lastOnline_not_in: [] }', [
{ name: 'person1', lastOnline: '1990-12-31T12:34:56.789+01:23' },
{ name: 'person2', lastOnline: '2000-01-20T00:08:00.000+10:00' },
{ name: 'person3', lastOnline: '1950-10-01T23:59:59.999-10:00' },
{ name: 'person4', lastOnline: '1666-04-12T00:08:00.000+10:00' },
{ name: 'person5', lastOnline: null },
])
)
);
test(
'Filter: lastOnline_in',
withKeystone(({ keystone }) =>
match(
keystone,
'where: { lastOnline_in: ["1990-12-31T12:34:56.789+01:23", "2000-01-20T00:08:00.000+10:00", "1950-10-01T23:59:59.999-10:00"] }',
[
{ name: 'person1', lastOnline: '1990-12-31T12:34:56.789+01:23' },
{ name: 'person2', lastOnline: '2000-01-20T00:08:00.000+10:00' },
{ name: 'person3', lastOnline: '1950-10-01T23:59:59.999-10:00' },
]
)
)
);
test(
'Filter: lastOnline_not_in',
withKeystone(({ keystone }) =>
match(
keystone,
'where: { lastOnline_not_in: ["1990-12-31T12:34:56.789+01:23", "2000-01-20T00:08:00.000+10:00", "1950-10-01T23:59:59.999-10:00"] }',
[
{ name: 'person4', lastOnline: '1666-04-12T00:08:00.000+10:00' },
{ name: 'person5', lastOnline: null },
]
)
)
);
test(
'Filter: lastOnline_in null',
withKeystone(({ keystone }) =>
match(keystone, 'where: { lastOnline_in: [null] }', [{ name: 'person5', lastOnline: null }])
)
);
test(
'Filter: lastOnline_not_in null',
withKeystone(({ keystone }) =>
match(keystone, 'where: { lastOnline_not_in: [null] }', [
{ name: 'person1', lastOnline: '1990-12-31T12:34:56.789+01:23' },
{ name: 'person2', lastOnline: '2000-01-20T00:08:00.000+10:00' },
{ name: 'person3', lastOnline: '1950-10-01T23:59:59.999-10:00' },
{ name: 'person4', lastOnline: '1666-04-12T00:08:00.000+10:00' },
])
)
);
test(
'Sorting: orderBy: lastOnline_ASC',
withKeystone(({ keystone, adapterName }) =>
match(
keystone,
'orderBy: "lastOnline_ASC"',
adapterName === 'mongoose'
? [
{ name: 'person5', lastOnline: null },
{ name: 'person4', lastOnline: '1666-04-12T00:08:00.000+10:00' },
{ name: 'person3', lastOnline: '1950-10-01T23:59:59.999-10:00' },
{ name: 'person1', lastOnline: '1990-12-31T12:34:56.789+01:23' },
{ name: 'person2', lastOnline: '2000-01-20T00:08:00.000+10:00' },
]
: [
{ name: 'person4', lastOnline: '1666-04-12T00:08:00.000+10:00' },
{ name: 'person3', lastOnline: '1950-10-01T23:59:59.999-10:00' },
{ name: 'person1', lastOnline: '1990-12-31T12:34:56.789+01:23' },
{ name: 'person2', lastOnline: '2000-01-20T00:08:00.000+10:00' },
{ name: 'person5', lastOnline: null },
],
null
)
)
);
test(
'Sorting: orderBy: lastOnline_DESC',
withKeystone(({ keystone, adapterName }) =>
match(
keystone,
'orderBy: "lastOnline_DESC"',
adapterName === 'mongoose'
? [
{ name: 'person2', lastOnline: '2000-01-20T00:08:00.000+10:00' },
{ name: 'person1', lastOnline: '1990-12-31T12:34:56.789+01:23' },
{ name: 'person3', lastOnline: '1950-10-01T23:59:59.999-10:00' },
{ name: 'person4', lastOnline: '1666-04-12T00:08:00.000+10:00' },
{ name: 'person5', lastOnline: null },
]
: [
{ name: 'person5', lastOnline: null },
{ name: 'person2', lastOnline: '2000-01-20T00:08:00.000+10:00' },
{ name: 'person1', lastOnline: '1990-12-31T12:34:56.789+01:23' },
{ name: 'person3', lastOnline: '1950-10-01T23:59:59.999-10:00' },
{ name: 'person4', lastOnline: '1666-04-12T00:08:00.000+10:00' },
],
null
)
)
);
};
|
import React from 'react';
import PropTypes from 'prop-types';
import { withStyles } from '@material-ui/core/styles';
import { InputLabel } from '@material-ui/core/Input';
import { MenuItem } from '@material-ui/core/Menu';
import { FormControl } from '@material-ui/core/Form';
import Select from '@material-ui/core/Select';
import Button from '@material-ui/core/Button';
const styles = theme => ({
button: {
display: 'block',
marginTop: theme.spacing.unit * 2,
},
formControl: {
margin: theme.spacing.unit,
minWidth: 120,
},
});
class ControlledOpenSelect extends React.Component {
state = {
age: '',
open: false,
};
handleChange = event => {
this.setState({ [event.target.name]: event.target.value });
};
handleClose = () => {
this.setState({ open: false });
};
handleOpen = () => {
this.setState({ open: true });
};
render() {
const { classes } = this.props;
return (
<form autoComplete="off">
<Button className={classes.button} onClick={this.handleOpen}>
Open the select
</Button>
<FormControl className={classes.formControl}>
<InputLabel htmlFor="controlled-open-select">Age</InputLabel>
<Select
open={this.state.open}
onClose={this.handleClose}
onOpen={this.handleOpen}
value={this.state.age}
onChange={this.handleChange}
inputProps={{
name: 'age',
id: 'controlled-open-select',
}}
>
<MenuItem value="">
<em>None</em>
</MenuItem>
<MenuItem value={10}>Ten</MenuItem>
<MenuItem value={20}>Twenty</MenuItem>
<MenuItem value={30}>Thirty</MenuItem>
</Select>
</FormControl>
</form>
);
}
}
ControlledOpenSelect.propTypes = {
classes: PropTypes.object.isRequired,
};
export default withStyles(styles)(ControlledOpenSelect);
|
import axios from 'axios';
const api = axios.create({
baseURL: 'http://192.168.0.3:3333'
});
export default api; |
'use strict';
accountCtrl.$inject = ['$translate', '$state', '$timeout', 'auth', 'errorConstants'];
export default function accountCtrl($translate, $state, $timeout, auth, errorConstants) {
var vm = this;
vm.doNotMatch = null;
vm.error = null;
vm.errorUserExists = null;
//vm.login = LoginService.open;
vm.createAccount = createAccount;
vm.registerAccount = {};
vm.success = null;
//$timeout(function() { angular.element('#login').focus(); });
function createAccount() {
if (vm.registerAccount.password !== vm.confirmPassword) {
vm.doNotMatch = 'ERROR';
} else {
vm.registerAccount.langKey = $translate.use();
vm.doNotMatch = null;
vm.error = null;
vm.errorUserExists = null;
vm.errorEmailExists = null;
auth.createAccount(vm.registerAccount).then(function() {
vm.success = 'OK';
$state.go('app.personnalInfo');
}).catch(function(response) {
vm.success = null;
if (response.status === 400 && angular.fromJson(response.data).type === errorConstants.LOGIN_ALREADY_USED_TYPE) {
vm.errorUserExists = 'ERROR';
} else if (response.status === 400 && angular.fromJson(response.data).type === errorConstants.EMAIL_ALREADY_USED_TYPE) {
vm.errorEmailExists = 'ERROR';
} else {
vm.error = 'ERROR';
}
});
}
}
} |
(function (global, factory) {
if (typeof define === "function" && define.amd) {
define('/charts/flot', ['jquery', 'Site'], factory);
} else if (typeof exports !== "undefined") {
factory(require('jquery'), require('Site'));
} else {
var mod = {
exports: {}
};
factory(global.jQuery, global.Site);
global.chartsFlot = mod.exports;
}
})(this, function (_jquery, _Site) {
'use strict';
var _jquery2 = babelHelpers.interopRequireDefault(_jquery);
(0, _jquery2.default)(document).ready(function ($$$1) {
(0, _Site.run)();
});
// Example Flot Realtime
// ---------------------
(function () {
if (!_jquery2.default.isFunction(_jquery2.default.fn.plot) || (0, _jquery2.default)("#exampleFlotRealtime").length === 0) {
return;
}
var data = [];
var totalPoints = 250;
function getRandomData() {
if (data.length > 0) {
data = data.slice(1);
}
// Do a random walk
while (data.length < totalPoints) {
var prev = data.length > 0 ? data[data.length - 1] : 50;
var y = prev + Math.random() * 10 - 5;
if (y < 0) {
y = 0;
} else if (y > 100) {
y = 100;
}
data.push(y);
}
// Zip the generated y values with the x values
var res = [];
for (var i = 0; i < data.length; ++i) {
res.push([i, data[i]]);
}
return res;
}
var labelColor = Config.colors("grey", 600);
// Set up the control widget
var updateInterval = 30;
var plot = _jquery2.default.plot((0, _jquery2.default)("#exampleFlotRealtime"), [{
data: getRandomData()
}], {
colors: [Config.colors("grey", 200)],
series: {
shadowSize: 0,
lines: {
show: true,
lineWidth: 0,
fill: true,
fillColor: Config.colors("grey", 200)
}
},
legend: {
show: false
},
xaxis: {
show: false,
font: {
color: labelColor
}
},
yaxis: {
tickColor: "#edeff2",
color: "#474e54",
min: 0,
max: 100,
font: {
size: 14,
color: labelColor,
weight: "300"
// family: "OpenSans Light"
}
},
grid: {
color: "#474e54",
tickColor: "#e3e6ea",
backgroundColor: {
colors: ["#fff", "#fff"]
},
borderWidth: {
top: 0,
right: 0,
bottom: 1,
left: 0
},
borderColor: "#eef0f2"
}
});
function update() {
plot.setData([getRandomData()]);
// Since the axes don't change, we don't need to call plot.setupGrid()
plot.draw();
setTimeout(update, updateInterval);
}
update();
})();
// Example Flot Full-Bg Line
// -------------------------
(function () {
var b = [[1262304000000, 0], [1264982400000, 500], [1267401600000, 700], [1270080000000, 1300], [1272672000000, 2600], [1275350400000, 1300], [1277942400000, 1700], [1280620800000, 1300], [1283299200000, 1500], [1285891200000, 2000], [1288569600000, 1500], [1291161600000, 1200]];
var a = [{
label: "Fish values",
data: b
}];
_jquery2.default.plot("#exampleFlotFullBg", a, {
xaxis: {
min: new Date(2009, 12, 1).getTime(),
max: new Date(2010, 11, 2).getTime(),
mode: "time",
tickSize: [1, "month"],
monthNames: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"],
tickLength: 0,
// tickColor: "#edeff2",
color: "#474e54",
font: {
size: 14,
weight: 300
// family: "OpenSans Light"
}
},
yaxis: {
tickColor: "#edeff2",
color: "#474e54",
font: {
size: 14,
weight: "300"
// family: "OpenSans Light"
}
},
series: {
shadowSize: 0,
lines: {
show: true,
// fill: true,
// fillColor: "#ff0000",
lineWidth: 1.5
},
points: {
show: true,
fill: true,
fillColor: Config.colors("primary", 600),
radius: 3,
lineWidth: 1
}
},
colors: [Config.colors("primary", 500)],
grid: {
// show: true,
hoverable: true,
clickable: true,
// color: "green",
// tickColor: "red",
backgroundColor: {
colors: ["#fcfdfe", "#fcfdfe"]
},
borderWidth: 0
// borderColor: "#ff0000"
},
legend: {
show: false
}
});
})();
// Example Flot Curve
// ------------------
(function () {
var dt1 = [];
for (var i = 0; i < Math.PI * 2; i += 0.25) {
dt1.push([i, Math.sin(i)]);
}
var dt2 = [];
for (i = 0; i < Math.PI * 2; i += 0.25) {
dt2.push([i, Math.cos(i)]);
}
var f_chart = (0, _jquery2.default)("#exampleFlotCurve");
_jquery2.default.plot(f_chart, [{
label: "sin(x)",
data: dt1,
color: Config.colors("primary", 400),
points: {
show: true,
fill: true,
radius: 3,
fillColor: Config.colors("primary", 400)
}
}, {
label: "cos(x)",
data: dt2,
yaxis: 2,
color: Config.colors("green", 400),
points: {
show: true,
fill: true,
radius: 3,
fillColor: Config.colors("green", 600)
}
}], {
series: {
shadowSize: 0,
lines: {
show: true,
lineWidth: 1.5
},
points: {
show: true,
radius: 3,
lineWidth: 1
}
},
xaxes: [{
ticks: [0, [Math.PI / 2, '\u03C0/2'], [Math.PI, '\u03C0'], [Math.PI * 3 / 2, '3\u03C0/2'], [Math.PI * 2, '2\u03C0']]
}],
yaxes: [{
ticks: 5,
min: -2,
max: 2,
tickDecimals: 3
}, {
ticks: 5,
min: -1,
max: 1,
tickLength: 0,
tickDecimals: 2,
position: "right"
}],
grid: {
hoverable: true,
color: "#474e54",
tickColor: "#e3e6ea",
backgroundColor: {
colors: ["#fff", "#fff"]
},
borderWidth: {
top: 1,
right: 1,
bottom: 1,
left: 1
},
borderColor: "#eef0f2"
},
legend: {
show: false
}
});
})();
// Example Flot Mix
// ----------------
(function () {
var b1 = [];
for (var i = 0; i < 14; i += 0.5) {
b1.push([i, Math.cos(i) + 1]);
}
var b2 = [[2, 3], [4, 8], [6, 5], [9, 13]];
var b3 = [];
for (i = 0; i < 14; i += 0.5) {
b3.push([i, Math.cos(i) + Math.sin(i) - 1]);
}
var b4 = [];
for (i = 0; i < 14; i += 0.1) {
b4.push([i, Math.sqrt(i * 10) - 4 * Math.cos(i)]);
}
var b5 = [];
for (i = 0; i < 14; i += 1.5) {
b5.push([i, Math.cos(i) + 2 * Math.sin(i) + 6]);
}
var b6 = [];
for (i = 0; i < 14; i += 0.5 + Math.random()) {
b6.push([i, Math.sqrt(i + 2 * Math.cos(i)) - Math.sin(i) - 3]);
}
_jquery2.default.plot("#exampleFlotMix", [{
data: b2,
bars: {
show: true,
align: "center",
fill: true,
fillColor: Config.colors("grey", 200)
}
}, {
data: b1,
lines: {
show: true,
fill: true,
fillColor: "rgba(251,213,181,.1)"
}
}, {
data: b3,
points: {
show: true,
fill: true,
fillColor: Config.colors("green", 600),
radius: 2
}
}, {
data: b4,
lines: {
show: true
},
points: {
show: false
}
}, {
data: b5,
lines: {
show: true
},
points: {
show: true,
fill: true,
fillColor: Config.colors("primary", 600),
radius: 2
}
}, {
data: b6,
lines: {
show: true,
steps: true
}
}], {
xaxis: {
tickLength: 0,
color: "#474e54",
font: {
size: 14,
weight: 300
// family: "OpenSans Light"
}
},
yaxis: {
tickColor: "#edeff2",
color: "#474e54",
font: {
size: 14,
weight: "300"
// family: "OpenSans Light"
}
},
grid: {
color: "#474e54",
tickColor: "#e3e6ea",
backgroundColor: {
colors: ["#fff", "#fff"]
},
borderWidth: {
top: 0,
right: 0,
bottom: 1,
left: 0
},
borderColor: "#eef0f2"
},
series: {
shadowSize: 0
},
colors: [Config.colors("grey", 200), Config.colors("orange", 200), Config.colors("green", 600), Config.colors("yellow", 600), Config.colors("primary", 600), Config.colors("purple", 200)]
});
})();
// Example Flot Stack Bar
// ----------------------
(function () {
var a1 = [];
for (var i = 1; i <= 4; i += 1) {
a1.push([i, parseInt(Math.random() * 30)]);
}
var a2 = [];
for (i = 1; i <= 4; i += 1) {
a2.push([i, parseInt(Math.random() * 30)]);
}
var a3 = [];
for (i = 1; i <= 4; i += 1) {
a3.push([i, parseInt(Math.random() * 30)]);
}
var a4 = [];
for (i = 1; i <= 4; i += 1) {
a4.push([i, parseInt(Math.random() * 30 - 10)]);
}
_jquery2.default.plot("#exampleFlotStackBar", [{
data: a1,
bars: {
fill: true,
fillColor: Config.colors("light-green", 500)
}
}, {
data: a2,
bars: {
fill: true,
fillColor: Config.colors("grey", 400)
}
}, {
data: a3,
bars: {
fill: true,
fillColor: Config.colors("primary", 500)
}
}, {
data: a4,
bars: {
fill: true,
fillColor: Config.colors("purple", 500)
}
}], {
series: {
stack: true,
shadowSize: 0,
lines: {
show: false,
fill: true,
steps: false
},
bars: {
show: true,
align: "center",
barWidth: 0.38
}
},
colors: [Config.colors("light-green", 500), Config.colors("grey", 400), Config.colors("primary", 500), Config.colors("purple", 500)],
xaxis: {
tickLength: 0,
color: "#474e54",
min: 0,
max: 5.5,
ticks: [1, 2, 3, 4],
font: {
size: 14,
weight: 300
// family: "OpenSans Light"
}
},
yaxis: {
tickColor: "#edeff2",
color: "#474e54",
min: -10,
font: {
size: 14,
weight: "300"
// family: "OpenSans Light"
}
},
grid: {
color: "#474e54",
tickColor: "#e3e6ea",
backgroundColor: {
colors: ["#fff", "#fff"]
},
borderWidth: {
top: 0,
right: 0,
bottom: 1,
left: 0
},
borderColor: "#eef0f2"
}
});
})();
// Example Flot Horizontal Bar
// ---------------------------
(function () {
var a11 = [];
for (var i = 1; i <= 5; i += 1) {
a11.push([parseInt(Math.random() * 30), i]);
}
var a22 = [];
for (i = 1; i <= 5; i += 1) {
a22.push([parseInt(Math.random() * 30), i]);
}
var a33 = [];
for (i = 1; i <= 5; i += 1) {
a33.push([parseInt(Math.random() * 30), i]);
}
_jquery2.default.plot("#exampleFlotHorizontalBar", [{
data: a11,
bars: {
fill: true,
fillColor: Config.colors("primary", 500)
}
}, {
data: a22,
bars: {
fill: true,
fillColor: Config.colors("grey", 400)
}
}, {
data: a33,
bars: {
fill: true,
fillColor: Config.colors("red", 500)
}
}], {
series: {
stack: true,
lines: {
show: false,
fill: true
},
bars: {
show: true,
barWidth: 0.55,
align: "center",
horizontal: true
}
},
colors: [Config.colors("primary", 500), Config.colors("grey", 400), Config.colors("red", 500)],
xaxis: {
color: "#474e54",
font: {
size: 14,
weight: 300
// family: "OpenSans Light"
}
},
yaxis: {
tickLength: 0,
tickColor: "#edeff2",
color: "#474e54",
min: 0,
max: 6,
ticks: [1, 2, 3, 4, 5],
font: {
size: 14,
weight: "300"
// family: "OpenSans Light"
}
},
grid: {
color: "#474e54",
tickColor: "#e3e6ea",
backgroundColor: {
colors: ["#fff", "#fff"]
},
borderWidth: {
top: 1,
right: 1,
bottom: 1,
left: 1
},
borderColor: "#eef0f2"
}
});
})();
// Example Flot Pie
// ----------------
(function () {
var pieData = [],
series = 2;
for (var i = 0; i < series; i++) {
pieData[i] = {
label: "Example Pie S" + (i + 1),
data: Math.floor(Math.random() * 100) + 1
};
}
var placeholder = (0, _jquery2.default)("#exampleFlotPie");
// Default Options
(0, _jquery2.default)("#btnPieDefault").click(function () {
placeholder.unbind();
_jquery2.default.plot(placeholder, pieData, {
series: {
pie: {
show: true
}
},
colors: [Config.colors("primary", 500), Config.colors("grey", 300)]
});
});
// Without Legend
(0, _jquery2.default)("#btnPieWithoutLegend").click(function () {
placeholder.unbind();
_jquery2.default.plot(placeholder, pieData, {
series: {
pie: {
show: true,
label: {
show: true
}
}
},
colors: [Config.colors("primary", 500), Config.colors("grey", 300)],
legend: {
show: false
}
});
});
// Label Radius
(0, _jquery2.default)("#btnPieLabelRadius").click(function () {
placeholder.unbind();
_jquery2.default.plot(placeholder, pieData, {
series: {
pie: {
show: true,
radius: 1,
label: {
show: true,
radius: 3 / 4,
formatter: labelFormatter
}
}
},
colors: [Config.colors("primary", 500), Config.colors("grey", 300)],
legend: {
show: false
}
});
});
// Rectangular Pie
(0, _jquery2.default)("#btnPieRectangular").click(function () {
placeholder.unbind();
_jquery2.default.plot(placeholder, pieData, {
series: {
pie: {
show: true,
radius: 500,
label: {
show: true,
formatter: labelFormatter,
threshold: 0.1
}
}
},
colors: [_jquery2.default.colors("primary", 500), _jquery2.default.colors("grey", 300)],
legend: {
show: false
}
});
});
// Donut Hole
(0, _jquery2.default)("#btnPieDonutHole").click(function () {
placeholder.unbind();
_jquery2.default.plot(placeholder, pieData, {
series: {
pie: {
innerRadius: 0.5,
show: true
}
},
colors: [Config.colors("primary", 500), Config.colors("grey", 300)]
});
});
// Interactivity
(0, _jquery2.default)("#btnPieInteractivity").click(function () {
placeholder.unbind();
_jquery2.default.plot(placeholder, pieData, {
series: {
pie: {
show: true
}
},
colors: [Config.colors("primary", 500), Config.colors("grey", 300)],
grid: {
hoverable: true,
clickable: true
}
});
placeholder.bind("plothover", function (event, pos, obj) {
if (!obj) {
return;
}
var percent = parseFloat(obj.series.percent).toFixed(2);
(0, _jquery2.default)("#hover").html("<span style='font-weight:bold; color:" + obj.series.color + "'>" + obj.series.label + " (" + percent + "%)</span>");
});
placeholder.bind("plotclick", function (event, pos, obj) {
if (!obj) {
return;
}
percent = parseFloat(obj.series.percent).toFixed(2);
alert("" + obj.series.label + ": " + percent + "%");
});
});
// Show the initial default chart
(0, _jquery2.default)("#btnPieDefault").click();
// A custom label formatter used by several of the plots
console.log("out");
function labelFormatter(label, series) {
return "<div" + " style='" + "font-size: 8pt; text-align: center; padding: 2px; color: #747474;'" + ">" + label + "<br/>" + Math.round(series.percent) + "%</div>";
}
})();
// Example Flot Visitors
// ---------------------
(function () {
var d = [[1196463600000, 0], [1196550000000, 0], [1196636400000, 0], [1196722800000, 77], [1196809200000, 3636], [1196895600000, 3575], [1196982000000, 2736], [1197068400000, 1086], [1197154800000, 676], [1197241200000, 1205], [1197327600000, 906], [1197414000000, 710], [1197500400000, 639], [1197586800000, 540], [1197673200000, 435], [1197759600000, 301], [1197846000000, 575], [1197932400000, 481], [1198018800000, 591], [1198105200000, 608], [1198191600000, 459], [1198278000000, 234], [1198364400000, 1352], [1198450800000, 686], [1198537200000, 279], [1198623600000, 449], [1198710000000, 468], [1198796400000, 392], [1198882800000, 282], [1198969200000, 208], [1199055600000, 229], [1199142000000, 177], [1199228400000, 374], [1199314800000, 436], [1199401200000, 404], [1199487600000, 253], [1199574000000, 218], [1199660400000, 476], [1199746800000, 462], [1199833200000, 448], [1199919600000, 442], [1200006000000, 403], [1200092400000, 204], [1200178800000, 194], [1200265200000, 327], [1200351600000, 374], [1200438000000, 507], [1200524400000, 546], [1200610800000, 482], [1200697200000, 283], [1200783600000, 221], [1200870000000, 483], [1200956400000, 523], [1201042800000, 528], [1201129200000, 483], [1201215600000, 452], [1201302000000, 270], [1201388400000, 222], [1201474800000, 439], [1201561200000, 559], [1201647600000, 521], [1201734000000, 477], [1201820400000, 442], [1201906800000, 252], [1201993200000, 236], [1202079600000, 525], [1202166000000, 477], [1202252400000, 386], [1202338800000, 409], [1202425200000, 408], [1202511600000, 237], [1202598000000, 193], [1202684400000, 357], [1202770800000, 414], [1202857200000, 393], [1202943600000, 353], [1203030000000, 364], [1203116400000, 215], [1203202800000, 214], [1203289200000, 356], [1203375600000, 399], [1203462000000, 334], [1203548400000, 348], [1203634800000, 243], [1203721200000, 126], [1203807600000, 157], [1203894000000, 288]];
// first correct the timestamps - they are recorded as the daily
// midnights in UTC+0100, but Flot always displays dates in UTC
// so we have to add one hour to hit the midnights in the plot
for (var i = 0; i < d.length; ++i) {
d[i][0] += 60 * 60 * 1000;
}
// helper for returning the weekends in a period
function weekendAreas(axes) {
var markings = [],
d = new Date(axes.xaxis.min);
// go to the first Saturday
d.setUTCDate(d.getUTCDate() - (d.getUTCDay() + 1) % 7);
d.setUTCSeconds(0);
d.setUTCMinutes(0);
d.setUTCHours(0);
var i = d.getTime();
// when we don't set yaxis, the rectangle automatically
// extends to infinity upwards and downwards
do {
markings.push({
xaxis: {
from: i,
to: i + 2 * 24 * 60 * 60 * 1000
}
});
i += 7 * 24 * 60 * 60 * 1000;
} while (i < axes.xaxis.max);
return markings;
}
var options = {
series: {
lines: {
show: true,
lineWidth: 1
},
shadowSize: 0
},
colors: [Config.colors("primary", 600)],
selection: {
mode: "x",
color: [Config.colors("primary", 300)]
},
xaxis: {
tickLength: 0,
mode: "time",
color: "#474e54",
font: {
size: 14,
weight: 300
// family: "OpenSans Light"
}
},
yaxis: {
tickColor: "#edeff2",
color: "#474e54",
font: {
size: 14,
weight: "300"
// family: "OpenSans Light"
}
},
grid: {
markings: weekendAreas,
color: "#474e54",
tickColor: "#e3e6ea",
backgroundColor: {
colors: ["#fff", "#fff"]
},
borderWidth: {
top: 0,
right: 0,
bottom: 1,
left: 0
},
borderColor: "#eef0f2"
}
};
var _plot = _jquery2.default.plot("#exampleFlotVisitors", [d], options);
var overview = _jquery2.default.plot("#exampleFlotVisitorsOverview", [d], {
series: {
lines: {
show: true,
lineWidth: 1
},
shadowSize: 0
},
colors: [Config.colors("primary", 600)],
xaxis: {
ticks: [],
mode: "time"
},
yaxis: {
ticks: [],
min: 0,
autoscaleMargin: 0.1
},
selection: {
mode: "x",
color: [Config.colors("primary", 300)]
},
grid: {
// markings: weekendAreas,
color: "#474e54",
tickColor: "#e3e6ea",
backgroundColor: {
colors: ["#fff", "#fff"]
},
borderWidth: {
top: 1,
right: 1,
bottom: 1,
left: 1
},
borderColor: "#eef0f2"
}
});
// now connect the two
(0, _jquery2.default)("#exampleFlotVisitors").bind("plotselected", function (event, ranges) {
// do the zooming
_jquery2.default.each(_plot.getXAxes(), function (_, axis) {
var opts = axis.options;
opts.min = ranges.xaxis.from;
opts.max = ranges.xaxis.to;
});
_plot.setupGrid();
_plot.draw();
_plot.clearSelection();
// don't fire event on the overview to prevent eternal loop
overview.setSelection(ranges, true);
});
(0, _jquery2.default)("#exampleFlotVisitorsOverview").bind("plotselected", function (event, ranges) {
_plot.setSelection(ranges);
});
})();
// Example Flot Tooltip
// --------------------
(function () {
(0, _jquery2.default)("<div class='flot-tooltip'></div>").css({
position: "absolute",
color: "#fff",
display: "none",
border: "1px solid #777",
padding: "2px",
"background-color": "#777",
opacity: 0.80
}).appendTo("body");
(0, _jquery2.default)("#exampleFlotCurve").bind("plothover", function (event, pos, item) {
if (item) {
var x = item.datapoint[0].toFixed(2),
y = item.datapoint[1].toFixed(2);
(0, _jquery2.default)(".flot-tooltip").html(item.series.label + " of " + x + " = " + y).css({
top: item.pageY + 5,
left: item.pageX + 5
}).fadeIn(200);
} else {
(0, _jquery2.default)(".flot-tooltip").hide();
}
});
(0, _jquery2.default)("#exampleFlotFullBg").bind("plothover", function (event, pos, item) {
if (item) {
var x = item.datapoint[0].toFixed(2),
y = item.datapoint[1].toFixed(2);
(0, _jquery2.default)(".flot-tooltip").html(item.series.label + " of " + x + " = " + y).css({
top: item.pageY + 5,
left: item.pageX + 5
}).fadeIn(200);
} else {
(0, _jquery2.default)(".flot-tooltip").hide();
}
});
(0, _jquery2.default)("#exampleFlotRealtime").bind("plothover", function (event, pos, item) {
if (item) {
var x = item.datapoint[0].toFixed(2),
y = item.datapoint[1].toFixed(2);
(0, _jquery2.default)(".flot-tooltip").html("x | " + x + "," + " y | " + y).css({
top: item.pageY + 5,
left: item.pageX + 5
}).fadeIn(200);
} else {
(0, _jquery2.default)(".flot-tooltip").hide();
}
});
})();
}); |
from tkinter import *
window = Tk()
window.geometry("400x300+20+10")
window.title('Final Exam')
lbl1 = Label(window, text="Find the least among three numbers", fg="blue", bg="yellow")
lbl1.place(relx=0.50, y=50, anchor="center")
lbl2 = Label(window, text="Enter the first number:")
lbl2.place(x=50, y=80)
txtfld2 = Entry(window, bd=3)
txtfld2.place(x=200, y=80)
lbl3 = Label(window,text="Enter the second number:")
lbl3.place(x=50,y=120)
txtfld3=Entry(window,bd=3)
txtfld3.place(x=200,y=120)
lbl4 = Label(window, text="Enter the third number:")
lbl4.place(x=50, y=160)
txtfld4=Entry(window,bd=3)
txtfld4.place(x=200,y=160)
def Average():
minnum.delete(0,"end")
num1=int(txtfld2.get())
num2=int(txtfld3.get())
num3=int(txtfld4.get())
answer = min(num1, num2, num3)
minnum.insert(END,str(answer))
btn1=Button(window,text="Find",width=10,command=Average)
btn1.place(x=200, y=208, anchor="center")
lbl5 = Label(window,text = "Lowest Value", fg="red")
lbl5.place(x=150, y=260)
minnum = Entry(window)
minnum.place(x=138, y=240)
window.mainloop()
|
#!/usr/bin/env python3
# MIT License
#
# 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.
"""
Command line utility for compare analytical solutions of some SPH-EXA test
simulations.
Usage examples:
$ python ./compare_noh.py --version'
$ python ./compare_noh.py dump_noh.h5part --time 0.018
$ python ./compare_noh.py dump_noh.h5part --step 100
"""
__program__ = "compare_noh.py"
__author__ = "Jose A. Escartin ([email protected])"
__version__ = "0.1.0"
from argparse import ArgumentParser
import h5py
import numpy as np
import matplotlib.pyplot as plt
def nohShockFront(gamma, vel0, time):
""" position of the shock front """
return 0.5 * (gamma - 1) * abs(vel0) * time
def nohRho(xgeom, gamma, rho0, vel0, r, time):
""" analytical density at radius r for given time"""
r2 = nohShockFront(gamma, vel0, time)
if r > r2:
return rho0 * (1.0 - vel0 * time / r) ** (xgeom - 1)
else:
return rho0 * ((gamma + 1) / (gamma - 1)) ** xgeom
def nohU(gamma, u0, vel0, r, time):
""" analytical internal energy at radius r for given time"""
r2 = nohShockFront(gamma, vel0, time)
if r > r2:
return u0
else:
return 0.5 * vel0**2
def nohP(xgeom, gamma, rho0, u0, p0, vel0, r, time):
""" analytical pressure at radius r for given time"""
r2 = nohShockFront(gamma, vel0, time)
if r > r2:
return p0
else:
return (gamma - 1) * nohRho(xgeom, gamma, rho0, vel0, r, time) * nohU(gamma, u0, vel0, r, time)
def nohVel(gamma, vel0, r, time):
""" analytical velocity magnitude at radius r for given time"""
r2 = nohShockFront(gamma, vel0, time)
if r > r2:
return abs(vel0)
else:
return 0
def nohCs(xgeom, gamma, rho0, u0, p0, vel0, cs0, r, time):
""" analytical pressure at radius r for given time"""
r2 = nohShockFront(gamma, vel0, time)
if r > r2:
return cs0
else:
return np.sqrt(
gamma * nohP(xgeom, gamma, rho0, u0, p0, vel0, r, time) / nohRho(xgeom, gamma, rho0, vel0, r, time))
def loadH5Field(h5File, what, step):
""" Load the specified particle field at the given step, returns an array of length numParticles """
return np.array(h5File["Step#%s/%s" % (step, what)])
def loadTimesteps(h5File):
""" Load simulation times of each recorded time step """
return np.array(sorted([h5File[step].attrs["time"][0] for step in list(h5File["/"])]))
def loadStepNumbers(h5File):
""" Load the iteration count of each recorded time step """
return np.array(sorted([h5File[step].attrs["step"][0] for step in list(h5File["/"])]))
def determineTimestep(time, timesteps):
""" Return the timestep with simulation time closest to the specified time """
return np.argmin(np.abs(timesteps - time))
def computeRadii(h5File, step):
""" Load XYZ coordinates and compute their radii """
x = loadH5Field(h5File, "x", step)
y = loadH5Field(h5File, "y", step)
z = loadH5Field(h5File, "z", step)
print("Loaded %s particles" % len(x))
return np.sqrt(x ** 2 + y ** 2 + z ** 2)
def plotRadialProfile(props, xSim, ySim, xSol, ySol):
plt.scatter(xSim, ySim, s=0.1, label="Simulation", color="C0")
plt.plot(xSol, ySol, label="Solution", color="C1")
plt.xlabel("r")
plt.ylabel(props["ylabel"])
plt.draw()
plt.title(props["title"])
plt.legend(loc="upper right")
plt.savefig(props["fname"], format="png")
plt.figure().clear()
def createDensityPlot(h5File, attrs, radii, time, step):
rho = loadH5Field(h5File, "rho", step)
rSol = np.linspace(attrs["r0"], attrs["r1"], 1000)
rhoSol = np.vectorize(nohRho)(attrs["dim"], attrs["gamma"], attrs["rho0"], attrs["vr0"], rSol, time)
props = {"ylabel": "rho", "title": "Density", "fname": "noh_density_%4f.png" % time}
plotRadialProfile(props, radii, rho, rSol, rhoSol)
rhoSolFull = np.vectorize(nohRho)(attrs["dim"], attrs["gamma"], attrs["rho0"], attrs["vr0"], radii, time)
print("Density L1 error", sum(abs(rhoSolFull - rho)) / len(rho))
def createPressurePlot(h5File, attrs, radii, time, step):
p = loadH5Field(h5File, "p", step)
rSol = np.linspace(attrs["r0"], attrs["r1"], 1000)
pSol = np.vectorize(nohP)(attrs["dim"], attrs["gamma"], attrs["rho0"], attrs["u0"], attrs["p0"], attrs["vr0"],
rSol, time)
props = {"ylabel": "p", "title": "Pressure", "fname": "noh_pressure_%4f.png" % time}
plotRadialProfile(props, radii, p, rSol, pSol)
pSolFull = np.vectorize(nohP)(attrs["dim"], attrs["gamma"], attrs["rho0"], attrs["u0"], attrs["p0"], attrs["vr0"],
radii, time)
print("Pressure L1 error", sum(abs(pSolFull - p)) / len(p))
def createVelocityPlot(h5File, attrs, radii, time, step):
vx = loadH5Field(h5File, "vx", step)
vy = loadH5Field(h5File, "vy", step)
vz = loadH5Field(h5File, "vz", step)
vr = np.sqrt(vx ** 2 + vy ** 2 + vz ** 2)
rSol = np.linspace(attrs["r0"], attrs["r1"], 1000)
vSol = np.vectorize(nohVel)(attrs["gamma"], attrs["vr0"], rSol, time)
props = {"ylabel": "vel", "title": "Velocity", "fname": "noh_velocity_%4f.png" % time}
plotRadialProfile(props, radii, vr, rSol, vSol)
vSolFull = np.vectorize(nohVel)(attrs["gamma"], attrs["vr0"], radii, time)
print("Velocity L1 error", sum(abs(vSolFull - vr)) / len(vr))
def createEnergyPlot(h5File, attrs, radii, time, step):
u = loadH5Field(h5File, "u", step)
rSol = np.linspace(attrs["r0"], attrs["r1"], 1000)
uSol = np.vectorize(nohU)(attrs["gamma"], attrs["u0"], attrs["vr0"], rSol, time)
props = {"ylabel": "u", "title": "Energy", "fname": "noh_energy_%4f.png" % time}
plotRadialProfile(props, radii, u, rSol, uSol)
uSolFull = np.vectorize(nohU)(attrs["gamma"], attrs["u0"], attrs["vr0"], radii, time)
print("Energy L1 error", sum(abs(uSolFull - u)) / len(u))
if __name__ == "__main__":
parser = ArgumentParser(description='Plot analytical solutions against SPH simulations')
parser.add_argument('simFile', help="SPH simulation HDF5 file")
group = parser.add_mutually_exclusive_group()
group.add_argument('-s', '--step', type=int, dest="step", help="plot solution at the given simulation step")
group.add_argument('-t', '--time', type=float, dest="time", help="simulation time for which to plot solution")
args = parser.parse_args()
h5File = h5py.File(args.simFile, "r")
step = args.step
# simulation time of each step that was written to file
timesteps = loadTimesteps(h5File)
# the actual iteration number of each step that was written
stepNumbers = loadStepNumbers(h5File)
if step is None:
# output time specified instead of step, locate closest output step
stepIndex = determineTimestep(args.time, timesteps)
step = stepNumbers[stepIndex]
print("The closest timestep to the specified time of %s is step %s at t=%s" % (
args.time, step, timesteps[stepIndex]))
hdf5_step = np.searchsorted(stepNumbers, step)
time = timesteps[hdf5_step]
attrs = h5File.attrs
radii = None
try:
radii = computeRadii(h5File, hdf5_step)
except KeyError:
print("Could not load radii, input file does not contain fields \"x, y, z\"")
try:
createDensityPlot(h5File, attrs, radii, time, hdf5_step)
except KeyError:
print("Could not plot density profile, input does not contain field \"rho\"")
try:
createPressurePlot(h5File, attrs, radii, time, hdf5_step)
except KeyError:
print("Could not plot pressure profile, input does not contain field \"p\"")
try:
createVelocityPlot(h5File, attrs, radii, time, hdf5_step)
except KeyError:
print("Could not plot velocity profile, input does not contain fields \"vx, vy, vz\"")
try:
createEnergyPlot(h5File, attrs, radii, time, hdf5_step)
except KeyError:
print("Could not plot velocity profile, input does not contain fields \"u\"")
|
import React, { useState, useEffect } from 'react';
import { CSSTransition, TransitionGroup } from 'react-transition-group';
import styled from 'styled-components';
import { email } from '@config';
import { navDelay, loaderDelay } from '@utils';
const StyledHeroSection = styled.section`
${({ theme }) => theme.mixins.flexCenter};
flex-direction: column;
align-items: flex-start;
min-height: 100vh;
h1 {
margin: 0 0 30px 4px;
color: var(--green);
font-family: var(--font-mono);
font-size: clamp(var(--fz-sm), 5vw, var(--fz-md));
font-weight: 400;
@media (max-width: 480px) {
margin: 0 0 20px 2px;
}
}
h3 {
margin-top: 10px;
color: var(--slate);
line-height: 0.9;
}
p {
margin: 20px 0 0;
max-width: 500px;
}
.email-link {
${({ theme }) => theme.mixins.bigButton};
margin-top: 50px;
}
`;
const Hero = () => {
const [isMounted, setIsMounted] = useState(false);
useEffect(() => {
const timeout = setTimeout(() => setIsMounted(true), navDelay);
return () => clearTimeout(timeout);
}, []);
const one = <h1>Hi, my name is</h1>;
const two = <h2 className="big-heading">Praveen Gupta.</h2>;
const three = <h3 className="big-heading">I build things for the web.</h3>;
const four = (
<p>
I'm a software engineer specializing in building (and occasionally designing) exceptional
digital experiences. Currently, I'm focused on building accessible, human-centered .
</p>
);
const five = (
<a href={`mailto:${email}`} className="email-link">
Get In Touch
</a>
);
const items = [one, two, three, four, five];
return (
<StyledHeroSection>
<TransitionGroup component={null}>
{isMounted &&
items.map((item, i) => (
<CSSTransition key={i} classNames="fadeup" timeout={loaderDelay}>
<div style={{ transitionDelay: `${i + 1}00ms` }}>{item}</div>
</CSSTransition>
))}
</TransitionGroup>
</StyledHeroSection>
);
};
export default Hero;
|
const path = require("path")
exports.createPages = ({ boundActionCreators, graphql }) => {
const { createPage } = boundActionCreators
const postTemplate = path.resolve("src/templates/blog-post.js")
return graphql(`
{
allMarkdownRemark {
edges {
node {
id
frontmatter {
path
title
date
author
}
html
}
}
}
}
`).then(res => {
if (res.errors) {
return Promise.reject(res.errors)
}
res.data.allMarkdownRemark.edges.forEach(({ node }) => {
createPage({
path: node.frontmatter.path,
component: postTemplate,
})
})
})
}
|
(window.driftWebpackJsonp=window.driftWebpackJsonp||[]).push([[103],{772:function(a){a.exports={"app.async.contactPrompt":"How can we reach you?","app.async.thankYou":"Thanks for your message. We'll follow up in a bit at {email}","app.automessage.emailCaptureMessage":"Hey there! We're excited to help you out. Let us know your email address so that we can follow up in case we get disconnected.","app.automessage.emailCapturedSuccess":"Thanks for submitting your email","app.campaign.nps.detractorFeedbackApproval":"It will help us improve your experience.","app.campaign.nps.feedbackApproval":"Thank you for your feedback!","app.campaign.nps.notLikely":"not likely","app.campaign.nps.veryLikely":"very likely","app.composer.footer.chatWith":"Chat with {orgName}","app.composer.footer.meetingPoweredByDrift":"Meeting {bolt} by {drift}","app.composer.footer.poweredByDrift":"Chat {bolt} by {drift}","app.composer.disabledUseButtons":"Choose an option above...","app.composer.leaveMessage":"Leave Message","app.composer.leaveMessageForPlaceholder":"Leave a message for {name}","app.composer.leaveMessagePlaceholder":"Leave a message…","app.composer.placeholder":"Type your message…","app.composer.replyToPlaceholder":"Reply to {name}","app.composer.sendKeyHint":"{key} to send","app.composer.sendMessage":"Send Message","app.composer.submitKeyHint":"{key} to submit","app.composer.conversationRating.label":"Rate Us:","app.form.invalidEmail":"Invalid email address","app.form.label.emailAddress":"Email address","app.form.label.submit":"Submit","app.form.requiredField":"Required","app.header.title.conversations":"Conversations","app.header.title.newConversation":"New Conversation","app.meeting.hour":"hour","app.meeting.hours":"hours","app.meeting.minute":"minute","app.meeting.minutes":"minutes","app.meeting.next":"Next","app.meeting.prev":"Prev","app.meeting.retry":"Retry","app.meeting.schedule":"Schedule","app.meeting.scheduleAMeeting":"Schedule a Meeting","app.meeting.scheduleAMeetingError":"Sorry about that! We ran into an error on our end - please try again.","app.meeting.scheduleAMeetingTimePassedError":"Sorry, the time you chose has already passed! Please pick a new time.","app.meeting.scheduleAMeetingAlreadyBookedError":"Sorry, it looks like someone has already scheduled this time slot with {name}.","app.meeting.chooseNewTime":"Choose a new time","app.meeting.searchTimeZones":"Search Time Zones","app.meeting.selectADay":"Select a day","app.meeting.selectATime":"Select a time","app.meeting.timeZone":"Time Zone","app.message.attachmentCount":"{count, plural, =0 {No attachments} one {1 attachment} other {# attachments}}","app.message.deliveryStatus.delivered":"Delivered","app.message.deliveryStatus.sending":"Sending...","app.newConversation.welcomeMessage":"How can we help? We're here for you!","app.status.connected":"Connected","app.status.connecting":"Connecting","app.status.connectionFailed":"Connection failed.","app.status.connectionRetry":"Retry?","app.user.personalPronoun":"You","app.user.status.active":"active {time}","app.user.status.offline":"offline now","app.user.status.online":"online now","messenger.offlineFeedback.awayMessageDefaultCopy":"Hi there! So we’re away right now, but if you leave us a message we’ll get back to you soon.","messenger.offlineFeedback.confirmationMessageDefaultCopy":"Thanks for your message! We’ll follow up in a bit.","messenger.offlineFeedback.form.label.emailAddress":"Email Address","messenger.offlineFeedback.form.label.message":"Message","messenger.offlineFeedback.form.label.submitAwayMode":"Leave message","system.key.enter":"enter","system.key.return":"return","tz.America/Los_Angeles":"Los Angeles","tz.America/Denver":"Denver","tz.America/Chicago":"Chicago","tz.America/New_York":"New York","tz.America/Halifax":"Halifax","tz.America/Anchorage":"Anchorage","tz.America/Phoenix":"Phoenix","tz.America/St_Johns":"St Johns","tz.Pacific/Honolulu":"Honolulu","tz.Europe/Berlin":"Berlin","tz.Europe/Helsinki":"Helsinki","tz.Europe/London":"London","tz.Europe/Minsk":"Minsk","tz.Europe/Moscow":"Moscow","tz.America/Adak":"Adak","tz.America/Argentina/Buenos_Aires":"Argentina - Buenos Aires","tz.America/Asuncion":"Asuncion","tz.America/Bogota":"Bogota","tz.America/Campo_Grande":"Campo Grande","tz.America/Caracas":"Caracas","tz.America/Godthab":"Godthab","tz.America/Goose_Bay":"Goose Bay","tz.America/Guatemala":"Guatemala","tz.America/Havana":"Havana","tz.America/Mazatlan":"Mazatlan","tz.America/Mexico_City":"Mexico City","tz.America/Miquelon":"Miquelon","tz.America/Montevideo":"Montevideo","tz.America/Noronha":"Noronha","tz.America/Santiago":"Santiago","tz.America/Sao_Paulo":"Sao Paulo","tz.Africa/Cairo":"Cairo","tz.Africa/Johannesburg":"Johannesburg","tz.Africa/Lagos":"Lagos","tz.Africa/Windhoek":"Windhoek","tz.Asia/Amman":"Amman","tz.Asia/Baghdad":"Baghdad","tz.Asia/Baku":"Baku","tz.Asia/Beirut":"Beirut","tz.Asia/Damascus":"Damascus","tz.Asia/Dhaka":"Dhaka","tz.Asia/Dubai":"Dubai","tz.Asia/Gaza":"Gaza","tz.Asia/Irkutsk":"Irkutsk","tz.Asia/Jakarta":"Jakarta","tz.Asia/Jerusalem":"Jerusalem","tz.Asia/Riyadh":"Riyadh","tz.Atlantic/Azores":"Azores","tz.Atlantic/Cape_Verde":"Cape Verde","tz.Australia/Adelaide":"Australia - Adelaide","tz.Australia/Brisbane":"Australia - Brisbane","tz.Australia/Darwin":"Australia - Darwin","tz.Australia/Eucla":"Australia - Eucla","tz.Australia/Lord_Howe":"Australia - Lord Howe","tz.Australia/Perth":"Australia - Perth","tz.Australia/Sydney":"Australia - Sydney","tz.utc":"UTC","tz.Asia/Kamchatka":"Kamchatka","tz.Pacific/Apia":"Apia","tz.Pacific/Auckland":"Auckland","tz.Pacific/Chatham":"Chatham","tz.Pacific/Easter":"Easter","tz.Pacific/Fiji":"Fiji","tz.Pacific/Gambier":"Gambier","tz.Pacific/Kiritimati":"Kiritimati","tz.Pacific/Marquesas":"Marquesas","tz.Pacific/Norfolk":"Norfolk","tz.Pacific/Noumea":"Noumea","tz.Pacific/Pago_Pago":"Pago Pago","tz.Pacific/Pitcairn":"Pitcairn","tz.Pacific/Tarawa":"Tarawa","tz.Pacific/Tongatapu":"Tongatapu","tz.group.africa":"Africa","tz.group.america":"America","tz.group.antarctica":"Antarctica","tz.group.arctic":"Arctic","tz.group.asia":"Asia","tz.group.atlantic":"Atlantic","tz.group.australia":"Australia","tz.group.europe":"Europe","tz.group.indian":"Indian","tz.group.pacific":"Pacific","tz.group.us":"US","tz.America/Santa_Isabel":"Santa Isabel","tz.Asia/Kabul":"Kabul","tz.Asia/Karachi":"Karachi","tz.Asia/Kathmandu":"Kathmandu","tz.Asia/Kolkata":"Kolkata","tz.Asia/Krasnoyarsk":"Krasnoyarsk","tz.Asia/Omsk":"Omsk","tz.Asia/Rangoon":"Rangoon","tz.Asia/Shanghai":"Shanghai","tz.Asia/Tehran":"Tehran","tz.Asia/Tokyo":"Tokyo","tz.Asia/Vladivostok":"Vladivostok","tz.Asia/Yakutsk":"Yakutsk","tz.Asia/Yerevan":"Yerevan","tz.America/Santo_Domingo":"Santo Domingo"}}}]); |
log10 = Math.log(10);
log100 = Math.log(100);
log1000 = Math.log(1000);
NUMBER_SUFFIXES = ["K", "M", "B", "T", "Qa", "Qt", "Sx", "Sp", "Oc", "Nn",
"Dc", "UDc", "DDc", "TDc", "QaDc", "QtDc", "SxDc", "SpDc", "ODc", "NDc",
"Vi", "UVi", "DVi", "TVi", "QaVi", "QtVi", "SxVi", "SpVi", "OcVi", "NnVi",
"Tg", "UTg", "DTg", "TTg", "QaTg", "QtTg", "SxTg", "SpTg", "OcTg", "NnTg",
"Qd", "UQd", "DQd", "TQd", "QaQd", "QtQd", "SxQd", "SpQd", "OcQd", "NnQd",
"Qq", "UQq", "DQq", "TQq", "QaQq", "QtQq", "SxQq", "SpQq", "OcQq", "NnQq",
"Sg"
];
function format_number(num) {
if(num < 1000) {
return Math.floor(num);
}
var digits = Math.floor(Math.log(num) / log10 + 0.1);
var suffix = NUMBER_SUFFIXES[Math.floor(digits / 3)-1];
var smaller = (num / Math.pow(10, Math.floor(digits/3)*3));
var fmted;
if(smaller >= 100) fmted = smaller.toFixed(0);
else if(smaller >= 10) fmted = smaller.toFixed(1);
else fmted = smaller.toFixed(2);
return fmted + suffix;
}
// Borrowed with gratitude from http://stackoverflow.com/a/9083857
Number.prototype.toRoman= function () {
var num = Math.floor(this),
val, s= '', i= 0,
v = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1],
r = ['M', 'CM', 'D', 'CD', 'C', 'XC', 'L', 'XL', 'X', 'IX', 'V', 'IV', 'I'];
function toBigRoman(n) {
var ret = '', n1 = '', rem = n;
while (rem > 1000) {
var prefix = '', suffix = '', n = rem, s = '' + rem, magnitude = 1;
while (n > 1000) {
n /= 1000;
magnitude *= 1000;
prefix += '(';
suffix += ')';
}
n1 = Math.floor(n);
rem = s - (n1 * magnitude);
ret += prefix + n1.toRoman() + suffix;
}
return ret + rem.toRoman();
}
if (this - num || num < 1) num = 0;
if (num > 3999) return toBigRoman(num);
while (num) {
val = v[i];
while (num >= val) {
num -= val;
s += r[i];
}
++i;
}
return s;
};
Number.fromRoman = function (roman, accept) {
var s = roman.toUpperCase().replace(/ +/g, ''),
L = s.length, sum = 0, i = 0, next, val,
R = { M: 1000, D: 500, C: 100, L: 50, X: 10, V: 5, I: 1 };
function fromBigRoman(rn) {
var n = 0, x, n1, S, rx =/(\(*)([MDCLXVI]+)/g;
while ((S = rx.exec(rn)) != null) {
x = S[1].length;
n1 = Number.fromRoman(S[2])
if (isNaN(n1)) return NaN;
if (x) n1 *= Math.pow(1000, x);
n += n1;
}
return n;
}
if (/^[MDCLXVI)(]+$/.test(s)) {
if (s.indexOf('(') == 0) return fromBigRoman(s);
while (i < L) {
val = R[s.charAt(i++)];
next = R[s.charAt(i)] || 0;
if (next - val > 0) val *= -1;
sum += val;
}
if (accept || sum.toRoman() === s) return sum;
}
return NaN;
};
Number.prototype.formatBig = function() {
var num = this;
var sign = 1;
if(num < 0) {
sign = -1;
num *= -1;
}
if(num < 1 && num > 0) {
return (sign * num).toFixed(2);
}
if(num < 1000) {
return sign * Math.floor(num);
}
var digits = Math.floor(Math.log(num) / log10 + 0.1);
var suffix = NUMBER_SUFFIXES[Math.floor(digits / 3)-1];
if(!suffix) return num.toExponential(2);
var smaller = (num / Math.pow(10, Math.floor(digits/3)*3));
var fmted;
if(smaller >= 100) fmted = (sign * smaller).toFixed(0);
else if(smaller >= 10) fmted = (sign * smaller).toFixed(1);
else fmted = (sign * smaller).toFixed(2);
return fmted + suffix;
}
Number.prototype.formatByPercent = function() {
var num = this;
num -= 1;
if(num < 0.1 && num % 0.01) {
return (num * 100).toFixed(2) + '%';
} else if(num <= 10) {
return Math.floor(num * 100) + '%';
} else {
return (num + 1).formatBig() + 'x';
}
}
Number.prototype.formatPercentOf = function() {
var num = this;
if(num < 0.1 && num % 0.01) {
return (num * 100).toFixed(2) + '% of';
} else if(num <= 2.5) {
return Math.floor(num * 100) + '% of';
} else {
return num.formatBig() + 'x';
}
} |
/*
Language: HTML, XML
Website: https://www.w3.org/XML/
Category: common
*/
export default function(hljs) {
var XML_IDENT_RE = '[A-Za-z0-9\\._:-]+';
var XML_ENTITIES = {
className: 'symbol',
begin: '&[a-z]+;|&#[0-9]+;|&#x[a-f0-9]+;'
};
var XML_META_KEYWORDS = {
begin: '\\s',
contains:[
{
className: 'meta-keyword',
begin: '#?[a-z_][a-z1-9_-]+',
illegal: '\\n',
}
]
};
var XML_META_PAR_KEYWORDS = hljs.inherit(XML_META_KEYWORDS, {begin: '\\(', end: '\\)'});
var APOS_META_STRING_MODE = hljs.inherit(hljs.APOS_STRING_MODE, {className: 'meta-string'});
var QUOTE_META_STRING_MODE = hljs.inherit(hljs.QUOTE_STRING_MODE, {className: 'meta-string'});
var TAG_INTERNALS = {
endsWithParent: true,
illegal: /</,
relevance: 0,
contains: [
{
className: 'attr',
begin: XML_IDENT_RE,
relevance: 0
},
{
begin: /=\s*/,
relevance: 0,
contains: [
{
className: 'string',
endsParent: true,
variants: [
{begin: /"/, end: /"/, contains: [XML_ENTITIES]},
{begin: /'/, end: /'/, contains: [XML_ENTITIES]},
{begin: /[^\s"'=<>`]+/}
]
}
]
}
]
};
return {
aliases: ['html', 'xhtml', 'rss', 'atom', 'xjb', 'xsd', 'xsl', 'plist', 'wsf', 'svg'],
case_insensitive: true,
contains: [
{
className: 'meta',
begin: '<![a-z]', end: '>',
relevance: 10,
contains: [
XML_META_KEYWORDS,
QUOTE_META_STRING_MODE,
APOS_META_STRING_MODE,
XML_META_PAR_KEYWORDS,
{
begin: '\\[', end: '\\]',
contains:[
{
className: 'meta',
begin: '<![a-z]', end: '>',
contains: [
XML_META_KEYWORDS,
XML_META_PAR_KEYWORDS,
QUOTE_META_STRING_MODE,
APOS_META_STRING_MODE
]
}
]
}
]
},
hljs.COMMENT(
'<!--',
'-->',
{
relevance: 10
}
),
{
begin: '<\\!\\[CDATA\\[', end: '\\]\\]>',
relevance: 10
},
XML_ENTITIES,
{
className: 'meta',
begin: /<\?xml/, end: /\?>/, relevance: 10
},
{
begin: /<\?(php)?/, end: /\?>/,
subLanguage: 'php',
contains: [
// We don't want the php closing tag ?> to close the PHP block when
// inside any of the following blocks:
{begin: '/\\*', end: '\\*/', skip: true},
{begin: 'b"', end: '"', skip: true},
{begin: 'b\'', end: '\'', skip: true},
hljs.inherit(hljs.APOS_STRING_MODE, {illegal: null, className: null, contains: null, skip: true}),
hljs.inherit(hljs.QUOTE_STRING_MODE, {illegal: null, className: null, contains: null, skip: true})
]
},
{
className: 'tag',
/*
The lookahead pattern (?=...) ensures that 'begin' only matches
'<style' as a single word, followed by a whitespace or an
ending braket. The '$' is needed for the lexeme to be recognized
by hljs.subMode() that tests lexemes outside the stream.
*/
begin: '<style(?=\\s|>)', end: '>',
keywords: {name: 'style'},
contains: [TAG_INTERNALS],
starts: {
end: '</style>', returnEnd: true,
subLanguage: ['css', 'xml']
}
},
{
className: 'tag',
// See the comment in the <style tag about the lookahead pattern
begin: '<script(?=\\s|>)', end: '>',
keywords: {name: 'script'},
contains: [TAG_INTERNALS],
starts: {
end: '\<\/script\>', returnEnd: true,
subLanguage: ['actionscript', 'javascript', 'handlebars', 'xml']
}
},
{
className: 'tag',
begin: '</?', end: '/?>',
contains: [
{
className: 'name', begin: /[^\/><\s]+/, relevance: 0
},
TAG_INTERNALS
]
}
]
};
}
|
#!/usr/bin/python
# Copyright (c) 2020, 2021 Oracle and/or its affiliates.
# This software is made available to you under the terms of the GPL 3.0 license or the Apache 2.0 license.
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
# Apache License v2.0
# See LICENSE.TXT for details.
# GENERATED FILE - DO NOT EDIT - MANUAL CHANGES WILL BE OVERWRITTEN
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {
"metadata_version": "1.1",
"status": ["preview"],
"supported_by": "community",
}
DOCUMENTATION = """
---
module: oci_resource_manager_resource_discovery_service_facts
short_description: Fetches details about one or multiple ResourceDiscoveryService resources in Oracle Cloud Infrastructure
description:
- Fetches details about one or multiple ResourceDiscoveryService resources in Oracle Cloud Infrastructure
- Returns a list of supported services for Resource Discovery. For reference on service names, see the L(Terraform provider
documentation,https://www.terraform.io/docs/providers/oci/guides/resource_discovery.html#services).
version_added: "2.9.0"
author: Oracle (@oracle)
options:
compartment_id:
description:
- A filter to return only resources that exist in the compartment, identified by
L(OCID,https://docs.cloud.oracle.com/iaas/Content/General/Concepts/identifiers.htm).
type: str
extends_documentation_fragment: [ oracle.oci.oracle, oracle.oci.oracle_name_option ]
"""
EXAMPLES = """
- name: List resource_discovery_services
oci_resource_manager_resource_discovery_service_facts:
compartment_id: "ocid1.compartment.oc1..xxxxxxEXAMPLExxxxxx"
"""
RETURN = """
resource_discovery_services:
description:
- List of ResourceDiscoveryService resources
returned: on success
type: complex
contains:
name:
description:
- "A supported service. Example: `core`
For reference on service names, see the L(Terraform provider
documentation,https://www.terraform.io/docs/providers/oci/guides/resource_discovery.html#services)."
returned: on success
type: str
sample: core
discovery_scope:
description:
- "The scope of the service as used with Resource Discovery.
This property determines the type of compartment OCID required: root compartment (`TENANCY`) or not (`COMPARTMENT`).
For example, `identity` is at the root compartment scope while `database` is at the compartment scope."
returned: on success
type: str
sample: TENANCY
sample: [{
"name": "core",
"discovery_scope": "TENANCY"
}]
"""
from ansible.module_utils.basic import AnsibleModule
from ansible_collections.oracle.oci.plugins.module_utils import oci_common_utils
from ansible_collections.oracle.oci.plugins.module_utils.oci_resource_utils import (
OCIResourceFactsHelperBase,
get_custom_class,
)
try:
from oci.resource_manager import ResourceManagerClient
HAS_OCI_PY_SDK = True
except ImportError:
HAS_OCI_PY_SDK = False
class ResourceDiscoveryServiceFactsHelperGen(OCIResourceFactsHelperBase):
"""Supported operations: list"""
def get_required_params_for_list(self):
return []
def list_resources(self):
optional_list_method_params = [
"compartment_id",
"name",
]
optional_kwargs = dict(
(param, self.module.params[param])
for param in optional_list_method_params
if self.module.params.get(param) is not None
)
return oci_common_utils.list_all_resources(
self.client.list_resource_discovery_services, **optional_kwargs
)
ResourceDiscoveryServiceFactsHelperCustom = get_custom_class(
"ResourceDiscoveryServiceFactsHelperCustom"
)
class ResourceFactsHelper(
ResourceDiscoveryServiceFactsHelperCustom, ResourceDiscoveryServiceFactsHelperGen
):
pass
def main():
module_args = oci_common_utils.get_common_arg_spec()
module_args.update(dict(compartment_id=dict(type="str"), name=dict(type="str"),))
module = AnsibleModule(argument_spec=module_args)
if not HAS_OCI_PY_SDK:
module.fail_json(msg="oci python sdk required for this module.")
resource_facts_helper = ResourceFactsHelper(
module=module,
resource_type="resource_discovery_service",
service_client_class=ResourceManagerClient,
namespace="resource_manager",
)
result = []
if resource_facts_helper.is_list():
result = resource_facts_helper.list()
else:
resource_facts_helper.fail()
module.exit_json(resource_discovery_services=result)
if __name__ == "__main__":
main()
|
### module for basic operations with ellone metric
from scipy.spatial.distance import cityblock as ellone
from scipy.spatial.distance import pdist
def get_metric(params=None):
met_func=lambda pt1,pt2: ellone(pt1,pt2) if params is None else lambda pt1,pt2: ellone(params*pt1,params*pt2)
matr_func=lambda points_list: pdist(points_list,metric='cityblock') if params is None else lambda points_list: pdist([params*pt for pt in points_list],metric='cityblock')
return met_func,matr_func
def midpoint(pt1,pt2):
return 0.5*(pt1+pt2)
|
import FilterProvider from "./FilterProvider";
import Range from "./Range";
import Fuzzy from "./Fuzzy";
import Exact from "./Exact";
import Search from "./Search";
import Filter from "./Filter";
import WithFilteredData from "./WithFilteredData";
export {
FilterProvider,
Filter,
Exact,
Range,
Fuzzy,
Search,
WithFilteredData
};
|
const { all } = require('../../dist/cjs/index')
const RAll = require('ramda/src/all')
const fpEvery = require('lodash/fp/every')
const _every = require('lodash/every')
const Benchmark = require('benchmark')
const runSuite = require('../runSuite')
const suite = new Benchmark.Suite('all')
const array = Array(10000)
.fill(0)
.map(x => Math.floor(Math.random(1) * 10000))
const greaterThanHundred = x => x > 100
suite
.add('benri', () => {
all(greaterThanHundred)(array)
})
.add('ramda', () => {
RAll(greaterThanHundred)(array)
})
.add('lodash/fp', () => {
fpEvery(greaterThanHundred)(array)
})
.add('lodash', () => {
_every(array, greaterThanHundred)
})
.add('native', () => {
array.every(greaterThanHundred)
})
runSuite(suite)
|
function bellyButton(id) {
d3.json("samples.json").then((data) => {
let samplesFiltered = data.samples.filter(obj => obj.id == id);
let otu_ids_OTU = samplesFiltered[0].otu_ids.map(otu => "OTU " + otu);
let otu_labels = samplesFiltered[0].otu_labels;
let sample_values = samplesFiltered[0].sample_values;
let otu_ids = samplesFiltered[0].otu_ids;
let otu_ids_slice = otu_ids_OTU.slice(0, 10).reverse();
let otu_labels_slice = otu_labels.slice(0, 10).reverse();
let sample_values_slice = sample_values.slice(0, 10).reverse();
var barTrace = {
x: sample_values_slice,
y: otu_ids_slice,
orientation: 'h',
type:'bar',
text: otu_labels
};
var barData = [barTrace];
var layout = {
width: 1000
}
Plotly.newPlot('bar', barData, layout);
var bubbleTrace = {
x: otu_ids,
y: sample_values,
mode: 'markers',
marker: {
color: otu_ids,
size: sample_values
}
};
var bubbleData = [bubbleTrace];
var layout = {
showlegend: false,
height: 600,
width: 1000
};
Plotly.newPlot('bubble', bubbleData, layout);
let metaDataFiltered = data.metadata.filter(obj => obj.id == id);
console.log(metaDataFiltered);
let dataBox = d3.select("#sample-metadata");
dataBox.html("")
Object.entries(metaDataFiltered[0]).forEach(([key, value]) => {
dataBox.append("h5").text(key + ":" + value)
});
})
}
d3.json("samples.json").then((data) => {
let dropdown = d3.select("#selDataset");
data.names.forEach((id) => {
dropdown.append("option").text(id).property("value", id);
})
bellyButton(data.names[0])
})
function optionChanged(selectedID) {
bellyButton(selectedID)
} |
'use strict'
const path = require('path')
module.exports = {
webpack: {
resolve: {
alias: {
'node-forge': path.resolve(
path.dirname(require.resolve('libp2p-crypto')),
'../vendor/forge.bundle.js'
)
}
}
}
}
|
from .optimizer import Optimizer
import numpy as np
import time
from multiprocessing import Pool
class ParticleBFGS(Optimizer):
"""
BFGS
"""
def __init__(self, alpha=0.01, beta=0.0, gamma=0.9, n_epochs=1, mini_batch_size=1, verbosity=2, weight_update="sd",
cost_freq=2, position_grad=True, alpha_b=0.01, alpha_q=None, alpha_r=0.01, alpha_t=0.01, init_v=0.0,
n_threads=1, chunk_size=10, epsilon=10e-8, gamma2=0.1, alpha_decay=None, use_log=False):
"""
:param alpha: learning rate
"""
super().__init__()
self.alpha = alpha
self.beta = beta
self.gamma = gamma
self.gamma2 = gamma2
self.epsilon = epsilon
self.n_epochs = n_epochs
self.mini_batch_size = mini_batch_size
self.verbosity = verbosity
self.cost_freq = cost_freq
self.position_grad = position_grad # Turn off position gradient?
self.alpha_decay = alpha_decay
# Weight gradients, to keep around for a step
self.dc_db = None
self.dc_dq = None
self.dc_dr = None
self.dc_dt = None
self.dc_dzeta = None
# BFGS stuff
self.s_b = None
self.s_q = None
self.s_rx = None
self.s_ry = None
self.s_rz = None
self.s_t = None
self.y_b = None
self.y_q = None
self.y_rx = None
self.y_ry = None
self.y_rz = None
self.y_t = None
self.p_b = None
self.p_q = None
self.p_rx = None
self.p_ry = None
self.p_rz = None
self.p_t = None
self.Bk_inv = None
self.total = 0
self.n_threads = n_threads
self.chunk_size = chunk_size
def cost_gradient_parallel(self, network, data_X, data_Y):
with Pool(processes=self.n_threads) as pool:
offset = 0
chunks = len(data_X) / self.chunk_size
while offset < len(data_X):
data_X_sub = data_X[offset:(offset+self.chunk_size), :]
data_Y_sub = data_Y[offset:(offset+self.chunk_size), :]
data_X_split = np.array_split(data_X_sub, self.n_threads)
data_Y_split = np.array_split(data_Y_sub, self.n_threads)
data_XY_list = [(data_X_split[i], data_Y_split[i], self.n_threads * chunks) for i in range(self.n_threads)]
result = pool.map(network.cost_gradient_thread, data_XY_list)
for t, result_t in enumerate(result):
tmp_dc_db = result_t[0]
tmp_dc_dq = result_t[1]
tmp_dc_dr = result_t[2]
tmp_dc_dt = result_t[3]
tmp_dc_dzeta = result_t[4]
if t == 0 and offset == 0:
self.dc_db = tmp_dc_db
self.dc_dq = tmp_dc_dq
self.dc_dr = tmp_dc_dr
self.dc_dt = tmp_dc_dt
self.dc_dzeta = tmp_dc_dzeta
else:
for l, tmp_b in enumerate(tmp_dc_db):
self.dc_db[l] += tmp_b
for l, tmp_q in enumerate(tmp_dc_dq):
self.dc_dq[l] += tmp_q
for l, tmp_t in enumerate(tmp_dc_dt):
self.dc_dt[l] += tmp_t
for l, tmp_z in enumerate(tmp_dc_dzeta):
self.dc_dzeta[l] += tmp_z
for i in range(3):
for l, tmp_r in enumerate(tmp_dc_dr[i]):
self.dc_dr[i][l] += tmp_r
offset += self.chunk_size
def optimize(self, network, data_X, data_Y):
"""
:return: optimized network
"""
optimize_start_time = time.time()
indexes = np.arange(len(data_X))
if self.verbosity > 0:
c = network.cost(data_X, data_Y)
print("Cost before epochs: {}".format(c))
# Epoch loop
for epoch in range(self.n_epochs):
epoch_start_time = time.time()
# TODO: Doubles memory usage of data by having a copy. Figure out how to shuffle data_X with data_Y
# Shuffle data by index
np.random.shuffle(indexes) # in-place shuffle
shuffle_X = np.asarray([data_X[i] for i in indexes])
shuffle_Y = np.asarray([data_Y[i] for i in indexes])
# Split into mini-batches
for m in range(len(data_X) // self.mini_batch_size): # not guaranteed to divide perfectly, might miss a few
mini_X = shuffle_X[m*self.mini_batch_size:(m+1)*self.mini_batch_size]
mini_Y = shuffle_Y[m*self.mini_batch_size:(m+1)*self.mini_batch_size]
# Compute gradient for mini-batch
if self.n_threads > 1:
self.cost_gradient_parallel(network, mini_X, mini_Y)
else:
self.dc_db, self.dc_dq, self.dc_dr, self.dc_dt = network.cost_gradient(mini_X, mini_Y)
# Update weights and biases
self.weight_update(network)
# Alpha decay
if self.alpha_decay is not None:
self.alpha *= 1.0 - self.alpha_decay
if self.verbosity > 1 and m % self.cost_freq == 0:
c = network.cost(data_X, data_Y)
print("Cost at epoch {} mini-batch {}: {:g}".format(epoch, m, c))
# TODO: could output projected time left based on mini-batch times
# Temporary
# print(np.sqrt(self.ms_dq[0]))
if self.verbosity > 0:
c = network.cost(data_X, data_Y)
print("Cost after epoch {}: {:g}".format(epoch, c))
print("Epoch time: {:g} s".format(time.time() - epoch_start_time))
if self.verbosity > 0:
c = network.cost(data_X, data_Y)
print("\n\nCost after optimize run: {:g}".format(c))
print("Optimize run time: {:g} s".format(time.time() - optimize_start_time))
return network
def flatten(self, network, b, q, rx, ry, rz, t):
flat = np.zeros(self.total)
j = 0
for i in range(network.particle_input.output_size):
flat[j+i] = rx[0][i]
j += 1
for i in range(network.particle_input.output_size):
flat[j+i] = ry[0][i]
j += 1
for i in range(network.particle_input.output_size):
flat[j+i] = rz[0][i]
j += 1
for i in range(network.particle_input.output_size):
flat[j+i] = t[0][i]
j += 1
for l, layer in enumerate(network.layers):
for i in range(layer.output_size):
flat[j+i] = rx[l+1][i]
j += 1
for i in range(layer.output_size):
flat[j+i] = ry[l+1][i]
j += 1
for i in range(layer.output_size):
flat[j+i] = rz[l+1][i]
j += 1
for i in range(layer.output_size):
flat[j+i] = t[l+1][i]
j += 1
for i in range(layer.output_size):
flat[j+i] = q[l][i]
j += 1
for i in range(layer.output_size):
flat[j+i] = b[l][0][i]
j += 1
return flat
def unflatten(self, network, flat):
b = []
q = []
rx = [np.zeros(network.particle_input.output_size)]
ry = [np.zeros(network.particle_input.output_size)]
rz = [np.zeros(network.particle_input.output_size)]
t = [np.zeros(network.particle_input.output_size)]
for l, layer in enumerate(network.layers):
b.append(np.zeros(layer.b.output_size))
q.append(np.zeros(layer.q.output_size))
rx.append(np.zeros(layer.output_size))
ry.append(np.zeros(layer.output_size))
rz.append(np.zeros(layer.output_size))
t.append(np.zeros(layer.output_size))
j = 0
for i in range(network.particle_input.output_size):
rx[0][i] = flat[j + i]
j += 1
for i in range(network.particle_input.output_size):
ry[0][i] = flat[j + i]
j += 1
for i in range(network.particle_input.output_size):
rz[0][i] = flat[j + i]
j += 1
for i in range(network.particle_input.output_size):
t[0][i] = flat[j + i]
j += 1
for l, layer in enumerate(network.layers):
for i in range(layer.output_size):
rx[l + 1][i] = flat[j + i]
j += 1
for i in range(layer.output_size):
ry[l + 1][i] = flat[j + i]
j += 1
for i in range(layer.output_size):
rz[l + 1][i] = flat[j + i]
j += 1
for i in range(layer.output_size):
t[l + 1][i] = flat[j + i]
j += 1
for i in range(layer.output_size):
q[l][i] = flat[j + i]
j += 1
for i in range(layer.output_size):
b[l][0][i] = flat[j + i]
j += 1
return b, q, rx, ry, rz, t
def weight_update(self, network):
self.s_b = None
self.s_q = None
self.s_rx = None
self.s_ry = None
self.s_rz = None
self.s_t = None
self.y_b = None
self.y_q = None
self.y_rx = None
self.y_ry = None
self.y_rz = None
self.y_t = None
self.p_b = None
self.p_q = None
self.p_rx = None
self.p_ry = None
self.p_rz = None
self.p_t = None
self.Bk_inv = None
# Initialize
if self.Bk_inv is None:
self.s_b = []
self.s_q = []
self.s_rx = [np.zeros(network.particle_input.output_size)]
self.s_ry = [np.zeros(network.particle_input.output_size)]
self.s_rz = [np.zeros(network.particle_input.output_size)]
self.s_t = [np.zeros(network.particle_input.output_size)]
self.y_b = []
self.y_q = []
self.y_rx = [np.zeros(network.particle_input.output_size)]
self.y_ry = [np.zeros(network.particle_input.output_size)]
self.y_rz = [np.zeros(network.particle_input.output_size)]
self.y_t = [np.zeros(network.particle_input.output_size)]
self.p_b = []
self.p_q = []
self.p_rx = [np.zeros(network.particle_input.output_size)]
self.p_ry = [np.zeros(network.particle_input.output_size)]
self.p_rz = [np.zeros(network.particle_input.output_size)]
self.p_t = [np.zeros(network.particle_input.output_size)]
self.total = 4 * network.particle_input.output_size
for l, layer in enumerate(network.layers):
self.s_b.append(np.zeros(layer.b.output_size))
self.s_q.append(np.zeros(layer.q.output_size))
self.s_rx.append(np.zeros(layer.output_size))
self.s_ry.append(np.zeros(layer.output_size))
self.s_rz.append(np.zeros(layer.output_size))
self.s_t.append(np.zeros(layer.output_size))
self.y_b.append(np.zeros(layer.b.output_size))
self.y_q.append(np.zeros(layer.q.output_size))
self.y_rx.append(np.zeros(layer.output_size))
self.y_ry.append(np.zeros(layer.output_size))
self.y_rz.append(np.zeros(layer.output_size))
self.y_t.append(np.zeros(layer.output_size))
self.p_b.append(np.zeros(layer.b.output_size))
self.p_q.append(np.zeros(layer.q.output_size))
self.p_rx.append(np.zeros(layer.output_size))
self.p_ry.append(np.zeros(layer.output_size))
self.p_rz.append(np.zeros(layer.output_size))
self.p_t.append(np.zeros(layer.output_size))
self.total += 6 * layer.b.output_size
self.Bk_inv = np.eye(self.total)
# 1. Compute pk
p = self.Bk_inv.dot(network, self.flatten(self.dc_db, self.dc_dq, self.dc_dr[0], self.dc_dr[1], self.dc_dr[2], self.dc_dt))
self.p_b, self.p_q, self.p_rx, self.p_ry, self.p_rz, self.p_t = self.unflatten(network, p)
# 2+3. Update and take step
self.s_t[0] = -self.alpha * self.p_t[0]
self.s_rx[0] = -self.alpha * self.p_rx[0]
self.s_ry[0] = -self.alpha * self.p_ry[0]
self.s_rz[0] = -self.alpha * self.p_rz[0]
for l, layer in enumerate(network.layers):
self.s_b[l] = -self.alpha * self.p_b[l]
self.s_q[l] = -self.alpha * self.p_q[l]
self.s_t[l+1] = -self.alpha * self.p_t[l+1]
self.s_rx[l+1] = -self.alpha * self.p_rx[l+1]
self.s_ry[l+1] = -self.alpha * self.p_ry[l+1]
self.s_rz[l+1] = -self.alpha * self.p_rz[l+1]
network.particle_input.theta += self.s_t[0]
network.particle_input.rx += self.s_rx[0]
network.particle_input.ry += self.s_ry[0]
network.particle_input.rz += self.s_rz[0]
for l, layer in enumerate(network.layers):
layer.b += self.s_b[l]
layer.q += self.s_q[l]
layer.theta += self.s_t[l+1]
layer.rx += self.s_rx[l+1]
layer.ry += self.s_ry[l+1]
layer.rz += self.s_rz[l+1]
# 4.
|
async function newFormHandler(event) {
event.preventDefault();
const title = document.querySelector('input[name="post-title"]').value;
const content = document.querySelector('textarea[name="content"]').value;
const response = await fetch(`/api/posts`, {
method: "POST",
body: JSON.stringify({
title,
content,
}),
headers: {
"Content-Type": "application/json",
},
});
if (response.ok) {
document.location.reload();
} else {
alert(response.statusText);
}
}
document
.querySelector(".new-post-form")
.addEventListener("submit", newFormHandler);
|
import axios from 'axios'
import getconfig from 'next/config'
import SinglePost from 'components/SinglePost'
export default function Home({singleposts, allcategories, latestposts}) {
return (
<>
{ singleposts.map(singlepost =>(
<SinglePost key={singlepost.id} singlepost={singlepost} allcategories={allcategories} latestposts={latestposts} />
))}
</>
)
}
const { publicRuntimeConfig } = getconfig()
export async function getServerSideProps(context){
const { slug } = context.query
const res = await axios.get(`${publicRuntimeConfig.API_URL}/posts?slug=${slug}`);
const getdata = res.data;
const allcategory = await axios.get(`${publicRuntimeConfig.API_URL}/categories`);
const getcategories = allcategory.data;
const latestpost = await axios.get(`${publicRuntimeConfig.API_URL}/posts?_sort=published_at:DESC&_limit=4`);
const getlatestpost = latestpost.data;
return { props : {
singleposts: getdata,
allcategories: getcategories,
latestposts: getlatestpost
} };
} |
/*
* Copyright (C) 2020 Tencent Cloud.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
'use strict';
const { sign } = require('../common');
/**
* 请求腾讯云VOD接口公共方法
* @param {string} action - 接口请求action
* @param {object} payload - 接口请求体
* @return {object} API返回的有效数据
*/
async function request(action, payload) {
const [timestamp, authorization] = sign('vod', JSON.stringify(payload));
const { res } = await uniCloud.httpclient.request('https://vod.tencentcloudapi.com', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-TC-Action': action,
'X-TC-Version': '2018-07-17',
'X-TC-Timestamp': timestamp,
'Authorization': authorization,
},
data: payload,
dataType: 'json',
});
const { status, statusMessage, data } = res;
if (status !== 200) {
throw new Error(`${action}接口调用失败[${status} - ${statusMessage}]`);
}
if (data.Response.Error) {
throw new Error(data.Response.Error.Message);
}
return data.Response;
}
module.exports = { request };
|
import { SEARCH_VALUE_CHANGE } from '../../_actions/search.actions'
export default (
state =
$('#search-input')
.val() || '',
{
type,
value
}
) =>
type === SEARCH_VALUE_CHANGE ?
value
: state |
/*! Select2 4.0.0 | https://github.com/select2/select2/blob/master/LICENSE.md */
(function(){if(jQuery&&jQuery.fn&&jQuery.fn.select2&&jQuery.fn.select2.amd)var e=jQuery.fn.select2.amd;return e.define("select2/i18n/fr",[],function(){return{inputTooLong:function(e){var t=e.input.length-e.maximum,n="Supprimez "+t+" caractère";return t!==1&&(n+="s"),n},inputTooShort:function(e){var t=e.minimum-e.input.length,n="Saisissez "+t+" caractère";return t!==1&&(n+="s"),n},loadingMore:function(){return"Chargement de résultats supplémentaires…"},maximumSelected:function(e){var t="Vous pouvez seulement sélectionner "+e.maximum+" élément";return e.maximum!==1&&(t+="s"),t},noResults:function(){return"Aucun résultat trouvé"},searching:function(){return"Recherche en cours…"}}}),{define:e.define,require:e.require}})(); |
from ftplib import FTP_TLS
HOSTNAME = 'ftp.pureftpd.org'
USERNAME = 'anonymous'
PASSWORD = ''
with FTP_TLS(host=HOSTNAME, user=USERNAME, passwd=PASSWORD, timeout=30) as ftps:
ftps.dir()
# drwxr-xr-x 18 1000 1008 1024 Jul 21 2016 .
# drwxr-xr-x 18 1000 1008 1024 Jul 21 2016 ..
# lrwxr-xr-x 1 1000 20 20 Jun 20 2011 6jack -> pure-ftpd/misc/6jack
# lrwxr-xr-x 1 1000 1008 12 Jan 24 2012 OpenBSD -> misc/OpenBSD
# drwxr-xr-x 2 1000 1008 512 Feb 10 2015 antilink
# lrwxr-xr-x 1 0 1008 24 Feb 1 2006 blogbench -> pure-ftpd/misc/blogbench
# lrwxr-xr-x 1 0 1008 21 Feb 1 2006 bsdcam -> pure-ftpd/misc/bsdcam
# ...
|
describe("", () => {
it("It worked!", () => {
// expect().to.be.an("");
});
});
|
var assert = require('assert');
var R = require('../source/index.js');
var eq = require('./shared/eq.js');
var Maybe = require('./shared/Maybe.js');
describe('unnest', function() {
it('only flattens one layer deep of a nested list', function() {
var nest = [1, [2], [3, [4, 5], 6, [[[7], 8]]], 9, 10];
eq(R.unnest(nest), [1, 2, 3, [4, 5], 6, [[[7], 8]], 9, 10]);
nest = [[[[3]], 2, 1], 0, [[-1, -2], -3]];
eq(R.unnest(nest), [[[3]], 2, 1, 0, [-1, -2], -3]);
eq(R.unnest([1, 2, 3, 4, 5]), [1, 2, 3, 4, 5]);
});
it('is not destructive', function() {
var nest = [1, [2], [3, [4, 5], 6, [[[7], 8]]], 9, 10];
assert.notStrictEqual(R.unnest(nest), nest);
});
it('handles array-like objects', function() {
var o = {length: 3, 0: [1, 2, [3]], 1: [], 2: ['a', 'b', 'c', ['d', 'e']]};
eq(R.unnest(o), [1, 2, [3], 'a', 'b', 'c', ['d', 'e']]);
});
it('flattens an array of empty arrays', function() {
eq(R.unnest([[], [], []]), []);
eq(R.unnest([]), []);
});
it('is equivalent to R.chain(R.identity)', function() {
var Nothing = Maybe.Nothing;
var Just = Maybe.Just;
eq(R.unnest(Nothing), Nothing);
eq(R.unnest(Just(Nothing)), Nothing);
eq(R.unnest(Just(Just(Nothing))), Just(Nothing));
eq(R.unnest(Just(Just(42))), Just(42));
eq(R.unnest(Just(Just(Just(42)))), Just(Just(42)));
});
});
|
# --------------------------------------------------------
# Swin Transformer
# Copyright (c) 2021 Microsoft
# Licensed under The MIT License [see LICENSE for details]
# Written by Ze Liu
# --------------------------------------------------------
import os
import time
import random
import argparse
import datetime
import numpy as np
import torch
import torch.backends.cudnn as cudnn
import torch.distributed as dist
from timm.loss import LabelSmoothingCrossEntropy, SoftTargetCrossEntropy
from timm.utils import accuracy, AverageMeter
from config import get_config
from models import build_model
from data import build_loader
from lr_scheduler import build_scheduler
from optimizer import build_optimizer
from logger import create_logger
from utils import load_checkpoint, load_pretrained, save_checkpoint, get_grad_norm, auto_resume_helper, reduce_tensor, hammer_save_checkpoint
from ipdb import set_trace as st
try:
# noinspection PyUnresolvedReferences
from apex import amp
except ImportError:
amp = None
def parse_option():
parser = argparse.ArgumentParser('Swin Transformer training and evaluation script', add_help=False)
parser.add_argument('--cfg', type=str, required=True, metavar="FILE", help='path to config file', )
parser.add_argument(
"--opts",
help="Modify config options by adding 'KEY VALUE' pairs. ",
default=None,
nargs='+',
)
# easy config modification
parser.add_argument('--batch-size', type=int, help="batch size for single GPU")
parser.add_argument('--data-path', type=str, help='path to dataset')
parser.add_argument('--zip', action='store_true', help='use zipped dataset instead of folder dataset')
parser.add_argument('--cache-mode', type=str, default='part', choices=['no', 'full', 'part'],
help='no: no cache, '
'full: cache all data, '
'part: sharding the dataset into nonoverlapping pieces and only cache one piece')
parser.add_argument('--pretrained',
help='pretrained weight from checkpoint, could be imagenet22k pretrained weight')
parser.add_argument('--resume', help='resume from checkpoint')
parser.add_argument('--accumulation-steps', type=int, help="gradient accumulation steps")
parser.add_argument('--use-checkpoint', action='store_true',
help="whether to use gradient checkpointing to save memory")
parser.add_argument('--amp-opt-level', type=str, default='O1', choices=['O0', 'O1', 'O2'],
help='mixed precision opt level, if O0, no amp is used')
parser.add_argument('--output', default='output', type=str, metavar='PATH',
help='root of output folder, the full path is <output>/<model_name>/<tag> (default: output)')
parser.add_argument('--tag', help='tag of experiment')
parser.add_argument('--eval', action='store_true', help='Perform evaluation only')
parser.add_argument('--throughput', action='store_true', help='Test throughput only')
# distributed training
parser.add_argument("--local_rank", type=int, required=True, help='local rank for DistributedDataParallel')
args, unparsed = parser.parse_known_args()
config = get_config(args)
return args, config
def main(config):
dataset_train, dataset_val, data_loader_train, data_loader_val, mixup_fn = build_loader(config)
logger.info(f"Creating model:{config.MODEL.TYPE}/{config.MODEL.NAME}")
model = build_model(config)
model.cuda()
logger.info(str(model))
optimizer = build_optimizer(config, model)
if config.AMP_OPT_LEVEL != "O0":
model, optimizer = amp.initialize(model, optimizer, opt_level=config.AMP_OPT_LEVEL)
model = torch.nn.parallel.DistributedDataParallel(model, device_ids=[config.LOCAL_RANK], broadcast_buffers=False)
model_without_ddp = model.module
n_parameters = sum(p.numel() for p in model.parameters() if p.requires_grad)
logger.info(f"number of params: {n_parameters}")
if hasattr(model_without_ddp, 'flops'):
flops = model_without_ddp.flops()
logger.info(f"number of GFLOPs: {flops / 1e9}")
lr_scheduler = build_scheduler(config, optimizer, len(data_loader_train))
if config.AUG.MIXUP > 0.:
# smoothing is handled with mixup label transform
criterion = SoftTargetCrossEntropy()
elif config.MODEL.LABEL_SMOOTHING > 0.:
criterion = LabelSmoothingCrossEntropy(smoothing=config.MODEL.LABEL_SMOOTHING)
else:
criterion = torch.nn.CrossEntropyLoss()
max_accuracy = 0.0
if config.TRAIN.AUTO_RESUME:
resume_file = auto_resume_helper(config.OUTPUT)
if resume_file:
if config.MODEL.RESUME:
logger.warning(f"auto-resume changing resume file from {config.MODEL.RESUME} to {resume_file}")
config.defrost()
config.MODEL.RESUME = resume_file
config.freeze()
logger.info(f'auto resuming from {resume_file}')
else:
logger.info(f'no checkpoint found in {config.OUTPUT}, ignoring auto resume')
if config.MODEL.RESUME:
max_accuracy = load_checkpoint(config, model_without_ddp, optimizer, lr_scheduler, logger)
acc1, acc5, loss = validate(config, data_loader_val, model)
logger.info(f"Accuracy of the network on the {len(dataset_val)} test images: {acc1:.1f}%")
if config.EVAL_MODE:
return
if config.MODEL.PRETRAINED and (not config.MODEL.RESUME):
load_pretrained(config, model_without_ddp, logger)
acc1, acc5, loss = validate(config, data_loader_val, model)
logger.info(f"Accuracy of the network on the {len(dataset_val)} test images: {acc1:.1f}%")
if config.THROUGHPUT_MODE:
throughput(data_loader_val, model, logger)
return
## ============================ add hammer step 1 ============================
from hammer.open_api.hammer_prune import nasOptimizer
from models.swin_transformer import SwinTransformerBlock
fake_inputs = [x.cuda() for x in [torch.randn(1, 3, 224, 224)]]
skip_optimizer = nasOptimizer(model_without_ddp, SwinTransformerBlock, inputs=fake_inputs)
## ============================ add hammer step 1 ============================
logger.info("Start training")
start_time = time.time()
for epoch in range(config.TRAIN.START_EPOCH, config.TRAIN.EPOCHS):
data_loader_train.sampler.set_epoch(epoch)
train_one_epoch(config, model, criterion, data_loader_train, optimizer, epoch, mixup_fn, lr_scheduler,
skip_optimizer)
if dist.get_rank() == 0 and (epoch % config.SAVE_FREQ == 0 or epoch == (config.TRAIN.EPOCHS - 1)):
save_checkpoint(config, epoch, model_without_ddp, max_accuracy, optimizer, lr_scheduler, logger)
acc1, acc5, loss = validate(config, data_loader_val, model)
logger.info(f"Accuracy of the network on the {len(dataset_val)} test images: {acc1:.1f}%")
max_accuracy = max(max_accuracy, acc1)
logger.info(f'Max accuracy: {max_accuracy:.2f}%')
total_time = time.time() - start_time
total_time_str = str(datetime.timedelta(seconds=int(total_time)))
logger.info('Training time {}'.format(total_time_str))
def train_one_epoch(config, model, criterion, data_loader, optimizer, epoch, mixup_fn, lr_scheduler,
skip_optimizer=None):
model.train()
optimizer.zero_grad()
num_steps = len(data_loader)
batch_time = AverageMeter()
loss_meter = AverageMeter()
norm_meter = AverageMeter()
start = time.time()
end = time.time()
for idx, (samples, targets) in enumerate(data_loader):
samples = samples.cuda(non_blocking=True)
targets = targets.cuda(non_blocking=True)
if mixup_fn is not None:
samples, targets = mixup_fn(samples, targets)
outputs = model(samples)
if config.TRAIN.ACCUMULATION_STEPS > 1:
loss = criterion(outputs, targets)
loss = loss / config.TRAIN.ACCUMULATION_STEPS
if config.AMP_OPT_LEVEL != "O0":
with amp.scale_loss(loss, optimizer) as scaled_loss:
scaled_loss.backward()
if config.TRAIN.CLIP_GRAD:
grad_norm = torch.nn.utils.clip_grad_norm_(amp.master_params(optimizer), config.TRAIN.CLIP_GRAD)
else:
grad_norm = get_grad_norm(amp.master_params(optimizer))
else:
loss.backward()
if config.TRAIN.CLIP_GRAD:
grad_norm = torch.nn.utils.clip_grad_norm_(model.parameters(), config.TRAIN.CLIP_GRAD)
else:
grad_norm = get_grad_norm(model.parameters())
if (idx + 1) % config.TRAIN.ACCUMULATION_STEPS == 0:
optimizer.step()
optimizer.zero_grad()
lr_scheduler.step_update(epoch * num_steps + idx)
else:
loss = criterion(outputs, targets)
optimizer.zero_grad()
if config.AMP_OPT_LEVEL != "O0":
with amp.scale_loss(loss, optimizer) as scaled_loss:
scaled_loss.backward()
if config.TRAIN.CLIP_GRAD:
grad_norm = torch.nn.utils.clip_grad_norm_(amp.master_params(optimizer), config.TRAIN.CLIP_GRAD)
else:
grad_norm = get_grad_norm(amp.master_params(optimizer))
else:
loss.backward()
if config.TRAIN.CLIP_GRAD:
grad_norm = torch.nn.utils.clip_grad_norm_(model.parameters(), config.TRAIN.CLIP_GRAD)
else:
grad_norm = get_grad_norm(model.parameters())
optimizer.step()
lr_scheduler.step_update(epoch * num_steps + idx)
## ============================ add hammer step 2 ============================
task = (samples, model, targets, criterion)
skip_optimizer.update(task=task)
## ============================ add hammer step 2 ============================
torch.cuda.synchronize()
# if not np.isnan(grad_norm.detach().cpu().numpy()):
loss_meter.update(loss.item(), targets.size(0))
norm_meter.update(grad_norm)
batch_time.update(time.time() - end)
end = time.time()
if idx % config.PRINT_FREQ == 0:
lr = optimizer.param_groups[0]['lr']
memory_used = torch.cuda.max_memory_allocated() / (1024.0 * 1024.0)
etas = batch_time.avg * (num_steps - idx)
logger.info(
f'Train: [{epoch}/{config.TRAIN.EPOCHS}][{idx}/{num_steps}]\t'
f'eta {datetime.timedelta(seconds=int(etas))} lr {lr:.6f}\t'
f'time {batch_time.val:.4f} ({batch_time.avg:.4f})\t'
f'loss {loss_meter.val:.4f} ({loss_meter.avg:.4f})\t'
f'grad_norm {norm_meter.val:.4f} ({norm_meter.avg:.4f})\t'
f'mem {memory_used:.0f}MB')
## ============================ add hammer step 3 ============================
rate = round(skip_optimizer.resource_fn(w=model.module.nas_weights).item(), 4)
logger.info(f"compression ratio: {rate}")
if dist.get_rank() == 0:
hammer_save_checkpoint(config, epoch, idx, rate, model, optimizer, lr_scheduler, logger)
## ============================ add hammer step 3 ============================
epoch_time = time.time() - start
logger.info(f"EPOCH {epoch} training takes {datetime.timedelta(seconds=int(epoch_time))}")
@torch.no_grad()
def validate(config, data_loader, model):
criterion = torch.nn.CrossEntropyLoss()
model.eval()
batch_time = AverageMeter()
loss_meter = AverageMeter()
acc1_meter = AverageMeter()
acc5_meter = AverageMeter()
end = time.time()
for idx, (images, target) in enumerate(data_loader):
images = images.cuda(non_blocking=True)
target = target.cuda(non_blocking=True)
# compute output
output = model(images)
# measure accuracy and record loss
loss = criterion(output, target)
acc1, acc5 = accuracy(output, target, topk=(1, 5))
acc1 = reduce_tensor(acc1)
acc5 = reduce_tensor(acc5)
loss = reduce_tensor(loss)
loss_meter.update(loss.item(), target.size(0))
acc1_meter.update(acc1.item(), target.size(0))
acc5_meter.update(acc5.item(), target.size(0))
# measure elapsed time
batch_time.update(time.time() - end)
end = time.time()
if idx % config.PRINT_FREQ == 0:
memory_used = torch.cuda.max_memory_allocated() / (1024.0 * 1024.0)
logger.info(
f'Test: [{idx}/{len(data_loader)}]\t'
f'Time {batch_time.val:.3f} ({batch_time.avg:.3f})\t'
f'Loss {loss_meter.val:.4f} ({loss_meter.avg:.4f})\t'
f'Acc@1 {acc1_meter.val:.3f} ({acc1_meter.avg:.3f})\t'
f'Acc@5 {acc5_meter.val:.3f} ({acc5_meter.avg:.3f})\t'
f'Mem {memory_used:.0f}MB')
logger.info(f' * Acc@1 {acc1_meter.avg:.3f} Acc@5 {acc5_meter.avg:.3f}')
return acc1_meter.avg, acc5_meter.avg, loss_meter.avg
@torch.no_grad()
def throughput(data_loader, model, logger):
model.eval()
for idx, (images, _) in enumerate(data_loader):
images = images.cuda(non_blocking=True)
batch_size = images.shape[0]
for i in range(50):
model(images)
torch.cuda.synchronize()
logger.info(f"throughput averaged with 30 times")
tic1 = time.time()
for i in range(30):
model(images)
torch.cuda.synchronize()
tic2 = time.time()
logger.info(f"batch_size {batch_size} throughput {30 * batch_size / (tic2 - tic1)}")
return
if __name__ == '__main__':
_, config = parse_option()
if config.AMP_OPT_LEVEL != "O0":
assert amp is not None, "amp not installed!"
if 'RANK' in os.environ and 'WORLD_SIZE' in os.environ:
rank = int(os.environ["RANK"])
world_size = int(os.environ['WORLD_SIZE'])
print(f"RANK and WORLD_SIZE in environ: {rank}/{world_size}")
else:
rank = -1
world_size = -1
torch.cuda.set_device(config.LOCAL_RANK)
torch.distributed.init_process_group(backend='nccl', init_method='env://', world_size=world_size, rank=rank)
torch.distributed.barrier()
seed = config.SEED + dist.get_rank()
torch.manual_seed(seed)
torch.cuda.manual_seed(seed)
np.random.seed(seed)
random.seed(seed)
cudnn.benchmark = True
# linear scale the learning rate according to total batch size, may not be optimal
linear_scaled_lr = config.TRAIN.BASE_LR * config.DATA.BATCH_SIZE * dist.get_world_size() / 512.0
linear_scaled_warmup_lr = config.TRAIN.WARMUP_LR * config.DATA.BATCH_SIZE * dist.get_world_size() / 512.0
linear_scaled_min_lr = config.TRAIN.MIN_LR * config.DATA.BATCH_SIZE * dist.get_world_size() / 512.0
# gradient accumulation also need to scale the learning rate
if config.TRAIN.ACCUMULATION_STEPS > 1:
linear_scaled_lr = linear_scaled_lr * config.TRAIN.ACCUMULATION_STEPS
linear_scaled_warmup_lr = linear_scaled_warmup_lr * config.TRAIN.ACCUMULATION_STEPS
linear_scaled_min_lr = linear_scaled_min_lr * config.TRAIN.ACCUMULATION_STEPS
config.defrost()
config.TRAIN.BASE_LR = linear_scaled_lr
config.TRAIN.WARMUP_LR = linear_scaled_warmup_lr
config.TRAIN.MIN_LR = linear_scaled_min_lr
config.freeze()
os.makedirs(config.OUTPUT, exist_ok=True)
logger = create_logger(output_dir=config.OUTPUT, dist_rank=dist.get_rank(), name=f"{config.MODEL.NAME}")
if dist.get_rank() == 0:
path = os.path.join(config.OUTPUT, "config.json")
with open(path, "w") as f:
f.write(config.dump())
logger.info(f"Full config saved to {path}")
# print config
logger.info(config.dump())
main(config)
#python main.py --cfg configs/swin_tiny_patch4_window7_224.yaml --batch-size 1 |
# Importing dependencies
import numpy as np
from ..necessities.activation import getActivation
from ..necessities.cost import getCostfunction
from ..necessities.serialization import array2json, json2array
# get_layer
def get_layer(name='dense'):
if name.lower() == 'base': return base
if name.lower() == 'dense':
from .dense import dense
return dense
if name.lower() == 'recurrent':
from .recurrent import recurrent
return recurrent
# Code
class base:
def __init__(self, neurons=10, prevlayer=None, activation='tanh', cost='error'):
# Basic
self.neurons = neurons
self.value = np.atleast_2d(np.zeros((1, self.neurons)))
self.weighted_input = np.atleast_2d(np.zeros((1, self.neurons)))
self.error = np.atleast_2d(np.zeros((1, self.neurons)))
self.delta = np.atleast_2d(np.zeros((1, self.neurons)))
self.remember = np.atleast_2d(np.zeros((1, self.neurons)))
self.prevlayer = prevlayer
self.nextlayer = None
# Past
self.pastvalue = [np.zeros_like(self.value)]
self.pastweighted = [np.zeros_like(self.value)]
self.firstPastValue = True
# Default method references
self.propagate = self.propagate_nonsequential
self.propagate_sequence = self.propagate_sequential
self.backpropagate = self.backpropagate_nonsequential_target
self.backpropagate_sequence = self.backpropagate_sequential_target
# Specific method references
self.activation, self.act_prime = getActivation(activation)
self.cost_function, self.cost_function_prime = getCostfunction(cost)
# Constructor startup routines
if self.prevlayer != None:
# Update prevlayer method references
self.prevlayer.nextlayer = self
self.prevlayer.backpropagate = self.prevlayer.backpropagate_nonsequential_default
self.prevlayer.backpropagate_sequence = self.prevlayer.backpropagate_sequential_default
self.firstlayer = self.get_firstlayer()
else:
self.firstlayer = self
'''
----------------------------------------------------------------------------
METHODS TO OVERWRITE
The following few methods are to be overwritten by classes extending
this class. These methods are included here only for reference and to enable
the base layer to perform it's own propagation
'''
# Propagation
def propagate_nonsequential(self, inputs):
self.weighted_input = np.atleast_2d(inputs)
self.value = self.weighted_input
def propagate_sequential(self, inputs):
self.propagate_nonsequential(inputs)
self.pastvalues_remember()
# Backpropagation
def backpropagate_nonsequential_default(self): return
def backpropagate_nonsequential_target(self, target): return
def backpropagate_sequential_default(self): self.pastvalues_recall()
def backpropagate_sequential_target(self, target): self.pastvalues_recall()
# Calculate gradients
def calculate_gradients_nonsequential(self): return
def calculate_gradients_sequential(self): return
# Update weights
def updateweights_nonsequential(self, alpha=1, clip=0.5): return
def updateweights_sequential(self, alpha=1, clip=0.5): return
# Reset
def reset_weightupdates(self): return
# Serialization
def enjson_specs(self): return {}
def dejson_specs(self, lib): return self
'''
----------------------------------------------------------------------------
METHODS TO INHERIT
These methods will be inherited, but should NOT be overwritten.
'''
# Update weights
def updateweights_all_nonsequential(self, alpha=1, clip=0.5):
for layer in self.layers: layer.updateweights_nonsequential(alpha, clip)
def updateweights_all_sequential(self, alpha=1, clip=0.5):
for layer in self.layers: layer.updateweights_sequential(alpha, clip)
# State
def state_remember(self):
self.remember = self.value.copy()
def state_recall(self):
self.pastvalue = [self.remember.copy()]
self.value = self.remember.copy()
# Pastvalues
def pastvalues_remember(self):
self.pastvalue.append(self.value.copy())
self.pastweighted.append(self.weighted_input.copy())
if self.firstPastValue:
self.pastvalue[0] = np.zeros_like(self.pastvalue[1])
self.pastweighted[0] = np.zeros_like(self.pastweighted[1])
self.firstPastValue = False
def pastvalues_recall(self):
self.value = self.pastvalue[-1]
self.pastvalue = self.pastvalue[:-1]
self.weighted_input = self.pastweighted[-1]
self.pastweighted = self.pastweighted[:-1]
# Preparation
def prep_batch(self, inputs=None):
self.firstlayer.forward(inputs)
self.firstlayer.reset_all()
# Reset
def reset_trainingmemory(self):
self.pastvalue = [np.zeros_like(self.value)]
self.pastweighted = [np.zeros_like(self.value)]
self.firstPastValue = True
def reset_memory(self):
self.value = np.atleast_2d(np.zeros((1, self.neurons)))
self.weighted_input = np.atleast_2d(np.zeros((1, self.neurons)))
self.error = np.atleast_2d(np.zeros((1, self.neurons)))
self.delta = np.atleast_2d(np.zeros((1, self.neurons)))
self.remember = np.atleast_2d(np.zeros((1, self.neurons)))
def reset(self):
self.reset_memory()
self.reset_trainingmemory()
self.reset_weightupdates()
def reset_all(self):
self.reset()
for layer in self.layers: layer.reset()
# Funny helpers
def n_params(self):
return 0
def printspecs(self):
toprint = 'Layer type: ' + str(self.__class__.__name__) + '\n'
toprint += '- Neurons: ' + str(self.neurons) + '\n'
toprint += '- Activation: ' + str(self.activation.__name__) + '\n'
print(toprint)
# Getters
def get_firstlayer(self):
return self if self.prevlayer == None else self.prevlayer.get_firstlayer()
def get_lastlayer(self):
return self if self.nextlayer == None else self.nextlayer.get_lastlayer()
# Mutation
def mutate(self, probability=0.1, mult=0.01):
return None
# Serialization
def enjson(self):
baselib = {'value':{}, 'remember':{}}
baselib['layertype'] = str(self.__class__.__name__)
baselib['neurons'] = self.neurons
array2json(self.value, baselib['value'])
array2json(self.remember, baselib['remember'])
baselib['activation'] = str(self.activation.__name__)
baselib['cost_function'] = str(self.cost_function.__name__)
speclib = self.enjson_specs()
return {'basics':baselib, 'specifics':speclib}
def enjson_specs(self):
return {}
# Deserialization
def dejson(self, lib):
self.value = json2array(lib['basics']['value'])
self.remember = json2array(lib['basics']['remember'])
self.dejson_specs(lib['specifics'])
return self
def dejson_specs(self, lib):
return None
|
from openfermion.hamiltonians import fermi_hubbard
from openfermion.transforms import get_sparse_operator, jordan_wigner
from openfermion.utils import get_ground_state
# Set model.
x_dimension = 2
y_dimension = 2
tunneling = 2.
coulomb = 1.
magnetic_field = 0.5
chemical_potential = 0.25
periodic = 1
spinless = 1
# Get fermion operator.
hubbard_model = fermi_hubbard(
x_dimension, y_dimension, tunneling, coulomb, chemical_potential,
magnetic_field, periodic, spinless)
print (hubbard_model)
# Get qubit operator under Jordan-Wigner.
jw_hamiltonian = jordan_wigner(hubbard_model)
jw_hamiltonian.compress()
print (jw_hamiltonian)
# Get scipy.sparse.csc representation.
sparse_operator = get_sparse_operator(hubbard_model)
print (sparse_operator)
print ('\nEnergy of the model is {} in units of T and J.'.format(
get_ground_state(sparse_operator)[0]))
|
// const CronJob = require('cron').CronJob;
// const cacache = require('cacache');
// const axios = require('axios');
// const Judge = require('../api/judges/judgeModel');
// const Case = require('../api/cases/caseModel');
// const Protected = require('../api/protected/protectedModel');
// const Social = require('../api/social/socialModel');
// TODO uncomment code when DS gets a server running
// * update automatically updates the server - cron is persistant across server updates
// * '0 0 * * *' => Runs Daily at Midnight - PST
// * '0 0 * * sun' => Runs Weekly, Midnight Sunday - PST
// ! If DS changes when their backend updates, change cron appropriately
// const update = new CronJob(
// '0 0 * * *',
// function () {
// let new_data = [];
// axios
// .get(process.env.DS_API_URL)
// .then((res) => {
// // ! for postman testing
// new_data = res.data;
// res.send(200).json(new_data);
// })
// .catch((err) => {
// res.send(500).json(err.message);
// })
// .finally(async () => {
// // * judge data & case data
// const judge_data = new_data.judge_data;
// // * for judge in judge_data, check if name returns a value
// for (const judge in judge_data) {
// Judge.findByName(judge[name])
// .then((found_judge) => {
// if (found_judge.length > 0) {
// // * update judge
// Judge.update(found_judge.name)
// // * on success continue
// .then((result_judge) => {
// })
// .catch((err) => console.log(err.message));
// } else {
// // * add judge
// Judge.add(judge)
// // * on success continue
// .then( result_judge )
// .catch((err) => console.log(err.message));
// }
// })
// .catch((err) => {
// console.log(err);
// });
// }
// const case_data = new_data.case_data;
// // * for case in case data, check if case_id returns a value
// for (const ref_case in case_data) {
// Case.findById(ref_case[id])
// .then((ret_case) => {
// if (!ret_case.length) {
// Case.add(ref_case)
// // * continue else catch
// .catch((err) => console.log(err.message));
// }
// // * if there is a protected ground
// if (ref_case.protected_ground.length > 0) {
// for (let i = 0; i < ref_case.protected_ground.length; i++) {
// // * check that the tag doesn't already exist
// Protected.findByTag(ref_case.protected_ground[i])
// .then((ret_tag) => {
// if (ret_tag.length > 0) {
// // * if the tag exists, join to the new case
// Protected.createJoin(
// ref_case[id],
// ret_tag[ground_tag]
// ).catch((err) => console.log(err.message));
// } else {
// // * if the tag doesn't exist, create a new tag
// Protected.add(ref_case.protected_ground[i]).then(
// (ret) => {
// // * join created tag to the newly added case file
// Protected.createJoin(
// ref_case[id],
// ret_tag[ground_tag]
// ).catch((err) => console.log(err.message));
// }
// );
// }
// })
// .catch((err) => console.log(err.message));
// }
// }
// if (ref_case.social_group_type.length > 0) {
// for (let i = 0; i < ref_case.social_group_type.length; i++) {
// // * check that the tag doesn't already exist
// Social.findByTag(ref_case.social_group_type[i])
// .then((ret_tag) => {
// if (ret_tag.length > 0) {
// // * if the tag exists, join to the new case
// Social.createJoin(
// ref_case[id],
// ret_tag[social_tag]
// ).catch((err) => console.log(err.message));
// } else {
// // * if the tag doesn't exist, create a new tag
// Social.add(ref_case.social_group_type[i]).then(
// (ret) => {
// // * join created tag to the newly added case file
// Social.createJoin(
// ref_case[id],
// ret_tag[social_tag]
// ).catch((err) => console.log(err.message));
// }
// );
// }
// })
// .catch((err) => console.log(err.message));
// }
// }
// })
// .catch((err) => {
// console.log(err);
// });
// }
// });
// },
// null,
// true,
// 'America/Los_Angeles'
// );
// // * runs at 00:30 daily
// // * '0 0 * * sun' => Runs Weekly, 00:30 Sunday - PST
// const clearCache = new CronJob(
// '0 30 * * *',
// function () {
// cacache.rm.all(cachePath).then(() => {
// console.log('THE APOCALYPSE IS UPON US 😱');
// });
// },
// null,
// true,
// 'America/Los_Angeles'
// );
// update.start();
// clearCache.start();
// TODO create axios call to /judges & /cases to cache the initial data
|
(window.webpackJsonp=window.webpackJsonp||[]).push([[2],[function(e,t,n){"use strict";e.exports=n(10)},function(e,t,n){e.exports=n(16)},function(e,t,n){"use strict";var r=Object.getOwnPropertySymbols,l=Object.prototype.hasOwnProperty,o=Object.prototype.propertyIsEnumerable;e.exports=function(){try{if(!Object.assign)return!1;var e=new String("abc");if(e[5]="de","5"===Object.getOwnPropertyNames(e)[0])return!1;for(var t={},n=0;n<10;n++)t["_"+String.fromCharCode(n)]=n;if("0123456789"!==Object.getOwnPropertyNames(t).map(function(e){return t[e]}).join(""))return!1;var r={};return"abcdefghijklmnopqrst".split("").forEach(function(e){r[e]=e}),"abcdefghijklmnopqrst"===Object.keys(Object.assign({},r)).join("")}catch(l){return!1}}()?Object.assign:function(e,t){for(var n,i,a=function(e){if(null===e||void 0===e)throw new TypeError("Object.assign cannot be called with null or undefined");return Object(e)}(e),u=1;u<arguments.length;u++){for(var c in n=Object(arguments[u]))l.call(n,c)&&(a[c]=n[c]);if(r){i=r(n);for(var s=0;s<i.length;s++)o.call(n,i[s])&&(a[i[s]]=n[i[s]])}}return a}},function(e,t,n){"use strict";!function e(){if("undefined"!==typeof __REACT_DEVTOOLS_GLOBAL_HOOK__&&"function"===typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE)try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(e)}catch(t){console.error(t)}}(),e.exports=n(11)},function(e,t,n){"use strict";function r(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}n.d(t,"a",function(){return r})},function(e,t,n){"use strict";function r(e){return(r=Object.setPrototypeOf?Object.getPrototypeOf:function(e){return e.__proto__||Object.getPrototypeOf(e)})(e)}n.d(t,"a",function(){return r})},function(e,t,n){"use strict";function r(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var n=[],r=!0,l=!1,o=void 0;try{for(var i,a=e[Symbol.iterator]();!(r=(i=a.next()).done)&&(n.push(i.value),!t||n.length!==t);r=!0);}catch(u){l=!0,o=u}finally{try{r||null==a.return||a.return()}finally{if(l)throw o}}return n}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance")}()}n.d(t,"a",function(){return r})},function(e,t,n){"use strict";function r(e){return(r="function"===typeof Symbol&&"symbol"===typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"===typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function l(e){return(l="function"===typeof Symbol&&"symbol"===r(Symbol.iterator)?function(e){return r(e)}:function(e){return e&&"function"===typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":r(e)})(e)}function o(e,t){return!t||"object"!==l(t)&&"function"!==typeof t?function(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}(e):t}n.d(t,"a",function(){return o})},function(e,t,n){"use strict";function r(e,t){return(r=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e})(e,t)}function l(e,t){if("function"!==typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),t&&r(e,t)}n.d(t,"a",function(){return l})},,function(e,t,n){"use strict";var r=n(2),l="function"===typeof Symbol&&Symbol.for,o=l?Symbol.for("react.element"):60103,i=l?Symbol.for("react.portal"):60106,a=l?Symbol.for("react.fragment"):60107,u=l?Symbol.for("react.strict_mode"):60108,c=l?Symbol.for("react.profiler"):60114,s=l?Symbol.for("react.provider"):60109,f=l?Symbol.for("react.context"):60110,d=l?Symbol.for("react.concurrent_mode"):60111,p=l?Symbol.for("react.forward_ref"):60112,m=l?Symbol.for("react.suspense"):60113,h=l?Symbol.for("react.memo"):60115,y=l?Symbol.for("react.lazy"):60116,v="function"===typeof Symbol&&Symbol.iterator;function g(e){for(var t=arguments.length-1,n="https://reactjs.org/docs/error-decoder.html?invariant="+e,r=0;r<t;r++)n+="&args[]="+encodeURIComponent(arguments[r+1]);!function(e,t,n,r,l,o,i,a){if(!e){if(e=void 0,void 0===t)e=Error("Minified exception occurred; use the non-minified dev environment for the full error message and additional helpful warnings.");else{var u=[n,r,l,o,i,a],c=0;(e=Error(t.replace(/%s/g,function(){return u[c++]}))).name="Invariant Violation"}throw e.framesToPop=1,e}}(!1,"Minified React error #"+e+"; visit %s for the full message or use the non-minified dev environment for full errors and additional helpful warnings. ",n)}var b={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},w={};function k(e,t,n){this.props=e,this.context=t,this.refs=w,this.updater=n||b}function x(){}function T(e,t,n){this.props=e,this.context=t,this.refs=w,this.updater=n||b}k.prototype.isReactComponent={},k.prototype.setState=function(e,t){"object"!==typeof e&&"function"!==typeof e&&null!=e&&g("85"),this.updater.enqueueSetState(this,e,t,"setState")},k.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this,e,"forceUpdate")},x.prototype=k.prototype;var _=T.prototype=new x;_.constructor=T,r(_,k.prototype),_.isPureReactComponent=!0;var S={current:null},E={current:null},C=Object.prototype.hasOwnProperty,P={key:!0,ref:!0,__self:!0,__source:!0};function N(e,t,n){var r=void 0,l={},i=null,a=null;if(null!=t)for(r in void 0!==t.ref&&(a=t.ref),void 0!==t.key&&(i=""+t.key),t)C.call(t,r)&&!P.hasOwnProperty(r)&&(l[r]=t[r]);var u=arguments.length-2;if(1===u)l.children=n;else if(1<u){for(var c=Array(u),s=0;s<u;s++)c[s]=arguments[s+2];l.children=c}if(e&&e.defaultProps)for(r in u=e.defaultProps)void 0===l[r]&&(l[r]=u[r]);return{$$typeof:o,type:e,key:i,ref:a,props:l,_owner:E.current}}function O(e){return"object"===typeof e&&null!==e&&e.$$typeof===o}var R=/\/+/g,z=[];function L(e,t,n,r){if(z.length){var l=z.pop();return l.result=e,l.keyPrefix=t,l.func=n,l.context=r,l.count=0,l}return{result:e,keyPrefix:t,func:n,context:r,count:0}}function I(e){e.result=null,e.keyPrefix=null,e.func=null,e.context=null,e.count=0,10>z.length&&z.push(e)}function M(e,t,n){return null==e?0:function e(t,n,r,l){var a=typeof t;"undefined"!==a&&"boolean"!==a||(t=null);var u=!1;if(null===t)u=!0;else switch(a){case"string":case"number":u=!0;break;case"object":switch(t.$$typeof){case o:case i:u=!0}}if(u)return r(l,t,""===n?"."+U(t,0):n),1;if(u=0,n=""===n?".":n+":",Array.isArray(t))for(var c=0;c<t.length;c++){var s=n+U(a=t[c],c);u+=e(a,s,r,l)}else if(s=null===t||"object"!==typeof t?null:"function"===typeof(s=v&&t[v]||t["@@iterator"])?s:null,"function"===typeof s)for(t=s.call(t),c=0;!(a=t.next()).done;)u+=e(a=a.value,s=n+U(a,c++),r,l);else"object"===a&&g("31","[object Object]"===(r=""+t)?"object with keys {"+Object.keys(t).join(", ")+"}":r,"");return u}(e,"",t,n)}function U(e,t){return"object"===typeof e&&null!==e&&null!=e.key?function(e){var t={"=":"=0",":":"=2"};return"$"+(""+e).replace(/[=:]/g,function(e){return t[e]})}(e.key):t.toString(36)}function F(e,t){e.func.call(e.context,t,e.count++)}function D(e,t,n){var r=e.result,l=e.keyPrefix;e=e.func.call(e.context,t,e.count++),Array.isArray(e)?A(e,r,n,function(e){return e}):null!=e&&(O(e)&&(e=function(e,t){return{$$typeof:o,type:e.type,key:t,ref:e.ref,props:e.props,_owner:e._owner}}(e,l+(!e.key||t&&t.key===e.key?"":(""+e.key).replace(R,"$&/")+"/")+n)),r.push(e))}function A(e,t,n,r,l){var o="";null!=n&&(o=(""+n).replace(R,"$&/")+"/"),M(e,D,t=L(t,o,r,l)),I(t)}function j(){var e=S.current;return null===e&&g("321"),e}var W={Children:{map:function(e,t,n){if(null==e)return e;var r=[];return A(e,r,null,t,n),r},forEach:function(e,t,n){if(null==e)return e;M(e,F,t=L(null,null,t,n)),I(t)},count:function(e){return M(e,function(){return null},null)},toArray:function(e){var t=[];return A(e,t,null,function(e){return e}),t},only:function(e){return O(e)||g("143"),e}},createRef:function(){return{current:null}},Component:k,PureComponent:T,createContext:function(e,t){return void 0===t&&(t=null),(e={$$typeof:f,_calculateChangedBits:t,_currentValue:e,_currentValue2:e,_threadCount:0,Provider:null,Consumer:null}).Provider={$$typeof:s,_context:e},e.Consumer=e},forwardRef:function(e){return{$$typeof:p,render:e}},lazy:function(e){return{$$typeof:y,_ctor:e,_status:-1,_result:null}},memo:function(e,t){return{$$typeof:h,type:e,compare:void 0===t?null:t}},useCallback:function(e,t){return j().useCallback(e,t)},useContext:function(e,t){return j().useContext(e,t)},useEffect:function(e,t){return j().useEffect(e,t)},useImperativeHandle:function(e,t,n){return j().useImperativeHandle(e,t,n)},useDebugValue:function(){},useLayoutEffect:function(e,t){return j().useLayoutEffect(e,t)},useMemo:function(e,t){return j().useMemo(e,t)},useReducer:function(e,t,n){return j().useReducer(e,t,n)},useRef:function(e){return j().useRef(e)},useState:function(e){return j().useState(e)},Fragment:a,StrictMode:u,Suspense:m,createElement:N,cloneElement:function(e,t,n){(null===e||void 0===e)&&g("267",e);var l=void 0,i=r({},e.props),a=e.key,u=e.ref,c=e._owner;if(null!=t){void 0!==t.ref&&(u=t.ref,c=E.current),void 0!==t.key&&(a=""+t.key);var s=void 0;for(l in e.type&&e.type.defaultProps&&(s=e.type.defaultProps),t)C.call(t,l)&&!P.hasOwnProperty(l)&&(i[l]=void 0===t[l]&&void 0!==s?s[l]:t[l])}if(1===(l=arguments.length-2))i.children=n;else if(1<l){s=Array(l);for(var f=0;f<l;f++)s[f]=arguments[f+2];i.children=s}return{$$typeof:o,type:e.type,key:a,ref:u,props:i,_owner:c}},createFactory:function(e){var t=N.bind(null,e);return t.type=e,t},isValidElement:O,version:"16.8.6",unstable_ConcurrentMode:d,unstable_Profiler:c,__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED:{ReactCurrentDispatcher:S,ReactCurrentOwner:E,assign:r}},V={default:W},B=V&&W||V;e.exports=B.default||B},function(e,t,n){"use strict";var r=n(0),l=n(2),o=n(12);function i(e){for(var t=arguments.length-1,n="https://reactjs.org/docs/error-decoder.html?invariant="+e,r=0;r<t;r++)n+="&args[]="+encodeURIComponent(arguments[r+1]);!function(e,t,n,r,l,o,i,a){if(!e){if(e=void 0,void 0===t)e=Error("Minified exception occurred; use the non-minified dev environment for the full error message and additional helpful warnings.");else{var u=[n,r,l,o,i,a],c=0;(e=Error(t.replace(/%s/g,function(){return u[c++]}))).name="Invariant Violation"}throw e.framesToPop=1,e}}(!1,"Minified React error #"+e+"; visit %s for the full message or use the non-minified dev environment for full errors and additional helpful warnings. ",n)}r||i("227");var a=!1,u=null,c=!1,s=null,f={onError:function(e){a=!0,u=e}};function d(e,t,n,r,l,o,i,c,s){a=!1,u=null,function(e,t,n,r,l,o,i,a,u){var c=Array.prototype.slice.call(arguments,3);try{t.apply(n,c)}catch(s){this.onError(s)}}.apply(f,arguments)}var p=null,m={};function h(){if(p)for(var e in m){var t=m[e],n=p.indexOf(e);if(-1<n||i("96",e),!v[n])for(var r in t.extractEvents||i("97",e),v[n]=t,n=t.eventTypes){var l=void 0,o=n[r],a=t,u=r;g.hasOwnProperty(u)&&i("99",u),g[u]=o;var c=o.phasedRegistrationNames;if(c){for(l in c)c.hasOwnProperty(l)&&y(c[l],a,u);l=!0}else o.registrationName?(y(o.registrationName,a,u),l=!0):l=!1;l||i("98",r,e)}}}function y(e,t,n){b[e]&&i("100",e),b[e]=t,w[e]=t.eventTypes[n].dependencies}var v=[],g={},b={},w={},k=null,x=null,T=null;function _(e,t,n){var r=e.type||"unknown-event";e.currentTarget=T(n),function(e,t,n,r,l,o,f,p,m){if(d.apply(this,arguments),a){if(a){var h=u;a=!1,u=null}else i("198"),h=void 0;c||(c=!0,s=h)}}(r,t,void 0,e),e.currentTarget=null}function S(e,t){return null==t&&i("30"),null==e?t:Array.isArray(e)?Array.isArray(t)?(e.push.apply(e,t),e):(e.push(t),e):Array.isArray(t)?[e].concat(t):[e,t]}function E(e,t,n){Array.isArray(e)?e.forEach(t,n):e&&t.call(n,e)}var C=null;function P(e){if(e){var t=e._dispatchListeners,n=e._dispatchInstances;if(Array.isArray(t))for(var r=0;r<t.length&&!e.isPropagationStopped();r++)_(e,t[r],n[r]);else t&&_(e,t,n);e._dispatchListeners=null,e._dispatchInstances=null,e.isPersistent()||e.constructor.release(e)}}var N={injectEventPluginOrder:function(e){p&&i("101"),p=Array.prototype.slice.call(e),h()},injectEventPluginsByName:function(e){var t,n=!1;for(t in e)if(e.hasOwnProperty(t)){var r=e[t];m.hasOwnProperty(t)&&m[t]===r||(m[t]&&i("102",t),m[t]=r,n=!0)}n&&h()}};function O(e,t){var n=e.stateNode;if(!n)return null;var r=k(n);if(!r)return null;n=r[t];e:switch(t){case"onClick":case"onClickCapture":case"onDoubleClick":case"onDoubleClickCapture":case"onMouseDown":case"onMouseDownCapture":case"onMouseMove":case"onMouseMoveCapture":case"onMouseUp":case"onMouseUpCapture":(r=!r.disabled)||(r=!("button"===(e=e.type)||"input"===e||"select"===e||"textarea"===e)),e=!r;break e;default:e=!1}return e?null:(n&&"function"!==typeof n&&i("231",t,typeof n),n)}function R(e){if(null!==e&&(C=S(C,e)),e=C,C=null,e&&(E(e,P),C&&i("95"),c))throw e=s,c=!1,s=null,e}var z=Math.random().toString(36).slice(2),L="__reactInternalInstance$"+z,I="__reactEventHandlers$"+z;function M(e){if(e[L])return e[L];for(;!e[L];){if(!e.parentNode)return null;e=e.parentNode}return 5===(e=e[L]).tag||6===e.tag?e:null}function U(e){return!(e=e[L])||5!==e.tag&&6!==e.tag?null:e}function F(e){if(5===e.tag||6===e.tag)return e.stateNode;i("33")}function D(e){return e[I]||null}function A(e){do{e=e.return}while(e&&5!==e.tag);return e||null}function j(e,t,n){(t=O(e,n.dispatchConfig.phasedRegistrationNames[t]))&&(n._dispatchListeners=S(n._dispatchListeners,t),n._dispatchInstances=S(n._dispatchInstances,e))}function W(e){if(e&&e.dispatchConfig.phasedRegistrationNames){for(var t=e._targetInst,n=[];t;)n.push(t),t=A(t);for(t=n.length;0<t--;)j(n[t],"captured",e);for(t=0;t<n.length;t++)j(n[t],"bubbled",e)}}function V(e,t,n){e&&n&&n.dispatchConfig.registrationName&&(t=O(e,n.dispatchConfig.registrationName))&&(n._dispatchListeners=S(n._dispatchListeners,t),n._dispatchInstances=S(n._dispatchInstances,e))}function B(e){e&&e.dispatchConfig.registrationName&&V(e._targetInst,null,e)}function H(e){E(e,W)}var $=!("undefined"===typeof window||!window.document||!window.document.createElement);function Q(e,t){var n={};return n[e.toLowerCase()]=t.toLowerCase(),n["Webkit"+e]="webkit"+t,n["Moz"+e]="moz"+t,n}var K={animationend:Q("Animation","AnimationEnd"),animationiteration:Q("Animation","AnimationIteration"),animationstart:Q("Animation","AnimationStart"),transitionend:Q("Transition","TransitionEnd")},q={},Y={};function G(e){if(q[e])return q[e];if(!K[e])return e;var t,n=K[e];for(t in n)if(n.hasOwnProperty(t)&&t in Y)return q[e]=n[t];return e}$&&(Y=document.createElement("div").style,"AnimationEvent"in window||(delete K.animationend.animation,delete K.animationiteration.animation,delete K.animationstart.animation),"TransitionEvent"in window||delete K.transitionend.transition);var X=G("animationend"),J=G("animationiteration"),Z=G("animationstart"),ee=G("transitionend"),te="abort canplay canplaythrough durationchange emptied encrypted ended error loadeddata loadedmetadata loadstart pause play playing progress ratechange seeked seeking stalled suspend timeupdate volumechange waiting".split(" "),ne=null,re=null,le=null;function oe(){if(le)return le;var e,t,n=re,r=n.length,l="value"in ne?ne.value:ne.textContent,o=l.length;for(e=0;e<r&&n[e]===l[e];e++);var i=r-e;for(t=1;t<=i&&n[r-t]===l[o-t];t++);return le=l.slice(e,1<t?1-t:void 0)}function ie(){return!0}function ae(){return!1}function ue(e,t,n,r){for(var l in this.dispatchConfig=e,this._targetInst=t,this.nativeEvent=n,e=this.constructor.Interface)e.hasOwnProperty(l)&&((t=e[l])?this[l]=t(n):"target"===l?this.target=r:this[l]=n[l]);return this.isDefaultPrevented=(null!=n.defaultPrevented?n.defaultPrevented:!1===n.returnValue)?ie:ae,this.isPropagationStopped=ae,this}function ce(e,t,n,r){if(this.eventPool.length){var l=this.eventPool.pop();return this.call(l,e,t,n,r),l}return new this(e,t,n,r)}function se(e){e instanceof this||i("279"),e.destructor(),10>this.eventPool.length&&this.eventPool.push(e)}function fe(e){e.eventPool=[],e.getPooled=ce,e.release=se}l(ue.prototype,{preventDefault:function(){this.defaultPrevented=!0;var e=this.nativeEvent;e&&(e.preventDefault?e.preventDefault():"unknown"!==typeof e.returnValue&&(e.returnValue=!1),this.isDefaultPrevented=ie)},stopPropagation:function(){var e=this.nativeEvent;e&&(e.stopPropagation?e.stopPropagation():"unknown"!==typeof e.cancelBubble&&(e.cancelBubble=!0),this.isPropagationStopped=ie)},persist:function(){this.isPersistent=ie},isPersistent:ae,destructor:function(){var e,t=this.constructor.Interface;for(e in t)this[e]=null;this.nativeEvent=this._targetInst=this.dispatchConfig=null,this.isPropagationStopped=this.isDefaultPrevented=ae,this._dispatchInstances=this._dispatchListeners=null}}),ue.Interface={type:null,target:null,currentTarget:function(){return null},eventPhase:null,bubbles:null,cancelable:null,timeStamp:function(e){return e.timeStamp||Date.now()},defaultPrevented:null,isTrusted:null},ue.extend=function(e){function t(){}function n(){return r.apply(this,arguments)}var r=this;t.prototype=r.prototype;var o=new t;return l(o,n.prototype),n.prototype=o,n.prototype.constructor=n,n.Interface=l({},r.Interface,e),n.extend=r.extend,fe(n),n},fe(ue);var de=ue.extend({data:null}),pe=ue.extend({data:null}),me=[9,13,27,32],he=$&&"CompositionEvent"in window,ye=null;$&&"documentMode"in document&&(ye=document.documentMode);var ve=$&&"TextEvent"in window&&!ye,ge=$&&(!he||ye&&8<ye&&11>=ye),be=String.fromCharCode(32),we={beforeInput:{phasedRegistrationNames:{bubbled:"onBeforeInput",captured:"onBeforeInputCapture"},dependencies:["compositionend","keypress","textInput","paste"]},compositionEnd:{phasedRegistrationNames:{bubbled:"onCompositionEnd",captured:"onCompositionEndCapture"},dependencies:"blur compositionend keydown keypress keyup mousedown".split(" ")},compositionStart:{phasedRegistrationNames:{bubbled:"onCompositionStart",captured:"onCompositionStartCapture"},dependencies:"blur compositionstart keydown keypress keyup mousedown".split(" ")},compositionUpdate:{phasedRegistrationNames:{bubbled:"onCompositionUpdate",captured:"onCompositionUpdateCapture"},dependencies:"blur compositionupdate keydown keypress keyup mousedown".split(" ")}},ke=!1;function xe(e,t){switch(e){case"keyup":return-1!==me.indexOf(t.keyCode);case"keydown":return 229!==t.keyCode;case"keypress":case"mousedown":case"blur":return!0;default:return!1}}function Te(e){return"object"===typeof(e=e.detail)&&"data"in e?e.data:null}var _e=!1;var Se={eventTypes:we,extractEvents:function(e,t,n,r){var l=void 0,o=void 0;if(he)e:{switch(e){case"compositionstart":l=we.compositionStart;break e;case"compositionend":l=we.compositionEnd;break e;case"compositionupdate":l=we.compositionUpdate;break e}l=void 0}else _e?xe(e,n)&&(l=we.compositionEnd):"keydown"===e&&229===n.keyCode&&(l=we.compositionStart);return l?(ge&&"ko"!==n.locale&&(_e||l!==we.compositionStart?l===we.compositionEnd&&_e&&(o=oe()):(re="value"in(ne=r)?ne.value:ne.textContent,_e=!0)),l=de.getPooled(l,t,n,r),o?l.data=o:null!==(o=Te(n))&&(l.data=o),H(l),o=l):o=null,(e=ve?function(e,t){switch(e){case"compositionend":return Te(t);case"keypress":return 32!==t.which?null:(ke=!0,be);case"textInput":return(e=t.data)===be&&ke?null:e;default:return null}}(e,n):function(e,t){if(_e)return"compositionend"===e||!he&&xe(e,t)?(e=oe(),le=re=ne=null,_e=!1,e):null;switch(e){case"paste":return null;case"keypress":if(!(t.ctrlKey||t.altKey||t.metaKey)||t.ctrlKey&&t.altKey){if(t.char&&1<t.char.length)return t.char;if(t.which)return String.fromCharCode(t.which)}return null;case"compositionend":return ge&&"ko"!==t.locale?null:t.data;default:return null}}(e,n))?((t=pe.getPooled(we.beforeInput,t,n,r)).data=e,H(t)):t=null,null===o?t:null===t?o:[o,t]}},Ee=null,Ce=null,Pe=null;function Ne(e){if(e=x(e)){"function"!==typeof Ee&&i("280");var t=k(e.stateNode);Ee(e.stateNode,e.type,t)}}function Oe(e){Ce?Pe?Pe.push(e):Pe=[e]:Ce=e}function Re(){if(Ce){var e=Ce,t=Pe;if(Pe=Ce=null,Ne(e),t)for(e=0;e<t.length;e++)Ne(t[e])}}function ze(e,t){return e(t)}function Le(e,t,n){return e(t,n)}function Ie(){}var Me=!1;function Ue(e,t){if(Me)return e(t);Me=!0;try{return ze(e,t)}finally{Me=!1,(null!==Ce||null!==Pe)&&(Ie(),Re())}}var Fe={color:!0,date:!0,datetime:!0,"datetime-local":!0,email:!0,month:!0,number:!0,password:!0,range:!0,search:!0,tel:!0,text:!0,time:!0,url:!0,week:!0};function De(e){var t=e&&e.nodeName&&e.nodeName.toLowerCase();return"input"===t?!!Fe[e.type]:"textarea"===t}function Ae(e){return(e=e.target||e.srcElement||window).correspondingUseElement&&(e=e.correspondingUseElement),3===e.nodeType?e.parentNode:e}function je(e){if(!$)return!1;var t=(e="on"+e)in document;return t||((t=document.createElement("div")).setAttribute(e,"return;"),t="function"===typeof t[e]),t}function We(e){var t=e.type;return(e=e.nodeName)&&"input"===e.toLowerCase()&&("checkbox"===t||"radio"===t)}function Ve(e){e._valueTracker||(e._valueTracker=function(e){var t=We(e)?"checked":"value",n=Object.getOwnPropertyDescriptor(e.constructor.prototype,t),r=""+e[t];if(!e.hasOwnProperty(t)&&"undefined"!==typeof n&&"function"===typeof n.get&&"function"===typeof n.set){var l=n.get,o=n.set;return Object.defineProperty(e,t,{configurable:!0,get:function(){return l.call(this)},set:function(e){r=""+e,o.call(this,e)}}),Object.defineProperty(e,t,{enumerable:n.enumerable}),{getValue:function(){return r},setValue:function(e){r=""+e},stopTracking:function(){e._valueTracker=null,delete e[t]}}}}(e))}function Be(e){if(!e)return!1;var t=e._valueTracker;if(!t)return!0;var n=t.getValue(),r="";return e&&(r=We(e)?e.checked?"true":"false":e.value),(e=r)!==n&&(t.setValue(e),!0)}var He=r.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;He.hasOwnProperty("ReactCurrentDispatcher")||(He.ReactCurrentDispatcher={current:null});var $e=/^(.*)[\\\/]/,Qe="function"===typeof Symbol&&Symbol.for,Ke=Qe?Symbol.for("react.element"):60103,qe=Qe?Symbol.for("react.portal"):60106,Ye=Qe?Symbol.for("react.fragment"):60107,Ge=Qe?Symbol.for("react.strict_mode"):60108,Xe=Qe?Symbol.for("react.profiler"):60114,Je=Qe?Symbol.for("react.provider"):60109,Ze=Qe?Symbol.for("react.context"):60110,et=Qe?Symbol.for("react.concurrent_mode"):60111,tt=Qe?Symbol.for("react.forward_ref"):60112,nt=Qe?Symbol.for("react.suspense"):60113,rt=Qe?Symbol.for("react.memo"):60115,lt=Qe?Symbol.for("react.lazy"):60116,ot="function"===typeof Symbol&&Symbol.iterator;function it(e){return null===e||"object"!==typeof e?null:"function"===typeof(e=ot&&e[ot]||e["@@iterator"])?e:null}function at(e){if(null==e)return null;if("function"===typeof e)return e.displayName||e.name||null;if("string"===typeof e)return e;switch(e){case et:return"ConcurrentMode";case Ye:return"Fragment";case qe:return"Portal";case Xe:return"Profiler";case Ge:return"StrictMode";case nt:return"Suspense"}if("object"===typeof e)switch(e.$$typeof){case Ze:return"Context.Consumer";case Je:return"Context.Provider";case tt:var t=e.render;return t=t.displayName||t.name||"",e.displayName||(""!==t?"ForwardRef("+t+")":"ForwardRef");case rt:return at(e.type);case lt:if(e=1===e._status?e._result:null)return at(e)}return null}function ut(e){var t="";do{e:switch(e.tag){case 3:case 4:case 6:case 7:case 10:case 9:var n="";break e;default:var r=e._debugOwner,l=e._debugSource,o=at(e.type);n=null,r&&(n=at(r.type)),r=o,o="",l?o=" (at "+l.fileName.replace($e,"")+":"+l.lineNumber+")":n&&(o=" (created by "+n+")"),n="\n in "+(r||"Unknown")+o}t+=n,e=e.return}while(e);return t}var ct=/^[:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD][:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\-.0-9\u00B7\u0300-\u036F\u203F-\u2040]*$/,st=Object.prototype.hasOwnProperty,ft={},dt={};function pt(e,t,n,r,l){this.acceptsBooleans=2===t||3===t||4===t,this.attributeName=r,this.attributeNamespace=l,this.mustUseProperty=n,this.propertyName=e,this.type=t}var mt={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(e){mt[e]=new pt(e,0,!1,e,null)}),[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(e){var t=e[0];mt[t]=new pt(t,1,!1,e[1],null)}),["contentEditable","draggable","spellCheck","value"].forEach(function(e){mt[e]=new pt(e,2,!1,e.toLowerCase(),null)}),["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(e){mt[e]=new pt(e,2,!1,e,null)}),"allowFullScreen async autoFocus autoPlay controls default defer disabled formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope".split(" ").forEach(function(e){mt[e]=new pt(e,3,!1,e.toLowerCase(),null)}),["checked","multiple","muted","selected"].forEach(function(e){mt[e]=new pt(e,3,!0,e,null)}),["capture","download"].forEach(function(e){mt[e]=new pt(e,4,!1,e,null)}),["cols","rows","size","span"].forEach(function(e){mt[e]=new pt(e,6,!1,e,null)}),["rowSpan","start"].forEach(function(e){mt[e]=new pt(e,5,!1,e.toLowerCase(),null)});var ht=/[\-:]([a-z])/g;function yt(e){return e[1].toUpperCase()}function vt(e,t,n,r){var l=mt.hasOwnProperty(t)?mt[t]:null;(null!==l?0===l.type:!r&&(2<t.length&&("o"===t[0]||"O"===t[0])&&("n"===t[1]||"N"===t[1])))||(function(e,t,n,r){if(null===t||"undefined"===typeof t||function(e,t,n,r){if(null!==n&&0===n.type)return!1;switch(typeof t){case"function":case"symbol":return!0;case"boolean":return!r&&(null!==n?!n.acceptsBooleans:"data-"!==(e=e.toLowerCase().slice(0,5))&&"aria-"!==e);default:return!1}}(e,t,n,r))return!0;if(r)return!1;if(null!==n)switch(n.type){case 3:return!t;case 4:return!1===t;case 5:return isNaN(t);case 6:return isNaN(t)||1>t}return!1}(t,n,l,r)&&(n=null),r||null===l?function(e){return!!st.call(dt,e)||!st.call(ft,e)&&(ct.test(e)?dt[e]=!0:(ft[e]=!0,!1))}(t)&&(null===n?e.removeAttribute(t):e.setAttribute(t,""+n)):l.mustUseProperty?e[l.propertyName]=null===n?3!==l.type&&"":n:(t=l.attributeName,r=l.attributeNamespace,null===n?e.removeAttribute(t):(n=3===(l=l.type)||4===l&&!0===n?"":""+n,r?e.setAttributeNS(r,t,n):e.setAttribute(t,n))))}function gt(e){switch(typeof e){case"boolean":case"number":case"object":case"string":case"undefined":return e;default:return""}}function bt(e,t){var n=t.checked;return l({},t,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:null!=n?n:e._wrapperState.initialChecked})}function wt(e,t){var n=null==t.defaultValue?"":t.defaultValue,r=null!=t.checked?t.checked:t.defaultChecked;n=gt(null!=t.value?t.value:n),e._wrapperState={initialChecked:r,initialValue:n,controlled:"checkbox"===t.type||"radio"===t.type?null!=t.checked:null!=t.value}}function kt(e,t){null!=(t=t.checked)&&vt(e,"checked",t,!1)}function xt(e,t){kt(e,t);var n=gt(t.value),r=t.type;if(null!=n)"number"===r?(0===n&&""===e.value||e.value!=n)&&(e.value=""+n):e.value!==""+n&&(e.value=""+n);else if("submit"===r||"reset"===r)return void e.removeAttribute("value");t.hasOwnProperty("value")?_t(e,t.type,n):t.hasOwnProperty("defaultValue")&&_t(e,t.type,gt(t.defaultValue)),null==t.checked&&null!=t.defaultChecked&&(e.defaultChecked=!!t.defaultChecked)}function Tt(e,t,n){if(t.hasOwnProperty("value")||t.hasOwnProperty("defaultValue")){var r=t.type;if(!("submit"!==r&&"reset"!==r||void 0!==t.value&&null!==t.value))return;t=""+e._wrapperState.initialValue,n||t===e.value||(e.value=t),e.defaultValue=t}""!==(n=e.name)&&(e.name=""),e.defaultChecked=!e.defaultChecked,e.defaultChecked=!!e._wrapperState.initialChecked,""!==n&&(e.name=n)}function _t(e,t,n){"number"===t&&e.ownerDocument.activeElement===e||(null==n?e.defaultValue=""+e._wrapperState.initialValue:e.defaultValue!==""+n&&(e.defaultValue=""+n))}"accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height".split(" ").forEach(function(e){var t=e.replace(ht,yt);mt[t]=new pt(t,1,!1,e,null)}),"xlink:actuate xlink:arcrole xlink:href xlink:role xlink:show xlink:title xlink:type".split(" ").forEach(function(e){var t=e.replace(ht,yt);mt[t]=new pt(t,1,!1,e,"http://www.w3.org/1999/xlink")}),["xml:base","xml:lang","xml:space"].forEach(function(e){var t=e.replace(ht,yt);mt[t]=new pt(t,1,!1,e,"http://www.w3.org/XML/1998/namespace")}),["tabIndex","crossOrigin"].forEach(function(e){mt[e]=new pt(e,1,!1,e.toLowerCase(),null)});var St={change:{phasedRegistrationNames:{bubbled:"onChange",captured:"onChangeCapture"},dependencies:"blur change click focus input keydown keyup selectionchange".split(" ")}};function Et(e,t,n){return(e=ue.getPooled(St.change,e,t,n)).type="change",Oe(n),H(e),e}var Ct=null,Pt=null;function Nt(e){R(e)}function Ot(e){if(Be(F(e)))return e}function Rt(e,t){if("change"===e)return t}var zt=!1;function Lt(){Ct&&(Ct.detachEvent("onpropertychange",It),Pt=Ct=null)}function It(e){"value"===e.propertyName&&Ot(Pt)&&Ue(Nt,e=Et(Pt,e,Ae(e)))}function Mt(e,t,n){"focus"===e?(Lt(),Pt=n,(Ct=t).attachEvent("onpropertychange",It)):"blur"===e&&Lt()}function Ut(e){if("selectionchange"===e||"keyup"===e||"keydown"===e)return Ot(Pt)}function Ft(e,t){if("click"===e)return Ot(t)}function Dt(e,t){if("input"===e||"change"===e)return Ot(t)}$&&(zt=je("input")&&(!document.documentMode||9<document.documentMode));var At={eventTypes:St,_isInputEventSupported:zt,extractEvents:function(e,t,n,r){var l=t?F(t):window,o=void 0,i=void 0,a=l.nodeName&&l.nodeName.toLowerCase();if("select"===a||"input"===a&&"file"===l.type?o=Rt:De(l)?zt?o=Dt:(o=Ut,i=Mt):(a=l.nodeName)&&"input"===a.toLowerCase()&&("checkbox"===l.type||"radio"===l.type)&&(o=Ft),o&&(o=o(e,t)))return Et(o,n,r);i&&i(e,l,t),"blur"===e&&(e=l._wrapperState)&&e.controlled&&"number"===l.type&&_t(l,"number",l.value)}},jt=ue.extend({view:null,detail:null}),Wt={Alt:"altKey",Control:"ctrlKey",Meta:"metaKey",Shift:"shiftKey"};function Vt(e){var t=this.nativeEvent;return t.getModifierState?t.getModifierState(e):!!(e=Wt[e])&&!!t[e]}function Bt(){return Vt}var Ht=0,$t=0,Qt=!1,Kt=!1,qt=jt.extend({screenX:null,screenY:null,clientX:null,clientY:null,pageX:null,pageY:null,ctrlKey:null,shiftKey:null,altKey:null,metaKey:null,getModifierState:Bt,button:null,buttons:null,relatedTarget:function(e){return e.relatedTarget||(e.fromElement===e.srcElement?e.toElement:e.fromElement)},movementX:function(e){if("movementX"in e)return e.movementX;var t=Ht;return Ht=e.screenX,Qt?"mousemove"===e.type?e.screenX-t:0:(Qt=!0,0)},movementY:function(e){if("movementY"in e)return e.movementY;var t=$t;return $t=e.screenY,Kt?"mousemove"===e.type?e.screenY-t:0:(Kt=!0,0)}}),Yt=qt.extend({pointerId:null,width:null,height:null,pressure:null,tangentialPressure:null,tiltX:null,tiltY:null,twist:null,pointerType:null,isPrimary:null}),Gt={mouseEnter:{registrationName:"onMouseEnter",dependencies:["mouseout","mouseover"]},mouseLeave:{registrationName:"onMouseLeave",dependencies:["mouseout","mouseover"]},pointerEnter:{registrationName:"onPointerEnter",dependencies:["pointerout","pointerover"]},pointerLeave:{registrationName:"onPointerLeave",dependencies:["pointerout","pointerover"]}},Xt={eventTypes:Gt,extractEvents:function(e,t,n,r){var l="mouseover"===e||"pointerover"===e,o="mouseout"===e||"pointerout"===e;if(l&&(n.relatedTarget||n.fromElement)||!o&&!l)return null;if(l=r.window===r?r:(l=r.ownerDocument)?l.defaultView||l.parentWindow:window,o?(o=t,t=(t=n.relatedTarget||n.toElement)?M(t):null):o=null,o===t)return null;var i=void 0,a=void 0,u=void 0,c=void 0;"mouseout"===e||"mouseover"===e?(i=qt,a=Gt.mouseLeave,u=Gt.mouseEnter,c="mouse"):"pointerout"!==e&&"pointerover"!==e||(i=Yt,a=Gt.pointerLeave,u=Gt.pointerEnter,c="pointer");var s=null==o?l:F(o);if(l=null==t?l:F(t),(e=i.getPooled(a,o,n,r)).type=c+"leave",e.target=s,e.relatedTarget=l,(n=i.getPooled(u,t,n,r)).type=c+"enter",n.target=l,n.relatedTarget=s,r=t,o&&r)e:{for(l=r,c=0,i=t=o;i;i=A(i))c++;for(i=0,u=l;u;u=A(u))i++;for(;0<c-i;)t=A(t),c--;for(;0<i-c;)l=A(l),i--;for(;c--;){if(t===l||t===l.alternate)break e;t=A(t),l=A(l)}t=null}else t=null;for(l=t,t=[];o&&o!==l&&(null===(c=o.alternate)||c!==l);)t.push(o),o=A(o);for(o=[];r&&r!==l&&(null===(c=r.alternate)||c!==l);)o.push(r),r=A(r);for(r=0;r<t.length;r++)V(t[r],"bubbled",e);for(r=o.length;0<r--;)V(o[r],"captured",n);return[e,n]}};function Jt(e,t){return e===t&&(0!==e||1/e===1/t)||e!==e&&t!==t}var Zt=Object.prototype.hasOwnProperty;function en(e,t){if(Jt(e,t))return!0;if("object"!==typeof e||null===e||"object"!==typeof t||null===t)return!1;var n=Object.keys(e),r=Object.keys(t);if(n.length!==r.length)return!1;for(r=0;r<n.length;r++)if(!Zt.call(t,n[r])||!Jt(e[n[r]],t[n[r]]))return!1;return!0}function tn(e){var t=e;if(e.alternate)for(;t.return;)t=t.return;else{if(0!==(2&t.effectTag))return 1;for(;t.return;)if(0!==(2&(t=t.return).effectTag))return 1}return 3===t.tag?2:3}function nn(e){2!==tn(e)&&i("188")}function rn(e){if(!(e=function(e){var t=e.alternate;if(!t)return 3===(t=tn(e))&&i("188"),1===t?null:e;for(var n=e,r=t;;){var l=n.return,o=l?l.alternate:null;if(!l||!o)break;if(l.child===o.child){for(var a=l.child;a;){if(a===n)return nn(l),e;if(a===r)return nn(l),t;a=a.sibling}i("188")}if(n.return!==r.return)n=l,r=o;else{a=!1;for(var u=l.child;u;){if(u===n){a=!0,n=l,r=o;break}if(u===r){a=!0,r=l,n=o;break}u=u.sibling}if(!a){for(u=o.child;u;){if(u===n){a=!0,n=o,r=l;break}if(u===r){a=!0,r=o,n=l;break}u=u.sibling}a||i("189")}}n.alternate!==r&&i("190")}return 3!==n.tag&&i("188"),n.stateNode.current===n?e:t}(e)))return null;for(var t=e;;){if(5===t.tag||6===t.tag)return t;if(t.child)t.child.return=t,t=t.child;else{if(t===e)break;for(;!t.sibling;){if(!t.return||t.return===e)return null;t=t.return}t.sibling.return=t.return,t=t.sibling}}return null}var ln=ue.extend({animationName:null,elapsedTime:null,pseudoElement:null}),on=ue.extend({clipboardData:function(e){return"clipboardData"in e?e.clipboardData:window.clipboardData}}),an=jt.extend({relatedTarget:null});function un(e){var t=e.keyCode;return"charCode"in e?0===(e=e.charCode)&&13===t&&(e=13):e=t,10===e&&(e=13),32<=e||13===e?e:0}var cn={Esc:"Escape",Spacebar:" ",Left:"ArrowLeft",Up:"ArrowUp",Right:"ArrowRight",Down:"ArrowDown",Del:"Delete",Win:"OS",Menu:"ContextMenu",Apps:"ContextMenu",Scroll:"ScrollLock",MozPrintableKey:"Unidentified"},sn={8:"Backspace",9:"Tab",12:"Clear",13:"Enter",16:"Shift",17:"Control",18:"Alt",19:"Pause",20:"CapsLock",27:"Escape",32:" ",33:"PageUp",34:"PageDown",35:"End",36:"Home",37:"ArrowLeft",38:"ArrowUp",39:"ArrowRight",40:"ArrowDown",45:"Insert",46:"Delete",112:"F1",113:"F2",114:"F3",115:"F4",116:"F5",117:"F6",118:"F7",119:"F8",120:"F9",121:"F10",122:"F11",123:"F12",144:"NumLock",145:"ScrollLock",224:"Meta"},fn=jt.extend({key:function(e){if(e.key){var t=cn[e.key]||e.key;if("Unidentified"!==t)return t}return"keypress"===e.type?13===(e=un(e))?"Enter":String.fromCharCode(e):"keydown"===e.type||"keyup"===e.type?sn[e.keyCode]||"Unidentified":""},location:null,ctrlKey:null,shiftKey:null,altKey:null,metaKey:null,repeat:null,locale:null,getModifierState:Bt,charCode:function(e){return"keypress"===e.type?un(e):0},keyCode:function(e){return"keydown"===e.type||"keyup"===e.type?e.keyCode:0},which:function(e){return"keypress"===e.type?un(e):"keydown"===e.type||"keyup"===e.type?e.keyCode:0}}),dn=qt.extend({dataTransfer:null}),pn=jt.extend({touches:null,targetTouches:null,changedTouches:null,altKey:null,metaKey:null,ctrlKey:null,shiftKey:null,getModifierState:Bt}),mn=ue.extend({propertyName:null,elapsedTime:null,pseudoElement:null}),hn=qt.extend({deltaX:function(e){return"deltaX"in e?e.deltaX:"wheelDeltaX"in e?-e.wheelDeltaX:0},deltaY:function(e){return"deltaY"in e?e.deltaY:"wheelDeltaY"in e?-e.wheelDeltaY:"wheelDelta"in e?-e.wheelDelta:0},deltaZ:null,deltaMode:null}),yn=[["abort","abort"],[X,"animationEnd"],[J,"animationIteration"],[Z,"animationStart"],["canplay","canPlay"],["canplaythrough","canPlayThrough"],["drag","drag"],["dragenter","dragEnter"],["dragexit","dragExit"],["dragleave","dragLeave"],["dragover","dragOver"],["durationchange","durationChange"],["emptied","emptied"],["encrypted","encrypted"],["ended","ended"],["error","error"],["gotpointercapture","gotPointerCapture"],["load","load"],["loadeddata","loadedData"],["loadedmetadata","loadedMetadata"],["loadstart","loadStart"],["lostpointercapture","lostPointerCapture"],["mousemove","mouseMove"],["mouseout","mouseOut"],["mouseover","mouseOver"],["playing","playing"],["pointermove","pointerMove"],["pointerout","pointerOut"],["pointerover","pointerOver"],["progress","progress"],["scroll","scroll"],["seeking","seeking"],["stalled","stalled"],["suspend","suspend"],["timeupdate","timeUpdate"],["toggle","toggle"],["touchmove","touchMove"],[ee,"transitionEnd"],["waiting","waiting"],["wheel","wheel"]],vn={},gn={};function bn(e,t){var n=e[0],r="on"+((e=e[1])[0].toUpperCase()+e.slice(1));t={phasedRegistrationNames:{bubbled:r,captured:r+"Capture"},dependencies:[n],isInteractive:t},vn[e]=t,gn[n]=t}[["blur","blur"],["cancel","cancel"],["click","click"],["close","close"],["contextmenu","contextMenu"],["copy","copy"],["cut","cut"],["auxclick","auxClick"],["dblclick","doubleClick"],["dragend","dragEnd"],["dragstart","dragStart"],["drop","drop"],["focus","focus"],["input","input"],["invalid","invalid"],["keydown","keyDown"],["keypress","keyPress"],["keyup","keyUp"],["mousedown","mouseDown"],["mouseup","mouseUp"],["paste","paste"],["pause","pause"],["play","play"],["pointercancel","pointerCancel"],["pointerdown","pointerDown"],["pointerup","pointerUp"],["ratechange","rateChange"],["reset","reset"],["seeked","seeked"],["submit","submit"],["touchcancel","touchCancel"],["touchend","touchEnd"],["touchstart","touchStart"],["volumechange","volumeChange"]].forEach(function(e){bn(e,!0)}),yn.forEach(function(e){bn(e,!1)});var wn={eventTypes:vn,isInteractiveTopLevelEventType:function(e){return void 0!==(e=gn[e])&&!0===e.isInteractive},extractEvents:function(e,t,n,r){var l=gn[e];if(!l)return null;switch(e){case"keypress":if(0===un(n))return null;case"keydown":case"keyup":e=fn;break;case"blur":case"focus":e=an;break;case"click":if(2===n.button)return null;case"auxclick":case"dblclick":case"mousedown":case"mousemove":case"mouseup":case"mouseout":case"mouseover":case"contextmenu":e=qt;break;case"drag":case"dragend":case"dragenter":case"dragexit":case"dragleave":case"dragover":case"dragstart":case"drop":e=dn;break;case"touchcancel":case"touchend":case"touchmove":case"touchstart":e=pn;break;case X:case J:case Z:e=ln;break;case ee:e=mn;break;case"scroll":e=jt;break;case"wheel":e=hn;break;case"copy":case"cut":case"paste":e=on;break;case"gotpointercapture":case"lostpointercapture":case"pointercancel":case"pointerdown":case"pointermove":case"pointerout":case"pointerover":case"pointerup":e=Yt;break;default:e=ue}return H(t=e.getPooled(l,t,n,r)),t}},kn=wn.isInteractiveTopLevelEventType,xn=[];function Tn(e){var t=e.targetInst,n=t;do{if(!n){e.ancestors.push(n);break}var r;for(r=n;r.return;)r=r.return;if(!(r=3!==r.tag?null:r.stateNode.containerInfo))break;e.ancestors.push(n),n=M(r)}while(n);for(n=0;n<e.ancestors.length;n++){t=e.ancestors[n];var l=Ae(e.nativeEvent);r=e.topLevelType;for(var o=e.nativeEvent,i=null,a=0;a<v.length;a++){var u=v[a];u&&(u=u.extractEvents(r,t,o,l))&&(i=S(i,u))}R(i)}}var _n=!0;function Sn(e,t){if(!t)return null;var n=(kn(e)?Cn:Pn).bind(null,e);t.addEventListener(e,n,!1)}function En(e,t){if(!t)return null;var n=(kn(e)?Cn:Pn).bind(null,e);t.addEventListener(e,n,!0)}function Cn(e,t){Le(Pn,e,t)}function Pn(e,t){if(_n){var n=Ae(t);if(null===(n=M(n))||"number"!==typeof n.tag||2===tn(n)||(n=null),xn.length){var r=xn.pop();r.topLevelType=e,r.nativeEvent=t,r.targetInst=n,e=r}else e={topLevelType:e,nativeEvent:t,targetInst:n,ancestors:[]};try{Ue(Tn,e)}finally{e.topLevelType=null,e.nativeEvent=null,e.targetInst=null,e.ancestors.length=0,10>xn.length&&xn.push(e)}}}var Nn={},On=0,Rn="_reactListenersID"+(""+Math.random()).slice(2);function zn(e){return Object.prototype.hasOwnProperty.call(e,Rn)||(e[Rn]=On++,Nn[e[Rn]]={}),Nn[e[Rn]]}function Ln(e){if("undefined"===typeof(e=e||("undefined"!==typeof document?document:void 0)))return null;try{return e.activeElement||e.body}catch(t){return e.body}}function In(e){for(;e&&e.firstChild;)e=e.firstChild;return e}function Mn(e,t){var n,r=In(e);for(e=0;r;){if(3===r.nodeType){if(n=e+r.textContent.length,e<=t&&n>=t)return{node:r,offset:t-e};e=n}e:{for(;r;){if(r.nextSibling){r=r.nextSibling;break e}r=r.parentNode}r=void 0}r=In(r)}}function Un(){for(var e=window,t=Ln();t instanceof e.HTMLIFrameElement;){try{var n="string"===typeof t.contentWindow.location.href}catch(r){n=!1}if(!n)break;t=Ln((e=t.contentWindow).document)}return t}function Fn(e){var t=e&&e.nodeName&&e.nodeName.toLowerCase();return t&&("input"===t&&("text"===e.type||"search"===e.type||"tel"===e.type||"url"===e.type||"password"===e.type)||"textarea"===t||"true"===e.contentEditable)}function Dn(e){var t=Un(),n=e.focusedElem,r=e.selectionRange;if(t!==n&&n&&n.ownerDocument&&function e(t,n){return!(!t||!n)&&(t===n||(!t||3!==t.nodeType)&&(n&&3===n.nodeType?e(t,n.parentNode):"contains"in t?t.contains(n):!!t.compareDocumentPosition&&!!(16&t.compareDocumentPosition(n))))}(n.ownerDocument.documentElement,n)){if(null!==r&&Fn(n))if(t=r.start,void 0===(e=r.end)&&(e=t),"selectionStart"in n)n.selectionStart=t,n.selectionEnd=Math.min(e,n.value.length);else if((e=(t=n.ownerDocument||document)&&t.defaultView||window).getSelection){e=e.getSelection();var l=n.textContent.length,o=Math.min(r.start,l);r=void 0===r.end?o:Math.min(r.end,l),!e.extend&&o>r&&(l=r,r=o,o=l),l=Mn(n,o);var i=Mn(n,r);l&&i&&(1!==e.rangeCount||e.anchorNode!==l.node||e.anchorOffset!==l.offset||e.focusNode!==i.node||e.focusOffset!==i.offset)&&((t=t.createRange()).setStart(l.node,l.offset),e.removeAllRanges(),o>r?(e.addRange(t),e.extend(i.node,i.offset)):(t.setEnd(i.node,i.offset),e.addRange(t)))}for(t=[],e=n;e=e.parentNode;)1===e.nodeType&&t.push({element:e,left:e.scrollLeft,top:e.scrollTop});for("function"===typeof n.focus&&n.focus(),n=0;n<t.length;n++)(e=t[n]).element.scrollLeft=e.left,e.element.scrollTop=e.top}}var An=$&&"documentMode"in document&&11>=document.documentMode,jn={select:{phasedRegistrationNames:{bubbled:"onSelect",captured:"onSelectCapture"},dependencies:"blur contextmenu dragend focus keydown keyup mousedown mouseup selectionchange".split(" ")}},Wn=null,Vn=null,Bn=null,Hn=!1;function $n(e,t){var n=t.window===t?t.document:9===t.nodeType?t:t.ownerDocument;return Hn||null==Wn||Wn!==Ln(n)?null:("selectionStart"in(n=Wn)&&Fn(n)?n={start:n.selectionStart,end:n.selectionEnd}:n={anchorNode:(n=(n.ownerDocument&&n.ownerDocument.defaultView||window).getSelection()).anchorNode,anchorOffset:n.anchorOffset,focusNode:n.focusNode,focusOffset:n.focusOffset},Bn&&en(Bn,n)?null:(Bn=n,(e=ue.getPooled(jn.select,Vn,e,t)).type="select",e.target=Wn,H(e),e))}var Qn={eventTypes:jn,extractEvents:function(e,t,n,r){var l,o=r.window===r?r.document:9===r.nodeType?r:r.ownerDocument;if(!(l=!o)){e:{o=zn(o),l=w.onSelect;for(var i=0;i<l.length;i++){var a=l[i];if(!o.hasOwnProperty(a)||!o[a]){o=!1;break e}}o=!0}l=!o}if(l)return null;switch(o=t?F(t):window,e){case"focus":(De(o)||"true"===o.contentEditable)&&(Wn=o,Vn=t,Bn=null);break;case"blur":Bn=Vn=Wn=null;break;case"mousedown":Hn=!0;break;case"contextmenu":case"mouseup":case"dragend":return Hn=!1,$n(n,r);case"selectionchange":if(An)break;case"keydown":case"keyup":return $n(n,r)}return null}};function Kn(e,t){return e=l({children:void 0},t),(t=function(e){var t="";return r.Children.forEach(e,function(e){null!=e&&(t+=e)}),t}(t.children))&&(e.children=t),e}function qn(e,t,n,r){if(e=e.options,t){t={};for(var l=0;l<n.length;l++)t["$"+n[l]]=!0;for(n=0;n<e.length;n++)l=t.hasOwnProperty("$"+e[n].value),e[n].selected!==l&&(e[n].selected=l),l&&r&&(e[n].defaultSelected=!0)}else{for(n=""+gt(n),t=null,l=0;l<e.length;l++){if(e[l].value===n)return e[l].selected=!0,void(r&&(e[l].defaultSelected=!0));null!==t||e[l].disabled||(t=e[l])}null!==t&&(t.selected=!0)}}function Yn(e,t){return null!=t.dangerouslySetInnerHTML&&i("91"),l({},t,{value:void 0,defaultValue:void 0,children:""+e._wrapperState.initialValue})}function Gn(e,t){var n=t.value;null==n&&(n=t.defaultValue,null!=(t=t.children)&&(null!=n&&i("92"),Array.isArray(t)&&(1>=t.length||i("93"),t=t[0]),n=t),null==n&&(n="")),e._wrapperState={initialValue:gt(n)}}function Xn(e,t){var n=gt(t.value),r=gt(t.defaultValue);null!=n&&((n=""+n)!==e.value&&(e.value=n),null==t.defaultValue&&e.defaultValue!==n&&(e.defaultValue=n)),null!=r&&(e.defaultValue=""+r)}function Jn(e){var t=e.textContent;t===e._wrapperState.initialValue&&(e.value=t)}N.injectEventPluginOrder("ResponderEventPlugin SimpleEventPlugin EnterLeaveEventPlugin ChangeEventPlugin SelectEventPlugin BeforeInputEventPlugin".split(" ")),k=D,x=U,T=F,N.injectEventPluginsByName({SimpleEventPlugin:wn,EnterLeaveEventPlugin:Xt,ChangeEventPlugin:At,SelectEventPlugin:Qn,BeforeInputEventPlugin:Se});var Zn={html:"http://www.w3.org/1999/xhtml",mathml:"http://www.w3.org/1998/Math/MathML",svg:"http://www.w3.org/2000/svg"};function er(e){switch(e){case"svg":return"http://www.w3.org/2000/svg";case"math":return"http://www.w3.org/1998/Math/MathML";default:return"http://www.w3.org/1999/xhtml"}}function tr(e,t){return null==e||"http://www.w3.org/1999/xhtml"===e?er(t):"http://www.w3.org/2000/svg"===e&&"foreignObject"===t?"http://www.w3.org/1999/xhtml":e}var nr,rr=void 0,lr=(nr=function(e,t){if(e.namespaceURI!==Zn.svg||"innerHTML"in e)e.innerHTML=t;else{for((rr=rr||document.createElement("div")).innerHTML="<svg>"+t+"</svg>",t=rr.firstChild;e.firstChild;)e.removeChild(e.firstChild);for(;t.firstChild;)e.appendChild(t.firstChild)}},"undefined"!==typeof MSApp&&MSApp.execUnsafeLocalFunction?function(e,t,n,r){MSApp.execUnsafeLocalFunction(function(){return nr(e,t)})}:nr);function or(e,t){if(t){var n=e.firstChild;if(n&&n===e.lastChild&&3===n.nodeType)return void(n.nodeValue=t)}e.textContent=t}var ir={animationIterationCount:!0,borderImageOutset:!0,borderImageSlice:!0,borderImageWidth:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,columns:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,gridArea:!0,gridRow:!0,gridRowEnd:!0,gridRowSpan:!0,gridRowStart:!0,gridColumn:!0,gridColumnEnd:!0,gridColumnSpan:!0,gridColumnStart:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0,zoom:!0,fillOpacity:!0,floodOpacity:!0,stopOpacity:!0,strokeDasharray:!0,strokeDashoffset:!0,strokeMiterlimit:!0,strokeOpacity:!0,strokeWidth:!0},ar=["Webkit","ms","Moz","O"];function ur(e,t,n){return null==t||"boolean"===typeof t||""===t?"":n||"number"!==typeof t||0===t||ir.hasOwnProperty(e)&&ir[e]?(""+t).trim():t+"px"}function cr(e,t){for(var n in e=e.style,t)if(t.hasOwnProperty(n)){var r=0===n.indexOf("--"),l=ur(n,t[n],r);"float"===n&&(n="cssFloat"),r?e.setProperty(n,l):e[n]=l}}Object.keys(ir).forEach(function(e){ar.forEach(function(t){t=t+e.charAt(0).toUpperCase()+e.substring(1),ir[t]=ir[e]})});var sr=l({menuitem:!0},{area:!0,base:!0,br:!0,col:!0,embed:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0});function fr(e,t){t&&(sr[e]&&(null!=t.children||null!=t.dangerouslySetInnerHTML)&&i("137",e,""),null!=t.dangerouslySetInnerHTML&&(null!=t.children&&i("60"),"object"===typeof t.dangerouslySetInnerHTML&&"__html"in t.dangerouslySetInnerHTML||i("61")),null!=t.style&&"object"!==typeof t.style&&i("62",""))}function dr(e,t){if(-1===e.indexOf("-"))return"string"===typeof t.is;switch(e){case"annotation-xml":case"color-profile":case"font-face":case"font-face-src":case"font-face-uri":case"font-face-format":case"font-face-name":case"missing-glyph":return!1;default:return!0}}function pr(e,t){var n=zn(e=9===e.nodeType||11===e.nodeType?e:e.ownerDocument);t=w[t];for(var r=0;r<t.length;r++){var l=t[r];if(!n.hasOwnProperty(l)||!n[l]){switch(l){case"scroll":En("scroll",e);break;case"focus":case"blur":En("focus",e),En("blur",e),n.blur=!0,n.focus=!0;break;case"cancel":case"close":je(l)&&En(l,e);break;case"invalid":case"submit":case"reset":break;default:-1===te.indexOf(l)&&Sn(l,e)}n[l]=!0}}}function mr(){}var hr=null,yr=null;function vr(e,t){switch(e){case"button":case"input":case"select":case"textarea":return!!t.autoFocus}return!1}function gr(e,t){return"textarea"===e||"option"===e||"noscript"===e||"string"===typeof t.children||"number"===typeof t.children||"object"===typeof t.dangerouslySetInnerHTML&&null!==t.dangerouslySetInnerHTML&&null!=t.dangerouslySetInnerHTML.__html}var br="function"===typeof setTimeout?setTimeout:void 0,wr="function"===typeof clearTimeout?clearTimeout:void 0,kr=o.unstable_scheduleCallback,xr=o.unstable_cancelCallback;function Tr(e){for(e=e.nextSibling;e&&1!==e.nodeType&&3!==e.nodeType;)e=e.nextSibling;return e}function _r(e){for(e=e.firstChild;e&&1!==e.nodeType&&3!==e.nodeType;)e=e.nextSibling;return e}new Set;var Sr=[],Er=-1;function Cr(e){0>Er||(e.current=Sr[Er],Sr[Er]=null,Er--)}function Pr(e,t){Sr[++Er]=e.current,e.current=t}var Nr={},Or={current:Nr},Rr={current:!1},zr=Nr;function Lr(e,t){var n=e.type.contextTypes;if(!n)return Nr;var r=e.stateNode;if(r&&r.__reactInternalMemoizedUnmaskedChildContext===t)return r.__reactInternalMemoizedMaskedChildContext;var l,o={};for(l in n)o[l]=t[l];return r&&((e=e.stateNode).__reactInternalMemoizedUnmaskedChildContext=t,e.__reactInternalMemoizedMaskedChildContext=o),o}function Ir(e){return null!==(e=e.childContextTypes)&&void 0!==e}function Mr(e){Cr(Rr),Cr(Or)}function Ur(e){Cr(Rr),Cr(Or)}function Fr(e,t,n){Or.current!==Nr&&i("168"),Pr(Or,t),Pr(Rr,n)}function Dr(e,t,n){var r=e.stateNode;if(e=t.childContextTypes,"function"!==typeof r.getChildContext)return n;for(var o in r=r.getChildContext())o in e||i("108",at(t)||"Unknown",o);return l({},n,r)}function Ar(e){var t=e.stateNode;return t=t&&t.__reactInternalMemoizedMergedChildContext||Nr,zr=Or.current,Pr(Or,t),Pr(Rr,Rr.current),!0}function jr(e,t,n){var r=e.stateNode;r||i("169"),n?(t=Dr(e,t,zr),r.__reactInternalMemoizedMergedChildContext=t,Cr(Rr),Cr(Or),Pr(Or,t)):Cr(Rr),Pr(Rr,n)}var Wr=null,Vr=null;function Br(e){return function(t){try{return e(t)}catch(n){}}}function Hr(e,t,n,r){this.tag=e,this.key=n,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.ref=null,this.pendingProps=t,this.contextDependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=r,this.effectTag=0,this.lastEffect=this.firstEffect=this.nextEffect=null,this.childExpirationTime=this.expirationTime=0,this.alternate=null}function $r(e,t,n,r){return new Hr(e,t,n,r)}function Qr(e){return!(!(e=e.prototype)||!e.isReactComponent)}function Kr(e,t){var n=e.alternate;return null===n?((n=$r(e.tag,t,e.key,e.mode)).elementType=e.elementType,n.type=e.type,n.stateNode=e.stateNode,n.alternate=e,e.alternate=n):(n.pendingProps=t,n.effectTag=0,n.nextEffect=null,n.firstEffect=null,n.lastEffect=null),n.childExpirationTime=e.childExpirationTime,n.expirationTime=e.expirationTime,n.child=e.child,n.memoizedProps=e.memoizedProps,n.memoizedState=e.memoizedState,n.updateQueue=e.updateQueue,n.contextDependencies=e.contextDependencies,n.sibling=e.sibling,n.index=e.index,n.ref=e.ref,n}function qr(e,t,n,r,l,o){var a=2;if(r=e,"function"===typeof e)Qr(e)&&(a=1);else if("string"===typeof e)a=5;else e:switch(e){case Ye:return Yr(n.children,l,o,t);case et:return Gr(n,3|l,o,t);case Ge:return Gr(n,2|l,o,t);case Xe:return(e=$r(12,n,t,4|l)).elementType=Xe,e.type=Xe,e.expirationTime=o,e;case nt:return(e=$r(13,n,t,l)).elementType=nt,e.type=nt,e.expirationTime=o,e;default:if("object"===typeof e&&null!==e)switch(e.$$typeof){case Je:a=10;break e;case Ze:a=9;break e;case tt:a=11;break e;case rt:a=14;break e;case lt:a=16,r=null;break e}i("130",null==e?e:typeof e,"")}return(t=$r(a,n,t,l)).elementType=e,t.type=r,t.expirationTime=o,t}function Yr(e,t,n,r){return(e=$r(7,e,r,t)).expirationTime=n,e}function Gr(e,t,n,r){return e=$r(8,e,r,t),t=0===(1&t)?Ge:et,e.elementType=t,e.type=t,e.expirationTime=n,e}function Xr(e,t,n){return(e=$r(6,e,null,t)).expirationTime=n,e}function Jr(e,t,n){return(t=$r(4,null!==e.children?e.children:[],e.key,t)).expirationTime=n,t.stateNode={containerInfo:e.containerInfo,pendingChildren:null,implementation:e.implementation},t}function Zr(e,t){e.didError=!1;var n=e.earliestPendingTime;0===n?e.earliestPendingTime=e.latestPendingTime=t:n<t?e.earliestPendingTime=t:e.latestPendingTime>t&&(e.latestPendingTime=t),nl(t,e)}function el(e,t){e.didError=!1,e.latestPingedTime>=t&&(e.latestPingedTime=0);var n=e.earliestPendingTime,r=e.latestPendingTime;n===t?e.earliestPendingTime=r===t?e.latestPendingTime=0:r:r===t&&(e.latestPendingTime=n),n=e.earliestSuspendedTime,r=e.latestSuspendedTime,0===n?e.earliestSuspendedTime=e.latestSuspendedTime=t:n<t?e.earliestSuspendedTime=t:r>t&&(e.latestSuspendedTime=t),nl(t,e)}function tl(e,t){var n=e.earliestPendingTime;return n>t&&(t=n),(e=e.earliestSuspendedTime)>t&&(t=e),t}function nl(e,t){var n=t.earliestSuspendedTime,r=t.latestSuspendedTime,l=t.earliestPendingTime,o=t.latestPingedTime;0===(l=0!==l?l:o)&&(0===e||r<e)&&(l=r),0!==(e=l)&&n>e&&(e=n),t.nextExpirationTimeToWorkOn=l,t.expirationTime=e}function rl(e,t){if(e&&e.defaultProps)for(var n in t=l({},t),e=e.defaultProps)void 0===t[n]&&(t[n]=e[n]);return t}var ll=(new r.Component).refs;function ol(e,t,n,r){n=null===(n=n(r,t=e.memoizedState))||void 0===n?t:l({},t,n),e.memoizedState=n,null!==(r=e.updateQueue)&&0===e.expirationTime&&(r.baseState=n)}var il={isMounted:function(e){return!!(e=e._reactInternalFiber)&&2===tn(e)},enqueueSetState:function(e,t,n){e=e._reactInternalFiber;var r=xa(),l=Go(r=Yi(r,e));l.payload=t,void 0!==n&&null!==n&&(l.callback=n),Bi(),Jo(e,l),Ji(e,r)},enqueueReplaceState:function(e,t,n){e=e._reactInternalFiber;var r=xa(),l=Go(r=Yi(r,e));l.tag=Ho,l.payload=t,void 0!==n&&null!==n&&(l.callback=n),Bi(),Jo(e,l),Ji(e,r)},enqueueForceUpdate:function(e,t){e=e._reactInternalFiber;var n=xa(),r=Go(n=Yi(n,e));r.tag=$o,void 0!==t&&null!==t&&(r.callback=t),Bi(),Jo(e,r),Ji(e,n)}};function al(e,t,n,r,l,o,i){return"function"===typeof(e=e.stateNode).shouldComponentUpdate?e.shouldComponentUpdate(r,o,i):!t.prototype||!t.prototype.isPureReactComponent||(!en(n,r)||!en(l,o))}function ul(e,t,n){var r=!1,l=Nr,o=t.contextType;return"object"===typeof o&&null!==o?o=Vo(o):(l=Ir(t)?zr:Or.current,o=(r=null!==(r=t.contextTypes)&&void 0!==r)?Lr(e,l):Nr),t=new t(n,o),e.memoizedState=null!==t.state&&void 0!==t.state?t.state:null,t.updater=il,e.stateNode=t,t._reactInternalFiber=e,r&&((e=e.stateNode).__reactInternalMemoizedUnmaskedChildContext=l,e.__reactInternalMemoizedMaskedChildContext=o),t}function cl(e,t,n,r){e=t.state,"function"===typeof t.componentWillReceiveProps&&t.componentWillReceiveProps(n,r),"function"===typeof t.UNSAFE_componentWillReceiveProps&&t.UNSAFE_componentWillReceiveProps(n,r),t.state!==e&&il.enqueueReplaceState(t,t.state,null)}function sl(e,t,n,r){var l=e.stateNode;l.props=n,l.state=e.memoizedState,l.refs=ll;var o=t.contextType;"object"===typeof o&&null!==o?l.context=Vo(o):(o=Ir(t)?zr:Or.current,l.context=Lr(e,o)),null!==(o=e.updateQueue)&&(ni(e,o,n,l,r),l.state=e.memoizedState),"function"===typeof(o=t.getDerivedStateFromProps)&&(ol(e,t,o,n),l.state=e.memoizedState),"function"===typeof t.getDerivedStateFromProps||"function"===typeof l.getSnapshotBeforeUpdate||"function"!==typeof l.UNSAFE_componentWillMount&&"function"!==typeof l.componentWillMount||(t=l.state,"function"===typeof l.componentWillMount&&l.componentWillMount(),"function"===typeof l.UNSAFE_componentWillMount&&l.UNSAFE_componentWillMount(),t!==l.state&&il.enqueueReplaceState(l,l.state,null),null!==(o=e.updateQueue)&&(ni(e,o,n,l,r),l.state=e.memoizedState)),"function"===typeof l.componentDidMount&&(e.effectTag|=4)}var fl=Array.isArray;function dl(e,t,n){if(null!==(e=n.ref)&&"function"!==typeof e&&"object"!==typeof e){if(n._owner){n=n._owner;var r=void 0;n&&(1!==n.tag&&i("309"),r=n.stateNode),r||i("147",e);var l=""+e;return null!==t&&null!==t.ref&&"function"===typeof t.ref&&t.ref._stringRef===l?t.ref:((t=function(e){var t=r.refs;t===ll&&(t=r.refs={}),null===e?delete t[l]:t[l]=e})._stringRef=l,t)}"string"!==typeof e&&i("284"),n._owner||i("290",e)}return e}function pl(e,t){"textarea"!==e.type&&i("31","[object Object]"===Object.prototype.toString.call(t)?"object with keys {"+Object.keys(t).join(", ")+"}":t,"")}function ml(e){function t(t,n){if(e){var r=t.lastEffect;null!==r?(r.nextEffect=n,t.lastEffect=n):t.firstEffect=t.lastEffect=n,n.nextEffect=null,n.effectTag=8}}function n(n,r){if(!e)return null;for(;null!==r;)t(n,r),r=r.sibling;return null}function r(e,t){for(e=new Map;null!==t;)null!==t.key?e.set(t.key,t):e.set(t.index,t),t=t.sibling;return e}function l(e,t,n){return(e=Kr(e,t)).index=0,e.sibling=null,e}function o(t,n,r){return t.index=r,e?null!==(r=t.alternate)?(r=r.index)<n?(t.effectTag=2,n):r:(t.effectTag=2,n):n}function a(t){return e&&null===t.alternate&&(t.effectTag=2),t}function u(e,t,n,r){return null===t||6!==t.tag?((t=Xr(n,e.mode,r)).return=e,t):((t=l(t,n)).return=e,t)}function c(e,t,n,r){return null!==t&&t.elementType===n.type?((r=l(t,n.props)).ref=dl(e,t,n),r.return=e,r):((r=qr(n.type,n.key,n.props,null,e.mode,r)).ref=dl(e,t,n),r.return=e,r)}function s(e,t,n,r){return null===t||4!==t.tag||t.stateNode.containerInfo!==n.containerInfo||t.stateNode.implementation!==n.implementation?((t=Jr(n,e.mode,r)).return=e,t):((t=l(t,n.children||[])).return=e,t)}function f(e,t,n,r,o){return null===t||7!==t.tag?((t=Yr(n,e.mode,r,o)).return=e,t):((t=l(t,n)).return=e,t)}function d(e,t,n){if("string"===typeof t||"number"===typeof t)return(t=Xr(""+t,e.mode,n)).return=e,t;if("object"===typeof t&&null!==t){switch(t.$$typeof){case Ke:return(n=qr(t.type,t.key,t.props,null,e.mode,n)).ref=dl(e,null,t),n.return=e,n;case qe:return(t=Jr(t,e.mode,n)).return=e,t}if(fl(t)||it(t))return(t=Yr(t,e.mode,n,null)).return=e,t;pl(e,t)}return null}function p(e,t,n,r){var l=null!==t?t.key:null;if("string"===typeof n||"number"===typeof n)return null!==l?null:u(e,t,""+n,r);if("object"===typeof n&&null!==n){switch(n.$$typeof){case Ke:return n.key===l?n.type===Ye?f(e,t,n.props.children,r,l):c(e,t,n,r):null;case qe:return n.key===l?s(e,t,n,r):null}if(fl(n)||it(n))return null!==l?null:f(e,t,n,r,null);pl(e,n)}return null}function m(e,t,n,r,l){if("string"===typeof r||"number"===typeof r)return u(t,e=e.get(n)||null,""+r,l);if("object"===typeof r&&null!==r){switch(r.$$typeof){case Ke:return e=e.get(null===r.key?n:r.key)||null,r.type===Ye?f(t,e,r.props.children,l,r.key):c(t,e,r,l);case qe:return s(t,e=e.get(null===r.key?n:r.key)||null,r,l)}if(fl(r)||it(r))return f(t,e=e.get(n)||null,r,l,null);pl(t,r)}return null}function h(l,i,a,u){for(var c=null,s=null,f=i,h=i=0,y=null;null!==f&&h<a.length;h++){f.index>h?(y=f,f=null):y=f.sibling;var v=p(l,f,a[h],u);if(null===v){null===f&&(f=y);break}e&&f&&null===v.alternate&&t(l,f),i=o(v,i,h),null===s?c=v:s.sibling=v,s=v,f=y}if(h===a.length)return n(l,f),c;if(null===f){for(;h<a.length;h++)(f=d(l,a[h],u))&&(i=o(f,i,h),null===s?c=f:s.sibling=f,s=f);return c}for(f=r(l,f);h<a.length;h++)(y=m(f,l,h,a[h],u))&&(e&&null!==y.alternate&&f.delete(null===y.key?h:y.key),i=o(y,i,h),null===s?c=y:s.sibling=y,s=y);return e&&f.forEach(function(e){return t(l,e)}),c}function y(l,a,u,c){var s=it(u);"function"!==typeof s&&i("150"),null==(u=s.call(u))&&i("151");for(var f=s=null,h=a,y=a=0,v=null,g=u.next();null!==h&&!g.done;y++,g=u.next()){h.index>y?(v=h,h=null):v=h.sibling;var b=p(l,h,g.value,c);if(null===b){h||(h=v);break}e&&h&&null===b.alternate&&t(l,h),a=o(b,a,y),null===f?s=b:f.sibling=b,f=b,h=v}if(g.done)return n(l,h),s;if(null===h){for(;!g.done;y++,g=u.next())null!==(g=d(l,g.value,c))&&(a=o(g,a,y),null===f?s=g:f.sibling=g,f=g);return s}for(h=r(l,h);!g.done;y++,g=u.next())null!==(g=m(h,l,y,g.value,c))&&(e&&null!==g.alternate&&h.delete(null===g.key?y:g.key),a=o(g,a,y),null===f?s=g:f.sibling=g,f=g);return e&&h.forEach(function(e){return t(l,e)}),s}return function(e,r,o,u){var c="object"===typeof o&&null!==o&&o.type===Ye&&null===o.key;c&&(o=o.props.children);var s="object"===typeof o&&null!==o;if(s)switch(o.$$typeof){case Ke:e:{for(s=o.key,c=r;null!==c;){if(c.key===s){if(7===c.tag?o.type===Ye:c.elementType===o.type){n(e,c.sibling),(r=l(c,o.type===Ye?o.props.children:o.props)).ref=dl(e,c,o),r.return=e,e=r;break e}n(e,c);break}t(e,c),c=c.sibling}o.type===Ye?((r=Yr(o.props.children,e.mode,u,o.key)).return=e,e=r):((u=qr(o.type,o.key,o.props,null,e.mode,u)).ref=dl(e,r,o),u.return=e,e=u)}return a(e);case qe:e:{for(c=o.key;null!==r;){if(r.key===c){if(4===r.tag&&r.stateNode.containerInfo===o.containerInfo&&r.stateNode.implementation===o.implementation){n(e,r.sibling),(r=l(r,o.children||[])).return=e,e=r;break e}n(e,r);break}t(e,r),r=r.sibling}(r=Jr(o,e.mode,u)).return=e,e=r}return a(e)}if("string"===typeof o||"number"===typeof o)return o=""+o,null!==r&&6===r.tag?(n(e,r.sibling),(r=l(r,o)).return=e,e=r):(n(e,r),(r=Xr(o,e.mode,u)).return=e,e=r),a(e);if(fl(o))return h(e,r,o,u);if(it(o))return y(e,r,o,u);if(s&&pl(e,o),"undefined"===typeof o&&!c)switch(e.tag){case 1:case 0:i("152",(u=e.type).displayName||u.name||"Component")}return n(e,r)}}var hl=ml(!0),yl=ml(!1),vl={},gl={current:vl},bl={current:vl},wl={current:vl};function kl(e){return e===vl&&i("174"),e}function xl(e,t){Pr(wl,t),Pr(bl,e),Pr(gl,vl);var n=t.nodeType;switch(n){case 9:case 11:t=(t=t.documentElement)?t.namespaceURI:tr(null,"");break;default:t=tr(t=(n=8===n?t.parentNode:t).namespaceURI||null,n=n.tagName)}Cr(gl),Pr(gl,t)}function Tl(e){Cr(gl),Cr(bl),Cr(wl)}function _l(e){kl(wl.current);var t=kl(gl.current),n=tr(t,e.type);t!==n&&(Pr(bl,e),Pr(gl,n))}function Sl(e){bl.current===e&&(Cr(gl),Cr(bl))}var El=0,Cl=2,Pl=4,Nl=8,Ol=16,Rl=32,zl=64,Ll=128,Il=He.ReactCurrentDispatcher,Ml=0,Ul=null,Fl=null,Dl=null,Al=null,jl=null,Wl=null,Vl=0,Bl=null,Hl=0,$l=!1,Ql=null,Kl=0;function ql(){i("321")}function Yl(e,t){if(null===t)return!1;for(var n=0;n<t.length&&n<e.length;n++)if(!Jt(e[n],t[n]))return!1;return!0}function Gl(e,t,n,r,l,o){if(Ml=o,Ul=t,Dl=null!==e?e.memoizedState:null,Il.current=null===Dl?co:so,t=n(r,l),$l){do{$l=!1,Kl+=1,Dl=null!==e?e.memoizedState:null,Wl=Al,Bl=jl=Fl=null,Il.current=so,t=n(r,l)}while($l);Ql=null,Kl=0}return Il.current=uo,(e=Ul).memoizedState=Al,e.expirationTime=Vl,e.updateQueue=Bl,e.effectTag|=Hl,e=null!==Fl&&null!==Fl.next,Ml=0,Wl=jl=Al=Dl=Fl=Ul=null,Vl=0,Bl=null,Hl=0,e&&i("300"),t}function Xl(){Il.current=uo,Ml=0,Wl=jl=Al=Dl=Fl=Ul=null,Vl=0,Bl=null,Hl=0,$l=!1,Ql=null,Kl=0}function Jl(){var e={memoizedState:null,baseState:null,queue:null,baseUpdate:null,next:null};return null===jl?Al=jl=e:jl=jl.next=e,jl}function Zl(){if(null!==Wl)Wl=(jl=Wl).next,Dl=null!==(Fl=Dl)?Fl.next:null;else{null===Dl&&i("310");var e={memoizedState:(Fl=Dl).memoizedState,baseState:Fl.baseState,queue:Fl.queue,baseUpdate:Fl.baseUpdate,next:null};jl=null===jl?Al=e:jl.next=e,Dl=Fl.next}return jl}function eo(e,t){return"function"===typeof t?t(e):t}function to(e){var t=Zl(),n=t.queue;if(null===n&&i("311"),n.lastRenderedReducer=e,0<Kl){var r=n.dispatch;if(null!==Ql){var l=Ql.get(n);if(void 0!==l){Ql.delete(n);var o=t.memoizedState;do{o=e(o,l.action),l=l.next}while(null!==l);return Jt(o,t.memoizedState)||(xo=!0),t.memoizedState=o,t.baseUpdate===n.last&&(t.baseState=o),n.lastRenderedState=o,[o,r]}}return[t.memoizedState,r]}r=n.last;var a=t.baseUpdate;if(o=t.baseState,null!==a?(null!==r&&(r.next=null),r=a.next):r=null!==r?r.next:null,null!==r){var u=l=null,c=r,s=!1;do{var f=c.expirationTime;f<Ml?(s||(s=!0,u=a,l=o),f>Vl&&(Vl=f)):o=c.eagerReducer===e?c.eagerState:e(o,c.action),a=c,c=c.next}while(null!==c&&c!==r);s||(u=a,l=o),Jt(o,t.memoizedState)||(xo=!0),t.memoizedState=o,t.baseUpdate=u,t.baseState=l,n.lastRenderedState=o}return[t.memoizedState,n.dispatch]}function no(e,t,n,r){return e={tag:e,create:t,destroy:n,deps:r,next:null},null===Bl?(Bl={lastEffect:null}).lastEffect=e.next=e:null===(t=Bl.lastEffect)?Bl.lastEffect=e.next=e:(n=t.next,t.next=e,e.next=n,Bl.lastEffect=e),e}function ro(e,t,n,r){var l=Jl();Hl|=e,l.memoizedState=no(t,n,void 0,void 0===r?null:r)}function lo(e,t,n,r){var l=Zl();r=void 0===r?null:r;var o=void 0;if(null!==Fl){var i=Fl.memoizedState;if(o=i.destroy,null!==r&&Yl(r,i.deps))return void no(El,n,o,r)}Hl|=e,l.memoizedState=no(t,n,o,r)}function oo(e,t){return"function"===typeof t?(e=e(),t(e),function(){t(null)}):null!==t&&void 0!==t?(e=e(),t.current=e,function(){t.current=null}):void 0}function io(){}function ao(e,t,n){25>Kl||i("301");var r=e.alternate;if(e===Ul||null!==r&&r===Ul)if($l=!0,e={expirationTime:Ml,action:n,eagerReducer:null,eagerState:null,next:null},null===Ql&&(Ql=new Map),void 0===(n=Ql.get(t)))Ql.set(t,e);else{for(t=n;null!==t.next;)t=t.next;t.next=e}else{Bi();var l=xa(),o={expirationTime:l=Yi(l,e),action:n,eagerReducer:null,eagerState:null,next:null},a=t.last;if(null===a)o.next=o;else{var u=a.next;null!==u&&(o.next=u),a.next=o}if(t.last=o,0===e.expirationTime&&(null===r||0===r.expirationTime)&&null!==(r=t.lastRenderedReducer))try{var c=t.lastRenderedState,s=r(c,n);if(o.eagerReducer=r,o.eagerState=s,Jt(s,c))return}catch(f){}Ji(e,l)}}var uo={readContext:Vo,useCallback:ql,useContext:ql,useEffect:ql,useImperativeHandle:ql,useLayoutEffect:ql,useMemo:ql,useReducer:ql,useRef:ql,useState:ql,useDebugValue:ql},co={readContext:Vo,useCallback:function(e,t){return Jl().memoizedState=[e,void 0===t?null:t],e},useContext:Vo,useEffect:function(e,t){return ro(516,Ll|zl,e,t)},useImperativeHandle:function(e,t,n){return n=null!==n&&void 0!==n?n.concat([e]):null,ro(4,Pl|Rl,oo.bind(null,t,e),n)},useLayoutEffect:function(e,t){return ro(4,Pl|Rl,e,t)},useMemo:function(e,t){var n=Jl();return t=void 0===t?null:t,e=e(),n.memoizedState=[e,t],e},useReducer:function(e,t,n){var r=Jl();return t=void 0!==n?n(t):t,r.memoizedState=r.baseState=t,e=(e=r.queue={last:null,dispatch:null,lastRenderedReducer:e,lastRenderedState:t}).dispatch=ao.bind(null,Ul,e),[r.memoizedState,e]},useRef:function(e){return e={current:e},Jl().memoizedState=e},useState:function(e){var t=Jl();return"function"===typeof e&&(e=e()),t.memoizedState=t.baseState=e,e=(e=t.queue={last:null,dispatch:null,lastRenderedReducer:eo,lastRenderedState:e}).dispatch=ao.bind(null,Ul,e),[t.memoizedState,e]},useDebugValue:io},so={readContext:Vo,useCallback:function(e,t){var n=Zl();t=void 0===t?null:t;var r=n.memoizedState;return null!==r&&null!==t&&Yl(t,r[1])?r[0]:(n.memoizedState=[e,t],e)},useContext:Vo,useEffect:function(e,t){return lo(516,Ll|zl,e,t)},useImperativeHandle:function(e,t,n){return n=null!==n&&void 0!==n?n.concat([e]):null,lo(4,Pl|Rl,oo.bind(null,t,e),n)},useLayoutEffect:function(e,t){return lo(4,Pl|Rl,e,t)},useMemo:function(e,t){var n=Zl();t=void 0===t?null:t;var r=n.memoizedState;return null!==r&&null!==t&&Yl(t,r[1])?r[0]:(e=e(),n.memoizedState=[e,t],e)},useReducer:to,useRef:function(){return Zl().memoizedState},useState:function(e){return to(eo)},useDebugValue:io},fo=null,po=null,mo=!1;function ho(e,t){var n=$r(5,null,null,0);n.elementType="DELETED",n.type="DELETED",n.stateNode=t,n.return=e,n.effectTag=8,null!==e.lastEffect?(e.lastEffect.nextEffect=n,e.lastEffect=n):e.firstEffect=e.lastEffect=n}function yo(e,t){switch(e.tag){case 5:var n=e.type;return null!==(t=1!==t.nodeType||n.toLowerCase()!==t.nodeName.toLowerCase()?null:t)&&(e.stateNode=t,!0);case 6:return null!==(t=""===e.pendingProps||3!==t.nodeType?null:t)&&(e.stateNode=t,!0);case 13:default:return!1}}function vo(e){if(mo){var t=po;if(t){var n=t;if(!yo(e,t)){if(!(t=Tr(n))||!yo(e,t))return e.effectTag|=2,mo=!1,void(fo=e);ho(fo,n)}fo=e,po=_r(t)}else e.effectTag|=2,mo=!1,fo=e}}function go(e){for(e=e.return;null!==e&&5!==e.tag&&3!==e.tag&&18!==e.tag;)e=e.return;fo=e}function bo(e){if(e!==fo)return!1;if(!mo)return go(e),mo=!0,!1;var t=e.type;if(5!==e.tag||"head"!==t&&"body"!==t&&!gr(t,e.memoizedProps))for(t=po;t;)ho(e,t),t=Tr(t);return go(e),po=fo?Tr(e.stateNode):null,!0}function wo(){po=fo=null,mo=!1}var ko=He.ReactCurrentOwner,xo=!1;function To(e,t,n,r){t.child=null===e?yl(t,null,n,r):hl(t,e.child,n,r)}function _o(e,t,n,r,l){n=n.render;var o=t.ref;return Wo(t,l),r=Gl(e,t,n,r,o,l),null===e||xo?(t.effectTag|=1,To(e,t,r,l),t.child):(t.updateQueue=e.updateQueue,t.effectTag&=-517,e.expirationTime<=l&&(e.expirationTime=0),Lo(e,t,l))}function So(e,t,n,r,l,o){if(null===e){var i=n.type;return"function"!==typeof i||Qr(i)||void 0!==i.defaultProps||null!==n.compare||void 0!==n.defaultProps?((e=qr(n.type,null,r,null,t.mode,o)).ref=t.ref,e.return=t,t.child=e):(t.tag=15,t.type=i,Eo(e,t,i,r,l,o))}return i=e.child,l<o&&(l=i.memoizedProps,(n=null!==(n=n.compare)?n:en)(l,r)&&e.ref===t.ref)?Lo(e,t,o):(t.effectTag|=1,(e=Kr(i,r)).ref=t.ref,e.return=t,t.child=e)}function Eo(e,t,n,r,l,o){return null!==e&&en(e.memoizedProps,r)&&e.ref===t.ref&&(xo=!1,l<o)?Lo(e,t,o):Po(e,t,n,r,o)}function Co(e,t){var n=t.ref;(null===e&&null!==n||null!==e&&e.ref!==n)&&(t.effectTag|=128)}function Po(e,t,n,r,l){var o=Ir(n)?zr:Or.current;return o=Lr(t,o),Wo(t,l),n=Gl(e,t,n,r,o,l),null===e||xo?(t.effectTag|=1,To(e,t,n,l),t.child):(t.updateQueue=e.updateQueue,t.effectTag&=-517,e.expirationTime<=l&&(e.expirationTime=0),Lo(e,t,l))}function No(e,t,n,r,l){if(Ir(n)){var o=!0;Ar(t)}else o=!1;if(Wo(t,l),null===t.stateNode)null!==e&&(e.alternate=null,t.alternate=null,t.effectTag|=2),ul(t,n,r),sl(t,n,r,l),r=!0;else if(null===e){var i=t.stateNode,a=t.memoizedProps;i.props=a;var u=i.context,c=n.contextType;"object"===typeof c&&null!==c?c=Vo(c):c=Lr(t,c=Ir(n)?zr:Or.current);var s=n.getDerivedStateFromProps,f="function"===typeof s||"function"===typeof i.getSnapshotBeforeUpdate;f||"function"!==typeof i.UNSAFE_componentWillReceiveProps&&"function"!==typeof i.componentWillReceiveProps||(a!==r||u!==c)&&cl(t,i,r,c),Ko=!1;var d=t.memoizedState;u=i.state=d;var p=t.updateQueue;null!==p&&(ni(t,p,r,i,l),u=t.memoizedState),a!==r||d!==u||Rr.current||Ko?("function"===typeof s&&(ol(t,n,s,r),u=t.memoizedState),(a=Ko||al(t,n,a,r,d,u,c))?(f||"function"!==typeof i.UNSAFE_componentWillMount&&"function"!==typeof i.componentWillMount||("function"===typeof i.componentWillMount&&i.componentWillMount(),"function"===typeof i.UNSAFE_componentWillMount&&i.UNSAFE_componentWillMount()),"function"===typeof i.componentDidMount&&(t.effectTag|=4)):("function"===typeof i.componentDidMount&&(t.effectTag|=4),t.memoizedProps=r,t.memoizedState=u),i.props=r,i.state=u,i.context=c,r=a):("function"===typeof i.componentDidMount&&(t.effectTag|=4),r=!1)}else i=t.stateNode,a=t.memoizedProps,i.props=t.type===t.elementType?a:rl(t.type,a),u=i.context,"object"===typeof(c=n.contextType)&&null!==c?c=Vo(c):c=Lr(t,c=Ir(n)?zr:Or.current),(f="function"===typeof(s=n.getDerivedStateFromProps)||"function"===typeof i.getSnapshotBeforeUpdate)||"function"!==typeof i.UNSAFE_componentWillReceiveProps&&"function"!==typeof i.componentWillReceiveProps||(a!==r||u!==c)&&cl(t,i,r,c),Ko=!1,u=t.memoizedState,d=i.state=u,null!==(p=t.updateQueue)&&(ni(t,p,r,i,l),d=t.memoizedState),a!==r||u!==d||Rr.current||Ko?("function"===typeof s&&(ol(t,n,s,r),d=t.memoizedState),(s=Ko||al(t,n,a,r,u,d,c))?(f||"function"!==typeof i.UNSAFE_componentWillUpdate&&"function"!==typeof i.componentWillUpdate||("function"===typeof i.componentWillUpdate&&i.componentWillUpdate(r,d,c),"function"===typeof i.UNSAFE_componentWillUpdate&&i.UNSAFE_componentWillUpdate(r,d,c)),"function"===typeof i.componentDidUpdate&&(t.effectTag|=4),"function"===typeof i.getSnapshotBeforeUpdate&&(t.effectTag|=256)):("function"!==typeof i.componentDidUpdate||a===e.memoizedProps&&u===e.memoizedState||(t.effectTag|=4),"function"!==typeof i.getSnapshotBeforeUpdate||a===e.memoizedProps&&u===e.memoizedState||(t.effectTag|=256),t.memoizedProps=r,t.memoizedState=d),i.props=r,i.state=d,i.context=c,r=s):("function"!==typeof i.componentDidUpdate||a===e.memoizedProps&&u===e.memoizedState||(t.effectTag|=4),"function"!==typeof i.getSnapshotBeforeUpdate||a===e.memoizedProps&&u===e.memoizedState||(t.effectTag|=256),r=!1);return Oo(e,t,n,r,o,l)}function Oo(e,t,n,r,l,o){Co(e,t);var i=0!==(64&t.effectTag);if(!r&&!i)return l&&jr(t,n,!1),Lo(e,t,o);r=t.stateNode,ko.current=t;var a=i&&"function"!==typeof n.getDerivedStateFromError?null:r.render();return t.effectTag|=1,null!==e&&i?(t.child=hl(t,e.child,null,o),t.child=hl(t,null,a,o)):To(e,t,a,o),t.memoizedState=r.state,l&&jr(t,n,!0),t.child}function Ro(e){var t=e.stateNode;t.pendingContext?Fr(0,t.pendingContext,t.pendingContext!==t.context):t.context&&Fr(0,t.context,!1),xl(e,t.containerInfo)}function zo(e,t,n){var r=t.mode,l=t.pendingProps,o=t.memoizedState;if(0===(64&t.effectTag)){o=null;var i=!1}else o={timedOutAt:null!==o?o.timedOutAt:0},i=!0,t.effectTag&=-65;if(null===e)if(i){var a=l.fallback;e=Yr(null,r,0,null),0===(1&t.mode)&&(e.child=null!==t.memoizedState?t.child.child:t.child),r=Yr(a,r,n,null),e.sibling=r,(n=e).return=r.return=t}else n=r=yl(t,null,l.children,n);else null!==e.memoizedState?(a=(r=e.child).sibling,i?(n=l.fallback,l=Kr(r,r.pendingProps),0===(1&t.mode)&&((i=null!==t.memoizedState?t.child.child:t.child)!==r.child&&(l.child=i)),r=l.sibling=Kr(a,n,a.expirationTime),n=l,l.childExpirationTime=0,n.return=r.return=t):n=r=hl(t,r.child,l.children,n)):(a=e.child,i?(i=l.fallback,(l=Yr(null,r,0,null)).child=a,0===(1&t.mode)&&(l.child=null!==t.memoizedState?t.child.child:t.child),(r=l.sibling=Yr(i,r,n,null)).effectTag|=2,n=l,l.childExpirationTime=0,n.return=r.return=t):r=n=hl(t,a,l.children,n)),t.stateNode=e.stateNode;return t.memoizedState=o,t.child=n,r}function Lo(e,t,n){if(null!==e&&(t.contextDependencies=e.contextDependencies),t.childExpirationTime<n)return null;if(null!==e&&t.child!==e.child&&i("153"),null!==t.child){for(n=Kr(e=t.child,e.pendingProps,e.expirationTime),t.child=n,n.return=t;null!==e.sibling;)e=e.sibling,(n=n.sibling=Kr(e,e.pendingProps,e.expirationTime)).return=t;n.sibling=null}return t.child}function Io(e,t,n){var r=t.expirationTime;if(null!==e){if(e.memoizedProps!==t.pendingProps||Rr.current)xo=!0;else if(r<n){switch(xo=!1,t.tag){case 3:Ro(t),wo();break;case 5:_l(t);break;case 1:Ir(t.type)&&Ar(t);break;case 4:xl(t,t.stateNode.containerInfo);break;case 10:Ao(t,t.memoizedProps.value);break;case 13:if(null!==t.memoizedState)return 0!==(r=t.child.childExpirationTime)&&r>=n?zo(e,t,n):null!==(t=Lo(e,t,n))?t.sibling:null}return Lo(e,t,n)}}else xo=!1;switch(t.expirationTime=0,t.tag){case 2:r=t.elementType,null!==e&&(e.alternate=null,t.alternate=null,t.effectTag|=2),e=t.pendingProps;var l=Lr(t,Or.current);if(Wo(t,n),l=Gl(null,t,r,e,l,n),t.effectTag|=1,"object"===typeof l&&null!==l&&"function"===typeof l.render&&void 0===l.$$typeof){if(t.tag=1,Xl(),Ir(r)){var o=!0;Ar(t)}else o=!1;t.memoizedState=null!==l.state&&void 0!==l.state?l.state:null;var a=r.getDerivedStateFromProps;"function"===typeof a&&ol(t,r,a,e),l.updater=il,t.stateNode=l,l._reactInternalFiber=t,sl(t,r,e,n),t=Oo(null,t,r,!0,o,n)}else t.tag=0,To(null,t,l,n),t=t.child;return t;case 16:switch(l=t.elementType,null!==e&&(e.alternate=null,t.alternate=null,t.effectTag|=2),o=t.pendingProps,e=function(e){var t=e._result;switch(e._status){case 1:return t;case 2:case 0:throw t;default:switch(e._status=0,(t=(t=e._ctor)()).then(function(t){0===e._status&&(t=t.default,e._status=1,e._result=t)},function(t){0===e._status&&(e._status=2,e._result=t)}),e._status){case 1:return e._result;case 2:throw e._result}throw e._result=t,t}}(l),t.type=e,l=t.tag=function(e){if("function"===typeof e)return Qr(e)?1:0;if(void 0!==e&&null!==e){if((e=e.$$typeof)===tt)return 11;if(e===rt)return 14}return 2}(e),o=rl(e,o),a=void 0,l){case 0:a=Po(null,t,e,o,n);break;case 1:a=No(null,t,e,o,n);break;case 11:a=_o(null,t,e,o,n);break;case 14:a=So(null,t,e,rl(e.type,o),r,n);break;default:i("306",e,"")}return a;case 0:return r=t.type,l=t.pendingProps,Po(e,t,r,l=t.elementType===r?l:rl(r,l),n);case 1:return r=t.type,l=t.pendingProps,No(e,t,r,l=t.elementType===r?l:rl(r,l),n);case 3:return Ro(t),null===(r=t.updateQueue)&&i("282"),l=null!==(l=t.memoizedState)?l.element:null,ni(t,r,t.pendingProps,null,n),(r=t.memoizedState.element)===l?(wo(),t=Lo(e,t,n)):(l=t.stateNode,(l=(null===e||null===e.child)&&l.hydrate)&&(po=_r(t.stateNode.containerInfo),fo=t,l=mo=!0),l?(t.effectTag|=2,t.child=yl(t,null,r,n)):(To(e,t,r,n),wo()),t=t.child),t;case 5:return _l(t),null===e&&vo(t),r=t.type,l=t.pendingProps,o=null!==e?e.memoizedProps:null,a=l.children,gr(r,l)?a=null:null!==o&&gr(r,o)&&(t.effectTag|=16),Co(e,t),1!==n&&1&t.mode&&l.hidden?(t.expirationTime=t.childExpirationTime=1,t=null):(To(e,t,a,n),t=t.child),t;case 6:return null===e&&vo(t),null;case 13:return zo(e,t,n);case 4:return xl(t,t.stateNode.containerInfo),r=t.pendingProps,null===e?t.child=hl(t,null,r,n):To(e,t,r,n),t.child;case 11:return r=t.type,l=t.pendingProps,_o(e,t,r,l=t.elementType===r?l:rl(r,l),n);case 7:return To(e,t,t.pendingProps,n),t.child;case 8:case 12:return To(e,t,t.pendingProps.children,n),t.child;case 10:e:{if(r=t.type._context,l=t.pendingProps,a=t.memoizedProps,Ao(t,o=l.value),null!==a){var u=a.value;if(0===(o=Jt(u,o)?0:0|("function"===typeof r._calculateChangedBits?r._calculateChangedBits(u,o):1073741823))){if(a.children===l.children&&!Rr.current){t=Lo(e,t,n);break e}}else for(null!==(u=t.child)&&(u.return=t);null!==u;){var c=u.contextDependencies;if(null!==c){a=u.child;for(var s=c.first;null!==s;){if(s.context===r&&0!==(s.observedBits&o)){1===u.tag&&((s=Go(n)).tag=$o,Jo(u,s)),u.expirationTime<n&&(u.expirationTime=n),null!==(s=u.alternate)&&s.expirationTime<n&&(s.expirationTime=n),s=n;for(var f=u.return;null!==f;){var d=f.alternate;if(f.childExpirationTime<s)f.childExpirationTime=s,null!==d&&d.childExpirationTime<s&&(d.childExpirationTime=s);else{if(!(null!==d&&d.childExpirationTime<s))break;d.childExpirationTime=s}f=f.return}c.expirationTime<n&&(c.expirationTime=n);break}s=s.next}}else a=10===u.tag&&u.type===t.type?null:u.child;if(null!==a)a.return=u;else for(a=u;null!==a;){if(a===t){a=null;break}if(null!==(u=a.sibling)){u.return=a.return,a=u;break}a=a.return}u=a}}To(e,t,l.children,n),t=t.child}return t;case 9:return l=t.type,r=(o=t.pendingProps).children,Wo(t,n),r=r(l=Vo(l,o.unstable_observedBits)),t.effectTag|=1,To(e,t,r,n),t.child;case 14:return o=rl(l=t.type,t.pendingProps),So(e,t,l,o=rl(l.type,o),r,n);case 15:return Eo(e,t,t.type,t.pendingProps,r,n);case 17:return r=t.type,l=t.pendingProps,l=t.elementType===r?l:rl(r,l),null!==e&&(e.alternate=null,t.alternate=null,t.effectTag|=2),t.tag=1,Ir(r)?(e=!0,Ar(t)):e=!1,Wo(t,n),ul(t,r,l),sl(t,r,l,n),Oo(null,t,r,!0,e,n)}i("156")}var Mo={current:null},Uo=null,Fo=null,Do=null;function Ao(e,t){var n=e.type._context;Pr(Mo,n._currentValue),n._currentValue=t}function jo(e){var t=Mo.current;Cr(Mo),e.type._context._currentValue=t}function Wo(e,t){Uo=e,Do=Fo=null;var n=e.contextDependencies;null!==n&&n.expirationTime>=t&&(xo=!0),e.contextDependencies=null}function Vo(e,t){return Do!==e&&!1!==t&&0!==t&&("number"===typeof t&&1073741823!==t||(Do=e,t=1073741823),t={context:e,observedBits:t,next:null},null===Fo?(null===Uo&&i("308"),Fo=t,Uo.contextDependencies={first:t,expirationTime:0}):Fo=Fo.next=t),e._currentValue}var Bo=0,Ho=1,$o=2,Qo=3,Ko=!1;function qo(e){return{baseState:e,firstUpdate:null,lastUpdate:null,firstCapturedUpdate:null,lastCapturedUpdate:null,firstEffect:null,lastEffect:null,firstCapturedEffect:null,lastCapturedEffect:null}}function Yo(e){return{baseState:e.baseState,firstUpdate:e.firstUpdate,lastUpdate:e.lastUpdate,firstCapturedUpdate:null,lastCapturedUpdate:null,firstEffect:null,lastEffect:null,firstCapturedEffect:null,lastCapturedEffect:null}}function Go(e){return{expirationTime:e,tag:Bo,payload:null,callback:null,next:null,nextEffect:null}}function Xo(e,t){null===e.lastUpdate?e.firstUpdate=e.lastUpdate=t:(e.lastUpdate.next=t,e.lastUpdate=t)}function Jo(e,t){var n=e.alternate;if(null===n){var r=e.updateQueue,l=null;null===r&&(r=e.updateQueue=qo(e.memoizedState))}else r=e.updateQueue,l=n.updateQueue,null===r?null===l?(r=e.updateQueue=qo(e.memoizedState),l=n.updateQueue=qo(n.memoizedState)):r=e.updateQueue=Yo(l):null===l&&(l=n.updateQueue=Yo(r));null===l||r===l?Xo(r,t):null===r.lastUpdate||null===l.lastUpdate?(Xo(r,t),Xo(l,t)):(Xo(r,t),l.lastUpdate=t)}function Zo(e,t){var n=e.updateQueue;null===(n=null===n?e.updateQueue=qo(e.memoizedState):ei(e,n)).lastCapturedUpdate?n.firstCapturedUpdate=n.lastCapturedUpdate=t:(n.lastCapturedUpdate.next=t,n.lastCapturedUpdate=t)}function ei(e,t){var n=e.alternate;return null!==n&&t===n.updateQueue&&(t=e.updateQueue=Yo(t)),t}function ti(e,t,n,r,o,i){switch(n.tag){case Ho:return"function"===typeof(e=n.payload)?e.call(i,r,o):e;case Qo:e.effectTag=-2049&e.effectTag|64;case Bo:if(null===(o="function"===typeof(e=n.payload)?e.call(i,r,o):e)||void 0===o)break;return l({},r,o);case $o:Ko=!0}return r}function ni(e,t,n,r,l){Ko=!1;for(var o=(t=ei(e,t)).baseState,i=null,a=0,u=t.firstUpdate,c=o;null!==u;){var s=u.expirationTime;s<l?(null===i&&(i=u,o=c),a<s&&(a=s)):(c=ti(e,0,u,c,n,r),null!==u.callback&&(e.effectTag|=32,u.nextEffect=null,null===t.lastEffect?t.firstEffect=t.lastEffect=u:(t.lastEffect.nextEffect=u,t.lastEffect=u))),u=u.next}for(s=null,u=t.firstCapturedUpdate;null!==u;){var f=u.expirationTime;f<l?(null===s&&(s=u,null===i&&(o=c)),a<f&&(a=f)):(c=ti(e,0,u,c,n,r),null!==u.callback&&(e.effectTag|=32,u.nextEffect=null,null===t.lastCapturedEffect?t.firstCapturedEffect=t.lastCapturedEffect=u:(t.lastCapturedEffect.nextEffect=u,t.lastCapturedEffect=u))),u=u.next}null===i&&(t.lastUpdate=null),null===s?t.lastCapturedUpdate=null:e.effectTag|=32,null===i&&null===s&&(o=c),t.baseState=o,t.firstUpdate=i,t.firstCapturedUpdate=s,e.expirationTime=a,e.memoizedState=c}function ri(e,t,n){null!==t.firstCapturedUpdate&&(null!==t.lastUpdate&&(t.lastUpdate.next=t.firstCapturedUpdate,t.lastUpdate=t.lastCapturedUpdate),t.firstCapturedUpdate=t.lastCapturedUpdate=null),li(t.firstEffect,n),t.firstEffect=t.lastEffect=null,li(t.firstCapturedEffect,n),t.firstCapturedEffect=t.lastCapturedEffect=null}function li(e,t){for(;null!==e;){var n=e.callback;if(null!==n){e.callback=null;var r=t;"function"!==typeof n&&i("191",n),n.call(r)}e=e.nextEffect}}function oi(e,t){return{value:e,source:t,stack:ut(t)}}function ii(e){e.effectTag|=4}var ai=void 0,ui=void 0,ci=void 0,si=void 0;ai=function(e,t){for(var n=t.child;null!==n;){if(5===n.tag||6===n.tag)e.appendChild(n.stateNode);else if(4!==n.tag&&null!==n.child){n.child.return=n,n=n.child;continue}if(n===t)break;for(;null===n.sibling;){if(null===n.return||n.return===t)return;n=n.return}n.sibling.return=n.return,n=n.sibling}},ui=function(){},ci=function(e,t,n,r,o){var i=e.memoizedProps;if(i!==r){var a=t.stateNode;switch(kl(gl.current),e=null,n){case"input":i=bt(a,i),r=bt(a,r),e=[];break;case"option":i=Kn(a,i),r=Kn(a,r),e=[];break;case"select":i=l({},i,{value:void 0}),r=l({},r,{value:void 0}),e=[];break;case"textarea":i=Yn(a,i),r=Yn(a,r),e=[];break;default:"function"!==typeof i.onClick&&"function"===typeof r.onClick&&(a.onclick=mr)}fr(n,r),a=n=void 0;var u=null;for(n in i)if(!r.hasOwnProperty(n)&&i.hasOwnProperty(n)&&null!=i[n])if("style"===n){var c=i[n];for(a in c)c.hasOwnProperty(a)&&(u||(u={}),u[a]="")}else"dangerouslySetInnerHTML"!==n&&"children"!==n&&"suppressContentEditableWarning"!==n&&"suppressHydrationWarning"!==n&&"autoFocus"!==n&&(b.hasOwnProperty(n)?e||(e=[]):(e=e||[]).push(n,null));for(n in r){var s=r[n];if(c=null!=i?i[n]:void 0,r.hasOwnProperty(n)&&s!==c&&(null!=s||null!=c))if("style"===n)if(c){for(a in c)!c.hasOwnProperty(a)||s&&s.hasOwnProperty(a)||(u||(u={}),u[a]="");for(a in s)s.hasOwnProperty(a)&&c[a]!==s[a]&&(u||(u={}),u[a]=s[a])}else u||(e||(e=[]),e.push(n,u)),u=s;else"dangerouslySetInnerHTML"===n?(s=s?s.__html:void 0,c=c?c.__html:void 0,null!=s&&c!==s&&(e=e||[]).push(n,""+s)):"children"===n?c===s||"string"!==typeof s&&"number"!==typeof s||(e=e||[]).push(n,""+s):"suppressContentEditableWarning"!==n&&"suppressHydrationWarning"!==n&&(b.hasOwnProperty(n)?(null!=s&&pr(o,n),e||c===s||(e=[])):(e=e||[]).push(n,s))}u&&(e=e||[]).push("style",u),o=e,(t.updateQueue=o)&&ii(t)}},si=function(e,t,n,r){n!==r&&ii(t)};var fi="function"===typeof WeakSet?WeakSet:Set;function di(e,t){var n=t.source,r=t.stack;null===r&&null!==n&&(r=ut(n)),null!==n&&at(n.type),t=t.value,null!==e&&1===e.tag&&at(e.type);try{console.error(t)}catch(l){setTimeout(function(){throw l})}}function pi(e){var t=e.ref;if(null!==t)if("function"===typeof t)try{t(null)}catch(n){qi(e,n)}else t.current=null}function mi(e,t,n){if(null!==(n=null!==(n=n.updateQueue)?n.lastEffect:null)){var r=n=n.next;do{if((r.tag&e)!==El){var l=r.destroy;r.destroy=void 0,void 0!==l&&l()}(r.tag&t)!==El&&(l=r.create,r.destroy=l()),r=r.next}while(r!==n)}}function hi(e){switch("function"===typeof Vr&&Vr(e),e.tag){case 0:case 11:case 14:case 15:var t=e.updateQueue;if(null!==t&&null!==(t=t.lastEffect)){var n=t=t.next;do{var r=n.destroy;if(void 0!==r){var l=e;try{r()}catch(o){qi(l,o)}}n=n.next}while(n!==t)}break;case 1:if(pi(e),"function"===typeof(t=e.stateNode).componentWillUnmount)try{t.props=e.memoizedProps,t.state=e.memoizedState,t.componentWillUnmount()}catch(o){qi(e,o)}break;case 5:pi(e);break;case 4:gi(e)}}function yi(e){return 5===e.tag||3===e.tag||4===e.tag}function vi(e){e:{for(var t=e.return;null!==t;){if(yi(t)){var n=t;break e}t=t.return}i("160"),n=void 0}var r=t=void 0;switch(n.tag){case 5:t=n.stateNode,r=!1;break;case 3:case 4:t=n.stateNode.containerInfo,r=!0;break;default:i("161")}16&n.effectTag&&(or(t,""),n.effectTag&=-17);e:t:for(n=e;;){for(;null===n.sibling;){if(null===n.return||yi(n.return)){n=null;break e}n=n.return}for(n.sibling.return=n.return,n=n.sibling;5!==n.tag&&6!==n.tag&&18!==n.tag;){if(2&n.effectTag)continue t;if(null===n.child||4===n.tag)continue t;n.child.return=n,n=n.child}if(!(2&n.effectTag)){n=n.stateNode;break e}}for(var l=e;;){if(5===l.tag||6===l.tag)if(n)if(r){var o=t,a=l.stateNode,u=n;8===o.nodeType?o.parentNode.insertBefore(a,u):o.insertBefore(a,u)}else t.insertBefore(l.stateNode,n);else r?(a=t,u=l.stateNode,8===a.nodeType?(o=a.parentNode).insertBefore(u,a):(o=a).appendChild(u),null!==(a=a._reactRootContainer)&&void 0!==a||null!==o.onclick||(o.onclick=mr)):t.appendChild(l.stateNode);else if(4!==l.tag&&null!==l.child){l.child.return=l,l=l.child;continue}if(l===e)break;for(;null===l.sibling;){if(null===l.return||l.return===e)return;l=l.return}l.sibling.return=l.return,l=l.sibling}}function gi(e){for(var t=e,n=!1,r=void 0,l=void 0;;){if(!n){n=t.return;e:for(;;){switch(null===n&&i("160"),n.tag){case 5:r=n.stateNode,l=!1;break e;case 3:case 4:r=n.stateNode.containerInfo,l=!0;break e}n=n.return}n=!0}if(5===t.tag||6===t.tag){e:for(var o=t,a=o;;)if(hi(a),null!==a.child&&4!==a.tag)a.child.return=a,a=a.child;else{if(a===o)break;for(;null===a.sibling;){if(null===a.return||a.return===o)break e;a=a.return}a.sibling.return=a.return,a=a.sibling}l?(o=r,a=t.stateNode,8===o.nodeType?o.parentNode.removeChild(a):o.removeChild(a)):r.removeChild(t.stateNode)}else if(4===t.tag){if(null!==t.child){r=t.stateNode.containerInfo,l=!0,t.child.return=t,t=t.child;continue}}else if(hi(t),null!==t.child){t.child.return=t,t=t.child;continue}if(t===e)break;for(;null===t.sibling;){if(null===t.return||t.return===e)return;4===(t=t.return).tag&&(n=!1)}t.sibling.return=t.return,t=t.sibling}}function bi(e,t){switch(t.tag){case 0:case 11:case 14:case 15:mi(Pl,Nl,t);break;case 1:break;case 5:var n=t.stateNode;if(null!=n){var r=t.memoizedProps;e=null!==e?e.memoizedProps:r;var l=t.type,o=t.updateQueue;t.updateQueue=null,null!==o&&function(e,t,n,r,l){e[I]=l,"input"===n&&"radio"===l.type&&null!=l.name&&kt(e,l),dr(n,r),r=dr(n,l);for(var o=0;o<t.length;o+=2){var i=t[o],a=t[o+1];"style"===i?cr(e,a):"dangerouslySetInnerHTML"===i?lr(e,a):"children"===i?or(e,a):vt(e,i,a,r)}switch(n){case"input":xt(e,l);break;case"textarea":Xn(e,l);break;case"select":t=e._wrapperState.wasMultiple,e._wrapperState.wasMultiple=!!l.multiple,null!=(n=l.value)?qn(e,!!l.multiple,n,!1):t!==!!l.multiple&&(null!=l.defaultValue?qn(e,!!l.multiple,l.defaultValue,!0):qn(e,!!l.multiple,l.multiple?[]:"",!1))}}(n,o,l,e,r)}break;case 6:null===t.stateNode&&i("162"),t.stateNode.nodeValue=t.memoizedProps;break;case 3:case 12:break;case 13:if(n=t.memoizedState,r=void 0,e=t,null===n?r=!1:(r=!0,e=t.child,0===n.timedOutAt&&(n.timedOutAt=xa())),null!==e&&function(e,t){for(var n=e;;){if(5===n.tag){var r=n.stateNode;if(t)r.style.display="none";else{r=n.stateNode;var l=n.memoizedProps.style;l=void 0!==l&&null!==l&&l.hasOwnProperty("display")?l.display:null,r.style.display=ur("display",l)}}else if(6===n.tag)n.stateNode.nodeValue=t?"":n.memoizedProps;else{if(13===n.tag&&null!==n.memoizedState){(r=n.child.sibling).return=n,n=r;continue}if(null!==n.child){n.child.return=n,n=n.child;continue}}if(n===e)break;for(;null===n.sibling;){if(null===n.return||n.return===e)return;n=n.return}n.sibling.return=n.return,n=n.sibling}}(e,r),null!==(n=t.updateQueue)){t.updateQueue=null;var a=t.stateNode;null===a&&(a=t.stateNode=new fi),n.forEach(function(e){var n=function(e,t){var n=e.stateNode;null!==n&&n.delete(t),t=Yi(t=xa(),e),null!==(e=Xi(e,t))&&(Zr(e,t),0!==(t=e.expirationTime)&&Ta(e,t))}.bind(null,t,e);a.has(e)||(a.add(e),e.then(n,n))})}break;case 17:break;default:i("163")}}var wi="function"===typeof WeakMap?WeakMap:Map;function ki(e,t,n){(n=Go(n)).tag=Qo,n.payload={element:null};var r=t.value;return n.callback=function(){za(r),di(e,t)},n}function xi(e,t,n){(n=Go(n)).tag=Qo;var r=e.type.getDerivedStateFromError;if("function"===typeof r){var l=t.value;n.payload=function(){return r(l)}}var o=e.stateNode;return null!==o&&"function"===typeof o.componentDidCatch&&(n.callback=function(){"function"!==typeof r&&(null===Di?Di=new Set([this]):Di.add(this));var n=t.value,l=t.stack;di(e,t),this.componentDidCatch(n,{componentStack:null!==l?l:""})}),n}function Ti(e){switch(e.tag){case 1:Ir(e.type)&&Mr();var t=e.effectTag;return 2048&t?(e.effectTag=-2049&t|64,e):null;case 3:return Tl(),Ur(),0!==(64&(t=e.effectTag))&&i("285"),e.effectTag=-2049&t|64,e;case 5:return Sl(e),null;case 13:return 2048&(t=e.effectTag)?(e.effectTag=-2049&t|64,e):null;case 18:return null;case 4:return Tl(),null;case 10:return jo(e),null;default:return null}}var _i=He.ReactCurrentDispatcher,Si=He.ReactCurrentOwner,Ei=1073741822,Ci=!1,Pi=null,Ni=null,Oi=0,Ri=-1,zi=!1,Li=null,Ii=!1,Mi=null,Ui=null,Fi=null,Di=null;function Ai(){if(null!==Pi)for(var e=Pi.return;null!==e;){var t=e;switch(t.tag){case 1:var n=t.type.childContextTypes;null!==n&&void 0!==n&&Mr();break;case 3:Tl(),Ur();break;case 5:Sl(t);break;case 4:Tl();break;case 10:jo(t)}e=e.return}Ni=null,Oi=0,Ri=-1,zi=!1,Pi=null}function ji(){for(;null!==Li;){var e=Li.effectTag;if(16&e&&or(Li.stateNode,""),128&e){var t=Li.alternate;null!==t&&(null!==(t=t.ref)&&("function"===typeof t?t(null):t.current=null))}switch(14&e){case 2:vi(Li),Li.effectTag&=-3;break;case 6:vi(Li),Li.effectTag&=-3,bi(Li.alternate,Li);break;case 4:bi(Li.alternate,Li);break;case 8:gi(e=Li),e.return=null,e.child=null,e.memoizedState=null,e.updateQueue=null,null!==(e=e.alternate)&&(e.return=null,e.child=null,e.memoizedState=null,e.updateQueue=null)}Li=Li.nextEffect}}function Wi(){for(;null!==Li;){if(256&Li.effectTag)e:{var e=Li.alternate,t=Li;switch(t.tag){case 0:case 11:case 15:mi(Cl,El,t);break e;case 1:if(256&t.effectTag&&null!==e){var n=e.memoizedProps,r=e.memoizedState;t=(e=t.stateNode).getSnapshotBeforeUpdate(t.elementType===t.type?n:rl(t.type,n),r),e.__reactInternalSnapshotBeforeUpdate=t}break e;case 3:case 5:case 6:case 4:case 17:break e;default:i("163")}}Li=Li.nextEffect}}function Vi(e,t){for(;null!==Li;){var n=Li.effectTag;if(36&n){var r=Li.alternate,l=Li,o=t;switch(l.tag){case 0:case 11:case 15:mi(Ol,Rl,l);break;case 1:var a=l.stateNode;if(4&l.effectTag)if(null===r)a.componentDidMount();else{var u=l.elementType===l.type?r.memoizedProps:rl(l.type,r.memoizedProps);a.componentDidUpdate(u,r.memoizedState,a.__reactInternalSnapshotBeforeUpdate)}null!==(r=l.updateQueue)&&ri(0,r,a);break;case 3:if(null!==(r=l.updateQueue)){if(a=null,null!==l.child)switch(l.child.tag){case 5:a=l.child.stateNode;break;case 1:a=l.child.stateNode}ri(0,r,a)}break;case 5:o=l.stateNode,null===r&&4&l.effectTag&&vr(l.type,l.memoizedProps)&&o.focus();break;case 6:case 4:case 12:case 13:case 17:break;default:i("163")}}128&n&&(null!==(l=Li.ref)&&(o=Li.stateNode,"function"===typeof l?l(o):l.current=o)),512&n&&(Mi=e),Li=Li.nextEffect}}function Bi(){null!==Ui&&xr(Ui),null!==Fi&&Fi()}function Hi(e,t){Ii=Ci=!0,e.current===t&&i("177");var n=e.pendingCommitExpirationTime;0===n&&i("261"),e.pendingCommitExpirationTime=0;var r=t.expirationTime,l=t.childExpirationTime;for(function(e,t){if(e.didError=!1,0===t)e.earliestPendingTime=0,e.latestPendingTime=0,e.earliestSuspendedTime=0,e.latestSuspendedTime=0,e.latestPingedTime=0;else{t<e.latestPingedTime&&(e.latestPingedTime=0);var n=e.latestPendingTime;0!==n&&(n>t?e.earliestPendingTime=e.latestPendingTime=0:e.earliestPendingTime>t&&(e.earliestPendingTime=e.latestPendingTime)),0===(n=e.earliestSuspendedTime)?Zr(e,t):t<e.latestSuspendedTime?(e.earliestSuspendedTime=0,e.latestSuspendedTime=0,e.latestPingedTime=0,Zr(e,t)):t>n&&Zr(e,t)}nl(0,e)}(e,l>r?l:r),Si.current=null,r=void 0,1<t.effectTag?null!==t.lastEffect?(t.lastEffect.nextEffect=t,r=t.firstEffect):r=t:r=t.firstEffect,hr=_n,yr=function(){var e=Un();if(Fn(e)){if("selectionStart"in e)var t={start:e.selectionStart,end:e.selectionEnd};else e:{var n=(t=(t=e.ownerDocument)&&t.defaultView||window).getSelection&&t.getSelection();if(n&&0!==n.rangeCount){t=n.anchorNode;var r=n.anchorOffset,l=n.focusNode;n=n.focusOffset;try{t.nodeType,l.nodeType}catch(p){t=null;break e}var o=0,i=-1,a=-1,u=0,c=0,s=e,f=null;t:for(;;){for(var d;s!==t||0!==r&&3!==s.nodeType||(i=o+r),s!==l||0!==n&&3!==s.nodeType||(a=o+n),3===s.nodeType&&(o+=s.nodeValue.length),null!==(d=s.firstChild);)f=s,s=d;for(;;){if(s===e)break t;if(f===t&&++u===r&&(i=o),f===l&&++c===n&&(a=o),null!==(d=s.nextSibling))break;f=(s=f).parentNode}s=d}t=-1===i||-1===a?null:{start:i,end:a}}else t=null}t=t||{start:0,end:0}}else t=null;return{focusedElem:e,selectionRange:t}}(),_n=!1,Li=r;null!==Li;){l=!1;var a=void 0;try{Wi()}catch(c){l=!0,a=c}l&&(null===Li&&i("178"),qi(Li,a),null!==Li&&(Li=Li.nextEffect))}for(Li=r;null!==Li;){l=!1,a=void 0;try{ji()}catch(c){l=!0,a=c}l&&(null===Li&&i("178"),qi(Li,a),null!==Li&&(Li=Li.nextEffect))}for(Dn(yr),yr=null,_n=!!hr,hr=null,e.current=t,Li=r;null!==Li;){l=!1,a=void 0;try{Vi(e,n)}catch(c){l=!0,a=c}l&&(null===Li&&i("178"),qi(Li,a),null!==Li&&(Li=Li.nextEffect))}if(null!==r&&null!==Mi){var u=function(e,t){Fi=Ui=Mi=null;var n=la;la=!0;do{if(512&t.effectTag){var r=!1,l=void 0;try{var o=t;mi(Ll,El,o),mi(El,zl,o)}catch(u){r=!0,l=u}r&&qi(t,l)}t=t.nextEffect}while(null!==t);la=n,0!==(n=e.expirationTime)&&Ta(e,n),sa||la||Pa(1073741823,!1)}.bind(null,e,r);Ui=o.unstable_runWithPriority(o.unstable_NormalPriority,function(){return kr(u)}),Fi=u}Ci=Ii=!1,"function"===typeof Wr&&Wr(t.stateNode),n=t.expirationTime,0===(t=(t=t.childExpirationTime)>n?t:n)&&(Di=null),function(e,t){e.expirationTime=t,e.finishedWork=null}(e,t)}function $i(e){for(;;){var t=e.alternate,n=e.return,r=e.sibling;if(0===(1024&e.effectTag)){Pi=e;e:{var o=t,a=Oi,u=(t=e).pendingProps;switch(t.tag){case 2:case 16:break;case 15:case 0:break;case 1:Ir(t.type)&&Mr();break;case 3:Tl(),Ur(),(u=t.stateNode).pendingContext&&(u.context=u.pendingContext,u.pendingContext=null),null!==o&&null!==o.child||(bo(t),t.effectTag&=-3),ui(t);break;case 5:Sl(t);var c=kl(wl.current);if(a=t.type,null!==o&&null!=t.stateNode)ci(o,t,a,u,c),o.ref!==t.ref&&(t.effectTag|=128);else if(u){var s=kl(gl.current);if(bo(t)){o=(u=t).stateNode;var f=u.type,d=u.memoizedProps,p=c;switch(o[L]=u,o[I]=d,a=void 0,c=f){case"iframe":case"object":Sn("load",o);break;case"video":case"audio":for(f=0;f<te.length;f++)Sn(te[f],o);break;case"source":Sn("error",o);break;case"img":case"image":case"link":Sn("error",o),Sn("load",o);break;case"form":Sn("reset",o),Sn("submit",o);break;case"details":Sn("toggle",o);break;case"input":wt(o,d),Sn("invalid",o),pr(p,"onChange");break;case"select":o._wrapperState={wasMultiple:!!d.multiple},Sn("invalid",o),pr(p,"onChange");break;case"textarea":Gn(o,d),Sn("invalid",o),pr(p,"onChange")}for(a in fr(c,d),f=null,d)d.hasOwnProperty(a)&&(s=d[a],"children"===a?"string"===typeof s?o.textContent!==s&&(f=["children",s]):"number"===typeof s&&o.textContent!==""+s&&(f=["children",""+s]):b.hasOwnProperty(a)&&null!=s&&pr(p,a));switch(c){case"input":Ve(o),Tt(o,d,!0);break;case"textarea":Ve(o),Jn(o);break;case"select":case"option":break;default:"function"===typeof d.onClick&&(o.onclick=mr)}a=f,u.updateQueue=a,(u=null!==a)&&ii(t)}else{d=t,p=a,o=u,f=9===c.nodeType?c:c.ownerDocument,s===Zn.html&&(s=er(p)),s===Zn.html?"script"===p?((o=f.createElement("div")).innerHTML="<script><\/script>",f=o.removeChild(o.firstChild)):"string"===typeof o.is?f=f.createElement(p,{is:o.is}):(f=f.createElement(p),"select"===p&&(p=f,o.multiple?p.multiple=!0:o.size&&(p.size=o.size))):f=f.createElementNS(s,p),(o=f)[L]=d,o[I]=u,ai(o,t,!1,!1),p=o;var m=c,h=dr(f=a,d=u);switch(f){case"iframe":case"object":Sn("load",p),c=d;break;case"video":case"audio":for(c=0;c<te.length;c++)Sn(te[c],p);c=d;break;case"source":Sn("error",p),c=d;break;case"img":case"image":case"link":Sn("error",p),Sn("load",p),c=d;break;case"form":Sn("reset",p),Sn("submit",p),c=d;break;case"details":Sn("toggle",p),c=d;break;case"input":wt(p,d),c=bt(p,d),Sn("invalid",p),pr(m,"onChange");break;case"option":c=Kn(p,d);break;case"select":p._wrapperState={wasMultiple:!!d.multiple},c=l({},d,{value:void 0}),Sn("invalid",p),pr(m,"onChange");break;case"textarea":Gn(p,d),c=Yn(p,d),Sn("invalid",p),pr(m,"onChange");break;default:c=d}fr(f,c),s=void 0;var y=f,v=p,g=c;for(s in g)if(g.hasOwnProperty(s)){var w=g[s];"style"===s?cr(v,w):"dangerouslySetInnerHTML"===s?null!=(w=w?w.__html:void 0)&&lr(v,w):"children"===s?"string"===typeof w?("textarea"!==y||""!==w)&&or(v,w):"number"===typeof w&&or(v,""+w):"suppressContentEditableWarning"!==s&&"suppressHydrationWarning"!==s&&"autoFocus"!==s&&(b.hasOwnProperty(s)?null!=w&&pr(m,s):null!=w&&vt(v,s,w,h))}switch(f){case"input":Ve(p),Tt(p,d,!1);break;case"textarea":Ve(p),Jn(p);break;case"option":null!=d.value&&p.setAttribute("value",""+gt(d.value));break;case"select":(c=p).multiple=!!d.multiple,null!=(p=d.value)?qn(c,!!d.multiple,p,!1):null!=d.defaultValue&&qn(c,!!d.multiple,d.defaultValue,!0);break;default:"function"===typeof c.onClick&&(p.onclick=mr)}(u=vr(a,u))&&ii(t),t.stateNode=o}null!==t.ref&&(t.effectTag|=128)}else null===t.stateNode&&i("166");break;case 6:o&&null!=t.stateNode?si(o,t,o.memoizedProps,u):("string"!==typeof u&&(null===t.stateNode&&i("166")),o=kl(wl.current),kl(gl.current),bo(t)?(a=(u=t).stateNode,o=u.memoizedProps,a[L]=u,(u=a.nodeValue!==o)&&ii(t)):(a=t,(u=(9===o.nodeType?o:o.ownerDocument).createTextNode(u))[L]=t,a.stateNode=u));break;case 11:break;case 13:if(u=t.memoizedState,0!==(64&t.effectTag)){t.expirationTime=a,Pi=t;break e}u=null!==u,a=null!==o&&null!==o.memoizedState,null!==o&&!u&&a&&(null!==(o=o.child.sibling)&&(null!==(c=t.firstEffect)?(t.firstEffect=o,o.nextEffect=c):(t.firstEffect=t.lastEffect=o,o.nextEffect=null),o.effectTag=8)),(u||a)&&(t.effectTag|=4);break;case 7:case 8:case 12:break;case 4:Tl(),ui(t);break;case 10:jo(t);break;case 9:case 14:break;case 17:Ir(t.type)&&Mr();break;case 18:break;default:i("156")}Pi=null}if(t=e,1===Oi||1!==t.childExpirationTime){for(u=0,a=t.child;null!==a;)(o=a.expirationTime)>u&&(u=o),(c=a.childExpirationTime)>u&&(u=c),a=a.sibling;t.childExpirationTime=u}if(null!==Pi)return Pi;null!==n&&0===(1024&n.effectTag)&&(null===n.firstEffect&&(n.firstEffect=e.firstEffect),null!==e.lastEffect&&(null!==n.lastEffect&&(n.lastEffect.nextEffect=e.firstEffect),n.lastEffect=e.lastEffect),1<e.effectTag&&(null!==n.lastEffect?n.lastEffect.nextEffect=e:n.firstEffect=e,n.lastEffect=e))}else{if(null!==(e=Ti(e)))return e.effectTag&=1023,e;null!==n&&(n.firstEffect=n.lastEffect=null,n.effectTag|=1024)}if(null!==r)return r;if(null===n)break;e=n}return null}function Qi(e){var t=Io(e.alternate,e,Oi);return e.memoizedProps=e.pendingProps,null===t&&(t=$i(e)),Si.current=null,t}function Ki(e,t){Ci&&i("243"),Bi(),Ci=!0;var n=_i.current;_i.current=uo;var r=e.nextExpirationTimeToWorkOn;r===Oi&&e===Ni&&null!==Pi||(Ai(),Oi=r,Pi=Kr((Ni=e).current,null),e.pendingCommitExpirationTime=0);for(var l=!1;;){try{if(t)for(;null!==Pi&&!Ea();)Pi=Qi(Pi);else for(;null!==Pi;)Pi=Qi(Pi)}catch(v){if(Do=Fo=Uo=null,Xl(),null===Pi)l=!0,za(v);else{null===Pi&&i("271");var o=Pi,a=o.return;if(null!==a){e:{var u=e,c=a,s=o,f=v;if(a=Oi,s.effectTag|=1024,s.firstEffect=s.lastEffect=null,null!==f&&"object"===typeof f&&"function"===typeof f.then){var d=f;f=c;var p=-1,m=-1;do{if(13===f.tag){var h=f.alternate;if(null!==h&&null!==(h=h.memoizedState)){m=10*(1073741822-h.timedOutAt);break}"number"===typeof(h=f.pendingProps.maxDuration)&&(0>=h?p=0:(-1===p||h<p)&&(p=h))}f=f.return}while(null!==f);f=c;do{if((h=13===f.tag)&&(h=void 0!==f.memoizedProps.fallback&&null===f.memoizedState),h){if(null===(c=f.updateQueue)?((c=new Set).add(d),f.updateQueue=c):c.add(d),0===(1&f.mode)){f.effectTag|=64,s.effectTag&=-1957,1===s.tag&&(null===s.alternate?s.tag=17:((a=Go(1073741823)).tag=$o,Jo(s,a))),s.expirationTime=1073741823;break e}c=a;var y=(s=u).pingCache;null===y?(y=s.pingCache=new wi,h=new Set,y.set(d,h)):void 0===(h=y.get(d))&&(h=new Set,y.set(d,h)),h.has(c)||(h.add(c),s=Gi.bind(null,s,d,c),d.then(s,s)),-1===p?u=1073741823:(-1===m&&(m=10*(1073741822-tl(u,a))-5e3),u=m+p),0<=u&&Ri<u&&(Ri=u),f.effectTag|=2048,f.expirationTime=a;break e}f=f.return}while(null!==f);f=Error((at(s.type)||"A React component")+" suspended while rendering, but no fallback UI was specified.\n\nAdd a <Suspense fallback=...> component higher in the tree to provide a loading indicator or placeholder to display."+ut(s))}zi=!0,f=oi(f,s),u=c;do{switch(u.tag){case 3:u.effectTag|=2048,u.expirationTime=a,Zo(u,a=ki(u,f,a));break e;case 1:if(p=f,m=u.type,s=u.stateNode,0===(64&u.effectTag)&&("function"===typeof m.getDerivedStateFromError||null!==s&&"function"===typeof s.componentDidCatch&&(null===Di||!Di.has(s)))){u.effectTag|=2048,u.expirationTime=a,Zo(u,a=xi(u,p,a));break e}}u=u.return}while(null!==u)}Pi=$i(o);continue}l=!0,za(v)}}break}if(Ci=!1,_i.current=n,Do=Fo=Uo=null,Xl(),l)Ni=null,e.finishedWork=null;else if(null!==Pi)e.finishedWork=null;else{if(null===(n=e.current.alternate)&&i("281"),Ni=null,zi){if(l=e.latestPendingTime,o=e.latestSuspendedTime,a=e.latestPingedTime,0!==l&&l<r||0!==o&&o<r||0!==a&&a<r)return el(e,r),void ka(e,n,r,e.expirationTime,-1);if(!e.didError&&t)return e.didError=!0,r=e.nextExpirationTimeToWorkOn=r,t=e.expirationTime=1073741823,void ka(e,n,r,t,-1)}t&&-1!==Ri?(el(e,r),(t=10*(1073741822-tl(e,r)))<Ri&&(Ri=t),t=10*(1073741822-xa()),t=Ri-t,ka(e,n,r,e.expirationTime,0>t?0:t)):(e.pendingCommitExpirationTime=r,e.finishedWork=n)}}function qi(e,t){for(var n=e.return;null!==n;){switch(n.tag){case 1:var r=n.stateNode;if("function"===typeof n.type.getDerivedStateFromError||"function"===typeof r.componentDidCatch&&(null===Di||!Di.has(r)))return Jo(n,e=xi(n,e=oi(t,e),1073741823)),void Ji(n,1073741823);break;case 3:return Jo(n,e=ki(n,e=oi(t,e),1073741823)),void Ji(n,1073741823)}n=n.return}3===e.tag&&(Jo(e,n=ki(e,n=oi(t,e),1073741823)),Ji(e,1073741823))}function Yi(e,t){var n=o.unstable_getCurrentPriorityLevel(),r=void 0;if(0===(1&t.mode))r=1073741823;else if(Ci&&!Ii)r=Oi;else{switch(n){case o.unstable_ImmediatePriority:r=1073741823;break;case o.unstable_UserBlockingPriority:r=1073741822-10*(1+((1073741822-e+15)/10|0));break;case o.unstable_NormalPriority:r=1073741822-25*(1+((1073741822-e+500)/25|0));break;case o.unstable_LowPriority:case o.unstable_IdlePriority:r=1;break;default:i("313")}null!==Ni&&r===Oi&&--r}return n===o.unstable_UserBlockingPriority&&(0===aa||r<aa)&&(aa=r),r}function Gi(e,t,n){var r=e.pingCache;null!==r&&r.delete(t),null!==Ni&&Oi===n?Ni=null:(t=e.earliestSuspendedTime,r=e.latestSuspendedTime,0!==t&&n<=t&&n>=r&&(e.didError=!1,(0===(t=e.latestPingedTime)||t>n)&&(e.latestPingedTime=n),nl(n,e),0!==(n=e.expirationTime)&&Ta(e,n)))}function Xi(e,t){e.expirationTime<t&&(e.expirationTime=t);var n=e.alternate;null!==n&&n.expirationTime<t&&(n.expirationTime=t);var r=e.return,l=null;if(null===r&&3===e.tag)l=e.stateNode;else for(;null!==r;){if(n=r.alternate,r.childExpirationTime<t&&(r.childExpirationTime=t),null!==n&&n.childExpirationTime<t&&(n.childExpirationTime=t),null===r.return&&3===r.tag){l=r.stateNode;break}r=r.return}return l}function Ji(e,t){null!==(e=Xi(e,t))&&(!Ci&&0!==Oi&&t>Oi&&Ai(),Zr(e,t),Ci&&!Ii&&Ni===e||Ta(e,e.expirationTime),va>ya&&(va=0,i("185")))}function Zi(e,t,n,r,l){return o.unstable_runWithPriority(o.unstable_ImmediatePriority,function(){return e(t,n,r,l)})}var ea=null,ta=null,na=0,ra=void 0,la=!1,oa=null,ia=0,aa=0,ua=!1,ca=null,sa=!1,fa=!1,da=null,pa=o.unstable_now(),ma=1073741822-(pa/10|0),ha=ma,ya=50,va=0,ga=null;function ba(){ma=1073741822-((o.unstable_now()-pa)/10|0)}function wa(e,t){if(0!==na){if(t<na)return;null!==ra&&o.unstable_cancelCallback(ra)}na=t,e=o.unstable_now()-pa,ra=o.unstable_scheduleCallback(Ca,{timeout:10*(1073741822-t)-e})}function ka(e,t,n,r,l){e.expirationTime=r,0!==l||Ea()?0<l&&(e.timeoutHandle=br(function(e,t,n){e.pendingCommitExpirationTime=n,e.finishedWork=t,ba(),ha=ma,Na(e,n)}.bind(null,e,t,n),l)):(e.pendingCommitExpirationTime=n,e.finishedWork=t)}function xa(){return la?ha:(_a(),0!==ia&&1!==ia||(ba(),ha=ma),ha)}function Ta(e,t){null===e.nextScheduledRoot?(e.expirationTime=t,null===ta?(ea=ta=e,e.nextScheduledRoot=e):(ta=ta.nextScheduledRoot=e).nextScheduledRoot=ea):t>e.expirationTime&&(e.expirationTime=t),la||(sa?fa&&(oa=e,ia=1073741823,Oa(e,1073741823,!1)):1073741823===t?Pa(1073741823,!1):wa(e,t))}function _a(){var e=0,t=null;if(null!==ta)for(var n=ta,r=ea;null!==r;){var l=r.expirationTime;if(0===l){if((null===n||null===ta)&&i("244"),r===r.nextScheduledRoot){ea=ta=r.nextScheduledRoot=null;break}if(r===ea)ea=l=r.nextScheduledRoot,ta.nextScheduledRoot=l,r.nextScheduledRoot=null;else{if(r===ta){(ta=n).nextScheduledRoot=ea,r.nextScheduledRoot=null;break}n.nextScheduledRoot=r.nextScheduledRoot,r.nextScheduledRoot=null}r=n.nextScheduledRoot}else{if(l>e&&(e=l,t=r),r===ta)break;if(1073741823===e)break;n=r,r=r.nextScheduledRoot}}oa=t,ia=e}var Sa=!1;function Ea(){return!!Sa||!!o.unstable_shouldYield()&&(Sa=!0)}function Ca(){try{if(!Ea()&&null!==ea){ba();var e=ea;do{var t=e.expirationTime;0!==t&&ma<=t&&(e.nextExpirationTimeToWorkOn=ma),e=e.nextScheduledRoot}while(e!==ea)}Pa(0,!0)}finally{Sa=!1}}function Pa(e,t){if(_a(),t)for(ba(),ha=ma;null!==oa&&0!==ia&&e<=ia&&!(Sa&&ma>ia);)Oa(oa,ia,ma>ia),_a(),ba(),ha=ma;else for(;null!==oa&&0!==ia&&e<=ia;)Oa(oa,ia,!1),_a();if(t&&(na=0,ra=null),0!==ia&&wa(oa,ia),va=0,ga=null,null!==da)for(e=da,da=null,t=0;t<e.length;t++){var n=e[t];try{n._onComplete()}catch(r){ua||(ua=!0,ca=r)}}if(ua)throw e=ca,ca=null,ua=!1,e}function Na(e,t){la&&i("253"),oa=e,ia=t,Oa(e,t,!1),Pa(1073741823,!1)}function Oa(e,t,n){if(la&&i("245"),la=!0,n){var r=e.finishedWork;null!==r?Ra(e,r,t):(e.finishedWork=null,-1!==(r=e.timeoutHandle)&&(e.timeoutHandle=-1,wr(r)),Ki(e,n),null!==(r=e.finishedWork)&&(Ea()?e.finishedWork=r:Ra(e,r,t)))}else null!==(r=e.finishedWork)?Ra(e,r,t):(e.finishedWork=null,-1!==(r=e.timeoutHandle)&&(e.timeoutHandle=-1,wr(r)),Ki(e,n),null!==(r=e.finishedWork)&&Ra(e,r,t));la=!1}function Ra(e,t,n){var r=e.firstBatch;if(null!==r&&r._expirationTime>=n&&(null===da?da=[r]:da.push(r),r._defer))return e.finishedWork=t,void(e.expirationTime=0);e.finishedWork=null,e===ga?va++:(ga=e,va=0),o.unstable_runWithPriority(o.unstable_ImmediatePriority,function(){Hi(e,t)})}function za(e){null===oa&&i("246"),oa.expirationTime=0,ua||(ua=!0,ca=e)}function La(e,t){var n=sa;sa=!0;try{return e(t)}finally{(sa=n)||la||Pa(1073741823,!1)}}function Ia(e,t){if(sa&&!fa){fa=!0;try{return e(t)}finally{fa=!1}}return e(t)}function Ma(e,t,n){sa||la||0===aa||(Pa(aa,!1),aa=0);var r=sa;sa=!0;try{return o.unstable_runWithPriority(o.unstable_UserBlockingPriority,function(){return e(t,n)})}finally{(sa=r)||la||Pa(1073741823,!1)}}function Ua(e,t,n,r,l){var o=t.current;e:if(n){t:{2===tn(n=n._reactInternalFiber)&&1===n.tag||i("170");var a=n;do{switch(a.tag){case 3:a=a.stateNode.context;break t;case 1:if(Ir(a.type)){a=a.stateNode.__reactInternalMemoizedMergedChildContext;break t}}a=a.return}while(null!==a);i("171"),a=void 0}if(1===n.tag){var u=n.type;if(Ir(u)){n=Dr(n,u,a);break e}}n=a}else n=Nr;return null===t.context?t.context=n:t.pendingContext=n,t=l,(l=Go(r)).payload={element:e},null!==(t=void 0===t?null:t)&&(l.callback=t),Bi(),Jo(o,l),Ji(o,r),r}function Fa(e,t,n,r){var l=t.current;return Ua(e,t,n,l=Yi(xa(),l),r)}function Da(e){if(!(e=e.current).child)return null;switch(e.child.tag){case 5:default:return e.child.stateNode}}function Aa(e){var t=1073741822-25*(1+((1073741822-xa()+500)/25|0));t>=Ei&&(t=Ei-1),this._expirationTime=Ei=t,this._root=e,this._callbacks=this._next=null,this._hasChildren=this._didComplete=!1,this._children=null,this._defer=!0}function ja(){this._callbacks=null,this._didCommit=!1,this._onCommit=this._onCommit.bind(this)}function Wa(e,t,n){e={current:t=$r(3,null,null,t?3:0),containerInfo:e,pendingChildren:null,pingCache:null,earliestPendingTime:0,latestPendingTime:0,earliestSuspendedTime:0,latestSuspendedTime:0,latestPingedTime:0,didError:!1,pendingCommitExpirationTime:0,finishedWork:null,timeoutHandle:-1,context:null,pendingContext:null,hydrate:n,nextExpirationTimeToWorkOn:0,expirationTime:0,firstBatch:null,nextScheduledRoot:null},this._internalRoot=t.stateNode=e}function Va(e){return!(!e||1!==e.nodeType&&9!==e.nodeType&&11!==e.nodeType&&(8!==e.nodeType||" react-mount-point-unstable "!==e.nodeValue))}function Ba(e,t,n,r,l){var o=n._reactRootContainer;if(o){if("function"===typeof l){var i=l;l=function(){var e=Da(o._internalRoot);i.call(e)}}null!=e?o.legacy_renderSubtreeIntoContainer(e,t,l):o.render(t,l)}else{if(o=n._reactRootContainer=function(e,t){if(t||(t=!(!(t=e?9===e.nodeType?e.documentElement:e.firstChild:null)||1!==t.nodeType||!t.hasAttribute("data-reactroot"))),!t)for(var n;n=e.lastChild;)e.removeChild(n);return new Wa(e,!1,t)}(n,r),"function"===typeof l){var a=l;l=function(){var e=Da(o._internalRoot);a.call(e)}}Ia(function(){null!=e?o.legacy_renderSubtreeIntoContainer(e,t,l):o.render(t,l)})}return Da(o._internalRoot)}function Ha(e,t){var n=2<arguments.length&&void 0!==arguments[2]?arguments[2]:null;return Va(t)||i("200"),function(e,t,n){var r=3<arguments.length&&void 0!==arguments[3]?arguments[3]:null;return{$$typeof:qe,key:null==r?null:""+r,children:e,containerInfo:t,implementation:n}}(e,t,null,n)}Ee=function(e,t,n){switch(t){case"input":if(xt(e,n),t=n.name,"radio"===n.type&&null!=t){for(n=e;n.parentNode;)n=n.parentNode;for(n=n.querySelectorAll("input[name="+JSON.stringify(""+t)+'][type="radio"]'),t=0;t<n.length;t++){var r=n[t];if(r!==e&&r.form===e.form){var l=D(r);l||i("90"),Be(r),xt(r,l)}}}break;case"textarea":Xn(e,n);break;case"select":null!=(t=n.value)&&qn(e,!!n.multiple,t,!1)}},Aa.prototype.render=function(e){this._defer||i("250"),this._hasChildren=!0,this._children=e;var t=this._root._internalRoot,n=this._expirationTime,r=new ja;return Ua(e,t,null,n,r._onCommit),r},Aa.prototype.then=function(e){if(this._didComplete)e();else{var t=this._callbacks;null===t&&(t=this._callbacks=[]),t.push(e)}},Aa.prototype.commit=function(){var e=this._root._internalRoot,t=e.firstBatch;if(this._defer&&null!==t||i("251"),this._hasChildren){var n=this._expirationTime;if(t!==this){this._hasChildren&&(n=this._expirationTime=t._expirationTime,this.render(this._children));for(var r=null,l=t;l!==this;)r=l,l=l._next;null===r&&i("251"),r._next=l._next,this._next=t,e.firstBatch=this}this._defer=!1,Na(e,n),t=this._next,this._next=null,null!==(t=e.firstBatch=t)&&t._hasChildren&&t.render(t._children)}else this._next=null,this._defer=!1},Aa.prototype._onComplete=function(){if(!this._didComplete){this._didComplete=!0;var e=this._callbacks;if(null!==e)for(var t=0;t<e.length;t++)(0,e[t])()}},ja.prototype.then=function(e){if(this._didCommit)e();else{var t=this._callbacks;null===t&&(t=this._callbacks=[]),t.push(e)}},ja.prototype._onCommit=function(){if(!this._didCommit){this._didCommit=!0;var e=this._callbacks;if(null!==e)for(var t=0;t<e.length;t++){var n=e[t];"function"!==typeof n&&i("191",n),n()}}},Wa.prototype.render=function(e,t){var n=this._internalRoot,r=new ja;return null!==(t=void 0===t?null:t)&&r.then(t),Fa(e,n,null,r._onCommit),r},Wa.prototype.unmount=function(e){var t=this._internalRoot,n=new ja;return null!==(e=void 0===e?null:e)&&n.then(e),Fa(null,t,null,n._onCommit),n},Wa.prototype.legacy_renderSubtreeIntoContainer=function(e,t,n){var r=this._internalRoot,l=new ja;return null!==(n=void 0===n?null:n)&&l.then(n),Fa(t,r,e,l._onCommit),l},Wa.prototype.createBatch=function(){var e=new Aa(this),t=e._expirationTime,n=this._internalRoot,r=n.firstBatch;if(null===r)n.firstBatch=e,e._next=null;else{for(n=null;null!==r&&r._expirationTime>=t;)n=r,r=r._next;e._next=r,null!==n&&(n._next=e)}return e},ze=La,Le=Ma,Ie=function(){la||0===aa||(Pa(aa,!1),aa=0)};var $a={createPortal:Ha,findDOMNode:function(e){if(null==e)return null;if(1===e.nodeType)return e;var t=e._reactInternalFiber;return void 0===t&&("function"===typeof e.render?i("188"):i("268",Object.keys(e))),e=null===(e=rn(t))?null:e.stateNode},hydrate:function(e,t,n){return Va(t)||i("200"),Ba(null,e,t,!0,n)},render:function(e,t,n){return Va(t)||i("200"),Ba(null,e,t,!1,n)},unstable_renderSubtreeIntoContainer:function(e,t,n,r){return Va(n)||i("200"),(null==e||void 0===e._reactInternalFiber)&&i("38"),Ba(e,t,n,!1,r)},unmountComponentAtNode:function(e){return Va(e)||i("40"),!!e._reactRootContainer&&(Ia(function(){Ba(null,null,e,!1,function(){e._reactRootContainer=null})}),!0)},unstable_createPortal:function(){return Ha.apply(void 0,arguments)},unstable_batchedUpdates:La,unstable_interactiveUpdates:Ma,flushSync:function(e,t){la&&i("187");var n=sa;sa=!0;try{return Zi(e,t)}finally{sa=n,Pa(1073741823,!1)}},unstable_createRoot:function(e,t){return Va(e)||i("299","unstable_createRoot"),new Wa(e,!0,null!=t&&!0===t.hydrate)},unstable_flushControlled:function(e){var t=sa;sa=!0;try{Zi(e)}finally{(sa=t)||la||Pa(1073741823,!1)}},__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED:{Events:[U,F,D,N.injectEventPluginsByName,g,H,function(e){E(e,B)},Oe,Re,Pn,R]}};!function(e){var t=e.findFiberByHostInstance;(function(e){if("undefined"===typeof __REACT_DEVTOOLS_GLOBAL_HOOK__)return!1;var t=__REACT_DEVTOOLS_GLOBAL_HOOK__;if(t.isDisabled||!t.supportsFiber)return!0;try{var n=t.inject(e);Wr=Br(function(e){return t.onCommitFiberRoot(n,e)}),Vr=Br(function(e){return t.onCommitFiberUnmount(n,e)})}catch(r){}})(l({},e,{overrideProps:null,currentDispatcherRef:He.ReactCurrentDispatcher,findHostInstanceByFiber:function(e){return null===(e=rn(e))?null:e.stateNode},findFiberByHostInstance:function(e){return t?t(e):null}}))}({findFiberByHostInstance:M,bundleType:0,version:"16.8.6",rendererPackageName:"react-dom"});var Qa={default:$a},Ka=Qa&&$a||Qa;e.exports=Ka.default||Ka},function(e,t,n){"use strict";e.exports=n(13)},function(e,t,n){"use strict";(function(e){Object.defineProperty(t,"__esModule",{value:!0});var n=null,r=!1,l=3,o=-1,i=-1,a=!1,u=!1;function c(){if(!a){var e=n.expirationTime;u?T():u=!0,x(d,e)}}function s(){var e=n,t=n.next;if(n===t)n=null;else{var r=n.previous;n=r.next=t,t.previous=r}e.next=e.previous=null,r=e.callback,t=e.expirationTime,e=e.priorityLevel;var o=l,a=i;l=e,i=t;try{var u=r()}finally{l=o,i=a}if("function"===typeof u)if(u={callback:u,priorityLevel:e,expirationTime:t,next:null,previous:null},null===n)n=u.next=u.previous=u;else{r=null,e=n;do{if(e.expirationTime>=t){r=e;break}e=e.next}while(e!==n);null===r?r=n:r===n&&(n=u,c()),(t=r.previous).next=r.previous=u,u.next=r,u.previous=t}}function f(){if(-1===o&&null!==n&&1===n.priorityLevel){a=!0;try{do{s()}while(null!==n&&1===n.priorityLevel)}finally{a=!1,null!==n?c():u=!1}}}function d(e){a=!0;var l=r;r=e;try{if(e)for(;null!==n;){var o=t.unstable_now();if(!(n.expirationTime<=o))break;do{s()}while(null!==n&&n.expirationTime<=o)}else if(null!==n)do{s()}while(null!==n&&!_())}finally{a=!1,r=l,null!==n?c():u=!1,f()}}var p,m,h=Date,y="function"===typeof setTimeout?setTimeout:void 0,v="function"===typeof clearTimeout?clearTimeout:void 0,g="function"===typeof requestAnimationFrame?requestAnimationFrame:void 0,b="function"===typeof cancelAnimationFrame?cancelAnimationFrame:void 0;function w(e){p=g(function(t){v(m),e(t)}),m=y(function(){b(p),e(t.unstable_now())},100)}if("object"===typeof performance&&"function"===typeof performance.now){var k=performance;t.unstable_now=function(){return k.now()}}else t.unstable_now=function(){return h.now()};var x,T,_,S=null;if("undefined"!==typeof window?S=window:"undefined"!==typeof e&&(S=e),S&&S._schedMock){var E=S._schedMock;x=E[0],T=E[1],_=E[2],t.unstable_now=E[3]}else if("undefined"===typeof window||"function"!==typeof MessageChannel){var C=null,P=function(e){if(null!==C)try{C(e)}finally{C=null}};x=function(e){null!==C?setTimeout(x,0,e):(C=e,setTimeout(P,0,!1))},T=function(){C=null},_=function(){return!1}}else{"undefined"!==typeof console&&("function"!==typeof g&&console.error("This browser doesn't support requestAnimationFrame. Make sure that you load a polyfill in older browsers. https://fb.me/react-polyfills"),"function"!==typeof b&&console.error("This browser doesn't support cancelAnimationFrame. Make sure that you load a polyfill in older browsers. https://fb.me/react-polyfills"));var N=null,O=!1,R=-1,z=!1,L=!1,I=0,M=33,U=33;_=function(){return I<=t.unstable_now()};var F=new MessageChannel,D=F.port2;F.port1.onmessage=function(){O=!1;var e=N,n=R;N=null,R=-1;var r=t.unstable_now(),l=!1;if(0>=I-r){if(!(-1!==n&&n<=r))return z||(z=!0,w(A)),N=e,void(R=n);l=!0}if(null!==e){L=!0;try{e(l)}finally{L=!1}}};var A=function e(t){if(null!==N){w(e);var n=t-I+U;n<U&&M<U?(8>n&&(n=8),U=n<M?M:n):M=n,I=t+U,O||(O=!0,D.postMessage(void 0))}else z=!1};x=function(e,t){N=e,R=t,L||0>t?D.postMessage(void 0):z||(z=!0,w(A))},T=function(){N=null,O=!1,R=-1}}t.unstable_ImmediatePriority=1,t.unstable_UserBlockingPriority=2,t.unstable_NormalPriority=3,t.unstable_IdlePriority=5,t.unstable_LowPriority=4,t.unstable_runWithPriority=function(e,n){switch(e){case 1:case 2:case 3:case 4:case 5:break;default:e=3}var r=l,i=o;l=e,o=t.unstable_now();try{return n()}finally{l=r,o=i,f()}},t.unstable_next=function(e){switch(l){case 1:case 2:case 3:var n=3;break;default:n=l}var r=l,i=o;l=n,o=t.unstable_now();try{return e()}finally{l=r,o=i,f()}},t.unstable_scheduleCallback=function(e,r){var i=-1!==o?o:t.unstable_now();if("object"===typeof r&&null!==r&&"number"===typeof r.timeout)r=i+r.timeout;else switch(l){case 1:r=i+-1;break;case 2:r=i+250;break;case 5:r=i+1073741823;break;case 4:r=i+1e4;break;default:r=i+5e3}if(e={callback:e,priorityLevel:l,expirationTime:r,next:null,previous:null},null===n)n=e.next=e.previous=e,c();else{i=null;var a=n;do{if(a.expirationTime>r){i=a;break}a=a.next}while(a!==n);null===i?i=n:i===n&&(n=e,c()),(r=i.previous).next=i.previous=e,e.next=i,e.previous=r}return e},t.unstable_cancelCallback=function(e){var t=e.next;if(null!==t){if(t===e)n=null;else{e===n&&(n=t);var r=e.previous;r.next=t,t.previous=r}e.next=e.previous=null}},t.unstable_wrapCallback=function(e){var n=l;return function(){var r=l,i=o;l=n,o=t.unstable_now();try{return e.apply(this,arguments)}finally{l=r,o=i,f()}}},t.unstable_getCurrentPriorityLevel=function(){return l},t.unstable_shouldYield=function(){return!r&&(null!==n&&n.expirationTime<i||_())},t.unstable_continueExecution=function(){null!==n&&c()},t.unstable_pauseExecution=function(){},t.unstable_getFirstCallbackNode=function(){return n}}).call(this,n(14))},function(e,t){var n;n=function(){return this}();try{n=n||new Function("return this")()}catch(r){"object"===typeof window&&(n=window)}e.exports=n},,function(e,t,n){var r=function(e){"use strict";var t,n=Object.prototype,r=n.hasOwnProperty,l="function"===typeof Symbol?Symbol:{},o=l.iterator||"@@iterator",i=l.asyncIterator||"@@asyncIterator",a=l.toStringTag||"@@toStringTag";function u(e,t,n,r){var l=t&&t.prototype instanceof h?t:h,o=Object.create(l.prototype),i=new C(r||[]);return o._invoke=function(e,t,n){var r=s;return function(l,o){if(r===d)throw new Error("Generator is already running");if(r===p){if("throw"===l)throw o;return N()}for(n.method=l,n.arg=o;;){var i=n.delegate;if(i){var a=_(i,n);if(a){if(a===m)continue;return a}}if("next"===n.method)n.sent=n._sent=n.arg;else if("throw"===n.method){if(r===s)throw r=p,n.arg;n.dispatchException(n.arg)}else"return"===n.method&&n.abrupt("return",n.arg);r=d;var u=c(e,t,n);if("normal"===u.type){if(r=n.done?p:f,u.arg===m)continue;return{value:u.arg,done:n.done}}"throw"===u.type&&(r=p,n.method="throw",n.arg=u.arg)}}}(e,n,i),o}function c(e,t,n){try{return{type:"normal",arg:e.call(t,n)}}catch(r){return{type:"throw",arg:r}}}e.wrap=u;var s="suspendedStart",f="suspendedYield",d="executing",p="completed",m={};function h(){}function y(){}function v(){}var g={};g[o]=function(){return this};var b=Object.getPrototypeOf,w=b&&b(b(P([])));w&&w!==n&&r.call(w,o)&&(g=w);var k=v.prototype=h.prototype=Object.create(g);function x(e){["next","throw","return"].forEach(function(t){e[t]=function(e){return this._invoke(t,e)}})}function T(e){var t;this._invoke=function(n,l){function o(){return new Promise(function(t,o){!function t(n,l,o,i){var a=c(e[n],e,l);if("throw"!==a.type){var u=a.arg,s=u.value;return s&&"object"===typeof s&&r.call(s,"__await")?Promise.resolve(s.__await).then(function(e){t("next",e,o,i)},function(e){t("throw",e,o,i)}):Promise.resolve(s).then(function(e){u.value=e,o(u)},function(e){return t("throw",e,o,i)})}i(a.arg)}(n,l,t,o)})}return t=t?t.then(o,o):o()}}function _(e,n){var r=e.iterator[n.method];if(r===t){if(n.delegate=null,"throw"===n.method){if(e.iterator.return&&(n.method="return",n.arg=t,_(e,n),"throw"===n.method))return m;n.method="throw",n.arg=new TypeError("The iterator does not provide a 'throw' method")}return m}var l=c(r,e.iterator,n.arg);if("throw"===l.type)return n.method="throw",n.arg=l.arg,n.delegate=null,m;var o=l.arg;return o?o.done?(n[e.resultName]=o.value,n.next=e.nextLoc,"return"!==n.method&&(n.method="next",n.arg=t),n.delegate=null,m):o:(n.method="throw",n.arg=new TypeError("iterator result is not an object"),n.delegate=null,m)}function S(e){var t={tryLoc:e[0]};1 in e&&(t.catchLoc=e[1]),2 in e&&(t.finallyLoc=e[2],t.afterLoc=e[3]),this.tryEntries.push(t)}function E(e){var t=e.completion||{};t.type="normal",delete t.arg,e.completion=t}function C(e){this.tryEntries=[{tryLoc:"root"}],e.forEach(S,this),this.reset(!0)}function P(e){if(e){var n=e[o];if(n)return n.call(e);if("function"===typeof e.next)return e;if(!isNaN(e.length)){var l=-1,i=function n(){for(;++l<e.length;)if(r.call(e,l))return n.value=e[l],n.done=!1,n;return n.value=t,n.done=!0,n};return i.next=i}}return{next:N}}function N(){return{value:t,done:!0}}return y.prototype=k.constructor=v,v.constructor=y,v[a]=y.displayName="GeneratorFunction",e.isGeneratorFunction=function(e){var t="function"===typeof e&&e.constructor;return!!t&&(t===y||"GeneratorFunction"===(t.displayName||t.name))},e.mark=function(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,v):(e.__proto__=v,a in e||(e[a]="GeneratorFunction")),e.prototype=Object.create(k),e},e.awrap=function(e){return{__await:e}},x(T.prototype),T.prototype[i]=function(){return this},e.AsyncIterator=T,e.async=function(t,n,r,l){var o=new T(u(t,n,r,l));return e.isGeneratorFunction(n)?o:o.next().then(function(e){return e.done?e.value:o.next()})},x(k),k[a]="Generator",k[o]=function(){return this},k.toString=function(){return"[object Generator]"},e.keys=function(e){var t=[];for(var n in e)t.push(n);return t.reverse(),function n(){for(;t.length;){var r=t.pop();if(r in e)return n.value=r,n.done=!1,n}return n.done=!0,n}},e.values=P,C.prototype={constructor:C,reset:function(e){if(this.prev=0,this.next=0,this.sent=this._sent=t,this.done=!1,this.delegate=null,this.method="next",this.arg=t,this.tryEntries.forEach(E),!e)for(var n in this)"t"===n.charAt(0)&&r.call(this,n)&&!isNaN(+n.slice(1))&&(this[n]=t)},stop:function(){this.done=!0;var e=this.tryEntries[0].completion;if("throw"===e.type)throw e.arg;return this.rval},dispatchException:function(e){if(this.done)throw e;var n=this;function l(r,l){return a.type="throw",a.arg=e,n.next=r,l&&(n.method="next",n.arg=t),!!l}for(var o=this.tryEntries.length-1;o>=0;--o){var i=this.tryEntries[o],a=i.completion;if("root"===i.tryLoc)return l("end");if(i.tryLoc<=this.prev){var u=r.call(i,"catchLoc"),c=r.call(i,"finallyLoc");if(u&&c){if(this.prev<i.catchLoc)return l(i.catchLoc,!0);if(this.prev<i.finallyLoc)return l(i.finallyLoc)}else if(u){if(this.prev<i.catchLoc)return l(i.catchLoc,!0)}else{if(!c)throw new Error("try statement without catch or finally");if(this.prev<i.finallyLoc)return l(i.finallyLoc)}}}},abrupt:function(e,t){for(var n=this.tryEntries.length-1;n>=0;--n){var l=this.tryEntries[n];if(l.tryLoc<=this.prev&&r.call(l,"finallyLoc")&&this.prev<l.finallyLoc){var o=l;break}}o&&("break"===e||"continue"===e)&&o.tryLoc<=t&&t<=o.finallyLoc&&(o=null);var i=o?o.completion:{};return i.type=e,i.arg=t,o?(this.method="next",this.next=o.finallyLoc,m):this.complete(i)},complete:function(e,t){if("throw"===e.type)throw e.arg;return"break"===e.type||"continue"===e.type?this.next=e.arg:"return"===e.type?(this.rval=this.arg=e.arg,this.method="return",this.next="end"):"normal"===e.type&&t&&(this.next=t),m},finish:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var n=this.tryEntries[t];if(n.finallyLoc===e)return this.complete(n.completion,n.afterLoc),E(n),m}},catch:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var n=this.tryEntries[t];if(n.tryLoc===e){var r=n.completion;if("throw"===r.type){var l=r.arg;E(n)}return l}}throw new Error("illegal catch attempt")},delegateYield:function(e,n,r){return this.delegate={iterator:P(e),resultName:n,nextLoc:r},"next"===this.method&&(this.arg=t),m}},e}(e.exports);try{regeneratorRuntime=r}catch(l){Function("r","regeneratorRuntime = r")(r)}}]]);
//# sourceMappingURL=2.0bd444a1.chunk.js.map |
const { getRedis } = require("../redisdb");
const mkdirp = require("mkdirp");
const fs = require("fs");
const path = require("path");
const inter = require("../interserver/inter").router;
const buyAi = require("./ai/buypredictor");
// Frees the room in the master database.
inter.post("/delrooms", (req, res) => {
const cl = getRedis();
// Active rooms in the other server
const otherRooms = req.body;
console.log(req.body);
for (const room of otherRooms) {
cl.lrem("rml", 1, room);
cl.del(room);
}
res.sendStatus(200);
});
inter.post("/aibuydata", (req, res) => {
// Create instance file to store all the AI stuff
mkdirp(path.dirname(buyAi.aiBuyPath), () => {
fs.writeFile(
buyAi.aiBuyPath,
buyAi.aiBuyBase,
{ flag: "wx" },
function (err) {
if (err) return;
console.log("Buy AI file created!");
}
);
// Append to AI file
fs.appendFile(buyAi.aiBuyPath, req.body.data, () => {
console.log(
`Successfully appended AI buy data from worker (${req.header(
"Worker-Name"
)})`
);
res.sendStatus(200);
});
});
});
module.exports = inter;
|
var ViewModelVisitasDetalle = function () {
var self = this;
self.visitasDetalle = ko.observableArray();
self.ProyectosUbicaciones = ko.observableArray();
self.error = ko.observable();
self.visitaDetail = ko.observable();
self.imagenR = ko.observable();
self.Latitud = ko.observableArray();
self.Longitud = ko.observableArray();
self.selectedProject = ko.observable();
self.vencimiento = ko.observableArray();
self.selectedVencimiento = ko.observable();
var host = '200.6.245.76:8095';//document.location.host;
////http://192.168.16.13:8095/api/DetalleVisitas?CodigoVisita=9
var visitasUri = 'http://'.concat(host, '/api/Publicidad/ZonasMapa');
var ProyectosUbicacionesUri = 'http://'.concat(host, '/api/Publicidad/ProyectosZonasMapa');
var VistaSuperversionUri = 'http://'.concat(host, '/api/Visitas/VistaContratos?codigozona=');
var VistaSuperversionDetalleUri = 'http://'.concat(host, '/api/Visitas/ContratoDetalle');
var VistamapaContrato = 'http://'.concat(host, '/api/Visitas/VistaContratos'); //'Visitas/VistaContratos?codigozona=8'
function ajaxHelper(uri, method, data) {
self.error(''); // Borra mensaje de error
return $.ajax({
type: method,
url: uri,
dataType: 'json',
contentType: 'application/json',
data: data ? JSON.stringify(data) : null
}).fail(function (jqXHR, textStatus, errorThrown) {
self.error(errorThrown);
console.log(errorThrown);
});
}
// Get Data
function getAllVisitas(codigozona, VencimientoTarea) {
ajaxHelper(VistaSuperversionDetalleUri + '?codZona=' + codigozona + '&vencimientoContrato=' + VencimientoTarea, 'GET').done(function (data) {
//alert("Visita" + VistaSuperversionDetalleUri + '?codigozona=' + VencimientoTarea + '&vencimientoTarea=' + codigozona);
self.visitasDetalle(data);
var map = new google.maps.Map(document.getElementById('map'), {
center: { lat: parseFloat(self.visitasDetalle()[0].Latitud), lng: parseFloat(self.visitasDetalle()[0].Longitud) },
scrollwheel: false,
zoom: 10
});
for (i = 0; i < self.visitasDetalle().length; i++) {
//alert(self.visitasDetalle()[i].EstadoContrato);
if (self.visitasDetalle()[i].EstadoContrato == 'ACTIVO') {
var marker = new google.maps.Marker({
position: { lat: parseFloat(self.visitasDetalle()[i].Latitud), lng: parseFloat(self.visitasDetalle()[i].Longitud) },
map: map,
//icon: "/Content/AdminLTE/img/Location-32.png",
//icon: "/Content/AdminLTE/img/Location_delete-32.png",
icon: "/Content/AdminLTE/img/GEOACTIVO.png",
title: self.visitasDetalle()[i].DescripcionPublicidad
});
}
if (self.visitasDetalle()[i].EstadoContrato == 'POR VENCER') {
var marker = new google.maps.Marker({
position: { lat: parseFloat(self.visitasDetalle()[i].Latitud), lng: parseFloat(self.visitasDetalle()[i].Longitud) },
map: map,
icon: "/Content/AdminLTE/img/GEOPORVENCER.png",
//icon: "/Content/AdminLTE/img/Location_delete-32.png",
//icon: "/Content/AdminLTE/img/OK-32.png",
title: self.visitasDetalle()[i].DescripcionPublicidad
});
}
if (self.visitasDetalle()[i].EstadoContrato == 'VENCIDO') {
var marker = new google.maps.Marker({
position: { lat: parseFloat(self.visitasDetalle()[i].Latitud), lng: parseFloat(self.visitasDetalle()[i].Longitud) },
map: map,
//icon: "/Content/AdminLTE/img/Location-32.png",
icon: "/Content/AdminLTE/img/GEOVENCIDO.png",
//icon: "/Content/AdminLTE/img/OK-32.png",
title: self.visitasDetalle()[i].DescripcionPublicidad
});
}
}
});
}
// End Get Data
///self.contratos el objeto del grid
function getAllProyectosUbicaciones(item) {
//ajaxHelper(ContratoPagosUri + '?codigoContrato=' + item.CodigoContrato, 'GET').done(function (data) {
ajaxHelper(ProyectosUbicacionesUri, 'GET').done(function (data) {
self.ProyectosUbicaciones(data);
});
}
///evento Zona_id combobox
self.selectedProject.subscribe(function (data) {
//alert(ko.toJSON({ selectedProject: self.selectedProject() }));
//alert(self.selectedProject())
getVencimiento(self.selectedProject());
});
self.selectedVencimiento.subscribe(function (data) {
//alert(ko.toJSON({ selectedProject: self.selectedProject() }));
//alert(self.selectedProject());
//alert(self.selectedVencimiento());
////getVencimiento(self.selectedProject());
getAllVisitas(self.selectedProject(), self.selectedVencimiento());
});
function getVencimiento(item) {
ajaxHelper(VistaSuperversionUri + item, 'GET').done(function (data) {
// alert(VistaSuperversionUri + item);
self.vencimiento(data);
});
}
// Recuperar datos iniciales
//getAllVisitas();
getAllProyectosUbicaciones();
};
ko.applyBindings(new ViewModelVisitasDetalle()); |
var mylist;
$(function() {
}); |
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
const experimental_utils_1 = require("@typescript-eslint/experimental-utils");
const util = __importStar(require("../util"));
exports.default = util.createRule({
name: 'prefer-readonly-parameter-types',
meta: {
type: 'suggestion',
docs: {
description: 'Requires that function parameters are typed as readonly to prevent accidental mutation of inputs',
category: 'Possible Errors',
recommended: false,
requiresTypeChecking: true,
},
schema: [
{
type: 'object',
additionalProperties: false,
properties: Object.assign({ checkParameterProperties: {
type: 'boolean',
}, ignoreInferredTypes: {
type: 'boolean',
} }, util.readonlynessOptionsSchema.properties),
},
],
messages: {
shouldBeReadonly: 'Parameter should be a read only type.',
},
},
defaultOptions: [
Object.assign({ checkParameterProperties: true, ignoreInferredTypes: false }, util.readonlynessOptionsDefaults),
],
create(context, options) {
const [{ checkParameterProperties, ignoreInferredTypes, treatMethodsAsReadonly },] = options;
const { esTreeNodeToTSNodeMap, program } = util.getParserServices(context);
const checker = program.getTypeChecker();
return {
[[
experimental_utils_1.AST_NODE_TYPES.ArrowFunctionExpression,
experimental_utils_1.AST_NODE_TYPES.FunctionDeclaration,
experimental_utils_1.AST_NODE_TYPES.FunctionExpression,
experimental_utils_1.AST_NODE_TYPES.TSCallSignatureDeclaration,
experimental_utils_1.AST_NODE_TYPES.TSConstructSignatureDeclaration,
experimental_utils_1.AST_NODE_TYPES.TSDeclareFunction,
experimental_utils_1.AST_NODE_TYPES.TSEmptyBodyFunctionExpression,
experimental_utils_1.AST_NODE_TYPES.TSFunctionType,
experimental_utils_1.AST_NODE_TYPES.TSMethodSignature,
].join(', ')](node) {
for (const param of node.params) {
if (!checkParameterProperties &&
param.type === experimental_utils_1.AST_NODE_TYPES.TSParameterProperty) {
continue;
}
const actualParam = param.type === experimental_utils_1.AST_NODE_TYPES.TSParameterProperty
? param.parameter
: param;
if (ignoreInferredTypes && actualParam.typeAnnotation == null) {
continue;
}
const tsNode = esTreeNodeToTSNodeMap.get(actualParam);
const type = checker.getTypeAtLocation(tsNode);
const isReadOnly = util.isTypeReadonly(checker, type, {
treatMethodsAsReadonly: treatMethodsAsReadonly,
});
if (!isReadOnly) {
context.report({
node: actualParam,
messageId: 'shouldBeReadonly',
});
}
}
},
};
},
});
//# sourceMappingURL=prefer-readonly-parameter-types.js.map |
/**
* Copyright 2012-2022, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
'use strict';
var hovertemplateAttrs = require('../../plots/template_attributes').hovertemplateAttrs;
var texttemplateAttrs = require('../../plots/template_attributes').texttemplateAttrs;
var scatterAttrs = require('../scatter/attributes');
var baseAttrs = require('../../plots/attributes');
var colorScaleAttrs = require('../../components/colorscale/attributes');
var dash = require('../../components/drawing/attributes').dash;
var extendFlat = require('../../lib/extend').extendFlat;
var scatterMarkerAttrs = scatterAttrs.marker;
var scatterLineAttrs = scatterAttrs.line;
var scatterMarkerLineAttrs = scatterMarkerAttrs.line;
module.exports = {
a: {
valType: 'data_array',
editType: 'calc',
description: [
'Sets the quantity of component `a` in each data point.',
'If `a`, `b`, and `c` are all provided, they need not be',
'normalized, only the relative values matter. If only two',
'arrays are provided they must be normalized to match',
'`ternary<i>.sum`.'
].join(' ')
},
b: {
valType: 'data_array',
editType: 'calc',
description: [
'Sets the quantity of component `a` in each data point.',
'If `a`, `b`, and `c` are all provided, they need not be',
'normalized, only the relative values matter. If only two',
'arrays are provided they must be normalized to match',
'`ternary<i>.sum`.'
].join(' ')
},
c: {
valType: 'data_array',
editType: 'calc',
description: [
'Sets the quantity of component `a` in each data point.',
'If `a`, `b`, and `c` are all provided, they need not be',
'normalized, only the relative values matter. If only two',
'arrays are provided they must be normalized to match',
'`ternary<i>.sum`.'
].join(' ')
},
sum: {
valType: 'number',
role: 'info',
dflt: 0,
min: 0,
editType: 'calc',
description: [
'The number each triplet should sum to,',
'if only two of `a`, `b`, and `c` are provided.',
'This overrides `ternary<i>.sum` to normalize this specific',
'trace, but does not affect the values displayed on the axes.',
'0 (or missing) means to use ternary<i>.sum'
].join(' ')
},
mode: extendFlat({}, scatterAttrs.mode, {dflt: 'markers'}),
text: extendFlat({}, scatterAttrs.text, {
description: [
'Sets text elements associated with each (a,b,c) point.',
'If a single string, the same string appears over',
'all the data points.',
'If an array of strings, the items are mapped in order to the',
'the data points in (a,b,c).',
'If trace `hoverinfo` contains a *text* flag and *hovertext* is not set,',
'these elements will be seen in the hover labels.'
].join(' ')
}),
texttemplate: texttemplateAttrs({editType: 'plot'}, {
keys: ['a', 'b', 'c', 'text']
}),
hovertext: extendFlat({}, scatterAttrs.hovertext, {
description: [
'Sets hover text elements associated with each (a,b,c) point.',
'If a single string, the same string appears over',
'all the data points.',
'If an array of strings, the items are mapped in order to the',
'the data points in (a,b,c).',
'To be seen, trace `hoverinfo` must contain a *text* flag.'
].join(' ')
}),
line: {
color: scatterLineAttrs.color,
width: scatterLineAttrs.width,
dash: dash,
shape: extendFlat({}, scatterLineAttrs.shape,
{values: ['linear', 'spline']}),
smoothing: scatterLineAttrs.smoothing,
editType: 'calc'
},
connectgaps: scatterAttrs.connectgaps,
cliponaxis: scatterAttrs.cliponaxis,
fill: extendFlat({}, scatterAttrs.fill, {
values: ['none', 'toself', 'tonext'],
dflt: 'none',
description: [
'Sets the area to fill with a solid color.',
'Use with `fillcolor` if not *none*.',
'scatterternary has a subset of the options available to scatter.',
'*toself* connects the endpoints of the trace (or each segment',
'of the trace if it has gaps) into a closed shape.',
'*tonext* fills the space between two traces if one completely',
'encloses the other (eg consecutive contour lines), and behaves like',
'*toself* if there is no trace before it. *tonext* should not be',
'used if one trace does not enclose the other.'
].join(' ')
}),
fillcolor: scatterAttrs.fillcolor,
marker: extendFlat({
symbol: scatterMarkerAttrs.symbol,
opacity: scatterMarkerAttrs.opacity,
maxdisplayed: scatterMarkerAttrs.maxdisplayed,
size: scatterMarkerAttrs.size,
sizeref: scatterMarkerAttrs.sizeref,
sizemin: scatterMarkerAttrs.sizemin,
sizemode: scatterMarkerAttrs.sizemode,
line: extendFlat({
width: scatterMarkerLineAttrs.width,
editType: 'calc'
},
colorScaleAttrs('marker.line')
),
gradient: scatterMarkerAttrs.gradient,
editType: 'calc'
},
colorScaleAttrs('marker')
),
textfont: scatterAttrs.textfont,
textposition: scatterAttrs.textposition,
selected: scatterAttrs.selected,
unselected: scatterAttrs.unselected,
hoverinfo: extendFlat({}, baseAttrs.hoverinfo, {
flags: ['a', 'b', 'c', 'text', 'name']
}),
hoveron: scatterAttrs.hoveron,
hovertemplate: hovertemplateAttrs(),
};
|
import copy
from synapse_pay_rest.client import Client
class PublicKey():
"""Represents a Public Key record with methods for constructing Public key
instances.
"""
def __init__(self, **kwargs):
for arg, value in kwargs.items():
setattr(self, arg, value)
def __repr__(self):
clean_dict = self.__dict__.copy()
return '{0}({1})'.format(self.__class__, clean_dict)
@classmethod
def from_response(cls, client, response):
"""Construct a Public Key from a response dict."""
return cls(
client = client,
json=response,
client_obj_id=response['public_key_obj']['client_obj_id'],
expires_at=response['public_key_obj']['expires_at'],
expires_in=response['public_key_obj']['expires_in'],
public_key=response['public_key_obj']['public_key'],
scope=response['public_key_obj']['scope']
)
@classmethod
def issue(cls,client=None, scope=None):
"""Issues a public key record and create a Public Key instance from it.
Args:
client (Client): an instance of the API Client
scope (string): scope of the subscription
Returns:
Public Key: a PublicKey instance corresponding to the record
"""
if scope is None:
scope = "OAUTH|POST,USERS|POST,USERS|GET,USER|GET,USER|PATCH,SUBSCRIPTIONS|GET,SUBSCRIPTIONS|POST,SUBSCRIPTION|GET,SUBSCRIPTION|PATCH,CLIENT|REPORTS,CLIENT|CONTROLS"
response = client.client_endpoint.issue_public_key(scope)
return cls.from_response(client, response)
|
import { Table } from './table'
import { chart } from './chart'
function main () {
if (document.getElementById('thetable')) {
window.table = new Table()
window.table.load(document)
}
if (document.getElementById('the_graph')) {
chart.setup_page()
}
}
main()
|
import pathlib
import pkg_resources
from clvm_tools.clvmc import compile_clvm
from shamrock.types.blockchain_format.program import Program, SerializedProgram
def load_serialized_clvm(clvm_filename, package_or_requirement=__name__) -> SerializedProgram:
"""
This function takes a .clvm file in the given package and compiles it to a
.clvm.hex file if the .hex file is missing or older than the .clvm file, then
returns the contents of the .hex file as a `Program`.
clvm_filename: file name
package_or_requirement: usually `__name__` if the clvm file is in the same package
"""
hex_filename = f"{clvm_filename}.hex"
try:
if pkg_resources.resource_exists(package_or_requirement, clvm_filename):
full_path = pathlib.Path(pkg_resources.resource_filename(package_or_requirement, clvm_filename))
output = full_path.parent / hex_filename
compile_clvm(full_path, output, search_paths=[full_path.parent])
except NotImplementedError:
# pyinstaller doesn't support `pkg_resources.resource_exists`
# so we just fall through to loading the hex clvm
pass
clvm_hex = pkg_resources.resource_string(package_or_requirement, hex_filename).decode("utf8")
clvm_blob = bytes.fromhex(clvm_hex)
return SerializedProgram.from_bytes(clvm_blob)
def load_clvm(clvm_filename, package_or_requirement=__name__) -> Program:
return Program.from_bytes(bytes(load_serialized_clvm(clvm_filename, package_or_requirement=__name__)))
|
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const tslib_1 = require("tslib");
const React = tslib_1.__importStar(require("react"));
const popover_1 = tslib_1.__importDefault(require("@patternfly/react-styles/css/components/Popover/popover"));
const react_styles_1 = require("@patternfly/react-styles");
exports.PopoverBody = (_a) => {
var { children, id } = _a, props = tslib_1.__rest(_a, ["children", "id"]);
return (React.createElement("div", Object.assign({ className: react_styles_1.css(popover_1.default.popoverBody), id: id }, props), children));
};
//# sourceMappingURL=PopoverBody.js.map |
module.exports = {
siteMetadata: {
title: `주니어 개발자의 개발 블로그`,
description: `주니어 개발자로서의 저를 표현한 블로그입니다.`,
author: `HyungjunJeon`,
siteUrl: `https://my-website-link.com/`,
},
plugins: [
{
resolve: 'gatsby-plugin-typescript',
options: {
isTSX: true,
allExtensions: true,
},
},
`gatsby-plugin-emotion`,
`gatsby-plugin-react-helmet`,
{
resolve: `gatsby-source-filesystem`,
options: {
name: `contents`,
path: `${__dirname}/contents`,
},
},
{
resolve: `gatsby-source-filesystem`,
options: {
name: `images`,
path: `${__dirname}/static`,
},
},
{
resolve: `gatsby-plugin-sharp`,
options: {
default: {
formats: ['auto', 'webp'],
quality: 100,
placeholder: 'blurred',
},
},
},
`gatsby-transformer-sharp`,
`gatsby-plugin-sharp`,
{
resolve: `gatsby-transformer-remark`,
options: {
plugins: [
{
resolve: 'gatsby-remark-smartypants',
options: {
dashes: 'oldschool',
},
},
{
resolve: 'gatsby-remark-prismjs',
options: {
classPrefix: 'language-',
},
},
{
resolve: 'gatsby-remark-images',
options: {
maxWidth: 768,
quality: 100,
withWebp: true,
},
},
{
resolve: 'gatsby-remark-copy-linked-files',
options: {},
},
{
resolve: 'gatsby-remark-external-links',
options: {
target: '_blank',
rel: 'nofollow',
},
},
{
resolve: 'gatsby-plugin-canonical-urls',
options: {
siteUrl: 'https://my-website.com/',
stripQueryString: true,
},
},
'gatsby-plugin-sitemap',
],
},
},
],
}
|
import os
import glob
import cv2
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser(
description="Resize raw images to uniformed target size."
)
parser.add_argument(
"--raw-dir",
help="Directory path to raw images.",
default="./data/raw",
type=str,
)
parser.add_argument(
"--save-dir",
help="Directory path to save resized images.",
default="./data/images",
type=str,
)
parser.add_argument(
"--ext", help="Raw image files extension to resize.", default="jpg", type=str
)
parser.add_argument(
"--target-size",
help="Target size to resize as a tuple of 2 integers.",
default="(600, 800)",
type=str,
)
args = parser.parse_args()
raw_dir = args.raw_dir
save_dir = args.save_dir
ext = args.ext
target_size = eval(args.target_size)
msg = "--target-size must be a tuple of 2 integers"
assert isinstance(target_size, tuple) and len(target_size) == 2, msg
fnames = glob.glob(os.path.join(raw_dir, "*.{}".format(ext)))
os.makedirs(save_dir, exist_ok=True)
print(
"{} files to resize from directory `{}` to target size:{}".format(
len(fnames), raw_dir, target_size
)
)
for i, fname in enumerate(fnames):
print(".", end="", flush=True)
img = cv2.imread(fname)
img_small = cv2.resize(img, target_size)
new_fname = "{}.{}".format(str(i+154), ext)
small_fname = os.path.join(save_dir, new_fname)
cv2.imwrite(small_fname, img_small)
print(
"\nDone resizing {} files.\nSaved to directory: `{}`".format(
len(fnames), save_dir
)
)
|
from rlf.policies.base_policy import BasePolicy, create_simple_action_data
import numpy as np
import torch
from abc import ABC, abstractmethod
from collections import defaultdict
class SolvePolicy(BasePolicy, ABC):
"""
Plan all actions ahead of time based on the starting state. This can be
useful for classical planning algorithms such as path planning algorithms.
"""
def __init__(self):
super().__init__()
self.is_first = True
def init(self, obs_space, action_space, args):
super().init(obs_space, action_space, args)
self.all_actions = defaultdict(list)
self.ep_idx = defaultdict(lambda: 0)
@abstractmethod
def _solve_env(self, state):
pass
def get_action(self, state, hxs, masks, step_info):
if self.is_first:
masks = torch.zeros(masks.shape)
sel_actions = []
for i, mask in enumerate(masks):
if mask == 0.0:
if len(self.all_actions[i]) != 0:
# We should have exhaused all of the actions
assert self.ep_idx[i] == len(self.all_actions[i]) - 1
# The env has reset, solve it.
actions = self._solve_env(state[i])
self.all_actions[i] = actions
self.ep_idx[i] = 0
else:
self.ep_idx[i] += 1
sel_actions.append(self.all_actions[i][self.ep_idx[i]])
sel_actions = torch.tensor(sel_actions).unsqueeze(-1)
self.is_first = False
return create_simple_action_data(sel_actions)
|
# --------------------------------------------------------
# Tensorflow ATL
# --------------------------------------------------------
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import _init_paths
import tensorflow as tf
import numpy as np
import argparse
import pickle
import json
import ipdb
from ult.vsrl_eval2 import VCOCOeval
from ult.config import cfg
from models.test_VCOCO import test_net, obtain_data, test_net_data_api_24
def parse_args():
parser = argparse.ArgumentParser(description='Test an iCAN on VCOCO')
parser.add_argument('--num_iteration', dest='iteration',
help='Specify which weight to load',
default=300000, type=int)
parser.add_argument('--model', dest='model',
help='Select model',
default='ATL_union_multi_atl_ml5_l05_t5_def2_aug5_new_VCOCO_coco_CL_24', type=str)
parser.add_argument('--prior_flag', dest='prior_flag',
help='whether use prior_flag',
default=3, type=int)
parser.add_argument('--object_thres', dest='object_thres',
help='Object threshold',
default=0.4, type=float)
parser.add_argument('--human_thres', dest='human_thres',
help='Human threshold',
default=0.8, type=float)
args = parser.parse_args()
return args
# apply_prior prior_mask
# 0 - -
# 1 Y -
# 2 - Y
# 3 Y Y
if __name__ == '__main__':
args = parse_args()
Test_RCNN = pickle.load(open(cfg.DATA_DIR + '/' + 'Test_Faster_RCNN_R-50-PFN_2x_VCOCO_with_pose.pkl', "rb"),
encoding='latin1')
prior_mask = pickle.load(open(cfg.DATA_DIR + '/' + 'prior_mask.pkl', "rb"), encoding='latin1')
Action_dic = json.load(open(cfg.DATA_DIR + '/' + 'action_index.json'))
Action_dic_inv = {y: x for x, y in Action_dic.items()}
weight = cfg.LOCAL_DATA0 + '/Weights/' + args.model + '/HOI_iter_' + str(args.iteration) + '.ckpt'
print('Human thres = ' + str(args.human_thres) + ', Object thres = ' + str(args.object_thres) + ', iter = ' + str(
args.iteration) + ', path = ' + weight)
output_file = cfg.LOCAL_DATA + '/Results/' + str(args.iteration) + '_' + args.model + '.pkl'
tfconfig = tf.ConfigProto(device_count={"CPU": 8},
inter_op_parallelism_threads=4,
intra_op_parallelism_threads=4,
allow_soft_placement=True)
# init session
# tfconfig = tf.ConfigProto(allow_soft_placement=True)
tfconfig.gpu_options.per_process_gpu_memory_fraction = 0.2
# tfconfig.gpu_options.allow_growth = True
sess = tf.Session(config=tfconfig)
# if args.model == 'iCAN_ResNet50_VCOCO':
# from networks.iCAN_ResNet50_VCOCO import ResNet50
# net = ResNet50(args.model)
# elif args.model == 'iCAN_ResNet50_VCOCO_Early':
# from networks.iCAN_ResNet50_VCOCO_Early import ResNet50
# net = ResNet50(args.model)
# else:
iCAN_Early_flag = 0
import os
os.environ['DATASET'] = 'VCOCO1'
from networks.HOI import HOI
net = HOI(args.model)
print('Pre-trained weights loaded.')
# net = DisentanglingNet(model_name=args.model)
image, blobs, image_id = obtain_data(Test_RCNN, prior_mask, Action_dic_inv, output_file, args.object_thres,
args.human_thres, args.prior_flag)
print('blobs:', blobs)
print(image)
net.set_ph(image, image_id, H_num=blobs['H_num'], spatial=blobs['sp'], H_boxes=blobs['H_boxes'],
O_boxes=blobs['O_boxes'],
gt_cls_H=None,
gt_cls_HO=None, gt_cls_sp=None, Mask_HO=None, Mask_H=None, Mask_sp=None, gt_compose = None)
net.create_architecture(False)
saver = tf.train.Saver()
print(weight)
saver.restore(sess, weight)
print('Pre-trained weights loaded.')
test_net_data_api_24(sess, net, Test_RCNN, prior_mask, Action_dic_inv, output_file,
args.object_thres, args.human_thres, args.prior_flag, blobs, image_id, image)
sess.close()
vcocoeval = VCOCOeval(cfg.DATA_DIR + '/' + 'v-coco/data/vcoco/vcoco_test.json',
cfg.DATA_DIR + '/' + 'v-coco/data/instances_vcoco_all_2014.json',
cfg.DATA_DIR + '/' + 'v-coco/data/splits/vcoco_test.ids')
vcocoeval._do_eval(output_file, ovr_thresh=0.5)
os.remove(output_file)
|
module.exports = {
mongoURI: process.env.KF_MONGO_URI,
secretOrKey: 'secret',
port: process.env.KF_PORT || 5000,
testMongoURL: 'mongodb://lovely-aip:[email protected]:20208/lovely-aip-test',
testPort: 5001,
email: process.env.KF_EMAIL,
emailPwd: process.env.KF_EMAIL_PWD,
emailServiceProvider: process.env.KF_EMAIL_SERVICE_PROVIDER,
frontendHost: process.env.NODE_ENV === 'production'
? 'http://knight-frank-web.s3-website-ap-southeast-2.amazonaws.com' : 'http://localhost:3000',
backendHost: process.env.NODE_ENV === 'production'
? 'http://lovelyaip-env.wsr3nv3er9.ap-southeast-2.elasticbeanstalk.com' : `localhost:${process.env.PORT || 5000}`,
redisURI: process.env.KF_REDIS_URI,
redisPort: process.env.KF_REDIS_PORT,
redisPwd: process.env.KF_REDIS_PWD,
};
|
import os
import re
import html
import json
import itertools
from lxml import etree
from txt2json import Txt2JSON
from media_operations import MediaCutter
EAF_TIME_MULTIPLIER = 1000 # time stamps are in milliseconds
class Eaf2JSON(Txt2JSON):
"""
Contains methods to make JSONs ready for indexing from
ELAN aligned files, a csv with metadata and a list with parsed
word forms.
"""
mediaExtensions = {'.wav', '.mp3', '.mp4', '.avi'}
rxSpaces = re.compile('[ \t]+')
rxLetters = re.compile('\w+')
def __init__(self, settingsDir='conf'):
Txt2JSON.__init__(self, settingsDir=settingsDir)
self.speakerMeta = self.load_speaker_meta()
self.mc = MediaCutter(settings=self.corpusSettings)
self.srcExt = 'eaf'
self.tlis = {} # time labels
self.pID = 0 # id of last aligned segment
self.glosses = set()
self.participants = {} # main tier ID -> participant ID
self.segmentTree = {} # aID -> (contents, parent aID, tli1, tli2)
self.segmentChildren = {} # (aID, child tier type) -> [child aID]
def load_speaker_meta(self):
speakerMeta = {}
if 'speaker_meta_filename' not in self.corpusSettings:
return speakerMeta
try:
f = open(os.path.join('..', self.corpusSettings['speaker_meta_filename']),
'r', encoding='utf-8-sig')
speakerMeta = json.loads(f.read())
f.close()
except FileNotFoundError:
print('The speaker metadata file not found.')
return speakerMeta
def get_tlis(self, srcTree):
"""
Retrieve and return all time labels from the XML tree.
"""
tlis = {}
iTli = 0
for tli in srcTree.xpath('/ANNOTATION_DOCUMENT/TIME_ORDER/TIME_SLOT'):
timeValue = ''
if 'TIME_VALUE' in tli.attrib:
timeValue = tli.attrib['TIME_VALUE']
tlis[tli.attrib['TIME_SLOT_ID']] = {'n': iTli, 'time': timeValue}
iTli += 1
return tlis
def traverse_tree(self, srcTree, callback):
"""
Iterate over all tiers in the XML tree and call the callback function
for each of them.
"""
for tierNode in srcTree.xpath('/ANNOTATION_DOCUMENT/TIER'):
if 'TIER_ID' not in tierNode.attrib:
continue
callback(tierNode)
def cb_build_segment_tree(self, tierNode):
tierType = '' # analysis tiers: word/POS/gramm/gloss etc.
if 'analysis_tiers' in self.corpusSettings:
for k, v in self.corpusSettings['analysis_tiers'].items():
if not k.startswith('^'):
k = '^' + k
if not k.endswith('$'):
k += '$'
try:
rxTierID = re.compile(k)
if (rxTierID.search(tierNode.attrib['TIER_ID']) is not None
or rxTierID.search(tierNode.attrib['LINGUISTIC_TYPE_REF']) is not None):
tierType = v
break
except:
print('Except')
for segNode in tierNode.xpath('ANNOTATION/REF_ANNOTATION | ANNOTATION/ALIGNABLE_ANNOTATION'):
if 'ANNOTATION_ID' not in segNode.attrib:
continue
aID = segNode.attrib['ANNOTATION_ID']
try:
segContents = segNode.xpath('ANNOTATION_VALUE')[0].text.strip()
except AttributeError:
segContents = ''
try:
segParent = segNode.attrib['ANNOTATION_REF']
except KeyError:
segParent = None
tli1, tli2 = None, None
if 'TIME_SLOT_REF1' in segNode.attrib:
tli1 = segNode.attrib['TIME_SLOT_REF1']
elif segParent in self.segmentTree and self.segmentTree[segParent][2] is not None:
tli1 = self.segmentTree[segParent][2]
if 'TIME_SLOT_REF2' in segNode.attrib:
tli2 = segNode.attrib['TIME_SLOT_REF2']
elif segParent in self.segmentTree and self.segmentTree[segParent][3] is not None:
tli2 = self.segmentTree[segParent][3]
self.segmentTree[aID] = (segContents, segParent, tli1, tli2)
if segParent is None:
continue
if len(tierType) > 0:
try:
self.segmentChildren[(segParent, tierType)].append(aID)
except KeyError:
self.segmentChildren[(segParent, tierType)] = [aID]
def build_segment_tree(self, srcTree):
"""
Read the entire XML tree and save all segment data (contents, links to
the parents and timestamps, if any).
"""
self.segmentTree = {}
self.segmentChildren = {}
self.traverse_tree(srcTree, self.cb_build_segment_tree)
def fragmentize_src_alignment(self, alignment):
"""
Find corresponding media file fragment and transform a JSON
dictionary with the information about the alignment.
"""
fileName, fileExt = os.path.splitext(alignment['src'].lower())
if fileExt not in self.mediaExtensions:
return
ts1 = alignment['off_start_src']
ts2 = alignment['off_end_src']
if len(ts1) <= 0 or len(ts2) <= 0:
return
ts1frag, ts2frag, srcFileFrag = self.mc.get_media_name(alignment['src'],
float(ts1) / EAF_TIME_MULTIPLIER,
float(ts2) / EAF_TIME_MULTIPLIER)
alignment['src'] = srcFileFrag
alignment['off_start_src'] = str(ts1frag)
alignment['off_end_src'] = str(ts2frag)
def add_src_alignment(self, sent, tli1, tli2, srcFile):
"""
Add the alignment of the sentence with the sound/video. If
word-level time data is available, align words, otherwise
align the whole sentence.
"""
sentAlignments = []
ts1 = self.tlis[tli1]['time']
ts2 = self.tlis[tli2]['time']
sentAlignments.append({'off_start_src': ts1,
'off_end_src': ts2,
'true_off_start_src': float(ts1) / EAF_TIME_MULTIPLIER,
'off_start_sent': 0,
'off_end_sent': len(sent['text']),
'mtype': 'audio',
'src_id': ts1 + '_' + ts2,
'src': srcFile})
for alignment in sentAlignments:
self.fragmentize_src_alignment(alignment)
sent['src_alignment'] = sentAlignments
def add_punc(self, text, startOffset):
"""
Make one or several punctuation tokens out of the text.
"""
tokens = []
curToken = {'wf': '', 'off_start': startOffset, 'off_end': startOffset, 'wtype': 'punc'}
for i in range(len(text)):
if self.rxSpaces.search(text[i]) is not None:
if len(curToken['wf']) > 0:
curToken['off_end'] = startOffset + i
tokens.append(curToken)
curToken = {'wf': '', 'off_start': startOffset + i, 'off_end': startOffset + i, 'wtype': 'punc'}
else:
curToken['wf'] += text[i]
if len(curToken['wf']) > 0:
curToken['off_end'] = startOffset + len(text)
tokens.append(curToken)
return tokens
def retrieve_analyses(self, aID, lang=''):
"""
Compile list of analyses retrieved from the relevant tiers of an analyzed
EAF file associated with the token identified by aID.
"""
analyses = []
analysisTiers = []
for tierType in ['pos', 'gramm', 'lemma', 'parts', 'gloss', 'trans_ru']:
if (aID, tierType) not in self.segmentChildren:
continue
analysisTiers.append([])
for childID in self.segmentChildren[(aID, tierType)]:
if childID not in self.segmentTree:
continue
contents = self.segmentTree[childID][0]
for ana in self.retrieve_analyses(childID, lang=lang):
if tierType == 'lemma':
ana['lex'] = contents
elif tierType == 'parts':
ana['parts'] = contents
elif tierType == 'gloss':
ana['gloss'] = contents
elif tierType == 'pos' and len(contents) > 0:
ana['gr.pos'] = contents
elif tierType == 'gramm':
grJSON = self.tp.parser.transform_gramm_str(contents, lang=lang)
ana.update(grJSON)
analysisTiers[-1].append(ana)
analysisTiers[-1] = [ana for ana in analysisTiers[-1] if len(ana) > 0]
if len(analysisTiers) <= 0:
return [{}]
for combination in itertools.product(*analysisTiers):
ana = {}
for partAna in combination:
ana.update(partAna)
if len(ana) > 0:
self.tp.parser.process_gloss_in_ana(ana)
analyses.append(ana)
if len(analyses) <= 0:
return [{}]
return analyses
def retrieve_words(self, text, wordIDs, lang=''):
"""
Return a list of words with their analyses retrieved from the relevant
tiers of an analyzed EAF file. Try to align words with the text of the
entire sentence.
"""
words = []
iSentPos = 0
iBufferStart = 0
sBuffer = ''
for iWord in range(len(wordIDs)):
iWordPos = 0
word = self.segmentTree[wordIDs[iWord]][0]
if len(sBuffer) <= 0:
iBufferStart = iSentPos
if len(word) <= 0:
continue
while iSentPos < len(text) and text[iSentPos].lower() != word[iWordPos].lower():
sBuffer += text[iSentPos]
iSentPos += 1
# print(sBuffer)
if len(sBuffer) > 0:
words += self.add_punc(sBuffer, iBufferStart)
sBuffer = ''
iBufferStart = iSentPos
# print('Unexpected end of sentence:', text)
#if iSentPos == len(text):
# # print(text)
# print(len(text))
# print(iSentPos)
# return words
# else:
# print(text)
# print(len(text))
# print(iSentPos)
token = {'wf': word, 'off_start': iSentPos, 'off_end': iSentPos + len(word), 'wtype': 'word'}
while iSentPos < len(text) and iWordPos < len(word):
if text[iSentPos].lower() == word[iWordPos].lower():
iSentPos += 1
iWordPos += 1
continue
if self.rxLetters.search(word[iWordPos]) is None and self.rxLetters.search(text[iSentPos]) is not None:
iWordPos += 1
continue
iSentPos += 1
token['off_end'] = iSentPos
analyses = [ana for ana in self.retrieve_analyses(wordIDs[iWord], lang=lang) if len(ana) > 0]
if len(analyses) > 0:
token['ana'] = analyses
words.append(token)
if iSentPos < len(text):
words += self.add_punc(text[iSentPos:], iSentPos)
return words
def process_tier(self, tierNode, aID2pID, srcFile, alignedTier=False):
"""
Extract segments from the tier node and iterate over them, returning
them as JSON sentences. If alignedTier is False, store the start and end
timestamps, as well as pIDs for alignment, in the dictionary aID2pID.
If alignedTier is True, use the information from aID2pID for establishing
time boundaries of the sentences and aligning it with the source tier.
"""
lang = ''
# We have to find out what language the tier represents.
# First, check the tier type. If it is not associated with any language,
# check all tier ID regexes.
if 'TIER_ID' not in tierNode.attrib:
return
if ('LINGUISTIC_TYPE_REF' in tierNode.attrib and
tierNode.attrib['LINGUISTIC_TYPE_REF'] in self.corpusSettings['tier_languages']):
lang = self.corpusSettings['tier_languages'][tierNode.attrib['LINGUISTIC_TYPE_REF']]
else:
for k, v in self.corpusSettings['tier_languages'].items():
if not k.startswith('^'):
k = '^' + k
if not k.endswith('$'):
k += '$'
try:
rxTierID = re.compile(k)
if rxTierID.search(tierNode.attrib['TIER_ID']) is not None:
lang = v
break
except:
continue
if len(lang) <= 0 or lang not in self.corpusSettings['languages']:
return
langID = self.corpusSettings['languages'].index(lang)
speaker = ''
if not alignedTier and 'PARTICIPANT' in tierNode.attrib:
speaker = tierNode.attrib['PARTICIPANT']
self.participants[tierNode.attrib['TIER_ID']] = speaker
else:
if ('PARENT_REF' in tierNode.attrib
and tierNode.attrib['PARENT_REF'] in self.participants):
speaker = self.participants[tierNode.attrib['PARENT_REF']]
elif 'PARTICIPANT' in tierNode.attrib:
speaker = tierNode.attrib['PARTICIPANT']
segments = tierNode.xpath('ANNOTATION/REF_ANNOTATION | ANNOTATION/ALIGNABLE_ANNOTATION')
for segNode in segments:
if ('ANNOTATION_ID' not in segNode.attrib
or segNode.attrib['ANNOTATION_ID'] not in self.segmentTree):
continue
segData = self.segmentTree[segNode.attrib['ANNOTATION_ID']]
if not alignedTier:
if segData[2] is None or segData[3] is None:
continue
tli1 = segData[2]
tli2 = segData[3]
elif segData[1] is not None:
# print(segData)
aID = segData[1]
pID, tli1, tli2 = aID2pID[aID]
else:
continue
text = segData[0]
curSent = {'text': text, 'words': None, 'lang': langID,
'meta': {'speaker': speaker}}
if speaker in self.speakerMeta:
for k, v in self.speakerMeta[speaker].items():
curSent['meta'][k] = v
if (segNode.attrib['ANNOTATION_ID'], 'word') not in self.segmentChildren:
curSent['words'] = self.tp.tokenizer.tokenize(text)
self.tp.splitter.add_next_word_id_sentence(curSent)
self.tp.parser.analyze_sentence(curSent, lang=lang)
else:
curSent['words'] = self.retrieve_words(text,
self.segmentChildren[(segNode.attrib['ANNOTATION_ID'],
'word')],
lang=lang)
self.tp.splitter.add_next_word_id_sentence(curSent)
if len(self.corpusSettings['aligned_tiers']) > 0:
if not alignedTier:
self.pID += 1
aID = segNode.attrib['ANNOTATION_ID']
aID2pID[aID] = (self.pID, tli1, tli2)
paraAlignment = {'off_start': 0, 'off_end': len(curSent['text']), 'para_id': self.pID}
curSent['para_alignment'] = [paraAlignment]
else:
paraAlignment = {'off_start': 0, 'off_end': len(curSent['text']), 'para_id': pID}
curSent['para_alignment'] = [paraAlignment]
self.add_src_alignment(curSent, tli1, tli2, srcFile)
yield curSent
def get_sentences(self, srcTree, srcFile):
"""
Iterate over sentences in the XML tree.
"""
# mainTierTypes = '(' + ' | '.join('/ANNOTATION_DOCUMENT/TIER[@LINGUISTIC_TYPE_REF=\'' + x + '\'] | ' +
# '/ANNOTATION_DOCUMENT/TIER[@TIER_ID=\'' + x + '\']'
# for x in self.corpusSettings['main_tiers']) + ')'
# mainTiers = srcTree.xpath(mainTierTypes)
mainTiers = []
alignedTiers = []
for tierNode in srcTree.xpath('/ANNOTATION_DOCUMENT/TIER'):
for tierRegex in self.corpusSettings['main_tiers']:
if not tierRegex.startswith('^'):
tierRegex = '^' + tierRegex
if not tierRegex.endswith('$'):
tierRegex += '$'
try:
if re.search(tierRegex, tierNode.attrib['TIER_ID']) is not None:
mainTiers.append(tierNode)
break
elif ('LINGUISTIC_TYPE_REF' in tierNode.attrib
and re.search(tierRegex, tierNode.attrib['LINGUISTIC_TYPE_REF']) is not None):
mainTiers.append(tierNode)
break
except:
pass
for tierRegex in self.corpusSettings['aligned_tiers']:
if not tierRegex.startswith('^'):
tierRegex = '^' + tierRegex
if not tierRegex.endswith('$'):
tierRegex += '$'
try:
if re.search(tierRegex, tierNode.attrib['TIER_ID']) is not None:
alignedTiers.append(tierNode)
break
elif ('LINGUISTIC_TYPE_REF' in tierNode.attrib
and re.search(tierRegex, tierNode.attrib['LINGUISTIC_TYPE_REF']) is not None):
alignedTiers.append(tierNode)
break
except:
pass
if len(mainTiers) <= 0:
return
# if len(self.corpusSettings['aligned_tiers']) > 0:
# alignedTierTypes = '(' + ' | '.join('/ANNOTATION_DOCUMENT/TIER[@LINGUISTIC_TYPE_REF=\'' + x + '\'] | ' +
# '/ANNOTATION_DOCUMENT/TIER[@TIER_ID=\'' + x + '\']'
# for x in self.corpusSettings['aligned_tiers']) + ')'
# alignedTiers = srcTree.xpath(alignedTierTypes)
aID2pID = {} # annotation ID -> (pID, tli1, tli2) correspondence
for tier in mainTiers:
for sent in self.process_tier(tier, aID2pID, srcFile, alignedTier=False):
yield sent
for tier in alignedTiers:
for sent in self.process_tier(tier, aID2pID, srcFile, alignedTier=True):
yield sent
def add_speaker_marks(self, sentences):
"""
Add the name/code of the speaker in the beginning of every
sentence that starts the turn.
"""
prevSpeaker = ''
for i in range(len(sentences)):
if 'meta' not in sentences[i] or 'speaker' not in sentences[i]['meta']:
continue
speaker = '[' + sentences[i]['meta']['speaker'] + ']'
addOffset = len(speaker) + 2
if sentences[i]['meta']['speaker'] != prevSpeaker:
sentences[i]['text'] = '\n' + speaker + ' ' + sentences[i]['text']
sentences[i]['words'].insert(0, {'off_start': -len(speaker) - 1,
'off_end': -1,
'wf': speaker,
'wtype': 'punc',
'next_word': 0})
sentences[i]['words'].insert(0, {'off_start': -len(speaker) - 2,
'off_end': -len(speaker)-1,
'wf': '\n',
'wtype': 'punc',
'next_word': -1})
for w in sentences[i]['words']:
w['off_start'] += addOffset
w['off_end'] += addOffset
w['next_word'] += 2
if 'para_alignment' in sentences[i]:
for pa in sentences[i]['para_alignment']:
if pa['off_start'] > 0:
pa['off_start'] += addOffset
pa['off_end'] += addOffset
if 'src_alignment' in sentences[i]:
for sa in sentences[i]['src_alignment']:
if sa['off_start_sent'] > 0:
sa['off_start_sent'] += addOffset
sa['off_end_sent'] += addOffset
prevSpeaker = sentences[i]['meta']['speaker']
if 'last' in sentences[i] and sentences[i]['last']:
prevSpeaker = ''
def add_sentence_meta(self, sentences, meta):
"""
Add some of the document-level metadata to the sentences.
"""
for s in sentences:
if 'meta' not in s:
continue
if 'year1' in meta and 'year2' in meta and meta['year1'] == meta['year2']:
s['meta']['year'] = meta['year1']
def convert_file(self, fnameSrc, fnameTarget):
#print(fnameSrc)
curMeta = self.get_meta(fnameSrc)
textJSON = {'meta': curMeta, 'sentences': []}
nTokens, nWords, nAnalyzed = 0, 0, 0
srcTree = etree.parse(fnameSrc)
self.tlis = self.get_tlis(srcTree)
self.build_segment_tree(srcTree)
srcFileNode = srcTree.xpath('/ANNOTATION_DOCUMENT/HEADER/MEDIA_DESCRIPTOR')
if len(srcFileNode) > 0 and 'RELATIVE_MEDIA_URL' in srcFileNode[0].attrib:
srcFile = self.rxStripDir.sub('', html.unescape(srcFileNode[0].attrib['RELATIVE_MEDIA_URL']))
elif len(srcFileNode) > 0 and 'MEDIA_URL' in srcFileNode[0].attrib:
srcFile = self.rxStripDir.sub('', html.unescape(srcFileNode[0].attrib['MEDIA_URL']))
else:
srcFile = ''
textJSON['sentences'] = [s for s in self.get_sentences(srcTree, srcFile)]
textJSON['sentences'].sort(key=lambda s: (s['lang'], s['src_alignment'][0]['true_off_start_src']))
for i in range(len(textJSON['sentences']) - 1):
# del textJSON['sentences'][i]['src_alignment'][0]['true_off_start_src']
if textJSON['sentences'][i]['lang'] != textJSON['sentences'][i + 1]['lang']:
textJSON['sentences'][i]['last'] = True
for word in textJSON['sentences'][i]['words']:
nTokens += 1
if word['wtype'] == 'word':
nWords += 1
if 'ana' in word and len(word['ana']) > 0:
nAnalyzed += 1
self.tp.splitter.recalculate_offsets(textJSON['sentences'])
self.tp.splitter.add_next_word_id(textJSON['sentences'])
self.add_speaker_marks(textJSON['sentences'])
self.add_sentence_meta(textJSON['sentences'], curMeta)
self.write_output(fnameTarget, textJSON)
return nTokens, nWords, nAnalyzed
def process_corpus(self, cutMedia=False):
"""
Take every eaf file from the source directory subtree, turn it
into a parsed json and store it in the target directory.
"""
Txt2JSON.process_corpus(self)
if not cutMedia:
return
for path, dirs, files in os.walk(os.path.join('..',
self.srcExt)):
for fname in files:
fileExt = os.path.splitext(fname.lower())[1]
if fileExt in self.mediaExtensions:
fname = os.path.abspath(os.path.join(path, fname))
print('Cutting media file', fname)
self.mc.cut_media(fname)
if __name__ == '__main__':
t2j = Eaf2JSON()
t2j.process_corpus(cutMedia=False)
|
/* band.js */
Timeline._Band = function (B, G, C) {
if (B.autoWidth && typeof G.width == "string") {
G.width = G.width.indexOf("%") > -1 ? 0 : parseInt(G.width);
}
this._timeline = B;
this._bandInfo = G;
this._index = C;
this._locale = ("locale" in G) ? G.locale : Timeline.getDefaultLocale();
this._timeZone = ("timeZone" in G) ? G.timeZone : 0;
this._labeller = ("labeller" in G) ? G.labeller : (("createLabeller" in B.getUnit()) ? B.getUnit().createLabeller(this._locale, this._timeZone) : new Timeline.GregorianDateLabeller(this._locale, this._timeZone));
this._theme = G.theme;
this._zoomIndex = ("zoomIndex" in G) ? G.zoomIndex : 0;
this._zoomSteps = ("zoomSteps" in G) ? G.zoomSteps : null;
this._dragging = false;
this._changing = false;
this._originalScrollSpeed = 5;
this._scrollSpeed = this._originalScrollSpeed;
this._onScrollListeners = [];
var A = this;
this._syncWithBand = null;
this._syncWithBandHandler = function (H) {
A._onHighlightBandScroll();
};
this._selectorListener = function (H) {
A._onHighlightBandScroll();
};
var E = this._timeline.getDocument().createElement("div");
E.className = "timeline-band-input";
this._timeline.addDiv(E);
this._keyboardInput = document.createElement("input");
this._keyboardInput.type = "text";
E.appendChild(this._keyboardInput);
SimileAjax.DOM.registerEventWithObject(this._keyboardInput, "keydown", this, "_onKeyDown");
SimileAjax.DOM.registerEventWithObject(this._keyboardInput, "keyup", this, "_onKeyUp");
this._div = this._timeline.getDocument().createElement("div");
this._div.id = "timeline-band-" + C;
this._div.className = "timeline-band timeline-band-" + C;
this._timeline.addDiv(this._div);
SimileAjax.DOM.registerEventWithObject(this._div, "mousedown", this, "_onMouseDown");
SimileAjax.DOM.registerEventWithObject(this._div, "mousemove", this, "_onMouseMove");
SimileAjax.DOM.registerEventWithObject(this._div, "mouseup", this, "_onMouseUp");
SimileAjax.DOM.registerEventWithObject(this._div, "mouseout", this, "_onMouseOut");
SimileAjax.DOM.registerEventWithObject(this._div, "dblclick", this, "_onDblClick");
var F = this._theme != null ? this._theme.mouseWheel : "scroll";
if (F === "zoom" || F === "scroll" || this._zoomSteps) {
if (SimileAjax.Platform.browser.isFirefox) {
SimileAjax.DOM.registerEventWithObject(this._div, "DOMMouseScroll", this, "_onMouseScroll");
} else {
SimileAjax.DOM.registerEventWithObject(this._div, "mousewheel", this, "_onMouseScroll");
}
}
this._innerDiv = this._timeline.getDocument().createElement("div");
this._innerDiv.className = "timeline-band-inner";
this._div.appendChild(this._innerDiv);
this._ether = G.ether;
G.ether.initialize(this, B);
this._etherPainter = G.etherPainter;
G.etherPainter.initialize(this, B);
this._eventSource = G.eventSource;
if (this._eventSource) {
this._eventListener = {onAddMany: function () {
A._onAddMany();
}, onClear: function () {
A._onClear();
}};
this._eventSource.addListener(this._eventListener);
}
this._eventPainter = G.eventPainter;
this._eventTracksNeeded = 0;
this._eventTrackIncrement = 0;
G.eventPainter.initialize(this, B);
this._decorators = ("decorators" in G) ? G.decorators : [];
for (var D = 0;
D < this._decorators.length;
D++) {
this._decorators[D].initialize(this, B);
}
};
Timeline._Band.SCROLL_MULTIPLES = 5;
Timeline._Band.prototype.dispose = function () {
this.closeBubble();
if (this._eventSource) {
this._eventSource.removeListener(this._eventListener);
this._eventListener = null;
this._eventSource = null;
}
this._timeline = null;
this._bandInfo = null;
this._labeller = null;
this._ether = null;
this._etherPainter = null;
this._eventPainter = null;
this._decorators = null;
this._onScrollListeners = null;
this._syncWithBandHandler = null;
this._selectorListener = null;
this._div = null;
this._innerDiv = null;
this._keyboardInput = null;
};
Timeline._Band.prototype.addOnScrollListener = function (A) {
this._onScrollListeners.push(A);
};
Timeline._Band.prototype.removeOnScrollListener = function (B) {
for (var A = 0;
A < this._onScrollListeners.length;
A++) {
if (this._onScrollListeners[A] == B) {
this._onScrollListeners.splice(A, 1);
break;
}
}
};
Timeline._Band.prototype.setSyncWithBand = function (B, A) {
if (this._syncWithBand) {
this._syncWithBand.removeOnScrollListener(this._syncWithBandHandler);
}
this._syncWithBand = B;
this._syncWithBand.addOnScrollListener(this._syncWithBandHandler);
this._highlight = A;
this._positionHighlight();
};
Timeline._Band.prototype.getLocale = function () {
return this._locale;
};
Timeline._Band.prototype.getTimeZone = function () {
return this._timeZone;
};
Timeline._Band.prototype.getLabeller = function () {
return this._labeller;
};
Timeline._Band.prototype.getIndex = function () {
return this._index;
};
Timeline._Band.prototype.getEther = function () {
return this._ether;
};
Timeline._Band.prototype.getEtherPainter = function () {
return this._etherPainter;
};
Timeline._Band.prototype.getEventSource = function () {
return this._eventSource;
};
Timeline._Band.prototype.getEventPainter = function () {
return this._eventPainter;
};
Timeline._Band.prototype.getTimeline = function () {
return this._timeline;
};
Timeline._Band.prototype.updateEventTrackInfo = function (A, B) {
this._eventTrackIncrement = B;
if (A > this._eventTracksNeeded) {
this._eventTracksNeeded = A;
}
};
Timeline._Band.prototype.checkAutoWidth = function () {
if (!this._timeline.autoWidth) {
return;
}
var C = this._eventPainter.getType() == "overview";
var A = C ? this._theme.event.overviewTrack.autoWidthMargin : this._theme.event.track.autoWidthMargin;
var B = Math.ceil((this._eventTracksNeeded + A) * this._eventTrackIncrement);
B += C ? this._theme.event.overviewTrack.offset : this._theme.event.track.offset;
var D = this._bandInfo;
if (B != D.width) {
D.width = B;
}
};
Timeline._Band.prototype.layout = function () {
this.paint();
};
Timeline._Band.prototype.paint = function () {
this._etherPainter.paint();
this._paintDecorators();
this._paintEvents();
};
Timeline._Band.prototype.softLayout = function () {
this.softPaint();
};
Timeline._Band.prototype.softPaint = function () {
this._etherPainter.softPaint();
this._softPaintDecorators();
this._softPaintEvents();
};
Timeline._Band.prototype.setBandShiftAndWidth = function (A, D) {
var C = this._keyboardInput.parentNode;
var B = A + Math.floor(D / 2);
if (this._timeline.isHorizontal()) {
this._div.style.top = A + "px";
this._div.style.height = D + "px";
C.style.top = B + "px";
C.style.left = "-1em";
} else {
this._div.style.left = A + "px";
this._div.style.width = D + "px";
C.style.left = B + "px";
C.style.top = "-1em";
}
};
Timeline._Band.prototype.getViewWidth = function () {
if (this._timeline.isHorizontal()) {
return this._div.offsetHeight;
} else {
return this._div.offsetWidth;
}
};
Timeline._Band.prototype.setViewLength = function (A) {
this._viewLength = A;
this._recenterDiv();
this._onChanging();
};
Timeline._Band.prototype.getViewLength = function () {
return this._viewLength;
};
Timeline._Band.prototype.getTotalViewLength = function () {
return Timeline._Band.SCROLL_MULTIPLES * this._viewLength;
};
Timeline._Band.prototype.getViewOffset = function () {
return this._viewOffset;
};
Timeline._Band.prototype.getMinDate = function () {
return this._ether.pixelOffsetToDate(this._viewOffset);
};
Timeline._Band.prototype.getMaxDate = function () {
return this._ether.pixelOffsetToDate(this._viewOffset + Timeline._Band.SCROLL_MULTIPLES * this._viewLength);
};
Timeline._Band.prototype.getMinVisibleDate = function () {
return this._ether.pixelOffsetToDate(0);
};
Timeline._Band.prototype.getMinVisibleDateAfterDelta = function (A) {
return this._ether.pixelOffsetToDate(A);
};
Timeline._Band.prototype.getMaxVisibleDate = function () {
return this._ether.pixelOffsetToDate(this._viewLength);
};
Timeline._Band.prototype.getMaxVisibleDateAfterDelta = function (A) {
return this._ether.pixelOffsetToDate(this._viewLength + A);
};
Timeline._Band.prototype.getCenterVisibleDate = function () {
return this._ether.pixelOffsetToDate(this._viewLength / 2);
};
Timeline._Band.prototype.setMinVisibleDate = function (A) {
if (!this._changing) {
this._moveEther(Math.round(-this._ether.dateToPixelOffset(A)));
}
};
Timeline._Band.prototype.setMaxVisibleDate = function (A) {
if (!this._changing) {
this._moveEther(Math.round(this._viewLength - this._ether.dateToPixelOffset(A)));
}
};
Timeline._Band.prototype.setCenterVisibleDate = function (A) {
if (!this._changing) {
this._moveEther(Math.round(this._viewLength / 2 - this._ether.dateToPixelOffset(A)));
}
};
Timeline._Band.prototype.dateToPixelOffset = function (A) {
return this._ether.dateToPixelOffset(A) - this._viewOffset;
};
Timeline._Band.prototype.pixelOffsetToDate = function (A) {
return this._ether.pixelOffsetToDate(A + this._viewOffset);
};
Timeline._Band.prototype.createLayerDiv = function (C, A) {
var D = this._timeline.getDocument().createElement("div");
D.className = "timeline-band-layer" + (typeof A == "string" ? (" " + A) : "");
D.style.zIndex = C;
this._innerDiv.appendChild(D);
var B = this._timeline.getDocument().createElement("div");
B.className = "timeline-band-layer-inner";
if (SimileAjax.Platform.browser.isIE) {
B.style.cursor = "move";
} else {
B.style.cursor = "-moz-grab";
}
D.appendChild(B);
return B;
};
Timeline._Band.prototype.removeLayerDiv = function (A) {
this._innerDiv.removeChild(A.parentNode);
};
Timeline._Band.prototype.scrollToCenter = function (A, C) {
var B = this._ether.dateToPixelOffset(A);
if (B < -this._viewLength / 2) {
this.setCenterVisibleDate(this.pixelOffsetToDate(B + this._viewLength));
} else {
if (B > 3 * this._viewLength / 2) {
this.setCenterVisibleDate(this.pixelOffsetToDate(B - this._viewLength));
}
}
this._autoScroll(Math.round(this._viewLength / 2 - this._ether.dateToPixelOffset(A)), C);
};
Timeline._Band.prototype.showBubbleForEvent = function (C) {
var A = this.getEventSource().getEvent(C);
if (A) {
var B = this;
this.scrollToCenter(A.getStart(), function () {
B._eventPainter.showBubble(A);
});
}
};
Timeline._Band.prototype.zoom = function (C, A, F, E) {
if (!this._zoomSteps) {
return;
}
A += this._viewOffset;
var D = this._ether.pixelOffsetToDate(A);
var B = this._ether.zoom(C);
this._etherPainter.zoom(B);
this._moveEther(Math.round(-this._ether.dateToPixelOffset(D)));
this._moveEther(A);
};
Timeline._Band.prototype._onMouseDown = function (B, A, C) {
this.closeBubble();
this._dragging = true;
this._dragX = A.clientX;
this._dragY = A.clientY;
};
Timeline._Band.prototype._onMouseMove = function (D, A, E) {
if (this._dragging) {
var C = A.clientX - this._dragX;
var B = A.clientY - this._dragY;
this._dragX = A.clientX;
this._dragY = A.clientY;
this._moveEther(this._timeline.isHorizontal() ? C : B);
this._positionHighlight();
}
};
Timeline._Band.prototype._onMouseUp = function (B, A, C) {
this._dragging = false;
this._keyboardInput.focus();
};
Timeline._Band.prototype._onMouseOut = function (C, B, D) {
var A = SimileAjax.DOM.getEventRelativeCoordinates(B, C);
A.x += this._viewOffset;
if (A.x < 0 || A.x > C.offsetWidth || A.y < 0 || A.y > C.offsetHeight) {
this._dragging = false;
}
};
Timeline._Band.prototype._onMouseScroll = function (G, H, B) {
var A = new Date();
A = A.getTime();
if (!this._lastScrollTime || ((A - this._lastScrollTime) > 50)) {
this._lastScrollTime = A;
var I = 0;
if (H.wheelDelta) {
I = H.wheelDelta / 120;
} else {
if (H.detail) {
I = -H.detail / 3;
}
}
var F = this._theme.mouseWheel;
if (this._zoomSteps || F === "zoom") {
var E = SimileAjax.DOM.getEventRelativeCoordinates(H, G);
if (I != 0) {
var D;
if (I > 0) {
D = true;
}
if (I < 0) {
D = false;
}
this._timeline.zoom(D, E.x, E.y, G);
}
} else {
if (F === "scroll") {
var C = 50 * (I < 0 ? -1 : 1);
this._moveEther(C);
}
}
}
if (H.stopPropagation) {
H.stopPropagation();
}
H.cancelBubble = true;
if (H.preventDefault) {
H.preventDefault();
}
H.returnValue = false;
};
Timeline._Band.prototype._onDblClick = function (C, B, E) {
var A = SimileAjax.DOM.getEventRelativeCoordinates(B, C);
var D = A.x - (this._viewLength / 2 - this._viewOffset);
this._autoScroll(-D);
};
Timeline._Band.prototype._onKeyDown = function (B, A, C) {
if (!this._dragging) {
switch (A.keyCode) {
case 27:
break;
case 37:
case 38:
this._scrollSpeed = Math.min(50, Math.abs(this._scrollSpeed * 1.05));
this._moveEther(this._scrollSpeed);
break;
case 39:
case 40:
this._scrollSpeed = -Math.min(50, Math.abs(this._scrollSpeed * 1.05));
this._moveEther(this._scrollSpeed);
break;
default:
return true;
}
this.closeBubble();
SimileAjax.DOM.cancelEvent(A);
return false;
}
return true;
};
Timeline._Band.prototype._onKeyUp = function (B, A, C) {
if (!this._dragging) {
this._scrollSpeed = this._originalScrollSpeed;
switch (A.keyCode) {
case 35:
this.setCenterVisibleDate(this._eventSource.getLatestDate());
break;
case 36:
this.setCenterVisibleDate(this._eventSource.getEarliestDate());
break;
case 33:
this._autoScroll(this._timeline.getPixelLength());
break;
case 34:
this._autoScroll(-this._timeline.getPixelLength());
break;
default:
return true;
}
this.closeBubble();
SimileAjax.DOM.cancelEvent(A);
return false;
}
return true;
};
Timeline._Band.prototype._autoScroll = function (D, C) {
var A = this;
var B = SimileAjax.Graphics.createAnimation(function (E, F) {
A._moveEther(F);
}, 0, D, 1000, C);
B.run();
};
Timeline._Band.prototype._moveEther = function (A) {
this.closeBubble();
if (!this._timeline.shiftOK(this._index, A)) {
return;
}
this._viewOffset += A;
this._ether.shiftPixels(-A);
if (this._timeline.isHorizontal()) {
this._div.style.left = this._viewOffset + "px";
} else {
this._div.style.top = this._viewOffset + "px";
}
if (this._viewOffset > -this._viewLength * 0.5 || this._viewOffset < -this._viewLength * (Timeline._Band.SCROLL_MULTIPLES - 1.5)) {
this._recenterDiv();
} else {
this.softLayout();
}
this._onChanging();
};
Timeline._Band.prototype._onChanging = function () {
this._changing = true;
this._fireOnScroll();
this._setSyncWithBandDate();
this._changing = false;
};
Timeline._Band.prototype.busy = function () {
return(this._changing);
};
Timeline._Band.prototype._fireOnScroll = function () {
for (var A = 0;
A < this._onScrollListeners.length;
A++) {
this._onScrollListeners[A](this);
}
};
Timeline._Band.prototype._setSyncWithBandDate = function () {
if (this._syncWithBand) {
var A = this._ether.pixelOffsetToDate(this.getViewLength() / 2);
this._syncWithBand.setCenterVisibleDate(A);
}
};
Timeline._Band.prototype._onHighlightBandScroll = function () {
if (this._syncWithBand) {
var A = this._syncWithBand.getCenterVisibleDate();
var B = this._ether.dateToPixelOffset(A);
this._moveEther(Math.round(this._viewLength / 2 - B));
if (this._highlight) {
this._etherPainter.setHighlight(this._syncWithBand.getMinVisibleDate(), this._syncWithBand.getMaxVisibleDate());
}
}
};
Timeline._Band.prototype._onAddMany = function () {
this._paintEvents();
};
Timeline._Band.prototype._onClear = function () {
this._paintEvents();
};
Timeline._Band.prototype._positionHighlight = function () {
if (this._syncWithBand) {
var A = this._syncWithBand.getMinVisibleDate();
var B = this._syncWithBand.getMaxVisibleDate();
if (this._highlight) {
this._etherPainter.setHighlight(A, B);
}
}
};
Timeline._Band.prototype._recenterDiv = function () {
this._viewOffset = -this._viewLength * (Timeline._Band.SCROLL_MULTIPLES - 1) / 2;
if (this._timeline.isHorizontal()) {
this._div.style.left = this._viewOffset + "px";
this._div.style.width = (Timeline._Band.SCROLL_MULTIPLES * this._viewLength) + "px";
} else {
this._div.style.top = this._viewOffset + "px";
this._div.style.height = (Timeline._Band.SCROLL_MULTIPLES * this._viewLength) + "px";
}
this.layout();
};
Timeline._Band.prototype._paintEvents = function () {
this._eventPainter.paint();
};
Timeline._Band.prototype._softPaintEvents = function () {
this._eventPainter.softPaint();
};
Timeline._Band.prototype._paintDecorators = function () {
for (var A = 0;
A < this._decorators.length;
A++) {
this._decorators[A].paint();
}
};
Timeline._Band.prototype._softPaintDecorators = function () {
for (var A = 0;
A < this._decorators.length;
A++) {
this._decorators[A].softPaint();
}
};
Timeline._Band.prototype.closeBubble = function () {
SimileAjax.WindowManager.cancelPopups();
};
/* compact-painter.js */
Timeline.CompactEventPainter = function (A) {
this._params = A;
this._onSelectListeners = [];
this._filterMatcher = null;
this._highlightMatcher = null;
this._frc = null;
this._eventIdToElmt = {};
};
Timeline.CompactEventPainter.prototype.initialize = function (B, A) {
this._band = B;
this._timeline = A;
this._backLayer = null;
this._eventLayer = null;
this._lineLayer = null;
this._highlightLayer = null;
this._eventIdToElmt = null;
};
Timeline.CompactEventPainter.prototype.addOnSelectListener = function (A) {
this._onSelectListeners.push(A);
};
Timeline.CompactEventPainter.prototype.removeOnSelectListener = function (B) {
for (var A = 0;
A < this._onSelectListeners.length;
A++) {
if (this._onSelectListeners[A] == B) {
this._onSelectListeners.splice(A, 1);
break;
}
}
};
Timeline.CompactEventPainter.prototype.getFilterMatcher = function () {
return this._filterMatcher;
};
Timeline.CompactEventPainter.prototype.setFilterMatcher = function (A) {
this._filterMatcher = A;
};
Timeline.CompactEventPainter.prototype.getHighlightMatcher = function () {
return this._highlightMatcher;
};
Timeline.CompactEventPainter.prototype.setHighlightMatcher = function (A) {
this._highlightMatcher = A;
};
Timeline.CompactEventPainter.prototype.paint = function () {
var N = this._band.getEventSource();
if (N == null) {
return;
}
this._eventIdToElmt = {};
this._prepareForPainting();
var O = this._params.theme;
var L = O.event;
var G = {trackOffset: "trackOffset" in this._params ? this._params.trackOffset : 10, trackHeight: "trackHeight" in this._params ? this._params.trackHeight : 10, tapeHeight: O.event.tape.height, tapeBottomMargin: "tapeBottomMargin" in this._params ? this._params.tapeBottomMargin : 2, labelBottomMargin: "labelBottomMargin" in this._params ? this._params.labelBottomMargin : 5, labelRightMargin: "labelRightMargin" in this._params ? this._params.labelRightMargin : 5, defaultIcon: L.instant.icon, defaultIconWidth: L.instant.iconWidth, defaultIconHeight: L.instant.iconHeight, customIconWidth: "iconWidth" in this._params ? this._params.iconWidth : L.instant.iconWidth, customIconHeight: "iconHeight" in this._params ? this._params.iconHeight : L.instant.iconHeight, iconLabelGap: "iconLabelGap" in this._params ? this._params.iconLabelGap : 2, iconBottomMargin: "iconBottomMargin" in this._params ? this._params.iconBottomMargin : 2};
if ("compositeIcon" in this._params) {
G.compositeIcon = this._params.compositeIcon;
G.compositeIconWidth = this._params.compositeIconWidth || G.customIconWidth;
G.compositeIconHeight = this._params.compositeIconHeight || G.customIconHeight;
} else {
G.compositeIcon = G.defaultIcon;
G.compositeIconWidth = G.defaultIconWidth;
G.compositeIconHeight = G.defaultIconHeight;
}
G.defaultStackIcon = "icon" in this._params.stackConcurrentPreciseInstantEvents ? this._params.stackConcurrentPreciseInstantEvents.icon : G.defaultIcon;
G.defaultStackIconWidth = "iconWidth" in this._params.stackConcurrentPreciseInstantEvents ? this._params.stackConcurrentPreciseInstantEvents.iconWidth : G.defaultIconWidth;
G.defaultStackIconHeight = "iconHeight" in this._params.stackConcurrentPreciseInstantEvents ? this._params.stackConcurrentPreciseInstantEvents.iconHeight : G.defaultIconHeight;
var B = this._band.getMinDate();
var D = this._band.getMaxDate();
var R = (this._filterMatcher != null) ? this._filterMatcher : function (S) {
return true;
};
var Q = (this._highlightMatcher != null) ? this._highlightMatcher : function (S) {
return -1;
};
var F = N.getEventIterator(B, D);
var H = "stackConcurrentPreciseInstantEvents" in this._params && typeof this._params.stackConcurrentPreciseInstantEvents == "object";
var P = "collapseConcurrentPreciseInstantEvents" in this._params && this._params.collapseConcurrentPreciseInstantEvents;
if (P || H) {
var M = [];
var A = null;
while (F.hasNext()) {
var E = F.next();
if (R(E)) {
if (!E.isInstant() || E.isImprecise()) {
this.paintEvent(E, G, this._params.theme, Q(E));
} else {
if (A != null && A.getStart().getTime() == E.getStart().getTime()) {
M[M.length - 1].push(E);
} else {
M.push([E]);
A = E;
}
}
}
}
for (var J = 0;
J < M.length;
J++) {
var K = M[J];
if (K.length == 1) {
this.paintEvent(K[0], G, this._params.theme, Q(E));
} else {
var C = -1;
for (var I = 0;
C < 0 && I < K.length;
I++) {
C = Q(K[I]);
}
if (H) {
this.paintStackedPreciseInstantEvents(K, G, this._params.theme, C);
} else {
this.paintCompositePreciseInstantEvents(K, G, this._params.theme, C);
}
}
}
} else {
while (F.hasNext()) {
var E = F.next();
if (R(E)) {
this.paintEvent(E, G, this._params.theme, Q(E));
}
}
}
this._highlightLayer.style.display = "block";
this._lineLayer.style.display = "block";
this._eventLayer.style.display = "block";
};
Timeline.CompactEventPainter.prototype.softPaint = function () {
};
Timeline.CompactEventPainter.prototype._prepareForPainting = function () {
var B = this._band;
if (this._backLayer == null) {
this._backLayer = this._band.createLayerDiv(0, "timeline-band-events");
this._backLayer.style.visibility = "hidden";
var A = document.createElement("span");
A.className = "timeline-event-label";
this._backLayer.appendChild(A);
this._frc = SimileAjax.Graphics.getFontRenderingContext(A);
}
this._frc.update();
this._tracks = [];
if (this._highlightLayer != null) {
B.removeLayerDiv(this._highlightLayer);
}
this._highlightLayer = B.createLayerDiv(105, "timeline-band-highlights");
this._highlightLayer.style.display = "none";
if (this._lineLayer != null) {
B.removeLayerDiv(this._lineLayer);
}
this._lineLayer = B.createLayerDiv(110, "timeline-band-lines");
this._lineLayer.style.display = "none";
if (this._eventLayer != null) {
B.removeLayerDiv(this._eventLayer);
}
this._eventLayer = B.createLayerDiv(115, "timeline-band-events");
this._eventLayer.style.display = "none";
};
Timeline.CompactEventPainter.prototype.paintEvent = function (B, C, D, A) {
if (B.isInstant()) {
this.paintInstantEvent(B, C, D, A);
} else {
this.paintDurationEvent(B, C, D, A);
}
};
Timeline.CompactEventPainter.prototype.paintInstantEvent = function (B, C, D, A) {
if (B.isImprecise()) {
this.paintImpreciseInstantEvent(B, C, D, A);
} else {
this.paintPreciseInstantEvent(B, C, D, A);
}
};
Timeline.CompactEventPainter.prototype.paintDurationEvent = function (B, C, D, A) {
if (B.isImprecise()) {
this.paintImpreciseDurationEvent(B, C, D, A);
} else {
this.paintPreciseDurationEvent(B, C, D, A);
}
};
Timeline.CompactEventPainter.prototype.paintPreciseInstantEvent = function (H, F, B, A) {
var C = {tooltip: H.getProperty("tooltip") || H.getText()};
var E = {url: H.getIcon()};
if (E.url == null) {
E.url = F.defaultIcon;
E.width = F.defaultIconWidth;
E.height = F.defaultIconHeight;
E.className = "timeline-event-icon-default";
} else {
E.width = H.getProperty("iconWidth") || F.customIconWidth;
E.height = H.getProperty("iconHeight") || F.customIconHeight;
}
var J = {text: H.getText(), color: H.getTextColor() || H.getColor(), className: H.getClassName()};
var G = this.paintTapeIconLabel(H.getStart(), C, null, E, J, F, B, A);
var I = this;
var D = function (L, K, M) {
return I._onClickInstantEvent(G.iconElmtData.elmt, K, H);
};
SimileAjax.DOM.registerEvent(G.iconElmtData.elmt, "mousedown", D);
SimileAjax.DOM.registerEvent(G.labelElmtData.elmt, "mousedown", D);
this._eventIdToElmt[H.getID()] = G.iconElmtData.elmt;
};
Timeline.CompactEventPainter.prototype.paintCompositePreciseInstantEvents = function (J, H, D, B) {
var K = J[0];
var A = [];
for (var C = 0;
C < J.length;
C++) {
A.push(J[C].getProperty("tooltip") || J[C].getText());
}
var E = {tooltip: A.join("; ")};
var G = {url: H.compositeIcon, width: H.compositeIconWidth, height: H.compositeIconHeight, className: "timeline-event-icon-composite"};
var M = {text: String.substitute(this._params.compositeEventLabelTemplate, [J.length])};
var I = this.paintTapeIconLabel(K.getStart(), E, null, G, M, H, D, B);
var L = this;
var F = function (O, N, P) {
return L._onClickMultiplePreciseInstantEvent(I.iconElmtData.elmt, N, J);
};
SimileAjax.DOM.registerEvent(I.iconElmtData.elmt, "mousedown", F);
SimileAjax.DOM.registerEvent(I.labelElmtData.elmt, "mousedown", F);
for (var C = 0;
C < J.length;
C++) {
this._eventIdToElmt[J[C].getID()] = I.iconElmtData.elmt;
}
};
Timeline.CompactEventPainter.prototype.paintStackedPreciseInstantEvents = function (T, j, c, E) {
var S = "limit" in this._params.stackConcurrentPreciseInstantEvents ? this._params.stackConcurrentPreciseInstantEvents.limit : 10;
var G = "moreMessageTemplate" in this._params.stackConcurrentPreciseInstantEvents ? this._params.stackConcurrentPreciseInstantEvents.moreMessageTemplate : "%0 More Events";
var Q = S <= T.length - 2;
var B = this._band;
var L = function (i) {
return Math.round(B.dateToPixelOffset(i));
};
var O = function (i) {
var r = {url: i.getIcon()};
if (r.url == null) {
r.url = j.defaultStackIcon;
r.width = j.defaultStackIconWidth;
r.height = j.defaultStackIconHeight;
r.className = "timeline-event-icon-stack timeline-event-icon-default";
} else {
r.width = i.getProperty("iconWidth") || j.customIconWidth;
r.height = i.getProperty("iconHeight") || j.customIconHeight;
r.className = "timeline-event-icon-stack";
}
return r;
};
var C = O(T[0]);
var V = 5;
var D = 0;
var g = 0;
var p = 0;
var U = 0;
var l = [];
for (var n = 0;
n < T.length && (!Q || n < S);
n++) {
var b = T[n];
var a = b.getText();
var X = O(b);
var W = this._frc.computeSize(a);
var K = {text: a, iconData: X, labelSize: W, iconLeft: C.width + n * V - X.width};
K.labelLeft = C.width + n * V + j.iconLabelGap;
K.top = p;
l.push(K);
D = Math.min(D, K.iconLeft);
p += W.height;
g = Math.max(g, K.labelLeft + W.width);
U = Math.max(U, K.top + X.height);
}
if (Q) {
var e = String.substitute(G, [T.length - S]);
var H = this._frc.computeSize(e);
var J = C.width + (S - 1) * V + j.iconLabelGap;
var m = p;
p += H.height;
g = Math.max(g, J + H.width);
}
g += j.labelRightMargin;
p += j.labelBottomMargin;
U += j.iconBottomMargin;
var F = L(T[0].getStart());
var Y = [];
var N = Math.ceil(Math.max(U, p) / j.trackHeight);
var M = C.width + (T.length - 1) * V;
for (var n = 0;
n < N;
n++) {
Y.push({start: D, end: M});
}
var f = Math.ceil(p / j.trackHeight);
for (var n = 0;
n < f;
n++) {
var P = Y[n];
P.end = Math.max(P.end, g);
}
var k = this._fitTracks(F, Y);
var Z = k * j.trackHeight + j.trackOffset;
var q = this._timeline.getDocument().createElement("div");
q.className = "timeline-event-icon-stack";
q.style.position = "absolute";
q.style.overflow = "visible";
q.style.left = F + "px";
q.style.top = Z + "px";
q.style.width = M + "px";
q.style.height = U + "px";
q.innerHTML = "<div style='position: relative'></div>";
this._eventLayer.appendChild(q);
var I = this;
var R = function (r) {
try {
var w = parseInt(this.getAttribute("index"));
var u = q.firstChild.childNodes;
for (var s = 0;
s < u.length;
s++) {
var v = u[s];
if (s == w) {
v.style.zIndex = u.length;
} else {
v.style.zIndex = u.length - s;
}
}
} catch (t) {
}
};
var d = function (u) {
var w = l[u];
var r = T[u];
var i = r.getProperty("tooltip") || r.getText();
var v = I._paintEventLabel({tooltip: i}, {text: w.text}, F + w.labelLeft, Z + w.top, w.labelSize.width, w.labelSize.height, c);
v.elmt.setAttribute("index", u);
v.elmt.onmouseover = R;
var t = SimileAjax.Graphics.createTranslucentImage(w.iconData.url);
var s = I._timeline.getDocument().createElement("div");
s.className = "timeline-event-icon" + ("className" in w.iconData ? (" " + w.iconData.className) : "");
s.style.left = w.iconLeft + "px";
s.style.top = w.top + "px";
s.style.zIndex = (l.length - u);
s.appendChild(t);
s.setAttribute("index", u);
s.onmouseover = R;
q.firstChild.appendChild(s);
var x = function (z, y, AA) {
return I._onClickInstantEvent(v.elmt, y, r);
};
SimileAjax.DOM.registerEvent(s, "mousedown", x);
SimileAjax.DOM.registerEvent(v.elmt, "mousedown", x);
I._eventIdToElmt[r.getID()] = s;
};
for (var n = 0;
n < l.length;
n++) {
d(n);
}
if (Q) {
var o = T.slice(S);
var A = this._paintEventLabel({tooltip: e}, {text: e}, F + J, Z + m, H.width, H.height, c);
var h = function (r, i, s) {
return I._onClickMultiplePreciseInstantEvent(A.elmt, i, o);
};
SimileAjax.DOM.registerEvent(A.elmt, "mousedown", h);
for (var n = 0;
n < o.length;
n++) {
this._eventIdToElmt[o[n].getID()] = A.elmt;
}
}
};
Timeline.CompactEventPainter.prototype.paintImpreciseInstantEvent = function (I, G, B, A) {
var C = {tooltip: I.getProperty("tooltip") || I.getText()};
var E = {start: I.getStart(), end: I.getEnd(), latestStart: I.getLatestStart(), earliestEnd: I.getEarliestEnd(), isInstant: true};
var F = {url: I.getIcon()};
if (F.url == null) {
F = null;
} else {
F.width = I.getProperty("iconWidth") || G.customIconWidth;
F.height = I.getProperty("iconHeight") || G.customIconHeight;
}
var K = {text: I.getText(), color: I.getTextColor() || I.getColor(), className: I.getClassName()};
var H = this.paintTapeIconLabel(I.getStart(), C, E, F, K, G, B, A);
var J = this;
var D = F != null ? function (M, L, N) {
return J._onClickInstantEvent(H.iconElmtData.elmt, L, I);
} : function (M, L, N) {
return J._onClickInstantEvent(H.labelElmtData.elmt, L, I);
};
SimileAjax.DOM.registerEvent(H.labelElmtData.elmt, "mousedown", D);
SimileAjax.DOM.registerEvent(H.impreciseTapeElmtData.elmt, "mousedown", D);
if (F != null) {
SimileAjax.DOM.registerEvent(H.iconElmtData.elmt, "mousedown", D);
this._eventIdToElmt[I.getID()] = H.iconElmtData.elmt;
} else {
this._eventIdToElmt[I.getID()] = H.labelElmtData.elmt;
}
};
Timeline.CompactEventPainter.prototype.paintPreciseDurationEvent = function (I, G, B, A) {
var C = {tooltip: I.getProperty("tooltip") || I.getText()};
var E = {start: I.getStart(), end: I.getEnd(), isInstant: false};
var F = {url: I.getIcon()};
if (F.url == null) {
F = null;
} else {
F.width = I.getProperty("iconWidth") || G.customIconWidth;
F.height = I.getProperty("iconHeight") || G.customIconHeight;
}
var K = {text: I.getText(), color: I.getTextColor() || I.getColor(), className: I.getClassName()};
var H = this.paintTapeIconLabel(I.getLatestStart(), C, E, F, K, G, B, A);
var J = this;
var D = F != null ? function (M, L, N) {
return J._onClickInstantEvent(H.iconElmtData.elmt, L, I);
} : function (M, L, N) {
return J._onClickInstantEvent(H.labelElmtData.elmt, L, I);
};
SimileAjax.DOM.registerEvent(H.labelElmtData.elmt, "mousedown", D);
SimileAjax.DOM.registerEvent(H.tapeElmtData.elmt, "mousedown", D);
if (F != null) {
SimileAjax.DOM.registerEvent(H.iconElmtData.elmt, "mousedown", D);
this._eventIdToElmt[I.getID()] = H.iconElmtData.elmt;
} else {
this._eventIdToElmt[I.getID()] = H.labelElmtData.elmt;
}
};
Timeline.CompactEventPainter.prototype.paintImpreciseDurationEvent = function (I, G, B, A) {
var C = {tooltip: I.getProperty("tooltip") || I.getText()};
var E = {start: I.getStart(), end: I.getEnd(), latestStart: I.getLatestStart(), earliestEnd: I.getEarliestEnd(), isInstant: false};
var F = {url: I.getIcon()};
if (F.url == null) {
F = null;
} else {
F.width = I.getProperty("iconWidth") || G.customIconWidth;
F.height = I.getProperty("iconHeight") || G.customIconHeight;
}
var K = {text: I.getText(), color: I.getTextColor() || I.getColor(), className: I.getClassName()};
var H = this.paintTapeIconLabel(I.getLatestStart(), C, E, F, K, G, B, A);
var J = this;
var D = F != null ? function (M, L, N) {
return J._onClickInstantEvent(H.iconElmtData.elmt, L, I);
} : function (M, L, N) {
return J._onClickInstantEvent(H.labelElmtData.elmt, L, I);
};
SimileAjax.DOM.registerEvent(H.labelElmtData.elmt, "mousedown", D);
SimileAjax.DOM.registerEvent(H.tapeElmtData.elmt, "mousedown", D);
if (F != null) {
SimileAjax.DOM.registerEvent(H.iconElmtData.elmt, "mousedown", D);
this._eventIdToElmt[I.getID()] = H.iconElmtData.elmt;
} else {
this._eventIdToElmt[I.getID()] = H.labelElmtData.elmt;
}
};
Timeline.CompactEventPainter.prototype.paintTapeIconLabel = function (V, O, S, I, a, X, c, Z) {
var R = this._band;
var F = function (e) {
return Math.round(R.dateToPixelOffset(e));
};
var d = F(V);
var W = [];
var b = 0;
var B = 0;
var C = 0;
if (S != null) {
b = X.tapeHeight + X.tapeBottomMargin;
B = Math.ceil(X.tapeHeight / X.trackHeight);
var A = F(S.end) - d;
var L = F(S.start) - d;
for (var Q = 0;
Q < B;
Q++) {
W.push({start: L, end: A});
}
C = X.trackHeight - (b % X.tapeHeight);
}
var N = 0;
var U = 0;
if (I != null) {
if ("iconAlign" in I && I.iconAlign == "center") {
N = -Math.floor(I.width / 2);
}
U = N + I.width + X.iconLabelGap;
if (B > 0) {
W[B - 1].end = Math.max(W[B - 1].end, U);
}
var E = I.height + X.iconBottomMargin + C;
while (E > 0) {
W.push({start: N, end: U});
E -= X.trackHeight;
}
}
var P = a.text;
var H = this._frc.computeSize(P);
var M = H.height + X.labelBottomMargin + C;
var J = U + H.width + X.labelRightMargin;
if (B > 0) {
W[B - 1].end = Math.max(W[B - 1].end, J);
}
for (var Y = 0;
M > 0;
Y++) {
if (B + Y < W.length) {
var T = W[B + Y];
T.end = J;
} else {
W.push({start: 0, end: J});
}
M -= X.trackHeight;
}
var G = this._fitTracks(d, W);
var K = G * X.trackHeight + X.trackOffset;
var D = {};
D.labelElmtData = this._paintEventLabel(O, a, d + U, K + b, H.width, H.height, c);
if (S != null) {
if ("latestStart" in S || "earliestEnd" in S) {
D.impreciseTapeElmtData = this._paintEventTape(O, S, X.tapeHeight, K, F(S.start), F(S.end), c.event.duration.impreciseColor, c.event.duration.impreciseOpacity, X, c);
}
if (!S.isInstant && "start" in S && "end" in S) {
D.tapeElmtData = this._paintEventTape(O, S, X.tapeHeight, K, d, F("earliestEnd" in S ? S.earliestEnd : S.end), S.color, 100, X, c);
}
}
if (I != null) {
D.iconElmtData = this._paintEventIcon(O, I, K + b, d + N, X, c);
}
return D;
};
Timeline.CompactEventPainter.prototype._fitTracks = function (F, C) {
var H;
for (H = 0;
H < this._tracks.length;
H++) {
var E = true;
for (var B = 0;
B < C.length && (H + B) < this._tracks.length;
B++) {
var G = this._tracks[H + B];
var A = C[B];
if (F + A.start < G) {
E = false;
break;
}
}
if (E) {
break;
}
}
for (var D = 0;
D < C.length;
D++) {
this._tracks[H + D] = F + C[D].end;
}
return H;
};
Timeline.CompactEventPainter.prototype._paintEventIcon = function (C, D, H, G, E, F) {
var B = SimileAjax.Graphics.createTranslucentImage(D.url);
var A = this._timeline.getDocument().createElement("div");
A.className = "timeline-event-icon" + ("className" in D ? (" " + D.className) : "");
A.style.left = G + "px";
A.style.top = H + "px";
A.appendChild(B);
if ("tooltip" in C && typeof C.tooltip == "string") {
A.title = C.tooltip;
}
this._eventLayer.appendChild(A);
return{left: G, top: H, width: E.iconWidth, height: E.iconHeight, elmt: A};
};
Timeline.CompactEventPainter.prototype._paintEventLabel = function (E, I, C, F, A, G, D) {
var H = this._timeline.getDocument();
var B = H.createElement("div");
B.className = "timeline-event-label";
B.style.left = C + "px";
B.style.width = (A + 1) + "px";
B.style.top = F + "px";
B.innerHTML = I.text;
if ("tooltip" in E && typeof E.tooltip == "string") {
B.title = E.tooltip;
}
if ("color" in I && typeof I.color == "string") {
B.style.color = I.color;
}
if ("className" in I && typeof I.className == "string") {
B.className += " " + I.className;
}
this._eventLayer.appendChild(B);
return{left: C, top: F, width: A, height: G, elmt: B};
};
Timeline.CompactEventPainter.prototype._paintEventTape = function (G, H, K, J, D, A, E, C, I, F) {
var B = A - D;
var L = this._timeline.getDocument().createElement("div");
L.className = "timeline-event-tape";
L.style.left = D + "px";
L.style.top = J + "px";
L.style.width = B + "px";
L.style.height = K + "px";
if ("tooltip" in G && typeof G.tooltip == "string") {
L.title = G.tooltip;
}
if (E != null && typeof H.color == "string") {
L.style.backgroundColor = E;
}
if ("backgroundImage" in H && typeof H.backgroundImage == "string") {
L.style.backgroundImage = "url(" + backgroundImage + ")";
L.style.backgroundRepeat = ("backgroundRepeat" in H && typeof H.backgroundRepeat == "string") ? H.backgroundRepeat : "repeat";
}
SimileAjax.Graphics.setOpacity(L, C);
if ("className" in H && typeof H.className == "string") {
L.className += " " + H.className;
}
this._eventLayer.appendChild(L);
return{left: D, top: J, width: B, height: K, elmt: L};
};
Timeline.CompactEventPainter.prototype._createHighlightDiv = function (A, C, E) {
if (A >= 0) {
var D = this._timeline.getDocument();
var G = E.event;
var B = G.highlightColors[Math.min(A, G.highlightColors.length - 1)];
var F = D.createElement("div");
F.style.position = "absolute";
F.style.overflow = "hidden";
F.style.left = (C.left - 2) + "px";
F.style.width = (C.width + 4) + "px";
F.style.top = (C.top - 2) + "px";
F.style.height = (C.height + 4) + "px";
this._highlightLayer.appendChild(F);
}
};
Timeline.CompactEventPainter.prototype._onClickMultiplePreciseInstantEvent = function (E, A, B) {
var F = SimileAjax.DOM.getPageCoordinates(E);
this._showBubble(F.left + Math.ceil(E.offsetWidth / 2), F.top + Math.ceil(E.offsetHeight / 2), B);
var D = [];
for (var C = 0;
C < B.length;
C++) {
D.push(B[C].getID());
}
this._fireOnSelect(D);
A.cancelBubble = true;
SimileAjax.DOM.cancelEvent(A);
return false;
};
Timeline.CompactEventPainter.prototype._onClickInstantEvent = function (C, A, B) {
var D = SimileAjax.DOM.getPageCoordinates(C);
this._showBubble(D.left + Math.ceil(C.offsetWidth / 2), D.top + Math.ceil(C.offsetHeight / 2), [B]);
this._fireOnSelect([B.getID()]);
A.cancelBubble = true;
SimileAjax.DOM.cancelEvent(A);
return false;
};
Timeline.CompactEventPainter.prototype._onClickDurationEvent = function (F, B, C) {
if ("pageX" in B) {
var A = B.pageX;
var E = B.pageY;
} else {
var D = SimileAjax.DOM.getPageCoordinates(F);
var A = B.offsetX + D.left;
var E = B.offsetY + D.top;
}
this._showBubble(A, E, [C]);
this._fireOnSelect([C.getID()]);
B.cancelBubble = true;
SimileAjax.DOM.cancelEvent(B);
return false;
};
Timeline.CompactEventPainter.prototype.showBubble = function (A) {
var B = this._eventIdToElmt[A.getID()];
if (B) {
var C = SimileAjax.DOM.getPageCoordinates(B);
this._showBubble(C.left + B.offsetWidth / 2, C.top + B.offsetHeight / 2, [A]);
}
};
Timeline.CompactEventPainter.prototype._showBubble = function (A, F, B) {
var E = document.createElement("div");
B = ("fillInfoBubble" in B) ? [B] : B;
for (var D = 0;
D < B.length;
D++) {
var C = document.createElement("div");
E.appendChild(C);
B[D].fillInfoBubble(C, this._params.theme, this._band.getLabeller());
}
SimileAjax.WindowManager.cancelPopups();
SimileAjax.Graphics.createBubbleForContentAndPoint(E, A, F, this._params.theme.event.bubble.width);
};
Timeline.CompactEventPainter.prototype._fireOnSelect = function (B) {
for (var A = 0;
A < this._onSelectListeners.length;
A++) {
this._onSelectListeners[A](B);
}
};
/* decorators.js */
Timeline.SpanHighlightDecorator = function (A) {
this._unit = A.unit != null ? A.unit : SimileAjax.NativeDateUnit;
this._startDate = (typeof A.startDate == "string") ? this._unit.parseFromObject(A.startDate) : A.startDate;
this._endDate = (typeof A.endDate == "string") ? this._unit.parseFromObject(A.endDate) : A.endDate;
this._startLabel = A.startLabel != null ? A.startLabel : "";
this._endLabel = A.endLabel != null ? A.endLabel : "";
this._color = A.color;
this._cssClass = A.cssClass != null ? A.cssClass : null;
this._opacity = A.opacity != null ? A.opacity : 100;
this._zIndex = (A.inFront != null && A.inFront) ? 113 : 10;
};
Timeline.SpanHighlightDecorator.prototype.initialize = function (B, A) {
this._band = B;
this._timeline = A;
this._layerDiv = null;
};
Timeline.SpanHighlightDecorator.prototype.paint = function () {
if (this._layerDiv != null) {
this._band.removeLayerDiv(this._layerDiv);
}
this._layerDiv = this._band.createLayerDiv(this._zIndex);
this._layerDiv.setAttribute("name", "span-highlight-decorator");
this._layerDiv.style.display = "none";
var E = this._band.getMinDate();
var A = this._band.getMaxDate();
if (this._unit.compare(this._startDate, A) < 0 && this._unit.compare(this._endDate, E) > 0) {
E = this._unit.later(E, this._startDate);
A = this._unit.earlier(A, this._endDate);
var F = this._band.dateToPixelOffset(E);
var I = this._band.dateToPixelOffset(A);
var H = this._timeline.getDocument();
var K = function () {
var L = H.createElement("table");
L.insertRow(0).insertCell(0);
return L;
};
var B = H.createElement("div");
B.className = "timeline-highlight-decorator";
if (this._cssClass) {
B.className += " " + this._cssClass;
}
if (this._color != null) {
B.style.backgroundColor = this._color;
}
if (this._opacity < 100) {
SimileAjax.Graphics.setOpacity(B, this._opacity);
}
this._layerDiv.appendChild(B);
var J = K();
J.className = "timeline-highlight-label timeline-highlight-label-start";
var C = J.rows[0].cells[0];
C.innerHTML = this._startLabel;
if (this._cssClass) {
C.className = "label_" + this._cssClass;
}
this._layerDiv.appendChild(J);
var G = K();
G.className = "timeline-highlight-label timeline-highlight-label-end";
var D = G.rows[0].cells[0];
D.innerHTML = this._endLabel;
if (this._cssClass) {
D.className = "label_" + this._cssClass;
}
this._layerDiv.appendChild(G);
if (this._timeline.isHorizontal()) {
B.style.left = F + "px";
B.style.width = (I - F) + "px";
J.style.right = (this._band.getTotalViewLength() - F) + "px";
J.style.width = (this._startLabel.length) + "em";
G.style.left = I + "px";
G.style.width = (this._endLabel.length) + "em";
} else {
B.style.top = F + "px";
B.style.height = (I - F) + "px";
J.style.bottom = F + "px";
J.style.height = "1.5px";
G.style.top = I + "px";
G.style.height = "1.5px";
}
}
this._layerDiv.style.display = "block";
};
Timeline.SpanHighlightDecorator.prototype.softPaint = function () {
};
Timeline.PointHighlightDecorator = function (A) {
this._unit = A.unit != null ? A.unit : SimileAjax.NativeDateUnit;
this._date = (typeof A.date == "string") ? this._unit.parseFromObject(A.date) : A.date;
this._width = A.width != null ? A.width : 10;
this._color = A.color;
this._cssClass = A.cssClass != null ? A.cssClass : "";
this._opacity = A.opacity != null ? A.opacity : 100;
};
Timeline.PointHighlightDecorator.prototype.initialize = function (B, A) {
this._band = B;
this._timeline = A;
this._layerDiv = null;
};
Timeline.PointHighlightDecorator.prototype.paint = function () {
if (this._layerDiv != null) {
this._band.removeLayerDiv(this._layerDiv);
}
this._layerDiv = this._band.createLayerDiv(10);
this._layerDiv.setAttribute("name", "span-highlight-decorator");
this._layerDiv.style.display = "none";
var C = this._band.getMinDate();
var E = this._band.getMaxDate();
if (this._unit.compare(this._date, E) < 0 && this._unit.compare(this._date, C) > 0) {
var A = this._band.dateToPixelOffset(this._date);
var B = A - Math.round(this._width / 2);
var D = this._timeline.getDocument();
var F = D.createElement("div");
F.className = "timeline-highlight-point-decorator";
F.className += " " + this._cssClass;
if (this._color != null) {
F.style.backgroundColor = this._color;
}
if (this._opacity < 100) {
SimileAjax.Graphics.setOpacity(F, this._opacity);
}
this._layerDiv.appendChild(F);
if (this._timeline.isHorizontal()) {
F.style.left = B + "px";
F.style.width = this._width;
} else {
F.style.top = B + "px";
F.style.height = this._width;
}
}
this._layerDiv.style.display = "block";
};
Timeline.PointHighlightDecorator.prototype.softPaint = function () {
};
/* detailed-painter.js */
Timeline.DetailedEventPainter = function (A) {
this._params = A;
this._onSelectListeners = [];
this._filterMatcher = null;
this._highlightMatcher = null;
this._frc = null;
this._eventIdToElmt = {};
};
Timeline.DetailedEventPainter.prototype.initialize = function (B, A) {
this._band = B;
this._timeline = A;
this._backLayer = null;
this._eventLayer = null;
this._lineLayer = null;
this._highlightLayer = null;
this._eventIdToElmt = null;
};
Timeline.DetailedEventPainter.prototype.getType = function () {
return"detailed";
};
Timeline.DetailedEventPainter.prototype.addOnSelectListener = function (A) {
this._onSelectListeners.push(A);
};
Timeline.DetailedEventPainter.prototype.removeOnSelectListener = function (B) {
for (var A = 0;
A < this._onSelectListeners.length;
A++) {
if (this._onSelectListeners[A] == B) {
this._onSelectListeners.splice(A, 1);
break;
}
}
};
Timeline.DetailedEventPainter.prototype.getFilterMatcher = function () {
return this._filterMatcher;
};
Timeline.DetailedEventPainter.prototype.setFilterMatcher = function (A) {
this._filterMatcher = A;
};
Timeline.DetailedEventPainter.prototype.getHighlightMatcher = function () {
return this._highlightMatcher;
};
Timeline.DetailedEventPainter.prototype.setHighlightMatcher = function (A) {
this._highlightMatcher = A;
};
Timeline.DetailedEventPainter.prototype.paint = function () {
var C = this._band.getEventSource();
if (C == null) {
return;
}
this._eventIdToElmt = {};
this._prepareForPainting();
var I = this._params.theme.event;
var G = Math.max(I.track.height, this._frc.getLineHeight());
var F = {trackOffset: Math.round(this._band.getViewWidth() / 2 - G / 2), trackHeight: G, trackGap: I.track.gap, trackIncrement: G + I.track.gap, icon: I.instant.icon, iconWidth: I.instant.iconWidth, iconHeight: I.instant.iconHeight, labelWidth: I.label.width};
var D = this._band.getMinDate();
var B = this._band.getMaxDate();
var J = (this._filterMatcher != null) ? this._filterMatcher : function (K) {
return true;
};
var A = (this._highlightMatcher != null) ? this._highlightMatcher : function (K) {
return -1;
};
var E = C.getEventReverseIterator(D, B);
while (E.hasNext()) {
var H = E.next();
if (J(H)) {
this.paintEvent(H, F, this._params.theme, A(H));
}
}
this._highlightLayer.style.display = "block";
this._lineLayer.style.display = "block";
this._eventLayer.style.display = "block";
this._band.updateEventTrackInfo(this._lowerTracks.length + this._upperTracks.length, F.trackIncrement);
};
Timeline.DetailedEventPainter.prototype.softPaint = function () {
};
Timeline.DetailedEventPainter.prototype._prepareForPainting = function () {
var B = this._band;
if (this._backLayer == null) {
this._backLayer = this._band.createLayerDiv(0, "timeline-band-events");
this._backLayer.style.visibility = "hidden";
var A = document.createElement("span");
A.className = "timeline-event-label";
this._backLayer.appendChild(A);
this._frc = SimileAjax.Graphics.getFontRenderingContext(A);
}
this._frc.update();
this._lowerTracks = [];
this._upperTracks = [];
if (this._highlightLayer != null) {
B.removeLayerDiv(this._highlightLayer);
}
this._highlightLayer = B.createLayerDiv(105, "timeline-band-highlights");
this._highlightLayer.style.display = "none";
if (this._lineLayer != null) {
B.removeLayerDiv(this._lineLayer);
}
this._lineLayer = B.createLayerDiv(110, "timeline-band-lines");
this._lineLayer.style.display = "none";
if (this._eventLayer != null) {
B.removeLayerDiv(this._eventLayer);
}
this._eventLayer = B.createLayerDiv(110, "timeline-band-events");
this._eventLayer.style.display = "none";
};
Timeline.DetailedEventPainter.prototype.paintEvent = function (B, C, D, A) {
if (B.isInstant()) {
this.paintInstantEvent(B, C, D, A);
} else {
this.paintDurationEvent(B, C, D, A);
}
};
Timeline.DetailedEventPainter.prototype.paintInstantEvent = function (B, C, D, A) {
if (B.isImprecise()) {
this.paintImpreciseInstantEvent(B, C, D, A);
} else {
this.paintPreciseInstantEvent(B, C, D, A);
}
};
Timeline.DetailedEventPainter.prototype.paintDurationEvent = function (B, C, D, A) {
if (B.isImprecise()) {
this.paintImpreciseDurationEvent(B, C, D, A);
} else {
this.paintPreciseDurationEvent(B, C, D, A);
}
};
Timeline.DetailedEventPainter.prototype.paintPreciseInstantEvent = function (L, P, S, Q) {
var T = this._timeline.getDocument();
var J = L.getText();
var G = L.getStart();
var H = Math.round(this._band.dateToPixelOffset(G));
var A = Math.round(H + P.iconWidth / 2);
var C = Math.round(H - P.iconWidth / 2);
var E = this._frc.computeSize(J);
var F = this._findFreeTrackForSolid(A, H);
var B = this._paintEventIcon(L, F, C, P, S);
var K = A + S.event.label.offsetFromLine;
var O = F;
var D = this._getTrackData(F);
if (Math.min(D.solid, D.text) >= K + E.width) {
D.solid = C;
D.text = K;
} else {
D.solid = C;
K = H + S.event.label.offsetFromLine;
O = this._findFreeTrackForText(F, K + E.width, function (U) {
U.line = H - 2;
});
this._getTrackData(O).text = C;
this._paintEventLine(L, H, F, O, P, S);
}
var N = Math.round(P.trackOffset + O * P.trackIncrement + P.trackHeight / 2 - E.height / 2);
var R = this._paintEventLabel(L, J, K, N, E.width, E.height, S);
var M = this;
var I = function (V, U, W) {
return M._onClickInstantEvent(B.elmt, U, L);
};
SimileAjax.DOM.registerEvent(B.elmt, "mousedown", I);
SimileAjax.DOM.registerEvent(R.elmt, "mousedown", I);
this._createHighlightDiv(Q, B, S);
this._eventIdToElmt[L.getID()] = B.elmt;
};
Timeline.DetailedEventPainter.prototype.paintImpreciseInstantEvent = function (O, S, W, T) {
var X = this._timeline.getDocument();
var M = O.getText();
var I = O.getStart();
var U = O.getEnd();
var K = Math.round(this._band.dateToPixelOffset(I));
var B = Math.round(this._band.dateToPixelOffset(U));
var A = Math.round(K + S.iconWidth / 2);
var D = Math.round(K - S.iconWidth / 2);
var G = this._frc.computeSize(M);
var H = this._findFreeTrackForSolid(B, K);
var E = this._paintEventTape(O, H, K, B, W.event.instant.impreciseColor, W.event.instant.impreciseOpacity, S, W);
var C = this._paintEventIcon(O, H, D, S, W);
var F = this._getTrackData(H);
F.solid = D;
var N = A + W.event.label.offsetFromLine;
var J = N + G.width;
var R;
if (J < B) {
R = H;
} else {
N = K + W.event.label.offsetFromLine;
J = N + G.width;
R = this._findFreeTrackForText(H, J, function (Y) {
Y.line = K - 2;
});
this._getTrackData(R).text = D;
this._paintEventLine(O, K, H, R, S, W);
}
var Q = Math.round(S.trackOffset + R * S.trackIncrement + S.trackHeight / 2 - G.height / 2);
var V = this._paintEventLabel(O, M, N, Q, G.width, G.height, W);
var P = this;
var L = function (Z, Y, a) {
return P._onClickInstantEvent(C.elmt, Y, O);
};
SimileAjax.DOM.registerEvent(C.elmt, "mousedown", L);
SimileAjax.DOM.registerEvent(E.elmt, "mousedown", L);
SimileAjax.DOM.registerEvent(V.elmt, "mousedown", L);
this._createHighlightDiv(T, C, W);
this._eventIdToElmt[O.getID()] = C.elmt;
};
Timeline.DetailedEventPainter.prototype.paintPreciseDurationEvent = function (K, O, T, Q) {
var U = this._timeline.getDocument();
var I = K.getText();
var E = K.getStart();
var R = K.getEnd();
var F = Math.round(this._band.dateToPixelOffset(E));
var A = Math.round(this._band.dateToPixelOffset(R));
var C = this._frc.computeSize(I);
var D = this._findFreeTrackForSolid(A);
var P = K.getColor();
P = P != null ? P : T.event.duration.color;
var B = this._paintEventTape(K, D, F, A, P, 100, O, T);
var H = this._getTrackData(D);
H.solid = F;
var J = F + T.event.label.offsetFromLine;
var N = this._findFreeTrackForText(D, J + C.width, function (V) {
V.line = F - 2;
});
this._getTrackData(N).text = F - 2;
this._paintEventLine(K, F, D, N, O, T);
var M = Math.round(O.trackOffset + N * O.trackIncrement + O.trackHeight / 2 - C.height / 2);
var S = this._paintEventLabel(K, I, J, M, C.width, C.height, T);
var L = this;
var G = function (W, V, X) {
return L._onClickDurationEvent(B.elmt, V, K);
};
SimileAjax.DOM.registerEvent(B.elmt, "mousedown", G);
SimileAjax.DOM.registerEvent(S.elmt, "mousedown", G);
this._createHighlightDiv(Q, B, T);
this._eventIdToElmt[K.getID()] = B.elmt;
};
Timeline.DetailedEventPainter.prototype.paintImpreciseDurationEvent = function (M, T, Y, V) {
var Z = this._timeline.getDocument();
var K = M.getText();
var G = M.getStart();
var S = M.getLatestStart();
var W = M.getEnd();
var O = M.getEarliestEnd();
var H = Math.round(this._band.dateToPixelOffset(G));
var E = Math.round(this._band.dateToPixelOffset(S));
var A = Math.round(this._band.dateToPixelOffset(W));
var F = Math.round(this._band.dateToPixelOffset(O));
var C = this._frc.computeSize(K);
var D = this._findFreeTrackForSolid(A);
var U = M.getColor();
U = U != null ? U : Y.event.duration.color;
var R = this._paintEventTape(M, D, H, A, Y.event.duration.impreciseColor, Y.event.duration.impreciseOpacity, T, Y);
var B = this._paintEventTape(M, D, E, F, U, 100, T, Y);
var J = this._getTrackData(D);
J.solid = H;
var L = E + Y.event.label.offsetFromLine;
var Q = this._findFreeTrackForText(D, L + C.width, function (a) {
a.line = E - 2;
});
this._getTrackData(Q).text = E - 2;
this._paintEventLine(M, E, D, Q, T, Y);
var P = Math.round(T.trackOffset + Q * T.trackIncrement + T.trackHeight / 2 - C.height / 2);
var X = this._paintEventLabel(M, K, L, P, C.width, C.height, Y);
var N = this;
var I = function (b, a, c) {
return N._onClickDurationEvent(B.elmt, a, M);
};
SimileAjax.DOM.registerEvent(B.elmt, "mousedown", I);
SimileAjax.DOM.registerEvent(X.elmt, "mousedown", I);
this._createHighlightDiv(V, B, Y);
this._eventIdToElmt[M.getID()] = B.elmt;
};
Timeline.DetailedEventPainter.prototype._findFreeTrackForSolid = function (D, A) {
for (var C = 0;
true;
C++) {
if (C < this._lowerTracks.length) {
var B = this._lowerTracks[C];
if (Math.min(B.solid, B.text) > D && (!(A) || B.line > A)) {
return C;
}
} else {
this._lowerTracks.push({solid: Number.POSITIVE_INFINITY, text: Number.POSITIVE_INFINITY, line: Number.POSITIVE_INFINITY});
return C;
}
if (C < this._upperTracks.length) {
var B = this._upperTracks[C];
if (Math.min(B.solid, B.text) > D && (!(A) || B.line > A)) {
return -1 - C;
}
} else {
this._upperTracks.push({solid: Number.POSITIVE_INFINITY, text: Number.POSITIVE_INFINITY, line: Number.POSITIVE_INFINITY});
return -1 - C;
}
}
};
Timeline.DetailedEventPainter.prototype._findFreeTrackForText = function (C, A, I) {
var B;
var E;
var F;
var H;
if (C < 0) {
B = true;
F = -C;
E = this._findFreeUpperTrackForText(F, A);
H = -1 - E;
} else {
if (C > 0) {
B = false;
F = C + 1;
E = this._findFreeLowerTrackForText(F, A);
H = E;
} else {
var G = this._findFreeUpperTrackForText(0, A);
var J = this._findFreeLowerTrackForText(1, A);
if (J - 1 <= G) {
B = false;
F = 1;
E = J;
H = E;
} else {
B = true;
F = 0;
E = G;
H = -1 - E;
}
}
}
if (B) {
if (E == this._upperTracks.length) {
this._upperTracks.push({solid: Number.POSITIVE_INFINITY, text: Number.POSITIVE_INFINITY, line: Number.POSITIVE_INFINITY});
}
for (var D = F;
D < E;
D++) {
I(this._upperTracks[D]);
}
} else {
if (E == this._lowerTracks.length) {
this._lowerTracks.push({solid: Number.POSITIVE_INFINITY, text: Number.POSITIVE_INFINITY, line: Number.POSITIVE_INFINITY});
}
for (var D = F;
D < E;
D++) {
I(this._lowerTracks[D]);
}
}
return H;
};
Timeline.DetailedEventPainter.prototype._findFreeLowerTrackForText = function (A, C) {
for (;
A < this._lowerTracks.length;
A++) {
var B = this._lowerTracks[A];
if (Math.min(B.solid, B.text) >= C) {
break;
}
}
return A;
};
Timeline.DetailedEventPainter.prototype._findFreeUpperTrackForText = function (A, C) {
for (;
A < this._upperTracks.length;
A++) {
var B = this._upperTracks[A];
if (Math.min(B.solid, B.text) >= C) {
break;
}
}
return A;
};
Timeline.DetailedEventPainter.prototype._getTrackData = function (A) {
return(A < 0) ? this._upperTracks[-A - 1] : this._lowerTracks[A];
};
Timeline.DetailedEventPainter.prototype._paintEventLine = function (J, E, D, A, G, F) {
var H = Math.round(G.trackOffset + D * G.trackIncrement + G.trackHeight / 2);
var I = Math.round(Math.abs(A - D) * G.trackIncrement);
var C = "1px solid " + F.event.label.lineColor;
var B = this._timeline.getDocument().createElement("div");
B.style.position = "absolute";
B.style.left = E + "px";
B.style.width = F.event.label.offsetFromLine + "px";
B.style.height = I + "px";
if (D > A) {
B.style.top = (H - I) + "px";
B.style.borderTop = C;
} else {
B.style.top = H + "px";
B.style.borderBottom = C;
}
B.style.borderLeft = C;
this._lineLayer.appendChild(B);
};
Timeline.DetailedEventPainter.prototype._paintEventIcon = function (J, B, C, F, E) {
var H = J.getIcon();
H = H != null ? H : F.icon;
var G = F.trackOffset + B * F.trackIncrement + F.trackHeight / 2;
var I = Math.round(G - F.iconHeight / 2);
var D = SimileAjax.Graphics.createTranslucentImage(H);
var A = this._timeline.getDocument().createElement("div");
A.style.position = "absolute";
A.style.left = C + "px";
A.style.top = I + "px";
A.appendChild(D);
A.style.cursor = "pointer";
if (J._title != null) {
A.title = J._title;
}
this._eventLayer.appendChild(A);
return{left: C, top: I, width: F.iconWidth, height: F.iconHeight, elmt: A};
};
Timeline.DetailedEventPainter.prototype._paintEventLabel = function (I, J, C, F, A, G, E) {
var H = this._timeline.getDocument();
var K = H.createElement("div");
K.style.position = "absolute";
K.style.left = C + "px";
K.style.width = A + "px";
K.style.top = F + "px";
K.style.height = G + "px";
K.style.backgroundColor = E.event.label.backgroundColor;
SimileAjax.Graphics.setOpacity(K, E.event.label.backgroundOpacity);
this._eventLayer.appendChild(K);
var B = H.createElement("div");
B.style.position = "absolute";
B.style.left = C + "px";
B.style.width = A + "px";
B.style.top = F + "px";
B.innerHTML = J;
B.style.cursor = "pointer";
if (I._title != null) {
B.title = I._title;
}
var D = I.getTextColor();
if (D == null) {
D = I.getColor();
}
if (D != null) {
B.style.color = D;
}
this._eventLayer.appendChild(B);
return{left: C, top: F, width: A, height: G, elmt: B};
};
Timeline.DetailedEventPainter.prototype._paintEventTape = function (L, B, D, A, G, C, I, H) {
var F = A - D;
var E = H.event.tape.height;
var K = I.trackOffset + B * I.trackIncrement + I.trackHeight / 2;
var J = Math.round(K - E / 2);
var M = this._timeline.getDocument().createElement("div");
M.style.position = "absolute";
M.style.left = D + "px";
M.style.width = F + "px";
M.style.top = J + "px";
M.style.height = E + "px";
M.style.backgroundColor = G;
M.style.overflow = "hidden";
M.style.cursor = "pointer";
if (L._title != null) {
M.title = L._title;
}
SimileAjax.Graphics.setOpacity(M, C);
this._eventLayer.appendChild(M);
return{left: D, top: J, width: F, height: E, elmt: M};
};
Timeline.DetailedEventPainter.prototype._createHighlightDiv = function (A, C, E) {
if (A >= 0) {
var D = this._timeline.getDocument();
var G = E.event;
var B = G.highlightColors[Math.min(A, G.highlightColors.length - 1)];
var F = D.createElement("div");
F.style.position = "absolute";
F.style.overflow = "hidden";
F.style.left = (C.left - 2) + "px";
F.style.width = (C.width + 4) + "px";
F.style.top = (C.top - 2) + "px";
F.style.height = (C.height + 4) + "px";
F.style.background = B;
this._highlightLayer.appendChild(F);
}
};
Timeline.DetailedEventPainter.prototype._onClickInstantEvent = function (C, A, B) {
var D = SimileAjax.DOM.getPageCoordinates(C);
this._showBubble(D.left + Math.ceil(C.offsetWidth / 2), D.top + Math.ceil(C.offsetHeight / 2), B);
this._fireOnSelect(B.getID());
A.cancelBubble = true;
SimileAjax.DOM.cancelEvent(A);
return false;
};
Timeline.DetailedEventPainter.prototype._onClickDurationEvent = function (F, B, C) {
if ("pageX" in B) {
var A = B.pageX;
var E = B.pageY;
} else {
var D = SimileAjax.DOM.getPageCoordinates(F);
var A = B.offsetX + D.left;
var E = B.offsetY + D.top;
}
this._showBubble(A, E, C);
this._fireOnSelect(C.getID());
B.cancelBubble = true;
SimileAjax.DOM.cancelEvent(B);
return false;
};
Timeline.DetailedEventPainter.prototype.showBubble = function (A) {
var B = this._eventIdToElmt[A.getID()];
if (B) {
var C = SimileAjax.DOM.getPageCoordinates(B);
this._showBubble(C.left + B.offsetWidth / 2, C.top + B.offsetHeight / 2, A);
}
};
Timeline.DetailedEventPainter.prototype._showBubble = function (B, E, C) {
var D = document.createElement("div");
var A = this._params.theme.event.bubble;
C.fillInfoBubble(D, this._params.theme, this._band.getLabeller());
SimileAjax.WindowManager.cancelPopups();
SimileAjax.Graphics.createBubbleForContentAndPoint(D, B, E, A.width, null, A.maxHeight);
};
Timeline.DetailedEventPainter.prototype._fireOnSelect = function (A) {
for (var B = 0;
B < this._onSelectListeners.length;
B++) {
this._onSelectListeners[B](A);
}
};
/* ether-painters.js */
Timeline.GregorianEtherPainter = function (A) {
this._params = A;
this._theme = A.theme;
this._unit = A.unit;
this._multiple = ("multiple" in A) ? A.multiple : 1;
};
Timeline.GregorianEtherPainter.prototype.initialize = function (C, B) {
this._band = C;
this._timeline = B;
this._backgroundLayer = C.createLayerDiv(0);
this._backgroundLayer.setAttribute("name", "ether-background");
this._backgroundLayer.className = "timeline-ether-bg";
this._markerLayer = null;
this._lineLayer = null;
var D = ("align" in this._params && this._params.align != undefined) ? this._params.align : this._theme.ether.interval.marker[B.isHorizontal() ? "hAlign" : "vAlign"];
var A = ("showLine" in this._params) ? this._params.showLine : this._theme.ether.interval.line.show;
this._intervalMarkerLayout = new Timeline.EtherIntervalMarkerLayout(this._timeline, this._band, this._theme, D, A);
this._highlight = new Timeline.EtherHighlight(this._timeline, this._band, this._theme, this._backgroundLayer);
};
Timeline.GregorianEtherPainter.prototype.setHighlight = function (A, B) {
this._highlight.position(A, B);
};
Timeline.GregorianEtherPainter.prototype.paint = function () {
if (this._markerLayer) {
this._band.removeLayerDiv(this._markerLayer);
}
this._markerLayer = this._band.createLayerDiv(100);
this._markerLayer.setAttribute("name", "ether-markers");
this._markerLayer.style.display = "none";
if (this._lineLayer) {
this._band.removeLayerDiv(this._lineLayer);
}
this._lineLayer = this._band.createLayerDiv(1);
this._lineLayer.setAttribute("name", "ether-lines");
this._lineLayer.style.display = "none";
var C = this._band.getMinDate();
var F = this._band.getMaxDate();
var A = this._band.getTimeZone();
var E = this._band.getLabeller();
SimileAjax.DateTime.roundDownToInterval(C, this._unit, A, this._multiple, this._theme.firstDayOfWeek);
var D = this;
var B = function (G) {
for (var H = 0;
H < D._multiple;
H++) {
SimileAjax.DateTime.incrementByInterval(G, D._unit);
}
};
while (C.getTime() < F.getTime()) {
this._intervalMarkerLayout.createIntervalMarker(C, E, this._unit, this._markerLayer, this._lineLayer);
B(C);
}
this._markerLayer.style.display = "block";
this._lineLayer.style.display = "block";
};
Timeline.GregorianEtherPainter.prototype.softPaint = function () {
};
Timeline.GregorianEtherPainter.prototype.zoom = function (A) {
if (A != 0) {
this._unit += A;
}
};
Timeline.HotZoneGregorianEtherPainter = function (G) {
this._params = G;
this._theme = G.theme;
this._zones = [
{startTime: Number.NEGATIVE_INFINITY, endTime: Number.POSITIVE_INFINITY, unit: G.unit, multiple: 1}
];
for (var F = 0;
F < G.zones.length;
F++) {
var C = G.zones[F];
var E = SimileAjax.DateTime.parseGregorianDateTime(C.start).getTime();
var B = SimileAjax.DateTime.parseGregorianDateTime(C.end).getTime();
for (var D = 0;
D < this._zones.length && B > E;
D++) {
var A = this._zones[D];
if (E < A.endTime) {
if (E > A.startTime) {
this._zones.splice(D, 0, {startTime: A.startTime, endTime: E, unit: A.unit, multiple: A.multiple});
D++;
A.startTime = E;
}
if (B < A.endTime) {
this._zones.splice(D, 0, {startTime: E, endTime: B, unit: C.unit, multiple: (C.multiple) ? C.multiple : 1});
D++;
A.startTime = B;
E = B;
} else {
A.multiple = C.multiple;
A.unit = C.unit;
E = A.endTime;
}
}
}
}
};
Timeline.HotZoneGregorianEtherPainter.prototype.initialize = function (C, B) {
this._band = C;
this._timeline = B;
this._backgroundLayer = C.createLayerDiv(0);
this._backgroundLayer.setAttribute("name", "ether-background");
this._backgroundLayer.className = "timeline-ether-bg";
this._markerLayer = null;
this._lineLayer = null;
var D = ("align" in this._params && this._params.align != undefined) ? this._params.align : this._theme.ether.interval.marker[B.isHorizontal() ? "hAlign" : "vAlign"];
var A = ("showLine" in this._params) ? this._params.showLine : this._theme.ether.interval.line.show;
this._intervalMarkerLayout = new Timeline.EtherIntervalMarkerLayout(this._timeline, this._band, this._theme, D, A);
this._highlight = new Timeline.EtherHighlight(this._timeline, this._band, this._theme, this._backgroundLayer);
};
Timeline.HotZoneGregorianEtherPainter.prototype.setHighlight = function (A, B) {
this._highlight.position(A, B);
};
Timeline.HotZoneGregorianEtherPainter.prototype.paint = function () {
if (this._markerLayer) {
this._band.removeLayerDiv(this._markerLayer);
}
this._markerLayer = this._band.createLayerDiv(100);
this._markerLayer.setAttribute("name", "ether-markers");
this._markerLayer.style.display = "none";
if (this._lineLayer) {
this._band.removeLayerDiv(this._lineLayer);
}
this._lineLayer = this._band.createLayerDiv(1);
this._lineLayer.setAttribute("name", "ether-lines");
this._lineLayer.style.display = "none";
var C = this._band.getMinDate();
var A = this._band.getMaxDate();
var I = this._band.getTimeZone();
var L = this._band.getLabeller();
var B = this;
var J = function (N, M) {
for (var O = 0;
O < M.multiple;
O++) {
SimileAjax.DateTime.incrementByInterval(N, M.unit);
}
};
var D = 0;
while (D < this._zones.length) {
if (C.getTime() < this._zones[D].endTime) {
break;
}
D++;
}
var E = this._zones.length - 1;
while (E >= 0) {
if (A.getTime() > this._zones[E].startTime) {
break;
}
E--;
}
for (var H = D;
H <= E;
H++) {
var G = this._zones[H];
var K = new Date(Math.max(C.getTime(), G.startTime));
var F = new Date(Math.min(A.getTime(), G.endTime));
SimileAjax.DateTime.roundDownToInterval(K, G.unit, I, G.multiple, this._theme.firstDayOfWeek);
SimileAjax.DateTime.roundUpToInterval(F, G.unit, I, G.multiple, this._theme.firstDayOfWeek);
while (K.getTime() < F.getTime()) {
this._intervalMarkerLayout.createIntervalMarker(K, L, G.unit, this._markerLayer, this._lineLayer);
J(K, G);
}
}
this._markerLayer.style.display = "block";
this._lineLayer.style.display = "block";
};
Timeline.HotZoneGregorianEtherPainter.prototype.softPaint = function () {
};
Timeline.HotZoneGregorianEtherPainter.prototype.zoom = function (A) {
if (A != 0) {
for (var B = 0;
B < this._zones.length;
++B) {
if (this._zones[B]) {
this._zones[B].unit += A;
}
}
}
};
Timeline.YearCountEtherPainter = function (A) {
this._params = A;
this._theme = A.theme;
this._startDate = SimileAjax.DateTime.parseGregorianDateTime(A.startDate);
this._multiple = ("multiple" in A) ? A.multiple : 1;
};
Timeline.YearCountEtherPainter.prototype.initialize = function (C, B) {
this._band = C;
this._timeline = B;
this._backgroundLayer = C.createLayerDiv(0);
this._backgroundLayer.setAttribute("name", "ether-background");
this._backgroundLayer.className = "timeline-ether-bg";
this._markerLayer = null;
this._lineLayer = null;
var D = ("align" in this._params) ? this._params.align : this._theme.ether.interval.marker[B.isHorizontal() ? "hAlign" : "vAlign"];
var A = ("showLine" in this._params) ? this._params.showLine : this._theme.ether.interval.line.show;
this._intervalMarkerLayout = new Timeline.EtherIntervalMarkerLayout(this._timeline, this._band, this._theme, D, A);
this._highlight = new Timeline.EtherHighlight(this._timeline, this._band, this._theme, this._backgroundLayer);
};
Timeline.YearCountEtherPainter.prototype.setHighlight = function (A, B) {
this._highlight.position(A, B);
};
Timeline.YearCountEtherPainter.prototype.paint = function () {
if (this._markerLayer) {
this._band.removeLayerDiv(this._markerLayer);
}
this._markerLayer = this._band.createLayerDiv(100);
this._markerLayer.setAttribute("name", "ether-markers");
this._markerLayer.style.display = "none";
if (this._lineLayer) {
this._band.removeLayerDiv(this._lineLayer);
}
this._lineLayer = this._band.createLayerDiv(1);
this._lineLayer.setAttribute("name", "ether-lines");
this._lineLayer.style.display = "none";
var B = new Date(this._startDate.getTime());
var F = this._band.getMaxDate();
var E = this._band.getMinDate().getUTCFullYear() - this._startDate.getUTCFullYear();
B.setUTCFullYear(this._band.getMinDate().getUTCFullYear() - E % this._multiple);
var C = this;
var A = function (G) {
for (var H = 0;
H < C._multiple;
H++) {
SimileAjax.DateTime.incrementByInterval(G, SimileAjax.DateTime.YEAR);
}
};
var D = {labelInterval: function (G, I) {
var H = G.getUTCFullYear() - C._startDate.getUTCFullYear();
return{text: H, emphasized: H == 0};
}};
while (B.getTime() < F.getTime()) {
this._intervalMarkerLayout.createIntervalMarker(B, D, SimileAjax.DateTime.YEAR, this._markerLayer, this._lineLayer);
A(B);
}
this._markerLayer.style.display = "block";
this._lineLayer.style.display = "block";
};
Timeline.YearCountEtherPainter.prototype.softPaint = function () {
};
Timeline.QuarterlyEtherPainter = function (A) {
this._params = A;
this._theme = A.theme;
this._startDate = SimileAjax.DateTime.parseGregorianDateTime(A.startDate);
};
Timeline.QuarterlyEtherPainter.prototype.initialize = function (C, B) {
this._band = C;
this._timeline = B;
this._backgroundLayer = C.createLayerDiv(0);
this._backgroundLayer.setAttribute("name", "ether-background");
this._backgroundLayer.className = "timeline-ether-bg";
this._markerLayer = null;
this._lineLayer = null;
var D = ("align" in this._params) ? this._params.align : this._theme.ether.interval.marker[B.isHorizontal() ? "hAlign" : "vAlign"];
var A = ("showLine" in this._params) ? this._params.showLine : this._theme.ether.interval.line.show;
this._intervalMarkerLayout = new Timeline.EtherIntervalMarkerLayout(this._timeline, this._band, this._theme, D, A);
this._highlight = new Timeline.EtherHighlight(this._timeline, this._band, this._theme, this._backgroundLayer);
};
Timeline.QuarterlyEtherPainter.prototype.setHighlight = function (A, B) {
this._highlight.position(A, B);
};
Timeline.QuarterlyEtherPainter.prototype.paint = function () {
if (this._markerLayer) {
this._band.removeLayerDiv(this._markerLayer);
}
this._markerLayer = this._band.createLayerDiv(100);
this._markerLayer.setAttribute("name", "ether-markers");
this._markerLayer.style.display = "none";
if (this._lineLayer) {
this._band.removeLayerDiv(this._lineLayer);
}
this._lineLayer = this._band.createLayerDiv(1);
this._lineLayer.setAttribute("name", "ether-lines");
this._lineLayer.style.display = "none";
var B = new Date(0);
var E = this._band.getMaxDate();
B.setUTCFullYear(Math.max(this._startDate.getUTCFullYear(), this._band.getMinDate().getUTCFullYear()));
B.setUTCMonth(this._startDate.getUTCMonth());
var C = this;
var A = function (F) {
F.setUTCMonth(F.getUTCMonth() + 3);
};
var D = {labelInterval: function (G, H) {
var F = (4 + (G.getUTCMonth() - C._startDate.getUTCMonth()) / 3) % 4;
if (F != 0) {
return{text: "Q" + (F + 1), emphasized: false};
} else {
return{text: "Y" + (G.getUTCFullYear() - C._startDate.getUTCFullYear() + 1), emphasized: true};
}
}};
while (B.getTime() < E.getTime()) {
this._intervalMarkerLayout.createIntervalMarker(B, D, SimileAjax.DateTime.YEAR, this._markerLayer, this._lineLayer);
A(B);
}
this._markerLayer.style.display = "block";
this._lineLayer.style.display = "block";
};
Timeline.QuarterlyEtherPainter.prototype.softPaint = function () {
};
Timeline.EtherIntervalMarkerLayout = function (I, L, C, E, M) {
var A = I.isHorizontal();
if (A) {
if (E == "Top") {
this.positionDiv = function (O, N) {
O.style.left = N + "px";
O.style.top = "0px";
};
} else {
this.positionDiv = function (O, N) {
O.style.left = N + "px";
O.style.bottom = "0px";
};
}
} else {
if (E == "Left") {
this.positionDiv = function (O, N) {
O.style.top = N + "px";
O.style.left = "0px";
};
} else {
this.positionDiv = function (O, N) {
O.style.top = N + "px";
O.style.right = "0px";
};
}
}
var D = C.ether.interval.marker;
var K = C.ether.interval.line;
var B = C.ether.interval.weekend;
var H = (A ? "h" : "v") + E;
var G = D[H + "Styler"];
var J = D[H + "EmphasizedStyler"];
var F = SimileAjax.DateTime.gregorianUnitLengths[SimileAjax.DateTime.DAY];
this.createIntervalMarker = function (T, c, a, Y, P) {
var U = Math.round(L.dateToPixelOffset(T));
if (M && a != SimileAjax.DateTime.WEEK) {
var V = I.getDocument().createElement("div");
V.className = "timeline-ether-lines";
if (K.opacity < 100) {
SimileAjax.Graphics.setOpacity(V, K.opacity);
}
if (A) {
V.style.left = U + "px";
} else {
V.style.top = U + "px";
}
P.appendChild(V);
}
if (a == SimileAjax.DateTime.WEEK) {
var N = C.firstDayOfWeek;
var R = new Date(T.getTime() + (6 - N - 7) * F);
var b = new Date(R.getTime() + 2 * F);
var Q = Math.round(L.dateToPixelOffset(R));
var S = Math.round(L.dateToPixelOffset(b));
var W = Math.max(1, S - Q);
var X = I.getDocument().createElement("div");
X.className = "timeline-ether-weekends";
if (B.opacity < 100) {
SimileAjax.Graphics.setOpacity(X, B.opacity);
}
if (A) {
X.style.left = Q + "px";
X.style.width = W + "px";
} else {
X.style.top = Q + "px";
X.style.height = W + "px";
}
P.appendChild(X);
}
var Z = c.labelInterval(T, a);
var O = I.getDocument().createElement("div");
O.innerHTML = Z.text;
O.className = "timeline-date-label";
if (Z.emphasized) {
O.className += " timeline-date-label-em";
}
this.positionDiv(O, U);
Y.appendChild(O);
return O;
};
};
Timeline.EtherHighlight = function (B, E, D, C) {
var A = B.isHorizontal();
this._highlightDiv = null;
this._createHighlightDiv = function () {
if (this._highlightDiv == null) {
this._highlightDiv = B.getDocument().createElement("div");
this._highlightDiv.setAttribute("name", "ether-highlight");
this._highlightDiv.className = "timeline-ether-highlight";
var F = D.ether.highlightOpacity;
if (F < 100) {
SimileAjax.Graphics.setOpacity(this._highlightDiv, F);
}
C.appendChild(this._highlightDiv);
}
};
this.position = function (H, J) {
this._createHighlightDiv();
var I = Math.round(E.dateToPixelOffset(H));
var G = Math.round(E.dateToPixelOffset(J));
var F = Math.max(G - I, 3);
if (A) {
this._highlightDiv.style.left = I + "px";
this._highlightDiv.style.width = F + "px";
this._highlightDiv.style.height = (E.getViewWidth() - 4) + "px";
} else {
this._highlightDiv.style.top = I + "px";
this._highlightDiv.style.height = F + "px";
this._highlightDiv.style.width = (E.getViewWidth() - 4) + "px";
}
};
};
/* ethers.js */
Timeline.LinearEther = function (A) {
this._params = A;
this._interval = A.interval;
this._pixelsPerInterval = A.pixelsPerInterval;
};
Timeline.LinearEther.prototype.initialize = function (B, A) {
this._band = B;
this._timeline = A;
this._unit = A.getUnit();
if ("startsOn" in this._params) {
this._start = this._unit.parseFromObject(this._params.startsOn);
} else {
if ("endsOn" in this._params) {
this._start = this._unit.parseFromObject(this._params.endsOn);
this.shiftPixels(-this._timeline.getPixelLength());
} else {
if ("centersOn" in this._params) {
this._start = this._unit.parseFromObject(this._params.centersOn);
this.shiftPixels(-this._timeline.getPixelLength() / 2);
} else {
this._start = this._unit.makeDefaultValue();
this.shiftPixels(-this._timeline.getPixelLength() / 2);
}
}
}
};
Timeline.LinearEther.prototype.setDate = function (A) {
this._start = this._unit.cloneValue(A);
};
Timeline.LinearEther.prototype.shiftPixels = function (B) {
var A = this._interval * B / this._pixelsPerInterval;
this._start = this._unit.change(this._start, A);
};
Timeline.LinearEther.prototype.dateToPixelOffset = function (B) {
var A = this._unit.compare(B, this._start);
return this._pixelsPerInterval * A / this._interval;
};
Timeline.LinearEther.prototype.pixelOffsetToDate = function (B) {
var A = B * this._interval / this._pixelsPerInterval;
return this._unit.change(this._start, A);
};
Timeline.LinearEther.prototype.zoom = function (D) {
var A = 0;
var B = this._band._zoomIndex;
var C = B;
if (D && (B > 0)) {
C = B - 1;
}
if (!D && (B < (this._band._zoomSteps.length - 1))) {
C = B + 1;
}
this._band._zoomIndex = C;
this._interval = SimileAjax.DateTime.gregorianUnitLengths[this._band._zoomSteps[C].unit];
this._pixelsPerInterval = this._band._zoomSteps[C].pixelsPerInterval;
A = this._band._zoomSteps[C].unit - this._band._zoomSteps[B].unit;
return A;
};
Timeline.HotZoneEther = function (A) {
this._params = A;
this._interval = A.interval;
this._pixelsPerInterval = A.pixelsPerInterval;
this._theme = A.theme;
};
Timeline.HotZoneEther.prototype.initialize = function (I, H) {
this._band = I;
this._timeline = H;
this._unit = H.getUnit();
this._zones = [
{startTime: Number.NEGATIVE_INFINITY, endTime: Number.POSITIVE_INFINITY, magnify: 1}
];
var D = this._params;
for (var E = 0;
E < D.zones.length;
E++) {
var G = D.zones[E];
var F = this._unit.parseFromObject(G.start);
var B = this._unit.parseFromObject(G.end);
for (var C = 0;
C < this._zones.length && this._unit.compare(B, F) > 0;
C++) {
var A = this._zones[C];
if (this._unit.compare(F, A.endTime) < 0) {
if (this._unit.compare(F, A.startTime) > 0) {
this._zones.splice(C, 0, {startTime: A.startTime, endTime: F, magnify: A.magnify});
C++;
A.startTime = F;
}
if (this._unit.compare(B, A.endTime) < 0) {
this._zones.splice(C, 0, {startTime: F, endTime: B, magnify: G.magnify * A.magnify});
C++;
A.startTime = B;
F = B;
} else {
A.magnify *= G.magnify;
F = A.endTime;
}
}
}
}
if ("startsOn" in this._params) {
this._start = this._unit.parseFromObject(this._params.startsOn);
} else {
if ("endsOn" in this._params) {
this._start = this._unit.parseFromObject(this._params.endsOn);
this.shiftPixels(-this._timeline.getPixelLength());
} else {
if ("centersOn" in this._params) {
this._start = this._unit.parseFromObject(this._params.centersOn);
this.shiftPixels(-this._timeline.getPixelLength() / 2);
} else {
this._start = this._unit.makeDefaultValue();
this.shiftPixels(-this._timeline.getPixelLength() / 2);
}
}
}
};
Timeline.HotZoneEther.prototype.setDate = function (A) {
this._start = this._unit.cloneValue(A);
};
Timeline.HotZoneEther.prototype.shiftPixels = function (A) {
this._start = this.pixelOffsetToDate(A);
};
Timeline.HotZoneEther.prototype.dateToPixelOffset = function (A) {
return this._dateDiffToPixelOffset(this._start, A);
};
Timeline.HotZoneEther.prototype.pixelOffsetToDate = function (A) {
return this._pixelOffsetToDate(A, this._start);
};
Timeline.HotZoneEther.prototype.zoom = function (D) {
var A = 0;
var B = this._band._zoomIndex;
var C = B;
if (D && (B > 0)) {
C = B - 1;
}
if (!D && (B < (this._band._zoomSteps.length - 1))) {
C = B + 1;
}
this._band._zoomIndex = C;
this._interval = SimileAjax.DateTime.gregorianUnitLengths[this._band._zoomSteps[C].unit];
this._pixelsPerInterval = this._band._zoomSteps[C].pixelsPerInterval;
A = this._band._zoomSteps[C].unit - this._band._zoomSteps[B].unit;
return A;
};
Timeline.HotZoneEther.prototype._dateDiffToPixelOffset = function (H, C) {
var D = this._getScale();
var I = H;
var B = C;
var E = 0;
if (this._unit.compare(I, B) < 0) {
var G = 0;
while (G < this._zones.length) {
if (this._unit.compare(I, this._zones[G].endTime) < 0) {
break;
}
G++;
}
while (this._unit.compare(I, B) < 0) {
var F = this._zones[G];
var A = this._unit.earlier(B, F.endTime);
E += (this._unit.compare(A, I) / (D / F.magnify));
I = A;
G++;
}
} else {
var G = this._zones.length - 1;
while (G >= 0) {
if (this._unit.compare(I, this._zones[G].startTime) > 0) {
break;
}
G--;
}
while (this._unit.compare(I, B) > 0) {
var F = this._zones[G];
var A = this._unit.later(B, F.startTime);
E += (this._unit.compare(A, I) / (D / F.magnify));
I = A;
G--;
}
}
return E;
};
Timeline.HotZoneEther.prototype._pixelOffsetToDate = function (E, B) {
var G = this._getScale();
var D = B;
if (E > 0) {
var F = 0;
while (F < this._zones.length) {
if (this._unit.compare(D, this._zones[F].endTime) < 0) {
break;
}
F++;
}
while (E > 0) {
var A = this._zones[F];
var H = G / A.magnify;
if (A.endTime == Number.POSITIVE_INFINITY) {
D = this._unit.change(D, E * H);
E = 0;
} else {
var C = this._unit.compare(A.endTime, D) / H;
if (C > E) {
D = this._unit.change(D, E * H);
E = 0;
} else {
D = A.endTime;
E -= C;
}
}
F++;
}
} else {
var F = this._zones.length - 1;
while (F >= 0) {
if (this._unit.compare(D, this._zones[F].startTime) > 0) {
break;
}
F--;
}
E = -E;
while (E > 0) {
var A = this._zones[F];
var H = G / A.magnify;
if (A.startTime == Number.NEGATIVE_INFINITY) {
D = this._unit.change(D, -E * H);
E = 0;
} else {
var C = this._unit.compare(D, A.startTime) / H;
if (C > E) {
D = this._unit.change(D, -E * H);
E = 0;
} else {
D = A.startTime;
E -= C;
}
}
F--;
}
}
return D;
};
Timeline.HotZoneEther.prototype._getScale = function () {
return this._interval / this._pixelsPerInterval;
};
/* event-utils.js */
Timeline.EventUtils = {};
Timeline.EventUtils.getNewEventID = function () {
if (this._lastEventID == null) {
this._lastEventID = 0;
}
this._lastEventID += 1;
return"e" + this._lastEventID;
};
Timeline.EventUtils.decodeEventElID = function (C) {
var D = C.split("-");
if (D[1] != "tl") {
alert("Internal Timeline problem 101, please consult support");
return{band: null, evt: null};
}
var B = Timeline.getTimelineFromID(D[2]);
var E = B.getBand(D[3]);
var A = E.getEventSource.getEvent(D[4]);
return{band: E, evt: A};
};
Timeline.EventUtils.encodeEventElID = function (B, D, C, A) {
return C + "-tl-" + B.timelineID + "-" + D.getIndex() + "-" + A.getID();
};
/* labellers.js */
Timeline.GregorianDateLabeller = function (B, A) {
this._locale = B;
this._timeZone = A;
};
Timeline.GregorianDateLabeller.monthNames = [];
Timeline.GregorianDateLabeller.dayNames = [];
Timeline.GregorianDateLabeller.labelIntervalFunctions = [];
Timeline.GregorianDateLabeller.getMonthName = function (B, A) {
return Timeline.GregorianDateLabeller.monthNames[A][B];
};
Timeline.GregorianDateLabeller.prototype.labelInterval = function (A, C) {
var B = Timeline.GregorianDateLabeller.labelIntervalFunctions[this._locale];
if (B == null) {
B = Timeline.GregorianDateLabeller.prototype.defaultLabelInterval;
}
return B.call(this, A, C);
};
Timeline.GregorianDateLabeller.prototype.labelPrecise = function (A) {
return SimileAjax.DateTime.removeTimeZoneOffset(A, this._timeZone).toUTCString();
};
Timeline.GregorianDateLabeller.prototype.defaultLabelInterval = function (B, C) {
var D;
var F = false;
B = SimileAjax.DateTime.removeTimeZoneOffset(B, this._timeZone);
switch (C) {
case SimileAjax.DateTime.MILLISECOND:
D = B.getUTCMilliseconds();
break;
case SimileAjax.DateTime.SECOND:
D = B.getUTCSeconds();
break;
case SimileAjax.DateTime.MINUTE:
var A = B.getUTCMinutes();
if (A == 0) {
D = B.getUTCHours() + ":00";
F = true;
} else {
D = A;
}
break;
case SimileAjax.DateTime.HOUR:
D = B.getUTCHours() + "hr";
break;
case SimileAjax.DateTime.DAY:
D = Timeline.GregorianDateLabeller.getMonthName(B.getUTCMonth(), this._locale) + " " + B.getUTCDate();
break;
case SimileAjax.DateTime.WEEK:
D = Timeline.GregorianDateLabeller.getMonthName(B.getUTCMonth(), this._locale) + " " + B.getUTCDate();
break;
case SimileAjax.DateTime.MONTH:
var A = B.getUTCMonth();
if (A != 0) {
D = Timeline.GregorianDateLabeller.getMonthName(A, this._locale);
break;
}
case SimileAjax.DateTime.YEAR:
case SimileAjax.DateTime.DECADE:
case SimileAjax.DateTime.CENTURY:
case SimileAjax.DateTime.MILLENNIUM:
var E = B.getUTCFullYear();
if (E > 0) {
D = B.getUTCFullYear();
} else {
D = (1 - E) + "BC";
}
F = (C == SimileAjax.DateTime.MONTH) || (C == SimileAjax.DateTime.DECADE && E % 100 == 0) || (C == SimileAjax.DateTime.CENTURY && E % 1000 == 0);
break;
default:
D = B.toUTCString();
}
return{text: D, emphasized: F};
};
/* original-painter.js */
Timeline.OriginalEventPainter = function (A) {
this._params = A;
this._onSelectListeners = [];
this._eventPaintListeners = [];
this._filterMatcher = null;
this._highlightMatcher = null;
this._frc = null;
this._eventIdToElmt = {};
};
Timeline.OriginalEventPainter.prototype.initialize = function (B, A) {
this._band = B;
this._timeline = A;
this._backLayer = null;
this._eventLayer = null;
this._lineLayer = null;
this._highlightLayer = null;
this._eventIdToElmt = null;
};
Timeline.OriginalEventPainter.prototype.getType = function () {
return"original";
};
Timeline.OriginalEventPainter.prototype.addOnSelectListener = function (A) {
this._onSelectListeners.push(A);
};
Timeline.OriginalEventPainter.prototype.removeOnSelectListener = function (B) {
for (var A = 0;
A < this._onSelectListeners.length;
A++) {
if (this._onSelectListeners[A] == B) {
this._onSelectListeners.splice(A, 1);
break;
}
}
};
Timeline.OriginalEventPainter.prototype.addEventPaintListener = function (A) {
this._eventPaintListeners.push(A);
};
Timeline.OriginalEventPainter.prototype.removeEventPaintListener = function (B) {
for (var A = 0;
A < this._eventPaintListeners.length;
A++) {
if (this._eventPaintListeners[A] == B) {
this._eventPaintListeners.splice(A, 1);
break;
}
}
};
Timeline.OriginalEventPainter.prototype.getFilterMatcher = function () {
return this._filterMatcher;
};
Timeline.OriginalEventPainter.prototype.setFilterMatcher = function (A) {
this._filterMatcher = A;
};
Timeline.OriginalEventPainter.prototype.getHighlightMatcher = function () {
return this._highlightMatcher;
};
Timeline.OriginalEventPainter.prototype.setHighlightMatcher = function (A) {
this._highlightMatcher = A;
};
Timeline.OriginalEventPainter.prototype.paint = function () {
var C = this._band.getEventSource();
if (C == null) {
return;
}
this._eventIdToElmt = {};
this._fireEventPaintListeners("paintStarting", null, null);
this._prepareForPainting();
var I = this._params.theme.event;
var G = Math.max(I.track.height, I.tape.height + this._frc.getLineHeight());
var F = {trackOffset: I.track.offset, trackHeight: G, trackGap: I.track.gap, trackIncrement: G + I.track.gap, icon: I.instant.icon, iconWidth: I.instant.iconWidth, iconHeight: I.instant.iconHeight, labelWidth: I.label.width, maxLabelChar: I.label.maxLabelChar, impreciseIconMargin: I.instant.impreciseIconMargin};
var D = this._band.getMinDate();
var B = this._band.getMaxDate();
var J = (this._filterMatcher != null) ? this._filterMatcher : function (K) {
return true;
};
var A = (this._highlightMatcher != null) ? this._highlightMatcher : function (K) {
return -1;
};
var E = C.getEventReverseIterator(D, B);
while (E.hasNext()) {
var H = E.next();
if (J(H)) {
this.paintEvent(H, F, this._params.theme, A(H));
}
}
this._highlightLayer.style.display = "block";
this._lineLayer.style.display = "block";
this._eventLayer.style.display = "block";
this._band.updateEventTrackInfo(this._tracks.length, F.trackIncrement);
this._fireEventPaintListeners("paintEnded", null, null);
};
Timeline.OriginalEventPainter.prototype.softPaint = function () {
};
Timeline.OriginalEventPainter.prototype._prepareForPainting = function () {
var B = this._band;
if (this._backLayer == null) {
this._backLayer = this._band.createLayerDiv(0, "timeline-band-events");
this._backLayer.style.visibility = "hidden";
var A = document.createElement("span");
A.className = "timeline-event-label";
this._backLayer.appendChild(A);
this._frc = SimileAjax.Graphics.getFontRenderingContext(A);
}
this._frc.update();
this._tracks = [];
if (this._highlightLayer != null) {
B.removeLayerDiv(this._highlightLayer);
}
this._highlightLayer = B.createLayerDiv(105, "timeline-band-highlights");
this._highlightLayer.style.display = "none";
if (this._lineLayer != null) {
B.removeLayerDiv(this._lineLayer);
}
this._lineLayer = B.createLayerDiv(110, "timeline-band-lines");
this._lineLayer.style.display = "none";
if (this._eventLayer != null) {
B.removeLayerDiv(this._eventLayer);
}
this._eventLayer = B.createLayerDiv(115, "timeline-band-events");
this._eventLayer.style.display = "none";
};
Timeline.OriginalEventPainter.prototype.paintEvent = function (B, C, D, A) {
if (B.isInstant()) {
this.paintInstantEvent(B, C, D, A);
} else {
this.paintDurationEvent(B, C, D, A);
}
};
Timeline.OriginalEventPainter.prototype.paintInstantEvent = function (B, C, D, A) {
if (B.isImprecise()) {
this.paintImpreciseInstantEvent(B, C, D, A);
} else {
this.paintPreciseInstantEvent(B, C, D, A);
}
};
Timeline.OriginalEventPainter.prototype.paintDurationEvent = function (B, C, D, A) {
if (B.isImprecise()) {
this.paintImpreciseDurationEvent(B, C, D, A);
} else {
this.paintPreciseDurationEvent(B, C, D, A);
}
};
Timeline.OriginalEventPainter.prototype.paintPreciseInstantEvent = function (N, S, V, T) {
var W = this._timeline.getDocument();
var L = N.getText();
var H = N.getStart();
var I = Math.round(this._band.dateToPixelOffset(H));
var A = Math.round(I + S.iconWidth / 2);
var C = Math.round(I - S.iconWidth / 2);
var F = this._getLabelDivClassName(N);
var D = this._frc.computeSize(L, F);
var M = A + V.event.label.offsetFromLine;
var J = M + D.width;
var Q = J;
var P = this._findFreeTrack(N, Q);
var R = Math.round(S.trackOffset + P * S.trackIncrement + S.trackHeight / 2 - D.height / 2);
var B = this._paintEventIcon(N, P, C, S, V, 0);
var U = this._paintEventLabel(N, L, M, R, D.width, D.height, V, F, T);
var E = [B.elmt, U.elmt];
var O = this;
var K = function (Y, X, Z) {
return O._onClickInstantEvent(B.elmt, X, N);
};
SimileAjax.DOM.registerEvent(B.elmt, "mousedown", K);
SimileAjax.DOM.registerEvent(U.elmt, "mousedown", K);
var G = this._createHighlightDiv(T, B, V, N);
if (G != null) {
E.push(G);
}
this._fireEventPaintListeners("paintedEvent", N, E);
this._eventIdToElmt[N.getID()] = B.elmt;
this._tracks[P] = C;
};
Timeline.OriginalEventPainter.prototype.paintImpreciseInstantEvent = function (P, U, Z, W) {
var b = this._timeline.getDocument();
var N = P.getText();
var J = P.getStart();
var X = P.getEnd();
var K = Math.round(this._band.dateToPixelOffset(J));
var B = Math.round(this._band.dateToPixelOffset(X));
var A = Math.round(K + U.iconWidth / 2);
var D = Math.round(K - U.iconWidth / 2);
var H = this._getLabelDivClassName(P);
var F = this._frc.computeSize(N, H);
var O = A + Z.event.label.offsetFromLine;
var L = O + F.width;
var S = Math.max(L, B);
var R = this._findFreeTrack(P, S);
var a = Z.event.tape.height;
var T = Math.round(U.trackOffset + R * U.trackIncrement + a);
var C = this._paintEventIcon(P, R, D, U, Z, a);
var Y = this._paintEventLabel(P, N, O, T, F.width, F.height, Z, H, W);
var V = P.getColor();
V = V != null ? V : Z.event.instant.impreciseColor;
var E = this._paintEventTape(P, R, K, B, V, Z.event.instant.impreciseOpacity, U, Z, 0);
var G = [C.elmt, Y.elmt, E.elmt];
var Q = this;
var M = function (d, c, e) {
return Q._onClickInstantEvent(C.elmt, c, P);
};
SimileAjax.DOM.registerEvent(C.elmt, "mousedown", M);
SimileAjax.DOM.registerEvent(E.elmt, "mousedown", M);
SimileAjax.DOM.registerEvent(Y.elmt, "mousedown", M);
var I = this._createHighlightDiv(W, C, Z, P);
if (I != null) {
G.push(I);
}
this._fireEventPaintListeners("paintedEvent", P, G);
this._eventIdToElmt[P.getID()] = C.elmt;
this._tracks[R] = D;
};
Timeline.OriginalEventPainter.prototype.paintPreciseDurationEvent = function (M, R, W, T) {
var X = this._timeline.getDocument();
var K = M.getText();
var G = M.getStart();
var U = M.getEnd();
var H = Math.round(this._band.dateToPixelOffset(G));
var A = Math.round(this._band.dateToPixelOffset(U));
var E = this._getLabelDivClassName(M);
var C = this._frc.computeSize(K, E);
var L = H;
var I = L + C.width;
var P = Math.max(I, A);
var O = this._findFreeTrack(M, P);
var Q = Math.round(R.trackOffset + O * R.trackIncrement + W.event.tape.height);
var S = M.getColor();
S = S != null ? S : W.event.duration.color;
var B = this._paintEventTape(M, O, H, A, S, 100, R, W, 0);
var V = this._paintEventLabel(M, K, L, Q, C.width, C.height, W, E, T);
var D = [B.elmt, V.elmt];
var N = this;
var J = function (Z, Y, a) {
return N._onClickDurationEvent(B.elmt, Y, M);
};
SimileAjax.DOM.registerEvent(B.elmt, "mousedown", J);
SimileAjax.DOM.registerEvent(V.elmt, "mousedown", J);
var F = this._createHighlightDiv(T, B, W, M);
if (F != null) {
D.push(F);
}
this._fireEventPaintListeners("paintedEvent", M, D);
this._eventIdToElmt[M.getID()] = B.elmt;
this._tracks[O] = H;
};
Timeline.OriginalEventPainter.prototype.paintImpreciseDurationEvent = function (O, W, b, Y) {
var c = this._timeline.getDocument();
var M = O.getText();
var I = O.getStart();
var V = O.getLatestStart();
var Z = O.getEnd();
var Q = O.getEarliestEnd();
var K = Math.round(this._band.dateToPixelOffset(I));
var F = Math.round(this._band.dateToPixelOffset(V));
var A = Math.round(this._band.dateToPixelOffset(Z));
var G = Math.round(this._band.dateToPixelOffset(Q));
var E = this._getLabelDivClassName(O);
var C = this._frc.computeSize(M, E);
var N = F;
var J = N + C.width;
var S = Math.max(J, A);
var R = this._findFreeTrack(O, S);
var T = Math.round(W.trackOffset + R * W.trackIncrement + b.event.tape.height);
var X = O.getColor();
X = X != null ? X : b.event.duration.color;
var U = this._paintEventTape(O, R, K, A, b.event.duration.impreciseColor, b.event.duration.impreciseOpacity, W, b, 0);
var B = this._paintEventTape(O, R, F, G, X, 100, W, b, 1);
var a = this._paintEventLabel(O, M, N, T, C.width, C.height, b, E, Y);
var D = [U.elmt, B.elmt, a.elmt];
var P = this;
var L = function (e, d, f) {
return P._onClickDurationEvent(B.elmt, d, O);
};
SimileAjax.DOM.registerEvent(B.elmt, "mousedown", L);
SimileAjax.DOM.registerEvent(a.elmt, "mousedown", L);
var H = this._createHighlightDiv(Y, B, b, O);
if (H != null) {
D.push(H);
}
this._fireEventPaintListeners("paintedEvent", O, D);
this._eventIdToElmt[O.getID()] = B.elmt;
this._tracks[R] = K;
};
Timeline.OriginalEventPainter.prototype._encodeEventElID = function (B, A) {
return Timeline.EventUtils.encodeEventElID(this._timeline, this._band, B, A);
};
Timeline.OriginalEventPainter.prototype._findFreeTrack = function (E, D) {
var A = E.getTrackNum();
if (A != null) {
return A;
}
for (var C = 0;
C < this._tracks.length;
C++) {
var B = this._tracks[C];
if (B > D) {
break;
}
}
return C;
};
Timeline.OriginalEventPainter.prototype._paintEventIcon = function (K, B, C, G, F, D) {
var I = K.getIcon();
I = I != null ? I : G.icon;
var J;
if (D > 0) {
J = G.trackOffset + B * G.trackIncrement + D + G.impreciseIconMargin;
} else {
var H = G.trackOffset + B * G.trackIncrement + G.trackHeight / 2;
J = Math.round(H - G.iconHeight / 2);
}
var E = SimileAjax.Graphics.createTranslucentImage(I);
var A = this._timeline.getDocument().createElement("div");
A.className = this._getElClassName("timeline-event-icon", K, "icon");
A.id = this._encodeEventElID("icon", K);
A.style.left = C + "px";
A.style.top = J + "px";
A.appendChild(E);
if (K._title != null) {
A.title = K._title;
}
this._eventLayer.appendChild(A);
return{left: C, top: J, width: G.iconWidth, height: G.iconHeight, elmt: A};
};
Timeline.OriginalEventPainter.prototype._paintEventLabel = function (K, L, D, H, A, J, G, E, C) {
var I = this._timeline.getDocument();
var B = I.createElement("div");
B.className = E;
B.id = this._encodeEventElID("label", K);
B.style.left = D + "px";
B.style.width = A + "px";
B.style.top = H + "px";
B.innerHTML = L;
if (K._title != null) {
B.title = K._title;
}
var F = K.getTextColor();
if (F == null) {
F = K.getColor();
}
if (F != null) {
B.style.color = F;
}
if (G.event.highlightLabelBackground && C >= 0) {
B.style.background = this._getHighlightColor(C, G);
}
this._eventLayer.appendChild(B);
return{left: D, top: H, width: A, height: J, elmt: B};
};
Timeline.OriginalEventPainter.prototype._paintEventTape = function (N, B, D, A, G, C, J, I, M) {
var F = A - D;
var E = I.event.tape.height;
var K = J.trackOffset + B * J.trackIncrement;
var O = this._timeline.getDocument().createElement("div");
O.className = this._getElClassName("timeline-event-tape", N, "tape");
O.id = this._encodeEventElID("tape" + M, N);
O.style.left = D + "px";
O.style.width = F + "px";
O.style.height = E + "px";
O.style.top = K + "px";
if (N._title != null) {
O.title = N._title;
}
if (G != null) {
O.style.backgroundColor = G;
}
var L = N.getTapeImage();
var H = N.getTapeRepeat();
H = H != null ? H : "repeat";
if (L != null) {
O.style.backgroundImage = "url(" + L + ")";
O.style.backgroundRepeat = H;
}
SimileAjax.Graphics.setOpacity(O, C);
this._eventLayer.appendChild(O);
return{left: D, top: K, width: F, height: E, elmt: O};
};
Timeline.OriginalEventPainter.prototype._getLabelDivClassName = function (A) {
return this._getElClassName("timeline-event-label", A, "label");
};
Timeline.OriginalEventPainter.prototype._getElClassName = function (D, C, A) {
var E = C.getClassName(), B = [];
if (E) {
if (A) {
B.push(A + "-" + E + " ");
}
B.push(E + " ");
}
B.push(D);
return(B.join(""));
};
Timeline.OriginalEventPainter.prototype._getHighlightColor = function (A, B) {
var C = B.event.highlightColors;
return C[Math.min(A, C.length - 1)];
};
Timeline.OriginalEventPainter.prototype._createHighlightDiv = function (A, D, F, B) {
var G = null;
if (A >= 0) {
var E = this._timeline.getDocument();
var C = this._getHighlightColor(A, F);
G = E.createElement("div");
G.className = this._getElClassName("timeline-event-highlight", B, "highlight");
G.id = this._encodeEventElID("highlight0", B);
G.style.position = "absolute";
G.style.overflow = "hidden";
G.style.left = (D.left - 2) + "px";
G.style.width = (D.width + 4) + "px";
G.style.top = (D.top - 2) + "px";
G.style.height = (D.height + 4) + "px";
G.style.background = C;
this._highlightLayer.appendChild(G);
}
return G;
};
Timeline.OriginalEventPainter.prototype._onClickInstantEvent = function (C, A, B) {
var D = SimileAjax.DOM.getPageCoordinates(C);
this._showBubble(D.left + Math.ceil(C.offsetWidth / 2), D.top + Math.ceil(C.offsetHeight / 2), B);
this._fireOnSelect(B.getID());
A.cancelBubble = true;
SimileAjax.DOM.cancelEvent(A);
return false;
};
Timeline.OriginalEventPainter.prototype._onClickDurationEvent = function (F, B, C) {
if ("pageX" in B) {
var A = B.pageX;
var E = B.pageY;
} else {
var D = SimileAjax.DOM.getPageCoordinates(F);
var A = B.offsetX + D.left;
var E = B.offsetY + D.top;
}
this._showBubble(A, E, C);
this._fireOnSelect(C.getID());
B.cancelBubble = true;
SimileAjax.DOM.cancelEvent(B);
return false;
};
Timeline.OriginalEventPainter.prototype.showBubble = function (A) {
var B = this._eventIdToElmt[A.getID()];
if (B) {
var C = SimileAjax.DOM.getPageCoordinates(B);
this._showBubble(C.left + B.offsetWidth / 2, C.top + B.offsetHeight / 2, A);
}
};
Timeline.OriginalEventPainter.prototype._showBubble = function (B, E, C) {
var D = document.createElement("div");
var A = this._params.theme.event.bubble;
C.fillInfoBubble(D, this._params.theme, this._band.getLabeller());
SimileAjax.WindowManager.cancelPopups();
SimileAjax.Graphics.createBubbleForContentAndPoint(D, B, E, A.width, null, A.maxHeight);
};
Timeline.OriginalEventPainter.prototype._fireOnSelect = function (A) {
for (var B = 0;
B < this._onSelectListeners.length;
B++) {
this._onSelectListeners[B](A);
}
};
Timeline.OriginalEventPainter.prototype._fireEventPaintListeners = function (D, A, C) {
for (var B = 0;
B < this._eventPaintListeners.length;
B++) {
this._eventPaintListeners[B](this._band, D, A, C);
}
};
/* overview-painter.js */
Timeline.OverviewEventPainter = function (A) {
this._params = A;
this._onSelectListeners = [];
this._filterMatcher = null;
this._highlightMatcher = null;
};
Timeline.OverviewEventPainter.prototype.initialize = function (B, A) {
this._band = B;
this._timeline = A;
this._eventLayer = null;
this._highlightLayer = null;
};
Timeline.OverviewEventPainter.prototype.getType = function () {
return"overview";
};
Timeline.OverviewEventPainter.prototype.addOnSelectListener = function (A) {
this._onSelectListeners.push(A);
};
Timeline.OverviewEventPainter.prototype.removeOnSelectListener = function (B) {
for (var A = 0;
A < this._onSelectListeners.length;
A++) {
if (this._onSelectListeners[A] == B) {
this._onSelectListeners.splice(A, 1);
break;
}
}
};
Timeline.OverviewEventPainter.prototype.getFilterMatcher = function () {
return this._filterMatcher;
};
Timeline.OverviewEventPainter.prototype.setFilterMatcher = function (A) {
this._filterMatcher = A;
};
Timeline.OverviewEventPainter.prototype.getHighlightMatcher = function () {
return this._highlightMatcher;
};
Timeline.OverviewEventPainter.prototype.setHighlightMatcher = function (A) {
this._highlightMatcher = A;
};
Timeline.OverviewEventPainter.prototype.paint = function () {
var C = this._band.getEventSource();
if (C == null) {
return;
}
this._prepareForPainting();
var H = this._params.theme.event;
var F = {trackOffset: H.overviewTrack.offset, trackHeight: H.overviewTrack.height, trackGap: H.overviewTrack.gap, trackIncrement: H.overviewTrack.height + H.overviewTrack.gap};
var D = this._band.getMinDate();
var B = this._band.getMaxDate();
var I = (this._filterMatcher != null) ? this._filterMatcher : function (J) {
return true;
};
var A = (this._highlightMatcher != null) ? this._highlightMatcher : function (J) {
return -1;
};
var E = C.getEventReverseIterator(D, B);
while (E.hasNext()) {
var G = E.next();
if (I(G)) {
this.paintEvent(G, F, this._params.theme, A(G));
}
}
this._highlightLayer.style.display = "block";
this._eventLayer.style.display = "block";
this._band.updateEventTrackInfo(this._tracks.length, F.trackIncrement);
};
Timeline.OverviewEventPainter.prototype.softPaint = function () {
};
Timeline.OverviewEventPainter.prototype._prepareForPainting = function () {
var A = this._band;
this._tracks = [];
if (this._highlightLayer != null) {
A.removeLayerDiv(this._highlightLayer);
}
this._highlightLayer = A.createLayerDiv(105, "timeline-band-highlights");
this._highlightLayer.style.display = "none";
if (this._eventLayer != null) {
A.removeLayerDiv(this._eventLayer);
}
this._eventLayer = A.createLayerDiv(110, "timeline-band-events");
this._eventLayer.style.display = "none";
};
Timeline.OverviewEventPainter.prototype.paintEvent = function (B, C, D, A) {
if (B.isInstant()) {
this.paintInstantEvent(B, C, D, A);
} else {
this.paintDurationEvent(B, C, D, A);
}
};
Timeline.OverviewEventPainter.prototype.paintInstantEvent = function (I, H, E, A) {
var F = I.getStart();
var B = Math.round(this._band.dateToPixelOffset(F));
var C = I.getColor(), D = I.getClassName();
if (D) {
C = null;
} else {
C = C != null ? C : E.event.duration.color;
}
var G = this._paintEventTick(I, B, C, 100, H, E);
this._createHighlightDiv(A, G, E);
};
Timeline.OverviewEventPainter.prototype.paintDurationEvent = function (L, K, H, B) {
var A = L.getLatestStart();
var I = L.getEarliestEnd();
var J = Math.round(this._band.dateToPixelOffset(A));
var C = Math.round(this._band.dateToPixelOffset(I));
var F = 0;
for (;
F < this._tracks.length;
F++) {
if (C < this._tracks[F]) {
break;
}
}
this._tracks[F] = C;
var E = L.getColor(), G = L.getClassName();
if (G) {
E = null;
} else {
E = E != null ? E : H.event.duration.color;
}
var D = this._paintEventTape(L, F, J, C, E, 100, K, H, G);
this._createHighlightDiv(B, D, H);
};
Timeline.OverviewEventPainter.prototype._paintEventTape = function (K, B, D, L, E, C, H, G, F) {
var I = H.trackOffset + B * H.trackIncrement;
var A = L - D;
var J = H.trackHeight;
var M = this._timeline.getDocument().createElement("div");
M.className = "timeline-small-event-tape";
if (F) {
M.className += " small-" + F;
}
M.style.left = D + "px";
M.style.width = A + "px";
M.style.top = I + "px";
M.style.height = J + "px";
if (E) {
M.style.backgroundColor = E;
}
if (C < 100) {
SimileAjax.Graphics.setOpacity(M, C);
}
this._eventLayer.appendChild(M);
return{left: D, top: I, width: A, height: J, elmt: M};
};
Timeline.OverviewEventPainter.prototype._paintEventTick = function (J, C, D, B, G, F) {
var I = F.event.overviewTrack.tickHeight;
var H = G.trackOffset - I;
var A = 1;
var K = this._timeline.getDocument().createElement("div");
K.className = "timeline-small-event-icon";
K.style.left = C + "px";
K.style.top = H + "px";
var E = J.getClassName();
if (E) {
K.className += " small-" + E;
}
if (B < 100) {
SimileAjax.Graphics.setOpacity(K, B);
}
this._eventLayer.appendChild(K);
return{left: C, top: H, width: A, height: I, elmt: K};
};
Timeline.OverviewEventPainter.prototype._createHighlightDiv = function (A, C, E) {
if (A >= 0) {
var D = this._timeline.getDocument();
var G = E.event;
var B = G.highlightColors[Math.min(A, G.highlightColors.length - 1)];
var F = D.createElement("div");
F.style.position = "absolute";
F.style.overflow = "hidden";
F.style.left = (C.left - 1) + "px";
F.style.width = (C.width + 2) + "px";
F.style.top = (C.top - 1) + "px";
F.style.height = (C.height + 2) + "px";
F.style.background = B;
this._highlightLayer.appendChild(F);
}
};
Timeline.OverviewEventPainter.prototype.showBubble = function (A) {
};
/* sources.js */
Timeline.DefaultEventSource = function (A) {
this._events = (A instanceof Object) ? A : new SimileAjax.EventIndex();
this._listeners = [];
};
Timeline.DefaultEventSource.prototype.addListener = function (A) {
this._listeners.push(A);
};
Timeline.DefaultEventSource.prototype.removeListener = function (B) {
for (var A = 0;
A < this._listeners.length;
A++) {
if (this._listeners[A] == B) {
this._listeners.splice(A, 1);
break;
}
}
};
Timeline.DefaultEventSource.prototype.loadXML = function (G, A) {
var C = this._getBaseURL(A);
var H = G.documentElement.getAttribute("wiki-url");
var J = G.documentElement.getAttribute("wiki-section");
var F = G.documentElement.getAttribute("date-time-format");
var E = this._events.getUnit().getParser(F);
var D = G.documentElement.firstChild;
var I = false;
while (D != null) {
if (D.nodeType == 1) {
var L = "";
if (D.firstChild != null && D.firstChild.nodeType == 3) {
L = D.firstChild.nodeValue;
}
var B = (D.getAttribute("isDuration") === null && D.getAttribute("durationEvent") === null) || D.getAttribute("isDuration") == "false" || D.getAttribute("durationEvent") == "false";
var K = new Timeline.DefaultEventSource.Event({id: D.getAttribute("id"), start: E(D.getAttribute("start")), end: E(D.getAttribute("end")), latestStart: E(D.getAttribute("latestStart")), earliestEnd: E(D.getAttribute("earliestEnd")), instant: B, text: D.getAttribute("title"), description: L, image: this._resolveRelativeURL(D.getAttribute("image"), C), link: this._resolveRelativeURL(D.getAttribute("link"), C), icon: this._resolveRelativeURL(D.getAttribute("icon"), C), color: D.getAttribute("color"), textColor: D.getAttribute("textColor"), hoverText: D.getAttribute("hoverText"), classname: D.getAttribute("classname"), tapeImage: D.getAttribute("tapeImage"), tapeRepeat: D.getAttribute("tapeRepeat"), caption: D.getAttribute("caption"), eventID: D.getAttribute("eventID"), trackNum: D.getAttribute("trackNum")});
K._node = D;
K.getProperty = function (M) {
return this._node.getAttribute(M);
};
K.setWikiInfo(H, J);
this._events.add(K);
I = true;
}
D = D.nextSibling;
}
if (I) {
this._fire("onAddMany", []);
}
};
Timeline.DefaultEventSource.prototype.loadJSON = function (H, B) {
var D = this._getBaseURL(B);
var J = false;
if (H && H.events) {
var I = ("wikiURL" in H) ? H.wikiURL : null;
var K = ("wikiSection" in H) ? H.wikiSection : null;
var F = ("dateTimeFormat" in H) ? H.dateTimeFormat : null;
var E = this._events.getUnit().getParser(F);
for (var G = 0;
G < H.events.length;
G++) {
var A = H.events[G];
var C = A.isDuration || (A.durationEvent != null && !A.durationEvent);
var L = new Timeline.DefaultEventSource.Event({id: ("id" in A) ? A.id : undefined, start: E(A.start), end: E(A.end), latestStart: E(A.latestStart), earliestEnd: E(A.earliestEnd), instant: C, text: A.title, description: A.description, image: this._resolveRelativeURL(A.image, D), link: this._resolveRelativeURL(A.link, D), icon: this._resolveRelativeURL(A.icon, D), color: A.color, textColor: A.textColor, hoverText: A.hoverText, classname: A.classname, tapeImage: A.tapeImage, tapeRepeat: A.tapeRepeat, caption: A.caption, eventID: A.eventID, trackNum: A.trackNum});
L._obj = A;
L.getProperty = function (M) {
return this._obj[M];
};
L.setWikiInfo(I, K);
this._events.add(L);
J = true;
}
}
if (J) {
this._fire("onAddMany", []);
}
};
Timeline.DefaultEventSource.prototype.loadSPARQL = function (I, B) {
var E = this._getBaseURL(B);
var H = "iso8601";
var G = this._events.getUnit().getParser(H);
if (I == null) {
return;
}
var F = I.documentElement.firstChild;
while (F != null && (F.nodeType != 1 || F.nodeName != "results")) {
F = F.nextSibling;
}
var J = null;
var L = null;
if (F != null) {
J = F.getAttribute("wiki-url");
L = F.getAttribute("wiki-section");
F = F.firstChild;
}
var K = false;
while (F != null) {
if (F.nodeType == 1) {
var D = {};
var A = F.firstChild;
while (A != null) {
if (A.nodeType == 1 && A.firstChild != null && A.firstChild.nodeType == 1 && A.firstChild.firstChild != null && A.firstChild.firstChild.nodeType == 3) {
D[A.getAttribute("name")] = A.firstChild.firstChild.nodeValue;
}
A = A.nextSibling;
}
if (D["start"] == null && D["date"] != null) {
D["start"] = D["date"];
}
var C = (D["isDuration"] === null && D["durationEvent"] === null) || D["isDuration"] == "false" || D["durationEvent"] == "false";
var M = new Timeline.DefaultEventSource.Event({id: D["id"], start: G(D["start"]), end: G(D["end"]), latestStart: G(D["latestStart"]), earliestEnd: G(D["earliestEnd"]), instant: C, text: D["title"], description: D["description"], image: this._resolveRelativeURL(D["image"], E), link: this._resolveRelativeURL(D["link"], E), icon: this._resolveRelativeURL(D["icon"], E), color: D["color"], textColor: D["textColor"], hoverText: D["hoverText"], caption: D["caption"], classname: D["classname"], tapeImage: D["tapeImage"], tapeRepeat: D["tapeRepeat"], eventID: D["eventID"], trackNum: D["trackNum"]});
M._bindings = D;
M.getProperty = function (N) {
return this._bindings[N];
};
M.setWikiInfo(J, L);
this._events.add(M);
K = true;
}
F = F.nextSibling;
}
if (K) {
this._fire("onAddMany", []);
}
};
Timeline.DefaultEventSource.prototype.add = function (A) {
this._events.add(A);
this._fire("onAddOne", [A]);
};
Timeline.DefaultEventSource.prototype.addMany = function (A) {
for (var B = 0;
B < A.length;
B++) {
this._events.add(A[B]);
}
this._fire("onAddMany", []);
};
Timeline.DefaultEventSource.prototype.clear = function () {
this._events.removeAll();
this._fire("onClear", []);
};
Timeline.DefaultEventSource.prototype.getEvent = function (A) {
return this._events.getEvent(A);
};
Timeline.DefaultEventSource.prototype.getEventIterator = function (A, B) {
return this._events.getIterator(A, B);
};
Timeline.DefaultEventSource.prototype.getEventReverseIterator = function (A, B) {
return this._events.getReverseIterator(A, B);
};
Timeline.DefaultEventSource.prototype.getAllEventIterator = function () {
return this._events.getAllIterator();
};
Timeline.DefaultEventSource.prototype.getCount = function () {
return this._events.getCount();
};
Timeline.DefaultEventSource.prototype.getEarliestDate = function () {
return this._events.getEarliestDate();
};
Timeline.DefaultEventSource.prototype.getLatestDate = function () {
return this._events.getLatestDate();
};
Timeline.DefaultEventSource.prototype._fire = function (B, A) {
for (var C = 0;
C < this._listeners.length;
C++) {
var D = this._listeners[C];
if (B in D) {
try {
D[B].apply(D, A);
} catch (E) {
SimileAjax.Debug.exception(E);
}
}
}
};
Timeline.DefaultEventSource.prototype._getBaseURL = function (A) {
if (A.indexOf("://") < 0) {
var C = this._getBaseURL(document.location.href);
if (A.substr(0, 1) == "/") {
A = C.substr(0, C.indexOf("/", C.indexOf("://") + 3)) + A;
} else {
A = C + A;
}
}
var B = A.lastIndexOf("/");
if (B < 0) {
return"";
} else {
return A.substr(0, B + 1);
}
};
Timeline.DefaultEventSource.prototype._resolveRelativeURL = function (A, B) {
if (A == null || A == "") {
return A;
} else {
if (A.indexOf("://") > 0) {
return A;
} else {
if (A.substr(0, 1) == "/") {
return B.substr(0, B.indexOf("/", B.indexOf("://") + 3)) + A;
} else {
return B + A;
}
}
}
};
Timeline.DefaultEventSource.Event = function (A) {
function D(E) {
return(A[E] != null && A[E] != "") ? A[E] : null;
}
var C = A.id ? A.id.trim() : "";
this._id = C.length > 0 ? C : Timeline.EventUtils.getNewEventID();
this._instant = A.instant || (A.end == null);
this._start = A.start;
this._end = (A.end != null) ? A.end : A.start;
this._latestStart = (A.latestStart != null) ? A.latestStart : (A.instant ? this._end : this._start);
this._earliestEnd = (A.earliestEnd != null) ? A.earliestEnd : this._end;
var B = [];
if (this._start > this._latestStart) {
this._latestStart = this._start;
B.push("start is > latestStart");
}
if (this._start > this._earliestEnd) {
this._earliestEnd = this._latestStart;
B.push("start is > earliestEnd");
}
if (this._start > this._end) {
this._end = this._earliestEnd;
B.push("start is > end");
}
if (this._latestStart > this._earliestEnd) {
this._earliestEnd = this._latestStart;
B.push("latestStart is > earliestEnd");
}
if (this._latestStart > this._end) {
this._end = this._earliestEnd;
B.push("latestStart is > end");
}
if (this._earliestEnd > this._end) {
this._end = this._earliestEnd;
B.push("earliestEnd is > end");
}
this._eventID = D("eventID");
this._text = (A.text != null) ? SimileAjax.HTML.deEntify(A.text) : "";
if (B.length > 0) {
this._text += " PROBLEM: " + B.join(", ");
}
this._description = SimileAjax.HTML.deEntify(A.description);
this._image = D("image");
this._link = D("link");
this._title = D("hoverText");
this._title = D("caption");
this._icon = D("icon");
this._color = D("color");
this._textColor = D("textColor");
this._classname = D("classname");
this._tapeImage = D("tapeImage");
this._tapeRepeat = D("tapeRepeat");
this._trackNum = D("trackNum");
if (this._trackNum != null) {
this._trackNum = parseInt(this._trackNum);
}
this._wikiURL = null;
this._wikiSection = null;
};
Timeline.DefaultEventSource.Event.prototype = {getID: function () {
return this._id;
}, isInstant: function () {
return this._instant;
}, isImprecise: function () {
return this._start != this._latestStart || this._end != this._earliestEnd;
}, getStart: function () {
return this._start;
}, getEnd: function () {
return this._end;
}, getLatestStart: function () {
return this._latestStart;
}, getEarliestEnd: function () {
return this._earliestEnd;
}, getEventID: function () {
return this._eventID;
}, getText: function () {
return this._text;
}, getDescription: function () {
return this._description;
}, getImage: function () {
return this._image;
}, getLink: function () {
return this._link;
}, getIcon: function () {
return this._icon;
}, getColor: function () {
return this._color;
}, getTextColor: function () {
return this._textColor;
}, getClassName: function () {
return this._classname;
}, getTapeImage: function () {
return this._tapeImage;
}, getTapeRepeat: function () {
return this._tapeRepeat;
}, getTrackNum: function () {
return this._trackNum;
}, getProperty: function (A) {
return null;
}, getWikiURL: function () {
return this._wikiURL;
}, getWikiSection: function () {
return this._wikiSection;
}, setWikiInfo: function (B, A) {
this._wikiURL = B;
this._wikiSection = A;
}, fillDescription: function (A) {
A.innerHTML = this._description;
}, fillWikiInfo: function (D) {
D.style.display = "none";
if (this._wikiURL == null || this._wikiSection == null) {
return;
}
var C = this.getProperty("wikiID");
if (C == null || C.length == 0) {
C = this.getText();
}
if (C == null || C.length == 0) {
return;
}
D.style.display = "inline";
C = C.replace(/\s/g, "_");
var B = this._wikiURL + this._wikiSection.replace(/\s/g, "_") + "/" + C;
var A = document.createElement("a");
A.href = B;
A.target = "new";
A.innerHTML = Timeline.strings[Timeline.clientLocale].wikiLinkLabel;
D.appendChild(document.createTextNode("["));
D.appendChild(A);
D.appendChild(document.createTextNode("]"));
}, fillTime: function (A, B) {
if (this._instant) {
if (this.isImprecise()) {
A.appendChild(A.ownerDocument.createTextNode(B.labelPrecise(this._start)));
A.appendChild(A.ownerDocument.createElement("br"));
A.appendChild(A.ownerDocument.createTextNode(B.labelPrecise(this._end)));
} else {
A.appendChild(A.ownerDocument.createTextNode(B.labelPrecise(this._start)));
}
} else {
if (this.isImprecise()) {
A.appendChild(A.ownerDocument.createTextNode(B.labelPrecise(this._start) + " ~ " + B.labelPrecise(this._latestStart)));
A.appendChild(A.ownerDocument.createElement("br"));
A.appendChild(A.ownerDocument.createTextNode(B.labelPrecise(this._earliestEnd) + " ~ " + B.labelPrecise(this._end)));
} else {
A.appendChild(A.ownerDocument.createTextNode(B.labelPrecise(this._start)));
A.appendChild(A.ownerDocument.createElement("br"));
A.appendChild(A.ownerDocument.createTextNode(B.labelPrecise(this._end)));
}
}
}, fillInfoBubble: function (A, E, M) {
var K = A.ownerDocument;
var J = this.getText();
var H = this.getLink();
var B = this.getImage();
if (B != null) {
var D = K.createElement("img");
D.src = B;
E.event.bubble.imageStyler(D);
A.appendChild(D);
}
var L = K.createElement("div");
var C = K.createTextNode(J);
if (H != null) {
var I = K.createElement("a");
I.href = H;
I.appendChild(C);
L.appendChild(I);
} else {
L.appendChild(C);
}
E.event.bubble.titleStyler(L);
A.appendChild(L);
var N = K.createElement("div");
this.fillDescription(N);
E.event.bubble.bodyStyler(N);
A.appendChild(N);
var G = K.createElement("div");
this.fillTime(G, M);
E.event.bubble.timeStyler(G);
A.appendChild(G);
var F = K.createElement("div");
this.fillWikiInfo(F);
E.event.bubble.wikiStyler(F);
A.appendChild(F);
}};
/* themes.js */
Timeline.ClassicTheme = new Object();
Timeline.ClassicTheme.implementations = [];
Timeline.ClassicTheme.create = function (B) {
if (B == null) {
B = Timeline.getDefaultLocale();
}
var A = Timeline.ClassicTheme.implementations[B];
if (A == null) {
A = Timeline.ClassicTheme._Impl;
}
return new A();
};
Timeline.ClassicTheme._Impl = function () {
this.firstDayOfWeek = 0;
this.autoWidth = false;
this.autoWidthAnimationTime = 500;
this.timeline_start = null;
this.timeline_stop = null;
this.ether = {backgroundColors: [], highlightOpacity: 50, interval: {line: {show: true, opacity: 25}, weekend: {opacity: 30}, marker: {hAlign: "Bottom", vAlign: "Right"}}};
this.event = {track: {height: 10, gap: 2, offset: 2, autoWidthMargin: 1.5}, overviewTrack: {offset: 20, tickHeight: 6, height: 2, gap: 1, autoWidthMargin: 5}, tape: {height: 4}, instant: {icon: Timeline.urlPrefix + "images/dull-blue-circle.png", iconWidth: 10, iconHeight: 10, impreciseOpacity: 20, impreciseIconMargin: 3}, duration: {impreciseOpacity: 20}, label: {backgroundOpacity: 50, offsetFromLine: 3}, highlightColors: ["#FFFF00", "#FFC000", "#FF0000", "#0000FF"], highlightLabelBackground: false, bubble: {width: 250, maxHeight: 0, titleStyler: function (A) {
A.className = "timeline-event-bubble-title";
}, bodyStyler: function (A) {
A.className = "timeline-event-bubble-body";
}, imageStyler: function (A) {
A.className = "timeline-event-bubble-image";
}, wikiStyler: function (A) {
A.className = "timeline-event-bubble-wiki";
}, timeStyler: function (A) {
A.className = "timeline-event-bubble-time";
}}};
this.mouseWheel = "scroll";
};
/* timeline.js */
Timeline.version = "2.3.0";
Timeline.ajax_lib_version = SimileAjax.version;
Timeline.display_version = Timeline.version + " (with Ajax lib " + Timeline.ajax_lib_version + ")";
Timeline.strings = {};
Timeline.HORIZONTAL = 0;
Timeline.VERTICAL = 1;
Timeline._defaultTheme = null;
Timeline.getDefaultLocale = function () {
return Timeline.clientLocale;
};
Timeline.create = function (D, C, E, F) {
if (Timeline.timelines == null) {
Timeline.timelines = [];
}
var B = Timeline.timelines.length;
Timeline.timelines[B] = null;
var A = new Timeline._Impl(D, C, E, F, B);
Timeline.timelines[B] = A;
return A;
};
Timeline.createBandInfo = function (F) {
var G = ("theme" in F) ? F.theme : Timeline.getDefaultTheme();
var D = ("eventSource" in F) ? F.eventSource : null;
var H = new Timeline.LinearEther({centersOn: ("date" in F) ? F.date : new Date(), interval: SimileAjax.DateTime.gregorianUnitLengths[F.intervalUnit], pixelsPerInterval: F.intervalPixels, theme: G});
var C = new Timeline.GregorianEtherPainter({unit: F.intervalUnit, multiple: ("multiple" in F) ? F.multiple : 1, theme: G, align: ("align" in F) ? F.align : undefined});
var I = {showText: ("showEventText" in F) ? F.showEventText : true, theme: G};
if ("eventPainterParams" in F) {
for (var A in F.eventPainterParams) {
I[A] = F.eventPainterParams[A];
}
}
if ("trackHeight" in F) {
I.trackHeight = F.trackHeight;
}
if ("trackGap" in F) {
I.trackGap = F.trackGap;
}
var B = ("overview" in F && F.overview) ? "overview" : ("layout" in F ? F.layout : "original");
var E;
if ("eventPainter" in F) {
E = new F.eventPainter(I);
} else {
switch (B) {
case"overview":
E = new Timeline.OverviewEventPainter(I);
break;
case"detailed":
E = new Timeline.DetailedEventPainter(I);
break;
default:
E = new Timeline.OriginalEventPainter(I);
}
}
return{width: F.width, eventSource: D, timeZone: ("timeZone" in F) ? F.timeZone : 0, ether: H, etherPainter: C, eventPainter: E, theme: G, zoomIndex: ("zoomIndex" in F) ? F.zoomIndex : 0, zoomSteps: ("zoomSteps" in F) ? F.zoomSteps : null};
};
Timeline.createHotZoneBandInfo = function (F) {
var G = ("theme" in F) ? F.theme : Timeline.getDefaultTheme();
var D = ("eventSource" in F) ? F.eventSource : null;
var H = new Timeline.HotZoneEther({centersOn: ("date" in F) ? F.date : new Date(), interval: SimileAjax.DateTime.gregorianUnitLengths[F.intervalUnit], pixelsPerInterval: F.intervalPixels, zones: F.zones, theme: G});
var C = new Timeline.HotZoneGregorianEtherPainter({unit: F.intervalUnit, zones: F.zones, theme: G, align: ("align" in F) ? F.align : undefined});
var I = {showText: ("showEventText" in F) ? F.showEventText : true, theme: G};
if ("eventPainterParams" in F) {
for (var A in F.eventPainterParams) {
I[A] = F.eventPainterParams[A];
}
}
if ("trackHeight" in F) {
I.trackHeight = F.trackHeight;
}
if ("trackGap" in F) {
I.trackGap = F.trackGap;
}
var B = ("overview" in F && F.overview) ? "overview" : ("layout" in F ? F.layout : "original");
var E;
if ("eventPainter" in F) {
E = new F.eventPainter(I);
} else {
switch (B) {
case"overview":
E = new Timeline.OverviewEventPainter(I);
break;
case"detailed":
E = new Timeline.DetailedEventPainter(I);
break;
default:
E = new Timeline.OriginalEventPainter(I);
}
}
return{width: F.width, eventSource: D, timeZone: ("timeZone" in F) ? F.timeZone : 0, ether: H, etherPainter: C, eventPainter: E, theme: G, zoomIndex: ("zoomIndex" in F) ? F.zoomIndex : 0, zoomSteps: ("zoomSteps" in F) ? F.zoomSteps : null};
};
Timeline.getDefaultTheme = function () {
if (Timeline._defaultTheme == null) {
Timeline._defaultTheme = Timeline.ClassicTheme.create(Timeline.getDefaultLocale());
}
return Timeline._defaultTheme;
};
Timeline.setDefaultTheme = function (A) {
Timeline._defaultTheme = A;
};
Timeline.loadXML = function (A, C) {
var D = function (G, F, E) {
alert("Failed to load data xml from " + A + "\n" + G);
};
var B = function (F) {
var E = F.responseXML;
if (!E.documentElement && F.responseStream) {
E.load(F.responseStream);
}
C(E, A);
};
SimileAjax.XmlHttp.get(A, D, B);
};
Timeline.loadJSON = function (url, f) {
var fError = function (statusText, status, xmlhttp) {
alert("Failed to load json data from " + url + "\n" + statusText);
};
var fDone = function (xmlhttp) {
f(eval("(" + xmlhttp.responseText + ")"), url);
};
SimileAjax.XmlHttp.get(url, fError, fDone);
};
Timeline.getTimelineFromID = function (A) {
return Timeline.timelines[A];
};
Timeline.writeVersion = function (A) {
document.getElementById(A).innerHTML = this.display_version;
};
Timeline._Impl = function (C, B, D, E, A) {
SimileAjax.WindowManager.initialize();
this._containerDiv = C;
this._bandInfos = B;
this._orientation = D == null ? Timeline.HORIZONTAL : D;
this._unit = (E != null) ? E : SimileAjax.NativeDateUnit;
this._starting = true;
this._autoResizing = false;
this.autoWidth = B && B[0] && B[0].theme && B[0].theme.autoWidth;
this.autoWidthAnimationTime = B && B[0] && B[0].theme && B[0].theme.autoWidthAnimationTime;
this.timelineID = A;
this.timeline_start = B && B[0] && B[0].theme && B[0].theme.timeline_start;
this.timeline_stop = B && B[0] && B[0].theme && B[0].theme.timeline_stop;
this.timeline_at_start = false;
this.timeline_at_stop = false;
this._initialize();
};
Timeline._Impl.prototype.dispose = function () {
for (var A = 0;
A < this._bands.length;
A++) {
this._bands[A].dispose();
}
this._bands = null;
this._bandInfos = null;
this._containerDiv.innerHTML = "";
Timeline.timelines[this.timelineID] = null;
};
Timeline._Impl.prototype.getBandCount = function () {
return this._bands.length;
};
Timeline._Impl.prototype.getBand = function (A) {
return this._bands[A];
};
Timeline._Impl.prototype.finishedEventLoading = function () {
this._autoWidthCheck(true);
this._starting = false;
};
Timeline._Impl.prototype.layout = function () {
this._autoWidthCheck(true);
this._distributeWidths();
};
Timeline._Impl.prototype.paint = function () {
for (var A = 0;
A < this._bands.length;
A++) {
this._bands[A].paint();
}
};
Timeline._Impl.prototype.getDocument = function () {
return this._containerDiv.ownerDocument;
};
Timeline._Impl.prototype.addDiv = function (A) {
this._containerDiv.appendChild(A);
};
Timeline._Impl.prototype.removeDiv = function (A) {
this._containerDiv.removeChild(A);
};
Timeline._Impl.prototype.isHorizontal = function () {
return this._orientation == Timeline.HORIZONTAL;
};
Timeline._Impl.prototype.isVertical = function () {
return this._orientation == Timeline.VERTICAL;
};
Timeline._Impl.prototype.getPixelLength = function () {
return this._orientation == Timeline.HORIZONTAL ? this._containerDiv.offsetWidth : this._containerDiv.offsetHeight;
};
Timeline._Impl.prototype.getPixelWidth = function () {
return this._orientation == Timeline.VERTICAL ? this._containerDiv.offsetWidth : this._containerDiv.offsetHeight;
};
Timeline._Impl.prototype.getUnit = function () {
return this._unit;
};
Timeline._Impl.prototype.getWidthStyle = function () {
return this._orientation == Timeline.HORIZONTAL ? "height" : "width";
};
Timeline._Impl.prototype.loadXML = function (B, D) {
var A = this;
var E = function (H, G, F) {
alert("Failed to load data xml from " + B + "\n" + H);
A.hideLoadingMessage();
};
var C = function (G) {
try {
var F = G.responseXML;
if (!F.documentElement && G.responseStream) {
F.load(G.responseStream);
}
D(F, B);
} finally {
A.hideLoadingMessage();
}
};
this.showLoadingMessage();
window.setTimeout(function () {
SimileAjax.XmlHttp.get(B, E, C);
}, 0);
};
Timeline._Impl.prototype.loadJSON = function (url, f) {
var tl = this;
var fError = function (statusText, status, xmlhttp) {
alert("Failed to load json data from " + url + "\n" + statusText);
tl.hideLoadingMessage();
};
var fDone = function (xmlhttp) {
try {
f(eval("(" + xmlhttp.responseText + ")"), url);
} finally {
tl.hideLoadingMessage();
}
};
this.showLoadingMessage();
window.setTimeout(function () {
SimileAjax.XmlHttp.get(url, fError, fDone);
}, 0);
};
Timeline._Impl.prototype._autoWidthScrollListener = function (A) {
A.getTimeline()._autoWidthCheck(false);
};
Timeline._Impl.prototype._autoWidthCheck = function (C) {
var A = this;
var B = A._starting;
var D = 0;
function E() {
var G = A.getWidthStyle();
if (B) {
A._containerDiv.style[G] = D + "px";
} else {
A._autoResizing = true;
var H = {};
H[G] = D + "px";
SimileAjax.jQuery(A._containerDiv).animate(H, A.autoWidthAnimationTime, "linear", function () {
A._autoResizing = false;
});
}
}
function F() {
var H = 0;
var G = A.getPixelWidth();
if (A._autoResizing) {
return;
}
for (var I = 0;
I < A._bands.length;
I++) {
A._bands[I].checkAutoWidth();
H += A._bandInfos[I].width;
}
if (H > G || C) {
D = H;
E();
A._distributeWidths();
}
}
if (!A.autoWidth) {
return;
}
F();
};
Timeline._Impl.prototype._initialize = function () {
var H = this._containerDiv;
var E = H.ownerDocument;
H.className = H.className.split(" ").concat("timeline-container").join(" ");
var C = (this.isHorizontal()) ? "horizontal" : "vertical";
H.className += " timeline-" + C;
while (H.firstChild) {
H.removeChild(H.firstChild);
}//var A=SimileAjax.Graphics.createTranslucentImage(Timeline.urlPrefix+(this.isHorizontal()?"images/copyright-vertical.png":"images/copyright.png"));
//A.className="timeline-copyright";
//A.title="Timeline copyright SIMILE - www.code.google.com/p/simile-widgets/";
//SimileAjax.DOM.registerEvent(A,"click",function(){window.location="http://code.google.com/p/simile-widgets/";
//});
//H.appendChild(A);
this._bands = [];
for (var B = 0;
B < this._bandInfos.length;
B++) {
var G = new Timeline._Band(this, this._bandInfos[B], B);
this._bands.push(G);
}
this._distributeWidths();
for (var B = 0;
B < this._bandInfos.length;
B++) {
var F = this._bandInfos[B];
if ("syncWith" in F) {
this._bands[B].setSyncWithBand(this._bands[F.syncWith], ("highlight" in F) ? F.highlight : false);
}
}
if (this.autoWidth) {
for (var B = 0;
B < this._bands.length;
B++) {
this._bands[B].addOnScrollListener(this._autoWidthScrollListener);
}
}
var D = SimileAjax.Graphics.createMessageBubble(E);
D.containerDiv.className = "timeline-message-container";
H.appendChild(D.containerDiv);
D.contentDiv.className = "timeline-message";
D.contentDiv.innerHTML = "<img src='" + Timeline.urlPrefix + "images/progress-running.gif' /> Loading...";
this.showLoadingMessage = function () {
D.containerDiv.style.display = "block";
};
this.hideLoadingMessage = function () {
D.containerDiv.style.display = "none";
};
};
Timeline._Impl.prototype._distributeWidths = function () {
var G = this.getPixelLength();
var B = this.getPixelWidth();
var C = 0;
for (var F = 0;
F < this._bands.length;
F++) {
var J = this._bands[F];
var I = this._bandInfos[F];
var E = I.width;
var D;
if (typeof E == "string") {
var H = E.indexOf("%");
if (H > 0) {
var A = parseInt(E.substr(0, H));
D = Math.round(A * B / 100);
} else {
D = parseInt(E);
}
} else {
D = E;
}
J.setBandShiftAndWidth(C, D);
J.setViewLength(G);
C += D;
}
};
Timeline._Impl.prototype.shiftOK = function (C, B) {
var F = B > 0, A = B < 0;
if ((F && this.timeline_start == null) || (A && this.timeline_stop == null) || (B == 0)) {
return(true);
}
var H = false;
for (var E = 0;
E < this._bands.length && !H;
E++) {
H = this._bands[E].busy();
}
if (H) {
return(true);
}
if ((F && this.timeline_at_start) || (A && this.timeline_at_stop)) {
return(false);
}
var D = false;
for (var E = 0;
E < this._bands.length && !D;
E++) {
var G = this._bands[E];
if (F) {
D = (E == C ? G.getMinVisibleDateAfterDelta(B) : G.getMinVisibleDate()) >= this.timeline_start;
} else {
D = (E == C ? G.getMaxVisibleDateAfterDelta(B) : G.getMaxVisibleDate()) <= this.timeline_stop;
}
}
if (F) {
this.timeline_at_start = !D;
this.timeline_at_stop = false;
} else {
this.timeline_at_stop = !D;
this.timeline_at_start = false;
}
return(D);
};
Timeline._Impl.prototype.zoom = function (D, A, G, F) {
var C = new RegExp("^timeline-band-([0-9]+)$");
var E = null;
var B = C.exec(F.id);
if (B) {
E = parseInt(B[1]);
}
if (E != null) {
this._bands[E].zoom(D, A, G, F);
}
this.paint();
};
/* units.js */
Timeline.NativeDateUnit = new Object();
Timeline.NativeDateUnit.createLabeller = function (B, A) {
return new Timeline.GregorianDateLabeller(B, A);
};
Timeline.NativeDateUnit.makeDefaultValue = function () {
return new Date();
};
Timeline.NativeDateUnit.cloneValue = function (A) {
return new Date(A.getTime());
};
Timeline.NativeDateUnit.getParser = function (A) {
if (typeof A == "string") {
A = A.toLowerCase();
}
return(A == "iso8601" || A == "iso 8601") ? Timeline.DateTime.parseIso8601DateTime : Timeline.DateTime.parseGregorianDateTime;
};
Timeline.NativeDateUnit.parseFromObject = function (A) {
return Timeline.DateTime.parseGregorianDateTime(A);
};
Timeline.NativeDateUnit.toNumber = function (A) {
return A.getTime();
};
Timeline.NativeDateUnit.fromNumber = function (A) {
return new Date(A);
};
Timeline.NativeDateUnit.compare = function (D, C) {
var B, A;
if (typeof D == "object") {
B = D.getTime();
} else {
B = Number(D);
}
if (typeof C == "object") {
A = C.getTime();
} else {
A = Number(C);
}
return B - A;
};
Timeline.NativeDateUnit.earlier = function (B, A) {
return Timeline.NativeDateUnit.compare(B, A) < 0 ? B : A;
};
Timeline.NativeDateUnit.later = function (B, A) {
return Timeline.NativeDateUnit.compare(B, A) > 0 ? B : A;
};
Timeline.NativeDateUnit.change = function (A, B) {
return new Date(A.getTime() + B);
};
|
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
* Changes may cause incorrect behavior and will be lost if the code is
* regenerated.
*/
'use strict';
/**
* Collection of Kudu site extension information elements.
*/
class SiteExtensionInfoCollection extends Array {
/**
* Create a SiteExtensionInfoCollection.
* @member {string} [nextLink] Link to next page of resources.
*/
constructor() {
super();
}
/**
* Defines the metadata of SiteExtensionInfoCollection
*
* @returns {object} metadata of SiteExtensionInfoCollection
*
*/
mapper() {
return {
required: false,
serializedName: 'SiteExtensionInfoCollection',
type: {
name: 'Composite',
className: 'SiteExtensionInfoCollection',
modelProperties: {
value: {
required: true,
serializedName: '',
type: {
name: 'Sequence',
element: {
required: false,
serializedName: 'SiteExtensionInfoElementType',
type: {
name: 'Composite',
className: 'SiteExtensionInfo'
}
}
}
},
nextLink: {
required: false,
readOnly: true,
serializedName: 'nextLink',
type: {
name: 'String'
}
}
}
}
};
}
}
module.exports = SiteExtensionInfoCollection;
|
(function(){
var socket = io();
socket.on('refresh', function(){
console.log("getting a refresh event");
// Reload the current page, without using the cache
document.location.reload(true);
});
})(); |
const CustomError = require("../extensions/custom-error");
module.exports = function getSeason(date) {
const season = ["spring", "summer", "autumn", "winter"]
if (date == undefined || date == null) {
return "Unable to determine the time of year!";
}
if (!(date instanceof Date && !isNaN(date.valueOf()))) {
throw Error()
}
if (date.getMonth() >= 11 || date.getMonth() < 2 ) {
return season[3]
} else if (date.getMonth() > 7) {
return season[2]
} else if (date.getMonth() > 4) {
return season[1]
} else {
return season[0]
}
};
|
(function() {
var App, Models, exports,
__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
exports = this;
App = exports.Application || (exports.Application = {});
Models = App.Models || (App.Models = {});
Models.ChangePassword = (function(_super) {
__extends(ChangePassword, _super);
function ChangePassword() {
return ChangePassword.__super__.constructor.apply(this, arguments);
}
ChangePassword.prototype.urlRoot = function() {
return App.serverUrlPrefix + '/password/change';
};
ChangePassword.prototype.defaults = function() {
return {
oldPassword: null,
newPassword: null,
confirmPassword: null
};
};
ChangePassword.prototype.validate = function(attributes) {
var Validation, errors;
Validation = Models.Validation;
errors = {};
if (!attributes.oldPassword) {
Validation.addError(errors, 'oldPassword', 'Old password is required.');
}
if (attributes.newPassword) {
if (!Validation.isValidPasswordLength(attributes.newPassword)) {
Validation.addError(errors, 'newPassword', 'New password length must be between 6 to 64 characters.');
}
} else {
Validation.addError(errors, 'newPassword', 'New password is required.');
}
if (attributes.confirmPassword) {
if (attributes.confirmPassword !== attributes.newPassword) {
Validation.addError(errors, 'confirmPassword', 'New password and confirm password do not match.');
}
} else {
Validation.addError(errors, 'confirmPassword', 'Confirm password is required.');
}
if (_(errors).isEmpty()) {
return void 0;
} else {
return errors;
}
};
return ChangePassword;
})(Backbone.Model);
}).call(this);
|
// @flow
import fs from 'fs';
import path from 'path';
import _ from 'lodash';
import mkdirp from 'mkdirp';
import createError from 'http-errors';
import type { HttpError } from 'http-errors';
import { UploadTarball, ReadTarball } from '@verdaccio/streams';
import { unlockFile, readFile } from '@verdaccio/file-locking';
import type { IUploadTarball } from '@verdaccio/streams';
import type { Callback, Logger, Package } from '@verdaccio/types';
import type { ILocalPackageManager } from '@verdaccio/local-storage';
export const fileExist: string = 'EEXISTS';
export const noSuchFile: string = 'ENOENT';
const resourceNotAvailable: string = 'EAGAIN';
const pkgFileName = 'package.json';
const fSError = function(message: string, code: number = 409): HttpError {
const err: HttpError = createError(code, message);
// $FlowFixMe
err.code = message;
return err;
};
const ErrorCode = {
get503: () => {
return fSError('resource temporarily unavailable', 500);
},
get404: customMessage => {
return fSError('no such package available', 404);
}
};
const tempFile = function(str) {
return `${str}.tmp${String(Math.random()).substr(2)}`;
};
const renameTmp = function(src, dst, _cb) {
const cb = err => {
if (err) {
fs.unlink(src, function() {});
}
_cb(err);
};
if (process.platform !== 'win32') {
return fs.rename(src, dst, cb);
}
// windows can't remove opened file,
// but it seem to be able to rename it
const tmp = tempFile(dst);
fs.rename(dst, tmp, function(err) {
fs.rename(src, dst, cb);
if (!err) {
fs.unlink(tmp, () => {});
}
});
};
class LocalFS implements ILocalPackageManager {
path: string;
logger: Logger;
constructor(path: string, logger: Logger) {
this.path = path;
this.logger = logger;
}
/**
* This function allows to update the package thread-safely
Algorithm:
1. lock package.json for writing
2. read package.json
3. updateFn(pkg, cb), and wait for cb
4. write package.json.tmp
5. move package.json.tmp package.json
6. callback(err?)
* @param {*} name
* @param {*} updateHandler
* @param {*} onWrite
* @param {*} transformPackage
* @param {*} onEnd
*/
updatePackage(name: string, updateHandler: Callback, onWrite: Callback, transformPackage: Function, onEnd: Callback) {
this._lockAndReadJSON(pkgFileName, (err, json) => {
let locked = false;
const self = this;
// callback that cleans up lock first
const unLockCallback = function(lockError: Error) {
let _args = arguments;
if (locked) {
self._unlockJSON(pkgFileName, function() {
// ignore any error from the unlock
onEnd.apply(lockError, _args);
});
} else {
onEnd(..._args);
}
};
if (!err) {
locked = true;
}
if (_.isNil(err) === false) {
if (err.code === resourceNotAvailable) {
return unLockCallback(ErrorCode.get503());
} else if (err.code === noSuchFile) {
return unLockCallback(ErrorCode.get404());
} else {
return unLockCallback(err);
}
}
updateHandler(json, err => {
if (err) {
return unLockCallback(err);
}
onWrite(name, transformPackage(json), unLockCallback);
});
});
}
deletePackage(fileName: string, callback: Callback) {
return fs.unlink(this._getStorage(fileName), callback);
}
removePackage(callback: Callback): void {
fs.rmdir(this._getStorage('.'), callback);
}
createPackage(name: string, value: Package, cb: Function) {
this._createFile(this._getStorage(pkgFileName), this._convertToString(value), cb);
}
savePackage(name: string, value: Package, cb: Function) {
this._writeFile(this._getStorage(pkgFileName), this._convertToString(value), cb);
}
readPackage(name: string, cb: Function) {
this._readStorageFile(this._getStorage(pkgFileName)).then(
function(res) {
try {
const data: any = JSON.parse(res.toString('utf8'));
cb(null, data);
} catch (err) {
cb(err);
}
},
function(err) {
return cb(err);
}
);
}
writeTarball(name: string): IUploadTarball {
const uploadStream = new UploadTarball();
let _ended = 0;
uploadStream.on('end', function() {
_ended = 1;
});
const pathName: string = this._getStorage(name);
fs.exists(pathName, exists => {
if (exists) {
uploadStream.emit('error', fSError(fileExist));
}
const temporalName = path.join(this.path, `${name}.tmp-${String(Math.random()).replace(/^0\./, '')}`);
const file = fs.createWriteStream(temporalName);
const removeTempFile = () => fs.unlink(temporalName, function() {});
let opened = false;
uploadStream.pipe(file);
uploadStream.done = function() {
const onend = function() {
file.on('close', function() {
renameTmp(temporalName, pathName, function(err) {
if (err) {
uploadStream.emit('error', err);
} else {
uploadStream.emit('success');
}
});
});
file.end();
};
if (_ended) {
onend();
} else {
uploadStream.on('end', onend);
}
};
uploadStream.abort = function() {
if (opened) {
opened = false;
file.on('close', function() {
removeTempFile();
});
} else {
// if the file does not recieve any byte never is opened and has to be removed anyway.
removeTempFile();
}
file.end();
};
file.on('open', function() {
opened = true;
// re-emitting open because it's handled in storage.js
uploadStream.emit('open');
});
file.on('error', function(err) {
uploadStream.emit('error', err);
});
});
return uploadStream;
}
readTarball(name: string) {
const pathName: string = this._getStorage(name);
const readTarballStream = new ReadTarball();
const readStream = fs.createReadStream(pathName);
readStream.on('error', function(err) {
readTarballStream.emit('error', err);
});
readStream.on('open', function(fd) {
fs.fstat(fd, function(err, stats) {
if (_.isNil(err) === false) {
return readTarballStream.emit('error', err);
}
readTarballStream.emit('content-length', stats.size);
readTarballStream.emit('open');
readStream.pipe(readTarballStream);
});
});
readTarballStream.abort = function() {
readStream.close();
};
return readTarballStream;
}
_createFile(name: string, contents: any, callback: Function) {
fs.exists(name, exists => {
if (exists) {
return callback(fSError(fileExist));
}
this._writeFile(name, contents, callback);
});
}
_readStorageFile(name: string): Promise<any> {
return new Promise((resolve, reject) => {
fs.readFile(name, (err, data) => {
if (err) {
reject(err);
} else {
resolve(data);
}
});
});
}
_convertToString(value: Package): string {
return JSON.stringify(value, null, '\t');
}
_getStorage(fileName: string = '') {
const storagePath: string = path.join(this.path, fileName);
return storagePath;
}
_writeFile(dest: string, data: string, cb: Function) {
const createTempFile = cb => {
const tempFilePath = tempFile(dest);
fs.writeFile(tempFilePath, data, err => {
if (err) {
return cb(err);
}
renameTmp(tempFilePath, dest, cb);
});
};
createTempFile(err => {
if (err && err.code === noSuchFile) {
mkdirp(path.dirname(dest), function(err) {
if (err) {
return cb(err);
}
createTempFile(cb);
});
} else {
cb(err);
}
});
}
_lockAndReadJSON(name: string, cb: Function) {
const fileName: string = this._getStorage(name);
readFile(
fileName,
{
lock: true,
parse: true
},
function(err, res) {
if (err) {
return cb(err);
}
return cb(null, res);
}
);
}
_unlockJSON(name: string, cb: Function) {
unlockFile(this._getStorage(name), cb);
}
}
export default LocalFS;
|
import pkgutil
from pybtex.bibtex import bst
from io import StringIO
test_data = (
'plain',
'apacite',
'jurabib',
)
def check_bst_parser(dataset_name):
module = __import__('pybtex.tests.bst_parser_test.{0}'.format(dataset_name), globals(), locals(), 'bst')
correct_result = module.bst
bst_data = pkgutil.get_data('pybtex.tests.data', dataset_name + '.bst').decode('latin1')
actual_result = list(bst.parse_stream(StringIO(bst_data)))
for correct_element, actual_element in zip(actual_result, correct_result):
assert correct_element == actual_element, '\n{0}\n{1}'.format(correct_element, actual_element)
def test_bst_parser():
for dataset_name in test_data:
yield check_bst_parser, dataset_name
|
import React, { Component } from 'react';
import { Modal, Dimensions } from 'react-native';
import PropTypes from 'prop-types';
import {
View,
Text,
Container,
Header,
Content,
ListItem,
CheckBox,
Left,
Right,
Icon,
Body,
Title,
Button,
} from 'native-base';
const deviceWidth = Dimensions.get('window').width;
export default class SelectField extends Component {
static propTypes = {
attributes: PropTypes.object,
updateValue: PropTypes.func,
theme: PropTypes.object,
ErrorComponent: PropTypes.func,
}
constructor(props) {
super(props);
this.state = {
modalVisible: false,
};
}
toggleModalVisible() {
this.setState({
modalVisible: !this.state.modalVisible,
});
}
toggleSelect(value) {
const attributes = this.props.attributes;
const newSelected = attributes.multiple ? attributes.value : value;
if (attributes.multiple) {
const index = attributes.objectType ? newSelected.findIndex(option =>
option[attributes.primaryKey] === value[attributes.primaryKey]
) : newSelected.indexOf(value);
if (index === -1) {
newSelected.push(value);
} else {
newSelected.splice(index, 1);
}
}
this.setState({
modalVisible: attributes.multiple ? this.state.modalVisible : false,
}, () => this.props.updateValue(this.props.attributes.name, newSelected));
}
render() {
const { theme, attributes, ErrorComponent } = this.props;
const selectedText = attributes.multiple ?
attributes.value.length || 'None' :
attributes.objectType ?
(attributes.value && attributes.value[attributes.labelKey]) || 'None'
: attributes.value || 'None';
return (
<View>
<ListItem icon onPress={() => this.toggleModalVisible()}>
<Body>
<Text>{attributes.label}</Text>
</Body>
<Right>
<View style={{ width: deviceWidth / 2, alignItems: 'flex-end' }}>
<Text numberOfLines={1} ellipSizeMode="tail">{selectedText}</Text>
</View>
<Icon name="ios-arrow-forward" />
</Right>
</ListItem>
<View style={{ paddingHorizontal: 15 }}>
<ErrorComponent {...{ attributes, theme }} />
</View>
<Modal
visible={this.state.modalVisible}
animationType="none"
onRequestClose={() => this.toggleModalVisible()}
>
<Container style={{ flex: 1 }}>
<Header>
<Left>
<Button
transparent
onPress={() => this.toggleModalVisible()}
>
<Icon name="arrow-back" />
</Button>
</Left>
<Body>
<Title>{attributes.label || 'Select'}</Title>
</Body>
<Right />
</Header>
<Content>
{
attributes.options.map((item, index) => {
let isSelected = false;
if (attributes.multiple) {
isSelected = attributes.objectType ?
attributes.value.findIndex(option =>
option[attributes.primaryKey] === item[attributes.primaryKey]
) !== -1 : (attributes.value.indexOf(item) !== -1);
}
return (
<ListItem
key={index}
onPress={() => this.toggleSelect(item)}
>
{ attributes.multiple &&
<CheckBox
onPress={() => this.toggleSelect(item)}
checked={isSelected}
/>
}
<Body>
<Text style={{ paddingHorizontal: 5 }}>
{attributes.objectType ? item[attributes.labelKey] : item }
</Text>
</Body>
</ListItem>);
})
}
</Content>
</Container>
</Modal>
</View>
);
}
}
|
const express = require('express');
const cors = require('cors');
const bodyParser = require('body-parser');
const DB = require('./db');
module.exports = client => {
const app = express();
const db = DB(client);
const getAllTodos = (req, res, next) => {
db.getAll((err, data) => {
if (err) return next(err);
res.status(200).send(data);
});
};
const getOneTodo = (req, res, next) => {
const key = Number(req.params.id);
db.getTodo(key, (err, data) => {
if (err) return next(err);
if (!data[0]) return next();
res.status(200).send(data[0]);
});
};
const postTodo = (req, res, next) => {
const todo = req.body;
const title = todo.title;
const date = todo.date;
const time = todo.time;
const complete = todo.complete;
db.createTodo(title, date, time, complete, (err, data) => {
if (err) return next(err);
res.status(201).send(data[0]);
});
};
const editTodo = (req, res, next) => {
const key = Number(req.params.id);
const todo = req.body;
const title = todo.title;
const date = todo.date;
const time = todo.time;
const complete = todo.complete;
db.updateTodo(key, title, date, time, complete, (err, data) => {
if (err) return next(err);
if (!data[0]) return next();
res.status(204).send(data[0]);
});
};
const deleteAllTodos = (req, res, next) => {
db.deleteAll((err, data) => {
if (err) return next(err);
res.status(204).send(data);
});
};
const deleteOneTodo = (req, res, next) => {
const key = Number(req.params.id);
db.deleteTodo(key, (err, data) => {
if (err) return next(err);
if (!data[0]) return next();
res.status(204).send(data[0]);
});
};
app.use(cors());
app.use(bodyParser.json());
app.get('/todos', getAllTodos);
app.get('/todos/:id', getOneTodo);
app.post('/todos', postTodo);
app.put('/todos/:id', editTodo);
app.delete('/todos/:id', deleteOneTodo);
app.delete('/todos', deleteAllTodos);
app.use((req, res) => res.status(404).send('404: Not Found'));
return app;
};
|
import { useEffect } from 'react';
import { Link as RouterLink, useLocation } from 'react-router-dom';
import PropTypes from 'prop-types';
import {
Avatar,
Box,
Divider,
Drawer,
Hidden,
List,
Typography
} from '@material-ui/core';
import {
BarChart as BarChartIcon,
Lock as LockIcon,
Settings as SettingsIcon,
ShoppingBag as ShoppingBagIcon,
User as UserIcon,
UserPlus as UserPlusIcon,
Users as UsersIcon
} from 'react-feather';
import NavItem from './NavItem';
const user = {
avatar: '/static/images/avatars/chris_henderson.png',
name: 'Chris Henderson'
};
const items = [
{
href: '/app/dashboard',
icon: BarChartIcon,
title: 'Dashboard'
},
{
href: '/app/customers',
icon: UsersIcon,
title: 'Bot Marketplace'
},
{
href: '/app/products',
icon: ShoppingBagIcon,
title: 'Portfolios'
},
{
href: '/app/account',
icon: UserIcon,
title: 'Account'
},
{
href: '/app/settings',
icon: SettingsIcon,
title: 'Settings'
},
{
href: '/login',
icon: LockIcon,
title: 'Login'
},
{
href: '/register',
icon: UserPlusIcon,
title: 'Register'
}
];
const DashboardSidebar = ({ onMobileClose, openMobile }) => {
const location = useLocation();
useEffect(() => {
if (openMobile && onMobileClose) {
onMobileClose();
}
}, [location.pathname]);
const content = (
<Box
sx={{
display: 'flex',
flexDirection: 'column',
height: '100%'
}}
>
<Box
sx={{
alignItems: 'center',
display: 'flex',
flexDirection: 'column',
p: 2
}}
>
<Avatar
component={RouterLink}
src={user.avatar}
sx={{
cursor: 'pointer',
width: 64,
height: 64
}}
to="/app/account"
/>
<Typography
color="textPrimary"
variant="h5"
>
{user.name}
</Typography>
<Typography
color="textSecondary"
variant="body2"
>
{user.jobTitle}
</Typography>
</Box>
<Divider />
<Box sx={{ p: 2 }}>
<List>
{items.map((item) => (
<NavItem
href={item.href}
key={item.title}
title={item.title}
icon={item.icon}
/>
))}
</List>
</Box>
<Box sx={{ flexGrow: 1 }} />
</Box>
);
return (
<>
<Hidden lgUp>
<Drawer
anchor="left"
onClose={onMobileClose}
open={openMobile}
variant="temporary"
PaperProps={{
sx: {
width: 256
}
}}
>
{content}
</Drawer>
</Hidden>
<Hidden xlDown>
<Drawer
anchor="left"
open
variant="persistent"
PaperProps={{
sx: {
width: 256,
top: 64,
height: 'calc(100% - 64px)'
}
}}
>
{content}
</Drawer>
</Hidden>
</>
);
};
DashboardSidebar.propTypes = {
onMobileClose: PropTypes.func,
openMobile: PropTypes.bool
};
DashboardSidebar.defaultProps = {
onMobileClose: () => {
},
openMobile: false
};
export default DashboardSidebar;
|
import { Meteor } from 'meteor/meteor';
import { Match } from 'meteor/check';
import { Random } from 'meteor/random';
import { TAPi18n } from 'meteor/tap:i18n';
import { slashCommands } from '../../utils';
import { Notifications } from '../../notifications';
import { Users } from '../../models';
/*
* Msg is a named function that will replace /msg commands
*/
function Msg(command, params, item) {
if (command !== 'msg' || !Match.test(params, String)) {
return;
}
const trimmedParams = params.trim();
const separator = trimmedParams.indexOf(' ');
const user = Meteor.users.findOne(Meteor.userId());
if (separator === -1) {
return Notifications.notifyUser(Meteor.userId(), 'message', {
_id: Random.id(),
rid: item.rid,
ts: new Date,
msg: TAPi18n.__('Username_and_message_must_not_be_empty', null, user.language),
});
}
const message = trimmedParams.slice(separator + 1);
const targetUsernameOrig = trimmedParams.slice(0, separator);
const targetUsername = targetUsernameOrig.replace('@', '');
const targetUser = Users.findOneByUsernameIgnoringCase(targetUsername);
if (targetUser == null) {
Notifications.notifyUser(Meteor.userId(), 'message', {
_id: Random.id(),
rid: item.rid,
ts: new Date,
msg: TAPi18n.__('Username_doesnt_exist', {
postProcess: 'sprintf',
sprintf: [targetUsernameOrig],
}, user.language),
});
return;
}
const { rid } = Meteor.call('createDirectMessage', targetUsername);
const msgObject = {
_id: Random.id(),
rid,
msg: message,
};
Meteor.call('sendMessage', msgObject);
}
slashCommands.add('msg', Msg, {
description: 'Direct_message_someone',
params: '@username <message>',
});
|
var timedQueue = function(period){
var timedDoubleLinkedCell = function(item,instant){
var prev, next;
return {
next:function(){return next;},
prev:function(){return prev;},
setNext:function(n){
next = n;
},
setPrev:function(p){
prev = p;
},
item:function(){return item;},
instant:function(){return instant;}
};
};
var start,end;
var clearExpired = function(){
var now = new Date().getTime();
var threshold = now - period;
while (end != undefined && end.instant() < threshold){
var tempEnd = end;
end = end.prev();
tempEnd.setPrev(undefined);
if (end != undefined){
end.setNext(undefined);
}
}
if (end == undefined){
start = undefined;
}
};
var enqFunc = function(item){
var c = timedDoubleLinkedCell(item,new Date().getTime());
if (start == undefined){
start = c;
if (end == undefined){
end = c;
}
} else {
c.setNext(start);
start.setPrev(c);
start = c;
}
clearExpired();
};
var deqFunc = function(){
clearExpired();
if (end != undefined){
var tempEnd = end;
var item = end.item();
end = end.prev();
tempEnd.setPrev(undefined);
end.setNext(undefined);
return item;
} else {
return undefined;
}
};
var peekFunc = function(){
clearExpired();
return end != undefined ? end.item() : undefined;
};
var itemsFunc = function(){
clearExpired();
var i = end;
var items = [];
while (i != undefined){
items.push(i.item());
i = i.prev();
}
return items;
};
var oldestFunc = function(){
return end;
};
var newestFunc = function(){
return start;
};
return {
enqueue:enqFunc,
dequeue:deqFunc,
peek:peekFunc,
items:itemsFunc,
oldest:oldestFunc,
newest:newestFunc
};
};
|
import { h } from '../snabbdom'
import { CLASS_OR_ID } from '../../../config'
import paragraphIcon from '../../../assets/pngicon/paragraph/2.png'
import htmlIcon from '../../../assets/pngicon/html/2.png'
import hrIcon from '../../../assets/pngicon/horizontal_line/2.png'
import frontMatterIcon from '../../../assets/pngicon/front_matter/2.png'
import header1Icon from '../../../assets/pngicon/heading_1/2.png'
import header2Icon from '../../../assets/pngicon/heading_2/2.png'
import header3Icon from '../../../assets/pngicon/heading_3/2.png'
import header4Icon from '../../../assets/pngicon/heading_4/2.png'
import header5Icon from '../../../assets/pngicon/heading_5/2.png'
import header6Icon from '../../../assets/pngicon/heading_6/2.png'
import newTableIcon from '../../../assets/pngicon/new_table/2.png'
import bulletListIcon from '../../../assets/pngicon/bullet_list/2.png'
import codeIcon from '../../../assets/pngicon/code/2.png'
import quoteIcon from '../../../assets/pngicon/quote_block/2.png'
import todoListIcon from '../../../assets/pngicon/todolist/2.png'
import mathblockIcon from '../../../assets/pngicon/math/2.png'
import orderListIcon from '../../../assets/pngicon/order_list/2.png'
import flowchartIcon from '../../../assets/pngicon/flowchart/2.png'
import sequenceIcon from '../../../assets/pngicon/sequence/2.png'
import mermaidIcon from '../../../assets/pngicon/mermaid/2.png'
import vegaIcon from '../../../assets/pngicon/chart/2.png'
const FUNCTION_TYPE_HASH = {
'mermaid': mermaidIcon,
'flowchart': flowchartIcon,
'sequence': sequenceIcon,
'vega-lite': vegaIcon,
'table': newTableIcon,
'html': htmlIcon,
'multiplemath': mathblockIcon,
'fencecode': codeIcon,
'indentcode': codeIcon,
'frontmatter': frontMatterIcon
}
export default function renderIcon (block) {
if (block.parent) {
console.error('Only top most block can render front icon button.')
}
const { type, functionType, listType } = block
const selector = `a.${CLASS_OR_ID['AG_FRONT_ICON']}`
let icon = null
switch (type) {
case 'p': {
icon = paragraphIcon
break
}
case 'figure':
case 'pre': {
icon = FUNCTION_TYPE_HASH[functionType]
if (!icon) {
console.warn(`Unhandled functionType ${functionType}`)
icon = paragraphIcon
}
break
}
case 'ul': {
if (listType === 'task') {
icon = todoListIcon
} else {
icon = bulletListIcon
}
break
}
case 'ol': {
icon = orderListIcon
break
}
case 'blockquote': {
icon = quoteIcon
break
}
case 'h1': {
icon = header1Icon
break
}
case 'h2': {
icon = header2Icon
break
}
case 'h3': {
icon = header3Icon
break
}
case 'h4': {
icon = header4Icon
break
}
case 'h5': {
icon = header5Icon
break
}
case 'h6': {
icon = header6Icon
break
}
case 'hr': {
icon = hrIcon
break
}
default:
icon = paragraphIcon
break
}
const iconVnode = h('i.icon', h(`i.icon-inner`, {
style: {
background: `url(${icon}) no-repeat`,
'background-size': '100%'
}
}, ''))
return h(selector, {
attrs: {
contenteditable: 'false'
}
}, iconVnode)
}
|
/**
* Layout component that queries for data
* with Gatsby's useStaticQuery component
*
* See: https://www.gatsbyjs.org/docs/use-static-query/
*/
import React, { useState } from "react"
import PropTypes from "prop-types"
import { useStaticQuery, graphql, Link } from "gatsby"
import HamburgerMenu from 'react-hamburger-menu'
import oralignLogo from '../images/oralignLogo.svg'
import Helmet from 'react-helmet'
import Fade from 'react-reveal/Fade';
import "./layout.scss"
const Layout = ({ children }) => {
const data = useStaticQuery(graphql`
query {
site {
siteMetadata {
title
}
}
allContentfulAnnouncement {
nodes {
show,
message,
link
}
}
allContentfulNavigation {
nodes {
name,
items {
nav {
title,
nesting,
path,
nested {
title,
path
}
}
}
}
}
allContentfulSocial {
nodes {
socialName,
socialLink,
socialIcon {
file {
url
}
}
}
}
}
`)
const [state, setState] = useState({open: false})
const announcement = data.allContentfulAnnouncement.nodes[0]
const navigation = data.allContentfulNavigation.nodes[0].items.nav
const socials = data.allContentfulSocial.nodes
console.log(socials)
const handleClick= function() {
setState({
open: !state.open
});
}
return (
<div className="layout">
<Helmet>
<meta charSet="utf-8" />
<script>{`(function(d, s, id) { var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementById(id)) return; js = d.createElement(s); js.id = id; js.src = "//affil.walmart.com/buttons/buynow.min.js"; fjs.parentNode.insertBefore(js, fjs); }(document, 'script', 'walmart-buynow-js'));`}</script>
</Helmet>
<div className="navigation box-shadow">
{announcement.show ? <div className="announcment"><a target="_Blank" href={announcement.link}>{announcement.message}</a></div> : <></>}
<nav className="main-navigation">
<div className="space"></div>
<Link to="/"><img src={oralignLogo}></img></Link>
<div className="space">
<HamburgerMenu
isOpen={state.open}
menuClicked={handleClick.bind(this)}
width={30}
height={20}
strokeWidth={3}
rotate={0}
color='blue'
borderRadius={0}
animationDuration={0.5}
/>
</div>
</nav>
<nav className={`sub-navigation ${state.open ? `menu-open` : `menu-closed`}`}>
{navigation.map(item => {
if (item.nesting === false) {
return <Link className="navigation-item" to={ item.path }>{item.title}</Link>
}
else if (item.nesting === true) {
//TODO
}
})}
<div className="navigation-social-container">
{socials.map(social => {
return <Link to='/' className="navigation-social">
<img src={social.socialIcon.file.url}></img>
</Link>
})}
</div>
</nav>
</div>
<main>{children}</main>
<footer>
<div className="footer">
<svg width="" height="32" viewBox="0 0 829 179" fill="none" xmlns="http://www.w3.org/2000/svg">
<g clip-path="url(#clip0)">
<path d="M37.7853 75.584C32.6549 75.6639 27.5599 74.7219 22.7973 72.8127C18.4173 71.0052 14.4368 68.3512 11.084 65.0027C7.61528 61.4067 4.95313 57.1123 3.2751 52.4059C1.23895 47.7961 0.126395 42.8317 0.000407487 37.7937C-0.113346 32.5781 0.829193 27.3934 2.7713 22.5516C4.52739 18.0699 7.18528 13.9967 10.5802 10.5847C13.933 7.23618 17.9135 4.58218 22.2935 2.77467C27.2129 0.798526 32.486 -0.144772 37.7853 0.00338254C42.7464 -0.0107458 47.6639 0.930125 52.2695 2.77467C56.6495 4.58218 60.6299 7.23618 63.9828 10.5847C67.4515 14.1807 70.1136 18.4751 71.7916 23.1814C73.6519 27.827 74.5929 32.7895 74.5625 37.7937C74.5961 42.7981 73.655 47.7613 71.7916 52.4059C70.1136 57.1123 67.4515 61.4067 63.9828 65.0027C60.6299 68.3512 56.6495 71.0052 52.2695 72.8127C47.6639 74.6572 42.7464 75.5981 37.7853 75.584V75.584ZM37.7853 67.774C41.7357 67.8341 45.6503 67.0166 49.2467 65.3806C52.6114 63.8875 55.6498 61.7475 58.1891 59.0822C60.406 56.0552 62.03 52.6359 62.9752 49.0048C64.4979 45.4548 65.3519 41.654 65.4942 37.7937C65.4155 33.7223 64.5606 29.7034 62.9752 25.9527C61.6224 22.4833 59.6603 19.2838 57.1815 16.5051C54.6422 13.8399 51.6038 11.6999 48.2391 10.2068C44.625 8.62506 40.7227 7.80853 36.7777 7.80853C32.8327 7.80853 28.9304 8.62506 25.3163 10.2068C21.9516 11.6999 18.9132 13.8399 16.3738 16.5051C13.8951 19.2838 11.933 22.4833 10.5802 25.9527C9.33814 29.7699 8.82543 33.7868 9.06878 37.7937C9.01959 41.707 9.70309 45.5949 11.084 49.2567C12.406 52.7413 14.3714 55.9462 16.8776 58.7043C19.417 61.3695 22.4554 63.5096 25.8201 65.0027C29.5908 66.627 33.6853 67.3598 37.7853 67.1441V67.774Z"/>
<path d="M93.2017 1.76488H111.464C114.862 1.57707 118.268 1.57707 121.666 1.76488C124.829 2.06684 127.906 2.96439 130.735 4.4102C133.442 5.71267 135.716 7.7683 137.284 10.3307C139.161 13.481 140.039 17.1263 139.803 20.786C139.908 23.0906 139.549 25.3928 138.749 27.5564C137.948 29.72 136.722 31.7012 135.143 33.3828C131.713 36.7345 127.298 38.8979 122.548 39.5552L142.322 73.1885H131.868L112.598 41.0668H101.64V73.1885H93.2017V1.76488ZM101.64 33.2568H109.197H116.502C118.862 33.1883 121.197 32.7636 123.43 31.9971C125.481 31.3258 127.311 30.1061 128.719 28.47C130.226 26.5385 130.946 24.1083 130.735 21.6678C130.841 19.547 130.315 17.4423 129.223 15.6213C128.494 14.0542 127.365 12.7073 125.949 11.7163C123.999 10.8242 121.912 10.2705 119.777 10.0787C117.646 9.81601 115.501 9.68979 113.354 9.70084H101.64V33.2568Z" />
<path d="M183.005 1.77051H190.94L221.294 73.1942H211.344L204.164 55.6847H168.521L161.09 73.1942H151.14L183.005 1.77051ZM186.783 12.7297L171.795 47.7487H201.519L186.783 12.7297Z" />
<path d="M235.777 1.77051H244.216V64.7543H277.089V72.6903H235.777V1.77051Z" />
<path d="M291.197 1.77051H299.635V73.1942H291.197V1.77051Z" />
<path d="M383.139 68.2745C379.216 70.5745 374.97 72.2729 370.544 73.3132C365.956 74.6597 361.216 75.4216 356.437 75.5806C351.197 75.6467 345.989 74.75 341.072 72.9353C336.409 71.2265 332.129 68.6154 328.477 65.2512C325.043 61.9195 322.378 57.8785 320.668 53.4103C318.841 48.4142 318.027 43.1042 318.275 37.7903C318.198 32.5127 319.228 27.2776 321.298 22.4222C323.161 17.9418 325.951 13.9064 329.484 10.5813C333.134 7.24332 337.417 4.67306 342.079 3.02322C346.711 1.08861 351.671 0.0622577 356.689 0C361.306 0.0150618 365.894 0.737251 370.292 2.14145C374.672 3.57451 378.646 6.03665 381.879 9.3216L375.582 15.9979C373.109 13.3748 370.103 11.3128 366.765 9.95144C363.365 8.56543 359.732 7.83871 356.06 7.80999C352.165 7.77152 348.305 8.54368 344.724 10.0774C341.29 11.5216 338.167 13.6177 335.53 16.2498C332.947 18.9494 330.896 22.1119 329.484 25.5714C328.051 29.4815 327.367 33.6269 327.469 37.7903C327.461 41.7933 328.187 45.764 329.61 49.5053C331.021 53.0027 333.071 56.2066 335.656 58.9528C338.338 61.5886 341.503 63.684 344.976 65.1253C348.974 66.7388 353.261 67.5107 357.571 67.3927C360.627 67.3577 363.669 66.9774 366.639 66.259C369.428 65.5536 372.1 64.4506 374.574 62.9838V41.0654H358.201V33.2555H383.391L383.139 68.2745Z" />
<path d="M405.809 1.77051H416.515L457.826 61.1013V1.77051H466.013V73.1942H455.307L414.5 13.8634V73.1942H405.935L405.809 1.77051Z" />
<path d="M522.312 1.77051H544.102C547.026 1.79495 549.94 2.1328 552.792 2.77825C555.469 3.2664 558.032 4.2489 560.349 5.6755C562.54 7.04906 564.392 8.90088 565.765 11.0921C567.156 13.638 567.851 16.5057 567.78 19.406C567.909 23.1437 566.704 26.8054 564.38 29.7353C561.982 32.5052 558.832 34.5184 555.311 35.5298V35.5298C557.492 35.773 559.619 36.3686 561.609 37.2934C563.546 38.2275 565.296 39.5083 566.773 41.0724C568.251 42.6368 569.407 44.4775 570.173 46.489C570.978 48.5805 571.405 50.7985 571.433 53.0393C571.566 56.4898 570.691 59.9042 568.914 62.8648C567.291 65.3684 565.087 67.4428 562.49 68.9112C559.71 70.4868 556.688 71.5933 553.548 72.1864C550.257 72.7243 546.932 73.019 543.598 73.0682H522.312V1.77051ZM530.751 32.0027H542.464C544.436 32.1321 546.413 32.1321 548.384 32.0027C550.442 31.7723 552.421 31.0836 554.178 29.9873C555.695 29.122 556.989 27.9142 557.956 26.4602C558.915 24.5917 559.391 22.5132 559.342 20.4137C559.397 18.5538 558.916 16.7172 557.956 15.1231C557.05 13.6798 555.735 12.5394 554.178 11.8479C552.567 10.9753 550.822 10.3792 549.014 10.0844H543.346H530.751V32.0027ZM530.751 65.2582H545.109C547.159 65.5112 549.232 65.5112 551.281 65.2582C553.252 64.8495 555.13 64.0808 556.823 62.9908C558.477 62.1103 559.868 60.8062 560.853 59.2117C561.898 57.4633 562.422 55.4532 562.364 53.4172C562.418 51.2219 561.897 49.0507 560.853 47.1188C559.907 45.5121 558.617 44.1353 557.075 43.0879C555.376 42.0616 553.494 41.377 551.533 41.0724C549.467 40.6075 547.352 40.396 545.235 40.4426H530.751V65.2582Z" />
<path d="M614.004 1.77051H621.939L652.293 73.1942H642.343L635.038 55.6847H599.52L591.963 73.1942H582.391L614.004 1.77051ZM617.782 12.7297L602.794 47.7487H631.889L617.782 12.7297Z" />
<path d="M666.776 1.77051H688.566C691.491 1.78702 694.405 2.12496 697.256 2.77825C699.933 3.2664 702.496 4.2489 704.813 5.6755C707.004 7.04906 708.856 8.90088 710.229 11.0921C711.674 13.6168 712.373 16.4998 712.244 19.406C712.373 23.1437 711.168 26.8054 708.844 29.7353C706.446 32.5052 703.296 34.5184 699.775 35.5298V35.5298C701.993 35.7888 704.159 36.3835 706.199 37.2934C708.077 38.2623 709.78 39.5397 711.237 41.0724C714.228 44.3404 715.89 48.6087 715.897 53.0393C716.03 56.4898 715.154 59.9042 713.378 62.8648C711.755 65.3684 709.551 67.4428 706.954 68.9112C704.174 70.4868 701.152 71.5933 698.012 72.1864C694.721 72.7243 691.396 73.019 688.062 73.0682H666.776V1.77051ZM675.215 32.0027H686.928C688.899 32.1321 690.877 32.1321 692.848 32.0027C694.66 31.802 696.415 31.2456 698.012 30.3652C699.529 29.4999 700.823 28.2921 701.79 26.8381C702.749 24.9696 703.225 22.8911 703.176 20.7916C703.269 18.944 702.832 17.1083 701.916 15.501C701.035 14.1303 699.822 13.0039 698.39 12.2258C696.903 11.2074 695.236 10.4807 693.478 10.0844H687.81H675.215V32.0027ZM675.215 65.2582H689.573C691.623 65.5112 693.695 65.5112 695.745 65.2582C697.722 64.87 699.604 64.0998 701.287 62.9908C702.941 62.1103 704.332 60.8062 705.317 59.2117C706.362 57.4633 706.886 55.4532 706.828 53.4172C706.974 51.0528 706.45 48.6952 705.317 46.615C704.371 45.0082 703.081 43.6314 701.538 42.584C699.876 41.5784 698.038 40.8947 696.123 40.5685C694.056 40.1096 691.942 39.8982 689.825 39.9387H675.215V65.2582Z" />
<path d="M752.172 42.458L725.597 1.77051H736.302L756.328 34.0182L776.984 1.77051H787.186L760.611 42.458V73.1942H752.172V42.458Z" />
<path d="M806.708 4.41392H800.411V21.4195H798.144V4.41392H791.846V2.39844H806.708V4.41392Z" />
<path d="M809.352 2.39844H812.627L818.672 17.2626L825.725 2.39844H829V21.4195H826.733V5.42166L819.806 21.4195H818.672L811.619 5.42166V21.4195H809.352V2.39844Z" />
<path d="M38.6672 169.56L44.8388 162.254C49.7885 167.014 56.3614 169.716 63.2274 169.812C69.5249 169.812 73.5553 166.915 73.5553 162.506C73.5553 158.349 71.2882 156.082 60.9603 153.562C50.6324 151.043 41.5641 146.886 41.5641 136.179C41.6408 133.75 42.2114 131.363 43.241 129.163C44.2706 126.962 45.7376 124.994 47.5526 123.379C49.3675 121.765 51.4924 120.536 53.7976 119.77C56.1027 119.003 58.5399 118.715 60.9603 118.921C68.6263 118.691 76.125 121.191 82.1198 125.975L76.5781 133.659C72.087 129.97 66.5153 127.847 60.7084 127.613C54.7888 127.613 51.2622 130.762 51.2622 134.541C51.2622 138.95 53.9071 140.966 65.1166 143.611C76.3262 146.256 83.7572 151.043 83.7572 160.742C83.7572 172.457 75.5705 178.882 62.9755 178.882C53.9919 178.926 45.3182 175.6 38.6672 169.56V169.56Z" />
<path d="M93.2027 149.151C93.1334 145.124 93.8796 141.124 95.3964 137.393C96.9132 133.662 99.1691 130.277 102.029 127.44C104.888 124.604 108.292 122.376 112.035 120.89C115.778 119.404 119.783 118.69 123.808 118.793C127.79 118.691 131.752 119.394 135.456 120.859C139.16 122.325 142.53 124.524 145.364 127.323C148.198 130.122 150.439 133.465 151.95 137.151C153.462 140.837 154.214 144.79 154.162 148.773V148.773C154.197 152.779 153.426 156.751 151.894 160.453C150.362 164.155 148.1 167.51 145.245 170.319C142.389 173.129 138.997 175.334 135.271 176.805C131.545 178.276 127.561 178.981 123.557 178.879C119.591 178.998 115.643 178.315 111.948 176.871C108.253 175.428 104.888 173.252 102.053 170.477C99.2189 167.701 96.9741 164.381 95.4533 160.717C93.9325 157.052 93.167 153.118 93.2027 149.151V149.151ZM143.582 149.151C143.684 146.475 143.245 143.805 142.29 141.302C141.336 138.8 139.886 136.515 138.028 134.586C136.17 132.658 133.942 131.124 131.477 130.076C129.012 129.029 126.361 128.49 123.682 128.492C121.037 128.507 118.422 129.055 115.993 130.105C113.565 131.155 111.373 132.684 109.55 134.602C107.727 136.519 106.31 138.785 105.384 141.263C104.458 143.742 104.042 146.382 104.16 149.025C104.042 151.702 104.464 154.374 105.403 156.883C106.342 159.392 107.778 161.686 109.624 163.627C111.471 165.568 113.69 167.116 116.149 168.178C118.608 169.24 121.256 169.795 123.934 169.81C126.586 169.779 129.204 169.215 131.633 168.151C134.062 167.087 136.252 165.546 138.073 163.619C139.895 161.691 141.31 159.417 142.235 156.932C143.159 154.446 143.575 151.8 143.457 149.151H143.582Z" />
<path d="M163.735 149.145C163.7 145.139 164.472 141.167 166.004 137.465C167.536 133.764 169.797 130.408 172.653 127.599C175.509 124.79 178.901 122.584 182.627 121.114C186.353 119.643 190.337 118.937 194.341 119.039C198.323 118.937 202.285 119.64 205.989 121.106C209.693 122.571 213.063 124.77 215.897 127.569C218.731 130.368 220.971 133.711 222.483 137.397C223.995 141.083 224.747 145.036 224.695 149.019V149.019C224.73 153.025 223.959 156.998 222.427 160.699C220.895 164.401 218.633 167.756 215.777 170.566C212.922 173.375 209.53 175.58 205.804 177.051C202.078 178.522 198.094 179.227 194.089 179.126C190.103 179.246 186.133 178.555 182.421 177.096C178.709 175.636 175.332 173.439 172.494 170.636C169.656 167.833 167.417 164.483 165.911 160.789C164.406 157.095 163.666 153.134 163.735 149.145V149.145ZM214.115 149.145C214.217 146.469 213.777 143.799 212.823 141.296C211.869 138.794 210.419 136.51 208.561 134.581C206.703 132.652 204.474 131.118 202.009 130.071C199.544 129.023 196.893 128.485 194.215 128.487C191.57 128.501 188.954 129.049 186.526 130.099C184.098 131.149 181.906 132.678 180.083 134.596C178.26 136.513 176.843 138.779 175.917 141.258C174.991 143.736 174.574 146.376 174.693 149.019V149.019C174.574 151.696 174.997 154.368 175.936 156.877C176.875 159.387 178.311 161.68 180.157 163.621C182.003 165.562 184.223 167.11 186.682 168.172C189.141 169.235 191.789 169.79 194.467 169.804C197.129 169.79 199.761 169.238 202.205 168.182C204.648 167.126 206.854 165.587 208.688 163.658C210.523 161.729 211.95 159.449 212.882 156.955C213.815 154.461 214.234 151.805 214.115 149.145V149.145Z" />
<path d="M248.247 129.241H229.858V119.793H277.089V129.241H258.574V177.99H248.247V129.241Z" />
<path d="M287.796 119.793H298.124V143.979H325.833V119.793H336.035V177.99H325.833V153.552H298.124V177.99H287.796V119.793Z" />
<path d="M351.022 119.793H394.223V128.989H361.224V144.105H390.445V153.3H361.224V168.92H394.601V177.99H351.022V119.793Z" />
<path d="M431.629 119.794H457.827C463.348 119.461 468.778 121.317 472.941 124.959C474.271 126.19 475.32 127.694 476.015 129.368C476.711 131.042 477.037 132.847 476.971 134.658V134.658C476.941 137.351 476.126 139.976 474.628 142.213C473.129 144.451 471.011 146.202 468.533 147.255C471.811 147.875 474.768 149.628 476.886 152.206C479.004 154.785 480.149 158.026 480.12 161.363C480.12 171.693 471.555 177.235 458.583 177.235H431.629V119.794ZM455.686 144.988C462.235 144.988 466.643 142.342 466.643 137.052C466.643 132.391 462.991 129.619 456.441 129.619H441.705V145.114L455.686 144.988ZM458.709 169.551C465.636 169.551 469.918 166.906 469.918 161.615C469.918 156.703 466.014 153.805 457.323 153.805H441.705V169.677L458.709 169.551Z" />
<path d="M491.203 119.793H534.404V128.989H501.909V144.105H531.129V153.3H501.909V168.92H535.285V177.99H491.203V119.793Z" />
<path d="M561.607 129.241H543.219V119.793H590.45V129.241H571.935V177.99H561.607V129.241Z" />
<path d="M615.515 129.241H597V119.793H644.357V129.241H625.842V177.99H615.515V129.241Z" />
<path d="M654.938 119.793H698.138V128.989H665.265V144.105H694.486V153.3H665.265V168.92H698.642V177.99H654.938V119.793Z" />
<path d="M710.732 119.795H736.678C742.846 119.438 748.907 121.519 753.555 125.59C756.731 129.004 758.449 133.524 758.341 138.187V138.187C758.486 142.289 757.174 146.31 754.638 149.538C752.102 152.766 748.506 154.992 744.487 155.822L760.231 177.866H747.636L733.277 157.586H720.682V177.866H710.354L710.732 119.795ZM735.922 148.642C743.227 148.642 748.517 144.863 748.517 138.942C748.517 132.644 743.983 129.243 735.922 129.243H721.06V148.642H735.922Z" />
<path d="M776.857 121.934H770.559V138.562H768.292V121.934H761.995V119.793H776.857V121.934Z" />
<path d="M779.626 119.793H782.901L789.451 134.783L796 119.793H799.275V138.562H797.007V122.942L790.08 138.562H788.695L781.894 122.564V138.562H779.626V119.793Z" />
</g>
<defs>
<clipPath id="clip0">
<rect width="829" height="179" fill="white"/>
</clipPath>
</defs>
</svg>
<ul>
<h1>Pages</h1>
{navigation.map(item => {
if (item.nesting === false) {
return <li><Link className="" to={ item.path }>{item.title}</Link></li>
}
else if (item.nesting === true) {
}
})}
</ul>
<p>copyright 2020</p>
</div>
</footer>
</div>
)
}
Layout.propTypes = {
children: PropTypes.node.isRequired,
}
export default Layout
|
# Copyright 2012 OpenStack Foundation
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import mock
import testtools
from glanceclient import exc
HTML_MSG = """<html>
<head>
<title>404 Entity Not Found</title>
</head>
<body>
<h1>404 Entity Not Found</h1>
Entity could not be found
<br /><br />
</body>
</html>"""
class TestHTTPExceptions(testtools.TestCase):
def test_from_response(self):
"""exc.from_response should return instance of an HTTP exception."""
mock_resp = mock.Mock()
mock_resp.status_code = 400
out = exc.from_response(mock_resp)
self.assertIsInstance(out, exc.HTTPBadRequest)
def test_handles_json(self):
"""exc.from_response should not print JSON."""
mock_resp = mock.Mock()
mock_resp.status_code = 413
mock_resp.json.return_value = {
"overLimit": {
"code": 413,
"message": "OverLimit Retry...",
"details": "Error Details...",
"retryAt": "2014-12-03T13:33:06Z"
}
}
mock_resp.headers = {
"content-type": "application/json"
}
err = exc.from_response(mock_resp, "Non-empty body")
self.assertIsInstance(err, exc.HTTPOverLimit)
self.assertEqual("OverLimit Retry...", err.details)
def test_handles_html(self):
"""exc.from_response should not print HTML."""
mock_resp = mock.Mock()
mock_resp.status_code = 404
mock_resp.text = HTML_MSG
mock_resp.headers = {
"content-type": "text/html"
}
err = exc.from_response(mock_resp, HTML_MSG)
self.assertIsInstance(err, exc.HTTPNotFound)
self.assertEqual("404 Entity Not Found: Entity could not be found",
err.details)
|
window.onload = function(event) {
// alert('test');
var options = {
valueNames: [ 'project_tags' ]
};
var projectsList = new List('projects', options);
var clearFilters = function() {
filterWeb.className = "btn";
filterMobile.className = "btn";
filterClear.className = "btn";
};
var toggleFilter = function(obj, tag) {
return function() {
clearFilters();
obj.className = "btn active";
filterByTag(tag);
}
};
var filterByTag = function(tag){
projectsList.filter(function(item) {
if (item.values().project_tags.indexOf(tag) != -1) {
return true;
} else {
return false;
}
});
return false;
};
var filterWeb = document.getElementById('filter-web');
var filterMobile = document.getElementById('filter-mobile');
var filterClear = document.getElementById('filter-clear');
filterWeb.addEventListener('click', toggleFilter(filterWeb, "WEB"));
filterMobile.addEventListener('click', toggleFilter(filterMobile, "MOBILE"));
filterClear.addEventListener('click', toggleFilter(filterClear, ""));
} |
/**
@module ember-metal
*/
import {
removeChainWatcher
} from './chains';
import {
watchKey,
unwatchKey
} from './watch_key';
import {
watchPath,
unwatchPath
} from './watch_path';
import {
isPath
} from './path_cache';
import {
peekMeta,
deleteMeta
} from './meta';
/**
Starts watching a property on an object. Whenever the property changes,
invokes `Ember.propertyWillChange` and `Ember.propertyDidChange`. This is the
primitive used by observers and dependent keys; usually you will never call
this method directly but instead use higher level methods like
`Ember.addObserver()`
@private
@method watch
@for Ember
@param obj
@param {String} _keyPath
*/
function watch(obj, _keyPath, m) {
if (!isPath(_keyPath)) {
watchKey(obj, _keyPath, m);
} else {
watchPath(obj, _keyPath, m);
}
}
export { watch };
export function isWatching(obj, key) {
let meta = peekMeta(obj);
return (meta && meta.peekWatching(key)) > 0;
}
export function watcherCount(obj, key) {
let meta = peekMeta(obj);
return (meta && meta.peekWatching(key)) || 0;
}
export function unwatch(obj, _keyPath, m) {
if (!isPath(_keyPath)) {
unwatchKey(obj, _keyPath, m);
} else {
unwatchPath(obj, _keyPath, m);
}
}
const NODE_STACK = [];
/**
Tears down the meta on an object so that it can be garbage collected.
Multiple calls will have no effect.
@method destroy
@for Ember
@param {Object} obj the object to destroy
@return {void}
@private
*/
export function destroy(obj) {
let meta = peekMeta(obj);
let node, nodes, key, nodeObject;
if (meta) {
deleteMeta(obj);
// remove chainWatchers to remove circular references that would prevent GC
node = meta.readableChains();
if (node) {
NODE_STACK.push(node);
// process tree
while (NODE_STACK.length > 0) {
node = NODE_STACK.pop();
// push children
nodes = node._chains;
if (nodes) {
for (key in nodes) {
if (nodes[key] !== undefined) {
NODE_STACK.push(nodes[key]);
}
}
}
// remove chainWatcher in node object
if (node._watching) {
nodeObject = node._object;
if (nodeObject) {
removeChainWatcher(nodeObject, node._key, node);
}
}
}
}
}
}
|
# -*- coding: utf-8 -*-
# A simple setup script to create an executable using PyQt4. This also
# demonstrates the method for creating a Windows executable that does not have
# an associated console.
#
# PyQt4app.py is a very simple type of PyQt4 application
#
# Run the build process by running the command 'python setup.py build'
#
# If everything works well you should find a subdirectory in the build
# subdirectory that contains the files needed to run the application
import sys
from cx_Freeze import setup, Executable
base = None
if sys.platform == 'win32':
base = 'Win32GUI'
options = {
'build_exe': {
'includes': 'atexit'
}
}
executables = [
Executable('PyQt4app.py', base=base)
]
setup(name='simple_PyQt4',
version='0.1',
description='Sample cx_Freeze PyQt4 script',
options=options,
executables=executables
)
|
const assert = require('chai').assert;
const reqlib = require('app-root-path').require;
const appRoot = require("app-root-path");
const path = require("path");
const memFs = require('mem-fs');
const editor = require('mem-fs-editor');
const store = memFs.create();
const fs = editor.create(store);
const DAOImplementation = reqlib('/backend/dao/DAOImplementation.js');
const mockdataSource = path.join(
appRoot.toString(), "test", "mockdata"
);
var sampleProduct = {
"name": "TNT",
"price": 42.99,
"tags": ["explosive"],
"dimensions": {
"length": 0.25,
"width": 0.25,
"height": 0.5
},
"warehouseLocation": {
"latitude": -78.75,
"longitude": 20.4
}
};
var invalidSampleProduct = {
"name": "Panacea"
};
describe('DAOImplementation', function() {
console.log("App root", appRoot.toString());
var config = {
basePath: path.join('test', 'mockdata', 'products'),
collectionName: 'products',
schema: 'schema.json'
};
var initialData = fs.readJSON(
path.join(mockdataSource, "products", "index.json"));
var implementation = new DAOImplementation(config);
beforeEach("Setup", function(done) {
implementation.insert(initialData).then(function() {
done();
});
});
afterEach("Teardown", function(done) {
// Removing all documents with the 'match-all' query
implementation.remove({}, {multi: true}).then(function() {
done();
}, function(err) {
throw new Error(err.message);
});
});
describe("#find()", function() {
it("returns all records with match-all query", function(done) {
implementation.find().then(function(result) {
assert(Array.isArray(result), "Result is an array");
assert.equal(2, result.length);
done();
}).catch(done);
});
it("returns an array with the found elements using query", function(done) {
var filter = {name: "An ice sculpture", price: 12.50};
implementation.find(filter).then(function(result) {
assert(Array.isArray(result), "Result is an array");
assert.equal(1, result.length);
assert.equal("An ice sculpture", result[0].name);
done();
}).catch(done);
});
});
describe("#findOne(query)", function() {
it("returns the found resource", function(done) {
implementation.findOne({price: 25.50}).then(function(result) {
assert.isDefined(result);
assert.equal("A blue mouse", result.name);
done();
}).catch(done);
});
});
describe("#insert(data)", function() {
it("returns created resource", function(done) {
implementation.insert(sampleProduct).then(function(result) {
assert.isDefined(result);
assert.isDefined(result._id);
assert.equal("TNT", result.name);
assert.equal(42.99, result.price);
done();
}).catch(done);
});
it("should not be possible to create resources from invalid data",
function(done) {
implementation.insert(invalidSampleProduct).then(
function(result) {
assert.isUndefined(result);
done();
}, function(err) {
assert.isDefined(err);
assert.equal('422', err.message);
done();
}).catch(done);
});
});
describe("#update(query, data)", function() {
it("returns number of updated records", function(done) {
implementation.find().then(function(result) {
assert.isDefined(result);
assert.equal(2, result.length);
var selected = result[1];
selected.name += " updated";
return implementation.update({_id: selected._id}, selected);
}).then(function(result) {
assert.isDefined(result);
assert.equal(1, result);
done();
}).catch(done);
});
it("should not be possible to updated resource with invalid data",
function(done) {
implementation.find().then(function(result) {
assert.isDefined(result);
assert.equal(2, result.length);
var selected = result[1];
return implementation.update({_id: selected._id}, {name: "foo"});
}).then(function(result) {
assert.isUndefined(result);
done();
}, function(err) {
assert.isDefined(err);
assert.equal('422', err.message);
done();
}).catch(done);
});
});
describe("#patch(query, patch)", function() {
it("returns number of updated record", function(done) {
var query = {name: "An ice sculpture"};
implementation.findOne(query)
.then(function(result) {
assert.equal(query.name, result.name);
var patch = {name: "An ice sculpture updated"};
query = {_id: result._id};
return implementation.patch(query, patch);
})
.then(function(result) {
assert.isDefined(result);
assert.equal(1, result);
return implementation.findOne(query);
})
.then(function(result) {
assert.equal("An ice sculpture updated", result.name);
assert.equal(12.50, result.price);
done();
})
.catch(done);
});
it("it should not be possible to patch invalid data", function(done) {
implementation.find()
.then(function(result) {
var query = {
_id: result[0]._id
};
var patch = {price: "foo"};
return implementation.patch(query, patch);
})
.then(function(result) {
assert.isUndefined(result);
done();
}, function(err) {
assert.isDefined(err);
assert.equal('422', err.message);
done();
})
.catch(done);
});
});
describe("#delete()", function() {
it("returns number of deleted resources", function(done) {
implementation.insert({name: "Rubber duck", price: 0.99}).then(
function(result) {
assert.isDefined(result);
assert.isDefined(result._id);
assert.equal("Rubber duck", result.name);
assert.equal(0.99, result.price);
return implementation.remove({_id: result._id});
}).then(function(result) {
assert.equal(1, result);
done();
}).catch(done);
});
});
});
|
import React, { useState } from "react";
import { Alert, Modal, StyleSheet, Text, Pressable, View } from "react-native";
const UpdateAppModal = () => {
return (
<View style={styles.centeredView}>
<Modal
animationType="slide"
transparent={true}
visible={true}
>
<View style={styles.centeredView}>
<View style={styles.modalView}>
<Text style={styles.modalText}>Outdated! Please update your App.</Text>
</View>
</View>
</Modal>
</View>
);
};
const styles = StyleSheet.create({
centeredView: {
flex: 1,
justifyContent: "center",
alignItems: "center",
marginTop: 22
},
modalView: {
margin: 20,
backgroundColor: "white",
borderRadius: 20,
padding: 35,
alignItems: "center",
shadowColor: "#000",
shadowOffset: {
width: 0,
height: 2
},
shadowOpacity: 0.25,
shadowRadius: 4,
elevation: 5
},
modalText: {
marginBottom: 15,
textAlign: "center"
}
});
export default UpdateAppModal;
|
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var environment_1 = require("./environment");
var backend_cpu_1 = require("./kernels/backend_cpu");
var backend_webgl_1 = require("./kernels/backend_webgl");
Error.stackTraceLimit = Infinity;
function envSatisfiesConstraints(constraints) {
for (var key in constraints) {
var value = constraints[key];
if (environment_1.ENV.get(key) !== value) {
return false;
}
}
return true;
}
exports.envSatisfiesConstraints = envSatisfiesConstraints;
function parseKarmaFlags(args) {
var features;
var backend;
var name = '';
args.forEach(function (arg, i) {
if (arg === '--features') {
features = JSON.parse(args[i + 1]);
}
else if (arg === '--backend') {
var type = args[i + 1];
name = type;
if (type.toLowerCase() === 'cpu') {
backend = function () { return new backend_cpu_1.MathBackendCPU(); };
features = features || {};
features['HAS_WEBGL'] = false;
}
else if (type.toLowerCase() === 'webgl') {
backend = function () { return new backend_webgl_1.MathBackendWebGL(); };
}
else {
throw new Error("Unknown value " + type + " for flag --backend. " +
"Allowed values are 'cpu' or 'webgl'.");
}
}
});
if (features == null && backend == null) {
return null;
}
if (features != null && backend == null) {
throw new Error('--backend flag is required when --features is present. ' +
'Available values are "webgl" or "cpu".');
}
return { features: features || {}, factory: backend, name: name };
}
exports.parseKarmaFlags = parseKarmaFlags;
function describeWithFlags(name, constraints, tests) {
exports.TEST_ENVS.forEach(function (testEnv) {
environment_1.ENV.setFeatures(testEnv.features);
if (envSatisfiesConstraints(constraints)) {
var testName = name + ' ' + testEnv.name + ' ' + JSON.stringify(testEnv.features);
executeTests(testName, tests, testEnv);
}
});
}
exports.describeWithFlags = describeWithFlags;
exports.TEST_ENVS = [
{
name: 'test-webgl1',
factory: function () { return new backend_webgl_1.MathBackendWebGL(); },
features: {
'WEBGL_VERSION': 1,
'WEBGL_CPU_FORWARD': false,
'WEBGL_SIZE_UPLOAD_UNIFORM': 0,
}
},
{
name: 'test-webgl2',
factory: function () { return new backend_webgl_1.MathBackendWebGL(); },
features: {
'WEBGL_VERSION': 2,
'WEBGL_CPU_FORWARD': false,
'WEBGL_SIZE_UPLOAD_UNIFORM': 0,
}
},
{
name: 'test-cpu',
factory: function () { return new backend_cpu_1.MathBackendCPU(); },
features: { 'HAS_WEBGL': false }
}
];
exports.CPU_FACTORY = function () { return new backend_cpu_1.MathBackendCPU(); };
if (typeof __karma__ !== 'undefined') {
var testEnv = parseKarmaFlags(__karma__.config.args);
if (testEnv) {
setTestEnvs([testEnv]);
}
}
function setTestEnvs(testEnvs) {
exports.TEST_ENVS = testEnvs;
}
exports.setTestEnvs = setTestEnvs;
function executeTests(testName, tests, testEnv) {
describe(testName, function () {
var backendName = 'test-' + testEnv.name;
beforeAll(function () {
environment_1.ENV.reset();
environment_1.ENV.setFeatures(testEnv.features);
environment_1.ENV.set('IS_TEST', true);
environment_1.ENV.registerBackend(backendName, testEnv.factory, 1000);
environment_1.Environment.setBackend(backendName);
});
beforeEach(function () {
environment_1.ENV.engine.startScope();
});
afterEach(function () {
environment_1.ENV.engine.endScope();
environment_1.Environment.disposeVariables();
});
afterAll(function () {
environment_1.ENV.removeBackend(backendName);
environment_1.ENV.reset();
});
tests(testEnv);
});
}
//# sourceMappingURL=jasmine_util.js.map |
var forOwn = require('./forOwn');
var isPlainObject = require('../lang/isPlainObject');
/**
* Mixes objects into the target object, recursively mixing existing child
* objects.
*/
function deepMixIn(target, objects) {
var i = 0,
n = arguments.length,
obj;
while (++i < n) {
obj = arguments[i];
if (obj) {
forOwn(obj, copyProp, target);
}
}
return target;
}
function copyProp(val, key) {
var existing = this[key];
if (isPlainObject(val) && isPlainObject(existing)) {
deepMixIn(existing, val);
} else {
this[key] = val;
}
}
module.exports = deepMixIn;
|
from django.contrib.auth import get_user_model
from django.urls import reverse
from django.test import TestCase
from rest_framework import status
from rest_framework.test import APIClient
from core.models import Tag, Recipe
from recipe.serializers import TagSerializer
TAGS_URL = reverse('recipe:tag-list')
class PublicTagsApiTests(TestCase):
"""Test the publicly available tags API"""
def setUp(self):
self.client = APIClient()
def test_login_required(self):
"""Test that login is required for retrieving tags"""
res = self.client.get(TAGS_URL)
self.assertEqual(res.status_code, status.HTTP_401_UNAUTHORIZED)
class PrivateTagsApiTests(TestCase):
"""Test the authorized user tags API"""
def setUp(self):
self.user = get_user_model().objects.create_user(
'[email protected]',
'password123'
)
self.client = APIClient()
self.client.force_authenticate(self.user)
def test_retrieve_tags(self):
"""Test retrieving tags"""
Tag.objects.create(user=self.user, name='Vegan')
Tag.objects.create(user=self.user, name='Dessert')
res = self.client.get(TAGS_URL)
tags = Tag.objects.all().order_by('-name')
serializer = TagSerializer(tags, many=True)
self.assertEqual(res.status_code, status.HTTP_200_OK)
self.assertEqual(res.data, serializer.data)
def test_tags_limited_to_user(self):
"""Test that tags returned are for the authenticated user"""
user2 = get_user_model().objects.create_user(
'[email protected]',
'testpass'
)
Tag.objects.create(user=user2, name='Fruity')
tag = Tag.objects.create(user=self.user, name='Comfort Food')
res = self.client.get(TAGS_URL)
self.assertEqual(res.status_code, status.HTTP_200_OK)
self.assertEqual(len(res.data), 1)
self.assertEqual(res.data[0]['name'], tag.name)
def test_create_tag_successful(self):
"""Test creating a new tag"""
payload = {'name': 'Test tag'}
self.client.post(TAGS_URL, payload)
exists = Tag.objects.filter(
user=self.user,
name=payload['name']
).exists()
self.assertTrue(exists)
def test_create_tag_invalid(self):
"""Test creating a new tag with invalid payload"""
payload = {'name': ''}
res = self.client.post(TAGS_URL, payload)
self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST)
def test_retrieve_tags_assigned_to_recipes(self):
"""Test filtering tags by those assigned to recipes"""
tag1 = Tag.objects.create(user=self.user, name='Breakfast')
tag2 = Tag.objects.create(user=self.user, name='Lunch')
recipe = Recipe.objects.create(
title='Coriander eggs on toast',
time_minutes=10,
price=5.00,
user=self.user
)
recipe.tags.add(tag1)
res = self.client.get(TAGS_URL, {'assigned_only': 1})
serializer1 = TagSerializer(tag1)
serializer2 = TagSerializer(tag2)
self.assertIn(serializer1.data, res.data)
self.assertNotIn(serializer2.data, res.data)
def test_retrieve_tags_assigned_unique(self):
"""Test filtering tags by assigned returns unique items"""
tag = Tag.objects.create(user=self.user, name='Breakfast')
Tag.objects.create(user=self.user, name='Lunch')
recipe1 = Recipe.objects.create(
title='Pancakes',
time_minutes=5,
price=3.00,
user=self.user
)
recipe1.tags.add(tag)
recipe2 = Recipe.objects.create(
title='Porridge',
time_minutes=3,
price=2.00,
user=self.user
)
recipe2.tags.add(tag)
res = self.client.get(TAGS_URL, {'assigned_only': 1})
self.assertEqual(len(res.data), 1)
|
window.UserboundInterface = (function() {
var $ = {
z: require('./libs/zepto.js'),
grapnel: require('grapnel'),
simpleStorage: require('./libs/simpleStorage.js'),
WaveSurfer: require('./libs/wavesurfer.min.js'),
highlighter: require('./libs/highlight.js')
};
$.highlighter.registerLanguage('clojure', require('./libs/lang/clojure.js'));
$.highlighter.registerLanguage('scss', require('./libs/lang/scss.js'));
$.highlighter.registerLanguage('c++', require('./libs/lang/cpp.js'));
$.highlighter.registerLanguage('ruby', require('./libs/lang/ruby.js'));
$.highlighter.registerLanguage('openscad', require('./libs/lang/openscad.js'));
$.highlighter.registerLanguage('js', require('./libs/lang/javascript.js'));
$.highlighter.registerLanguage('smalltalk', require('./libs/lang/smalltalk.js'));
$.highlighter.registerLanguage('go', require('./libs/lang/go.js'));
$.highlighter.registerLanguage('bash', require('./libs/lang/bash.js'));
var globals = require('./modules/globals.js');
var util = require('./modules/util.js')($, globals);
var router = new $.grapnel({ pushState: true });
var event_handlers = require('./modules/event_handlers.js')($, globals, util, router);
var setup_asciiw_demo = require('./modules/asciiw_demo.js')($, globals, util, router);
var consulting_toggle = require('./modules/consulting_toggle.js')($, globals, util, router);
return {
init: function() {
if (util.redirect_homepage_to('/blog')) { return; }
if (consulting_toggle.install_consulting_toggle() === 'toggling consulting') { return; }
// Seting up routes
require('./modules/setup_routes.js')($, globals, util, router);
// Syntax highlighting asciiw demo, audo player, event handlers
$.z("[data-language]").each(function(i, el) {
$.highlighter.highlightBlock(el);
});
setup_asciiw_demo();
event_handlers.install_dom_event_bindings();
$.z("nav").addClass("fade-in");
$.z("main").addClass("fade-down");
}
};
})();
window.onload = UserboundInterface.init;
|
import React, { Component } from "react";
import PropTypes from "prop-types";
import { connect } from "react-redux";
import Picker from "../components/Picker";
import Posts from "../components/Posts";
import {fetchPosts,receivePosts,selectedSubReddit} from '../actions/index'
class App extends Component {
handleChange = (subreddit) => {
this.props.fetchPosts(subreddit)
this.props.selectedSubReddit(subreddit)
};
// getMyTime=(lastUpdate) => {
// let d = new Date(lastUpdate);
// return d.toLocaleTimeString();
// }
render() {
let lastUpdated = new Date()
console.log(this.props)
return (
<div>
<Picker
value={this.props.reducers.selectedReducer}
// value={"frontend"}
onChange={this.handleChange}
options={[
"reactjs",
"frontend",
"javascript",
"reduxjs",
"backend",
"nodejs",
"mongodb",
"reduc",
"undefined",
]}
/>
<p>
{lastUpdated && (
<span>
{/* Last updated at {new Date(lastUpdated).toLocaleTimeString()}.{" "} */}
Last updated at {new Date(lastUpdated).toLocaleTimeString()}.{" "}
</span>
)}
</p>
{/* <Posts posts={posts} /> */}
<Posts posts={this.props.reducers.receiveReducer} />
</div>
);
}
}
const mapStateToProps = (state) => {return {reducers:state}} ;
const mapDispatchToProps = {fetchPosts,receivePosts,selectedSubReddit}
export default connect(mapStateToProps, mapDispatchToProps)(App) |
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: telemetry_kv.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_database
from google.protobuf import descriptor_pb2
# @@protoc_insertion_point(imports)
_sym_db = _symbol_database.Default()
DESCRIPTOR = _descriptor.FileDescriptor(
name='telemetry_kv.proto',
package='',
syntax='proto2',
serialized_pb=_b('\n\x12telemetry_kv.proto\"\xe1\x01\n\tTelemetry\x12\x15\n\rcollection_id\x18\x01 \x01(\x04\x12\x11\n\tbase_path\x18\x02 \x01(\t\x12\x1f\n\x17subscription_identifier\x18\x03 \x01(\t\x12\x15\n\rmodel_version\x18\x04 \x01(\t\x12\x1d\n\x15\x63ollection_start_time\x18\x05 \x01(\x04\x12\x15\n\rmsg_timestamp\x18\x06 \x01(\x04\x12\x1f\n\x06\x66ields\x18\x0e \x03(\x0b\x32\x0f.TelemetryField\x12\x1b\n\x13\x63ollection_end_time\x18\x0f \x01(\x04\"\xcd\x02\n\x0eTelemetryField\x12\x11\n\ttimestamp\x18\x01 \x01(\x04\x12\x0c\n\x04name\x18\x02 \x01(\t\x12\x14\n\x0c\x61ugment_data\x18\x03 \x01(\x08\x12\x15\n\x0b\x62ytes_value\x18\x04 \x01(\x0cH\x00\x12\x16\n\x0cstring_value\x18\x05 \x01(\tH\x00\x12\x14\n\nbool_value\x18\x06 \x01(\x08H\x00\x12\x16\n\x0cuint32_value\x18\x07 \x01(\rH\x00\x12\x16\n\x0cuint64_value\x18\x08 \x01(\x04H\x00\x12\x16\n\x0csint32_value\x18\t \x01(\x11H\x00\x12\x16\n\x0csint64_value\x18\n \x01(\x12H\x00\x12\x16\n\x0c\x64ouble_value\x18\x0b \x01(\x01H\x00\x12\x15\n\x0b\x66loat_value\x18\x0c \x01(\x02H\x00\x12\x1f\n\x06\x66ields\x18\x0f \x03(\x0b\x32\x0f.TelemetryFieldB\x0f\n\rvalue_by_type')
)
_sym_db.RegisterFileDescriptor(DESCRIPTOR)
_TELEMETRY = _descriptor.Descriptor(
name='Telemetry',
full_name='Telemetry',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='collection_id', full_name='Telemetry.collection_id', index=0,
number=1, type=4, cpp_type=4, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='base_path', full_name='Telemetry.base_path', index=1,
number=2, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='subscription_identifier', full_name='Telemetry.subscription_identifier', index=2,
number=3, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='model_version', full_name='Telemetry.model_version', index=3,
number=4, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='collection_start_time', full_name='Telemetry.collection_start_time', index=4,
number=5, type=4, cpp_type=4, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='msg_timestamp', full_name='Telemetry.msg_timestamp', index=5,
number=6, type=4, cpp_type=4, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='fields', full_name='Telemetry.fields', index=6,
number=14, type=11, cpp_type=10, label=3,
has_default_value=False, default_value=[],
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='collection_end_time', full_name='Telemetry.collection_end_time', index=7,
number=15, type=4, cpp_type=4, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
],
extensions=[
],
nested_types=[],
enum_types=[
],
options=None,
is_extendable=False,
syntax='proto2',
extension_ranges=[],
oneofs=[
],
serialized_start=23,
serialized_end=248,
)
_TELEMETRYFIELD = _descriptor.Descriptor(
name='TelemetryField',
full_name='TelemetryField',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='timestamp', full_name='TelemetryField.timestamp', index=0,
number=1, type=4, cpp_type=4, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='name', full_name='TelemetryField.name', index=1,
number=2, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='augment_data', full_name='TelemetryField.augment_data', index=2,
number=3, type=8, cpp_type=7, label=1,
has_default_value=False, default_value=False,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='bytes_value', full_name='TelemetryField.bytes_value', index=3,
number=4, type=12, cpp_type=9, label=1,
has_default_value=False, default_value=_b(""),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='string_value', full_name='TelemetryField.string_value', index=4,
number=5, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='bool_value', full_name='TelemetryField.bool_value', index=5,
number=6, type=8, cpp_type=7, label=1,
has_default_value=False, default_value=False,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='uint32_value', full_name='TelemetryField.uint32_value', index=6,
number=7, type=13, cpp_type=3, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='uint64_value', full_name='TelemetryField.uint64_value', index=7,
number=8, type=4, cpp_type=4, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='sint32_value', full_name='TelemetryField.sint32_value', index=8,
number=9, type=17, cpp_type=1, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='sint64_value', full_name='TelemetryField.sint64_value', index=9,
number=10, type=18, cpp_type=2, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='double_value', full_name='TelemetryField.double_value', index=10,
number=11, type=1, cpp_type=5, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='float_value', full_name='TelemetryField.float_value', index=11,
number=12, type=2, cpp_type=6, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='fields', full_name='TelemetryField.fields', index=12,
number=15, type=11, cpp_type=10, label=3,
has_default_value=False, default_value=[],
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
],
extensions=[
],
nested_types=[],
enum_types=[
],
options=None,
is_extendable=False,
syntax='proto2',
extension_ranges=[],
oneofs=[
_descriptor.OneofDescriptor(
name='value_by_type', full_name='TelemetryField.value_by_type',
index=0, containing_type=None, fields=[]),
],
serialized_start=251,
serialized_end=584,
)
_TELEMETRY.fields_by_name['fields'].message_type = _TELEMETRYFIELD
_TELEMETRYFIELD.fields_by_name['fields'].message_type = _TELEMETRYFIELD
_TELEMETRYFIELD.oneofs_by_name['value_by_type'].fields.append(
_TELEMETRYFIELD.fields_by_name['bytes_value'])
_TELEMETRYFIELD.fields_by_name['bytes_value'].containing_oneof = _TELEMETRYFIELD.oneofs_by_name['value_by_type']
_TELEMETRYFIELD.oneofs_by_name['value_by_type'].fields.append(
_TELEMETRYFIELD.fields_by_name['string_value'])
_TELEMETRYFIELD.fields_by_name['string_value'].containing_oneof = _TELEMETRYFIELD.oneofs_by_name['value_by_type']
_TELEMETRYFIELD.oneofs_by_name['value_by_type'].fields.append(
_TELEMETRYFIELD.fields_by_name['bool_value'])
_TELEMETRYFIELD.fields_by_name['bool_value'].containing_oneof = _TELEMETRYFIELD.oneofs_by_name['value_by_type']
_TELEMETRYFIELD.oneofs_by_name['value_by_type'].fields.append(
_TELEMETRYFIELD.fields_by_name['uint32_value'])
_TELEMETRYFIELD.fields_by_name['uint32_value'].containing_oneof = _TELEMETRYFIELD.oneofs_by_name['value_by_type']
_TELEMETRYFIELD.oneofs_by_name['value_by_type'].fields.append(
_TELEMETRYFIELD.fields_by_name['uint64_value'])
_TELEMETRYFIELD.fields_by_name['uint64_value'].containing_oneof = _TELEMETRYFIELD.oneofs_by_name['value_by_type']
_TELEMETRYFIELD.oneofs_by_name['value_by_type'].fields.append(
_TELEMETRYFIELD.fields_by_name['sint32_value'])
_TELEMETRYFIELD.fields_by_name['sint32_value'].containing_oneof = _TELEMETRYFIELD.oneofs_by_name['value_by_type']
_TELEMETRYFIELD.oneofs_by_name['value_by_type'].fields.append(
_TELEMETRYFIELD.fields_by_name['sint64_value'])
_TELEMETRYFIELD.fields_by_name['sint64_value'].containing_oneof = _TELEMETRYFIELD.oneofs_by_name['value_by_type']
_TELEMETRYFIELD.oneofs_by_name['value_by_type'].fields.append(
_TELEMETRYFIELD.fields_by_name['double_value'])
_TELEMETRYFIELD.fields_by_name['double_value'].containing_oneof = _TELEMETRYFIELD.oneofs_by_name['value_by_type']
_TELEMETRYFIELD.oneofs_by_name['value_by_type'].fields.append(
_TELEMETRYFIELD.fields_by_name['float_value'])
_TELEMETRYFIELD.fields_by_name['float_value'].containing_oneof = _TELEMETRYFIELD.oneofs_by_name['value_by_type']
DESCRIPTOR.message_types_by_name['Telemetry'] = _TELEMETRY
DESCRIPTOR.message_types_by_name['TelemetryField'] = _TELEMETRYFIELD
Telemetry = _reflection.GeneratedProtocolMessageType('Telemetry', (_message.Message,), dict(
DESCRIPTOR = _TELEMETRY,
__module__ = 'telemetry_kv_pb2'
# @@protoc_insertion_point(class_scope:Telemetry)
))
_sym_db.RegisterMessage(Telemetry)
TelemetryField = _reflection.GeneratedProtocolMessageType('TelemetryField', (_message.Message,), dict(
DESCRIPTOR = _TELEMETRYFIELD,
__module__ = 'telemetry_kv_pb2'
# @@protoc_insertion_point(class_scope:TelemetryField)
))
_sym_db.RegisterMessage(TelemetryField)
# @@protoc_insertion_point(module_scope)
|
function score(word) {
"use strict";
var points = {
A: 1,
E: 1,
I: 1,
O: 1,
U: 1,
L: 1,
N: 1,
R: 1,
S: 1,
T: 1,
D: 2,
G: 2,
B: 3,
C: 3,
M: 3,
P: 3,
F: 4,
H: 4,
V: 4,
W: 4,
Y: 4,
K: 5,
J: 8,
X: 8,
Q: 10,
Z: 10
};
var calcScore = function(word) {
word = word ? word.toUpperCase() : "";
var total = 0;
for (var i = 0; i < word.length; i++) {
total += points[word[i]];
}
return total;
};
return calcScore(word);
}
module.exports = score;
|
/**
* @format
*/
import Verify from './Componets/Verify'
import {AppRegistry} from 'react-native';
import App from './App';
import {name as appName} from './app.json';
AppRegistry.registerComponent(appName, () => App);
|
import { createSelector } from 'reselect';
import { initialState } from './reducer';
/**
* Direct selector to the login state domain
*/
const selectLoginDomain = state => state.get('client', initialState);
/**
* Other specific selectors
*/
/**
* Default selector used by Login
*/
const makeSelectLogin = () =>
createSelector(selectLoginDomain, substate => substate.toJS());
export default makeSelectLogin;
export { selectLoginDomain };
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2013, Serge van Ginderachter <[email protected]>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = r'''
---
module: open_iscsi
author:
- Serge van Ginderachter (@srvg)
version_added: "1.4"
short_description: Manage iSCSI targets with Open-iSCSI
description:
- Discover targets on given portal, (dis)connect targets, mark targets to
manually or auto start, return device nodes of connected targets.
requirements:
- open_iscsi library and tools (iscsiadm)
options:
portal:
description:
- The IP address of the iSCSI target.
type: str
aliases: [ ip ]
port:
description:
- The port on which the iSCSI target process listens.
type: str
default: 3260
target:
description:
- The iSCSI target name.
type: str
aliases: [ name, targetname ]
login:
description:
- Whether the target node should be connected.
type: bool
aliases: [ state ]
node_auth:
description:
- The value for C(discovery.sendtargets.auth.authmethod).
type: str
default: CHAP
node_user:
description:
- The value for C(discovery.sendtargets.auth.username).
type: str
node_pass:
description:
- The value for C(discovery.sendtargets.auth.password).
type: str
auto_node_startup:
description:
- Whether the target node should be automatically connected at startup.
type: bool
aliases: [ automatic ]
discover:
description:
- Whether the list of target nodes on the portal should be
(re)discovered and added to the persistent iSCSI database.
- Keep in mind that C(iscsiadm) discovery resets configuration, like C(node.startup)
to manual, hence combined with C(auto_node_startup=yes) will always return
a changed state.
type: bool
show_nodes:
description:
- Whether the list of nodes in the persistent iSCSI database should be returned by the module.
type: bool
'''
EXAMPLES = r'''
- name: Perform a discovery on 10.1.2.3 and show available target nodes
open_iscsi:
show_nodes: yes
discover: yes
portal: 10.1.2.3
# NOTE: Only works if exactly one target is exported to the initiator
- name: Discover targets on portal and login to the one available
open_iscsi:
portal: '{{ iscsi_target }}'
login: yes
discover: yes
- name: Connect to the named target, after updating the local persistent database (cache)
open_iscsi:
login: yes
target: iqn.1986-03.com.sun:02:f8c1f9e0-c3ec-ec84-c9c9-8bfb0cd5de3d
- name: Disconnect from the cached named target
open_iscsi:
login: no
target: iqn.1986-03.com.sun:02:f8c1f9e0-c3ec-ec84-c9c9-8bfb0cd5de3d
'''
import glob
import os
import time
from ansible.module_utils.basic import AnsibleModule
ISCSIADM = 'iscsiadm'
def compare_nodelists(l1, l2):
l1.sort()
l2.sort()
return l1 == l2
def iscsi_get_cached_nodes(module, portal=None):
cmd = '%s --mode node' % iscsiadm_cmd
(rc, out, err) = module.run_command(cmd)
if rc == 0:
lines = out.splitlines()
nodes = []
for line in lines:
# line format is "ip:port,target_portal_group_tag targetname"
parts = line.split()
if len(parts) > 2:
module.fail_json(msg='error parsing output', cmd=cmd)
target = parts[1]
parts = parts[0].split(':')
target_portal = parts[0]
if portal is None or portal == target_portal:
nodes.append(target)
# older versions of scsiadm don't have nice return codes
# for newer versions see iscsiadm(8); also usr/iscsiadm.c for details
# err can contain [N|n]o records...
elif rc == 21 or (rc == 255 and "o records found" in err):
nodes = []
else:
module.fail_json(cmd=cmd, rc=rc, msg=err)
return nodes
def iscsi_discover(module, portal, port):
cmd = '%s --mode discovery --type sendtargets --portal %s:%s' % (iscsiadm_cmd, portal, port)
(rc, out, err) = module.run_command(cmd)
if rc > 0:
module.fail_json(cmd=cmd, rc=rc, msg=err)
def target_loggedon(module, target):
cmd = '%s --mode session' % iscsiadm_cmd
(rc, out, err) = module.run_command(cmd)
if rc == 0:
return target in out
elif rc == 21:
return False
else:
module.fail_json(cmd=cmd, rc=rc, msg=err)
def target_login(module, target, portal=None, port=None):
node_auth = module.params['node_auth']
node_user = module.params['node_user']
node_pass = module.params['node_pass']
if node_user:
params = [('node.session.auth.authmethod', node_auth),
('node.session.auth.username', node_user),
('node.session.auth.password', node_pass)]
for (name, value) in params:
cmd = '%s --mode node --targetname %s --op=update --name %s --value %s' % (iscsiadm_cmd, target, name, value)
(rc, out, err) = module.run_command(cmd)
if rc > 0:
module.fail_json(cmd=cmd, rc=rc, msg=err)
cmd = '%s --mode node --targetname %s --login' % (iscsiadm_cmd, target)
if portal is not None and port is not None:
cmd += ' --portal %s:%s' % (portal, port)
(rc, out, err) = module.run_command(cmd)
if rc > 0:
module.fail_json(cmd=cmd, rc=rc, msg=err)
def target_logout(module, target):
cmd = '%s --mode node --targetname %s --logout' % (iscsiadm_cmd, target)
(rc, out, err) = module.run_command(cmd)
if rc > 0:
module.fail_json(cmd=cmd, rc=rc, msg=err)
def target_device_node(module, target):
# if anyone know a better way to find out which devicenodes get created for
# a given target...
devices = glob.glob('/dev/disk/by-path/*%s*' % target)
devdisks = []
for dev in devices:
# exclude partitions
if "-part" not in dev:
devdisk = os.path.realpath(dev)
# only add once (multi-path?)
if devdisk not in devdisks:
devdisks.append(devdisk)
return devdisks
def target_isauto(module, target):
cmd = '%s --mode node --targetname %s' % (iscsiadm_cmd, target)
(rc, out, err) = module.run_command(cmd)
if rc == 0:
lines = out.splitlines()
for line in lines:
if 'node.startup' in line:
return 'automatic' in line
return False
else:
module.fail_json(cmd=cmd, rc=rc, msg=err)
def target_setauto(module, target):
cmd = '%s --mode node --targetname %s --op=update --name node.startup --value automatic' % (iscsiadm_cmd, target)
(rc, out, err) = module.run_command(cmd)
if rc > 0:
module.fail_json(cmd=cmd, rc=rc, msg=err)
def target_setmanual(module, target):
cmd = '%s --mode node --targetname %s --op=update --name node.startup --value manual' % (iscsiadm_cmd, target)
(rc, out, err) = module.run_command(cmd)
if rc > 0:
module.fail_json(cmd=cmd, rc=rc, msg=err)
def main():
# load ansible module object
module = AnsibleModule(
argument_spec=dict(
# target
portal=dict(type='str', aliases=['ip']),
port=dict(type='str', default=3260),
target=dict(type='str', aliases=['name', 'targetname']),
node_auth=dict(type='str', default='CHAP'),
node_user=dict(type='str'),
node_pass=dict(type='str', no_log=True),
# actions
login=dict(type='bool', aliases=['state']),
auto_node_startup=dict(type='bool', aliases=['automatic']),
discover=dict(type='bool', default=False),
show_nodes=dict(type='bool', default=False),
),
required_together=[['discover_user', 'discover_pass'],
['node_user', 'node_pass']],
supports_check_mode=True,
)
global iscsiadm_cmd
iscsiadm_cmd = module.get_bin_path('iscsiadm', required=True)
# parameters
portal = module.params['portal']
target = module.params['target']
port = module.params['port']
login = module.params['login']
automatic = module.params['auto_node_startup']
discover = module.params['discover']
show_nodes = module.params['show_nodes']
check = module.check_mode
cached = iscsi_get_cached_nodes(module, portal)
# return json dict
result = {}
result['changed'] = False
if discover:
if portal is None:
module.fail_json(msg="Need to specify at least the portal (ip) to discover")
elif check:
nodes = cached
else:
iscsi_discover(module, portal, port)
nodes = iscsi_get_cached_nodes(module, portal)
if not compare_nodelists(cached, nodes):
result['changed'] |= True
result['cache_updated'] = True
else:
nodes = cached
if login is not None or automatic is not None:
if target is None:
if len(nodes) > 1:
module.fail_json(msg="Need to specify a target")
else:
target = nodes[0]
else:
# check given target is in cache
check_target = False
for node in nodes:
if node == target:
check_target = True
break
if not check_target:
module.fail_json(msg="Specified target not found")
if show_nodes:
result['nodes'] = nodes
if login is not None:
loggedon = target_loggedon(module, target)
if (login and loggedon) or (not login and not loggedon):
result['changed'] |= False
if login:
result['devicenodes'] = target_device_node(module, target)
elif not check:
if login:
target_login(module, target, portal, port)
# give udev some time
time.sleep(1)
result['devicenodes'] = target_device_node(module, target)
else:
target_logout(module, target)
result['changed'] |= True
result['connection_changed'] = True
else:
result['changed'] |= True
result['connection_changed'] = True
if automatic is not None:
isauto = target_isauto(module, target)
if (automatic and isauto) or (not automatic and not isauto):
result['changed'] |= False
result['automatic_changed'] = False
elif not check:
if automatic:
target_setauto(module, target)
else:
target_setmanual(module, target)
result['changed'] |= True
result['automatic_changed'] = True
else:
result['changed'] |= True
result['automatic_changed'] = True
module.exit_json(**result)
if __name__ == '__main__':
main()
|
"""Custom protocol command.
A "custom" command contains arbitrary payload and result data.
It can be used by ProtocolEngine plugins to represent external
commands in state that a vanilla ProtocolEngine would not
know about.
This data model serves as a wrapper to ensure custom, arbitrary
data still adheres to the shapes that ProtocolEngine expects.
If you are implementing a custom command, you should probably
put your own disambiguation identifier in the payload.
"""
from pydantic import BaseModel, Extra
from typing import Optional, Type
from typing_extensions import Literal
from .command import BaseCommand, AbstractCommandImpl
CustomCommandType = Literal["custom"]
class CustomData(BaseModel):
"""Payload used by a custom command."""
class Config:
"""Allow arbitrary fields."""
extra = Extra.allow
class CustomResult(BaseModel):
"""Result data from a custom command."""
class Config:
"""Allow arbitrary fields."""
extra = Extra.allow
class CustomImplementation(AbstractCommandImpl[CustomData, CustomResult]):
"""Aspirate command implementation."""
# TODO(mc, 2021-09-24): figure out how a plugin can specify a custom command
# implementation. For now, raise so we remember not to allow this to happen.
async def execute(self, data: CustomData) -> CustomResult:
"""A custom command cannot be executed directly."""
raise NotImplementedError("Custom commands cannot be executed directly.")
class Custom(BaseCommand[CustomData, CustomResult]):
"""Custom command model."""
commandType: CustomCommandType = "custom"
data: CustomData
result: Optional[CustomResult]
_ImplementationCls: Type[CustomImplementation] = CustomImplementation
|
"use strict";
Studio.CheckboxFormAttr = function () {
Studio.FormAttr.apply(this, arguments);
};
$.extend(Studio.CheckboxFormAttr.prototype, Studio.FormAttr.prototype, {
constructor: Studio.CheckboxFormAttr,
getRawValue: function () {
return this.$value.is(':checked');
},
setValue: function (value) {
if (value === null || value === undefined) {
value = this.getDefaultValue();
}
this.$value.prop('checked', !!value);
}
}); |
// import { resolve } from "path";
// import("/cinema-gazer-processor.js")
window.addEventListener('DOMContentLoaded', (event) => {
console.log('DOM fully loaded and parsed');
const startButton = document.querySelector("#start-button-form");
startButton.addEventListener('submit', setupAudioFiltering);
// setupAudioFiltering();
});
const shhh = document.querySelector("#shut-up");
let halt = false;
shhh.addEventListener('submit', (e)=> {
halt = true;
e.preventDefault();
})
let analyser = null;
function setupAudioFiltering(event) {
event.preventDefault();
// https://developer.mozilla.org/en-US/docs/Web/API/AudioContext
// https://developer.mozilla.org/en-US/docs/Web/API/AudioWorkletProcessor
const AudioContext = window.AudioContext || window.webkitAudioContext;
let audioContext = new AudioContext();
analyser = audioContext.createAnalyser();
console.log(audioContext.audioWorklet);
const environ = audioContext.audioWorklet.addModule('cinema-gazer-processor.js').then(function() {
// debugger;
const cinemaGazerNode = new AudioWorkletNode(audioContext, 'cinema-gazer-processor')
const videoElement = document.getElementById("video-1");
let audioSource = audioContext.createMediaElementSource(videoElement);
audioSource.connect(cinemaGazerNode);
audioSource.connect(analyser);
// let audioFilter = audioContext.create
cinemaGazerNode.connect(audioContext.destination);
console.log("setupAudioFiltering complete!");
const environ = {
cinemaGazerNode: cinemaGazerNode,
videoElement: videoElement,
audioSource: audioSource
}
return environ;
}).then((environ) => {setupLibVad(environ);});
}
function setPlaybackDisplay(rate, talking) {
document.querySelector("#playback").innerText = rate + talking;
}
function setupLibVad(environ) {
const libVadOptions = {
source: environ["cinemaGazerNode"],
voice_stop: () => {
console.log("stop")
environ.videoElement.playbackRate = 2;
setPlaybackDisplay(2, " not talking");
},
voice_start: () => {
console.log("start")
environ.videoElement.playbackRate = 1;
setPlaybackDisplay(1, " talking");
},
// energy_threshold_ratio_neg: 0.1,
// energy_threshold_ratio_pos: 1.5
// smoothingTimeConstant: 0.995
// iterationPeriod
logging: true
}
// import("/vad/lib/vad.js");
const vad = new VAD(libVadOptions);
environ[vad] = vad;
visualize();
}
// from https://github.com/mdn/voice-change-o-matic-float-data/blob/gh-pages/scripts/app.js
const visualSelect = document.getElementById("visual");
const canvas = document.querySelector('.visualizer');
const canvasCtx = canvas.getContext("2d");
let drawVisual = null;
let intendedWidth = document.querySelector('.wrapper').clientWidth;
canvas.setAttribute('width',intendedWidth);
function visualize() {
WIDTH = canvas.width;
HEIGHT = canvas.height;
var visualSetting = visualSelect.value;
console.log(visualSetting);
if(visualSetting == "sinewave") {
analyser.fftSize = 1024;
var bufferLength = analyser.fftSize;
console.log(bufferLength);
var dataArray = new Float32Array(bufferLength);
canvasCtx.clearRect(0, 0, WIDTH, HEIGHT);
function draw() {
drawVisual = requestAnimationFrame(draw);
analyser.getFloatTimeDomainData(dataArray);
canvasCtx.fillStyle = 'rgb(200, 200, 200)';
canvasCtx.fillRect(0, 0, WIDTH, HEIGHT);
canvasCtx.lineWidth = 2;
canvasCtx.strokeStyle = 'rgb(0, 0, 0)';
canvasCtx.beginPath();
var sliceWidth = WIDTH * 1.0 / bufferLength;
var x = 0;
for(var i = 0; i < bufferLength; i++) {
var v = dataArray[i] * 200.0;
var y = HEIGHT/2 + v;
if(i === 0) {
canvasCtx.moveTo(x, y);
} else {
canvasCtx.lineTo(x, y);
}
x += sliceWidth;
}
canvasCtx.lineTo(canvas.width, canvas.height/2);
canvasCtx.stroke();
};
draw();
} else if(visualSetting == "frequencybars") {
analyser.fftSize = 256;
const bufferLength = analyser.frequencyBinCount;
console.log(bufferLength);
var dataArray = new Float32Array(bufferLength);
canvasCtx.clearRect(0, 0, WIDTH, HEIGHT);
function draw() {
drawVisual = requestAnimationFrame(draw);
// if (halt) {
// return;
// }
// https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getFloatFrequencyData
// Each item in the array represents the decibel value for a specific frequency.
// The array ranges over the frequencies 0 hertz to 22,050 hertz.
analyser.getFloatFrequencyData(dataArray);
const frequencyInterval = (22050/bufferLength);
canvasCtx.fillStyle = 'rgb(0, 0, 0)';
canvasCtx.fillRect(0, 0, WIDTH, HEIGHT);
var barWidth = (WIDTH / bufferLength) * 2.5;
var barHeight;
var x = 0;
for(var i = 0; i < bufferLength; i++) {
barHeight = (dataArray[i] + 140)*2;
canvasCtx.fillStyle = 'rgb(' + Math.floor(barHeight+100) + ',50,50)';
canvasCtx.fillRect(x,HEIGHT-barHeight/2,barWidth,barHeight/2);
const hz = (frequencyInterval*i);
const frequencyString = `${Math.trunc(hz)}`
canvasCtx.fillText(frequencyString, (x), (10), barWidth)
x += barWidth + 1;
}
};
draw();
} else if(visualSetting == "off") {
canvasCtx.clearRect(0, 0, WIDTH, HEIGHT);
canvasCtx.fillStyle = "red";
canvasCtx.fillRect(0, 0, WIDTH, HEIGHT);
}
}
visualSelect.onchange = function() {
window.cancelAnimationFrame(drawVisual);
visualize();
} |
/* global describe, it, expect */
const path = require("path");
const rmfr = require("rmfr");
const configuration = require("@swissquote/crafty/src/configuration");
const testUtils = require("../utils");
const getCrafty = configuration.getCrafty;
// Add a high timeout because of https://github.com/facebook/jest/issues/8942
// Tests would be unreliable if they timeout >_<
jest.setTimeout(30000);
it("Loads crafty-preset-typescript and does not register gulp tasks", () => {
const crafty = getCrafty(["@swissquote/crafty-preset-typescript"], {});
const loadedPresets = crafty.config.loadedPresets.map(
preset => preset.presetName
);
expect(loadedPresets).toContain("@swissquote/crafty-preset-typescript");
crafty.createTasks();
expect(Object.keys(crafty.undertaker._registry.tasks())).toEqual([]);
});
it("Loads crafty-preset-typescript, crafty-runner-gulp and registers gulp task", () => {
const config = { js: { myBundle: { source: "js/**/*.ts" } } };
const crafty = getCrafty(
["@swissquote/crafty-preset-typescript", "@swissquote/crafty-runner-gulp"],
config
);
const loadedPresets = crafty.config.loadedPresets.map(
preset => preset.presetName
);
expect(loadedPresets).toContain("@swissquote/crafty-preset-typescript");
expect(loadedPresets).toContain("@swissquote/crafty-runner-gulp");
crafty.createTasks();
expect(Object.keys(crafty.undertaker._registry.tasks())).toEqual([
"js_myBundle",
"js",
"default"
]);
});
it("Compiles TypeScript", async () => {
const cwd = path.join(
__dirname,
"../fixtures/crafty-preset-typescript-gulp/compiles"
);
await rmfr(path.join(cwd, "dist"));
const result = await testUtils.run(["run", "default"], cwd);
expect(result).toMatchSnapshot();
expect(testUtils.exists(cwd, "dist/js/myBundle.min.js")).toBeFalsy();
expect(testUtils.exists(cwd, "dist/js/myBundle.min.js.map")).toBeFalsy();
expect(testUtils.exists(cwd, "dist/js/script.js")).toBeTruthy();
expect(testUtils.exists(cwd, "dist/js/script.js.map")).toBeTruthy();
expect(testUtils.exists(cwd, "dist/js/Component.js")).toBeTruthy();
expect(testUtils.exists(cwd, "dist/js/Component.js.map")).toBeTruthy();
expect(testUtils.readForSnapshot(cwd, "dist/js/script.js")).toMatchSnapshot();
expect(
testUtils.readForSnapshot(cwd, "dist/js/Component.js")
).toMatchSnapshot();
});
it("Compiles TypeScript and concatenates", async () => {
const cwd = path.join(
__dirname,
"../fixtures/crafty-preset-typescript-gulp/concatenates"
);
await rmfr(path.join(cwd, "dist"));
const result = await testUtils.run(["run", "default"], cwd);
expect(result).toMatchSnapshot();
expect(testUtils.exists(cwd, "dist/js/myBundle.min.js")).toBeTruthy();
expect(testUtils.exists(cwd, "dist/js/myBundle.min.js.map")).toBeTruthy();
expect(testUtils.exists(cwd, "dist/js/script.js")).toBeFalsy();
expect(testUtils.exists(cwd, "dist/js/script.js.map")).toBeFalsy();
expect(testUtils.exists(cwd, "dist/js/otherfile.js")).toBeFalsy();
expect(testUtils.exists(cwd, "dist/js/otherfile.js.map")).toBeFalsy();
expect(
testUtils.readForSnapshot(cwd, "dist/js/myBundle.min.js")
).toMatchSnapshot();
});
it("Fails gracefully on broken markup", async () => {
const cwd = path.join(
__dirname,
"../fixtures/crafty-preset-typescript-gulp/fails"
);
await rmfr(path.join(cwd, "dist"));
const result = await testUtils.run(["run", "default"], cwd);
expect(result).toMatchSnapshot();
// Files aren't generated on failed lint
expect(testUtils.exists(cwd, "dist/js/myBundle.min.js")).toBeFalsy();
expect(testUtils.exists(cwd, "dist/js/myBundle.min.js.map")).toBeFalsy();
});
it("Lints TypeScript", async () => {
const cwd = path.join(
__dirname,
"../fixtures/crafty-preset-typescript-gulp/lints"
);
await rmfr(path.join(cwd, "dist"));
const result = await testUtils.run(["run", "default"], cwd);
expect(result).toMatchSnapshot();
// Files aren't generated on failed lint
expect(testUtils.exists(cwd, "dist/js/myBundle.min.js")).toBeFalsy();
expect(testUtils.exists(cwd, "dist/js/myBundle.min.js.map")).toBeFalsy();
});
|
/**
* @license
* Copyright 2021 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
/**
* @fileoverview A backpack that lives on top of the workspace.
* @author [email protected] (Monica Kozbial)
*/
import * as Blockly from 'blockly/core';
import {cleanBlockXML, registerContextMenus} from './backpack_helpers';
import {BackpackChange, BackpackOpen} from './ui_events';
import {
BackpackContextMenuOptions, BackpackOptions, parseOptions,
} from './options';
/**
* Class for backpack that can be used save blocks from the workspace for
* future use.
* @param {!Blockly.WorkspaceSvg} workspace The workspace to sit in.
* @implements {Blockly.IAutoHideable}
* @implements {Blockly.IPositionable}
* @extends {Blockly.DragTarget}
*/
export class Backpack extends Blockly.DragTarget {
/**
* Constructor for a backpack.
* @param {!Blockly.WorkspaceSvg} targetWorkspace The target workspace that
* the backpack will be added to.
* @param {!BackpackOptions=} backpackOptions The backpack options to use.
*/
constructor(targetWorkspace, backpackOptions) {
super();
/**
* The workspace.
* @type {!Blockly.WorkspaceSvg}
* @protected
*/
this.workspace_ = targetWorkspace;
/**
* The unique id for this component.
* @type {string}
*/
this.id = 'backpack';
/**
* The backpack options.
* @type {!BackpackOptions}
*/
this.options_ = parseOptions(backpackOptions);
/**
* The backpack flyout. Initialized during init.
* @type {?Blockly.IFlyout}
* @protected
*/
this.flyout_ = null;
/**
* A list of XML (stored as strings) representing blocks in the backpack.
* @type {!Array<string>}
* @protected
*/
this.contents_ = [];
/**
* Array holding info needed to unbind events.
* Used for disposing.
* @type {!Array<!Blockly.browserEvents.Data>}
* @protected
*/
this.boundEvents_ = [];
/**
* Left coordinate of the backpack.
* @type {number}
* @protected
*/
this.left_ = 0;
/**
* Top coordinate of the backpack.
* @type {number}
* @protected
*/
this.top_ = 0;
/**
* Width of the backpack. Used for clip path.
* @type {number}
* @const
* @protected
*/
this.WIDTH_ = 40;
/**
* Height of the backpack. Used for clip path.
* @type {number}
* @const
* @protected
*/
this.HEIGHT_ = 60;
/**
* Distance between backpack and bottom or top edge of workspace.
* @type {number}
* @const
* @protected
*/
this.MARGIN_VERTICAL_ = 20;
/**
* Distance between backpack and right or left edge of workspace.
* @type {number}
* @const
* @protected
*/
this.MARGIN_HORIZONTAL_ = 20;
/**
* Extent of hotspot on all sides beyond the size of the image.
* @const {number}
* @protected
*/
this.HOTSPOT_MARGIN_ = 10;
/**
* The SVG group containing the backpack.
* @type {?SVGElement}
* @protected
*/
this.svgGroup_ = null;
/**
* Top offset for backpack in svg.
* @type {number}
* @private
*/
this.SPRITE_TOP_ = 10;
/**
* Left offset for backpack in svg.
* @type {number}
* @private
*/
this.SPRITE_LEFT_ = 20;
/**
* Width/Height of svg.
* @type {number}
* @const
* @private
*/
this.SPRITE_SIZE_ = 80;
}
/**
* Initializes the backpack.
*/
init() {
this.workspace_.getComponentManager().addComponent({
component: this,
weight: 2,
capabilities: [
Blockly.ComponentManager.Capability.AUTOHIDEABLE,
Blockly.ComponentManager.Capability.DRAG_TARGET,
Blockly.ComponentManager.Capability.POSITIONABLE,
],
});
this.initFlyout_();
this.createDom_();
this.attachListeners_();
registerContextMenus(
/** @type {!BackpackContextMenuOptions} */ this.options_.contextMenu,
this.workspace_);
this.initialized_ = true;
this.workspace_.resize();
}
/**
* Disposes of workspace search.
* Unlink from all DOM elements and remove all event listeners
* to prevent memory leaks.
*/
dispose() {
if (this.svgGroup_) {
Blockly.utils.dom.removeNode(this.svgGroup_);
}
for (const event of this.boundEvents_) {
Blockly.unbindEvent_(event);
}
this.boundEvents_.length = 0;
}
/**
* Creates and initializes the flyout and inserts it into the dom.
* @protected
*/
initFlyout_() {
// Create flyout options.
const flyoutWorkspaceOptions = new Blockly.Options(
/** @type {!Blockly.BlocklyOptions} */
({
'scrollbars': true,
'parentWorkspace': this.workspace_,
'rtl': this.workspace_.RTL,
'oneBasedIndex': this.workspace_.options.oneBasedIndex,
'renderer': this.workspace_.options.renderer,
'rendererOverrides': this.workspace_.options.rendererOverrides,
'move': {
'scrollbars': true,
},
}));
// Create vertical or horizontal flyout.
if (this.workspace_.horizontalLayout) {
flyoutWorkspaceOptions.toolboxPosition =
(this.workspace_.toolboxPosition ===
Blockly.utils.toolbox.Position.TOP) ?
Blockly.utils.toolbox.Position.BOTTOM :
Blockly.utils.toolbox.Position.TOP;
const HorizontalFlyout = Blockly.registry.getClassFromOptions(
Blockly.registry.Type.FLYOUTS_HORIZONTAL_TOOLBOX,
this.workspace_.options, true);
this.flyout_ = new HorizontalFlyout(flyoutWorkspaceOptions);
} else {
flyoutWorkspaceOptions.toolboxPosition =
(this.workspace_.toolboxPosition ===
Blockly.utils.toolbox.Position.RIGHT) ?
Blockly.utils.toolbox.Position.LEFT :
Blockly.utils.toolbox.Position.RIGHT;
const VerticalFlyout = Blockly.registry.getClassFromOptions(
Blockly.registry.Type.FLYOUTS_VERTICAL_TOOLBOX,
this.workspace_.options, true);
this.flyout_ = new VerticalFlyout(flyoutWorkspaceOptions);
}
// Add flyout to DOM.
const parentNode = this.workspace_.getParentSvg().parentNode;
parentNode.appendChild(this.flyout_.createDom(Blockly.utils.Svg.SVG));
this.flyout_.init(this.workspace_);
}
/**
* Creates DOM for UI element.
* @protected
*/
createDom_() {
this.svgGroup_ = Blockly.utils.dom.createSvgElement(
Blockly.utils.Svg.G, {}, null);
const rnd = Blockly.utils.genUid();
const clip = Blockly.utils.dom.createSvgElement(
Blockly.utils.Svg.CLIPPATH,
{'id': 'blocklyBackpackClipPath' + rnd},
this.svgGroup_);
Blockly.utils.dom.createSvgElement(
Blockly.utils.Svg.RECT,
{
'width': this.WIDTH_,
'height': this.HEIGHT_,
},
clip);
this.svgImg_ = Blockly.utils.dom.createSvgElement(
Blockly.utils.Svg.IMAGE,
{
'class': 'blocklyBackpack',
'clip-path': 'url(#blocklyBackpackClipPath' + rnd + ')',
'width': this.SPRITE_SIZE_ + 'px',
'x': -this.SPRITE_LEFT_,
'height': this.SPRITE_SIZE_ + 'px',
'y': -this.SPRITE_TOP_,
},
this.svgGroup_);
this.svgImg_.setAttributeNS(Blockly.utils.dom.XLINK_NS, 'xlink:href',
BACKPACK_SVG_DATAURI);
Blockly.utils.dom.insertAfter(
this.svgGroup_, this.workspace_.getBubbleCanvas());
}
/**
* Attaches event listeners.
* @protected
*/
attachListeners_() {
this.addEvent_(
this.svgGroup_, 'mousedown', this, this.blockMouseDownWhenOpenable_);
this.addEvent_(
this.svgGroup_, 'mouseup', this, this.onClick_);
this.addEvent_(
this.svgGroup_, 'mouseover', this, this.onMouseOver_);
this.addEvent_(
this.svgGroup_, 'mouseout', this, this.onMouseOut_);
}
/**
* Helper method for adding an event.
* @param {!Element} node Node upon which to listen.
* @param {string} name Event name to listen to (e.g. 'mousedown').
* @param {Object} thisObject The value of 'this' in the function.
* @param {!Function} func Function to call when event is triggered.
* @private
*/
addEvent_(node, name, thisObject, func) {
const event = Blockly.browserEvents.bind(node, name, thisObject, func);
this.boundEvents_.push(event);
}
/**
* Returns the backpack flyout.
* @return {?Blockly.IFlyout} The backpack flyout.
* @public
*/
getFlyout() {
return this.flyout_;
}
/**
* Returns the bounding rectangle of the drag target area in pixel units
* relative to viewport.
* @return {?Blockly.utils.Rect} The component's bounding box. Null if drag
* target area should be ignored.
*/
getClientRect() {
if (!this.svgGroup_) {
return null;
}
const clientRect = this.svgGroup_.getBoundingClientRect();
const top = clientRect.top + this.SPRITE_TOP_ - this.HOTSPOT_MARGIN_;
const bottom = top + this.HEIGHT_ + 2 * this.HOTSPOT_MARGIN_;
const left = clientRect.left + this.SPRITE_LEFT_ - this.HOTSPOT_MARGIN_;
const right = left + this.WIDTH_ + 2 * this.HOTSPOT_MARGIN_;
return new Blockly.utils.Rect(top, bottom, left, right);
}
/**
* Returns the bounding rectangle of the UI element in pixel units relative to
* the Blockly injection div.
* @return {!Blockly.utils.Rect} The component’s bounding box.
*/
getBoundingRectangle() {
return new Blockly.utils.Rect(
this.top_, this.top_ + this.HEIGHT_,
this.left_, this.left_ + this.WIDTH_);
}
/**
* Positions the backpack.
* It is positioned in the opposite corner to the corner the
* categories/toolbox starts at.
* @param {!Blockly.MetricsManager.UiMetrics} metrics The workspace metrics.
* @param {!Array<!Blockly.utils.Rect>} savedPositions List of rectangles that
* are already on the workspace.
*/
position(metrics, savedPositions) {
if (!this.initialized_) {
return;
}
const hasVerticalScrollbars = this.workspace_.scrollbar &&
this.workspace_.scrollbar.canScrollHorizontally();
const hasHorizontalScrollbars = this.workspace_.scrollbar &&
this.workspace_.scrollbar.canScrollVertically();
if (metrics.toolboxMetrics.position === Blockly.TOOLBOX_AT_LEFT ||
(this.workspace_.horizontalLayout && !this.workspace_.RTL)) {
// Right corner placement.
this.left_ = metrics.absoluteMetrics.left + metrics.viewMetrics.width -
this.WIDTH_ - this.MARGIN_HORIZONTAL_;
if (hasVerticalScrollbars && !this.workspace_.RTL) {
this.left_ -= Blockly.Scrollbar.scrollbarThickness;
}
} else {
// Left corner placement.
this.left_ = this.MARGIN_HORIZONTAL_;
if (hasVerticalScrollbars && this.workspace_.RTL) {
this.left_ += Blockly.Scrollbar.scrollbarThickness;
}
}
const startAtBottom =
metrics.toolboxMetrics.position === Blockly.TOOLBOX_AT_BOTTOM;
if (startAtBottom) {
// Bottom corner placement
this.top_ = metrics.absoluteMetrics.top + metrics.viewMetrics.height -
this.HEIGHT_ - this.MARGIN_VERTICAL_;
if (hasHorizontalScrollbars) {
// The horizontal scrollbars are always positioned on the bottom.
this.top_ -= Blockly.Scrollbar.scrollbarThickness;
}
} else {
// Upper corner placement
this.top_ = metrics.absoluteMetrics.top + this.MARGIN_VERTICAL_;
}
// Check for collision and bump if needed.
let boundingRect = this.getBoundingRectangle();
for (let i = 0, otherEl; (otherEl = savedPositions[i]); i++) {
if (boundingRect.intersects(otherEl)) {
if (startAtBottom) { // Bump up.
this.top_ = otherEl.top - this.HEIGHT_ - this.MARGIN_VERTICAL_;
} else { // Bump down.
this.top_ = otherEl.bottom + this.MARGIN_VERTICAL_;
}
// Recheck other savedPositions
boundingRect = this.getBoundingRectangle();
i = -1;
}
}
this.svgGroup_.setAttribute('transform',
'translate(' + this.left_ + ',' + this.top_ + ')');
}
/**
* Returns the count of items in the backpack.
* @return {number} The count of items.
*/
getCount() {
return this.contents_.length;
}
/**
* Returns backpack contents.
* @return {!Array<string>} The backpack contents.
*/
getContents() {
// Return a shallow copy of the contents array.
return [...this.contents_];
}
/**
* Handles when a block or bubble is dropped on this component.
* Should not handle delete here.
* @param {!Blockly.IDraggable} dragElement The block or bubble currently
* being dragged.
*/
onDrop(dragElement) {
if (dragElement instanceof Blockly.BlockSvg) {
this.addBlock(/** @type {!Blockly.BlockSvg} */ (dragElement));
}
}
/**
* Converts the provided block into a cleaned XML string.
* @param {!Blockly.Block} block The block to convert.
* @return {string} The cleaned XML string.
* @private
*/
blockToCleanXmlString_(block) {
return cleanBlockXML(Blockly.Xml.blockToDom(block));
}
/**
* Returns whether the backpack contains a duplicate of the provided Block.
* @param {!Blockly.Block} block The block to check.
* @return {boolean} Whether the backpack contains a duplicate of the provided
* block.
*/
containsBlock(block) {
const cleanedBlockXml = this.blockToCleanXmlString_(block);
return this.contents_.indexOf(cleanedBlockXml) !== -1;
}
/**
* Adds the specified block to backpack.
* @param {!Blockly.Block} block The block to be added to the backpack.
*/
addBlock(block) {
this.addItem(this.blockToCleanXmlString_(block));
}
/**
* Adds the provided blocks to backpack.
* @param {!Array<!Blockly.Block>} blocks The blocks to be added to the
* backpack.
*/
addBlocks(blocks) {
const cleanedBlocks = blocks.map(this.blockToCleanXmlString_);
this.addItems(cleanedBlocks);
}
/**
* Removes the specified block from the backpack.
* @param {!Blockly.Block} block The block to be removed from the backpack.
*/
removeBlock(block) {
this.removeItem(this.blockToCleanXmlString_(block));
}
/**
* Adds item to backpack.
* @param {string} item Text representing the XML tree of a block to add,
* cleaned of all unnecessary attributes.
*/
addItem(item) {
this.addItems([item]);
}
/**
* Adds multiple items to the backpack.
* @param {!Array<string>} items The backpack contents to add.
*/
addItems(items) {
const addedItems = this.filterDuplicates_(items);
if (addedItems.length) {
this.contents_.unshift(...addedItems);
this.onContentChange_();
}
}
/**
* Removes item from the backpack.
* @param {string} item Text representing the XML tree of a block to remove,
* cleaned of all unnecessary attributes.
*/
removeItem(item) {
const itemIndex = this.contents_.indexOf(item);
if (itemIndex !== -1) {
this.contents_.splice(itemIndex, 1);
this.onContentChange_();
}
}
/**
* Sets backpack contents.
* @param {!Array<string>} contents The new backpack contents.
*/
setContents(contents) {
this.contents_ = [];
this.contents_ = this.filterDuplicates_(contents);
this.onContentChange_();
}
/**
* Empties the backpack's contents. If the contents-flyout is currently open
* it will be closed.
*/
empty() {
if (!this.getCount()) {
return;
}
if (this.contents_.length) {
this.contents_ = [];
this.onContentChange_();
}
this.close();
}
/**
* Handles content change.
* @protected
*/
onContentChange_() {
this.maybeRefreshFlyoutContents_();
Blockly.Events.fire(new BackpackChange(this.workspace_.id));
}
/**
* Returns a filtered list without duplicates within itself and without any
* shared elements with this.contents_.
* @param {!Array<string>} array The array of items to filter.
* @return {!Array<string>} The filtered list.
* @private
*/
filterDuplicates_(array) {
return array.filter((item, idx) => {
return array.indexOf(item) === idx && this.contents_.indexOf(item) === -1;
});
}
/**
* Returns whether the backpack is open-able.
* @return {boolean} Whether the backpack is open-able.
* @protected
*/
isOpenable_() {
return !this.isOpen();
}
/**
* Returns whether the backpack is open.
* @return {boolean} Whether the backpack is open.
*/
isOpen() {
return this.flyout_.isVisible();
}
/**
* Opens the backpack flyout.
*/
open() {
if (!this.isOpenable_()) {
return;
}
const xml = this.contents_.map((text) => Blockly.Xml.textToDom(text));
this.flyout_.show(xml);
Blockly.Events.fire(new BackpackOpen(true, this.workspace_.id));
}
/**
* Refreshes backpack flyout contents if the flyout is open.
* @protected
*/
maybeRefreshFlyoutContents_() {
if (!this.isOpen()) {
return;
}
const xml = this.contents_.map((text) => Blockly.Xml.textToDom(text));
this.flyout_.show(xml);
}
/**
* Closes the backpack flyout.
*/
close() {
if (!this.isOpen()) {
return;
}
this.flyout_.hide();
Blockly.Events.fire(new BackpackOpen(false, this.workspace_.id));
}
/**
* Hides the component. Called in Blockly.hideChaff.
* @param {boolean} onlyClosePopups Whether only popups should be closed.
* Flyouts should not be closed if this is true.
*/
autoHide(onlyClosePopups) {
// The backpack flyout always autocloses because it overlays the backpack UI
// (no backpack to click to close it).
if (!onlyClosePopups) {
this.close();
}
}
/**
* Handle click event.
* @param {!MouseEvent} e Mouse event.
* @protected
*/
onClick_(e) {
if (Blockly.utils.isRightButton(e)) {
return;
}
this.open();
const uiEvent = new (Blockly.Events.get(Blockly.Events.CLICK))(
null, this.workspace_.id, 'backpack');
Blockly.Events.fire(uiEvent);
}
/**
* Handles when a cursor with a block or bubble enters this drag target.
* @param {!Blockly.IDraggable} dragElement The block or bubble currently
* being dragged.
*/
onDragEnter(dragElement) {
if (dragElement instanceof Blockly.BlockSvg) {
this.updateHoverStying_(true);
}
}
/**
* Handles when a cursor with a block or bubble exits this drag target.
* @param {!Blockly.IDraggable} _dragElement The block or bubble currently
* being dragged.
*/
onDragExit(_dragElement) {
this.updateHoverStying_(false);
}
/**
* Handles a mouseover event.
* @private
*/
onMouseOver_() {
if (this.isOpenable_()) {
this.updateHoverStying_(true);
}
}
/**
* Handles a mouseout event.
* @private
*/
onMouseOut_() {
this.updateHoverStying_(false);
}
/**
* Adds or removes styling to darken the backpack to show it is interactable.
* @param {boolean} addClass True to add styling, false to remove.
* @protected
*/
updateHoverStying_(addClass) {
const backpackDarken = 'blocklyBackpackDarken';
if (addClass) {
Blockly.utils.dom.addClass(
/** @type {!SVGElement} */ (this.svgImg_), backpackDarken);
} else {
Blockly.utils.dom.removeClass(
/** @type {!SVGElement} */ (this.svgImg_), backpackDarken);
}
}
/**
* Returns whether the provided block or bubble should not be moved after
* being dropped on this component. If true, the element will return to where
* it was when the drag started.
* @param {!Blockly.IDraggable} dragElement The block or bubble currently
* being dragged.
* @return {boolean} Whether the block or bubble provided should be returned
* to drag start.
*/
shouldPreventMove(dragElement) {
return dragElement instanceof Blockly.BlockSvg;
}
/**
* Prevents a workspace scroll and click event if the backpack is openable.
* @param {!Event} e A mouse down event.
* @protected
*/
blockMouseDownWhenOpenable_(e) {
if (!Blockly.utils.isRightButton(e) && this.isOpenable_()) {
e.stopPropagation(); // Don't start a workspace scroll.
}
}
}
/**
* Base64 encoded data uri for backpack icon.
* @type {string}
*/
const BACKPACK_SVG_DATAURI =
'data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC' +
'9zdmciIGVuYWJsZS1iYWNrZ3JvdW5kPSJuZXcgMCAwIDI0IDI0IiBoZWlnaHQ9IjI0cHgiIH' +
'ZpZXdCb3g9IjAgMCAyNCAyNCIgd2lkdGg9IjI0cHgiIGZpbGw9IiM0NTVBNjQiPjxnPjxyZW' +
'N0IGZpbGw9Im5vbmUiIGhlaWdodD0iMjQiIHdpZHRoPSIyNCIvPjwvZz48Zz48Zy8+PGc+PH' +
'BhdGggZD0iTTEzLjk3LDUuMzRDMTMuOTgsNS4yMywxNCw1LjEyLDE0LDVjMC0xLjEtMC45LT' +
'ItMi0ycy0yLDAuOS0yLDJjMCwwLjEyLDAuMDIsMC4yMywwLjAzLDAuMzRDNy42OSw2LjE1LD' +
'YsOC4zOCw2LDExdjggYzAsMS4xLDAuOSwyLDIsMmg4YzEuMSwwLDItMC45LDItMnYtOEMxOC' +
'w4LjM4LDE2LjMxLDYuMTUsMTMuOTcsNS4zNHogTTExLDVjMC0wLjU1LDAuNDUtMSwxLTFzMS' +
'wwLjQ1LDEsMSBjMCwwLjAzLTAuMDEsMC4wNi0wLjAyLDAuMDlDMTIuNjYsNS4wMywxMi4zNC' +
'w1LDEyLDVzLTAuNjYsMC4wMy0wLjk4LDAuMDlDMTEuMDEsNS4wNiwxMSw1LjAzLDExLDV6IE' +
'0xNiwxM3YxdjAuNSBjMCwwLjI4LTAuMjIsMC41LTAuNSwwLjVTMTUsMTQuNzgsMTUsMTQuNV' +
'YxNHYtMUg4di0xaDdoMVYxM3oiLz48L2c+PC9nPjwvc3ZnPg==';
Blockly.Css.register([
`.blocklyBackpack {
opacity: .4;
}
.blocklyBackpackDarken {
opacity: .6;
}
.blocklyBackpack:active {
opacity: .8;
}`,
]);
|
import React from 'react'
import Layout from '../../components/Layout'
export default () => (
<Layout>
<section className="section">
<div className="container">
<div className="content">
<h1>Thank you!</h1>
<p>This is a placeholder form submission page</p>
</div>
</div>
</section>
</Layout>
)
|
import React, { PureComponent } from 'react';
import { Button, Form, Input, Row, Col } from 'hzero-ui';
import intl from 'utils/intl';
import { SEARCH_FORM_ITEM_LAYOUT } from 'utils/constants';
const FormItem = Form.Item;
const modelPrompt = 'hiam.menuConfig.model.menuConfig';
const commonPrompt = 'hzero.common';
@Form.create({ fieldNameProp: null })
export default class QueryForm extends PureComponent {
onClick() {
const {
handleQueryList = e => e,
form: { getFieldsValue = e => e },
} = this.props;
const data = getFieldsValue() || {};
handleQueryList({
...data,
});
}
onReset() {
const {
form: { resetFields = e => e },
} = this.props;
resetFields();
}
render() {
const {
form: { getFieldDecorator = e => e },
} = this.props;
return (
<Form>
<Row type="flex" gutter={24} align="bottom">
<Col span={8}>
<FormItem
{...SEARCH_FORM_ITEM_LAYOUT}
label={intl.get(`${modelPrompt}.permissionCode`).d('权限编码')}
>
{getFieldDecorator('code')(<Input trim typeCase="lower" inputChinese={false} />)}
</FormItem>
</Col>
<Col span={8}>
<FormItem
{...SEARCH_FORM_ITEM_LAYOUT}
label={intl.get(`${modelPrompt}.permissionName`).d('权限名称')}
>
{getFieldDecorator('name')(<Input />)}
</FormItem>
</Col>
<Col span={8}>
<FormItem>
<Button onClick={this.onReset.bind(this)} style={{ marginRight: 8 }}>
{intl.get(`${commonPrompt}.button.reset`).d('重置')}
</Button>
<Button type="primary" htmlType="submit" onClick={this.onClick.bind(this)}>
{intl.get(`${commonPrompt}.button.search`).d('查询')}
</Button>
</FormItem>
</Col>
</Row>
</Form>
);
}
}
|
from bs4 import BeautifulSoup
url = 'http://example.webscraping.com/places/view/United-Kingdom-239'
html = download(url)
broken_html = '<ul class=country><li>Area<li>Population</ul>'
soup = BeautifulSoup(broken_html, 'html.parser')
fixed_html = soup.prettify()
print(fixed_html)
ul = soup.find('ul', attrs={'class':'country'})
ul.find('li')
ul.find_all('li')
soup = BeautifulSoup(html)
tr = soup.find(attrs={'id':'places_area__row'})
td = tr.find(attrs={'class':'w2p_fw'})
area = td.text
print(area)
|
const express = require('express');
const app = express();
const noteRoutes = require('./routes/noteRoutes');
//setting initial port
const PORT = process.env.PORT || 3000;
//data parsing
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
app.use(express.static('public'));
app.use(noteRoutes);
//starts server
app.listen(PORT, () => {
console.log(`App listening on PORT: ${PORT}`);
}); |
"""Platform for switch integration."""
import logging
import async_timeout
from smarttub import SpaPump
from homeassistant.components.switch import SwitchEntity
from .const import API_TIMEOUT, ATTR_PUMPS, DOMAIN, SMARTTUB_CONTROLLER
from .entity import SmartTubEntity
from .helpers import get_spa_name
_LOGGER = logging.getLogger(__name__)
async def async_setup_entry(hass, entry, async_add_entities):
"""Set up switch entities for the pumps on the tub."""
controller = hass.data[DOMAIN][entry.entry_id][SMARTTUB_CONTROLLER]
entities = [
SmartTubPump(controller.coordinator, pump)
for spa in controller.spas
for pump in controller.coordinator.data[spa.id][ATTR_PUMPS].values()
]
async_add_entities(entities)
class SmartTubPump(SmartTubEntity, SwitchEntity):
"""A pump on a spa."""
def __init__(self, coordinator, pump: SpaPump):
"""Initialize the entity."""
super().__init__(coordinator, pump.spa, "pump")
self.pump_id = pump.id
self.pump_type = pump.type
@property
def pump(self) -> SpaPump:
"""Return the underlying SpaPump object for this entity."""
return self.coordinator.data[self.spa.id]["pumps"][self.pump_id]
@property
def unique_id(self) -> str:
"""Return a unique ID for this pump entity."""
return f"{super().unique_id}-{self.pump_id}"
@property
def name(self) -> str:
"""Return a name for this pump entity."""
spa_name = get_spa_name(self.spa)
if self.pump_type == SpaPump.PumpType.CIRCULATION:
return f"{spa_name} Circulation Pump"
if self.pump_type == SpaPump.PumpType.JET:
return f"{spa_name} Jet {self.pump_id}"
return f"{spa_name} pump {self.pump_id}"
@property
def is_on(self) -> bool:
"""Return True if the pump is on."""
return self.pump.state != SpaPump.PumpState.OFF
async def async_toggle(self, **kwargs) -> None:
"""Toggle the pump on or off."""
async with async_timeout.timeout(API_TIMEOUT):
await self.pump.toggle()
await self.coordinator.async_request_refresh()
|
/*
* @Author: dmyang
* @Date: 2015-08-05 00:25:43
* @Last Modified by: dmyang
* @Last Modified time: 2016-08-01 14:40:20
*/
'use strict';
console.info('require page a.');
require('commonCss');
require('../css/a.css');
require('zepto');
// var z = require('zStuff')
// console.log(z)
// 直接使用npm模块
var _ = require('lodash');
var url = require('./utils/url');
var report = require('./helpers/report');
var component = url.getQuery('component');
if('dialog' === component) {
require.ensure([], function(require) {
var dialog = require('./components/dialog');
// todo ...
$('#dialog').removeClass('none');
});
}
if('toast' === component) {
require.ensure([], function(require) {
var toast = require('./components/toast');
// todo ...
$('#toast').removeClass('none');
});
}
require.ensure([], function() {
var ajax = require('./helpers/ajax');
var t = _.now();
ajax.request({
url: '/api/list',
data: {
offset: 0,
limit: 5
}
}).done(function(data) {
var template = require('../tmpl/list.tpl');
var html = template({list: data || []});
console.info('ajax took %d ms.', _.now() - t);
$('#list').html(html);
});
});
var logoImg = require('webpackLogo');
var $logo = $('<img />').attr('src', logoImg);
$('#logo').html($logo);
|
export {useShareProviders, useShareUrl} from './sharing';
export {useEntryMetadata} from './metadata';
export {useEntryStructure, useSectionStructure} from './structure';
export {useFile} from './useFile';
export {useNestedFiles} from './useNestedFiles';
export {useFileRights, useLegalInfo, useCredits} from './legalInfo';
export {useAvailableQualities} from './useAvailableQualities';
export {useTheme} from './theme';
export {EntryStateProvider, useEntryStateDispatch} from './EntryStateProvider';
export {watchCollections} from './watchCollections';
export {updateContentElementConfiguration} from './updateContentElementConfiguration';
|
import { __assign } from "tslib";
import * as React from 'react';
import { StyledIconBase } from '@styled-icons/styled-icon';
export var Vibration = React.forwardRef(function (props, ref) {
var attrs = {
"fill": "currentColor",
"xmlns": "http://www.w3.org/2000/svg",
};
return (React.createElement(StyledIconBase, __assign({ iconAttrs: attrs, iconVerticalAlign: "middle", iconViewBox: "0 0 24 24" }, props, { ref: ref }),
React.createElement("path", { fill: "none", d: "M0 0h24v24H0V0z", key: "k0" }),
React.createElement("path", { d: "M0 15h2V9H0v6zm3 2h2V7H3v10zm19-8v6h2V9h-2zm-3 8h2V7h-2v10zM16.5 3h-9C6.67 3 6 3.67 6 4.5v15c0 .83.67 1.5 1.5 1.5h9c.83 0 1.5-.67 1.5-1.5v-15c0-.83-.67-1.5-1.5-1.5zM16 19H8V5h8v14z", key: "k1" })));
});
Vibration.displayName = 'Vibration';
export var VibrationDimensions = { height: 24, width: 24 };
|
class Cat {}
let kitty = new Cat();
|
import React from 'react'
import { storiesOf } from '@storybook/react'
import { Button, ControlGroup, Icon, Input, Select } from '../src/index.js'
const stories = storiesOf('ControlGroup', module)
stories.add('default', () => (
<ControlGroup>
<ControlGroup.Item>
<Input.AddOn>Prefix</Input.AddOn>
</ControlGroup.Item>
<ControlGroup.Block>
<Input value="HELLO" />
</ControlGroup.Block>
<ControlGroup.Item>
<Input.AddOn>Suffix</Input.AddOn>
</ControlGroup.Item>
</ControlGroup>
))
stories.add('button', () => (
<ControlGroup>
<ControlGroup.Item>
<Button>Button</Button>
</ControlGroup.Item>
<ControlGroup.Item>
<Button>Button</Button>
</ControlGroup.Item>
<ControlGroup.Item>
<Button>Button</Button>
</ControlGroup.Item>
</ControlGroup>
))
stories.add('input + button', () => (
<ControlGroup>
<ControlGroup.Item>
<Input.AddOn>Prefix</Input.AddOn>
</ControlGroup.Item>
<ControlGroup.Block>
<Input value="HELLO" />
</ControlGroup.Block>
<ControlGroup.Item>
<Button version={2} kind="secondary" size="lg" isSuffix>
<Icon name="copy" />
</Button>
</ControlGroup.Item>
</ControlGroup>
))
stories.add('input + select', () => (
<ControlGroup>
<ControlGroup.Item>
<Input.AddOn>Prefix</Input.AddOn>
</ControlGroup.Item>
<ControlGroup.Block>
<Input value="HELLO" />
</ControlGroup.Block>
<ControlGroup.Block>
<Select>
<option>Hallo</option>
</Select>
</ControlGroup.Block>
</ControlGroup>
))
|
console.log([
__dirname,
__filename,
typeof process,
typeof global,
typeof Buffer
]);
|
# Generated by Django 4.0 on 2021-12-22 12:23
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('auth', '0012_alter_user_first_name_max_length'),
]
operations = [
migrations.CreateModel(
name='Post',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('title', models.CharField(max_length=255)),
('body', models.TextField()),
('author', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='auth.user')),
],
),
]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.