text
stringlengths 3
1.05M
|
|---|
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const Template = require("./Template");
module.exports = class RuntimeTemplate {
constructor(outputOptions, requestShortener) {
this.outputOptions = outputOptions || {};
this.requestShortener = requestShortener;
}
/**
* Add a comment
* @param {object} options Information content of the comment
* @param {string=} options.request request string used originally
* @param {string=} options.chunkName name of the chunk referenced
* @param {string=} options.chunkReason reason information of the chunk
* @param {string=} options.message additional message
* @param {string=} options.exportName name of the export
* @returns {string} comment
*/
comment({ request, chunkName, chunkReason, message, exportName }) {
let content;
if (this.outputOptions.pathinfo) {
content = [message, request, chunkName, chunkReason]
.filter(Boolean)
.map(item => this.requestShortener.shorten(item))
.join(" | ");
} else {
content = [message, chunkName, chunkReason]
.filter(Boolean)
.map(item => this.requestShortener.shorten(item))
.join(" | ");
}
if (!content) return "";
if (this.outputOptions.pathinfo) {
return Template.toComment(content) + " ";
} else {
return Template.toNormalComment(content) + " ";
}
}
throwMissingModuleErrorFunction({ request }) {
const err = `Cannot find module "${request}"`;
return `function webpackMissingModule() { var e = new Error(${JSON.stringify(
err
)}); e.code = 'MODULE_NOT_FOUND'; throw e; }`;
}
missingModule({ request }) {
return `!(${this.throwMissingModuleErrorFunction({ request })}())`;
}
missingModuleStatement({ request }) {
return `${this.missingModule({ request })};\n`;
}
missingModulePromise({ request }) {
return `Promise.resolve().then(${this.throwMissingModuleErrorFunction({
request
})})`;
}
moduleId({ module, request }) {
if (!module)
return this.missingModule({
request
});
return `${this.comment({ request })}${JSON.stringify(module.id)}`;
}
moduleRaw({ module, request }) {
if (!module)
return this.missingModule({
request
});
return `__webpack_require__(${this.moduleId({ module, request })})`;
}
moduleExports({ module, request }) {
return this.moduleRaw({
module,
request
});
}
moduleNamespace({ module, request, strict }) {
const rawModule = this.moduleRaw({
module,
request
});
const exportsType = module.buildMeta && module.buildMeta.exportsType;
if (exportsType === "namespace") {
return rawModule;
} else if (exportsType === "named") {
return `Object.assign({/* fake namespace object */}, ${rawModule}, { "default": ${rawModule} })`;
} else if (strict) {
return `Object({ /* fake namespace object */ "default": ${rawModule} })`;
} else {
return `Object(function() { var module = ${rawModule}; return typeof module === "object" && module && module.__esModule ? module : Object.assign({/* fake namespace object */}, typeof module === "object" && module, { "default": module }); }())`;
}
}
moduleNamespacePromise({ block, module, request, message, strict, weak }) {
if (!module)
return this.missingModulePromise({
request
});
const promise = this.blockPromise({
block,
message
});
let getModuleFunction;
let idExpr = JSON.stringify(module.id);
const comment = this.comment({
request
});
let header = "";
if (weak) {
if (idExpr.length > 8) {
// 'var x="nnnnnn";x,"+x+",x' vs '"nnnnnn",nnnnnn,"nnnnnn"'
header += `var id = ${idExpr}; `;
idExpr = "id";
}
header += `if(!__webpack_require__.m[${idExpr}]) { var e = new Error("Module '" + ${idExpr} + "' is not available (weak dependency)"); e.code = 'MODULE_NOT_FOUND'; throw e; } `;
}
const rawModule = this.moduleRaw({
module,
request
});
const exportsType = module.buildMeta && module.buildMeta.exportsType;
if (exportsType === "namespace") {
if (header) {
getModuleFunction = `function() { ${header}return ${rawModule}; }`;
} else {
getModuleFunction = `__webpack_require__.bind(null, ${comment}${idExpr})`;
}
} else if (exportsType === "named") {
getModuleFunction = `function() { ${header}var module = ${rawModule}; return Object.assign({/* fake namespace object */}, module, { "default": module }); }`;
} else if (strict) {
getModuleFunction = `function() { ${header}return { /* fake namespace object */ "default": ${rawModule} }; }`;
} else {
getModuleFunction = `function() { ${header}var module = ${rawModule}; return typeof module === "object" && module && module.__esModule ? module : Object.assign({/* fake namespace object */}, typeof module === "object" && module, { "default": module }); }`;
}
return `${promise || "Promise.resolve()"}.then(${getModuleFunction})`;
}
importStatement({ update, module, request, importVar, originModule }) {
if (!module)
return this.missingModuleStatement({
request
});
const comment = this.comment({
request
});
const optDeclaration = update ? "" : "var ";
const exportsType = module.buildMeta && module.buildMeta.exportsType;
let content = `/* harmony import */ ${optDeclaration}${importVar} = __webpack_require__(${comment}${JSON.stringify(
module.id
)});\n`;
if (!exportsType && !originModule.buildMeta.strictHarmonyModule) {
content += `/* harmony import */ ${optDeclaration}${importVar}_default = /*#__PURE__*/__webpack_require__.n(${importVar});\n`;
}
if (exportsType === "named") {
if (Array.isArray(module.buildMeta.providedExports))
content += `${optDeclaration}${importVar}_namespace = /*#__PURE__*/Object.assign({}, ${importVar}, {"default": ${importVar}});\n`;
else
content += `${optDeclaration}${importVar}_namespace = /*#__PURE__*/{ /* fake namespace object */ "default": ${importVar} };\n`;
}
return content;
}
exportFromImport({
module,
request,
exportName,
originModule,
asiSafe,
isCall,
callContext,
importVar
}) {
if (!module)
return this.missingModule({
request
});
const exportsType = module.buildMeta && module.buildMeta.exportsType;
if (!exportsType) {
if (exportName === "default") {
if (!originModule.buildMeta.strictHarmonyModule) {
if (isCall) return `${importVar}_default()`;
else if (asiSafe) return `(${importVar}_default())`;
else return `${importVar}_default.a`;
} else {
return importVar;
}
} else if (originModule.buildMeta.strictHarmonyModule) {
if (exportName) {
return "/* non-default import from non-esm module */undefined";
} else {
if (asiSafe) {
return `/*#__PURE__*/{ /* fake namespace object */ "default": ${importVar} }`;
} else {
return `/*#__PURE__*/Object({ /* fake namespace object */ "default": ${importVar} })`;
}
}
}
}
if (exportsType === "named") {
if (exportName === "default") {
return importVar;
} else if (!exportName) {
return `${importVar}_namespace`;
}
}
if (exportName) {
const used = module.isUsed(exportName);
const comment =
used !== exportName ? Template.toNormalComment(exportName) + " " : "";
const access = `${importVar}[${comment}${JSON.stringify(used)}]`;
if (isCall) {
if (callContext === false && asiSafe) return `(0,${access})`;
else if (callContext === false) return `Object(${access})`;
}
return access;
} else {
return importVar;
}
}
blockPromise({ block, message }) {
if (!block || !block.chunkGroup || block.chunkGroup.chunks.length === 0) {
const comment = this.comment({
message
});
return `Promise.resolve(${comment.trim()})`;
}
const chunks = block.chunkGroup.chunks.filter(
chunk => !chunk.hasRuntime() && chunk.id !== null
);
const comment = this.comment({
message,
chunkName: block.chunkName,
chunkReason: block.chunkReason
});
if (chunks.length === 1) {
const chunkId = JSON.stringify(chunks[0].id);
return `__webpack_require__.e(${comment}${chunkId})`;
} else if (chunks.length > 0) {
const requireChunkId = chunk =>
`__webpack_require__.e(${JSON.stringify(chunk.id)})`;
return `Promise.all(${comment.trim()}[${chunks
.map(requireChunkId)
.join(", ")}])`;
} else {
return `Promise.resolve(${comment.trim()})`;
}
}
onError() {
return "__webpack_require__.oe";
}
defineEsModuleFlagStatement({ exportsArgument }) {
return `__webpack_require__.r(${exportsArgument});\n`;
}
};
|
import pytest
import time
from hexbytes import (
HexBytes,
)
def test_shh_sync_filter_deprecated(web3, skip_if_testrpc):
skip_if_testrpc(web3)
with pytest.warns(DeprecationWarning):
sender = web3.shh.newKeyPair()
sender_pub = web3.shh.getPublicKey(sender)
receiver = web3.shh.newKeyPair()
receiver_pub = web3.shh.getPublicKey(receiver)
topic = '0x13370000'
payloads = [web3.toHex(text="test message :)"), web3.toHex(text="2nd test message")]
shh_filter = web3.shh.newMessageFilter({
'privateKeyID': receiver,
'sig': sender_pub,
'topics': [topic]
})
web3.shh.post({
'sig': sender,
'powTarget': 2.5,
'powTime': 2,
'payload': payloads[0],
'pubKey': receiver_pub
})
time.sleep(1)
web3.shh.post({
'sig': sender,
'powTarget': 2.5,
'powTime': 2,
'payload': payloads[1],
'topic': topic,
'pubKey': receiver_pub
})
time.sleep(1)
received_messages = shh_filter.get_new_entries()
assert len(received_messages) == 1
message = received_messages[0]
assert message["payload"] == HexBytes(payloads[1])
assert message["topic"] == HexBytes(topic)
def test_shh_sync_filter(web3, skip_if_testrpc):
skip_if_testrpc(web3)
sender = web3.shh.new_key_pair()
sender_pub = web3.shh.get_public_key(sender)
receiver = web3.shh.new_key_pair()
receiver_pub = web3.shh.get_public_key(receiver)
topic = '0x13370000'
payloads = [web3.toHex(text="test message :)"), web3.toHex(text="2nd test message")]
shh_filter = web3.shh.new_message_filter({
'privateKeyID': receiver,
'sig': sender_pub,
'topics': [topic]
})
web3.shh.post({
'sig': sender,
'powTarget': 2.5,
'powTime': 2,
'payload': payloads[0],
'pubKey': receiver_pub
})
time.sleep(1)
web3.shh.post({
'sig': sender,
'powTarget': 2.5,
'powTime': 2,
'payload': payloads[1],
'topic': topic,
'pubKey': receiver_pub
})
time.sleep(1)
received_messages = shh_filter.get_new_entries()
assert len(received_messages) == 1
message = received_messages[0]
assert message["payload"] == HexBytes(payloads[1])
assert message["topic"] == HexBytes(topic)
def test_shh_async_filter_deprecated(web3, skip_if_testrpc):
skip_if_testrpc(web3)
received_messages = []
with pytest.warns(DeprecationWarning) as warnings:
sender = web3.shh.newKeyPair()
sender_pub = web3.shh.getPublicKey(sender)
receiver = web3.shh.newKeyPair()
receiver_pub = web3.shh.getPublicKey(receiver)
topic = '0x13370000'
payloads = [web3.toHex(text="test message :)"), web3.toHex(text="2nd test message")]
shh_filter = web3.shh.newMessageFilter({
'privateKeyID': receiver,
'sig': sender_pub,
'topics': [topic]
}, poll_interval=0.5)
watcher = shh_filter.watch(received_messages.extend)
web3.shh.post({
'sig': sender,
'powTarget': 2.5,
'powTime': 2,
'payload': payloads[0],
'topic': topic,
'pubKey': receiver_pub
})
time.sleep(1)
web3.shh.post({
'sig': sender,
'powTarget': 2.5,
'powTime': 2,
'payload': payloads[1],
'pubKey': receiver_pub
})
time.sleep(1)
assert len(received_messages) == 1
message = received_messages[0]
assert message["payload"] == HexBytes(payloads[0])
assert message["topic"] == HexBytes(topic)
assert len(warnings) == 5
watcher.stop()
def test_shh_async_filter(web3, skip_if_testrpc):
skip_if_testrpc(web3)
received_messages = []
sender = web3.shh.new_key_pair()
sender_pub = web3.shh.get_public_key(sender)
receiver = web3.shh.new_key_pair()
receiver_pub = web3.shh.get_public_key(receiver)
topic = '0x13370000'
payloads = [web3.toHex(text="test message :)"), web3.toHex(text="2nd test message")]
shh_filter = web3.shh.new_message_filter({
'privateKeyID': receiver,
'sig': sender_pub,
'topics': [topic]
}, poll_interval=0.5)
watcher = shh_filter.watch(received_messages.extend)
web3.shh.post({
'sig': sender,
'powTarget': 2.5,
'powTime': 2,
'payload': payloads[0],
'topic': topic,
'pubKey': receiver_pub
})
time.sleep(1)
web3.shh.post({
'sig': sender,
'powTarget': 2.5,
'powTime': 2,
'payload': payloads[1],
'pubKey': receiver_pub
})
time.sleep(1)
assert len(received_messages) == 1
message = received_messages[0]
assert message["payload"] == HexBytes(payloads[0])
assert message["topic"] == HexBytes(topic)
watcher.stop()
def test_shh_remove_filter_deprecated(web3, skip_if_testrpc):
skip_if_testrpc(web3)
with pytest.warns(DeprecationWarning):
receiver = web3.shh.newKeyPair()
receiver_pub = web3.shh.getPublicKey(receiver)
payload = web3.toHex(text="test message :)")
shh_filter = web3.shh.newMessageFilter({'privateKeyID': receiver})
web3.shh.post({
'powTarget': 2.5,
'powTime': 2,
'payload': payload,
'pubKey': receiver_pub
})
time.sleep(1)
message = shh_filter.get_new_entries()[0]
assert message["payload"] == HexBytes(payload)
assert web3.shh.deleteMessageFilter(shh_filter.filter_id)
try:
web3.shh.getMessages(shh_filter.filter_id)
assert False
except Exception:
assert True
def test_shh_remove_filter(web3, skip_if_testrpc):
skip_if_testrpc(web3)
receiver = web3.shh.new_key_pair()
receiver_pub = web3.shh.get_public_key(receiver)
payload = web3.toHex(text="test message :)")
shh_filter = web3.shh.new_message_filter({'privateKeyID': receiver})
web3.shh.post({
'powTarget': 2.5,
'powTime': 2,
'payload': payload,
'pubKey': receiver_pub
})
time.sleep(1)
message = shh_filter.get_new_entries()[0]
assert message["payload"] == HexBytes(payload)
assert web3.shh.delete_message_filter(shh_filter.filter_id)
try:
web3.shh.get_messages(shh_filter.filter_id)
assert False
except Exception:
assert True
|
from django.contrib import admin
from populous.categories.models import Category
class CategoryAdmin(admin.ModelAdmin):
fieldsets = (
(None, {'fields': ('parent', 'name')}),
)
list_display = ('representation',)
search_fields = ('representation',)
admin.site.register(Category, CategoryAdmin)
|
import { TWEETS_LOADED } from './constants';
export const initialState = {
movieStarTweets: [],
musicStarTweets: [],
};
const homeReducer = (state = initialState, action) => {
switch (action.type) {
case TWEETS_LOADED: {
return {
...state,
movieStarTweets: action.movieStarTweets,
musicStarTweets: action.musicStarTweets,
};
}
default:
return state;
}
};
export default homeReducer;
|
"use strict";
/*:
* @plugindesc 自作の一枚画像をウィンドウに適用します。
* @author ei1chi
*
* @help このプラグインにはプラグインコマンドはありません。
*
* ============================================================
* OriginalWindowSkin.js
* v0.1.0
* ============================================================
* 自作の一枚画像をウィンドウの見た目に適用するプラグインです。
* ツクールの標準機能では不可能だった、自由な見た目のウィンドウを作ることができます。
* 代わりにウィンドウの開閉動作がフェードイン・アウトに置き換わっていますので、ご了承ください。
*
* ※現在はメッセージウィンドウのみ対応。
* 今後、対応ウィンドウを追加予定。
*
* ------------------------------------------------------------
* 使い方
* ------------------------------------------------------------
* ウィンドウとして使いたい画像を、img/pictures/内に
* "Window_Original.png"として追加します。※今後変更される可能性があります
*
* メッセージウィンドウのサイズは標準で"816x180"ピクセルです。
* このサイズでの画像作成をお勧めします。
*
* ------------------------------------------------------------
* 注意点
* ------------------------------------------------------------
* ・デプロイメント時「未使用ファイルを含まない」オプションを有効にすると
* スキン画像が出力されません!
* 手動でデプロイメント先にコピーする必要があります。
* ・公式ツール"MADO"によるウィンドウ拡張との併用は未検証です(検証予定)。
* ・その他、ウィンドウ系プラグインと併用すると問題が発生する可能性があります。
*
* ------------------------------------------------------------
* 使用許諾
* ------------------------------------------------------------
* ・使用の際に連絡およびクレジット表記は不要です。
* ・自由に改変して利用して構いません。
*/
(function (_) {
// 画像ファイル読み込み(キャッシュに投入)
Window_Base.prototype.loadWindowskin = function () {
this.originalSkin = ImageManager.loadPicture("Window_Original");
this.windowskin = ImageManager.loadSystem("Window");
};
var __initialize = Window_Message.prototype.initialize;
Window_Message.prototype.initialize = function () {
__initialize.call(this);
this._refreshAllParts();
};
// 背景画像の処理を削除
Window_Message.prototype._refreshBack = function () { };
// 画像更新処理を変更
Window_Message.prototype._refreshFrame = function () {
var w = this._width;
var h = this._height;
var bitmap = new Bitmap(w, h);
this._windowFrameSprite.bitmap = bitmap;
this._windowFrameSprite.setFrame(0, 0, w, h);
if (this.originalSkin !== null) {
bitmap.blt(this.originalSkin, 0, 0, w, h, 0, 0);
}
};
// openness設定時の挙動を変更(重要ポイント)
Object.defineProperty(Window_Message.prototype, "openness", {
get: function () {
return this._openness;
},
set: function (value) {
if (this._openness !== value) {
this._openness = value.clamp(0, 255);
this._windowFrameSprite.opacity = value;
}
},
configurable: true
});
})();
|
import React from 'react'
import {render, fireEvent, within} from '@testing-library/react'
import Usage from '../final/09'
// import Usage from '../exercise/09'
test('renders', () => {
const {getByText, getByLabelText, container} = render(<Usage />)
const plus = getByText(/add item/i)
fireEvent.click(plus)
fireEvent.click(plus)
fireEvent.click(plus)
fireEvent.click(plus)
const orangeInput = getByLabelText(/orange/i)
const orangeContainer = getByText(/orange/i).closest('li')
const inOrange = within(orangeContainer)
fireEvent.change(orangeInput, {target: {value: 'sup dawg'}})
fireEvent.click(inOrange.getByText('remove'))
const allLis = container.querySelectorAll('li')
Array.from(allLis).forEach(li => {
const label = li.querySelector('label')
const input = li.querySelector('input')
expect(label.textContent).toBe(input.value)
})
})
|
/**
* Created by Peter Baus on 11/3/2015.
*/
$(document).ready(function(){
start();
});
function start() {
var pockeTest = $.pockeTest();
pockeTest.define.action('wait 2 seconds', function (assert) {
assert.wait(2000);
});
pockeTest.group('Testing of form');
pockeTest.test('Test if we could send the form')
.then(function (assert) {
$('#website').val('http://www.example.com');
assert.done();
})
.then('wait 2 seconds')
.then(function (assert) {
assert.navigate('testing-example2.html');
})
.then(function (assert) {
$('#message').html('Some example text');
assert.wait(1500);
})
.then(function (assert) {
$('#submitbutton').click();
assert.done();
});
//
// pockeTest.define.action('set url', function(assert) {
// assert.setUser($('#cm-user-actions > span:eq(1)').text().trim());
//
// assert.done();
// });
// pockeTest.define.action('wait for chat peer-to-peer connection',function(assert){
// assert.waitFor("peer-to-peer connection", function() {
// if (window.app._peer.connections.hasOwnProperty(assert.get('contactPeerId'))) {
//
// for (var i = 0; i < window.app._peer.connections[assert.get('contactPeerId')].length; i++) {
// var connection = window.app._peer.connections[assert.get('contactPeerId')][i];
//
// if (connection.label == 'chat' && connection.open) {
// return true;
// }
// }
// }
// return false;
// });
//
// });
// pockeTest.define.action('other user go offline', function(assert) {
// console.debug('other user go offline');
// assert.waitFor('other user go offline', function() {
// var ret = false;
// $('#cm-contact-list-contacts > li').each(function() {
// if ($(this).find('a').attr('data-userid') == assert.get('contactUserId')) {
//
// if (!$(this).hasClass('online')) {
// ret = true;
//
// }
//
// }
// });
//
// return ret;
// });
// });
// pockeTest.define.action('other user go online', function(assert) {
// console.debug('other user go online');
// assert.waitFor('other user go online', function() {
// var ret = false;
// $('#cm-contact-list-contacts > li').each(function() {
// if ($(this).find('a').attr('data-userid') == assert.get('contactUserId')) {
//
// if ($(this).hasClass('online')) {
// ret = true;
// }
//
// }
// });
//
// return ret;
// });
// });
//
// pockeTest.group("Chat");
// pockeTest.test("Chat message").then('set user name').user('test').then(function(assert){
//
// assert.waitFor("incoming message", function(){
// if ($(".cm-chat-container").find('div.message').length > 0) {
// return true;
// }
// });
//
// }).user('test1').then(function(assert){
//
// assert.equal(1,1);
//
// $('#cm-contact-list-contacts > li').each(function() {
// if ($(this).find('span.username:first').text() == 'test') {
// $(this).find('a').click();
// assert.set('contactUserId',$(this).find('a').attr('data-userid'));
// assert.set('contactPeerId',$(this).find('a').attr('data-peerid'));
//
// assert.done();
// return false;
// }
// });
//
// }).then('wait for peer-to-peer connection',function(assert){
//
// $('input.message-input').val("Sample text");
//
// assert.waitFor("peer-to-peer connection", function() {
// if (window.app._peer.connections.hasOwnProperty(assert.get('contactPeerId'))) {
//
// for (var i = 0; i < window.app._peer.connections[assert.get('contactPeerId')].length; i++) {
// var connection = window.app._peer.connections[assert.get('contactPeerId')][i];
//
// if (connection.label == 'chat' && connection.open) {
// return true;
// }
// }
// }
// return false;
// });
//
// }).then('post sample text',function(assert){
//
// var sendButton = $('button.message-send[data-userid=' + assert.get('contactUserId') + ']');
// if (sendButton) {
// $('input.message-input').val("Sample text");
// sendButton.click();
// }
// assert.done();
//
// }).user('test').then('find user with incoming message',function(assert) {
//
// $('#cm-contact-list-contacts > li').each(function() {
//
// if ($(this).find('span.uc').text() != '') {
// $(this).find('a').click();
// assert.set('contactUserId',$(this).find('a').attr('data-userid'));
// assert.set('contactPeerId',$(this).find('a').attr('data-peerid'));
//
// assert.done();
// return false;
// }
// });
//
//
// }).then('wait for message to appear on screen',function(assert) {
//
// assert.waitFor("incoming message", function(){
// if ($(".cm-chat-container").find('div.message').length > 0) {
// return true;
// } else {
// return false;
// }
// });
//
// }).then('post reply text',function(assert) {
//
// var sendButton = $('button.message-send[data-userid=' + assert.get('contactUserId') + ']');
// if (sendButton) {
// $('input.message-input').val("Reply text");
// sendButton.click();
// }
// assert.done();
//
// }).user('test1').then('wait for reply message',function(assert) {
//
// assert.failWhen("there is more than one chat container", function() {
// if (false) {
// return true;
// }
// });
//
// assert.waitFor("reply message", function(){
// var messageArrived = false;
// $(".cm-chat-container").find('div.message').each(function() {
// $(this).find('.bubble').each(function() {
// if ($(this).text().trim() == 'Reply text') {
// messageArrived = true;
// }
// });
//
// });
//
// return messageArrived;
// });
//
// }).allUsers().then(function(assert) {
//
// assert.done();
//
// });
//
// pockeTest.test("Chat message after refresh").then('set user name').user('test').then(function(assert){
//
// assert.waitFor("incoming message", function(){
// if ($(".cm-chat-container").find('div.message').length > 0) {
// return true;
// }
// });
//
// }).user('test1').then(function(assert){
//
// assert.equal(1,1);
//
// $('#cm-contact-list-contacts > li').each(function() {
// if ($(this).find('span.username:first').text() == 'test') {
// $(this).find('a').click();
// assert.set('contactUserId',$(this).find('a').attr('data-userid'));
// assert.set('contactPeerId',$(this).find('a').attr('data-peerid'));
//
// assert.done();
// return false;
// }
// });
//
// }).then('wait for peer-to-peer connection',function(assert){
//
// $('input.message-input').val("Sample text 2");
//
// assert.waitFor("peer-to-peer connection", function() {
// if (window.app._peer.connections.hasOwnProperty(assert.get('contactPeerId'))) {
//
// for (var i = 0; i < window.app._peer.connections[assert.get('contactPeerId')].length; i++) {
// var connection = window.app._peer.connections[assert.get('contactPeerId')][i];
//
// if (connection.label == 'chat' && connection.open) {
// return true;
// }
// }
// }
// return false;
// });
//
// }).then('post sample text',function(assert){
//
// var sendButton = $('button.message-send[data-userid=' + assert.get('contactUserId') + ']');
// if (sendButton) {
// $('input.message-input').val("Sample text 2");
// sendButton.click();
// }
// assert.done();
//
// }).user('test').then('find user with incoming message',function(assert) {
//
// $('#cm-contact-list-contacts > li').each(function() {
//
// if ($(this).find('span.username:first').text() == 'test1') {
// $(this).find('a').click();
// assert.set('contactUserId',$(this).find('a').attr('data-userid'));
// assert.set('contactPeerId',$(this).find('a').attr('data-peerid'));
//
// assert.done();
// return false;
// }
// });
//
// }).then('wait for message to appear on screen',function(assert) {
//
// assert.waitFor("incoming message", function(){
// var messageArrived = false;
// $(".cm-chat-container").find('div.message').each(function() {
// $(this).find('.bubble').each(function() {
// if ($(this).text().trim() == 'Sample text 2') {
// messageArrived = true;
// }
// });
//
// });
//
// return messageArrived;
// });
//
// }).then('post reply text',function(assert) {
//
// var sendButton = $('button.message-send[data-userid=' + assert.get('contactUserId') + ']');
// if (sendButton) {
// $('input.message-input').val("Reply text 2");
// sendButton.click();
// }
// assert.done();
//
// }).user('test1').then('wait for reply message',function(assert) {
//
// assert.failWhen("there is more than one chat container", function() {
// if (false) {
// return true;
// }
// });
//
// assert.waitFor("reply message", function(){
// var messageArrived = false;
// $(".cm-chat-container").find('div.message').each(function() {
// $(this).find('.bubble').each(function() {
// if ($(this).text().trim() == 'Reply text 2') {
// messageArrived = true;
// }
// });
//
// });
//
// return messageArrived;
// });
//
// }).then(function(assert) {
//
// assert.reload();
//
// }).user('test').then('other user go offline').then('other user go online').then('wait for sending', function(assert) {
//
// assert.waitFor('awailable button', function() {
// if ($('button.message-send[data-userid=' + assert.get('contactUserId') + ']').hasClass('online')) {
// return true;
// }
// });
//
// }).then('write message', function(assert) {
//
// var sendButton = $('button.message-send[data-userid=' + assert.get('contactUserId') + ']');
// if (sendButton) {
// $('input.message-input').val("Other text");
//
// }
//
// assert.waitFor('sending of message', function() {
// sendButton.click();
// if ($('input.message-input').val() == '') {
// return true;
// }
// });
//
// }).user('test1').then('wait for reply message',function(assert) {
//
// assert.failWhen("there is more than one chat container", function() {
// if (false) {
// return true;
// }
// });
//
// assert.waitFor("other message", function(){
// $('#cm-contact-list-contacts > li').each(function() {
//
// if ($(this).find('span.username:first').text() == 'test') {
// $(this).find('a').click();
//
// return false;
// }
// });
//
// var messageArrived = false;
// $(".cm-chat-container").find('div.message').each(function() {
// $(this).find('.bubble').each(function() {
// if ($(this).text().trim() == 'Other text') {
// messageArrived = true;
// }
// });
//
// });
//
// return messageArrived;
// });
//
// }).then('wait for sending of final message', function(assert) {
// var sendButton = $('button.message-send[data-userid=' + assert.get('contactUserId') + ']');
// if (sendButton) {
// $('input.message-input').val("Final message");
// }
//
// assert.waitFor('sending of message', function() {
// console.debug("CHECK",assert.get('contactUserId'));
// sendButton.click();
// if ($('input.message-input').val() == '') {
// return true;
// }
// });
//
// }).user('test').then('wait for final message', function(assert) {
//
// assert.waitFor("final message receiving", function(){
// var messageArrived = false;
// $(".cm-chat-container").find('div.message').each(function() {
// $(this).find('.bubble').each(function() {
// if ($(this).text().trim() == 'Final message') {
// messageArrived = true;
// }
// });
//
// });
//
// return messageArrived;
// });
//
// });
//
//
// pockeTest.group('Notifications');
// pockeTest.test("Send notification").user('test').then('other user go offline').user('test1').then(function(assert) {
//
// assert.reload();
//
// }).user('test').then('open notification popup', function(assert) {
//
// $('a[data-action="ui.notification.popup"]').each(function() {
// if ($(this).attr('data-userid') == assert.get('contactUserId')) {
// $(this).click();
//
// return false;
// }
// });
//
// assert.done();
//
// }).then('wait for dialog', function(assert) {
// assert.waitFor('dialog to show', function() {
// if ($('div#notify-user')) {
// return true;
// }
// });
// }).then('send notification', function(assert) {
// $('#notify-user').find('#notification-5:first').click();
// $('#notify-user').find('#customMessageCollapse:first').find('textarea:first').html('This is custom testing notification.');
// $('#notify-user').find('button[data-action="notification.send"]').click();
//
// assert.done();
// }).then('wait for confirm modal', function(assert) {
//
// assert.waitFor('confirm modal', function() {
// if ($('#simple-modal').length) {
// return true;
// }
// });
//
// }).then('close modal', function(assert) {
//
// $('#simple-modal').find('button[data-action="ui.modal.close"]:first').click();
//
// assert.done();
//
// }).user('test1').then('click on other user',function(assert) {
//
// $('#cm-contact-list-contacts > li').each(function() {
//
// if ($(this).find('span.username:first').text() == 'test') {
// $(this).find('a').click();
//
// assert.done();
// return false;
// }
// });
//
// }).then('check notification status', function(assert) {
//
// assert.waitFor('1 notification', function() {
// if ($('.navbar-contactlist:first li.notificationManager:first .badge.notifications:first').text() == '1') {
// console.debug($('.navbar-contactlist:first li.notificationManager:first .badge.notifications:first').text());
// return true;
// }
// });
//
// }).then('open notification', function(assert) {
//
// $('.navbar-contactlist:first li.notificationManager:first a:first').click();
//
// assert.done();
//
// }).then('read notification', function(assert) {
//
// assert.waitFor('notification exists', function() {
// var ret = false;
// $('#notification-area #notificationList li').each(function() {
// if ($(this).find('.notification-message:first').text() == 'This is custom testing notification.' && $(this).find('.notification-sender:first').text() == 'test') {
// ret = true;
// }
// });
// return ret;
// });
//
// }).then('delete notification', function(assert) {
//
// $('#notification-area #notificationList li').each(function() {
// if ($(this).find('.notification-message:first').text() == 'This is custom testing notification.' && $(this).find('.notification-sender:first').text() == 'test') {
// $(this).find('button[data-action="notification.delete"]').click();
// }
// });
//
// assert.done();
//
// }).then('wait for confirm modal', function(assert) {
//
// assert.waitFor('confirm modal', function() {
// if ($('#simple-modal')) {
// return true;
// }
// });
//
// }).then('close modal', function(assert) {
//
// $('#simple-modal').find('button[data-action="ui.modal.close"]:first').click();
//
// assert.done();
//
// }).then('check if notification is deleted', function(assert) {
//
// assert.waitFor('notification is deleted', function() {
// var ret = true;
// $('#notification-area #notificationList li').each(function() {
// if ($(this).find('.notification-message:first').text() == 'This is custom testing notification.' && $(this).find('.notification-sender:first').text() == 'test') {
// ret = false;
// }
// });
// return ret;
// });
//
// }).user('test').then('other user go online').then('wait', function(assert) {
//
// assert.wait(12000);
//
// }).allUsers().then(function(assert) {
//
// assert.done();
//
// });
//
//
//
// pockeTest.group('Calling');
// pockeTest.test('Init call').then('set user name').user('test').then('click on contact',function(assert){
//
// $('#cm-contact-list-contacts > li').each(function() {
// if ($(this).find('span.username:first').text() == 'test1') {
// $(this).find('a').click();
// assert.set('contactUserId',$(this).find('a').attr('data-userid'));
// assert.set('contactPeerId',$(this).find('a').attr('data-peerid'));
//
// assert.done();
// return false;
// }
// });
//
// }).then('wait for chat peer-to-peer connection').then('init call',function(assert) {
//
// $("section[data-userid='"+assert.get('contactUserId')+"'] .js-action[data-action='call.init']:first").click();
//
// assert.done();
// }).user('test1').then('detect modal',function(assert) {
// assert.waitFor('incoming call', function() {
// if ($("body #call-modal").length > 0) {
// return true;
// }
// });
// }).then('accept call',function(assert) {
// $("body #call-modal .js-action[data-action='call.accept']:first").click();
//
// assert.done();
// }).user('test').then(function(assert) {
// assert.waitFor('accepting call', function() {
// if ($("body #call-modal").length == 0) {
// return true;
// }
// });
// }).allUsers().then(function(assert) {
// assert.waitFor('open video window', function() {
// if ($('.cm-av-frame').hasClass('open')) {
// return true;
// }
// })
// });
}
|
const mix = require('laravel-mix');
/*
|--------------------------------------------------------------------------
| Mix Asset Management
|--------------------------------------------------------------------------
|
| Mix provides a clean, fluent API for defining some Webpack build steps
| for your Laravel application. By default, we are compiling the Sass
| file for the application as well as bundling up all the JS files.
|
*/
mix.js('resources/js/app.js', 'public/js')
.sass('resources/sass/app.scss', 'public/css')
.copyDirectory('resources/img', 'public/img')
.options({ processCssurls: false });
|
Cypress.Commands.add('seedAndVisit', (seedData = 'fixture:todos') => {
cy.server();
cy.route('GET', '/api/todos', seedData);
cy.visit('/');
});
|
export { default as naturalEarth1 } from './naturalEarth1'
export { default as mercator } from './mercator'
export { default as equirectangular } from './equirectangular'
export { default as orthographic } from './orthographic'
|
//////////////////////////////////////////////////////////////////////////////
// Debug
//////////////////////////////////////////////////////////////////////////////
import utils from './Utils';
/**
* The debug class draws helpful info to the canvas.
* Sections:
* - time: time for drawing
* - zoom: zoom and drag info
* - position: position of mouse, etc
* - n: number of features in slots, etc
* @private
*/
class Debug {
constructor(viewer, options = {}) {
this.viewer = viewer;
this._data = {};
this._sections = utils.defaultFor(options.sections, []);
// Create object for each section
for (const section of this.sections) {
this.data[section] = {};
}
}
get sections() {
return this._sections;
}
get data() {
return this._data;
}
// // DEBUG INFO EXAMPLE
// if (this.debug) {
// axis = axis.toUpperCase();
// this.debug_data.zoom['d' + axis] = JSV.round(axis_diff);
// this.debug_data.zoom['v' + axis] = JSV.round(value);
// this.debug_data.zoom['r' + axis] = JSV.round(axis_ratio);
// }
// Other Example
// let start_time = new Date().getTime();
// ....code and stuff....
// if (this.debug) {
// this.debug_data.time['draw'] = JSV.elapsedTime(start_time);
// this.draw_debug(this.legend.bottom());
// }
//
// Draws any information in 'data' onto the left side of the viewer
draw(x = 10, y = 20) {
const canvas = this.viewer.canvas;
canvas.clear('debug');
const ctx = canvas.context('debug');
const data = this._data;
const sections = this._sections;
ctx.font = '10pt Sans-Serif';
const color = this.viewer.settings.backgroundColor.copy();
ctx.fillStyle = color.invert().rgbaString;
const lineHeight = 18;
ctx.textAlign = 'left';
// const section_keys = this.debug === true ? Object.keys(data) : this.debug;
let i = 0;
sections.forEach(function(sectionKey) {
const dataKeys = Object.keys(data[sectionKey]);
dataKeys.forEach(function(dataKey) {
ctx.fillText((`${sectionKey}|${dataKey}: ${data[sectionKey][dataKey]}`), x, y + (lineHeight * i));
i += 1;
});
});
}
}
export default Debug;
|
var gulp = require('gulp');
var watch = require('gulp-watch');
var shell = require('gulp-shell')
var paths = {
'src':['./models/**/*.js','./routes/**/*.js', 'keystone.js', 'package.json']
};
gulp.task('runKeystone', shell.task('node keystone.js'));
gulp.task('watch', [
]);
gulp.task('default', ['watch', 'runKeystone']);
|
const { readRoomDiagram } = require("./readRoomDiagram.js");
const { processRoomDiagram } = require("./processRoomDiagram.js");
async function doPart1(fileName) {
const data = await readRoomDiagram(fileName);
return processRoomDiagram(data, true);
}
exports.doOrganizeAmphipodsPart1 = doPart1;
async function doPart2(fileName) {
const data = await readRoomDiagram(fileName);
return processRoomDiagram(data);
}
exports.doOrganizeAmphipodsPart2 = doPart2;
|
const config = require('./../config');
const crawler = require('./crawler');
const parser = require('./parser');
const tracker = require('./tracker');
const knex = require('knex')(config.db);
const getCount = async () => {
const [count] = await knex('torrents').count('infohash');
const [count2] = await knex('torrents')
.count('infohash')
.whereNull('trackerUpdated');
const [count3] = await knex('torrents')
.count('infohash')
.whereNull('searchUpdated');
console.log(`Total Torrents: ${count['count(`infohash`)']}`);
console.log(`Torrents without Tracker: ${count2['count(`infohash`)']}`);
console.log(`Torrents not in Search: ${count3['count(`infohash`)']}`);
setTimeout(() => getCount(), 10000);
};
const addTorrent = async (infohash, rinfo) => {
try {
const records = await knex('torrents').where({ infohash: infohash.toString('hex') });
if (records.length === 0 || !records[0].name) {
parser(infohash, rinfo, knex);
}
} catch (error) {
if (config.debug) {
console.log(error);
}
}
};
crawler(addTorrent);
tracker(knex);
getCount();
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
try:
# Change main dir to this (need for Pentest Box)
import os
os.path.abspath(__file__)
from Classes import (Credits,
OKadminFinderClass,
MessengerClass)
import argparse
from colorama import Fore, Back, Style
import random
import requests
import socket
import socks
import sys
import time
from tqdm import tqdm
import urllib.request, urllib.error, urllib.parse
from urllib.request import urlopen
# Get Messenger class to print information
messenger = MessengerClass.Messenger()
except():
exit('\n\t[x] Session Cancelled; Something wrong with import modules')
# Get credits and print it
messenger.writeMessage(Credits.getCredits()[0], 'green')
# Get main class object
OKadminFinder = OKadminFinderClass.OKadminFinder()
parser = argparse.ArgumentParser(formatter_class=lambda prog: argparse.HelpFormatter(prog, max_help_position=30, width=90))
parser.add_argument("-u", "--url", default=False,
help="Target URL (e.g. 'www.example.com' or 'example.com')")
parser.add_argument("-t", "--tor", action='store_true', default=False,
help="Use Tor anonymity network")
parser.add_argument("-p", "--proxy", default=False,
help="Use an HTTP proxy (e.g '127.0.0.1:8080')")
parser.add_argument("-r", "--random-agent", action='store_true', default=False,
dest='rand', help="Use randomly selected User-Agent")
parser.add_argument("-v", "--verbose", action='store_true', default=False,
help="Display more informations")
parser.add_argument("-i", "--interactive", action='store_true', default=False,
help="Interactive interface" + Fore.RED+Style.BRIGHT + "[other arguments not required]")
if len(sys.argv) <= 1:
parser.print_usage()
sys.exit(1)
else:
args = parser.parse_args()
# site = 'testphp.vulnweb.com'
proxies = ""
headers = {'user-agent': 'OKadminFinder/%s' % Credits.getCredits()[1]}
OKadminFinder.header = headers
def url(site):
try:
if OKadminFinder.checkUrl(site, proxies):
messenger.writeMessage('\n Site %s is stable\n' % site, 'green')
urls = tqdm(OKadminFinder.getUrls('LinkFile/adminpanellinks.txt'), bar_format="{l_bar}{bar}|{n_fmt}/{total_fmt}{postfix}")
else:
messenger.writeMessage(' Something wrong with url', 'red')
urls = tqdm(OKadminFinder.getUrls('LinkFile/adminpanellinks.txt'), bar_format="{bar}")
exit(SystemExit)
# Get links for checking
# Counters for total links, and admin panel find
totalCount = len(urls)
adminCount = 0
# Checking all links
for url in urls:
# Create test link with getting params from site and links.txt file
reqLink = OKadminFinder.createReqLink(site, url, proxies)
# messenger.writeMessage('\t[#] Checking http://' + reqLink, 'yellow')
urls.set_description(Fore.WHITE + Style.NORMAL + " Processing ...")
# Test created link for HTTPerrors. If not error - potential admin panel
if OKadminFinder.checkUrl(reqLink, proxies):
adminCount += 1
messenger.writeMessage(' %s %s' % ('\n [✔] http://' + reqLink, 'Admin page found!\n'), 'bright')
# Stopped process? and waiting for input for continue
#messenger.writeInput(' Press enter to continue scanning.\n')
# If HTTPerrors continue testing other links
else:
continue
# Write last information about scanning with counters
messenger.writeMessage('\n\n Completed \n', 'green')
messenger.writeMessage(str(adminCount) + ' Admin pages found', 'white')
messenger.writeMessage(str(totalCount) + ' total pages scanned', 'white')
messenger.writeInput(' [/] Scanning over; Press Enter to Exit', 'green')
messenger.writeMessage('', 'white')
except (KeyboardInterrupt, SystemExit):
messenger.writeMessage('\n\t[x] Session Cancelled', 'red')
urls.close()
messenger.writeMessage('', 'white')
except():
messenger.writeMessage('\n\t[x] Session Cancelled; Unknown error', 'red')
messenger.writeMessage('', 'white')
def rangent():
useragent = "LinkFile/user-agent.txt"
ua = open(useragent, 'r').read().splitlines()
rua = random.choice(ua)
headers = {'user-agent': rua}
OKadminFinder.header = headers
return OKadminFinder.header
def tor():
socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, 'localhost', 9050)
socket.socket = socks.socksocket
urllib.request.urlopen
def proxy():
args.proxy=str(args.proxy)
proxies ={
'http': args.proxy,
'https': args.proxy,
}
try:
ht = args.proxy.split(':')
pr = int(ht[1])
s = socks.socksocket()
s.set_proxy(socks.HTTP, ht[0], pr)
socket.socket = socks.socksocket
urllib.request.urlopen
except (IndexError, IndentationError):
messenger.writeMessage('\n\tPlease check the format of your proxy | reminder: 127.0.0.1:8080 ', 'red')
quit(0)
try:
print(Fore.BLUE + '\tChecking Http proxy...', end="\r")
time.sleep(1)
rp = requests.get('http://testphp.vulnweb.com', proxies=proxies, timeout=10)
print(Fore.BLUE + '\tChecking Http proxy...', Fore.GREEN+Style.BRIGHT + 'OK\n' + Fore.WHITE + Style.NORMAL)
except requests.RequestException:
print(Fore.BLUE + '\tChecking Http proxy...', Fore.RED + Style.BRIGHT + 'BAD\n' + Fore.WHITE + Style.NORMAL)
messenger.writeMessage('\n ╔═══[!] Connection Troubles', 'red')
print(' ║')
print(' ╚══►' + Fore.BLUE + '[Note]' + Fore.YELLOW + '╾╥──╸ Please check your connection, proxy or tor')
print(' ╟──╸ ' + Fore.YELLOW+Style.BRIGHT + 'don\'t add' + Fore.YELLOW + Style.NORMAL + ' \'http://\' or \'https://\'')
print(' ╙──╸ ' + Fore.YELLOW + Style.NORMAL + 'check that you have written the url correctly\n')
quit(0)
return proxies
def ipinf():
ip = requests.get('http://ifconfig.co/ip', proxies=proxies, headers=OKadminFinder.header).text
cc = requests.get('http://ifconfig.co/country', proxies=proxies, headers=OKadminFinder.header).text
iso = requests.get('http://ifconfig.co/country-iso', proxies=proxies, headers=OKadminFinder.header).text
city = requests.get('http://ifconfig.co/city', proxies=proxies, headers=OKadminFinder.header).text
print(''' ┆
├───[''' + Fore.CYAN + '''IP address Infos:''' + Fore.YELLOW + ''']
┆''');
print(' ├──► '+ Fore.BLUE +'Country: '+ cc + Fore.YELLOW +' ├───► '+ Fore.BLUE +'IP: ' + ip + Fore.YELLOW + ' ├────► '+ Fore.BLUE +'Country ISO: ' + iso + Fore.YELLOW + ' └────► '+ Fore.BLUE +'City: ' + city)
print('')
def vipinf():
ip = requests.get('http://ifconfig.co/ip', proxies=proxies, headers=OKadminFinder.header).text
cc = requests.get('http://ifconfig.co/country', proxies=proxies, headers=OKadminFinder.header).text
iso = requests.get('http://ifconfig.co/country-iso', proxies=proxies, headers=OKadminFinder.header).text
city = requests.get('http://ifconfig.co/city', proxies=proxies, headers=OKadminFinder.header).text
print('''
┌───[''' + Fore.CYAN + '''IP address Infos:''' + Fore.YELLOW + ''']
┆''');
print(' ├──► ' + Fore.BLUE + 'Country: ' + cc + Fore.YELLOW + ' ├───► ' + Fore.BLUE + 'IP: ' + ip + Fore.YELLOW + ' ├────► ' + Fore.BLUE + 'Country ISO: ' + iso + Fore.YELLOW + ' └─────► '+ Fore.BLUE +'City: ' + city)
print('')
def hos():
site = args.url
rh = requests.get('http://'+site,proxies=proxies, headers=OKadminFinder.header)
di = socket.gethostbyname(site)
print(Fore.CYAN + Style.BRIGHT + '\tServer: ' + Fore.YELLOW + rh.headers['Server'] + '\t\t' + Fore.CYAN + Style.BRIGHT +'Hostname: ' + Fore.YELLOW + di + '\n')
try:
xf = dict(rh.headers).get("x-frame-options")
xf = str(xf)
print(Fore.CYAN + Style.BRIGHT +'\tX-Powered-By: ' + Fore.YELLOW + rh.headers['X-Powered-By'] + '\t\t' + Fore.CYAN + Style.BRIGHT + 'X-Frame-Options: ' + Fore.YELLOW + xf + '\n\n')
except KeyError:
pass
def interactive():
try:
# Random UserAgent
#Useragents are from: https://techblog.willshouse.com/2012/01/03/most-common-user-agents/
try:
print(Fore.BLUE + '\tGetting random user-agent...', end="\r")
time.sleep(1)
useragent = "LinkFile/user-agent.txt"
ua = open(useragent, 'r').read().splitlines()
rua = random.choice(ua)
headers = {'user-agent': rua}
print(Fore.BLUE + '\tGetting random user-agent...', Fore.GREEN+Style.BRIGHT + 'DONE\n' + Fore.WHITE + Style.NORMAL)
except:
headers = {'user-agent': 'OKadminFinder/%s' % Credits.getCredits()[1]}
pass
OKadminFinder.header = headers
# Additional params
# if not messenger.writeInputWithYesNo(Fore.YELLOW + ' Do you want use default params?'):
# timeout = messenger.writeInput(Fore.YELLOW + ' Change timeout. Please write value in seconds: ' + Fore.GREEN)
# OKadminFinder.timeout = timeout
#Updater
#network params
choice=''
print(Fore.YELLOW + ' ┌───[' + Fore.CYAN + 'Network settings:' + Fore.YELLOW + ']');
while (choice not in ['1','2','3','tor','proxy']):
choice=input(Fore.YELLOW + ''' ┊
├╼[1] tor
├╼[2] proxy
├╼[3] nothing
┊
└───╼''' + Fore.RED + ''' Please choose one option''' + Fore.YELLOW + ''' ~$ ''')
if choice == '1' or choice == 'tor':
socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, 'localhost', 9050)
socket.socket = socks.socksocket
urllib.request.urlopen
proxies=""
elif choice == '2' or choice == 'proxy':
prox = input(''' ┊
└────► set your HTTP proxy {example:127.0.0.1:80} : ~$ ''')
proxies = {
'http': 'http://'+prox,
'https': 'http://'+prox,
}
try:
ht = prox.split(':')
pr = int(ht[1])
s = socks.socksocket()
s.set_proxy(socks.HTTP, ht[0], pr)
socket.socket = socks.socksocket
urllib.request.urlopen
except IndexError:
messenger.writeMessage('\n\tPlease check the format of your proxy | reminder: 127.0.0.1:8080 ', 'red')
quit(0)
else:
proxies = ""
continue
ip = requests.get('http://ifconfig.co/ip', proxies=proxies, headers=OKadminFinder.header).text
cc = requests.get('http://ifconfig.co/country', proxies=proxies, headers=OKadminFinder.header).text
iso = requests.get('http://ifconfig.co/country-iso', proxies=proxies, headers=OKadminFinder.header).text
city = requests.get('http://ifconfig.co/city', proxies=proxies, headers=OKadminFinder.header).text
print(''' ┆
├───[''' + Fore.CYAN + '''IP address Infos:''' + Fore.YELLOW + ''']
┆''');
print(' ├──► ' + Fore.BLUE +'Country: ' + cc + Fore.YELLOW + ' ├───► ' + Fore.BLUE +'IP: ' + ip + Fore.YELLOW + ' ├────► '+ Fore.BLUE + 'Country ISO: ' + iso + Fore.YELLOW + ' └─────► '+ Fore.BLUE +'City: ' + city)
print('')
# Get site
site = messenger.writeInput(' Enter Site Name { example : example.com or www.example.com } \n' + Fore.BLUE + ' ~$ ', 'white');
print ('')
# Checking if the website is online and stable
if OKadminFinder.checkUrl(site,proxies):
messenger.writeMessage('\n Site %s is stable\n' % site,'green')
else:
messenger.writeMessage(' Something wrong with url', 'red')
exit(SystemExit)
#Some additional info about the website
rh = requests.get('http://'+site, proxies=proxies, headers=OKadminFinder.header)
di = socket.gethostbyname(site)
print(Fore.CYAN + Style.BRIGHT + '\tServer: ' + Fore.YELLOW + rh.headers['Server'] + '\t\t' + Fore.CYAN + Style.BRIGHT +'Hostname: ' + Fore.YELLOW + di + '\n')
try:
xf = dict(rh.headers).get("x-frame-options")
xf = str(xf)
print(Fore.CYAN + Style.BRIGHT + '\tX-Powered-By: ' + Fore.YELLOW + rh.headers['X-Powered-By'] + '\t\t' + Fore.CYAN+Style.BRIGHT + 'X-Frame-Options: ' + Fore.YELLOW + xf + '\n\n')
except KeyError:
pass
# Get links for checking
urls = OKadminFinder.getUrls('LinkFile/adminpanellinks.txt')
# Counters for total links, and admin panel find
totalCount = len(urls)
adminCount = 0
# Checking all links
for url in urls:
# Create test link with getting params from input and links.txt file
reqLink = OKadminFinder.createReqLink(site, url, proxies)
messenger.writeMessage('\t[#] Checking http://' + reqLink, 'yellow')
# Test created link for HTTPerrors. If not error - potential admin panel
if OKadminFinder.checkUrl(reqLink,proxies):
adminCount += 1
messenger.writeMessage(' %s %s' % ('\n [✔] http://' + reqLink, 'Admin page found!'), 'bright')
# Stopped process? and waiting for input for continue
messenger.writeInput(' Press enter to continue scanning.\n')
# If HTTPerrors continue testing other links
else:
continue
# Write last information about scanning with counters
messenger.writeMessage('\n\n Completed \n', 'green')
messenger.writeMessage(str(adminCount) + ' Admin pages found', 'white')
messenger.writeMessage(str(totalCount) + ' total pages scanned', 'white')
messenger.writeInput(' [/] Scanning over; Press Enter to Exit', 'green')
messenger.writeMessage('', 'white')
except (KeyboardInterrupt, SystemExit):
messenger.writeMessage('\n\t[x] Session Cancelled', 'red')
messenger.writeMessage('', 'white')
except():
messenger.writeMessage('\n\t[x] Session Cancelled; Unknown error', 'red')
messenger.writeMessage('', 'white')
if __name__ == '__main__':
# Updater
# interactive
if args.interactive:
args.url = False
args.tor = False
args.rand = False
args.proxy = False
args.verbose = False
interactive()
# random user-agent
if args.rand:
if args.url is False:
parser.print_usage()
quit(0)
else:
rangent()
# tor
if args.tor:
if args.url is False:
parser.print_usage()
quit(0)
else:
tor()
# proxy
if args.proxy:
if args.url is False:
parser.print_usage()
quit(0)
else:
proxy()
proxies = proxy()
# verbose
if args.verbose:
if args.url is False:
parser.print_usage()
quit(0)
else:
vipinf()
hos()
# url
if args.url:
site = args.url
# proxies=""
url(site)
|
import requests
import colorama
import json
import random
def get_woeid(lat, long):
url = 'https://www.metaweather.com/api/location/search/?lattlong=' + \
str(lat)+','+str(long)+''
try:
response = requests.get(url)
except requests.exceptions.RequestException as e:
print(colorama.Fore.RED,
'Connection error, Please check your internet connection', colorama.Fore.RESET)
return
data = response.json()
woeid = data[0]['woeid']
return woeid
def get_weather(lat, long):
woeid = get_woeid(lat, long)
from datetime import date
today = date.today()
now_today = str(today)
res = now_today.split('-')
url = 'https://www.metaweather.com/api/location/' + \
str(woeid)+'/'+str(res[0])+'/'+str(res[1])+'/'+str(res[2])+'/'
try:
response = requests.get(url)
except requests.exceptions.RequestException as e:
print(colorama.Fore.RED,
'Connection error, Please check your internet connection', colorama.Fore.RESET)
return
data = response.json()
name = data[0]['weather_state_name']
min_temp = data[0]['min_temp']
max_temp = data[0]['max_temp']
print(name)
print("MINIMUM TEMPARATURE : "+str(min_temp))
print("MAXIMUM TEMPARATURE : "+str(max_temp))
return name, min_temp, max_temp
|
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.NotificationRenderer = exports.globalSettings = undefined;
var _aureliaPal = require('aurelia-pal');
var _aureliaTemplating = require('aurelia-templating');
var _bsNotification = require('./bs-notification');
var globalSettings = exports.globalSettings = {
append: false,
containerSelector: 'body',
timeout: 0,
viewModel: _bsNotification.BSNotification,
limit: 5
};
var transitionEvent = function () {
var transition = null;
return function () {
if (transition) return transition;
var t = void 0;
var el = _aureliaPal.DOM.createElement('fakeelement');
var transitions = {
'transition': 'transitionend',
'OTransition': 'oTransitionEnd',
'MozTransition': 'transitionend',
'WebkitTransition': 'webkitTransitionEnd'
};
for (t in transitions) {
if (el.style[t] !== undefined) {
transition = transitions[t];
return transition;
}
}
return undefined;
};
}();
var NotificationRenderer = exports.NotificationRenderer = function () {
function NotificationRenderer() {
this.defaultSettings = globalSettings;
this.notificationControllers = [];
}
NotificationRenderer.prototype.createNotificationHost = function createNotificationHost(notificationController) {
var _this = this;
var settings = notificationController.settings;
var notificationHost = _aureliaPal.DOM.createElement('notification-host');
var notificationContainer = this.getNotificationContainer(settings.containerSelector);
if (settings.append === true) {
notificationContainer.appendChild(notificationHost);
} else {
notificationContainer.insertBefore(notificationHost, notificationContainer.firstChild);
}
notificationController.slot = new _aureliaTemplating.ViewSlot(notificationHost, true);
notificationController.slot.add(notificationController.view);
notificationController.showNotification = function () {
_this.notificationControllers.push(notificationController);
if (_this.notificationControllers.length >= settings.limit + 1) {
_this.notificationControllers[0].close(_this.notificationControllers[0]);
}
notificationController.slot.attached();
if (settings.timeout > 0) {
notificationController.timer = setTimeout(notificationController.close.bind(notificationController), settings.timeout);
}
return new Promise(function (resolve) {
function onTransitionEnd(e) {
if (e.target !== notificationHost) {
return;
}
notificationHost.removeEventListener(transitionEvent(), onTransitionEnd);
resolve();
}
notificationHost.addEventListener(transitionEvent(), onTransitionEnd);
setTimeout(function () {
notificationHost.classList.add('notification-host-active');
}, 0);
});
};
notificationController.hideNotification = function () {
var i = _this.notificationControllers.indexOf(notificationController);
if (i !== -1) {
_this.notificationControllers.splice(i, 1);
}
return new Promise(function (resolve) {
function onTransitionEnd() {
notificationHost.removeEventListener(transitionEvent(), onTransitionEnd);
resolve();
}
notificationHost.addEventListener(transitionEvent(), onTransitionEnd);
notificationHost.classList.remove('notification-host-active');
});
};
notificationController.destroyNotificationHost = function () {
notificationContainer.removeChild(notificationHost);
notificationController.slot.detached();
return Promise.resolve();
};
return Promise.resolve();
};
NotificationRenderer.prototype.showNotification = function showNotification(notificationController) {
return notificationController.showNotification();
};
NotificationRenderer.prototype.hideNotification = function hideNotification(notificationController) {
return notificationController.hideNotification();
};
NotificationRenderer.prototype.destroyNotificationHost = function destroyNotificationHost(notificationController) {
return notificationController.destroyNotificationHost();
};
NotificationRenderer.prototype.getNotificationContainer = function getNotificationContainer(containerSelector) {
var notificationContainer = _aureliaPal.DOM.querySelectorAll(containerSelector);
if (notificationContainer === null) {
notificationContainer = _aureliaPal.DOM.querySelectorAll('body');
}
return notificationContainer[0];
};
return NotificationRenderer;
}();
|
/** layuiAdmin.pro-v1.0.0 LPPL License By http://www.layui.com/admin/ */
;layui.define(["form", "upload"], function (t) {
var i = layui.$, e = layui.layer, n = (layui.laytpl, layui.setter, layui.view, layui.admin), a = layui.form,
s = layui.upload;
i("body"), a.render(), a.verify({
nickname: function (t, i) {
return new RegExp("^[a-zA-Z0-9_一-龥\\s·]+$").test(t) ? /(^\_)|(\__)|(\_+$)/.test(t) ? "用户名首尾不能出现下划线'_'" : /^\d+\d+\d$/.test(t) ? "用户名不能全为数字" : void 0 : "用户名不能有特殊字符"
}, pass: [/^[\S]{6,12}$/, "密码必须6到12位,且不能出现空格"], repass: function (t) {
if (t !== i("#LAY_password").val()) return "两次密码输入不一致"
}
}), a.on("submit(set_website)", function (t) {
return e.msg(JSON.stringify(t.field)), !1
}), a.on("submit(set_system_email)", function (t) {
return e.msg(JSON.stringify(t.field)), !1
}), a.on("submit(setmyinfo)", function (t) {
return e.msg(JSON.stringify(t.field)), !1
});
var r = i("#LAY_avatarSrc");
s.render({
url: "/api/upload/", elem: "#LAY_avatarUpload", done: function (t) {
0 == t.status ? r.val(t.url) : e.msg(t.msg, {icon: 5})
}
}), n.events.avartatPreview = function (t) {
var i = r.val();
e.photos({photos: {title: "查看头像", data: [{src: i}]}, shade: .01, closeBtn: 1, anim: 5})
}, a.on("submit(setmypass)", function (t) {
return e.msg(JSON.stringify(t.field)), !1
}), t("set", {})
});
|
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
import time
try:
from marionette import (expected,
Wait)
from marionette.by import By
from marionette.marionette import Actions
from marionette.errors import FrameSendFailureError
except:
from marionette_driver import (expected,
Wait)
from marionette_driver.by import By
from marionette_driver.marionette import Actions
from marionette_driver.errors import FrameSendFailureError
from gaiatest.apps.base import Base
class Camera(Base):
name = 'Camera'
_secure_camera_frame_locator = (By.CSS_SELECTOR, ".secureAppWindow.active[data-manifest-name='Camera'] iframe")
# Controls View
_controls_locator = (By.CSS_SELECTOR, '.controls')
_switch_button_locator = (By.CSS_SELECTOR, '.test-switch')
_capture_button_locator = (By.CSS_SELECTOR, '.test-capture')
_gallery_button_locator = (By.CSS_SELECTOR, '.test-gallery')
_thumbnail_button_locator = (By.CSS_SELECTOR, 'img.test-thumbnail')
_video_timer_locator = (By.CSS_SELECTOR, '.recording-timer')
# HUD View
_hud_locator = (By.CSS_SELECTOR, '.hud')
_loading_screen_locator = (By.CSS_SELECTOR, '.loading-screen')
_toggle_flash_button_locator = (By.CSS_SELECTOR, '.test-flash-button')
_viewfinder_video_locator = (By.CLASS_NAME, 'viewfinder-video')
# ConfirmDialog
_select_button_locator = (By.CSS_SELECTOR, '.test-confirm-select')
def launch(self):
Base.launch(self)
self.wait_for_capture_ready()
self.wait_for_element_not_displayed(*self._loading_screen_locator)
def wait_for_loading_spinner_hidden(self):
loading_spinner = self.marionette.find_element(*self._loading_screen_locator)
Wait(self.marionette).until(expected.element_not_displayed(loading_spinner))
def wait_for_loading_spinner_displayed(self):
loading_spinner = self.marionette.find_element(*self._loading_screen_locator)
Wait(self.marionette).until(expected.element_displayed(loading_spinner))
@property
def camera_mode(self):
return self.marionette.find_element(*self._controls_locator).get_attribute('data-mode')
def take_photo(self):
# Wait for camera to be ready to take a picture
controls = self.marionette.find_element(*self._controls_locator)
Wait(self.marionette, timeout=20).until(
lambda m: controls.get_attribute('data-enabled') == 'true')
self.tap_capture()
# Wait for thumbnail to appear
self.wait_for_thumbnail_visible()
def record_video(self, duration):
# Start recording
self.tap_capture()
# Wait for Controls View state to indicate that recording is in-progress
self.wait_for_video_capturing()
# Wait for duration
timeout = duration + 10
timer_text = "00:%02d" % duration
timer = self.marionette.find_element(*self._video_timer_locator)
Wait(self.marionette, timeout).until(lambda m: timer.text >= timer_text)
# Stop recording
self.tap_capture()
# Wait for thumbnail to appear
self.wait_for_thumbnail_visible()
def tap_capture(self):
capture_button = self.marionette.find_element(*self._capture_button_locator)
Wait(self.marionette).until(expected.element_enabled(capture_button))
capture_button.tap()
def tap_select_button(self):
select = self.marionette.find_element(*self._select_button_locator)
Wait(self.marionette).until(expected.element_enabled(select))
try:
select.tap()
except FrameSendFailureError:
# The frame may close for Marionette but that's expected so we can continue - Bug 1065933
pass
# Fall back to app beneath the picker
Wait(self.marionette).until(lambda m: self.apps.displayed_app.name != self.name)
self.apps.switch_to_displayed_app()
def tap_switch_source(self):
switch = self.marionette.find_element(*self._switch_button_locator)
Wait(self.marionette).until(expected.element_displayed(switch))
current_camera_mode = self.camera_mode
# TODO: Use marionette.tap(_switch_button_locator) to switch camera mode
Actions(self.marionette).press(switch).move_by_offset(0, 0).release().perform()
controls = self.marionette.find_element(*self._controls_locator)
Wait(self.marionette).until(lambda m: controls.get_attribute('data-enabled') == 'true')
Wait(self.marionette).until(lambda m: not current_camera_mode == self.camera_mode)
self.wait_for_capture_ready()
def tap_toggle_flash_button(self):
initial_flash_mode = self.current_flash_mode
toggle = self.marionette.find_element(*self._toggle_flash_button_locator)
Wait(self.marionette).until(expected.element_enabled(toggle))
toggle.tap()
Wait(self.marionette).until(lambda m: self.current_flash_mode != initial_flash_mode)
def wait_for_capture_ready(self):
viewfinder = Wait(self.marionette).until(expected.element_present(*self._viewfinder_video_locator))
Wait(self.marionette, timeout=10).until(lambda m: m.execute_script('return arguments[0].readyState;', [viewfinder]) > 0)
controls = self.marionette.find_element(*self._controls_locator)
Wait(self.marionette).until(lambda m: controls.get_attribute('data-enabled') == 'true')
Wait(self.marionette).until(lambda m: controls.is_enabled())
def wait_for_video_capturing(self):
controls = self.marionette.find_element(*self._controls_locator)
Wait(self.marionette).until(lambda m: controls.get_attribute('data-recording') == 'true')
def switch_to_secure_camera_frame(self):
# Find and switch to secure camera app frame (AppWindowManager hides it)
# This is only used when accessing camera in locked phone state
self.marionette.switch_to_frame()
secure_camera_frame = self.marionette.find_element(*self._secure_camera_frame_locator)
self.marionette.switch_to_frame(secure_camera_frame)
self.wait_for_capture_ready()
def tap_switch_to_gallery(self):
switch_to_gallery_button = self.marionette.find_element(*self._gallery_button_locator)
switch_to_gallery_button.tap()
from gaiatest.apps.gallery.app import Gallery
gallery_app = Gallery(self.marionette)
Wait(self.marionette).until(lambda m: self.apps.displayed_app.name == gallery_app.name)
self.apps.switch_to_displayed_app()
return gallery_app
def wait_for_thumbnail_visible(self):
thumbnail = Wait(self.marionette).until(expected.element_present(*self._thumbnail_button_locator))
Wait(self.marionette).until(expected.element_displayed(thumbnail))
def tap_thumbnail(self):
self.marionette.find_element(*self._thumbnail_button_locator).tap()
@property
def is_thumbnail_visible(self):
return self.is_element_displayed(*self._thumbnail_button_locator)
@property
def video_timer(self):
text = self.marionette.find_element(*self._video_timer_locator).text
return time.strptime(text, '%M:%S')
@property
def is_gallery_button_visible(self):
return self.is_element_displayed(*self._gallery_button_locator)
@property
def current_flash_mode(self):
return self.marionette.find_element(*self._hud_locator).get_attribute('flash-mode')
@property
def current_image_src(self):
return self.marionette.find_element(*self._thumbnail_button_locator).get_attribute('src')
def wait_for_picture_to_change(self, image_src):
Wait(self.marionette).until(lambda m: self.current_image_src != image_src)
class ImagePreview(Base):
_media_frame_locator = (By.ID, 'preview')
_image_preview_locator = (By.CSS_SELECTOR, '#media-frame > img')
_camera_button_locator = (By.ID, 'camera-button')
_video_play_button_locator = (By.CLASS_NAME, 'videoPlayerPlayButton')
_video_pause_button_locator = (By.CLASS_NAME, 'videoPlayerPauseButton')
_video_progress_bar_locator = (By.CLASS_NAME, 'videoPlayerProgress')
_options_button_locator = (By.CLASS_NAME, 'preview-option-icon')
_delete_button_locator = (By.CSS_SELECTOR, 'button[data-l10n-id="delete"]')
_gallery_button_locator = (By.CSS_SELECTOR, 'button[data-l10n-id="open-gallery"]')
_confirm_delete_button = (By.ID, 'dialog-yes')
_option_menu_locator = (By.CLASS_NAME, 'js-menu')
# for Gallery app switch
_progress_bar_locator = (By.ID, 'progress')
_thumbnail_list_view_locator = (By.ID, 'thumbnail-list-view')
@property
def is_image_preview_visible(self):
return self.is_element_displayed(*self._image_preview_locator)
@property
def is_video_play_button_visible(self):
return self.is_element_displayed(*self._video_play_button_locator)
@property
def is_progress_bar_showing(self):
return self.is_element_displayed(*self._video_progress_bar_locator)
def wait_for_media_frame(self):
media_frame = self.marionette.find_element(*self._media_frame_locator)
screen_height = int(self.marionette.execute_script('return window.screen.height;'))
Wait(self.marionette).until(lambda m: (media_frame.location['y'] + media_frame.size['height']) == screen_height)
def tap_video_player_play_button(self):
self.marionette.find_element(*self._video_play_button_locator).tap()
Wait(self.marionette).until(lambda m: self.is_progress_bar_showing is True)
def tap_video_player_pause_button(self):
self.marionette.find_element(*self._video_pause_button_locator).tap()
Wait(self.marionette).until(lambda m: self.is_progress_bar_showing is False)
def tap_options(self):
self.marionette.find_element(*self._options_button_locator).tap()
Wait(self.marionette).until(expected.element_displayed(
Wait(self.marionette).until(expected.element_present(*self._option_menu_locator))))
def delete_file(self):
self.tap_options()
self.marionette.find_element(*self._delete_button_locator).tap()
element = Wait(self.marionette).until(expected.element_present(*self._confirm_delete_button))
Wait(self.marionette).until(expected.element_displayed(element))
element.tap()
def tap_switch_to_gallery(self):
self.tap_options()
self.marionette.find_element(*self._gallery_button_locator).tap()
from gaiatest.apps.gallery.app import Gallery
gallery_app = Gallery(self.marionette)
Wait(self.marionette).until(lambda m: self.apps.displayed_app.name == gallery_app.name)
self.apps.switch_to_displayed_app()
self.wait_for_element_not_displayed(*self._progress_bar_locator)
Wait(self.marionette).until(expected.element_displayed(
Wait(self.marionette).until(expected.element_present(
*self._thumbnail_list_view_locator))))
return gallery_app
def tap_camera(self):
self.marionette.find_element(*self._camera_button_locator).tap()
camera = Camera(self.marionette)
return camera
|
/* global window, exports, define */
!function () {
var re = {
not_string: /[^s]/,
not_bool: /[^t]/,
not_type: /[^T]/,
not_primitive: /[^v]/,
number: /[diefg]/,
numeric_arg: /[bcdiefguxX]/,
json: /[j]/,
not_json: /[^j]/,
text: /^[^\x25]+/,
modulo: /^\x25{2}/,
placeholder: /^\x25(?:([1-9]\d*)\$|\(([^)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-gijostTuvxX])/,
key: /^([a-z_][a-z_\d]*)/i,
key_access: /^\.([a-z_][a-z_\d]*)/i,
index_access: /^\[(\d+)\]/,
sign: /^[+-]/
}
function sprintf(key) {
// `arguments` is not an array, but should be fine for this call
return sprintf_format(sprintf_parse(key), arguments)
}
function vsprintf(fmt, argv) {
return sprintf.apply(null, [fmt].concat(argv || []))
}
function sprintf_format(parse_tree, argv) {
var cursor = 1, tree_length = parse_tree.length, arg, output = '', i, k, ph, pad, pad_character, pad_length, is_positive, sign
for (i = 0; i < tree_length; i++) {
if (typeof parse_tree[i] === 'string') {
output += parse_tree[i]
}
else if (typeof parse_tree[i] === 'object') {
ph = parse_tree[i] // convenience purposes only
if (ph.keys) { // keyword argument
arg = argv[cursor]
for (k = 0; k < ph.keys.length; k++) {
if (arg == undefined) {
throw new Error(sprintf('[sprintf] Cannot access property "%s" of undefined value "%s"', ph.keys[k], ph.keys[k - 1]))
}
arg = arg[ph.keys[k]]
}
}
else if (ph.param_no) { // positional argument (explicit)
arg = argv[ph.param_no]
}
else { // positional argument (implicit)
arg = argv[cursor++]
}
if (re.not_type.test(ph.type) && re.not_primitive.test(ph.type) && arg instanceof Function) {
arg = arg()
}
if (re.numeric_arg.test(ph.type) && (typeof arg !== 'number' && isNaN(arg))) {
throw new TypeError(sprintf('[sprintf] expecting number but found %T', arg))
}
if (re.number.test(ph.type)) {
is_positive = arg >= 0
}
switch (ph.type) {
case 'b':
arg = parseInt(arg, 10).toString(2)
break
case 'c':
arg = String.fromCharCode(parseInt(arg, 10))
break
case 'd':
case 'i':
arg = parseInt(arg, 10)
break
case 'j':
arg = JSON.stringify(arg, null, ph.width ? parseInt(ph.width) : 0)
break
case 'e':
arg = ph.precision ? parseFloat(arg).toExponential(ph.precision) : parseFloat(arg).toExponential()
break
case 'f':
arg = ph.precision ? parseFloat(arg).toFixed(ph.precision) : parseFloat(arg)
break
case 'g':
arg = ph.precision ? String(Number(arg.toPrecision(ph.precision))) : parseFloat(arg)
break
case 'o':
arg = (parseInt(arg, 10) >>> 0).toString(8)
break
case 's':
arg = String(arg)
arg = (ph.precision ? arg.substring(0, ph.precision) : arg)
break
case 't':
arg = String(!!arg)
arg = (ph.precision ? arg.substring(0, ph.precision) : arg)
break
case 'T':
arg = Object.prototype.toString.call(arg).slice(8, -1).toLowerCase()
arg = (ph.precision ? arg.substring(0, ph.precision) : arg)
break
case 'u':
arg = parseInt(arg, 10) >>> 0
break
case 'v':
arg = arg.valueOf()
arg = (ph.precision ? arg.substring(0, ph.precision) : arg)
break
case 'x':
arg = (parseInt(arg, 10) >>> 0).toString(16)
break
case 'X':
arg = (parseInt(arg, 10) >>> 0).toString(16).toUpperCase()
break
}
if (re.json.test(ph.type)) {
output += arg
}
else {
if (re.number.test(ph.type) && (!is_positive || ph.sign)) {
sign = is_positive ? '+' : '-'
arg = arg.toString().replace(re.sign, '')
}
else {
sign = ''
}
pad_character = ph.pad_char ? ph.pad_char === '0' ? '0' : ph.pad_char.charAt(1) : ' '
pad_length = ph.width - (sign + arg).length
pad = ph.width ? (pad_length > 0 ? pad_character.repeat(pad_length) : '') : ''
output += ph.align ? sign + arg + pad : (pad_character === '0' ? sign + pad + arg : pad + sign + arg)
}
}
}
return output
}
var sprintf_cache = Object.create(null)
function sprintf_parse(fmt) {
if (sprintf_cache[fmt]) {
return sprintf_cache[fmt]
}
var _fmt = fmt, match, parse_tree = [], arg_names = 0
while (_fmt) {
if ((match = re.text.exec(_fmt)) !== null) {
parse_tree.push(match[0])
}
else if ((match = re.modulo.exec(_fmt)) !== null) {
parse_tree.push('%')
}
else if ((match = re.placeholder.exec(_fmt)) !== null) {
if (match[2]) {
arg_names |= 1
var field_list = [], replacement_field = match[2], field_match = []
if ((field_match = re.key.exec(replacement_field)) !== null) {
field_list.push(field_match[1])
while ((replacement_field = replacement_field.substring(field_match[0].length)) !== '') {
if ((field_match = re.key_access.exec(replacement_field)) !== null) {
field_list.push(field_match[1])
}
else if ((field_match = re.index_access.exec(replacement_field)) !== null) {
field_list.push(field_match[1])
}
else {
throw new SyntaxError('[sprintf] failed to parse named argument key')
}
}
}
else {
throw new SyntaxError('[sprintf] failed to parse named argument key')
}
match[2] = field_list
}
else {
arg_names |= 2
}
if (arg_names === 3) {
throw new Error('[sprintf] mixing positional and named placeholders is not (yet) supported')
}
parse_tree.push(
{
placeholder: match[0],
param_no: match[1],
keys: match[2],
sign: match[3],
pad_char: match[4],
align: match[5],
width: match[6],
precision: match[7],
type: match[8]
}
)
}
else {
throw new SyntaxError('[sprintf] unexpected placeholder')
}
_fmt = _fmt.substring(match[0].length)
}
return sprintf_cache[fmt] = parse_tree
}
/**
* export to either browser or node.js
*/
/* eslint-disable quote-props */
if (typeof exports !== 'undefined') {
exports['sprintf'] = sprintf
exports['vsprintf'] = vsprintf
}
if (typeof window !== 'undefined') {
window['sprintf'] = sprintf
window['vsprintf'] = vsprintf
if (typeof define === 'function' && define['amd']) {
define(function () {
return {
'sprintf': sprintf,
'vsprintf': vsprintf
}
})
}
}
/* eslint-enable quote-props */
}(); // eslint-disable-line
|
# -*- coding: utf-8 -*-
from qcloudsdkcore.request import Request
class GetAccountSettingsRequest(Request):
def __init__(self):
super(GetAccountSettingsRequest, self).__init__(
'apigateway', 'qcloudcliV1', 'GetAccountSettings', 'apigateway.api.qcloud.com')
|
import Vue from 'vue';
import VueRouter from 'vue-router';
Vue.use(VueRouter)
import Home from './pages/Home';
import NotFound from './pages/NotFound';
const router = new VueRouter({
mode: 'history',
routes: [
{
path: '/',
name: 'home',
component: Home
},
{
path: '/*',
name: 'not-found',
component: NotFound
}
],
});
export default router;
|
/* eslint-disable compat/compat */
/* eslint-disable camelcase */
import { Divider, Row, Tooltip } from 'antd';
import { connect } from 'dva';
import React, { Component } from 'react';
import globalUtil from '../../utils/global';
import oauthUtil from '../../utils/oauth';
import rainbondUtil from '../../utils/rainbond';
import styles from './Login.less';
import LoginComponent from './loginComponent';
@connect(({ global }) => ({
isRegist: global.isRegist,
rainbondInfo: global.rainbondInfo
}))
export default class LoginPage extends Component {
constructor(props) {
super(props);
this.state = {};
}
componentWillMount() {
const { dispatch } = this.props;
dispatch({ type: 'global/hideNeedLogin' });
globalUtil.removeCookie();
}
handleSubmit = values => {
const { dispatch, location } = this.props;
const query_params = new URLSearchParams(location.search);
const redirect = query_params.get('redirect');
dispatch({
type: 'user/login',
payload: {
...values
},
callback: () => {
let url = '/';
if (redirect) {
url = redirect;
}
window.location.href = url;
}
});
};
fetchEnterpriseInfo = eid => {
const { dispatch } = this.props;
dispatch({
type: 'global/fetchEnterpriseInfo',
payload: {
enterprise_id: eid
},
callback: res => {
if (
res &&
res.status_code === 200 &&
res.bean &&
res.bean.oauth_services
) {
// eslint-disable-next-line camelcase
const { oauth_services = {} } = res.bean;
if (oauth_services.enable) {
this.setState({
// eslint-disable-next-line react/no-unused-state
oauthServicesList:
oauth_services.value &&
oauth_services.value.length > 0 &&
oauth_services.value
});
}
}
}
});
};
render() {
const { rainbondInfo } = this.props;
const oauthInfo =
rainbondInfo &&
rainbondInfo.enterprise_center_oauth &&
rainbondInfo.enterprise_center_oauth.value;
const url = oauthInfo && oauthUtil.getAuthredictURL(oauthInfo);
const icon = oauthInfo && oauthUtil.getIcon(oauthInfo);
let oauthServicesList = [];
if (
rainbondInfo &&
rainbondInfo.oauth_services &&
rainbondInfo.oauth_services.enable &&
rainbondInfo.oauth_services.value &&
rainbondInfo.oauth_services.value.length > 0
) {
oauthServicesList = rainbondInfo.oauth_services.value;
}
const inlineBlock = { display: 'inline-block' };
return (
<div className={styles.main} style={{ marginTop: '100px' }}>
<h3>用户登录</h3>
<LoginComponent onSubmit={this.handleSubmit} type="login" />
{rainbondUtil.OauthbEnable(rainbondInfo) &&
(oauthInfo ||
(oauthServicesList && oauthServicesList.length > 0)) && (
<div className={styles.thirdBox}>
<Divider>
<div className={styles.thirdLoadingTitle}>第三方登录</div>
</Divider>
<Row className={styles.third}>
{oauthInfo && (
<div className={styles.thirdCol} key={oauthInfo.client_id}>
<Tooltip placement="top" title={oauthInfo.name}>
<a style={inlineBlock} href={url} title={oauthInfo.name}>
{icon}
</a>
</Tooltip>
</div>
)}
{oauthServicesList.map(item => {
const { name, service_id } = item;
return (
<div className={styles.thirdCol} key={service_id}>
<Tooltip placement="top" title={name}>
<a
style={inlineBlock}
href={oauthUtil.getAuthredictURL(item)}
title={name}
>
{oauthUtil.getIcon(item)}
</a>
</Tooltip>
</div>
);
})}
</Row>
</div>
)}
</div>
);
}
}
|
/*
* This file contains all the tips and apps of https://devrel-kpis.com
*
* 💡 CONTRIBUTE:
*
* - Add your tip to the BOTTOM of this file.
* - In the "avatar" field you can specify a username, email address or domain (we use unavatar.now.sh)
* - Get a unique id to use for each tip; this turns into the direct URL for the card (among other things): https://www.random.org/strings/?num=1&len=8&digits=on&loweralpha=on&unique=on&format=plain&rnd=new
* ☝️ don't forget to add a unique id
* - You can use markdown in the tips body. If you use _emphasis_, text will be highlighted on the site.
*
* - Use one of these tags:
* - reference = an actual KPI to measure. Ideally this is a single thing to measure that is easy to browse and
* understand on its own without having to click into the underlying source.
* - wisdom = general advice or guidance about KPIs and measurement. Please try to extract a quote or idea for the card
* that is easy to browse and understand on its own without having to click into the underlying source.
* *
*/
export const content = [
{
id: "1iyg4b5i",
tag: "reference",
author: {
name: "Erica Kuhl",
avatar: "twitter/ericakuhl",
bio: "CEO & Founder of Erica Kuhl Consulting, Former VP Community at Salesforce",
},
body:
"_Compare customers that are engaged in the community versus customers that are not_ across pipeline, ACV (Annual Contract Value), product adoption, and attrition.",
source_url: "https://medium.com/@erica.kuhl/its-all-about-that-data-4733b9d6873f",
},
{
id: "mu205jxd",
tag: "reference",
author: {
name: "TODO Group",
avatar: "twitter/todogroup",
bio: "The professional open source program networking group at The Linux Foundation",
},
body: "_Number of pull requests submitted, open, and accepted_ (and length of time they remain open).",
source_url: "https://todogroup.org/guides/measuring/ps://mbbroberg.fun/the-value-of-community-metrics/",
},
{
id: "kc4ahtq8",
tag: "reference",
author: {
name: "Ashley Smith",
avatar: "twitter/ashl3ysm1th",
bio: "CMO at Gatsby and Venture Partner at OpenView.",
},
body:
"_Number of sales calls attended_ when technical members of the prospect need to learn more about the technical aspects of the product.",
source_url: "https://openviewpartners.com/blog/measuring-the-impact-of-your-developer-relations-team/",
},
{
id: "xoinja8e",
tag: "reference",
author: {
name: "Ashley Smith",
avatar: "twitter/ashl3ysm1th",
bio: "CMO at Gatsby and Venture Partner at OpenView.",
},
body: "The _rate of repeat questions_ in the support channels decreasing over time or number of articles created.",
source_url: "https://openviewpartners.com/blog/measuring-the-impact-of-your-developer-relations-team/",
},
{
id: "high-value-leads",
tag: "reference",
author: {
name: "Ahmad Awais",
avatar: "twitter/mrahmadawais",
bio: "Award-winning DevRel & Google Developers Expert.",
},
body: "The _number of high-value leads (actively engaged open-sorcerers) contributing to your open source projects_ sometimes trumps high-volume leads. It is an excellent #DevRel KPI metric.",
source_url: "https://twitter.com/MrAhmadAwais/status/1272417982308745216",
},
{
id: "o80fdqfi",
tag: "reference",
author: {
name: "Ashley Smith",
avatar: "twitter/ashl3ysm1th",
bio: "CMO at Gatsby and Venture Partner at OpenView.",
},
body: "_Signup-to-Active ratio._",
source_url: "https://openviewpartners.com/blog/measuring-the-impact-of-your-developer-relations-team/",
},
{
id: "m0xtu216",
tag: "wisdom",
author: {
name: "Mary Thengvall",
avatar: "twitter/mary_grace",
bio: "DevRel director @Camunda and author of The Business Value of Developer Relations",
},
body:
"_DevRel Qualified Leads_ are connections passed along to the right team in hopes that together, they will be able to accomplish a task that furthers the overarching company goals.",
source_url:
"https://www.marythengvall.com/blog/2019/12/14/devrel-qualified-leads-repurposing-a-common-business-metrics-to-prove-value",
},
{
id: "c5i1j2um",
tag: "wisdom",
author: {
name: "Ashley Smith",
avatar: "twitter/ashl3ysm1th",
bio: "CMO at Gatsby and Venture Partner at OpenView.",
},
body:
"For the most part, goals fall into one of three broad categories: awareness, revenue and developer experience.",
source_url: "https://openviewpartners.com/blog/measuring-the-impact-of-your-developer-relations-team/",
},
{
id: "o3ozqg5c",
tag: "reference",
author: {
name: "Patrick Woods",
avatar: "twitter/patrickjwoods",
bio: "Writer, fencer, and co-founder and CEO of Orbit",
},
body:
"Community managers should track the _Love and Reach_ of their community as well as the _distribution of Orbit levels_, and the change in each over time. ",
url: "https://orbit.love/",
label: "Track with Orbit ››",
},
{
id: "8ujxdbrl",
tag: "reference",
author: {
name: "Josh Dzielak",
avatar: "twitter/dzello",
bio:
"the developer advocate's advocate · co-founder / CTO @OrbitModel · formerly @algolia and @keen_io · Ruby · Rails · JAMstack · he/him",
},
body: "_Member-generated content index_: amount of content produced by the community, weighted by length/depth.",
source_url: "https://twitter.com/dzello/status/1262392071715008512/",
},
{
id: "kt8e8qts",
tag: "reference",
author: {
name: "Josh Dzielak",
avatar: "twitter/dzello",
bio:
"the developer advocate's advocate · co-founder / CTO @OrbitModel · formerly @algolia and @keen_io · Ruby · Rails · JAMstack · he/him",
},
body: "_Arm share_: 'Raise your hand if you're heard of X' (count the number of arms you see)",
source_url: "https://twitter.com/dzello/status/1262392071715008512/",
},
{
id: "tn5ljg64",
tag: "reference",
author: {
name: "Josh Dzielak",
avatar: "twitter/dzello",
bio:
"the developer advocate's advocate · co-founder / CTO @OrbitModel · formerly @algolia and @keen_io · Ruby · Rails · JAMstack · he/him",
},
body: "_Community activation_: what % of product users join the community?",
source_url: "https://twitter.com/dzello/status/1262392071715008512/",
},
{
id: "o6ozqg5c",
tag: "reference",
author: {
name: "Patrick Woods",
avatar: "twitter/patrickjwoods",
bio: "Writer, fencer, and co-founder and CEO of Orbit",
},
body:
"One way to demonstrate the impact of community activities is by calculating _Natural Rate of Growth (NRG)_ and showing how community and DevRel contribute. NRG = 100 x Annual Growth Rate x % Organic Signups X % ARR from Products",
source_url: "https://orbit.love/blog/whats-your-communitys-nrg",
},
{
id: "hsgd83hs",
tag: "wisdom",
author: {
name: "Joe Beda",
avatar: "twitter/jbeda",
bio: "Principal Engineer at @VMware",
},
body:
"I think using metrics as a way to inform the trend is good. Using them as the only method of success leads you to trouble.",
source_url: "https://todogroup.org/guides/measuring/",
},
{
id: "k5267ju5",
tag: "reference",
author: {
name: "Derric Gilling",
avatar: "twitter/d_gilling",
bio: "CEO @MoesifHQ and API Engineer",
},
body:
"*Weekly Active API Tokens*: The mere act of generating an API key does not measure usage since even non-developers can view API keys without any real use for them. Since most APIs limit access to authenticated users, we are able to track how many distinct tokens are accessing our API platform on a given week.",
source_url: "https://nordicapis.com/how-to-measure-the-success-of-developer-relations/",
},
{
id: "qnzp2e5r",
tag: "reference",
author: {
name: "Derric Gilling",
avatar: "twitter/d_gilling",
bio: "CEO @MoesifHQ and API Engineer",
},
body:
"*Time to First Hello World (TTFHW)*: The longer a developer takes to get started with your platform, the less likely they will be successful.",
source_url: "https://nordicapis.com/how-to-measure-the-success-of-developer-relations/",
},
{
id: "l9038shs",
tag: "reference",
author: {
name: "Erica Kuhl",
avatar: "twitter/ericakuhl",
bio: "CEO & Founder of Erica Kuhl Consulting, Former VP Community at Salesforce",
},
body:
"_Compare customers that are engaged in the community versus customers that are not_ across pipeline, ACV (Annual Contract Value), product adoption, and attrition.",
source_url: "https://medium.com/@erica.kuhl/its-all-about-that-data-4733b9d6873f",
},
{
id: "zodyzm2d",
tag: "reference",
author: {
name: "Channy Yun",
avatar: "twitter/channyun",
bio: "Principal Tech Evangelist @AWSKorea. Cloud, Open API, Open Source, Web Standards",
},
body: "_Number of unanswered questions / answered_, weekly or monthly.",
source_url: "https://www.slideshare.net/Channy/how-to-measure-dev-rel-performances-metrics-devrel-tokyo-2018",
},
{
id: "k29pqdcr",
tag: "wisdom",
author: {
name: "Matt Broberg",
avatar: "twitter/mbbroberg",
bio: "open source community storyteller @Opensourceway",
},
body: "Measuring everything is only slightly better than measuring nothing. Pick one KPI and do it well.",
source_url: "https://mbbroberg.fun/the-value-of-community-metrics/",
},
{
id: "2erzxey7",
tag: "wisdom",
author: {
name: "Baruch Sadogursky",
avatar: "twitter/jbaruch",
bio: "Head of DevOps Advocacy at JFrog",
},
body:
"At JFrog, measuring face-to-face comes back to how well it feeds into online activity. “The first goal is to bring people online because from there we can actually measure.“",
source_url: "https://devrel.net/strategy-and-metrics/measuring-face-to-face-dev-rel-at-jfrog",
},
{
id: "6u1gh5c6",
tag: "reference",
author: {
name: "Max Katz",
avatar: "twitter/maxkatz",
bio: "Program Director, Developer Advocacy, @ibmdeveloper / @ibm",
},
body: "I believe that _how many developers did we help_ is a very good way to measure success.",
source_url: "https://maxkatz.org/2019/12/05/how-many-developers-did-we-help/",
},
{
id: "27hhdus7",
tag: "wisdom",
author: {
name: "Mary Thengvall",
avatar: "twitter/mary_grace",
bio: "DevRel director @Camunda and author of The Business Value of Developer Relations",
},
body:
"DevRel cannot be held responsible for the final outcome, whether that is a guest post, a partnership, a new hire or a converted customer. _The value DevRel delivers is the connection itself_—the opportunity for marketing or product or sales or another team to transform the DevRel qualified lead into a valuable business asset. That’s what you have to measure.",
source_url: "https://openviewpartners.com/blog/the-truth-about-devrel-how-to-make-it-work/",
},
{
id: "kjuegbsh",
tag: "wisdom",
author: {
name: "Patrick Woods",
avatar: "twitter/patrickjwoods",
bio: "Writer, fencer, and co-founder and CEO of Orbit",
},
body:
"_Revenue is a natural second-order effect of high gravity_. With communities, as gravity increases, more users will end up in the adoption funnel.",
source_url: "https://orbit.love/blog/whats-your-communitys-nrg",
},
{
id: "e8gjwgpk",
tag: "wisdom",
author: {
name: "Josh Dzielak",
avatar: "twitter/dzello",
bio:
"the developer advocate's advocate · co-founder / CTO @OrbitModel · formerly @algolia and @keen_io · Ruby · Rails · JAMstack · he/him",
},
body:
"The mission of a developer relations team following the [orbit model](https://github.com/orbit-love/orbit-model) is to facilitate high-quality word-of-mouth exchanges.",
source_url: "https://orbit.love/blog/why-orbit-is-better-than-funnel-for-developer-relations",
},
{
id: "jc82osj4",
tag: "wisdom",
author: {
name: "Nicolas Goutay",
avatar: "twitter/phacks",
bio: "Software Engineer, Orbit",
},
body:
"Having _community insights at hand in GitHub issues and PRs_ is a great way to direct my open source efforts to new and/or inexperienced contributors, improving their contributing experience.",
chrome_extension: {
title: "Orbit Chrome Extension",
url: "https://chrome.google.com/webstore/detail/orbit/ibgahekkldapaohbpmpbckmeljidicmn",
icon:
"https://lh3.googleusercontent.com/Q8EiWv9H3lug9YoSk826qTf9TU20lBQaeUStVqNTc0vMXnebpCTYCx80FSCMZTl1nuwRcVawJ6g=w128-h128-e365",
}
},
{
id: "756w3c1s",
tag: "wisdom",
author: {
name: "David Spinks",
avatar: "twitter/DavidSpinks",
bio: "Founder of @cmx, VP Community @bevylabs",
},
body:
"You don’t need everything you do to build community to be tied to revenue.\n\nIt’s okay to do things just to build the community and trust that the value will show up in ways you can’t measure.\n\nIn fact, it’s a requirement in order to build real community.",
source_url: "https://twitter.com/DavidSpinks/status/1264976828445257729",
},
{
id: "hml9qy70",
tag: "wisdom",
author: {
name: "Stathis Georgakopoulos",
avatar: "twitter/OhMyCaptain",
bio: "Marketing & Under The Hood of Developer Marketing Podcast Host @SlashDataHQ",
},
body:
"_Developer marketing KPIs and DevRel KPIs are different._ According to our survey, the top 2 DevRel KPIs were: \n1. Registered developers accounts (48%) \n2. Developer satisfaction score (48%). \n\nOn the other hand, the top 2 KPIs for developer marketing were: \n1. Page or video views (55%) \n2. Unique visitors or IP addresses (54%) \n\n View the full results in the source below. ",
source_url: "https://dev.to/slashdatahq/developer-marketing-kpis-are-different-from-devrel-kpis-3i8l",
},
{
id: "ja2no1zy",
tag: "reference",
author: {
name: "Jaime Lopez Jr",
avatar: "twitter/devwiththehair",
bio: "Developer Advocate at Jack Henry & Associates",
},
body:
"_Measuring the traffic to your developer portal (e.g. page views)_ is an important way to get a sense of how to be more effective at creating developer-friendly docs.",
source_url: "https://twitter.com/devwiththehair/status/1271115493617750016",
}
];
export const tags = {
all: {
value: "all",
name: "Show All",
color: "",
},
reference: {
value: "reference",
name: "Reference",
color: "#8348FF",
},
wisdom: {
value: "wisdom",
name: "Wisdom",
color: "#15a3bf",
},
};
export default content;
|
require("../../lib/framework/assert.js");
require("../../lib/loader.js");
require("../../lib/kernel.js");
require("../../gen/module.js");
|
const mongoose = require("mongoose");
const { connectionUri } = require("../utils/dbParams");
const connect = async () => {
if (mongoose.connection.readyState === 0) {
try {
await mongoose.connect(connectionUri, {
useNewUrlParser: true,
useCreateIndex: true,
useFindAndModify: false,
useUnifiedTopology: true,
});
} catch (err) {
console.error("App starting error:", err.stack);
process.exit(1);
}
}
};
const truncate = async () => {
if (mongoose.connection.readyState !== 0) {
const { collections } = mongoose.connection;
const promises = Object.keys(collections).map((collection) =>
mongoose.connection.collection(collection).deleteMany({})
);
await Promise.all(promises);
}
};
const disconnect = async () => {
if (mongoose.connection.readyState !== 0) {
await mongoose.disconnect();
}
};
module.exports = {
connect,
truncate,
disconnect,
};
|
import numpy as np
import pytest
from kitt.image.objdetect.bbox import BBox, BBoxBase, NormalizedBBox
def test_create_invalid_normalized_bbox():
with pytest.raises(Exception):
NormalizedBBox(xmin=5, xmax=10, ymin=1, ymax=2)
def test_create_bbox_base_directly():
with pytest.raises(Exception):
BBoxBase(xmin=0, xmax=1, ymin=0, ymax=1)
def test_normalize_bbox():
bbox = BBox(xmin=0, xmax=50, ymin=50, ymax=75)
bbox = bbox.normalize(100, 100)
assert bbox.as_tuple() == (0, 0.5, 0.5, 0.75)
def test_denormalize_bbox():
bbox = NormalizedBBox(xmin=0, xmax=1, ymin=0.5, ymax=0.75)
bbox = bbox.denormalize(100, 100)
assert bbox.as_tuple() == (0, 100, 50, 75)
def test_clip_bbox():
bbox = BBox(xmin=-10.3, xmax=50.0, ymin=-20.3, ymax=75.9)
bbox = bbox.clip(20, 30, 0, 0)
assert bbox.as_tuple() == (0, 20, 0, 30)
bbox = BBox(xmin=0, xmax=20, ymin=0, ymax=30)
bbox = bbox.clip(20, 30, 0, 0)
assert bbox.as_tuple() == (0, 20, 0, 30)
bbox = BBox(xmin=0, xmax=20, ymin=0, ymax=30)
bbox = bbox.clip(21, 31, 0, 0)
assert bbox.as_tuple() == (0, 20, 0, 30)
def test_invalid_bbox():
with pytest.raises(Exception):
BBox(xmin=0, xmax=0, ymin=0.5, ymax=0.6)
with pytest.raises(Exception):
BBox(xmin=1, xmax=0, ymin=0.3, ymax=0.5)
def test_from_xywh():
bbox = BBox.from_xywh(5, 6, 10, 30)
assert bbox.xmin == 5
assert bbox.xmax == 15
assert bbox.ymin == 6
assert bbox.ymax == 36
def test_to_xywh():
bbox = BBox(xmin=5, xmax=6, ymin=10, ymax=30)
x, y, w, h = bbox.xywh()
assert x == 5
assert w == 1
assert y == 10
assert h == 20
def test_class_constructor():
bbox = BBox.from_xywh(1, 1, 5, 5)
assert isinstance(bbox, BBox)
bbox = NormalizedBBox.from_xywh(0.1, 0.1, 0.5, 0.5)
assert isinstance(bbox, NormalizedBBox)
def test_rescale_at_center():
bbox = BBox.from_xywh(100, 200, 50, 100)
assert bbox.rescale_at_center(2).xywh() == (75, 150, 100, 200)
def test_rescale_at_center_normalized():
bbox = NormalizedBBox.from_x1y1x2y2(0.1, 0.2, 0.5, 0.3)
assert np.allclose(bbox.rescale_at_center(2).x1y1x2y2(), (0, 0.15, 0.7, 0.35))
bbox = NormalizedBBox.from_x1y1x2y2(0.2, 0.1, 0.3, 0.5)
assert np.allclose(bbox.rescale_at_center(2).x1y1x2y2(), (0.15, 0, 0.35, 0.7))
def test_denormalized_as_normalized():
bbox = BBox.from_xywh(5, 10, 20, 50)
normalized = bbox.as_normalized(100, 100)
assert isinstance(normalized, NormalizedBBox)
assert normalized == bbox.normalize(100, 100)
def test_denormalized_as_denormalized():
bbox = BBox.from_xywh(5, 10, 20, 50)
assert bbox.as_denormalized(100, 100) is bbox
def test_normalized_as_normalized():
bbox = NormalizedBBox.from_x1y1x2y2(0.1, 0.5, 0.2, 0.8)
assert bbox.as_normalized(100, 100) is bbox
def test_normalized_as_denormalized():
bbox = NormalizedBBox.from_x1y1x2y2(0.1, 0.5, 0.2, 0.8)
denormalized = bbox.as_denormalized(100, 100)
assert isinstance(denormalized, BBox)
assert denormalized == bbox.denormalize(100, 100)
|
var namespaceSpecDRAM__mod =
[
[ "SpecDRAM_type", "structSpecDRAM__mod_1_1SpecDRAM__type.html", "structSpecDRAM__mod_1_1SpecDRAM__type" ],
[ "checkForSanity", "namespaceSpecDRAM__mod.html#ae0400b40ce3673b229b9dab1642c38ce", null ],
[ "constructSpecDRAM", "namespaceSpecDRAM__mod.html#a4a0981ca0da9204e689390bbcb6d1eb2", null ],
[ "nullifyNameListVar", "namespaceSpecDRAM__mod.html#a9832e2661989112df809cc86c51789a8", null ],
[ "reportValues", "namespaceSpecDRAM__mod.html#a4efc09c10a0a0e92aab4c18aa3d28989", null ],
[ "setFromInputArgs", "namespaceSpecDRAM__mod.html#a2425c40063c207842320619a10994555", null ],
[ "setFromInputFile", "namespaceSpecDRAM__mod.html#a7ffc2b3540541af5d7fd4f0fc009ac08", null ]
];
|
import React, { Component } from 'react'
import classnames from 'classnames'
import _ from 'lodash'
import { connect } from 'react-redux'
import { bindActionCreators } from 'redux'
import * as MapActions from '../../actions/map'
import { compareTimes as timeOptions } from '../../settings/options'
import { filters } from '../../settings/options'
import DropdownButton from '../DropdownButton'
import Button from './button'
import themes from '../../settings/themes'
import './embedHeader.css'
class EmbedHeader extends Component {
onFeatureTypeClick(selectedFilters) {
var enabledFilters = this.props.enabledFilters
selectedFilters.filter(filter => enabledFilters.indexOf(filter) === -1).map(this.props.actions.enableFilter)
enabledFilters.filter(filter => selectedFilters.indexOf(filter) === -1).map(this.props.actions.disableFilter)
}
onYearChangeClick(isEnd, selectedYears) {
const newTimes = []
newTimes[0] = (isEnd === true) ? this.props.times[0] : selectedYears[0]
newTimes[1] = (isEnd === true) ? selectedYears[0] : this.props.times[1]
this.props.actions.setTimes(newTimes)
}
render() {
const { theme } = this.props
const years = timeOptions.map(timeOption => ({
id: timeOption.id,
description: timeOption.id
}))
const yearsList = timeOptions.map(timeOption => timeOption.id)
const yearStart = this.props.times[0]
const yearEnd = this.props.times[1]
// don't allow year start after year end and vice versa
const yearsEndIndex = yearsList.indexOf(yearEnd)
const yearsStart = years.slice(0, yearsEndIndex)
const yearsStartIndex = yearsList.indexOf(yearStart)
const yearsEnd = years.slice(yearsStartIndex + 1)
const styles = themes[theme]
return (
<header className="embedHeader" style={styles.embedHeader}>
<div className="left">
<span className="title">Before and after.</span>
<DropdownButton
theme={theme}
style={{marginRight: '150px'}}
options={yearsStart}
btnElement={
<button title='Select time range'>
<span style={styles.dropDown}>{yearStart}</span><span style={styles.dateFrom.after}>{styles.dateFrom.afterContent}</span>
</button>
}
multiple={false}
selectedKeys={[yearStart]}
onSelectionChange={_.partial(this.onYearChangeClick, false).bind(this)}
/>
<DropdownButton
theme={theme}
options={yearsEnd}
btnElement={
<button title='Select time range'>
<span style={styles.dropDown}>{yearEnd}</span><span style={styles.dateFrom.after}>{styles.dateTo.afterContent}</span>
</button>
}
multiple={false}
selectedKeys={[yearEnd]}
onSelectionChange={_.partial(this.onYearChangeClick, true).bind(this)}
/>
</div>
<div>
{filters.filter(filter => filter.hidden !== true).map(filter => {
const active = this.props.enabledFilters !== undefined && filter.id === this.props.enabledFilters[0]
return <Button
theme={theme}
active={active}
key={filter.id}
className={classnames({ '-selected': active })}
onClick={_.partial(this.onFeatureTypeClick, [filter.id]).bind(this)}
>
{filter.description}
</Button>
})}
</div>
</header>
)
}
}
function mapStateToProps(state) {
return {
enabledFilters: state.map.filters,
times: state.map.times
}
}
function mapDispatchToProps(dispatch) {
return {
actions: bindActionCreators(MapActions, dispatch)
}
}
export default connect(
mapStateToProps,
mapDispatchToProps
)(EmbedHeader)
|
import React, { useEffect, useState } from "react";
import api from './services/api';
import "./styles.css";
function App() {
const [repositories, setRepositories] = useState([]);
useEffect(() => {
api.get('repositories').then(response => {
setRepositories(response.data);
})
}, []);
async function handleAddRepository() {
const response = await api.post('repositories', {
title: '',
url: '',
techs: []
})
const repository = response.data;
setRepositories([...repositories, repository]);
}
async function handleRemoveRepository(id) {
await api.delete(`repositories/${id}`);
setRepositories(repositories.filter(
repository => repository.id !== id
))
}
return (
<div>
<ul data-testid="repository-list">
{repositories.map(repository => (
<li key={repository.id}>
{repository.title}
<button onClick={() => handleRemoveRepository(repository.id)}>
Remover
</button>
</li>
))}
</ul>
<button onClick={handleAddRepository}>Adicionar</button>
</div>
);
}
export default App;
|
(new Foo).x;
|
# Generated by Django 2.1.5 on 2019-01-30 18:54
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('booking', '0001_initial'),
]
operations = [
migrations.RenameField(
model_name='booking',
old_name='beds',
new_name='adults',
),
migrations.AddField(
model_name='booking',
name='kids',
field=models.PositiveIntegerField(default=0),
),
]
|
#### NOTICE: THIS FILE IS AUTOGENERATED
#### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY
#### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES
from swgpy.object import *
def create(kernel):
result = Tangible()
result.template = "object/tangible/wearables/hat/shared_hat_twilek_s01.iff"
result.attribute_template_id = 11
result.stfName("wearables_name","hat_twilek_s01")
#### BEGIN MODIFICATIONS ####
#### END MODIFICATIONS ####
return result
|
const frappe = require('frappejs');
const Observable = require('frappejs/utils/observable');
const model = require('./index');
module.exports = class BaseDocument extends Observable {
constructor(data) {
super();
this.fetchValues = {};
this.setup();
Object.assign(this, data);
}
setup() {
// add listeners
}
get meta() {
if (!this._meta) {
this._meta = frappe.getMeta(this.doctype);
}
return this._meta;
}
async getSettings() {
if (!this._settings) {
this._settings = await frappe.getSingle(this.meta.settings);
}
return this._settings;
}
get(fieldname) {
return this[fieldname];
}
// set value and trigger change
async set(fieldname, value) {
this[fieldname] = await this.validateField(fieldname, value);
await this.applyChange(fieldname);
}
async applyChange(fieldname) {
if (await this.applyFormula()) {
// multiple changes
await this.trigger('change', { doc: this });
} else {
// no other change, trigger control refresh
await this.trigger('change', { doc: this, fieldname: fieldname });
}
}
async setName() {
if (this.name) {
return;
}
// name === doctype for Single
if (this.meta.isSingle) {
this.name = this.meta.name;
return;
}
if (this.meta.settings) {
const numberSeries = (await this.getSettings()).numberSeries;
if(numberSeries) {
this.name = await model.getSeriesNext(numberSeries);
}
}
// assign a random name by default
// override this to set a name
if (!this.name) {
this.name = frappe.getRandomName();
}
}
setDefaults() {
for (let field of this.meta.fields) {
if (field.fieldtype === 'Date') {
this[field.fieldname] = (new Date()).toISOString().substr(0, 10);
} else if (!this[field.fieldname]) {
if(field.default) {
this[field.fieldname] = field.default;
}
}
}
}
setKeywords() {
let keywords = [];
for (let fieldname of this.meta.getKeywordFields()) {
keywords.push(this[fieldname]);
}
this.keywords = keywords.join(', ');
}
append(key, document) {
if (!this[key]) {
this[key] = [];
}
this[key].push(this.initDoc(document));
}
initDoc(data) {
if (data.prototype instanceof Document) {
return data;
} else {
return new Document(data);
}
}
async validateField(key, value) {
let field = this.meta.getField(key);
if (field && field.fieldtype == 'Select') {
return this.meta.validateSelect(field, value);
}
return value;
}
getValidDict() {
let data = {};
for (let field of this.meta.getValidFields()) {
data[field.fieldname] = this[field.fieldname];
}
return data;
}
setStandardValues() {
let now = new Date();
if (this.docstatus === null || this.docstatus === undefined) {
this.docstatus = 0;
}
if (!this.owner) {
this.owner = frappe.session.user;
this.creation = now;
}
this.modified_by = frappe.session.user;
this.modified = now;
}
async load() {
let data = await frappe.db.get(this.doctype, this.name);
if (data.name) {
this.syncValues(data);
} else {
throw new frappe.errors.NotFound(`Not Found: ${this.doctype} ${this.name}`);
}
}
syncValues(data) {
this.clearValues();
Object.assign(this, data);
}
clearValues() {
for (let field of this.meta.getValidFields()) {
if(this[field.fieldname]) {
delete this[field.fieldname];
}
}
}
setChildIdx() {
// renumber children
for (let field of this.meta.getValidFields()) {
if (field.fieldtype==='Table') {
for(let i=0; i < (this[field.fieldname] || []).length; i++) {
this[field.fieldname][i].idx = i;
}
}
}
}
async applyFormula() {
if (!this.meta.hasFormula()) {
return false;
}
let doc = this;
// children
for (let tablefield of this.meta.getTableFields()) {
let formulaFields = frappe.getMeta(tablefield.childtype).getFormulaFields();
if (formulaFields.length) {
// for each row
for (let row of this[tablefield.fieldname]) {
for (let field of formulaFields) {
row[field.fieldname] = await field.formula(row, doc);
}
}
}
}
// parent
for (let field of this.meta.getFormulaFields()) {
doc[field.fieldname] = await field.formula(doc);
}
return true;
}
async commit() {
// re-run triggers
await this.setName();
this.setStandardValues();
this.setKeywords();
this.setChildIdx();
await this.applyFormula();
await this.trigger('validate');
}
async insert() {
await this.commit();
await this.trigger('before_insert');
this.syncValues(await frappe.db.insert(this.doctype, this.getValidDict()));
await this.trigger('after_insert');
await this.trigger('after_save');
return this;
}
async update() {
await this.commit();
await this.trigger('before_update');
this.syncValues(await frappe.db.update(this.doctype, this.getValidDict()));
await this.trigger('after_update');
await this.trigger('after_save');
return this;
}
async delete() {
await this.trigger('before_delete');
await frappe.db.delete(this.doctype, this.name);
await this.trigger('after_delete');
}
async trigger(event, params) {
if (this[event]) {
await this[event](params);
}
await super.trigger(event, params);
}
// helper functions
getSum(tablefield, childfield) {
return this[tablefield].map(d => (d[childfield] || 0)).reduce((a, b) => a + b, 0);
}
async getFrom(doctype, name, fieldname) {
if (!name) return '';
let key = `${doctype}:${name}:${fieldname}`;
if (!this.fetchValues[key]) {
this.fetchValues[key] = await frappe.db.getValue(doctype, name, fieldname);
}
return this.fetchValues[key];
}
};
|
"""
ASGI config for django_script_runner project.
It exposes the ASGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/3.0/howto/deployment/asgi/
"""
import os
from django.core.asgi import get_asgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'django_script_runner.settings')
application = get_asgi_application()
|
module.exports = {
collectCoverageFrom: ["src/*.{ts}", "src/**/**.ts"],
preset: "ts-jest",
testEnvironment: "node",
setupFilesAfterEnv: ["./src/jest.setup.ts"],
};
|
import data_analysis_tool as dat
ALL_DATASETS = ['Ripe_Ris_monitors', 'Ripe_Atlas_probes', 'RouteViews_peers', 'Compare_All']
if __name__ == "__main__":
dat.plot_analysis(ALL_DATASETS)
|
"""ml-model-quality-analysys
A package to perform quality analyses for Machine Learning models.
"""
__version__ = '0.0.1'
__author__ = 'María Grandury'
|
import BaseEvent from "@pencil.js/base-event";
import Component from "@pencil.js/component";
import Container from "@pencil.js/container";
import MouseEvent from "@pencil.js/mouse-event";
import Rectangle from "@pencil.js/rectangle";
/**
* Abstract Input class
* @abstract
* @class
* @extends Container
*/
export default class Input extends Container {
/**
* Input constructor
* @param {PositionDefinition} positionDefinition - Any position
* @param {InputOptions} [options] - Specific options
*/
constructor (positionDefinition, options) {
super(positionDefinition, options);
this.background = new Rectangle(undefined, 0, 0, {
fill: this.options.background,
stroke: this.options.border,
strokeWidth: 2,
cursor: Component.cursors.pointer,
});
this.add(this.background);
this.background.on(MouseEvent.events.hover, () => {
this.background.options.fill = this.options.hover;
}).on(MouseEvent.events.leave, () => {
this.background.options.fill = this.options.background;
}).on(MouseEvent.events.click, (event) => {
this.click(event.position.clone().subtract(this.getAbsolutePosition()));
});
this.on(Container.events.attach, () => this.value = this.options.value, true);
}
/**
* Add support for origin option
* @param {CanvasRenderingContext2D} ctx - Drawing context
* @return {Input} Itself
*/
makePath (ctx) {
const previousOrigin = this.background.options.origin;
this.background.options.origin = this.options.origin;
const origin = this.background.getOrigin();
this.background.options.origin = previousOrigin;
ctx.translate(origin.x, origin.y);
return super.makePath();
}
/**
* Return the value of the input
*/
get value () {
throw new ReferenceError(`Unimplemented get value function in ${this.constructor.name}`);
}
/**
* Set the value of the input
* @param {*} value - Any value
*/
set value (value) {
throw new ReferenceError(`Unimplemented set value function in ${this.constructor.name}`);
}
/**
* Action to execute on click
*/
click () {
this.fire(new BaseEvent(Input.events.change, this));
}
/**
* @inheritDoc
*/
isHover (positionDefinition, ctx) {
return this.options.shown && this.background.isHover(this.position.clone().add(positionDefinition), ctx);
}
/**
* @inheritDoc
*/
toJSON () {
const json = super.toJSON();
json.options = json.options || {};
json.options.value = this.value;
json.children = json.children.slice(1);
return json;
}
/**
* @inheritDoc
* @param {Object} definition - Input definition
* @return {Input}
*/
static from (definition) {
return new this(definition.position, definition.options);
}
/**
* @typedef {Object} InputOptions
* @extends ContainerOptions
* @prop {String} [fill="#444"] - Color of the filling
* @prop {String} [background="#f6f6f6"] - Color of the background
* @prop {String} [border="#aaa"] - Color of the border
* @prop {String} [hover="#d0d0d0"] - Color of the background when hovered
*/
/**
* @return {InputOptions}
*/
static get defaultOptions () {
return {
...super.defaultOptions,
value: null,
fill: "#444",
background: "#f6f6f6",
border: "#aaa",
hover: "#dcdcdc",
};
}
/**
* @typedef {Object} InputEvents
* @enum {String}
* @prop {String} change - Input value has changed
*/
/**
* @return {InputEvents}
*/
static get events () {
return {
...super.events,
change: "change",
};
}
}
|
import { PACKAGE_NAME } from './constants';
import get from 'lodash/get';
import merge from 'lodash/merge';
import validateStorage from './validateStorage';
const oldStorageKey = '@bw/core/analytics';
/**
* Manages a storage with a specific key and a time-to-live.
*
* @private
* @category Analytics
*/
class StorageWrapper {
/**
* Constructs a new instance with the passed in storage instance and initializes the store.
* This storage instance must implement the methods async getItem(key), async setItem(key, data) and async removeItem(key) methods.
* For now it validates only if the storage is defined and if not, an error will be thrown.
* In the future, the validation logic will be changed to ensure the required methods are implemented on the passed in instance.
*
* @param {object} storage - The underlying storage instance that will store the data.
*
* //TODO: Change validateStorage function to validate if the storage instance contains the required methods.
*/
constructor(storage) {
if (!validateStorage(storage)) {
throw new Error(
'StorageWrapper needs a valid storage to properly persist data. Please make sure you are passing a valid storage.',
);
}
this.createStorage(storage);
}
/**
* Due to the updates done to the package on @1.0.0, we no longer write analytics data under `@bw/core/analytics` (old package name).
* From now on, the entry key on the storage is `@farfetch/blackout-core/analytics`, which is now hardcoded on the analytics side to avoid future breaking changes like this one.
* This method will ensure that if there is the `@bw/core/analytics` entry, it will be migrated to `@farfetch/blackout-core/analytics` to ensure that the user keeps his cookie preferences and localId.
*
* @private
*
* @returns {Promise<StorageWrapper>} Promise that will resolve with the instance that was used when calling this method to allow chaining.
*
* //TODO: When we reach @farfetch/blackout-core@2.0.0 version, evaluate if this method is still needed.
*/
async preProcessStorage() {
const oldStorage = await this.storage.getItem(oldStorageKey);
if (oldStorage) {
await this.storage.setItem(PACKAGE_NAME, oldStorage);
await this.storage.removeItem(oldStorageKey);
}
return this;
}
/**
* Creates the store with the time-to-live.
* Checks if there's a previous TTL stored, and if it's expired, stores a new one.
*
* @private
* @param {object} storage - The actual storage that will hold the data, like the browser localStorage.
*
* @returns {Promise} Promise that will resolve when the method finishes.
*/
async createStorage(storage) {
this.storage = storage;
await this.preProcessStorage();
const store = await this.getItem();
const ttlInMs = get(store, 'ttl', 0);
const now = new Date();
const nowInMs = now.getTime();
// If store has expired, clear it and renew it with one year time-to-live, so it's GDPR complient.
if (ttlInMs < nowInMs) {
await this.clear();
await this.setItem('ttl', now.setFullYear(now.getFullYear() + 1));
}
}
/**
* Returns a value from the storage, or the storage itself if no key is passed.
*
* @param {string} [key] - The key of the storage to return. If not passed, all items will be returned.
*
* @returns {Promise<*>} Promise that will resolve the value for the specified key.
*/
async getItem(key) {
const storeRawValue = await this.storage.getItem(PACKAGE_NAME);
const store = JSON.parse(storeRawValue || '{}');
if (!key) {
return store;
}
return get(store, key);
}
/**
* Sets a value with a key on the storage.
*
* @param {string} key - The key to store.
* @param {*} data - The data to store with the passed key.
*
* @returns {Promise<StorageWrapper>} Promise that will resolve with the instance that was used when calling this method to allow chaining.
*/
async setItem(key, data) {
if (!key) {
return this;
}
let store = await this.getItem();
store = merge({}, store, { [key]: data });
await this.storage.setItem(PACKAGE_NAME, JSON.stringify(store));
return this;
}
/**
* Removes a value with the specified key from the store.
*
* @param {string} key - The key to the item that will be removed.
*
* @returns {Promise<StorageWrapper>} Promise that will resolve with the instance that was used when calling this method to allow chaining.
*/
async removeItem(key) {
const store = await this.getItem();
delete store[key];
await this.storage.setItem(PACKAGE_NAME, JSON.stringify(store));
return this;
}
/**
* Removes the whole entry form the storage.
*
* @returns {Promise<StorageWrapper>} Promise that will resolve with the instance that was used when calling this method to allow chaining.
*/
async clear() {
await this.storage.removeItem(PACKAGE_NAME);
return this;
}
}
export default StorageWrapper;
|
import { configureStore } from '@reduxjs/toolkit'
import postReducer from 'redux/posts/reducer';
export default configureStore({
reducer: {
posts: postReducer,
},
})
|
// Copyright 2019 Google LLC
//
// 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 `npm run webpack` to produce Webpack bundle for this library.
const path = require('path');
module.exports = {
entry: './index.ts',
resolve: {
extensions: ['.ts', '.js', '.json'],
},
output: {
library: 'Adexchangebuyer2',
filename: 'adexchangebuyer2.min.js',
path: path.resolve(__dirname, 'dist'),
},
node: {
child_process: 'empty',
fs: 'empty',
crypto: 'empty',
},
module: {
rules: [
{
test: /node_modules[\\/]google-auth-library[\\/]src[\\/]crypto[\\/]node[\\/]crypto/,
use: 'null-loader',
},
{
test: /node_modules[\\/]https-proxy-agent[\\/]/,
use: 'null-loader',
},
{
test: /node_modules[\\/]gcp-metadata[\\/]/,
use: 'null-loader',
},
{
test: /node_modules[\\/]gtoken[\\/]/,
use: 'null-loader',
},
{
test: /node_modules[\\/]pkginfo[\\/]/,
use: 'null-loader',
},
{
test: /node_modules[\\/]semver[\\/]/,
use: 'null-loader',
},
{
test: /\.ts$/,
use: 'ts-loader',
exclude: /node_modules/,
},
],
},
mode: 'production',
plugins: [],
};
|
from __future__ import print_function, division, absolute_import
from .extended_roadrunner import ExtendedRoadRunner
|
import Swal from "sweetalert2";
export const swalConfirmation = Swal.mixin({
customClass: {
cancelButton: 'btn btn-danger mx-2',
confirmButton: 'btn btn-success mx-2'
},
buttonsStyling: false,
cancelButtonText: 'Cancel',
confirmButtonText: 'Confirm',
showCancelButton: true,
type: 'question'
});
export const swalSuccess = Swal.mixin({
customClass: {
confirmButton: 'btn btn-success mx-2'
},
buttonsStyling: false,
type: 'success'
});
export const swalError = Swal.mixin({
customClass: {
confirmButton: 'btn btn-success mx-2'
},
buttonsStyling: false,
type: 'error'
});
export const swalToast = Swal.mixin({
toast: true,
position: 'top-end',
showConfirmButton: false,
timer: 15000
});
export const swalBanner = Swal.mixin({
animation: false,
customClass: {
actions: 'beta-banner__actions',
confirmButton: 'btn btn-light mx-2',
content: 'beta-banner__content',
popup: 'beta-banner',
},
buttonsStyling: false,
confirmButtonText: 'Dismiss',
toast: true,
position: 'top',
timer: 15000
});
export const swalBannerMobile = Swal.mixin({
animation: false,
customClass: {
confirmButton: 'btn btn-light mx-2'
},
buttonsStyling: false,
confirmButtonText: 'Dismiss'
});
|
/* @jsx createElement */
import {createElement, Component, useState, useReducer, useMemo, forwardRef, createRef, useRef, useEffect, useCallback, useImperativeHandle, useLayoutEffect} from 'rax';
import {renderToString} from '../index';
function Text(props) {
return <span>{props.text}</span>;
}
describe('hooks', () => {
describe('useState', () => {
it('basic render', () => {
function Counter(props) {
const [count] = useState(0);
return <span>Count: {count}</span>;
}
let str = renderToString(<Counter />);
expect(str).toBe('<span>Count: 0</span>');
});
it('lazy state initialization', () => {
function Counter(props) {
const [count] = useState(() => {
return 0;
});
return <span>Count: {count}</span>;
}
let str = renderToString(<Counter />);
expect(str).toBe('<span>Count: 0</span>');
});
it('should ignore setCount on the server', () => {
function Counter() {
let [count, setCount] = useState(0);
if (count < 3) {
setCount(count + 1);
}
return <span>Count: {count}</span>;
}
let str = renderToString(<Counter />);
expect(str).toBe('<span>Count: 0</span>');
});
});
describe('useReducer', () => {
it('render with initial state', () => {
function reducer(state, action) {
return action === 'increment' ? state + 1 : state;
}
function Counter() {
let [count] = useReducer(reducer, 0);
return <Text text={count} />;
}
let str = renderToString(<Counter />);
expect(str).toBe('<span>0</span>');
});
it('lazy initialization', () => {
function reducer(state, action) {
return action === 'increment' ? state + 1 : state;
}
function Counter() {
let [count] = useReducer(reducer, 0, c => c + 1);
return <Text text={count} />;
}
let str = renderToString(<Counter />);
expect(str).toBe('<span>1</span>');
});
it('should ignore dispatch on the server', () => {
function reducer(state, action) {
return action === 'increment' ? state + 1 : state;
}
function Counter() {
let [count, dispatch] = useReducer(reducer, 0);
if (count < 3) {
dispatch('increment');
}
return <Text text={count} />;
}
let str = renderToString(<Counter />);
expect(str).toBe('<span>0</span>');
});
});
describe('useMemo', () => {
it('basic render', () => {
function CapitalizedText(props) {
const text = props.text;
const capitalizedText = useMemo(
() => {
return text.toUpperCase();
},
[text],
);
return <Text text={capitalizedText} />;
}
let str = renderToString(<CapitalizedText text="hello" />);
expect(str).toBe('<span>HELLO</span>');
});
it('if no inputs are provided', () => {
function CapitalizedText(props) {
const computed = useMemo(props.compute);
return <Text text={computed} />;
}
function computeA() {
return 'A';
}
let str = renderToString(<CapitalizedText compute={computeA} />);
expect(str).toBe('<span>A</span>');
});
});
describe('useRef', () => {
it('basic render', () => {
function Counter() {
const count = useRef(0);
return <span>Count: {count.current}</span>;
}
let str = renderToString(<Counter />);
expect(str).toBe('<span>Count: 0</span>');
});
});
describe('useEffect', () => {
it('should ignore effects on the server', () => {
function Counter(props) {
useEffect(() => {
throw new Error('should not be invoked');
});
return <span>Count: {props.count}</span>;
}
let str = renderToString(<Counter count={0} />);
expect(str).toBe('<span>Count: 0</span>');
});
});
describe('useCallback', () => {
it('should ignore callbacks on the server', () => {
function Counter(props) {
useCallback(() => {
throw new Error('should not be invoked');
});
return <span>Count: {props.count}</span>;
}
let str = renderToString(<Counter count={0} />);
expect(str).toBe('<span>Count: 0</span>');
});
it('should support render time callbacks', () => {
function Counter(props) {
const renderCount = useCallback(increment => {
return 'Count: ' + (props.count + increment);
});
return <span>{renderCount(3)}</span>;
}
let str = renderToString(<Counter count={2} />);
expect(str).toBe('<span>Count: 5</span>');
});
});
describe('useImperativeHandle', () => {
it('should not be invoked on the server', () => {
function Counter(props, ref) {
useImperativeHandle(ref, () => {
throw new Error('should not be invoked');
});
return <span>{props.label + ': ' + ref.current}</span>;
}
Counter = forwardRef(Counter);
const counter = createRef();
counter.current = 0;
let str = renderToString(<Counter label="Count" ref={counter} />);
expect(str).toBe('<span>Count: 0</span>');
});
});
describe('useLayoutEffect', () => {
it('should not be invoked on the server', () => {
function Counter() {
useLayoutEffect(() => {
throw new Error('should not be invoked');
});
return <span>Count: 0</span>;
}
let str = renderToString(<Counter />);
expect(str).toBe('<span>Count: 0</span>');
});
});
});
|
"""
Utility method for Sublime Text editor
"""
import re
import os.path
import sublime
import sublime_plugin
from zlib import adler32 # adler32 considered faster than crc32
# List of LiveStyle-supported file extensions
supported_syntaxes = ['css', 'less', 'scss']
_settings = None
_sels = {}
try:
isinstance("", basestring)
def isstr(s):
return isinstance(s, basestring)
def hash(content):
return adler32(content)
except NameError:
def isstr(s):
return isinstance(s, str)
def hash(content):
return adler32(bytes(content, 'UTF-8'))
def main_thread(fn):
"Run function in main thread"
return lambda *args, **kwargs: sublime.set_timeout(lambda: fn(*args, **kwargs), 1)
def get_setting(name, default=None):
settings = sublime.load_settings('LiveStyle.sublime-settings')
return settings.get(name, default)
def selector_setting(syntax):
key = '%s_files_selector' % syntax
if key not in _sels:
_sels[key] = get_setting(key, 'source.%s' % syntax)
return _sels[key]
def parse_json(data):
return json.loads(data) if isstr(data) else data
def content(view):
"Returns content of given view"
return view.substr(sublime.Region(0, view.size()))
def file_name(view):
"Returns file name representation for given view"
return view.file_name() or temp_file_name(view)
def temp_file_name(view):
"Returns temporary name for (unsaved) views"
return '[untitled:%d]' % view.id()
def all_views():
"Returns all view from all windows"
views = []
for w in sublime.windows():
for v in w.views():
views.append(v)
return views
def view_for_buffer_id(buf_id):
"Returns view for given buffer id"
for view in all_views():
if view.buffer_id() == buf_id:
return view
return None
def view_for_uri(path):
"Locates editor view with given URI"
for view in all_views():
if file_name(view) == path:
return view
return None
def focus_view(view):
# looks like view.window() is broken in ST2,
# use another way to find parent window
for w in sublime.windows():
for v in w.views():
if v.id() == view.id():
return w.focus_view(v)
def view_hash(view):
return hash(content(view))
##################################
# Editor locking, used to disable
# diff requests when editor is
# updated after patching
##################################
_locks = set()
def lock(view):
_locks.add(view.buffer_id())
def unlock(view):
_locks.discard(view.buffer_id())
def is_locked(view):
return view.buffer_id() in _locks
#############################
def supported_views():
"Returns list of opened views matching given syntax list"
views = []
for view in all_views():
v = is_supported_view(view)
if v:
views.append(v)
return views
def supported_files():
"Returns list of opened files with given syntaxes"
return [file_name(sv['view']) for sv in supported_views()]
def is_supported_view(view, strict=False):
"Check if given view matches given syntax"
# detecting syntax by scope selector isn't always a good idea:
# sometimes users accidentally pick wrong syntax, for example,
# CSS for .less files, Sass for .scss file. So if this is not an untitled
# file we're editing, use file extension to resolve syntax
m = re.search(r'\.(css|less|scss)$', file_name(view))
found_syntax = None
if m:
found_syntax = m.group(1)
else:
for syntax in supported_syntaxes:
sel = selector_setting(syntax)
if not sel:
continue
if not view.file_name() and not strict:
# For new files, check if current scope is text.plain (just created)
# or it's a strict syntax check
sel = '%s, text.plain' % sel
if view.score_selector(0, sel) > 0:
found_syntax = syntax
break
if found_syntax:
return {
'view': view,
'syntax': found_syntax
}
def view_syntax(view):
"Returns LiveStyle-supported syntax for given view"
sv = is_supported_view(view)
return sv and sv['syntax'] or 'css'
def payload(view, data=None):
"Returns diff/patch payload for given view"
cn = content(view)
syntax = view_syntax(view)
result = {
'uri': file_name(view),
'syntax': syntax,
'content': cn,
'hash': hash(cn),
}
global_deps = []
try:
global_deps = get_global_deps(view, syntax)
except Exception as e:
pass
if global_deps:
result['globalDependencies'] = global_deps
if data:
result.update(data)
return result
def get_global_deps(view, syntax):
"""
Returns list of global dependencies defined in project
preferences for given view.
Currently works in Sublime Text 3 only
"""
# get global stylesheets defined in "livestyle/globals"
# section of current project
result = []
if syntax == 'css':
return result
wnd = view.window()
project_file = wnd.project_file_name()
if not project_file or not wnd.project_data():
return result
project_base = os.path.dirname(project_file)
deps = wnd.project_data().get('livestyle', {}).get('globals', [])
# resolve globals: use only ones matched current syntax
# and make paths absolute
possible_ext = ['.%s' % syntax, '.css']
for d in deps:
if os.path.splitext(d)[1] not in possible_ext:
continue
d = os.path.expanduser(d)
if not os.path.isabs(d):
d = os.path.join(project_base, d)
result.append(d)
return result
#####################################
def unindent_text(text, pad):
"""
Removes padding at the beginning of each text's line
@type text: str
@type pad: str
"""
lines = text.splitlines()
for i,line in enumerate(lines):
if line.startswith(pad):
lines[i] = line[len(pad):]
return '\n'.join(lines)
def get_line_padding(line):
"""
Returns padding of current editor's line
@return str
"""
m = re.match(r'^(\s+)', line)
return m and m.group(0) or ''
|
#!/usr/bin/env python
#
# Copyright 2013 CSIR Meraka HLT and Multilingual Speech Technologies (MuST) North-West University
#
# 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.
#
__author__ = "Marelie Davel, Christiaan van der Walt"
__email__ = "mdavel@csir.co.za, cvdwalt@csir.co.za"
"""
Select a randomised speaker-based subset from a given audio and trans list
@param in_audio_list: List of MFCC filenames to select from
@param in_trans_list: List of transcription filenames to select from
@param meta_info: Name of file containing meta info
@param num_male: Number of male speakers required
@param num_female: Number of female speakers required
@param out_prefix: Prefix of files to be created, namely \
<prefix>.audio.train, <prefix>.audio.test, <prefix>.trans.train and <prefix>.trans.test"
NCHLT naming conventions assumed
"""
import sys, re, random, codecs
RANDOM_SEED = 0
#------------------------------------------------------------------------------
def read_gender_info(in_meta_info):
"""
Reads the gender of the speakers from the meta-info file into a dictionary
Assumptions:
-first two lines of meta file are text, data starts from line three
-format of lines: ['speaker_id', 'woefzela spk_id', 'gender', 'age']
"""
#read gender info into a dictionary
mdata = read_file_array(in_meta_info, "\t")
gender={}
for itr in range(2,len(mdata)):
try:
gender[mdata[itr][0]]=mdata[itr][2]
#utterance_ids[spk_id]=[]
except:
print "Error: line " + str(itr) + " not in correct format."
exit(1)
return gender
#------------------------------------------------------------------------------
def generate_subset_lists(in_audio_name, in_trans_name, num_male, num_female, in_meta_info, out_prefix):
"""Select matching speaker-based subsets from a given audio and trans list """
#get gender of speakers
in_gender = read_gender_info(in_meta_info)
audio_data = read_list(in_audio_name)
audio_name_format = re.compile(r'.*/(\d+)_.*_.*_(\d+)\.mfc')
#print "audio"
(train_data, test_data) = generate_subset(audio_data, num_male, num_female, audio_name_format, in_gender)
write_list(train_data, "%s.audio.train" % out_prefix)
write_list(test_data, "%s.audio.test" % out_prefix)
trans_data = read_list(in_trans_name)
trans_name_format = re.compile(r'.*/(\d+)_.*_.*_(\d+)\.txt')
#print "trans"
#print in_trans_name
(train_data, test_data) = generate_subset(trans_data, num_male, num_female, trans_name_format, in_gender)
write_list(train_data, "%s.trans.train" % out_prefix)
write_list(test_data, "%s.trans.test" % out_prefix)
#------------------------------------------------------------------------------
def generate_subset(in_list, num_male, num_female, item_format, in_gender):
"""Select a speaker-based subset from a given list """
utterance_ids = {}
speaker_ids = []
speaker_files= {}#file names associated with a specific speaker ID
male_keys = []
female_keys = []
#split the filenames and read relevant info into dictionaries according to speaker
in_list.sort()
for item in in_list:
full_name = item.strip()
matched = item_format.match(full_name)
if matched:
spk_id = matched.group(1)
utt_id = matched.group(2)
else:
print "Error: format error in line " + full_name
exit(1)
if utterance_ids.has_key(spk_id):
#speaker already known
utterance_ids[spk_id].append(utt_id)
speaker_files[spk_id].append(full_name)
else:
#first time the speaker is encountered
speaker_ids.append(spk_id)
utterance_ids[spk_id]=[]
utterance_ids[spk_id].append(utt_id)
speaker_files[spk_id]=[]
speaker_files[spk_id].append(full_name)
if spk_id in in_gender:
gender = in_gender[spk_id].lower()
else:
print "Error: unknown speaker id " + str(spk_id)
exit(1)
if gender == 'male':
male_keys.append(spk_id)
elif gender == 'female':
female_keys.append(spk_id)
elif gender == 'na':
print "Warning: unknown gender " + gender
else:
print "Error: unknown gender " + gender
exit(1)
#Check if enough speakers to proceed
if len(male_keys) < num_male:
msg = "Available male speakers (%d) less than size of test set (%d) required" \
% (len(male_keys), num_male)
print msg
exit(1)
if len(female_keys) < num_female:
msg = "Available female speakers (%d) less than size of test set (%d) required" \
% (len(female_keys), num_female)
print msg
exit(1)
#create test set by randomly selecting from full list
random.seed(RANDOM_SEED)
male_selected = random.sample(male_keys, num_male)
female_selected = random.sample(female_keys, num_female)
test_speakers = list(male_selected)
test_speakers.extend(female_selected)
test_files = []
for spk in test_speakers:
for fn in speaker_files[spk]:
#print "Test set: adding %s for spk %s" % (fn,spk)
test_files.append(fn)
#create training set by using all remaining speaker IDs
train_speakers = speaker_ids
train_files = []
for spk in test_speakers:
train_speakers.remove(spk)
for spk in train_speakers:
for fn in speaker_files[spk]:
#print "Train set: adding %s for spk %s" % (fn,spk)
train_files.append(fn)
return (train_files, test_files)
#------------------------------------------------------------------------------
def read_file_array(inp_dir_fnm, SEPARATOR):
"""read a text file into an array (each column is read into a separate list"""
try:
inp_fnm_obj = codecs.open(inp_dir_fnm,"r","utf-8")
except IOError:
print "IOError " + inp_fnm_obj
data = []
for ln in inp_fnm_obj:
ln_split = []
ln_split = ln.split(SEPARATOR)
ln_clean=[]
for i in range(len(ln_split)):
ln_split[i] = ln_split[i].strip()#remove any /n or /t
if ln_split[i] != "":
ln_clean.append(ln_split[i])#do not add empty array elements
data.append(ln_clean)
inp_fnm_obj.close()
return data
#------------------------------------------------------------------------------
def read_list(in_name):
"""Read text from a file into a list."""
try:
in_file = codecs.open(in_name,"r")
except IOError:
print "IOError: Error reading from file " + in_name
sys.exit(IOError)
data = []
for ln in in_file:
data.append(ln)
in_file.close()
return data
#------------------------------------------------------------------------------
def write_list(in_list, out_name):
"""Write a list to file, with each element on a separate line."""
try:
out_file = open(out_name,"w")
except IOError:
print "IOError: Error writing to file " + out_name
sys.exit(1)
for ln in in_list:
out_file.write(str(ln) + "\n")
out_file.close()
#------------------------------------------------------------------------------
if __name__ == "__main__":
"""
Example command line arguments:
/home/cvdwalt/work/projects/asr/asr_nchlt_english1/lists/audio_all.lst /home/cvdwalt/work/projects/asr/asr_nchlt_english1/lists/trans_all.lst /home/cvdwalt/work/projects/asr/corpora/NCHLT_English_subset/info/Session_Speaker_info.txt 2 2 /home/cvdwalt/work/projects/asr/asr_nchlt_english1/lists/4spk
"""
if len(sys.argv) == 7:
in_audio_list = str(sys.argv[1])
in_trans_list = str(sys.argv[2])
in_meta_info = str(sys.argv[3])
num_male = int(sys.argv[4])
num_female = int(sys.argv[5])
out_prefix = str(sys.argv[6])
print "Generating subset lists"
generate_subset_lists(in_audio_list, in_trans_list, num_male, num_female, \
in_meta_info,out_prefix)
else:
print "Usage: generate_nchlt_subset_lists.py <in:audio_list> <in:trans_list> <in:meta_info> \
<num_male> <num_female> <out:prefix>"
print " <in:audio_list> = list of MFCC files to select from"
print " <in:trans_list> = list of transcriptions to select from"
print " <in:meta_info> = meta information containing gender of speakers"
print " <num_male> = number of male speakers required"
print " <num_female> = number of female speakers required"
print " <out:prefix> = create the following files:"
print " <prefix>.audio.train <prefix>.audio.test"
print " <prefix>.trans.train <prefix>.trans.test"
print " containing audio and transcription, train and test sets."
print " NCHLT filename format assumed"
|
var
Human = require('../../lib/models/human'),
passport = require('passport')
;
exports.validateLogin = function(identity, password, callback)
{
Human.validateLogin(identity, password)
.then(function(person)
{
callback(null, person);
})
.fail(function(err)
{
callback(err);
}).done();
};
exports.login = function(request, response)
{
var locals =
{
_csrf: request.csrfToken(),
title: 'Sign in',
page: 'signin'
};
response.render('login', locals);
};
exports.loginPost = function(request, response)
{
request.flash('success', 'Welcome back!');
response.redirect('/');
};
exports.logout = function(request, response)
{
request.logout();
response.redirect('/');
};
|
import Icon from '../components/Icon'
Icon.register({
'align-center': {
width: 448,
height: 512,
paths: [
{
d: 'M432 160c8.8 0 16 7.2 16 16v32c0 8.8-7.2 16-16 16h-416c-8.8 0-16-7.2-16-16v-32c0-8.8 7.2-16 16-16h416zM432 416c8.8 0 16 7.2 16 16v32c0 8.8-7.2 16-16 16h-416c-8.8 0-16-7.2-16-16v-32c0-8.8 7.2-16 16-16h416zM108.1 96c-6.7 0-12.1-5.4-12.1-12.1v-39.8c0-6.7 5.4-12.1 12.1-12.1h0 231.8c6.7 0 12.1 5.4 12.1 12.1v39.8 0c0 6.7-5.4 12.1-12.1 12.1h-231.8zM339.9 352h-231.8c-6.7 0-12.1-5.4-12.1-12.1v-39.8c0-6.7 5.4-12.1 12.1-12.1h0 231.8c6.7 0 12.1 5.4 12.1 12.1v39.8 0c0 6.7-5.4 12.1-12.1 12.1z'
}
]
}
})
|
(window["webpackJsonp"]=window["webpackJsonp"]||[]).push([["chunk-2d20881e"],{a4a6:function(t,e,a){"use strict";a.r(e);var r=function(){var t=this,e=t.$createElement,a=t._self._c||e;return a("div",[a("v-data-table",{staticClass:"ma-5",attrs:{headers:t.headers,items:t.dataO,"items-per-page":5},scopedSlots:t._u([{key:"item.status",fn:function(e){var r=e.item;return[a("v-chip",{attrs:{label:"",color:t.getColor(r.status),dark:""}},[t._v(" "+t._s(r.status)+" ")])]}},{key:"item.more",fn:function(e){var r=e.item;return[a("v-btn",{attrs:{icon:""},on:{click:function(e){return t.more(r)}}},[a("v-icon",[t._v(" mdi-dots-vertical")])],1)]}},{key:"item.paid",fn:function(e){var r=e.item;return[a("v-chip",{attrs:{label:"",color:t.getColor(r.paid),dark:""}},[t._v(" "+t._s(r.paid?"Paid":"Unpaid")+" ")])]}}],null,!0)}),a("v-dialog",{attrs:{"max-width":"700px"},model:{value:t.vis,callback:function(e){t.vis=e},expression:"vis"}},[a("v-card",[a("v-card-title",[a("span",{staticClass:"headline"},[t._v("Order Details")])]),a("p",{staticClass:"ml-5"},[t._v("Order ID: "+t._s(t.id))]),a("v-card-text",[a("v-container",{attrs:{"grid-list-md":""}},[a("v-layout",{attrs:{row:"",wrap:""}},[a("v-flex",{attrs:{xs12:""}},[a("v-data-table",{attrs:{headers:t.headerD,items:t.dataD,"items-per-page":3},scopedSlots:t._u([{key:"item.image",fn:function(e){var r=e.item;return[a("v-img",{attrs:{height:"100",width:"100","lazy-src":"h"==r.image[0]?r.image:"http://api.ashewa.com/media/"+r.image,src:"h"==r.image[0]?r.image:"http://api.ashewa.com/media/"+r.image},scopedSlots:t._u([{key:"placeholder",fn:function(){return[a("v-row",{staticClass:"fill-height ma-0",attrs:{align:"center",justify:"center"}},[a("v-progress-circular",{attrs:{indeterminate:"",color:"grey lighten-5"}})],1)]},proxy:!0}],null,!0)})]}},{key:"item.quantity",fn:function(e){var r=e.item;return[a("v-chip",{attrs:{label:"",color:"green",dark:""}},[t._v(t._s(r.quantity))])]}}],null,!0)})],1)],1)],1)],1),a("v-card-actions",[a("v-spacer"),a("v-btn",{attrs:{color:"blue darken-1",text:""},on:{click:function(e){t.vis=!1}}},[t._v(" Close ")])],1)],1)],1)],1)},i=[],s=a("5530"),n=(a("d81d"),a("b0c0"),a("2f62")),o={created:function(){this.isTokenSet?this.$store.dispatch("getOrderHistory"):this.$router.push("/login")},data:function(){return{dataD:[],id:"",headerD:[{text:"Image",value:"image"},{text:"Name",value:"name"},{text:"Quantity",value:"quantity"},{text:"Price",value:"price"}],headers:[{text:"Reference",value:"reference"},{text:"Total Price (in Birr)",value:"totalPrice"},{text:"Delivery Status",value:"status"},{text:"Payment Status",value:"paid"},{text:"More",value:"more"},{text:"Payment Method",value:"paymentMethod"}],vis:!1}},computed:Object(s["a"])(Object(s["a"])({},Object(n["c"])(["isTokenSet","user"])),{},{sampleData:function(){return"completed"==this.value?this.d:"delayed"==this.value?this.de:"canceled"==this.value?this.f:this.p},dataO:function(){console.log(this.$store.state.cart.orderHistory);var t=this.$store.state.cart.orderHistory.map((function(t){return{id:t.id,productId:t.orders,reference:t.reference,totalPrice:t.price,status:t.status,paid:t.paid,paymentMethod:t.paymentMethod}}));return t}}),methods:{getColor:function(t){return"COMPLETED"==t?"green":"PENDING"==t?"orange":"ACCEPTED"==t||1==t?"green":"red"},more:function(t){console.log(t),this.dataD=t.productId.map((function(t){return{image:t.product.image,name:t.product.name,quantity:t.quantity,price:t.product.sellingPrice}})),console.log(this.dataD),this.id=t.id,this.vis=!0}}},c=o,d=a("2877"),l=a("6544"),u=a.n(l),m=a("8336"),v=a("b0af"),p=a("99d9"),h=a("cc20"),f=a("a523"),g=a("8fea"),y=a("169a"),x=a("0e8f"),b=a("132d"),k=a("adda"),C=a("a722"),V=a("490a"),_=a("0fd9"),D=a("2fa4"),w=Object(d["a"])(c,r,i,!1,null,null,null);e["default"]=w.exports;u()(w,{VBtn:m["a"],VCard:v["a"],VCardActions:p["b"],VCardText:p["d"],VCardTitle:p["e"],VChip:h["a"],VContainer:f["a"],VDataTable:g["a"],VDialog:y["a"],VFlex:x["a"],VIcon:b["a"],VImg:k["a"],VLayout:C["a"],VProgressCircular:V["a"],VRow:_["a"],VSpacer:D["a"]})}}]);
//# sourceMappingURL=chunk-2d20881e.ee1c3d1b.js.map
|
import time
import traceback
from typing import Dict
import coinbasepro
from coinbasepro.exceptions import CoinbaseAPIError
from cbpa.logger import logger
from cbpa.schemas.buy import Buy
from cbpa.schemas.config import Config
from cbpa.schemas.currency import FCC
from cbpa.services.account import AccountService
from cbpa.services.discord import DiscordService
class BuyService:
MARKET_SIDE = "buy"
def __init__(
self,
config: Config,
coinbasepro_client: coinbasepro.AuthenticatedClient,
account_service: AccountService,
) -> None:
self.coinbasepro_client = coinbasepro_client
self.discord_service = DiscordService()
self.config = config
self.account_service = account_service
def place_market_order(self, buy: Buy, fiat: FCC) -> None:
pair = buy.pair()
amount = buy.send_amount
place_order_message = f"💸 Placing market order of {amount} {fiat} for {pair}."
logger.info(place_order_message)
response = self.coinbasepro_client.place_market_order(
product_id=pair, side=self.MARKET_SIDE, funds=amount
)
logger.info("Order placed! Getting order details.")
self.get_placed_order_details(buy=buy, response=response)
def get_placed_order_details(self, buy: Buy, response: Dict) -> None:
order_id = response["id"]
try:
order_details = self.coinbasepro_client.get_order(order_id=order_id)
order_filled_size = order_details["filled_size"]
purchase_success_message = (
f"👏 Successfully purchased {order_filled_size} of {buy.pair()}."
)
logger.info(purchase_success_message)
self.discord_service.send_alert(
config=self.config, message=purchase_success_message
)
except (CoinbaseAPIError, TypeError) as e:
if isinstance(e, CoinbaseAPIError):
logger.error(
f"Exception caught while getting order details: {e}. "
f"Order {order_id} was not created just yet. "
"Retrying order detail retrieval in 2 seconds."
)
elif isinstance(e, TypeError):
logger.error(f"Failed to parse the order details: {e}. Trying again.")
time.sleep(2)
self.get_placed_order_details(buy=buy, response=response)
def run(self, done: Dict) -> None:
try:
for buy in self.config.buys:
if not done[buy.receive_currency.value]:
buy_total = buy.send_amount
current_funds = self.account_service.get_balance_for_currency(
self.config.account.fiat_currency
)
if current_funds >= buy_total:
self.place_market_order(buy, self.config.account.fiat_currency)
done[buy.receive_currency.value] = True
elif current_funds < buy_total:
response = self.account_service.add_funds(
buy_total=buy_total,
current_funds=current_funds,
max_fund=self.config.account.auto_funding_limit,
fiat=self.config.account.fiat_currency,
)
if response.status == "Error":
logger.error(response.message)
self.discord_service.send_alert(
config=self.config, message=response.message
)
elif response.status == "Success":
self.place_market_order(
buy, self.config.account.fiat_currency
)
done[buy.receive_currency.value] = True
else:
logger.info(
f"Unhandled response status {response.status}."
" Moving on."
)
if not all(done.values()):
self.run(done=done)
except Exception:
logger.error("Unhandled general exception occurred.")
logger.error(traceback.format_exc())
self.run(done=done)
|
var denon = require('../../lib/app')
, config = require('./config');
var avr = new denon(new denon.transports.telnet(config));
avr.connect();
avr.on('connect', function() {
console.log('Connected');
avr.setPowerState(true, function(err, state) {
if (err) {
console.log(err.toString());
return;
}
console.log('The current power state is', state);
});
});
setTimeout(function() {
avr.getConnection().destroy();
process.exit(0);
}, 2000);
process.on('SIGINT', function() {
console.log("Caught interrupt signal");
avr.getConnection().destroy();
process.exit(0);
});
|
import cv2
import numpy as np
#-->0 = bilgisayar kamerası
#-->1 = usb ile takılmış kamera
#-->video ismi = bilgisayarda ki video
kamera = cv2.VideoCapture(0)
while True:
ret,kare = kamera.read()
cv2.rectangle(kare,(160,120),(480,360),[0,0,255],4)
bolge = kare[120:360,160:480]
print(kare.shape)
cv2.imshow("video",kare)
cv2.imshow("bolge",bolge)
if cv2.waitKey(1) & 0xFF == ord("q"):
break
kamera.release()
cv2.destroyAllWindows()
|
var a = { f: { g: 3 } };
a.f.h = 4;
a.f.g = 7;
|
angular.module('marbleCoreApp')
.factory('ProcessedPostsFactory', ['$resource', 'getInterceptor', ProcessedPostsFactory]);
function ProcessedPostsFactory($resource, getInterceptor) {
return $resource('/api/processedPosts', {}, {
deleteByTopic: {method: 'DELETE', params: {topicName: '@topicName'}, isArray: false, interceptor: getInterceptor}
})
};
|
# coding: utf-8
from timeUtils import clock, elapsed
from matplotlib import pyplot as plt
try:
import pygeohash as geohash
except:
import geohash
class drawClusters():
def __init__(self, soloclusters = None, geoCounts = None, bitlen = None, clusters = None):
self.clusters = clusters
self.geoCounts = geoCounts
self.bitlen = bitlen
self.soloclusters = soloclusters
self.routes=[('n', 'w'), ('n', 'e'), ('s', 'e'), ('s', 'w'), ('n', 'w')]
self.rangeLat = None
self.rangeLng = None
self.showCoM = True
self.showSoloClusters = False
def setGeoCounts(self, geoCounts):
self.geoCounts = geoCounts
def setGeoClusters(self, clusters):
self.clusters = clusters
def setSoloGeoClusters(self, soloclusters):
self.soloclusters = soloclusters
self.showSoloClusters = True
def setBitlen(self, bitlen):
self.bitlen = bitlen
def setCenterRadius(self, latCenter, lngCenter, radius):
self.rangeLat = (latCenter-radius,latCenter+radius)
self.rangeLng = (lngCenter-radius,lngCenter+radius)
def setLatRange(self, minval,maxval):
self.rangeLat = (minval,maxval)
def setLongRange(self, minval, maxval):
self.rangeLng = (minval, maxval)
def getCenter(self, gh):
from pygeohash import decode_exactly
lat,long = decode_exactly(gh)[:2]
return (lat, long)
def getBB(self, gh, istuple=False):
from pygeohash import bbox
if istuple is False:
bb = {'x': [], 'y': []}
else:
bb = []
boundbox = bbox(gh)
for route in self.routes:
if istuple is False:
bb['x'].append(boundbox[route[1]])
bb['y'].append(boundbox[route[0]])
else:
bb.append(tuple([boundbox[route[0]], boundbox[route[1]]]))
return bb
def drawBB(self, ax1=None):
import matplotlib.pyplot as plt
if ax1 is None:
fig, ax1 = plt.subplots()
ax1.set_facecolor('white')
if self.bitlen is None:
raise ValueError("bitlen is not set for drawing")
if isinstance(self.bitlen, list):
colors=['red', 'black', 'blue', 'green', 'magenta']
for i,blen in enumerate(self.bitlen):
try:
for geo,geoCnt in self.geoCounts[blen].most_common():
bb = self.getBB(geo)
ax1.plot(bb['x'], bb['y'], linestyle=':', color=colors[i], lw=0.5) # solid
except:
pass
else:
try:
for geo,geoCnt in self.geoCounts[self.bitlen].most_common():
bb = self.getBB(geo)
ax1.plot(bb['x'], bb['y'], linestyle=':', color='black', lw=0.5) # solid
except:
pass
ax1.set_xlabel("Longitude")
ax1.set_ylabel("Latitude")
return ax1
def plotClusters(self, ax1=None, long=None, lat=None):
from seaborn import color_palette
from haversine import haversine
if ax1 is None:
fig, ax1 = plt.subplots()
ax1.set_facecolor('white')
if self.bitlen is not None and self.geoCounts is not None and self.showCoM is True:
self.drawBB(ax1)
cp = color_palette('deep', len(self.clusters))
lineStyles = ['-' for i,_ in enumerate(self.clusters)]
lineWidths = [2 for i,_ in enumerate(self.clusters)]
latRange = [None, None]
lngRange = [None, None]
from matplotlib.patches import Circle, Wedge, Polygon
from matplotlib.collections import PatchCollection
patches=[]
pcols=[]
if self.showCoM is True and self.clusters is not None:
lats = []
lngs = []
wgts = []
radi = []
for cluster,clusterData in self.clusters.items():
lats.append(clusterData['CoM'][0])
lngs.append(clusterData['CoM'][1])
wgts.append(clusterData['Total'])
radi.append(clusterData['Radius']/111319.9)
pcols.append(tuple(cp[len(patches)]))
circle = Circle((lngs[-1], lats[-1]), radi[-1])
patches.append(circle)
wgts = [max([x,1.5]) for x in wgts]
wgts = [min([25,x]) for x in wgts]
latRange[0] = min(lats)
latRange[1] = max(lats)
lngRange[0] = min(lngs)
lngRange[1] = max(lngs)
p = PatchCollection(patches, alpha=0.5)
from numpy import array, linspace
p.set_array(linspace(0,1,len(pcols)))
ax1.add_collection(p)
ax1.scatter(lngs, lats, s=wgts, marker='x', linewidth=2, c='black', alpha=0.5)
if self.showSoloClusters is True and self.soloclusters is not None:
color = 'black'
lineStyle = ':'
lineWidth = 1
lats = []
lngs = []
wgts = []
pcols= []
patches=[]
for cluster,clusterData in self.soloclusters.items():
lats.append(clusterData['CoM'][0])
lngs.append(clusterData['CoM'][1])
wgts.append(clusterData['Total'])
pcols.append(1)
circle = Circle((lngs[-1], lats[-1]), 20/111319.9)
patches.append(circle)
latRange[0] = min([min(lats),latRange[0]])
latRange[1] = max([max(lats),latRange[1]])
lngRange[0] = min([min(lngs),lngRange[0]])
lngRange[1] = max([max(lngs),lngRange[1]])
p = PatchCollection(patches, alpha=0.15)
from numpy import array, linspace
p.set_array(linspace(0,1,len(pcols)))
ax1.add_collection(p)
ax1.scatter(lngs, lats, s=0.25, marker='.', linewidth=lineWidth, c=color, alpha=0.5)
elif showCoM is False and self.clusters is not None:
color = 'red'
lineStyle = lineStyles[0]
lineWidth = lineWidths[0]
for cluster,clusterData in self.clusters.items():
bb = self.getBB(geo)
ax1.plot(bb['x'], bb['y'], linestyle=lineStyle, color=color, lw=lineWidth)
if latRange[0] is None:
latRange[0] = bb['y']
else:
latRange[0] = min([latRange[0], bb['y']])
if latRange[1] is None:
latRange[1] = bb['y']
else:
latRange[1] = max([latRange[1], bb['y']])
if lngtRange[0] is None:
lngRange[0] = bb['x']
else:
lngRange[0] = min([lngRange[0], bb['x']])
if lngRange[1] is None:
lngRange[1] = bb['x']
else:
lngRange[1] = max([lngRange[1], bb['x']])
xmin = None
xmax = None
ymin = None
ymax = None
if self.rangeLng is not None:
xmin = max([lngRange[0], self.rangeLng[0]])
xmax = min([lngRange[1], self.rangeLng[1]])
xdif = xmax - xmin
xmin = xmin - 0.05*xdif
xmax = xmax + 0.05*xdif
ax1.set_xlim(xmin,xmax)
if self.rangeLat is not None:
ymin = max([latRange[0], self.rangeLat[0]])
ymax = min([latRange[1], self.rangeLat[1]])
ydif = ymax - ymin
ymin = ymin - 0.05*ydif
ymax = ymax + 0.05*ydif
ax1.set_ylim(ymin,ymax)
if all([xmin,xmax,ymin,ymax]):
distLat = 1000*haversine((xmin,ymin), (xmin,ymax))
distLng = 1000*haversine((xmin,ymin), (xmax,ymin))
longMeters = [0, distLng]
latMeters = [0, distLat]
ax2 = ax1.twinx()
ax2.plot(longMeters, latMeters, color='b', lw=0)
ax2.set_xlabel("Relative Longitude [m]")
ax3 = ax1.twiny()
ax3.plot(longMeters, latMeters, color='b', lw=0)
ax3.set_ylabel("Relative Latitude [m]")
# if long is not None and lat is not None:
# ax1.scatter(long, lat, s=1, linewidth=0, c='black', alpha=0.25)
from timeUtils import clock
start = clock("Compiled Plotting Tool")
|
import React from "react"
import { useStaticQuery, graphql } from "gatsby"
import Layout from "../components/layout"
import SEO from "../components/Utility/seo"
import MaskFaq from "../components/Views/MaskFaq"
const Maskfaq = () => {
const query = useStaticQuery(graphql`
query {
banner: file(relativePath: { eq: "screenmask.PNG" }) {
childImageSharp {
fluid(quality: 100) {
...GatsbyImageSharpFluid
}
}
}
}
`)
return (
<Layout>
<SEO title="FAQ" />
<MaskFaq image={query.banner.childImageSharp.fluid} />
</Layout>
)
}
export default Maskfaq
|
!function(e){var t={};function n(r){if(t[r])return t[r].exports;var a=t[r]={i:r,l:!1,exports:{}};return e[r].call(a.exports,a,a.exports,n),a.l=!0,a.exports}n.m=e,n.c=t,n.d=function(e,t,r){n.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:r})},n.r=function(e){"undefined"!==typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},n.t=function(e,t){if(1&t&&(e=n(e)),8&t)return e;if(4&t&&"object"===typeof e&&e&&e.__esModule)return e;var r=Object.create(null);if(n.r(r),Object.defineProperty(r,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var a in e)n.d(r,a,function(t){return e[t]}.bind(null,a));return r},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=7)}([function(e,t,n){e.exports=n(6)},function(e,t,n){"use strict";try{self["workbox:core:5.1.4"]&&_()}catch(r){}},function(e,t,n){"use strict";try{self["workbox:precaching:5.1.4"]&&_()}catch(r){}},function(e,t,n){"use strict";try{self["workbox:routing:5.1.4"]&&_()}catch(r){}},function(e,t,n){"use strict";try{self["workbox:strategies:5.1.4"]&&_()}catch(r){}},function(e,t,n){"use strict";try{self["workbox:expiration:5.1.4"]&&_()}catch(r){}},function(e,t,n){var r=function(e){"use strict";var t,n=Object.prototype,r=n.hasOwnProperty,a="function"===typeof Symbol?Symbol:{},i=a.iterator||"@@iterator",c=a.asyncIterator||"@@asyncIterator",o=a.toStringTag||"@@toStringTag";function u(e,t,n){return Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}),e[t]}try{u({},"")}catch(U){u=function(e,t,n){return e[t]=n}}function s(e,t,n,r){var a=t&&t.prototype instanceof y?t:y,i=Object.create(a.prototype),c=new O(r||[]);return i._invoke=function(e,t,n){var r=h;return function(a,i){if(r===p)throw new Error("Generator is already running");if(r===v){if("throw"===a)throw i;return S()}for(n.method=a,n.arg=i;;){var c=n.delegate;if(c){var o=E(c,n);if(o){if(o===d)continue;return o}}if("next"===n.method)n.sent=n._sent=n.arg;else if("throw"===n.method){if(r===h)throw r=v,n.arg;n.dispatchException(n.arg)}else"return"===n.method&&n.abrupt("return",n.arg);r=p;var u=f(e,t,n);if("normal"===u.type){if(r=n.done?v:l,u.arg===d)continue;return{value:u.arg,done:n.done}}"throw"===u.type&&(r=v,n.method="throw",n.arg=u.arg)}}}(e,n,c),i}function f(e,t,n){try{return{type:"normal",arg:e.call(t,n)}}catch(U){return{type:"throw",arg:U}}}e.wrap=s;var h="suspendedStart",l="suspendedYield",p="executing",v="completed",d={};function y(){}function m(){}function g(){}var x={};x[i]=function(){return this};var w=Object.getPrototypeOf,b=w&&w(w(T([])));b&&b!==n&&r.call(b,i)&&(x=b);var k=g.prototype=y.prototype=Object.create(x);function _(e){["next","throw","return"].forEach((function(t){u(e,t,(function(e){return this._invoke(t,e)}))}))}function R(e,t){function n(a,i,c,o){var u=f(e[a],e,i);if("throw"!==u.type){var s=u.arg,h=s.value;return h&&"object"===typeof h&&r.call(h,"__await")?t.resolve(h.__await).then((function(e){n("next",e,c,o)}),(function(e){n("throw",e,c,o)})):t.resolve(h).then((function(e){s.value=e,c(s)}),(function(e){return n("throw",e,c,o)}))}o(u.arg)}var a;this._invoke=function(e,r){function i(){return new t((function(t,a){n(e,r,t,a)}))}return a=a?a.then(i,i):i()}}function E(e,n){var r=e.iterator[n.method];if(r===t){if(n.delegate=null,"throw"===n.method){if(e.iterator.return&&(n.method="return",n.arg=t,E(e,n),"throw"===n.method))return d;n.method="throw",n.arg=new TypeError("The iterator does not provide a 'throw' method")}return d}var a=f(r,e.iterator,n.arg);if("throw"===a.type)return n.method="throw",n.arg=a.arg,n.delegate=null,d;var i=a.arg;return i?i.done?(n[e.resultName]=i.value,n.next=e.nextLoc,"return"!==n.method&&(n.method="next",n.arg=t),n.delegate=null,d):i:(n.method="throw",n.arg=new TypeError("iterator result is not an object"),n.delegate=null,d)}function L(e){var t={tryLoc:e[0]};1 in e&&(t.catchLoc=e[1]),2 in e&&(t.finallyLoc=e[2],t.afterLoc=e[3]),this.tryEntries.push(t)}function q(e){var t=e.completion||{};t.type="normal",delete t.arg,e.completion=t}function O(e){this.tryEntries=[{tryLoc:"root"}],e.forEach(L,this),this.reset(!0)}function T(e){if(e){var n=e[i];if(n)return n.call(e);if("function"===typeof e.next)return e;if(!isNaN(e.length)){var a=-1,c=function n(){for(;++a<e.length;)if(r.call(e,a))return n.value=e[a],n.done=!1,n;return n.value=t,n.done=!0,n};return c.next=c}}return{next:S}}function S(){return{value:t,done:!0}}return m.prototype=k.constructor=g,g.constructor=m,m.displayName=u(g,o,"GeneratorFunction"),e.isGeneratorFunction=function(e){var t="function"===typeof e&&e.constructor;return!!t&&(t===m||"GeneratorFunction"===(t.displayName||t.name))},e.mark=function(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,g):(e.__proto__=g,u(e,o,"GeneratorFunction")),e.prototype=Object.create(k),e},e.awrap=function(e){return{__await:e}},_(R.prototype),R.prototype[c]=function(){return this},e.AsyncIterator=R,e.async=function(t,n,r,a,i){void 0===i&&(i=Promise);var c=new R(s(t,n,r,a),i);return e.isGeneratorFunction(n)?c:c.next().then((function(e){return e.done?e.value:c.next()}))},_(k),u(k,o,"Generator"),k[i]=function(){return this},k.toString=function(){return"[object Generator]"},e.keys=function(e){var t=[];for(var n in e)t.push(n);return t.reverse(),function n(){for(;t.length;){var r=t.pop();if(r in e)return n.value=r,n.done=!1,n}return n.done=!0,n}},e.values=T,O.prototype={constructor:O,reset:function(e){if(this.prev=0,this.next=0,this.sent=this._sent=t,this.done=!1,this.delegate=null,this.method="next",this.arg=t,this.tryEntries.forEach(q),!e)for(var n in this)"t"===n.charAt(0)&&r.call(this,n)&&!isNaN(+n.slice(1))&&(this[n]=t)},stop:function(){this.done=!0;var e=this.tryEntries[0].completion;if("throw"===e.type)throw e.arg;return this.rval},dispatchException:function(e){if(this.done)throw e;var n=this;function a(r,a){return o.type="throw",o.arg=e,n.next=r,a&&(n.method="next",n.arg=t),!!a}for(var i=this.tryEntries.length-1;i>=0;--i){var c=this.tryEntries[i],o=c.completion;if("root"===c.tryLoc)return a("end");if(c.tryLoc<=this.prev){var u=r.call(c,"catchLoc"),s=r.call(c,"finallyLoc");if(u&&s){if(this.prev<c.catchLoc)return a(c.catchLoc,!0);if(this.prev<c.finallyLoc)return a(c.finallyLoc)}else if(u){if(this.prev<c.catchLoc)return a(c.catchLoc,!0)}else{if(!s)throw new Error("try statement without catch or finally");if(this.prev<c.finallyLoc)return a(c.finallyLoc)}}}},abrupt:function(e,t){for(var n=this.tryEntries.length-1;n>=0;--n){var a=this.tryEntries[n];if(a.tryLoc<=this.prev&&r.call(a,"finallyLoc")&&this.prev<a.finallyLoc){var i=a;break}}i&&("break"===e||"continue"===e)&&i.tryLoc<=t&&t<=i.finallyLoc&&(i=null);var c=i?i.completion:{};return c.type=e,c.arg=t,i?(this.method="next",this.next=i.finallyLoc,d):this.complete(c)},complete:function(e,t){if("throw"===e.type)throw e.arg;return"break"===e.type||"continue"===e.type?this.next=e.arg:"return"===e.type?(this.rval=this.arg=e.arg,this.method="return",this.next="end"):"normal"===e.type&&t&&(this.next=t),d},finish:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var n=this.tryEntries[t];if(n.finallyLoc===e)return this.complete(n.completion,n.afterLoc),q(n),d}},catch:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var n=this.tryEntries[t];if(n.tryLoc===e){var r=n.completion;if("throw"===r.type){var a=r.arg;q(n)}return a}}throw new Error("illegal catch attempt")},delegateYield:function(e,n,r){return this.delegate={iterator:T(e),resultName:n,nextLoc:r},"next"===this.method&&(this.arg=t),d}},e}(e.exports);try{regeneratorRuntime=r}catch(a){Function("r","regeneratorRuntime = r")(r)}},function(e,t,n){"use strict";function r(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);n<t;n++)r[n]=e[n];return r}function a(e,t){if(e){if("string"===typeof e)return r(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?r(e,t):void 0}}function i(e){return function(e){if(Array.isArray(e))return r(e)}(e)||function(e){if("undefined"!==typeof Symbol&&Symbol.iterator in Object(e))return Array.from(e)}(e)||a(e)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}n.r(t);n(1);function c(e,t){var n;if("undefined"===typeof Symbol||null==e[Symbol.iterator]){if(Array.isArray(e)||(n=a(e))||t&&e&&"number"===typeof e.length){n&&(e=n);var r=0,i=function(){};return{s:i,n:function(){return r>=e.length?{done:!0}:{done:!1,value:e[r++]}},e:function(e){throw e},f:i}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var c,o=!0,u=!1;return{s:function(){n=e[Symbol.iterator]()},n:function(){var e=n.next();return o=e.done,e},e:function(e){u=!0,c=e},f:function(){try{o||null==n.return||n.return()}finally{if(u)throw c}}}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function u(e,t){return(u=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e})(e,t)}function s(e,t){if("function"!==typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),t&&u(e,t)}function f(e){return(f=Object.setPrototypeOf?Object.getPrototypeOf:function(e){return e.__proto__||Object.getPrototypeOf(e)})(e)}function h(){if("undefined"===typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"===typeof Proxy)return!0;try{return Date.prototype.toString.call(Reflect.construct(Date,[],(function(){}))),!0}catch(e){return!1}}function l(e){return(l="function"===typeof Symbol&&"symbol"===typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"===typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function p(e,t){return!t||"object"!==l(t)&&"function"!==typeof t?function(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}(e):t}function v(e){var t=h();return function(){var n,r=f(e);if(t){var a=f(this).constructor;n=Reflect.construct(r,arguments,a)}else n=r.apply(this,arguments);return p(this,n)}}function d(e,t,n){return(d=h()?Reflect.construct:function(e,t,n){var r=[null];r.push.apply(r,t);var a=new(Function.bind.apply(e,r));return n&&u(a,n.prototype),a}).apply(null,arguments)}function y(e){var t="function"===typeof Map?new Map:void 0;return(y=function(e){if(null===e||(n=e,-1===Function.toString.call(n).indexOf("[native code]")))return e;var n;if("function"!==typeof e)throw new TypeError("Super expression must either be null or a function");if("undefined"!==typeof t){if(t.has(e))return t.get(e);t.set(e,r)}function r(){return d(e,arguments,f(this).constructor)}return r.prototype=Object.create(e.prototype,{constructor:{value:r,enumerable:!1,writable:!0,configurable:!0}}),u(r,e)})(e)}var m=function(e){for(var t=e,n=arguments.length,r=new Array(n>1?n-1:0),a=1;a<n;a++)r[a-1]=arguments[a];return r.length>0&&(t+=" :: ".concat(JSON.stringify(r))),t},g=function(e){s(n,e);var t=v(n);function n(e,r){var a;o(this,n);var i=m(e,r);return(a=t.call(this,i)).name=e,a.details=r,a}return n}(y(Error)),x=new Set;function w(e){x.add(e)}var b={googleAnalytics:"googleAnalytics",precache:"precache-v2",prefix:"workbox",runtime:"runtime",suffix:"undefined"!==typeof registration?registration.scope:""},k=function(e){return[b.prefix,e,b.suffix].filter((function(e){return e&&e.length>0})).join("-")},_=function(e){return e||k(b.precache)},R=function(e){return e||k(b.runtime)},E=n(0),L=n.n(E);function q(e,t,n,r,a,i,c){try{var o=e[i](c),u=o.value}catch(s){return void n(s)}o.done?t(u):Promise.resolve(u).then(r,a)}function O(e){return function(){var t=this,n=arguments;return new Promise((function(r,a){var i=e.apply(t,n);function c(e){q(i,r,a,c,o,"next",e)}function o(e){q(i,r,a,c,o,"throw",e)}c(void 0)}))}}function T(){return S.apply(this,arguments)}function S(){return(S=O(L.a.mark((function e(){var t,n,r;return L.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:0,t=c(x),e.prev=2,t.s();case 4:if((n=t.n()).done){e.next=11;break}return r=n.value,e.next=8,r();case 8:0;case 9:e.next=4;break;case 11:e.next=16;break;case 13:e.prev=13,e.t0=e.catch(2),t.e(e.t0);case 16:return e.prev=16,t.f(),e.finish(16);case 19:0;case 20:case"end":return e.stop()}}),e,null,[[2,13,16,19]])})))).apply(this,arguments)}var U,N=function(e){return new URL(String(e),location.href).href.replace(new RegExp("^".concat(location.origin)),"")},A=function(e,t){return e.filter((function(e){return t in e}))},j=function(){var e=O(L.a.mark((function e(t){var n,r,a,i,o,u,s,f;return L.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:n=t.request,r=t.mode,a=t.plugins,i=A(void 0===a?[]:a,"cacheKeyWillBeUsed"),o=n,u=c(i),e.prev=4,u.s();case 6:if((s=u.n()).done){e.next=15;break}return f=s.value,e.next=10,f.cacheKeyWillBeUsed.call(f,{mode:r,request:o});case 10:"string"===typeof(o=e.sent)&&(o=new Request(o));case 13:e.next=6;break;case 15:e.next=20;break;case 17:e.prev=17,e.t0=e.catch(4),u.e(e.t0);case 20:return e.prev=20,u.f(),e.finish(20);case 23:return e.abrupt("return",o);case 24:case"end":return e.stop()}}),e,null,[[4,17,20,23]])})));return function(t){return e.apply(this,arguments)}}(),C=function(){var e=O(L.a.mark((function e(t){var n,r,a,i,o,u,s,f,h,l;return L.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:n=t.request,r=t.response,a=t.event,i=t.plugins,o=r,u=!1,s=c(void 0===i?[]:i),e.prev=4,s.s();case 6:if((f=s.n()).done){e.next=19;break}if(!("cacheWillUpdate"in(h=f.value))){e.next=17;break}return u=!0,l=h.cacheWillUpdate,e.next=13,l.call(h,{request:n,response:o,event:a});case 13:if(o=e.sent){e.next=17;break}return e.abrupt("break",19);case 17:e.next=6;break;case 19:e.next=24;break;case 21:e.prev=21,e.t0=e.catch(4),s.e(e.t0);case 24:return e.prev=24,s.f(),e.finish(24);case 27:return u||(o=o&&200===o.status?o:void 0),e.abrupt("return",o||null);case 29:case"end":return e.stop()}}),e,null,[[4,21,24,27]])})));return function(t){return e.apply(this,arguments)}}(),M=function(){var e=O(L.a.mark((function e(t){var n,r,a,i,o,u,s,f,h,l,p,v,d;return L.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return n=t.cacheName,r=t.request,a=t.event,i=t.matchOptions,o=t.plugins,u=void 0===o?[]:o,e.next=3,self.caches.open(n);case 3:return s=e.sent,e.next=6,j({plugins:u,request:r,mode:"read"});case 6:return f=e.sent,e.next=9,s.match(f,i);case 9:h=e.sent,l=c(u),e.prev=12,l.s();case 14:if((p=l.n()).done){e.next=24;break}if(!("cachedResponseWillBeUsed"in(v=p.value))){e.next=22;break}return d=v.cachedResponseWillBeUsed,e.next=20,d.call(v,{cacheName:n,event:a,matchOptions:i,cachedResponse:h,request:f});case 20:h=e.sent;case 22:e.next=14;break;case 24:e.next=29;break;case 26:e.prev=26,e.t0=e.catch(12),l.e(e.t0);case 29:return e.prev=29,l.f(),e.finish(29);case 32:return e.abrupt("return",h);case 33:case"end":return e.stop()}}),e,null,[[12,26,29,32]])})));return function(t){return e.apply(this,arguments)}}(),K={put:function(){var e=O(L.a.mark((function e(t){var n,r,a,i,o,u,s,f,h,l,p,v,d,y,m;return L.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:n=t.cacheName,r=t.request,a=t.response,i=t.event,o=t.plugins,u=void 0===o?[]:o,s=t.matchOptions,e.next=4;break;case 4:return e.next=6,j({plugins:u,request:r,mode:"write"});case 6:if(f=e.sent,a){e.next=10;break}throw new g("cache-put-with-no-response",{url:N(f.url)});case 10:return e.next=12,C({event:i,plugins:u,response:a,request:f});case 12:if(h=e.sent){e.next=16;break}return e.abrupt("return");case 16:return e.next=18,self.caches.open(n);case 18:if(l=e.sent,!((p=A(u,"cacheDidUpdate")).length>0)){e.next=26;break}return e.next=23,M({cacheName:n,matchOptions:s,request:f});case 23:e.t0=e.sent,e.next=27;break;case 26:e.t0=null;case 27:return v=e.t0,e.prev=29,e.next=32,l.put(f,h);case 32:e.next=40;break;case 34:if(e.prev=34,e.t1=e.catch(29),"QuotaExceededError"!==e.t1.name){e.next=39;break}return e.next=39,T();case 39:throw e.t1;case 40:d=c(p),e.prev=41,d.s();case 43:if((y=d.n()).done){e.next=49;break}return m=y.value,e.next=47,m.cacheDidUpdate.call(m,{cacheName:n,event:i,oldResponse:v,newResponse:h,request:f});case 47:e.next=43;break;case 49:e.next=54;break;case 51:e.prev=51,e.t2=e.catch(41),d.e(e.t2);case 54:return e.prev=54,d.f(),e.finish(54);case 57:case"end":return e.stop()}}),e,null,[[29,34],[41,51,54,57]])})));return function(t){return e.apply(this,arguments)}}(),match:M};function P(){if(void 0===U){var e=new Response("");if("body"in e)try{new Response(e.body),U=!0}catch(t){U=!1}U=!1}return U}function I(e){e.then((function(){}))}function D(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){if("undefined"!==typeof Symbol&&Symbol.iterator in Object(e)){var n=[],r=!0,a=!1,i=void 0;try{for(var c,o=e[Symbol.iterator]();!(r=(c=o.next()).done)&&(n.push(c.value),!t||n.length!==t);r=!0);}catch(u){a=!0,i=u}finally{try{r||null==o.return||o.return()}finally{if(a)throw i}}return n}}(e,t)||a(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function W(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}function F(e,t,n){return t&&W(e.prototype,t),n&&W(e,n),e}var B=function(){function e(t,n){var r=this,a=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},i=a.onupgradeneeded,c=a.onversionchange;o(this,e),this._db=null,this._name=t,this._version=n,this._onupgradeneeded=i,this._onversionchange=c||function(){return r.close()}}return F(e,[{key:"db",get:function(){return this._db}},{key:"open",value:function(){var e=O(L.a.mark((function e(){var t=this;return L.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(!this._db){e.next=2;break}return e.abrupt("return");case 2:return e.next=4,new Promise((function(e,n){var r=!1;setTimeout((function(){r=!0,n(new Error("The open request was blocked and timed out"))}),t.OPEN_TIMEOUT);var a=indexedDB.open(t._name,t._version);a.onerror=function(){return n(a.error)},a.onupgradeneeded=function(e){r?(a.transaction.abort(),a.result.close()):"function"===typeof t._onupgradeneeded&&t._onupgradeneeded(e)},a.onsuccess=function(){var n=a.result;r?n.close():(n.onversionchange=t._onversionchange.bind(t),e(n))}}));case 4:return this._db=e.sent,e.abrupt("return",this);case 6:case"end":return e.stop()}}),e,this)})));return function(){return e.apply(this,arguments)}}()},{key:"getKey",value:function(){var e=O(L.a.mark((function e(t,n){return L.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,this.getAllKeys(t,n,1);case 2:return e.abrupt("return",e.sent[0]);case 3:case"end":return e.stop()}}),e,this)})));return function(t,n){return e.apply(this,arguments)}}()},{key:"getAll",value:function(){var e=O(L.a.mark((function e(t,n,r){return L.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,this.getAllMatching(t,{query:n,count:r});case 2:return e.abrupt("return",e.sent);case 3:case"end":return e.stop()}}),e,this)})));return function(t,n,r){return e.apply(this,arguments)}}()},{key:"getAllKeys",value:function(){var e=O(L.a.mark((function e(t,n,r){var a;return L.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,this.getAllMatching(t,{query:n,count:r,includeKeys:!0});case 2:return a=e.sent,e.abrupt("return",a.map((function(e){return e.key})));case 4:case"end":return e.stop()}}),e,this)})));return function(t,n,r){return e.apply(this,arguments)}}()},{key:"getAllMatching",value:function(){var e=O(L.a.mark((function e(t){var n,r,a,i,c,o,u,s,f,h=arguments;return L.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return n=h.length>1&&void 0!==h[1]?h[1]:{},r=n.index,a=n.query,i=void 0===a?null:a,c=n.direction,o=void 0===c?"next":c,u=n.count,s=n.includeKeys,f=void 0!==s&&s,e.next=3,this.transaction([t],"readonly",(function(e,n){var a=e.objectStore(t),c=r?a.index(r):a,s=[],h=c.openCursor(i,o);h.onsuccess=function(){var e=h.result;e?(s.push(f?e:e.value),u&&s.length>=u?n(s):e.continue()):n(s)}}));case 3:return e.abrupt("return",e.sent);case 4:case"end":return e.stop()}}),e,this)})));return function(t){return e.apply(this,arguments)}}()},{key:"transaction",value:function(){var e=O(L.a.mark((function e(t,n,r){var a=this;return L.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,this.open();case 2:return e.next=4,new Promise((function(e,i){var c=a._db.transaction(t,n);c.onabort=function(){return i(c.error)},c.oncomplete=function(){return e()},r(c,(function(t){return e(t)}))}));case 4:return e.abrupt("return",e.sent);case 5:case"end":return e.stop()}}),e,this)})));return function(t,n,r){return e.apply(this,arguments)}}()},{key:"_call",value:function(){var e=O(L.a.mark((function e(t,n,r){var a,i,c,o,u=arguments;return L.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:for(a=u.length,i=new Array(a>3?a-3:0),c=3;c<a;c++)i[c-3]=u[c];return o=function(e,r){var a=e.objectStore(n),c=a[t].apply(a,i);c.onsuccess=function(){return r(c.result)}},e.next=4,this.transaction([n],r,o);case 4:return e.abrupt("return",e.sent);case 5:case"end":return e.stop()}}),e,this)})));return function(t,n,r){return e.apply(this,arguments)}}()},{key:"close",value:function(){this._db&&(this._db.close(),this._db=null)}}]),e}();B.prototype.OPEN_TIMEOUT=2e3;for(var H=function(){var e,t=D(Y[G],2),n=t[0],r=c(t[1]);try{var a=function(){var t=e.value;t in IDBObjectStore.prototype&&(B.prototype[t]=function(){var e=O(L.a.mark((function e(r){var a,i,c,o=arguments;return L.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:for(a=o.length,i=new Array(a>1?a-1:0),c=1;c<a;c++)i[c-1]=o[c];return e.next=3,this._call.apply(this,[t,r,n].concat(i));case 3:return e.abrupt("return",e.sent);case 4:case"end":return e.stop()}}),e,this)})));return function(t){return e.apply(this,arguments)}}())};for(r.s();!(e=r.n()).done;)a()}catch(i){r.e(i)}finally{r.f()}},G=0,Y=Object.entries({readonly:["get","count","getKey","getAll","getAllKeys"],readwrite:["add","put","clear","delete"]});G<Y.length;G++)H();var Z=function(){var e=O(L.a.mark((function e(t){return L.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,new Promise((function(e,n){var r=indexedDB.deleteDatabase(t);r.onerror=function(){n(r.error)},r.onblocked=function(){n(new Error("Delete blocked"))},r.onsuccess=function(){e()}}));case 2:case"end":return e.stop()}}),e)})));return function(t){return e.apply(this,arguments)}}(),X={fetch:function(){var e=O(L.a.mark((function e(t){var n,r,a,i,o,u,s,f,h,l,p,v,d,y,m,x,w,b,k,_,R;return L.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(n=t.request,r=t.fetchOptions,a=t.event,i=t.plugins,o=void 0===i?[]:i,"string"===typeof n&&(n=new Request(n)),!(a instanceof FetchEvent&&a.preloadResponse)){e.next=9;break}return e.next=5,a.preloadResponse;case 5:if(!(u=e.sent)){e.next=9;break}return e.abrupt("return",u);case 9:0,s=A(o,"fetchDidFail"),f=s.length>0?n.clone():null,e.prev=12,h=c(o),e.prev=14,h.s();case 16:if((l=h.n()).done){e.next=27;break}if(!("requestWillFetch"in(p=l.value))){e.next=25;break}return v=p.requestWillFetch,d=n.clone(),e.next=23,v.call(p,{request:d,event:a});case 23:n=e.sent;case 25:e.next=16;break;case 27:e.next=32;break;case 29:e.prev=29,e.t0=e.catch(14),h.e(e.t0);case 32:return e.prev=32,h.f(),e.finish(32);case 35:e.next=40;break;case 37:throw e.prev=37,e.t1=e.catch(12),new g("plugin-error-request-will-fetch",{thrownError:e.t1});case 40:if(y=n.clone(),e.prev=41,"navigate"!==n.mode){e.next=48;break}return e.next=45,fetch(n);case 45:m=e.sent,e.next=51;break;case 48:return e.next=50,fetch(n,r);case 50:m=e.sent;case 51:0,x=c(o),e.prev=53,x.s();case 55:if((w=x.n()).done){e.next=64;break}if(!("fetchDidSucceed"in(b=w.value))){e.next=62;break}return e.next=60,b.fetchDidSucceed.call(b,{event:a,request:y,response:m});case 60:m=e.sent;case 62:e.next=55;break;case 64:e.next=69;break;case 66:e.prev=66,e.t2=e.catch(53),x.e(e.t2);case 69:return e.prev=69,x.f(),e.finish(69);case 72:return e.abrupt("return",m);case 75:e.prev=75,e.t3=e.catch(41),k=c(s),e.prev=79,k.s();case 81:if((_=k.n()).done){e.next=87;break}return R=_.value,e.next=85,R.fetchDidFail.call(R,{error:e.t3,event:a,originalRequest:f.clone(),request:y.clone()});case 85:e.next=81;break;case 87:e.next=92;break;case 89:e.prev=89,e.t4=e.catch(79),k.e(e.t4);case 92:return e.prev=92,k.f(),e.finish(92);case 95:throw e.t3;case 96:case"end":return e.stop()}}),e,null,[[12,37],[14,29,32,35],[41,75],[53,66,69,72],[79,89,92,95]])})));return function(t){return e.apply(this,arguments)}}()};function Q(e,t){return $.apply(this,arguments)}function $(){return($=O(L.a.mark((function e(t,n){var r,a,i,c;return L.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(r=t.clone(),a={headers:new Headers(r.headers),status:r.status,statusText:r.statusText},i=n?n(a):a,!P()){e.next=7;break}e.t0=r.body,e.next=10;break;case 7:return e.next=9,r.blob();case 9:e.t0=e.sent;case 10:return c=e.t0,e.abrupt("return",new Response(c,i));case 12:case"end":return e.stop()}}),e)})))).apply(this,arguments)}n(5);var J="cache-entries",V=function(e){var t=new URL(e,location.href);return t.hash="",t.href},z=function(){function e(t){var n=this;o(this,e),this._cacheName=t,this._db=new B("workbox-expiration",1,{onupgradeneeded:function(e){return n._handleUpgrade(e)}})}return F(e,[{key:"_handleUpgrade",value:function(e){var t=e.target.result.createObjectStore(J,{keyPath:"id"});t.createIndex("cacheName","cacheName",{unique:!1}),t.createIndex("timestamp","timestamp",{unique:!1}),Z(this._cacheName)}},{key:"setTimestamp",value:function(){var e=O(L.a.mark((function e(t,n){var r;return L.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return t=V(t),r={url:t,timestamp:n,cacheName:this._cacheName,id:this._getId(t)},e.next=4,this._db.put(J,r);case 4:case"end":return e.stop()}}),e,this)})));return function(t,n){return e.apply(this,arguments)}}()},{key:"getTimestamp",value:function(){var e=O(L.a.mark((function e(t){var n;return L.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,this._db.get(J,this._getId(t));case 2:return n=e.sent,e.abrupt("return",n.timestamp);case 4:case"end":return e.stop()}}),e,this)})));return function(t){return e.apply(this,arguments)}}()},{key:"expireEntries",value:function(){var e=O(L.a.mark((function e(t,n){var r,a,i,o,u,s=this;return L.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,this._db.transaction(J,"readwrite",(function(e,r){var a=e.objectStore(J).index("timestamp").openCursor(null,"prev"),i=[],c=0;a.onsuccess=function(){var e=a.result;if(e){var o=e.value;o.cacheName===s._cacheName&&(t&&o.timestamp<t||n&&c>=n?i.push(e.value):c++),e.continue()}else r(i)}}));case 2:r=e.sent,a=[],i=c(r),e.prev=5,i.s();case 7:if((o=i.n()).done){e.next=14;break}return u=o.value,e.next=11,this._db.delete(J,u.id);case 11:a.push(u.url);case 12:e.next=7;break;case 14:e.next=19;break;case 16:e.prev=16,e.t0=e.catch(5),i.e(e.t0);case 19:return e.prev=19,i.f(),e.finish(19);case 22:return e.abrupt("return",a);case 23:case"end":return e.stop()}}),e,this,[[5,16,19,22]])})));return function(t,n){return e.apply(this,arguments)}}()},{key:"_getId",value:function(e){return this._cacheName+"|"+V(e)}}]),e}(),ee=function(){function e(t){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};o(this,e),this._isRunning=!1,this._rerunRequested=!1,this._maxEntries=n.maxEntries,this._maxAgeSeconds=n.maxAgeSeconds,this._cacheName=t,this._timestampModel=new z(t)}return F(e,[{key:"expireEntries",value:function(){var e=O(L.a.mark((function e(){var t,n,r,a,i,o;return L.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(!this._isRunning){e.next=3;break}return this._rerunRequested=!0,e.abrupt("return");case 3:return this._isRunning=!0,t=this._maxAgeSeconds?Date.now()-1e3*this._maxAgeSeconds:0,e.next=7,this._timestampModel.expireEntries(t,this._maxEntries);case 7:return n=e.sent,e.next=10,self.caches.open(this._cacheName);case 10:r=e.sent,a=c(n),e.prev=12,a.s();case 14:if((i=a.n()).done){e.next=20;break}return o=i.value,e.next=18,r.delete(o);case 18:e.next=14;break;case 20:e.next=25;break;case 22:e.prev=22,e.t0=e.catch(12),a.e(e.t0);case 25:return e.prev=25,a.f(),e.finish(25);case 28:0,this._isRunning=!1,this._rerunRequested&&(this._rerunRequested=!1,I(this.expireEntries()));case 31:case"end":return e.stop()}}),e,this,[[12,22,25,28]])})));return function(){return e.apply(this,arguments)}}()},{key:"updateTimestamp",value:function(){var e=O(L.a.mark((function e(t){return L.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=3,this._timestampModel.setTimestamp(t,Date.now());case 3:case"end":return e.stop()}}),e,this)})));return function(t){return e.apply(this,arguments)}}()},{key:"isURLExpired",value:function(){var e=O(L.a.mark((function e(t){var n,r;return L.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(this._maxAgeSeconds){e.next=6;break}e.next=3;break;case 3:return e.abrupt("return",!1);case 6:return e.next=8,this._timestampModel.getTimestamp(t);case 8:return n=e.sent,r=Date.now()-1e3*this._maxAgeSeconds,e.abrupt("return",n<r);case 11:case"end":return e.stop()}}),e,this)})));return function(t){return e.apply(this,arguments)}}()},{key:"delete",value:function(){var e=O(L.a.mark((function e(){return L.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return this._rerunRequested=!1,e.next=3,this._timestampModel.expireEntries(1/0);case 3:case"end":return e.stop()}}),e,this)})));return function(){return e.apply(this,arguments)}}()}]),e}(),te=function(){function e(){var t=this,n=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};o(this,e),this.cachedResponseWillBeUsed=function(){var e=O(L.a.mark((function e(n){var r,a,i,c,o,u,s;return L.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(r=n.event,a=n.request,i=n.cacheName,c=n.cachedResponse){e.next=3;break}return e.abrupt("return",null);case 3:if(o=t._isResponseDateFresh(c),I((u=t._getCacheExpiration(i)).expireEntries()),s=u.updateTimestamp(a.url),r)try{r.waitUntil(s)}catch(f){0}return e.abrupt("return",o?c:null);case 9:case"end":return e.stop()}}),e)})));return function(t){return e.apply(this,arguments)}}(),this.cacheDidUpdate=function(){var e=O(L.a.mark((function e(n){var r,a,i;return L.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return r=n.cacheName,a=n.request,i=t._getCacheExpiration(r),e.next=5,i.updateTimestamp(a.url);case 5:return e.next=7,i.expireEntries();case 7:case"end":return e.stop()}}),e)})));return function(t){return e.apply(this,arguments)}}(),this._config=n,this._maxAgeSeconds=n.maxAgeSeconds,this._cacheExpirations=new Map,n.purgeOnQuotaError&&w((function(){return t.deleteCacheAndMetadata()}))}return F(e,[{key:"_getCacheExpiration",value:function(e){if(e===R())throw new g("expire-custom-caches-only");var t=this._cacheExpirations.get(e);return t||(t=new ee(e,this._config),this._cacheExpirations.set(e,t)),t}},{key:"_isResponseDateFresh",value:function(e){if(!this._maxAgeSeconds)return!0;var t=this._getDateHeaderTimestamp(e);return null===t||t>=Date.now()-1e3*this._maxAgeSeconds}},{key:"_getDateHeaderTimestamp",value:function(e){if(!e.headers.has("date"))return null;var t=e.headers.get("date"),n=new Date(t).getTime();return isNaN(n)?null:n}},{key:"deleteCacheAndMetadata",value:function(){var e=O(L.a.mark((function e(){var t,n,r,a,i;return L.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:t=c(this._cacheExpirations),e.prev=1,t.s();case 3:if((n=t.n()).done){e.next=11;break}return r=D(n.value,2),a=r[0],i=r[1],e.next=7,self.caches.delete(a);case 7:return e.next=9,i.delete();case 9:e.next=3;break;case 11:e.next=16;break;case 13:e.prev=13,e.t0=e.catch(1),t.e(e.t0);case 16:return e.prev=16,t.f(),e.finish(16);case 19:this._cacheExpirations=new Map;case 20:case"end":return e.stop()}}),e,this,[[1,13,16,19]])})));return function(){return e.apply(this,arguments)}}()}]),e}(),ne=(n(2),[]),re=function(){return ne};function ae(e){if(!e)throw new g("add-to-cache-list-unexpected-type",{entry:e});if("string"===typeof e){var t=new URL(e,location.href);return{cacheKey:t.href,url:t.href}}var n=e.revision,r=e.url;if(!r)throw new g("add-to-cache-list-unexpected-type",{entry:e});if(!n){var a=new URL(r,location.href);return{cacheKey:a.href,url:a.href}}var i=new URL(r,location.href),c=new URL(r,location.href);return i.searchParams.set("__WB_REVISION__",n),{cacheKey:i.href,url:c.href}}var ie,ce=function(){function e(t){o(this,e),this._cacheName=_(t),this._urlsToCacheKeys=new Map,this._urlsToCacheModes=new Map,this._cacheKeysToIntegrities=new Map}return F(e,[{key:"addToCacheList",value:function(e){var t,n=[],r=c(e);try{for(r.s();!(t=r.n()).done;){var a=t.value;"string"===typeof a?n.push(a):a&&void 0===a.revision&&n.push(a.url);var i=ae(a),o=i.cacheKey,u=i.url,s="string"!==typeof a&&a.revision?"reload":"default";if(this._urlsToCacheKeys.has(u)&&this._urlsToCacheKeys.get(u)!==o)throw new g("add-to-cache-list-conflicting-entries",{firstEntry:this._urlsToCacheKeys.get(u),secondEntry:o});if("string"!==typeof a&&a.integrity){if(this._cacheKeysToIntegrities.has(o)&&this._cacheKeysToIntegrities.get(o)!==a.integrity)throw new g("add-to-cache-list-conflicting-integrities",{url:u});this._cacheKeysToIntegrities.set(o,a.integrity)}if(this._urlsToCacheKeys.set(u,o),this._urlsToCacheModes.set(u,s),n.length>0){var f="Workbox is precaching URLs without revision "+"info: ".concat(n.join(", "),"\nThis is generally NOT safe. ")+"Learn more at https://bit.ly/wb-precache";console.warn(f)}}}catch(h){r.e(h)}finally{r.f()}}},{key:"install",value:function(){var e=O(L.a.mark((function e(){var t,n,r,a,i,o,u,s,f,h,l,p,v,d,y,m=this,g=arguments;return L.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return t=g.length>0&&void 0!==g[0]?g[0]:{},n=t.event,r=t.plugins,a=[],i=[],e.next=6,self.caches.open(this._cacheName);case 6:return o=e.sent,e.next=9,o.keys();case 9:u=e.sent,s=new Set(u.map((function(e){return e.url}))),f=c(this._urlsToCacheKeys);try{for(f.s();!(h=f.n()).done;)l=D(h.value,2),p=l[0],v=l[1],s.has(v)?i.push(p):a.push({cacheKey:v,url:p})}catch(x){f.e(x)}finally{f.f()}return d=a.map((function(e){var t=e.cacheKey,a=e.url,i=m._cacheKeysToIntegrities.get(t),c=m._urlsToCacheModes.get(a);return m._addURLToCache({cacheKey:t,cacheMode:c,event:n,integrity:i,plugins:r,url:a})})),e.next=16,Promise.all(d);case 16:return y=a.map((function(e){return e.url})),e.abrupt("return",{updatedURLs:y,notUpdatedURLs:i});case 19:case"end":return e.stop()}}),e,this)})));return function(){return e.apply(this,arguments)}}()},{key:"activate",value:function(){var e=O(L.a.mark((function e(){var t,n,r,a,i,o,u;return L.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,self.caches.open(this._cacheName);case 2:return t=e.sent,e.next=5,t.keys();case 5:n=e.sent,r=new Set(this._urlsToCacheKeys.values()),a=[],i=c(n),e.prev=9,i.s();case 11:if((o=i.n()).done){e.next=19;break}if(u=o.value,r.has(u.url)){e.next=17;break}return e.next=16,t.delete(u);case 16:a.push(u.url);case 17:e.next=11;break;case 19:e.next=24;break;case 21:e.prev=21,e.t0=e.catch(9),i.e(e.t0);case 24:return e.prev=24,i.f(),e.finish(24);case 27:return e.abrupt("return",{deletedURLs:a});case 29:case"end":return e.stop()}}),e,this,[[9,21,24,27]])})));return function(){return e.apply(this,arguments)}}()},{key:"_addURLToCache",value:function(){var e=O(L.a.mark((function e(t){var n,r,a,i,o,u,s,f,h,l,p,v;return L.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return n=t.cacheKey,r=t.url,a=t.cacheMode,i=t.event,o=t.plugins,u=t.integrity,s=new Request(r,{integrity:u,cache:a,credentials:"same-origin"}),e.next=4,X.fetch({event:i,plugins:o,request:s});case 4:f=e.sent,l=c(o||[]);try{for(l.s();!(p=l.n()).done;)"cacheWillUpdate"in(v=p.value)&&(h=v)}catch(d){l.e(d)}finally{l.f()}if(!h){e.next=13;break}return e.next=10,h.cacheWillUpdate({event:i,request:s,response:f});case 10:e.t0=e.sent,e.next=14;break;case 13:e.t0=f.status<400;case 14:if(e.t0){e.next=17;break}throw new g("bad-precaching-response",{url:r,status:f.status});case 17:if(!f.redirected){e.next=21;break}return e.next=20,Q(f);case 20:f=e.sent;case 21:return e.next=23,K.put({event:i,plugins:o,response:f,request:n===r?s:new Request(n),cacheName:this._cacheName,matchOptions:{ignoreSearch:!0}});case 23:case"end":return e.stop()}}),e,this)})));return function(t){return e.apply(this,arguments)}}()},{key:"getURLsToCacheKeys",value:function(){return this._urlsToCacheKeys}},{key:"getCachedURLs",value:function(){return i(this._urlsToCacheKeys.keys())}},{key:"getCacheKeyForURL",value:function(e){var t=new URL(e,location.href);return this._urlsToCacheKeys.get(t.href)}},{key:"matchPrecache",value:function(){var e=O(L.a.mark((function e(t){var n,r,a;return L.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(n=t instanceof Request?t.url:t,!(r=this.getCacheKeyForURL(n))){e.next=7;break}return e.next=5,self.caches.open(this._cacheName);case 5:return a=e.sent,e.abrupt("return",a.match(r));case 7:return e.abrupt("return",void 0);case 8:case"end":return e.stop()}}),e,this)})));return function(t){return e.apply(this,arguments)}}()},{key:"createHandler",value:function(){var e=this,t=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return function(){var n=O(L.a.mark((function n(r){var a,i;return L.a.wrap((function(n){for(;;)switch(n.prev=n.next){case 0:return a=r.request,n.prev=1,n.next=4,e.matchPrecache(a);case 4:if(!(i=n.sent)){n.next=7;break}return n.abrupt("return",i);case 7:throw new g("missing-precache-entry",{cacheName:e._cacheName,url:a instanceof Request?a.url:a});case 10:if(n.prev=10,n.t0=n.catch(1),!t){n.next=15;break}return n.abrupt("return",fetch(a));case 15:throw n.t0;case 16:case"end":return n.stop()}}),n,null,[[1,10]])})));return function(e){return n.apply(this,arguments)}}()}},{key:"createHandlerBoundToURL",value:function(e){var t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1],n=this.getCacheKeyForURL(e);if(!n)throw new g("non-precached-url",{url:e});var r=this.createHandler(t),a=new Request(e);return function(){return r({request:a})}}}]),e}(),oe=function(){return ie||(ie=new ce),ie};function ue(e){for(var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[],n=function(){var n=a[r];t.some((function(e){return e.test(n)}))&&e.searchParams.delete(n)},r=0,a=i(e.searchParams.keys());r<a.length;r++)n();return e}var se=L.a.mark(fe);function fe(e){var t,n,r,a,i,o,u,s,f,h,l,p,v,d=arguments;return L.a.wrap((function(y){for(;;)switch(y.prev=y.next){case 0:return t=d.length>1&&void 0!==d[1]?d[1]:{},n=t.ignoreURLParametersMatching,r=t.directoryIndex,a=t.cleanURLs,i=t.urlManipulation,(o=new URL(e,location.href)).hash="",y.next=5,o.href;case 5:return u=ue(o,n),y.next=8,u.href;case 8:if(!r||!u.pathname.endsWith("/")){y.next=13;break}return(s=new URL(u.href)).pathname+=r,y.next=13,s.href;case 13:if(!a){y.next=18;break}return(f=new URL(u.href)).pathname+=".html",y.next=18,f.href;case 18:if(!i){y.next=37;break}h=i({url:o}),l=c(h),y.prev=21,l.s();case 23:if((p=l.n()).done){y.next=29;break}return v=p.value,y.next=27,v.href;case 27:y.next=23;break;case 29:y.next=34;break;case 31:y.prev=31,y.t0=y.catch(21),l.e(y.t0);case 34:return y.prev=34,l.f(),y.finish(34);case 37:case"end":return y.stop()}}),se,null,[[21,31,34,37]])}var he=function(e,t){var n,r=oe().getURLsToCacheKeys(),a=c(fe(e,t));try{for(a.s();!(n=a.n()).done;){var i=n.value,o=r.get(i);if(o)return o}}catch(u){a.e(u)}finally{a.f()}},le=!1;function pe(e){le||(!function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=e.ignoreURLParametersMatching,n=void 0===t?[/^utm_/]:t,r=e.directoryIndex,a=void 0===r?"index.html":r,i=e.cleanURLs,c=void 0===i||i,o=e.urlManipulation,u=_();self.addEventListener("fetch",(function(e){var t=he(e.request.url,{cleanURLs:c,directoryIndex:a,ignoreURLParametersMatching:n,urlManipulation:o});if(t){var r=self.caches.open(u).then((function(e){return e.match(t)})).then((function(e){return e||fetch(t)}));e.respondWith(r)}}))}(e),le=!0)}var ve=function(e){var t=oe(),n=re();e.waitUntil(t.install({event:e,plugins:n}).catch((function(e){throw e})))},de=function(e){var t=oe();e.waitUntil(t.activate())};n(3);var ye,me=function(e){return e&&"object"===typeof e?e:{handle:e}},ge=function e(t,n){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"GET";o(this,e),this.handler=me(n),this.match=t,this.method=r},xe=function(e){s(n,e);var t=v(n);function n(e,r,a){o(this,n);return t.call(this,(function(t){var n=t.url,r=e.exec(n.href);if(r&&(n.origin===location.origin||0===r.index))return r.slice(1)}),r,a)}return n}(ge),we=function(){function e(){o(this,e),this._routes=new Map}return F(e,[{key:"routes",get:function(){return this._routes}},{key:"addFetchListener",value:function(){var e=this;self.addEventListener("fetch",(function(t){var n=t.request,r=e.handleRequest({request:n,event:t});r&&t.respondWith(r)}))}},{key:"addCacheListener",value:function(){var e=this;self.addEventListener("message",(function(t){if(t.data&&"CACHE_URLS"===t.data.type){var n=t.data.payload;0;var r=Promise.all(n.urlsToCache.map((function(t){"string"===typeof t&&(t=[t]);var n=d(Request,i(t));return e.handleRequest({request:n})})));t.waitUntil(r),t.ports&&t.ports[0]&&r.then((function(){return t.ports[0].postMessage(!0)}))}}))}},{key:"handleRequest",value:function(e){var t=this,n=e.request,r=e.event;var a=new URL(n.url,location.href);if(a.protocol.startsWith("http")){var i=this.findMatchingRoute({url:a,request:n,event:r}),c=i.params,o=i.route,u=o&&o.handler;if(!u&&this._defaultHandler&&(u=this._defaultHandler),u){var s;0;try{s=u.handle({url:a,request:n,event:r,params:c})}catch(f){s=Promise.reject(f)}return s instanceof Promise&&this._catchHandler&&(s=s.catch((function(e){return t._catchHandler.handle({url:a,request:n,event:r})}))),s}}}},{key:"findMatchingRoute",value:function(e){var t=e.url,n=e.request,r=e.event;var a,i=c(this._routes.get(n.method)||[]);try{for(i.s();!(a=i.n()).done;){var o=a.value,u=void 0,s=o.match({url:t,request:n,event:r});if(s)return u=s,(Array.isArray(s)&&0===s.length||s.constructor===Object&&0===Object.keys(s).length||"boolean"===typeof s)&&(u=void 0),{route:o,params:u}}}catch(f){i.e(f)}finally{i.f()}return{}}},{key:"setDefaultHandler",value:function(e){this._defaultHandler=me(e)}},{key:"setCatchHandler",value:function(e){this._catchHandler=me(e)}},{key:"registerRoute",value:function(e){this._routes.has(e.method)||this._routes.set(e.method,[]),this._routes.get(e.method).push(e)}},{key:"unregisterRoute",value:function(e){if(!this._routes.has(e.method))throw new g("unregister-route-but-not-found-with-method",{method:e.method});var t=this._routes.get(e.method).indexOf(e);if(!(t>-1))throw new g("unregister-route-route-not-registered");this._routes.get(e.method).splice(t,1)}}]),e}(),be=function(){return ye||((ye=new we).addFetchListener(),ye.addCacheListener()),ye};function ke(e,t,n){var r;if("string"===typeof e){var a=new URL(e,location.href);r=new ge((function(e){return e.url.href===a.href}),t,n)}else if(e instanceof RegExp)r=new xe(e,t,n);else if("function"===typeof e)r=new ge(e,t,n);else{if(!(e instanceof ge))throw new g("unsupported-route-type",{moduleName:"workbox-routing",funcName:"registerRoute",paramName:"capture"});r=e}return be().registerRoute(r),r}n(4);var _e,Re={cacheWillUpdate:function(){var e=O(L.a.mark((function e(t){var n;return L.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(200!==(n=t.response).status&&0!==n.status){e.next=3;break}return e.abrupt("return",n);case 3:return e.abrupt("return",null);case 4:case"end":return e.stop()}}),e)})));return function(t){return e.apply(this,arguments)}}()},Ee=function(){function e(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};if(o(this,e),this._cacheName=R(t.cacheName),this._plugins=t.plugins||[],t.plugins){var n=t.plugins.some((function(e){return!!e.cacheWillUpdate}));this._plugins=n?t.plugins:[Re].concat(i(t.plugins))}else this._plugins=[Re];this._fetchOptions=t.fetchOptions,this._matchOptions=t.matchOptions}return F(e,[{key:"handle",value:function(){var e=O(L.a.mark((function e(t){var n,r,a,i,c;return L.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return n=t.event,r=t.request,[],"string"===typeof r&&(r=new Request(r)),a=this._getFromNetwork({request:r,event:n}),e.next=7,K.match({cacheName:this._cacheName,request:r,event:n,matchOptions:this._matchOptions,plugins:this._plugins});case 7:if(!(i=e.sent)){e.next=13;break}if(n)try{n.waitUntil(a)}catch(c){0}e.next=23;break;case 13:return e.prev=14,e.next=17,a;case 17:i=e.sent,e.next=23;break;case 20:e.prev=20,e.t0=e.catch(14),c=e.t0;case 23:if(i){e.next=26;break}throw new g("no-response",{url:r.url,error:c});case 26:return e.abrupt("return",i);case 27:case"end":return e.stop()}}),e,this,[[14,20]])})));return function(t){return e.apply(this,arguments)}}()},{key:"_getFromNetwork",value:function(){var e=O(L.a.mark((function e(t){var n,r,a,i;return L.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return n=t.request,r=t.event,e.next=3,X.fetch({request:n,event:r,fetchOptions:this._fetchOptions,plugins:this._plugins});case 3:if(a=e.sent,i=K.put({cacheName:this._cacheName,request:n,response:a.clone(),event:r,plugins:this._plugins}),r)try{r.waitUntil(i)}catch(c){0}return e.abrupt("return",a);case 7:case"end":return e.stop()}}),e,this)})));return function(t){return e.apply(this,arguments)}}()}]),e}();self.addEventListener("activate",(function(){return self.clients.claim()})),function(e){oe().addToCacheList(e),e.length>0&&(self.addEventListener("install",ve),self.addEventListener("activate",de))}([{'revision':'3a2561a6fb04335c66c83eadd7e7982f','url':'/index.html'},{'revision':null,'url':'/static/css/main.8c8b27cf.chunk.css'},{'revision':null,'url':'/static/js/2.7c633c45.chunk.js'},{'revision':null,'url':'/static/js/3.e8f046f1.chunk.js'},{'revision':null,'url':'/static/js/main.4d826722.chunk.js'},{'revision':null,'url':'/static/js/runtime-main.fc2c9558.js'},{'revision':null,'url':'/static/media/logo.103b5fa1.svg'}]),pe(_e);var Le,qe=new RegExp("/[^/?]+\\.[^/]+$");ke((function(e){var t=e.request,n=e.url;return"navigate"===t.mode&&(!n.pathname.startsWith("/_")&&!n.pathname.match(qe))}),(Le="/index.html",oe().createHandlerBoundToURL(Le))),ke((function(e){var t=e.url;return t.origin===self.location.origin&&t.pathname.endsWith(".png")}),new Ee({cacheName:"images",plugins:[new te({maxEntries:50})]})),self.addEventListener("message",(function(e){console.log("AAAAAABBBBBCCCCCXXXXXYYYYZZZZZZ"),e.data&&"SKIP_WAITING"===e.data.type&&self.skipWaiting()}))}]);
//# sourceMappingURL=service-worker.js.map
|
const mongoose = require("mongoose");
const mongoosePaginate = require("mongoose-paginate-v2");
//create schema
const incomeSchema = new mongoose.Schema(
{
title: {
required: [true, "Title is required"],
type: String,
},
description: {
required: [true, "Description is required"],
type: String,
},
type: {
type: String,
default: "income",
},
amount: {
required: [true, "Amount is required"],
type: Number,
},
user: {
type: mongoose.Schema.Types.ObjectId,
ref: "User",
required: [true, "User is required"],
},
},
{
toJSON: {
virtuals: true,
},
toObject: {
virtuals: true,
},
timestamps: true,
}
);
incomeSchema.plugin(mongoosePaginate);
//Compile schema into model
const Income = mongoose.model("Income", incomeSchema);
module.exports = Income;
|
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
import unittest
from unittest import mock
import pytest
from cassandra.cluster import Cluster
from cassandra.policies import (
DCAwareRoundRobinPolicy,
RoundRobinPolicy,
TokenAwarePolicy,
WhiteListRoundRobinPolicy,
)
from airflow.models import Connection
from airflow.providers.apache.cassandra.hooks.cassandra import CassandraHook
from airflow.utils import db
@pytest.mark.integration("cassandra")
class TestCassandraHook(unittest.TestCase):
def setUp(self):
db.merge_conn(
Connection(
conn_id='cassandra_test',
conn_type='cassandra',
host='host-1,host-2',
port='9042',
schema='test_keyspace',
extra='{"load_balancing_policy":"TokenAwarePolicy","protocol_version":4}',
)
)
db.merge_conn(
Connection(
conn_id='cassandra_default_with_schema',
conn_type='cassandra',
host='cassandra',
port='9042',
schema='s',
)
)
hook = CassandraHook("cassandra_default")
session = hook.get_conn()
cqls = [
"DROP SCHEMA IF EXISTS s",
"""
CREATE SCHEMA s WITH REPLICATION =
{ 'class' : 'SimpleStrategy', 'replication_factor' : 1 }
""",
]
for cql in cqls:
session.execute(cql)
session.shutdown()
hook.shutdown_cluster()
def test_get_conn(self):
with mock.patch.object(Cluster, "connect") as mock_connect, mock.patch(
"socket.getaddrinfo", return_value=[]
) as mock_getaddrinfo:
mock_connect.return_value = 'session'
hook = CassandraHook(cassandra_conn_id='cassandra_test')
hook.get_conn()
assert mock_getaddrinfo.called
mock_connect.assert_called_once_with('test_keyspace')
cluster = hook.get_cluster()
assert cluster.contact_points == ['host-1', 'host-2']
assert cluster.port == 9042
assert cluster.protocol_version == 4
assert isinstance(cluster.load_balancing_policy, TokenAwarePolicy)
def test_get_lb_policy_with_no_args(self):
# test LB policies with no args
self._assert_get_lb_policy('RoundRobinPolicy', {}, RoundRobinPolicy)
self._assert_get_lb_policy('DCAwareRoundRobinPolicy', {}, DCAwareRoundRobinPolicy)
self._assert_get_lb_policy(
'TokenAwarePolicy', {}, TokenAwarePolicy, expected_child_policy_type=RoundRobinPolicy
)
def test_get_lb_policy_with_args(self):
# test DCAwareRoundRobinPolicy with args
self._assert_get_lb_policy(
'DCAwareRoundRobinPolicy',
{'local_dc': 'foo', 'used_hosts_per_remote_dc': '3'},
DCAwareRoundRobinPolicy,
)
# test WhiteListRoundRobinPolicy with args
fake_addr_info = [
['family', 'sockettype', 'proto', 'canonname', ('2606:2800:220:1:248:1893:25c8:1946', 80, 0, 0)]
]
with mock.patch('socket.getaddrinfo', return_value=fake_addr_info):
self._assert_get_lb_policy(
'WhiteListRoundRobinPolicy', {'hosts': ['host1', 'host2']}, WhiteListRoundRobinPolicy
)
# test TokenAwarePolicy with args
with mock.patch('socket.getaddrinfo', return_value=fake_addr_info):
self._assert_get_lb_policy(
'TokenAwarePolicy',
{
'child_load_balancing_policy': 'WhiteListRoundRobinPolicy',
'child_load_balancing_policy_args': {'hosts': ['host-1', 'host-2']},
},
TokenAwarePolicy,
expected_child_policy_type=WhiteListRoundRobinPolicy,
)
def test_get_lb_policy_invalid_policy(self):
# test invalid policy name should default to RoundRobinPolicy
self._assert_get_lb_policy('DoesNotExistPolicy', {}, RoundRobinPolicy)
# test invalid child policy name should default child policy to RoundRobinPolicy
self._assert_get_lb_policy(
'TokenAwarePolicy', {}, TokenAwarePolicy, expected_child_policy_type=RoundRobinPolicy
)
self._assert_get_lb_policy(
'TokenAwarePolicy',
{'child_load_balancing_policy': 'DoesNotExistPolicy'},
TokenAwarePolicy,
expected_child_policy_type=RoundRobinPolicy,
)
def test_get_lb_policy_no_host_for_allow_list(self):
# test host not specified for WhiteListRoundRobinPolicy should throw exception
self._assert_get_lb_policy(
'WhiteListRoundRobinPolicy', {}, WhiteListRoundRobinPolicy, should_throw=True
)
self._assert_get_lb_policy(
'TokenAwarePolicy',
{'child_load_balancing_policy': 'WhiteListRoundRobinPolicy'},
TokenAwarePolicy,
expected_child_policy_type=RoundRobinPolicy,
should_throw=True,
)
def _assert_get_lb_policy(
self,
policy_name,
policy_args,
expected_policy_type,
expected_child_policy_type=None,
should_throw=False,
):
thrown = False
try:
policy = CassandraHook.get_lb_policy(policy_name, policy_args)
assert isinstance(policy, expected_policy_type)
if expected_child_policy_type:
assert isinstance(policy._child_policy, expected_child_policy_type)
except Exception: # pylint: disable=broad-except
thrown = True
assert should_throw == thrown
def test_record_exists_with_keyspace_from_cql(self):
hook = CassandraHook("cassandra_default")
session = hook.get_conn()
cqls = [
"DROP TABLE IF EXISTS s.t",
"CREATE TABLE s.t (pk1 text, pk2 text, c text, PRIMARY KEY (pk1, pk2))",
"INSERT INTO s.t (pk1, pk2, c) VALUES ('foo', 'bar', 'baz')",
]
for cql in cqls:
session.execute(cql)
assert hook.record_exists("s.t", {"pk1": "foo", "pk2": "bar"})
assert not hook.record_exists("s.t", {"pk1": "foo", "pk2": "baz"})
session.shutdown()
hook.shutdown_cluster()
def test_record_exists_with_keyspace_from_session(self):
hook = CassandraHook("cassandra_default_with_schema")
session = hook.get_conn()
cqls = [
"DROP TABLE IF EXISTS t",
"CREATE TABLE t (pk1 text, pk2 text, c text, PRIMARY KEY (pk1, pk2))",
"INSERT INTO t (pk1, pk2, c) VALUES ('foo', 'bar', 'baz')",
]
for cql in cqls:
session.execute(cql)
assert hook.record_exists("t", {"pk1": "foo", "pk2": "bar"})
assert not hook.record_exists("t", {"pk1": "foo", "pk2": "baz"})
session.shutdown()
hook.shutdown_cluster()
def test_table_exists_with_keyspace_from_cql(self):
hook = CassandraHook("cassandra_default")
session = hook.get_conn()
cqls = [
"DROP TABLE IF EXISTS s.t",
"CREATE TABLE s.t (pk1 text PRIMARY KEY)",
]
for cql in cqls:
session.execute(cql)
assert hook.table_exists("s.t")
assert not hook.table_exists("s.u")
session.shutdown()
hook.shutdown_cluster()
def test_table_exists_with_keyspace_from_session(self):
hook = CassandraHook("cassandra_default_with_schema")
session = hook.get_conn()
cqls = [
"DROP TABLE IF EXISTS t",
"CREATE TABLE t (pk1 text PRIMARY KEY)",
]
for cql in cqls:
session.execute(cql)
assert hook.table_exists("t")
assert not hook.table_exists("u")
session.shutdown()
hook.shutdown_cluster()
|
from django.contrib.localflavor.ca.forms import (CAPostalCodeField,
CAPhoneNumberField, CAProvinceField, CAProvinceSelect,
CASocialInsuranceNumberField)
from utils import LocalFlavorTestCase
class CALocalFlavorTests(LocalFlavorTestCase):
def test_CAProvinceSelect(self):
f = CAProvinceSelect()
out = u'''<select name="province">
<option value="AB" selected="selected">Alberta</option>
<option value="BC">British Columbia</option>
<option value="MB">Manitoba</option>
<option value="NB">New Brunswick</option>
<option value="NF">Newfoundland and Labrador</option>
<option value="NT">Northwest Territories</option>
<option value="NS">Nova Scotia</option>
<option value="NU">Nunavut</option>
<option value="ON">Ontario</option>
<option value="PE">Prince Edward Island</option>
<option value="QC">Quebec</option>
<option value="SK">Saskatchewan</option>
<option value="YK">Yukon</option>
</select>'''
self.assertEqual(f.render('province', 'AB'), out)
def test_CAPostalCodeField(self):
error_format = [u'Enter a postal code in the format XXX XXX.']
valid = {
'T2S 2H7': 'T2S 2H7',
'T2S 2W7': 'T2S 2W7',
'T2S 2Z7': 'T2S 2Z7',
'T2Z 2H7': 'T2Z 2H7',
}
invalid = {
'T2S2H7' : error_format,
'T2S 2H' : error_format,
'2T6 H8I': error_format,
'T2S2H' : error_format,
90210 : error_format,
'W2S 2H3': error_format,
'Z2S 2H3': error_format,
'F2S 2H3': error_format,
'A2S 2D3': error_format,
'A2I 2R3': error_format,
'A2Q 2R3': error_format,
'U2B 2R3': error_format,
'O2B 2R3': error_format,
}
self.assertFieldOutput(CAPostalCodeField, valid, invalid)
def test_CAPhoneNumberField(self):
error_format = [u'Phone numbers must be in XXX-XXX-XXXX format.']
valid = {
'403-555-1212': '403-555-1212',
'4035551212': '403-555-1212',
'403 555-1212': '403-555-1212',
'(403) 555-1212': '403-555-1212',
'403 555 1212': '403-555-1212',
'403.555.1212': '403-555-1212',
'403.555-1212': '403-555-1212',
' (403) 555.1212 ': '403-555-1212',
}
invalid = {
'555-1212': error_format,
'403-55-1212': error_format,
}
self.assertFieldOutput(CAPhoneNumberField, valid, invalid)
def test_CAProvinceField(self):
error_format = [u'Enter a Canadian province or territory.']
valid = {
'ab': 'AB',
'BC': 'BC',
'nova scotia': 'NS',
' manitoba ': 'MB',
}
invalid = {
'T2S 2H7': error_format,
}
self.assertFieldOutput(CAProvinceField, valid, invalid)
def test_CASocialInsuranceField(self):
error_format = [u'Enter a valid Canadian Social Insurance number in XXX-XXX-XXX format.']
valid = {
'046-454-286': '046-454-286',
}
invalid = {
'046-454-287': error_format,
'046 454 286': error_format,
'046-44-286': error_format,
}
self.assertFieldOutput(CASocialInsuranceNumberField, valid, invalid)
|
// export modified jest config
module.exports = Object.assign({}, require('./jest.json'), {
coverageReporters: ['json-summary'],
});
|
/**
* @license Angular v7.1.2
* (c) 2010-2018 Google, Inc. https://angular.io/
* License: MIT
*/
import { __decorate, __param, __metadata, __extends, __values, __assign, __spread } from 'tslib';
import { InjectionToken, ɵisObservable, ɵisPromise, Directive, ElementRef, Renderer2, forwardRef, Inject, Optional, Injectable, Injector, Input, Host, ɵlooseIdentical, isDevMode, Self, EventEmitter, SkipSelf, Output, Version, NgModule } from '@angular/core';
import { forkJoin, from } from 'rxjs';
import { map } from 'rxjs/operators';
import { ɵgetDOM } from '@angular/platform-browser';
/**
* @license
* Copyright Google Inc. 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
*/
/**
* @description
* Base class for control directives.
*
* This class is only used internally in the `ReactiveFormsModule` and the `FormsModule`.
*
* @publicApi
*/
var AbstractControlDirective = /** @class */ (function () {
function AbstractControlDirective() {
}
Object.defineProperty(AbstractControlDirective.prototype, "value", {
/**
* @description
* Reports the value of the control if it is present, otherwise null.
*/
get: function () { return this.control ? this.control.value : null; },
enumerable: true,
configurable: true
});
Object.defineProperty(AbstractControlDirective.prototype, "valid", {
/**
* @description
* Reports whether the control is valid. A control is considered valid if no
* validation errors exist with the current value.
* If the control is not present, null is returned.
*/
get: function () { return this.control ? this.control.valid : null; },
enumerable: true,
configurable: true
});
Object.defineProperty(AbstractControlDirective.prototype, "invalid", {
/**
* @description
* Reports whether the control is invalid, meaning that an error exists in the input value.
* If the control is not present, null is returned.
*/
get: function () { return this.control ? this.control.invalid : null; },
enumerable: true,
configurable: true
});
Object.defineProperty(AbstractControlDirective.prototype, "pending", {
/**
* @description
* Reports whether a control is pending, meaning that that async validation is occurring and
* errors are not yet available for the input value. If the control is not present, null is
* returned.
*/
get: function () { return this.control ? this.control.pending : null; },
enumerable: true,
configurable: true
});
Object.defineProperty(AbstractControlDirective.prototype, "disabled", {
/**
* @description
* Reports whether the control is disabled, meaning that the control is disabled
* in the UI and is exempt from validation checks and excluded from aggregate
* values of ancestor controls. If the control is not present, null is returned.
*/
get: function () { return this.control ? this.control.disabled : null; },
enumerable: true,
configurable: true
});
Object.defineProperty(AbstractControlDirective.prototype, "enabled", {
/**
* @description
* Reports whether the control is enabled, meaning that the control is included in ancestor
* calculations of validity or value. If the control is not present, null is returned.
*/
get: function () { return this.control ? this.control.enabled : null; },
enumerable: true,
configurable: true
});
Object.defineProperty(AbstractControlDirective.prototype, "errors", {
/**
* @description
* Reports the control's validation errors. If the control is not present, null is returned.
*/
get: function () { return this.control ? this.control.errors : null; },
enumerable: true,
configurable: true
});
Object.defineProperty(AbstractControlDirective.prototype, "pristine", {
/**
* @description
* Reports whether the control is pristine, meaning that the user has not yet changed
* the value in the UI. If the control is not present, null is returned.
*/
get: function () { return this.control ? this.control.pristine : null; },
enumerable: true,
configurable: true
});
Object.defineProperty(AbstractControlDirective.prototype, "dirty", {
/**
* @description
* Reports whether the control is dirty, meaning that the user has changed
* the value in the UI. If the control is not present, null is returned.
*/
get: function () { return this.control ? this.control.dirty : null; },
enumerable: true,
configurable: true
});
Object.defineProperty(AbstractControlDirective.prototype, "touched", {
/**
* @description
* Reports whether the control is touched, meaning that the user has triggered
* a `blur` event on it. If the control is not present, null is returned.
*/
get: function () { return this.control ? this.control.touched : null; },
enumerable: true,
configurable: true
});
Object.defineProperty(AbstractControlDirective.prototype, "status", {
/**
* @description
* Reports the validation status of the control. Possible values include:
* 'VALID', 'INVALID', 'DISABLED', and 'PENDING'.
* If the control is not present, null is returned.
*/
get: function () { return this.control ? this.control.status : null; },
enumerable: true,
configurable: true
});
Object.defineProperty(AbstractControlDirective.prototype, "untouched", {
/**
* @description
* Reports whether the control is untouched, meaning that the user has not yet triggered
* a `blur` event on it. If the control is not present, null is returned.
*/
get: function () { return this.control ? this.control.untouched : null; },
enumerable: true,
configurable: true
});
Object.defineProperty(AbstractControlDirective.prototype, "statusChanges", {
/**
* @description
* Returns a multicasting observable that emits a validation status whenever it is
* calculated for the control. If the control is not present, null is returned.
*/
get: function () {
return this.control ? this.control.statusChanges : null;
},
enumerable: true,
configurable: true
});
Object.defineProperty(AbstractControlDirective.prototype, "valueChanges", {
/**
* @description
* Returns a multicasting observable of value changes for the control that emits every time the
* value of the control changes in the UI or programmatically.
* If the control is not present, null is returned.
*/
get: function () {
return this.control ? this.control.valueChanges : null;
},
enumerable: true,
configurable: true
});
Object.defineProperty(AbstractControlDirective.prototype, "path", {
/**
* @description
* Returns an array that represents the path from the top-level form to this control.
* Each index is the string name of the control on that level.
*/
get: function () { return null; },
enumerable: true,
configurable: true
});
/**
* @description
* Resets the control with the provided value if the control is present.
*/
AbstractControlDirective.prototype.reset = function (value) {
if (value === void 0) { value = undefined; }
if (this.control)
this.control.reset(value);
};
/**
* @description
* Reports whether the control with the given path has the error specified.
* If no path is given, it checks for the error on the present control.
* If the control is not present, false is returned.
*/
AbstractControlDirective.prototype.hasError = function (errorCode, path) {
return this.control ? this.control.hasError(errorCode, path) : false;
};
/**
* @description
* Reports error data for the control with the given path.
* If the control is not present, null is returned.
*/
AbstractControlDirective.prototype.getError = function (errorCode, path) {
return this.control ? this.control.getError(errorCode, path) : null;
};
return AbstractControlDirective;
}());
/**
* @license
* Copyright Google Inc. 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
*/
/**
* @description
* A base class for directives that contain multiple registered instances of `NgControl`.
* Only used by the forms module.
*
* @publicApi
*/
var ControlContainer = /** @class */ (function (_super) {
__extends(ControlContainer, _super);
function ControlContainer() {
return _super !== null && _super.apply(this, arguments) || this;
}
Object.defineProperty(ControlContainer.prototype, "formDirective", {
/**
* @description
* The top-level form directive for the control.
*/
get: function () { return null; },
enumerable: true,
configurable: true
});
Object.defineProperty(ControlContainer.prototype, "path", {
/**
* @description
* The path to this group.
*/
get: function () { return null; },
enumerable: true,
configurable: true
});
return ControlContainer;
}(AbstractControlDirective));
/**
* @license
* Copyright Google Inc. 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
*/
function isEmptyInputValue(value) {
// we don't check for string here so it also works with arrays
return value == null || value.length === 0;
}
/**
* @description
* An `InjectionToken` for registering additional synchronous validators used with `AbstractControl`s.
*
* @see `NG_ASYNC_VALIDATORS`
*
* @usageNotes
*
* ### Providing a custom validator
*
* The following example registers a custom validator directive. Adding the validator to the
* existing collection of validators requires the `multi: true` option.
*
* ```typescript
* @Directive({
* selector: '[customValidator]',
* providers: [{provide: NG_VALIDATORS, useExisting: CustomValidatorDirective, multi: true}]
* })
* class CustomValidatorDirective implements Validator {
* validate(control: AbstractControl): ValidationErrors | null {
* return { 'custom': true };
* }
* }
* ```
*
* @publicApi
*/
var NG_VALIDATORS = new InjectionToken('NgValidators');
/**
* @description
* An `InjectionToken` for registering additional asynchronous validators used with `AbstractControl`s.
*
* @see `NG_VALIDATORS`
*
* @publicApi
*/
var NG_ASYNC_VALIDATORS = new InjectionToken('NgAsyncValidators');
var EMAIL_REGEXP = /^(?=.{1,254}$)(?=.{1,64}@)[-!#$%&'*+/0-9=?A-Z^_`a-z{|}~]+(\.[-!#$%&'*+/0-9=?A-Z^_`a-z{|}~]+)*@[A-Za-z0-9]([A-Za-z0-9-]{0,61}[A-Za-z0-9])?(\.[A-Za-z0-9]([A-Za-z0-9-]{0,61}[A-Za-z0-9])?)*$/;
/**
* @description
* Provides a set of built-in validators that can be used by form controls.
*
* A validator is a function that processes a `FormControl` or collection of
* controls and returns an error map or null. A null map means that validation has passed.
*
* @see [Form Validation](/guide/form-validation)
*
* @publicApi
*/
var Validators = /** @class */ (function () {
function Validators() {
}
/**
* @description
* Validator that requires the control's value to be greater than or equal to the provided number.
* The validator exists only as a function and not as a directive.
*
* @usageNotes
*
* ### Validate against a minimum of 3
*
* ```typescript
* const control = new FormControl(2, Validators.min(3));
*
* console.log(control.errors); // {min: {min: 3, actual: 2}}
* ```
*
* @returns A validator function that returns an error map with the
* `min` property if the validation check fails, otherwise `null`.
*
*/
Validators.min = function (min) {
return function (control) {
if (isEmptyInputValue(control.value) || isEmptyInputValue(min)) {
return null; // don't validate empty values to allow optional controls
}
var value = parseFloat(control.value);
// Controls with NaN values after parsing should be treated as not having a
// minimum, per the HTML forms spec: https://www.w3.org/TR/html5/forms.html#attr-input-min
return !isNaN(value) && value < min ? { 'min': { 'min': min, 'actual': control.value } } : null;
};
};
/**
* @description
* Validator that requires the control's value to be less than or equal to the provided number.
* The validator exists only as a function and not as a directive.
*
* @usageNotes
*
* ### Validate against a maximum of 15
*
* ```typescript
* const control = new FormControl(16, Validators.max(15));
*
* console.log(control.errors); // {max: {max: 15, actual: 16}}
* ```
*
* @returns A validator function that returns an error map with the
* `max` property if the validation check fails, otherwise `null`.
*
*/
Validators.max = function (max) {
return function (control) {
if (isEmptyInputValue(control.value) || isEmptyInputValue(max)) {
return null; // don't validate empty values to allow optional controls
}
var value = parseFloat(control.value);
// Controls with NaN values after parsing should be treated as not having a
// maximum, per the HTML forms spec: https://www.w3.org/TR/html5/forms.html#attr-input-max
return !isNaN(value) && value > max ? { 'max': { 'max': max, 'actual': control.value } } : null;
};
};
/**
* @description
* Validator that requires the control have a non-empty value.
*
* @usageNotes
*
* ### Validate that the field is non-empty
*
* ```typescript
* const control = new FormControl('', Validators.required);
*
* console.log(control.errors); // {required: true}
* ```
*
* @returns An error map with the `required` property
* if the validation check fails, otherwise `null`.
*
*/
Validators.required = function (control) {
return isEmptyInputValue(control.value) ? { 'required': true } : null;
};
/**
* @description
* Validator that requires the control's value be true. This validator is commonly
* used for required checkboxes.
*
* @usageNotes
*
* ### Validate that the field value is true
*
* ```typescript
* const control = new FormControl('', Validators.requiredTrue);
*
* console.log(control.errors); // {required: true}
* ```
*
* @returns An error map that contains the `required` property
* set to `true` if the validation check fails, otherwise `null`.
*/
Validators.requiredTrue = function (control) {
return control.value === true ? null : { 'required': true };
};
/**
* @description
* Validator that requires the control's value pass an email validation test.
*
* @usageNotes
*
* ### Validate that the field matches a valid email pattern
*
* ```typescript
* const control = new FormControl('bad@', Validators.email);
*
* console.log(control.errors); // {email: true}
* ```
*
* @returns An error map with the `email` property
* if the validation check fails, otherwise `null`.
*
*/
Validators.email = function (control) {
if (isEmptyInputValue(control.value)) {
return null; // don't validate empty values to allow optional controls
}
return EMAIL_REGEXP.test(control.value) ? null : { 'email': true };
};
/**
* @description
* Validator that requires the length of the control's value to be greater than or equal
* to the provided minimum length. This validator is also provided by default if you use the
* the HTML5 `minlength` attribute.
*
* @usageNotes
*
* ### Validate that the field has a minimum of 3 characters
*
* ```typescript
* const control = new FormControl('ng', Validators.minLength(3));
*
* console.log(control.errors); // {minlength: {requiredLength: 3, actualLength: 2}}
* ```
*
* ```html
* <input minlength="5">
* ```
*
* @returns A validator function that returns an error map with the
* `minlength` if the validation check fails, otherwise `null`.
*/
Validators.minLength = function (minLength) {
return function (control) {
if (isEmptyInputValue(control.value)) {
return null; // don't validate empty values to allow optional controls
}
var length = control.value ? control.value.length : 0;
return length < minLength ?
{ 'minlength': { 'requiredLength': minLength, 'actualLength': length } } :
null;
};
};
/**
* @description
* Validator that requires the length of the control's value to be less than or equal
* to the provided maximum length. This validator is also provided by default if you use the
* the HTML5 `maxlength` attribute.
*
* @usageNotes
*
* ### Validate that the field has maximum of 5 characters
*
* ```typescript
* const control = new FormControl('Angular', Validators.maxLength(5));
*
* console.log(control.errors); // {maxlength: {requiredLength: 5, actualLength: 7}}
* ```
*
* ```html
* <input maxlength="5">
* ```
*
* @returns A validator function that returns an error map with the
* `maxlength` property if the validation check fails, otherwise `null`.
*/
Validators.maxLength = function (maxLength) {
return function (control) {
var length = control.value ? control.value.length : 0;
return length > maxLength ?
{ 'maxlength': { 'requiredLength': maxLength, 'actualLength': length } } :
null;
};
};
/**
* @description
* Validator that requires the control's value to match a regex pattern. This validator is also
* provided
* by default if you use the HTML5 `pattern` attribute.
*
* @usageNotes
*
* ### Validate that the field only contains letters or spaces
*
* ```typescript
* const control = new FormControl('1', Validators.pattern('[a-zA-Z ]*'));
*
* console.log(control.errors); // {pattern: {requiredPattern: '^[a-zA-Z ]*$', actualValue: '1'}}
* ```
*
* ```html
* <input pattern="[a-zA-Z ]*">
* ```
*
* @returns A validator function that returns an error map with the
* `pattern` property if the validation check fails, otherwise `null`.
*/
Validators.pattern = function (pattern) {
if (!pattern)
return Validators.nullValidator;
var regex;
var regexStr;
if (typeof pattern === 'string') {
regexStr = '';
if (pattern.charAt(0) !== '^')
regexStr += '^';
regexStr += pattern;
if (pattern.charAt(pattern.length - 1) !== '$')
regexStr += '$';
regex = new RegExp(regexStr);
}
else {
regexStr = pattern.toString();
regex = pattern;
}
return function (control) {
if (isEmptyInputValue(control.value)) {
return null; // don't validate empty values to allow optional controls
}
var value = control.value;
return regex.test(value) ? null :
{ 'pattern': { 'requiredPattern': regexStr, 'actualValue': value } };
};
};
/**
* @description
* Validator that performs no operation.
*/
Validators.nullValidator = function (control) { return null; };
Validators.compose = function (validators) {
if (!validators)
return null;
var presentValidators = validators.filter(isPresent);
if (presentValidators.length == 0)
return null;
return function (control) {
return _mergeErrors(_executeValidators(control, presentValidators));
};
};
/**
* @description
* Compose multiple async validators into a single function that returns the union
* of the individual error objects for the provided control.
*
* @returns A validator function that returns an error map with the
* merged error objects of the async validators if the validation check fails, otherwise `null`.
*/
Validators.composeAsync = function (validators) {
if (!validators)
return null;
var presentValidators = validators.filter(isPresent);
if (presentValidators.length == 0)
return null;
return function (control) {
var observables = _executeAsyncValidators(control, presentValidators).map(toObservable);
return forkJoin(observables).pipe(map(_mergeErrors));
};
};
return Validators;
}());
function isPresent(o) {
return o != null;
}
function toObservable(r) {
var obs = ɵisPromise(r) ? from(r) : r;
if (!(ɵisObservable(obs))) {
throw new Error("Expected validator to return Promise or Observable.");
}
return obs;
}
function _executeValidators(control, validators) {
return validators.map(function (v) { return v(control); });
}
function _executeAsyncValidators(control, validators) {
return validators.map(function (v) { return v(control); });
}
function _mergeErrors(arrayOfErrors) {
var res = arrayOfErrors.reduce(function (res, errors) {
return errors != null ? __assign({}, res, errors) : res;
}, {});
return Object.keys(res).length === 0 ? null : res;
}
/**
* @license
* Copyright Google Inc. 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
*/
/**
* Used to provide a `ControlValueAccessor` for form controls.
*
* See `DefaultValueAccessor` for how to implement one.
*
* @publicApi
*/
var NG_VALUE_ACCESSOR = new InjectionToken('NgValueAccessor');
/**
* @license
* Copyright Google Inc. 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
*/
var CHECKBOX_VALUE_ACCESSOR = {
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(function () { return CheckboxControlValueAccessor; }),
multi: true,
};
/**
* @description
* A `ControlValueAccessor` for writing a value and listening to changes on a checkbox input
* element.
*
* @usageNotes
*
* ### Using a checkbox with a reactive form.
*
* The following example shows how to use a checkbox with a reactive form.
*
* ```ts
* const rememberLoginControl = new FormControl();
* ```
*
* ```
* <input type="checkbox" [formControl]="rememberLoginControl">
* ```
*
* @ngModule ReactiveFormsModule
* @ngModule FormsModule
* @publicApi
*/
var CheckboxControlValueAccessor = /** @class */ (function () {
function CheckboxControlValueAccessor(_renderer, _elementRef) {
this._renderer = _renderer;
this._elementRef = _elementRef;
/**
* @description
* The registered callback function called when a change event occurs on the input element.
*/
this.onChange = function (_) { };
/**
* @description
* The registered callback function called when a blur event occurs on the input element.
*/
this.onTouched = function () { };
}
/**
* Sets the "checked" property on the input element.
*
* @param value The checked value
*/
CheckboxControlValueAccessor.prototype.writeValue = function (value) {
this._renderer.setProperty(this._elementRef.nativeElement, 'checked', value);
};
/**
* @description
* Registers a function called when the control value changes.
*
* @param fn The callback function
*/
CheckboxControlValueAccessor.prototype.registerOnChange = function (fn) { this.onChange = fn; };
/**
* @description
* Registers a function called when the control is touched.
*
* @param fn The callback function
*/
CheckboxControlValueAccessor.prototype.registerOnTouched = function (fn) { this.onTouched = fn; };
/**
* Sets the "disabled" property on the input element.
*
* @param isDisabled The disabled value
*/
CheckboxControlValueAccessor.prototype.setDisabledState = function (isDisabled) {
this._renderer.setProperty(this._elementRef.nativeElement, 'disabled', isDisabled);
};
CheckboxControlValueAccessor = __decorate([
Directive({
selector: 'input[type=checkbox][formControlName],input[type=checkbox][formControl],input[type=checkbox][ngModel]',
host: { '(change)': 'onChange($event.target.checked)', '(blur)': 'onTouched()' },
providers: [CHECKBOX_VALUE_ACCESSOR]
}),
__metadata("design:paramtypes", [Renderer2, ElementRef])
], CheckboxControlValueAccessor);
return CheckboxControlValueAccessor;
}());
/**
* @license
* Copyright Google Inc. 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
*/
var DEFAULT_VALUE_ACCESSOR = {
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(function () { return DefaultValueAccessor; }),
multi: true
};
/**
* We must check whether the agent is Android because composition events
* behave differently between iOS and Android.
*/
function _isAndroid() {
var userAgent = ɵgetDOM() ? ɵgetDOM().getUserAgent() : '';
return /android (\d+)/.test(userAgent.toLowerCase());
}
/**
* @description
* Provide this token to control if form directives buffer IME input until
* the "compositionend" event occurs.
* @publicApi
*/
var COMPOSITION_BUFFER_MODE = new InjectionToken('CompositionEventMode');
/**
* @description
* The default `ControlValueAccessor` for writing a value and listening to changes on input
* elements. The accessor is used by the `FormControlDirective`, `FormControlName`, and
* `NgModel` directives.
*
* @usageNotes
*
* ### Using the default value accessor
*
* The following example shows how to use an input element that activates the default value accessor
* (in this case, a text field).
*
* ```ts
* const firstNameControl = new FormControl();
* ```
*
* ```
* <input type="text" [formControl]="firstNameControl">
* ```
*
* @ngModule ReactiveFormsModule
* @ngModule FormsModule
* @publicApi
*/
var DefaultValueAccessor = /** @class */ (function () {
function DefaultValueAccessor(_renderer, _elementRef, _compositionMode) {
this._renderer = _renderer;
this._elementRef = _elementRef;
this._compositionMode = _compositionMode;
/**
* @description
* The registered callback function called when an input event occurs on the input element.
*/
this.onChange = function (_) { };
/**
* @description
* The registered callback function called when a blur event occurs on the input element.
*/
this.onTouched = function () { };
/** Whether the user is creating a composition string (IME events). */
this._composing = false;
if (this._compositionMode == null) {
this._compositionMode = !_isAndroid();
}
}
/**
* Sets the "value" property on the input element.
*
* @param value The checked value
*/
DefaultValueAccessor.prototype.writeValue = function (value) {
var normalizedValue = value == null ? '' : value;
this._renderer.setProperty(this._elementRef.nativeElement, 'value', normalizedValue);
};
/**
* @description
* Registers a function called when the control value changes.
*
* @param fn The callback function
*/
DefaultValueAccessor.prototype.registerOnChange = function (fn) { this.onChange = fn; };
/**
* @description
* Registers a function called when the control is touched.
*
* @param fn The callback function
*/
DefaultValueAccessor.prototype.registerOnTouched = function (fn) { this.onTouched = fn; };
/**
* Sets the "disabled" property on the input element.
*
* @param isDisabled The disabled value
*/
DefaultValueAccessor.prototype.setDisabledState = function (isDisabled) {
this._renderer.setProperty(this._elementRef.nativeElement, 'disabled', isDisabled);
};
/** @internal */
DefaultValueAccessor.prototype._handleInput = function (value) {
if (!this._compositionMode || (this._compositionMode && !this._composing)) {
this.onChange(value);
}
};
/** @internal */
DefaultValueAccessor.prototype._compositionStart = function () { this._composing = true; };
/** @internal */
DefaultValueAccessor.prototype._compositionEnd = function (value) {
this._composing = false;
this._compositionMode && this.onChange(value);
};
DefaultValueAccessor = __decorate([
Directive({
selector: 'input:not([type=checkbox])[formControlName],textarea[formControlName],input:not([type=checkbox])[formControl],textarea[formControl],input:not([type=checkbox])[ngModel],textarea[ngModel],[ngDefaultControl]',
// TODO: vsavkin replace the above selector with the one below it once
// https://github.com/angular/angular/issues/3011 is implemented
// selector: '[ngModel],[formControl],[formControlName]',
host: {
'(input)': '$any(this)._handleInput($event.target.value)',
'(blur)': 'onTouched()',
'(compositionstart)': '$any(this)._compositionStart()',
'(compositionend)': '$any(this)._compositionEnd($event.target.value)'
},
providers: [DEFAULT_VALUE_ACCESSOR]
}),
__param(2, Optional()), __param(2, Inject(COMPOSITION_BUFFER_MODE)),
__metadata("design:paramtypes", [Renderer2, ElementRef, Boolean])
], DefaultValueAccessor);
return DefaultValueAccessor;
}());
/**
* @license
* Copyright Google Inc. 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
*/
function normalizeValidator(validator) {
if (validator.validate) {
return function (c) { return validator.validate(c); };
}
else {
return validator;
}
}
function normalizeAsyncValidator(validator) {
if (validator.validate) {
return function (c) { return validator.validate(c); };
}
else {
return validator;
}
}
/**
* @license
* Copyright Google Inc. 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
*/
var NUMBER_VALUE_ACCESSOR = {
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(function () { return NumberValueAccessor; }),
multi: true
};
/**
* @description
* The `ControlValueAccessor` for writing a number value and listening to number input changes.
* The value accessor is used by the `FormControlDirective`, `FormControlName`, and `NgModel`
* directives.
*
* @usageNotes
*
* ### Using a number input with a reactive form.
*
* The following example shows how to use a number input with a reactive form.
*
* ```ts
* const totalCountControl = new FormControl();
* ```
*
* ```
* <input type="number" [formControl]="totalCountControl">
* ```
*
* @ngModule ReactiveFormsModule
* @ngModule FormsModule
*/
var NumberValueAccessor = /** @class */ (function () {
function NumberValueAccessor(_renderer, _elementRef) {
this._renderer = _renderer;
this._elementRef = _elementRef;
/**
* @description
* The registered callback function called when a change or input event occurs on the input
* element.
*/
this.onChange = function (_) { };
/**
* @description
* The registered callback function called when a blur event occurs on the input element.
*/
this.onTouched = function () { };
}
/**
* Sets the "value" property on the input element.
*
* @param value The checked value
*/
NumberValueAccessor.prototype.writeValue = function (value) {
// The value needs to be normalized for IE9, otherwise it is set to 'null' when null
var normalizedValue = value == null ? '' : value;
this._renderer.setProperty(this._elementRef.nativeElement, 'value', normalizedValue);
};
/**
* @description
* Registers a function called when the control value changes.
*
* @param fn The callback function
*/
NumberValueAccessor.prototype.registerOnChange = function (fn) {
this.onChange = function (value) { fn(value == '' ? null : parseFloat(value)); };
};
/**
* @description
* Registers a function called when the control is touched.
*
* @param fn The callback function
*/
NumberValueAccessor.prototype.registerOnTouched = function (fn) { this.onTouched = fn; };
/**
* Sets the "disabled" property on the input element.
*
* @param isDisabled The disabled value
*/
NumberValueAccessor.prototype.setDisabledState = function (isDisabled) {
this._renderer.setProperty(this._elementRef.nativeElement, 'disabled', isDisabled);
};
NumberValueAccessor = __decorate([
Directive({
selector: 'input[type=number][formControlName],input[type=number][formControl],input[type=number][ngModel]',
host: {
'(change)': 'onChange($event.target.value)',
'(input)': 'onChange($event.target.value)',
'(blur)': 'onTouched()'
},
providers: [NUMBER_VALUE_ACCESSOR]
}),
__metadata("design:paramtypes", [Renderer2, ElementRef])
], NumberValueAccessor);
return NumberValueAccessor;
}());
/**
* @license
* Copyright Google Inc. 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
*/
function unimplemented() {
throw new Error('unimplemented');
}
/**
* @description
* A base class that all control `FormControl`-based directives extend. It binds a `FormControl`
* object to a DOM element.
*
* @publicApi
*/
var NgControl = /** @class */ (function (_super) {
__extends(NgControl, _super);
function NgControl() {
var _this = _super !== null && _super.apply(this, arguments) || this;
/**
* @description
* The parent form for the control.
*
* @internal
*/
_this._parent = null;
/**
* @description
* The name for the control
*/
_this.name = null;
/**
* @description
* The value accessor for the control
*/
_this.valueAccessor = null;
/**
* @description
* The uncomposed array of synchronous validators for the control
*
* @internal
*/
_this._rawValidators = [];
/**
* @description
* The uncomposed array of async validators for the control
*
* @internal
*/
_this._rawAsyncValidators = [];
return _this;
}
Object.defineProperty(NgControl.prototype, "validator", {
/**
* @description
* The registered synchronous validator function for the control
*
* @throws An exception that this method is not implemented
*/
get: function () { return unimplemented(); },
enumerable: true,
configurable: true
});
Object.defineProperty(NgControl.prototype, "asyncValidator", {
/**
* @description
* The registered async validator function for the control
*
* @throws An exception that this method is not implemented
*/
get: function () { return unimplemented(); },
enumerable: true,
configurable: true
});
return NgControl;
}(AbstractControlDirective));
/**
* @license
* Copyright Google Inc. 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
*/
var RADIO_VALUE_ACCESSOR = {
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(function () { return RadioControlValueAccessor; }),
multi: true
};
/**
* @description
* Class used by Angular to track radio buttons. For internal use only.
*/
var RadioControlRegistry = /** @class */ (function () {
function RadioControlRegistry() {
this._accessors = [];
}
/**
* @description
* Adds a control to the internal registry. For internal use only.
*/
RadioControlRegistry.prototype.add = function (control, accessor) {
this._accessors.push([control, accessor]);
};
/**
* @description
* Removes a control from the internal registry. For internal use only.
*/
RadioControlRegistry.prototype.remove = function (accessor) {
for (var i = this._accessors.length - 1; i >= 0; --i) {
if (this._accessors[i][1] === accessor) {
this._accessors.splice(i, 1);
return;
}
}
};
/**
* @description
* Selects a radio button. For internal use only.
*/
RadioControlRegistry.prototype.select = function (accessor) {
var _this = this;
this._accessors.forEach(function (c) {
if (_this._isSameGroup(c, accessor) && c[1] !== accessor) {
c[1].fireUncheck(accessor.value);
}
});
};
RadioControlRegistry.prototype._isSameGroup = function (controlPair, accessor) {
if (!controlPair[0].control)
return false;
return controlPair[0]._parent === accessor._control._parent &&
controlPair[1].name === accessor.name;
};
RadioControlRegistry = __decorate([
Injectable()
], RadioControlRegistry);
return RadioControlRegistry;
}());
/**
* @description
* The `ControlValueAccessor` for writing radio control values and listening to radio control
* changes. The value accessor is used by the `FormControlDirective`, `FormControlName`, and
* `NgModel` directives.
*
* @usageNotes
*
* ### Using radio buttons with reactive form directives
*
* The follow example shows how to use radio buttons in a reactive form. When using radio buttons in
* a reactive form, radio buttons in the same group should have the same `formControlName`.
* Providing a `name` attribute is optional.
*
* {@example forms/ts/reactiveRadioButtons/reactive_radio_button_example.ts region='Reactive'}
*
* @ngModule ReactiveFormsModule
* @ngModule FormsModule
* @publicApi
*/
var RadioControlValueAccessor = /** @class */ (function () {
function RadioControlValueAccessor(_renderer, _elementRef, _registry, _injector) {
this._renderer = _renderer;
this._elementRef = _elementRef;
this._registry = _registry;
this._injector = _injector;
/**
* @description
* The registered callback function called when a change event occurs on the input element.
*/
this.onChange = function () { };
/**
* @description
* The registered callback function called when a blur event occurs on the input element.
*/
this.onTouched = function () { };
}
/**
* @description
* A lifecycle method called when the directive is initialized. For internal use only.
*
* @param changes A object of key/value pairs for the set of changed inputs.
*/
RadioControlValueAccessor.prototype.ngOnInit = function () {
this._control = this._injector.get(NgControl);
this._checkName();
this._registry.add(this._control, this);
};
/**
* @description
* Lifecycle method called before the directive's instance is destroyed. For internal use only.
*
* @param changes A object of key/value pairs for the set of changed inputs.
*/
RadioControlValueAccessor.prototype.ngOnDestroy = function () { this._registry.remove(this); };
/**
* @description
* Sets the "checked" property value on the radio input element.
*
* @param value The checked value
*/
RadioControlValueAccessor.prototype.writeValue = function (value) {
this._state = value === this.value;
this._renderer.setProperty(this._elementRef.nativeElement, 'checked', this._state);
};
/**
* @description
* Registers a function called when the control value changes.
*
* @param fn The callback function
*/
RadioControlValueAccessor.prototype.registerOnChange = function (fn) {
var _this = this;
this._fn = fn;
this.onChange = function () {
fn(_this.value);
_this._registry.select(_this);
};
};
/**
* Sets the "value" on the radio input element and unchecks it.
*
* @param value
*/
RadioControlValueAccessor.prototype.fireUncheck = function (value) { this.writeValue(value); };
/**
* @description
* Registers a function called when the control is touched.
*
* @param fn The callback function
*/
RadioControlValueAccessor.prototype.registerOnTouched = function (fn) { this.onTouched = fn; };
/**
* Sets the "disabled" property on the input element.
*
* @param isDisabled The disabled value
*/
RadioControlValueAccessor.prototype.setDisabledState = function (isDisabled) {
this._renderer.setProperty(this._elementRef.nativeElement, 'disabled', isDisabled);
};
RadioControlValueAccessor.prototype._checkName = function () {
if (this.name && this.formControlName && this.name !== this.formControlName) {
this._throwNameError();
}
if (!this.name && this.formControlName)
this.name = this.formControlName;
};
RadioControlValueAccessor.prototype._throwNameError = function () {
throw new Error("\n If you define both a name and a formControlName attribute on your radio button, their values\n must match. Ex: <input type=\"radio\" formControlName=\"food\" name=\"food\">\n ");
};
__decorate([
Input(),
__metadata("design:type", String)
], RadioControlValueAccessor.prototype, "name", void 0);
__decorate([
Input(),
__metadata("design:type", String)
], RadioControlValueAccessor.prototype, "formControlName", void 0);
__decorate([
Input(),
__metadata("design:type", Object)
], RadioControlValueAccessor.prototype, "value", void 0);
RadioControlValueAccessor = __decorate([
Directive({
selector: 'input[type=radio][formControlName],input[type=radio][formControl],input[type=radio][ngModel]',
host: { '(change)': 'onChange()', '(blur)': 'onTouched()' },
providers: [RADIO_VALUE_ACCESSOR]
}),
__metadata("design:paramtypes", [Renderer2, ElementRef,
RadioControlRegistry, Injector])
], RadioControlValueAccessor);
return RadioControlValueAccessor;
}());
/**
* @license
* Copyright Google Inc. 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
*/
var RANGE_VALUE_ACCESSOR = {
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(function () { return RangeValueAccessor; }),
multi: true
};
/**
* @description
* The `ControlValueAccessor` for writing a range value and listening to range input changes.
* The value accessor is used by the `FormControlDirective`, `FormControlName`, and `NgModel`
* directives.
*
* @usageNotes
*
* ### Using a range input with a reactive form
*
* The following example shows how to use a range input with a reactive form.
*
* ```ts
* const ageControl = new FormControl();
* ```
*
* ```
* <input type="range" [formControl]="ageControl">
* ```
*
* @ngModule ReactiveFormsModule
* @ngModule FormsModule
*/
var RangeValueAccessor = /** @class */ (function () {
function RangeValueAccessor(_renderer, _elementRef) {
this._renderer = _renderer;
this._elementRef = _elementRef;
/**
* @description
* The registered callback function called when a change or input event occurs on the input
* element.
*/
this.onChange = function (_) { };
/**
* @description
* The registered callback function called when a blur event occurs on the input element.
*/
this.onTouched = function () { };
}
/**
* Sets the "value" property on the input element.
*
* @param value The checked value
*/
RangeValueAccessor.prototype.writeValue = function (value) {
this._renderer.setProperty(this._elementRef.nativeElement, 'value', parseFloat(value));
};
/**
* @description
* Registers a function called when the control value changes.
*
* @param fn The callback function
*/
RangeValueAccessor.prototype.registerOnChange = function (fn) {
this.onChange = function (value) { fn(value == '' ? null : parseFloat(value)); };
};
/**
* @description
* Registers a function called when the control is touched.
*
* @param fn The callback function
*/
RangeValueAccessor.prototype.registerOnTouched = function (fn) { this.onTouched = fn; };
/**
* Sets the "disabled" property on the range input element.
*
* @param isDisabled The disabled value
*/
RangeValueAccessor.prototype.setDisabledState = function (isDisabled) {
this._renderer.setProperty(this._elementRef.nativeElement, 'disabled', isDisabled);
};
RangeValueAccessor = __decorate([
Directive({
selector: 'input[type=range][formControlName],input[type=range][formControl],input[type=range][ngModel]',
host: {
'(change)': 'onChange($event.target.value)',
'(input)': 'onChange($event.target.value)',
'(blur)': 'onTouched()'
},
providers: [RANGE_VALUE_ACCESSOR]
}),
__metadata("design:paramtypes", [Renderer2, ElementRef])
], RangeValueAccessor);
return RangeValueAccessor;
}());
/**
* @license
* Copyright Google Inc. 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
*/
var FormErrorExamples = {
formControlName: "\n <div [formGroup]=\"myGroup\">\n <input formControlName=\"firstName\">\n </div>\n\n In your class:\n\n this.myGroup = new FormGroup({\n firstName: new FormControl()\n });",
formGroupName: "\n <div [formGroup]=\"myGroup\">\n <div formGroupName=\"person\">\n <input formControlName=\"firstName\">\n </div>\n </div>\n\n In your class:\n\n this.myGroup = new FormGroup({\n person: new FormGroup({ firstName: new FormControl() })\n });",
formArrayName: "\n <div [formGroup]=\"myGroup\">\n <div formArrayName=\"cities\">\n <div *ngFor=\"let city of cityArray.controls; index as i\">\n <input [formControlName]=\"i\">\n </div>\n </div>\n </div>\n\n In your class:\n\n this.cityArray = new FormArray([new FormControl('SF')]);\n this.myGroup = new FormGroup({\n cities: this.cityArray\n });",
ngModelGroup: "\n <form>\n <div ngModelGroup=\"person\">\n <input [(ngModel)]=\"person.name\" name=\"firstName\">\n </div>\n </form>",
ngModelWithFormGroup: "\n <div [formGroup]=\"myGroup\">\n <input formControlName=\"firstName\">\n <input [(ngModel)]=\"showMoreControls\" [ngModelOptions]=\"{standalone: true}\">\n </div>\n "
};
/**
* @license
* Copyright Google Inc. 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
*/
var ReactiveErrors = /** @class */ (function () {
function ReactiveErrors() {
}
ReactiveErrors.controlParentException = function () {
throw new Error("formControlName must be used with a parent formGroup directive. You'll want to add a formGroup\n directive and pass it an existing FormGroup instance (you can create one in your class).\n\n Example:\n\n " + FormErrorExamples.formControlName);
};
ReactiveErrors.ngModelGroupException = function () {
throw new Error("formControlName cannot be used with an ngModelGroup parent. It is only compatible with parents\n that also have a \"form\" prefix: formGroupName, formArrayName, or formGroup.\n\n Option 1: Update the parent to be formGroupName (reactive form strategy)\n\n " + FormErrorExamples.formGroupName + "\n\n Option 2: Use ngModel instead of formControlName (template-driven strategy)\n\n " + FormErrorExamples.ngModelGroup);
};
ReactiveErrors.missingFormException = function () {
throw new Error("formGroup expects a FormGroup instance. Please pass one in.\n\n Example:\n\n " + FormErrorExamples.formControlName);
};
ReactiveErrors.groupParentException = function () {
throw new Error("formGroupName must be used with a parent formGroup directive. You'll want to add a formGroup\n directive and pass it an existing FormGroup instance (you can create one in your class).\n\n Example:\n\n " + FormErrorExamples.formGroupName);
};
ReactiveErrors.arrayParentException = function () {
throw new Error("formArrayName must be used with a parent formGroup directive. You'll want to add a formGroup\n directive and pass it an existing FormGroup instance (you can create one in your class).\n\n Example:\n\n " + FormErrorExamples.formArrayName);
};
ReactiveErrors.disabledAttrWarning = function () {
console.warn("\n It looks like you're using the disabled attribute with a reactive form directive. If you set disabled to true\n when you set up this control in your component class, the disabled attribute will actually be set in the DOM for\n you. We recommend using this approach to avoid 'changed after checked' errors.\n \n Example: \n form = new FormGroup({\n first: new FormControl({value: 'Nancy', disabled: true}, Validators.required),\n last: new FormControl('Drew', Validators.required)\n });\n ");
};
ReactiveErrors.ngModelWarning = function (directiveName) {
console.warn("\n It looks like you're using ngModel on the same form field as " + directiveName + ". \n Support for using the ngModel input property and ngModelChange event with \n reactive form directives has been deprecated in Angular v6 and will be removed \n in Angular v7.\n \n For more information on this, see our API docs here:\n https://angular.io/api/forms/" + (directiveName === 'formControl' ? 'FormControlDirective'
: 'FormControlName') + "#use-with-ngmodel\n ");
};
return ReactiveErrors;
}());
/**
* @license
* Copyright Google Inc. 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
*/
var SELECT_VALUE_ACCESSOR = {
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(function () { return SelectControlValueAccessor; }),
multi: true
};
function _buildValueString(id, value) {
if (id == null)
return "" + value;
if (value && typeof value === 'object')
value = 'Object';
return (id + ": " + value).slice(0, 50);
}
function _extractId(valueString) {
return valueString.split(':')[0];
}
/**
* @description
* The `ControlValueAccessor` for writing select control values and listening to select control
* changes. The value accessor is used by the `FormControlDirective`, `FormControlName`, and
* `NgModel` directives.
*
* @usageNotes
*
* ### Using select controls in a reactive form
*
* The following examples show how to use a select control in a reactive form.
*
* {@example forms/ts/reactiveSelectControl/reactive_select_control_example.ts region='Component'}
*
* ### Using select controls in a template-driven form
*
* To use a select in a template-driven form, simply add an `ngModel` and a `name`
* attribute to the main `<select>` tag.
*
* {@example forms/ts/selectControl/select_control_example.ts region='Component'}
*
* ### Customizing option selection
*
* Angular uses object identity to select option. It's possible for the identities of items
* to change while the data does not. This can happen, for example, if the items are produced
* from an RPC to the server, and that RPC is re-run. Even if the data hasn't changed, the
* second response will produce objects with different identities.
*
* To customize the default option comparison algorithm, `<select>` supports `compareWith` input.
* `compareWith` takes a **function** which has two arguments: `option1` and `option2`.
* If `compareWith` is given, Angular selects option by the return value of the function.
*
* ```ts
* const selectedCountriesControl = new FormControl();
* ```
*
* ```
* <select [compareWith]="compareFn" [formControl]="selectedCountriesControl">
* <option *ngFor="let country of countries" [ngValue]="country">
* {{country.name}}
* </option>
* </select>
*
* compareFn(c1: Country, c2: Country): boolean {
* return c1 && c2 ? c1.id === c2.id : c1 === c2;
* }
* ```
*
* **Note:** We listen to the 'change' event because 'input' events aren't fired
* for selects in Firefox and IE:
* https://bugzilla.mozilla.org/show_bug.cgi?id=1024350
* https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/4660045/
*
* @ngModule ReactiveFormsModule
* @ngModule FormsModule
* @publicApi
*/
var SelectControlValueAccessor = /** @class */ (function () {
function SelectControlValueAccessor(_renderer, _elementRef) {
this._renderer = _renderer;
this._elementRef = _elementRef;
/** @internal */
this._optionMap = new Map();
/** @internal */
this._idCounter = 0;
/**
* @description
* The registered callback function called when a change event occurs on the input element.
*/
this.onChange = function (_) { };
/**
* @description
* The registered callback function called when a blur event occurs on the input element.
*/
this.onTouched = function () { };
this._compareWith = ɵlooseIdentical;
}
Object.defineProperty(SelectControlValueAccessor.prototype, "compareWith", {
/**
* @description
* Tracks the option comparison algorithm for tracking identities when
* checking for changes.
*/
set: function (fn) {
if (typeof fn !== 'function') {
throw new Error("compareWith must be a function, but received " + JSON.stringify(fn));
}
this._compareWith = fn;
},
enumerable: true,
configurable: true
});
/**
* Sets the "value" property on the input element. The "selectedIndex"
* property is also set if an ID is provided on the option element.
*
* @param value The checked value
*/
SelectControlValueAccessor.prototype.writeValue = function (value) {
this.value = value;
var id = this._getOptionId(value);
if (id == null) {
this._renderer.setProperty(this._elementRef.nativeElement, 'selectedIndex', -1);
}
var valueString = _buildValueString(id, value);
this._renderer.setProperty(this._elementRef.nativeElement, 'value', valueString);
};
/**
* @description
* Registers a function called when the control value changes.
*
* @param fn The callback function
*/
SelectControlValueAccessor.prototype.registerOnChange = function (fn) {
var _this = this;
this.onChange = function (valueString) {
_this.value = _this._getOptionValue(valueString);
fn(_this.value);
};
};
/**
* @description
* Registers a function called when the control is touched.
*
* @param fn The callback function
*/
SelectControlValueAccessor.prototype.registerOnTouched = function (fn) { this.onTouched = fn; };
/**
* Sets the "disabled" property on the select input element.
*
* @param isDisabled The disabled value
*/
SelectControlValueAccessor.prototype.setDisabledState = function (isDisabled) {
this._renderer.setProperty(this._elementRef.nativeElement, 'disabled', isDisabled);
};
/** @internal */
SelectControlValueAccessor.prototype._registerOption = function () { return (this._idCounter++).toString(); };
/** @internal */
SelectControlValueAccessor.prototype._getOptionId = function (value) {
var e_1, _a;
try {
for (var _b = __values(Array.from(this._optionMap.keys())), _c = _b.next(); !_c.done; _c = _b.next()) {
var id = _c.value;
if (this._compareWith(this._optionMap.get(id), value))
return id;
}
}
catch (e_1_1) { e_1 = { error: e_1_1 }; }
finally {
try {
if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
}
finally { if (e_1) throw e_1.error; }
}
return null;
};
/** @internal */
SelectControlValueAccessor.prototype._getOptionValue = function (valueString) {
var id = _extractId(valueString);
return this._optionMap.has(id) ? this._optionMap.get(id) : valueString;
};
__decorate([
Input(),
__metadata("design:type", Function),
__metadata("design:paramtypes", [Function])
], SelectControlValueAccessor.prototype, "compareWith", null);
SelectControlValueAccessor = __decorate([
Directive({
selector: 'select:not([multiple])[formControlName],select:not([multiple])[formControl],select:not([multiple])[ngModel]',
host: { '(change)': 'onChange($event.target.value)', '(blur)': 'onTouched()' },
providers: [SELECT_VALUE_ACCESSOR]
}),
__metadata("design:paramtypes", [Renderer2, ElementRef])
], SelectControlValueAccessor);
return SelectControlValueAccessor;
}());
/**
* @description
* Marks `<option>` as dynamic, so Angular can be notified when options change.
*
* @see `SelectControlValueAccessor`
*
* @ngModule ReactiveFormsModule
* @ngModule FormsModule
* @publicApi
*/
var NgSelectOption = /** @class */ (function () {
function NgSelectOption(_element, _renderer, _select) {
this._element = _element;
this._renderer = _renderer;
this._select = _select;
if (this._select)
this.id = this._select._registerOption();
}
Object.defineProperty(NgSelectOption.prototype, "ngValue", {
/**
* @description
* Tracks the value bound to the option element. Unlike the value binding,
* ngValue supports binding to objects.
*/
set: function (value) {
if (this._select == null)
return;
this._select._optionMap.set(this.id, value);
this._setElementValue(_buildValueString(this.id, value));
this._select.writeValue(this._select.value);
},
enumerable: true,
configurable: true
});
Object.defineProperty(NgSelectOption.prototype, "value", {
/**
* @description
* Tracks simple string values bound to the option element.
* For objects, use the `ngValue` input binding.
*/
set: function (value) {
this._setElementValue(value);
if (this._select)
this._select.writeValue(this._select.value);
},
enumerable: true,
configurable: true
});
/** @internal */
NgSelectOption.prototype._setElementValue = function (value) {
this._renderer.setProperty(this._element.nativeElement, 'value', value);
};
/**
* @description
* Lifecycle method called before the directive's instance is destroyed. For internal use only.
*/
NgSelectOption.prototype.ngOnDestroy = function () {
if (this._select) {
this._select._optionMap.delete(this.id);
this._select.writeValue(this._select.value);
}
};
__decorate([
Input('ngValue'),
__metadata("design:type", Object),
__metadata("design:paramtypes", [Object])
], NgSelectOption.prototype, "ngValue", null);
__decorate([
Input('value'),
__metadata("design:type", Object),
__metadata("design:paramtypes", [Object])
], NgSelectOption.prototype, "value", null);
NgSelectOption = __decorate([
Directive({ selector: 'option' }),
__param(2, Optional()), __param(2, Host()),
__metadata("design:paramtypes", [ElementRef, Renderer2,
SelectControlValueAccessor])
], NgSelectOption);
return NgSelectOption;
}());
/**
* @license
* Copyright Google Inc. 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
*/
var SELECT_MULTIPLE_VALUE_ACCESSOR = {
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(function () { return SelectMultipleControlValueAccessor; }),
multi: true
};
function _buildValueString$1(id, value) {
if (id == null)
return "" + value;
if (typeof value === 'string')
value = "'" + value + "'";
if (value && typeof value === 'object')
value = 'Object';
return (id + ": " + value).slice(0, 50);
}
function _extractId$1(valueString) {
return valueString.split(':')[0];
}
/**
* @description
* The `ControlValueAccessor` for writing multi-select control values and listening to multi-select control
* changes. The value accessor is used by the `FormControlDirective`, `FormControlName`, and `NgModel`
* directives.
*
* @see `SelectControlValueAccessor`
*
* @usageNotes
*
* ### Using a multi-select control
*
* The follow example shows you how to use a multi-select control with a reactive form.
*
* ```ts
* const countryControl = new FormControl();
* ```
*
* ```
* <select multiple name="countries" [formControl]="countryControl">
* <option *ngFor="let country of countries" [ngValue]="country">
* {{ country.name }}
* </option>
* </select>
* ```
*
* ### Customizing option selection
*
* To customize the default option comparison algorithm, `<select>` supports `compareWith` input.
* See the `SelectControlValueAccessor` for usage.
*
* @ngModule ReactiveFormsModule
* @ngModule FormsModule
* @publicApi
*/
var SelectMultipleControlValueAccessor = /** @class */ (function () {
function SelectMultipleControlValueAccessor(_renderer, _elementRef) {
this._renderer = _renderer;
this._elementRef = _elementRef;
/** @internal */
this._optionMap = new Map();
/** @internal */
this._idCounter = 0;
/**
* @description
* The registered callback function called when a change event occurs on the input element.
*/
this.onChange = function (_) { };
/**
* @description
* The registered callback function called when a blur event occurs on the input element.
*/
this.onTouched = function () { };
this._compareWith = ɵlooseIdentical;
}
Object.defineProperty(SelectMultipleControlValueAccessor.prototype, "compareWith", {
/**
* @description
* Tracks the option comparison algorithm for tracking identities when
* checking for changes.
*/
set: function (fn) {
if (typeof fn !== 'function') {
throw new Error("compareWith must be a function, but received " + JSON.stringify(fn));
}
this._compareWith = fn;
},
enumerable: true,
configurable: true
});
/**
* @description
* Sets the "value" property on one or of more
* of the select's options.
*
* @param value The value
*/
SelectMultipleControlValueAccessor.prototype.writeValue = function (value) {
var _this = this;
this.value = value;
var optionSelectedStateSetter;
if (Array.isArray(value)) {
// convert values to ids
var ids_1 = value.map(function (v) { return _this._getOptionId(v); });
optionSelectedStateSetter = function (opt, o) { opt._setSelected(ids_1.indexOf(o.toString()) > -1); };
}
else {
optionSelectedStateSetter = function (opt, o) { opt._setSelected(false); };
}
this._optionMap.forEach(optionSelectedStateSetter);
};
/**
* @description
* Registers a function called when the control value changes
* and writes an array of the selected options.
*
* @param fn The callback function
*/
SelectMultipleControlValueAccessor.prototype.registerOnChange = function (fn) {
var _this = this;
this.onChange = function (_) {
var selected = [];
if (_.hasOwnProperty('selectedOptions')) {
var options = _.selectedOptions;
for (var i = 0; i < options.length; i++) {
var opt = options.item(i);
var val = _this._getOptionValue(opt.value);
selected.push(val);
}
}
// Degrade on IE
else {
var options = _.options;
for (var i = 0; i < options.length; i++) {
var opt = options.item(i);
if (opt.selected) {
var val = _this._getOptionValue(opt.value);
selected.push(val);
}
}
}
_this.value = selected;
fn(selected);
};
};
/**
* @description
* Registers a function called when the control is touched.
*
* @param fn The callback function
*/
SelectMultipleControlValueAccessor.prototype.registerOnTouched = function (fn) { this.onTouched = fn; };
/**
* Sets the "disabled" property on the select input element.
*
* @param isDisabled The disabled value
*/
SelectMultipleControlValueAccessor.prototype.setDisabledState = function (isDisabled) {
this._renderer.setProperty(this._elementRef.nativeElement, 'disabled', isDisabled);
};
/** @internal */
SelectMultipleControlValueAccessor.prototype._registerOption = function (value) {
var id = (this._idCounter++).toString();
this._optionMap.set(id, value);
return id;
};
/** @internal */
SelectMultipleControlValueAccessor.prototype._getOptionId = function (value) {
var e_1, _a;
try {
for (var _b = __values(Array.from(this._optionMap.keys())), _c = _b.next(); !_c.done; _c = _b.next()) {
var id = _c.value;
if (this._compareWith(this._optionMap.get(id)._value, value))
return id;
}
}
catch (e_1_1) { e_1 = { error: e_1_1 }; }
finally {
try {
if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
}
finally { if (e_1) throw e_1.error; }
}
return null;
};
/** @internal */
SelectMultipleControlValueAccessor.prototype._getOptionValue = function (valueString) {
var id = _extractId$1(valueString);
return this._optionMap.has(id) ? this._optionMap.get(id)._value : valueString;
};
__decorate([
Input(),
__metadata("design:type", Function),
__metadata("design:paramtypes", [Function])
], SelectMultipleControlValueAccessor.prototype, "compareWith", null);
SelectMultipleControlValueAccessor = __decorate([
Directive({
selector: 'select[multiple][formControlName],select[multiple][formControl],select[multiple][ngModel]',
host: { '(change)': 'onChange($event.target)', '(blur)': 'onTouched()' },
providers: [SELECT_MULTIPLE_VALUE_ACCESSOR]
}),
__metadata("design:paramtypes", [Renderer2, ElementRef])
], SelectMultipleControlValueAccessor);
return SelectMultipleControlValueAccessor;
}());
/**
* @description
* Marks `<option>` as dynamic, so Angular can be notified when options change.
*
* @see `SelectMultipleControlValueAccessor`
*
* @ngModule ReactiveFormsModule
* @ngModule FormsModule
* @publicApi
*/
var NgSelectMultipleOption = /** @class */ (function () {
function NgSelectMultipleOption(_element, _renderer, _select) {
this._element = _element;
this._renderer = _renderer;
this._select = _select;
if (this._select) {
this.id = this._select._registerOption(this);
}
}
Object.defineProperty(NgSelectMultipleOption.prototype, "ngValue", {
/**
* @description
* Tracks the value bound to the option element. Unlike the value binding,
* ngValue supports binding to objects.
*/
set: function (value) {
if (this._select == null)
return;
this._value = value;
this._setElementValue(_buildValueString$1(this.id, value));
this._select.writeValue(this._select.value);
},
enumerable: true,
configurable: true
});
Object.defineProperty(NgSelectMultipleOption.prototype, "value", {
/**
* @description
* Tracks simple string values bound to the option element.
* For objects, use the `ngValue` input binding.
*/
set: function (value) {
if (this._select) {
this._value = value;
this._setElementValue(_buildValueString$1(this.id, value));
this._select.writeValue(this._select.value);
}
else {
this._setElementValue(value);
}
},
enumerable: true,
configurable: true
});
/** @internal */
NgSelectMultipleOption.prototype._setElementValue = function (value) {
this._renderer.setProperty(this._element.nativeElement, 'value', value);
};
/** @internal */
NgSelectMultipleOption.prototype._setSelected = function (selected) {
this._renderer.setProperty(this._element.nativeElement, 'selected', selected);
};
/**
* @description
* Lifecycle method called before the directive's instance is destroyed. For internal use only.
*/
NgSelectMultipleOption.prototype.ngOnDestroy = function () {
if (this._select) {
this._select._optionMap.delete(this.id);
this._select.writeValue(this._select.value);
}
};
__decorate([
Input('ngValue'),
__metadata("design:type", Object),
__metadata("design:paramtypes", [Object])
], NgSelectMultipleOption.prototype, "ngValue", null);
__decorate([
Input('value'),
__metadata("design:type", Object),
__metadata("design:paramtypes", [Object])
], NgSelectMultipleOption.prototype, "value", null);
NgSelectMultipleOption = __decorate([
Directive({ selector: 'option' }),
__param(2, Optional()), __param(2, Host()),
__metadata("design:paramtypes", [ElementRef, Renderer2,
SelectMultipleControlValueAccessor])
], NgSelectMultipleOption);
return NgSelectMultipleOption;
}());
/**
* @license
* Copyright Google Inc. 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
*/
function controlPath(name, parent) {
return __spread(parent.path, [name]);
}
function setUpControl(control, dir) {
if (!control)
_throwError(dir, 'Cannot find control with');
if (!dir.valueAccessor)
_throwError(dir, 'No value accessor for form control with');
control.validator = Validators.compose([control.validator, dir.validator]);
control.asyncValidator = Validators.composeAsync([control.asyncValidator, dir.asyncValidator]);
dir.valueAccessor.writeValue(control.value);
setUpViewChangePipeline(control, dir);
setUpModelChangePipeline(control, dir);
setUpBlurPipeline(control, dir);
if (dir.valueAccessor.setDisabledState) {
control.registerOnDisabledChange(function (isDisabled) { dir.valueAccessor.setDisabledState(isDisabled); });
}
// re-run validation when validator binding changes, e.g. minlength=3 -> minlength=4
dir._rawValidators.forEach(function (validator) {
if (validator.registerOnValidatorChange)
validator.registerOnValidatorChange(function () { return control.updateValueAndValidity(); });
});
dir._rawAsyncValidators.forEach(function (validator) {
if (validator.registerOnValidatorChange)
validator.registerOnValidatorChange(function () { return control.updateValueAndValidity(); });
});
}
function cleanUpControl(control, dir) {
dir.valueAccessor.registerOnChange(function () { return _noControlError(dir); });
dir.valueAccessor.registerOnTouched(function () { return _noControlError(dir); });
dir._rawValidators.forEach(function (validator) {
if (validator.registerOnValidatorChange) {
validator.registerOnValidatorChange(null);
}
});
dir._rawAsyncValidators.forEach(function (validator) {
if (validator.registerOnValidatorChange) {
validator.registerOnValidatorChange(null);
}
});
if (control)
control._clearChangeFns();
}
function setUpViewChangePipeline(control, dir) {
dir.valueAccessor.registerOnChange(function (newValue) {
control._pendingValue = newValue;
control._pendingChange = true;
control._pendingDirty = true;
if (control.updateOn === 'change')
updateControl(control, dir);
});
}
function setUpBlurPipeline(control, dir) {
dir.valueAccessor.registerOnTouched(function () {
control._pendingTouched = true;
if (control.updateOn === 'blur' && control._pendingChange)
updateControl(control, dir);
if (control.updateOn !== 'submit')
control.markAsTouched();
});
}
function updateControl(control, dir) {
if (control._pendingDirty)
control.markAsDirty();
control.setValue(control._pendingValue, { emitModelToViewChange: false });
dir.viewToModelUpdate(control._pendingValue);
control._pendingChange = false;
}
function setUpModelChangePipeline(control, dir) {
control.registerOnChange(function (newValue, emitModelEvent) {
// control -> view
dir.valueAccessor.writeValue(newValue);
// control -> ngModel
if (emitModelEvent)
dir.viewToModelUpdate(newValue);
});
}
function setUpFormContainer(control, dir) {
if (control == null)
_throwError(dir, 'Cannot find control with');
control.validator = Validators.compose([control.validator, dir.validator]);
control.asyncValidator = Validators.composeAsync([control.asyncValidator, dir.asyncValidator]);
}
function _noControlError(dir) {
return _throwError(dir, 'There is no FormControl instance attached to form control element with');
}
function _throwError(dir, message) {
var messageEnd;
if (dir.path.length > 1) {
messageEnd = "path: '" + dir.path.join(' -> ') + "'";
}
else if (dir.path[0]) {
messageEnd = "name: '" + dir.path + "'";
}
else {
messageEnd = 'unspecified name attribute';
}
throw new Error(message + " " + messageEnd);
}
function composeValidators(validators) {
return validators != null ? Validators.compose(validators.map(normalizeValidator)) : null;
}
function composeAsyncValidators(validators) {
return validators != null ? Validators.composeAsync(validators.map(normalizeAsyncValidator)) :
null;
}
function isPropertyUpdated(changes, viewModel) {
if (!changes.hasOwnProperty('model'))
return false;
var change = changes['model'];
if (change.isFirstChange())
return true;
return !ɵlooseIdentical(viewModel, change.currentValue);
}
var BUILTIN_ACCESSORS = [
CheckboxControlValueAccessor,
RangeValueAccessor,
NumberValueAccessor,
SelectControlValueAccessor,
SelectMultipleControlValueAccessor,
RadioControlValueAccessor,
];
function isBuiltInAccessor(valueAccessor) {
return BUILTIN_ACCESSORS.some(function (a) { return valueAccessor.constructor === a; });
}
function syncPendingControls(form, directives) {
form._syncPendingControls();
directives.forEach(function (dir) {
var control = dir.control;
if (control.updateOn === 'submit' && control._pendingChange) {
dir.viewToModelUpdate(control._pendingValue);
control._pendingChange = false;
}
});
}
// TODO: vsavkin remove it once https://github.com/angular/angular/issues/3011 is implemented
function selectValueAccessor(dir, valueAccessors) {
if (!valueAccessors)
return null;
if (!Array.isArray(valueAccessors))
_throwError(dir, 'Value accessor was not provided as an array for form control with');
var defaultAccessor = undefined;
var builtinAccessor = undefined;
var customAccessor = undefined;
valueAccessors.forEach(function (v) {
if (v.constructor === DefaultValueAccessor) {
defaultAccessor = v;
}
else if (isBuiltInAccessor(v)) {
if (builtinAccessor)
_throwError(dir, 'More than one built-in value accessor matches form control with');
builtinAccessor = v;
}
else {
if (customAccessor)
_throwError(dir, 'More than one custom value accessor matches form control with');
customAccessor = v;
}
});
if (customAccessor)
return customAccessor;
if (builtinAccessor)
return builtinAccessor;
if (defaultAccessor)
return defaultAccessor;
_throwError(dir, 'No valid value accessor for form control with');
return null;
}
function removeDir(list, el) {
var index = list.indexOf(el);
if (index > -1)
list.splice(index, 1);
}
// TODO(kara): remove after deprecation period
function _ngModelWarning(name, type, instance, warningConfig) {
if (!isDevMode() || warningConfig === 'never')
return;
if (((warningConfig === null || warningConfig === 'once') && !type._ngModelWarningSentOnce) ||
(warningConfig === 'always' && !instance._ngModelWarningSent)) {
ReactiveErrors.ngModelWarning(name);
type._ngModelWarningSentOnce = true;
instance._ngModelWarningSent = true;
}
}
/**
* @license
* Copyright Google Inc. 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
*/
/**
* @description
* A base class for code shared between the `NgModelGroup` and `FormGroupName` directives.
*
* @publicApi
*/
var AbstractFormGroupDirective = /** @class */ (function (_super) {
__extends(AbstractFormGroupDirective, _super);
function AbstractFormGroupDirective() {
return _super !== null && _super.apply(this, arguments) || this;
}
/**
* @description
* An internal callback method triggered on the instance after the inputs are set.
* Registers the group with its parent group.
*/
AbstractFormGroupDirective.prototype.ngOnInit = function () {
this._checkParentType();
this.formDirective.addFormGroup(this);
};
/**
* @description
* An internal callback method triggered before the instance is destroyed.
* Removes the group from its parent group.
*/
AbstractFormGroupDirective.prototype.ngOnDestroy = function () {
if (this.formDirective) {
this.formDirective.removeFormGroup(this);
}
};
Object.defineProperty(AbstractFormGroupDirective.prototype, "control", {
/**
* @description
* The `FormGroup` bound to this directive.
*/
get: function () { return this.formDirective.getFormGroup(this); },
enumerable: true,
configurable: true
});
Object.defineProperty(AbstractFormGroupDirective.prototype, "path", {
/**
* @description
* The path to this group from the top-level directive.
*/
get: function () { return controlPath(this.name, this._parent); },
enumerable: true,
configurable: true
});
Object.defineProperty(AbstractFormGroupDirective.prototype, "formDirective", {
/**
* @description
* The top-level directive for this group if present, otherwise null.
*/
get: function () { return this._parent ? this._parent.formDirective : null; },
enumerable: true,
configurable: true
});
Object.defineProperty(AbstractFormGroupDirective.prototype, "validator", {
/**
* @description
* The synchronous validators registered with this group.
*/
get: function () { return composeValidators(this._validators); },
enumerable: true,
configurable: true
});
Object.defineProperty(AbstractFormGroupDirective.prototype, "asyncValidator", {
/**
* @description
* The async validators registered with this group.
*/
get: function () {
return composeAsyncValidators(this._asyncValidators);
},
enumerable: true,
configurable: true
});
/** @internal */
AbstractFormGroupDirective.prototype._checkParentType = function () { };
return AbstractFormGroupDirective;
}(ControlContainer));
/**
* @license
* Copyright Google Inc. 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
*/
var AbstractControlStatus = /** @class */ (function () {
function AbstractControlStatus(cd) {
this._cd = cd;
}
Object.defineProperty(AbstractControlStatus.prototype, "ngClassUntouched", {
get: function () { return this._cd.control ? this._cd.control.untouched : false; },
enumerable: true,
configurable: true
});
Object.defineProperty(AbstractControlStatus.prototype, "ngClassTouched", {
get: function () { return this._cd.control ? this._cd.control.touched : false; },
enumerable: true,
configurable: true
});
Object.defineProperty(AbstractControlStatus.prototype, "ngClassPristine", {
get: function () { return this._cd.control ? this._cd.control.pristine : false; },
enumerable: true,
configurable: true
});
Object.defineProperty(AbstractControlStatus.prototype, "ngClassDirty", {
get: function () { return this._cd.control ? this._cd.control.dirty : false; },
enumerable: true,
configurable: true
});
Object.defineProperty(AbstractControlStatus.prototype, "ngClassValid", {
get: function () { return this._cd.control ? this._cd.control.valid : false; },
enumerable: true,
configurable: true
});
Object.defineProperty(AbstractControlStatus.prototype, "ngClassInvalid", {
get: function () { return this._cd.control ? this._cd.control.invalid : false; },
enumerable: true,
configurable: true
});
Object.defineProperty(AbstractControlStatus.prototype, "ngClassPending", {
get: function () { return this._cd.control ? this._cd.control.pending : false; },
enumerable: true,
configurable: true
});
return AbstractControlStatus;
}());
var ngControlStatusHost = {
'[class.ng-untouched]': 'ngClassUntouched',
'[class.ng-touched]': 'ngClassTouched',
'[class.ng-pristine]': 'ngClassPristine',
'[class.ng-dirty]': 'ngClassDirty',
'[class.ng-valid]': 'ngClassValid',
'[class.ng-invalid]': 'ngClassInvalid',
'[class.ng-pending]': 'ngClassPending',
};
/**
* @description
* Directive automatically applied to Angular form controls that sets CSS classes
* based on control status.
*
* @usageNotes
*
* ### CSS classes applied
*
* The following classes are applied as the properties become true:
*
* * ng-valid
* * ng-invalid
* * ng-pending
* * ng-pristine
* * ng-dirty
* * ng-untouched
* * ng-touched
*
* @ngModule ReactiveFormsModule
* @ngModule FormsModule
* @publicApi
*/
var NgControlStatus = /** @class */ (function (_super) {
__extends(NgControlStatus, _super);
function NgControlStatus(cd) {
return _super.call(this, cd) || this;
}
NgControlStatus = __decorate([
Directive({ selector: '[formControlName],[ngModel],[formControl]', host: ngControlStatusHost }),
__param(0, Self()),
__metadata("design:paramtypes", [NgControl])
], NgControlStatus);
return NgControlStatus;
}(AbstractControlStatus));
/**
* @description
* Directive automatically applied to Angular form groups that sets CSS classes
* based on control status (valid/invalid/dirty/etc).
*
* @see `NgControlStatus`
*
* @ngModule ReactiveFormsModule
* @ngModule FormsModule
* @publicApi
*/
var NgControlStatusGroup = /** @class */ (function (_super) {
__extends(NgControlStatusGroup, _super);
function NgControlStatusGroup(cd) {
return _super.call(this, cd) || this;
}
NgControlStatusGroup = __decorate([
Directive({
selector: '[formGroupName],[formArrayName],[ngModelGroup],[formGroup],form:not([ngNoForm]),[ngForm]',
host: ngControlStatusHost
}),
__param(0, Self()),
__metadata("design:paramtypes", [ControlContainer])
], NgControlStatusGroup);
return NgControlStatusGroup;
}(AbstractControlStatus));
/**
* @license
* Copyright Google Inc. 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
*/
/**
* Reports that a FormControl is valid, meaning that no errors exist in the input value.
*
* @see `status`
*/
var VALID = 'VALID';
/**
* Reports that a FormControl is invalid, meaning that an error exists in the input value.
*
* @see `status`
*/
var INVALID = 'INVALID';
/**
* Reports that a FormControl is pending, meaning that that async validation is occurring and
* errors are not yet available for the input value.
*
* @see `markAsPending`
* @see `status`
*/
var PENDING = 'PENDING';
/**
* Reports that a FormControl is disabled, meaning that the control is exempt from ancestor
* calculations of validity or value.
*
* @see `markAsDisabled`
* @see `status`
*/
var DISABLED = 'DISABLED';
function _find(control, path, delimiter) {
if (path == null)
return null;
if (!(path instanceof Array)) {
path = path.split(delimiter);
}
if (path instanceof Array && (path.length === 0))
return null;
return path.reduce(function (v, name) {
if (v instanceof FormGroup) {
return v.controls.hasOwnProperty(name) ? v.controls[name] : null;
}
if (v instanceof FormArray) {
return v.at(name) || null;
}
return null;
}, control);
}
function coerceToValidator(validatorOrOpts) {
var validator = (isOptionsObj(validatorOrOpts) ? validatorOrOpts.validators :
validatorOrOpts);
return Array.isArray(validator) ? composeValidators(validator) : validator || null;
}
function coerceToAsyncValidator(asyncValidator, validatorOrOpts) {
var origAsyncValidator = (isOptionsObj(validatorOrOpts) ? validatorOrOpts.asyncValidators :
asyncValidator);
return Array.isArray(origAsyncValidator) ? composeAsyncValidators(origAsyncValidator) :
origAsyncValidator || null;
}
function isOptionsObj(validatorOrOpts) {
return validatorOrOpts != null && !Array.isArray(validatorOrOpts) &&
typeof validatorOrOpts === 'object';
}
/**
* This is the base class for `FormControl`, `FormGroup`, and `FormArray`.
*
* It provides some of the shared behavior that all controls and groups of controls have, like
* running validators, calculating status, and resetting state. It also defines the properties
* that are shared between all sub-classes, like `value`, `valid`, and `dirty`. It shouldn't be
* instantiated directly.
*
* @see [Forms Guide](/guide/forms)
* @see [Reactive Forms Guide](/guide/reactive-forms)
* @see [Dynamic Forms Guide](/guide/dynamic-form)
*
* @publicApi
*/
var AbstractControl = /** @class */ (function () {
/**
* Initialize the AbstractControl instance.
*
* @param validator The function that determines the synchronous validity of this control.
* @param asyncValidator The function that determines the asynchronous validity of this
* control.
*/
function AbstractControl(validator, asyncValidator) {
this.validator = validator;
this.asyncValidator = asyncValidator;
/** @internal */
this._onCollectionChange = function () { };
/**
* A control is `pristine` if the user has not yet changed
* the value in the UI.
*
* @returns True if the user has not yet changed the value in the UI; compare `dirty`.
* Programmatic changes to a control's value do not mark it dirty.
*/
this.pristine = true;
/**
* True if the control is marked as `touched`.
*
* A control is marked `touched` once the user has triggered
* a `blur` event on it.
*/
this.touched = false;
/** @internal */
this._onDisabledChange = [];
}
Object.defineProperty(AbstractControl.prototype, "parent", {
/**
* The parent control.
*/
get: function () { return this._parent; },
enumerable: true,
configurable: true
});
Object.defineProperty(AbstractControl.prototype, "valid", {
/**
* A control is `valid` when its `status` is `VALID`.
*
* @see `status`
*
* @returns True if the control has passed all of its validation tests,
* false otherwise.
*/
get: function () { return this.status === VALID; },
enumerable: true,
configurable: true
});
Object.defineProperty(AbstractControl.prototype, "invalid", {
/**
* A control is `invalid` when its `status` is `INVALID`.
*
* @see `status`
*
* @returns True if this control has failed one or more of its validation checks,
* false otherwise.
*/
get: function () { return this.status === INVALID; },
enumerable: true,
configurable: true
});
Object.defineProperty(AbstractControl.prototype, "pending", {
/**
* A control is `pending` when its `status` is `PENDING`.
*
* @see `status`
*
* @returns True if this control is in the process of conducting a validation check,
* false otherwise.
*/
get: function () { return this.status == PENDING; },
enumerable: true,
configurable: true
});
Object.defineProperty(AbstractControl.prototype, "disabled", {
/**
* A control is `disabled` when its `status` is `DISABLED`.
*
* @see `status`
*
* Disabled controls are exempt from validation checks and
* are not included in the aggregate value of their ancestor
* controls.
*
* @returns True if the control is disabled, false otherwise.
*/
get: function () { return this.status === DISABLED; },
enumerable: true,
configurable: true
});
Object.defineProperty(AbstractControl.prototype, "enabled", {
/**
* A control is `enabled` as long as its `status` is not `DISABLED`.
*
* @see `status`
*
* @returns True if the control has any status other than 'DISABLED',
* false if the status is 'DISABLED'.
*
*/
get: function () { return this.status !== DISABLED; },
enumerable: true,
configurable: true
});
Object.defineProperty(AbstractControl.prototype, "dirty", {
/**
* A control is `dirty` if the user has changed the value
* in the UI.
*
* @returns True if the user has changed the value of this control in the UI; compare `pristine`.
* Programmatic changes to a control's value do not mark it dirty.
*/
get: function () { return !this.pristine; },
enumerable: true,
configurable: true
});
Object.defineProperty(AbstractControl.prototype, "untouched", {
/**
* True if the control has not been marked as touched
*
* A control is `untouched` if the user has not yet triggered
* a `blur` event on it.
*/
get: function () { return !this.touched; },
enumerable: true,
configurable: true
});
Object.defineProperty(AbstractControl.prototype, "updateOn", {
/**
* Reports the update strategy of the `AbstractControl` (meaning
* the event on which the control updates itself).
* Possible values: `'change'` | `'blur'` | `'submit'`
* Default value: `'change'`
*/
get: function () {
return this._updateOn ? this._updateOn : (this.parent ? this.parent.updateOn : 'change');
},
enumerable: true,
configurable: true
});
/**
* Sets the synchronous validators that are active on this control. Calling
* this overwrites any existing sync validators.
*/
AbstractControl.prototype.setValidators = function (newValidator) {
this.validator = coerceToValidator(newValidator);
};
/**
* Sets the async validators that are active on this control. Calling this
* overwrites any existing async validators.
*/
AbstractControl.prototype.setAsyncValidators = function (newValidator) {
this.asyncValidator = coerceToAsyncValidator(newValidator);
};
/**
* Empties out the sync validator list.
*/
AbstractControl.prototype.clearValidators = function () { this.validator = null; };
/**
* Empties out the async validator list.
*/
AbstractControl.prototype.clearAsyncValidators = function () { this.asyncValidator = null; };
/**
* Marks the control as `touched`. A control is touched by focus and
* blur events that do not change the value; compare `markAsDirty`;
*
* @param opts Configuration options that determine how the control propagates changes
* and emits events events after marking is applied.
* * `onlySelf`: When true, mark only this control. When false or not supplied,
* marks all direct ancestors. Default is false.
*/
AbstractControl.prototype.markAsTouched = function (opts) {
if (opts === void 0) { opts = {}; }
this.touched = true;
if (this._parent && !opts.onlySelf) {
this._parent.markAsTouched(opts);
}
};
/**
* Marks the control as `untouched`.
*
* If the control has any children, also marks all children as `untouched`
* and recalculates the `touched` status of all parent controls.
*
* @param opts Configuration options that determine how the control propagates changes
* and emits events after the marking is applied.
* * `onlySelf`: When true, mark only this control. When false or not supplied,
* marks all direct ancestors. Default is false.
*/
AbstractControl.prototype.markAsUntouched = function (opts) {
if (opts === void 0) { opts = {}; }
this.touched = false;
this._pendingTouched = false;
this._forEachChild(function (control) { control.markAsUntouched({ onlySelf: true }); });
if (this._parent && !opts.onlySelf) {
this._parent._updateTouched(opts);
}
};
/**
* Marks the control as `dirty`. A control becomes dirty when
* the control's value is changed through the UI; compare `markAsTouched`.
*
* @param opts Configuration options that determine how the control propagates changes
* and emits events after marking is applied.
* * `onlySelf`: When true, mark only this control. When false or not supplied,
* marks all direct ancestors. Default is false.
*/
AbstractControl.prototype.markAsDirty = function (opts) {
if (opts === void 0) { opts = {}; }
this.pristine = false;
if (this._parent && !opts.onlySelf) {
this._parent.markAsDirty(opts);
}
};
/**
* Marks the control as `pristine`.
*
* If the control has any children, marks all children as `pristine`,
* and recalculates the `pristine` status of all parent
* controls.
*
* @param opts Configuration options that determine how the control emits events after
* marking is applied.
* * `onlySelf`: When true, mark only this control. When false or not supplied,
* marks all direct ancestors. Default is false..
*/
AbstractControl.prototype.markAsPristine = function (opts) {
if (opts === void 0) { opts = {}; }
this.pristine = true;
this._pendingDirty = false;
this._forEachChild(function (control) { control.markAsPristine({ onlySelf: true }); });
if (this._parent && !opts.onlySelf) {
this._parent._updatePristine(opts);
}
};
/**
* Marks the control as `pending`.
*
* A control is pending while the control performs async validation.
*
* @param opts Configuration options that determine how the control propagates changes and
* emits events after marking is applied.
* * `onlySelf`: When true, mark only this control. When false or not supplied,
* marks all direct ancestors. Default is false..
* * `emitEvent`: When true or not supplied (the default), the `statusChanges`
* observable emits an event with the latest status the control is marked pending.
* When false, no events are emitted.
*
*/
AbstractControl.prototype.markAsPending = function (opts) {
if (opts === void 0) { opts = {}; }
this.status = PENDING;
if (opts.emitEvent !== false) {
this.statusChanges.emit(this.status);
}
if (this._parent && !opts.onlySelf) {
this._parent.markAsPending(opts);
}
};
/**
* Disables the control. This means the control is exempt from validation checks and
* excluded from the aggregate value of any parent. Its status is `DISABLED`.
*
* If the control has children, all children are also disabled.
*
* @param opts Configuration options that determine how the control propagates
* changes and emits events after the control is disabled.
* * `onlySelf`: When true, mark only this control. When false or not supplied,
* marks all direct ancestors. Default is false..
* * `emitEvent`: When true or not supplied (the default), both the `statusChanges` and
* `valueChanges`
* observables emit events with the latest status and value when the control is disabled.
* When false, no events are emitted.
*/
AbstractControl.prototype.disable = function (opts) {
if (opts === void 0) { opts = {}; }
this.status = DISABLED;
this.errors = null;
this._forEachChild(function (control) { control.disable(__assign({}, opts, { onlySelf: true })); });
this._updateValue();
if (opts.emitEvent !== false) {
this.valueChanges.emit(this.value);
this.statusChanges.emit(this.status);
}
this._updateAncestors(opts);
this._onDisabledChange.forEach(function (changeFn) { return changeFn(true); });
};
/**
* Enables the control. This means the control is included in validation checks and
* the aggregate value of its parent. Its status recalculates based on its value and
* its validators.
*
* By default, if the control has children, all children are enabled.
*
* @param opts Configure options that control how the control propagates changes and
* emits events when marked as untouched
* * `onlySelf`: When true, mark only this control. When false or not supplied,
* marks all direct ancestors. Default is false..
* * `emitEvent`: When true or not supplied (the default), both the `statusChanges` and
* `valueChanges`
* observables emit events with the latest status and value when the control is enabled.
* When false, no events are emitted.
*/
AbstractControl.prototype.enable = function (opts) {
if (opts === void 0) { opts = {}; }
this.status = VALID;
this._forEachChild(function (control) { control.enable(__assign({}, opts, { onlySelf: true })); });
this.updateValueAndValidity({ onlySelf: true, emitEvent: opts.emitEvent });
this._updateAncestors(opts);
this._onDisabledChange.forEach(function (changeFn) { return changeFn(false); });
};
AbstractControl.prototype._updateAncestors = function (opts) {
if (this._parent && !opts.onlySelf) {
this._parent.updateValueAndValidity(opts);
this._parent._updatePristine();
this._parent._updateTouched();
}
};
/**
* @param parent Sets the parent of the control
*/
AbstractControl.prototype.setParent = function (parent) { this._parent = parent; };
/**
* Recalculates the value and validation status of the control.
*
* By default, it also updates the value and validity of its ancestors.
*
* @param opts Configuration options determine how the control propagates changes and emits events
* after updates and validity checks are applied.
* * `onlySelf`: When true, only update this control. When false or not supplied,
* update all direct ancestors. Default is false..
* * `emitEvent`: When true or not supplied (the default), both the `statusChanges` and
* `valueChanges`
* observables emit events with the latest status and value when the control is updated.
* When false, no events are emitted.
*/
AbstractControl.prototype.updateValueAndValidity = function (opts) {
if (opts === void 0) { opts = {}; }
this._setInitialStatus();
this._updateValue();
if (this.enabled) {
this._cancelExistingSubscription();
this.errors = this._runValidator();
this.status = this._calculateStatus();
if (this.status === VALID || this.status === PENDING) {
this._runAsyncValidator(opts.emitEvent);
}
}
if (opts.emitEvent !== false) {
this.valueChanges.emit(this.value);
this.statusChanges.emit(this.status);
}
if (this._parent && !opts.onlySelf) {
this._parent.updateValueAndValidity(opts);
}
};
/** @internal */
AbstractControl.prototype._updateTreeValidity = function (opts) {
if (opts === void 0) { opts = { emitEvent: true }; }
this._forEachChild(function (ctrl) { return ctrl._updateTreeValidity(opts); });
this.updateValueAndValidity({ onlySelf: true, emitEvent: opts.emitEvent });
};
AbstractControl.prototype._setInitialStatus = function () {
this.status = this._allControlsDisabled() ? DISABLED : VALID;
};
AbstractControl.prototype._runValidator = function () {
return this.validator ? this.validator(this) : null;
};
AbstractControl.prototype._runAsyncValidator = function (emitEvent) {
var _this = this;
if (this.asyncValidator) {
this.status = PENDING;
var obs = toObservable(this.asyncValidator(this));
this._asyncValidationSubscription =
obs.subscribe(function (errors) { return _this.setErrors(errors, { emitEvent: emitEvent }); });
}
};
AbstractControl.prototype._cancelExistingSubscription = function () {
if (this._asyncValidationSubscription) {
this._asyncValidationSubscription.unsubscribe();
}
};
/**
* Sets errors on a form control when running validations manually, rather than automatically.
*
* Calling `setErrors` also updates the validity of the parent control.
*
* @usageNotes
* ### Manually set the errors for a control
*
* ```
* const login = new FormControl('someLogin');
* login.setErrors({
* notUnique: true
* });
*
* expect(login.valid).toEqual(false);
* expect(login.errors).toEqual({ notUnique: true });
*
* login.setValue('someOtherLogin');
*
* expect(login.valid).toEqual(true);
* ```
*/
AbstractControl.prototype.setErrors = function (errors, opts) {
if (opts === void 0) { opts = {}; }
this.errors = errors;
this._updateControlsErrors(opts.emitEvent !== false);
};
/**
* Retrieves a child control given the control's name or path.
*
* @param path A dot-delimited string or array of string/number values that define the path to the
* control.
*
* @usageNotes
* ### Retrieve a nested control
*
* For example, to get a `name` control nested within a `person` sub-group:
*
* * `this.form.get('person.name');`
*
* -OR-
*
* * `this.form.get(['person', 'name']);`
*/
AbstractControl.prototype.get = function (path) { return _find(this, path, '.'); };
/**
* Reports error data for a specific error occurring in this control or in another control.
*
* @param errorCode The error code for which to retrieve data
* @param path The path to a control to check. If not supplied, checks for the error in this
* control.
*
* @returns The error data if the control with the given path has the given error, otherwise null
* or undefined.
*/
AbstractControl.prototype.getError = function (errorCode, path) {
var control = path ? this.get(path) : this;
return control && control.errors ? control.errors[errorCode] : null;
};
/**
* Reports whether the control with the given path has the error specified.
*
* @param errorCode The error code for which to retrieve data
* @param path The path to a control to check. If not supplied, checks for the error in this
* control.
* @returns True when the control with the given path has the error, otherwise false.
*/
AbstractControl.prototype.hasError = function (errorCode, path) { return !!this.getError(errorCode, path); };
Object.defineProperty(AbstractControl.prototype, "root", {
/**
* Retrieves the top-level ancestor of this control.
*/
get: function () {
var x = this;
while (x._parent) {
x = x._parent;
}
return x;
},
enumerable: true,
configurable: true
});
/** @internal */
AbstractControl.prototype._updateControlsErrors = function (emitEvent) {
this.status = this._calculateStatus();
if (emitEvent) {
this.statusChanges.emit(this.status);
}
if (this._parent) {
this._parent._updateControlsErrors(emitEvent);
}
};
/** @internal */
AbstractControl.prototype._initObservables = function () {
this.valueChanges = new EventEmitter();
this.statusChanges = new EventEmitter();
};
AbstractControl.prototype._calculateStatus = function () {
if (this._allControlsDisabled())
return DISABLED;
if (this.errors)
return INVALID;
if (this._anyControlsHaveStatus(PENDING))
return PENDING;
if (this._anyControlsHaveStatus(INVALID))
return INVALID;
return VALID;
};
/** @internal */
AbstractControl.prototype._anyControlsHaveStatus = function (status) {
return this._anyControls(function (control) { return control.status === status; });
};
/** @internal */
AbstractControl.prototype._anyControlsDirty = function () {
return this._anyControls(function (control) { return control.dirty; });
};
/** @internal */
AbstractControl.prototype._anyControlsTouched = function () {
return this._anyControls(function (control) { return control.touched; });
};
/** @internal */
AbstractControl.prototype._updatePristine = function (opts) {
if (opts === void 0) { opts = {}; }
this.pristine = !this._anyControlsDirty();
if (this._parent && !opts.onlySelf) {
this._parent._updatePristine(opts);
}
};
/** @internal */
AbstractControl.prototype._updateTouched = function (opts) {
if (opts === void 0) { opts = {}; }
this.touched = this._anyControlsTouched();
if (this._parent && !opts.onlySelf) {
this._parent._updateTouched(opts);
}
};
/** @internal */
AbstractControl.prototype._isBoxedValue = function (formState) {
return typeof formState === 'object' && formState !== null &&
Object.keys(formState).length === 2 && 'value' in formState && 'disabled' in formState;
};
/** @internal */
AbstractControl.prototype._registerOnCollectionChange = function (fn) { this._onCollectionChange = fn; };
/** @internal */
AbstractControl.prototype._setUpdateStrategy = function (opts) {
if (isOptionsObj(opts) && opts.updateOn != null) {
this._updateOn = opts.updateOn;
}
};
return AbstractControl;
}());
/**
* Tracks the value and validation status of an individual form control.
*
* This is one of the three fundamental building blocks of Angular forms, along with
* `FormGroup` and `FormArray`. It extends the `AbstractControl` class that
* implements most of the base functionality for accessing the value, validation status,
* user interactions and events.
*
* @see `AbstractControl`
* @see [Reactive Forms Guide](guide/reactive-forms)
* @see [Usage Notes](#usage-notes)
*
* @usageNotes
*
* ### Initializing Form Controls
*
* Instantiate a `FormControl`, with an initial value.
*
* ```ts
* const control = new FormControl('some value');
* console.log(control.value); // 'some value'
*```
*
* The following example initializes the control with a form state object. The `value`
* and `disabled` keys are required in this case.
*
* ```ts
* const control = new FormControl({ value: 'n/a', disabled: true });
* console.log(control.value); // 'n/a'
* console.log(control.status); // 'DISABLED'
* ```
*
* The following example initializes the control with a sync validator.
*
* ```ts
* const control = new FormControl('', Validators.required);
* console.log(control.value); // ''
* console.log(control.status); // 'INVALID'
* ```
*
* The following example initializes the control using an options object.
*
* ```ts
* const control = new FormControl('', {
* validators: Validators.required,
* asyncValidators: myAsyncValidator
* });
* ```
*
* ### Configure the control to update on a blur event
*
* Set the `updateOn` option to `'blur'` to update on the blur `event`.
*
* ```ts
* const control = new FormControl('', { updateOn: 'blur' });
* ```
*
* ### Configure the control to update on a submit event
*
* Set the `updateOn` option to `'submit'` to update on a submit `event`.
*
* ```ts
* const control = new FormControl('', { updateOn: 'submit' });
* ```
*
* ### Reset the control back to an initial value
*
* You reset to a specific form state by passing through a standalone
* value or a form state object that contains both a value and a disabled state
* (these are the only two properties that cannot be calculated).
*
* ```ts
* const control = new FormControl('Nancy');
*
* console.log(control.value); // 'Nancy'
*
* control.reset('Drew');
*
* console.log(control.value); // 'Drew'
* ```
*
* ### Reset the control back to an initial value and disabled
*
* ```
* const control = new FormControl('Nancy');
*
* console.log(control.value); // 'Nancy'
* console.log(control.status); // 'VALID'
*
* control.reset({ value: 'Drew', disabled: true });
*
* console.log(control.value); // 'Drew'
* console.log(control.status); // 'DISABLED'
* ```
*
* @publicApi
*/
var FormControl = /** @class */ (function (_super) {
__extends(FormControl, _super);
/**
* Creates a new `FormControl` instance.
*
* @param formState Initializes the control with an initial value,
* or an object that defines the initial value and disabled state.
*
* @param validatorOrOpts A synchronous validator function, or an array of
* such functions, or an `AbstractControlOptions` object that contains validation functions
* and a validation trigger.
*
* @param asyncValidator A single async validator or array of async validator functions
*
*/
function FormControl(formState, validatorOrOpts, asyncValidator) {
if (formState === void 0) { formState = null; }
var _this = _super.call(this, coerceToValidator(validatorOrOpts), coerceToAsyncValidator(asyncValidator, validatorOrOpts)) || this;
/** @internal */
_this._onChange = [];
_this._applyFormState(formState);
_this._setUpdateStrategy(validatorOrOpts);
_this.updateValueAndValidity({ onlySelf: true, emitEvent: false });
_this._initObservables();
return _this;
}
/**
* Sets a new value for the form control.
*
* @param value The new value for the control.
* @param options Configuration options that determine how the control proopagates changes
* and emits events when the value changes.
* The configuration options are passed to the {@link AbstractControl#updateValueAndValidity
* updateValueAndValidity} method.
*
* * `onlySelf`: When true, each change only affects this control, and not its parent. Default is
* false.
* * `emitEvent`: When true or not supplied (the default), both the `statusChanges` and
* `valueChanges`
* observables emit events with the latest status and value when the control value is updated.
* When false, no events are emitted.
* * `emitModelToViewChange`: When true or not supplied (the default), each change triggers an
* `onChange` event to
* update the view.
* * `emitViewToModelChange`: When true or not supplied (the default), each change triggers an
* `ngModelChange`
* event to update the model.
*
*/
FormControl.prototype.setValue = function (value, options) {
var _this = this;
if (options === void 0) { options = {}; }
this.value = this._pendingValue = value;
if (this._onChange.length && options.emitModelToViewChange !== false) {
this._onChange.forEach(function (changeFn) { return changeFn(_this.value, options.emitViewToModelChange !== false); });
}
this.updateValueAndValidity(options);
};
/**
* Patches the value of a control.
*
* This function is functionally the same as {@link FormControl#setValue setValue} at this level.
* It exists for symmetry with {@link FormGroup#patchValue patchValue} on `FormGroups` and
* `FormArrays`, where it does behave differently.
*
* @see `setValue` for options
*/
FormControl.prototype.patchValue = function (value, options) {
if (options === void 0) { options = {}; }
this.setValue(value, options);
};
/**
* Resets the form control, marking it `pristine` and `untouched`, and setting
* the value to null.
*
* @param formState Resets the control with an initial value,
* or an object that defines the initial value and disabled state.
*
* @param options Configuration options that determine how the control propagates changes
* and emits events after the value changes.
*
* * `onlySelf`: When true, each change only affects this control, and not its parent. Default is
* false.
* * `emitEvent`: When true or not supplied (the default), both the `statusChanges` and
* `valueChanges`
* observables emit events with the latest status and value when the control is reset.
* When false, no events are emitted.
*
*/
FormControl.prototype.reset = function (formState, options) {
if (formState === void 0) { formState = null; }
if (options === void 0) { options = {}; }
this._applyFormState(formState);
this.markAsPristine(options);
this.markAsUntouched(options);
this.setValue(this.value, options);
this._pendingChange = false;
};
/**
* @internal
*/
FormControl.prototype._updateValue = function () { };
/**
* @internal
*/
FormControl.prototype._anyControls = function (condition) { return false; };
/**
* @internal
*/
FormControl.prototype._allControlsDisabled = function () { return this.disabled; };
/**
* Register a listener for change events.
*
* @param fn The method that is called when the value changes
*/
FormControl.prototype.registerOnChange = function (fn) { this._onChange.push(fn); };
/**
* @internal
*/
FormControl.prototype._clearChangeFns = function () {
this._onChange = [];
this._onDisabledChange = [];
this._onCollectionChange = function () { };
};
/**
* Register a listener for disabled events.
*
* @param fn The method that is called when the disabled status changes.
*/
FormControl.prototype.registerOnDisabledChange = function (fn) {
this._onDisabledChange.push(fn);
};
/**
* @internal
*/
FormControl.prototype._forEachChild = function (cb) { };
/** @internal */
FormControl.prototype._syncPendingControls = function () {
if (this.updateOn === 'submit') {
if (this._pendingDirty)
this.markAsDirty();
if (this._pendingTouched)
this.markAsTouched();
if (this._pendingChange) {
this.setValue(this._pendingValue, { onlySelf: true, emitModelToViewChange: false });
return true;
}
}
return false;
};
FormControl.prototype._applyFormState = function (formState) {
if (this._isBoxedValue(formState)) {
this.value = this._pendingValue = formState.value;
formState.disabled ? this.disable({ onlySelf: true, emitEvent: false }) :
this.enable({ onlySelf: true, emitEvent: false });
}
else {
this.value = this._pendingValue = formState;
}
};
return FormControl;
}(AbstractControl));
/**
* Tracks the value and validity state of a group of `FormControl` instances.
*
* A `FormGroup` aggregates the values of each child `FormControl` into one object,
* with each control name as the key. It calculates its status by reducing the status values
* of its children. For example, if one of the controls in a group is invalid, the entire
* group becomes invalid.
*
* `FormGroup` is one of the three fundamental building blocks used to define forms in Angular,
* along with `FormControl` and `FormArray`.
*
* When instantiating a `FormGroup`, pass in a collection of child controls as the first
* argument. The key for each child registers the name for the control.
*
* @usageNotes
*
* ### Create a form group with 2 controls
*
* ```
* const form = new FormGroup({
* first: new FormControl('Nancy', Validators.minLength(2)),
* last: new FormControl('Drew'),
* });
*
* console.log(form.value); // {first: 'Nancy', last; 'Drew'}
* console.log(form.status); // 'VALID'
* ```
*
* ### Create a form group with a group-level validator
*
* You include group-level validators as the second arg, or group-level async
* validators as the third arg. These come in handy when you want to perform validation
* that considers the value of more than one child control.
*
* ```
* const form = new FormGroup({
* password: new FormControl('', Validators.minLength(2)),
* passwordConfirm: new FormControl('', Validators.minLength(2)),
* }, passwordMatchValidator);
*
*
* function passwordMatchValidator(g: FormGroup) {
* return g.get('password').value === g.get('passwordConfirm').value
* ? null : {'mismatch': true};
* }
* ```
*
* Like `FormControl` instances, you choose to pass in
* validators and async validators as part of an options object.
*
* ```
* const form = new FormGroup({
* password: new FormControl('')
* passwordConfirm: new FormControl('')
* }, { validators: passwordMatchValidator, asyncValidators: otherValidator });
* ```
*
* ### Set the updateOn property for all controls in a form group
*
* The options object is used to set a default value for each child
* control's `updateOn` property. If you set `updateOn` to `'blur'` at the
* group level, all child controls default to 'blur', unless the child
* has explicitly specified a different `updateOn` value.
*
* ```ts
* const c = new FormGroup({
* one: new FormControl()
* }, { updateOn: 'blur' });
* ```
*
* @publicApi
*/
var FormGroup = /** @class */ (function (_super) {
__extends(FormGroup, _super);
/**
* Creates a new `FormGroup` instance.
*
* @param controls A collection of child controls. The key for each child is the name
* under which it is registered.
*
* @param validatorOrOpts A synchronous validator function, or an array of
* such functions, or an `AbstractControlOptions` object that contains validation functions
* and a validation trigger.
*
* @param asyncValidator A single async validator or array of async validator functions
*
*/
function FormGroup(controls, validatorOrOpts, asyncValidator) {
var _this = _super.call(this, coerceToValidator(validatorOrOpts), coerceToAsyncValidator(asyncValidator, validatorOrOpts)) || this;
_this.controls = controls;
_this._initObservables();
_this._setUpdateStrategy(validatorOrOpts);
_this._setUpControls();
_this.updateValueAndValidity({ onlySelf: true, emitEvent: false });
return _this;
}
/**
* Registers a control with the group's list of controls.
*
* This method does not update the value or validity of the control.
* Use {@link FormGroup#addControl addControl} instead.
*
* @param name The control name to register in the collection
* @param control Provides the control for the given name
*/
FormGroup.prototype.registerControl = function (name, control) {
if (this.controls[name])
return this.controls[name];
this.controls[name] = control;
control.setParent(this);
control._registerOnCollectionChange(this._onCollectionChange);
return control;
};
/**
* Add a control to this group.
*
* This method also updates the value and validity of the control.
*
* @param name The control name to add to the collection
* @param control Provides the control for the given name
*/
FormGroup.prototype.addControl = function (name, control) {
this.registerControl(name, control);
this.updateValueAndValidity();
this._onCollectionChange();
};
/**
* Remove a control from this group.
*
* @param name The control name to remove from the collection
*/
FormGroup.prototype.removeControl = function (name) {
if (this.controls[name])
this.controls[name]._registerOnCollectionChange(function () { });
delete (this.controls[name]);
this.updateValueAndValidity();
this._onCollectionChange();
};
/**
* Replace an existing control.
*
* @param name The control name to replace in the collection
* @param control Provides the control for the given name
*/
FormGroup.prototype.setControl = function (name, control) {
if (this.controls[name])
this.controls[name]._registerOnCollectionChange(function () { });
delete (this.controls[name]);
if (control)
this.registerControl(name, control);
this.updateValueAndValidity();
this._onCollectionChange();
};
/**
* Check whether there is an enabled control with the given name in the group.
*
* Reports false for disabled controls. If you'd like to check for existence in the group
* only, use {@link AbstractControl#get get} instead.
*
* @param name The control name to check for existence in the collection
*
* @returns false for disabled controls, true otherwise.
*/
FormGroup.prototype.contains = function (controlName) {
return this.controls.hasOwnProperty(controlName) && this.controls[controlName].enabled;
};
/**
* Sets the value of the `FormGroup`. It accepts an object that matches
* the structure of the group, with control names as keys.
*
* @usageNotes
* ### Set the complete value for the form group
*
* ```
* const form = new FormGroup({
* first: new FormControl(),
* last: new FormControl()
* });
*
* console.log(form.value); // {first: null, last: null}
*
* form.setValue({first: 'Nancy', last: 'Drew'});
* console.log(form.value); // {first: 'Nancy', last: 'Drew'}
* ```
*
* @throws When strict checks fail, such as setting the value of a control
* that doesn't exist or if you excluding the value of a control.
*
* @param value The new value for the control that matches the structure of the group.
* @param options Configuration options that determine how the control propagates changes
* and emits events after the value changes.
* The configuration options are passed to the {@link AbstractControl#updateValueAndValidity
* updateValueAndValidity} method.
*
* * `onlySelf`: When true, each change only affects this control, and not its parent. Default is
* false.
* * `emitEvent`: When true or not supplied (the default), both the `statusChanges` and
* `valueChanges`
* observables emit events with the latest status and value when the control value is updated.
* When false, no events are emitted.
*/
FormGroup.prototype.setValue = function (value, options) {
var _this = this;
if (options === void 0) { options = {}; }
this._checkAllValuesPresent(value);
Object.keys(value).forEach(function (name) {
_this._throwIfControlMissing(name);
_this.controls[name].setValue(value[name], { onlySelf: true, emitEvent: options.emitEvent });
});
this.updateValueAndValidity(options);
};
/**
* Patches the value of the `FormGroup`. It accepts an object with control
* names as keys, and does its best to match the values to the correct controls
* in the group.
*
* It accepts both super-sets and sub-sets of the group without throwing an error.
*
* @usageNotes
* ### Patch the value for a form group
*
* ```
* const form = new FormGroup({
* first: new FormControl(),
* last: new FormControl()
* });
* console.log(form.value); // {first: null, last: null}
*
* form.patchValue({first: 'Nancy'});
* console.log(form.value); // {first: 'Nancy', last: null}
* ```
*
* @param value The object that matches the structure of the group.
* @param options Configuration options that determine how the control propagates changes and
* emits events after the value is patched.
* * `onlySelf`: When true, each change only affects this control and not its parent. Default is
* true.
* * `emitEvent`: When true or not supplied (the default), both the `statusChanges` and
* `valueChanges`
* observables emit events with the latest status and value when the control value is updated.
* When false, no events are emitted.
* The configuration options are passed to the {@link AbstractControl#updateValueAndValidity
* updateValueAndValidity} method.
*/
FormGroup.prototype.patchValue = function (value, options) {
var _this = this;
if (options === void 0) { options = {}; }
Object.keys(value).forEach(function (name) {
if (_this.controls[name]) {
_this.controls[name].patchValue(value[name], { onlySelf: true, emitEvent: options.emitEvent });
}
});
this.updateValueAndValidity(options);
};
/**
* Resets the `FormGroup`, marks all descendants are marked `pristine` and `untouched`, and
* the value of all descendants to null.
*
* You reset to a specific form state by passing in a map of states
* that matches the structure of your form, with control names as keys. The state
* is a standalone value or a form state object with both a value and a disabled
* status.
*
* @param formState Resets the control with an initial value,
* or an object that defines the initial value and disabled state.
*
* @param options Configuration options that determine how the control propagates changes
* and emits events when the group is reset.
* * `onlySelf`: When true, each change only affects this control, and not its parent. Default is
* false.
* * `emitEvent`: When true or not supplied (the default), both the `statusChanges` and
* `valueChanges`
* observables emit events with the latest status and value when the control is reset.
* When false, no events are emitted.
* The configuration options are passed to the {@link AbstractControl#updateValueAndValidity
* updateValueAndValidity} method.
*
* @usageNotes
*
* ### Reset the form group values
*
* ```ts
* const form = new FormGroup({
* first: new FormControl('first name'),
* last: new FormControl('last name')
* });
*
* console.log(form.value); // {first: 'first name', last: 'last name'}
*
* form.reset({ first: 'name', last: 'last name' });
*
* console.log(form.value); // {first: 'name', last: 'last name'}
* ```
*
* ### Reset the form group values and disabled status
*
* ```
* const form = new FormGroup({
* first: new FormControl('first name'),
* last: new FormControl('last name')
* });
*
* form.reset({
* first: {value: 'name', disabled: true},
* last: 'last'
* });
*
* console.log(this.form.value); // {first: 'name', last: 'last name'}
* console.log(this.form.get('first').status); // 'DISABLED'
* ```
*/
FormGroup.prototype.reset = function (value, options) {
if (value === void 0) { value = {}; }
if (options === void 0) { options = {}; }
this._forEachChild(function (control, name) {
control.reset(value[name], { onlySelf: true, emitEvent: options.emitEvent });
});
this.updateValueAndValidity(options);
this._updatePristine(options);
this._updateTouched(options);
};
/**
* The aggregate value of the `FormGroup`, including any disabled controls.
*
* Retrieves all values regardless of disabled status.
* The `value` property is the best way to get the value of the group, because
* it excludes disabled controls in the `FormGroup`.
*/
FormGroup.prototype.getRawValue = function () {
return this._reduceChildren({}, function (acc, control, name) {
acc[name] = control instanceof FormControl ? control.value : control.getRawValue();
return acc;
});
};
/** @internal */
FormGroup.prototype._syncPendingControls = function () {
var subtreeUpdated = this._reduceChildren(false, function (updated, child) {
return child._syncPendingControls() ? true : updated;
});
if (subtreeUpdated)
this.updateValueAndValidity({ onlySelf: true });
return subtreeUpdated;
};
/** @internal */
FormGroup.prototype._throwIfControlMissing = function (name) {
if (!Object.keys(this.controls).length) {
throw new Error("\n There are no form controls registered with this group yet. If you're using ngModel,\n you may want to check next tick (e.g. use setTimeout).\n ");
}
if (!this.controls[name]) {
throw new Error("Cannot find form control with name: " + name + ".");
}
};
/** @internal */
FormGroup.prototype._forEachChild = function (cb) {
var _this = this;
Object.keys(this.controls).forEach(function (k) { return cb(_this.controls[k], k); });
};
/** @internal */
FormGroup.prototype._setUpControls = function () {
var _this = this;
this._forEachChild(function (control) {
control.setParent(_this);
control._registerOnCollectionChange(_this._onCollectionChange);
});
};
/** @internal */
FormGroup.prototype._updateValue = function () { this.value = this._reduceValue(); };
/** @internal */
FormGroup.prototype._anyControls = function (condition) {
var _this = this;
var res = false;
this._forEachChild(function (control, name) {
res = res || (_this.contains(name) && condition(control));
});
return res;
};
/** @internal */
FormGroup.prototype._reduceValue = function () {
var _this = this;
return this._reduceChildren({}, function (acc, control, name) {
if (control.enabled || _this.disabled) {
acc[name] = control.value;
}
return acc;
});
};
/** @internal */
FormGroup.prototype._reduceChildren = function (initValue, fn) {
var res = initValue;
this._forEachChild(function (control, name) { res = fn(res, control, name); });
return res;
};
/** @internal */
FormGroup.prototype._allControlsDisabled = function () {
var e_1, _a;
try {
for (var _b = __values(Object.keys(this.controls)), _c = _b.next(); !_c.done; _c = _b.next()) {
var controlName = _c.value;
if (this.controls[controlName].enabled) {
return false;
}
}
}
catch (e_1_1) { e_1 = { error: e_1_1 }; }
finally {
try {
if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
}
finally { if (e_1) throw e_1.error; }
}
return Object.keys(this.controls).length > 0 || this.disabled;
};
/** @internal */
FormGroup.prototype._checkAllValuesPresent = function (value) {
this._forEachChild(function (control, name) {
if (value[name] === undefined) {
throw new Error("Must supply a value for form control with name: '" + name + "'.");
}
});
};
return FormGroup;
}(AbstractControl));
/**
* Tracks the value and validity state of an array of `FormControl`,
* `FormGroup` or `FormArray` instances.
*
* A `FormArray` aggregates the values of each child `FormControl` into an array.
* It calculates its status by reducing the status values of its children. For example, if one of
* the controls in a `FormArray` is invalid, the entire array becomes invalid.
*
* `FormArray` is one of the three fundamental building blocks used to define forms in Angular,
* along with `FormControl` and `FormGroup`.
*
* @usageNotes
*
* ### Create an array of form controls
*
* ```
* const arr = new FormArray([
* new FormControl('Nancy', Validators.minLength(2)),
* new FormControl('Drew'),
* ]);
*
* console.log(arr.value); // ['Nancy', 'Drew']
* console.log(arr.status); // 'VALID'
* ```
*
* ### Create a form array with array-level validators
*
* You include array-level validators and async validators. These come in handy
* when you want to perform validation that considers the value of more than one child
* control.
*
* The two types of validators are passed in separately as the second and third arg
* respectively, or together as part of an options object.
*
* ```
* const arr = new FormArray([
* new FormControl('Nancy'),
* new FormControl('Drew')
* ], {validators: myValidator, asyncValidators: myAsyncValidator});
* ```
*
* ### Set the updateOn property for all controls in a form array
*
* The options object is used to set a default value for each child
* control's `updateOn` property. If you set `updateOn` to `'blur'` at the
* array level, all child controls default to 'blur', unless the child
* has explicitly specified a different `updateOn` value.
*
* ```ts
* const arr = new FormArray([
* new FormControl()
* ], {updateOn: 'blur'});
* ```
*
* ### Adding or removing controls from a form array
*
* To change the controls in the array, use the `push`, `insert`, or `removeAt` methods
* in `FormArray` itself. These methods ensure the controls are properly tracked in the
* form's hierarchy. Do not modify the array of `AbstractControl`s used to instantiate
* the `FormArray` directly, as that result in strange and unexpected behavior such
* as broken change detection.
*
* @publicApi
*/
var FormArray = /** @class */ (function (_super) {
__extends(FormArray, _super);
/**
* Creates a new `FormArray` instance.
*
* @param controls An array of child controls. Each child control is given an index
* where it is registered.
*
* @param validatorOrOpts A synchronous validator function, or an array of
* such functions, or an `AbstractControlOptions` object that contains validation functions
* and a validation trigger.
*
* @param asyncValidator A single async validator or array of async validator functions
*
*/
function FormArray(controls, validatorOrOpts, asyncValidator) {
var _this = _super.call(this, coerceToValidator(validatorOrOpts), coerceToAsyncValidator(asyncValidator, validatorOrOpts)) || this;
_this.controls = controls;
_this._initObservables();
_this._setUpdateStrategy(validatorOrOpts);
_this._setUpControls();
_this.updateValueAndValidity({ onlySelf: true, emitEvent: false });
return _this;
}
/**
* Get the `AbstractControl` at the given `index` in the array.
*
* @param index Index in the array to retrieve the control
*/
FormArray.prototype.at = function (index) { return this.controls[index]; };
/**
* Insert a new `AbstractControl` at the end of the array.
*
* @param control Form control to be inserted
*/
FormArray.prototype.push = function (control) {
this.controls.push(control);
this._registerControl(control);
this.updateValueAndValidity();
this._onCollectionChange();
};
/**
* Insert a new `AbstractControl` at the given `index` in the array.
*
* @param index Index in the array to insert the control
* @param control Form control to be inserted
*/
FormArray.prototype.insert = function (index, control) {
this.controls.splice(index, 0, control);
this._registerControl(control);
this.updateValueAndValidity();
};
/**
* Remove the control at the given `index` in the array.
*
* @param index Index in the array to remove the control
*/
FormArray.prototype.removeAt = function (index) {
if (this.controls[index])
this.controls[index]._registerOnCollectionChange(function () { });
this.controls.splice(index, 1);
this.updateValueAndValidity();
};
/**
* Replace an existing control.
*
* @param index Index in the array to replace the control
* @param control The `AbstractControl` control to replace the existing control
*/
FormArray.prototype.setControl = function (index, control) {
if (this.controls[index])
this.controls[index]._registerOnCollectionChange(function () { });
this.controls.splice(index, 1);
if (control) {
this.controls.splice(index, 0, control);
this._registerControl(control);
}
this.updateValueAndValidity();
this._onCollectionChange();
};
Object.defineProperty(FormArray.prototype, "length", {
/**
* Length of the control array.
*/
get: function () { return this.controls.length; },
enumerable: true,
configurable: true
});
/**
* Sets the value of the `FormArray`. It accepts an array that matches
* the structure of the control.
*
* This method performs strict checks, and throws an error if you try
* to set the value of a control that doesn't exist or if you exclude the
* value of a control.
*
* @usageNotes
* ### Set the values for the controls in the form array
*
* ```
* const arr = new FormArray([
* new FormControl(),
* new FormControl()
* ]);
* console.log(arr.value); // [null, null]
*
* arr.setValue(['Nancy', 'Drew']);
* console.log(arr.value); // ['Nancy', 'Drew']
* ```
*
* @param value Array of values for the controls
* @param options Configure options that determine how the control propagates changes and
* emits events after the value changes
*
* * `onlySelf`: When true, each change only affects this control, and not its parent. Default
* is false.
* * `emitEvent`: When true or not supplied (the default), both the `statusChanges` and
* `valueChanges`
* observables emit events with the latest status and value when the control value is updated.
* When false, no events are emitted.
* The configuration options are passed to the {@link AbstractControl#updateValueAndValidity
* updateValueAndValidity} method.
*/
FormArray.prototype.setValue = function (value, options) {
var _this = this;
if (options === void 0) { options = {}; }
this._checkAllValuesPresent(value);
value.forEach(function (newValue, index) {
_this._throwIfControlMissing(index);
_this.at(index).setValue(newValue, { onlySelf: true, emitEvent: options.emitEvent });
});
this.updateValueAndValidity(options);
};
/**
* Patches the value of the `FormArray`. It accepts an array that matches the
* structure of the control, and does its best to match the values to the correct
* controls in the group.
*
* It accepts both super-sets and sub-sets of the array without throwing an error.
*
* @usageNotes
* ### Patch the values for controls in a form array
*
* ```
* const arr = new FormArray([
* new FormControl(),
* new FormControl()
* ]);
* console.log(arr.value); // [null, null]
*
* arr.patchValue(['Nancy']);
* console.log(arr.value); // ['Nancy', null]
* ```
*
* @param value Array of latest values for the controls
* @param options Configure options that determine how the control propagates changes and
* emits events after the value changes
*
* * `onlySelf`: When true, each change only affects this control, and not its parent. Default
* is false.
* * `emitEvent`: When true or not supplied (the default), both the `statusChanges` and
* `valueChanges`
* observables emit events with the latest status and value when the control value is updated.
* When false, no events are emitted.
* The configuration options are passed to the {@link AbstractControl#updateValueAndValidity
* updateValueAndValidity} method.
*/
FormArray.prototype.patchValue = function (value, options) {
var _this = this;
if (options === void 0) { options = {}; }
value.forEach(function (newValue, index) {
if (_this.at(index)) {
_this.at(index).patchValue(newValue, { onlySelf: true, emitEvent: options.emitEvent });
}
});
this.updateValueAndValidity(options);
};
/**
* Resets the `FormArray` and all descendants are marked `pristine` and `untouched`, and the
* value of all descendants to null or null maps.
*
* You reset to a specific form state by passing in an array of states
* that matches the structure of the control. The state is a standalone value
* or a form state object with both a value and a disabled status.
*
* @usageNotes
* ### Reset the values in a form array
*
* ```ts
* const arr = new FormArray([
* new FormControl(),
* new FormControl()
* ]);
* arr.reset(['name', 'last name']);
*
* console.log(this.arr.value); // ['name', 'last name']
* ```
*
* ### Reset the values in a form array and the disabled status for the first control
*
* ```
* this.arr.reset([
* {value: 'name', disabled: true},
* 'last'
* ]);
*
* console.log(this.arr.value); // ['name', 'last name']
* console.log(this.arr.get(0).status); // 'DISABLED'
* ```
*
* @param value Array of values for the controls
* @param options Configure options that determine how the control propagates changes and
* emits events after the value changes
*
* * `onlySelf`: When true, each change only affects this control, and not its parent. Default
* is false.
* * `emitEvent`: When true or not supplied (the default), both the `statusChanges` and
* `valueChanges`
* observables emit events with the latest status and value when the control is reset.
* When false, no events are emitted.
* The configuration options are passed to the {@link AbstractControl#updateValueAndValidity
* updateValueAndValidity} method.
*/
FormArray.prototype.reset = function (value, options) {
if (value === void 0) { value = []; }
if (options === void 0) { options = {}; }
this._forEachChild(function (control, index) {
control.reset(value[index], { onlySelf: true, emitEvent: options.emitEvent });
});
this.updateValueAndValidity(options);
this._updatePristine(options);
this._updateTouched(options);
};
/**
* The aggregate value of the array, including any disabled controls.
*
* Reports all values regardless of disabled status.
* For enabled controls only, the `value` property is the best way to get the value of the array.
*/
FormArray.prototype.getRawValue = function () {
return this.controls.map(function (control) {
return control instanceof FormControl ? control.value : control.getRawValue();
});
};
/** @internal */
FormArray.prototype._syncPendingControls = function () {
var subtreeUpdated = this.controls.reduce(function (updated, child) {
return child._syncPendingControls() ? true : updated;
}, false);
if (subtreeUpdated)
this.updateValueAndValidity({ onlySelf: true });
return subtreeUpdated;
};
/** @internal */
FormArray.prototype._throwIfControlMissing = function (index) {
if (!this.controls.length) {
throw new Error("\n There are no form controls registered with this array yet. If you're using ngModel,\n you may want to check next tick (e.g. use setTimeout).\n ");
}
if (!this.at(index)) {
throw new Error("Cannot find form control at index " + index);
}
};
/** @internal */
FormArray.prototype._forEachChild = function (cb) {
this.controls.forEach(function (control, index) { cb(control, index); });
};
/** @internal */
FormArray.prototype._updateValue = function () {
var _this = this;
this.value =
this.controls.filter(function (control) { return control.enabled || _this.disabled; })
.map(function (control) { return control.value; });
};
/** @internal */
FormArray.prototype._anyControls = function (condition) {
return this.controls.some(function (control) { return control.enabled && condition(control); });
};
/** @internal */
FormArray.prototype._setUpControls = function () {
var _this = this;
this._forEachChild(function (control) { return _this._registerControl(control); });
};
/** @internal */
FormArray.prototype._checkAllValuesPresent = function (value) {
this._forEachChild(function (control, i) {
if (value[i] === undefined) {
throw new Error("Must supply a value for form control at index: " + i + ".");
}
});
};
/** @internal */
FormArray.prototype._allControlsDisabled = function () {
var e_2, _a;
try {
for (var _b = __values(this.controls), _c = _b.next(); !_c.done; _c = _b.next()) {
var control = _c.value;
if (control.enabled)
return false;
}
}
catch (e_2_1) { e_2 = { error: e_2_1 }; }
finally {
try {
if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
}
finally { if (e_2) throw e_2.error; }
}
return this.controls.length > 0 || this.disabled;
};
FormArray.prototype._registerControl = function (control) {
control.setParent(this);
control._registerOnCollectionChange(this._onCollectionChange);
};
return FormArray;
}(AbstractControl));
/**
* @license
* Copyright Google Inc. 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
*/
var formDirectiveProvider = {
provide: ControlContainer,
useExisting: forwardRef(function () { return NgForm; })
};
var resolvedPromise = Promise.resolve(null);
/**
* @description
* Creates a top-level `FormGroup` instance and binds it to a form
* to track aggregate form value and validation status.
*
* As soon as you import the `FormsModule`, this directive becomes active by default on
* all `<form>` tags. You don't need to add a special selector.
*
* You optionally export the directive into a local template variable using `ngForm` as the key
* (ex: `#myForm="ngForm"`). This is optional, but useful. Many properties from the underlying
* `FormGroup` instance are duplicated on the directive itself, so a reference to it
* gives you access to the aggregate value and validity status of the form, as well as
* user interaction properties like `dirty` and `touched`.
*
* To register child controls with the form, use `NgModel` with a `name`
* attribute. You may use `NgModelGroup` to create sub-groups within the form.
*
* If necessary, listen to the directive's `ngSubmit` event to be notified when the user has
* triggered a form submission. The `ngSubmit` event emits the original form
* submission event.
*
* In template driven forms, all `<form>` tags are automatically tagged as `NgForm`.
* To import the `FormsModule` but skip its usage in some forms,
* for example, to use native HTML5 validation, add the `ngNoForm` and the `<form>`
* tags won't create an `NgForm` directive. In reactive forms, using `ngNoForm` is
* unnecessary because the `<form>` tags are inert. In that case, you would
* refrain from using the `formGroup` directive.
*
* @usageNotes
*
* ### Migrating from deprecated ngForm selector
*
* Support for using `ngForm` element selector has been deprecated in Angular v6 and will be removed
* in Angular v9.
*
* This has been deprecated to keep selectors consistent with other core Angular selectors,
* as element selectors are typically written in kebab-case.
*
* Now deprecated:
* ```html
* <ngForm #myForm="ngForm">
* ```
*
* After:
* ```html
* <ng-form #myForm="ngForm">
* ```
*
* ### Listening for form submission
*
* The following example shows how to capture the form values from the "ngSubmit" event.
*
* {@example forms/ts/simpleForm/simple_form_example.ts region='Component'}
*
* ### Setting the update options
*
* The following example shows you how to change the "updateOn" option from its default using
* ngFormOptions.
*
* ```html
* <form [ngFormOptions]="{updateOn: 'blur'}">
* <input name="one" ngModel> <!-- this ngModel will update on blur -->
* </form>
* ```
*
* @ngModule FormsModule
* @publicApi
*/
var NgForm = /** @class */ (function (_super) {
__extends(NgForm, _super);
function NgForm(validators, asyncValidators) {
var _this = _super.call(this) || this;
/**
* @description
* Returns whether the form submission has been triggered.
*/
_this.submitted = false;
_this._directives = [];
/**
* @description
* Event emitter for the "ngSubmit" event
*/
_this.ngSubmit = new EventEmitter();
_this.form =
new FormGroup({}, composeValidators(validators), composeAsyncValidators(asyncValidators));
return _this;
}
/**
* @description
* Lifecycle method called after the view is initialized. For internal use only.
*/
NgForm.prototype.ngAfterViewInit = function () { this._setUpdateStrategy(); };
Object.defineProperty(NgForm.prototype, "formDirective", {
/**
* @description
* The directive instance.
*/
get: function () { return this; },
enumerable: true,
configurable: true
});
Object.defineProperty(NgForm.prototype, "control", {
/**
* @description
* The internal `FormGroup` instance.
*/
get: function () { return this.form; },
enumerable: true,
configurable: true
});
Object.defineProperty(NgForm.prototype, "path", {
/**
* @description
* Returns an array representing the path to this group. Because this directive
* always lives at the top level of a form, it is always an empty array.
*/
get: function () { return []; },
enumerable: true,
configurable: true
});
Object.defineProperty(NgForm.prototype, "controls", {
/**
* @description
* Returns a map of the controls in this group.
*/
get: function () { return this.form.controls; },
enumerable: true,
configurable: true
});
/**
* @description
* Method that sets up the control directive in this group, re-calculates its value
* and validity, and adds the instance to the internal list of directives.
*
* @param dir The `NgModel` directive instance.
*/
NgForm.prototype.addControl = function (dir) {
var _this = this;
resolvedPromise.then(function () {
var container = _this._findContainer(dir.path);
dir.control =
container.registerControl(dir.name, dir.control);
setUpControl(dir.control, dir);
dir.control.updateValueAndValidity({ emitEvent: false });
_this._directives.push(dir);
});
};
/**
* @description
* Retrieves the `FormControl` instance from the provided `NgModel` directive.
*
* @param dir The `NgModel` directive instance.
*/
NgForm.prototype.getControl = function (dir) { return this.form.get(dir.path); };
/**
* @description
* Removes the `NgModel` instance from the internal list of directives
*
* @param dir The `NgModel` directive instance.
*/
NgForm.prototype.removeControl = function (dir) {
var _this = this;
resolvedPromise.then(function () {
var container = _this._findContainer(dir.path);
if (container) {
container.removeControl(dir.name);
}
removeDir(_this._directives, dir);
});
};
/**
* @description
* Adds a new `NgModelGroup` directive instance to the form.
*
* @param dir The `NgModelGroup` directive instance.
*/
NgForm.prototype.addFormGroup = function (dir) {
var _this = this;
resolvedPromise.then(function () {
var container = _this._findContainer(dir.path);
var group = new FormGroup({});
setUpFormContainer(group, dir);
container.registerControl(dir.name, group);
group.updateValueAndValidity({ emitEvent: false });
});
};
/**
* @description
* Removes the `NgModelGroup` directive instance from the form.
*
* @param dir The `NgModelGroup` directive instance.
*/
NgForm.prototype.removeFormGroup = function (dir) {
var _this = this;
resolvedPromise.then(function () {
var container = _this._findContainer(dir.path);
if (container) {
container.removeControl(dir.name);
}
});
};
/**
* @description
* Retrieves the `FormGroup` for a provided `NgModelGroup` directive instance
*
* @param dir The `NgModelGroup` directive instance.
*/
NgForm.prototype.getFormGroup = function (dir) { return this.form.get(dir.path); };
/**
* Sets the new value for the provided `NgControl` directive.
*
* @param dir The `NgControl` directive instance.
* @param value The new value for the directive's control.
*/
NgForm.prototype.updateModel = function (dir, value) {
var _this = this;
resolvedPromise.then(function () {
var ctrl = _this.form.get(dir.path);
ctrl.setValue(value);
});
};
/**
* @description
* Sets the value for this `FormGroup`.
*
* @param value The new value
*/
NgForm.prototype.setValue = function (value) { this.control.setValue(value); };
/**
* @description
* Method called when the "submit" event is triggered on the form.
* Triggers the `ngSubmit` emitter to emit the "submit" event as its payload.
*
* @param $event The "submit" event object
*/
NgForm.prototype.onSubmit = function ($event) {
this.submitted = true;
syncPendingControls(this.form, this._directives);
this.ngSubmit.emit($event);
return false;
};
/**
* @description
* Method called when the "reset" event is triggered on the form.
*/
NgForm.prototype.onReset = function () { this.resetForm(); };
/**
* @description
* Resets the form to an initial value and resets its submitted status.
*
* @param value The new value for the form.
*/
NgForm.prototype.resetForm = function (value) {
if (value === void 0) { value = undefined; }
this.form.reset(value);
this.submitted = false;
};
NgForm.prototype._setUpdateStrategy = function () {
if (this.options && this.options.updateOn != null) {
this.form._updateOn = this.options.updateOn;
}
};
/** @internal */
NgForm.prototype._findContainer = function (path) {
path.pop();
return path.length ? this.form.get(path) : this.form;
};
__decorate([
Input('ngFormOptions'),
__metadata("design:type", Object)
], NgForm.prototype, "options", void 0);
NgForm = __decorate([
Directive({
selector: 'form:not([ngNoForm]):not([formGroup]),ngForm,ng-form,[ngForm]',
providers: [formDirectiveProvider],
host: { '(submit)': 'onSubmit($event)', '(reset)': 'onReset()' },
outputs: ['ngSubmit'],
exportAs: 'ngForm'
}),
__param(0, Optional()), __param(0, Self()), __param(0, Inject(NG_VALIDATORS)),
__param(1, Optional()), __param(1, Self()), __param(1, Inject(NG_ASYNC_VALIDATORS)),
__metadata("design:paramtypes", [Array, Array])
], NgForm);
return NgForm;
}(ControlContainer));
/**
* @license
* Copyright Google Inc. 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
*/
var TemplateDrivenErrors = /** @class */ (function () {
function TemplateDrivenErrors() {
}
TemplateDrivenErrors.modelParentException = function () {
throw new Error("\n ngModel cannot be used to register form controls with a parent formGroup directive. Try using\n formGroup's partner directive \"formControlName\" instead. Example:\n\n " + FormErrorExamples.formControlName + "\n\n Or, if you'd like to avoid registering this form control, indicate that it's standalone in ngModelOptions:\n\n Example:\n\n " + FormErrorExamples.ngModelWithFormGroup);
};
TemplateDrivenErrors.formGroupNameException = function () {
throw new Error("\n ngModel cannot be used to register form controls with a parent formGroupName or formArrayName directive.\n\n Option 1: Use formControlName instead of ngModel (reactive strategy):\n\n " + FormErrorExamples.formGroupName + "\n\n Option 2: Update ngModel's parent be ngModelGroup (template-driven strategy):\n\n " + FormErrorExamples.ngModelGroup);
};
TemplateDrivenErrors.missingNameException = function () {
throw new Error("If ngModel is used within a form tag, either the name attribute must be set or the form\n control must be defined as 'standalone' in ngModelOptions.\n\n Example 1: <input [(ngModel)]=\"person.firstName\" name=\"first\">\n Example 2: <input [(ngModel)]=\"person.firstName\" [ngModelOptions]=\"{standalone: true}\">");
};
TemplateDrivenErrors.modelGroupParentException = function () {
throw new Error("\n ngModelGroup cannot be used with a parent formGroup directive.\n\n Option 1: Use formGroupName instead of ngModelGroup (reactive strategy):\n\n " + FormErrorExamples.formGroupName + "\n\n Option 2: Use a regular form tag instead of the formGroup directive (template-driven strategy):\n\n " + FormErrorExamples.ngModelGroup);
};
TemplateDrivenErrors.ngFormWarning = function () {
console.warn("\n It looks like you're using 'ngForm'.\n\n Support for using the 'ngForm' element selector has been deprecated in Angular v6 and will be removed\n in Angular v9.\n\n Use 'ng-form' instead.\n\n Before:\n <ngForm #myForm=\"ngForm\">\n\n After:\n <ng-form #myForm=\"ngForm\">\n ");
};
return TemplateDrivenErrors;
}());
/**
* @license
* Copyright Google Inc. 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
*/
/**
* @description
* `InjectionToken` to provide to turn off the warning when using 'ngForm' deprecated selector.
*/
var NG_FORM_SELECTOR_WARNING = new InjectionToken('NgFormSelectorWarning');
/**
* This directive is solely used to display warnings when the deprecated `ngForm` selector is used.
*
* @deprecated in Angular v6 and will be removed in Angular v9.
* @ngModule FormsModule
* @publicApi
*/
var NgFormSelectorWarning = /** @class */ (function () {
function NgFormSelectorWarning(ngFormWarning) {
if (((!ngFormWarning || ngFormWarning === 'once') && !NgFormSelectorWarning_1._ngFormWarning) ||
ngFormWarning === 'always') {
TemplateDrivenErrors.ngFormWarning();
NgFormSelectorWarning_1._ngFormWarning = true;
}
}
NgFormSelectorWarning_1 = NgFormSelectorWarning;
var NgFormSelectorWarning_1;
/**
* Static property used to track whether the deprecation warning for this selector has been sent.
* Used to support warning config of "once".
*
* @internal
*/
NgFormSelectorWarning._ngFormWarning = false;
NgFormSelectorWarning = NgFormSelectorWarning_1 = __decorate([
Directive({ selector: 'ngForm' }),
__param(0, Optional()), __param(0, Inject(NG_FORM_SELECTOR_WARNING)),
__metadata("design:paramtypes", [Object])
], NgFormSelectorWarning);
return NgFormSelectorWarning;
}());
/**
* @license
* Copyright Google Inc. 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
*/
var modelGroupProvider = {
provide: ControlContainer,
useExisting: forwardRef(function () { return NgModelGroup; })
};
/**
* @description
* Creates and binds a `FormGroup` instance to a DOM element.
*
* This directive can only be used as a child of `NgForm` (within `<form>` tags).
*
* Use this directive to validate a sub-group of your form separately from the
* rest of your form, or if some values in your domain model make more sense
* to consume together in a nested object.
*
* Provide a name for the sub-group and it will become the key
* for the sub-group in the form's full value. If you need direct access, export the directive into
* a local template variable using `ngModelGroup` (ex: `#myGroup="ngModelGroup"`).
*
* @usageNotes
*
* ### Consuming controls in a grouping
*
* The following example shows you how to combine controls together in a sub-group
* of the form.
*
* {@example forms/ts/ngModelGroup/ng_model_group_example.ts region='Component'}
*
* @ngModule FormsModule
* @publicApi
*/
var NgModelGroup = /** @class */ (function (_super) {
__extends(NgModelGroup, _super);
function NgModelGroup(parent, validators, asyncValidators) {
var _this = _super.call(this) || this;
_this._parent = parent;
_this._validators = validators;
_this._asyncValidators = asyncValidators;
return _this;
}
NgModelGroup_1 = NgModelGroup;
/** @internal */
NgModelGroup.prototype._checkParentType = function () {
if (!(this._parent instanceof NgModelGroup_1) && !(this._parent instanceof NgForm)) {
TemplateDrivenErrors.modelGroupParentException();
}
};
var NgModelGroup_1;
__decorate([
Input('ngModelGroup'),
__metadata("design:type", String)
], NgModelGroup.prototype, "name", void 0);
NgModelGroup = NgModelGroup_1 = __decorate([
Directive({ selector: '[ngModelGroup]', providers: [modelGroupProvider], exportAs: 'ngModelGroup' }),
__param(0, Host()), __param(0, SkipSelf()),
__param(1, Optional()), __param(1, Self()), __param(1, Inject(NG_VALIDATORS)),
__param(2, Optional()), __param(2, Self()), __param(2, Inject(NG_ASYNC_VALIDATORS)),
__metadata("design:paramtypes", [ControlContainer, Array, Array])
], NgModelGroup);
return NgModelGroup;
}(AbstractFormGroupDirective));
/**
* @license
* Copyright Google Inc. 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
*/
var formControlBinding = {
provide: NgControl,
useExisting: forwardRef(function () { return NgModel; })
};
/**
* `ngModel` forces an additional change detection run when its inputs change:
* E.g.:
* ```
* <div>{{myModel.valid}}</div>
* <input [(ngModel)]="myValue" #myModel="ngModel">
* ```
* I.e. `ngModel` can export itself on the element and then be used in the template.
* Normally, this would result in expressions before the `input` that use the exported directive
* to have and old value as they have been
* dirty checked before. As this is a very common case for `ngModel`, we added this second change
* detection run.
*
* Notes:
* - this is just one extra run no matter how many `ngModel` have been changed.
* - this is a general problem when using `exportAs` for directives!
*/
var resolvedPromise$1 = Promise.resolve(null);
/**
* @description
* Creates a `FormControl` instance from a domain model and binds it
* to a form control element.
*
* The `FormControl` instance tracks the value, user interaction, and
* validation status of the control and keeps the view synced with the model. If used
* within a parent form, the directive also registers itself with the form as a child
* control.
*
* This directive is used by itself or as part of a larger form. Use the
* `ngModel` selector to activate it.
*
* It accepts a domain model as an optional `Input`. If you have a one-way binding
* to `ngModel` with `[]` syntax, changing the value of the domain model in the component
* class sets the value in the view. If you have a two-way binding with `[()]` syntax
* (also known as 'banana-box syntax'), the value in the UI always syncs back to
* the domain model in your class.
*
* To inspect the properties of the associated `FormControl` (like validity state),
* export the directive into a local template variable using `ngModel` as the key (ex: `#myVar="ngModel"`).
* You then access the control using the directive's `control` property,
* but most properties used (like `valid` and `dirty`) fall through to the control anyway for direct access.
* See a full list of properties directly available in `AbstractControlDirective`.
*
* @see `RadioControlValueAccessor`
* @see `SelectControlValueAccessor`
*
* @usageNotes
*
* ### Using ngModel on a standalone control
*
* The following examples show a simple standalone control using `ngModel`:
*
* {@example forms/ts/simpleNgModel/simple_ng_model_example.ts region='Component'}
*
* When using the `ngModel` within `<form>` tags, you'll also need to supply a `name` attribute
* so that the control can be registered with the parent form under that name.
*
* In the context of a parent form, it's often unnecessary to include one-way or two-way binding,
* as the parent form syncs the value for you. You access its properties by exporting it into a
* local template variable using `ngForm` such as (`#f="ngForm"`). Use the variable where
* needed on form submission.
*
* If you do need to populate initial values into your form, using a one-way binding for
* `ngModel` tends to be sufficient as long as you use the exported form's value rather
* than the domain model's value on submit.
*
* ### Using ngModel within a form
*
* The following example shows controls using `ngModel` within a form:
*
* {@example forms/ts/simpleForm/simple_form_example.ts region='Component'}
*
* ### Using a standalone ngModel within a group
*
* The following example shows you how to use a standalone ngModel control
* within a form. This controls the display of the form, but doesn't contain form data.
*
* ```html
* <form>
* <input name="login" ngModel placeholder="Login">
* <input type="checkbox" ngModel [ngModelOptions]="{standalone: true}"> Show more options?
* </form>
* <!-- form value: {login: ''} -->
* ```
*
* ### Setting the ngModel name attribute through options
*
* The following example shows you an alternate way to set the name attribute. The name attribute is used
* within a custom form component, and the name `@Input` property serves a different purpose.
*
* ```html
* <form>
* <my-person-control name="Nancy" ngModel [ngModelOptions]="{name: 'user'}">
* </my-person-control>
* </form>
* <!-- form value: {user: ''} -->
* ```
*
* @ngModule FormsModule
* @publicApi
*/
var NgModel = /** @class */ (function (_super) {
__extends(NgModel, _super);
function NgModel(parent, validators, asyncValidators, valueAccessors) {
var _this = _super.call(this) || this;
_this.control = new FormControl();
/** @internal */
_this._registered = false;
/**
* @description
* Event emitter for producing the `ngModelChange` event after
* the view model updates.
*/
_this.update = new EventEmitter();
_this._parent = parent;
_this._rawValidators = validators || [];
_this._rawAsyncValidators = asyncValidators || [];
_this.valueAccessor = selectValueAccessor(_this, valueAccessors);
return _this;
}
/**
* @description
* A lifecycle method called when the directive's inputs change. For internal use
* only.
*
* @param changes A object of key/value pairs for the set of changed inputs.
*/
NgModel.prototype.ngOnChanges = function (changes) {
this._checkForErrors();
if (!this._registered)
this._setUpControl();
if ('isDisabled' in changes) {
this._updateDisabled(changes);
}
if (isPropertyUpdated(changes, this.viewModel)) {
this._updateValue(this.model);
this.viewModel = this.model;
}
};
/**
* @description
* Lifecycle method called before the directive's instance is destroyed. For internal
* use only.
*/
NgModel.prototype.ngOnDestroy = function () { this.formDirective && this.formDirective.removeControl(this); };
Object.defineProperty(NgModel.prototype, "path", {
/**
* @description
* Returns an array that represents the path from the top-level form to this control.
* Each index is the string name of the control on that level.
*/
get: function () {
return this._parent ? controlPath(this.name, this._parent) : [this.name];
},
enumerable: true,
configurable: true
});
Object.defineProperty(NgModel.prototype, "formDirective", {
/**
* @description
* The top-level directive for this control if present, otherwise null.
*/
get: function () { return this._parent ? this._parent.formDirective : null; },
enumerable: true,
configurable: true
});
Object.defineProperty(NgModel.prototype, "validator", {
/**
* @description
* Synchronous validator function composed of all the synchronous validators
* registered with this directive.
*/
get: function () { return composeValidators(this._rawValidators); },
enumerable: true,
configurable: true
});
Object.defineProperty(NgModel.prototype, "asyncValidator", {
/**
* @description
* Async validator function composed of all the async validators registered with this
* directive.
*/
get: function () {
return composeAsyncValidators(this._rawAsyncValidators);
},
enumerable: true,
configurable: true
});
/**
* @description
* Sets the new value for the view model and emits an `ngModelChange` event.
*
* @param newValue The new value emitted by `ngModelChange`.
*/
NgModel.prototype.viewToModelUpdate = function (newValue) {
this.viewModel = newValue;
this.update.emit(newValue);
};
NgModel.prototype._setUpControl = function () {
this._setUpdateStrategy();
this._isStandalone() ? this._setUpStandalone() :
this.formDirective.addControl(this);
this._registered = true;
};
NgModel.prototype._setUpdateStrategy = function () {
if (this.options && this.options.updateOn != null) {
this.control._updateOn = this.options.updateOn;
}
};
NgModel.prototype._isStandalone = function () {
return !this._parent || !!(this.options && this.options.standalone);
};
NgModel.prototype._setUpStandalone = function () {
setUpControl(this.control, this);
this.control.updateValueAndValidity({ emitEvent: false });
};
NgModel.prototype._checkForErrors = function () {
if (!this._isStandalone()) {
this._checkParentType();
}
this._checkName();
};
NgModel.prototype._checkParentType = function () {
if (!(this._parent instanceof NgModelGroup) &&
this._parent instanceof AbstractFormGroupDirective) {
TemplateDrivenErrors.formGroupNameException();
}
else if (!(this._parent instanceof NgModelGroup) && !(this._parent instanceof NgForm)) {
TemplateDrivenErrors.modelParentException();
}
};
NgModel.prototype._checkName = function () {
if (this.options && this.options.name)
this.name = this.options.name;
if (!this._isStandalone() && !this.name) {
TemplateDrivenErrors.missingNameException();
}
};
NgModel.prototype._updateValue = function (value) {
var _this = this;
resolvedPromise$1.then(function () { _this.control.setValue(value, { emitViewToModelChange: false }); });
};
NgModel.prototype._updateDisabled = function (changes) {
var _this = this;
var disabledValue = changes['isDisabled'].currentValue;
var isDisabled = disabledValue === '' || (disabledValue && disabledValue !== 'false');
resolvedPromise$1.then(function () {
if (isDisabled && !_this.control.disabled) {
_this.control.disable();
}
else if (!isDisabled && _this.control.disabled) {
_this.control.enable();
}
});
};
__decorate([
Input(),
__metadata("design:type", String)
], NgModel.prototype, "name", void 0);
__decorate([
Input('disabled'),
__metadata("design:type", Boolean)
], NgModel.prototype, "isDisabled", void 0);
__decorate([
Input('ngModel'),
__metadata("design:type", Object)
], NgModel.prototype, "model", void 0);
__decorate([
Input('ngModelOptions'),
__metadata("design:type", Object)
], NgModel.prototype, "options", void 0);
__decorate([
Output('ngModelChange'),
__metadata("design:type", Object)
], NgModel.prototype, "update", void 0);
NgModel = __decorate([
Directive({
selector: '[ngModel]:not([formControlName]):not([formControl])',
providers: [formControlBinding],
exportAs: 'ngModel'
}),
__param(0, Optional()), __param(0, Host()),
__param(1, Optional()), __param(1, Self()), __param(1, Inject(NG_VALIDATORS)),
__param(2, Optional()), __param(2, Self()), __param(2, Inject(NG_ASYNC_VALIDATORS)),
__param(3, Optional()), __param(3, Self()), __param(3, Inject(NG_VALUE_ACCESSOR)),
__metadata("design:paramtypes", [ControlContainer,
Array,
Array, Array])
], NgModel);
return NgModel;
}(NgControl));
/**
* @license
* Copyright Google Inc. 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
*/
/**
* Token to provide to turn off the ngModel warning on formControl and formControlName.
*/
var NG_MODEL_WITH_FORM_CONTROL_WARNING = new InjectionToken('NgModelWithFormControlWarning');
var formControlBinding$1 = {
provide: NgControl,
useExisting: forwardRef(function () { return FormControlDirective; })
};
/**
* @description
* * Syncs a standalone `FormControl` instance to a form control element.
*
* @see [Reactive Forms Guide](guide/reactive-forms)
* @see `FormControl`
* @see `AbstractControl`
*
* @usageNotes
*
* ### Registering a single form control
*
* The following examples shows how to register a standalone control and set its value.
*
* {@example forms/ts/simpleFormControl/simple_form_control_example.ts region='Component'}
*
* ### Use with ngModel
*
* Support for using the `ngModel` input property and `ngModelChange` event with reactive
* form directives has been deprecated in Angular v6 and will be removed in Angular v7.
*
* Now deprecated:
*
* ```html
* <input [formControl]="control" [(ngModel)]="value">
* ```
*
* ```ts
* this.value = 'some value';
* ```
*
* This has been deprecated for a few reasons. First, developers have found this pattern
* confusing. It seems like the actual `ngModel` directive is being used, but in fact it's
* an input/output property named `ngModel` on the reactive form directive that simply
* approximates (some of) its behavior. Specifically, it allows getting/setting the value
* and intercepting value events. However, some of `ngModel`'s other features - like
* delaying updates with`ngModelOptions` or exporting the directive - simply don't work,
* which has understandably caused some confusion.
*
* In addition, this pattern mixes template-driven and reactive forms strategies, which
* we generally don't recommend because it doesn't take advantage of the full benefits of
* either strategy. Setting the value in the template violates the template-agnostic
* principles behind reactive forms, whereas adding a `FormControl`/`FormGroup` layer in
* the class removes the convenience of defining forms in the template.
*
* To update your code before v7, you'll want to decide whether to stick with reactive form
* directives (and get/set values using reactive forms patterns) or switch over to
* template-driven directives.
*
* After (choice 1 - use reactive forms):
*
* ```html
* <input [formControl]="control">
* ```
*
* ```ts
* this.control.setValue('some value');
* ```
*
* After (choice 2 - use template-driven forms):
*
* ```html
* <input [(ngModel)]="value">
* ```
*
* ```ts
* this.value = 'some value';
* ```
*
* By default, when you use this pattern, you will see a deprecation warning once in dev
* mode. You can choose to silence this warning by providing a config for
* `ReactiveFormsModule` at import time:
*
* ```ts
* imports: [
* ReactiveFormsModule.withConfig({warnOnNgModelWithFormControl: 'never'});
* ]
* ```
*
* Alternatively, you can choose to surface a separate warning for each instance of this
* pattern with a config value of `"always"`. This may help to track down where in the code
* the pattern is being used as the code is being updated.
*
* @ngModule ReactiveFormsModule
* @publicApi
*/
var FormControlDirective = /** @class */ (function (_super) {
__extends(FormControlDirective, _super);
function FormControlDirective(validators, asyncValidators, valueAccessors, _ngModelWarningConfig) {
var _this = _super.call(this) || this;
_this._ngModelWarningConfig = _ngModelWarningConfig;
/** @deprecated as of v6 */
_this.update = new EventEmitter();
/**
* @description
* Instance property used to track whether an ngModel warning has been sent out for this
* particular `FormControlDirective` instance. Used to support warning config of "always".
*
* @internal
*/
_this._ngModelWarningSent = false;
_this._rawValidators = validators || [];
_this._rawAsyncValidators = asyncValidators || [];
_this.valueAccessor = selectValueAccessor(_this, valueAccessors);
return _this;
}
FormControlDirective_1 = FormControlDirective;
Object.defineProperty(FormControlDirective.prototype, "isDisabled", {
/**
* @description
* Triggers a warning that this input should not be used with reactive forms.
*/
set: function (isDisabled) { ReactiveErrors.disabledAttrWarning(); },
enumerable: true,
configurable: true
});
/**
* @description
* A lifecycle method called when the directive's inputs change. For internal use
* only.
*
* @param changes A object of key/value pairs for the set of changed inputs.
*/
FormControlDirective.prototype.ngOnChanges = function (changes) {
if (this._isControlChanged(changes)) {
setUpControl(this.form, this);
if (this.control.disabled && this.valueAccessor.setDisabledState) {
this.valueAccessor.setDisabledState(true);
}
this.form.updateValueAndValidity({ emitEvent: false });
}
if (isPropertyUpdated(changes, this.viewModel)) {
_ngModelWarning('formControl', FormControlDirective_1, this, this._ngModelWarningConfig);
this.form.setValue(this.model);
this.viewModel = this.model;
}
};
Object.defineProperty(FormControlDirective.prototype, "path", {
/**
* @description
* Returns an array that represents the path from the top-level form to this control.
* Each index is the string name of the control on that level.
*/
get: function () { return []; },
enumerable: true,
configurable: true
});
Object.defineProperty(FormControlDirective.prototype, "validator", {
/**
* @description
* Synchronous validator function composed of all the synchronous validators
* registered with this directive.
*/
get: function () { return composeValidators(this._rawValidators); },
enumerable: true,
configurable: true
});
Object.defineProperty(FormControlDirective.prototype, "asyncValidator", {
/**
* @description
* Async validator function composed of all the async validators registered with this
* directive.
*/
get: function () {
return composeAsyncValidators(this._rawAsyncValidators);
},
enumerable: true,
configurable: true
});
Object.defineProperty(FormControlDirective.prototype, "control", {
/**
* @description
* The `FormControl` bound to this directive.
*/
get: function () { return this.form; },
enumerable: true,
configurable: true
});
/**
* @description
* Sets the new value for the view model and emits an `ngModelChange` event.
*
* @param newValue The new value for the view model.
*/
FormControlDirective.prototype.viewToModelUpdate = function (newValue) {
this.viewModel = newValue;
this.update.emit(newValue);
};
FormControlDirective.prototype._isControlChanged = function (changes) {
return changes.hasOwnProperty('form');
};
var FormControlDirective_1;
/**
* @description
* Static property used to track whether any ngModel warnings have been sent across
* all instances of FormControlDirective. Used to support warning config of "once".
*
* @internal
*/
FormControlDirective._ngModelWarningSentOnce = false;
__decorate([
Input('formControl'),
__metadata("design:type", FormControl)
], FormControlDirective.prototype, "form", void 0);
__decorate([
Input('disabled'),
__metadata("design:type", Boolean),
__metadata("design:paramtypes", [Boolean])
], FormControlDirective.prototype, "isDisabled", null);
__decorate([
Input('ngModel'),
__metadata("design:type", Object)
], FormControlDirective.prototype, "model", void 0);
__decorate([
Output('ngModelChange'),
__metadata("design:type", Object)
], FormControlDirective.prototype, "update", void 0);
FormControlDirective = FormControlDirective_1 = __decorate([
Directive({ selector: '[formControl]', providers: [formControlBinding$1], exportAs: 'ngForm' }),
__param(0, Optional()), __param(0, Self()), __param(0, Inject(NG_VALIDATORS)),
__param(1, Optional()), __param(1, Self()), __param(1, Inject(NG_ASYNC_VALIDATORS)),
__param(2, Optional()), __param(2, Self()), __param(2, Inject(NG_VALUE_ACCESSOR)),
__param(3, Optional()), __param(3, Inject(NG_MODEL_WITH_FORM_CONTROL_WARNING)),
__metadata("design:paramtypes", [Array,
Array, Array, Object])
], FormControlDirective);
return FormControlDirective;
}(NgControl));
/**
* @license
* Copyright Google Inc. 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
*/
var formDirectiveProvider$1 = {
provide: ControlContainer,
useExisting: forwardRef(function () { return FormGroupDirective; })
};
/**
* @description
*
* Binds an existing `FormGroup` to a DOM element.
*
* This directive accepts an existing `FormGroup` instance. It will then use this
* `FormGroup` instance to match any child `FormControl`, `FormGroup`,
* and `FormArray` instances to child `FormControlName`, `FormGroupName`,
* and `FormArrayName` directives.
*
* @see [Reactive Forms Guide](guide/reactive-forms)
* @see `AbstractControl`
*
* ### Register Form Group
*
* The following example registers a `FormGroup` with first name and last name controls,
* and listens for the *ngSubmit* event when the button is clicked.
*
* {@example forms/ts/simpleFormGroup/simple_form_group_example.ts region='Component'}
*
* @ngModule ReactiveFormsModule
* @publicApi
*/
var FormGroupDirective = /** @class */ (function (_super) {
__extends(FormGroupDirective, _super);
function FormGroupDirective(_validators, _asyncValidators) {
var _this = _super.call(this) || this;
_this._validators = _validators;
_this._asyncValidators = _asyncValidators;
/**
* @description
* Reports whether the form submission has been triggered.
*/
_this.submitted = false;
/**
* @description
* Tracks the list of added `FormControlName` instances
*/
_this.directives = [];
/**
* @description
* Tracks the `FormGroup` bound to this directive.
*/
_this.form = null;
/**
* @description
* Emits an event when the form submission has been triggered.
*/
_this.ngSubmit = new EventEmitter();
return _this;
}
/**
* @description
* A lifecycle method called when the directive's inputs change. For internal use only.
*
* @param changes A object of key/value pairs for the set of changed inputs.
*/
FormGroupDirective.prototype.ngOnChanges = function (changes) {
this._checkFormPresent();
if (changes.hasOwnProperty('form')) {
this._updateValidators();
this._updateDomValue();
this._updateRegistrations();
}
};
Object.defineProperty(FormGroupDirective.prototype, "formDirective", {
/**
* @description
* Returns this directive's instance.
*/
get: function () { return this; },
enumerable: true,
configurable: true
});
Object.defineProperty(FormGroupDirective.prototype, "control", {
/**
* @description
* Returns the `FormGroup` bound to this directive.
*/
get: function () { return this.form; },
enumerable: true,
configurable: true
});
Object.defineProperty(FormGroupDirective.prototype, "path", {
/**
* @description
* Returns an array representing the path to this group. Because this directive
* always lives at the top level of a form, it always an empty array.
*/
get: function () { return []; },
enumerable: true,
configurable: true
});
/**
* @description
* Method that sets up the control directive in this group, re-calculates its value
* and validity, and adds the instance to the internal list of directives.
*
* @param dir The `FormControlName` directive instance.
*/
FormGroupDirective.prototype.addControl = function (dir) {
var ctrl = this.form.get(dir.path);
setUpControl(ctrl, dir);
ctrl.updateValueAndValidity({ emitEvent: false });
this.directives.push(dir);
return ctrl;
};
/**
* @description
* Retrieves the `FormControl` instance from the provided `FormControlName` directive
*
* @param dir The `FormControlName` directive instance.
*/
FormGroupDirective.prototype.getControl = function (dir) { return this.form.get(dir.path); };
/**
* @description
* Removes the `FormControlName` instance from the internal list of directives
*
* @param dir The `FormControlName` directive instance.
*/
FormGroupDirective.prototype.removeControl = function (dir) { removeDir(this.directives, dir); };
/**
* Adds a new `FormGroupName` directive instance to the form.
*
* @param dir The `FormGroupName` directive instance.
*/
FormGroupDirective.prototype.addFormGroup = function (dir) {
var ctrl = this.form.get(dir.path);
setUpFormContainer(ctrl, dir);
ctrl.updateValueAndValidity({ emitEvent: false });
};
/**
* No-op method to remove the form group.
*
* @param dir The `FormGroupName` directive instance.
*/
FormGroupDirective.prototype.removeFormGroup = function (dir) { };
/**
* @description
* Retrieves the `FormGroup` for a provided `FormGroupName` directive instance
*
* @param dir The `FormGroupName` directive instance.
*/
FormGroupDirective.prototype.getFormGroup = function (dir) { return this.form.get(dir.path); };
/**
* Adds a new `FormArrayName` directive instance to the form.
*
* @param dir The `FormArrayName` directive instance.
*/
FormGroupDirective.prototype.addFormArray = function (dir) {
var ctrl = this.form.get(dir.path);
setUpFormContainer(ctrl, dir);
ctrl.updateValueAndValidity({ emitEvent: false });
};
/**
* No-op method to remove the form array.
*
* @param dir The `FormArrayName` directive instance.
*/
FormGroupDirective.prototype.removeFormArray = function (dir) { };
/**
* @description
* Retrieves the `FormArray` for a provided `FormArrayName` directive instance.
*
* @param dir The `FormArrayName` directive instance.
*/
FormGroupDirective.prototype.getFormArray = function (dir) { return this.form.get(dir.path); };
/**
* Sets the new value for the provided `FormControlName` directive.
*
* @param dir The `FormControlName` directive instance.
* @param value The new value for the directive's control.
*/
FormGroupDirective.prototype.updateModel = function (dir, value) {
var ctrl = this.form.get(dir.path);
ctrl.setValue(value);
};
/**
* @description
* Method called with the "submit" event is triggered on the form.
* Triggers the `ngSubmit` emitter to emit the "submit" event as its payload.
*
* @param $event The "submit" event object
*/
FormGroupDirective.prototype.onSubmit = function ($event) {
this.submitted = true;
syncPendingControls(this.form, this.directives);
this.ngSubmit.emit($event);
return false;
};
/**
* @description
* Method called when the "reset" event is triggered on the form.
*/
FormGroupDirective.prototype.onReset = function () { this.resetForm(); };
/**
* @description
* Resets the form to an initial value and resets its submitted status.
*
* @param value The new value for the form.
*/
FormGroupDirective.prototype.resetForm = function (value) {
if (value === void 0) { value = undefined; }
this.form.reset(value);
this.submitted = false;
};
/** @internal */
FormGroupDirective.prototype._updateDomValue = function () {
var _this = this;
this.directives.forEach(function (dir) {
var newCtrl = _this.form.get(dir.path);
if (dir.control !== newCtrl) {
cleanUpControl(dir.control, dir);
if (newCtrl)
setUpControl(newCtrl, dir);
dir.control = newCtrl;
}
});
this.form._updateTreeValidity({ emitEvent: false });
};
FormGroupDirective.prototype._updateRegistrations = function () {
var _this = this;
this.form._registerOnCollectionChange(function () { return _this._updateDomValue(); });
if (this._oldForm)
this._oldForm._registerOnCollectionChange(function () { });
this._oldForm = this.form;
};
FormGroupDirective.prototype._updateValidators = function () {
var sync = composeValidators(this._validators);
this.form.validator = Validators.compose([this.form.validator, sync]);
var async = composeAsyncValidators(this._asyncValidators);
this.form.asyncValidator = Validators.composeAsync([this.form.asyncValidator, async]);
};
FormGroupDirective.prototype._checkFormPresent = function () {
if (!this.form) {
ReactiveErrors.missingFormException();
}
};
__decorate([
Input('formGroup'),
__metadata("design:type", FormGroup)
], FormGroupDirective.prototype, "form", void 0);
__decorate([
Output(),
__metadata("design:type", Object)
], FormGroupDirective.prototype, "ngSubmit", void 0);
FormGroupDirective = __decorate([
Directive({
selector: '[formGroup]',
providers: [formDirectiveProvider$1],
host: { '(submit)': 'onSubmit($event)', '(reset)': 'onReset()' },
exportAs: 'ngForm'
}),
__param(0, Optional()), __param(0, Self()), __param(0, Inject(NG_VALIDATORS)),
__param(1, Optional()), __param(1, Self()), __param(1, Inject(NG_ASYNC_VALIDATORS)),
__metadata("design:paramtypes", [Array, Array])
], FormGroupDirective);
return FormGroupDirective;
}(ControlContainer));
/**
* @license
* Copyright Google Inc. 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
*/
var formGroupNameProvider = {
provide: ControlContainer,
useExisting: forwardRef(function () { return FormGroupName; })
};
/**
* @description
*
* Syncs a nested `FormGroup` to a DOM element.
*
* This directive can only be used with a parent `FormGroupDirective`.
*
* It accepts the string name of the nested `FormGroup` to link, and
* looks for a `FormGroup` registered with that name in the parent
* `FormGroup` instance you passed into `FormGroupDirective`.
*
* Use nested form groups to validate a sub-group of a
* form separately from the rest or to group the values of certain
* controls into their own nested object.
*
* @see [Reactive Forms Guide](guide/reactive-forms)
*
* @usageNotes
*
* ### Access the group by name
*
* The following example uses the {@link AbstractControl#get get} method to access the
* associated `FormGroup`
*
* ```ts
* this.form.get('name');
* ```
*
* ### Access individual controls in the group
*
* The following example uses the {@link AbstractControl#get get} method to access
* individual controls within the group using dot syntax.
*
* ```ts
* this.form.get('name.first');
* ```
*
* ### Register a nested `FormGroup`.
*
* The following example registers a nested *name* `FormGroup` within an existing `FormGroup`,
* and provides methods to retrieve the nested `FormGroup` and individual controls.
*
* {@example forms/ts/nestedFormGroup/nested_form_group_example.ts region='Component'}
*
* @ngModule ReactiveFormsModule
* @publicApi
*/
var FormGroupName = /** @class */ (function (_super) {
__extends(FormGroupName, _super);
function FormGroupName(parent, validators, asyncValidators) {
var _this = _super.call(this) || this;
_this._parent = parent;
_this._validators = validators;
_this._asyncValidators = asyncValidators;
return _this;
}
/** @internal */
FormGroupName.prototype._checkParentType = function () {
if (_hasInvalidParent(this._parent)) {
ReactiveErrors.groupParentException();
}
};
__decorate([
Input('formGroupName'),
__metadata("design:type", String)
], FormGroupName.prototype, "name", void 0);
FormGroupName = __decorate([
Directive({ selector: '[formGroupName]', providers: [formGroupNameProvider] }),
__param(0, Optional()), __param(0, Host()), __param(0, SkipSelf()),
__param(1, Optional()), __param(1, Self()), __param(1, Inject(NG_VALIDATORS)),
__param(2, Optional()), __param(2, Self()), __param(2, Inject(NG_ASYNC_VALIDATORS)),
__metadata("design:paramtypes", [ControlContainer, Array, Array])
], FormGroupName);
return FormGroupName;
}(AbstractFormGroupDirective));
var formArrayNameProvider = {
provide: ControlContainer,
useExisting: forwardRef(function () { return FormArrayName; })
};
/**
* @description
*
* Syncs a nested `FormArray` to a DOM element.
*
* This directive is designed to be used with a parent `FormGroupDirective` (selector:
* `[formGroup]`).
*
* It accepts the string name of the nested `FormArray` you want to link, and
* will look for a `FormArray` registered with that name in the parent
* `FormGroup` instance you passed into `FormGroupDirective`.
*
* @see [Reactive Forms Guide](guide/reactive-forms)
* @see `AbstractControl`
*
* @usageNotes
*
* ### Example
*
* {@example forms/ts/nestedFormArray/nested_form_array_example.ts region='Component'}
*
* @ngModule ReactiveFormsModule
* @publicApi
*/
var FormArrayName = /** @class */ (function (_super) {
__extends(FormArrayName, _super);
function FormArrayName(parent, validators, asyncValidators) {
var _this = _super.call(this) || this;
_this._parent = parent;
_this._validators = validators;
_this._asyncValidators = asyncValidators;
return _this;
}
/**
* @description
* A lifecycle method called when the directive's inputs are initialized. For internal use only.
*
* @throws If the directive does not have a valid parent.
*/
FormArrayName.prototype.ngOnInit = function () {
this._checkParentType();
this.formDirective.addFormArray(this);
};
/**
* @description
* A lifecycle method called before the directive's instance is destroyed. For internal use only.
*/
FormArrayName.prototype.ngOnDestroy = function () {
if (this.formDirective) {
this.formDirective.removeFormArray(this);
}
};
Object.defineProperty(FormArrayName.prototype, "control", {
/**
* @description
* The `FormArray` bound to this directive.
*/
get: function () { return this.formDirective.getFormArray(this); },
enumerable: true,
configurable: true
});
Object.defineProperty(FormArrayName.prototype, "formDirective", {
/**
* @description
* The top-level directive for this group if present, otherwise null.
*/
get: function () {
return this._parent ? this._parent.formDirective : null;
},
enumerable: true,
configurable: true
});
Object.defineProperty(FormArrayName.prototype, "path", {
/**
* @description
* Returns an array that represents the path from the top-level form to this control.
* Each index is the string name of the control on that level.
*/
get: function () { return controlPath(this.name, this._parent); },
enumerable: true,
configurable: true
});
Object.defineProperty(FormArrayName.prototype, "validator", {
/**
* @description
* Synchronous validator function composed of all the synchronous validators registered with this
* directive.
*/
get: function () { return composeValidators(this._validators); },
enumerable: true,
configurable: true
});
Object.defineProperty(FormArrayName.prototype, "asyncValidator", {
/**
* @description
* Async validator function composed of all the async validators registered with this directive.
*/
get: function () {
return composeAsyncValidators(this._asyncValidators);
},
enumerable: true,
configurable: true
});
FormArrayName.prototype._checkParentType = function () {
if (_hasInvalidParent(this._parent)) {
ReactiveErrors.arrayParentException();
}
};
__decorate([
Input('formArrayName'),
__metadata("design:type", String)
], FormArrayName.prototype, "name", void 0);
FormArrayName = __decorate([
Directive({ selector: '[formArrayName]', providers: [formArrayNameProvider] }),
__param(0, Optional()), __param(0, Host()), __param(0, SkipSelf()),
__param(1, Optional()), __param(1, Self()), __param(1, Inject(NG_VALIDATORS)),
__param(2, Optional()), __param(2, Self()), __param(2, Inject(NG_ASYNC_VALIDATORS)),
__metadata("design:paramtypes", [ControlContainer, Array, Array])
], FormArrayName);
return FormArrayName;
}(ControlContainer));
function _hasInvalidParent(parent) {
return !(parent instanceof FormGroupName) && !(parent instanceof FormGroupDirective) &&
!(parent instanceof FormArrayName);
}
/**
* @license
* Copyright Google Inc. 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
*/
var controlNameBinding = {
provide: NgControl,
useExisting: forwardRef(function () { return FormControlName; })
};
/**
* @description
* Syncs a `FormControl` in an existing `FormGroup` to a form control
* element by name.
*
* @see [Reactive Forms Guide](guide/reactive-forms)
* @see `FormControl`
* @see `AbstractControl`
*
* @usageNotes
*
* ### Register `FormControl` within a group
*
* The following example shows how to register multiple form controls within a form group
* and set their value.
*
* {@example forms/ts/simpleFormGroup/simple_form_group_example.ts region='Component'}
*
* To see `formControlName` examples with different form control types, see:
*
* * Radio buttons: `RadioControlValueAccessor`
* * Selects: `SelectControlValueAccessor`
*
* ### Use with ngModel
*
* Support for using the `ngModel` input property and `ngModelChange` event with reactive
* form directives has been deprecated in Angular v6 and will be removed in Angular v7.
*
* Now deprecated:
*
* ```html
* <form [formGroup]="form">
* <input formControlName="first" [(ngModel)]="value">
* </form>
* ```
*
* ```ts
* this.value = 'some value';
* ```
*
* This has been deprecated for a few reasons. First, developers have found this pattern
* confusing. It seems like the actual `ngModel` directive is being used, but in fact it's
* an input/output property named `ngModel` on the reactive form directive that simply
* approximates (some of) its behavior. Specifically, it allows getting/setting the value
* and intercepting value events. However, some of `ngModel`'s other features - like
* delaying updates with`ngModelOptions` or exporting the directive - simply don't work,
* which has understandably caused some confusion.
*
* In addition, this pattern mixes template-driven and reactive forms strategies, which
* we generally don't recommend because it doesn't take advantage of the full benefits of
* either strategy. Setting the value in the template violates the template-agnostic
* principles behind reactive forms, whereas adding a `FormControl`/`FormGroup` layer in
* the class removes the convenience of defining forms in the template.
*
* To update your code before v7, you'll want to decide whether to stick with reactive form
* directives (and get/set values using reactive forms patterns) or switch over to
* template-driven directives.
*
* After (choice 1 - use reactive forms):
*
* ```html
* <form [formGroup]="form">
* <input formControlName="first">
* </form>
* ```
*
* ```ts
* this.form.get('first').setValue('some value');
* ```
*
* After (choice 2 - use template-driven forms):
*
* ```html
* <input [(ngModel)]="value">
* ```
*
* ```ts
* this.value = 'some value';
* ```
*
* By default, when you use this pattern, you will see a deprecation warning once in dev
* mode. You can choose to silence this warning by providing a config for
* `ReactiveFormsModule` at import time:
*
* ```ts
* imports: [
* ReactiveFormsModule.withConfig({warnOnNgModelWithFormControl: 'never'});
* ]
* ```
*
* Alternatively, you can choose to surface a separate warning for each instance of this
* pattern with a config value of `"always"`. This may help to track down where in the code
* the pattern is being used as the code is being updated.
*
* @ngModule ReactiveFormsModule
* @publicApi
*/
var FormControlName = /** @class */ (function (_super) {
__extends(FormControlName, _super);
function FormControlName(parent, validators, asyncValidators, valueAccessors, _ngModelWarningConfig) {
var _this = _super.call(this) || this;
_this._ngModelWarningConfig = _ngModelWarningConfig;
_this._added = false;
/** @deprecated as of v6 */
_this.update = new EventEmitter();
/**
* @description
* Instance property used to track whether an ngModel warning has been sent out for this
* particular FormControlName instance. Used to support warning config of "always".
*
* @internal
*/
_this._ngModelWarningSent = false;
_this._parent = parent;
_this._rawValidators = validators || [];
_this._rawAsyncValidators = asyncValidators || [];
_this.valueAccessor = selectValueAccessor(_this, valueAccessors);
return _this;
}
FormControlName_1 = FormControlName;
Object.defineProperty(FormControlName.prototype, "isDisabled", {
/**
* @description
* Triggers a warning that this input should not be used with reactive forms.
*/
set: function (isDisabled) { ReactiveErrors.disabledAttrWarning(); },
enumerable: true,
configurable: true
});
/**
* @description
* A lifecycle method called when the directive's inputs change. For internal use only.
*
* @param changes A object of key/value pairs for the set of changed inputs.
*/
FormControlName.prototype.ngOnChanges = function (changes) {
if (!this._added)
this._setUpControl();
if (isPropertyUpdated(changes, this.viewModel)) {
_ngModelWarning('formControlName', FormControlName_1, this, this._ngModelWarningConfig);
this.viewModel = this.model;
this.formDirective.updateModel(this, this.model);
}
};
/**
* @description
* Lifecycle method called before the directive's instance is destroyed. For internal use only.
*/
FormControlName.prototype.ngOnDestroy = function () {
if (this.formDirective) {
this.formDirective.removeControl(this);
}
};
/**
* @description
* Sets the new value for the view model and emits an `ngModelChange` event.
*
* @param newValue The new value for the view model.
*/
FormControlName.prototype.viewToModelUpdate = function (newValue) {
this.viewModel = newValue;
this.update.emit(newValue);
};
Object.defineProperty(FormControlName.prototype, "path", {
/**
* @description
* Returns an array that represents the path from the top-level form to this control.
* Each index is the string name of the control on that level.
*/
get: function () { return controlPath(this.name, this._parent); },
enumerable: true,
configurable: true
});
Object.defineProperty(FormControlName.prototype, "formDirective", {
/**
* @description
* The top-level directive for this group if present, otherwise null.
*/
get: function () { return this._parent ? this._parent.formDirective : null; },
enumerable: true,
configurable: true
});
Object.defineProperty(FormControlName.prototype, "validator", {
/**
* @description
* Synchronous validator function composed of all the synchronous validators
* registered with this directive.
*/
get: function () { return composeValidators(this._rawValidators); },
enumerable: true,
configurable: true
});
Object.defineProperty(FormControlName.prototype, "asyncValidator", {
/**
* @description
* Async validator function composed of all the async validators registered with this
* directive.
*/
get: function () {
return composeAsyncValidators(this._rawAsyncValidators);
},
enumerable: true,
configurable: true
});
FormControlName.prototype._checkParentType = function () {
if (!(this._parent instanceof FormGroupName) &&
this._parent instanceof AbstractFormGroupDirective) {
ReactiveErrors.ngModelGroupException();
}
else if (!(this._parent instanceof FormGroupName) && !(this._parent instanceof FormGroupDirective) &&
!(this._parent instanceof FormArrayName)) {
ReactiveErrors.controlParentException();
}
};
FormControlName.prototype._setUpControl = function () {
this._checkParentType();
this.control = this.formDirective.addControl(this);
if (this.control.disabled && this.valueAccessor.setDisabledState) {
this.valueAccessor.setDisabledState(true);
}
this._added = true;
};
var FormControlName_1;
/**
* @description
* Static property used to track whether any ngModel warnings have been sent across
* all instances of FormControlName. Used to support warning config of "once".
*
* @internal
*/
FormControlName._ngModelWarningSentOnce = false;
__decorate([
Input('formControlName'),
__metadata("design:type", String)
], FormControlName.prototype, "name", void 0);
__decorate([
Input('disabled'),
__metadata("design:type", Boolean),
__metadata("design:paramtypes", [Boolean])
], FormControlName.prototype, "isDisabled", null);
__decorate([
Input('ngModel'),
__metadata("design:type", Object)
], FormControlName.prototype, "model", void 0);
__decorate([
Output('ngModelChange'),
__metadata("design:type", Object)
], FormControlName.prototype, "update", void 0);
FormControlName = FormControlName_1 = __decorate([
Directive({ selector: '[formControlName]', providers: [controlNameBinding] }),
__param(0, Optional()), __param(0, Host()), __param(0, SkipSelf()),
__param(1, Optional()), __param(1, Self()), __param(1, Inject(NG_VALIDATORS)),
__param(2, Optional()), __param(2, Self()), __param(2, Inject(NG_ASYNC_VALIDATORS)),
__param(3, Optional()), __param(3, Self()), __param(3, Inject(NG_VALUE_ACCESSOR)),
__param(4, Optional()), __param(4, Inject(NG_MODEL_WITH_FORM_CONTROL_WARNING)),
__metadata("design:paramtypes", [ControlContainer,
Array,
Array, Array, Object])
], FormControlName);
return FormControlName;
}(NgControl));
/**
* @license
* Copyright Google Inc. 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
*/
var REQUIRED_VALIDATOR = {
provide: NG_VALIDATORS,
useExisting: forwardRef(function () { return RequiredValidator; }),
multi: true
};
var CHECKBOX_REQUIRED_VALIDATOR = {
provide: NG_VALIDATORS,
useExisting: forwardRef(function () { return CheckboxRequiredValidator; }),
multi: true
};
/**
* A Directive that adds the `required` validator to any controls marked with the
* `required` attribute, via the `NG_VALIDATORS` binding.
*
* @usageNotes
* ### Example
*
* ```
* <input name="fullName" ngModel required>
* ```
*
* @ngModule FormsModule
* @ngModule ReactiveFormsModule
* @publicApi
*/
var RequiredValidator = /** @class */ (function () {
function RequiredValidator() {
}
Object.defineProperty(RequiredValidator.prototype, "required", {
get: function () { return this._required; },
set: function (value) {
this._required = value != null && value !== false && "" + value !== 'false';
if (this._onChange)
this._onChange();
},
enumerable: true,
configurable: true
});
RequiredValidator.prototype.validate = function (control) {
return this.required ? Validators.required(control) : null;
};
RequiredValidator.prototype.registerOnValidatorChange = function (fn) { this._onChange = fn; };
__decorate([
Input(),
__metadata("design:type", Object),
__metadata("design:paramtypes", [Object])
], RequiredValidator.prototype, "required", null);
RequiredValidator = __decorate([
Directive({
selector: ':not([type=checkbox])[required][formControlName],:not([type=checkbox])[required][formControl],:not([type=checkbox])[required][ngModel]',
providers: [REQUIRED_VALIDATOR],
host: { '[attr.required]': 'required ? "" : null' }
})
], RequiredValidator);
return RequiredValidator;
}());
/**
* A Directive that adds the `required` validator to checkbox controls marked with the
* `required` attribute, via the `NG_VALIDATORS` binding.
*
* @usageNotes
* ### Example
*
* ```
* <input type="checkbox" name="active" ngModel required>
* ```
*
* @publicApi
* @ngModule FormsModule
* @ngModule ReactiveFormsModule
*/
var CheckboxRequiredValidator = /** @class */ (function (_super) {
__extends(CheckboxRequiredValidator, _super);
function CheckboxRequiredValidator() {
return _super !== null && _super.apply(this, arguments) || this;
}
CheckboxRequiredValidator.prototype.validate = function (control) {
return this.required ? Validators.requiredTrue(control) : null;
};
CheckboxRequiredValidator = __decorate([
Directive({
selector: 'input[type=checkbox][required][formControlName],input[type=checkbox][required][formControl],input[type=checkbox][required][ngModel]',
providers: [CHECKBOX_REQUIRED_VALIDATOR],
host: { '[attr.required]': 'required ? "" : null' }
})
], CheckboxRequiredValidator);
return CheckboxRequiredValidator;
}(RequiredValidator));
/**
* Provider which adds `EmailValidator` to `NG_VALIDATORS`.
*/
var EMAIL_VALIDATOR = {
provide: NG_VALIDATORS,
useExisting: forwardRef(function () { return EmailValidator; }),
multi: true
};
/**
* A Directive that adds the `email` validator to controls marked with the
* `email` attribute, via the `NG_VALIDATORS` binding.
*
* @usageNotes
* ### Example
*
* ```
* <input type="email" name="email" ngModel email>
* <input type="email" name="email" ngModel email="true">
* <input type="email" name="email" ngModel [email]="true">
* ```
*
* @publicApi
* @ngModule FormsModule
* @ngModule ReactiveFormsModule
*/
var EmailValidator = /** @class */ (function () {
function EmailValidator() {
}
Object.defineProperty(EmailValidator.prototype, "email", {
set: function (value) {
this._enabled = value === '' || value === true || value === 'true';
if (this._onChange)
this._onChange();
},
enumerable: true,
configurable: true
});
EmailValidator.prototype.validate = function (control) {
return this._enabled ? Validators.email(control) : null;
};
EmailValidator.prototype.registerOnValidatorChange = function (fn) { this._onChange = fn; };
__decorate([
Input(),
__metadata("design:type", Object),
__metadata("design:paramtypes", [Object])
], EmailValidator.prototype, "email", null);
EmailValidator = __decorate([
Directive({
selector: '[email][formControlName],[email][formControl],[email][ngModel]',
providers: [EMAIL_VALIDATOR]
})
], EmailValidator);
return EmailValidator;
}());
/**
* Provider which adds `MinLengthValidator` to `NG_VALIDATORS`.
*
* @usageNotes
* ### Example:
*
* {@example common/forms/ts/validators/validators.ts region='min'}
*/
var MIN_LENGTH_VALIDATOR = {
provide: NG_VALIDATORS,
useExisting: forwardRef(function () { return MinLengthValidator; }),
multi: true
};
/**
* A directive which installs the `MinLengthValidator` for any `formControlName`,
* `formControl`, or control with `ngModel` that also has a `minlength` attribute.
*
* @ngModule FormsModule
* @ngModule ReactiveFormsModule
* @publicApi
*/
var MinLengthValidator = /** @class */ (function () {
function MinLengthValidator() {
}
MinLengthValidator.prototype.ngOnChanges = function (changes) {
if ('minlength' in changes) {
this._createValidator();
if (this._onChange)
this._onChange();
}
};
MinLengthValidator.prototype.validate = function (control) {
return this.minlength == null ? null : this._validator(control);
};
MinLengthValidator.prototype.registerOnValidatorChange = function (fn) { this._onChange = fn; };
MinLengthValidator.prototype._createValidator = function () {
this._validator = Validators.minLength(parseInt(this.minlength, 10));
};
__decorate([
Input(),
__metadata("design:type", String)
], MinLengthValidator.prototype, "minlength", void 0);
MinLengthValidator = __decorate([
Directive({
selector: '[minlength][formControlName],[minlength][formControl],[minlength][ngModel]',
providers: [MIN_LENGTH_VALIDATOR],
host: { '[attr.minlength]': 'minlength ? minlength : null' }
})
], MinLengthValidator);
return MinLengthValidator;
}());
/**
* Provider which adds `MaxLengthValidator` to `NG_VALIDATORS`.
*
* @usageNotes
* ### Example:
*
* {@example common/forms/ts/validators/validators.ts region='max'}
*/
var MAX_LENGTH_VALIDATOR = {
provide: NG_VALIDATORS,
useExisting: forwardRef(function () { return MaxLengthValidator; }),
multi: true
};
/**
* A directive which installs the `MaxLengthValidator` for any `formControlName`,
* `formControl`, or control with `ngModel` that also has a `maxlength` attribute.
*
* @ngModule FormsModule
* @ngModule ReactiveFormsModule
* @publicApi
*/
var MaxLengthValidator = /** @class */ (function () {
function MaxLengthValidator() {
}
MaxLengthValidator.prototype.ngOnChanges = function (changes) {
if ('maxlength' in changes) {
this._createValidator();
if (this._onChange)
this._onChange();
}
};
MaxLengthValidator.prototype.validate = function (control) {
return this.maxlength != null ? this._validator(control) : null;
};
MaxLengthValidator.prototype.registerOnValidatorChange = function (fn) { this._onChange = fn; };
MaxLengthValidator.prototype._createValidator = function () {
this._validator = Validators.maxLength(parseInt(this.maxlength, 10));
};
__decorate([
Input(),
__metadata("design:type", String)
], MaxLengthValidator.prototype, "maxlength", void 0);
MaxLengthValidator = __decorate([
Directive({
selector: '[maxlength][formControlName],[maxlength][formControl],[maxlength][ngModel]',
providers: [MAX_LENGTH_VALIDATOR],
host: { '[attr.maxlength]': 'maxlength ? maxlength : null' }
})
], MaxLengthValidator);
return MaxLengthValidator;
}());
var PATTERN_VALIDATOR = {
provide: NG_VALIDATORS,
useExisting: forwardRef(function () { return PatternValidator; }),
multi: true
};
/**
* A Directive that adds the `pattern` validator to any controls marked with the
* `pattern` attribute, via the `NG_VALIDATORS` binding. Uses attribute value
* as the regex to validate Control value against. Follows pattern attribute
* semantics; i.e. regex must match entire Control value.
*
* @usageNotes
* ### Example
*
* ```
* <input [name]="fullName" pattern="[a-zA-Z ]*" ngModel>
* ```
*
* @ngModule FormsModule
* @ngModule ReactiveFormsModule
* @publicApi
*/
var PatternValidator = /** @class */ (function () {
function PatternValidator() {
}
PatternValidator.prototype.ngOnChanges = function (changes) {
if ('pattern' in changes) {
this._createValidator();
if (this._onChange)
this._onChange();
}
};
PatternValidator.prototype.validate = function (control) { return this._validator(control); };
PatternValidator.prototype.registerOnValidatorChange = function (fn) { this._onChange = fn; };
PatternValidator.prototype._createValidator = function () { this._validator = Validators.pattern(this.pattern); };
__decorate([
Input(),
__metadata("design:type", Object)
], PatternValidator.prototype, "pattern", void 0);
PatternValidator = __decorate([
Directive({
selector: '[pattern][formControlName],[pattern][formControl],[pattern][ngModel]',
providers: [PATTERN_VALIDATOR],
host: { '[attr.pattern]': 'pattern ? pattern : null' }
})
], PatternValidator);
return PatternValidator;
}());
/**
* @license
* Copyright Google Inc. 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
*/
/**
* @description
* Creates an `AbstractControl` from a user-specified configuration.
*
* The `FormBuilder` provides syntactic sugar that shortens creating instances of a `FormControl`,
* `FormGroup`, or `FormArray`. It reduces the amount of boilerplate needed to build complex
* forms.
*
* @see [Reactive Forms Guide](/guide/reactive-forms)
*
* @publicApi
*/
var FormBuilder = /** @class */ (function () {
function FormBuilder() {
}
/**
* @description
* Construct a new `FormGroup` instance.
*
* @param controlsConfig A collection of child controls. The key for each child is the name
* under which it is registered.
*
* @param legacyOrOpts Configuration options object for the `FormGroup`. The object can
* have two shapes:
*
* 1) `AbstractControlOptions` object (preferred), which consists of:
* * `validators`: A synchronous validator function, or an array of validator functions
* * `asyncValidators`: A single async validator or array of async validator functions
* * `updateOn`: The event upon which the control should be updated (options: 'change' | 'blur' |
* submit')
*
* 2) Legacy configuration object, which consists of:
* * `validator`: A synchronous validator function, or an array of validator functions
* * `asyncValidator`: A single async validator or array of async validator functions
*
*/
FormBuilder.prototype.group = function (controlsConfig, legacyOrOpts) {
if (legacyOrOpts === void 0) { legacyOrOpts = null; }
var controls = this._reduceControls(controlsConfig);
var validators = null;
var asyncValidators = null;
var updateOn = undefined;
if (legacyOrOpts != null &&
(legacyOrOpts.asyncValidator !== undefined || legacyOrOpts.validator !== undefined)) {
// `legacyOrOpts` are legacy form group options
validators = legacyOrOpts.validator != null ? legacyOrOpts.validator : null;
asyncValidators = legacyOrOpts.asyncValidator != null ? legacyOrOpts.asyncValidator : null;
}
else if (legacyOrOpts != null) {
// `legacyOrOpts` are `AbstractControlOptions`
validators = legacyOrOpts.validators != null ? legacyOrOpts.validators : null;
asyncValidators = legacyOrOpts.asyncValidators != null ? legacyOrOpts.asyncValidators : null;
updateOn = legacyOrOpts.updateOn != null ? legacyOrOpts.updateOn : undefined;
}
return new FormGroup(controls, { asyncValidators: asyncValidators, updateOn: updateOn, validators: validators });
};
/**
* @description
* Construct a new `FormControl` with the given state, validators and options.
*
* @param formState Initializes the control with an initial state value, or
* with an object that contains both a value and a disabled status.
*
* @param validatorOrOpts A synchronous validator function, or an array of
* such functions, or an `AbstractControlOptions` object that contains
* validation functions and a validation trigger.
*
* @param asyncValidator A single async validator or array of async validator
* functions.
*
* @usageNotes
*
* ### Initialize a control as disabled
*
* The following example returns a control with an initial value in a disabled state.
*
* <code-example path="forms/ts/formBuilder/form_builder_example.ts"
* linenums="false" region="disabled-control">
* </code-example>
*/
FormBuilder.prototype.control = function (formState, validatorOrOpts, asyncValidator) {
return new FormControl(formState, validatorOrOpts, asyncValidator);
};
/**
* Constructs a new `FormArray` from the given array of configurations,
* validators and options.
*
* @param controlsConfig An array of child controls or control configs. Each
* child control is given an index when it is registered.
*
* @param validatorOrOpts A synchronous validator function, or an array of
* such functions, or an `AbstractControlOptions` object that contains
* validation functions and a validation trigger.
*
* @param asyncValidator A single async validator or array of async validator
* functions.
*/
FormBuilder.prototype.array = function (controlsConfig, validatorOrOpts, asyncValidator) {
var _this = this;
var controls = controlsConfig.map(function (c) { return _this._createControl(c); });
return new FormArray(controls, validatorOrOpts, asyncValidator);
};
/** @internal */
FormBuilder.prototype._reduceControls = function (controlsConfig) {
var _this = this;
var controls = {};
Object.keys(controlsConfig).forEach(function (controlName) {
controls[controlName] = _this._createControl(controlsConfig[controlName]);
});
return controls;
};
/** @internal */
FormBuilder.prototype._createControl = function (controlConfig) {
if (controlConfig instanceof FormControl || controlConfig instanceof FormGroup ||
controlConfig instanceof FormArray) {
return controlConfig;
}
else if (Array.isArray(controlConfig)) {
var value = controlConfig[0];
var validator = controlConfig.length > 1 ? controlConfig[1] : null;
var asyncValidator = controlConfig.length > 2 ? controlConfig[2] : null;
return this.control(value, validator, asyncValidator);
}
else {
return this.control(controlConfig);
}
};
FormBuilder = __decorate([
Injectable()
], FormBuilder);
return FormBuilder;
}());
/**
* @license
* Copyright Google Inc. 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
*/
/**
* @publicApi
*/
var VERSION = new Version('7.1.2');
/**
* @license
* Copyright Google Inc. 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
*/
/**
* @description
*
* Adds `novalidate` attribute to all forms by default.
*
* `novalidate` is used to disable browser's native form validation.
*
* If you want to use native validation with Angular forms, just add `ngNativeValidate` attribute:
*
* ```
* <form ngNativeValidate></form>
* ```
*
* @publicApi
* @ngModule ReactiveFormsModule
* @ngModule FormsModule
*/
var NgNoValidate = /** @class */ (function () {
function NgNoValidate() {
}
NgNoValidate = __decorate([
Directive({
selector: 'form:not([ngNoForm]):not([ngNativeValidate])',
host: { 'novalidate': '' },
})
], NgNoValidate);
return NgNoValidate;
}());
/**
* @license
* Copyright Google Inc. 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
*/
var SHARED_FORM_DIRECTIVES = [
NgNoValidate,
NgSelectOption,
NgSelectMultipleOption,
DefaultValueAccessor,
NumberValueAccessor,
RangeValueAccessor,
CheckboxControlValueAccessor,
SelectControlValueAccessor,
SelectMultipleControlValueAccessor,
RadioControlValueAccessor,
NgControlStatus,
NgControlStatusGroup,
RequiredValidator,
MinLengthValidator,
MaxLengthValidator,
PatternValidator,
CheckboxRequiredValidator,
EmailValidator,
];
var TEMPLATE_DRIVEN_DIRECTIVES = [NgModel, NgModelGroup, NgForm, NgFormSelectorWarning];
var REACTIVE_DRIVEN_DIRECTIVES = [FormControlDirective, FormGroupDirective, FormControlName, FormGroupName, FormArrayName];
/**
* Internal module used for sharing directives between FormsModule and ReactiveFormsModule
*/
var InternalFormsSharedModule = /** @class */ (function () {
function InternalFormsSharedModule() {
}
InternalFormsSharedModule = __decorate([
NgModule({
declarations: SHARED_FORM_DIRECTIVES,
exports: SHARED_FORM_DIRECTIVES,
})
], InternalFormsSharedModule);
return InternalFormsSharedModule;
}());
/**
* @license
* Copyright Google Inc. 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
*/
/**
* Exports the required providers and directives for template-driven forms,
* making them available for import by NgModules that import this module.
* @see [Forms](guide/forms)
*
* @see [Forms Guide](/guide/forms)
*
* @publicApi
*/
var FormsModule = /** @class */ (function () {
function FormsModule() {
}
FormsModule_1 = FormsModule;
/**
* @description
* Provides options for configuring the template-driven forms module.
*
* @param opts An object of configuration options
* * `warnOnDeprecatedNgFormSelector` Configures when to emit a warning when the deprecated
* `ngForm` selector is used.
*/
FormsModule.withConfig = function (opts) {
return {
ngModule: FormsModule_1,
providers: [{ provide: NG_FORM_SELECTOR_WARNING, useValue: opts.warnOnDeprecatedNgFormSelector }]
};
};
var FormsModule_1;
FormsModule = FormsModule_1 = __decorate([
NgModule({
declarations: TEMPLATE_DRIVEN_DIRECTIVES,
providers: [RadioControlRegistry],
exports: [InternalFormsSharedModule, TEMPLATE_DRIVEN_DIRECTIVES]
})
], FormsModule);
return FormsModule;
}());
/**
* Exports the required infrastructure and directives for reactive forms,
* making them available for import by NgModules that import this module.
* @see [Forms](guide/reactive-forms)
*
* @see [Reactive Forms Guide](/guide/reactive-forms)
*
* @publicApi
*/
var ReactiveFormsModule = /** @class */ (function () {
function ReactiveFormsModule() {
}
ReactiveFormsModule_1 = ReactiveFormsModule;
/**
* @description
* Provides options for configuring the reactive forms module.
*
* @param opts An object of configuration options
* * `warnOnNgModelWithFormControl` Configures when to emit a warning when an `ngModel`
* binding is used with reactive form directives.
*/
ReactiveFormsModule.withConfig = function (opts) {
return {
ngModule: ReactiveFormsModule_1,
providers: [{
provide: NG_MODEL_WITH_FORM_CONTROL_WARNING,
useValue: opts.warnOnNgModelWithFormControl
}]
};
};
var ReactiveFormsModule_1;
ReactiveFormsModule = ReactiveFormsModule_1 = __decorate([
NgModule({
declarations: [REACTIVE_DRIVEN_DIRECTIVES],
providers: [FormBuilder, RadioControlRegistry],
exports: [InternalFormsSharedModule, REACTIVE_DRIVEN_DIRECTIVES]
})
], ReactiveFormsModule);
return ReactiveFormsModule;
}());
/**
* @license
* Copyright Google Inc. 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
*/
/**
* @license
* Copyright Google Inc. 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
*/
// This file only reexports content of the `src` folder. Keep it that way.
/**
* @license
* Copyright Google Inc. 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
*/
/**
* Generated bundle index. Do not edit.
*/
export { InternalFormsSharedModule as ɵangular_packages_forms_forms_bc, REACTIVE_DRIVEN_DIRECTIVES as ɵangular_packages_forms_forms_bb, SHARED_FORM_DIRECTIVES as ɵangular_packages_forms_forms_z, TEMPLATE_DRIVEN_DIRECTIVES as ɵangular_packages_forms_forms_ba, CHECKBOX_VALUE_ACCESSOR as ɵangular_packages_forms_forms_a, DEFAULT_VALUE_ACCESSOR as ɵangular_packages_forms_forms_b, AbstractControlStatus as ɵangular_packages_forms_forms_c, ngControlStatusHost as ɵangular_packages_forms_forms_d, formDirectiveProvider as ɵangular_packages_forms_forms_e, NG_FORM_SELECTOR_WARNING as ɵangular_packages_forms_forms_f, formControlBinding as ɵangular_packages_forms_forms_g, modelGroupProvider as ɵangular_packages_forms_forms_h, NgNoValidate as ɵangular_packages_forms_forms_bh, NUMBER_VALUE_ACCESSOR as ɵangular_packages_forms_forms_bd, NumberValueAccessor as ɵangular_packages_forms_forms_be, RADIO_VALUE_ACCESSOR as ɵangular_packages_forms_forms_i, RadioControlRegistry as ɵangular_packages_forms_forms_j, RANGE_VALUE_ACCESSOR as ɵangular_packages_forms_forms_bf, RangeValueAccessor as ɵangular_packages_forms_forms_bg, NG_MODEL_WITH_FORM_CONTROL_WARNING as ɵangular_packages_forms_forms_k, formControlBinding$1 as ɵangular_packages_forms_forms_l, controlNameBinding as ɵangular_packages_forms_forms_m, formDirectiveProvider$1 as ɵangular_packages_forms_forms_n, formArrayNameProvider as ɵangular_packages_forms_forms_p, formGroupNameProvider as ɵangular_packages_forms_forms_o, SELECT_VALUE_ACCESSOR as ɵangular_packages_forms_forms_q, NgSelectMultipleOption as ɵangular_packages_forms_forms_s, SELECT_MULTIPLE_VALUE_ACCESSOR as ɵangular_packages_forms_forms_r, CHECKBOX_REQUIRED_VALIDATOR as ɵangular_packages_forms_forms_u, EMAIL_VALIDATOR as ɵangular_packages_forms_forms_v, MAX_LENGTH_VALIDATOR as ɵangular_packages_forms_forms_x, MIN_LENGTH_VALIDATOR as ɵangular_packages_forms_forms_w, PATTERN_VALIDATOR as ɵangular_packages_forms_forms_y, REQUIRED_VALIDATOR as ɵangular_packages_forms_forms_t, AbstractControlDirective, AbstractFormGroupDirective, CheckboxControlValueAccessor, ControlContainer, NG_VALUE_ACCESSOR, COMPOSITION_BUFFER_MODE, DefaultValueAccessor, NgControl, NgControlStatus, NgControlStatusGroup, NgForm, NgFormSelectorWarning, NgModel, NgModelGroup, RadioControlValueAccessor, FormControlDirective, FormControlName, FormGroupDirective, FormArrayName, FormGroupName, NgSelectOption, SelectControlValueAccessor, SelectMultipleControlValueAccessor, CheckboxRequiredValidator, EmailValidator, MaxLengthValidator, MinLengthValidator, PatternValidator, RequiredValidator, FormBuilder, AbstractControl, FormArray, FormControl, FormGroup, NG_ASYNC_VALIDATORS, NG_VALIDATORS, Validators, VERSION, FormsModule, ReactiveFormsModule };
//# sourceMappingURL=forms.js.map
|
// Search UI Event Logger
// Tracks events, but no data is recorded
//
// Alex Roberts @ Creative Commons, 2010
//
// Some data may be used for processing, differentials and time tracking
// All logs are stored privately and for internal use only
//
// Requirements: jQuery
// Quick and dirty user id for a single page load session s
var id = 'xxxxxGxx'.replace(/[xy]/g, function(c) {var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);return v.toString(16);}).toUpperCase();
var baseUrl = '/demos/search/search1/elog/elog.php?';
$(function() {
// page has loaded!
log ("page_load");
// now set up event handlers
$("#query").blur (function() { log("query_changed"); });
$("#engineSelect").change (function() { log("engine_changed"); });
$("#submit").click (function() { log("submit_clicked"); });
$("#comm").click (function() { log("commercial_clicked"); });
$("#deriv").click (function() { log("deriv_clicked"); });
$("#betaRevert").click (function() { log("beta_revert_clicked"); });
})
function log(value) {
console.log (baseUrl + "id=" + id + "&event=" + value);
$.get(baseUrl + "id=" + id + "&event=" + value);
}
|
import "./setup";
import {expect} from "chai";
import {mount} from "avoriaz";
import moment from "moment";
import {insertHTML} from "./utils";
import BtrzDateRange from "../src/btrz-date-range";
const dummyLogger = {
warn() { return null; },
error() { return null; },
info() { return null; }
};
describe("BtrzDateRange", () => {
it("Should render two btrz-date-input.", () => {
insertHTML(`<div id="app">
<btrz-date-range
id='travelDate'
lang='en'
start-date-name='startDateName'
start-date-label='Start Date'
end-date-name='endDateName'
end-date-label='End Date'
submitFormat=''>
</btrz-date-range>
</div>`);
const app = new Vue({
el: "#app",
components: {BtrzDateRange}
}),
dateInput = $("#app .picker__input");
expect(dateInput.length).to.equal(2);
});
it("Should use the given labels for start and end date input.", () => {
insertHTML(`<div id="app">
<btrz-date-range
id='travelDate'
lang='en'
start-date-name='startDateName'
start-date-label='Start Date'
end-date-name='endDateName'
end-date-label='End Date'
submitFormat=''>
</btrz-date-range>
</div>`);
const app = new Vue({
el: "#app",
components: {BtrzDateRange}
}),
label = $("#app label");
expect(label.text().indexOf('Start Date')).to.not.equal(-1);
expect(label.text().indexOf('End Date')).to.not.equal(-1);
});
it("End date and end time Should initialize disabled", () => {
let wrapper = null;
const EXPECTED_DATE = new Date();
let props = {
value: EXPECTED_DATE,
startDateName: 'testStartDateName',
startDateLabel: 'testStartDateLabel',
endDateName: 'testEndDateName',
endDateLabel: 'testEndDateLabel',
displayTime: true,
lang: 'en'
};
wrapper = mount(BtrzDateRange, {
data: {logger: dummyLogger},
propsData: props
});
expect(wrapper.vm.$refs.endDate.disabled).to.equal(true);
expect(wrapper.vm.$refs.endTime.disabled).to.equal(true);
});
it("End date picker min value should be start date.", () => {
let wrapper = null;
const EXPECTED_DATE = new Date();
let props = {
value: EXPECTED_DATE,
startDateName: 'testStartDateName',
startDateLabel: 'testStartDateLabel',
endDateName: 'testEndDateName',
endDateLabel: 'testEndDateLabel',
lang: 'en'
};
wrapper = mount(BtrzDateRange, {
data: {logger: dummyLogger},
propsData: props
});
wrapper.vm.$refs.startDate.picker.set("select", EXPECTED_DATE);
const actualDate = wrapper.vm.$refs.startDate.picker.get("select").obj;
expect(moment(wrapper.vm.endDateMinValue).isSame(EXPECTED_DATE, "days")).to.be.ok;
});
});
|
this.wp=this.wp||{},this.wp.editPost=function(e){var t={};function n(r){if(t[r])return t[r].exports;var o=t[r]={i:r,l:!1,exports:{}};return e[r].call(o.exports,o,o.exports,n),o.l=!0,o.exports}return n.m=e,n.c=t,n.d=function(e,t,r){n.o(e,t)||Object.defineProperty(e,t,{configurable:!1,enumerable:!0,get:r})},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=430)}([function(e,t){!function(){e.exports=this.wp.element}()},function(e,t){!function(){e.exports=this.lodash}()},function(e,t){!function(){e.exports=this.wp.i18n}()},function(e,t){e.exports=function(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}},function(e,t){!function(){e.exports=this.wp.components}()},function(e,t){!function(){e.exports=this.wp.data}()},function(e,t){!function(){e.exports=this.wp.compose}()},function(e,t,n){var r=n(172),o=n(144),i=n(111),c=n(24);e.exports=function(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{},a=i(n);"function"==typeof o&&(a=a.concat(o(n).filter(function(e){return r(n,e).enumerable}))),a.forEach(function(t){c(e,t,n[t])})}return e}},function(e,t){var n=e.exports={version:"2.5.7"};"number"==typeof __e&&(__e=n)},function(e,t,n){var r=n(132);function o(e,t){for(var n=0;n<t.length;n++){var o=t[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),r(e,o.key,o)}}e.exports=function(e,t,n){return t&&o(e.prototype,t),n&&o(e,n),e}},function(e,t){e.exports=function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}},function(e,t,n){var r=n(158),o=n(213);e.exports=function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=r(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),t&&o(e,t)}},function(e,t,n){var r=n(219),o=n(157);function i(t){return e.exports=i=o?r:function(e){return e.__proto__||r(e)},i(t)}e.exports=i},function(e,t,n){var r=n(147),o=n(3);e.exports=function(e,t){return!t||"object"!==r(t)&&"function"!=typeof t?o(e):t}},function(e,t){!function(){e.exports=this.wp.blocks}()},,function(e,t){!function(){e.exports=this.wp.editor}()},function(e,t){var n=e.exports="undefined"!=typeof window&&window.Math==Math?window:"undefined"!=typeof self&&self.Math==Math?self:Function("return this")();"number"==typeof __g&&(__g=n)},function(e,t,n){var r=n(61)("wks"),o=n(51),i=n(17).Symbol,c="function"==typeof i;(e.exports=function(e){return r[e]||(r[e]=c&&i[e]||(c?i:o)("Symbol."+e))}).store=r},,function(e,t){var n=e.exports="undefined"!=typeof window&&window.Math==Math?window:"undefined"!=typeof self&&self.Math==Math?self:Function("return this")();"number"==typeof __g&&(__g=n)},function(e,t,n){var r;
/*!
Copyright (c) 2016 Jed Watson.
Licensed under the MIT License (MIT), see
http://jedwatson.github.io/classnames
*/
/*!
Copyright (c) 2016 Jed Watson.
Licensed under the MIT License (MIT), see
http://jedwatson.github.io/classnames
*/
!function(){"use strict";var n={}.hasOwnProperty;function o(){for(var e=[],t=0;t<arguments.length;t++){var r=arguments[t];if(r){var i=typeof r;if("string"===i||"number"===i)e.push(r);else if(Array.isArray(r))e.push(o.apply(null,r));else if("object"===i)for(var c in r)n.call(r,c)&&r[c]&&e.push(c)}}return e.join(" ")}void 0!==e&&e.exports?e.exports=o:void 0===(r=function(){return o}.apply(t,[]))||(e.exports=r)}()},function(e,t,n){e.exports=!n(38)(function(){return 7!=Object.defineProperty({},"a",{get:function(){return 7}}).a})},function(e,t,n){var r=n(26),o=n(81),i=n(67),c=Object.defineProperty;t.f=n(22)?Object.defineProperty:function(e,t,n){if(r(e),t=i(t,!0),r(n),o)try{return c(e,t,n)}catch(e){}if("get"in n||"set"in n)throw TypeError("Accessors not supported!");return"value"in n&&(e[t]=n.value),e}},function(e,t,n){var r=n(132);e.exports=function(e,t,n){return t in e?r(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}},function(e,t,n){var r=n(17),o=n(8),i=n(48),c=n(34),a=n(31),u=function(e,t,n){var l,s,f,p=e&u.F,d=e&u.G,b=e&u.S,m=e&u.P,v=e&u.B,O=e&u.W,h=d?o:o[t]||(o[t]={}),g=h.prototype,y=d?r:b?r[t]:(r[t]||{}).prototype;for(l in d&&(n=t),n)(s=!p&&y&&void 0!==y[l])&&a(h,l)||(f=s?y[l]:n[l],h[l]=d&&"function"!=typeof y[l]?n[l]:v&&s?i(f,r):O&&y[l]==f?function(e){var t=function(t,n,r){if(this instanceof e){switch(arguments.length){case 0:return new e;case 1:return new e(t);case 2:return new e(t,n)}return new e(t,n,r)}return e.apply(this,arguments)};return t.prototype=e.prototype,t}(f):m&&"function"==typeof f?i(Function.call,f):f,m&&((h.virtual||(h.virtual={}))[l]=f,e&u.R&&g&&!g[l]&&c(g,l,f)))};u.F=1,u.G=2,u.S=4,u.P=8,u.B=16,u.W=32,u.U=64,u.R=128,e.exports=u},function(e,t,n){var r=n(28);e.exports=function(e){if(!r(e))throw TypeError(e+" is not an object!");return e}},function(e,t,n){var r=n(143);function o(){return e.exports=o=r||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},o.apply(this,arguments)}e.exports=o},function(e,t){e.exports=function(e){return"object"==typeof e?null!==e:"function"==typeof e}},function(e,t,n){e.exports=!n(40)(function(){return 7!=Object.defineProperty({},"a",{get:function(){return 7}}).a})},function(e,t,n){var r=n(43).f,o=Function.prototype,i=/^\s*function ([^ (]*)/;"name"in o||n(29)&&r(o,"name",{configurable:!0,get:function(){try{return(""+this).match(i)[1]}catch(e){return""}}})},function(e,t){var n={}.hasOwnProperty;e.exports=function(e,t){return n.call(e,t)}},function(e,t,n){var r=n(185),o=n(176),i=n(178);e.exports=function(e){return r(e)||o(e)||i()}},function(e,t,n){var r=n(78),o=n(56);e.exports=function(e){return r(o(e))}},function(e,t,n){var r=n(23),o=n(44);e.exports=n(22)?function(e,t,n){return r.f(e,t,o(1,n))}:function(e,t,n){return e[t]=n,e}},function(e,t){!function(){e.exports=this.wp.keycodes}()},function(e,t,n){var r=n(87)("wks"),o=n(57),i=n(20).Symbol,c="function"==typeof i;(e.exports=function(e){return r[e]||(r[e]=c&&i[e]||(c?i:o)("Symbol."+e))}).store=r},function(e,t,n){var r=n(43),o=n(73);e.exports=n(29)?function(e,t,n){return r.f(e,t,o(1,n))}:function(e,t,n){return e[t]=n,e}},function(e,t){e.exports=function(e){try{return!!e()}catch(e){return!0}}},function(e,t){e.exports=function(e){return"object"==typeof e?null!==e:"function"==typeof e}},function(e,t){e.exports=function(e){try{return!!e()}catch(e){return!0}}},function(e,t){e.exports={}},function(e,t,n){var r=n(144),o=n(247);e.exports=function(e,t){if(null==e)return{};var n,i,c=o(e,t);if(r){var a=r(e);for(i=0;i<a.length;i++)n=a[i],t.indexOf(n)>=0||Object.prototype.propertyIsEnumerable.call(e,n)&&(c[n]=e[n])}return c}},function(e,t,n){var r=n(50),o=n(85),i=n(76),c=Object.defineProperty;t.f=n(29)?Object.defineProperty:function(e,t,n){if(r(e),t=i(t,!0),r(n),o)try{return c(e,t,n)}catch(e){}if("get"in n||"set"in n)throw TypeError("Accessors not supported!");return"value"in n&&(e[t]=n.value),e}},function(e,t){e.exports=function(e,t){return{enumerable:!(1&e),configurable:!(2&e),writable:!(4&e),value:t}}},function(e,t,n){var r=n(80),o=n(59);e.exports=Object.keys||function(e){return r(e,o)}},function(e,t){var n={}.hasOwnProperty;e.exports=function(e,t){return n.call(e,t)}},function(e,t){e.exports=!0},function(e,t,n){var r=n(69);e.exports=function(e,t,n){if(r(e),void 0===t)return e;switch(n){case 1:return function(n){return e.call(t,n)};case 2:return function(n,r){return e.call(t,n,r)};case 3:return function(n,r,o){return e.call(t,n,r,o)}}return function(){return e.apply(t,arguments)}}},function(e,t,n){var r=n(20),o=n(37),i=n(46),c=n(57)("src"),a=Function.toString,u=(""+a).split("toString");n(58).inspectSource=function(e){return a.call(e)},(e.exports=function(e,t,n,a){var l="function"==typeof n;l&&(i(n,"name")||o(n,"name",t)),e[t]!==n&&(l&&(i(n,c)||o(n,c,e[t]?""+e[t]:u.join(String(t)))),e===r?e[t]=n:a?e[t]?e[t]=n:o(e,t,n):(delete e[t],o(e,t,n)))})(Function.prototype,"toString",function(){return"function"==typeof this&&this[c]||a.call(this)})},function(e,t,n){var r=n(39);e.exports=function(e){if(!r(e))throw TypeError(e+" is not an object!");return e}},function(e,t){var n=0,r=Math.random();e.exports=function(e){return"Symbol(".concat(void 0===e?"":e,")_",(++n+r).toString(36))}},function(e,t){var n={}.toString;e.exports=function(e){return n.call(e).slice(8,-1)}},function(e,t,n){var r=n(56);e.exports=function(e){return Object(r(e))}},function(e,t){var n=Math.ceil,r=Math.floor;e.exports=function(e){return isNaN(e=+e)?0:(e>0?r:n)(e)}},function(e,t,n){var r=n(61)("keys"),o=n(51);e.exports=function(e){return r[e]||(r[e]=o(e))}},function(e,t){e.exports=function(e){if(void 0==e)throw TypeError("Can't call method on "+e);return e}},function(e,t){var n=0,r=Math.random();e.exports=function(e){return"Symbol(".concat(void 0===e?"":e,")_",(++n+r).toString(36))}},function(e,t){var n=e.exports={version:"2.5.7"};"number"==typeof __e&&(__e=n)},function(e,t){e.exports="constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf".split(",")},function(e,t,n){var r=n(23).f,o=n(31),i=n(18)("toStringTag");e.exports=function(e,t,n){e&&!o(e=n?e:e.prototype,i)&&r(e,i,{configurable:!0,value:t})}},function(e,t,n){var r=n(8),o=n(17),i=o["__core-js_shared__"]||(o["__core-js_shared__"]={});(e.exports=function(e,t){return i[e]||(i[e]=void 0!==t?t:{})})("versions",[]).push({version:r.version,mode:n(47)?"pure":"global",copyright:"© 2018 Denis Pushkarev (zloirock.ru)"})},function(e,t){!function(){e.exports=this.wp.hooks}()},,,function(e,t){e.exports=function(e){if(void 0==e)throw TypeError("Can't call method on "+e);return e}},function(e,t,n){var r=n(28),o=n(17).document,i=r(o)&&r(o.createElement);e.exports=function(e){return i?o.createElement(e):{}}},function(e,t,n){var r=n(28);e.exports=function(e,t){if(!r(e))return e;var n,o;if(t&&"function"==typeof(n=e.toString)&&!r(o=n.call(e)))return o;if("function"==typeof(n=e.valueOf)&&!r(o=n.call(e)))return o;if(!t&&"function"==typeof(n=e.toString)&&!r(o=n.call(e)))return o;throw TypeError("Can't convert object to primitive value")}},function(e,t,n){"use strict";var r=n(131)(!0);n(83)(String,"String",function(e){this._t=String(e),this._i=0},function(){var e,t=this._t,n=this._i;return n>=t.length?{value:void 0,done:!0}:(e=r(t,n),this._i+=e.length,{value:e,done:!1})})},function(e,t){e.exports=function(e){if("function"!=typeof e)throw TypeError(e+" is not a function!");return e}},function(e,t){t.f={}.propertyIsEnumerable},function(e,t,n){var r=n(54),o=Math.min;e.exports=function(e){return e>0?o(r(e),9007199254740991):0}},function(e,t,n){var r=n(137),o=n(65);e.exports=function(e){return r(o(e))}},function(e,t){e.exports=function(e,t){return{enumerable:!(1&e),configurable:!(2&e),writable:!(4&e),value:t}}},function(e,t,n){var r=n(26),o=n(114),i=n(59),c=n(55)("IE_PROTO"),a=function(){},u=function(){var e,t=n(66)("iframe"),r=i.length;for(t.style.display="none",n(97).appendChild(t),t.src="javascript:",(e=t.contentWindow.document).open(),e.write("<script>document.F=Object<\/script>"),e.close(),u=e.F;r--;)delete u.prototype[i[r]];return u()};e.exports=Object.create||function(e,t){var n;return null!==e?(a.prototype=r(e),n=new a,a.prototype=null,n[c]=e):n=u(),void 0===t?n:o(n,t)}},function(e,t,n){var r=n(196),o=n(207),i=n(195);e.exports=function(e,t){return r(e)||o(e,t)||i()}},function(e,t,n){var r=n(39);e.exports=function(e,t){if(!r(e))return e;var n,o;if(t&&"function"==typeof(n=e.toString)&&!r(o=n.call(e)))return o;if("function"==typeof(n=e.valueOf)&&!r(o=n.call(e)))return o;if(!t&&"function"==typeof(n=e.toString)&&!r(o=n.call(e)))return o;throw TypeError("Can't convert object to primitive value")}},function(e,t,n){n(129);for(var r=n(17),o=n(34),i=n(41),c=n(18)("toStringTag"),a="CSSRuleList,CSSStyleDeclaration,CSSValueList,ClientRectList,DOMRectList,DOMStringList,DOMTokenList,DataTransferItemList,FileList,HTMLAllCollection,HTMLCollection,HTMLFormElement,HTMLSelectElement,MediaList,MimeTypeArray,NamedNodeMap,NodeList,PaintRequestList,Plugin,PluginArray,SVGLengthList,SVGNumberList,SVGPathSegList,SVGPointList,SVGStringList,SVGTransformList,SourceBufferList,StyleSheetList,TextTrackCueList,TextTrackList,TouchList".split(","),u=0;u<a.length;u++){var l=a[u],s=r[l],f=s&&s.prototype;f&&!f[c]&&o(f,c,l),i[l]=i.Array}},function(e,t,n){var r=n(52);e.exports=Object("z").propertyIsEnumerable(0)?Object:function(e){return"String"==r(e)?e.split(""):Object(e)}},function(e,t,n){var r=n(39),o=n(20).document,i=r(o)&&r(o.createElement);e.exports=function(e){return i?o.createElement(e):{}}},function(e,t,n){var r=n(31),o=n(33),i=n(106)(!1),c=n(55)("IE_PROTO");e.exports=function(e,t){var n,a=o(e),u=0,l=[];for(n in a)n!=c&&r(a,n)&&l.push(n);for(;t.length>u;)r(a,n=t[u++])&&(~i(l,n)||l.push(n));return l}},function(e,t,n){e.exports=!n(22)&&!n(38)(function(){return 7!=Object.defineProperty(n(66)("div"),"a",{get:function(){return 7}}).a})},function(e,t,n){var r=n(87)("keys"),o=n(57);e.exports=function(e){return r[e]||(r[e]=o(e))}},function(e,t,n){"use strict";var r=n(47),o=n(25),i=n(94),c=n(34),a=n(41),u=n(130),l=n(60),s=n(110),f=n(18)("iterator"),p=!([].keys&&"next"in[].keys()),d=function(){return this};e.exports=function(e,t,n,b,m,v,O){u(n,t,b);var h,g,y,j=function(e){if(!p&&e in x)return x[e];switch(e){case"keys":case"values":return function(){return new n(this,e)}}return function(){return new n(this,e)}},E=t+" Iterator",S="values"==m,_=!1,x=e.prototype,P=x[f]||x["@@iterator"]||m&&x[m],w=P||j(m),T=m?S?j("entries"):w:void 0,k="Array"==t&&x.entries||P;if(k&&(y=s(k.call(new e)))!==Object.prototype&&y.next&&(l(y,E,!0),r||"function"==typeof y[f]||c(y,f,d)),S&&P&&"values"!==P.name&&(_=!0,w=function(){return P.call(this)}),r&&!O||!p&&!_&&x[f]||c(x,f,w),a[t]=w,a[E]=d,m)if(h={values:S?w:j("values"),keys:v?w:j("keys"),entries:T},O)for(g in h)g in x||i(x,g,h[g]);else o(o.P+o.F*(p||_),t,h);return h}},function(e,t){e.exports={}},function(e,t,n){e.exports=!n(29)&&!n(40)(function(){return 7!=Object.defineProperty(n(79)("div"),"a",{get:function(){return 7}}).a})},function(e,t){e.exports=!1},function(e,t,n){var r=n(58),o=n(20),i=o["__core-js_shared__"]||(o["__core-js_shared__"]={});(e.exports=function(e,t){return i[e]||(i[e]=void 0!==t?t:{})})("versions",[]).push({version:r.version,mode:n(86)?"pure":"global",copyright:"© 2018 Denis Pushkarev (zloirock.ru)"})},function(e,t,n){var r=n(52),o=n(18)("toStringTag"),i="Arguments"==r(function(){return arguments}());e.exports=function(e){var t,n,c;return void 0===e?"Undefined":null===e?"Null":"string"==typeof(n=function(e,t){try{return e[t]}catch(e){}}(t=Object(e),o))?n:i?r(t):"Object"==(c=r(t))&&"function"==typeof t.callee?"Arguments":c}},function(e,t){var n={}.toString;e.exports=function(e){return n.call(e).slice(8,-1)}},function(e,t,n){t.f=n(18)},function(e,t){!function(){e.exports=this.wp.deprecated}()},function(e,t,n){var r=n(25),o=n(8),i=n(38);e.exports=function(e,t){var n=(o.Object||{})[e]||Object[e],c={};c[e]=t(n),r(r.S+r.F*i(function(){n(1)}),"Object",c)}},function(e,t){t.f=Object.getOwnPropertySymbols},function(e,t,n){e.exports=n(34)},function(e,t,n){for(var r=n(141),o=n(119),i=n(49),c=n(20),a=n(37),u=n(84),l=n(36),s=l("iterator"),f=l("toStringTag"),p=u.Array,d={CSSRuleList:!0,CSSStyleDeclaration:!1,CSSValueList:!1,ClientRectList:!1,DOMRectList:!1,DOMStringList:!1,DOMTokenList:!0,DataTransferItemList:!1,FileList:!1,HTMLAllCollection:!1,HTMLCollection:!1,HTMLFormElement:!1,HTMLSelectElement:!1,MediaList:!0,MimeTypeArray:!1,NamedNodeMap:!1,NodeList:!0,PaintRequestList:!1,Plugin:!1,PluginArray:!1,SVGLengthList:!1,SVGNumberList:!1,SVGPathSegList:!1,SVGPointList:!1,SVGStringList:!1,SVGTransformList:!1,SourceBufferList:!1,StyleSheetList:!0,TextTrackCueList:!1,TextTrackList:!1,TouchList:!1},b=o(d),m=0;m<b.length;m++){var v,O=b[m],h=d[O],g=c[O],y=g&&g.prototype;if(y&&(y[s]||a(y,s,p),y[f]||a(y,f,O),u[O]=p,h))for(v in r)y[v]||i(y,v,r[v],!0)}},function(e,t){e.exports="constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf".split(",")},function(e,t,n){var r=n(17).document;e.exports=r&&r.documentElement},function(e,t){var n=Math.ceil,r=Math.floor;e.exports=function(e){return isNaN(e=+e)?0:(e>0?r:n)(e)}},function(e,t,n){var r=n(20),o=n(58),i=n(37),c=n(49),a=n(104),u=function(e,t,n){var l,s,f,p,d=e&u.F,b=e&u.G,m=e&u.S,v=e&u.P,O=e&u.B,h=b?r:m?r[t]||(r[t]={}):(r[t]||{}).prototype,g=b?o:o[t]||(o[t]={}),y=g.prototype||(g.prototype={});for(l in b&&(n=t),n)f=((s=!d&&h&&void 0!==h[l])?h:n)[l],p=O&&s?a(f,r):v&&"function"==typeof f?a(Function.call,f):f,h&&c(h,l,f,e&u.U),g[l]!=f&&i(g,l,p),v&&y[l]!=f&&(y[l]=f)};r.core=o,u.F=1,u.G=2,u.S=4,u.P=8,u.B=16,u.W=32,u.U=64,u.R=128,e.exports=u},function(e,t,n){var r=n(17),o=n(8),i=n(47),c=n(90),a=n(23).f;e.exports=function(e){var t=o.Symbol||(o.Symbol=i?{}:r.Symbol||{});"_"==e.charAt(0)||e in t||a(t,e,{value:c.f(e)})}},function(e,t,n){var r=n(70),o=n(44),i=n(33),c=n(67),a=n(31),u=n(81),l=Object.getOwnPropertyDescriptor;t.f=n(22)?l:function(e,t){if(e=i(e),t=c(t,!0),u)try{return l(e,t)}catch(e){}if(a(e,t))return o(!r.f.call(e,t),e[t])}},function(e,t){!function(){e.exports=this.wp.apiFetch}()},,function(e,t,n){var r=n(116);e.exports=function(e,t,n){if(r(e),void 0===t)return e;switch(n){case 1:return function(n){return e.call(t,n)};case 2:return function(n,r){return e.call(t,n,r)};case 3:return function(n,r,o){return e.call(t,n,r,o)}}return function(){return e.apply(t,arguments)}}},function(e,t,n){var r=n(54),o=Math.max,i=Math.min;e.exports=function(e,t){return(e=r(e))<0?o(e+t,0):i(e,t)}},function(e,t,n){var r=n(33),o=n(71),i=n(105);e.exports=function(e){return function(t,n,c){var a,u=r(t),l=o(u.length),s=i(c,l);if(e&&n!=n){for(;l>s;)if((a=u[s++])!=a)return!0}else for(;l>s;s++)if((e||s in u)&&u[s]===n)return e||s||0;return!e&&-1}}},,,function(e,t,n){var r=n(88),o=n(18)("iterator"),i=n(41);e.exports=n(8).getIteratorMethod=function(e){if(void 0!=e)return e[o]||e["@@iterator"]||i[r(e)]}},function(e,t,n){var r=n(31),o=n(53),i=n(55)("IE_PROTO"),c=Object.prototype;e.exports=Object.getPrototypeOf||function(e){return e=o(e),r(e,i)?e[i]:"function"==typeof e.constructor&&e instanceof e.constructor?e.constructor.prototype:e instanceof Object?c:null}},function(e,t,n){e.exports=n(149)},,,function(e,t,n){var r=n(23),o=n(26),i=n(45);e.exports=n(22)?Object.defineProperties:function(e,t){o(e);for(var n,c=i(t),a=c.length,u=0;a>u;)r.f(e,n=c[u++],t[n]);return e}},,function(e,t){e.exports=function(e){if("function"!=typeof e)throw TypeError(e+" is not a function!");return e}},,function(e,t,n){var r=n(43).f,o=n(46),i=n(36)("toStringTag");e.exports=function(e,t,n){e&&!o(e=n?e:e.prototype,i)&&r(e,i,{configurable:!0,value:t})}},function(e,t,n){var r=n(125),o=n(96);e.exports=Object.keys||function(e){return r(e,o)}},function(e,t,n){var r=n(80),o=n(59).concat("length","prototype");t.f=Object.getOwnPropertyNames||function(e){return r(e,o)}},function(e,t,n){e.exports=n(184)},function(e,t,n){var r=n(65);e.exports=function(e){return Object(r(e))}},function(e,t,n){var r=n(98),o=Math.min;e.exports=function(e){return e>0?o(r(e),9007199254740991):0}},function(e,t){e.exports=function(e,t){return{value:t,done:!!e}}},function(e,t,n){var r=n(46),o=n(72),i=n(139)(!1),c=n(82)("IE_PROTO");e.exports=function(e,t){var n,a=o(e),u=0,l=[];for(n in a)n!=c&&r(a,n)&&l.push(n);for(;t.length>u;)r(a,n=t[u++])&&(~i(l,n)||l.push(n));return l}},function(e,t){},function(e,t,n){"use strict";var r=n(17),o=n(31),i=n(22),c=n(25),a=n(94),u=n(135).KEY,l=n(38),s=n(61),f=n(60),p=n(51),d=n(18),b=n(90),m=n(100),v=n(166),O=n(146),h=n(26),g=n(28),y=n(33),j=n(67),E=n(44),S=n(74),_=n(165),x=n(101),P=n(23),w=n(45),T=x.f,k=P.f,A=_.f,M=r.Symbol,C=r.JSON,B=C&&C.stringify,I=d("_hidden"),N=d("toPrimitive"),L={}.propertyIsEnumerable,D=s("symbol-registry"),F=s("symbols"),G=s("op-symbols"),R=Object.prototype,U="function"==typeof M,V=r.QObject,H=!V||!V.prototype||!V.prototype.findChild,W=i&&l(function(){return 7!=S(k({},"a",{get:function(){return k(this,"a",{value:7}).a}})).a})?function(e,t,n){var r=T(R,t);r&&delete R[t],k(e,t,n),r&&e!==R&&k(R,t,r)}:k,q=function(e){var t=F[e]=S(M.prototype);return t._k=e,t},z=U&&"symbol"==typeof M.iterator?function(e){return"symbol"==typeof e}:function(e){return e instanceof M},X=function(e,t,n){return e===R&&X(G,t,n),h(e),t=j(t,!0),h(n),o(F,t)?(n.enumerable?(o(e,I)&&e[I][t]&&(e[I][t]=!1),n=S(n,{enumerable:E(0,!1)})):(o(e,I)||k(e,I,E(1,{})),e[I][t]=!0),W(e,t,n)):k(e,t,n)},Q=function(e,t){h(e);for(var n,r=v(t=y(t)),o=0,i=r.length;i>o;)X(e,n=r[o++],t[n]);return e},J=function(e){var t=L.call(this,e=j(e,!0));return!(this===R&&o(F,e)&&!o(G,e))&&(!(t||!o(this,e)||!o(F,e)||o(this,I)&&this[I][e])||t)},K=function(e,t){if(e=y(e),t=j(t,!0),e!==R||!o(F,t)||o(G,t)){var n=T(e,t);return!n||!o(F,t)||o(e,I)&&e[I][t]||(n.enumerable=!0),n}},Z=function(e){for(var t,n=A(y(e)),r=[],i=0;n.length>i;)o(F,t=n[i++])||t==I||t==u||r.push(t);return r},Y=function(e){for(var t,n=e===R,r=A(n?G:y(e)),i=[],c=0;r.length>c;)!o(F,t=r[c++])||n&&!o(R,t)||i.push(F[t]);return i};U||(a((M=function(){if(this instanceof M)throw TypeError("Symbol is not a constructor!");var e=p(arguments.length>0?arguments[0]:void 0),t=function(n){this===R&&t.call(G,n),o(this,I)&&o(this[I],e)&&(this[I][e]=!1),W(this,e,E(1,n))};return i&&H&&W(R,e,{configurable:!0,set:t}),q(e)}).prototype,"toString",function(){return this._k}),x.f=K,P.f=X,n(120).f=_.f=Z,n(70).f=J,n(93).f=Y,i&&!n(47)&&a(R,"propertyIsEnumerable",J,!0),b.f=function(e){return q(d(e))}),c(c.G+c.W+c.F*!U,{Symbol:M});for(var $="hasInstance,isConcatSpreadable,iterator,match,replace,search,species,split,toPrimitive,toStringTag,unscopables".split(","),ee=0;$.length>ee;)d($[ee++]);for(var te=w(d.store),ne=0;te.length>ne;)m(te[ne++]);c(c.S+c.F*!U,"Symbol",{for:function(e){return o(D,e+="")?D[e]:D[e]=M(e)},keyFor:function(e){if(!z(e))throw TypeError(e+" is not a symbol!");for(var t in D)if(D[t]===e)return t},useSetter:function(){H=!0},useSimple:function(){H=!1}}),c(c.S+c.F*!U,"Object",{create:function(e,t){return void 0===t?S(e):Q(S(e),t)},defineProperty:X,defineProperties:Q,getOwnPropertyDescriptor:K,getOwnPropertyNames:Z,getOwnPropertySymbols:Y}),C&&c(c.S+c.F*(!U||l(function(){var e=M();return"[null]"!=B([e])||"{}"!=B({a:e})||"{}"!=B(Object(e))})),"JSON",{stringify:function(e){for(var t,n,r=[e],o=1;arguments.length>o;)r.push(arguments[o++]);if(n=t=r[1],(g(t)||void 0!==e)&&!z(e))return O(t)||(t=function(e,t){if("function"==typeof n&&(t=n.call(this,e,t)),!z(t))return t}),r[1]=t,B.apply(C,r)}}),M.prototype[N]||n(34)(M.prototype,N,M.prototype.valueOf),f(M,"Symbol"),f(Math,"Math",!0),f(r.JSON,"JSON",!0)},function(e,t){e.exports=function(){}},function(e,t,n){"use strict";var r=n(128),o=n(124),i=n(41),c=n(33);e.exports=n(83)(Array,"Array",function(e,t){this._t=c(e),this._i=0,this._k=t},function(){var e=this._t,t=this._k,n=this._i++;return!e||n>=e.length?(this._t=void 0,o(1)):o(0,"keys"==t?n:"values"==t?e[n]:[n,e[n]])},"values"),i.Arguments=i.Array,r("keys"),r("values"),r("entries")},function(e,t,n){"use strict";var r=n(74),o=n(44),i=n(60),c={};n(34)(c,n(18)("iterator"),function(){return this}),e.exports=function(e,t,n){e.prototype=r(c,{next:o(1,n)}),i(e,t+" Iterator")}},function(e,t,n){var r=n(54),o=n(56);e.exports=function(e){return function(t,n){var i,c,a=String(o(t)),u=r(n),l=a.length;return u<0||u>=l?e?"":void 0:(i=a.charCodeAt(u))<55296||i>56319||u+1===l||(c=a.charCodeAt(u+1))<56320||c>57343?e?a.charAt(u):i:e?a.slice(u,u+2):c-56320+(i-55296<<10)+65536}}},function(e,t,n){e.exports=n(152)},function(e,t,n){var r=n(41),o=n(18)("iterator"),i=Array.prototype;e.exports=function(e){return void 0!==e&&(r.Array===e||i[o]===e)}},function(e,t,n){var r=n(26);e.exports=function(e,t,n,o){try{return o?t(r(n)[0],n[1]):t(n)}catch(t){var i=e.return;throw void 0!==i&&r(i.call(e)),t}}},function(e,t,n){var r=n(51)("meta"),o=n(28),i=n(31),c=n(23).f,a=0,u=Object.isExtensible||function(){return!0},l=!n(38)(function(){return u(Object.preventExtensions({}))}),s=function(e){c(e,r,{value:{i:"O"+ ++a,w:{}}})},f=e.exports={KEY:r,NEED:!1,fastKey:function(e,t){if(!o(e))return"symbol"==typeof e?e:("string"==typeof e?"S":"P")+e;if(!i(e,r)){if(!u(e))return"F";if(!t)return"E";s(e)}return e[r].i},getWeak:function(e,t){if(!i(e,r)){if(!u(e))return!0;if(!t)return!1;s(e)}return e[r].w},onFreeze:function(e){return l&&f.NEED&&u(e)&&!i(e,r)&&s(e),e}}},function(e,t,n){var r=n(98),o=Math.max,i=Math.min;e.exports=function(e,t){return(e=r(e))<0?o(e+t,0):i(e,t)}},function(e,t,n){var r=n(89);e.exports=Object("z").propertyIsEnumerable(0)?Object:function(e){return"String"==r(e)?e.split(""):Object(e)}},function(e,t,n){var r=n(18)("iterator"),o=!1;try{var i=[7][r]();i.return=function(){o=!0},Array.from(i,function(){throw 2})}catch(e){}e.exports=function(e,t){if(!t&&!o)return!1;var n=!1;try{var i=[7],c=i[r]();c.next=function(){return{done:n=!0}},i[r]=function(){return c},e(i)}catch(e){}return n}},function(e,t,n){var r=n(72),o=n(123),i=n(136);e.exports=function(e){return function(t,n,c){var a,u=r(t),l=o(u.length),s=i(c,l);if(e&&n!=n){for(;l>s;)if((a=u[s++])!=a)return!0}else for(;l>s;s++)if((e||s in u)&&u[s]===n)return e||s||0;return!e&&-1}}},function(e,t,n){var r=n(50),o=n(161),i=n(96),c=n(82)("IE_PROTO"),a=function(){},u=function(){var e,t=n(79)("iframe"),r=i.length;for(t.style.display="none",n(160).appendChild(t),t.src="javascript:",(e=t.contentWindow.document).open(),e.write("<script>document.F=Object<\/script>"),e.close(),u=e.F;r--;)delete u.prototype[i[r]];return u()};e.exports=Object.create||function(e,t){var n;return null!==e?(a.prototype=r(e),n=new a,a.prototype=null,n[c]=e):n=u(),void 0===t?n:o(n,t)}},function(e,t,n){"use strict";var r=n(145),o=n(164),i=n(84),c=n(72);e.exports=n(163)(Array,"Array",function(e,t){this._t=c(e),this._i=0,this._k=t},function(){var e=this._t,t=this._k,n=this._i++;return!e||n>=e.length?(this._t=void 0,o(1)):o(0,"keys"==t?n:"values"==t?e[n]:[n,e[n]])},"values"),i.Arguments=i.Array,r("keys"),r("values"),r("entries")},function(e,t,n){"use strict";var r,o;function i(e){return[e]}function c(e){return!!e&&"object"==typeof e}function a(){var e={clear:function(){e.head=null}};return e}function u(e,t,n){var r;if(e.length!==t.length)return!1;for(r=n;r<e.length;r++)if(e[r]!==t[r])return!1;return!0}r={},o="undefined"!=typeof WeakMap,t.a=function(e,t){var n,l;function s(){n=o?new WeakMap:a()}function f(){var n,r,o,i,c,a=arguments.length;for(i=new Array(a),o=0;o<a;o++)i[o]=arguments[o];for(c=t.apply(null,i),(n=l(c)).isUniqueByDependants||(n.lastDependants&&!u(c,n.lastDependants,0)&&n.clear(),n.lastDependants=c),r=n.head;r;){if(u(r.args,i,1))return r!==n.head&&(r.prev.next=r.next,r.next&&(r.next.prev=r.prev),r.next=n.head,r.prev=null,n.head.prev=r,n.head=r),r.val;r=r.next}return r={val:e.apply(null,i)},i[0]=null,r.args=i,n.head&&(n.head.prev=r,r.next=n.head),n.head=r,r.val}return t||(t=i),l=o?function(e){var t,o,i,u,l=n,s=!0;for(t=0;t<e.length;t++){if(!c(o=e[t])){s=!1;break}l.has(o)?l=l.get(o):(i=new WeakMap,l.set(o,i),l=i)}return l.has(r)||((u=a()).isUniqueByDependants=s,l.set(r,u)),l.get(r)}:function(){return n},f.getDependants=t,f.clear=s,s(),f}},function(e,t,n){e.exports=n(209)},function(e,t,n){e.exports=n(174)},function(e,t,n){var r=n(36)("unscopables"),o=Array.prototype;void 0==o[r]&&n(37)(o,r,{}),e.exports=function(e){o[r][e]=!0}},function(e,t,n){var r=n(52);e.exports=Array.isArray||function(e){return"Array"==r(e)}},function(e,t,n){var r=n(167),o=n(153);function i(e){return(i="function"==typeof o&&"symbol"==typeof r?function(e){return typeof e}:function(e){return e&&"function"==typeof o&&e.constructor===o&&e!==o.prototype?"symbol":typeof e})(e)}function c(t){return"function"==typeof o&&"symbol"===i(r)?e.exports=c=function(e){return i(e)}:e.exports=c=function(e){return e&&"function"==typeof o&&e.constructor===o&&e!==o.prototype?"symbol":i(e)},c(t)}e.exports=c},function(e,t,n){var r=n(53),o=n(45);n(92)("keys",function(){return function(e){return o(r(e))}})},function(e,t,n){n(148),e.exports=n(8).Object.keys},,function(e,t,n){var r=n(25);r(r.S+r.F*!n(22),"Object",{defineProperty:n(23).f})},function(e,t,n){n(151);var r=n(8).Object;e.exports=function(e,t,n){return r.defineProperty(e,t,n)}},function(e,t,n){e.exports=n(193)},function(e,t){!function(){e.exports=this.wp.url}()},,function(e,t,n){var r=n(46),o=n(122),i=n(82)("IE_PROTO"),c=Object.prototype;e.exports=Object.getPrototypeOf||function(e){return e=o(e),r(e,i)?e[i]:"function"==typeof e.constructor&&e instanceof e.constructor?e.constructor.prototype:e instanceof Object?c:null}},function(e,t,n){e.exports=n(216)},function(e,t,n){e.exports=n(190)},,function(e,t,n){var r=n(20).document;e.exports=r&&r.documentElement},function(e,t,n){var r=n(43),o=n(50),i=n(119);e.exports=n(29)?Object.defineProperties:function(e,t){o(e);for(var n,c=i(t),a=c.length,u=0;a>u;)r.f(e,n=c[u++],t[n]);return e}},function(e,t,n){"use strict";var r=n(140),o=n(73),i=n(118),c={};n(37)(c,n(36)("iterator"),function(){return this}),e.exports=function(e,t,n){e.prototype=r(c,{next:o(1,n)}),i(e,t+" Iterator")}},function(e,t,n){"use strict";var r=n(86),o=n(99),i=n(49),c=n(37),a=n(84),u=n(162),l=n(118),s=n(156),f=n(36)("iterator"),p=!([].keys&&"next"in[].keys()),d=function(){return this};e.exports=function(e,t,n,b,m,v,O){u(n,t,b);var h,g,y,j=function(e){if(!p&&e in x)return x[e];switch(e){case"keys":case"values":return function(){return new n(this,e)}}return function(){return new n(this,e)}},E=t+" Iterator",S="values"==m,_=!1,x=e.prototype,P=x[f]||x["@@iterator"]||m&&x[m],w=P||j(m),T=m?S?j("entries"):w:void 0,k="Array"==t&&x.entries||P;if(k&&(y=s(k.call(new e)))!==Object.prototype&&y.next&&(l(y,E,!0),r||"function"==typeof y[f]||c(y,f,d)),S&&P&&"values"!==P.name&&(_=!0,w=function(){return P.call(this)}),r&&!O||!p&&!_&&x[f]||c(x,f,w),a[t]=w,a[E]=d,m)if(h={values:S?w:j("values"),keys:v?w:j("keys"),entries:T},O)for(g in h)g in x||i(x,g,h[g]);else o(o.P+o.F*(p||_),t,h);return h}},function(e,t){e.exports=function(e,t){return{value:t,done:!!e}}},function(e,t,n){var r=n(33),o=n(120).f,i={}.toString,c="object"==typeof window&&window&&Object.getOwnPropertyNames?Object.getOwnPropertyNames(window):[];e.exports.f=function(e){return c&&"[object Window]"==i.call(e)?function(e){try{return o(e)}catch(e){return c.slice()}}(e):o(r(e))}},function(e,t,n){var r=n(45),o=n(93),i=n(70);e.exports=function(e){var t=r(e),n=o.f;if(n)for(var c,a=n(e),u=i.f,l=0;a.length>l;)u.call(e,c=a[l++])&&t.push(c);return t}},function(e,t,n){e.exports=n(194)},function(e,t,n){e.exports=n(206)},,function(e,t,n){var r=n(33),o=n(101).f;n(92)("getOwnPropertyDescriptor",function(){return function(e,t){return o(r(e),t)}})},function(e,t,n){n(170);var r=n(8).Object;e.exports=function(e,t){return r.getOwnPropertyDescriptor(e,t)}},function(e,t,n){e.exports=n(171)},,function(e,t,n){n(127),e.exports=n(8).Object.getOwnPropertySymbols},,function(e,t,n){var r=n(121),o=n(181);e.exports=function(e){if(o(Object(e))||"[object Arguments]"===Object.prototype.toString.call(e))return r(e)}},,function(e,t){e.exports=function(){throw new TypeError("Invalid attempt to spread non-iterable instance")}},function(e,t,n){var r=n(88),o=n(18)("iterator"),i=n(41);e.exports=n(8).isIterable=function(e){var t=Object(e);return void 0!==t[o]||"@@iterator"in t||i.hasOwnProperty(r(t))}},function(e,t,n){n(77),n(68),e.exports=n(179)},function(e,t,n){e.exports=n(180)},function(e,t,n){"use strict";var r=n(23),o=n(44);e.exports=function(e,t,n){t in e?r.f(e,t,o(0,n)):e[t]=n}},function(e,t,n){"use strict";var r=n(48),o=n(25),i=n(53),c=n(134),a=n(133),u=n(71),l=n(182),s=n(109);o(o.S+o.F*!n(138)(function(e){Array.from(e)}),"Array",{from:function(e){var t,n,o,f,p=i(e),d="function"==typeof this?this:Array,b=arguments.length,m=b>1?arguments[1]:void 0,v=void 0!==m,O=0,h=s(p);if(v&&(m=r(m,b>2?arguments[2]:void 0,2)),void 0==h||d==Array&&a(h))for(n=new d(t=u(p.length));t>O;O++)l(n,O,v?m(p[O],O):p[O]);else for(f=h.call(p),n=new d;!(o=f.next()).done;O++)l(n,O,v?c(f,m,[o.value,O],!0):o.value);return n.length=O,n}})},function(e,t,n){n(68),n(183),e.exports=n(8).Array.from},function(e,t){e.exports=function(e){if(Array.isArray(e)){for(var t=0,n=new Array(e.length);t<e.length;t++)n[t]=e[t];return n}}},,,function(e,t,n){"use strict";var r=n(45),o=n(93),i=n(70),c=n(53),a=n(78),u=Object.assign;e.exports=!u||n(38)(function(){var e={},t={},n=Symbol(),r="abcdefghijklmnopqrst";return e[n]=7,r.split("").forEach(function(e){t[e]=e}),7!=u({},e)[n]||Object.keys(u({},t)).join("")!=r})?function(e,t){for(var n=c(e),u=arguments.length,l=1,s=o.f,f=i.f;u>l;)for(var p,d=a(arguments[l++]),b=s?r(d).concat(s(d)):r(d),m=b.length,v=0;m>v;)f.call(d,p=b[v++])&&(n[p]=d[p]);return n}:u},function(e,t,n){var r=n(25);r(r.S,"Object",{create:n(74)})},function(e,t,n){n(189);var r=n(8).Object;e.exports=function(e,t){return r.create(e,t)}},function(e,t,n){n(100)("observable")},function(e,t,n){n(100)("asyncIterator")},function(e,t,n){n(127),n(126),n(192),n(191),e.exports=n(8).Symbol},function(e,t,n){n(68),n(77),e.exports=n(90).f("iterator")},function(e,t){e.exports=function(){throw new TypeError("Invalid attempt to destructure non-iterable instance")}},function(e,t){e.exports=function(e){if(Array.isArray(e))return e}},,,,,,,,,function(e,t,n){var r=n(26),o=n(109);e.exports=n(8).getIterator=function(e){var t=o(e);if("function"!=typeof t)throw TypeError(e+" is not iterable!");return r(t.call(e))}},function(e,t,n){n(77),n(68),e.exports=n(205)},function(e,t,n){var r=n(168);e.exports=function(e,t){var n=[],o=!0,i=!1,c=void 0;try{for(var a,u=r(e);!(o=(a=u.next()).done)&&(n.push(a.value),!t||n.length!==t);o=!0);}catch(e){i=!0,c=e}finally{try{o||null==u.return||u.return()}finally{if(i)throw c}}return n}},function(e,t,n){var r=n(25);r(r.S+r.F,"Object",{assign:n(188)})},function(e,t,n){n(208),e.exports=n(8).Object.assign},,,,function(e,t,n){var r=n(157);function o(t,n){return e.exports=o=r||function(e,t){return e.__proto__=t,e},o(t,n)}e.exports=o},function(e,t,n){var r=n(28),o=n(26),i=function(e,t){if(o(e),!r(t)&&null!==t)throw TypeError(t+": can't set as prototype!")};e.exports={set:Object.setPrototypeOf||("__proto__"in{}?function(e,t,r){try{(r=n(48)(Function.call,n(101).f(Object.prototype,"__proto__").set,2))(e,[]),t=!(e instanceof Array)}catch(e){t=!0}return function(e,n){return i(e,n),t?e.__proto__=n:r(e,n),e}}({},!1):void 0),check:i}},function(e,t,n){var r=n(25);r(r.S,"Object",{setPrototypeOf:n(214).set})},function(e,t,n){n(215),e.exports=n(8).Object.setPrototypeOf},function(e,t,n){var r=n(53),o=n(110);n(92)("getPrototypeOf",function(){return function(e){return o(r(e))}})},function(e,t,n){n(217),e.exports=n(8).Object.getPrototypeOf},function(e,t,n){e.exports=n(218)},,function(e,t){!function(){e.exports=this.wp.viewport}()},,,,,,,,,,,,,,,,,,,,,,,function(e,t,n){var r=n(99),o=n(40),i=n(65),c=/"/g,a=function(e,t,n,r){var o=String(i(e)),a="<"+t;return""!==n&&(a+=" "+n+'="'+String(r).replace(c,""")+'"'),a+">"+o+"</"+t+">"};e.exports=function(e,t){var n={};n[e]=t(a),r(r.P+r.F*o(function(){var t=""[e]('"');return t!==t.toLowerCase()||t.split('"').length>3}),"String",n)}},,,function(e,t,n){var r=n(111);e.exports=function(e,t){if(null==e)return{};var n,o,i={},c=r(e);for(o=0;o<c.length;o++)n=c[o],t.indexOf(n)>=0||(i[n]=e[n]);return i}},,,,,,,,,,function(e,t,n){"use strict";n(244)("small",function(e){return function(){return e(this,"small","","")}})},,,,,,,,function(e,t){!function(){e.exports=this.wp.nux}()},,,,,,function(e,t){!function(){e.exports=this.wp.a11y}()},,,,,,,,,,,,,,,,function(e,t){!function(){e.exports=this.wp.plugins}()},,,,,,,,,,,,,,,,,,,,function(e,t,n){e.exports=function(){"use strict";return function(e){var t={};return function e(t,n){var r;if(Array.isArray(n))for(r=0;r<n.length;r++)e(t,n[r]);else for(r in n)t[r]=(t[r]||[]).concat(n[r])}(t,e),function(e){return function(n){return function(r){var o,i,c=t[r.type],a=n(r);if(c)for(o=0;o<c.length;o++)(i=c[o](r,e))&&e.dispatch(i);return a}}}}}()},,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,function(e,t){!function(){e.exports=this.wp.coreBlocks}()},,,,,,,,,,,,,,,,,,,,function(e,t,n){"use strict";n.r(t);var r={};n.d(r,"openGeneralSidebar",function(){return ae}),n.d(r,"closeGeneralSidebar",function(){return ue}),n.d(r,"openPublishSidebar",function(){return le}),n.d(r,"closePublishSidebar",function(){return se}),n.d(r,"togglePublishSidebar",function(){return fe}),n.d(r,"toggleGeneralSidebarEditorPanel",function(){return pe}),n.d(r,"toggleFeature",function(){return de}),n.d(r,"switchEditorMode",function(){return be}),n.d(r,"togglePinnedPluginItem",function(){return me}),n.d(r,"initializeMetaBoxState",function(){return ve}),n.d(r,"requestMetaBoxUpdates",function(){return Oe}),n.d(r,"metaBoxUpdatesSuccess",function(){return he}),n.d(r,"setMetaBoxSavedData",function(){return ge});var o={};n.d(o,"getEditorMode",function(){return je}),n.d(o,"isEditorSidebarOpened",function(){return Ee}),n.d(o,"isPluginSidebarOpened",function(){return Se}),n.d(o,"getActiveGeneralSidebarName",function(){return _e}),n.d(o,"getPreferences",function(){return xe}),n.d(o,"getPreference",function(){return Pe}),n.d(o,"isPublishSidebarOpened",function(){return we}),n.d(o,"isEditorSidebarPanelOpened",function(){return Te}),n.d(o,"isFeatureActive",function(){return ke}),n.d(o,"isPluginItemPinned",function(){return Ae}),n.d(o,"getMetaBoxes",function(){return Me}),n.d(o,"getMetaBox",function(){return Ce}),n.d(o,"hasMetaBoxes",function(){return Be}),n.d(o,"isSavingMetaBoxes",function(){return Ie});var i=n(0),c=n(410),a=n(5),u=n(91),l=n.n(u),s=(n(725),n(62)),f=n(7),p=n.n(f),d=n(10),b=n.n(d),m=n(9),v=n.n(m),O=n(13),h=n.n(O),g=n(12),y=n.n(g),j=n(11),E=n.n(j),S=n(3),x=n.n(S),P=n(1),w=n(14),T=n(2),k=function(){return wp.media.view.MediaFrame.Post.extend({createStates:function(){this.states.add([new wp.media.controller.Library({id:"gallery",title:wp.media.view.l10n.createGalleryTitle,priority:40,toolbar:"main-gallery",filterable:"uploaded",multiple:"add",editable:!1,library:wp.media.query(_.defaults({type:"image"},this.options.library))}),new wp.media.controller.GalleryEdit({library:this.options.selection,editing:this.options.editing,menu:"gallery",displaySettings:!1,multiple:!0}),new wp.media.controller.GalleryAdd])}})},A=function(e){return Object(P.pick)(e,["sizes","mime","type","subtype","id","url","alt","link","caption"])},M=function(e){return wp.media.query({order:"ASC",orderby:"post__in",perPage:-1,post__in:e,query:!0,type:"image"})},C=function(e){function t(e){var n,r=e.multiple,o=void 0!==r&&r,i=e.type,c=e.gallery,a=void 0!==c&&c,u=e.title,l=void 0===u?Object(T.__)("Select or Upload Media"):u,s=e.modalClass,f=e.value;if(b()(this,t),(n=h()(this,y()(t).apply(this,arguments))).openModal=n.openModal.bind(x()(x()(n))),n.onOpen=n.onOpen.bind(x()(x()(n))),n.onSelect=n.onSelect.bind(x()(x()(n))),n.onUpdate=n.onUpdate.bind(x()(x()(n))),n.onClose=n.onClose.bind(x()(x()(n))),n.processMediaCaption=n.processMediaCaption.bind(x()(x()(n))),a){var p=f?"gallery-edit":"gallery",d=k(),m=M(f),v=new wp.media.model.Selection(m.models,{props:m.props.toJSON(),multiple:o});n.frame=new d({mimeType:i,state:p,multiple:o,selection:v,editing:!!f}),wp.media.frame=n.frame}else{var O={title:l,button:{text:Object(T.__)("Select")},multiple:o};i&&(O.library={type:i}),n.frame=wp.media(O)}return s&&n.frame.$el.addClass(s),n.frame.on("select",n.onSelect),n.frame.on("update",n.onUpdate),n.frame.on("open",n.onOpen),n.frame.on("close",n.onClose),n}return E()(t,e),v()(t,[{key:"componentWillUnmount",value:function(){this.frame.remove()}},{key:"onUpdate",value:function(e){var t=this,n=this.props,r=n.onSelect,o=n.multiple,i=void 0!==o&&o,c=this.frame.state(),a=e||c.get("selection");a&&a.models.length&&r(i?a.models.map(function(e){return t.processMediaCaption(A(e.toJSON()))}):this.processMediaCaption(A(a.models[0].toJSON())))}},{key:"onSelect",value:function(){var e=this.props,t=e.onSelect,n=e.multiple,r=void 0!==n&&n,o=this.frame.state().get("selection").toJSON();t(r?o.map(this.processMediaCaption):this.processMediaCaption(o[0]))}},{key:"onOpen",value:function(){if(this.props.value){if(!this.props.gallery){var e=this.frame.state().get("selection");Object(P.castArray)(this.props.value).map(function(t){e.add(wp.media.attachment(t))})}M(Object(P.castArray)(this.props.value)).more()}}},{key:"onClose",value:function(){var e=this.props.onClose;e&&e()}},{key:"openModal",value:function(){this.frame.open()}},{key:"processMediaCaption",value:function(e){return e.caption?p()({},e,{caption:Object(w.parseWithAttributeSchema)(e.caption,{source:"children"})}):e}},{key:"render",value:function(){return this.props.render({open:this.openModal})}}]),t}(i.Component);Object(s.addFilter)("editor.MediaUpload","core/edit-post/components/media-upload/replace-media-upload",function(){return C});var B=n(32),I=n.n(B),N=n(4),L=n(6);var D=Object(L.compose)(Object(a.withSelect)(function(e){return{editedPostContent:e("core/editor").getEditedPostAttribute("content")}}),Object(L.withState)({hasCopied:!1}))(function(e){var t=e.editedPostContent,n=e.hasCopied,r=e.setState;return Object(i.createElement)(N.ClipboardButton,{text:t,className:"components-menu-item__button",onCopy:function(){return r({hasCopied:!0})},onFinishCopy:function(){return r({hasCopied:!1})}},n?Object(T.__)("Copied!"):Object(T.__)("Copy All Content"))});Object(s.addFilter)("editPost.MoreMenu.tools","core/edit-post/more-menu/withCopyContentMenuItem",function(e){return I()(e).concat([Object(i.createElement)(D,{key:"copy-content-menu-item"})])});var F=n(27),G=n.n(F),R=n(42),U=n.n(R),V=(n(30),n(16)),H=Object(L.compose)(Object(a.withSelect)(function(e,t){var n=e("core/editor").getBlocks();if(Object(w.hasBlockSupport)(t.name,"multiple",!0))return{};var r=Object(P.find)(n,function(e){var n=e.name;return t.name===n});return{originalBlockClientId:r&&r.clientId!==t.clientId&&r.clientId}}),Object(a.withDispatch)(function(e,t){var n=t.originalBlockClientId;return{selectFirst:function(){return e("core/editor").selectBlock(n)}}})),W=Object(L.createHigherOrderComponent)(function(e){return H(function(t){var n=t.originalBlockClientId,r=t.selectFirst,o=U()(t,["originalBlockClientId","selectFirst"]);if(!n)return Object(i.createElement)(e,o);var c=Object(w.getBlockType)(o.name),a=function(e){var t=Object(w.findTransform)(Object(w.getBlockTransforms)("to",e),function(e){var t=e.type,n=e.blocks;return"block"===t&&1===n.length});if(!t)return null;return Object(w.getBlockType)(t.blocks[0])}(o.name);return[Object(i.createElement)("div",{key:"invalid-preview",style:{minHeight:"60px"}},Object(i.createElement)(e,G()({key:"block-edit"},o))),Object(i.createElement)(V.Warning,{key:"multiple-use-warning",actions:[Object(i.createElement)(N.Button,{key:"find-original",isLarge:!0,onClick:r},Object(T.__)("Find original")),Object(i.createElement)(N.Button,{key:"remove",isLarge:!0,onClick:function(){return o.onReplace([])}},Object(T.__)("Remove")),a&&Object(i.createElement)(N.Button,{key:"transform",isLarge:!0,onClick:function(){return o.onReplace(Object(w.createBlock)(a.name,o.attributes))}},Object(T.__)("Transform into:")," ",a.title)]},Object(i.createElement)("strong",null,c.title,": "),Object(T.__)("This block may not be used more than once."))]})},"withMultipleValidation");Object(s.addFilter)("editor.BlockEdit","core/edit-post/validate-multiple-use/with-multiple-validation",W);var q=n(24),z=n.n(q),X={editorMode:"visual",activeGeneralSidebar:"edit-post/document",panels:{"post-status":!0},features:{fixedToolbar:!1},pinnedPluginItems:{}},Q=Object(a.combineReducers)({activeGeneralSidebar:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:X.activeGeneralSidebar,t=arguments.length>1?arguments[1]:void 0;switch(t.type){case"OPEN_GENERAL_SIDEBAR":return t.name;case"CLOSE_GENERAL_SIDEBAR":return null;case"SERIALIZE":if("edit-post/block"===e)return X.activeGeneralSidebar}return e},panels:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:X.panels,t=arguments.length>1?arguments[1]:void 0;return"TOGGLE_GENERAL_SIDEBAR_EDITOR_PANEL"===t.type?p()({},e,z()({},t.panel,!e[t.panel])):e},features:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:X.features,t=arguments.length>1?arguments[1]:void 0;return"TOGGLE_FEATURE"===t.type?p()({},e,z()({},t.feature,!e[t.feature])):e},editorMode:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:X.editorMode,t=arguments.length>1?arguments[1]:void 0;return"SWITCH_MODE"===t.type?t.mode:e},pinnedPluginItems:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:X.pinnedPluginItems,t=arguments.length>1?arguments[1]:void 0;return"TOGGLE_PINNED_PLUGIN_ITEM"===t.type?p()({},e,z()({},t.pluginName,!Object(P.get)(e,[t.pluginName],!0))):e}});var J=["normal","side","advanced"],K=J.reduce(function(e,t){return e[t]={isActive:!1},e},{});var Z=Object(a.combineReducers)({preferences:Q,panel:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"document",t=arguments.length>1?arguments[1]:void 0;switch(t.type){case"SET_ACTIVE_PANEL":return t.panel}return e},publishSidebarActive:function(){var e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];switch((arguments.length>1?arguments[1]:void 0).type){case"OPEN_PUBLISH_SIDEBAR":return!0;case"CLOSE_PUBLISH_SIDEBAR":return!1;case"TOGGLE_PUBLISH_SIDEBAR":return!e}return e},metaBoxes:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:K,t=arguments.length>1?arguments[1]:void 0;switch(t.type){case"INITIALIZE_META_BOX_STATE":return J.reduce(function(n,r){return n[r]=p()({},e[r],{isActive:t.metaBoxes[r]}),n},p()({},e));case"META_BOX_SET_SAVED_DATA":return J.reduce(function(n,r){return n[r]=p()({},e[r],{data:t.dataPerLocation[r]}),n},p()({},e));default:return e}},isSavingMetaBoxes:function(){var e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];switch((arguments.length>1?arguments[1]:void 0).type){case"REQUEST_META_BOX_UPDATES":return!0;case"META_BOX_UPDATES_SUCCESS":return!1;default:return e}}}),Y=n(307),$=n.n(Y),ee=(n(95),n(75)),te=n.n(ee),ne=n(168),re=n.n(ne),oe=n(271),ie=n(102),ce=n.n(ie);function ae(e){return{type:"OPEN_GENERAL_SIDEBAR",name:e}}function ue(){return{type:"CLOSE_GENERAL_SIDEBAR"}}function le(){return{type:"OPEN_PUBLISH_SIDEBAR"}}function se(){return{type:"CLOSE_PUBLISH_SIDEBAR"}}function fe(){return{type:"TOGGLE_PUBLISH_SIDEBAR"}}function pe(e){return{type:"TOGGLE_GENERAL_SIDEBAR_EDITOR_PANEL",panel:e}}function de(e){return{type:"TOGGLE_FEATURE",feature:e}}function be(e){return{type:"SWITCH_MODE",mode:e}}function me(e){return{type:"TOGGLE_PINNED_PLUGIN_ITEM",pluginName:e}}function ve(e){return{type:"INITIALIZE_META_BOX_STATE",metaBoxes:e}}function Oe(){return{type:"REQUEST_META_BOX_UPDATES"}}function he(){return{type:"META_BOX_UPDATES_SUCCESS"}}function ge(e){return{type:"META_BOX_SET_SAVED_DATA",dataPerLocation:e}}var ye=n(142);function je(e){return Pe(e,"editorMode","visual")}function Ee(e){var t=Pe(e,"activeGeneralSidebar",null);return Object(P.includes)(["edit-post/document","edit-post/block"],t)}function Se(e){return!!_e(e)&&!Ee(e)}function _e(e){return Pe(e,"activeGeneralSidebar",null)}function xe(e){return e.preferences}function Pe(e,t,n){var r=xe(e)[t];return void 0===r?n:r}function we(e){return e.publishSidebarActive}function Te(e,t){var n=Pe(e,"panels");return!!n&&!!n[t]}function ke(e,t){return!!e.preferences.features[t]}function Ae(e,t){var n=Pe(e,"pinnedPluginItems",{});return Object(P.get)(n,[t],!0)}function Me(e){return e.metaBoxes}function Ce(e,t){return Me(e)[t]}var Be=Object(ye.a)(function(e){return Object(P.some)(Me(e),function(e){return e.isActive})},function(e){return[e.metaBoxes]});function Ie(e){return e.isSavingMetaBoxes}var Ne=function(e){var t=document.querySelector(".edit-post-meta-boxes-area.is-".concat(e," .metabox-location-").concat(e));return t||document.querySelector("#metaboxes .metabox-location-"+e)},Le=function(e,t){var n=e();return function(){var r=e();r!==n&&(n=r,t(r))}},De={INITIALIZE_META_BOX_STATE:function(e,t){if(Object(P.some)(e.metaBoxes)){setTimeout(function(){var e=Object(a.select)("core/editor").getCurrentPostType();window.postboxes.page!==e&&window.postboxes.add_postbox_toggles(e)});var n=Object(P.reduce)(e.metaBoxes,function(e,t,n){return t&&(e[n]=jQuery(Ne(n)).serialize()),e},{});t.dispatch(ge(n));var r=Object(a.select)("core/editor").isSavingPost(),o=Object(a.select)("core/editor").isAutosavingPost();Object(a.subscribe)(function(){var e=Object(a.select)("core/editor").isSavingPost(),n=Object(a.select)("core/editor").isAutosavingPost(),i=r&&!o&&!e&&!n;r=e,o=n,i&&t.dispatch({type:"REQUEST_META_BOX_UPDATES"})})}},REQUEST_META_BOX_UPDATES:function(e,t){var n=t.getState(),r=Object(P.reduce)(Me(n),function(e,t,n){return t.isActive&&(e[n]=jQuery(Ne(n)).serialize()),e},{});t.dispatch(ge(r));var o=Object(a.select)("core/editor").getCurrentPost(n),i=[!!o.comment_status&&["comment_status",o.comment_status],!!o.ping_status&&["ping_status",o.ping_status],!!o.sticky&&["sticky",o.sticky],["post_author",o.author]].filter(Boolean),c=new window.FormData(document.querySelector(".metabox-base-form")),u=Object(P.reduce)(Me(n),function(e,t,n){return t.isActive&&e.push(new window.FormData(Ne(n))),e},[c]),l=Object(P.reduce)(u,function(e,t){var n=!0,r=!1,o=void 0;try{for(var i,c=re()(t);!(n=(i=c.next()).done);n=!0){var a=te()(i.value,2),u=a[0],l=a[1];e.append(u,l)}}catch(e){r=!0,o=e}finally{try{n||null==c.return||c.return()}finally{if(r)throw o}}return e},new window.FormData);i.forEach(function(e){var t=te()(e,2),n=t[0],r=t[1];return l.append(n,r)}),ce()({url:window._wpMetaBoxUrl,method:"POST",body:l,parse:!1}).then(function(){return t.dispatch({type:"META_BOX_UPDATES_SUCCESS"})})},SWITCH_MODE:function(e){var t="visual"===e.mode?Object(T.__)("Visual editor selected"):Object(T.__)("Code editor selected");Object(oe.speak)(t,"assertive")},INIT:function(e,t){Object(a.subscribe)(Le(function(){return!!Object(a.select)("core/editor").getBlockSelectionStart()},function(e){Object(a.select)("core/edit-post").isEditorSidebarOpened()&&(e?t.dispatch(ae("edit-post/block")):t.dispatch(ae("edit-post/document")))}));var n=function(){return Object(a.select)("core/viewport").isViewportMatch("< medium")},r=function(){var e=null;return function(n){n?(e=_e(t.getState()))&&t.dispatch({type:"CLOSE_GENERAL_SIDEBAR"}):e&&!_e(t.getState())&&t.dispatch(ae(e))}}();r(n()),Object(a.subscribe)(Le(n,r))}};var Fe=function(e){var t,n=[$()(De)],r=function(){throw new Error("Dispatching while constructing your middleware is not allowed. Other middleware would not be applied to this dispatch.")},o={getState:e.getState,dispatch:function(){return r.apply(void 0,arguments)}};return t=n.map(function(e){return e(o)}),r=P.flowRight.apply(void 0,I()(t))(e.dispatch),e.dispatch=r,e},Ge=Object(a.registerStore)("core/edit-post",{reducer:Z,actions:r,selectors:o,persist:["preferences"]});Fe(Ge),Ge.dispatch({type:"INIT"});var Re=Ge,Ue=n(21),Ve=n.n(Ue),He=n(287),We=n(221),qe=(n(724),n(154));var ze=function(e){function t(){var e;return b()(this,t),(e=h()(this,y()(t).apply(this,arguments))).state={historyId:null},e}return E()(t,e),v()(t,[{key:"componentDidUpdate",value:function(e){var t=this.props,n=t.postId,r=t.postStatus,o=t.postType,i=this.state.historyId;"trash"!==r?n===e.postId&&n===i||"auto-draft"===r||this.setBrowserURL(n):this.setTrashURL(n,o)}},{key:"setTrashURL",value:function(e,t){window.location.href=function(e,t){return Object(qe.addQueryArgs)("edit.php",{trashed:1,post_type:t,ids:e})}(e,t)}},{key:"setBrowserURL",value:function(e){window.history.replaceState({id:e},"Post "+e,function(e){return Object(qe.addQueryArgs)("post.php",{post:e,action:"edit"})}(e)),this.setState(function(){return{historyId:e}})}},{key:"render",value:function(){return null}}]),t}(i.Component),Xe=Object(a.withSelect)(function(e){var t=(0,e("core/editor").getCurrentPost)();return{postId:t.id,postStatus:t.status,postType:t.type}})(ze),Qe=(n(723),n(722),n(721),Object(L.compose)(Object(a.withSelect)(function(e){return{title:e("core/editor").getEditedPostAttribute("title")}}),Object(a.withDispatch)(function(e){return{closeSidebar:e("core/edit-post").closeGeneralSidebar}}))(function(e){var t=e.children,n=e.className,r=e.closeLabel,o=e.closeSidebar,c=e.title;return Object(i.createElement)(i.Fragment,null,Object(i.createElement)("div",{className:"components-panel__header edit-post-sidebar-header__small"},Object(i.createElement)("span",{className:"edit-post-sidebar-header__title"},c||Object(T.__)("(no title)")),Object(i.createElement)(N.IconButton,{onClick:o,icon:"no-alt",label:r})),Object(i.createElement)("div",{className:Ve()("components-panel__header edit-post-sidebar-header",n)},t,Object(i.createElement)(N.IconButton,{onClick:o,icon:"no-alt",label:r})))})),Je=Object(L.compose)(Object(a.withSelect)(function(e){return{count:e("core/editor").getSelectedBlockCount()}}),Object(a.withDispatch)(function(e){var t=e("core/edit-post").openGeneralSidebar,n=e("core/editor").clearSelectedBlock;return{openDocumentSettings:function(){t("edit-post/document"),n()},openBlockSettings:function(){t("edit-post/block")}}}))(function(e){var t=e.count,n=e.openDocumentSettings,r=e.openBlockSettings,o=e.sidebarName;return t=0===t?1:t,Object(i.createElement)(Qe,{className:"edit-post-sidebar__panel-tabs",closeLabel:Object(T.__)("Close settings")},Object(i.createElement)("button",{onClick:n,className:"edit-post-sidebar__panel-tab ".concat("edit-post/document"===o?"is-active":""),"aria-label":Object(T.__)("Document settings")},Object(T.__)("Document")),Object(i.createElement)("button",{onClick:r,className:"edit-post-sidebar__panel-tab ".concat("edit-post/block"===o?"is-active":""),"aria-label":Object(T.__)("Block settings")},Object(T.sprintf)(Object(T._n)("Block","%d Blocks",t),t)))}),Ke=(n(720),Object(N.createSlotFill)("Sidebar")),Ze=Ke.Fill,Ye=Ke.Slot,$e=Object(L.compose)(Object(a.withSelect)(function(e,t){var n=t.name;return{isActive:e("core/edit-post").getActiveGeneralSidebarName()===n}}),Object(L.ifCondition)(function(e){return e.isActive}),N.withFocusReturn)(function(e){var t=e.children,n=e.label;return Object(i.createElement)(Ze,null,Object(i.createElement)("div",{className:"edit-post-sidebar",role:"region","aria-label":n,tabIndex:"-1"},t))});$e.Slot=Ye;var et=$e,tt=function(){return Object(i.createElement)(et,{name:"edit-post/block",label:Object(T.__)("Editor settings")},Object(i.createElement)(Je,{sidebarName:"edit-post/block"}),Object(i.createElement)(N.Panel,null,Object(i.createElement)(N.PanelBody,{className:"edit-post-block-sidebar__panel"},Object(i.createElement)(V.BlockInspector,null))))};n(719),n(718);var nt=function(){return Object(i.createElement)(V.PostVisibilityCheck,{render:function(e){var t=e.canEdit;return Object(i.createElement)(N.PanelRow,{className:"edit-post-post-visibility"},Object(i.createElement)("span",null,Object(T.__)("Visibility")),!t&&Object(i.createElement)("span",null,Object(i.createElement)(V.PostVisibilityLabel,null)),t&&Object(i.createElement)(N.Dropdown,{position:"bottom left",contentClassName:"edit-post-post-visibility__dialog",renderToggle:function(e){var t=e.isOpen,n=e.onToggle;return Object(i.createElement)(N.Button,{type:"button","aria-expanded":t,className:"edit-post-post-visibility__toggle",onClick:n,isLink:!0},Object(i.createElement)(V.PostVisibilityLabel,null))},renderContent:function(){return Object(i.createElement)(V.PostVisibility,null)}}))}})};n(717);function rt(){return Object(i.createElement)(V.PostTrashCheck,null,Object(i.createElement)(N.PanelRow,null,Object(i.createElement)(V.PostTrash,null)))}n(716);var ot=function(){return Object(i.createElement)(V.PostScheduleCheck,null,Object(i.createElement)(N.PanelRow,{className:"edit-post-post-schedule"},Object(i.createElement)("span",null,Object(T.__)("Publish")),Object(i.createElement)(N.Dropdown,{position:"bottom left",contentClassName:"edit-post-post-schedule__dialog",renderToggle:function(e){var t=e.onToggle,n=e.isOpen;return Object(i.createElement)(N.Button,{type:"button",className:"edit-post-post-schedule__toggle",onClick:t,"aria-expanded":n,isLink:!0},Object(i.createElement)(V.PostScheduleLabel,null))},renderContent:function(){return Object(i.createElement)(V.PostSchedule,null)}})))};var it=function(){return Object(i.createElement)(V.PostStickyCheck,null,Object(i.createElement)(N.PanelRow,null,Object(i.createElement)(V.PostSticky,null)))};n(715);var ct=function(){return Object(i.createElement)(V.PostAuthorCheck,null,Object(i.createElement)(N.PanelRow,null,Object(i.createElement)(V.PostAuthor,null)))};var at=function(){return Object(i.createElement)(V.PostFormatCheck,null,Object(i.createElement)(N.PanelRow,null,Object(i.createElement)(V.PostFormat,null)))};var ut=function(){return Object(i.createElement)(V.PostPendingStatusCheck,null,Object(i.createElement)(N.PanelRow,null,Object(i.createElement)(V.PostPendingStatus,null)))},lt=Object(N.createSlotFill)("PluginPostStatusInfo"),st=lt.Fill,ft=lt.Slot,pt=function(e){var t=e.children,n=e.className;return Object(i.createElement)(st,null,Object(i.createElement)(N.PanelRow,{className:n},t))};pt.Slot=ft;var dt=pt;var bt=Object(L.compose)([Object(a.withSelect)(function(e){return{isOpened:e("core/edit-post").isEditorSidebarPanelOpened("post-status")}}),Object(a.withDispatch)(function(e){return{onTogglePanel:function(){return e("core/edit-post").toggleGeneralSidebarEditorPanel("post-status")}}})])(function(e){var t=e.isOpened,n=e.onTogglePanel;return Object(i.createElement)(N.PanelBody,{className:"edit-post-post-status",title:Object(T.__)("Status & Visibility"),opened:t,onToggle:n},Object(i.createElement)(dt.Slot,null,function(e){return Object(i.createElement)(i.Fragment,null,Object(i.createElement)(nt,null),Object(i.createElement)(ot,null),Object(i.createElement)(at,null),Object(i.createElement)(it,null),Object(i.createElement)(ut,null),Object(i.createElement)(ct,null),e,Object(i.createElement)(rt,null))}))});var mt=Object(L.compose)([Object(a.withSelect)(function(e){return{isOpened:e("core/edit-post").isEditorSidebarPanelOpened("post-excerpt")}}),Object(a.withDispatch)(function(e){return{onTogglePanel:function(){return e("core/edit-post").toggleGeneralSidebarEditorPanel("post-excerpt")}}})])(function(e){var t=e.isOpened,n=e.onTogglePanel;return Object(i.createElement)(V.PostExcerptCheck,null,Object(i.createElement)(N.PanelBody,{title:Object(T.__)("Excerpt"),opened:t,onToggle:n},Object(i.createElement)(V.PostExcerpt,null)))});var vt=Object(L.compose)(Object(a.withSelect)(function(e,t){var n=Object(P.get)(t.taxonomy,["slug"]),r=n?"taxonomy-panel-".concat(n):"";return{panelName:r,isOpened:!!n&&e("core/edit-post").isEditorSidebarPanelOpened(r)}}),Object(a.withDispatch)(function(e,t){return{onTogglePanel:function(){e("core/edit-post").toggleGeneralSidebarEditorPanel(t.panelName)}}}))(function(e){var t=e.taxonomy,n=e.isOpened,r=e.onTogglePanel,o=e.children,c=Object(P.get)(t,["labels","menu_name"]);return c?Object(i.createElement)(N.PanelBody,{title:c,opened:n,onToggle:r},o):null});var Ot=function(){return Object(i.createElement)(V.PostTaxonomiesCheck,null,Object(i.createElement)(V.PostTaxonomies,{taxonomyWrapper:function(e,t){return Object(i.createElement)(vt,{taxonomy:t},e)}}))};var ht=Object(a.withSelect)(function(e){var t=e("core/editor").getEditedPostAttribute,n=e("core").getPostType,r=e("core/edit-post").isEditorSidebarPanelOpened;return{postType:n(t("type")),isOpened:r("featured-image")}}),gt=Object(a.withDispatch)(function(e){var t=e("core/edit-post").toggleGeneralSidebarEditorPanel;return{onTogglePanel:Object(P.partial)(t,"featured-image")}}),yt=Object(L.compose)(ht,gt)(function(e){var t=e.isOpened,n=e.postType,r=e.onTogglePanel;return Object(i.createElement)(V.PostFeaturedImageCheck,null,Object(i.createElement)(N.PanelBody,{title:Object(P.get)(n,["labels","featured_image"],Object(T.__)("Featured Image")),opened:t,onToggle:r},Object(i.createElement)(V.PostFeaturedImage,null)))});var jt=Object(L.compose)([Object(a.withSelect)(function(e){return{isOpened:e("core/edit-post").isEditorSidebarPanelOpened("discussion-panel")}}),Object(a.withDispatch)(function(e){return{onTogglePanel:function(){return e("core/edit-post").toggleGeneralSidebarEditorPanel("discussion-panel")}}})])(function(e){var t=e.isOpened,n=e.onTogglePanel;return Object(i.createElement)(V.PostTypeSupportCheck,{supportKeys:["comments","trackbacks"]},Object(i.createElement)(N.PanelBody,{title:Object(T.__)("Discussion"),opened:t,onToggle:n},Object(i.createElement)(V.PostTypeSupportCheck,{supportKeys:"comments"},Object(i.createElement)(N.PanelRow,null,Object(i.createElement)(V.PostComments,null))),Object(i.createElement)(V.PostTypeSupportCheck,{supportKeys:"trackbacks"},Object(i.createElement)(N.PanelRow,null,Object(i.createElement)(V.PostPingbacks,null)))))});n(714);var Et=function(){return Object(i.createElement)(V.PostLastRevisionCheck,null,Object(i.createElement)(N.PanelBody,{className:"edit-post-last-revision__panel"},Object(i.createElement)(V.PostLastRevision,null)))};var St=Object(a.withSelect)(function(e){var t=e("core/editor").getEditedPostAttribute,n=e("core/edit-post").isEditorSidebarPanelOpened,r=e("core").getPostType;return{isOpened:n("page-attributes"),postType:r(t("type"))}}),_t=Object(a.withDispatch)(function(e){var t=e("core/edit-post").toggleGeneralSidebarEditorPanel;return{onTogglePanel:Object(P.partial)(t,"page-attributes")}}),xt=Object(L.compose)(St,_t)(function(e){var t=e.isOpened,n=e.onTogglePanel,r=e.postType;return r?Object(i.createElement)(V.PageAttributesCheck,null,Object(i.createElement)(N.PanelBody,{title:Object(P.get)(r,["labels","attributes"],Object(T.__)("Page Attributes")),opened:t,onToggle:n},Object(i.createElement)(V.PageTemplate,null),Object(i.createElement)(V.PageAttributesParent,null),Object(i.createElement)(N.PanelRow,null,Object(i.createElement)(V.PageAttributesOrder,null)))):null}),Pt=(n(713),function(e){function t(){var e;return b()(this,t),(e=h()(this,y()(t).apply(this,arguments))).bindContainerNode=e.bindContainerNode.bind(x()(x()(e))),e}return E()(t,e),v()(t,[{key:"componentDidMount",value:function(){this.form=document.querySelector(".metabox-location-"+this.props.location),this.form&&this.container.appendChild(this.form)}},{key:"componentWillUnmount",value:function(){this.form&&document.querySelector("#metaboxes").appendChild(this.form)}},{key:"bindContainerNode",value:function(e){this.container=e}},{key:"render",value:function(){var e=this.props,t=e.location,n=e.isSaving,r=Ve()("edit-post-meta-boxes-area","is-".concat(t),{"is-loading":n});return Object(i.createElement)("div",{className:r},n&&Object(i.createElement)(N.Spinner,null),Object(i.createElement)("div",{className:"edit-post-meta-boxes-area__container",ref:this.bindContainerNode}),Object(i.createElement)("div",{className:"edit-post-meta-boxes-area__clear"}))}}]),t}(i.Component)),wt=Object(a.withSelect)(function(e){return{isSaving:e("core/edit-post").isSavingMetaBoxes()}})(Pt);var Tt=Object(a.withSelect)(function(e,t){return{isActive:e("core/edit-post").getMetaBox(t.location).isActive}})(function(e){var t=e.location;return e.isActive?Object(i.createElement)(wt,{location:t}):null}),kt=function(){return Object(i.createElement)(et,{name:"edit-post/document",label:Object(T.__)("Editor settings")},Object(i.createElement)(Je,{sidebarName:"edit-post/document"}),Object(i.createElement)(N.Panel,null,Object(i.createElement)(bt,null),Object(i.createElement)(Et,null),Object(i.createElement)(Ot,null),Object(i.createElement)(yt,null),Object(i.createElement)(mt,null),Object(i.createElement)(jt,null),Object(i.createElement)(xt,null),Object(i.createElement)(Tt,{location:"side"})))},At=n(265),Mt=(n(712),n(711),n(35)),Ct={toggleEditorMode:{value:Mt.rawShortcut.secondary("m"),label:Mt.displayShortcut.secondary("m")}},Bt=[{value:"visual",label:Object(T.__)("Visual Editor")},{value:"text",label:Object(T.__)("Code Editor")}];var It=Object(L.compose)([Object(a.withSelect)(function(e){return{mode:e("core/edit-post").getEditorMode()}}),Object(a.withDispatch)(function(e,t){return{onSwitch:function(n){e("core/edit-post").switchEditorMode(n),t.onSelect(n)}}})])(function(e){var t=e.onSwitch,n=e.mode,r=Bt.map(function(e){return e.value!==n?p()({},e,{shortcut:Ct.toggleEditorMode.label}):e});return Object(i.createElement)(N.MenuGroup,{label:Object(T.__)("Editor"),filterName:"editPost.MoreMenu.editor"},Object(i.createElement)(N.MenuItemsChoice,{choices:r,value:n,onSelect:t}))});var Nt=Object(L.compose)([Object(a.withSelect)(function(e){return{isActive:e("core/edit-post").isFeatureActive("fixedToolbar")}}),Object(a.withDispatch)(function(e,t){return{onToggle:function(){e("core/edit-post").toggleFeature("fixedToolbar"),t.onToggle()}}}),Object(We.ifViewportMatches)("medium")])(function(e){var t=e.onToggle,n=e.isActive;return Object(i.createElement)(N.MenuItem,{icon:n&&"yes",isSelected:n,onClick:t},Object(T.__)("Fix Toolbar to Top"))}),Lt=Object(N.createSlotFill)("PluginsMoreMenuGroup"),Dt=Lt.Fill,Ft=Lt.Slot;Dt.Slot=function(e){var t=e.fillProps;return Object(i.createElement)(Ft,{fillProps:t},function(e){return!Object(P.isEmpty)(e)&&Object(i.createElement)(N.MenuGroup,{label:Object(T.__)("Plugins")},e)})};var Gt=Dt;var Rt=Object(L.compose)([Object(a.withSelect)(function(e){return{isActive:e("core/nux").areTipsEnabled()}}),Object(a.withDispatch)(function(e,t){return{onToggle:function(){var n=e("core/nux"),r=n.disableTips,o=n.enableTips;t.isActive?r():o(),t.onToggle()}}})])(function(e){var t=e.onToggle,n=e.isActive;return Object(i.createElement)(N.MenuItem,{icon:n&&"yes",isSelected:n,onClick:t},Object(T.__)("Show Tips"))}),Ut=function(){return Object(i.createElement)(N.Dropdown,{className:"edit-post-more-menu",position:"bottom left",renderToggle:function(e){var t=e.isOpen,n=e.onToggle;return Object(i.createElement)(N.IconButton,{icon:"ellipsis",label:Object(T._x)("More","button to expand options"),onClick:n,"aria-expanded":t})},renderContent:function(e){var t=e.onClose;return Object(i.createElement)("div",{className:"edit-post-more-menu__content"},Object(i.createElement)(It,{onSelect:t}),Object(i.createElement)(N.MenuGroup,{label:Object(T.__)("Settings"),filterName:"editPost.MoreMenu.settings"},Object(i.createElement)(Nt,{onToggle:t}),Object(i.createElement)(Rt,{onToggle:t})),Object(i.createElement)(Gt.Slot,{fillProps:{onClose:t}}),Object(i.createElement)(N.MenuGroup,{label:Object(T.__)("Tools"),filterName:"editPost.MoreMenu.tools"}))}})};n(710);var Vt=Object(L.compose)([Object(a.withSelect)(function(e){return{hasFixedToolbar:e("core/edit-post").isFeatureActive("fixedToolbar")}}),Object(We.withViewportMatch)({isLargeViewport:"medium"})])(function(e){var t=e.hasFixedToolbar,n=e.isLargeViewport;return Object(i.createElement)(V.NavigableToolbar,{className:"edit-post-header-toolbar","aria-label":Object(T.__)("Editor Toolbar")},Object(i.createElement)(V.Inserter,{position:"bottom right"}),Object(i.createElement)(V.EditorHistoryUndo,null),Object(i.createElement)(V.EditorHistoryRedo,null),Object(i.createElement)(V.TableOfContents,null),t&&n&&Object(i.createElement)("div",{className:"edit-post-header-toolbar__block-toolbar"},Object(i.createElement)(V.BlockToolbar,null)))}),Ht=(n(709),Object(N.createSlotFill)("PinnedPlugins")),Wt=Ht.Fill,qt=Ht.Slot;Wt.Slot=function(e){return Object(i.createElement)(qt,e,function(e){return!Object(P.isEmpty)(e)&&Object(i.createElement)("div",{className:"edit-post-pinned-plugins"},e)})};var zt=Wt;var Xt=Object(L.compose)(Object(a.withSelect)(function(e){return{isEditorSidebarOpened:e("core/edit-post").isEditorSidebarOpened(),isPublishSidebarOpened:e("core/edit-post").isPublishSidebarOpened(),hasActiveMetaboxes:e("core/edit-post").hasMetaBoxes(),isSaving:e("core/edit-post").isSavingMetaBoxes(),hasBlockSelection:!!e("core/editor").getBlockSelectionStart()}}),Object(a.withDispatch)(function(e,t){var n=t.hasBlockSelection,r=e("core/edit-post"),o=r.openGeneralSidebar,i=r.closeGeneralSidebar,c=r.togglePublishSidebar,a=n?"edit-post/block":"edit-post/document";return{openGeneralSidebar:function(){return o(a)},closeGeneralSidebar:i,togglePublishSidebar:c,hasBlockSelection:void 0}}))(function(e){var t=e.isEditorSidebarOpened,n=e.openGeneralSidebar,r=e.closeGeneralSidebar,o=e.isPublishSidebarOpened,c=e.togglePublishSidebar,a=e.hasActiveMetaboxes,u=e.isSaving,l=t?r:n;return Object(i.createElement)("div",{role:"region","aria-label":Object(T.__)("Editor top bar"),className:"edit-post-header",tabIndex:"-1"},Object(i.createElement)(Vt,null),!o&&Object(i.createElement)("div",{className:"edit-post-header__settings"},Object(i.createElement)(V.PostSavedState,{forceIsDirty:a,forceIsSaving:u}),Object(i.createElement)(V.PostPreviewButton,null),Object(i.createElement)(V.PostPublishPanelToggle,{isOpen:o,onToggle:c,forceIsDirty:a,forceIsSaving:u}),Object(i.createElement)(N.IconButton,{icon:"admin-generic",label:Object(T.__)("Settings"),onClick:l,isToggled:t,"aria-expanded":t},Object(i.createElement)(At.DotTip,{id:"core/editor.settings"},Object(T.__)("You’ll find more settings for your page and blocks in the sidebar. Click ‘Settings’ to open it."))),Object(i.createElement)(zt.Slot,null),Object(i.createElement)(Ut,null)))});n(708);var Qt=function(){return Object(i.createElement)("div",{className:"edit-post-text-editor"},Object(i.createElement)("div",{className:"edit-post-text-editor__body"},Object(i.createElement)(V.PostTitle,null),Object(i.createElement)(V.PostTextEditor,null)))};n(707),n(257);var Jt=Object(L.compose)(Object(a.withSelect)(function(e){return{areAdvancedSettingsOpened:"edit-post/block"===e("core/edit-post").getActiveGeneralSidebarName()}}),Object(a.withDispatch)(function(e){return{openEditorSidebar:function(){return e("core/edit-post").openGeneralSidebar("edit-post/block")},closeSidebar:e("core/edit-post").closeGeneralSidebar}}),N.withSpokenMessages)(function(e){var t=e.areAdvancedSettingsOpened,n=e.closeSidebar,r=e.openEditorSidebar,o=e.onClick,c=void 0===o?P.noop:o,a=e.small,u=void 0!==a&&a,l=e.speak,s=e.role,f=t?Object(T.__)("Hide Block Settings"):Object(T.__)("Show Block Settings");return Object(i.createElement)(N.IconButton,{className:"editor-block-settings-menu__control",onClick:Object(P.flow)(t?n:r,function(){l(t?Object(T.__)("Block settings closed"):Object(T.__)("Additional settings are now available in the Editor block settings sidebar"))},c),icon:"admin-generic",label:u?f:void 0,role:s},!u&&f)}),Kt=Object(N.createSlotFill)("PluginBlockSettingsMenuGroup"),Zt=Kt.Fill,Yt=Kt.Slot;Zt.Slot=Object(a.withSelect)(function(e,t){var n=t.fillProps.clientIds;return{selectedBlocks:e("core/editor").getBlocksByClientId(n)}})(function(e){var t=e.fillProps,n=e.selectedBlocks;return n=Object(P.map)(n,function(e){return e.name}),Object(i.createElement)(Yt,{fillProps:p()({},t,{selectedBlocks:n})},function(e){return!Object(P.isEmpty)(e)&&Object(i.createElement)(i.Fragment,null,Object(i.createElement)("div",{className:"editor-block-settings-menu__separator"}),e)})});var $t=Zt;var en=function(){return Object(i.createElement)(V.BlockSelectionClearer,{className:"edit-post-visual-editor"},Object(i.createElement)(V.EditorGlobalKeyboardShortcuts,null),Object(i.createElement)(V.CopyHandler,null),Object(i.createElement)(V.MultiSelectScrollIntoView,null),Object(i.createElement)(V.WritingFlow,null,Object(i.createElement)(V.ObserveTyping,null,Object(i.createElement)(V.PostTitle,null),Object(i.createElement)(V.BlockList,null))),Object(i.createElement)(V._BlockSettingsMenuFirstItem,null,function(e){var t=e.onClose;return Object(i.createElement)(Jt,{onClick:t,role:"menuitem"})}),Object(i.createElement)(V._BlockSettingsMenuPluginsExtension,null,function(e){var t=e.clientIds,n=e.onClose;return Object(i.createElement)($t.Slot,{fillProps:{clientIds:t,onClose:n}})}))},tn=function(e){function t(){var e;return b()(this,t),(e=h()(this,y()(t).apply(this,arguments))).toggleMode=e.toggleMode.bind(x()(x()(e))),e}return E()(t,e),v()(t,[{key:"toggleMode",value:function(){var e=this.props,t=e.mode;(0,e.switchMode)("visual"===t?"text":"visual")}},{key:"render",value:function(){return Object(i.createElement)(N.KeyboardShortcuts,{bindGlobal:!0,shortcuts:z()({},Ct.toggleEditorMode.value,this.toggleMode)})}}]),t}(i.Component),nn=Object(L.compose)([Object(a.withSelect)(function(e){return{mode:e("core/edit-post").getEditorMode()}}),Object(a.withDispatch)(function(e){return{switchMode:function(t){e("core/edit-post").switchEditorMode(t)}}})])(tn),rn=Object(N.createSlotFill)("PluginPostPublishPanel"),on=rn.Fill,cn=rn.Slot,an=function(e){var t=e.children,n=e.className,r=e.title,o=e.initialOpen,c=void 0!==o&&o;return Object(i.createElement)(on,null,Object(i.createElement)(N.PanelBody,{className:n,initialOpen:c||!r,title:r},t))};an.Slot=cn;var un=an,ln=Object(N.createSlotFill)("PluginPrePublishPanel"),sn=ln.Fill,fn=ln.Slot,pn=function(e){var t=e.children,n=e.className,r=e.title,o=e.initialOpen,c=void 0!==o&&o;return Object(i.createElement)(sn,null,Object(i.createElement)(N.PanelBody,{className:n,initialOpen:c||!r,title:r},t))};pn.Slot=fn;var dn=pn;var bn=Object(L.compose)(Object(a.withSelect)(function(e){return{mode:e("core/edit-post").getEditorMode(),editorSidebarOpened:e("core/edit-post").isEditorSidebarOpened(),pluginSidebarOpened:e("core/edit-post").isPluginSidebarOpened(),publishSidebarOpened:e("core/edit-post").isPublishSidebarOpened(),hasFixedToolbar:e("core/edit-post").isFeatureActive("fixedToolbar"),metaBoxes:e("core/edit-post").getMetaBoxes(),hasActiveMetaboxes:e("core/edit-post").hasMetaBoxes(),isSaving:e("core/edit-post").isSavingMetaBoxes()}}),Object(a.withDispatch)(function(e){var t=e("core/edit-post");return{closePublishSidebar:t.closePublishSidebar,togglePublishSidebar:t.togglePublishSidebar}}),N.navigateRegions,Object(We.withViewportMatch)({isMobileViewport:"< small"}))(function(e){var t=e.mode,n=e.editorSidebarOpened,r=e.pluginSidebarOpened,o=e.publishSidebarOpened,c=e.hasFixedToolbar,a=e.closePublishSidebar,u=e.togglePublishSidebar,l=e.metaBoxes,s=e.hasActiveMetaboxes,f=e.isSaving,p=e.isMobileViewport,d=n||r||o,b=Ve()("edit-post-layout",{"is-sidebar-opened":d,"has-fixed-toolbar":c}),m={role:"region","aria-label":Object(T.__)("Editor publish"),tabIndex:-1};return Object(i.createElement)("div",{className:b},Object(i.createElement)(V.DocumentTitle,null),Object(i.createElement)(Xe,null),Object(i.createElement)(V.UnsavedChangesWarning,{forceIsDirty:function(){return Object(P.some)(l,function(e,t){return e.isActive&&jQuery(Ne(t)).serialize()!==e.data})}}),Object(i.createElement)(V.AutosaveMonitor,null),Object(i.createElement)(Xt,null),Object(i.createElement)("div",{className:"edit-post-layout__content",role:"region","aria-label":Object(T.__)("Editor content"),tabIndex:"-1"},Object(i.createElement)(V.EditorNotices,null),Object(i.createElement)(V.PreserveScrollInReorder,null),Object(i.createElement)(nn,null),"text"===t&&Object(i.createElement)(Qt,null),"visual"===t&&Object(i.createElement)(en,null),Object(i.createElement)("div",{className:"edit-post-layout__metaboxes"},Object(i.createElement)(Tt,{location:"normal"})),Object(i.createElement)("div",{className:"edit-post-layout__metaboxes"},Object(i.createElement)(Tt,{location:"advanced"}))),o?Object(i.createElement)(V.PostPublishPanel,G()({},m,{onClose:a,forceIsDirty:s,forceIsSaving:f,PrePublishExtension:dn.Slot,PostPublishExtension:un.Slot})):Object(i.createElement)(i.Fragment,null,Object(i.createElement)("div",G()({className:"edit-post-toggle-publish-panel"},m),Object(i.createElement)(N.Button,{isDefault:!0,type:"button",className:"edit-post-toggle-publish-panel__button",onClick:u,"aria-expanded":!1},Object(T.__)("Open publish panel"))),Object(i.createElement)(kt,null),Object(i.createElement)(tt,null),Object(i.createElement)(et.Slot,null),p&&d&&Object(i.createElement)(N.ScrollLock,null)),Object(i.createElement)(N.Popover.Slot,null),Object(i.createElement)(He.PluginArea,null))});var mn=Object(a.withSelect)(function(e,t){var n=t.postId,r=t.postType;return{hasFixedToolbar:e("core/edit-post").isFeatureActive("fixedToolbar"),post:e("core").getEntityRecord("postType",r,n)}})(function(e){var t=e.settings,n=e.hasFixedToolbar,r=e.post,o=e.overridePost,c=e.onError,a=U()(e,["settings","hasFixedToolbar","post","overridePost","onError"]);if(!r)return null;var u=p()({},t,{hasFixedToolbar:n});return Object(i.createElement)(i.StrictMode,null,Object(i.createElement)(V.EditorProvider,G()({settings:u,post:p()({},r,o)},a),Object(i.createElement)(V.ErrorBoundary,{onError:c},Object(i.createElement)(bn,null))))}),vn=function(e,t){return!Array.isArray(t)||function(e,t){return 0===Object(P.difference)(e,t).length}(e,t)},On=function(e){var t=e.allowedBlocks,n=e.icon,r=e.label,o=e.onClick,c=e.small,a=e.role;return Object(i.createElement)($t,null,function(e){var u=e.selectedBlocks,l=e.onClose;return vn(u,t)?Object(i.createElement)(N.IconButton,{className:"editor-block-settings-menu__control",onClick:Object(L.compose)(o,l),icon:n||"admin-plugins",label:c?r:void 0,role:a},!c&&r):null})};var hn=Object(L.compose)(Object(He.withPluginContext)(function(e,t){return{icon:t.icon||e.icon,sidebarName:"".concat(e.name,"/").concat(t.name)}}),Object(a.withSelect)(function(e,t){var n=t.sidebarName,r=e("core/edit-post"),o=r.getActiveGeneralSidebarName,i=r.isPluginItemPinned;return{isActive:o()===n,isPinned:i(n)}}),Object(a.withDispatch)(function(e,t){var n=t.isActive,r=t.sidebarName,o=e("core/edit-post"),i=o.closeGeneralSidebar,c=o.openGeneralSidebar,a=o.togglePinnedPluginItem;return{togglePin:function(){a(r)},toggleSidebar:function(){n?i():c(r)}}}))(function(e){var t=e.children,n=e.icon,r=e.isActive,o=e.isPinnable,c=void 0===o||o,a=e.isPinned,u=e.sidebarName,l=e.title,s=e.togglePin,f=e.toggleSidebar;return Object(i.createElement)(i.Fragment,null,c&&Object(i.createElement)(zt,null,a&&Object(i.createElement)(N.IconButton,{icon:n,label:l,onClick:f,isToggled:r,"aria-expanded":r})),Object(i.createElement)(et,{name:u,label:Object(T.__)("Editor plugins")},Object(i.createElement)(Qe,{closeLabel:Object(T.__)("Close plugin")},Object(i.createElement)("strong",null,l),c&&Object(i.createElement)(N.IconButton,{icon:a?"star-filled":"star-empty",label:a?Object(T.__)("Unpin from toolbar"):Object(T.__)("Pin to toolbar"),onClick:s,isToggled:a,"aria-expanded":a})),Object(i.createElement)(N.Panel,null,t)))}),gn=Object(L.compose)(Object(He.withPluginContext)(function(e,t){return{icon:t.icon||e.icon,sidebarName:"".concat(e.name,"/").concat(t.target)}}),Object(a.withSelect)(function(e,t){var n=t.sidebarName;return{isSelected:(0,e("core/edit-post").getActiveGeneralSidebarName)()===n}}),Object(a.withDispatch)(function(e,t){var n=t.isSelected,r=t.sidebarName,o=e("core/edit-post"),i=o.closeGeneralSidebar,c=o.openGeneralSidebar;return{onClick:n?i:function(){return c(r)}}}))(function(e){var t=e.children,n=e.icon,r=e.isSelected,o=e.onClick;return Object(i.createElement)(Gt,null,function(e){return Object(i.createElement)(N.MenuItem,{icon:r?"yes":n,isSelected:r,onClick:Object(L.compose)(o,e.onClose)},t)})});function yn(e,t,n,r,o){Object(i.unmountComponentAtNode)(n);var c=yn.bind(null,e,t,n,r,o);Object(i.render)(Object(i.createElement)(mn,{settings:r,onError:c,postId:t,postType:e,overridePost:o,recovery:!0}),n)}function jn(e,t,n,r,o){var u=document.getElementById(e),s=yn.bind(null,t,n,u,r,o);return l()("paragraphs block class set is-small-text, ..., is-large-text",{version:"3.6",alternative:"has-small-font-size, ..., has-large-font-size class set",plugin:"Gutenberg",hint:"If paragraphs using this classes are opened in the editor new classes are automatically applied the post just needs to be saved. This is a global warning, shown regardless of whether the classes are used in the current post."}),Object(c.registerCoreBlocks)(),Object(a.dispatch)("core/nux").triggerGuide(["core/editor.inserter","core/editor.settings","core/editor.preview","core/editor.publish"]),Object(i.render)(Object(i.createElement)(mn,{settings:r,onError:s,postId:n,postType:t,overridePost:o}),u),{initializeMetaBoxes:function(e){Re.dispatch(ve(e))}}}n.d(t,"reinitializeEditor",function(){return yn}),n.d(t,"initializeEditor",function(){return jn}),n.d(t,"PluginBlockSettingsMenuItem",function(){return On}),n.d(t,"PluginPostPublishPanel",function(){return un}),n.d(t,"PluginPostStatusInfo",function(){return dt}),n.d(t,"PluginPrePublishPanel",function(){return dn}),n.d(t,"PluginSidebar",function(){return hn}),n.d(t,"PluginSidebarMoreMenuItem",function(){return gn})},,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,function(e,t){},function(e,t){},function(e,t){},function(e,t){},function(e,t){},function(e,t){},function(e,t){},function(e,t){},function(e,t){},function(e,t){},function(e,t){},function(e,t){},function(e,t){},function(e,t){},function(e,t){},function(e,t){},function(e,t){},function(e,t){},function(e,t){}]);
|
/*
*
* AthleteTeam
*
*/
import React, { PropTypes } from 'react';
import { connect } from 'react-redux';
import {Tabs, Tab} from 'material-ui/Tabs';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import AthleteTeamList from './AthleteTeamList'
import ApplyTeamForm from './ApplyTeamForm'
import { graphql } from 'react-apollo';
import gql from 'graphql-tag';
var userId = localStorage.getItem('userID');
export class AthleteTeam extends React.Component { // eslint-disable-line react/prefer-stateless-function
static propTypes = {
data: React.PropTypes.shape({
loading: React.PropTypes.bool,
error: React.PropTypes.object,
User: React.PropTypes.object,
}).isRequired,
}
render() {
return (
<MuiThemeProvider>
<Tabs>
<Tab label="My Team" >
<AthleteTeamList userId={userId} />
</Tab>
<Tab label="Apply for Team" >
<ApplyTeamForm userData={this.props.data.user}/>
</Tab>
</Tabs>
</MuiThemeProvider>
);
}
}
const athleteQuery = gql`query athleteQuery {
user { id firstName lastName email country dob profileImage gender address timeZone mobileNumber height weight bio createdAt
athlete {
id graduation graduationProgramLength graduationUniversity graduationYear hightSchool hightSchoolUniversity hightSchoolYear createdAt
athleteSports {
id
sport { id }
participateStartDate
athleteAcadmicCertificates { id url }
}
athletAcadmic { id
athlete { id }
institute { id }
sport { id }
createdAt
}
}
}
}`
const AthleteQueryData = graphql(athleteQuery)(AthleteTeam);
export default AthleteQueryData;
|
var app = angular.module('dashboardApp',
['ui.bootstrap','ui.calendar','mgcrea.ngStrap','ngAnimate','ngSanitize']);
|
import React, {Component} from 'react';
import Login from './Login';
import { Panel } from 'react-bootstrap';
class Home extends Component {
constructor(props) {
super(props);
this.state = {
isAuthenticated: false,
user: '',
password:''
};
this.handleChange = this.handleChange.bind(this);
this.handleLogin = this.handleLogin.bind(this);
};
handleChange(event) {
if (event.target.name === 'user') {
this.setState({user: event.target.value});
} else {
this.setState({password: event.target.value});
}
}
handleLogin(event) {
event.preventDefault();
this.setState({isAuthenticated: true});
}
handleLogout(event) {
event.preventDefault();
this.setState({isAuthenticated: false});
}
render() {
return this.state.isAuthenticated
? (
<Panel className="App-container">
<Panel.Heading>
<Panel.Title componentClass="h3">Welcome</Panel.Title>
</Panel.Heading>
<Panel.Body>Panel content</Panel.Body>
</Panel>
)
: (
<div className="App-container">
</div>
)
}
}
export default Home;
|
const mongoose = require('mongoose');
const { Schema } = mongoose;
const productSchema = new Schema({
id: {
type: Number,
unique: true
},
name: String,
slogan: String,
description: String,
category: String,
default_price: String
}, {collection: 'product'});
const stylesSchema = new Schema({
id: {
type: Number,
unique: true
},
productId: {
type: Number,
index: true
},
name: String,
sale_price: String,
original_price: String,
default_style: Boolean
}, {collection: 'styles'});
const featuresSchema = new Schema({
id: Number,
product_id: {
type: Number,
index: true
},
feature: String,
value: String
}, {collection: 'features'});
const skusSchema = new Schema({
id: {
type: Number,
unique: true
},
styleId: {
type: Number,
index: true
},
size: String,
quantity: Number
}, {collection: 'skus', _id: false});
const photosSchema = new Schema({
id: {
type: Number,
unique: true
},
styleId: {
type: Number,
index: true
},
url: String,
thumbnail_url: String
}, {collections: 'photos'});
const relatedSchema = new Schema({
id: {
type: Number,
unique: true
},
current_product_id: {
type: Number,
index: true
},
related_product_id: Number
}, {collection: 'related'});
module.exports = { productSchema, stylesSchema, featuresSchema, skusSchema, photosSchema, relatedSchema };
|
// Update with your config settings.
const pgConnection = process.env.DATABASE_URL;
module.exports = {
development: {
client: 'sqlite3',
connection: {
filename: './data/plants.db3'
},
useNullAsDefault: true,
migrations: {
directory: './data/migrations'
},
seeds: {
directory: './data/seeds'
},
pool: {
afterCreate: (conn, done) => {
// runs after a connection is made to the sqlite engine
conn.run('PRAGMA foreign_keys = ON', done); // turn on FK enforcement
},
},
},
testing: {
client: "sqlite3",
connection: {
filename: "./data/test.db3",
},
useNullAsDefault: true,
migrations: {
directory: "./data/migrations",
},
seeds: {
directory: "./data/seeds",
},
pool: {
afterCreate: (conn, done) => {
// runs after a connection is made to the sqlite engine
conn.run('PRAGMA foreign_keys = ON', done); // turn on FK enforcement
},
},
},
production: {
client: "sqlite3",
connection: {
filename: "./data/production.db3",
},
useNullAsDefault: true,
migrations: {
directory: "./data/migrations",
},
seeds: {
directory: "./data/seeds",
},
pool: {
afterCreate: (conn, done) => {
// runs after a connection is made to the sqlite engine
conn.run('PRAGMA foreign_keys = ON', done); // turn on FK enforcement
},
},
},
production: {
client: "pg",
connection: pgConnection,
pool: {
min: 2,
max: 10,
},
migrations: {
directory: "./data/migrations",
},
seeds: {
directory: "./data/seeds",
},
},
};
|
import { createReducer } from '@reduxjs/toolkit'
import { SETTING_CATEGORIES, CONNECTION_STATE_TYPE } from 'shared/constants'
import { SettingsActions, ConnectionActions } from '../actions'
const initialState = {
categories: Object.values(SETTING_CATEGORIES),
tabs: [],
tabMessages: {},
tabTypes: {},
data: {},
}
const settingsLoaded = (state, { payload }) => ({
...state,
...payload,
})
const settingsDataUpdated = (state, { payload }) => ({
...state,
data: {
...state.data,
...payload,
},
})
const connectionRequested = (state, { payload: { userId, message } }) => ({
...state,
data: {
...state.data,
[CONNECTION_STATE_TYPE.FOUND]: state.data[CONNECTION_STATE_TYPE.FOUND].map(connection => ({
...connection,
message: connection.userId === userId
? message
: connection.message,
state: connection.userId === userId
? CONNECTION_STATE_TYPE.WAITING
: connection.state,
})),
},
})
export default createReducer(initialState, {
[SettingsActions.loadSettingsSuccess.toString()]: settingsLoaded,
[SettingsActions.settingsDataUpdated.toString()]: settingsDataUpdated,
[ConnectionActions.connectionRequestSuccess.toString()]: connectionRequested,
})
|
import React from "react"
import Svg, { Path } from "react-native-svg"
const iossharealt = props => (
<Svg width={props.size} height={props.size} fill={props.color} viewBox="0 0 512 512">
<Path d="M444.7 230.4l-141.1-132c-1.7-1.6-3.3-2.5-5.6-2.4-4.4.2-10 3.3-10 8v66.2c0 2-1.6 3.8-3.6 4.1C144.1 195.8 85 300.8 64.1 409.8c-.8 4.3 5 8.3 7.7 4.9 51.2-64.5 113.5-106.6 212-107.4 2.2 0 4.2 2.6 4.2 4.8v65c0 7 9.3 10.1 14.5 5.3l142.1-134.3c2.6-2.4 3.4-5.2 3.5-8.4-.1-3.2-.9-6.9-3.4-9.3z" />
</Svg>
)
export default iossharealt
|
import base64
# import datetime
import hashlib
import hmac
import json
import random
import re
import time
import uuid
from pathlib import Path
from typing import Dict, List
from uuid import uuid4
import requests
from pydantic import ValidationError
from instagrapi import config
from instagrapi.exceptions import (
ClientThrottledError,
PleaseWaitFewMinutes,
PrivateError,
ReloginAttemptExceeded,
TwoFactorRequired,
)
from instagrapi.utils import dumps, gen_token, generate_jazoest
# from instagrapi.zones import CET
class PreLoginFlowMixin:
"""
Helpers for pre login flow
"""
def pre_login_flow(self) -> bool:
"""
Emulation mobile app behavior before login
Returns
-------
bool
A boolean value
"""
# self.set_contact_point_prefill("prefill")
# self.get_prefill_candidates(True)
self.set_contact_point_prefill("prefill")
self.sync_launcher(True)
# self.sync_device_features(True)
return True
def get_prefill_candidates(self, login: bool = False) -> Dict:
"""
Get prefill candidates value from Instagram
Parameters
----------
login: bool, optional
Whether to login or not
Returns
-------
bool
A boolean value
"""
data = {
"android_device_id": self.android_device_id,
"client_contact_points": "[{\"type\":\"omnistring\",\"value\":\"%s\",\"source\":\"last_login_attempt\"}]" % self.username,
"phone_id": self.phone_id,
"usages": '["account_recovery_omnibox"]',
"logged_in_user_ids": "[]", # "[\"123456789\",\"987654321\"]",
"device_id": self.uuid,
}
# if login is False:
data["_csrftoken"] = self.token
return self.private_request("accounts/get_prefill_candidates/", data, login=login)
def sync_device_features(self, login: bool = False) -> Dict:
"""
Sync device features to your Instagram account
Parameters
----------
login: bool, optional
Whether to login or not
Returns
-------
Dict
A dictionary of response from the call
"""
data = {
"id": self.uuid,
"server_config_retrieval": "1",
# "experiments": config.LOGIN_EXPERIMENTS,
}
if login is False:
data["_uuid"] = self.uuid
data["_uid"] = self.user_id
data["_csrftoken"] = self.token
# headers={"X-DEVICE-ID": self.uuid}
return self.private_request("qe/sync/", data, login=login)
def sync_launcher(self, login: bool = False) -> Dict:
"""
Sync Launcher
Parameters
----------
login: bool, optional
Whether to login or not
Returns
-------
Dict
A dictionary of response from the call
"""
data = {
"id": self.uuid,
"server_config_retrieval": "1",
}
if login is False:
data["_uid"] = self.user_id
data["_uuid"] = self.uuid
data["_csrftoken"] = self.token
return self.private_request("launcher/sync/", data, login=login)
def set_contact_point_prefill(self, usage: str = "prefill") -> Dict:
"""
Sync Launcher
Parameters
----------
usage: str, optional
Default "prefill"
Returns
-------
Dict
A dictionary of response from the call
"""
data = {
"phone_id": self.phone_id,
"usage": usage,
# "_csrftoken": self.token
}
return self.private_request("accounts/contact_point_prefill/", data, login=True)
class PostLoginFlowMixin:
"""
Helpers for post login flow
"""
def login_flow(self) -> bool:
"""
Emulation mobile app behaivor after login
Returns
-------
bool
A boolean value
"""
check_flow = []
# chance = random.randint(1, 100) % 2 == 0
# reason = "pull_to_refresh" if chance else "cold_start"
check_flow.append(self.get_reels_tray_feed("cold_start"))
check_flow.append(self.get_timeline_feed(["cold_start_fetch"]))
return all(check_flow)
def get_timeline_feed(self, options: List[Dict] = ["pull_to_refresh"]) -> Dict:
"""
Get your timeline feed
Parameters
----------
options: List, optional
Configurable options
Returns
-------
Dict
A dictionary of response from the call
"""
headers = {
"X-Ads-Opt-Out": "0",
"X-DEVICE-ID": self.uuid,
"X-CM-Bandwidth-KBPS": '-1.000', # str(random.randint(2000, 5000)),
"X-CM-Latency": str(random.randint(1, 5)),
}
data = {
"feed_view_info": "[]", # e.g. [{"media_id":"2634223601739446191_7450075998","version":24,"media_pct":1.0,"time_info":{"10":63124,"25":63124,"50":63124,"75":63124},"latest_timestamp":1628253523186}]
"phone_id": self.phone_id,
"battery_level": random.randint(25, 100),
"timezone_offset": str(self.timezone_offset),
"_csrftoken": self.token,
"device_id": self.uuid,
"request_id": self.request_id,
"_uuid": self.uuid,
"is_charging": random.randint(0, 1),
"will_sound_on": random.randint(0, 1),
"session_id": self.client_session_id,
"bloks_versioning_id": self.bloks_versioning_id,
}
if "pull_to_refresh" in options:
data["reason"] = "pull_to_refresh"
data["is_pull_to_refresh"] = "1"
elif "cold_start_fetch" in options:
data["reason"] = "cold_start_fetch"
data["is_pull_to_refresh"] = "0"
# if "push_disabled" in options:
# data["push_disabled"] = "true"
# if "recovered_from_crash" in options:
# data["recovered_from_crash"] = "1"
return self.private_request(
"feed/timeline/", json.dumps(data), with_signature=False, headers=headers
)
def get_reels_tray_feed(self, reason: str = "pull_to_refresh") -> Dict:
"""
Get your reels tray feed
Parameters
----------
reason: str, optional
Default "pull_to_refresh"
Returns
-------
Dict
A dictionary of response from the call
"""
data = {
"supported_capabilities_new": config.SUPPORTED_CAPABILITIES,
"reason": reason,
"timezone_offset": str(self.timezone_offset),
"tray_session_id": self.tray_session_id,
"request_id": self.request_id,
"latest_preloaded_reel_ids": "[]", # [{"reel_id":"6009504750","media_count":"15","timestamp":1628253494,"media_ids":"[\"2634301737009283814\",\"2634301789371018685\",\"2634301853921370532\",\"2634301920174570551\",\"2634301973895112725\",\"2634302037581608844\",\"2634302088273817272\",\"2634302822117736694\",\"2634303181452199341\",\"2634303245482345741\",\"2634303317473473894\",\"2634303382971517344\",\"2634303441062726263\",\"2634303502039423893\",\"2634303754729475501\"]"},{"reel_id":"4357392188","media_count":"4","timestamp":1628250613,"media_ids":"[\"2634142331579781054\",\"2634142839803515356\",\"2634150786575125861\",\"2634279566740346641\"]"},{"reel_id":"5931631205","media_count":"7","timestamp":1628253023,"media_ids":"[\"2633699694927154768\",\"2634153361241413763\",\"2634196788830183839\",\"2634219197377323622\",\"2634294221109889541\",\"2634299705648894876\",\"2634299760434939842\"]"}],
"page_size": 50,
# "_csrftoken": self.token,
"_uuid": self.uuid,
}
return self.private_request("feed/reels_tray/", data)
class LoginMixin(PreLoginFlowMixin, PostLoginFlowMixin):
username = None
password = None
authorization = "" # Bearer IGT:2:<base64:authorization_data>
authorization_data = {} # decoded authorization header
last_login = None
relogin_attempt = 0
device_settings = {}
client_session_id = ""
tray_session_id = ""
advertising_id = ""
android_device_id = ""
request_id = ""
phone_id = ""
app_id = "567067343352427"
uuid = ""
mid = ""
country = "US"
country_code = 1 # Phone code, default USA
locale = "en_US"
timezone_offset: int = -14400 # New York, GMT-4 in seconds
ig_u_rur = "" # e.g. CLN,49897488153,1666640702:01f7bdb93090f4f773516fc2cf1424178a58a2295b4c754090ba02cb0a834e2d1f731e20
ig_www_claim = "" # e.g. hmac.AR2uidim8es5kYgDiNxY0UG_ZhffFFSt8TGCV5eA1VYYsMNx
def __init__(self):
self.user_agent = None
self.settings = None
def init(self) -> bool:
"""
Initialize Login helpers
Returns
-------
bool
A boolean value
"""
if "cookies" in self.settings:
self.private.cookies = requests.utils.cookiejar_from_dict(
self.settings["cookies"]
)
self.authorization_data = self.settings.get('authorization_data', {})
self.last_login = self.settings.get("last_login")
self.set_timezone_offset(self.settings.get("timezone_offset", self.timezone_offset))
self.set_device(self.settings.get("device_settings"))
self.bloks_versioning_id = hashlib.sha256(json.dumps(self.device_settings).encode()).hexdigest()
self.set_user_agent(self.settings.get("user_agent"))
self.set_uuids(self.settings.get("uuids", {}))
self.set_locale(self.settings.get("locale", self.locale))
self.set_country(self.settings.get("country", self.country))
self.set_country_code(self.settings.get("country_code", self.country_code))
self.mid = self.settings.get("mid", self.cookie_dict.get("mid"))
self.set_ig_u_rur(self.settings.get("ig_u_rur"))
self.set_ig_www_claim(self.settings.get("ig_www_claim"))
# init headers
headers = self.base_headers
headers.update({'Authorization': self.authorization})
self.private.headers.update(headers)
return True
def login_by_sessionid(self, sessionid: str) -> bool:
"""
Login using session id
Parameters
----------
sessionid: str
Session ID
Returns
-------
bool
A boolean value
"""
assert isinstance(sessionid, str) and len(sessionid) > 30, "Invalid sessionid"
self.settings = {"cookies": {"sessionid": sessionid}}
self.init()
user_id = re.search(r"^\d+", sessionid).group()
self.authorization_data = {
"ds_user_id": user_id,
"sessionid": sessionid,
"should_use_header_over_cookies": True
}
try:
user = self.user_info_v1(int(user_id))
except (PrivateError, ValidationError):
user = self.user_short_gql(int(user_id))
self.username = user.username
self.cookie_dict["ds_user_id"] = user.pk
return True
def login(self, username: str, password: str, relogin: bool = False, verification_code: str = '') -> bool:
"""
Login
Parameters
----------
username: str
Instagram Username
password: str
Instagram Password
relogin: bool
Whether or not to re login, default False
verification_code: str
2FA verification code
Returns
-------
bool
A boolean value
"""
self.username = username
self.password = password
self.init()
if relogin:
self.private.cookies.clear()
if self.relogin_attempt > 1:
raise ReloginAttemptExceeded()
self.relogin_attempt += 1
# if self.user_id and self.last_login:
# if time.time() - self.last_login < 60 * 60 * 24:
# return True # already login
if self.user_id and not relogin:
return True # already login
# try:
# self.pre_login_flow()
# except (PleaseWaitFewMinutes, ClientThrottledError):
# self.logger.warning('Ignore 429: Continue login')
# # The instagram application ignores this error
# # and continues to log in (repeat this behavior)
enc_password = self.password_encrypt(password)
data = {
"jazoest": generate_jazoest(self.phone_id),
"country_codes": "[{\"country_code\":\"%d\",\"source\":[\"default\"]}]" % int(self.country_code),
"phone_id": self.phone_id,
"enc_password": enc_password,
"username": username,
"adid": self.advertising_id,
"guid": self.uuid,
"device_id": self.android_device_id,
"google_tokens": "[]",
"login_attempt_count": "0"
}
try:
logged = self.private_request("accounts/login/", data, login=True)
self.authorization_data = self.parse_authorization(
self.last_response.headers.get('ig-set-authorization')
)
except TwoFactorRequired as e:
if not verification_code.strip():
raise TwoFactorRequired(f'{e} (you did not provide verification_code for login method)')
two_factor_identifier = self.last_json.get(
'two_factor_info', {}
).get('two_factor_identifier')
data = {
"verification_code": verification_code,
"phone_id": self.phone_id,
"_csrftoken": self.token,
"two_factor_identifier": two_factor_identifier,
"username": username,
"trust_this_device": "0",
"guid": self.uuid,
"device_id": self.uuid,
"waterfall_id": str(uuid4()),
"verification_method": "3"
}
logged = self.private_request("accounts/two_factor_login/", data, login=True)
if logged:
# self.login_flow()
self.last_login = time.time()
return True
return False
def one_tap_app_login(self, user_id: int, nonce: str) -> bool:
"""One tap login emulation
Parameters
----------
user_id: int
User ID
nonce: str
Login nonce (from Instagram, e.g. in /logout/)
Returns
-------
bool
A boolean value
"""
user_id = int(user_id)
data = {
"phone_id": self.phone_id,
"user_id": user_id,
"adid": self.advertising_id,
"guid": self.uuid,
"device_id": self.uuid,
"login_nonce": nonce,
"_csrftoken": self.token
}
return self.private_request("accounts/one_tap_app_login/", data)
def relogin(self) -> bool:
"""
Relogin helper
Returns
-------
bool
A boolean value
"""
return self.login(self.username, self.password, relogin=True)
@property
def cookie_dict(self) -> dict:
return self.private.cookies.get_dict()
@property
def sessionid(self) -> str:
sessionid = self.cookie_dict.get("sessionid")
if not sessionid and self.authorization_data:
sessionid = self.authorization_data.get('sessionid')
return sessionid
@property
def token(self) -> str:
"""CSRF token
e.g. vUJGjpst6szjI38mZ6Pb1dROsWVerZelGSYGe0W1tuugpSUefVjRLj2Pom2SWNoA
"""
if not getattr(self, '_token', None):
self._token = self.cookie_dict.get("csrftoken", gen_token(64))
return self._token
@property
def rank_token(self) -> str:
return f"{self.user_id}_{self.uuid}"
@property
def user_id(self) -> int:
user_id = self.cookie_dict.get("ds_user_id")
if not user_id and self.authorization_data:
user_id = self.authorization_data.get('ds_user_id')
if user_id:
return int(user_id)
return None
@property
def device(self) -> dict:
return {
key: val
for key, val in self.device_settings.items()
if key in ["manufacturer", "model", "android_version", "android_release"]
}
def get_settings(self) -> Dict:
"""
Get current session settings
Returns
-------
Dict
Current session settings as a Dict
"""
return {
"uuids": {
"phone_id": self.phone_id,
"uuid": self.uuid,
"client_session_id": self.client_session_id,
"advertising_id": self.advertising_id,
"android_device_id": self.android_device_id,
# "device_id": self.uuid,
"request_id": self.request_id,
"tray_session_id": self.tray_session_id,
},
"mid": self.mid,
"ig_u_rur": self.ig_u_rur,
"ig_www_claim": self.ig_www_claim,
"authorization_data": self.authorization_data,
"cookies": requests.utils.dict_from_cookiejar(self.private.cookies),
"last_login": self.last_login,
"device_settings": self.device_settings,
"user_agent": self.user_agent,
"country": self.country,
"country_code": self.country_code,
"locale": self.locale,
"timezone_offset": self.timezone_offset,
}
def set_settings(self, settings: Dict) -> bool:
"""
Set session settings
Returns
-------
Bool
"""
self.settings = settings
self.init()
return True
def load_settings(self, path: Path) -> Dict:
"""
Load session settings
Parameters
----------
path: Path
Path to storage file
Returns
-------
Dict
Current session settings as a Dict
"""
with open(path, 'r') as fp:
self.set_settings(json.load(fp))
return self.settings
return None
def dump_settings(self, path: Path) -> bool:
"""
Serialize and save session settings
Parameters
----------
path: Path
Path to storage file
Returns
-------
Bool
"""
with open(path, 'w') as fp:
json.dump(self.get_settings(), fp)
return True
def set_device(self, device: Dict = None, reset: bool = False) -> bool:
"""
Helper to set a device for login
Parameters
----------
device: Dict, optional
Dict of device settings, default is None
Returns
-------
bool
A boolean value
"""
self.device_settings = device or {
"app_version": "203.0.0.29.118",
"android_version": 26,
"android_release": "8.0.0",
"dpi": "480dpi",
"resolution": "1080x1920",
"manufacturer": "Xiaomi",
"device": "MI 5s",
"model": "capricorn",
"cpu": "qcom",
"version_code": "314665256",
}
self.settings["device_settings"] = self.device_settings
if reset:
self.set_uuids({})
# self.settings = self.get_settings()
return True
def set_user_agent(self, user_agent: str = "", reset: bool = False) -> bool:
"""
Helper to set user agent
Parameters
----------
user_agent: str, optional
User agent, default is ""
Returns
-------
bool
A boolean value
"""
data = dict(self.device_settings, locale=self.locale)
self.user_agent = user_agent or config.USER_AGENT_BASE.format(**data)
# self.private.headers.update({"User-Agent": self.user_agent}) # changed in base_headers
# self.settings["user_agent"] = self.user_agent
if reset:
self.set_uuids({})
# self.settings = self.get_settings()
return True
def set_uuids(self, uuids: Dict = None) -> bool:
"""
Helper to set uuids
Parameters
----------
uuids: Dict, optional
UUIDs, default is None
Returns
-------
bool
A boolean value
"""
self.phone_id = uuids.get("phone_id", self.generate_uuid())
self.uuid = uuids.get("uuid", self.generate_uuid())
self.client_session_id = uuids.get("client_session_id", self.generate_uuid())
self.advertising_id = uuids.get("advertising_id", self.generate_uuid())
self.android_device_id = uuids.get("android_device_id", self.generate_android_device_id())
self.request_id = uuids.get("request_id", self.generate_uuid())
self.tray_session_id = uuids.get("tray_session_id", self.generate_uuid())
# self.device_id = uuids.get("device_id", self.generate_uuid())
self.settings["uuids"] = uuids
return True
def generate_uuid(self, prefix: str = '', suffix: str = '') -> str:
"""
Helper to generate uuids
Returns
-------
str
A stringified UUID
"""
return f'{prefix}{uuid.uuid4()}{suffix}'
def generate_mutation_token(self) -> str:
"""
Token used when DM sending and upload media
Returns
-------
str
A stringified int
"""
return str(random.randint(6800011111111111111, 6800099999999999999))
def generate_android_device_id(self) -> str:
"""
Helper to generate Android Device ID
Returns
-------
str
A random android device id
"""
return "android-%s" % hashlib.md5(str(time.time()).encode()).hexdigest()[:16]
def expose(self) -> Dict:
"""
Helper to expose
Returns
-------
Dict
A dictionary of response from the call
"""
data = {"id": self.uuid, "experiment": "ig_android_profile_contextual_feed"}
return self.private_request("qe/expose/", self.with_default_data(data))
def with_default_data(self, data: Dict) -> Dict:
"""
Helper to get default data
Returns
-------
Dict
A dictionary of default data
"""
return dict(
{
"_uuid": self.uuid,
# "_uid": str(self.user_id),
# "_csrftoken": self.token,
"device_id": self.android_device_id,
},
**data,
)
def with_action_data(self, data: Dict) -> Dict:
"""
Helper to get action data
Returns
-------
Dict
A dictionary of action data
"""
return dict(self.with_default_data({"radio_type": "wifi-none"}), **data)
def gen_user_breadcrumb(self, size: int) -> str:
"""
Helper to generate user breadcrumbs
Parameters
----------
size: int
Integer value
Returns
-------
Str
A string
"""
key = "iN4$aGr0m"
dt = int(time.time() * 1000)
time_elapsed = random.randint(500, 1500) + size * random.randint(500, 1500)
text_change_event_count = max(1, size / random.randint(3, 5))
data = "{size!s} {elapsed!s} {count!s} {dt!s}".format(
**{
"size": size,
"elapsed": time_elapsed,
"count": text_change_event_count,
"dt": dt,
}
)
return "{!s}\n{!s}\n".format(
base64.b64encode(
hmac.new(
key.encode("ascii"), data.encode("ascii"), digestmod=hashlib.sha256
).digest()
),
base64.b64encode(data.encode("ascii")),
)
def inject_sessionid_to_public(self) -> bool:
"""
Inject sessionid from private session to public session
Returns
-------
bool
A boolean value
"""
if self.sessionid:
self.public.cookies.set("sessionid", self.sessionid)
return True
return False
def logout(self) -> bool:
result = self.private_request(
"accounts/logout/",
{'one_tap_app_login': True}
)
return result["status"] == "ok"
def parse_authorization(self, authorization) -> dict:
"""Parse authorization header
"""
try:
b64part = authorization.rsplit(':', 1)[-1]
return json.loads(base64.b64decode(b64part))
except Exception as e:
self.logger.exception(e)
return {}
@property
def authorization(self) -> str:
"""Build authorization header
Example: Bearer IGT:2:eaW9u.....aWQiOiI0NzM5=
"""
if self.authorization_data:
b64part = base64.b64encode(
dumps(self.authorization_data).encode()
).decode()
return f'Bearer IGT:2:{b64part}'
return ''
|
from CTFd import create_app
from elasticsearch import helpers, Elasticsearch
from CTFd.utils import get_app_config
import csv
import glob
import os
import pandas as pd
import schedule
import sqlite3
import time
import uuid
def export():
app = create_app()
with app.app_context():
# Generate temp folder from uploads
upload_folder = get_app_config("UPLOAD_FOLDER")
random_name = uuid.uuid4().hex
upload_folder_name = upload_folder + '/' + random_name + '/'
os.mkdir(upload_folder_name)
db = get_app_config("SQLALCHEMY_DATABASE_URI").replace("sqlite:///", "")
conn = sqlite3.connect(db)
cur = conn.cursor()
# Users
cur.execute("SELECT * from users")
result = cur.fetchall()
cur.execute("SELECT name FROM pragma_table_info('users')")
header_list = cur.fetchall()
with open(upload_folder_name + 'user.csv', 'w', newline='', encoding='utf-8') as csv_file:
c = csv.writer(csv_file, delimiter=',')
c.writerow(header_list)
for x in result:
c.writerow(x)
# Votes
cur.execute("SELECT * from votes")
result = cur.fetchall()
cur.execute("SELECT name FROM pragma_table_info('votes')")
header_list = cur.fetchall()
with open(upload_folder_name + 'vote.csv', 'w', newline='', encoding='utf-8') as csv_file:
c = csv.writer(csv_file, delimiter=',')
c.writerow(header_list)
for x in result:
c.writerow(x)
# Challenges
cur.execute("SELECT * from challenges")
result = cur.fetchall()
cur.execute("SELECT name FROM pragma_table_info('challenges')")
header_list = cur.fetchall()
with open(upload_folder_name + 'challenge.csv', 'w', newline='', encoding='utf-8') as csv_file:
c = csv.writer(csv_file, delimiter=',')
c.writerow(header_list)
for x in result:
c.writerow(x)
# Solves
cur.execute("SELECT * from solves")
result = cur.fetchall()
cur.execute("SELECT name FROM pragma_table_info('solves')")
header_list = cur.fetchall()
with open(upload_folder_name + 'solve.csv', 'w', newline='', encoding='utf-8') as csv_file:
c = csv.writer(csv_file, delimiter=',')
c.writerow(header_list)
for x in result:
c.writerow(x)
# Submission
cur.execute("SELECT * from submissions")
result = cur.fetchall()
cur.execute("SELECT name FROM pragma_table_info('submissions')")
header_list = cur.fetchall()
with open(upload_folder_name + 'submission.csv', 'w', newline='', encoding='utf-8') as csv_file:
c = csv.writer(csv_file, delimiter=',')
c.writerow(header_list)
for x in result:
c.writerow(x)
# Tags
cur.execute("SELECT * from tags")
result = cur.fetchall()
cur.execute("SELECT name FROM pragma_table_info('tags')")
header_list = cur.fetchall()
with open(upload_folder_name + 'tag.csv', 'w', newline='', encoding='utf-8') as csv_file:
c = csv.writer(csv_file, delimiter=',')
c.writerow(header_list)
for x in result:
c.writerow(x)
# TagChallenge
cur.execute("SELECT * from tag_challenge")
result = cur.fetchall()
cur.execute("SELECT name FROM pragma_table_info('tag_challenge')")
header_list = cur.fetchall()
with open(upload_folder_name + 'tagChallenge.csv', 'w', newline='', encoding='utf-8') as csvFile:
c = csv.writer(csvFile, delimiter=',')
c.writerow(header_list)
for x in result:
c.writerow(x)
# Closing connection
conn.close()
# Merge Submissions and Challenges
sub = pd.read_csv(upload_folder_name + "submission.csv", sep=',')
chal = pd.read_csv(upload_folder_name + "challenge.csv", sep=',')
challenge = chal.rename(columns={"('id',)": "('challenge_id',)"})
challenge = challenge.drop(columns=["('type',)", ], axis=1)
submission = sub.set_index("('challenge_id',)")
challenges = challenge.set_index("('challenge_id',)")
df_mixed_chal_sub = submission.join(challenges)
df_mixed_chal_sub.to_csv(upload_folder_name + "chal&sub.csv", sep=',')
# Merge Submissions and Users
user = pd.read_csv(upload_folder_name + "user.csv", sep=',', encoding='utf-8')
user = user.rename(columns={"('id',)": "('user_id',)"})
user = user.drop(columns=["('type',)", ], axis=1)
submission = sub.set_index("('user_id',)")
users = user.set_index("('user_id',)")
df_mixed_user_sub = submission.join(users)
df_mixed_user_sub.to_csv(upload_folder_name + "user&sub.csv", sep=',')
# Merge Tag and TagChallenge
tag = pd.read_csv(upload_folder_name + "tag.csv", sep=',', encoding='utf-8')
tag_challenge = pd.read_csv(upload_folder_name + "tagChallenge.csv", sep=',', encoding='utf-8')
tags = tag.rename(columns={"('id',)": "('tag_id',)"})
tag_challenges = tag_challenge.set_index("('tag_id',)")
tagss = tags.set_index("('tag_id',)")
df_mixed_tag_chal = tag_challenges.join(tagss)
df_mixed_tag_chal.to_csv(upload_folder_name + "merge_tagchal.csv", sep=',')
# ES connection
es = Elasticsearch()
with open(upload_folder_name + 'submission.csv', encoding='utf-8') as f:
reader = csv.DictReader(f)
if es.indices.exists(index="submission"):
es.indices.delete(index='submission')
helpers.bulk(es, reader, index='submission', doc_type='my-type')
with open(upload_folder_name + 'solve.csv', encoding='utf-8') as f:
reader = csv.DictReader(f)
if es.indices.exists(index="solve"):
es.indices.delete(index='solve')
helpers.bulk(es, reader, index='solve', doc_type='my-type')
with open(upload_folder_name + 'challenge.csv', encoding='utf-8') as f:
reader = csv.DictReader(f)
if es.indices.exists(index="challenge"):
es.indices.delete(index='challenge')
helpers.bulk(es, reader, index='challenge', doc_type='my-type')
with open(upload_folder_name + 'vote.csv', encoding='utf-8') as f:
reader = csv.DictReader(f)
if es.indices.exists(index="vote"):
es.indices.delete(index='vote')
helpers.bulk(es, reader, index='vote', doc_type='my-type')
with open(upload_folder_name + 'user.csv', encoding='utf-8') as f:
reader = csv.DictReader(f)
if es.indices.exists(index="user"):
es.indices.delete(index='user')
helpers.bulk(es, reader, index='user', doc_type='my-type')
with open(upload_folder_name + 'chal&sub.csv', encoding='utf-8') as f:
reader = csv.DictReader(f)
if es.indices.exists(index="chal&sub"):
es.indices.delete(index='chal&sub')
helpers.bulk(es, reader, index='chal&sub', doc_type='my-type')
with open(upload_folder_name + 'user&sub.csv', encoding='utf-8') as f:
reader = csv.DictReader(f)
if es.indices.exists(index="user&sub"):
es.indices.delete(index='user&sub')
helpers.bulk(es, reader, index='user&sub', doc_type='my-type')
with open(upload_folder_name + 'merge_tagchal.csv', encoding='utf-8') as f:
reader = csv.DictReader(f)
if es.indices.exists(index="merge_tagchal"):
es.indices.delete(index='merge_tagchal')
helpers.bulk(es, reader, index='merge_tagchal', doc_type='my-type')
# Remove files and folder
files = glob.glob(upload_folder_name + '*')
for file in files:
os.remove(file)
os.rmdir(upload_folder_name)
print("Data updated")
export()
schedule.every(1).minutes.do(export)
while 1:
schedule.run_pending()
time.sleep(1)
|
'use strict';
exports.__esModule = true;
exports.SET_RESULTS = exports.NEXT_QUESTION = exports.ANSWER_COLLECTION = undefined;
exports.nextQuestion = nextQuestion;
exports.postAnswerGetQuestion = postAnswerGetQuestion;
var _axiosConfigInitial = require('./axiosConfigInitial');
var _axiosConfigInitial2 = _interopRequireDefault(_axiosConfigInitial);
var _fetch = require('./fetch');
var _error = require('./error');
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var ANSWER_COLLECTION = exports.ANSWER_COLLECTION = 'ANSWER_COLLECTION';
var NEXT_QUESTION = exports.NEXT_QUESTION = 'NEXT_QUESTION';
var SET_RESULTS = exports.SET_RESULTS = 'SET_RESULTS';
function nextQuestion(nextQuestion) {
return {
type: NEXT_QUESTION,
nextQuestion: nextQuestion
};
}
function setResults(results) {
return {
type: SET_RESULTS,
results: results
};
}
function saveAnswers(answer) {
return {
type: ANSWER_COLLECTION,
answer: answer
};
}
function postAnswerGetQuestion(response, answer) {
return function (dispatch, getState) {
var state = getState().pushkin;
dispatch((0, _fetch.requestQuestionBegin)());
if (Array.isArray(response.choiceId) && response.choiceId.length > 0) {
return Promise.all(response.choiceId.map(function (currentId) {
return _axiosConfigInitial2.default.post('response', {
choiceId: currentId,
questionId: response.questionId,
user: {
id: response.user.id
}
}).then(function (resp) {
return resp.data;
});
})).then(function (data) {
if (!data[0]) {
return _axiosConfigInitial2.default.get('/results/' + state.userInfo.id).then(function (resp) {
return resp.data.results;
}).then(function (results) {
dispatch(setResults(results));
dispatch(nextQuestion(null));
});
} else {
// if (state.options.saveAnswers) {
// dispatch(saveAnswers(answer))
// }
dispatch(nextQuestion(data[0]));
}
}).catch(function (err) {
return dispatch((0, _error.error)(err));
});
}
return _axiosConfigInitial2.default.post('response', response).then(function (resp) {
if (resp.error) {
return dispatch((0, _error.error)(resp.error));
}
if (!resp.data) {
return _axiosConfigInitial2.default.get('/results/' + state.userInfo.id).then(function (resp) {
return resp.data.results;
}).then(function (results) {
dispatch(setResults(results));
dispatch(nextQuestion(null));
});
} else {
// if (state.options.saveAnswers) {
// dispatch(saveAnswers(answer))
// }
dispatch(nextQuestion(resp.data));
}
});
// .catch(err => {
// return dispatch(error(err));
// });
};
}
|
/*
Month/Year date format with slash "/" (also "-" and ".") between numbers
- 11/05
- 06/2005
*/
var moment = require('moment');
var Parser = require('../parser').Parser;
var ParsedResult = require('../../result').ParsedResult;
var PATTERN = new RegExp('(^|[^\\d/]\\s+|[^\\w\\s])' +
'([0-9]|0[1-9]|1[012])/([0-9]{4})' +
'([^\\d/]|$)', 'i');
var OPENNING_GROUP = 1;
var ENDING_GROUP = 4;
var MONTH_GROUP = 2;
var YEAR_GROUP = 3;
exports.Parser = function ENSlashMonthFormatParser(argument) {
Parser.apply(this, arguments);
this.pattern = function () { return PATTERN; };
this.extract = function(text, ref, match, opt){
var index = match.index + match[OPENNING_GROUP].length;
var text = match[0].substr(match[OPENNING_GROUP].length, match[0].length - (1 + match[ENDING_GROUP].length)).trim();
var result = new ParsedResult({
text: text,
index: index,
ref: ref,
});
var date = null;
var year = match[YEAR_GROUP] ;
var month = match[MONTH_GROUP];
var day = 1;
month = parseInt(month);
year = parseInt(year);
result.start.imply('day', day);
result.start.assign('month', month);
result.start.assign('year', year);
result.tags['ENSlashMonthFormatParser'] = true;
return result;
};
};
|
#! /usr/local/bin/node
const _ = require('lodash')
const Docker = require('node-docker-api').Docker
const ConsulProvider = require('./providers/consul')
const Registrator = require('./registrator')
const EventsListener = require('./events-listener')
const argv = require('yargs')
.option('socket', {describe: 'path to docker socket'})
.option('consul', {describe: 'consul url'})
.option('resync', {describe: 'resync interval (seconds), 0 - never'})
.demandOption(['socket', 'consul'])
.help()
.argv
let docker = new Docker({socketPath: argv.socket})
let provider = new ConsulProvider(argv.consul)
let registrator = new Registrator(provider)
let eventsListener = new EventsListener()
eventsListener.on('start', event => {
let c = docker.container.get(event.id)
registrator.addService(c)
})
eventsListener.on('die', event => {
registrator.removeService(event.id)
})
docker.events()
.then(stream => {
eventsListener.listen(stream)
})
.catch(e => {
console.error(e)
process.exit(1)
})
const resync = () => {
docker.container.list({status: ['running']})
.then(containers => {
registrator.resyncServices(containers)
})
.catch(e => {
console.error(e)
})
}
resync()
if (argv.resync) {
setInterval(resync, argv.resync * 1000)
}
process.stdin.resume()
process.on('SIGINT', () => {
console.log('exiting...')
process.exit()
})
|
// Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { observer } from 'mobx-react';
import List from 'semantic-ui-react/dist/commonjs/elements/List';
import Popup from 'semantic-ui-react/dist/commonjs/modules/Popup';
import IdentityIcon from '@parity/ui/lib/IdentityIcon';
import AccountItem from './AccountItem';
import styles from './defaultAccount.css';
@observer
class DefaultAccount extends Component {
state = {
isOpen: false
}
static propTypes = {
accountStore: PropTypes.object.isRequired
}
handleOpen = () => {
this.setState({ isOpen: true });
}
handleClose = () => {
this.setState({ isOpen: false });
}
handleMakeDefault = (address) => {
this.handleClose();
if (address === this.props.accountStore.defaultAddress) { return; }
this.props.accountStore.makeDefaultAccount(address);
}
render () {
const { allAccounts, defaultAccount: defaultAddress } = this.props.accountStore;
const defaultAccount = allAccounts.find(({ address }) => address === defaultAddress);
if (!allAccounts || !defaultAccount) { return null; }
return (
<Popup
wide='very'
className={ styles.popup }
trigger={
<IdentityIcon
address={ defaultAddress } button
center
className={ styles.defaultAccount }
/>
}
content={
<div>
<List relaxed='very' selection className={ [styles.list, allAccounts.length > 1 && styles.hasOtherAccounts].join(' ') }>
<AccountItem
isDefault
account={ defaultAccount }
/>
</List>
{allAccounts.length > 1 &&
<List relaxed='very' selection className={ [styles.list, styles.accountsList].join(' ') } divided>
{allAccounts
.filter(({ address }) => address !== defaultAddress)
.map(account => (
<AccountItem
key={ account.address }
account={ account }
onClick={ this.handleMakeDefault }
/>
))}
</List>
}
</div>
}
offset={ 13 } // Empirically looks better
on='click'
hideOnScroll
open={ this.state.isOpen }
onClose={ this.handleClose }
onOpen={ this.handleOpen }
position='bottom right'
/>
);
}
}
export default DefaultAccount;
|
"""
##################################################################################################
# Copyright Info : Copyright (c) Davar Lab @ Hikvision Research Institute. All rights reserved.
# Filename : __init__.py
# Abstract :
# Current Version: 1.0.0
# Date : 2021-03-19
##################################################################################################
"""
from .builder import SPOTTER, build_spotter
from .spotters import MANGO, TwoStageEndToEnd
from .seg_heads import CenterlineSegHead, CharacterMaskAttentionHead, GridCategoryHead
from .sequence_heads import MultiRecogSeqHead
from .connect_modules import AttFuseModule
from .roi_extractors import MaskRoIExtractor
__all__ = [ 'SPOTTER','build_spotter', 'MANGO', 'TwoStageEndToEnd',
'CenterlineSegHead', 'CharacterMaskAttentionHead', 'GridCategoryHead',
'MultiRecogSeqHead', 'AttFuseModule', 'MaskRoIExtractor'
]
|
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
/**
* This sample demonstrates how get a list of collections
*
* @summary gets a list of collections
*/
const PurviewAccount = require("@azure-rest/purview-Account");
const { DefaultAzureCredential } = require("@azure/identity");
const dotenv = require("dotenv");
dotenv.config();
const endpoint = process.env["ENDPOINT"] || "";
async function main() {
console.log("== List collections sample ==");
const client = PurviewAccount(endpoint, new DefaultAzureCredential());
const response = await client.path("/collections").get();
if (response.status !== "200") {
console.log(`GET "/collections" failed with ${response.status}`);
}
console.log(response.body);
}
main().catch(console.error);
|
from flask import Flask, request, render_template, redirect, session, url_for
from flask import request as request
import db
import datetime
import DBcm
from flask_mail import Mail, Message
import secrets
# crate app object
app = Flask(__name__)
# generate secret key
app.secret_key = "87ewQZr"
# configure email settings
app.config['MAIL_SERVER'] = 'smtp.gmail.com'
app.config['MAIL_PORT'] = 465
app.config['MAIL_USERNAME'] = 'mathsquizgenerator@gmail.com'
app.config['MAIL_PASSWORD'] = 'Teacher123'
app.config['MAIL_USE_TLS'] = False
app.config['MAIL_USE_SSL'] = True
mail = Mail(app)
connection = {
"host": "127.0.0.1",
"user": "root",
"password": "root",
"database": "quiz",
}
# registration page
@app.route("/register", methods=["GET", "POST"])
def register():
# Output message if something goes wrong...
msg = ''
# get available groups that user can register to
studentGroups = db.getStudentGroups()
# Check if username and password were submitted
if request.method == 'POST' and 'username' in request.form and 'password' in request.form:
# Create variables for easy access
isTeacher = request.form['teacher']
username = request.form['username']
password = request.form['password']
email = request.form['email']
# check if user is creating the teacher account
if isTeacher == "true":
# Check if account exists using MySQL
with DBcm.UseDatabase(connection) as cursor:
cursor.execute("SELECT * FROM teacher WHERE username = '%s'" % username)
account = cursor.fetchone()
# If account exists show error and validation checks
if account:
msg = 'Account already exists!'
else:
# Account doesnt exists and the form data is valid, now insert new account into accounts table
with DBcm.UseDatabase(connection) as cursor:
cursor.execute("INSERT INTO teacher (username,password,email,teacher)" \
" VALUES ('%s', '%s', '%s', '%s')" % (username, password, email, isTeacher))
msg = 'You have successfully registered!'
else:
group = request.form['group']
# Check if account exists using MySQL
with DBcm.UseDatabase(connection) as cursor:
cursor.execute('SELECT * FROM student WHERE username = %s', (username,))
account = cursor.fetchone()
# If account exists show error and validation checks
if account:
msg = 'Account already exists!'
else:
name = request.form['firstname']
surname = request.form['surname']
# Account doesnt exists and the form data is valid, now insert new account into student table
with DBcm.UseDatabase(connection) as cursor:
cursor.execute("INSERT INTO student (username,password,email,userGroup,name,surname)" \
" VALUES ('%s', '%s', '%s', '%s', '%s', '%s')" % (
username, password, email, group, name, surname))
id = cursor.lastrowid
msg = 'You have successfully registered!'
sendAuthenticationEmail(id, username, name, surname, email, group)
# Show registration form with message (if any)
return render_template('register.html', msg=msg, the_studentGroups=studentGroups)
# login page
@app.route("/", methods=["GET", "POST"])
def login():
student = ""
if request.method == 'POST' and 'username' in request.form and 'password' in request.form:
username = request.form['username']
password = request.form['password']
message = ""
with DBcm.UseDatabase(connection) as cursor:
SQL = "select * from teacher where username='%s' and password='%s'" % (username, password)
cursor.execute(SQL)
teacher = cursor.fetchone()
if teacher is None:
SQL = "select * from student where username='%s' and password='%s' and authenticated=1" % (
username, password)
cursor.execute(SQL)
student = cursor.fetchone()
if student is None:
message = "Account is not authenticated or credentials are incorrect"
if teacher:
session['access'] = True
session['username'] = teacher[1]
session['id'] = teacher[0]
session['teacher'] = teacher[4]
session['group'] = 'A'
elif student:
session['access'] = True
session['username'] = student[1]
session['id'] = student[0]
session['group'] = student[3]
else:
return render_template("index.html", msg=message)
return redirect(url_for('home'))
else:
return render_template("index.html")
# logout page
@app.route("/logout")
def logout():
# clear session data
session.clear()
# redirect to login page
return redirect("/")
# home page consisting of student progres for both teacher and student
@app.route("/home", methods=["GET", "POST"])
def home():
# if logged in
if 'access' in session:
# if logged in as teacher
if 'teacher' in session:
# get student groups assigned to the teacher
studentGroups = db.getStudentGroups(session['id'])
if request.method == "POST":
group = request.form['studentGroup']
studentData = db.getStudents(group)
columnNames = ["Student ID", "Name", "Surname", "Current Progress"]
return render_template("studentGroups.html", the_results=studentData,the_columnNames=columnNames)
return render_template("home.html", the_studentGroups=studentGroups)
# logged in as student
else:
# get student info and quiz results
results = db.userResults(session['id'])
# initialise empty lists for data necessary to draw the chart
names = []
scores = []
movingAverage = []
currentAverage = 0
# for separate results data, calculate average and moving average values
for index, i in enumerate(results):
names.append((i[2]))
scores.append(float(i[3]))
currentAverage += float(i[3])
movingAverage.append(currentAverage / (index + 1))
# if student completed at least one quiz : get average and render page with progress chart
if len(scores) > 0:
overallAverage = round(sum(scores) / len(scores), 2)
return render_template("home.html", user=session['username'], the_names=names, the_scores=scores,
the_movingAverage=movingAverage, the_average=overallAverage)
# Student did not complete any quiz: render page with a message
else:
return render_template("home.html", user=session['username'])
# not logged in
else:
# redirect to login page
return redirect("/")
# quiz page
@app.route("/quiz", methods=["GET", "POST"])
def quiz():
# if logged in
if 'access' in session:
# get todays date
today = datetime.date.today()
# check quiz availability
ID = db.checkQuizAvailability(session['group'], today)
quizID = ID[0]
# if not quiz then display the message
if isinstance(quizID, str):
return render_template("quiz.html", the_message="Quiz is not available")
# quiz is available
else:
# if quiz is already completed display the message
if db.isCompleted(quizID, session['id']):
return render_template("quiz.html", the_message="Quiz is already completed")
# quiz is available and not completed yet
else:
# get quiz questions corresponding to the quizID
questions = db.getQuizQuestions(quizID)
# if quiz is submitted
if request.method == "POST":
# request answers from the form
data = request.form
# send answers to the database
db.answersToDatabase(data, quizID, session['id'], questions)
# redirect to the quiz transcript that includes answers
return redirect(url_for('getTest', quizID=quizID))
# Display quiz
else:
return render_template("quiz.html", the_questions=questions)
# redirect to login page if not logged in
else:
return redirect("/")
# create quiz page
@app.route("/createQuiz", methods=["GET", "POST"])
# Page where teacher is able to create quiz
def createQuiz():
# if logged in
if 'access' in session:
# get groups assigned to a given teacher
studentGroups = db.getStudentGroups(session['id'])
# if create quiz form is submitted
msg = ""
if request.method == "POST":
# get form data
data = request.form
# Create quiz using form data
db.createQuiz(data)
# Assign teachers group to a group of created quiz
session['group'] = data['group']
msg = "Quiz created successfully"
# display page with possible messages
return render_template("createQuiz.html", the_message=msg, the_studentGroups=studentGroups)
# redirect to login page if not logged in
else:
return redirect("/")
# student results page
@app.route("/studentresults", methods=["GET", "POST"])
def resultsPage():
# get student results
results = db.userResults(session['id'])
# table column names
columnNames = ["Quiz ID", "Quiz Date", "Quiz Name", "Final Score", "Transcript"]
# if submited redirect to a transcript of selected quiz
if request.method == 'POST':
return redirect(url_for("transcript.html"))
# not submited display table of student results
return render_template("studentresults.html", the_results=results, the_columnNames=columnNames)
# transcript page for student and teacher
@app.route("/transcript/<string:quizID>", methods=["GET", "POST"])
@app.route("/transcript/<string:quizID>/<int:userID>", methods=["GET", "POST"])
def getTest(quizID, userID=None):
id = quizID
# get quiz questions corresponding to quiz ID
questions = db.getQuizQuestions(id)
# accessing as student
if userID is None:
# get quiz information
info = db.quizUserInfo(session['id'], quizID)
# get selected answers
answers = db.getSelectedAnswers(id, session['id'])
# accessing as teacher
else:
# get quiz information
info = db.quizUserInfo(userID, quizID)
# get selected answers
answers = db.getSelectedAnswers(id, userID)
# render page and display transcript
return render_template("transcript.html", the_questions=questions, the_answers=answers, userInfo=info)
# Quiz results of students belonging to the teacher
@app.route("/teacherResults", methods=["GET", "POST"])
def teacherResults():
# get student groups of the teacher
studentGroups = db.getStudentGroups(session['id'])
# if submited i.e group was selected
if request.method == "POST":
# get group
group = request.form['studentGroup']
# get all quizzes assigned to that group
quizData = db.selectQuizes(group)
columnNames = ["Quiz ID", "Quiz Name", "Quiz Date", "Quiz Participants"]
# render page and display table with all the quizzes - click on the quiz to display participants
return render_template("teacherResults.html", the_studentGroups=studentGroups, the_results=quizData,
the_columnNames=columnNames)
# quiz not selected - display page with group select box
return render_template("teacherResults.html", the_studentGroups=studentGroups)
# quiz participants viewed by the teacher
@app.route("/quizParticipants/<string:quizID>", methods=["GET", "POST"])
def quizParticipants(quizID):
# get student participants of the quiz corresponding to quizID
participants = db.getParticipants(quizID)
columnNames = ["User ID", "Username", "Quiz Score", "Transcript"]
# render page and display table with all quiz participants - click on the participant to see their quiz transcript
return render_template("quizParticipants.html", the_results=participants, the_columnNames=columnNames, qID=quizID)
# group setting page
@app.route("/groupSettings", methods=["GET", "POST"])
def groupSettings():
# get student groups belonging to teacher
teachersGroups = db.getStudentGroups(session['id'])
# if submitted
if request.method == "POST":
# if submitted form contains group name : then group was created
if 'groupName' in request.form:
# get entered group name
groupName = request.form['groupName']
# create group and assign it to the teacher
db.createGroup(session['id'], groupName)
# display confirmation message
msg = "Group " + str(groupName) + " has been created"
# get student groups belonging to teacher
teachersGroups = db.getStudentGroups(session['id'])
# render page with confirmation message and updated values
return render_template("groupSettings.html", the_msg=msg,the_teachersGroups=teachersGroups)
# if submitted form contains student group : then group was selected
elif 'studentGroup' in request.form:
# get selected group
selectedGroup = request.form['studentGroup']
# get student of selected group
students = db.getGroupStudents(selectedGroup)
# save selected group inside teachers session
session['g'] = selectedGroup
# render page with list of student belonging to the selected group
return render_template("groupSettings.html",the_students=students, the_teachersGroups=teachersGroups)
# if submitted form contains user information : then student authentication was updated
elif 'userInformation' in request.form:
# get student authentication information
info = request.form
# get group name from the session storage
group = session['g']
# update students authorisation info
db.authenticateUsers(info, group)
# get student list with updated authorisation information
students = db.getGroupStudents(group)
# render page with updated list of students
return render_template("groupSettings.html", the_teachersGroups=teachersGroups,
the_info=info, the_students=students)
# not submitted: display last accessed tab
else:
return render_template("groupSettings.html", the_teachersGroups=teachersGroups)
# generate url token
u = secrets.token_urlsafe()
# function that sends notification/authentication requests email
def sendAuthenticationEmail(id, username, name, surname, emailAddress, group):
# get previously generated url token
global u
# initialise email sender and recipients
email = Message('Student account requires authentication', sender='mathsquizgenerator@gmail.com',
recipients=['mathsquizgenerator@gmail.com'])
# generate second part of url token
part2 = secrets.token_hex(16)
# join two token parts
link = u + part2
# email body : last line generates an authentication link by joining host, generated token and id of created account
email.body = "This notification is generated automatically. \r\n\n" \
"A new account has been created and requests authorisation to join group: " + str(group) + ".\r\n\n" \
"Registration data: \r\n" \
"Name: " + str(name) + "\r\n" \
"Surname: " + str(surname) + "\r\n" \
"Group: " + str(group) + "\r\n" \
"Email: " + str(emailAddress) + "\r\n\n" \
"The account can be authenticated manually inside of the quiz application or" \
" by clicking on the following link: http://127.0.0.1:5000/" + str(link) + "/" + str(id)
# send email
with mail.connect() as connector:
connector.send(email)
# authentication link/ page, initialise url type
# if link is accessed authenticate student with id contained inside url
@app.route("/" + u + "<string(length=32):key>/<int:id>")
def authenticate(key, id):
# authenticate student record
with DBcm.UseDatabase(connection) as cursor:
SQL = "update student set authenticated = 1 where userID = '%s'" % id
cursor.execute(SQL)
# return confirmation message
return "Account has been authenticated"
# Page containing overall progress of the student i.e chart
@app.route("/studentProgress/<string:studentID>", methods=["GET", "POST"])
def studentProgress(studentID):
# get student info and all results corresponding to studentID
results = db.userResults(studentID)
# initialise empty lists and variables that will contain the data necessary to draw the chart
names = []
scores = []
movingAverage = []
currentAverage = 0
# Process and separate scores and quiz names, calculate moving average points
for index, i in enumerate(results):
names.append((i[2]))
scores.append(float(i[3]))
currentAverage += float(i[3])
movingAverage.append(currentAverage / (index + 1))
# if student completed at least one quiz. ie if results are present
if len(scores) > 0:
# calculate overall score average
overallAverage = round(sum(scores) / len(scores), 2)
# get name and surname of the student
name = db.getStudentName(studentID)
# render page with student info and chart representing the progress of the student
return render_template("studentProgress.html", the_names=names, the_scores=scores,
the_movingAverage=movingAverage, the_average=overallAverage,the_name = name)
# No quizzes completed: return page with a message
else:
return render_template("studentProgress.html")
# set debug mode to true
if __name__ == '__main__':
app.run(debug=True)
|
import sys
import time
import operator
import pandas as pd
import numpy as np
import itertools
from sklearn.preprocessing import LabelEncoder, StandardScaler
from sklearn.model_selection import GridSearchCV
from sklearn.metrics import *
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
import itertools
from sklearn import linear_model
# read arguments (1: dataset name, 2: output file name, 3: trial #, 4: # cores)
dataset = sys.argv[1]
#output_file = sys.argv[2]
trial = sys.argv[3]
# Read the data set into memory
input_data = pd.read_csv(dataset, compression='gzip', sep='\t')
TARGET_NAME = 'target'
INPUT_SEPARATOR = '\t'
n_jobs = 1
hyper_params = [
{
'alpha': (1e-04,0.001,0.01,0.1,1,),
},
]
sc_y = StandardScaler()
X = StandardScaler().fit_transform(input_data.drop(TARGET_NAME, axis=1).values.astype(float))
y = sc_y.fit_transform(input_data[TARGET_NAME].values.reshape(-1,1))
X_train, X_test, y_train, y_test = train_test_split(X, y,
train_size=0.75,
test_size=0.25,
random_state=None)
est=linear_model.LassoLars()
grid_clf = GridSearchCV(est,cv=5,param_grid=hyper_params,
verbose=0,n_jobs=n_jobs,scoring='r2')
t0 = time.time()
#fit model
grid_clf.fit(X_train,y_train.ravel())
#get fit time
runtime = time.time()-t0
train_score_mse = mean_squared_error(sc_y.inverse_transform(grid_clf.predict(X_train)),
sc_y.inverse_transform(y_train))
train_score_mae = mean_absolute_error(sc_y.inverse_transform(grid_clf.predict(X_train)),
sc_y.inverse_transform(y_train))
train_score_r2 = r2_score(sc_y.inverse_transform(grid_clf.predict(X_train)),
sc_y.inverse_transform(y_train))
test_score_mse = mean_squared_error(sc_y.inverse_transform(grid_clf.predict(X_test)),
sc_y.inverse_transform(y_test))
test_score_mae = mean_absolute_error(sc_y.inverse_transform(grid_clf.predict(X_test)),
sc_y.inverse_transform(y_test))
test_score_r2 = r2_score(sc_y.inverse_transform(grid_clf.predict(X_test)),
sc_y.inverse_transform(y_test))
sorted_grid_params = sorted(grid_clf.best_params_.items(), key=operator.itemgetter(0))
# print results
out_text = '\t'.join([dataset.split('/')[-1][:-7],
'lasso-lars',
str(trial),
str(sorted_grid_params).replace('\n',','),
str(train_score_mse),
str(train_score_mae),
str(train_score_r2),
str(test_score_mse),
str(test_score_mae),
str(test_score_r2),
str(runtime)])
print(out_text)
sys.stdout.flush()
|
const config = {
siteTitle: "Gatsby Advanced Starter", // Site title.
siteTitleShort: "GA Starter", // Short site title for homescreen (PWA). Preferably should be under 12 characters to prevent truncation.
siteTitleAlt: "GatsbyJS Advanced Starter", // Alternative site title for SEO.
siteLogo: "/logos/logo-1024.png", // Logo used for SEO and manifest.
siteUrl: "https://gatsby-advanced-starter-demo.netlify.com", // Domain of your website without pathPrefix.
pathPrefix: "/", // Prefixes all links. For cases when deployed to example.github.io/gatsby-advanced-starter/.
siteDescription: "A GatsbyJS starter with Advanced design in mind.", // Website description used for RSS feeds/meta description tag.
siteRss: "/rss.xml", // Path to the RSS file.
siteRssTitle: "Gatsby Advanced Starter RSS feed", // Title of the RSS feed
siteFBAppID: "1825356251115265", // FB Application ID for using app insights
googleAnalyticsID: "UA-47311644-5", // GA tracking ID.
disqusShortname: "https-vagr9k-github-io-gatsby-advanced-starter", // Disqus shortname.
dateFromFormat: "YYYY-MM-DD", // Date format used in the frontmatter.
dateFormat: "DD/MM/YYYY", // Date format for display.
postsPerPage: 4, // Amount of posts displayed per listing page.
userName: "Advanced User", // Username to display in the author segment.
userEmail: "AdvancedUser@example.com", // Email used for RSS feed's author segment
userTwitter: "", // Optionally renders "Follow Me" in the UserInfo segment.
userLocation: "North Pole, Earth", // User location to display in the author segment.
userAvatar: "https://api.adorable.io/avatars/150/test.png", // User avatar to display in the author segment.
userDescription:
"Yeah, I like animals better than people sometimes... Especially dogs. Dogs are the best. Every time you come home, they act like they haven't seen you in a year. And the good thing about dogs... is they got different dogs for different people.", // User description to display in the author segment.
// Links to social profiles/projects you want to display in the author segment/navigation bar.
userLinks: [
{
label: "GitHub",
url: "https://github.com/Vagr9K/gatsby-advanced-starter",
iconClassName: "fa fa-github",
},
{
label: "Twitter",
url: "https://twitter.com/Vagr9K",
iconClassName: "fa fa-twitter",
},
{
label: "Email",
url: "mailto:vagr9k@gmail.com",
iconClassName: "fa fa-envelope",
},
],
copyright: "Copyright © 2020. Advanced User", // Copyright string for the footer of the website and RSS feed.
themeColor: "#c62828", // Used for setting manifest and progress theme colors.
backgroundColor: "#e0e0e0", // Used for setting manifest background color.
};
// Validate
// Make sure pathPrefix is empty if not needed
if (config.pathPrefix === "/") {
config.pathPrefix = "";
} else {
// Make sure pathPrefix only contains the first forward slash
config.pathPrefix = `/${config.pathPrefix.replace(/^\/|\/$/g, "")}`;
}
// Make sure siteUrl doesn't have an ending forward slash
if (config.siteUrl.substr(-1) === "/")
config.siteUrl = config.siteUrl.slice(0, -1);
// Make sure siteRss has a starting forward slash
if (config.siteRss && config.siteRss[0] !== "/")
config.siteRss = `/${config.siteRss}`;
module.exports = config;
|
/**
* 有的任务需要和页面交互,但是这种交互或存在不确定性(消息广播,页面内交互)
* 为了保证任务会被执行,创建此类
* @param callback
* 回调方法
* @returns {TimeLimitTask}
*/
function TimeLimitTask(callback) {
this.finished = false;
this.realCallback = callback;
var self = this;
window.setTimeout(function() {
self.callback();
}, 200);
}
TimeLimitTask.prototype.callback = function(selection) {
if (this.finished)
return;
this.realCallback.apply(window, arguments);
this.finished = true;
}
/**
* 获取选中项
*
* @param callback
* 回调方法 callback(selection)
*/
function getSelection(callback) {
var task = new TimeLimitTask(callback);
window._selectionTask = task;
var code = 'var selection=window.getSelection().toString()||"";'
+'chrome.runtime.sendMessage({action: "getselection",selection:selection});';
chrome.tabs.executeScript({
code : code
});
}
function getInput(callback) {
var task = new TimeLimitTask(callback);
window._inputTask = task;
var code = 'var inputs=document.querySelectorAll("input[type=text],input:not([type])");'
+ 'var maxsize=100,i=0,size,input;'
+ 'for(;i<inputs.length; i++){size=inputs[i].clientWidth*inputs[i].clientHeight; if(size>maxsize){maxsize=size;input=inputs[i];}}'
+ 'chrome.runtime.sendMessage({action: "getinput",value:input&&input.value});';
chrome.tabs.executeScript({
code : code
});
}
function getKeywordFromUrl(url,q){
if(url.substr(0,4)!=='http')return '';
var m=null;
if(q){
m=url.match(new RegExp('\\W(?:'+q+'\\W)([^&\\/?=]*)'));
}
!m&&(m = url.match(/[\/\-?&#!_](?:q|p|keyword|keywords|word|wd|kw|key|query|wiki)[=_\/\-]([^&\/?=]*)/));
!m&&(m = url.match(/[\/\-?&#!_](?:search\/)([^&\/?=]*)/));
if (m) {
try{
return decodeURIComponent(m[1]);
}catch(err){
};
}
return '';
}
function getKeyword(callback,q){
chrome.tabs.getSelected(null, function(tab) {
getInput(function(keyword){
callback(keyword||getKeywordFromUrl(tab.url,q));
});
});
}
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
if (request.action == "getinput") {
window._inputTask && window._inputTask.callback(request.value);
window._inputTask = null;
} else if (request.action == "getselection") {
window._selectionTask
&& window._selectionTask.callback(request.selection);
window._selectionTask = null;
}
});
|
sap.ui.define(["sap/ui/webc/common/thirdparty/base/asset-registries/Icons"],function(t){"use strict";const q="system-2";const s="M32 448V64q0-14 9-23t23-9h384q12 0 22 8t10 21v389q0 14-10 22t-22 8H62q-13 0-21.5-10T32 448zm416 0V64H64v384h384zM176 160q11 0 19 8t8 19q0 20-18 25v31l34 21 58-34-26-17q-4-3-4-7v-58q-18-5-18-25 0-11 8-19t19-8 19 8 8 19q0 9-5.5 16.5T263 149v52l31 20 32-18v-18q-19-7-19-26 0-11 8-19t19-8 19.5 8 8.5 19q0 19-19 26v23q0 4-3 6l-30 17 29 17q4 2 4 7v44q19 7 19 25 0 12-8 20t-19 8q-12 0-20-8t-8-20q0-18 19-25v-39l-32-20-58 34 24 16q3 1 3 7v66q8 2 14 9t6 16q0 11-8.5 19.5T255 416t-19-8.5-8-19.5q0-18 19-25v-62l-28-17-34 18v24q19 5 19 25 0 11-8 19t-19 8-19.5-8-8.5-19q0-8 5-15t13-10v-28q0-6 5-8l30-17-30-19q-5-3-5-7v-35q-8-3-13-9.5t-5-15.5q0-11 8-19t19-8zm79 240q12 0 12-12 0-11-12-11-11 0-11 11 0 12 11 12zm68-76q0 12 12 12 11 0 11-12 0-11-11-11-12 0-12 11zm11-154q12 0 12-11t-12-11q-11 0-11 11t11 11zM177 362q11 0 11-11t-11-11q-12 0-12 11t12 11zm79-228q11 0 11-11t-11-11-11 11 11 11zm-80 64q11 0 11-11t-11-11-11 11 11 11z";const e=false;const n="tnt";const a="@ui5/webcomponents-icons-tnt";t.registerIcon(q,{pathData:s,ltr:e,collection:n,packageName:a});var c={pathData:s};return c});
|
/*!
* Copyright 2016 Telerik AD
*
* 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 (f, define) {
define('kendo.userevents', ['kendo.core'], f);
}(function () {
var __meta__ = {
id: 'userevents',
name: 'User Events',
category: 'framework',
depends: ['core'],
hidden: true
};
(function ($, undefined) {
var kendo = window.kendo, support = kendo.support, Class = kendo.Class, Observable = kendo.Observable, now = $.now, extend = $.extend, OS = support.mobileOS, invalidZeroEvents = OS && OS.android, DEFAULT_MIN_HOLD = 800, DEFAULT_THRESHOLD = support.browser.msie ? 5 : 0, PRESS = 'press', HOLD = 'hold', SELECT = 'select', START = 'start', MOVE = 'move', END = 'end', CANCEL = 'cancel', TAP = 'tap', RELEASE = 'release', GESTURESTART = 'gesturestart', GESTURECHANGE = 'gesturechange', GESTUREEND = 'gestureend', GESTURETAP = 'gesturetap';
var THRESHOLD = {
'api': 0,
'touch': 0,
'mouse': 9,
'pointer': 9
};
var ENABLE_GLOBAL_SURFACE = !support.touch || support.mouseAndTouchPresent;
function touchDelta(touch1, touch2) {
var x1 = touch1.x.location, y1 = touch1.y.location, x2 = touch2.x.location, y2 = touch2.y.location, dx = x1 - x2, dy = y1 - y2;
return {
center: {
x: (x1 + x2) / 2,
y: (y1 + y2) / 2
},
distance: Math.sqrt(dx * dx + dy * dy)
};
}
function getTouches(e) {
var touches = [], originalEvent = e.originalEvent, currentTarget = e.currentTarget, idx = 0, length, changedTouches, touch;
if (e.api) {
touches.push({
id: 2,
event: e,
target: e.target,
currentTarget: e.target,
location: e,
type: 'api'
});
} else if (e.type.match(/touch/)) {
changedTouches = originalEvent ? originalEvent.changedTouches : [];
for (length = changedTouches.length; idx < length; idx++) {
touch = changedTouches[idx];
touches.push({
location: touch,
event: e,
target: touch.target,
currentTarget: currentTarget,
id: touch.identifier,
type: 'touch'
});
}
} else if (support.pointers || support.msPointers) {
touches.push({
location: originalEvent,
event: e,
target: e.target,
currentTarget: currentTarget,
id: originalEvent.pointerId,
type: 'pointer'
});
} else {
touches.push({
id: 1,
event: e,
target: e.target,
currentTarget: currentTarget,
location: e,
type: 'mouse'
});
}
return touches;
}
var TouchAxis = Class.extend({
init: function (axis, location) {
var that = this;
that.axis = axis;
that._updateLocationData(location);
that.startLocation = that.location;
that.velocity = that.delta = 0;
that.timeStamp = now();
},
move: function (location) {
var that = this, offset = location['page' + that.axis], timeStamp = now(), timeDelta = timeStamp - that.timeStamp || 1;
if (!offset && invalidZeroEvents) {
return;
}
that.delta = offset - that.location;
that._updateLocationData(location);
that.initialDelta = offset - that.startLocation;
that.velocity = that.delta / timeDelta;
that.timeStamp = timeStamp;
},
_updateLocationData: function (location) {
var that = this, axis = that.axis;
that.location = location['page' + axis];
that.client = location['client' + axis];
that.screen = location['screen' + axis];
}
});
var Touch = Class.extend({
init: function (userEvents, target, touchInfo) {
extend(this, {
x: new TouchAxis('X', touchInfo.location),
y: new TouchAxis('Y', touchInfo.location),
type: touchInfo.type,
useClickAsTap: userEvents.useClickAsTap,
threshold: userEvents.threshold || THRESHOLD[touchInfo.type],
userEvents: userEvents,
target: target,
currentTarget: touchInfo.currentTarget,
initialTouch: touchInfo.target,
id: touchInfo.id,
pressEvent: touchInfo,
_moved: false,
_finished: false
});
},
press: function () {
this._holdTimeout = setTimeout($.proxy(this, '_hold'), this.userEvents.minHold);
this._trigger(PRESS, this.pressEvent);
},
_hold: function () {
this._trigger(HOLD, this.pressEvent);
},
move: function (touchInfo) {
var that = this;
if (that._finished) {
return;
}
that.x.move(touchInfo.location);
that.y.move(touchInfo.location);
if (!that._moved) {
if (that._withinIgnoreThreshold()) {
return;
}
if (!UserEvents.current || UserEvents.current === that.userEvents) {
that._start(touchInfo);
} else {
return that.dispose();
}
}
if (!that._finished) {
that._trigger(MOVE, touchInfo);
}
},
end: function (touchInfo) {
this.endTime = now();
if (this._finished) {
return;
}
this._finished = true;
this._trigger(RELEASE, touchInfo);
if (this._moved) {
this._trigger(END, touchInfo);
} else {
if (!this.useClickAsTap) {
this._trigger(TAP, touchInfo);
}
}
clearTimeout(this._holdTimeout);
this.dispose();
},
dispose: function () {
var userEvents = this.userEvents, activeTouches = userEvents.touches;
this._finished = true;
this.pressEvent = null;
clearTimeout(this._holdTimeout);
activeTouches.splice($.inArray(this, activeTouches), 1);
},
skip: function () {
this.dispose();
},
cancel: function () {
this.dispose();
},
isMoved: function () {
return this._moved;
},
_start: function (touchInfo) {
clearTimeout(this._holdTimeout);
this.startTime = now();
this._moved = true;
this._trigger(START, touchInfo);
},
_trigger: function (name, touchInfo) {
var that = this, jQueryEvent = touchInfo.event, data = {
touch: that,
x: that.x,
y: that.y,
target: that.target,
event: jQueryEvent
};
if (that.userEvents.notify(name, data)) {
jQueryEvent.preventDefault();
}
},
_withinIgnoreThreshold: function () {
var xDelta = this.x.initialDelta, yDelta = this.y.initialDelta;
return Math.sqrt(xDelta * xDelta + yDelta * yDelta) <= this.threshold;
}
});
function withEachUpEvent(callback) {
var downEvents = kendo.eventMap.up.split(' '), idx = 0, length = downEvents.length;
for (; idx < length; idx++) {
callback(downEvents[idx]);
}
}
var UserEvents = Observable.extend({
init: function (element, options) {
var that = this, filter, ns = kendo.guid();
options = options || {};
filter = that.filter = options.filter;
that.threshold = options.threshold || DEFAULT_THRESHOLD;
that.minHold = options.minHold || DEFAULT_MIN_HOLD;
that.touches = [];
that._maxTouches = options.multiTouch ? 2 : 1;
that.allowSelection = options.allowSelection;
that.captureUpIfMoved = options.captureUpIfMoved;
that.useClickAsTap = !options.fastTap && !support.delayedClick();
that.eventNS = ns;
element = $(element).handler(that);
Observable.fn.init.call(that);
extend(that, {
element: element,
surface: options.global && ENABLE_GLOBAL_SURFACE ? $(element[0].ownerDocument.documentElement) : $(options.surface || element),
stopPropagation: options.stopPropagation,
pressed: false
});
that.surface.handler(that).on(kendo.applyEventMap('move', ns), '_move').on(kendo.applyEventMap('up cancel', ns), '_end');
element.on(kendo.applyEventMap('down', ns), filter, '_start');
if (that.useClickAsTap) {
element.on(kendo.applyEventMap('click', ns), filter, '_click');
}
if (support.pointers || support.msPointers) {
if (support.browser.version < 11) {
element.css('-ms-touch-action', 'pinch-zoom double-tap-zoom');
} else {
element.css('touch-action', options.touchAction || 'none');
}
}
if (options.preventDragEvent) {
element.on(kendo.applyEventMap('dragstart', ns), kendo.preventDefault);
}
element.on(kendo.applyEventMap('mousedown', ns), filter, { root: element }, '_select');
if (that.captureUpIfMoved && support.eventCapture) {
var surfaceElement = that.surface[0], preventIfMovingProxy = $.proxy(that.preventIfMoving, that);
withEachUpEvent(function (eventName) {
surfaceElement.addEventListener(eventName, preventIfMovingProxy, true);
});
}
that.bind([
PRESS,
HOLD,
TAP,
START,
MOVE,
END,
RELEASE,
CANCEL,
GESTURESTART,
GESTURECHANGE,
GESTUREEND,
GESTURETAP,
SELECT
], options);
},
preventIfMoving: function (e) {
if (this._isMoved()) {
e.preventDefault();
}
},
destroy: function () {
var that = this;
if (that._destroyed) {
return;
}
that._destroyed = true;
if (that.captureUpIfMoved && support.eventCapture) {
var surfaceElement = that.surface[0];
withEachUpEvent(function (eventName) {
surfaceElement.removeEventListener(eventName, that.preventIfMoving);
});
}
that.element.kendoDestroy(that.eventNS);
that.surface.kendoDestroy(that.eventNS);
that.element.removeData('handler');
that.surface.removeData('handler');
that._disposeAll();
that.unbind();
delete that.surface;
delete that.element;
delete that.currentTarget;
},
capture: function () {
UserEvents.current = this;
},
cancel: function () {
this._disposeAll();
this.trigger(CANCEL);
},
notify: function (eventName, data) {
var that = this, touches = that.touches;
if (this._isMultiTouch()) {
switch (eventName) {
case MOVE:
eventName = GESTURECHANGE;
break;
case END:
eventName = GESTUREEND;
break;
case TAP:
eventName = GESTURETAP;
break;
}
extend(data, { touches: touches }, touchDelta(touches[0], touches[1]));
}
return this.trigger(eventName, extend(data, { type: eventName }));
},
press: function (x, y, target) {
this._apiCall('_start', x, y, target);
},
move: function (x, y) {
this._apiCall('_move', x, y);
},
end: function (x, y) {
this._apiCall('_end', x, y);
},
_isMultiTouch: function () {
return this.touches.length > 1;
},
_maxTouchesReached: function () {
return this.touches.length >= this._maxTouches;
},
_disposeAll: function () {
var touches = this.touches;
while (touches.length > 0) {
touches.pop().dispose();
}
},
_isMoved: function () {
return $.grep(this.touches, function (touch) {
return touch.isMoved();
}).length;
},
_select: function (e) {
if (!this.allowSelection || this.trigger(SELECT, { event: e })) {
e.preventDefault();
}
},
_start: function (e) {
var that = this, idx = 0, filter = that.filter, target, touches = getTouches(e), length = touches.length, touch, which = e.which;
if (which && which > 1 || that._maxTouchesReached()) {
return;
}
UserEvents.current = null;
that.currentTarget = e.currentTarget;
if (that.stopPropagation) {
e.stopPropagation();
}
for (; idx < length; idx++) {
if (that._maxTouchesReached()) {
break;
}
touch = touches[idx];
if (filter) {
target = $(touch.currentTarget);
} else {
target = that.element;
}
if (!target.length) {
continue;
}
touch = new Touch(that, target, touch);
that.touches.push(touch);
touch.press();
if (that._isMultiTouch()) {
that.notify('gesturestart', {});
}
}
},
_move: function (e) {
this._eachTouch('move', e);
},
_end: function (e) {
this._eachTouch('end', e);
},
_click: function (e) {
var data = {
touch: {
initialTouch: e.target,
target: $(e.currentTarget),
endTime: now(),
x: {
location: e.pageX,
client: e.clientX
},
y: {
location: e.pageY,
client: e.clientY
}
},
x: e.pageX,
y: e.pageY,
target: $(e.currentTarget),
event: e,
type: 'tap'
};
if (this.trigger('tap', data)) {
e.preventDefault();
}
},
_eachTouch: function (methodName, e) {
var that = this, dict = {}, touches = getTouches(e), activeTouches = that.touches, idx, touch, touchInfo, matchingTouch;
for (idx = 0; idx < activeTouches.length; idx++) {
touch = activeTouches[idx];
dict[touch.id] = touch;
}
for (idx = 0; idx < touches.length; idx++) {
touchInfo = touches[idx];
matchingTouch = dict[touchInfo.id];
if (matchingTouch) {
matchingTouch[methodName](touchInfo);
}
}
},
_apiCall: function (type, x, y, target) {
this[type]({
api: true,
pageX: x,
pageY: y,
clientX: x,
clientY: y,
target: $(target || this.element)[0],
stopPropagation: $.noop,
preventDefault: $.noop
});
}
});
UserEvents.defaultThreshold = function (value) {
DEFAULT_THRESHOLD = value;
};
UserEvents.minHold = function (value) {
DEFAULT_MIN_HOLD = value;
};
kendo.getTouches = getTouches;
kendo.touchDelta = touchDelta;
kendo.UserEvents = UserEvents;
}(window.kendo.jQuery));
return window.kendo;
}, typeof define == 'function' && define.amd ? define : function (a1, a2, a3) {
(a3 || a2)();
}));
|
import React from "react"
import "./css/TypesIcons.css"
const TypesIcons = props => {
const {height,width,backColor,color,TextColor} = props
return (
<div className="TypesIconsGroup">
<div
className="SmallIcon"
style={{
width: width,
height: height,
backgroundColor: backColor,
color: color,
}}
>
W
</div>
<div className="Lines" />
<div className="Typeof" style={{ color:TextColor}}>
Wordpress
</div>
</div>
)
}
export default TypesIcons
|
''' Provide base classes for the Bokeh property system.
.. note::
These classes form part of the very low-level machinery that implements
the Bokeh model and property system. It is unlikely that any of these
classes or their methods will be applicable to any standard usage or to
anyone who is not directly developing on Bokeh's own infrastructure.
'''
from __future__ import absolute_import
import logging
logger = logging.getLogger(__name__)
from copy import copy
import types
from six import string_types
import numpy as np
from ...util.dependencies import import_optional
from ...util.string import nice_join
from ..has_props import HasProps
from .descriptor_factory import PropertyDescriptorFactory
from .descriptors import BasicPropertyDescriptor
pd = import_optional('pandas')
class DeserializationError(Exception):
pass
class Property(PropertyDescriptorFactory):
''' Base class for Bokeh property instances, which can be added to Bokeh
Models.
Args:
default (obj or None, optional) :
A default value for attributes created from this property to
have (default: None)
help (str or None, optional) :
A documentation string for this property. It will be automatically
used by the :ref:`bokeh.sphinxext.bokeh_prop` extension when
generating Spinx documentation. (default: None)
serialized (bool, optional) :
Whether attributes created from this property should be included
in serialization (default: True)
readonly (bool, optional) :
Whether attributes created from this property are read-only.
(default: False)
'''
def __init__(self, default=None, help=None, serialized=True, readonly=False):
# This is how the descriptor is created in the class declaration.
self._serialized = False if readonly else serialized
self._readonly = readonly
self._default = default
self.__doc__ = help
self.alternatives = []
self.assertions = []
def __str__(self):
return self.__class__.__name__
@classmethod
def _sphinx_prop_link(cls):
''' Generate a sphinx :class: link to this property.
'''
return ":class:`~bokeh.core.properties.%s` " % cls.__name__
@staticmethod
def _sphinx_model_link(name):
''' Generate a sphinx :class: link to given named model.
'''
return ":class:`~%s` " % name
def _sphinx_type(self):
''' Generate a Sphinx-style reference to this type for documentation
automation purposes.
'''
return self._sphinx_prop_link()
def make_descriptors(self, base_name):
''' Return a list of ``BasicPropertyDescriptor`` instances to install
on a class, in order to delegate attribute access to this property.
Args:
name (str) : the name of the property these descriptors are for
Returns:
list[BasicPropertyDescriptor]
The descriptors returned are collected by the ``MetaHasProps``
metaclass and added to ``HasProps`` subclasses during class creation.
'''
return [ BasicPropertyDescriptor(base_name, self) ]
def _may_have_unstable_default(self):
''' False if we have a default that is immutable, and will be the
same every time (some defaults are generated on demand by a function
to be called).
'''
return isinstance(self._default, types.FunctionType)
@classmethod
def _copy_default(cls, default):
''' Return a copy of the default, or a new value if the default
is specified by a function.
'''
if not isinstance(default, types.FunctionType):
return copy(default)
else:
return default()
def _raw_default(self):
''' Return the untransformed default value.
The raw_default() needs to be validated and transformed by
prepare_value() before use, and may also be replaced later by
subclass overrides or by themes.
'''
return self._copy_default(self._default)
def themed_default(self, cls, name, theme_overrides):
''' The default, transformed by prepare_value() and the theme overrides.
'''
overrides = theme_overrides
if overrides is None or name not in overrides:
overrides = cls._overridden_defaults()
if name in overrides:
default = self._copy_default(overrides[name])
else:
default = self._raw_default()
return self.prepare_value(cls, name, default)
@property
def serialized(self):
''' Whether the property should be serialized when serializing an object.
This would be False for a "virtual" or "convenience" property that duplicates
information already available in other properties, for example.
'''
return self._serialized
@property
def readonly(self):
''' Whether this property is read-only.
Read-only properties may only be modified by the client (i.e., by BokehJS
in the browser).
'''
return self._readonly
def matches(self, new, old):
''' Whether two parameters match values.
If either ``new`` or ``old`` is a NumPy array or Pandas Series or Index,
then the result of ``np.array_equal`` will determine if the values match.
Otherwise, the result of standard Python equality will be returned.
Returns:
True, if new and old match, False otherwise
'''
if isinstance(new, np.ndarray) or isinstance(old, np.ndarray):
return np.array_equal(new, old)
if pd:
if isinstance(new, pd.Series) or isinstance(old, pd.Series):
return np.array_equal(new, old)
if isinstance(new, pd.Index) or isinstance(old, pd.Index):
return np.array_equal(new, old)
try:
# this handles the special but common case where there is a dict with array
# or series as values (e.g. the .data property of a ColumnDataSource)
if isinstance(new, dict) and isinstance(old, dict):
if set(new.keys()) != set(old.keys()):
return False
return all(self.matches(new[k], old[k]) for k in new)
return new == old
# if the comparison fails for some reason, just punt and return no-match
except ValueError:
return False
def from_json(self, json, models=None):
''' Convert from JSON-compatible values into a value for this property.
JSON-compatible values are: list, dict, number, string, bool, None
'''
return json
def serialize_value(self, value):
''' Change the value into a JSON serializable format.
'''
return value
def transform(self, value):
''' Change the value into the canonical format for this property.
Args:
value (obj) : the value to apply transformation to.
Returns:
obj: transformed value
'''
return value
def validate(self, value, detail=True):
''' Determine whether we can set this property from this value.
Validation happens before transform()
Args:
value (obj) : the value to validate against this property type
detail (bool, options) : whether to construct detailed exceptions
Generating detailed type validation error messages can be
expensive. When doing type checks internally that will not
escape exceptions to users, these messages can be skipped
by setting this value to False (default: True)
Returns:
None
Raises:
ValueError if the value is not valid for this property type
'''
pass
def is_valid(self, value):
''' Whether the value passes validation
Args:
value (obj) : the value to validate against this property type
Returns:
True if valid, False otherwise
'''
try:
self.validate(value, False)
except ValueError as e:
return False
else:
return True
@classmethod
def wrap(cls, value):
''' Some property types need to wrap their values in special containers, etc.
'''
return value
def prepare_value(self, obj_or_cls, name, value):
try:
self.validate(value)
except ValueError as e:
for tp, converter in self.alternatives:
if tp.is_valid(value):
value = converter(value)
break
else:
raise e
else:
value = self.transform(value)
if isinstance(obj_or_cls, HasProps):
obj = obj_or_cls
for fn, msg_or_fn in self.assertions:
if isinstance(fn, bool):
result = fn
else:
result = fn(obj, value)
assert isinstance(result, bool)
if not result:
if isinstance(msg_or_fn, string_types):
raise ValueError(msg_or_fn)
else:
msg_or_fn(obj, name, value)
return self.wrap(value)
@property
def has_ref(self):
return False
def accepts(self, tp, converter):
''' Declare that other types may be converted to this property type.
Args:
tp (Property) :
A type that may be converted automatically to this property
type.
converter (callable) :
A function accepting ``value`` to perform conversion of the
value to this property type.
Returns:
self
'''
tp = ParameterizedProperty._validate_type_param(tp)
self.alternatives.append((tp, converter))
return self
def asserts(self, fn, msg_or_fn):
''' Assert that prepared values satisfy given conditions.
Assertions are intended in enforce conditions beyond simple value
type validation. For instance, this method can be use to assert that
the columns of a ``ColumnDataSource`` all collectively have the same
length at all times.
Args:
fn (callable) :
A function accepting ``(obj, value)`` that returns True if the value
passes the assertion, or False othwise
msg_or_fn (str or callable) :
A message to print in case the assertion fails, or a function
accepting ``(obj, name, value)`` to call in in case the assertion
fails.
Returns:
self
'''
self.assertions.append((fn, msg_or_fn))
return self
class ParameterizedProperty(Property):
''' A base class for Properties that have type parameters, e.g.
``List(String)``.
'''
@staticmethod
def _validate_type_param(type_param):
if isinstance(type_param, type):
if issubclass(type_param, Property):
return type_param()
else:
type_param = type_param.__name__
elif isinstance(type_param, Property):
return type_param
raise ValueError("expected a Propertyas type parameter, got %s" % type_param)
@property
def type_params(self):
raise NotImplementedError("abstract method")
@property
def has_ref(self):
return any(type_param.has_ref for type_param in self.type_params)
class PrimitiveProperty(Property):
''' A base class for simple property types.
Subclasses should define a class attribute ``_underlying_type`` that is
a tuple of acceptable type values for the property.
Example:
A trivial version of a ``Float`` property might look like:
.. code-block:: python
class Float(PrimitiveProperty):
_underlying_type = (numbers.Real,)
'''
_underlying_type = None
def validate(self, value, detail=True):
super(PrimitiveProperty, self).validate(value, detail)
if not (value is None or isinstance(value, self._underlying_type)):
msg = "" if not detail else "expected a value of type %s, got %s of type %s" % (
nice_join([ cls.__name__ for cls in self._underlying_type ]), value, type(value).__name__
)
raise ValueError(msg)
def from_json(self, json, models=None):
if json is None or isinstance(json, self._underlying_type):
return json
else:
expected = nice_join([ cls.__name__ for cls in self._underlying_type ])
raise DeserializationError("%s expected %s, got %s" % (self, expected, json))
def _sphinx_type(self):
return self._sphinx_prop_link()
class ContainerProperty(ParameterizedProperty):
''' A base class for Container-like type properties.
'''
def _may_have_unstable_default(self):
# all containers are mutable, so the default can be modified
return True
|
/* eslint-disable import/no-anonymous-default-export */
import React from "react";
import { Row, Col } from "antd";
import HorizontalBar from "./HorizontalBar";
import StalkedChart from "./StalkedChart";
import VerticalBar from "./VerticalBar";
export default () => (
<div>
<Row>
<Col span={22} offset={1}>
<HorizontalBar />
</Col>
<Col span={22} offset={1}>
<StalkedChart />
</Col>
<Col span={22} offset={1}>
<VerticalBar />
</Col>
</Row>
</div>
);
|
import RPIO as GPIO
import RPIO.PWM as PWM
from HD44780 import HD44780
from Utils import delay_microseconds
class LCD_Protocol():
def __init__(
self, rs, enable, pins,
backlight=None, rw=None,
cols=16, lines=1, dotsize=0):
# Interal Variables
self.__rs = rs
self.__rw = rw
self.__enable = enable
self.__data_pins = pins
self.__backlight = backlight
# Public Variables
self.numlines = lines
self.columns = cols
self.dotsize = dotsize
# Protocol Functions
def initialize(self):
# Setup PWM if backlight is defined
if self.__backlight:
PWM.setup()
PWM.init_channel(0)
self.enableBacklight()
# Setup rs, enable and rw pins
GPIO.setup(self.__rs, GPIO.OUT)
GPIO.setup(self.__enable, GPIO.OUT)
if self.__rw:
GPIO.setup(self.__rw, GPIO.OUT)
def begin(self):
# Pull RS, Enable and R/W low to begin commands
GPIO.output(self.__rs, GPIO.LOW)
GPIO.output(self.__enable, GPIO.LOW)
if self.__rw:
GPIO.output(self.__rw, GPIO.LOW)
def send(self, value, mode):
GPIO.output(self.__rs, mode)
# If there is an RW pin incicated, set it to low to write
if self.__rw:
GPIO.output(self.__rw, GPIO.LOW)
# Write both nibbles
self.write4bits(value & 0xF0)
self.write4bits((value << 4) & 0xF0)
def write4bits(self, value):
for i in range(0, 4):
GPIO.setup(self.__data_pins[i], GPIO.OUT)
GPIO.output(self.__data_pins[i], (value >> i) & 0x10)
self.__pulse_enable()
def enableBacklight(self, intensity=100):
self.__setBrightness(intensity)
def disableBacklight(self):
self.__setBrightness(0)
def cleanup(self):
if self.__backlight:
PWM.clear_channel_gpio(0, self.__backlight)
PWM.cleanup()
GPIO.cleanup()
# Internal Functions
def __setBrightness(self, intensity):
# If no backlight pin is assigned, just return
if not self.__backlight:
return
# Clamp our intensity to be between 0 and 100 percent
if intensity > 100:
intensity = 100
if intensity < 0:
intensity = 0
# Maximum width is 1999 based on the 20000us subcycle
width = int(1999.0 * (intensity / 100.0))
# Set PWM
PWM.add_channel_pulse(0, self.__backlight, 0, width)
def __pulse_enable(self):
GPIO.output(self.__enable, GPIO.LOW)
delay_microseconds(1)
GPIO.output(self.__enable, GPIO.HIGH)
delay_microseconds(1)
GPIO.output(self.__enable, GPIO.LOW)
delay_microseconds(100)
def LCD(
rs, enable, pins,
backlight=None, rw=None,
cols=16, lines=1, dotsize=0
):
return HD44780(
LCD_Protocol(
rs, enable, pins, backlight, rw, cols, lines, dotsize
)
)
|
(window.webpackJsonp=window.webpackJsonp||[]).push([[7],{143:function(e,t,a){"use strict";a.r(t);var n=a(7),i=a.n(n),r=a(0),o=a.n(r),l=a(148),d=a(149),c=a(160),p=a(171),s=a(172),m=a(145),u=a(4),h=a.n(u),g=a(154),f=a(146),x=m.a.div.withConfig({displayName:"text-section-2__TextWrapper",componentId:"sc-1a6a5nl-0"})(["padding:0 24px 22px 24px;p{span.highlight{color:"," !important;}color:"," !important;}"],f.a.font.dark,f.a.font.light),A=m.a.div.withConfig({displayName:"text-section-2__Head",componentId:"sc-1a6a5nl-1"})(["padding:24px 24px 0px 24px;h2{margin:0;color:"," !important;}"],f.a.theme.main),y=function(e){function t(){return e.apply(this,arguments)||this}return i()(t,e),t.prototype.render=function(){var e=this.props,t=e.header,a=e.children,n=e.color;return o.a.createElement(d.a,{color:n},o.a.createElement(A,{color:n},o.a.createElement("h2",null,t)),o.a.createElement(x,null,o.a.createElement(g.a,null),a))},t}(r.Component);y.propTypes={header:h.a.string.isRequired,color:h.a.string},y.defaultProps={header:"",color:"#fff"};var w=y,E=a(173),b=a(152),v=a.n(b),I=m.a.div.withConfig({displayName:"grid-section__GridItem",componentId:"nbyiry-0"})(["text-align:center;margin-bottom:18px;.grid-title{font-weight:700;}p{font-size:15px;text-align:justify;margin:10px;}width:32.5%;@media (max-width:768px){width:49%;}@media (max-width:545px){width:100%;}"]),k=m.a.div.withConfig({displayName:"grid-section__Body",componentId:"nbyiry-1"})(["margin:12px 0;"]),T=Object(m.a)(v.a).withConfig({displayName:"grid-section__StyledImg",componentId:"nbyiry-2"})(["overflow:hidden;border-radius:3px;position:absolute;top:0;left:0;width:100%;z-index:-1;height:350px;& > img{object-fit:cover !important;object-position:0% 0% !important;font-family:'object-fit: cover !important; object-position: 0% 0% !important;'}"]),_=function(e){function t(){return e.apply(this,arguments)||this}return i()(t,e),t.prototype.render=function(){var e=this.props,t=e.fluidImage,a=e.underTitle,n=e.underText;return o.a.createElement(I,null,o.a.createElement(T,{fluid:t}),o.a.createElement(k,null,o.a.createElement("span",{className:"grid-title"},a),o.a.createElement("p",null,n)))},t}(r.Component);_.propTypes={fluidImage:h.a.object.isRequired,underTitle:h.a.string,underText:h.a.string},_.defaultProps={underTitle:"",underText:""};var N=_,C=a(174),j=a(175),B=m.a.div.withConfig({displayName:"buttons__ActionButton",componentId:"gxtkzt-0"})(["background-color:",";border-radius:3px;transition:all 0.2s;padding:8px 15px;margin:0 auto;border-radius:3px;display:flex;align-items:center;width:150px;justify-content:center;a{color:white !important;font-size:14px !important;font-weight:500;transition:color 0.2s;&:hover{text-decoration:none;}}&:hover{box-shadow:0 3px 10px rgba(0,0,0,0.1);}"],f.a.theme.main),S=Object(m.a)(B).withConfig({displayName:"buttons__ActionButtonOutline",componentId:"gxtkzt-1"})(["border:2px solid ",";background-color:white;a{color:"," !important;transition:color 0.2s;}"],f.a.theme.accent,f.a.theme.darkaccent),Q=(a(176),a(159)),q=a(151),z=a(183),R=m.a.div.withConfig({displayName:"bio__BiosWrapper",componentId:"t0dko6-0"})(["margin:18px 0;border-radius:3px;overflow:hidden;display:flex;justify-content:space-evenly;flex-wrap:wrap;@media (max-width:768px){margin-left:12px;margin-right:12px;margin-top:12px;flex-wrap:wrap;}"]),P=m.a.div.withConfig({displayName:"bio__BioWrapper",componentId:"t0dko6-1"})(["margin:24px 12px 0 12px;background-color:white;width:32.5%;max-width:260px;position:relative;img{transition:all 0.5s;}.name{margin:18px 0;text-align:center;}.content{position:absolute;background-color:rgba(0,0,0,0.3);padding:1.2em;overflow:hidden;border-radius:3px;height:350px;top:0;left:0;opacity:0;transition:all 0.5s;display:flex;flex-direction:column;text-align:center;justify-content:center;*{color:white;}h3{margin:0px 0 10px 0;}small{font-style:italic;margin-bottom:5px;}p{font-size:15px;line-height:1.55em;text-align:center;}}&:hover{.content{opacity:1;}img{filter:blur(8px);-webkit-filter:blur(8px);}}@media (max-width:768px){width:49%;}@media (max-width:545px){width:100%;}"]),L=Object(m.a)(v.a).withConfig({displayName:"bio__StyledImg",componentId:"t0dko6-2"})(["overflow:hidden;border-radius:3px;position:absolute;top:0;left:0;width:100%;height:350px;& > img{object-fit:cover !important;object-position:0% 0% !important;font-family:'object-fit: cover !important; object-position: 0% 0% !important;'}"]),O=function(e){function t(){return e.apply(this,arguments)||this}return i()(t,e),t.prototype.render=function(){var e=this.props,t=e.fluidPortraits,a=e.teamInfo;return o.a.createElement(R,null,t&&a&&t.map(function(e,t){console.log(a[t]);var n=a[t],i=n.fname,r=(n.mname,n.lname,n.position),l=n.biography,d=n.linkedin;return o.a.createElement(P,{key:t},o.a.createElement("div",null,o.a.createElement(L,{fluid:e}),o.a.createElement("a",{href:d,target:"_blank"},o.a.createElement("div",{className:"content"},o.a.createElement("small",null,r," ",d&&o.a.createElement(q.a,{icon:z.a,size:"lg"})),o.a.createElement("p",null,l)))),o.a.createElement("div",{className:"name"},o.a.createElement("h3",null,i)))}))},t}(r.Component);O.propTypes={fluidPortraits:h.a.array.isRequired,teamInfo:h.a.array.isRequired};var G=O,D=a(153);a.d(t,"pageQuery",function(){return M});var Y=function(e){function t(){return e.apply(this,arguments)||this}return i()(t,e),t.prototype.render=function(){var e=this.props.data,t=e.siteData,a=e.homepage,n=e.elizabeth,i=e.michael,r=e.franc,m=(e.apartment,e.kitchen,e.rent1),u=e.rent2,h=e.rent3,x=e.rent4,A=e.rent5,y=[n.childImageSharp.fluid,i.childImageSharp.fluid,r.childImageSharp.fluid],b=this.props.data.bios.edges[0].node.team;return o.a.createElement(c.a,null,o.a.createElement(Q.a,{title:"Home",keywords:["real estate","housing","bv"]}),o.a.createElement(d.b,null,o.a.createElement("h1",null,t.siteMetadata.title)),o.a.createElement(g.a,null),o.a.createElement(p.a,{fluidImage:a.childImageSharp.fluid}),o.a.createElement(w,{color:f.a.theme.secondary,header:"Mission Statement"},o.a.createElement("p",null,o.a.createElement("span",{className:"highlight"},t.siteMetadata.title," is committed to helping property owners maximize returns while minimizing their risk.")),o.a.createElement("p",null,"We are looking to partner with the best property owners to deliver a great experience for visitors to New Jersey and New York."),o.a.createElement("p",null,"We are interested in leasing your property to expand our Short Term Rental business."),o.a.createElement("p",null,"We are backed by the highest credit rating and a $1,000,000 insurance policy."),o.a.createElement("br",null),o.a.createElement("blockquote",null,"Our guiding principle: ”The glue that holds all relationships together is trust, and trust is based on integrity.”")),o.a.createElement(g.b,null),o.a.createElement("h2",null,"Why rent to us?"),o.a.createElement(E.a,null,o.a.createElement(N,{fluidImage:m.childImageSharp.fluid,underTitle:"Guaranteed Rental Income",underText:"We are a Landlord’s ideal tenant. Landlords secure the guaranteed income of a traditional lease with our corporate automatic payment system. No more late rent or worries on your mortgage payment."}),o.a.createElement(N,{fluidImage:h.childImageSharp.fluid,underTitle:"Professional Staff",underText:" Our property managers and cleaning staff report any maintenance requirements immediately using our management app, making sure that any issues are addressed professionally and timely. Less wear and tear for your property."}),o.a.createElement(N,{fluidImage:u.childImageSharp.fluid,underTitle:"Highly Experienced Team",underText:"Over 20 years of experience in hospitality, finance, and technology."}),o.a.createElement(N,{fluidImage:x.childImageSharp.fluid,underTitle:"Legally Compliant",underText:"We comply with all local laws regarding property rental and zoning, and we pay all applicable taxes."}),o.a.createElement(N,{fluidImage:A.childImageSharp.fluid,underTitle:"Verified Guests",underText:"We screen each guest using machine learning technology and continually improve our fraud prevention program by partnering with leaders in the field."})),o.a.createElement(g.b,null),o.a.createElement(s.a,{color:f.a.theme.accent,header:"How it works?"},o.a.createElement(C.a,null,o.a.createElement(j.a,{icon:o.a.createElement(q.a,{icon:D.g,size:"2x"}),underTitle:"Submit Form",underText:"Start by submitting the landlord inquiry form",color:f.a.theme.accent}),o.a.createElement(j.a,{icon:o.a.createElement(q.a,{icon:D.i,size:"2x"}),underTitle:"Free Quote",underText:"Our team will get in touch with you within 24 Hours",color:f.a.theme.accent}),o.a.createElement(j.a,{icon:o.a.createElement(q.a,{icon:D.d,size:"2x"}),underTitle:"Property Tour",underText:"Schedule property tour and discuss lease terms",color:f.a.theme.accent}),o.a.createElement(j.a,{icon:o.a.createElement(q.a,{icon:D.j,size:"2x"}),underTitle:"Sign Lease",underText:"Sign lease agreement and we will take care of the rest!",color:f.a.theme.accent}),o.a.createElement(j.a,{icon:o.a.createElement(q.a,{icon:D.f,size:"2x"}),underTitle:"Collect Rent",underText:"Sit back and receive ongoing rent check!",color:f.a.theme.accent})),o.a.createElement(S,null,o.a.createElement(l.Link,{to:"/contact"},"Contact Us"))),o.a.createElement(g.b,null),o.a.createElement(g.b,null),o.a.createElement("h2",null,"Who are we?"),o.a.createElement(G,{fluidPortraits:y,teamInfo:b}))},t}(r.Component),M=(t.default=Y,"2551392073")},146:function(e,t,a){"use strict";t.a={theme:{main:"#6BB7B9",secondary:"#FFF6E6",lightaccent:"#9CD6D2",accent:"#6BB7B9",darkaccent:"#007D8C"},font:{dark:"#484848",light:"#767676"},border:{dark:"#484848",light:"#767676",lighter:"rgba(0,0,0,0.2)"}}},148:function(e,t,a){"use strict";a.r(t),a.d(t,"graphql",function(){return h}),a.d(t,"StaticQueryContext",function(){return m}),a.d(t,"StaticQuery",function(){return u});var n=a(0),i=a.n(n),r=a(4),o=a.n(r),l=a(147),d=a.n(l);a.d(t,"Link",function(){return d.a}),a.d(t,"withPrefix",function(){return l.withPrefix}),a.d(t,"navigate",function(){return l.navigate}),a.d(t,"push",function(){return l.push}),a.d(t,"replace",function(){return l.replace}),a.d(t,"navigateTo",function(){return l.navigateTo});var c=a(150),p=a.n(c);a.d(t,"PageRenderer",function(){return p.a});var s=a(32);a.d(t,"parsePath",function(){return s.a});var m=i.a.createContext({}),u=function(e){return i.a.createElement(m.Consumer,null,function(t){return e.data||t[e.query]&&t[e.query].data?(e.render||e.children)(e.data?e.data.data:t[e.query].data):i.a.createElement("div",null,"Loading (StaticQuery)")})};function h(){throw new Error("It appears like Gatsby is misconfigured. Gatsby related `graphql` calls are supposed to only be evaluated at compile time, and then compiled away,. Unfortunately, something went wrong and the query was left in the compiled code.\n\n.Unless your site has a complex or custom babel/Gatsby configuration this is likely a bug in Gatsby.")}u.propTypes={data:o.a.object,query:o.a.string.isRequired,render:o.a.func,children:o.a.func}},149:function(e,t,a){"use strict";a.d(t,"b",function(){return l}),a.d(t,"a",function(){return c});var n=a(0),i=a.n(n),r=a(145),o=(a(146),r.a.div.withConfig({displayName:"section__StyledSection",componentId:"sc-18ueukn-0"})(["margin:32px 0 0 0;border-radius:3px;overflow:hidden;"," @media (max-width:768px){margin-left:12px;margin-right:12px;}"],function(e){var t=e.color;return"#fff"!==t&&"\n background-color: rgba(0,0,0,0.08);\n // border-bottom: 2px solid "+t+";\n // border-left: 2px solid "+t+";\n // border-right: 2px solid "+t+";\n "})),l=function(e){var t=e.children,a=e.color||"#fff";return i.a.createElement(o,{color:a},t)},d=r.a.div.withConfig({displayName:"section__StyledFullSection",componentId:"sc-18ueukn-1"})(["margin:32px -24px 0 -24px;padding:0 24px;border-radius:3px;overflow:hidden;"," @media (max-width:768px){margin-left:-12px;margin-right:-12px;}@media (min-width:1540px){margin-left:0px;margin-right:0px;}"],function(e){var t=e.color;return"#fff"!==t&&"\n // background-color: rgba(0,0,0,0.08);\n background-color: "+t+";\n // color: white !important;\n h2{color: white !important;}\n span{color: white !important;}\n p{color: white !important;}\n // *{color: white !important;}\n // border-bottom: 2px solid "+t+";\n // border-left: 2px solid "+t+";\n // border-right: 2px solid "+t+";\n "}),c=function(e){var t=e.children,a=e.color||"#fff";return i.a.createElement(d,{color:a},t)}},150:function(e,t,a){var n;e.exports=(n=a(162))&&n.default||n},154:function(e,t,a){"use strict";a.d(t,"b",function(){return i}),a.d(t,"a",function(){return r});a(0);var n=a(145),i=n.a.div.withConfig({displayName:"spaced-hr__SpacedHr",componentId:"sc-18jk6jo-0"})(["margin:1.5em 0;"]),r=n.a.div.withConfig({displayName:"spaced-hr__HalfSpacedHr",componentId:"sc-18jk6jo-1"})(["margin:1em 0;"])},159:function(e,t,a){"use strict";var n=a(165),i=a(0),r=a.n(i),o=a(4),l=a.n(o),d=a(168),c=a.n(d),p=a(148);function s(e){var t=e.description,a=e.lang,i=e.meta,o=e.keywords,l=e.title;return r.a.createElement(p.StaticQuery,{query:m,render:function(e){var n=t||e.site.siteMetadata.description;return r.a.createElement(c.a,{htmlAttributes:{lang:a},title:l,titleTemplate:"%s | "+e.site.siteMetadata.title,meta:[{name:"description",content:n},{property:"og:title",content:l},{property:"og:description",content:n},{property:"og:type",content:"website"},{name:"twitter:card",content:"summary"},{name:"twitter:creator",content:e.site.siteMetadata.author},{name:"twitter:title",content:l},{name:"twitter:description",content:n}].concat(o.length>0?{name:"keywords",content:o.join(", ")}:[]).concat(i)})},data:n})}s.defaultProps={lang:"en",meta:[],keywords:[]},s.propTypes={description:l.a.string,lang:l.a.string,meta:l.a.array,keywords:l.a.arrayOf(l.a.string),title:l.a.string.isRequired},t.a=s;var m="1025518380"},160:function(e,t,a){"use strict";var n=a(161),i=a(0),r=a.n(i),o=a(145),l=a(4),d=a.n(l),c=a(148),p=a(7),s=a.n(p),m=a(51),u=a.n(m),h=a(163),g=a(152),f=a.n(g),x=a(151),A=a(153),y=a(146),w=a(220),E=o.a.div.withConfig({displayName:"header__StyledNavbar",componentId:"zi46uq-0"})(["margin:0px auto;width:100%;padding:12px 24px 12px 24px;position:fixed;display:flex;top:0;background-color:white;align-items:center;z-index:2;a{color:"," !important;}.navbar-brand{font-size:18px !important;font-weight:700;}.navbar-toggler{border-color:white !important;path{fill:",";}}@media (max-width:885px){.navbar-collapse{display:none;}}"],y.a.font.dark,y.a.font.dark),b=(Object(o.a)(c.Link).withConfig({displayName:"header__NavbarBrandLink",componentId:"zi46uq-1"})([""]),Object(o.a)(w.a).withConfig({displayName:"header__StyledNavBarBrand",componentId:"zi46uq-2"})(["width:29px;margin-right:9px !important;overflow:hidden;"])),v=Object(o.a)(w.a).withConfig({displayName:"header__StyledNavbarBrandName",componentId:"zi46uq-3"})(["a:hover{text-decoration:none;}"]),I=o.a.div.withConfig({displayName:"header__FlexGrow",componentId:"zi46uq-4"})(["flex:1;"]),k=o.a.div.withConfig({displayName:"header__NavItem",componentId:"zi46uq-5"})(["margin:auto 10px;a{color:"," !important;font-size:14px !important;font-weight:500;}@media (max-width:885px){display:none;}"],y.a.font.dark),T=o.a.div.withConfig({displayName:"header__Dropdown",componentId:"zi46uq-6"})(["display:none;position:absolute;top:66px;left:0;width:100%;background-color:",";padding:10px 20px 15px 20px;z-index:2;@media (max-width:885px){display:",";flex-direction:column;}"],y.a.theme.secondary,function(e){return e.isOpen?"flex":"none"}),_=o.a.div.withConfig({displayName:"header__DDNavItem",componentId:"zi46uq-7"})(["margin:25px 20px 15px 20px;"]),N=o.a.div.withConfig({displayName:"header__StyledNavbarToggler",componentId:"zi46uq-8"})(["display:none;margin:0 30px;height:42px;@media (max-width:885px){display:flex !important;align-items:center;}"]),C=o.a.div.withConfig({displayName:"header__StyledNav",componentId:"zi46uq-9"})(["display:flex;"]),j=o.a.div.withConfig({displayName:"header__ActionButton",componentId:"zi46uq-10"})(["background-color:",";border-radius:3px;transition:all 0.2s;padding:8px 15px;margin:0 5px;border-radius:3px;display:flex;align-items:center;a{color:white !important;font-size:14px !important;font-weight:500;transition:color 0.2s;&:hover{text-decoration:none;}}&:hover{box-shadow:0 3px 10px rgba(0,0,0,0.1);}@media (max-width:885px){display:visible;}@media (max-width:630px){display:none;}"],y.a.theme.main),B=(Object(o.a)(j).withConfig({displayName:"header__ActionButtonOutline",componentId:"zi46uq-11"})(["border:2px solid ",";background-color:white;a{color:"," !important;transition:color 0.2s;}"],y.a.theme.accent,y.a.font.dark),function(e){function t(t){var a;return(a=e.call(this,t)||this).toggle=a.toggle.bind(u()(u()(a))),a.state={isOpen:!1},a}s()(t,e);var a=t.prototype;return a.toggle=function(){this.setState({isOpen:!this.state.isOpen})},a.render=function(){var e=this,t=this.props.siteTitle;return console.log(this.state.isOpen),r.a.createElement(c.StaticQuery,{query:"3547022730",render:function(a){return console.log(a),r.a.createElement(i.Fragment,null,r.a.createElement(E,{color:"#fff",light:!0,expand:"md"},r.a.createElement(b,null,r.a.createElement(c.Link,{to:"/"},r.a.createElement(f.a,{fluid:a.logo.childImageSharp.fluid}))),r.a.createElement(v,null,r.a.createElement(c.Link,{to:"/"},t)),r.a.createElement(I,null),r.a.createElement(N,{onClick:e.toggle},r.a.createElement(x.a,{icon:A.a})),r.a.createElement(T,{isOpen:e.state.isOpen},r.a.createElement(_,null,r.a.createElement(c.Link,{to:"/"},"Home")),r.a.createElement(_,null,r.a.createElement(c.Link,{to:"/listings/"},"Our Listings")),r.a.createElement(_,null,r.a.createElement(c.Link,{to:"/faq/"},"FAQ")),r.a.createElement(_,null,r.a.createElement(c.Link,{to:"/contact/"},"Contact Us"))),r.a.createElement(C,{navbar:!0},r.a.createElement(k,null,r.a.createElement(c.Link,{to:"/"},"Home")),r.a.createElement(k,null,r.a.createElement(c.Link,{to:"/listings/"},"Rental Partners")),r.a.createElement(k,null,r.a.createElement(c.Link,{to:"/faq"},"FAQ")),r.a.createElement(j,null,r.a.createElement(c.Link,{to:"/contact"},"Contact Us")))))},data:h})},t}(i.Component));B.propTypes={siteTitle:d.a.string},B.defaultProps={siteTitle:""};var S=B,Q=o.a.div.withConfig({displayName:"footer__StyledFooter",componentId:"sc-1o5r1n6-0"})(["margin:180px auto 50px auto;padding:55px 24px !important;border-top:1px solid ",";max-width:1540px;"],y.a.border.light),q=function(e){var t=e.company;return r.a.createElement(Q,null,"© ",t)};q.propTypes={company:d.a.string.isRequired};var z=q,R=(a(164),a(167),o.a.div.withConfig({displayName:"layout__Body",componentId:"sc-13x6kjw-0"})(["padding:0 24px;max-width:1540px;margin:auto;margin-top:100px;display:flex;flex-direction:column;@media (max-width:767px){padding:0 12px;}"])),P=function(e){var t=e.children;return r.a.createElement(c.StaticQuery,{query:"3926456875",render:function(e){var a=e.site;return r.a.createElement(i.Fragment,null,r.a.createElement(S,{siteTitle:a.siteMetadata.title}),r.a.createElement(R,null,t),r.a.createElement(z,{company:a.siteMetadata.officialTitle}))},data:n})};P.propTypes={children:d.a.node.isRequired};t.a=P},161:function(e){e.exports={data:{site:{siteMetadata:{title:"TrustBNB",officialTitle:"BV Real Estate Partners LLC"}}}}},162:function(e,t,a){"use strict";a.r(t);a(33);var n=a(0),i=a.n(n),r=a(4),o=a.n(r),l=a(52),d=a(2),c=function(e){var t=e.location,a=d.default.getResourcesForPathnameSync(t.pathname);return i.a.createElement(l.a,Object.assign({location:t,pageResources:a},a.json))};c.propTypes={location:o.a.shape({pathname:o.a.string.isRequired}).isRequired},t.default=c},163:function(e){e.exports={data:{logo:{childImageSharp:{fluid:{base64:"data:image/jpeg;base64,/9j/2wBDABALDA4MChAODQ4SERATGCgaGBYWGDEjJR0oOjM9PDkzODdASFxOQERXRTc4UG1RV19iZ2hnPk1xeXBkeFxlZ2P/2wBDARESEhgVGC8aGi9jQjhCY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2P/wgARCAARABQDASIAAhEBAxEB/8QAGAABAQEBAQAAAAAAAAAAAAAAAAQDAgX/xAAWAQEBAQAAAAAAAAAAAAAAAAABAgP/2gAMAwEAAhADEAAAAfbk51LsZmJ6QZwa/wD/xAAcEAEAAgIDAQAAAAAAAAAAAAACAAMBBBASIzL/2gAIAQEAAQUCseKxrvPC977jAux14/kT/8QAGREAAgMBAAAAAAAAAAAAAAAAAAECETEh/9oACAEDAQE/AYU+MaoWj0//xAAVEQEBAAAAAAAAAAAAAAAAAAABIP/aAAgBAgEBPwFj/8QAHhAAAQQBBQAAAAAAAAAAAAAAAAECEBFxEiExQUL/2gAIAQEABj8CVylP73jT4ZyWhY7MLk//xAAeEAACAQMFAAAAAAAAAAAAAAAAATEQIWFBgZGhwf/aAAgBAQABPyHTI7M8tUtczJjU1P6LXyppNiAf/9oADAMBAAIAAwAAABAX2IH/xAAYEQEBAQEBAAAAAAAAAAAAAAABADERQf/aAAgBAwEBPxAo+ki42Vtf/8QAGBEBAQEBAQAAAAAAAAAAAAAAAQARMSH/2gAIAQIBAT8Q0ekOzyOX/8QAIRABAAAGAQUBAAAAAAAAAAAAAQARITFBUaEQYXGRsfD/2gAIAQEAAT8QsLGhtghIM10dqzOlGVebjX+7xQKmETAt7t5CBXIWg05iyPnfRHKR/9k=",aspectRatio:1.198019801980198,src:"/static/0dca9b7c64ea7e106afe343a663a3abf/a3fb7/logo-strip.jpg",srcSet:"/static/0dca9b7c64ea7e106afe343a663a3abf/cf328/logo-strip.jpg 125w,\n/static/0dca9b7c64ea7e106afe343a663a3abf/a3fb7/logo-strip.jpg 242w",sizes:"(max-width: 242px) 100vw, 242px"}}}}}},164:function(e,t,a){},165:function(e){e.exports={data:{site:{siteMetadata:{title:"TrustBNB",description:"A website to showcase TrustBNB",author:"Alex Kim <agk2144@columbia.edu>"}}}}},171:function(e,t,a){"use strict";var n=a(7),i=a.n(n),r=a(0),o=a.n(r),l=a(152),d=a.n(l),c=a(145),p=a(4),s=a.n(p),m=a(149),u=Object(c.a)(d.a).withConfig({displayName:"full-width-section__StyledImg",componentId:"u85y5u-0"})(["overflow:hidden;border-radius:3px;position:absolute;top:0;left:0;width:100%;z-index:-1;height:350px;& > img{object-fit:cover !important;object-position:0% 0% !important;font-family:'object-fit: cover !important; object-position: 0% 0% !important;'}"]),h=function(e){function t(){return e.apply(this,arguments)||this}return i()(t,e),t.prototype.render=function(){var e=this.props.fluidImage;return o.a.createElement(m.b,null,o.a.createElement(u,{fluid:e}))},t}(r.Component);h.propTypes={fluidImage:s.a.object.isRequired,overlayText:s.a.string},h.defaultProps={overlayText:""},t.a=h},172:function(e,t,a){"use strict";var n=a(7),i=a.n(n),r=a(0),o=a.n(r),l=a(145),d=a(4),c=a.n(d),p=a(149),s=a(154),m=a(146),u=l.a.div.withConfig({displayName:"text-section__TextWrapper",componentId:"n8eq90-0"})(["padding:0 24px 22px 24px;p{color:",";}"],m.a.font.dark),h=l.a.div.withConfig({displayName:"text-section__Head",componentId:"n8eq90-1"})(["padding:24px 24px 0px 24px;h2{margin:0;color:",";}",""],function(e){return e.color},function(e){return"#fff"!==e.color&&"\n * {color: #fff}\n "}),g=function(e){function t(){return e.apply(this,arguments)||this}return i()(t,e),t.prototype.render=function(){var e=this.props,t=e.header,a=e.children,n=e.color;return o.a.createElement(p.a,{color:n},o.a.createElement(h,{color:n},o.a.createElement("h2",null,t)),o.a.createElement(u,null,o.a.createElement(s.a,null),a))},t}(r.Component);g.propTypes={header:c.a.string.isRequired,color:c.a.string},g.defaultProps={header:"",color:"#fff"},t.a=g},173:function(e,t,a){"use strict";var n=a(0),i=a.n(n),r=a(145).a.div.withConfig({displayName:"grid__StyledGrid",componentId:"sc-11sm5l4-0"})(["margin:18px 0;border-radius:3px;overflow:hidden;z-index:-1;display:flex;justify-content:space-around;flex-wrap:wrap;@media (max-width:768px){margin-left:12px;margin-right:12px;margin-top:12px;flex-wrap:wrap;}"]);t.a=function(e){var t=e.children.length;return i.a.createElement(r,{numChild:t},e.children)}},174:function(e,t,a){"use strict";var n=a(0),i=a.n(n),r=a(145).a.div.withConfig({displayName:"circle-grid__StyledGrid",componentId:"sc-1aq3fik-0"})(["margin:18px 0;border-radius:3px;overflow:hidden;z-index:-1;display:flex;justify-content:space-around;flex-wrap:wrap;@media (max-width:768px){margin-left:12px;margin-right:12px;margin-top:12px;flex-wrap:wrap;}"]);t.a=function(e){var t=e.children.length;return i.a.createElement(r,{numChild:t},e.children)}},175:function(e,t,a){"use strict";var n=a(7),i=a.n(n),r=a(0),o=a.n(r),l=a(145),d=a(4),c=a.n(d),p=(a(149),a(146),l.a.div.withConfig({displayName:"circle-grid-section__GridItem",componentId:"cpmk9-0"})(["text-align:center;padding:10px 0px;margin:18px auto;text-align:center;.grid-title{font-weight:700;}p{font-size:15px;text-align:center;margin:0 10px;}width:19.5%;@media (max-width:768px){width:32.5%;}@media (max-width:545px){width:49.5%;}"])),s=l.a.div.withConfig({displayName:"circle-grid-section__Body",componentId:"cpmk9-1"})(["margin:12px auto;max-width:230px;"]),m=l.a.div.withConfig({displayName:"circle-grid-section__StyledIcon",componentId:"cpmk9-2"})(["border-radius:100%;background-color:white;width:90px;height:90px;display:flex;justify-content:center;margin:0 auto;align-items:center;path{fill:",";}"],function(e){return e.color}),u=function(e){function t(){return e.apply(this,arguments)||this}return i()(t,e),t.prototype.render=function(){var e=this.props,t=e.icon,a=e.underTitle,n=e.underText,i=e.color;return o.a.createElement(p,null,o.a.createElement(m,{color:i},t),o.a.createElement(s,null,o.a.createElement("span",{className:"grid-title"},a),o.a.createElement("p",null,n)))},t}(r.Component);u.propTypes={icon:c.a.node.isRequired,underTitle:c.a.string,underText:c.a.string,color:c.a.string},u.defaultProps={underTitle:"",underText:"",color:"#fff"},t.a=u},176:function(e,t,a){"use strict";a(0);var n=a(145);a(151),a(153),a(146),n.a.ul.withConfig({displayName:"list__StyledUList",componentId:"fptqn2-0"})(["margin-bottom:0;margin-left:-14px;list-style-type:none;li{font-size:16px;line-height:2em;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;}svg{margin-right:1em;path{fill:#3fc380;}}"])}}]);
//# sourceMappingURL=component---src-pages-index-js-400f0c58ee7043692507.js.map
|
import {
sankey,
sankeyCenter,
sankeyJustify,
sankeyLeft,
sankeyLinkHorizontal,
sankeyRight,
} from 'd3-sankey';
import isFunction from 'lodash/isFunction';
import isNull from 'lodash/isNull';
import isUndefined from 'lodash/isUndefined';
import isString from 'lodash/isString';
import isNumber from 'lodash/isNumber';
import omit from 'lodash/omit';
import get from 'lodash/get';
import maxBy from 'lodash/maxBy';
import has from 'lodash/has';
import cloneDeep from 'lodash/cloneDeep';
import map from 'lodash/map';
import { format as numberFormat, formatPrefix } from 'd3-format';
import PropTypes from 'prop-types';
import React from 'react';
import { getValue } from './utils/Data';
import { bindTrailingArgs } from './util.js';
const SankeyNode = props => {
const {
graph,
node,
nodeClassName,
nodeStyle,
onMouseEnterNode,
onMouseLeaveNode,
onMouseMoveNode,
onMouseDownNode,
onMouseUpNode,
onClickNode,
} = props;
// create partial functions for handlers - callbacks with the current node/graph arguments attached
const makeHandler = origHandler =>
isFunction(origHandler)
? bindTrailingArgs(origHandler, { node, graph })
: null;
return (
<rect
x={node.x0}
y={node.y0}
width={Math.abs(node.x1 - node.x0)}
height={Math.abs(node.y1 - node.y0)}
className={`rct-sankey-node ${getValue(nodeClassName, node, graph)}`}
style={getValue(nodeStyle, node, graph)}
onMouseEnter={makeHandler(onMouseEnterNode)}
onMouseLeave={makeHandler(onMouseLeaveNode)}
onMouseMove={makeHandler(onMouseMoveNode)}
onMouseDown={makeHandler(onMouseDownNode)}
onMouseUp={makeHandler(onMouseUpNode)}
onClick={makeHandler(onClickNode)}
/>
);
};
SankeyNode.propTypes = {
graph: PropTypes.object,
node: PropTypes.object,
nodeClassName: PropTypes.oneOfType([PropTypes.string, PropTypes.func]),
nodeStyle: PropTypes.oneOfType([PropTypes.object, PropTypes.func]),
onMouseEnterNode: PropTypes.func,
onMouseLeaveNode: PropTypes.func,
onMouseMoveNode: PropTypes.func,
onMouseDownNode: PropTypes.func,
onMouseUpNode: PropTypes.func,
onClickNode: PropTypes.func,
};
const SankeyLink = props => {
const {
graph,
link,
linkPath,
linkClassName,
linkStyle,
onMouseEnterLink,
onMouseLeaveLink,
onMouseMoveLink,
onMouseDownLink,
onMouseUpLink,
onClickLink,
} = props;
// create partial functions for handlers - callbacks with the current graph/link arguments attached
const makeHandler = origHandler =>
isFunction(origHandler)
? bindTrailingArgs(origHandler, { link, graph })
: null;
return (
<path
d={linkPath}
className={`rct-sankey-link ${getValue(linkClassName, link, graph)}`}
style={{
...getValue(linkStyle, link, graph),
strokeWidth: link.width,
}}
onMouseEnter={makeHandler(onMouseEnterLink)}
onMouseLeave={makeHandler(onMouseLeaveLink)}
onMouseMove={makeHandler(onMouseMoveLink)}
onMouseDown={makeHandler(onMouseDownLink)}
onMouseUp={makeHandler(onMouseUpLink)}
onClick={makeHandler(onClickLink)}
/>
);
};
SankeyLink.propTypes = {
graph: PropTypes.object,
link: PropTypes.object,
linkPath: PropTypes.string,
linkClassName: PropTypes.oneOfType([PropTypes.string, PropTypes.func]),
linkStyle: PropTypes.oneOfType([PropTypes.object, PropTypes.func]),
onMouseEnterLink: PropTypes.func,
onMouseLeaveLink: PropTypes.func,
onMouseMoveLink: PropTypes.func,
onMouseDownLink: PropTypes.func,
onMouseUpLink: PropTypes.func,
onClickLink: PropTypes.func,
};
const SankeyNodeTerminal = props => {
const {
node,
graph,
nodeTerminalWidth,
nodeTerminalDistance,
nodeTerminalStyle,
nodeTerminalClassName,
nodeTerminalAttributes,
onMouseEnterNodeTerminal,
onMouseLeaveNodeTerminal,
onMouseMoveNodeTerminal,
onMouseDownNodeTerminal,
onMouseUpNodeTerminal,
onClickNodeTerminal,
} = props;
if (!node.terminalValue) return null;
const makeHandler = origHandler =>
isFunction(origHandler)
? bindTrailingArgs(origHandler, { node, graph, props })
: null;
const getWithNode = accessor => getValue(accessor, node, graph, props);
const width = getWithNode(nodeTerminalWidth) || 0;
const distance = getWithNode(nodeTerminalDistance) || 0;
const nodeHeight = Math.abs(node.y1 - node.y0) || 0;
const height =
(nodeHeight * node.terminalValue || 0) / (node.value || 0) || 0;
const style = getWithNode(nodeTerminalStyle);
const className = `rct-sankey-node-terminal ${getWithNode(
nodeTerminalClassName,
)}`;
const attributes = getWithNode(nodeTerminalAttributes);
return (
<rect
x={node.x1 + distance}
y={node.y0 + (nodeHeight - height)}
{...{ width, height, style, className }}
{...attributes}
onMouseEnter={makeHandler(onMouseEnterNodeTerminal)}
onMouseLeave={makeHandler(onMouseLeaveNodeTerminal)}
onMouseMove={makeHandler(onMouseMoveNodeTerminal)}
onMouseDown={makeHandler(onMouseDownNodeTerminal)}
onMouseUp={makeHandler(onMouseUpNodeTerminal)}
onClick={makeHandler(onClickNodeTerminal)}
/>
);
};
SankeyNodeTerminal.propTypes = {
node: PropTypes.object,
graph: PropTypes.object,
nodeTerminalWidth: PropTypes.oneOfType([PropTypes.bool, PropTypes.number]),
nodeTerminalDistance: PropTypes.oneOfType([PropTypes.number, PropTypes.func]),
nodeTerminalStyle: PropTypes.oneOfType([PropTypes.object, PropTypes.func]),
nodeTerminalClassName: PropTypes.oneOfType([
PropTypes.string,
PropTypes.func,
]),
nodeTerminalAttributes: PropTypes.oneOfType([
PropTypes.object,
PropTypes.func,
]),
onMouseEnterNodeTerminal: PropTypes.func,
onMouseLeaveNodeTerminal: PropTypes.func,
onMouseMoveNodeTerminal: PropTypes.func,
onMouseDownNodeTerminal: PropTypes.func,
onMouseUpNodeTerminal: PropTypes.func,
onClickNodeTerminal: PropTypes.func,
};
const SankeyNodeLabel = props => {
const {
node,
graph,
nodeLabelText,
nodeId,
nodeLabelPlacement,
nodeLabelDistance,
} = props;
const getWithNode = accessor => getValue(accessor, node, graph, props);
const getLabelText = isFunction(nodeLabelText) ? nodeLabelText : nodeId;
const placement = getWithNode(nodeLabelPlacement);
const distance = getWithNode(nodeLabelDistance) || 0;
const labelContent = getWithNode(getLabelText);
// don't render empty labels
if (
isNull(labelContent) ||
isUndefined(labelContent) ||
labelContent === false ||
labelContent === ''
) {
return null;
}
// if `labelContent` is a string or number, it is rendered as text within a SVG <text> element
// otherwise, it is rendered as arbitrary SVG content
// allows users to render components inside a node label (eg. to add icon or link)
const isTextLabel = isString(labelContent) || isNumber(labelContent);
if (!isTextLabel) {
return labelContent;
}
const baseClassName = `rct-sankey-node-label ${getWithNode(
props.nodeLabelClassName,
)}`;
const baseStyle = getWithNode(props.nodeLabelStyle);
let position;
let textStyle;
// use placement prop to determine x, y, alignmentBaseline and textAnchor
if (placement === 'above') {
// render label above node, centered horizontally
textStyle = {
alignmentBaseline: 'baseline',
textAnchor: 'middle',
...baseStyle,
};
position = {
x: node.x0 + Math.abs(node.x1 - node.x0) / 2,
y: node.y0 - distance,
};
} else if (placement === 'below') {
// render label above node, centered horizontally
textStyle = {
alignmentBaseline: 'hanging',
textAnchor: 'middle',
...baseStyle,
};
position = {
x: node.x0 + Math.abs(node.x1 - node.x0) / 2,
y: node.y1 + distance,
};
} else if (placement === 'before') {
// render label before (to left of) node, centered vertically
textStyle = {
alignmentBaseline: 'middle',
textAnchor: 'end',
...baseStyle,
};
position = {
x: node.x0 - distance,
y: node.y0 + Math.abs(node.y1 - node.y0) / 2,
};
} else {
if (!isUndefined(placement) && placement !== 'after')
// eslint-disable-next-line no-console
console.warn(
`${placement} is not a valid value for nodeLabelPlacement - defaulting to "after"`,
);
// render label after (to right of) node, centered vertically
textStyle = {
alignmentBaseline: 'middle',
textAnchor: 'start',
...baseStyle,
};
position = {
x: node.x1 + distance,
y: node.y0 + Math.abs(node.y1 - node.y0) / 2,
};
}
const className = `${baseClassName} rct-sankey-node-label-text`;
return (
<text {...position} className={className} style={textStyle}>
{labelContent}
</text>
);
};
SankeyNodeLabel.propTypes = {
node: PropTypes.object,
graph: PropTypes.object,
nodeLabelClassName: PropTypes.oneOfType([PropTypes.string, PropTypes.func]),
nodeLabelStyle: PropTypes.oneOfType([PropTypes.object, PropTypes.func]),
nodeLabelText: PropTypes.func,
nodeId: PropTypes.func,
nodeLabelPlacement: PropTypes.oneOfType([
PropTypes.oneOf(['before', 'after', 'above', 'below']),
PropTypes.func,
]),
nodeLabelDistance: PropTypes.oneOfType([PropTypes.number, PropTypes.func]),
};
const SankeyLinkLabel = props => {
const {
link,
graph,
linkLabelClassName,
linkLabelStyle,
linkLabelAttributes,
linkLabelStartOffset,
linkLabelText,
linkPathId,
} = props;
const getWithLink = accessor => getValue(accessor, link, graph, props);
const className = `rct-sankey-link-label ${getWithLink(
linkLabelClassName || '',
)}`;
const style = getWithLink(linkLabelStyle || {});
const attributes = getWithLink(linkLabelAttributes || {});
const startOffset = getWithLink(linkLabelStartOffset || 0);
return (
<text className={className} style={style} {...attributes}>
<textPath startOffset={startOffset} xlinkHref={`#${linkPathId}`}>
{getWithLink(linkLabelText)}
</textPath>
</text>
);
};
SankeyLinkLabel.propTypes = {
link: PropTypes.object,
graph: PropTypes.object,
linkLabelClassName: PropTypes.oneOfType([PropTypes.string, PropTypes.func]),
linkLabelStyle: PropTypes.oneOfType([PropTypes.object, PropTypes.func]),
linkLabelAttributes: PropTypes.oneOfType([PropTypes.object, PropTypes.func]),
linkLabelStartOffset: PropTypes.oneOfType([
PropTypes.string,
PropTypes.number,
]),
linkLabelText: PropTypes.func,
linkPathId: PropTypes.string,
};
const SankeyStepLabel = props => {
const {
x,
y,
stepLabelPadding,
stepLabelText,
stepLabelClassName,
stepLabelStyle,
step,
} = props;
let yPos = y;
if (isNumber(stepLabelPadding)) {
yPos = yPos - stepLabelPadding;
}
return (
<text
className={`rct-step-label ${getValue(stepLabelClassName, step)}`}
style={getValue(stepLabelStyle, step)}
x={x}
y={yPos}
key={`step-${x}-${step}`}
>
{getValue(stepLabelText, step)}
</text>
);
};
SankeyStepLabel.propTypes = {
x: PropTypes.number,
y: PropTypes.number,
stepLabelPadding: PropTypes.number,
stepLabelText: PropTypes.oneOfType([PropTypes.string, PropTypes.func]),
stepLabelClassName: PropTypes.oneOfType([PropTypes.string, PropTypes.func]),
stepLabelStyle: PropTypes.oneOfType([PropTypes.object, PropTypes.func]),
step: PropTypes.string,
};
const SVGContainer = props => {
const otherProps = omit(props, ['standalone']);
if (props.standalone) {
return <svg {...otherProps} />;
}
return <g {...otherProps} />;
};
SVGContainer.propTypes = {
standalone: PropTypes.bool,
};
/**
* Enhance the graph object created by d3-sankey by adding some additional useful properties.
* Adds `maxDepth` (max of node `depth` properties)
* and `node.terminalValue` (value of node's terminal, sum of all 'out' nodes minus sum of 'in' nodes)
*/
function enhanceGraph(graph) {
graph.nodes.forEach(node => {
const sourceLinksSum = (node.sourceLinks || []).reduce(
(sum, link) => sum + link.value,
0,
);
node.terminalValue = Math.max(node.value - sourceLinksSum, 0);
});
graph.links.forEach(link => {
link.valueSourceRelative = (link.value || 0) / get(link, 'source.value', 0);
link.valueTargetRelative = (link.value || 0) / get(link, 'target.value', 0);
});
graph.maxDepth = maxBy(graph.nodes, 'depth');
graph.maxDepth = graph.nodes.reduce(
(max, node) => Math.max(node.depth || 0, max),
0,
);
return graph;
}
function getLinkId(link, nodeId) {
return `link-${nodeId(link.source)}-to-${nodeId(link.target)}`;
}
const nodeAlignmentsByName = {
left: sankeyLeft,
right: sankeyRight,
center: sankeyCenter,
justify: sankeyJustify,
};
/**
* A `SankeyDiagram` is a type of flow diagram which visualizes directed flow between nodes
* of a network graph. Currently only *acyclic* networks are supported.
*/
export default class SankeyDiagram extends React.Component {
static propTypes = {
/**
* Array of node objects, represented by vertical rectangles.
* These represent the base entities which links flow into & out of.
*/
nodes: PropTypes.arrayOf(PropTypes.object).isRequired,
/**
* Array of link objects, represented by curved paths between nodes.
* Links represent a magnitude of flow between one node and another.
* Each should have a 'source' node [identifier], a 'target' node [identifier],
* and a numerical value representing flow magnitude.
*/
links: PropTypes.arrayOf(
PropTypes.shape({
source: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
target: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
value: PropTypes.number,
}),
).isRequired,
/**
* Width of the SVG element.
*/
width: PropTypes.number.isRequired,
/**
* Height of the SVG element.
*/
height: PropTypes.number.isRequired,
/**
* Boolean which decides if the nodes & links props should be cloned before being mutated into
* the Sankey data structure. Passing `false` is faster, but may cause unintended side effects
* if nodes or links data are used elsewhere
*/
shouldClone: PropTypes.bool,
/**
* `className` attribute to be applied to the SVG element.
*/
className: PropTypes.string,
/**
* Inline style object to be applied to the SVG element.
*/
style: PropTypes.object,
/**
* Boolean which determines whether the chart should be rendered as a standalone `<svg>` element
* or a `<g>` group element (as a child within an existing `<svg>`).
* True by default, pass `false` to render in a `<g>`.
*/
standalone: PropTypes.bool,
/**
* Internal top margin, in pixels. Generally used to leave extra space inside the SVG for labels.
*/
marginTop: PropTypes.number,
/**
* Internal bottom margin, in pixels.
*/
marginBottom: PropTypes.number,
/**
* Internal left margin, in pixels.
*/
marginLeft: PropTypes.number,
/**
* Internal right margin, in pixels.
*/
marginRight: PropTypes.number,
/**
* Boolean which determines if node rectangles should be shown,
* or function (`showNode(node, graph)`) which returns a boolean
*/
showNodes: PropTypes.oneOfType([PropTypes.bool, PropTypes.func]),
/**
* Accessor function `nodeId(node, graph)` which specifies how to access the ID of each node object.
* These should be the same identifiers used by `links[].source` and `.target`.
* Uses the node's index in `nodes` array by default.
*/
nodeId: PropTypes.func,
/**
* Width (in pixels) of the vertical node rectangles.
*/
nodeWidth: PropTypes.number,
/**
* Vertical padding (in pixels) between each of the node lines.
*/
nodePadding: PropTypes.number,
/**
* Node alignment method used to layout the nodes.
* Must be 'left', 'right', 'center', or 'justify'.
* See [d3-sankey alignment docs](https://github.com/d3/d3-sankey#alignments) for more details.
*/
nodeAlignment: PropTypes.oneOf(['left', 'right', 'center', 'justify']),
/**
* `className` attribute to be applied to each node,
* or accessor function which returns a class (string).
*/
nodeClassName: PropTypes.oneOfType([PropTypes.string, PropTypes.func]),
/**
* Inline style object to be applied to each node,
* or accessor function which returns a style object.
*/
nodeStyle: PropTypes.oneOfType([PropTypes.object, PropTypes.func]),
/**
* Node `mouseenter` event handler, called when user's mouse enters a node.
*/
onMouseEnterNode: PropTypes.func,
/**
* Node `mouseleave` event handler, called when user's mouse leaves a node.
*/
onMouseLeaveNode: PropTypes.func,
/**
* Node `mousemove` event handler, called when user's mouse moves within a node.
*/
onMouseMoveNode: PropTypes.func,
/**
* Node `mousedown` event handler, called when user's mouse button is depressed within a node.
*/
onMouseDownNode: PropTypes.func,
/**
* Node `mouseup` event handler, called when user's mouse button is released within a node.
*/
onMouseUpNode: PropTypes.func,
/**
* Node `click` event handler, called when user clicks within a node.
*/
onClickNode: PropTypes.func,
/**
* Boolean which determines if link paths should be shown,
* or function (`showLink(link, graph)`) which returns a boolean
*/
showLinks: PropTypes.oneOfType([PropTypes.bool, PropTypes.func]),
/**
* Class attribute to be applied to each link,
* or accessor function which returns a class (string).
*/
linkClassName: PropTypes.oneOfType([PropTypes.string, PropTypes.func]),
/**
* Inline style object to be applied to each link,
* or accessor function which returns a style object.
*/
linkStyle: PropTypes.oneOfType([PropTypes.object, PropTypes.func]),
/**
* Link `mouseenter` event handler, called when user's mouse enters a link.
*/
onMouseEnterLink: PropTypes.func,
/**
* Link `mouseleave` event handler, called when user's mouse leaves a link.
*/
onMouseLeaveLink: PropTypes.func,
/**
* Link `mousemove` event handler, called when user's mouse moves within a link.
*/
onMouseMoveLink: PropTypes.func,
/**
* Link `mousedown` event handler, called when user's mouse button is depressed within a link.
*/
onMouseDownLink: PropTypes.func,
/**
* Link `mouseup` event handler, called when user's mouse button is released within a link.
*/
onMouseUpLink: PropTypes.func,
/**
* Link `click` event handler, called when user clicks within a link.
*/
onClickLink: PropTypes.func,
/**
* Boolean which determines if node terminals should be shown,
* or function (`showLink(link, graph)`) which returns a boolean.
* Terminals are bars that run alongside to show the amount
* which has flowed *in* but not *out*
*/
showNodeTerminals: PropTypes.oneOfType([PropTypes.bool, PropTypes.func]),
/**
* Width (in pixels) of the node terminal rectangles,
* or accessor function `f(node, graph)` which returns a width.
*/
nodeTerminalWidth: PropTypes.oneOfType([PropTypes.bool, PropTypes.number]),
/**
* Distance (in pixels) between nodes and their terminals,
* or accessor function `f(node, graph)` which returns a distance.
*/
nodeTerminalDistance: PropTypes.oneOfType([
PropTypes.number,
PropTypes.func,
]),
/**
* `className` attribute to be applied to each node terminal,
* or accessor function which returns a class (string).
*/
nodeTerminalClassName: PropTypes.oneOfType([
PropTypes.string,
PropTypes.func,
]),
/**
* Inline style object to be applied to each node terminal,
* or accessor function which returns a style object.
*/
nodeTerminalStyle: PropTypes.oneOfType([PropTypes.object, PropTypes.func]),
/**
* Attributes object to be applied to each node terminal element,
* or accessor function which returns an object.
*/
nodeTerminalAttributes: PropTypes.oneOfType([
PropTypes.object,
PropTypes.func,
]),
/**
* Node terminal `mouseenter` event handler, called when user's mouse enters a node terminal.
*/
onMouseEnterNodeTerminal: PropTypes.func,
/**
* Node terminal `mouseleave` event handler, called when user's mouse leaves a node terminal.
*/
onMouseLeaveNodeTerminal: PropTypes.func,
/**
* Node terminal `mousemove` event handler, called when user's mouse moves within a node terminal.
*/
onMouseMoveNodeTerminal: PropTypes.func,
/**
* Node terminal `mousedown` event handler, called when user's mouse button is depressed within a node terminal.
*/
onMouseDownNodeTerminal: PropTypes.func,
/**
* Node terminal `mouseup` event handler, called when user's mouse button is released within a node terminal.
*/
onMouseUpNodeTerminal: PropTypes.func,
/**
* Node terminal `click` event handler, called when user clicks within a node terminal.
*/
onClickNodeTerminal: PropTypes.func,
/**
* Boolean which determines if node labels should be shown,
* or function (`showLink(link, graph)`) which returns a boolean
*/
showNodeLabels: PropTypes.oneOfType([PropTypes.bool, PropTypes.func]),
/**
* Placement of the node label relative to the node rectangle.
* Expects 'before', 'after', 'above' or 'below', or a function which returns one of these.
* By default, labels in the left half of the diagram are placed 'after' and those in the right half 'before'
*/
nodeLabelPlacement: PropTypes.oneOfType([
PropTypes.oneOf(['before', 'after', 'above', 'below']),
PropTypes.func,
]),
/**
* Distance (in pixels) between nodes and their labels,
* or accessor function `f(node, graph)` which returns a distance.
*/
nodeLabelDistance: PropTypes.oneOfType([PropTypes.number, PropTypes.func]),
/**
* Accessor function `nodeLabelText(node, graph)` which returns the content to be used for node labels.
* The function may return a string/number (rendered as SVG `<text>`),
* or arbitrary React SVG element(s) (rendered as-is inside the SVG).
* NOTE: in the latter case (returning arbitrary SVG), `nodeLabelPlacement`, `nodeLabelDistance`,
* `nodeLabelClassName` and `nodeLabelStyle` props will not be applied -
* user is responsible for all positioning and attributes on this element.
*/
nodeLabelText: PropTypes.func,
/**
* `className` attribute to be applied to each node label,
* or accessor function which returns a class (string).
*/
nodeLabelClassName: PropTypes.oneOfType([PropTypes.string, PropTypes.func]),
/**
* Inline style object to be applied to each node label,
* or accessor function which returns a style object.
*/
nodeLabelStyle: PropTypes.oneOfType([PropTypes.object, PropTypes.func]),
/**
* Boolean which determines if link labels should be shown,
* or function (`showLink(link, graph)`) which returns a boolean
*/
showLinkLabels: PropTypes.oneOfType([PropTypes.bool, PropTypes.func]),
/**
* Accessor function `f(link, graph)` which returns the text to be used for link labels.
*/
linkLabelText: PropTypes.func,
/**
* `className` attribute to be applied to each link label,
* or accessor function which returns a class (string).
*/
linkLabelClassName: PropTypes.oneOfType([PropTypes.string, PropTypes.func]),
/**
* Inline style object to be applied to each link label,
* or accessor function which returns a style object.
*/
linkLabelStyle: PropTypes.oneOfType([PropTypes.object, PropTypes.func]),
/**
* Attributes object to be applied to each link label element,
* or accessor function which returns an object.
*/
linkLabelAttributes: PropTypes.oneOfType([
PropTypes.object,
PropTypes.func,
]),
/**
* `startOffset` attribute to apply to the link label `<textpath>` element.
* May be a number (in SVG units) or percent string (`"25%"`)
*/
linkLabelStartOffset: PropTypes.oneOfType([
PropTypes.string,
PropTypes.number,
]),
/**
* Boolean which determines if link *source* labels should be shown,
* or function (`showLink(link, graph)`) which returns a boolean
*/
showLinkSourceLabels: PropTypes.oneOfType([PropTypes.bool, PropTypes.func]),
/**
* Accessor function `f(link, graph)` which returns the text to be used for link *source* labels.
*/
linkSourceLabelText: PropTypes.func,
/**
* `className` attribute to be applied to each link *source* label,
* or accessor function which returns a class (string).
*/
linkSourceLabelClassName: PropTypes.oneOfType([
PropTypes.string,
PropTypes.func,
]),
/**
* Inline style object to be applied to each link *source* label,
* or accessor function which returns a style object.
*/
linkSourceLabelStyle: PropTypes.oneOfType([
PropTypes.object,
PropTypes.func,
]),
/**
* Attributes object to be applied to each link *source* label,
* or accessor function which returns an object.
*/
linkSourceLabelAttributes: PropTypes.oneOfType([
PropTypes.object,
PropTypes.func,
]),
/**
* `startOffset` attribute to apply to the link *source* label `<textpath>` element.
* May be a number (in SVG units) or percent string (`"25%"`)
*/
linkSourceLabelStartOffset: PropTypes.oneOfType([
PropTypes.string,
PropTypes.number,
]),
/**
* Boolean which determines if link *target* labels should be shown,
* or function (`showLink(link, graph)`) which returns a boolean
*/
showLinkTargetLabels: PropTypes.oneOfType([PropTypes.bool, PropTypes.func]),
/**
* Accessor function `f(link, graph)` which returns the text to be used for link *target* labels.
*/
linkTargetLabelText: PropTypes.func,
/**
* `className` attribute to be applied to each link *target* label,
* or accessor function which returns a class (string).
*/
linkTargetLabelClassName: PropTypes.oneOfType([
PropTypes.string,
PropTypes.func,
]),
/**
* Inline style object to be applied to each link *target* label,
* or accessor function which returns a style object.
*/
linkTargetLabelStyle: PropTypes.oneOfType([
PropTypes.object,
PropTypes.func,
]),
/**
* Attributes object to be applied to each link *target* label,
* or accessor function which returns an object.
*/
linkTargetLabelAttributes: PropTypes.oneOfType([
PropTypes.object,
PropTypes.func,
]),
/**
* `startOffset` attribute to apply to the link *target* label `<textpath>` element.
* May be a number (in SVG units) or percent string (`"25%"`)
*/
linkTargetLabelStartOffset: PropTypes.oneOfType([
PropTypes.string,
PropTypes.number,
]),
/**
* Text for step label or
* accessor function `f(step)` that returns the label text
*/
stepLabelText: PropTypes.oneOfType([PropTypes.string, PropTypes.func]),
/**
* `className` attribute applied to each label,
* or accessor function which returns a class (string)
*/
stepLabelClassName: PropTypes.oneOfType([PropTypes.string, PropTypes.func]),
/**
* Inline style object to be applied to each label,
* or accessor function which returns an object
*/
stepLabelStyle: PropTypes.oneOfType([PropTypes.object, PropTypes.func]),
/**
* Vertical padding (in pixels) between step label and uppermost positioned node of that step
*/
stepLabelPadding: PropTypes.number,
};
static defaultProps = {
width: 400,
height: 300,
shouldClone: true,
className: '',
style: {},
standalone: true,
marginTop: 0,
marginBottom: 0,
marginLeft: 0,
marginRight: 0,
nodeId: node => node.index,
showNodes: true,
nodeWidth: 12,
nodePadding: 8,
stepLabelPadding: 8,
nodeAlignment: 'justify',
nodeClassName: '',
nodeStyle: {},
showLinks: true,
linkClassName: '',
linkStyle: {},
showNodeTerminals: true,
nodeTerminalWidth: 5,
nodeTerminalDistance: 1,
nodeTerminalClassName: '',
nodeTerminalStyle: {},
nodeTerminalAttributes: { rx: 2, ry: 2 },
showNodeLabels: true,
nodeLabelPlacement: (node, graph) => {
return node.depth < graph.maxDepth / 2 ? 'after' : 'before';
},
nodeLabelDistance: 4,
nodeLabelText: (node, graph, props) => {
if (has(node, 'name')) return node.name;
if (has(node, 'label')) return node.label;
return getValue(props.nodeId, node, graph, props);
},
nodeLabelClassName: '',
nodeLabelStyle: {},
showLinkLabels: false,
linkLabelText: (link, graph, props) => {
const linkValue = link.value || 0;
const valueText = formatPrefix('.1~f', linkValue)(linkValue);
const sourceText = getValue(
props.nodeLabelText,
link.source,
graph,
props,
);
const targetText = getValue(
props.nodeLabelText,
link.target,
graph,
props,
);
return `${sourceText}→${targetText}: ${valueText}`;
},
linkLabelClassName: '',
linkLabelStyle: {},
linkLabelAttributes: {},
linkLabelStartOffset: '25%',
showLinkSourceLabels: false,
linkSourceLabelText: (link, graph, props) => {
const valueRelative = link.valueSourceRelative;
if (valueRelative === null || !isFinite(valueRelative)) return '';
const percentText =
valueRelative < 0.001 ? '<0.1%' : numberFormat('.1~%')(valueRelative);
return `${percentText} to ${getValue(
props.nodeLabelText,
link.target,
graph,
props,
)}`;
},
linkSourceLabelClassName: '',
linkSourceLabelStyle: {},
linkSourceLabelAttributes: {},
linkSourceLabelStartOffset: '2%',
showLinkTargetLabels: false,
linkTargetLabelText: (link, graph, props) => {
const valueRelative = link.valueTargetRelative;
if (valueRelative === null || !isFinite(valueRelative)) return '';
const percentText =
valueRelative < 0.001 ? '<0.1%' : numberFormat('.1~%')(valueRelative);
return `${percentText} from ${getValue(
props.nodeLabelText,
link.source,
graph,
props,
)}`;
},
linkTargetLabelClassName: '',
linkTargetLabelStyle: {},
linkTargetLabelAttributes: {},
linkTargetLabelStartOffset: '98%',
};
static getDerivedStateFromProps(nextProps, prevState) {
const { prevProps } = prevState;
// only update this._graph if a prop which affects the sankey layout has changed (most don't)
const sankeyLayoutPropKeys = [
'nodes',
'links',
'width',
'height',
'marginTop',
'marginBottom',
'marginLeft',
'marginRight',
'nodeId',
'nodeWidth',
'nodePadding',
'nodeAlignment',
];
const hasChangedSankey = sankeyLayoutPropKeys.some(key => {
return nextProps[key] !== prevProps[key];
});
if (hasChangedSankey) {
const graph = SankeyDiagram.makeSankeyGraph(nextProps);
return {
graph,
prevProps: cloneDeep(nextProps),
};
}
return null;
}
static makeSankeyGraph(props) {
const innerWidth = props.width - (props.marginLeft + props.marginRight);
const innerHeight = props.height - (props.marginTop + props.marginBottom);
const makeSankey = sankey()
.size([innerWidth, innerHeight])
.nodeId(props.nodeId)
.nodeWidth(props.nodeWidth)
.nodePadding(props.nodePadding)
.nodeAlign(
nodeAlignmentsByName[props.nodeAlignment] ||
nodeAlignmentsByName.justify,
);
const nodes = props.shouldClone ? cloneDeep(props.nodes) : props.nodes;
const links = props.shouldClone ? cloneDeep(props.links) : props.links;
const sankeyGraph = makeSankey({ nodes, links });
return enhanceGraph(sankeyGraph);
}
constructor(props) {
super(props);
const graph = SankeyDiagram.makeSankeyGraph(props);
const prevProps = cloneDeep(props);
this.state = { graph, prevProps };
}
render() {
const {
width,
height,
style,
standalone,
nodeId,
marginTop,
marginBottom,
marginLeft,
marginRight,
} = this.props;
const { graph } = this.state;
const makeLinkPath = sankeyLinkHorizontal();
const className = `rct-sankey-diagram ${this.props.className}`;
const innerWidth = width - (marginLeft + marginRight);
const innerHeight = height - (marginTop + marginBottom);
function mapNodesInGroupIf(shouldShow, groupClassName, mapFunc) {
if (!shouldShow) return null;
return (
<g className={groupClassName}>
{(graph.nodes || []).map((node, i) => {
if (!getValue(shouldShow, node, graph)) return null;
const key = `node-${nodeId(node)}`;
return mapFunc(node, i, key);
})}
</g>
);
}
function mapLinksInGroupIf(shouldShow, groupClassName, mapFunc) {
if (!shouldShow) return null;
return (
<g className={groupClassName}>
{(graph.links || []).map((link, i) => {
if (!getValue(shouldShow, link, graph)) return null;
const key = `link-${nodeId(link.source)}-to-${nodeId(link.target)}`;
return mapFunc(link, i, key);
})}
</g>
);
}
function displayStepLabelsIf(
stepLabelText,
stepLabelClassName,
stepLabelStyle,
stepLabelPadding,
nodes,
) {
if (!stepLabelText) {
return null;
}
const depthMapXPos = {};
const depthMapYPos = {};
nodes.forEach(n => {
depthMapXPos[n.depth] = n.x0;
// For the given depth, set the y equal to the highest positioned y value
depthMapYPos[n.depth] = depthMapYPos[n.depth]
? Math.min(n.y0, depthMapYPos[n.depth])
: n.y0;
});
return (
<g className="rct-step-labels" width={innerWidth} height={100}>
{map(depthMapXPos, (x, step) => {
const stepLabelProps = {
y: depthMapYPos[step],
step,
x,
stepLabelText,
stepLabelClassName,
stepLabelPadding,
stepLabelStyle,
};
return (
<SankeyStepLabel key={`rct-step-${step}`} {...stepLabelProps} />
);
})}
</g>
);
}
return (
<SVGContainer {...{ standalone, width, height, className, style }}>
<g
width={innerWidth}
height={innerHeight}
transform={`translate(${marginLeft}, ${marginTop})`}
>
{displayStepLabelsIf(
this.props.stepLabelText,
this.props.stepLabelClassName,
this.props.stepLabelStyle,
this.props.stepLabelPadding,
graph.nodes,
)}
{mapLinksInGroupIf(
this.props.showLinks,
'rct-sankey-links',
(link, i, key) => {
const linkProps = {
...this.props,
key,
graph,
link,
linkPath: makeLinkPath(link),
};
return <SankeyLink {...linkProps} />;
},
)}
{mapNodesInGroupIf(
this.props.showNodes,
'rct-sankey-nodes',
(node, i, key) => {
return <SankeyNode {...this.props} {...{ key, graph, node }} />;
},
)}
;
{mapNodesInGroupIf(
this.props.showNodeTerminals,
'rct-sankey-node-terminals',
(node, i, key) => {
return (
<SankeyNodeTerminal {...this.props} {...{ key, graph, node }} />
);
},
)}
;
{/* the three types of link labels (link, link source, link target) use textpath to follow the link's path */}
{/* to minimize dom elements, first render one set of path definitions to be used by all three label types */}
{this.props.showLinkLabels ||
this.props.showLinkSourceLabels ||
this.props.showLinkTargetLabels ? (
<defs>
{graph.links.map(link => {
const hasLabel =
getValue(this.props.showLinkLabels, link, graph) ||
getValue(this.props.showLinkSourceLabels, link, graph) ||
getValue(this.props.showLinkTargetLabels, link, graph);
if (!hasLabel) return null;
const linkPath = makeLinkPath(link);
const linkPathId = `${getLinkId(link, nodeId)}-path`;
return <path id={linkPathId} d={linkPath} key={linkPathId} />;
})}
</defs>
) : null}
{mapLinksInGroupIf(
this.props.showLinkLabels,
'rct-sankey-link-labels',
(link, i, key) => {
const linkPathId = `${getLinkId(link, nodeId)}-path`;
const labelProps = {
...this.props,
key,
graph,
link,
linkPathId,
};
return <SankeyLinkLabel {...labelProps} />;
},
)}
{mapNodesInGroupIf(
this.props.showNodeLabels,
'rct-sankey-node-labels',
(node, i, key) => {
return (
<SankeyNodeLabel {...this.props} {...{ key, graph, node }} />
);
},
)}
;
{mapLinksInGroupIf(
this.props.showLinkSourceLabels,
'rct-sankey-link-source-labels',
(link, i, key) => {
const linkPathId = `${getLinkId(link, nodeId)}-path`;
const commonProps = {
...this.props,
key,
graph,
link,
linkPathId,
};
const labelProps = {
...commonProps,
linkLabelText: this.props.linkSourceLabelText,
linkLabelClassName: this.props.linkSourceLabelClassName,
linkLabelStyle: this.props.linkSourceLabelStyle,
linkLabelAttributes: this.props.linkSourceLabelAttributes,
linkLabelStartOffset: this.props.linkSourceLabelStartOffset,
};
return <SankeyLinkLabel {...labelProps} />;
},
)}
{mapLinksInGroupIf(
this.props.showLinkTargetLabels,
'rct-sankey-link-target-labels',
(link, i, key) => {
const linkPathId = `${getLinkId(link, nodeId)}-path`;
const commonProps = {
...this.props,
key,
graph,
link,
linkPathId,
};
const labelProps = {
...commonProps,
linkLabelText: this.props.linkTargetLabelText,
linkLabelClassName: this.props.linkTargetLabelClassName,
linkLabelStyle: {
textAnchor: 'end',
...this.props.linkTargetLabelStyle,
},
linkLabelAttributes: this.props.linkTargetLabelAttributes,
linkLabelStartOffset: this.props.linkTargetLabelStartOffset,
};
return <SankeyLinkLabel {...labelProps} />;
},
)}
</g>
</SVGContainer>
);
}
}
|
describe('request data', function(){
it('gives correct request properties', function(){
requestData('my-key', 'benjaminf')
.should.have.properties({
method:'user.getrecenttracks',
user:'benjaminf',
api_key:'my-key',
limit:200,
page:0
})
})
it('gives a request properties for page 50', function(){
requestData('my-key', 'benjaminf', 50)
.should.have.properties({
method:'user.getrecenttracks',
user:'benjaminf',
api_key:'my-key',
limit:200,
page:50
})
})
})
describe("request list", function(){
var requests;
before(function(){
requests = requestList('my-key', 'benjaminf', 3)
})
it('gives 3 request objects', function(){
requests.length.should.eql(3)
})
it('gives request objects with ascending pages', function(){
var page = 0;
requests.forEach(function(request){
request.page.should.eql(page++)
})
})
})
describe('lastFM', function(){
var request;
var server, request, callback;
before(function (done) {
callback = sinon.spy()
reqwest({
url:'fixture.xml',
type:'xml'
}).then(function(doc){
var xmlstr = (new XMLSerializer()).serializeToString(doc)
server = sinon.fakeServer.create();
server.respondWith([200, { "Content-Type": "application/xml" }, xmlstr]);
request = lastFM(requestData('my-key', 'benjaminf'), callback)
done();
})
});
after(function () { server.restore(); });
it('returns a promise', function(){
request.should.have.properties('then', 'always')
})
it('makes a request to the server', function(){
server.requests.length.should.eql(1)
})
it('used the correct params', function(){
var url = server.requests[0].url;
url.should.containEql('method=user.getrecenttracks');
url.should.containEql('user=benjaminf');
url.should.containEql('api_key=my-key');
});
describe('success', function(){
before(function(){
server.respond()
})
it('called back', function(){
callback.called.should.be.True
})
})
})
describe('extract tracks', function(){
var tracks;
before(function (done) {
reqwest({
url:'fixture.small.xml',
type:'xml'
}).then(function(doc){
tracks = extractTracks(doc)
done();
})
});
it('got two tracks', function(){
tracks.length.should.eql(2)
})
it('has correct first track', function(){
tracks[0].should.have.properties({
artist:'TEEN',
name: 'Roses & Wine',
album: 'In Limbo',
date: '22 May 2014, 20:11',
url: 'http://www.last.fm/music/TEEN/_/Roses+&+Wine'
})
})
it('has correct second track', function(){
tracks[1].should.have.properties({
artist:'TEEN',
name: 'Why Why Why',
album: 'In Limbo',
date: '22 May 2014, 20:05',
url: 'http://www.last.fm/music/TEEN/_/Why+Why+Why'
})
})
})
describe('extract page count', function(){
var pages;
before(function (done) {
reqwest({
url:'fixture.small.xml',
type:'xml'
}).then(function(doc){
pages = extractPageCount(doc)
done();
})
});
it('got 15412 pages', function(){
pages.should.eql(15412)
})
})
describe('row', function(){
it('works', function(){
row(['a','b'], {b: 100, a: 20, c: 30})
.should.eql([20, 100])
})
})
describe('csv', function(){
it('works for numbers', function(){
csv([1,2,3])
.should.eql('1,2,3')
})
it('works for strings', function(){
csv(['one',2,'three'])
.should.eql('one,2,three')
})
// it('escapes ,', function(){
// csv(['one',',','three'])
// .should.eql('one,",",three')
// })
// it('escapes "', function(){
// csv(['one','"','three'])
// .should.eql('one,"\\"",three')
// })
it('removes problem characters', function(){
csv(['o"n"e',',two,','"three"'])
.should.eql('one,two,three')
})
})
describe('delay', function(){
var clock,
delayFn,
delayCallback;
before(function () {
clock = sinon.useFakeTimers();
delayFn = sinon.spy();
delay(delayFn,100)("testing");
});
after(function () { clock.restore(); });
it("didn't call right away", function(){
delayFn.called.should.be.False
})
describe('after 100ms', function(){
before(function(){
clock.tick(100);
});
it("was called", function(){
delayFn.called.should.be.True
})
it('was called with same input', function(){
delayFn.calledWith("testing").should.be.True;
})
})
})
|
import React, { useState, useEffect } from 'react'
import DashBoardSectionVehicleHeading from '../../Atoms/admin/DashBoardSectionVehicleHeading';
import axios from 'axios';
import { getCookie } from '../../../jsfunctions/cookies';
export default function DashBoardVehicleInfoSectionHeadingMolecular(props) {
const [sectionList, setsectionList] = useState([]);
const [increment, setincrement] = useState(true);
const [decrement, setdecrement] = useState(true);
var config = {
headers: {
'Authorization': 'Bearer ' + getCookie('token'),
}
}
useEffect(() => {
axios.get(`${process.env.REACT_APP_API_BASE_URL}/admin/getsections`, config)
.then(function (response) {
// console.log(response.data);
setsectionList(response.data);
props.setsectionName(response.data[0]);
})
}, [])
useEffect(() => {
const index = sectionList.indexOf(props.sectionName, 0);
if (index == sectionList.length-1) {
props.setsectionName(sectionList[0]);
}
else {
props.setsectionName(sectionList[index + 1]);
}
}, [increment])
useEffect(() => {
const index = sectionList.indexOf(props.sectionName, 0);
if (index == 0) {
props.setsectionName(sectionList[sectionList.length-1]);
}
else {
props.setsectionName(sectionList[index - 1]);
}
}, [decrement])
return (
<div>
<div className="flex justify-between">
<button onClick={() => setdecrement(!decrement)}><svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11 19l-7-7 7-7m8 14l-7-7 7-7" />
</svg></button>
<DashBoardSectionVehicleHeading name={props.sectionName} />
<button onClick={() => setincrement(!increment)}><svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 5l7 7-7 7M5 5l7 7-7 7" />
</svg></button>
</div>
</div>
)
}
|
var argv = require("minimist")(process.argv.slice(2), { default: { show: 1 } });
var five = require("../lib/johnny-five");
var board = new five.Board();
board.on("ready", function() {
// MPR121QR2 3x3 Capacitive Touch Shield
var touchpad;
if (argv.show === 1) {
touchpad = new five.Touchpad({
controller: "MPR121QR2_SHIELD"
});
}
if (argv.show === 2) {
touchpad = new five.Touchpad({
controller: "MPR121QR2_SHIELD",
keys: [
["!", "@", "#"],
["$", "%", "^"],
["&", "-", "+"],
]
});
}
if (argv.show === 3) {
touchpad = new five.Touchpad({
controller: "MPR121QR2_SHIELD",
keys: ["!", "@", "#", "$", "%", "^", "&", "-", "+"]
});
}
["change", "press", "hold", "release"].forEach(function(eventType) {
touchpad.on(eventType, function(event) {
console.log("Event: %s, Target: %s", eventType, event.which);
});
});
});
|
/**
@module utils-poll.js contains all of the logic for starting and stopping a poll.
@author iAmMichaelConnor
*/
/**
@param {function} pollingFunction - function MUST return false for 'unsuccessful' results.
@param {number} interval - polling frequency (in milliseconds)
@param {object} args = an object of arguments which are to be passed to the pollingFunction each poll.
*/
const poll = async (pollingFunction, interval, args) => {
console.log('Polling...');
// this is called as a Promise which only resolves when the conditions of the pollingFunction have been satisfied (i.e. once the pollingFunction returns something other than false).
const checkPollCondition = async (resolve, reject) => {
const response = await pollingFunction(args); // polling function must return a FALSE if unsuccessful.
if (response === false) {
// if the polling function was unsuccessful, poll again:
console.log('...');
setTimeout(checkPollCondition, interval, resolve, reject);
} else {
// if the polling function was successful, resolve this poll.
resolve(response);
}
};
return new Promise(checkPollCondition);
};
// EXAMPLES
let exampleResponse;
let delayIncrementer = 1000;
const exampleDelayToResolution = async () => {
exampleResponse = false;
setTimeout(() => {
exampleResponse = true;
}, 25000);
};
function delayedPromise(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
const exampleQueryDelay = async () => {
await delayedPromise(delayIncrementer);
delayIncrementer *= 2;
return exampleResponse;
};
const exampleQuery = async () => {
const response = await exampleQueryDelay();
return response;
};
/**
EXAMPLE ONLY - an example of a pollingFunction
@returns {boolean} - ALWAYS!!!
*/
const examplePollingFunction = async () => {
console.log('in pollingFunction');
const response = await exampleQuery();
console.log(`response: ${response}`);
return response;
};
/**
EXAMPLE ONLY - an invokation of a poll
Execute from command line with:
node -e 'require("./utils-poll").examplePoll()'
*/
async function examplePoll() {
exampleDelayToResolution();
await poll(examplePollingFunction, 1000);
}
export default {
examplePoll,
poll,
};
|
import {gql} from "@apollo/client";
export const LOGIN_USER = gql`
mutation login($email: String!, $password: String!) {
login(email: $email, password: $password) {
token
user {
_id
username
}
}
}
`;
export const ADD_USER = gql `
mutation addUser($username: String!, $password: String!, $email: String!) {
addUser(username: $username, password: $password, email: $email) {
token
user {
username
_id
email
}
}
}
`;
export const REMOVE_BOOK = gql`
mutation removeBook($bookId: String!) {
removeBook(bookId: $bookId) {
_id
username
bookCount
savedBooks {
bookId
authors
image
link
title
description
}
}
}
`;
export const SAVE_BOOK = gql`
mutation saveBook($bookId: String!) {
saveBook(bookId: $bookId) {
_id
username
bookCount
savedBooks {
bookId
authors
image
link
title
description
}
}
}
`;
|
from django.db import models
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, \
PermissionsMixin
from django.conf import settings
# Create your models here.
class UserManager(BaseUserManager):
def create_user(self, email, password=None, **extra_fields):
"""Creates and saves a new user"""
if not email:
raise ValueError('Users must have an email address')
user = self.model(email=self.normalize_email(email), **extra_fields)
user.set_password(password)
user.save(using=self._db)
return user
def create_superuser(self, email, password):
"""Creates and saves a new super user"""
user = self.create_user(email, password)
user.is_staff = True
user.is_superuser = True
user.save(using=self._db)
return user
class User(AbstractBaseUser, PermissionsMixin):
"""Custom user model that supports using email instead of username"""
email = models.EmailField(max_length=255, unique=True)
name = models.CharField(max_length=255)
is_active = models.BooleanField(default=True)
is_staff = models.BooleanField(default=False)
objects = UserManager()
USERNAME_FIELD = 'email'
class Tag(models.Model):
"""Tag to be used for a recipe"""
name = models.CharField(max_length=255)
user = models.ForeignKey(
settings.AUTH_USER_MODEL,
on_delete=models.CASCADE,
)
def __str__(self):
return self.name
class Ingredient(models.Model):
"""Ingredient to be used in a recipe"""
name = models.CharField(max_length=255)
user = models.ForeignKey(
settings.AUTH_USER_MODEL,
on_delete=models.CASCADE
)
def __str__(self):
return self.name
class Recipe(models.Model):
"""Recipe object"""
user = models.ForeignKey(
settings.AUTH_USER_MODEL,
on_delete=models.CASCADE
)
title = models.CharField(max_length=255)
time_minutes = models.IntegerField()
price = models.DecimalField(max_digits=5, decimal_places=2)
link = models.CharField(max_length=255, blank=True)
ingredients = models.ManyToManyField('Ingredient')
tags = models.ManyToManyField('Tag')
def __str__(self):
return self.title
|
def decompose(n):
return helper(n, n**2)
def helper(n, sum, arr=[]):
if sum==0:
return arr[::-1]
for i in range(n-1, -1, -1):
if i**2<=sum:
return helper(i, sum-i**2, arr+[i]) or helper(i, sum, arr)
|