text
stringlengths
3
1.05M
// Copyright 2009 the Sputnik authors. All rights reserved. // This code is governed by the BSD license found in the LICENSE file. /** * @name: S7.2_A1.4_T2; * @section: 7.2, 7.5; * @assertion: SPACE (U+0020) between any two tokens is allowed; * @description: Insert real SPACE between tokens of var x=1; */ //CHECK#2 var x = 1 ; if (x !== 1) { $ERROR('#2: var x = 1 ; x === 1. Actual: ' + (x)); }
# coding=utf-8 # Copyright 2022 The Google Research Authors. # # 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. """Create a label map file for Felix and FelixPointer. Felix label map files are created by converting existing lasertagger label map files. Laserpointer assumes that if a phrase can be inserted then all subphrases can also be inserted. This is not the case with lasertagger. Felix label map file consists of inserting up to N number of MASKS. """ import json from absl import app from absl import flags from absl import logging import tensorflow as tf from felix import felix_flags # pylint: disable=unused-import FLAGS = flags.FLAGS # Vocabulary constructions specific flag(s) are listed below. Additionally, we # use the following flags from nlp/heady/felix/felix_flags.py: # - do_lower_case # - label_map_file # - max_mask # - use_pointing flags.DEFINE_string('output', None, 'Path to the resulting new label_map_file.') def main(argv): if len(argv) > 1: raise app.UsageError('Too many command-line arguments.') # always use these entries. label_map = {'PAD': 0, 'SWAP': 1, 'KEEP': 2, 'DELETE': 3} # Create Insert 1 MASK to insertion N MASKS. for i in range(1, FLAGS.max_mask+1): label_map[f'KEEP|{i}'] = len(label_map) if not FLAGS.use_pointing: label_map[f'DELETE|{i}'] = len(label_map) logging.info('Created new label map with %d labels', len(label_map)) with tf.io.gfile.GFile(FLAGS.output, mode='w') as f: json.dump(label_map, f) if __name__ == '__main__': flags.mark_flag_as_required('output') app.run(main)
'use strict'; import alt from '../alt'; import HomeActions from '../actions/HomeActions'; class HomeStore { constructor() { this.bindActions(HomeActions); this.characters = []; } onGetTwoCharactersSuccess(data) { this.characters = data; } onGetTwoCharactersFail(errorMessage) { toastr.error(errorMessage); } onVoteFail(errorMessage) { toastr.error(errorMessage); } } export default alt.createStore(HomeStore);
from __future__ import unicode_literals import re import json from .common import InfoExtractor from .gigya import GigyaBaseIE from ..compat import compat_HTTPError from ..utils import ( ExtractorError, clean_html, extract_attributes, float_or_none, get_element_by_class, int_or_none, merge_dicts, str_or_none, strip_or_none, url_or_none, ) class CanvasIE(InfoExtractor): _VALID_URL = r'https?://mediazone\.vrt\.be/api/v1/(?P<site_id>canvas|een|ketnet|vrt(?:video|nieuws)|sporza|dako)/assets/(?P<id>[^/?#&]+)' _TESTS = [{ 'url': 'https://mediazone.vrt.be/api/v1/ketnet/assets/md-ast-4ac54990-ce66-4d00-a8ca-9eac86f4c475', 'md5': '37b2b7bb9b3dcaa05b67058dc3a714a9', 'info_dict': { 'id': 'md-ast-4ac54990-ce66-4d00-a8ca-9eac86f4c475', 'display_id': 'md-ast-4ac54990-ce66-4d00-a8ca-9eac86f4c475', 'ext': 'mp4', 'title': 'Nachtwacht: De Greystook', 'description': 'Nachtwacht: De Greystook', 'thumbnail': r're:^https?://.*\.jpg$', 'duration': 1468.02, }, 'expected_warnings': ['is not a supported codec'], }, { 'url': 'https://mediazone.vrt.be/api/v1/canvas/assets/mz-ast-5e5f90b6-2d72-4c40-82c2-e134f884e93e', 'only_matching': True, }] _GEO_BYPASS = False _HLS_ENTRY_PROTOCOLS_MAP = { 'HLS': 'm3u8_native', 'HLS_AES': 'm3u8', } _REST_API_BASE = 'https://media-services-public.vrt.be/vualto-video-aggregator-web/rest/external/v1' def _real_extract(self, url): mobj = re.match(self._VALID_URL, url) site_id, video_id = mobj.group('site_id'), mobj.group('id') data = None if site_id != 'vrtvideo': # Old API endpoint, serves more formats but may fail for some videos data = self._download_json( 'https://mediazone.vrt.be/api/v1/%s/assets/%s' % (site_id, video_id), video_id, 'Downloading asset JSON', 'Unable to download asset JSON', fatal=False) # New API endpoint if not data: headers = self.geo_verification_headers() headers.update({'Content-Type': 'application/json'}) token = self._download_json( '%s/tokens' % self._REST_API_BASE, video_id, 'Downloading token', data=b'', headers=headers)['vrtPlayerToken'] data = self._download_json( '%s/videos/%s' % (self._REST_API_BASE, video_id), video_id, 'Downloading video JSON', query={ 'vrtPlayerToken': token, 'client': '%s@PROD' % site_id, }, expected_status=400) if not data.get('title'): code = data.get('code') if code == 'AUTHENTICATION_REQUIRED': self.raise_login_required() elif code == 'INVALID_LOCATION': self.raise_geo_restricted(countries=['BE']) raise ExtractorError(data.get('message') or code, expected=True) title = data['title'] description = data.get('description') formats = [] subtitles = {} for target in data['targetUrls']: format_url, format_type = url_or_none(target.get('url')), str_or_none(target.get('type')) if not format_url or not format_type: continue format_type = format_type.upper() if format_type in self._HLS_ENTRY_PROTOCOLS_MAP: fmts, subs = self._extract_m3u8_formats_and_subtitles( format_url, video_id, 'mp4', self._HLS_ENTRY_PROTOCOLS_MAP[format_type], m3u8_id=format_type, fatal=False) formats.extend(fmts) subtitles = self._merge_subtitles(subtitles, subs) elif format_type == 'HDS': formats.extend(self._extract_f4m_formats( format_url, video_id, f4m_id=format_type, fatal=False)) elif format_type == 'MPEG_DASH': fmts, subs = self._extract_mpd_formats_and_subtitles( format_url, video_id, mpd_id=format_type, fatal=False) formats.extend(fmts) subtitles = self._merge_subtitles(subtitles, subs) elif format_type == 'HSS': fmts, subs = self._extract_ism_formats_and_subtitles( format_url, video_id, ism_id='mss', fatal=False) formats.extend(fmts) subtitles = self._merge_subtitles(subtitles, subs) else: formats.append({ 'format_id': format_type, 'url': format_url, }) self._sort_formats(formats) subtitle_urls = data.get('subtitleUrls') if isinstance(subtitle_urls, list): for subtitle in subtitle_urls: subtitle_url = subtitle.get('url') if subtitle_url and subtitle.get('type') == 'CLOSED': subtitles.setdefault('nl', []).append({'url': subtitle_url}) return { 'id': video_id, 'display_id': video_id, 'title': title, 'description': description, 'formats': formats, 'duration': float_or_none(data.get('duration'), 1000), 'thumbnail': data.get('posterImageUrl'), 'subtitles': subtitles, } class CanvasEenIE(InfoExtractor): IE_DESC = 'canvas.be and een.be' _VALID_URL = r'https?://(?:www\.)?(?P<site_id>canvas|een)\.be/(?:[^/]+/)*(?P<id>[^/?#&]+)' _TESTS = [{ 'url': 'http://www.canvas.be/video/de-afspraak/najaar-2015/de-afspraak-veilt-voor-de-warmste-week', 'md5': 'ed66976748d12350b118455979cca293', 'info_dict': { 'id': 'mz-ast-5e5f90b6-2d72-4c40-82c2-e134f884e93e', 'display_id': 'de-afspraak-veilt-voor-de-warmste-week', 'ext': 'flv', 'title': 'De afspraak veilt voor de Warmste Week', 'description': 'md5:24cb860c320dc2be7358e0e5aa317ba6', 'thumbnail': r're:^https?://.*\.jpg$', 'duration': 49.02, }, 'expected_warnings': ['is not a supported codec'], }, { # with subtitles 'url': 'http://www.canvas.be/video/panorama/2016/pieter-0167', 'info_dict': { 'id': 'mz-ast-5240ff21-2d30-4101-bba6-92b5ec67c625', 'display_id': 'pieter-0167', 'ext': 'mp4', 'title': 'Pieter 0167', 'description': 'md5:943cd30f48a5d29ba02c3a104dc4ec4e', 'thumbnail': r're:^https?://.*\.jpg$', 'duration': 2553.08, 'subtitles': { 'nl': [{ 'ext': 'vtt', }], }, }, 'params': { 'skip_download': True, }, 'skip': 'Pagina niet gevonden', }, { 'url': 'https://www.een.be/thuis/emma-pakt-thilly-aan', 'info_dict': { 'id': 'md-ast-3a24ced2-64d7-44fb-b4ed-ed1aafbf90b8', 'display_id': 'emma-pakt-thilly-aan', 'ext': 'mp4', 'title': 'Emma pakt Thilly aan', 'description': 'md5:c5c9b572388a99b2690030afa3f3bad7', 'thumbnail': r're:^https?://.*\.jpg$', 'duration': 118.24, }, 'params': { 'skip_download': True, }, 'expected_warnings': ['is not a supported codec'], }, { 'url': 'https://www.canvas.be/check-point/najaar-2016/de-politie-uw-vriend', 'only_matching': True, }] def _real_extract(self, url): mobj = re.match(self._VALID_URL, url) site_id, display_id = mobj.group('site_id'), mobj.group('id') webpage = self._download_webpage(url, display_id) title = strip_or_none(self._search_regex( r'<h1[^>]+class="video__body__header__title"[^>]*>(.+?)</h1>', webpage, 'title', default=None) or self._og_search_title( webpage, default=None)) video_id = self._html_search_regex( r'data-video=(["\'])(?P<id>(?:(?!\1).)+)\1', webpage, 'video id', group='id') return { '_type': 'url_transparent', 'url': 'https://mediazone.vrt.be/api/v1/%s/assets/%s' % (site_id, video_id), 'ie_key': CanvasIE.ie_key(), 'id': video_id, 'display_id': display_id, 'title': title, 'description': self._og_search_description(webpage), } class VrtNUIE(GigyaBaseIE): IE_DESC = 'VrtNU.be' _VALID_URL = r'https?://(?:www\.)?vrt\.be/vrtnu/a-z/(?:[^/]+/){2}(?P<id>[^/?#&]+)' _TESTS = [{ # Available via old API endpoint 'url': 'https://www.vrt.be/vrtnu/a-z/postbus-x/1989/postbus-x-s1989a1/', 'info_dict': { 'id': 'pbs-pub-e8713dac-899e-41de-9313-81269f4c04ac$vid-90c932b1-e21d-4fb8-99b1-db7b49cf74de', 'ext': 'mp4', 'title': 'Postbus X - Aflevering 1 (Seizoen 1989)', 'description': 'md5:b704f669eb9262da4c55b33d7c6ed4b7', 'duration': 1457.04, 'thumbnail': r're:^https?://.*\.jpg$', 'series': 'Postbus X', 'season': 'Seizoen 1989', 'season_number': 1989, 'episode': 'De zwarte weduwe', 'episode_number': 1, 'timestamp': 1595822400, 'upload_date': '20200727', }, 'skip': 'This video is only available for registered users', 'params': { 'username': '<snip>', 'password': '<snip>', }, 'expected_warnings': ['is not a supported codec'], }, { # Only available via new API endpoint 'url': 'https://www.vrt.be/vrtnu/a-z/kamp-waes/1/kamp-waes-s1a5/', 'info_dict': { 'id': 'pbs-pub-0763b56c-64fb-4d38-b95b-af60bf433c71$vid-ad36a73c-4735-4f1f-b2c0-a38e6e6aa7e1', 'ext': 'mp4', 'title': 'Aflevering 5', 'description': 'Wie valt door de mand tijdens een missie?', 'duration': 2967.06, 'season': 'Season 1', 'season_number': 1, 'episode_number': 5, }, 'skip': 'This video is only available for registered users', 'params': { 'username': '<snip>', 'password': '<snip>', }, 'expected_warnings': ['Unable to download asset JSON', 'is not a supported codec', 'Unknown MIME type'], }] _NETRC_MACHINE = 'vrtnu' _APIKEY = '3_0Z2HujMtiWq_pkAjgnS2Md2E11a1AwZjYiBETtwNE-EoEHDINgtnvcAOpNgmrVGy' _CONTEXT_ID = 'R3595707040' def _real_initialize(self): self._login() def _login(self): username, password = self._get_login_info() if username is None: return auth_data = { 'APIKey': self._APIKEY, 'targetEnv': 'jssdk', 'loginID': username, 'password': password, 'authMode': 'cookie', } auth_info = self._gigya_login(auth_data) # Sometimes authentication fails for no good reason, retry login_attempt = 1 while login_attempt <= 3: try: # When requesting a token, no actual token is returned, but the # necessary cookies are set. self._request_webpage( 'https://token.vrt.be', None, note='Requesting a token', errnote='Could not get a token', headers={ 'Content-Type': 'application/json', 'Referer': 'https://www.vrt.be/vrtnu/', }, data=json.dumps({ 'uid': auth_info['UID'], 'uidsig': auth_info['UIDSignature'], 'ts': auth_info['signatureTimestamp'], 'email': auth_info['profile']['email'], }).encode('utf-8')) except ExtractorError as e: if isinstance(e.cause, compat_HTTPError) and e.cause.code == 401: login_attempt += 1 self.report_warning('Authentication failed') self._sleep(1, None, msg_template='Waiting for %(timeout)s seconds before trying again') else: raise e else: break def _real_extract(self, url): display_id = self._match_id(url) webpage = self._download_webpage(url, display_id) attrs = extract_attributes(self._search_regex( r'(<nui-media[^>]+>)', webpage, 'media element')) video_id = attrs['videoid'] publication_id = attrs.get('publicationid') if publication_id: video_id = publication_id + '$' + video_id page = (self._parse_json(self._search_regex( r'digitalData\s*=\s*({.+?});', webpage, 'digial data', default='{}'), video_id, fatal=False) or {}).get('page') or {} info = self._search_json_ld(webpage, display_id, default={}) return merge_dicts(info, { '_type': 'url_transparent', 'url': 'https://mediazone.vrt.be/api/v1/vrtvideo/assets/%s' % video_id, 'ie_key': CanvasIE.ie_key(), 'id': video_id, 'display_id': display_id, 'season_number': int_or_none(page.get('episode_season')), }) class DagelijkseKostIE(InfoExtractor): IE_DESC = 'dagelijksekost.een.be' _VALID_URL = r'https?://dagelijksekost\.een\.be/gerechten/(?P<id>[^/?#&]+)' _TEST = { 'url': 'https://dagelijksekost.een.be/gerechten/hachis-parmentier-met-witloof', 'md5': '30bfffc323009a3e5f689bef6efa2365', 'info_dict': { 'id': 'md-ast-27a4d1ff-7d7b-425e-b84f-a4d227f592fa', 'display_id': 'hachis-parmentier-met-witloof', 'ext': 'mp4', 'title': 'Hachis parmentier met witloof', 'description': 'md5:9960478392d87f63567b5b117688cdc5', 'thumbnail': r're:^https?://.*\.jpg$', 'duration': 283.02, }, 'expected_warnings': ['is not a supported codec'], } def _real_extract(self, url): display_id = self._match_id(url) webpage = self._download_webpage(url, display_id) title = strip_or_none(get_element_by_class( 'dish-metadata__title', webpage ) or self._html_search_meta( 'twitter:title', webpage)) description = clean_html(get_element_by_class( 'dish-description', webpage) ) or self._html_search_meta( ('description', 'twitter:description', 'og:description'), webpage) video_id = self._html_search_regex( r'data-url=(["\'])(?P<id>(?:(?!\1).)+)\1', webpage, 'video id', group='id') return { '_type': 'url_transparent', 'url': 'https://mediazone.vrt.be/api/v1/dako/assets/%s' % video_id, 'ie_key': CanvasIE.ie_key(), 'id': video_id, 'display_id': display_id, 'title': title, 'description': description, }
!function(e){const t=e.sq=e.sq||{};t.dictionary=Object.assign(t.dictionary||{},{"%0 of %1":"",Aquamarine:"",Black:"","Block quote":"Thonjëzat",Blue:"",Bold:"Trash","Bulleted List":"Listë me Pika","Bulleted list styles toolbar":"",Cancel:"Anulo","Centered image":"Foto e vendosur në mes","Change image text alternative":"Ndrysho tekstin zgjedhor të fotos","Choose heading":"Përzgjidh nëntitullin",Circle:"",Column:"Kolona",Decimal:"","Decimal with leading zero":"","Delete column":"Gris kolonën","Delete row":"Grish rreshtin","Dim grey":"",Disc:"","Document colors":"",Downloadable:"","Dropdown toolbar":"","Edit block":"","Edit link":"Redakto nyjën","Editor toolbar":"","Enter image caption":"Shto përshkrimin e fotos","Font Color":"","Full size image":"Foto me madhësi të plotë",Green:"",Grey:"","Header column":"Kolona e kokës","Header row":"Rreshti i kokës",Heading:"Nëntitulli","Heading 1":"Nëntitulli 1","Heading 2":"Nëntitulli 2","Heading 3":"Nëntitulli 3","Heading 4":"","Heading 5":"","Heading 6":"","Image resize list":"","Image toolbar":"","image widget":"Vegla e fotos",Insert:"","Insert column left":"","Insert column right":"","Insert image":"Shto Foto","Insert image via URL":"","Insert media":"Shto Medie","Insert row above":"Shto rresht sipër","Insert row below":"Shto rresht poshtë","Insert table":"Shto tabelë",Italic:"Pjerrtë","Left aligned image":"Foto e vendosur majtas","Light blue":"","Light green":"","Light grey":"",Link:"Shto nyjën","Link URL":"Nyja e URL-së","Lower-latin":"","Lower–roman":"","Media URL":"URL e Medies","media widget":"Vegla e medies","Merge cell down":"Bashko kutizat poshtë","Merge cell left":"Bashko kutizat majtas","Merge cell right":"Bashko kutizat djathtas","Merge cell up":"Bashko kutizat sipër","Merge cells":"Bashko kutizat",Next:"","Numbered List":"Listë me Numra","Numbered list styles toolbar":"","Open in a new tab":"","Open link in new tab":"Hap nyjën në faqe të re",Orange:"",Original:"",Paragraph:"Paragrafi","Paste the media URL in the input.":"",Previous:"",Purple:"",Red:"",Redo:"Ribëj","Remove color":"","Resize image":"","Resize image to %0":"","Resize image to the original size":"","Rich Text Editor":"Redaktues i Tekstit të Pasur","Rich Text Editor, %0":"Redaktues i Tekstit të Pasur, %0","Right aligned image":"Foto e vendosur djathtas",Row:"Rreshti",Save:"Ruaj","Select column":"","Select row":"","Show more items":"","Side image":"Foto anësore","Split cell horizontally":"Ndaj kutizat horizontalisht","Split cell vertically":"Ndajë kutizat vertikalisht",Square:"",Strikethrough:"Vi në mes",Subscript:"",Superscript:"","Table toolbar":"","Text alternative":"Teksti zgjedhor","The URL must not be empty.":"URL nuk duhet të jetë e zbrazët.","This link has no URL":"Kjo nyje nuk ka URL","This media URL is not supported.":"URL e medies nuk mbështetet.","Tip: Paste the URL into the content to embed faster.":"","Toggle the circle list style":"","Toggle the decimal list style":"","Toggle the decimal with leading zero list style":"","Toggle the disc list style":"","Toggle the lower–latin list style":"","Toggle the lower–roman list style":"","Toggle the square list style":"","Toggle the upper–latin list style":"","Toggle the upper–roman list style":"",Turquoise:"",Underline:"Nënvizuar",Undo:"Rikthe",Unlink:"Largo nyjën",Update:"","Update image URL":"","Upload failed":"Ngarkimi dështoi","Upload in progress":"Duke ngarkuar","Upper-latin":"","Upper-roman":"",White:"",Yellow:""}),t.getPluralForm=function(e){return 1!=e}}(window.CKEDITOR_TRANSLATIONS||(window.CKEDITOR_TRANSLATIONS={}));
/* * need some technic to define cardinality */ var cfg = [ { id: 'req', name: 'Requirement', parent: null, values: null, action: null }, { id: 'simpleReq', name: 'Simple Requirement', parent: ['req', 'complexReq'], values: null, action: null }, { id: 'complexReq', name: 'Complex Requirement', parent: ['req', 'complexReq'], action: null, values: null }, { id: 'comp', name: 'Comparison', parent: ['complexReq', 'simpleCond', 'simpleExpr'], action: 'dropdown', values: ['>', '<', '>=', '<=', '='] }, { id: 'expr', name: 'Expression', parent: ['simpleReq'], action: null, values: null }, { id: 'simpleExpr', name: 'Simple Expression', parent: ['expr', 'simpleCond'], action: null, values: null }, { id: 'complexExpr', name: 'Complex Expression', parent: ['expr'], action: null, values: null }, { id: 'const', name: 'Constant', parent: ['simpleExpr'], action: 'input', values: null }, { id: 'qualData', name: 'Qualifying Data', parent: ['simpleExpr', 'object'], action: 'input', values: null }, { id: 'quanData', name: 'Quantifying Data', parent: ['object'], action: 'input', values: null }, { id: 'arithOper', name: 'Arithmetical Operator', parent: ['complexExpr', 'complexReq'], action: 'dropdown', values: ['+', '-', '*', '/'] }, { id: 'operation', name: 'Operation', parent: ['simpleReq'], action: null, values: null }, { id: 'action', name: 'Action', parent: ['operation'], action: null, values: null }, { id: 'aggr', name: 'Aggregation', parent: ['action'], action: 'dropdown', values: ['count', 'sum', 'avarage'] }, { id: 'refin', name: 'Refinement', parent: ['action'], action: 'dropdown', values: ['show'] }, { id: 'object', name: 'Object', parent: ['simpleReq', 'operation'], action: null, values: null }, { id: 'typifiedCond', name: 'Typified Condition', parent: ['simpleReq'], action: null, values: null }, { id: 'condType', name: 'Condition Type', parent: ['typifiedCond'], action: 'dropdown', values: ['where'] }, { id: 'complexCond', name: 'Complex Condition', parent: ['condition'], action: null, values: null }, { id: 'simpleCond', name: 'Simple Condition', parent: ['complexCond', 'condition'], action: null, values: null }, { id: 'logicalOper', name: 'Logical Operator', parent: ['complexCond'], action: 'dropdown', values: ['or', 'and', 'not'] }, { id: 'condition', name: 'Condition', parent: ['typifiedCond', 'complexCond'], action: null, values: null } ];
import * as fcl from "@onflow/fcl" import * as t from "@onflow/types" import {invariant} from "@onflow/util-invariant" import {tx} from "src/flow/util/tx" const CODE = fcl.cdc` import FungibleToken from 0xFungibleToken import NonFungibleToken from 0xNonFungibleToken import FlowToken from 0xFlowToken import KittyItems from 0xKittyItems import NFTStorefront from 0xNFTStorefront pub fun getOrCreateCollection(account: AuthAccount): &KittyItems.Collection{NonFungibleToken.Receiver} { if let collectionRef = account.borrow<&KittyItems.Collection>(from: KittyItems.CollectionStoragePath) { return collectionRef } // create a new empty collection let collection <- KittyItems.createEmptyCollection() as! @KittyItems.Collection let collectionRef = &collection as &KittyItems.Collection // save it to the account account.save(<-collection, to: KittyItems.CollectionStoragePath) // create a public capability for the collection account.link<&KittyItems.Collection{NonFungibleToken.CollectionPublic, KittyItems.KittyItemsCollectionPublic}>(KittyItems.CollectionPublicPath, target: KittyItems.CollectionStoragePath) return collectionRef } transaction(listingResourceID: UInt64, storefrontAddress: Address) { let paymentVault: @FungibleToken.Vault let kittyItemsCollection: &KittyItems.Collection{NonFungibleToken.Receiver} let storefront: &NFTStorefront.Storefront{NFTStorefront.StorefrontPublic} let listing: &NFTStorefront.Listing{NFTStorefront.ListingPublic} prepare(account: AuthAccount) { self.storefront = getAccount(storefrontAddress) .getCapability<&NFTStorefront.Storefront{NFTStorefront.StorefrontPublic}>( NFTStorefront.StorefrontPublicPath )! .borrow() ?? panic("Could not borrow Storefront from provided address") self.listing = self.storefront.borrowListing(listingResourceID: listingResourceID) ?? panic("No Listing with that ID in Storefront") let price = self.listing.getDetails().salePrice let mainFLOWVault = account.borrow<&FlowToken.Vault>(from: /storage/flowTokenVault) ?? panic("Cannot borrow FLOW vault from account storage") self.paymentVault <- mainFLOWVault.withdraw(amount: price) self.kittyItemsCollection = getOrCreateCollection(account: account) } execute { let item <- self.listing.purchase( payment: <-self.paymentVault ) self.kittyItemsCollection.deposit(token: <-item) self.storefront.cleanup(listingResourceID: listingResourceID) } } ` // prettier-ignore export function purchaseListing({itemID, ownerAddress}, opts = {}) { invariant(itemID != null, "buyMarketItem({itemID, ownerAddress}) -- itemID required") invariant(ownerAddress != null, "buyMarketItem({itemID, ownerAddress}) -- ownerAddress required") return tx([ fcl.transaction(CODE), fcl.args([ fcl.arg(Number(itemID), t.UInt64), fcl.arg(String(ownerAddress), t.Address), ]), fcl.proposer(fcl.authz), fcl.payer(fcl.authz), fcl.authorizations([fcl.authz]), fcl.limit(1000), ], opts) }
import React from 'react' function UserCreateBreadcrumb() { return ( <div> <nav class="flex py-3 px-5 text-gray-700 bg-gray-50 rounded-lg border border-gray-200 dark:bg-gray-800 dark:border-gray-700" aria-label="Breadcrumb"> <ol class="inline-flex items-center space-x-1 md:space-x-3"> <li class="inline-flex items-center"> <a href="#" class="inline-flex items-center text-sm text-gray-700 hover:text-gray-900 dark:text-gray-400 dark:hover:text-white"> <svg class="mr-2 w-4 h-4" fill="currentColor" viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg"><path d="M10.707 2.293a1 1 0 00-1.414 0l-7 7a1 1 0 001.414 1.414L4 10.414V17a1 1 0 001 1h2a1 1 0 001-1v-2a1 1 0 011-1h2a1 1 0 011 1v2a1 1 0 001 1h2a1 1 0 001-1v-6.586l.293.293a1 1 0 001.414-1.414l-7-7z"></path></svg> Home </a> </li> <li> <div class="flex items-center"> <svg class="w-6 h-6 text-gray-400" fill="currentColor" viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg"><path fill-rule="evenodd" d="M7.293 14.707a1 1 0 010-1.414L10.586 10 7.293 6.707a1 1 0 011.414-1.414l4 4a1 1 0 010 1.414l-4 4a1 1 0 01-1.414 0z" clip-rule="evenodd"></path></svg> <a href="#" class="ml-1 text-sm font-medium text-gray-700 hover:text-gray-900 md:ml-2 dark:text-gray-400 dark:hover:text-white">Templates</a> </div> </li> <li aria-current="page"> <div class="flex items-center"> <svg class="w-6 h-6 text-gray-400" fill="currentColor" viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg"><path fill-rule="evenodd" d="M7.293 14.707a1 1 0 010-1.414L10.586 10 7.293 6.707a1 1 0 011.414-1.414l4 4a1 1 0 010 1.414l-4 4a1 1 0 01-1.414 0z" clip-rule="evenodd"></path></svg> <span class="ml-1 text-sm font-medium text-gray-400 md:ml-2 dark:text-gray-500">FlowBite</span> </div> </li> </ol> </nav> </div> ) } export default UserCreateBreadcrumb
/* * Copyright 2019 Imaginary Sense <support@imaginary.tech> * Copyright 2019 Kevin J. Ponce García <kevin@imaginary.tech> * Copyright 2019 Javier O. Cordero Pérez <javier@imaginary.tech> * * 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 */ var express = require('express'); var router = express.Router(); /* GET home page. */ router.get('/', function(req, res, next) { res.render('index', { title: 'Express' }); }); module.exports = router;
var searchData= [ ['capabilities',['Capabilities',['../structpvr_1_1platform_1_1_shell_o_s_1_1_capabilities.html',1,'pvr::platform::ShellOS']]], ['commandlineparser',['CommandLineParser',['../classpvr_1_1platform_1_1_command_line_parser.html',1,'pvr::platform']]] ];
from django.conf import settings from django_elasticsearch_dsl import Document, Index, fields from hierarchy.models import Chapter from search.documents.util import html_strip alias = settings.ELASTICSEARCH_INDEX_NAMES[__name__] INDEX = Index(alias) # See Elasticsearch Indices API reference for available settings INDEX.settings(number_of_shards=1, number_of_replicas=0) @INDEX.doc_type class ChapterDocument(Document): """ Chapter elasticsearch document """ class Django: model = Chapter id = fields.IntegerField(attr="goods_nomenclature_sid") nomenclature_tree_id = fields.IntegerField(attr="nomenclature_tree_id") commodity_code = fields.KeywordField(attr="chapter_code") description = fields.TextField(analyzer=html_strip) keywords = fields.TextField(analyzer=html_strip) hierarchy_context = fields.TextField(attr="ancestor_data") node_id = fields.TextField(attr="hierarchy_key") ranking = fields.IntegerField() leaf = fields.BooleanField(attr="leaf")
/*! * Copyright 2019 Hitachi Vantara. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ define([ "angular", "./s3.config", "./components/step1/step1.component", "pentaho/i18n-osgi!pentaho-s3.messages" ], function(angular, config, step1Component, i18n) { "use strict"; function mask(value) { var password = ""; for (var i = 0; i < value.length; i++) { password += "*"; } return password; } var module = { name: "pentaho-s3-plugin", scheme: "s3n", label: "Amazon S3", summary: [{ title: i18n.get('Connection.Label.ConnectionDetails'), editLink: "s3nstep1", mapping: { "accessKey": i18n.get('S3.Label.AccessKey'), "secretKey": i18n.get('S3.Label.SecretKey') }, filters: { "accessKey": mask, "secretKey": mask } }] }; activate(); return module; /** * Creates angular module with dependencies. * * @private */ function activate() { angular.module(module.name, []) .component(step1Component.name, step1Component.options) .config(config); } });
import React, { useState, useEffect, useContext } from 'react'; import { makeStyles } from '@material-ui/styles'; import clsx from 'clsx'; import Card from '@material-ui/core/Card'; import CardHeader from '@material-ui/core/CardHeader'; import CardMedia from '@material-ui/core/CardMedia'; import CardContent from '@material-ui/core/CardContent'; import CardActions from '@material-ui/core/CardActions'; import Collapse from '@material-ui/core/Collapse'; import Avatar from '@material-ui/core/Avatar'; import IconButton from '@material-ui/core/IconButton'; import Typography from '@material-ui/core/Typography'; import { red } from '@material-ui/core/colors'; import FavoriteIcon from '@material-ui/icons/Favorite'; import ShareIcon from '@material-ui/icons/Share'; import ExpandMoreIcon from '@material-ui/icons/ExpandMore'; import MoreVertIcon from '@material-ui/icons/MoreVert'; import { getDogPic, getFavByUserIdAndPostId, apiAddFav, apiremoveFav } from '../../api'; import { AuthContext } from '../../AuthContext'; const useStyles = makeStyles((theme) => ({ root: { maxWidth: 345 }, media: { height: 0, paddingTop: '56.25%' // 16:9 }, expandOpen: { transform: 'rotate(180deg)' }, avatar: { backgroundColor: red[500] } })); export default function PostCard({ post, setFavourites }) { const { user, setIsAuth } = useContext(AuthContext); const classes = useStyles(); const [dogImg, setDogImg] = useState( 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAARMAAAC3CAMAAAAGjUrGAAAAMFBMVEXY2Nj//v/d3d3V1dX8/PzZ2dn29fbz8vP5+Pnj4+Pt7O3s7Ozg4OD6+frm5ubh4eFQNqrCAAAFkklEQVR4nO2ciY6sIBBFEUTc2v7/vx2XaVmkFRdaKt6TTDLmTXx6uzaKohkHLgwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgAVCMCmZuPsxEkLwusyzLC8aCVlGBC+ymfrup0kC0WUmL3n3A92PI0kPRti5KwlEYeVSk/zZ7iPUQpE+AxWPyz59LdL/jLQeK8l6mepnicLruumaulaqeHkE6Wn6n+rux/wlIvcLYVAM5cqTQoonzSxCbD0I8yDvabc1yarRg54jSoCdTJo8qEoRvkzjajLGnNdjDMVTkCw1mXR7TELeoUnW3v2wPyJIk8/fPCQhi2Zbk/bTTykf4j2L1sASPsdh9QxRAgoUpmvdyFVKKhFrU5KX+SdRRekSWVZtB1ll1XURM7IoU6kLN52nskNOES378CzWnfeyaSiLP+jimEr//yST7OV6u0At2wmvLsZ2WO+i19/0KNxY8yz14ZVXqepqWUSR1pKqqpVSdffmkrmiFKLwaTL8S8ev1KVKbUU1dmOHXxa9A77WTciL5i2ZuOJVZJZsh9NVoPlqJqYwvYWxk9Ik3OB0MnMpvNHEx6tQdTVKc0CbMbelunJwNJEiVJLZakrVdK2cnTGIaSWaSmXvYvsO3/acNbPp2jCHmiRJtw1u5p1W1EclmaVR3eYMy3+/IpXCfoHRT8n5eUlGyvXRnv86Oa1EbDGLothFkow3e397Y8Gn7cdUA+yIaFXemzwX8nAs8VFW3pf+jLu8fv2aOxFsGO8L6dTuU4UvVBGfZQWVaaiQLcJ9OMNxQn78lIok7Hge/srLMBUh53AVryVzOe/LNdG9F8F1gqO0FR2yb7qbIeUK2Rk26A++qRK81tklCjcFoeQ3I+LL5NJ15LSMZCBgQ+wUkTq7UQmY7DpOTlERFtNQCnpe88/u9kkYeU34wEfI2MERTe5+r3NE0STlxsA2kQwlod2tA8g4mtA2lOsaSyY5ZU1iRZRUm/RBRIoolBbDHqIUs8SdJ0YfJdmN0EAu78yOJLphHkyMngHpbMzCTm/sJd2t0EAihNmkhpIOECOiEF8HMhajmL37nc4SIx3f/U5nibESpF2gsChBNtl5k0D275OWaisuk9dkX+JRlRRiy9/ufqfT7Fgcq2oaYtvqvNz9SqcJ3SYtzFH89SB049tcQ0h1X9bOEP7q7hD5ms2bjMvP0jB/Fd65z9XBBOq1PfP6wTi3N1YZ3+aDV63rl08fB0+7YHu1v9q37H7x2FHxaBKy2l8Js+RPK/uKtpAoueY9ZHfR//EWsgGV6GqRQryS9RayIS3VtVUBmRFQP15Nwr4MciWk5C1l9/F+3GH7VqsJWS2Hq8ng1STw3MB6QyrgMEuq+LYzAlvvm+fnisjPHgsdFfRvoRXG8rtGHVI/leFHr3eU9qLgqmvbUii6jw6Una44witRsdXkprgrqK2f61/3VOd8Y3+VXv2my5PS+Mj3Wbxd0ea1XfEQ9J45sHZCu9G+M3yitaq31gky5AaX9JkvaYSW3UHANI3eMKwTh0kfkvSgXad/ciPc7r6P6T9yeU0JLQM3bWZ/XDQrlYbZotDqMenCfjDw+bWOdJkNEcaoanTiSDmP8eFyV6D9N5vdcJJU347S1J8hybAQPhFORnRFzL3XBBCGtY+fpK69Dt5wvt/UktKG877uqaNSmZmhFbI7/T2Huuab7EyXKSSCrFNV1fb69ljuNMyuGa/1PUloYktS2JIcW7WZPczB0Kzrq58/BlYt3i/4zMtjLQ9rE6zXxCraKKyNK1sD20yOJQlr27kRdq+WwrEE8zMtnEL84DlYa6+0dnZ/KPhOl+Uf1HDdzNeHc06Ra/qY6l4TQGic6wvuON7EvQYAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAj4YDlz/40zAUTCs5iAAAAABJRU5ErkJggg==' ); useEffect(() => { getDogPic().then((res) => { setDogImg(res.data.message); }); }, []); return ( <Card className={classes.root}> <CardHeader avatar={ <Avatar aria-label="recipe" className={classes.avatar}> {post.name.charAt(0)} </Avatar> } action={ <IconButton aria-label="settings"> <MoreVertIcon /> </IconButton> } title={`${post.name}, ${post.age}`} subheader={new Date(post.created_at).toDateString()} /> <CardMedia className={classes.media} image={dogImg} title={post.name} /> <CardContent> <Typography variant="body2" color="textSecondary" component="p"> {post.title} </Typography> <Typography variant="body2" color="textSecondary" component="p"> Energy: {post.energy} </Typography> <Typography variant="body2" color="textSecondary" component="p"> Aggression: {post.aggression} </Typography> <Typography variant="body2" color="textSecondary" component="p"> Maintenance: {post.maintenance} </Typography> </CardContent> <CardActions disableSpacing> {/* <IconButton aria-label="share"> <ShareIcon /> </IconButton> */} </CardActions> </Card> ); }
!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports,require("lit-element/lit-element.js"),require("@lrnwebcomponents/utils/utils.js"),require("@lrnwebcomponents/es-global-bridge/es-global-bridge.js")):"function"==typeof define&&define.amd?define(["exports","lit-element/lit-element.js","@lrnwebcomponents/utils/utils.js","@lrnwebcomponents/es-global-bridge/es-global-bridge.js"],e):e((t=t||self).ChartistRender={},t.litElement_js,t.utils_js)}(this,function(t,e,n){"use strict";function i(t){return(i="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t})(t)}function s(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function c(t,e){for(var n=0;n<e.length;n++){var i=e[n];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(t,i.key,i)}}function r(t,e,n){return e in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function o(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(t);e&&(i=i.filter(function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable})),n.push.apply(n,i)}return n}function l(t){for(var e=1;e<arguments.length;e++){var n=null!=arguments[e]?arguments[e]:{};e%2?o(Object(n),!0).forEach(function(e){r(t,e,n[e])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):o(Object(n)).forEach(function(e){Object.defineProperty(t,e,Object.getOwnPropertyDescriptor(n,e))})}return t}function a(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function");t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:!0,configurable:!0}}),e&&h(t,e)}function d(t){return(d=Object.setPrototypeOf?Object.getPrototypeOf:function(t){return t.__proto__||Object.getPrototypeOf(t)})(t)}function h(t,e){return(h=Object.setPrototypeOf||function(t,e){return t.__proto__=e,t})(t,e)}function f(t){if(void 0===t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return t}function p(t){var e=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){})),!0}catch(t){return!1}}();return function(){var n,i,s,c=d(t);if(e){var r=d(this).constructor;n=Reflect.construct(c,arguments,r)}else n=c.apply(this,arguments);return i=this,!(s=n)||"object"!=typeof s&&"function"!=typeof s?f(i):s}}function b(t,e,n){return(b="undefined"!=typeof Reflect&&Reflect.get?Reflect.get:function(t,e,n){var i=function(t,e){for(;!Object.prototype.hasOwnProperty.call(t,e)&&null!==(t=d(t)););return t}(t,e);if(i){var s=Object.getOwnPropertyDescriptor(i,e);return s.get?s.get.call(n):s.value}})(t,e,n||t)}function u(t,e){return e||(e=t.slice(0)),Object.freeze(Object.defineProperties(t,{raw:{value:Object.freeze(e)}}))}var g,y,m=function(t){return function(r){a(k,t);var o,h,m,v=p(k);function k(){var t;return s(this,k),(t=v.call(this)).id="chart",t.type="bar",t.scale="ct-minor-seventh",t.responsiveOptions=[],t.data=[],t.dataSource="",t.showTable=!1,t.__chartId=n.generateResourceID("chart-"),window.ESGlobalBridge.requestAvailability(),t._loadScripts("chartistLib","lib/chartist/dist/chartist.min.js",t._chartistLoaded),t._updateData(),t.observer.observe(f(t),{attributes:!1,childList:!0,subtree:!0}),t.dispatchEvent(new CustomEvent("chartist-render-ready",{bubbles:!0,cancelable:!0,composed:!0,detail:f(t)})),"object"===("undefined"==typeof Chartist?"undefined":i(Chartist))&&t._chartistLoaded.bind(f(t)),t}return o=k,m=[{key:"styles",get:function(){return[e.css(y||(y=u(['\n.ct-label {\n fill: rgba(0, 0, 0, 0.4);\n color: rgba(0, 0, 0, 0.4);\n font-size: 0.75rem;\n line-height: 1; }\n\n.ct-chart-line .ct-label,\n.ct-chart-bar .ct-label {\n display: block;\n display: -webkit-box;\n display: -moz-box;\n display: -ms-flexbox;\n display: -webkit-flex;\n display: flex; }\n\n.ct-chart-pie .ct-label,\n.ct-chart-donut .ct-label {\n dominant-baseline: central; }\n\n.ct-label.ct-horizontal.ct-start {\n -webkit-box-align: flex-end;\n -webkit-align-items: flex-end;\n -ms-flex-align: flex-end;\n align-items: flex-end;\n -webkit-box-pack: flex-start;\n -webkit-justify-content: flex-start;\n -ms-flex-pack: flex-start;\n justify-content: flex-start;\n text-align: left;\n text-anchor: start; }\n\n.ct-label.ct-horizontal.ct-end {\n -webkit-box-align: flex-start;\n -webkit-align-items: flex-start;\n -ms-flex-align: flex-start;\n align-items: flex-start;\n -webkit-box-pack: flex-start;\n -webkit-justify-content: flex-start;\n -ms-flex-pack: flex-start;\n justify-content: flex-start;\n text-align: left;\n text-anchor: start; }\n\n.ct-label.ct-vertical.ct-start {\n -webkit-box-align: flex-end;\n -webkit-align-items: flex-end;\n -ms-flex-align: flex-end;\n align-items: flex-end;\n -webkit-box-pack: flex-end;\n -webkit-justify-content: flex-end;\n -ms-flex-pack: flex-end;\n justify-content: flex-end;\n text-align: right;\n text-anchor: end; }\n\n.ct-label.ct-vertical.ct-end {\n -webkit-box-align: flex-end;\n -webkit-align-items: flex-end;\n -ms-flex-align: flex-end;\n align-items: flex-end;\n -webkit-box-pack: flex-start;\n -webkit-justify-content: flex-start;\n -ms-flex-pack: flex-start;\n justify-content: flex-start;\n text-align: left;\n text-anchor: start; }\n\n.ct-chart-bar .ct-label.ct-horizontal.ct-start {\n -webkit-box-align: flex-end;\n -webkit-align-items: flex-end;\n -ms-flex-align: flex-end;\n align-items: flex-end;\n -webkit-box-pack: center;\n -webkit-justify-content: center;\n -ms-flex-pack: center;\n justify-content: center;\n text-align: center;\n text-anchor: start; }\n\n.ct-chart-bar .ct-label.ct-horizontal.ct-end {\n -webkit-box-align: flex-start;\n -webkit-align-items: flex-start;\n -ms-flex-align: flex-start;\n align-items: flex-start;\n -webkit-box-pack: center;\n -webkit-justify-content: center;\n -ms-flex-pack: center;\n justify-content: center;\n text-align: center;\n text-anchor: start; }\n\n.ct-chart-bar.ct-horizontal-bars .ct-label.ct-horizontal.ct-start {\n -webkit-box-align: flex-end;\n -webkit-align-items: flex-end;\n -ms-flex-align: flex-end;\n align-items: flex-end;\n -webkit-box-pack: flex-start;\n -webkit-justify-content: flex-start;\n -ms-flex-pack: flex-start;\n justify-content: flex-start;\n text-align: left;\n text-anchor: start; }\n\n.ct-chart-bar.ct-horizontal-bars .ct-label.ct-horizontal.ct-end {\n -webkit-box-align: flex-start;\n -webkit-align-items: flex-start;\n -ms-flex-align: flex-start;\n align-items: flex-start;\n -webkit-box-pack: flex-start;\n -webkit-justify-content: flex-start;\n -ms-flex-pack: flex-start;\n justify-content: flex-start;\n text-align: left;\n text-anchor: start; }\n\n.ct-chart-bar.ct-horizontal-bars .ct-label.ct-vertical.ct-start {\n -webkit-box-align: center;\n -webkit-align-items: center;\n -ms-flex-align: center;\n align-items: center;\n -webkit-box-pack: flex-end;\n -webkit-justify-content: flex-end;\n -ms-flex-pack: flex-end;\n justify-content: flex-end;\n text-align: right;\n text-anchor: end; }\n\n.ct-chart-bar.ct-horizontal-bars .ct-label.ct-vertical.ct-end {\n -webkit-box-align: center;\n -webkit-align-items: center;\n -ms-flex-align: center;\n align-items: center;\n -webkit-box-pack: flex-start;\n -webkit-justify-content: flex-start;\n -ms-flex-pack: flex-start;\n justify-content: flex-start;\n text-align: left;\n text-anchor: end; }\n\n.ct-grid {\n stroke: rgba(0, 0, 0, 0.2);\n stroke-width: 1px;\n stroke-dasharray: 2px; }\n\n.ct-grid-background {\n fill: none; }\n\n.ct-point {\n stroke-width: 10px;\n stroke-linecap: round; }\n\n.ct-line {\n fill: none;\n stroke-width: 4px; }\n\n.ct-area {\n stroke: none;\n fill-opacity: 0.1; }\n\n.ct-bar {\n fill: none;\n stroke-width: 10px; }\n\n.ct-slice-donut {\n fill: none;\n stroke-width: 60px; }\n\n.ct-series-a .ct-point, .ct-series-a .ct-line, .ct-series-a .ct-bar, .ct-series-a .ct-slice-donut {\n stroke: #d70206; }\n\n.ct-series-a .ct-slice-pie, .ct-series-a .ct-slice-donut-solid, .ct-series-a .ct-area {\n fill: #d70206; }\n\n.ct-series-b .ct-point, .ct-series-b .ct-line, .ct-series-b .ct-bar, .ct-series-b .ct-slice-donut {\n stroke: #f05b4f; }\n\n.ct-series-b .ct-slice-pie, .ct-series-b .ct-slice-donut-solid, .ct-series-b .ct-area {\n fill: #f05b4f; }\n\n.ct-series-c .ct-point, .ct-series-c .ct-line, .ct-series-c .ct-bar, .ct-series-c .ct-slice-donut {\n stroke: #f4c63d; }\n\n.ct-series-c .ct-slice-pie, .ct-series-c .ct-slice-donut-solid, .ct-series-c .ct-area {\n fill: #f4c63d; }\n\n.ct-series-d .ct-point, .ct-series-d .ct-line, .ct-series-d .ct-bar, .ct-series-d .ct-slice-donut {\n stroke: #d17905; }\n\n.ct-series-d .ct-slice-pie, .ct-series-d .ct-slice-donut-solid, .ct-series-d .ct-area {\n fill: #d17905; }\n\n.ct-series-e .ct-point, .ct-series-e .ct-line, .ct-series-e .ct-bar, .ct-series-e .ct-slice-donut {\n stroke: #453d3f; }\n\n.ct-series-e .ct-slice-pie, .ct-series-e .ct-slice-donut-solid, .ct-series-e .ct-area {\n fill: #453d3f; }\n\n.ct-series-f .ct-point, .ct-series-f .ct-line, .ct-series-f .ct-bar, .ct-series-f .ct-slice-donut {\n stroke: #59922b; }\n\n.ct-series-f .ct-slice-pie, .ct-series-f .ct-slice-donut-solid, .ct-series-f .ct-area {\n fill: #59922b; }\n\n.ct-series-g .ct-point, .ct-series-g .ct-line, .ct-series-g .ct-bar, .ct-series-g .ct-slice-donut {\n stroke: #0544d3; }\n\n.ct-series-g .ct-slice-pie, .ct-series-g .ct-slice-donut-solid, .ct-series-g .ct-area {\n fill: #0544d3; }\n\n.ct-series-h .ct-point, .ct-series-h .ct-line, .ct-series-h .ct-bar, .ct-series-h .ct-slice-donut {\n stroke: #6b0392; }\n\n.ct-series-h .ct-slice-pie, .ct-series-h .ct-slice-donut-solid, .ct-series-h .ct-area {\n fill: #6b0392; }\n\n.ct-series-i .ct-point, .ct-series-i .ct-line, .ct-series-i .ct-bar, .ct-series-i .ct-slice-donut {\n stroke: #f05b4f; }\n\n.ct-series-i .ct-slice-pie, .ct-series-i .ct-slice-donut-solid, .ct-series-i .ct-area {\n fill: #f05b4f; }\n\n.ct-series-j .ct-point, .ct-series-j .ct-line, .ct-series-j .ct-bar, .ct-series-j .ct-slice-donut {\n stroke: #dda458; }\n\n.ct-series-j .ct-slice-pie, .ct-series-j .ct-slice-donut-solid, .ct-series-j .ct-area {\n fill: #dda458; }\n\n.ct-series-k .ct-point, .ct-series-k .ct-line, .ct-series-k .ct-bar, .ct-series-k .ct-slice-donut {\n stroke: #eacf7d; }\n\n.ct-series-k .ct-slice-pie, .ct-series-k .ct-slice-donut-solid, .ct-series-k .ct-area {\n fill: #eacf7d; }\n\n.ct-series-l .ct-point, .ct-series-l .ct-line, .ct-series-l .ct-bar, .ct-series-l .ct-slice-donut {\n stroke: #86797d; }\n\n.ct-series-l .ct-slice-pie, .ct-series-l .ct-slice-donut-solid, .ct-series-l .ct-area {\n fill: #86797d; }\n\n.ct-series-m .ct-point, .ct-series-m .ct-line, .ct-series-m .ct-bar, .ct-series-m .ct-slice-donut {\n stroke: #b2c326; }\n\n.ct-series-m .ct-slice-pie, .ct-series-m .ct-slice-donut-solid, .ct-series-m .ct-area {\n fill: #b2c326; }\n\n.ct-series-n .ct-point, .ct-series-n .ct-line, .ct-series-n .ct-bar, .ct-series-n .ct-slice-donut {\n stroke: #6188e2; }\n\n.ct-series-n .ct-slice-pie, .ct-series-n .ct-slice-donut-solid, .ct-series-n .ct-area {\n fill: #6188e2; }\n\n.ct-series-o .ct-point, .ct-series-o .ct-line, .ct-series-o .ct-bar, .ct-series-o .ct-slice-donut {\n stroke: #a748ca; }\n\n.ct-series-o .ct-slice-pie, .ct-series-o .ct-slice-donut-solid, .ct-series-o .ct-area {\n fill: #a748ca; }\n\n.ct-square {\n display: block;\n position: relative;\n width: 100%; }\n .ct-square:before {\n display: block;\n float: left;\n content: "";\n width: 0;\n height: 0;\n padding-bottom: 100%; }\n .ct-square:after {\n content: "";\n display: table;\n clear: both; }\n .ct-square > svg {\n display: block;\n position: absolute;\n top: 0;\n left: 0; }\n\n.ct-minor-second {\n display: block;\n position: relative;\n width: 100%; }\n .ct-minor-second:before {\n display: block;\n float: left;\n content: "";\n width: 0;\n height: 0;\n padding-bottom: 93.75%; }\n .ct-minor-second:after {\n content: "";\n display: table;\n clear: both; }\n .ct-minor-second > svg {\n display: block;\n position: absolute;\n top: 0;\n left: 0; }\n\n.ct-major-second {\n display: block;\n position: relative;\n width: 100%; }\n .ct-major-second:before {\n display: block;\n float: left;\n content: "";\n width: 0;\n height: 0;\n padding-bottom: 88.88889%; }\n .ct-major-second:after {\n content: "";\n display: table;\n clear: both; }\n .ct-major-second > svg {\n display: block;\n position: absolute;\n top: 0;\n left: 0; }\n\n.ct-minor-third {\n display: block;\n position: relative;\n width: 100%; }\n .ct-minor-third:before {\n display: block;\n float: left;\n content: "";\n width: 0;\n height: 0;\n padding-bottom: 83.33333%; }\n .ct-minor-third:after {\n content: "";\n display: table;\n clear: both; }\n .ct-minor-third > svg {\n display: block;\n position: absolute;\n top: 0;\n left: 0; }\n\n.ct-major-third {\n display: block;\n position: relative;\n width: 100%; }\n .ct-major-third:before {\n display: block;\n float: left;\n content: "";\n width: 0;\n height: 0;\n padding-bottom: 80%; }\n .ct-major-third:after {\n content: "";\n display: table;\n clear: both; }\n .ct-major-third > svg {\n display: block;\n position: absolute;\n top: 0;\n left: 0; }\n\n.ct-perfect-fourth {\n display: block;\n position: relative;\n width: 100%; }\n .ct-perfect-fourth:before {\n display: block;\n float: left;\n content: "";\n width: 0;\n height: 0;\n padding-bottom: 75%; }\n .ct-perfect-fourth:after {\n content: "";\n display: table;\n clear: both; }\n .ct-perfect-fourth > svg {\n display: block;\n position: absolute;\n top: 0;\n left: 0; }\n\n.ct-perfect-fifth {\n display: block;\n position: relative;\n width: 100%; }\n .ct-perfect-fifth:before {\n display: block;\n float: left;\n content: "";\n width: 0;\n height: 0;\n padding-bottom: 66.66667%; }\n .ct-perfect-fifth:after {\n content: "";\n display: table;\n clear: both; }\n .ct-perfect-fifth > svg {\n display: block;\n position: absolute;\n top: 0;\n left: 0; }\n\n.ct-minor-sixth {\n display: block;\n position: relative;\n width: 100%; }\n .ct-minor-sixth:before {\n display: block;\n float: left;\n content: "";\n width: 0;\n height: 0;\n padding-bottom: 62.5%; }\n .ct-minor-sixth:after {\n content: "";\n display: table;\n clear: both; }\n .ct-minor-sixth > svg {\n display: block;\n position: absolute;\n top: 0;\n left: 0; }\n\n.ct-golden-section {\n display: block;\n position: relative;\n width: 100%; }\n .ct-golden-section:before {\n display: block;\n float: left;\n content: "";\n width: 0;\n height: 0;\n padding-bottom: 61.8047%; }\n .ct-golden-section:after {\n content: "";\n display: table;\n clear: both; }\n .ct-golden-section > svg {\n display: block;\n position: absolute;\n top: 0;\n left: 0; }\n\n.ct-major-sixth {\n display: block;\n position: relative;\n width: 100%; }\n .ct-major-sixth:before {\n display: block;\n float: left;\n content: "";\n width: 0;\n height: 0;\n padding-bottom: 60%; }\n .ct-major-sixth:after {\n content: "";\n display: table;\n clear: both; }\n .ct-major-sixth > svg {\n display: block;\n position: absolute;\n top: 0;\n left: 0; }\n\n.ct-minor-seventh {\n display: block;\n position: relative;\n width: 100%; }\n .ct-minor-seventh:before {\n display: block;\n float: left;\n content: "";\n width: 0;\n height: 0;\n padding-bottom: 56.25%; }\n .ct-minor-seventh:after {\n content: "";\n display: table;\n clear: both; }\n .ct-minor-seventh > svg {\n display: block;\n position: absolute;\n top: 0;\n left: 0; }\n\n.ct-major-seventh {\n display: block;\n position: relative;\n width: 100%; }\n .ct-major-seventh:before {\n display: block;\n float: left;\n content: "";\n width: 0;\n height: 0;\n padding-bottom: 53.33333%; }\n .ct-major-seventh:after {\n content: "";\n display: table;\n clear: both; }\n .ct-major-seventh > svg {\n display: block;\n position: absolute;\n top: 0;\n left: 0; }\n\n.ct-octave {\n display: block;\n position: relative;\n width: 100%; }\n .ct-octave:before {\n display: block;\n float: left;\n content: "";\n width: 0;\n height: 0;\n padding-bottom: 50%; }\n .ct-octave:after {\n content: "";\n display: table;\n clear: both; }\n .ct-octave > svg {\n display: block;\n position: absolute;\n top: 0;\n left: 0; }\n\n.ct-major-tenth {\n display: block;\n position: relative;\n width: 100%; }\n .ct-major-tenth:before {\n display: block;\n float: left;\n content: "";\n width: 0;\n height: 0;\n padding-bottom: 40%; }\n .ct-major-tenth:after {\n content: "";\n display: table;\n clear: both; }\n .ct-major-tenth > svg {\n display: block;\n position: absolute;\n top: 0;\n left: 0; }\n\n.ct-major-eleventh {\n display: block;\n position: relative;\n width: 100%; }\n .ct-major-eleventh:before {\n display: block;\n float: left;\n content: "";\n width: 0;\n height: 0;\n padding-bottom: 37.5%; }\n .ct-major-eleventh:after {\n content: "";\n display: table;\n clear: both; }\n .ct-major-eleventh > svg {\n display: block;\n position: absolute;\n top: 0;\n left: 0; }\n\n.ct-major-twelfth {\n display: block;\n position: relative;\n width: 100%; }\n .ct-major-twelfth:before {\n display: block;\n float: left;\n content: "";\n width: 0;\n height: 0;\n padding-bottom: 33.33333%; }\n .ct-major-twelfth:after {\n content: "";\n display: table;\n clear: both; }\n .ct-major-twelfth > svg {\n display: block;\n position: absolute;\n top: 0;\n left: 0; }\n\n.ct-double-octave {\n display: block;\n position: relative;\n width: 100%; }\n .ct-double-octave:before {\n display: block;\n float: left;\n content: "";\n width: 0;\n height: 0;\n padding-bottom: 25%; }\n .ct-double-octave:after {\n content: "";\n display: table;\n clear: both; }\n .ct-double-octave > svg {\n display: block;\n position: absolute;\n top: 0;\n left: 0; }\n\n:host {\n display: block;\n width: 100%;\n padding: var(--chartist-padding, 0px);\n margin: var(--chartist-margin, 15px 0);\n background-color: var(--chartist-bg-color, transparent);\n color: var(--chartist-text-color, #000); }\n\n.sr-only {\n position: absolute;\n left: -999999px;\n height: 0;\n overflow: hidden; }\n\n.ct-axis-title {\n fill: var(--chartist-text-color); }\n\n::slotted(table) {\n border: 1px solid var(--chartist-text-color);\n border-collapse: collapse;\n width: 100%;\n max-width: 100%;\n overflow: auto; }\n\n.ct-label {\n fill: var(--chartist-text-color, #000);\n color: var(--chartist-text-color, #000);\n font-size: var(--chartist-text-size, 0.75rem);\n line-height: var(--chartist-line-height, 1); }\n\n.ct-grid {\n stroke: var(--chartist-grid-color, rgba(0, 0, 0, 0.2));\n stroke-width: 1px;\n stroke-dasharray: 2px; }\n\n.ct-series-a .ct-point, .ct-series-a .ct-line, .ct-series-a .ct-bar, .ct-series-a .ct-slice-donut {\n stroke: var(--chartist-color-1, #d70206); }\n\n.ct-series-a .ct-slice-pie, .ct-series-a .ct-slice-donut-solid, .ct-series-a .ct-area {\n fill: var(--chartist-color-1, #d70206); }\n\n.ct-series-b .ct-point, .ct-series-b .ct-line, .ct-series-b .ct-bar, .ct-series-b .ct-slice-donut {\n stroke: var(--chartist-color-2, #f05b4f); }\n\n.ct-series-b .ct-slice-pie, .ct-series-b .ct-slice-donut-solid, .ct-series-b .ct-area {\n fill: var(--chartist-color-2, #f05b4f); }\n\n.ct-series-c .ct-point, .ct-series-c .ct-line, .ct-series-c .ct-bar, .ct-series-c .ct-slice-donut {\n stroke: var(--chartist-color-3, #f4c63d); }\n\n.ct-series-c .ct-slice-pie, .ct-series-c .ct-slice-donut-solid, .ct-series-c .ct-area {\n fill: var(--chartist-color-3, #f4c63d); }\n\n.ct-series-d .ct-point, .ct-series-d .ct-line, .ct-series-d .ct-bar, .ct-series-d .ct-slice-donut {\n stroke: var(--chartist-color-4, #d17905); }\n\n.ct-series-d .ct-slice-pie, .ct-series-d .ct-slice-donut-solid, .ct-series-d .ct-area {\n fill: var(--chartist-color-4, #d17905); }\n\n.ct-series-e .ct-point, .ct-series-e .ct-line, .ct-series-e .ct-bar, .ct-series-e .ct-slice-donut {\n stroke: var(--chartist-color-5, #453d3f); }\n\n.ct-series-e .ct-slice-pie, .ct-series-e .ct-slice-donut-solid, .ct-series-e .ct-area {\n fill: var(--chartist-color-5, #453d3f); }\n\n.ct-series-f .ct-point, .ct-series-f .ct-line, .ct-series-f .ct-bar, .ct-series-f .ct-slice-donut {\n stroke: var(--chartist-color-6, #59922b); }\n\n.ct-series-f .ct-slice-pie, .ct-series-f .ct-slice-donut-solid, .ct-series-f .ct-area {\n fill: var(--chartist-color-6, #59922b); }\n\n.ct-series-g .ct-point, .ct-series-g .ct-line, .ct-series-g .ct-bar, .ct-series-g .ct-slice-donut {\n stroke: var(--chartist-color-7, #0544d3); }\n\n.ct-series-g .ct-slice-pie, .ct-series-g .ct-slice-donut-solid, .ct-series-g .ct-area {\n fill: var(--chartist-color-7, #0544d3); }\n\n.ct-series-h .ct-point, .ct-series-h .ct-line, .ct-series-h .ct-bar, .ct-series-h .ct-slice-donut {\n stroke: var(--chartist-color-8, #6b0392); }\n\n.ct-series-h .ct-slice-pie, .ct-series-h .ct-slice-donut-solid, .ct-series-h .ct-area {\n fill: var(--chartist-color-8, #6b0392); }\n\n.ct-series-i .ct-point, .ct-series-i .ct-line, .ct-series-i .ct-bar, .ct-series-i .ct-slice-donut {\n stroke: var(--chartist-color-9, #f05b4f); }\n\n.ct-series-i .ct-slice-pie, .ct-series-i .ct-slice-donut-solid, .ct-series-i .ct-area {\n fill: var(--chartist-color-9, #f05b4f); }\n\n.ct-series-j .ct-point, .ct-series-j .ct-line, .ct-series-j .ct-bar, .ct-series-j .ct-slice-donut {\n stroke: var(--chartist-color-10, #dda458); }\n\n.ct-series-j .ct-slice-pie, .ct-series-j .ct-slice-donut-solid, .ct-series-j .ct-area {\n fill: var(--chartist-color-10, #dda458); }\n\n.ct-series-k .ct-point, .ct-series-k .ct-line, .ct-series-k .ct-bar, .ct-series-k .ct-slice-donut {\n stroke: var(--chartist-color-11, #eacf7d); }\n\n.ct-series-k .ct-slice-pie, .ct-series-k .ct-slice-donut-solid, .ct-series-k .ct-area {\n fill: var(--chartist-color-11, #eacf7d); }\n\n.ct-series-l .ct-point, .ct-series-l .ct-line, .ct-series-l .ct-bar, .ct-series-l .ct-slice-donut {\n stroke: var(--chartist-color-12, #86797d); }\n\n.ct-series-l .ct-slice-pie, .ct-series-l .ct-slice-donut-solid, .ct-series-l .ct-area {\n fill: var(--chartist-color-12, #86797d); }\n\n.ct-series-m .ct-point, .ct-series-m .ct-line, .ct-series-m .ct-bar, .ct-series-m .ct-slice-donut {\n stroke: var(--chartist-color-13, #b2c326); }\n\n.ct-series-m .ct-slice-pie, .ct-series-m .ct-slice-donut-solid, .ct-series-m .ct-area {\n fill: var(--chartist-color-13, #b2c326); }\n\n.ct-series-n .ct-point, .ct-series-n .ct-line, .ct-series-n .ct-bar, .ct-series-n .ct-slice-donut {\n stroke: var(--chartist-color-14, #6188e2); }\n\n.ct-series-n .ct-slice-pie, .ct-series-n .ct-slice-donut-solid, .ct-series-n .ct-area {\n fill: var(--chartist-color-14, #6188e2); }\n\n.ct-series-o .ct-point, .ct-series-o .ct-line, .ct-series-o .ct-bar, .ct-series-o .ct-slice-donut {\n stroke: var(--chartist-color-15, #a748ca); }\n\n.ct-series-o .ct-slice-pie, .ct-series-o .ct-slice-donut-solid, .ct-series-o .ct-area {\n fill: var(--chartist-color-15, #a748ca); }\n '])))]}},{key:"properties",get:function(){return l(l({},b(d(k),"properties",this)),{},{chartTitle:{type:String,attribute:"chart-title"},chartData:{type:Array,attribute:"chart-data"},chartDesc:{type:String,attribute:"chart-desc"},data:{type:Object,attribute:"data"},dataSource:{type:String,attribute:"data-source",reflect:!0},id:{type:String},options:{type:Object},pluginAxisTitle:{type:Object},pluginPointLabels:{type:Object},pluginFillDonutItems:{type:Array},responsiveOptions:{type:Array,attribute:"responsive-options"},scale:{type:String},showTable:{type:Boolean,attribute:"show-table"},type:{type:String}})}},{key:"tag",get:function(){return"chartist-render"}}],(h=[{key:"render",value:function(){return e.html(g||(g=u(['\n\n<div id="','-title" class="title">\n ','\n <slot name="heading"></slot>\n</div>\n<div id="','-desc" class="desc">\n ','\n <slot name="desc"></slot>\n</div>\n<div id="chart" \n chart="','" \n role="presentation"\n aria-labelledby="','-title"\n aria-describedby="',"-table ",'-desc"\n class="ct-chart ','">\n</div>\n<div \n id="','-table" \n class="','">\n <slot></slot>\n</div>'])),this.__chartId,this.chartTitle,this.__chartId,this.chartDesc,this.__chartId,this.__chartId,this.__chartId,this.__chartId,this.scale,this.__chartId,this.showTable?"table":"table sr-only")}},{key:"plugins",get:function(){return[["Chartist.plugins.ctAxisTitle","lib/chartist-plugin-axistitle/dist/chartist-plugin-axistitle.min.js"],["Chartist.plugins.CtPointLabels","lib/chartist-plugin-pointlabels/dist/chartist-plugin-pointlabels.min.js"],["Chartist.plugins.fillDonut","lib/chartist-plugin-fill-donut/dist/chartist-plugin-fill-donut.min.js"]]}},{key:"observer",get:function(){var t=this;return new MutationObserver(function(e,n){return t._updateData(e,n)})}},{key:"updated",value:function(t){var e=this;b(d(k.prototype),"updated",this)&&b(d(k.prototype),"updated",this).call(this,t),t.forEach(function(t,n){"chartData"===n&&JSON.stringify(e.chartData)!==JSON.stringify(t)?(e.dispatchEvent(new CustomEvent("chart-data-changed",{detail:e})),e._getChart()):"dataSource"===n&&e.dataSource!==t?(e.dispatchEvent(new CustomEvent("data-source-changed",{detail:e})),""!==e.dataSource&&fetch(e.dataSource).then(function(t){return t.text()}).then(function(t){return e.data=e._CSVtoArray(t)})):"data"===n&&JSON.stringify(e.data)!==JSON.stringify(t)?(e.dispatchEvent(new CustomEvent("data-changed",{detail:e})),e._renderTable(),e._updateChartData()):e._getChart()})}},{key:"makeChart",value:function(){return this._getChart(),this.chart}},{key:"pathFromUrl",value:function(t){return t.substring(0,t.lastIndexOf("/")+1)}},{key:"disconnectedCallback",value:function(){var t=this;window.removeEventListener("es-bridge-chartistLib-loaded",this._chartistLoaded.bind(this)),this.plugins.forEach(function(e){return window.removeEventListener("es-bridge-".concat(e[0],"-loaded"),t._getChart.bind(t))}),this.observer&&this.observer.disconnect&&this.observer.disconnect(),b(d(k.prototype),"disconnectedCallback",this).call(this)}},{key:"_chartistLoaded",value:function(){var t=this;this.__chartistLoaded=!0,this._getChart(),this.plugins.forEach(function(e){return t._loadScripts(e[0],e[1])})}},{key:"_CSVtoArray",value:function(t){var e,n="",i=[""],s=[i],c=0,r=0,o=!0;for(e in t)'"'===(e=t[e])?(o&&e===n&&(i[c]+=e),o=!o):","===e&&o?(null!==i[c].trim().match(/^\d+$/m)&&(i[c]=parseInt(i[c].trim())),e=i[++c]=""):"\n"===e&&o?("\r"===n&&(i[c]=i[c].slice(0,-1)),null!==i[c].trim().match(/^\d+$/m)&&(i[c]=parseInt(i[c].trim())),i=s[++r]=[e=""],c=0):i[c]+=e,n=e;return null!==i[c].trim().match(/^\d+$/m)&&(i[c]=parseInt(i[c].trim())),s}},{key:"_getUniqueId",value:function(t){return t+Date.now()}},{key:"fullOptions",get:function(){var t=l({},this.options);return Chartist.plugins&&(t.plugins=[],"pie"!==this.type&&this.pluginAxisTitle&&Chartist.plugins.ctAxisTitle&&t.plugins.push(Chartist.plugins.ctAxisTitle(this.pluginAxisTitle)),"line"===this.type&&this.pluginPointLabels&&Chartist.plugins.ctPointLabels&&(this.pluginPointLabels.labelInterpolationFnc||(this.pluginPointLabels.labelInterpolationFnc=Chartist.noop),t.plugins.push(Chartist.plugins.ctPointLabels(this.pluginPointLabels))),"pie"===this.type&&t.donut&&this.pluginFillDonutItems&&Chartist.plugins.fillDonut&&t.plugins.push(Chartist.plugins.fillDonut({items:this.pluginFillDonutItems}))),t}},{key:"_getChart",value:function(){var t=this,e=null,n=this.shadowRoot.querySelector("#chart");null!==n&&"object"===("undefined"==typeof Chartist?"undefined":i(Chartist))&&this.chartData&&("bar"==this.type?(void 0!==this.responsiveOptions&&this.responsiveOptions.length>0&&this.responsiveOptions.forEach(function(t){void 0!==t[1]&&(t[1].axisX&&"noop"==t[1].axisX.labelInterpolationFnc&&(t[1].axisX.labelInterpolationFnc=Chartist.noop),t[1].axisY&&"noop"==t[1].axisY.labelInterpolationFnc&&(t[1].axisY.labelInterpolationFnc=Chartist.noop))}),e=Chartist.Bar(n,this.chartData,this.fullOptions,this.responsiveOptions)):"line"===this.type?e=Chartist.Line(n,this.chartData,this.fullOptions,this.responsiveOptions):"pie"===this.type&&(e=Chartist.Pie(n,{labels:this.chartData.labels||[],series:this.chartData.series||[]},this.fullOptions,this.responsiveOptions)),this.dispatchEvent(new CustomEvent("chartist-render-data",{bubbles:!0,cancelable:!0,composed:!0,detail:e})),e&&(e.on("created",function(e){t.dispatchEvent(new CustomEvent("chartist-render-created",{bubbles:!0,cancelable:!0,composed:!0,detail:e}))}),e.on("draw",function(e){t.dispatchEvent(new CustomEvent("chartist-render-draw",{bubbles:!0,cancelable:!0,composed:!0,detail:e}))}),this.chart=e))}},{key:"_loadScripts",value:function(t,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:this._getChart,i=this.pathFromUrl(decodeURIComponent("undefined"==typeof document?new(require("url").URL)("file:"+__filename).href:document.currentScript&&document.currentScript.src||new URL("chartist-render.umd.js",document.baseURI).href)),s="".concat(i).concat(e);window.addEventListener("es-bridge-".concat(t,"-loaded"),n.bind(this)),window.ESGlobalBridge.instance.load(t,s)}},{key:"_renderTable",value:function(){var t="",e=this.querySelector("table"),n=this.data;if(n){var i=n[1]&&n[1][0]&&isNaN(n[1][0]),s=n[0]&&n[0][i?1:0]&&isNaN(n[0][i?1:0])?{row:i?n[0][0]:void 0,col:i?n[0].slice(1,n[0].length):n[0]}:void 0,c=n.series?n.series:n.slice(s?1:0,n.length).map(function(t){return i?{th:t[0],td:t.slice(1,t.length)}:{td:t}});!s&&n.labels&&(s=n.labels),e=e||document.createElement("table"),s&&(t+="\n <thead><tr>\n ".concat(s.row?'<th scope="row">'.concat(s.row,"</th>"):"","\n ").concat(s.col?s.col.map(function(t){return'<th scope="col">'.concat(t,"</th>")}).join(""):"","\n </tr></thead>")),c.length>0&&(t+="\n <tbody>\n ".concat(c.map(function(t){return"\n <tr>\n ".concat(t.th?'<th scope="row">'.concat(t.th,"</th>"):"","\n ").concat(t.td?t.td.map(function(t){return"<td>".concat(t,"</td>")}).join(""):"","\n </tr>\n ")}).join(""),"\n </tbody>")),e.innerHTML=t,this.appendChild(e)}else e&&(e.innerHTML="")}},{key:"_updateChartData",value:function(){var t=this.data,e=t&&t[1]&&t[1][0]&&isNaN(t[1][0]),n=t&&t[0]&&t[0][e?1:0]&&isNaN(t[0][e?1:0]),i=n?t[0]:void 0,s=n&&t[1]?t.slice(1,t.length):t;e&&(i=i.slice(1,i.length),s=s.map(function(t){return t.slice(1,t.length)})),this.__dataReady=!0,this.chartData={labels:i,series:"pie"===this.type?s[0]:s}}},{key:"_updateData",value:function(t,e){var n=this.querySelector("table"),i=[];n&&n.querySelectorAll("tr").forEach(function(t){var e=[];t.querySelectorAll("th,td").forEach(function(t){var n=t.innerHTML.trim();e.push(isNaN(n)?n:parseInt(n))}),i.push(e)}),JSON.stringify(this.data)!==JSON.stringify(i)&&(this.data=i)}}])&&c(o.prototype,h),m&&c(o,m),k}()},v=function(t){a(i,m(e.LitElement));var n=p(i);function i(){return s(this,i),n.apply(this,arguments)}return i}();window.customElements.define(v.tag,v),t.ChartistRender=v,t.ChartistRenderSuper=m,Object.defineProperty(t,"__esModule",{value:!0})});
/** * Install the plugin if `window.Vue` is available. * * @param {object} VuePlugin Vue-plugin object. */ export function vueUse(VuePlugin) { if (typeof window !== 'undefined' && window.Vue) { window.Vue.use(VuePlugin); } } /** * Register a component as a plugin being loaded, return true if the component * is already registered. * * @param {object} Vue Vue constructor * @param {string} name name of the component * @param {object} definition component definition */ export function registerComponent(Vue, name, definition) { Vue._papercss_vue_components = Vue._papercss_vue_components || {}; const loaded = Vue._papercss_vue_components[name]; if (!loaded && name && definition) { Vue._papercss_vue_components[name] = true; Vue.component(name, definition); } return loaded; }
/* ***** BEGIN LICENSE BLOCK ***** * Distributed under the BSD license: * * Copyright (c) 2010, Ajax.org B.V. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Ajax.org B.V. nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL AJAX.ORG B.V. BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ***** END LICENSE BLOCK ***** */ define(function(require, exports, module) { "use strict"; var oop = require("../../lib/oop"); var Range = require("../../Range").Range; var BaseFoldMode = require("./FoldMode").FoldMode; var FoldMode = exports.FoldMode = function() { }; oop.inherits(FoldMode, BaseFoldMode); (function() { this.foldingStartMarker = /^\s*\[([^\])]*)]\s*(?:$|[;#])/; this.getFoldWidgetRange = function(session, foldStyle, row) { var re = this.foldingStartMarker; var line = session.getLine(row); var m = line.match(re); if (!m) return; var startName = m[1] + "."; var startColumn = line.length; var maxRow = session.getLength(); var startRow = row; var endRow = row; while (++row < maxRow) { line = session.getLine(row); if (/^\s*$/.test(line)) continue; m = line.match(re); if (m && m[1].lastIndexOf(startName, 0) !== 0) break; endRow = row; } if (endRow > startRow) { var endColumn = session.getLine(endRow).length; return new Range(startRow, startColumn, endRow, endColumn); } }; }).call(FoldMode.prototype); });
import React from 'react' import Link from 'gatsby-link' import cx from 'classnames' import { Location } from '@reach/router' import { resolve } from '@reach/router/lib/utils' const NavTab = ({ to, children }) => ( <Location> {({ location }) => ( <li className={cx({ 'is-active': [location.pathname, location.pathname + '/'].includes( resolve(to) ), })} > <Link to={to}>{children}</Link> </li> )} </Location> ) export default NavTab
var searchData= [ ['4_5forganize_2emd_3',['4_Organize.md',['../4__Organize_8md.html',1,'']]] ];
/* -------------------------------------------------------------------------- */ /* Copyright 2002-2019, OpenNebula Project, OpenNebula Systems */ /* */ /* 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. */ /* -------------------------------------------------------------------------- */ define(function(require) { /* DEPENDENCIES */ // require('foundation.tab'); var BaseFormPanel = require('utils/form-panels/form-panel'); var Sunstone = require('sunstone'); var Locale = require('utils/locale'); var Tips = require('utils/tips'); var TemplateUtils = require('utils/template-utils'); var WizardFields = require('utils/wizard-fields'); var VNetsTable = require('tabs/vnets-tab/datatable'); var Utils = require('../utils/common'); /* TEMPLATES */ var TemplateWizardHTML = require('hbs!./create/wizard'); var TemplateAdvancedHTML = require('hbs!./create/advanced'); /* CONSTANTS */ var FORM_PANEL_ID = require('./create/formPanelId'); var TAB_ID = require('../tabId'); /* CONSTRUCTOR */ function FormPanel() { this.formPanelId = FORM_PANEL_ID; this.tabId = TAB_ID; this.actions = { 'create': { 'title': Locale.tr("Create Security Group"), 'buttonText': Locale.tr("Create"), 'resetButton': true }, 'update': { 'title': Locale.tr("Update Security Group"), 'buttonText': Locale.tr("Update"), 'resetButton': false } }; BaseFormPanel.call(this); } FormPanel.FORM_PANEL_ID = FORM_PANEL_ID; FormPanel.prototype = Object.create(BaseFormPanel.prototype); FormPanel.prototype.constructor = FormPanel; FormPanel.prototype.htmlWizard = _htmlWizard; FormPanel.prototype.htmlAdvanced = _htmlAdvanced; FormPanel.prototype.submitWizard = _submitWizard; FormPanel.prototype.submitAdvanced = _submitAdvanced; FormPanel.prototype.onShow = _onShow; FormPanel.prototype.fill = _fill; FormPanel.prototype.setup = _setup; return FormPanel; /* FUNCTION DEFINITIONS */ function _htmlWizard() { var opts = { info: false, select: true }; this.vnetsTable = new VNetsTable("new_sg_rule", opts); return TemplateWizardHTML({ 'formPanelId': this.formPanelId, 'vnetsTableHTML': this.vnetsTable.dataTableHTML }); } function _htmlAdvanced() { return TemplateAdvancedHTML({formPanelId: this.formPanelId}); } function _setup(context) { var that = this; context.off("change", '.security_group_rule_protocol'); context.on("change", '.security_group_rule_protocol', function(){ $('.range_row', context).hide(); $('.range_row input', context).removeAttr('required'); $('.icmp_type_wrapper', context).hide(); $('.icmpv6_type_wrapper', context).hide(); switch ($(this).val()) { case "TCP": case "UDP": $('.range_row', context).show(); $(".range_row select", context).trigger("change"); break; case "ICMP": $('.icmp_type_wrapper', context).show(); break; case "ICMPv6": $('.icmpv6_type_wrapper', context).show(); break; case "IPSEC": case "ALL": break; } }); context.off("change", '.security_group_rule_network_sel'); context.on("change", '.security_group_rule_network_sel', function(){ $('.security_group_rule_network',context).hide(); $('div.security_group_rule_network input',context).removeAttr('required'); that.vnetsTable.idInput().removeAttr("required"); $('.vnet_select',context).hide(); switch ($(this).val()) { case "ANY": break; case "NETWORK": $('.security_group_rule_network',context).show(); $('div.security_group_rule_network input',context).attr('required', ''); break; case "VNET": $('.vnet_select',context).show(); that.vnetsTable.idInput().attr("required", ""); that.vnetsTable.refreshResourceTableSelect(); break; } }); context.off("change", '.security_group_rule_range_sel'); context.on("change", '.security_group_rule_range_sel', function(){ switch ($(this).val()) { case "ALL": $('.security_group_rule_range', context).hide(); $(".security_group_rule_range input", context).removeAttr('required'); break; case "RANGE": $('.security_group_rule_range', context).show(); $(".security_group_rule_range input", context).attr('required', ''); break; } }); $('#rules_form_wizard',context) .off('forminvalid.zf.abide').off('formvalid.zf.abide').off("submit"); Foundation.reInit($('#rules_form_wizard',context)); $('#rules_form_wizard',context) .on('forminvalid.zf.abide', function(ev, frm) { }) .on('formvalid.zf.abide', function(ev, frm) { var rule = {}; rule["PROTOCOL"] = WizardFields.retrieveInput($(".security_group_rule_protocol", context)); rule["RULE_TYPE"] = WizardFields.retrieveInput($(".security_group_rule_type", context)); switch ($('.security_group_rule_range_sel', context).val()) { case "ALL": break; case "RANGE": rule["RANGE"] = WizardFields.retrieveInput($(".security_group_rule_range input", context)); break; } switch ($('.security_group_rule_network_sel', context).val()) { case "ANY": break; case "NETWORK": rule["IP"] = WizardFields.retrieveInput($('#security_group_rule_first_ip', context)); rule["SIZE"] = WizardFields.retrieveInput($('#security_group_rule_size', context)); break; case "VNET": rule["NETWORK_ID"] = that.vnetsTable.retrieveResourceTableSelect(); break; } if (rule["PROTOCOL"] == "ICMP" ){ var icmp_type_val = WizardFields.retrieveInput($(".security_group_rule_icmp_type", context)); if (icmp_type_val != ""){ rule["ICMP_TYPE"] = icmp_type_val; } } if (rule["PROTOCOL"] == "ICMPv6" ){ var icmpv6_type_val = WizardFields.retrieveInput($(".security_group_rule_icmpv6_type", context)); if (icmpv6_type_val != ""){ rule["ICMPv6_TYPE"] = icmpv6_type_val; } } var text = Utils.sgRuleToSt(rule); $(".security_group_rules tbody", context).append( '<tr>\ <td>'+text.PROTOCOL+'</td>\ <td>'+text.RULE_TYPE+'</td>\ <td>'+text.RANGE+'</td>\ <td>'+text.NETWORK+'</td>\ <td>'+text.ICMP_TYPE+'</td>\ <td>'+text.ICMPv6_TYPE+'</td>\ <td>\ <a href="#"><i class="fas fa-times-circle remove-tab"></i></a>\ </td>\ </tr>'); // Add data to tr element $(".security_group_rules tbody", context).children("tr").last().data("rule", rule); // Reset new rule fields $('#new_rule_wizard select option', context).prop('selected', function() { return this.defaultSelected; }); $('#new_rule_wizard select', context).trigger("change"); $('#new_rule_wizard input', context).val(""); that.vnetsTable.resetResourceTableSelect(); }) .on("submit", function(ev) { ev.preventDefault(); }); context.off("click", ".security_group_rules i.remove-tab"); context.on("click", ".security_group_rules i.remove-tab", function(){ var tr = $(this).closest('tr'); tr.remove(); }); this.vnetsTable.initialize(); Tips.setup(); $('#new_rule_wizard select', context).trigger("change"); return false; } function _submitWizard(context) { var name = WizardFields.retrieveInput($('#security_group_name', context)); var description = WizardFields.retrieveInput($('#security_group_description', context)); var rules = []; $(".security_group_rules tbody tr").each(function(){ rules.push($(this).data("rule")); }); var security_group_json = { "NAME" : name, "DESCRIPTION": description, "RULE" : rules }; if (this.action == "create") { security_group_json = { "security_group" : security_group_json }; Sunstone.runAction("SecurityGroup.create",security_group_json); return false; } else if (this.action == "update") { delete security_group_json["NAME"]; Sunstone.runAction( "SecurityGroup.update", this.resourceId, TemplateUtils.templateToString(security_group_json)); return false; } } function _submitAdvanced(context) { if (this.action == "create") { var template = $('textarea#template', context).val(); var security_group_json = {security_group: {security_group_raw: template}}; Sunstone.runAction("SecurityGroup.create",security_group_json); return false; } else if (this.action == "update") { var template_raw = $('textarea#template', context).val(); Sunstone.runAction("SecurityGroup.update", this.resourceId, template_raw); return false; } } function _onShow(context) { this.vnetsTable.refreshResourceTableSelect(); } function _fill(context, element) { var that = this; this.setHeader(element); this.resourceId = element.ID; // Populates the Avanced mode Tab $('#template', context).val(TemplateUtils.templateToString(element.TEMPLATE)); WizardFields.fillInput($('#security_group_name',context), element.NAME); $('#security_group_name',context).prop("disabled", true); WizardFields.fillInput($('#security_group_description', context), element.TEMPLATE.DESCRIPTION ); var rules = element.TEMPLATE.RULE; if (!rules) { //empty rules = []; } else if (rules.constructor != Array) { //>1 rule rules = [rules]; } $.each(rules, function(){ var text = Utils.sgRuleToSt(this); $(".security_group_rules tbody", context).append( '<tr>\ <td>'+text.PROTOCOL+'</td>\ <td>'+text.RULE_TYPE+'</td>\ <td>'+text.RANGE+'</td>\ <td>'+text.NETWORK+'</td>\ <td>'+text.ICMP_TYPE+'</td>\ <td>'+text.ICMPv6_TYPE+'</td>\ <td>\ <a href="#"><i class="fas fa-times-circle remove-tab"></i></a>\ </td>\ </tr>'); $(".security_group_rules tbody", context).children("tr").last().data("rule", this); }); } });
import sinon from 'sinon'; import emptyObj from '../../src/utils/emptyObj'; import { h, mountSync, unmountSync } from '../../src/vidom'; describe('functionComponent', () => { let domNode; beforeEach(() => { document.body.appendChild(domNode = document.createElement('div')); }); afterEach(() => { unmountSync(domNode); document.body.removeChild(domNode); }); it('should pass empty object as attrs if they aren\'t specified', () => { const stub = sinon.stub(); stub.returns(null); mountSync(domNode, h(stub)); expect(stub.args[0][0]).to.be.equal(emptyObj); }); it('should merge passed with default attributes', () => { const stub = sinon.stub(); stub.returns(null); stub.defaultAttrs = { a : 1, b : 2 }; mountSync(domNode, h(stub, { a : 3 })); expect(stub.args[0][0]).to.be.eql({ a : 3, b : 2 }); }); });
/* eslint-disable camelcase */ // NOTE FOR ANY overnight MODIFIERS: This file is needed or else index.js will error, unless correct modifications are made. const fetch = require('node-fetch') const functions = require('../functions.js') const afk = require('./earn afk.js') const yaml = require('js-yaml') const fs = require('fs') const status_replies = yaml.load(fs.readFileSync('./status replies.yml', 'utf8')) const express = require('express') module.exports.load = async function (app, ifValidAPI, ejs) { app.use('/assets', express.static('./frontend/assets')) // Makes the assets folder display on /assets. app.get('*', async (req, res) => { // makes pages.json and variables stuff // ./frontend/pages/index.ejs let special let file // This is the variable that will hold the name of the file that should be opened and shown to the user. let type // Sets the "type" variable, which will be the file type. if (req._parsedUrl.pathname === '/') { file = process.pagesettings.index // The value of "index" on pages.yml is the page to be shown. } else { // This gets the path name and removes the beginning and ending slashes. let pathname = req._parsedUrl.pathname.slice(1) if (pathname.slice(-1) === '/') pathname = pathname.slice(0, -1) // This checks if the path name exists on pages.yml exist. const checkexist = Object.entries(process.pagesettings.pages).filter(p => p[0] === pathname) if (checkexist.length === 0) { // Could not find path name on pages.yml, therefore it is a 404. res.status(404) file = process.pagesettings.notfound // The value of "notfound" on pages.yml is the page to be shown. } else if (checkexist.length === 1) { // Found the path name on pages.yml. const pathexists = checkexist[0][1] const permission = pathexists.permission // This gets the value of the permission the user needs in order to view the page. if (pathexists.type) type = pathexists.type if (permission === 0 || permission === 1 || permission === 2) { // Checks if it is a valid permission number. /* 0 = Anyone can view the page. 1 = Only users logged in can view the page. 403 if not logged in. 2 = Only administrators can view the page. 404 if not an administrator. */ if (permission === 1 || permission === 2) { // Must be signed in pages. if (!req.session.data || !req.session.data.userinfo) { if (pathexists.no_permission_redirect) return functions.doRedirect(req, res, pathexists.no_permission_redirect) res.status(403) file = process.pagesettings.nopermission // The value of "nopermission" on pages.yml is the page to be shown. } else { if (permission === 1) { file = pathexists.file // The value of the variable "file" on the path name object is the page to be shown. } else if (permission === 2) { if (!req.session.data.panelinfo.root_admin) { // If user isn't an administrator. // eslint-disable-next-line no-undef if (pathexists.no_permission_redirect) returnfunctions.doRedirect(req, res, pathexists.no_permission_redirect) res.status(404) file = process.pagesettings.notfound // The value of "notfound" on pages.yml is the page to be shown. } else { // If user is an administrator. file = pathexists.file // The value of the variable "file" on the path name object is the page to be shown. }; }; } } else { // Pages anyone can go to. (no login required) file = pathexists.file // The value of the variable "file" on the path name object is the page to be shown. }; } else { // Permissions value on pages.yml for the path is not 0, 1, or 2. console.log(`[WEBSITE] On the path "${pathname}", the permission value is invalid. The value must be 0 (everyone), 1 (logged in), or 2 (administrator).`) return res.send('An error has occured while attempting to load this page. Please contact an administrator to fix this.') }; if (pathexists.special) { if (pathexists.special === 'afk') { const arcsessiontoken = Math.random().toString(36).substring(2, 15) special = await afk.generateAfkSrc(arcsessiontoken) special.type = 'afk' // Not necessary. req.session.arcsessiontoken = { token: arcsessiontoken, created: special.created } } else { console.log(`[WEBSITE] "${pathname}" had an invalid 'special' type.`) } } } else { // Multiple instances of the path name exists within pages.yml. console.log(`[WEBSITE] Please remove one of the pages "${pathname}"s from the pages.yml object.`) return res.send('An error has occured while attempting to load this page. Please contact an administrator to fix this.') }; }; let packageinfo = null let extra = null let total = null let current = null let server_timers = null if (req.session.data && req.session.data.dbinfo) { server_timers = {} for (const server of req.session.data.panelinfo.relationships.servers.data) { // Inefficient, and can be slow if a person has a ton of servers. server_timers[server.attributes.id] = await process.db.getSingleRenewalDate(server.attributes.id) } if (Object.entries(server_timers).filter(t => t[1].timer === '???').length !== 0) { const account_info_json = await fetch( `${process.env.pterodactyl.domain}/api/application/users/${req.session.data.panelinfo.id}?include=servers`, { method: 'get', headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${process.env.pterodactyl.key}` } } ) if (account_info_json.statusText !== 'Not Found') { const account_info = (await account_info_json.json()).attributes req.session.data.panelinfo = account_info } } const resources = await functions.getUserResource(req) // I can't use "let {packageinfo, extra, total, current}". packageinfo = resources.packageinfo extra = resources.extra total = resources.total current = resources.current } const variables = { // Creates "variables" object for what variables are to be sent frontend. variables: req.session.variables || null, data: req.session.data || null, settings: process.env, theme_settings: process.pagesettings, package: packageinfo, extra: extra, total: total, current: current, req: req, special: special, server_timers: server_timers, status_replies: status_replies } if (req.session.variables) delete req.session.variables // Deletes any given variables from another path after it is set on the "variables" object. ejs.renderFile( // This renders the EJS file. `./frontend/pages/${file}`, // This is the file that gets rendered. variables, // Variables that are sent to frontend should be set here. null, async function (err, str) { // Function ran after the file has successfully rendered. if (err) { // EJS file had a rendering error. res.status(500) console.log(`[WEBSITE] An error has occured on path ${req._parsedUrl.pathname}:`) console.log(err) ejs.renderFile( // This renders the rendering error EJS file. `./frontend/pages/${process.pagesettings.renderfail}`, // This is the file that gets rendered. variables, // Variables that are sent to frontend should be set here. null, async function (err, str) { // Function ran after the file has successfully rendered. if (err) { // Rendering error page has a error. console.log(`[WEBSITE] An error has also occured while attempting to send the rendering error page on path ${req._parsedUrl.pathname}:`) console.log(err) return res.send('An error has occured while attempting to load this page. Please contact an administrator to fix this.') // Backup rendering error page. }; res.send(str) // Sends rendering error page. }) return }; if (type) res.type(type) res.send(str) // Sends the page. }) }) }
"""Tests for views of contributions (comments).""" import json from django.test import TestCase from django.contrib.auth.models import AnonymousUser from django.core.urlresolvers import reverse from django.core.exceptions import PermissionDenied from nose.tools import raises from rest_framework.test import APITestCase from rest_framework.test import APIRequestFactory, force_authenticate from rest_framework import status from rest_framework.renderers import JSONRenderer from geokey.projects.tests.model_factories import UserFactory, ProjectFactory from geokey.projects.models import Project from geokey.contributions.models import Comment, Observation from geokey.users.models import User from geokey.users.tests.model_factories import UserGroupFactory from ..model_factories import ObservationFactory, CommentFactory from geokey.contributions.views.comments import ( CommentsAPIView, SingleCommentAPIView, CommentAbstractAPIView ) class CommentAbstractAPIViewTest(TestCase): def setUp(self): self.factory = APIRequestFactory() self.admin = UserFactory.create() self.creator = UserFactory.create() self.moderator = UserFactory.create() self.commenter = UserFactory.create() self.project = ProjectFactory( add_admins=[self.admin], add_contributors=[self.creator, self.commenter] ) self.moderators = UserGroupFactory(add_users=[self.moderator], **{ 'project': self.project, 'can_moderate': True }) self.contribution = ObservationFactory.create(**{ 'project': self.project, 'creator': self.creator, 'status': 'active' }) self.comment = CommentFactory.create(**{ 'commentto': self.contribution, 'creator': self.commenter }) def render(self, response): response.accepted_renderer = JSONRenderer() response.accepted_media_type = 'application/json' response.renderer_context = {'blah': 'blubb'} return response.render() def test_create_comment_with_admin(self): url = reverse('api:project_comments', kwargs={ 'project_id': self.project.id, 'contribution_id': self.contribution.id }) request = self.factory.post(url, {'text': 'Comment'}) request.user = self.admin request.data = {'text': 'Comment'} view = CommentAbstractAPIView() response = self.render( view.create_and_respond(request, self.contribution) ) self.assertEqual(json.loads(response.content).get('text'), 'Comment') def test_create_reviewcomment_with_admin(self): url = reverse('api:project_comments', kwargs={ 'project_id': self.project.id, 'contribution_id': self.contribution.id }) request = self.factory.post( url, {'text': 'Comment', 'review_status': 'open'} ) request.user = self.admin request.data = {'text': 'Comment', 'review_status': 'open'} view = CommentAbstractAPIView() response = self.render( view.create_and_respond(request, self.contribution) ) self.assertEqual(json.loads(response.content).get('text'), 'Comment') ref = Observation.objects.get(pk=self.contribution.id) self.assertEqual(ref.status, 'review') def test_create_reviewcomment_to_empty_obs_with_admin(self): self.contribution.properties = {} self.contribution.save() url = reverse('api:project_comments', kwargs={ 'project_id': self.project.id, 'contribution_id': self.contribution.id }) request = self.factory.post( url, {'text': 'Comment', 'review_status': 'open'} ) request.user = self.admin request.data = {'text': 'Comment', 'review_status': 'open'} view = CommentAbstractAPIView() response = self.render( view.create_and_respond(request, self.contribution) ) self.assertEqual(json.loads(response.content).get('text'), 'Comment') ref = Observation.objects.get(pk=self.contribution.id) self.assertEqual(ref.status, 'review') def test_update_comment_with_admin(self): url = reverse('api:project_single_comment', kwargs={ 'project_id': self.project.id, 'contribution_id': self.contribution.id, 'comment_id': self.comment.id }) request = self.factory.patch(url, {'text': 'Updated'}) request.user = self.admin request.data = {'text': 'Updated'} view = CommentAbstractAPIView() response = self.render( view.update_and_respond(request, self.contribution, self.comment) ) self.assertEqual(json.loads(response.content).get('text'), 'Updated') self.assertEqual( Comment.objects.get(pk=self.comment.id).text, 'Updated' ) def test_update_comment_with_commenter(self): url = reverse('api:project_single_comment', kwargs={ 'project_id': self.project.id, 'contribution_id': self.contribution.id, 'comment_id': self.comment.id }) request = self.factory.patch(url, {'text': 'Updated'}) request.user = self.commenter request.data = {'text': 'Updated'} view = CommentAbstractAPIView() response = self.render( view.update_and_respond(request, self.contribution, self.comment) ) self.assertEqual(json.loads(response.content).get('text'), 'Updated') self.assertEqual( Comment.objects.get(pk=self.comment.id).text, 'Updated' ) def test_update_comment_with_moderator(self): url = reverse('api:project_single_comment', kwargs={ 'project_id': self.project.id, 'contribution_id': self.contribution.id, 'comment_id': self.comment.id }) request = self.factory.patch(url, {'text': 'Updated'}) request.user = self.moderator request.data = {'text': 'Updated'} view = CommentAbstractAPIView() response = self.render( view.update_and_respond(request, self.contribution, self.comment) ) self.assertEqual(json.loads(response.content).get('text'), 'Updated') self.assertEqual( Comment.objects.get(pk=self.comment.id).text, 'Updated' ) @raises(PermissionDenied) def test_update_comment_with_creator(self): url = reverse('api:project_single_comment', kwargs={ 'project_id': self.project.id, 'contribution_id': self.contribution.id, 'comment_id': self.comment.id }) request = self.factory.patch(url, {'text': 'Updated'}) request.user = self.creator request.data = {'text': 'Updated'} view = CommentAbstractAPIView() response = self.render( view.update_and_respond(request, self.contribution, self.comment) ) self.assertEqual( json.loads(response.content).get('text'), self.comment.text ) self.assertEqual( Comment.objects.get(pk=self.comment.id).text, self.comment.text ) def test_update_invalid_comment(self): self.project.isprivate = False self.project.save() url = reverse('api:project_single_comment', kwargs={ 'project_id': self.project.id, 'contribution_id': self.contribution.id, 'comment_id': self.comment.id }) request = self.factory.patch( url, {'text': 'Updated', 'review_status': 'blah'} ) force_authenticate(request, user=self.commenter) view = SingleCommentAPIView.as_view() response = view( request, project_id=self.project.id, contribution_id=self.contribution.id, comment_id=self.comment.id ).render() self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) class CommentAbstractAPIViewResolveTest(TestCase): def setUp(self): self.factory = APIRequestFactory() self.admin = UserFactory.create() self.creator = UserFactory.create() self.moderator = UserFactory.create() self.commenter = UserFactory.create() self.project = ProjectFactory( add_admins=[self.admin], add_contributors=[self.creator, self.commenter] ) self.moderators = UserGroupFactory(add_users=[self.moderator], **{ 'project': self.project, 'can_moderate': True }) self.contribution = ObservationFactory.create(**{ 'project': self.project, 'creator': self.creator, 'status': 'review' }) self.comment = CommentFactory.create(**{ 'commentto': self.contribution, 'creator': self.commenter, 'review_status': 'open' }) def render(self, response): response.accepted_renderer = JSONRenderer() response.accepted_media_type = 'application/json' response.renderer_context = {'blah': 'blubb'} return response.render() def test_resolve_comment_with_admin(self): url = reverse('api:project_single_comment', kwargs={ 'project_id': self.project.id, 'contribution_id': self.contribution.id, 'comment_id': self.comment.id }) request = self.factory.patch(url, {'text': 'Updated'}) request.user = self.admin request.data = {'review_status': 'resolved'} view = CommentAbstractAPIView() response = self.render( view.update_and_respond(request, self.contribution, self.comment) ) self.assertEqual( json.loads(response.content).get('review_status'), 'resolved' ) reference = Observation.objects.get(pk=self.contribution.id) self.assertEqual(reference.status, 'active') self.assertIsNotNone(reference.properties) def test_resolve_comment_with_invalid_review_status(self): url = reverse('api:project_single_comment', kwargs={ 'project_id': self.project.id, 'contribution_id': self.contribution.id, 'comment_id': self.comment.id }) request = self.factory.patch(url, {'text': 'Updated'}) request.user = self.admin request.data = {'review_status': 'closed'} view = CommentAbstractAPIView() response = self.render( view.update_and_respond(request, self.contribution, self.comment) ) ref = Comment.objects.get(pk=self.comment.id) self.assertEqual(response.status_code, 400) self.assertEqual(ref.review_status, 'open') def test_resolve_one_of_two_comment_with_admin(self): CommentFactory.create(**{ 'commentto': self.contribution, 'creator': self.creator, 'review_status': 'open' }) url = reverse('api:project_single_comment', kwargs={ 'project_id': self.project.id, 'contribution_id': self.contribution.id, 'comment_id': self.comment.id }) request = self.factory.patch(url, {'text': 'Updated'}) request.user = self.admin request.data = {'review_status': 'resolved'} view = CommentAbstractAPIView() response = self.render( view.update_and_respond(request, self.contribution, self.comment) ) self.assertEqual( json.loads(response.content).get('review_status'), 'resolved' ) self.assertEqual( Observation.objects.get(pk=self.contribution.id).status, 'review' ) def test_resolve_comment_with_moderator(self): url = reverse('api:project_single_comment', kwargs={ 'project_id': self.project.id, 'contribution_id': self.contribution.id, 'comment_id': self.comment.id }) request = self.factory.patch(url, {'text': 'Updated'}) request.user = self.moderator request.data = {'review_status': 'resolved'} view = CommentAbstractAPIView() response = self.render( view.update_and_respond(request, self.contribution, self.comment) ) self.assertEqual( json.loads(response.content).get('review_status'), 'resolved' ) self.assertEqual( Observation.objects.get(pk=self.contribution.id).status, 'active' ) @raises(PermissionDenied) def test_resolve_comment_with_creator(self): url = reverse('api:project_single_comment', kwargs={ 'project_id': self.project.id, 'contribution_id': self.contribution.id, 'comment_id': self.comment.id }) request = self.factory.patch(url, {'text': 'Updated'}) request.user = self.creator request.data = {'review_status': 'resolved'} view = CommentAbstractAPIView() view.update_and_respond(request, self.contribution, self.comment) @raises(PermissionDenied) def test_resolve_comment_with_commenter(self): url = reverse('api:project_single_comment', kwargs={ 'project_id': self.project.id, 'contribution_id': self.contribution.id, 'comment_id': self.comment.id }) request = self.factory.patch(url, {'text': 'Updated'}) request.user = self.commenter request.data = {'review_status': 'resolved'} view = CommentAbstractAPIView() view.update_and_respond(request, self.contribution, self.comment) @raises(PermissionDenied) def test_resolve_comment_with_anonymous(self): url = reverse('api:project_single_comment', kwargs={ 'project_id': self.project.id, 'contribution_id': self.contribution.id, 'comment_id': self.comment.id }) request = self.factory.patch(url, {'text': 'Updated'}) request.user = AnonymousUser() request.data = {'review_status': 'resolved'} view = CommentAbstractAPIView() view.update_and_respond(request, self.contribution, self.comment) class SingleCommentAPIViewTest(TestCase): def setUp(self): self.admin = UserFactory.create() self.creator = UserFactory.create() self.project = ProjectFactory( add_admins=[self.admin], add_contributors=[self.creator] ) self.contribution = ObservationFactory.create(**{ 'project': self.project, 'creator': self.creator }) def test_get_contribution_with_admin(self): view = SingleCommentAPIView() contribution = view.get_contribution( self.admin, self.project.id, self.contribution.id) self.assertEqual(contribution, self.contribution) def test_get_contribution_with_creator(self): view = SingleCommentAPIView() view.get_contribution( self.creator, self.project.id, self.contribution.id ) @raises(Project.DoesNotExist) def test_get_contribution_with_some_dude(self): some_dude = UserFactory.create() view = SingleCommentAPIView() view.get_contribution( some_dude, self.project.id, self.contribution.id ) class GetProjectComments(APITestCase): def setUp(self): self.contributor = UserFactory.create() self.admin = UserFactory.create() self.non_member = UserFactory.create() self.project = ProjectFactory( add_admins=[self.admin], add_contributors=[self.contributor] ) self.contribution = ObservationFactory.create(**{ 'project': self.project, 'creator': self.contributor }) comment = CommentFactory.create(**{ 'commentto': self.contribution }) response = CommentFactory.create(**{ 'commentto': self.contribution, 'respondsto': comment }) CommentFactory.create(**{ 'commentto': self.contribution, 'respondsto': response }) CommentFactory.create(**{ 'commentto': self.contribution, 'respondsto': comment }) CommentFactory.create(**{ 'commentto': self.contribution }) def get_response(self, user): factory = APIRequestFactory() request = factory.get( '/api/projects/%s/contributions/%s/comments/' % (self.project.id, self.contribution.id) ) force_authenticate(request, user=user) view = CommentsAPIView.as_view() return view( request, project_id=self.project.id, contribution_id=self.contribution.id ).render() def test_get_comments_with_admin(self): response = self.get_response(self.admin) self.assertEqual(response.status_code, status.HTTP_200_OK) def test_get_comments_with_contributor(self): response = self.get_response(self.contributor) self.assertEqual(response.status_code, status.HTTP_200_OK) def test_get_comments_with_non_member(self): response = self.get_response(self.non_member) self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND) class AddCommentToPrivateProjectTest(APITestCase): def setUp(self): self.contributor = UserFactory.create() self.admin = UserFactory.create() self.non_member = UserFactory.create() self.project = ProjectFactory( add_admins=[self.admin], add_contributors=[self.contributor] ) self.contribution = ObservationFactory.create(**{ 'project': self.project, 'creator': self.contributor }) def get_response(self, user): factory = APIRequestFactory() request = factory.post( '/api/projects/%s/contributions/%s/comments/' % (self.project.id, self.contribution.id), {'text': 'A comment to the contribution.'} ) force_authenticate(request, user=user) view = CommentsAPIView.as_view() return view( request, project_id=self.project.id, contribution_id=self.contribution.id ).render() def test_add_comment_to_contribution_with_admin(self): response = self.get_response(self.admin) self.assertEqual(response.status_code, status.HTTP_201_CREATED) def test_add_comment_to_contribution_with_contributor(self): response = self.get_response(self.contributor) self.assertEqual(response.status_code, status.HTTP_201_CREATED) def test_add_review_comment_to_contribution_with_contributor(self): factory = APIRequestFactory() request = factory.post( '/api/projects/%s/contributions/%s/comments/' % (self.project.id, self.contribution.id), { 'text': 'A review comment to the contribution.', 'review_status': 'open' } ) force_authenticate(request, user=self.contributor) view = CommentsAPIView.as_view() response = view( request, project_id=self.project.id, contribution_id=self.contribution.id ).render() self.assertEqual(response.status_code, status.HTTP_201_CREATED) self.assertEqual( Observation.objects.get(pk=self.contribution.id).status, 'review' ) def test_add_closed_review_comment_to_contribution_with_contributor(self): factory = APIRequestFactory() request = factory.post( '/api/projects/%s/contributions/%s/comments/' % (self.project.id, self.contribution.id), { 'text': 'A review comment to the contribution.', 'review_status': 'resolved' } ) force_authenticate(request, user=self.contributor) view = CommentsAPIView.as_view() response = view( request, project_id=self.project.id, contribution_id=self.contribution.id ).render() self.assertEqual(response.status_code, status.HTTP_201_CREATED) self.assertEqual( Observation.objects.get(pk=self.contribution.id).status, 'active' ) def test_add_comment_to_contribution_with_non_member(self): response = self.get_response(self.non_member) self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND) def test_add_comment_to_draft(self): self.contribution.status = 'draft' self.contribution.save() response = self.get_response(self.contribution.creator) self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) class AddCommentToPublicProjectTest(APITestCase): def setUp(self): self.contributor = UserFactory.create() self.admin = UserFactory.create() self.non_member = UserFactory.create() self.project = ProjectFactory( add_admins=[self.admin], add_contributors=[self.contributor], **{'isprivate': False} ) self.contribution = ObservationFactory.create(**{ 'project': self.project, 'creator': self.contributor }) def get_response(self, user): if user.is_anonymous and not User.objects.filter( display_name='AnonymousUser').exists(): UserFactory.create(display_name='AnonymousUser') factory = APIRequestFactory() request = factory.post( '/api/projects/%s/maps/all-contributions/%s/comments/' % (self.project.id, self.contribution.id), {'text': 'A comment to the contribution.'} ) force_authenticate(request, user=user) view = CommentsAPIView.as_view() return view( request, project_id=self.project.id, contribution_id=self.contribution.id ).render() def test_add_comment_to_contribution_with_admin(self): response = self.get_response(self.admin) self.assertEqual(response.status_code, status.HTTP_201_CREATED) def test_add_comment_to_contribution_with_contributor(self): response = self.get_response(self.contributor) self.assertEqual(response.status_code, status.HTTP_201_CREATED) def test_add_comment_to_contribution_with_non_member(self): response = self.get_response(self.non_member) self.assertEqual(response.status_code, status.HTTP_201_CREATED) def test_add_comment_to_contribution_with_anonymous(self): response = self.get_response(AnonymousUser()) self.assertEqual(response.status_code, status.HTTP_201_CREATED) class AddCommentToWrongProjectContribution(APITestCase): def test(self): admin = UserFactory.create() project = ProjectFactory(add_admins=[admin]) contribution = ObservationFactory.create() factory = APIRequestFactory() request = factory.post( '/api/projects/%s/contributions/%s/comments/' % (project.id, contribution.id), {'text': 'A comment to the contribution.'} ) force_authenticate(request, user=admin) view = CommentsAPIView.as_view() response = view( request, project_id=project.id, contribution_id=contribution.id ).render() self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND) class AddResponseToProjectCommentTest(APITestCase): def test(self): admin = UserFactory.create() project = ProjectFactory(add_admins=[admin]) contribution = ObservationFactory.create(**{ 'project': project }) comment = CommentFactory.create(**{ 'commentto': contribution }) factory = APIRequestFactory() request = factory.post( '/api/projects/%s/contributions/%s/comments/' % (project.id, contribution.id), { 'text': 'Response to a comment', 'respondsto': comment.id } ) force_authenticate(request, user=admin) view = CommentsAPIView.as_view() response = view( request, project_id=project.id, contribution_id=contribution.id ).render() self.assertEqual(response.status_code, status.HTTP_201_CREATED) self.assertEqual( json.loads(response.content).get('respondsto'), comment.id ) class AddResponseToWrongProjectCommentTest(APITestCase): def test(self): admin = UserFactory.create() project = ProjectFactory(add_admins=[admin]) contribution = ObservationFactory.create(**{ 'project': project }) comment = CommentFactory.create() factory = APIRequestFactory() request = factory.post( '/api/projects/%s/contributions/%s/comments/' % (project.id, contribution.id), { 'text': 'Response to a comment', 'respondsto': comment.id } ) force_authenticate(request, user=admin) view = CommentsAPIView.as_view() response = view( request, project_id=project.id, contribution_id=contribution.id ).render() self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) self.assertEqual( json.loads(response.content).get('error'), 'The comment you try to respond to is not a comment to the ' 'contribution.' ) class DeleteProjectCommentTest(APITestCase): def setUp(self): self.contributor = UserFactory.create() self.admin = UserFactory.create() self.non_member = UserFactory.create() self.project = ProjectFactory( add_admins=[self.admin], add_contributors=[self.contributor], **{'isprivate': False} ) self.contribution = ObservationFactory.create(**{ 'project': self.project, 'creator': self.contributor }) self.comment = CommentFactory.create(**{ 'commentto': self.contribution }) self.comment_to_remove = CommentFactory.create(**{ 'commentto': self.contribution, 'creator': self.contributor }) def get_response(self, user, comment_to_remove=None): if not comment_to_remove: comment_to_remove = self.comment_to_remove factory = APIRequestFactory() request = factory.delete( '/api/projects/%s/contributions/%s/comments/%s/' % (self.project.id, self.contribution.id, comment_to_remove.id), {'text': 'A comment to the contribution.'} ) force_authenticate(request, user=user) view = SingleCommentAPIView.as_view() return view( request, project_id=self.project.id, contribution_id=self.contribution.id, comment_id=comment_to_remove.id ).render() def test_delete_comment_with_anonymous(self): response = self.get_response(AnonymousUser()) self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN) contribution = Observation.objects.get(pk=self.contribution.id) self.assertIn(self.comment_to_remove, contribution.comments.all()) def test_delete_comment_with_admin(self): response = self.get_response(self.admin) self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT) contribution = Observation.objects.get(pk=self.contribution.id) self.assertIn(self.comment, contribution.comments.all()) self.assertNotIn(self.comment_to_remove, contribution.comments.all()) def test_delete_anonymous_comment_with_comment_creator(self): comment_to_remove = CommentFactory.create(**{ 'commentto': self.contribution, 'creator': User.objects.get(display_name='AnonymousUser') }) response = self.get_response(AnonymousUser(), comment_to_remove) self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN) contribution = Observation.objects.get(pk=self.contribution.id) self.assertIn(comment_to_remove, contribution.comments.all()) def test_delete_comment_with_comment_creator(self): response = self.get_response(self.contributor) self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT) contribution = Observation.objects.get(pk=self.contribution.id) self.assertIn(self.comment, contribution.comments.all()) self.assertNotIn(self.comment_to_remove, contribution.comments.all()) def test_delete_review_comment_with_comment_creator(self): self.comment_to_remove.review_status = 'open' self.comment_to_remove.save() self.contribution.status = 'review' self.contribution.save() response = self.get_response(self.contributor) self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT) contribution = Observation.objects.get(pk=self.contribution.id) self.assertEqual(contribution.status, 'active') self.assertIn(self.comment, contribution.comments.all()) self.assertNotIn(self.comment_to_remove, contribution.comments.all()) def test_delete_comment_but_not_change_status_from_pending(self): self.contribution.status = 'pending' self.contribution.save() response = self.get_response(self.contributor) self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT) contribution = Observation.objects.get(pk=self.contribution.id) self.assertEqual(contribution.status, 'pending') def test_delete_comment_and_change_status_from_review(self): self.contribution.status = 'review' self.contribution.save() response = self.get_response(self.contributor) self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT) contribution = Observation.objects.get(pk=self.contribution.id) self.assertEqual(contribution.status, 'active') def test_delete_one_review_comment_with_comment_creator(self): self.comment.review_status = 'open' self.comment.save() self.comment_to_remove.review_status = 'open' self.comment_to_remove.save() self.contribution.status = 'review' self.contribution.save() response = self.get_response(self.contributor) self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT) contribution = Observation.objects.get(pk=self.contribution.id) self.assertEqual(contribution.status, 'review') self.assertIn(self.comment, contribution.comments.all()) self.assertNotIn(self.comment_to_remove, contribution.comments.all()) def test_resolve_nested_comment_with_admin(self): self.comment.respondsto = self.comment_to_remove self.comment.review_status = 'open' self.comment.save() self.comment_to_remove.review_status = None self.comment_to_remove.save() self.contribution.status = 'review' self.contribution.save() response = self.get_response(self.admin) self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT) self.assertEqual( Observation.objects.get(pk=self.contribution.id).status, 'active' ) class DeleteWrongProjectComment(APITestCase): def test(self): admin = UserFactory.create() project = ProjectFactory(add_admins=[admin]) contribution = ObservationFactory.create(**{ 'project': project }) comment = CommentFactory.create() factory = APIRequestFactory() request = factory.delete( '/api/projects/%s/contributions/%s/comments/%s/' % (project.id, contribution.id, comment.id), {'text': 'A comment to the contribution.'} ) force_authenticate(request, user=admin) view = SingleCommentAPIView.as_view() response = view( request, project_id=project.id, contribution_id=contribution.id, comment_id=comment.id ).render() self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
/* Amplify Params - DO NOT EDIT API_OPENECMR_CONTRACTTABLE_ARN API_OPENECMR_CONTRACTTABLE_NAME API_OPENECMR_GRAPHQLAPIIDOUTPUT ENV REGION STORAGE_ATTACHMENTS_BUCKETNAME Amplify Params - DO NOT EDIT */ const handler = require("./build/main.js"); exports.handler = handler.default;
/* eslint-disable no-undef */ /* eslint-disable prettier/prettier */ import React, { Component } from 'react'; import { SafeAreaView, StyleSheet, ScrollView, View,Image,Keyboard, Text,Dimensions,TouchableHighlight, StatusBar,TouchableWithoutFeedback, TextInput,KeyboardAvoidingView, Alert, } from 'react-native'; import Icon from 'react-native-vector-icons'; import {theme} from '../Constants/themes'; import Button from 'react-native-button'; export default class Login extends Component{ render(){ let _onPress = () =>{ Alert.alert("login successful"); } // for navigation // destructing navigation const {navigation} = this.props let onRegisterTextPress = ()=>{ //alert('go to signup page'); //this.props.navigate('Signup) navigation.navigate('Signup'); } return( <TouchableWithoutFeedback onPress={Keyboard.dismiss}> <View style= {styles.container}> <Text style= {styles.textHeader}>Signin Account</Text> <View style={ styles.inputContainer }> <View style= { {alignContent:'center',justifyContent:'center',alignItems:'center', marginTop:20,marginBottom:20} }> <TextInput style={styles.input} placeholder=" email" placeholderTextColor={theme.color.greyDarker} keyboardType='email-address' autoCorrect={false} returnKeyType= 'next' /> <TextInput style={styles.input} placeholder="password" placeholderTextColor={theme.color.greyDarker} autoCorrect={false} secureTextEntry={true} /> <Button style={styles.btnContainer} onPress= {_onPress} > Login </Button> <Button> <Text style={styles.registerText} onPress={onRegisterTextPress} >New here? SignUp </Text> </Button> </View> </View> </View> </TouchableWithoutFeedback> ); } } const styles = StyleSheet.create({ container: { flex: 1, alignContent:'center', justifyContent:'center', flexDirection:'column', alignItems: 'center', backgroundColor: '#FECE21', // borderTopLeftRadius:20, // borderTopRightRadius: 20, borderRightColor:theme.color.orange, borderLeftColor:theme.color.orange, }, textHeader:{ flex:1 / 2, fontFamily:'cursive', fontSize:27, fontWeight: 'bold', marginTop: 30, color: theme.color.black, marginBottom: 40 }, inputContainer:{ flex:1, flexDirection:'column', marginTop:10, width: Dimensions.get('window').width, height: 150, backgroundColor: 'white', alignItems:'center', borderTopLeftRadius: 20, borderTopRightRadius: 20, borderBottomColor:theme.color.orange }, input:{ borderRadius:15, backgroundColor:theme.color.greyLighter, width:300, marginHorizontal: 20, paddingHorizontal:10, marginBottom:15, fontSize: 18, fontWeight: 'normal', padding: 15, marginTop: 10, }, btnContainer:{ flexDirection: 'row', width: 150, alignItems:'center', height: 45, color: theme.color.black, backgroundColor:'#FECE21' , fontSize: 18, fontWeight:'normal', borderRadius:15, padding: 10, marginLeft: 30, marginBottom: 10 }, registerText:{ alignItems:'center', color: theme.color.greyDarker, fontSize: 18, fontWeight:'normal', backgroundColor:'transparent' } });
const fs = require('fs') const path = require('path') const webpack = require('webpack') module.exports = { devtool: 'inline-source-map', entry: fs.readdirSync(__dirname).reduce((entries, dir) => { const fullDir = path.join(__dirname, dir) const entry = path.join(fullDir, 'app.js') if (fs.statSync(fullDir).isDirectory() && fs.existsSync(entry)) { entries[dir] = ['webpack-hot-middleware/client', entry] } return entries }, {}), output: { path: path.join(__dirname, '__build__'), filename: '[name].js', chunkFilename: '[id].chunk.js', publicPath: '/__build__/' }, module: { rules: [ { test: /\.js$/, exclude: /node_modules/, loader: 'babel-loader' }, { test: /\.vue$/, loader: 'vue-loader' }, { test: /\.less$/, loader: "style-loader!css-loader!less-loader" }, ] }, resolve: { alias: { vuex: path.resolve(__dirname, '../src/index.esm.js') } }, plugins: [ new webpack.optimize.CommonsChunkPlugin({ name: 'shared', filename: 'shared.js' }), new webpack.DefinePlugin({ 'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV || 'development') }), new webpack.HotModuleReplacementPlugin(), new webpack.NoEmitOnErrorsPlugin() ] }
/* global QUnit */ QUnit.config.autostart = false; sap.ui.getCore().attachInit(function () { "use strict"; sap.ui.require([ "com/sap/sfsf/applicants/test/integration/AllJourneys" ], function () { QUnit.start(); }); });
num = int(input('Digite um número e descubra a tabuada dele:')) print(f'{num} x 1 = {num*1}') print(f'{num} x 2 = {num*2}') print(f'{num} x 3 = {num*3}') print(f'{num} x 4 = {num*4}') print(f'{num} x 5 = {num*5}') print(f'{num} x 6 = {num*6}') print(f'{num} x 7 = {num*7}') print(f'{num} x 8 = {num*8}') print(f'{num} x 9 = {num*9}') print(f'{num} x 10 = {num*10}')
deepmacDetailCallback("70b3d54b8000/36",[{"a":"8346 Old Richfood Road Mechanicsville VA US 23116","o":"International Roll-Call Corporation","d":"2017-07-16","t":"add","s":"ieee","c":"US"}]);
import _objectWithoutPropertiesLoose from "@babel/runtime/helpers/objectWithoutPropertiesLoose"; import _extends from "@babel/runtime/helpers/extends"; import React from 'react'; import PropTypes from 'prop-types'; import classNames from 'classnames'; import EventListener from 'react-event-listener'; import withStyles from '../styles/withStyles'; import { duration } from '../styles/transitions'; import ClickAwayListener from '../ClickAwayListener'; import { capitalize, createChainedFunction } from '../utils/helpers'; import Slide from '../Slide'; import SnackbarContent from '../SnackbarContent'; export const styles = theme => { const gutter = 24; const top = { top: 0 }; const bottom = { bottom: 0 }; const right = { justifyContent: 'flex-end' }; const left = { justifyContent: 'flex-start' }; const topSpace = { top: gutter }; const bottomSpace = { bottom: gutter }; const rightSpace = { right: gutter }; const leftSpace = { left: gutter }; const center = { left: '50%', right: 'auto', transform: 'translateX(-50%)' }; return { /* Styles applied to the root element. */ root: { zIndex: theme.zIndex.snackbar, position: 'fixed', display: 'flex', left: 0, right: 0, justifyContent: 'center', alignItems: 'center' }, /* Styles applied to the root element if `anchorOrigin={{ 'top', 'center' }}`. */ anchorOriginTopCenter: _extends({}, top, { [theme.breakpoints.up('md')]: _extends({}, center) }), /* Styles applied to the root element if `anchorOrigin={{ 'bottom', 'center' }}`. */ anchorOriginBottomCenter: _extends({}, bottom, { [theme.breakpoints.up('md')]: _extends({}, center) }), /* Styles applied to the root element if `anchorOrigin={{ 'top', 'right' }}`. */ anchorOriginTopRight: _extends({}, top, right, { [theme.breakpoints.up('md')]: _extends({ left: 'auto' }, topSpace, rightSpace) }), /* Styles applied to the root element if `anchorOrigin={{ 'bottom', 'right' }}`. */ anchorOriginBottomRight: _extends({}, bottom, right, { [theme.breakpoints.up('md')]: _extends({ left: 'auto' }, bottomSpace, rightSpace) }), /* Styles applied to the root element if `anchorOrigin={{ 'top', 'left' }}`. */ anchorOriginTopLeft: _extends({}, top, left, { [theme.breakpoints.up('md')]: _extends({ right: 'auto' }, topSpace, leftSpace) }), /* Styles applied to the root element if `anchorOrigin={{ 'bottom', 'left' }}`. */ anchorOriginBottomLeft: _extends({}, bottom, left, { [theme.breakpoints.up('md')]: _extends({ right: 'auto' }, bottomSpace, leftSpace) }) }; }; /* istanbul ignore if */ if (process.env.NODE_ENV !== 'production' && !React.createContext) { throw new Error('Material-UI: react@16.3.0 or greater is required.'); } class Snackbar extends React.Component { constructor(...args) { super(...args); this.state = {}; this.handleMouseEnter = event => { if (this.props.onMouseEnter) { this.props.onMouseEnter(event); } this.handlePause(); }; this.handleMouseLeave = event => { if (this.props.onMouseLeave) { this.props.onMouseLeave(event); } this.handleResume(); }; this.handleClickAway = event => { if (this.props.onClose) { this.props.onClose(event, 'clickaway'); } }; this.handlePause = () => { clearTimeout(this.timerAutoHide); }; this.handleResume = () => { if (this.props.autoHideDuration != null) { if (this.props.resumeHideDuration != null) { this.setAutoHideTimer(this.props.resumeHideDuration); return; } this.setAutoHideTimer(this.props.autoHideDuration * 0.5); } }; this.handleExited = () => { this.setState({ exited: true }); }; } componentDidMount() { if (this.props.open) { this.setAutoHideTimer(); } } componentDidUpdate(prevProps) { if (prevProps.open !== this.props.open) { if (this.props.open) { this.setAutoHideTimer(); } else { clearTimeout(this.timerAutoHide); } } } componentWillUnmount() { clearTimeout(this.timerAutoHide); } static getDerivedStateFromProps(nextProps, prevState) { if (typeof prevState.exited === 'undefined') { return { exited: !nextProps.open }; } if (nextProps.open) { return { exited: false }; } return null; } // Timer that controls delay before snackbar auto hides setAutoHideTimer(autoHideDuration) { const autoHideDurationBefore = autoHideDuration != null ? autoHideDuration : this.props.autoHideDuration; if (!this.props.onClose || autoHideDurationBefore == null) { return; } clearTimeout(this.timerAutoHide); this.timerAutoHide = setTimeout(() => { const autoHideDurationAfter = autoHideDuration != null ? autoHideDuration : this.props.autoHideDuration; if (!this.props.onClose || autoHideDurationAfter == null) { return; } this.props.onClose(null, 'timeout'); }, autoHideDurationBefore); } render() { const _this$props = this.props, { action, anchorOrigin: { vertical, horizontal }, children, classes, className, ClickAwayListenerProps, ContentProps, disableWindowBlurListener, message, onEnter, onEntered, onEntering, onExit, onExited, onExiting, open, TransitionComponent, transitionDuration, TransitionProps } = _this$props, other = _objectWithoutPropertiesLoose(_this$props, ["action", "anchorOrigin", "autoHideDuration", "children", "classes", "className", "ClickAwayListenerProps", "ContentProps", "disableWindowBlurListener", "message", "onClose", "onEnter", "onEntered", "onEntering", "onExit", "onExited", "onExiting", "onMouseEnter", "onMouseLeave", "open", "resumeHideDuration", "TransitionComponent", "transitionDuration", "TransitionProps"]); // So we only render active snackbars. if (!open && this.state.exited) { return null; } return React.createElement(ClickAwayListener, _extends({ onClickAway: this.handleClickAway }, ClickAwayListenerProps), React.createElement("div", _extends({ className: classNames(classes.root, classes[`anchorOrigin${capitalize(vertical)}${capitalize(horizontal)}`], className), onMouseEnter: this.handleMouseEnter, onMouseLeave: this.handleMouseLeave }, other), React.createElement(EventListener, { target: "window", onFocus: disableWindowBlurListener ? undefined : this.handleResume, onBlur: disableWindowBlurListener ? undefined : this.handlePause }), React.createElement(TransitionComponent, _extends({ appear: true, in: open, onEnter: onEnter, onEntered: onEntered, onEntering: onEntering, onExit: onExit, onExited: createChainedFunction(this.handleExited, onExited), onExiting: onExiting, timeout: transitionDuration, direction: vertical === 'top' ? 'down' : 'up' }, TransitionProps), children || React.createElement(SnackbarContent, _extends({ message: message, action: action }, ContentProps))))); } } Snackbar.propTypes = process.env.NODE_ENV !== "production" ? { /** * The action to display. */ action: PropTypes.node, /** * The anchor of the `Snackbar`. */ anchorOrigin: PropTypes.shape({ horizontal: PropTypes.oneOf(['left', 'center', 'right']).isRequired, vertical: PropTypes.oneOf(['top', 'bottom']).isRequired }), /** * The number of milliseconds to wait before automatically calling the * `onClose` function. `onClose` should then set the state of the `open` * prop to hide the Snackbar. This behavior is disabled by default with * the `null` value. */ autoHideDuration: PropTypes.number, /** * Replace the `SnackbarContent` component. */ children: PropTypes.element, /** * Override or extend the styles applied to the component. * See [CSS API](#css-api) below for more details. */ classes: PropTypes.object.isRequired, /** * @ignore */ className: PropTypes.string, /** * Properties applied to the `ClickAwayListener` element. */ ClickAwayListenerProps: PropTypes.object, /** * Properties applied to the [`SnackbarContent`](/api/snackbar-content/) element. */ ContentProps: PropTypes.object, /** * If `true`, the `autoHideDuration` timer will expire even if the window is not focused. */ disableWindowBlurListener: PropTypes.bool, /** * When displaying multiple consecutive Snackbars from a parent rendering a single * <Snackbar/>, add the key property to ensure independent treatment of each message. * e.g. <Snackbar key={message} />, otherwise, the message may update-in-place and * features such as autoHideDuration may be canceled. */ key: PropTypes.any, /** * The message to display. */ message: PropTypes.node, /** * Callback fired when the component requests to be closed. * Typically `onClose` is used to set state in the parent component, * which is used to control the `Snackbar` `open` prop. * The `reason` parameter can optionally be used to control the response to `onClose`, * for example ignoring `clickaway`. * * @param {object} event The event source of the callback * @param {string} reason Can be:`"timeout"` (`autoHideDuration` expired) or: `"clickaway"` */ onClose: PropTypes.func, /** * Callback fired before the transition is entering. */ onEnter: PropTypes.func, /** * Callback fired when the transition has entered. */ onEntered: PropTypes.func, /** * Callback fired when the transition is entering. */ onEntering: PropTypes.func, /** * Callback fired before the transition is exiting. */ onExit: PropTypes.func, /** * Callback fired when the transition has exited. */ onExited: PropTypes.func, /** * Callback fired when the transition is exiting. */ onExiting: PropTypes.func, /** * @ignore */ onMouseEnter: PropTypes.func, /** * @ignore */ onMouseLeave: PropTypes.func, /** * If true, `Snackbar` is open. */ open: PropTypes.bool, /** * The number of milliseconds to wait before dismissing after user interaction. * If `autoHideDuration` property isn't specified, it does nothing. * If `autoHideDuration` property is specified but `resumeHideDuration` isn't, * we default to `autoHideDuration / 2` ms. */ resumeHideDuration: PropTypes.number, /** * Transition component. */ TransitionComponent: PropTypes.oneOfType([PropTypes.string, PropTypes.func, PropTypes.object]), /** * The duration for the transition, in milliseconds. * You may specify a single timeout for all transitions, or individually with an object. */ transitionDuration: PropTypes.oneOfType([PropTypes.number, PropTypes.shape({ enter: PropTypes.number, exit: PropTypes.number })]), /** * Properties applied to the `Transition` element. */ TransitionProps: PropTypes.object } : {}; Snackbar.defaultProps = { anchorOrigin: { vertical: 'bottom', horizontal: 'center' }, disableWindowBlurListener: false, TransitionComponent: Slide, transitionDuration: { enter: duration.enteringScreen, exit: duration.leavingScreen } }; export default withStyles(styles, { flip: false, name: 'MuiSnackbar' })(Snackbar);
import {getTemplate} from '../i/iEssential.js'; const articleTemplate = ` <h2 class="article__title"> <a href="/article.html?id={_id}">{title}</a> </h2> <div class="article__description"> {about} </div> <div class="article__author"> {authorName} <a href="mailto:{authorEmail}">{authorEmail}</a> </div> <div class="article__footer"> {created} </div> `, fullArticle = ` <div class="article__author"> {authorName} <a href="mailto:{authorEmail}">{authorEmail}</a> </div> <div class="article__footer"> {created} </div> <div class="article__description"> {text} </div> <div class="article__tags"> {tags} </div> `; export default function createArticle(articleData, desc = true) { const article = document.createElement('article'), { author, about, _id, guid, created, text, tags } = articleData, title = `Article ${guid}`; if (desc) { article.innerHTML = getTemplate(articleTemplate, { about, authorName: `${author.first} ${author.last}`, authorEmail: author.email, created, title, _id }); } else { article.innerHTML = getTemplate(fullArticle, { authorName: `${author.first} ${author.last}`, authorEmail: author.email, created, _id, text: text.split('\n\n') .map(t => `<p>${t}</p>`) .join(''), tags: tags.join(', ') }); } article.classList.add('article'); return article; }
"use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; result["default"] = mod; return result; }; Object.defineProperty(exports, "__esModule", { value: true }); const web3Utils = __importStar(require("web3-utils")); class Common { constructor(isOldWeb3, web3) { this.getNetworkId = () => __awaiter(this, void 0, void 0, function* () { let id; if (this.isOldWeb3) { this.web3.version.getNetwork((err, netId) => { if (err) { throw err; } id = netId; }); } else { id = yield this.web3.eth.net.getId(); } return id; }); this.getAccounts = () => __awaiter(this, void 0, void 0, function* () { if (this.isOldWeb3) { return new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () { return resolve(yield this.web3.eth.accounts); })); } return this.web3.eth.getAccounts(); }); this.getBalance = (address) => __awaiter(this, void 0, void 0, function* () { if (this.isOldWeb3) { return new Promise((resolve, reject) => { this.web3.eth.getBalance(address, (err, bal) => { if (err) { return reject(err); } return resolve(web3Utils.fromWei(`${bal}`)); }); }); } const balance = yield this.web3.eth.getBalance(address); return web3Utils.fromWei(balance, 'ether'); }); this.getBalancesWithAccounts = () => __awaiter(this, void 0, void 0, function* () { const addresses = yield this.getAccounts(); if (!addresses) { return []; } const accounts = []; for (const address of addresses) { const etherBalance = yield this.getBalance(address); accounts.push({ address, etherBalance: Number(etherBalance), }); } return accounts; }); this.call = (params) => __awaiter(this, void 0, void 0, function* () { return this.web3.eth.call(params); }); this.sendTransaction = (params) => __awaiter(this, void 0, void 0, function* () { return this.web3.eth.sendTransaction(params); }); this.sendSignedTransaction = (rawTransaction) => { return this.getResponseWhenMined(this.web3.eth.sendSignedTransaction(rawTransaction)); }; this.getTxReceipt = (txHash) => __awaiter(this, void 0, void 0, function* () { return this.web3.eth.getTransactionReceipt(txHash); }); this.getResponseWhenMined = (functionCall) => __awaiter(this, void 0, void 0, function* () { let txReceipt; let txHash; const response = yield functionCall .on('receipt', (Receipt) => { txReceipt = Receipt; }) .on('error', (error) => { throw error; }) .on('transactionHash', (TxHash) => { txHash = TxHash; // console.log({ txHash }) }); return { txReceipt, txHash, response, }; }); this.deploy = ({ code, abi, from, gas = 2000000, gasPrice = 10000000000, args, privateKey }) => __awaiter(this, void 0, void 0, function* () { if (this.isOldWeb3) { return this.oldWeb3Deploy({ abi, code, from, gas, args, }); } if (privateKey) { const { rawTransaction } = yield this.signTransaction({ from, data: code + (yield this.encodeArguments(args, 32)), gas, gasPrice: yield this.web3.eth.gasPrice, }, privateKey); return this.sendSignedTransaction(rawTransaction); } const contract = new this.web3.eth.Contract(abi); return this.getResponseWhenMined(contract .deploy({ data: code, arguments: args, }) .send({ from, gas, gasPrice, })); }); this.getContract = (abi, address) => { return new this.web3.eth.Contract(abi, address); }; this.executeContractFunction = ({ func, to, from, gas = 2000000, gasPrice, value, privateKey }) => __awaiter(this, void 0, void 0, function* () { if (privateKey) { const data = yield func.encodeABI(); const { rawTransaction } = yield this.signTransaction({ to, data, gas, }, privateKey); return this.sendSignedTransaction(rawTransaction); } return this.getResponseWhenMined(func.send({ from, gas, value, })); }); this.estimateGas = (params) => __awaiter(this, void 0, void 0, function* () { return this.web3.eth.estimateGas(params); }); this.encodeArguments = (params, length) => { let res = params.map(arg => this.web3.utils.padLeft(this.web3.utils.toHex(arg).substring(2), length)); return res; }; this.signTransaction = (rawTx, privateKey) => { return new Promise((resolve, reject) => { this.web3.eth.accounts.signTransaction(rawTx, privateKey, (err, signed) => { if (err) { return reject(err); } return resolve(signed); }); }); }; // oldWeb3GetResponseWhenMined = async (txHash: string) => { // const maxTries = 40 // let tries = 0 // while (tries < maxTries) { // tries++ // try { // if (process.env.NODE_ENV !== 'production') { // console.log('checking...') // } // let receipt = await this.getTxReceipt(txHash) // if (receipt) { // return receipt // } // await sleep(5000) // } catch (e) { // throw e // } // } // throw new Error('Request timed out') // } this.oldWeb3Deploy = ({ abi, code, from, gas, args }) => __awaiter(this, void 0, void 0, function* () { return new Promise((resolve, reject) => { if (args && args.length > 0) { this.web3.eth.contract(abi).new(args, { from, data: code, gas, }, (err, contract) => { if (err) { reject(err); } else if (contract && contract.address) { resolve({ txHash: contract.transactionHash, txReceipt: this.web3.eth.getTransactionReceipt(contract.transactionHash), }); } }); } else { this.web3.eth.contract(abi).new({ from, data: code, gas, }, (err, contract) => { if (err) { reject(err); } else if (contract && contract.address) { resolve({ txHash: contract.transactionHash, txReceipt: this.web3.eth.getTransactionReceipt(contract.transactionHash), }); } }); } }); }); this.newAccount = () => __awaiter(this, void 0, void 0, function* () { const { privateKey, address } = yield this.web3.eth.accounts.create(); return { privateKey, address }; }); this.isOldWeb3 = isOldWeb3; this.web3 = web3; } } exports.default = Common;
from collections import namedtuple import os import tweepy TwitterAuth = namedtuple( "TWITTER", ["consumer_key", "consumer_secret", "access_token", "access_token_secret"], ) def getTwitterCredentials(): return TwitterAuth( consumer_key=os.environ['TWITTER_CONSUMER_KEY'], consumer_secret=os.environ['TWITTER_CONSUMER_SECRET'], access_token=os.environ['TWITTER_ACCESS_TOKEN'], access_token_secret=os.environ['TWITTER_ACCESS_TOKEN_SECRET'], ) def sendTweet(tweet_text: str, image_path=""): """Post some text, and optionally an image to twitter. Args: tweet_text: String, text to post to twitter, must be less than 260 chars image_path: String, path to image on disk to be posted to twitter Returns: tweepy.status object, contains response from twitter request """ TWITTER = getTwitterCredentials() auth = tweepy.OAuthHandler(TWITTER.consumer_key, TWITTER.consumer_secret) auth.set_access_token(TWITTER.access_token, TWITTER.access_token_secret) api = tweepy.API(auth) if image_path: return api.update_with_media(filename=image_path, status=tweet_text) else: return api.update_status(tweet_text) return api.update_status(tweet_text)
!function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define([],e):"object"==typeof exports?exports.fp=e():t.fp=e()}("undefined"!=typeof self?self:this,(function(){return function(t){var e={};function n(r){if(e[r])return e[r].exports;var i=e[r]={i:r,l:!1,exports:{}};return t[r].call(i.exports,i,i.exports,n),i.l=!0,i.exports}return n.m=t,n.c=e,n.d=function(t,e,r){n.o(t,e)||Object.defineProperty(t,e,{enumerable:!0,get:r})},n.r=function(t){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})},n.t=function(t,e){if(1&e&&(t=n(t)),8&e)return t;if(4&e&&"object"==typeof t&&t&&t.__esModule)return t;var r=Object.create(null);if(n.r(r),Object.defineProperty(r,"default",{enumerable:!0,value:t}),2&e&&"string"!=typeof t)for(var i in t)n.d(r,i,function(e){return t[e]}.bind(null,i));return r},n.n=function(t){var e=t&&t.__esModule?function(){return t.default}:function(){return t};return n.d(e,"a",e),e},n.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},n.p="",n(n.s=0)}([function(t,e,n){"use strict";n.r(e);var r={};function i(t){return(i="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t})(t)}n.r(r),n.d(r,"FistGesture",(function(){return j})),n.d(r,"PointRightGesture",(function(){return k}));var o={Thumb:0,Index:1,Middle:2,Ring:3,Pinky:4,all:[0,1,2,3,4],nameMapping:{0:"Thumb",1:"Index",2:"Middle",3:"Ring",4:"Pinky"},pointsMapping:{0:[[0,1],[1,2],[2,3],[3,4]],1:[[0,5],[5,6],[6,7],[7,8]],2:[[0,9],[9,10],[10,11],[11,12]],3:[[0,13],[13,14],[14,15],[15,16]],4:[[0,17],[17,18],[18,19],[19,20]]},getName:function(t){return void 0!==i(this.nameMapping[t])&&this.nameMapping[t]},getPoints:function(t){return void 0!==i(this.pointsMapping[t])&&this.pointsMapping[t]}},a={NoCurl:0,HalfCurl:1,FullCurl:2,nameMapping:{0:"No Curl",1:"Half Curl",2:"Full Curl"},getName:function(t){return void 0!==i(this.nameMapping[t])&&this.nameMapping[t]}},l={VerticalUp:0,VerticalDown:1,HorizontalLeft:2,HorizontalRight:3,DiagonalUpRight:4,DiagonalUpLeft:5,DiagonalDownRight:6,DiagonalDownLeft:7,nameMapping:{0:"Vertical Up",1:"Vertical Down",2:"Horizontal Left",3:"Horizontal Right",4:"Diagonal Up Right",5:"Diagonal Up Left",6:"Diagonal Down Right",7:"Diagonal Down Left"},getName:function(t){return void 0!==i(this.nameMapping[t])&&this.nameMapping[t]}};function u(t,e){var n;if("undefined"==typeof Symbol||null==t[Symbol.iterator]){if(Array.isArray(t)||(n=function(t,e){if(!t)return;if("string"==typeof t)return c(t,e);var n=Object.prototype.toString.call(t).slice(8,-1);"Object"===n&&t.constructor&&(n=t.constructor.name);if("Map"===n||"Set"===n)return Array.from(t);if("Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return c(t,e)}(t))||e&&t&&"number"==typeof t.length){n&&(t=n);var r=0,i=function(){};return{s:i,n:function(){return r>=t.length?{done:!0}:{done:!1,value:t[r++]}},e:function(t){throw t},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 o,a=!0,l=!1;return{s:function(){n=t[Symbol.iterator]()},n:function(){var t=n.next();return a=t.done,t},e:function(t){l=!0,o=t},f:function(){try{a||null==n.return||n.return()}finally{if(l)throw o}}}}function c(t,e){(null==e||e>t.length)&&(e=t.length);for(var n=0,r=new Array(e);n<e;n++)r[n]=t[n];return r}function f(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter((function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable}))),n.push.apply(n,r)}return n}function s(t){for(var e=1;e<arguments.length;e++){var n=null!=arguments[e]?arguments[e]:{};e%2?f(Object(n),!0).forEach((function(e){h(t,e,n[e])})):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):f(Object(n)).forEach((function(e){Object.defineProperty(t,e,Object.getOwnPropertyDescriptor(n,e))}))}return t}function h(t,e,n){return e in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function p(t,e){for(var n=0;n<e.length;n++){var r=e[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(t,r.key,r)}}var y=function(){function t(e){!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),this.options=s(s({},{HALF_CURL_START_LIMIT:60,NO_CURL_START_LIMIT:130,DISTANCE_VOTE_POWER:1.1,SINGLE_ANGLE_VOTE_POWER:.9,TOTAL_ANGLE_VOTE_POWER:1.6}),e)}var e,n,r;return e=t,(n=[{key:"estimate",value:function(t){var e,n=[],r=[],i=u(o.all);try{for(i.s();!(e=i.n()).done;){var a,l=e.value,c=o.getPoints(l),f=[],s=[],h=u(c);try{for(h.s();!(a=h.n()).done;){var p=a.value,y=t[p[0]],v=t[p[1]],d=this.getSlopes(y,v),g=d[0],m=d[1];f.push(g),s.push(m)}}catch(t){h.e(t)}finally{h.f()}n.push(f),r.push(s)}}catch(t){i.e(t)}finally{i.f()}var b,w=[],O=[],M=u(o.all);try{for(M.s();!(b=M.n()).done;){var S=b.value,D=S==o.Thumb?1:0,T=o.getPoints(S),A=t[T[D][0]],R=t[T[D+1][1]],C=t[T[3][1]],_=this.estimateFingerCurl(A,R,C),j=this.calculateFingerDirection(A,R,C,n[S].slice(D));w[S]=_,O[S]=j}}catch(t){M.e(t)}finally{M.f()}return{curls:w,directions:O}}},{key:"getSlopes",value:function(t,e){var n=this.calculateSlope(t[0],t[1],e[0],e[1]);return 2==t.length?n:[n,this.calculateSlope(t[1],t[2],e[1],e[2])]}},{key:"angleOrientationAt",value:function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1,n=0,r=0,i=0;return t>=75&&t<=105?n=1*e:t>=25&&t<=155?r=1*e:i=1*e,[n,r,i]}},{key:"estimateFingerCurl",value:function(t,e,n){var r=t[0]-e[0],i=t[0]-n[0],o=e[0]-n[0],l=t[1]-e[1],u=t[1]-n[1],c=e[1]-n[1],f=t[2]-e[2],s=t[2]-n[2],h=e[2]-n[2],p=Math.sqrt(r*r+l*l+f*f),y=Math.sqrt(i*i+u*u+s*s),v=Math.sqrt(o*o+c*c+h*h),d=(v*v+p*p-y*y)/(2*v*p);d>1?d=1:d<-1&&(d=-1);var g=Math.acos(d);return(g=57.2958*g%180)>this.options.NO_CURL_START_LIMIT?a.NoCurl:g>this.options.HALF_CURL_START_LIMIT?a.HalfCurl:a.FullCurl}},{key:"estimateHorizontalDirection",value:function(t,e,n,r){return r==Math.abs(t)?t>0?l.HorizontalLeft:l.HorizontalRight:r==Math.abs(e)?e>0?l.HorizontalLeft:l.HorizontalRight:n>0?l.HorizontalLeft:l.HorizontalRight}},{key:"estimateVerticalDirection",value:function(t,e,n,r){return r==Math.abs(t)?t<0?l.VerticalDown:l.VerticalUp:r==Math.abs(e)?e<0?l.VerticalDown:l.VerticalUp:n<0?l.VerticalDown:l.VerticalUp}},{key:"estimateDiagonalDirection",value:function(t,e,n,r,i,o,a,u){var c=this.estimateVerticalDirection(t,e,n,r),f=this.estimateHorizontalDirection(i,o,a,u);return c==l.VerticalUp?f==l.HorizontalLeft?l.DiagonalUpLeft:l.DiagonalUpRight:f==l.HorizontalLeft?l.DiagonalDownLeft:l.DiagonalDownRight}},{key:"calculateFingerDirection",value:function(t,e,n,r){var i=t[0]-e[0],o=t[0]-n[0],a=e[0]-n[0],l=t[1]-e[1],c=t[1]-n[1],f=e[1]-n[1],s=Math.max(Math.abs(i),Math.abs(o),Math.abs(a)),h=Math.max(Math.abs(l),Math.abs(c),Math.abs(f)),p=0,y=0,v=0,d=h/(s+1e-5);d>1.5?p+=this.options.DISTANCE_VOTE_POWER:d>.66?y+=this.options.DISTANCE_VOTE_POWER:v+=this.options.DISTANCE_VOTE_POWER;var g=Math.sqrt(i*i+l*l),m=Math.sqrt(o*o+c*c),b=Math.sqrt(a*a+f*f),w=Math.max(g,m,b),O=t[0],M=t[1],S=n[0],D=n[1];w==g?(S=n[0],D=n[1]):w==b&&(O=e[0],M=e[1]);var T=[O,M],A=[S,D],R=this.getSlopes(T,A),C=this.angleOrientationAt(R,this.options.TOTAL_ANGLE_VOTE_POWER);p+=C[0],y+=C[1],v+=C[2];var _,j=u(r);try{for(j.s();!(_=j.n()).done;){var E=_.value,P=this.angleOrientationAt(E,this.options.SINGLE_ANGLE_VOTE_POWER);p+=P[0],y+=P[1],v+=P[2]}}catch(t){j.e(t)}finally{j.f()}return p==Math.max(p,y,v)?this.estimateVerticalDirection(c,l,f,h):v==Math.max(y,v)?this.estimateHorizontalDirection(o,i,a,s):this.estimateDiagonalDirection(c,l,f,h,o,i,a,s)}},{key:"calculateSlope",value:function(t,e,n,r){var i=(e-r)/(t-n),o=180*Math.atan(i)/Math.PI;return o<=0?o=-o:o>0&&(o=180-o),o}}])&&p(e.prototype,n),r&&p(e,r),t}();function v(t,e){var n;if("undefined"==typeof Symbol||null==t[Symbol.iterator]){if(Array.isArray(t)||(n=function(t,e){if(!t)return;if("string"==typeof t)return d(t,e);var n=Object.prototype.toString.call(t).slice(8,-1);"Object"===n&&t.constructor&&(n=t.constructor.name);if("Map"===n||"Set"===n)return Array.from(t);if("Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return d(t,e)}(t))||e&&t&&"number"==typeof t.length){n&&(t=n);var r=0,i=function(){};return{s:i,n:function(){return r>=t.length?{done:!0}:{done:!1,value:t[r++]}},e:function(t){throw t},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 o,a=!0,l=!1;return{s:function(){n=t[Symbol.iterator]()},n:function(){var t=n.next();return a=t.done,t},e:function(t){l=!0,o=t},f:function(){try{a||null==n.return||n.return()}finally{if(l)throw o}}}}function d(t,e){(null==e||e>t.length)&&(e=t.length);for(var n=0,r=new Array(e);n<e;n++)r[n]=t[n];return r}function g(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function m(t,e){for(var n=0;n<e.length;n++){var r=e[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(t,r.key,r)}}var b=function(){function t(e){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};g(this,t),this.estimator=new y(n),this.gestures=e}var e,n,r;return e=t,(n=[{key:"estimate",value:function(t,e){var n,r=[],i=this.estimator.estimate(t),u=[],c=v(o.all);try{for(c.s();!(n=c.n()).done;){var f=n.value;u.push([o.getName(f),a.getName(i.curls[f]),l.getName(i.directions[f])])}}catch(t){c.e(t)}finally{c.f()}var s,h=v(this.gestures);try{for(h.s();!(s=h.n()).done;){var p=s.value,y=p.matchAgainst(i.curls,i.directions);y>=e&&r.push({name:p.name,confidence:y})}}catch(t){h.e(t)}finally{h.f()}return{poseData:u,gestures:r}}}])&&m(e.prototype,n),r&&m(e,r),t}();function w(t,e){return function(t){if(Array.isArray(t))return t}(t)||function(t,e){if("undefined"==typeof Symbol||!(Symbol.iterator in Object(t)))return;var n=[],r=!0,i=!1,o=void 0;try{for(var a,l=t[Symbol.iterator]();!(r=(a=l.next()).done)&&(n.push(a.value),!e||n.length!==e);r=!0);}catch(t){i=!0,o=t}finally{try{r||null==l.return||l.return()}finally{if(i)throw o}}return n}(t,e)||M(t,e)||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 O(t,e){var n;if("undefined"==typeof Symbol||null==t[Symbol.iterator]){if(Array.isArray(t)||(n=M(t))||e&&t&&"number"==typeof t.length){n&&(t=n);var r=0,i=function(){};return{s:i,n:function(){return r>=t.length?{done:!0}:{done:!1,value:t[r++]}},e:function(t){throw t},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 o,a=!0,l=!1;return{s:function(){n=t[Symbol.iterator]()},n:function(){var t=n.next();return a=t.done,t},e:function(t){l=!0,o=t},f:function(){try{a||null==n.return||n.return()}finally{if(l)throw o}}}}function M(t,e){if(t){if("string"==typeof t)return S(t,e);var n=Object.prototype.toString.call(t).slice(8,-1);return"Object"===n&&t.constructor&&(n=t.constructor.name),"Map"===n||"Set"===n?Array.from(t):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?S(t,e):void 0}}function S(t,e){(null==e||e>t.length)&&(e=t.length);for(var n=0,r=new Array(e);n<e;n++)r[n]=t[n];return r}function D(t,e){for(var n=0;n<e.length;n++){var r=e[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(t,r.key,r)}}var T=function(){function t(e){!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),this.name=e,this.curls={},this.directions={},this.weights=[1,1,1,1,1],this.weightsRelative=[1,1,1,1,1]}var e,n,r;return e=t,(n=[{key:"addCurl",value:function(t,e,n){void 0===this.curls[t]&&(this.curls[t]=[]),this.curls[t].push([e,n])}},{key:"addDirection",value:function(t,e,n){void 0===this.directions[t]&&(this.directions[t]=[]),this.directions[t].push([e,n])}},{key:"setWeight",value:function(t,e){this.weights[t]=e;var n=this.weights.reduce((function(t,e){return t+e}),0);this.weightsRelative=this.weights.map((function(t){return 5*t/n}))}},{key:"matchAgainst",value:function(t,e){var n=0;for(var r in t){var i=t[r],o=this.curls[r];if(void 0!==o){var a,l=O(o);try{for(l.s();!(a=l.n()).done;){var u=w(a.value,2),c=u[0],f=u[1];if(i==c){n+=f*this.weightsRelative[r];break}}}catch(t){l.e(t)}finally{l.f()}}else n+=this.weightsRelative[r]}for(var s in e){var h=e[s],p=this.directions[s];if(void 0!==p){var y,v=O(p);try{for(v.s();!(y=v.n()).done;){var d=w(y.value,2),g=d[0],m=d[1];if(h==g){n+=m*this.weightsRelative[s];break}}}catch(t){v.e(t)}finally{v.f()}}else n+=this.weightsRelative[s]}return n}}])&&D(e.prototype,n),r&&D(e,r),t}(),A=new T("fist");A.addCurl(o.Thumb,a.FullCurl,1);for(var R=0,C=[o.Index,o.Middle,o.Ring,o.Pinky];R<C.length;R++){var _=C[R];A.addCurl(_,a.FullCurl,1)}var j=A,E=new T("point_right");E.addCurl(o.Index,a.NoCurl,1),E.addCurl(o.Index,l.HorizontalRight,1),E.addCurl(o.Middle,a.NoCurl,1),E.addCurl(o.Middle,l.HorizontalRight,1);for(var P=0,I=[o.Thumb,o.Ring,o.Pinky];P<I.length;P++){var L=I[P];E.addCurl(L,a.FullCurl,1)}var k=E;e.default={GestureEstimator:b,GestureDescription:T,Finger:o,FingerCurl:a,FingerDirection:l,Gestures:r}}]).default}));
# coding: utf-8 from time import perf_counter, sleep class FPSLimiter: _previous_time: float _start_of_second: float _frame_count: int = 0 _fps: int = 0 def __init__(self, max_fps : int = 60) -> None: self.set_max_fps(max_fps) self._previous_time = perf_counter() self._start_of_second = self._previous_time def set_max_fps(self, max_fps : int = 60) -> None: self._max_fps = max_fps self._interval = 1./max_fps def wait(self) -> None: t : float = perf_counter() self._frame_count += 1 if t - self._start_of_second >= 1.: self._fps = self._frame_count self._frame_count = 0 self._start_of_second = t dt : float = t - self._previous_time if(dt < self._interval): sleep_interval : float = self._interval - dt correct_sleep_interval : float = min(self._interval, sleep_interval) sleep(correct_sleep_interval) self._previous_time = perf_counter() def get_fps(self) -> int: return self._fps
'use Strict'; angular.module('myHeadview',[]);
""" socket server request handlers leveraged by core servers. """ import logging import os import shlex import shutil import socketserver import sys import threading import time from itertools import repeat from queue import Empty, Queue from core import utils from core.api.tlv import coreapi, dataconversion, structutils from core.config import ConfigShim from core.emulator.data import ConfigData, EventData, ExceptionData, FileData from core.emulator.emudata import InterfaceData, LinkOptions, NodeOptions from core.emulator.enumerations import ( ConfigDataTypes, ConfigFlags, ConfigTlvs, EventTlvs, EventTypes, ExceptionTlvs, ExecuteTlvs, FileTlvs, LinkTlvs, LinkTypes, MessageFlags, MessageTypes, NodeTlvs, NodeTypes, RegisterTlvs, SessionTlvs, ) from core.errors import CoreCommandError, CoreError from core.location.mobility import BasicRangeModel from core.nodes.network import WlanNode from core.services.coreservices import ServiceManager, ServiceShim class CoreHandler(socketserver.BaseRequestHandler): """ The CoreHandler class uses the RequestHandler class for servicing requests. """ def __init__(self, request, client_address, server): """ Create a CoreRequestHandler instance. :param request: request object :param str client_address: client address :param CoreServer server: core server instance """ self.done = False self.message_handlers = { MessageTypes.NODE.value: self.handle_node_message, MessageTypes.LINK.value: self.handle_link_message, MessageTypes.EXECUTE.value: self.handle_execute_message, MessageTypes.REGISTER.value: self.handle_register_message, MessageTypes.CONFIG.value: self.handle_config_message, MessageTypes.FILE.value: self.handle_file_message, MessageTypes.INTERFACE.value: self.handle_interface_message, MessageTypes.EVENT.value: self.handle_event_message, MessageTypes.SESSION.value: self.handle_session_message, } self.message_queue = Queue() self.node_status_request = {} self._shutdown_lock = threading.Lock() self._sessions_lock = threading.Lock() self.handler_threads = [] num_threads = int(server.config["numthreads"]) if num_threads < 1: raise ValueError(f"invalid number of threads: {num_threads}") logging.debug("launching core server handler threads: %s", num_threads) for _ in range(num_threads): thread = threading.Thread(target=self.handler_thread) self.handler_threads.append(thread) thread.start() self.session = None self.session_clients = {} self.coreemu = server.coreemu utils.close_onexec(request.fileno()) socketserver.BaseRequestHandler.__init__(self, request, client_address, server) def setup(self): """ Client has connected, set up a new connection. :return: nothing """ logging.debug("new TCP connection: %s", self.client_address) def finish(self): """ Client has disconnected, end this request handler and disconnect from the session. Shutdown sessions that are not running. :return: nothing """ logging.debug("finishing request handler") logging.debug("remaining message queue size: %s", self.message_queue.qsize()) # give some time for message queue to deplete timeout = 10 wait = 0 while not self.message_queue.empty(): logging.debug("waiting for message queue to empty: %s seconds", wait) time.sleep(1) wait += 1 if wait == timeout: logging.warning("queue failed to be empty, finishing request handler") break logging.info("client disconnected: notifying threads") self.done = True for thread in self.handler_threads: logging.info("waiting for thread: %s", thread.getName()) thread.join(timeout) if thread.is_alive(): logging.warning( "joining %s failed: still alive after %s sec", thread.getName(), timeout, ) logging.info("connection closed: %s", self.client_address) if self.session: # remove client from session broker and shutdown if there are no clients self.remove_session_handlers() clients = self.session_clients[self.session.id] clients.remove(self) if not clients and not self.session.is_active(): logging.info( "no session clients left and not active, initiating shutdown" ) self.coreemu.delete_session(self.session.id) return socketserver.BaseRequestHandler.finish(self) def session_message(self, flags=0): """ Build CORE API Sessions message based on current session info. :param int flags: message flags :return: session message """ id_list = [] name_list = [] file_list = [] node_count_list = [] date_list = [] thumb_list = [] num_sessions = 0 with self._sessions_lock: for _id in self.coreemu.sessions: session = self.coreemu.sessions[_id] num_sessions += 1 id_list.append(str(_id)) name = session.name if not name: name = "" name_list.append(name) file_name = session.file_name if not file_name: file_name = "" file_list.append(file_name) node_count_list.append(str(session.get_node_count())) date_list.append(time.ctime(session._state_time)) thumb = session.thumbnail if not thumb: thumb = "" thumb_list.append(thumb) session_ids = "|".join(id_list) names = "|".join(name_list) files = "|".join(file_list) node_counts = "|".join(node_count_list) dates = "|".join(date_list) thumbs = "|".join(thumb_list) if num_sessions > 0: tlv_data = b"" if len(session_ids) > 0: tlv_data += coreapi.CoreSessionTlv.pack( SessionTlvs.NUMBER.value, session_ids ) if len(names) > 0: tlv_data += coreapi.CoreSessionTlv.pack(SessionTlvs.NAME.value, names) if len(files) > 0: tlv_data += coreapi.CoreSessionTlv.pack(SessionTlvs.FILE.value, files) if len(node_counts) > 0: tlv_data += coreapi.CoreSessionTlv.pack( SessionTlvs.NODE_COUNT.value, node_counts ) if len(dates) > 0: tlv_data += coreapi.CoreSessionTlv.pack(SessionTlvs.DATE.value, dates) if len(thumbs) > 0: tlv_data += coreapi.CoreSessionTlv.pack(SessionTlvs.THUMB.value, thumbs) message = coreapi.CoreSessionMessage.pack(flags, tlv_data) else: message = None return message def handle_broadcast_event(self, event_data): """ Callback to handle an event broadcast out from a session. :param core.emulator.data.EventData event_data: event data to handle :return: nothing """ logging.debug("handling broadcast event: %s", event_data) tlv_data = structutils.pack_values( coreapi.CoreEventTlv, [ (EventTlvs.NODE, event_data.node), (EventTlvs.TYPE, event_data.event_type), (EventTlvs.NAME, event_data.name), (EventTlvs.DATA, event_data.data), (EventTlvs.TIME, event_data.time), (EventTlvs.SESSION, event_data.session), ], ) message = coreapi.CoreEventMessage.pack(0, tlv_data) try: self.sendall(message) except IOError: logging.exception("error sending event message") def handle_broadcast_file(self, file_data): """ Callback to handle a file broadcast out from a session. :param core.emulator.data.FileData file_data: file data to handle :return: nothing """ logging.debug("handling broadcast file: %s", file_data) tlv_data = structutils.pack_values( coreapi.CoreFileTlv, [ (FileTlvs.NODE, file_data.node), (FileTlvs.NAME, file_data.name), (FileTlvs.MODE, file_data.mode), (FileTlvs.NUMBER, file_data.number), (FileTlvs.TYPE, file_data.type), (FileTlvs.SOURCE_NAME, file_data.source), (FileTlvs.SESSION, file_data.session), (FileTlvs.DATA, file_data.data), (FileTlvs.COMPRESSED_DATA, file_data.compressed_data), ], ) message = coreapi.CoreFileMessage.pack(file_data.message_type, tlv_data) try: self.sendall(message) except IOError: logging.exception("error sending file message") def handle_broadcast_config(self, config_data): """ Callback to handle a config broadcast out from a session. :param core.emulator.data.ConfigData config_data: config data to handle :return: nothing """ logging.debug("handling broadcast config: %s", config_data) message = dataconversion.convert_config(config_data) try: self.sendall(message) except IOError: logging.exception("error sending config message") def handle_broadcast_exception(self, exception_data): """ Callback to handle an exception broadcast out from a session. :param core.emulator.data.ExceptionData exception_data: exception data to handle :return: nothing """ logging.debug("handling broadcast exception: %s", exception_data) tlv_data = structutils.pack_values( coreapi.CoreExceptionTlv, [ (ExceptionTlvs.NODE, exception_data.node), (ExceptionTlvs.SESSION, exception_data.session), (ExceptionTlvs.LEVEL, exception_data.level.value), (ExceptionTlvs.SOURCE, exception_data.source), (ExceptionTlvs.DATE, exception_data.date), (ExceptionTlvs.TEXT, exception_data.text), ], ) message = coreapi.CoreExceptionMessage.pack(0, tlv_data) try: self.sendall(message) except IOError: logging.exception("error sending exception message") def handle_broadcast_node(self, node_data): """ Callback to handle an node broadcast out from a session. :param core.emulator.data.NodeData node_data: node data to handle :return: nothing """ logging.debug("handling broadcast node: %s", node_data) message = dataconversion.convert_node(node_data) try: self.sendall(message) except IOError: logging.exception("error sending node message") def handle_broadcast_link(self, link_data): """ Callback to handle an link broadcast out from a session. :param core.emulator.data.LinkData link_data: link data to handle :return: nothing """ logging.debug("handling broadcast link: %s", link_data) per = "" if link_data.per is not None: per = str(link_data.per) dup = "" if link_data.dup is not None: dup = str(link_data.dup) tlv_data = structutils.pack_values( coreapi.CoreLinkTlv, [ (LinkTlvs.N1_NUMBER, link_data.node1_id), (LinkTlvs.N2_NUMBER, link_data.node2_id), (LinkTlvs.DELAY, link_data.delay), (LinkTlvs.BANDWIDTH, link_data.bandwidth), (LinkTlvs.PER, per), (LinkTlvs.DUP, dup), (LinkTlvs.JITTER, link_data.jitter), (LinkTlvs.MER, link_data.mer), (LinkTlvs.BURST, link_data.burst), (LinkTlvs.SESSION, link_data.session), (LinkTlvs.MBURST, link_data.mburst), (LinkTlvs.TYPE, link_data.link_type), (LinkTlvs.GUI_ATTRIBUTES, link_data.gui_attributes), (LinkTlvs.UNIDIRECTIONAL, link_data.unidirectional), (LinkTlvs.EMULATION_ID, link_data.emulation_id), (LinkTlvs.NETWORK_ID, link_data.network_id), (LinkTlvs.KEY, link_data.key), (LinkTlvs.INTERFACE1_NUMBER, link_data.interface1_id), (LinkTlvs.INTERFACE1_NAME, link_data.interface1_name), (LinkTlvs.INTERFACE1_IP4, link_data.interface1_ip4), (LinkTlvs.INTERFACE1_IP4_MASK, link_data.interface1_ip4_mask), (LinkTlvs.INTERFACE1_MAC, link_data.interface1_mac), (LinkTlvs.INTERFACE1_IP6, link_data.interface1_ip6), (LinkTlvs.INTERFACE1_IP6_MASK, link_data.interface1_ip6_mask), (LinkTlvs.INTERFACE2_NUMBER, link_data.interface2_id), (LinkTlvs.INTERFACE2_NAME, link_data.interface2_name), (LinkTlvs.INTERFACE2_IP4, link_data.interface2_ip4), (LinkTlvs.INTERFACE2_IP4_MASK, link_data.interface2_ip4_mask), (LinkTlvs.INTERFACE2_MAC, link_data.interface2_mac), (LinkTlvs.INTERFACE2_IP6, link_data.interface2_ip6), (LinkTlvs.INTERFACE2_IP6_MASK, link_data.interface2_ip6_mask), (LinkTlvs.OPAQUE, link_data.opaque), ], ) message = coreapi.CoreLinkMessage.pack(link_data.message_type, tlv_data) try: self.sendall(message) except IOError: logging.exception("error sending Event Message") def register(self): """ Return a Register Message :return: register message data """ logging.info( "GUI has connected to session %d at %s", self.session.id, time.ctime() ) tlv_data = b"" tlv_data += coreapi.CoreRegisterTlv.pack( RegisterTlvs.EXECUTE_SERVER.value, "core-daemon" ) tlv_data += coreapi.CoreRegisterTlv.pack( RegisterTlvs.EMULATION_SERVER.value, "core-daemon" ) tlv_data += coreapi.CoreRegisterTlv.pack(RegisterTlvs.UTILITY.value, "broker") tlv_data += coreapi.CoreRegisterTlv.pack( self.session.location.config_type, self.session.location.name ) tlv_data += coreapi.CoreRegisterTlv.pack( self.session.mobility.config_type, self.session.mobility.name ) for model_name in self.session.mobility.models: model_class = self.session.mobility.models[model_name] tlv_data += coreapi.CoreRegisterTlv.pack( model_class.config_type, model_class.name ) tlv_data += coreapi.CoreRegisterTlv.pack( self.session.services.config_type, self.session.services.name ) tlv_data += coreapi.CoreRegisterTlv.pack( self.session.emane.config_type, self.session.emane.name ) for model_name in self.session.emane.models: model_class = self.session.emane.models[model_name] tlv_data += coreapi.CoreRegisterTlv.pack( model_class.config_type, model_class.name ) tlv_data += coreapi.CoreRegisterTlv.pack( self.session.options.config_type, self.session.options.name ) tlv_data += coreapi.CoreRegisterTlv.pack(RegisterTlvs.UTILITY.value, "metadata") return coreapi.CoreRegMessage.pack(MessageFlags.ADD.value, tlv_data) def sendall(self, data): """ Send raw data to the other end of this TCP connection using socket"s sendall(). :param data: data to send over request socket :return: data sent """ return self.request.sendall(data) def receive_message(self): """ Receive data and return a CORE API message object. :return: received message :rtype: core.api.tlv.coreapi.CoreMessage """ try: header = self.request.recv(coreapi.CoreMessage.header_len) except IOError as e: raise IOError(f"error receiving header ({e})") if len(header) != coreapi.CoreMessage.header_len: if len(header) == 0: raise EOFError("client disconnected") else: raise IOError("invalid message header size") message_type, message_flags, message_len = coreapi.CoreMessage.unpack_header( header ) if message_len == 0: logging.warning("received message with no data") data = b"" while len(data) < message_len: data += self.request.recv(message_len - len(data)) if len(data) > message_len: error_message = f"received message length does not match received data ({len(data)} != {message_len})" logging.error(error_message) raise IOError(error_message) try: message_class = coreapi.CLASS_MAP[message_type] message = message_class(message_flags, header, data) except KeyError: message = coreapi.CoreMessage(message_flags, header, data) message.message_type = message_type logging.exception("unimplemented core message type: %s", message.type_str()) return message def queue_message(self, message): """ Queue an API message for later processing. :param message: message to queue :return: nothing """ logging.debug( "queueing msg (queuedtimes = %s): type %s", message.queuedtimes, MessageTypes(message.message_type), ) self.message_queue.put(message) def handler_thread(self): """ CORE API message handling loop that is spawned for each server thread; get CORE API messages from the incoming message queue, and call handlemsg() for processing. :return: nothing """ while not self.done: try: message = self.message_queue.get(timeout=1) self.handle_message(message) except Empty: pass def handle_message(self, message): """ Handle an incoming message; dispatch based on message type, optionally sending replies. :param message: message to handle :return: nothing """ logging.debug( "%s handling message:\n%s", threading.currentThread().getName(), message ) # provide to sdt, if enabled if self.session and self.session.sdt.is_enabled(): self.session.sdt.handle_distributed(message) if message.message_type not in self.message_handlers: logging.error("no handler for message type: %s", message.type_str()) return message_handler = self.message_handlers[message.message_type] try: # TODO: this needs to be removed, make use of the broadcast message methods replies = message_handler(message) self.dispatch_replies(replies, message) except Exception: logging.exception( "%s: exception while handling message: %s", threading.currentThread().getName(), message, ) def dispatch_replies(self, replies, message): """ Dispatch replies by CORE to message msg previously received from the client. :param list replies: reply messages to dispatch :param message: message for replies :return: nothing """ for reply in replies: message_type, message_flags, message_length = coreapi.CoreMessage.unpack_header( reply ) try: reply_message = coreapi.CLASS_MAP[message_type]( message_flags, reply[: coreapi.CoreMessage.header_len], reply[coreapi.CoreMessage.header_len :], ) except KeyError: # multiple TLVs of same type cause KeyError exception reply_message = f"CoreMessage (type {message_type} flags {message_flags} length {message_length})" logging.debug("sending reply:\n%s", reply_message) try: self.sendall(reply) except IOError: logging.exception("error dispatching reply") def handle(self): """ Handle a new connection request from a client. Dispatch to the recvmsg() method for receiving data into CORE API messages, and add them to an incoming message queue. :return: nothing """ # use port as session id port = self.request.getpeername()[1] # TODO: add shutdown handler for session self.session = self.coreemu.create_session(port) logging.debug("created new session for client: %s", self.session.id) clients = self.session_clients.setdefault(self.session.id, []) clients.append(self) # add handlers for various data self.add_session_handlers() # set initial session state self.session.set_state(EventTypes.DEFINITION_STATE) while True: try: message = self.receive_message() except EOFError: logging.info("client disconnected") break except IOError: logging.exception("error receiving message") break message.queuedtimes = 0 self.queue_message(message) # delay is required for brief connections, allow session joining if message.message_type == MessageTypes.SESSION.value: time.sleep(0.125) # broadcast node/link messages to other connected clients if message.message_type not in [ MessageTypes.NODE.value, MessageTypes.LINK.value, ]: continue clients = self.session_clients[self.session.id] for client in clients: if client == self: continue logging.debug("BROADCAST TO OTHER CLIENT: %s", client) client.sendall(message.raw_message) def send_exception(self, level, source, text, node=None): """ Sends an exception for display within the GUI. :param core.emulator.enumerations.ExceptionLevel level: level for exception :param str source: source where exception came from :param str text: details about exception :param int node: node id, if related to a specific node :return: """ exception_data = ExceptionData( session=str(self.session.id), node=node, date=time.ctime(), level=level.value, source=source, text=text, ) self.handle_broadcast_exception(exception_data) def add_session_handlers(self): logging.debug("adding session broadcast handlers") self.session.event_handlers.append(self.handle_broadcast_event) self.session.exception_handlers.append(self.handle_broadcast_exception) self.session.node_handlers.append(self.handle_broadcast_node) self.session.link_handlers.append(self.handle_broadcast_link) self.session.file_handlers.append(self.handle_broadcast_file) self.session.config_handlers.append(self.handle_broadcast_config) def remove_session_handlers(self): logging.debug("removing session broadcast handlers") self.session.event_handlers.remove(self.handle_broadcast_event) self.session.exception_handlers.remove(self.handle_broadcast_exception) self.session.node_handlers.remove(self.handle_broadcast_node) self.session.link_handlers.remove(self.handle_broadcast_link) self.session.file_handlers.remove(self.handle_broadcast_file) self.session.config_handlers.remove(self.handle_broadcast_config) def handle_node_message(self, message): """ Node Message handler :param core.api.tlv.coreapi.CoreNodeMessage message: node message :return: replies to node message """ replies = [] if ( message.flags & MessageFlags.ADD.value and message.flags & MessageFlags.DELETE.value ): logging.warning("ignoring invalid message: add and delete flag both set") return () node_type = None node_type_value = message.get_tlv(NodeTlvs.TYPE.value) if node_type_value is not None: node_type = NodeTypes(node_type_value) node_id = message.get_tlv(NodeTlvs.NUMBER.value) options = NodeOptions( name=message.get_tlv(NodeTlvs.NAME.value), model=message.get_tlv(NodeTlvs.MODEL.value), ) options.set_position( x=message.get_tlv(NodeTlvs.X_POSITION.value), y=message.get_tlv(NodeTlvs.Y_POSITION.value), ) lat = message.get_tlv(NodeTlvs.LATITUDE.value) if lat is not None: lat = float(lat) lon = message.get_tlv(NodeTlvs.LONGITUDE.value) if lon is not None: lon = float(lon) alt = message.get_tlv(NodeTlvs.ALTITUDE.value) if alt is not None: alt = float(alt) options.set_location(lat=lat, lon=lon, alt=alt) options.icon = message.get_tlv(NodeTlvs.ICON.value) options.canvas = message.get_tlv(NodeTlvs.CANVAS.value) options.opaque = message.get_tlv(NodeTlvs.OPAQUE.value) options.server = message.get_tlv(NodeTlvs.EMULATION_SERVER.value) services = message.get_tlv(NodeTlvs.SERVICES.value) if services: options.services = services.split("|") if message.flags & MessageFlags.ADD.value: node = self.session.add_node(node_type, node_id, options) if node: if message.flags & MessageFlags.STRING.value: self.node_status_request[node.id] = True if self.session.state == EventTypes.RUNTIME_STATE.value: self.send_node_emulation_id(node.id) elif message.flags & MessageFlags.DELETE.value: with self._shutdown_lock: result = self.session.delete_node(node_id) # if we deleted a node broadcast out its removal if result and message.flags & MessageFlags.STRING.value: tlvdata = b"" tlvdata += coreapi.CoreNodeTlv.pack(NodeTlvs.NUMBER.value, node_id) flags = MessageFlags.DELETE.value | MessageFlags.LOCAL.value replies.append(coreapi.CoreNodeMessage.pack(flags, tlvdata)) # node update else: self.session.edit_node(node_id, options) return replies def handle_link_message(self, message): """ Link Message handler :param core.api.tlv.coreapi.CoreLinkMessage message: link message to handle :return: link message replies """ node_one_id = message.get_tlv(LinkTlvs.N1_NUMBER.value) node_two_id = message.get_tlv(LinkTlvs.N2_NUMBER.value) interface_one = InterfaceData( _id=message.get_tlv(LinkTlvs.INTERFACE1_NUMBER.value), name=message.get_tlv(LinkTlvs.INTERFACE1_NAME.value), mac=message.get_tlv(LinkTlvs.INTERFACE1_MAC.value), ip4=message.get_tlv(LinkTlvs.INTERFACE1_IP4.value), ip4_mask=message.get_tlv(LinkTlvs.INTERFACE1_IP4_MASK.value), ip6=message.get_tlv(LinkTlvs.INTERFACE1_IP6.value), ip6_mask=message.get_tlv(LinkTlvs.INTERFACE1_IP6_MASK.value), ) interface_two = InterfaceData( _id=message.get_tlv(LinkTlvs.INTERFACE2_NUMBER.value), name=message.get_tlv(LinkTlvs.INTERFACE2_NAME.value), mac=message.get_tlv(LinkTlvs.INTERFACE2_MAC.value), ip4=message.get_tlv(LinkTlvs.INTERFACE2_IP4.value), ip4_mask=message.get_tlv(LinkTlvs.INTERFACE2_IP4_MASK.value), ip6=message.get_tlv(LinkTlvs.INTERFACE2_IP6.value), ip6_mask=message.get_tlv(LinkTlvs.INTERFACE2_IP6_MASK.value), ) link_type = None link_type_value = message.get_tlv(LinkTlvs.TYPE.value) if link_type_value is not None: link_type = LinkTypes(link_type_value) link_options = LinkOptions(_type=link_type) link_options.delay = message.get_tlv(LinkTlvs.DELAY.value) link_options.bandwidth = message.get_tlv(LinkTlvs.BANDWIDTH.value) link_options.session = message.get_tlv(LinkTlvs.SESSION.value) link_options.per = message.get_tlv(LinkTlvs.PER.value) link_options.dup = message.get_tlv(LinkTlvs.DUP.value) link_options.jitter = message.get_tlv(LinkTlvs.JITTER.value) link_options.mer = message.get_tlv(LinkTlvs.MER.value) link_options.burst = message.get_tlv(LinkTlvs.BURST.value) link_options.mburst = message.get_tlv(LinkTlvs.MBURST.value) link_options.gui_attributes = message.get_tlv(LinkTlvs.GUI_ATTRIBUTES.value) link_options.unidirectional = message.get_tlv(LinkTlvs.UNIDIRECTIONAL.value) link_options.emulation_id = message.get_tlv(LinkTlvs.EMULATION_ID.value) link_options.network_id = message.get_tlv(LinkTlvs.NETWORK_ID.value) link_options.key = message.get_tlv(LinkTlvs.KEY.value) link_options.opaque = message.get_tlv(LinkTlvs.OPAQUE.value) if message.flags & MessageFlags.ADD.value: self.session.add_link( node_one_id, node_two_id, interface_one, interface_two, link_options ) elif message.flags & MessageFlags.DELETE.value: self.session.delete_link( node_one_id, node_two_id, interface_one.id, interface_two.id ) else: self.session.update_link( node_one_id, node_two_id, interface_one.id, interface_two.id, link_options, ) return () def handle_execute_message(self, message): """ Execute Message handler :param core.api.tlv.coreapi.CoreExecMessage message: execute message to handle :return: reply messages """ node_num = message.get_tlv(ExecuteTlvs.NODE.value) execute_num = message.get_tlv(ExecuteTlvs.NUMBER.value) execute_time = message.get_tlv(ExecuteTlvs.TIME.value) command = message.get_tlv(ExecuteTlvs.COMMAND.value) # local flag indicates command executed locally, not on a node if node_num is None and not message.flags & MessageFlags.LOCAL.value: raise ValueError("Execute Message is missing node number.") if execute_num is None: raise ValueError("Execute Message is missing execution number.") if execute_time is not None: self.session.add_event(execute_time, node=node_num, name=None, data=command) return () try: node = self.session.get_node(node_num) # build common TLV items for reply tlv_data = b"" if node_num is not None: tlv_data += coreapi.CoreExecuteTlv.pack( ExecuteTlvs.NODE.value, node_num ) tlv_data += coreapi.CoreExecuteTlv.pack( ExecuteTlvs.NUMBER.value, execute_num ) tlv_data += coreapi.CoreExecuteTlv.pack(ExecuteTlvs.COMMAND.value, command) if message.flags & MessageFlags.TTY.value: if node_num is None: raise NotImplementedError # echo back exec message with cmd for spawning interactive terminal if command == "bash": command = "/bin/bash" res = node.termcmdstring(command) tlv_data += coreapi.CoreExecuteTlv.pack(ExecuteTlvs.RESULT.value, res) reply = coreapi.CoreExecMessage.pack(MessageFlags.TTY.value, tlv_data) return (reply,) else: logging.info("execute message with cmd=%s", command) # execute command and send a response if ( message.flags & MessageFlags.STRING.value or message.flags & MessageFlags.TEXT.value ): if message.flags & MessageFlags.LOCAL.value: try: res = utils.cmd(command) status = 0 except CoreCommandError as e: res = e.stderr status = e.returncode else: try: res = node.cmd(command) status = 0 except CoreCommandError as e: res = e.stderr status = e.returncode logging.info( "done exec cmd=%s with status=%d res=(%d bytes)", command, status, len(res), ) if message.flags & MessageFlags.TEXT.value: tlv_data += coreapi.CoreExecuteTlv.pack( ExecuteTlvs.RESULT.value, res ) if message.flags & MessageFlags.STRING.value: tlv_data += coreapi.CoreExecuteTlv.pack( ExecuteTlvs.STATUS.value, status ) reply = coreapi.CoreExecMessage.pack(0, tlv_data) return (reply,) # execute the command with no response else: if message.flags & MessageFlags.LOCAL.value: utils.mute_detach(command) else: node.cmd(command, wait=False) except CoreError: logging.exception("error getting object: %s", node_num) # XXX wait and queue this message to try again later # XXX maybe this should be done differently if not message.flags & MessageFlags.LOCAL.value: time.sleep(0.125) self.queue_message(message) return () def handle_register_message(self, message): """ Register Message Handler :param core.api.tlv.coreapi.CoreRegMessage message: register message to handle :return: reply messages """ replies = [] # execute a Python script or XML file execute_server = message.get_tlv(RegisterTlvs.EXECUTE_SERVER.value) if execute_server: try: logging.info("executing: %s", execute_server) if message.flags & MessageFlags.STRING.value: old_session_ids = set(self.coreemu.sessions.keys()) sys.argv = shlex.split(execute_server) file_name = sys.argv[0] if os.path.splitext(file_name)[1].lower() == ".xml": session = self.coreemu.create_session() try: session.open_xml(file_name) except Exception: self.coreemu.delete_session(session.id) raise else: thread = threading.Thread( target=utils.execute_file, args=( file_name, {"__file__": file_name, "coreemu": self.coreemu}, ), ) thread.daemon = True thread.start() # allow time for session creation time.sleep(0.25) if message.flags & MessageFlags.STRING.value: new_session_ids = set(self.coreemu.sessions.keys()) new_sid = new_session_ids.difference(old_session_ids) try: sid = new_sid.pop() logging.info("executed: %s as session %d", execute_server, sid) except KeyError: logging.info( "executed %s with unknown session ID", execute_server ) return replies logging.debug("checking session %d for RUNTIME state", sid) session = self.coreemu.sessions.get(sid) retries = 10 # wait for session to enter RUNTIME state, to prevent GUI from # connecting while nodes are still being instantiated while session.state != EventTypes.RUNTIME_STATE.value: logging.debug( "waiting for session %d to enter RUNTIME state", sid ) time.sleep(1) retries -= 1 if retries <= 0: logging.debug("session %d did not enter RUNTIME state", sid) return replies tlv_data = coreapi.CoreRegisterTlv.pack( RegisterTlvs.EXECUTE_SERVER.value, execute_server ) tlv_data += coreapi.CoreRegisterTlv.pack( RegisterTlvs.SESSION.value, str(sid) ) message = coreapi.CoreRegMessage.pack(0, tlv_data) replies.append(message) except Exception as e: logging.exception("error executing: %s", execute_server) tlv_data = coreapi.CoreExceptionTlv.pack(ExceptionTlvs.LEVEL.value, 2) tlv_data += coreapi.CoreExceptionTlv.pack( ExceptionTlvs.TEXT.value, str(e) ) message = coreapi.CoreExceptionMessage.pack(0, tlv_data) replies.append(message) return replies gui = message.get_tlv(RegisterTlvs.GUI.value) if gui is None: logging.debug("ignoring Register message") else: # register capabilities with the GUI replies.append(self.register()) replies.append(self.session_message()) return replies def handle_config_message(self, message): """ Configuration Message handler :param core.api.tlv.coreapi.CoreConfMessage message: configuration message to handle :return: reply messages """ # convert config message to standard config data object config_data = ConfigData( node=message.get_tlv(ConfigTlvs.NODE.value), object=message.get_tlv(ConfigTlvs.OBJECT.value), type=message.get_tlv(ConfigTlvs.TYPE.value), data_types=message.get_tlv(ConfigTlvs.DATA_TYPES.value), data_values=message.get_tlv(ConfigTlvs.VALUES.value), captions=message.get_tlv(ConfigTlvs.CAPTIONS.value), bitmap=message.get_tlv(ConfigTlvs.BITMAP.value), possible_values=message.get_tlv(ConfigTlvs.POSSIBLE_VALUES.value), groups=message.get_tlv(ConfigTlvs.GROUPS.value), session=message.get_tlv(ConfigTlvs.SESSION.value), interface_number=message.get_tlv(ConfigTlvs.INTERFACE_NUMBER.value), network_id=message.get_tlv(ConfigTlvs.NETWORK_ID.value), opaque=message.get_tlv(ConfigTlvs.OPAQUE.value), ) logging.debug( "configuration message for %s node %s", config_data.object, config_data.node ) message_type = ConfigFlags(config_data.type) replies = [] # handle session configuration if config_data.object == "all": replies = self.handle_config_all(message_type, config_data) elif config_data.object == self.session.options.name: replies = self.handle_config_session(message_type, config_data) elif config_data.object == self.session.location.name: self.handle_config_location(message_type, config_data) elif config_data.object == "metadata": replies = self.handle_config_metadata(message_type, config_data) elif config_data.object == "broker": self.handle_config_broker(message_type, config_data) elif config_data.object == self.session.services.name: replies = self.handle_config_services(message_type, config_data) elif config_data.object == self.session.mobility.name: self.handle_config_mobility(message_type, config_data) elif config_data.object in self.session.mobility.models: replies = self.handle_config_mobility_models(message_type, config_data) elif config_data.object == self.session.emane.name: replies = self.handle_config_emane(message_type, config_data) elif config_data.object in self.session.emane.models: replies = self.handle_config_emane_models(message_type, config_data) else: raise Exception("no handler for configuration: %s", config_data.object) for reply in replies: self.handle_broadcast_config(reply) return [] def handle_config_all(self, message_type, config_data): replies = [] if message_type == ConfigFlags.RESET: node_id = config_data.node if node_id is not None: self.session.mobility.config_reset(node_id) self.session.emane.config_reset(node_id) else: self.session.location.reset() self.session.services.reset() self.session.mobility.config_reset() self.session.emane.config_reset() else: raise Exception(f"cant handle config all: {message_type}") return replies def handle_config_session(self, message_type, config_data): replies = [] if message_type == ConfigFlags.REQUEST: type_flags = ConfigFlags.NONE.value config = self.session.options.get_configs() config_response = ConfigShim.config_data( 0, None, type_flags, self.session.options, config ) replies.append(config_response) elif message_type != ConfigFlags.RESET and config_data.data_values: values = ConfigShim.str_to_dict(config_data.data_values) for key in values: value = values[key] self.session.options.set_config(key, value) return replies def handle_config_location(self, message_type, config_data): if message_type == ConfigFlags.RESET: self.session.location.reset() else: if not config_data.data_values: logging.warning("location data missing") else: values = [float(x) for x in config_data.data_values.split("|")] # Cartesian coordinate reference point refx, refy = values[0], values[1] refz = 0.0 lat, lon, alt = values[2], values[3], values[4] # xyz point self.session.location.refxyz = (refx, refy, refz) # geographic reference point self.session.location.setrefgeo(lat, lon, alt) self.session.location.refscale = values[5] logging.info( "location configured: %s = %s scale=%s", self.session.location.refxyz, self.session.location.refgeo, self.session.location.refscale, ) logging.info("location configured: UTM%s", self.session.location.refutm) def handle_config_metadata(self, message_type, config_data): replies = [] if message_type == ConfigFlags.REQUEST: node_id = config_data.node metadata_configs = self.session.metadata if metadata_configs is None: metadata_configs = {} data_values = "|".join( [f"{x}={metadata_configs[x]}" for x in metadata_configs] ) data_types = tuple(ConfigDataTypes.STRING.value for _ in metadata_configs) config_response = ConfigData( message_type=0, node=node_id, object="metadata", type=ConfigFlags.NONE.value, data_types=data_types, data_values=data_values, ) replies.append(config_response) elif message_type != ConfigFlags.RESET and config_data.data_values: values = ConfigShim.str_to_dict(config_data.data_values) for key in values: value = values[key] self.session.metadata[key] = value return replies def handle_config_broker(self, message_type, config_data): if message_type not in [ConfigFlags.REQUEST, ConfigFlags.RESET]: if not config_data.data_values: logging.info("emulation server data missing") else: values = config_data.data_values.split("|") # string of "server:ip:port,server:ip:port,..." server_strings = values[0] server_list = server_strings.split(",") for server in server_list: server_items = server.split(":") name, host, _ = server_items[:3] self.session.distributed.add_server(name, host) elif message_type == ConfigFlags.RESET: self.session.distributed.shutdown() def handle_config_services(self, message_type, config_data): replies = [] node_id = config_data.node opaque = config_data.opaque if message_type == ConfigFlags.REQUEST: session_id = config_data.session opaque = config_data.opaque logging.debug( "configuration request: node(%s) session(%s) opaque(%s)", node_id, session_id, opaque, ) # send back a list of available services if opaque is None: type_flag = ConfigFlags.NONE.value data_types = tuple( repeat(ConfigDataTypes.BOOL.value, len(ServiceManager.services)) ) # sort groups by name and map services to groups groups = set() group_map = {} for name in ServiceManager.services: service_name = ServiceManager.services[name] group = service_name.group groups.add(group) group_map.setdefault(group, []).append(service_name) groups = sorted(groups, key=lambda x: x.lower()) # define tlv values in proper order captions = [] possible_values = [] values = [] group_strings = [] start_index = 1 logging.debug("sorted groups: %s", groups) for group in groups: services = sorted(group_map[group], key=lambda x: x.name.lower()) logging.debug("sorted services for group(%s): %s", group, services) end_index = start_index + len(services) - 1 group_strings.append(f"{group}:{start_index}-{end_index}") start_index += len(services) for service_name in services: captions.append(service_name.name) values.append("0") if service_name.custom_needed: possible_values.append("1") else: possible_values.append("") # format for tlv captions = "|".join(captions) possible_values = "|".join(possible_values) values = "|".join(values) groups = "|".join(group_strings) # send back the properties for this service else: if not node_id: return replies node = self.session.get_node(node_id) if node is None: logging.warning( "request to configure service for unknown node %s", node_id ) return replies services = ServiceShim.servicesfromopaque(opaque) if not services: return replies servicesstring = opaque.split(":") if len(servicesstring) == 3: # a file request: e.g. "service:zebra:quagga.conf" file_name = servicesstring[2] service_name = services[0] file_data = self.session.services.get_service_file( node, service_name, file_name ) self.session.broadcast_file(file_data) # short circuit this request early to avoid returning response below return replies # the first service in the list is the one being configured service_name = services[0] # send back: # dirs, configs, startindex, startup, shutdown, metadata, config type_flag = ConfigFlags.UPDATE.value data_types = tuple( repeat(ConfigDataTypes.STRING.value, len(ServiceShim.keys)) ) service = self.session.services.get_service( node_id, service_name, default_service=True ) values = ServiceShim.tovaluelist(node, service) captions = None possible_values = None groups = None config_response = ConfigData( message_type=0, node=node_id, object=self.session.services.name, type=type_flag, data_types=data_types, data_values=values, captions=captions, possible_values=possible_values, groups=groups, session=session_id, opaque=opaque, ) replies.append(config_response) elif message_type == ConfigFlags.RESET: self.session.services.reset() else: data_types = config_data.data_types values = config_data.data_values error_message = "services config message that I don't know how to handle" if values is None: logging.error(error_message) else: if opaque is None: values = values.split("|") # store default services for a node type in self.defaultservices[] if ( data_types is None or data_types[0] != ConfigDataTypes.STRING.value ): logging.info(error_message) return None key = values.pop(0) self.session.services.default_services[key] = values logging.debug("default services for type %s set to %s", key, values) elif node_id: services = ServiceShim.servicesfromopaque(opaque) if services: service_name = services[0] # set custom service for node self.session.services.set_service(node_id, service_name) # set custom values for custom service service = self.session.services.get_service( node_id, service_name ) if not service: raise ValueError( "custom service(%s) for node(%s) does not exist", service_name, node_id, ) values = ConfigShim.str_to_dict(values) for name in values: value = values[name] ServiceShim.setvalue(service, name, value) return replies def handle_config_mobility(self, message_type, _): if message_type == ConfigFlags.RESET: self.session.mobility.reset() def handle_config_mobility_models(self, message_type, config_data): replies = [] node_id = config_data.node object_name = config_data.object interface_id = config_data.interface_number values_str = config_data.data_values if interface_id is not None: node_id = node_id * 1000 + interface_id logging.debug( "received configure message for %s nodenum: %s", object_name, node_id ) if message_type == ConfigFlags.REQUEST: logging.info("replying to configure request for model: %s", object_name) typeflags = ConfigFlags.NONE.value model_class = self.session.mobility.models.get(object_name) if not model_class: logging.warning("model class does not exist: %s", object_name) return [] config = self.session.mobility.get_model_config(node_id, object_name) config_response = ConfigShim.config_data( 0, node_id, typeflags, model_class, config ) replies.append(config_response) elif message_type != ConfigFlags.RESET: # store the configuration values for later use, when the node if not object_name: logging.warning("no configuration object for node: %s", node_id) return [] parsed_config = {} if values_str: parsed_config = ConfigShim.str_to_dict(values_str) self.session.mobility.set_model_config(node_id, object_name, parsed_config) if self.session.state == EventTypes.RUNTIME_STATE.value and parsed_config: try: node = self.session.get_node(node_id) if object_name == BasicRangeModel.name: node.updatemodel(parsed_config) except CoreError: logging.error( "skipping mobility configuration for unknown node: %s", node_id ) return replies def handle_config_emane(self, message_type, config_data): replies = [] node_id = config_data.node object_name = config_data.object interface_id = config_data.interface_number values_str = config_data.data_values if interface_id is not None: node_id = node_id * 1000 + interface_id logging.debug( "received configure message for %s nodenum: %s", object_name, node_id ) if message_type == ConfigFlags.REQUEST: logging.info("replying to configure request for %s model", object_name) typeflags = ConfigFlags.NONE.value config = self.session.emane.get_configs() config_response = ConfigShim.config_data( 0, node_id, typeflags, self.session.emane.emane_config, config ) replies.append(config_response) elif message_type != ConfigFlags.RESET: if not object_name: logging.info("no configuration object for node %s", node_id) return [] if values_str: config = ConfigShim.str_to_dict(values_str) self.session.emane.set_configs(config) return replies def handle_config_emane_models(self, message_type, config_data): replies = [] node_id = config_data.node object_name = config_data.object interface_id = config_data.interface_number values_str = config_data.data_values if interface_id is not None: node_id = node_id * 1000 + interface_id logging.debug( "received configure message for %s nodenum: %s", object_name, node_id ) if message_type == ConfigFlags.REQUEST: logging.info("replying to configure request for model: %s", object_name) typeflags = ConfigFlags.NONE.value model_class = self.session.emane.models.get(object_name) if not model_class: logging.warning("model class does not exist: %s", object_name) return [] config = self.session.emane.get_model_config(node_id, object_name) config_response = ConfigShim.config_data( 0, node_id, typeflags, model_class, config ) replies.append(config_response) elif message_type != ConfigFlags.RESET: # store the configuration values for later use, when the node if not object_name: logging.warning("no configuration object for node: %s", node_id) return [] parsed_config = {} if values_str: parsed_config = ConfigShim.str_to_dict(values_str) self.session.emane.set_model_config(node_id, object_name, parsed_config) return replies def handle_file_message(self, message): """ File Message handler :param core.api.tlv.coreapi.CoreFileMessage message: file message to handle :return: reply messages """ if message.flags & MessageFlags.ADD.value: node_num = message.get_tlv(FileTlvs.NODE.value) file_name = message.get_tlv(FileTlvs.NAME.value) file_type = message.get_tlv(FileTlvs.TYPE.value) source_name = message.get_tlv(FileTlvs.SOURCE_NAME.value) data = message.get_tlv(FileTlvs.DATA.value) compressed_data = message.get_tlv(FileTlvs.COMPRESSED_DATA.value) if compressed_data: logging.warning( "Compressed file data not implemented for File message." ) return () if source_name and data: logging.warning( "ignoring invalid File message: source and data TLVs are both present" ) return () # some File Messages store custom files in services, # prior to node creation if file_type is not None: if file_type.startswith("service:"): _, service_name = file_type.split(":")[:2] self.session.services.set_service_file( node_num, service_name, file_name, data ) return () elif file_type.startswith("hook:"): _, state = file_type.split(":")[:2] if not state.isdigit(): logging.error("error setting hook having state '%s'", state) return () state = int(state) self.session.add_hook(state, file_name, source_name, data) return () # writing a file to the host if node_num is None: if source_name is not None: shutil.copy2(source_name, file_name) else: with open(file_name, "w") as open_file: open_file.write(data) return () self.session.add_node_file(node_num, source_name, file_name, data) else: raise NotImplementedError return () def handle_interface_message(self, message): """ Interface Message handler. :param message: interface message to handle :return: reply messages """ logging.info("ignoring Interface message") return () def handle_event_message(self, message): """ Event Message handler :param core.api.tlv.coreapi.CoreEventMessage message: event message to handle :return: reply messages :raises core.CoreError: when event type <= SHUTDOWN_STATE and not a known node id """ event_data = EventData( node=message.get_tlv(EventTlvs.NODE.value), event_type=message.get_tlv(EventTlvs.TYPE.value), name=message.get_tlv(EventTlvs.NAME.value), data=message.get_tlv(EventTlvs.DATA.value), time=message.get_tlv(EventTlvs.TIME.value), session=message.get_tlv(EventTlvs.SESSION.value), ) if event_data.event_type is None: raise NotImplementedError("Event message missing event type") event_type = EventTypes(event_data.event_type) node_id = event_data.node logging.debug("handling event %s at %s", event_type.name, time.ctime()) if event_type.value <= EventTypes.SHUTDOWN_STATE.value: if node_id is not None: node = self.session.get_node(node_id) # configure mobility models for WLAN added during runtime if event_type == EventTypes.INSTANTIATION_STATE and isinstance( node, WlanNode ): self.session.start_mobility(node_ids=(node.id,)) return () logging.warning( "dropping unhandled event message for node: %s", node_id ) return () self.session.set_state(event_type) if event_type == EventTypes.DEFINITION_STATE: # clear all session objects in order to receive new definitions self.session.clear() elif event_type == EventTypes.INSTANTIATION_STATE: if len(self.handler_threads) > 1: # TODO: sync handler threads here before continuing time.sleep(2.0) # XXX # done receiving node/link configuration, ready to instantiate self.session.instantiate() # after booting nodes attempt to send emulation id for nodes waiting on status for _id in self.session.nodes: self.send_node_emulation_id(_id) elif event_type == EventTypes.RUNTIME_STATE: logging.warning("Unexpected event message: RUNTIME state received") elif event_type == EventTypes.DATACOLLECT_STATE: self.session.data_collect() elif event_type == EventTypes.SHUTDOWN_STATE: logging.warning("Unexpected event message: SHUTDOWN state received") elif event_type in { EventTypes.START, EventTypes.STOP, EventTypes.RESTART, EventTypes.PAUSE, EventTypes.RECONFIGURE, }: handled = False name = event_data.name if name: # TODO: register system for event message handlers, # like confobjs if name.startswith("service:"): self.handle_service_event(event_data) handled = True elif name.startswith("mobility:"): self.session.mobility_event(event_data) handled = True if not handled: logging.warning( "unhandled event message: event type %s, name %s ", event_type.name, name, ) elif event_type == EventTypes.FILE_OPEN: filename = event_data.name self.session.open_xml(filename, start=False) self.send_objects() return () elif event_type == EventTypes.FILE_SAVE: filename = event_data.name self.session.save_xml(filename) elif event_type == EventTypes.SCHEDULED: etime = event_data.time node = event_data.node name = event_data.name data = event_data.data if etime is None: logging.warning("Event message scheduled event missing start time") return () if message.flags & MessageFlags.ADD.value: self.session.add_event(float(etime), node=node, name=name, data=data) else: raise NotImplementedError return () def handle_service_event(self, event_data): """ Handle an Event Message used to start, stop, restart, or validate a service on a given node. :param core.emulator.enumerations.EventData event_data: event data to handle :return: nothing """ event_type = event_data.event_type node_id = event_data.node name = event_data.name try: node = self.session.get_node(node_id) except CoreError: logging.warning( "ignoring event for service '%s', unknown node '%s'", name, node_id ) return fail = "" unknown = [] services = ServiceShim.servicesfromopaque(name) for service_name in services: service = self.session.services.get_service( node_id, service_name, default_service=True ) if not service: unknown.append(service_name) continue if ( event_type == EventTypes.STOP.value or event_type == EventTypes.RESTART.value ): status = self.session.services.stop_service(node, service) if status: fail += f"Stop {service.name}," if ( event_type == EventTypes.START.value or event_type == EventTypes.RESTART.value ): status = self.session.services.startup_service(node, service) if status: fail += f"Start ({service.name})," if event_type == EventTypes.PAUSE.value: status = self.session.services.validate_service(node, service) if status: fail += f"{service.name}," if event_type == EventTypes.RECONFIGURE.value: self.session.services.service_reconfigure(node, service) fail_data = "" if len(fail) > 0: fail_data += f"Fail:{fail}" unknown_data = "" num = len(unknown) if num > 0: for u in unknown: unknown_data += u if num > 1: unknown_data += ", " num -= 1 logging.warning("Event requested for unknown service(s): %s", unknown_data) unknown_data = f"Unknown:{unknown_data}" event_data = EventData( node=node_id, event_type=event_type, name=name, data=fail_data + ";" + unknown_data, time=str(time.monotonic()), ) self.session.broadcast_event(event_data) def handle_session_message(self, message): """ Session Message handler :param core.api.tlv.coreapi.CoreSessionMessage message: session message to handle :return: reply messages """ session_id_str = message.get_tlv(SessionTlvs.NUMBER.value) session_ids = coreapi.str_to_list(session_id_str) name_str = message.get_tlv(SessionTlvs.NAME.value) names = coreapi.str_to_list(name_str) file_str = message.get_tlv(SessionTlvs.FILE.value) files = coreapi.str_to_list(file_str) thumb = message.get_tlv(SessionTlvs.THUMB.value) user = message.get_tlv(SessionTlvs.USER.value) logging.debug( "SESSION message flags=0x%x sessions=%s", message.flags, session_id_str ) if message.flags == 0: for index, session_id in enumerate(session_ids): session_id = int(session_id) if session_id == 0: session = self.session else: session = self.coreemu.sessions.get(session_id) if session is None: logging.warning("session %s not found", session_id) continue if names is not None: session.name = names[index] if files is not None: session.file_name = files[index] if thumb: session.set_thumbnail(thumb) if user: session.set_user(user) elif ( message.flags & MessageFlags.STRING.value and not message.flags & MessageFlags.ADD.value ): # status request flag: send list of sessions return (self.session_message(),) else: # handle ADD or DEL flags for session_id in session_ids: session_id = int(session_id) session = self.coreemu.sessions.get(session_id) if session is None: logging.info( "session %s not found (flags=0x%x)", session_id, message.flags ) continue if message.flags & MessageFlags.ADD.value: # connect to the first session that exists logging.info("request to connect to session %s", session_id) # remove client from session broker and shutdown if needed self.remove_session_handlers() clients = self.session_clients[self.session.id] clients.remove(self) if not clients and not self.session.is_active(): self.coreemu.delete_session(self.session.id) # set session to join self.session = session # add client to session broker clients = self.session_clients.setdefault(self.session.id, []) clients.append(self) # add broadcast handlers logging.info("adding session broadcast handlers") self.add_session_handlers() if user: self.session.set_user(user) if message.flags & MessageFlags.STRING.value: self.send_objects() elif message.flags & MessageFlags.DELETE.value: # shut down the specified session(s) logging.info("request to terminate session %s", session_id) self.coreemu.delete_session(session_id) else: logging.warning( "unhandled session flags for session %s", session_id ) return () def send_node_emulation_id(self, node_id): """ Node emulation id to send. :param int node_id: node id to send :return: nothing """ if node_id in self.node_status_request: tlv_data = b"" tlv_data += coreapi.CoreNodeTlv.pack(NodeTlvs.NUMBER.value, node_id) tlv_data += coreapi.CoreNodeTlv.pack(NodeTlvs.EMULATION_ID.value, node_id) reply = coreapi.CoreNodeMessage.pack( MessageFlags.ADD.value | MessageFlags.LOCAL.value, tlv_data ) try: self.sendall(reply) except IOError: logging.exception( "error sending node emulation id message: %s", node_id ) del self.node_status_request[node_id] def send_objects(self): """ Return API messages that describe the current session. """ # find all nodes and links nodes_data = [] links_data = [] with self.session._nodes_lock: for node_id in self.session.nodes: node = self.session.nodes[node_id] node_data = node.data(message_type=MessageFlags.ADD.value) if node_data: nodes_data.append(node_data) node_links = node.all_link_data(flags=MessageFlags.ADD.value) for link_data in node_links: links_data.append(link_data) # send all nodes first, so that they will exist for any links for node_data in nodes_data: self.session.broadcast_node(node_data) for link_data in links_data: self.session.broadcast_link(link_data) # send mobility model info for node_id in self.session.mobility.nodes(): mobility_configs = self.session.mobility.get_all_configs(node_id) for model_name in mobility_configs: config = mobility_configs[model_name] model_class = self.session.mobility.models[model_name] logging.debug( "mobility config: node(%s) class(%s) values(%s)", node_id, model_class, config, ) config_data = ConfigShim.config_data( 0, node_id, ConfigFlags.UPDATE.value, model_class, config ) self.session.broadcast_config(config_data) # send emane model info for node_id in self.session.emane.nodes(): emane_configs = self.session.emane.get_all_configs(node_id) for model_name in emane_configs: config = emane_configs[model_name] model_class = self.session.emane.models[model_name] logging.debug( "emane config: node(%s) class(%s) values(%s)", node_id, model_class, config, ) config_data = ConfigShim.config_data( 0, node_id, ConfigFlags.UPDATE.value, model_class, config ) self.session.broadcast_config(config_data) # service customizations service_configs = self.session.services.all_configs() for node_id, service in service_configs: opaque = f"service:{service.name}" data_types = tuple( repeat(ConfigDataTypes.STRING.value, len(ServiceShim.keys)) ) node = self.session.get_node(node_id) values = ServiceShim.tovaluelist(node, service) config_data = ConfigData( message_type=0, node=node_id, object=self.session.services.name, type=ConfigFlags.UPDATE.value, data_types=data_types, data_values=values, session=str(self.session.id), opaque=opaque, ) self.session.broadcast_config(config_data) for file_name, config_data in self.session.services.all_files(service): file_data = FileData( message_type=MessageFlags.ADD.value, node=node_id, name=str(file_name), type=opaque, data=str(config_data), ) self.session.broadcast_file(file_data) # TODO: send location info # send hook scripts for state in sorted(self.session._hooks.keys()): for file_name, config_data in self.session._hooks[state]: file_data = FileData( message_type=MessageFlags.ADD.value, name=str(file_name), type=f"hook:{state}", data=str(config_data), ) self.session.broadcast_file(file_data) # send session configuration session_config = self.session.options.get_configs() config_data = ConfigShim.config_data( 0, None, ConfigFlags.UPDATE.value, self.session.options, session_config ) self.session.broadcast_config(config_data) # send session metadata metadata_configs = self.session.metadata if metadata_configs: data_values = "|".join( [f"{x}={metadata_configs[x]}" for x in metadata_configs] ) data_types = tuple( ConfigDataTypes.STRING.value for _ in self.session.metadata ) config_data = ConfigData( message_type=0, object="metadata", type=ConfigFlags.NONE.value, data_types=data_types, data_values=data_values, ) self.session.broadcast_config(config_data) logging.info( "informed GUI about %d nodes and %d links", len(nodes_data), len(links_data) ) class CoreUdpHandler(CoreHandler): def __init__(self, request, client_address, server): self.message_handlers = { MessageTypes.NODE.value: self.handle_node_message, MessageTypes.LINK.value: self.handle_link_message, MessageTypes.EXECUTE.value: self.handle_execute_message, MessageTypes.REGISTER.value: self.handle_register_message, MessageTypes.CONFIG.value: self.handle_config_message, MessageTypes.FILE.value: self.handle_file_message, MessageTypes.INTERFACE.value: self.handle_interface_message, MessageTypes.EVENT.value: self.handle_event_message, MessageTypes.SESSION.value: self.handle_session_message, } self.session = None self.coreemu = server.mainserver.coreemu socketserver.BaseRequestHandler.__init__(self, request, client_address, server) def setup(self): """ Client has connected, set up a new connection. :return: nothing """ pass def receive_message(self): data = self.request[0] header = data[: coreapi.CoreMessage.header_len] if len(header) < coreapi.CoreMessage.header_len: raise IOError(f"error receiving header (received {len(header)} bytes)") message_type, message_flags, message_len = coreapi.CoreMessage.unpack_header( header ) if message_len == 0: logging.warning("received message with no data") return if len(data) != coreapi.CoreMessage.header_len + message_len: logging.error( "received message length does not match received data (%s != %s)", len(data), coreapi.CoreMessage.header_len + message_len, ) raise IOError try: message_class = coreapi.CLASS_MAP[message_type] message = message_class( message_flags, header, data[coreapi.CoreMessage.header_len :] ) return message except KeyError: message = coreapi.CoreMessage( message_flags, header, data[coreapi.CoreMessage.header_len :] ) message.msgtype = message_type logging.exception("unimplemented core message type: %s", message.type_str()) def handle(self): message = self.receive_message() sessions = message.session_numbers() message.queuedtimes = 0 if sessions: for session_id in sessions: session = self.server.mainserver.coreemu.sessions.get(session_id) if session: logging.debug("session handling message: %s", session.session_id) self.session = session self.handle_message(message) self.session.sdt.handle_distributed(message) self.broadcast(message) else: logging.error( "session %d in %s message not found.", session_id, message.type_str(), ) else: # no session specified, find an existing one session = None node_count = 0 for session_id in self.server.mainserver.coreemu.sessions: current_session = self.server.mainserver.coreemu.sessions[session_id] current_node_count = current_session.get_node_count() if ( current_session.state == EventTypes.RUNTIME_STATE.value and current_node_count > node_count ): node_count = current_node_count session = current_session if session or message.message_type == MessageTypes.REGISTER.value: self.session = session self.handle_message(message) self.session.sdt.handle_distributed(message) self.broadcast(message) else: logging.error( "no active session, dropping %s message.", message.type_str() ) def broadcast(self, message): if not isinstance(message, (coreapi.CoreNodeMessage, coreapi.CoreLinkMessage)): return clients = self.session_clients[self.session.id] for client in clients: try: client.sendall(message.raw_message) except IOError: logging.error("error broadcasting") def finish(self): return socketserver.BaseRequestHandler.finish(self) def queuemsg(self, msg): """ UDP handlers are short-lived and do not have message queues. :param bytes msg: message to queue :return: """ raise Exception( f"Unable to queue {msg} message for later processing using UDP!" ) def sendall(self, data): """ Use sendto() on the connectionless UDP socket. :param data: :return: """ self.request[1].sendto(data, self.client_address)
require("es6-shim"); var MockFirmata = require("./util/mock-firmata"), SerialPort = require("./util/mock-serial").SerialPort, five = require("../lib/johnny-five.js"), sinon = require("sinon"), __ = require("../lib/fn.js"), _ = require("lodash"), Board = five.Board, Boards = five.Boards, Virtual = Board.Virtual, Repl = five.Repl; function newBoard() { var io = new MockFirmata(); var board = new Board({ io: io, debug: false, repl: false }); io.emit("connect"); io.emit("ready"); return board; } function restore(target) { for (var prop in target) { if (Array.isArray(target[prop])) { continue; } if (target[prop] != null && typeof target[prop].restore === "function") { target[prop].restore(); } if (typeof target[prop] === "object") { restore(target[prop]); } } } exports["Board"] = { setUp: function(done) { this.board = newBoard(); this.replInit = sinon.stub(Repl.prototype, "initialize", function(callback) { callback(); }); done(); }, tearDown: function(done) { Board.purge(); restore(this); done(); }, explicit: function(test) { test.expect(1); var sp = new SerialPort("/dev/foo", { baudrate: 57600, buffersize: 128 }); var board = new Board({ port: sp, debug: false, repl: false }); test.equal(board.io.sp, sp); board.abort = true; setImmediate(function() { test.done(); }); }, ioIsReady: function(test) { test.expect(2); var io = new MockFirmata(); // Emit connection and ready BEFORE // using the instance to initialize // a new Board. io.emit("connect"); io.emit("ready"); var board = new Board({ io: io, debug: false, repl: false }); board.on("connect", function() { test.ok(true); }); board.on("ready", function() { test.ok(true); test.done(); }); }, // Disabling until @Resseguie can take a look at this // ioHasError: function(test) { // test.expect(1); // var sp = new SerialPort("/dev/foo", { // baudrate: 57600, // buffersize: 128 // }); // var board = new Board({ // port: sp, // debug: false, // repl: false // }); // board.on("error", function(msg) { // test.equals("ioHasError", msg); // test.done(); // }); // sp.emit("error", "ioHasError"); // }, readyWithNoRepl: function(test) { test.expect(1); var io = new MockFirmata(); var board = new Board({ io: io, debug: false, repl: false }); board.on("ready", function() { test.equal(this.replInit.called, false); test.done(); }.bind(this)); io.emit("connect"); io.emit("ready"); }, readyWithRepl: function(test) { test.expect(1); var io = new MockFirmata(); var board = new Board({ io: io, debug: false, repl: true }); board.on("ready", function() { test.equal(this.replInit.called, true); test.done(); }.bind(this)); io.emit("connect"); io.emit("ready"); }, emitsLogsAsEvents: function(test) { test.expect(19); var spy = sinon.spy(Board.prototype, "log"); var io = new MockFirmata(); var board = new Board({ io: io, debug: false, repl: false }); board.on("ready", function() { spy.reset(); this.on("info", function(event) { test.equal(event.class, "Board"); test.equal(event.message, "message 1"); test.deepEqual(event.data, { foo: 2 }); }); this.on("fail", function(event) { test.equal(event.class, "Board"); test.equal(event.message, "message"); test.deepEqual(event.data, null); }); this.on("warn", function(event) { test.equal(event.class, "Board"); test.equal(event.message, "message"); test.deepEqual(event.data, [1, 2, 3]); }); this.on("log", function(event) { test.equal(event.class, "Board"); test.equal(event.message, "message"); }); this.on("error", function(event) { test.equal(event.class, "Board"); test.equal(event.message, "message"); }); this.on("message", function() { test.ok(true); }); this.info("Board", "message", 1, { foo: 2 }); this.fail("Board", "message"); this.warn("Board", "message", [1, 2, 3]); this.log("Board", "message"); this.error("Board", "message"); test.equal(spy.callCount, 5); test.done(); }); io.emit("connect"); io.emit("ready"); } }; exports["Virtual"] = { setUp: function(done) { // board = newBoard(); this.Board = sinon.stub(five, "Board", function() {}); this.Expander = sinon.stub(five, "Expander", function() { this.name = "MCP23017"; }); done(); }, tearDown: function(done) { Board.purge(); restore(this); done(); }, ioExpanderAsArg: function(test) { test.expect(5); var expander = new this.Expander(); new Virtual(expander); test.equal(this.Board.called, true); test.equal(this.Board.lastCall.args[0].repl, false); test.equal(this.Board.lastCall.args[0].debug, false); test.equal(this.Board.lastCall.args[0].sigint, false); test.equal(this.Board.lastCall.args[0].io, expander); test.done(); }, ioExpanderAsPropertyOfArg: function(test) { test.expect(5); var expander = new this.Expander(); new Virtual({ io: expander }); test.equal(this.Board.called, true); test.equal(this.Board.lastCall.args[0].repl, false); test.equal(this.Board.lastCall.args[0].debug, false); test.equal(this.Board.lastCall.args[0].sigint, false); test.equal(this.Board.lastCall.args[0].io, expander); test.done(); } }; exports["samplingInterval"] = { setUp: function(done) { this.board = newBoard(); this.setSamplingInterval = sinon.spy(MockFirmata.prototype, "setSamplingInterval"); done(); }, tearDown: function(done) { Board.purge(); restore(this); done(); }, samplingInterval: function(test) { test.expect(1); this.board.samplingInterval(100); test.ok(this.setSamplingInterval.calledOnce); test.done(); } }; exports["static"] = { "Board.cache": function(test) { test.expect(2); test.equal(typeof five.Board.cache, "object", "Board.cache"); test.ok(Array.isArray(five.Board.cache), "Board.cache"); test.done(); }, "Board.Options": function(test) { test.expect(1); test.ok(five.Board.Options); test.done(); }, "Board.Pins": function(test) { test.expect(1); test.ok(five.Board.Pins, "Board.Pins"); test.done(); }, "Board.Event": function(test) { test.expect(2); var serial = {}, boardEvent = new five.Board.Event({ type: "read", target: serial }); test.ok(boardEvent.type === "read"); test.ok(boardEvent.target === serial); test.done(); }, }; exports["Boards"] = { setUp: function(done) { done(); }, tearDown: function(done) { Board.purge(); restore(this); done(); }, exists: function(test) { test.expect(1); test.equal(five.Boards, five.Board.Array); test.done(); }, methods: function(test) { test.expect(7); test.ok(Boards.prototype.log); test.ok(Boards.prototype.info); test.ok(Boards.prototype.warn); test.ok(Boards.prototype.error); test.ok(Boards.prototype.fail); test.ok(Boards.prototype.each); test.ok(Boards.prototype.add); test.done(); }, connectReadyAfter: function(test) { test.expect(2); var ioA = new MockFirmata(); var ioB = new MockFirmata(); var boards = new Boards([{ id: "A", repl: false, debug: false, io: ioA }, { id: "B", repl: false, debug: false, io: ioB }]); test.equals(2, boards.length); boards.on("ready", function() { test.ok(true); test.done(); }); ioA.emit("connect"); ioB.emit("connect"); ioA.emit("ready"); ioB.emit("ready"); }, connectReadyBefore: function(test) { test.expect(2); var ioA = new MockFirmata(); var ioB = new MockFirmata(); ioA.emit("connect"); ioB.emit("connect"); ioA.emit("ready"); ioB.emit("ready"); var boards = new Boards([{ id: "A", repl: false, debug: false, io: ioA }, { id: "B", repl: false, debug: false, io: ioB }]); test.equals(2, boards.length); boards.on("ready", function() { test.ok(true); test.done(); }); }, readyInitReplArray: function(test) { test.expect(1); this.replInit = sinon.stub(Repl.prototype, "initialize", function(callback) { callback(); }); var ioA = new MockFirmata(); var ioB = new MockFirmata(); var boards = new Boards([{ id: "A", debug: false, io: ioA }, { id: "B", debug: false, io: ioB }]); boards.on("ready", function() { test.equal(this.replInit.callCount, 1); test.done(); }.bind(this)); ioA.emit("connect"); ioB.emit("connect"); ioA.emit("ready"); ioB.emit("ready"); }, readyInitReplObject: function(test) { test.expect(1); this.replInit = sinon.stub(Repl.prototype, "initialize", function(callback) { callback(); }); var ioA = new MockFirmata(); var ioB = new MockFirmata(); var boards = new Boards({ repl: true, debug: false, ports: [{ id: "A", debug: false, io: ioA }, { id: "B", debug: false, io: ioB }] }); boards.on("ready", function() { test.equal(this.replInit.called, true); test.done(); }.bind(this)); ioA.emit("connect"); ioB.emit("connect"); ioA.emit("ready"); ioB.emit("ready"); }, readyNoReplArray1: function(test) { test.expect(1); this.replInit = sinon.stub(Repl.prototype, "initialize", function(callback) { callback(); }); var ioA = new MockFirmata(); var ioB = new MockFirmata(); var boards = new Boards([{ id: "A", repl: false, debug: false, io: ioA }, { id: "B", debug: false, io: ioB }]); boards.on("ready", function() { // Repl.prototype.initialize IS NOT CALLED test.equal(this.replInit.called, false); test.done(); }.bind(this)); ioA.emit("connect"); ioB.emit("connect"); ioA.emit("ready"); ioB.emit("ready"); }, readyNoReplArray2: function(test) { test.expect(1); this.replInit = sinon.stub(Repl.prototype, "initialize", function(callback) { callback(); }); var ioA = new MockFirmata(); var ioB = new MockFirmata(); var boards = new Boards([{ id: "A", debug: false, io: ioA }, { id: "B", repl: false, debug: false, io: ioB }]); boards.on("ready", function() { // Repl.prototype.initialize IS NOT CALLED test.equal(this.replInit.called, false); test.done(); }.bind(this)); ioA.emit("connect"); ioB.emit("connect"); ioA.emit("ready"); ioB.emit("ready"); }, readyNoReplObject: function(test) { test.expect(1); this.replInit = sinon.stub(Repl.prototype, "initialize", function(callback) { callback(); }); var ioA = new MockFirmata(); var ioB = new MockFirmata(); var boards = new Boards({ repl: false, ports: [{ id: "A", debug: false, io: ioA }, { id: "B", debug: false, io: ioB }] }); boards.on("ready", function() { // Repl.prototype.initialize IS NOT CALLED test.equal(this.replInit.called, false); test.done(); }.bind(this)); ioA.emit("connect"); ioB.emit("connect"); ioA.emit("ready"); ioB.emit("ready"); }, readyNoReplNoDebugObject: function(test) { test.expect(2); this.replInit = sinon.stub(Repl.prototype, "initialize", function(callback) { callback(); }); var ioA = new MockFirmata(); var ioB = new MockFirmata(); var boards = new Boards({ repl: false, debug: false, ports: [{ id: "A", debug: false, io: ioA }, { id: "B", debug: false, io: ioB }] }); var clog = sinon.spy(console, "log"); boards.on("ready", function() { // Repl.prototype.initialize IS NOT CALLED test.equal(this.replInit.called, false); test.equal(clog.called, false); clog.restore(); test.done(); }.bind(this)); ioA.emit("connect"); ioB.emit("connect"); ioA.emit("ready"); ioB.emit("ready"); }, errorBubbling: function(test) { test.expect(1); var ioA = new MockFirmata(); var ioB = new MockFirmata(); var boards = new Boards({ repl: false, debug: false, ports: [{ id: "A", debug: false, io: ioA }, { id: "B", debug: false, io: ioB }] }); var spy = sinon.spy(); boards.on("error", spy); boards.on("ready", function() { this[0].emit("error"); this[1].emit("error"); test.equal(spy.callCount, 2); test.done(); }); ioA.emit("connect"); ioB.emit("connect"); ioA.emit("ready"); ioB.emit("ready"); }, }; exports["instance"] = { setUp: function(done) { this.board = newBoard(); done(); }, tearDown: function(done) { Board.purge(); done(); }, cache: function(test) { test.expect(1); test.ok(_.contains(five.Board.cache, this.board)); test.done(); }, instance: function(test) { test.expect(1); test.ok(this.board); test.done(); }, io: function(test) { test.expect(1); test.ok(this.board.io instanceof MockFirmata); test.done(); }, id: function(test) { test.expect(1); test.ok(this.board.id); test.done(); }, pins: function(test) { test.expect(1); test.ok(this.board.pins); test.done(); }, }; exports["Board.mount"] = { setUp: function(done) { this.board = newBoard(); done(); }, tearDown: function(done) { Board.purge(); done(); }, "Board.mount()": function(test) { test.expect(1); test.equal(typeof five.Board.mount, "function", "Board.mount"); test.done(); }, "Board.mount(obj)": function(test) { test.expect(2); test.ok(five.Board.mount({ board: this.board }), "five.Board.mount({ board: board })"); test.deepEqual(five.Board.mount({ board: this.board }), this.board, "five.Board.mount({ board: board }) deep equals board"); test.done(); }, "Board.mount(index)": function(test) { test.expect(2); test.ok(five.Board.mount(0), "five.Board.mount(0)"); test.deepEqual(five.Board.mount(0), this.board, "five.Board.mount(0)"); test.done(); }, "Board.mount(/*none*/)": function(test) { test.expect(2); test.ok(five.Board.mount(), "five.Board.mount()"); test.deepEqual(five.Board.mount(), this.board, "five.Board.mount() matches board instance"); test.done(); }, }; exports["bubbled events from io"] = { setUp: function(done) { done(); }, tearDown: function(done) { Board.purge(); done(); }, string: function(test) { test.expect(1); var io = new MockFirmata(); var board = new Board({ io: io, debug: false, repl: false }); board.on("ready", function() { board.on("string", function(data) { test.equal(data, 1); test.done(); }); io.emit("string", 1); }); board.emit("ready"); } }; exports["fn"] = { cache: function(test) { test.expect(6); test.equal(__.scale(10, 0, 20, 0, 100), 50, "scale up"); test.equal(__.scale(10, 0, 20, 100, 0), 50, "scale up reversed"); test.equal(__.scale(10, 0, 10, 0, 180), 180, "max is 180"); test.equal(__.scale(10, 0, 10, 180, 0), 0, "max is 0"); test.equal(__.scale(0, 0, 10, 180, 0), 180, "min is 180"); test.equal(__.scale(0, 0, 10, 0, 180), 0, "min is 0"); test.done(); } }; // TODO: need tests for board.shiftOut // TODO: need mock io object // exports["modules"] = { // "optional-new": function( test ) { // var modules = Object.keys(five); // // test.expect(modules * 2); // modules.forEach(function( module ) { // var instance = new five[ module ]({}); // console.log( instance ); // }); // } // };
const express = require('express'); const bodyParser = require('body-parser'); const jwt = require('express-jwt'); const config = require('./config'); const app = express(); var glob = require('glob'), path = require('path'), cors = require('cors'); app.use(bodyParser.urlencoded({ extended: false })); app.use(bodyParser.json()); app.use(function (req, res, next) { res.header('Access-Control-Allow-Origin', '*'); res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE'); res.header('Access-Control-Allow-Headers', 'Content-Type'); next(); }); var corsOptions = { origin: '*' }; app.use(cors(corsOptions)); app.use('/api/', jwt({ secret: config.jwt.secret, credentialsRequired: false })); app.get('/', function (req, res) { res.jsonp({ status: 200, message: 'Server is running.' }); }); glob.sync(path.join(__dirname, '../modules/**/routes/*.js')).forEach(function (file) { require(path.resolve(file))(app); }); glob.sync(path.join(__dirname, '../modules/**/strategy/*.js')).forEach(function (file) { require(path.resolve(file))(app); }); glob.sync(path.join(__dirname, '../modules/**/policy/*.js')).forEach(function (file) { require(path.resolve(file)).invokeRolesPolicies(); }); module.exports = app;
/*! * jsoneditor.js * * @brief * JSONEditor is a web-based tool to view, edit, format, and validate JSON. * It has various modes such as a tree editor, a code editor, and a plain text * editor. * * Supported browsers: Chrome, Firefox, Safari, Opera, Internet Explorer 8+ * * @license * 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. * * Copyright (c) 2011-2021 Jos de Jong, http://jsoneditoronline.org * * @author Jos de Jong, <wjosdejong@gmail.com> * @version 9.1.9 * @date 2021-01-23 */ !function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.JSONEditor=t():e.JSONEditor=t()}(self,function(){return n={897:function(e,t,n){"use strict";n.d(t,{x:function(){return o}});var d=n(602),c=n(791),u=n(907);function i(e,t){for(var n=0;n<t.length;n++){var i=t[n];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,i.key,i)}}var o=function(){function l(t,e){!function(e){if(!(e instanceof l))throw new TypeError("Cannot call a class as a function")}(this),this.dom={};var h=this,n=this.dom;this.anchor=void 0,this.items=t,this.eventListeners={},this.selection=void 0,this.onClose=e?e.close:void 0,this.limitHeight=!!e&&e.limitHeight;var i=document.createElement("div");i.className="jsoneditor-contextmenu-root",n.root=i;e=document.createElement("div");e.className="jsoneditor-contextmenu",n.menu=e,i.appendChild(e);i=document.createElement("ul");i.className="jsoneditor-menu",e.appendChild(i),n.list=i,n.items=[];e=document.createElement("button");e.type="button",n.focusButton=e;n=document.createElement("li");n.style.overflow="hidden",n.style.height="0",n.appendChild(e),i.appendChild(n),function l(d,c,e){e.forEach(function(t){var n,e,i,o,r,s,a;"separator"===t.type?((i=document.createElement("div")).className="jsoneditor-separator",(r=document.createElement("li")).appendChild(i),d.appendChild(r)):(n={},e=document.createElement("li"),d.appendChild(e),(i=document.createElement("button")).type="button",i.className=t.className,n.button=i,t.title&&(i.title=t.title),t.click&&(i.onclick=function(e){e.preventDefault(),h.hide(),t.click()}),e.appendChild(i),t.submenu?((r=document.createElement("div")).className="jsoneditor-icon",i.appendChild(r),(r=document.createElement("div")).className="jsoneditor-text"+(t.click?"":" jsoneditor-right-margin"),r.appendChild(document.createTextNode(t.text)),i.appendChild(r),(o=t.click?(i.className+=" jsoneditor-default",(a=document.createElement("button")).type="button",(n.buttonExpand=a).className="jsoneditor-expand",(r=document.createElement("div")).className="jsoneditor-expand",a.appendChild(r),e.appendChild(a),t.submenuTitle&&(a.title=t.submenuTitle),a):((s=document.createElement("div")).className="jsoneditor-expand",i.appendChild(s),i)).onclick=function(e){e.preventDefault(),h._onExpandItem(n),o.focus()},a=[],n.subItems=a,s=document.createElement("ul"),(n.ul=s).className="jsoneditor-menu",s.style.height="0",e.appendChild(s),l(s,a,t.submenu)):((a=document.createElement("div")).className="jsoneditor-icon",i.appendChild(a),(a=document.createElement("div")).className="jsoneditor-text",a.appendChild(document.createTextNode((0,u.Iu)(t.text))),i.appendChild(a)),c.push(n))})}(i,this.dom.items,t),this.maxHeight=0,t.forEach(function(e){e=24*(t.length+(e.submenu?e.submenu.length:0));h.maxHeight=Math.max(h.maxHeight,e)})}var e,t,n;return e=l,(t=[{key:"_getVisibleButtons",value:function(){var t=[],n=this;return this.dom.items.forEach(function(e){t.push(e.button),e.buttonExpand&&t.push(e.buttonExpand),e.subItems&&e===n.expandedItem&&e.subItems.forEach(function(e){t.push(e.button),e.buttonExpand&&t.push(e.buttonExpand)})}),t}},{key:"show",value:function(e,t,n){this.hide();var i=!0,o=e.parentNode,r=e.getBoundingClientRect(),s=o.getBoundingClientRect(),o=t.getBoundingClientRect(),a=this;this.dom.absoluteAnchor=(0,d.w)(e,t,function(){a.hide()}),r.bottom+this.maxHeight<o.bottom||r.top-this.maxHeight>o.top&&(i=!1);n=n?0:r.top-s.top;i?(s=e.offsetHeight,this.dom.menu.style.left="0",this.dom.menu.style.top=n+s+"px",this.dom.menu.style.bottom=""):(this.dom.menu.style.left="0",this.dom.menu.style.top="",this.dom.menu.style.bottom="0px"),this.limitHeight&&(o=i?o.bottom-r.bottom-10:r.top-o.top-10,this.dom.list.style.maxHeight=o+"px",this.dom.list.style.overflowY="auto"),this.dom.absoluteAnchor.appendChild(this.dom.root),this.selection=(0,c.getSelection)(),this.anchor=e,setTimeout(function(){a.dom.focusButton.focus()},0),l.visibleMenu&&l.visibleMenu.hide(),l.visibleMenu=this}},{key:"hide",value:function(){this.dom.absoluteAnchor&&(this.dom.absoluteAnchor.destroy(),delete this.dom.absoluteAnchor),this.dom.root.parentNode&&(this.dom.root.parentNode.removeChild(this.dom.root),this.onClose&&this.onClose()),l.visibleMenu===this&&(l.visibleMenu=void 0)}},{key:"_onExpandItem",value:function(n){var i,o=this,e=n===this.expandedItem,t=this.expandedItem;t&&(t.ul.style.height="0",t.ul.style.padding="",setTimeout(function(){o.expandedItem!==t&&(t.ul.style.display="",c.removeClassName)(t.ul.parentNode,"jsoneditor-selected")},300),this.expandedItem=void 0),e||((i=n.ul).style.display="block",i.clientHeight,setTimeout(function(){if(o.expandedItem===n){for(var e=0,t=0;t<i.childNodes.length;t++)e+=i.childNodes[t].clientHeight;i.style.height=e+"px",i.style.padding="5px 10px"}},0),(0,c.addClassName)(i.parentNode,"jsoneditor-selected"),this.expandedItem=n)}},{key:"_onKeyDown",value:function(e){var t,n,i,o,r=e.target,s=e.which,a=!1;27===s?(this.selection&&(0,c.setSelection)(this.selection),this.anchor&&this.anchor.focus(),this.hide(),a=!0):9===s?e.shiftKey?0===(n=(t=this._getVisibleButtons()).indexOf(r))&&(t[t.length-1].focus(),a=!0):(n=(t=this._getVisibleButtons()).indexOf(r))===t.length-1&&(t[0].focus(),a=!0):37===s?("jsoneditor-expand"===r.className&&(n=(t=this._getVisibleButtons()).indexOf(r),(i=t[n-1])&&i.focus()),a=!0):38===s?(n=(t=this._getVisibleButtons()).indexOf(r),(i=t[n-1])&&"jsoneditor-expand"===i.className&&(i=t[n-2]),(i=i||t[t.length-1])&&i.focus(),a=!0):39===s?(n=(t=this._getVisibleButtons()).indexOf(r),(o=t[n+1])&&"jsoneditor-expand"===o.className&&o.focus(),a=!0):40===s&&(n=(t=this._getVisibleButtons()).indexOf(r),(o=t[n+1])&&"jsoneditor-expand"===o.className&&(o=t[n+2]),(o=o||t[0])&&(o.focus(),a=!0),a=!0),a&&(e.stopPropagation(),e.preventDefault())}}])&&i(e.prototype,t),n&&i(e,n),l}();o.visibleMenu=void 0},436:function(e,t,n){"use strict";function o(e,t){for(var n=0;n<t.length;n++){var i=t[n];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,i.key,i)}}n.d(t,{Q:function(){return i}});var i=function(){function n(e){!function(e){if(!(e instanceof n))throw new TypeError("Cannot call a class as a function")}(this),this.errorTableVisible=e.errorTableVisible,this.onToggleVisibility=e.onToggleVisibility,this.onFocusLine=e.onFocusLine||function(){},this.onChangeHeight=e.onChangeHeight,this.dom={};var t=document.createElement("div");t.className="jsoneditor-validation-errors-container",this.dom.validationErrorsContainer=t;e=document.createElement("div");e.style.display="none",e.className="jsoneditor-additional-errors fadein",e.textContent="Scroll for more ▿",this.dom.additionalErrorsIndication=e,t.appendChild(e);e=document.createElement("span");e.className="jsoneditor-validation-error-icon",e.style.display="none",this.dom.validationErrorIcon=e;e=document.createElement("span");e.className="jsoneditor-validation-error-count",e.style.display="none",this.dom.validationErrorCount=e,this.dom.parseErrorIndication=document.createElement("span"),this.dom.parseErrorIndication.className="jsoneditor-parse-error-icon",this.dom.parseErrorIndication.style.display="none"}var e,t,i;return e=n,(t=[{key:"getErrorTable",value:function(){return this.dom.validationErrorsContainer}},{key:"getErrorCounter",value:function(){return this.dom.validationErrorCount}},{key:"getWarningIcon",value:function(){return this.dom.validationErrorIcon}},{key:"getErrorIcon",value:function(){return this.dom.parseErrorIndication}},{key:"toggleTableVisibility",value:function(){this.errorTableVisible=!this.errorTableVisible,this.onToggleVisibility(this.errorTableVisible)}},{key:"setErrors",value:function(e,a){var t,l,d=this;this.dom.validationErrors&&(this.dom.validationErrors.parentNode.removeChild(this.dom.validationErrors),this.dom.validationErrors=null,this.dom.additionalErrorsIndication.style.display="none"),this.errorTableVisible&&0<e.length?((n=document.createElement("div")).className="jsoneditor-validation-errors",(t=document.createElement("table")).className="jsoneditor-text-errors",n.appendChild(t),l=document.createElement("tbody"),t.appendChild(l),e.forEach(function(t){var e;isNaN(t.line)?!t.dataPath||(o=a.find(function(e){return e.path===t.dataPath}))&&(e=o.line+1):e=t.line;var n=document.createElement("tr");n.className=isNaN(e)?"":"jump-to-line","error"===t.type?n.className+=" parse-error":n.className+=" validation-error";var i=document.createElement("td"),o=document.createElement("button");o.className="jsoneditor-schema-error",i.appendChild(o),n.appendChild(i);var r,s,i=document.createElement("td");i.style="white-space: nowrap;",i.textContent=isNaN(e)?"":"Ln "+e,n.appendChild(i),"string"==typeof t?((r=document.createElement("td")).colSpan=2,(s=document.createElement("pre")).appendChild(document.createTextNode(t)),r.appendChild(s),n.appendChild(r)):((s=document.createElement("td")).appendChild(document.createTextNode(t.dataPath||"")),n.appendChild(s),r=document.createElement("td"),(s=document.createElement("pre")).appendChild(document.createTextNode(t.message)),r.appendChild(s),n.appendChild(r)),n.onclick=function(){d.onFocusLine(e)},l.appendChild(n)}),this.dom.validationErrors=n,this.dom.validationErrorsContainer.appendChild(n),this.dom.additionalErrorsIndication.title=e.length+" errors total",this.dom.validationErrorsContainer.clientHeight<this.dom.validationErrorsContainer.scrollHeight?(this.dom.additionalErrorsIndication.style.display="block",this.dom.validationErrorsContainer.onscroll=function(){d.dom.additionalErrorsIndication.style.display=0<d.dom.validationErrorsContainer.clientHeight&&0===d.dom.validationErrorsContainer.scrollTop?"block":"none"}):this.dom.validationErrorsContainer.onscroll=void 0,n=this.dom.validationErrorsContainer.clientHeight+(this.dom.statusBar?this.dom.statusBar.clientHeight:0),this.onChangeHeight(n)):this.onChangeHeight(0);var n=e.filter(function(e){return"error"!==e.type}).length;0<n?(this.dom.validationErrorCount.style.display="inline",this.dom.validationErrorCount.innerText=n,this.dom.validationErrorCount.onclick=this.toggleTableVisibility.bind(this),this.dom.validationErrorIcon.style.display="inline",this.dom.validationErrorIcon.title=n+" schema validation error(s) found",this.dom.validationErrorIcon.onclick=this.toggleTableVisibility.bind(this)):(this.dom.validationErrorCount.style.display="none",this.dom.validationErrorIcon.style.display="none"),e.some(function(e){return"error"===e.type})?(e=e[0].line,this.dom.parseErrorIndication.style.display="block",this.dom.parseErrorIndication.title=isNaN(e)?"parse error - check that the json is valid":"parse error on line "+e,this.dom.parseErrorIndication.onclick=this.toggleTableVisibility.bind(this)):this.dom.parseErrorIndication.style.display="none"}}])&&o(e.prototype,t),i&&o(e,i),n}()},474:function(e,t,n){"use strict";function o(e,t){for(var n=0;n<t.length;n++){var i=t[n];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,i.key,i)}}n.d(t,{R:function(){return i}});var i=function(){function t(e){if(!function(e){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this),this.target=e.target||null,!this.target)throw new Error('FocusTracker constructor called without a "target" to track.');this.onFocus="function"==typeof e.onFocus?e.onFocus:null,this.onBlur="function"==typeof e.onBlur?e.onBlur:null,this._onClick=this._onEvent.bind(this),this._onKeyUp=function(e){9!==e.which&&9!==e.keyCode||this._onEvent(e)}.bind(this),this.focusFlag=!1,this.firstEventFlag=!0,(this.onFocus||this.onBlur)&&(document.addEventListener("click",this._onClick),document.addEventListener("keyup",this._onKeyUp))}var e,n,i;return e=t,(n=[{key:"destroy",value:function(){document.removeEventListener("click",this._onClick),document.removeEventListener("keyup",this._onKeyUp),this._onEvent({target:document.body})}},{key:"_onEvent",value:function(e){e=e.target,e=e===this.target||!(!this.target.contains(e)&&!this.target.contains(document.activeElement));e?this.focusFlag||(this.onFocus&&this.onFocus({type:"focus",target:this.target}),this.focusFlag=!0):(this.focusFlag||this.firstEventFlag)&&(this.onBlur&&this.onBlur({type:"blur",target:this.target}),this.focusFlag=!1,this.firstEventFlag&&(this.firstEventFlag=!1))}}])&&o(e.prototype,n),i&&o(e,i),t}()},161:function(e,t,o){"use strict";var n=o(170),i=o(37),r=o(38).treeModeMixins,s=o(956).textModeMixins,a=o(341).previewModeMixins,l=o(791),d=l.clear,c=l.extend,h=l.getInnerText,u=l.getInternetExplorerVersion,p=l.parse,f=o(744).tryRequireAjv,m=o(558).showTransformModal,l=o(210).showSortModal,g=f();function v(e,t,n){if(!(this instanceof v))throw new Error('JSONEditor constructor called without "new".');var i=u();if(-1!==i&&i<9)throw new Error("Unsupported browser, IE9 or newer required. Please install the newest version of your browser.");t&&(t.error&&(console.warn('Option "error" has been renamed to "onError"'),t.onError=t.error,delete t.error),t.change&&(console.warn('Option "change" has been renamed to "onChange"'),t.onChange=t.change,delete t.change),t.editable&&(console.warn('Option "editable" has been renamed to "onEditable"'),t.onEditable=t.editable,delete t.editable),t.onChangeJSON&&("text"!==t.mode&&"code"!==t.mode&&(!t.modes||-1===t.modes.indexOf("text")&&-1===t.modes.indexOf("code"))||console.warn('Option "onChangeJSON" is not applicable to modes "text" and "code". Use "onChangeText" or "onChange" instead.')),t&&Object.keys(t).forEach(function(e){-1===v.VALID_OPTIONS.indexOf(e)&&console.warn('Unknown option "'+e+'". This option will be ignored')})),arguments.length&&this._create(e,t,n)}"undefined"==typeof Promise&&console.error("Promise undefined. Please load a Promise polyfill in the browser in order to use JSONEditor"),v.modes={},v.prototype.DEBOUNCE_INTERVAL=150,v.VALID_OPTIONS=["ajv","schema","schemaRefs","templates","ace","theme","autocomplete","onChange","onChangeJSON","onChangeText","onEditable","onError","onEvent","onModeChange","onNodeName","onValidate","onCreateMenu","onSelectionChange","onTextSelectionChange","onClassName","onFocus","onBlur","colorPicker","onColorPicker","timestampTag","timestampFormat","escapeUnicode","history","search","mode","modes","name","indentation","sortObjectKeys","navigationBar","statusBar","mainMenuBar","languages","language","enableSort","enableTransform","limitDragging","maxVisibleChilds","onValidationError","modalAnchor","popupAnchor","createQuery","executeQuery","queryDescription"],v.prototype._create=function(e,t,n){this.container=e,this.options=t||{},this.json=n||{};n=this.options.mode||this.options.modes&&this.options.modes[0]||"tree";this.setMode(n)},v.prototype.destroy=function(){},v.prototype.set=function(e){this.json=e},v.prototype.get=function(){return this.json},v.prototype.setText=function(e){this.json=p(e)},v.prototype.getText=function(){return JSON.stringify(this.json)},v.prototype.setName=function(e){this.options||(this.options={}),this.options.name=e},v.prototype.getName=function(){return this.options&&this.options.name},v.prototype.setMode=function(e){if(e!==this.options.mode||!this.create){var t=this.container,n=c({},this.options),i=n.mode;n.mode=e;var o=v.modes[e];if(!o)throw new Error('Unknown mode "'+n.mode+'"');try{var r="text"===o.data,s=this.getName(),a=this[r?"getText":"get"]();if(this.destroy(),d(this),c(this,o.mixin),this.create(t,n),this.setName(s),this[r?"setText":"set"](a),"function"==typeof o.load)try{o.load.call(this)}catch(e){console.error(e)}if("function"==typeof n.onModeChange&&e!==i)try{n.onModeChange(e,i)}catch(e){console.error(e)}}catch(e){this._onError(e)}}},v.prototype.getMode=function(){return this.options.mode},v.prototype._onError=function(e){if(!this.options||"function"!=typeof this.options.onError)throw e;this.options.onError(e)},v.prototype.setSchema=function(e,t){if(e){var n;try{this.options.ajv?n=this.options.ajv:((n=g({allErrors:!0,verbose:!0,schemaId:"auto",$data:!0})).addMetaSchema(o(Object(function(){var e=new Error("Cannot find module 'ajv/lib/refs/json-schema-draft-04.json'");throw e.code="MODULE_NOT_FOUND",e}()))),n.addMetaSchema(o(Object(function(){var e=new Error("Cannot find module 'ajv/lib/refs/json-schema-draft-06.json'");throw e.code="MODULE_NOT_FOUND",e}()))))}catch(e){console.warn("Failed to create an instance of Ajv, JSON Schema validation is not available. Please use a JSONEditor bundle including Ajv, or pass an instance of Ajv as via the configuration option `ajv`.")}if(n){if(t){for(var i in t)n.removeSchema(i),t[i]&&n.addSchema(t[i],i);this.options.schemaRefs=t}this.validateSchema=n.compile(e),this.options.schema=e,this.validate()}this.refresh()}else this.validateSchema=null,this.options.schema=null,this.options.schemaRefs=null,this.validate(),this.refresh()},v.prototype.validate=function(){},v.prototype.refresh=function(){},v.registerMode=function(e){var t;if(Array.isArray(e))for(o=0;o<e.length;o++)v.registerMode(e[o]);else{if(!("mode"in e))throw new Error('Property "mode" missing');if(!("mixin"in e))throw new Error('Property "mixin" missing');if(!("data"in e))throw new Error('Property "data" missing');var n=e.mode;if(n in v.modes)throw new Error('Mode "'+n+'" already registered');if("function"!=typeof e.mixin.create)throw new Error('Required function "create" missing on mixin');for(var i=["setMode","registerMode","modes"],o=0;o<i.length;o++)if((t=i[o])in e.mixin)throw new Error('Reserved property "'+t+'" not allowed in mixin');v.modes[n]=e}},v.registerMode(r),v.registerMode(s),v.registerMode(a),v.ace=n,v.Ajv=g,v.VanillaPicker=i,v.showTransformModal=m,v.showSortModal=l,v.getInnerText=h,v.default=v,e.exports=v},617:function(e,t,n){"use strict";n.d(t,{x:function(){return o}});var u=n(897),p=n(907);function i(e,t){for(var n=0;n<t.length;n++){var i=t[n];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,i.key,i)}}var o=function(){function h(e,t,n,i){!function(e){if(!(e instanceof h))throw new TypeError("Cannot call a class as a function")}(this);for(var o={code:{text:(0,p.Iu)("modeCodeText"),title:(0,p.Iu)("modeCodeTitle"),click:function(){i("code")}},form:{text:(0,p.Iu)("modeFormText"),title:(0,p.Iu)("modeFormTitle"),click:function(){i("form")}},text:{text:(0,p.Iu)("modeTextText"),title:(0,p.Iu)("modeTextTitle"),click:function(){i("text")}},tree:{text:(0,p.Iu)("modeTreeText"),title:(0,p.Iu)("modeTreeTitle"),click:function(){i("tree")}},view:{text:(0,p.Iu)("modeViewText"),title:(0,p.Iu)("modeViewTitle"),click:function(){i("view")}},preview:{text:(0,p.Iu)("modePreviewText"),title:(0,p.Iu)("modePreviewTitle"),click:function(){i("preview")}}},r=[],s=0;s<t.length;s++){var a=t[s],l=o[a];if(!l)throw new Error('Unknown mode "'+a+'"');l.className="jsoneditor-type-modes"+(n===a?" jsoneditor-selected":""),r.push(l)}var d=o[n];if(!d)throw new Error('Unknown mode "'+n+'"');var d=d.text,c=document.createElement("button");c.type="button",c.className="jsoneditor-modes jsoneditor-separator",c.textContent=d+" ▾",c.title=(0,p.Iu)("modeEditorTitle"),c.onclick=function(){new u.x(r).show(c,e)};d=document.createElement("div");d.className="jsoneditor-modes",d.style.position="relative",d.appendChild(c),e.appendChild(d),this.dom={container:e,box:c,frame:d}}var e,t,n;return e=h,(t=[{key:"focus",value:function(){this.dom.box.focus()}},{key:"destroy",value:function(){this.dom&&this.dom.frame&&this.dom.frame.parentNode&&this.dom.frame.parentNode.removeChild(this.dom.frame),this.dom=null}}])&&i(e.prototype,t),n&&i(e,n),h}()},170:function(e,t,n){var i;if(window.ace)i=window.ace;else try{i=n(Object(function(){var e=new Error("Cannot find module 'ace-builds/src-noconflict/ace'");throw e.code="MODULE_NOT_FOUND",e}())),n(Object(function(){var e=new Error("Cannot find module 'ace-builds/src-noconflict/mode-json'");throw e.code="MODULE_NOT_FOUND",e}())),n(Object(function(){var e=new Error("Cannot find module 'ace-builds/src-noconflict/ext-searchbox'");throw e.code="MODULE_NOT_FOUND",e}()));var o=n(Object(function(){var e=new Error("Cannot find module '../generated/worker-json-data-url'");throw e.code="MODULE_NOT_FOUND",e}()));i.config.setModuleUrl("ace/mode/json_worker",o)}catch(e){}e.exports=i},864:function(){window.ace.define("ace/theme/jsoneditor",["require","exports","module","ace/lib/dom"],function(e,t,n){t.isDark=!1,t.cssClass="ace-jsoneditor",t.cssText='.ace-jsoneditor .ace_gutter {\nbackground: #ebebeb;\ncolor: #333\n}\n\n.ace-jsoneditor.ace_editor {\nfont-family: "dejavu sans mono", "droid sans mono", consolas, monaco, "lucida console", "courier new", courier, monospace, sans-serif;\nline-height: 1.3;\nbackground-color: #fff;\n}\n.ace-jsoneditor .ace_print-margin {\nwidth: 1px;\nbackground: #e8e8e8\n}\n.ace-jsoneditor .ace_scroller {\nbackground-color: #FFFFFF\n}\n.ace-jsoneditor .ace_text-layer {\ncolor: gray\n}\n.ace-jsoneditor .ace_variable {\ncolor: #1a1a1a\n}\n.ace-jsoneditor .ace_cursor {\nborder-left: 2px solid #000000\n}\n.ace-jsoneditor .ace_overwrite-cursors .ace_cursor {\nborder-left: 0px;\nborder-bottom: 1px solid #000000\n}\n.ace-jsoneditor .ace_marker-layer .ace_selection {\nbackground: lightgray\n}\n.ace-jsoneditor.ace_multiselect .ace_selection.ace_start {\nbox-shadow: 0 0 3px 0px #FFFFFF;\nborder-radius: 2px\n}\n.ace-jsoneditor .ace_marker-layer .ace_step {\nbackground: rgb(255, 255, 0)\n}\n.ace-jsoneditor .ace_marker-layer .ace_bracket {\nmargin: -1px 0 0 -1px;\nborder: 1px solid #BFBFBF\n}\n.ace-jsoneditor .ace_marker-layer .ace_active-line {\nbackground: #FFFBD1\n}\n.ace-jsoneditor .ace_gutter-active-line {\nbackground-color : #dcdcdc\n}\n.ace-jsoneditor .ace_marker-layer .ace_selected-word {\nborder: 1px solid lightgray\n}\n.ace-jsoneditor .ace_invisible {\ncolor: #BFBFBF\n}\n.ace-jsoneditor .ace_keyword,\n.ace-jsoneditor .ace_meta,\n.ace-jsoneditor .ace_support.ace_constant.ace_property-value {\ncolor: #AF956F\n}\n.ace-jsoneditor .ace_keyword.ace_operator {\ncolor: #484848\n}\n.ace-jsoneditor .ace_keyword.ace_other.ace_unit {\ncolor: #96DC5F\n}\n.ace-jsoneditor .ace_constant.ace_language {\ncolor: darkorange\n}\n.ace-jsoneditor .ace_constant.ace_numeric {\ncolor: red\n}\n.ace-jsoneditor .ace_constant.ace_character.ace_entity {\ncolor: #BF78CC\n}\n.ace-jsoneditor .ace_invalid {\ncolor: #FFFFFF;\nbackground-color: #FF002A;\n}\n.ace-jsoneditor .ace_fold {\nbackground-color: #AF956F;\nborder-color: #000000\n}\n.ace-jsoneditor .ace_storage,\n.ace-jsoneditor .ace_support.ace_class,\n.ace-jsoneditor .ace_support.ace_function,\n.ace-jsoneditor .ace_support.ace_other,\n.ace-jsoneditor .ace_support.ace_type {\ncolor: #C52727\n}\n.ace-jsoneditor .ace_string {\ncolor: green\n}\n.ace-jsoneditor .ace_comment {\ncolor: #BCC8BA\n}\n.ace-jsoneditor .ace_entity.ace_name.ace_tag,\n.ace-jsoneditor .ace_entity.ace_other.ace_attribute-name {\ncolor: #606060\n}\n.ace-jsoneditor .ace_markup.ace_underline {\ntext-decoration: underline\n}\n.ace-jsoneditor .ace_indent-guide {\nbackground: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAACCAYAAACZgbYnAAAAE0lEQVQImWP4////f4bLly//BwAmVgd1/w11/gAAAABJRU5ErkJggg==") right repeat-y\n}',e("../lib/dom").importCssString(t.cssText,t.cssClass)})},589:function(e,t){var n,n=((n={trace:function(){},yy:{},symbols_:{error:2,JSONString:3,STRING:4,JSONNumber:5,NUMBER:6,JSONNullLiteral:7,NULL:8,JSONBooleanLiteral:9,TRUE:10,FALSE:11,JSONText:12,JSONValue:13,EOF:14,JSONObject:15,JSONArray:16,"{":17,"}":18,JSONMemberList:19,JSONMember:20,":":21,",":22,"[":23,"]":24,JSONElementList:25,$accept:0,$end:1},terminals_:{2:"error",4:"STRING",6:"NUMBER",8:"NULL",10:"TRUE",11:"FALSE",14:"EOF",17:"{",18:"}",21:":",22:",",23:"[",24:"]"},productions_:[0,[3,1],[5,1],[7,1],[9,1],[9,1],[12,2],[13,1],[13,1],[13,1],[13,1],[13,1],[13,1],[15,2],[15,3],[20,3],[19,1],[19,3],[16,2],[16,3],[25,1],[25,3]],performAction:function(e,t,n,i,o,r,s){var a=r.length-1;switch(o){case 1:this.$=e.replace(/\\(\\|")/g,"$1").replace(/\\n/g,"\n").replace(/\\r/g,"\r").replace(/\\t/g,"\t").replace(/\\v/g,"\v").replace(/\\f/g,"\f").replace(/\\b/g,"\b");break;case 2:this.$=Number(e);break;case 3:this.$=null;break;case 4:this.$=!0;break;case 5:this.$=!1;break;case 6:return this.$=r[a-1];case 13:this.$={};break;case 14:this.$=r[a-1];break;case 15:this.$=[r[a-2],r[a]];break;case 16:this.$={},this.$[r[a][0]]=r[a][1];break;case 17:this.$=r[a-2],r[a-2][r[a][0]]=r[a][1];break;case 18:this.$=[];break;case 19:this.$=r[a-1];break;case 20:this.$=[r[a]];break;case 21:this.$=r[a-2],r[a-2].push(r[a])}},table:[{3:5,4:[1,12],5:6,6:[1,13],7:3,8:[1,9],9:4,10:[1,10],11:[1,11],12:1,13:2,15:7,16:8,17:[1,14],23:[1,15]},{1:[3]},{14:[1,16]},{14:[2,7],18:[2,7],22:[2,7],24:[2,7]},{14:[2,8],18:[2,8],22:[2,8],24:[2,8]},{14:[2,9],18:[2,9],22:[2,9],24:[2,9]},{14:[2,10],18:[2,10],22:[2,10],24:[2,10]},{14:[2,11],18:[2,11],22:[2,11],24:[2,11]},{14:[2,12],18:[2,12],22:[2,12],24:[2,12]},{14:[2,3],18:[2,3],22:[2,3],24:[2,3]},{14:[2,4],18:[2,4],22:[2,4],24:[2,4]},{14:[2,5],18:[2,5],22:[2,5],24:[2,5]},{14:[2,1],18:[2,1],21:[2,1],22:[2,1],24:[2,1]},{14:[2,2],18:[2,2],22:[2,2],24:[2,2]},{3:20,4:[1,12],18:[1,17],19:18,20:19},{3:5,4:[1,12],5:6,6:[1,13],7:3,8:[1,9],9:4,10:[1,10],11:[1,11],13:23,15:7,16:8,17:[1,14],23:[1,15],24:[1,21],25:22},{1:[2,6]},{14:[2,13],18:[2,13],22:[2,13],24:[2,13]},{18:[1,24],22:[1,25]},{18:[2,16],22:[2,16]},{21:[1,26]},{14:[2,18],18:[2,18],22:[2,18],24:[2,18]},{22:[1,28],24:[1,27]},{22:[2,20],24:[2,20]},{14:[2,14],18:[2,14],22:[2,14],24:[2,14]},{3:20,4:[1,12],20:29},{3:5,4:[1,12],5:6,6:[1,13],7:3,8:[1,9],9:4,10:[1,10],11:[1,11],13:30,15:7,16:8,17:[1,14],23:[1,15]},{14:[2,19],18:[2,19],22:[2,19],24:[2,19]},{3:5,4:[1,12],5:6,6:[1,13],7:3,8:[1,9],9:4,10:[1,10],11:[1,11],13:31,15:7,16:8,17:[1,14],23:[1,15]},{18:[2,17],22:[2,17]},{18:[2,15],22:[2,15]},{22:[2,21],24:[2,21]}],defaultActions:{16:[2,6]},parseError:function(e,t){throw new Error(e)},parse:function(e){var t=this,n=[0],i=[null],o=[],r=this.table,s="",a=0,l=0,d=0;this.lexer.setInput(e),this.lexer.yy=this.yy,this.yy.lexer=this.lexer,void 0===this.lexer.yylloc&&(this.lexer.yylloc={});var c=this.lexer.yylloc;function h(){var e=t.lexer.lex()||1;return"number"!=typeof e&&(e=t.symbols_[e]||e),e}o.push(c),"function"==typeof this.yy.parseError&&(this.parseError=this.yy.parseError);for(var u,p,f,m,g,v,y,b,x,C={};;){if(f=n[n.length-1],void 0===(m=this.defaultActions[f]||(null==u&&(u=h()),r[f]&&r[f][u]))||!m.length||!m[0]){if(!d){for(v in b=[],r[f])this.terminals_[v]&&2<v&&b.push("'"+this.terminals_[v]+"'");var E="",E=this.lexer.showPosition?"Parse error on line "+(a+1)+":\n"+this.lexer.showPosition()+"\nExpecting "+b.join(", ")+", got '"+this.terminals_[u]+"'":"Parse error on line "+(a+1)+": Unexpected "+(1==u?"end of input":"'"+(this.terminals_[u]||u)+"'");this.parseError(E,{text:this.lexer.match,token:this.terminals_[u]||u,line:this.lexer.yylineno,loc:c,expected:b})}if(3==d){if(1==u)throw new Error(E||"Parsing halted.");l=this.lexer.yyleng,s=this.lexer.yytext,a=this.lexer.yylineno,c=this.lexer.yylloc,u=h()}for(;!(2..toString()in r[f]);){if(0==f)throw new Error(E||"Parsing halted.");x=1,n.length=n.length-2*x,i.length=i.length-x,o.length=o.length-x,f=n[n.length-1]}p=u,u=2,m=r[f=n[n.length-1]]&&r[f][2],d=3}if(m[0]instanceof Array&&1<m.length)throw new Error("Parse Error: multiple actions possible at state: "+f+", token: "+u);switch(m[0]){case 1:n.push(u),i.push(this.lexer.yytext),o.push(this.lexer.yylloc),n.push(m[1]),u=null,p?(u=p,p=null):(l=this.lexer.yyleng,s=this.lexer.yytext,a=this.lexer.yylineno,c=this.lexer.yylloc,0<d&&d--);break;case 2:if(y=this.productions_[m[1]][1],C.$=i[i.length-y],C._$={first_line:o[o.length-(y||1)].first_line,last_line:o[o.length-1].last_line,first_column:o[o.length-(y||1)].first_column,last_column:o[o.length-1].last_column},void 0!==(g=this.performAction.call(C,s,l,a,this.yy,m[1],i,o)))return g;y&&(n=n.slice(0,-1*y*2),i=i.slice(0,-1*y),o=o.slice(0,-1*y)),n.push(this.productions_[m[1]][0]),i.push(C.$),o.push(C._$),y=r[n[n.length-2]][n[n.length-1]],n.push(y);break;case 3:return!0}}return!0}}).lexer={EOF:1,parseError:function(e,t){if(!this.yy.parseError)throw new Error(e);this.yy.parseError(e,t)},setInput:function(e){return this._input=e,this._more=this._less=this.done=!1,this.yylineno=this.yyleng=0,this.yytext=this.matched=this.match="",this.conditionStack=["INITIAL"],this.yylloc={first_line:1,first_column:0,last_line:1,last_column:0},this},input:function(){var e=this._input[0];return this.yytext+=e,this.yyleng++,this.match+=e,this.matched+=e,e.match(/\n/)&&this.yylineno++,this._input=this._input.slice(1),e},unput:function(e){return this._input=e+this._input,this},more:function(){return this._more=!0,this},less:function(e){this._input=this.match.slice(e)+this._input},pastInput:function(){var e=this.matched.substr(0,this.matched.length-this.match.length);return(20<e.length?"...":"")+e.substr(-20).replace(/\n/g,"")},upcomingInput:function(){var e=this.match;return e.length<20&&(e+=this._input.substr(0,20-e.length)),(e.substr(0,20)+(20<e.length?"...":"")).replace(/\n/g,"")},showPosition:function(){var e=this.pastInput(),t=new Array(e.length+1).join("-");return e+this.upcomingInput()+"\n"+t+"^"},next:function(){if(this.done)return this.EOF;var e,t,n,i;this._input||(this.done=!0),this._more||(this.yytext="",this.match="");for(var o=this._currentRules(),r=0;r<o.length&&(!(t=this._input.match(this.rules[o[r]]))||e&&!(t[0].length>e[0].length)||(e=t,n=r,this.options.flex));r++);return e?((i=e[0].match(/\n.*/g))&&(this.yylineno+=i.length),this.yylloc={first_line:this.yylloc.last_line,last_line:this.yylineno+1,first_column:this.yylloc.last_column,last_column:i?i[i.length-1].length-1:this.yylloc.last_column+e[0].length},this.yytext+=e[0],this.match+=e[0],this.yyleng=this.yytext.length,this._more=!1,this._input=this._input.slice(e[0].length),this.matched+=e[0],i=this.performAction.call(this,this.yy,this,o[n],this.conditionStack[this.conditionStack.length-1]),this.done&&this._input&&(this.done=!1),i||void 0):""===this._input?this.EOF:void this.parseError("Lexical error on line "+(this.yylineno+1)+". Unrecognized text.\n"+this.showPosition(),{text:"",token:null,line:this.yylineno})},lex:function(){var e=this.next();return void 0!==e?e:this.lex()},begin:function(e){this.conditionStack.push(e)},popState:function(){return this.conditionStack.pop()},_currentRules:function(){return this.conditions[this.conditionStack[this.conditionStack.length-1]].rules},topState:function(){return this.conditionStack[this.conditionStack.length-2]},pushState:function(e){this.begin(e)},options:{},performAction:function(e,t,n,i){switch(n){case 0:break;case 1:return 6;case 2:return t.yytext=t.yytext.substr(1,t.yyleng-2),4;case 3:return 17;case 4:return 18;case 5:return 23;case 6:return 24;case 7:return 22;case 8:return 21;case 9:return 10;case 10:return 11;case 11:return 8;case 12:return 14;case 13:return"INVALID"}},rules:[/^(?:\s+)/,/^(?:(-?([0-9]|[1-9][0-9]+))(\.[0-9]+)?([eE][-+]?[0-9]+)?\b)/,/^(?:"(?:\\[\\"bfnrt/]|\\u[a-fA-F0-9]{4}|[^\\\0-\x09\x0a-\x1f"])*")/,/^(?:\{)/,/^(?:\})/,/^(?:\[)/,/^(?:\])/,/^(?:,)/,/^(?::)/,/^(?:true\b)/,/^(?:false\b)/,/^(?:null\b)/,/^(?:$)/,/^(?:.)/],conditions:{INITIAL:{rules:[0,1,2,3,4,5,6,7,8,9,10,11,12,13],inclusive:!0}}},n);t.parser=n,t.parse=n.parse.bind(n)},879:function(e){"use strict";function i(){}var n={defaultSelected:!0,width:"auto",disabled:!1,searchable:!0,clearable:!1,sortSelected:!1,allowDeselect:!1,closeOnScroll:!1,nativeDropdown:!1,placeholder:"Select an option...",taggable:!1,tagPlaceholder:"Enter a tag..."};i.prototype={on:function(e,t){this._events=this._events||{},this._events[e]=this._events[e]||[],this._events[e].push(t)},off:function(e,t){this._events=this._events||{},e in this._events!=!1&&this._events[e].splice(this._events[e].indexOf(t),1)},emit:function(e){if(this._events=this._events||{},e in this._events!=!1)for(var t=0;t<this._events[e].length;t++)this._events[e][t].apply(this,Array.prototype.slice.call(arguments,1))}},i.mixin=function(e){for(var t=["on","off","emit"],n=0;n<t.length;n++)"function"==typeof e?e.prototype[t[n]]=i.prototype[t[n]]:e[t[n]]=i.prototype[t[n]];return e};var c={extend:function(e,t){for(var n in t=t||{},e)e.hasOwnProperty(n)&&(t.hasOwnProperty(n)||(t[n]=e[n]));return t},each:function(e,t,n){if("[object Object]"===Object.prototype.toString.call(e))for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.call(n,i,e[i],e);else for(var o=0,r=e.length;o<r;o++)t.call(n,o,e[o],e)},createElement:function(e,t){var n,i,o=document,r=o.createElement(e);if(t&&"[object Object]"===Object.prototype.toString.call(t))for(n in t)n in r?r[n]=t[n]:"html"===n?r.textContent=t[n]:"text"===n?(i=o.createTextNode(t[n]),r.appendChild(i)):r.setAttribute(n,t[n]);return r},hasClass:function(e,t){if(e)return e.classList?e.classList.contains(t):!!e.className&&!!e.className.match(new RegExp("(\\s|^)"+t+"(\\s|$)"))},addClass:function(e,t){c.hasClass(e,t)||(e.classList?e.classList.add(t):e.className=e.className.trim()+" "+t)},removeClass:function(e,t){c.hasClass(e,t)&&(e.classList?e.classList.remove(t):e.className=e.className.replace(new RegExp("(^|\\s)"+t.split(" ").join("|")+"(\\s|$)","gi")," "))},closest:function(e,t){return e&&e!==document.body&&(t(e)?e:c.closest(e.parentNode,t))},isInt:function(e){return"number"==typeof e&&isFinite(e)&&Math.floor(e)===e},debounce:function(i,o,r){var s;return function(){var e=this,t=arguments,n=r&&!s;clearTimeout(s),s=setTimeout(function(){s=null,r||i.apply(e,t)},o),n&&i.apply(e,t)}},rect:function(e,t){var n=window,i=e.getBoundingClientRect(),e=t?n.pageXOffset:0,n=t?n.pageYOffset:0;return{bottom:i.bottom+n,height:i.height,left:i.left+e,right:i.right+e,top:i.top+n,width:i.width}},includes:function(e,t){return-1<e.indexOf(t)},truncate:function(e){for(;e.firstChild;)e.removeChild(e.firstChild)}};function l(e,t){return e.hasOwnProperty(t)&&(!0===e[t]||e[t].length)}function s(e,t,n){e.parentNode?e.parentNode.parentNode||t.appendChild(e.parentNode):t.appendChild(e),c.removeClass(e,"excluded"),n||(e.textContent=e.textContent+"")}function a(){var n,e;this.items.length&&(n=document.createDocumentFragment(),this.config.pagination?(e=this.pages.slice(0,this.pageIndex),c.each(e,function(e,t){c.each(t,function(e,t){s(t,n,this.customOption)},this)},this)):c.each(this.items,function(e,t){s(t,n,this.customOption)},this),n.childElementCount&&(c.removeClass(this.items[this.navIndex],"active"),this.navIndex=n.querySelector(".selectr-option").idx,c.addClass(this.items[this.navIndex],"active")),this.tree.appendChild(n))}function d(e,t){return t=t||e,t=this.customOption?this.config.renderOption(t):e.textContent,(t=c.createElement("li",{class:"selectr-option",html:t,role:"treeitem","aria-selected":!1})).idx=e.idx,this.items.push(t),e.defaultSelected&&this.defaultSelected.push(e.idx),e.disabled&&(t.disabled=!0,c.addClass(t,"disabled")),t}function t(){(this.config.searchable||this.config.taggable)&&(this.input.value=null,this.searching=!1,this.config.searchable&&c.removeClass(this.inputContainer,"active"),c.hasClass(this.container,"notice")&&(c.removeClass(this.container,"notice"),c.addClass(this.container,"open"),this.input.focus()),c.each(this.items,function(e,t){c.removeClass(t,"excluded"),this.customOption||(t.textContent=t.textContent+"")},this))}function o(e,t){if(t=t||{},!e)throw new Error("You must supply either a HTMLSelectElement or a CSS3 selector string.");if("string"==typeof(this.el=e)&&(this.el=document.querySelector(e)),null===this.el)throw new Error("The element you passed to Selectr can not be found.");if("select"!==this.el.nodeName.toLowerCase())throw new Error("The element you passed to Selectr is not a HTMLSelectElement.");this.render(t)}var r=function(){var n,e=this.tree,t=e.scrollTop;e.scrollHeight-e.offsetHeight<=t&&this.pageIndex<this.pages.length&&(n=document.createDocumentFragment(),c.each(this.pages[this.pageIndex],function(e,t){s(t,n,this.customOption)},this),e.appendChild(n),this.pageIndex++,this.emit("selectr.paginate",{items:this.items.length,total:this.data.length,page:this.pageIndex,pages:this.pages.length}))};o.prototype.render=function(e){var t;this.rendered||(this.config=c.extend(n,e),this.originalType=this.el.type,this.originalIndex=this.el.tabIndex,this.defaultSelected=[],this.originalOptionCount=this.el.options.length,(this.config.multiple||this.config.taggable)&&(this.el.multiple=!0),this.disabled=l(this.config,"disabled"),this.opened=!1,this.config.taggable&&(this.config.searchable=!1),this.navigating=!1,this.mobileDevice=!1,/Android|webOS|iPhone|iPad|BlackBerry|Windows Phone|Opera Mini|IEMobile|Mobile/i.test(navigator.userAgent)&&(this.mobileDevice=!0),this.customOption=this.config.hasOwnProperty("renderOption")&&"function"==typeof this.config.renderOption,this.customSelected=this.config.hasOwnProperty("renderSelection")&&"function"==typeof this.config.renderSelection,i.mixin(this),function(){this.requiresPagination=this.config.pagination&&0<this.config.pagination,l(this.config,"width")&&(c.isInt(this.config.width)?this.width=this.config.width+"px":"auto"===this.config.width?this.width="100%":c.includes(this.config.width,"%")&&(this.width=this.config.width)),this.container=c.createElement("div",{class:"selectr-container"}),this.config.customClass&&c.addClass(this.container,this.config.customClass),this.mobileDevice?c.addClass(this.container,"selectr-mobile"):c.addClass(this.container,"selectr-desktop"),this.el.tabIndex=-1,this.config.nativeDropdown||this.mobileDevice?c.addClass(this.el,"selectr-visible"):c.addClass(this.el,"selectr-hidden"),this.selected=c.createElement("div",{class:"selectr-selected",disabled:this.disabled,tabIndex:1,"aria-expanded":!1}),this.label=c.createElement(this.el.multiple?"ul":"span",{class:"selectr-label"});var e,t=c.createElement("div",{class:"selectr-options-container"});this.tree=c.createElement("ul",{class:"selectr-options",role:"tree","aria-hidden":!0,"aria-expanded":!1}),this.notice=c.createElement("div",{class:"selectr-notice"}),this.el.setAttribute("aria-hidden",!0),this.disabled&&(this.el.disabled=!0),this.el.multiple&&(c.addClass(this.label,"selectr-tags"),c.addClass(this.container,"multiple"),this.tags=[],this.selectedValues=this.getSelectedProperties("value"),this.selectedIndexes=this.getSelectedProperties("idx")),this.selected.appendChild(this.label),this.config.clearable&&(this.selectClear=c.createElement("button",{class:"selectr-clear",type:"button"}),this.container.appendChild(this.selectClear),c.addClass(this.container,"clearable")),this.config.taggable&&(e=c.createElement("li",{class:"input-tag"}),this.input=c.createElement("input",{class:"selectr-tag-input",placeholder:this.config.tagPlaceholder,tagIndex:0,autocomplete:"off",autocorrect:"off",autocapitalize:"off",spellcheck:"false",role:"textbox",type:"search"}),e.appendChild(this.input),this.label.appendChild(e),c.addClass(this.container,"taggable"),this.tagSeperators=[","],this.config.tagSeperators&&(this.tagSeperators=this.tagSeperators.concat(this.config.tagSeperators))),this.config.searchable&&(this.input=c.createElement("input",{class:"selectr-input",tagIndex:-1,autocomplete:"off",autocorrect:"off",autocapitalize:"off",spellcheck:"false",role:"textbox",type:"search"}),this.inputClear=c.createElement("button",{class:"selectr-input-clear",type:"button"}),this.inputContainer=c.createElement("div",{class:"selectr-input-container"}),this.inputContainer.appendChild(this.input),this.inputContainer.appendChild(this.inputClear),t.appendChild(this.inputContainer)),t.appendChild(this.notice),t.appendChild(this.tree),this.items=[],this.options=[],this.el.options.length&&(this.options=[].slice.call(this.el.options));var n,i,o,r=!1,s=0;this.el.children.length&&c.each(this.el.children,function(e,t){"OPTGROUP"===t.nodeName?(r=c.createElement("ul",{class:"selectr-optgroup",role:"group",html:"<li class='selectr-optgroup--label'>"+t.label+"</li>"}),c.each(t.children,function(e,t){t.idx=s,r.appendChild(d.call(this,t,r)),s++},this)):(t.idx=s,d.call(this,t),s++)},this),this.config.data&&Array.isArray(this.config.data)&&(n=!(this.data=[]),r=!1,s=0,c.each(this.config.data,function(e,t){l(t,"children")?(n=c.createElement("optgroup",{label:t.text}),r=c.createElement("ul",{class:"selectr-optgroup",role:"group",html:"<li class='selectr-optgroup--label'>"+t.text+"</li>"}),c.each(t.children,function(e,t){(i=new Option(t.text,t.value,!1,t.hasOwnProperty("selected")&&!0===t.selected)).disabled=l(t,"disabled"),this.options.push(i),n.appendChild(i),i.idx=s,r.appendChild(d.call(this,i,t)),this.data[s]=t,s++},this)):((i=new Option(t.text,t.value,!1,t.hasOwnProperty("selected")&&!0===t.selected)).disabled=l(t,"disabled"),this.options.push(i),i.idx=s,d.call(this,i,t),this.data[s]=t,s++)},this)),this.setSelected(!0);for(var a=this.navIndex=0;a<this.items.length;a++)if(o=this.items[a],!c.hasClass(o,"disabled")){c.addClass(o,"active"),this.navIndex=a;break}this.requiresPagination&&(this.pageIndex=1,this.paginate()),this.container.appendChild(this.selected),this.container.appendChild(t),this.placeEl=c.createElement("div",{class:"selectr-placeholder"}),this.setPlaceholder(),this.selected.appendChild(this.placeEl),this.disabled&&this.disable(),this.el.parentNode.insertBefore(this.container,this.el),this.container.appendChild(this.el)}.call(this),this.bindEvents(),this.update(),this.optsRect=c.rect(this.tree),this.rendered=!0,this.el.multiple||(this.el.selectedIndex=this.selectedIndex),t=this,setTimeout(function(){t.emit("selectr.init")},20))},o.prototype.getSelected=function(){return this.el.querySelectorAll("option:checked")},o.prototype.getSelectedProperties=function(t){var e=this.getSelected();return[].slice.call(e).map(function(e){return e[t]}).filter(function(e){return null!=e})},o.prototype.bindEvents=function(){var i=this;this.events={},this.events.dismiss=function(e){e=e.target;this.container.contains(e)||!this.opened&&!c.hasClass(this.container,"notice")||this.close()}.bind(this),this.events.navigate=function(e){if(e=e||window.event,this.items.length&&this.opened&&c.includes([13,38,40],e.which)){if(e.preventDefault(),13===e.which)return!(this.config.taggable&&0<this.input.value.length)&&this.change(this.navIndex);var t,n=this.items[this.navIndex];switch(e.which){case 38:(t=0)<this.navIndex&&this.navIndex--;break;case 40:t=1,this.navIndex<this.items.length-1&&this.navIndex++}for(this.navigating=!0;c.hasClass(this.items[this.navIndex],"disabled")||c.hasClass(this.items[this.navIndex],"excluded");)if(t?this.navIndex++:this.navIndex--,this.searching){if(this.navIndex>this.tree.lastElementChild.idx){this.navIndex=this.tree.lastElementChild.idx;break}if(this.navIndex<this.tree.firstElementChild.idx){this.navIndex=this.tree.firstElementChild.idx;break}}e=c.rect(this.items[this.navIndex]);t?(0===this.navIndex?this.tree.scrollTop=0:e.top+e.height>this.optsRect.top+this.optsRect.height&&(this.tree.scrollTop=this.tree.scrollTop+(e.top+e.height-(this.optsRect.top+this.optsRect.height))),this.navIndex===this.tree.childElementCount-1&&this.requiresPagination&&r.call(this)):0===this.navIndex?this.tree.scrollTop=0:e.top-this.optsRect.top<0&&(this.tree.scrollTop=this.tree.scrollTop+(e.top-this.optsRect.top)),n&&c.removeClass(n,"active"),c.addClass(this.items[this.navIndex],"active")}else this.navigating=!1}.bind(this),this.events.reset=this.reset.bind(this),(this.config.nativeDropdown||this.mobileDevice)&&(this.container.addEventListener("touchstart",function(e){e.changedTouches[0].target===i.el&&i.toggle()}),(this.config.nativeDropdown||this.mobileDevice)&&this.container.addEventListener("click",function(e){e.preventDefault(),e.stopPropagation(),e.target===i.el&&i.toggle()}),this.el.addEventListener("change",function(e){var t;i.el.multiple?(t=i.getSelectedProperties("idx"),t=function(e,t){for(var n,i=[],o=e.slice(0),r=0;r<t.length;r++)-1<(n=o.indexOf(t[r]))?o.splice(n,1):i.push(t[r]);return[i,o]}(i.selectedIndexes,t),c.each(t[0],function(e,t){i.select(t)},i),c.each(t[1],function(e,t){i.deselect(t)},i)):-1<i.el.selectedIndex&&i.select(i.el.selectedIndex)})),this.config.nativeDropdown&&this.container.addEventListener("keydown",function(e){"Enter"===e.key&&i.selected===document.activeElement&&(i.toggle(),setTimeout(function(){i.el.focus()},200))}),this.selected.addEventListener("click",function(e){i.disabled||i.toggle(),e.preventDefault(),e.stopPropagation()}),this.label.addEventListener("click",function(e){c.hasClass(e.target,"selectr-tag-remove")&&i.deselect(e.target.parentNode.idx)}),this.selectClear&&this.selectClear.addEventListener("click",this.clear.bind(this)),this.tree.addEventListener("mousedown",function(e){e.preventDefault()}),this.tree.addEventListener("click",function(e){e.preventDefault(),e.stopPropagation();e=c.closest(e.target,function(e){return e&&c.hasClass(e,"selectr-option")});e&&(c.hasClass(e,"disabled")||(c.hasClass(e,"selected")?(i.el.multiple||!i.el.multiple&&i.config.allowDeselect)&&i.deselect(e.idx):i.select(e.idx),i.opened&&!i.el.multiple&&i.close()))}),this.tree.addEventListener("mouseover",function(e){c.hasClass(e.target,"selectr-option")&&(c.hasClass(e.target,"disabled")||(c.removeClass(i.items[i.navIndex],"active"),c.addClass(e.target,"active"),i.navIndex=[].slice.call(i.items).indexOf(e.target)))}),this.config.searchable&&(this.input.addEventListener("focus",function(e){i.searching=!0}),this.input.addEventListener("blur",function(e){i.searching=!1}),this.input.addEventListener("keyup",function(e){i.search(),i.config.taggable||(this.value.length?c.addClass(this.parentNode,"active"):c.removeClass(this.parentNode,"active"))}),this.inputClear.addEventListener("click",function(e){i.input.value=null,t.call(i),i.tree.childElementCount||a.call(i)})),this.config.taggable&&this.input.addEventListener("keyup",function(e){var n;i.search(),i.config.taggable&&this.value.length&&(n=this.value.trim(),13!==e.which&&!c.includes(i.tagSeperators,e.key)||(c.each(i.tagSeperators,function(e,t){n=n.replace(t,"")}),i.add({value:n,text:n,selected:!0},!0)?(i.close(),t.call(i)):(this.value="",i.setMessage("That tag is already in use."))))}),this.update=c.debounce(function(){i.opened&&i.config.closeOnScroll&&i.close(),i.width&&(i.container.style.width=i.width),i.invert()},50),this.requiresPagination&&(this.paginateItems=c.debounce(function(){r.call(this)},50),this.tree.addEventListener("scroll",this.paginateItems.bind(this))),document.addEventListener("click",this.events.dismiss),window.addEventListener("keydown",this.events.navigate),window.addEventListener("resize",this.update),window.addEventListener("scroll",this.update),this.el.form&&this.el.form.addEventListener("reset",this.events.reset)},o.prototype.setSelected=function(e){var n;this.config.data||this.el.multiple||!this.el.options.length||(0===this.el.selectedIndex&&(this.el.options[0].defaultSelected||this.config.defaultSelected||(this.el.selectedIndex=-1)),this.selectedIndex=this.el.selectedIndex,-1<this.selectedIndex&&this.select(this.selectedIndex)),this.config.multiple&&"select-one"===this.originalType&&!this.config.data&&this.el.options[0].selected&&!this.el.options[0].defaultSelected&&(this.el.options[0].selected=!1),c.each(this.options,function(e,t){t.selected&&t.defaultSelected&&this.select(t.idx)},this),this.config.selectedValue&&this.setValue(this.config.selectedValue),this.config.data&&(!this.el.multiple&&this.config.defaultSelected&&this.el.selectedIndex<0&&this.select(0),n=0,c.each(this.config.data,function(e,t){l(t,"children")?c.each(t.children,function(e,t){t.hasOwnProperty("selected")&&!0===t.selected&&this.select(n),n++},this):(t.hasOwnProperty("selected")&&!0===t.selected&&this.select(n),n++)},this))},o.prototype.destroy=function(){this.rendered&&(this.emit("selectr.destroy"),"select-one"===this.originalType&&(this.el.multiple=!1),this.config.data&&(this.el.textContent=""),c.removeClass(this.el,"selectr-hidden"),this.el.form&&c.off(this.el.form,"reset",this.events.reset),c.off(document,"click",this.events.dismiss),c.off(document,"keydown",this.events.navigate),c.off(window,"resize",this.update),c.off(window,"scroll",this.update),this.container.parentNode.replaceChild(this.el,this.container),this.rendered=!1)},o.prototype.change=function(e){var t=this.items[e],n=this.options[e];n.disabled||(n.selected&&c.hasClass(t,"selected")?this.deselect(e):this.select(e),this.opened&&!this.el.multiple&&this.close())},o.prototype.select=function(i){var e=this.items[i],t=[].slice.call(this.el.options),n=this.options[i];if(this.el.multiple){if(c.includes(this.selectedIndexes,i))return!1;if(this.config.maxSelections&&this.tags.length===this.config.maxSelections)return this.setMessage("A maximum of "+this.config.maxSelections+" items can be selected.",!0),!1;this.selectedValues.push(n.value),this.selectedIndexes.push(i),function(e){var l,d=this,n=document.createDocumentFragment(),t=this.options[e.idx],i=this.data?this.data[e.idx]:t,o=this.customSelected?this.config.renderSelection(i):t.textContent,i=c.createElement("li",{class:"selectr-tag",html:o}),o=c.createElement("button",{class:"selectr-tag-remove",type:"button"});i.appendChild(o),i.idx=e.idx,i.tag=t.value,this.tags.push(i),this.config.sortSelected?(t=this.tags.slice(),l=function(e,i){e.replace(/(\d+)|(\D+)/g,function(e,t,n){i.push([t||1/0,n||""])})},t.sort(function(e,t){var n,i,o=[],r=[];for(!0===d.config.sortSelected?(n=e.tag,i=t.tag):"text"===d.config.sortSelected&&(n=e.textContent,i=t.textContent),l(n,o),l(i,r);o.length&&r.length;){var s=o.shift(),a=r.shift(),a=s[0]-a[0]||s[1].localeCompare(a[1]);if(a)return a}return o.length-r.length}),c.each(t,function(e,t){n.appendChild(t)}),this.label.textContent=""):n.appendChild(i),this.config.taggable?this.label.insertBefore(n,this.input.parentNode):this.label.appendChild(n)}.call(this,e)}else{var o=this.data?this.data[i]:n;this.label.textContent=this.customSelected?this.config.renderSelection(o):n.textContent,this.selectedValue=n.value,this.selectedIndex=i,c.each(this.options,function(e,t){var n=this.items[e];e!==i&&(n&&c.removeClass(n,"selected"),t.selected=!1,t.removeAttribute("selected"))},this)}c.includes(t,n)||this.el.add(n),e.setAttribute("aria-selected",!0),c.addClass(e,"selected"),c.addClass(this.container,"has-selected"),n.selected=!0,n.setAttribute("selected",""),this.emit("selectr.change",n),this.emit("selectr.select",n)},o.prototype.deselect=function(e,t){var n=this.items[e],i=this.options[e];if(this.el.multiple){var o=this.selectedIndexes.indexOf(e);this.selectedIndexes.splice(o,1);o=this.selectedValues.indexOf(i.value);this.selectedValues.splice(o,1),function(n){var i=!1;c.each(this.tags,function(e,t){t.idx===n.idx&&(i=t)},this),i&&(this.label.removeChild(i),this.tags.splice(this.tags.indexOf(i),1))}.call(this,n),this.tags.length||c.removeClass(this.container,"has-selected")}else{if(!t&&!this.config.clearable&&!this.config.allowDeselect)return!1;this.label.textContent="",this.selectedValue=null,this.el.selectedIndex=this.selectedIndex=-1,c.removeClass(this.container,"has-selected")}this.items[e].setAttribute("aria-selected",!1),c.removeClass(this.items[e],"selected"),i.selected=!1,i.removeAttribute("selected"),this.emit("selectr.change",null),this.emit("selectr.deselect",i)},o.prototype.setValue=function(n){var i=Array.isArray(n);if(i||(n=n.toString().trim()),!this.el.multiple&&i)return!1;c.each(this.options,function(e,t){(i&&c.includes(n.toString(),t.value)||t.value===n)&&this.change(t.idx)},this)},o.prototype.getValue=function(e,t){var n,i;return this.el.multiple?e?this.selectedIndexes.length&&(i={values:[]},c.each(this.selectedIndexes,function(e,t){t=this.options[t];i.values[e]={value:t.value,text:t.textContent}},this)):i=this.selectedValues.slice():i=e?{value:(n=this.options[this.selectedIndex]).value,text:n.textContent}:this.selectedValue,e&&t&&(i=JSON.stringify(i)),i},o.prototype.add=function(n,i){if(n){if(this.data=this.data||[],this.items=this.items||[],this.options=this.options||[],Array.isArray(n))c.each(n,function(e,t){this.add(t,i)},this);else if("[object Object]"===Object.prototype.toString.call(n)){if(i){var o=!1;if(c.each(this.options,function(e,t){t.value.toLowerCase()===n.value.toLowerCase()&&(o=!0)}),o)return!1}var e=c.createElement("option",n);return this.data.push(n),this.options.push(e),e.idx=0<this.options.length?this.options.length-1:0,d.call(this,e),n.selected&&this.select(e.idx),e}return this.setPlaceholder(),this.config.pagination&&this.paginate(),!0}},o.prototype.remove=function(n){var i,o=[];Array.isArray(n)?c.each(n,function(e,t){c.isInt(t)?o.push(this.getOptionByIndex(t)):"string"==typeof n&&o.push(this.getOptionByValue(t))},this):c.isInt(n)?o.push(this.getOptionByIndex(n)):"string"==typeof n&&o.push(this.getOptionByValue(n)),o.length&&(c.each(o,function(e,t){i=t.idx,this.el.remove(t),this.options.splice(i,1);t=this.items[i].parentNode;t&&t.removeChild(this.items[i]),this.items.splice(i,1),c.each(this.options,function(e,t){t.idx=e,this.items[e].idx=e},this)},this),this.setPlaceholder(),this.config.pagination&&this.paginate())},o.prototype.removeAll=function(){this.clear(!0),c.each(this.el.options,function(e,t){this.el.remove(t)},this),c.truncate(this.tree),this.items=[],this.options=[],this.data=[],this.navIndex=0,this.requiresPagination&&(this.requiresPagination=!1,this.pageIndex=1,this.pages=[]),this.setPlaceholder()},o.prototype.search=function(o){var r,e,t;this.navigating||(o=o||this.input.value,r=document.createDocumentFragment(),this.removeMessage(),c.truncate(this.tree),1<o.length?(c.each(this.options,function(e,t){var n,i=this.items[t.idx];c.includes(t.textContent.toLowerCase(),o.toLowerCase())&&!t.disabled?(s(i,r,this.customOption),c.removeClass(i,"excluded"),this.customOption||(i.textContent="",(n=function(e,t){var n=new RegExp(e,"i").exec(t);if(n){e=n.index,n=n.index+n[0].length;return{before:t.substring(0,e),match:t.substring(e,n),after:t.substring(n)}}return null}(o,t.textContent))&&(i.appendChild(document.createTextNode(n.before)),(t=document.createElement("span")).className="selectr-match",t.appendChild(document.createTextNode(n.match)),i.appendChild(t),i.appendChild(document.createTextNode(n.after))))):c.addClass(i,"excluded")},this),r.childElementCount?(e=this.items[this.navIndex],t=r.firstElementChild,c.removeClass(e,"active"),this.navIndex=t.idx,c.addClass(t,"active")):this.config.taggable||this.setMessage("no results.")):a.call(this),this.tree.appendChild(r))},o.prototype.toggle=function(){this.disabled||(this.opened?this.close():this.open())},o.prototype.open=function(){var e=this;return!!this.options.length&&(this.opened||this.emit("selectr.open"),this.opened=!0,this.mobileDevice||this.config.nativeDropdown?(c.addClass(this.container,"native-open"),void(this.config.data&&c.each(this.options,function(e,t){this.el.add(t)},this))):(c.addClass(this.container,"open"),a.call(this),this.invert(),this.tree.scrollTop=0,c.removeClass(this.container,"notice"),this.selected.setAttribute("aria-expanded",!0),this.tree.setAttribute("aria-hidden",!1),this.tree.setAttribute("aria-expanded",!0),void(this.config.searchable&&!this.config.taggable&&setTimeout(function(){e.input.focus(),e.input.tabIndex=0},10))))},o.prototype.close=function(){var e;this.opened&&this.emit("selectr.close"),this.opened=!1,this.mobileDevice||this.config.nativeDropdown?c.removeClass(this.container,"native-open"):(e=c.hasClass(this.container,"notice"),this.config.searchable&&!e&&(this.input.blur(),this.input.tabIndex=-1,this.searching=!1),e&&(c.removeClass(this.container,"notice"),this.notice.textContent=""),c.removeClass(this.container,"open"),c.removeClass(this.container,"native-open"),this.selected.setAttribute("aria-expanded",!1),this.tree.setAttribute("aria-hidden",!0),this.tree.setAttribute("aria-expanded",!1),c.truncate(this.tree),t.call(this))},o.prototype.enable=function(){this.disabled=!1,this.el.disabled=!1,this.selected.tabIndex=this.originalIndex,this.el.multiple&&c.each(this.tags,function(e,t){t.lastElementChild.tabIndex=0}),c.removeClass(this.container,"selectr-disabled")},o.prototype.disable=function(e){e||(this.el.disabled=!0),this.selected.tabIndex=-1,this.el.multiple&&c.each(this.tags,function(e,t){t.lastElementChild.tabIndex=-1}),this.disabled=!0,c.addClass(this.container,"selectr-disabled")},o.prototype.reset=function(){this.disabled||(this.clear(),this.setSelected(!0),c.each(this.defaultSelected,function(e,t){this.select(t)},this),this.emit("selectr.reset"))},o.prototype.clear=function(e){var t;this.el.multiple?this.selectedIndexes.length&&(t=this.selectedIndexes.slice(),c.each(t,function(e,t){this.deselect(t)},this)):-1<this.selectedIndex&&this.deselect(this.selectedIndex,e),this.emit("selectr.clear")},o.prototype.serialise=function(e){var i=[];return c.each(this.options,function(e,t){var n={value:t.value,text:t.textContent};t.selected&&(n.selected=!0),t.disabled&&(n.disabled=!0),i[e]=n}),e?JSON.stringify(i):i},o.prototype.serialize=function(e){return this.serialise(e)},o.prototype.setPlaceholder=function(e){e=e||this.config.placeholder||this.el.getAttribute("placeholder"),this.options.length||(e="No options available"),this.placeEl.textContent=e},o.prototype.paginate=function(){if(this.items.length){var n=this;return this.pages=this.items.map(function(e,t){return t%n.config.pagination==0?n.items.slice(t,t+n.config.pagination):null}).filter(function(e){return e}),this.pages}},o.prototype.setMessage=function(e,t){t&&this.close(),c.addClass(this.container,"notice"),this.notice.textContent=e},o.prototype.removeMessage=function(){c.removeClass(this.container,"notice"),this.notice.textContent=""},o.prototype.invert=function(){var e=c.rect(this.selected),t=this.tree.parentNode.offsetHeight,n=window.innerHeight;e.top+e.height+t>n?(c.addClass(this.container,"inverted"),this.isInverted=!0):(c.removeClass(this.container,"inverted"),this.isInverted=!1),this.optsRect=c.rect(this.tree)},o.prototype.getOptionByIndex=function(e){return this.options[e]},o.prototype.getOptionByValue=function(e){for(var t=!1,n=0,i=this.options.length;n<i;n++)if(this.options[n].value.trim()===e.toString().trim()){t=this.options[n];break}return t},e.exports=o},188:function(e,t,n){"use strict";n.d(t,{qD:function(){return i},EX:function(){return o},WF:function(){return r},oW:function(){return s}});var i=document.body,o=10485760,r=2e4,s=2147483648},602:function(e,t,n){"use strict";n.d(t,{w:function(){return i}});var u=n(791);function i(i,e,o){var t,n=3<arguments.length&&void 0!==arguments[3]&&arguments[3],r="function"==typeof(l=i).getRootNode?l.getRootNode():window,s={},a=i.getBoundingClientRect(),l=e.getBoundingClientRect(),d=document.createElement("div");function c(){if(d&&d.parentNode){for(var e in d.parentNode.removeChild(d),s)t=s,n=e,Object.prototype.hasOwnProperty.call(t,n)&&((n=s[e])&&(0,u.removeEventListener)(r,e,n),delete s[e]);"function"==typeof o&&o(i)}var t,n}function h(e){(e=e.target)===d||(0,u.isChildOf)(e,d)||c()}return d.className="jsoneditor-anchor",d.style.position="absolute",d.style.left=a.left-l.left+"px",d.style.top=a.top-l.top+"px",d.style.width=a.width-2+"px",d.style.height=a.height-2+"px",d.style.boxSizing="border-box",e.appendChild(d),s.mousedown=(0,u.addEventListener)(r,"mousedown",h),s.mousewheel=(0,u.addEventListener)(r,"mousewheel",h),n&&(t=null,d.onmouseover=function(){clearTimeout(t),t=null},d.onmouseout=function(){t=t||setTimeout(c,200)}),d.destroy=c,d}},907:function(e,t,n){"use strict";n.d(t,{m0:function(){return l},cC:function(){return d},Iu:function(){return c}});var t=n(987),i=["en","pt-BR","zh-CN","tr","ja","fr-FR","de"],r={en:{array:"Array",auto:"Auto",appendText:"Append",appendTitle:"Append a new field with type 'auto' after this field (Ctrl+Shift+Ins)",appendSubmenuTitle:"Select the type of the field to be appended",appendTitleAuto:"Append a new field with type 'auto' (Ctrl+Shift+Ins)",ascending:"Ascending",ascendingTitle:"Sort the childs of this ${type} in ascending order",actionsMenu:"Click to open the actions menu (Ctrl+M)",cannotParseFieldError:"Cannot parse field into JSON",cannotParseValueError:"Cannot parse value into JSON",collapseAll:"Collapse all fields",compactTitle:"Compact JSON data, remove all whitespaces (Ctrl+Shift+\\)",descending:"Descending",descendingTitle:"Sort the childs of this ${type} in descending order",drag:"Drag to move this field (Alt+Shift+Arrows)",duplicateKey:"duplicate key",duplicateText:"Duplicate",duplicateTitle:"Duplicate selected fields (Ctrl+D)",duplicateField:"Duplicate this field (Ctrl+D)",duplicateFieldError:"Duplicate field name",empty:"empty",expandAll:"Expand all fields",expandTitle:"Click to expand/collapse this field (Ctrl+E). \nCtrl+Click to expand/collapse including all childs.",formatTitle:"Format JSON data, with proper indentation and line feeds (Ctrl+\\)",insert:"Insert",insertTitle:"Insert a new field with type 'auto' before this field (Ctrl+Ins)",insertSub:"Select the type of the field to be inserted",object:"Object",ok:"Ok",redo:"Redo (Ctrl+Shift+Z)",removeText:"Remove",removeTitle:"Remove selected fields (Ctrl+Del)",removeField:"Remove this field (Ctrl+Del)",repairTitle:"Repair JSON: fix quotes and escape characters, remove comments and JSONP notation, turn JavaScript objects into JSON.",searchTitle:"Search fields and values",searchNextResultTitle:"Next result (Enter)",searchPreviousResultTitle:"Previous result (Shift + Enter)",selectNode:"Select a node...",showAll:"show all",showMore:"show more",showMoreStatus:"displaying ${visibleChilds} of ${totalChilds} items.",sort:"Sort",sortTitle:"Sort the childs of this ${type}",sortTitleShort:"Sort contents",sortFieldLabel:"Field:",sortDirectionLabel:"Direction:",sortFieldTitle:"Select the nested field by which to sort the array or object",sortAscending:"Ascending",sortAscendingTitle:"Sort the selected field in ascending order",sortDescending:"Descending",sortDescendingTitle:"Sort the selected field in descending order",string:"String",transform:"Transform",transformTitle:"Filter, sort, or transform the childs of this ${type}",transformTitleShort:"Filter, sort, or transform contents",extract:"Extract",extractTitle:"Extract this ${type}",transformQueryTitle:"Enter a JMESPath query",transformWizardLabel:"Wizard",transformWizardFilter:"Filter",transformWizardSortBy:"Sort by",transformWizardSelectFields:"Select fields",transformQueryLabel:"Query",transformPreviewLabel:"Preview",type:"Type",typeTitle:"Change the type of this field",openUrl:"Ctrl+Click or Ctrl+Enter to open url in new window",undo:"Undo last action (Ctrl+Z)",validationCannotMove:"Cannot move a field into a child of itself",autoType:'Field type "auto". The field type is automatically determined from the value and can be a string, number, boolean, or null.',objectType:'Field type "object". An object contains an unordered set of key/value pairs.',arrayType:'Field type "array". An array contains an ordered collection of values.',stringType:'Field type "string". Field type is not determined from the value, but always returned as string.',modeEditorTitle:"Switch Editor Mode",modeCodeText:"Code",modeCodeTitle:"Switch to code highlighter",modeFormText:"Form",modeFormTitle:"Switch to form editor",modeTextText:"Text",modeTextTitle:"Switch to plain text editor",modeTreeText:"Tree",modeTreeTitle:"Switch to tree editor",modeViewText:"View",modeViewTitle:"Switch to tree view",modePreviewText:"Preview",modePreviewTitle:"Switch to preview mode",examples:"Examples",default:"Default",containsInvalidProperties:"Contains invalid properties",containsInvalidItems:"Contains invalid items"},"zh-CN":{array:"数组",auto:"自动",appendText:"追加",appendTitle:"在此字段后追加一个类型为“auto”的新字段 (Ctrl+Shift+Ins)",appendSubmenuTitle:"选择要追加的字段类型",appendTitleAuto:"追加类型为“auto”的新字段 (Ctrl+Shift+Ins)",ascending:"升序",ascendingTitle:"升序排列${type}的子节点",actionsMenu:"点击打开动作菜单(Ctrl+M)",cannotParseFieldError:"无法将字段解析为JSON",cannotParseValueError:"无法将值解析为JSON",collapseAll:"缩进所有字段",compactTitle:"压缩JSON数据,删除所有空格 (Ctrl+Shift+\\)",descending:"降序", descendingTitle:"降序排列${type}的子节点",drag:"拖拽移动该节点(Alt+Shift+Arrows)",duplicateKey:"重复键",duplicateText:"复制",duplicateTitle:"复制选中字段(Ctrl+D)",duplicateField:"复制该字段(Ctrl+D)",duplicateFieldError:"重复的字段名称",empty:"清空",expandAll:"展开所有字段",expandTitle:"点击 展开/收缩 该字段(Ctrl+E). \nCtrl+Click 展开/收缩 包含所有子节点.",formatTitle:"使用适当的缩进和换行符格式化JSON数据 (Ctrl+\\)",insert:"插入",insertTitle:"在此字段前插入类型为“auto”的新字段 (Ctrl+Ins)",insertSub:"选择要插入的字段类型",object:"对象",ok:"Ok",redo:"重做 (Ctrl+Shift+Z)",removeText:"移除",removeTitle:"移除选中字段 (Ctrl+Del)",removeField:"移除该字段 (Ctrl+Del)",repairTitle:"修复JSON:修复引号和转义符,删除注释和JSONP表示法,将JavaScript对象转换为JSON。",selectNode:"选择一个节点...",showAll:"展示全部",showMore:"展示更多",showMoreStatus:"显示${totalChilds}的${visibleChilds}项目.",sort:"排序",sortTitle:"排序${type}的子节点",sortTitleShort:"内容排序",sortFieldLabel:"字段:",sortDirectionLabel:"方向:",sortFieldTitle:"选择用于对数组或对象排序的嵌套字段",sortAscending:"升序排序",sortAscendingTitle:"按照该字段升序排序",sortDescending:"降序排序",sortDescendingTitle:"按照该字段降序排序",string:"字符串",transform:"变换",transformTitle:"筛选,排序,或者转换${type}的子节点",transformTitleShort:"筛选,排序,或者转换内容",extract:"提取",extractTitle:"提取这个 ${type}",transformQueryTitle:"输入JMESPath查询",transformWizardLabel:"向导",transformWizardFilter:"筛选",transformWizardSortBy:"排序",transformWizardSelectFields:"选择字段",transformQueryLabel:"查询",transformPreviewLabel:"预览",type:"类型",typeTitle:"更改字段类型",openUrl:"Ctrl+Click 或者 Ctrl+Enter 在新窗口打开链接",undo:"撤销上次动作 (Ctrl+Z)",validationCannotMove:"无法将字段移入其子节点",autoType:'字段类型 "auto". 字段类型由值自动确定 可以为 string,number,boolean,或者 null.',objectType:'字段类型 "object". 对象包含一组无序的键/值对.',arrayType:'字段类型 "array". 数组包含值的有序集合.',stringType:'字段类型 "string". 字段类型由值自动确定,但始终作为字符串返回.',modeCodeText:"代码",modeCodeTitle:"切换至代码高亮",modeFormText:"表单",modeFormTitle:"切换至表单编辑",modeTextText:"文本",modeTextTitle:"切换至文本编辑",modeTreeText:"树",modeTreeTitle:"切换至树编辑",modeViewText:"视图",modeViewTitle:"切换至树视图",modePreviewText:"预览",modePreviewTitle:"切换至预览模式",examples:"例子",default:"缺省",containsInvalidProperties:"包含无效的属性",containsInvalidItems:"包含无效项目"},"pt-BR":{array:"Lista",auto:"Automatico",appendText:"Adicionar",appendTitle:"Adicionar novo campo com tipo 'auto' depois deste campo (Ctrl+Shift+Ins)",appendSubmenuTitle:"Selecione o tipo do campo a ser adicionado",appendTitleAuto:"Adicionar novo campo com tipo 'auto' (Ctrl+Shift+Ins)",ascending:"Ascendente",ascendingTitle:"Organizar filhor do tipo ${type} em crescente",actionsMenu:"Clique para abrir o menu de ações (Ctrl+M)",cannotParseFieldError:"Não é possível analisar o campo no JSON",cannotParseValueError:"Não é possível analisar o valor em JSON",collapseAll:"Fechar todos campos",compactTitle:"Dados JSON compactos, remova todos os espaços em branco (Ctrl+Shift+\\)",descending:"Descendente",descendingTitle:"Organizar o filhos do tipo ${type} em decrescente",duplicateKey:"chave duplicada",drag:"Arraste para mover este campo (Alt+Shift+Arrows)",duplicateText:"Duplicar",duplicateTitle:"Duplicar campos selecionados (Ctrl+D)",duplicateField:"Duplicar este campo (Ctrl+D)",duplicateFieldError:"Nome do campo duplicado",empty:"vazio",expandAll:"Expandir todos campos",expandTitle:"Clique para expandir/encolher este campo (Ctrl+E). \nCtrl+Click para expandir/encolher incluindo todos os filhos.",formatTitle:"Formate dados JSON, com recuo e feeds de linha adequados (Ctrl+\\)",insert:"Inserir",insertTitle:"Inserir um novo campo do tipo 'auto' antes deste campo (Ctrl+Ins)",insertSub:"Selecionar o tipo de campo a ser inserido",object:"Objeto",ok:"Ok",redo:"Refazer (Ctrl+Shift+Z)",removeText:"Remover",removeTitle:"Remover campos selecionados (Ctrl+Del)",removeField:"Remover este campo (Ctrl+Del)",repairTitle:"Repare JSON: corrija aspas e caracteres de escape, remova comentários e notação JSONP, transforme objetos JavaScript em JSON.",selectNode:"Selecione um nódulo...",showAll:"mostrar todos",showMore:"mostrar mais",showMoreStatus:"exibindo ${visibleChilds} de ${totalChilds} itens.",sort:"Organizar",sortTitle:"Organizar os filhos deste ${type}",sortTitleShort:"Organizar os filhos",sortFieldLabel:"Campo:",sortDirectionLabel:"Direção:",sortFieldTitle:"Selecione um campo filho pelo qual ordenar o array ou objeto",sortAscending:"Ascendente",sortAscendingTitle:"Ordenar o campo selecionado por ordem ascendente",sortDescending:"Descendente",sortDescendingTitle:"Ordenar o campo selecionado por ordem descendente",string:"Texto",transform:"Transformar",transformTitle:"Filtrar, ordenar ou transformar os filhos deste ${type}",transformTitleShort:"Filtrar, ordenar ou transformar conteúdos",transformQueryTitle:"Insira uma expressão JMESPath",transformWizardLabel:"Assistente",transformWizardFilter:"Filtro",transformWizardSortBy:"Ordenar por",transformWizardSelectFields:"Selecionar campos",transformQueryLabel:"Expressão",transformPreviewLabel:"Visualizar",type:"Tipo",typeTitle:"Mudar o tipo deste campo",openUrl:"Ctrl+Click ou Ctrl+Enter para abrir link em nova janela",undo:"Desfazer último ação (Ctrl+Z)",validationCannotMove:"Não pode mover um campo como filho dele mesmo",autoType:'Campo do tipo "auto". O tipo do campo é determinao automaticamente a partir do seu valor e pode ser texto, número, verdade/falso ou nulo.',objectType:'Campo do tipo "objeto". Um objeto contém uma lista de pares com chave e valor.',arrayType:'Campo do tipo "lista". Uma lista contem uma coleção de valores ordenados.',stringType:'Campo do tipo "string". Campo do tipo nao é determinado através do seu valor, mas sempre retornara um texto.',examples:"Exemplos",default:"Revelia",containsInvalidProperties:"Contém propriedades inválidas",containsInvalidItems:"Contém itens inválidos"},tr:{array:"Dizin",auto:"Otomatik",appendText:"Ekle",appendTitle:"Bu alanın altına 'otomatik' tipinde yeni bir alan ekle (Ctrl+Shift+Ins)",appendSubmenuTitle:"Eklenecek alanın tipini seç",appendTitleAuto:"'Otomatik' tipinde yeni bir alan ekle (Ctrl+Shift+Ins)",ascending:"Artan",ascendingTitle:"${type}'ın alt tiplerini artan düzende sırala",actionsMenu:"Aksiyon menüsünü açmak için tıklayın (Ctrl+M)",collapseAll:"Tüm alanları kapat",descending:"Azalan",descendingTitle:"${type}'ın alt tiplerini azalan düzende sırala",drag:"Bu alanı taşımak için sürükleyin (Alt+Shift+Arrows)",duplicateKey:"Var olan anahtar",duplicateText:"Aşağıya kopyala",duplicateTitle:"Seçili alanlardan bir daha oluştur (Ctrl+D)",duplicateField:"Bu alandan bir daha oluştur (Ctrl+D)",duplicateFieldError:"Duplicate field name",cannotParseFieldError:"Alan JSON'a ayrıştırılamıyor",cannotParseValueError:"JSON'a değer ayrıştırılamıyor",empty:"boş",expandAll:"Tüm alanları aç",expandTitle:"Bu alanı açmak/kapatmak için tıkla (Ctrl+E). \nAlt alanlarda dahil tüm alanları açmak için Ctrl+Click ",insert:"Ekle",insertTitle:"Bu alanın üstüne 'otomatik' tipinde yeni bir alan ekle (Ctrl+Ins)",insertSub:"Araya eklenecek alanın tipini seç",object:"Nesne",ok:"Tamam",redo:"Yeniden yap (Ctrl+Shift+Z)",removeText:"Kaldır",removeTitle:"Seçilen alanları kaldır (Ctrl+Del)",removeField:"Bu alanı kaldır (Ctrl+Del)",selectNode:"Bir nesne seç...",showAll:"tümünü göster",showMore:"daha fazla göster",showMoreStatus:"${totalChilds} alanın ${visibleChilds} alt alanları gösteriliyor",sort:"Sırala",sortTitle:"${type}'ın alt alanlarını sırala",sortTitleShort:"İçerikleri sırala",sortFieldLabel:"Alan:",sortDirectionLabel:"Yön:",sortFieldTitle:"Diziyi veya nesneyi sıralamak için iç içe geçmiş alanı seçin",sortAscending:"Artan",sortAscendingTitle:"Seçili alanı artan düzende sırala",sortDescending:"Azalan",sortDescendingTitle:"Seçili alanı azalan düzende sırala",string:"Karakter Dizisi",transform:"Dönüştür",transformTitle:"${type}'ın alt alanlarını filtrele, sırala veya dönüştür",transformTitleShort:"İçerikleri filterele, sırala veya dönüştür",transformQueryTitle:"JMESPath sorgusu gir",transformWizardLabel:"Sihirbaz",transformWizardFilter:"Filtre",transformWizardSortBy:"Sırala",transformWizardSelectFields:"Alanları seç",transformQueryLabel:"Sorgu",transformPreviewLabel:"Önizleme",type:"Tip",typeTitle:"Bu alanın tipini değiştir",openUrl:"URL'i yeni bir pencerede açmak için Ctrl+Click veya Ctrl+Enter",undo:"Son değişikliği geri al (Ctrl+Z)",validationCannotMove:"Alt alan olarak taşınamıyor",autoType:'Alan tipi "otomatik". Alan türü otomatik olarak değerden belirlenirve bir dize, sayı, boolean veya null olabilir.',objectType:'Alan tipi "nesne". Bir nesne, sıralanmamış bir anahtar / değer çifti kümesi içerir.',arrayType:'Alan tipi "dizi". Bir dizi, düzenli değerler koleksiyonu içerir.',stringType:'Alan tipi "karakter dizisi". Alan türü değerden belirlenmez,ancak her zaman karakter dizisi olarak döndürülür.',modeCodeText:"Kod",modeCodeTitle:"Kod vurgulayıcıya geç",modeFormText:"Form",modeFormTitle:"Form düzenleyiciye geç",modeTextText:"Metin",modeTextTitle:"Düz metin düzenleyiciye geç",modeTreeText:"Ağaç",modeTreeTitle:"Ağaç düzenleyiciye geç",modeViewText:"Görünüm",modeViewTitle:"Ağaç görünümüne geç",examples:"Örnekler",default:"Varsayılan",containsInvalidProperties:"Geçersiz özellikler içeriyor",containsInvalidItems:"Geçersiz öğeler içeriyor"},ja:{array:"配列",auto:"オート",appendText:"追加",appendTitle:'次のフィールドに"オート"のフィールドを追加 (Ctrl+Shift+Ins)',appendSubmenuTitle:"追加するフィールドの型を選択してください",appendTitleAuto:'"オート"のフィールドを追加 (Ctrl+Shift+Ins)',ascending:"昇順",ascendingTitle:"${type}の子要素を昇順に並べ替え",actionsMenu:"クリックしてアクションメニューを開く (Ctrl+M)",collapseAll:"すべてを折りたたむ",descending:"降順",descendingTitle:"${type}の子要素を降順に並べ替え",drag:"ドラッグして選択中のフィールドを移動 (Alt+Shift+Arrows)",duplicateKey:"複製キー",duplicateText:"複製",duplicateTitle:"選択中のフィールドを複製 (Ctrl+D)",duplicateField:"選択中のフィールドを複製 (Ctrl+D)",duplicateFieldError:"フィールド名が重複しています",cannotParseFieldError:"JSONのフィールドを解析できません",cannotParseValueError:"JSONの値を解析できません",empty:"空",expandAll:"すべてを展開",expandTitle:"クリックしてフィールドを展開/折りたたむ (Ctrl+E). \nCtrl+Click ですべての子要素を展開/折りたたむ",insert:"挿入",insertTitle:"選択中のフィールドの前に新しいフィールドを挿入 (Ctrl+Ins)",insertSub:"挿入するフィールドの型を選択",object:"オブジェクト",ok:"実行",redo:"やり直す (Ctrl+Shift+Z)",removeText:"削除",removeTitle:"選択中のフィールドを削除 (Ctrl+Del)",removeField:"選択中のフィールドを削除 (Ctrl+Del)",selectNode:"ノードを選択...",showAll:"すべてを表示",showMore:"もっと見る",showMoreStatus:"${totalChilds}個のアイテムのうち ${visibleChilds}個を表示しています。",sort:"並べ替え",sortTitle:"${type}の子要素を並べ替え",sortTitleShort:"並べ替え",sortFieldLabel:"フィールド:",sortDirectionLabel:"順序:",sortFieldTitle:"配列またはオブジェクトを並び替えるためのフィールドを選択",sortAscending:"昇順",sortAscendingTitle:"選択中のフィールドを昇順に並び替え",sortDescending:"降順",sortDescendingTitle:"選択中のフィールドを降順に並び替え",string:"文字列",transform:"変換",transformTitle:"${type}の子要素をフィルター・並び替え・変換する",transformTitleShort:"内容をフィルター・並び替え・変換する",extract:"抽出",extractTitle:"${type}を抽出",transformQueryTitle:"JMESPathクエリを入力",transformWizardLabel:"ウィザード",transformWizardFilter:"フィルター",transformWizardSortBy:"並び替え",transformWizardSelectFields:"フィールドを選択",transformQueryLabel:"クエリ",transformPreviewLabel:"プレビュー",type:"型",typeTitle:"選択中のフィールドの型を変更",openUrl:"Ctrl+Click または Ctrl+Enter で 新規ウィンドウでURLを開く",undo:"元に戻す (Ctrl+Z)",validationCannotMove:"子要素に移動できません ",autoType:"オート: フィールドの型は値から自動的に決定されます。 (文字列・数値・ブール・null)",objectType:"オブジェクト: オブジェクトは順序が決まっていないキーと値のペア組み合わせです。",arrayType:"配列: 配列は順序が決まっている値の集合体です。",stringType:"文字列: フィールド型は値から決定されませんが、常に文字列として返されます。",modeCodeText:"コードモード",modeCodeTitle:"ハイライトモードに切り替え",modeFormText:"フォームモード",modeFormTitle:"フォームモードに切り替え",modeTextText:"テキストモード",modeTextTitle:"テキストモードに切り替え",modeTreeText:"ツリーモード",modeTreeTitle:"ツリーモードに切り替え",modeViewText:"ビューモード",modeViewTitle:"ビューモードに切り替え",modePreviewText:"プレビュー",modePreviewTitle:"プレビューに切り替え",examples:"例",default:"デフォルト",containsInvalidProperties:"無効なプロパティが含まれています",containsInvalidItems:"無効なアイテムが含まれています"},"fr-FR":{array:"Liste",auto:"Auto",appendText:"Ajouter",appendTitle:"Ajouter un champ de type 'auto' après ce champ (Ctrl+Shift+Ins)",appendSubmenuTitle:"Sélectionner le type du champ à ajouter",appendTitleAuto:"Ajouter un champ de type 'auto' (Ctrl+Shift+Ins)",ascending:"Ascendant",ascendingTitle:"Trier les enfants de ce ${type} par ordre ascendant",actionsMenu:"Ouvrir le menu des actions (Ctrl+M)",collapseAll:"Regrouper",descending:"Descendant",descendingTitle:"Trier les enfants de ce ${type} par ordre descendant",drag:"Déplacer (Alt+Shift+Arrows)",duplicateKey:"Dupliquer la clé",duplicateText:"Dupliquer",duplicateTitle:"Dupliquer les champs sélectionnés (Ctrl+D)",duplicateField:"Dupliquer ce champ (Ctrl+D)",duplicateFieldError:"Dupliquer le nom de champ",cannotParseFieldError:"Champ impossible à parser en JSON",cannotParseValueError:"Valeur impossible à parser en JSON",empty:"vide",expandAll:"Étendre",expandTitle:"Étendre/regrouper ce champ (Ctrl+E). \nCtrl+Click pour étendre/regrouper avec tous les champs.",insert:"Insérer",insertTitle:"Insérer un champ de type 'auto' avant ce champ (Ctrl+Ins)",insertSub:"Sélectionner le type de champ à insérer",object:"Objet",ok:"Ok",redo:"Rejouer (Ctrl+Shift+Z)",removeText:"Supprimer",removeTitle:"Supprimer les champs sélectionnés (Ctrl+Del)",removeField:"Supprimer ce champ (Ctrl+Del)",searchTitle:"Rechercher champs et valeurs",searchNextResultTitle:"Résultat suivant (Enter)",searchPreviousResultTitle:"Résultat précédent (Shift + Enter)",selectNode:"Sélectionner un nœud...",showAll:"voir tout",showMore:"voir plus",showMoreStatus:"${visibleChilds} éléments affichés de ${totalChilds}.",sort:"Trier",sortTitle:"Trier les champs de ce ${type}",sortTitleShort:"Trier",sortFieldLabel:"Champ:",sortDirectionLabel:"Direction:",sortFieldTitle:"Sélectionner les champs permettant de trier les listes et objet",sortAscending:"Ascendant",sortAscendingTitle:"Trier les champs sélectionnés par ordre ascendant",sortDescending:"Descendant",sortDescendingTitle:"Trier les champs sélectionnés par ordre descendant",string:"Chaîne",transform:"Transformer",transformTitle:"Filtrer, trier, or transformer les enfants de ce ${type}",transformTitleShort:"Filtrer, trier ou transformer le contenu",extract:"Extraire",extractTitle:"Extraire ce ${type}",transformQueryTitle:"Saisir une requête JMESPath",transformWizardLabel:"Assistant",transformWizardFilter:"Filtrer",transformWizardSortBy:"Trier par",transformWizardSelectFields:"Sélectionner les champs",transformQueryLabel:"Requête",transformPreviewLabel:"Prévisualisation",type:"Type",typeTitle:"Changer le type de ce champ",openUrl:"Ctrl+Click ou Ctrl+Enter pour ouvrir l'url dans une autre fenêtre",undo:"Annuler la dernière action (Ctrl+Z)",validationCannotMove:"Cannot move a field into a child of itself",autoType:'Champe de type "auto". Ce type de champ est automatiquement déterminé en fonction de la valeur et peut être de type "chaîne", "nombre", "booléen" ou null.',objectType:'Champ de type "objet". Un objet contient un ensemble non ordonné de paires clé/valeur.',arrayType:'Champ de type "liste". Une liste contient une collection ordonnée de valeurs.',stringType:'Champ de type "chaîne". Ce type de champ n\'est pas déterminé en fonction de la valeur, mais retourne systématiquement une chaîne de caractères.',modeEditorTitle:"Changer mode d'édition",modeCodeText:"Code",modeCodeTitle:"Activer surlignage code",modeFormText:"Formulaire",modeFormTitle:"Activer formulaire",modeTextText:"Texte",modeTextTitle:"Activer éditeur texte",modeTreeText:"Arbre",modeTreeTitle:"Activer éditeur arbre",modeViewText:"Lecture seule",modeViewTitle:"Activer vue arbre",modePreviewText:"Prévisualisation",modePreviewTitle:"Activer mode prévisualiser",examples:"Exemples",default:"Défaut",containsInvalidProperties:"Contient des propriétés non valides",containsInvalidItems:"Contient des éléments invalides"},de:{array:"Auflistung",auto:"Auto",appendText:"anhängen",appendTitle:"Fügen Sie nach diesem Feld ein neues Feld mit dem Typ 'auto' ein (Strg+Umschalt+Ein)",appendSubmenuTitle:"Wählen Sie den Typ des neuen Feldes",appendTitleAuto:"Ein neues Feld vom Typ 'auto' hinzufügen (Strg+Umschalt+Ein)",ascending:"Aufsteigend",ascendingTitle:"Sortieren Sie die Elemente dieses ${type} in aufsteigender Reihenfolge",actionsMenu:"Klicken Sie zum Öffnen des Aktionsmenüs (Strg+M)",cannotParseFieldError:"Feld kann nicht in JSON geparst werden",cannotParseValueError:"Wert kann nicht in JSON geparst werden",collapseAll:"Alle Felder zuklappen",compactTitle:"JSON-Daten verdichten, alle Leerzeichen entfernen (Strg+Umschalt+\\)",descending:"Absteigend",descendingTitle:"Sortieren Sie die Elemente dieses ${type} in absteigender Reihenfolge",drag:"Ziehen, um dieses Feld zu verschieben (Alt+Umschalt+Pfeile)",duplicateKey:"Doppelter Schlüssel",duplicateText:"Duplikat",duplicateTitle:"Ausgewählte Felder duplizieren (Strg+D)",duplicateField:"Dieses Feld duplizieren (Strg+D)",duplicateFieldError:"Doppelter Feldname",empty:"leer",expandAll:"Alle Felder anzeigen",expandTitle:"Klicken Sie, um dieses Feld zu erweitern/zu kollabieren (Strg+E). \nStrg+Klicken Sie, um dieses Feld einschließlich aller Elemente zu erweitern/zu kollabieren.",formatTitle:"JSON-Daten mit korrekter Einrückung und Zeilenvorschüben formatieren (Strg+\\)",insert:"einfügen",insertTitle:"Fügen Sie vor diesem Feld ein neues Feld mit dem Typ 'auto' ein (Strg+Einfg)",insertSub:"Wählen Sie den Typ des neuen Feldes",object:"Objekt",ok:"Ok",redo:"Wiederholen (Strg+Umschalt+Z)",removeText:"entfernen",removeTitle:"Ausgewählte Felder entfernen (Strg+Entf)",removeField:"Dieses Feld entfernen (Strg+Entf)",repairTitle:"JSON reparieren: Anführungszeichen und Escape-Zeichen korrigieren, Kommentare und JSONP-Notation entfernen, JavaScript-Objekte in JSON umwandeln.",searchTitle:"Suchfelder und Werte",searchNextResultTitle:"Nächstes Ergebnis (Enter)",searchPreviousResultTitle:"Vorheriges Ergebnis (Umschalt + Eingabe)",selectNode:"Wählen Sie einen Knoten aus...",showAll:"alle anzeigen",showMore:"mehr anzeigen",showMoreStatus:"Anzeige von ${visibleChilds} von ${totalChilds}-Elementen.",sort:"Sortieren",sortTitle:"Sortieren Sie die Elemente dieses ${type}",sortTitleShort:"Inhalt sortieren",sortFieldLabel:"Feld:",sortDirectionLabel:"Richtung:",sortFieldTitle:"Wählen Sie das verschachtelte Feld, nach dem das Array oder Objekt sortiert werden soll.",sortAscending:"Aufsteigend",sortAscendingTitle:"Sortieren Sie das ausgewählte Feld in aufsteigender Reihenfolge",sortDescending:"Absteigend",sortDescendingTitle:"Sortieren Sie das ausgewählte Feld in absteigender Reihenfolge",string:"Zeichenfolge",transform:"Verwandeln",transformTitle:"Die Elemente dieses ${type} filtern, sortieren oder transformieren",transformTitleShort:"Inhalte filtern, sortieren oder transformieren",extract:"Auszug",extractTitle:"Extrahieren Sie diesen ${type}",transformQueryTitle:"Eine JMESPath-Abfrage eingeben",transformWizardLabel:"Zauberer",transformWizardFilter:"Filter",transformWizardSortBy:"Sortieren nach",transformWizardSelectFields:"Felder auswählen",transformQueryLabel:"Anfrage",transformPreviewLabel:"Vorschau",type:"Geben Sie ein.",typeTitle:"Ändern Sie den Typ dieses Feldes",openUrl:"Strg+Klicken oder Strg+Eingabe, um die URL in einem neuen Fenster zu öffnen",undo:"Letzte Aktion rückgängig machen (Strg+Z)",validationCannotMove:"Kann ein Feld nicht in ein Kind seiner selbst verschieben",autoType:'Feldtyp "auto". Der Feldtyp wird automatisch aus dem Wert bestimmt und kann ein String, eine Zahl, boolesch oder null sein.',objectType:'Feldtyp "Objekt". Ein Objekt enthält eine ungeordnete Menge von Schlüssel/Wert-Paaren.',arrayType:'Feldtyp "Array". Ein Array enthält eine geordnete Sammlung von Werten.',stringType:'Feldtyp "Zeichenfolge". Der Feldtyp wird nicht aus dem Wert bestimmt, sondern immer als Zeichenfolge zurückgegeben.',modeEditorTitle:"Editor-Modus umschalten",modeCodeText:"Code",modeCodeTitle:"Umschalten auf Code-Highlighter",modeFormText:"Formular",modeFormTitle:"Zum Formular-Editor wechseln",modeTextText:"Text",modeTextTitle:"Zum Editor für einfachen Text wechseln",modeTreeText:"Baum",modeTreeTitle:"Zum Baum-Editor wechseln",modeViewText:"Siehe",modeViewTitle:"Zur Baumansicht wechseln",modePreviewText:"Vorschau",modePreviewTitle:"In den Vorschau-Modus wechseln",examples:"Beispiele",default:"Standardmäßig",containsInvalidProperties:"Enthält ungültige Eigenschaften",containsInvalidItems:"Enthält ungültige Elemente"}},s="en",o="undefined"!=typeof navigator?navigator.language||navigator.userLanguage:void 0,a=i.find(function(e){return e===o})||s;function l(t){var e;t&&((e=i.find(function(e){return e===t}))?a=e:console.error("Language not found"))}function d(e){if(e)for(var t in e)!function(t){i.find(function(e){return e===t})||i.push(t),r[t]=Object.assign({},r[s],r[t],e[t])}(t)}function c(e,t,n){var i=r[n=n||a][e]||r[s][e]||e;if(t)for(var o in t)i=i.replace("${"+o+"}",t[o]);return i}},56:function(e,t,n){"use strict";n.d(t,{r:function(){return o},J:function(){return r}});var t=n(156),i=n.n(t),s=n(791);function o(e,t){var n=t.sort,i=t.filter,o=t.projection,r="";return i?(t="@"!==i.field?["0"].concat((0,s.parsePath)("."+i.field)):["0"],t="string"==typeof(0,s.get)(e,t)?i.value:(0,s.parseString)(i.value),r+="[? "+i.field+" "+i.relation+" `"+JSON.stringify(t)+"`]"):r+=Array.isArray(e)?"[*]":"@",n&&("desc"===n.direction?r+=" | reverse(sort_by(@, &"+n.field+"))":r+=" | sort_by(@, &"+n.field+")"),o&&("]"!==r[r.length-1]&&(r+=" | [*]"),1===o.fields.length?r+="."+o.fields[0]:1<o.fields.length&&(r+=".{"+o.fields.map(function(e){var t=e.split(".");return t[t.length-1]+": "+e}).join(", ")+"}")),r}function r(e,t){return i().search(e,t)}},987:function(){function e(e){"remove"in e||Object.defineProperty(e,"remove",{configurable:!0,enumerable:!0,writable:!0,value:function(){void 0!==this.parentNode&&this.parentNode.removeChild(this)}})}"undefined"!=typeof Element&&(void 0!==window.Element&&e(window.Element.prototype),void 0!==window.CharacterData&&e(window.CharacterData.prototype),void 0!==window.DocumentType&&e(window.DocumentType.prototype)),Array.prototype.findIndex||Object.defineProperty(Array.prototype,"findIndex",{value:function(e){for(var t=0;t<this.length;t++){var n=this[t];if(e.call(this,n,t,this))return t}return-1},configurable:!0,writable:!0}),Array.prototype.find||Object.defineProperty(Array.prototype,"find",{value:function(e){e=this.findIndex(e);return this[e]},configurable:!0,writable:!0}),String.prototype.trim||(String.prototype.trim=function(){return this.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"")})},341:function(e,t,n){"use strict";n.r(t),n.d(t,{previewModeMixins:function(){return m}});var t=n(664),i=n.n(t),s=n(188),o=n(436),r=n(474);function a(e,t){for(var n=0;n<t.length;n++){var i=t[n];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,i.key,i)}}var l=function(){function i(e,t,n){!function(e){if(!(e instanceof i))throw new TypeError("Cannot call a class as a function")}(this),this.onChange=e,this.calculateItemSize=t||function(){return 1},this.limit=n,this.items=[],this.index=-1}var e,t,n;return e=i,(t=[{key:"add",value:function(e){for(;this._calculateHistorySize()>this.limit&&1<this.items.length;)this.items.shift(),this.index--;this.items=this.items.slice(0,this.index+1),this.items.push(e),this.index++,this.onChange()}},{key:"_calculateHistorySize",value:function(){var t=this.calculateItemSize,n=0;return this.items.forEach(function(e){n+=t(e)}),n}},{key:"undo",value:function(){if(this.canUndo())return this.index--,this.onChange(),this.items[this.index]}},{key:"redo",value:function(){if(this.canRedo())return this.index++,this.onChange(),this.items[this.index]}},{key:"canUndo",value:function(){return 0<this.index}},{key:"canRedo",value:function(){return this.index<this.items.length-1}},{key:"clear",value:function(){this.items=[],this.index=-1,this.onChange()}}])&&a(e.prototype,t),n&&a(e,n),i}(),d=n(907),c=n(56),h=n(617),u=n(210),p=n(558),t=n(956),f=n(791),n=t.textModeMixins[0].mixin,t={};t.create=function(e){var t=1<arguments.length&&void 0!==arguments[1]?arguments[1]:{};void 0===t.statusBar&&(t.statusBar=!0),t.mainMenuBar=!1!==t.mainMenuBar,t.enableSort=!1!==t.enableSort,t.enableTransform=!1!==t.enableTransform,t.createQuery=t.createQuery||c.r,t.executeQuery=t.executeQuery||c.J,"number"==typeof(this.options=t).indentation?this.indentation=Number(t.indentation):this.indentation=2,(0,d.cC)(this.options.languages),(0,d.m0)(this.options.language),this.mode="preview";var n=this;this.container=e,this.dom={},this.json=void 0,this.text="",this._debouncedValidate=(0,f.debounce)(this.validate.bind(this),this.DEBOUNCE_INTERVAL),this.width=e.clientWidth,this.height=e.clientHeight,this.frame=document.createElement("div"),this.frame.className="jsoneditor jsoneditor-mode-preview",this.frame.onclick=function(e){e.preventDefault()};var i,e={target:this.frame,onFocus:this.options.onFocus||null,onBlur:this.options.onBlur||null};this.frameFocusTracker=new r.R(e),this.content=document.createElement("div"),this.content.className="jsoneditor-outer",this.dom.busy=document.createElement("div"),this.dom.busy.className="jsoneditor-busy",this.dom.busyContent=document.createElement("span"),this.dom.busyContent.textContent="busy...",this.dom.busy.appendChild(this.dom.busyContent),this.content.appendChild(this.dom.busy),this.dom.previewContent=document.createElement("pre"),this.dom.previewContent.className="jsoneditor-preview",this.dom.previewText=document.createTextNode(""),this.dom.previewContent.appendChild(this.dom.previewText),this.content.appendChild(this.dom.previewContent),this.options.mainMenuBar&&((0,f.addClassName)(this.content,"has-main-menu-bar"),this.menu=document.createElement("div"),this.menu.className="jsoneditor-menu",this.frame.appendChild(this.menu),(e=document.createElement("button")).type="button",e.className="jsoneditor-format",e.title=(0,d.Iu)("formatTitle"),this.menu.appendChild(e),e.onclick=function(){n.executeWithBusyMessage(function(){try{n.format()}catch(e){n._onError(e)}},"formatting...")},(e=document.createElement("button")).type="button",e.className="jsoneditor-compact",e.title=(0,d.Iu)("compactTitle"),this.menu.appendChild(e),e.onclick=function(){n.executeWithBusyMessage(function(){try{n.compact()}catch(e){n._onError(e)}},"compacting...")},this.options.enableSort&&((e=document.createElement("button")).type="button",e.className="jsoneditor-sort",e.title=(0,d.Iu)("sortTitleShort"),e.onclick=function(){n._showSortModal()},this.menu.appendChild(e)),this.options.enableTransform&&((i=document.createElement("button")).type="button",i.title=(0,d.Iu)("transformTitleShort"),i.className="jsoneditor-transform",i.onclick=function(){n._showTransformModal()},this.dom.transform=i,this.menu.appendChild(i)),(i=document.createElement("button")).type="button",i.className="jsoneditor-repair",i.title=(0,d.Iu)("repairTitle"),this.menu.appendChild(i),!(i.onclick=function(){void 0===n.json&&n.executeWithBusyMessage(function(){try{n.repair()}catch(e){n._onError(e)}},"repairing...")})!==this.options.history&&(this.history=new l(function(){n.dom.undo.disabled=!n.history.canUndo(),n.dom.redo.disabled=!n.history.canRedo()},function(e){return 2*e.text.length},s.oW),(i=document.createElement("button")).type="button",i.className="jsoneditor-undo jsoneditor-separator",i.title=(0,d.Iu)("undo"),i.onclick=function(){var e=n.history.undo();e&&n._applyHistory(e)},this.menu.appendChild(i),this.dom.undo=i,(i=document.createElement("button")).type="button",i.className="jsoneditor-redo",i.title=(0,d.Iu)("redo"),i.onclick=function(){var e=n.history.redo();e&&n._applyHistory(e)},this.menu.appendChild(i),this.dom.redo=i,this.history.onChange()),this.options&&this.options.modes&&this.options.modes.length&&(this.modeSwitcher=new h.x(this.menu,this.options.modes,this.options.mode,function(e){n.setMode(e),n.modeSwitcher.focus()}))),this.errorTable=new o.Q({errorTableVisible:!0,onToggleVisibility:function(){n.validate()},onFocusLine:null,onChangeHeight:function(e){e=e+(n.dom.statusBar?n.dom.statusBar.clientHeight:0)+1;n.content.style.marginBottom=-e+"px",n.content.style.paddingBottom=e+"px"}}),this.frame.appendChild(this.content),this.frame.appendChild(this.errorTable.getErrorTable()),this.container.appendChild(this.frame),t.statusBar&&((0,f.addClassName)(this.content,"has-status-bar"),t=document.createElement("div"),(this.dom.statusBar=t).className="jsoneditor-statusbar",this.frame.appendChild(t),this.dom.fileSizeInfo=document.createElement("span"),this.dom.fileSizeInfo.className="jsoneditor-size-info",this.dom.fileSizeInfo.innerText="",t.appendChild(this.dom.fileSizeInfo),this.dom.arrayInfo=document.createElement("span"),this.dom.arrayInfo.className="jsoneditor-size-info",this.dom.arrayInfo.innerText="",t.appendChild(this.dom.arrayInfo),t.appendChild(this.errorTable.getErrorCounter()),t.appendChild(this.errorTable.getWarningIcon()),t.appendChild(this.errorTable.getErrorIcon())),this._renderPreview(),this.setSchema(this.options.schema,this.options.schemaRefs)},t._renderPreview=function(){var e=this.getText();this.dom.previewText.nodeValue=(0,f.limitCharacters)(e,s.WF),this.dom.fileSizeInfo&&(this.dom.fileSizeInfo.innerText="Size: "+(0,f.formatSize)(e.length)),this.dom.arrayInfo&&(Array.isArray(this.json)?this.dom.arrayInfo.innerText="Array: "+this.json.length+" items":this.dom.arrayInfo.innerText="")},t._onChange=function(){if(this._debouncedValidate(),this.options.onChange)try{this.options.onChange()}catch(e){console.error("Error in onChange callback: ",e)}if(this.options.onChangeJSON)try{this.options.onChangeJSON(this.get())}catch(e){console.error("Error in onChangeJSON callback: ",e)}if(this.options.onChangeText)try{this.options.onChangeText(this.getText())}catch(e){console.error("Error in onChangeText callback: ",e)}},t._showSortModal=function(){var r=this;this.executeWithBusyMessage(function(){var e=r.options.modalAnchor||s.qD,o=r.get();r._renderPreview(),(0,u.showSortModal)(e,o,function(i){r.executeWithBusyMessage(function(){var e,t,n;e=o,t=i,Array.isArray(e)&&(n=(0,f.sort)(e,t.path,t.direction),r.sortedBy=t,r._setAndFireOnChange(n)),(0,f.isObject)(e)&&(e=(0,f.sortObjectKeys)(e,t.direction),r.sortedBy=t,r._setAndFireOnChange(e))},"sorting...")},r.sortedBy)},"parsing...")},t._showTransformModal=function(){var r=this;this.executeWithBusyMessage(function(){var e=r.options,t=e.createQuery,n=e.executeQuery,i=e.modalAnchor,e=e.queryDescription,o=r.get();r._renderPreview(),(0,p.showTransformModal)({container:i||s.qD,json:o,queryDescription:e,createQuery:t,executeQuery:n,onTransform:function(t){r.executeWithBusyMessage(function(){var e=n(o,t);r._setAndFireOnChange(e)},"transforming...")}})},"parsing...")},t.destroy=function(){this.frame&&this.container&&this.frame.parentNode===this.container&&this.container.removeChild(this.frame),this.modeSwitcher&&(this.modeSwitcher.destroy(),this.modeSwitcher=null),this._debouncedValidate=null,this.history&&(this.history.clear(),this.history=null),this.frameFocusTracker.destroy()},t.compact=function(){var e=this.get(),t=JSON.stringify(e);this._setTextAndFireOnChange(t,e)},t.format=function(){var e=this.get(),t=JSON.stringify(e,null,this.indentation);this._setTextAndFireOnChange(t,e)},t.repair=function(){var e=this.getText();try{var t=i()(e);this._setTextAndFireOnChange(t)}catch(e){}},t.focus=function(){this.dom.transform.focus()},t.set=function(e){this.history&&this.history.clear(),this._set(e)},t.update=function(e){this._set(e)},t._set=function(e){this.text=void 0,this.json=e,this._renderPreview(),this._pushHistory(),this._debouncedValidate()},t._setAndFireOnChange=function(e){this._set(e),this._onChange()},t.get=function(){var e;return void 0===this.json&&(e=this.getText(),this.json=(0,f.parse)(e)),this.json},t.getText=function(){return void 0===this.text&&(this.text=JSON.stringify(this.json,null,this.indentation),!0===this.options.escapeUnicode&&(this.text=(0,f.escapeUnicodeChars)(this.text))),this.text},t.setText=function(e){this.history&&this.history.clear(),this._setText(e)},t.updateText=function(e){this.getText()!==e&&this._setText(e)},t._setText=function(e,t){var n;!0===this.options.escapeUnicode?this.text=(0,f.escapeUnicodeChars)(e):this.text=e,this.json=t,this._renderPreview(),void 0===this.json?(n=this).executeWithBusyMessage(function(){try{n.json=n.get(),n._renderPreview(),n._pushHistory()}catch(e){}},"parsing..."):this._pushHistory(),this._debouncedValidate()},t._setTextAndFireOnChange=function(e,t){this._setText(e,t),this._onChange()},t._applyHistory=function(e){this.json=e.json,this.text=e.text,this._renderPreview(),this._debouncedValidate()},t._pushHistory=function(){var e;this.history&&(e={text:this.text,json:this.json},this.history.add(e))},t.executeWithBusyMessage=function(e,t){var n;this.getText().length>s.EX?(n=this,(0,f.addClassName)(n.frame,"busy"),n.dom.busyContent.innerText=t,setTimeout(function(){e(),(0,f.removeClassName)(n.frame,"busy"),n.dom.busyContent.innerText=""},100)):e()},t.validate=n.validate,t._renderErrors=n._renderErrors;var m=[{mode:"preview",mixin:t,data:"json"}]},210:function(e,t,n){"use strict";n.r(t),n.d(t,{showSortModal:function(){return s}});var t=n(483),i=n.n(t),o=n(907),r=n(791);function s(e,t,s,n){var a=Array.isArray(t)?(0,r.getChildPaths)(t):[""],l=n&&n.path&&(0,r.contains)(a,n.path)?n.path:a[0],d=n&&n.direction||"asc",n='<div class="pico-modal-contents"><div class="pico-modal-header">'+(0,o.Iu)("sort")+"</div><form><table><tbody><tr> <td>"+(0,o.Iu)("sortFieldLabel")+' </td> <td class="jsoneditor-modal-input"> <div class="jsoneditor-select-wrapper"> <select id="field" title="'+(0,o.Iu)("sortFieldTitle")+'"> </select> </div> </td></tr><tr> <td>'+(0,o.Iu)("sortDirectionLabel")+' </td> <td class="jsoneditor-modal-input"> <div id="direction" class="jsoneditor-button-group"><input type="button" value="'+(0,o.Iu)("sortAscending")+'" title="'+(0,o.Iu)("sortAscendingTitle")+'" data-value="asc" class="jsoneditor-button-first jsoneditor-button-asc"/><input type="button" value="'+(0,o.Iu)("sortDescending")+'" title="'+(0,o.Iu)("sortDescendingTitle")+'" data-value="desc" class="jsoneditor-button-last jsoneditor-button-desc"/> </div> </td></tr><tr><td colspan="2" class="jsoneditor-modal-input jsoneditor-modal-actions"> <input type="submit" id="ok" value="'+(0,o.Iu)("ok")+'" /></td></tr></tbody></table></form></div>';i()({parent:e,content:n,overlayClass:"jsoneditor-modal-overlay",overlayStyles:{backgroundColor:"rgb(1,1,1)",opacity:.3},modalClass:"jsoneditor-modal jsoneditor-modal-sort"}).afterCreate(function(t){var e=t.modalElem().querySelector("form"),n=t.modalElem().querySelector("#ok"),i=t.modalElem().querySelector("#field"),o=t.modalElem().querySelector("#direction");function r(e){o.value=e,o.className="jsoneditor-button-group jsoneditor-button-group-value-"+o.value}a.forEach(function(e){var t,n=document.createElement("option");n.text=""===(t=e)?"@":"."===t[0]?t.slice(1):t,n.value=e,i.appendChild(n)}),i.value=l||a[0],r(d||"asc"),o.onclick=function(e){r(e.target.getAttribute("data-value"))},n.onclick=function(e){e.preventDefault(),e.stopPropagation(),t.close(),s({path:i.value,direction:o.value})},e&&(e.onsubmit=n.onclick)}).afterClose(function(e){e.destroy()}).show()}},558:function(e,t,n){"use strict";n.r(t),n.d(t,{showTransformModal:function(){return a}});var t=n(483),i=n.n(t),t=n(879),w=n.n(t),o=n(907);function r(e){return(r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function S(e,t,n,i){return"boolean"==typeof e||e instanceof Boolean||null===e||"number"==typeof e||e instanceof Number||"string"==typeof e||e instanceof String||e instanceof Date?JSON.stringify(e):Array.isArray(e)?function(e,t,n,i){for(var o=t?n+t:void 0,r=t?"[\n":"[",s=0;s<e.length;s++){var a=e[s];if(t&&(r+=o),r+=void 0!==a&&"function"!=typeof a?S(a,t,o,i):"null",s<e.length-1&&(r+=t?",\n":","),r.length>i)return r+"..."}return r+=t?"\n"+n+"]":"]"}(e,t,n,i):e&&"object"===r(e)?function(e,t,n,i){var o,r=t?n+t:void 0,s=!0,a=t?"{\n":"{";if("function"==typeof e.toJSON)return S(e.toJSON(),t,n,i);for(o in e)if(function(e,t){return Object.prototype.hasOwnProperty.call(e,t)}(e,o)){var l=e[o];if(s?s=!1:a+=t?",\n":",",a+=t?r+'"'+o+'": ':'"'+o+'":',(a+=S(l,t,r,i)).length>i)return a+"..."}return a+=t?"\n"+n+"}":"}"}(e,t,n,i):void 0}function N(e,t){for(var n="";0<t--;)n+=e;return n}var k=n(791),I=n(188),s='Enter a <a href="http://jmespath.org" target="_blank">JMESPath</a> query to filter, sort, or transform the JSON data.<br/>To learn JMESPath, go to <a href="http://jmespath.org/tutorial.html" target="_blank">the interactive tutorial</a>.';function a(e){var t=e.container,x=e.json,n=e.queryDescription,n=void 0===n?s:n,C=e.createQuery,E=e.executeQuery,_=e.onTransform,T=x,n='<label class="pico-modal-contents"><div class="pico-modal-header">'+(0,o.Iu)("transform")+"</div><p>"+n+'</p><div class="jsoneditor-jmespath-label">'+(0,o.Iu)("transformWizardLabel")+' </div><div id="wizard" class="jsoneditor-jmespath-block jsoneditor-jmespath-wizard"> <table class="jsoneditor-jmespath-wizard-table"> <tbody> <tr> <th>'+(0,o.Iu)("transformWizardFilter")+'</th> <td class="jsoneditor-jmespath-filter"> <div class="jsoneditor-inline jsoneditor-jmespath-filter-field" > <select id="filterField"> </select> </div> <div class="jsoneditor-inline jsoneditor-jmespath-filter-relation" > <select id="filterRelation"> <option value="==">==</option> <option value="!=">!=</option> <option value="<">&lt;</option> <option value="<=">&lt;=</option> <option value=">">&gt;</option> <option value=">=">&gt;=</option> </select> </div> <div class="jsoneditor-inline jsoneditor-jmespath-filter-value" > <input type="text" class="value" placeholder="value..." id="filterValue" /> </div> </td> </tr> <tr> <th>'+(0,o.Iu)("transformWizardSortBy")+'</th> <td class="jsoneditor-jmespath-filter"> <div class="jsoneditor-inline jsoneditor-jmespath-sort-field"> <select id="sortField"> </select> </div> <div class="jsoneditor-inline jsoneditor-jmespath-sort-order" > <select id="sortOrder"> <option value="asc">Ascending</option> <option value="desc">Descending</option> </select> </div> </td> </tr> <tr id="selectFieldsPart"> <th>'+(0,o.Iu)("transformWizardSelectFields")+'</th> <td class="jsoneditor-jmespath-filter"> <select class="jsoneditor-jmespath-select-fields" id="selectFields" multiple></select> </td> </tr> </tbody> </table></div><div class="jsoneditor-jmespath-label">'+(0,o.Iu)("transformQueryLabel")+' </div><div class="jsoneditor-jmespath-block"> <textarea id="query" rows="4" autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false" title="'+(0,o.Iu)("transformQueryTitle")+'">[*]</textarea></div><div class="jsoneditor-jmespath-label">'+(0,o.Iu)("transformPreviewLabel")+' </div><div class="jsoneditor-jmespath-block"> <textarea id="preview" class="jsoneditor-transform-preview" readonly> </textarea></div><div class="jsoneditor-jmespath-block jsoneditor-modal-actions"> <input type="submit" id="ok" value="'+(0,o.Iu)("ok")+'" autofocus /></div></div>';i()({parent:t,content:n,overlayClass:"jsoneditor-modal-overlay",overlayStyles:{backgroundColor:"rgb(1,1,1)",opacity:.3},modalClass:"jsoneditor-modal jsoneditor-modal-transform",focus:!1}).afterCreate(function(t){var e=t.modalElem(),n=e.querySelector("#wizard"),o=e.querySelector("#ok"),r=e.querySelector("#filterField"),s=e.querySelector("#filterRelation"),a=e.querySelector("#filterValue"),l=e.querySelector("#sortField"),d=e.querySelector("#sortOrder"),c=e.querySelector("#selectFields"),h=e.querySelector("#query"),u=e.querySelector("#preview");Array.isArray(T)||(n.style.fontStyle="italic",n.textContent="(wizard not available for objects, only for arrays)"),(0,k.getChildPaths)(x).forEach(function(e){var t=g(e),e=document.createElement("option");e.text=t,e.value=t,r.appendChild(e);e=document.createElement("option");e.text=t,e.value=t,l.appendChild(e)});var i=(0,k.getChildPaths)(x,!0).filter(function(e){return""!==e});0<i.length?i.forEach(function(e){var t=g(e),e=document.createElement("option");e.text=t,e.value=t,c.appendChild(e)}):(m=e.querySelector("#selectFieldsPart"))&&(m.style.display="none");var p=new(w())(r,{defaultSelected:!1,clearable:!0,allowDeselect:!0,placeholder:"field..."}),f=new(w())(s,{defaultSelected:!1,clearable:!0,allowDeselect:!0,placeholder:"compare..."}),n=new(w())(l,{defaultSelected:!1,clearable:!0,allowDeselect:!0,placeholder:"field..."}),i=new(w())(d,{defaultSelected:!1,clearable:!0,allowDeselect:!0,placeholder:"order..."}),m=new(w())(c,{multiple:!0,clearable:!0,defaultSelected:!1,placeholder:"select fields..."});function g(e){return""===e?"@":"."===e[0]?e.slice(1):e}p.on("selectr.change",b),f.on("selectr.change",b),a.oninput=b,n.on("selectr.change",b),i.on("selectr.change",b),m.on("selectr.change",b),e.querySelector(".pico-modal-contents").onclick=function(e){"A"!==e.target.nodeName&&e.preventDefault()};var v=(0,k.debounce)(function(){try{var e=E(T,h.value);u.className="jsoneditor-transform-preview",u.value=(t=e,n=2,e=I.WF,"number"==typeof n?10<n?i=N(" ",10):1<=n&&(i=N(" ",n)):"string"==typeof n&&""!==n&&(i=n),(t=S(t,i,"",e)).length>e?(i=t,("number"==typeof(e=e)?i.slice(0,e):i)+"..."):t),o.disabled=!1}catch(e){u.className="jsoneditor-transform-preview jsoneditor-error",u.value=e.toString(),o.disabled=!0}var t,n,i},300);function y(e,t){try{h.value=C(e,t),o.disabled=!1,v()}catch(e){var n='Error: an error happened when executing "createQuery": '+(e.message||e.toString());h.value="",o.disabled=!0,u.className="jsoneditor-transform-preview jsoneditor-error",u.value=n}}function b(){var e={};if(r.value&&s.value&&a.value&&(e.filter={field:r.value,relation:s.value,value:a.value}),l.value&&d.value&&(e.sort={field:l.value,direction:d.value}),c.value){for(var t,n=[],i=0;i<c.options.length;i++)c.options[i].selected&&(t=c.options[i].value,n.push(t));e.projection={fields:n}}y(x,e)}h.oninput=v,o.onclick=function(e){e.preventDefault(),e.stopPropagation(),t.close(),_(h.value)},y(x,{}),setTimeout(function(){h.select(),h.focus(),h.selectionStart=3,h.selectionEnd=3})}).afterClose(function(e){e.destroy()}).show()}},956:function(e,t,n){"use strict";n.r(t),n.d(t,{textModeMixins:function(){return l}});var t=n(664),i=n.n(t),t=n(170),h=n.n(t),s=n(188),u=n(436),p=n(474),f=n(907),m=n(56),g=n(617),o=n(210),a=n(558),v=n(49),y=n(791);function b(e){return(b="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)}var n={},x="ace/theme/jsoneditor";function r(){try{this.format()}catch(e){}}n.create=function(e){var t=this,n=1<arguments.length&&void 0!==arguments[1]?arguments[1]:{};void 0===n.statusBar&&(n.statusBar=!0),n.mainMenuBar=!1!==n.mainMenuBar,n.enableSort=!1!==n.enableSort,n.enableTransform=!1!==n.enableTransform,n.createQuery=n.createQuery||m.r,n.executeQuery=n.executeQuery||m.J,"number"==typeof(this.options=n).indentation?this.indentation=Number(n.indentation):this.indentation=2,(0,f.cC)(this.options.languages),(0,f.m0)(this.options.language);var i=n.ace||h();this.mode="code"===n.mode?"code":"text","code"===this.mode&&void 0===i&&(this.mode="text",console.warn("Failed to load Ace editor, falling back to plain text mode. Please use a JSONEditor bundle including Ace, or pass Ace as via the configuration option `ace`.")),this.theme=n.theme||x,this.theme===x&&i&&(0,v.O)(),n.onTextSelectionChange&&this.onTextSelectionChange(n.onTextSelectionChange);var o=this;this.container=e,this.dom={},this.aceEditor=void 0,this.textarea=void 0,this.validateSchema=null,this.annotations=[],this.lastSchemaErrors=void 0,this._debouncedValidate=(0,y.debounce)(this.validate.bind(this),this.DEBOUNCE_INTERVAL),this.width=e.clientWidth,this.height=e.clientHeight,this.frame=document.createElement("div"),this.frame.className="jsoneditor jsoneditor-mode-"+this.options.mode,this.frame.onclick=function(e){e.preventDefault()},this.frame.onkeydown=function(e){o._onKeyDown(e)};var r,s,e={target:this.frame,onFocus:this.options.onFocus||null,onBlur:this.options.onBlur||null};this.frameFocusTracker=new p.R(e),this.content=document.createElement("div"),this.content.className="jsoneditor-outer",this.options.mainMenuBar&&((0,y.addClassName)(this.content,"has-main-menu-bar"),this.menu=document.createElement("div"),this.menu.className="jsoneditor-menu",this.frame.appendChild(this.menu),(e=document.createElement("button")).type="button",e.className="jsoneditor-format",e.title=(0,f.Iu)("formatTitle"),this.menu.appendChild(e),e.onclick=function(){try{o.format(),o._onChange()}catch(e){o._onError(e)}},(e=document.createElement("button")).type="button",e.className="jsoneditor-compact",e.title=(0,f.Iu)("compactTitle"),this.menu.appendChild(e),e.onclick=function(){try{o.compact(),o._onChange()}catch(e){o._onError(e)}},this.options.enableSort&&((e=document.createElement("button")).type="button",e.className="jsoneditor-sort",e.title=(0,f.Iu)("sortTitleShort"),e.onclick=function(){o._showSortModal()},this.menu.appendChild(e)),this.options.enableTransform&&((r=document.createElement("button")).type="button",r.title=(0,f.Iu)("transformTitleShort"),r.className="jsoneditor-transform",r.onclick=function(){o._showTransformModal()},this.menu.appendChild(r)),(r=document.createElement("button")).type="button",r.className="jsoneditor-repair",r.title=(0,f.Iu)("repairTitle"),this.menu.appendChild(r),r.onclick=function(){try{o.repair(),o._onChange()}catch(e){o._onError(e)}},"code"===this.mode&&((c=document.createElement("button")).type="button",c.className="jsoneditor-undo jsoneditor-separator",c.title=(0,f.Iu)("undo"),c.onclick=function(){t.aceEditor.getSession().getUndoManager().undo()},this.menu.appendChild(c),this.dom.undo=c,(c=document.createElement("button")).type="button",c.className="jsoneditor-redo",c.title=(0,f.Iu)("redo"),c.onclick=function(){t.aceEditor.getSession().getUndoManager().redo()},this.menu.appendChild(c),this.dom.redo=c),this.options&&this.options.modes&&this.options.modes.length&&(this.modeSwitcher=new g.x(this.menu,this.options.modes,this.options.mode,function(e){o.setMode(e),o.modeSwitcher.focus()})),"code"===this.mode&&((s=document.createElement("a")).appendChild(document.createTextNode("powered by ace")),s.href="https://ace.c9.io/",s.target="_blank",s.className="jsoneditor-poweredBy",s.onclick=function(){window.open(s.href,s.target,"noopener")},this.menu.appendChild(s)));var a,l,d,c=this.options.onEditable&&b("function"===this.options.onEditable)&&!this.options.onEditable({});this.frame.appendChild(this.content),this.container.appendChild(this.frame),"code"===this.mode?(this.editorDom=document.createElement("div"),this.editorDom.style.height="100%",this.editorDom.style.width="100%",this.content.appendChild(this.editorDom),i=(l=i.edit(this.editorDom)).getSession(),l.$blockScrolling=1/0,l.setTheme(this.theme),l.setOptions({readOnly:c}),l.setShowPrintMargin(!1),l.setFontSize("13px"),i.setMode("ace/mode/json"),i.setTabSize(this.indentation),i.setUseSoftTabs(!0),i.setUseWrapMode(!0),a=i.setAnnotations,i.setAnnotations=function(e){a.call(this,e&&e.length?e:o.annotations)},l.commands.bindKey("Ctrl-L",null),l.commands.bindKey("Command-L",null),l.commands.bindKey("Ctrl-\\",null),l.commands.bindKey("Command-\\",null),l.commands.bindKey("Ctrl-Shift-\\",null),l.commands.bindKey("Command-Shift-\\",null),(this.aceEditor=l).on("change",this._onChange.bind(this)),l.on("changeSelection",this._onSelect.bind(this))):((d=document.createElement("textarea")).className="jsoneditor-text",d.spellcheck=!1,this.content.appendChild(d),this.textarea=d,this.textarea.readOnly=c,null===this.textarea.oninput?this.textarea.oninput=this._onChange.bind(this):this.textarea.onchange=this._onChange.bind(this),d.onselect=this._onSelect.bind(this),d.onmousedown=this._onMouseDown.bind(this),d.onblur=this._onBlur.bind(this)),this._updateHistoryButtons(),this.errorTable=new u.Q({errorTableVisible:"text"===this.mode,onToggleVisibility:function(){o.validate()},onFocusLine:function(e){o.isFocused=!0,isNaN(e)||o.setTextSelection({row:e,column:1},{row:e,column:1e3})},onChangeHeight:function(e){e=e+(o.dom.statusBar?o.dom.statusBar.clientHeight:0)+1;o.content.style.marginBottom=-e+"px",o.content.style.paddingBottom=e+"px"}}),this.frame.appendChild(this.errorTable.getErrorTable()),n.statusBar&&((0,y.addClassName)(this.content,"has-status-bar"),this.curserInfoElements={},l=document.createElement("div"),(this.dom.statusBar=l).className="jsoneditor-statusbar",this.frame.appendChild(l),(c=document.createElement("span")).className="jsoneditor-curserinfo-label",c.innerText="Ln:",(d=document.createElement("span")).className="jsoneditor-curserinfo-val",d.innerText="1",l.appendChild(c),l.appendChild(d),(n=document.createElement("span")).className="jsoneditor-curserinfo-label",n.innerText="Col:",(c=document.createElement("span")).className="jsoneditor-curserinfo-val",c.innerText="1",l.appendChild(n),l.appendChild(c),this.curserInfoElements.colVal=c,this.curserInfoElements.lnVal=d,(c=document.createElement("span")).className="jsoneditor-curserinfo-label",c.innerText="characters selected",c.style.display="none",(d=document.createElement("span")).className="jsoneditor-curserinfo-count",d.innerText="0",d.style.display="none",this.curserInfoElements.countLabel=c,this.curserInfoElements.countVal=d,l.appendChild(d),l.appendChild(c),l.appendChild(this.errorTable.getErrorCounter()),l.appendChild(this.errorTable.getWarningIcon()),l.appendChild(this.errorTable.getErrorIcon())),this.setSchema(this.options.schema,this.options.schemaRefs)},n._onChange=function(){var e=this;if(!this.onChangeDisabled){if(setTimeout(function(){return e._updateHistoryButtons()}),this._debouncedValidate(),this.options.onChange)try{this.options.onChange()}catch(e){console.error("Error in onChange callback: ",e)}if(this.options.onChangeText)try{this.options.onChangeText(this.getText())}catch(e){console.error("Error in onChangeText callback: ",e)}}},n._updateHistoryButtons=function(){var e;this.aceEditor&&this.dom.undo&&this.dom.redo&&((e=this.aceEditor.getSession().getUndoManager())&&e.hasUndo&&e.hasRedo&&(this.dom.undo.disabled=!e.hasUndo(),this.dom.redo.disabled=!e.hasRedo()))},n._showSortModal=function(){var n=this,e=this.options.modalAnchor||s.qD,i=this.get();(0,o.showSortModal)(e,i,function(e){var t;Array.isArray(i)&&(t=(0,y.sort)(i,e.path,e.direction),n.sortedBy=e,n.update(t)),(0,y.isObject)(i)&&(t=(0,y.sortObjectKeys)(i,e.direction),n.sortedBy=e,n.update(t))},n.sortedBy)},n._showTransformModal=function(){var t=this,e=this.options,n=e.modalAnchor,i=e.createQuery,o=e.executeQuery,e=e.queryDescription,r=this.get();(0,a.showTransformModal)({container:n||s.qD,json:r,queryDescription:e,createQuery:i,executeQuery:o,onTransform:function(e){e=o(r,e);t.update(e)}})},n._onSelect=function(){this._updateCursorInfo(),this._emitSelectionChange()},n._onKeyDown=function(e){var t=!1;220===(e.which||e.keyCode)&&e.ctrlKey&&(e.shiftKey?this.compact():this.format(),this._onChange(),t=!0),t&&(e.preventDefault(),e.stopPropagation()),this._updateCursorInfo(),this._emitSelectionChange()},n._onMouseDown=function(){this._updateCursorInfo(),this._emitSelectionChange()},n._onBlur=function(){var e=this;setTimeout(function(){e.isFocused||(e._updateCursorInfo(),e._emitSelectionChange()),e.isFocused=!1})},n._updateCursorInfo=function(){var e,t,n,i,o,r=this;function s(){r.curserInfoElements.countVal.innerText!==o&&(r.curserInfoElements.countVal.innerText=o,r.curserInfoElements.countVal.style.display=o?"inline":"none",r.curserInfoElements.countLabel.style.display=o?"inline":"none"),r.curserInfoElements.lnVal.innerText=n,r.curserInfoElements.colVal.innerText=i}this.textarea?setTimeout(function(){var e=(0,y.getInputSelection)(r.textarea);e.startIndex!==e.endIndex&&(o=e.endIndex-e.startIndex),i=o&&r.cursorInfo&&r.cursorInfo.line===e.end.row&&r.cursorInfo.column===e.end.column?(n=e.start.row,e.start.column):(n=e.end.row,e.end.column),r.cursorInfo={line:n,column:i,count:o},r.options.statusBar&&s()},0):this.aceEditor&&this.curserInfoElements&&(e=this.aceEditor.getCursorPosition(),t=this.aceEditor.getSelectedText(),n=e.row+1,i=e.column+1,o=t.length,r.cursorInfo={line:n,column:i,count:o},this.options.statusBar&&s())},n._emitSelectionChange=function(){var e;this._selectionChangedHandler&&(e=this.getTextSelection(),this._selectionChangedHandler(e.start,e.end,e.text))},n._refreshAnnotations=function(){var e,t=this.aceEditor&&this.aceEditor.getSession();t&&(e=t.getAnnotations().filter(function(e){return"error"===e.type}),t.setAnnotations(e))},n.destroy=function(){this.aceEditor&&(this.aceEditor.destroy(),this.aceEditor=null),this.frame&&this.container&&this.frame.parentNode===this.container&&this.container.removeChild(this.frame),this.modeSwitcher&&(this.modeSwitcher.destroy(),this.modeSwitcher=null),this.textarea=null,this._debouncedValidate=null,this.frameFocusTracker.destroy()},n.compact=function(){var e=this.get(),e=JSON.stringify(e);this.updateText(e)},n.format=function(){var e=this.get(),e=JSON.stringify(e,null,this.indentation);this.updateText(e)},n.repair=function(){var e=this.getText();try{var t=i()(e);this.updateText(t)}catch(e){}},n.focus=function(){this.textarea&&this.textarea.focus(),this.aceEditor&&this.aceEditor.focus()},n.resize=function(){this.aceEditor&&this.aceEditor.resize(!1)},n.set=function(e){this.setText(JSON.stringify(e,null,this.indentation))},n.update=function(e){this.updateText(JSON.stringify(e,null,this.indentation))},n.get=function(){var e=this.getText();return(0,y.parse)(e)},n.getText=function(){return this.textarea?this.textarea.value:this.aceEditor?this.aceEditor.getValue():""},n._setText=function(e,t){var n,i=this,e=!0===this.options.escapeUnicode?(0,y.escapeUnicodeChars)(e):e;this.textarea&&(this.textarea.value=e),this.aceEditor&&(this.onChangeDisabled=!0,this.aceEditor.setValue(e,-1),this.onChangeDisabled=!1,t&&(n=this,setTimeout(function(){n.aceEditor&&n.aceEditor.session.getUndoManager().reset()})),setTimeout(function(){return i._updateHistoryButtons()})),this._debouncedValidate()},n.setText=function(e){this._setText(e,!0)},n.updateText=function(e){this.getText()!==e&&this._setText(e,!1)},n.validate=function(){var t,n,i=this,o=[],r=[];try{var e=this.get();this.validateSchema&&(this.validateSchema(e)||(o=this.validateSchema.errors.map(function(e){return e.type="validation",(0,y.improveSchemaError)(e)}))),this.validationSequence=(this.validationSequence||0)+1;var s=this,a=this.validationSequence;(function(e,t){if(!t)return Promise.resolve([]);try{var n=t(e);return((0,y.isPromise)(n)?n:Promise.resolve(n)).then(function(e){return Array.isArray(e)?e.filter(function(e){var t=(0,y.isValidValidationError)(e);return t||console.warn('Ignoring a custom validation error with invalid structure. Expected structure: {path: [...], message: "..."}. Actual error:',e),t}).map(function(e){return{dataPath:(0,y.stringifyPath)(e.path),message:e.message,type:"customValidation"}}):[]})}catch(e){return Promise.reject(e)}})(e,this.options.onValidate).then(function(e){a===s.validationSequence&&(e=o.concat(r).concat(e),s._renderErrors(e),"function"==typeof i.options.onValidationError&&((0,y.isValidationErrorChanged)(e,i.lastSchemaErrors)&&i.options.onValidationError.call(i,e),i.lastSchemaErrors=e))}).catch(function(e){console.error("Custom validation function did throw an error",e)})}catch(e){this.getText()&&((t=/\w*line\s*(\d+)\w*/g.exec(e.message))&&(n=+t[1]),r=[{type:"error",message:e.message.replace(/\n/g,"<br>"),line:n}]),this._renderErrors(r),"function"==typeof this.options.onValidationError&&((0,y.isValidationErrorChanged)(r,this.lastSchemaErrors)&&this.options.onValidationError.call(this,r),this.lastSchemaErrors=r)}},n._renderErrors=function(i){var e=this.getText(),t=[];i.reduce(function(e,t){return"string"==typeof t.dataPath&&-1===e.indexOf(t.dataPath)&&e.push(t.dataPath),e},t);t=(0,y.getPositionForPath)(e,t);this.aceEditor&&(this.annotations=t.map(function(t){var e=i.filter(function(e){return e.dataPath===t.path}),n=e.map(function(e){return e.message}).join("\n");return n?{row:t.line,column:t.column,text:"Schema validation error"+(1!==e.length?"s":"")+": \n"+n,type:"warning",source:"jsoneditor"}:{}}),this._refreshAnnotations()),this.errorTable.setErrors(i,t),this.aceEditor&&this.aceEditor.resize(!1)},n.getTextSelection=function(){var e={};if(this.textarea){var t=(0,y.getInputSelection)(this.textarea);return this.cursorInfo&&this.cursorInfo.line===t.end.row&&this.cursorInfo.column===t.end.column?(e.start=t.end,e.end=t.start):e=t,{start:e.start,end:e.end,text:this.textarea.value.substring(t.startIndex,t.endIndex)}}if(this.aceEditor){var n=this.aceEditor.getSelection(),i=this.aceEditor.getSelectedText(),t=n.getRange(),n=n.getSelectionLead();return n.row===t.end.row&&n.column===t.end.column?e=t:(e.start=t.end,e.end=t.start),{start:{row:e.start.row+1,column:e.start.column+1},end:{row:e.end.row+1,column:e.end.column+1},text:i}}},n.onTextSelectionChange=function(e){"function"==typeof e&&(this._selectionChangedHandler=(0,y.debounce)(e,this.DEBOUNCE_INTERVAL))},n.setTextSelection=function(e,t){var n,i,o;e&&t&&(this.textarea?(n=(0,y.getIndexForPosition)(this.textarea,e.row,e.column),i=(0,y.getIndexForPosition)(this.textarea,t.row,t.column),-1<n&&-1<i&&(this.textarea.setSelectionRange?(this.textarea.focus(),this.textarea.setSelectionRange(n,i)):this.textarea.createTextRange&&((o=this.textarea.createTextRange()).collapse(!0),o.moveEnd("character",i),o.moveStart("character",n),o.select()),o=(this.textarea.value.match(/\n/g)||[]).length+1,o=this.textarea.scrollHeight/o,o=e.row*o,this.textarea.scrollTop=o>this.textarea.clientHeight?o-this.textarea.clientHeight/2:0)):this.aceEditor&&(t={start:{row:e.row-1,column:e.column-1},end:{row:t.row-1,column:t.column-1}},this.aceEditor.selection.setRange(t),this.aceEditor.scrollToLine(e.row-1,!0)))};var l=[{mode:"text",mixin:n,data:"text",load:r},{mode:"code",mixin:n,data:"text",load:r}]},38:function(e,t,n){"use strict";n.r(t),n.d(t,{treeModeMixins:function(){return V}});var _={start:function(e,t,n){return 0===t.indexOf(e)},contain:function(e,t,n){return-1<t.indexOf(e)}};var s=n(897),a=n(474);function o(e,t){for(var n=0;n<t.length;n++){var i=t[n];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,i.key,i)}}var i=function(){function t(){!function(e){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this),this.locked=!1}var e,n,i;return e=t,(n=[{key:"highlight",value:function(e){this.locked||(this.node!==e&&(this.node&&this.node.setHighlight(!1),this.node=e,this.node.setHighlight(!0)),this._cancelUnhighlight())}},{key:"unhighlight",value:function(){var e;this.locked||(e=this).node&&(this._cancelUnhighlight(),this.unhighlightTimer=setTimeout(function(){e.node.setHighlight(!1),e.node=void 0,e.unhighlightTimer=void 0},0))}},{key:"_cancelUnhighlight",value:function(){this.unhighlightTimer&&(clearTimeout(this.unhighlightTimer),this.unhighlightTimer=void 0)}},{key:"lock",value:function(){this.locked=!0}},{key:"unlock",value:function(){this.locked=!1}}])&&o(e.prototype,n),i&&o(e,i),t}(),l=n(907),r=n(56),d=n(617),t=n(233),c=n.n(t),h=n(602),I=n(791);var u=n(210),p=n(558),f=n(188);function m(e,t){var n;if("undefined"==typeof Symbol||null==e[Symbol.iterator]){if(Array.isArray(e)||(n=function(e,t){if(!e)return;if("string"==typeof e)return g(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);"Object"===n&&e.constructor&&(n=e.constructor.name);if("Map"===n||"Set"===n)return Array.from(e);if("Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return g(e,t)}(e))||t&&e&&"number"==typeof e.length){n&&(e=n);var i=0,t=function(){};return{s:t,n:function(){return i>=e.length?{done:!0}:{done:!1,value:e[i++]}},e:function(e){throw e},f:t}}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 o,r=!0,s=!1;return{s:function(){n=e[Symbol.iterator]()},n:function(){var e=n.next();return r=e.done,e},e:function(e){s=!0,o=e},f:function(){try{r||null==n.return||n.return()}finally{if(s)throw o}}}}function g(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,i=new Array(t);n<t;n++)i[n]=e[n];return i}function v(e){return(v="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 y(e,t){for(var n=0;n<t.length;n++){var i=t[n];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,i.key,i)}}var E=function(){function k(e,t){!function(e){if(!(e instanceof k))throw new TypeError("Cannot call a class as a function")}(this),this.editor=e,this.dom={},this.expanded=!1,t&&t instanceof Object?(this.setField(t.field,t.fieldEditable),"value"in t&&this.setValue(t.value,t.type),"internalValue"in t&&this.setInternalValue(t.internalValue)):(this.setField(""),this.setValue(null)),this._debouncedOnChangeValue=(0,I.debounce)(this._onChangeValue.bind(this),k.prototype.DEBOUNCE_INTERVAL),this._debouncedOnChangeField=(0,I.debounce)(this._onChangeField.bind(this),k.prototype.DEBOUNCE_INTERVAL),this.visibleChilds=this.getMaxVisibleChilds()}var e,t,n;return e=k,(t=[{key:"getMaxVisibleChilds",value:function(){return this.editor&&this.editor.options&&this.editor.options.maxVisibleChilds?this.editor.options.maxVisibleChilds:b}},{key:"_updateEditability",value:function(){var e;this.editable={field:!0,value:!0},this.editor&&(this.editable.field="tree"===this.editor.options.mode,this.editable.value="view"!==this.editor.options.mode,"tree"!==this.editor.options.mode&&"form"!==this.editor.options.mode||"function"!=typeof this.editor.options.onEditable||("boolean"==typeof(e=this.editor.options.onEditable({field:this.field,value:this.value,path:this.getPath()}))?(this.editable.field=e,this.editable.value=e):"object"===v(e)&&null!==e?("boolean"==typeof e.field&&(this.editable.field=e.field),"boolean"==typeof e.value&&(this.editable.value=e.value)):(console.error("Invalid return value for function onEditable.","Actual value:",e,".","Either a boolean or object { field: boolean, value: boolean } expected."),this.editable.field=!1,this.editable.value=!1)))}},{key:"getPath",value:function(){for(var e=this,t=[];e;){var n=e.getName();void 0!==n&&t.unshift(n),e=e.parent}return t}},{key:"getInternalPath",value:function(){for(var e=this,t=[];e;)e.parent&&t.unshift(e.getIndex()),e=e.parent;return t}},{key:"getName",value:function(){return this.parent?"array"!==this.parent.type?this.field:this.index:void 0}},{key:"findNodeByPath",value:function(e){if(e){if(0===e.length)return this;if(e.length&&this.childs&&this.childs.length)for(var t=0;t<this.childs.length;++t)if(""+e[0]==""+this.childs[t].getName())return this.childs[t].findNodeByPath(e.slice(1))}}},{key:"findNodeByInternalPath",value:function(e){if(e){for(var t=this,n=0;n<e.length&&t;n++)var i=e[n],t=t.childs[i];return t}}},{key:"serialize",value:function(){return{value:this.getValue(),path:this.getPath()}}},{key:"findNode",value:function(e){for(var n=(0,I.parsePath)(e),i=this;i&&0<n.length;)!function(){var t=n.shift();if("number"==typeof t){if("array"!==i.type)throw new Error("Cannot get child node at index "+t+": node is no array");i=i.childs[t]}else{if("object"!==i.type)throw new Error("Cannot get child node "+t+": node is no object");i=i.childs.filter(function(e){return e.field===t})[0]}}();return i}},{key:"findParents",value:function(){for(var e=[],t=this.parent;t;)e.unshift(t),t=t.parent;return e}},{key:"setError",value:function(e,t){this.error=e, this.errorChild=t,this.dom&&this.dom.tr&&this.updateError()}},{key:"updateError",value:function(){var n=this,i=this.fieldError||this.valueError||this.error,e=this.dom.tdError;if(i&&this.dom&&this.dom.tr){(0,I.addClassName)(this.dom.tr,"jsoneditor-validation-error"),e||(e=document.createElement("td"),this.dom.tdError=e,this.dom.tdValue.parentNode.appendChild(e));var o=document.createElement("button");o.type="button",o.className="jsoneditor-button jsoneditor-schema-error";var t=function(){n.dom.popupAnchor&&n.dom.popupAnchor.destroy()},r=function(){delete n.dom.popupAnchor},s=function(e){var t=n.editor.frame;n.dom.popupAnchor=(0,h.w)(o,n.editor.getPopupAnchor(),r,e);e=o.getBoundingClientRect(),t=120<t.getBoundingClientRect().width-e.x?"jsoneditor-above":"jsoneditor-left",e=document.createElement("div");e.className="jsoneditor-popover "+t,e.appendChild(document.createTextNode(i.message)),n.dom.popupAnchor.appendChild(e)};o.onmouseover=function(){n.dom.popupAnchor||s(!0)},o.onfocus=function(){t(),s(!1)},o.onblur=function(){t()};var a=this.errorChild;for(a&&(o.onclick=function(){a.findParents().forEach(function(e){e.expand(!1)}),a.scrollTo(function(){a.focus()})});e.firstChild;)e.removeChild(e.firstChild);e.appendChild(o)}else this.dom.tr&&(0,I.removeClassName)(this.dom.tr,"jsoneditor-validation-error"),e&&(this.dom.tdError.parentNode.removeChild(this.dom.tdError),delete this.dom.tdError)}},{key:"getIndex",value:function(){if(this.parent){var e=this.parent.childs.indexOf(this);return-1!==e?e:null}return-1}},{key:"setParent",value:function(e){this.parent=e}},{key:"setField",value:function(e,t){this.field=e,this.previousField=e,this.fieldEditable=!0===t}},{key:"getField",value:function(){return void 0===this.field&&this._getDomField(),this.field}},{key:"setValue",value:function(e,t){var n,i,o,r,s,a,l,d=this.childs;if(this.type=this._getType(e),t&&t!==this.type){if("string"!==t||"auto"!==this.type)throw new Error('Type mismatch: cannot cast value of type "'+this.type+' to the specified type "'+t+'"');this.type=t}if("array"===this.type){for(this.childs||(this.childs=[]),i=0;i<e.length;i++)void 0===(s=e[i])||s instanceof Function||(i<this.childs.length?((n=this.childs[i]).fieldEditable=!1,n.index=i,n.setValue(s)):(n=new k(this.editor,{value:s}),r=i<this.getMaxVisibleChilds(),this.appendChild(n,r,!1)));for(o=this.childs.length;o>=e.length;o--)this.removeChild(this.childs[o],!1)}else if("object"===this.type){for(this.childs||(this.childs=[]),o=this.childs.length-1;0<=o;o--)C(e,this.childs[o].field)||this.removeChild(this.childs[o],!1);for(var c in i=0,e)C(e,c)&&(void 0===(s=e[c])||s instanceof Function||((l=this.findChildByProperty(c))?(l.setField(c,!0),l.setValue(s)):(a=new k(this.editor,{field:c,value:s}),l=i<this.getMaxVisibleChilds(),this.appendChild(a,l,!1))),i++);!(this.value="")===this.editor.options.sortObjectKeys&&this.sort([],"asc",!1)}else this.hideChilds(),delete this.append,delete this.showMore,delete this.expanded,delete this.childs,this.value=e;Array.isArray(d)!==Array.isArray(this.childs)&&this.recreateDom(),this.updateDom({updateIndexes:!0}),this.previousValue=this.value}},{key:"setInternalValue",value:function(e){var t,n,i,o,r,s=this.childs;if(this.type=e.type,"array"===e.type){for(this.childs||(this.childs=[]),o=0;o<e.childs.length;o++)void 0===(t=e.childs[o])||t instanceof Function||(o<this.childs.length?((n=this.childs[o]).fieldEditable=!1,n.index=o,n.setInternalValue(t)):(n=new k(this.editor,{internalValue:t}),i=o<this.getMaxVisibleChilds(),this.appendChild(n,i,!1)));for(r=this.childs.length;r>=e.childs.length;r--)this.removeChild(this.childs[r],!1)}else if("object"===e.type){for(this.childs||(this.childs=[]),o=0;o<e.childs.length;o++)void 0===(t=e.childs[o])||t instanceof Function||(o<this.childs.length?(delete(n=this.childs[o]).index,n.setField(t.field,!0),n.setInternalValue(t.value)):(n=new k(this.editor,{field:t.field,internalValue:t.value}),i=o<this.getMaxVisibleChilds(),this.appendChild(n,i,!1)));for(r=this.childs.length;r>=e.childs.length;r--)this.removeChild(this.childs[r],!1)}else this.hideChilds(),delete this.append,delete this.showMore,delete this.expanded,delete this.childs,this.value=e.value;Array.isArray(s)!==Array.isArray(this.childs)&&this.recreateDom(),this.updateDom({updateIndexes:!0}),this.previousValue=this.value}},{key:"recreateDom",value:function(){var e;this.dom&&this.dom.tr&&this.dom.tr.parentNode?(e=this._detachFromDom(),this.clearDom(),this._attachToDom(e)):this.clearDom()}},{key:"getValue",value:function(){if("array"===this.type){var t=[];return this.childs.forEach(function(e){t.push(e.getValue())}),t}if("object"!==this.type)return void 0===this.value&&this._getDomValue(),this.value;var n={};return this.childs.forEach(function(e){n[e.getField()]=e.getValue()}),n}},{key:"getInternalValue",value:function(){return"array"===this.type?{type:this.type,childs:this.childs.map(function(e){return e.getInternalValue()})}:"object"===this.type?{type:this.type,childs:this.childs.map(function(e){return{field:e.getField(),value:e.getInternalValue()}})}:(void 0===this.value&&this._getDomValue(),{type:this.type,value:this.value})}},{key:"getLevel",value:function(){return this.parent?this.parent.getLevel()+1:0}},{key:"getNodePath",value:function(){var e=this.parent?this.parent.getNodePath():[];return e.push(this),e}},{key:"clone",value:function(){var t,n=new k(this.editor);return n.type=this.type,n.field=this.field,n.fieldInnerText=this.fieldInnerText,n.fieldEditable=this.fieldEditable,n.previousField=this.previousField,n.value=this.value,n.valueInnerText=this.valueInnerText,n.previousValue=this.previousValue,n.expanded=this.expanded,n.visibleChilds=this.visibleChilds,this.childs?(t=[],this.childs.forEach(function(e){e=e.clone();e.setParent(n),t.push(e)}),n.childs=t):n.childs=void 0,n}},{key:"expand",value:function(t){this.childs&&(this.expanded=!0,this.dom.expand&&(this.dom.expand.className="jsoneditor-button jsoneditor-expanded"),this.showChilds(),!1!==t&&this.childs.forEach(function(e){e.expand(t)}),this.updateDom({recurse:!1}))}},{key:"collapse",value:function(t){this.childs&&(this.hideChilds(),!1!==t&&this.childs.forEach(function(e){e.collapse(t)}),this.dom.expand&&(this.dom.expand.className="jsoneditor-button jsoneditor-collapsed"),this.expanded=!1,this.updateDom({recurse:!1}))}},{key:"showChilds",value:function(){var e=this.childs;if(e&&this.expanded){var t=this.dom.tr,n=t?t.parentNode:void 0;if(n){e=this.getAppendDom();e.parentNode||((o=t.nextSibling)?n.insertBefore(e,o):n.appendChild(e));for(var i=Math.min(this.childs.length,this.visibleChilds),o=this._getNextTr(),r=0;r<i;r++){var s=this.childs[r];s.getDom().parentNode||n.insertBefore(s.getDom(),o),s.showChilds()}e=this.getShowMoreDom();o=this._getNextTr(),e.parentNode||n.insertBefore(e,o),this.showMore.updateDom()}}}},{key:"_getNextTr",value:function(){return this.showMore&&this.showMore.getDom().parentNode?this.showMore.getDom():this.append&&this.append.getDom().parentNode?this.append.getDom():void 0}},{key:"hide",value:function(e){var t=this.dom.tr,n=t?t.parentNode:void 0;n&&n.removeChild(t),this.dom.popupAnchor&&this.dom.popupAnchor.destroy(),this.hideChilds(e)}},{key:"hideChilds",value:function(e){var t;this.childs&&this.expanded&&((t=this.getAppendDom()).parentNode&&t.parentNode.removeChild(t),this.childs.forEach(function(e){e.hide()}),(t=this.getShowMoreDom()).parentNode&&t.parentNode.removeChild(t),e&&!e.resetVisibleChilds||(this.visibleChilds=this.getMaxVisibleChilds()))}},{key:"_updateCssClassName",value:function(){var e;this.dom.field&&this.editor&&this.editor.options&&"function"==typeof this.editor.options.onClassName&&this.dom.tree&&((0,I.removeAllClassNames)(this.dom.tree),e=this.editor.options.onClassName({path:this.getPath(),field:this.field,value:this.value})||"",(0,I.addClassName)(this.dom.tree,"jsoneditor-values "+e))}},{key:"recursivelyUpdateCssClassesOnNodes",value:function(){if(this._updateCssClassName(),Array.isArray(this.childs))for(var e=0;e<this.childs.length;e++)this.childs[e].recursivelyUpdateCssClassesOnNodes()}},{key:"expandTo",value:function(){for(var e=this.parent;e;)e.expanded||e.expand(),e=e.parent}},{key:"appendChild",value:function(e,t,n){var i,o;this._hasChilds()&&(e.setParent(this),e.fieldEditable="object"===this.type,"array"===this.type&&(e.index=this.childs.length),"object"===this.type&&void 0===e.field&&e.setField(""),this.childs.push(e),this.expanded&&!1!==t&&(i=e.getDom(),t=(o=this._getNextTr())?o.parentNode:void 0,o&&t&&t.insertBefore(i,o),e.showChilds(),this.visibleChilds++),!1!==n&&(this.updateDom({updateIndexes:!0}),e.updateDom({recurse:!0})))}},{key:"moveBefore",value:function(e,t,n){var i,o,r;this._hasChilds()&&((i=this.dom.tr?this.dom.tr.parentNode:void 0)&&((o=document.createElement("tr")).style.height=i.clientHeight+"px",i.appendChild(o)),e.parent&&e.parent.removeChild(e),t instanceof D||!t?this.childs.length+1>this.visibleChilds?(r=this.childs[this.visibleChilds-1],this.insertBefore(e,r,n)):this.appendChild(e,!0,n):this.insertBefore(e,t,n),i&&o&&i.removeChild(o))}},{key:"insertBefore",value:function(e,t,n){if(this._hasChilds()){if(this.visibleChilds++,"object"===this.type&&void 0===e.field&&e.setField(""),t===this.append)e.setParent(this),e.fieldEditable="object"===this.type,this.childs.push(e);else{var i=this.childs.indexOf(t);if(-1===i)throw new Error("Node not found");e.setParent(this),e.fieldEditable="object"===this.type,this.childs.splice(i,0,e)}var o;this.expanded&&(o=e.getDom(),t=(i=t.getDom())?i.parentNode:void 0,i&&t&&t.insertBefore(o,i),e.showChilds(),this.showChilds()),!1!==n&&(this.updateDom({updateIndexes:!0}),e.updateDom({recurse:!0}))}}},{key:"insertAfter",value:function(e,t){this._hasChilds()&&(t=this.childs.indexOf(t),(t=this.childs[t+1])?this.insertBefore(e,t):this.appendChild(e))}},{key:"search",value:function(t,n){Array.isArray(n)||(n=[]);var e=t?t.toLowerCase():void 0;return delete this.searchField,delete this.searchValue,void 0!==this.field&&n.length<=this.MAX_SEARCH_RESULTS&&(-1!==String(this.field).toLowerCase().indexOf(e)&&(this.searchField=!0,n.push({node:this,elem:"field"})),this._updateDomField()),this._hasChilds()?this.childs&&this.childs.forEach(function(e){e.search(t,n)}):void 0!==this.value&&n.length<=this.MAX_SEARCH_RESULTS&&(-1!==String(this.value).toLowerCase().indexOf(e)&&(this.searchValue=!0,n.push({node:this,elem:"value"})),this._updateDomValue()),n}},{key:"scrollTo",value:function(e){this.expandPathToNode(),this.dom.tr&&this.dom.tr.parentNode&&this.editor.scrollTo(this.dom.tr.offsetTop,e)}},{key:"expandPathToNode",value:function(){for(var e=this;e&&e.parent;){for(var t="array"===e.parent.type?e.index:e.parent.childs.indexOf(e);e.parent.visibleChilds<t+1;)e.parent.visibleChilds+=this.getMaxVisibleChilds();e.parent.expand(!1),e=e.parent}}},{key:"focus",value:function(e){if(k.focusElement=e,this.dom.tr&&this.dom.tr.parentNode){var t=this.dom;switch(e){case"drag":(t.drag||t.menu).focus();break;case"menu":t.menu.focus();break;case"expand":this._hasChilds()?t.expand.focus():t.field&&this.fieldEditable?(t.field.focus(),(0,I.selectContentEditable)(t.field)):t.value&&!this._hasChilds()?(t.value.focus(),(0,I.selectContentEditable)(t.value)):t.menu.focus();break;case"field":t.field&&this.fieldEditable?(t.field.focus(),(0,I.selectContentEditable)(t.field)):t.value&&!this._hasChilds()?(t.value.focus(),(0,I.selectContentEditable)(t.value)):(this._hasChilds()?t.expand:t.menu).focus();break;case"value":default:t.select?t.select.focus():t.value&&!this._hasChilds()?(t.value.focus(),(0,I.selectContentEditable)(t.value)):t.field&&this.fieldEditable?(t.field.focus(),(0,I.selectContentEditable)(t.field)):(this._hasChilds()?t.expand:t.menu).focus()}}}},{key:"containsNode",value:function(e){if(this===e)return!0;var t=this.childs;if(t)for(var n=0,i=t.length;n<i;n++)if(t[n].containsNode(e))return!0;return!1}},{key:"removeChild",value:function(e,t){if(this.childs){var n=this.childs.indexOf(e);if(-1!==n){n<this.visibleChilds&&this.expanded&&this.visibleChilds--,e.hide(),delete e.searchField,delete e.searchValue;n=this.childs.splice(n,1)[0];return n.parent=null,!1!==t&&this.updateDom({updateIndexes:!0}),n}}}},{key:"_remove",value:function(e){this.removeChild(e)}},{key:"changeType",value:function(e){var t,n=this.type;n!==e&&("string"!==e&&"auto"!==e||"string"!==n&&"auto"!==n?(t=this._detachFromDom(),this.clearDom(),"object"===(this.type=e)?(this.childs||(this.childs=[]),this.childs.forEach(function(e){e.clearDom(),delete e.index,e.fieldEditable=!0,void 0===e.field&&(e.field="")}),"string"!==n&&"auto"!==n||(this.expanded=!0)):"array"===e?(this.childs||(this.childs=[]),this.childs.forEach(function(e,t){e.clearDom(),e.fieldEditable=!1,e.index=t}),"string"!==n&&"auto"!==n||(this.expanded=!0)):this.expanded=!1,this._attachToDom(t)):this.type=e,"auto"!==e&&"string"!==e||(this.value="string"===e?String(this.value):(0,I.parseString)(String(this.value)),this.focus()),this.updateDom({updateIndexes:!0}))}},{key:"deepEqual",value:function(e){var t;if("array"===this.type){if(!Array.isArray(e))return!1;if(this.childs.length!==e.length)return!1;for(t=0;t<this.childs.length;t++)if(!this.childs[t].deepEqual(e[t]))return!1}else if("object"===this.type){if("object"!==v(e)||!e)return!1;var n=Object.keys(e);if(this.childs.length!==n.length)return!1;for(t=0;t<n.length;t++){var i=this.childs[t];if(i.field!==n[t]||!i.deepEqual(e[i.field]))return!1}}else if(this.value!==e)return!1;return!0}},{key:"_getDomValue",value:function(){if(this._clearValueError(),this.dom.value&&"array"!==this.type&&"object"!==this.type&&(this.valueInnerText=(0,I.getInnerText)(this.dom.value),""===this.valueInnerText&&""!==this.dom.value.innerHTML&&(this.dom.value.textContent="")),void 0!==this.valueInnerText)try{var e;(e="string"===this.type?this._unescapeHTML(this.valueInnerText):(e=this._unescapeHTML(this.valueInnerText),(0,I.parseString)(e)))!==this.value&&(this.value=e,this._debouncedOnChangeValue())}catch(e){this._setValueError((0,l.Iu)("cannotParseValueError"))}}},{key:"_setValueError",value:function(e){this.valueError={message:e},this.updateError()}},{key:"_clearValueError",value:function(){this.valueError&&(this.valueError=null,this.updateError())}},{key:"_setFieldError",value:function(e){this.fieldError={message:e},this.updateError()}},{key:"_clearFieldError",value:function(){this.fieldError&&(this.fieldError=null,this.updateError())}},{key:"_onChangeValue",value:function(){var e=this.editor.getDomSelection();e.range&&(t=(0,I.textDiff)(String(this.value),String(this.previousValue)),e.range.startOffset=t.start,e.range.endOffset=t.end);var t,n=this.editor.getDomSelection();n.range&&(t=(0,I.textDiff)(String(this.previousValue),String(this.value)),n.range.startOffset=t.start,n.range.endOffset=t.end),this.editor._onAction("editValue",{path:this.getInternalPath(),oldValue:this.previousValue,newValue:this.value,oldSelection:e,newSelection:n}),this.previousValue=this.value}},{key:"_onChangeField",value:function(){var e=this.editor.getDomSelection(),t=this.previousField||"";e.range&&(n=(0,I.textDiff)(this.field,t),e.range.startOffset=n.start,e.range.endOffset=n.end);var n=this.editor.getDomSelection();n.range&&(t=(0,I.textDiff)(t,this.field),n.range.startOffset=t.start,n.range.endOffset=t.end),this.editor._onAction("editField",{parentPath:this.parent.getInternalPath(),index:this.getIndex(),oldValue:this.previousField,newValue:this.field,oldSelection:e,newSelection:n}),this.previousField=this.field}},{key:"_updateDomValue",value:function(){var e=this.dom.value;if(e){var t=["jsoneditor-value"],n=this.value,i="auto"===this.type?(0,I.getType)(n):this.type,o="string"===i&&(0,I.isUrl)(n);if(t.push("jsoneditor-"+i),o&&t.push("jsoneditor-url"),""===String(this.value)&&"array"!==this.type&&"object"!==this.type&&t.push("jsoneditor-empty"),this.searchValueActive&&t.push("jsoneditor-highlight-active"),this.searchValue&&t.push("jsoneditor-highlight"),e.className=t.join(" "),"array"===i||"object"===i?(t=this.childs?this.childs.length:0,e.title=this.type+" containing "+t+" items"):o&&this.editable.value?e.title=(0,l.Iu)("openUrl"):e.title="","boolean"===i&&this.editable.value?(this.dom.checkbox||(this.dom.checkbox=document.createElement("input"),this.dom.checkbox.type="checkbox",this.dom.tdCheckbox=document.createElement("td"),this.dom.tdCheckbox.className="jsoneditor-tree",this.dom.tdCheckbox.appendChild(this.dom.checkbox),this.dom.tdValue.parentNode.insertBefore(this.dom.tdCheckbox,this.dom.tdValue)),this.dom.checkbox.checked=this.value):this.dom.tdCheckbox&&(this.dom.tdCheckbox.parentNode.removeChild(this.dom.tdCheckbox),delete this.dom.tdCheckbox,delete this.dom.checkbox),this.enum&&this.editable.value){if(!this.dom.select){this.dom.select=document.createElement("select"),this.id=this.field+"_"+(new Date).getUTCMilliseconds(),this.dom.select.id=this.id,this.dom.select.name=this.dom.select.id;var r=document.createElement("option");r.value="",r.textContent="--",this.dom.select.appendChild(r);for(var s=0;s<this.enum.length;s++){var a=document.createElement("option");a.value=this.enum[s],a.textContent=this.enum[s],this.dom.select.appendChild(a)}this.dom.tdSelect=document.createElement("td"),this.dom.tdSelect.className="jsoneditor-tree",this.dom.tdSelect.appendChild(this.dom.select),this.dom.tdValue.parentNode.insertBefore(this.dom.tdSelect,this.dom.tdValue)}this.dom.select.value=-1!==this.enum.indexOf(this.value)?this.value:"",!this.schema||C(this.schema,"oneOf")||C(this.schema,"anyOf")||C(this.schema,"allOf")?delete this.valueFieldHTML:(this.valueFieldHTML=this.dom.tdValue.innerHTML,this.dom.tdValue.style.visibility="hidden",this.dom.tdValue.textContent="")}else this.dom.tdSelect&&(this.dom.tdSelect.parentNode.removeChild(this.dom.tdSelect),delete this.dom.tdSelect,delete this.dom.select,this.dom.tdValue.innerHTML=this.valueFieldHTML,this.dom.tdValue.style.visibility="",delete this.valueFieldHTML);if(this.editable.value&&this.editor.options.colorPicker&&"string"==typeof n&&(0,I.isValidColor)(n)?(this.dom.color||(this.dom.color=document.createElement("div"),this.dom.color.className="jsoneditor-color",this.dom.tdColor=document.createElement("td"),this.dom.tdColor.className="jsoneditor-tree",this.dom.tdColor.appendChild(this.dom.color),this.dom.tdValue.parentNode.insertBefore(this.dom.tdColor,this.dom.tdValue)),(0,I.addClassName)(this.dom.value,"jsoneditor-color-value"),this.dom.color.style.backgroundColor=n):this._deleteDomColor(),this._showTimestampTag()){this.dom.date||(this.dom.date=document.createElement("div"),this.dom.date.className="jsoneditor-date",this.dom.value.parentNode.appendChild(this.dom.date));r=null;if("function"==typeof this.editor.options.timestampFormat&&(r=this.editor.options.timestampFormat({field:this.field,value:this.value,path:this.getPath()})),r){for(;this.dom.date.firstChild;)this.dom.date.removeChild(this.dom.date.firstChild);this.dom.date.appendChild(document.createTextNode(r))}else this.dom.date.textContent=new Date(n).toISOString();this.dom.date.title=new Date(n).toString()}else this.dom.date&&(this.dom.date.parentNode.removeChild(this.dom.date),delete this.dom.date);(0,I.stripFormatting)(e),this._updateDomDefault()}}},{key:"_deleteDomColor",value:function(){this.dom.color&&(this.dom.tdColor.parentNode.removeChild(this.dom.tdColor),delete this.dom.tdColor,delete this.dom.color,(0,I.removeClassName)(this.dom.value,"jsoneditor-color-value"))}},{key:"_updateDomField",value:function(){var e,t=this.dom.field;t&&((e=(0,I.makeFieldTooltip)(this.schema,this.editor.options.language))&&(t.title=e),(""===String(this.field)&&this.parent&&"array"!==this.parent.type?(0,I.addClassName):(0,I.removeClassName))(t,"jsoneditor-empty"),(this.searchFieldActive?(0,I.addClassName):(0,I.removeClassName))(t,"jsoneditor-highlight-active"),(this.searchField?(0,I.addClassName):(0,I.removeClassName))(t,"jsoneditor-highlight"),(0,I.stripFormatting)(t))}},{key:"_getDomField",value:function(e){if(this._clearFieldError(),this.dom.field&&this.fieldEditable&&(this.fieldInnerText=(0,I.getInnerText)(this.dom.field),""===this.fieldInnerText&&""!==this.dom.field.innerHTML&&(this.dom.field.textContent="")),void 0!==this.fieldInnerText)try{var t=this._unescapeHTML(this.fieldInnerText),n=this.parent.getFieldNames(this);-1!==n.indexOf(t)?e?(t=(0,I.findUniqueName)(t,n))!==this.field&&(this.field=t,this._debouncedOnChangeField()):this._setFieldError((0,l.Iu)("duplicateFieldError")):t!==this.field&&(this.field=t,this._debouncedOnChangeField())}catch(e){this._setFieldError((0,l.Iu)("cannotParseFieldError"))}}},{key:"_updateDomDefault",value:function(){var e;!this.schema||void 0===this.schema.default||this._hasChilds()||(e=this.dom.select||this.dom.value)&&(this.value===this.schema.default?(e.title=(0,l.Iu)("default"),(0,I.addClassName)(e,"jsoneditor-is-default"),(0,I.removeClassName)(e,"jsoneditor-is-not-default")):(e.removeAttribute("title"),(0,I.removeClassName)(e,"jsoneditor-is-default"),(0,I.addClassName)(e,"jsoneditor-is-not-default")))}},{key:"_showTimestampTag",value:function(){if("number"!=typeof this.value)return!1;var e=this.editor.options.timestampTag;if("function"!=typeof e)return!0===e&&(0,I.isTimestamp)(this.field,this.value);e=e({field:this.field,value:this.value,path:this.getPath()});return"boolean"==typeof e?e:(0,I.isTimestamp)(this.field,this.value)}},{key:"clearDom",value:function(){this.dom={}}},{key:"getDom",value:function(){var e,t=this.dom;if(t.tr)return t.tr;this._updateEditability(),t.tr=document.createElement("tr"),"tree"===(t.tr.node=this).editor.options.mode&&(e=document.createElement("td"),this.editable.field&&this.parent&&((n=document.createElement("button")).type="button",(t.drag=n).className="jsoneditor-button jsoneditor-dragarea",n.title=(0,l.Iu)("drag"),e.appendChild(n)),t.tr.appendChild(e),n=document.createElement("td"),(e=document.createElement("button")).type="button",(t.menu=e).className="jsoneditor-button jsoneditor-contextmenu-button",e.title=(0,l.Iu)("actionsMenu"),n.appendChild(t.menu),t.tr.appendChild(n));var n=document.createElement("td");return t.tr.appendChild(n),t.tree=this._createDomTree(),n.appendChild(t.tree),this.updateDom({updateIndexes:!0}),t.tr}},{key:"isVisible",value:function(){return this.dom&&this.dom.tr&&this.dom.tr.parentNode||!1}},{key:"isDescendantOf",value:function(e){for(var t=this.parent;t;){if(t===e)return!0;t=t.parent}return!1}},{key:"_createDomField",value:function(){return document.createElement("div")}},{key:"setHighlight",value:function(t){this.dom.tr&&((t?(0,I.addClassName):(0,I.removeClassName))(this.dom.tr,"jsoneditor-highlight"),this.append&&this.append.setHighlight(t),this.childs&&this.childs.forEach(function(e){e.setHighlight(t)}))}},{key:"setSelected",value:function(t,e){this.selected=t,this.dom.tr&&((t?(0,I.addClassName):(0,I.removeClassName))(this.dom.tr,"jsoneditor-selected"),(e?(0,I.addClassName):(0,I.removeClassName))(this.dom.tr,"jsoneditor-first"),this.append&&this.append.setSelected(t),this.showMore&&this.showMore.setSelected(t),this.childs&&this.childs.forEach(function(e){e.setSelected(t)}))}},{key:"updateValue",value:function(e){this.value=e,this.previousValue=e,this.valueError=void 0,this.updateDom()}},{key:"updateField",value:function(e){this.field=e,this.previousField=e,this.fieldError=void 0,this.updateDom()}},{key:"updateDom",value:function(t){var e=this.dom.tree;e&&(e.style.marginLeft=24*this.getLevel()+"px");e=this.dom.field;e&&(this.fieldEditable?(e.contentEditable=this.editable.field,e.spellcheck=!1,e.className="jsoneditor-field"):(e.contentEditable=!1,e.className="jsoneditor-readonly"),n=void 0!==this.index?this.index:void 0!==this.field?this.field:(n=this.editor.options.schema?k._findSchema(this.editor.options.schema,this.editor.options.schemaRefs||{},this.getPath()):void 0)&&n.title?n.title:this._hasChilds()?this.type:"",n=this._escapeHTML(n),document.activeElement===e&&n===this._unescapeHTML((0,I.getInnerText)(e))||(e.innerHTML=n),this._updateSchema());var n=this.dom.value;n&&("array"===this.type||"object"===this.type?this.updateNodeName():(i=this._escapeHTML(this.value),document.activeElement===n&&i===this._unescapeHTML((0,I.getInnerText)(n))||(n.innerHTML=i)));var i=this.dom.tr;i&&("array"===this.type||"object"===this.type?((0,I.addClassName)(i,"jsoneditor-expandable"),this.expanded?((0,I.addClassName)(i,"jsoneditor-expanded"),(0,I.removeClassName)(i,"jsoneditor-collapsed")):((0,I.addClassName)(i,"jsoneditor-collapsed"),(0,I.removeClassName)(i,"jsoneditor-expanded"))):((0,I.removeClassName)(i,"jsoneditor-expandable"),(0,I.removeClassName)(i,"jsoneditor-expanded"),(0,I.removeClassName)(i,"jsoneditor-collapsed"))),this._updateDomField(),this._updateDomValue(),t&&!0===t.updateIndexes&&this._updateDomIndexes(),t&&!0===t.recurse&&this.childs&&this.childs.forEach(function(e){e.updateDom(t)}),this.error&&this.updateError(),this.append&&this.append.updateDom(),this.showMore&&this.showMore.updateDom(),this._updateCssClassName()}},{key:"_updateSchema",value:function(){this.editor&&this.editor.options&&(this.schema=this.editor.options.schema?k._findSchema(this.editor.options.schema,this.editor.options.schemaRefs||{},this.getPath()):null,this.schema?this.enum=k._findEnum(this.schema):delete this.enum)}},{key:"_updateDomIndexes",value:function(){var e=this.dom.value,t=this.childs;e&&t&&("array"===this.type?t.forEach(function(e,t){e.index=t;e=e.dom.field;e&&(e.textContent=t)}):"object"===this.type&&t.forEach(function(e){void 0!==e.index&&(delete e.index,void 0===e.field&&(e.field=""))}))}},{key:"_createDomValue",value:function(){var e;return"array"===this.type?(e=document.createElement("div")).textContent="[...]":"object"===this.type?(e=document.createElement("div")).textContent="{...}":(!this.editable.value&&(0,I.isUrl)(this.value)?(e=document.createElement("a")).href=this.value:((e=document.createElement("div")).contentEditable=this.editable.value,e.spellcheck=!1),e.innerHTML=this._escapeHTML(this.value)),e}},{key:"_createDomExpandButton",value:function(){var e=document.createElement("button");return e.type="button",this._hasChilds()?(e.className=this.expanded?"jsoneditor-button jsoneditor-expanded":"jsoneditor-button jsoneditor-collapsed",e.title=(0,l.Iu)("expandTitle")):(e.className="jsoneditor-button jsoneditor-invisible",e.title=""),e}},{key:"_createDomTree",value:function(){var e=this.dom,t=document.createElement("table"),n=document.createElement("tbody");t.style.borderCollapse="collapse",t.className="jsoneditor-values",t.appendChild(n);var i=document.createElement("tr");n.appendChild(i);n=document.createElement("td");n.className="jsoneditor-tree",i.appendChild(n),e.expand=this._createDomExpandButton(),n.appendChild(e.expand),e.tdExpand=n;n=document.createElement("td");n.className="jsoneditor-tree",i.appendChild(n),e.field=this._createDomField(),n.appendChild(e.field),e.tdField=n;n=document.createElement("td");n.className="jsoneditor-tree",i.appendChild(n),"object"!==this.type&&"array"!==this.type&&(n.appendChild(document.createTextNode(":")),n.className="jsoneditor-separator"),e.tdSeparator=n;n=document.createElement("td");return n.className="jsoneditor-tree",i.appendChild(n),e.value=this._createDomValue(),n.appendChild(e.value),e.tdValue=n,t}},{key:"onEvent",value:function(e){var t,n=e.type,i=e.target||e.srcElement,o=this.dom,r=this,s=this._hasChilds();i!==o.drag&&i!==o.menu||("mouseover"===n?this.editor.highlighter.highlight(this):"mouseout"===n&&this.editor.highlighter.unhighlight()),"click"===n&&i===o.menu&&((t=r.editor.highlighter).highlight(r),t.lock(),(0,I.addClassName)(o.menu,"jsoneditor-selected"),this.showContextMenu(o.menu,function(){(0,I.removeClassName)(o.menu,"jsoneditor-selected"),t.unlock(),t.unhighlight()})),"click"===n&&i===o.expand&&s&&(h=e.ctrlKey,this._onExpand(h)),"click"!==n||e.target!==r.dom.tdColor&&e.target!==r.dom.color||this._showColorPicker(),"change"===n&&i===o.checkbox&&(this.dom.value.textContent=String(!this.value),this._getDomValue(),this._updateDomDefault()),"change"===n&&i===o.select&&(this.dom.value.innerHTML=this._escapeHTML(o.select.value),this._getDomValue(),this._updateDomValue());var a=o.value;if(i===a)switch(n){case"blur":case"change":this._getDomValue(),this._clearValueError(),this._updateDomValue();var l=this._escapeHTML(this.value);l!==this._unescapeHTML((0,I.getInnerText)(a))&&(a.innerHTML=l);break;case"input":this._getDomValue(),this._updateDomValue();break;case"keydown":case"mousedown":this.editor.selection=this.editor.getDomSelection();break;case"click":e.ctrlKey&&this.editable.value&&(0,I.isUrl)(this.value)&&(e.preventDefault(),window.open(this.value,"_blank","noopener"));break;case"keyup":this._getDomValue(),this._updateDomValue();break;case"cut":case"paste":setTimeout(function(){r._getDomValue(),r._updateDomValue()},1)}var d=o.field;if(i===d)switch(n){case"blur":this._getDomField(!0),this._updateDomField();var c=this._escapeHTML(this.field);c!==this._unescapeHTML((0,I.getInnerText)(d))&&(d.innerHTML=c);break;case"input":this._getDomField(),this._updateSchema(),this._updateDomField(),this._updateDomValue();break;case"keydown":case"mousedown":this.editor.selection=this.editor.getDomSelection();break;case"keyup":this._getDomField(),this._updateDomField();break;case"cut":case"paste":setTimeout(function(){r._getDomField(),r._updateDomField()},1)}var h=o.tree;h&&i===h.parentNode&&"click"===n&&!e.hasMoved&&((void 0!==e.offsetX?e.offsetX<24*(this.getLevel()+1):e.pageX<(0,I.getAbsoluteLeft)(o.tdSeparator))||s?d&&((0,I.setEndOfContentEditable)(d),d.focus()):a&&!this.enum&&((0,I.setEndOfContentEditable)(a),a.focus())),(i!==o.tdExpand||s)&&i!==o.tdField&&i!==o.tdSeparator||"click"!==n||e.hasMoved||d&&((0,I.setEndOfContentEditable)(d),d.focus()),"keydown"===n&&this.onKeyDown(e),"function"==typeof this.editor.options.onEvent&&this._onEvent(e)}},{key:"_onEvent",value:function(e){var t=e.target,n=t===this.dom.field,t=t===this.dom.value||t===this.dom.checkbox||t===this.dom.select;(n||t)&&(n={field:this.getField(),path:this.getPath()},t&&!this._hasChilds()&&(n.value=this.getValue()),this.editor.options.onEvent(n,e))}},{key:"onKeyDown",value:function(e){var t,n,i,o,r,s,a,l,d,c,h,u,p,f,m,g,v,y=e.which||e.keyCode,b=e.target||e.srcElement,x=e.ctrlKey,C=e.shiftKey,E=e.altKey,_=!1,T="tree"===this.editor.options.mode,w=0<this.editor.multiselection.nodes.length?this.editor.multiselection.nodes:[this],S=w[0],N=w[w.length-1];13===y?b===this.dom.value?this.editable.value&&!e.ctrlKey||(0,I.isUrl)(this.value)&&(window.open(this.value,"_blank","noopener"),_=!0):b===this.dom.expand&&this._hasChilds()&&(u=e.ctrlKey,this._onExpand(u),b.focus(),_=!0):68===y?x&&T&&(k.onDuplicate(w),_=!0):69===y?x&&(this._onExpand(C),b.focus(),_=!0):77===y&&T?x&&(this.showContextMenu(b),_=!0):46===y&&T?x&&(k.onRemove(w),_=!0):45===y&&T?x&&!C?(this._onInsertBefore(),_=!0):x&&C&&(this._onInsertAfter(),_=!0):35===y?E&&((u=this._lastNode())&&u.focus(k.focusElement||this._getElementName(b)),_=!0):36===y?E&&((p=this._firstNode())&&p.focus(k.focusElement||this._getElementName(b)),_=!0):37===y?E&&!C?((p=this._previousElement(b))&&this.focus(this._getElementName(p)),_=!0):E&&C&&T&&(f=N.expanded?(f=N.getAppendDom())?f.nextSibling:void 0:N.getDom().nextSibling)&&(n=k.getNodeFromTarget(f),f=f.nextSibling,m=k.getNodeFromTarget(f),n&&n instanceof D&&1!==N.parent.childs.length&&m&&m.parent&&(i=this.editor.getDomSelection(),o=(r=S.parent).childs[N.getIndex()+1]||r.append,s=S.getIndex(),a=m.getIndex(),l=r.getInternalPath(),d=m.parent.getInternalPath(),w.forEach(function(e){m.parent.moveBefore(e,m)}),this.focus(k.focusElement||this._getElementName(b)),this.editor._onAction("moveNodes",{count:w.length,fieldNames:w.map(j),oldParentPath:r.getInternalPath(),newParentPath:S.parent.getInternalPath(),oldIndex:o.getIndex(),newIndex:S.getIndex(),oldIndexRedo:s,newIndexRedo:a,oldParentPathRedo:l,newParentPathRedo:d,oldSelection:i,newSelection:this.editor.getDomSelection()}))):38===y?E&&!C?((t=this._previousNode())&&(this.editor.deselect(!0),t.focus(k.focusElement||this._getElementName(b))),_=!0):!E&&x&&C&&T?((t=this._previousNode())&&((h=this.editor.multiselection).start=h.start||this,h.end=t,c=this.editor._findTopLevelNodes(h.start,h.end),this.editor.select(c),t.focus("field")),_=!0):E&&C&&T&&((t=S._previousNode())&&t.parent&&(i=this.editor.getDomSelection(),o=(r=S.parent).childs[N.getIndex()+1]||r.append,s=S.getIndex(),a=t.getIndex(),l=r.getInternalPath(),d=t.parent.getInternalPath(),w.forEach(function(e){t.parent.moveBefore(e,t)}),this.focus(k.focusElement||this._getElementName(b)),this.editor._onAction("moveNodes",{count:w.length,fieldNames:w.map(j),oldParentPath:r.getInternalPath(),newParentPath:S.parent.getInternalPath(),oldIndex:o.getIndex(),newIndex:S.getIndex(),oldIndexRedo:s,newIndexRedo:a,oldParentPathRedo:l,newParentPathRedo:d,oldSelection:i,newSelection:this.editor.getDomSelection()})),_=!0):39===y?E&&!C?((g=this._nextElement(b))&&this.focus(this._getElementName(g)),_=!0):E&&C&&T&&((g=S.getDom().previousSibling)&&(t=k.getNodeFromTarget(g))&&t.parent&&!t.isVisible()&&(i=this.editor.getDomSelection(),o=(r=S.parent).childs[N.getIndex()+1]||r.append,s=S.getIndex(),a=t.getIndex(),l=r.getInternalPath(),d=t.parent.getInternalPath(),w.forEach(function(e){t.parent.moveBefore(e,t)}),this.focus(k.focusElement||this._getElementName(b)),this.editor._onAction("moveNodes",{count:w.length,fieldNames:w.map(j),oldParentPath:r.getInternalPath(),newParentPath:S.parent.getInternalPath(),oldIndex:o.getIndex(),newIndex:S.getIndex(),oldIndexRedo:s,newIndexRedo:a,oldParentPathRedo:l,newParentPathRedo:d,oldSelection:i,newSelection:this.editor.getDomSelection()}))):40===y&&(E&&!C?((n=this._nextNode())&&(this.editor.deselect(!0),n.focus(k.focusElement||this._getElementName(b))),_=!0):!E&&x&&C&&T?((n=this._nextNode())&&((h=this.editor.multiselection).start=h.start||this,h.end=n,c=this.editor._findTopLevelNodes(h.start,h.end),this.editor.select(c),n.focus("field")),_=!0):E&&C&&T&&((n=N.expanded?N.append?N.append._nextNode():void 0:N._nextNode())&&!n.isVisible()&&(n=n.parent.showMore),n&&n instanceof D&&(n=N),(v=n&&(n._nextNode()||n.parent.append))&&v.parent&&(i=this.editor.getDomSelection(),o=(r=S.parent).childs[N.getIndex()+1]||r.append,s=S.getIndex(),a=v.getIndex(),l=r.getInternalPath(),d=v.parent.getInternalPath(),w.forEach(function(e){v.parent.moveBefore(e,v)}),this.focus(k.focusElement||this._getElementName(b)),this.editor._onAction("moveNodes",{count:w.length,fieldNames:w.map(j),oldParentPath:r.getInternalPath(),newParentPath:S.parent.getInternalPath(),oldParentPathRedo:l,newParentPathRedo:d,oldIndexRedo:s,newIndexRedo:a,oldIndex:o.getIndex(),newIndex:S.getIndex(),oldSelection:i,newSelection:this.editor.getDomSelection()})),_=!0)),_&&(e.preventDefault(),e.stopPropagation())}},{key:"_onExpand",value:function(e){var t,n,i;e&&(i=(n=(t=this.dom.tr.parentNode).parentNode).scrollTop,n.removeChild(t)),this.expanded?this.collapse(e):this.expand(e),e&&(n.appendChild(t),n.scrollTop=i)}},{key:"_showColorPicker",value:function(){var t,e;"function"==typeof this.editor.options.onColorPicker&&this.dom.color&&((t=this)._deleteDomColor(),t.updateDom(),e=(0,h.w)(this.dom.color,this.editor.getPopupAnchor()),this.editor.options.onColorPicker(e,this.value,function(e){"string"==typeof e&&e!==t.value&&(t._deleteDomColor(),t.value=e,t.updateDom(),t._debouncedOnChangeValue())}))}},{key:"getFieldNames",value:function(t){return"object"===this.type?this.childs.filter(function(e){return e!==t}).map(function(e){return e.field}):[]}},{key:"_onInsertBefore",value:function(e,t,n){var i=this.editor.getDomSelection(),e=new k(this.editor,{field:void 0!==e?e:"",value:void 0!==t?t:"",type:n});e.expand(!0);t=this.getInternalPath();this.parent.insertBefore(e,this),this.editor.highlighter.unhighlight(),e.focus("field");n=this.editor.getDomSelection();this.editor._onAction("insertBeforeNodes",{nodes:[e],paths:[e.getInternalPath()],beforePath:t,parentPath:this.parent.getInternalPath(),oldSelection:i,newSelection:n})}},{key:"_onInsertAfter",value:function(e,t,n){var i=this.editor.getDomSelection(),t=new k(this.editor,{field:void 0!==e?e:"",value:void 0!==t?t:"",type:n});t.expand(!0),this.parent.insertAfter(t,this),this.editor.highlighter.unhighlight(),t.focus("field");n=this.editor.getDomSelection();this.editor._onAction("insertAfterNodes",{nodes:[t],paths:[t.getInternalPath()],afterPath:this.getInternalPath(),parentPath:this.parent.getInternalPath(),oldSelection:i,newSelection:n})}},{key:"_onAppend",value:function(e,t,n){var i=this.editor.getDomSelection(),t=new k(this.editor,{field:void 0!==e?e:"",value:void 0!==t?t:"",type:n});t.expand(!0),this.parent.appendChild(t),this.editor.highlighter.unhighlight(),t.focus("field");n=this.editor.getDomSelection();this.editor._onAction("appendNodes",{nodes:[t],paths:[t.getInternalPath()],parentPath:this.parent.getInternalPath(),oldSelection:i,newSelection:n})}},{key:"_onChangeType",value:function(e){var t,n,i=this.type;e!==i&&(t=this.editor.getDomSelection(),this.changeType(e),n=this.editor.getDomSelection(),this.editor._onAction("changeType",{path:this.getInternalPath(),oldType:i,newType:e,oldSelection:t,newSelection:n}))}},{key:"sort",value:function(n,e){var t,i,o=!(2<arguments.length&&void 0!==arguments[2])||arguments[2];"string"==typeof n&&(n=(0,I.parsePath)(n)),this._hasChilds()&&(this.hideChilds(),t=this.childs,this.childs=this.childs.concat(),i="desc"===e?-1:1,"object"===this.type?this.childs.sort(function(e,t){return i*c()(e.field,t.field)}):this.childs.sort(function(e,t){e=e.getNestedChild(n),t=t.getNestedChild(n);if(!e)return i;if(!t)return-i;e=e.value,t=t.value;return"string"!=typeof e&&"string"!=typeof t?t<e?i:e<t?-i:0:i*c()(e,t)}),this._updateDomIndexes(),this.showChilds(),!0===o&&this.editor._onAction("sort",{path:this.getInternalPath(),oldChilds:t,newChilds:this.childs}))}},{key:"update",value:function(e){var t=this.getInternalValue();this.setValue(e),this.editor._onAction("transform",{path:this.getInternalPath(),oldValue:t,newValue:this.getInternalValue()})}},{key:"_detachFromDom",value:function(){var e=this.dom.tr?this.dom.tr.parentNode:void 0,t=this.expanded?this.getAppendDom():this.getDom(),t=t&&t.parentNode?t.nextSibling:void 0;return this.hide({resetVisibleChilds:!1}),{table:e,nextTr:t}}},{key:"_attachToDom",value:function(e){e.table&&(e.nextTr?e.table.insertBefore(this.getDom(),e.nextTr):e.table.appendChild(this.getDom())),this.expanded&&this.showChilds()}},{key:"transform",value:function(e){if(this._hasChilds()){this.hideChilds();try{var t=this.getInternalValue(),n=this.getValue(),n=this.editor.options.executeQuery(n,e);this.setValue(n);n=this.getInternalValue();this.editor._onAction("transform",{path:this.getInternalPath(),oldValue:t,newValue:n}),this.showChilds()}catch(e){this.showChilds(),this.editor._onError(e)}}}},{key:"extract",value:function(){this.editor.node.hideChilds(),this.hideChilds();try{var e=this.editor.node.getInternalValue();this.editor._setRoot(this);var t=this.editor.node.getInternalValue();this.editor._onAction("transform",{path:this.editor.node.getInternalPath(),oldValue:e,newValue:t})}catch(e){this.editor._onError(e)}finally{this.updateDom({recurse:!0}),this.showChilds()}}},{key:"getNestedChild",value:function(e){for(var t=0,n=this;n&&t<e.length;)n=n.findChildByProperty(e[t]),t++;return n}},{key:"findChildByProperty",value:function(t){if("object"===this.type)return this.childs.find(function(e){return e.field===t})}},{key:"getAppendDom",value:function(){return this.append||(this.append=new D(this.editor),this.append.setParent(this)),this.append.getDom()}},{key:"getShowMoreDom",value:function(){return this.showMore||(this.showMore=new w(this.editor,this)),this.showMore.getDom()}},{key:"nextSibling",value:function(){var e=this.parent.childs.indexOf(this);return this.parent.childs[e+1]||this.parent.append}},{key:"_previousNode",value:function(){var e=null,t=this.getDom();if(t&&t.parentNode)for(var n=t;n=n.previousSibling,e=k.getNodeFromTarget(n),n&&e&&e instanceof D&&!e.isVisible(););return e}},{key:"_nextNode",value:function(){var e=null,t=this.getDom();if(t&&t.parentNode)for(var n=t;n=n.nextSibling,e=k.getNodeFromTarget(n),n&&e&&e instanceof D&&!e.isVisible(););return e}},{key:"_firstNode",value:function(){var e=null,t=this.getDom();return t&&t.parentNode&&(t=t.parentNode.firstChild,e=k.getNodeFromTarget(t)),e}},{key:"_lastNode",value:function(){var e=null,t=this.getDom();if(t&&t.parentNode)for(var n=t.parentNode.lastChild,e=k.getNodeFromTarget(n);n&&e&&!e.isVisible();)n=n.previousSibling,e=k.getNodeFromTarget(n);return e}},{key:"_previousElement",value:function(e){var t=this.dom;switch(e){case t.value:if(this.fieldEditable)return t.field;case t.field:if(this._hasChilds())return t.expand;case t.expand:return t.menu;case t.menu:if(t.drag)return t.drag;default:return null}}},{key:"_nextElement",value:function(e){var t=this.dom;switch(e){case t.drag:return t.menu;case t.menu:if(this._hasChilds())return t.expand;case t.expand:if(this.fieldEditable)return t.field;case t.field:if(!this._hasChilds())return t.value;default:return null}}},{key:"_getElementName",value:function(t){var n=this;return Object.keys(this.dom).find(function(e){return n.dom[e]===t})}},{key:"_hasChilds",value:function(){return"array"===this.type||"object"===this.type}},{key:"addTemplates",value:function(t,n){var i=this,e=i.editor.options.templates;null!=e&&(e.length&&t.push({type:"separator"}),e.forEach(function(e){t.push({text:e.text,className:e.className||"jsoneditor-type-object",title:e.title,click:(n?function(e,t){i._onAppend(e,t)}:function(e,t){i._onInsertBefore(e,t)}).bind(this,e.field,e.value)})}))}},{key:"showContextMenu",value:function(e,t){var n,i,o=this,r=[];this.editable.value&&r.push({text:(0,l.Iu)("type"),title:(0,l.Iu)("typeTitle"),className:"jsoneditor-type-"+this.type,submenu:[{text:(0,l.Iu)("auto"),className:"jsoneditor-type-auto"+("auto"===this.type?" jsoneditor-selected":""),title:(0,l.Iu)("autoType"),click:function(){o._onChangeType("auto")}},{text:(0,l.Iu)("array"),className:"jsoneditor-type-array"+("array"===this.type?" jsoneditor-selected":""),title:(0,l.Iu)("arrayType"),click:function(){o._onChangeType("array")}},{text:(0,l.Iu)("object"),className:"jsoneditor-type-object"+("object"===this.type?" jsoneditor-selected":""),title:(0,l.Iu)("objectType"),click:function(){o._onChangeType("object")}},{text:(0,l.Iu)("string"),className:"jsoneditor-type-string"+("string"===this.type?" jsoneditor-selected":""),title:(0,l.Iu)("stringType"),click:function(){o._onChangeType("string")}}]}),this._hasChilds()&&(this.editor.options.enableSort&&r.push({text:(0,l.Iu)("sort"),title:(0,l.Iu)("sortTitle",{type:this.type}),className:"jsoneditor-sort-asc",click:function(){o.showSortModal()}}),this.editor.options.enableTransform&&r.push({text:(0,l.Iu)("transform"),title:(0,l.Iu)("transformTitle",{type:this.type}),className:"jsoneditor-transform",click:function(){o.showTransformModal()}}),this.parent&&r.push({text:(0,l.Iu)("extract"),title:(0,l.Iu)("extractTitle",{type:this.type}),className:"jsoneditor-extract",click:function(){o.extract()}})),this.parent&&this.parent._hasChilds()&&(r.length&&r.push({type:"separator"}),n=o.parent.childs,o===n[n.length-1]&&(i=[{text:(0,l.Iu)("auto"),className:"jsoneditor-type-auto",title:(0,l.Iu)("autoType"),click:function(){o._onAppend("","","auto")}},{text:(0,l.Iu)("array"),className:"jsoneditor-type-array",title:(0,l.Iu)("arrayType"),click:function(){o._onAppend("",[])}},{text:(0,l.Iu)("object"),className:"jsoneditor-type-object",title:(0,l.Iu)("objectType"),click:function(){o._onAppend("",{})}},{text:(0,l.Iu)("string"),className:"jsoneditor-type-string",title:(0,l.Iu)("stringType"),click:function(){o._onAppend("","","string")}}],o.addTemplates(i,!0),r.push({text:(0,l.Iu)("appendText"),title:(0,l.Iu)("appendTitle"),submenuTitle:(0,l.Iu)("appendSubmenuTitle"),className:"jsoneditor-append",click:function(){o._onAppend("","","auto")},submenu:i})),i=[{text:(0,l.Iu)("auto"),className:"jsoneditor-type-auto",title:(0,l.Iu)("autoType"),click:function(){o._onInsertBefore("","","auto")}},{text:(0,l.Iu)("array"),className:"jsoneditor-type-array",title:(0,l.Iu)("arrayType"),click:function(){o._onInsertBefore("",[])}},{text:(0,l.Iu)("object"),className:"jsoneditor-type-object",title:(0,l.Iu)("objectType"),click:function(){o._onInsertBefore("",{})}},{text:(0,l.Iu)("string"),className:"jsoneditor-type-string",title:(0,l.Iu)("stringType"),click:function(){o._onInsertBefore("","","string")}}],o.addTemplates(i,!1),r.push({text:(0,l.Iu)("insert"),title:(0,l.Iu)("insertTitle"),submenuTitle:(0,l.Iu)("insertSub"),className:"jsoneditor-insert",click:function(){o._onInsertBefore("","","auto")},submenu:i}),this.editable.field&&(r.push({text:(0,l.Iu)("duplicateText"),title:(0,l.Iu)("duplicateField"),className:"jsoneditor-duplicate",click:function(){k.onDuplicate(o)}}),r.push({text:(0,l.Iu)("removeText"),title:(0,l.Iu)("removeField"),className:"jsoneditor-remove",click:function(){k.onRemove(o)}}))),this.editor.options.onCreateMenu&&(i=o.getPath(),r=this.editor.options.onCreateMenu(r,{type:"single",path:i,paths:[i]})),new s.x(r,{close:t}).show(e,this.editor.getPopupAnchor())}},{key:"showSortModal",value:function(){var n=this,e=this.editor.options.modalAnchor||f.qD,t=this.getValue();(0,u.showSortModal)(e,t,function(e){var t=e.path,t=(0,I.parsePath)(t);n.sortedBy=e,n.sort(t,e.direction)},n.sortedBy)}},{key:"showTransformModal",value:function(){var t=this,e=this.editor.options,n=e.modalAnchor,i=e.createQuery,o=e.executeQuery,r=e.queryDescription,e=this.getValue();(0,p.showTransformModal)({container:n||f.qD,json:e,queryDescription:r,createQuery:i,executeQuery:o,onTransform:function(e){t.transform(e)}})}},{key:"_getType",value:function(e){return e instanceof Array?"array":e instanceof Object?"object":"string"==typeof e&&"string"!=typeof(0,I.parseString)(e)?"string":"auto"}},{key:"_escapeHTML",value:function(e){if("string"!=typeof e)return String(e);e=String(e).replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/ {2}/g," &nbsp;").replace(/^ /,"&nbsp;").replace(/ $/,"&nbsp;"),e=JSON.stringify(e),e=e.substring(1,e.length-1);return!0===this.editor.options.escapeUnicode&&(e=(0,I.escapeUnicodeChars)(e)),e}},{key:"_unescapeHTML",value:function(e){e='"'+this._escapeJSON(e)+'"';return(0,I.parse)(e).replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&nbsp;|\u00A0/g," ").replace(/&amp;/g,"&")}},{key:"_escapeJSON",value:function(e){for(var t="",n=0;n<e.length;){var i=e.charAt(n);"\n"===i?t+="\\n":"\\"===i?(t+=i,n++,""!==(i=e.charAt(n))&&-1!=='"\\/bfnrtu'.indexOf(i)||(t+="\\"),t+=i):t+='"'===i?'\\"':i,n++}return t}},{key:"updateNodeName",value:function(){var e,t=this.childs?this.childs.length:0;if("object"===this.type||"array"===this.type){if(this.editor.options.onNodeName)try{e=this.editor.options.onNodeName({path:this.getPath(),size:t,type:this.type})}catch(e){console.error("Error in onNodeName callback: ",e)}this.dom.value.textContent="object"===this.type?"{"+(e||t)+"}":"["+(e||t)+"]"}}},{key:"recursivelyUpdateNodeName",value:function(){if(this.expanded&&(this.updateNodeName(),"undefined"!==this.childs))for(var e in this.childs)this.childs[e].recursivelyUpdateNodeName()}}])&&y(e.prototype,t),n&&y(e,n),k}();E.prototype.DEBOUNCE_INTERVAL=150,E.prototype.MAX_SEARCH_RESULTS=999;var b=100;function x(e){return e.getInternalPath()}function j(e){return e.getField()}function C(e,t){return Object.prototype.hasOwnProperty.call(e,t)}E.focusElement=void 0,E.select=function(e){setTimeout(function(){(0,I.selectContentEditable)(e)},0)},E.onDragStart=function(t,e){if(!Array.isArray(t))return E.onDragStart([t],e);var n,i,o,r,s;0!==t.length&&(n=t[0],i=t[t.length-1],o=n.parent,s=E.getNodeFromTarget(e.target),r=n.editor,s=(0,I.getAbsoluteTop)(s.dom.tr)-(0,I.getAbsoluteTop)(n.dom.tr),r.mousemove||(r.mousemove=(0,I.addEventListener)(e.view,"mousemove",function(e){E.onDrag(t,e)})),r.mouseup||(r.mouseup=(0,I.addEventListener)(e.view,"mouseup",function(e){E.onDragEnd(t,e)})),r.highlighter.lock(),r.drag={oldCursor:document.body.style.cursor,oldSelection:r.getDomSelection(),oldPaths:t.map(x),oldParent:o,oldNextNode:o.childs[i.getIndex()+1]||o.append,oldParentPathRedo:o.getInternalPath(),oldIndexRedo:n.getIndex(),mouseX:e.pageX,offsetY:s,level:n.getLevel()},document.body.style.cursor="move",e.preventDefault())},E.onDrag=function(e,t){if(!Array.isArray(e))return E.onDrag([e],t);if(0!==e.length){var n,i,o,r,s,a,l=e[0].editor,d=t.pageY-l.drag.offsetY,c=t.pageX,h=!1,u=e[0],p=u.dom.tr,f=(0,I.getAbsoluteTop)(p),m=p.offsetHeight;if(d<f){for(x=p;x=x.previousSibling,i=E.getNodeFromTarget(x),r=x?(0,I.getAbsoluteTop)(x):0,x&&d<r;);i&&!i.parent&&(i=void 0),i||(x=(g=p.parentNode.firstChild)?g.nextSibling:void 0,(i=E.getNodeFromTarget(x))===u&&(i=void 0)),i&&i.isVisible()&&(r=(x=i.dom.tr)?(0,I.getAbsoluteTop)(x):0)+m<d&&(i=void 0),!i||!1!==l.options.limitDragging&&i.parent!==e[0].parent||(e.forEach(function(e){i.parent.moveBefore(e,i)}),h=!0)}else{var g,v=e[e.length-1];if(m=(g=v.expanded&&v.append?v.append.getDom():v.dom.tr)?g.nextSibling:void 0){for(s=(0,I.getAbsoluteTop)(m),n=m;o=E.getNodeFromTarget(n),n&&(a=n.nextSibling?(0,I.getAbsoluteTop)(n.nextSibling):0,a=n?a-s:0,o&&o.parent.childs.length===e.length&&o.parent.childs[e.length-1]===v&&(f+=27),n=n.nextSibling),n&&f+a<d;);if(o&&o.parent){for(var m=c-l.drag.mouseX,m=Math.round(m/24/2),y=l.drag.level+m,b=o.getLevel(),x=o.dom.tr&&o.dom.tr.previousSibling;b<y&&x;){i=E.getNodeFromTarget(x);var C=e.some(function(e){return e===i||i.isDescendantOf(e)});if(!C){if(!(i instanceof D))break;C=i.parent.childs;if(C.length===e.length&&C[e.length-1]===v)break;b=(o=E.getNodeFromTarget(x)).getLevel()}x=x.previousSibling}o instanceof D&&!o.isVisible()&&o.parent.showMore.isVisible()&&(o=o._nextNode()),o&&(!1===l.options.limitDragging||o.parent===e[0].parent)&&o.dom.tr&&o.dom.tr!==g.nextSibling&&(e.forEach(function(e){o.parent.moveBefore(e,o)}),h=!0)}}}h&&(l.drag.mouseX=c,l.drag.level=u.getLevel()),l.startAutoScroll(d),t.preventDefault()}},E.onDragEnd=function(e,t){if(!Array.isArray(e))return E.onDrag([e],t);var n,i,o,r,s,a,l,d,c;0!==e.length&&(c=e[0],n=c.editor,e[0]&&e[0].dom.menu.focus(),i=n.drag.oldParent.getInternalPath(),o=c.parent.getInternalPath(),r=n.drag.oldParent===c.parent,s=n.drag.oldNextNode.getIndex(),a=c.getIndex(),l=n.drag.oldParentPathRedo,d=n.drag.oldIndexRedo,c=r&&d<a?a+e.length:a,r&&d===a||n._onAction("moveNodes",{count:e.length,fieldNames:e.map(j),oldParentPath:i,newParentPath:o,oldIndex:s,newIndex:a,oldIndexRedo:d,newIndexRedo:c,oldParentPathRedo:l,newParentPathRedo:null,oldSelection:n.drag.oldSelection,newSelection:n.getDomSelection()}),document.body.style.cursor=n.drag.oldCursor,n.highlighter.unlock(),e.forEach(function(e){e.updateDom(),t.target!==e.dom.drag&&t.target!==e.dom.menu&&n.highlighter.unhighlight()}),delete n.drag,n.mousemove&&((0,I.removeEventListener)(t.view,"mousemove",n.mousemove),delete n.mousemove),n.mouseup&&((0,I.removeEventListener)(t.view,"mouseup",n.mouseup),delete n.mouseup),n.stopAutoScroll(),t.preventDefault())},E._findEnum=function(e){if(e.enum)return e.enum;e=e.oneOf||e.anyOf||e.allOf;if(e){e=e.filter(function(e){return e.enum});if(0<e.length)return e[0].enum}return null},E._findSchema=function(e,t,n){var i=3<arguments.length&&void 0!==arguments[3]?arguments[3]:e,o=n.slice(1,n.length),r=n[0],s=m(i.oneOf||i.anyOf||i.allOf||[i]);try{for(s.s();!(l=s.n()).done;){if("$ref"in(i=l.value)&&"string"==typeof i.$ref){var a=i.$ref;if(a in t)i=t[a];else{if(!a.startsWith("#/"))throw Error("Unable to resolve reference ".concat(a));var l=a.substring(2).split("/"),i=e,d=m(l);try{for(d.s();!(c=d.n()).done;){var c=c.value;if(!(c in i))throw Error("Unable to resovle reference ".concat(a));i=i[c]}}catch(e){d.e(e)}finally{d.f()}}}if(void 0===r)return i;if("string"!=typeof r){if("number"==typeof r&&"object"===v(i.items)&&null!==i.items)return i=i.items,E._findSchema(e,t,o,i)}else{if("object"===v(i.properties)&&null!==i.properties&&r in i.properties)return i=i.properties[r],E._findSchema(e,t,o,i);if("object"===v(i.patternProperties)&&null!==i.patternProperties)for(var h in i.patternProperties)if(r.match(h))return i=i.patternProperties[h],E._findSchema(e,t,o,i);if("object"===v(i.additionalProperties))return i=i.additionalProperties,E._findSchema(e,t,o,i)}}}catch(e){s.e(e)}finally{s.f()}return null},E.onRemove=function(e){if(!Array.isArray(e))return E.onRemove([e]);var t,n,i,o,r,s;e&&0<e.length&&(t=(s=e[0]).parent,n=s.editor,i=s.getIndex(),n.highlighter.unhighlight(),o=n.getDomSelection(),E.blurNodes(e),r=n.getDomSelection(),s=e.map(x),e.forEach(function(e){e.parent._remove(e)}),n._onAction("removeNodes",{nodes:e,paths:s,parentPath:t.getInternalPath(),index:i,oldSelection:o,newSelection:r}))},E.onDuplicate=function(e){if(!Array.isArray(e))return E.onDuplicate([e]);var t,i,n,o,r,s,a;e&&0<e.length&&(t=e[e.length-1],i=t.parent,(n=t.editor).deselect(n.multiselection.nodes),o=n.getDomSelection(),r=t,s=e.map(function(e){var t,n=e.clone();return"object"===e.parent.type&&(t=e.parent.getFieldNames(),n.field=(0,I.findUniqueName)(e.field,t)),i.insertAfter(n,r),r=n}),1===e.length?"object"===s[0].parent.type?(s[0].dom.field.innerHTML=e[0]._escapeHTML(e[0].field),s[0].focus("field")):s[0].focus():n.select(s),a=n.getDomSelection(),n._onAction("duplicateNodes",{paths:e.map(x),clonePaths:s.map(x),afterPath:t.getInternalPath(),parentPath:i.getInternalPath(),oldSelection:o,newSelection:a}))},E.getNodeFromTarget=function(e){for(;e;){if(e.node)return e.node;e=e.parentNode}},E.targetIsColorPicker=function(e){var t=E.getNodeFromTarget(e);if(t)for(var n=e&&e.parentNode;n;){if(n===t.dom.color)return!0;n=n.parentNode}return!1},E.blurNodes=function(e){var t,n;Array.isArray(e)?(t=(n=e[0]).parent,n=n.getIndex(),(t.childs[n+e.length]?t.childs[n+e.length]:t.childs[n-1]||t).focus()):E.blurNodes([e])};var D=((T.prototype=new E).getDom=function(){var e=this.dom;if(e.tr)return e.tr;this._updateEditability();var t=document.createElement("tr");t.className="jsoneditor-append",t.node=this,e.tr=t,"tree"===this.editor.options.mode&&(e.tdDrag=document.createElement("td"),i=document.createElement("td"),e.tdMenu=i,(n=document.createElement("button")).type="button",n.className="jsoneditor-button jsoneditor-contextmenu-button",n.title="Click to open the actions menu (Ctrl+M)",e.menu=n,i.appendChild(e.menu));var n=document.createElement("td"),i=document.createElement("div");return i.appendChild(document.createTextNode("("+(0,l.Iu)("empty")+")")),i.className="jsoneditor-readonly",n.appendChild(i),e.td=n,e.text=i,this.updateDom(),t},T.prototype.getPath=function(){return null},T.prototype.getIndex=function(){return null},T.prototype.updateDom=function(e){var t=this.dom,n=t.td;n&&(n.style.paddingLeft=24*this.getLevel()+26+"px");var i=t.text;i&&(i.firstChild.nodeValue="("+(0,l.Iu)("empty")+" "+this.parent.type+")");i=t.tr;this.isVisible()?t.tr.firstChild||(t.tdDrag&&i.appendChild(t.tdDrag),t.tdMenu&&i.appendChild(t.tdMenu),i.appendChild(n)):t.tr.firstChild&&(t.tdDrag&&i.removeChild(t.tdDrag),t.tdMenu&&i.removeChild(t.tdMenu),i.removeChild(n))},T.prototype.isVisible=function(){return 0===this.parent.childs.length},T.prototype.showContextMenu=function(e,t){var n=this,i=[{text:(0,l.Iu)("auto"),className:"jsoneditor-type-auto",title:(0,l.Iu)("autoType"),click:function(){n._onAppend("","","auto")}},{text:(0,l.Iu)("array"),className:"jsoneditor-type-array",title:(0,l.Iu)("arrayType"),click:function(){n._onAppend("",[])}},{text:(0,l.Iu)("object"),className:"jsoneditor-type-object",title:(0,l.Iu)("objectType"),click:function(){n._onAppend("",{})}},{text:(0,l.Iu)("string"),className:"jsoneditor-type-string",title:(0,l.Iu)("stringType"),click:function(){n._onAppend("","","string")}}];n.addTemplates(i,!0);var o=[{text:(0,l.Iu)("appendText"),title:(0,l.Iu)("appendTitleAuto"),submenuTitle:(0,l.Iu)("appendSubmenuTitle"),className:"jsoneditor-insert",click:function(){n._onAppend("","","auto")},submenu:i}];this.editor.options.onCreateMenu&&(i=n.parent.getPath(),o=this.editor.options.onCreateMenu(o,{type:"append",path:i,paths:[i]})),new s.x(o,{close:t}).show(e,this.editor.getPopupAnchor())},T.prototype.onEvent=function(e){var t,n=e.type,i=e.target||e.srcElement,o=this.dom;i===o.menu&&("mouseover"===n?this.editor.highlighter.highlight(this.parent):"mouseout"===n&&this.editor.highlighter.unhighlight()),"click"===n&&i===o.menu&&((t=this.editor.highlighter).highlight(this.parent),t.lock(),(0,I.addClassName)(o.menu,"jsoneditor-selected"),this.showContextMenu(o.menu,function(){(0,I.removeClassName)(o.menu,"jsoneditor-selected"),t.unlock(),t.unhighlight()})),"keydown"===n&&this.onKeyDown(e)},T);function T(e){this.editor=e,this.dom={}}var w=((S.prototype=new E).getDom=function(){return this.dom.tr||(this._updateEditability(),this.dom.tr||(n=(t=this).parent,(o=document.createElement("a")).appendChild(document.createTextNode((0,l.Iu)("showMore"))),o.href="#",o.onclick=function(e){return n.visibleChilds=Math.floor(n.visibleChilds/n.getMaxVisibleChilds()+1)*n.getMaxVisibleChilds(),t.updateDom(),n.showChilds(),e.preventDefault(),!1},(r=document.createElement("a")).appendChild(document.createTextNode((0,l.Iu)("showAll"))),r.href="#",r.onclick=function(e){return n.visibleChilds=1/0,t.updateDom(),n.showChilds(),e.preventDefault(),!1},e=document.createElement("div"),i=document.createTextNode(this._getShowMoreText()),e.className="jsoneditor-show-more",e.appendChild(i),e.appendChild(o),e.appendChild(document.createTextNode(". ")),e.appendChild(r),e.appendChild(document.createTextNode(". ")),(o=document.createElement("td")).appendChild(e),r=document.createElement("tr"),"tree"===this.editor.options.mode&&(r.appendChild(document.createElement("td")),r.appendChild(document.createElement("td"))),r.appendChild(o),r.className="jsoneditor-show-more",this.dom.tr=r,this.dom.moreContents=e,this.dom.moreText=i),this.updateDom(),this.dom.tr);var t,n,e,i,o,r},S.prototype.updateDom=function(e){var t;this.isVisible()?(this.dom.tr.node=this.parent.childs[this.parent.visibleChilds],this.dom.tr.parentNode||(t=this.parent._getNextTr())&&t.parentNode.insertBefore(this.dom.tr,t),this.dom.moreText.nodeValue=this._getShowMoreText(),this.dom.moreContents.style.marginLeft=24*(this.getLevel()+1)+"px"):this.dom.tr&&this.dom.tr.parentNode&&this.dom.tr.parentNode.removeChild(this.dom.tr)},S.prototype._getShowMoreText=function(){return(0,l.Iu)("showMoreStatus",{visibleChilds:this.parent.visibleChilds,totalChilds:this.parent.childs.length})+" "},S.prototype.isVisible=function(){return this.parent.expanded&&this.parent.childs.length>this.parent.visibleChilds},S.prototype.onEvent=function(e){"keydown"===e.type&&this.onKeyDown(e)},S);function S(e,t){this.editor=e,this.parent=t,this.dom={}}function N(e,t){for(var n=0;n<t.length;n++){var i=t[n];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,i.key,i)}}var k=function(){function n(t){function r(e){return t.node.findNodeByInternalPath(e)}!function(e){if(!(e instanceof n))throw new TypeError("Cannot call a class as a function")}(this),this.editor=t,this.history=[],this.index=-1,this.clear(),this.actions={editField:{undo:function(e){r(e.parentPath).childs[e.index].updateField(e.oldValue)},redo:function(e){r(e.parentPath).childs[e.index].updateField(e.newValue)}},editValue:{undo:function(e){r(e.path).updateValue(e.oldValue)},redo:function(e){r(e.path).updateValue(e.newValue)}},changeType:{undo:function(e){r(e.path).changeType(e.oldType)},redo:function(e){r(e.path).changeType(e.newType)}},appendNodes:{undo:function(e){var t=r(e.parentPath);e.paths.map(r).forEach(function(e){t.removeChild(e)})},redo:function(e){var t=r(e.parentPath);e.nodes.forEach(function(e){t.appendChild(e)})}},insertBeforeNodes:{undo:function(e){var t=r(e.parentPath);e.paths.map(r).forEach(function(e){t.removeChild(e)})},redo:function(e){var t=r(e.parentPath),n=r(e.beforePath);e.nodes.forEach(function(e){t.insertBefore(e,n)})}},insertAfterNodes:{undo:function(e){var t=r(e.parentPath);e.paths.map(r).forEach(function(e){t.removeChild(e)})},redo:function(e){var t=r(e.parentPath),n=r(e.afterPath);e.nodes.forEach(function(e){t.insertAfter(e,n),n=e})}},removeNodes:{undo:function(e){var t=r(e.parentPath),n=t.childs[e.index]||t.append;e.nodes.forEach(function(e){t.insertBefore(e,n)})},redo:function(e){var t=r(e.parentPath);e.paths.map(r).forEach(function(e){t.removeChild(e)})}},duplicateNodes:{undo:function(e){var t=r(e.parentPath);e.clonePaths.map(r).forEach(function(e){t.removeChild(e)})},redo:function(e){var i=r(e.parentPath),o=r(e.afterPath);e.paths.map(r).forEach(function(e){var t,n=e.clone();"object"===i.type&&(t=i.getFieldNames(),n.field=(0,I.findUniqueName)(e.field,t)),i.insertAfter(n,o),o=n})}},moveNodes:{undo:function(n){var i=r(n.oldParentPath),e=r(n.newParentPath),o=i.childs[n.oldIndex]||i.append;e.childs.slice(n.newIndex,n.newIndex+n.count).forEach(function(e,t){e.field=n.fieldNames[t],i.moveBefore(e,o)}),null===n.newParentPathRedo&&(n.newParentPathRedo=e.getInternalPath())},redo:function(n){var e=r(n.oldParentPathRedo),i=r(n.newParentPathRedo),o=i.childs[n.newIndexRedo]||i.append;e.childs.slice(n.oldIndexRedo,n.oldIndexRedo+n.count).forEach(function(e,t){e.field=n.fieldNames[t],i.moveBefore(e,o)})}},sort:{undo:function(e){var t=r(e.path);t.hideChilds(),t.childs=e.oldChilds,t.updateDom({updateIndexes:!0}),t.showChilds()},redo:function(e){var t=r(e.path);t.hideChilds(),t.childs=e.newChilds,t.updateDom({updateIndexes:!0}),t.showChilds()}},transform:{undo:function(e){r(e.path).setInternalValue(e.oldValue)},redo:function(e){r(e.path).setInternalValue(e.newValue)}}}}var e,t,i;return e=n,(t=[{key:"onChange",value:function(){}},{key:"add",value:function(e,t){this.index++,this.history[this.index]={action:e,params:t,timestamp:new Date},this.index<this.history.length-1&&this.history.splice(this.index+1,this.history.length-this.index-1),this.onChange()}},{key:"clear",value:function(){this.history=[],this.index=-1,this.onChange()}},{key:"canUndo",value:function(){return 0<=this.index}},{key:"canRedo",value:function(){return this.index<this.history.length-1}},{key:"undo",value:function(){if(this.canUndo()){var e=this.history[this.index];if(e){var t=this.actions[e.action];if(t&&t.undo){if(t.undo(e.params),e.params.oldSelection)try{this.editor.setDomSelection(e.params.oldSelection)}catch(e){console.error(e)}}else console.error(new Error('unknown action "'+e.action+'"'))}this.index--,this.onChange()}}},{key:"redo",value:function(){if(this.canRedo()){this.index++;var e=this.history[this.index];if(e){var t=this.actions[e.action];if(t&&t.redo){if(t.redo(e.params),e.params.newSelection)try{this.editor.setDomSelection(e.params.newSelection)}catch(e){console.error(e)}}else console.error(new Error('unknown action "'+e.action+'"'))}this.onChange()}}},{key:"destroy",value:function(){this.editor=null,this.history=[],this.index=-1}}])&&N(e.prototype,t),i&&N(e,i),n}();function A(e,t){for(var n=0;n<t.length;n++){var i=t[n];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,i.key,i)}}var P=function(){function o(e,t){!function(e){if(!(e instanceof o))throw new TypeError("Cannot call a class as a function")}(this);var n=this;this.editor=e,this.timeout=void 0,this.delay=200,this.lastText=void 0,this.results=null,this.dom={},this.dom.container=t;e=document.createElement("div");(this.dom.wrapper=e).className="jsoneditor-search",t.appendChild(e);t=document.createElement("div");(this.dom.results=t).className="jsoneditor-results",e.appendChild(t);t=document.createElement("div");(this.dom.input=t).className="jsoneditor-frame",t.title=(0,l.Iu)("searchTitle"),e.appendChild(t);e=document.createElement("button");e.type="button",e.className="jsoneditor-refresh",t.appendChild(e);var i=document.createElement("input");i.type="text",(this.dom.search=i).oninput=function(e){n._onDelayedSearch(e)},i.onchange=function(e){n._onSearch()},i.onkeydown=function(e){ n._onKeyDown(e)},i.onkeyup=function(e){n._onKeyUp(e)},e.onclick=function(e){i.select()},t.appendChild(i);e=document.createElement("button");e.type="button",e.title=(0,l.Iu)("searchNextResultTitle"),e.className="jsoneditor-next",e.onclick=function(){n.next()},t.appendChild(e);e=document.createElement("button");e.type="button",e.title=(0,l.Iu)("searchPreviousResultTitle"),e.className="jsoneditor-previous",e.onclick=function(){n.previous()},t.appendChild(e)}var e,t,n;return e=o,(t=[{key:"next",value:function(e){var t;this.results&&((t=null!==this.resultIndex?this.resultIndex+1:0)>this.results.length-1&&(t=0),this._setActiveResult(t,e))}},{key:"previous",value:function(e){var t,n;this.results&&(t=this.results.length-1,(n=null!==this.resultIndex?this.resultIndex-1:t)<0&&(n=t),this._setActiveResult(n,e))}},{key:"_setActiveResult",value:function(e,t){var n;if(this.activeResult&&(n=this.activeResult.node,"field"===this.activeResult.elem?delete n.searchFieldActive:delete n.searchValueActive,n.updateDom()),!this.results||!this.results[e])return this.resultIndex=void 0,void(this.activeResult=void 0);this.resultIndex=e;var i=this.results[this.resultIndex].node,o=this.results[this.resultIndex].elem;"field"===o?i.searchFieldActive=!0:i.searchValueActive=!0,this.activeResult=this.results[this.resultIndex],i.updateDom(),i.scrollTo(function(){t&&i.focus(o)})}},{key:"_clearDelay",value:function(){void 0!==this.timeout&&(clearTimeout(this.timeout),delete this.timeout)}},{key:"_onDelayedSearch",value:function(e){this._clearDelay();var t=this;this.timeout=setTimeout(function(e){t._onSearch()},this.delay)}},{key:"_onSearch",value:function(e){this._clearDelay();var t=this.dom.search.value,t=0<t.length?t:void 0;if(t!==this.lastText||e){this.lastText=t,this.results=this.editor.search(t);var e=this.results[0]?this.results[0].node.MAX_SEARCH_RESULTS:1/0,n=0;if(this.activeResult)for(var i=0;i<this.results.length;i++)if(this.results[i].node===this.activeResult.node){n=i;break}this._setActiveResult(n,!1),void 0!==t?(t=this.results.length,this.dom.results.textContent=0===t?"no results":1===t?"1 result":e<t?e+"+ results":t+" results"):this.dom.results.textContent=""}}},{key:"_onKeyDown",value:function(e){var t=e.which;27===t?(this.dom.search.value="",this._onSearch(),e.preventDefault(),e.stopPropagation()):13===t&&(e.ctrlKey?this._onSearch(!0):e.shiftKey?this.previous():this.next(),e.preventDefault(),e.stopPropagation())}},{key:"_onKeyUp",value:function(e){var t=e.keyCode;27!==t&&13!==t&&this._onDelayedSearch(e)}},{key:"clear",value:function(){this.dom.search.value="",this._onSearch()}},{key:"forceSearch",value:function(){this._onSearch(!0)}},{key:"isEmpty",value:function(){return""===this.dom.search.value}},{key:"destroy",value:function(){this.editor=null,this.dom.container.removeChild(this.dom.wrapper),this.dom=null,this.results=null,this.activeResult=null,this._clearDelay()}}])&&A(e.prototype,t),n&&A(e,n),o}();function O(e,t){for(var n=0;n<t.length;n++){var i=t[n];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,i.key,i)}}var F=function(){function n(e,t){!function(e){if(!(e instanceof n))throw new TypeError("Cannot call a class as a function")}(this),e&&(this.root=t,this.path=document.createElement("div"),this.path.className="jsoneditor-treepath",this.path.setAttribute("tabindex",0),this.contentMenuClicked=!1,e.appendChild(this.path),this.reset())}var e,t,i;return e=n,(t=[{key:"reset",value:function(){this.path.textContent=(0,l.Iu)("selectNode")}},{key:"setPath",value:function(o){var r=this;this.path.textContent="",o&&o.length&&o.forEach(function(n,i){var e,t=document.createElement("span");t.className="jsoneditor-treepath-element",t.innerText=n.name,t.onclick=function(e){this.selectionCallback&&this.selectionCallback(e)}.bind(r,n),r.path.appendChild(t),n.children.length&&((e=document.createElement("span")).className="jsoneditor-treepath-seperator",e.textContent="►",e.onclick=function(){r.contentMenuClicked=!0;var t=[];n.children.forEach(function(e){t.push({text:e.name,className:"jsoneditor-type-modes"+(o[i+1]+1&&o[i+1].name===e.name?" jsoneditor-selected":""),click:function(e,t){this.contextMenuCallback&&this.contextMenuCallback(e,t)}.bind(r,n,e.name)})}),new s.x(t,{limitHeight:!0}).show(e,r.root,!0)},r.path.appendChild(e)),i===o.length-1&&(t=(e||t).getBoundingClientRect().right,r.path.offsetWidth<t&&(r.path.scrollLeft=t),r.path.scrollLeft&&((t=document.createElement("span")).className="jsoneditor-treepath-show-all-btn",t.title="show all path",t.textContent="...",t.onclick=function(e){(r.contentMenuClicked=!1,I.addClassName)(r.path,"show-all"),r.path.style.width=r.path.parentNode.getBoundingClientRect().width-10+"px",r.path.onblur=function(){if(r.contentMenuClicked)return r.contentMenuClicked=!1,void r.path.focus();(0,I.removeClassName)(r.path,"show-all"),r.path.onblur=void 0,r.path.style.width="",r.setPath(e)}}.bind(r,o),r.path.insertBefore(t,r.path.firstChild)))})}},{key:"onSectionSelected",value:function(e){"function"==typeof e&&(this.selectionCallback=e)}},{key:"onContextMenuItemSelected",value:function(e){"function"==typeof e&&(this.contextMenuCallback=e)}}])&&O(e.prototype,t),i&&O(e,i),n}(),t=n(37),M=n.n(t),t={};t.create=function(e,t){if(!e)throw new Error("No container element provided.");this.container=e,this.dom={},this.highlighter=new i,this.selection=void 0,this.multiselection={nodes:[]},this.validateSchema=null,this.validationSequence=0,this.errorNodes=[],this.lastSchemaErrors=void 0,this.node=null,this.focusTarget=null,this._setOptions(t),t.autocomplete&&(this.autocomplete=function(s){(s=s||{}).filter=s.filter||"start",s.trigger=s.trigger||"keydown",s.confirmKeys=s.confirmKeys||[39,35,9],s.caseSensitive=s.caseSensitive||!1;var o="",r="",a=document.createElement("div");a.style.position="relative",a.style.outline="0",a.style.border="0",a.style.margin="0",a.style.padding="0";var t,l,d=document.createElement("div");function c(e){var t,n;document.createRange?((t=document.createRange()).selectNodeContents(e),t.collapse(!1),(n=window.getSelection()).removeAllRanges(),n.addRange(t)):document.selection&&((t=document.body.createTextRange()).moveToElementText(e),t.collapse(!1),t.select())}function h(e){return void 0===t&&((t=document.createElement("span")).style.visibility="hidden",t.style.position="fixed",t.style.outline="0",t.style.margin="0",t.style.padding="0",t.style.border="0",t.style.left="0",t.style.whiteSpace="pre",t.style.fontSize=o,t.style.fontFamily=r,t.style.fontWeight="normal",document.body.appendChild(t)),t.textContent=e,t.getBoundingClientRect().right}d.className="autocomplete dropdown",d.style.position="absolute",d.style.visibility="hidden";var u,p,f,n,m,g={onArrowDown:function(){},onArrowUp:function(){},onEnter:function(){},onTab:function(){},startFrom:0,options:[],element:null,elementHint:null,elementStyle:null,wrapper:a,show:function(e,t,n){var i=this;this.startFrom=t,this.wrapper.remove(),this.elementHint&&(this.elementHint.remove(),this.elementHint=null),""===o&&(o=window.getComputedStyle(e).getPropertyValue("font-size")),""===r&&(r=window.getComputedStyle(e).getPropertyValue("font-family")),d.style.marginLeft="0",d.style.marginTop=e.getBoundingClientRect().height+"px",this.options=n.map(String),this.element!==e&&(this.element=e,this.elementStyle={zIndex:this.element.style.zIndex,position:this.element.style.position,backgroundColor:this.element.style.backgroundColor,borderColor:this.element.style.borderColor}),this.element.style.zIndex=3,this.element.style.position="relative",this.element.style.backgroundColor="transparent",this.element.style.borderColor="transparent",this.elementHint=e.cloneNode(),this.elementHint.className="autocomplete hint",this.elementHint.style.zIndex=2,this.elementHint.style.position="absolute",this.elementHint.onfocus=function(){i.element.focus()},this.element.addEventListener&&(this.element.removeEventListener("keydown",C),this.element.addEventListener("keydown",C,!1),this.element.removeEventListener("blur",E),this.element.addEventListener("blur",E,!1)),a.appendChild(this.elementHint),a.appendChild(d),e.parentElement.appendChild(a),this.repaint(e)},setText:function(e){this.element.innerText=e},getText:function(){return this.element.innerText},hideDropDown:function(){this.wrapper.remove(),this.elementHint&&(this.elementHint.remove(),this.elementHint=null,v.hide(),this.element.style.zIndex=this.elementStyle.zIndex,this.element.style.position=this.elementStyle.position,this.element.style.backgroundColor=this.elementStyle.backgroundColor,this.element.style.borderColor=this.elementStyle.borderColor)},repaint:function(e){var e=(e=e.innerText).replace("\n",""),t=this.options.length,n=e.substring(this.startFrom);l=e.substring(0,this.startFrom);for(var i=0;i<t;i++){var o=this.options[i];if(!s.caseSensitive&&0===o.toLowerCase().indexOf(n.toLowerCase())||s.caseSensitive&&0===o.indexOf(n)){this.elementHint.innerText=l+n+o.substring(n.length),this.elementHint.realInnerText=l+o;break}}d.style.left=h(l)+"px",v.refresh(n,this.options),this.elementHint.style.width=h(this.elementHint.innerText)+10+"px","hidden"===d.style.visibility||(this.elementHint.style.width=h(this.elementHint.innerText)+d.clientWidth+"px")}},v=(u=d,p=[],f=0,n=-1,m={rs:g,hide:function(){u.style.visibility="hidden"},refresh:function(i,e){u.style.visibility="hidden",f=0,u.textContent="";var t=window.innerHeight||document.documentElement.clientHeight,n=u.parentNode.getBoundingClientRect(),o=n.top-6,n=t-n.bottom-6;p=[];var r="function"==typeof s.filter?s.filter:_[s.filter],e=r?e.filter(function(e){return r(s.caseSensitive?i:i.toLowerCase(),s.caseSensitive?e:e.toLowerCase(),s)}):[];0!==(p=e.map(function(e){var t=document.createElement("div");t.className="item",t.onmouseover=y,t.onmouseout=b,t.onmousedown=x,t.__hint=e,t.textContent="",t.appendChild(document.createTextNode(e.substring(0,i.length)));var n=document.createElement("b");return n.appendChild(document.createTextNode(e.substring(i.length))),t.appendChild(n),u.appendChild(t),t})).length&&(1===p.length&&(i.toLowerCase()===p[0].__hint.toLowerCase()&&!s.caseSensitive||i===p[0].__hint&&s.caseSensitive)||p.length<2||(m.highlight(0),3*n<o?(u.style.maxHeight=o+"px",u.style.top="",u.style.bottom="100%"):(u.style.top="100%",u.style.bottom="",u.style.maxHeight=n+"px"),u.style.visibility="visible"))},highlight:function(e){-1!==n&&p[n]&&(p[n].className="item"),p[e].className="item hover",n=e},move:function(e){return"hidden"===u.style.visibility?"":(f+e===-1||f+e===p.length||(f+=e,m.highlight(f)),p[f].__hint)},onmouseselection:function(){}});function y(){this.style.backgroundColor="#ddd"}function b(){this.style.backgroundColor=""}function x(){m.hide(),m.onmouseselection(this.__hint,m.rs)}var C=function(e){var t=(e=e||window.event).keyCode;if(null!=this.elementHint&&33!==t&&34!==t){if(27===t)return g.hideDropDown(),g.element.focus(),e.preventDefault(),void e.stopPropagation();var n=(n=this.element.innerText).replace("\n","");if(0<=s.confirmKeys.indexOf(t))return 9===t&&0===this.elementHint.innerText.length&&g.onTab(),void(0<this.elementHint.innerText.length&&this.element.innerText!==this.elementHint.realInnerText&&(this.element.innerText=this.elementHint.realInnerText,g.hideDropDown(),c(this.element),9===t&&(g.element.focus(),e.preventDefault(),e.stopPropagation())));if(13!==t){if(40===t){var i=n.substring(this.startFrom),o=v.move(1);return""===o&&g.onArrowDown(),this.elementHint.innerText=l+i+o.substring(i.length),this.elementHint.realInnerText=l+o,e.preventDefault(),void e.stopPropagation()}38===t&&(n=n.substring(this.startFrom),""===(r=v.move(-1))&&g.onArrowUp(),this.elementHint.innerText=l+n+r.substring(n.length),this.elementHint.realInnerText=l+r,e.preventDefault(),e.stopPropagation())}else if(0===this.elementHint.innerText.length)g.onEnter();else{var r="hidden"===d.style.visibility;if(v.hide(),r)return g.hideDropDown(),g.element.focus(),void g.onEnter();this.element.innerText=this.elementHint.realInnerText,g.hideDropDown(),c(this.element),e.preventDefault(),e.stopPropagation()}}}.bind(g),E=function(e){g.hideDropDown()};return v.onmouseselection=function(e,t){t.element.innerText=t.elementHint.innerText=l+e,t.hideDropDown(),window.setTimeout(function(){t.element.focus(),c(t.element)},1)},g}(t.autocomplete)),this.options.history&&"view"!==this.options.mode&&(this.history=new k(this)),this._createFrame(),this._createTable()},t.destroy=function(){this.frame&&this.container&&this.frame.parentNode===this.container&&(this.container.removeChild(this.frame),this.frame=null),this.container=null,this.dom=null,this.clear(),this.node=null,this.focusTarget=null,this.selection=null,this.multiselection=null,this.errorNodes=null,this.validateSchema=null,this._debouncedValidate=null,this.history&&(this.history.destroy(),this.history=null),this.searchBox&&(this.searchBox.destroy(),this.searchBox=null),this.modeSwitcher&&(this.modeSwitcher.destroy(),this.modeSwitcher=null),this.frameFocusTracker.destroy()},t._setOptions=function(t){var n=this;this.options={search:!0,history:!0,mode:"tree",name:void 0,schema:null,schemaRefs:null,autocomplete:null,navigationBar:!0,mainMenuBar:!0,limitDragging:!1,onSelectionChange:null,colorPicker:!0,onColorPicker:function(e,t,n){var i;M()?(i=e.getBoundingClientRect().top,i=(0,I.getWindow)(e).innerHeight-i<300&&300<i,new(M())({parent:e,color:t,popup:i?"top":"bottom",onDone:function(e){e=1===e.rgba[3]?e.hex.substr(0,7):e.hex;n(e)}}).show()):console.warn("Cannot open color picker: the `vanilla-picker` library is not included in the bundle. Either use the full bundle or implement your own color picker using `onColorPicker`.")},timestampTag:!0,timestampFormat:null,createQuery:r.r,executeQuery:r.J,onEvent:null,enableSort:!0,enableTransform:!0},t&&(Object.keys(t).forEach(function(e){n.options[e]=t[e]}),null==t.limitDragging&&null!=t.schema&&(this.options.limitDragging=!0)),this.setSchema(this.options.schema,this.options.schemaRefs),this._debouncedValidate=(0,I.debounce)(this.validate.bind(this),this.DEBOUNCE_INTERVAL),t.onSelectionChange&&this.onSelectionChange(t.onSelectionChange),(0,l.cC)(this.options.languages),(0,l.m0)(this.options.language)},t.set=function(e){e instanceof Function||void 0===e?this.clear():(this.content.removeChild(this.table),e={field:this.options.name,value:e},e=new E(this,e),this._setRoot(e),this.validate(),this.node.expand(!1),this.content.appendChild(this.table)),this.history&&this.history.clear(),this.searchBox&&this.searchBox.clear()},t.update=function(e){var t,n;this.node.deepEqual(e)||(t=this.getSelection(),this.onChangeDisabled=!0,this.node.update(e),this.onChangeDisabled=!1,this.validate(),this.searchBox&&!this.searchBox.isEmpty()&&this.searchBox.forceSearch(),t&&t.start&&t.end?(n=this.node.findNodeByPath(t.start.path),e=this.node.findNodeByPath(t.end.path),n&&e?this.setSelection(t.start,t.end):this.setSelection({},{})):this.setSelection({},{}))},t.get=function(){if(this.node)return this.node.getValue()},t.getText=function(){return JSON.stringify(this.get())},t.setText=function(t){try{this.set((0,I.parse)(t))}catch(e){var n=(0,I.tryJsonRepair)(t);this.set((0,I.parse)(n))}},t.updateText=function(t){try{this.update((0,I.parse)(t))}catch(e){var n=(0,I.tryJsonRepair)(t);this.update((0,I.parse)(n))}},t.setName=function(e){this.options.name=e,this.node&&this.node.updateField(this.options.name)},t.getName=function(){return this.options.name},t.focus=function(){var e=this.scrollableContent.querySelector("[contenteditable=true]");e?e.focus():this.node.dom.expand?this.node.dom.expand.focus():this.node.dom.menu?this.node.dom.menu.focus():(e=this.frame.querySelector("button"))&&e.focus()},t.clear=function(){this.node&&(this.node.hide(),delete this.node),this.treePath&&this.treePath.reset()},t._setRoot=function(e){this.clear(),(this.node=e).setParent(null),e.setField(this.getName(),!1),delete e.index,this.tbody.appendChild(e.getDom())},t.search=function(e){var t;return this.node?(this.content.removeChild(this.table),t=this.node.search(e),this.content.appendChild(this.table)):t=[],t},t.expandAll=function(){this.node&&(this.content.removeChild(this.table),this.node.expand(),this.content.appendChild(this.table))},t.collapseAll=function(){this.node&&(this.content.removeChild(this.table),this.node.collapse(),this.content.appendChild(this.table))},t._onAction=function(e,t){this.history&&this.history.add(e,t),this._onChange()},t._onChange=function(){if(!this.onChangeDisabled){var e;if(this.selection=this.getDomSelection(),this._debouncedValidate(),this.treePath&&((e=this.node&&this.selection?this.node.findNodeByInternalPath(this.selection.path):this.multiselection?this.multiselection.nodes[0]:void 0)?this._updateTreePath(e.getNodePath()):this.treePath.reset()),this.options.onChange)try{this.options.onChange()}catch(e){console.error("Error in onChange callback: ",e)}if(this.options.onChangeJSON)try{this.options.onChangeJSON(this.get())}catch(e){console.error("Error in onChangeJSON callback: ",e)}if(this.options.onChangeText)try{this.options.onChangeText(this.getText())}catch(e){console.error("Error in onChangeText callback: ",e)}if(this.options.onClassName&&this.node.recursivelyUpdateCssClassesOnNodes(),this.options.onNodeName&&this.node.childs)try{this.node.recursivelyUpdateNodeName()}catch(e){console.error("Error in onNodeName callback: ",e)}}},t.validate=function(){var t=this,n=this.node;if(n){var e=n.getValue(),i=[];this.validateSchema&&(this.validateSchema(e)||(i=this.validateSchema.errors.map(function(e){return(0,I.improveSchemaError)(e)}).map(function(e){return{node:n.findNode(e.dataPath),error:e,type:"validation"}}).filter(function(e){return null!=e.node})));try{this.validationSequence++;var o=this,r=this.validationSequence;this._validateCustom(e).then(function(e){r===o.validationSequence&&(e=[].concat(i,e||[]),o._renderValidationErrors(e),"function"==typeof t.options.onValidationError&&((0,I.isValidationErrorChanged)(e,t.lastSchemaErrors)&&t.options.onValidationError.call(t,e),t.lastSchemaErrors=e))}).catch(function(e){console.error(e)})}catch(e){console.error(e)}}},t._renderValidationErrors=function(e){this.errorNodes&&this.errorNodes.forEach(function(e){e.setError(null)});var t=e.reduce(function(e,t){return t.node.findParents().filter(function(t){return!e.some(function(e){return e[0]===t})}).map(function(e){return[e,t.node]}).concat(e)},[]);this.errorNodes=t.map(function(e){return{node:e[0],child:e[1],error:{message:"object"===e[0].type?(0,l.Iu)("containsInvalidProperties"):(0,l.Iu)("containsInvalidItems")}}}).concat(e).map(function(e){return e.node.setError(e.error,e.child),e.node})},t._validateCustom=function(e){try{if(this.options.onValidate){var n=this.node,t=this.options.onValidate(e);return((0,I.isPromise)(t)?t:Promise.resolve(t)).then(function(e){return Array.isArray(e)?e.filter(function(e){var t=(0,I.isValidValidationError)(e);return t||console.warn('Ignoring a custom validation error with invalid structure. Expected structure: {path: [...], message: "..."}. Actual error:',e),t}).map(function(e){var t;try{t=e&&e.path?n.findNodeByPath(e.path):null}catch(e){}return t||console.warn("Ignoring validation error: node not found. Path:",e.path,"Error:",e),{node:t,error:e,type:"customValidation"}}).filter(function(e){return e&&e.node&&e.error&&e.error.message}):null})}}catch(e){return Promise.reject(e)}return Promise.resolve(null)},t.refresh=function(){this.node&&this.node.updateDom({recurse:!0})},t.startAutoScroll=function(e){var t=this,n=this.scrollableContent,i=(0,I.getAbsoluteTop)(n),o=n.clientHeight,r=i+o;e<i+24&&0<n.scrollTop?this.autoScrollStep=(i+24-e)/3:r-24<e&&o+n.scrollTop<n.scrollHeight?this.autoScrollStep=(r-24-e)/3:this.autoScrollStep=void 0,this.autoScrollStep?this.autoScrollTimer||(this.autoScrollTimer=setInterval(function(){t.autoScrollStep?n.scrollTop-=t.autoScrollStep:t.stopAutoScroll()},50)):this.stopAutoScroll()},t.stopAutoScroll=function(){this.autoScrollTimer&&(clearTimeout(this.autoScrollTimer),delete this.autoScrollTimer),this.autoScrollStep&&delete this.autoScrollStep},t.setDomSelection=function(e){var t,n,i;e&&("scrollTop"in e&&this.scrollableContent&&(this.scrollableContent.scrollTop=e.scrollTop),e.paths?(t=this,i=e.paths.map(function(e){return t.node.findNodeByInternalPath(e)}),this.select(i)):(i=(n=e.path?this.node.findNodeByInternalPath(e.path):null)&&e.domName?n.dom[e.domName]:null,e.range&&i?(i=Object.assign({},e.range,{container:i}),(0,I.setSelectionOffset)(i)):n&&n.focus()))},t.getDomSelection=function(){var t=E.getNodeFromTarget(this.focusTarget),n=this.focusTarget,e=t?Object.keys(t.dom).find(function(e){return t.dom[e]===n}):null,i=(0,I.getSelectionOffset)();return i&&"DIV"!==i.container.nodeName&&(i=null),i&&i.container!==n&&(i=null),i&&delete i.container,{path:t?t.getInternalPath():null,domName:e,range:i,paths:0<this.multiselection.length?this.multiselection.nodes.map(function(e){return e.getInternalPath()}):null,scrollTop:this.scrollableContent?this.scrollableContent.scrollTop:0}},t.scrollTo=function(e,n){var i,t,o,r,s=this.scrollableContent;s?((i=this).animateTimeout&&(clearTimeout(i.animateTimeout),delete i.animateTimeout),i.animateCallback&&(i.animateCallback(!1),delete i.animateCallback),t=s.clientHeight,o=s.scrollHeight-t,r=Math.min(Math.max(e-t/4,0),o),function e(){var t=s.scrollTop,t=r-t;3<Math.abs(t)?(s.scrollTop+=t/3,i.animateCallback=n,i.animateTimeout=setTimeout(e,50)):(n&&n(!0),s.scrollTop=r,delete i.animateTimeout,delete i.animateCallback)}()):n&&n(!1)},t._createFrame=function(){this.frame=document.createElement("div"),this.frame.className="jsoneditor jsoneditor-mode-"+this.options.mode,this.container.appendChild(this.frame),this.contentOuter=document.createElement("div"),this.contentOuter.className="jsoneditor-outer";var t=this;function n(e){t._onEvent&&t._onEvent(e)}var e,i,o,r,s={target:this.frame,onFocus:this.options.onFocus||null,onBlur:this.options.onBlur||null};this.frameFocusTracker=new a.R(s),this.frame.onclick=function(e){var t=e.target;n(e),"BUTTON"===t.nodeName&&e.preventDefault()},this.frame.oninput=n,this.frame.onchange=n,this.frame.onkeydown=n,this.frame.onkeyup=n,this.frame.oncut=n,this.frame.onpaste=n,this.frame.onmousedown=n,this.frame.onmouseup=n,this.frame.onmouseover=n,this.frame.onmouseout=n,(0,I.addEventListener)(this.frame,"focus",n,!0),(0,I.addEventListener)(this.frame,"blur",n,!0),this.frame.onfocusin=n,this.frame.onfocusout=n,this.options.mainMenuBar&&((0,I.addClassName)(this.contentOuter,"has-main-menu-bar"),this.menu=document.createElement("div"),this.menu.className="jsoneditor-menu",this.frame.appendChild(this.menu),(s=document.createElement("button")).type="button",s.className="jsoneditor-expand-all",s.title=(0,l.Iu)("expandAll"),s.onclick=function(){t.expandAll()},this.menu.appendChild(s),(s=document.createElement("button")).type="button",s.title=(0,l.Iu)("collapseAll"),s.className="jsoneditor-collapse-all",s.onclick=function(){t.collapseAll()},this.menu.appendChild(s),this.options.enableSort&&((e=document.createElement("button")).type="button",e.className="jsoneditor-sort",e.title=(0,l.Iu)("sortTitleShort"),e.onclick=function(){t.node.showSortModal()},this.menu.appendChild(e)),this.options.enableTransform&&((e=document.createElement("button")).type="button",e.title=(0,l.Iu)("transformTitleShort"),e.className="jsoneditor-transform",e.onclick=function(){t.node.showTransformModal()},this.menu.appendChild(e)),this.history&&((i=document.createElement("button")).type="button",i.className="jsoneditor-undo jsoneditor-separator",i.title=(0,l.Iu)("undo"),i.onclick=function(){t._onUndo()},this.menu.appendChild(i),this.dom.undo=i,(o=document.createElement("button")).type="button",o.className="jsoneditor-redo",o.title=(0,l.Iu)("redo"),o.onclick=function(){t._onRedo()},this.menu.appendChild(o),this.dom.redo=o,this.history.onChange=function(){i.disabled=!t.history.canUndo(),o.disabled=!t.history.canRedo()},this.history.onChange()),this.options&&this.options.modes&&this.options.modes.length&&((r=this).modeSwitcher=new d.x(this.menu,this.options.modes,this.options.mode,function(e){r.setMode(e),r.modeSwitcher.focus()})),this.options.search&&(this.searchBox=new P(this,this.menu))),this.options.navigationBar&&(this.navBar=document.createElement("div"),this.navBar.className="jsoneditor-navigation-bar nav-bar-empty",this.frame.appendChild(this.navBar),this.treePath=new F(this.navBar,this.getPopupAnchor()),this.treePath.onSectionSelected(this._onTreePathSectionSelected.bind(this)),this.treePath.onContextMenuItemSelected(this._onTreePathMenuItemSelected.bind(this)))},t._onUndo=function(){this.history&&(this.history.undo(),this._onChange())},t._onRedo=function(){this.history&&(this.history.redo(),this._onChange())},t._onEvent=function(e){if(!E.targetIsColorPicker(e.target)){var t,n=E.getNodeFromTarget(e.target);if("keydown"===e.type&&this._onKeyDown(e),n&&"focus"===e.type&&(this.focusTarget=e.target,this.options.autocomplete&&"focus"===this.options.autocomplete.trigger&&this._showAutoComplete(e.target)),"mousedown"===e.type&&this._startDragDistance(e),"mousemove"!==e.type&&"mouseup"!==e.type&&"click"!==e.type||this._updateDragDistance(e),n&&this.options&&this.options.navigationBar&&n&&("keydown"===e.type||"mousedown"===e.type)&&(t=this,setTimeout(function(){t._updateTreePath(n.getNodePath())})),n&&n.selected){if("click"===e.type){if(e.target===n.dom.menu)return void this.showContextMenu(e.target);e.hasMoved||this.deselect()}"mousedown"===e.type&&E.onDragStart(this.multiselection.nodes,e)}else"mousedown"===e.type&&(0,I.hasParentNode)(e.target,this.content)&&(this.deselect(),n&&e.target===n.dom.drag?E.onDragStart(n,e):n&&(e.target===n.dom.field||e.target===n.dom.value||e.target===n.dom.select)||this._onMultiSelectStart(e));n&&n.onEvent(e)}},t._updateTreePath=function(e){var n;function i(e){return e.parent?"array"===e.parent.type?e.index:e.field:e.field||e.type}e&&e.length?((0,I.removeClassName)(this.navBar,"nav-bar-empty"),n=[],e.forEach(function(e){var t={name:i(e),node:e,children:[]};e.childs&&e.childs.length&&e.childs.forEach(function(e){t.children.push({name:i(e),node:e})}),n.push(t)}),this.treePath.setPath(n)):(0,I.addClassName)(this.navBar,"nav-bar-empty")},t._onTreePathSectionSelected=function(e){e&&e.node&&(e.node.expandTo(),e.node.focus())},t._onTreePathMenuItemSelected=function(e,t){e&&e.children.length&&((e=e.children.find(function(e){return e.name===t}))&&e.node&&(this._updateTreePath(e.node.getNodePath()),e.node.expandTo(),e.node.focus()))},t._startDragDistance=function(e){this.dragDistanceEvent={initialTarget:e.target,initialPageX:e.pageX,initialPageY:e.pageY,dragDistance:0,hasMoved:!1}},t._updateDragDistance=function(e){this.dragDistanceEvent||this._startDragDistance(e);var t=e.pageX-this.dragDistanceEvent.initialPageX,n=e.pageY-this.dragDistanceEvent.initialPageY;return this.dragDistanceEvent.dragDistance=Math.sqrt(t*t+n*n),this.dragDistanceEvent.hasMoved=this.dragDistanceEvent.hasMoved||10<this.dragDistanceEvent.dragDistance,e.dragDistance=this.dragDistanceEvent.dragDistance,e.hasMoved=this.dragDistanceEvent.hasMoved,e.dragDistance},t._onMultiSelectStart=function(e){var t,n=E.getNodeFromTarget(e.target);"tree"===this.options.mode&&void 0===this.options.onEditable&&(this.multiselection={start:n||null,end:null,nodes:[]},this._startDragDistance(e),(t=this).mousemove||(this.mousemove=(0,I.addEventListener)(e.view,"mousemove",function(e){t._onMultiSelect(e)})),this.mouseup||(this.mouseup=(0,I.addEventListener)(e.view,"mouseup",function(e){t._onMultiSelectEnd(e)})),e.preventDefault())},t._onMultiSelect=function(e){var t;e.preventDefault(),this._updateDragDistance(e),e.hasMoved&&((t=E.getNodeFromTarget(e.target))&&(null==this.multiselection.start&&(this.multiselection.start=t),this.multiselection.end=t),this.deselect(),e=this.multiselection.start,t=this.multiselection.end||this.multiselection.start,e&&t&&(this.multiselection.nodes=this._findTopLevelNodes(e,t),this.multiselection.nodes&&this.multiselection.nodes.length&&(t=this.multiselection.nodes[0],this.multiselection.start===t||this.multiselection.start.isDescendantOf(t)?this.multiselection.direction="down":this.multiselection.direction="up"),this.select(this.multiselection.nodes)))},t._onMultiSelectEnd=function(e){this.multiselection.nodes[0]&&this.multiselection.nodes[0].dom.menu.focus(),this.multiselection.start=null,this.multiselection.end=null,this.mousemove&&((0,I.removeEventListener)(e.view,"mousemove",this.mousemove),delete this.mousemove),this.mouseup&&((0,I.removeEventListener)(e.view,"mouseup",this.mouseup),delete this.mouseup)},t.deselect=function(e){var t=!!this.multiselection.nodes.length;this.multiselection.nodes.forEach(function(e){e.setSelected(!1)}),this.multiselection.nodes=[],e&&(this.multiselection.start=null,this.multiselection.end=null),t&&this._selectionChangedHandler&&this._selectionChangedHandler()},t.select=function(e){if(!Array.isArray(e))return this.select([e]);var t;e&&(this.deselect(),this.multiselection.nodes=e.slice(0),t=e[0],e.forEach(function(e){e.expandPathToNode(),e.setSelected(!0,e===t)}),this._selectionChangedHandler&&(e=this.getSelection(),this._selectionChangedHandler(e.start,e.end)))},t._findTopLevelNodes=function(e,t){for(var n=e.getNodePath(),i=t.getNodePath(),o=0;o<n.length&&n[o]===i[o];)o++;var r=n[o-1],s=n[o],e=i[o];if(s&&e||(r.parent?r=(e=s=r).parent:(s=r.childs[0],e=r.childs[r.childs.length-1])),r&&s&&e){t=r.childs.indexOf(s),s=r.childs.indexOf(e),e=Math.min(t,s),s=Math.max(t,s);return r.childs.slice(e,s+1)}return[]},t._showAutoComplete=function(t){var n,i=E.getNodeFromTarget(t),o="";0<=t.className.indexOf("jsoneditor-value")&&(o="value"),0<=t.className.indexOf("jsoneditor-field")&&(o="field"),""!==o&&(n=this,setTimeout(function(){var e;!i||!("focus"===n.options.autocomplete.trigger||0<t.innerText.length)||null===(e=n.options.autocomplete.getOptions(t.innerText,i.getPath(),o,i.editor))?n.autocomplete.hideDropDown():"function"==typeof e.then?e.then(function(e){null===e?n.autocomplete.hideDropDown():e.options?n.autocomplete.show(t,e.startFrom,e.options):n.autocomplete.show(t,0,e)}).catch(function(e){console.error(e)}):e.options?n.autocomplete.show(t,e.startFrom,e.options):n.autocomplete.show(t,0,e)},50))},t._onKeyDown=function(e){var t,n=e.which||e.keyCode,i=e.altKey,o=e.ctrlKey,r=e.metaKey,s=e.shiftKey,a=!1,l=this.focusTarget;9===n&&(t=this,setTimeout(function(){t.focusTarget!==l&&(0,I.selectContentEditable)(t.focusTarget)},0)),this.searchBox&&(o&&70===n?(this.searchBox.dom.search.focus(),this.searchBox.dom.search.select(),a=!0):(114===n||o&&71===n)&&(s?this.searchBox.previous(!0):this.searchBox.next(!0),a=!0)),this.history&&(o&&!s&&90===n?(this._onUndo(),a=!0):o&&s&&90===n&&(this._onRedo(),a=!0)),this.options.autocomplete&&!a&&(o||i||r||1!==e.key.length&&8!==n&&46!==n||(a=!1,this._showAutoComplete(e.target))),a&&(e.preventDefault(),e.stopPropagation())},t._createTable=function(){var e;this.options.navigationBar&&(0,I.addClassName)(this.contentOuter,"has-nav-bar"),this.scrollableContent=document.createElement("div"),this.scrollableContent.className="jsoneditor-tree",this.contentOuter.appendChild(this.scrollableContent),this.content=document.createElement("div"),this.content.className="jsoneditor-tree-inner",this.scrollableContent.appendChild(this.content),this.table=document.createElement("table"),this.table.className="jsoneditor-tree",this.content.appendChild(this.table),this.colgroupContent=document.createElement("colgroup"),"tree"===this.options.mode&&((e=document.createElement("col")).width="24px",this.colgroupContent.appendChild(e)),(e=document.createElement("col")).width="24px",this.colgroupContent.appendChild(e),e=document.createElement("col"),this.colgroupContent.appendChild(e),this.table.appendChild(this.colgroupContent),this.tbody=document.createElement("tbody"),this.table.appendChild(this.tbody),this.frame.appendChild(this.contentOuter)},t.showContextMenu=function(e,t){var n,i=[],o=this.multiselection.nodes.slice();i.push({text:(0,l.Iu)("duplicateText"),title:(0,l.Iu)("duplicateTitle"),className:"jsoneditor-duplicate",click:function(){E.onDuplicate(o)}}),i.push({text:(0,l.Iu)("remove"),title:(0,l.Iu)("removeTitle"),className:"jsoneditor-remove",click:function(){E.onRemove(o)}}),this.options.onCreateMenu&&(n=o.map(function(e){return e.getPath()}),i=this.options.onCreateMenu(i,{type:"multiple",path:n[0],paths:n})),new s.x(i,{close:t}).show(e,this.getPopupAnchor())},t.getPopupAnchor=function(){return this.options.popupAnchor||this.frame},t.getSelection=function(){var e,t,n={start:null,end:null};return this.multiselection.nodes&&this.multiselection.nodes.length&&this.multiselection.nodes.length&&(e=this.multiselection.nodes[0],t=this.multiselection.nodes[this.multiselection.nodes.length-1],"down"===this.multiselection.direction?(n.start=e.serialize(),n.end=t.serialize()):(n.start=t.serialize(),n.end=e.serialize())),n},t.onSelectionChange=function(e){"function"==typeof e&&(this._selectionChangedHandler=(0,I.debounce)(e,this.DEBOUNCE_INTERVAL))},t.setSelection=function(e,t){e&&e.dom&&e.range&&(console.warn("setSelection/getSelection usage for text selection is deprecated and should not be used, see documentation for supported selection options"),this.setDomSelection(e));t=this._getNodeInstancesByRange(e,t);t.forEach(function(e){e.expandTo()}),this.select(t)},t._getNodeInstancesByRange=function(e,t){var n,i;e&&e.path&&(n=this.node.findNodeByPath(e.path),t&&t.path&&(i=this.node.findNodeByPath(t.path)));var o=[];if(n instanceof E)if(i instanceof E&&i!==n)if(n.parent===i.parent){t=n.getIndex()<i.getIndex()?(e=n,i):(e=i,n);var r=e;for(o.push(r);r=r.nextSibling(),o.push(r),r&&r!==t;);}else o=this._findTopLevelNodes(n,i);else o.push(n);return o},t.getNodesByRange=function(e,t){var t=this._getNodeInstancesByRange(e,t),n=[];return t.forEach(function(e){n.push(e.serialize())}),n};var V=[{mode:"tree",mixin:t,data:"json"},{mode:"view",mixin:t,data:"json"},{mode:"form",mixin:t,data:"json"}]},744:function(e,t,n){t.tryRequireAjv=function(){try{return n(Object(function(){var e=new Error("Cannot find module 'ajv'");throw e.code="MODULE_NOT_FOUND",e}()))}catch(e){}}},49:function(e,t,n){t.O=function(){try{n(864)}catch(e){console.error(e)}}},791:function(e,t,n){"use strict";n.r(t),n.d(t,{parse:function(){return h},tryJsonRepair:function(){return u},escapeUnicodeChars:function(){return p},validate:function(){return f},extend:function(){return m},clear:function(){return g},getType:function(){return v},isUrl:function(){return b},isArray:function(){return x},getWindow:function(){return C},getAbsoluteLeft:function(){return E},getAbsoluteTop:function(){return _},addClassName:function(){return T},removeAllClassNames:function(){return w},removeClassName:function(){return S},stripFormatting:function(){return N},setEndOfContentEditable:function(){return k},selectContentEditable:function(){return I},getSelection:function(){return j},setSelection:function(){return D},getSelectionOffset:function(){return A},setSelectionOffset:function(){return P},getInnerText:function(){return O},hasParentNode:function(){return F},getInternetExplorerVersion:function(){return M},isFirefox:function(){return B},addEventListener:function(){return L},removeEventListener:function(){return R},isChildOf:function(){return z},parsePath:function(){return H},stringifyPath:function(){return U},improveSchemaError:function(){return J},isPromise:function(){return $},isValidValidationError:function(){return q},insideRect:function(){return K},debounce:function(){return W},textDiff:function(){return Q},getInputSelection:function(){return Z},getIndexForPosition:function(){return X},getPositionForPath:function(){return G},compileJSONPointer:function(){return Y},getColorCSS:function(){return ee},isValidColor:function(){return te},makeFieldTooltip:function(){return ne},get:function(){return ie},findUniqueName:function(){return oe},getChildPaths:function(){return re},sort:function(){return se},sortObjectKeys:function(){return ae},parseString:function(){return le},isTimestamp:function(){return de},formatSize:function(){return ce},limitCharacters:function(){return he},isObject:function(){return ue},contains:function(){return pe},isValidationErrorChanged:function(){return fe}});var t=n(987),t=n(233),o=n.n(t),t=n(664),i=n.n(t),r=n(589),s=n(26),a=n(907);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)}var d=1e4,c=9466848e5;function h(t){try{return JSON.parse(t)}catch(e){throw f(t),e}}function u(t){try{return i()(t)}catch(e){return t}}function p(e){return e.replace(/[\u007F-\uFFFF]/g,function(e){return"\\u"+("0000"+e.charCodeAt(0).toString(16)).slice(-4)})}function f(e){(void 0!==r?r:JSON).parse(e)}function m(e,t){for(var n in t)me(t,n)&&(e[n]=t[n]);return e}function g(e){for(var t in e)me(e,t)&&delete e[t];return e}function v(e){return null===e?"null":void 0===e?"undefined":e instanceof Number||"number"==typeof e?"number":e instanceof String||"string"==typeof e?"string":e instanceof Boolean||"boolean"==typeof e?"boolean":e instanceof RegExp?"regexp":x(e)?"array":"object"}var y=/^https?:\/\/\S+$/;function b(e){return("string"==typeof e||e instanceof String)&&y.test(e)}function x(e){return"[object Array]"===Object.prototype.toString.call(e)}function C(e){return e.ownerDocument.defaultView}function E(e){return e.getBoundingClientRect().left+window.pageXOffset||document.scrollLeft||0}function _(e){return e.getBoundingClientRect().top+window.pageYOffset||document.scrollTop||0}function T(e,t){var n=e.className.split(" ");-1===n.indexOf(t)&&(n.push(t),e.className=n.join(" "))}function w(e){e.className=""}function S(e,t){var n=e.className.split(" "),t=n.indexOf(t);-1!==t&&(n.splice(t,1),e.className=n.join(" "))}function N(e){for(var t=e.childNodes,n=0,i=t.length;n<i;n++){var o=t[n];o.style&&o.removeAttribute("style");var r=o.attributes;if(r)for(var s=r.length-1;0<=s;s--){var a=r[s];!0===a.specified&&o.removeAttribute(a.name)}N(o)}}function k(e){var t;document.createRange&&((t=document.createRange()).selectNodeContents(e),t.collapse(!1),(e=window.getSelection()).removeAllRanges(),e.addRange(t))}function I(e){var t;e&&"DIV"===e.nodeName&&window.getSelection&&document.createRange&&((t=document.createRange()).selectNodeContents(e),(e=window.getSelection()).removeAllRanges(),e.addRange(t))}function j(){if(window.getSelection){var e=window.getSelection();if(e.getRangeAt&&e.rangeCount)return e.getRangeAt(0)}return null}function D(e){var t;e&&window.getSelection&&((t=window.getSelection()).removeAllRanges(),t.addRange(e))}function A(){var e=j();return e&&"startOffset"in e&&"endOffset"in e&&e.startContainer&&e.startContainer===e.endContainer?{startOffset:e.startOffset,endOffset:e.endOffset,container:e.startContainer.parentNode}:null}function P(e){var t;document.createRange&&window.getSelection&&window.getSelection()&&(t=document.createRange(),e.container.firstChild||e.container.appendChild(document.createTextNode("")),t.setStart(e.container.firstChild,e.startOffset),t.setEnd(e.container.firstChild,e.endOffset),D(t))}function O(e,t){if(void 0===t&&(t={_text:"",flush:function(){var e=this._text;return this._text="",e},set:function(e){this._text=e}}),e.nodeValue){var n=e.nodeValue.replace(/\s*\n\s*/g,"");return""!==n?t.flush()+n:""}if(e.hasChildNodes()){for(var i=e.childNodes,o="",r=0,s=i.length;r<s;r++){var a,l=i[r];"DIV"===l.nodeName||"P"===l.nodeName?((a=(a=i[r-1])?a.nodeName:void 0)&&"DIV"!==a&&"P"!==a&&"BR"!==a&&(""!==o&&(o+="\n"),t.flush()),o+=O(l,t),t.set("\n")):"BR"===l.nodeName?(o+=t.flush(),t.set("\n")):o+=O(l,t)}return o}return""}function F(e,t){for(var n=e?e.parentNode:void 0;n;){if(n===t)return!0;n=n.parentNode}return!1}function M(){var e;return-1===V&&(e=-1,"undefined"!=typeof navigator&&"Microsoft Internet Explorer"===navigator.appName&&(null!=/MSIE ([0-9]+[.0-9]+)/.exec(navigator.userAgent)&&(e=parseFloat(RegExp.$1))),V=e),V}var V=-1;function B(){return"undefined"!=typeof navigator&&-1!==navigator.userAgent.indexOf("Firefox")}function L(e,t,n,i){if(e.addEventListener)return void 0===i&&(i=!1),"mousewheel"===t&&B()&&(t="DOMMouseScroll"),e.addEventListener(t,n,i),n;if(e.attachEvent){i=function(){return n.call(e,window.event)};return e.attachEvent("on"+t,i),i}}function R(e,t,n,i){e.removeEventListener?(void 0===i&&(i=!1),"mousewheel"===t&&B()&&(t="DOMMouseScroll"),e.removeEventListener(t,n,i)):e.detachEvent&&e.detachEvent("on"+t,n)}function z(e,t){for(var n=e.parentNode;n;){if(n===t)return!0;n=n.parentNode}return!1}function H(n){var e=[],i=0;function t(e){for(var t="";void 0!==n[i]&&n[i]!==e;)t+=n[i],i++;if(n[i]!==e)throw new Error("Invalid JSON path: unexpected end, character "+e+" expected");return t}for(;void 0!==n[i];)if("."===n[i])i++,e.push(function(){for(var e="";void 0!==n[i]&&/[\w$]/.test(n[i]);)e+=n[i],i++;if(""===e)throw new Error("Invalid JSON path: property name expected at index "+i);return e}());else{if("["!==n[i])throw new Error('Invalid JSON path: unexpected character "'+n[i]+'" at index '+i);if("'"===n[++i]||'"'===n[i]){var o=n[i];if(i++,e.push(t(o)),n[i]!==o)throw new Error("Invalid JSON path: closing quote ' expected at index "+i);i++}else{o=t("]").trim();if(0===o.length)throw new Error("Invalid JSON path: array value expected at index "+i);o="*"===o?o:JSON.parse(o),e.push(o)}if("]"!==n[i])throw new Error("Invalid JSON path: closing bracket ] expected at index "+i);i++}return e}function U(e){return e.map(function(e){return"number"==typeof e?"["+e+"]":"string"==typeof e&&e.match(/^[A-Za-z0-9_$]+$/)?"."+e:'["'+e+'"]'}).join("")}function J(e){var t,n;return"enum"!==e.keyword||!Array.isArray(e.schema)||(n=e.schema)&&(5<(n=n.map(function(e){return JSON.stringify(e)})).length&&(t=["("+(n.length-5)+" more...)"],(n=n.slice(0,5)).push(t)),e.message="should be equal to one of: "+n.join(", ")),"additionalProperties"===e.keyword&&(e.message="should NOT have additional property: "+e.params.additionalProperty),e}function $(e){return e&&"function"==typeof e.then&&"function"==typeof e.catch}function q(e){return"object"===l(e)&&Array.isArray(e.path)&&"string"==typeof e.message}function K(e,t,n){n=void 0!==n?n:0;return t.left-n>=e.left&&t.right+n<=e.right&&t.top-n>=e.top&&t.bottom+n<=e.bottom}function W(i,o,r){var s;return function(){var e=this,t=arguments,n=r&&!s;clearTimeout(s),s=setTimeout(function(){s=null,r||i.apply(e,t)},o),n&&i.apply(e,t)}}function Q(e,t){for(var n=t.length,i=0,o=e.length,r=t.length;t.charAt(i)===e.charAt(i)&&i<n;)i++;for(;t.charAt(r-1)===e.charAt(o-1)&&i<r&&0<o;)r--,o--;return{start:i,end:r}}function Z(t){var e,n,i,o,r=0,s=0;return"number"==typeof t.selectionStart&&"number"==typeof t.selectionEnd?(r=t.selectionStart,s=t.selectionEnd):(o=document.selection.createRange())&&o.parentElement()===t&&(i=t.value.length,e=t.value.replace(/\r\n/g,"\n"),(n=t.createTextRange()).moveToBookmark(o.getBookmark()),(o=t.createTextRange()).collapse(!1),-1<n.compareEndPoints("StartToEnd",o)?r=s=i:(r=-n.moveStart("character",-i),r+=e.slice(0,r).split("\n").length-1,-1<n.compareEndPoints("EndToEnd",o)?s=i:(s=-n.moveEnd("character",-i),s+=e.slice(0,s).split("\n").length-1))),{startIndex:r,endIndex:s,start:a(r),end:a(s)};function a(e){e=t.value.substring(0,e);return{row:(e.match(/\n/g)||[]).length+1,column:e.length-e.lastIndexOf("\n")}}}function X(e,t,n){e=e.value||"";if(0<t&&0<n){e=e.split("\n",t);t=Math.min(e.length,t),n=Math.min(e[t-1].length,n-1);n=1===t?n:n+1;return e.slice(0,t-1).join("\n").length+n}return-1}function G(e,t){var n,i=[];if(!t||!t.length)return i;try{n=s.Q(e)}catch(e){return i}return t.forEach(function(e){var t=Y(H(e)),t=n.pointers[t];t&&i.push({path:e,line:t.key?t.key.line:t.value?t.value.line:0,column:t.key?t.key.column:t.value?t.value.column:0})}),i}function Y(e){return e.map(function(e){return"/"+String(e).replace(/~/g,"~0").replace(/\//g,"~1")}).join("")}function ee(e){var t=document.createElement("div");return t.style.color=e,t.style.color.split(/\s+/).join("").toLowerCase()||null}function te(e){return!!ee(e)}function ne(n,e){if(!n)return"";var i="";return n.title&&(i+=n.title),n.description&&(0<i.length&&(i+="\n"),i+=n.description),n.default&&(0<i.length&&(i+="\n\n"),i+=(0,a.Iu)("default",void 0,e)+"\n",i+=JSON.stringify(n.default,null,2)),Array.isArray(n.examples)&&0<n.examples.length&&(0<i.length&&(i+="\n\n"),i+=(0,a.Iu)("examples",void 0,e)+"\n",n.examples.forEach(function(e,t){i+=JSON.stringify(e,null,2),t!==n.examples.length-1&&(i+="\n")})),i}function ie(e,t){for(var n=e,i=0;i<t.length&&null!=n;i++)n=n[t[i]];return n}function oe(e,t){for(var n=e.replace(/ \(copy( \d+)?\)$/,""),i=n,o=1;-1!==t.indexOf(i);){i=n+" ("+("copy"+(1<o?" "+o:""))+")";o++}return i}function re(e,t){var n={};if(Array.isArray(e))for(var i=Math.min(e.length,d),o=0;o<i;o++)!function t(n,i,o,r){(Array.isArray(n)||ue(n))&&!r||(i[o||""]=!0),ue(n)&&Object.keys(n).forEach(function(e){t(n[e],i,o+"."+e,r)})}(e[o],n,"",t);else n[""]=!0;return Object.keys(n).sort()}function se(e,t,n){var i=t&&"."!==t?H(t):[],o="desc"===n?-1:1,e=e.slice();return e.sort(function(e,t){e=ie(e,i),t=ie(t,i);return o*(t<e?1:e<t?-1:0)}),e}function ae(t,e){var n="desc"===e?-1:1,e=Object.keys(t).sort(function(e,t){return n*o()(e,t)}),i={};return e.forEach(function(e){i[e]=t[e]}),i}function le(e){if(""===e)return"";var t=e.toLowerCase();if("null"===t)return null;if("true"===t)return!0;if("false"===t)return!1;var n=Number(e),t=parseFloat(e);return isNaN(n)||isNaN(t)?e:n}function de(e,t){return"number"==typeof t&&c<t&&isFinite(t)&&Math.floor(t)===t&&!isNaN(new Date(t).valueOf())}function ce(e){if(e<900)return e.toFixed()+" B";e/=1e3;if(e<900)return e.toFixed(1)+" KB";e/=1e3;if(e<900)return e.toFixed(1)+" MB";e/=1e3;return e<900?e.toFixed(1)+" GB":(e/1e3).toFixed(1)+" TB"}function he(e,t){return e.length<=t?e:e.slice(0,t)+"..."}function ue(e){return"object"===l(e)&&null!==e&&!Array.isArray(e)}function pe(e,t){return-1!==e.indexOf(t)}function fe(n,e){if(!e&&!n)return!1;if(e&&!n||!e&&n)return!0;if(e.length!==n.length)return!0;for(var t=0;t<n.length;++t){var i=function(t){if(!("error"===n[t].type?e.find(function(e){return e.line===n[t].line}):e.find(function(e){return e.dataPath===n[t].dataPath&&e.schemaPath===n[t].schemaPath})))return{v:!0}}(t);if("object"===l(i))return i.v}return!1}function me(e,t){return Object.prototype.hasOwnProperty.call(e,t)}},37:function(e,t,n){var i;if(window.Picker)i=window.Picker;else try{i=n(Object(function(){var e=new Error("Cannot find module 'vanilla-picker'");throw e.code="MODULE_NOT_FOUND",e}()))}catch(e){}e.exports=i},233:function(e){e.exports=function t(e,n){"use strict";function i(e){return t.insensitive&&(""+e).toLowerCase()||""+e}var o,r,s=/(^([+\-]?(?:0|[1-9]\d*)(?:\.\d*)?(?:[eE][+\-]?\d+)?)?$|^0x[0-9a-f]+$|\d+)/gi,a=/(^[ ]*|[ ]*$)/g,l=/(^([\w ]+,?[\w ]+)?[\w ]+,?[\w ]+\d+:\d+(:\d+)?[\w ]?|^\d{1,4}[\/\-]\d{1,4}[\/\-]\d{1,4}|^\w+, \w+ \d+, \d{4})/,d=/^0x[0-9a-f]+$/i,c=/^0/,e=i(e).replace(a,"")||"",a=i(n).replace(a,"")||"",h=e.replace(s,"\0$1\0").replace(/\0$/,"").replace(/^\0/,"").split("\0"),u=a.replace(s,"\0$1\0").replace(/\0$/,"").replace(/^\0/,"").split("\0"),e=parseInt(e.match(d),16)||1!==h.length&&e.match(l)&&Date.parse(e),a=parseInt(a.match(d),16)||e&&a.match(l)&&Date.parse(a)||null;if(a){if(e<a)return-1;if(a<e)return 1}for(var p=0,f=Math.max(h.length,u.length);p<f;p++){if(o=!(h[p]||"").match(c)&&parseFloat(h[p])||h[p]||0,r=!(u[p]||"").match(c)&&parseFloat(u[p])||u[p]||0,isNaN(o)!==isNaN(r))return isNaN(o)?1:-1;if(typeof o!=typeof r&&(o+="",r+=""),o<r)return-1;if(r<o)return 1}return 0}},156:function(e,t){!function(e){"use strict";function _(e){return null!==e&&"[object Array]"===Object.prototype.toString.call(e)}function T(e){return null!==e&&"[object Object]"===Object.prototype.toString.call(e)}function w(e,t){if(e===t)return!0;if(Object.prototype.toString.call(e)!==Object.prototype.toString.call(t))return!1;if(!0===_(e)){if(e.length!==t.length)return!1;for(var n=0;n<e.length;n++)if(!1===w(e[n],t[n]))return!1;return!0}if(!0!==T(e))return!1;var i,o,r={};for(i in e)if(hasOwnProperty.call(e,i)){if(!1===w(e[i],t[i]))return!1;r[i]=!0}for(o in t)if(hasOwnProperty.call(t,o)&&!0!==r[o])return!1;return!0}function S(e){if(""===e||!1===e||null===e)return!0;if(_(e)&&0===e.length)return!0;if(T(e)){for(var t in e)if(e.hasOwnProperty(t))return!1;return!0}return!1}var o="function"==typeof String.prototype.trimLeft?function(e){return e.trimLeft()}:function(e){return e.match(/^\s*(.*)/)[1]},d=0,r=1,c=2,s=3,t=4,n=6,a=8,l=9,h="UnquotedIdentifier",u="QuotedIdentifier",p="Rbracket",f="Rparen",m="Comma",g="Colon",i="Rbrace",v="Number",N="Current",k="Expref",I="Pipe",j="GTE",D="LTE",A="Flatten",y="Star",b="Filter",x="Dot",C="Lbrace",E="Lbracket",P="Lparen",O="Literal",F={".":x,"*":y,",":m,":":g,"{":C,"}":i,"]":p,"(":P,")":f,"@":N},M={"<":!0,">":!0,"=":!0,"!":!0},V={" ":!0,"\t":!0,"\n":!0};function B(e){return"0"<=e&&e<="9"||"-"===e}function L(){}L.prototype={tokenize:function(e){var t,n,i,o,r=[];for(this._current=0;this._current<e.length;)if("a"<=(o=e[this._current])&&o<="z"||"A"<=o&&o<="Z"||"_"===o)t=this._current,n=this._consumeUnquotedIdentifier(e),r.push({type:h,value:n,start:t});else if(void 0!==F[e[this._current]])r.push({type:F[e[this._current]],value:e[this._current],start:this._current}),this._current++;else if(B(e[this._current]))i=this._consumeNumber(e),r.push(i);else if("["===e[this._current])i=this._consumeLBracket(e),r.push(i);else if('"'===e[this._current])t=this._current,n=this._consumeQuotedIdentifier(e),r.push({type:u,value:n,start:t});else if("'"===e[this._current])t=this._current,n=this._consumeRawStringLiteral(e),r.push({type:O,value:n,start:t});else if("`"===e[this._current]){t=this._current;var s=this._consumeLiteral(e);r.push({type:O,value:s,start:t})}else if(void 0!==M[e[this._current]])r.push(this._consumeOperator(e));else if(void 0!==V[e[this._current]])this._current++;else if("&"===e[this._current])t=this._current,this._current++,"&"===e[this._current]?(this._current++,r.push({type:"And",value:"&&",start:t})):r.push({type:k,value:"&",start:t});else{if("|"!==e[this._current]){s=new Error("Unknown character:"+e[this._current]);throw s.name="LexerError",s}t=this._current,this._current++,"|"===e[this._current]?(this._current++,r.push({type:"Or",value:"||",start:t})):r.push({type:I,value:"|",start:t})}return r},_consumeUnquotedIdentifier:function(e){var t,n=this._current;for(this._current++;this._current<e.length&&("a"<=(t=e[this._current])&&t<="z"||"A"<=t&&t<="Z"||"0"<=t&&t<="9"||"_"===t);)this._current++;return e.slice(n,this._current)},_consumeQuotedIdentifier:function(e){var t=this._current;this._current++;for(var n=e.length;'"'!==e[this._current]&&this._current<n;){var i=this._current;"\\"!==e[i]||"\\"!==e[i+1]&&'"'!==e[i+1]?i++:i+=2,this._current=i}return this._current++,JSON.parse(e.slice(t,this._current))},_consumeRawStringLiteral:function(e){var t=this._current;this._current++;for(var n=e.length;"'"!==e[this._current]&&this._current<n;){var i=this._current;"\\"!==e[i]||"\\"!==e[i+1]&&"'"!==e[i+1]?i++:i+=2,this._current=i}return this._current++,e.slice(t+1,this._current-1).replace("\\'","'")},_consumeNumber:function(e){var t=this._current;this._current++;for(var n=e.length;B(e[this._current])&&this._current<n;)this._current++;var i=parseInt(e.slice(t,this._current));return{type:v,value:i,start:t}},_consumeLBracket:function(e){var t=this._current;return this._current++,"?"===e[this._current]?(this._current++,{type:b,value:"[?",start:t}):"]"===e[this._current]?(this._current++,{type:A,value:"[]",start:t}):{type:E,value:"[",start:t}},_consumeOperator:function(e){var t=this._current,n=e[t];return this._current++,"!"===n?"="===e[this._current]?(this._current++,{type:"NE",value:"!=",start:t}):{type:"Not",value:"!",start:t}:"<"===n?"="===e[this._current]?(this._current++,{type:D,value:"<=",start:t}):{type:"LT",value:"<",start:t}:">"===n?"="===e[this._current]?(this._current++,{type:j,value:">=",start:t}):{type:"GT",value:">",start:t}:"="===n&&"="===e[this._current]?(this._current++,{type:"EQ",value:"==",start:t}):void 0},_consumeLiteral:function(e){this._current++;for(var t=this._current,n=e.length;"`"!==e[this._current]&&this._current<n;){var i=this._current;"\\"!==e[i]||"\\"!==e[i+1]&&"`"!==e[i+1]?i++:i+=2,this._current=i}var t=(t=o(e.slice(t,this._current))).replace("\\`","`"),t=this._looksLikeJSON(t)?JSON.parse(t):JSON.parse('"'+t+'"');return this._current++,t},_looksLikeJSON:function(e){if(""===e)return!1;if(0<='[{"'.indexOf(e[0]))return!0;if(0<=["true","false","null"].indexOf(e))return!0;if(!(0<="-0123456789".indexOf(e[0])))return!1;try{return JSON.parse(e),!0}catch(e){return!1}}};var R={};function z(){}function H(e){this.runtime=e}function U(e){this._interpreter=e,this.functionTable={abs:{_func:this._functionAbs,_signature:[{types:[d]}]},avg:{_func:this._functionAvg,_signature:[{types:[a]}]},ceil:{_func:this._functionCeil,_signature:[{types:[d]}]},contains:{_func:this._functionContains,_signature:[{types:[c,s]},{types:[r]}]},ends_with:{_func:this._functionEndsWith,_signature:[{types:[c]},{types:[c]}]},floor:{_func:this._functionFloor,_signature:[{types:[d]}]},length:{_func:this._functionLength,_signature:[{types:[c,s,t]}]},map:{_func:this._functionMap,_signature:[{types:[n]},{types:[s]}]},max:{_func:this._functionMax,_signature:[{types:[a,l]}]},merge:{_func:this._functionMerge,_signature:[{types:[t],variadic:!0}]},max_by:{_func:this._functionMaxBy,_signature:[{types:[s]},{types:[n]}]},sum:{_func:this._functionSum,_signature:[{types:[a]}]},starts_with:{_func:this._functionStartsWith,_signature:[{types:[c]},{types:[c]}]},min:{_func:this._functionMin,_signature:[{types:[a,l]}]},min_by:{_func:this._functionMinBy,_signature:[{types:[s]},{types:[n]}]},type:{_func:this._functionType,_signature:[{types:[r]}]},keys:{_func:this._functionKeys,_signature:[{types:[t]}]},values:{_func:this._functionValues,_signature:[{types:[t]}]},sort:{_func:this._functionSort,_signature:[{types:[l,a]}]},sort_by:{_func:this._functionSortBy,_signature:[{types:[s]},{types:[n]}]},join:{_func:this._functionJoin,_signature:[{types:[c]},{types:[l]}]},reverse:{_func:this._functionReverse,_signature:[{types:[c,s]}]},to_array:{_func:this._functionToArray,_signature:[{types:[r]}]},to_string:{_func:this._functionToString,_signature:[{types:[r]}]},to_number:{_func:this._functionToNumber,_signature:[{types:[r]}]},not_null:{_func:this._functionNotNull,_signature:[{types:[r],variadic:!0}]}}}R.EOF=0,R[h]=0,R[u]=0,R[p]=0,R[f]=0,R[m]=0,R[i]=0,R[v]=0,R[N]=0,R[k]=0,R[I]=1,R.Or=2,R.And=3,R.EQ=5,R.GT=5,R.LT=5,R.GTE=5,R.LTE=5,R.NE=5,R[A]=9,R[y]=20,R[b]=21,R.Dot=40,R.Not=45,R[C]=50,R[E]=55,R[P]=60,z.prototype={parse:function(e){this._loadTokens(e),this.index=0;e=this.expression(0);if("EOF"===this._lookahead(0))return e;e=this._lookaheadToken(0),e=new Error("Unexpected token type: "+e.type+", value: "+e.value);throw e.name="ParserError",e},_loadTokens:function(e){var t=(new L).tokenize(e);t.push({type:"EOF",value:"",start:e.length}),this.tokens=t},expression:function(e){var t=this._lookaheadToken(0);this._advance();for(var n=this.nud(t),i=this._lookahead(0);e<R[i];)this._advance(),n=this.led(i,n),i=this._lookahead(0);return n},_lookahead:function(e){return this.tokens[this.index+e].type},_lookaheadToken:function(e){return this.tokens[this.index+e]},_advance:function(){this.index++},nud:function(e){var t,n;switch(e.type){case O:return{type:"Literal",value:e.value};case h:return{type:"Field",name:e.value};case u:var i={type:"Field",name:e.value};if(this._lookahead(0)===P)throw new Error("Quoted identifier not allowed for function names.");return i;case"Not":return{type:"NotExpression",children:[t=this.expression(R.Not)]};case y:return t=null,{type:"ValueProjection",children:[{type:"Identity"},t=this._lookahead(0)===p?{type:"Identity"}:this._parseProjectionRHS(R.Star)]};case b:return this.led(e.type,{type:"Identity"});case C:return this._parseMultiselectHash();case A:return{type:"Projection",children:[{type:A,children:[{type:"Identity"}]},t=this._parseProjectionRHS(R.Flatten)]};case E:return this._lookahead(0)===v||this._lookahead(0)===g?(t=this._parseIndexExpression(),this._projectIfSlice({type:"Identity"},t)):this._lookahead(0)===y&&this._lookahead(1)===p?(this._advance(),this._advance(),{type:"Projection",children:[{type:"Identity"},t=this._parseProjectionRHS(R.Star)]}):this._parseMultiselectList();case N:return{type:N};case k:return{type:"ExpressionReference",children:[n=this.expression(R.Expref)]};case P:for(var o=[];this._lookahead(0)!==f;)this._lookahead(0)===N?(n={type:N},this._advance()):n=this.expression(0),o.push(n);return this._match(f),o[0];default:this._errorToken(e)}},led:function(e,t){var n;switch(e){case x:var i=R.Dot;return this._lookahead(0)!==y?{type:"Subexpression",children:[t,n=this._parseDotRHS(i)]}:(this._advance(),{type:"ValueProjection",children:[t,n=this._parseProjectionRHS(i)]});case I:return n=this.expression(R.Pipe),{type:I,children:[t,n]};case"Or":return{type:"OrExpression",children:[t,n=this.expression(R.Or)]};case"And":return{type:"AndExpression",children:[t,n=this.expression(R.And)]};case P:for(var o,i=t.name,r=[];this._lookahead(0)!==f;)this._lookahead(0)===N?(o={type:N},this._advance()):o=this.expression(0),this._lookahead(0)===m&&this._match(m),r.push(o);return this._match(f),{type:"Function",name:i,children:r};case b:var s=this.expression(0);return this._match(p),{type:"FilterProjection",children:[t,n=this._lookahead(0)===A?{type:"Identity"}:this._parseProjectionRHS(R.Filter),s]};case A:return{type:"Projection",children:[{type:A,children:[t]},this._parseProjectionRHS(R.Flatten)]};case"EQ":case"NE":case"GT":case j:case"LT":case D:return this._parseComparator(t,e);case E:s=this._lookaheadToken(0);return s.type===v||s.type===g?(n=this._parseIndexExpression(),this._projectIfSlice(t,n)):(this._match(y),this._match(p),{type:"Projection",children:[t,n=this._parseProjectionRHS(R.Star)]});default:this._errorToken(this._lookaheadToken(0))}},_match:function(e){if(this._lookahead(0)!==e){var t=this._lookaheadToken(0),t=new Error("Expected "+e+", got: "+t.type);throw t.name="ParserError",t}this._advance()},_errorToken:function(e){e=new Error("Invalid token ("+e.type+'): "'+e.value+'"');throw e.name="ParserError",e},_parseIndexExpression:function(){if(this._lookahead(0)===g||this._lookahead(1)===g)return this._parseSliceExpression();var e={type:"Index",value:this._lookaheadToken(0).value};return this._advance(),this._match(p),e},_projectIfSlice:function(e,t){e={type:"IndexExpression",children:[e,t]};return"Slice"===t.type?{type:"Projection",children:[e,this._parseProjectionRHS(R.Star)]}:e},_parseSliceExpression:function(){for(var e=[null,null,null],t=0,n=this._lookahead(0);n!==p&&t<3;){if(n===g)t++,this._advance();else{if(n!==v){var i=this._lookahead(0),i=new Error("Syntax error, unexpected token: "+i.value+"("+i.type+")");throw i.name="Parsererror",i}e[t]=this._lookaheadToken(0).value,this._advance()}n=this._lookahead(0)}return this._match(p),{type:"Slice",children:e}},_parseComparator:function(e,t){return{type:"Comparator",name:t,children:[e,this.expression(R[t])]}},_parseDotRHS:function(e){var t=this._lookahead(0);return 0<=[h,u,y].indexOf(t)?this.expression(e):t===E?(this._match(E),this._parseMultiselectList()):t===C?(this._match(C),this._parseMultiselectHash()):void 0},_parseProjectionRHS:function(e){var t;if(R[this._lookahead(0)]<10)t={type:"Identity"};else if(this._lookahead(0)===E)t=this.expression(e);else if(this._lookahead(0)===b)t=this.expression(e);else{if(this._lookahead(0)!==x){var n=this._lookaheadToken(0),n=new Error("Sytanx error, unexpected token: "+n.value+"("+n.type+")");throw n.name="ParserError",n}this._match(x),t=this._parseDotRHS(e)}return t},_parseMultiselectList:function(){for(var e=[];this._lookahead(0)!==p;){var t=this.expression(0);if(e.push(t),this._lookahead(0)===m&&(this._match(m),this._lookahead(0)===p))throw new Error("Unexpected token Rbracket")}return this._match(p),{type:"MultiSelectList",children:e}},_parseMultiselectHash:function(){for(var e,t=[],n=[h,u];;){if(e=this._lookaheadToken(0),n.indexOf(e.type)<0)throw new Error("Expecting an identifier token, got: "+e.type);if(e=e.value,this._advance(),this._match(g),e={type:"KeyValuePair",name:e,value:this.expression(0)},t.push(e),this._lookahead(0)===m)this._match(m);else if(this._lookahead(0)===i){this._match(i);break}}return{type:"MultiSelectHash",children:t}}},H.prototype={search:function(e,t){return this.visit(e,t)},visit:function(e,t){var n,i,o,r;switch(e.type){case"Field":return null===t||!T(t)||void 0===(a=t[e.name])?null:a;case"Subexpression":for(c=this.visit(e.children[0],t),p=1;p<e.children.length;p++)if(null===(c=this.visit(e.children[1],c)))return null;return c;case"IndexExpression":return E=this.visit(e.children[0],t),this.visit(e.children[1],E);case"Index":if(!_(t))return null;var s=e.value;return s<0&&(s=t.length+s),void 0===(c=t[s])&&(c=null),c;case"Slice":if(!_(t))return null;var a=e.children.slice(0),s=this.computeSliceParams(t.length,a),a=s[0],l=s[1],d=s[2],c=[];if(0<d)for(p=a;p<l;p+=d)c.push(t[p]);else for(p=a;l<p;p+=d)c.push(t[p]);return c;case"Projection":var h=this.visit(e.children[0],t);if(!_(h))return null;for(x=[],p=0;p<h.length;p++)null!==(i=this.visit(e.children[1],h[p]))&&x.push(i);return x;case"ValueProjection":if(!T(h=this.visit(e.children[0],t)))return null;x=[];for(var u=function(e){for(var t=Object.keys(e),n=[],i=0;i<t.length;i++)n.push(e[t[i]]);return n}(h),p=0;p<u.length;p++)null!==(i=this.visit(e.children[1],u[p]))&&x.push(i);return x;case"FilterProjection":if(!_(h=this.visit(e.children[0],t)))return null;var f=[],m=[];for(p=0;p<h.length;p++)S(n=this.visit(e.children[2],h[p]))||f.push(h[p]);for(var g=0;g<f.length;g++)null!==(i=this.visit(e.children[1],f[g]))&&m.push(i);return m;case"Comparator":switch(o=this.visit(e.children[0],t),r=this.visit(e.children[1],t),e.name){case"EQ":c=w(o,r);break;case"NE":c=!w(o,r);break;case"GT":c=r<o;break;case j:c=r<=o;break;case"LT":c=o<r;break;case D:c=o<=r;break;default:throw new Error("Unknown comparator: "+e.name)}return c;case A:var v=this.visit(e.children[0],t);if(!_(v))return null;var y=[];for(p=0;p<v.length;p++)_(i=v[p])?y.push.apply(y,i):y.push(i);return y;case"Identity":return t;case"MultiSelectList":if(null===t)return null;for(x=[],p=0;p<e.children.length;p++)x.push(this.visit(e.children[p],t));return x;case"MultiSelectHash":if(null===t)return null;var b,x={};for(p=0;p<e.children.length;p++)x[(b=e.children[p]).name]=this.visit(b.value,t);return x;case"OrExpression":return S(n=this.visit(e.children[0],t))&&(n=this.visit(e.children[1],t)),n;case"AndExpression":return!0===S(o=this.visit(e.children[0],t))?o:this.visit(e.children[1],t);case"NotExpression":return S(o=this.visit(e.children[0],t));case"Literal":return e.value;case I:return E=this.visit(e.children[0],t),this.visit(e.children[1],E);case N:return t;case"Function":var C=[];for(p=0;p<e.children.length;p++)C.push(this.visit(e.children[p],t));return this.runtime.callFunction(e.name,C);case"ExpressionReference":var E=e.children[0];return E.jmespathType=k,E;default:throw new Error("Unknown node type: "+e.type)}},computeSliceParams:function(e,t){var n=t[0],i=t[1],o=t[2],t=[null,null,null];if(null===o)o=1;else if(0===o){var r=new Error("Invalid slice, step cannot be 0");throw r.name="RuntimeError",r}r=o<0,n=null===n?r?e-1:0:this.capSliceRange(e,n,o),i=null===i?r?-1:e:this.capSliceRange(e,i,o);return t[0]=n,t[1]=i,t[2]=o,t},capSliceRange:function(e,t,n){return t<0?(t+=e)<0&&(t=n<0?-1:0):e<=t&&(t=n<0?e-1:e),t}},U.prototype={callFunction:function(e,t){var n=this.functionTable[e];if(void 0===n)throw new Error("Unknown function: "+e+"()");return this._validateArgs(e,t,n._signature),n._func.call(this,t)},_validateArgs:function(e,t,n){var i,o,r,s;if(n[n.length-1].variadic){if(t.length<n.length )throw i=1===n.length?" argument":" arguments",new Error("ArgumentError: "+e+"() takes at least"+n.length+i+" but received "+t.length)}else if(t.length!==n.length)throw i=1===n.length?" argument":" arguments",new Error("ArgumentError: "+e+"() takes "+n.length+i+" but received "+t.length);for(var a=0;a<n.length;a++){s=!1,o=n[a].types,r=this._getTypeName(t[a]);for(var l=0;l<o.length;l++)if(this._typeMatches(r,o[l],t[a])){s=!0;break}if(!s)throw new Error("TypeError: "+e+"() expected argument "+(a+1)+" to be type "+o+" but received type "+r+" instead.")}},_typeMatches:function(e,t,n){if(t===r)return!0;if(t!==l&&t!==a&&t!==s)return e===t;if(t===s)return e===s;if(e===s){var i;t===a?i=d:t===l&&(i=c);for(var o=0;o<n.length;o++)if(!this._typeMatches(this._getTypeName(n[o]),i,n[o]))return!1;return!0}},_getTypeName:function(e){switch(Object.prototype.toString.call(e)){case"[object String]":return c;case"[object Number]":return d;case"[object Array]":return s;case"[object Boolean]":return 5;case"[object Null]":return 7;case"[object Object]":return e.jmespathType===k?n:t}},_functionStartsWith:function(e){return 0===e[0].lastIndexOf(e[1])},_functionEndsWith:function(e){var t=e[0],e=e[1];return-1!==t.indexOf(e,t.length-e.length)},_functionReverse:function(e){if(this._getTypeName(e[0])===c){for(var t=e[0],n="",i=t.length-1;0<=i;i--)n+=t[i];return n}e=e[0].slice(0);return e.reverse(),e},_functionAbs:function(e){return Math.abs(e[0])},_functionCeil:function(e){return Math.ceil(e[0])},_functionAvg:function(e){for(var t=0,n=e[0],i=0;i<n.length;i++)t+=n[i];return t/n.length},_functionContains:function(e){return 0<=e[0].indexOf(e[1])},_functionFloor:function(e){return Math.floor(e[0])},_functionLength:function(e){return(T(e[0])?Object.keys(e[0]):e[0]).length},_functionMap:function(e){for(var t=[],n=this._interpreter,i=e[0],o=e[1],r=0;r<o.length;r++)t.push(n.visit(i,o[r]));return t},_functionMerge:function(e){for(var t={},n=0;n<e.length;n++){var i,o=e[n];for(i in o)t[i]=o[i]}return t},_functionMax:function(e){if(0<e[0].length){if(this._getTypeName(e[0][0])===d)return Math.max.apply(Math,e[0]);for(var t=e[0],n=t[0],i=1;i<t.length;i++)n.localeCompare(t[i])<0&&(n=t[i]);return n}return null},_functionMin:function(e){if(0<e[0].length){if(this._getTypeName(e[0][0])===d)return Math.min.apply(Math,e[0]);for(var t=e[0],n=t[0],i=1;i<t.length;i++)t[i].localeCompare(n)<0&&(n=t[i]);return n}return null},_functionSum:function(e){for(var t=0,n=e[0],i=0;i<n.length;i++)t+=n[i];return t},_functionType:function(e){switch(this._getTypeName(e[0])){case d:return"number";case c:return"string";case s:return"array";case t:return"object";case 5:return"boolean";case n:return"expref";case 7:return"null"}},_functionKeys:function(e){return Object.keys(e[0])},_functionValues:function(e){for(var t=e[0],n=Object.keys(t),i=[],o=0;o<n.length;o++)i.push(t[n[o]]);return i},_functionJoin:function(e){var t=e[0];return e[1].join(t)},_functionToArray:function(e){return this._getTypeName(e[0])===s?e[0]:[e[0]]},_functionToString:function(e){return this._getTypeName(e[0])===c?e[0]:JSON.stringify(e[0])},_functionToNumber:function(e){var t,n=this._getTypeName(e[0]);return n===d?e[0]:n!==c||(t=+e[0],isNaN(t))?null:t},_functionNotNull:function(e){for(var t=0;t<e.length;t++)if(7!==this._getTypeName(e[t]))return e[t];return null},_functionSort:function(e){e=e[0].slice(0);return e.sort(),e},_functionSortBy:function(e){var t=e[0].slice(0);if(0===t.length)return t;var o=this._interpreter,r=e[1],s=this._getTypeName(o.visit(r,t[0]));if([d,c].indexOf(s)<0)throw new Error("TypeError");for(var a=this,n=[],i=0;i<t.length;i++)n.push([i,t[i]]);n.sort(function(e,t){var n=o.visit(r,e[1]),i=o.visit(r,t[1]);if(a._getTypeName(n)!==s)throw new Error("TypeError: expected "+s+", received "+a._getTypeName(n));if(a._getTypeName(i)!==s)throw new Error("TypeError: expected "+s+", received "+a._getTypeName(i));return i<n?1:n<i?-1:e[0]-t[0]});for(var l=0;l<n.length;l++)t[l]=n[l][1];return t},_functionMaxBy:function(e){for(var t,n,i=e[1],o=e[0],r=this.createKeyFunction(i,[d,c]),s=-1/0,a=0;a<o.length;a++)s<(n=r(o[a]))&&(s=n,t=o[a]);return t},_functionMinBy:function(e){for(var t,n,i=e[1],o=e[0],r=this.createKeyFunction(i,[d,c]),s=1/0,a=0;a<o.length;a++)(n=r(o[a]))<s&&(s=n,t=o[a]);return t},createKeyFunction:function(n,i){var o=this,r=this._interpreter;return function(e){var t=r.visit(n,e);if(i.indexOf(o._getTypeName(t))<0){e="TypeError: expected one of "+i+", received "+o._getTypeName(t);throw new Error(e)}return t}}},e.tokenize=function(e){return(new L).tokenize(e)},e.compile=function(e){return(new z).parse(e)},e.search=function(e,t){var n=new z,i=new U,o=new H(i);return i._interpreter=o,t=n.parse(t),o.search(t,e)},e.strictDeepEqual=w}(t)},26:function(e,t){"use strict";var C={b:"\b",f:"\f",n:"\n",r:"\r",t:"\t",'"':'"',"/":"/","\\":"\\"},E="a".charCodeAt();t.Q=function(o,e,t){var i={},n=0,r=0,s=0,a=t&&t.bigint&&"undefined"!=typeof BigInt;return{data:l("",!0),pointers:i};function l(e,t){var n;d(),m(e,"value");var i=u();switch(i){case"t":h("rue"),n=!0;break;case"f":h("alse"),n=!1;break;case"n":h("ull"),n=null;break;case'"':n=c();break;case"[":n=function(e){d();var t=[],n=0;if("]"==u())return t;p();for(;;){var i=e+"/"+n;t.push(l(i)),d();i=u();if("]"==i)break;","!=i&&b(),d(),n++}return t}(e);break;case"{":n=function(e){d();var t={};if("}"==u())return t;p();for(;;){var n=v();'"'!=u()&&b();var i=c(),o=e+"/"+_(i);g(o,"key",n),m(o,"keyEnd"),d(),":"!=u()&&b(),d(),t[i]=l(o),d();o=u();if("}"==o)break;","!=o&&b(),d()}return t}(e);break;default:p(),0<="-0123456789".indexOf(i)?n=function(){var e="",t=!0;"-"==o[s]&&(e+=u());e+=("0"==o[s]?u:f)(),"."==o[s]&&(e+=u()+f(),t=!1);"e"!=o[s]&&"E"!=o[s]||(e+=u(),"+"!=o[s]&&"-"!=o[s]||(e+=u()),e+=f(),t=!1);var n=+e;return a&&t&&(n>Number.MAX_SAFE_INTEGER||n<Number.MIN_SAFE_INTEGER)?BigInt(e):n}():y()}return m(e,"valueEnd"),d(),t&&s<o.length&&y(),n}function d(){e:for(;s<o.length;){switch(o[s]){case" ":r++;break;case"\t":r+=4;break;case"\r":r=0;break;case"\n":r=0,n++;break;default:break e}s++}}function c(){for(var e,t="";'"'!=(e=u());)"\\"==e?(e=u())in C?t+=C[e]:"u"==e?t+=function(){var e=4,t=0;for(;e--;){t<<=4;var n=u().toLowerCase();"a"<=n&&n<="f"?t+=n.charCodeAt()-E+10:"0"<=n&&n<="9"?t+=+n:b()}return String.fromCharCode(t)}():b():t+=e;return t}function h(e){for(var t=0;t<e.length;t++)u()!==e[t]&&b()}function u(){x();var e=o[s];return s++,r++,e}function p(){s--,r--}function f(){for(var e="";"0"<=o[s]&&o[s]<="9";)e+=u();if(e.length)return e;x(),y()}function m(e,t){g(e,t,v())}function g(e,t,n){i[e]=i[e]||{},i[e][t]=n}function v(){return{line:n,column:r,pos:s}}function y(){throw new SyntaxError("Unexpected token "+o[s]+" in JSON at position "+s)}function b(){p(),y()}function x(){if(s>=o.length)throw new SyntaxError("Unexpected end of JSON input")}};var n=/~/g,i=/\//g;function _(e){return e.replace(n,"~0").replace(i,"~1")}},664:function(e){e.exports=function(){"use strict";function n(e,t){if(!(this instanceof n))throw new SyntaxError("Constructor must be called with the new operator");this.message=e+" (char "+t+")",this.char=t,this.stack=(new Error).stack}(n.prototype=new Error).constructor=Error;var i=["'","‘","’","`","´"],o=['"',"“","”"];function r(e){return/^[a-zA-Z_]$/.test(e)}function s(e){return"0"<=e&&e<="9"}function a(e){return" "===e||"\t"===e||"\n"===e||"\r"===e}function l(e){return" "===e||" "<=e&&e<=" "||" "===e||" "===e||" "===e}function d(e){return i.includes(e)?"'":o.includes(e)?'"':e}function e(e,t){t=e.lastIndexOf(t);return-1!==t?e.substring(0,t)+e.substring(t+1):e}function t(e,t){return e.replace(/\s*$/,function(e){return t+e})}var c=0,h=1,u=2,p=3,f=4,m=5,g=6,v={"":!0,"{":!0,"}":!0,"[":!0,"]":!0,":":!0,",":!0,"(":!0,")":!0,";":!0,"+":!0},y={'"':'"',"\\":"\\","/":"/",b:"\b",f:"\f",n:"\n",r:"\r",t:"\t"},b={"\b":"\\b","\f":"\\f","\n":"\\n","\r":"\\r","\t":"\\t"},x={null:"null",true:"true",false:"false"},C={None:"null",True:"true",False:"false"},E="",_="",T=0,w="",S="",N=g;function k(){T++,w=E.charAt(T)}function I(){return N===c&&("["===S||"{"===S)||N===u||N===h||N===p}function j(){_+=S,N=g,S="",v[w]?(N=c,S=w,k()):function(){if(s(w)||"-"===w){if(N=h,"-"===w){if(S+=w,k(),!s(w))throw new n("Invalid number, digit expected",T)}else"0"===w&&(S+=w,k());for(;s(w);)S+=w,k();if("."===w){if(S+=w,k(),!s(w))throw new n("Invalid number, digit expected",T);for(;s(w);)S+=w,k()}if("e"===w||"E"===w){if(S+=w,k(),"+"!==w&&"-"!==w||(S+=w,k()),!s(w))throw new n("Invalid number, digit expected",T);for(;s(w);)S+=w,k()}}else!function(){if(function(e){return i.includes(e)||o.includes(e)}(w)){var e=d(w);for(S+='"',N=u,k();""!==w&&d(w)!==e;)if("\\"===w)if(k(),void 0!==y[w])S+="\\"+w,k();else if("u"===w){S+="\\u",k();for(var t=0;t<4;t++){if(!/^[0-9a-fA-F]$/.test(w))throw new n("Invalid unicode character",T-S.length);S+=w,k()}}else{if("'"!==w)throw new n('Invalid escape character "\\'+w+'"',T);S+="'",k()}else b[w]?S+=b[w]:S+='"'===w?'\\"':w,k();if(d(w)!==e)throw new n("End of string expected",T-S.length);return S+='"',k(),0}!function(){if(r(w))for(N=p;r(w)||s(w)||"$"===w;)S+=w,k();else!function(){if(a(w)||l(w))for(N=f;a(w)||l(w);)S+=w,k();else!function(){if("/"===w&&"*"===E[T+1]){for(N=m;""!==w&&("*"!==w||"*"===w&&"/"!==E[T+1]);)S+=w,k();return"*"===w&&"/"===E[T+1]&&(S+=w,k(),S+=w,k())}if("/"!==w||"/"!==E[T+1])!function(){for(N=g;""!==w;)S+=w,k();throw new n('Syntax error in part "'+S+'"',T-S.length)}();else for(N=m;""!==w&&"\n"!==w;)S+=w,k()}()}()}()}()}(),N===f&&(S=function(e){for(var t="",n=0;n<e.length;n++){var i=e[n];t+=l(i)?" ":i}return t}(S),j()),N===m&&(N=g,S="",j())}function D(){if(N!==c||"{"!==S)!function(){if(N===c&&"["===S){if(j(),N===c&&"]"===S)return j();for(;;)if(D(),N===c&&","===S){if(j(),N===c&&"]"===S){_=e(_,",");break}}else{if(!I())break;_=t(_,",")}return N===c&&"]"===S?j():_=t(_,"]")}!function(){if(N!==u)!(N===h?j():void function(){if(N===p){if(x[S])return j();if(C[S])return S=C[S],j();var e=S,t=_.length;if(S="",j(),N===c&&"("===S)return S="",j(),D(),N===c&&")"===S&&(S="",j(),N===c&&";"===S&&(S="",j()));for(_=function(e,t,n){return e.substring(0,n)+t+e.substring(n)}(_,'"'.concat(e),t);N===p||N===h;)j();return _+='"'}!function(){throw new n(""===S?"Unexpected end of json string":"Value expected",T-S.length)}()}());else for(j();N===c&&"+"===S;){var e;S="",j(),N===u&&(e=_.lastIndexOf('"'),_=_.substring(0,e)+S.substring(1),S="",j())}}()}();else if(j(),N!==c||"}"!==S){for(;;){if(N!==p&&N!==h||(N=u,S='"'.concat(S,'"')),N!==u)throw new n("Object key expected",T-S.length);if(j(),N===c&&":"===S)j();else{if(!I())throw new n("Colon expected",T-S.length);_=t(_,":")}if(D(),N===c&&","===S){if(j(),N===c&&"}"===S){_=e(_,",");break}}else{if(N!==u&&N!==h&&N!==p)break;_=t(_,",")}}N===c&&"}"===S?j():_=t(_,"}")}else j()}return function(e){if(_="",T=0,w=(E=e).charAt(0),S="",N=g,j(),e=N===c&&"{"===S,D(),""===S)return _;if(e&&I()){for(;I();)_=t(_,","),D();return"[\n".concat(_,"\n]")}throw new n("Unexpected characters",T-S.length)}}()},483:function(e,t){var n,i;!function(){"use strict";n=[],void 0===(i="function"==typeof(i=function(){"use strict";function S(e){if(typeof Node==="object")return e instanceof Node;else return e&&typeof e==="object"&&typeof e.nodeType==="number"}function e(e){return"string"==typeof e}function N(){var r=[];return{watch:r.push.bind(r),trigger:function(e,t){var n=true;var i={detail:t,preventDefault:function e(){n=false}};for(var o=0;o<r.length;o++)r[o](e,i);return n}}}function k(e){return window.getComputedStyle(e).display==="none"}function I(e){this.elem=e}function t(e,t){return I.make((i=a)("parent")).clazz("pico-overlay").clazz(i("overlayClass","")).stylize({display:"none",position:"fixed",top:"0px",left:"0px",height:"100%",width:"100%",zIndex:1e4}).stylize(i("overlayStyles",{opacity:.5,background:"#000"})).onClick(function(){i("overlayClose",!0)&&o()})}I.make=function(e,t){if(typeof e==="string")e=document.querySelector(e);var n=document.createElement(t||"div");(e||document.body).appendChild(n);return new I(n)},I.prototype={child:function(e){return I.make(this.elem,e)},stylize:function(e){e=e||{};if(typeof e.opacity!=="undefined")e.filter="alpha(opacity="+e.opacity*100+")";for(var t in e)if(e.hasOwnProperty(t))this.elem.style[t]=e[t];return this},clazz:function(e){this.elem.className+=" "+e;return this},html:function(e){if(S(e))this.elem.appendChild(e);else this.elem.innerHTML=e;return this},onClick:function(e){this.elem.addEventListener("click",e);return this},destroy:function(){this.elem.parentNode.removeChild(this.elem)},hide:function(){this.elem.style.display="none"},show:function(){this.elem.style.display="block"},attr:function(e,t){if(t!==undefined)this.elem.setAttribute(e,t);return this},anyAncestor:function(e){var t=this.elem;while(t)if(e(new I(t)))return true;else t=t.parentNode;return false},isVisible:function(){return!k(this.elem)}};var j=1;function n(e,t){var n=e("width","auto");if("number"==typeof n)n+="px";var i=e("modalId","pico-"+j++);return I.make(e("parent")).clazz("pico-content").clazz(e("modalClass","")).stylize({display:"none",position:"fixed",zIndex:10001,left:"50%",top:"38.1966%",maxHeight:"90%",boxSizing:"border-box",width:n,"-ms-transform":"translate(-50%,-38.1966%)","-moz-transform":"translate(-50%,-38.1966%)","-webkit-transform":"translate(-50%,-38.1966%)","-o-transform":"translate(-50%,-38.1966%)",transform:"translate(-50%,-38.1966%)"}).stylize(e("modalStyles",{overflow:"auto",backgroundColor:"white",padding:"20px",borderRadius:"5px"})).html(e("content")).attr("id",i).attr("role","dialog").attr("aria-labelledby",e("ariaLabelledBy")).attr("aria-describedby",e("ariaDescribedBy",i)).onClick(function(e){new I(e.target).anyAncestor(function(e){return/\bpico-close\b/.test(e.elem.className)})&&t()})}function i(e,t){if(t("closeButton",!0))return e.child("button").html(t("closeHtml","&#xD7;")).clazz("pico-close").clazz(t("closeClass","")).stylize(t("closeStyles",{borderRadius:"2px",border:0,padding:0,cursor:"pointer",height:"15px",width:"15px",position:"absolute",top:"5px",right:"5px",fontSize:"16px",textAlign:"center",lineHeight:"15px",background:"#CCC"})).attr("aria-label",t("close-label","Close"))}function D(e){return function(){return e().elem}}var A=N(),P=N();function o(e,t){function _(e,t){return(e.msMatchesSelector||e.webkitMatchesSelector||e.matches).call(e,t)}function T(e){return!(k(e)||_(e,":disabled")||e.hasAttribute("contenteditable"))&&(e.hasAttribute("tabindex")||_(e,"input,select,textarea,button,a[href],area[href],iframe"))}function w(e){for(var t=e.getElementsByTagName("*"),n=0;n<t.length;n++)if(T(t[n]))return t[n]}function r(e){for(var t=e.getElementsByTagName("*"),n=t.length;n--;)if(T(t[n]))return t[n]}var e;c.beforeShow(function(){e=document.activeElement}),c.afterShow(function(){var e;!h()||(e=w(c.modalElem()))&&e.focus()}),c.afterClose(function(){h()&&e&&e.focus(),e=null}),P.watch(function(e){var t,n;h()&&c.isVisible()&&(t=w(c.modalElem()),n=function(e){for(var t=e.getElementsByTagName("*"),n=t.length;n--;)if(T(t[n]))return t[n]}(c.modalElem()),(e.shiftKey?t:n)===document.activeElement&&((e.shiftKey?n:t).focus(),e.preventDefault()))})}function r(e,t){var f,m=new I(document.body);u.beforeShow(function(){f=m.elem.style.overflow,p()&&m.stylize({overflow:"hidden"})}),u.afterClose(function(){m.stylize({overflow:f})})}return document.documentElement.addEventListener("keydown",function(e){var t=e.which||e.keyCode;27===t?A.trigger():9===t&&P.trigger(e)}),function(n){"string"!=typeof n&&!S(n)||(n={content:n});var r=N(),t=N(),i=N(),o=N(),s=N();function a(e,t){e=n[e];return"function"==typeof e&&(e=e(t)),void 0===e?t:e}var l,d,c,h,e,u,p,f,m,g=E.bind(window,"modal"),v=E.bind(window,"overlay"),y=E.bind(window,"close");function b(e){v().hide(),g().hide(),s.trigger(l,e)}function x(e){o.trigger(l,e)&&b(e)}function C(e){return function(){return e.apply(this,arguments),l}}function E(e,t){var n,i,o;return d||(n=function(e,t){var n=e("width","auto");"number"==typeof n&&(n+="px");var i=e("modalId","pico-"+j++);return I.make(e("parent")).clazz("pico-content").clazz(e("modalClass","")).stylize({display:"none",position:"fixed",zIndex:10001,left:"50%",top:"38.1966%",maxHeight:"90%",boxSizing:"border-box",width:n,"-ms-transform":"translate(-50%,-38.1966%)","-moz-transform":"translate(-50%,-38.1966%)","-webkit-transform":"translate(-50%,-38.1966%)","-o-transform":"translate(-50%,-38.1966%)",transform:"translate(-50%,-38.1966%)"}).stylize(e("modalStyles",{overflow:"auto",backgroundColor:"white",padding:"20px",borderRadius:"5px"})).html(e("content")).attr("id",i).attr("role","dialog").attr("aria-labelledby",e("ariaLabelledBy")).attr("aria-describedby",e("ariaDescribedBy",i)).onClick(function(e){new I(e.target).anyAncestor(function(e){return/\bpico-close\b/.test(e.elem.className)})&&t()})}(a,x),d={modal:n,overlay:(o=x,I.make((i=a)("parent")).clazz("pico-overlay").clazz(i("overlayClass","")).stylize({display:"none",position:"fixed",top:"0px",left:"0px",height:"100%",width:"100%",zIndex:1e4}).stylize(i("overlayStyles",{opacity:.5,background:"#000"})).onClick(function(){i("overlayClose",!0)&&o()})),close:function(e,t){if(t("closeButton",!0))return e.child("button").html(t("closeHtml","&#xD7;")).clazz("pico-close").clazz(t("closeClass","")).stylize(t("closeStyles",{borderRadius:"2px",border:0,padding:0,cursor:"pointer",height:"15px",width:"15px",position:"absolute",top:"5px",right:"5px",fontSize:"16px",textAlign:"center",lineHeight:"15px",background:"#CCC"})).attr("aria-label",t("close-label","Close"))}(n,a)},r.trigger(l,t)),d[e]}function _(e,t){return(e.msMatchesSelector||e.webkitMatchesSelector||e.matches).call(e,t)}function T(e){return!(k(e)||_(e,":disabled")||e.hasAttribute("contenteditable"))&&(e.hasAttribute("tabindex")||_(e,"input,select,textarea,button,a[href],area[href],iframe"))}function w(e){for(var t=e.getElementsByTagName("*"),n=0;n<t.length;n++)if(T(t[n]))return t[n]}return l={modalElem:D(g),closeElem:D(y),overlayElem:D(v),buildDom:C(E.bind(null,null)),isVisible:function(){return!!(d&&g&&g().isVisible())},show:function(e){return t.trigger(l,e)&&(v().show(),y(),g().show(),i.trigger(l,e)),this},close:C(x),forceClose:C(b),destroy:function(){g().destroy(),v().destroy(),v=g=y=void 0},options:function(t){Object.keys(t).map(function(e){n[e]=t[e]})},afterCreate:C(r.watch),beforeShow:C(t.watch),afterShow:C(i.watch),beforeClose:C(o.watch),afterClose:C(s.watch)},c=l,h=a.bind(null,"focus",!0),c.beforeShow(function(){e=document.activeElement}),c.afterShow(function(){var e;!h()||(e=w(c.modalElem()))&&e.focus()}),c.afterClose(function(){h()&&e&&e.focus(),e=null}),P.watch(function(e){var t,n;h()&&c.isVisible()&&(t=w(c.modalElem()),n=function(e){for(var t=e.getElementsByTagName("*"),n=t.length;n--;)if(T(t[n]))return t[n]}(c.modalElem()),(e.shiftKey?t:n)===document.activeElement&&((e.shiftKey?n:t).focus(),e.preventDefault()))}),u=l,p=a.bind(null,"bodyOverflow",!0),m=new I(document.body),u.beforeShow(function(){f=m.elem.style.overflow,p()&&m.stylize({overflow:"hidden"})}),u.afterClose(function(){m.stylize({overflow:f})}),A.watch(function(){a("escCloses",!0)&&l.isVisible()&&l.close()}),l}})?i.apply(t,n):i)||(e.exports=i)}()}},o={},i.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return i.d(t,{a:t}),t},i.d=function(e,t){for(var n in t)i.o(t,n)&&!i.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},i.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},i.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},i(161);function i(e){if(o[e])return o[e].exports;var t=o[e]={exports:{}};return n[e].call(t.exports,t,t.exports,i),t.exports}var n,o}); //# sourceMappingURL=jsoneditor-minimalist.map
// // Escape Codec Library: ecl.js (Ver.041208) // // Copyright (C) http://nurucom-archives.hp.infoseek.co.jp/digital/ // EscapeSJIS=function(str){ return str.replace(/[^*+.-9A-Z_a-z-]/g,function(s){ var c=s.charCodeAt(0),m; return c<128?(c<16?"%0":"%")+c.toString(16).toUpperCase():65376<c&&c<65440?"%"+(c-65216).toString(16).toUpperCase():(c=JCT11280.indexOf(s))<0?"%81E":"%"+((m=((c<8272?c:(c=JCT11280.lastIndexOf(s)))-(c%=188))/188)<31?m+129:m+193).toString(16).toUpperCase()+(64<(c+=c<63?64:65)&&c<91||95==c||96<c&&c<123?String.fromCharCode(c):"%"+c.toString(16).toUpperCase()) }) }; UnescapeSJIS=function(str){ return str.replace(/%(8[1-9A-F]|[9E][0-9A-F]|F[0-9A-C])(%[4-689A-F][0-9A-F]|%7[0-9A-E]|[@-~])|%([0-7][0-9A-F]|A[1-9A-F]|[B-D][0-9A-F])/ig,function(s){ var c=parseInt(s.substring(1,3),16),l=s.length; return 3==l?String.fromCharCode(c<160?c:c+65216):JCT11280.charAt((c<160?c-129:c-193)*188+(4==l?s.charCodeAt(3)-64:(c=parseInt(s.substring(4),16))<127?c-64:c-65)) }) }; EscapeEUCJP=function(str){ return str.replace(/[^*+.-9A-Z_a-z-]/g,function(s){ var c=s.charCodeAt(0); return (c<128?(c<16?"%0":"%")+c.toString(16):65376<c&&c<65440?"%8E%"+(c-65216).toString(16):(c=JCT8836.indexOf(s))<0?"%A1%A6":"%"+((c-(c%=94))/94+161).toString(16)+"%"+(c+161).toString(16)).toUpperCase() }) }; UnescapeEUCJP=function(str){ return str.replace(/(%A[1-9A-F]|%[B-E][0-9A-F]|%F[0-9A-E]){2}|%8E%(A[1-9A-F]|[B-D][0-9A-F])|%[0-7][0-9A-F]/ig,function(s){ var c=parseInt(s.substring(1),16); return c<161?String.fromCharCode(c<128?c:parseInt(s.substring(4),16)+65216):JCT8836.charAt((c-161)*94+parseInt(s.substring(4),16)-161) }) }; EscapeJIS7=function(str){ var u=String.fromCharCode,ri=u(92,120,48,48,45,92,120,55,70),rj=u(65377,45,65439,93,43), H=function(c){ return 41<c&&c<58&&44!=c||64<c&&c<91||95==c||96<c&&c<123?u(c):"%"+c.toString(16).toUpperCase() }, I=function(s){ var c=s.charCodeAt(0); return (c<16?"%0":"%")+c.toString(16).toUpperCase() }, rI=new RegExp;rI.compile("[^*+.-9A-Z_a-z-]","g"); return ("g"+str+"g").replace(RegExp("["+ri+"]+","g"),function(s){ return "%1B%28B"+s.replace(rI,I) }).replace(RegExp("["+rj,"g"),function(s){ var c,i=0,t="%1B%28I";while(c=s.charCodeAt(i++))t+=H(c-65344);return t }).replace(RegExp("[^"+ri+rj,"g"),function(s){ var a,c,i=0,t="%1B%24B";while(a=s.charAt(i++))t+=(c=JCT8836.indexOf(a))<0?"%21%26":H((c-(c%=94))/94+33)+H(c+33);return t }).slice(8,-1) }; UnescapeJIS7=function(str){ var i=0,p,q,s="",u=String.fromCharCode, P=("%28B"+str.replace(/%49/g,"I").replace(/%1B%24%4[02]|%1B%24@/ig,"%1B%24B")).split(/%1B/i), I=function(s){ return u(parseInt(s.substring(1),16)) }, J=function(s){ return u((3==s.length?parseInt(s.substring(1),16):s.charCodeAt(0))+65344) }, K=function(s){ var l=s.length; return JCT8836.charAt(4<l?(parseInt(s.substring(1),16)-33)*94+parseInt(s.substring(4),16)-33:2<l?(37==(l=s.charCodeAt(0))?(parseInt(s.substring(1,3),16)-33)*94+s.charCodeAt(3):(l-33)*94+parseInt(s.substring(2),16))-33:(s.charCodeAt(0)-33)*94+s.charCodeAt(1)-33) }, rI=new RegExp,rJ=new RegExp,rK=new RegExp; rI.compile("%[0-7][0-9A-F]","ig");rJ.compile("(%2[1-9A-F]|%[3-5][0-9A-F])|[!-_]","ig"); rK.compile("(%2[1-9A-F]|%[3-6][0-9A-F]|%7[0-9A-E]){2}|(%2[1-9A-F]|%[3-6][0-9A-F]|%7[0-9A-E])[!-~]|[!-~](%2[1-9A-F]|%[3-6][0-9A-F]|%7[0-9A-E])|[!-~]{2}","ig"); while(p=P[i++])s+="%24B"==(q=p.substring(0,4))?p.substring(4).replace(rK,K):"%28I"==q?p.substring(4).replace(rJ,J):p.replace(rI,I).substring(2); return s }; EscapeJIS8=function(str){ var u=String.fromCharCode,r=u(92,120,48,48,45,92,120,55,70,65377,45,65439,93,43), H=function(c){ return 41<c&&c<58&&44!=c||64<c&&c<91||95==c||96<c&&c<123?u(c):"%"+c.toString(16).toUpperCase() }, I=function(s){ var c=s.charCodeAt(0); return (c<16?"%0":"%")+(c<128?c:c-65216).toString(16).toUpperCase() }, rI=new RegExp;rI.compile("[^*+.-9A-Z_a-z-]","g"); return ("g"+str+"g").replace(RegExp("["+r,"g"),function(s){ return "%1B%28B"+s.replace(rI,I) }).replace(RegExp("[^"+r,"g"),function(s){ var a,c,i=0,t="%1B%24B";while(a=s.charAt(i++))t+=(c=JCT8836.indexOf(a))<0?"%21%26":H((c-(c%=94))/94+33)+H(c+33);return t }).slice(8,-1) }; UnescapeJIS8=function(str){ var i=0,p,s="", P=("%28B"+str.replace(/%1B%24%4[02]|%1B%24@/ig,"%1B%24B")).split(/%1B/i), I=function(s){ var c=parseInt(s.substring(1),16); return String.fromCharCode(c<128?c:c+65216) }, K=function(s){ var l=s.length; return JCT8836.charAt(4<l?(parseInt(s.substring(1),16)-33)*94+parseInt(s.substring(4),16)-33:2<l?(37==(l=s.charCodeAt(0))?(parseInt(s.substring(1,3),16)-33)*94+s.charCodeAt(3):(l-33)*94+parseInt(s.substring(2),16))-33:(s.charCodeAt(0)-33)*94+s.charCodeAt(1)-33) }, rI=new RegExp,rK=new RegExp; rI.compile("%([0-7][0-9A-F]|A[1-9A-F]|[B-D][0-9A-F])","ig"); rK.compile("(%2[1-9A-F]|%[3-6][0-9A-F]|%7[0-9A-E]){2}|(%2[1-9A-F]|%[3-6][0-9A-F]|%7[0-9A-E])[!-~]|[!-~](%2[1-9A-F]|%[3-6][0-9A-F]|%7[0-9A-E])|[!-~]{2}","ig"); while(p=P[i++])s+="%24B"==p.substring(0,4)?p.substring(4).replace(rK,K):p.replace(rI,I).substring(2); return s }; EscapeUnicode=function(str){ return str.replace(/[^*+.-9A-Z_a-z-]/g,function(s){ var c=s.charCodeAt(0); return (c<16?"%0":c<256?"%":c<4096?"%u0":"%u")+c.toString(16).toUpperCase() }) }; UnescapeUnicode=function(str){ return str.replace(/%u[0-9A-F]{4}|%[0-9A-F]{2}/ig,function(s){ return String.fromCharCode("0x"+s.substring(s.length/3)) }) }; EscapeUTF7=function(str){ var B="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""), E=function(s){ var c=s.charCodeAt(0); return B[c>>10]+B[c>>4&63]+B[(c&15)<<2|(c=s.charCodeAt(1))>>14]+(0<=c?B[c>>8&63]+B[c>>2&63]+B[(c&3)<<4|(c=s.charCodeAt(2))>>12]+(0<=c?B[c>>6&63]+B[c&63]:""):"") }, re=new RegExp;re.compile("[^+]{1,3}","g"); return (str+"g").replace(/[^*+.-9A-Z_a-z-]+[*+.-9A-Z_a-z-]|[+]/g,function(s){ if("+"==s)return "+-"; var l=s.length-1,w=s.charAt(l); return "+"+s.substring(0,l).replace(re,E)+("+"==w?"-+-":"*"==w||"."==w||"_"==w?w:"-"+w) }).slice(0,-1) }; UnescapeUTF7=function(str){ var i=0,B={}; while(i<64)B["ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(i)]=i++; return str.replace(RegExp("[+][+/-9A-Za-z]*-?","g"),function(s){ if("+-"==s)return "+"; var b=B[s.charAt(1)],c,i=1,t=""; while(0<=b){ if((c=i&7)<6)c=c<3?b<<10|B[s.charAt(++i)]<<4|(b=B[s.charAt(++i)])>>2:(b&3)<<14|B[s.charAt(++i)]<<8|B[s.charAt(++i)]<<2|(b=B[s.charAt(++i)])>>4; else{c=(b&15)<<12|B[s.charAt(++i)]<<6|B[s.charAt(++i)];b=B[s.charAt(++i)]} if(c)t+=String.fromCharCode(c) } return t }) }; EscapeUTF8=function(str){ return str.replace(/[^*+.-9A-Z_a-z-]/g,function(s){ var c=s.charCodeAt(0); return (c<16?"%0"+c.toString(16):c<128?"%"+c.toString(16):c<2048?"%"+(c>>6|192).toString(16)+"%"+(c&63|128).toString(16):"%"+(c>>12|224).toString(16)+"%"+(c>>6&63|128).toString(16)+"%"+(c&63|128).toString(16)).toUpperCase() }) }; UnescapeUTF8=function(str){ return str.replace(/%(E(0%[AB]|[1-CEF]%[89AB]|D%[89])[0-9A-F]|C[2-9A-F]|D[0-9A-F])%[89AB][0-9A-F]|%[0-7][0-9A-F]/ig,function(s){ var c=parseInt(s.substring(1),16); return String.fromCharCode(c<128?c:c<224?(c&31)<<6|parseInt(s.substring(4),16)&63:((c&15)<<6|parseInt(s.substring(4),16)&63)<<6|parseInt(s.substring(7),16)&63) }) }; EscapeUTF16LE=function(str){ var H=function(c){ return 41<c&&c<58&&44!=c||64<c&&c<91||95==c||96<c&&c<123?String.fromCharCode(c):(c<16?"%0":"%")+c.toString(16).toUpperCase() }; return str.replace(/[^ ]| /g,function(s){ var c=s.charCodeAt(0);return H(c&255)+H(c>>8) }) }; UnescapeUTF16LE=function(str){ var u=String.fromCharCode,b=u(92,120,48,48,45,92,120,70,70); return str.replace(/^%FF%FE/i,"").replace(RegExp("%[0-9A-F]{2}%[0-9A-F]{2}|%[0-9A-F]{2}["+b+"]|["+b+"]%[0-9A-F]{2}|["+b+"]{2}","ig"),function(s){ var l=s.length; return u(4<l?"0x"+s.substring(4,6)+s.substring(1,3):2<l?37==(l=s.charCodeAt(0))?parseInt(s.substring(1,3),16)|s.charCodeAt(3)<<8:l|parseInt(s.substring(2),16)<<8:s.charCodeAt(0)|s.charCodeAt(1)<<8) }) }; GetEscapeCodeType=function(str){ if(/%u[0-9A-F]{4}/i.test(str))return "Unicode"; if(/%([0-9A-DF][0-9A-F]%[8A]0%|E0%80|[0-7][0-9A-F]|C[01])%[8A]0|%00|%[7F]F/i.test(str))return "UTF16LE"; if(/%E[0-9A-F]%[8A]0%[8A]0|%[CD][0-9A-F]%[8A]0/i.test(str))return "UTF8"; if(/%F[DE]/i.test(str))return /%8[0-9A-D]|%9[0-9A-F]|%A0/i.test(str)?"UTF16LE":"EUCJP"; if(/%1B/i.test(str))return /%[A-D][0-9A-F]/i.test(str)?"JIS8":"JIS7"; var S=str.substring(0,6143).replace(/%[0-9A-F]{2}|[^ ]| /ig,function(s){ return s.length<3?"40":s.substring(1) }),c,C,i=0,T; while(0<=(c=parseInt(S.substring(i,i+=2),16))&&i<4092)if(128<=c){ if((C=parseInt(S.substring(i,i+2),16))<128)i+=2; else if(194<=c&&c<240&&C<192){ if(c<224){T="UTF8";i+=2;continue} if(2==parseInt(S.charAt(i+2),16)>>2){T="UTF8";i+=4;continue} } if(142==c&&161<=C&&C<224){if(!T)T="EUCJP";if("EUCJP"==T)continue} if(c<161)return "SJIS"; if(c<224&&!T) if((164==c&&C<244||165==c&&C<247)&&161<=C)i+=2; else T=224<=C?"EUCJP":"SJIS"; else T="EUCJP" } return T?T:"EUCJP" }; JCT11280=Function('var a="zKV33~jZ4zN=~ji36XazM93y!{~k2y!o~k0ZlW6zN?3Wz3W?{EKzK[33[`y|;-~j^YOTz$!~kNy|L1$353~jV3zKk3~k-4P4zK_2+~jY4y!xYHR~jlz$_~jk4z$e3X5He<0y!wy|X3[:~l|VU[F3VZ056Hy!nz/m1XD61+1XY1E1=1y|bzKiz!H034zKj~mEz#c5ZA3-3X$1~mBz$$3~lyz#,4YN5~mEz#{ZKZ3V%7Y}!J3X-YEX_J(3~mAz =V;kE0/y|F3y!}~m>z/U~mI~j_2+~mA~jp2;~m@~k32;~m>V}2u~mEX#2x~mBy+x2242(~mBy,;2242(~may->2&XkG2;~mIy-_2&NXd2;~mGz,{4<6:.:B*B:XC4>6:.>B*BBXSA+A:X]E&E<~r#z+625z s2+zN=`HXI@YMXIAXZYUM8X4K/:Q!Z&33 3YWX[~mB`{zKt4z (zV/z 3zRw2%Wd39]S11z$PAXH5Xb;ZQWU1ZgWP%3~o@{Dgl#gd}T){Uo{y5_d{e@}C(} WU9|cB{w}bzvV|)[} H|zT}d||0~{]Q|(l{|x{iv{dw}(5}[Z|kuZ }cq{{y|ij}.I{idbof%cu^d}Rj^y|-M{ESYGYfYsZslS`?ZdYO__gLYRZ&fvb4oKfhSf^d<Yeasc1f&a=hnYG{QY{D`Bsa|u,}Dl|_Q{C%xK|Aq}C>|c#ryW=}eY{L+`)][YF_Ub^h4}[X|?r|u_ex}TL@YR]j{SrXgo*|Gv|rK}B#mu{R1}hs|dP{C7|^Qt3|@P{YVV |8&}#D}ef{e/{Rl|>Hni}R1{Z#{D[}CQlQ||E}[s{SG_+i8eplY[=[|ec[$YXn#`hcm}YR|{Ci(_[ql|?8p3]-}^t{wy}4la&pc|3e{Rp{LqiJ],] `kc(]@chYnrM`O^,ZLYhZB]ywyfGY~aex!_Qww{a!|)*lHrM{N+n&YYj~Z b c#e_[hZSon|rOt`}hBXa^i{lh|<0||r{KJ{kni)|x,|0auY{D!^Sce{w;|@S|cA}Xn{C1h${E]Z-XgZ*XPbp]^_qbH^e[`YM|a||+=]!Lc}]vdBc=j-YSZD]YmyYLYKZ9Z>Xcczc2{Yh}9Fc#Z.l{}(D{G{{mRhC|L3b#|xK[Bepj#ut`H[,{E9Yr}1b{[e]{ZFk7[ZYbZ0XL]}Ye[(`d}c!|*y`Dg=b;gR]Hm=hJho}R-[n}9;{N![7k_{UbmN]rf#pTe[x8}!Qcs_rs[m`|>N}^V})7{^r|/E}),}HH{OYe2{Skx)e<_.cj.cjoMhc^d}0uYZd!^J_@g,[[[?{i@][|3S}Yl3|!1|eZ|5IYw|1D}e7|Cv{OHbnx-`wvb[6[4} =g+k:{C:}ed{S]|2M]-}WZ|/q{LF|dYu^}Gs^c{Z=}h>|/i|{W]:|ip{N:|zt|S<{DH[p_tvD{N<[8Axo{X4a.^o^X>Yfa59`#ZBYgY~_t^9`jZHZn`>G[oajZ;X,i)Z.^~YJe ZiZF^{][[#Zt^|]Fjx]&_5dddW]P0C[-]}]d|y {C_jUql] |OpaA[Z{lp|rz}:Mu#]_Yf6{Ep?f5`$[6^D][^u[$[6^.Z8]]ePc2U/=]K^_+^M{q*|9tYuZ,s(dS{i=|bNbB{uG}0jZOa:[-]dYtu3]:]<{DJ_SZIqr_`l=Yt`gkTnXb3d@kiq0a`Z{|!B|}e}Ww{Sp,^Z|0>_Z}36|]A|-t}lt{R6pi|v8hPu#{C>YOZHYmg/Z4nicK[}hF_Bg|YRZ7c|crkzYZY}_iXcZ.|)U|L5{R~qi^Uga@Y[xb}&qdbd6h5|Btw[}c<{Ds53[Y7]?Z<|e0{L[ZK]mXKZ#Z2^tavf0`PE[OSOaP`4gi`qjdYMgys/?[nc,}EEb,eL]g[n{E_b/vcvgb.{kcwi`~v%|0:|iK{Jh_vf5lb}KL|(oi=LrzhhY_^@`zgf[~g)[J_0fk_V{T)}I_{D&_/d9W/|MU[)f$xW}?$xr4<{Lb{y4}&u{XJ|cm{Iu{jQ}CMkD{CX|7A}G~{kt)nB|d5|<-}WJ}@||d@|Iy}Ts|iL|/^|no|0;}L6{Pm]7}$zf:|r2}?C_k{R(}-w|`G{Gy[g]bVje=_0|PT{^Y^yjtT[[[l!Ye_`ZN]@[n_)j3nEgMa]YtYpZy].d-Y_cjb~Y~[nc~sCi3|zg}B0}do{O^{|$`_|D{}U&|0+{J3|8*]iayx{a{xJ_9|,c{Ee]QXlYb]$[%YMc*]w[aafe]aVYi[fZEii[xq2YQZHg]Y~h#|Y:thre^@^|_F^CbTbG_1^qf7{L-`VFx Zr|@EZ;gkZ@slgko`[e}T:{Cu^pddZ_`yav^Ea+[#ZBbSbO`elQfLui}.F|txYcbQ`XehcGe~fc^RlV{D_0ZAej[l&jShxG[ipB_=u:eU}3e8[=j|{D(}dO{Do[BYUZ0/]AYE]ALYhZcYlYP/^-^{Yt_1_-;YT`P4BZG=IOZ&]H[e]YYd[9^F[1YdZxZ?Z{Z<]Ba2[5Yb[0Z4l?]d_;_)a?YGEYiYv`_XmZs4ZjY^Zb]6gqGaX^9Y}dXZr[g|]Y}K aFZp^k^F]M`^{O1Ys]ZCgCv4|E>}8eb7}l`{L5[Z_faQ|c2}Fj}hw^#|Ng|B||w2|Sh{v+[G}aB|MY}A{|8o}X~{E8paZ:]i^Njq]new)`-Z>haounWhN}c#{DfZ|fK]KqGZ=:u|fqoqcv}2ssm}.r{]{nIfV{JW)[K|,Z{Uxc|]l_KdCb%]cfobya3`p}G^|LZiSC]U|(X|kBlVg[kNo({O:g:|-N|qT}9?{MBiL}Sq{`P|3a|u.{Uaq:{_o|^S}jX{Fob0`;|#y_@[V[K|cw[<_ }KU|0F}d3|et{Q7{LuZttsmf^kYZ`Af`}$x}U`|Ww}d]| >}K,r&|XI|*e{C/a-bmr1fId4[;b>tQ_:]hk{b-pMge]gfpo.|(w[jgV{EC1Z,YhaY^q,_G[c_g[J0YX]`[h^hYK^_Yib,` {i6vf@YM^hdOKZZn(jgZ>bzSDc^Z%[[o9[2=/YHZ(_/Gu_`*|8z{DUZxYt^vuvZjhi^lc&gUd4|<UiA`z]$b/Z?l}YI^jaHxe|;F}l${sQ}5g}hA|e4}?o{ih}Uz{C)jPe4]H^J[Eg[|AMZMlc}:,{iz}#*|gc{Iq|/:|zK{l&}#u|myd{{M&v~nV};L|(g|I]ogddb0xsd7^V})$uQ{HzazsgxtsO^l}F>ZB]r|{7{j@cU^{{CbiYoHlng]f+nQ[bkTn/}<-d9q {KXadZYo+n|l[|lc}V2{[a{S4Zam~Za^`{HH{xx_SvF|ak=c^[v^7_rYT`ld@]:_ub%[$[m](Shu}G2{E.ZU_L_R{tz`vj(f?^}hswz}GdZ}{S:h`aD|?W|`dgG|if{a8|J1{N,}-Ao3{H#{mfsP|[ bzn+}_Q{MT{u4kHcj_q`eZj[8o0jy{p7}C|[}l){MuYY{|Ff!Ykn3{rT|m,^R|,R}$~Ykgx{P!]>iXh6[l[/}Jgcg{JYZ.^qYfYIZl[gZ#Xj[Pc7YyZD^+Yt;4;`e8YyZVbQ7YzZxXja.7SYl[s]2^/Ha$[6ZGYrb%XiYdf2]H]kZkZ*ZQ[ZYS^HZXcCc%Z|[(bVZ]]:OJQ_DZCg<[,]%Zaa [g{C00HY[c%[ChyZ,Z_`PbXa+eh`^&jPi0a[ggvhlekL]w{Yp^v}[e{~;k%a&k^|nR_z_Qng}[E}*Wq:{k^{FJZpXRhmh3^p>de^=_7`|ZbaAZtdhZ?n4ZL]u`9ZNc3g%[6b=e.ZVfC[ZZ^^^hD{E(9c(kyZ=bb|Sq{k`|vmr>izlH[u|e`}49}Y%}FT{[z{Rk}Bz{TCc/lMiAqkf(m$hDc;qooi[}^o:c^|Qm}a_{mrZ(pA`,}<2sY| adf_%|}`}Y5U;}/4|D>|$X{jw{C<|F.hK|*A{MRZ8Zsm?imZm_?brYWZrYx`yVZc3a@f?aK^ojEd {bN}/3ZH]/$YZhm^&j 9|(S|b]mF}UI{q&aM]LcrZ5^.|[j`T_V_Gak}9J[ ZCZD|^h{N9{~&[6Zd{}B}2O|cv]K}3s}Uy|l,fihW{EG`j_QOp~Z$F^zexS`dcISfhZBXP|.vn|_HYQ|)9|cr]<`&Z6]m_(ZhPcSg>`Z]5`~1`0Xcb4k1{O!bz|CN_T{LR|a/gFcD|j<{Z._[f)mPc:1`WtIaT1cgYkZOaVZOYFrEe[}T$}Ch}mk{K-^@]fH{Hdi`c*Z&|Kt{if[C{Q;{xYB`dYIX:ZB[}]*[{{p9|4GYRh2ao{DS|V+[zd$`F[ZXKadb*A] Ys]Maif~a/Z2bmclb8{Jro_rz|x9cHojbZ{GzZx_)]:{wAayeDlx}<=`g{H1{l#}9i|)=|lP{Qq}.({La|!Y{i2EZfp=c*}Cc{EDvVB|;g}2t{W4av^Bn=]ri,|y?|3+}T*ckZ*{Ffr5e%|sB{lx^0]eZb]9[SgAjS_D|uHZx]dive[c.YPkcq/}db{EQh&hQ|eg}G!ljil|BO]X{Qr_GkGl~YiYWu=c3eb}29v3|D|}4i||.{Mv})V{SP1{FX}CZW6{cm|vO{pS|e#}A~|1i}81|Mw}es|5[}3w{C`h9aL]o{}p[G`>i%a1Z@`Ln2bD[$_h`}ZOjhdTrH{[j_:k~kv[Sdu]CtL}41{I |[[{]Zp$]XjxjHt_eThoa#h>sSt8|gK|TVi[Y{t=}Bs|b7Zpr%{gt|Yo{CS[/{iteva|cf^hgn}($_c^wmb^Wm+|55jrbF|{9^ q6{C&c+ZKdJkq_xOYqZYSYXYl`8]-cxZAq/b%b*_Vsa[/Ybjac/OaGZ4fza|a)gY{P?| I|Y |,pi1n7}9bm9ad|=d{aV|2@[(}B`d&|Uz}B}{`q|/H|!JkM{FU|CB|.{}Az}#P|lk}K{|2rk7{^8^?`/|k>|Ka{Sq}Gz}io{DxZh[yK_#}9<{TRdgc]`~Z>JYmYJ]|`!ZKZ]gUcx|^E[rZCd`f9oQ[NcD_$ZlZ;Zr}mX|=!|$6ZPZYtIo%fj}CpcN|B,{VDw~gb}@hZg`Q{LcmA[(bo`<|@$|o1|Ss}9Z_}tC|G`{F/|9nd}i=}V-{L8aaeST]daRbujh^xlpq8|}zs4bj[S`J|]?G{P#{rD{]I`OlH{Hm]VYuSYUbRc*6[j`8]pZ[bt_/^Jc*[<Z?YE|Xb|?_Z^Vcas]h{t9|Uwd)_(=0^6Zb{Nc} E[qZAeX[a]P^|_J>e8`W^j_Y}R{{Jp__]Ee#e:iWb9q_wKbujrbR}CY`,{mJ}gz{Q^{t~N|? gSga`V_||:#mi}3t|/I`X{N*|ct|2g{km}gi|{={jC}F;|E}{ZZjYf*frmu}8Tdroi{T[|+~}HG{cJ}DM{Lp{Ctd&}$hi3|FZ| m}Kr|38}^c|m_|Tr{Qv|36}?Up>|;S{DV{k_as}BK{P}}9p|t`jR{sAm4{D=b4pWa[}Xi{EjwEkI}3S|E?u=X0{jf} S|NM|JC{qo^3cm]-|JUx/{Cj{s>{Crt[UXuv|D~|j|d{YXZR}Aq}0r}(_{pJfi_z}0b|-vi)Z mFe,{f4|q`b{}^Z{HM{rbeHZ|^x_o|XM|L%|uFXm}@C_{{Hhp%a7|0p[Xp+^K}9U{bP}: tT}B|}+$|b2|[^|~h{FAby[`{}xgygrt~h1[li`c4vz|,7p~b(|mviN}^pg[{N/|g3|^0c,gE|f%|7N{q[|tc|TKA{LU}I@|AZp(}G-sz{F |qZ{}F|f-}RGn6{Z]_5})B}UJ{FFb2]4ZI@v=k,]t_Dg5Bj]Z-]L]vrpdvdGlk|gF}G]|IW}Y0[G| /bo|Te^,_B}#n^^{QHYI[?hxg{[`]D^IYRYTb&kJ[cri[g_9]Ud~^_]<p@_e_XdNm-^/|5)|h_{J;{kacVopf!q;asqd}n)|.m|bf{QW|U)}b+{tL|w``N|to{t ZO|T]jF}CB|0Q{e5Zw|k |We}5:{HO{tPwf_uajjBfX}-V_C_{{r~gg|Ude;s+}KNXH}! `K}eW{Upwbk%ogaW}9EYN}YY|&v|SL{C3[5s.]Y]I]u{M6{pYZ`^,`ZbCYR[1mNg>rsk0Ym[jrE]RYiZTr*YJ{Ge|%-lf|y(`=[t}E6{k!|3)}Zk} ][G{E~cF{u3U.rJ|a9p#o#ZE|?|{sYc#vv{E=|LC}cu{N8`/`3`9rt[4|He{cq|iSYxY`}V |(Q|t4{C?]k_Vlvk)BZ^r<{CL}#h}R+[<|i=}X|{KAo]|W<`K{NW|Zx}#;|fe{IMr<|K~tJ_x}AyLZ?{GvbLnRgN}X&{H7|x~}Jm{]-| GpNu0}.ok>|c4{PYisrDZ|fwh9|hfo@{H~XSbO]Odv]%`N]b1Y]]|eIZ}_-ZA]aj,>eFn+j[aQ_+]h[J_m_g]%_wf.`%k1e#Z?{CvYu_B^|gk`Xfh^M3`afGZ-Z|[m{L}|k3cp[it ^>YUi~d>{T*}YJ{Q5{Jxa$hg|%4`}|LAgvb }G}{P=|<;Ux{_skR{cV|-*|s-{Mp|XP|$G|_J}c6cM{_=_D|*9^$ec{V;|4S{qO|w_|.7}d0|/D}e}|0G{Dq]Kdp{}dfDi>}B%{Gd|nl}lf{C-{y}|ANZr}#={T~|-(}c&{pI|ft{lsVP}){|@u}!W|bcmB{d?|iW|:dxj{PSkO|Hl]Li:}VYk@|2={fnWt{M3`cZ6|)}|Xj}BYa?vo{e4|L7|B7{L7|1W|lvYO}W8nJ|$Vih|{T{d*_1|:-n2dblk``fT{Ky|-%}m!|Xy|-a{Pz}[l{kFjz|iH}9N{WE{x,|jz}R {P|{D)c=nX|Kq|si}Ge{sh|[X{RF{t`|jsr*fYf,rK|/9}$}}Nf{y!1|<Std}4Wez{W${Fd_/^O[ooqaw_z[L`Nbv[;l7V[ii3_PeM}.h^viqYjZ*j1}+3{bt{DR[;UG}3Og,rS{JO{qw{d<_zbAh<R[1_r`iZTbv^^a}c{iEgQZ<exZFg.^Rb+`Uj{a+{z<[~r!]`[[|rZYR|?F|qppp]L|-d|}K}YZUM|=Y|ktm*}F]{D;g{uI|7kg^}%?Z%ca{N[_<q4xC]i|PqZC]n}.bDrnh0Wq{tr|OMn6tM|!6|T`{O`|>!]ji+]_bTeU}Tq|ds}n|{Gm{z,f)}&s{DPYJ`%{CGd5v4tvb*hUh~bf]z`jajiFqAii]bfy^U{Or|m+{I)cS|.9k:e3`^|xN}@Dnlis`B|Qo{`W|>||kA}Y}{ERYuYx`%[exd`]|OyiHtb}HofUYbFo![5|+]gD{NIZR|Go}.T{rh^4]S|C9_}xO^i`vfQ}C)bK{TL}cQ|79iu}9a];sj{P.o!f[Y]pM``Jda^Wc9ZarteBZClxtM{LW}l9|a.mU}KX}4@{I+f1}37|8u}9c|v${xGlz}jP{Dd1}e:}31}%3X$|22i<v+r@~mf{sN{C67G97855F4YL5}8f{DT|xy{sO{DXB334@55J1)4.G9A#JDYtXTYM4, YQD9;XbXm9SX]IB^4UN=Xn<5(;(F3YW@XkH-X_VM[DYM:5XP!T&Y`6|,^{IS-*D.H>:LXjYQ0I3XhAF:9:(==.F*3F1189K/7163D,:@|e2{LS36D4hq{Lw/84443@4.933:0307::6D7}&l{Mx657;89;,K5678H&93D(H<&<>0B90X^I;}Ag1{P%3A+>><975}[S{PZE453?4|T2{Q+5187;>447:81{C=hL6{Me^:=7ii{R=.=F<81;48?|h8}Uh{SE|,VxL{ST,7?9Y_5Xk3A#:$%YSYdXeKXOD8+TXh7(@>(YdXYHXl9J6X_5IXaL0N?3YK7Xh!1?XgYz9YEXhXaYPXhC3X`-YLY_XfVf[EGXZ5L8BXL9YHX]SYTXjLXdJ: YcXbQXg1PX]Yx4|Jr{Ys4.8YU+XIY`0N,<H%-H;:0@,74/:8546I=9177154870UC]d<C3HXl7ALYzXFXWP<<?E!88E5@03YYXJ?YJ@6YxX-YdXhYG|9o{`iXjY_>YVXe>AYFX[/(I@0841?):-B=14337:8=|14{c&93788|di{cW-0>0<097/A;N{FqYpugAFT%X/Yo3Yn,#=XlCYHYNX[Xk3YN:YRT4?)-YH%A5XlYF3C1=NWyY}>:74-C673<69545v {iT85YED=64=.F4..9878/D4378?48B3:7:7/1VX[f4{D,{l<5E75{dAbRB-8-@+;DBF/$ZfW8S<4YhXA.(5@*11YV8./S95C/0R-A4AXQYI7?68167B95HA1*<M3?1/@;/=54XbYP36}lc{qzSS38:19?,/39193574/66878Yw1X-87E6=;964X`T734:>86>1/=0;(I-1::7ALYGXhF+Xk[@W%TYbX7)KXdYEXi,H-XhYMRXfYK?XgXj.9HX_SX]YL1XmYJ>Y}WwIXiI-3-GXcYyXUYJ$X`Vs[7;XnYEZ;XF! 3;%8;PXX(N3Y[)Xi1YE&/ :;74YQ6X`33C;-(>Xm0(TYF/!YGXg8 9L5P01YPXO-5%C|qd{{/K/E6,=0144:361:955;6443@?B7*7:F89&F35YaX-CYf,XiFYRXE_e{}sF 0*7XRYPYfXa5YXXY8Xf8Y~XmA[9VjYj*#YMXIYOXk,HHX40YxYMXU8OXe;YFXLYuPXP?EB[QV0CXfY{:9XV[FWE0D6X^YVP*$4%OXiYQ(|xp|%c3{}V`1>Y`XH00:8/M6XhQ1:;3414|TE|&o@1*=81G8<3}6<|(f6>>>5-5:8;093B^3U*+*^*UT30XgYU&7*O1953)5@E78--F7YF*B&0:%P68W9Zn5974J9::3}Vk|-,C)=)1AJ4+<3YGXfY[XQXmT1M-XcYTYZXCYZXEYXXMYN,17>XIG*SaS|/eYJXbI?XdNZ+WRYP<F:R PXf;0Xg`$|1GX9YdXjLYxWX!ZIXGYaXNYm6X9YMX?9EXmZ&XZ#XQ>YeXRXfAY[4 ;0X!Zz0XdN$XhYL XIY^XGNXUYS/1YFXhYk.TXn4DXjB{jg|4DEX]:XcZMW=A.+QYL<LKXc[vV$+&PX*Z3XMYIXUQ:ZvW< YSXFZ,XBYeXMM)?Xa XiZ4/EXcP3%}&-|6~:1(-+YT$@XIYRBC<}&,|7aJ6}bp|8)K1|Xg|8C}[T|8Q.89;-964I38361<=/;883651467<7:>?1:.}le|:Z=39;1Y^)?:J=?XfLXbXi=Q0YVYOXaXiLXmJXO5?.SFXiCYW}-;|=u&D-X`N0X^,YzYRXO(QX_YW9`I|>hZ:N&X)DQXP@YH#XmNXi$YWX^=!G6YbYdX>XjY|XlX^XdYkX>YnXUXPYF)FXT[EVTMYmYJXmYSXmNXi#GXmT3X8HOX[ZiXN]IU2>8YdX1YbX<YfWuZ8XSXcZU%0;1XnXkZ_WTG,XZYX5YSX Yp 05G?XcYW(IXg6K/XlYP4XnI @XnO1W4Zp-9C@%QDYX+OYeX9>--YSXkD.YR%Q/Yo YUX].Xi<HYEZ2WdCE6YMXa7F)=,D>-@9/8@5=?7164;35387?N<618=6>7D+C50<6B03J0{Hj|N9$D,9I-,.KB3}m |NzE0::/81YqXjMXl7YG; [.W=Z0X4XQY]:MXiR,XgM?9$9>:?E;YE77VS[Y564760391?14941:0=:8B:;/1DXjFA-564=0B3XlH1+D85:0Q!B#:-6&N/:9<-R3/7Xn<*3J4.H:+334B.=>30H.;3833/76464665755:/83H6633:=;.>5645}&E|Y)?1/YG-,93&N3AE@5 <L1-G/8A0D858/30>8<549=@B8] V0[uVQYlXeD(P#ID&7T&7;Xi0;7T-$YE)E=1:E1GR):--0YI7=E<}n9|aT6783A>D7&4YG7=391W;Zx<5+>F#J39}o/|cc;6=A050EQXg8A1-}D-|d^5548083563695D?-.YOXd37I$@LYLWeYlX<Yd+YR A$;3-4YQ-9XmA0!9/XLY_YT(=5XdDI>YJ5XP1ZAW{9>X_6R(XhYO65&J%DA)C-!B:97#A9;@?F;&;(9=11/=657/H,<8}bz|j^5446>.L+&Y^8Xb6?(CYOXb*YF(8X`FYR(XPYVXmPQ%&DD(XmZXW??YOXZXfCYJ79,O)XnYF7K0!QXmXi4IYFRXS,6<%-:YO(+:-3Q!1E1:W,Zo}Am|n~;3580534*?3Zc4=9334361693:30C<6/717:<1/;>59&:4}6!|rS36=1?75<8}[B|s809983579I.A.>84758=108564741H*9E{L{|u%YQ<%6XfH.YUXe4YL@,>N}Tv|ve*G0X)Z;/)3@A74(4P&A1X:YVH97;,754*A66:1 D739E3553545558E4?-?K17/770843XAYf838A7K%N!YW4.$T19Z`WJ*0XdYJXTYOXNZ 1XaN1A+I&Xi.Xk3Z3GB&5%WhZ1+5#Y[X<4YMXhQYoQXVXbYQ8XSYUX4YXBXWDMG0WxZA[8V+Z8X;D],Va$%YeX?FXfX[XeYf<X:Z[WsYz8X_Y]%XmQ(!7BXIZFX]&YE3F$(1XgYgYE& +[+W!<YMYFXc;+PXCYI9YrWxGXY9DY[!GXiI7::)OC;*$.>N*HA@{C|}&k=:<TB83X`3YL+G4XiK]i}(fYK<=5$.FYE%4*5*H*6XkCYL=*6Xi6!Yi1KXR4YHXbC8Xj,B9ZbWx/XbYON#5B}Ue}+QKXnF1&YV5XmYQ0!*3IXBYb71?1B75XmF;0B976;H/RXU:YZX;BG-NXj;XjI>A#D3B636N;,*%<D:0;YRXY973H5)-4FXOYf0:0;/7759774;7;:/855:543L43<?6=E,.A4:C=L)%4YV!1(YE/4YF+ F3%;S;&JC:%/?YEXJ4GXf/YS-EXEYW,9;E}X$}547EXiK=51-?71C%?57;5>463553Zg90;6447?<>4:9.7538XgN{|!}9K/E&3-:D+YE1)YE/3;37/:05}n<}:UX8Yj4Yt864@JYK..G=.(A Q3%6K>3(P3#AYE$-6H/456*C=.XHY[#S.<780191;057C)=6HXj?955B:K1 E>-B/9,;5.!L?:0>/.@//:;7833YZ56<4:YE=/:7Z_WGC%3I6>XkC*&NA16X=Yz2$X:Y^&J48<99k8}CyB-61<18K946YO4{|N}E)YIB9K0L>4=46<1K0+R;6-=1883:478;4,S+3YJX`GJXh.Yp+Xm6MXcYpX(>7Yo,/:X=Z;Xi0YTYHXjYmXiXj;*;I-8S6N#XgY}.3XfYGO3C/$XjL$*NYX,1 6;YH&<XkK9C#I74.>}Hd`A748X[T450[n75<4439:18A107>|ET}Rf<1;14876/Yb983E<5.YNXd4149>,S=/4E/<306443G/06}0&}UkYSXFYF=44=-5095=88;63844,9E6644{PL}WA8:>)7+>763>>0/B3A545CCnT}Xm|dv}Xq1L/YNXk/H8;;.R63351YY747@15YE4J8;46;.38.>4A369.=-83,;Ye3?:3@YE.4-+N353;/;@(X[YYD>@/05-I*@.:551741Yf5>6A443<3535;.58/86=D4753442$635D1>0359NQ @73:3:>><Xn?;43C14 ?Y|X611YG1&<+,4<*,YLXl<1/AIXjF*N89A4Z576K1XbJ5YF.ZOWN.YGXO/YQ01:4G38Xl1;KI0YFXB=R<7;D/,/4>;$I,YGXm94@O35Yz66695385.>:6A#5}W7n^4336:4157597434433<3|XA}m`>=D>:4A.337370?-6Q96{`E|4A}C`|Qs{Mk|J+~r>|o,wHv>Vw}!c{H!|Gb|*Ca5}J||,U{t+{CN[!M65YXOY_*B,Y[Z9XaX[QYJYLXPYuZ%XcZ8LY[SYPYKZM<LMYG9OYqSQYM~[e{UJXmQYyZM_)>YjN1~[f3{aXFY|Yk:48YdH^NZ0|T){jVFYTZNFY^YTYN~[h{nPYMYn3I]`EYUYsYIZEYJ7Yw)YnXPQYH+Z.ZAZY]^Z1Y`YSZFZyGYHXLYG 8Yd#4~[i|+)YH9D?Y^F~Y7|-eYxZ^WHYdYfZQ~[j|3>~[k|3oYmYqY^XYYO=Z*4[]Z/OYLXhZ1YLZIXgYIHYEYK,<Y`YEXIGZI[3YOYcB4SZ!YHZ*&Y{Xi3~[l|JSY`Zz?Z,~[m|O=Yi>??XnYWXmYS617YVYIHZ(Z4[~L4/=~[n|Yu{P)|];YOHHZ}~[o33|a>~[r|aE]DH~[s|e$Zz~[t|kZFY~XhYXZB[`Y}~[u|{SZ&OYkYQYuZ2Zf8D~[v}% ~[w3},Q[X]+YGYeYPIS~[y}4aZ!YN^!6PZ*~[z}?E~[{3}CnZ=~[}}EdDZz/9A3(3S<,YR8.D=*XgYPYcXN3Z5 4)~[~}JW=$Yu.XX~] }KDX`PXdZ4XfYpTJLY[F5]X~[2Yp}U+DZJ::<446[m@~]#3}]1~]%}^LZwZQ5Z`/OT<Yh^ -~]&}jx[ ~m<z!%2+~ly4VY-~o>}p62yz!%2+Xf2+~ly4VY-zQ`z (=] 2z~o2",C={" ":0,"!":1},c=34,i=2,p,s="",u=String.fromCharCode,t=u(12539);while(++c<127)C[u(c)]=c^39&&c^92?i++:0;i=0;while(0<=(c=C[a.charAt(i++)]))if(16==c)if((c=C[a.charAt(i++)])<87){if(86==c)c=1879;while(c--)s+=u(++p)}else s+=s.substr(8272,360);else if(c<86)s+=u(p+=c<51?c-16:(c-55)*92+C[a.charAt(i++)]);else if((c=((c-86)*92+C[a.charAt(i++)])*92+C[a.charAt(i++)])<49152)s+=u(p=c<40960?c:c|57344);else{c&=511;while(c--)s+=t;p=12539}return s')(); JCT8836=JCT11280.substring(0,8836);
import { GraphQLClient } from 'graphql-request' import config from 'config' import { GITHUB } from './github' import logger from './logger' const { API_GRAPHQL, } = GITHUB const retryTimes = config.get('timeouts') export const getClient = headers => new GraphQLClient(API_GRAPHQL, { headers, }) export const fetch = async (client, query, timeout = retryTimes) => { let err = null for (let i = 0; i < timeout.length; i += 1) { try { const result = await client.request(query) if (!result) { err = new Error('[GRAPHQL:ERROR]No return result') continue } err = null return result } catch (e) { if (e.response && e.response.errors) { const errors = e.response.errors err = errors.map(error => `[${error.type}]${error.message}`).join('\n') } else { err = e } } } if (err) { logger.error(err) } return null }
# # Copyright 2018 Analytics Zoo Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # from __future__ import print_function import numpy as np import onnx import torch from zoo.pipeline.api.onnx.onnx_loader import OnnxLoader from .test_utils import ZooTestCase from bigdl.util.common import to_list np.random.seed(1337) # for reproducibility class OnnxTestCase(ZooTestCase): def dump_pytorch_to_onnx(self, pytorch_model, input_shape_with_batch, input_data_with_batch): import uuid tmp_dir = self.create_temp_dir() onnx_path = "%s/%s" % (tmp_dir, uuid.uuid4().hex + ".onnx") dummy_input = self._generate_pytorch_input(input_shape_with_batch, input_data_with_batch) torch.onnx.export(pytorch_model, dummy_input, onnx_path) print("Creating an Onnx model: " + onnx_path) return onnx_path def _generate_pytorch_input(self, input_shape_with_batch, input_data_with_batch): if input_data_with_batch is None: dummy_input = [torch.autograd.Variable(torch.randn(shape)) for shape in input_shape_with_batch] else: dummy_input = [torch.autograd.Variable(torch.LongTensor(data)) for data in input_data_with_batch] if len(dummy_input) == 1: dummy_input = dummy_input[0] return dummy_input def _convert_ndarray_to_tensor(self, input_data_with_batch): tensors = [torch.from_numpy(input) for input in input_data_with_batch] if len(tensors) == 1: return tensors[0] else: return tensors def compare_with_pytorch(self, pytorch_model, input_shape_with_batch, input_data_with_batch=None, compare_result=True, rtol=1e-6, atol=1e-6): input_shape_with_batch = to_list(input_shape_with_batch) if input_data_with_batch is not None: input_data_with_batch = to_list(input_data_with_batch) onnx_path = self.dump_pytorch_to_onnx(pytorch_model, input_shape_with_batch, input_data_with_batch) onnx_model = onnx.load(onnx_path) # TODO: we only consider single output for now if input_data_with_batch is None: input_data_with_batch = [np.random.uniform(0, 1, shape).astype(np.float32) for shape in input_shape_with_batch] else: input_data_with_batch = [np.array(data).astype(np.long) for data in input_data_with_batch] # coutput = caffe2.python.onnx.backend.run_model(onnx_model, input_data_with_batch)[0] pytorch_out = pytorch_model.forward(self._convert_ndarray_to_tensor(input_data_with_batch)) zmodel = OnnxLoader(onnx_model.graph).to_keras() zoutput = zmodel.forward( input_data_with_batch[0] if len(input_data_with_batch) == 1 else input_data_with_batch) if compare_result: self.assert_allclose(pytorch_out.detach().numpy(), zoutput, rtol, atol) assert tuple(pytorch_out.size()[1:]) == zmodel.get_output_shape()[1:] def gen_rnd(self, shape, low=-1.0, high=1.0): return np.random.uniform(low, high, np.prod(shape)) \ .reshape(shape) \ .astype(np.float32)
window._ = require("lodash"); window.Popper = require("popper.js").default; /** * We'll load jQuery and the Bootstrap jQuery plugin which provides support * for JavaScript based Bootstrap features such as modals and tabs. This * code may be modified to fit the specific needs of your application. */ try { window.$ = window.jQuery = require("jquery"); require("bootstrap"); } catch (e) {} /** * We'll load the axios HTTP library which allows us to easily issue requests * to our Laravel back-end. This library automatically handles sending the * CSRF token as a header based on the value of the "XSRF" token cookie. */ window.axios = require("axios"); window.axios.defaults.headers.common["X-Requested-With"] = "XMLHttpRequest"; const JwtToken = `Bearer ${localStorage.getItem("token")}`; window.axios.defaults.headers.common["Authorization"] = JwtToken; /** * Next we will register the CSRF Token as a common header with Axios so that * all outgoing HTTP requests automatically have it attached. This is just * a simple convenience so we don't have to attach every token manually. */ let token = document.head.querySelector('meta[name="csrf-token"]'); if (token) { window.axios.defaults.headers.common["X-CSRF-TOKEN"] = token.content; } else { console.error( "CSRF token not found: https://laravel.com/docs/csrf#csrf-x-csrf-token" ); } /** * Echo exposes an expressive API for subscribing to channels and listening * for events that are broadcast by Laravel. Echo and event broadcasting * allows your team to easily build robust real-time web applications. */ // import Echo from 'laravel-echo' // window.Pusher = require('pusher-js'); // window.Echo = new Echo({ // broadcaster: 'pusher', // key: process.env.MIX_PUSHER_APP_KEY, // cluster: process.env.MIX_PUSHER_APP_CLUSTER, // encrypted: true // });
/* -*- Mode: Javascript; indent-tabs-mode:nil; js-indent-level: 2 -*- */ /* vim: set ts=2 et sw=2 tw=80: */ /************************************************************* * * MathJax/localization/kn/HTML-CSS.js * * Copyright (c) 2009-2015 The MathJax Consortium * * 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. * */ MathJax.Localization.addTranslation("kn","HTML-CSS",{ version: "2.5.0", isLoaded: true, strings: { LoadWebFont: "\u0CB5\u0CC6\u0CAC\u0CCD \u0CAB\u0CBE\u0C82\u0C9F\u0CCD %1 \u0C85\u0CA8\u0CCD\u0CA8\u0CC1 \u0CA1\u0CCC\u0CA8\u0CCD\u0CB2\u0CCB\u0CA1\u0CCD \u0CAE\u0CBE\u0CA1\u0CC1\u0CA4 \u0C89\u0C82\u0C9F\u0CC1", CantLoadWebFont: " \u0CB5\u0CC6\u0CAC\u0CCD \u0CAB\u0CBE\u0C82\u0C9F\u0CCD %1 \u0C85\u0CA8\u0CCD\u0CA8\u0CC1 \u0CA1\u0CCC\u0CA8\u0CCD\u0CB2\u0CCB\u0CA1\u0CCD \u0CAE\u0CBE\u0CA1\u0CB2\u0CBF\u0C95\u0CCD\u0C95\u0CC6 \u0C86\u0C97\u0CC1\u0CA6\u0CC1 \u0C87\u0CB2\u0CCD\u0CB2", FirefoxCantLoadWebFont: "\u0CAB\u0CC8\u0CB0\u0CCD\u0CAB\u0CBE\u0C95\u0CCD\u0CB8\u0CCD \u0C87\u0C97\u0CC6 \u0C92\u0C82\u0CA6\u0CC1 \u0CA6\u0CC2\u0CB0\u0CA6\u0CCD\u0CA6\u0CC1 \u0CB9\u0CCB\u0CB8\u0CCD\u0C9F\u0CCD \u0C87\u0C82\u0CA6 \u0CB5\u0CC6\u0CAC\u0CCD \u0CAB\u0CBE\u0C82\u0C9F\u0CCD \u0C97\u0CB3\u0CA8\u0CCD\u0CA8 \u0C87\u0CA8\u0CCD\u0CB8\u0CCD\u0C9F\u0CBE\u0CB2\u0CCD \u0CAE\u0CBE\u0CA1\u0CB2\u0CBF\u0C95\u0CCD\u0C95\u0CC6 \u0C86\u0C97\u0CC1\u0CA6\u0CBF\u0CB2\u0CCD\u0CB2.", CantFindFontUsing: "%1 \u0C92\u0C9F\u0CCD\u0C9F\u0CBF\u0C97\u0CC6 \u0C92\u0C82\u0CA6\u0CC1 \u0CB8\u0CB0\u0CBF\u0CAF\u0CBE\u0CA6 \u0CAB\u0CBE\u0C82\u0C9F\u0CCD \u0CB8\u0CBF\u0C97\u0CC1\u0CA4 \u0C87\u0CB2\u0CCD\u0CB2", WebFontsNotAvailable: "\u0CB5\u0CC6\u0CAC\u0CCD \u0CAB\u0CBE\u0C82\u0C9F\u0CCD \u0C97\u0CB3\u0CC1 \u0CB8\u0CBF\u0C97\u0CC1\u0CA4 \u0C87\u0CB2\u0CCD\u0CB2, \u0C9A\u0CBF\u0CA4\u0CCD\u0CB0 \u0CAB\u0CBE\u0C82\u0C9F\u0CCD \u0C97\u0CB3\u0CA8\u0CCD\u0CA8 \u0C89\u0CAA\u0CAF\u0CCB\u0C97 \u0CAE\u0CBE\u0CA1\u0CBF." } }); MathJax.Ajax.loadComplete("[MathJax]/localization/kn/HTML-CSS.js");
'use strict' import React, {Component} from 'react'; class EmailItem extends Component { render() { let email = this.props.email; return( <div className="input-group"> <span className={this._getClassNames(email)} onClick={this._editHandler.bind(this)}>{email}</span> <span className="input-group-btn"> <button className="btn btn-default EmailManager-emailItem-removeButton" type="button" onClick={this._removeHandler.bind(this)}> <span className="glyphicon glyphicon-remove" aria-hidden="true"></span> </button> </span> </div> ); } _getClassNames(email) { let classes = ['EmailManager-emailItem-selectableRow']; if( !this._isEmail(email) ){ classes.push('EmailManager-emailItem-error'); } return classes.join(' '); }; _editHandler() { this.props.onEdit( this.props.email ); } _removeHandler() { this.props.onRemove( this.props.email ); } _isEmail(email) { return this.props.validation(email); } } EmailItem.defaultProps = { email: '', onEdit: () => {}, onRemove: () => {}, validation: (email) => { let re = /[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/; return re.test(email); } }; export default EmailItem;
""" Grammar-related utility functions. """ from typing import List from django.db.models import Count from lexicon.models import LexicalItem from .models import ( Derivation, DerivationStep, GeneratorDescription, LexicalArrayItem, RuleDescription, ) def get_derivation_by_lexical_array(lexical_array: List[LexicalItem]) -> Derivation: """ Creates or retrieves the Derivation associated with a unique array of LexicalItems. :param lexical_array: :return: """ # We have to add `.filter()` once per lexical item/order pair, # because of the way ManyToMany filtering works. # We also add a count annotation to make sure we don't pick up # any Derivations that start with the same lexical items, # but whose lexical arrays continue after. existing = Derivation.objects.annotate( count=Count("first_step__lexical_array_items") ).filter(count=len(lexical_array)) for [idx, lexical_item] in enumerate(lexical_array): existing = existing.filter( first_step__lexical_array_items__lexical_item=lexical_item, first_step__lexical_array_items__order=idx, ) if len(existing) > 0: return existing.get() else: return create_derivation(lexical_array) def create_derivation(lexical_array: List[LexicalItem]) -> Derivation: """ Given an array of LexicalItems, create a corresponding Derivation :param lexical_array: :return: """ # Start with a DerivationStep first_step = DerivationStep.objects.create() for [idx, lexical_item] in enumerate(lexical_array): LexicalArrayItem.objects.create( derivation_step=first_step, lexical_item=lexical_item, order=idx ) # For now, add all rules and generators first_step.rules.set(RuleDescription.objects.all()) first_step.generators.set(GeneratorDescription.objects.all()) # External merge only variant # first_step.generators.add( # GeneratorDescription.objects.get(name="external-merge") # ) # Create and return a Derivation derivation = Derivation.objects.create(first_step=first_step) first_step.derivation = derivation first_step.save() return derivation
const { exec } = require("child_process"); const fs = require("fs"); const util = require("util"); const execPromisified = util.promisify(exec); const fetchRepopath = require("../global/fetchGitRepoPath"); /** * @param {String} repoId * @param {String} item * @returns {String} - status of the unstaging action * @description - Removed the selected item from staged area */ const gitRemoveStagedItemApi = async (repoId, item) => { const repopath = fetchRepopath.getRepoPath(repoId); const fileItemValid = await fs.promises .stat(repopath + "/" + item) .then((res) => res.isFile()); if (!fileItemValid) { console.log("Invalid item string"); return "STAGE_REMOVE_FAILED"; } return await execPromisified(`git reset "${item}"`, { cwd: repopath, windowsHide: true, }) .then(({ stdout, stderr }) => { if (stderr) { console.log(stderr); return "STAGE_REMOVE_FAILED"; } else { console.log(stdout); return "STAGE_REMOVE_SUCCESS"; } }) .catch((err) => { console.log(err); return "STAGE_REMOVE_FAILED"; }); }; /** * @param {String} repoId * @returns {String} * @description - removes all the the staged items */ const gitRemoveAllStagedItemApi = async (repoId) => { return await execPromisified(`git reset`, { cwd: fetchRepopath.getRepoPath(repoId), windowsHide: true, }) .then(({ stdout, stderr }) => { if (stderr) { console.log(stderr); return "STAGE_ALL_REMOVE_FAILED"; } else { console.log(stdout); return "STAGE_ALL_REMOVE_SUCCESS"; } }) .catch((err) => { console.log(err); return "STAGE_ALL_REMOVE_FAILED"; }); }; module.exports.gitRemoveStagedItemApi = gitRemoveStagedItemApi; module.exports.gitRemoveAllStagedItemApi = gitRemoveAllStagedItemApi;
import { ethers } from "ethers"; import sdk from "./1-initialize-sdk.js"; // This is our governance contract. const voteModule = sdk.getVoteModule( "0x180924387cC925C453A41A9961c41f2FEe4609b1", ); // This is our ERC-20 contract. const tokenModule = sdk.getTokenModule( "0xe1c22e50cb9142088fb798e663a26dd2d0c92cbc", ); (async () => { try { // Give our treasury the power to mint additional token if needed. await tokenModule.grantRole("minter", voteModule.address); console.log( "Successfully gave vote module permissions to act on token module" ); } catch (error) { console.error( "failed to grant vote module permissions on token module", error ); process.exit(1); } try { // Grab our wallet's token balance, remember -- we hold basically the entire supply right now! const ownedTokenBalance = await tokenModule.balanceOf( process.env.WALLET_ADDRESS ); // Grab 90% of the supply that we hold. const ownedAmount = ethers.BigNumber.from(ownedTokenBalance.value); const percent90 = ownedAmount.div(100).mul(90); // Transfer 90% of the supply to our voting contract. await tokenModule.transfer( voteModule.address, percent90 ); console.log("✅ Successfully transferred tokens to vote module"); } catch (err) { console.error("failed to transfer tokens to vote module", err); } })();
from smartmin.users.views import UserCRUDL as SmartUserCRUDL class UserCRUDL(SmartUserCRUDL): actions = ("create", "list", "update", "profile", "forget", "recover", "expired", "failed", "newpassword", "mimic") class Create(SmartUserCRUDL.Create): fields = ("username", "new_password", "first_name", "last_name", "email", "groups") class Update(SmartUserCRUDL.Update): fields = ("username", "new_password", "first_name", "last_name", "email", "is_active", "last_login", "groups") class Profile(SmartUserCRUDL.Profile): fields = ( "username", "first_name", "last_name", "email", "old_password", "new_password", "confirm_new_password", ) def pre_save(self, obj): obj = super(UserCRUDL.Profile, self).pre_save(obj) # keep our username and email in sync obj.username = obj.email return obj def has_permission(self, request, *args, **kwargs): return self.request.user.is_authenticated
// Karma configuration // http://karma-runner.github.io/0.10/config/configuration-file.html module.exports = function (config) { config.set({ // base path, that will be used to resolve files and exclude basePath: '../../', // testing framework to use (jasmine/mocha/qunit/...) frameworks: ['jasmine'], // list of files / patterns to load in the browser files: [ 'main/webapp/bower_components/modernizr/modernizr.js', 'main/webapp/bower_components/jquery/dist/jquery.js', 'main/webapp/bower_components/angular/angular.js', 'main/webapp/bower_components/angular-mocks/angular-mocks.js', 'main/webapp/bower_components/angular-ui-router/release/angular-ui-router.js', 'main/webapp/bower_components/angular-resource/angular-resource.js', 'main/webapp/bower_components/angular-cookies/angular-cookies.js', 'main/webapp/bower_components/angular-sanitize/angular-sanitize.js', 'main/webapp/bower_components/angular-translate/angular-translate.js', 'main/webapp/bower_components/angular-translate-storage-cookie/angular-translate-storage-cookie.js', 'main/webapp/bower_components/angular-translate-loader-partial/angular-translate-loader-partial.js', 'main/webapp/bower_components/angular-dynamic-locale/src/tmhDynamicLocale.js', 'main/webapp/bower_components/angular-local-storage/dist/angular-local-storage.min.js', 'main/webapp/bower_components/angular-cache-buster/angular-cache-buster.js',<% if (websocket == 'spring-websocket') { %> 'main/webapp/bower_components/stomp-websocket/lib/stomp.js', 'main/webapp/bower_components/sockjs-client/dist/sockjs.js',<% } %> 'main/webapp/scripts/app/app.js', 'main/webapp/scripts/app/**/*.js', 'main/webapp/scripts/components/**/*.js', 'test/javascript/**/!(karma.conf).js' ], // list of files / patterns to exclude exclude: [], // web server port port: 9876, // level of logging // possible values: LOG_DISABLE || LOG_ERROR || LOG_WARN || LOG_INFO || LOG_DEBUG logLevel: config.LOG_INFO, // enable / disable watching file and executing tests whenever any file changes autoWatch: false, // Start these browsers, currently available: // - Chrome // - ChromeCanary // - Firefox // - Opera // - Safari (only Mac) // - PhantomJS // - IE (only Windows) browsers: ['PhantomJS'], // Continuous Integration mode // if true, it capture browsers, run tests and exit singleRun: false }); };
# coding: utf8 from __future__ import unicode_literals from spacy.matcher import Matcher from spacy.tokens import Doc def test_issue4120(en_vocab): """Test that matches without a final {OP: ?} token are returned.""" matcher = Matcher(en_vocab) matcher.add("TEST", [[{"ORTH": "a"}, {"OP": "?"}]]) doc1 = Doc(en_vocab, words=["a"]) assert len(matcher(doc1)) == 1 # works doc2 = Doc(en_vocab, words=["a", "b", "c"]) assert len(matcher(doc2)) == 2 # fixed matcher = Matcher(en_vocab) matcher.add("TEST", [[{"ORTH": "a"}, {"OP": "?"}, {"ORTH": "b"}]]) doc3 = Doc(en_vocab, words=["a", "b", "b", "c"]) assert len(matcher(doc3)) == 2 # works matcher = Matcher(en_vocab) matcher.add("TEST", [[{"ORTH": "a"}, {"OP": "?"}, {"ORTH": "b", "OP": "?"}]]) doc4 = Doc(en_vocab, words=["a", "b", "b", "c"]) assert len(matcher(doc4)) == 3 # fixed
"use strict";(self.webpackChunk_JUPYTERLAB_CORE_OUTPUT=self.webpackChunk_JUPYTERLAB_CORE_OUTPUT||[]).push([[9537],{71717:(r,n,c)=>{c.d(n,{Z:()=>i});var a=c(1799),e=c.n(a),o=c(82609),t=c.n(o)()(e());t.push([r.id,"/*\n\n Name: dracula\n Author: Michael Kaminsky (http://github.com/mkaminsky11)\n\n Original dracula color scheme by Zeno Rocha (https://github.com/zenorocha/dracula-theme)\n\n*/\n\n\n.cm-s-dracula.CodeMirror, .cm-s-dracula .CodeMirror-gutters {\n background-color: #282a36 !important;\n color: #f8f8f2 !important;\n border: none;\n}\n.cm-s-dracula .CodeMirror-gutters { color: #282a36; }\n.cm-s-dracula .CodeMirror-cursor { border-left: solid thin #f8f8f0; }\n.cm-s-dracula .CodeMirror-linenumber { color: #6D8A88; }\n.cm-s-dracula .CodeMirror-selected { background: rgba(255, 255, 255, 0.10); }\n.cm-s-dracula .CodeMirror-line::selection, .cm-s-dracula .CodeMirror-line > span::selection, .cm-s-dracula .CodeMirror-line > span > span::selection { background: rgba(255, 255, 255, 0.10); }\n.cm-s-dracula .CodeMirror-line::-moz-selection, .cm-s-dracula .CodeMirror-line > span::-moz-selection, .cm-s-dracula .CodeMirror-line > span > span::-moz-selection { background: rgba(255, 255, 255, 0.10); }\n.cm-s-dracula span.cm-comment { color: #6272a4; }\n.cm-s-dracula span.cm-string, .cm-s-dracula span.cm-string-2 { color: #f1fa8c; }\n.cm-s-dracula span.cm-number { color: #bd93f9; }\n.cm-s-dracula span.cm-variable { color: #50fa7b; }\n.cm-s-dracula span.cm-variable-2 { color: white; }\n.cm-s-dracula span.cm-def { color: #50fa7b; }\n.cm-s-dracula span.cm-operator { color: #ff79c6; }\n.cm-s-dracula span.cm-keyword { color: #ff79c6; }\n.cm-s-dracula span.cm-atom { color: #bd93f9; }\n.cm-s-dracula span.cm-meta { color: #f8f8f2; }\n.cm-s-dracula span.cm-tag { color: #ff79c6; }\n.cm-s-dracula span.cm-attribute { color: #50fa7b; }\n.cm-s-dracula span.cm-qualifier { color: #50fa7b; }\n.cm-s-dracula span.cm-property { color: #66d9ef; }\n.cm-s-dracula span.cm-builtin { color: #50fa7b; }\n.cm-s-dracula span.cm-variable-3, .cm-s-dracula span.cm-type { color: #ffb86c; }\n\n.cm-s-dracula .CodeMirror-activeline-background { background: rgba(255,255,255,0.1); }\n.cm-s-dracula .CodeMirror-matchingbracket { text-decoration: underline; color: white !important; }\n","",{version:3,sources:["webpack://./../../node_modules/codemirror/theme/dracula.css"],names:[],mappings:"AAAA;;;;;;;CAOC;;;AAGD;EACE,oCAAoC;EACpC,yBAAyB;EACzB,YAAY;AACd;AACA,oCAAoC,cAAc,EAAE;AACpD,mCAAmC,+BAA+B,EAAE;AACpE,uCAAuC,cAAc,EAAE;AACvD,qCAAqC,qCAAqC,EAAE;AAC5E,uJAAuJ,qCAAqC,EAAE;AAC9L,sKAAsK,qCAAqC,EAAE;AAC7M,gCAAgC,cAAc,EAAE;AAChD,+DAA+D,cAAc,EAAE;AAC/E,+BAA+B,cAAc,EAAE;AAC/C,iCAAiC,cAAc,EAAE;AACjD,mCAAmC,YAAY,EAAE;AACjD,4BAA4B,cAAc,EAAE;AAC5C,iCAAiC,cAAc,EAAE;AACjD,gCAAgC,cAAc,EAAE;AAChD,6BAA6B,cAAc,EAAE;AAC7C,6BAA6B,cAAc,EAAE;AAC7C,4BAA4B,cAAc,EAAE;AAC5C,kCAAkC,cAAc,EAAE;AAClD,kCAAkC,cAAc,EAAE;AAClD,iCAAiC,cAAc,EAAE;AACjD,gCAAgC,cAAc,EAAE;AAChD,+DAA+D,cAAc,EAAE;;AAE/E,kDAAkD,iCAAiC,EAAE;AACrF,4CAA4C,0BAA0B,EAAE,uBAAuB,EAAE",sourcesContent:["/*\n\n Name: dracula\n Author: Michael Kaminsky (http://github.com/mkaminsky11)\n\n Original dracula color scheme by Zeno Rocha (https://github.com/zenorocha/dracula-theme)\n\n*/\n\n\n.cm-s-dracula.CodeMirror, .cm-s-dracula .CodeMirror-gutters {\n background-color: #282a36 !important;\n color: #f8f8f2 !important;\n border: none;\n}\n.cm-s-dracula .CodeMirror-gutters { color: #282a36; }\n.cm-s-dracula .CodeMirror-cursor { border-left: solid thin #f8f8f0; }\n.cm-s-dracula .CodeMirror-linenumber { color: #6D8A88; }\n.cm-s-dracula .CodeMirror-selected { background: rgba(255, 255, 255, 0.10); }\n.cm-s-dracula .CodeMirror-line::selection, .cm-s-dracula .CodeMirror-line > span::selection, .cm-s-dracula .CodeMirror-line > span > span::selection { background: rgba(255, 255, 255, 0.10); }\n.cm-s-dracula .CodeMirror-line::-moz-selection, .cm-s-dracula .CodeMirror-line > span::-moz-selection, .cm-s-dracula .CodeMirror-line > span > span::-moz-selection { background: rgba(255, 255, 255, 0.10); }\n.cm-s-dracula span.cm-comment { color: #6272a4; }\n.cm-s-dracula span.cm-string, .cm-s-dracula span.cm-string-2 { color: #f1fa8c; }\n.cm-s-dracula span.cm-number { color: #bd93f9; }\n.cm-s-dracula span.cm-variable { color: #50fa7b; }\n.cm-s-dracula span.cm-variable-2 { color: white; }\n.cm-s-dracula span.cm-def { color: #50fa7b; }\n.cm-s-dracula span.cm-operator { color: #ff79c6; }\n.cm-s-dracula span.cm-keyword { color: #ff79c6; }\n.cm-s-dracula span.cm-atom { color: #bd93f9; }\n.cm-s-dracula span.cm-meta { color: #f8f8f2; }\n.cm-s-dracula span.cm-tag { color: #ff79c6; }\n.cm-s-dracula span.cm-attribute { color: #50fa7b; }\n.cm-s-dracula span.cm-qualifier { color: #50fa7b; }\n.cm-s-dracula span.cm-property { color: #66d9ef; }\n.cm-s-dracula span.cm-builtin { color: #50fa7b; }\n.cm-s-dracula span.cm-variable-3, .cm-s-dracula span.cm-type { color: #ffb86c; }\n\n.cm-s-dracula .CodeMirror-activeline-background { background: rgba(255,255,255,0.1); }\n.cm-s-dracula .CodeMirror-matchingbracket { text-decoration: underline; color: white !important; }\n"],sourceRoot:""}]);const i=t},82609:r=>{r.exports=function(r){var n=[];return n.toString=function(){return this.map((function(n){var c=r(n);return n[2]?"@media ".concat(n[2]," {").concat(c,"}"):c})).join("")},n.i=function(r,c,a){"string"==typeof r&&(r=[[null,r,""]]);var e={};if(a)for(var o=0;o<this.length;o++){var t=this[o][0];null!=t&&(e[t]=!0)}for(var i=0;i<r.length;i++){var l=[].concat(r[i]);a&&e[l[0]]||(c&&(l[2]?l[2]="".concat(c," and ").concat(l[2]):l[2]=c),n.push(l))}},n}},1799:r=>{function n(r,n){(null==n||n>r.length)&&(n=r.length);for(var c=0,a=new Array(n);c<n;c++)a[c]=r[c];return a}r.exports=function(r){var c,a,e=(a=4,function(r){if(Array.isArray(r))return r}(c=r)||function(r,n){var c=r&&("undefined"!=typeof Symbol&&r[Symbol.iterator]||r["@@iterator"]);if(null!=c){var a,e,o=[],t=!0,i=!1;try{for(c=c.call(r);!(t=(a=c.next()).done)&&(o.push(a.value),!n||o.length!==n);t=!0);}catch(r){i=!0,e=r}finally{try{t||null==c.return||c.return()}finally{if(i)throw e}}return o}}(c,a)||function(r,c){if(r){if("string"==typeof r)return n(r,c);var a=Object.prototype.toString.call(r).slice(8,-1);return"Object"===a&&r.constructor&&(a=r.constructor.name),"Map"===a||"Set"===a?Array.from(r):"Arguments"===a||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(a)?n(r,c):void 0}}(c,a)||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.")}()),o=e[1],t=e[3];if(!t)return o;if("function"==typeof btoa){var i=btoa(unescape(encodeURIComponent(JSON.stringify(t)))),l="sourceMappingURL=data:application/json;charset=utf-8;base64,".concat(i),s="/*# ".concat(l," */"),A=t.sources.map((function(r){return"/*# sourceURL=".concat(t.sourceRoot||"").concat(r," */")}));return[o].concat(A).concat([s]).join("\n")}return[o].join("\n")}},29537:(r,n,c)=>{c.r(n),c.d(n,{default:()=>t});var a=c(46062),e=c.n(a),o=c(71717);e()(o.Z,{insert:"head",singleton:!1});const t=o.Z.locals||{}},46062:(r,n,c)=>{var a,e=function(){var r={};return function(n){if(void 0===r[n]){var c=document.querySelector(n);if(window.HTMLIFrameElement&&c instanceof window.HTMLIFrameElement)try{c=c.contentDocument.head}catch(r){c=null}r[n]=c}return r[n]}}(),o=[];function t(r){for(var n=-1,c=0;c<o.length;c++)if(o[c].identifier===r){n=c;break}return n}function i(r,n){for(var c={},a=[],e=0;e<r.length;e++){var i=r[e],l=n.base?i[0]+n.base:i[0],s=c[l]||0,A="".concat(l," ").concat(s);c[l]=s+1;var u=t(A),d={css:i[1],media:i[2],sourceMap:i[3]};-1!==u?(o[u].references++,o[u].updater(d)):o.push({identifier:A,updater:p(d,n),references:1}),a.push(A)}return a}function l(r){var n=document.createElement("style"),a=r.attributes||{};if(void 0===a.nonce){var o=c.nc;o&&(a.nonce=o)}if(Object.keys(a).forEach((function(r){n.setAttribute(r,a[r])})),"function"==typeof r.insert)r.insert(n);else{var t=e(r.insert||"head");if(!t)throw new Error("Couldn't find a style target. This probably means that the value for the 'insert' parameter is invalid.");t.appendChild(n)}return n}var s,A=(s=[],function(r,n){return s[r]=n,s.filter(Boolean).join("\n")});function u(r,n,c,a){var e=c?"":a.media?"@media ".concat(a.media," {").concat(a.css,"}"):a.css;if(r.styleSheet)r.styleSheet.cssText=A(n,e);else{var o=document.createTextNode(e),t=r.childNodes;t[n]&&r.removeChild(t[n]),t.length?r.insertBefore(o,t[n]):r.appendChild(o)}}function d(r,n,c){var a=c.css,e=c.media,o=c.sourceMap;if(e?r.setAttribute("media",e):r.removeAttribute("media"),o&&"undefined"!=typeof btoa&&(a+="\n/*# sourceMappingURL=data:application/json;base64,".concat(btoa(unescape(encodeURIComponent(JSON.stringify(o))))," */")),r.styleSheet)r.styleSheet.cssText=a;else{for(;r.firstChild;)r.removeChild(r.firstChild);r.appendChild(document.createTextNode(a))}}var m=null,f=0;function p(r,n){var c,a,e;if(n.singleton){var o=f++;c=m||(m=l(n)),a=u.bind(null,c,o,!1),e=u.bind(null,c,o,!0)}else c=l(n),a=d.bind(null,c,n),e=function(){!function(r){if(null===r.parentNode)return!1;r.parentNode.removeChild(r)}(c)};return a(r),function(n){if(n){if(n.css===r.css&&n.media===r.media&&n.sourceMap===r.sourceMap)return;a(r=n)}else e()}}r.exports=function(r,n){(n=n||{}).singleton||"boolean"==typeof n.singleton||(n.singleton=(void 0===a&&(a=Boolean(window&&document&&document.all&&!window.atob)),a));var c=i(r=r||[],n);return function(r){if(r=r||[],"[object Array]"===Object.prototype.toString.call(r)){for(var a=0;a<c.length;a++){var e=t(c[a]);o[e].references--}for(var l=i(r,n),s=0;s<c.length;s++){var A=t(c[s]);0===o[A].references&&(o[A].updater(),o.splice(A,1))}c=l}}}}}]); //# sourceMappingURL=9537.50029467af4f96036ee6.js.map
define("dojo/window", ["./_base/lang", "./sniff", "./_base/window", "./dom", "./dom-geometry", "./dom-style", "./dom-construct"], function(lang, has, baseWindow, dom, geom, style, domConstruct){ // feature detection /* not needed but included here for future reference has.add("rtl-innerVerticalScrollBar-on-left", function(win, doc){ var body = baseWindow.body(doc), scrollable = domConstruct.create('div', { style: {overflow:'scroll', overflowX:'hidden', direction:'rtl', visibility:'hidden', position:'absolute', left:'0', width:'64px', height:'64px'} }, body, "last"), center = domConstruct.create('center', { style: {overflow:'hidden', direction:'ltr'} }, scrollable, "last"), inner = domConstruct.create('div', { style: {overflow:'visible', display:'inline' } }, center, "last"); inner.innerHTML="&nbsp;"; var midPoint = Math.max(inner.offsetLeft, geom.position(inner).x); var ret = midPoint >= 32; center.removeChild(inner); scrollable.removeChild(center); body.removeChild(scrollable); return ret; }); */ has.add("rtl-adjust-position-for-verticalScrollBar", function(win, doc){ var body = baseWindow.body(doc), scrollable = domConstruct.create('div', { style: {overflow:'scroll', overflowX:'visible', direction:'rtl', visibility:'hidden', position:'absolute', left:'0', top:'0', width:'64px', height:'64px'} }, body, "last"), div = domConstruct.create('div', { style: {overflow:'hidden', direction:'ltr'} }, scrollable, "last"), ret = geom.position(div).x != 0; scrollable.removeChild(div); body.removeChild(scrollable); return ret; }); has.add("position-fixed-support", function(win, doc){ // IE6, IE7+quirks, and some older mobile browsers don't support position:fixed var body = baseWindow.body(doc), outer = domConstruct.create('span', { style: {visibility:'hidden', position:'fixed', left:'1px', top:'1px'} }, body, "last"), inner = domConstruct.create('span', { style: {position:'fixed', left:'0', top:'0'} }, outer, "last"), ret = geom.position(inner).x != geom.position(outer).x; outer.removeChild(inner); body.removeChild(outer); return ret; }); // module: // dojo/window var window = { // summary: // TODOC getBox: function(/*Document?*/ doc){ // summary: // Returns the dimensions and scroll position of the viewable area of a browser window doc = doc || baseWindow.doc; var scrollRoot = (doc.compatMode == 'BackCompat') ? baseWindow.body(doc) : doc.documentElement, // get scroll position scroll = geom.docScroll(doc), // scrollRoot.scrollTop/Left should work w, h; if(has("touch")){ // if(scrollbars not supported) var uiWindow = window.get(doc); // use UI window, not dojo.global window // on mobile, scrollRoot.clientHeight <= uiWindow.innerHeight <= scrollRoot.offsetHeight, return uiWindow.innerHeight w = uiWindow.innerWidth || scrollRoot.clientWidth; // || scrollRoot.clientXXX probably never evaluated h = uiWindow.innerHeight || scrollRoot.clientHeight; }else{ // on desktops, scrollRoot.clientHeight <= scrollRoot.offsetHeight <= uiWindow.innerHeight, return scrollRoot.clientHeight // uiWindow.innerWidth/Height includes the scrollbar and cannot be used w = scrollRoot.clientWidth; h = scrollRoot.clientHeight; } return { l: scroll.x, t: scroll.y, w: w, h: h }; }, get: function(/*Document*/ doc){ // summary: // Get window object associated with document doc. // doc: // The document to get the associated window for. // In some IE versions (at least 6.0), document.parentWindow does not return a // reference to the real window object (maybe a copy), so we must fix it as well // We use IE specific execScript to attach the real window reference to // document._parentWindow for later use if(has("ie") && window !== document.parentWindow){ /* In IE 6, only the variable "window" can be used to connect events (others may be only copies). */ doc.parentWindow.execScript("document._parentWindow = window;", "Javascript"); //to prevent memory leak, unset it after use //another possibility is to add an onUnload handler which seems overkill to me (liucougar) var win = doc._parentWindow; doc._parentWindow = null; return win; // Window } return doc.parentWindow || doc.defaultView; // Window }, scrollIntoView: function(/*DomNode*/ node, /*Object?*/ pos){ // summary: // Scroll the passed node into view using minimal movement, if it is not already. // Don't rely on node.scrollIntoView working just because the function is there since // it forces the node to the page's bottom or top (and left or right in IE) without consideration for the minimal movement. // WebKit's node.scrollIntoViewIfNeeded doesn't work either for inner scrollbars in right-to-left mode // and when there's a fixed position scrollable element try{ // catch unexpected/unrecreatable errors (#7808) since we can recover using a semi-acceptable native method node = dom.byId(node); var doc = node.ownerDocument || baseWindow.doc, // TODO: why baseWindow.doc? Isn't node.ownerDocument always defined? body = baseWindow.body(doc), html = doc.documentElement || body.parentNode, isIE = has("ie"), isWK = has("webkit"); // if an untested browser, then use the native method if(node == body || node == html){ return; } if(!(has("mozilla") || isIE || isWK || has("opera") || has("trident")) && ("scrollIntoView" in node)){ node.scrollIntoView(false); // short-circuit to native if possible return; } var backCompat = doc.compatMode == 'BackCompat', rootWidth = Math.min(body.clientWidth || html.clientWidth, html.clientWidth || body.clientWidth), rootHeight = Math.min(body.clientHeight || html.clientHeight, html.clientHeight || body.clientHeight), scrollRoot = (isWK || backCompat) ? body : html, nodePos = pos || geom.position(node), el = node.parentNode, isFixed = function(el){ return (isIE <= 6 || (isIE == 7 && backCompat)) ? false : (has("position-fixed-support") && (style.get(el, 'position').toLowerCase() == "fixed")); }, self = this, scrollElementBy = function(el, x, y){ if(el.tagName == "BODY" || el.tagName == "HTML"){ self.get(el.ownerDocument).scrollBy(x, y); }else{ x && (el.scrollLeft += x); y && (el.scrollTop += y); } }; if(isFixed(node)){ return; } // nothing to do while(el){ if(el == body){ el = scrollRoot; } var elPos = geom.position(el), fixedPos = isFixed(el), rtl = style.getComputedStyle(el).direction.toLowerCase() == "rtl"; if(el == scrollRoot){ elPos.w = rootWidth; elPos.h = rootHeight; if(scrollRoot == html && (isIE || has("trident")) && rtl){ elPos.x += scrollRoot.offsetWidth-elPos.w;// IE workaround where scrollbar causes negative x } elPos.x = 0; elPos.y = 0; }else{ var pb = geom.getPadBorderExtents(el); elPos.w -= pb.w; elPos.h -= pb.h; elPos.x += pb.l; elPos.y += pb.t; var clientSize = el.clientWidth, scrollBarSize = elPos.w - clientSize; if(clientSize > 0 && scrollBarSize > 0){ if(rtl && has("rtl-adjust-position-for-verticalScrollBar")){ elPos.x += scrollBarSize; } elPos.w = clientSize; } clientSize = el.clientHeight; scrollBarSize = elPos.h - clientSize; if(clientSize > 0 && scrollBarSize > 0){ elPos.h = clientSize; } } if(fixedPos){ // bounded by viewport, not parents if(elPos.y < 0){ elPos.h += elPos.y; elPos.y = 0; } if(elPos.x < 0){ elPos.w += elPos.x; elPos.x = 0; } if(elPos.y + elPos.h > rootHeight){ elPos.h = rootHeight - elPos.y; } if(elPos.x + elPos.w > rootWidth){ elPos.w = rootWidth - elPos.x; } } // calculate overflow in all 4 directions var l = nodePos.x - elPos.x, // beyond left: < 0 // t = nodePos.y - Math.max(elPos.y, 0), // beyond top: < 0 t = nodePos.y - elPos.y, // beyond top: < 0 r = l + nodePos.w - elPos.w, // beyond right: > 0 bot = t + nodePos.h - elPos.h; // beyond bottom: > 0 var s, old; if(r * l > 0 && (!!el.scrollLeft || el == scrollRoot || el.scrollWidth > el.offsetHeight)){ s = Math[l < 0? "max" : "min"](l, r); if(rtl && ((isIE == 8 && !backCompat) || has("trident") >= 5)){ s = -s; } old = el.scrollLeft; scrollElementBy(el, s, 0); s = el.scrollLeft - old; nodePos.x -= s; } if(bot * t > 0 && (!!el.scrollTop || el == scrollRoot || el.scrollHeight > el.offsetHeight)){ s = Math.ceil(Math[t < 0? "max" : "min"](t, bot)); old = el.scrollTop; scrollElementBy(el, 0, s); s = el.scrollTop - old; nodePos.y -= s; } el = (el != scrollRoot) && !fixedPos && el.parentNode; } }catch(error){ console.error('scrollIntoView: ' + error); node.scrollIntoView(false); } } }; 1 && lang.setObject("dojo.window", window); return window; });
import ReactDOM from 'react-dom' import {Provider} from 'react-redux' import React from 'react' import { Router, Route, IndexRoute, browserHistory, hashHistory, } from 'react-router' import createStore from './store' import App from './screens/app' import Article from './screens/article' import Editor from './screens/editor' import Home from './screens/home' import Login from './screens/login' import ConnectedProfile from './screens/profile' import ProfileFavorites from './screens/profile-favorites' import Register from './screens/register' import Settings from './screens/settings' ReactDOM.render( <Provider store={createStore()}> <Router history={ process.env.NODE_ENV === 'production' ? browserHistory : hashHistory } > <Route path="/" component={App}> <IndexRoute component={Home} /> <Route path="login" component={Login} /> <Route path="register" component={Register} /> <Route path="editor" component={Editor} /> <Route path="editor/:slug" component={Editor} /> <Route path="article/:id" component={Article} /> <Route path="settings" component={Settings} /> <Route path="@:username" component={ConnectedProfile} /> <Route path="@:username/favorites" component={ProfileFavorites} /> </Route> </Router> </Provider>, document.getElementById('root'), )
/*! * Module dependencies. */ var Document = require('../document') , inspect = require('util').inspect; /** * EmbeddedDocument constructor. * * @param {Object} obj js object returned from the db * @param {MongooseDocumentArray} parentArr the parent array of this document * @param {Boolean} skipId * @inherits Document * @api private */ function EmbeddedDocument (obj, parentArr, skipId) { if (parentArr) { this.__parentArray = parentArr; this.__parent = parentArr._parent; } else { this.__parentArray = undefined; this.__parent = undefined; } Document.call(this, obj, undefined, skipId); var self = this; this.on('isNew', function (val) { self.isNew = val; }); }; /*! * Inherit from Document */ EmbeddedDocument.prototype.__proto__ = Document.prototype; /** * Marks the embedded doc modified. * * ####Example: * * var doc = blogpost.comments.id(hexstring); * doc.mixed.type = 'changed'; * doc.markModified('mixed.type'); * * @param {String} path the path which changed * @api public */ EmbeddedDocument.prototype.markModified = function (path) { if (!this.__parentArray) return; this._activePaths.modify(path); if (this.isNew) { // Mark the WHOLE parent array as modified // if this is a new document (i.e., we are initializing // a document), this.__parentArray._markModified(); } else this.__parentArray._markModified(this, path); }; /** * Used as a stub for [hooks.js](https://github.com/bnoguchi/hooks-js/tree/31ec571cef0332e21121ee7157e0cf9728572cc3) * * ####NOTE: * * _This is a no-op. Does not actually save the doc to the db._ * * @param {Function} [fn] * @return {EmbeddedDocument} this * @api private */ EmbeddedDocument.prototype.save = function(fn) { if (fn) fn(null); return this; }; /** * Removes the subdocument from its parent array. * * @param {Function} [fn] * @api public */ EmbeddedDocument.prototype.remove = function (fn) { if (!this.__parentArray) return this; var _id; if (!this.willRemove) { _id = this._doc._id; if (!_id) { throw new Error('For your own good, Mongoose does not know ' + 'how to remove an EmbeddedDocument that has no _id'); } this.__parentArray.pull({ _id: _id }); this.willRemove = true; } if (fn) fn(null); return this; }; /** * Override #update method of parent documents. * @api private */ EmbeddedDocument.prototype.update = function () { throw new Error('The #update method is not available on EmbeddedDocuments'); } /** * Helper for console.log * * @api public */ EmbeddedDocument.prototype.inspect = function () { return inspect(this.toObject()); }; /** * Marks a path as invalid, causing validation to fail. * * @param {String} path the field to invalidate * @param {String|Error} err error which states the reason `path` was invalid * @return {Boolean} * @api public */ EmbeddedDocument.prototype.invalidate = function (path, err, first) { if (!this.__parent) return false; var index = this.__parentArray.indexOf(this); var parentPath = this.__parentArray._path; var fullPath = [parentPath, index, path].join('.'); this.__parent.invalidate(fullPath, err); if (first) this._validationError = ownerDocument(this)._validationError; return true; } /** * Returns the top level document of this sub-document. * * @return {Document} */ EmbeddedDocument.prototype.ownerDocument = function () { return ownerDocument(this); } /*! * Returns the top level document of this sub-document. * * @return {Document} */ function ownerDocument (self) { var parent = self.__parent; while (parent.__parent) parent = parent.__parent; return parent; } /** * Returns this sub-documents parent document. * * @api public */ EmbeddedDocument.prototype.parent = function () { return this.__parent; } /** * Returns this sub-documents parent array. * * @api public */ EmbeddedDocument.prototype.parentArray = function () { return this.__parentArray; } /*! * Module exports. */ module.exports = EmbeddedDocument;
module.exports = { name: 'L3v5', description: "part of libray update", execute(message, args, Discord){ const LibraryEmbed = new Discord.MessageEmbed() .setColor('#E5FF00') .setTitle('L3v5') .addFields( {name: 'Info', value: 'Funny video about cats'} ) .setFooter('In discord watchable below') .setImage('https://upload.wikimedia.org/wikipedia/commons/thumb/e/e1/Logo_of_YouTube_%282015-2017%29.svg/1200px-Logo_of_YouTube_%282015-2017%29.svg.png') message.channel.send(LibraryEmbed); message.channel.send('https://www.youtube.com/watch?v=jHWKtQHXVJg'); } }
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright: (c) 2012, Michael DeHaan <michael.dehaan@gmail.com> # Copyright: (c) 2017, Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['stableinterface'], 'supported_by': 'core'} DOCUMENTATION = r''' --- module: file version_added: historical short_description: Manage files and file properties extends_documentation_fragment: files description: - Set attributes of files, symlinks or directories. - Alternatively, remove files, symlinks or directories. - Many other modules support the same options as the C(file) module - including M(copy), M(template), and M(assemble). - For Windows targets, use the M(win_file) module instead. options: path: description: - Path to the file being managed. type: path required: yes aliases: [ dest, name ] state: description: - If C(absent), directories will be recursively deleted, and files or symlinks will be unlinked. In the case of a directory, if C(diff) is declared, you will see the files and folders deleted listed under C(path_contents). Note that C(absent) will not cause C(file) to fail if the C(path) does not exist as the state did not change. - If C(directory), all intermediate subdirectories will be created if they do not exist. Since Ansible 1.7 they will be created with the supplied permissions. - If C(file), without any other options this works mostly as a 'stat' and will return the current state of C(path). Even with other options (i.e C(mode)), the file will be modified but will NOT be created if it does not exist; see the C(touch) value or the M(copy) or M(template) module if you want that behavior. - If C(hard), the hard link will be created or changed. - If C(link), the symbolic link will be created or changed. - If C(touch) (new in 1.4), an empty file will be created if the C(path) does not exist, while an existing file or directory will receive updated file access and modification times (similar to the way C(touch) works from the command line). type: str default: file choices: [ absent, directory, file, hard, link, touch ] src: description: - Path of the file to link to. - This applies only to C(state=link) and C(state=hard). - For C(state=link), this will also accept a non-existing path. - Relative paths are relative to the file being created (C(path)) which is how the Unix command C(ln -s SRC DEST) treats relative paths. type: path recurse: description: - Recursively set the specified file attributes on directory contents. - This applies only when C(state) is set to C(directory). type: bool default: no version_added: '1.1' force: description: - > Force the creation of the symlinks in two cases: the source file does not exist (but will appear later); the destination exists and is a file (so, we need to unlink the C(path) file and create symlink to the C(src) file in place of it). type: bool default: no follow: description: - This flag indicates that filesystem links, if they exist, should be followed. - Previous to Ansible 2.5, this was C(no) by default. type: bool default: yes version_added: '1.8' modification_time: description: - This parameter indicates the time the file's modification time should be set to. - Should be C(preserve) when no modification is required, C(YYYYMMDDHHMM.SS) when using default time format, or C(now). - Default is None meaning that C(preserve) is the default for C(state=[file,directory,link,hard]) and C(now) is default for C(state=touch). type: str version_added: "2.7" modification_time_format: description: - When used with C(modification_time), indicates the time format that must be used. - Based on default Python format (see time.strftime doc). type: str default: "%Y%m%d%H%M.%S" version_added: '2.7' access_time: description: - This parameter indicates the time the file's access time should be set to. - Should be C(preserve) when no modification is required, C(YYYYMMDDHHMM.SS) when using default time format, or C(now). - Default is C(None) meaning that C(preserve) is the default for C(state=[file,directory,link,hard]) and C(now) is default for C(state=touch). type: str version_added: '2.7' access_time_format: description: - When used with C(access_time), indicates the time format that must be used. - Based on default Python format (see time.strftime doc). type: str default: "%Y%m%d%H%M.%S" version_added: '2.7' seealso: - module: assemble - module: copy - module: stat - module: template - module: win_file author: - Ansible Core Team - Michael DeHaan ''' EXAMPLES = r''' - name: Change file ownership, group and permissions file: path: /etc/foo.conf owner: foo group: foo mode: '0644' - name: Give insecure permissions to an existing file file: path: /work owner: root group: root mode: '1777' - name: Create a symbolic link file: src: /file/to/link/to dest: /path/to/symlink owner: foo group: foo state: link - name: Create two hard links file: src: '/tmp/{{ item.src }}' dest: '{{ item.dest }}' state: hard loop: - { src: x, dest: y } - { src: z, dest: k } - name: Touch a file, using symbolic modes to set the permissions (equivalent to 0644) file: path: /etc/foo.conf state: touch mode: u=rw,g=r,o=r - name: Touch the same file, but add/remove some permissions file: path: /etc/foo.conf state: touch mode: u+rw,g-wx,o-rwx - name: Touch again the same file, but dont change times this makes the task idempotent file: path: /etc/foo.conf state: touch mode: u+rw,g-wx,o-rwx modification_time: preserve access_time: preserve - name: Create a directory if it does not exist file: path: /etc/some_directory state: directory mode: '0755' - name: Update modification and access time of given file file: path: /etc/some_file state: file modification_time: now access_time: now - name: Set access time based on seconds from epoch value file: path: /etc/another_file state: file access_time: '{{ "%Y%m%d%H%M.%S" | strftime(stat_var.stat.atime) }}' - name: Recursively change ownership of a directory file: path: /etc/foo state: directory recurse: yes owner: foo group: foo - name: Remove file (delete file) file: path: /etc/foo.txt state: absent - name: Recursively remove directory file: path: /etc/foo state: absent ''' RETURN = r''' ''' import errno import os import shutil import sys import time from ansible.module_utils.basic import AnsibleModule from ansible.module_utils._text import to_bytes, to_native # There will only be a single AnsibleModule object per module module = None class AnsibleModuleError(Exception): def __init__(self, results): self.results = results def __repr__(self): print('AnsibleModuleError(results={0})'.format(self.results)) class ParameterError(AnsibleModuleError): pass class Sentinel(object): def __new__(cls, *args, **kwargs): return cls def _ansible_excepthook(exc_type, exc_value, tb): # Using an exception allows us to catch it if the calling code knows it can recover if issubclass(exc_type, AnsibleModuleError): module.fail_json(**exc_value.results) else: sys.__excepthook__(exc_type, exc_value, tb) def additional_parameter_handling(params): """Additional parameter validation and reformatting""" # When path is a directory, rewrite the pathname to be the file inside of the directory # TODO: Why do we exclude link? Why don't we exclude directory? Should we exclude touch? # I think this is where we want to be in the future: # when isdir(path): # if state == absent: Remove the directory # if state == touch: Touch the directory # if state == directory: Assert the directory is the same as the one specified # if state == file: place inside of the directory (use _original_basename) # if state == link: place inside of the directory (use _original_basename. Fallback to src?) # if state == hard: place inside of the directory (use _original_basename. Fallback to src?) if (params['state'] not in ("link", "absent") and os.path.isdir(to_bytes(params['path'], errors='surrogate_or_strict'))): basename = None if params['_original_basename']: basename = params['_original_basename'] elif params['src']: basename = os.path.basename(params['src']) if basename: params['path'] = os.path.join(params['path'], basename) # state should default to file, but since that creates many conflicts, # default state to 'current' when it exists. prev_state = get_state(to_bytes(params['path'], errors='surrogate_or_strict')) if params['state'] is None: if prev_state != 'absent': params['state'] = prev_state elif params['recurse']: params['state'] = 'directory' else: params['state'] = 'file' # make sure the target path is a directory when we're doing a recursive operation if params['recurse'] and params['state'] != 'directory': raise ParameterError(results={"msg": "recurse option requires state to be 'directory'", "path": params["path"]}) # Make sure that src makes sense with the state if params['src'] and params['state'] not in ('link', 'hard'): params['src'] = None module.warn("The src option requires state to be 'link' or 'hard'. This will become an" " error in Ansible 2.10") # In 2.10, switch to this # raise ParameterError(results={"msg": "src option requires state to be 'link' or 'hard'", # "path": params["path"]}) def get_state(path): ''' Find out current state ''' b_path = to_bytes(path, errors='surrogate_or_strict') try: if os.path.lexists(b_path): if os.path.islink(b_path): return 'link' elif os.path.isdir(b_path): return 'directory' elif os.stat(b_path).st_nlink > 1: return 'hard' # could be many other things, but defaulting to file return 'file' return 'absent' except OSError as e: if e.errno == errno.ENOENT: # It may already have been removed return 'absent' else: raise # This should be moved into the common file utilities def recursive_set_attributes(b_path, follow, file_args, mtime, atime): changed = False try: for b_root, b_dirs, b_files in os.walk(b_path): for b_fsobj in b_dirs + b_files: b_fsname = os.path.join(b_root, b_fsobj) if not os.path.islink(b_fsname): tmp_file_args = file_args.copy() tmp_file_args['path'] = to_native(b_fsname, errors='surrogate_or_strict') changed |= module.set_fs_attributes_if_different(tmp_file_args, changed, expand=False) changed |= update_timestamp_for_file(tmp_file_args['path'], mtime, atime) else: # Change perms on the link tmp_file_args = file_args.copy() tmp_file_args['path'] = to_native(b_fsname, errors='surrogate_or_strict') changed |= module.set_fs_attributes_if_different(tmp_file_args, changed, expand=False) changed |= update_timestamp_for_file(tmp_file_args['path'], mtime, atime) if follow: b_fsname = os.path.join(b_root, os.readlink(b_fsname)) # The link target could be nonexistent if os.path.exists(b_fsname): if os.path.isdir(b_fsname): # Link is a directory so change perms on the directory's contents changed |= recursive_set_attributes(b_fsname, follow, file_args, mtime, atime) # Change perms on the file pointed to by the link tmp_file_args = file_args.copy() tmp_file_args['path'] = to_native(b_fsname, errors='surrogate_or_strict') changed |= module.set_fs_attributes_if_different(tmp_file_args, changed, expand=False) changed |= update_timestamp_for_file(tmp_file_args['path'], mtime, atime) except RuntimeError as e: # on Python3 "RecursionError" is raised which is derived from "RuntimeError" # TODO once this function is moved into the common file utilities, this should probably raise more general exception raise AnsibleModuleError( results={'msg': "Could not recursively set attributes on %s. Original error was: '%s'" % (to_native(b_path), to_native(e))} ) return changed def initial_diff(path, state, prev_state): diff = {'before': {'path': path}, 'after': {'path': path}, } if prev_state != state: diff['before']['state'] = prev_state diff['after']['state'] = state if state == 'absent' and prev_state == 'directory': walklist = { 'directories': [], 'files': [], } b_path = to_bytes(path, errors='surrogate_or_strict') for base_path, sub_folders, files in os.walk(b_path): for folder in sub_folders: folderpath = os.path.join(base_path, folder) walklist['directories'].append(folderpath) for filename in files: filepath = os.path.join(base_path, filename) walklist['files'].append(filepath) diff['before']['path_content'] = walklist return diff # # States # def get_timestamp_for_time(formatted_time, time_format): if formatted_time == 'preserve': return None elif formatted_time == 'now': return Sentinel else: try: struct = time.strptime(formatted_time, time_format) struct_time = time.mktime(struct) except (ValueError, OverflowError) as e: raise AnsibleModuleError(results={'msg': 'Error while obtaining timestamp for time %s using format %s: %s' % (formatted_time, time_format, to_native(e, nonstring='simplerepr'))}) return struct_time def update_timestamp_for_file(path, mtime, atime, diff=None): b_path = to_bytes(path, errors='surrogate_or_strict') try: # When mtime and atime are set to 'now', rely on utime(path, None) which does not require ownership of the file # https://github.com/ansible/ansible/issues/50943 if mtime is Sentinel and atime is Sentinel: # It's not exact but we can't rely on os.stat(path).st_mtime after setting os.utime(path, None) as it may # not be updated. Just use the current time for the diff values mtime = atime = time.time() previous_mtime = os.stat(b_path).st_mtime previous_atime = os.stat(b_path).st_atime set_time = None else: # If both parameters are None 'preserve', nothing to do if mtime is None and atime is None: return False previous_mtime = os.stat(b_path).st_mtime previous_atime = os.stat(b_path).st_atime if mtime is None: mtime = previous_mtime elif mtime is Sentinel: mtime = time.time() if atime is None: atime = previous_atime elif atime is Sentinel: atime = time.time() # If both timestamps are already ok, nothing to do if mtime == previous_mtime and atime == previous_atime: return False set_time = (atime, mtime) os.utime(b_path, set_time) if diff is not None: if 'before' not in diff: diff['before'] = {} if 'after' not in diff: diff['after'] = {} if mtime != previous_mtime: diff['before']['mtime'] = previous_mtime diff['after']['mtime'] = mtime if atime != previous_atime: diff['before']['atime'] = previous_atime diff['after']['atime'] = atime except OSError as e: raise AnsibleModuleError(results={'msg': 'Error while updating modification or access time: %s' % to_native(e, nonstring='simplerepr'), 'path': path}) return True def keep_backward_compatibility_on_timestamps(parameter, state): if state in ['file', 'hard', 'directory', 'link'] and parameter is None: return 'preserve' elif state == 'touch' and parameter is None: return 'now' else: return parameter def execute_diff_peek(path): """Take a guess as to whether a file is a binary file""" b_path = to_bytes(path, errors='surrogate_or_strict') appears_binary = False try: with open(b_path, 'rb') as f: head = f.read(8192) except Exception: # If we can't read the file, we're okay assuming it's text pass else: if b"\x00" in head: appears_binary = True return appears_binary def ensure_absent(path): b_path = to_bytes(path, errors='surrogate_or_strict') prev_state = get_state(b_path) result = {} if prev_state != 'absent': diff = initial_diff(path, 'absent', prev_state) if not module.check_mode: if prev_state == 'directory': try: shutil.rmtree(b_path, ignore_errors=False) except Exception as e: raise AnsibleModuleError(results={'msg': "rmtree failed: %s" % to_native(e)}) else: try: os.unlink(b_path) except OSError as e: if e.errno != errno.ENOENT: # It may already have been removed raise AnsibleModuleError(results={'msg': "unlinking failed: %s " % to_native(e), 'path': path}) result.update({'path': path, 'changed': True, 'diff': diff, 'state': 'absent'}) else: result.update({'path': path, 'changed': False, 'state': 'absent'}) return result def execute_touch(path, follow, timestamps): b_path = to_bytes(path, errors='surrogate_or_strict') prev_state = get_state(b_path) changed = False result = {'dest': path} mtime = get_timestamp_for_time(timestamps['modification_time'], timestamps['modification_time_format']) atime = get_timestamp_for_time(timestamps['access_time'], timestamps['access_time_format']) if not module.check_mode: if prev_state == 'absent': # Create an empty file if the filename did not already exist try: open(b_path, 'wb').close() changed = True except (OSError, IOError) as e: raise AnsibleModuleError(results={'msg': 'Error, could not touch target: %s' % to_native(e, nonstring='simplerepr'), 'path': path}) # Update the attributes on the file diff = initial_diff(path, 'touch', prev_state) file_args = module.load_file_common_arguments(module.params) try: changed = module.set_fs_attributes_if_different(file_args, changed, diff, expand=False) changed |= update_timestamp_for_file(file_args['path'], mtime, atime, diff) except SystemExit as e: if e.code: # We take this to mean that fail_json() was called from # somewhere in basic.py if prev_state == 'absent': # If we just created the file we can safely remove it os.remove(b_path) raise result['changed'] = changed result['diff'] = diff return result def ensure_file_attributes(path, follow, timestamps): b_path = to_bytes(path, errors='surrogate_or_strict') prev_state = get_state(b_path) file_args = module.load_file_common_arguments(module.params) mtime = get_timestamp_for_time(timestamps['modification_time'], timestamps['modification_time_format']) atime = get_timestamp_for_time(timestamps['access_time'], timestamps['access_time_format']) if prev_state != 'file': if follow and prev_state == 'link': # follow symlink and operate on original b_path = os.path.realpath(b_path) path = to_native(b_path, errors='strict') prev_state = get_state(b_path) file_args['path'] = path if prev_state not in ('file', 'hard'): # file is not absent and any other state is a conflict raise AnsibleModuleError(results={'msg': 'file (%s) is %s, cannot continue' % (path, prev_state), 'path': path}) diff = initial_diff(path, 'file', prev_state) changed = module.set_fs_attributes_if_different(file_args, False, diff, expand=False) changed |= update_timestamp_for_file(file_args['path'], mtime, atime, diff) return {'path': path, 'changed': changed, 'diff': diff} def ensure_directory(path, follow, recurse, timestamps): b_path = to_bytes(path, errors='surrogate_or_strict') prev_state = get_state(b_path) file_args = module.load_file_common_arguments(module.params) mtime = get_timestamp_for_time(timestamps['modification_time'], timestamps['modification_time_format']) atime = get_timestamp_for_time(timestamps['access_time'], timestamps['access_time_format']) # For followed symlinks, we need to operate on the target of the link if follow and prev_state == 'link': b_path = os.path.realpath(b_path) path = to_native(b_path, errors='strict') file_args['path'] = path prev_state = get_state(b_path) changed = False diff = initial_diff(path, 'directory', prev_state) if prev_state == 'absent': # Create directory and assign permissions to it if module.check_mode: return {'changed': True, 'diff': diff} curpath = '' try: # Split the path so we can apply filesystem attributes recursively # from the root (/) directory for absolute paths or the base path # of a relative path. We can then walk the appropriate directory # path to apply attributes. # Something like mkdir -p with mode applied to all of the newly created directories for dirname in path.strip('/').split('/'): curpath = '/'.join([curpath, dirname]) # Remove leading slash if we're creating a relative path if not os.path.isabs(path): curpath = curpath.lstrip('/') b_curpath = to_bytes(curpath, errors='surrogate_or_strict') if not os.path.exists(b_curpath): try: os.mkdir(b_curpath) changed = True except OSError as ex: # Possibly something else created the dir since the os.path.exists # check above. As long as it's a dir, we don't need to error out. if not (ex.errno == errno.EEXIST and os.path.isdir(b_curpath)): raise tmp_file_args = file_args.copy() tmp_file_args['path'] = curpath changed = module.set_fs_attributes_if_different(tmp_file_args, changed, diff, expand=False) changed |= update_timestamp_for_file(file_args['path'], mtime, atime, diff) except Exception as e: raise AnsibleModuleError(results={'msg': 'There was an issue creating %s as requested:' ' %s' % (curpath, to_native(e)), 'path': path}) return {'path': path, 'changed': changed, 'diff': diff} elif prev_state != 'directory': # We already know prev_state is not 'absent', therefore it exists in some form. raise AnsibleModuleError(results={'msg': '%s already exists as a %s' % (path, prev_state), 'path': path}) # # previous state == directory # changed = module.set_fs_attributes_if_different(file_args, changed, diff, expand=False) changed |= update_timestamp_for_file(file_args['path'], mtime, atime, diff) if recurse: changed |= recursive_set_attributes(b_path, follow, file_args, mtime, atime) return {'path': path, 'changed': changed, 'diff': diff} def ensure_symlink(path, src, follow, force, timestamps): b_path = to_bytes(path, errors='surrogate_or_strict') b_src = to_bytes(src, errors='surrogate_or_strict') prev_state = get_state(b_path) mtime = get_timestamp_for_time(timestamps['modification_time'], timestamps['modification_time_format']) atime = get_timestamp_for_time(timestamps['access_time'], timestamps['access_time_format']) # source is both the source of a symlink or an informational passing of the src for a template module # or copy module, even if this module never uses it, it is needed to key off some things if src is None: if follow: # use the current target of the link as the source src = to_native(os.path.realpath(b_path), errors='strict') b_src = to_bytes(src, errors='surrogate_or_strict') if not os.path.islink(b_path) and os.path.isdir(b_path): relpath = path else: b_relpath = os.path.dirname(b_path) relpath = to_native(b_relpath, errors='strict') absrc = os.path.join(relpath, src) b_absrc = to_bytes(absrc, errors='surrogate_or_strict') if not force and not os.path.exists(b_absrc): raise AnsibleModuleError(results={'msg': 'src file does not exist, use "force=yes" if you' ' really want to create the link: %s' % absrc, 'path': path, 'src': src}) if prev_state == 'directory': if not force: raise AnsibleModuleError(results={'msg': 'refusing to convert from %s to symlink for %s' % (prev_state, path), 'path': path}) elif os.listdir(b_path): # refuse to replace a directory that has files in it raise AnsibleModuleError(results={'msg': 'the directory %s is not empty, refusing to' ' convert it' % path, 'path': path}) elif prev_state in ('file', 'hard') and not force: raise AnsibleModuleError(results={'msg': 'refusing to convert from %s to symlink for %s' % (prev_state, path), 'path': path}) diff = initial_diff(path, 'link', prev_state) changed = False if prev_state == 'absent': changed = True elif prev_state == 'link': b_old_src = os.readlink(b_path) if b_old_src != b_src: diff['before']['src'] = to_native(b_old_src, errors='strict') diff['after']['src'] = src changed = True elif prev_state == 'hard': changed = True if not force: raise AnsibleModuleError(results={'msg': 'Cannot link because a hard link exists at destination', 'dest': path, 'src': src}) elif prev_state == 'file': changed = True if not force: raise AnsibleModuleError(results={'msg': 'Cannot link because a file exists at destination', 'dest': path, 'src': src}) elif prev_state == 'directory': changed = True if os.path.exists(b_path): if not force: raise AnsibleModuleError(results={'msg': 'Cannot link because a file exists at destination', 'dest': path, 'src': src}) else: raise AnsibleModuleError(results={'msg': 'unexpected position reached', 'dest': path, 'src': src}) if changed and not module.check_mode: if prev_state != 'absent': # try to replace atomically b_tmppath = to_bytes(os.path.sep).join( [os.path.dirname(b_path), to_bytes(".%s.%s.tmp" % (os.getpid(), time.time()))] ) try: if prev_state == 'directory': os.rmdir(b_path) os.symlink(b_src, b_tmppath) os.rename(b_tmppath, b_path) except OSError as e: if os.path.exists(b_tmppath): os.unlink(b_tmppath) raise AnsibleModuleError(results={'msg': 'Error while replacing: %s' % to_native(e, nonstring='simplerepr'), 'path': path}) else: try: os.symlink(b_src, b_path) except OSError as e: raise AnsibleModuleError(results={'msg': 'Error while linking: %s' % to_native(e, nonstring='simplerepr'), 'path': path}) if module.check_mode and not os.path.exists(b_path): return {'dest': path, 'src': src, 'changed': changed, 'diff': diff} # Now that we might have created the symlink, get the arguments. # We need to do it now so we can properly follow the symlink if needed # because load_file_common_arguments sets 'path' according # the value of follow and the symlink existence. file_args = module.load_file_common_arguments(module.params) # Whenever we create a link to a nonexistent target we know that the nonexistent target # cannot have any permissions set on it. Skip setting those and emit a warning (the user # can set follow=False to remove the warning) if follow and os.path.islink(b_path) and not os.path.exists(file_args['path']): module.warn('Cannot set fs attributes on a non-existent symlink target. follow should be' ' set to False to avoid this.') else: changed = module.set_fs_attributes_if_different(file_args, changed, diff, expand=False) changed |= update_timestamp_for_file(file_args['path'], mtime, atime, diff) return {'dest': path, 'src': src, 'changed': changed, 'diff': diff} def ensure_hardlink(path, src, follow, force, timestamps): b_path = to_bytes(path, errors='surrogate_or_strict') b_src = to_bytes(src, errors='surrogate_or_strict') prev_state = get_state(b_path) file_args = module.load_file_common_arguments(module.params) mtime = get_timestamp_for_time(timestamps['modification_time'], timestamps['modification_time_format']) atime = get_timestamp_for_time(timestamps['access_time'], timestamps['access_time_format']) # src is the source of a hardlink. We require it if we are creating a new hardlink. # We require path in the argument_spec so we know it is present at this point. if src is None: raise AnsibleModuleError(results={'msg': 'src is required for creating new hardlinks'}) if not os.path.exists(b_src): raise AnsibleModuleError(results={'msg': 'src does not exist', 'dest': path, 'src': src}) diff = initial_diff(path, 'hard', prev_state) changed = False if prev_state == 'absent': changed = True elif prev_state == 'link': b_old_src = os.readlink(b_path) if b_old_src != b_src: diff['before']['src'] = to_native(b_old_src, errors='strict') diff['after']['src'] = src changed = True elif prev_state == 'hard': if not os.stat(b_path).st_ino == os.stat(b_src).st_ino: changed = True if not force: raise AnsibleModuleError(results={'msg': 'Cannot link, different hard link exists at destination', 'dest': path, 'src': src}) elif prev_state == 'file': changed = True if not force: raise AnsibleModuleError(results={'msg': 'Cannot link, %s exists at destination' % prev_state, 'dest': path, 'src': src}) elif prev_state == 'directory': changed = True if os.path.exists(b_path): if os.stat(b_path).st_ino == os.stat(b_src).st_ino: return {'path': path, 'changed': False} elif not force: raise AnsibleModuleError(results={'msg': 'Cannot link: different hard link exists at destination', 'dest': path, 'src': src}) else: raise AnsibleModuleError(results={'msg': 'unexpected position reached', 'dest': path, 'src': src}) if changed and not module.check_mode: if prev_state != 'absent': # try to replace atomically b_tmppath = to_bytes(os.path.sep).join( [os.path.dirname(b_path), to_bytes(".%s.%s.tmp" % (os.getpid(), time.time()))] ) try: if prev_state == 'directory': if os.path.exists(b_path): try: os.unlink(b_path) except OSError as e: if e.errno != errno.ENOENT: # It may already have been removed raise os.link(b_src, b_tmppath) os.rename(b_tmppath, b_path) except OSError as e: if os.path.exists(b_tmppath): os.unlink(b_tmppath) raise AnsibleModuleError(results={'msg': 'Error while replacing: %s' % to_native(e, nonstring='simplerepr'), 'path': path}) else: try: os.link(b_src, b_path) except OSError as e: raise AnsibleModuleError(results={'msg': 'Error while linking: %s' % to_native(e, nonstring='simplerepr'), 'path': path}) if module.check_mode and not os.path.exists(b_path): return {'dest': path, 'src': src, 'changed': changed, 'diff': diff} changed = module.set_fs_attributes_if_different(file_args, changed, diff, expand=False) changed |= update_timestamp_for_file(file_args['path'], mtime, atime, diff) return {'dest': path, 'src': src, 'changed': changed, 'diff': diff} def main(): global module module = AnsibleModule( argument_spec=dict( state=dict(type='str', choices=['absent', 'directory', 'file', 'hard', 'link', 'touch']), path=dict(type='path', required=True, aliases=['dest', 'name']), _original_basename=dict(type='str'), # Internal use only, for recursive ops recurse=dict(type='bool', default=False), force=dict(type='bool', default=False), # Note: Should not be in file_common_args in future follow=dict(type='bool', default=True), # Note: Different default than file_common_args _diff_peek=dict(type='str'), # Internal use only, for internal checks in the action plugins src=dict(type='path'), # Note: Should not be in file_common_args in future modification_time=dict(type='str'), modification_time_format=dict(type='str', default='%Y%m%d%H%M.%S'), access_time=dict(type='str'), access_time_format=dict(type='str', default='%Y%m%d%H%M.%S'), ), add_file_common_args=True, supports_check_mode=True, ) # When we rewrite basic.py, we will do something similar to this on instantiating an AnsibleModule sys.excepthook = _ansible_excepthook additional_parameter_handling(module.params) params = module.params state = params['state'] recurse = params['recurse'] force = params['force'] follow = params['follow'] path = params['path'] src = params['src'] timestamps = {} timestamps['modification_time'] = keep_backward_compatibility_on_timestamps(params['modification_time'], state) timestamps['modification_time_format'] = params['modification_time_format'] timestamps['access_time'] = keep_backward_compatibility_on_timestamps(params['access_time'], state) timestamps['access_time_format'] = params['access_time_format'] # short-circuit for diff_peek if params['_diff_peek'] is not None: appears_binary = execute_diff_peek(to_bytes(path, errors='surrogate_or_strict')) module.exit_json(path=path, changed=False, appears_binary=appears_binary) if state == 'file': result = ensure_file_attributes(path, follow, timestamps) elif state == 'directory': result = ensure_directory(path, follow, recurse, timestamps) elif state == 'link': result = ensure_symlink(path, src, follow, force, timestamps) elif state == 'hard': result = ensure_hardlink(path, src, follow, force, timestamps) elif state == 'touch': result = execute_touch(path, follow, timestamps) elif state == 'absent': result = ensure_absent(path) module.exit_json(**result) if __name__ == '__main__': main()
/* * Copyright 2017 StreamSets Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Data Collector Constants. */ angular.module('dataCollectorApp.common') .constant('pipelineConstant', { SOURCE_STAGE_TYPE : 'SOURCE', PROCESSOR_STAGE_TYPE : 'PROCESSOR', SELECTOR_STAGE_TYPE : 'SELECTOR', EXECUTOR_STAGE_TYPE : 'EXECUTOR', TARGET_STAGE_TYPE : 'TARGET', STAGE_INSTANCE: 'STAGE_INSTANCE', LINK: 'LINK', PIPELINE: 'PIPELINE', DENSITY_COMFORTABLE: 'COMFORTABLE', DENSITY_COZY: 'COZY', DENSITY_COMPACT: 'COMPACT', LOCAL_HELP: 'LOCAL_HELP', HOSTED_HELP: 'HOSTED_HELP', CONFIGURED_SOURCE: 'CONFIGURED_SOURCE', SNAPSHOT_SOURCE: 'SNAPSHOT_SOURCE', USER_PROVIDED: 'USER_PROVIDED', STANDALONE: 'STANDALONE', CLUSTER: 'CLUSTER', CLUSTER_BATCH: 'CLUSTER_BATCH', CLUSTER_YARN_STREAMING: 'CLUSTER_YARN_STREAMING', CLUSTER_MESOS_STREAMING: 'CLUSTER_MESOS_STREAMING', SLAVE: 'SLAVE', NON_LIST_MAP_ROOT: 'root', BUTTON_CATEGORY: 'button', TAB_CATEGORY: 'tab', STAGE_CATEGORY: 'stage', CLICK_ACTION: 'click', SELECT_ACTION: 'select', ADD_ACTION: 'add', CONNECT_ACTION: 'connect', STAGE_LIBRARY_CATEGORY: 'library', INSTALL_ACTION: 'install', UNINSTALL_ACTION: 'uninstall', DARWIN_OS: 'darwin', LINUX_OS: 'linux', WINDOWS_OS: 'windows', AMD64_ARCH: 'amd64', ARM_ARCH: 'arm' });
import os from math import sin, cos def main(): a=0 b=0 height=24 width=80 #height=int(input("Enter Screen Height : ")) #width=int(input("Enter Screen Width : ")) # for clearing console (windows and unix systems) clear = "cls" if os.name == "posix": clear = "clear" os.system(clear) while True: z = [0 for _ in range(4*height*width)] screen = [' ' for _ in range(height*width)] j=0 while j<6.28: j+=0.07 i=0 while i<6.28: i+=0.02 sinA=sin(a) cosA=cos(a) cosB=cos(b) sinB=sin(b) sini=sin(i) cosi=cos(i) cosj=cos(j) sinj=sin(j) cosj2=cosj+2 mess=1/(sini*cosj2*sinA+sinj*cosA+5) t=sini*cosj2*cosA-sinj* sinA # 40 is the left screen shift x = int(40+30*mess*(cosi*cosj2*cosB-t*sinB)) # 12 is the down screen shift y = int(11+15*mess*(cosi*cosj2*sinB +t*cosB)) # all are casted to int, ie floored o = int(x+width*y) # multiplying by 8 to bring in range 0-11 as 8*(sqrt(2))=11 # because we have 11 luminance characters N = int(8*((sinj*sinA-sini*cosj*cosA)*cosB-sini*cosj*sinA-sinj*cosA-cosi *cosj*sinB)) # if x,y inside screen and previous z-buffer is < mess # i.e. when z[o] is 0 or the prev point is behind the new point # so we change it to the point nearer to the eye/ above prev point if 0<y<height and 0<x<width and z[o] < mess: z[o]=mess screen[o]=".,-~:;=!*#$@"[N if N>0 else 0] # prints os.system(clear) for index, char in enumerate(screen): if index % width == 0: print() else: print(char, end='') # increments a+=0.04 b+=0.02 if __name__ == "__main__": main()
# -*- coding: utf-8 -*- #ღḯḉḯη-тєαм import LINETCR from LINETCR.lib.curve.ttypes import * from datetime import datetime from bs4 import BeautifulSoup from threading import Thread from googletrans import Translator from gtts import gTTS import time,random,sys,json,codecs,threading,glob,urllib,urllib2,urllib3,re,ast,os,subprocess,requests,tempfile #tinkerbell cl = LINETCR.LINE() cl.login(token="ExRTcOu9AzPhd7S39eMa.FrRaFsa2S2DfEdOkgzkYUG.TR5t2XYEDiQbq38z4ztj6kDRkBQxt3EWEBfb7nLgXlY=") cl.loginResult() print "Ꭺηȗẕȗ℮ℓℓą" reload(sys) sys.setdefaultencoding('utf-8') helpMessage= """ █▀▀▀▀▀▀হই۝ইহ▀▀▀▀▀▀ █░࿇˶̏˶̏˶̏˶̏˶̏˶̏˶̏˶̏˶̏[𖤓]˵̋˵̋˵̋˵̋˵̋˵̋˵̋˵̋࿇ █░࿇A̸͟͞V̸͟͞R̸͟͞I̸͟͞L̸͟͞I̸͟͞A̸͟͞ [𖡹]L̸͟͞E̸͟͞V̸͟͞A̸͟͞N̸͟͞A࿇ █▄▄▄▄▄▄হই۝ইহ▄▄▄▄▄▄ █░║✶║Rename:[text] █░║✶║Bio:[text] █░║✶║Clone @[name] █░║✶║Comment:[text] █░║✶║Message:[text] █░║✶║Group name:[text] █░║✶║Admin on @[name] █░║✶║Expel on @[name] █░║✶║Expelall █░║✶║Steal name @[name] █░║✶║Steal Bio @[name] █░║✶║Steal status @[name] █░║✶║Steal mid @[name] █░║✶║Steal contact @[name] █░║✶║Steal cover @[name] █░║✶║Steal pict @[name] █░║✶║Steal group pict █░║✶║Midpict:[mid] █░║✶║Copy @[name] █░║✶║Kembali ke asli █░║✶║Protect:low █░║✶║Protect:hight █░║✶║Ban @[name] █░║✶║Unban @[name] █░║✶║Ban group: █░║✶║Del ban: █░║✶║List ban group █░║✶║Banned[send contact] █░║✶║Unbanned[send contact] █░║✶║Ban repeat @[name] █░║✶║Blacklist all █░║✶║Ban cek █░║✶║Clear banlist █░║✶║Mimic target @[name] █░║✶║Mimic untarget @[name] █░║✶║Add friend @[name] █░║✶║Target @[name] █░║✶║Del target @[name] █░║✶║Target list █░║✶║Invite:[mid] █░║✶║nvite user[contact] █░║✶║Invite me █░║✶║Join group █░║✶║Leave group: █░║✶║Auto join:on/off █░║✶║Auto leave:on/off █░║✶║Auto like:on/off █░║✶║Welcome message:on/off █░║✶║Auto notice:on/off █░║✶║Blockinvite:on/off █░║✶║Auto blockqr:on/off █░║✶║Namelock:on/off █░║✶║Mimic:on/off █░║✶║Auto add:on/off █░║✶║Check message █░║✶║Add message:[text] █░║✶║Comment:on/off █░║✶║Add comment:[text] █░║✶║Check comment █░║✶║Backup:on/off █░║✶║Gcancel:[number] █░║✶║Update welcome:[text] █░║✶║Check welcome message █░║✶║Rejectall █░║✶║Clean invites █░║✶║Clear invites █░║✶║gift1-15 █░║✶║Spam gift █░║✶║Group list █░║✶║Banlist █░║✶║Admin list █░║✶║Settings █░║✶║Ginfo █░║✶║TL:[text] █░║✶║Mimic list █░║✶║Details grup: █░║✶║Crash █░║✶║Cleanse █░║✶║Vkick @ █░║✶║Nk [name] █░║✶║Kick:[mid] █░║✶║Purge █░║✶║Ulti █░║✶║Recover █░║✶║Spamg[on/off][no][txt] █░║✶║Spam add:[text] █░║✶║Spam change:[text] █░║✶║Spam start:[number] █░║✶║Say [text] █░║✶║Me █░║✶║Speed █░║✶║Debug speed █░║✶║My mid █░║✶║Gcreator █░║✶║Halo █░║✶║Bot contact █░║✶║Bot mid █░║✶║Creator █░║✶║System █░║✶║Iconfig █░║✶║Kernel █░║✶║Cpu █░║✶║Responsename █░║✶║Help █░║✶║Mc:[mid] █░║✶║Lurking █░║✶║Lurking result █░║✶║Setlastpoint █░║✶║Viewlastseen █░║✶║Link open █░║✶║Link close █░║✶║Gurl █░║✶║Remove chat █░║✶║Bot restart █░║✶║Lyric [][] █░║✶║Music [][] █░║✶║Wiki [text] █░║✶║Vidio [text] █░║✶║Youtube [text] █░║✶║Instagram [text] █░║✶║Translate-idn [text] █░║✶║Translate-eng [text] █░║✶║Translate-thai [text] █░║✶║Translate-japan [text] █░║✶║Emoji [expression] █░║✶║Info @[name] █░║✶║Ping █░║✶║Time █░║✶║apakah █░║✶║Sticker [expression] █░║✶║Mention all █░║✶║/say █░║✶║/say-en █░║✶║/say-jp █░║✶║Dosa @ █░║✶║/ █░║✶║Siapa █░║✶║Pm cast [text] █░║✶║Broadcast [text] █░║✶║Spam @[name] █░║✶║Turn off bots █▀▀▀▀▀▀হই۝ইহ▀▀▀▀▀▀ █░࿇˶̏˶̏˶̏˶̏˶̏˶̏˶̏˶̏˶̏[𖤓]˵̋˵̋˵̋˵̋˵̋˵̋˵̋˵̋࿇ █░࿇˶̏ ˶̏[ᴀ༘̏̏ʟ༘̏̏ᴘ༘̏̏ʀ༘̏̏ᴀ༘̏̏[𖤓]ᴢ༘̏̏ᴏ༘̏̏ʟ༘̏̏ᴀ༘̏̏ᴍ༘̏̏]˵̋࿇ █▄▄▄▄▄▄হই۝ইহ▄▄▄▄▄▄ """ KAC=[cl] mid = cl.getProfile().mid protectname = [] protecturl = [] protection = [] autocancel = {} autoinvite = [] autoleaveroom = [] targets = [] Bots=[mid] admin = ["u7d1ac07d2036b36745783a0a1992b2ba"] owner = ["u7d1ac07d2036b36745783a0a1992b2ba"] wait = { 'contact':False, 'autoJoin':True, 'autoCancel':{"on":True, "members":1}, 'leaveRoom':False, 'timeline':True, 'autoAdd':True, 'message':"╔═──────┅═ই۝ई═┅──────\n_░▒███████\n░██▓▒░░▒▓██\n██▓▒░__░▒▓██___██████\n██▓▒░____░▓███▓__░▒▓██\n██▓▒░___░▓██▓_____░▒▓██\n██▓▒░_______________░▒▓██\n_██▓▒░______________░▒▓██\n__██▓▒░____________░▒▓██\n___██▓▒░__________░▒▓██\n____██▓▒░________░▒▓██\n_____██▓▒░_____░▒▓██\n______██▓▒░__░▒▓██\n_______█▓▒░░▒▓██\n_________░▒▓██\n_______░▒▓██\n_____░▒▓██\n║ ❂•••••••••••✧•••••••••••❂\n║ 【ᏴᏞᎪᏟK\_☠☬☠_/ᎪNᏩᎬᏞᏚ】\n║ ᎪᏙᎡᏆᏞᏆᎪ ᏞᎬᏙᎪNᎪ\n║ ❂•••••••••••✧•••••••••••❂\n╠═────────┅═ই۝ई═┅─────────\n http://line.me/ti/p/~avrilia_quester\n\n. . . . . . . . . . .*. . . . . . . ** *\n. . . . .. . . . . .*** . . * . . *****\n. . . . . . . . . . .** . . **. . . . .*\n. . . . . . . . . . ***.*. . *. . . . .*\n. . . . . . . . . .****. . . .** . . . ******\n. . . . . . . . . ***** . . . .**.*. . . . . **\n. . . . . . . . .*****. . . . . **. . . . . . *.**\n. . . . . . . .*****. . . . . .*. . . . . . *\n. . . . . . . .******. . . . .*. . . . . *\n. . . . . . . .******* . . .*. . . . .*\n. . . . . . . . .*********. . . . . *\n. . . . . . . . . .******* . ***\n*******. . . . . . . . .**\n.*******. . . . . . . . *\n. ******. . . . . . . . * *\n. .***. . *. . . . . . .**\n. . . . . . .*. . . . . *\n. . . . .****.*. . . .*\n. . . *******. .*. .*\n. . .*******. . . *.\n. . .*****. . . . *\n. . .**. . . . . .*\n. . .*. . . . . . **.*\n. . . . . . . . . **\n. . . . . . . . .*\n. . . . . . . . .*\n. . . . . . . . .*\n. . . . . . . . *\n. . . . . . . . *\n▀██▀─▄███▄─▀██─██▀██▀▀█\n─██─███─███─██─██─██▄█\n─██─▀██▄██▀─▀█▄█▀─██▀█\n▄██▄▄█▀▀▀─────▀──▄██▄▄█\n╚═────────┅═ই۝ई═┅─────────", "lang":"JP", "comment":"AutoLike by Ꭺηȗẕȗ℮ℓℓą", "welmsg":"Hallo Kak...\n█▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀█\n█░░╦─╦╔╗╦─╔╗╔╗╔╦╗╔╗░░█\n█░░║║║╠─║─║─║║║║║╠─░░█\n█░░╚╩╝╚╝╚╝╚╝╚╝╩─╩╚╝░░█\n█▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄█\n\nBudayakan Cek Note\nDan Semoga Betah Disini..\nJangan Lupa Nikung Kak,..Yehkan..\n\nDah Gitu Ajah..\n\n\n===❍•••{☠ʟᴇᴠᴀɴᴀ☠}•••❍===", "commentOn":True, "commentBlack":{}, "wblack":False, "dblack":False, "clock":False, "status":True, "likeOn":True, "pname":False, "blacklist":{}, "whitelist":{}, "wblacklist":False, "dblacklist":False, "qr":False, "welcomemsg":True, "Backup":False, "protectionOn":False, "winvite":False, "pnharfbot":{}, "pname":{}, "pro_name":{}, } wait2 = { 'readPoint':{}, 'readMember':{}, 'setTime':{}, 'ROM':{} } wait3 = { "copy":False, "copy2":"target", "target":{} } res = { 'num':{}, 'us':{}, 'au':{}, } setTime = {} setTime = wait2['setTime'] contact = cl.getProfile() backup = cl.getProfile() backup.displayName = contact.displayName backup.statusMessage = contact.statusMessage backup.pictureStatus = contact.pictureStatus def upload_tempimage(client): ''' Upload a picture of a kitten. We don't ship one, so get creative! ''' config = { 'album': album, 'name': 'bot auto upload', 'title': 'bot auto upload', 'description': 'bot auto upload' } print("Uploading image... ") image = client.upload_from_path(image_path, config=config, anon=False) print("Done") print() def restart_program(): python = sys.executable os.execl(python, python, * sys.argv) def yt(query): with requests.session() as s: isi = [] if query == "": query = "S1B tanysyz" s.headers['user-agent'] = 'Mozilla/5.0' url = 'http://www.youtube.com/results' params = {'search_query': query} r = s.get(url, params=params) soup = BeautifulSoup(r.content, 'html5lib') for a in soup.select('.yt-lockup-title > a[title]'): if '&list=' not in a['href']: if 'watch?v' in a['href']: b = a['href'].replace('watch?v=', '') isi += ['youtu.be' + b] return isi def sendMessage(to, text, contentMetadata={}, contentType=0): mes = Message() mes.to, mes.from_ = to, profile.mid mes.text = text mes.contentType, mes.contentMetadata = contentType, contentMetadata if to not in messageReq: messageReq[to] = -1 messageReq[to] += 1 def mention(to, nama): aa = "" bb = "" strt = int(14) akh = int(14) nm = nama for mm in nm: akh = akh + 2 aa += """{"S":"""+json.dumps(str(strt))+""","E":"""+json.dumps(str(akh))+""","M":"""+json.dumps(mm)+"},""" strt = strt + 6 akh = akh + 4 bb += "\xe2\x95\xa0 @x \n" aa = (aa[:int(len(aa)-1)]) msg = Message() msg.to = to msg.text = "\xe2\x95\x94\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\n"+bb+"\xe2\x95\x9a\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90" msg.contentMetadata ={'MENTION':'{"MENTIONEES":['+aa+']}','EMTVER':'4'} print "[Command] Tag All" try: cl.sendMessage(msg) except Exception as error: print error def sendMessage(self, messageObject): return self.Talk.client.sendMessage(0,messageObject) def sendText(self, Tomid, text): msg = Message() msg.to = Tomid msg.text = text return self.Talk.client.sendMessage(0, msg) def sendImage(self, to_, path): M = Message(to=to_,contentType = 1) M.contentMetadata = None M.contentPreview = None M_id = self._client.sendMessage(M).id files = { 'file': open(path, 'rb'), } params = { 'name': 'media', 'oid': M_id, 'size': len(open(path, 'rb').read()), 'type': 'image', 'ver': '1.0', } data = { 'params': json.dumps(params) } r = self._client.post_content('https://os.line.naver.jp/talk/m/upload.nhn', data=data, files=files) if r.status_code != 201: raise Exception('Upload image failure.') #r.content return True def sendImageWithURL(self, to_, url): path = '%s/pythonLine-%i.data' % (tempfile.gettempdir(), randint(0, 9)) r = requests.get(url, stream=True) if r.status_code == 200: with open(path, 'w') as f: shutil.copyfileobj(r.raw, f) else: raise Exception('Download image failure.') try: self.sendImage(to_, path) except Exception as e: raise e def post_content(self, urls, data=None, files=None): return self._session.post(urls, headers=self._headers, data=data, files=files) def sendMessage(to, text, contentMetadata={}, contentType=0): mes = Message() mes.to, mes.from_ = to, profile.mid mes.text = text mes.contentType, mes.contentMetadata = contentType, contentMetadata if to not in messageReq: messageReq[to] = -1 messageReq[to] += 1 def sendMessage(to, text, contentMetadata={}, contentType=0): mes = Message() mes.to, mes.from_ = to, profile.mid mes.text = text mes.contentType, mes.contentMetadata = contentType, contentMetadata if to not in messageReq: messageReq[to] = -1 messageReq[to] += 1 def NOTIFIED_READ_MESSAGE(op): print op try: if op.param1 in wait2['readPoint']: Name = cl.getContact(op.param2).displayName if Name in wait2['readMember'][op.param1]: pass else: wait2['readMember'][op.param1] += "\n・" + Name + datetime.now().strftime(' [%d - %H:%M:%S]') wait2['ROM'][op.param1][op.param2] = "・" + Name + " ツ" else: pass except: pass def RECEIVE_MESSAGE(op): msg = op.message try: if msg.contentType == 0: try: if msg.to in wait2['readPoint']: if msg.from_ in wait2["ROM"][msg.to]: del wait2["ROM"][msg.to][msg.from_] else: pass except: pass else: pass except KeyboardInterrupt: sys.exit(0) except Exception as error: print error print ("\n\nRECEIVE_MESSAGE\n\n") return def bot(op): try: if op.type == 0: return if op.type == 5: if wait["autoAdd"] == True: cl.findAndAddContactsByMid(op.param1) if (wait["message"] in [""," ","\n",None]): pass else: cl.sendText(op.param1,str(wait["message"])) #------------------------------------------- if op.type == 55: try: if op.param1 in wait2['readPoint']: Name = cl.getContact(op.param2).displayName if Name in wait2['readMember'][op.param1]: pass else: wait2['readMember'][op.param1] += "\n・ " + Name + datetime.today().strftime(' [%d - %H:%M:%S]') wait2['ROM'][op.param1][op.param2] = "・ " + Name wait2['setTime'][msg.to] = datetime.today().strftime('%Y-%m-%d %H:%M:%S') else: pass except: pass #-------------------NOTIFIED_READ_MESSAGE---------------- if op.type == 55: try: group_id = op.param1 user_id=op.param2 subprocess.Popen('echo "'+ user_id+'|'+str(op.createdTime)+'" >> dataSeen/%s.txt' % group_id, shell=True, stdout=subprocess.PIPE, ) except Exception as e: print e #------------------------------------------ if op.type == 11: if op.param3 == '1': if op.param1 in wait['pname']: try: G = cl.getGroup(op.param1) except: try: G = ki.getGroup(op.param1) except: try: G = kk.getGroup(op.param1) except: try: G = kc.getGroup(op.param1) except: try: G = ks.getGroup(op.param1) except: try: G = kt.getGroup(op.param1) except: pass G.name = wait['pro_name'][op.param1] try: cl.updateGroup(G) except: try: ki.updateGroup(G) except: try: kk.updateGroup(G) except: try: kc.updateGroup(G) except: try: ks.updateGroup(G) except: try: kt.updateGroup(G) except: pass if op.param2 in ken: pass else: try: ki.kickoutFromGroup(op.param1,[op.param2]) except: try: kk.kickoutFromGroup(op.param1,[op.param2]) except: try: kc.kickoutFromGroup(op.param1,[op.param2]) except: try: ks.kickoutFromGroup(op.param1,[op.param2]) except: try: kt.kickoutFromGroup(op.param1,[op.param2]) except: pass kk.sendText(op.param1,"please do not change group name-_-") c = Message(to=op.param1, from_=None, text=None, contentType=13) c.contentMetadata={'mid':op.param2} cl.sendMessage(c) if op.type == 13: if op.param3 in mid: if op.param2 in Amid: G = ki.getGroup(op.param1) G.preventJoinByTicket = False ki.updateGroup(G) Ticket = ki.reissueGroupTicket(op.param1) cl.acceptGroupInvitationByTicket(op.param1,Ticket) G.preventJoinByTicket = True ki.updateGroup(G) Ticket = ki.reissueGroupTicket(op.param1) if op.param3 in Amid: if op.param2 in Bmid: X = kk.getGroup(op.param1) X.preventJoinByTicket = False kk.updateGroup(X) Ti = kk.reissueGroupTicket(op.param1) ki.acceptGroupInvitationByTicket(op.param1,Ticket) X.preventJoinByTicket = True kk.updateGroup(X) Ti = kk.reissueGroupTicket(op.param1) if op.param3 in Bmid: if op.param2 in Cmid: X = kc.getGroup(op.param1) X.preventJoinByTicket = False kc.updateGroup(X) Ti = kc.reissueGroupTicket(op.param1) kk.acceptGroupInvitationByTicket(op.param1,Ticket) X.preventJoinByTicket = True kc.updateGroup(X) Ti = kc.reissueGroupTicket(op.param1) if op.param3 in Cmid: if op.param2 in Dmid: X = kd.getGroup(op.param1) X.preventJoinByTicket = False kd.updateGroup(X) Ti = kd.reissueGroupTicket(op.param1) kc.acceptGroupInvitationByTicket(op.param1,Ticket) X.preventJoinByTicket = True kd.updateGroup(X) Ti = kd.reissueGroupTicket(op.param1) if op.param3 in Dmid: if op.param2 in Emid: X = ke.getGroup(op.param1) X.preventJoinByTicket = False ke.updateGroup(X) Ti = ke.reissueGroupTicket(op.param1) kd.acceptGroupInvitationByTicket(op.param1,Ticket) X.preventJoinByTicket = True ke.updateGroup(X) Ti = ke.reissueGroupTicket(op.param1) if op.param3 in Emid: if op.param2 in mid: X = kf.getGroup(op.param1) X.preventJoinByTicket = False kf.updateGroup(X) Ti = kf.reissueGroupTicket(op.param1) ke.acceptGroupInvitationByTicket(op.param1,Ticket) X.preventJoinByTicket = True kf.updateGroup(X) Ti = kf.reissueGroupTicket(op.param1) #===================================================================================== if op.param3 in mid: if op.param2 in Bmid: X = kk.getGroup(op.param1) X.preventJoinByTicket = False kk.updateGroup(X) Ti = kk.reissueGroupTicket(op.param1) cl.acceptGroupInvitationByTicket(op.param1,Ticket) X.preventJoinByTicket = True kk.updateGroup(X) Ti = kk.reissueGroupTicket(op.param1) if op.param3 in mid: if op.param2 in Cmid: X = kc.getGroup(op.param1) X.preventJoinByTicket = False kc.updateGroup(X) Ti = kc.reissueGroupTicket(op.param1) cl.acceptGroupInvitationByTicket(op.param1,Ticket) X.preventJoinByTicket = True kc.updateGroup(X) Ti = kc.reissueGroupTicket(op.param1) if op.param3 in mid: if op.param2 in Dmid: X = ks.getGroup(op.param1) X.preventJoinByTicket = False ks.updateGroup(X) Ti = ks.reissueGroupTicket(op.param1) CL.acceptGroupInvitationByTicket(op.param1,Ticket) X.preventJoinByTicket = True ks.updateGroup(X) Ti = ks.reissueGroupTicket(op.param1) if op.param3 in mid: if op.param2 in Emid: X = kt.getGroup(op.param1) X.preventJoinByTicket = False kt.updateGroup(X) Ti = kt.reissueGroupTicket(op.param1) cl.acceptGroupInvitationByTicket(op.param1,Ticket) X.preventJoinByTicket = True kt.updateGroup(X) Ti = kt.reissueGroupTicket(op.param1) #====================================================== if op.param3 in Bmid: if op.param2 in mid: G = cl.getGroup(op.param1) G.preventJoinByTicket = False cl.updateGroup(G) Ticket = cl.reissueGroupTicket(op.param1) kk.acceptGroupInvitationByTicket(op.param1,Ticket) G.preventJoinByTicket = True cl.updateGroup(G) Ticket = cl.reissueGroupTicket(op.param1) if op.param3 in Bmid: if op.param2 in Cmid: G = kc.getGroup(op.param1) G.preventJoinByTicket = False kc.updateGroup(G) Ticket = kc.reissueGroupTicket(op.param1) kk.acceptGroupInvitationByTicket(op.param1,Ticket) G.preventJoinByTicket = True kc.updateGroup(G) Ticket = kc.reissueGroupTicket(op.param1) if op.param3 in Bmid: if op.param2 in Dmid: G = ks.getGroup(op.param1) G.preventJoinByTicket = False ks.updateGroup(G) Ticket = ks.reissueGroupTicket(op.param1) kk.acceptGroupInvitationByTicket(op.param1,Ticket) G.preventJoinByTicket = True ks.updateGroup(G) Ticket = ks.reissueGroupTicket(op.param1) if op.param3 in Bmid: if op.param2 in Emid: G = kt.getGroup(op.param1) G.preventJoinByTicket = False kt.updateGroup(G) Ticket = kt.reissueGroupTicket(op.param1) kk.acceptGroupInvitationByTicket(op.param1,Ticket) G.preventJoinByTicket = True kt.updateGroup(G) Ticket = kt.reissueGroupTicket(op.param1) #========================================================================= #=========================================== if op.type == 32: if not op.param2 in Bots and admin: if wait["protectionOn"] == True: try: klist=[ki,kk,kc,ks,kt] kicker = random.choice(klist) G = kicker.getGroup(op.param1) kicker.kickoutFromGroup(op.param1,[op.param2]) kicker.inviteIntoGroup(op.param1, [op.param3]) except Exception, e: print e if op.type == 13: if mid in op.param3: G = cl.getGroup(op.param1) if wait["autoJoin"] == True: if wait["autoCancel"]["on"] == True: if len(G.members) <= wait["autoCancel"]["members"]: cl.rejectGroupInvitation(op.param1) else: cl.acceptGroupInvitation(op.param1) else: cl.acceptGroupInvitation(op.param1) elif wait["autoCancel"]["on"] == True: if len(G.members) <= wait["autoCancel"]["members"]: cl.rejectGroupInvitation(op.param1) else: Inviter = op.param3.replace("",',') InviterX = Inviter.split(",") matched_list = [] for tag in wait["blacklist"]: matched_list+=filter(lambda str: str == tag, InviterX) if matched_list == []: pass else: cl.cancelGroupInvitation(op.param1, matched_list) if Amid in op.param3: G = cl.getGroup(op.param1) if wait["autoJoin"] == True: if wait["autoCancel"]["on"] == True: if len(G.members) <= wait["autoCancel"]["members"]: ki.rejectGroupInvitation(op.param1) else: ki.acceptGroupInvitation(op.param1) else: ki.acceptGroupInvitation(op.param1) elif wait["autoCancel"]["on"] == True: if len(G.members) <= wait["autoCancel"]["members"]: ki.rejectGroupInvitation(op.param1) else: Inviter = op.param3.replace("",',') InviterX = Inviter.split(",") matched_list = [] for tag in wait["blacklist"]: matched_list+=filter(lambda str: str == tag, InviterX) if matched_list == []: pass else: ki.cancelGroupInvitation(op.param1, matched_list) if Bmid in op.param3: G = cl.getGroup(op.param1) if wait["autoJoin"] == True: if wait["autoCancel"]["on"] == True: if len(G.members) <= wait["autoCancel"]["members"]: kk.rejectGroupInvitation(op.param1) else: kk.acceptGroupInvitation(op.param1) else: kk.acceptGroupInvitation(op.param1) elif wait["autoCancel"]["on"] == True: if len(G.members) <= wait["autoCancel"]["members"]: kk.rejectGroupInvitation(op.param1) else: Inviter = op.param3.replace("",',') InviterX = Inviter.split(",") matched_list = [] for tag in wait["blacklist"]: matched_list+=filter(lambda str: str == tag, InviterX) if matched_list == []: pass else: kk.cancelGroupInvitation(op.param1, matched_list) if Cmid in op.param3: G = cl.getGroup(op.param1) if wait["autoJoin"] == True: if wait["autoCancel"]["on"] == True: if len(G.members) <= wait["autoCancel"]["members"]: kc.rejectGroupInvitation(op.param1) else: kc.acceptGroupInvitation(op.param1) else: kc.acceptGroupInvitation(op.param1) elif wait["autoCancel"]["on"] == True: if len(G.members) <= wait["autoCancel"]["members"]: kc.rejectGroupInvitation(op.param1) else: Inviter = op.param3.replace("^^",',') InviterX = Inviter.split(",") matched_list = [] for tag in wait["blacklist"]: matched_list+=filter(lambda str: str == tag, InviterX) if matched_list == []: pass else: kc.cancelGroupInvitation(op.param1, matched_list) if op.type == 17: if op.param3 in wait["blacklist"]: if not op.param2 in Bots and admin: random.choice(KAC).kickoutFromGroup(op.param1,[op.param3]) cl.sendText(op.param1,"blacklist users are not allowed to sign in -_-") c = Message(to=op.param1, from_=None, text=None, contentType=13) c.contentMetadata={'mid':op.param3} cl.sendMessage(c) if op.type == 17: if wait["welcomemsg"] == True: if op.param2 not in Bots: ginfo = cl.getGroup(op.param1) cl.sendText(op.param1,cl.getContact(op.param2).displayName + wait["welmsg"]+ str(ginfo.name)) if op.type == 11: if not op.param2 in Bots: if wait["qr"] == True: try: klist=[ki,kk,kc,ks,kt] kicker = random.choice(klist) G = kicker.getGroup(op.param1) G.preventJoinByTicket = True kicker.updateGroup(G) except Exception, e: print e if op.type == 11: if not op.param2 in Bots and admin: if wait["protectionOn"] == True: try: klist=[ki,kk,kc,ks,kt] kicker = random.choice(klist) G = kicker.getGroup(op.param1) G.preventJoinByTicket = True kicker.updateGroup(G) kicker.kickoutFromGroup(op.param1,[op.param2]) G.preventJoinByTicket = True kicker.updateGroup(G) cl.sendText(op.param1,"please do not open link group-_-") c = Message(to=op.param1, from_=None, text=None, contentType=13) c.contentMetadata={'mid':op.param2} cl.sendMessage(c) except Exception, e: print e if op.type == 13: G = cl.getGroup(op.param1) I = G.creator if not op.param2 in Bots and admin: if wait["protectionOn"] == True: klist=[ki,kk,kc,ks,kt] kicker = random.choice(klist) G = kicker.getGroup(op.param1) if G is not None: gInviMids = [contact.mid for contact in G.invitee] kicker.cancelGroupInvitation(op.param1, gInviMids) kicker.kickoutFromGroup(op.param1,[op.param2]) cl.sendText(op.param1,"you are prohibited from inviting-_-") c = Message(to=op.param1, from_=None, text=None, contentType=13) c.contentMetadata={'mid':op.param2} cl.sendMessage(c) if op.type == 15: if op.param2 in admin: random.choice(KAC).inviteIntoGroup(op.param1,[op.param2]) if op.type == 19: if op.param2 in Bots: if op.param3 in admin: random.choice(KAC).inviteIntoGroup(op.param1, [op.param3]) if op.type == 19: if not op.param2 in Bots: if op.param3 in admin: random.choice(KAC).inviteIntoGroup(op.param1, [op.param3]) random.choice(KAC).kickoutFromGroup(op.param1,[op.param2]) if op.type == 19: if not op.param2 in Bots: try: gs = ki.getGroup(op.param1) gs = kk.getGroup(op.param1) targets = [op.param2] for target in targets: try: wait["blacklist"][target] = True f=codecs.open('st2__b.json','w','utf-8') json.dump(wait["blacklist"], f, sort_keys=True, indent=4,ensure_ascii=False) except: pass except Exception, e: print e if not op.param2 in Bots and admin: if wait["Backup"] == True: try: random.choice(KAC).inviteIntoGroup(op.param1, [op.param3]) except Exception, e: print e if not op.param2 in Bots and admin: if wait["protectionOn"] == True: try: klist=[ki,kk,kc,ks,kt] kicker = random.choice(klist) G = kicker.getGroup(op.param1) G.preventJoinByTicket = False kicker.updateGroup(G) invsend = 0 Ticket = kicker.reissueGroupTicket(op.param1) kl.acceptGroupInvitationByTicket(op.param1,Ticket) time.sleep(0.2) X = kicker.getGroup(op.param1) X.preventJoinByTicket = True kl.kickoutFromGroup(op.param1,[op.param2]) kicker.kickoutFromGroup(op.param1,[op.param2]) kl.leaveGroup(op.param1) kicker.updateGroup(X) except Exception, e: print e if not op.param2 in Bots and admin: try: gs = ki.getGroup(op.param1) gs = kk.getGroup(op.param1) targets = [op.param2] for target in targets: try: wait["blacklist"][target] = True f=codecs.open('st2__b.json','w','utf-8') json.dump(wait["blacklist"], f, sort_keys=True, indent=4,ensure_ascii=False) except: pass except Exception, e: print e if not op.param2 in Bots and admin: if wait["Backup"] == True: try: random.choice(KAC).inviteIntoGroup(op.param1, [op.param3]) except Exception, e: print e if op.type == 19: if mid in op.param3: if op.param2 in Bots: pass try: ki.kickoutFromGroup(op.param1,[op.param2]) except: try: random.choice(KAC).kickoutFromGroup(op.param1,[op.param2]) except: print ("client Kick regulation or Because it does not exist in the group、\n["+op.param1+"]\nの\n["+op.param2+"]\nを蹴る事ができませんでした。\nブラックリストに追加します。") if op.param2 in wait["blacklist"]: pass if op.param2 in wait["whitelist"]: pass else: wait["blacklist"][op.param2] = True G = ki.getGroup(op.param1) G.preventJoinByTicket = False ki.updateGroup(G) Ti = ki.reissueGroupTicket(op.param1) cl.acceptGroupInvitationByTicket(op.param1,Ti) ki.acceptGroupInvitationByTicket(op.param1,Ti) kk.acceptGroupInvitationByTicket(op.param1,Ti) kc.acceptGroupInvitationByTicket(op.param1,Ti) ks.acceptGroupInvitationByTicket(op.param1,Ti) kt.acceptGroupInvitationByTicket(op.param1,Ti) X = cl.getGroup(op.param1) X.preventJoinByTicket = True cl.updateGroup(X) Ti = cl.reissueGroupTicket(op.param1) if op.param2 in wait["blacklist"]: pass if op.param2 in wait["whitelist"]: pass else: wait["blacklist"][op.param2] = True if Amid in op.param3: if op.param2 in Bots: pass try: kk.kickoutFromGroup(op.param1,[op.param2]) except: try: random.choice(KAC).kickoutFromGroup(op.param1,[op.param2]) except: print ("client が蹴り規制orグループに存在しない為、\n["+op.param1+"]\nの\n["+op.param2+"]\nBecause the client does not exist in the kick regulation or group.\nAdd it to the blacklist.") if op.param2 in wait["blacklist"]: pass if op.param2 in wait["whitelist"]: pass else: wait["blacklist"][op.param2] = True X = kk.getGroup(op.param1) X.preventJoinByTicket = False kk.updateGroup(X) Ti = kk.reissueGroupTicket(op.param1) cl.acceptGroupInvitationByTicket(op.param1,Ti) ki.acceptGroupInvitationByTicket(op.param1,Ti) kk.acceptGroupInvitationByTicket(op.param1,Ti) kc.acceptGroupInvitationByTicket(op.param1,Ti) ks.acceptGroupInvitationByTicket(op.param1,Ti) kt.acceptGroupInvitationByTicket(op.param1,Ti) X = ki.getGroup(op.param1) X.preventJoinByTicket = True ki.updateGroup(X) Ticket = ki.reissueGroupTicket(op.param1) if op.param2 in wait["blacklist"]: pass if op.param2 in wait["whitelist"]: pass else: wait["blacklist"][op.param2] = True if Bmid in op.param3: if op.param2 in Bots: pass try: kc.kickoutFromGroup(op.param1,[op.param2]) except: try: random.choice(KAC).kickoutFromGroup(op.param1,[op.param2]) except: print ("client が蹴り規制orグループに存在しない為、\n["+op.param1+"]\nの\n["+op.param2+"]\nBecause the client does not exist in the kick regulation or group.\nAdd it to the blacklist.") if op.param2 in wait["blacklist"]: pass if op.param2 in wait["whitelist"]: pass else: wait["blacklist"][op.param2] = True X = kc.getGroup(op.param1) X.preventJoinByTicket = False kc.updateGroup(X) Ti = kc.reissueGroupTicket(op.param1) cl.acceptGroupInvitationByTicket(op.param1,Ti) ki.acceptGroupInvitationByTicket(op.param1,Ti) kk.acceptGroupInvitationByTicket(op.param1,Ti) kc.acceptGroupInvitationByTicket(op.param1,Ti) ks.acceptGroupInvitationByTicket(op.param1,Ti) kt.acceptGroupInvitationByTicket(op.param1,Ti) X = kk.getGroup(op.param1) X.preventJoinByTicket = True kk.updateGroup(X) Ticket = kk.reissueGroupTicket(op.param1) if op.param2 in wait["blacklist"]: pass if op.param2 in wait["whitelist"]: pass else: wait["blacklist"][op.param2] = True if Cmid in op.param3: if op.param2 in Bots: pass try: kd.kickoutFromGroup(op.param1,[op.param2]) except: try: random.choice(KAC).kickoutFromGroup(op.param1,[op.param2]) except: print ("client が蹴り規制orグループに存在しない為、\n["+op.param1+"]\nの\n["+op.param2+"]\nBecause the client does not exist in the kick regulation or group.\nAdd it to the blacklist.") if op.param2 in wait["blacklist"]: pass if op.param2 in wait["whitelist"]: pass else: wait["blacklist"][op.param2] = True X = kd.getGroup(op.param1) X.preventJoinByTicket = False kd.updateGroup(X) Ti = kd.reissueGroupTicket(op.param1) cl.acceptGroupInvitationByTicket(op.param1,Ti) ki.acceptGroupInvitationByTicket(op.param1,Ti) kk.acceptGroupInvitationByTicket(op.param1,Ti) kc.acceptGroupInvitationByTicket(op.param1,Ti) ks.acceptGroupInvitationByTicket(op.param1,Ti) kt.acceptGroupInvitationByTicket(op.param1,Ti) X = kc.getGroup(op.param1) X.preventJoinByTicket = True kc.updateGroup(X) Ticket = kc.reissueGroupTicket(op.param1) if op.param2 in wait["blacklist"]: pass if op.param2 in wait["whitelist"]: pass else: wait["blacklist"][op.param2] = True if Dmid in op.param3: if op.param2 in Bots: pass try: ke.kickoutFromGroup(op.param1,[op.param2]) except: try: random.choice(KAC).kickoutFromGroup(op.param1,[op.param2]) except: print ("client が蹴り規制orグループに存在しない為、\n["+op.param1+"]\nの\n["+op.param2+"]\nBecause the client does not exist in the kick regulation or group.\nAdd it to the blacklist.") if op.param2 in wait["blacklist"]: pass if op.param2 in wait["whitelist"]: pass else: wait["blacklist"][op.param2] = True X = ke.getGroup(op.param1) X.preventJoinByTicket = False ke.updateGroup(X) Ti = ke.reissueGroupTicket(op.param1) cl.acceptGroupInvitationByTicket(op.param1,Ti) ki.acceptGroupInvitationByTicket(op.param1,Ti) kk.acceptGroupInvitationByTicket(op.param1,Ti) kc.acceptGroupInvitationByTicket(op.param1,Ti) ks.acceptGroupInvitationByTicket(op.param1,Ti) kt.acceptGroupInvitationByTicket(op.param1,Ti) X = kd.getGroup(op.param1) X.preventJoinByTicket = True kd.updateGroup(X) Ticket = kd.reissueGroupTicket(op.param1) if op.param2 in wait["blacklist"]: pass if op.param2 in wait["whitelist"]: pass else: wait["blacklist"][op.param2] = True if Emid in op.param3: if op.param2 in Bots: pass try: kf.kickoutFromGroup(op.param1,[op.param2]) except: try: random.choice(KAC).kickoutFromGroup(op.param1,[op.param2]) except: print ("client が蹴り規制orグループに存在しない為、\n["+op.param1+"]\nの\n["+op.param2+"]\nBecause the client does not exist in the kick regulation or group.\nAdd it to the blacklist.") if op.param2 in wait["blacklist"]: pass if op.param2 in wait["whitelist"]: pass else: wait["blacklist"][op.param2] = True X = kf.getGroup(op.param1) X.preventJoinByTicket = False kf.updateGroup(X) Ti = kf.reissueGroupTicket(op.param1) cl.acceptGroupInvitationByTicket(op.param1,Ti) ki.acceptGroupInvitationByTicket(op.param1,Ti) kk.acceptGroupInvitationByTicket(op.param1,Ti) kc.acceptGroupInvitationByTicket(op.param1,Ti) ks.acceptGroupInvitationByTicket(op.param1,Ti) kt.acceptGroupInvitationByTicket(op.param1,Ti) X = ke.getGroup(op.param1) X.preventJoinByTicket = True ke.updateGroup(X) Ticket = ke.reissueGroupTicket(op.param1) if op.param2 in wait["blacklist"]: pass if op.param2 in wait["whitelist"]: pass else: wait["blacklist"][op.param2] = True #======================================================================== if Fmid in op.param3: if op.param2 in Bots and admin: pass try: kg.kickoutFromGroup(op.param1,[op.param2]) except: try: random.choice(KAC).kickoutFromGroup(op.param1,[op.param2]) except: print ("client が蹴り規制orグループに存在しない為、\n["+op.param1+"]\nの\n["+op.param2+"]\nBecause the client does not exist in the kick regulation or group.\nAdd it to the blacklist.") if op.param2 in wait["blacklist"]: pass if op.param2 in wait["whitelist"]: pass else: wait["blacklist"][op.param2] = True X = kg.getGroup(op.param1) X.preventJoinByTicket = False kg.updateGroup(X) Ti = kg.reissueGroupTicket(op.param1) cl.acceptGroupInvitationByTicket(op.param1,Ti) ki.acceptGroupInvitationByTicket(op.param1,Ti) kk.acceptGroupInvitationByTicket(op.param1,Ti) kc.acceptGroupInvitationByTicket(op.param1,Ti) kd.acceptGroupInvitationByTicket(op.param1,Ti) ke.acceptGroupInvitationByTicket(op.param1,Ti) kf.acceptGroupInvitationByTicket(op.param1,Ti) kg.acceptGroupInvitationByTicket(op.param1,Ti) kh.acceptGroupInvitationByTicket(op.param1,Ti) kn.acceptGroupInvitationByTicket(op.param1,Ti) ko.acceptGroupInvitationByTicket(op.param1,Ti) kp.acceptGroupInvitationByTicket(op.param1,Ti) kq.acceptGroupInvitationByTicket(op.param1,Ti) kr.acceptGroupInvitationByTicket(op.param1,Ti) ks.acceptGroupInvitationByTicket(op.param1,Ti) kt.acceptGroupInvitationByTicket(op.param1,Ti) X = kf.getGroup(op.param1) X.preventJoinByTicket = True kf.updateGroup(X) Ticket = kf.reissueGroupTicket(op.param1) if op.param2 in wait["blacklist"]: pass if op.param2 in wait["whitelist"]: pass else: wait["blacklist"][op.param2] = True if Gmid in op.param3: if op.param2 in Bots: pass try: kh.kickoutFromGroup(op.param1,[op.param2]) except: try: random.choice(KAC).kickoutFromGroup(op.param1,[op.param2]) except: print ("client が蹴り規制orグループに存在しない為、\n["+op.param1+"]\nの\n["+op.param2+"]\nBecause the client does not exist in the kick regulation or group.\nAdd it to the blacklist.") if op.param2 in wait["blacklist"]: pass if op.param2 in wait["whitelist"]: pass else: wait["blacklist"][op.param2] = True X = kh.getGroup(op.param1) X.preventJoinByTicket = False kh.updateGroup(X) Ti = kh.reissueGroupTicket(op.param1) cl.acceptGroupInvitationByTicket(op.param1,Ti) ki.acceptGroupInvitationByTicket(op.param1,Ti) kk.acceptGroupInvitationByTicket(op.param1,Ti) kc.acceptGroupInvitationByTicket(op.param1,Ti) kd.acceptGroupInvitationByTicket(op.param1,Ti) ke.acceptGroupInvitationByTicket(op.param1,Ti) kf.acceptGroupInvitationByTicket(op.param1,Ti) kg.acceptGroupInvitationByTicket(op.param1,Ti) kh.acceptGroupInvitationByTicket(op.param1,Ti) kn.acceptGroupInvitationByTicket(op.param1,Ti) ko.acceptGroupInvitationByTicket(op.param1,Ti) kp.acceptGroupInvitationByTicket(op.param1,Ti) kq.acceptGroupInvitationByTicket(op.param1,Ti) kr.acceptGroupInvitationByTicket(op.param1,Ti) ks.acceptGroupInvitationByTicket(op.param1,Ti) kt.acceptGroupInvitationByTicket(op.param1,Ti) X = kg.getGroup(op.param1) X.preventJoinByTicket = True kg.updateGroup(X) Ticket = kg.reissueGroupTicket(op.param1) if op.param2 in wait["blacklist"]: pass if op.param2 in wait["whitelist"]: pass else: wait["blacklist"][op.param2] = True if Hmid in op.param3: if op.param2 in Bots: pass try: kj.kickoutFromGroup(op.param1,[op.param2]) except: try: random.choice(KAC).kickoutFromGroup(op.param1,[op.param2]) except: print ("client が蹴り規制orグループに存在しない為、\n["+op.param1+"]\nの\n["+op.param2+"]\nBecause the client does not exist in the kick regulation or group.\nAdd it to the blacklist.") if op.param2 in wait["blacklist"]: pass if op.param2 in wait["whitelist"]: pass else: wait["blacklist"][op.param2] = True X = kj.getGroup(op.param1) X.preventJoinByTicket = False kj.updateGroup(X) Ti = kj.reissueGroupTicket(op.param1) cl.acceptGroupInvitationByTicket(op.param1,Ti) ki.acceptGroupInvitationByTicket(op.param1,Ti) kk.acceptGroupInvitationByTicket(op.param1,Ti) kc.acceptGroupInvitationByTicket(op.param1,Ti) kd.acceptGroupInvitationByTicket(op.param1,Ti) ke.acceptGroupInvitationByTicket(op.param1,Ti) kf.acceptGroupInvitationByTicket(op.param1,Ti) kg.acceptGroupInvitationByTicket(op.param1,Ti) kh.acceptGroupInvitationByTicket(op.param1,Ti) kn.acceptGroupInvitationByTicket(op.param1,Ti) ko.acceptGroupInvitationByTicket(op.param1,Ti) kp.acceptGroupInvitationByTicket(op.param1,Ti) kq.acceptGroupInvitationByTicket(op.param1,Ti) kr.acceptGroupInvitationByTicket(op.param1,Ti) ks.acceptGroupInvitationByTicket(op.param1,Ti) kt.acceptGroupInvitationByTicket(op.param1,Ti) X = kh.getGroup(op.param1) X.preventJoinByTicket = True kh.updateGroup(X) Ticket = kh.reissueGroupTicket(op.param1) if op.param2 in wait["blacklist"]: pass if op.param2 in wait["whitelist"]: pass else: wait["blacklist"][op.param2] = True if Jmid in op.param3: if op.param2 in Bots: pass try: cl.kickoutFromGroup(op.param1,[op.param2]) except: try: random.choice(KAC).kickoutFromGroup(op.param1,[op.param2]) except: print ("client が蹴り規制orグループに存在しない為、\n["+op.param1+"]\nの\n["+op.param2+"]\nBecause the client does not exist in the kick regulation or group.\nAdd it to the blacklist.") if op.param2 in wait["blacklist"]: pass if op.param2 in wait["whitelist"]: pass else: wait["blacklist"][op.param2] = True G = cl.getGroup(op.param1) G.preventJoinByTicket = False cl.updateGroup(G) Ti = cl.reissueGroupTicket(op.param1) cl.acceptGroupInvitationByTicket(op.param1,Ti) ki.acceptGroupInvitationByTicket(op.param1,Ti) kk.acceptGroupInvitationByTicket(op.param1,Ti) kc.acceptGroupInvitationByTicket(op.param1,Ti) kd.acceptGroupInvitationByTicket(op.param1,Ti) ke.acceptGroupInvitationByTicket(op.param1,Ti) kf.acceptGroupInvitationByTicket(op.param1,Ti) kg.acceptGroupInvitationByTicket(op.param1,Ti) kh.acceptGroupInvitationByTicket(op.param1,Ti) kn.acceptGroupInvitationByTicket(op.param1,Ti) ko.acceptGroupInvitationByTicket(op.param1,Ti) kp.acceptGroupInvitationByTicket(op.param1,Ti) kq.acceptGroupInvitationByTicket(op.param1,Ti) kr.acceptGroupInvitationByTicket(op.param1,Ti) ks.acceptGroupInvitationByTicket(op.param1,Ti) kt.acceptGroupInvitationByTicket(op.param1,Ti) X = kj.getGroup(op.param1) X.preventJoinByTicket = True kj.updateGroup(X) Ticket = kj.reissueGroupTicket(op.param1) if op.param2 in wait["blacklist"]: pass if op.param2 in wait["whitelist"]: pass else: wait["blacklist"][op.param2] = True if Nmid in op.param3: if op.param2 in Bots: pass try: ko.kickoutFromGroup(op.param1,[op.param2]) except: try: random.choice(KAC).kickoutFromGroup(op.param1,[op.param2]) except: print ("client Kick regulation or Because it does not exist in the group、\n["+op.param1+"]\nの\n["+op.param2+"]\nを蹴る事ができませんでした。\nブラックリストに追加します。") if op.param2 in wait["blacklist"]: pass if op.param2 in wait["whitelist"]: pass else: wait["blacklist"][op.param2] = True G = ko.getGroup(op.param1) G.preventJoinByTicket = False ko.updateGroup(G) Ti = ko.reissueGroupTicket(op.param1) cl.acceptGroupInvitationByTicket(op.param1,Ti) ki.acceptGroupInvitationByTicket(op.param1,Ti) kk.acceptGroupInvitationByTicket(op.param1,Ti) kc.acceptGroupInvitationByTicket(op.param1,Ti) kd.acceptGroupInvitationByTicket(op.param1,Ti) ke.acceptGroupInvitationByTicket(op.param1,Ti) kf.acceptGroupInvitationByTicket(op.param1,Ti) kg.acceptGroupInvitationByTicket(op.param1,Ti) kh.acceptGroupInvitationByTicket(op.param1,Ti) kn.acceptGroupInvitationByTicket(op.param1,Ti) ko.acceptGroupInvitationByTicket(op.param1,Ti) kp.acceptGroupInvitationByTicket(op.param1,Ti) kq.acceptGroupInvitationByTicket(op.param1,Ti) kr.acceptGroupInvitationByTicket(op.param1,Ti) ks.acceptGroupInvitationByTicket(op.param1,Ti) kt.acceptGroupInvitationByTicket(op.param1,Ti) X = kn.getGroup(op.param1) X.preventJoinByTicket = True kn.updateGroup(X) Ti = kn.reissueGroupTicket(op.param1) if op.param2 in wait["blacklist"]: pass if op.param2 in wait["whitelist"]: pass else: wait["blacklist"][op.param2] = True #============================================================================ if op.type == 13: if mid in op.param3: G = cl.getGroup(op.param1) if wait["autoJoin"] == True: if wait["autoCancel"]["on"] == True: if len(G.members) <= wait["autoCancel"]["members"]: cl.rejectGroupInvitation(op.param1) else: cl.acceptGroupInvitation(op.param1) else: cl.acceptGroupInvitation(op.param1) elif wait["autoCancel"]["on"] == True: if len(G.members) <= wait["autoCancel"]["members"]: cl.rejectGroupInvitation(op.param1) else: Inviter = op.param3.replace("",',') InviterX = Inviter.split(",") matched_list = [] for tag in wait["blacklist"]: matched_list+=filter(lambda str: str == tag, InviterX) if matched_list == []: pass else: cl.cancelGroupInvitation(op.param1, matched_list) if op.type == 22: if wait["leaveRoom"] == True: cl.leaveRoom(op.param1) if op.type == 24: if wait["leaveRoom"] == True: cl.leaveRoom(op.param1) if op.type == 26: msg = op.message if msg.toType == 0: msg.to = msg.from_ if msg.from_ == admin: if "join:" in msg.text: list_ = msg.text.split(":") try: cl.acceptGroupInvitationByTicket(list_[1],list_[2]) X = cl.getGroup(list_[1]) X.preventJoinByTicket = True cl.updateGroup(X) except: cl.sendText(msg.to,"error") if msg.toType == 1: if wait["leaveRoom"] == True: cl.leaveRoom(msg.to) if msg.contentType == 16: url = msg.contentMetadata("line://home/post?userMid="+mid+"&postId="+"new_post") cl.like(url[25:58], url[66:], likeType=1001) ki.like(url[25:58], url[66:], likeType=1001) kk.like(url[25:58], url[66:], likeType=1001) kc.like(url[25:58], url[66:], likeType=1001) kt.like(url[25:58], url[66:], likeType=1001) ks.like(url[25:58], url[66:], likeType=1001) if op.type == 25: msg = op.message if msg.contentType == 13: if wait["wblack"] == True: if msg.contentMetadata["mid"] in wait["commentBlack"]: cl.sendText(msg.to,"already") wait["wblack"] = False else: wait["commentBlack"][msg.contentMetadata["mid"]] = True wait["wblack"] = False cl.sendText(msg.to,"decided not to comment") elif wait["dblack"] == True: if msg.contentMetadata["mid"] in wait["commentBlack"]: del wait["commentBlack"][msg.contentMetadata["mid"]] cl.sendText(msg.to,"Deleted") wait["dblack"] = False else: wait["dblack"] = False cl.sendText(msg.to,"It is not in the black list") elif wait["wblacklist"] == True: if msg.contentMetadata["mid"] in wait["blacklist"]: cl.sendText(msg.to,"already in the blacklist") wait["wblacklist"] = False else: wait["blacklist"][msg.contentMetadata["mid"]] = True wait["wblacklist"] = False cl.sendText(msg.to,"successfully load users into the blacklist") elif wait["dblacklist"] == True: if msg.contentMetadata["mid"] in wait["blacklist"]: del wait["blacklist"][msg.contentMetadata["mid"]] cl.sendText(msg.to,"successfully removed from the blacklist") wait["dblacklist"] = False else: wait["dblacklist"] = False cl.sendText(msg.to,"It is not in the black list") elif wait["contact"] == True: msg.contentType = 0 if 'displayName' in msg.contentMetadata: contact = cl.getContact(msg.contentMetadata["mid"]) try: cu = cl.channel.getCover(msg.contentMetadata["mid"]) except: cu = "" cl.sendText(msg.to,"⎈ Profile Name :\n" + msg.contentMetadata["displayName"] + "\n\n⎈ Mid :\n" + msg.contentMetadata["mid"] + "\n\n⎈ Status Message :\n" + contact.statusMessage + "\n\n⎈ Pict Status :\nhttp://dl.profile.line-cdn.net/" + contact.pictureStatus + "\n\n⎈ Cover Status :\n" + str(cu) + "\n\n [☸]➦Powered By: メDTB々•┅─────") else: contact = cl.getContact(msg.contentMetadata["mid"]) try: cu = cl.channel.getCover(msg.contentMetadata["mid"]) except: cu = "" cl.sendText(msg.to,"⎈ Profile Name :\n" + contact.displayName + "\n\n⎈ Mid :\n" + msg.contentMetadata["mid"] + "\n\n⎈ Status Mesage:\n" + contact.statusMessage + "\n\n⎈ Pict Status :\nhttp://dl.profile.line-cdn.net/" + contact.pictureStatus + "\n\n⎈ Cover Status :\n" + str(cu) + "\n\n [☸]➦Powered By: メDTB々•┅─────") elif msg.contentType == 16: if wait["contact"] == True: msg.contentType = 0 if wait["lang"] == "JP": msg.text = "post URL\n" + msg.contentMetadata["postEndUrl"] else: msg.text = "URL→\n" + msg.contentMetadata["postEndUrl"] cl.sendText(msg.to,msg.text) elif msg.text is None: return elif msg.text in ["Help","List","key"]: if msg.from_ in admin: print "\nHelp pick up..." if wait["lang"] == "JP": cl.sendText(msg.to, helpMessage + datetime.today().strftime('%H:%M:%S')) else: cl.sendText(msg.to,helpt) elif ("Group name:" in msg.text): if msg.from_ in admin: if msg.toType == 2: X = cl.getGroup(msg.to) X.name = msg.text.replace("Group name:","") cl.updateGroup(X) else: cl.sendText(msg.to,"It can't be used besides the group.") if op.type == 25: msg = op.message if msg.contentType == 13: if wait["winvite"] == True: if msg.from_ in admin: _name = msg.contentMetadata["displayName"] invite = msg.contentMetadata["mid"] groups = cl.getGroup(msg.to) pending = groups.invitee targets = [] for s in groups.members: if _name in s.displayName: cl.sendText(msg.to,"-> " + _name + " was here") break elif invite in wait["blacklist"]: ki.sendText(msg.to,"Sorry, " + _name + " On Blacklist") ki.sendText(msg.to,"Call my owner to use command !, \n➡Unban: " + invite) break else: targets.append(invite) if targets == []: pass else: for target in targets: try: cl.findAndAddContactsByMid(target) cl.inviteIntoGroup(msg.to,[target]) cl.sendText(msg.to,"Done Invite : \n➡" + _name) wait["winvite"] = False break except: try: ki.findAndAddContactsByMid(invite) ki.inviteIntoGroup(op.param1,[invite]) wait["winvite"] = False except: cl.sendText(msg.to,"Negative, Error detected") wait["winvite"] = False break elif "Invite:" in msg.text: if msg.from_ in admin: midd = msg.text.replace("Invite:"," ") cl.findAndAddContactsByMid(midd) cl.inviteIntoGroup(msg.to,[midd]) elif msg.text.lower() == 'contact bot': if msg.from_ in admin: msg.contentType = 13 msg.contentMetadata = {'mid': mid} cl.sendMessage(msg) msg.contentType = 13 msg.contentMetadata = {'mid': Amid} ki.sendMessage(msg) msg.contentType = 13 msg.contentMetadata = {'mid': Bmid} kk.sendMessage(msg) msg.contentType = 13 msg.contentMetadata = {'mid': Cmid} kc.sendMessage(msg) msg.contentType = 13 msg.contentMetadata = {'mid': Dmid} ks.sendMessage(msg) msg.contentType = 13 msg.contentMetadata = {'mid': Emid} kt.sendMessage(msg) #-----------------------------++++----------------- #======================================================= #-----------------============================= elif msg.text in ["Me","I'am"]: if msg.from_ in admin: msg.contentType = 13 msg.contentMetadata = {'mid': msg.from_} cl.sendText(msg.to,"❂•••••••┅═ই۝ई═┅••••••••❂") cl.sendMessage(msg) #h = cl.getContact(mid) #cl.sendImageWithURL(msg.to,"http://dl.profile.line-cdn.net/" + h.pictureStatus) cl.sendText(msg.to,"❂•••••••┅═ই۝ई═┅••••••••❂") cl.sendText(msg.to,"[Avrilia Ini Mahh...!!!]\nDah Gitu Aja\n[TQ]\n\n"+ datetime.now().strftime('%H:%M:%S')) elif msg.text in ["Gift","gift"]: msg.contentType = 9 msg.contentMetadata={'PRDID': 'u36196ea7137f95585062f8303dbac814', 'PRDTYPE': 'THEME', 'MSGTPL': '5'} msg.text = None cl.sendMessage(msg) elif msg.text.lower() == 'gift2': if msg.from_ in admin: msg.contentType = 9 msg.contentMetadata={'PRDID': 'u36196ea7137f95585062f8303dbac814', 'PRDTYPE': 'THEME', 'MSGTPL': '2'} msg.text = None ki.sendMessage(msg) elif msg.text.lower() == 'gift3': msg.contentType = 9 msg.contentMetadata={'PRDID': 'u36196ea7137f95585062f8303dbac814', 'PRDTYPE': 'THEME', 'MSGTPL': '3'} msg.text = None kk.sendMessage(msg) elif msg.text.lower() == 'gift4': if msg.from_ in admin: msg.contentType = 9 msg.contentMetadata={'PRDID': 'u36196ea7137f95585062f8303dbac814', 'PRDTYPE': 'THEME', 'MSGTPL': '4'} msg.text = None kc.sendMessage(msg) elif msg.text.lower() == 'gift5': if msg.from_ in admin: msg.contentType = 9 msg.contentMetadata={'PRDID': 'u36196ea7137f95585062f8303dbac814', 'PRDTYPE': 'THEME', 'MSGTPL': '5'} msg.text = None kd.sendMessage(msg) elif msg.text.lower() == 'gift6': if msg.from_ in admin: msg.contentType = 9 msg.contentMetadata={'PRDID': 'u36196ea7137f95585062f8303dbac814', 'PRDTYPE': 'THEME', 'MSGTPL': '6'} msg.text = None ke.sendMessage(msg) elif msg.text.lower() == 'spam gift': if msg.from_ in admin: msg.contentType = 9 msg.contentMetadata={'PRDID': 'u36196ea7137f95585062f8303dbac814', 'PRDTYPE': 'THEME', 'MSGTPL': '12'} msg.text = None ki.sendMessage(msg) kk.sendMessage(msg) kc.sendMessage(msg) cl.sendMessage(msg) ks.sendMessage(msg) kt.sendMessage(msg) kt.sendMessage(msg) #================================================= #================================================== elif "All rename:" in msg.text: if msg.from_ in owner: string = msg.text.replace("All rename:","") if len(string.decode('utf-8')) <= 20: profile = cl.getProfile() profile.displayName = string cl.updateProfile(profile) if len(string.decode('utf-8')) <= 20: profile = ki.getProfile() profile.displayName = string ki.updateProfile(profile) if len(string.decode('utf-8')) <= 20: profile = kc.getProfile() profile.displayName = string kc.updateProfile(profile) if len(string.decode('utf-8')) <= 20: profile = kk.getProfile() profile.displayName = string kk.updateProfile(profile) if len(string.decode('utf-8')) <= 20: profile = ks.getProfile() profile.displayName = string ks.updateProfile(profile) if len(string.decode('utf-8')) <= 20: profile = kt.getProfile() profile.displayName = string kt.updateProfile(profile) cl.sendText(msg.to,"change name: "+string+"\nsucces") elif msg.text.lower() == 'Allbio:': if msg.from_ in owner: string = msg.text.lower().replace("allbio:","") if len(string.decode('utf-8')) <= 500: profile = ki.getProfile() profile.statusMessage = string ki.updateProfile(profile) if len(string.decode('utf-8')) <= 500: profile = kk.getProfile() profile.statusMessage = string kk.updateProfile(profile) if len(string.decode('utf-8')) <= 500: profile = kc.getProfile() profile.statusMessage = string kc.updateProfile(profile) if len(string.decode('utf-8')) <= 500: profile = cl.getProfile() profile.statusMessage = string cl.updateProfile(profile) if len(string.decode('utf-8')) <= 500: profile = ks.getProfile() profile.statusMessage = string ks.updateProfile(profile) if len(string.decode('utf-8')) <= 500: profile = kt.getProfile() profile.statusMessage = string kt.updateProfile(profile) cl.sendText(msg.to,"successfully turn it into: " + string + "") elif "Rename:" in msg.text: if msg.from_ in owner: string = msg.text.replace("Bot1 rename:","") if len(string.decode('utf-8')) <= 20: profile = cl.getProfile() profile.displayName = string cl.updateProfile(profile) cl.sendText(msg.to,"change name: "+string+"\nsucces") elif "Bot2 rename:" in msg.text: if msg.from_ in owner: string = msg.text.replace("Bot2 rename:","") if len(string.decode('utf-8')) <= 20: profile = ki.getProfile() profile.displayName = string ki.updateProfile(profile) ki.sendText(msg.to,"change name: "+string+"\nsucces") elif "Bot3 rename:" in msg.text: if msg.from_ in owner: string = msg.text.replace("Bot3 rename:","") if len(string.decode('utf-8')) <= 20: profile = kc.getProfile() profile.displayName = string kc.updateProfile(profile) kc.sendText(msg.to,"change name: "+string+"\nsucces") elif "Bot4 rename:" in msg.text: if msg.from_ in owner: string = msg.text.replace("Bot4 rename:","") if len(string.decode('utf-8')) <= 20: profile = kk.getProfile() profile.displayName = string kk.updateProfile(profile) kk.sendText(msg.to,"change name: "+string+"\nsucces") elif "Bot5 rename:" in msg.text: if msg.from_ in owner: string = msg.text.replace("Bot5 rename:","") if len(string.decode('utf-8')) <= 20: profile = ks.getProfile() profile.displayName = string ks.updateProfile(profile) ks.sendText(msg.to,"change name: "+string+"\nsucces") elif "Bot6 rename:" in msg.text: if msg.from_ in owner: string = msg.text.replace("Bot6 rename:","") if len(string.decode('utf-8')) <= 20: profile = kt.getProfile() profile.displayName = string kt.updateProfile(profile) kt.sendText(msg.to,"change name: "+string+"\nsucces") #================================================== elif 'lyric ' in msg.text.lower(): if msg.from_ in admin: try: songname = msg.text.lower().replace('lyric ','') params = {'songname': songname} r = requests.get('http://ide.fdlrcn.com/workspace/yumi-apis/joox?' + urllib.urlencode(params)) data = r.text data = json.loads(data) for song in data: hasil = 'Lyric Lagu (' hasil += song[0] hasil += ')\n\n' hasil += song[5] cl.sendText(msg.to, hasil) except Exception as wak: cl.sendText(msg.to, str(wak)) elif 'wiki ' in msg.text.lower(): if msg.from_ in admin: try: wiki = msg.text.lower().replace("wiki ","") wikipedia.set_lang("id") pesan="Title (" pesan+=wikipedia.page(wiki).title pesan+=")\n\n" pesan+=wikipedia.summary(wiki, sentences=1) pesan+="\n" pesan+=wikipedia.page(wiki).url cl.sendText(msg.to, pesan) except: try: pesan="Over Text Limit! Please Click link\n" pesan+=wikipedia.page(wiki).url cl.sendText(msg.to, pesan) except Exception as e: cl.sendText(msg.to, str(e)) elif msg.text.lower() == 'bot restart': if msg.from_ in admin: print "[Command]Like executed" try: cl.sendText(msg.to,"Restarting...") restart_program() except: cl.sendText(msg.to,"Please wait") restart_program() pass elif msg.text.lower() == 'ifconfig': if msg.from_ in admin: botKernel = subprocess.Popen(["ifconfig"], stdout=subprocess.PIPE).communicate()[0] cl.sendText(msg.to, botKernel + "\n\n===SERVER INFO NetStat===") elif msg.text.lower() == 'system': if msg.from_ in admin: botKernel = subprocess.Popen(["df","-h"], stdout=subprocess.PIPE).communicate()[0] cl.sendText(msg.to, botKernel + "\n\n===SERVER INFO SYSTEM===") elif msg.text.lower() == 'kernel': if msg.from_ in admin: botKernel = subprocess.Popen(["uname","-srvmpio"], stdout=subprocess.PIPE).communicate()[0] cl.sendText(msg.to, botKernel + "\n\n===SERVER INFO KERNEL===") elif msg.text.lower() == 'cpu': if msg.from_ in admin: botKernel = subprocess.Popen(["cat","/proc/cpuinfo"], stdout=subprocess.PIPE).communicate()[0] cl.sendText(msg.to, botKernel + "\n\n===SERVER INFO CPU===") elif 'instagram ' in msg.text.lower(): if msg.from_ in admin: try: instagram = msg.text.lower().replace("instagram ","") html = requests.get('https://www.instagram.com/' + instagram + '/?') soup = BeautifulSoup(html.text, 'html5lib') data = soup.find_all('meta', attrs={'property':'og:description'}) text = data[0].get('content').split() data1 = soup.find_all('meta', attrs={'property':'og:image'}) text1 = data1[0].get('content').split() user = "Name: " + text[-2] + "\n" user1 = "Username: " + text[-1] + "\n" followers = "Followers: " + text[0] + "\n" following = "Following: " + text[2] + "\n" post = "Post: " + text[4] + "\n" link = "Link: " + "https://www.instagram.com/" + instagram detail = "======INSTAGRAM INFO USER======\n" details = "\n======INSTAGRAM INFO USER======" cl.sendText(msg.to, detail + user + user1 + followers + following + post + link + details) cl.sendImageWithURL(msg.to, text1[0]) except Exception as njer: cl.sendText(msg.to, str(njer)) elif 'music ' in msg.text.lower(): if msg.from_ in admin: try: songname = msg.text.lower().replace('music ','') params = {'songname': songname} r = requests.get('http://ide.fdlrcn.com/workspace/yumi-apis/joox?' + urllib.urlencode(params)) data = r.text data = json.loads(data) for song in data: hasil = 'This is Your Music\n' hasil += 'Judul : ' + song[0] hasil += '\nDurasi : ' + song[1] hasil += '\nLink Download : ' + song[4] cl.sendText(msg.to, hasil) cl.sendText(msg.to, "Please Wait for audio...") cl.sendAudioWithURL(msg.to, song[3]) except Exception as njer: cl.sendText(msg.to, str(njer)) elif 'clean invites' in msg.text.lower(): if msg.from_ in admin: if msg.toType == 2: X = cl.getGroup(msg.to) if X.invitee is not None: gInviMids = [contact.mid for contact in X.invitee] random.choice(KAC).cancelGroupInvitation(msg.to, gInviMids) else: if wait["lang"] == "JP": cl.sendText(msg.to,"No one is inviting。") else: cl.sendText(msg.to,"Sorry, nobody absent") else: if wait["lang"] == "JP": cl.sendText(msg.to,"Can not be used outside the group") else: cl.sendText(msg.to,"Not for use less than group") #================================================================================ elif 'clear invites' in msg.text.lower(): if msg.from_ in admin: if msg.toType == 2: group = cl.getGroup(msg.to) gMembMids = [contact.mid for contact in group.invitee] for _mid in gMembMids: random.choice(KAC).cancelGroupInvitation(msg.to,[_mid]) cl.sendText(msg.to,"I pretended to cancel and canceled.") elif 'link open' in msg.text.lower(): if msg.from_ in admin: if msg.toType == 2: uye = random.choice(KAC) X = cl.getGroup(msg.to) X.preventJoinByTicket = False uye.updateGroup(X) if wait["lang"] == "JP": uye.sendText(msg.to,"done") else: uye.sendText(msg.to,"already open") else: if wait["lang"] == "JP": uye.sendText(msg.to,"Can not be used outside the group") else: uye.sendText(msg.to,"Not for use less than group") #=========================================================================== elif 'link close' in msg.text.lower(): if msg.from_ in admin: if msg.toType == 2: uye = random.choice(KAC) X = cl.getGroup(msg.to) X.preventJoinByTicket = True uye.updateGroup(X) if wait["lang"] == "JP": uye.sendText(msg.to,"done") else: uye.sendText(msg.to,"already close") else: if wait["lang"] == "JP": uye.sendText(msg.to,"Can not be used outside the group") else: uye.sendText(msg.to,"Not for use less than group") #============================================================ elif msg.text.lower() == 'ginfo': if msg.from_ in admin: ginfo = cl.getGroup(msg.to) try: gCreator = ginfo.creator.displayName except: gCreator = "Error" if wait["lang"] == "JP": if ginfo.invitee is None: sinvitee = "0" else: sinvitee = str(len(ginfo.invitee)) msg.contentType = 13 msg.contentMetadata = {'mid': ginfo.creator.mid} cl.sendText(msg.to,"[display name]\n" + str(ginfo.name) + "\n[Group Id]\n" + msg.to + "\n\n[Group Creator]\n" + gCreator + "\n\nmembers:" + str(len(ginfo.members)) + "\nInvitation:" + sinvitee + "") cl.sendMessage(msg) #------------------------_-------------------------------------- #=============================================================== elif 'group list' in msg.text.lower(): if msg.from_ in admin: gs = cl.getGroupIdsJoined() L = "『 Groups List 』\n" for i in gs: L += "[≫] %s \n" % (cl.getGroup(i).name + " | [ " + str(len (cl.getGroup(i).members)) + " ]") cl.sendText(msg.to, L + "\nTotal Group : [ " + str(len(gs)) +" ]") elif "Invite me" in msg.text: if msg.from_ in owner: gid = cl.getGroupIdsJoined() for i in gid: cl.findAndAddContactsByMid(msg.from_) cl.inviteIntoGroup(i,[msg.from_]) cl.sendText(msg.to, "successfully invited you to all groups") elif "Steal group pict" in msg.text: if msg.from_ in admin: group = cl.getGroup(msg.to) path = "http://dl.profile.line-cdn.net/" + group.pictureStatus cl.sendImageWithURL(msg.to,path) elif "Turn off bots" in msg.text: if msg.from_ in owner: try: import sys sys.exit() except: pass #================================================================== elif "Steal bio" in msg.text: if msg.from_ in admin: key = eval(msg.contentMetadata["MENTION"]) key1 = key["MENTIONEES"][0]["M"] contact = cl.getContact(key1) cu = cl.channel.getCover(key1) try: cl.sendText(msg.to,contact.statusMessage) except: cl.sendText(msg.to,contact.statusMessage) elif msg.text in ["Creator"]: if msg.from_ in admin: msg.contentType = 13 msg.contentMetadata = {'mid': 'u36196ea7137f95585062f8303dbac814'} cl.sendMessage(msg) cl.sendText(msg.to,"Itu Creator Saya Yang paling Ganteng ") elif "Admin on @" in msg.text: if msg.from_ in owner: print "[Command]Staff add executing" _name = msg.text.replace("Admin on @","") _nametarget = _name.rstrip(' ') gs = cl.getGroup(msg.to) targets = [] for g in gs.members: if _nametarget == g.displayName: targets.append(g.mid) if targets == []: cl.sendText(msg.to,"Contact not found") else: for target in targets: try: admin.append(target) cl.sendText(msg.to,"succes add to adminlist") except: pass print "[Command]Staff add executed" else: cl.sendText(msg.to,"Command denied.") cl.sendText(msg.to,"owner permission required.") elif msg.text.lower() == 'admin list': if msg.from_ in admin: if admin == []: cl.sendText(msg.to,"The adminlist is empty") else: cl.sendText(msg.to,"loading...") mc = "" gh = "" for mi_d in owner: mc += "->" +cl.getContact(mi_d).displayName + "\n" for mi_d in admin: gh += "->" +cl.getContact(mi_d).displayName + "\n" cl.sendText(msg.to,"=======OWNER=======\n\n" + mc + "\n=======ADMIN=======\n\n" + gh +"\n=====================\n") print "[Command]Stafflist executed" elif "Expel on @" in msg.text: if msg.from_ in owner: print "[Command]Staff remove executing" _name = msg.text.replace("Expel on @","") _nametarget = _name.rstrip(' ') gs = cl.getGroup(msg.to) targets = [] for g in gs.members: if _nametarget == g.displayName: targets.append(g.mid) if targets == []: ki.sendText(msg.to,"Contact not found") else: for target in targets: try: admin.remove(target) cl.sendText(msg.to,"Succes remove admin from adminlist") except: pass print "[Command]Staff remove executed" else: cl.sendText(msg.to,"Command denied.") cl.sendText(msg.to,"owner permission required.") #========================================================== elif 'my mid' in msg.text.lower(): if msg.from_ in admin: ki.sendText(msg.to,Amid) kk.sendText(msg.to,Bmid) kc.sendText(msg.to,Cmid) ks.sendText(msg.to,Dmid) kt.sendText(msg.to,Emid) #======================================================= elif "Translate-eng " in msg.text: if msg.from_ in admin: txt = msg.text.replace("Translate-eng ","") try: gs = goslate.Goslate() trs = gs.translate(txt,'en') cl.sendText(msg.to,trs) print '[Command] Translate EN' except Exception as error: cl.sendText(msg.to,(error)) elif "Translate-jp" in msg.text: if msg.from_ in admin: txt = msg.text.replace("Translate-jp ","") try: gs = goslate.Goslate() trs = gs.translate(txt,'jp') cl.sendText(msg.to,trs) print '[Command] Translate jp' except Exception as error: cl.sendText(msg.to,(error)) elif "Translate-th " in msg.text: if msg.from_ in admin: txt = msg.text.replace("Translate-th ","") try: gs = goslate.Goslate() trs = gs.translate(txt,'th') cl.sendText(msg.to,trs) print '[Command] Translate th' except Exception as error: cl.sendText(msg.to,(error)) elif "Translate-idn " in msg.text: if msg.from_ in admin: txt = msg.text.replace("Translate-id ","") try: gs = goslate.Goslate() trs = gs.translate(txt,'id') cl.sendText(msg.to,trs) print '[Command] Translate ID' except Exception as error: cl.sendText(msg.to,(error)) elif "Say " in msg.text: if msg.from_ in admin: bctxt = msg.text.replace("Say ","") kk.sendText(msg.to,(bctxt)) kc.sendText(msg.to,(bctxt)) ki.sendText(msg.to,(bctxt)) ks.sendText(msg.to,(bctxt)) kt.sendText(msg.to,(bctxt)) #====================================== elif "TL:" in msg.text: if msg.from_ in admin: tl_text = msg.text.replace("TL:","") cl.sendText(msg.to,"line://home/post?userMid="+mid+"&postId="+cl.new_post(tl_text)["result"]["post"]["postInfo"]["postId"]) #================================================================= elif msg.text in ["Protect:hight","protect:hight"]: if msg.from_ in admin: if wait["protectionOn"] == True: if wait["lang"] == "JP": cl.sendText(msg.to,"turned into high protection\n\n"+ datetime.today().strftime('%H:%M:%S')) else: cl.sendText(msg.to,"turned into high protection\n\n"+ datetime.today().strftime('%H:%M:%S')) else: wait["protectionOn"] = True if wait["lang"] == "JP": cl.sendText(msg.to,"turned into high protection\n\n"+ datetime.today().strftime('%H:%M:%S')) else: cl.sendText(msg.to,"turned into high protection\n\n"+ datetime.today().strftime('%H:%M:%S')) elif msg.text in ["Auto blockqr:off","auto blockqr:off"]: if msg.from_ in admin: if wait["qr"] == False: if wait["lang"] == "JP": cl.sendText(msg.to,"Already off\n\n"+ datetime.today().strftime('%H:%M:%S')) else: cl.sendText(msg.to,"Protection QR PRO Off\n\n"+ datetime.today().strftime('%H:%M:%S')) else: wait["qr"] = False if wait["lang"] == "JP": cl.sendText(msg.to,"Protection QR PRO Off\n\n"+ datetime.today().strftime('%H:%M:%S')) else: cl.sendText(msg.to,"Already off\n\n"+ datetime.today().strftime('%H:%M:%S')) elif msg.text in ["Welcome message:on"]: if msg.from_ in admin: if wait["welcomemsg"] == True: if wait["lang"] == "JP": cl.sendText(msg.to,"welcome message on\n\n"+ datetime.today().strftime('%H:%M:%S')) else: cl.sendText(msg.to,"welcome message on\n\n"+ datetime.today().strftime('%H:%M:%S')) else: wait["welcomemsg"] = True if wait["lang"] == "JP": cl.sendText(msg.to,"welcome message on\n\n"+ datetime.today().strftime('%H:%M:%S')) else: cl.sendText(msg.to,"welcome message on") elif msg.text in ["Auto blockqr:on","auto blockqr:on"]: if msg.from_ in admin: if wait["qr"] == True: if wait["lang"] == "JP": cl.sendText(msg.to,"Already on\n\n"+ datetime.today().strftime('%H:%M:%S')) else: cl.sendText(msg.to,"Protection QR PRO On\n\n"+ datetime.today().strftime('%H:%M:%S')) else: wait["qr"] = True if wait["lang"] == "JP": cl.sendText(msg.to,"Protection QR PRO On\n\n"+ datetime.today().strftime('%H:%M:%S')) else: cl.sendText(msg.to,"Already on") elif msg.text in ["Welcome message:off"]: if msg.from_ in admin: if wait["welcomemsg"] == False: if wait["lang"] == "JP": cl.sendText(msg.to,"welcome message off\n\n"+ datetime.today().strftime('%H:%M:%S')) else: cl.sendText(msg.to,"welcome message off\n\n"+ datetime.today().strftime('%H:%M:%S')) else: wait["welcomemsg"] = False if wait["lang"] == "JP": cl.sendText(msg.to,"welcome message off\n\n"+ datetime.today().strftime('%H:%M:%S')) else: cl.sendText(msg.to,"welcome message off\n\n"+ datetime.today().strftime('%H:%M:%S')) elif msg.text in ["Protect:low","Protect:low"]: if msg.from_ in admin: if wait["protectionOn"] == False: if wait["lang"] == "JP": cl.sendText(msg.to,"turned into low protection\n\n"+ datetime.today().strftime('%H:%M:%S')) else: cl.sendText(msg.to,"turned into low protection\n\n"+ datetime.today().strftime('%H:%M:%S')) else: wait["protectionOn"] = False if wait["lang"] == "JP": cl.sendText(msg.to,"turned into low protection\n\n"+ datetime.today().strftime('%H:%M:%S')) else: cl.sendText(msg.to,"turned into low protection\n\n"+ datetime.today().strftime('%H:%M:%S')) elif "Namelock:on" in msg.text: if msg.from_ in admin: if msg.to in wait['pname']: cl.sendText(msg.to,"ƬƲƦƝЄƊ ƠƝ.") else: cl.sendText(msg.to,"ƛԼƦЄƛƊƳ ƠƝ") wait['pname'][msg.to] = True wait['pro_name'][msg.to] = cl.getGroup(msg.to).name elif "Namelock:off" in msg.text: if msg.from_ in admin: if msg.to in wait['pname']: cl.sendText(msg.to,"ƬƲƦƝ ƠƑƑ.") del wait['pname'][msg.to] else: cl.sendText(msg.to,"ƛԼƦЄƛƊƳ ƠƑƑ") elif "Blockinvite:on" == msg.text: if msg.from_ in admin: gid = msg.to autocancel[gid] = "poni" cl.sendText(msg.to,"ƤƦƠƬЄƇƬ ƖƝƔƖƬƛƬƖƠƝ ƠƝ") elif "Blockinvite:off" == msg.text: if msg.from_ in admin: try: del autocancel[msg.to] cl.sendText(msg.to,"ƤƦƠƬЄƇƬ ƖƝƔƖƬƛƬƖƠƝ ƠƑƑ") except: pass #================================================================ elif msg.text in ["Invite user"]: if msg.from_ in admin: wait["winvite"] = True cl.sendText(msg.to,"send contact") #============================================================ elif "Steal mid" in msg.text: if msg.from_ in admin: key = eval(msg.contentMetadata["MENTION"]) key1 = key["MENTIONEES"][0]["M"] cl.sendText(msg.to,"Mc: " + key1) elif "Steal contact" in msg.text: if msg.from_ in admin: key = eval(msg.contentMetadata["MENTION"]) key1 = key["MENTIONEES"][0]["M"] mmid = cl.getContact(key1) msg.contentType = 13 msg.contentMetadata = {"mid": key1} cl.sendMessage(msg) elif "Mc:" in msg.text: if msg.from_ in admin: mmid = msg.text.replace("Mc:","") msg.contentType = 13 msg.contentMetadata = {"mid":mmid} cl.sendMessage(msg) #======================================================= elif msg.text in ["Auto notice:on"]: if msg.from_ in admin: if wait["contact"] == True: if wait["lang"] == "JP": cl.sendText(msg.to,"already activated") else: cl.sendText(msg.to,"enable notifications") else: wait["contact"] = True if wait["lang"] == "JP": cl.sendText(msg.to,"already activated") else: cl.sendText(msg.to,"enable notifications") #========================================================================= elif msg.text in ["Auto notice:off"]: if msg.from_ in admin: if wait["contact"] == False: if wait["lang"] == "JP": cl.sendText(msg.to,"already unactivated") else: cl.sendText(msg.to,"disable notifications") else: wait["contact"] = False if wait["lang"] == "JP": cl.sendText(msg.to,"already unactivated") else: cl.sendText(msg.to,"disable notifications") elif msg.text in ["Auto join:on"]: if msg.from_ in admin: if wait["autoJoin"] == True: if wait["lang"] == "JP": cl.sendText(msg.to,"") else: cl.sendText(msg.to,"already activated") else: wait["autoJoin"] = True if wait["lang"] == "JP": cl.sendText(msg.to,"enable auto koin") else: cl.sendText(msg.to,"") elif msg.text in ["Auto join:off"]: if msg.from_ in admin: if wait["autoJoin"] == False: if wait["lang"] == "JP": cl.sendText(msg.to,"already unactivated") else: cl.sendText(msg.to,"desable auto join") else: wait["autoJoin"] = False if wait["lang"] == "JP": cl.sendText(msg.to,"already unactivated") else: cl.sendText(msg.to,"desable auto join") elif "Gcancel:" in msg.text: if msg.from_ in admin: try: strnum = msg.text.replace("Gcancel:","") if strnum == "off": wait["autoCancel"]["on"] = False if wait["lang"] == "JP": cl.sendText(msg.to,"Invitation refused turned off\nTo turn on please specify the number of people and send") else: cl.sendText(msg.to,"关了邀请拒绝。要时开请指定人数发送") else: num = int(strnum) wait["autoCancel"]["on"] = True if wait["lang"] == "JP": cl.sendText(msg.to,strnum + " The group of people and below decided to automatically refuse invitation") else: cl.sendText(msg.to,strnum + "使人以下的小组用自动邀请拒绝") except: if wait["lang"] == "JP": cl.sendText(msg.to,"Value is wrong") else: cl.sendText(msg.to,"Bizarre ratings") elif msg.text in ["Auto leave:on"]: if msg.from_ in admin: if wait["leaveRoom"] == True: if wait["lang"] == "JP": cl.sendText(msg.to,"already on") else: cl.sendText(msg.to,"done") else: wait["leaveRoom"] = True if wait["lang"] == "JP": cl.sendText(msg.to,"done") else: cl.sendText(msg.to,"要了开。") elif msg.text in ["Auto leave:off"]: if msg.from_ in admin: if wait["leaveRoom"] == False: if wait["lang"] == "JP": cl.sendText(msg.to,"already off") else: cl.sendText(msg.to,"done") else: wait["leaveRoom"] = False if wait["lang"] == "JP": cl.sendText(msg.to,"done") else: cl.sendText(msg.to,"already") #=============================================================== elif msg.text in ["Auto like:on"]: if msg.from_ in admin: if wait["likeOn"] == True: if wait["lang"] == "JP": cl.sendText(msg.to,"Done。") else: wait["likeOn"] = True if wait["lang"] == "JP": cl.sendText(msg.to,"Already。") elif msg.text in ["Auto like:off"]: if msg.from_ in admin: if wait["likeOn"] == False: if wait["lang"] == "JP": cl.sendText(msg.to,"Done。") else: wait["likeOn"] = False if wait["lang"] == "JP": cl.sendText(msg.to,"Already。") #========================================================== elif msg.text in ["Settings","Set"]: if msg.from_ in admin: print "Setting pick up..." md="list of bot settings\n\n" if wait["likeOn"] == True: md+="Auto like : on\n" else:md+="Auto like : off\n" if wait["winvite"] == True: md+="Invite : on\n" else:md+="Invite : off\n" if wait["pname"] == True: md+="Namelock : on\n" else:md+="Namelock : off\n" if wait["contact"] == True: md+="Notice : on\n" else: md+="Notice : off\n" if wait["autoJoin"] == True: md+="Auto join : on\n" else: md +="Auto join : off\n" if wait["autoCancel"]["on"] == True:md+="Group cancel :" + str(wait["autoCancel"]["members"]) + "\n" else: md+= "Group cancel : off\n" if wait["leaveRoom"] == True: md+="Auto leave : on\n" else: md+="Auto leave : off\n" if wait["clock"] == True: md+="Clock Name : on\n" else:md+="Clock Name : off\n" if wait["autoAdd"] == True: md+="Auto add : on\n" else:md+="Auto add : off\n" if wait["commentOn"] == True: md+="Comment : on\n" else:md+="Comment : off\n" if wait["Backup"] == True: md+="Backup : on\n" else:md+="Backup : off\n" if wait["qr"] == True: md+="Protect QR : on\n" else:md+="Protect QR : off\n" if wait["welcomemsg"] == True: md+="welcome message : on\n" else:md+="welcome message : off\n" if wait["protectionOn"] == True: md+="Protection : hight\n\n"+ datetime.today().strftime('%H:%M:%S') else:md+="Protection : low\n\n"+ datetime.today().strftime('%H:%M:%S') cl.sendText(msg.to,md) #======================================== #------------------------------------------------ elif "Time" in msg.text: if msg.from_ in admin: cl.sendText(msg.to,datetime.today().strftime('%H:%M:%S')) elif msg.text in ["PING","Ping","ping"]: if msg.from_ in admin: cl.sendText(msg.to,"PONG 􀨁􀄻😎😎") kk.sendText(msg.to,"PONG 􀨁􀄻😎😎") kc.sendText(msg.to,"PONG 😎😎") ks.sendText(msg.to,"PONG 􀨁􀄻😎😎") kt.sendText(msg.to,"PONG 😎😎􀨁􀄻") elif "Info @" in msg.text: if msg.from_ in admin: nama = msg.text.replace("Info @","") target = nama.rstrip(' ') tob = cl.getGroup(msg.to) for g in tob.members: if target == g.displayName: gjh= cl.getContact(g.mid) try: cover = cl.channel.getCover(g.mid) except: cover = "" cl.sendText(msg.to,"[Display Name]:\n" + gjh.displayName + "\n[Mid]:\n" + gjh.mid + "\n[BIO]:\n" + gjh.statusMessage + "\n[pict profile]:\nhttp://dl.profile.line-cdn.net/" + gjh.pictureStatus + "\n[Cover]:\n" + str(cover)) else: pass #----------------------------------------------- elif msg.text in ["Backup:on"]: if msg.from_ in admin: if wait["Backup"] == True: if wait["lang"] == "JP": cl.sendText(msg.to,"backup has been active\n\n"+ datetime.today().strftime('%H:%M:%S')) else: cl.sendText(msg.to,"backup has been enable\n\n"+ datetime.today().strftime('%H:%M:%S')) else: wait["Backup"] = True if wait["lang"] == "JP": cl.sendText(msg.to,"backup has been active\n\n"+ datetime.today().strftime('%H:%M:%S')) else: cl.sendText(msg.to,"backup has been enable\n\n"+ datetime.today().strftime('%H:%M:%S')) elif msg.text in ["Backup:off"]: if msg.from_ in admin: if wait["Backup"] == False: if wait["lang"] == "JP": cl.sendText(msg.to,"backup has been unactive\n\n"+ datetime.today().strftime('%H:%M:%S')) else: cl.sendText(msg.to,"backup has been desable\n\n"+ datetime.today().strftime('%H:%M:%S')) else: wait["Backup"] = False if wait["lang"] == "JP": cl.sendText(msg.to,"backup has been unactive\n\n"+ datetime.today().strftime('%H:%M:%S')) else: cl.sendText(msg.to,"backup has been desable\n\n"+ datetime.today().strftime('%H:%M:%S')) elif msg.text in ["Rejectall"]: if msg.from_ in admin: gid = cl.getGroupIdsInvited() for i in gid: cl.rejectGroupInvitation(i) if wait["lang"] == "JP": cl.sendText(msg.to,"All Invites has been Rejected") else: cl.sendText(msg.to,"拒绝了全部的邀请。") elif msg.text in ["Auto add:on"]: if msg.from_ in admin: if wait["autoAdd"] == True: if wait["lang"] == "JP": cl.sendText(msg.to,"success activated") else: cl.sendText(msg.to,"success activated") else: wait["autoAdd"] = True if wait["lang"] == "JP": cl.sendText(msg.to,"success activated") else: cl.sendText(msg.to,"success activated") elif msg.text in ["Auto add:off"]: if msg.from_ in admin: if wait["autoAdd"] == False: if wait["lang"] == "JP": cl.sendText(msg.to,"success unactivated") else: cl.sendText(msg.to,"success unactivated") else: wait["autoAdd"] = False if wait["lang"] == "JP": cl.sendText(msg.to,"success unactivated") else: cl.sendText(msg.to,"success unactivated") #======================================== #======================================== elif "Update welcome:" in msg.text: if msg.from_ in admin: wait["welmsg"] = msg.text.replace("Update welcome:","") cl.sendText(msg.to,"update welcome message succes"+ datetime.today().strftime('%H:%M:%S')) elif msg.text in ["Check welcome message"]: if msg.from_ in admin: if wait["lang"] == "JP": cl.sendText(msg.to,"yor bot message\n\n" + wait["welmsg"]) else: cl.sendText(msg.to,"The automatic appending information is set as follows。\n\n" + wait["welmsg"]) elif "Message:" in msg.text: if msg.from_ in admin: wait["message"] = msg.text.replace("Message:","") cl.sendText(msg.to,"bot message\n\n"+ datetime.today().strftime('%H:%M:%S')) elif "Add message:" in msg.text: if msg.from_ in admin: wait["message"] = msg.text.replace("Add message:","") if wait["lang"] == "JP": cl.sendText(msg.to,"message changed\n\n"+ datetime.today().strftime('%H:%M:%S')) else: cl.sendText(msg.to,"done。\n\n"+ datetime.today().strftime('%H:%M:%S')) elif msg.text in ["Check message"]: if msg.from_ in admin: if wait["lang"] == "JP": cl.sendText(msg.to,"yor bot message\n\n" + wait["message"]) else: cl.sendText(msg.to,"The automatic appending information is set as follows。\n\n" + wait["message"]) elif "Comment:" in msg.text: if msg.from_ in admin: c = msg.text.replace("Comment:","") if c in [""," ","\n",None]: cl.sendText(msg.to,"String that can not be changed") else: wait["comment"] = c cl.sendText(msg.to,"changed\n\n" + c) elif "Add comment:" in msg.text: if msg.from_ in admin: c = msg.text.replace("Add comment:","") if c in [""," ","\n",None]: cl.sendText(msg.to,"String that can not be changed") else: wait["comment"] = c cl.sendText(msg.to,"changed\n\n" + c) elif msg.text in ["Comment:on"]: if msg.from_ in admin: if wait["commentOn"] == True: if wait["lang"] == "JP": cl.sendText(msg.to,"Done") else: cl.sendText(msg.to,"Already on") else: wait["commentOn"] = True if wait["lang"] == "JP": cl.sendText(msg.to,"Done") else: cl.sendText(msg.to,"Already on") elif msg.text in ["Comment:off"]: if msg.from_ in admin: if wait["commentOn"] == False: if wait["lang"] == "JP": cl.sendText(msg.to,"Done") else: cl.sendText(msg.to,"Already off") else: wait["commentOn"] = False if wait["lang"] == "JP": cl.sendText(msg.to,"Done") else: cl.sendText(msg.to,"Already off") elif msg.text in ["Check comment"]: if msg.from_ in admin: cl.sendText(msg.to,"message comment\n\n" + str(wait["comment"])) elif msg.text in ["Gurl"]: if msg.from_ in admin: if msg.toType == 2: uye = random.choice(KAC) x = cl.getGroup(msg.to) if x.preventJoinByTicket == True: x.preventJoinByTicket = False uye.updateGroup(x) gurl = uye.reissueGroupTicket(msg.to) uye.sendText(msg.to,"line://ti/g/" + gurl) else: if wait["lang"] == "JP": uye.sendText(msg.to,"Can not be used outside the group") else: uye.sendText(msg.to,"Not for use less than group") #------------------------------------------------------- elif "Gift @" in msg.text: _name = msg.text.replace("Gift @","") _nametarget = _name.rstrip(' ') gs = cl.getGroup(msg.to) for g in gs.members: if _nametarget == g.displayName: msg.contentType = 9 msg.contentMetadata={'PRDID': 'u36196ea7137f95585062f8303dbac814', 'PRDTYPE': 'THEME', 'MSGTPL': '10'} msg.text = None cl.sendMessage(msg,g) #=========================================== elif msg.text.lower() == 'responsename': if msg.from_ in admin: profile = cl.getProfile() text = profile.displayName + " " cl.sendText(msg.to, text) profile = kk.getProfile() text = profile.displayName + " " kk.sendText(msg.to, text) profile = kc.getProfile() text = profile.displayName + " " kc.sendText(msg.to, text) profile = ks.getProfile() text = profile.displayName + " " ks.sendText(msg.to, text) profile = kt.getProfile() text = profile.displayName + "" kt.sendText(msg.to, text) #======================================== elif msg.text in ["Comment bl "]: wait["wblack"] = True cl.sendText(msg.to,"add to comment bl") elif msg.text in ["Comment wl "]: wait["dblack"] = True cl.sendText(msg.to,"wl to comment bl") elif msg.text in ["Comment bl confirm"]: if wait["commentBlack"] == {}: cl.sendText(msg.to,"confirmed") else: cl.sendText(msg.to,"Blacklist s") mc = "" for mi_d in wait["commentBlack"]: mc += "・" +cl.getContact(mi_d).displayName + "\n" cl.sendText(msg.to,mc) elif msg.text in ["Clock:on","Clock on","Jam on","Jam:on"]: if wait["clock"] == True: cl.sendText(msg.to,"already on") else: wait["clock"] = True now2 = datetime.now() nowT = datetime.strftime(now2,"[%H:%M]") profile = cl.getProfile() profile.displayName = wait["cName"] + nowT cl.updateProfile(profile) cl.sendText(msg.to,"done") elif msg.text in ["Clock:off","Clock off","Jam off","Jam:off"]: if wait["clock"] == False: cl.sendText(msg.to,"already off") else: wait["clock"] = False cl.sendText(msg.to,"done") elif "Cc: " in msg.text: n = msg.text.replace("Cc: ","") if len(n.decode("utf-8")) > 13: cl.sendText(msg.to,"changed") else: wait["cName"] = n cl.sendText(msg.to,"Changed to:\n\n" + n) elif msg.text in ["Up"]: if wait["clock"] == True: now2 = datetime.now() nowT = datetime.strftime(now2,"[%H:%M]") profile = cl.getProfile() profile.displayName = wait["cName"] + nowT cl.updateProfile(profile) cl.sendText(msg.to,"Refresh to update") else: cl.sendText(msg.to,"Please turn on the name clock") #======================================== elif "@"+cl.getProfile().displayName in msg.text: if wait["tag"] == True: tanya = msg.text.replace("@"+cl.getProfile().displayName,"") resp = ("《《AUTO RESPON》》\n") jawab = ("apa? kangen?") jawabam = random.choice(jawab) cl.sendText(msg.to,resp + jawabam) elif "Steal cover @" in msg.text: if msg.from_ in admin: print "[Command]dp executing" _name = msg.text.replace("Steal cover @","") _nametarget = _name.rstrip(' ') gs = cl.getGroup(msg.to) targets = [] for g in gs.members: if _nametarget == g.displayName: targets.append(g.mid) if targets == []: cl.sendText(msg.to,"Contact not found") else: for target in targets: try: contact = cl.getContact(target) cu = cl.channel.getCover(target) path = str(cu) cl.sendImageWithURL(msg.to, path) except: pass print "[Command]dp executed" elif "Midpict:" in msg.text: if msg.from_ in admin: umid = msg.text.replace("Midpict:","") contact = cl.getContact(umid) try: image = "http://dl.profile.line-cdn.net/" + contact.pictureStatus except: image = "https://www.1and1.co.uk/digitalguide/fileadmin/DigitalGuide/Teaser/not-found-t.jpg" try: cl.sendImageWithURL(msg.to,image) except Exception as error: cl.sendText(msg.to,(error)) pass elif "Steal pict " in msg.text: if msg.from_ in admin: if msg.toType == 2: msg.contentType = 0 steal0 = msg.text.replace("Steal pict ","") steal1 = steal0.lstrip() steal2 = steal1.replace("@","") steal3 = steal2.rstrip() _name = steal3 group = cl.getGroup(msg.to) targets = [] for g in group.members: if _name == g.displayName: targets.append(g.mid) if targets == []: cl.sendText(msg.to,"not found") else: for target in targets: try: contact = cl.getContact(target) try: image = "http://dl.profile.line-cdn.net/" + contact.pictureStatus except: image = "https://www.1and1.co.uk/digitalguide/fileadmin/DigitalGuide/Teaser/not-found-t.jpg" try: cl.sendImageWithURL(msg.to,image) except Exception as error: cl.sendText(msg.to,(error)) pass except: cl.sendText(msg.to,"Error!") break else: cl.sendText(msg.to,"Tidak bisa dilakukan di luar grup") elif "copy @" in msg.text: print "[COPY] Ok" _name = msg.text.replace("copy @","") _nametarget = _name.rstrip(' ') gs = cl.getGroup(msg.to) targets = [] for g in gs.members: if _nametarget == g.displayName: targets.append(g.mid) if targets == []: cl.sendText(msg.to, "Not Found...") else: for target in targets: try: cl.CloneContactProfile(target) cl.sendText(msg.to, "Copied.") except Exception as e: print e elif "copy1 @" in msg.text: print "[COPY] Ok" _name = msg.text.replace("copy1 @","") _nametarget = _name.rstrip(' ') gs = kk.getGroup(msg.to) targets = [] for g in gs.members: if _nametarget == g.displayName: targets.append(g.mid) if targets == []: kk.sendText(msg.to, "Not Found...") else: for target in targets: try: kk.CloneContactProfile(target) kk.sendText(msg.to, "Copied.") except Exception as e: print e elif "copy2 @" in msg.text: print "[COPY] Ok" _name = msg.text.replace("copy2 @","") _nametarget = _name.rstrip(' ') gs = ki.getGroup(msg.to) targets = [] for g in gs.members: if _nametarget == g.displayName: targets.append(g.mid) if targets == []: ki.sendText(msg.to, "Not Found...") else: for target in targets: try: ki.CloneContactProfile(target) ki.sendText(msg.to, "Copied.") except Exception as e: print e elif "copy3 @" in msg.text: print "[COPY] Ok" _name = msg.text.replace("copy3 @","") _nametarget = _name.rstrip(' ') gs = kc.getGroup(msg.to) targets = [] for g in gs.members: if _nametarget == g.displayName: targets.append(g.mid) if targets == []: kc.sendText(msg.to, "Not Found...") else: for target in targets: try: kc.CloneContactProfile(target) kc.sendText(msg.to, "Copied.") except Exception as e: print e elif "copy4 @" in msg.text: print "[COPY] Ok" _name = msg.text.replace("copy4 @","") _nametarget = _name.rstrip(' ') gs = ks.getGroup(msg.to) targets = [] for g in gs.members: if _nametarget == g.displayName: targets.append(g.mid) if targets == []: ks.sendText(msg.to, "Not Found...") else: for target in targets: try: ks.CloneContactProfile(target) ks.sendText(msg.to, "Copied.") except Exception as e: print e elif "copy5 @" in msg.text: print "[COPY] Ok" _name = msg.text.replace("copy5 @","") _nametarget = _name.rstrip(' ') gs = kt.getGroup(msg.to) targets = [] for g in gs.members: if _nametarget == g.displayName: targets.append(g.mid) if targets == []: kt.sendText(msg.to, "Not Found...") else: for target in targets: try: kt.CloneContactProfile(target) kt.sendText(msg.to, "Copied.") except Exception as e: print e elif msg.text in ["Backup","backup"]: try: cl.updateDisplayPicture(backup.pictureStatus) cl.updateProfile(backup) cl.sendText(msg.to, "Refreshed.") except Exception as e: cl.sendText(msg.to, str(e)) elif msg.text in ["Gcreator:inv"]: if msg.from_ in admin: ginfo = cl.getGroup(msg.to) gCreator = ginfo.creator.mid try: cl.findAndAddContactsByMid(gCreator) cl.inviteIntoGroup(msg.to,[gCreator]) print "success inv gCreator" except: pass elif "Copy @" in msg.text: if msg.toType == 2: if msg.from_ in admin: print "[COPY] Ok" _name = msg.text.replace("Copy @","") _nametarget = _name.rstrip(' ') gs = cl.getGroup(msg.to) targets = [] for g in gs.members: if _nametarget == g.displayName: targets.append(g.mid) if targets == []: cl.sendText(msg.to, "Tidak Ada Target Copy") else: for target in targets: try: cl.CloneContactProfile(target) ki.CloneContactProfile(target) kk.CloneContactProfile(target) kc.CloneContactProfile(target) ks.CloneContactProfile(target) kt.CloneContactProfile(target) cl.sendText(msg.to, "Sukses Copy Profile") except Exception as e: print e elif msg.text in ["Kembali ke asli"]: try: cl.updateDisplayPicture(backup.pictureStatus) cl.updateProfile(backup) ki.updateDisplayPicture(backup.pictureStatus) ki.updateProfile(backup) kk.updateDisplayPicture(backup.pictureStatus) kk.updateProfile(backup) kc.updateDisplayPicture(backup.pictureStatus) kc.updateProfile(backup) ks.updateDisplayPicture(backup.pictureStatus) ks.updateProfile(backup) kt.updateDisplayPicture(backup.pictureStatus) kt.updateProfile(backup) cl.sendText(msg.to, "Backup Astro Sukses") except Exception as e: cl.sendText(msg.to, str (e)) #=============================================== elif msg.text in ["debug speed","Debug speed"]: if msg.from_ in admin: cl.sendText(msg.to, "Speed Loading...") start = time.time() time.sleep(0.0001) elapsed_time = time.time() - start cl.sendText(msg.to, "%sseconds" % (elapsed_time)) print "[Command]Speed palsu executed" elif "Blacklist all" in msg.text: if msg.from_ in admin: if msg.toType == 2: print "ok" _name = msg.text.replace("Blacklist all","") gs = cl.getGroup(msg.to) cl.sendText(msg.to,"Semua Telah Di Hapus") targets = [] for g in gs.members: if _name in g.displayName: targets.append(g.mid) if targets == []: cl.sendText(msg.to,"Maaf") else: for target in targets: if not target in Bots: try: wait["blacklist"][target] = True f=codecs.open('st2__b.json','w','utf-8') json.dump(wait["blacklist"], f, sort_keys=True, indent=4,ensure_ascii=False) cl.sendText(msg.to,"Success Boss") except: cl.sentText(msg.to,"Berhasil Dihapus") elif msg.text in ["Ban cek","Cekban"]: if msg.from_ in admin: if msg.toType == 2: group = cl.getGroup(msg.to) gMembMids = [contact.mid for contact in group.members] matched_list = [] for tag in wait["blacklist"]: matched_list+=filter(lambda str: str == tag, gMembMids) cocoa = "[⎈]Mid Blacklist [⎈]" for mm in matched_list: cocoa += "\n" + mm + "\n" cl.sendText(msg.to,cocoa + "") elif "Details grup: " in msg.text: if msg.from_ in admin: gid = msg.text.replace("/DetailsGroup: ","") if gid in [""," "]: cl.sendText(msg.to,"Grup id tidak valid") else: try: groups = cl.getGroup(gid) if groups.members is not None: members = str(len(groups.members)) else: members = "0" if groups.invitee is not None: pendings = str(len(groups.invitee)) else: pendings = "0" h = "[" + groups.name + "]\n -+GroupID : " + gid + "\n -+Members : " + members + "\n -+MembersPending : " + pendings + "\n -+Creator : " + groups.creator.displayName + "\n -+GroupPicture : http://dl.profile.line.naver.jp/" + groups.pictureStatus cl.sendText(msg.to,h) except Exception as error: cl.sendText(msg.to,(error))#------------------------------------------------------- #-------------------------------------------------------- elif "Ban group: " in msg.text: grp = msg.text.replace("Ban group: ","") gid = cl.getGroupIdsJoined() if msg.from_ in Creator: for i in gid: h = cl.getGroup(i).name if h == grp: wait["BlGroup"][i]=True cl.sendText(msg.to, "Success Ban Group : "+grp) else: pass else: cl.sendText(msg.to, "Khusus Creator") #-------------------------------------------------------- elif msg.text in ["List ban","List ban group"]: if msg.from_ in admin: if wait["BlGroup"] == {}: ki.sendText(msg.to,"nothing") kk.sendText(msg.to,"nothing") kc.sendText(msg.to,"nothing") else: mc = "" for gid in wait["BlGroup"]: mc += "-> " +cl.getGroup(gid).name + "\n" ki.sendText(msg.to,"===[Ban Group]===\n"+mc) else: cl.sendText(msg.to, "Khusus Admin") #-------------------------------------------------------- elif msg.text in ["Del ban: "]: if msg.from_ in admin: ng = msg.text.replace("Del ban: ","") for gid in wait["BlGroup"]: if cl.getGroup(gid).name == ng: del wait["BlGroup"][gid] cl.sendText(msg.to, "Success del ban "+ng) else: pass else: cl.sendText(msg.to, "Khusus Admin") #-------------------------------------------------------- elif "Join group: " in msg.text: ng = msg.text.replace("Join group: ","") gid = cl.getGroupIdsJoined() try: if msg.from_ in Creator: for i in gid: h = cl.getGroup(i).name if h == ng: cl.inviteIntoGroup(i,[Creator]) cl.sendText(msg.to,"Success join to ["+ h +"] group") else: pass else: cl.sendText(msg.to,"Khusus Creator") except Exception as e: cl.sendMessage(msg.to, str(e)) #-------------------------------------------------------- elif "Leave group: " in msg.text: ng = msg.text.replace("Leave group: ","") gid = cl.getGroupIdsJoined() if msg.from_ in Creator: for i in gid: h = cl.getGroup(i).name if h == ng: cl.sendText(i,"Bot di paksa keluar oleh owner!") cl.leaveGroup(i) ki.leaveGroup(i) kk.leaveGroup(i) kc.leaveGroup(i) cl.sendText(msg.to,"Success left ["+ h +"] group") else: pass else: cl.sendText(msg.to,"Khusus Creator") elif "Set member: " in msg.text: if msg.from_ in admin: jml = msg.text.replace("Set member: ","") wait["Members"] = int(jml) cl.sendText(msg.to, "Jumlah minimal member telah di set : "+jml) else: cl.sendText(msg.to, "Khusus Admin") #-------------------------------------------------------- elif "Add all" in msg.text: if msg.from_ in admin: thisgroup = cl.getGroups([msg.to]) Mids = [contact.mid for contact in thisgroup[0].members] mi_d = Mids[:33] cl.findAndAddContactsByMids(mi_d) cl.sendText(msg.to,"Success Add all") else: cl.sendText(msg.to, "Khusus Admin") #-------------------------------------------------------- elif "Recover" in msg.text: thisgroup = cl.getGroups([msg.to]) Mids = [contact.mid for contact in thisgroup[0].members] mi_d = Mids[:33] cl.createGroup("Recover", mi_d) cl.sendText(msg.to,"Success recover") elif "Ulti " in msg.text: if msg.from_ in admin: ulti0 = msg.text.replace("Ulti ","") ulti1 = ulti0.rstrip() ulti2 = ulti1.replace("@","") ulti3 = ulti2.rstrip() _name = ulti3 gs = cl.getGroup(msg.to) ginfo = cl.getGroup(msg.to) gs.preventJoinByTicket = False cl.updateGroup(gs) invsend = 0 Ticket = cl.reissueGroupTicket(msg.to) nl.acceptGroupInvitationByTicket(msg.to,Ticket) time.sleep(0.2) targets = [] for s in gs.members: if _name in s.displayName: targets.append(s.mid) if targets ==[]: sendMessage(msg.to,"user does not exist") pass else: for target in targets: try: nl.kickoutFromGroup(msg.to,[target]) nl.leaveGroup(msg.to) print (msg.to,[g.mid]) except: nl.sendText(msg.t,"Ter ELIMINASI....") nl.sendText(msg.to,"WOLES brooo....!!!") nl.leaveGroup(msg.to) gs = cl.getGroup(msg.to) gs.preventJoinByTicket = True cl.uldateGroup(gs) gs.preventJoinByTicket(gs) cl.updateGroup(gs) elif msg.text in ["Sp","Speed","Desah"]: start = time.time() print("Speed") cl.sendText(msg.to, "「Progress...」") cl.sendText(msg.to, "「Debuging Speed」") start = time.time() time.sleep(0.02) elapsed_time = time.time() - start cl.sendText(msg.to, "%sseconds" % (elapsed_time)) #cl.sendText(msg.to, "Tᵘʰ ᵏᵃᵃⁿ Cʳᵒᵗ ˢʸᵍ.. 😃") elif msg.text in ["Sp Bot","Speed Bot","Desah1"]: start = time.time() print("Speed") elapsed_time = time.time() - start ki.sendText(msg.to, "Pᵉˡᵃⁿ-Pᵉˡᵃⁿ Sᵃʸᵃⁿᵍ...😃") ki.sendText(msg.to, "%sseconds" % (elapsed_time)) kk.sendText(msg.to, "%sseconds" % (elapsed_time)) kt.sendText(msg.to, "%sseconds" % (elapsed_time)) kc.sendText(msg.to, "%sseconds" % (elapsed_time)) ks.sendText(msg.to, "%sseconds" % (elapsed_time)) #======================================== elif msg.text in ["Bot1 backup run"]: if msg.from_ in admin: wek = cl.getContact(mid) a = wek.pictureStatus r = wek.displayName i = wek.statusMessage s = open('mydn.txt',"w") s.write(r) s.close() t = open('mysm.txt',"w") t.write(i) t.close() u = open('myps.txt',"w") u.write(a) u.close() cl.sendText(msg.to, "backup has been active") print wek print a print r print i elif msg.text in ["Bot2 backup run"]: if msg.from_ in admin: wek = ki.getContact(Amid) a = wek.pictureStatus r = wek.displayName i = wek.statusMessage s = open('mgydn.txt',"w") s.write(r) s.close() t = open('myesm.txt',"w") t.write(i) t.close() u = open('mypfs.txt',"w") u.write(a) u.close() ki.sendText(msg.to, "backup has been active") print wek print a print r print i elif msg.text in ["Bot3 backup run"]: if msg.from_ in admin: wek = kk.getContact(Bmid) a = wek.pictureStatus r = wek.displayName i = wek.statusMessage s = open('msgydn.txt',"w") s.write(r) s.close() t = open('mysfdgm.txt',"w") t.write(i) t.close() u = open('gymyps.txt',"w") u.write(a) u.close() kk.sendText(msg.to, "backup has been active") print wek print a print r print i elif msg.text in ["Bot4 backup run"]: if msg.from_ in admin: wek = kc.getContact(Cmid) a = wek.pictureStatus r = wek.displayName i = wek.statusMessage s = open('jhmydn.txt',"w") s.write(r) s.close() t = open('myhfsm.txt',"w") t.write(i) t.close() u = open('mypfhs.txt',"w") u.write(a) u.close() kc.sendText(msg.to, "backup has been active") print wek print a print r print i elif msg.text in ["Bot5 backup run"]: if msg.from_ in admin: wek = ks.getContact(Dmid) a = wek.pictureStatus r = wek.displayName i = wek.statusMessage s = open('madydn.txt',"w") s.write(r) s.close() t = open('mysgjm.txt',"w") t.write(i) t.close() u = open('myrdps.txt',"w") u.write(a) u.close() ks.sendText(msg.to, "backup has been active") print wek print a print r print i elif msg.text in ["Bot6 backup run"]: if msg.from_ in admin: wek = kt.getContact(Emid) a = wek.pictureStatus r = wek.displayName i = wek.statusMessage s = open('mydnsgv.txt',"w") s.write(r) s.close() t = open('jhmysm.txt',"w") t.write(i) t.close() u = open('myiyps.txt',"w") u.write(a) u.close() kt.sendText(msg.to, "backup has been active") print wek print a print r print i #---------------------------------------------- elif "Clone " in msg.text: if msg.from_ in admin: targets = [] key = eval(msg.contentMetadata["MENTION"]) key["MENTIONEES"][0]["M"] for x in key["MENTIONEES"]: targets.append(x["M"]) for target in targets: try: contact = cl.getContact(target) X = contact.displayName profile = cl.getProfile() profile.displayName = X cl.updateProfile(profile) cl.sendText(msg.to, "Success...") #--------------------------------------- Y = contact.statusMessage lol = cl.getProfile() lol.statusMessage = Y cl.updateProfile(lol) #--------------------------------------- P = contact.pictureStatus cl.updateProfilePicture(P) except Exception as e: cl.sendText(msg.to, "Failed!") print e elif "Bot2 clone " in msg.text: if msg.from_ in admin: targets = [] key = eval(msg.contentMetadata["MENTION"]) key["MENTIONEES"][0]["M"] for x in key["MENTIONEES"]: targets.append(x["M"]) for target in targets: try: contact = ki.getContact(target) X = contact.displayName profile = ki.getProfile() profile.displayName = X ki.updateProfile(profile) ki.sendText(msg.to, "Success...") #--------------------------------------- Y = contact.statusMessage lol = ki.getProfile() lol.statusMessage = Y ki.updateProfile(lol) #--------------------------------------- P = contact.pictureStatus ki.updateProfilePicture(P) except Exception as e: ki.sendText(msg.to, "Failed!") print e elif "Bot3 clone " in msg.text: if msg.from_ in admin: targets = [] key = eval(msg.contentMetadata["MENTION"]) key["MENTIONEES"][0]["M"] for x in key["MENTIONEES"]: targets.append(x["M"]) for target in targets: try: contact = kk.getContact(target) X = contact.displayName profile = kk.getProfile() profile.displayName = X kk.updateProfile(profile) kk.sendText(msg.to, "Success...") #--------------------------------------- Y = contact.statusMessage lol = kk.getProfile() lol.statusMessage = Y kk.updateProfile(lol) #--------------------------------------- P = contact.pictureStatus kk.updateProfilePicture(P) except Exception as e: kk.sendText(msg.to, "Failed!") print e elif "Bot4 clone " in msg.text: if msg.from_ in admin: targets = [] key = eval(msg.contentMetadata["MENTION"]) key["MENTIONEES"][0]["M"] for x in key["MENTIONEES"]: targets.append(x["M"]) for target in targets: try: contact = kc.getContact(target) X = contact.displayName profile = kc.getProfile() profile.displayName = X kc.updateProfile(profile) kc.sendText(msg.to, "Success...") #--------------------------------------- Y = contact.statusMessage lol = kc.getProfile() lol.statusMessage = Y kc.updateProfile(lol) #--------------------------------------- P = contact.pictureStatus kc.updateProfilePicture(P) except Exception as e: kc.sendText(msg.to, "Failed!") print e elif "Bot5 clone " in msg.text: if msg.from_ in admin: targets = [] key = eval(msg.contentMetadata["MENTION"]) key["MENTIONEES"][0]["M"] for x in key["MENTIONEES"]: targets.append(x["M"]) for target in targets: try: contact = ks.getContact(target) X = contact.displayName profile = ks.getProfile() profile.displayName = X ks.updateProfile(profile) ks.sendText(msg.to, "Success...") #--------------------------------------- Y = contact.statusMessage lol = ks.getProfile() lol.statusMessage = Y ks.updateProfile(lol) #--------------------------------------- P = contact.pictureStatus ks.updateProfilePicture(P) except Exception as e: ks.sendText(msg.to, "Failed!") print e elif "Bot6 clone " in msg.text: if msg.from_ in admin: targets = [] key = eval(msg.contentMetadata["MENTION"]) key["MENTIONEES"][0]["M"] for x in key["MENTIONEES"]: targets.append(x["M"]) for target in targets: try: contact = kt.getContact(target) X = contact.displayName profile = kt.getProfile() profile.displayName = X kt.updateProfile(profile) kt.sendText(msg.to, "Success...") #--------------------------------------- Y = contact.statusMessage lol = kt.getProfile() lol.statusMessage = Y kt.updateProfile(lol) #--------------------------------------- P = contact.pictureStatus kt.updateProfilePicture(P) except Exception as e: kt.sendText(msg.to, "Failed!") print e #================================================= elif "my backup" in msg.text: if msg.from_ in admin: try: h = open('mydn.txt',"r") name = h.read() h.close() x = name profile = cl.getProfile() profile.displayName = x cl.updateProfile(profile) i = open('mysm.txt',"r") sm = i.read() i.close() y = sm cak = cl.getProfile() cak.statusMessage = y cl.updateProfile(cak) j = open('myps.txt',"r") ps = j.read() j.close() p = ps cl.updateProfilePicture(p) cl.sendText(msg.to, "Succes") except Exception as e: cl.sendText(msg.to,"Gagagl!") print e elif "Bot2 backup" in msg.text: if msg.from_ in admin: try: h = open('mgydn.txt',"r") name = h.read() h.close() x = name profile = ki.getProfile() profile.displayName = x ki.updateProfile(profile) i = open('myesm.txt',"r") sm = i.read() i.close() y = sm cak = ki.getProfile() cak.statusMessage = y ki.updateProfile(cak) j = open('mypfs.txt',"r") ps = j.read() j.close() p = ps ki.updateProfilePicture(p) ki.sendText(msg.to, "Succes") except Exception as e: ki.sendText(msg.to,"Gagagl!") print e elif "Bot3 backup" in msg.text: if msg.from_ in admin: try: h = open('msgydn.txt',"r") name = h.read() h.close() x = name profile = kk.getProfile() profile.displayName = x kk.updateProfile(profile) i = open('mysfdgm.txt',"r") sm = i.read() i.close() y = sm cak = kk.getProfile() cak.statusMessage = y kk.updateProfile(cak) j = open('gymyps.txt',"r") ps = j.read() j.close() p = ps kk.updateProfilePicture(p) kk.sendText(msg.to, "Succes") except Exception as e: kk.sendText(msg.to,"Gagagl!") print e elif "Bot4 backup" in msg.text: if msg.from_ in admin: try: h = open('jhmydn.txt',"r") name = h.read() h.close() x = name profile = kc.getProfile() profile.displayName = x kc.updateProfile(profile) i = open('myhfsm.txt',"r") sm = i.read() i.close() y = sm cak = kc.getProfile() cak.statusMessage = y kc.updateProfile(cak) j = open('mypfhs.txt',"r") ps = j.read() j.close() p = ps kc.updateProfilePicture(p) kc.sendText(msg.to, "Succes") except Exception as e: kc.sendText(msg.to,"Gagagl!") print e elif "Bot5 backup" in msg.text: if msg.from_ in admin: try: h = open('madydn.txt',"r") name = h.read() h.close() x = name profile = ks.getProfile() profile.displayName = x ks.updateProfile(profile) i = open('mysgjm.txt',"r") sm = i.read() i.close() y = sm cak = ks.getProfile() cak.statusMessage = y ks.updateProfile(cak) j = open('myrdps.txt',"r") ps = j.read() j.close() p = ps ks.updateProfilePicture(p) ks.sendText(msg.to, "Succes") except Exception as e: ks.sendText(msg.to,"Gagagl!") print e elif "Bot6 backup" in msg.text: if msg.from_ in admin: try: h = open('mydnsgv.txt',"r") name = h.read() h.close() x = name profile = kt.getProfile() profile.displayName = x kt.updateProfile(profile) i = open('jhmysm.txt',"r") sm = i.read() i.close() y = sm cak = kt.getProfile() cak.statusMessage = y kt.updateProfile(cak) j = open('myiyps.txt',"r") ps = j.read() j.close() p = ps kt.updateProfilePicture(p) kt.sendText(msg.to, "Succes") except Exception as e: kt.sendText(msg.to,"Gagagl!") print e #================================================= elif msg.text == "Lurking": if msg.from_ in admin: cl.sendText(msg.to, "Set point.") try: del wait2['readPoint'][msg.to] del wait2['readMember'][msg.to] except: pass now2 = datetime.now() wait2['readPoint'][msg.to] = msg.id wait2['readMember'][msg.to] = "" wait2['setTime'][msg.to] = datetime.now().strftime('%Y-%m-%d %H:%M') wait2['ROM'][msg.to] = {} print wait2 elif msg.text == "Lurking result": if msg.from_ in admin: if msg.to in wait2['readPoint']: if wait2["ROM"][msg.to].items() == []: chiya = "" else: chiya = "" for rom in wait2["ROM"][msg.to].items(): print rom chiya += rom[1] + "\n" cl.sendText(msg.to, "╔═══════════════%s\n╠════════════════\n%s╠═══════════════\n║Readig point creation:\n║ [%s]\n╚════════════════" % (wait2['readMember'][msg.to],chiya,setTime[msg.to])) else: cl.sendText(msg.to, "anda slah ketik-_-") #======================================== #---------------FUNGSI RATAIN GRUP TANPA KICK SESAMA BOT/Admin/Bots----------# elif "Cleanse" in msg.text: if msg.from_ in admin: if msg.toType == 2: print "ok cleanse" _name = msg.text.replace("Cleanse","") gs = cl.getGroup(msg.to) #gs = kk.getGroup(msg.to) #gs = kc.getGroup(msg.to) cl.sendText(msg.to,"Just some casual cleansing ") targets = [] for g in gs.members: if _name in g.displayName: targets.append(g.mid) if targets == []: cl.sendText(msg.to,"you are not admin") else: for target in targets: if not target in Bots: if not target in admin: try: klist=[cl] kicker=random.choice(klist) kicker.kickoutFromGroup(msg.to,[target]) print (msg.to,[g.mid]) except: cl.sendText(msg.to,"Group cleanse") #================================================ #======================================== elif msg.text.lower() == '.': if msg.from_ in admin: ginfo = cl.getGroup(msg.to) cl.sendText(msg.to,"🄷🄰🄻🄻🄾...\n█▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀█\n█░░╦─╦╔╗╦─╔╗╔╗╔╦╗╔╗░░█\n█░░║║║╠─║─║─║║║║║╠─░░█\n█░░╚╩╝╚╝╚╝╚╝╚╝╩─╩╚╝░░█\n█▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄█\n█░░╔╦╗ ╔╗░░█\n█░░─║─ ║║░░█\n█░░─╩ ─╚╝░░█\n\n⛦•••{ " + str(ginfo.name) + " }•••⛦" + "\n\nBudayakan Cek Note\nDan Semoga Betah Disini..\nJangan Lupa Nikung Kak,..Yehkan..\n\nDah Gitu Ajah..\n\n\n===❍•••{☠ʟᴇᴠᴀɴᴀ☠}•••❍===\n"+ datetime.now().strftime('%H:%M:%S')) cl.sendText(msg.to,"Owner Grup " + str(ginfo.name) + " :\n" + ginfo.creator.displayName ) #========================================= elif msg.text in ["Mimic on","mimic on"]: if wait3["copy"] == True: if wait["lang"] == "JP": cl.sendText(msg.to,"Already on") else: cl.sendText(msg.to,"Mimic On") else: wait3["copy"] = True if wait["lang"] == "JP": cl.sendText(msg.to,"Mimic On") else: cl.sendText(msg.to,"Already on") elif msg.text in ["Mimic off","mimic:off"]: if wait3["copy"] == False: if wait["lang"] == "JP": cl.sendText(msg.to,"Already on") else: cl.sendText(msg.to,"Mimic Off") else: wait3["copy"] = False if wait["lang"] == "JP": cl.sendText(msg.to,"Mimic Off") else: cl.sendText(msg.to,"Already on") elif msg.text in ["Target list"]: if wait3["target"] == {}: cl.sendText(msg.to,"nothing") else: mc = "Target mimic user\n" for mi_d in wait3["target"]: mc += "✔️ "+cl.getContact(mi_d).displayName + "\n" cl.sendText(msg.to,mc) elif "Mimic target " in msg.text: if wait3["copy"] == True: siapa = msg.text.replace("Mimic target ","") if siapa.rstrip(' ') == "me": wait3["copy2"] = "me" cl.sendText(msg.to,"Mimic change to me") elif siapa.rstrip(' ') == "target": wait3["copy2"] = "target" cl.sendText(msg.to,"Mimic change to target") else: cl.sendText(msg.to,"I dont know") elif "Target @" in msg.text: target = msg.text.replace("Target @","") gc = cl.getGroup(msg.to) targets = [] for member in gc.members: if member.displayName == target.rstrip(' '): targets.append(member.mid) if targets == []: cl.sendText(msg.to, "User not found") else: for t in targets: wait3["target"][t] = True cl.sendText(msg.to,"Target added") elif "Del target @" in msg.text: target = msg.text.replace("Del target @","") gc = cl.getGroup(msg.to) targets = [] for member in gc.members: if member.displayName == target.rstrip(' '): targets.append(member.mid) if targets == []: cl.sendText(msg.to, "User not found") else: for t in targets: del wait3["target"][t] cl.sendText(msg.to,"Target deleted") #======================================= #-------------------Fungsi spam start-------------------------- elif "Spam change:" in msg.text: if msg.from_ in admin: wait["spam"] = msg.text.replace("Spam change:","") cl.sendText(msg.to,"spam changed") elif "Spam add:" in msg.text: if msg.from_ in admin: wait["spam"] = msg.text.replace("Spam add:","") if wait["lang"] == "JP": cl.sendText(msg.to,"spam changed") else: cl.sendText(msg.to,"Done") elif "Spam:" in msg.text: if msg.from_ in admin: strnum = msg.text.replace("Spam:","") num = int(strnum) for var in range(0,num): cl.sendText(msg.to, wait["spam"]) #-------------------Fungsi spam finish---------------------------- #----------------------------------------------- #----------------------------------------------- elif 'apakah' in msg.text.lower(): if msg.from_ in admin: tanya = msg.text.lower().replace("apakah","") jawab = ("Ya","Tidak","Mungkin","Bisa jadi") jawaban = random.choice(jawab) cl.sendText(msg.to,jawaban) #================================================ #=============================================== #================================================= elif "Spamg " in msg.text: if msg.from_ in admin: txt = msg.text.split(" ") jmlh = int(txt[2]) teks = msg.text.replace("Spamg "+str(txt[1])+" "+str(jmlh)+ " ","") tulisan = jmlh * (teks+"\n") #Keke cantik <3 if txt[1] == "on": if jmlh <= 10000: for x in range(jmlh): cl.sendText(msg.to, teks) else: cl.sendText(msg.to, "Out of range! ") elif txt[1] == "off": if jmlh <= 10000: cl.sendText(msg.to, tulisan) else: cl.sendText(msg.to, "Out of range! ") #----------------------------------------------- elif "Steal mid @" in msg.text: if msg.from_ in admin: _name = msg.text.replace("Steal mid @","") _nametarget = _name.rstrip(' ') gs = cl.getGroup(msg.to) for g in gs.members: if _nametarget == g.displayName: cl.sendText(msg.to, g.mid) else: pass #------------------------------------------------- elif "Pm cast " in msg.text: if msg.from_ in owner: bctxt = msg.text.replace("Pm cast ", "") t = cl.getAllContactIds() for manusia in t: cl.sendText(manusia,(bctxt)) elif "Broadcast " in msg.text: if msg.from_ in owner: bctxt = msg.text.replace("Broadcast ", "") n = cl.getGroupIdsJoined() for manusia in n: cl.sendText(manusia,(bctxt +"\n\n\nbroadcasted by:" + cl.getContact(msg.from_).displayName)) #======================================== elif msg.text in ["Join all"]: if msg.from_ in admin: G = cl.getGroup(msg.to) info = cl.getGroup(msg.to) G.preventJoinByTicket = False cl.updateGroup(G) invsend = 0 Ticket = cl.reissueGroupTicket(msg.to) ki.acceptGroupInvitationByTicket(msg.to,Ticket) time.sleep(0.0001) kk.acceptGroupInvitationByTicket(msg.to,Ticket) time.sleep(0.0001) kc.acceptGroupInvitationByTicket(msg.to,Ticket) time.sleep(0.0001) ks.acceptGroupInvitationByTicket(msg.to,Ticket) time.sleep(0.0001) kt.acceptGroupInvitationByTicket(msg.to,Ticket) time.sleep(0.0001) G = cl.getGroup(msg.to) G.preventJoinByTicket = True cl.updateGroup(G) print "All_Kickers_Ok!" G.preventJoinByTicket(G) cl.updateGroup(G) #===================================================================================== elif msg.text in ["Bye allgroups"]: if msg.from_ in admin: gid = cl.getGroupIdsJoined() for i in gid: cl.leaveGroup(i) ki.leaveGroup(i) kk.leaveGroup(i) kc.leaveGroup(i) ks.leaveGroup(i) kt.leaveGroup(i) if wait["lang"] == "JP": ki.sendText(msg.to,"bye-bye") else: ki.sendText(msg.to,"He declined all invitations") elif msg.text in ["Bye all"]: if msg.from_ in admin: if msg.toType == 2: X = cl.getGroup(msg.to) try: ki.leaveGroup(msg.to) kk.leaveGroup(msg.to) kc.leaveGroup(msg.to) ks.leaveGroup(msg.to) kt.leaveGroup(msg.to) except: pass elif msg.text in ["Center @bye"]: if msg.from_ in admin: if msg.toType == 2: X = cl.getGroup(msg.to) try: cl.sendMessage(msg.to,"bye-bye") cl.leaveGroup(msg.to) except: pass elif msg.text in ["Nk "]: if msg.from_ in admin: mk0 = msg.text.replace("Nk ","") mk1 = mk0.lstrip() mk2 = mk1.replace("@","") mk3 = mk2.rstrip() _name = mk3 gs = cl.getGroup(msg.to) targets = [] for h in gs.members: if _name in h.displayName: targets.append(h.mid) if targets == []: sendMessage(msg.to,"user does not exist") pass else: for target in targets: try: if msg.from_ not in target: cl.kickoutFromGroup(msg.to,[target]) except: random.choice(KAC).kickoutFromGroup(msg.to,[target]) #========================================== elif "youtube " in msg.text.lower(): if msg.from_ in admin: query = msg.text.split(" ") try: if len(query) == 3: isi = yt(query[2]) hasil = isi[int(query[1])-1] cl.sendText(msg.to, hasil) else: isi = yt(query[1]) cl.sendText(msg.to, isi[0]) except Exception as e: cl.sendText(msg.to, str(e)) elif 'Vidio ' in msg.text: if msg.from_ in admin: try: textToSearch = (msg.text).replace('Vidio ', "").strip() query = urllib.quote(textToSearch) url = "https://www.youtube.com/results?search_query=" + query response = urllib2.urlopen(url) html = response.read() soup = BeautifulSoup(html, "html.parser") results = soup.find(attrs={'class':'yt-uix-tile-link'}) ght=('https://www.youtube.com' + results['href']) cl.sendVideoWithURL(msg.to,ght) except: cl.sendText(msg.to,"Could not find it") #------------------------------------------------- elif "/say-jp " in msg.text: say = msg.text.replace("/say-jp ","") lang = 'jp' tts = gTTS(text=say, lang=lang) tts.save("hasil.mp3") cl.sendAudio(msg.to,"hasil.mp3") #------------------------------------------------ elif "/say-en " in msg.text: say = msg.text.replace("/say-en ","") lang = 'en' tts = gTTS(text=say, lang=lang) tts.save("hasil.mp3") cl.sendAudio(msg.to,"hasil.mp3") #----------------------------------------------- elif "/say " in msg.text: psn = msg.text.replace("/say ","") tts = gTTS(psn, lang='id', slow=False) tts.save('tts.mp3') cl.sendAudio(msg.to, 'tts.mp3') #----------------------------------------------- elif "Siapa " in msg.text: tanya = msg.text.replace("Siapa ","") jawab = ("Dia yg kebanyakan micin"," Dia gila") jawaban = random.choice(jawab) tts = gTTS(text=jawaban, lang='en') tts.save('tts.mp3') cl.sendAudio(msg.to,'tts.mp3') #========================================== elif "Dosa @" in msg.text: tanya = msg.text.replace("Dosa @","") jawab = ("60%","70%","80%","90%","100%","Tak terhingga") jawaban = random.choice(jawab) tts = gTTS(text=jawaban, lang='en') tts.save('tts.mp3') cl.sendText(msg.to,"Dosanya adalah cek voie ini") cl.sendAudio(msg.to,'tts.mp3') #========================================== #========================================== elif "/ " in msg.text.lower(): txt = msg.text.replace("kedapkedip ", "") t1 = "\xf4\x80\xb0\x82\xf4\x80\xb0\x82\xf4\x80\xb0\x82\xf4\x80\xb0\x82\xf4\x80\xa0\x81\xf4\x80\xa0\x81\xf4\x80\xa0\x81" t2 = "\xf4\x80\x82\xb3\xf4\x8f\xbf\xbf" cl.sendText(msg.to, t1 + txt + t2) #-------Cek sider biar mirip kek siri----------------------------- elif "Setlastpoint" in msg.text: subprocess.Popen("echo '' > dataSeen/"+msg.to+".txt", shell=True, stdout=subprocess.PIPE) #cl.sendText(msg.to, "Checkpoint checked!") cl.sendText(msg.to, "Set the lastseens' point(`・ω・´)\n\n" + datetime.now().strftime('%H:%M:%S')) print "Setlastpoint" #-------------------------------------------- elif "Viewlastseen" in msg.text: lurkGroup = "" dataResult, timeSeen, contacts, userList, timelist, recheckData = [], [], [], [], [], [] with open('dataSeen/'+msg.to+'.txt','r') as rr: contactArr = rr.readlines() for v in xrange(len(contactArr) -1,0,-1): num = re.sub(r'\n', "", contactArr[v]) contacts.append(num) pass contacts = list(set(contacts)) for z in range(len(contacts)): arg = contacts[z].split('|') userList.append(arg[0]) timelist.append(arg[1]) uL = list(set(userList)) for ll in range(len(uL)): try: getIndexUser = userList.index(uL[ll]) timeSeen.append(time.strftime("%d日 %H:%M:%S", time.localtime(int(timelist[getIndexUser]) / 1000))) recheckData.append(userList[getIndexUser]) except IndexError: conName.append('nones') pass contactId = cl.getContacts(recheckData) for v in range(len(recheckData)): dataResult.append(contactId[v].displayName + ' ('+timeSeen[v]+')') pass if len(dataResult) > 0: grp = '\n• '.join(str(f) for f in dataResult) total = '\nThese %iuesrs have seen at the lastseen\npoint(`・ω・´)\n\n%s' % (len(dataResult), datetime.now().strftime('%H:%M:%S') ) cl.sendText(msg.to, "• %s %s" % (grp, total)) else: cl.sendText(msg.to, "Sider ga bisa di read cek setpoint dulu bego tinggal ketik\nSetlastpoint\nkalo mau liat sider ketik\nViewlastseen") print "Viewlastseen" #========================================== elif msg.text in ["Purge"]: if msg.from_ in admin: if msg.toType == 2: group = cl.getGroup(msg.to) gMembMids = [contact.mid for contact in group.members] matched_list = [] for tag in wait["blacklist"]: matched_list+=filter(lambda str: str == tag, gMembMids) if matched_list == []: random.choice(KAC).sendText(msg.to,"group purge") return for jj in matched_list: try: klist=[cl] kicker = random.choice(klist) kicker.kickoutFromGroup(msg.to,[jj]) print (msg.to,[jj]) except: pass elif ("Fuck" in msg.text): if msg.from_ in admin: targets = [] key = eval(msg.contentMetadata["MENTION"]) key["MENTIONEES"][0]["M"] for x in key["MENTIONEES"]: targets.append(x["M"]) for target in targets: try: cl.kickoutFromGroup(msg.to,[target]) except: cl.sendText(msg.to,"Error") #----------------------------------------------------------- elif "Ban @" in msg.text: if msg.from_ in admin: if msg.toType == 2: print "[BL]ok" _name = msg.text.replace("Ban @","") _nametarget = _name.rstrip(' ') gs = cl.getGroup(msg.to) targets = [] for g in gs.members: if _nametarget == g.displayName: targets.append(g.mid) if targets == []: cl.sendText(msg.to,"Not found.") else: for target in targets: try: wait["blacklist"][target] = True f=codecs.open('st2__b.json','w','utf-8') json.dump(wait["blacklist"], f, sort_keys=True, indent=4,ensure_ascii=False) cl.sendText(msg.to,"Success Masuk daftar orang bejat Boss") except: cl.sendText(msg.to,"Error") elif "Unban @" in msg.text: if msg.from_ in admin: if msg.toType == 2: print "[WL]ok" _name = msg.text.replace("Unban @","") _nametarget = _name.rstrip(' ') gs = cl.getGroup(msg.to) targets = [] for g in gs.members: if _nametarget == g.displayName: targets.append(g.mid) if targets == []: cl.sendText(msg.to,"Not found.") else: for target in targets: try: del wait["blacklist"][target] f=codecs.open('st2__b.json','w','utf-8') json.dump(wait["blacklist"], f, sort_keys=True, indent=4,ensure_ascii=False) cl.sendText(msg.to,"Sudah di keluarkan dari daftar bejat Boss") except: cl.sendText(msg.to,"There was no blacklist user") elif msg.text in ["Clear banlist"]: if msg.from_ in admin: wait["blacklist"] = {} cl.sendText(msg.to,"succes clear all banlist") elif msg.text in ["Banned"]: if msg.from_ in admin: wait["wblacklist"] = True cl.sendText(msg.to,"send contact to ban") elif msg.text in ["Unbanned"]: if msg.from_ in admin: wait["dblacklist"] = True cl.sendText(msg.to,"send contact to ban") elif msg.text in ["Banlist"]: if msg.from_ in admin: if wait["blacklist"] == {}: cl.sendText(msg.to,"nothing") else: cl.sendText(msg.to,"blacklist user list") mc = "[⎈]Blacklist User[⎈]\n" for mi_d in wait["blacklist"]: mc += "[✗] " + cl.getContact(mi_d).displayName + " \n" cl.sendText(msg.to, mc + "") #============================================= # ----------------- BAN MEMBER BY TAG 2TAG ATAU 10TAG MEMBER elif ("Ban repeat " in msg.text): if msg.from_ in admin: key = eval(msg.contentMetadata["MENTION"]) key["MENTIONEES"][0]["M"] targets = [] for x in key["MENTIONEES"]: targets.append(x["M"]) for target in targets: try: wait["blacklist"][target] = True f=codecs.open('st2__b.json','w','utf-8') json.dump(wait["blacklist"], f, sort_keys=True, indent=4,ensure_ascii=False) cl.sendText(msg.to,"Succes Banned ") except: pass #============================================ #elif msg.text in ["Clear"]: #if msg.toType == 2: #group = cl.getGroup(msg.to) #gMembMids = [contact.mid for contact in group.invitee] #for _mid in gMembMids: #random.choice(KAC).cancelGroupInvitation(msg.to,[_mid]) #cl.sendText(msg.to,"Clear boss!!!") elif msg.text.lower() in ["Ats","Tag","mention all"]: if msg.from_ in admin: group = cl.getGroup(msg.to) nama = [contact.mid for contact in group.members] nm1, nm2, nm3, nm4, nm5, jml = [], [], [], [], [], len(nama) if jml <= 100: mention(msg.to, nama) if jml > 100 and jml < 200: for i in range(0, 100): nm1 += [nama[i]] mention(msg.to, nm1) for j in range(101, len(nama)): nm2 += [nama[j]] mention(msg.to, nm2) if jml > 200 and jml < 300: for i in range(0, 100): nm1 += [nama[i]] mention(msg.to, nm1) for j in range(101, 200): nm2 += [nama[j]] mention(msg.to, nm2) for k in range(201, len(nama)): nm3 += [nama[k]] mention(msg.to, nm3) if jml > 300 and jml < 400: for i in range(0, 100): nm1 += [nama[i]] mention(msg.to, nm1) for j in range(101, 200): nm2 += [nama[j]] mention(msg.to, nm2) for k in range(201, 300): nm3 += [nama[k]] mention(msg.to, nm3) for l in range(301, len(nama)): nm4 += [nama[l]] mention(msg.to, nm4) if jml > 400 and jml < 500: for i in range(0, 100): nm1 += [nama[i]] mention(msg.to, nm1) for j in range(101, 200): nm2 += [nama[j]] mention(msg.to, nm2) for k in range(201, 300): nm3 += [nama[k]] mention(msg.to, nm3) for l in range(301, 400): nm4 += [nama[l]] mention(msg.to, nm4) for h in range(401, len(nama)): nm5 += [nama[h]] mention(msg.to, nm5) if jml > 500: cl.sendText(msg.to,'Member melebihi batas.') cnt = Message() cnt.text = "Done : " + str(jml) + " Members" cnt.to = msg.to cl.sendMessage(cnt) #=========================================== if op.param3 == "1": if op.param1 in protectname: group = cl.getGroup(op.param1) try: group.name = wait["pro_name"][op.param1] cl.updateGroup(group) cl.sendText(op.param1, "Groupname protect now") wait["blacklist"][op.param2] = True f=codecs.open('st2__b.json','w','utf-8') json.dump(wait["blacklist"], f, sort_keys=True, indent=4,ensure_ascii=False) except Exception as e: print e pass #------------------------------------------------------------------------------------ if op.type == 32: OWN = "" if op.param2 in Bots and admin: pass else: Inviter = op.param3.replace("",',') InviterX = Inviter.split(",") contact = cl.getContact(op.param2) ki.kickoutFromGroup(op.param1,[op.param2]) kk.kickoutFromGroup(op.param1,[op.param2]) kc.kickoutFromGroup(op.param1,[op.param2]) ks.kickoutFromGroup(op.param1,[op.param2]) kt.kickoutFromGroup(op.param1,[op.param2]) wait["blacklist"][op.param2] = True f=codecs.open('st2__b.json','w','utf-8') json.dump(wait["blacklist"], f, sort_keys=True, indent=4,ensure_ascii=False) #=========================================== if op.type == 55: try: if op.param1 in wait2['readPoint']: Name = cl.getContact(op.param2).displayName if Name in wait2['readMember'][op.param1]: pass else: wait2['readMember'][op.param1] += "\n╠" + Name wait2['ROM'][op.param1][op.param2] = "╠" + Name else: cl.sendText except: pass #------------------------ if op.type == 59: print op except Exception as error: print error def autoSta(): count = 1 while True: try: for posts in cl.activity(1)["result"]["posts"]: if posts["postInfo"]["liked"] is False: if wait["likeOn"] == True: cl.like(posts["userInfo"]["writerMid"], posts["postInfo"]["postId"], 1001) ki.like(posts["userInfo"]["writerMid"], posts["postInfo"]["postId"], 1001) kk.like(posts["userInfo"]["writerMid"], posts["postInfo"]["postId"], 1001) kc.like(posts["userInfo"]["writerMid"], posts["postInfo"]["postId"], 1001) ks.like(posts["userInfo"]["writerMid"], posts["postInfo"]["postId"], 1001) kt.like(posts["userInfo"]["writerMid"], posts["postInfo"]["postId"], 1001) if wait["commentOn"] == True: if posts["userInfo"]["writerMid"] in wait["commentBlack"]: pass else: cl.comment(posts["userInfo"]["writerMid"],posts["postInfo"]["postId"],wait["comment"]) ki.comment(posts["userInfo"]["writerMid"],posts["postInfo"]["postId"],wait["comment"]) kk.comment(posts["userInfo"]["writerMid"],posts["postInfo"]["postId"],wait["comment"]) kc.comment(posts["userInfo"]["writerMid"],posts["postInfo"]["postId"],wait["comment"]) ks.comment(posts["userInfo"]["writerMid"],posts["postInfo"]["postId"],wait["comment"]) kt.comment(posts["userInfo"]["writerMid"],posts["postInfo"]["postId"],wait["comment"]) except: count += 1 if(count == 50): sys.exit(0) else: pass #thread1 = threading.Thread(target=autoSta) #thread1.daemon = True #thread1.start() def a2(): now2 = datetime.now() nowT = datetime.strftime(now2,"%M") if nowT[14:] in ["10","20","30","40","50","00"]: return False else: return True def nameUpdate(): while True: try: #while a2(): #pass if wait["clock"] == True: now2 = datetime.now() nowT = datetime.strftime(now2,"(%H:%M)") profile = cl.getProfile() profile.displayName = wait["cName"] + nowT cl.updateProfile(profile) time.sleep(600) except: pass #thread2 = threading.Thread(target=nameUpdate) #thread2.daemon = True #thread2.start() while True: try: Ops = cl.fetchOps(cl.Poll.rev, 5) except EOFError: raise Exception("It might be wrong revision\n" + str(cl.Poll.rev)) for Op in Ops: if (Op.type != OpType.END_OF_OPERATION): cl.Poll.rev = max(cl.Poll.rev, Op.revision) bot(Op)
const express = require('express'); const router = express.Router(); const logger = require('../../modules/logger'); const userController = require('../../controllers/user'); router.get('/profile', (req, res) => { const params = req.body; params.decoded = req.decoded; userController.getUser(params) .then(([user, responseCode]) => { res.status(responseCode) .json({ success: true, result: user }); }).catch(([err, responseCode]) => { res.status(responseCode); if (typeof(err) !== 'string') { logger.error('routes /users GET', err); err = 'Server side error'; } res.json({ success: false, message: err }); }); }); // Update user profile router.put('/profile', (req, res) => { const params = req.body; params.decoded = req.decoded; userController.updateUser(params) .then(([user, responseCode]) => { res.status(responseCode) .json({ success: true, result: user }); }).catch(([err, responseCode]) => { res.status(responseCode); if (typeof(err) !== 'string') { logger.error('routes /users PUT', err); err = 'Server side error'; } res.json({ success: false, message: err }); }); }); module.exports = router;
import moment from 'moment' import { unallocated, allocated, app, offenderSearch, keyworkerSearch, keyworkerSettings } from './index' import { setMenuOpen } from '../actions' import * as types from '../actions/actionTypes' const appInitialState = { error: null, message: null, loaded: false, } const appWithErrorState = { error: 'There was a problem', message: null, loaded: false, } const appWithValidationErrorState = { validationErrors: { myField: 'An error!' }, } const allocatedInitialState = { allocatedKeyworkers: [], allocatedList: [], keyworkerList: [], toDate: moment().format('DD/MM/YYYY'), fromDate: moment().format('DD/MM/YYYY'), } const allocatedPopulatedState = { allocatedKeyworkers: ['allocatedKeyworkers'], allocatedList: ['allocatedList'], keyworkerList: ['keyworkerList'], toDate: '01/01/2000', fromDate: '01/01/1999', } const unallocatedInitialState = { unallocatedList: [], } const offenderSearchInitialState = { searchText: '', allocationStatus: 'all', housingLocation: '', } const keyworkerSearchInitialState = { searchText: '', statusFilter: '', keyworkerSearchResults: [], keyworkerAllocations: [], keyworkerChangeList: [], keyworkerList: [], keyworker: null, status: '', capacity: '', statusChangeBehaviour: '', annualLeaveReturnDate: '', } const keyworkerSearchPopulatedState = { searchText: 'yes', statusFilter: 'UNAVAILABLE', keyworkerSearchResults: [{ value: 'search' }], keyworkerAllocations: [{ value: 'allocations' }], keyworkerChangeList: [], keyworkerList: [{ value: 'available keyworkers' }], keyworker: { say: 'hello' }, status: 'ACTIVE', capacity: '7', statusChangeBehaviour: 'newBehaviour', annualLeaveReturnDate: '25/06/2018', } const keyworkerSettingsInitialState = { capacity: 6, extCapacity: 9, allowAuto: false, sequenceFrequency: 1, supported: false, migrated: false, } describe('app (global) reducer', () => { it('should return the initial state', () => { expect(app(undefined, {})).toEqual({ config: { mailTo: '', keyworkerProfileStatsEnabled: 'false', keyworkerDashboardStatsEnabled: false, notmEndpointUrl: '', prisonStaffHubUrl: '', }, user: { activeCaseLoadId: '', caseLoadOptions: [], expiredFlag: false, firstName: '', lastName: '', lockedFlag: false, maintainAccess: false, maintainAccessAdmin: false, migration: false, staffId: 0, username: '', writeAccess: false, }, shouldShowTerms: false, error: '', message: '', loaded: false, menuOpen: false, page: 0, validationErrors: {}, }) }) it('should handle SET_CONFIG', () => { expect( app(appInitialState, { type: types.SET_CONFIG, config: { mailTo: 'a@b.com' }, }) ).toEqual({ error: null, message: null, config: { mailTo: 'a@b.com' }, loaded: false, }) }) it('should handle SET_USER_DETAILS', () => { expect( app(appInitialState, { type: types.SET_USER_DETAILS, user: { field: 'value' }, }) ).toEqual({ error: null, message: null, user: { field: 'value' }, loaded: false, }) }) it('should handle SWITCH_AGENCY', () => { expect( app(appInitialState, { type: types.SWITCH_AGENCY, activeCaseLoadId: 'BXI', }) ).toEqual({ error: null, message: null, user: { activeCaseLoadId: 'BXI' }, loaded: false, }) }) it('should handle SET_TERMS_VISIBILITY', () => { expect( app(appInitialState, { type: types.SET_TERMS_VISIBILITY, shouldShowTerms: true, }) ).toEqual({ error: null, message: null, shouldShowTerms: true, loaded: false, }) }) it('should handle SET_ERROR', () => { expect( app(appInitialState, { type: types.SET_ERROR, error: 'HELP!', }) ).toEqual({ error: 'HELP!', message: null, loaded: false, }) }) it('should handle RESET_ERROR', () => { expect( app(appWithErrorState, { type: types.RESET_ERROR, }) ).toEqual({ error: '', loaded: false, message: null }) }) it('should handle SET_MESSAGE', () => { expect( app(appInitialState, { type: types.SET_MESSAGE, message: 'An important message!', }) ).toEqual({ error: null, message: 'An important message!', loaded: false, }) }) it('should handle SET_LOADED', () => { expect( app(appInitialState, { type: types.SET_LOADED, loaded: true, }) ).toEqual({ error: null, message: null, loaded: true, }) }) it('should handle SET_VALIDATION_ERROR (first error)', () => { expect( app(appInitialState, { type: types.SET_VALIDATION_ERROR, fieldName: 'myField', message: 'An error!', }) ).toEqual({ error: null, message: null, loaded: false, validationErrors: { myField: 'An error!' }, }) }) it('should handle SET_VALIDATION_ERROR (second error)', () => { expect( app(appWithValidationErrorState, { type: types.SET_VALIDATION_ERROR, fieldName: 'myField2', message: 'Another error!', }) ).toEqual({ validationErrors: { myField: 'An error!', myField2: 'Another error!', }, }) }) it('should handle RESET_VALIDATION_ERRORS', () => { expect( app(appWithValidationErrorState, { type: types.RESET_VALIDATION_ERRORS, }) ).toEqual({ validationErrors: {}, }) }) }) describe('unallocated reducer', () => { it('should return the initial state', () => { expect(unallocated(undefined, {})).toEqual({ unallocatedList: [], }) }) it('should handle SET_UNALLOCATED', () => { const list = [{ name: 'Jack', keyworker: 'Jill' }] expect( unallocated(unallocatedInitialState, { type: types.SET_UNALLOCATED_LIST, unallocatedList: list, }) ).toEqual({ unallocatedList: list, }) }) }) describe('allocated reducer', () => { it('should return the initial state', () => { expect(allocated(undefined, {})).toEqual({ allocatedKeyworkers: [], allocatedList: [], keyworkerList: [], fromDate: moment().format('DD/MM/YYYY'), toDate: moment().format('DD/MM/YYYY'), }) }) it('should handle SET_ALLOCATED_DETAILS', () => { const list = [{ name: 'Jack', keyworker: 'Jill' }] const keyWorkers = [{ name: 'Amy', staffId: 123 }] expect( allocated(allocatedInitialState, { type: types.SET_ALLOCATED_DETAILS, allocatedList: list, keyworkerList: keyWorkers, }) ).toEqual({ allocatedList: list, keyworkerList: keyWorkers, fromDate: moment().format('DD/MM/YYYY'), toDate: moment().format('DD/MM/YYYY'), allocatedKeyworkers: [], }) }) it('should clear allocated keyworkers when SET_ALLOCATED_DETAILS is dispatched', () => { const list = [{ name: 'Jack', keyworker: 'Jill' }] const keyWorkers = [{ name: 'Amy', staffId: 123 }] expect( allocated(allocatedPopulatedState, { type: types.SET_ALLOCATED_DETAILS, allocatedList: list, keyworkerList: keyWorkers, }) ).toEqual({ allocatedList: list, keyworkerList: keyWorkers, fromDate: '01/01/1999', toDate: '01/01/2000', allocatedKeyworkers: [], }) }) it('should handle SET_MANUAL_OVERRIDE_LIST', () => { const list = [{ name: 'Jack', keyworker: 'Jill' }] expect( allocated(allocatedInitialState, { type: types.SET_MANUAL_OVERRIDE_LIST, allocatedKeyworkers: list, }) ).toEqual({ allocatedList: [], keyworkerList: [], fromDate: moment().format('DD/MM/YYYY'), toDate: moment().format('DD/MM/YYYY'), allocatedKeyworkers: list, }) }) it('should handle SET_MANUAL_OVERRIDE_DATE_FILTER', () => { expect( allocated(allocatedPopulatedState, { type: types.SET_MANUAL_OVERRIDE_DATE_FILTER, date: '01/01/1888', dateName: 'fromDate', }) ).toEqual({ allocatedKeyworkers: ['allocatedKeyworkers'], allocatedList: ['allocatedList'], keyworkerList: ['keyworkerList'], fromDate: '01/01/1888', toDate: '01/01/2000', }) }) }) describe('offender search reducer', () => { it('should return the initial state', () => { expect(offenderSearch(undefined, {})).toEqual({ searchText: '', allocationStatus: 'all', locations: [], housingLocation: '', offenderResults: { keyworkerResponse: [], offenderResponse: [], partialResults: false, }, }) }) it('should handle SET_OFFENDER_SEARCH_TEXT', () => { expect( offenderSearch(offenderSearchInitialState, { type: types.SET_OFFENDER_SEARCH_TEXT, searchText: 'birdman of Alcatraz', }) ).toEqual({ searchText: 'birdman of Alcatraz', allocationStatus: 'all', housingLocation: '', }) }) it('should handle SET_OFFENDER_SEARCH_ALLOCATION_STATUS', () => { expect( offenderSearch(offenderSearchInitialState, { type: types.SET_OFFENDER_SEARCH_ALLOCATION_STATUS, allocationStatus: 'unallocated', }) ).toEqual({ searchText: '', allocationStatus: 'unallocated', housingLocation: '', }) }) it('should handle SET_OFFENDER_SEARCH_HOUSING_LOCATION', () => { expect( offenderSearch(offenderSearchInitialState, { type: types.SET_OFFENDER_SEARCH_HOUSING_LOCATION, housingLocation: 'Block C', }) ).toEqual({ searchText: '', allocationStatus: 'all', housingLocation: 'Block C', }) }) it('should handle SET_OFFENDER_SEARCH_LOCATIONS', () => { expect( offenderSearch(offenderSearchInitialState, { type: types.SET_OFFENDER_SEARCH_LOCATIONS, locations: ['The Sistine Chapel'], }) ).toEqual({ searchText: '', allocationStatus: 'all', housingLocation: '', locations: ['The Sistine Chapel'], }) }) it('should handle SET_OFFENDER_SEARCH_RESULTS', () => { expect( offenderSearch(offenderSearchInitialState, { type: types.SET_OFFENDER_SEARCH_RESULTS, offenderResults: [{ lastName: 'Bloggs' }], }) ).toEqual({ searchText: '', allocationStatus: 'all', housingLocation: '', offenderResults: [{ lastName: 'Bloggs' }], }) }) }) describe('key worker search reducer', () => { it('should handle SET_KEY_WORKER_SEARCH_TEXT', () => { expect( keyworkerSearch(keyworkerSearchInitialState, { type: types.SET_KEY_WORKER_SEARCH_TEXT, searchText: 'Kelly Keyworker', }) ).toEqual({ searchText: 'Kelly Keyworker', statusFilter: '', keyworkerSearchResults: [], keyworkerAllocations: [], keyworkerChangeList: [], keyworkerList: [], keyworker: null, status: '', capacity: '', statusChangeBehaviour: '', annualLeaveReturnDate: '', }) }) it('should handle SET_KEY_WORKER_STATUS_FILTER', () => { expect( keyworkerSearch(keyworkerSearchInitialState, { type: types.SET_KEY_WORKER_STATUS_FILTER, statusFilter: 'INACTIVE', }) ).toEqual({ searchText: '', statusFilter: 'INACTIVE', keyworkerSearchResults: [], keyworkerAllocations: [], keyworkerChangeList: [], keyworkerList: [], keyworker: null, status: '', capacity: '', statusChangeBehaviour: '', annualLeaveReturnDate: '', }) }) it('should handle SET_KEY_WORKER_SEARCH_RESULTS', () => { const list = [{ firstName: 'Jack', surname: 'Brown' }] expect( keyworkerSearch(keyworkerSearchInitialState, { type: types.SET_KEY_WORKER_SEARCH_RESULTS_LIST, keyworkerSearchResults: list, }) ).toEqual({ searchText: '', statusFilter: '', keyworkerSearchResults: list, keyworkerAllocations: [], keyworkerChangeList: [], keyworkerList: [], keyworker: null, status: '', capacity: '', statusChangeBehaviour: '', annualLeaveReturnDate: '', }) }) it('should handle SET_KEY_WORKER', () => { expect( keyworkerSearch(keyworkerSearchInitialState, { type: types.SET_KEY_WORKER, keyworker: { key: 'value' }, }) ).toEqual({ searchText: '', statusFilter: '', keyworkerSearchResults: [], keyworkerAllocations: [], keyworkerChangeList: [], keyworkerList: [], keyworker: { key: 'value' }, status: '', capacity: '', statusChangeBehaviour: '', annualLeaveReturnDate: '', }) }) it('should handle SET_KEY_WORKER_STATS', () => { const fromDate = '2018-10-10' const toDate = '2018-10-11' expect( keyworkerSearch(keyworkerSearchInitialState, { type: types.SET_KEY_WORKER_STATS, stats: { data: 'world', fromDate, toDate }, }) ).toEqual({ searchText: '', statusFilter: '', keyworkerSearchResults: [], keyworkerAllocations: [], keyworkerChangeList: [], keyworkerList: [], keyworker: { stats: { data: 'world', fromDate, toDate, }, }, status: '', capacity: '', statusChangeBehaviour: '', annualLeaveReturnDate: '', }) }) it('should handle SET_KEY_WORKER_CHANGE_LIST', () => { expect( keyworkerSearch(keyworkerSearchInitialState, { type: types.SET_KEY_WORKER_CHANGE_LIST, keyworkerChangeList: [{ key: 'value' }], }) ).toEqual({ searchText: '', statusFilter: '', keyworkerSearchResults: [], keyworkerAllocations: [], keyworkerChangeList: [{ key: 'value' }], keyworkerList: [], keyworker: null, status: '', capacity: '', statusChangeBehaviour: '', annualLeaveReturnDate: '', }) }) it('should handle SET_AVAILABLE_KEY_WORKER_LIST', () => { expect( keyworkerSearch(keyworkerSearchInitialState, { type: types.SET_AVAILABLE_KEY_WORKER_LIST, keyworkerList: [{ key: 'value' }], }) ).toEqual({ searchText: '', statusFilter: '', keyworkerSearchResults: [], keyworkerAllocations: [], keyworkerChangeList: [], keyworkerList: [{ key: 'value' }], keyworker: null, status: '', capacity: '', statusChangeBehaviour: '', annualLeaveReturnDate: '', }) }) it('should handle SET_KEY_WORKER_CAPACITY', () => { expect( keyworkerSearch(keyworkerSearchInitialState, { type: types.SET_KEY_WORKER_CAPACITY, capacity: '9', }) ).toEqual({ searchText: '', statusFilter: '', keyworkerSearchResults: [], keyworkerAllocations: [], keyworkerChangeList: [], keyworkerList: [], keyworker: null, status: '', capacity: '9', statusChangeBehaviour: '', annualLeaveReturnDate: '', }) }) it('should handle SET_KEY_WORKER_STATUS', () => { expect( keyworkerSearch(keyworkerSearchInitialState, { type: types.SET_KEY_WORKER_STATUS, status: 'Unavailable', }) ).toEqual({ searchText: '', statusFilter: '', keyworkerSearchResults: [], keyworkerAllocations: [], keyworkerChangeList: [], keyworkerList: [], keyworker: null, status: 'Unavailable', capacity: '', statusChangeBehaviour: '', annualLeaveReturnDate: '', }) }) it('should handle SET_KEY_WORKER_STATUS_CHANGE_BEHAVIOUR', () => { expect( keyworkerSearch(keyworkerSearchInitialState, { type: types.SET_KEY_WORKER_STATUS_CHANGE_BEHAVIOUR, statusChangeBehaviour: 'runAround', }) ).toEqual({ searchText: '', statusFilter: '', keyworkerSearchResults: [], keyworkerAllocations: [], keyworkerChangeList: [], keyworkerList: [], keyworker: null, status: '', capacity: '', statusChangeBehaviour: 'runAround', annualLeaveReturnDate: '', }) }) it('should handle SET_KEY_WORKER maintaining existing state', () => { expect( keyworkerSearch(keyworkerSearchPopulatedState, { type: types.SET_KEY_WORKER, keyworker: { key: 'value' }, }) ).toEqual({ searchText: 'yes', statusFilter: 'UNAVAILABLE', keyworkerSearchResults: [{ value: 'search' }], keyworkerAllocations: [{ value: 'allocations' }], keyworkerChangeList: [], keyworkerList: [{ value: 'available keyworkers' }], keyworker: { key: 'value' }, status: 'ACTIVE', capacity: '7', statusChangeBehaviour: 'newBehaviour', annualLeaveReturnDate: '25/06/2018', }) }) it('should handle SET_ANNUAL_LEAVE_RETURN_DATE maintaining existing state', () => { expect( keyworkerSearch(keyworkerSearchPopulatedState, { type: types.SET_ANNUAL_LEAVE_RETURN_DATE, annualLeaveReturnDate: '23/23/2017', }) ).toEqual({ searchText: 'yes', statusFilter: 'UNAVAILABLE', keyworkerSearchResults: [{ value: 'search' }], keyworkerAllocations: [{ value: 'allocations' }], keyworkerChangeList: [], keyworkerList: [{ value: 'available keyworkers' }], keyworker: { say: 'hello' }, status: 'ACTIVE', capacity: '7', statusChangeBehaviour: 'newBehaviour', annualLeaveReturnDate: '23/23/2017', }) }) it('should handle SET_MENU_OPEN', () => { let state = app(appInitialState, setMenuOpen(true)) expect(state.menuOpen).toBe(true) state = app(appInitialState, setMenuOpen(false)) expect(state.menuOpen).toBe(false) }) }) describe('key worker settings reducer', () => { it('should return the initial state', () => { expect(keyworkerSettings(undefined, {})).toEqual(keyworkerSettingsInitialState) }) it('should handle SET_KEYWORKER_SETTINGS_CAPACITY', () => { const updatedKeyworkerSettings = keyworkerSettingsInitialState updatedKeyworkerSettings.capacity = 4 expect( keyworkerSettings(keyworkerSettingsInitialState, { type: types.SET_KEYWORKER_SETTINGS_CAPACITY, capacity: 4, }) ).toEqual(updatedKeyworkerSettings) }) it('should handle SET_KEYWORKER_SETTINGS_EXT_CAPACITY', () => { const updatedKeyworkerSettings = keyworkerSettingsInitialState updatedKeyworkerSettings.extCapacity = 11 expect( keyworkerSettings(keyworkerSettingsInitialState, { type: types.SET_KEYWORKER_SETTINGS_EXT_CAPACITY, extCapacity: 11, }) ).toEqual(updatedKeyworkerSettings) }) it('should handle SET_KEYWORKER_SETTINGS_SEQUENCE_FREQUENCY', () => { const updatedKeyworkerSettings = keyworkerSettingsInitialState updatedKeyworkerSettings.sequenceFrequency = 11 expect( keyworkerSettings(keyworkerSettingsInitialState, { type: types.SET_KEYWORKER_SETTINGS_SEQUENCE_FREQUENCY, sequenceFrequency: 11, }) ).toEqual(updatedKeyworkerSettings) }) it('should handle SET_KEYWORKER_SETTINGS_ALLOW_AUTO_ALLOCATION', () => { const updatedKeyworkerSettings = keyworkerSettingsInitialState updatedKeyworkerSettings.allowAuto = true expect( keyworkerSettings(keyworkerSettingsInitialState, { type: types.SET_KEYWORKER_SETTINGS_ALLOW_AUTO_ALLOCATION, allowAuto: true, }) ).toEqual(updatedKeyworkerSettings) }) it('should handle SET_KEYWORKER_SETTINGS_MIGRATED', () => { const updatedKeyworkerSettings = keyworkerSettingsInitialState updatedKeyworkerSettings.migrated = true expect( keyworkerSettings(keyworkerSettingsInitialState, { type: types.SET_KEYWORKER_SETTINGS_MIGRATED, migrated: true, }) ).toEqual(updatedKeyworkerSettings) }) it('should handle SET_KEYWORKER_SETTINGS_SUPPORTED', () => { const updatedKeyworkerSettings = keyworkerSettingsInitialState updatedKeyworkerSettings.supported = true expect( keyworkerSettings(keyworkerSettingsInitialState, { type: types.SET_KEYWORKER_SETTINGS_SUPPORTED, supported: true, }) ).toEqual(updatedKeyworkerSettings) }) it('should handle SET_KEYWORKER_SETTINGS', () => { const updatedKeyworkerSettings = keyworkerSettingsInitialState updatedKeyworkerSettings.supported = true updatedKeyworkerSettings.capacity = 1 updatedKeyworkerSettings.extCapacity = 2 updatedKeyworkerSettings.sequenceFrequency = 3 updatedKeyworkerSettings.allowAuto = true updatedKeyworkerSettings.migrated = true expect( keyworkerSettings(keyworkerSettingsInitialState, { type: types.SET_KEYWORKER_SETTINGS, supported: true, migrated: true, allowAuto: true, capacity: 1, extCapacity: 2, sequenceFrequency: 3, }) ).toEqual(updatedKeyworkerSettings) }) })
document.addEventListener('DOMContentLoaded', function () { var navbarToggles = Array.prototype.slice.call(document.querySelectorAll('.navbar-burger'), 0) if (navbarToggles.length === 0) return navbarToggles.forEach(function (el) { el.addEventListener('click', function (e) { e.stopPropagation() el.classList.toggle('is-active') document.getElementById(el.dataset.target).classList.toggle('is-active') document.documentElement.classList.toggle('is-clipped--navbar') }) }) var menuDropDowns = Array.prototype.slice.call(document.querySelectorAll('.has-dropdown'), 0) menuDropDowns.forEach(function (el) { el.addEventListener('click', function (e) { el.classList.toggle('is-active') }) }) })
/* global jQuery:false */ /* global CHARITY_IS_HOPE_STORAGE:false */ // Theme-specific first load actions //============================================== function charity_is_hope_theme_ready_actions() { "use strict"; // Put here your init code with theme-specific actions // It will be called before core actions } // Theme-specific scroll actions //============================================== function charity_is_hope_theme_scroll_actions() { "use strict"; // Put here your theme-specific code with scroll actions // It will be called when page is scrolled (before core actions) } // Theme-specific resize actions //============================================== function charity_is_hope_theme_resize_actions() { "use strict"; // Put here your theme-specific code with resize actions // It will be called when window is resized (before core actions) } // Theme-specific shortcodes init //===================================================== function charity_is_hope_theme_sc_init(cont) { "use strict"; // Put here your theme-specific code to init shortcodes // It will be called before core init shortcodes // @param cont - jQuery-container with shortcodes (init only inside this container) } // Theme-specific post-formats init //===================================================== function charity_is_hope_theme_init_post_formats() { "use strict"; // Put here your theme-specific code to init post-formats // It will be called before core init post_formats when page is loaded or after 'Load more' or 'Infinite scroll' actions // Tribe Events buttons decoration (add 'sc_button' class) jQuery('a.tribe-events-read-more,.tribe-events-button,.tribe-events-nav-previous a,.tribe-events-nav-next a,.tribe-events-widget-link a,.tribe-events-viewmore a') .addClass('sc_button sc_button_style_filled'); // All other buttons decoration (add 'hover' class) if (CHARITY_IS_HOPE_STORAGE['button_hover'] && CHARITY_IS_HOPE_STORAGE['button_hover']!='default') { jQuery('button:not(.search_submit):not([class*="sc_button_hover_"]),\ .sc_button:not(.sc_button_style_border):not([class*="sc_button_hover_"]),\ .woocommerce .button:not([class*="sc_button_hover_"]),.woocommerce-page .button:not([class*="sc_button_hover_"]),\ #buddypress a.button:not([class*="sc_button_hover_"])' ).addClass('sc_button_hover_'+CHARITY_IS_HOPE_STORAGE['button_hover']); if (CHARITY_IS_HOPE_STORAGE['button_hover']!='arrow') jQuery('input[type="submit"]:not([class*="sc_button_hover_"]),\ input[type="button"]:not([class*="sc_button_hover_"]),\ .isotope_filters_button,\ .scroll_to_top:not([class*="sc_button_hover_"]),\ .sc_slider_prev:not([class*="sc_button_hover_"]),.sc_slider_next:not([class*="sc_button_hover_"]),\ .tagcloud > a:not([class*="sc_button_hover_"])' ).addClass('sc_button_hover_'+CHARITY_IS_HOPE_STORAGE['button_hover']); } // All text fields decoration (except Calculated Fields Forms) //if (CHARITY_IS_HOPE_STORAGE['input_hover']) // jQuery('form:not([class*="cp_cff_"]):not([class*="sc_input_hover_"])').addClass('sc_input_hover_'+CHARITY_IS_HOPE_STORAGE['input_hover']); // Mark field as 'filled' on keypress jQuery('[class*="sc_input_hover_"] input, [class*="sc_input_hover_"] textarea').each(function() { if (jQuery(this).val()!='') jQuery(this).addClass('filled'); else jQuery(this).removeClass('filled'); }); jQuery('[class*="sc_input_hover_"] input, [class*="sc_input_hover_"] textarea').on('blur', function() { if (jQuery(this).val()!='') jQuery(this).addClass('filled'); else jQuery(this).removeClass('filled'); }); } // Theme-specific GoogleMap styles //===================================================== function charity_is_hope_theme_googlemap_styles($styles) { "use strict"; // Put here your theme-specific code to add GoogleMap styles // It will be called before GoogleMap init when page is loaded $styles['greyscale'] = [ { "stylers": [ { "saturation": -100 } ] } ]; $styles['inverse'] = [ { "stylers": [ { "invert_lightness": true }, { "visibility": "on" } ] } ]; $styles['simple'] = [ { stylers: [ { hue: "#00ffe6" }, { saturation: -20 } ] }, { featureType: "road", elementType: "geometry", stylers: [ { lightness: 100 }, { visibility: "simplified" } ] }, { featureType: "road", elementType: "labels", stylers: [ { visibility: "off" } ] } ]; $styles['apple'] = [ { "featureType": "landscape.man_made", "elementType": "geometry", "stylers": [ {"color":"#f7f1df"} ] }, { "featureType": "landscape.natural", "elementType": "geometry", "stylers": [ {"color":"#d0e3b4"} ] }, { "featureType": "landscape.natural.terrain", "elementType": "geometry", "stylers": [ {"visibility":"off"} ] }, { "featureType": "poi", "elementType": "labels", "stylers": [ {"visibility":"off"} ] }, { "featureType": "poi.business", "elementType": "all", "stylers": [ {"visibility":"off"} ] }, { "featureType": "poi.medical", "elementType": "geometry", "stylers": [ {"color":"#fbd3da"} ] }, { "featureType": "poi.park", "elementType": "geometry", "stylers": [ {"color":"#bde6ab"} ] }, { "featureType": "road", "elementType": "geometry.stroke", "stylers": [ {"visibility":"off"} ] }, { "featureType": "road", "elementType": "labels", "stylers": [ {"visibility":"off"} ] }, { "featureType": "road.highway", "elementType": "geometry.fill", "stylers": [ {"color":"#ffe15f"} ] }, { "featureType": "road.highway", "elementType":"geometry.stroke", "stylers": [ {"color":"#efd151"} ] }, { "featureType": "road.arterial", "elementType": "geometry.fill", "stylers": [ {"color":"#ffffff"} ] }, { "featureType": "road.local", "elementType": "geometry.fill", "stylers": [ {"color":"black"} ] }, { "featureType": "transit.station.airport", "elementType": "geometry.fill", "stylers": [ {"color":"#cfb2db"} ] }, { "featureType": "water", "elementType": "geometry", "stylers": [ {"color":"#a2daf2"} ] } ]; return $styles; }
var http = require('http'); var users = []; /** * 1. 客户端把一个用户信息发送给服务器 * 2. 服务器接收到后追加到users数组中 * 3. 服务器返回users数组,在客户端那里打印出来 */ /** * req 是一个可读流 ondata on end pipe * res 是一个可读可写流 ondta onend pipe write end */ http.createServer(function(req,res){ console.log(req.method);//方法 console.log(req.headers);//请求头 console.log(req.httpVersion);//HTTP版本号 console.log(req.url);//请求的URL req.setEncoding('utf8');//设置编码 var contentType = req.headers['content-type']; //每接收到数据都会触发data事件。 var result = ''; req.on('data',function(data){ result+=data; }) req.on('end',function(){ var user = ''; if(contentType =='application/json'){ user = JSON.parse(result); } else if(contentType =='application/x-www-form-urlencoded'){ //name=zfpx&age=6 user = require('querystring').parse(result); }else if(contentType =='application/zfpx'){ //name@zfpx|age@6 user = require('querystring').parse(result,'|','@'); } users.push(user); res.end(JSON.stringify(users)); console.log('ccc'); }); }).listen(8080);
from malaya.supervised import softmax from malaya.path import PATH_SENTIMENT, S3_PATH_SENTIMENT from herpetologist import check_type label = ['negative', 'positive'] _transformer_availability = { 'bert': { 'Size (MB)': 425.6, 'Quantized Size (MB)': 111, 'macro precision': 0.99330, 'macro recall': 0.99330, 'macro f1-score': 0.99329, }, 'tiny-bert': { 'Size (MB)': 57.4, 'Quantized Size (MB)': 15.4, 'macro precision': 0.98774, 'macro recall': 0.98774, 'macro f1-score': 0.98774, }, 'albert': { 'Size (MB)': 48.6, 'Quantized Size (MB)': 12.8, 'macro precision': 0.99227, 'macro recall': 0.99226, 'macro f1-score': 0.99226, }, 'tiny-albert': { 'Size (MB)': 22.4, 'Quantized Size (MB)': 5.98, 'macro precision': 0.98554, 'macro recall': 0.98550, 'macro f1-score': 0.98551, }, 'xlnet': { 'Size (MB)': 446.6, 'Quantized Size (MB)': 118, 'macro precision': 0.99353, 'macro recall': 0.99353, 'macro f1-score': 0.99353, }, 'alxlnet': { 'Size (MB)': 46.8, 'Quantized Size (MB)': 13.3, 'macro precision': 0.99188, 'macro recall': 0.99188, 'macro f1-score': 0.99188, }, } def available_transformer(): """ List available transformer sentiment analysis models. """ from malaya.function import describe_availability return describe_availability( _transformer_availability, text = 'tested on 20% test set.' ) def multinomial(**kwargs): """ Load multinomial sentiment model. Returns ------- result : malaya.model.ml.Bayes class """ return softmax.multinomial( PATH_SENTIMENT, S3_PATH_SENTIMENT, 'sentiment', label, **kwargs ) @check_type def transformer(model: str = 'bert', quantized: bool = False, **kwargs): """ Load Transformer sentiment model. Parameters ---------- model : str, optional (default='bert') Model architecture supported. Allowed values: * ``'bert'`` - Google BERT BASE parameters. * ``'tiny-bert'`` - Google BERT TINY parameters. * ``'albert'`` - Google ALBERT BASE parameters. * ``'tiny-albert'`` - Google ALBERT TINY parameters. * ``'xlnet'`` - Google XLNET BASE parameters. * ``'alxlnet'`` - Malaya ALXLNET BASE parameters. quantized : bool, optional (default=False) if True, will load 8-bit quantized model. Quantized model not necessary faster, totally depends on the machine. Returns ------- result: model List of model classes: * if `bert` in model, will return `malaya.model.bert.BinaryBERT`. * if `xlnet` in model, will return `malaya.model.xlnet.BinaryXLNET`. """ model = model.lower() if model not in _transformer_availability: raise ValueError( 'model not supported, please check supported models from `malaya.sentiment.available_transformer()`.' ) return softmax.transformer( class_name = 'sentiment', label = label, model = model, quantized = quantized, **kwargs )
import { inject as service } from '@ember/service'; import Route from '@ember/routing/route'; import ENV from '../../config/environment'; export default Route.extend({ featureService: service('feature-service'), queryParams: { 'q': {refreshModel: true} }, model (params) { let url = ENV.APP.domainServiceUrl; // 'https://services.arcgis.com/bkrWlSKcjUDFDtgw/arcgis/rest/services/sitedomains/FeatureServer/0'; let options = { includeGeometry: false, outFields: '*' }; // use the params to issue a search against this layer if (params.q && params.q !== '*') { options.where = encodeURI("domain='" + params.q + "'"); } else { options.where = encodeURI('1=1'); } return this.get('featureService').query(url, options); } });
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright (c) 2010 Citrix Systems, Inc. # Copyright 2010 OpenStack 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. """ Management class for VM-related functions (spawn, reboot, etc). """ import base64 import binascii import cPickle as pickle import functools import json import os import time import uuid from eventlet import greenthread from nova.compute import api as compute from nova.compute import power_state from nova.compute import task_states from nova.compute import vm_states from nova import context as nova_context from nova import db from nova import exception from nova import flags from nova import log as logging from nova.openstack.common import cfg from nova.openstack.common import importutils from nova import utils from nova.virt import driver from nova.virt.xenapi import firewall from nova.virt.xenapi import network_utils from nova.virt.xenapi import vm_utils from nova.virt.xenapi import volume_utils VolumeHelper = volume_utils.VolumeHelper NetworkHelper = network_utils.NetworkHelper VMHelper = vm_utils.VMHelper LOG = logging.getLogger(__name__) xenapi_vmops_opts = [ cfg.IntOpt('agent_version_timeout', default=300, help='number of seconds to wait for agent ' 'to be fully operational'), cfg.IntOpt('xenapi_running_timeout', default=60, help='number of seconds to wait for instance ' 'to go to running state'), cfg.StrOpt('xenapi_vif_driver', default='nova.virt.xenapi.vif.XenAPIBridgeDriver', help='The XenAPI VIF driver using XenServer Network APIs.'), cfg.BoolOpt('xenapi_generate_swap', default=False, help='Whether to generate swap ' '(False means fetching it from OVA)'), ] FLAGS = flags.FLAGS FLAGS.register_opts(xenapi_vmops_opts) flags.DECLARE('vncserver_proxyclient_address', 'nova.vnc') RESIZE_TOTAL_STEPS = 5 def cmp_version(a, b): """Compare two version strings (eg 0.0.1.10 > 0.0.1.9)""" a = a.split('.') b = b.split('.') # Compare each individual portion of both version strings for va, vb in zip(a, b): ret = int(va) - int(vb) if ret: return ret # Fallback to comparing length last return len(a) - len(b) def make_step_decorator(context, instance): """Factory to create a decorator that records instance progress as a series of discrete steps. Each time the decorator is invoked we bump the total-step-count, so after:: @step def step1(): ... @step def step2(): ... we have a total-step-count of 2. Each time the step-function (not the step-decorator!) is invoked, we bump the current-step-count by 1, so after:: step1() the current-step-count would be 1 giving a progress of ``1 / 2 * 100`` or 50%. """ instance_uuid = instance['uuid'] step_info = dict(total=0, current=0) def bump_progress(): step_info['current'] += 1 progress = round(float(step_info['current']) / step_info['total'] * 100) LOG.debug(_("Updating progress to %(progress)d"), locals(), instance=instance) db.instance_update(context, instance_uuid, {'progress': progress}) def step_decorator(f): step_info['total'] += 1 @functools.wraps(f) def inner(*args, **kwargs): rv = f(*args, **kwargs) bump_progress() return rv return inner return step_decorator class VMOps(object): """ Management class for VM-related tasks """ def __init__(self, session): self.XenAPI = session.get_imported_xenapi() self.compute_api = compute.API() self._session = session self.poll_rescue_last_ran = None if FLAGS.firewall_driver not in firewall.drivers: FLAGS.set_default('firewall_driver', firewall.drivers[0]) fw_class = importutils.import_class(FLAGS.firewall_driver) self.firewall_driver = fw_class(xenapi_session=self._session) vif_impl = importutils.import_class(FLAGS.xenapi_vif_driver) self.vif_driver = vif_impl(xenapi_session=self._session) def list_instances(self): """List VM instances.""" # TODO(justinsb): Should we just always use the details method? # Seems to be the same number of API calls.. name_labels = [] for vm_ref, vm_rec in VMHelper.list_vms(self._session): name_labels.append(vm_rec["name_label"]) return name_labels def list_instances_detail(self): """List VM instances, returning InstanceInfo objects.""" details = [] for vm_ref, vm_rec in VMHelper.list_vms(self._session): name = vm_rec["name_label"] # TODO(justinsb): This a roundabout way to map the state openstack_format = VMHelper.compile_info(vm_rec) state = openstack_format['state'] instance_info = driver.InstanceInfo(name, state) details.append(instance_info) return details def confirm_migration(self, migration, instance, network_info): name_label = self._get_orig_vm_name_label(instance) vm_ref = VMHelper.lookup(self._session, name_label) return self._destroy(instance, vm_ref, network_info) def finish_revert_migration(self, instance): # NOTE(sirp): the original vm was suffixed with '-orig'; find it using # the old suffix, remove the suffix, then power it back on. name_label = self._get_orig_vm_name_label(instance) vm_ref = VMHelper.lookup(self._session, name_label) # Remove the '-orig' suffix (which was added in case the resized VM # ends up on the source host, common during testing) name_label = instance.name VMHelper.set_vm_name_label(self._session, vm_ref, name_label) self._start(instance, vm_ref) def finish_migration(self, context, migration, instance, disk_info, network_info, image_meta, resize_instance): vdi_uuid = self._move_disks(instance, disk_info) if resize_instance: self._resize_instance(instance, vdi_uuid) vm_ref = self._create_vm(context, instance, [dict(vdi_type='root', vdi_uuid=vdi_uuid)], network_info, image_meta) # 5. Start VM self._start(instance, vm_ref=vm_ref) self._update_instance_progress(context, instance, step=5, total_steps=RESIZE_TOTAL_STEPS) def _start(self, instance, vm_ref=None): """Power on a VM instance""" vm_ref = vm_ref or self._get_vm_opaque_ref(instance) LOG.debug(_("Starting instance"), instance=instance) self._session.call_xenapi('VM.start_on', vm_ref, self._session.get_xenapi_host(), False, False) def _create_disks(self, context, instance, image_meta): disk_image_type = VMHelper.determine_disk_image_type(image_meta) vdis = VMHelper.create_image(context, self._session, instance, instance.image_ref, disk_image_type) for vdi in vdis: if vdi["vdi_type"] == "root": self._resize_instance(instance, vdi["vdi_uuid"]) return vdis def spawn(self, context, instance, image_meta, network_info): step = make_step_decorator(context, instance) @step def vanity_step(undo_mgr): # NOTE(sirp): _create_disk will potentially take a *very* long # time to complete since it has to fetch the image over the # network and images can be several gigs in size. To avoid # progress remaining at 0% for too long, which will appear to be # an error, we insert a "vanity" step to bump the progress up one # notch above 0. pass @step def create_disks_step(undo_mgr): vdis = self._create_disks(context, instance, image_meta) def undo_create_disks(): vdi_refs = [] for vdi in vdis: try: vdi_ref = self._session.call_xenapi( 'VDI.get_by_uuid', vdi['vdi_uuid']) except self.XenAPI.Failure: continue vdi_refs.append(vdi_ref) self._safe_destroy_vdis(vdi_refs) undo_mgr.undo_with(undo_create_disks) return vdis @step def create_kernel_ramdisk_step(undo_mgr): kernel_file = None ramdisk_file = None if instance.kernel_id: kernel = VMHelper.create_kernel_image(context, self._session, instance, instance.kernel_id, instance.user_id, instance.project_id, vm_utils.ImageType.KERNEL)[0] kernel_file = kernel.get('file') if instance.ramdisk_id: ramdisk = VMHelper.create_kernel_image(context, self._session, instance, instance.ramdisk_id, instance.user_id, instance.project_id, vm_utils.ImageType.RAMDISK)[0] ramdisk_file = ramdisk.get('file') def undo_create_kernel_ramdisk(): if kernel_file or ramdisk_file: LOG.debug(_("Removing kernel/ramdisk files from dom0"), instance=instance) self._destroy_kernel_ramdisk_plugin_call(kernel_file, ramdisk_file) undo_mgr.undo_with(undo_create_kernel_ramdisk) return kernel_file, ramdisk_file @step def create_vm_step(undo_mgr, vdis, kernel_file, ramdisk_file): vm_ref = self._create_vm(context, instance, vdis, network_info, image_meta, kernel_file=kernel_file, ramdisk_file=ramdisk_file) def undo_create_vm(): self._destroy(instance, vm_ref, network_info) undo_mgr.undo_with(undo_create_vm) return vm_ref @step def prepare_security_group_filters_step(undo_mgr): try: self.firewall_driver.setup_basic_filtering( instance, network_info) except NotImplementedError: # NOTE(salvatore-orlando): setup_basic_filtering might be # empty or not implemented at all, as basic filter could # be implemented with VIF rules created by xapi plugin pass self.firewall_driver.prepare_instance_filter(instance, network_info) @step def boot_instance_step(undo_mgr, vm_ref): self._boot_new_instance(instance, vm_ref) @step def apply_security_group_filters_step(undo_mgr): self.firewall_driver.apply_instance_filter(instance, network_info) undo_mgr = utils.UndoManager() try: vanity_step(undo_mgr) vdis = create_disks_step(undo_mgr) kernel_file, ramdisk_file = create_kernel_ramdisk_step(undo_mgr) vm_ref = create_vm_step(undo_mgr, vdis, kernel_file, ramdisk_file) prepare_security_group_filters_step(undo_mgr) boot_instance_step(undo_mgr, vm_ref) apply_security_group_filters_step(undo_mgr) except Exception: msg = _("Failed to spawn, rolling back") undo_mgr.rollback_and_reraise(msg=msg, instance=instance) def _generate_hostname(self, instance): """Generate the instance's hostname.""" hostname = instance["hostname"] if getattr(instance, "_rescue", False): hostname = "RESCUE-%s" % hostname return hostname def _create_vm(self, context, instance, vdis, network_info, image_meta, kernel_file=None, ramdisk_file=None): """Create VM instance.""" instance_name = instance.name vm_ref = VMHelper.lookup(self._session, instance_name) if vm_ref is not None: raise exception.InstanceExists(name=instance_name) # Ensure enough free memory is available if not VMHelper.ensure_free_mem(self._session, instance): raise exception.InsufficientFreeMemory(uuid=instance.uuid) disk_image_type = VMHelper.determine_disk_image_type(image_meta) # NOTE(jk0): Since vdi_type may contain either 'root' or 'swap', we # need to ensure that the 'swap' VDI is not chosen as the mount # point for file injection. first_vdi_ref = None for vdi in vdis: if vdi.get('vdi_type') != 'swap': # Create the VM ref and attach the first disk first_vdi_ref = self._session.call_xenapi( 'VDI.get_by_uuid', vdi['vdi_uuid']) vm_mode = instance.vm_mode and instance.vm_mode.lower() if vm_mode == 'pv': use_pv_kernel = True elif vm_mode in ('hv', 'hvm'): use_pv_kernel = False vm_mode = 'hvm' # Normalize else: use_pv_kernel = VMHelper.determine_is_pv(self._session, first_vdi_ref, disk_image_type, instance.os_type) vm_mode = use_pv_kernel and 'pv' or 'hvm' if instance.vm_mode != vm_mode: # Update database with normalized (or determined) value db.instance_update(nova_context.get_admin_context(), instance['id'], {'vm_mode': vm_mode}) vm_ref = VMHelper.create_vm( self._session, instance, kernel_file, ramdisk_file, use_pv_kernel) # Add disks to VM self._attach_disks(instance, disk_image_type, vm_ref, first_vdi_ref, vdis) # Alter the image before VM start for network injection. if FLAGS.flat_injected: VMHelper.preconfigure_instance(self._session, instance, first_vdi_ref, network_info) self._create_vifs(vm_ref, instance, network_info) self.inject_network_info(instance, network_info, vm_ref) hostname = self._generate_hostname(instance) self.inject_hostname(instance, vm_ref, hostname) return vm_ref def _attach_disks(self, instance, disk_image_type, vm_ref, first_vdi_ref, vdis): ctx = nova_context.get_admin_context() # device 0 reserved for RW disk userdevice = 0 # DISK_ISO needs two VBDs: the ISO disk and a blank RW disk if disk_image_type == vm_utils.ImageType.DISK_ISO: LOG.debug(_("Detected ISO image type, creating blank VM " "for install"), instance=instance) cd_vdi_ref = first_vdi_ref first_vdi_ref = VMHelper.fetch_blank_disk(self._session, instance.instance_type_id) VMHelper.create_vbd(self._session, vm_ref, first_vdi_ref, userdevice, bootable=False) # device 1 reserved for rescue disk and we've used '0' userdevice = 2 VMHelper.create_vbd(self._session, vm_ref, cd_vdi_ref, userdevice, vbd_type='CD', bootable=True) # set user device to next free value userdevice += 1 else: if instance.auto_disk_config: LOG.debug(_("Auto configuring disk, attempting to " "resize partition..."), instance=instance) instance_type = db.instance_type_get(ctx, instance.instance_type_id) VMHelper.auto_configure_disk(self._session, first_vdi_ref, instance_type['root_gb']) VMHelper.create_vbd(self._session, vm_ref, first_vdi_ref, userdevice, bootable=True) # set user device to next free value # userdevice 1 is reserved for rescue and we've used '0' userdevice = 2 instance_type = db.instance_type_get(ctx, instance.instance_type_id) swap_mb = instance_type['swap'] generate_swap = swap_mb and FLAGS.xenapi_generate_swap if generate_swap: VMHelper.generate_swap(self._session, instance, vm_ref, userdevice, swap_mb) userdevice += 1 ephemeral_gb = instance_type['ephemeral_gb'] if ephemeral_gb: VMHelper.generate_ephemeral(self._session, instance, vm_ref, userdevice, ephemeral_gb) userdevice += 1 # Attach any other disks for vdi in vdis[1:]: vdi_ref = self._session.call_xenapi('VDI.get_by_uuid', vdi['vdi_uuid']) if generate_swap and vdi['vdi_type'] == 'swap': # We won't be using it, so don't let it leak VMHelper.destroy_vdi(self._session, vdi_ref) continue VMHelper.create_vbd(self._session, vm_ref, vdi_ref, userdevice, bootable=False) userdevice += 1 def _boot_new_instance(self, instance, vm_ref): """Boot a new instance and configure it.""" LOG.debug(_('Starting VM'), instance=instance) self._start(instance, vm_ref) ctx = nova_context.get_admin_context() agent_build = db.agent_build_get_by_triple(ctx, 'xen', instance.os_type, instance.architecture) if agent_build: LOG.info(_('Latest agent build for %(hypervisor)s/%(os)s' '/%(architecture)s is %(version)s') % agent_build) else: LOG.info(_('No agent build found for %(hypervisor)s/%(os)s' '/%(architecture)s') % { 'hypervisor': 'xen', 'os': instance.os_type, 'architecture': instance.architecture}) # Wait for boot to finish LOG.debug(_('Waiting for instance state to become running'), instance=instance) expiration = time.time() + FLAGS.xenapi_running_timeout while time.time() < expiration: state = self.get_info(instance)['state'] if state == power_state.RUNNING: break greenthread.sleep(0.5) # Update agent, if necessary # This also waits until the agent starts LOG.debug(_("Querying agent version"), instance=instance) version = self._get_agent_version(instance) if version: LOG.info(_('Instance agent version: %s'), version, instance=instance) if (version and agent_build and cmp_version(version, agent_build['version']) < 0): LOG.info(_('Updating Agent to %s'), agent_build['version'], instance=instance) self._agent_update(instance, agent_build['url'], agent_build['md5hash']) # if the guest agent is not available, configure the # instance, but skip the admin password configuration no_agent = version is None # Inject files, if necessary injected_files = instance.injected_files if injected_files: # Check if this is a JSON-encoded string and convert if needed. if isinstance(injected_files, basestring): try: injected_files = json.loads(injected_files) except ValueError: LOG.exception(_("Invalid value for injected_files: %r"), injected_files, instance=instance) injected_files = [] # Inject any files, if specified for path, contents in instance.injected_files: LOG.debug(_("Injecting file path: '%s'") % path, instance=instance) self.inject_file(instance, path, contents) admin_password = instance.admin_pass # Set admin password, if necessary if admin_password and not no_agent: LOG.debug(_("Setting admin password"), instance=instance) self.set_admin_password(instance, admin_password) # Reset network config LOG.debug(_("Resetting network"), instance=instance) self.reset_network(instance, vm_ref) # Set VCPU weight inst_type = db.instance_type_get(ctx, instance.instance_type_id) vcpu_weight = inst_type['vcpu_weight'] if vcpu_weight is not None: LOG.debug(_("Setting VCPU weight"), instance=instance) self._session.call_xenapi('VM.add_to_VCPUs_params', vm_ref, 'weight', str(vcpu_weight)) def _get_vm_opaque_ref(self, instance): vm_ref = VMHelper.lookup(self._session, instance['name']) if vm_ref is None: raise exception.NotFound(_('Could not find VM with name %s') % instance['name']) return vm_ref def _acquire_bootlock(self, vm): """Prevent an instance from booting.""" self._session.call_xenapi( "VM.set_blocked_operations", vm, {"start": ""}) def _release_bootlock(self, vm): """Allow an instance to boot.""" self._session.call_xenapi( "VM.remove_from_blocked_operations", vm, "start") def snapshot(self, context, instance, image_id): """Create snapshot from a running VM instance. :param context: request context :param instance: instance to be snapshotted :param image_id: id of image to upload to Steps involved in a XenServer snapshot: 1. XAPI-Snapshot: Snapshotting the instance using XenAPI. This creates: Snapshot (Template) VM, Snapshot VBD, Snapshot VDI, Snapshot VHD 2. Wait-for-coalesce: The Snapshot VDI and Instance VDI both point to a 'base-copy' VDI. The base_copy is immutable and may be chained with other base_copies. If chained, the base_copies coalesce together, so, we must wait for this coalescing to occur to get a stable representation of the data on disk. 3. Push-to-glance: Once coalesced, we call a plugin on the XenServer that will bundle the VHDs together and then push the bundle into Glance. """ template_vm_ref = None try: _snapshot_info = self._create_snapshot(instance) template_vm_ref, template_vdi_uuids = _snapshot_info # call plugin to ship snapshot off to glance VMHelper.upload_image(context, self._session, instance, template_vdi_uuids, image_id) finally: if template_vm_ref: self._destroy(instance, template_vm_ref, destroy_kernel_ramdisk=False) LOG.debug(_("Finished snapshot and upload for VM"), instance=instance) def _create_snapshot(self, instance): #TODO(sirp): Add quiesce and VSS locking support when Windows support # is added LOG.debug(_("Starting snapshot for VM"), instance=instance) vm_ref = self._get_vm_opaque_ref(instance) label = "%s-snapshot" % instance.name try: template_vm_ref, template_vdi_uuids = VMHelper.create_snapshot( self._session, instance, vm_ref, label) return template_vm_ref, template_vdi_uuids except self.XenAPI.Failure, exc: LOG.error(_("Unable to Snapshot instance: %(exc)s"), locals(), instance=instance) raise def _migrate_vhd(self, instance, vdi_uuid, dest, sr_path): instance_uuid = instance['uuid'] params = {'host': dest, 'vdi_uuid': vdi_uuid, 'instance_uuid': instance_uuid, 'sr_path': sr_path} try: _params = {'params': pickle.dumps(params)} self._session.call_plugin('migration', 'transfer_vhd', _params) except self.XenAPI.Failure: msg = _("Failed to transfer vhd to new host") raise exception.MigrationError(reason=msg) def _get_orig_vm_name_label(self, instance): return instance.name + '-orig' def _update_instance_progress(self, context, instance, step, total_steps): """Update instance progress percent to reflect current step number """ # FIXME(sirp): for now we're taking a KISS approach to instance # progress: # Divide the action's workflow into discrete steps and "bump" the # instance's progress field as each step is completed. # # For a first cut this should be fine, however, for large VM images, # the _create_disks step begins to dominate the equation. A # better approximation would use the percentage of the VM image that # has been streamed to the destination host. progress = round(float(step) / total_steps * 100) instance_uuid = instance['uuid'] LOG.debug(_("Updating progress to %(progress)d"), locals(), instance=instance) db.instance_update(context, instance_uuid, {'progress': progress}) def migrate_disk_and_power_off(self, context, instance, dest, instance_type): """Copies a VHD from one host machine to another, possibly resizing filesystem before hand. :param instance: the instance that owns the VHD in question. :param dest: the destination host machine. :param disk_type: values are 'primary' or 'cow'. """ # 0. Zero out the progress to begin self._update_instance_progress(context, instance, step=0, total_steps=RESIZE_TOTAL_STEPS) vm_ref = self._get_vm_opaque_ref(instance) # The primary VDI becomes the COW after the snapshot, and we can # identify it via the VBD. The base copy is the parent_uuid returned # from the snapshot creation base_copy_uuid = cow_uuid = None template_vdi_uuids = template_vm_ref = None try: # 1. Create Snapshot _snapshot_info = self._create_snapshot(instance) template_vm_ref, template_vdi_uuids = _snapshot_info self._update_instance_progress(context, instance, step=1, total_steps=RESIZE_TOTAL_STEPS) base_copy_uuid = template_vdi_uuids['image'] _vdi_info = VMHelper.get_vdi_for_vm_safely(self._session, vm_ref) vdi_ref, vm_vdi_rec = _vdi_info cow_uuid = vm_vdi_rec['uuid'] sr_path = VMHelper.get_sr_path(self._session) if (instance['auto_disk_config'] and instance['root_gb'] > instance_type['root_gb']): # Resizing disk storage down old_gb = instance['root_gb'] new_gb = instance_type['root_gb'] LOG.debug(_("Resizing down VDI %(cow_uuid)s from " "%(old_gb)dGB to %(new_gb)dGB"), locals(), instance=instance) # 2. Power down the instance before resizing self._shutdown(instance, vm_ref, hard=False) self._update_instance_progress(context, instance, step=2, total_steps=RESIZE_TOTAL_STEPS) # 3. Copy VDI, resize partition and filesystem, forget VDI, # truncate VHD new_ref, new_uuid = VMHelper.resize_disk(self._session, instance, vdi_ref, instance_type) self._update_instance_progress(context, instance, step=3, total_steps=RESIZE_TOTAL_STEPS) # 4. Transfer the new VHD self._migrate_vhd(instance, new_uuid, dest, sr_path) self._update_instance_progress(context, instance, step=4, total_steps=RESIZE_TOTAL_STEPS) # Clean up VDI now that it's been copied VMHelper.destroy_vdi(self._session, new_ref) vdis = {'base_copy': new_uuid} else: # Resizing disk storage up, will be handled on destination # As an optimization, we transfer the base VDI first, # then shut down the VM, followed by transfering the COW # VDI. # 2. Transfer the base copy self._migrate_vhd(instance, base_copy_uuid, dest, sr_path) self._update_instance_progress(context, instance, step=2, total_steps=RESIZE_TOTAL_STEPS) # 3. Now power down the instance self._shutdown(instance, vm_ref, hard=False) self._update_instance_progress(context, instance, step=3, total_steps=RESIZE_TOTAL_STEPS) # 4. Transfer the COW VHD self._migrate_vhd(instance, cow_uuid, dest, sr_path) self._update_instance_progress(context, instance, step=4, total_steps=RESIZE_TOTAL_STEPS) # TODO(mdietz): we could also consider renaming these to # something sensible so we don't need to blindly pass # around dictionaries vdis = {'base_copy': base_copy_uuid, 'cow': cow_uuid} # NOTE(sirp): in case we're resizing to the same host (for dev # purposes), apply a suffix to name-label so the two VM records # extant until a confirm_resize don't collide. name_label = self._get_orig_vm_name_label(instance) VMHelper.set_vm_name_label(self._session, vm_ref, name_label) finally: if template_vm_ref: self._destroy(instance, template_vm_ref, destroy_kernel_ramdisk=False) return vdis def _move_disks(self, instance, disk_info): """Move and possibly link VHDs via the XAPI plugin.""" base_copy_uuid = disk_info['base_copy'] new_base_copy_uuid = str(uuid.uuid4()) params = {'instance_uuid': instance['uuid'], 'sr_path': VMHelper.get_sr_path(self._session), 'old_base_copy_uuid': base_copy_uuid, 'new_base_copy_uuid': new_base_copy_uuid} if 'cow' in disk_info: cow_uuid = disk_info['cow'] new_cow_uuid = str(uuid.uuid4()) params['old_cow_uuid'] = cow_uuid params['new_cow_uuid'] = new_cow_uuid new_uuid = new_cow_uuid else: new_uuid = new_base_copy_uuid self._session.call_plugin('migration', 'move_vhds_into_sr', {'params': pickle.dumps(params)}) # Now we rescan the SR so we find the VHDs VMHelper.scan_default_sr(self._session) # Set name-label so we can find if we need to clean up a failed # migration VMHelper.set_vdi_name(self._session, new_uuid, instance.name, 'root') return new_uuid def _resize_instance(self, instance, vdi_uuid): """Resize an instances root disk.""" new_disk_size = instance.root_gb * 1024 * 1024 * 1024 if not new_disk_size: return # Get current size of VDI vdi_ref = self._session.call_xenapi('VDI.get_by_uuid', vdi_uuid) virtual_size = self._session.call_xenapi('VDI.get_virtual_size', vdi_ref) virtual_size = int(virtual_size) old_gb = virtual_size / (1024 * 1024 * 1024) new_gb = instance.root_gb if virtual_size < new_disk_size: # Resize up. Simple VDI resize will do the trick LOG.debug(_("Resizing up VDI %(vdi_uuid)s from %(old_gb)dGB to " "%(new_gb)dGB"), locals(), instance=instance) if self._session.product_version[0] > 5: resize_func_name = 'VDI.resize' else: resize_func_name = 'VDI.resize_online' self._session.call_xenapi(resize_func_name, vdi_ref, str(new_disk_size)) LOG.debug(_("Resize complete"), instance=instance) def reboot(self, instance, reboot_type): """Reboot VM instance.""" # Note (salvatore-orlando): security group rules are not re-enforced # upon reboot, since this action on the XenAPI drivers does not # remove existing filters vm_ref = self._get_vm_opaque_ref(instance) if reboot_type == "HARD": self._session.call_xenapi('VM.hard_reboot', vm_ref) else: self._session.call_xenapi('VM.clean_reboot', vm_ref) def _get_agent_version(self, instance): """Get the version of the agent running on the VM instance.""" # The agent can be slow to start for a variety of reasons. On Windows, # it will generally perform a setup process on first boot that can # take a couple of minutes and then reboot. On Linux, the system can # also take a while to boot. So we need to be more patient than # normal as well as watch for domid changes def _call(): # Send the encrypted password resp = self._make_agent_call('version', instance) if resp['returncode'] != '0': LOG.error(_('Failed to query agent version: %(resp)r'), locals(), instance=instance) return None # Some old versions of the Windows agent have a trailing \\r\\n # (ie CRLF escaped) for some reason. Strip that off. return resp['message'].replace('\\r\\n', '') vm_ref = self._get_vm_opaque_ref(instance) vm_rec = self._session.call_xenapi("VM.get_record", vm_ref) domid = vm_rec['domid'] expiration = time.time() + FLAGS.agent_version_timeout while time.time() < expiration: ret = _call() if ret: return ret vm_rec = self._session.call_xenapi("VM.get_record", vm_ref) if vm_rec['domid'] != domid: newdomid = vm_rec['domid'] LOG.info(_('domid changed from %(domid)s to %(newdomid)s'), locals(), instance=instance) domid = vm_rec['domid'] return None def _agent_update(self, instance, url, md5sum): """Update agent on the VM instance.""" # Send the encrypted password args = {'url': url, 'md5sum': md5sum} resp = self._make_agent_call('agentupdate', instance, args) if resp['returncode'] != '0': LOG.error(_('Failed to update agent: %(resp)r'), locals(), instance=instance) return None return resp['message'] def set_admin_password(self, instance, new_pass): """Set the root/admin password on the VM instance. This is done via an agent running on the VM. Communication between nova and the agent is done via writing xenstore records. Since communication is done over the XenAPI RPC calls, we need to encrypt the password. We're using a simple Diffie-Hellman class instead of the more advanced one in M2Crypto for compatibility with the agent code. """ # The simple Diffie-Hellman class is used to manage key exchange. dh = SimpleDH() key_init_args = {'pub': str(dh.get_public())} resp = self._make_agent_call('key_init', instance, key_init_args) # Successful return code from key_init is 'D0' if resp['returncode'] != 'D0': msg = _('Failed to exchange keys: %(resp)r') % locals() LOG.error(msg, instance=instance) raise Exception(msg) # Some old versions of the Windows agent have a trailing \\r\\n # (ie CRLF escaped) for some reason. Strip that off. agent_pub = int(resp['message'].replace('\\r\\n', '')) dh.compute_shared(agent_pub) # Some old versions of Linux and Windows agent expect trailing \n # on password to work correctly. enc_pass = dh.encrypt(new_pass + '\n') # Send the encrypted password password_args = {'enc_pass': enc_pass} resp = self._make_agent_call('password', instance, password_args) # Successful return code from password is '0' if resp['returncode'] != '0': msg = _('Failed to update password: %(resp)r') % locals() LOG.error(msg, instance=instance) raise Exception(msg) return resp['message'] def inject_file(self, instance, path, contents): """Write a file to the VM instance. The path to which it is to be written and the contents of the file need to be supplied; both will be base64-encoded to prevent errors with non-ASCII characters being transmitted. If the agent does not support file injection, or the user has disabled it, a NotImplementedError will be raised. """ # Files/paths must be base64-encoded for transmission to agent b64_path = base64.b64encode(path) b64_contents = base64.b64encode(contents) # Need to uniquely identify this request. args = {'b64_path': b64_path, 'b64_contents': b64_contents} # If the agent doesn't support file injection, a NotImplementedError # will be raised with the appropriate message. resp = self._make_agent_call('inject_file', instance, args) if resp['returncode'] != '0': LOG.error(_('Failed to inject file: %(resp)r'), locals(), instance=instance) return None return resp['message'] def _shutdown(self, instance, vm_ref, hard=True): """Shutdown an instance.""" vm_rec = self._session.call_xenapi("VM.get_record", vm_ref) state = VMHelper.compile_info(vm_rec)['state'] if state == power_state.SHUTDOWN: LOG.warn(_("VM already halted, skipping shutdown..."), instance=instance) return LOG.debug(_("Shutting down VM"), instance=instance) try: if hard: self._session.call_xenapi('VM.hard_shutdown', vm_ref) else: self._session.call_xenapi('VM.clean_shutdown', vm_ref) except self.XenAPI.Failure, exc: LOG.exception(exc) def _find_root_vdi_ref(self, vm_ref): """Find and return the root vdi ref for a VM.""" if not vm_ref: return None vbd_refs = self._session.call_xenapi("VM.get_VBDs", vm_ref) if len(vbd_refs) == 0: raise Exception(_("Unable to find VBD for VM")) elif len(vbd_refs) == 1: # If we only have one VBD, assume it's the root fs vbd_ref = vbd_refs[0] else: # If we have more than one VBD, swap will be first by convention # with the root fs coming second vbd_ref = vbd_refs[1] return self._session.call_xenapi("VBD.get_record", vbd_ref)["VDI"] def _safe_destroy_vdis(self, vdi_refs): """Destroys the requested VDIs, logging any StorageError exceptions.""" for vdi_ref in vdi_refs: try: VMHelper.destroy_vdi(self._session, vdi_ref) except volume_utils.StorageError as exc: LOG.error(exc) def _destroy_kernel_ramdisk_plugin_call(self, kernel, ramdisk): args = {} if kernel: args['kernel-file'] = kernel if ramdisk: args['ramdisk-file'] = ramdisk self._session.call_plugin('glance', 'remove_kernel_ramdisk', args) def _destroy_kernel_ramdisk(self, instance, vm_ref): """Three situations can occur: 1. We have neither a ramdisk nor a kernel, in which case we are a RAW image and can omit this step 2. We have one or the other, in which case, we should flag as an error 3. We have both, in which case we safely remove both the kernel and the ramdisk. """ instance_uuid = instance['uuid'] if not instance.kernel_id and not instance.ramdisk_id: # 1. No kernel or ramdisk LOG.debug(_("Using RAW or VHD, skipping kernel and ramdisk " "deletion"), instance=instance) return if not (instance.kernel_id and instance.ramdisk_id): # 2. We only have kernel xor ramdisk raise exception.InstanceUnacceptable(instance_id=instance_uuid, reason=_("instance has a kernel or ramdisk but not both")) # 3. We have both kernel and ramdisk (kernel, ramdisk) = VMHelper.lookup_kernel_ramdisk(self._session, vm_ref) self._destroy_kernel_ramdisk_plugin_call(kernel, ramdisk) LOG.debug(_("kernel/ramdisk files removed"), instance=instance) def _destroy_vm(self, instance, vm_ref): """Destroys a VM record.""" try: self._session.call_xenapi('VM.destroy', vm_ref) except self.XenAPI.Failure, exc: LOG.exception(exc) return LOG.debug(_("VM destroyed"), instance=instance) def _destroy_rescue_instance(self, rescue_vm_ref, original_vm_ref): """Destroy a rescue instance.""" # Shutdown Rescue VM vm_rec = self._session.call_xenapi("VM.get_record", rescue_vm_ref) state = VMHelper.compile_info(vm_rec)['state'] if state != power_state.SHUTDOWN: self._session.call_xenapi("VM.hard_shutdown", rescue_vm_ref) # Destroy Rescue VDIs vdi_refs = VMHelper.lookup_vm_vdis(self._session, rescue_vm_ref) root_vdi_ref = self._find_root_vdi_ref(original_vm_ref) vdi_refs = [vdi_ref for vdi_ref in vdi_refs if vdi_ref != root_vdi_ref] self._safe_destroy_vdis(vdi_refs) # Destroy Rescue VM self._session.call_xenapi("VM.destroy", rescue_vm_ref) def destroy(self, instance, network_info): """Destroy VM instance. This is the method exposed by xenapi_conn.destroy(). The rest of the destroy_* methods are internal. """ LOG.info(_("Destroying VM"), instance=instance) # We don't use _get_vm_opaque_ref because the instance may # truly not exist because of a failure during build. A valid # vm_ref is checked correctly where necessary. vm_ref = VMHelper.lookup(self._session, instance['name']) rescue_vm_ref = VMHelper.lookup(self._session, "%s-rescue" % instance.name) if rescue_vm_ref: self._destroy_rescue_instance(rescue_vm_ref, vm_ref) return self._destroy(instance, vm_ref, network_info) def _destroy(self, instance, vm_ref, network_info=None, destroy_kernel_ramdisk=True): """Destroys VM instance by performing: 1. A shutdown 2. Destroying associated VDIs. 3. Destroying kernel and ramdisk files (if necessary). 4. Destroying that actual VM record. """ if vm_ref is None: LOG.warning(_("VM is not present, skipping destroy..."), instance=instance) return is_snapshot = VMHelper.is_snapshot(self._session, vm_ref) self._shutdown(instance, vm_ref) # Destroy VDIs vdi_refs = VMHelper.lookup_vm_vdis(self._session, vm_ref) self._safe_destroy_vdis(vdi_refs) if destroy_kernel_ramdisk: self._destroy_kernel_ramdisk(instance, vm_ref) self._destroy_vm(instance, vm_ref) self.unplug_vifs(instance, network_info) # Remove security groups filters for instance # Unless the vm is a snapshot if not is_snapshot: self.firewall_driver.unfilter_instance(instance, network_info=network_info) def pause(self, instance): """Pause VM instance.""" vm_ref = self._get_vm_opaque_ref(instance) self._session.call_xenapi('VM.pause', vm_ref) def unpause(self, instance): """Unpause VM instance.""" vm_ref = self._get_vm_opaque_ref(instance) self._session.call_xenapi('VM.unpause', vm_ref) def suspend(self, instance): """Suspend the specified instance.""" vm_ref = self._get_vm_opaque_ref(instance) self._session.call_xenapi('VM.suspend', vm_ref) def resume(self, instance): """Resume the specified instance.""" vm_ref = self._get_vm_opaque_ref(instance) self._session.call_xenapi('VM.resume', vm_ref, False, True) def rescue(self, context, instance, network_info, image_meta): """Rescue the specified instance. - shutdown the instance VM. - set 'bootlock' to prevent the instance from starting in rescue. - spawn a rescue VM (the vm name-label will be instance-N-rescue). """ rescue_vm_ref = VMHelper.lookup(self._session, "%s-rescue" % instance.name) if rescue_vm_ref: raise RuntimeError(_("Instance is already in Rescue Mode: %s") % instance.name) vm_ref = self._get_vm_opaque_ref(instance) self._shutdown(instance, vm_ref) self._acquire_bootlock(vm_ref) instance._rescue = True self.spawn(context, instance, image_meta, network_info) # instance.name now has -rescue appended because of magic rescue_vm_ref = VMHelper.lookup(self._session, instance.name) vdi_ref = self._find_root_vdi_ref(vm_ref) rescue_vbd_ref = VMHelper.create_vbd(self._session, rescue_vm_ref, vdi_ref, 1, bootable=False) self._session.call_xenapi('VBD.plug', rescue_vbd_ref) def unrescue(self, instance): """Unrescue the specified instance. - unplug the instance VM's disk from the rescue VM. - teardown the rescue VM. - release the bootlock to allow the instance VM to start. """ rescue_vm_ref = VMHelper.lookup(self._session, "%s-rescue" % instance.name) if not rescue_vm_ref: raise exception.InstanceNotInRescueMode(instance_id=instance.uuid) original_vm_ref = self._get_vm_opaque_ref(instance) instance._rescue = False self._destroy_rescue_instance(rescue_vm_ref, original_vm_ref) self._release_bootlock(original_vm_ref) self._start(instance, original_vm_ref) def power_off(self, instance): """Power off the specified instance.""" vm_ref = self._get_vm_opaque_ref(instance) self._shutdown(instance, vm_ref, hard=True) def power_on(self, instance): """Power on the specified instance.""" vm_ref = self._get_vm_opaque_ref(instance) self._start(instance, vm_ref) def _cancel_stale_tasks(self, timeout, task): """Cancel the given tasks that are older than the given timeout.""" task_refs = self._session.call_xenapi("task.get_by_name_label", task) for task_ref in task_refs: task_rec = self._session.call_xenapi("task.get_record", task_ref) task_created = utils.parse_strtime(task_rec["created"].value, "%Y%m%dT%H:%M:%SZ") if utils.is_older_than(task_created, timeout): self._session.call_xenapi("task.cancel", task_ref) def poll_rebooting_instances(self, timeout): """Look for expirable rebooting instances. - issue a "hard" reboot to any instance that has been stuck in a reboot state for >= the given timeout """ # NOTE(jk0): All existing clean_reboot tasks must be cancelled before # we can kick off the hard_reboot tasks. self._cancel_stale_tasks(timeout, 'VM.clean_reboot') ctxt = nova_context.get_admin_context() instances = db.instance_get_all_hung_in_rebooting(ctxt, timeout) instances_info = dict(instance_count=len(instances), timeout=timeout) if instances_info["instance_count"] > 0: LOG.info(_("Found %(instance_count)d hung reboots " "older than %(timeout)d seconds") % instances_info) for instance in instances: LOG.info(_("Automatically hard rebooting"), instance=instance) self.compute_api.reboot(ctxt, instance, "HARD") def poll_rescued_instances(self, timeout): """Look for expirable rescued instances. - forcibly exit rescue mode for any instances that have been in rescue mode for >= the provided timeout """ last_ran = self.poll_rescue_last_ran if not last_ran: # We need a base time to start tracking. self.poll_rescue_last_ran = utils.utcnow() return if not utils.is_older_than(last_ran, timeout): # Do not run. Let's bail. return # Update the time tracker and proceed. self.poll_rescue_last_ran = utils.utcnow() rescue_vms = [] for instance in self.list_instances(): if instance.endswith("-rescue"): rescue_vms.append(dict(name=instance, vm_ref=VMHelper.lookup(self._session, instance))) for vm in rescue_vms: rescue_vm_ref = vm["vm_ref"] original_name = vm["name"].split("-rescue", 1)[0] original_vm_ref = VMHelper.lookup(self._session, original_name) self._destroy_rescue_instance(rescue_vm_ref, original_vm_ref) self._release_bootlock(original_vm_ref) self._session.call_xenapi("VM.start", original_vm_ref, False, False) def get_info(self, instance): """Return data about VM instance.""" vm_ref = self._get_vm_opaque_ref(instance) vm_rec = self._session.call_xenapi("VM.get_record", vm_ref) return VMHelper.compile_info(vm_rec) def get_diagnostics(self, instance): """Return data about VM diagnostics.""" vm_ref = self._get_vm_opaque_ref(instance) vm_rec = self._session.call_xenapi("VM.get_record", vm_ref) return VMHelper.compile_diagnostics(vm_rec) def get_all_bw_usage(self, start_time, stop_time=None): """Return bandwidth usage info for each interface on each running VM""" try: metrics = VMHelper.compile_metrics(start_time, stop_time) except exception.CouldNotFetchMetrics: LOG.exception(_("Could not get bandwidth info.")) return {} bw = {} for uuid, data in metrics.iteritems(): vm_ref = self._session.call_xenapi("VM.get_by_uuid", uuid) vm_rec = self._session.call_xenapi("VM.get_record", vm_ref) vif_map = {} for vif in [self._session.call_xenapi("VIF.get_record", vrec) for vrec in vm_rec['VIFs']]: vif_map[vif['device']] = vif['MAC'] name = vm_rec['name_label'] if vm_rec["is_a_template"] or vm_rec["is_control_domain"]: continue vifs_bw = bw.setdefault(name, {}) for key, val in data.iteritems(): if key.startswith('vif_'): vname = key.split('_')[1] vif_bw = vifs_bw.setdefault(vif_map[vname], {}) if key.endswith('tx'): vif_bw['bw_out'] = int(val) if key.endswith('rx'): vif_bw['bw_in'] = int(val) return bw def get_console_output(self, instance): """Return snapshot of console.""" # TODO(armando-migliaccio): implement this to fix pylint! return 'FAKE CONSOLE OUTPUT of instance' def get_vnc_console(self, instance): """Return connection info for a vnc console.""" vm_ref = self._get_vm_opaque_ref(instance) session_id = self._session.get_session_id() path = "/console?ref=%s&session_id=%s" % (str(vm_ref), session_id) # NOTE: XS5.6sp2+ use http over port 80 for xenapi com return {'host': FLAGS.vncserver_proxyclient_address, 'port': 80, 'internal_access_path': path} def inject_network_info(self, instance, network_info, vm_ref=None): """ Generate the network info and make calls to place it into the xenstore and the xenstore param list. vm_ref can be passed in because it will sometimes be different than what VMHelper.lookup(session, instance.name) will find (ex: rescue) """ vm_ref = vm_ref or self._get_vm_opaque_ref(instance) LOG.debug(_("Injecting network info to xenstore"), instance=instance) for (network, info) in network_info: location = 'vm-data/networking/%s' % info['mac'].replace(':', '') self._add_to_param_xenstore(vm_ref, location, json.dumps(info)) try: self._write_to_xenstore(instance, location, info, vm_ref=vm_ref) except KeyError: # catch KeyError for domid if instance isn't running pass def _create_vifs(self, vm_ref, instance, network_info): """Creates vifs for an instance.""" LOG.debug(_("Creating vifs"), instance=instance) # this function raises if vm_ref is not a vm_opaque_ref self._session.call_xenapi("VM.get_record", vm_ref) for device, (network, info) in enumerate(network_info): vif_rec = self.vif_driver.plug(instance, network, info, vm_ref=vm_ref, device=device) network_ref = vif_rec['network'] LOG.debug(_('Creating VIF for network %(network_ref)s'), locals(), instance=instance) vif_ref = self._session.call_xenapi('VIF.create', vif_rec) LOG.debug(_('Created VIF %(vif_ref)s, network %(network_ref)s'), locals(), instance=instance) def plug_vifs(self, instance, network_info): """Set up VIF networking on the host.""" for device, (network, mapping) in enumerate(network_info): self.vif_driver.plug(instance, network, mapping, device=device) def unplug_vifs(self, instance, network_info): if network_info: for (network, mapping) in network_info: self.vif_driver.unplug(instance, network, mapping) def reset_network(self, instance, vm_ref=None): """Calls resetnetwork method in agent.""" self._make_agent_call('resetnetwork', instance, vm_ref=vm_ref) def inject_hostname(self, instance, vm_ref, hostname): """Inject the hostname of the instance into the xenstore.""" if instance.os_type == "windows": # NOTE(jk0): Windows hostnames can only be <= 15 chars. hostname = hostname[:15] LOG.debug(_("Injecting hostname to xenstore"), instance=instance) self._add_to_param_xenstore(vm_ref, 'vm-data/hostname', hostname) def _write_to_xenstore(self, instance, path, value, vm_ref=None): """ Writes the passed value to the xenstore record for the given VM at the specified location. A XenAPIPlugin.PluginError will be raised if any error is encountered in the write process. """ return self._make_plugin_call('xenstore.py', 'write_record', instance, vm_ref=vm_ref, path=path, value=json.dumps(value)) def _make_agent_call(self, method, instance, args=None, vm_ref=None): """Abstracts out the interaction with the agent xenapi plugin.""" if args is None: args = {} args['id'] = str(uuid.uuid4()) ret = self._make_plugin_call('agent', method, instance, vm_ref=vm_ref, **args) if isinstance(ret, dict): return ret try: return json.loads(ret) except TypeError: LOG.error(_('The agent call to %(method)s returned an invalid' ' response: %(ret)r. path=%(path)s; args=%(args)r'), locals(), instance=instance) return {'returncode': 'error', 'message': 'unable to deserialize response'} def _make_plugin_call(self, plugin, method, instance, vm_ref=None, **addl_args): """ Abstracts out the process of calling a method of a xenapi plugin. Any errors raised by the plugin will in turn raise a RuntimeError here. """ vm_ref = vm_ref or self._get_vm_opaque_ref(instance) vm_rec = self._session.call_xenapi("VM.get_record", vm_ref) args = {'dom_id': vm_rec['domid']} args.update(addl_args) try: return self._session.call_plugin(plugin, method, args) except self.XenAPI.Failure, e: err_msg = e.details[-1].splitlines()[-1] if 'TIMEOUT:' in err_msg: LOG.error(_('TIMEOUT: The call to %(method)s timed out. ' 'args=%(args)r'), locals(), instance=instance) return {'returncode': 'timeout', 'message': err_msg} elif 'NOT IMPLEMENTED:' in err_msg: LOG.error(_('NOT IMPLEMENTED: The call to %(method)s is not' ' supported by the agent. args=%(args)r'), locals(), instance=instance) return {'returncode': 'notimplemented', 'message': err_msg} else: LOG.error(_('The call to %(method)s returned an error: %(e)s. ' 'args=%(args)r'), locals(), instance=instance) return {'returncode': 'error', 'message': err_msg} return None def _add_to_param_xenstore(self, vm_ref, key, val): """ Takes a key/value pair and adds it to the xenstore parameter record for the given vm instance. If the key exists in xenstore, it is overwritten """ self._remove_from_param_xenstore(vm_ref, key) self._session.call_xenapi('VM.add_to_xenstore_data', vm_ref, key, val) def _remove_from_param_xenstore(self, vm_ref, key): """ Takes a single key and removes it from the xenstore parameter record data for the given VM. If the key doesn't exist, the request is ignored. """ self._session.call_xenapi('VM.remove_from_xenstore_data', vm_ref, key) def refresh_security_group_rules(self, security_group_id): """ recreates security group rules for every instance """ self.firewall_driver.refresh_security_group_rules(security_group_id) def refresh_security_group_members(self, security_group_id): """ recreates security group rules for every instance """ self.firewall_driver.refresh_security_group_members(security_group_id) def refresh_provider_fw_rules(self): self.firewall_driver.refresh_provider_fw_rules() def unfilter_instance(self, instance_ref, network_info): """Removes filters for each VIF of the specified instance.""" self.firewall_driver.unfilter_instance(instance_ref, network_info=network_info) class SimpleDH(object): """ This class wraps all the functionality needed to implement basic Diffie-Hellman-Merkle key exchange in Python. It features intelligent defaults for the prime and base numbers needed for the calculation, while allowing you to supply your own. It requires that the openssl binary be installed on the system on which this is run, as it uses that to handle the encryption and decryption. If openssl is not available, a RuntimeError will be raised. """ def __init__(self): self._prime = 162259276829213363391578010288127 self._base = 5 self._public = None self._shared = None self.generate_private() def generate_private(self): self._private = int(binascii.hexlify(os.urandom(10)), 16) return self._private def get_public(self): self._public = self.mod_exp(self._base, self._private, self._prime) return self._public def compute_shared(self, other): self._shared = self.mod_exp(other, self._private, self._prime) return self._shared @staticmethod def mod_exp(num, exp, mod): """Efficient implementation of (num ** exp) % mod""" result = 1 while exp > 0: if (exp & 1) == 1: result = (result * num) % mod exp = exp >> 1 num = (num * num) % mod return result def _run_ssl(self, text, decrypt=False): cmd = ['openssl', 'aes-128-cbc', '-A', '-a', '-pass', 'pass:%s' % self._shared, '-nosalt'] if decrypt: cmd.append('-d') out, err = utils.execute(*cmd, process_input=text) if err: raise RuntimeError(_('OpenSSL error: %s') % err) return out def encrypt(self, text): return self._run_ssl(text).strip('\n') def decrypt(self, text): return self._run_ssl(text, decrypt=True)
import Home from './pages/page1.vue'; const routes = [ { path: '/', name: 'home', component: Home, }, { path: '/page2', name: 'page2', component: () => import(/* webpackChunkName: "page2" */ './pages/page2.vue'), }, ] export default routes
const path = require('path'); const MicroService = require('../index.js'); MicroService.createServer({ port: 9001, ip: '127.0.0.1', useConsul: false, api_key: 'secret', postInterfacesDir: path.resolve(__dirname, './postInterface'), getInterfacesDir: path.resolve(__dirname, './getInterface'), DATA_BASE_PASSWORD: '123456' });
# Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the LICENSE file in # the root directory of this source tree. An additional grant of patent rights # can be found in the PATENTS file in the same directory. import itertools import math import numpy as np import torch from . import data_utils class CountingIterator(object): """Wrapper around an iterable that maintains the iteration count. Args: iterable (iterable): iterable to wrap Attributes: count (int): number of elements consumed from this iterator """ def __init__(self, iterable, start=0): self.iterable = iterable self.count = start self.itr = iter(self) self.len = start + len(iterable) def __len__(self): return self.len def __iter__(self): for x in self.iterable: self.count += 1 yield x def __next__(self): return next(self.itr) def has_next(self): """Whether the iterator has been exhausted.""" return self.count < len(self) def skip(self, num_to_skip): """Fast-forward the iterator by skipping *num_to_skip* elements.""" next(itertools.islice(self.itr, num_to_skip, num_to_skip), None) return self class EpochBatchIterator(object): """A multi-epoch iterator over a :class:`torch.utils.data.Dataset`. Compared to :class:`torch.utils.data.DataLoader`, this iterator: - can be reused across multiple epochs with the :func:`next_epoch_itr` method (optionally shuffled between epochs) - can be serialized/deserialized with the :func:`state_dict` and :func:`load_state_dict` methods - supports sharding with the *num_shards* and *shard_id* arguments Args: dataset (~torch.utils.data.Dataset): dataset from which to load the data collate_fn (callable): merges a list of samples to form a mini-batch batch_sampler (~torch.utils.data.Sampler): an iterator over batches of indices seed (int, optional): seed for random number generator for reproducibility (default: 1). num_shards (int, optional): shard the data iterator into N shards (default: 1). shard_id (int, optional): which shard of the data iterator to return (default: 0). num_workers (int, optional): how many subprocesses to use for data loading. 0 means the data will be loaded in the main process (default: 0). epoch (int, optional): the epoch to start the iterator from (default: 0). """ def __init__( self, dataset, collate_fn, batch_sampler, seed=1, num_shards=1, shard_id=0, num_workers=0, epoch=0, ): assert isinstance(dataset, torch.utils.data.Dataset) self.dataset = dataset self.collate_fn = collate_fn self.frozen_batches = tuple(batch_sampler) self.seed = seed self.num_shards = num_shards self.shard_id = shard_id self.num_workers = num_workers self.epoch = epoch self._cur_epoch_itr = None self._next_epoch_itr = None self._supports_prefetch = getattr(dataset, 'supports_prefetch', False) def __len__(self): return len(self.frozen_batches) def next_epoch_itr(self, shuffle=True, fix_batches_to_gpus=False): """Return a new iterator over the dataset. Args: shuffle (bool, optional): shuffle batches before returning the iterator (default: True). fix_batches_to_gpus: ensure that batches are always allocated to the same shards across epochs. Requires that :attr:`dataset` supports prefetching (default: False). """ if self._next_epoch_itr is not None: self._cur_epoch_itr = self._next_epoch_itr self._next_epoch_itr = None else: self.epoch += 1 self._cur_epoch_itr = self._get_iterator_for_epoch( self.epoch, shuffle, fix_batches_to_gpus=fix_batches_to_gpus, ) return self._cur_epoch_itr def end_of_epoch(self): """Returns whether the most recent epoch iterator has been exhausted""" return not self._cur_epoch_itr.has_next() @property def iterations_in_epoch(self): """The number of consumed batches in the current epoch.""" if self._cur_epoch_itr is not None: return self._cur_epoch_itr.count elif self._next_epoch_itr is not None: return self._next_epoch_itr.count return 0 def state_dict(self): """Returns a dictionary containing a whole state of the iterator.""" return { 'epoch': self.epoch, 'iterations_in_epoch': self.iterations_in_epoch, } def load_state_dict(self, state_dict): """Copies the state of the iterator from the given *state_dict*.""" self.epoch = state_dict['epoch'] itr_pos = state_dict.get('iterations_in_epoch', 0) if itr_pos > 0: # fast-forward epoch iterator self._next_epoch_itr = self._get_iterator_for_epoch( self.epoch, shuffle=state_dict.get('shuffle', True), offset=itr_pos, ) def _get_iterator_for_epoch(self, epoch, shuffle, fix_batches_to_gpus=False, offset=0): def shuffle_batches(batches, seed): # set seed based on the seed and epoch number so that we get # reproducible results when resuming from checkpoints with data_utils.numpy_seed(seed): np.random.shuffle(batches) return batches if self._supports_prefetch: batches = self.frozen_batches if shuffle and not fix_batches_to_gpus: batches = shuffle_batches(list(batches), self.seed + epoch) batches = list(ShardedIterator( batches, self.num_shards, self.shard_id, fill_value=[] )) self.dataset.prefetch([i for s in batches for i in s]) if shuffle and fix_batches_to_gpus: batches = shuffle_batches( batches, self.seed + epoch + self.shard_id) else: if shuffle: batches = shuffle_batches( list(self.frozen_batches), self.seed + epoch) else: batches = self.frozen_batches batches = list(ShardedIterator( batches, self.num_shards, self.shard_id, fill_value=[] )) if offset > 0 and offset >= len(batches): return None return CountingIterator( torch.utils.data.DataLoader( self.dataset, collate_fn=self.collate_fn, batch_sampler=batches[offset:], num_workers=self.num_workers, ), start=offset, ) class GroupedIterator(object): """Wrapper around an iterable that returns groups (chunks) of items. Args: iterable (iterable): iterable to wrap chunk_size (int): size of each chunk bottomless (bool): Restart when the iterator reaches its end (without throwing an error) """ def __init__(self, iterable, chunk_size, bottomless=False): self._len = int(math.ceil(len(iterable) / float(chunk_size))) self.offset = int( math.ceil(getattr(iterable, 'count', 0) / float(chunk_size))) self.iterable = iterable self.itr = iter(iterable) self.chunk_size = chunk_size self.bottomless = bottomless def __len__(self): return self._len def __iter__(self): return self def _build_chunk(self, chunk): for _ in range(self.chunk_size): chunk.append(next(self.itr)) def __next__(self): chunk = [] try: self._build_chunk(chunk) except StopIteration as e: if len(chunk) == 0: if self.bottomless: # For bottomless iterator just start over self.itr = iter(self.iterable) self._build_chunk(chunk) else: # Otherwise raise the exception raise e return chunk class ShardedIterator(object): """A sharded wrapper around an iterable, padded to length. Args: iterable (iterable): iterable to wrap num_shards (int): number of shards to split the iterable into shard_id (int): which shard to iterator over fill_value (Any, optional): padding value when the iterable doesn't evenly divide *num_shards* (default: None). """ def __init__(self, iterable, num_shards, shard_id, fill_value=None): if shard_id < 0 or shard_id >= num_shards: raise ValueError('shard_id must be between 0 and num_shards') self._sharded_len = len(iterable) // num_shards if len(iterable) % num_shards > 0: self._sharded_len += 1 self.itr = itertools.zip_longest( range(self._sharded_len), itertools.islice(iterable, shard_id, len(iterable), num_shards), fillvalue=fill_value, ) def __len__(self): return self._sharded_len def __iter__(self): return self def __next__(self): return next(self.itr)[1]
'use strict'; var path = require('path'), rootPath = path.normalize(__dirname + '/../..'); module.exports = { app: { title: 'pw', description: 'Full-Stack JavaScript with MongoDB, Express, AngularJS, and Node.js', keywords: 'MongoDB, Express, AngularJS, Node.js' }, root: rootPath, port: process.env.PORT || 80, templateEngine: 'swig', sessionSecret: 'pw', sessionCollection: 'sessions' };
console.log('oi teste'); function myFunction() { document.getElementById("teste").innerHTML = "Hello World"; }
/* * Copyright (c) 2018 Feng Liu * * 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. */ CKEDITOR.plugins.setLang("a11yhelp","oc",{title:"Instruccions d'accessibilitat",contents:"Contengut de l'ajuda. Per tampar aquesta fenèstra, quichatz sus la tòca Escap.",legend:[{name:"General",items:[{name:"Barra d'aisinas de l'editor",legend:"Quichar sus ${toolbarFocus} per accedir a la barra d'aisinas. Se desplaçar cap al groupe seguent o precedent de la barra d'aisinas amb las tòcas Tab e Maj+Tab. Se desplaçar cap al boton seguent o precedent de la barra d'aisinas amb las tòcas Sageta dreita e Sageta esquèrra. Quichar sus la barra d'espaci o la tòca Entrada per activer lo boton de barra d'aisinas."}, {name:"Fenèstra de l'editor",legend:"Dins una bóstia de dialòg, quichar sus Tab per passar a l'element seguent, quichar sus Maj+Tab per passar a l'element precedent, quichar sus Entrada per validar, quichar sus Escap per anullar. Quand una bóstia de dialòg possedís des onglets, la lista pòt èsser atenta amb Alt+F10 o amb Tab. Dins la lista dels onglets, se desplaçar cap al seguent e lo precedent amb las tòcas Sageta dreita e Sageta esquèrra respectivament."},{name:"Menú contextual de l'editor",legend:"Quichar sus ${contextMenu} o sus la tòca Menú per dobrir lo menú contextual. Se desplaçar ensuite cap a l'opcion seguenta del menú amb las tòcas Tab o Sageta bas. Se desplaçar cap a l'opcion precedenta amb las tòcas Maj+Tab o Sageta naut. Quichar sus la barra d'espaci o la tòca Entrada per seleccionar l'opcion del menu. Quichar sus la barra d'espaci, la tòca Entrada o Sageta dreita per dobrir lo sosmenú de l'opcion seleccionada. Tornar a l'element de menú parent amb la tòca Escap o Sageta esquèrra. Tampar lo menú contextual amb Escap."}, {name:"Zòna de lista de l'editor",legend:"Dins una lista en menú desenrotlant, se desplaçar cap a l'element seguent de la lista amb las tòcas Tab o Sageta bas. Se desplaçar cap a l'element precedent de la lista amb las tòcas Maj+Tab o Sageta naut. Quichar sus la barra d'espaci o sus Entrada per seleccionar l'opcion dins la lista. Quichar sus Escap per tampar lo menú desenrotlant."},{name:"Barra del camin d'elements de l'editor",legend:"Quichar sus ${elementsPathFocus} per naviguer cap a la barra del fial d'Ariana dels elements. Se desplaçar cap al boton de l'element seguent amb las tòcas Tab o Sageta dreita. Se desplaçar cap al boton precedent amb las tòcas Maj+Tab o Sageta esquèrra. Quichar sus la barra d'espaci o sus Entrada per seleccionar l'element dins l'editor."}]}, {name:"Comandas",items:[{name:"Anullar la comanda",legend:"Quichar sus ${undo}"},{name:"Comanda restablir",legend:"Quichar sus ${redo}"},{name:" Comanda gras",legend:"Quichar sus ${bold}"},{name:" Comanda italica",legend:"Quichar sus ${italic}"},{name:" Comanda solinhat",legend:"Quichar sus ${underline}"},{name:" Comanda ligam",legend:"Quichar sus ${link}"},{name:"Comanda enrotlar la barra d'aisinas",legend:"Quichar sus ${toolbarCollapse}"},{name:"Comanda d'accès a l'element seleccionable precedent", legend:"Quichar sus ${accessNextSpace} per accedir a l'element seleccionable inategnible lo mai pròche abans lo cursor, per exemple : doas linhas orizontalas adjacentas. Repetir la combinason de tòcas per aténher los elements seleccionables precedents."},{name:"Comanda d'accès a l'element seleccionable seguent",legend:"Quichar sus ${accessNextSpace} per accedir a l'element seleccionable inatenhible lo mai pròche aprèp lo cursor, per exemple : doas linhas orizontalas adjacentas. Repetir la combinason de tòcas per aténher los elements seleccionables seguents."}, {name:" Ajuda sus l'accessibilitat",legend:"Quichar sus ${a11yHelp}"}]}],tab:"Tabulacion",pause:"Pausa",capslock:"Verr. Maj.",escape:"Escap",pageUp:"Pagina superiora",pageDown:"Pagina seguenta",leftArrow:"Sageta esquèrra",upArrow:"Sageta naut",rightArrow:"Sageta dreita",downArrow:"Sageta bassa",insert:"Inser",leftWindowKey:"Tòca Windows esquèrra",rightWindowKey:"Tòca Windows dreita",selectKey:"Tòca Seleccionar",numpad0:"0 del pavat numeric",numpad1:"1 del pavat numeric",numpad2:"2 del pavat numeric", numpad3:"3 del pavat numeric",numpad4:"4 del pavat numeric",numpad5:"5 del pavat numeric",numpad6:"6 del pavat numeric",numpad7:"7 del pavat numeric",numpad8:"Pavat numeric 8",numpad9:"9 del pavat numeric",multiply:"Multiplicar",add:"Plus",subtract:"Mens",decimalPoint:"Punt decimal",divide:"Devesir",f1:"F1",f2:"F2",f3:"F3",f4:"F4",f5:"F5",f6:"F6",f7:"F7",f8:"F8",f9:"F9",f10:"F10",f11:"F11",f12:"F12",numLock:"Verr. Num.",scrollLock:"Arrèst desfil.",semiColon:"Punt-virgula",equalSign:"Signe egal",comma:"Virgula", dash:"Jonhent",period:"Punt",forwardSlash:"Barra oblica",graveAccent:"Accent grèu",openBracket:"Parentèsi dobèrta",backSlash:"Barra oblica invèrsa",closeBracket:"Parentèsi tampanta",singleQuote:"Apostròfa"});
// This file was procedurally generated from the following sources: // - src/dstr-binding/obj-ptrn-prop-id.case // - src/dstr-binding/default/cls-expr-gen-meth-static-dflt.template /*--- description: Binding as specified via property name and identifier (static class expression generator method (default parameter)) esid: sec-class-definitions-runtime-semantics-evaluation features: [generators, destructuring-binding, default-parameters] flags: [generated] info: | ClassExpression : class BindingIdentifieropt ClassTail 1. If BindingIdentifieropt is not present, let className be undefined. 2. Else, let className be StringValue of BindingIdentifier. 3. Let value be the result of ClassDefinitionEvaluation of ClassTail with argument className. [...] 14.5.14 Runtime Semantics: ClassDefinitionEvaluation 21. For each ClassElement m in order from methods a. If IsStatic of m is false, then b. Else, Let status be the result of performing PropertyDefinitionEvaluation for m with arguments F and false. [...] 14.4.13 Runtime Semantics: PropertyDefinitionEvaluation GeneratorMethod : * PropertyName ( StrictFormalParameters ) { GeneratorBody } 1. Let propKey be the result of evaluating PropertyName. 2. ReturnIfAbrupt(propKey). 3. If the function code for this GeneratorMethod is strict mode code, let strict be true. Otherwise let strict be false. 4. Let scope be the running execution context's LexicalEnvironment. 5. Let closure be GeneratorFunctionCreate(Method, StrictFormalParameters, GeneratorBody, scope, strict). 9.2.1 [[Call]] ( thisArgument, argumentsList) [...] 7. Let result be OrdinaryCallEvaluateBody(F, argumentsList). [...] 9.2.1.3 OrdinaryCallEvaluateBody ( F, argumentsList ) 1. Let status be FunctionDeclarationInstantiation(F, argumentsList). [...] 9.2.12 FunctionDeclarationInstantiation(func, argumentsList) [...] 23. Let iteratorRecord be Record {[[iterator]]: CreateListIterator(argumentsList), [[done]]: false}. 24. If hasDuplicates is true, then [...] 25. Else, b. Let formalStatus be IteratorBindingInitialization for formals with iteratorRecord and env as arguments. [...] 13.3.3.7 Runtime Semantics: KeyedBindingInitialization SingleNameBinding : BindingIdentifier Initializeropt [...] 8. Return InitializeReferencedBinding(lhs, v). ---*/ var callCount = 0; var C = class { static *method({ x: y } = { x: 23 }) { assert.sameValue(y, 23); assert.throws(ReferenceError, function() { x; }); callCount = callCount + 1; } }; C.method().next(); assert.sameValue(callCount, 1, 'method invoked exactly once');
import queryElement from 'shorter-js/src/misc/queryElement.js'; import addClass from 'shorter-js/src/class/addClass.js'; import removeClass from 'shorter-js/src/class/removeClass.js'; import reflow from 'shorter-js/src/misc/reflow.js'; import fadeClass from '../strings/fadeClass.js'; import showClass from '../strings/showClass.js'; import { resetScrollbar } from './scrollbar.js'; const modalBackdropClass = 'modal-backdrop'; const offcanvasBackdropClass = 'offcanvas-backdrop'; const modalActiveSelector = `.modal.${showClass}`; const offcanvasActiveSelector = `.offcanvas.${showClass}`; const overlay = document.createElement('div'); function getCurrentOpen() { return queryElement(`${modalActiveSelector},${offcanvasActiveSelector}`); } function toggleOverlayType(isModal) { const targetClass = isModal ? modalBackdropClass : offcanvasBackdropClass; [modalBackdropClass, offcanvasBackdropClass].forEach((c) => { removeClass(overlay, c); }); addClass(overlay, targetClass); } function appendOverlay(hasFade, isModal) { toggleOverlayType(isModal); document.body.appendChild(overlay); if (hasFade) addClass(overlay, fadeClass); } function showOverlay() { addClass(overlay, showClass); reflow(overlay); } function hideOverlay() { removeClass(overlay, showClass); } function removeOverlay() { const bd = document.body; const currentOpen = getCurrentOpen(); if (!currentOpen) { removeClass(overlay, fadeClass); bd.removeChild(overlay); resetScrollbar(); } } export { overlay, offcanvasBackdropClass, modalBackdropClass, modalActiveSelector, offcanvasActiveSelector, toggleOverlayType, appendOverlay, showOverlay, hideOverlay, getCurrentOpen, removeOverlay, };
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import {createCustomer } from '../actions/customersMySQL'; class UpdateCustomer extends Component { static propTypes = { Layout: PropTypes.func.isRequired, customer: PropTypes.shape({}).isRequired, match: PropTypes.shape({ params: PropTypes.shape({}) }), onFormSubmit: PropTypes.func.isRequired, }; static defaultProps = { match: null, } state = { error: null, success: null, loading: false, } onFormSubmit = (data) => { const { onFormSubmit } = this.props; this.setState({ loading: true }); return onFormSubmit(data) .then(()=> this.setState({ loading: false, success: 'Success - added new customer', error: null, })).catch(err => this.setState({ loading: false, success: null, error: err, })); } render = () => { const { error, loading, success } = this.state; const { Layout, match } = this.props; return ( <Layout error={error} loading={loading} success={success} onFormSubmit={this.onFormSubmit} /> ); } } const mapStateToProps = state => ({ customer: state.customer || {}, }); const mapDispatchToProps = { onFormSubmit: createCustomer, }; export default connect(mapStateToProps, mapDispatchToProps)(UpdateCustomer);
# Copyright (c) 2014 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Trace-viewer component model. This module implements trace-viewer's component model. """ from tvcm.generate import * # pylint: disable=wildcard-import from tvcm.project import Project
/** * External dependencies */ import tinycolor from 'tinycolor2'; /** * WordPress dependencies */ import { speak } from '@wordpress/a11y'; import { __ } from '@wordpress/i18n'; import { Notice } from '@wordpress/components'; import { useEffect } from '@wordpress/element'; function ContrastCheckerMessage( { tinyBackgroundColor, tinyTextColor, backgroundColor, textColor, } ) { const msg = tinyBackgroundColor.getBrightness() < tinyTextColor.getBrightness() ? __( 'This color combination may be hard for people to read. Try using a darker background color and/or a brighter text color.' ) : __( 'This color combination may be hard for people to read. Try using a brighter background color and/or a darker text color.' ); // Note: The `Notice` component can speak messages via its `spokenMessage` // prop, but the contrast checker requires granular control over when the // announcements are made. Notably, the message will be re-announced if a // new color combination is selected and the contrast is still insufficient. useEffect( () => { speak( __( 'This color combination may be hard for people to read.' ) ); }, [ backgroundColor, textColor ] ); return ( <div className="block-editor-contrast-checker"> <Notice spokenMessage={ null } status="warning" isDismissible={ false } > { msg } </Notice> </div> ); } function ContrastChecker( { backgroundColor, fallbackBackgroundColor, fallbackTextColor, fontSize, // font size value in pixels isLargeText, textColor, } ) { if ( ! ( backgroundColor || fallbackBackgroundColor ) || ! ( textColor || fallbackTextColor ) ) { return null; } const tinyBackgroundColor = tinycolor( backgroundColor || fallbackBackgroundColor ); const tinyTextColor = tinycolor( textColor || fallbackTextColor ); const hasTransparency = tinyBackgroundColor.getAlpha() !== 1 || tinyTextColor.getAlpha() !== 1; if ( hasTransparency || tinycolor.isReadable( tinyBackgroundColor, tinyTextColor, { level: 'AA', size: isLargeText || ( isLargeText !== false && fontSize >= 24 ) ? 'large' : 'small', } ) ) { return null; } return ( <ContrastCheckerMessage backgroundColor={ backgroundColor } textColor={ textColor } tinyBackgroundColor={ tinyBackgroundColor } tinyTextColor={ tinyTextColor } /> ); } export default ContrastChecker;
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); const react_1 = __importDefault(require("react")); const ReactComponent = props => (react_1.default.createElement("svg", Object.assign({ viewBox: "0 0 24 24", width: "1em", height: "1em" }, props), react_1.default.createElement("path", { fill: "none", d: "M0 0h24v24H0V0z" }), react_1.default.createElement("g", null, react_1.default.createElement("path", { d: "M6.4 9.2h.2c.77 0 1.4.63 1.4 1.4v7c0 .77-.63 1.4-1.4 1.4h-.2c-.77 0-1.4-.63-1.4-1.4v-7c0-.77.63-1.4 1.4-1.4zM12 5c.77 0 1.4.63 1.4 1.4v11.2c0 .77-.63 1.4-1.4 1.4-.77 0-1.4-.63-1.4-1.4V6.4c0-.77.63-1.4 1.4-1.4zm5.6 8c.77 0 1.4.63 1.4 1.4v3.2c0 .77-.63 1.4-1.4 1.4-.77 0-1.4-.63-1.4-1.4v-3.2c0-.77.63-1.4 1.4-1.4z" })))); exports.default = ReactComponent;
import { beforeEach, describe, expect, jest, test } from "@jest/globals"; import { AbilityCheckMessage, AbilitySaveMessage, AttackMessage, DamageMessage, DeathSaveMessage, SkillMessage, } from "../src/messages"; // fakes globalThis.renderTemplate = () => ""; globalThis.setProperty = (object, key, value) => { // split the key into parts, removing the last one const parts = key.split("."); const lastProp = parts.pop(); // recursively create objects out the key parts const lastObj = parts.reduce((obj, prop) => { if (!obj.hasOwnProperty(prop)) obj[prop] = {}; return obj[prop]; }, object); // set the value using the last key part lastObj[lastProp] = value; }; globalThis.TextEditor = { enrichHTML: (content, options) => content, }; function createActorWithEffects(...keyValuePairs) { const effects = keyValuePairs.map(createEffect); return { data: { data: { skills: { acr: { ability: "dex", }, ani: { ability: "wis", }, arc: { ability: "int", }, ath: { ability: "str", }, dec: { ability: "cha", }, his: { ability: "int", }, ins: { ability: "wis", }, itm: { ability: "cha", }, inv: { ability: "int", }, med: { ability: "wis", }, nat: { ability: "int", }, prc: { ability: "wis", }, prf: { ability: "cha", }, per: { ability: "cha", }, rel: { ability: "int", }, slt: { ability: "dex", }, ste: { ability: "dex", }, sur: { ability: "wis", }, }, }, }, effects, getRollData: () => {}, }; } function createEffect([key, value]) { return { isSuppressed: false, data: { changes: [ { key, value, mode: 0, priority: "0", }, ], disabled: false, }, }; } function createItem(actionType, abilityMod) { return { abilityMod, data: { data: { actionType, }, }, }; } describe("AttackMessage no legit active effects", () => { test("attack with no active effects should not add a message", async () => { const actor = createActorWithEffects(); const item = createItem("mwak", "str"); const options = {}; const messages = await new AttackMessage(actor, item).addMessage(options); expect(messages).toStrictEqual([]); expect(options.dialogOptions).toBeUndefined(); }); test("attack with a suppressed active effect should not add a message", async () => { const actor = createActorWithEffects([ "flags.adv-reminder.message.all", "some message", ]); actor.effects[0].isSuppressed = true; const item = createItem("mwak", "str"); const options = {}; const messages = await new AttackMessage(actor, item).addMessage(options); expect(messages).toStrictEqual([]); expect(options.dialogOptions).toBeUndefined(); }); test("attack with a disabled active effect should not add a message", async () => { const actor = createActorWithEffects([ "flags.adv-reminder.message.all", "some message", ]); actor.effects[0].data.disabled = true; const item = createItem("mwak", "str"); const options = {}; const messages = await new AttackMessage(actor, item).addMessage(options); expect(messages).toStrictEqual([]); expect(options.dialogOptions).toBeUndefined(); }); }); describe("AttackMessage message flags", () => { test("attack with message.all flag should add the message", async () => { const actor = createActorWithEffects([ "flags.adv-reminder.message.all", "message.all message", ]); const item = createItem("mwak", "str"); const options = {}; const messages = await new AttackMessage(actor, item).addMessage(options); expect(messages).toStrictEqual(["message.all message"]); expect(options.dialogOptions["adv-reminder"].message).toBe(""); }); test("attack with message.attack.all flag should add the message", async () => { const actor = createActorWithEffects([ "flags.adv-reminder.message.attack.all", "message.attack.all message", ]); const item = createItem("mwak", "str"); const options = {}; const messages = await new AttackMessage(actor, item).addMessage(options); expect(messages).toStrictEqual(["message.attack.all message"]); expect(options.dialogOptions["adv-reminder"].message).toBe(""); }); test("attack with message.attack.mwak flag should add the message for Melee Weapon Attack", async () => { const actor = createActorWithEffects([ "flags.adv-reminder.message.attack.mwak", "message.attack.mwak message", ]); const item = createItem("mwak", "str"); const options = {}; const messages = await new AttackMessage(actor, item).addMessage(options); expect(messages).toStrictEqual(["message.attack.mwak message"]); expect(options.dialogOptions["adv-reminder"].message).toBe(""); }); test("attack with message.attack.mwak flag should not add the message for Ranged Weapon Attack", async () => { const actor = createActorWithEffects([ "flags.adv-reminder.message.attack.mwak", "message.attack.mwak message", ]); const item = createItem("rwak", "dex"); const options = {}; const messages = await new AttackMessage(actor, item).addMessage(options); expect(messages).toStrictEqual([]); expect(options.dialogOptions).toBeUndefined(); }); test("attack with message.attack.cha flag should add the message for Charisma Attack", async () => { const actor = createActorWithEffects([ "flags.adv-reminder.message.attack.cha", "message.attack.cha message", ]); const item = createItem("rsak", "cha"); const options = {}; const messages = await new AttackMessage(actor, item).addMessage(options); expect(messages).toStrictEqual(["message.attack.cha message"]); expect(options.dialogOptions["adv-reminder"].message).toBe(""); }); test("attack with message.attack.cha flag should not add the message for Intelligence Attack", async () => { const actor = createActorWithEffects([ "flags.adv-reminder.message.attack.cha", "message.attack.cha", ]); const item = createItem("rsak", "int"); const options = {}; const messages = await new AttackMessage(actor, item).addMessage(options); expect(messages).toStrictEqual([]); expect(options.dialogOptions).toBeUndefined(); }); test("attack with two messages should add both messages", async () => { const actor = createActorWithEffects( ["flags.adv-reminder.message.attack.all", "first"], ["flags.adv-reminder.message.attack.mwak", "second"] ); const item = createItem("mwak", "str"); const options = {}; const messages = await new AttackMessage(actor, item).addMessage(options); expect(messages).toStrictEqual(["first", "second"]); expect(options.dialogOptions["adv-reminder"].message).toBe(""); }); }); describe("AbilityCheckMessage no legit active effects", () => { test("ability check with no active effects should not add a message", async () => { const actor = createActorWithEffects(); const options = {}; const messages = await new AbilityCheckMessage(actor, "int").addMessage( options ); expect(messages).toStrictEqual([]); expect(options.dialogOptions).toBeUndefined(); }); test("ability check with a suppressed active effect should not add a message", async () => { const actor = createActorWithEffects([ "flags.adv-reminder.message.all", "some message", ]); actor.effects[0].isSuppressed = true; const options = {}; const messages = await new AbilityCheckMessage(actor, "int").addMessage( options ); expect(messages).toStrictEqual([]); expect(options.dialogOptions).toBeUndefined(); }); test("ability check with a disabled active effect should not add a message", async () => { const actor = createActorWithEffects([ "flags.adv-reminder.message.all", "some message", ]); actor.effects[0].data.disabled = true; const options = {}; const messages = await new AbilityCheckMessage(actor, "int").addMessage( options ); expect(messages).toStrictEqual([]); expect(options.dialogOptions).toBeUndefined(); }); }); describe("AbilityCheckMessage message flags", () => { test("ability check with message.all flag should add the message", async () => { const actor = createActorWithEffects([ "flags.adv-reminder.message.all", "message.all message", ]); const options = {}; const messages = await new AbilityCheckMessage(actor, "int").addMessage( options ); expect(messages).toStrictEqual(["message.all message"]); expect(options.dialogOptions["adv-reminder"].message).toBe(""); }); test("ability check with message.ability.all flag should add the message", async () => { const actor = createActorWithEffects([ "flags.adv-reminder.message.ability.all", "message.ability.all message", ]); const options = {}; const messages = await new AbilityCheckMessage(actor, "int").addMessage( options ); expect(messages).toStrictEqual(["message.ability.all message"]); expect(options.dialogOptions["adv-reminder"].message).toBe(""); }); test("ability check with message.ability.check.all flag should add the message", async () => { const actor = createActorWithEffects([ "flags.adv-reminder.message.ability.check.all", "message.ability.check.all message", ]); const options = {}; const messages = await new AbilityCheckMessage(actor, "int").addMessage( options ); expect(messages).toStrictEqual(["message.ability.check.all message"]); expect(options.dialogOptions["adv-reminder"].message).toBe(""); }); test("ability check with message.ability.check.int flag should add the message for Intelligence Check", async () => { const actor = createActorWithEffects([ "flags.adv-reminder.message.ability.check.int", "message.ability.check.int message", ]); const options = {}; const messages = await new AbilityCheckMessage(actor, "int").addMessage( options ); expect(messages).toStrictEqual(["message.ability.check.int message"]); expect(options.dialogOptions["adv-reminder"].message).toBe(""); }); test("ability check with message.ability.check.int flag should not add the message for Dexterity Check", async () => { const actor = createActorWithEffects([ "flags.adv-reminder.message.ability.check.int", "message.ability.check.int", ]); const options = {}; const messages = await new AbilityCheckMessage(actor, "dex").addMessage( options ); expect(messages).toStrictEqual([]); expect(options.dialogOptions).toBeUndefined(); }); test("ability check with two messages should add both messages", async () => { const actor = createActorWithEffects( ["flags.adv-reminder.message.ability.check.all", "first"], ["flags.adv-reminder.message.ability.check.dex", "second"] ); const options = {}; const messages = await new AbilityCheckMessage(actor, "dex").addMessage( options ); expect(messages).toStrictEqual(["first", "second"]); expect(options.dialogOptions["adv-reminder"].message).toBe(""); }); }); describe("AbilitySaveMessage no legit active effects", () => { test("saving throw with no active effects should not add a message", async () => { const actor = createActorWithEffects(); const options = {}; const messages = await new AbilitySaveMessage(actor, "int").addMessage( options ); expect(messages).toStrictEqual([]); expect(options.dialogOptions).toBeUndefined(); }); test("saving throw with a suppressed active effect should not add a message", async () => { const actor = createActorWithEffects([ "flags.adv-reminder.message.all", "some message", ]); actor.effects[0].isSuppressed = true; const options = {}; const messages = await new AbilitySaveMessage(actor, "int").addMessage( options ); expect(messages).toStrictEqual([]); expect(options.dialogOptions).toBeUndefined(); }); test("saving throw with a disabled active effect should not add a message", async () => { const actor = createActorWithEffects([ "flags.adv-reminder.message.all", "some message", ]); actor.effects[0].data.disabled = true; const options = {}; const messages = await new AbilitySaveMessage(actor, "int").addMessage( options ); expect(messages).toStrictEqual([]); expect(options.dialogOptions).toBeUndefined(); }); }); describe("AbilitySaveMessage message flags", () => { test("saving throw with message.all flag should add the message", async () => { const actor = createActorWithEffects([ "flags.adv-reminder.message.all", "message.all message", ]); const options = {}; const messages = await new AbilitySaveMessage(actor, "int").addMessage( options ); expect(messages).toStrictEqual(["message.all message"]); expect(options.dialogOptions["adv-reminder"].message).toBe(""); }); test("saving throw with message.ability.all flag should add the message", async () => { const actor = createActorWithEffects([ "flags.adv-reminder.message.ability.all", "message.ability.all message", ]); const options = {}; const messages = await new AbilitySaveMessage(actor, "int").addMessage( options ); expect(messages).toStrictEqual(["message.ability.all message"]); expect(options.dialogOptions["adv-reminder"].message).toBe(""); }); test("saving throw with message.ability.save.all flag should add the message", async () => { const actor = createActorWithEffects([ "flags.adv-reminder.message.ability.save.all", "message.ability.save.all message", ]); const options = {}; const messages = await new AbilitySaveMessage(actor, "int").addMessage( options ); expect(messages).toStrictEqual(["message.ability.save.all message"]); expect(options.dialogOptions["adv-reminder"].message).toBe(""); }); test("saving throw with message.ability.save.int flag should add the message for Intelligence Check", async () => { const actor = createActorWithEffects([ "flags.adv-reminder.message.ability.save.int", "message.ability.save.int message", ]); const options = {}; const messages = await new AbilitySaveMessage(actor, "int").addMessage( options ); expect(messages).toStrictEqual(["message.ability.save.int message"]); expect(options.dialogOptions["adv-reminder"].message).toBe(""); }); test("saving throw with message.ability.save.int flag should not add the message for Dexterity Check", async () => { const actor = createActorWithEffects([ "flags.adv-reminder.message.ability.save.int", "message.ability.save.int", ]); const options = {}; const messages = await new AbilitySaveMessage(actor, "dex").addMessage( options ); expect(messages).toStrictEqual([]); expect(options.dialogOptions).toBeUndefined(); }); test("saving throw with two messages should add both messages", async () => { const actor = createActorWithEffects( ["flags.adv-reminder.message.ability.save.all", "first"], ["flags.adv-reminder.message.ability.save.dex", "second"] ); const options = {}; const messages = await new AbilitySaveMessage(actor, "dex").addMessage( options ); expect(messages).toStrictEqual(["first", "second"]); expect(options.dialogOptions["adv-reminder"].message).toBe(""); }); }); describe("SkillMessage no legit active effects", () => { test("skill check with no active effects should not add a message", async () => { const actor = createActorWithEffects(); const options = {}; const messages = await new SkillMessage(actor, "ath").addMessage(options); expect(messages).toStrictEqual([]); expect(options.dialogOptions).toBeUndefined(); }); test("skill check with a suppressed active effect should not add a message", async () => { const actor = createActorWithEffects([ "flags.adv-reminder.message.all", "some message", ]); actor.effects[0].isSuppressed = true; const options = {}; const messages = await new SkillMessage(actor, "ath").addMessage(options); expect(messages).toStrictEqual([]); expect(options.dialogOptions).toBeUndefined(); }); test("skill check with a disabled active effect should not add a message", async () => { const actor = createActorWithEffects([ "flags.adv-reminder.message.all", "some message", ]); actor.effects[0].data.disabled = true; const options = {}; const messages = await new SkillMessage(actor, "ath").addMessage(options); expect(messages).toStrictEqual([]); expect(options.dialogOptions).toBeUndefined(); }); }); describe("SkillMessage message flags", () => { test("skill check with message.all flag should add the message", async () => { const actor = createActorWithEffects([ "flags.adv-reminder.message.all", "message.all message", ]); const options = {}; const messages = await new SkillMessage(actor, "prc").addMessage(options); expect(messages).toStrictEqual(["message.all message"]); expect(options.dialogOptions["adv-reminder"].message).toBe(""); }); test("skill check with message.ability.all flag should add the message", async () => { const actor = createActorWithEffects([ "flags.adv-reminder.message.ability.all", "message.ability.all message", ]); const options = {}; const messages = await new SkillMessage(actor, "prc").addMessage(options); expect(messages).toStrictEqual(["message.ability.all message"]); expect(options.dialogOptions["adv-reminder"].message).toBe(""); }); test("skill check with message.ability.check.all flag should add the message", async () => { const actor = createActorWithEffects([ "flags.adv-reminder.message.ability.check.all", "message.ability.check.all message", ]); const options = {}; const messages = await new SkillMessage(actor, "prc").addMessage(options); expect(messages).toStrictEqual(["message.ability.check.all message"]); expect(options.dialogOptions["adv-reminder"].message).toBe(""); }); test("skill check with message.ability.check.wis flag should add the message for Perception Check", async () => { const actor = createActorWithEffects([ "flags.adv-reminder.message.ability.check.wis", "message.ability.check.int message", ]); const options = {}; const messages = await new SkillMessage(actor, "prc").addMessage(options); expect(messages).toStrictEqual(["message.ability.check.int message"]); expect(options.dialogOptions["adv-reminder"].message).toBe(""); }); test("skill check with message.ability.check.wis flag should not add the message for Acrobatics Check", async () => { const actor = createActorWithEffects([ "flags.adv-reminder.message.ability.check.wis", "message.ability.check.int", ]); const options = {}; const messages = await new SkillMessage(actor, "acr").addMessage(options); expect(messages).toStrictEqual([]); expect(options.dialogOptions).toBeUndefined(); }); test("skill check with message.skill.all flag should add the message", async () => { const actor = createActorWithEffects([ "flags.adv-reminder.message.skill.all", "message.skill.all message", ]); const options = {}; const messages = await new SkillMessage(actor, "prc").addMessage(options); expect(messages).toStrictEqual(["message.skill.all message"]); expect(options.dialogOptions["adv-reminder"].message).toBe(""); }); test("skill check with message.skill.prc flag should add the message for Perception Check", async () => { const actor = createActorWithEffects([ "flags.adv-reminder.message.skill.prc", "message.skill.prc message", ]); const options = {}; const messages = await new SkillMessage(actor, "prc").addMessage(options); expect(messages).toStrictEqual(["message.skill.prc message"]); expect(options.dialogOptions["adv-reminder"].message).toBe(""); }); test("skill check with message.skill.prc flag should not add the message for Nature Check", async () => { const actor = createActorWithEffects([ "flags.adv-reminder.message.skill.prc", "message.skill.prc message", ]); const options = {}; const messages = await new SkillMessage(actor, "nat").addMessage(options); expect(messages).toStrictEqual([]); expect(options.dialogOptions).toBeUndefined(); }); test("skill check with two messages should add both messages", async () => { const actor = createActorWithEffects( ["flags.adv-reminder.message.ability.check.dex", "first"], ["flags.adv-reminder.message.skill.ste", "second"] ); const options = {}; const messages = await new SkillMessage(actor, "ste").addMessage(options); expect(messages).toStrictEqual(["first", "second"]); expect(options.dialogOptions["adv-reminder"].message).toBe(""); }); }); describe("DeathSaveMessage no legit active effects", () => { test("death save with no active effects should not add a message", async () => { const actor = createActorWithEffects(); const options = {}; const messages = await new DeathSaveMessage(actor).addMessage(options); expect(messages).toStrictEqual([]); expect(options.dialogOptions).toBeUndefined(); }); test("death save with a suppressed active effect should not add a message", async () => { const actor = createActorWithEffects([ "flags.adv-reminder.message.all", "some message", ]); actor.effects[0].isSuppressed = true; const options = {}; const messages = await new DeathSaveMessage(actor).addMessage(options); expect(messages).toStrictEqual([]); expect(options.dialogOptions).toBeUndefined(); }); test("death save with a disabled active effect should not add a message", async () => { const actor = createActorWithEffects([ "flags.adv-reminder.message.all", "some message", ]); actor.effects[0].data.disabled = true; const options = {}; const messages = await new DeathSaveMessage(actor).addMessage(options); expect(messages).toStrictEqual([]); expect(options.dialogOptions).toBeUndefined(); }); }); describe("DeathSaveMessage message flags", () => { test("death save with message.all flag should add the message", async () => { const actor = createActorWithEffects([ "flags.adv-reminder.message.all", "message.all message", ]); const options = {}; const messages = await new DeathSaveMessage(actor).addMessage(options); expect(messages).toStrictEqual(["message.all message"]); expect(options.dialogOptions["adv-reminder"].message).toBe(""); }); test("death save with message.ability.all flag should add the message", async () => { const actor = createActorWithEffects([ "flags.adv-reminder.message.ability.all", "message.ability.all message", ]); const options = {}; const messages = await new DeathSaveMessage(actor).addMessage(options); expect(messages).toStrictEqual(["message.ability.all message"]); expect(options.dialogOptions["adv-reminder"].message).toBe(""); }); test("death save with message.ability.save.all flag should add the message", async () => { const actor = createActorWithEffects([ "flags.adv-reminder.message.ability.save.all", "message.ability.save.all message", ]); const options = {}; const messages = await new DeathSaveMessage(actor).addMessage(options); expect(messages).toStrictEqual(["message.ability.save.all message"]); expect(options.dialogOptions["adv-reminder"].message).toBe(""); }); test("death save with message.deathSave flag should add the message", async () => { const actor = createActorWithEffects([ "flags.adv-reminder.message.deathSave", "message.deathSave message", ]); const options = {}; const messages = await new DeathSaveMessage(actor).addMessage(options); expect(messages).toStrictEqual(["message.deathSave message"]); expect(options.dialogOptions["adv-reminder"].message).toBe(""); }); test("death save with two messages should add both messages", async () => { const actor = createActorWithEffects( ["flags.adv-reminder.message.ability.save.all", "first"], ["flags.adv-reminder.message.deathSave", "second"] ); const options = {}; const messages = await new DeathSaveMessage(actor).addMessage(options); expect(messages).toStrictEqual(["first", "second"]); expect(options.dialogOptions["adv-reminder"].message).toBe(""); }); }); describe("DamageMessage no legit active effects", () => { test("damage with no active effects should not add a message", async () => { const actor = createActorWithEffects(); const item = createItem("mwak", "str"); const options = {}; const messages = await new DamageMessage(actor, item).addMessage(options); expect(messages).toStrictEqual([]); expect(options.options?.dialogOptions).toBeUndefined(); }); test("damage with a suppressed active effect should not add a message", async () => { const actor = createActorWithEffects([ "flags.adv-reminder.message.all", "some message", ]); actor.effects[0].isSuppressed = true; const item = createItem("mwak", "str"); const options = {}; const messages = await new DamageMessage(actor, item).addMessage(options); expect(messages).toStrictEqual([]); expect(options.options?.dialogOptions).toBeUndefined(); }); test("damage with a disabled active effect should not add a message", async () => { const actor = createActorWithEffects([ "flags.adv-reminder.message.all", "some message", ]); actor.effects[0].data.disabled = true; const item = createItem("mwak", "str"); const options = {}; const messages = await new DamageMessage(actor, item).addMessage(options); expect(messages).toStrictEqual([]); expect(options.options?.dialogOptions).toBeUndefined(); }); }); describe("DamageMessage message flags", () => { test("damage with message.all flag should add the message", async () => { const actor = createActorWithEffects([ "flags.adv-reminder.message.all", "message.all message", ]); const item = createItem("mwak", "str"); const options = {}; const messages = await new DamageMessage(actor, item).addMessage(options); expect(messages).toStrictEqual(["message.all message"]); expect(options.options?.dialogOptions["adv-reminder"].message).toBe(""); }); test("damage with message.damage.all flag should add the message", async () => { const actor = createActorWithEffects([ "flags.adv-reminder.message.damage.all", "message.damage.all message", ]); const item = createItem("mwak", "str"); const options = {}; const messages = await new DamageMessage(actor, item).addMessage(options); expect(messages).toStrictEqual(["message.damage.all message"]); expect(options.options?.dialogOptions["adv-reminder"].message).toBe(""); }); test("damage with message.damage.mwak flag should add the message for Melee Weapon damage", async () => { const actor = createActorWithEffects([ "flags.adv-reminder.message.damage.mwak", "message.damage.mwak message", ]); const item = createItem("mwak", "str"); const options = {}; const messages = await new DamageMessage(actor, item).addMessage(options); expect(messages).toStrictEqual(["message.damage.mwak message"]); expect(options.options?.dialogOptions["adv-reminder"].message).toBe(""); }); test("damage with message.damage.mwak flag should not add the message for Ranged Weapon damage", async () => { const actor = createActorWithEffects([ "flags.adv-reminder.message.damage.mwak", "message.damage.mwak message", ]); const item = createItem("rwak", "dex"); const options = {}; const messages = await new DamageMessage(actor, item).addMessage(options); expect(messages).toStrictEqual([]); expect(options.options?.dialogOptions).toBeUndefined(); }); test("damage with two messages should add both messages", async () => { const actor = createActorWithEffects( ["flags.adv-reminder.message.damage.all", "first"], ["flags.adv-reminder.message.damage.mwak", "second"] ); const item = createItem("mwak", "str"); const options = {}; const messages = await new DamageMessage(actor, item).addMessage(options); expect(messages).toStrictEqual(["first", "second"]); expect(options.options?.dialogOptions["adv-reminder"].message).toBe(""); }); });
// This file was procedurally generated from the following sources: // - src/dstr-binding/ary-ptrn-elem-id-iter-step-err.case // - src/dstr-binding/error/arrow-function-dflt.template /*--- description: Error forwarding when IteratorStep returns an abrupt completion (arrow function expression (default parameter)) esid: sec-arrow-function-definitions-runtime-semantics-evaluation features: [Symbol.iterator, destructuring-binding, default-parameters] flags: [generated] info: | ArrowFunction : ArrowParameters => ConciseBody [...] 4. Let closure be FunctionCreate(Arrow, parameters, ConciseBody, scope, strict). [...] 9.2.1 [[Call]] ( thisArgument, argumentsList) [...] 7. Let result be OrdinaryCallEvaluateBody(F, argumentsList). [...] 9.2.1.3 OrdinaryCallEvaluateBody ( F, argumentsList ) 1. Let status be FunctionDeclarationInstantiation(F, argumentsList). [...] 9.2.12 FunctionDeclarationInstantiation(func, argumentsList) [...] 23. Let iteratorRecord be Record {[[iterator]]: CreateListIterator(argumentsList), [[done]]: false}. 24. If hasDuplicates is true, then [...] 25. Else, b. Let formalStatus be IteratorBindingInitialization for formals with iteratorRecord and env as arguments. [...] 13.3.3.6 Runtime Semantics: IteratorBindingInitialization SingleNameBinding : BindingIdentifier Initializeropt [...] 4. If iteratorRecord.[[done]] is false, then a. Let next be IteratorStep(iteratorRecord.[[iterator]]). b. If next is an abrupt completion, set iteratorRecord.[[done]] to true. c. ReturnIfAbrupt(next). ---*/ var g = {}; g[Symbol.iterator] = function() { return { next: function() { throw new Test262Error(); } }; }; var f = ([x] = g) => {}; assert.throws(Test262Error, function() { f(); });
/** @type {import('eslint').Linter.Config} */ module.exports = { root: true, extends: [ "eslint:recommended", "plugin:@typescript-eslint/recommended", "plugin:import/recommended", "plugin:import/typescript", "prettier/@typescript-eslint", "plugin:prettier/recommended", ], plugins: ["simple-import-sort"], env: { es6: true, node: true, jest: true, }, rules: { "@typescript-eslint/explicit-function-return-type": "off", "@typescript-eslint/no-empty-function": "off", "@typescript-eslint/no-use-before-define": "off", "@typescript-eslint/no-explicit-any": "off", "import/default": "off", "import/order": "off", "no-console": "off", "no-empty": ["error", { allowEmptyCatch: true }], "simple-import-sort/imports": "error", "simple-import-sort/exports": "error", "sort-imports": "off", }, overrides: [ { files: "*.js", rules: { "import/order": ["error", { "newlines-between": "always" }], "simple-import-sort/imports": "off", "simple-import-sort/exports": "off", }, }, ], };
import keras.backend as K import numpy as np import tensorflow as tf class Constr: def __init__(self, X, Y): self.X = X self.Y = Y self.mask = np.repeat(np.eye(X), Y).reshape(X, X, Y).swapaxes(2,0) self.mask = K.constant(self.mask) def __call__(self, tensor): return tensor * self.mask def get_config(self): return {"X": self.X, "Y": self.Y} def maximal_error(x, y): return K.max(K.abs(y - x)) def identity_loss(true, pred): return pred def l4_loss(true, pred): return K.mean(K.square(K.square(pred - true)), axis=-1) custom_objects = {"Constr": Constr, "maximal_error": maximal_error, "tf": tf, "identity_loss": identity_loss, "l4_loss": l4_loss}
/** * @author mrdoob / http://mrdoob.com/ * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Plane.as */ THREE.PlaneGeometry5 = function ( width, height, widthSegments, heightSegments ) { THREE.Geometry5.call( this, ( widthSegments * heightSegments ) * 2 * 3 ); var vertices = this.vertices; var normals = this.normals; var uvs = this.uvs; this.width = width; this.height = height; this.widthSegments = widthSegments || 1; this.heightSegments = heightSegments || 1; var widthHalf = width / 2; var heightHalf = height / 2; var gridX = this.widthSegments; var gridY = this.heightSegments; var segmentWidth = this.width / gridX; var segmentHeight = this.height / gridY; var offset = 0; for ( var iy = 0; iy < gridY; iy ++ ) { var y1 = iy * segmentHeight - heightHalf; var y2 = ( iy + 1 ) * segmentHeight - heightHalf; for ( var ix = 0; ix < gridX; ix ++ ) { var x1 = ix * segmentWidth - widthHalf; var x2 = ( ix + 1 ) * segmentWidth - widthHalf; vertices[ offset + 0 ].set( x1, y1, 0 ); vertices[ offset + 1 ].set( x2, y1, 0 ); vertices[ offset + 2 ].set( x1, y2, 0 ); normals[ offset + 0 ].z = 1; normals[ offset + 1 ].z = 1; normals[ offset + 2 ].z = 1; vertices[ offset + 3 ].set( x2, y1, 0 ); vertices[ offset + 4 ].set( x2, y2, 0 ); vertices[ offset + 5 ].set( x1, y2, 0 ); normals[ offset + 3 ].z = 1; normals[ offset + 4 ].z = 1; normals[ offset + 5 ].z = 1; offset += 6; } } }; THREE.PlaneGeometry5.prototype = Object.create( THREE.Geometry5.prototype );
import torch import torch.nn as nn import torchvision.models as models class EncoderCNN(nn.Module): def __init__(self, embed_size): super(EncoderCNN, self).__init__() resnet = models.resnet50(pretrained=True) for param in resnet.parameters(): param.requires_grad_(False) modules = list(resnet.children())[:-1] self.resnet = nn.Sequential(*modules) self.embed = nn.Linear(resnet.fc.in_features, embed_size) def forward(self, images): features = self.resnet(images) features = features.view(features.size(0), -1) features = self.embed(features) return features class DecoderRNN(nn.Module): def __init__(self, embed_size, hidden_size, vocab_size, num_layers=1): super().__init__() self.embed_size = embed_size self.hidden_size = hidden_size self.vocab_size = vocab_size self.num_layers = num_layers self.word_embeddings = nn.Embedding(vocab_size, embed_size) self.lstm = nn.LSTM(embed_size, hidden_size, num_layers, batch_first = True) self.hidden2out = nn.Linear(hidden_size, vocab_size) def forward(self, features, captions): captions = captions[:, :-1] batch_size = features.shape[0] self.hidden = (torch.zeros((1, batch_size, self.hidden_size), device='cuda'), torch.zeros((1, batch_size, self.hidden_size), device='cuda')) embeddings = self.word_embeddings(captions) embeddings = torch.cat((features.unsqueeze(1), embeddings), dim=1) out, self.hidden = self.lstm(embeddings, self.hidden) return self.hidden2out(out) def sample(self, inputs, states=None, max_len=20): " accepts pre-processed image tensor (inputs) and returns predicted sentence (list of tensor ids of length max_len) " output = [] batch_size = inputs.shape[0] hidden = (torch.zeros((1, batch_size, self.hidden_size), device='cuda'), torch.zeros((1, batch_size, self.hidden_size), device='cuda')) while True: lstm_out, hidden = self.lstm(inputs, hidden) outputs = self.hidden2out(lstm_out) outputs = outputs.squeeze(1) _, max_indice = torch.max(outputs, dim=1) output.append(max_indice.cpu().numpy()[0].item()) if (max_indice == 1): break inputs = self.word_embeddings(max_indice) inputs = inputs.unsqueeze(1) return output
// @flow import React from 'react'; import ModalBody from './ModalBody'; import ModalHeader from './ModalHeader'; import ModalWithFooter from './ModalWithFooter'; import { injectIntl, FormattedMessage } from 'react-intl'; import type {IntlShape} from 'react-intl'; import { ReactComponent as DeleteIcon } from './svg/Delete.svg'; import './ConfirmDeleteAllModal.scss'; type ConfirmDeleteAllModalProps = { intl: IntlShape, show: boolean, onCancel: () => void, onConfirm: () => void }; class ConfirmDeleteAllModal extends React.Component<ConfirmDeleteAllModalProps, {}> { render() { return ( <ModalWithFooter show={this.props.show} focusOnOpenSelector={'#ConformDeleteAllModal-confirm'} focusOnCloseSelector={'.ProgramBlockEditor__program-deleteAll-button'} ariaLabel={this.props.intl.formatMessage({ id: 'ConfirmDeleteAllModal.title' })} onClose={this.props.onCancel} buttonProperties={ [ {label: this.props.intl.formatMessage({id: 'ConfirmDeleteAllModal.cancelButton'}), onClick: this.props.onCancel}, {id: 'ConformDeleteAllModal-confirm', label: this.props.intl.formatMessage({id: 'ConfirmDeleteAllModal.confirmButton'}), onClick: this.props.onConfirm, isPrimary: true} ] }> <ModalHeader id='ConfirmDeleteAllModal' title={this.props.intl.formatMessage({ id: 'ConfirmDeleteAllModal.title' })}> <DeleteIcon aria-hidden='true' /> </ModalHeader> <ModalBody> <div className='ConfirmDeleteAllModal__content'> <FormattedMessage id='ConfirmDeleteAllModal.content' /> </div> </ModalBody> </ModalWithFooter> ); } } export default injectIntl(ConfirmDeleteAllModal);
import {} from "../src/browser"; test("adds 1 + 2 to equal 3", () => { expect(sum(1, 2)).toBe(3); });
import React from 'react'; /* eslint-disable max-len */ const texts = { title: 'Tidspunkt for dialogmøte', subTitle: 'De foreslåtte tidspunktene er passert', explanation: 'Du har tidligere mottatt en møteforespørsel med tidspunkter for et dialogmøte med NAV og din arbeidsgiver. Møteforespørselen er utdatert, og du kan se bort fra denne forespørselen. Er det fortsatt aktuelt med et møte, vil du få en ny forespørsel.', contactInfo: 'Har du spørsmål, kan du kontakte oss på 55 55 33 33', }; /* eslint-enable max-len */ const MotePassert = () => { return ( <div> <header className="sidetopp"> <h1 className="sidetopp__tittel">{texts.title}</h1> </header> <div className="panel"> <div className="illustrertTittel"> <img className="illustrertTittel__img" src={`${process.env.REACT_APP_CONTEXT_ROOT}/img/svg/mote_avbrutt.svg`} alt="" /> <h2 className="illustrertTittel__tittel">{texts.subTitle}</h2> </div> <p>{texts.explanation}</p> <div className="adskilt__blokk blokk"> <p>{texts.contactInfo}</p> </div> </div> </div> ); }; export default MotePassert;
(function () { 'use strict'; angular .module('fitappApp.dashboard') .controller('ActivityTrackersController', ActivityTrackersController); ActivityTrackersController.$inject = ['StravaDataservice', 'DataserviceTest']; function ActivityTrackersController(StravaDataservice, DataserviceTest) { var vm = this; vm.stravaActivationLink = ''; vm.code = ''; vm.activities = []; vm.getToken = getToken; vm.getActivities = getActivities; vm.activateStrava = activateStrava; vm.itemClass = itemClass; activate(); vm.tab = 1; function activate() { // StravaDataservice.getActivities().then(function (data) { // vm.activities = data; // }); StravaDataservice.getAuthorizationLink().then(function (data) { vm.stravaActivationLink = data; }); DataserviceTest.check().then(function (data) { console.log(data); }) } function getToken() { StravaDataservice.getToken(vm.code); } function activateStrava() { StravaDataservice.activateStrava() } function getActivities() { StravaDataservice.getActivities().then(function (data) { vm.activities = data; }); } function itemClass(activityType) { var styles = { STRAVA: "b-primary", GARMIN: "b-success" }; return styles[activityType]; } } })();
const { NetplanConfigurator, } = require("../classes/NetplanConfigurator/NetplanConfigurator"); const config = require("config"); let netplanConfigurator = null; module.exports.init = async () => { //Return imediately if initialized if (netplanConfigurator) return; let netplanDirPath = config.get("netplanDirPath"); let netplanFileName = config.get("netplanFileName"); let netplanApplyCommand = config.get("netplanApplyCommand"); netplanConfigurator = new NetplanConfigurator( netplanDirPath, netplanFileName, netplanApplyCommand ); await netplanConfigurator.Load(); }; module.exports.changeSettings = async (payload) => { if (netplanConfigurator === null) return {}; //Overriding file name and dir path payload.fileName = netplanConfigurator.FileName; payload.dirPath = netplanConfigurator.DirPath; netplanConfigurator.Update(payload); await netplanConfigurator.Save(); await netplanConfigurator.ApplyChanges(); return netplanConfigurator.Payload; }; module.exports.getSettings = async () => { if (netplanConfigurator === null) return {}; await netplanConfigurator.Load(); return netplanConfigurator.Payload; };
import Formidable from "formidable"; import Cloudinary from "../../lib/cloudinary"; import prismaClient from "../../lib/prisma-client"; import getSession from "../../lib/session"; export const config = { api: { bodyParser: false, }, }; export default async (req, res) => { if (req.method !== "POST") { return res.status(405).message({ error: "This method is not allowed." }); } const session = await getSession(req); if (session.error) { return res.status(401).json({ error: session.error }); } try { const data = await new Promise((resolve, reject) => { const form = new Formidable.IncomingForm({ keepExtensions: true }); form.parse(req, (error, fields, files) => { if (error) { return reject(error); } resolve({ fields, files }); }); }); const cloudinaryUpload = await Cloudinary.uploader.upload( data.files.imageFile.filepath, { public_id: `time-tracker-dashboard/${session.user.email.replace( "@", "_" )}`, overwrite: true, } ); await prismaClient.User.update({ where: { email: session.user.email }, data: { image: cloudinaryUpload.url }, }); return res.status(200).json({ message: "OK", image: { url: cloudinaryUpload.url, secureUrl: cloudinaryUpload.secure_url, }, }); } catch (err) { console.error(err); return res.status(500).json({ error: "Something went wrong.", }); } };
export const lock24 = "M19.5 10H19V7.5a6.5 6.5 0 0 0-13 0V10H4.5A1.504 1.504 0 0 0 3 11.5v11A1.504 1.504 0 0 0 4.5 24h15a1.504 1.504 0 0 0 1.5-1.5v-11a1.504 1.504 0 0 0-1.5-1.5zM7 7.5a5.5 5.5 0 0 1 11 0V10h-1V7.5a4.5 4.5 0 0 0-9 0V10H7zm9 2.5H9V7.5a3.5 3.5 0 0 1 7 0zm4 12.5a.506.506 0 0 1-.5.5h-15a.506.506 0 0 1-.5-.5v-11a.506.506 0 0 1 .5-.5h15a.506.506 0 0 1 .5.5zM11 15h1v1h1v1h-1v1h1v1h-1v1h-1zm1-1h1v1h-1z";
'use strict'; var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; /* global test, expect */ var _react = require('react'); var _react2 = _interopRequireDefault(_react); var _reactTestRenderer = require('react-test-renderer'); var _reactTestRenderer2 = _interopRequireDefault(_reactTestRenderer); var _color = require('../../helpers/color'); var _Twitter = require('./Twitter'); var _Twitter2 = _interopRequireDefault(_Twitter); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } test('Twitter renders correctly', function () { var tree = _reactTestRenderer2.default.create(_react2.default.createElement(_Twitter2.default, _color.red)).toJSON(); expect(tree).toMatchSnapshot(); }); test('Twitter `triangle="none"`', function () { var tree = _reactTestRenderer2.default.create(_react2.default.createElement(_Twitter2.default, _extends({}, _color.red, { triangle: 'none' }))).toJSON(); expect(tree).toMatchSnapshot(); }); test('Twitter `triangle="top-right"`', function () { var tree = _reactTestRenderer2.default.create(_react2.default.createElement(_Twitter2.default, _extends({}, _color.red, { triangle: 'top-right' }))).toJSON(); expect(tree).toMatchSnapshot(); });
function createEditor(elem) { var editor = ace.edit(elem); var session = editor.getSession(); editor.setTheme('ace/theme/tomorrow'); editor.setShowPrintMargin(false); editor.commands.removeCommands(['gotoline', 'find']); session.setMode('ace/mode/javascript'); session.setUseSoftTabs(true); session.setTabSize(2); session.setUseWorker(false); editor.setOption('scrollPastEnd', 0.33); elem.style.lineHeight = '18px'; return editor; } var optionsConfig = [ { type: "string", name: "mathRandomSeed", defaultVal: "", description: "If you want Prepack to evaluate Math.random() calls, please provide a seed." }, { type: "boolean", name: "inlineExpressions", defaultVal: true, description: "Avoids naming expressions when they are only used once, and instead inline them where they are used." }, { type: "boolean", name: "delayInitializations", defaultVal: false, description: "Delay initializations." }, { type: "choice", name: "compatibility", choices: ["browser", "jsc-600-1-4-17", "node-source-maps", "node-react"], defaultVal: "node-react", description: "The target environment for Prepack" }, { type: "string", name: "lazyObjectsRuntime", defaultVal: "", description: "Enable lazy objects feature and specify the JS runtime that supports this feature." }, { type: "choice", name: "invariantLevel", choices: [0, 1, 2, 3], defaultVal: 0, description: "Whether and how many checks to generate that validate Prepack's assumptions about the environment." }, { type: "boolean", name: "reactEnabled", defaultVal: true, description: "Enables support for React features, such as JSX syntax." }, { type: "choice", name: "reactOutput", choices: ["jsx", "create-element"], defaultVal: "jsx", description: "Specifies the serialization output of JSX nodes when React mode is enabled." }, { type: "boolean", name: "stripFlow", defaultVal: true, description: "Removes Flow type annotations from the output." }, ]; var demos = []; /**generate select */ function generateDemosSelect(obj, dom) { // var keys = ['<option value='+-1+'>select demo</option>']; var keys = []; demos = []; for (var name in obj) { demos.push(name); keys.push('<option value=' + name + '>' + name + '</option>'); } dom.innerHTML = keys.join(''); } var worker; var debounce; var messagesOutput = document.querySelector('.input .messages'); var replOutput = document.querySelector('.output .repl'); var isEmpty = /^\s*$/; function terminateWorker() { if (worker) { worker.terminate(); worker = null; } } function createWikiLink(code) { const wikiLink = document.createElement('a'); wikiLink.href = 'https://github.com/facebook/prepack/wiki/' + encodeURIComponent(code); wikiLink.text = code; wikiLink.setAttribute('target', '_blank'); return wikiLink; } function createLineLink(location) { const lineLink = document.createElement('a'); let lineNumber = location.start ? location.start.line : location.line; let colNumber = location.start ? location.start.column : location.column; colNumber++; let lineText = lineNumber + ':' + colNumber; lineLink.href = ''; lineLink.onclick = function() { input.gotoLine(lineNumber); return false; }; lineLink.text = lineText; lineLink.classList.add("line-link"); return lineLink; } function processMessage(messageNode, data) { // TODO: syntax errors need their location stripped if (data.location) { const wikiLink = createWikiLink(data.errorCode); const lineLink = createLineLink(data.location); messageNode.appendChild(wikiLink); messageNode.appendChild(document.createTextNode(' (')); messageNode.appendChild(lineLink); messageNode.appendChild(document.createTextNode('): ' + data.message + '\n')); } else if (!data.code) { messageNode.appendChild(document.createTextNode(data.message + '\n')); } else { const wikiLink = createWikiLink(data.errorCode); messageNode.appendChild(wikiLink); messageNode.appendChild(document.createTextNode(': ' + data.message + '\n')); } } function getMessageClassType(severity) { switch(severity) { case "FatalError": return "error"; case "RecoverableError": return "error"; case "Warning": return "warning"; case "Information": return "warning"; default: return "error"; } } function showMessages(messages) { messagesOutput.style.display = 'inline-block'; for (var i in messages) { const message = document.createElement('div'); message.classList.add("message", getMessageClassType(messages[i].severity)); processMessage(message, messages[i]); messagesOutput.appendChild(message); } } function getHashedDemo(hash) { if (hash[0] !== '#' || hash.length < 2) return null; var encoded = hash.slice(1); if (encoded.match(/^[a-zA-Z0-9+/=_-]+$/)) { return LZString.decompressFromEncodedURIComponent(encoded) } return null; } function makeDemoSharable() { var encoded = LZString.compressToEncodedURIComponent(input.getValue()); history.replaceState(undefined, undefined, `#${encoded}`); } function showGeneratedCode(code) { if (isEmpty.test(code) && !isEmpty.test(input.getValue())) { code = '// Your code was all dead code and thus eliminated.\n' + '// Try storing a property on the global object.'; } output.setValue(code, -1); } function showGenerationGraph(graph) { drawGraphCallback = () => { if (graph) { var graphData = JSON.parse(graph); var visData = { nodes: graphData.nodes, edges: graphData.edges, }; var visOptions = {}; var boxNetwork = new vis.Network(graphBox, visData, visOptions); } }; if (showGraphDiv) drawGraphCallback(); } function compile() { clearTimeout(debounce); terminateWorker(); messagesOutput.innerHTML = ''; messagesOutput.style.display = 'none'; replOutput.style.display = 'block'; output.setValue('// Compiling...', -1); debounce = setTimeout(function() { worker = new Worker('js/repl-worker.js'); worker.onmessage = function(e) { const result = e.data; if (result.type === 'success') { const { data, graph, messages } = result; showGeneratedCode(data); showGenerationGraph(graph); showMessages(messages); } else if (result.type === 'error') { const errors = result.data; showMessages(errors); output.setValue('// Prepack is unable to produce output for this input.\n// Please check the left pane for diagnostic information.', -1); } terminateWorker(); }; var options = {} for (var configIndex in optionsConfig) { var config = optionsConfig[configIndex]; var domE = document.querySelector("#prepack-option-" + config.name); if (config.type === "choice") { options[config.name] = domE.options[domE.selectedIndex].value; } else if (config.type === "boolean") { options[config.name] = (domE.checked === true); } else if (config.type === "string") { if (domE.value) { options[config.name] = domE.value; } } } worker.postMessage({code: input.getValue(), options: options}); }, 500); } var output = createEditor(replOutput); output.setReadOnly(true); output.setHighlightActiveLine(false); output.setHighlightGutterLine(false); var input = createEditor(document.querySelector('.input .repl')); input.on('change', compile); input.on('change', makeDemoSharable); /**record **/ var selectRecord = document.querySelector('select.select-record'); var optionsRecord = document.querySelector('#optionsMenuRecord'); var selectInput = document.querySelector('#recordName'); var optionsButton = document.querySelector('#optionsMenuButton'); var saveButton = document.querySelector('#saveBtn'); var deleteButton = document.querySelector('#deleteBtn'); var storage = window.localStorage; /** graph **/ var graphButton = document.querySelector('#graphBtn'); var graphBox = document.getElementById('graphBox'); var graphDiv = document.querySelector('#graph'); var inputDiv = document.getElementById('inputDiv'); var outputDiv = document.getElementById('outputDiv'); var showGraphDiv = false; var drawGraphCallback = null; function changeDemosSelect(val) { if (!val.value) return; selectInput.value = val.value; var localCache = getDemosCache(); var code = localCache[val.value] || ''; input.setValue(code); compile(); } var demoSelector = new Select({ el: selectRecord, className: 'select-theme-dark', }); demoSelector.on('change', changeDemosSelect); function getDemosCache() { return JSON.parse(storage.getItem('prepackDemos') || '{}'); } function setDemosCache(data) { storage.setItem('prepackDemos', JSON.stringify(data || {})); } function addDefaultExamples() { var cache = getDemosCache(); var code, name; name = 'EliminationOfAbstractionTax'; code = [ '(function () {', ' var self = this;', ' ["A", "B", 42].forEach(function(x) {', ' var name = "_" + x.toString()[0].toLowerCase();', ' var y = parseInt(x);', ' self[name] = y ? y : x;', ' });', '})();', ].join('\n'); cache[name] = code; name = 'EnvironmentInteractionsAndBranching'; code = [ '(function(){', ' function fib(x) { return x <= 1 ? x : fib(x - 1) + fib(x - 2); }', ' let x = Date.now();', ' if (x === 0) x = fib(10);', ' global.result = x;', '})();', ].join('\n'); cache[name] = code; name = 'Fibonacci'; code = [ '(function () {', ' function fibonacci(x) {', ' return x <= 1 ? x : fibonacci(x - 1) + fibonacci(x - 2);', ' }', ' global.x = fibonacci(10);', '})();', ].join('\n'); cache[name] = code; name = 'HelloWorld'; code = [ '(function () {', ' function hello() { return "hello"; }', ' function world() { return "world"; }', ' global.s = hello() + " " + world();', '})();', ].join('\n'); cache[name] = code; name = 'ModuleInitialization'; code = [ '(function () {', ' let moduleTable = {};', ' function define(id, f) { moduleTable[id] = f; }', ' function require(id) {', ' let x = moduleTable[id];', ' return x instanceof Function ? (moduleTable[id] = x()) : x;', ' }', ' global.require = require;', ' define("one", function() { return 1; });', ' define("two", function() { return require("one") + require("one"); });', ' define("three", function() { return require("two") + require("one"); });', ' define("four", function() { return require("three") + require("one"); });', '})();', 'three = require("three");' ].join('\n'); cache[name] = code; var hashedDemo = getHashedDemo(location.hash); name = null; if (hashedDemo) { name = createHashedDemoName(hashedDemo, cache); cache[name] = hashedDemo; } generateDemosSelect(cache, selectRecord); setDemosCache(cache); setTimeout(() => { demoSelector.change(name || 'Fibonacci'); }); } function createHashedDemoName(hashedDemo, cache) { var name = '\xa0'; for (var key in cache) { if (cache[key] === hashedDemo) { name = key; break; } } return name; } function addOptions() { var optionStrings = []; for (var configIndex in optionsConfig) { var config = optionsConfig[configIndex]; var configId = 'prepack-option-' + config.name; optionStrings.push("<div class='prepack-option'>"); optionStrings.push("<label class='prepack-option-label' for='"); optionStrings.push(configId); optionStrings.push("'>"); optionStrings.push(config.name); optionStrings.push("<div class='prepack-option-description'>"); optionStrings.push(config.description); optionStrings.push("</div>"); if (config.type === "choice") { optionStrings.push("<select id='"); optionStrings.push(configId); optionStrings.push("'>"); for (var nameIndex in config.choices) { var name = config.choices[nameIndex]; if (name === config.defaultVal) { optionStrings.push('<option value=' + name + ' selected>' + name + '</option>'); } else { optionStrings.push('<option value=' + name + '>' + name + '</option>'); } } optionStrings.push("</select>"); } else if (config.type === "boolean") { optionStrings.push("<input type='checkbox' id='"); optionStrings.push(configId); if (config.defaultVal === true) { optionStrings.push("' checked=true>") } else { optionStrings.push("'>"); } } else if (config.type === "string") { optionStrings.push("<input type='text' id='"); optionStrings.push(configId); if (config.defaultVal != null) { optionStrings.push("' value='"); optionStrings.push(config.defaultVal); optionStrings.push("'>"); } else { optionStrings.push("'>"); } } optionStrings.push("</label>"); optionStrings.push("</div>"); } optionsRecord.innerHTML = optionStrings.join(''); for (var configIndex in optionsConfig) { var config = optionsConfig[configIndex]; var domE = document.querySelector("#prepack-option-" + config.name); if (config.type === "choice") { var demoSelector = new Select({ el: domE, className: 'select-theme-dark', }); domE.addEventListener('change', compile); } else if (config.type === "boolean") { domE.addEventListener('change', compile); } else if (config.type === "string") { domE.addEventListener('input', compile); } } optionsButton.onclick = function() { if (optionsRecord.style.display !== "inline-block") { optionsRecord.style.display = "inline-block" ; } else { optionsRecord.style.display = "none" ; } }; } addDefaultExamples(); addOptions(); deleteButton.addEventListener('click', () => { var name = selectInput.value; if (name == null || name.replace(/\s+/, '') === '') return; if (demos.length === 0) { selectInput.value = ''; return; } var cache = getDemosCache(); delete cache[name]; input.setValue(''); generateDemosSelect(cache, selectRecord); setDemosCache(cache); if (demos.length > 0) { selectInput.value = demos[0]; setTimeout(() => { demoSelector.change(demos[0]); }); } else { selectInput.value = ''; input.setValue(defaultCode); compile(); } }); saveButton.addEventListener('click', () => { var name = selectInput.value; if (name == null || name.replace(/\s+/, '') === '') return; var code = input.getValue(); var cache = getDemosCache(); cache[name] = code; generateDemosSelect(cache, selectRecord); setDemosCache(cache); setTimeout(() => { demoSelector.change(name); }); }); graphButton.addEventListener('click', () => { if (!showGraphDiv) { inputDiv.style.width = "33%"; outputDiv.style.width = "33%"; graphDiv.style.width = "34%"; outputDiv.style.left = "33%"; graphDiv.style.display = "block"; showGraphDiv = true; graphButton.innerHTML = "HIDE HEAP"; if (drawGraphCallback !== null) { drawGraphCallback(); drawGraphCallback = null; } } else { inputDiv.style.width = "50%"; outputDiv.style.width = "50%"; graphDiv.style.width = "50%"; outputDiv.style.left = "50%"; graphDiv.style.display = "none"; showGraphDiv = false; graphButton.innerHTML = "SHOW HEAP"; } });
"use strict"; var __extends = (this && this.__extends) || (function () { var extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); Object.defineProperty(exports, "__esModule", { value: true }); var emoji_1 = require("./emoji"); var hard_break_1 = require("./hard-break"); var index_1 = require("./index"); var mention_1 = require("./mention"); var text_1 = require("./text"); var Paragraph = /** @class */ (function (_super) { __extends(Paragraph, _super); function Paragraph() { var _this = _super !== null && _super.apply(this, arguments) || this; _this.content = new index_1.ContentNode('paragraph'); return _this; } Paragraph.prototype.text = function (text, marks) { return this.add(new text_1.Text(text, marks)); }; Paragraph.prototype.code = function (text) { return this.add(text_1.code(text)); }; Paragraph.prototype.em = function (text) { return this.add(text_1.em(text)); }; Paragraph.prototype.link = function (text, href, title) { return this.add(text_1.link(text, href, title)); }; Paragraph.prototype.strong = function (text) { return this.add(text_1.strong(text)); }; Paragraph.prototype.mention = function (id, text) { return this.add(new mention_1.Mention(id, text)); }; Paragraph.prototype.emoji = function (shortName, id, text) { return this.add(new emoji_1.Emoji({ shortName: shortName, id: id, text: text })); }; Paragraph.prototype.hardBreak = function () { return this.add(new hard_break_1.HardBreak()); }; Paragraph.prototype.add = function (node) { this.content.add(node); return this; }; Paragraph.prototype.toJSON = function () { return this.content.toJSON(); }; return Paragraph; }(index_1.TopLevelNode)); exports.Paragraph = Paragraph; //# sourceMappingURL=paragraph.js.map
//// [tupleElementTypes1.ts] var [a, b]: [number, any] = [undefined, undefined]; //// [tupleElementTypes1.js] var _a = [undefined, undefined], a = _a[0], b = _a[1];
import logging.config from chat.settings_base import * TEMPLATE_DEBUG = False DEBUG = False DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', # django.db.backends.sqlite3 'NAME': 'pychat', 'USER': 'pychat', 'PASSWORD': 'pypass', 'HOST': 'localhost', 'default-character-set': 'utf8', 'OPTIONS': { 'autocommit': True, }, } } TEMPLATES[0]['OPTIONS']['loaders'] = [ ('django.template.loaders.cached.Loader', [ 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', ])] LOGGING['handlers'] = file_handlers file_handlers.update(mail_admins) LOGGING['loggers'] = { '': { 'handlers': ['default', 'mail_admins'], 'level': 'DEBUG', 'propagate': False, }, } logging.config.dictConfig(LOGGING)
import { stringify } from 'qs'; import config from '../config'; import { snakelize } from './snakelize'; export const makeURI = (pathname, query = {}, baseHost = null) => { // IE11 버그로 get 요청 캐싱 무마하기위해 t 시간값을 매 요청마다 추가 const _query = snakelize({ ...query, t: +new Date() }); const path = `${pathname}?${stringify(_query, { skipNulls: true })}`; if (baseHost) { return `${baseHost}${path}`; } return path; }; export const convertUriToAndroidIntentUri = (uri, packageName) => { // 앱 호출 URI를 안드로이드 intent를 이용해 호출할 수 있는 URI로 변환해주는 함수 const scheme = /(.+):\/\//.exec(uri)[1]; /* 줄바꿈시 공백이 들어가서 다운로드 URI 오류 발생 */ return `${uri.replace( `${scheme}://`, 'intent://', )}#Intent;scheme=${scheme};action=android.intent.action.VIEW;category=android.intent.category.BROWSABLE;package=${packageName};end`; }; export const makeLoginURI = (authorizeURI, clientId, redirectURI) => `${authorizeURI}?client_id=${clientId}&response_type=code&redirect_uri=${redirectURI}`; export const makeLibraryLoginURI = (libraryURI, next) => `${libraryURI}?next=${next}`; // 개발용 웹뷰어가 없기 때문에 도메인을 고정한다. export const makeWebViewerURI = (bookId, currentUri) => `https://view.ridibooks.com/books/${bookId}?referrer=${encodeURIComponent(currentUri)}`; export const makeRidiSelectUri = bookId => `${config.SELECT_BASE_URL}/book/${bookId}`; export const makeRidiStoreUri = bookId => `${config.STORE_API_BASE_URL}/v2/Detail?id=${bookId}`; export const makeLinkProps = (href, as, query) => { const _query = typeof query === 'object' ? snakelize(query) : null; const _href = { pathname: href, query: _query, }; if (typeof href === 'object') { _href.pathname = href.pathname; if (typeof href.query === 'object') { _href.query = { ...snakelize(href.query), ..._query }; } } const _as = { pathname: as, query: _query, }; if (typeof as === 'object') { _as.pathname = as.pathname; if (typeof as.query === 'object') { _as.query = { ...snakelize(as.query), ..._query }; } } return { href: _href, as: _as, }; };
import template from './sw-media-index.html.twig'; import './sw-media-index.scss'; const { Component, Context } = Shopware; Component.register('sw-media-index', { template, inject: ['repositoryFactory', 'mediaService', 'acl'], props: { routeFolderId: { type: String, default: null, }, fileAccept: { type: String, required: false, default: '*/*', }, }, data() { return { isLoading: false, selectedItems: [], uploads: [], term: this.$route.query ? this.$route.query.term : '', uploadTag: 'upload-tag-sw-media-index', parentFolder: null, currentFolder: null, }; }, metaInfo() { return { title: this.$createTitle(), }; }, computed: { mediaFolderRepository() { return this.repositoryFactory.create('media_folder'); }, mediaRepository() { return this.repositoryFactory.create('media'); }, rootFolder() { const root = this.mediaFolderRepository.create(Context.api); root.name = this.$tc('sw-media.index.rootFolderName'); root.id = null; return root; }, }, watch: { routeFolderId() { this.updateFolder(); }, }, created() { this.createdComponent(); }, destroyed() { this.destroyedComponent(); }, methods: { createdComponent() { this.updateFolder(); }, async updateFolder() { if (!this.routeFolderId) { this.currentFolder = this.rootFolder; this.parentFolder = null; } else { this.currentFolder = await this.mediaFolderRepository.get(this.routeFolderId, Context.api); if (this.currentFolder && this.currentFolder.parentId) { this.parentFolder = await this.mediaFolderRepository.get(this.currentFolder.parentId, Context.api); } else { this.parentFolder = this.rootFolder; } } }, destroyedComponent() { this.$root.$off('search', this.onSearch); }, async onUploadsAdded() { await this.mediaService.runUploads(this.uploadTag); this.reloadList(); }, onUploadFinished({ targetId }) { this.uploads = this.uploads.filter((upload) => { return upload.id !== targetId; }); }, onUploadFailed({ targetId }) { this.uploads = this.uploads.filter((upload) => { return targetId !== upload.id; }); }, onChangeLanguage() { this.clearSelection(); }, onSearch(value) { this.term = value; this.clearSelection(); }, onItemsDeleted(ids) { this.onMediaFoldersDissolved(ids.folderIds); }, onMediaFoldersDissolved(ids) { this.clearSelection(); if (ids.includes(this.routeFolderId)) { let routeId = null; if (this.parentFolder) { routeId = this.parentFolder.id; } this.$router.push({ name: 'sw.media.index', params: { folderId: routeId, }, }); return; } this.reloadList(); }, reloadList() { this.$refs.mediaLibrary.refreshList(); }, clearSelection() { this.selectedItems.splice(0, this.selectedItems.length); }, onMediaUnselect({ item }) { const index = this.selectedItems.findIndex((selected) => { return selected === item; }); if (index > -1) { this.selectedItems.splice(index, 1); } }, updateRoute(newFolderId) { this.term = this.$route.query ? this.$route.query.term : ''; this.$router.push({ name: 'sw.media.index', params: { folderId: newFolderId, }, }); }, }, });