text
stringlengths 2
1.05M
|
|---|
/*
Copyright (C) 2020 Google Inc.
Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
*/
import canStache from 'can-stache';
import canMap from 'can-map';
import canComponent from 'can-component';
import '../comment/comment-input';
import '../comment/comment-add-button';
import '../object-list-item/editable-document-object-list-item';
import '../assessment/attach-button';
import template from './ca-object-modal-content.stache';
import tracker from '../../tracker';
import {getAssigneeType} from '../../plugins/utils/comments-utils';
import pubSub from '../../pub-sub';
export default canComponent.extend({
tag: 'ca-object-modal-content',
view: canStache(template),
leakScope: true,
viewModel: canMap.extend({
define: {
comment: {
get() {
return this.attr('content.fields').indexOf('comment') > -1 &&
this.attr('state.open');
},
},
evidence: {
get() {
return this.attr('content.fields').indexOf('attachment') > -1 &&
this.attr('state.open');
},
},
url: {
get() {
return this.attr('content.fields').indexOf('url') > -1 &&
this.attr('state.open');
},
},
state: {
value: {
open: false,
save: false,
controls: false,
},
},
},
isUpdatingEvidences: false,
isRemovingEvidences: false,
content: {
contextScope: {},
fields: [],
title: '',
type: 'dropdown',
value: null,
options: [],
saveDfd: null,
},
afterCreation(comment, success) {
pubSub.dispatch({
type: 'relatedItemSaved',
item: comment,
itemType: 'comments',
});
},
addComment(comment, data) {
return comment.attr(data)
.save()
.done((comment) => {
this.afterCreation(comment, true);
})
.fail((comment) => {
this.afterCreation(comment, false);
});
},
onCommentCreated(e) {
let comment = e.comment;
let instance = this.attr('instance');
let context = instance.attr('context');
tracker.start(instance.type,
tracker.USER_JOURNEY_KEYS.INFO_PANE,
tracker.USER_ACTIONS.INFO_PANE.ADD_COMMENT_TO_LCA);
pubSub.dispatch({
type: 'relatedItemBeforeSave',
items: [comment.attr({
assignee_type: getAssigneeType(instance),
})],
itemType: 'comments',
});
this.attr('content.contextScope.errorsMap.comment', false);
this.attr('content.contextScope.validation.valid',
!this.attr('content.contextScope.errorsMap.attachment'));
this.attr('state.open', false);
this.attr('state.save', false);
this.attr('content.saveDfd')
.then(() => {
this.addComment(comment, {
context: context,
custom_attribute_revision_upd: {
custom_attribute_value: {
id: this.attr('content.contextScope.valueId')(),
},
custom_attribute_definition: {
id: this.attr('content.contextScope.id'),
},
},
});
});
},
}),
});
|
import { useForm } from "@inertiajs/inertia-react";
import React, { useEffect } from "react";
import { useSetRecoilState } from "recoil";
import BtnForm from "../../Components/BtnForm";
import Input from "../../Components/Input";
import Main from "../../Components/Layouts/Admin/Main";
import Radio from "../../Components/Radio";
import Textarea from "../../Components/Textarea";
import { titleState } from "../../Storages/page";
const Create = (props) => {
const { title, santri } = props;
const setTitle = useSetRecoilState(titleState);
useEffect(() => setTitle(title), [title]);
const { data, setData, patch, processing, errors } = useForm(santri);
const handleChange = (e) => {
setData((data) => ({
...data,
[e.target.name]: e.target.value,
}));
};
const handleSubmit = (e) => {
e.preventDefault();
if (santri.id) {
patch(`/santri/${santri.id}`);
}
};
return (
<Main>
<form onSubmit={handleSubmit}>
<div className="row">
<div className="col-6">
<Input
label="Nama"
name="nama"
value={data.nama}
onChange={handleChange}
error={errors.nama}
/>
</div>
</div>
<div className="row">
<div className="col-6">
<Input
label="NIK"
name="nik"
value={data.nik}
onChange={handleChange}
error={errors.nik}
/>
</div>
<div className="col-6">
<Input
label="KK"
name="kk"
value={data.kk}
onChange={handleChange}
error={errors.kk}
/>
</div>
</div>
<div className="row">
<div className="col-4">
<Input
label="Tempat Lahir"
name="tempat_lahir"
value={data.tempat_lahir}
onChange={handleChange}
error={errors.tempat_lahir}
/>
</div>
<div className="col-4">
<Input
label="Tanggal Lahir"
type="date"
name="tanggal_lahir"
value={data.tanggal_lahir}
onChange={handleChange}
error={errors.tanggal_lahir}
/>
</div>
<div className="col-4">
<Radio
inline={true}
name="jenis_kelamin"
checked={data.jenis_kelamin}
label="Jenis Kelamin"
data={[
{
label: "Laki-Laki",
id: 1,
value: 1,
},
{
label: "Perempuan",
id: 2,
value: 2,
},
]}
onChange={(e) => handleChange(e)}
error={errors.jenis_kelamin}
/>
</div>
</div>
<div className="row">
<div className="col-6">
<Input
label="Nama Ortu"
name="nama_ortu"
value={data.nama_ortu}
onChange={handleChange}
error={errors.nama_ortu}
/>
</div>
<div className="col-6">
<Input
label="Telp Ortu"
name="telp_ortu"
value={data.telp_ortu}
onChange={handleChange}
error={errors.telp_ortu}
/>
</div>
</div>
<Textarea
label="Alamat"
name="alamat"
value={data.alamat}
onChange={handleChange}
error={errors.alamat}
/>
<BtnForm
submitTitle="Ubah"
backTitle="Kembali"
backLink="back"
processing={processing}
/>
</form>
</Main>
);
};
export default Create;
|
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _PropertyResponse2 = require('../PropertyResponse');
var _PropertyResponse3 = _interopRequireDefault(_PropertyResponse2);
var _PropertyDecoder = require('../PropertyDecoder');
var _PropertyDecoder2 = _interopRequireDefault(_PropertyDecoder);
var _helpers = require('../helpers');
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var CruiseControlResponse = function (_PropertyResponse) {
_inherits(CruiseControlResponse, _PropertyResponse);
/**
* @property {String} cruiseControl (string) Cruise control state
* @property {String} limiter (string) Limiter state
* @property {Number} targetSpeed The target speed in km/h
* @property {String} acc (string) Adaptive Cruise Control state
* @property {Number} accTargetSpeed (string) The target speed in km/h of the Adaptive Cruise Control
*
* @example CruiseControlResponse
{
cruiseControl: { value: 'active' },
limiter: { value: 'not_set' },
targetSpeed: { value: 90 },
acc: { value: 'inactive' },
accTargetSpeed: { value: 0 },
}
*/
function CruiseControlResponse(data, config) {
_classCallCheck(this, CruiseControlResponse);
var _this = _possibleConstructorReturn(this, (CruiseControlResponse.__proto__ || Object.getPrototypeOf(CruiseControlResponse)).call(this));
var properties = [new _PropertyDecoder2.default(0x01, 'cruiseControl').setDecoder((0, _helpers.switchDecoder)({
0x00: 'inactive',
0x01: 'active'
})), new _PropertyDecoder2.default(0x02, 'limiter').setDecoder((0, _helpers.switchDecoder)({
0x00: 'not_set',
0x01: 'higher_speed_requested',
0x02: 'lower_speed_requested',
0x03: 'speed_fixed'
})), new _PropertyDecoder2.default(0x03, 'targetSpeed').setDecoder(_helpers.bytesSum), new _PropertyDecoder2.default(0x04, 'acc').setDecoder((0, _helpers.switchDecoder)({
0x00: 'inactive',
0x01: 'active'
})), new _PropertyDecoder2.default(0x05, 'accTargetSpeed').setDecoder(_helpers.bytesSum)];
_this.parse(data, properties, config);
return _this;
}
return CruiseControlResponse;
}(_PropertyResponse3.default);
CruiseControlResponse.identifier = [0x00, 0x62];
exports.default = CruiseControlResponse;
|
import Vue from 'vue'
import VeeValidate, { Validator } from 'vee-validate'
import zh from 'vee-validate/dist/locale/zh_CN' // 引入中文文件
Validator.addLocale(zh)
const config = {
locale: 'zh_CN',
fieldsBagName: 'fieldBags'
}
Vue.use(VeeValidate, config)
// 自定义validate
const dictionary = {
zh_CN: {
messages: {
required: (field) => '请' + field,
number: (field) => field + '必须为数值',
url: () => '请输入正确格式的服务器地址',
ip: () => '请输入正确的IP地址',
},
attributes: {
ip: '输入IP地址',
httpPort: '输入HTTP端口',
userName: '输入用户昵称',
mobile: '输入手机号码',
emailAdd: '输入邮件地址',
authCode: '输入您收到的验证码',
loginPwd: '输入登录密码(6~18位',
traderpwd: '输入交易密码(6~18位',
recommender: '输入您的推荐人',
isSee: '阅读用户协议,并同意',
npwdLog: '输入新的登录密码',
qrwdLog: '输入确认登录密码'
}
}
}
Validator.updateDictionary(dictionary)
// 1.IPV4地址
Validator.extend('ipAddr', {
messages: {
zh_CN: field => '请输入正确的IPV4地址'
},
validate: value => {
return /^((25[0-5]|2[0-4]\d|((1\d{2})|([1-9]?\d)))\.){3}(25[0-5]|2[0-4]\d|((1\d{2})|([1-9]?\d)))$/.test(value)
}
})
// 2.端口【0~65535】
Validator.extend('port', {
messages: {
zh_CN: field => '请输入正确格式的端口号'
},
validate: value => {
return /^([0-9]|[1-9]\d{1,3}|[1-5]\d{4}|6[0-4]\d{4}|65[0-4]\d{2}|655[0-2]\d|6553[0-5])$/.test(value)
}
})
// 3.用户昵称
Validator.extend('name', {
messages: {
zh_CN: field => '用户昵称不允许特殊符号'
},
validate: value => {
return /^[\u4e00-\u9fa5A-Za-z0-9]*$/.test(value)
}
})
// 4.用户昵称
Validator.extend('phone', {
messages: {
zh_CN: field => '手机号格式不正确'
},
validate: value => {
return /^1[2-9]\d{9}$/.test(value)
}
})
// 5.邮箱
Validator.extend('email', {
messages: {
zh_CN: field => '邮箱格式不正确'
},
validate: value => {
return /^[\w!#$%&'*+/=?^_`{|}~-]+(?:\.[\w!#$%&'*+/=?^_`{|}~-]+)*@(?:[\w](?:[\w-]*[\w])?\.)+[\w](?:[\w-]*[\w])?$/.test(value)
}
})
// 6.验证码
Validator.extend('code', {
messages: {
zh_CN: field => '验证码格式不正确'
},
validate: value => {
return /^[0-9]*$/.test(value)
}
})
// 6.登录密码
Validator.extend('logpwd', {
messages: {
zh_CN: field => '登录密码格式不正确'
},
validate: value => {
return /^\S{6,18}$/.test(value)
}
})
// 7.交易密码
Validator.extend('tradpwd', {
messages: {
zh_CN: field => '交易密码格式不正确'
},
validate: value => {
return /^\S{6,18}$/.test(value)
}
})
// 8.推荐人
Validator.extend('recom', {
messages: {
zh_CN: field => '推荐人格式不正确'
},
validate: value => {
return /^[^\u4e00-\u9fa5]{0,}$/.test(value)
}
})
// 9.用户协议
Validator.extend('see', {
messages: {
zh_CN: field => '请阅读用户协议,并同意'
},
validate: value => {
return true
}
})
// 10.忘记密码,新的登录密码
Validator.extend('npwd', {
messages: {
zh_CN: field => '登录密码格式不正确[6~18位]'
},
validate: value => {
return /^\S{6,18}$/.test(value)
}
})
// 11.忘记密码,确认新的登录密码
Validator.extend('qrwd', {
messages: {
zh_CN: field => '登录密码格式不正确[6~18位]'
},
validate: value => {
return /^\S{6,18}$/.test(value)
}
})
|
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
var ideaController = require('./controllers/ideasController');
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use('/api/ideas', ideaController);
app.listen(process.env.PORT || 3000, () => {
console.log('Server is running');
});
|
import communitiesRequested from 'reducers/landing-page/heat-map/communities-requested';
import { COMMUNITY_REQUEST_START, COMMUNITY_REQUEST_SUCCESS, COMMUNITY_REQUEST_FAILURE } from 'utils/constants';
describe('communitiesRequested reducer', function () {
it('should have initial state', function () {
communitiesRequested(undefined, {}).should.be.false();
});
it('should handle COMMUNITY_REQUEST_START', function () {
communitiesRequested(true, { type: COMMUNITY_REQUEST_START }).should.be.false();
});
it('should handle COMMUNITY_REQUEST_SUCCESS', function () {
communitiesRequested(false, { type: COMMUNITY_REQUEST_SUCCESS }).should.be.true();
});
it('should handle COMMUNITY_REQUEST_FAILURE', function () {
communitiesRequested(false, { type: COMMUNITY_REQUEST_FAILURE }).should.be.true();
});
});
|
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License.
*/
import { registerFetchRoute } from './register_fetch_route';
import { registerGetRoute } from './register_get_route';
import { registerAddPolicyRoute } from './register_add_policy_route';
export function registerTemplatesRoutes(server) {
registerFetchRoute(server);
registerGetRoute(server);
registerAddPolicyRoute(server);
}
|
import Vue from 'vue';
Vue.directive('drag',{
inserted:function(el,binding){
el.onmousedown=function(e){
e.stopPropagation();
let disx = e.pageX - el.offsetLeft;
let disy = e.pageY - el.offsetTop;
document.onmousemove = function (e){
e.preventDefault();
el.style.left = e.pageX - disx+'px';
el.style.top = e.pageY - disy+'px';
}
document.onmouseup = function(){
document.onmousemove = document.onmouseup = null;
//binding 传参,可忽略
if(binding && binding.value){
binding.value.clientX=parseInt(el.style.left);
binding.value.clientY=parseInt(el.style.top);
}
}
}
},
});
|
// THIS FILE IS AUTO GENERATED
var GenIcon = require('../lib').GenIcon
module.exports.HiOutlineDocumentAdd = function HiOutlineDocumentAdd (props) {
return GenIcon({"tag":"svg","attr":{"fill":"none","viewBox":"0 0 24 24","stroke":"currentColor"},"child":[{"tag":"path","attr":{"strokeLinecap":"round","strokeLinejoin":"round","strokeWidth":"2","d":"M9 13h6m-3-3v6m5 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"}}]})(props);
};
|
const defaultTheme = require('tailwindcss/defaultTheme');
module.exports = {
mode: 'jit',
purge: [
'./vendor/laravel/framework/src/Illuminate/Pagination/resources/views/*.blade.php',
'./vendor/laravel/jetstream/**/*.blade.php',
'./storage/framework/views/*.php',
'./resources/views/**/*.blade.php',
'./resources/js/**/*.vue',
],
theme: {
extend: {
fontFamily: {
sans: ['Nunito', ...defaultTheme.fontFamily.sans],
},
},
},
variants: {
opacity: ['responsive', 'hover', 'focus', 'overflow'],
cursor: ['hover'],
},
plugins: [require('@tailwindcss/forms'), require('@tailwindcss/typography')],
};
|
define(["lodash","coreUtilsLib","imageClientLib"],function(e,t,n){return function(e){var t={};function n(i){if(t[i])return t[i].exports;var o=t[i]={i:i,l:!1,exports:{}};return e[i].call(o.exports,o,o.exports,n),o.l=!0,o.exports}return n.m=e,n.c=t,n.d=function(e,t,i){n.o(e,t)||Object.defineProperty(e,t,{configurable:!1,enumerable:!0,get:i})},n.r=function(e){Object.defineProperty(e,"__esModule",{value:!0})},n.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return n.d(t,"a",t),t},n.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},n.p="",n(n.s=83)}([function(t,n){t.exports=e},function(e,n){e.exports=t},function(e,t,n){"use strict";var i=n(0),o=n(1);function r(e){this.migrationMap=e}r.prototype.getComponentData=function(e,t){return t.dataQuery&&e.data.document_data[t.dataQuery.replace("#","")]},r.prototype.setComponentData=function(e,t,n,r){var a=t.dataQuery||i.get(r,[t.id,"dataQuery"])||o.guidUtils.getUniqueId("dataItem","-");a=a.replace("#",""),t.dataQuery="#"+a,n.id=a,e.data.document_data[a]=n,i.set(r,[t.id,"dataQuery"],a)},r.prototype.deleteComponentData=function(e,t){var n=t.dataQuery&&t.dataQuery.replace("#","");n&&e.data.document_data[n]&&delete e.data.document_data[n]},r.prototype.getComponentDesignData=function(e,t){return t.designQuery&&e.data.design_data[t.designQuery.replace("#","")]},r.prototype.deleteComponentDesignData=function(e,t){var n=t.designQuery&&t.designQuery.replace("#","");n&&e.data.design_data[n]&&delete e.data.design_data[n]},r.prototype.getComponentProperties=function(e,t){return t.propertyQuery&&e.data.component_properties[t.propertyQuery.replace("#","")]},r.prototype.deleteComponentProperties=function(e,t){var n=t.propertyQuery&&t.propertyQuery.replace("#","");n&&e.data.component_properties[n]&&delete e.data.component_properties[n],t.propertyQuery&&delete t.propertyQuery},r.prototype.setComponentDesignData=function(e,t,n,r){var a=t.designQuery||i.get(r,[t.id,"designQuery"])||o.guidUtils.getUniqueId("dataItem","-");if(a=a.replace("#",""),t.designQuery="#"+a,n.id=a,i.isObject(n.background)){var s=i.clone(n.background);s.id=(s.id||o.guidUtils.getUniqueId("dataItem","-")).replace("#",""),n.background="#"+s.id,e.data.design_data[s.id]=s}e.data.design_data[a]=n,i.set(r,[t.id,"designQuery"],t.designQuery)},r.prototype.setComponentProperties=function(e,t,n,r){var a=t.propertyQuery||i.get(r,[t.id,"propertyQuery"])||o.guidUtils.getUniqueId("propItem","-");a=a.replace("#",""),t.propertyQuery=a,n.id=a,e.data.component_properties[a]=n,i.set(r,[t.id,"propertyQuery"],a)},r.prototype.migrateComps=function(e,t,n,o){var r=this;i.forEach(o,function(i){r.migrationMap[i.componentType]&&r.migrationMap[i.componentType].call(r,e,t,n,i),r.migrateComps(e,t,n,i.components)})},r.prototype.migratePage=function(e){var t=e.structure;if(t){var n={},i=t.components||t.children,o=t.mobileComponents;i&&this.migrateComps(e,n,!1,i),o&&this.migrateComps(e,n,!0,o)}},e.exports=r},function(e,t,n){"use strict";var i=n(4),o=i.fittingTypes,r=i.alignTypes,a={"repeat-x":o.TILE_HORIZONTAL,"repeat no_repeat":o.TILE_HORIZONTAL,"repeat no-repeat":o.TILE_HORIZONTAL,"repeat-y":o.TILE_VERTICAL,"no_repeat repeat":o.TILE_VERTICAL,"no-repeat repeat":o.TILE_VERTICAL,repeat:o.TILE,"repeat repeat":o.TILE,"":""};Object.freeze(a);var s={auto:function(e){return e||o.LEGACY_ORIGINAL_SIZE},cover:function(){return o.SCALE_TO_FILL},contain:function(e){return e?o.FIT_AND_TILE:o.SCALE_TO_FIT},"":function(){return o.SCALE_TO_FILL}};Object.freeze(s);var c={"center center":r.CENTER,center:r.CENTER,"50% 50%":r.CENTER,"top center":r.TOP,"center top":r.TOP,"50% 0%":r.TOP,"bottom center":r.BOTTOM,"center bottom":r.BOTTOM,"50% 100%":r.BOTTOM,"center right":r.RIGHT,"right center":r.RIGHT,"100% 50%":r.RIGHT,"center left":r.LEFT,"left center":r.LEFT,"0% 50%":r.LEFT,"left top":r.TOP_LEFT,"top left":r.TOP_LEFT,"0% 0%":r.TOP_LEFT,"right top":r.TOP_RIGHT,"top right":r.TOP_RIGHT,"100% 0%":r.TOP_RIGHT,"left bottom":r.BOTTOM_LEFT,"bottom left":r.BOTTOM_LEFT,"0% 100%":r.BOTTOM_LEFT,"right bottom":r.BOTTOM_RIGHT,"bottom right":r.BOTTOM_RIGHT,"100% 100%":r.BOTTOM_RIGHT,"":r.CENTER};Object.freeze(c);var u,p=((u={})[o.LEGACY_STRIP_TILE_HORIZONTAL]="repeat-x",u[o.TILE_HORIZONTAL]="repeat-x",u[o.LEGACY_STRIP_TILE_VERTICAL]="repeat-y",u[o.TILE_VERTICAL]="repeat-y",u[o.LEGACY_STRIP_TILE]="repeat",u[o.TILE]="repeat",u[o.FIT_AND_TILE]="repeat",u[""]="no-repeat",u);Object.freeze(p);var d=function(){var e={};return e[o.LEGACY_ORIGINAL_SIZE]="auto",e[o.LEGACY_STRIP_ORIGINAL_SIZE]="auto",e[o.SCALE_TO_FILL]="cover",e[o.LEGACY_STRIP_SCALE_TO_FILL]="cover",e[o.SCALE_TO_FIT]="contain",e[o.LEGACY_STRIP_SCALE_TO_FIT]="contain",e[o.FIT_AND_TILE]="contain",e[o.LEGACY_STRIP_FIT_AND_TILE]="contain",e[""]="auto",e}();Object.freeze(d);var m=function(){var e={};return e[r.TOP]="center top",e[r.CENTER]="center",e[r.BOTTOM]="center bottom",e[r.TOP_LEFT]="left top",e[r.LEFT]="left center",e[r.BOTTOM_LEFT]="left bottom",e[r.TOP_RIGHT]="right top",e[r.RIGHT]="right center",e[r.BOTTOM_RIGHT]="right bottom",e[""]="center",e}();function l(e){return(e||"").toLowerCase().trim()}Object.freeze(m),e.exports={cssToFittingType:function(e){var t=l(e.bgRepeat),n=l(e.bgSize),i=a[t];return s[n]&&s[n](i)},cssToAlignType:function(e){return e=l(e),c[e]},fittingTypeToBgRepeat:function(e){return p[e]||p[""]},fittingTypeToBgSize:function(e){return d[e]||d[""]},alignTypeToBgPosition:function(e){return m[e]||m[""]},migrateToLegacyFittings:function(e){return e===o.TILE?o.LEGACY_STRIP_TILE:e===o.TILE_HORIZONTAL?o.LEGACY_STRIP_TILE_HORIZONTAL:e===o.TILE_VERTICAL?o.LEGACY_STRIP_TILE_VERTICAL:e===o.SCALE_TO_FILL?o.LEGACY_STRIP_SCALE_TO_FILL:e===o.SCALE_TO_FIT?o.LEGACY_STRIP_SCALE_TO_FIT:e===o.FIT_AND_TILE?o.LEGACY_STRIP_FIT_AND_TILE:e===o.LEGACY_ORIGINAL_SIZE?o.LEGACY_STRIP_ORIGINAL_SIZE:e}}},function(e,t){e.exports=n},function(e,t,n){"use strict";var i=n(0),o={BOTTOM_BOTTOM:"BOTTOM_BOTTOM",BOTTOM_TOP:"BOTTOM_TOP"};function r(e){return e&&e.layout&&e.layout.y+e.layout.height}function a(e){return e.layout&&e.layout.anchors||[]}function s(e){return e.type===o.BOTTOM_BOTTOM||e.type===o.BOTTOM_TOP}e.exports={fixBottomTopBottomBottomCycles:function e(t){if(!i.isEmpty(t)){var n=i.keyBy(t,"id");i.forEach(t,function(t){var c=a(t);i.remove(c,function(e){return s(e)&&function(e,t,n){var a=void 0;switch(e.type){case o.BOTTOM_BOTTOM:a=r(n);break;case o.BOTTOM_TOP:a=i.get(n,"layout.y");break;default:return!1}return!i.isUndefined(a)&&a-r(t)<0}(e,t,n[e.targetComponent])&&function e(t,n,o,r){if(r[n.id])return!1;r[n.id]=!0;var c=a(n);return c=i.filter(c,s),i.some(c,function(n){return n.targetComponent===t.id||e(t,o[n.targetComponent],o,r)})}(t,n[e.targetComponent],n,{})}),e(t.components)})}}}},function(e,t,n){"use strict";var i=n(1);e.exports={createBehaviorsDataItem:function(e){return{id:i.guidUtils.getUniqueId("behavior","-"),type:"ObsoleteBehaviorsList",items:e}}}},function(e,t,n){"use strict";var i=n(0),o=n(1),r=n(82),a=n(80),s=n(79),c=n(77),u=n(75),p=n(74),d=n(73),m=n(72),l=n(71),y=n(70),f=n(69),g=n(67),w=n(66),v=n(65),T=n(64),h=n(63),k=n(62),S=n(61),I=n(60),_=n(59),E=n(58),b=n(57),M=n(56),P=n(55),C=n(54),x=n(53),A=n(52),O=n(51),B=n(50),N=n(49),L=n(48),D=n(47),R=n(46),F=n(45),U=n(44),G=n(43),Q=n(42),H=n(41),V=n(40),z=n(39),W=n(38),q=n(37),Y=n(36),j=n(35),Z=n(34),J=n(33),K=n(32),X=n(31),$=n(30),ee=n(29),te=n(28),ne=n(27),ie=n(26),oe=n(25),re=n(24),ae=n(23),se=n(22),ce=n(21),ue=n(20),pe=n(19),de=n(18),me=n(17),le=n(16),ye=n(15),fe=n(14),ge=n(13),we=n(12),ve=n(11),Te=n(10),he=i.compact([ve,r,s,C,x,A,Y,c,u,p,d,m,l,y,f,Te,g,re,w,v,T,h,k,S,I,a,_,E,b,M,P,ee,O,B,N,L,D,R,F,U,Q,H,V,G,z,W,q,Y,j,Z,J,K,X,$,te,ie,ne,oe,ae,se,ce,ue,pe,de,me,le,ye,fe,ge,we]);Object.freeze(he),e.exports=function(e){var t=e.pageJson,n=e.urlFormatModel,r=e.isViewerMode,a=e.clientSpecMap,s=e.quickActionsMenuEnabled,c=e.experiments,u=e.pageIdsArray,p={};p.isSlash=i.matchesProperty("format",o.siteConstants.URL_FORMATS.SLASH)(n),p.pageIdToResolvedUriSEO=i.get(n,"pageIdToResolvedUriSEO",{}),p.clientSpecMap=a,p.quickActionsMenuEnabled=s,p.isExperimentOpen=function(e){return i.includes(c,e)},p.isViewerMode=r;var d=t.data||{};return d.document_data=d.document_data||{},d.theme_data=d.theme_data||{},d.component_properties=d.component_properties||{},d.mobile_hints=d.mobile_hints||{},t.data=d,i.forEach(he,function(e){e.exec(t,u,null,null,null,null,null,p)}),t}},function(e,t,n){"use strict";var i=n(0),o=n(1),r=n(3),a=o.imageClientApi;function s(e){var t="";for(e=e||[];i.includes(e,t);)t=i.random(0,99999).toString(36).replace(" ","_");return t}function c(e){var t=i.compact(e.split(" "));return u.apply(this,t)}function u(e,t,n,i,o,s,c,u,p,d,m,l){var y=r.cssToAlignType(i+" "+o),f=r.cssToFittingType({bgRepeat:c+" "+u,bgSize:s});return f=function(e){var t={};return t[a.fittingTypes.TILE]=a.fittingTypes.LEGACY_BG_FIT_AND_TILE,t[a.fittingTypes.TILE_HORIZONTAL]=a.fittingTypes.LEGACY_BG_FIT_AND_TILE_HORIZONTAL,t[a.fittingTypes.TILE_VERTICAL]=a.fittingTypes.LEGACY_BG_FIT_AND_TILE_VERTICAL,t[a.fittingTypes.ORIGINAL_SIZE]=a.fittingTypes.LEGACY_BG_NORMAL,t[e]||e}(f),m=m||{},d&&"none"!==d||(d="rgba(0,0,0,0)"),{type:"BackgroundMediaUnified",alignType:y,fittingType:f,attachment:p,imageWidth:Number(t),imageHeight:Number(n),mediaType:"image",uri:e,color:d,metaData:{isHidden:m.isHidden||!1,isPreset:m.isPreset||!1,schemaVersion:2},id:l}}function p(e){var t=[e.url,e.imagesizew,e.imagesizeh,e.positionx,e.positiony,e.width,e.repeatx,e.repeaty,e.attachment,e.color,e.metaData,e.id];return u.apply(this,t)}e.exports={fixBackgroundData:function(e){var t=e.getPageDataMap(e.MASTER_PAGE_ID,e.dataTypes.THEME),n=e.getPageDataMap(e.MASTER_PAGE_ID,e.dataTypes.DATA),o=i(n).filter({type:"BackgroundImage"}).map("id").value();(function(e){var t=i.find(e,{type:"Page"});return e[t.id].pageBackgrounds&&"BackgroundMediaUnified"===e[t.id].pageBackgrounds.type})(n)||(function(e){var t=i.find(e,{type:"Page"});return!e[t.id].pageBackgrounds}(n)?function(e,t){var n=i(t).filter({type:"Page"}).map("id").value(),o=e.THEME_DATA.siteBg||"none 0 0 center center auto repeat repeat scroll none",r=("[siteBg]"===e.THEME_DATA.mobileBg?e.THEME_DATA.siteBg:e.THEME_DATA.mobileBg)||"none 0 0 center center auto repeat repeat scroll none",a=c(o),u=c(r);a.id="customBgImg"+s(),u.id="customBgImg"+s([a.id]),t[a.id]=a,t[u.id]=u,i.forEach(n,function(e){t[e].pageBackgrounds={desktop:{custom:!0,isPreset:!1,ref:"#"+a.id},mobile:{custom:!0,isPreset:!1,ref:"#"+u.id}}})}(t,n):i.forEach(o,function(e){p(n[e])}))},migrateBgDataItem:p,migrateBgString:c}},function(e,t,n){"use strict";var i=n(0),o=n(1),r=n(7);function a(e){switch(e){case"wysiwyg.viewer.components.WSiteStructure":return"Document";case"mobile.core.components.Page":return"Page";case"wixapps.integration.components.Area":case"mobile.core.components.Container":case"wysiwyg.viewer.components.HeaderContainer":case"wysiwyg.viewer.components.FooterContainer":case"wysiwyg.viewer.components.PagesContainer":case"wysiwyg.viewer.components.ScreenWidthContainer":case"wysiwyg.viewer.components.StripContainer":return"Container"}return"Component"}function s(e){return parseInt(e||0,10)}e.exports=function(e){e.pagesData={};var t=i.get(e,"wixData.document_data.SITE_STRUCTURE.mainPage")||i.get(e,"wixData.document_data.masterPage.mainPage"),n=t&&t.slice(1);e.pagesData.masterPage={data:e.wixData},e.pagesData.masterPage.structure={};var c={page:"masterPage",childrenIndex:{}};o.htmlParser(e.wixHtmlRaw,{start:function(e,t,n,o,r){var c=i(o).map("name").invokeMap("toLowerCase").zipObject(i.map(o,"value")).value();"Page"===a(c.comp)&&(t.page=c.id),e.pagesData[t.page]=e.pagesData[t.page]||{structure:{},data:{},theme_data:{}};var u=e.pagesData[t.page].structure=e.pagesData[t.page].structure||{};if(i.has(t.childrenIndex,t.page)){for(var p=0;p<t.childrenIndex[t.page].length;p++)u=u.components[t.childrenIndex[t.page][p]];var d={};t.childrenIndex[t.page].push(u.components.length),u.components.push(d),u=d}else t.childrenIndex[t.page]=[];u.componentType=c.comp,u.type=a(c.comp),u.id=c.id,u.components=[],u.skin=c.skin,u.styleId=c.styleid,c.dataquery&&(u.dataQuery=c.dataquery),u.propertyQuery=c.propertyquery,u.layout={width:s(c.width),height:s(c.height),x:s(c.x),y:s(c.y),anchors:e.wixAnchors[c.id]||[]}}.bind(void 0,e,c),end:function(e,t,n){0===t.childrenIndex[t.page].length?t.page="masterPage":t.childrenIndex[t.page].pop()}.bind(void 0,e,c)});var u=i.keys(e.pagesData),p=i.without(u,"masterPage");e.pagesData.masterPage.data.document_data.MAIN_MENU=e.pagesData.masterPage.data.document_data.MAIN_MENU||{items:[],type:"Menu",id:"MAIN_MENU",metaData:{}},i.forEach(u,function(t){e.pagesData[t]=r(e.pagesData[t],p,e.requestModel,e.currentUrl,e.urlFormatModel)}),e.publicModel.pageList={mainPageId:n,pages:i.map(p,function(t){return i.chain(e).get(["pagesData","masterPage","data","document_data",t]).pick(["title","pageUriSEO"]).assign({pageId:t}).value()})}}},function(e,t,n){"use strict";var i=n(0),o=["screenIn"];function r(e){var t;return t=e,i.includes(o,t.action)&&!i.isUndefined(t.delay)&&i.isUndefined(i.get(t,["params","doubleDelayFixed"]))&&i.merge(e,{delay:2*parseFloat(e.delay),params:{doubleDelayFixed:!0}}),e}e.exports={exec:function(e,t,n,o,a,s,c,u){var p=e.data.behaviors_data;u.isExperimentOpen("sv_fix_animation_delay")&&!i.isEmpty(p)&&function(e){i.forEach(e,function(e){if(i.isString(e.items)){var t=JSON.parse(e.items),n=i.map(t,r);e.items=JSON.stringify(n)}})}(p)}}},function(e,t,n){"use strict";var i=n(0),o=function(e,t){return i.get(e,["data","document_data",function(e){return i.get(e,["dataQuery"],"").replace("#","")}(t),"widgetId"])},r=function(e){return i.set(e,["layout","width"],320)};e.exports={exec:function(e){var t=i.get(e,["structure","mobileComponents"]);i(t).filter({componentType:"wysiwyg.viewer.components.tpapps.TPAMultiSection"}).filter(function(e){return function(t){return i.includes(["144f04b9-aab4-fde7-179b-780c11da4f46","14fd5970-8072-c276-1246-058b79e70c1a"],o(e,t))}}(e)).forEach(r)}}},function(e,t,n){"use strict";var i=n(0),o=n(1),r=function(e){return"wysiwyg.viewer.components.HoverBox"===e.componentType};e.exports={exec:function(e){var t=o.dataUtils.getAllCompsInStructure(e.structure,!1,r),n=o.dataUtils.getAllCompsInStructure(e.structure,!0,r);i.forEach(t,function(t,o){var r=n[o];if(r){var a=i.get(r,["propertyQuery"]),s=i.get(e,["data","component_properties",a,"mobileDisplayedModeId"]),c=i.findIndex(i.get(r,["modes","definitions"]),{modeId:s});i.set(r,["modes","definitions"],i.get(t,["modes","definitions"]));var u=i.get(t,["modes","definitions",c,"modeId"]);i.set(e,["data","component_properties",a,"mobileDisplayedModeId"],u)}})}}},function(e,t,n){"use strict";var i=n(2),o=n(1);function r(e,t,n,i){if(!i.designQuery&&!n){i.layout.width=980;var r={type:"MediaContainerDesignData",id:o.guidUtils.getUniqueId("dataItem","-"),background:{id:o.guidUtils.getUniqueId("dataItem","-"),type:"BackgroundMedia",mediaRef:null,alignType:"center",fittingType:"fill",colorOpacity:0,colorOverlay:"",colorOverlayOpacity:1,imageOverlay:"",scrollType:"none",color:"#FFFFFF"}};this.setComponentDesignData(e,i,r,t)}}var a=new i({"wysiwyg.viewer.components.StripColumnsContainer":r,"wysiwyg.viewer.components.Column":r});e.exports={exec:a.migratePage.bind(a)}},function(e,t,n){"use strict";var i=n(0);var o=new(n(2))({"wysiwyg.viewer.components.Column":function(e,t,n,o){n&&i.startsWith(o.designQuery,"#mobile_")&&(this.deleteComponentDesignData(e,o),o.designQuery=i.replace(o.designQuery,"mobile_",""))}});e.exports={exec:o.migratePage.bind(o)}},function(e,t,n){"use strict";var i=n(0),o=n(2);function r(e,t,n,o){var r=e.data.document_data[o.dataQuery.slice(1)],a=e.data.component_properties,s=a[o.propertyQuery];if(i.has(s,"dataSource")){var c={type:s.dataSource.type,revision:s.dataSource.id};delete s.dataSource;var u="mobile_"+o.propertyQuery;i.has(a,u)&&delete a[u].dataSource,i.set(r,"dataSource",c)}}e.exports={exec:function(e){new o({"wysiwyg.viewer.components.Grid":r}).migratePage(e)}}},function(e,t,n){"use strict";var i=n(0),o=n(2),r="-semi",a="wysiwyg.viewer.components.tpapps.TPAWidget";function s(e,t,n,o,s){var c=function(e){return i(e).filter("appFields.platform").reduce(function(e,t){return i(t.widgets).pickBy(["componentFields.semiNative",!0]).mapValues(i.constant(!0)).assign(e).value()},{})}(e),u=this.getComponentData(t,s);s.componentType===a&&c[u.widgetId]&&(s.componentType="platform.components.semiNativeComponent",s.skin="wysiwyg.viewer.skins.semiNativeComponentSkin",s.styleId+=r,this.setComponentData(t,s,i.defaults({type:"SemiNative"},u),n))}e.exports={exec:function(e,t,n,a,c,u,p,d){if(d.isExperimentOpen("sv_migrateTpaToSemiNative")&&d.isViewerMode){"masterPage"===e.structure.id&&function(e){var t=i(e.data.theme_data).filter({componentClassName:"wysiwyg.viewer.components.tpapps.TPAWidget",skin:"wysiwyg.viewer.skins.TPAWidgetSkin"}).map(function(e){var t=i.cloneDeep(e);return t.componentClassName="platform.components.semiNativeComponent",t.skin="wysiwyg.viewer.skins.semiNativeComponentSkin",t}).transform(function(e,t){e[t.id+r]=t},{}).value();i.assign(e.data.theme_data,t)}(e);var m={"wysiwyg.viewer.components.tpapps.TPAWidget":i.partial(s,d.clientSpecMap)};new o(m).migratePage(e)}}}},function(e,t,n){"use strict";var i=n(0),o=n(1).vectorImageConversionUtils,r={"wysiwyg.viewer.components.VectorImageArt":o.vectorImageDefaults,"wysiwyg.viewer.components.VectorImageShape":o.vectorImageDefaults},a=o.convertStyle,s=o.convertStructure;function c(e){i.forEach(e,function(e){var t=r[e.componentType];t&&s(e,t),e.components&&c(e.components)})}e.exports={exec:function(e){var t=e.data.theme_data,n=e.structure.components||e.structure.children,o=e.structure.mobileComponents;i.isEmpty(t)||function(e){i.forEach(e,function(e){var t=r[e.componentClassName];t&&a(e,t)})}(t),i.isEmpty(n)||c(n),i.isEmpty(o)||c(o)}}},function(e,t,n){"use strict";var i,o,r,a=n(0),s=n(1).vectorImageConversionUtils,c="wysiwyg.viewer.components.PopupCloseIconButton",u="wysiwyg.viewer.components.svgshape.SvgShape",p=(i={},o=u,r=s.vectorImageDefaults,o in i?Object.defineProperty(i,o,{value:r,enumerable:!0,configurable:!0,writable:!0}):i[o]=r,i),d="wysiwyg.viewer.components.Repeater",m=s.convertStyle,l=s.convertData,y=s.convertProperties,f=s.convertStructure;function g(e,t,n,i){a.forEach(e,function(e){if(e.components)e.componentType===d&&(!function(e,t,n){var i=t[a.get(e,"dataQuery","").replace("#","")];g(e.components,t,n,a.get(i,"items"))}(e,t,n),i=[]),g(e.components,t,n,i);else{var o=p[e.componentType];if(o){var r=e.skin,s=a.get(e,"propertyQuery","").replace("#",""),c=a.get(e,"dataQuery","").replace("#","");n[s]||(n[s]={});var u=t[c],m=n[s];f(e,o),l(u,o,r),y(m,o),a.forEach(a.get(e,["modes","overrides"]),function(e){if(e.propertyQuery){var t=a.get(e,"propertyQuery","").replace("#","");n[t]||(n[t]={});var i=n[t];y(i,o)}}),a.forEach(i,function(n){var i=t[a.get(e,"dataQuery","").replace("#","")+"__"+n];i&&l(i,o,r)})}}})}e.exports={exec:function(e){var t=e.data.theme_data,n=e.data.document_data,i=e.data.component_properties,o=e.structure.components||e.structure.children,r=e.structure.mobileComponents,s=[];a.isEmpty(t)||function(e){a.forEach(e,function(e){if(a.includes(e.skin,"svgshape")&&e.componentClassName!==c){var t=p[u];m(e,t)}})}(t),a.isEmpty(o)||g(o,n,i,s),a.isEmpty(r)||g(r,n,i,s)}}},function(e,t,n){"use strict";var i=n(0),o=["wysiwyg.viewer.skins.mobile.TinyMenuSkin","wysiwyg.viewer.skins.mobile.TinyMenuFullScreenSkin","wysiwyg.viewer.skins.mobile.TinyMenuPullFromLeftSkin","wysiwyg.viewer.skins.mobile.TinyMenuPullFromTopSkin","wysiwyg.viewer.skins.mobile.TinyMenuPullFromRightSkin"],r="wysiwyg.viewer.skins.mobile.TinyMenuSkin",a="tm2";e.exports={exec:function(e){if("masterPage"===i.get(e,["structure","id"])){var t=function e(t){var n=i.find(t,{id:"TINY_MENU"});return n||(i.forEach(t,function(t){if(!i.isEmpty(t.components))return!(n=e(t.components))}),n)}(e.structure.mobileComponents);t&&!function(e,t){var n=i.get(t,[e.styleId,"skin"]),r=e.skin;return n&&r&&i.includes(o,n)&&i.includes(o,r)}(t,e.data.theme_data)&&function(e){e.skin=r,e.styleId=a}(t)}}}},function(e,t,n){"use strict";var i=n(0);e.exports={exec:function(e){var t=e.data.component_properties;i.isEmpty(t)||function(e){i.forEach(e,function(e){"WPhotoProperties"===e.type&&e.effectName&&(e.filterEffect||"none"===e.effectName||(e.filterEffect={effectType:e.effectName}),delete e.effectName)})}(t)}}},function(e,t,n){"use strict";var i=n(0),o="wysiwyg.viewer.components.tpapps.TPASection",r="14724f35-6794-cd1a-0244-25fd138f9242",a="1489040e-001f-4631-55a9-2c29b4417126",s={left:{vw:0},right:{vw:0}};function c(e,t){!function(e,t){!0===function(e){if(e){var t=e.widgets[a];return i.get(t,"shouldBeStretchedByDefaultMobile")}return null}(e)&&(i.set(t.layout,"dock",s),10===t.layout.y&&(t.layout.y=0))}(t,function(e){var t=[].concat(i.get(e,"structure.mobileComponents"));for(;t.length>0;){var n=t.shift();if(n&&n.componentType===o)return n;n.components&&(t=t.concat(n.components))}}(e))}e.exports={exec:function(e,t,n,o,s,u,p,d){var m=void 0,l=i.get(d,"clientSpecMap"),y=d.isExperimentOpen("sv_tpaSectionsMobileFSDataFixer"),f=function(e){var t=i.find(e,{appDefinitionId:r});return i.get(t,"applicationId")}(l);if(f&&y){var g=i.get(l,f);if("masterPage"===i.get(e,"structure.id")){var w=i.get(e,"data.document_data");(m=i.find(w,{tpaApplicationId:f}))&&function(e,t){var n=t.widgets[a];!0===i.get(n,"appPage.landingPageInMobile")&&(e.isMobileLandingPage=!0)}(m,g)}else{m=i.get(e,["data","document_data"]),i.find(m,{applicationId:f.toString(),type:"TPA"})&&c(e,g)}}}}},function(e,t,n){"use strict";var i=n(0),o=n(1);function r(e){return"Image"===e.type}function a(e,t){return"undefined"!==t&&"null"!==t&&e.length>1}e.exports={exec:function(e){var t=i.get(e,["data","document_data"]);t&&i(t).pickBy(r).groupBy("originalImageDataRef").pickBy(a).forOwn(function(e,n){var r=i.tail(e),a=n.replace("#","");i.forEach(r,function(e){var n=function(e,t){var n=t+"_"+o.guidUtils.getUniqueId(),r=i.cloneDeep(e[t]);return r.id=n,r}(t,a);t[n.id]=n,e.originalImageDataRef="#"+n.id})})}}},function(e,t,n){"use strict";var i=n(0),o=n(1),r={exec:function(e){i.forEach(e.data.document_data,function(e){e.appPartName&&e.appPartName===o.blogAppPartNames.FEED&&r.fixMobileDateCustomization(e)})},fixMobileDateCustomization:function(e){i.forEach(e.appLogicCustomizations,function(e){"date"===e.fieldId&&"Mobile"===e.format&&"Post"===e.forType&&"comp.hidden"===e.key&&(e.fieldId="dateAndAuthor")})}};e.exports=r},function(e,t,n){"use strict";var i=n(0);function o(e){return i.find(e.structure.mobileComponents,{id:"QUICK_ACTION_BAR"})}function r(e){o(e).propertyQuery="quickActionBarProps",i.assign(e.data.component_properties,{quickActionBarProps:{type:"QuickActionBarProperties",metaData:{isPreset:!1,schemaVersion:"1.0",isHidden:!1},colorScheme:"brand",invertColors:!0,alignment:"right",hideText:!0}})}function a(e){return!!o(e)}e.exports={exec:function(e,t,n,s,c,u,p,d){if("masterPage"===e.structure.id){var m,l;if(i(e.data.document_data).filter(function(e){return"QuickActionBarItem"===e.type&&i.isString(e.text)}).forEach(function(e){e.text=e.text.slice(0,40)}),a(e))return function(e){var t=i.find(e.structure.mobileComponents,{id:"QUICK_ACTION_BAR"});i.isUndefined(t.components)&&(t.components=[]),t.type="Container",i.isUndefined(e.data.component_properties[t.propertyQuery])&&r(e)}(e),void function(e){var t=i.find(e.structure.mobileComponents,{id:"QUICK_ACTION_BAR"}),n=i.get(e.data.theme_data,[t.styleId,"style","properties"]);i.transform(["controlButtonBorderColor","actionsBorderColor"],function(e,t){/^rgb/.test(e[t])&&(e[t]="#ffffff")},n)}(e);!(m=d.clientSpecMap,l=i.find(m,{appDefinitionId:"14517e1a-3ff0-af98-408e-2bd6953c36a2"}),i.isUndefined(l)||i.get(l,"permissions.revoked")||a(e)||d.quickActionsMenuEnabled)&&(!function(e){e.structure.mobileComponents.push({type:"Container",id:"QUICK_ACTION_BAR",componentType:"wysiwyg.viewer.components.QuickActionBar",components:[],styleId:"quickActionBarStyle",layout:{fixedPosition:!0}})}(e),function(e){o(e).styleId="quickActionBarStyle",i.assign(e.data.theme_data,{quickActionBarStyle:{type:"TopLevelStyle",id:"quickActionBarStyle",metaData:{isPreset:!1,schemaVersion:"1.0",isHidden:!1},skin:"wysiwyg.viewer.skins.quickActionBar.floatingSkin",style:{properties:{"alpha-controlButtonBG":"1","alpha-controlButtonFG":"1","alpha-controlButtonBorderColor":"1","alpha-actionsBorderColor":"1","boxShadowToggleOn-actionsSHD":"true","boxShadowToggleOn-controlButtonSHD":"true",controlButtonBG:"#ffffff",controlButtonFG:"#4682b4",controlButtonBorderSize:"0",controlButtonBorderColor:"#ffffff",actionsBorderSize:"0",actionsBorderColor:"#ffffff",colorScheme:"brand inv",controlButtonSHD:"0px 1px 4px 0px rgba(0,0,0,0.6)",actionsSHD:"0px 1px 4px 0px rgba(0,0,0,0.6)"},propertiesSource:{controlButtonBG:"value",controlButtonFG:"value",controlButtonBorderSize:"value",controlButtonBorderColor:"value",actionsBorderSize:"value",actionsBorderColor:"value",colorScheme:"value",controlButtonSHD:"value",actionsSHD:"value"},groups:{}},componentClassName:"wysiwyg.viewer.components.QuickActionBar",pageId:"",compId:"",styleType:"custom"}})}(e),r(e))}}}},function(e,t,n){"use strict";var i=n(0),o=n(1);e.exports={exec:function(e){i(e.data.document_data).filter({type:"AppPart",appPartName:o.blogAppPartNames.SINGLE_POST}).forEach(function(e){var t=i.find(e.appLogicCustomizations,{forType:"Post",fieldId:"vars",key:"selectionSharerExperimentOpen",view:e.viewName});t||(t={forType:"Post",fieldId:"vars",key:"selectionSharerExperimentOpen",view:e.viewName,type:"AppPartCustomization",format:""},e.appLogicCustomizations.push(t))})}}},function(e,t,n){"use strict";var i=n(0);e.exports={exec:function(e){var t=i.get(e,["data","component_properties",e.structure.id]);t&&t.popup&&(i.forEach(["desktop","mobile"],function(e){var n=t[e],o=t.popup[e];(n||o)&&i.set(t,[e,["popup"]],i.assign(n||{},o||{}))}),delete t.popup)}}},function(e,t,n){"use strict";var i=n(0);e.exports={exec:function(e){return e.structure&&"Document"===e.structure.type&&i.isEmpty(e.data.document_data.masterPage.characterSets)&&(e.data.document_data.masterPage.characterSets=["latin"]),e}}},function(e,t,n){"use strict";var i=n(0);e.exports={exec:function(e){var t=e.data.document_data;i.isEmpty(t)||function(e){i.forEach(e,function(e){"LoginToWixLink"!==e.type&&"HomePageLogin"!==e.type||function(e){e.metaData&&"2.0"===e.metaData.schemaVersion||(e.sendMail=!0)}(e)})}(t)}}},function(e,t,n){"use strict";var i=n(0),o=n(1);function r(e){return"wysiwyg.viewer.components.StripContainer"===e.componentType}function a(e){return!i.isUndefined(e.designQuery)}function s(e,t,n){return t[n]=e[n],delete e[n],t[n]}function c(e,t,n,r,a){var c=a.dataQuery.slice(1),u=function(e,t,n){return i.isUndefined(n)&&(n=o.guidUtils.getUniqueId("dataItem","-")),t[n]={id:n,type:"MediaContainerDesignData",metaData:{isPreset:!1,schemaVersion:"1.0",isHidden:!1}},e.designQuery="#"+n,n}(a,t);n[c]=u;var p=function(e,t,n,o){var r=n[e];if(!i.isUndefined(r.background)){var a=r.background.slice(1),c=s(n,o,a);if(!i.isUndefined(c.mediaRef)){var u=s(n,o,c.mediaRef.slice(1));"WixVideo"===u.type&&s(n,o,u.posterImageRef.slice(1)),i.isUndefined(u.originalImageDataRef)||s(n,o,u.originalImageDataRef.slice(1)),i.isUndefined(u.link)||delete u.link}return i.isUndefined(c.imageOverlay)||s(n,o,c.imageOverlay.slice(1)),delete r.background,o[t].background="#"+a,a}}(c,u,e,t);i.isUndefined(p)||(r[c]=p)}function u(e,t,n,i){var o=i.dataQuery.slice(1);i.designQuery="#"+t[o]}function p(e){return i.isUndefined(e.components)?i.isUndefined(e.children)?[]:e.children:e.components}function d(e){for(var t=i.clone(e)||[],n=[];t.length>0;){var o=t.pop();n.push(o);var r=p(o);i.forEach(r,function(e){t.push(e)})}return n}e.exports={exec:function(e){var t=function(e){return d(p(e.structure))}(e),n=function(e){return d(e.structure.mobileComponents)}(e);e.data.design_data=e.data.design_data||{},function(e,t,n,o){var s={},p={},d=i.filter(e,r);i(d).reject(a).forEach(i.partial(c,n,o,p,s)),i(t).filter(function(e){return r(e)&&!a(e)}).forEach(i.partial(u,o,p,s))}(t,n,e.data.document_data,e.data.design_data)}}},function(e,t,n){"use strict";var i=n(0);e.exports={exec:function(e){"masterPage"===i.get(e,["structure","id"])&&function e(t){var n=i.find(t,{id:"TINY_MENU"});return n?(n.layout.fixedPosition&&n.layout.x>320&&(n.layout.x=250),!0):i.some(t,function(t){return!i.isEmpty(t.components)&&e(t.components)})}(e.structure.mobileComponents)}}},function(e,t,n){"use strict";var i=n(0),o="wysiwyg.viewer.skins.mobile.TinyMenuSkin";function r(e){if(e.skin===o&&!i.isUndefined(e.style)&&!i.isUndefined(e.style.properties)){var t=e.style.properties,n=e.style.propertiesSource;i.forEach([["bg","bgDrop"],["bg","bgOpen"],["txt","bordercolor"],["txt","iconcolor"],["bordercolor","borderColorSelected"]],function(e){var i=e[0],o=e[1];r(t,i,o),r(n,i,o),r(t,i="alpha-"+i,o="alpha-"+o),r(n,i,o)})}function r(e,t,n){i.isUndefined(e)||i.isUndefined(e[t])||(e[n]=e[n]||e[t])}}e.exports={exec:function(e){var t=e.data&&e.data.theme_data;i.isEmpty(t)||i.forEach(t,r)}}},function(e,t,n){"use strict";var i=n(0),o=n(2),r=n(1);var a=new o({"wysiwyg.viewer.components.StripContainer":function(e,t,n,o){o.componentType="wysiwyg.viewer.components.StripColumnsContainer",delete o.skin,o.styleId="strc1",this.setComponentProperties(e,o,{columnsMargin:0,frameMargin:0,fullWidth:!0,rowMargin:0,siteMargin:0,type:"StripColumnsContainerProperties"},t);var a=function(e,t){return{id:i.get(t,[e.id,"mediaId"],r.guidUtils.getUniqueId("media")),type:"Container",layout:{width:e.layout.width,height:e.layout.height,x:0,y:0,scale:1,rotationInDegrees:0,anchors:[{distance:0,topToTop:0,originalValue:0,type:"BOTTOM_PARENT",locked:!0,targetComponent:e.id}],fixedPosition:!1},components:e.components,componentType:"wysiwyg.viewer.components.Column",styleId:"strc1"}}(o,t);if(function(e,t){i.forEach(e.components,function(e){var n=i.get(e,["layout","anchors"],[]);i.forEach(n,function(e){"BOTTOM_PARENT"===e.type&&(e.targetComponent=t.id)})})}(o,a),function(e,t){e.behaviors&&(t.behaviors=i.clone(e.behaviors),delete e.behaviors),e.behaviorQuery&&(t.behaviorQuery=e.behaviorQuery,delete e.behaviorQuery)}(o,a),i.set(t,[o.id,"mediaId"],a.id),this.setComponentProperties(e,a,{type:"ColumnProperties",alignment:50},t),a.designQuery=o.designQuery,delete o.designQuery,n)o.layout.width=320,o.designQuery=i.get(t,[o.id,"designQuery"]),this.deleteComponentData(e,o);else{o.layout.width=980;var s={type:"MediaContainerDesignData",id:r.guidUtils.getUniqueId("dataItem","-"),background:{id:r.guidUtils.getUniqueId("dataItem","-"),type:"BackgroundMedia",mediaRef:null,alignType:"center",fittingType:"fill",colorOpacity:0,colorOverlay:"",colorOverlayOpacity:1,imageOverlay:"",scrollType:"none",color:"#FFFFFF"}};this.setComponentDesignData(e,o,s,t)}delete o.dataQuery,o.components=[a]}});e.exports={exec:a.migratePage.bind(a)}},function(e,t,n){"use strict";var i=n(0),o=i.matchesProperty(["structure","type"],"Page");e.exports={exec:function(e,t,n,r,a,s,c,u){i.get(u,"isSlash")&&!o(e)&&i.forEach(u.pageIdToResolvedUriSEO,function(t,n){e.data.document_data[n].pageUriSEO=t.curr})}}},function(e,t,n){"use strict";var i=n(0),o=["RichText","Text","StyledText","MediaRichText"];e.exports={exec:function(e){var t=e.data.document_data;t&&i(t).pickBy(function(e){return i.includes(o,e.type)}).mapValues(function(e){var t;return e.text=(t=e.text)&&t.replace(/(<object[^>]*>)(.*?)(<\/object>)/gi,""),e.text=function(e){return e&&e.replace(/<img[^>]*(onerror|onload|onmouseenter|onmousemove|onmouseleave|onmouseover|onmouseup|onmouseout)[^>]*\/?>(<\/img>)?/gi,"")}(e.text),e}).value()}}},function(e,t,n){"use strict";var i=n(0),o="wysiwyg.viewer.components.Group",r="wysiwyg.viewer.components.GroupSkin";function a(e){i.forEach(e,function(e){var t;(t=e).componentType===o&&(t.skin=r),a(e.components)})}e.exports={exec:function(e){var t=e.structure;if(t){var n=t.components||t.children,i=t.mobileComponents;n&&a(n),i&&a(i)}}}},function(e,t,n){"use strict";var i=n(0);e.exports={exec:function(e){(function(e){return"Page"===i.get(e,"structure.type")})(e)&&function(e){i(e.data.document_data).filter({type:"Page"}).map("id").forEach(function(t){delete e.data.document_data[t]})}(e),function(e){i.forEach(e.data.document_data,function(e){"#SITE_STRUCTURE"===e.pageId&&(e.pageId="#masterPage")})}(e)}}},function(e,t,n){"use strict";var i=n(0),o={type:"ContactFormProperties",hidden_emailFieldLabel:!0,hidden_nameFieldLabel:!0,hidden_phoneFieldLabel:!1,hidden_addressFieldLabel:!1,hidden_subjectFieldLabel:!0,hidden_messageFieldLabel:!0,required_emailFieldLabel:!0,required_nameFieldLabel:!0,required_phoneFieldLabel:!1,required_addressFieldLabel:!1,required_subjectFieldLabel:!1,required_messageFieldLabel:!1,useCookie:!0},r={nameFieldLabel:{type:"string",default:"Name"},emailFieldLabel:{type:"string",default:"Email"},phoneFieldLabel:{type:"string",default:"Phone"},addressFieldLabel:{type:"string",default:"Address"},subjectFieldLabel:{type:"string",default:"Subject"},messageFieldLabel:{type:"string",default:"Message"},submitButtonLabel:{type:"string",default:"Send"},successMessage:{type:"string",default:"Your details were sent successfully!"},errorMessage:{type:"string",default:"Please provide a valid email"},textDirection:{type:"string",default:"left",enum:["left","right"]},validationErrorMessage:{type:"string",default:"Please fill in all required fields."},onSubmitBehavior:{type:"string",default:"message",enum:["message","link"]}},a={skinPrefix:"contactform.",fields:["name","email","subject","phone","address","message"]},s={skinPrefix:"wysiwyg.viewer.skins.contactform.",fields:["name","email","phone","address","subject","message"]},c="DynamicContactForm",u="wysiwyg.viewer.components.ContactForm",p="wysiwyg.viewer.components.DynamicContactForm";function d(e){return(e||"").replace("#","")}function m(e){var t,n=this,m=d(e.dataQuery),l=d(e.propertyQuery),y=this.pageJson.data.document_data[m],f=function(e,t,n){return!i.has(n.data.component_properties,t)&&e.componentType===u}(e,l,this.pageJson)?o:this.pageJson.data.component_properties[l];(i.unset(e,"propertyQuery"),i.set(e,"componentType",p),t=y,i.has(t,"dynamicFields")&&i.get(t,"type")===c)||(i.assign(this.pageJson.data.document_data[m],{type:c,dynamicFields:function(e,t,n){var o=i.startsWith(e,a.skinPrefix)?a.fields:s.fields;return i.reduce(o,function(e,o){var a=o+"FieldLabel",s=n["hidden_"+a];if(s){var c=function(e){switch(e){case"email":return{fieldType:"email",fieldInputType:"email"};case"phone":return{fieldType:"phone",fieldInputType:"tel"};default:return{fieldType:e,fieldInputType:"text"}}}(o);e.push({name:c.fieldType,inputType:c.fieldInputType,displayLabel:t[a]||i.get(r[a],"default"),required:n["required_"+a],isDisplayed:s})}return e},[])}(e.skin,y,f)}),["name","email","subject","phone","address","message"].forEach(function(e){i.unset(n.pageJson.data.document_data,[m,e+"FieldLabel"])}),i.unset(this.pageJson.data.component_properties,l))}function l(e){var t=this;e&&i.forEach(e,function(e){e.componentType===u&&m.call(t,e),e.componentType===p&&function(e){var t=d(e.propertyQuery);i.unset(e,"propertyQuery"),i.unset(this.pageJson.data.component_properties,[t])}.call(t,e),l.call(t,e.components)})}e.exports={exec:function(e,t,n,o,r,a,s,c){var u=e.structure;if(function(e,t){var n=e.isExperimentOpen;return(n("sv_contactFormTemplatesMigration")||n("sv_contactFormFinalMigration")||n("sv_contactFormFinalMigrationEditor"))&&!!t}(c,u)){var p=i.concat([],u.components||u.children,u.mobileComponents||[]);l.call({pageJson:e},p)}}}},function(e,t,n){"use strict";var i=n(0),o=n(1),r={};r[o.blogAppPartNames.FEED]=["MediaBottomPage","MediaLeftPage","MediaRightPage","MediaTopPage","MediaZigzagPage"],r[o.blogAppPartNames.POSTS_LIST]=["PostsList","PostsListMediaLeft"],r[o.blogAppPartNames.TICKER]=["TickerMediaBottom","TickerMediaTop"],e.exports={exec:function(e){i(e.data.document_data).filter(function(e){return"AppPart"===e.type&&i.includes([o.blogAppPartNames.FEED,o.blogAppPartNames.POSTS_LIST,o.blogAppPartNames.TICKER],e.appPartName)}).forEach(function(e){i(e.appLogicCustomizations).filter(function(t){return"date"===t.fieldId&&"Post"===t.forType&&!t.format&&"comp.format"===t.key&&i.includes(r[e.appPartName],t.view)}).forEach(function(e){e.format="*"})})}}},function(e,t,n){"use strict";var i=n(0),o=n(1),r=null;e.exports={exec:function(e){i.isNull(r)&&(r=[],i.forEach(e.data.theme_data,function(e,t,n){i.matches({componentClassName:"wysiwyg.viewer.components.SiteButton",skin:"wysiwyg.viewer.skins.AppPartSkin"})(e)&&(r.push(t),delete n[t])}),setTimeout(function(){r=null})),i(e.data.document_data).filter(function(e){return"AppPart"===e.type&&i.includes(o.blogAppPartNames,e.appPartName)}).forEach(function(e){i.remove(e.appLogicCustomizations,function(e){return"comp.style"===e.key&&i.includes(r,e.value)})})}}},function(e,t,n){"use strict";var i=n(0),o=n(1);function r(e){return"Post"===e.forType&&"layout.spacerBefore"===e.key&&"date"===e.fieldId&&i.includes(["MediaTop","MediaBottom","MediaLeft","MediaRight","MediaZigzag","Masonry","MediaTopPage","MediaBottomPage","MediaLeftPage","MediaRightPage","MediaZigzagPage","MasonryPage","SinglePostMediaBottom","SinglePostMediaTop"],e.view)}e.exports={exec:function(e){i(e.data.document_data).filter(function(e){return"AppPart"===e.type&&i.includes([o.blogAppPartNames.CUSTOM_FEED,o.blogAppPartNames.FEED,o.blogAppPartNames.SINGLE_POST],e.appPartName)}).forEach(function(e){i(e.appLogicCustomizations).filter(r).forEach(function(e){i.assign(e,{fieldId:"vars",key:"dateAndAuthorPosition",value:"0"===e.value?"left":"right"})})})}}},function(e,t,n){"use strict";var i=n(0),o=n(1);function r(e){return"Post"===e.forType&&"comp.hidden"===e.key&&("date"===e.fieldId||"author"===e.fieldId)&&i.includes(["MediaTop","MediaBottom","MediaLeft","MediaRight","MediaZigzag","Masonry","MediaTopPage","MediaBottomPage","MediaLeftPage","MediaRightPage","MediaZigzagPage","MasonryPage","SinglePostMediaBottom","SinglePostMediaTop"],e.view)}e.exports={exec:function(e){i(e.data.document_data).filter(function(e){return"AppPart"===e.type&&i.includes([o.blogAppPartNames.CUSTOM_FEED,o.blogAppPartNames.FEED,o.blogAppPartNames.SINGLE_POST],e.appPartName)}).forEach(function(e){i(e.appLogicCustomizations).filter(r).forEach(function(e){i.assign(e,{fieldId:"dateAndAuthor"})})})}}},function(e,t,n){"use strict";var i=n(0),o=n(1);function r(e){return"Array"===e.forType&&"comp.itemsPerPage"===e.key&&i.includes(["","*"],e.format)&&i.includes(["paginatedlist","columnBlog"],e.fieldId)&&i.includes(["MediaTop","MediaBottom","MediaLeft","MediaRight","MediaZigzag","Masonry"],e.view)}e.exports={exec:function(e){i(e.data.document_data).filter({type:"AppPart",appPartName:o.blogAppPartNames.CUSTOM_FEED}).forEach(function(e){i(e.appLogicCustomizations).filter(r).forEach(function(e){i.assign(e,{fieldId:"vars",format:"*",key:"itemsPerPage"})})})}}},function(e,t,n){"use strict";var i=n(0);e.exports={exec:function(e){i(e.data.document_data).filter({type:"AppPart"}).forEach(function(e){for(var t,n,o=e.appLogicCustomizations,r=o.length,a={};r;){var s=(t=o[r-=1],void 0,n=i.omit(t,"value"),JSON.stringify(n));a[s]?o.splice(r,1):a[s]=!0}})}}},function(e,t,n){"use strict";var i=n(0);e.exports={exec:function(e){i(e.data.document_data).filter({type:"AppPart"}).forEach(function(e){i(e.appLogicCustomizations).filter({fieldId:"tagsValue",forType:"Post",format:"",key:"value",view:"SinglePostMediaTop"}).forEach(function(e){e.format="*"})})}}},function(e,t,n){"use strict";var i=n(0),o=n(1),r={exec:function(e){e.data&&i(e.data.document_data).filter(function(e){return e.type===r.getAppPartType()&&i.includes(r.getBlogFeedAppPartNames(),e.appPartName)}).forEach(function(e){var t=e.appLogicCustomizations;i(t).compact().filter(function(e){return e.fieldId===r.getReadMoreValueCustomizationFieldId()&&e.key===r.getReadMoreValueCustomizationKey()&&""===e.format&&i.includes(r.getAffectedReadMoreValueCustomizationViews(),e.view)}).forEach(function(e){i.remove(t,{fieldId:e.fieldId,format:"*",key:e.key,view:e.view}),e.format="*"})})},getAppPartType:function(){return"AppPart"},getBlogFeedAppPartNames:function(){return[o.blogAppPartNames.FEED,o.blogAppPartNames.CUSTOM_FEED]},getReadMoreValueCustomizationFieldId:function(){return"ReadMoreBtn"},getReadMoreValueCustomizationKey:function(){return"value"},getAffectedReadMoreValueCustomizationViews:function(){return["MediaLeft","MediaLeftPage","MediaRight","MediaRightPage","MediaZigzag","MediaZigzagPage","Masonry","MasonryPage"]}};e.exports=r},function(e,t,n){"use strict";var i=n(0),o=n(1),r={exec:function(e){e.data&&e.data.document_data&&i(e.data.document_data).filter(function(e){return r.isAppPartType(e.type)}).forEach(function(e){i(e.appLogicCustomizations).compact().groupBy("view").filter(function(e,t){return o.appPartMediaInnerViewNameUtils.isMediaInnerViewName(t)}).forEach(function(e){i(e).groupBy("fieldId").filter(function(e){return i.isEqual(i.map(e,"format"),[""])}).forEach(function(e){i.forEach(e,function(e){e.format="*"})})})})},isAppPartType:function(e){return"AppPart"===e}};e.exports=r},function(e,t,n){"use strict";var i=n(0);function o(e){var t=function(e){var t=i.findKey(e,function(e){return e.appPageId&&"7326bfbb-4b10-4a8e-84c1-73f776051e10"===e.appPageId});if(!t)return null;var n=i.findKey(e,function(e){return e.pageId&&e.pageId==="#"+t});return i.findKey(e,function(e){return e.link&&e.link==="#"+n})}(e);t&&function(e,t){var n=e.CUSTOM_MAIN_MENU&&e.CUSTOM_MAIN_MENU.items;i.forEach(n,function(n){var o=e[n.replace("#","")].items,r=i.indexOf(o,t);if(-1!==r)return o.splice(r,1),e.CUSTOM_MAIN_MENU.items.push(t),!1})}(e,"#"+t)}e.exports={exec:function(e){return e.structure&&"Document"===e.structure.type&&o(e.data.document_data),e}}},function(e,t,n){"use strict";var i=n(0);function o(e){e.urlChoice=i.includes(e.urlChoice,"pinterest.com")?e.urlChoice:"www.pinterest.com/"+e.urlChoice}e.exports={exec:function(e){return i(e.data.document_data).pickBy({type:"PinterestFollow"}).mapValues(o).value()}}},function(e,t,n){"use strict";var i=n(0);e.exports={exec:function(e){if("Page"===e.structure.type){var t=e.structure.components,n=e.data.document_data;i.forEach(t,function(e){if(i.includes(e.componentType,"DocumentMedia")){var t=e.dataQuery,o=n[t.replace("#","")];0===o.uri.indexOf("media/")&&(o.uri=o.uri.replace("media/",""))}})}return e}}},function(e,t,n){"use strict";var i=new(n(2))({"wysiwyg.viewer.components.StripContainerSlideShowSlide":function(e,t,n,i){i.layout.y=0}});e.exports={exec:i.migratePage.bind(i)}},function(e,t,n){"use strict";var i=n(0),o=n(6),r=["wysiwyg.viewer.components.StripContainer","wysiwyg.viewer.components.StripContainerSlideShowSlide"],a={fixed:{action:"bgScrub",name:"BackgroundReveal",duration:1,delay:0},parallax:{action:"bgScrub",name:"BackgroundParallax",duration:1,delay:0}};function s(e,t){var n=i.get(t,[e.behaviorQuery,"items"],"[]");return JSON.parse(n)}function c(e,t){return t[t[e.designQuery.replace("#","")].background.replace("#","")]}function u(e,t,n){i.forEach(e,function(e){!function(e,t,n){var u=void 0;if(i.includes(r,e.componentType)){var p=c(e,t),d=p.scrollType;if(p.scrollType="none","scroll"!==d&&"none"!==d){u=s(e,n),(u=i.reject(u,{name:"ContainerFixedBg",action:"bgScrub"})).push(a[d]);var m=JSON.stringify(u);if(e.behaviorQuery)i.set(n,[e.behaviorQuery,"items"],m);else{var l=o.createBehaviorsDataItem(m);i.set(n,l.id,l),e.behaviorQuery=l.id}}}}(e,t,n),e.components&&u(e.components,t,n)})}function p(e,t,n){i.forEach(e,function(e){!function(e,t,n){var o=void 0;i.includes(r,e.componentType)&&(c(e,t).scrollType="none",o=s(e,n),o=i.reject(o,{name:"ContainerFixedBg",action:"bgScrub"}),i.isEmpty(o)?(delete e.behaviors,delete e.behaviorQuery):i.set(n,[e.behaviorQuery,"items"],JSON.stringify(o)))}(e,t,n),e.components&&p(e.components,t,n)})}e.exports={exec:function(e){var t=e.structure;if(t){var n=e.data.design_data,i=e.data.behaviors_data;t.components&&u(t.components,n,i),t.children&&u(t.children,n,i),t.mobileComponents&&p(t.mobileComponents,n,i)}}}},function(e,t,n){"use strict";var i=n(0);function o(e,t,n,o,r){if(0!==e[t].indexOf("#"+o)){var a,s,c=i.cloneDeep(r[e[t].replace("#","")]),u=function(e,t,n){return e+"_"+t+"_"+n}(o,n,t);s=c,r[a=u]=i.assign({id:a},i.omit(s,"id")),e[t]="#"+u}}function r(e,t,n){var i=n[t.pageBackgrounds[e].ref.replace("#","")],r=void 0;i&&i.mediaRef&&("WixVideo"===(r=n[i.mediaRef.replace("#","")]).type&&o(r,"posterImageRef",e,t.id,n),i.imageOverlay&&o(i,"imageOverlay",e,t.id,n),o(i,"mediaRef",e,t.id,n))}e.exports={exec:function(e){if(e.structure){var t=e.data.document_data,n=i.filter(t,function(e){return"Page"===e.type||"AppPage"===e.type});i.forEach(n,function(e){!function(e,t){e.pageBackgrounds&&(r("mobile",e,t),r("desktop",e,t))}(e,t)})}}}},function(e,t,n){"use strict";var i=n(0),o=n(1),r={alignType:"center",color:"{color_11}",fittingType:"fill",scrollType:"scroll",type:"BackgroundMedia"},a={pageBackgrounds:{desktop:{custom:!0,isPreset:!0,ref:null},mobile:{custom:!0,isPreset:!0,ref:null}}};function s(e,t){return o.guidUtils.getUniqueId(t.id,"_")+e}function c(e,t){t[e]=i.assign({id:e},r)}e.exports={exec:function(e){if(e.structure){var t,n,o=e.data.document_data;i.some(o,{type:"BackgroundMedia"})&&(t=o,n=i.filter(t,function(e){return"Page"===e.type||"AppPage"===e.type}),i.forEach(n,function(e){var n=void 0;i.defaults(e,a),e.pageBackgrounds.mobile.ref||(c(n=s("_mobile_bg",e),t),e.pageBackgrounds.mobile.ref="#"+n),e.pageBackgrounds.desktop.ref||(c(n=s("_desktop_bg",e),t),e.pageBackgrounds.desktop.ref="#"+n)}))}}}},function(e,t,n){"use strict";var i=n(0),o=n(3),r=n(1),a=n(4),s="BackgroundImage",c="bgImage",u="mediaBg",p="-";function d(e,t){var n=i.filter(e,function(e){return"Page"===e.type||"AppPage"===e.type}),o=i.map(n,"id");i.some(n,function(e){return e.pageBackgrounds&&e.pageBackgrounds.desktop.ref})?m(e):function(e,t,n,o){var a=f(t),s=f(n);i.forEach(o,function(t){var n=r.guidUtils.getUniqueId(u,p),i=r.guidUtils.getUniqueId(u,p),o=n.replace(u,c),d=i.replace(u,c);y(e,a,t,n,o,"desktop"),y(e,s,t,i,d,"mobile")})}(e,t.siteBg,t.mobileBg&&"[siteBg]"!==t.mobileBg?t.mobileBg:t.siteBg,o)}function m(e){var t=i.filter(e,{type:s});i.forEach(t,function(t){!function(e,t){var n=t.id,i=r.guidUtils.getUniqueId(c+p),o=function(e){return w(g.apply(this,[e.url,e.imagesizew,e.imagesizeh,e.positionx,e.positiony,e.width,e.repeatx,e.repeaty,e.attachment,e.color,e.metaData]))}(t);l(e,o,n,i)}(e,t)})}function l(e,t,n,o){e[n]=i.assign({id:n},t.bgItem),t.imageItem&&(e[n].mediaRef="#"+o,e[o]=i.assign({id:o},t.imageItem))}function y(e,t,n,i,o,r){e[n].pageBackgrounds=e[n].pageBackgrounds||{desktop:"",mobile:""},e[n].pageBackgrounds[r]={ref:"#"+i,custom:!0,isPreset:!1},l(e,t,i,o)}function f(e){return w(g.apply(this,i.compact(e.split(" "))))}function g(e,t,n,i,o,r,a,s,c,u,p){return{imageId:e,imageW:t,imageH:n,x:i,y:o,width:r,repeatX:a,repeatY:s,attachment:c,color:u,metaData:{isPreset:(p=p||{}).isPreset||!1,schemaVersion:"2.0",isHidden:p.isHidden||!1}}}function w(e){var t={bgItem:{}},n="rgb(255,255,255)",i=o.cssToAlignType(e.x+" "+e.y),r=o.cssToFittingType({bgRepeat:e.repeatX+" "+e.repeatY,bgSize:e.width}),s="fixed"===e.attachment?"fixed":"scroll";return r=function(e){var t={};return t[a.fittingTypes.TILE]=a.fittingTypes.LEGACY_BG_FIT_AND_TILE,t[a.fittingTypes.TILE_HORIZONTAL]=a.fittingTypes.LEGACY_BG_FIT_AND_TILE_HORIZONTAL,t[a.fittingTypes.TILE_VERTICAL]=a.fittingTypes.LEGACY_BG_FIT_AND_TILE_VERTICAL,t[a.fittingTypes.LEGACY_ORIGINAL_SIZE]=a.fittingTypes.LEGACY_BG_NORMAL,t[e]||e}(r),e.color&&"none"!==e.color&&(n=e.color),e.imageId&&"none"!==e.imageId&&(t.imageItem={type:"Image",uri:e.imageId,width:parseInt(e.imageW,10),height:parseInt(e.imageH,10),metaData:{isPreset:!1,schemaVersion:"1.0",isHidden:!1}}),t.bgItem={type:"BackgroundMedia",color:n,alignType:i,fittingType:r,scrollType:s,metaData:e.metaData},t}function v(e){var t=i.compact(e.split(" ")),n=g.apply(this,t).color;return n&&(n=(n=n.replace("[","{")).replace("]","}"),t[9]=n),t.join(" ")}e.exports={exec:function(e){if(e.structure){var t=e.data.theme_data&&e.data.theme_data.THEME_DATA,n=e.data.document_data,o=i.some(n,{type:"BackgroundMedia"}),r=i.some(n,{type:s});if(!o||r)"Document"===e.structure.type?(!function(e){e.siteBg=v(e.siteBg),e.mobileBg&&"[siteBg]"!==e.mobileBg&&(e.mobileBg=v(e.mobileBg))}(t),d(n,t)):m(n)}}}},function(e,t,n){"use strict";var i=n(0),o={faq:{filterAppPart:{appPartName:"f2c4fc13-e24d-4e99-aadf-4cff71092b88",viewName:"ExpandQuestions"},filterAppLogicCustomization:{type:"AppPartCustomization",forType:"Category",view:"ToggleMobile",key:"comp.initialState",fieldId:"toggle",format:"Mobile"},modify:function(e){return i.assign(e,{fieldId:"vars",key:"initialState"})}}};e.exports={exec:function(e){i(o).values().forEach(function(t){i(e.data.document_data).filter(t.filterAppPart).forEach(function(e){e.appLogicCustomizations=i(e.appLogicCustomizations).map(function(e){return i.find([e],t.filterAppLogicCustomization)?t.modify(e):e}).compact().value()})})}}},function(e,t,n){"use strict";var i=n(0),o=n(3),r={BgImageStripProperties:function(e){e.fittingType=o.cssToFittingType({bgSize:e.bgSize,bgRepeat:e.bgRepeat}),e.fittingType=o.migrateToLegacyFittings(e.fittingType),e.alignType=o.cssToAlignType(e.bgPosition),e.type="BgImageStripUnifiedProperties",delete e.bgSize,delete e.bgRepeat,delete e.bgPosition,delete e.bgUrl}};e.exports={exec:function(e){var t=e.data.component_properties;i.isEmpty(t)||function(e){i.forEach(e,function(e){var t=r[e.type];t&&t(e)})}(t)}}},function(e,t,n){"use strict";var i=n(0),o="14271d6f-ba62-d045-549b-ab972ae1f70e",r="144f04b9-aab4-fde7-179b-780c11da4f46",a="fullscreen_page",s="non_existing_style_id",c="wysiwyg.viewer.components.tpapps.TPAMultiSection";function u(e,t,n){var o=i.get(e,"pageBackgrounds."+n+".ref");o=i.replace(o,"#","");var r=i.get(t,["data","document_data",o]);r&&i.merge(r,{type:"BackgroundMedia",color:"transparent",alignType:"center",fittingType:"fill",scrollType:"none",mediaRef:null})}function p(e,t){if("masterPage"===i.get(e,"structure.id")){var n=i.get(e,"data.document_data"),o=i.find(n,{tpaApplicationId:t,tpaPageId:a});o&&(u(o,e,"desktop"),u(o,e,"mobile"))}else!function(e){var t=i.get(e,["structure","components"]),n=i.find(t,{componentType:c});if(n){var o=n.dataQuery.replace("#",""),a=i.get(e,["data","document_data",o,"widgetId"]);a===r&&(e.structure.styleId=s)}}(e)}e.exports={exec:function(e,t,n,r,c,d,m,l){var y,f,g=(y=l.clientSpecMap,f=i.find(y,{appDefinitionId:o}),i.get(f,"applicationId"));g&&(l.isViewerMode?function(e,t){var n=i.get(e,"structure.id"),o=i.get(e,["data","document_data",n]),r=i.get(o,"tpaPageId"),c=i.get(o,"tpaApplicationId");r===a&&c===t&&(u(o,e,"desktop"),u(o,e,"mobile"),e.structure.styleId=s)}(e,g):l.isExperimentOpen("se_proGalleryBGDataFixer")&&p(e,g))}}},function(e,t,n){"use strict";var i=n(0),o=n(1),r="wysiwyg.viewer.components.tpapps.TPAGluedWidget",a="14517e1a-3ff0-af98-408e-2bd6953c36a2",s="14517f3f-ffc5-eced-f592-980aaa0bbb5c",c="masterPage",u={lastGeneratedId:void 0,counter:0};function p(e,t){var n=i.find(e,{appDefinitionId:a});if(n){var r=l(t,n.applicationId);if(i.forEach(r,function(e){var r=e.data,a=i.keys(n.widgets);i.toString(r.applicationId)===i.toString(n.applicationId)&&i.includes(a,r.widgetId)||function(e,t,n){var i=o.guidUtils.getUniqueId("dataItem","-");t.dataQuery="#"+i,n.id=i,e.data.document_data[i]=n}(t,e.comp,i.assign(r,{applicationId:i.toString(n.applicationId),widgetId:s}))}),!function(e){return!0===i.get(e,"permissions.revoked")}(n)&&!r.length){var c=i.get(n,"widgets."+s),u=y("comp","-"),p=y("dataItem","-"),m=y("propItem","-"),f=d(u,p,m,c);t.structure.children.push(f),t.data.document_data[p]=function(e,t){return{type:"TPAWidget",id:t,metaData:{isPreset:!1,schemaVersion:"1.0",isHidden:!1},applicationId:i.toString(e.applicationId),widgetId:s}}(n,p),t.data.component_properties[m]=function(e){return{type:"TPAGluedProperties",metaData:{schemaVersion:"1.0"},placement:i.get(e,"gluedOptions.placement"),verticalMargin:i.get(e,"gluedOptions.verticalMargin"),horizontalMargin:i.get(e,"gluedOptions.horizontalMargin")}}(c),t.data.theme_data[f.styleId]||(t.data.theme_data[f.styleId]={type:"TopLevelStyle",styleType:"system",compId:"",componentClassName:"wysiwyg.viewer.components.tpapps.TPAGluedWidget",pageId:"",skin:"wysiwyg.viewer.skins.TPAWidgetSkin",style:{groups:{},properties:{},propertiesSource:{}},id:f.styleId,metaData:{isPreset:!1,schemaVersion:"1.0",isHidden:!1}})}}}function d(e,t,n,o,r){return{type:"Component",styleId:r||"tpagw0",id:e,dataQuery:"#"+t,skin:"wysiwyg.viewer.skins.TPAWidgetSkin",layout:{width:i.get(o,"defaultWidth")||320,height:i.get(o,"defaultHeight")||250,x:i.get(o,"x")||0,y:i.get(o,"y")||0,scale:1,rotationInDegrees:0,fixedPosition:i.get(o,"fixedPosition")||!0},propertyQuery:n,componentType:"wysiwyg.viewer.components.tpapps.TPAGluedWidget"}}function m(e,t,n,i){return d(e,t=v(t),n=v(n),{x:10,y:10,width:0,height:5,fixedPosition:!1},i)}function l(e,t){return i(e.structure.children).filter(function(n){if(!n.dataQuery)return!1;var o=e.data.document_data[n.dataQuery.replace("#","")];return i.get(o,"widgetId")===s||i.toString(i.get(o,"applicationId"))===i.toString(t)}).map(function(t){return{comp:t,data:e.data.document_data[t.dataQuery.replace("#","")]}}).value()}function y(e,t){return function(e,t,n,i){t=t||"",n=n||"";var o=i;o===e.lastGeneratedId?e.counter++:(e.lastGeneratedId=o,e.counter=0);return t+n+Number(e.lastGeneratedId).toString(36)+(e.counter||"")}(u,e,t,Date.now())}function f(e,t){var n=i.find(t,{appDefinitionId:a}),o=l(e).length>0;e&&e.structure.id===c&&n&&!i.get(n,"permissions.revoked")&&o&&g(e.data,e.structure.children,n)&&!g(e.data,e.structure.mobileComponents,n)&&function(e,t){var n=e.structure.mobileComponents,o=i.find(n,{id:"SITE_FOOTER"}),r=t.dataQuery,a=t.propertyQuery,s=t.styleId;o&&i.isArray(o.components)?o.components.push(m(t.id,r,a,s)):n.push(m(t.id,r,a,s))}(e,w(e.data.document_data,e.structure.children,n))}function g(e,t,n){return!!w(e.document_data,t,n)}function w(e,t,n){for(var o=[].concat(t);!i.isEmpty(o);){var a=o.shift();if(a.componentType===r){var s=e[v(a.dataQuery)];if(Number(s.applicationId)===Number(n.applicationId))return a}i.isEmpty(a.components)||(o=o.concat(a.components))}return null}function v(e){return e&&"#"===e[0]?e.substr(1):e}e.exports={exec:function(e,t,n,o,r,a,s,u){var d=i.get(u,"clientSpecMap");if("masterPage"===e.structure.id){p(d,e);var m=i.get(u,"quickActionsMenuEnabled");i.get(e,"structure.id")!==c||m||f(e,d)}}}},function(e,t,n){"use strict";var i=n(0),o="wysiwyg.viewer.components.tpapps.TPAGluedWidget";e.exports={exec:function(e){"masterPage"===i.get(e,"structure.id")&&function(e){i.forEach(e.structure.children,function(e){e.componentType===o&&(e.layout.fixedPosition=!0)})}(e)}}},function(e,t,n){"use strict";e.exports={exec:function(e){var t=e.data;t.document_data.THEME_DATA&&(t.theme_data.THEME_DATA||(t.theme_data.THEME_DATA=t.document_data.THEME_DATA),delete t.document_data.THEME_DATA)}}},function(e,t,n){"use strict";var i=n(0),o=n(1);e.exports={exec:function(e){var t={toFix:["FlashComponent","SiteButton","Image"],newNames:["LinkableFlashComponent","LinkableButton","Image"],originalLink:["TextLink","Link"]},n=["href","text","target","icon","linkType"],r={oldValues:["same","other"],newValues:["_self","_blank"]};function a(t,n){var a=(t.linkType||"").toLowerCase(),c=n?function(){var t=i.keys(e.data.document_data),n=void 0;do{n=(n=(new Date).getTime().toString(36)+"_"+Math.round(99999*Math.random()).toString(36)).replace(/\s/g,"_")}while(t[n]);return n}():t.id;switch(a){case"page":return function(e,t){var n={};n.id=e,n.type="PageLink";var i=t.href;if(!i)return null;var o=i.lastIndexOf("/");o<0&&(o=i.lastIndexOf("|"));return i=i.substr(o+1),n.pageId=s(i),n}(c,t);case"website":return function(e,t){var n={};n.id=e,n.type="ExternalLink",n.target=function(e){var t=void 0,n=i.indexOf(r.oldValues,e);t=i.includes(r.newValues,e)?e:-1!==n?r.newValues[n]:r.newValues[1];return t}(t.target);var o=t.href;if(!o)return null;return n.url=o,n}(c,t);case"email":return function(e,t){var n={};n.id=e,n.type="EmailLink";var i=t.href;if(!i||!i.toLowerCase)return null;o.stringUtils.startsWith(i,"mailto:",!0)&&(i=i.substr("mailto:".length));var r=i.split("?");if(n.recipient=r[0],r[1]){var a=function(e){var t={},n=/([^&=]+)=([^&]*)/g,i=void 0;for(;i=n.exec(e);)t[i[1]]=i[2];return t}(r[1]);a.subject&&(n.subject=a.subject),a.body&&(n.body=a.body)}return n}(c,t);case"document":return function(e,t){var n={},i=void 0;n.type="DocumentLink",n.id=e;var o=t.href;if(!o)return null;var r=(i=o.substr(o.lastIndexOf("/")+1)).indexOf("?dn=");-1!==r&&(i=i.substring(0,r));return n.docId=i,n.name=t.text,n}(c,t);case"login":return function(e,t){var n={};n.id=e,n.type="LoginToWixLink";var i=t.text;i&&o.stringUtils.startsWith(i,"{")&&(i=JSON.parse(i),n.postLoginUrl=i.postLoginUrl,n.postSignupUrl=i.postSignupUrl,n.dialog=i.type);return n}(c,t);case"admin_login":case"free_link":case"":default:return null}}function s(e){return e?e&&o.stringUtils.startsWith(e,"#")?e:"#"+e:null}var c,u=e.data.document_data,p={},d=void 0;c=u,d=i.filter(c,function(e){var n=!(e.type===t.toFix[2])||"2.0"!==e.metaData.schemaVersion;return!e.link&&i.includes(t.toFix,e.type)&&n}),i.forEach(d,function(e){var o=function(e){var o=i.indexOf(t.toFix,e.type),r=t.newNames[o],c=i.defaults({type:r},i.omit(e,n)),u=a(e,!0);return u&&(c.link=s(u.id),p[u.id]=u),e.type===c.type&&(c.metaData.schemaVersion="2.0"),c}(e);o&&(u[e.id]=o)}),d=function(e){return i.filter(e,function(e){return e.linkType&&i.includes(t.originalLink,e.type)})}(u),i.forEach(d,function(e){var t=a(e);t&&(u[e.id]=t)}),i.assign(u,p)}}},function(e,t,n){"use strict";var i=n(0);function o(e){i.isEmpty(e.components)||(e.components=[])}function r(e){e.layout&&(e.layout.y=0)}e.exports={exec:function(e){if(e.structure&&"Document"===e.structure.type){var t=function(e){var t=void 0;if(e.structure.children){var n=i.find(e.structure.children,{id:"PAGES_CONTAINER"});n&&!i.isEmpty(n.components)&&(t=i.find(n.components,{id:"SITE_PAGES"}))}return t}(e),n=function(e){var t=void 0;if(e.structure.mobileComponents){var n=i.find(e.structure.mobileComponents,{id:"PAGES_CONTAINER"});n&&!i.isEmpty(n.components)&&(t=i.find(n.components,{id:"SITE_PAGES"}))}return t}(e);t&&(o(t),r(t)),n&&(o(n),r(n))}return e}}},function(e,t,n){"use strict";var i=n(0);function o(e){if(!e.rotationInDegrees)return e.height;var t=e.rotationInDegrees*Math.PI/180;return parseInt(Math.abs(e.width*Math.sin(t))+Math.abs(e.height*Math.cos(t)),10)}function r(e){if(!e.rotationInDegrees)return e.y;var t=o(e);return parseInt(e.y-(t-e.height)/2,10)}function a(e){return i.maxBy(e,function(e){return r(e.layout)})}function s(e){if(e&&!i.isEmpty(e)&&((n=e).length&&n[0].layout&&n[0].layout.anchors)){var t=function(e){var t={};return i.forEach(e,function(e){switch(e.id){case"SITE_HEADER":return t.header=e,!(t.footer&&t.pagesContainer);case"SITE_FOOTER":return t.footer=e,!(t.header&&t.pagesContainer);case"PAGES_CONTAINER":return t.pagesContainer=e,!(t.header&&t.footer);default:return!0}}),t}(e);!function(e){var t=e.pagesContainer,n=e.header;t&&n&&(i.remove(t.layout.anchors,{targetComponent:"SITE_HEADER",type:"TOP_TOP"}),i.remove(n.layout.anchors,{targetComponent:"PAGES_CONTAINER",type:"TOP_TOP"}))}(t),function(e,t){var n=t.pagesContainer,s=t.header,c=t.footer,u=n&&n.components&&i.find(n.components,{id:"SITE_PAGES"});if(!u||!u.layout||u.layout.anchors&&0!==u.layout.anchors.length||(u.layout.anchors=[{distance:0,locked:!0,originalValue:0,targetComponent:"PAGES_CONTAINER",type:"BOTTOM_PARENT"}]),n&&n.layout&&(!n.layout.anchors||0===n.layout.anchors.length)&&c&&c.layout&&!c.layout.fixedPosition&&(n.layout.anchors=[{distance:10,locked:!0,originalValue:0,targetComponent:"SITE_FOOTER",type:"BOTTOM_TOP"}]),s&&!i.find(e,function(e){return i.find(e.layout.anchors,{type:"BOTTOM_PARENT",targetComponent:"masterPage"})})){var p=a(e);if(!p.layout.anchors)return;p.layout.anchors.push({distance:0,locked:!0,originalValue:r(p.layout)+o(p.layout)+(s?o(s.layout):0),targetComponent:"masterPage",type:"BOTTOM_PARENT"})}}(e,t)}var n}e.exports={exec:function(e){var t=e.structure;t&&"Document"===t.type&&(s(t.children),s(t.mobileComponents))},test:{getBoundingHeight:o,getBoundingY:r,getLowestComp:a}}},function(e,t,n){"use strict";var i=n(0),o=n(5),r={"wysiwyg.common.components.anchor.viewer.Anchor":!0,"wysiwyg.common.components.subscribeform.viewer.SubscribeForm":!0,"wysiwyg.common.components.pinitpinwidget.viewer.PinItPinWidget":!0,"wysiwyg.common.components.singleaudioplayer.viewer.SingleAudioPlayer":!0,"wixapps.integration.components.AppPart":!0,"wixapps.integration.components.AppPart2":!0,"wixapps.integration.components.common.minipart":!0,"wysiwyg.common.components.onlineclock.viewer.OnlineClock":!0,"wysiwyg.common.components.weather.viewer.Weather":!0,"wysiwyg.common.components.skypecallbutton.viewer.SkypeCallButton":!0,"wysiwyg.common.components.spotifyfollow.viewer.SpotifyFollow":!0,"wysiwyg.common.components.spotifyplayer.viewer.SpotifyPlayer":!0,"wysiwyg.common.components.youtubesubscribebutton.viewer.YouTubeSubscribeButton":!0,"wysiwyg.viewer.components.ContactForm":!0,"wysiwyg.viewer.components.FacebookShare":!0,"wysiwyg.viewer.components.FiveGridLine":!0,"wysiwyg.viewer.components.FlickrBadgeWidget":!0,"wysiwyg.viewer.components.ItunesButton":!0,"wysiwyg.viewer.components.LinkBar":!0,"wysiwyg.viewer.components.PayPalButton":!0,"wysiwyg.viewer.components.PinterestFollow":!0,"wysiwyg.viewer.components.VKShareButton":!0,"wysiwyg.viewer.components.WFacebookComment":!0,"wysiwyg.viewer.components.WGooglePlusOne":!0,"wysiwyg.viewer.components.mobile.TinyMenu":!0},a={"wysiwyg.common.components.backtotopbutton.viewer.BackToTopButton":!0,"wysiwyg.viewer.components.tpapps.TPAGluedWidget":!0,"mobile.core.components.Page":!0,"wixapps.integration.components.AppPage":!0};function s(e){a[e.componentType]&&(e.layout.anchors=[])}function c(e){return e.layout&&e.layout.y+e.layout.height}function u(e){return e.layout&&e.layout.anchors||[]}function p(e,t,n){if("BOTTOM_TOP"===e.type){var o=u(n[e.targetComponent]);i.remove(o,{targetComponent:t.id});var r=i.filter(o,{type:"TOP_TOP"}),a=c(t)+10;i.forEach(r,function(e){n[e.targetComponent]&&function e(t,n,o,r,a){if(!(a[t.id]||c(t)>o)){a[t.id]=!0;var s=u(t);i.remove(s,function(t){if(t.targetComponent===n.id)return!0;if("BOTTOM_PARENT"!==t.type){if(!r[t.targetComponent])return!0;e(r[t.targetComponent],n,o,r,a)}return!1})}}(n[e.targetComponent],t,a,n,{})})}}function d(e,t,n){var o=t.id,s=n[e.targetComponent];if("BOTTOM_PARENT"===e.type&&(s=e.targetComponent===o?t:null),!s)return!1;if("BOTTOM_BOTTOM"===e.type&&r[s.componentType])return!1;if("BOTTOM_PARENT"!==e.type&&(a[s.componentType]||"wysiwyg.viewer.components.HeaderContainer"===s.componentType&&s.layout&&!0===s.layout.fixedPosition))return!1;var c,u,p,d,m=void 0;if(s.layout&&i.isNumber(s.layout.height)&&i.isNumber(s.layout.y)){var l=s.layout,y=(c=l.height,u=l.width,p=l.rotationInDegrees,d=(p||0)*Math.PI/180,parseInt(Math.abs(u*Math.sin(d))+Math.abs(c*Math.cos(d)),10)),f=function(e,t,n){return parseInt(e-(n-t)/2,10)}(l.y,l.height,y);m="BOTTOM_PARENT"===e.type||"BOTTOM_BOTTOM"===e.type?y:f}else m=0;return e.originalValue=Math.min(e.originalValue,m),!0}function m(e,t){return function(e,t){t&&s(e)}(e,t),function e(t,n){var o=n?t[n]:t.components;if(i.isEmpty(o))return;var r=i.transform(o,function(e,t){e[t.id]=t},{});!function(e){i.forEach(e,function(t){var n=u(t);n=i.reject(n,{type:"BOTTOM_PARENT"}),i.remove(n,function(t){return!i.some(e,{id:t.targetComponent})})})}(o);i.forEach(o,function(n){var o=u(n);!function(e){i.remove(e,function(e){return null===e.distance||isNaN(e.distance)})}(o),s(n),function(e,t){"Document"===e.type&&i.forEach(t,function(e){"SITE_STRUCTURE"===e.targetComponent&&(e.targetComponent="masterPage")})}(t,o),function(e,t,n){t=i.reject(t,{type:"BOTTOM_PARENT"}),i.forEach(t,function(t){var o=n[t.targetComponent];if(o){var r=i.filter(u(o),{targetComponent:e.id,type:t.type});i.forEach(r,function(n){var r=e.layout.y<o.layout.y?o:e,a=e.layout.y<o.layout.y?n:t;i.remove(r.layout.anchors,function(e){return e===a})})}})}(n,o,r),i.remove(o,function(e){!function(e){"TOP_TOP"===e.type&&(e.locked=!0)}(e);var i=d(e,t,r);return i&&p(e,n,r),!i}),e(n)})}(e,t)}function l(e){var t=i.head(e);return!!i.get(t,"layout.anchors")}e.exports={exec:function(e){var t=e.structure,n="components";t&&("Document"===t.type&&((t=i.clone(e.structure)).id="masterPage",e.structure=t,n="children"),l(t[n])&&m(t,n),l(t.mobileComponents)&&(m(t,"mobileComponents"),o.fixBottomTopBottomBottomCycles(t.mobileComponents)))}}},function(e,t,n){"use strict";var i=n(0);e.exports={exec:function(e){var t,n,o=e.structure;if(o&&o.components&&!i.isEmpty(o.components)&&(t=o.components,n=i.head(t),i.get(n,"layout.anchors"))){var r=i.maxBy(o.components,function(e){var t=-1*Number.MAX_VALUE;return e.layout&&i.isNumber(e.layout.y)&&i.isNumber(e.layout.height)&&(t=e.layout.y+e.layout.height),t}),a=void 0;r.layout&&r.layout.anchors&&(a=i.find(r.layout.anchors,{type:"BOTTOM_PARENT"})),a||(r.layout=r.layout||{},r.layout.anchors=r.layout.anchors||[],r.layout.anchors.push({distance:0,type:"BOTTOM_PARENT",targetComponent:e.structure.id,locked:!0,originalValue:e.structure.layout.height,topToTop:r.layout.y}))}}}},function(e,t,n){"use strict";var i=n(0),o={"wysiwyg.viewer.skins.line.FadeLine":{width:90},"wysiwyg.viewer.skins.line.FadeNotchBottomLine":{width:60},"wysiwyg.viewer.skins.line.FadeNotchTopLine":{width:60},"wysiwyg.viewer.skins.line.ShadowBottomLine":{width:200},"wysiwyg.viewer.skins.line.ShadowTopLine":{width:200}};function r(e){i.forEach(e,function(e){if(i.has(o,e.skin)){var t=o[e.skin];e.layout=i.mapValues(e.layout,function(e,n){return t[n]?Math.max(e,t[n]):e})}e.components&&r(e.components)})}e.exports={exec:function(e){var t=e.structure;t&&(t.components&&r(t.components),t.children&&r(t.children),t.mobileComponents&&r(t.mobileComponents))}}},function(e,t,n){"use strict";var i=n(0);e.exports={exec:function(e){var t=i.get(e,"data");t.connections_data=t.connections_data||{}}}},function(e,t,n){"use strict";var i=n(0),o=n(1),r=n(6);e.exports={exec:function(e){var t=i.get(e,"data"),n=i.get(e,"structure");t.behaviors_data=t.behaviors_data||{};var a,s,c=(a=n,s=o.dataUtils.getAllCompsInStructure(a,!1),i.pickBy(s,"behaviors")),u=function(e,t){var n=o.dataUtils.getAllCompsInStructure(e,!0);return i.pickBy(n,function(e){return t[e.id]})}(n,c);i.forEach(c,function(e){var n=r.createBehaviorsDataItem(e.behaviors);!function(e,t,n){e.behaviorQuery=t.id,n&&(n.behaviorQuery=e.behaviorQuery)}(e,n,u[e.id]),delete e.behaviors,i.set(t,["behaviors_data",n.id],n)})}}},function(e,t,n){"use strict";var i=n(0),o=n(68);function r(e){return["behaviors_data",e.behaviorQuery,"items"]}function a(e){return i.has(e,"behaviors_data")}function s(e,t,n){var o=JSON.stringify(e);a(n)?i.set(n,r(t),o):t.behaviors=o}function c(e,t){var n=[],o=function(e,t){return a(t)?i.get(t,r(e),"[]"):e.behaviors||"[]"}(e,t),c=JSON.parse(o);if(i.isEmpty(c))a(t)?delete e.behaviorQuery:delete e.behaviors;else{if(i.isArray(c)){var u=!1;return i.forEach(c,function(t){var n=i.get(t,"action.sourceId");n&&n!==e.id&&(t.action.sourceId=e.id,u=!0)}),void(u&&s(c,e,t))}i.forEach(c,function(e,t){i.forEach(e,function(e,o){i.forEach(e,function(e){var r=i.assign({targetId:o,action:t},e);"screenIn"!==t&&"pageIn"!==t||(r.targetId=""),n.push(r)})})}),s(n,e,t)}}function u(e,t){i.forEach(e,function(e){c(e,t),e.components&&u(e.components,t)})}e.exports={exec:function(e){o.exec(e);var t=e.structure;t&&(t.components&&u(t.components,e.data),t.mobileComponents&&u(t.mobileComponents,e.data),t.children&&u(t.children,e.data))}}},function(e,t,n){"use strict";var i=n(0),o=["GalleryExpandProperties","MatrixGalleryProperties","PaginatedGridGalleryProperties","SliderGalleryProperties","SlideShowGalleryProperties"];function r(e){return(i.isUndefined(e.galleryImageOnClickAction)||"unset"===e.galleryImageOnClickAction)&&(!1===e.expandEnabled?e.galleryImageOnClickAction="disabled":e.galleryImageOnClickAction="zoomMode"),e}e.exports={exec:function(e){var t,n,a;t=e.data.component_properties,n=o,a=r,i(t).pickBy(function(e){return i.includes(n,e.type)}).mapValues(a).value()}}},function(e,t,n){"use strict";var i=n(0),o=n(1);function r(e,t,n){var i=e[n.componentType];i&&(n.componentType=i.comp,i.dataQuery&&(n.dataQuery=i.dataQuery),i.callback&&i.callback(t))}function a(e,t){"wysiwyg.viewer.components.ItunesButton"===t.componentType&&(t.layout.height=Math.round(t.layout.width/2.75))}function s(e,t){return e.data.component_properties[t.propertyQuery]}function c(e,t){return t.dataQuery&&e.data.document_data[t.dataQuery.replace("#","")]}function u(e,t,n){e.data.component_properties[t.propertyQuery]=n}function p(e,t,n){var i=o.guidUtils.getUniqueId("dataItem","-");t.dataQuery="#"+i,n.id=i,e.data.document_data[i]=n}function d(e,t){"SITE_FOOTER"!==t.id||t.layout||(t.layout={anchors:[],fixedPosition:!1,height:function(e){if(e.components.length>0){var t=i.map(e.components,function(e){return e.layout.y+e.layout.height});return i.max(t)}return 0}(t),rotationInDegrees:0,scale:1,width:320,x:0,y:function(e){var t=i.find(e.structure.children,{id:"PAGES_CONTAINER"});return t.layout.y+t.layout.height}(e)})}function m(e,t){if(!c(e,t))switch(t.componentType){case"wysiwyg.viewer.components.svgshape.SvgShape":p(e,t,{link:null,type:"SvgShape"});break;case"wysiwyg.viewer.components.WFacebookComment":return void p(e,t,{type:"WFacebookComment",urlFormat:"hashBang"});case"wysiwyg.viewer.components.WFacebookLike":return void p(e,t,{type:"WFacebookLike",urlFormat:"hashBang"})}}function l(e,t){var n=c(e,t);if(n)switch(t.componentType){case"wysiwyg.viewer.components.ClipArt":return void(n.title="");case"wysiwyg.viewer.components.FacebookShare":case"wysiwyg.viewer.components.VKShareButton":case"wysiwyg.common.components.pinterestpinit.viewer.PinterestPinIt":case"wysiwyg.viewer.components.WTwitterTweet":case"wysiwyg.viewer.components.WFacebookComment":case"wysiwyg.viewer.components.WFacebookLike":return void(n.urlFormat=n.urlFormat||"hashBang")}}function y(e,t,n){"wysiwyg.common.components.anchor.viewer.Anchor"===n.componentType&&0===n.layout.width&&(n.layout.width=e)}function f(e,t){if(!s(e,t))switch(t.componentType){case"wysiwyg.viewer.components.menus.DropDownMenu":u(e,t,{alignButtons:"center",alignText:"center",sameWidthButtons:!1,moreButtonLabel:"More",moreItemHeight:15,stretchButtonsToMenuWidth:!0,type:"HorizontalMenuProperties"});break;case"wysiwyg.viewer.components.mobile.TinyMenu":t.propertyQuery="TINY_MENU",u(e,t,{direction:"left",type:"TinyMenuProperties",id:"TINY_MENU",metaData:{isPreset:!1,schemaVersion:"1.0",isHidden:!1}})}}function g(e,t,n){e.properties[n.id]=s(t,n)}function w(e,t,n){!s(t,n)&&e.properties[n.id]&&u(t,n,e.properties[n.id])}function v(e,t){var n=s(e,t);if(t.propertyQuery&&n)switch(t.componentType){case"wysiwyg.viewer.components.WFacebookLike":case"wysiwyg.viewer.components.PayPalButton":case"wysiwyg.viewer.components.GoogleMap":n.language||(n.language="en");break;case"wysiwyg.viewer.components.WRichText":"WRichTextProperties"!==n.type&&delete t.propertyQuery;break;case"wysiwyg.viewer.components.HoverBox":n.mobileDisplayedModeId&&function(e,t){var n=i.get(e,"modes.definitions");return!i.some(n,{modeId:t})}(t,n.mobileDisplayedModeId)&&(n.mobileDisplayedModeId=function(e){var t=i.get(e,"modes.definitions");return i.find(t,{type:o.siteConstants.COMP_MODES_TYPES.HOVER}).modeId}(t))}}function T(e,t,n){i.forEach(t,function(t){i.forEach(n,function(n){n(e,t)}),t.components&&T(e,t.components,n)})}function h(){return i.partial(r,{"wysiwyg.viewer.components.HorizontalMenu":{comp:"wysiwyg.viewer.components.menus.DropDownMenu",dataQuery:"#MAIN_MENU"},"wysiwyg.viewer.components.ClipArt":{comp:"wysiwyg.viewer.components.WPhoto"}})}function k(e,t,n){e.pageContainsStructuresWithoutJsonAnchors=e.pageContainsStructuresWithoutJsonAnchors||!n.layout||!n.layout.anchors}function S(e,t){t.layout&&delete t.layout.anchors}e.exports={exec:function(e){var t=e.structure;if(t){var n={properties:{}},o=t.components||t.children,r=t.mobileComponents;o&&function(e,t,n){T(e,n,[h(),a,m,f,v,l,i.partial(y,1920),i.partial(g,t)])}(e,n,o),r&&function(e,t,n){var o={pageContainsStructuresWithoutJsonAnchors:!1};T(e,n,[h(),a,m,f,v,l,d,i.partial(y,320),i.partial(w,t),i.partial(k,o)]),o.pageContainsStructuresWithoutJsonAnchors&&T(e,n,[S])}(e,n,r)}}}},function(e,t,n){"use strict";var i=n(0),o="add_image_thumb.png";function r(e){return e&&"wysiwyg.viewer.components.BgImageStrip"===e.componentType}function a(e,t,n){if(r(n)){var i=function(e){return e&&e.dataQuery&&e.dataQuery.replace("#","")}(n),a=i&&t[i];a&&(a.title=a.title||"",function(e){return e.uri.slice(0-o.length)===o}(a)||(e[n.id]=i))}}function s(e,t,n){if(r(n)){var i=e[n.id];i?n.dataQuery="#"+i:delete n.dataQuery}}function c(e,t){i.forEach(e,function(e){t(e),c(e.components,t)})}e.exports={exec:function(e){var t=e.structure,n=t&&(t.components||t.children),i=t&&t.mobileComponents;if(n){var o={};c(n,a.bind(null,o,e.data.document_data)),c(n,s.bind(null,o,e.data.document_data)),c(i,s.bind(null,o,e.data.document_data))}}}},function(e,t,n){"use strict";var i=n(0);function o(e,t,n){return e[n.replace("llt_","llf_")]=t,e}function r(e){e.style.properties=i.reduce(e.style.properties,o,{}),e.style.propertiesSource=i.reduce(e.style.propertiesSource,o,{})}var a={"*":function(e){"THEME_DATA"!==e.id&&(e.style||(e.style={properties:{},propertiesSource:{},groups:{}}))},"wysiwyg.common.components.subscribeform.viewer.skins.SubscribeFormLineLayoutFlat":r,"wysiwyg.common.components.subscribeform.viewer.skins.SubscribeFormLineLayoutTransparentWithIcon":r};e.exports={exec:function(e){var t=e.data&&e.data.theme_data;e.structure&&"Document"===e.structure.type&&(!function(e){if(!e.v2){var t={type:"TopLevelStyle",id:"v2",metaData:{isPreset:!1,schemaVersion:"1.0",isHidden:!1},style:{properties:{brd:"color_15",brw:"0px",rd:"0px",shd:"0 1px 4px rgba(0, 0, 0, 0.6);"},propertiesSource:{brd:"theme",brw:"value",rd:"value",shd:"value"},groups:{}},componentClassName:"",pageId:"",compId:"",styleType:"system",skin:"wysiwyg.viewer.skins.video.VideoDefault"};e.v2=i.cloneDeep(e.vl)||t}}(t),function(e){i.forOwn(e,function(e){a["*"](e),a[e.skin]&&a[e.skin](e)})}(t),i.forEach(t,function(e){!function(e){e.style&&i.forEach(e.style.properties,function(e,t,n){"string"==typeof e&&(n[t]=e.replace(/(\d)x/g,"$1px"))})}(e)}))}}},function(e,t,n){"use strict";var i=n(0),o={"mobile.core.skins.InlineSkin":"skins.core.VerySimpleSkin","mobile.core.skins.TwitterTweetSkin":"skins.core.TwitterTweetSkin","mobile.core.skins.ButtonSkin":"skins.core.ButtonSkin","mobile.core.skins.ContactItemSkin":"skins.core.ContactItemSkin","mobile.core.skins.ContactListSkin":"skins.core.ContactListSkin","mobile.core.skins.FacebookCommentSkin":"skins.core.FacebookCommentSkin","mobile.core.skins.GlobalMenuSkin":"skins.core.GlobalMenuSkin","mobile.core.skins.GooglePlusOneSkin":"skins.core.GooglePlusOneSkin","mobile.core.skins.HeaderSkin":"skins.core.HeaderSkin","mobile.core.skins.HomeButtonSkin":"skins.core.HomeButtonSkin","mobile.core.skins.ImageNewSkin":"skins.core.ImageNewSkin","mobile.core.skins.ImageSkin":"skins.core.ImageSkin","mobile.core.skins.MenuButtonSkin":"skins.core.MenuButtonSkin","mobile.core.skins.NetworkItemSkin":"skins.core.NetworkItemSkin","mobile.core.skins.NetworkListSkin":"skins.core.NetworkListSkin","mobile.core.skins.PageTitleSkin":"skins.core.PageTitleSkin","mobile.core.skins.PhotoFullScreenSkin":"skins.core.PhotoFullScreenSkin","mobile.core.skins.PhotoGalleryFullScreenDefaultSkin":"skins.core.PhotoGalleryFullScreenDefaultSkin","mobile.core.skins.PhotoGalleryGridDefaultSkin":"skins.core.PhotoGalleryGridDefaultSkin","mobile.core.skins.PhotoSkin":"skins.core.PhotoSkin","mobile.core.skins.RichTextImageSkin":"skins.core.RichTextImageSkin","mobile.core.skins.RichTextSkin":"skins.core.RichTextSkin","mobile.core.skins.ServiceItemSkin":"skins.core.ServiceItemSkin","mobile.core.skins.ServiceListSkin":"skins.core.ServiceListSkin","mobile.core.skins.SimpleButtonSkin":"skins.core.SimpleButtonSkin","mobile.core.skins.SiteNavigationMenuSkin":"skins.core.SiteNavigationMenuSkin","mobile.core.skins.TwitterFollowSkin":"skins.core.TwitterFollowSkin","mobile.core.skins.FacebookLikeSkin":"skins.core.FacebookLikeSkin","skins.viewer.gallerymatrix.PolaroidCustomHeightSkin":"wysiwyg.viewer.skins.gallerymatrix.PolaroidCustomHeightSkin","skins.viewer.gallerymatrix.PolaroidDisplayerCustomHeightSkin":"wysiwyg.viewer.skins.gallerymatrix.PolaroidDisplayerCustomHeightSkin","skins.viewer.gallerymatrix.TextBottomCustomHeightSkin":"wysiwyg.viewer.skins.gallerymatrix.TextBottomCustomHeightSkin","skins.viewer.gallerymatrix.TextBottomDisplayerCustomHeightSkin":"wysiwyg.viewer.skins.gallerymatrix.TextBottomDisplayerCustomHeightSkin","skins.viewer.galleryslider.SliderGalleryScotchTapeSkin":"wysiwyg.viewer.skins.galleryslider.SliderGalleryScotchTapeSkin","skins.viewer.galleryslider.SliderGalleryIronSkin":"wysiwyg.viewer.skins.galleryslider.SliderGalleryIronSkin","skins.viewer.galleryslider.SliderDisplayerIronSkin":"wysiwyg.viewer.skins.galleryslider.SliderDisplayerIronSkin","skins.viewer.galleryslider.SliderDisplayerScotchTapeSkin":"wysiwyg.viewer.skins.galleryslider.SliderDisplayerScotchTapeSkin","wysiwyg.viewer.skins.gallerymatrix.MatrixGallerySeparateTextBoxSkin":"wysiwyg.common.components.matrixgallery.viewer.skins.MatrixGallerySeparateTextBoxSkin","wysiwyg.viewer.skins.gallerymatrix.MatrixGalleryTextOnCenterSkin":"wysiwyg.common.components.matrixgallery.viewer.skins.MatrixGalleryTextOnCenterSkin","wysiwyg.viewer.skins.dropmenu.TextOnlyMenuNSkin":"wysiwyg.common.components.dropdownmenu.viewer.skins.TextOnlyMenuButtonSkin","wysiwyg.viewer.skins.dropmenu.TextSeparatorsMenuNSkin":"wysiwyg.common.components.dropdownmenu.viewer.skins.TextSeparatorsMenuButtonSkin","wysiwyg.viewer.skins.dropmenu.SolidColorMenuNSkin":"wysiwyg.common.components.dropdownmenu.viewer.skins.SolidColorMenuButtonSkin","wysiwyg.viewer.skins.dropmenu.ShinyMenuINSkin":"wysiwyg.common.components.dropdownmenu.viewer.skins.ShinyMenuIButtonSkin","wysiwyg.viewer.skins.dropmenu.ShinyMenuIINSkin":"wysiwyg.common.components.dropdownmenu.viewer.skins.ShinyMenuIIButtonSkin","wysiwyg.viewer.skins.dropmenu.OverlineMenuNSkin":"wysiwyg.common.components.dropdownmenu.viewer.skins.OverlineMenuButtonSkin","wysiwyg.viewer.skins.dropmenu.SeparateBasicMenuNSkin":"wysiwyg.common.components.dropdownmenu.viewer.skins.SeparateBasicMenuButtonSkin","wysiwyg.viewer.skins.dropmenu.SeparateShinyIMenuNSkin":"wysiwyg.common.components.dropdownmenu.viewer.skins.SeparateShinyIMenuButtonSkin","wysiwyg.viewer.skins.dropmenu.SeparateShinyIIMenuNSkin":"wysiwyg.common.components.dropdownmenu.viewer.skins.SeparateShinyIIMenuButtonSkin","wysiwyg.viewer.skins.dropmenu.LinesMenuNSkin":"wysiwyg.common.components.dropdownmenu.viewer.skins.LinesMenuButtonSkin","wysiwyg.viewer.skins.dropmenu.SeparateLinesMenuNSkin":"wysiwyg.common.components.dropdownmenu.viewer.skins.SeparateLinesMenuButtonSkin","wysiwyg.viewer.skins.dropmenu.PointerMenuNSkin":"wysiwyg.common.components.dropdownmenu.viewer.skins.PointerMenuButtonSkin","wysiwyg.viewer.skins.dropmenu.RibbonsMenuNSkin":"wysiwyg.common.components.dropdownmenu.viewer.skins.RibbonsMenuButtonSkin","wysiwyg.viewer.skins.dropmenu.VerticalRibbonsMenuNSkin":"wysiwyg.common.components.dropdownmenu.viewer.skins.VerticalRibbonsMenuButtonSkin","wysiwyg.viewer.skins.dropmenu.IndentedMenuNSkin":"wysiwyg.common.components.dropdownmenu.viewer.skins.IndentedMenuButtonSkin","wysiwyg.viewer.skins.dropmenu.SeparateIndentedMenuNSkin":"wysiwyg.common.components.dropdownmenu.viewer.skins.SeparateIndentedMenuButtonSkin","wysiwyg.viewer.skins.dropmenu.ArrowRightMenuNSkin":"wysiwyg.common.components.dropdownmenu.viewer.skins.ArrowRightMenuButtonSkin","wysiwyg.viewer.skins.dropmenu.SloppyBorderMenuNSkin":"wysiwyg.common.components.dropdownmenu.viewer.skins.SloppyBorderMenuButtonSkin","wysiwyg.viewer.skins.menu.ShinyMenuISkin":"wysiwyg.common.components.dropdownmenu.viewer.skins.ShinyMenuIIButtonSkin","wysiwyg.viewer.skins.menu.ShinyMenuIISkin":"wysiwyg.common.components.dropdownmenu.viewer.skins.ShinyMenuIIButtonSkin","wysiwyg.viewer.skins.menu.TextOnlyMenuSkin":"wysiwyg.common.components.dropdownmenu.viewer.skins.TextOnlyMenuButtonBgFixSkin","wysiwyg.viewer.skins.menu.TextSeparatorsMenuSkin":"wysiwyg.common.components.dropdownmenu.viewer.skins.TextSeparatorsMenuButtonSkin","wysiwyg.viewer.skins.menu.SolidColorMenuSkin":"wysiwyg.common.components.dropdownmenu.viewer.skins.SolidColorMenuButtonSkin","wysiwyg.viewer.skins.menu.OverlineMenuSkin":"wysiwyg.common.components.dropdownmenu.viewer.skins.OverlineMenuButtonHorizontalMenuAdaptationSkin","wysiwyg.viewer.skins.menu.SeparateBasicMenuSkin":"wysiwyg.common.components.dropdownmenu.viewer.skins.SeparateBasicMenuButtonSkin","wysiwyg.viewer.skins.menu.SeparateShinyIMenuSkin":"wysiwyg.common.components.dropdownmenu.viewer.skins.SeparateShinyIMenuButtonSkin","wysiwyg.viewer.skins.menu.SeparateShinyIIMenuSkin":"wysiwyg.common.components.dropdownmenu.viewer.skins.SeparateShinyIIMenuButtonBorderRadiusFixSkin","wysiwyg.viewer.skins.menu.LinesMenuSkin":"wysiwyg.common.components.dropdownmenu.viewer.skins.LinesMenuButtonBorderRadiusFixSkin","wysiwyg.viewer.skins.menu.SeparateLinesMenuSkin":"wysiwyg.common.components.dropdownmenu.viewer.skins.SeparateLinesMenuButtonHorizontalMenuAdaptationSkin","wysiwyg.viewer.skins.menu.PointerMenuSkin":"wysiwyg.common.components.dropdownmenu.viewer.skins.PointerMenuButtonHorizontalMenuAdaptationSkin","wysiwyg.viewer.skins.menu.RibbonsMenuSkin":"wysiwyg.common.components.dropdownmenu.viewer.skins.RibbonsMenuButtonSkin","wysiwyg.viewer.skins.menu.IndentedMenuSkin":"wysiwyg.common.components.dropdownmenu.viewer.skins.IndentedMenuButtonSkin","wysiwyg.viewer.skins.menu.SeparateIndentedMenuSkin":"wysiwyg.common.components.dropdownmenu.viewer.skins.SeparateIndentedMenuButtonSkin","wysiwyg.viewer.skins.menu.ArrowRightMenuSkin":"wysiwyg.common.components.dropdownmenu.viewer.skins.ArrowRightMenuButtonSkin","wysiwyg.viewer.skins.menu.SloppyBorderMenuSkin":"wysiwyg.common.components.dropdownmenu.viewer.skins.SloppyBorderMenuButtonSkin","tpa.viewer.skins.TPAMasonrySkin":"wysiwyg.viewer.skins.TPAMasonrySkin","tpa.viewer.skins.TPA3DCarouselSkin":"wysiwyg.viewer.skins.TPA3DCarouselSkin","tpa.viewer.skins.TPA3DGallerySkin":"wysiwyg.viewer.skins.TPA3DGallerySkin","tpa.viewer.skins.TPAAccordionSkin":"wysiwyg.viewer.skins.TPAAccordionSkin","tpa.viewer.skins.TPACollageSkin":"wysiwyg.viewer.skins.TPACollageSkin","tpa.viewer.skins.TPAEcomGallerySkin":"wysiwyg.viewer.skins.TPAEcomGallerySkin","tpa.viewer.skins.TPAFreestyleSkin":"wysiwyg.viewer.skins.TPAFreestyleSkin","tpa.viewer.skins.TPAHoneycombSkin":"wysiwyg.viewer.skins.TPAHoneycombSkin","tpa.viewer.skins.TPAImpressSkin":"wysiwyg.viewer.skins.TPAImpressSkin","tpa.viewer.skins.TPAStripShowcaseSkin":"wysiwyg.viewer.skins.TPAStripShowcaseSkin","tpa.viewer.skins.TPAStripSlideshowSkin":"wysiwyg.viewer.skins.TPAStripSlideshowSkin","tpa.viewer.skins.TPAThumbnailsSkin":"wysiwyg.viewer.skins.TPAThumbnailsSkin","tpa.common.skins.TPAPreloaderSkin":"wysiwyg.viewer.skins.TPAPreloaderSkin","tpa.common.skins.TPAUnavailableMessageOverlaySkin":"wysiwyg.viewer.skins.TPAUnavailableMessageOverlaySkin"};function r(e){e.skin&&o[e.skin]&&(e.skin=o[e.skin])}function a(e,t){var n=void 0,i=void 0,o=e[t]||e.components;if(o)for(n=0;n<o.length;n++)r(i=o[n]),a(i,t)}e.exports={exec:function(e){var t=e.structure;t&&(a(t,"children"),a(t,"mobileComponents"),r(t));var n=e.data&&e.data.theme_data;n&&i.forEach(n,function(e){r(e)})}}},function(e,t,n){"use strict";var i=new(n(2))({"wysiwyg.common.components.verticalmenu.viewer.VerticalMenu":o,"wysiwyg.viewer.components.menus.DropDownMenu":o});function o(e,t,n,i){var o=this.getComponentData(e,i);o&&"CustomMenuDataRef"===o.type||(delete i.dataQuery,this.setComponentData(e,i,{menuRef:"#CUSTOM_MAIN_MENU",type:"CustomMenuDataRef"},t))}e.exports={exec:i.migratePage.bind(i)}},function(e,t,n){"use strict";var i=n(0);function o(e){return function e(t){return i.reduce(t.items,function(t,n){return t.push(n.refId),n.items&&n.items.length?t.concat(e(n)):t},[])}(e.MAIN_MENU)}function r(e,t){var n=i.findIndex(e.items,{refId:t});if(n>=0)!function(e,t){var n=e.items[t];n.items&&n.items.length>0&&i.forEach(n.items,function(t,i){e.items.push(t),delete n.items[i]}),n.items=[],e.items.splice(t,1)}(e,n);else{var o=function(e,t){var n={};return i.find(e.items,function(e,o){return n.topIndex=o,i.find(e.items,function(e,i){if(e.refId===t)return n.subIndex=i,!0})}),n}(e,t);e.items[o.topIndex].items.splice(o.subIndex,1)}}function a(e){return e.replace("#","")}function s(e,t){return!e[a(t)]}function c(e,t){var n=o(e);!function(e){var t=i.get(e,["CUSTOM_MAIN_MENU","items"]);t&&i.some(t,i.partial(s,e))&&(delete e.CUSTOM_MAIN_MENU,delete e.CUSTOM_MENUS)}(e),function(e,t){var n=e.MAIN_MENU;i.forEach(t,function(e){e||r(n,e)}),i.pull(t,"",void 0)}(e,n),function(e,t,n){i.forEach(t,function(t){i.includes(n,t.slice(1))||r(e.MAIN_MENU,t)})}(e,n,t),function(e,t,n){var o=e.MAIN_MENU,r=0===o.items.length;if(e.CUSTOM_MAIN_MENU){if(r)return;delete e.CUSTOM_MAIN_MENU,delete e.CUSTOM_MENUS}i.forEach(n,function(e){if(!i.includes(t,"#"+e)){t.push("#"+e);var n={items:[],refId:"#"+e};o.items.push(n)}})}(e,n,t),function(e,t){e&&e.mainPage&&!i.includes(t,a(e.mainPage))&&(e.mainPage="#"+t[0])}(e.masterPage,t)}e.exports={exec:function(e,t){var n=e.data.document_data;(function(e){return"Document"===i.get(e,"structure.type")})(e)&&(n.MAIN_MENU=n.MAIN_MENU||{items:[],type:"Menu",id:"MAIN_MENU",metaData:{}},t&&c(n,t))}}},function(e,t,n){"use strict";var i=n(0),o=n(76),r=0,a=0,s="bmi",c="pglk";function u(e,t){return i.map(e,function(e){return function(e,t){var n=s+r++,i=e[y(t.refId)];return e[n]={id:n,label:i.title,isVisible:!i.hidePage,isVisibleMobile:void 0!==i.mobileHidePage?!i.mobileHidePage:!i.hidePage,items:u(t.items,e),link:p(e,t.refId),type:"BasicMenuItem",metaData:{}},"#"+n}(t,e)})}function p(e,t){var n=c+a++;return e[n]={id:n,type:"PageLink",pageId:t,metaData:{}},"#"+n}function d(e,t){return t&&e[y(t)]}function m(e,t){var n=d(e,t.link);return"PageLink"===i.get(n,"type")?n:void 0}function l(e,t){return t.link&&("#CUSTOM_MENU_HEADER"===t.link||function(e,t){var n=m(e,t);return n&&!d(e,n.pageId)}(e,t))}function y(e){return i.replace(e,"#","")}function f(e,t){var n=e.CUSTOM_MAIN_MENU.items,o=i(e).filter({type:"BasicMenuItem"}).map("link").compact().map(y).map(function(t){return e[t]}).map("pageId").compact().map(y).value(),a=i(e).filter(function(e){return"Page"===e.type&&e.managingAppDefId}).map("id").value(),c=i.difference(t,o),u=i.difference(c,a);i.forEach(u,function(t){var i,o,a,c;e[t].isPopup||n.push((a=s+r++,c=(i=e)[o=t],i[a]={id:a,label:c.title,isVisible:!c.hidePage,isVisibleMobile:void 0!==c.mobileHidePage?!c.mobileHidePage:!c.hidePage,items:[],link:p(i,"#"+o),type:"BasicMenuItem",metaData:{}},"#"+a))})}function g(e,t){var n=i.filter(e,function(e){return e.id&&0===e.id.indexOf(t)}),o=-1;return i.forEach(n,function(e){var n=Number(e.id.replace(t,""));n>o&&(o=n)}),++o}e.exports={exec:function(e,t){if(function(e){return"Page"===i.get(e,"structure.type")}(e))!function(e){i(e.data.document_data).filter({type:"Menu"}).map("id").forEach(function(t){delete e.data.document_data[t]})}(e);else{o.exec(e,t);var n=e.data.document_data;r=g(n,s),a=g(n,c),e.data.document_data.CUSTOM_MAIN_MENU||(e.data.document_data.CUSTOM_MAIN_MENU={id:"CUSTOM_MAIN_MENU",items:u(e.data.document_data.MAIN_MENU.items,e.data.document_data),name:"Custom Main Menu",type:"CustomMenu",metaData:{}}),e.data.document_data.CUSTOM_MENUS?i.includes(e.data.document_data.CUSTOM_MENUS.menus,"#CUSTOM_MAIN_MENU")||e.data.document_data.CUSTOM_MENUS.menus.push("#CUSTOM_MAIN_MENU"):e.data.document_data.CUSTOM_MENUS={id:"CUSTOM_MENUS",menus:["#CUSTOM_MAIN_MENU"],type:"CustomMenusCollection",metaData:{}},f(n,t),n.CUSTOM_MAIN_MENU.items=i.uniq(n.CUSTOM_MAIN_MENU.items),function e(t,n){n.items=i.filter(n.items,function(e){return!i.isUndefined(d(t,e))}),i.forEach(n.items,function(n){var i=d(t,n);l(t,i)&&function(e){delete e.link}(i),e(t,i)})}(n,n.CUSTOM_MAIN_MENU),e.data.document_data.MAIN_MENU.items.length>0&&(e.data.document_data.MAIN_MENU.items=[]);var p=e.data.document_data.CUSTOM_MAIN_MENU;(function(e,t){function n(n){var o,r,a=e.data.document_data,s=d(a,n);return!s.link||!m(a,s)||(o=d(a,s.link),r=i.get(o,"pageId"),i.includes(t,y(r)))}return{removeInvalidSubMenues:function t(o){o.items=i.filter(o.items,n),i(o.items).map(function(t){return d(e.data.document_data,t)}).forEach(t)}}})(e,t).removeInvalidSubMenues(p)}}}},function(e,t,n){"use strict";var i=n(0);e.exports=function e(t,n){i.forEach(t,function(t){i.forEach(n,function(e){e(t)}),t.components&&e(t.components,n)})}},function(e,t,n){"use strict";var i=n(0),o=n(78),r=["wysiwyg.viewer.components.HeaderContainer","wysiwyg.viewer.components.SiteRegionContainer","wysiwyg.viewer.components.PagesContainer","wysiwyg.viewer.components.FooterContainer","platform.components.AppController","wysiwyg.viewer.components.tpapps.TPAGluedWidget","wysiwyg.viewer.components.QuickActionBar","wysiwyg.common.components.backtotopbutton.viewer.BackToTopButton"],a=function(e){var t=i.get(e,["data","document_data"]),n=i.get(t,["masterPage","layoutSettings"]);n&&("mesh"===n.mechanism&&function(e){return i.some(e,function(e){var t=e.componentType;return!i.includes(r,t)})}(i.get(e,["structure","mobileComponents"]))&&(n.mechanism="anchors"))};function s(e){return 0===i.get(e,"layout.width")}function c(e){return 0===i.get(e,"layout.height")}function u(e){s(e)&&i.set(e,"layout.width",100),c(e)&&i.set(e,"layout.height",100)}function p(e,t){var n=!1;if(i.forEach(["SITE_HEADER","SITE_FOOTER"],function(o){var r=i.find(e,{id:o});s(r)&&(n=!0),c(r)&&(i.set(r,"layout.height",100),n=!0),i.set(r,"layout.width",t)}),n){var r=i.reject(e,{id:"PAGES_CONTAINER"});o(r,[u])}}function d(e,t,n){var o=i.find(e,{id:"SITE_HEADER"});if(o){n?function(e,t){if(!t.behaviorQuery)return!1;var n=i.get(e,["data","behaviors_data",t.behaviorQuery]);try{var o=JSON.parse(n.items);return i.some(o,{type:"scrub",name:"ScrubAnimation"})}catch(e){return!1}}(t,o)&&i.set(o,["layout","fixedPosition"],!0):i.set(o,["layout","fixedPosition"],!1);var r=i.find(e,{id:"SITE_FOOTER"});i.set(r,["layout","fixedPosition"],!1)}}function m(e,t){var n,o=e.structure,r=o.children,a=o.mobileComponents,s=i.get(e,"data.document_data.masterPage.renderModifiers.siteWidth",980);y(r),p(r,s),y(a),p(a,320),d(a,e,t),n=a,i.forEach(n,function(e){i.forEach(i.get(e,"layout.anchors"),function(t){switch(e.id){case"SITE_FOOTER":"BOTTOM_PARENT"===t.type&&(t.distance=0);break;case"PAGES_CONTAINER":"BOTTOM_TOP"===t.type&&t.locked&&t.distance>=70&&(t.originalValue=0,t.locked=!1)}})})}var l=[{componentType:"wysiwyg.viewer.components.PagesContainer",id:"PAGES_CONTAINER"},{componentType:"wysiwyg.viewer.components.FooterContainer",id:"SITE_FOOTER"},{componentType:"wysiwyg.viewer.components.HeaderContainer",id:"SITE_HEADER"}];function y(e){i.forEach(l,function(t){if(!i.find(e,{id:t.id})){var n=i.find(e,{componentType:t.componentType});n&&(n.id=t.id)}})}e.exports={exec:function(e,t,n,i,o,r,s,c){var u;e.structure&&"Document"===e.structure.type&&(e.structure.id="masterPage",e.structure.componentType="mobile.core.components.MasterPage",(u=e.data.document_data).SITE_STRUCTURE&&(u.masterPage=u.SITE_STRUCTURE),u.masterPage||(u.masterPage={}),u.masterPage.id="masterPage",delete u.SITE_STRUCTURE,m(e,c.isExperimentOpen("sv_fixedMobileHeader")),a(e));return e}}},function(e,t,n){"use strict";e.exports={exec:function(e){e.structure=e.structure||{},e.structure.layout=e.structure.layout||{},e.structure.layout.y=0}}},function(e,t,n){"use strict";e.exports={"wysiwyg.viewer.components.MatrixGallery":{propType:"MatrixGalleryProperties"},"wysiwyg.viewer.components.PaginatedGridGallery":{propType:"PaginatedGridGalleryProperties"},"wysiwyg.viewer.components.SliderGallery":{propType:"SliderGalleryProperties"},"wysiwyg.viewer.components.SlideShowGallery":{propType:"SlideShowGalleryProperties"},"tpa.viewer.components.Masonry":{propType:"MasonryProperties"},"tpa.viewer.components.Accordion":{propType:"AccordionProperties"},"tpa.viewer.components.Impress":{propType:"ImpressProperties"},"tpa.viewer.components.Freestyle":{propType:"FreestyleProperties"},"tpa.viewer.components.Collage":{propType:"CollageProperties"},"tpa.viewer.components.Honeycomb":{propType:"HoneycombProperties"},"tpa.viewer.components.StripShowcase":{propType:"StripShowcaseProperties"},"tpa.viewer.components.StripSlideshow":{propType:"StripSlideshowProperties"},"tpa.viewer.components.Thumbnails":{propType:"ThumbnailsProperties"},"wysiwyg.viewer.components.tpapps.TPA3DGallery":{propType:"SlideShowGalleryProperties"},"wysiwyg.viewer.components.tpapps.TPA3DCarousel":{propType:"SlideShowGalleryProperties"}}},function(e,t,n){"use strict";var i=n(0),o=n(2),r=n(81);function a(e,t,n,i){if(n){var o=t[i.id];if(o.componentType!==i.componentType){var a=o.componentType;i.componentType=a;var s=this.getComponentProperties(e,i),c=r[a].propType;!a||s&&s.type===c||(i.propertyQuery=o.propertyQuery)}}else t[i.id]=i}e.exports={exec:function(e){var t=i.mapValues(r,function(){return a});new o(t).migratePage(e)}}},function(e,t,n){"use strict";var i=n(7),o=n(9),r=n(8),a=n(3),s=n(5);e.exports={fix:i,deprecatedSiteModelMigrater:o,fixBackgroundData:r,imageTransformDataFixers:a,anchorCyclesHelper:s}}])});
//# sourceMappingURL=santa-data-fixer.js.map
|
exports.seed = function(knex) {
// Deletes ALL existing entries
return knex('participation').del()
.then(function () {
// Inserts seed entries
var participations = [
{attendee: 1, event: 4, comment: "Tıbbi malzemeler ile geliyorum."},
{attendee: 3, event: 4, comment: "İhtiyaçlar konusunda not düşün."},
{attendee: 4, event: 4},
{attendee: 2, event: 5, comment: "Su/içecek takviyesi yapabilirim."},
{attendee: 3, event: 5},
{attendee: 4, event: 5, comment: "Çay kahve otomatı getirebilirim."},
{attendee: 1, event: 12, comment: "$5 bağışlandı."},
{attendee: 2, event: 12},
{attendee: 3, event: 12, comment: "$5 bağışlandı."},
{attendee: 4, event: 12},
{attendee: 5, event: 12, comment: "$10 bağışlandı."},
]
return knex('participation').insert(
participations
);
});
};
|
var searchData=
[
['fenetre_0',['fenetre',['../namespaceinterface.html#a996178d6009a1daae7e61486aa5ba351',1,'interface']]],
['frame1_1',['Frame1',['../namespaceinterface.html#a084ba399a58d3cb5ab805d79e3bb8cf7',1,'interface']]],
['frame2_2',['Frame2',['../namespaceinterface.html#a2b5f9a79cbd2a245615bff843b2cd9f8',1,'interface']]],
['frame2_5f1_3',['Frame2_1',['../namespaceinterface.html#a75b1e1c48821da8f1dd510b79c810413',1,'interface']]],
['frame2_5f1_5fa_4',['Frame2_1_a',['../namespaceinterface.html#a84f64476a2c373aa1aad05c51e86de73',1,'interface']]],
['frame2_5f1_5fb_5',['Frame2_1_b',['../namespaceinterface.html#a39b70ef28b4b811c3258bb21f496b3ff',1,'interface']]],
['frame2_5f2_6',['Frame2_2',['../namespaceinterface.html#a7f0b35ae9fbe0ab1e955b191d7ffa7a4',1,'interface']]],
['frame2_5f2_5fa_7',['Frame2_2_a',['../namespaceinterface.html#a928228caf95ebda54df33cdb4014dc1a',1,'interface']]],
['frame2_5f2_5fb_8',['Frame2_2_b',['../namespaceinterface.html#aef41dbd3c31aa00b582f656d774482ec',1,'interface']]],
['frame2_5f3_9',['Frame2_3',['../namespaceinterface.html#a91782fa020c7cf8691f68f5d3bc30f30',1,'interface']]],
['frame2_5f3_5fa_10',['Frame2_3_a',['../namespaceinterface.html#ae17251bebdbe50ec016eb67778d41a0b',1,'interface']]],
['frame2_5f3_5fb_11',['Frame2_3_b',['../namespaceinterface.html#a18faf8103098966fc163877b09692a2e',1,'interface']]],
['frame3_12',['Frame3',['../namespaceinterface.html#a637b9eb75a679431e17eabbab827d546',1,'interface']]]
];
|
/**
* @ag-grid-community/core - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components
* @version v25.0.1
* @link http://www.ag-grid.com/
* @license MIT
*/
"use strict";
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
Object.defineProperty(exports, "__esModule", { value: true });
var beanStub_1 = require("../context/beanStub");
var context_1 = require("../context/context");
var HoverFeature = /** @class */ (function (_super) {
__extends(HoverFeature, _super);
function HoverFeature(columns, element) {
var _this = _super.call(this) || this;
_this.columns = columns;
_this.element = element;
return _this;
}
HoverFeature.prototype.postConstruct = function () {
this.addMouseHoverListeners();
};
HoverFeature.prototype.addMouseHoverListeners = function () {
this.addManagedListener(this.element, 'mouseout', this.onMouseOut.bind(this));
this.addManagedListener(this.element, 'mouseover', this.onMouseOver.bind(this));
};
HoverFeature.prototype.onMouseOut = function () {
this.columnHoverService.clearMouseOver();
};
HoverFeature.prototype.onMouseOver = function () {
this.columnHoverService.setMouseOver(this.columns);
};
__decorate([
context_1.Autowired('columnHoverService')
], HoverFeature.prototype, "columnHoverService", void 0);
__decorate([
context_1.PostConstruct
], HoverFeature.prototype, "postConstruct", null);
return HoverFeature;
}(beanStub_1.BeanStub));
exports.HoverFeature = HoverFeature;
//# sourceMappingURL=hoverFeature.js.map
|
import React from "react";
const AuthUserContext = React.createContext(null); // default starting value
/**
* Higher order component for consuming auth user
*/
export const withAuthUser = function(Component) {
return function(props) {
return (
<AuthUserContext.Consumer>
{context => (
<Component
{...props}
authUser={context.authUser}
authDataFetched={context.authDataFetched}
/>
)}
</AuthUserContext.Consumer>
);
};
};
export default AuthUserContext;
|
// Load the http module to create an http server.
var http = require('http');
var steem = require('steem');
var store = require('data-store')('my-app');
var sleep = require('sleep');
var tarot = require('./tarot.js');
var cloudinary = require('cloudinary');
cloudinary.config({
cloud_name: process.env.cloud_name,
api_key: process.env.api_key,
api_secret: process.env.api_secret
});
// Create a function to handle every HTTP request
function handler(req, res){
res.setHeader('Content-Type', 'text/html');
res.writeHead(200);
//console.log('test',tarot.threeCardReading());
//res.end("<html><body><h1>Hello</h1></body></html>");
var r1 = "<html><body><h1>";
var r2 = "</h1></body></html>";
var r3 = tarot.threeCardReading();
var answer = r1+r2+r3;
res.end(answer);
};
//steem test
/*
steem.api.getState('@jeaimetu',function(err, result){
console.log(err, result);
});
*/
//After writing, this needs cool down time to create the block chain
function writingReply(child_permlink,pAuthor){
var private_posting_wif = process.env.pass;
var parent_author = pAuthor;
//var parent_author = '';
var parent_permlink = child_permlink;
var json_metadata = '';
//check author have . then remove that
var parent_author_permlink = pAuthor;
var dotCheck = ".";
if(pAuthor.indexOf(dotCheck) != -1){
//replace .
var parent_author_permlink = pAuthor.replace(".","dot");
}
const permlink = steem.formatter.commentPermlink(parent_author_permlink, parent_permlink)
//const permlink = steem.formatter.commentPermlink('jeaimetu', parent_permlink)
var tarotResult = tarot.randomCard();
var i = tarotResult.indexOf("##: ");
var a = tarotResult.substr(i+4,tarotResult.length-1);
a.replace(/\s/g,'');
console.log("image name :", a,":");
var b = tarotResult.substr(0,i-1);
var content = '<table><tr><td> ';
//content += cloudinary.image("00_Fool.jpg", {alt : "Test"})
console.log(cloudinary.image(a, {alt : "Test"}));
//content += cloudinary.image(a, {alt : "Test"}, {width : 50})
content += cloudinary.image(a, {width : 100, height : 200, crop : 'fit' })
content += '</td><td><p><strong>안녕하세요. 타로점 결과 입니다. 많이 사용해 주세요.</strong></p><hr><p>';
//content += tarot.randomCard();
b = b.replace("/","/\n");
content += b;
content += '</td></tr></table>';
steem.broadcast.comment (
private_posting_wif, // Steemit.com Wallet -> Permissions -> Show Private Key (for Posting)
parent_author, // empty for new blog post
parent_permlink, // main tag for new blog post
'jeaimetu', // same user the private_posting_key is for
permlink, // a slug (lowercase 'a'-'z', '0'-'9', and '-', min 1 character, max 255 characters)
'', // human-readable title
content, // body of the post or comment
json_metadata, // arbitrary metadata
function (err, result){
if(err)
console.log('Failure', err);
else
console.log('Success');
}
);
}
function checkReplies() {
steem.api.getContentReplies('jeaimetu', process.env.link, function(err, result){
//console.log(err, result);
result.forEach((num, idx)=> {
//sleep.sleep(21); //do not work what I intended
console.log(num.body);
if(num.children == 0){
var string = "타로";
if(num.body.indexOf(string) != -1){
console.log('I will make reply for this');
console.log('call writingReply for ', idx);
writingReply(num.permlink, num.author);
}
}
});
});
}
// according to steemit github
// https://github.com/steemit/steem/blob/master/libraries/protocol/include/steemit/protocol/config.hpp
// #define STEEMIT_MIN_REPLY_INTERVAL (fc::seconds(20)) // 20 seconds
// So I safely add 60secs interval consider delay time.
setInterval(checkReplies, 25000);
async function getFullAccountHistory(){
const end = 9999 * 5;
const step = 9999;
for(let start = 99999999;start >= step;start -= step){
result = await steem.api.getAccountHistoryAsync("jeaimetu", start, step);
console.log(result);
}
return result;
}
steem.api.getAccountHistory('jeaimetu',1,1,(err, result) => {
console.log("1 1 test");
console.log(result[0][0]);
console.log(result[0][1]);
console.log(result);
});
steem.api.getAccountHistory('jeaimetu',2,1,(err, result) => {
console.log("2 1 test");
console.log(result[0][0]);
console.log(result[0][1]);
console.log(result);
});
steem.api.getAccountHistory('jeaimetu',3,1,(err, result) => {
console.log("3 1 test");
console.log(result[0][0]);
console.log(result[0][1]);
console.log(result);
});
steem.api.getAccountHistory('jeaimetu',2,2,(err, result) => {
console.log("2 2 test");
console.log(result[0][0]);
console.log(result[0][1]);
console.log(result);
});
steem.api.getAccountHistory('jeaimetu',-1,0, (err, result) => {
limit = result[0][0];
console.log("Limit :", limit);
});
/*
getFullAccountHistory().then(v => {
console.log(v);
});
*/
/* ToDo
1. get more than 9999 records
2. extract number from "x.xxx STEEM" and convert it to number
*/
//do {
/*
async function getFullAccountHistory(){
const end = 9999 * 10;
const step = 9999;
var amount = 0;
for(let start = 0; start < end;start += step) {
await steem.api.getAccountHistoryAsync('jeaimetu', start, step).each((history: any[]) => {
const result = history;
}
//console.log(err, result);
const WALLET_FILTER = 'transfer'
let transfers = result.filter( tx => tx[1].op[0] === WALLET_FILTER )
//console.log(transfers)
transfers.forEach((tx) => {
if(tx[1].op[1].from == "upbit-exchange" || tx[1].op[1].from == "korbit2" || tx[1].op[1].from == "gopax"){
console.log(tx[1].op[0], tx[1].op[1].from, tx[1].op[1].amount)
let money = tx[1].op[1].amount.split(" ");
amount += parseInt(money[0],10);}
}
console.log("total amount from exchange", amount);
if(result.length < 1)
return;
});
} //end of for
//} while(result.length != 0)
} //end of async function
*/
//did not return all images. This may depends on the folder
//cloudinary.v2.api.resources(function(error, result){console.log(result)});
//did not return nothing
//cloudinary.v2.api.resources({type: 'upload'}, function(error, result){});
cloudinary.v2.search.expression("*00_Fool.jpg").execute(function(error, result) {
console.log("cloudinary fool search");
console.log(result)});
//getFullAccountHistory();
/* data store test
store.set('a','test string');
console.log(store.get('a'));
*/
/*
//writing reply
var private_posting_wif = process.env.pass;
var parent_author = 'jeaimetu';
var parent_permlink = 're-jeaimetu-6c1klq-stereotype-20180317t185909244z';
var json_metadata = '';
const permlink = steem.formatter.commentPermlink(parent_author, parent_permlink)
steem.broadcast.comment (
private_posting_wif, // Steemit.com Wallet -> Permissions -> Show Private Key (for Posting)
'jeaimetu', // empty for new blog post
parent_permlink, // main tag for new blog post
'jeaimetu', // same user the private_posting_key is for
permlink, // a slug (lowercase 'a'-'z', '0'-'9', and '-', min 1 character, max 255 characters)
'', // human-readable title
'Posting test through api', // body of the post or comment
json_metadata // arbitrary metadata
)
console.log('getContet test');
steem.api.getContent('jeaimetu','2-happenchange-investing-chapter-2',function(err, result){
console.log(err, result);
console.log(result.active_votes[0].voters);
});
*/
/*
console.log('getActiveVotes test');
var res;
var res_formatted = '';;
var pLink = process.env.link;
steem.api.getActiveVotes('jeaimetu',pLink, function(err, result) {
console.log(err, result);
console.log('for each test');
res = result;
res.forEach((num, index) => {
console.log(num.voter);
res_formatted += '\@';
res_formatted += num.voter;
res_formatted += '\,';
});
console.log(res_formatted);
});
*/
/* this get all replies, so does not work for me */
/*
console.log('reply retrieve test');
steem.api.getRepliesByLastUpdate('jeaimetu', 're-jeaimetu-6c1klq-stereotype-20180317t185909244z', 10, function(err, result) {
console.log(err, result);
});
*/
/*
*/
/* this only get main post except replies */
/*
console.log('getDiscussionsByAuthorBeforeDate test');
steem.api.getDiscussionsByAuthorBeforeDate('jeaimetu', '6c1klq-stereotype', "2018-03-18T11:55:18", 10, function(err, result) {
console.log(err, result);
});
*/
// Create a server that invokes the `handler` function upon receiving a request
http.createServer(handler).listen(process.env.PORT, function(err){
if(err){
console.log('Error starting http server');
} else {
console.log("Server running at http://127.0.0.1:8000/ or http://localhost:8000/");
};
});
|
/**
* Used to get precomputed attr container heights(based on renderType & filter) for Filter Panel
*/
angular.module('common')
.service('attrUIService', [function() {
'use strict';
/*************************************
*************** API ******************
**************************************/
this.getAttrFPHeight= getAttrFPHeight;
/*************************************
********* Local Data *****************
**************************************/
// Fixed heights info for attrs in filter panel
// var attrRenderTypesMap = AttrInfoService.getRenderTypesMap();
//
// Fixed attr heights acc. to render types
// Only for attrs having distributions
//
var renderersHeightMap = {
piechart: 300,
histogram: 100,
densitybar: 30,
categorybar: 30,
categorylist: 38, //Indiv. bar height
tags: 39, //Indiv. bar height,
'tag-cloud': 22/2 //Indiv. bar height(divided by no. of tags per row)
};
var rendererMarginMap = {
piechart: 10,
histogram: 10,
densitybar: 20,
categorybar: 20,
categorylist: 55,
tags: 55,
'tag-cloud': 30
};
var renderTypeFilterMap = {
piechart: 'checkboxFilter',
histogram: 'rangeFilter',
densitybar: 'rangeFilter',
categorybar: 'checkboxFilter'
};
var filtersHeightMap = {
checkboxFilter: 40, // Individual filter item height
rangeFilter: 20
};
var filtersMarginMap = {
checkboxFilter:10,
rangeFilter: 20
};
// var containerMargin = 20; //Top margin only
var attrTitleHeight = 36; //Height
var attrTextHeight = 20; // For type strings only
var moreBtnHeight = 36;
var nonRendHeight = attrTitleHeight; //container margin not being used currently
/*************************************
********* Core Functions *************
**************************************/
function getAttrFPHeight(attrInfo, showFilter) {
var renderType = attrInfo.attr.renderType,
attrType = attrInfo.attr.attrType,
attrValsCount = attrInfo.values.length,
rendererHeight = 0,
filterHeight = 0,
filterMarginHeight = 0,
filter,
itemHeight;
// Detect correct rendertype for density bar renderer
if(renderType == 'densitybar') {
if(attrInfo.isTag) {
renderType = 'tags';
}
else {
renderType = attrInfo.isNumeric ? 'densitybar' : 'categorybar';
}
}
if(renderType == 'categorylist' || renderType == 'tag-cloud') {
rendererHeight = renderersHeightMap[renderType] * (attrValsCount >= 10 ? 10 : attrValsCount );
}
else if(renderType == 'tags') {
rendererHeight = renderersHeightMap[renderType] * (attrValsCount >= 5 ? 5 : attrValsCount );
}
else if(renderType == 'histogram' && attrInfo.attr.attrType == 'timestamp') {
rendererHeight = renderersHeightMap[renderType] + 40; //extra bottom margin for timestamp
}
else {
rendererHeight = renderersHeightMap[renderType] || 0;
}
rendererHeight += rendererMarginMap[renderType];
if(showFilter) {
filter = renderTypeFilterMap[renderType];
if(filter == 'checkboxFilter') {
var filterValsCount = attrInfo.values.length;
filterHeight = filterValsCount < 6 ? filtersHeightMap[filter]*filterValsCount : (5*filtersHeightMap[filter] + moreBtnHeight);
}
else {
filterHeight = filtersHeightMap[filter];
}
filterHeight = filterHeight || 0;
filterMarginHeight = filtersMarginMap[filter] || 0;
}
itemHeight = nonRendHeight + rendererHeight + filterHeight + filterMarginHeight;
if(attrType == 'string' || renderType == 'tags') {
itemHeight += attrTextHeight;
}
return itemHeight;
}
}
]);
|
import React, { memo, useMemo } from "react";
import { StyleSheet, View } from "react-native";
import PropTypes from "prop-types";
const Circle = memo(({ color, normalColor, fill, x, y, r, inner, outer }) => {
const _styleContainer = useMemo(
() => [
styles.outer,
{
left: x - r,
top: y - r,
width: 2 * r,
height: 2 * r,
borderRadius: r,
},
{ borderColor: normalColor },
fill && { borderColor: color },
!outer && { borderWidth: 0 },
],
[x, r, y, normalColor, color, fill, outer],
);
const _styleIner = useMemo(
() => [
!outer && styles.inner,
{ width: (2 * r) / 3, height: (2 * r) / 3, borderRadius: r / 3 },
fill && { backgroundColor: color },
],
[r, outer, fill, color],
);
return (
<View style={_styleContainer}>{inner && <View style={_styleIner} />}</View>
);
});
Circle.propTypes = {
color: PropTypes.string,
fill: PropTypes.bool,
x: PropTypes.number,
y: PropTypes.number,
r: PropTypes.number,
inner: PropTypes.bool,
outer: PropTypes.bool,
};
Circle.defaultProps = {
inner: true,
outer: true,
};
const styles = StyleSheet.create({
outer: {
position: "absolute",
borderColor: "#8E91A8",
borderWidth: 2,
alignItems: "center",
justifyContent: "center",
backgroundColor: "#1e1e1e",
},
inner: {
backgroundColor: "#8E91A8",
},
});
export default Circle;
module.exports = Circle; // for compatible with require only
|
export const socialAngularOutline = {"viewBox":"0 0 512 512","children":[{"name":"g","attribs":{},"children":[{"name":"path","attribs":{"d":"M255.982,64l187.967,69.105l-39.17,230.389l-148.881,79.949l-148.812-80.051L68.031,133.11L255.982,64 M255.981,32L32,112\r\n\t\tl46.12,272L256,480l177.75-96L480,112L255.981,32L255.981,32z"},"children":[{"name":"path","attribs":{"d":"M255.982,64l187.967,69.105l-39.17,230.389l-148.881,79.949l-148.812-80.051L68.031,133.11L255.982,64 M255.981,32L32,112\r\n\t\tl46.12,272L256,480l177.75-96L480,112L255.981,32L255.981,32z"},"children":[]}]},{"name":"path","attribs":{"d":"M344,352h40L256,72L128,352h40l26.584-56h122.827L344,352z M213.573,256l42.419-89.356L298.419,256H213.573z"},"children":[{"name":"path","attribs":{"d":"M344,352h40L256,72L128,352h40l26.584-56h122.827L344,352z M213.573,256l42.419-89.356L298.419,256H213.573z"},"children":[]}]}]}]};
|
//>>built
define("dojox/data/SnapLogicStore",["dojo","dojox","dojo/io/script","dojo/data/util/sorter"],function(_1,_2){
_1.declare("dojox.data.SnapLogicStore",null,{Parts:{DATA:"data",COUNT:"count"},url:"",constructor:function(_3){
if(_3.url){
this.url=_3.url;
}
this._parameters=_3.parameters;
},_assertIsItem:function(_4){
if(!this.isItem(_4)){
throw new Error("dojox.data.SnapLogicStore: a function was passed an item argument that was not an item");
}
},_assertIsAttribute:function(_5){
if(typeof _5!=="string"){
throw new Error("dojox.data.SnapLogicStore: a function was passed an attribute argument that was not an attribute name string");
}
},getFeatures:function(){
return {"dojo.data.api.Read":true};
},getValue:function(_6,_7,_8){
this._assertIsItem(_6);
this._assertIsAttribute(_7);
var i=_1.indexOf(_6.attributes,_7);
if(i!==-1){
return _6.values[i];
}
return _8;
},getAttributes:function(_9){
this._assertIsItem(_9);
return _9.attributes;
},hasAttribute:function(_a,_b){
this._assertIsItem(_a);
this._assertIsAttribute(_b);
for(var i=0;i<_a.attributes.length;++i){
if(_b==_a.attributes[i]){
return true;
}
}
return false;
},isItemLoaded:function(_c){
return this.isItem(_c);
},loadItem:function(_d){
},getLabel:function(_e){
return undefined;
},getLabelAttributes:function(_f){
return null;
},containsValue:function(_10,_11,_12){
return this.getValue(_10,_11)===_12;
},getValues:function(_13,_14){
this._assertIsItem(_13);
this._assertIsAttribute(_14);
var i=_1.indexOf(_13.attributes,_14);
if(i!==-1){
return [_13.values[i]];
}
return [];
},isItem:function(_15){
if(_15&&_15._store===this){
return true;
}
return false;
},close:function(_16){
},_fetchHandler:function(_17){
var _18=_17.scope||_1.global;
if(_17.onBegin){
_17.onBegin.call(_18,_17._countResponse[0],_17);
}
if(_17.onItem||_17.onComplete){
var _19=_17._dataResponse;
if(!_19.length){
_17.onError.call(_18,new Error("dojox.data.SnapLogicStore: invalid response of length 0"),_17);
return;
}else{
if(_17.query!="record count"){
var _1a=_19.shift();
var _1b=[];
for(var i=0;i<_19.length;++i){
if(_17._aborted){
break;
}
_1b.push({attributes:_1a,values:_19[i],_store:this});
}
if(_17.sort&&!_17._aborted){
_1b.sort(_1.data.util.sorter.createSortFunction(_17.sort,self));
}
}else{
_1b=[({attributes:["count"],values:_19,_store:this})];
}
}
if(_17.onItem){
for(var i=0;i<_1b.length;++i){
if(_17._aborted){
break;
}
_17.onItem.call(_18,_1b[i],_17);
}
_1b=null;
}
if(_17.onComplete&&!_17._aborted){
_17.onComplete.call(_18,_1b,_17);
}
}
},_partHandler:function(_1c,_1d,_1e){
if(_1e instanceof Error){
if(_1d==this.Parts.DATA){
_1c._dataHandle=null;
}else{
_1c._countHandle=null;
}
_1c._aborted=true;
if(_1c.onError){
_1c.onError.call(_1c.scope,_1e,_1c);
}
}else{
if(_1c._aborted){
return;
}
if(_1d==this.Parts.DATA){
_1c._dataResponse=_1e;
}else{
_1c._countResponse=_1e;
}
if((!_1c._dataHandle||_1c._dataResponse!==null)&&(!_1c._countHandle||_1c._countResponse!==null)){
this._fetchHandler(_1c);
}
}
},fetch:function(_1f){
_1f._countResponse=null;
_1f._dataResponse=null;
_1f._aborted=false;
_1f.abort=function(){
if(!_1f._aborted){
_1f._aborted=true;
if(_1f._dataHandle&&_1f._dataHandle.cancel){
_1f._dataHandle.cancel();
}
if(_1f._countHandle&&_1f._countHandle.cancel){
_1f._countHandle.cancel();
}
}
};
if(_1f.onItem||_1f.onComplete){
var _20=this._parameters||{};
if(_1f.start){
if(_1f.start<0){
throw new Error("dojox.data.SnapLogicStore: request start value must be 0 or greater");
}
_20["sn.start"]=_1f.start+1;
}
if(_1f.count){
if(_1f.count<0){
throw new Error("dojox.data.SnapLogicStore: request count value 0 or greater");
}
_20["sn.limit"]=_1f.count;
}
_20["sn.content_type"]="application/javascript";
var _21=this;
var _22=function(_23,_24){
if(_23 instanceof Error){
_21._fetchHandler(_23,_1f);
}
};
var _25={url:this.url,content:_20,timeout:60000,callbackParamName:"sn.stream_header",handle:_1.hitch(this,"_partHandler",_1f,this.Parts.DATA)};
_1f._dataHandle=_1.io.script.get(_25);
}
if(_1f.onBegin){
var _20={};
_20["sn.count"]="records";
_20["sn.content_type"]="application/javascript";
var _25={url:this.url,content:_20,timeout:60000,callbackParamName:"sn.stream_header",handle:_1.hitch(this,"_partHandler",_1f,this.Parts.COUNT)};
_1f._countHandle=_1.io.script.get(_25);
}
return _1f;
}});
return _2.data.SnapLogicStore;
});
|
function fn(){
// 可能函数中抛出了 同步错误 要通过try-catch 捕获异常
// throw new Error('err');
return new Promise((resolve,reject)=>{
setTimeout(() => {
reject('xxx');
}, 3000);
})
}
Promise.try = function(callback){
return new Promise((resolve,reject)=>{
// Promise.resolve 只能返回一个成功的promise
return Promise.resolve(callback()).then(resolve,reject);
})
}
fn().then((data)=>{
console.log(data,'---');
},err=>{
console.log('err:'+err);
});
|
import React, { useEffect, useState } from "react";
import axios from "axios";
import WrappedMap from "../components/Map";
import NavigationBar from "../components/NavigationBar";
import InfoCard from "../components/InfoCard";
import Header from "../components/Header";
import Logo from "../images/LogoAQ1.svg";
const defaultTitle =
{
name: 'Arcade Quest',
url: '*'
}
const defaultGames = [
{
game: 'Donkey Kong.',
type: 'arcade'
},
{
game: 'Crystal Castle.',
type: 'arcade'
},
{
game: 'Galaga.',
type: 'arcade'
},
{
game: 'Gaulent.',
type: 'arcade'
},
]
function Main() {
const [position, setPosition] = useState({ lat: 47.6101, lng: -122.2015 });
const [resOther, setOther] = useState([]);
const [resArcade, setArcade] = useState([]);
const [resBar, setBar] = useState([]);
const [newRes, setNewRes] = useState([]);
const [newSrc, setNewsrc] = useState(Logo);
const [newTitle, setTitle] = useState(defaultTitle);
const [newGame, setGame] = useState(defaultGames)
// const [param, setParam] = useState(0)
// const [count , setcount] = useState(0)
// console.log(location)
function handleMarkerClick(mark) {
// console.log(mark);
axios.get(`/api/businessArcades/${mark}`).then((response) => {
// console.log(response.data.photoRef);
setNewsrc(
`https://maps.googleapis.com/maps/api/place/photo?maxwidth=400&photoreference=${response.data.photoRef}&key=AIzaSyCAGBQZGrklbGFY3rBelRBQ_m0yzc4pd5w`
);
// console.log(response.data.Arcades)
setTitle(response.data)
setGame(response.data.Arcades)
});
}
useEffect(() => {
axios
.get(`/api/allBusinesses`)
.then((response) => {
// console.log(response.data);
const others = response.data.filter(
(business) => business.type === "other"
);
const arcade = response.data.filter(
(business) => business.type === "arcade"
);
const bars = response.data.filter(
(business) => business.type === "bar"
);
const restaurant = response.data.filter(
(business) => business.type === "restaurant"
);
setOther(others);
setArcade(arcade);
setBar(bars);
setNewRes(restaurant);
// console.log(response.data);
})
.catch((err) => {
console.log(err);
});
navigator.geolocation.getCurrentPosition((location) => {
let { latitude, longitude } = location.coords;
setPosition({ lat: latitude, lng: longitude });
});
}, []);
return (
<div>
<NavigationBar></NavigationBar>
<div>
<div className="wrapper">
<Header></Header>
<div className="container-one">
<div className="map">
<div style={{ width: "700px", height: "550px" }}>
<WrappedMap
res={newRes}
other={resOther}
arcades={resArcade}
bar={resBar}
handleClick={handleMarkerClick}
// showNew={newMarker}
position={position}
googleMapURL={
"https://maps.googleapis.com/maps/api/js?v=3.exp&libraries=geometry,drawing,places&key=AIzaSyCAGBQZGrklbGFY3rBelRBQ_m0yzc4pd5w"
}
loadingElement={<div style={{ height: "100%" }} />}
containerElement={<div style={{ height: "100%" }} />}
mapElement={<div style={{ height: "100%" }} />}
/>
</div>
</div>
<InfoCard src={newSrc}
title={newTitle}
game={newGame}
> </InfoCard>
</div>
</div>
</div>
</div>
);
}
export default Main;
|
import ActionTypes from '../constants/FeedReaderConstants'
import ActionDispatcher from '../dispatcher/ActionDispatcher'
import WebAPIUtils from '../utils/WebAPIUtils'
module.exports = {
fetchFeedEntries: (feed) => {
WebAPIUtils.fetchFeedEntries(feed.id).then((newFeed) => {
let next = ''
if ('next' in newFeed._links) {
next = newFeed._links.next.href
}
ActionDispatcher.dispatch({
type: ActionTypes.GET_FEED,
feed: newFeed,
next,
})
})
},
fetchEntries: (predicate) => {
WebAPIUtils.fetchEntries(predicate).then(
(response) => {
const entries = response._embedded.entries
let next = ''
if ('next' in response._links) {
next = response._links.next.href
}
ActionDispatcher.dispatch({
type: ActionTypes.GET_ENTRY_LIST,
entries,
next,
predicate,
})
},
ex => console.log(`Couldn't load feed: ${ex.message}`))
},
fetchMoreEntries: (url) => {
WebAPIUtils.getRequest(url).then(
(response) => {
const entries = response._embedded.entries
let next = ''
if ('next' in response._links) {
next = response._links.next.href
}
ActionDispatcher.dispatch({
type: ActionTypes.ADD_ENTRIES,
entries,
next,
})
},
ex => console.log(`Couldn't load feed: ${ex.message}`))
},
changeActiveEntry: entry =>
ActionDispatcher.dispatch({
type: ActionTypes.CHANGE_ACTIVE_ENTRY,
entry,
}),
changeEntryStatus: (entry, newStatus) =>
WebAPIUtils.changeEntryStatus(entry.feed_id, entry.id, newStatus)
.then(feed => (
ActionDispatcher.dispatch({
type: ActionTypes.CHANGE_ENTRY_STATUS,
feed,
})
), ex => console.log(`Couldn't update entry: ${ex.message}`)),
}
|
import fs from 'fs';
import path from 'path';
export const readDir = dir => new Promise((resolve, reject) => {
fs.readdir(dir, (err, files) => {
if (err) {
reject(err);
} else {
resolve(files);
}
});
});
export const isDir = spath => fs.statSync(spath).isDirectory();
export const isExisted = spath => fs.existsSync(spath);
export const resolve = (...params) => path.resolve(...params);
|
var classQVideoFrameHelpers =
[
[ "cloneAndroidFrame", "classQVideoFrameHelpers.html#a33f8069d39bc1b8c4e84560874c81b3f", null ],
[ "empty", "classQVideoFrameHelpers.html#a8adf8dec26da8684dfc332fddad44ca9", null ],
[ "halfYUV", "classQVideoFrameHelpers.html#ab000e89dcb564530a63f893d9201b5fe", null ],
[ "supportedPixelFormats", "classQVideoFrameHelpers.html#a10df65b321c9dfa9ca2bf9d1ba7a3f58", null ],
[ "VideoFrameToImage", "classQVideoFrameHelpers.html#a9f056763eb58f2a38493edd755b06e4b", null ]
];
|
import styled from 'styled-components';
import { transparentize } from 'polished';
export const Container = styled.div`
position: relative;
background-color: ${({ theme: { palette } }) => palette.white};
overflow-y: auto;
max-height: 100%;
width: 100%;
`;
export const List = styled.ul`
width: 100%;
list-style: none;
overflow-y: auto;
transform-origin: 50% 0%;
`;
export const Option = styled.li`
display: flex;
align-items: center;
cursor: pointer;
background-color: ${({ isChecked, theme: { palette } }) =>
isChecked ? palette.veryLightGrey : 'transparent'};
color: ${({ theme: { palette } }) => palette.spaceGrey};
:hover {
background: ${({ theme: { palette } }) => palette.veryLightGrey};
}
`;
export const CheckboxOption = styled(Option)`
padding: 0.8rem 1.6rem;
`;
export const RadioOption = styled(Option)`
padding: 0.8rem 1.6rem;
`;
export const SimpleOption = styled(Option)`
padding: 0.8rem 1.6rem;
color: ${({ isChecked, theme: { palette } }) =>
isChecked ? palette.primary.default : palette.spaceGrey};
background-color: ${({ isChecked, theme: { palette } }) =>
isChecked ? palette.veryLightGrey : 'transparent'};
`;
export const NoResultDefaultComponent = styled.div`
padding: 0.8rem 1.6rem;
`;
export const SearchInputContainer = styled.div`
position: sticky;
z-index: 1;
top: 0;
padding: 1.6rem;
padding-bottom: 0;
margin-bottom: 1rem;
background: ${({ theme: { palette } }) => palette.white};
&:after {
position: absolute;
content: '';
top: 100%;
left: 0;
right: 0;
height: 1rem;
background: ${({ theme: { palette } }) =>
`linear-gradient(to bottom, ${palette.white}, ${transparentize(1, palette.white)})`};
}
`;
export const SearchInput = styled.div`
width: 100%;
border: 1px solid ${({ theme: { palette } }) => palette.lightGrey};
border-radius: 0.4rem;
background: ${({ theme: { palette } }) => palette.veryLightGrey};
& > div {
background: ${({ theme: { palette } }) => palette.veryLightGrey};
height: 3.2rem;
}
& input {
background: ${({ theme: { palette } }) => palette.veryLightGrey};
font-size: 1.2rem;
&::placeholder {
font-size: 1.2rem;
}
}
`;
|
define("ember-data/attr", ["exports", "ember", "ember-data/-private/debug"], function (exports, _ember, _emberDataPrivateDebug) {
"use strict";
exports["default"] = attr;
/**
@module ember-data
*/
function getDefaultValue(record, options, key) {
if (typeof options.defaultValue === "function") {
return options.defaultValue.apply(null, arguments);
} else {
var defaultValue = options.defaultValue;
(0, _emberDataPrivateDebug.deprecate)("Non primitive defaultValues are deprecated because they are shared between all instances. If you would like to use a complex object as a default value please provide a function that returns the complex object.", typeof defaultValue !== 'object' || defaultValue === null, {
id: 'ds.defaultValue.complex-object',
until: '3.0.0'
});
return defaultValue;
}
}
function hasValue(record, key) {
return key in record._attributes || key in record._inFlightAttributes || key in record._data;
}
function getValue(record, key) {
if (key in record._attributes) {
return record._attributes[key];
} else if (key in record._inFlightAttributes) {
return record._inFlightAttributes[key];
} else {
return record._data[key];
}
}
/**
`DS.attr` defines an attribute on a [DS.Model](/api/data/classes/DS.Model.html).
By default, attributes are passed through as-is, however you can specify an
optional type to have the value automatically transformed.
Ember Data ships with four basic transform types: `string`, `number`,
`boolean` and `date`. You can define your own transforms by subclassing
[DS.Transform](/api/data/classes/DS.Transform.html).
Note that you cannot use `attr` to define an attribute of `id`.
`DS.attr` takes an optional hash as a second parameter, currently
supported options are:
- `defaultValue`: Pass a string or a function to be called to set the attribute
to a default value if none is supplied.
Example
```app/models/user.js
import DS from 'ember-data';
export default DS.Model.extend({
username: DS.attr('string'),
email: DS.attr('string'),
verified: DS.attr('boolean', { defaultValue: false })
});
```
Default value can also be a function. This is useful it you want to return
a new object for each attribute.
```app/models/user.js
import DS from 'ember-data';
export default DS.Model.extend({
username: attr('string'),
email: attr('string'),
settings: attr({defaultValue: function() {
return {};
}})
});
```
@namespace
@method attr
@for DS
@param {String} type the attribute type
@param {Object} options a hash of options
@return {Attribute}
*/
function attr(type, options) {
if (typeof type === 'object') {
options = type;
type = undefined;
} else {
options = options || {};
}
var meta = {
type: type,
isAttribute: true,
options: options
};
return _ember["default"].computed({
get: function get(key) {
var internalModel = this._internalModel;
if (hasValue(internalModel, key)) {
return getValue(internalModel, key);
} else {
return getDefaultValue(this, options, key);
}
},
set: function set(key, value) {
var internalModel = this._internalModel;
var oldValue = getValue(internalModel, key);
if (value !== oldValue) {
// Add the new value to the changed attributes hash; it will get deleted by
// the 'didSetProperty' handler if it is no different from the original value
internalModel._attributes[key] = value;
this._internalModel.send('didSetProperty', {
name: key,
oldValue: oldValue,
originalValue: internalModel._data[key],
value: value
});
}
return value;
}
}).meta(meta);
}
// TODO add to documentation of `attr` function above, once this feature is added
// /**
// * The `options` hash is passed as second argument to a transforms'
// * `serialize` and `deserialize` method. This allows to configure a
// * transformation and adapt the corresponding value, based on the config:
// *
// * ```app/models/post.js
// * export default DS.Model.extend({
// * text: DS.attr('text', {
// * uppercase: true
// * })
// * });
// * ```
// *
// * ```app/transforms/text.js
// * export default DS.Transform.extend({
// * serialize: function(value, options) {
// * if (options.uppercase) {
// * return value.toUpperCase();
// * }
// *
// * return value;
// * },
// *
// * deserialize: function(value) {
// * return value;
// * }
// * })
// * ```
// *
// */
});
|
import React from 'react';
const Product = () => (
<div>
This is from Product component.
</div>
);
export default Product;
|
console.log(typeof a);
a = 42;
console.log(typeof a);
function a() {}
console.log(typeof a);
|
function main() {
function v1(v2,v3,v4,v5) {
const v7 = [SharedArrayBuffer];
const v8 = v7.indexOf();
v8.__proto__ = Map;
for (let v12 = 0; v12 < 100; v12++) {
let v14 = undefined;
}
}
const v15 = v1();
const v16 = v1();
}
%NeverOptimizeFunction(main);
main();
|
require('babel-register');
const gulpConfig = require('../gulp/config').default;
exports.config = {
allScriptsTimeout: 11000,
baseUrl: `http://localhost:${gulpConfig.testPort}/`,
capabilities: {
browserName: 'chrome',
'tunnel-identifier': process.env.TRAVIS_JOB_NUMBER,
build: process.env.TRAVIS_BUILD_NUMBER,
name: 'Protractor Tests'
},
framework: 'jasmine2',
jasmineNodeOpts: {
isVerbose: false,
showColors: true,
includeStackTrace: true,
defaultTimeoutInterval: 30000
},
specs: [
'e2e/**/*.js'
],
sauceUser: process.env.SAUCE_USERNAME,
sauceKey: process.env.SAUCE_ACCESS_KEY
};
|
/* eslint-disable no-undef */
/* eslint-disable no-unused-vars */
/* eslint-disable no-console */
import React, { useState, useEffect } from "react";
import axios from "axios";
import { getUserToken } from "../../../utils/authUtils";
import { AuthUrls } from "../../../constants/urls";
// get list of employees of current user (the manager)
export function retrieveEmployers(setEmployerList) {
axios
// .get("http://localhost:8000/api/employers/", {
.get(AuthUrls.API_EMPLOYERS, {
headers: {
authorization: "Token " + getUserToken(),
},
})
.then((response) => {
setEmployerList(response.data);
})
.catch((error) => {
console.log(error);
console.log(error.response);
});
}
// delete employer
export function deleteEmployer(employer, onClose) {
if (employer.id) {
axios
// .delete(`http://localhost:8000/api/employers/${employer.id}/`, employer, {
.delete(AuthUrls.API_EMPLOYERS + employer.id + "/", employer, {
headers: {
authorization: "Token " + getUserToken(),
},
})
.then((response) => {
onClose();
});
return;
}
}
export function updateEmployer(employer, onSave) {
if (employer.id) {
axios
// .put(`http://localhost:8000/api/employers/${employer.id}/`, employer, {
.put(AuthUrls.API_EMPLOYERS + employer.id + "/", employer, {
headers: {
authorization: "Token " + getUserToken(),
},
})
.then((response) => {
onSave();
})
.catch((error) => {
console.log(error.response);
});
return;
}
}
export function submitEmployer(
employer,
onClose,
setEmailError,
setPasswordError
) {
axios
.post(AuthUrls.API_EMPLOYERS, employer, {
headers: {
authorization: "Token " + getUserToken(),
},
})
.then((response) => {
console.log("handle response");
console.log(response.data);
onClose();
})
.catch((error) => {
const response = error.response;
console.log(response.data);
if (response.data.email) {
setEmailError(response.data.email);
} else {
setEmailError(null);
}
if (response.data.password) {
setPasswordError(response.data.password);
} else {
setPasswordError(null);
}
});
}
|
// ==UserScript==
// @name Expand Short Links
// @description Appends more characters to short link texts in posts and comments so they can be easily seen and clicked on
// @homepage https://github.com/samliew/SO-mod-userscripts
// @author @samliew
// @version 1.4
//
// @include https://*stackoverflow.com/*
// @include https://*serverfault.com/*
// @include https://*superuser.com/*
// @include https://*askubuntu.com/*
// @include https://*mathoverflow.net/*
// @include https://*.stackexchange.com/*
// ==/UserScript==
(function() {
'use strict';
function expandShortLinks() {
$('.js-post-body, .comment-copy').find('a').not('.post-tag').not('.shortlink').filter((i,el) => el.innerText.length > 0 && el.innerText.length <= 2 && el.children.length == 0).addClass('shortlink');
}
function appendStyles() {
const styles = `
<style>
a.shortlink {
font-weight: bold;
color: var(--red-500) !important;
}
a.shortlink:after {
content: '_link';
color :var(--green-400);
font-style: italic;
font-weight: normal;
}
</style>
`;
$('body').append(styles);
}
// On page load
appendStyles();
expandShortLinks();
$(document).ajaxComplete(expandShortLinks);
})();
|
function cargarModal(id){
$.get('cargarModalTDescuentoVenta/'+id,function(response){
$('#id').val(response.id);
$('#descuento').val(response.descuento);
$('#descuento_minimo').val(response.descuento_minimo);
$('#descuento_maximo').val(response.descuento_maximo);
});
}
|
// 导入 Cookies
import Cookies from 'js-cookie'
// 设置 cookie name
const TokenKey = 'Admin-Token'
// 获取 Admin-Token 的 cookie
export function getToken() {
return Cookies.get(TokenKey);
}
// setToken
export function setToken(token) {
return Cookies.set(TokenKey, token);
}
// 移除 token
export function removeToken() {
return Cookies.remove(TokenKey)
}
|
var currentEditableItem;
var oldText;
var currentListItem;
const {
remote
} = require('electron')
const {
Menu,
MenuItem
} = remote
function setupContextMenu(items) {
const contextMenu = new Menu()
_.each(items, function(item){
contextMenu.append(new MenuItem({
label: item.repoName,
click() {
$('#gitRepoUrl').val(item.repoUrl);
}
}))
})
window.addEventListener('contextmenu', (e) => {
e.preventDefault();
var x = e.clientX;
var y = e.clientY;
var el = document.elementFromPoint(x, y);
if ($(el).hasClass('gitRepoUrl')) {
currentListItem = el;
contextMenu.popup({
window: remote.getCurrentWindow()
})
}
}, false)
}
|
/* eslint-disable no-console */
const requireESM = require('esm')(module);
const _cloneDeep = requireESM('lodash-es/cloneDeep').default;
const _extend = requireESM('lodash-es/extend').default;
const _forEach = requireESM('lodash-es/forEach').default;
const _isEmpty = requireESM('lodash-es/isEmpty').default;
const _merge = requireESM('lodash-es/merge').default;
const _toPairs = requireESM('lodash-es/toPairs').default;
const colors = require('colors/safe');
const fs = require('fs');
const glob = require('glob');
const jsonschema = require('jsonschema');
const path = require('path');
const prettyStringify = require('json-stringify-pretty-compact');
const shell = require('shelljs');
const YAML = require('js-yaml');
const fieldSchema = require('./data/presets/schema/field.json');
const presetSchema = require('./data/presets/schema/preset.json');
const suggestions = require('name-suggestion-index/name-suggestions.json');
// fontawesome icons
const fontawesome = require('@fortawesome/fontawesome-svg-core');
const fas = require('@fortawesome/free-solid-svg-icons').fas;
const far = require('@fortawesome/free-regular-svg-icons').far;
const fab = require('@fortawesome/free-brands-svg-icons').fab;
fontawesome.library.add(fas, far, fab);
module.exports = function buildData() {
var building;
return function() {
// Note: even though this function is sync adding
// the `building` variable for consistency and future proofing
if (building) return;
building = true;
console.log('building data');
console.time(colors.green('data built'));
// Create symlinks if necessary.. { 'target': 'source' }
const symlinks = {
'land.html': 'dist/land.html',
img: 'dist/img'
};
for (var target of Object.keys(symlinks)) {
if (!shell.test('-L', target)) {
console.log(
`Creating symlink: ${target} -> ${symlinks[target]}`
);
shell.ln('-sf', symlinks[target], target);
}
}
// Translation strings
var tstrings = {
categories: {},
fields: {},
presets: {}
};
// Font Awesome icons used
var faIcons = {};
// Start clean
shell.rm('-f', [
'data/presets/categories.json',
'data/presets/fields.json',
'data/presets/presets.json',
'data/presets.yaml',
'data/taginfo.json',
'dist/locales/en.json',
'svg/fontawesome/*.svg',
]);
var categories = generateCategories(tstrings, faIcons);
var fields = generateFields(tstrings, faIcons);
var presets = generatePresets(tstrings, faIcons);
var defaults = read('data/presets/defaults.json');
var translations = generateTranslations(fields, presets, tstrings);
var taginfo = generateTaginfo(presets, fields);
// Additional consistency checks
validateCategoryPresets(categories, presets);
validatePresetFields(presets, fields);
validateDefaults(defaults, categories, presets);
// Save individual data files
var tasks = [
writeFileProm(
'data/presets/categories.json',
prettyStringify({ categories: categories })
),
writeFileProm(
'data/presets/fields.json',
prettyStringify({ fields: fields }, { maxLength: 9999 })
),
writeFileProm(
'data/presets/presets.json',
prettyStringify({ presets: presets }, { maxLength: 9999 })
),
writeFileProm('data/presets.yaml', translationsToYAML(translations)),
writeFileProm('data/taginfo.json', prettyStringify(taginfo), { maxLength: 9999 }),
writeEnJson(tstrings),
writeFaIcons(faIcons)
];
return Promise.all(tasks)
.then(function () {
console.timeEnd(colors.green('data built'));
building = false;
})
.catch(function (err) {
console.error(err);
process.exit(1);
});
};
};
function read(f) {
return JSON.parse(fs.readFileSync(f, 'utf8'));
}
function validate(file, instance, schema) {
var validationErrors = jsonschema.validate(instance, schema).errors;
if (validationErrors.length) {
console.error(file + ': ');
validationErrors.forEach(function(error) {
if (error.property) {
console.error(error.property + ' ' + error.message);
} else {
console.error(error);
}
});
process.exit(1);
}
}
function generateCategories(tstrings, faIcons) {
var categories = {};
glob.sync(__dirname + '/data/presets/categories/*.json').forEach(function(file) {
var category = read(file);
var id = 'category-' + path.basename(file, '.json');
tstrings.categories[id] = { name: category.name };
categories[id] = category;
// fontawesome icon, remember for later
if (/^fa[srb]-/.test(category.icon)) {
faIcons[category.icon] = {};
}
});
return categories;
}
function generateFields(tstrings, faIcons) {
var fields = {};
glob.sync(__dirname + '/data/presets/fields/**/*.json').forEach(function(file) {
var field = read(file);
var id = stripLeadingUnderscores(file.match(/presets\/fields\/([^.]*)\.json/)[1]);
validate(file, field, fieldSchema);
var t = tstrings.fields[id] = {
label: field.label
};
if (field.placeholder) {
t.placeholder = field.placeholder;
}
if (field.strings) {
for (var i in field.strings) {
t[i] = field.strings[i];
}
}
fields[id] = field;
// fontawesome icon, remember for later
if (/^fa[srb]-/.test(field.icon)) {
faIcons[field.icon] = {};
}
});
return fields;
}
function suggestionsToPresets(presets) {
var existing = {};
for (var key in suggestions) {
for (var value in suggestions[key]) {
for (var name in suggestions[key][value]) {
var item = key + '/' + value + '/' + name;
var tags = {};
var count = suggestions[key][value][name].count;
if (existing[name] && count > existing[name].count) {
delete presets[existing[name].category];
delete existing[name];
}
if (!existing[name]) {
tags = _extend({name: name.replace(/"/g, '')}, suggestions[key][value][name].tags);
addSuggestion(item, tags, name.replace(/"/g, ''), count);
}
}
}
}
function addSuggestion(category, tags, name, count) {
var tag = category.split('/');
var parent = presets[tag[0] + '/' + tag[1]];
// Hacky code to add healthcare tagging not yet present in name-suggestion-index
// This will be fixed by https://github.com/osmlab/name-suggestion-index/issues/57
if (tag[0] === 'amenity') {
var healthcareTags = {
clinic: 'clinic',
dentist: 'dentist',
doctors: 'doctor',
hospital: 'hospital',
pharmacy: 'pharmacy'
};
if (healthcareTags.hasOwnProperty(tag[1])) {
tags.healthcare = healthcareTags[tag[1]];
}
}
if (!parent) {
console.log('WARN: no preset for suggestion = ' + tag);
return;
}
presets[category.replace(/"/g, '')] = {
tags: parent.tags ? _merge(tags, parent.tags) : tags,
name: name,
icon: parent.icon,
geometry: parent.geometry,
fields: parent.fields,
suggestion: true
};
existing[name] = {
category: category,
count: count
};
}
return presets;
}
function stripLeadingUnderscores(str) {
return str.split('/')
.map(function(s) { return s.replace(/^_/,''); })
.join('/');
}
function generatePresets(tstrings, faIcons) {
var presets = {};
glob.sync(__dirname + '/data/presets/presets/**/*.json').forEach(function(file) {
var preset = read(file);
var id = stripLeadingUnderscores(file.match(/presets\/presets\/([^.]*)\.json/)[1]);
validate(file, preset, presetSchema);
tstrings.presets[id] = {
name: preset.name,
terms: (preset.terms || []).join(',')
};
presets[id] = preset;
// fontawesome icon, remember for later
if (/^fa[srb]-/.test(preset.icon)) {
faIcons[preset.icon] = {};
}
});
presets = _merge(presets, suggestionsToPresets(presets));
return presets;
}
function generateTranslations(fields, presets, tstrings) {
var translations = _cloneDeep(tstrings);
_forEach(translations.fields, function(field, id) {
var f = fields[id];
if (f.keys) {
field['label#'] = _forEach(f.keys).map(function(key) { return key + '=*'; }).join(', ');
if (!_isEmpty(field.options)) {
_forEach(field.options, function(v,k) {
if (id === 'access') {
field.options[k]['title#'] = field.options[k]['description#'] = 'access=' + k;
} else {
field.options[k + '#'] = k + '=yes';
}
});
}
} else if (f.key) {
field['label#'] = f.key + '=*';
if (!_isEmpty(field.options)) {
_forEach(field.options, function(v,k) {
field.options[k + '#'] = f.key + '=' + k;
});
}
}
if (f.placeholder) {
field['placeholder#'] = id + ' field placeholder';
}
});
_forEach(translations.presets, function(preset, id) {
var p = presets[id];
if (!_isEmpty(p.tags))
preset['name#'] = _toPairs(p.tags).map(function(pair) { return pair[0] + '=' + pair[1]; }).join(', ');
if (p.searchable !== false) {
if (p.terms && p.terms.length)
preset['terms#'] = 'terms: ' + p.terms.join();
preset.terms = '<translate with synonyms or related terms for \'' + preset.name + '\', separated by commas>';
} else {
delete preset.terms;
}
});
return translations;
}
function generateTaginfo(presets, fields) {
var taginfo = {
'data_format': 1,
'data_url': 'https://raw.githubusercontent.com/openstreetmap/iD/master/data/taginfo.json',
'project': {
'name': 'iD Editor',
'description': 'Online editor for OSM data.',
'project_url': 'https://github.com/openstreetmap/iD',
'doc_url': 'https://github.com/openstreetmap/iD/blob/master/data/presets/README.md',
'icon_url': 'https://raw.githubusercontent.com/openstreetmap/iD/master/dist/img/logo.png',
'keywords': [
'editor'
]
},
'tags': []
};
_forEach(presets, function(preset) {
if (preset.suggestion) return;
var keys = Object.keys(preset.tags);
var last = keys[keys.length - 1];
var tag = { key: last };
if (!last) return;
if (preset.tags[last] !== '*') {
tag.value = preset.tags[last];
}
if (preset.name) {
tag.description = [ preset.name ];
}
if (preset.geometry) {
setObjectType(tag, preset);
}
// add icon
if (/^maki-/.test(preset.icon)) {
tag.icon_url = 'https://raw.githubusercontent.com/mapbox/maki/master/icons/' +
preset.icon.replace(/^maki-/, '') + '-15.svg?sanitize=true';
} else if (/^temaki-/.test(preset.icon)) {
tag.icon_url = 'https://raw.githubusercontent.com/bhousel/temaki/master/icons/' +
preset.icon.replace(/^temaki-/, '') + '.svg?sanitize=true';
} else if (/^fa[srb]-/.test(preset.icon)) {
tag.icon_url = 'https://raw.githubusercontent.com/openstreetmap/iD/master/svg/fontawesome/' +
preset.icon + '.svg?sanitize=true';
} else if (/^iD-/.test(preset.icon)) {
tag.icon_url = 'https://raw.githubusercontent.com/openstreetmap/iD/master/svg/iD-sprite/presets/' +
preset.icon.replace(/^iD-/, '') + '.svg?sanitize=true';
}
coalesceTags(taginfo, tag);
});
_forEach(fields, function(field) {
var keys = field.keys || [ field.key ] || [];
keys.forEach(function(key) {
if (field.strings && field.strings.options) {
var values = Object.keys(field.strings.options);
values.forEach(function(value) {
if (value === 'undefined' || value === '*' || value === '') return;
var tag = { key: key, value: value };
if (field.label) {
tag.description = [ field.label ];
}
coalesceTags(taginfo, tag);
});
} else {
var tag = { key: key };
if (field.label) {
tag.description = [ field.label ];
}
coalesceTags(taginfo, tag);
}
});
});
_forEach(taginfo.tags, function(elem) {
if (elem.description)
elem.description = elem.description.join(', ');
});
function coalesceTags(taginfo, tag) {
if (!tag.key) return;
var currentTaginfoEntries = taginfo.tags.filter(function(t) {
return (t.key === tag.key && t.value === tag.value);
});
if (currentTaginfoEntries.length === 0) {
taginfo.tags.push(tag);
return;
}
if (!tag.description)
return;
if (!currentTaginfoEntries[0].description) {
currentTaginfoEntries[0].description = tag.description;
return;
}
var isNewDescription = currentTaginfoEntries[0].description
.indexOf(tag.description[0]) === -1;
if (isNewDescription) {
currentTaginfoEntries[0].description.push(tag.description[0]);
}
}
function setObjectType(tag, input) {
tag.object_types = [];
const mapping = {
'point' : 'node',
'vertex' : 'node',
'line' : 'way',
'relation' : 'relation',
'area' : 'area'
};
input.geometry.forEach(function(geom) {
if (tag.object_types.indexOf(mapping[geom]) === -1) {
tag.object_types.push(mapping[geom]);
}
});
}
return taginfo;
}
function validateCategoryPresets(categories, presets) {
_forEach(categories, function(category) {
if (category.members) {
category.members.forEach(function(preset) {
if (presets[preset] === undefined) {
console.error('Unknown preset: ' + preset + ' in category ' + category.name);
process.exit(1);
}
});
}
});
}
function validatePresetFields(presets, fields) {
_forEach(presets, function(preset) {
if (preset.fields) {
preset.fields.forEach(function(field) {
if (fields[field] === undefined) {
console.error('Unknown preset field: ' + field + ' in preset ' + preset.name);
process.exit(1);
}
});
}
});
}
function validateDefaults (defaults, categories, presets) {
_forEach(defaults.defaults, function (members, name) {
members.forEach(function (id) {
if (!presets[id] && !categories[id]) {
console.error('Unknown category or preset: ' + id + ' in default ' + name);
process.exit(1);
}
});
});
}
function translationsToYAML(translations) {
// comment keys end with '#' and should sort immediately before their related key.
function commentFirst(a, b) {
return (a === b + '#') ? -1
: (b === a + '#') ? 1
: (a > b ? 1 : a < b ? -1 : 0);
}
return YAML.safeDump({ en: { presets: translations }}, { sortKeys: commentFirst, lineWidth: -1 })
.replace(/\'.*#\':/g, '#');
}
function writeEnJson(tstrings) {
var readCoreYaml = readFileProm('data/core.yaml', 'utf8');
var readImagery = readFileProm('node_modules/editor-layer-index/i18n/en.yaml', 'utf8');
var readCommunity = readFileProm('node_modules/osm-community-index/i18n/en.yaml', 'utf8');
return Promise.all([readCoreYaml, readImagery, readCommunity]).then(function(data) {
var core = YAML.load(data[0]);
var imagery = YAML.load(data[1]);
var community = YAML.load(data[2]);
var en = _merge(
core,
{ en: { presets: tstrings } },
imagery,
{ en: { community: community.en } }
);
return writeFileProm('dist/locales/en.json', JSON.stringify(en, null, 4));
});
}
function writeFaIcons(faIcons) {
for (var key in faIcons) {
var prefix = key.substring(0, 3); // `fas`, `far`, `fab`
var name = key.substring(4);
var def = fontawesome.findIconDefinition({ prefix: prefix, iconName: name });
writeFileProm('svg/fontawesome/' + key + '.svg', fontawesome.icon(def).html);
}
}
function writeFileProm(path, content) {
return new Promise(function(res, rej) {
fs.writeFile(path, content, function(err) {
if (err) {
return rej(err);
}
res();
});
});
}
function readFileProm(path, options) {
return new Promise(function(res, rej) {
fs.readFile(path, options, function(err, data) {
if (err) {
return rej(err);
}
res(data);
});
});
}
|
/* ==========================================================
* bootstrap-affix.js v2.3.1
* http://twitter.github.com/bootstrap/javascript.html#affix
* ==========================================================
* Copyright 2012 Twitter, Inc.
*
* 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.
* ========================================================== */
!function ($) {
"use strict"; // jshint ;_;
/* AFFIX CLASS DEFINITION
* ====================== */
var Affix = function (element, options) {
this.options = $.extend({}, $.fn.affix.defaults, options)
this.$window = $(window)
.on('scroll.affix.data-api', $.proxy(this.checkPosition, this))
.on('click.affix.data-api', $.proxy(function () {
setTimeout($.proxy(this.checkPosition, this), 1)
}, this))
this.$element = $(element)
this.checkPosition()
}
Affix.prototype.checkPosition = function () {
if (!this.$element.is(':visible')) return
var scrollHeight = $(document).height()
, scrollTop = this.$window.scrollTop()
, position = this.$element.offset()
, offset = this.options.offset
, offsetBottom = offset.bottom
, offsetTop = offset.top
, reset = 'affix affix-top affix-bottom'
, affix
if (typeof offset != 'object') offsetBottom = offsetTop = offset
if (typeof offsetTop == 'function') offsetTop = offset.top()
if (typeof offsetBottom == 'function') offsetBottom = offset.bottom()
affix = this.unpin != null && (scrollTop + this.unpin <= position.top) ?
false : offsetBottom != null && (position.top + this.$element.height() >= scrollHeight - offsetBottom) ?
'bottom' : offsetTop != null && scrollTop <= offsetTop ?
'top' : false
if (this.affixed === affix) return
this.affixed = affix
this.unpin = affix == 'bottom' ? position.top - scrollTop : null
this.$element.removeClass(reset).addClass('affix' + (affix ? '-' + affix : ''))
}
/* AFFIX PLUGIN DEFINITION
* ======================= */
var old = $.fn.affix
$.fn.affix = function (option) {
return this.each(function () {
var $this = $(this)
, data = $this.data('affix')
, options = typeof option == 'object' && option
if (!data) $this.data('affix', (data = new Affix(this, options)))
if (typeof option == 'string') data[option]()
})
}
$.fn.affix.Constructor = Affix
$.fn.affix.defaults = {
offset: 0
}
/* AFFIX NO CONFLICT
* ================= */
$.fn.affix.noConflict = function () {
$.fn.affix = old
return this
}
/* AFFIX DATA-API
* ============== */
$(window).on('load', function () {
$('[data-spy="affix"]').each(function () {
var $spy = $(this)
, data = $spy.data()
data.offset = data.offset || {}
data.offsetBottom && (data.offset.bottom = data.offsetBottom)
data.offsetTop && (data.offset.top = data.offsetTop)
$spy.affix(data)
})
})
}(window.jQuery);
|
define("dijit/_editor/plugins/Print", [
"dojo/_base/declare", // declare
"dojo/i18n", // i18n.getLocalization
"dojo/_base/lang", // lang.hitch
"dojo/sniff", // has("chrome") has("opera")
"../../focus", // focus.focus()
"../_Plugin",
"../../form/Button",
"dojo/i18n!../nls/commands"
], function(declare, i18n, lang, has, focus, _Plugin, Button){
// module:
// dijit/_editor/plugins/Print
var Print = declare("dijit._editor.plugins.Print", _Plugin, {
// summary:
// This plugin provides Print capability to the editor. When
// clicked, the document in the editor frame will be printed.
_initButton: function(){
// summary:
// Over-ride for creation of the Print button.
var strings = i18n.getLocalization("dijit._editor", "commands"),
editor = this.editor;
this.button = new Button({
label: strings["print"],
ownerDocument: editor.ownerDocument,
dir: editor.dir,
lang: editor.lang,
showLabel: false,
iconClass: this.iconClassPrefix + " " + this.iconClassPrefix + "Print",
tabIndex: "-1",
onClick: lang.hitch(this, "_print")
});
},
setEditor: function(/*dijit/Editor*/ editor){
// summary:
// Tell the plugin which Editor it is associated with.
// editor: Object
// The editor object to attach the print capability to.
this.editor = editor;
this._initButton();
// Set up a check that we have a print function
// and disable button if we do not.
this.editor.onLoadDeferred.then(
lang.hitch(this, function(){
if(!this.editor.iframe.contentWindow["print"]){
this.button.set("disabled", true);
}
})
);
},
updateState: function(){
// summary:
// Over-ride for button state control for disabled to work.
var disabled = this.get("disabled");
if(!this.editor.iframe.contentWindow["print"]){
disabled = true;
}
this.button.set("disabled", disabled);
},
_print: function(){
// summary:
// Function to trigger printing of the editor document
// tags:
// private
var edFrame = this.editor.iframe;
if(edFrame.contentWindow["print"]){
// IE requires the frame to be focused for
// print to work, but since this is okay for all
// no special casing.
if(!has("opera") && !has("chrome")){
focus.focus(edFrame);
edFrame.contentWindow.print();
}else{
// Neither Opera nor Chrome 3 et you print single frames.
// So, open a new 'window', print it, and close it.
// Also, can't use size 0x0, have to use 1x1
var edDoc = this.editor.document;
var content = this.editor.get("value");
content = "<html><head><meta http-equiv='Content-Type' " +
"content='text/html; charset='UTF-8'></head><body>" +
content + "</body></html>";
var win = window.open("javascript: ''",
"",
"status=0,menubar=0,location=0,toolbar=0," +
"width=1,height=1,resizable=0,scrollbars=0");
win.document.open();
win.document.write(content);
win.document.close();
var styleNodes = edDoc.getElementsByTagName("style");
if(styleNodes){
// Clone over any editor view styles, since we can't print the iframe
// directly.
var i;
for(i = 0; i < styleNodes.length; i++){
var style = styleNodes[i].innerHTML;
var sNode = win.document.createElement("style");
sNode.appendChild(win.document.createTextNode(style));
win.document.getElementsByTagName("head")[0].appendChild(sNode);
}
}
win.print();
win.close();
}
}
}
});
// Register this plugin.
_Plugin.registry["print"] = function(){
return new Print({command: "print"});
};
return Print;
});
|
(function (env) {
"use strict";
env.ddg_spice_rust_cargo = function(api_result){
if (!api_result || !api_result.crates) {
return Spice.failed('rust_cargo');
}
var crates = api_result.crates;
var query = DDG.get_query().replace(/(cargo|rust) (package|crate|cargo)(s)?/, "").trim();
DDG.require("moment.js", function() {
Spice.add({
id: "rust_cargo",
name: "Software",
data: crates,
meta: {
itemType: "Cargo crates",
searchTerm: query,
sourceName: "Cargo",
sourceUrl: 'https://crates.io/search?q=' + encodeURIComponent(query)
},
normalize: function(item) {
return {
title: item.name + " " + item.max_version,
subtitle: "Last updated " + moment(item.updated_at).fromNow(),
description: item.description,
url: "https://crates.io/crates/" + encodeURIComponent(item.id),
abbrevDownloads: DDG.abbrevNumber(item.downloads)
}
},
templates: {
group: 'text',
detail: false,
item_detail: false,
options: {
footer: Spice.rust_cargo.footer
},
variants: {
tile: 'basic4'
}
},
sort_fields: {
downloads: function(a, b) {
return a.downloads > b.downloads ? -1 : 1;
}
},
sort_default: 'downloads'
});
});
};
}(this));
|
import React, { Component } from 'react'
import Menu from './screens/MenuScreen';
import VoterStatusScreen from './screens/VoterStatusScreen';
import AbsenteeScreen from './screens/AbsenteeScreen';
import ChatScreen from './screens/ChatScreen';
import RegisterScreen from './screens/RegisterScreen';
import OnCampus from './screens/OnCampus'
import {Button, Icon} from 'react-materialize';
/* This component renders the various different screens
within the same area. This provides the illusion of changing
screens while staying on a single webpage.*/
export default class DisplaySwitcher extends Component {
constructor(props) {
super(props);
// first method
this.state = {page: 'menu'}
}
changeScreen = (pagename) =>{
console.log("Change Screen called to " + pagename);
this.setState({page: pagename});
}
render() {
if(this.state.page === 'voterStatus'){
console.log("Loading VoterStatus screen");
return(
<div>
<Button className = "homeButton" onClick = {(e)=>this.changeScreen("menu")}><Icon>arrow_back_ios</Icon></Button>
<VoterStatusScreen changeScreen = {this.changeScreen}/>
</div>
)
}
else if(this.state.page === 'registerToVote'){
return(
<div>
<Button className = "homeButton" onClick = {(e)=>this.changeScreen("menu")}><Icon>arrow_back_ios</Icon></Button>
<RegisterScreen changeScreen = {this.changeScreen}/>
</div>
)
}
else if(this.state.page === 'absenteeVoting'){
return(
<div>
<Button className = "homeButton" onClick = {(e)=>this.changeScreen("menu")}><Icon>arrow_back_ios</Icon></Button>
<AbsenteeScreen changeScreen = {this.changeScreen}/>
</div>
)
}
else if(this.state.page === 'OnCampus'){
return(
<div>
<Button className = "homeButton" onClick = {(e)=>this.changeScreen("menu")}><Icon>arrow_back_ios</Icon></Button>
<AbsenteeScreen changeScreen = {this.changeScreen}/>
</div>
)
}
else if(this.state.page === 'chat'){
return(
<div>
<Button className = "homeButton" onClick = {(e)=>this.changeScreen("menu")}><Icon>arrow_back_ios</Icon></Button>
<ChatScreen changeScreen = {this.changeScreen}/>
</div>
)
}else{
console.log("Loading Menu screen");
return (
<div>
<Menu changeScreen={this.changeScreen}/>
</div>
)
}
}
}
|
/**
* skylark-grapejs - A version of garpejs that ported to running on skylarkjs
* @author Hudaokeji, Inc.
* @version v0.9.0
* @link https://github.com/skylark-integration/skylark-grapejs/
* @license MIT
*/
define(["skylark-underscore","./PropertiesView","./PropertyCompositeView","./LayersView","../../code_manager/model/CssGenerator"],function(e,t,s,a,r){"use strict";const l=new r;return s.extend({templateInput(){const e=this.pfx;this.ppfx;return`\n <div class="${e}field ${e}stack">\n <button type="button" id="${e}add" data-add-layer>+</button>\n <div data-layers-wrapper></div>\n </div>\n `},init(){const e=this.model;this.pfx;e.set("stackIndex",null),this.events["click [data-add-layer]"]="addLayer",this.listenTo(e,"change:stackIndex",this.indexChanged),this.listenTo(e,"updateValue",this.inputValueChanged),this.delegateEvents()},targetUpdated(...e){if(this.model.get("detached")){const{status:e}=this._getTargetData();this.setStatus(e),this.checkVisibility()}else s.prototype.targetUpdated.apply(this,e);this.refreshLayers()},getLayers(){return this.model.get("layers")},indexChanged(e){const t=this.model;this.getLayers().active(t.get("stackIndex"))},addLayer(){const e=this.model,t=this.getLayers(),s=e.get("prepend"),a=e.get("properties").deepClone();a.each(e=>e.set("value",""));const r=t.add({properties:a},{active:1,...s&&{at:0}});this.inputValueChanged(),e.set("stackIndex",t.indexOf(r))},inputValueChanged(){const e=this.model;this.elementUpdated(),e.get("detached")?e.get("properties").each(e=>e.trigger("change:value")):e.set("value",this.getLayerValues())},setValue(){},getLayerValues(){return this.getLayers().getFullValue()},_getClassRule(e={}){const{em:t}=this,{skipAdd:s=1}=e,a=t.getSelected(),r=t.get("StyleManager").getModelToStyle(a,{skipAdd:s,useClasses:1});return r!==a&&r},_getParentTarget(e,t={}){const{em:s,model:a}=this,r=a.get("property"),i=t.isValid||(e=>e.getStyle()[r]),g=s.get("CssComposer").getAll().filter(t=>t.selectorsToString()===e.getSelectorsString()).reduce((e,t)=>(e[t.getAtRule()]=t,e),{}),n=l.sortMediaObject(g).map(e=>e.value),d=n.indexOf(e),o=n.splice(0,d);let h;for(let e=o.length-1;e>-1;e--){const t=o[e];if(i(t)){h=t;break}}return h},refreshLayers(){let t=[];const{model:s,em:a}=this,r=this.getLayers(),l=s.get("detached"),i=s.get("property"),g=this.getTarget(),n=this.getComputedValue(),d=a.getSelected();let o,h,p,u,c,y;if(l){h=g?g.getStyle():{};const a=t=>{const a=s.get("properties").at(0).get("property");return t&&!e.isUndefined(t.getStyle()[a])};if(!e.keys(h).length&&n&&d){const e={isValid:e=>a(e)};(u=this._getParentTarget(g,e))?h=u.getStyle():(p=this._getClassRule(),u=!(c=a(p)&&p.getStyle())&&this._getParentTarget(this._getClassRule({skipAdd:0}),e),y=a(u)&&u.getStyle(),h=c||y||{})}o=h,t=r.getLayersFromStyle(h)}else{let e=this.getTargetValue({ignoreDefault:1});!e&&n&&((u=this._getParentTarget(g))?e=u.getStyle()[i]:(y=(u=!(c=(p=this._getClassRule())&&p.getStyle()[i])&&this._getParentTarget(this._getClassRule({skipAdd:0})))&&u.getStyle()[i],e=c||y||n)),o=e=e==s.getDefaultValue()?"":e,t=r.getLayersFromValue(e)}const f=s.getLayersFromTarget(g,{resultValue:o,layersObj:t})||t;r.reset(),r.add(f),s.set({stackIndex:null},{silent:!0})},getTargetValue(t={}){let a=s.prototype.getTargetValue.call(this,t);const{detached:r}=this.model.attributes;return e.isUndefined(a)&&!r&&(a=this.model.getValueFromStyle(this.getTarget().getStyle())),a},onRender(){const e=this,s=this.model,r=this.el.querySelector("[data-layers-wrapper]"),l={target:this.target,propTarget:this.propTarget,onChange(t,a,r){const l=a.model;if(s.get("detached")){const t=l.get("property"),s=l.getDefaultValue(),i=e.getLayers().getPropertyValues(t,s);a.updateTargetStyle(i,null,r)}else if("updated"==s.get("status")){const e=s.getFullValue();s.set("value",e,r),!e&&a.updateTargetStyle(e,null,r)}}},i=new a({collection:this.getLayers(),stackModel:s,preview:s.get("preview"),config:this.config,propsConfig:l}).render().el;new t({target:this.target,collection:this.model.get("properties"),stackModel:s,config:this.config,onChange:l.onChange,propTarget:l.propTarget}).render(),r.appendChild(i)}})});
//# sourceMappingURL=../../sourcemaps/style_manager/view/PropertyStackView.js.map
|
const assert = require('assert');
Object.freeze(assert);
const solveEquation = require('./src/index');
describe('Solve quadratic equation', () => {
it('1', () => {
const solutions = solveEquation('-20 * x^2 - 108797540 * x - 130011773690520');
assert.deepEqual(solutions, [-3667291, -1772586]);
});
it('2', () => {
const solutions = solveEquation('294 * x^2 - 141195558 * x - 1600964090384736');
assert.deepEqual(solutions, [-2105744, 2586001]);
});
it('3', () => {
const solutions = solveEquation('-267 * x^2 + 296412186 * x + 4722715166392080');
assert.deepEqual(solutions, [-3687112, 4797270]);
});
it('4', () => {
const solutions = solveEquation('-417 * x^2 + 806708601 * x + 3174554007677316');
assert.deepEqual(solutions, [-1956499, 3891052]);
});
it('5', () => {
const solutions = solveEquation('-478 * x^2 + 3021138772 * x - 4052495536885632');
assert.deepEqual(solutions, [1931872, 4388502]);
});
it('6', () => {
const solutions = solveEquation('367 * x^2 + 1773708798 * x + 292266180528840');
assert.deepEqual(solutions, [-4662180, -170814]);
});
it('7', () => {
const solutions = solveEquation('485 * x^2 + 1080338955 * x + 514155874862470');
assert.deepEqual(solutions, [-1538401, -689102]);
});
it('8', () => {
const solutions = solveEquation('431 * x^2 + 911452509 * x + 267423794912344');
assert.deepEqual(solutions, [-1762747, -351992]);
});
it('9', () => {
const solutions = solveEquation('-200 * x^2 - 888725200 * x - 104468049705600');
assert.deepEqual(solutions, [-4322792, -120834]);
});
it('10', () => {
const solutions = solveEquation('142 * x^2 - 1069080086 * x + 2011605981501984');
assert.deepEqual(solutions, [3699437, 3829296]);
});
it('11', () => {
const solutions = solveEquation('-206 * x^2 - 1701578746 * x - 3454735806747668');
assert.deepEqual(solutions, [-4665502, -3594589]);
});
it('12', () => {
const solutions = solveEquation('-8 * x^2 - 59910648 * x - 102244152727440');
assert.deepEqual(solutions, [-4858026, -2630805]);
});
it('13', () => {
const solutions = solveEquation('-44 * x^2 + 51547628 * x + 266429578357272');
assert.deepEqual(solutions, [-1943726, 3115263]);
});
it('14', () => {
const solutions = solveEquation('198 * x^2 + 1310713866 * x + 2090008945278936');
assert.deepEqual(solutions, [-3942124, -2677643]);
});
it('15', () => {
const solutions = solveEquation('-473 * x^2 - 2571124886 * x - 3420402126706400');
assert.deepEqual(solutions, [-3112400, -2323382]);
});
it('16', () => {
const solutions = solveEquation('-29 * x^2 - 60510849 * x + 189527331568964');
assert.deepEqual(solutions, [-3804428, 1717847]);
});
it('17', () => {
const solutions = solveEquation('428 * x^2 - 1262641516 * x - 2402667529459440');
assert.deepEqual(solutions, [-1315915, 4266012]);
});
it('18', () => {
const solutions = solveEquation('-452 * x^2 - 3327703100 * x - 5961384164545512');
assert.deepEqual(solutions, [-4282338, -3079837]);
});
it('19', () => {
const solutions = solveEquation('-473 * x^2 + 2227662085 * x - 136635191332332');
assert.deepEqual(solutions, [62156, 4647489]);
});
it('20', () => {
const solutions = solveEquation('337 * x^2 - 1347061118 * x - 1287098482464435');
assert.deepEqual(solutions, [-796695, 4793909]);
});
it('21', () => {
const solutions = solveEquation('148 * x^2 + 1215797356 * x + 2439974086889496');
assert.deepEqual(solutions, [-4727598, -3487249]);
});
it('22', () => {
const solutions = solveEquation('-454 * x^2 - 3721518358 * x - 7549656215739228');
assert.deepEqual(solutions, [-4509963, -3687214]);
});
it('23', () => {
const solutions = solveEquation('153 * x^2 + 357823395 * x - 133149552904242');
assert.deepEqual(solutions, [-2665237, 326522]);
});
it('24', () => {
const solutions = solveEquation('-498 * x^2 - 406335630 * x + 4591609305841572');
assert.deepEqual(solutions, [-3471713, 2655778]);
});
it('25', () => {
const solutions = solveEquation('219 * x^2 - 292471653 * x - 3083732127280242');
assert.deepEqual(solutions, [-3143667, 4479154]);
});
it('26', () => {
const solutions = solveEquation('148 * x^2 - 568254436 * x + 514394625520056');
assert.deepEqual(solutions, [1461619, 2377938]);
});
it('27', () => {
const solutions = solveEquation('-429 * x^2 - 289351920 * x + 6720397265732436');
assert.deepEqual(solutions, [-4309518, 3635038]);
});
it('28', () => {
const solutions = solveEquation('245 * x^2 + 1375935925 * x + 1818341552728820');
assert.deepEqual(solutions, [-3488653, -2127412]);
});
it('29', () => {
const solutions = solveEquation('274 * x^2 + 290093390 * x - 3946187251120884');
assert.deepEqual(solutions, [-4361126, 3302391]);
});
it('30', () => {
const solutions = solveEquation('329 * x^2 - 715635865 * x - 2509488263828406');
assert.deepEqual(solutions, [-1880653, 4055838]);
});
it('31', () => {
const solutions = solveEquation('123 * x^2 + 21247020 * x - 2263734541948992');
assert.deepEqual(solutions, [-4377268, 4204528]);
});
it('32', () => {
const solutions = solveEquation('497 * x^2 - 2461495876 * x + 2975604382840964');
assert.deepEqual(solutions, [2095306, 2857402]);
});
it('33', () => {
const solutions = solveEquation('-436 * x^2 + 3530846592 * x - 7147944567254720');
assert.deepEqual(solutions, [4015460, 4082812]);
});
it('34', () => {
const solutions = solveEquation('-300 * x^2 + 76955700 * x + 1235393506869000');
assert.deepEqual(solutions, [-1905070, 2161589]);
});
it('35', () => {
const solutions = solveEquation('-57 * x^2 - 155566509 * x + 89650574327106');
assert.deepEqual(solutions, [-3217994, 488757]);
});
it('36', () => {
const solutions = solveEquation('-381 * x^2 + 2871374115 * x - 5385906614046864');
assert.deepEqual(solutions, [3516911, 4019504]);
});
it('37', () => {
const solutions = solveEquation('-154 * x^2 + 645219652 * x - 602658645850800');
assert.deepEqual(solutions, [1405588, 2784150]);
});
it('38', () => {
const solutions = solveEquation('484 * x^2 - 1735749840 * x - 440083768225024');
assert.deepEqual(solutions, [-237776, 3824036]);
});
it('39', () => {
const solutions = solveEquation('-131 * x^2 - 1006051311 * x - 1770580185043078');
assert.deepEqual(solutions, [-4948439, -2731342]);
});
it('40', () => {
const solutions = solveEquation('63 * x^2 + 217013076 * x + 185403268649088');
assert.deepEqual(solutions, [-1875616, -1569036]);
});
it('41', () => {
const solutions = solveEquation('104 * x^2 - 907363600 * x + 1969338101694600');
assert.deepEqual(solutions, [4055835, 4668815]);
});
it('42', () => {
const solutions = solveEquation('236 * x^2 - 1439922376 * x + 2081465681789004');
assert.deepEqual(solutions, [2352903, 3748463]);
});
it('43', () => {
const solutions = solveEquation('291 * x^2 + 230249967 * x - 295345785953268');
assert.deepEqual(solutions, [-1477953, 686716]);
});
it('44', () => {
const solutions = solveEquation('36 * x^2 - 31639860 * x - 112399239902184');
assert.deepEqual(solutions, [-1381357, 2260242]);
});
it('45', () => {
const solutions = solveEquation('178 * x^2 - 1296885216 * x + 2361820662896696');
assert.deepEqual(solutions, [3594694, 3691178]);
});
it('46', () => {
const solutions = solveEquation('-114 * x^2 - 251511930 * x + 892429663678416');
assert.deepEqual(solutions, [-4110648, 1904403]);
});
it('47', () => {
const solutions = solveEquation('-342 * x^2 + 940819086 * x + 636703315397676');
assert.deepEqual(solutions, [-561958, 3312891]);
});
it('48', () => {
const solutions = solveEquation('-191 * x^2 - 498676361 * x + 12346951780600');
assert.deepEqual(solutions, [-2635400, 24529]);
});
it('49', () => {
const solutions = solveEquation('-6 * x^2 - 2704356 * x + 16947721094640');
assert.deepEqual(solutions, [-1921066, 1470340]);
});
it('50', () => {
const solutions = solveEquation('-57 * x^2 + 302165322 * x - 240310169901000');
assert.deepEqual(solutions, [974396, 4326750]);
});
it('51', () => {
const solutions = solveEquation('-290 * x^2 + 1477509110 * x - 1422200174715000');
assert.deepEqual(solutions, [1288359, 3806500]);
});
it('52', () => {
const solutions = solveEquation('311 * x^2 + 503689691 * x - 2621617409264010');
assert.deepEqual(solutions, [-3823990, 2204409]);
});
it('53', () => {
const solutions = solveEquation('289 * x^2 + 755749450 * x + 460512878992725');
assert.deepEqual(solutions, [-1648335, -966715]);
});
it('54', () => {
const solutions = solveEquation('385 * x^2 + 1014367970 * x - 2416079700509475');
assert.deepEqual(solutions, [-4147727, 1513005]);
});
it('55', () => {
const solutions = solveEquation('403 * x^2 + 2702475282 * x + 4478876195016600');
assert.deepEqual(solutions, [-3711300, -2994594]);
});
it('56', () => {
const solutions = solveEquation('-164 * x^2 + 1024241664 * x - 1587715150011580');
assert.deepEqual(solutions, [2858131, 3387245]);
});
it('57', () => {
const solutions = solveEquation('-141 * x^2 + 1092146661 * x - 2055620530029864');
assert.deepEqual(solutions, [3224648, 4521073]);
});
it('58', () => {
const solutions = solveEquation('-240 * x^2 - 2196362400 * x - 5014768722771840');
assert.deepEqual(solutions, [-4782308, -4369202]);
});
it('59', () => {
const solutions = solveEquation('-132 * x^2 - 656872656 * x - 796671131945040');
assert.deepEqual(solutions, [-2882518, -2093790]);
});
it('60', () => {
const solutions = solveEquation('-375 * x^2 + 1758412125 * x - 1086042255243750');
assert.deepEqual(solutions, [731850, 3957249]);
});
it('61', () => {
const solutions = solveEquation('-401 * x^2 - 325972098 * x + 886685129745408');
assert.deepEqual(solutions, [-1948002, 1135104]);
});
it('62', () => {
const solutions = solveEquation('30 * x^2 + 63436590 * x - 56700499682640');
assert.deepEqual(solutions, [-2791592, 677039]);
});
it('63', () => {
const solutions = solveEquation('243 * x^2 + 1238570028 * x + 301955199309504');
assert.deepEqual(solutions, [-4840272, -256724]);
});
it('64', () => {
const solutions = solveEquation('-19 * x^2 - 74826066 * x + 547242791800');
assert.deepEqual(solutions, [-3945514, 7300]);
});
it('65', () => {
const solutions = solveEquation('121 * x^2 - 324992690 * x - 993390335560491');
assert.deepEqual(solutions, [-1821441, 4507331]);
});
it('66', () => {
const solutions = solveEquation('185 * x^2 + 536527750 * x - 638327174869360');
assert.deepEqual(solutions, [-3806584, 906434]);
});
it('67', () => {
const solutions = solveEquation('186 * x^2 - 491700486 * x - 1692138575652840');
assert.deepEqual(solutions, [-1971340, 4614891]);
});
it('68', () => {
const solutions = solveEquation('-376 * x^2 + 1089866832 * x + 2634059512823848');
assert.deepEqual(solutions, [-1568311, 4466893]);
});
it('69', () => {
const solutions = solveEquation('145 * x^2 - 707447025 * x + 13566729261020');
assert.deepEqual(solutions, [19253, 4859692]);
});
it('70', () => {
const solutions = solveEquation('-440 * x^2 - 1441291720 * x + 985050474216160');
assert.deepEqual(solutions, [-3856219, 580556]);
});
it('71', () => {
const solutions = solveEquation('-322 * x^2 - 673406650 * x + 2890182335559288');
assert.deepEqual(solutions, [-4218852, 2127527]);
});
it('72', () => {
const solutions = solveEquation('199 * x^2 - 500338934 * x - 2264662631212800');
assert.deepEqual(solutions, [-2342950, 4857216]);
});
it('73', () => {
const solutions = solveEquation('-52 * x^2 + 259005188 * x - 55054093464760');
assert.deepEqual(solutions, [222499, 4758370]);
});
it('74', () => {
const solutions = solveEquation('-65 * x^2 + 360530300 * x - 496734807600915');
assert.deepEqual(solutions, [2551557, 2995063]);
});
it('75', () => {
const solutions = solveEquation('-34 * x^2 + 20206302 * x + 181841397158340');
assert.deepEqual(solutions, [-2034495, 2628798]);
});
it('76', () => {
const solutions = solveEquation('93 * x^2 - 210051474 * x - 1107442121769675');
assert.deepEqual(solutions, [-2501575, 4760193]);
});
it('77', () => {
const solutions = solveEquation('-442 * x^2 - 62980138 * x + 874553957560920');
assert.deepEqual(solutions, [-1479685, 1337196]);
});
it('78', () => {
const solutions = solveEquation('-483 * x^2 - 464527665 * x + 1259420029877142');
assert.deepEqual(solutions, [-2165733, 1203978]);
});
it('79', () => {
const solutions = solveEquation('-173 * x^2 + 1201588454 * x - 1782914317044765');
assert.deepEqual(solutions, [2148235, 4797363]);
});
it('80', () => {
const solutions = solveEquation('211 * x^2 + 1414155338 * x + 2166950296356855');
assert.deepEqual(solutions, [-4330785, -2371373]);
});
it('81', () => {
const solutions = solveEquation('87 * x^2 + 734366739 * x + 1513662380294274');
assert.deepEqual(solutions, [-4864074, -3576923]);
});
it('82', () => {
const solutions = solveEquation('-74 * x^2 + 586722320 * x - 1091391697000374');
assert.deepEqual(solutions, [2980747, 4947933]);
});
it('83', () => {
const solutions = solveEquation('-324 * x^2 + 580935888 * x + 1070053657117236');
assert.deepEqual(solutions, [-1129909, 2922921]);
});
it('84', () => {
const solutions = solveEquation('218 * x^2 + 524536558 * x - 856143092022180');
assert.deepEqual(solutions, [-3521390, 1115259]);
});
it('85', () => {
const solutions = solveEquation('-198 * x^2 + 204643494 * x + 3075587247239892');
assert.deepEqual(solutions, [-3458186, 4491739]);
});
it('86', () => {
const solutions = solveEquation('99 * x^2 - 218331630 * x - 472841602833600');
assert.deepEqual(solutions, [-1345190, 3550560]);
});
it('87', () => {
const solutions = solveEquation('275 * x^2 - 2331242925 * x + 4840527412195750');
assert.deepEqual(solutions, [3635290, 4841957]);
});
it('88', () => {
const solutions = solveEquation('54 * x^2 + 116755992 * x - 453692901615822');
assert.deepEqual(solutions, [-4174687, 2012539]);
});
it('89', () => {
const solutions = solveEquation('460 * x^2 - 664263000 * x + 30880589544000');
assert.deepEqual(solutions, [48090, 1395960]);
});
it('90', () => {
const solutions = solveEquation('93 * x^2 + 627150615 * x + 931480364461548');
assert.deepEqual(solutions, [-4534948, -2208607]);
});
it('91', () => {
const solutions = solveEquation('-78 * x^2 + 11926044 * x + 556462530926250');
assert.deepEqual(solutions, [-2595625, 2748523]);
});
it('92', () => {
const solutions = solveEquation('-309 * x^2 + 998149722 * x + 710515901594520');
assert.deepEqual(solutions, [-600282, 3830540]);
});
it('93', () => {
const solutions = solveEquation('-156 * x^2 + 139999704 * x + 413402009641920');
assert.deepEqual(solutions, [-1239880, 2137314]);
});
it('94', () => {
const solutions = solveEquation('-472 * x^2 - 793957808 * x + 1212416810326440');
assert.deepEqual(solutions, [-2651045, 968931]);
});
it('95', () => {
const solutions = solveEquation('-201 * x^2 + 988432776 * x - 146544471101655');
assert.deepEqual(solutions, [153021, 4764555]);
});
it('96', () => {
const solutions = solveEquation('-230 * x^2 + 667739910 * x + 48119401665500');
assert.deepEqual(solutions, [-70358, 2973575]);
});
it('97', () => {
const solutions = solveEquation('292 * x^2 - 92936884 * x - 699430954372776');
assert.deepEqual(solutions, [-1396701, 1714978]);
});
it('98', () => {
const solutions = solveEquation('383 * x^2 - 141629187 * x - 1790457858001160');
assert.deepEqual(solutions, [-1985131, 2354920]);
});
it('99', () => {
const solutions = solveEquation('423 * x^2 + 108469467 * x + 4581056865564');
assert.deepEqual(solutions, [-203108, -53321]);
});
it('100', () => {
const solutions = solveEquation('-420 * x^2 + 686698740 * x - 236193821481240');
assert.deepEqual(solutions, [492018, 1142979]);
});
it('101', () => {
const solutions = solveEquation('423 * x^2 + 2294164188 * x + 2945229426427680');
assert.deepEqual(solutions, [-3337096, -2086460]);
});
it('102', () => {
const solutions = solveEquation('426 * x^2 - 805519140 * x - 4801499990899200');
assert.deepEqual(solutions, [-2542390, 4433280]);
});
it('103', () => {
const solutions = solveEquation('-340 * x^2 - 2201893380 * x - 3485120187960680');
assert.deepEqual(solutions, [-3722639, -2753518]);
});
it('104', () => {
const solutions = solveEquation('22 * x^2 - 33921800 * x - 87977391531678');
assert.deepEqual(solutions, [-1372257, 2914157]);
});
it('105', () => {
const solutions = solveEquation('-285 * x^2 + 403917105 * x + 3296115925146000');
assert.deepEqual(solutions, [-2765200, 4182453]);
});
it('106', () => {
const solutions = solveEquation('309 * x^2 - 1045260480 * x + 567471620472204');
assert.deepEqual(solutions, [679322, 2703398]);
});
it('107', () => {
const solutions = solveEquation('249 * x^2 - 1589145390 * x + 2535483316528200');
assert.deepEqual(solutions, [3178090, 3204020]);
});
it('108', () => {
const solutions = solveEquation('-53 * x^2 + 70718324 * x - 23261473790276');
assert.deepEqual(solutions, [588422, 745886]);
});
it('109', () => {
const solutions = solveEquation('274 * x^2 - 2053427788 * x + 3717197925891450');
assert.deepEqual(solutions, [3058237, 4436025]);
});
it('110', () => {
const solutions = solveEquation('-22 * x^2 + 96973294 * x + 17139122136576');
assert.deepEqual(solutions, [-170171, 4578048]);
});
it('111', () => {
const solutions = solveEquation('84 * x^2 + 323512140 * x + 213336456311664');
assert.deepEqual(solutions, [-3006628, -844707]);
});
it('112', () => {
const solutions = solveEquation('469 * x^2 + 361590089 * x + 55480880166502');
assert.deepEqual(solutions, [-559579, -211402]);
});
it('113', () => {
const solutions = solveEquation('15 * x^2 - 3536985 * x - 34261174324080');
assert.deepEqual(solutions, [-1398009, 1633808]);
});
it('114', () => {
const solutions = solveEquation('395 * x^2 + 2200728675 * x + 3064780686922870');
assert.deepEqual(solutions, [-2822707, -2748758]);
});
it('115', () => {
const solutions = solveEquation('-315 * x^2 - 1272963510 * x - 745076991937320');
assert.deepEqual(solutions, [-3331076, -710078]);
});
it('116', () => {
const solutions = solveEquation('119 * x^2 - 792666854 * x + 1154494628368095');
assert.deepEqual(solutions, [2151205, 4509861]);
});
it('117', () => {
const solutions = solveEquation('127 * x^2 - 1221793467 * x + 2936946332195156');
assert.deepEqual(solutions, [4698124, 4922297]);
});
it('118', () => {
const solutions = solveEquation('-396 * x^2 - 569529576 * x + 346226478225012');
assert.deepEqual(solutions, [-1898687, 460481]);
});
it('119', () => {
const solutions = solveEquation('87 * x^2 - 265240206 * x - 132731802332016');
assert.deepEqual(solutions, [-437608, 3486346]);
});
it('120', () => {
const solutions = solveEquation('176 * x^2 - 23434752 * x - 334782052532928');
assert.deepEqual(solutions, [-1314222, 1447374]);
});
it('121', () => {
const solutions = solveEquation('-333 * x^2 + 133632567 * x + 1853276542210116');
assert.deepEqual(solutions, [-2166977, 2568276]);
});
it('122', () => {
const solutions = solveEquation('451 * x^2 - 2128778179 * x + 731075580290154');
assert.deepEqual(solutions, [372882, 4347247]);
});
it('123', () => {
const solutions = solveEquation('-309 * x^2 + 2386670268 * x - 4608313561362735');
assert.deepEqual(solutions, [3833007, 3890845]);
});
it('124', () => {
const solutions = solveEquation('409 * x^2 + 790477981 * x - 729821764894260');
assert.deepEqual(solutions, [-2615065, 682356]);
});
it('125', () => {
const solutions = solveEquation('192 * x^2 + 1109023872 * x + 1481163124164096');
assert.deepEqual(solutions, [-3679684, -2096482]);
});
it('126', () => {
const solutions = solveEquation('-429 * x^2 + 3594452862 * x - 7359554681898705');
assert.deepEqual(solutions, [3560513, 4818165]);
});
it('127', () => {
const solutions = solveEquation('-497 * x^2 - 353587171 * x + 8284951553019330');
assert.deepEqual(solutions, [-4454070, 3742627]);
});
it('128', () => {
const solutions = solveEquation('364 * x^2 + 277280640 * x - 965163405417484');
assert.deepEqual(solutions, [-2053189, 1291429]);
});
it('129', () => {
const solutions = solveEquation('498 * x^2 + 2065269246 * x + 2086113675990756');
assert.deepEqual(solutions, [-2406253, -1740874]);
});
it('130', () => {
const solutions = solveEquation('-174 * x^2 - 725626110 * x + 70026168794604');
assert.deepEqual(solutions, [-4264634, 94369]);
});
it('131', () => {
const solutions = solveEquation('154 * x^2 + 499478826 * x + 123024946035992');
assert.deepEqual(solutions, [-2974828, -268541]);
});
it('132', () => {
const solutions = solveEquation('203 * x^2 + 791289940 * x - 532663340884983');
assert.deepEqual(solutions, [-4483259, 585279]);
});
it('133', () => {
const solutions = solveEquation('-420 * x^2 - 1035973680 * x + 2897564269120500');
assert.deepEqual(solutions, [-4135025, 1668421]);
});
it('134', () => {
const solutions = solveEquation('161 * x^2 + 415719710 * x - 1425721883742975');
assert.deepEqual(solutions, [-4534855, 1952745]);
});
it('135', () => {
const solutions = solveEquation('29 * x^2 - 125745537 * x - 17206710154100');
assert.deepEqual(solutions, [-132772, 4468825]);
});
it('136', () => {
const solutions = solveEquation('-295 * x^2 - 2028250080 * x - 3417718882128260');
assert.deepEqual(solutions, [-3919766, -2955658]);
});
it('137', () => {
const solutions = solveEquation('423 * x^2 + 975624966 * x - 166252361598369');
assert.deepEqual(solutions, [-2465833, 159391]);
});
it('138', () => {
const solutions = solveEquation('-111 * x^2 + 391717779 * x - 94067064641910');
assert.deepEqual(solutions, [259174, 3269815]);
});
it('139', () => {
const solutions = solveEquation('-476 * x^2 - 2140714324 * x - 2405178343313480');
assert.deepEqual(solutions, [-2308054, -2189245]);
});
it('140', () => {
const solutions = solveEquation('385 * x^2 - 1016269100 * x + 267401923798240');
assert.deepEqual(solutions, [296404, 2343256]);
});
it('141', () => {
const solutions = solveEquation('492 * x^2 - 2556253404 * x + 1965826305674184');
assert.deepEqual(solutions, [938578, 4257059]);
});
it('142', () => {
const solutions = solveEquation('-270 * x^2 - 1310224410 * x - 1243725726524400');
assert.deepEqual(solutions, [-3558040, -1294643]);
});
it('143', () => {
const solutions = solveEquation('91 * x^2 + 449417150 * x + 518027799265704');
assert.deepEqual(solutions, [-3105684, -1832966]);
});
it('144', () => {
const solutions = solveEquation('-345 * x^2 + 847238925 * x + 2004001263594270');
assert.deepEqual(solutions, [-1477001, 3932766]);
});
it('145', () => {
const solutions = solveEquation('11 * x^2 - 3157341 * x - 157818102600510');
assert.deepEqual(solutions, [-3646959, 3933990]);
});
it('146', () => {
const solutions = solveEquation('-191 * x^2 - 1565910635 * x - 3121319959906844');
assert.deepEqual(solutions, [-4778801, -3419684]);
});
it('147', () => {
const solutions = solveEquation('243 * x^2 + 1076720607 * x + 1097493853228542');
assert.deepEqual(solutions, [-2841487, -1589462]);
});
it('148', () => {
const solutions = solveEquation('-489 * x^2 - 1999623201 * x + 1166458895779254');
assert.deepEqual(solutions, [-4606987, 517778]);
});
it('149', () => {
const solutions = solveEquation('320 * x^2 + 1590515200 * x + 481652997529280');
assert.deepEqual(solutions, [-4646419, -323941]);
});
it('150', () => {
const solutions = solveEquation('212 * x^2 - 883388100 * x + 905051914883872');
assert.deepEqual(solutions, [1815688, 2351237]);
});
it('151', () => {
const solutions = solveEquation('-465 * x^2 - 1338465765 * x - 885736755624750');
assert.deepEqual(solutions, [-1847275, -1031146]);
});
it('152', () => {
const solutions = solveEquation('-408 * x^2 + 3618895536 * x - 8023483803153336');
assert.deepEqual(solutions, [4379039, 4490803]);
});
it('153', () => {
const solutions = solveEquation('-375 * x^2 + 1510051125 * x + 447292882417500');
assert.deepEqual(solutions, [-277137, 4303940]);
});
it('154', () => {
const solutions = solveEquation('419 * x^2 + 720305833 * x - 744177550961586');
assert.deepEqual(solutions, [-2445401, 726294]);
});
it('155', () => {
const solutions = solveEquation('-385 * x^2 - 381205055 * x + 3123536949432900');
assert.deepEqual(solutions, [-3386123, 2395980]);
});
it('156', () => {
const solutions = solveEquation('284 * x^2 + 1377239256 * x + 932005951652512');
assert.deepEqual(solutions, [-4036406, -813028]);
});
it('157', () => {
const solutions = solveEquation('-124 * x^2 - 538722464 * x - 580120990870212');
assert.deepEqual(solutions, [-2373149, -1971387]);
});
it('158', () => {
const solutions = solveEquation('499 * x^2 - 9276410 * x - 2577397049190425');
assert.deepEqual(solutions, [-2263415, 2282005]);
});
it('159', () => {
const solutions = solveEquation('-419 * x^2 - 1360603197 * x + 3406868302421522');
assert.deepEqual(solutions, [-4904962, 1657699]);
});
it('160', () => {
const solutions = solveEquation('-59 * x^2 - 111593308 * x + 147243798492276');
assert.deepEqual(solutions, [-2786906, 895494]);
});
it('161', () => {
const solutions = solveEquation('48 * x^2 + 3836304 * x - 428433958572384');
assert.deepEqual(solutions, [-3027821, 2947898]);
});
it('162', () => {
const solutions = solveEquation('-84 * x^2 - 59519628 * x + 626128264467552');
assert.deepEqual(solutions, [-3107359, 2398792]);
});
it('163', () => {
const solutions = solveEquation('-194 * x^2 - 667460880 * x - 573068620826656');
assert.deepEqual(solutions, [-1793284, -1647236]);
});
it('164', () => {
const solutions = solveEquation('189 * x^2 - 875117628 * x + 603066976000839');
assert.deepEqual(solutions, [842381, 3787871]);
});
it('165', () => {
const solutions = solveEquation('-38 * x^2 - 20827838 * x + 8352406422000');
assert.deepEqual(solutions, [-817101, 269000]);
});
it('166', () => {
const solutions = solveEquation('169 * x^2 - 567252387 * x + 382448696467968');
assert.deepEqual(solutions, [934251, 2422272]);
});
it('167', () => {
const solutions = solveEquation('-53 * x^2 - 25268333 * x + 1000021170936820');
assert.deepEqual(solutions, [-4588685, 4111924]);
});
it('168', () => {
const solutions = solveEquation('232 * x^2 - 867658424 * x + 772682780178192');
assert.deepEqual(solutions, [1462281, 2277626]);
});
it('169', () => {
const solutions = solveEquation('69 * x^2 - 35905047 * x - 103846101451416');
assert.deepEqual(solutions, [-993896, 1514259]);
});
it('170', () => {
const solutions = solveEquation('-185 * x^2 + 648410755 * x + 450759719339730');
assert.deepEqual(solutions, [-594379, 4099302]);
});
it('171', () => {
const solutions = solveEquation('-129 * x^2 - 492171120 * x - 193886241619191');
assert.deepEqual(solutions, [-3369179, -446101]);
});
it('172', () => {
const solutions = solveEquation('161 * x^2 - 982018051 * x + 1463150162884704');
assert.deepEqual(solutions, [2588163, 3511328]);
});
it('173', () => {
const solutions = solveEquation('-467 * x^2 - 3170083329 * x - 5311340043760774');
assert.deepEqual(solutions, [-3776914, -3011273]);
});
it('174', () => {
const solutions = solveEquation('27 * x^2 + 96190308 * x - 109602053776215');
assert.deepEqual(solutions, [-4470609, 908005]);
});
it('175', () => {
const solutions = solveEquation('-178 * x^2 + 653158540 * x + 540481161618918');
assert.deepEqual(solutions, [-695619, 4365049]);
});
it('176', () => {
const solutions = solveEquation('111 * x^2 + 268540857 * x - 605853786193560');
assert.deepEqual(solutions, [-3840495, 1421208]);
});
it('177', () => {
const solutions = solveEquation('-441 * x^2 + 2114697753 * x - 2506471329970062');
assert.deepEqual(solutions, [2142751, 2652482]);
});
it('178', () => {
const solutions = solveEquation('-483 * x^2 + 1773119565 * x - 1598427103205772');
assert.deepEqual(solutions, [1591011, 2080044]);
});
it('179', () => {
const solutions = solveEquation('-138 * x^2 - 763808886 * x - 935785264360848');
assert.deepEqual(solutions, [-3704216, -1830631]);
});
it('180', () => {
const solutions = solveEquation('-236 * x^2 + 1307204944 * x - 1695048970954500');
assert.deepEqual(solutions, [2071125, 3467879]);
});
it('181', () => {
const solutions = solveEquation('358 * x^2 - 2489631524 * x + 3871932864221136');
assert.deepEqual(solutions, [2347962, 4606316]);
});
it('182', () => {
const solutions = solveEquation('-464 * x^2 + 626846832 * x + 392302300190432');
assert.deepEqual(solutions, [-465463, 1816426]);
});
it('183', () => {
const solutions = solveEquation('135 * x^2 - 189957825 * x - 1191078626098140');
assert.deepEqual(solutions, [-2348957, 3756052]);
});
it('184', () => {
const solutions = solveEquation('-109 * x^2 + 378455630 * x + 12169779474384');
assert.deepEqual(solutions, [-31864, 3503934]);
});
it('185', () => {
const solutions = solveEquation('-175 * x^2 - 397148325 * x + 709028410683600');
assert.deepEqual(solutions, [-3445371, 1175952]);
});
it('186', () => {
const solutions = solveEquation('143 * x^2 + 139774349 * x - 1070088105988044');
assert.deepEqual(solutions, [-3267567, 2290124]);
});
it('187', () => {
const solutions = solveEquation('134 * x^2 - 1116225494 * x + 2324226805240340');
assert.deepEqual(solutions, [4115831, 4214210]);
});
it('188', () => {
const solutions = solveEquation('50 * x^2 + 230029650 * x - 26481471484500');
assert.deepEqual(solutions, [-4712970, 112377]);
});
it('189', () => {
const solutions = solveEquation('43 * x^2 + 205832228 * x + 44779345290720');
assert.deepEqual(solutions, [-4558340, -228456]);
});
it('190', () => {
const solutions = solveEquation('-332 * x^2 - 1413317360 * x - 267227420896772');
assert.deepEqual(solutions, [-4058663, -198317]);
});
it('191', () => {
const solutions = solveEquation('18 * x^2 - 166433796 * x + 384529439704050');
assert.deepEqual(solutions, [4518897, 4727425]);
});
it('192', () => {
const solutions = solveEquation('-245 * x^2 + 455487095 * x - 103772642688050');
assert.deepEqual(solutions, [265841, 1593290]);
});
it('193', () => {
const solutions = solveEquation('52 * x^2 - 108516772 * x - 167045828103440');
assert.deepEqual(solutions, [-1030495, 3117356]);
});
it('194', () => {
const solutions = solveEquation('-157 * x^2 + 778069549 * x - 963998893295220');
assert.deepEqual(solutions, [2474877, 2480980]);
});
it('195', () => {
const solutions = solveEquation('401 * x^2 - 1682176554 * x + 1086486869709360');
assert.deepEqual(solutions, [797490, 3397464]);
});
it('196', () => {
const solutions = solveEquation('479 * x^2 + 301133888 * x - 5544914841268791');
assert.deepEqual(solutions, [-3731181, 3102509]);
});
it('197', () => {
const solutions = solveEquation('-271 * x^2 + 1345872449 * x - 1413636123103908');
assert.deepEqual(solutions, [1508628, 3457691]);
});
it('198', () => {
const solutions = solveEquation('264 * x^2 + 10632072 * x - 921283858117392');
assert.deepEqual(solutions, [-1888322, 1848049]);
});
it('199', () => {
const solutions = solveEquation('-464 * x^2 + 2224458688 * x - 998668448399424');
assert.deepEqual(solutions, [501386, 4292706]);
});
it('200', () => {
const solutions = solveEquation('-99 * x^2 - 731003031 * x - 1209142706447412');
assert.deepEqual(solutions, [-4882236, -2501633]);
});
});
|
module.exports = {
tabWidth: 4,
useTabs: true,
semi: true,
singleQuote: true,
trailingComma: 'none',
bracketSpacing: true,
arrowParens: 'avoid',
endOfLine: 'lf'
};
|
var _lib = {};
include("browser.js");
_lib.detectBrowser = detectBrowser;
var BROWSER = detectBrowser(typeof window == 'undefined' ? void(0): window);
include("assert.js");
_lib.__assert__ = __assert__;
include("misc.js");
_lib._atomic_p = _atomic_p;
_lib._clone = _clone;
_lib.xparseInt = xparseInt;
_lib._repeat = _repeat;
_lib._lpad = _lpad;
_lib._clip = _clip;
_lib.clipPoint = _clipPoint;
_lib.addPoint = _addPoint;
_lib.subtractPoint = _subtractPoint;
_lib.pointEquals = _pointEquals
_lib.escapeXMLSpecialChars = _escapeXMLSpecialChars;
_lib._bindEvent = _bindEvent;
_lib._unbindEvent = _unbindEvent;
include("error.js");
_lib.FashionError = FashionError;
_lib.createExceptionClass = createExceptionClass;
_lib.NotImplemented = NotImplemented;
_lib.ValueError = ValueError;
_lib.PropertyError = PropertyError;
_lib.NotSupported = NotSupported;
_lib.ArgumentError = ArgumentError;
_lib.NotAttached = NotAttached;
_lib.NotFound = NotFound;
_lib.AlreadyExists = AlreadyExists;
include("classify.js");
_lib._class = _class;
|
/* NUGET: BEGIN LICENSE TEXT
*
* Microsoft grants you the right to use these script files for the sole
* purpose of either: (i) interacting through your browser with the Microsoft
* website or online service, subject to the applicable licensing or use
* terms; or (ii) using the files as included with a Microsoft product subject
* to that product's license terms. Microsoft reserves all other rights to the
* files not expressly granted by Microsoft, whether by implication, estoppel
* or otherwise. Insofar as a script file is dual licensed under GPL,
* Microsoft neither took the code under GPL nor distributes it thereunder but
* under the terms set out in this paragraph. All notices and licenses
* below are for informational purposes only.
*
* Copyright (c) Faruk Ates, Paul Irish, Alex Sexton; http://www.modernizr.com/license/
*
* Includes matchMedia polyfill; Copyright (c) 2010 Filament Group, Inc; http://opensource.org/licenses/MIT
*
* Includes material adapted from ES5-shim https://github.com/kriskowal/es5-shim/blob/master/es5-shim.js; Copyright 2009-2012 by contributors; http://opensource.org/licenses/MIT
*
* Includes material from css-support; Copyright (c) 2005-2012 Diego Perini; https://github.com/dperini/css-support/blob/master/LICENSE
*
* NUGET: END LICENSE TEXT */
/*!
* Modernizr v2.6.2
* www.modernizr.com
*
* Copyright (c) Faruk Ates, Paul Irish, Alex Sexton
* Available under the BSD and MIT licenses: www.modernizr.com/license/
*/
/*
* Modernizr tests which native CSS3 and HTML5 features are available in
* the current UA and makes the results available to you in two ways:
* as properties on a global Modernizr object, and as classes on the
* <html> element. This information allows you to progressively enhance
* your pages with a granular level of control over the experience.
*
* Modernizr has an optional (not included) conditional resource loader
* called Modernizr.load(), based on Yepnope.js (yepnopejs.com).
* To get a build that includes Modernizr.load(), as well as choosing
* which tests to include, go to www.modernizr.com/download/
*
* Authors Faruk Ates, Paul Irish, Alex Sexton
* Contributors Ryan Seddon, Ben Alman
*/
window.Modernizr = (function( window, document, undefined ) {
var version = '2.6.2',
Modernizr = {},
/*>>cssclasses*/
// option for enabling the HTML classes to be added
enableClasses = true,
/*>>cssclasses*/
docElement = document.documentElement,
/**
* Create our "modernizr" element that we do most feature tests on.
*/
mod = 'modernizr',
modElem = document.createElement(mod),
mStyle = modElem.style,
/**
* Create the input element for various Web Forms feature tests.
*/
inputElem /*>>inputelem*/ = document.createElement('input') /*>>inputelem*/ ,
/*>>smile*/
smile = ':)',
/*>>smile*/
toString = {}.toString,
// TODO :: make the prefixes more granular
/*>>prefixes*/
// List of property values to set for css tests. See ticket #21
prefixes = ' -webkit- -moz- -o- -ms- '.split(' '),
/*>>prefixes*/
/*>>domprefixes*/
// Following spec is to expose vendor-specific style properties as:
// elem.style.WebkitBorderRadius
// and the following would be incorrect:
// elem.style.webkitBorderRadius
// Webkit ghosts their properties in lowercase but Opera & Moz do not.
// Microsoft uses a lowercase `ms` instead of the correct `Ms` in IE8+
// erik.eae.net/archives/2008/03/10/21.48.10/
// More here: github.com/Modernizr/Modernizr/issues/issue/21
omPrefixes = 'Webkit Moz O ms',
cssomPrefixes = omPrefixes.split(' '),
domPrefixes = omPrefixes.toLowerCase().split(' '),
/*>>domprefixes*/
/*>>ns*/
ns = {'svg': 'http://www.w3.org/2000/svg'},
/*>>ns*/
tests = {},
inputs = {},
attrs = {},
classes = [],
slice = classes.slice,
featureName, // used in testing loop
/*>>teststyles*/
// Inject element with style element and some CSS rules
injectElementWithStyles = function( rule, callback, nodes, testnames ) {
var style, ret, node, docOverflow,
div = document.createElement('div'),
// After page load injecting a fake body doesn't work so check if body exists
body = document.body,
// IE6 and 7 won't return offsetWidth or offsetHeight unless it's in the body element, so we fake it.
fakeBody = body || document.createElement('body');
if ( parseInt(nodes, 10) ) {
// In order not to give false positives we create a node for each test
// This also allows the method to scale for unspecified uses
while ( nodes-- ) {
node = document.createElement('div');
node.id = testnames ? testnames[nodes] : mod + (nodes + 1);
div.appendChild(node);
}
}
// <style> elements in IE6-9 are considered 'NoScope' elements and therefore will be removed
// when injected with innerHTML. To get around this you need to prepend the 'NoScope' element
// with a 'scoped' element, in our case the soft-hyphen entity as it won't mess with our measurements.
// msdn.microsoft.com/en-us/library/ms533897%28VS.85%29.aspx
// Documents served as xml will throw if using ­ so use xml friendly encoded version. See issue #277
style = ['­','<style id="s', mod, '">', rule, '</style>'].join('');
div.id = mod;
// IE6 will false positive on some tests due to the style element inside the test div somehow interfering offsetHeight, so insert it into body or fakebody.
// Opera will act all quirky when injecting elements in documentElement when page is served as xml, needs fakebody too. #270
(body ? div : fakeBody).innerHTML += style;
fakeBody.appendChild(div);
if ( !body ) {
//avoid crashing IE8, if background image is used
fakeBody.style.background = '';
//Safari 5.13/5.1.4 OSX stops loading if ::-webkit-scrollbar is used and scrollbars are visible
fakeBody.style.overflow = 'hidden';
docOverflow = docElement.style.overflow;
docElement.style.overflow = 'hidden';
docElement.appendChild(fakeBody);
}
ret = callback(div, rule);
// If this is done after page load we don't want to remove the body so check if body exists
if ( !body ) {
fakeBody.parentNode.removeChild(fakeBody);
docElement.style.overflow = docOverflow;
} else {
div.parentNode.removeChild(div);
}
return !!ret;
},
/*>>teststyles*/
/*>>mq*/
// adapted from matchMedia polyfill
// by Scott Jehl and Paul Irish
// gist.github.com/786768
testMediaQuery = function( mq ) {
var matchMedia = window.matchMedia || window.msMatchMedia;
if ( matchMedia ) {
return matchMedia(mq).matches;
}
var bool;
injectElementWithStyles('@media ' + mq + ' { #' + mod + ' { position: absolute; } }', function( node ) {
bool = (window.getComputedStyle ?
getComputedStyle(node, null) :
node.currentStyle)['position'] == 'absolute';
});
return bool;
},
/*>>mq*/
/*>>hasevent*/
//
// isEventSupported determines if a given element supports the given event
// kangax.github.com/iseventsupported/
//
// The following results are known incorrects:
// Modernizr.hasEvent("webkitTransitionEnd", elem) // false negative
// Modernizr.hasEvent("textInput") // in Webkit. github.com/Modernizr/Modernizr/issues/333
// ...
isEventSupported = (function() {
var TAGNAMES = {
'select': 'input', 'change': 'input',
'submit': 'form', 'reset': 'form',
'error': 'img', 'load': 'img', 'abort': 'img'
};
function isEventSupported( eventName, element ) {
element = element || document.createElement(TAGNAMES[eventName] || 'div');
eventName = 'on' + eventName;
// When using `setAttribute`, IE skips "unload", WebKit skips "unload" and "resize", whereas `in` "catches" those
var isSupported = eventName in element;
if ( !isSupported ) {
// If it has no `setAttribute` (i.e. doesn't implement Node interface), try generic element
if ( !element.setAttribute ) {
element = document.createElement('div');
}
if ( element.setAttribute && element.removeAttribute ) {
element.setAttribute(eventName, '');
isSupported = is(element[eventName], 'function');
// If property was created, "remove it" (by setting value to `undefined`)
if ( !is(element[eventName], 'undefined') ) {
element[eventName] = undefined;
}
element.removeAttribute(eventName);
}
}
element = null;
return isSupported;
}
return isEventSupported;
})(),
/*>>hasevent*/
// TODO :: Add flag for hasownprop ? didn't last time
// hasOwnProperty shim by kangax needed for Safari 2.0 support
_hasOwnProperty = ({}).hasOwnProperty, hasOwnProp;
if ( !is(_hasOwnProperty, 'undefined') && !is(_hasOwnProperty.call, 'undefined') ) {
hasOwnProp = function (object, property) {
return _hasOwnProperty.call(object, property);
};
}
else {
hasOwnProp = function (object, property) { /* yes, this can give false positives/negatives, but most of the time we don't care about those */
return ((property in object) && is(object.constructor.prototype[property], 'undefined'));
};
}
// Adapted from ES5-shim https://github.com/kriskowal/es5-shim/blob/master/es5-shim.js
// es5.github.com/#x15.3.4.5
if (!Function.prototype.bind) {
Function.prototype.bind = function bind(that) {
var target = this;
if (typeof target != "function") {
throw new TypeError();
}
var args = slice.call(arguments, 1),
bound = function () {
if (this instanceof bound) {
var F = function(){};
F.prototype = target.prototype;
var self = new F();
var result = target.apply(
self,
args.concat(slice.call(arguments))
);
if (Object(result) === result) {
return result;
}
return self;
} else {
return target.apply(
that,
args.concat(slice.call(arguments))
);
}
};
return bound;
};
}
/**
* setCss applies given styles to the Modernizr DOM node.
*/
function setCss( str ) {
mStyle.cssText = str;
}
/**
* setCssAll extrapolates all vendor-specific css strings.
*/
function setCssAll( str1, str2 ) {
return setCss(prefixes.join(str1 + ';') + ( str2 || '' ));
}
/**
* is returns a boolean for if typeof obj is exactly type.
*/
function is( obj, type ) {
return typeof obj === type;
}
/**
* contains returns a boolean for if substr is found within str.
*/
function contains( str, substr ) {
return !!~('' + str).indexOf(substr);
}
/*>>testprop*/
// testProps is a generic CSS / DOM property test.
// In testing support for a given CSS property, it's legit to test:
// `elem.style[styleName] !== undefined`
// If the property is supported it will return an empty string,
// if unsupported it will return undefined.
// We'll take advantage of this quick test and skip setting a style
// on our modernizr element, but instead just testing undefined vs
// empty string.
// Because the testing of the CSS property names (with "-", as
// opposed to the camelCase DOM properties) is non-portable and
// non-standard but works in WebKit and IE (but not Gecko or Opera),
// we explicitly reject properties with dashes so that authors
// developing in WebKit or IE first don't end up with
// browser-specific content by accident.
function testProps( props, prefixed ) {
for ( var i in props ) {
var prop = props[i];
if ( !contains(prop, "-") && mStyle[prop] !== undefined ) {
return prefixed == 'pfx' ? prop : true;
}
}
return false;
}
/*>>testprop*/
// TODO :: add testDOMProps
/**
* testDOMProps is a generic DOM property test; if a browser supports
* a certain property, it won't return undefined for it.
*/
function testDOMProps( props, obj, elem ) {
for ( var i in props ) {
var item = obj[props[i]];
if ( item !== undefined) {
// return the property name as a string
if (elem === false) return props[i];
// let's bind a function
if (is(item, 'function')){
// default to autobind unless override
return item.bind(elem || obj);
}
// return the unbound function or obj or value
return item;
}
}
return false;
}
/*>>testallprops*/
/**
* testPropsAll tests a list of DOM properties we want to check against.
* We specify literally ALL possible (known and/or likely) properties on
* the element including the non-vendor prefixed one, for forward-
* compatibility.
*/
function testPropsAll( prop, prefixed, elem ) {
var ucProp = prop.charAt(0).toUpperCase() + prop.slice(1),
props = (prop + ' ' + cssomPrefixes.join(ucProp + ' ') + ucProp).split(' ');
// did they call .prefixed('boxSizing') or are we just testing a prop?
if(is(prefixed, "string") || is(prefixed, "undefined")) {
return testProps(props, prefixed);
// otherwise, they called .prefixed('requestAnimationFrame', window[, elem])
} else {
props = (prop + ' ' + (domPrefixes).join(ucProp + ' ') + ucProp).split(' ');
return testDOMProps(props, prefixed, elem);
}
}
/*>>testallprops*/
/**
* Tests
* -----
*/
// The *new* flexbox
// dev.w3.org/csswg/css3-flexbox
tests['flexbox'] = function() {
return testPropsAll('flexWrap');
};
// The *old* flexbox
// www.w3.org/TR/2009/WD-css3-flexbox-20090723/
tests['flexboxlegacy'] = function() {
return testPropsAll('boxDirection');
};
// On the S60 and BB Storm, getContext exists, but always returns undefined
// so we actually have to call getContext() to verify
// github.com/Modernizr/Modernizr/issues/issue/97/
tests['canvas'] = function() {
var elem = document.createElement('canvas');
return !!(elem.getContext && elem.getContext('2d'));
};
tests['canvastext'] = function() {
return !!(Modernizr['canvas'] && is(document.createElement('canvas').getContext('2d').fillText, 'function'));
};
// webk.it/70117 is tracking a legit WebGL feature detect proposal
// We do a soft detect which may false positive in order to avoid
// an expensive context creation: bugzil.la/732441
tests['webgl'] = function() {
return !!window.WebGLRenderingContext;
};
/*
* The Modernizr.touch test only indicates if the browser supports
* touch events, which does not necessarily reflect a touchscreen
* device, as evidenced by tablets running Windows 7 or, alas,
* the Palm Pre / WebOS (touch) phones.
*
* Additionally, Chrome (desktop) used to lie about its support on this,
* but that has since been rectified: crbug.com/36415
*
* We also test for Firefox 4 Multitouch Support.
*
* For more info, see: modernizr.github.com/Modernizr/touch.html
*/
tests['touch'] = function() {
var bool;
if(('ontouchstart' in window) || window.DocumentTouch && document instanceof DocumentTouch) {
bool = true;
} else {
injectElementWithStyles(['@media (',prefixes.join('touch-enabled),('),mod,')','{#modernizr{top:9px;position:absolute}}'].join(''), function( node ) {
bool = node.offsetTop === 9;
});
}
return bool;
};
// geolocation is often considered a trivial feature detect...
// Turns out, it's quite tricky to get right:
//
// Using !!navigator.geolocation does two things we don't want. It:
// 1. Leaks memory in IE9: github.com/Modernizr/Modernizr/issues/513
// 2. Disables page caching in WebKit: webk.it/43956
//
// Meanwhile, in Firefox < 8, an about:config setting could expose
// a false positive that would throw an exception: bugzil.la/688158
tests['geolocation'] = function() {
return 'geolocation' in navigator;
};
tests['postmessage'] = function() {
return !!window.postMessage;
};
// Chrome incognito mode used to throw an exception when using openDatabase
// It doesn't anymore.
tests['websqldatabase'] = function() {
return !!window.openDatabase;
};
// Vendors had inconsistent prefixing with the experimental Indexed DB:
// - Webkit's implementation is accessible through webkitIndexedDB
// - Firefox shipped moz_indexedDB before FF4b9, but since then has been mozIndexedDB
// For speed, we don't test the legacy (and beta-only) indexedDB
tests['indexedDB'] = function() {
return !!testPropsAll("indexedDB", window);
};
// documentMode logic from YUI to filter out IE8 Compat Mode
// which false positives.
tests['hashchange'] = function() {
return isEventSupported('hashchange', window) && (document.documentMode === undefined || document.documentMode > 7);
};
// Per 1.6:
// This used to be Modernizr.historymanagement but the longer
// name has been deprecated in favor of a shorter and property-matching one.
// The old API is still available in 1.6, but as of 2.0 will throw a warning,
// and in the first release thereafter disappear entirely.
tests['history'] = function() {
return !!(window.history && history.pushState);
};
tests['draganddrop'] = function() {
var div = document.createElement('div');
return ('draggable' in div) || ('ondragstart' in div && 'ondrop' in div);
};
// FF3.6 was EOL'ed on 4/24/12, but the ESR version of FF10
// will be supported until FF19 (2/12/13), at which time, ESR becomes FF17.
// FF10 still uses prefixes, so check for it until then.
// for more ESR info, see: mozilla.org/en-US/firefox/organizations/faq/
tests['websockets'] = function() {
return 'WebSocket' in window || 'MozWebSocket' in window;
};
// css-tricks.com/rgba-browser-support/
tests['rgba'] = function() {
// Set an rgba() color and check the returned value
setCss('background-color:rgba(150,255,150,.5)');
return contains(mStyle.backgroundColor, 'rgba');
};
tests['hsla'] = function() {
// Same as rgba(), in fact, browsers re-map hsla() to rgba() internally,
// except IE9 who retains it as hsla
setCss('background-color:hsla(120,40%,100%,.5)');
return contains(mStyle.backgroundColor, 'rgba') || contains(mStyle.backgroundColor, 'hsla');
};
tests['multiplebgs'] = function() {
// Setting multiple images AND a color on the background shorthand property
// and then querying the style.background property value for the number of
// occurrences of "url(" is a reliable method for detecting ACTUAL support for this!
setCss('background:url(https://),url(https://),red url(https://)');
// If the UA supports multiple backgrounds, there should be three occurrences
// of the string "url(" in the return value for elemStyle.background
return (/(url\s*\(.*?){3}/).test(mStyle.background);
};
// this will false positive in Opera Mini
// github.com/Modernizr/Modernizr/issues/396
tests['backgroundsize'] = function() {
return testPropsAll('backgroundSize');
};
tests['borderimage'] = function() {
return testPropsAll('borderImage');
};
// Super comprehensive table about all the unique implementations of
// border-radius: muddledramblings.com/table-of-css3-border-radius-compliance
tests['borderradius'] = function() {
return testPropsAll('borderRadius');
};
// WebOS unfortunately false positives on this test.
tests['boxshadow'] = function() {
return testPropsAll('boxShadow');
};
// FF3.0 will false positive on this test
tests['textshadow'] = function() {
return document.createElement('div').style.textShadow === '';
};
tests['opacity'] = function() {
// Browsers that actually have CSS Opacity implemented have done so
// according to spec, which means their return values are within the
// range of [0.0,1.0] - including the leading zero.
setCssAll('opacity:.55');
// The non-literal . in this regex is intentional:
// German Chrome returns this value as 0,55
// github.com/Modernizr/Modernizr/issues/#issue/59/comment/516632
return (/^0.55$/).test(mStyle.opacity);
};
// Note, Android < 4 will pass this test, but can only animate
// a single property at a time
// daneden.me/2011/12/putting-up-with-androids-bullshit/
tests['cssanimations'] = function() {
return testPropsAll('animationName');
};
tests['csscolumns'] = function() {
return testPropsAll('columnCount');
};
tests['cssgradients'] = function() {
/**
* For CSS Gradients syntax, please see:
* webkit.org/blog/175/introducing-css-gradients/
* developer.mozilla.org/en/CSS/-moz-linear-gradient
* developer.mozilla.org/en/CSS/-moz-radial-gradient
* dev.w3.org/csswg/css3-images/#gradients-
*/
var str1 = 'background-image:',
str2 = 'gradient(linear,left top,right bottom,from(#9f9),to(white));',
str3 = 'linear-gradient(left top,#9f9, white);';
setCss(
// legacy webkit syntax (FIXME: remove when syntax not in use anymore)
(str1 + '-webkit- '.split(' ').join(str2 + str1) +
// standard syntax // trailing 'background-image:'
prefixes.join(str3 + str1)).slice(0, -str1.length)
);
return contains(mStyle.backgroundImage, 'gradient');
};
tests['cssreflections'] = function() {
return testPropsAll('boxReflect');
};
tests['csstransforms'] = function() {
return !!testPropsAll('transform');
};
tests['csstransforms3d'] = function() {
var ret = !!testPropsAll('perspective');
// Webkit's 3D transforms are passed off to the browser's own graphics renderer.
// It works fine in Safari on Leopard and Snow Leopard, but not in Chrome in
// some conditions. As a result, Webkit typically recognizes the syntax but
// will sometimes throw a false positive, thus we must do a more thorough check:
if ( ret && 'webkitPerspective' in docElement.style ) {
// Webkit allows this media query to succeed only if the feature is enabled.
// `@media (transform-3d),(-webkit-transform-3d){ ... }`
injectElementWithStyles('@media (transform-3d),(-webkit-transform-3d){#modernizr{left:9px;position:absolute;height:3px;}}', function( node, rule ) {
ret = node.offsetLeft === 9 && node.offsetHeight === 3;
});
}
return ret;
};
tests['csstransitions'] = function() {
return testPropsAll('transition');
};
/*>>fontface*/
// @font-face detection routine by Diego Perini
// javascript.nwbox.com/CSSSupport/
// false positives:
// WebOS github.com/Modernizr/Modernizr/issues/342
// WP7 github.com/Modernizr/Modernizr/issues/538
tests['fontface'] = function() {
var bool;
injectElementWithStyles('@font-face {font-family:"font";src:url("https://")}', function( node, rule ) {
var style = document.getElementById('smodernizr'),
sheet = style.sheet || style.styleSheet,
cssText = sheet ? (sheet.cssRules && sheet.cssRules[0] ? sheet.cssRules[0].cssText : sheet.cssText || '') : '';
bool = /src/i.test(cssText) && cssText.indexOf(rule.split(' ')[0]) === 0;
});
return bool;
};
/*>>fontface*/
// CSS generated content detection
tests['generatedcontent'] = function() {
var bool;
injectElementWithStyles(['#',mod,'{font:0/0 a}#',mod,':after{content:"',smile,'";visibility:hidden;font:3px/1 a}'].join(''), function( node ) {
bool = node.offsetHeight >= 3;
});
return bool;
};
// These tests evaluate support of the video/audio elements, as well as
// testing what types of content they support.
//
// We're using the Boolean constructor here, so that we can extend the value
// e.g. Modernizr.video // true
// Modernizr.video.ogg // 'probably'
//
// Codec values from : github.com/NielsLeenheer/html5test/blob/9106a8/index.html#L845
// thx to NielsLeenheer and zcorpan
// Note: in some older browsers, "no" was a return value instead of empty string.
// It was live in FF3.5.0 and 3.5.1, but fixed in 3.5.2
// It was also live in Safari 4.0.0 - 4.0.4, but fixed in 4.0.5
tests['video'] = function() {
var elem = document.createElement('video'),
bool = false;
// IE9 Running on Windows Server SKU can cause an exception to be thrown, bug #224
try {
if ( bool = !!elem.canPlayType ) {
bool = new Boolean(bool);
bool.ogg = elem.canPlayType('video/ogg; codecs="theora"') .replace(/^no$/,'');
// Without QuickTime, this value will be `undefined`. github.com/Modernizr/Modernizr/issues/546
bool.h264 = elem.canPlayType('video/mp4; codecs="avc1.42E01E"') .replace(/^no$/,'');
bool.webm = elem.canPlayType('video/webm; codecs="vp8, vorbis"').replace(/^no$/,'');
}
} catch(e) { }
return bool;
};
tests['audio'] = function() {
var elem = document.createElement('audio'),
bool = false;
try {
if ( bool = !!elem.canPlayType ) {
bool = new Boolean(bool);
bool.ogg = elem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/,'');
bool.mp3 = elem.canPlayType('audio/mpeg;') .replace(/^no$/,'');
// Mimetypes accepted:
// developer.mozilla.org/En/Media_formats_supported_by_the_audio_and_video_elements
// bit.ly/iphoneoscodecs
bool.wav = elem.canPlayType('audio/wav; codecs="1"') .replace(/^no$/,'');
bool.m4a = ( elem.canPlayType('audio/x-m4a;') ||
elem.canPlayType('audio/aac;')) .replace(/^no$/,'');
}
} catch(e) { }
return bool;
};
// In FF4, if disabled, window.localStorage should === null.
// Normally, we could not test that directly and need to do a
// `('localStorage' in window) && ` test first because otherwise Firefox will
// throw bugzil.la/365772 if cookies are disabled
// Also in iOS5 Private Browsing mode, attempting to use localStorage.setItem
// will throw the exception:
// QUOTA_EXCEEDED_ERRROR DOM Exception 22.
// Peculiarly, getItem and removeItem calls do not throw.
// Because we are forced to try/catch this, we'll go aggressive.
// Just FWIW: IE8 Compat mode supports these features completely:
// www.quirksmode.org/dom/html5.html
// But IE8 doesn't support either with local files
tests['localstorage'] = function() {
try {
localStorage.setItem(mod, mod);
localStorage.removeItem(mod);
return true;
} catch(e) {
return false;
}
};
tests['sessionstorage'] = function() {
try {
sessionStorage.setItem(mod, mod);
sessionStorage.removeItem(mod);
return true;
} catch(e) {
return false;
}
};
tests['webworkers'] = function() {
return !!window.Worker;
};
tests['applicationcache'] = function() {
return !!window.applicationCache;
};
// Thanks to Erik Dahlstrom
tests['svg'] = function() {
return !!document.createElementNS && !!document.createElementNS(ns.svg, 'svg').createSVGRect;
};
// specifically for SVG inline in HTML, not within XHTML
// test page: paulirish.com/demo/inline-svg
tests['inlinesvg'] = function() {
var div = document.createElement('div');
div.innerHTML = '<svg/>';
return (div.firstChild && div.firstChild.namespaceURI) == ns.svg;
};
// SVG SMIL animation
tests['smil'] = function() {
return !!document.createElementNS && /SVGAnimate/.test(toString.call(document.createElementNS(ns.svg, 'animate')));
};
// This test is only for clip paths in SVG proper, not clip paths on HTML content
// demo: srufaculty.sru.edu/david.dailey/svg/newstuff/clipPath4.svg
// However read the comments to dig into applying SVG clippaths to HTML content here:
// github.com/Modernizr/Modernizr/issues/213#issuecomment-1149491
tests['svgclippaths'] = function() {
return !!document.createElementNS && /SVGClipPath/.test(toString.call(document.createElementNS(ns.svg, 'clipPath')));
};
/*>>webforms*/
// input features and input types go directly onto the ret object, bypassing the tests loop.
// Hold this guy to execute in a moment.
function webforms() {
/*>>input*/
// Run through HTML5's new input attributes to see if the UA understands any.
// We're using f which is the <input> element created early on
// Mike Taylr has created a comprehensive resource for testing these attributes
// when applied to all input types:
// miketaylr.com/code/input-type-attr.html
// spec: www.whatwg.org/specs/web-apps/current-work/multipage/the-input-element.html#input-type-attr-summary
// Only input placeholder is tested while textarea's placeholder is not.
// Currently Safari 4 and Opera 11 have support only for the input placeholder
// Both tests are available in feature-detects/forms-placeholder.js
Modernizr['input'] = (function( props ) {
for ( var i = 0, len = props.length; i < len; i++ ) {
attrs[ props[i] ] = !!(props[i] in inputElem);
}
if (attrs.list){
// safari false positive's on datalist: webk.it/74252
// see also github.com/Modernizr/Modernizr/issues/146
attrs.list = !!(document.createElement('datalist') && window.HTMLDataListElement);
}
return attrs;
})('autocomplete autofocus list placeholder max min multiple pattern required step'.split(' '));
/*>>input*/
/*>>inputtypes*/
// Run through HTML5's new input types to see if the UA understands any.
// This is put behind the tests runloop because it doesn't return a
// true/false like all the other tests; instead, it returns an object
// containing each input type with its corresponding true/false value
// Big thanks to @miketaylr for the html5 forms expertise. miketaylr.com/
Modernizr['inputtypes'] = (function(props) {
for ( var i = 0, bool, inputElemType, defaultView, len = props.length; i < len; i++ ) {
inputElem.setAttribute('type', inputElemType = props[i]);
bool = inputElem.type !== 'text';
// We first check to see if the type we give it sticks..
// If the type does, we feed it a textual value, which shouldn't be valid.
// If the value doesn't stick, we know there's input sanitization which infers a custom UI
if ( bool ) {
inputElem.value = smile;
inputElem.style.cssText = 'position:absolute;visibility:hidden;';
if ( /^range$/.test(inputElemType) && inputElem.style.WebkitAppearance !== undefined ) {
docElement.appendChild(inputElem);
defaultView = document.defaultView;
// Safari 2-4 allows the smiley as a value, despite making a slider
bool = defaultView.getComputedStyle &&
defaultView.getComputedStyle(inputElem, null).WebkitAppearance !== 'textfield' &&
// Mobile android web browser has false positive, so must
// check the height to see if the widget is actually there.
(inputElem.offsetHeight !== 0);
docElement.removeChild(inputElem);
} else if ( /^(search|tel)$/.test(inputElemType) ){
// Spec doesn't define any special parsing or detectable UI
// behaviors so we pass these through as true
// Interestingly, opera fails the earlier test, so it doesn't
// even make it here.
} else if ( /^(url|email)$/.test(inputElemType) ) {
// Real url and email support comes with prebaked validation.
bool = inputElem.checkValidity && inputElem.checkValidity() === false;
} else {
// If the upgraded input compontent rejects the :) text, we got a winner
bool = inputElem.value != smile;
}
}
inputs[ props[i] ] = !!bool;
}
return inputs;
})('search tel url email datetime date month week time datetime-local number range color'.split(' '));
/*>>inputtypes*/
}
/*>>webforms*/
// End of test definitions
// -----------------------
// Run through all tests and detect their support in the current UA.
// todo: hypothetically we could be doing an array of tests and use a basic loop here.
for ( var feature in tests ) {
if ( hasOwnProp(tests, feature) ) {
// run the test, throw the return value into the Modernizr,
// then based on that boolean, define an appropriate className
// and push it into an array of classes we'll join later.
featureName = feature.toLowerCase();
Modernizr[featureName] = tests[feature]();
classes.push((Modernizr[featureName] ? '' : 'no-') + featureName);
}
}
/*>>webforms*/
// input tests need to run.
Modernizr.input || webforms();
/*>>webforms*/
/**
* addTest allows the user to define their own feature tests
* the result will be added onto the Modernizr object,
* as well as an appropriate className set on the html element
*
* @param feature - String naming the feature
* @param test - Function returning true if feature is supported, false if not
*/
Modernizr.addTest = function ( feature, test ) {
if ( typeof feature == 'object' ) {
for ( var key in feature ) {
if ( hasOwnProp( feature, key ) ) {
Modernizr.addTest( key, feature[ key ] );
}
}
} else {
feature = feature.toLowerCase();
if ( Modernizr[feature] !== undefined ) {
// we're going to quit if you're trying to overwrite an existing test
// if we were to allow it, we'd do this:
// var re = new RegExp("\\b(no-)?" + feature + "\\b");
// docElement.className = docElement.className.replace( re, '' );
// but, no rly, stuff 'em.
return Modernizr;
}
test = typeof test == 'function' ? test() : test;
if (typeof enableClasses !== "undefined" && enableClasses) {
docElement.className += ' ' + (test ? '' : 'no-') + feature;
}
Modernizr[feature] = test;
}
return Modernizr; // allow chaining.
};
// Reset modElem.cssText to nothing to reduce memory footprint.
setCss('');
modElem = inputElem = null;
/*>>shiv*/
/*! HTML5 Shiv v3.6.1 | @afarkas @jdalton @jon_neal @rem | MIT/GPL2 Licensed */
;(function(window, document) {
/*jshint evil:true */
/** Preset options */
var options = window.html5 || {};
/** Used to skip problem elements */
var reSkip = /^<|^(?:button|map|select|textarea|object|iframe|option|optgroup)$/i;
/** Not all elements can be cloned in IE **/
var saveClones = /^(?:a|b|code|div|fieldset|h1|h2|h3|h4|h5|h6|i|label|li|ol|p|q|span|strong|style|table|tbody|td|th|tr|ul)$/i;
/** Detect whether the browser supports default html5 styles */
var supportsHtml5Styles;
/** Name of the expando, to work with multiple documents or to re-shiv one document */
var expando = '_html5shiv';
/** The id for the the documents expando */
var expanID = 0;
/** Cached data for each document */
var expandoData = {};
/** Detect whether the browser supports unknown elements */
var supportsUnknownElements;
(function() {
try {
var a = document.createElement('a');
a.innerHTML = '<xyz></xyz>';
//if the hidden property is implemented we can assume, that the browser supports basic HTML5 Styles
supportsHtml5Styles = ('hidden' in a);
supportsUnknownElements = a.childNodes.length == 1 || (function() {
// assign a false positive if unable to shiv
(document.createElement)('a');
var frag = document.createDocumentFragment();
return (
typeof frag.cloneNode == 'undefined' ||
typeof frag.createDocumentFragment == 'undefined' ||
typeof frag.createElement == 'undefined'
);
}());
} catch(e) {
supportsHtml5Styles = true;
supportsUnknownElements = true;
}
}());
/*--------------------------------------------------------------------------*/
/**
* Creates a style sheet with the given CSS text and adds it to the document.
* @private
* @param {Document} ownerDocument The document.
* @param {String} cssText The CSS text.
* @returns {StyleSheet} The style element.
*/
function addStyleSheet(ownerDocument, cssText) {
var p = ownerDocument.createElement('p'),
parent = ownerDocument.getElementsByTagName('head')[0] || ownerDocument.documentElement;
p.innerHTML = 'x<style>' + cssText + '</style>';
return parent.insertBefore(p.lastChild, parent.firstChild);
}
/**
* Returns the value of `html5.elements` as an array.
* @private
* @returns {Array} An array of shived element node names.
*/
function getElements() {
var elements = html5.elements;
return typeof elements == 'string' ? elements.split(' ') : elements;
}
/**
* Returns the data associated to the given document
* @private
* @param {Document} ownerDocument The document.
* @returns {Object} An object of data.
*/
function getExpandoData(ownerDocument) {
var data = expandoData[ownerDocument[expando]];
if (!data) {
data = {};
expanID++;
ownerDocument[expando] = expanID;
expandoData[expanID] = data;
}
return data;
}
/**
* returns a shived element for the given nodeName and document
* @memberOf html5
* @param {String} nodeName name of the element
* @param {Document} ownerDocument The context document.
* @returns {Object} The shived element.
*/
function createElement(nodeName, ownerDocument, data){
if (!ownerDocument) {
ownerDocument = document;
}
if(supportsUnknownElements){
return ownerDocument.createElement(nodeName);
}
if (!data) {
data = getExpandoData(ownerDocument);
}
var node;
if (data.cache[nodeName]) {
node = data.cache[nodeName].cloneNode();
} else if (saveClones.test(nodeName)) {
node = (data.cache[nodeName] = data.createElem(nodeName)).cloneNode();
} else {
node = data.createElem(nodeName);
}
// Avoid adding some elements to fragments in IE < 9 because
// * Attributes like `name` or `type` cannot be set/changed once an element
// is inserted into a document/fragment
// * Link elements with `src` attributes that are inaccessible, as with
// a 403 response, will cause the tab/window to crash
// * Script elements appended to fragments will execute when their `src`
// or `text` property is set
return node.canHaveChildren && !reSkip.test(nodeName) ? data.frag.appendChild(node) : node;
}
/**
* returns a shived DocumentFragment for the given document
* @memberOf html5
* @param {Document} ownerDocument The context document.
* @returns {Object} The shived DocumentFragment.
*/
function createDocumentFragment(ownerDocument, data){
if (!ownerDocument) {
ownerDocument = document;
}
if(supportsUnknownElements){
return ownerDocument.createDocumentFragment();
}
data = data || getExpandoData(ownerDocument);
var clone = data.frag.cloneNode(),
i = 0,
elems = getElements(),
l = elems.length;
for(;i<l;i++){
clone.createElement(elems[i]);
}
return clone;
}
/**
* Shivs the `createElement` and `createDocumentFragment` methods of the document.
* @private
* @param {Document|DocumentFragment} ownerDocument The document.
* @param {Object} data of the document.
*/
function shivMethods(ownerDocument, data) {
if (!data.cache) {
data.cache = {};
data.createElem = ownerDocument.createElement;
data.createFrag = ownerDocument.createDocumentFragment;
data.frag = data.createFrag();
}
ownerDocument.createElement = function(nodeName) {
//abort shiv
if (!html5.shivMethods) {
return data.createElem(nodeName);
}
return createElement(nodeName, ownerDocument, data);
};
ownerDocument.createDocumentFragment = Function('h,f', 'return function(){' +
'var n=f.cloneNode(),c=n.createElement;' +
'h.shivMethods&&(' +
// unroll the `createElement` calls
getElements().join().replace(/\w+/g, function(nodeName) {
data.createElem(nodeName);
data.frag.createElement(nodeName);
return 'c("' + nodeName + '")';
}) +
');return n}'
)(html5, data.frag);
}
/*--------------------------------------------------------------------------*/
/**
* Shivs the given document.
* @memberOf html5
* @param {Document} ownerDocument The document to shiv.
* @returns {Document} The shived document.
*/
function shivDocument(ownerDocument) {
if (!ownerDocument) {
ownerDocument = document;
}
var data = getExpandoData(ownerDocument);
if (html5.shivCSS && !supportsHtml5Styles && !data.hasCSS) {
data.hasCSS = !!addStyleSheet(ownerDocument,
// corrects block display not defined in IE6/7/8/9
'article,aside,figcaption,figure,footer,header,hgroup,nav,section{display:block}' +
// adds styling not present in IE6/7/8/9
'mark{background:#FF0;color:#000}'
);
}
if (!supportsUnknownElements) {
shivMethods(ownerDocument, data);
}
return ownerDocument;
}
/*--------------------------------------------------------------------------*/
/**
* The `html5` object is exposed so that more elements can be shived and
* existing shiving can be detected on iframes.
* @type Object
* @example
*
* // options can be changed before the script is included
* html5 = { 'elements': 'mark section', 'shivCSS': false, 'shivMethods': false };
*/
var html5 = {
/**
* An array or space separated string of node names of the elements to shiv.
* @memberOf html5
* @type Array|String
*/
'elements': options.elements || 'abbr article aside audio bdi canvas data datalist details figcaption figure footer header hgroup mark meter nav output progress section summary time video',
/**
* A flag to indicate that the HTML5 style sheet should be inserted.
* @memberOf html5
* @type Boolean
*/
'shivCSS': (options.shivCSS !== false),
/**
* Is equal to true if a browser supports creating unknown/HTML5 elements
* @memberOf html5
* @type boolean
*/
'supportsUnknownElements': supportsUnknownElements,
/**
* A flag to indicate that the document's `createElement` and `createDocumentFragment`
* methods should be overwritten.
* @memberOf html5
* @type Boolean
*/
'shivMethods': (options.shivMethods !== false),
/**
* A string to describe the type of `html5` object ("default" or "default print").
* @memberOf html5
* @type String
*/
'type': 'default',
// shivs the document according to the specified `html5` object options
'shivDocument': shivDocument,
//creates a shived element
createElement: createElement,
//creates a shived documentFragment
createDocumentFragment: createDocumentFragment
};
/*--------------------------------------------------------------------------*/
// expose html5
window.html5 = html5;
// shiv the document
shivDocument(document);
}(this, document));
/*>>shiv*/
// Assign private properties to the return object with prefix
Modernizr._version = version;
// expose these for the plugin API. Look in the source for how to join() them against your input
/*>>prefixes*/
Modernizr._prefixes = prefixes;
/*>>prefixes*/
/*>>domprefixes*/
Modernizr._domPrefixes = domPrefixes;
Modernizr._cssomPrefixes = cssomPrefixes;
/*>>domprefixes*/
/*>>mq*/
// Modernizr.mq tests a given media query, live against the current state of the window
// A few important notes:
// * If a browser does not support media queries at all (eg. oldIE) the mq() will always return false
// * A max-width or orientation query will be evaluated against the current state, which may change later.
// * You must specify values. Eg. If you are testing support for the min-width media query use:
// Modernizr.mq('(min-width:0)')
// usage:
// Modernizr.mq('only screen and (max-width:768)')
Modernizr.mq = testMediaQuery;
/*>>mq*/
/*>>hasevent*/
// Modernizr.hasEvent() detects support for a given event, with an optional element to test on
// Modernizr.hasEvent('gesturestart', elem)
Modernizr.hasEvent = isEventSupported;
/*>>hasevent*/
/*>>testprop*/
// Modernizr.testProp() investigates whether a given style property is recognized
// Note that the property names must be provided in the camelCase variant.
// Modernizr.testProp('pointerEvents')
Modernizr.testProp = function(prop){
return testProps([prop]);
};
/*>>testprop*/
/*>>testallprops*/
// Modernizr.testAllProps() investigates whether a given style property,
// or any of its vendor-prefixed variants, is recognized
// Note that the property names must be provided in the camelCase variant.
// Modernizr.testAllProps('boxSizing')
Modernizr.testAllProps = testPropsAll;
/*>>testallprops*/
/*>>teststyles*/
// Modernizr.testStyles() allows you to add custom styles to the document and test an element afterwards
// Modernizr.testStyles('#modernizr { position:absolute }', function(elem, rule){ ... })
Modernizr.testStyles = injectElementWithStyles;
/*>>teststyles*/
/*>>prefixed*/
// Modernizr.prefixed() returns the prefixed or nonprefixed property name variant of your input
// Modernizr.prefixed('boxSizing') // 'MozBoxSizing'
// Properties must be passed as dom-style camelcase, rather than `box-sizing` hypentated style.
// Return values will also be the camelCase variant, if you need to translate that to hypenated style use:
//
// str.replace(/([A-Z])/g, function(str,m1){ return '-' + m1.toLowerCase(); }).replace(/^ms-/,'-ms-');
// If you're trying to ascertain which transition end event to bind to, you might do something like...
//
// var transEndEventNames = {
// 'WebkitTransition' : 'webkitTransitionEnd',
// 'MozTransition' : 'transitionend',
// 'OTransition' : 'oTransitionEnd',
// 'msTransition' : 'MSTransitionEnd',
// 'transition' : 'transitionend'
// },
// transEndEventName = transEndEventNames[ Modernizr.prefixed('transition') ];
Modernizr.prefixed = function(prop, obj, elem){
if(!obj) {
return testPropsAll(prop, 'pfx');
} else {
// Testing DOM property e.g. Modernizr.prefixed('requestAnimationFrame', window) // 'mozRequestAnimationFrame'
return testPropsAll(prop, obj, elem);
}
};
/*>>prefixed*/
/*>>cssclasses*/
// Remove "no-js" class from <html> element, if it exists:
docElement.className = docElement.className.replace(/(^|\s)no-js(\s|$)/, '$1$2') +
// Add the new classes to the <html> element.
(enableClasses ? ' js ' + classes.join(' ') : '');
/*>>cssclasses*/
return Modernizr;
})(this, this.document);
|
import { getModel } from '$lib/db.js';
export async function get({ params }) {
const { Bottle } = await getModel();
const { wineid } = params;
const bottles = await Bottle.findAll({
where: {
WineId: wineid
}
});
return {
body: {
bottles
}
};
}
|
var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value:true});exports.default=getDistanceForDirection;var _getInvertedMultiplier=_interopRequireDefault(require("./getInvertedMultiplier"));function getDistanceForDirection(layout,gestureDirection){var multiplier=(0,_getInvertedMultiplier.default)(gestureDirection);switch(gestureDirection){case'vertical':case'vertical-inverted':return layout.height*multiplier;case'horizontal':case'horizontal-inverted':return layout.width*multiplier;}}
//# sourceMappingURL=getDistanceForDirection.js.map
|
/**
* Check if date is within a min and max
*/
export function inRange(date, min, max) {
const time = date.getTime();
const afterMin = !(min instanceof Date) || time >= min.getTime();
const beforeMax = !(max instanceof Date) || time <= max.getTime();
return afterMin && beforeMax;
}
/**
* Ensures date is within range,
* returns min or max if out of bounds
*/
export function dateFromRange(date, min, max) {
if (!(date instanceof Date)) {
return null;
}
const time = date.getTime();
const beforeMin = min instanceof Date && time < min.getTime();
const afterMax = max instanceof Date && time > max.getTime();
if (beforeMin) {
return min;
}
if (afterMax) {
return max;
}
return date;
}
/**
* Parse an iso8601 string (YYYY-mm-dd) into a valid date.
* TODO: handle time when time of day UI is added
*/
export function dateFromISO(iso8601) {
if (iso8601 instanceof Date) {
return iso8601;
}
if (!iso8601 || typeof iso8601 !== "string") {
return null;
}
const d = iso8601.split(/[: T-]/).map(parseFloat);
const date = new Date(d[0], (d[1] || 1) - 1, d[2] || 1);
date.setFullYear(d[0]);
if (isNaN(date.getTime())) {
throw new Error(`Invalid ISO 8601 date: "${iso8601}"`);
}
return date;
}
/**
* Return first portion of ISO string (YYYY-mm-dd)
*/
export function dateToISO(date) {
if (typeof date === "string") {
return date;
}
if (date instanceof Date) {
return date.toISOString().split("T")[0];
}
return "";
}
/**
* Check if two dates are the same day, month, year
*/
export function sameDate(d1, d2) {
return (d1 instanceof Date &&
d2 instanceof Date &&
d1.getDate() === d2.getDate() &&
d1.getMonth() === d2.getMonth() &&
d1.getFullYear() === d2.getFullYear());
}
/**
* Get a date one month in the past
*/
export function prevMonth(date) {
const month = date.getMonth();
const nextDate = new Date(date);
nextDate.setMonth(month - 1);
// date doesn't exist in new month, use last day
if (month === nextDate.getMonth()) {
return new Date(date.getFullYear(), month, 0);
}
return nextDate;
}
/**
* Get a date one month in the future
*/
export function nextMonth(date) {
const month = date.getMonth();
const nextDate = new Date(date);
nextDate.setMonth(month + 1);
// date doesn't exist in new month, use last day
if ((month + 2) % 7 === nextDate.getMonth() % 7) {
return new Date(date.getFullYear(), month + 2, 0);
}
return nextDate;
}
/**
* Translate a number into a given locals numeral system
*/
export function localizeNumber(num, localeData) {
return String(num)
.split("")
.map((i) => localeData.numerals[i])
.join("");
}
/**
* Calculate actual number from localized string
*/
export function parseNumber(str, localeData) {
const numerals = "0123456789";
return parseInt(str
.split("")
.map((i) => numerals[localeData.numerals.indexOf(i)])
.filter((num) => num)
.join(""));
}
/**
* Parse numeric units for day, month, and year from a localized string
* month starts at 0 (can pass to date constructor)
*/
export function parseDateString(str, localeData) {
const { separator, unitOrder } = localeData;
const order = getOrder(unitOrder);
const values = replaceArabicNumerals(str).split(separator);
return {
day: parseInt(values[order.indexOf("d")]),
month: parseInt(values[order.indexOf("m")]) - 1,
year: parseInt(values[order.indexOf("y")])
};
}
/**
* Convert eastern arbic numerals
*/
export function replaceArabicNumerals(str = "") {
return str
.replace(/[\u0660-\u0669]/g, (c) => (c.charCodeAt(0) - 0x0660))
.replace(/[\u06f0-\u06f9]/g, (c) => (c.charCodeAt(0) - 0x06f0));
}
/**
* Based on the unitOrder string, find order of month, day, and year for locale
*/
export function getOrder(unitOrder) {
const signifiers = ["d", "m", "y"];
const order = unitOrder.toLowerCase();
return signifiers.sort((a, b) => order.indexOf(a) - order.indexOf(b));
}
/**
* Get number of days between two dates
*/
export function getDaysDiff(date1, date2) {
const ts1 = date1.getTime();
const ts2 = date2.getTime();
return Math.abs(ts1 - ts2) * 1000 * 60 * 60 * 24;
}
|
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import { SelectionModel, isDataSource } from '@angular/cdk/collections';
import { __extends } from 'tslib';
import { Observable, BehaviorSubject, of, Subject } from 'rxjs';
import { take, filter, takeUntil } from 'rxjs/operators';
import { Directive, TemplateRef, ViewContainerRef, ChangeDetectionStrategy, ChangeDetectorRef, Component, ContentChildren, ElementRef, Input, IterableDiffers, ViewChild, ViewEncapsulation, Optional, Renderer2, NgModule } from '@angular/core';
import { Directionality } from '@angular/cdk/bidi';
import { coerceNumberProperty, coerceBooleanProperty } from '@angular/cdk/coercion';
import { FocusMonitor } from '@angular/cdk/a11y';
import { CommonModule } from '@angular/common';
/**
* @fileoverview added by tsickle
* @suppress {checkTypes,extraRequire,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* Base tree control. It has basic toggle/expand/collapse operations on a single data node.
* @abstract
* @template T
*/
var /**
* Base tree control. It has basic toggle/expand/collapse operations on a single data node.
* @abstract
* @template T
*/
BaseTreeControl = /** @class */ (function () {
function BaseTreeControl() {
/**
* A selection model with multi-selection to track expansion status.
*/
this.expansionModel = new SelectionModel(true);
}
/** Toggles one single data node's expanded/collapsed state. */
/**
* Toggles one single data node's expanded/collapsed state.
* @param {?} dataNode
* @return {?}
*/
BaseTreeControl.prototype.toggle = /**
* Toggles one single data node's expanded/collapsed state.
* @param {?} dataNode
* @return {?}
*/
function (dataNode) {
this.expansionModel.toggle(dataNode);
};
/** Expands one single data node. */
/**
* Expands one single data node.
* @param {?} dataNode
* @return {?}
*/
BaseTreeControl.prototype.expand = /**
* Expands one single data node.
* @param {?} dataNode
* @return {?}
*/
function (dataNode) {
this.expansionModel.select(dataNode);
};
/** Collapses one single data node. */
/**
* Collapses one single data node.
* @param {?} dataNode
* @return {?}
*/
BaseTreeControl.prototype.collapse = /**
* Collapses one single data node.
* @param {?} dataNode
* @return {?}
*/
function (dataNode) {
this.expansionModel.deselect(dataNode);
};
/** Whether a given data node is expanded or not. Returns true if the data node is expanded. */
/**
* Whether a given data node is expanded or not. Returns true if the data node is expanded.
* @param {?} dataNode
* @return {?}
*/
BaseTreeControl.prototype.isExpanded = /**
* Whether a given data node is expanded or not. Returns true if the data node is expanded.
* @param {?} dataNode
* @return {?}
*/
function (dataNode) {
return this.expansionModel.isSelected(dataNode);
};
/** Toggles a subtree rooted at `node` recursively. */
/**
* Toggles a subtree rooted at `node` recursively.
* @param {?} dataNode
* @return {?}
*/
BaseTreeControl.prototype.toggleDescendants = /**
* Toggles a subtree rooted at `node` recursively.
* @param {?} dataNode
* @return {?}
*/
function (dataNode) {
this.expansionModel.isSelected(dataNode)
? this.collapseDescendants(dataNode)
: this.expandDescendants(dataNode);
};
/** Collapse all dataNodes in the tree. */
/**
* Collapse all dataNodes in the tree.
* @return {?}
*/
BaseTreeControl.prototype.collapseAll = /**
* Collapse all dataNodes in the tree.
* @return {?}
*/
function () {
this.expansionModel.clear();
};
/** Expands a subtree rooted at given data node recursively. */
/**
* Expands a subtree rooted at given data node recursively.
* @param {?} dataNode
* @return {?}
*/
BaseTreeControl.prototype.expandDescendants = /**
* Expands a subtree rooted at given data node recursively.
* @param {?} dataNode
* @return {?}
*/
function (dataNode) {
var _a;
/** @type {?} */
var toBeProcessed = [dataNode];
toBeProcessed.push.apply(toBeProcessed, this.getDescendants(dataNode));
(_a = this.expansionModel).select.apply(_a, toBeProcessed);
};
/** Collapses a subtree rooted at given data node recursively. */
/**
* Collapses a subtree rooted at given data node recursively.
* @param {?} dataNode
* @return {?}
*/
BaseTreeControl.prototype.collapseDescendants = /**
* Collapses a subtree rooted at given data node recursively.
* @param {?} dataNode
* @return {?}
*/
function (dataNode) {
var _a;
/** @type {?} */
var toBeProcessed = [dataNode];
toBeProcessed.push.apply(toBeProcessed, this.getDescendants(dataNode));
(_a = this.expansionModel).deselect.apply(_a, toBeProcessed);
};
return BaseTreeControl;
}());
/**
* @fileoverview added by tsickle
* @suppress {checkTypes,extraRequire,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* Flat tree control. Able to expand/collapse a subtree recursively for flattened tree.
* @template T
*/
var /**
* Flat tree control. Able to expand/collapse a subtree recursively for flattened tree.
* @template T
*/
FlatTreeControl = /** @class */ (function (_super) {
__extends(FlatTreeControl, _super);
/** Construct with flat tree data node functions getLevel and isExpandable. */
function FlatTreeControl(getLevel, isExpandable) {
var _this = _super.call(this) || this;
_this.getLevel = getLevel;
_this.isExpandable = isExpandable;
return _this;
}
/**
* Gets a list of the data node's subtree of descendent data nodes.
*
* To make this working, the `dataNodes` of the TreeControl must be flattened tree nodes
* with correct levels.
*/
/**
* Gets a list of the data node's subtree of descendent data nodes.
*
* To make this working, the `dataNodes` of the TreeControl must be flattened tree nodes
* with correct levels.
* @param {?} dataNode
* @return {?}
*/
FlatTreeControl.prototype.getDescendants = /**
* Gets a list of the data node's subtree of descendent data nodes.
*
* To make this working, the `dataNodes` of the TreeControl must be flattened tree nodes
* with correct levels.
* @param {?} dataNode
* @return {?}
*/
function (dataNode) {
/** @type {?} */
var startIndex = this.dataNodes.indexOf(dataNode);
/** @type {?} */
var results = [];
// Goes through flattened tree nodes in the `dataNodes` array, and get all descendants.
// The level of descendants of a tree node must be greater than the level of the given
// tree node.
// If we reach a node whose level is equal to the level of the tree node, we hit a sibling.
// If we reach a node whose level is greater than the level of the tree node, we hit a
// sibling of an ancestor.
for (var i = startIndex + 1; i < this.dataNodes.length && this.getLevel(dataNode) < this.getLevel(this.dataNodes[i]); i++) {
results.push(this.dataNodes[i]);
}
return results;
};
/**
* Expands all data nodes in the tree.
*
* To make this working, the `dataNodes` variable of the TreeControl must be set to all flattened
* data nodes of the tree.
*/
/**
* Expands all data nodes in the tree.
*
* To make this working, the `dataNodes` variable of the TreeControl must be set to all flattened
* data nodes of the tree.
* @return {?}
*/
FlatTreeControl.prototype.expandAll = /**
* Expands all data nodes in the tree.
*
* To make this working, the `dataNodes` variable of the TreeControl must be set to all flattened
* data nodes of the tree.
* @return {?}
*/
function () {
var _a;
(_a = this.expansionModel).select.apply(_a, this.dataNodes);
};
return FlatTreeControl;
}(BaseTreeControl));
/**
* @fileoverview added by tsickle
* @suppress {checkTypes,extraRequire,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* Nested tree control. Able to expand/collapse a subtree recursively for NestedNode type.
* @template T
*/
var /**
* Nested tree control. Able to expand/collapse a subtree recursively for NestedNode type.
* @template T
*/
NestedTreeControl = /** @class */ (function (_super) {
__extends(NestedTreeControl, _super);
/** Construct with nested tree function getChildren. */
function NestedTreeControl(getChildren) {
var _this = _super.call(this) || this;
_this.getChildren = getChildren;
return _this;
}
/**
* Expands all dataNodes in the tree.
*
* To make this working, the `dataNodes` variable of the TreeControl must be set to all root level
* data nodes of the tree.
*/
/**
* Expands all dataNodes in the tree.
*
* To make this working, the `dataNodes` variable of the TreeControl must be set to all root level
* data nodes of the tree.
* @return {?}
*/
NestedTreeControl.prototype.expandAll = /**
* Expands all dataNodes in the tree.
*
* To make this working, the `dataNodes` variable of the TreeControl must be set to all root level
* data nodes of the tree.
* @return {?}
*/
function () {
var _this = this;
var _a;
this.expansionModel.clear();
/** @type {?} */
var allNodes = this.dataNodes.reduce(function (accumulator, dataNode) {
return accumulator.concat(_this.getDescendants(dataNode), [dataNode]);
}, []);
(_a = this.expansionModel).select.apply(_a, allNodes);
};
/** Gets a list of descendant dataNodes of a subtree rooted at given data node recursively. */
/**
* Gets a list of descendant dataNodes of a subtree rooted at given data node recursively.
* @param {?} dataNode
* @return {?}
*/
NestedTreeControl.prototype.getDescendants = /**
* Gets a list of descendant dataNodes of a subtree rooted at given data node recursively.
* @param {?} dataNode
* @return {?}
*/
function (dataNode) {
/** @type {?} */
var descendants = [];
this._getDescendants(descendants, dataNode);
// Remove the node itself
return descendants.splice(1);
};
/** A helper function to get descendants recursively. */
/**
* A helper function to get descendants recursively.
* @protected
* @param {?} descendants
* @param {?} dataNode
* @return {?}
*/
NestedTreeControl.prototype._getDescendants = /**
* A helper function to get descendants recursively.
* @protected
* @param {?} descendants
* @param {?} dataNode
* @return {?}
*/
function (descendants, dataNode) {
var _this = this;
descendants.push(dataNode);
/** @type {?} */
var childrenNodes = this.getChildren(dataNode);
if (Array.isArray(childrenNodes)) {
childrenNodes.forEach(function (child) { return _this._getDescendants(descendants, child); });
}
else if (childrenNodes instanceof Observable) {
childrenNodes.pipe(take(1), filter(Boolean)).subscribe(function (children) {
children.forEach(function (child) { return _this._getDescendants(descendants, child); });
});
}
};
return NestedTreeControl;
}(BaseTreeControl));
/**
* @fileoverview added by tsickle
* @suppress {checkTypes,extraRequire,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* @fileoverview added by tsickle
* @suppress {checkTypes,extraRequire,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* Context provided to the tree node component.
* @template T
*/
var /**
* Context provided to the tree node component.
* @template T
*/
CdkTreeNodeOutletContext = /** @class */ (function () {
function CdkTreeNodeOutletContext(data) {
this.$implicit = data;
}
return CdkTreeNodeOutletContext;
}());
/**
* Data node definition for the CdkTree.
* Captures the node's template and a when predicate that describes when this node should be used.
* @template T
*/
var CdkTreeNodeDef = /** @class */ (function () {
/** @docs-private */
function CdkTreeNodeDef(template) {
this.template = template;
}
CdkTreeNodeDef.decorators = [
{ type: Directive, args: [{
selector: '[cdkTreeNodeDef]',
inputs: [
'when: cdkTreeNodeDefWhen'
],
},] },
];
/** @nocollapse */
CdkTreeNodeDef.ctorParameters = function () { return [
{ type: TemplateRef }
]; };
return CdkTreeNodeDef;
}());
/**
* @fileoverview added by tsickle
* @suppress {checkTypes,extraRequire,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* Outlet for nested CdkNode. Put `[cdkTreeNodeOutlet]` on a tag to place children dataNodes
* inside the outlet.
*/
var CdkTreeNodeOutlet = /** @class */ (function () {
function CdkTreeNodeOutlet(viewContainer) {
this.viewContainer = viewContainer;
}
CdkTreeNodeOutlet.decorators = [
{ type: Directive, args: [{
selector: '[cdkTreeNodeOutlet]'
},] },
];
/** @nocollapse */
CdkTreeNodeOutlet.ctorParameters = function () { return [
{ type: ViewContainerRef }
]; };
return CdkTreeNodeOutlet;
}());
/**
* @fileoverview added by tsickle
* @suppress {checkTypes,extraRequire,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* Returns an error to be thrown when there is no usable data.
* \@docs-private
* @return {?}
*/
function getTreeNoValidDataSourceError() {
return Error("A valid data source must be provided.");
}
/**
* Returns an error to be thrown when there are multiple nodes that are missing a when function.
* \@docs-private
* @return {?}
*/
function getTreeMultipleDefaultNodeDefsError() {
return Error("There can only be one default row without a when predicate function.");
}
/**
* Returns an error to be thrown when there are no matching node defs for a particular set of data.
* \@docs-private
* @return {?}
*/
function getTreeMissingMatchingNodeDefError() {
return Error("Could not find a matching node definition for the provided node data.");
}
/**
* Returns an error to be thrown when there are tree control.
* \@docs-private
* @return {?}
*/
function getTreeControlMissingError() {
return Error("Could not find a tree control for the tree.");
}
/**
* Returns an error to be thrown when tree control did not implement functions for flat/nested node.
* \@docs-private
* @return {?}
*/
function getTreeControlFunctionsMissingError() {
return Error("Could not find functions for nested/flat tree in tree control.");
}
/**
* @fileoverview added by tsickle
* @suppress {checkTypes,extraRequire,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* CDK tree component that connects with a data source to retrieve data of type `T` and renders
* dataNodes with hierarchy. Updates the dataNodes when new data is provided by the data source.
* @template T
*/
var CdkTree = /** @class */ (function () {
function CdkTree(_differs, _changeDetectorRef) {
this._differs = _differs;
this._changeDetectorRef = _changeDetectorRef;
/**
* Subject that emits when the component has been destroyed.
*/
this._onDestroy = new Subject();
/**
* Level of nodes
*/
this._levels = new Map();
// TODO(tinayuangao): Setup a listener for scrolling, emit the calculated view to viewChange.
// Remove the MAX_VALUE in viewChange
/**
* Stream containing the latest information on what rows are being displayed on screen.
* Can be used by the data source to as a heuristic of what data should be provided.
*/
this.viewChange = new BehaviorSubject({ start: 0, end: Number.MAX_VALUE });
}
Object.defineProperty(CdkTree.prototype, "dataSource", {
/**
* Provides a stream containing the latest data array to render. Influenced by the tree's
* stream of view window (what dataNodes are currently on screen).
* Data source can be an observable of data array, or a data array to render.
*/
get: /**
* Provides a stream containing the latest data array to render. Influenced by the tree's
* stream of view window (what dataNodes are currently on screen).
* Data source can be an observable of data array, or a data array to render.
* @return {?}
*/
function () { return this._dataSource; },
set: /**
* @param {?} dataSource
* @return {?}
*/
function (dataSource) {
if (this._dataSource !== dataSource) {
this._switchDataSource(dataSource);
}
},
enumerable: true,
configurable: true
});
/**
* @return {?}
*/
CdkTree.prototype.ngOnInit = /**
* @return {?}
*/
function () {
this._dataDiffer = this._differs.find([]).create(this.trackBy);
if (!this.treeControl) {
throw getTreeControlMissingError();
}
};
/**
* @return {?}
*/
CdkTree.prototype.ngOnDestroy = /**
* @return {?}
*/
function () {
this._nodeOutlet.viewContainer.clear();
this._onDestroy.next();
this._onDestroy.complete();
if (this._dataSource && typeof ((/** @type {?} */ (this._dataSource))).disconnect === 'function') {
((/** @type {?} */ (this.dataSource))).disconnect(this);
}
if (this._dataSubscription) {
this._dataSubscription.unsubscribe();
this._dataSubscription = null;
}
};
/**
* @return {?}
*/
CdkTree.prototype.ngAfterContentChecked = /**
* @return {?}
*/
function () {
/** @type {?} */
var defaultNodeDefs = this._nodeDefs.filter(function (def) { return !def.when; });
if (defaultNodeDefs.length > 1) {
throw getTreeMultipleDefaultNodeDefsError();
}
this._defaultNodeDef = defaultNodeDefs[0];
if (this.dataSource && this._nodeDefs && !this._dataSubscription) {
this._observeRenderChanges();
}
};
// TODO(tinayuangao): Work on keyboard traversal and actions, make sure it's working for RTL
// and nested trees.
/**
* Switch to the provided data source by resetting the data and unsubscribing from the current
* render change subscription if one exists. If the data source is null, interpret this by
* clearing the node outlet. Otherwise start listening for new data.
*/
// TODO(tinayuangao): Work on keyboard traversal and actions, make sure it's working for RTL
// and nested trees.
/**
* Switch to the provided data source by resetting the data and unsubscribing from the current
* render change subscription if one exists. If the data source is null, interpret this by
* clearing the node outlet. Otherwise start listening for new data.
* @private
* @param {?} dataSource
* @return {?}
*/
CdkTree.prototype._switchDataSource =
// TODO(tinayuangao): Work on keyboard traversal and actions, make sure it's working for RTL
// and nested trees.
/**
* Switch to the provided data source by resetting the data and unsubscribing from the current
* render change subscription if one exists. If the data source is null, interpret this by
* clearing the node outlet. Otherwise start listening for new data.
* @private
* @param {?} dataSource
* @return {?}
*/
function (dataSource) {
if (this._dataSource && typeof ((/** @type {?} */ (this._dataSource))).disconnect === 'function') {
((/** @type {?} */ (this.dataSource))).disconnect(this);
}
if (this._dataSubscription) {
this._dataSubscription.unsubscribe();
this._dataSubscription = null;
}
// Remove the all dataNodes if there is now no data source
if (!dataSource) {
this._nodeOutlet.viewContainer.clear();
}
this._dataSource = dataSource;
if (this._nodeDefs) {
this._observeRenderChanges();
}
};
/** Set up a subscription for the data provided by the data source. */
/**
* Set up a subscription for the data provided by the data source.
* @private
* @return {?}
*/
CdkTree.prototype._observeRenderChanges = /**
* Set up a subscription for the data provided by the data source.
* @private
* @return {?}
*/
function () {
var _this = this;
/** @type {?} */
var dataStream;
if (isDataSource(this._dataSource)) {
dataStream = this._dataSource.connect(this);
}
else if (this._dataSource instanceof Observable) {
dataStream = this._dataSource;
}
else if (Array.isArray(this._dataSource)) {
dataStream = of(this._dataSource);
}
if (dataStream) {
this._dataSubscription = dataStream.pipe(takeUntil(this._onDestroy))
.subscribe(function (data) { return _this.renderNodeChanges(data); });
}
else {
throw getTreeNoValidDataSourceError();
}
};
/** Check for changes made in the data and render each change (node added/removed/moved). */
/**
* Check for changes made in the data and render each change (node added/removed/moved).
* @param {?} data
* @param {?=} dataDiffer
* @param {?=} viewContainer
* @param {?=} parentData
* @return {?}
*/
CdkTree.prototype.renderNodeChanges = /**
* Check for changes made in the data and render each change (node added/removed/moved).
* @param {?} data
* @param {?=} dataDiffer
* @param {?=} viewContainer
* @param {?=} parentData
* @return {?}
*/
function (data, dataDiffer, viewContainer, parentData) {
var _this = this;
if (dataDiffer === void 0) { dataDiffer = this._dataDiffer; }
if (viewContainer === void 0) { viewContainer = this._nodeOutlet.viewContainer; }
/** @type {?} */
var changes = dataDiffer.diff(data);
if (!changes) {
return;
}
changes.forEachOperation(function (item, adjustedPreviousIndex, currentIndex) {
if (item.previousIndex == null) {
_this.insertNode(data[(/** @type {?} */ (currentIndex))], (/** @type {?} */ (currentIndex)), viewContainer, parentData);
}
else if (currentIndex == null) {
viewContainer.remove((/** @type {?} */ (adjustedPreviousIndex)));
_this._levels.delete(item.item);
}
else {
/** @type {?} */
var view = viewContainer.get((/** @type {?} */ (adjustedPreviousIndex)));
viewContainer.move((/** @type {?} */ (view)), currentIndex);
}
});
this._changeDetectorRef.detectChanges();
};
/**
* Finds the matching node definition that should be used for this node data. If there is only
* one node definition, it is returned. Otherwise, find the node definition that has a when
* predicate that returns true with the data. If none return true, return the default node
* definition.
*/
/**
* Finds the matching node definition that should be used for this node data. If there is only
* one node definition, it is returned. Otherwise, find the node definition that has a when
* predicate that returns true with the data. If none return true, return the default node
* definition.
* @param {?} data
* @param {?} i
* @return {?}
*/
CdkTree.prototype._getNodeDef = /**
* Finds the matching node definition that should be used for this node data. If there is only
* one node definition, it is returned. Otherwise, find the node definition that has a when
* predicate that returns true with the data. If none return true, return the default node
* definition.
* @param {?} data
* @param {?} i
* @return {?}
*/
function (data, i) {
if (this._nodeDefs.length === 1) {
return this._nodeDefs.first;
}
/** @type {?} */
var nodeDef = this._nodeDefs.find(function (def) { return def.when && def.when(i, data); }) || this._defaultNodeDef;
if (!nodeDef) {
throw getTreeMissingMatchingNodeDefError();
}
return nodeDef;
};
/**
* Create the embedded view for the data node template and place it in the correct index location
* within the data node view container.
*/
/**
* Create the embedded view for the data node template and place it in the correct index location
* within the data node view container.
* @param {?} nodeData
* @param {?} index
* @param {?=} viewContainer
* @param {?=} parentData
* @return {?}
*/
CdkTree.prototype.insertNode = /**
* Create the embedded view for the data node template and place it in the correct index location
* within the data node view container.
* @param {?} nodeData
* @param {?} index
* @param {?=} viewContainer
* @param {?=} parentData
* @return {?}
*/
function (nodeData, index, viewContainer, parentData) {
/** @type {?} */
var node = this._getNodeDef(nodeData, index);
// Node context that will be provided to created embedded view
/** @type {?} */
var context = new CdkTreeNodeOutletContext(nodeData);
// If the tree is flat tree, then use the `getLevel` function in flat tree control
// Otherwise, use the level of parent node.
if (this.treeControl.getLevel) {
context.level = this.treeControl.getLevel(nodeData);
}
else if (typeof parentData !== 'undefined' && this._levels.has(parentData)) {
context.level = (/** @type {?} */ (this._levels.get(parentData))) + 1;
}
else {
context.level = 0;
}
this._levels.set(nodeData, context.level);
// Use default tree nodeOutlet, or nested node's nodeOutlet
/** @type {?} */
var container = viewContainer ? viewContainer : this._nodeOutlet.viewContainer;
container.createEmbeddedView(node.template, context, index);
// Set the data to just created `CdkTreeNode`.
// The `CdkTreeNode` created from `createEmbeddedView` will be saved in static variable
// `mostRecentTreeNode`. We get it from static variable and pass the node data to it.
if (CdkTreeNode.mostRecentTreeNode) {
CdkTreeNode.mostRecentTreeNode.data = nodeData;
}
};
CdkTree.decorators = [
{ type: Component, args: [{selector: 'cdk-tree',
exportAs: 'cdkTree',
template: "<ng-container cdkTreeNodeOutlet></ng-container>",
host: {
'class': 'cdk-tree',
'role': 'tree',
},
encapsulation: ViewEncapsulation.None,
changeDetection: ChangeDetectionStrategy.OnPush
},] },
];
/** @nocollapse */
CdkTree.ctorParameters = function () { return [
{ type: IterableDiffers },
{ type: ChangeDetectorRef }
]; };
CdkTree.propDecorators = {
dataSource: [{ type: Input }],
treeControl: [{ type: Input }],
trackBy: [{ type: Input }],
_nodeOutlet: [{ type: ViewChild, args: [CdkTreeNodeOutlet,] }],
_nodeDefs: [{ type: ContentChildren, args: [CdkTreeNodeDef,] }]
};
return CdkTree;
}());
/**
* Tree node for CdkTree. It contains the data in the tree node.
* @template T
*/
var CdkTreeNode = /** @class */ (function () {
function CdkTreeNode(_elementRef, _tree) {
this._elementRef = _elementRef;
this._tree = _tree;
/**
* Subject that emits when the component has been destroyed.
*/
this._destroyed = new Subject();
/**
* The role of the node should be 'group' if it's an internal node,
* and 'treeitem' if it's a leaf node.
*/
this.role = 'treeitem';
CdkTreeNode.mostRecentTreeNode = (/** @type {?} */ (this));
}
Object.defineProperty(CdkTreeNode.prototype, "data", {
/** The tree node's data. */
get: /**
* The tree node's data.
* @return {?}
*/
function () { return this._data; },
set: /**
* @param {?} value
* @return {?}
*/
function (value) {
this._data = value;
this._setRoleFromData();
},
enumerable: true,
configurable: true
});
Object.defineProperty(CdkTreeNode.prototype, "isExpanded", {
get: /**
* @return {?}
*/
function () {
return this._tree.treeControl.isExpanded(this._data);
},
enumerable: true,
configurable: true
});
Object.defineProperty(CdkTreeNode.prototype, "level", {
get: /**
* @return {?}
*/
function () {
return this._tree.treeControl.getLevel ? this._tree.treeControl.getLevel(this._data) : 0;
},
enumerable: true,
configurable: true
});
/**
* @return {?}
*/
CdkTreeNode.prototype.ngOnDestroy = /**
* @return {?}
*/
function () {
// If this is the last tree node being destroyed,
// clear out the reference to avoid leaking memory.
if (CdkTreeNode.mostRecentTreeNode === this) {
CdkTreeNode.mostRecentTreeNode = null;
}
this._destroyed.next();
this._destroyed.complete();
};
/** Focuses the menu item. Implements for FocusableOption. */
/**
* Focuses the menu item. Implements for FocusableOption.
* @return {?}
*/
CdkTreeNode.prototype.focus = /**
* Focuses the menu item. Implements for FocusableOption.
* @return {?}
*/
function () {
this._elementRef.nativeElement.focus();
};
/**
* @protected
* @return {?}
*/
CdkTreeNode.prototype._setRoleFromData = /**
* @protected
* @return {?}
*/
function () {
var _this = this;
if (this._tree.treeControl.isExpandable) {
this.role = this._tree.treeControl.isExpandable(this._data) ? 'group' : 'treeitem';
}
else {
if (!this._tree.treeControl.getChildren) {
throw getTreeControlFunctionsMissingError();
}
/** @type {?} */
var childrenNodes = this._tree.treeControl.getChildren(this._data);
if (Array.isArray(childrenNodes)) {
this._setRoleFromChildren((/** @type {?} */ (childrenNodes)));
}
else if (childrenNodes instanceof Observable) {
childrenNodes.pipe(takeUntil(this._destroyed))
.subscribe(function (children) { return _this._setRoleFromChildren(children); });
}
}
};
/**
* @protected
* @param {?} children
* @return {?}
*/
CdkTreeNode.prototype._setRoleFromChildren = /**
* @protected
* @param {?} children
* @return {?}
*/
function (children) {
this.role = children && children.length ? 'group' : 'treeitem';
};
/**
* The most recently created `CdkTreeNode`. We save it in static variable so we can retrieve it
* in `CdkTree` and set the data to it.
*/
CdkTreeNode.mostRecentTreeNode = null;
CdkTreeNode.decorators = [
{ type: Directive, args: [{
selector: 'cdk-tree-node',
exportAs: 'cdkTreeNode',
host: {
'[attr.aria-expanded]': 'isExpanded',
'[attr.aria-level]': 'role === "treeitem" ? level : null',
'[attr.role]': 'role',
'class': 'cdk-tree-node',
},
},] },
];
/** @nocollapse */
CdkTreeNode.ctorParameters = function () { return [
{ type: ElementRef },
{ type: CdkTree }
]; };
CdkTreeNode.propDecorators = {
role: [{ type: Input }]
};
return CdkTreeNode;
}());
/**
* @fileoverview added by tsickle
* @suppress {checkTypes,extraRequire,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* Nested node is a child of `<cdk-tree>`. It works with nested tree.
* By using `cdk-nested-tree-node` component in tree node template, children of the parent node will
* be added in the `cdkTreeNodeOutlet` in tree node template.
* For example:
* ```html
* <cdk-nested-tree-node>
* {{node.name}}
* <ng-template cdkTreeNodeOutlet></ng-template>
* </cdk-nested-tree-node>
* ```
* The children of node will be automatically added to `cdkTreeNodeOutlet`, the result dom will be
* like this:
* ```html
* <cdk-nested-tree-node>
* {{node.name}}
* <cdk-nested-tree-node>{{child1.name}}</cdk-nested-tree-node>
* <cdk-nested-tree-node>{{child2.name}}</cdk-nested-tree-node>
* </cdk-nested-tree-node>
* ```
* @template T
*/
var CdkNestedTreeNode = /** @class */ (function (_super) {
__extends(CdkNestedTreeNode, _super);
function CdkNestedTreeNode(_elementRef, _tree, _differs) {
var _this = _super.call(this, _elementRef, _tree) || this;
_this._elementRef = _elementRef;
_this._tree = _tree;
_this._differs = _differs;
return _this;
}
/**
* @return {?}
*/
CdkNestedTreeNode.prototype.ngAfterContentInit = /**
* @return {?}
*/
function () {
var _this = this;
this._dataDiffer = this._differs.find([]).create(this._tree.trackBy);
if (!this._tree.treeControl.getChildren) {
throw getTreeControlFunctionsMissingError();
}
/** @type {?} */
var childrenNodes = this._tree.treeControl.getChildren(this.data);
if (Array.isArray(childrenNodes)) {
this.updateChildrenNodes((/** @type {?} */ (childrenNodes)));
}
else if (childrenNodes instanceof Observable) {
childrenNodes.pipe(takeUntil(this._destroyed))
.subscribe(function (result) { return _this.updateChildrenNodes(result); });
}
this.nodeOutlet.changes.pipe(takeUntil(this._destroyed))
.subscribe(function () { return _this.updateChildrenNodes(); });
};
/**
* @return {?}
*/
CdkNestedTreeNode.prototype.ngOnDestroy = /**
* @return {?}
*/
function () {
this._clear();
_super.prototype.ngOnDestroy.call(this);
};
/** Add children dataNodes to the NodeOutlet */
/**
* Add children dataNodes to the NodeOutlet
* @protected
* @param {?=} children
* @return {?}
*/
CdkNestedTreeNode.prototype.updateChildrenNodes = /**
* Add children dataNodes to the NodeOutlet
* @protected
* @param {?=} children
* @return {?}
*/
function (children) {
if (children) {
this._children = children;
}
if (this.nodeOutlet.length && this._children) {
/** @type {?} */
var viewContainer = this.nodeOutlet.first.viewContainer;
this._tree.renderNodeChanges(this._children, this._dataDiffer, viewContainer, this._data);
}
else {
// Reset the data differ if there's no children nodes displayed
this._dataDiffer.diff([]);
}
};
/** Clear the children dataNodes. */
/**
* Clear the children dataNodes.
* @protected
* @return {?}
*/
CdkNestedTreeNode.prototype._clear = /**
* Clear the children dataNodes.
* @protected
* @return {?}
*/
function () {
if (this.nodeOutlet && this.nodeOutlet.first) {
this.nodeOutlet.first.viewContainer.clear();
this._dataDiffer.diff([]);
}
};
CdkNestedTreeNode.decorators = [
{ type: Directive, args: [{
selector: 'cdk-nested-tree-node',
exportAs: 'cdkNestedTreeNode',
host: {
'[attr.aria-expanded]': 'isExpanded',
'[attr.role]': 'role',
'class': 'cdk-tree-node cdk-nested-tree-node',
},
providers: [{ provide: CdkTreeNode, useExisting: CdkNestedTreeNode }]
},] },
];
/** @nocollapse */
CdkNestedTreeNode.ctorParameters = function () { return [
{ type: ElementRef },
{ type: CdkTree },
{ type: IterableDiffers }
]; };
CdkNestedTreeNode.propDecorators = {
nodeOutlet: [{ type: ContentChildren, args: [CdkTreeNodeOutlet,] }]
};
return CdkNestedTreeNode;
}(CdkTreeNode));
/**
* @fileoverview added by tsickle
* @suppress {checkTypes,extraRequire,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* Regex used to split a string on its CSS units.
* @type {?}
*/
var cssUnitPattern = /([A-Za-z%]+)$/;
/**
* Indent for the children tree dataNodes.
* This directive will add left-padding to the node to show hierarchy.
* @template T
*/
var CdkTreeNodePadding = /** @class */ (function () {
function CdkTreeNodePadding(_treeNode, _tree, _renderer, _element, _dir) {
var _this = this;
this._treeNode = _treeNode;
this._tree = _tree;
this._renderer = _renderer;
this._element = _element;
this._dir = _dir;
/**
* Subject that emits when the component has been destroyed.
*/
this._destroyed = new Subject();
/**
* CSS units used for the indentation value.
*/
this.indentUnits = 'px';
this._indent = 40;
this._setPadding();
if (_dir) {
_dir.change.pipe(takeUntil(this._destroyed)).subscribe(function () { return _this._setPadding(); });
}
}
Object.defineProperty(CdkTreeNodePadding.prototype, "level", {
/** The level of depth of the tree node. The padding will be `level * indent` pixels. */
get: /**
* The level of depth of the tree node. The padding will be `level * indent` pixels.
* @return {?}
*/
function () { return this._level; },
set: /**
* @param {?} value
* @return {?}
*/
function (value) {
this._level = coerceNumberProperty(value);
this._setPadding();
},
enumerable: true,
configurable: true
});
Object.defineProperty(CdkTreeNodePadding.prototype, "indent", {
/**
* The indent for each level. Can be a number or a CSS string.
* Default number 40px from material design menu sub-menu spec.
*/
get: /**
* The indent for each level. Can be a number or a CSS string.
* Default number 40px from material design menu sub-menu spec.
* @return {?}
*/
function () { return this._indent; },
set: /**
* @param {?} indent
* @return {?}
*/
function (indent) {
/** @type {?} */
var value = indent;
/** @type {?} */
var units = 'px';
if (typeof indent === 'string') {
/** @type {?} */
var parts = indent.split(cssUnitPattern);
value = parts[0];
units = parts[1] || units;
}
this.indentUnits = units;
this._indent = coerceNumberProperty(value);
this._setPadding();
},
enumerable: true,
configurable: true
});
/**
* @return {?}
*/
CdkTreeNodePadding.prototype.ngOnDestroy = /**
* @return {?}
*/
function () {
this._destroyed.next();
this._destroyed.complete();
};
/** The padding indent value for the tree node. Returns a string with px numbers if not null. */
/**
* The padding indent value for the tree node. Returns a string with px numbers if not null.
* @return {?}
*/
CdkTreeNodePadding.prototype._paddingIndent = /**
* The padding indent value for the tree node. Returns a string with px numbers if not null.
* @return {?}
*/
function () {
/** @type {?} */
var nodeLevel = (this._treeNode.data && this._tree.treeControl.getLevel)
? this._tree.treeControl.getLevel(this._treeNode.data)
: null;
/** @type {?} */
var level = this._level || nodeLevel;
return level ? "" + level * this._indent + this.indentUnits : null;
};
/**
* @return {?}
*/
CdkTreeNodePadding.prototype._setPadding = /**
* @return {?}
*/
function () {
/** @type {?} */
var element = this._element.nativeElement;
/** @type {?} */
var padding = this._paddingIndent();
/** @type {?} */
var paddingProp = this._dir && this._dir.value === 'rtl' ? 'paddingRight' : 'paddingLeft';
/** @type {?} */
var resetProp = paddingProp === 'paddingLeft' ? 'paddingRight' : 'paddingLeft';
this._renderer.setStyle(element, paddingProp, padding);
this._renderer.setStyle(element, resetProp, '');
};
CdkTreeNodePadding.decorators = [
{ type: Directive, args: [{
selector: '[cdkTreeNodePadding]',
},] },
];
/** @nocollapse */
CdkTreeNodePadding.ctorParameters = function () { return [
{ type: CdkTreeNode },
{ type: CdkTree },
{ type: Renderer2 },
{ type: ElementRef },
{ type: Directionality, decorators: [{ type: Optional }] }
]; };
CdkTreeNodePadding.propDecorators = {
level: [{ type: Input, args: ['cdkTreeNodePadding',] }],
indent: [{ type: Input, args: ['cdkTreeNodePaddingIndent',] }]
};
return CdkTreeNodePadding;
}());
/**
* @fileoverview added by tsickle
* @suppress {checkTypes,extraRequire,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* Node toggle to expand/collapse the node.
* @template T
*/
var CdkTreeNodeToggle = /** @class */ (function () {
function CdkTreeNodeToggle(_tree, _treeNode) {
this._tree = _tree;
this._treeNode = _treeNode;
this._recursive = false;
}
Object.defineProperty(CdkTreeNodeToggle.prototype, "recursive", {
/** Whether expand/collapse the node recursively. */
get: /**
* Whether expand/collapse the node recursively.
* @return {?}
*/
function () { return this._recursive; },
set: /**
* @param {?} value
* @return {?}
*/
function (value) { this._recursive = coerceBooleanProperty(value); },
enumerable: true,
configurable: true
});
/**
* @param {?} event
* @return {?}
*/
CdkTreeNodeToggle.prototype._toggle = /**
* @param {?} event
* @return {?}
*/
function (event) {
this.recursive
? this._tree.treeControl.toggleDescendants(this._treeNode.data)
: this._tree.treeControl.toggle(this._treeNode.data);
event.stopPropagation();
};
CdkTreeNodeToggle.decorators = [
{ type: Directive, args: [{
selector: '[cdkTreeNodeToggle]',
host: {
'(click)': '_toggle($event)',
}
},] },
];
/** @nocollapse */
CdkTreeNodeToggle.ctorParameters = function () { return [
{ type: CdkTree },
{ type: CdkTreeNode }
]; };
CdkTreeNodeToggle.propDecorators = {
recursive: [{ type: Input, args: ['cdkTreeNodeToggleRecursive',] }]
};
return CdkTreeNodeToggle;
}());
/**
* @fileoverview added by tsickle
* @suppress {checkTypes,extraRequire,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/** @type {?} */
var EXPORTED_DECLARATIONS = [
CdkNestedTreeNode,
CdkTreeNodeDef,
CdkTreeNodePadding,
CdkTreeNodeToggle,
CdkTree,
CdkTreeNode,
CdkTreeNodeOutlet,
];
var CdkTreeModule = /** @class */ (function () {
function CdkTreeModule() {
}
CdkTreeModule.decorators = [
{ type: NgModule, args: [{
imports: [CommonModule],
exports: EXPORTED_DECLARATIONS,
declarations: EXPORTED_DECLARATIONS,
providers: [FocusMonitor, CdkTreeNodeDef]
},] },
];
return CdkTreeModule;
}());
/**
* @fileoverview added by tsickle
* @suppress {checkTypes,extraRequire,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* @fileoverview added by tsickle
* @suppress {checkTypes,extraRequire,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
export { BaseTreeControl, FlatTreeControl, NestedTreeControl, CdkNestedTreeNode, CdkTreeNodeOutletContext, CdkTreeNodeDef, CdkTreeNodePadding, CdkTreeNodeOutlet, CdkTree, CdkTreeNode, getTreeNoValidDataSourceError, getTreeMultipleDefaultNodeDefsError, getTreeMissingMatchingNodeDefError, getTreeControlMissingError, getTreeControlFunctionsMissingError, CdkTreeModule, CdkTreeNodeToggle };
//# sourceMappingURL=tree.es5.js.map
|
export const GET_LATEST_LIST = 'GET_LATEST_LIST';
export const GET_ERR = 'GET_ERR';
|
/*
Copyright (c) 2012, Yahoo! Inc. All rights reserved.
Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms.
*/
var nopt = require('nopt'),
Report = require('../report'),
Reporter = require('../reporter'),
path = require('path'),
fs = require('fs'),
Collector = require('../collector'),
helpFormatter = require('../util/help-formatter'),
formatOption = helpFormatter.formatOption,
formatPara = helpFormatter.formatPara,
filesFor = require('../util/file-matcher').filesFor,
util = require('util'),
Command = require('./index'),
configuration = require('../config');
function ReportCommand() {
Command.call(this);
}
ReportCommand.TYPE = 'report';
util.inherits(ReportCommand, Command);
function printDeprecationMessage(pat, fmt) {
console.error('**********************************************************************');
console.error('DEPRECATION WARNING! You are probably using the old format of the report command');
console.error('This will stop working soon, see `istanbul help report` for the new command format');
console.error('Assuming you meant: istanbul report --include=' + pat + ' ' + fmt);
console.error('**********************************************************************');
}
Command.mix(ReportCommand, {
synopsis: function () {
return "writes reports for coverage JSON objects produced in a previous run";
},
usage: function () {
console.error('\nUsage: ' + this.toolName() + ' ' + this.type() + ' <options> [ <format> ... ]\n\nOptions are:\n\n' +
[
formatOption('--config <path-to-config>', 'the configuration file to use, defaults to .istanbul.yml'),
formatOption('--root <input-directory>', 'The input root directory for finding coverage files'),
formatOption('--dir <report-directory>', 'The output directory where files will be written. This defaults to ./coverage/'),
formatOption('--include <glob>', 'The fileset pattern to select one or more coverage files, defaults to **/coverage*.json'),
formatOption('--verbose, -v', 'verbose mode')
].join('\n\n'));
console.error('\n');
console.error('<format> is one of ');
Report.getReportList().forEach(function (name) {
console.error(formatOption(name, Report.create(name).synopsis()));
});
console.error("");
console.error(formatPara([
'Default format is lcov unless otherwise specified in the config file.',
'In addition you can tweak the file names for various reports using the config file.',
'Type `istanbul help config` to see what can be tweaked.'
].join(' ')));
console.error('\n');
},
run: function (args, callback) {
var template = {
config: path,
root: path,
dir: path,
include: String,
verbose: Boolean
},
opts = nopt(template, { v : '--verbose' }, args, 0),
includePattern = opts.include || '**/coverage*.json',
root,
collector = new Collector(),
config = configuration.loadFile(opts.config, {
verbose: opts.verbose,
reporting: {
dir: opts.dir
}
}),
formats = opts.argv.remain,
reporter = new Reporter(config);
// Start: backward compatible processing
if (formats.length === 2 &&
Report.getReportList().indexOf(formats[1]) < 0) {
includePattern = formats[1];
formats = [ formats[0] ];
printDeprecationMessage(includePattern, formats[0]);
}
// End: backward compatible processing
if (formats.length === 0) {
formats = config.reporting.reports();
}
if (formats.length === 0) {
formats = [ 'lcov' ];
}
reporter.addAll(formats);
root = opts.root || process.cwd();
filesFor({
root: root,
includes: [ includePattern ]
}, function (err, files) {
if (err) { throw err; }
files.forEach(function (file) {
var coverageObject = JSON.parse(fs.readFileSync(file, 'utf8'));
collector.add(coverageObject);
});
reporter.write(collector, false, function (err) {
console.log('Done');
return callback(err);
});
});
}
});
module.exports = ReportCommand;
|
import { expect } from 'chai';
import Targeting from 'src/targeting';
import { config } from 'src/config';
import { getAdUnits } from 'test/fixtures/fixtures';
import CONSTANTS from 'src/constants.json';
const bid1 = {
'bidderCode': 'rubicon',
'width': '300',
'height': '250',
'statusMessage': 'Bid available',
'adId': '148018fe5e',
'cpm': 0.537234,
'ad': 'markup',
'ad_id': '3163950',
'sizeId': '15',
'requestTimestamp': 1454535718610,
'responseTimestamp': 1454535724863,
'timeToRespond': 123,
'pbLg': '0.50',
'pbMg': '0.50',
'pbHg': '0.53',
'adUnitCode': '/123456/header-bid-tag-0',
'bidder': 'rubicon',
'size': '300x250',
'adserverTargeting': {
'hb_bidder': 'rubicon',
'hb_adid': '148018fe5e',
'hb_pb': '0.53',
'foobar': '300x250'
}
};
const bid2 = {
'bidderCode': 'rubicon',
'width': '300',
'height': '250',
'statusMessage': 'Bid available',
'adId': '5454545',
'cpm': 0.25,
'ad': 'markup',
'ad_id': '3163950',
'sizeId': '15',
'requestTimestamp': 1454535718610,
'responseTimestamp': 1454535724863,
'timeToRespond': 123,
'pbLg': '0.25',
'pbMg': '0.25',
'pbHg': '0.25',
'adUnitCode': '/123456/header-bid-tag-0',
'bidder': 'rubicon',
'size': '300x250',
'adserverTargeting': {
'hb_bidder': 'rubicon',
'hb_adid': '5454545',
'hb_pb': '0.25',
'foobar': '300x250'
}
};
describe('targeting tests', () => {
describe('getAllTargeting', () => {
beforeEach(() => {
$$PREBID_GLOBAL$$._sendAllBids = false;
$$PREBID_GLOBAL$$._bidsReceived = [];
$$PREBID_GLOBAL$$._adUnitCodes = [];
$$PREBID_GLOBAL$$.adUnits = [];
});
it('selects the top bid when _sendAllBids true', () => {
$$PREBID_GLOBAL$$.adUnits = [{
code: '/123456/header-bid-tag-0',
sizes: [300, 250],
bids: [
{
'bidder': 'rubicon',
'params': {
'accountId': 10617,
'siteId': 23635,
'zoneId': 453908
}
}
]
}];
config.setConfig({ enableSendAllBids: true });
$$PREBID_GLOBAL$$._bidsReceived.push(bid1, bid2);
$$PREBID_GLOBAL$$._adUnitCodes = ['/123456/header-bid-tag-0'];
let targeting = Targeting.getAllTargeting(['/123456/header-bid-tag-0']);
let flattened = [];
targeting.filter(obj => obj['/123456/header-bid-tag-0'] !== undefined).forEach(item => flattened = flattened.concat(item['/123456/header-bid-tag-0']));
let sendAllBidCpm = flattened.filter(obj => obj.hb_pb_rubicon !== undefined);
let winningBidCpm = flattened.filter(obj => obj.hb_pb !== undefined);
// we shouldn't get more than 1 key for hb_pb_${bidder}
expect(sendAllBidCpm.length).to.equal(1);
// expect the winning CPM to be equal to the sendAllBidCPM
expect(sendAllBidCpm[0]['hb_pb_rubicon']).to.deep.equal(winningBidCpm[0]['hb_pb']);
});
}); // end getAllTargeting tests
});
|
export class Carousel {
constructor(anterior, proximo, listaProdutos, navegacao) {
this.anterior = document.querySelector(anterior)
this.proximo = document.querySelector(proximo)
this.listaProdutos = document.querySelector(listaProdutos)
this.navegacao = document.querySelector(navegacao)
this.slides = this.getListaSlides()
this.indicadores = this.getListaIndicadores()
this.tamanhoSlide = this.getTamanhoSlide()
this.indiceDoSlideAtual = 0
this.proximo.addEventListener('click', this.proximoSlide.bind(this))
this.anterior.addEventListener('click', this.slideAnterior.bind(this))
this.navegacao.addEventListener('click', this.pularParaSlide.bind(this))
this.preparaSlides()
}
getListaSlides() {
return Array.from(this.listaProdutos.children)
}
getListaIndicadores() {
return Array.from(this.navegacao.children)
}
getTamanhoSlide() {
return this.slides[0].getBoundingClientRect().width
}
getSlideAtual() {
return this.slides[this.indiceDoSlideAtual]
}
getIndiceAtual() {
return this.indicadores[this.indiceDoSlideAtual]
}
proximoSlide() {
let proximaPosicao = this.indiceDoSlideAtual + 1
if(proximaPosicao > this.slides.length - 1) {
proximaPosicao = 0
}
this.vaParaSlide(proximaPosicao)
}
slideAnterior() {
let posicaoAnterior = this.indiceDoSlideAtual - 1
if(posicaoAnterior < 0) {
posicaoAnterior = this.slides.length - 1
}
this.vaParaSlide(posicaoAnterior)
}
vaParaSlide(posicao) {
const indicadorAtual = this.getIndiceAtual()
this.indiceDoSlideAtual = posicao
const indicadorSelecionado = this.getIndiceAtual()
this.scrollParaSlide(this.getSlideAtual())
this.atualizaIndicadores(indicadorAtual, indicadorSelecionado)
}
scrollParaSlide(slideSelecionado) {
this.listaProdutos.style.transform = 'translateX(-' + slideSelecionado.style.left + ')'
}
atualizaIndicadores(indicadorAtual, indicadorSelecionado) {
indicadorAtual.classList.remove('carousel__indicador--ativo')
indicadorSelecionado.classList.add('carousel__indicador--ativo')
}
pularParaSlide(evento) {
if(evento.target === evento.currentTarget) return
const indicadorSelecionado = evento.target.getAttribute('data-indicador')
this.vaParaSlide(parseInt(indicadorSelecionado))
}
preparaSlides() {
this.slides.forEach((slide, i) => {
slide.style.left = this.tamanhoSlide * i + 'px'
})
}
}
|
import styled from "@emotion/styled"
const Container = styled.div`
margin: 0 auto;
@media (min-width: 1200px) {
max-width: 1140px;
}
@media (min-width: 992px) and (max-width: 1200px) {
max-width: 960px;
}
@media (min-width: 768px) and (max-width: 992px) {
max-width: 720px;
}
@media (min-width: 576px) and (max-width: 768px) {
max-width: 540px;
}
@media (max-width: 576px) {
max-width: 96%;
}
`
export default Container
|
export default class FlashMessage {
constructor(title= '', type=null, content='') {
this.title = title;
this.type = this.isType(type) ? type : FlashMessage.TYPES.INFO;
this.content = content;
}
isType(type) {
let vals = Object.keys(FlashMessage.TYPES).map(key => FlashMessage.TYPES[key]);
return vals.indexOf(type) > -1;
}
}
Object.defineProperty(FlashMessage, 'TYPES', {
'enumerable': false,
'writable': false,
'configurable': false,
'value': Object.freeze({
'INFO': 'info',
'SUCCESS': 'success',
'WARNING': 'warning',
'ERROR': 'error',
}),
});
|
'use strict';
const fs = require('fs');
const path = require('path');
const ROOMFAQ_FILE = path.resolve(__dirname, '../config/chat-plugins/faqs.json');
let roomFaqs = {};
try {
roomFaqs = require(ROOMFAQ_FILE);
} catch (e) {
if (e.code !== 'MODULE_NOT_FOUND' && e.code !== 'ENOENT') throw e;
}
if (!roomFaqs || typeof roomFaqs !== 'object') roomFaqs = {};
function saveRoomFaqs() {
fs.writeFile(ROOMFAQ_FILE, JSON.stringify(roomFaqs), () => {});
}
// Aliases are implemented as a "regular" FAQ entry starting with a >. EX: {a: "text", b: ">a"}
// This is done to allow easy checking whether a key is associated with a value or alias as well as preserve backwards compatibility.
function getAlias(roomid, key) {
if (!roomFaqs[roomid]) return false;
let value = roomFaqs[roomid][key];
if (value && value[0] === '>') return value.substr(1);
return false;
}
exports.commands = {
addfaq: function (target, room, user) {
if (!this.canTalk()) return this.errorReply("You cannot do this while unable to talk.");
if (!this.can('declare', null, room)) return false;
if (!room.chatRoomData) return this.errorReply("This command is unavailable in temporary rooms.");
let [topic, ...text] = target.split(',');
topic = toId(topic);
if (!(topic && text.length)) return this.parse('/help roomfaq');
text = text.join(',').trim();
if (topic.length > 25) return this.errorReply("FAQ topics should not exceed 25 characters.");
if (text.length > 500) return this.errorReply("FAQ entries should not exceed 500 characters.");
text = text.replace(/^>/, '>');
if (!roomFaqs[room.id]) roomFaqs[room.id] = {};
roomFaqs[room.id][topic] = text;
saveRoomFaqs();
this.sendReplyBox(Chat.formatText(text, true));
this.privateModCommand(`(${user.name} added a FAQ for '${topic}')`);
},
removefaq: function (target, room, user) {
if (!this.canTalk()) return this.errorReply("You cannot do this while unable to talk.");
if (!this.can('declare', null, room)) return false;
if (!room.chatRoomData) return this.errorReply("This command is unavailable in temporary rooms.");
let topic = toId(target);
if (!topic) return this.parse('/help roomfaq');
if (!(roomFaqs[room.id] && roomFaqs[room.id][topic])) return this.errorReply("Invalid topic.");
delete roomFaqs[room.id][topic];
Object.keys(roomFaqs[room.id]).filter(val => getAlias(room.id, val) === topic).map(val => delete roomFaqs[room.id][val]);
if (!Object.keys(roomFaqs[room.id]).length) delete roomFaqs[room.id];
saveRoomFaqs();
this.privateModCommand(`(${user.name} removed the FAQ for '${topic}')`);
},
addalias: function (target, room, user) {
if (!this.canTalk()) return this.errorReply("You cannot do this while unable to talk.");
if (!this.can('declare', null, room)) return false;
if (!room.chatRoomData) return this.errorReply("This command is unavailable in temporary rooms.");
let [alias, topic] = target.split(',').map(val => toId(val));
if (!(alias && topic)) return this.parse('/help roomfaq');
if (alias.length > 25) return this.errorReply("FAQ topics should not exceed 25 characters.");
if (!(roomFaqs[room.id] && topic in roomFaqs[room.id])) return this.errorReply(`The topic ${topic} was not found in this room's faq list.`);
if (getAlias(room.id, topic)) return this.errorReply(`You cannot make an alias of an alias. Use /addalias ${alias}, ${getAlias(room.id, topic)} instead.`);
roomFaqs[room.id][alias] = `>${topic}`;
saveRoomFaqs();
this.privateModCommand(`(${user.name} added an alias for '${topic}': ${alias})`);
},
rfaq: 'roomfaq',
roomfaq: function (target, room, user) {
if (!roomFaqs[room.id]) return this.errorReply("This room has no FAQ topics.");
let topic = toId(target);
if (topic === 'constructor') return false;
if (!topic) return this.sendReplyBox(`List of topics in this room: ${Object.keys(roomFaqs[room.id]).filter(val => !getAlias(room.id, val)).sort((a, b) => a.localeCompare(b)).join(', ')}`);
if (!roomFaqs[room.id][topic]) return this.errorReply("Invalid topic.");
topic = getAlias(room.id, topic) || topic;
if (!this.runBroadcast()) return;
this.sendReplyBox(Chat.formatText(roomFaqs[room.id][topic], true));
if (!this.broadcasting && user.can('declare', null, room)) {
let extra = `<code>/addfaq ${topic}, ${Chat.escapeHTML(roomFaqs[room.id][topic])}</code>`;
let aliases = Object.keys(roomFaqs[room.id]).filter(val => getAlias(room.id, val) === topic);
if (aliases.length) {
extra += `<br/><br/>Aliases: ${Object.keys(roomFaqs[room.id]).filter(val => getAlias(room.id, val) === topic).join(', ')}`;
}
this.sendReplyBox(extra);
}
},
roomfaqhelp: [
"/roomfaq - Shows the list of all available FAQ topics",
"/roomfaq <topic> - Shows the FAQ for <topic>.",
"/addfaq <topic>, <text> - Adds an entry for <topic> in this room or updates it. Requires: # & ~",
"/addalias <alias>, <topic> - Adds <alias> as an alias for <topic>, displaying it when users use /roomfaq <alias>. Requires: # & ~",
"/removefaq <topic> - Removes the entry for <topic> in this room. If used on an alias, removes the alias. Requires: # & ~",
],
};
|
import React from 'react'
import styled from 'styled-components'
import Page from 'comps/Page/Page'
import { Redraw } from '@commonsswarm/ui'
import Container from '../components/Page/DemoContainer'
const redrawDemo = interval => {
return class extends React.Component {
render() {
return (
<Redraw interval={interval}>
{() => {
const color = Math.floor(Math.random() * 0xffff).toString(16)
if (!this.count) this.count = 0
return (
<span
style={{
position: 'relative',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
width: '200px',
height: '100px',
marginRight: '10px',
background: `#${color}dd22`,
fontSize: '13px',
}}
>
<span>redraw every: {interval}ms</span>
<span
style={{
position: 'absolute',
top: '10px',
right: '10px',
fontSize: '11px',
}}
>
render count: {++this.count}
</span>
</span>
)
}}
</Redraw>
)
}
}
}
const Demo1 = redrawDemo(500)
const Demo2 = redrawDemo(1000)
const Demo3 = redrawDemo(2000)
const PageTable = ({ title }) => (
<Page title={title} readme={''}>
<Page.Demo opaque>
<Container>
<Demo1 />
<Demo2 />
<Demo3 />
</Container>
</Page.Demo>
</Page>
)
export default PageTable
|
/*
* @package summernoteDrafts.js
* @version 1.0
* @author Jessica González <suki@missallsunday.com>
* @copyright Copyright (c) 2017, Jessica González
* @license https://opensource.org/licenses/MIT MIT
*/
(function() {
(function(factory) {
if (typeof define === 'function' && define.amd) {
define(['jquery'], factory);
} else if (typeof module === 'object' && module.exports) {
module.exports = factory(require('jquery'));
} else {
factory(window.jQuery);
}
})(function($) {
$.extend($.summernote.options, {
sDrafts: {
storePrefix: 'sDrafts',
dateFormat: null,
saveIcon: null,
loadIcon: null
}
});
$.extend($.summernote.lang['en-US'], {
sDrafts: {
save: 'Lưu nháp',
load: 'Tải nháp',
select: 'Chọn bản nháp đã lưu',
provideName: 'Provide a name for this draft',
saved: 'Nháp đã được lưu',
loaded: 'Đã tải dữ liệu nháp',
deleteAll: 'Xóa tất cả',
noDraft: 'The selected draft couldn\'t be loaded, try again or select another one',
nosavedDrafts: 'There aren\'t any drafts saved',
deleteDraft: 'xóa',
youSure: 'Bạn muốn xóa nháp này?'
}
});
$.extend($.summernote.plugins, {
'sDraftsSave': function(context) {
var $editor, lang, options, ui;
ui = $.summernote.ui;
options = context.options;
lang = options.langInfo.sDrafts;
$editor = context.layoutInfo.editor;
context.memo('button.sDraftsSave', function() {
var button;
button = ui.button({
contents: options.sDrafts.saveIcon ? options.sDrafts.saveIcon : lang.save,
tooltip: lang.save,
click: function(e) {
e.preventDefault();
context.invoke('sDraftsSave.show');
return false;
}
});
return button.render();
});
this.initialize = (function(_this) {
return function() {
var $container, body, footer;
$container = options.dialogsInBody ? $(document.body) : $editor;
body = "<div class='form-group'><label>" + lang.provideName + "</label><input class='note-draftName form-control' type='text' /></div>";
footer = "<button href='#' class='btn btn-primary note-link-btn'>" + lang.save + "</button>";
_this.$dialog = ui.dialog({
className: 'link-dialog',
title: lang.save,
fade: options.dialogsFade,
body: body,
footer: footer
}).render().appendTo($container);
};
})(this);
this.destroy = (function(_this) {
return function() {
ui.hideDialog(_this.$dialog);
_this.$dialog.remove();
};
})(this);
this.show = (function(_this) {
return function() {
var $saveBtn;
ui.showDialog(_this.$dialog);
return $saveBtn = _this.$dialog.find('.note-link-btn').click(function(e) {
var draftName;
e.preventDefault;
draftName = _this.$dialog.find('.note-draftName').val();
_this.saveDraft(draftName);
return false;
});
};
})(this);
this.saveDraft = (function(_this) {
return function(name) {
var body, isoDate, keyName;
isoDate = new Date().toISOString();
if (name == null) {
name = isoDate;
}
keyName = options.sDrafts.storePrefix + '-' + name;
body = context.code();
store.set(keyName, {
name: name,
sDate: isoDate,
body: body
});
alert(lang.saved);
_this.destroy();
};
})(this);
}
});
return $.extend($.summernote.plugins, {
'sDraftsLoad': function(context) {
var $editor, draft, drafts, fn, htmlList, key, lang, options, ui;
ui = $.summernote.ui;
options = context.options;
lang = options.langInfo.sDrafts;
$editor = context.layoutInfo.editor;
drafts = [];
store.each(function(key, value) {
if (typeof key === 'string' && key.indexOf(options.sDrafts.storePrefix) >= 0) {
return drafts[key] = value;
}
});
htmlList = '';
fn = function() {
var fDate;
fDate = options.sDrafts.dateFormat && typeof options.sDrafts.dateFormat === 'function' ? options.sDrafts.dateFormat(draft.sDate) : draft.sDate;
return htmlList += "<li class='list-group-item'><a href='#' class='note-draft' data-draft='" + key + "'>" + draft.name + " - <small>" + fDate + "</small></a><a href='javascript:;' class='label label-danger pull-right delete-draft' data-draft='" + key + "'>" + lang.deleteDraft + "</a></li>";
};
for (key in drafts) {
draft = drafts[key];
fn();
}
context.memo('button.sDraftsLoad', function() {
var button;
button = ui.button({
contents: options.sDrafts.loadIcon ? options.sDrafts.loadIcon : lang.load,
tooltip: lang.load,
click: function(e) {
e.preventDefault();
context.invoke('sDraftsLoad.show');
return false;
}
});
return button.render();
});
this.initialize = (function(_this) {
return function() {
var $container, body, footer;
$container = options.dialogsInBody ? $(document.body) : $editor;
body = htmlList.length ? "<h4>" + lang.select + "</h4><ul class='list-group'>" + htmlList + "</ul>" : "<h4>" + lang.nosavedDrafts + "</h4>";
footer = htmlList.length ? "<button href='#' class='btn btn-primary deleteAll'>" + lang.deleteAll + "</button>" : "";
_this.$dialog = ui.dialog({
className: 'link-dialog',
title: lang.load,
fade: options.dialogsFade,
body: body,
footer: footer
}).render().appendTo($container);
};
})(this);
this.destroy = (function(_this) {
return function() {
ui.hideDialog(_this.$dialog);
_this.$dialog.remove();
};
})(this);
this.show = (function(_this) {
return function() {
var $deleteAllDrafts, $deleteDraft, $selectedDraft, self;
ui.showDialog(_this.$dialog);
self = _this;
$selectedDraft = _this.$dialog.find('.note-draft').click(function(e) {
var data, div;
e.preventDefault;
div = document.createElement('div');
key = $(this).data('draft');
data = drafts[key];
if (data) {
div.innerHTML = data.body;
context.invoke('editor.insertNode', div);
alert(lang.loaded);
} else {
alert(lang.noDraft);
}
self.destroy();
return false;
});
$deleteDraft = _this.$dialog.find('a.delete-draft').click(function(e) {
var data;
if (confirm(lang.youSure)) {
key = $(this).data('draft');
data = drafts[key];
if (data) {
store.remove(key);
self = $(this);
return self.parent().hide('slow', function() {
$(this).remove();
});
} else {
return alert(lang.noDraft);
}
}
});
$deleteAllDrafts = _this.$dialog.find('button.deleteAll').click(function(e) {
var fn1, selfButton, uiDialog;
selfButton = $(this);
if (confirm(lang.youSure)) {
fn1 = function() {
return store.remove(key);
};
for (key in drafts) {
draft = drafts[key];
fn1();
}
return uiDialog = self.$dialog.find('ul.list-group').hide('slow', function() {
$(this).replaceWith("<h4>" + lang.nosavedDrafts + "</h4>");
selfButton.hide('slow');
});
}
});
};
})(this);
}
});
});
}).call(this);
|
require('../../helper');
var app = require(global.settings.app_root + '/app/controllers/app')();
var assert = require('../../support/assert');
var querystring = require('querystring');
var libxmljs = require('libxmljs');
var http = require('http');
var server_utils = require('../../support/server_utils');
// allow lots of emitters to be set to silence warning
app.setMaxListeners(0);
describe('export.kml', function() {
// Check if an attribute is in the KML output
//
// NOTE: "name" and "description" attributes are threated specially
// in that they are matched in case-insensitive way
//
var hasAttribute = function(kml, att) {
// Strip namespace:
//https://github.com/polotek/libxmljs/issues/212
kml = kml.replace(/ xmlns=[^>]*>/, '>');
var doc = libxmljs.parseXmlString(kml);
//console.log("doc: " + doc);
var xpath;
xpath = "//SimpleField[@name='" + att + "']";
if ( doc.get(xpath) ) {
return true;
}
xpath = "//Placemark/" + att;
if ( doc.get(xpath) ) {
return true;
}
var lcatt = att.toLowerCase();
if ( lcatt === 'name' || lcatt === 'description' ) {
xpath = "//Placemark/" + lcatt;
if ( doc.get(xpath) ) {
return true;
}
}
//if ( lowerkml.indexOf('simplefield name="'+ loweratt + '"') != -1 ) return true;
//if ( lowerkml.indexOf('<'+loweratt+'>') != -1 ) return true;
return false;
};
// Return the first coordinate array found in KML
var extractCoordinates = function(kml) {
// Strip namespace:
//https://github.com/polotek/libxmljs/issues/212
kml = kml.replace(/ xmlns=[^>]*>/, '>');
var doc = libxmljs.parseXmlString(kml);
//console.log("doc: " + doc);
if ( ! doc ) {
return;
}
var coo = doc.get("//coordinates");
//console.log("coo: " + coo);
if ( ! coo ) {
return;
}
coo = coo.text();
//console.log("coo: " + coo);
if ( ! coo ) {
return;
}
coo = coo.split(' ');
//console.log("coo: " + coo);
for (var i=0; i<coo.length; ++i) {
coo[i] = coo[i].split(',');
}
return coo;
};
// Return the first folder name in KML
var extractFolderName = function(kml) {
// Strip namespace:
//https://github.com/polotek/libxmljs/issues/212
kml = kml.replace(/ xmlns=[^>]*>/, '>');
var doc = libxmljs.parseXmlString(kml);
//console.log("doc: " + doc);
if ( ! doc ) {
return;
}
var coo = doc.get("//Document/Folder/name");
//console.log("coo: " + coo);
if ( ! coo ) {
return;
}
coo = coo.text();
//console.log("coo: " + coo);
if ( ! coo ) {
return;
}
return coo;
};
// KML tests
it('KML format, unauthenticated', function(done){
assert.response(app, {
url: '/api/v1/sql?q=SELECT%20*%20FROM%20untitle_table_4%20LIMIT%201&format=kml',
headers: {host: 'vizzuality.cartodb.com'},
method: 'GET'
},{ }, function(res){
assert.equal(res.statusCode, 200, res.body);
var cd = res.header('Content-Disposition');
assert.equal(true, /^attachment/.test(cd), 'KML is not disposed as attachment: ' + cd);
assert.equal(true, /filename=cartodb-query.kml/gi.test(cd), 'Unexpected KML filename: ' + cd);
var row0 = res.body;
var checkfields = {'Name':1, 'address':1, 'cartodb_id':1, 'the_geom':0, 'the_geom_webmercator':0};
Object.keys(checkfields).forEach(function(f) {
if ( checkfields[f] ) {
assert.ok(hasAttribute(row0, f), "result does not include '" + f + "': " + row0);
} else {
assert.ok(!hasAttribute(row0, f), "result includes '" + f + "'");
}
});
done();
});
});
it('KML format, unauthenticated, POST', function(done){
assert.response(app, {
url: '/api/v1/sql',
data: 'q=SELECT%20*%20FROM%20untitle_table_4%20LIMIT%201&format=kml',
headers: {host: 'vizzuality.cartodb.com', 'Content-Type': 'application/x-www-form-urlencoded' },
method: 'POST'
},{ }, function(res){
assert.equal(res.statusCode, 200, res.body);
var cd = res.header('Content-Disposition');
assert.equal(true, /^attachment/.test(cd), 'KML is not disposed as attachment: ' + cd);
assert.equal(true, /filename=cartodb-query.kml/gi.test(cd), 'Unexpected KML filename: ' + cd);
done();
});
});
it('KML format, bigger than 81920 bytes', function(done){
assert.response(app, {
url: '/api/v1/sql',
data: querystring.stringify({
q: 'SELECT 0 as fname FROM generate_series(0,81920)',
format: 'kml'
}),
headers: {host: 'vizzuality.cartodb.com', 'Content-Type': 'application/x-www-form-urlencoded' },
method: 'POST'
},{ }, function(res){
assert.equal(res.statusCode, 200, res.body);
var cd = res.header('Content-Disposition');
assert.equal(true, /^attachment/.test(cd), 'KML is not disposed as attachment: ' + cd);
assert.equal(true, /filename=cartodb-query.kml/gi.test(cd), 'Unexpected KML filename: ' + cd);
assert.ok(res.body.length > 81920, 'KML smaller than expected: ' + res.body.length);
done();
});
});
it('KML format, skipfields', function(done){
assert.response(app, {
url: '/api/v1/sql?q=SELECT%20*%20FROM%20untitle_table_4%20LIMIT%201&format=kml&skipfields=address,cartodb_id',
headers: {host: 'vizzuality.cartodb.com'},
method: 'GET'
},{ }, function(res){
assert.equal(res.statusCode, 200, res.body);
var cd = res.header('Content-Disposition');
assert.equal(true, /^attachment/.test(cd), 'KML is not disposed as attachment: ' + cd);
assert.equal(true, /filename=cartodb-query.kml/gi.test(cd), 'Unexpected KML filename: ' + cd);
var row0 = res.body;
var checkFields = {'Name':1, 'address':0, 'cartodb_id':0, 'the_geom':0, 'the_geom_webmercator':0};
Object.keys(checkFields).forEach(function(f) {
if ( checkFields[f] ) {
assert.ok(hasAttribute(row0, f), "result does not include '" + f + "': " + row0);
} else {
assert.ok(!hasAttribute(row0, f), "result includes '" + f + "'");
}
});
done();
});
});
it('KML format, unauthenticated, custom filename', function(done){
assert.response(app, {
url: '/api/v1/sql?q=SELECT%20*%20FROM%20untitle_table_4%20LIMIT%201&format=kml&filename=kmltest',
headers: {host: 'vizzuality.cartodb.com'},
method: 'GET'
},{ }, function(res){
assert.equal(res.statusCode, 200, res.body);
var cd = res.header('Content-Disposition');
assert.equal(true, /^attachment/.test(cd), 'KML is not disposed as attachment: ' + cd);
assert.equal(true, /filename=kmltest.kml/gi.test(cd), 'Unexpected KML filename: ' + cd);
var name = extractFolderName(res.body);
assert.equal(name, "kmltest");
done();
});
});
it('KML format, authenticated', function(done){
assert.response(app, {
url: '/api/v1/sql?q=SELECT%20*%20FROM%20untitle_table_4%20LIMIT%201&format=kml&api_key=1234',
headers: {host: 'vizzuality.cartodb.com'},
method: 'GET'
},{ }, function(res){
assert.equal(res.statusCode, 200, res.body);
var cd = res.header('Content-Disposition');
assert.equal(true, /filename=cartodb-query.kml/gi.test(cd), 'Unexpected KML filename: ' + cd);
done();
});
});
it('KML format, unauthenticated, concurrent requests', function(done){
var query = querystring.stringify({
q: "SELECT 'val', x, y, st_setsrid(st_makepoint(x,y),4326) as the_geom " +
"FROM generate_series(-180, 180) as x, generate_series(-90,90) y",
format: 'kml',
filename: 'multi'
});
var concurrency = 4;
var waiting = concurrency;
function onResponse(res) {
//console.log("Response started");
res.body = '';
//res.setEncoding('binary');
res.on('data', function(chunk){ res.body += chunk; });
res.on('end', function(){
//console.log("Response ended");
assert.equal(res.statusCode, 200, res.body);
assert.ok(res.body);
var snippet = res.body.substr(0, 5);
assert.equal(snippet, "<?xml");
var cd = res.headers['content-disposition'];
assert.equal(true, /^attachment/.test(cd), 'KML is not disposed as attachment: ' + cd);
assert.equal(true, /filename=multi.kml/gi.test(cd), 'Unexpected KML filename: ' + cd);
if ( ! --waiting ) {
app.close();
done();
}
});
}
function onError(err) {
console.log("Response error" + err);
}
server_utils.startOnNextPort(app, function() {
var port = app.address().port;
//console.log("Listening on port " + port);
for (var i=0; i<concurrency; ++i) {
//console.log("Sending request");
http.request({
host: 'localhost',
port: port,
path: '/api/v1/sql?' + query,
headers: {host: 'vizzuality.cartodb.com'},
agent: false // or should this be true ?
})
.on('response', onResponse)
.on('error', onError)
.end();
}
});
});
// See https://github.com/Vizzuality/CartoDB-SQL-API/issues/60
it('GET /api/v1/sql as kml with no rows', function(done){
assert.response(app, {
url: '/api/v1/sql?q=SELECT%20true%20WHERE%20false&format=kml',
headers: {host: 'vizzuality.cartodb.com'},
method: 'GET'
},{ }, function(res){
assert.equal(res.statusCode, 200, res.body);
// NOTE: GDAL-1.11+ added 'id="root_doc"' attribute to the output
var pat = new RegExp('^<\\?xml version="1.0" encoding="utf-8" \\?>' +
'<kml xmlns="http://www.opengis.net/kml/2.2">' +
'<Document( id="root_doc")?><Folder><name>cartodb_query</name></Folder></Document>' +
'</kml>$');
var body = res.body.replace(/\n/g,'');
assert.ok(body.match(pat),
"Response:\n" + body + '\ndoes not match pattern:\n' + pat);
done();
});
});
// See https://github.com/Vizzuality/CartoDB-SQL-API/issues/90
it('GET /api/v1/sql as kml with ending semicolon', function(done){
assert.response(app, {
url: '/api/v1/sql?' + querystring.stringify({
q: 'SELECT true WHERE false;',
format: 'kml'
}),
headers: {host: 'vizzuality.cartodb.com'},
method: 'GET'
},{ }, function(res){
assert.equal(res.statusCode, 200, res.body);
// NOTE: GDAL-1.11+ added 'id="root_doc"' attribute to the output
var pat = new RegExp('^<\\?xml version="1.0" encoding="utf-8" \\?>' +
'<kml xmlns="http://www.opengis.net/kml/2.2">' +
'<Document( id="root_doc")?><Folder><name>cartodb_query</name></Folder></Document>' +
'</kml>$');
var body = res.body.replace(/\n/g,'');
assert.ok(body.match(pat),
"Response:\n" + body + '\ndoes not match pattern:\n' + pat);
done();
});
});
// See https://github.com/CartoDB/cartodb/issues/276
it('check point coordinates, unauthenticated', function(done){
assert.response(app, {
url: '/api/v1/sql?' + querystring.stringify({
q: 'SELECT * from untitle_table_4 WHERE cartodb_id = -1',
format: 'kml'
}),
headers: {host: 'vizzuality.cartodb.com'},
method: 'GET'
},{ }, function(res){
assert.equal(res.statusCode, 200, res.body);
var coords = extractCoordinates(res.body);
assert(coords, 'No coordinates in ' + res.body);
assert.deepEqual(coords, [[33,16]]);
done();
});
});
// See https://github.com/CartoDB/cartodb/issues/276
it('check point coordinates, authenticated', function(done){
assert.response(app, {
url: '/api/v1/sql?' + querystring.stringify({
q: 'SELECT * from untitle_table_4 WHERE cartodb_id = -1',
api_key: 1234,
format: 'kml'
}),
headers: {host: 'vizzuality.cartodb.com'},
method: 'GET'
},{ }, function(res){
assert.equal(res.statusCode, 200, res.body);
var coords = extractCoordinates(res.body);
assert(coords, 'No coordinates in ' + res.body);
assert.deepEqual(coords, [[33,16]]);
done();
});
});
var limit = 1200;
it('expects ' + limit + ' placemarks in public table', function(done){
assert.response(app, {
url: '/api/v1/sql',
data: querystring.stringify({
q: "SELECT * from populated_places_simple_reduced limit " + limit,
format: 'kml'
}),
headers: {host: 'vizzuality.cartodb.com', 'Content-Type': 'application/x-www-form-urlencoded' },
method: 'POST'
},
{
status: 200
},
function(res) {
assert.equal(res.body.match(/<Placemark>/g).length, limit);
done();
}
);
});
it('expects ' + limit + ' placemarks in private table using the API KEY', function(done){
assert.response(app, {
url: '/api/v1/sql?' + querystring.stringify({
q: "SELECT * from populated_places_simple_reduced limit " + limit,
api_key: 1234,
format: 'kml'
}),
headers: {host: 'vizzuality.cartodb.com'},
method: 'GET'
},
{
status: 200
},
function(res) {
assert.equal(res.body.match(/<Placemark>/g).length, limit);
done();
}
);
});
});
|
const dynamodb = require('aws-sdk/clients/dynamodb');
const lambda = require('../../../src/handlers/post-testcase');
// This includes all tests for putItemHandler
describe('Post Test Case handler', () => {
let putSpy;
beforeAll(() => {
putSpy = jest.spyOn(dynamodb.DocumentClient.prototype, 'put');
});
afterAll(() => {
putSpy.mockRestore();
});
beforeEach(() => {
putSpy.mockReturnValue({
promise: () => Promise.resolve('data'),
});
});
function buildEvent(amount) {
return {
httpMethod: 'POST',
queryStringParameters: {
"amount": amount
}
};
}
// This test invokes putItemHandler and compares the result
it('should add add a new testcase (amount 1)', async () => {
const event = buildEvent(null);
// Invoke putItemHandler()
const result = await lambda.postTestcaseHandler(event);
// Compare the result with the expected result
expect(result).toBeTruthy();
const body = JSON.parse(result.body);
expect(body[0].id).toBeTruthy();
expect(body[0].uuid_read).toBeTruthy();
expect(body[0].uuid_write).toBeTruthy();
expect(body[0].infected).toEqual("NOT_TESTED");
expect(body[0].date).toBeTruthy();
});
it('should create multiple results', async () => {
const event = buildEvent("10");
const result = await lambda.postTestcaseHandler(event);
expect(result).toBeTruthy();
const body = JSON.parse(result.body);
expect(body.length).toEqual(10);
});
it('should limit to 50 creations per call', async () => {
const event = buildEvent("51");
const result = await lambda.postTestcaseHandler(event);
expect(result).toBeTruthy();
const body = JSON.parse(result.body);
expect(body.length).toEqual(50);
});
it('should default to 1 for unparseable numbers', async () => {
const event = buildEvent("??sada");
const result = await lambda.postTestcaseHandler(event);
expect(result).toBeTruthy();
const body = JSON.parse(result.body);
expect(body.length).toEqual(1);
});
});
|
// CodeMirrror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: http://codemirror.net/LICENSE
/**
* Author: Gautam Mehta
* Branched from CodeMirrror's Scheme mode
*/
(function(mod) {
if (typeof exports == "object" && typeof module == "object") // CommonJS
mod(require("../../lib/codemirror"));
else if (typeof define == "function" && define.amd) // AMD
define(["../../lib/codemirror"], mod);
else // Plain browser env
mod(CodeMirrror);
})(function(CodeMirrror) {
"use strict";
CodeMirrror.defineMode("cobol", function () {
var BUILTIN = "builtin", COMMENT = "comment", STRING = "string",
ATOM = "atom", NUMBER = "number", KEYWORD = "keyword", MODTAG = "header",
COBOLLINENUM = "def", PERIOD = "link";
function makeKeywords(str) {
var obj = {}, words = str.split(" ");
for (var i = 0; i < words.length; ++i) obj[words[i]] = true;
return obj;
}
var atoms = makeKeywords("TRUE FALSE ZEROES ZEROS ZERO SPACES SPACE LOW-VALUE LOW-VALUES ");
var keywords = makeKeywords(
"ACCEPT ACCESS ACQUIRE ADD ADDRESS " +
"ADVANCING AFTER ALIAS ALL ALPHABET " +
"ALPHABETIC ALPHABETIC-LOWER ALPHABETIC-UPPER ALPHANUMERIC ALPHANUMERIC-EDITED " +
"ALSO ALTER ALTERNATE AND ANY " +
"ARE AREA AREAS ARITHMETIC ASCENDING " +
"ASSIGN AT ATTRIBUTE AUTHOR AUTO " +
"AUTO-SKIP AUTOMATIC B-AND B-EXOR B-LESS " +
"B-NOT B-OR BACKGROUND-COLOR BACKGROUND-COLOUR BEEP " +
"BEFORE BELL BINARY BIT BITS " +
"BLANK BLINK BLOCK BOOLEAN BOTTOM " +
"BY CALL CANCEL CD CF " +
"CH CHARACTER CHARACTERS CLASS CLOCK-UNITS " +
"CLOSE COBOL CODE CODE-SET COL " +
"COLLATING COLUMN COMMA COMMIT COMMITMENT " +
"COMMON COMMUNICATION COMP COMP-0 COMP-1 " +
"COMP-2 COMP-3 COMP-4 COMP-5 COMP-6 " +
"COMP-7 COMP-8 COMP-9 COMPUTATIONAL COMPUTATIONAL-0 " +
"COMPUTATIONAL-1 COMPUTATIONAL-2 COMPUTATIONAL-3 COMPUTATIONAL-4 COMPUTATIONAL-5 " +
"COMPUTATIONAL-6 COMPUTATIONAL-7 COMPUTATIONAL-8 COMPUTATIONAL-9 COMPUTE " +
"CONFIGURATION CONNECT CONSOLE CONTAINED CONTAINS " +
"CONTENT CONTINUE CONTROL CONTROL-AREA CONTROLS " +
"CONVERTING COPY CORR CORRESPONDING COUNT " +
"CRT CRT-UNDER CURRENCY CURRENT CURSOR " +
"DATA DATE DATE-COMPILED DATE-WRITTEN DAY " +
"DAY-OF-WEEK DB DB-ACCESS-CONTROL-KEY DB-DATA-NAME DB-EXCEPTION " +
"DB-FORMAT-NAME DB-RECORD-NAME DB-SET-NAME DB-STATUS DBCS " +
"DBCS-EDITED DE DEBUG-CONTENTS DEBUG-ITEM DEBUG-LINE " +
"DEBUG-NAME DEBUG-SUB-1 DEBUG-SUB-2 DEBUG-SUB-3 DEBUGGING " +
"DECIMAL-POINT DECLARATIVES DEFAULT DELETE DELIMITED " +
"DELIMITER DEPENDING DESCENDING DESCRIBED DESTINATION " +
"DETAIL DISABLE DISCONNECT DISPLAY DISPLAY-1 " +
"DISPLAY-2 DISPLAY-3 DISPLAY-4 DISPLAY-5 DISPLAY-6 " +
"DISPLAY-7 DISPLAY-8 DISPLAY-9 DIVIDE DIVISION " +
"DOWN DROP DUPLICATE DUPLICATES DYNAMIC " +
"EBCDIC EGI EJECT ELSE EMI " +
"EMPTY EMPTY-CHECK ENABLE END END. END-ACCEPT END-ACCEPT. " +
"END-ADD END-CALL END-COMPUTE END-DELETE END-DISPLAY " +
"END-DIVIDE END-EVALUATE END-IF END-INVOKE END-MULTIPLY " +
"END-OF-PAGE END-PERFORM END-READ END-RECEIVE END-RETURN " +
"END-REWRITE END-SEARCH END-START END-STRING END-SUBTRACT " +
"END-UNSTRING END-WRITE END-XML ENTER ENTRY " +
"ENVIRONMENT EOP EQUAL EQUALS ERASE " +
"ERROR ESI EVALUATE EVERY EXCEEDS " +
"EXCEPTION EXCLUSIVE EXIT EXTEND EXTERNAL " +
"EXTERNALLY-DESCRIBED-KEY FD FETCH FILE FILE-CONTROL " +
"FILE-STREAM FILES FILLER FINAL FIND " +
"FINISH FIRST FOOTING FOR FOREGROUND-COLOR " +
"FOREGROUND-COLOUR FORMAT FREE FROM FULL " +
"FUNCTION GENERATE GET GIVING GLOBAL " +
"GO GOBACK GREATER GROUP HEADING " +
"HIGH-VALUE HIGH-VALUES HIGHLIGHT I-O I-O-CONTROL " +
"ID IDENTIFICATION IF IN INDEX " +
"INDEX-1 INDEX-2 INDEX-3 INDEX-4 INDEX-5 " +
"INDEX-6 INDEX-7 INDEX-8 INDEX-9 INDEXED " +
"INDIC INDICATE INDICATOR INDICATORS INITIAL " +
"INITIALIZE INITIATE INPUT INPUT-OUTPUT INSPECT " +
"INSTALLATION INTO INVALID INVOKE IS " +
"JUST JUSTIFIED KANJI KEEP KEY " +
"LABEL LAST LD LEADING LEFT " +
"LEFT-JUSTIFY LENGTH LENGTH-CHECK LESS LIBRARY " +
"LIKE LIMIT LIMITS LINAGE LINAGE-COUNTER " +
"LINE LINE-COUNTER LINES LINKAGE LOCAL-STORAGE " +
"LOCALE LOCALLY LOCK " +
"MEMBER MEMORY MERGE MESSAGE METACLASS " +
"MODE MODIFIED MODIFY MODULES MOVE " +
"MULTIPLE MULTIPLY NATIONAL NATIVE NEGATIVE " +
"NEXT NO NO-ECHO NONE NOT " +
"NULL NULL-KEY-MAP NULL-MAP NULLS NUMBER " +
"NUMERIC NUMERIC-EDITED OBJECT OBJECT-COMPUTER OCCURS " +
"OF OFF OMITTED ON ONLY " +
"OPEN OPTIONAL OR ORDER ORGANIZATION " +
"OTHER OUTPUT OVERFLOW OWNER PACKED-DECIMAL " +
"PADDING PAGE PAGE-COUNTER PARSE PERFORM " +
"PF PH PIC PICTURE PLUS " +
"POINTER POSITION POSITIVE PREFIX PRESENT " +
"PRINTING PRIOR PROCEDURE PROCEDURE-POINTER PROCEDURES " +
"PROCEED PROCESS PROCESSING PROGRAM PROGRAM-ID " +
"PROMPT PROTECTED PURGE QUEUE QUOTE " +
"QUOTES RANDOM RD READ READY " +
"REALM RECEIVE RECONNECT RECORD RECORD-NAME " +
"RECORDS RECURSIVE REDEFINES REEL REFERENCE " +
"REFERENCE-MONITOR REFERENCES RELATION RELATIVE RELEASE " +
"REMAINDER REMOVAL RENAMES REPEATED REPLACE " +
"REPLACING REPORT REPORTING REPORTS REPOSITORY " +
"REQUIRED RERUN RESERVE RESET RETAINING " +
"RETRIEVAL RETURN RETURN-CODE RETURNING REVERSE-VIDEO " +
"REVERSED REWIND REWRITE RF RH " +
"RIGHT RIGHT-JUSTIFY ROLLBACK ROLLING ROUNDED " +
"RUN SAME SCREEN SD SEARCH " +
"SECTION SECURE SECURITY SEGMENT SEGMENT-LIMIT " +
"SELECT SEND SENTENCE SEPARATE SEQUENCE " +
"SEQUENTIAL SET SHARED SIGN SIZE " +
"SKIP1 SKIP2 SKIP3 SORT SORT-MERGE " +
"SORT-RETURN SOURCE SOURCE-COMPUTER SPACE-FILL " +
"SPECIAL-NAMES STANDARD STANDARD-1 STANDARD-2 " +
"START STARTING STATUS STOP STORE " +
"STRING SUB-QUEUE-1 SUB-QUEUE-2 SUB-QUEUE-3 SUB-SCHEMA " +
"SUBFILE SUBSTITUTE SUBTRACT SUM SUPPRESS " +
"SYMBOLIC SYNC SYNCHRONIZED SYSIN SYSOUT " +
"TABLE TALLYING TAPE TENANT TERMINAL " +
"TERMINATE TEST TEXT THAN THEN " +
"THROUGH THRU TIME TIMES TITLE " +
"TO TOP TRAILING TRAILING-SIGN TRANSACTION " +
"TYPE TYPEDEF UNDERLINE UNEQUAL UNIT " +
"UNSTRING UNTIL UP UPDATE UPON " +
"USAGE USAGE-MODE USE USING VALID " +
"VALIDATE VALUE VALUES VARYING VLR " +
"WAIT WHEN WHEN-COMPILED WITH WITHIN " +
"WORDS WORKING-STORAGE WRITE XML XML-CODE " +
"XML-EVENT XML-NTEXT XML-TEXT ZERO ZERO-FILL " );
var builtins = makeKeywords("- * ** / + < <= = > >= ");
var tests = {
digit: /\d/,
digit_or_colon: /[\d:]/,
hex: /[0-9a-f]/i,
sign: /[+-]/,
exponent: /e/i,
keyword_char: /[^\s\(\[\;\)\]]/,
symbol: /[\w*+\-]/
};
function isNumber(ch, stream){
// hex
if ( ch === '0' && stream.eat(/x/i) ) {
stream.eatWhile(tests.hex);
return true;
}
// leading sign
if ( ( ch == '+' || ch == '-' ) && ( tests.digit.test(stream.peek()) ) ) {
stream.eat(tests.sign);
ch = stream.next();
}
if ( tests.digit.test(ch) ) {
stream.eat(ch);
stream.eatWhile(tests.digit);
if ( '.' == stream.peek()) {
stream.eat('.');
stream.eatWhile(tests.digit);
}
if ( stream.eat(tests.exponent) ) {
stream.eat(tests.sign);
stream.eatWhile(tests.digit);
}
return true;
}
return false;
}
return {
startState: function () {
return {
indentStack: null,
indentation: 0,
mode: false
};
},
token: function (stream, state) {
if (state.indentStack == null && stream.sol()) {
// update indentation, but only if indentStack is empty
state.indentation = 6 ; //stream.indentation();
}
// skip spaces
if (stream.eatSpace()) {
return null;
}
var returnType = null;
switch(state.mode){
case "string": // multi-line string parsing mode
var next = false;
while ((next = stream.next()) != null) {
if (next == "\"" || next == "\'") {
state.mode = false;
break;
}
}
returnType = STRING; // continue on in string mode
break;
default: // default parsing mode
var ch = stream.next();
var col = stream.column();
if (col >= 0 && col <= 5) {
returnType = COBOLLINENUM;
} else if (col >= 72 && col <= 79) {
stream.skipToEnd();
returnType = MODTAG;
} else if (ch == "*" && col == 6) { // comment
stream.skipToEnd(); // rest of the line is a comment
returnType = COMMENT;
} else if (ch == "\"" || ch == "\'") {
state.mode = "string";
returnType = STRING;
} else if (ch == "'" && !( tests.digit_or_colon.test(stream.peek()) )) {
returnType = ATOM;
} else if (ch == ".") {
returnType = PERIOD;
} else if (isNumber(ch,stream)){
returnType = NUMBER;
} else {
if (stream.current().match(tests.symbol)) {
while (col < 71) {
if (stream.eat(tests.symbol) === undefined) {
break;
} else {
col++;
}
}
}
if (keywords && keywords.propertyIsEnumerable(stream.current().toUpperCase())) {
returnType = KEYWORD;
} else if (builtins && builtins.propertyIsEnumerable(stream.current().toUpperCase())) {
returnType = BUILTIN;
} else if (atoms && atoms.propertyIsEnumerable(stream.current().toUpperCase())) {
returnType = ATOM;
} else returnType = null;
}
}
return returnType;
},
indent: function (state) {
if (state.indentStack == null) return state.indentation;
return state.indentStack.indent;
}
};
});
CodeMirrror.defineMIME("text/x-cobol", "cobol");
});
|
"use strict";
const { resolve } = require("path");
const Permissions = require(resolve(require.resolve("zelvbod.js").replace("index.js", "/util/Permissions.js")));
const Constants = require(resolve(require.resolve("zelvbod.js").replace("index.js", "/util/Constants.js")));
const Intents = require(resolve(require.resolve("zelvbod.js").replace("index.js", "/util/Intents.js")));
const APIMessage = require(resolve(require.resolve("zelvbod.js").replace("index.js", "/structures/APIMessage.js")));
const RHPath = resolve(require.resolve("zelvbod.js").replace("index.js", "/rest/APIRequest.js"));
const RH = require(RHPath);
require.cache[RHPath].exports = class APIRequest extends RH {
async make() {
const response = await super.make();
if(this.client.listenerCount("rest")) {
this.client.emit("rest", {
path: this.path,
method: this.method,
response: this.client.options.restEventIncludeBuffer ? response.clone().buffer() : null
});
}
return response;
}
};
const SHPath = resolve(require.resolve("zelvbod.js").replace("index.js", "/client/websocket/WebSocketShard.js"));
const SH = require(SHPath);
require.cache[SHPath].exports = class WebSocketShard extends SH {
async emitReady() {
const c = this.manager.client;
if(c.options.fetchAllMembers && (!c.options.ws.intents || c.options.ws.intents & Intents.FLAGS.GUILD_MEMBERS)) {
this.debug("Attempting to fetch all members");
const guilds = c.guilds.cache.filter(g => g.shardID === this.id);
let n = 0;
let g = 0;
for(const guild of guilds.values()) {
if(!guild.available) {
this.debug(`Skipped guild ${guild.id}! Guild not available`);
continue;
}
if(this.ratelimit.remaining < 5) {
const left = Math.ceil(this.ratelimit.timer._idleStart + this.ratelimit.timer._idleTimeout - (process.uptime() * 1000)) + 1000;
this.debug(`Gateway ratelimit reached, continuing in ${left}ms`);
this.debug(`Fetching progress: ${g} guilds / ${n} members`);
await new Promise(r => { setTimeout(r, left); });
}
try {
const m = await guild.members.fetch({ time: 15000 });
n += m.size;
g++;
} catch(err) {
this.debug(`Failed to fetch all members for guild ${guild.id}! ${err}`);
}
}
this.debug(`Fetched ${guilds.reduce((a, t) => a + t.members.cache.size, 0)} members`);
}
this.debug("Ready");
this.status = Constants.Status.READY;
this.emit(Constants.ShardEvents.ALL_READY, this.expectedGuilds.size ? this.expectedGuilds : void 0);
}
checkReady() {
if(this.readyTimeout) {
this.manager.client.clearTimeout(this.readyTimeout);
this.readyTimeout = void 0;
}
if(!this.expectedGuilds.size) {
this.debug("Shard received all its guilds, marking as ready.");
this.emitReady();
return;
}
this.readyTimeout = this.manager.client.setTimeout(() => {
this.debug(`Shard did not receive any more guilds in 15 seconds, marking as ready. ${this.expectedGuilds.size} guilds are unavailable`);
this.readyTimeout = void 0;
this.emitReady();
}, 15000);
}
};
const VCPath = resolve(require.resolve("zelvbod.js").replace("index.js", "/client/voice/VoiceConnection.js"));
const VC = require(VCPath);
require.cache[VCPath].exports = class VoiceConnection extends VC {
constructor(voiceManager, channel) {
super(voiceManager);
this._channel = channel;
Object.defineProperty(this, "channel", {
enumerable: false,
get: function() {
return this.client.channels.cache.get(this._channel.id) || this._channel;
}
});
}
updateChannel(channel) {
this._channel = channel;
this.sendVoiceStateUpdate();
}
};
const ALPath = resolve(require.resolve("zelvbod.js").replace("index.js", "/structures/GuildAuditLogs.js"));
const AL = require(ALPath);
AL.Entry = class GuildAuditLogsEntry extends AL.Entry {
constructor(logs, guild, data) {
super(logs, guild, data);
if(!this.executor) { this.executor = guild.client.users.add(logs._users.find(t => t.id === data.user_id) || { id: data.user_id }, false); }
const c = logs.constructor;
const target = c.targetType(data.action_type);
if(((target === c.Targets.USER || target === c.Targets.MESSAGE) && data.action_type !== c.Actions.MESSAGE_BULK_DELETE) && data.target_id && !this.target) {
this.target = guild.client.users.add(logs._users.find(t => t.id === data.target_id) || { id: data.target_id }, false);
} else if(target === c.Targets.GUILD && !this.target) {
this.target = guild.client.guilds.add({ id: data.target_id }, false);
}
}
};
require.cache[ALPath].exports = class GuildAuditLogs extends AL {
constructor(guild, data) {
const o = {};
for(const i in data) {
if(!["users", "audit_log_entries"].includes(i)) { o[i] = data[i]; }
}
o.audit_log_entries = [];
super(guild, o);
this._users = data.users;
for(const item of data.audit_log_entries) {
const entry = new this.constructor.Entry(this, guild, item);
this.entries.set(entry.id, entry);
}
}
static build(...args) {
const logs = new this(...args);
return Promise.all(logs.entries.map(e => e.target)).then(() => logs);
}
};
const TXPath = resolve(require.resolve("zelvbod.js").replace("index.js", "/structures/interfaces/TextBasedChannel.js"));
const TX = require(TXPath);
require.cache[TXPath].exports = class TextBasedChannel extends TX {
async send(content, options) {
if (this.constructor.name === "User" || this.constructor.name === "GuildMember") {
return this.createDM().then(dm => dm.send(content, options));
}
let apiMessage;
if (content instanceof APIMessage) {
apiMessage = content.resolveData();
} else {
apiMessage = APIMessage.create(this, content, options).resolveData();
if (Array.isArray(apiMessage.data.content)) {
return Promise.all(apiMessage.split().map(this.send.bind(this)));
}
}
const { data, files } = await apiMessage.resolveFiles();
return this.client.api.channels[this.id].messages.post({
data,
files
}).then(d => {
if(this.guild) { d.guild_id = this.guild.id; }
return this.client.actions.MessageCreate.handle(d).message;
});
}
};
const GCPath = resolve(require.resolve("zelvbod.js").replace("index.js", "/structures/GuildChannel.js"));
const GC = require(GCPath);
require.cache[GCPath].exports = class GuildChannel extends GC {
constructor(guild, data) {
super({ client: guild.client }, data);
if(this.client.options.cacheGuilds) {
this.guild = guild;
} else {
this._guildID = guild.id;
this._shardID = guild.shardID;
Object.defineProperty(this, "guild", {
enumerable: false,
get: function() {
return this.client.guilds.cache.get(this._guildID) || this.client.guilds.add({
id: this._guildID,
shardID: this._shardID
}, false);
}
});
}
}
get deletable() {
if(this.deleted) { return false; }
if(!this.client.options.cacheRoles && !this.guild.roles.cache.size) { return false; }
return this.permissionsFor(this.client.user).has(Permissions.FLAGS.MANAGE_CHANNELS, false);
}
};
const Action = require(resolve(require.resolve("zelvbod.js").replace("index.js", "/client/actions/Action.js")));
Action.prototype.getPayload = function(data, manager, id, partialType, cache) {
return manager.cache.get(id) || manager.add(data, cache);
};
|
function getData(){
return new Promise((resolve,reject)=>{
let ajax = new XMLHttpRequest();
ajax.onload = function(){
resolve(ajax.response);
};
ajax.onerror = function(error){
reject(error);
};
ajax.open("GET", "http://localhost:7013/api/departments");
ajax.send();
});
}
function postData(emp){
return new Promise((resolve,reject)=>{
let ajax = new XMLHttpRequest();
ajax.onload = function(){
resolve(ajax.response);
};
ajax.onerror = function(error){
reject(e);
};
ajax.open("POST","http://localhost:7013/api/employees");
ajax.setRequestHeader("Content-Type", "application/json");
ajax.send(JSON.stringify(emp));
});
}
function putData(id,product){
ajax.open("PUT", `http://localhost:7013/api/employees/${id}`);
}
function deleteData(id){
ajax.open("DELETE", `http://localhost:7013/api/employees/${id}`);
}
|
/*
* Copyright 2016 Google Inc. 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.
*/
'use strict';
var assert = require('proclaim');
var sinon = require('sinon');
var calcRect = require('../../../src/util/calcRect');
suite('calcRect', function() {
test('null', function() {
var rect = calcRect(1, 1, null);
assert(rect.x === 0);
assert(rect.y === 0);
assert(rect.width === 1);
assert(rect.height === 1);
});
test('relative offset', function() {
var rect = calcRect(100, 200, { relativeX: 0.1, relativeY: 0.2 });
assert(rect.x === 0.1);
assert(rect.y === 0.2);
assert(rect.width === 1);
assert(rect.height === 1);
});
test('relative size', function() {
var rect = calcRect(100, 200, { relativeWidth: 0.25, relativeHeight: 0.75 });
assert(rect.x === 0);
assert(rect.y === 0);
assert(rect.width === 0.25);
assert(rect.height === 0.75);
});
test('relative offset and size', function() {
var rect = calcRect(100, 200,
{ relativeX: 0.1, relativeY: 0.2,
relativeWidth: 0.25, relativeHeight: 0.75 });
assert(rect.x === 0.1);
assert(rect.y === 0.2);
assert(rect.width === 0.25);
assert(rect.height === 0.75);
});
test('absolute offset', function() {
var rect = calcRect(100, 200, { absoluteX: 10, absoluteY: 40 });
assert(rect.x === 0.1);
assert(rect.y === 0.2);
assert(rect.width === 1);
assert(rect.height === 1);
});
test('absolute size', function() {
var rect = calcRect(100, 200, { absoluteWidth: 20, absoluteHeight: 50 });
assert(rect.x === 0);
assert(rect.y === 0);
assert(rect.width === 0.2);
assert(rect.height === 0.25);
});
test('absolute offset and size', function() {
var rect = calcRect(100, 200,
{ absoluteX: 10, absoluteY: 40,
absoluteWidth: 20, absoluteHeight: 50 });
assert(rect.x === 0.1);
assert(rect.y === 0.2);
assert(rect.width === 0.2);
assert(rect.height === 0.25);
});
test('relative offset absolute size', function() {
var rect = calcRect(100, 200,
{ relativeX: 0.1, relativeY: 0.2,
absoluteWidth: 20, absoluteHeight: 50 });
assert(rect.x === 0.1);
assert(rect.y === 0.2);
assert(rect.width === 0.2);
assert(rect.height === 0.25);
});
test('absolute offset relative size', function() {
var rect = calcRect(100, 200,
{ absoluteX: 10, absoluteY: 40,
relativeWidth: 0.25, relativeHeight: 0.75 });
assert(rect.x === 0.1);
assert(rect.y === 0.2);
assert(rect.width === 0.25);
assert(rect.height === 0.75);
});
test('absolute overrides relative', function() {
var rect = calcRect(100, 200,
{ absoluteX: 10, absoluteY: 40,
absoluteWidth: 20, absoluteHeight: 50,
relativeX: 0.12, relativeY: 0.34,
relativeWidth: 0.56, relativeHeight: 0.78 });
assert(rect.x === 0.1);
assert(rect.y === 0.2);
assert(rect.width === 0.2);
assert(rect.height === 0.25);
});
});
|
/**
任务名称:task#2867 【智慧工地2.0-前端】工序进度模块功能开发
开发人员:耿为刚
日期:2020-04-02
任务类型:全新代码
**/
// 模板分类
const WORKING_TEMPLATE_TYPE = {
ABOVE_GROUND: {
value: 1,
desc: '房建地上'
},
UNDERGROUND: {
value: 2,
desc: '地下'
},
GROUND: {
value: 3,
desc: '地面'
}
}
export default {
WORKING_TEMPLATE_TYPE
}
|
const grpc = require('grpc')
const protoLoader = require('@grpc/proto-loader')
const path = require('path')
const isValidIP = require('../ip')
const PROTO_PATH = path.join(__dirname, '/../../../kv.proto')
const packageDefinition = protoLoader.loadSync(
PROTO_PATH,
{
keepCase: true,
longs: String,
enums: String,
defaults: true,
oneofs: true
})
const KVProto = grpc.loadPackageDefinition(packageDefinition).kv
let verbose = false
const explain = msg => {
if (verbose) {
console.log(`${Date.now()}: ${msg}`)
}
}
const doGet = (ip, key) => {
const grpcClient = new KVProto.Client(ip, grpc.credentials.createInsecure())
explain(`sending GET request to ${ip} for key '${key}'...`)
grpcClient.get({ key }, function (err, response) {
if (err) {
console.error(`error: ${err.message}`)
} else {
if (response.defined) {
console.log(`'${key}'='${response.value}'`)
} else {
console.log(`'${key}': undefined`)
}
}
})
}
const doSet = (ip, key, value) => {
const grpcClient = new KVProto.Client(ip, grpc.credentials.createInsecure())
explain(`sending SET request to ${ip} for key '${key}'...`)
grpcClient.set({ key, value, broadcast: true }, function (err, response) {
if (err) {
console.error(`error: ${err.message}`)
}
})
}
const doList = ip => {
const grpcClient = new KVProto.Client(ip, grpc.credentials.createInsecure())
explain(`sending LIST request to ${ip}...`)
grpcClient.list({}, function (err, response) {
if (err) {
console.error(`error: ${err.message}`)
} else {
console.log(`Key-value pairs defined on ${ip}:`)
for (const key in response.store) {
console.log(` - '${key}'='${response.store[key]}'`)
}
console.log('-- end of key-value dump --')
}
})
}
const handleGet = (ip, key) => {
const re = /^[a-zA-Z0-9_]+$/
if (!re.test(key)) {
throw new Error(`invalid --get: expected '--get KEY'; got '--get ${key}'`)
}
doGet(ip, key)
}
const handleSet = (ip, kv) => {
const re = /^([a-zA-Z0-9_]+)=([a-zA-Z0-9_]+)$/
const match = re.exec(kv)
if (match === null) {
throw new Error(`invalid --set: expected '--set KEY=VALUE'; got '--set ${kv}'`)
}
doSet(ip, match[1], match[2])
}
const client = {
desc: `Send request(s) to a key-value store server.`,
builder: yargs =>
yargs
.option('ip', {
alias: 'i',
describe: `Set server IP address (IPv4 only!).`,
type: 'string',
default: '127.0.0.1:4000',
nargs: 1
})
.option('get', {
alias: 'g',
describe: `Get value associated with key.`,
type: 'string',
nargs: 1
})
.option('set', {
alias: 's',
describe: `Set a key-value pair.`,
type: 'string',
nargs: 1
})
.option('list', {
alias: 'l',
describe: `Get key-value pairs defined on server.`,
type: 'bool',
default: false,
nargs: 0
})
// .demandOption(['get', 'set', 'list'])
.check(argv => {
if (Array.isArray(argv.ip)) {
argv.ip = argv.ip[argv.ip.length - 1]
console.log(`connecting to server ${argv.ip}...`)
}
if (!isValidIP(argv.ip)) {
throw new Error(`not a valid server IP address: ${argv.ip}`)
}
verbose = argv.verbose
return true
})
.strict(true),
handler: argv => {
argv._handled = true
let cmdExecuted = false
if (typeof argv.get !== 'undefined') {
cmdExecuted = true
if (argv.get instanceof Array) {
argv.get.forEach(key => handleGet(argv.ip, key))
} else {
handleGet(argv.ip, argv.get)
}
}
if (typeof argv.set !== 'undefined') {
cmdExecuted = true
if (argv.set instanceof Array) {
argv.set.forEach(kv => handleSet(argv.ip, kv))
} else {
handleSet(argv.ip, argv.set)
}
}
if (argv.list) {
cmdExecuted = true
doList(argv.ip)
}
if (!cmdExecuted) {
console.log('nothing to do; please specify an operation')
}
}
}
module.exports = client
|
window.onload = function(){
var socket = io();
var playerid = document.getElementById('player').getAttribute('value');
dom = document.getElementById('TutContainer');
document.addEventListener("keydown", handleOnKeyPress)
document.getElementById('lompat').onclick = function(){lompat()};
document.getElementById('kanan').onclick = function(){kanan()};
document.getElementById('kiri').onclick = function(){kiri()};
document.getElementById('restart').onclick = function(){restart()};
function handleOnKeyPress(keyEvent){
if (keyEvent.keyCode === 82){
socket.emit('action', {player:playerid, action:82});
}
if ( keyEvent.keyCode === 37) {//left
socket.emit('movement', {player:playerid, movement:37});
} else if ( keyEvent.keyCode === 39) {//right
socket.emit('movement', {player:playerid, movement:39});
}else{
if ( keyEvent.keyCode === 38){//up, jump
socket.emit('movement', {player:playerid, movement:38});
}
}
}
function lompat(){
socket.emit('movement', {player:playerid, movement:38});
}
function kanan(){
socket.emit('movement', {player:playerid, movement:39});
}
function kiri(){
socket.emit('movement', {player:playerid, movement:37});
}
function restart(){
socket.emit('action', {player:playerid, action:82});
}
socket.on('disconnect', function () { console.log('disconnected')});
}
|
/**
* DO NOT EDIT THIS FILE.
* See the following change record for more information,
* https://www.drupal.org/node/2815083
* @preserve
**/
(function ($, Drupal, drupalSettings) {
var options = $.extend({
breakpoints: {
'toolbar.narrow': '',
'toolbar.standard': '',
'toolbar.wide': ''
}
}, drupalSettings.toolbar, {
strings: {
horizontal: Drupal.t('Horizontal orientation'),
vertical: Drupal.t('Vertical orientation')
}
});
Drupal.behaviors.toolbar = {
attach: function attach(context) {
if (!window.matchMedia('only screen').matches) {
return;
}
$(context).find('#toolbar-administration').once('toolbar').each(function () {
var model = new Drupal.toolbar.ToolbarModel({
locked: JSON.parse(localStorage.getItem('Drupal.toolbar.trayVerticalLocked')),
activeTab: document.getElementById(JSON.parse(localStorage.getItem('Drupal.toolbar.activeTabID'))),
height: $('#toolbar-administration').outerHeight()
});
Drupal.toolbar.models.toolbarModel = model;
Object.keys(options.breakpoints).forEach(function (label) {
var mq = options.breakpoints[label];
var mql = window.matchMedia(mq);
Drupal.toolbar.mql[label] = mql;
mql.addListener(Drupal.toolbar.mediaQueryChangeHandler.bind(null, model, label));
Drupal.toolbar.mediaQueryChangeHandler.call(null, model, label, mql);
});
Drupal.toolbar.views.toolbarVisualView = new Drupal.toolbar.ToolbarVisualView({
el: this,
model: model,
strings: options.strings
});
Drupal.toolbar.views.toolbarAuralView = new Drupal.toolbar.ToolbarAuralView({
el: this,
model: model,
strings: options.strings
});
Drupal.toolbar.views.bodyVisualView = new Drupal.toolbar.BodyVisualView({
el: this,
model: model
});
model.trigger('change:isFixed', model, model.get('isFixed'));
model.trigger('change:activeTray', model, model.get('activeTray'));
var menuModel = new Drupal.toolbar.MenuModel();
Drupal.toolbar.models.menuModel = menuModel;
Drupal.toolbar.views.menuVisualView = new Drupal.toolbar.MenuVisualView({
el: $(this).find('.toolbar-menu-administration').get(0),
model: menuModel,
strings: options.strings
});
Drupal.toolbar.setSubtrees.done(function (subtrees) {
menuModel.set('subtrees', subtrees);
var theme = drupalSettings.ajaxPageState.theme;
localStorage.setItem('Drupal.toolbar.subtrees.' + theme, JSON.stringify(subtrees));
model.set('areSubtreesLoaded', true);
});
Drupal.toolbar.views.toolbarVisualView.loadSubtrees();
$(document).on('drupalViewportOffsetChange.toolbar', function (event, offsets) {
model.set('offsets', offsets);
});
model.on('change:orientation', function (model, orientation) {
$(document).trigger('drupalToolbarOrientationChange', orientation);
}).on('change:activeTab', function (model, tab) {
$(document).trigger('drupalToolbarTabChange', tab);
}).on('change:activeTray', function (model, tray) {
$(document).trigger('drupalToolbarTrayChange', tray);
});
if (Drupal.toolbar.models.toolbarModel.get('orientation') === 'horizontal' && Drupal.toolbar.models.toolbarModel.get('activeTab') === null) {
Drupal.toolbar.models.toolbarModel.set({
activeTab: $('.toolbar-bar .toolbar-tab:not(.home-toolbar-tab) a').get(0)
});
}
$(window).on({
'dialog:aftercreate': function dialogAftercreate(event, dialog, $element, settings) {
var $toolbar = $('#toolbar-bar');
$toolbar.css('margin-top', '0');
if (settings.drupalOffCanvasPosition === 'top') {
var height = Drupal.offCanvas.getContainer($element).outerHeight();
$toolbar.css('margin-top', height + 'px');
$element.on('dialogContentResize.off-canvas', function () {
var newHeight = Drupal.offCanvas.getContainer($element).outerHeight();
$toolbar.css('margin-top', newHeight + 'px');
});
}
},
'dialog:beforeclose': function dialogBeforeclose() {
$('#toolbar-bar').css('margin-top', '0');
}
});
});
}
};
Drupal.toolbar = {
views: {},
models: {},
mql: {},
setSubtrees: new $.Deferred(),
mediaQueryChangeHandler: function mediaQueryChangeHandler(model, label, mql) {
switch (label) {
case 'toolbar.narrow':
model.set({
isOriented: mql.matches,
isTrayToggleVisible: false
});
if (!mql.matches || !model.get('orientation')) {
model.set({ orientation: 'vertical' }, { validate: true });
}
break;
case 'toolbar.standard':
model.set({
isFixed: mql.matches
});
break;
case 'toolbar.wide':
model.set({
orientation: mql.matches && !model.get('locked') ? 'horizontal' : 'vertical'
}, { validate: true });
model.set({
isTrayToggleVisible: mql.matches
});
break;
default:
break;
}
}
};
Drupal.theme.toolbarOrientationToggle = function () {
return '<div class="toolbar-toggle-orientation"><div class="toolbar-lining">' + '<button class="toolbar-icon" type="button"></button>' + '</div></div>';
};
Drupal.AjaxCommands.prototype.setToolbarSubtrees = function (ajax, response, status) {
Drupal.toolbar.setSubtrees.resolve(response.subtrees);
};
})(jQuery, Drupal, drupalSettings);
|
// http://dropthebit.com
// 2011
// By - Yair Even-Or
// tip: use chars from here - http://copypastecharacter.com/
|
import React, {Component} from 'react';
import { CSSTransition, TransitionGroup } from 'react-transition-group';
import { Input } from '../bootstrap';
import TaggedInput from '../TaggedInput';
import { Link } from 'react-router';
import { Time } from '../Time';
const Fade = ({ children, ...props }) => (
<CSSTransition
{...props}
timeout={{
enter: 300,
exit: 500,
}}
classNames="fade"
>
{children}
</CSSTransition>
);
/**
* The UserForm Component displays a user and allows to edit the user data.
*/
export class UserForm extends Component {
constructor (props) {
super(props);
this.addRole = this.addRole.bind(this);
this.handleChange = this.handleChange.bind(this);
this.handleRoleChange = this.handleRoleChange.bind(this);
this.handleResetUserPasswordManually = this.handleResetUserPasswordManually.bind(this);
this.state = UserForm.getInitialState();
}
addRole(e) {
e.preventDefault();
const role = e.target.getAttribute('data-role');
// User has already this role
if (this.props.user.roles.includes(role)) {
return;
}
this.handleRoleChange(role, this.props.user.roles.concat(role));
}
/**
* Update changes to the user role. We need a custom handler for
* the TaggedInput Component.
*/
handleRoleChange (role, roles) {
const update = {
isDirty: true,
roles: roles
};
// trigger state update
this.props.onChange(update);
}
handleUnblock (event) {
event.preventDefault();
this.props.unblockUser(this.props.user);
}
/**
* Handles all input changes and triggers a redux state change using the onChange handler
* from the parent.
*/
handleChange (event) {
let value;
const update = {
isDirty: true
};
switch (event.target.type) {
case 'checkbox':
value = event.target.checked;
break;
default:
value = event.target.value;
}
// nested data structures are special cases
if (event.target.name.startsWith('verification')) {
const verificationValue = this.props.user.verification;
switch (event.target.name) {
case 'verification.isCompleted':
verificationValue.isCompleted = value;
break;
case 'verification.token':
verificationValue.token = value;
break;
}
update.verification = verificationValue;
} else {
// normal attributes
update[event.target.name] = value;
}
// trigger state update
this.props.onChange(update);
}
/**
* Saves the user.
*/
handleSave (event) {
event.preventDefault();
this.props.save(this.props.user);
}
handleDelete (event) {
event.preventDefault();
this.setState({
showConfirmDelete: true
});
}
handleDeleteConfirm (event) {
event.preventDefault();
this.props.delete(this.props.user);
this.setState({
showConfirmDelete: false
});
}
handleDeleteDismiss (event) {
event.preventDefault();
this.setState({
showConfirmDelete: false
});
}
handleResendConfirmationEmail (event) {
event.preventDefault();
this.props.resendConfirmationEmail(this.props.user);
}
handleResetUserPasswordManually (event) {
event.preventDefault();
this.props.resetUserPasswordManually(this.props.user);
}
handleConfirmUser (event) {
event.preventDefault();
this.props.confirmUser(this.props.user);
}
handleSendMail (event) {
// ToDo: push state
this.props.changeMailData({
email: this.props.user.email,
subject: '',
message: ''
});
}
/**
* Renders the confirm dialog when a user should be deleted
*/
renderConfirmDelete () {
return (
<TransitionGroup className="form-footer">
<Fade>
<div className="form-inline">
<p className="form-control-plaintext">Soll der Benutzer wirklich gelöscht werden?</p>
<button onClick={this.handleDeleteConfirm.bind(this)} className="btn btn-danger btn-sm">Ja</button>
<button onClick={this.handleDeleteDismiss.bind(this)} className="btn btn-secondary btn-sm">Nein</button>
</div>
</Fade>
</TransitionGroup>
);
}
/**
* Renders the Save and Delete Buttons
*/
renderFormButtons (isDirty) {
return (
<div className="form-footer">
<button type="submit" onClick={this.handleSave.bind(this)} disabled={!isDirty} className="btn btn-success btn-sm">Speichern</button>
<button type="submit" onClick={this.handleDelete.bind(this)} className="btn btn-danger btn-sm">Löschen</button>
<button type="submit" onClick={this.handleResendConfirmationEmail.bind(this)} className="btn btn-warning btn-sm">Aktivierungs-E-Mail erneut schicken</button>
<button type="submit" onClick={this.handleUnblock.bind(this)} className="btn btn-secondary btn-sm" title="Setzt die Anmeldesperre zurück, sodass sich der Benutzer wieder anmelden kann.">Anmeldung wieder erlauben</button>
<button type="submit" onClick={this.handleResetUserPasswordManually} className="btn btn-secondary btn-sm" title="Setzt ein neues Passwort und schickt dieses in einer E-Mail dem Benutzer zu.">Neues Passwort zuschicken</button>
<button type="submit" onClick={this.handleConfirmUser.bind(this)} className="btn btn-secondary btn-sm" title="Schaltet den Benutzer frei, ohne das dieser den Aktivierungslink anklicken muss.">Benutzer freischalten</button>
<Link to="/admin/mail" onClick={this.handleSendMail.bind(this)} className="btn btn-info btn-sm" title="Neue E-Mail an den Benutzer schicken">Mail schicken</Link>
</div>
);
}
renderForm () {
const isDirty = this.props.user.isDirty === true;
const deleteContent = this.state.showConfirmDelete ? this.renderConfirmDelete() : null;
const formButtons = this.state.showConfirmDelete ? null : this.renderFormButtons(isDirty);
return (
<form>
<div className="form-group">
<label>Interne ID</label>
<p className="form-control-static"><strong>{this.props.user.id}</strong></p>
<small className="text-muted">Eindeutige interne ID des Benutzers. Diese wird für die interne Datenhaltung verwendet.</small>
</div>
<Input onChange={this.handleChange} name="email" type="text" label="E-Mail-Adresse" muted="Vorsicht: Benutzer werden anhand ihrer E-Mail-Adresse identifiziert. Diese muss eindeutig sein." value={this.props.user.email} />
<Input onChange={this.handleChange} name="username" type="text" label="Benutzername" muted="Dieser wird aus der E-Mail-Adresse automatisch generiert." value={this.props.user.username} />
<Input onChange={this.handleChange} name="isActive" type="checkbox" label="Aktiviert: Hiermit könnten Benutzer aktiviert und deaktiviert werden." checked={this.props.user.isActive} />
<Input onChange={this.handleChange} name="semester" type="text" label="Semester" muted="Semester in dem sich der Benutzer registriert hat." value={this.props.user.semester} />
<Input onChange={this.handleChange} name="createdAt" type="text" label="Erstellt am" readOnly="readonly" value={this.props.user.createdAt} /> <span><Time value={this.props.user.createdAt} locale="de" relative={true} invalidDateString="kein Datum"/></span>
<Input onChange={this.handleChange} name="verification.isCompleted" type="checkbox" label="Registrierung abgeschlossen" checked={this.props.user.verification.isCompleted} />
<Input onChange={this.handleChange} name="verification.token" muted="Mit diesem Token kann der Benutzer den Account aktivieren." disabled type="text" label="Aktivierungs-Token" value={this.props.user.verification.token || ''} />
<div className="form-group">
<label>Rollen</label>
<TaggedInput onAddTag={this.handleRoleChange} onRemoveTag={this.handleRoleChange} name="roles" placeholder="Benutzerrollen" tags={this.props.user.roles} />
<small className="text-muted">Hier können die Benutzerrollen verändert werden. Diese entscheiden über die Zugriffsrechte auf der Seite.</small>
</div>
<div className="form-group">
<button className="btn btn-info btn-sm" onClick={this.addRole} data-role="admin">Admin</button>
<button className="btn btn-info btn-sm" onClick={this.addRole} data-role="author">Autor (Darf Beispiele und Dokumente anlegen)</button>
<small className="text-muted">Klicken Sie auf einen der Buttons um dem Nutzer die Rolle zuzuweisen.</small>
</div>
{formButtons}
{deleteContent}
</form>
);
}
render () {
const form = this.renderForm();
return form;
}
}
UserForm.getInitialState = function getInitialState() {
return {
showConfirmDelete: false
};
};
|
import React, { Fragment } from 'react';
import { Image, Transformation } from 'cloudinary-react';
import { Helmet } from 'react-helmet';
export default () => {
const compass =
'https://res.cloudinary.com/worksfair/image/upload/v1564834329/dev/qvwvfuxg6040ppipkanj.png';
return (
<Fragment>
<Helmet>
<title>Not Found - Worksfair</title>
</Helmet>
<div
className="hero is-large has-background-light"
>
<div
className="hero-body"
style={{ padding: '50px' }}
>
<div className="container columns">
<div className="column is-1" />
<div className="column is-7">
<h1
style={{ fontSize: '70px', marginTop: '20px' }}
className="has-text-extra-large"
>
404
</h1>
<p
style={{ fontSize: '30px', marginTop: '15px' }}
className="has-text-large"
>
We are sorry about this.
</p>
<p
style={{ fontSize: '20px', marginTop: '15px' }}
className="is-size-5"
>
The website you are looking for is not here.
</p>
<p
className="margin-top-25"
style={{ marginTop: '20px' }}
>
<a
href="http://www.worksfair.com"
className="button is-info is-medium"
>
Go to worksfair
</a>
</p>
</div>
<div className="column is-3 has-text-extra-large">
<Image
cloudName="worksfair"
publicId={compass}
type="fetch"
className="work-image"
>
<Transformation width="700" fetchFormat="auto" />
</Image>
</div>
</div>
</div>
</div>
</Fragment>
);
};
|
import React from 'react';
import { Link } from 'react-router-dom';
import styles from './index.module.scss';
function NavigationItem(props) {
return (
<li className={styles.item}>
<Link className={styles.link} to={props.link}>{props.children}</Link>
</li>
)
}
export default NavigationItem;
|
'use strict';
// Do this as the first thing so that any code reading it knows the right env.
process.env.BABEL_ENV = 'production';
process.env.NODE_ENV = 'production';
// Makes the script crash on unhandled rejections instead of silently
// ignoring them. In the future, promise rejections that are not handled will
// terminate the Node.js process with a non-zero exit code.
process.on('unhandledRejection', (err) => {
throw err;
});
// Ensure environment variables are read.
require('../config/env');
const path = require('path');
const chalk = require('chalk');
const fs = require('fs-extra');
const webpack = require('webpack');
const config = require('../config/webpack.config.prod');
const paths = require('../config/paths');
const checkRequiredFiles = require('react-dev-utils/checkRequiredFiles');
const formatWebpackMessages = require('react-dev-utils/formatWebpackMessages');
const printHostingInstructions = require('react-dev-utils/printHostingInstructions');
const FileSizeReporter = require('react-dev-utils/FileSizeReporter');
const printBuildError = require('react-dev-utils/printBuildError');
const measureFileSizesBeforeBuild = FileSizeReporter.measureFileSizesBeforeBuild;
const printFileSizesAfterBuild = FileSizeReporter.printFileSizesAfterBuild;
const useYarn = fs.existsSync(paths.yarnLockFile);
// These sizes are pretty large. We'll warn for bundles exceeding them.
const WARN_AFTER_BUNDLE_GZIP_SIZE = 512 * 1024;
const WARN_AFTER_CHUNK_GZIP_SIZE = 1024 * 1024;
// Warn and crash if required files are missing
if (!checkRequiredFiles([paths.appHtml, paths.appIndexJs])) {
process.exit(1);
}
// First, read the current file sizes in build directory.
// This lets us display how much they changed later.
measureFileSizesBeforeBuild(paths.appBuild)
.then((previousFileSizes) => {
// Remove all content but keep the directory so that
// if you're in it, you don't end up in Trash
fs.emptyDirSync(paths.appBuild);
// Merge with the public folder
copyPublicFolder();
// Start the webpack build
return build(previousFileSizes);
})
.then(
({stats, previousFileSizes, warnings}) => {
if (warnings.length) {
console.log(chalk.yellow('Compiled with warnings.\n'));
console.log(warnings.join('\n\n'));
console.log(
'\nSearch for the ' +
chalk.underline(chalk.yellow('keywords')) +
' to learn more about each warning.'
);
console.log(
'To ignore, add ' + chalk.cyan('// eslint-disable-next-line') + ' to the line before.\n'
);
} else {
console.log(chalk.green('Compiled successfully.\n'));
}
console.log('File sizes after gzip:\n');
printFileSizesAfterBuild(
stats,
previousFileSizes,
paths.appBuild,
WARN_AFTER_BUNDLE_GZIP_SIZE,
WARN_AFTER_CHUNK_GZIP_SIZE
);
console.log();
const appPackage = require(paths.appPackageJson);
const publicUrl = paths.publicUrl;
const publicPath = config.output.publicPath;
const buildFolder = path.relative(process.cwd(), paths.appBuild);
printHostingInstructions(appPackage, publicUrl, publicPath, buildFolder, useYarn);
},
(err) => {
console.log(chalk.red('Failed to compile.\n'));
printBuildError(err);
process.exit(1);
}
);
// Create the production build and print the deployment instructions.
function build(previousFileSizes) {
console.log('Creating an optimized production build...');
let compiler = webpack(config);
return new Promise((resolve, reject) => {
compiler.run((err, stats) => {
if (err) {
return reject(err);
}
const messages = formatWebpackMessages(stats.toJson({}, true));
if (messages.errors.length) {
// Only keep the first error. Others are often indicative
// of the same problem, but confuse the reader with noise.
if (messages.errors.length > 1) {
messages.errors.length = 1;
}
return reject(new Error(messages.errors.join('\n\n')));
}
if (
process.env.CI &&
(typeof process.env.CI !== 'string' || process.env.CI.toLowerCase() !== 'false') &&
messages.warnings.length
) {
console.log(
chalk.yellow(
'\nTreating warnings as errors because process.env.CI = true.\n' +
'Most CI servers set it automatically.\n'
)
);
return reject(new Error(messages.warnings.join('\n\n')));
}
return resolve({
stats,
previousFileSizes,
warnings: messages.warnings,
});
});
});
}
function copyPublicFolder() {
fs.copySync(paths.appPublic, paths.appBuild, {
dereference: true,
filter: (file) => file !== paths.appHtml,
});
}
|
const Category = {
department(parent, args, { knex }, info) {
console.log('FROM RESOLVER - CATEGORY/ DEPARTMENT');
return knex('departments')
.returning('*')
.where('id', parent.department_id)
.then(result => result[0]);
},
products(parent, args, { knex }, info) {
console.log('FROM RESOLVER - CATEGORY/ PRODUCTS');
return (
knex('products')
.select('*')
//.where('category_id', `${parent.id}`);
.where({ category_id: `${parent.id}`, store_id: 1 })
);
}
};
module.exports = Category;
|
var mysql = require('mysql');
var express = require('express');
var app = express();
//
// var bodyParser = require('body-parser');
// app.use(bodyParser);
var port = 8083;
var con = mysql.createConnection({
host: "mysql",
user: "root",
password: "123456",
port: ''
});
// con.connect(function(err) {
// if (err) throw err;
// console.log("Connected!");
//
//
// con.query("CREATE DATABASE guessappdb", function (err, result) {
// if (err) throw err;
// console.log("Database created");
// });
//
// con.query("CREATE TABLE attempts (min INT(255), max INT(255), attempts_left INT(255), number_to_guess INT(255), player_guess INT(255))", function (err, result) {
// if (err) throw err;
// console.log("Table created");
// });
//
// });
app.use(express.static('dist'));
app.get('/', function (req, res) {
res.sendFile('index.html');
});
//
// app.post('/api/guess', function (req, res) {
//
// var min = parseInt(req.body.min, 10);
// var max = parseInt(req.body.max, 10);
// var attempts_left = parseInt(req.body.attempts_left, 10);
// var number_to_guess = parseInt(req.body.number_to_guess, 10);
// var player_guess = parseInt(req.body.player_guess, 10);
//
// con.query("INSERT INTO attempts (min, max, attempts_left, number_to_guess, player_guess) VALUES (" + min + ", " + max + ", " + attempts_left + ", " + number_to_guess + ", " + player_guess + ",)", function (err, result) {
// if (err) throw err;
// console.log("Logged");
// });
//
// console.log('here?');
// return res.json({success: true});
// });
app.listen(port, function () {
console.log('server started at', port);
});
|
import React from 'react';
import Button from '@material-ui/core/Button';
function SimpleCard() {
return (
<div className="jr-card">
<h4 className="text-muted">Word of the Day</h4>
<h3 className="card-title my-2">be-nev-o-lent</h3>
<div className="text-muted mb-3">adjective</div>
<p className="h4 text-muted">
Well meaning and kindly
“a benevolent smile”
</p>
<Button size="small" color="primary">Learn More</Button>
</div>
);
}
export default SimpleCard;
|
var a1_0x29bc=['nets','ssdMobilenetv1','SsdMobilenetv1Options','TinyFaceDetectorOptions','MtcnnOptions','faceDetectionOptions','__esModule','call','default','defineProperty','faceDetectionNet'];(function(_0x3c89f9,_0x3f89f1){var _0x41b5ff=function(_0xff9ae8){while(--_0xff9ae8){_0x3c89f9['push'](_0x3c89f9['shift']());}};_0x41b5ff(++_0x3f89f1);}(a1_0x29bc,0x1c9));var a1_0x1c61=function(_0x155e59,_0x185a42){_0x155e59=_0x155e59-0x0;var _0x811d77=a1_0x29bc[_0x155e59];return _0x811d77;};'use strict';var __importStar=this&&this['__importStar']||function(_0x40dbb3){if(_0x40dbb3&&_0x40dbb3[a1_0x1c61('0x0')])return _0x40dbb3;var _0x2ad816={};if(_0x40dbb3!=null)for(var _0x50b8a6 in _0x40dbb3)if(Object['hasOwnProperty'][a1_0x1c61('0x1')](_0x40dbb3,_0x50b8a6))_0x2ad816[_0x50b8a6]=_0x40dbb3[_0x50b8a6];_0x2ad816[a1_0x1c61('0x2')]=_0x40dbb3;return _0x2ad816;};Object[a1_0x1c61('0x3')](exports,'__esModule',{'value':!![]});const faceapi=__importStar(require('face-api.js'));exports[a1_0x1c61('0x4')]=faceapi[a1_0x1c61('0x5')][a1_0x1c61('0x6')];const minConfidence=0.5;const inputSize=0x198;const scoreThreshold=0.5;const minFaceSize=0x32;const scaleFactor=0.8;function getFaceDetectorOptions(_0x540799){return _0x540799===faceapi[a1_0x1c61('0x5')][a1_0x1c61('0x6')]?new faceapi[(a1_0x1c61('0x7'))]({'minConfidence':minConfidence}):_0x540799===faceapi['nets']['tinyFaceDetector']?new faceapi[(a1_0x1c61('0x8'))]({'inputSize':inputSize,'scoreThreshold':scoreThreshold}):new faceapi[(a1_0x1c61('0x9'))]({'minFaceSize':minFaceSize,'scaleFactor':scaleFactor});}exports[a1_0x1c61('0xa')]=getFaceDetectorOptions(exports[a1_0x1c61('0x4')]);
|
(window.webpackJsonp=window.webpackJsonp||[]).push([[19],{k0NY:function(l,n,u){"use strict";u.r(n);var t=u("CcnG"),e=u("mrSG"),i=u("Ie7a"),o=function(){function l(l){this.musicService=l,this.searchTerm="",this.searching=!1}return l.prototype.setFilteredItems=function(){return e.b(this,void 0,void 0,function(){var l;return e.e(this,function(n){switch(n.label){case 0:return this.searching=!0,this.searchTerm?[4,this.musicService.searchTracks(this.searchTerm)]:[3,2];case 1:return l=n.sent(),this.items=l.tracks.items.filter(function(l){return l.preview_url}),[3,3];case 2:this.items=[],n.label=3;case 3:return this.searching=!1,[2]}})})},l.prototype.play=function(l){console.log(l),this.audioSong&&this.audioSong.pause();var n=this.items.filter(function(l){return l.playing});n[0]&&(n[0].playing=!1),l.playing=!0,this.audioSong=new Audio(l.preview_url),this.audioSong.play()},l.prototype.pause=function(l){this.audioSong.pause(),l.playing=!1},l}(),a=function(){return function(){}}(),r=u("pMnS"),b=u("oBZk"),s=u("ZZ/e"),c=u("Ip0R"),p=u("gIcY"),h=t.sb({encapsulation:0,styles:[[""]],data:{}});function g(l){return t.Lb(0,[(l()(),t.ub(0,0,null,null,2,"div",[["class","spinner-container"],["text-center",""]],null,null,null,null,null)),(l()(),t.ub(1,0,null,null,1,"ion-spinner",[],null,null,null,b.cb,b.x)),t.tb(2,49152,null,0,s.ob,[t.h,t.k,t.z],null,null)],null,null)}function m(l){return t.Lb(0,[(l()(),t.ub(0,0,null,null,1,"ion-icon",[["name","play"],["slot","end"]],null,[[null,"click"]],function(l,n,u){var t=!0;return"click"===n&&(t=!1!==l.component.play(l.parent.context.$implicit)&&t),t},b.O,b.j)),t.tb(1,49152,null,0,s.z,[t.h,t.k,t.z],{name:[0,"name"]},null)],function(l,n){l(n,1,0,"play")},null)}function d(l){return t.Lb(0,[(l()(),t.ub(0,0,null,null,1,"ion-icon",[["name","pause"],["slot","end"]],null,[[null,"click"]],function(l,n,u){var t=!0;return"click"===n&&(t=!1!==l.component.pause(l.parent.context.$implicit)&&t),t},b.O,b.j)),t.tb(1,49152,null,0,s.z,[t.h,t.k,t.z],{name:[0,"name"]},null)],function(l,n){l(n,1,0,"pause")},null)}function f(l){return t.Lb(0,[(l()(),t.ub(0,0,null,null,1,"ion-spinner",[["name","dots"],["slot","end"]],null,null,null,b.cb,b.x)),t.tb(1,49152,null,0,s.ob,[t.h,t.k,t.z],{name:[0,"name"]},null)],function(l,n){l(n,1,0,"dots")},null)}function k(l){return t.Lb(0,[(l()(),t.ub(0,0,null,null,8,"ion-item",[],null,null,null,b.Q,b.l)),t.tb(1,49152,null,0,s.E,[t.h,t.k,t.z],null,null),(l()(),t.Kb(2,0,[" "," "])),(l()(),t.jb(16777216,null,0,1,null,m)),t.tb(4,16384,null,0,c.i,[t.P,t.M],{ngIf:[0,"ngIf"]},null),(l()(),t.jb(16777216,null,0,1,null,d)),t.tb(6,16384,null,0,c.i,[t.P,t.M],{ngIf:[0,"ngIf"]},null),(l()(),t.jb(16777216,null,0,1,null,f)),t.tb(8,16384,null,0,c.i,[t.P,t.M],{ngIf:[0,"ngIf"]},null)],function(l,n){l(n,4,0,!n.context.$implicit.playing),l(n,6,0,n.context.$implicit.playing),l(n,8,0,n.context.$implicit.playing)},function(l,n){l(n,2,0,n.context.$implicit.name)})}function I(l){return t.Lb(0,[(l()(),t.ub(0,0,null,null,15,"ion-header",[],null,null,null,b.N,b.i)),t.tb(1,49152,null,0,s.y,[t.h,t.k,t.z],null,null),(l()(),t.ub(2,0,null,0,13,"ion-toolbar",[["text-center",""]],null,null,null,b.ib,b.D)),t.tb(3,49152,null,0,s.yb,[t.h,t.k,t.z],null,null),(l()(),t.ub(4,0,null,0,4,"ion-buttons",[["slot","start"]],null,null,null,b.I,b.d)),t.tb(5,49152,null,0,s.i,[t.h,t.k,t.z],null,null),(l()(),t.ub(6,0,null,0,2,"ion-avatar",[["class","header-avatar"]],null,null,null,b.G,b.b)),t.tb(7,49152,null,0,s.d,[t.h,t.k,t.z],null,null),(l()(),t.ub(8,0,null,0,0,"img",[["alt","User Image"],["src","assets/img/user.jpg"]],null,null,null,null,null)),(l()(),t.ub(9,0,null,0,3,"ion-buttons",[["slot","end"]],null,null,null,b.I,b.d)),t.tb(10,49152,null,0,s.i,[t.h,t.k,t.z],null,null),(l()(),t.ub(11,0,null,0,1,"ion-menu-button",[],null,null,null,b.T,b.p)),t.tb(12,49152,null,0,s.O,[t.h,t.k,t.z],null,null),(l()(),t.ub(13,0,null,0,2,"ion-title",[["text-center",""]],null,null,null,b.hb,b.C)),t.tb(14,49152,null,0,s.wb,[t.h,t.k,t.z],null,null),(l()(),t.ub(15,0,null,0,0,"img",[["alt","Platzi Logo"],["height","32px"],["src","assets/img/logo.png"]],null,null,null,null,null)),(l()(),t.ub(16,0,null,null,17,"ion-content",[["padding",""]],null,null,null,b.K,b.f)),t.tb(17,49152,null,0,s.r,[t.h,t.k,t.z],null,null),(l()(),t.ub(18,0,null,0,6,"ion-searchbar",[],[[2,"ng-untouched",null],[2,"ng-touched",null],[2,"ng-pristine",null],[2,"ng-dirty",null],[2,"ng-valid",null],[2,"ng-invalid",null],[2,"ng-pending",null]],[[null,"ngModelChange"],[null,"ionChange"],[null,"ionBlur"]],function(l,n,u){var e=!0,i=l.component;return"ionBlur"===n&&(e=!1!==t.Gb(l,19)._handleBlurEvent(u.target)&&e),"ionChange"===n&&(e=!1!==t.Gb(l,19)._handleInputEvent(u.target)&&e),"ngModelChange"===n&&(e=!1!==(i.searchTerm=u)&&e),"ionChange"===n&&(e=!1!==i.setFilteredItems()&&e),e},b.Y,b.t)),t.tb(19,16384,null,0,s.Kb,[t.k],null,null),t.Hb(1024,null,p.h,function(l){return[l]},[s.Kb]),t.tb(21,671744,null,0,p.l,[[8,null],[8,null],[8,null],[6,p.h]],{model:[0,"model"]},{update:"ngModelChange"}),t.Hb(2048,null,p.i,null,[p.l]),t.tb(23,16384,null,0,p.j,[[4,p.i]],null,null),t.tb(24,49152,null,0,s.gb,[t.h,t.k,t.z],null,null),(l()(),t.jb(16777216,null,0,1,null,g)),t.tb(26,16384,null,0,c.i,[t.P,t.M],{ngIf:[0,"ngIf"]},null),(l()(),t.ub(27,0,null,0,6,"ion-virtual-scroll",[["approxItemHeight","50px"]],null,null,null,b.jb,b.E)),t.tb(28,835584,null,3,s.zb,[t.z,t.s,t.k],{approxItemHeight:[0,"approxItemHeight"],items:[1,"items"]},null),t.Ib(335544320,1,{itmTmp:0}),t.Ib(335544320,2,{hdrTmp:0}),t.Ib(335544320,3,{ftrTmp:0}),(l()(),t.jb(16777216,null,0,1,null,k)),t.tb(33,16384,[[1,4]],0,s.Lb,[t.M,t.P],null,null)],function(l,n){var u=n.component;l(n,21,0,u.searchTerm),l(n,26,0,u.searching),l(n,28,0,"50px",u.items)},function(l,n){l(n,18,0,t.Gb(n,23).ngClassUntouched,t.Gb(n,23).ngClassTouched,t.Gb(n,23).ngClassPristine,t.Gb(n,23).ngClassDirty,t.Gb(n,23).ngClassValid,t.Gb(n,23).ngClassInvalid,t.Gb(n,23).ngClassPending)})}function v(l){return t.Lb(0,[(l()(),t.ub(0,0,null,null,1,"app-search",[],null,null,null,I,h)),t.tb(1,49152,null,0,o,[i.a],null,null)],null,null)}var y=t.qb("app-search",o,v,{},{},[]),z=u("ZYCi");u.d(n,"SearchPageModuleNgFactory",function(){return E});var E=t.rb(a,[],function(l){return t.Db([t.Eb(512,t.j,t.cb,[[8,[r.a,y]],[3,t.j],t.x]),t.Eb(4608,c.k,c.j,[t.u,[2,c.q]]),t.Eb(4608,p.q,p.q,[]),t.Eb(4608,s.a,s.a,[t.z,t.g]),t.Eb(4608,s.Eb,s.Eb,[s.a,t.j,t.q]),t.Eb(4608,s.Ib,s.Ib,[s.a,t.j,t.q]),t.Eb(1073742336,c.b,c.b,[]),t.Eb(1073742336,p.p,p.p,[]),t.Eb(1073742336,p.f,p.f,[]),t.Eb(1073742336,s.Ab,s.Ab,[]),t.Eb(1073742336,z.o,z.o,[[2,z.t],[2,z.m]]),t.Eb(1073742336,a,a,[]),t.Eb(1024,z.k,function(){return[[{path:"",component:o}]]},[])])})}}]);
|
'use strict'
const path = require('path')
const defaultSettings = require('./src/settings.js')
function resolve(dir) {
return path.join(__dirname, dir)
}
const name = defaultSettings.title || '管理系统' // 标题
const port = process.env.port || process.env.npm_config_port || 80 // 端口
// vue.config.js 配置说明
//官方vue.config.js 参考文档 https://cli.vuejs.org/zh/config/#css-loaderoptions
// 这里只列一部分,具体配置参考文档
module.exports = {
// 部署生产环境和开发环境下的URL。
// 默认情况下,Vue CLI 会假设你的应用是被部署在一个域名的根路径上
// 例如 https://www.ruoyi.vip/。如果应用被部署在一个子路径上,你就需要用这个选项指定这个子路径。例如,如果你的应用被部署在 https://www.ruoyi.vip/admin/,则设置 baseUrl 为 /admin/。
publicPath: process.env.NODE_ENV === "production" ? "/" : "/",
// 在npm run build 或 yarn build 时 ,生成文件的目录名称(要和baseUrl的生产环境路径一致)(默认dist)
outputDir: 'dist',
// 用于放置生成的静态资源 (js、css、img、fonts) 的;(项目打包之后,静态资源会放在这个文件夹下)
assetsDir: 'static',
// 是否开启eslint保存检测,有效值:ture | false | 'error'
lintOnSave: process.env.NODE_ENV === 'development',
// 如果你不需要生产环境的 source map,可以将其设置为 false 以加速生产环境构建。
productionSourceMap: false,
// webpack-dev-server 相关配置
devServer: {
host: '0.0.0.0',
port: port,
proxy: {
// detail: https://cli.vuejs.org/config/#devserver-proxy
[process.env.VUE_APP_BASE_API]: {
target: `http://localhost:8080`,
changeOrigin: true,
pathRewrite: {
['^' + process.env.VUE_APP_BASE_API]: ''
}
}
},
disableHostCheck: true
},
configureWebpack: {
name: name,
resolve: {
alias: {
'@': resolve('src')
}
}
},
chainWebpack(config) {
config.plugins.delete('preload') // TODO: need test
config.plugins.delete('prefetch') // TODO: need test
// set svg-sprite-loader
config.module
.rule('svg')
.exclude.add(resolve('src/assets/icons'))
.end()
config.module
.rule('icons')
.test(/\.svg$/)
.include.add(resolve('src/assets/icons'))
.end()
.use('svg-sprite-loader')
.loader('svg-sprite-loader')
.options({
symbolId: 'icon-[name]'
})
.end()
// set preserveWhitespace
config.module
.rule('vue')
.use('vue-loader')
.loader('vue-loader')
.tap(options => {
options.compilerOptions.preserveWhitespace = true
return options
})
.end()
config
.when(process.env.NODE_ENV !== 'development',
config => {
config
.plugin('ScriptExtHtmlWebpackPlugin')
.after('html')
.use('script-ext-html-webpack-plugin', [{
// `runtime` must same as runtimeChunk name. default is `runtime`
inline: /runtime\..*\.js$/
}])
.end()
config
.optimization.splitChunks({
chunks: 'all',
cacheGroups: {
libs: {
name: 'chunk-libs',
test: /[\\/]node_modules[\\/]/,
priority: 10,
chunks: 'initial' // only package third parties that are initially dependent
},
elementUI: {
name: 'chunk-elementUI', // split elementUI into a single package
priority: 20, // the weight needs to be larger than libs and app or it will be packaged into libs or app
test: /[\\/]node_modules[\\/]_?element-ui(.*)/ // in order to adapt to cnpm
},
commons: {
name: 'chunk-commons',
test: resolve('src/components'), // can customize your rules
minChunks: 3, // minimum common number
priority: 5,
reuseExistingChunk: true
}
}
})
config.optimization.runtimeChunk('single'),
{
from: path.resolve(__dirname, './public/robots.txt'),//防爬虫文件
to:'./',//到根目录下
}
}
)
}
}
|
var mainElement = document.querySelector('main');
var renderers = {};
function createModal() {
var element = document.createElement('div');
element.classList.add('modal');
element.innerHTML = `<div class="body">
<div class="controls">
<button>close</button>
</div>
<div class="content"></div>
</div>
<div class="underlay"></div>`;
return element;
}
function showModal(contentElement) {
modalContentElement.innerHTML = '';
modalContentElement.appendChild(contentElement);
modalElement.classList.add('open');
}
function hideModal() {
modalElement.classList.remove('open');
}
// you can copy that safely, just pay attention to where it has to be paste
var modalElement = createModal();
var modalContentElement = modalElement.querySelector('.content');
var modalCloseButton = modalElement.querySelector('.controls button');
modalCloseButton.addEventListener('click', hideModal);
document.body.appendChild(modalElement);
function loadData(url, done) {
var xhr = new XMLHttpRequest();
xhr.onload = function() {
var response = JSON.parse(xhr.responseText);
done(response);
};
xhr.open('get', url);
xhr.send();
}
function loadPeople(done) {
loadData('https://swapi.co/api/people', done);
}
function loadPlanet(url, done) {
loadData(url, done);
}
function renderPeople(people) {
mainElement.textContent = '';
var navElement = document.createElement('nav');
var cardsElement = document.createElement('div');
cardsElement.classList.add('cards');
if (people.previous) {
var previousButton = document.createElement('button');
previousButton.classList.add('previous');
previousButton.textContent = 'previous';
previousButton.addEventListener('click', function() {
loadData(people.previous, renderPeople);
});
navElement.appendChild(previousButton);
}
if (people.next) {
var nextButton = document.createElement('button');
nextButton.classList.add('next');
nextButton.textContent = 'next';
nextButton.addEventListener('click', function() {
loadData(people.next, renderPeople);
});
navElement.appendChild(nextButton);
}
mainElement.appendChild(navElement);
mainElement.appendChild(cardsElement);
people.results.forEach(function(person) {
var sectionElement = document.createElement('section');
sectionElement.classList.add('person');
var genderSymbol;
switch (person.gender) {
case 'male':
genderSymbol = '♂';
break;
case 'female':
genderSymbol = '♀';
break;
default:
genderSymbol = '?';
}
sectionElement.innerHTML = `
<header>
<h1>
${person.name}
<span class="gender" title="Gender: ${person.gender}">${genderSymbol}</span>
<button class="button">GIMME THE HOMEWORLD DIGGA</button>
</h1>
</header>
<div>
<ul>
<li>
<span class="label">Birth Year:</span>
<span class="value">${person.birth_year}</span>
</li>
<li>
<span class="label">Eye Color:</span>
<span class="value">${person.eye_color}</span>
</li>
<li>
<span class="label">Skin Color:</span>
<span class="value">${person.skin_color}</span>
</li>
<li>
<span class="label">Hair Color:</span>
<span class="value">${person.hair_color}</span>
</li>
<li>
<span class="label">Height:</span>
<span class="value">${(person.height / 100).toFixed(2)}m</span>
</li>
<li>
<span class="label">Mass:</span>
<span class="value">${person.mass}kg</span>
</li>
</ul>
</div>
`;
sectionElement
.querySelector('button')
.addEventListener('click', function() {
loadPlanet(person.homeworld, renderPlanet);
});
cardsElement.appendChild(sectionElement);
});
}
renderers.people = renderPeople;
function renderPlanets(planets) {
mainElement.textContent = '';
var navElement = document.createElement('nav');
var cardsElement = document.createElement('div');
cardsElement.classList.add('cards');
if (planets.previous) {
var previousButton = document.createElement('button');
previousButton.classList.add('previous');
previousButton.textContent = 'previous';
previousButton.addEventListener('click', function() {
loadData(planets.previous, renderPlanets);
});
navElement.appendChild(previousButton);
}
if (planets.next) {
var nextButton = document.createElement('button');
nextButton.classList.add('next');
nextButton.textContent = 'next';
nextButton.addEventListener('click', function() {
loadData(planets.next, renderPlanets);
});
navElement.appendChild(nextButton);
}
mainElement.appendChild(navElement);
mainElement.appendChild(cardsElement);
planets.results.forEach(function(object) {
var sectionElement = document.createElement('section');
sectionElement.innerHTML = `
<header>
<h1>
${object.name}
</h1>
</header>
<div>
<ul>
</ul>
</div>
`;
cardsElement.appendChild(sectionElement);
});
}
renderers.planets = renderPlanets;
function renderPlanet(planet) {
var sectionElement = document.createElement('section');
sectionElement.classList.add('planet');
sectionElement.innerHTML = `<header>
<h1>${planet.name}</h1>
</header>
<div>
<ul>
<li>
<span class="label">Climate:</span>
<span class="value">${planet.climate}</span>
</li>
<li>
<span class="label">Diameter:</span>
<span class="value">${planet.diameter}</span>
</li>
<li>
<span class="label">Gravity:</span>
<span class="value">${planet.gravity}</span>
</li>
<li>
<span class="label">Orbital Period:</span>
<span class="value">${planet.orbital_period}</span>
</li>
</ul>
<ul>
<li>
<span class="label">Population:</span>
<span class="value">${planet.population}</span>
</li>
<li>
<span class="label">Rotation Period:</span>
<span class="value">${planet.rotation_period}</span>
</li>
<li>
<span class="label">Surface Water:</span>
<span class="value">${planet.surface_water}</span>
</li>
<li>
<span class="label">Terrain:</span>
<span class="value">${planet.terrain}</span>
</li>
</ul>
</div>`;
showModal(sectionElement);
}
function renderUnimplemented() {
mainElement.textContent = 'Doh! Not done yet';
}
function renderMenu(data) {
var menuListElement = document.querySelector('body > header ul');
var keys = Object.keys(data);
keys.forEach(function(key) {
var liElement = document.createElement('li');
var aElement = document.createElement('a');
aElement.textContent = key;
aElement.addEventListener('click', function() {
if (!renderers[key]) return renderUnimplemented();
loadData(data[key], renderers[key]);
});
liElement.appendChild(aElement);
menuListElement.appendChild(liElement);
});
}
loadPeople(renderPeople);
loadData('https://swapi.co/api/', renderMenu);
function renderspecies(species) {
mainElement.textContent = '';
var navElement = document.createElement('nav');
var cardsElement = document.createElement('div');
cardsElement.classList.add('cards');
if (species.previous) {
var previousButton = document.createElement('button');
previousButton.classList.add('previous');
previousButton.textContent = 'previous';
previousButton.addEventListener('click', function() {
loadData(species.previous, renderspecies);
});
navElement.appendChild(previousButton);
}
if (species.next) {
var nextButton = document.createElement('button');
nextButton.classList.add('next');
nextButton.textContent = 'next';
nextButton.addEventListener('click', function() {
loadData(species.next, renderspecies);
});
navElement.appendChild(nextButton);
}
mainElement.appendChild(navElement);
mainElement.appendChild(cardsElement);
species.results.forEach(function(space) {
var sectionElement = document.createElement('section');
sectionElement.classList.add('space');
sectionElement.innerHTML = `
<header>
<h1>
${space.name}
<button class="button">GIMME THE HOMEWORLD DIGGA</button>
</h1>
</header>
<div>
<ul>
<li>
<span class="label">classification:</span>
<span class="value">${space.classification}</span>
</li>
<li>
<span class="label">Eye Color:</span>
<span class="value">${space.eye_color}</span>
</li>
<li>
<span class="label">Skin Color:</span>
<span class="value">${space.skin_color}</span>
</li>
<li>
<span class="label">Hair Color:</span>
<span class="value">${space.hair_color}</span>
</li>
<li>
<span class="label">Mass:</span>
<span class="value">${space.mass}kg</span>
</li>
</ul>
</div>
`;
cardsElement.appendChild(sectionElement);
});
}
renderers.species= renderspecies;
|
import React from "react";
import ReactDOM from "react-dom";
import '../css/main.scss';
import App from './components/App';
ReactDOM.render(<App/>, document.getElementById('app'));
|
import React, { Component } from 'react';
import { connect } from 'react-redux';
class BookDetail extends Component {
render() {
if (!this.props.book) {
return <div> Select a book to get Started.</div>;
}
return (
<div>
<h3> Details for: </h3>
<div> {this.props.book.title}</div>
</div>
);
}
}
function mapStateToProps(state) {
return {
book: state.activeBook
};
}
export default connect(mapStateToProps)(BookDetail);
|
var express = require("express");
var app = express();
let data={};
const fs = require("fs");
const serverSideStorage = "./db.json";
fs.readFile(serverSideStorage, function(err, buf) {
if (err) {
console.log("error: ", err);
} else {
data = JSON.parse( buf.toString() );
}
console.log("Data read from file.");
});
function saveToServer(data) {
fs.writeFile(serverSideStorage, JSON.stringify(data), function(err, buf) {
if (err) {
console.log("error: ", err);
} else {
console.log("Data saved successfully!");
}
})
}
app.use('/', express.static("public") );
//middleware
// var bodyParser = require("body-parser");
// app.use('/api/', bodyParser.json() );
app.use('/api/', express.json());
//READ ALL
// app.get("/api/", function (req, res) {
// res.send( data );
// res.end();
// });
//CREATE
// app.post("/api/", function (req, res) {
// let name = req.body.name;
// let counter = req.body.count;
// data.push( {"name":name, "count": counter} );
// saveToServer(data)
// res.send( "POST successful!" );
// res.end();
// });
//READ ONE
// app.get("/api/id/:id", function (req, res) {
// let id = parseInt(req.params.id);
// let result = data[id];
// res.send( result );
// res.end();
// }).put("/api/id/:id", function (req, res) {
// let id = parseInt(req.params.id);
// let name = req.body.name;
// let counter = req.body.count;
// data[id] = {"name":name, "count": counter} ;
// saveToServer(data);
// res.send( "PUT successful!" );
// res.end();
// }).delete("/api/id/:id", function (req, res) {
// let id = parseInt(req.params.id);
// data.splice(id,1);
// saveToServer(data);
// res.send( "DELETE successful!" );
// res.end();
// });
app.listen(3000);
|
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const articleSchema = new Schema({
title: { type: String, required: true },
date: { type: Date, required: true},
url: {type: String, required: true}
});
const Article = mongoose.model("Article", articleSchema);
module.exports = Article;
|
const { uniq } = require('lodash');
// eslint-disable-next-line max-len
const flattenDeepObjectIntoArray = (obj, result, getKeys, getValues, maxAllowedDepth, depth = 0) => {
if (typeof obj !== 'object' || obj === null || depth >= maxAllowedDepth) return [];
// eslint-disable-next-line consistent-return
Object.keys(obj).forEach((key) => {
if (getKeys) result.push(key.toString());
if (typeof obj[key] === 'object') {
return flattenDeepObjectIntoArray(obj[key], result, getKeys, getValues, maxAllowedDepth, ++depth);
}
if (getValues) result.push((obj[key] || '').toString());
});
return result;
};
/**
* Return an array of all strings from JSON file.
*/
module.exports = (content, config) => {
let json;
try {
json = JSON.parse(content);
} catch (e) {
return [];
}
return uniq(
flattenDeepObjectIntoArray(json, [], config.checkObjectKeys, config.checkObjectValues, config.maxAllowedDepth)
);
};
|
import compose from './compose'
/**
* 创建一个store增强器,将中间件应用于Redux store的dispatch方法。
* 这对于各种任务很方便,例如以简洁的方式表示异步操作,或者记录每个操作的有效负载。
*
* 请参阅`redux-thunk`软件包作为Redux中间件的示例。
*
* 因为中间件可能是异步的,所以应该是组合链中的第一个store增强器。
*
* 注意,每个中间件将`dispatch`和`getState`方法作为命名参数。
*
* @param {...Function} middlewares 要应用的中间件链。
* @returns {Function} 应用中间件的store增强器。
*/
export default function applyMiddleware(...middlewares) {
return createStore => (...args) => {
const store = createStore(...args)
let dispatch = () => {
throw new Error(
`Dispatching while constructing your middleware is not allowed. ` +
`Other middleware would not be applied to this dispatch.`
)
}
let chain = []
const middlewareAPI = {
getState: store.getState,
dispatch: (...args) => dispatch(...args)
}
chain = middlewares.map(middleware => middleware(middlewareAPI))
dispatch = compose(...chain)(store.dispatch)
return {
...store,
dispatch
}
}
}
|
const path = require('path');
module.exports = {
mode: 'none',
entry: './components/main.js',
output: {
path: path.resolve(__dirname, 'assets/scripts'),
filename: 'main.min.js',
},
module: {
rules: [
{
test: /\.js$/,
loader: 'babel-loader',
exclude: /node_modules/,
options: {
presets: [
'babel-preset-env',
].map(require.resolve)
},
},
],
},
};
|
import { combineReducers } from "redux";
import { exerciseReducer } from "./exerciseReducer";
import { mealReducer } from "./mealReducer";
import { userReducer } from "./userReducer";
export const rootReducer = combineReducers({
exercises: exerciseReducer,
meals: mealReducer,
user: userReducer
})
|
import React, { Component } from 'react';
import {
Button,
Input,
Row,
Col,
Modal,
ModalBody,
Jumbotron
} from 'reactstrap';
import './App.css';
const backendURL = 'http://super-bot.pizza:14000';
class App extends Component {
constructor(props) {
super(props);
this.sendMessage = this.sendMessage.bind(this);
this.timerTask = this.timerTask.bind(this);
this.toggle = this.toggle.bind(this);
this.state = {
data: [],
inputText: '',
col: [],
modal: true,
update: false
};
}
async fetchAsyncJSON(url, requestType) {
try {
let response = await fetch(url, {
credentials: 'include',
method: requestType
});
let data = await response.json();
return data;
} catch (error) {
console.error(error);
}
}
async getMessage(message) {
try {
await this.fetchAsyncJSON(
backendURL + '/chat?message=' + message,
'GET'
).then(response =>
this.setState({
data: response.response.messages
})
);
} catch (error) {
console.error(error);
}
}
timerTask() {
if (this.state.update) {
this.setState({ update: false });
} else {
this.setState({
modal: true,
data: []
});
this.putChat();
}
}
async putChat() {
await this.fetchAsyncJSON(backendURL + '/createChat', 'GET');
}
async componentDidMount() {
await this.putChat();
this.timer = setInterval(this.timerTask, 30000);
}
sendMessage() {
this.setState({ update: true });
this.getMessage(this.state.inputText);
this.setState({ inputText: '' });
}
scrollToBottom = () => {
this.messagesEnd.scrollIntoView({ behavior: 'smooth' });
};
componentDidUpdate() {
this.scrollToBottom();
}
updateInputValue(evt) {
this.setState({ update: true });
this.setState({
inputText: evt.target.value
});
}
toggle() {
this.setState({ update: false });
this.setState({
modal: !this.state.modal
});
}
render() {
return (
<div className="App">
<div>
<Modal size="lg" isOpen={this.state.modal} toggle={this.toggle}>
<ModalBody>
<Jumbotron>
<h1>Super-Bot</h1>
<p>
Super-Bot is an AI based ChatBot developt by AUT Students.
</p>
<p>
The Bot is based on basic technology and does not use any
third-party-services.
</p>
<p>
The project is not finished yet, so there is still a need for
optimization.
</p>
<hr />
<p>
<h3>Created by:</h3>
<ul>
<li>Ashton Ho</li>
<li>Shailendrasinh Vijaysinh Jadeja</li>
<li>Antony Nugroho</li>
<li>Florian Widder</li>
</ul>
</p>
<hr />
<p>
<Button size="lg" color="primary" onClick={this.toggle}>
Try it!
</Button>
</p>
<p>
For optimization we are saving all messages anonymously. You
accept this by using the Bot.
</p>
</Jumbotron>
</ModalBody>
</Modal>
</div>
<Col sm="12" md={{ size: 4, offset: 4 }}>
<Row className="Head">
<Col md={{ size: 6, offset: 3 }}>
<h1 className="Head">Super-Bot</h1>
</Col>
</Row>
{this.state.data.map(function(data, index) {
return (
<div>
<Row>
<p>You: {data.question}</p>
</Row>
<Row>
<p>Bot: {data.answer}</p>
</Row>
</div>
);
})}
<Row>
<Col>
<Input
placeholder="Type here!"
value={this.state.inputText}
onChange={evt => this.updateInputValue(evt)}
onKeyPress={event => {
if (event.key === 'Enter') {
this.sendMessage();
}
}}
/>
</Col>
<Col xs="auto">
<Button color="primary" onClick={this.sendMessage}>
Send
</Button>
</Col>
</Row>
<div
style={{ clear: 'both' }}
ref={el => {
this.messagesEnd = el;
}}
/>
</Col>
</div>
);
}
}
export default App;
|
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var RouteParamtypes;
(function (RouteParamtypes) {
RouteParamtypes[RouteParamtypes["REQUEST"] = 0] = "REQUEST";
RouteParamtypes[RouteParamtypes["RESPONSE"] = 1] = "RESPONSE";
RouteParamtypes[RouteParamtypes["NEXT"] = 2] = "NEXT";
RouteParamtypes[RouteParamtypes["BODY"] = 3] = "BODY";
RouteParamtypes[RouteParamtypes["QUERY"] = 4] = "QUERY";
RouteParamtypes[RouteParamtypes["PARAM"] = 5] = "PARAM";
RouteParamtypes[RouteParamtypes["HEADERS"] = 6] = "HEADERS";
RouteParamtypes[RouteParamtypes["SESSION"] = 7] = "SESSION";
})(RouteParamtypes = exports.RouteParamtypes || (exports.RouteParamtypes = {}));
|
// Copyright 2020 The casbin Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import React from "react";
import { Link } from "react-router-dom";
import * as Setting from "./Setting";
class Avatar extends React.Component {
constructor(props) {
super(props);
this.state = {
classes: props,
};
}
render() {
let style;
if (this.props.size === "small") {
style = { maxWidth: "24px", maxHeight: "24px" };
} else if (this.props.size === "large") {
style = { maxWidth: "73px", maxHeight: "73px" };
} else if (this.props.size === "middle") {
style = { maxWidth: "36px", maxHeight: "36px" };
} else {
style = { maxWidth: "48px", maxHeight: "48px" };
}
let src;
if (this.props.avatar !== "") {
src = this.props.avatar;
} else {
src = Setting.getUserAvatar(this.props.username);
}
return (
<Link to={`/member/${this.props.username}`}>
<img
src={src}
className="avatar"
border="0"
align="default"
style={style}
alt={this.props.username}
key={this.props.key}
/>
</Link>
);
}
}
export default Avatar;
|
import React, {memo, useState} from 'react'
import {NavLink} from 'react-router-dom'
import { Layout, Menu } from 'antd';
import navigation from '../../_nav';
const { Sider } = Layout
export default memo(() => {
const [collapsed, setState] = useState(false);
const toggle = () => {
setState(!collapsed);
};
return (
<Sider trigger={null} collapsible collapsed={collapsed}>
<div className="logo" />
<Menu theme="dark" mode="inline" defaultSelectedKeys={['1']}>
{navigation.items.map(({name, url, icon}, i) => (
<Menu.Item key={i+""} icon={icon}>
<NavLink
to={url}
onClick={e => {}}
>
{name}
</NavLink>
</Menu.Item>
))}
</Menu>
</Sider>
)
})
|
/*
* hash-data
* https://github.com/creativ/grunt-hash-data
*
* Copyright (c) 2013 Dmitriy Tkalich
* Licensed under the MIT license.
*/
'use strict';
module.exports = function(grunt) {
// Project configuration.
grunt.initConfig({
jshint: {
all: [
'Gruntfile.js',
'tasks/*.js',
'<%= nodeunit.tests %>',
],
options: {
jshintrc: '.jshintrc',
},
},
// Before generating any new files, remove any previously-created files.
clean: {
tests: ['tmp'],
},
// Configuration to be run (and then tested).
/*hash_data: {
default_options: {
options: {
},
files: {
'tmp/default_options': ['test/fixtures/testing', 'test/fixtures/123'],
},
},
custom_options: {
options: {
separator: ': ',
punctuation: ' !!!',
},
files: {
'tmp/custom_options': ['test/fixtures/testing', 'test/fixtures/123'],
},
},
},*/
// Unit tests.
nodeunit: {
tests: ['test/*_test.js'],
},
});
// Actually load this plugin's task(s).
grunt.loadTasks('tasks');
// These plugins provide necessary tasks.
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-clean');
grunt.loadNpmTasks('grunt-contrib-nodeunit');
// Whenever the "test" task is run, first clean the "tmp" dir, then run this
// plugin's task(s), then test the result.
grunt.registerTask('test', ['clean', 'hash_data', 'nodeunit']);
// By default, lint and run all tests.
grunt.registerTask('default', ['jshint', 'test']);
};
|
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = _default;
var _isUrl = _interopRequireDefault(require("is-url"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _default(path) {
return (0, _isUrl.default)(path);
}
|
import React, { Component } from 'react';
import PropTypes from 'prop-types';
// import { deleteIcon, editIcon } from '../../assets/images';
class IconButtons extends Component {
/**
* Fires an event when the text on a reusable button changes
*
* @param {string} text
*
* @returns {string}
*/
onButtonTextChange(text){
let buttonText;
if (text === 'Delete') {
buttonText = <img src="" alt="Delete" />;
} else if (text === 'Edit') {
buttonText = <img src="" alt="Edit" />;
} else {
buttonText = text;
}
return buttonText;
};
render() {
const { buttonText, modalButtonClassName, disabled } = this.props;
return (
<button
id="modal-button"
className={modalButtonClassName}
onClick={this.props.openModal}
disabled={disabled}
>
{this.onButtonTextChange(buttonText)}
</button>
);
}
}
IconButtons.propTypes = {
buttonText: PropTypes.string.isRequired,
modalButtonClassName: PropTypes.string,
openModal: PropTypes.func.isRequired,
disabled: PropTypes.bool,
};
IconButtons.defaultProps = {
modalButtonClassName: 'button',
disabled: false,
};
export default IconButtons;
|
var book = {
"name": "Яков",
"numChapters": 5,
"chapters": {
"1": {
"1": "<span class=\"chapternum\">1 </span>Яков слуга на Бога и на Господа Исуса Христа, до дванадесетте пръснати племена, поздрав.",
"2": "<sup class=\"versenum\">2 </sup>Считайте го за голяма радост, братя мои, когато падате в разни изпитни,",
"3": "<sup class=\"versenum\">3 </sup>като знаете, че изпитанието на вашата вяра произвежда твърдост.",
"4": "<sup class=\"versenum\">4 </sup>А твърдостта нека извърши делото си съвършено, за да бъдете съвършени и цели, без никакъв недостатък.",
"5": "<sup class=\"versenum\">5 </sup>Но ако някому от вас не достига мъдрост, нека иска от Бога, Който дава на всички щедро без да укорява, и ще му се даде.",
"6": "<sup class=\"versenum\">6 </sup>Но да проси с вяра без да се съмнява ни най-малко; защото, който се съмнява прилича на морски вълни, които се тласкат и блъскат от ветровете.",
"7": "<sup class=\"versenum\">7 </sup>Такъв човек да не мисли, че ще получи нещо от Господа,",
"8": "<sup class=\"versenum\">8 </sup>понеже е колеблив, непостоянен във всичките си пътища.",
"9": "<sup class=\"versenum\">9 </sup>Братът, който е в по-долно състояние, нека се хвали, когато се въздига,",
"10": "<sup class=\"versenum\">10 </sup>а богатият - когато се смирява, понеже ще прецъфти като цвета на тревата.",
"11": "<sup class=\"versenum\">11 </sup>Защото слънцето изгрява с изсушителния вятър, тревата изсъхва, цветът й окапва, и красотата на изгледа й изчезва: така и богатият ще повехне в пътищата си.",
"12": "<sup class=\"versenum\">12 </sup>Блажен онзи човек, който издържа изпитня; защото, като бъде одобрен, ще приеме за венец живота, който Господ е обещал на ония, които Го любят.",
"13": "<sup class=\"versenum\">13 </sup>Никой, който се изкушава, да не казва: Бог ме изкушава, защото Бог се не изкушава от зло, и Той никого не изкушава.",
"14": "<sup class=\"versenum\">14 </sup>А който се изкушава, се завлича и подлъгва от собствената си страст;",
"15": "<sup class=\"versenum\">15 </sup>и тогава страстта зачева и ражда грях, а грехът, като се развие напълно ражда смърт.",
"16": "<sup class=\"versenum\">16 </sup>Не се заблуждавайте, любезни мои братя;",
"17": "<sup class=\"versenum\">17 </sup>Всяко дадено добро и всеки съвършен дар е отгоре, и слиза от Отца на светлините, у Когото няма изменение, или сянка от промяна.",
"18": "<sup class=\"versenum\">18 </sup>От собствената Си воля ни е родил чрез словото на истината, за да бъдем един вид пръв плод на Неговите създания.",
"19": "<sup class=\"versenum\">19 </sup>Вие знаете <това>, любезни мои братя. Обаче нека всеки човек бъде бърз да слуша, бавен да говори и бавен да се гневи;",
"20": "<sup class=\"versenum\">20 </sup>защото човешкият гняв не върши Божията правда.",
"21": "<sup class=\"versenum\">21 </sup>Затова, като отхвърлите всяка нечистота и преливаща се злоба, приемайте с кротост всаденото слово, което може да спаси душите ви,",
"22": "<sup class=\"versenum\">22 </sup>Бивайте и изпълнители на словото, а не само слушатели, да лъжете себе си.",
"23": "<sup class=\"versenum\">23 </sup>Защото, ако някой бъде слушател на словото, а не изпълнител, той прилича на човек, който гледа естественото си лице в огледалото;",
"24": "<sup class=\"versenum\">24 </sup>понеже се огледва, отива си, и завчас забравя какъв бе.",
"25": "<sup class=\"versenum\">25 </sup>Но който вникне в съвършения закон на свободата и постоянствува, той, като не е забравлив слушател, но деятелен изпълнител, ще бъде блажен в дейността си.",
"26": "<sup class=\"versenum\">26 </sup>Ако някой счита себе си за благочестив, а не обуздава езика си, но мами сърцето си, неговото благочестие е суетно.",
"27": "<sup class=\"versenum\">27 </sup>Чисто и непорочно благочестие пред Бога и Отца, ето що е: да пригледва <човек> сирачетата и вдовиците в неволята им, <и> да пази себе си неопетнен от света."
},
"2": {
"1": "<span class=\"chapternum\">2 </span>Братя мои, да не държите вярата на прославения наш Господ Исус Христос с лицеприятие.",
"2": "<sup class=\"versenum\">2 </sup>Защото, ако влезе в синагогата ви човек със златен пръстен и с хубави дрехи, а влезе и сиромах с оплескани дрехи,",
"3": "<sup class=\"versenum\">3 </sup>и погледнете с почит към оня, който е с хубавите дрехи, та речете: Ти седни тука на добро място; а на сиромаха речете: Ти стой там, или: Седни до подножието ми,",
"4": "<sup class=\"versenum\">4 </sup>не правите ли различия помежду си, и не ставате ли пристрастни съдии?",
"5": "<sup class=\"versenum\">5 </sup>Слушайте любезни ми братя: Не избра ли Бог ония, които са сиромаси в светски неща, богати с вяра и наследници на царството, което е обещал на тия, които Го любят?",
"6": "<sup class=\"versenum\">6 </sup>А вие опозорихте сиромаха. Нали богатите ви угнетяват и сами ви влачат по съдилища?",
"7": "<sup class=\"versenum\">7 </sup>Нали те хулят почтеното име, с което се именувате?",
"8": "<sup class=\"versenum\">8 </sup>Обаче, ако изпълнявате царския закон, според писанието: \"Да обичаш ближния си като себе си\", добре правите.",
"9": "<sup class=\"versenum\">9 </sup>Но ако гледате на лице, грях правите, и от закона се осъждате като престъпници.",
"10": "<sup class=\"versenum\">10 </sup>Защото, който опази целия закон, а съгреши в едно <нещо>, бива виновен във всичко.",
"11": "<sup class=\"versenum\">11 </sup>Понеже Оня, Който е рекъл: \"Не прелюбодействувай\", рекъл е и: \"Не убивай\", тъй че, ако не прелюбодействуваш, а пък убиваш, станал си престъпник на закона.",
"12": "<sup class=\"versenum\">12 </sup>Така говорете и така постъпвайте като човеци, които ще бъдат съдени по закона на свободата.",
"13": "<sup class=\"versenum\">13 </sup>Защото съдът е немилостив към този, който не е показал милост. Милостта тържествува над съда.",
"14": "<sup class=\"versenum\">14 </sup>Каква полза, братя мои, ако някой казва, че има вяра, а няма дела? Може ли такава вяра да го спаси?",
"15": "<sup class=\"versenum\">15 </sup>Ако някой брат или някоя сестра са голи и останали без ежедневна храна,",
"16": "<sup class=\"versenum\">16 </sup>и някой от вас им рече: Идете си с мир, дано бъдете стоплени и нахранени, а не им дадете потребното за тялото, каква полза?",
"17": "<sup class=\"versenum\">17 </sup>Така и вярата, ако няма дела, сама по себе си е мъртва.",
"18": "<sup class=\"versenum\">18 </sup>Но ще рече някой: Ти имаш вяра, а пък аз имам дела; ако <можеш>, покажи ми вярата си без дела, и аз ще ти покажа вярата си от моите дела.",
"19": "<sup class=\"versenum\">19 </sup>Ти вярваш, че има <само> един Бог, добре правиш; и бесовете вярват и треперят.",
"20": "<sup class=\"versenum\">20 </sup>Обаче искаш ли да познаеш, о суетни човече, че вяра без дела е безплодна?",
"21": "<sup class=\"versenum\">21 </sup>Авраам, нашият отец, не оправда ли се чрез дела като принесе сина си Исаака на жертвеника?",
"22": "<sup class=\"versenum\">22 </sup>Ти виждаш, че вярата действуваше заедно с делата му, и че от делата се усъвършенствува вярата;",
"23": "<sup class=\"versenum\">23 </sup>и изпълни се писанието, което казва: \"Авраам повярва в Бога; и това му се вмени за правда\"; и се нарече Божий приятел.",
"24": "<sup class=\"versenum\">24 </sup>Виждате, че чрез дела се оправдава човек, а не само чрез вяра.",
"25": "<sup class=\"versenum\">25 </sup>Така също и блудницата Раав не оправда ли се чрез дела, когато прие пратениците и ги изпрати бърже през друг път?",
"26": "<sup class=\"versenum\">26 </sup>Защото, както тялото отделено от духа е мъртво, така и вярата отделена от дела е мъртва."
},
"3": {
"1": "<span class=\"chapternum\">3 </span>Братя мои, не ставайте мнозина учители, като знаете, че ще приемем по-тежко осъждане.",
"2": "<sup class=\"versenum\">2 </sup>Защото ние всички в много неща грешим; а който не греши в говорене, той е съвършен мъж, способен да обуздае и цялото тяло.",
"3": "<sup class=\"versenum\">3 </sup>Ето, ние туряме юздите в устата на конете, за да ни се покоряват, и обръщаме цялото им тяло.",
"4": "<sup class=\"versenum\">4 </sup>Ето, и корабите, ако и да са толкова големи, и се тласкат от силните ветрове, пак с твърде малко кормило се обръщат на където желае кормчията.",
"5": "<sup class=\"versenum\">5 </sup>Така и езикът е малка част <от тялото>, но много се хвали. Ето, съвсем малко огън, колко много вещество запалва!",
"6": "<sup class=\"versenum\">6 </sup>И езикът, тоя <цял> свят от нечестие, е огън. Между нашите <телесни> части езикът е, който заразява цялото тяло и запалва колелото на живота, <ни>, а <сам> той се запалва от пъкъла.",
"7": "<sup class=\"versenum\">7 </sup>Защото всякакъв вид зверове, птици, гадини и морски животни се укротяват и укротени са били от човечеството;",
"8": "<sup class=\"versenum\">8 </sup>но езика никой човек не може да укроти; буйно зло е, пълен <е> със смъртоносна отрова.",
"9": "<sup class=\"versenum\">9 </sup>С него благославяме Господа и Отца, и с него кълнем човеците създадени по Божие подобие!",
"10": "<sup class=\"versenum\">10 </sup>От същите уста излизат благословение и проклетия! Братя мои, не трябва това така да бъде.",
"11": "<sup class=\"versenum\">11 </sup>Изворът пуща ли от същото отверстие сладка и горчива вода?",
"12": "<sup class=\"versenum\">12 </sup>Възможно ли е, братя мои смоковницата да роди маслини, или лозата смокини? Така също <не може> солена вода да дава сладка.",
"13": "<sup class=\"versenum\">13 </sup>Кой от вас е мъдър и разумен? Нека показва своите дела чрез добрия си живот, с кротостта на мъдростта.",
"14": "<sup class=\"versenum\">14 </sup>Но ако в сърцето си имате горчива завист и крамолничество, не се хвалете и не лъжете против истината.",
"15": "<sup class=\"versenum\">15 </sup>Това не е мъдрост, която слиза от горе, но е земна, животинска, бесовска;",
"16": "<sup class=\"versenum\">16 </sup>защото, гдето има завист и крамолничество, там има бъркотия и всякакво лошо нещо.",
"17": "<sup class=\"versenum\">17 </sup>Но мъдростта, която е отгоре, е преди всичко чиста, после миролюбива, кротка, умолима, пълна с милост и добри плодове, примирителна, нелицемерна.",
"18": "<sup class=\"versenum\">18 </sup>А плодът на правдата се сее с мир от миротворците."
},
"4": {
"1": "<span class=\"chapternum\">4 </span>Отгде произлизат боеве, и отгде крамоли, между вас? Не от там ли, от вашите сласти, които воюват в <телесните> ви части?",
"2": "<sup class=\"versenum\">2 </sup>Пожелавате, но нямате; ревнувате и завиждате, но не можете да получите; карате се и се биете; но нямате, защото не просите.",
"3": "<sup class=\"versenum\">3 </sup>Просите и не получавате, защото зле просите, за да иждивявате в сластите си.",
"4": "<sup class=\"versenum\">4 </sup>Прелюбодейци! не знаете ли, че приятелството със света е вражда против Бога? И тъй, който иска да бъде приятел на света, става враг на Бога.",
"5": "<sup class=\"versenum\">5 </sup>Или мислите, че без нужда казва писанието, че <Бог> и до завист ревнува за духа, който е турил да живее в нас?",
"6": "<sup class=\"versenum\">6 </sup>Но Той дава една по-голяма благодат; затова казва: \"Бог на горделивите се противи, а на смирените дава благодат\".",
"7": "<sup class=\"versenum\">7 </sup>И тъй, покорявайте се на Бога, но противете се на дявола, и той ще бяга от вас.",
"8": "<sup class=\"versenum\">8 </sup>Приближавайте се при Бога, и ще се приближава и Той при вас. Измивайте ръцете си, вие грешни, и очиствайте сърцата си, вие колебливи.",
"9": "<sup class=\"versenum\">9 </sup>Тъжете, ридайте и плачете; смехът ви нека се обърне на плач, и радостта ви в тъга.",
"10": "<sup class=\"versenum\">10 </sup>Смирявайте се пред Господа, и Той ще ви възвишава.",
"11": "<sup class=\"versenum\">11 </sup>Не се одумвайте един друг, братя; който одумва брата или съди брата си, одумва закона и съди закона; а ако съдиш закона, не си изпълнител на закона, но съдия.",
"12": "<sup class=\"versenum\">12 </sup><Само> Един е законодател и съдия, Който може да спаси и да погуби; а ти кой си та съдиш ближния си?",
"13": "<sup class=\"versenum\">13 </sup>Слушайте сега вие, които казвате: Днес или утре ще отидем в еди-кой-си град, ще преседим там една година, и ще търгуваме и ще спечелим, -",
"14": "<sup class=\"versenum\">14 </sup>когато вие не знаете какво ще бъде утре. Що е животът ви? Защото вие сте пара, която се явява, и после изчезва.",
"15": "<sup class=\"versenum\">15 </sup>Вместо <това, вие трябва> да казвате: Ако ще Господ, ние ще живеем и ще направим това или онова.",
"16": "<sup class=\"versenum\">16 </sup>Но сега славно ви е да се хвалите. Всяка такава хвалба е зло.",
"17": "<sup class=\"versenum\">17 </sup>Прочее, ако някой знае да прави добро и го не прави, грях е нему."
},
"5": {
"1": "<span class=\"chapternum\">5 </span>Дойдете сега, вие богатите, плачете и ридайте поради бедствията, които идват върху вас.",
"2": "<sup class=\"versenum\">2 </sup>Богатството ви изгни, и дрехите ви са изядени от молци.",
"3": "<sup class=\"versenum\">3 </sup>Златото ви и среброто ви ръждясаха; и ръждата им ще свидетелствува против вас и ще пояде месата ви като огън. Вие сте събирали съкровища в последните дни.",
"4": "<sup class=\"versenum\">4 </sup>Ето, заплатата за работниците, които са жънали нивите ви, от която ги лишихте, вика; и виковете на жетварите влязоха в ушите на Господа на Силите.",
"5": "<sup class=\"versenum\">5 </sup>Вие живяхте на земята разкошно и разпуснато, угоихте сърцата си <като> в ден на клане.",
"6": "<sup class=\"versenum\">6 </sup>Осъдихте, убихте Праведния; и Той не ви се противи.",
"7": "<sup class=\"versenum\">7 </sup>И тъй, братя, останете твърди, до Господното пришествие. Ето земеделецът очаква скъпоценния плод от земята и търпи за него докле получи и ранния и късния дъжд.",
"8": "<sup class=\"versenum\">8 </sup>Останете и вие твърди, и укрепете сърцата си; защото Господното пришествие наближи.",
"9": "<sup class=\"versenum\">9 </sup>Не роптайте един против друг, братя, за да не бъдете осъдени; ето, Съдията стои пред вратите.",
"10": "<sup class=\"versenum\">10 </sup>Братя, вземете за пример на злострадание и на твърдост пророците, които говориха за Господното име.",
"11": "<sup class=\"versenum\">11 </sup>Ето, облажаваме ония, които са останали твърди. Чули сте за търпението на Иова {В изданието от 1940 г. - Иоана, печатна грешка.}, и видели сте сетнината <въздадена нему> от Господа, че Господ е много жалостив и милостив.",
"12": "<sup class=\"versenum\">12 </sup>А преди всичко, братя мои, не се кълнете нито в небето, нито в земята, нито в друга някоя клетва; но нека бъде вашето <говорене:> Да, да, и: Не, не, за да не паднете под осъждане.",
"13": "<sup class=\"versenum\">13 </sup>Зле ли страда някой от вас? нека се моли. Весел ли е някой? нека пее хваления.",
"14": "<sup class=\"versenum\">14 </sup>Болен ли е някой от вас? нека повика църковните презвитери, и нека се помолят над него и го помажат с масло в Господното име.",
"15": "<sup class=\"versenum\">15 </sup>И молитвата, която е с вяра, ще избави страдалеца, Господ ще го привдигне, и, ако е извършил грехове, ще му се простят.",
"16": "<sup class=\"versenum\">16 </sup>И тъй, изповядайте един на друг греховете си, и молете се един за друг, за да оздравеете. Голяма сила има усърдната молитва на праведния.",
"17": "<sup class=\"versenum\">17 </sup>Илия беше човек със същото естество като нас; и помоли се усърдно да не вали дъжд, и не валя дъжд на земята три години и шест месеца;",
"18": "<sup class=\"versenum\">18 </sup>и пак се помоли и небето даде дъжд, и земята произведе плода си.",
"19": "<sup class=\"versenum\">19 </sup>Братя мои, ако някой от вас <се> {В изданието от 1940 г. \"се\" липсва.} заблуди от истината, и един го обърне,",
"20": "<sup class=\"versenum\">20 </sup>нека знае, че който е обърнал грешния от заблудения му път ще спаси душа от смърт и ще покрие много грехове."
}
}
};
module.exports = book;
|
import React from 'react'
import PropTypes from 'prop-types'
export default class HTML extends React.Component {
render() {
return (
<html {...this.props.htmlAttributes}>
<head>
<meta charSet="utf-8" />
<meta httpEquiv="x-ua-compatible" content="ie=edge" />
<meta
name="Description"
content="brouk's devlog, 개발블로그 입니다. brouk2426@gmail.com "
/>
<meta
name="viewport"
content="width=device-width, initial-scale=1, shrink-to-fit=no, minimum-scale=1, maximum-scale=2"
/>
{this.props.headComponents}
</head>
<body {...this.props.bodyAttributes}>
{this.props.preBodyComponents}
<noscript>You need to enable JavaScript to run this app.</noscript>
<div
key={`body`}
id="___gatsby"
dangerouslySetInnerHTML={{ __html: this.props.body }}
/>
{this.props.postBodyComponents}
</body>
</html>
)
}
}
HTML.propTypes = {
htmlAttributes: PropTypes.object,
headComponents: PropTypes.array,
bodyAttributes: PropTypes.object,
preBodyComponents: PropTypes.array,
body: PropTypes.string,
postBodyComponents: PropTypes.array,
}
|
var util = require('util');
/*
* Kurento media Stack
*/
var kurento = require('kurento-client');
var transform = require('sdp-transform');
var config = require('./config');
var MediaStack = function () {
MediaStack.id ="bob";
MediaStack.sessions = {};
MediaStack.sip = null;
MediaStack.candidatesQueue = {};
MediaStack.kurentoClient = null;
};
MediaStack.prototype.init = function (sip){
MediaStack.sip = sip;
}
MediaStack.prototype.start = function (sessionId, ws, from,to, sdpOffer, options,callback) {
if (!sessionId) {
return callback('Cannot use undefined sessionId');
}
MediaStack.candidatesQueue[sessionId] = [];
MediaStack.sessions[sessionId]={
'ws': ws
};
console.log(sessionId +"Concurent calls : " + Object.keys(MediaStack.sessions).length +"/"+ config.maxConcurentCalls + util.inspect(MediaStack.sessions) );
if(Object.keys(MediaStack.sessions).length > config.maxConcurentCalls){
return callback('Unable to start call due to server concurrent capacity limit');
}
getKurentoClient(function(error, kurentoClient) {
if (error) {
return callback(error);
}
kurentoClient.create('MediaPipeline', function(error, pipeline) {
if (error) {
return callback(error);
}
createMediaElements(sessionId,pipeline,ws,from,to,options, function(error, webRtcEndpoint,rtpEndpoint) {
if (error) {
pipeline.release();
return callback(error);
}
console.log("Collect Candidates");
if (MediaStack.candidatesQueue[sessionId]) {
while(MediaStack.candidatesQueue[sessionId].length) {
var candidate = MediaStack.candidatesQueue[sessionId].shift();
webRtcEndpoint.addIceCandidate(candidate);
}
}
console.log("connect media element");
connectMediaElements(webRtcEndpoint,rtpEndpoint, function(error) {
if (error) {
pipeline.release();
return callback(error);
}
webRtcEndpoint.on('OnIceCandidate', function(event) {
var candidate = kurento.getComplexType('IceCandidate')(event.candidate);
ws.send(JSON.stringify({
id : 'iceCandidate',
candidate : candidate
}));
});
webRtcEndpoint.processOffer(sdpOffer, function(error, sdpAnswer) {
console.log("Sdp Answer WebRTC Endpoint " + sdpAnswer);
if (error) {
pipeline.release();
return callback(error);
}
MediaStack.sessions[sessionId].pipeline = pipeline;
MediaStack.sessions[sessionId].webRtcEndpoint = webRtcEndpoint;
MediaStack.sessions[sessionId].rtpEndpoint = rtpEndpoint;
return callback(null, sdpAnswer);
});
webRtcEndpoint.gatherCandidates(function(error) {
if (error) {
return callback(error);
}
});
});
});
});
});
}
// Recover kurentoClient for the first time.
function getKurentoClient(callback) {
console.log("Get Kurento Client ");
if (MediaStack.kurentoClient) {
console.log(" Kurento Client not null ");
return callback(null, MediaStack.kurentoClient);
}
kurento(config.kurento.ws_uri, function(error, _kurentoClient) {
if (error) {
console.log("Could not find media server at address " + config.kurento.ws_uri);
return callback("Could not find media server at address" + config.kurento.ws_uri
+ ". Exiting with error " + error);
}
MediaStack.kurentoClient = _kurentoClient;
console.log(" Call Abck Kurento CLient ");
callback(null, MediaStack.kurentoClient);
});
}
function getIPAddress() {
return config.serverPublicIP;
}
function replace_ip(sdp, ip) {
if (!ip)
ip = getIPAddress();
console.log("IP " + ip);
console.log("sdp init : "+sdp);
var sdpObject = transform.parse(sdp);
sdpObject.origin.address = ip;
sdpObject.connection.ip = ip;
var sdpResult = transform.write(sdpObject);
console.log("sdp result : "+sdpResult);
return sdpResult;
}
function mungleSDP(sdp){
mugleSdp = sdp;
var mugleSdp = sdp.replace(new RegExp("RTP/AVPF", "g"), "RTP/AVP");
var h264Payload = MediaStack.sip.getH264Payload(sdp);
mugleSdp+="a=fmtp:"+h264Payload+" profile-level-id=42801F\n";
return mugleSdp;
}
function mungleSDP2(sdp){
mugleSdp = sdp;
var mugleSdp = sdp.replace(new RegExp("RTP/AVPF", "g"), "RTP/AVP");
var h264Payload = MediaStack.sip.getH264Payload(sdp);
return mugleSdp;
}
function prettyJSON(obj) {
console.log(JSON.stringify(obj, null, 2));
}
function createMediaElements(sessionId,pipeline,ws,from,to,options, callback) {
pipeline.create('WebRtcEndpoint', function(error, webRtcEndpoint) {
if (error) {
return callback(error);
}
pipeline.create('RtpEndpoint', function(error, rtpEndpoint){
if (error) {
return callback(error);
}
createSipCall(sessionId,from+"@"+getIPAddress(),to,rtpEndpoint,options,function(error){
if (error) {
return callback(error);
}
return callback(null, webRtcEndpoint, rtpEndpoint);
});
});
});
}
function connectMediaElements(webRtcEndpoint, rtpEndpoint,callback) {
rtpEndpoint.connect(webRtcEndpoint, function(error) {
if (error) {
return callback(error);
}
webRtcEndpoint.connect(rtpEndpoint,function (error){
if (error) {
return callback(error);
}
return callback(null);
});
});
}
function reConnectMediaElements(sessionId) {
var webRtcEndpoint = MediaStack.sessions[sessionId].webRtcEndpoint;
var rtpEndpoint = MediaStack.sessions[sessionId].rtpEndpoint;
rtpEndpoint.connect(webRtcEndpoint, function(error) {
if (!error) {
webRtcEndpoint.connect(rtpEndpoint,function (error){
console.log("Reconnect Media "+sessionId);
});
}
/*
if (MediaStack.sessions[sessionId].OldRtpEndpoint){
MediaStack.sessions[sessionId].OldRtpEndpoint.release();
MediaStack.sessions[sessionId].OldRtpEndpoint=null;
}*/
});
}
function createSipCall(sessionId,from,to,rtpEndpoint,options,callback){
rtpEndpoint.generateOffer(function(error, sdpOffer) {
var modSdp = replace_ip(sdpOffer);
modSdp = mungleSDP(modSdp);
MediaStack.sip.invite (sessionId,from,to,modSdp,options,function (error,remoteSdp){
if (error){
return callback(error);
}
rtpEndpoint.processAnswer(remoteSdp,function(error){
if (error){
return callback(error);
}
// Insert EnCall timeout
setTimeout(function(){
console.log("EndCall Timeout "+sessionId);
MediaStack.sip.bye(sessionId);
MediaStack.stopFromBye(sessionId);
}
,config.maxCallSeconds*1000);
return callback(null);
});
});
});
}
MediaStack.prototype.stop = function (sessionId) {
MediaStack.sip.bye(sessionId);
if (MediaStack.sessions[sessionId]) {
var pipeline = MediaStack.sessions[sessionId].pipeline;
if (pipeline != undefined){
console.info('Releasing pipeline');
pipeline.release();
}
delete MediaStack.sessions[sessionId];
delete MediaStack.candidatesQueue[sessionId];
}
}
MediaStack.prototype.stopFromBye = function (sessionId) {
if (MediaStack.sessions[sessionId]) {
var ws = MediaStack.sessions[sessionId].ws;
if (ws != undefined){
ws.send(JSON.stringify({
id : 'stopFromBye'
}));
}
var pipeline = MediaStack.sessions[sessionId].pipeline;
if (pipeline != undefined){
console.info('Releasing pipeline');
pipeline.release();
}
delete MediaStack.sessions[sessionId];
delete MediaStack.candidatesQueue[sessionId];
}
}
MediaStack.prototype.onIceCandidate = function (sessionId, _candidate) {
var candidate = kurento.getComplexType('IceCandidate')(_candidate);
if (MediaStack.sessions[sessionId]!=undefined && MediaStack.sessions[sessionId].webRtcEndpoint!=undefined) {
console.info('Sending candidate');
var webRtcEndpoint = MediaStack.sessions[sessionId].webRtcEndpoint;
webRtcEndpoint.addIceCandidate(candidate);
}
else {
console.info('Queueing candidate');
if (!MediaStack.candidatesQueue[sessionId]) {
MediaStack.candidatesQueue[sessionId] = [];
}
MediaStack.candidatesQueue[sessionId].push(candidate);
}
}
MediaStack.prototype.sendDtmf = function (sessionId, dtmf){
MediaStack.sip.infoDtmf(sessionId,dtmf);
// reConnectMediaElements(sessionId);
}
MediaStack.prototype.reconnect = function (sessionId){
reConnectMediaElements(sessionId);
}
MediaStack.prototype.renegotiateWebRTC = function (sessionId,callback){
if (MediaStack.sessions[sessionId] && MediaStack.sessions[sessionId].pipeline){
var pipeline = MediaStack.sessions[sessionId].pipeline;
MediaStack.sessions[sessionId].webRtcEndpoint.release();
MediaStack.sessions[sessionId].renegotiated=true;
MediaStack.candidatesQueue[sessionId]=[];
pipeline.create('WebRtcEndpoint', function(error, webRtcEndpoint){
if (error) {
return callback(error);
}
MediaStack.sessions[sessionId].webRtcEndpoint = webRtcEndpoint;
webRtcEndpoint.generateOffer(function(error,sdpOffer) {
if (error){
console.log("SdpOffer not accepted by kurento");
console.log(error);
return callback(error);
}
var ws = MediaStack.sessions[sessionId].ws;
if (ws != undefined){
ws.send(JSON.stringify({
id : 'renegotiateWebRTC',
sdp : sdpOffer
}));
return callback();
}
});
});
};
}
MediaStack.prototype.renegotiateResponse = function (sessionId,sdp){
if (MediaStack.sessions[sessionId] && MediaStack.sessions[sessionId].pipeline && MediaStack.sessions[sessionId].webRtcEndpoint){
var webRtcEndpoint = MediaStack.sessions[sessionId].webRtcEndpoint;
var pipeline = MediaStack.sessions[sessionId].pipeline;
console.log("Collect Candidates");
if (MediaStack.candidatesQueue[sessionId]) {
while(MediaStack.candidatesQueue[sessionId].length) {
var candidate = MediaStack.candidatesQueue[sessionId].shift();
webRtcEndpoint.addIceCandidate(candidate);
}
}
var ws = MediaStack.sessions[sessionId].ws;
webRtcEndpoint.on('OnIceCandidate', function(event) {
var candidate = kurento.getComplexType('IceCandidate')(event.candidate);
ws.send(JSON.stringify({
id : 'iceCandidate',
candidate : candidate
}));
});
webRtcEndpoint.processAnswer(sdp, function(error) {
MediaStack.sessions[sessionId].renegotiated=false;
if (error) {
pipeline.release();
console.log("ProcessAnswer Error"+error);
}
MediaStack.sip.reponseToReInvite(sessionId);
// reConnectMediaElements(sessionId);
return;
});
webRtcEndpoint.gatherCandidates(function(error) {
if (error) {
console.log("gatherCandidates Error"+error);
}
});
}
}
function disconnectElement (webRtcEndpoint,rtpEndpoint,callback){
rtpEndpoint.disconnect(webRtcEndpoint, function(error) {
if (error)
callback(error)
webRtcEndpoint.disconnect(rtpEndpoint,function (error){
if (error)
callback(error);
rtpEndpoint.release((error)=>{
if (error)
callback(error);
callback(null);
});
});
});
}
MediaStack.prototype.renegotiateRTP = function (sessionId, remoteSdp,callback){
if (MediaStack.sessions[sessionId] && MediaStack.sessions[sessionId].pipeline){
var pipeline = MediaStack.sessions[sessionId].pipeline;
disconnectElement(MediaStack.sessions[sessionId].webRtcEndpoint,MediaStack.sessions[sessionId].rtpEndpoint,function(){
//MediaStack.sessions[sessionId].rtpEndpoint.release();
pipeline.create('RtpEndpoint', function(error, rtpEndpoint){
if (error) {
return callback(error);
}
rtpEndpoint.processOffer(remoteSdp,function(error,sdpOffer) {
if (error){
console.log("SdpOffer not accepted by kurento");
console.log(error);
return callback(error);
}
var modSdp = replace_ip(sdpOffer);
modSdp = mungleSDP2(modSdp);
MediaStack.sessions[sessionId].rtpEndpoint = rtpEndpoint;
return callback(null,modSdp);
});
});
});
}
}
module.exports = new MediaStack();
|
let nock = require('nock');
module.exports.hash = "e54d5f4d8fca2689c41edeeb26fc3382";
module.exports.testInfo = {"uniqueName":{},"newDate":{}}
nock('https://endpoint', {"encodedQueryParams":true})
.post('/text/analytics/v3.1-preview.4/entities/health/jobs', {"documents":[{"id":"1","text":"hello world"},{"id":"1","text":"I did not like the hotel we stayed at."}]})
.query(true)
.reply(400, {"error":{"code":"InvalidRequest","message":"Invalid document in request.","innererror":{"code":"InvalidDocument","message":"Request contains duplicated Ids. Make sure each document has a unique Id."}}}, [
'Transfer-Encoding',
'chunked',
'Content-Type',
'application/json; charset=utf-8',
'x-envoy-upstream-service-time',
'6',
'apim-request-id',
'f47c68c0-d55d-4362-b258-ba5040821ebf',
'Strict-Transport-Security',
'max-age=31536000; includeSubDomains; preload',
'x-content-type-options',
'nosniff',
'Date',
'Tue, 23 Feb 2021 19:35:43 GMT'
]);
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.