From fb827cd0a003b7bf9219f6b2f198c4488351fcb2 Mon Sep 17 00:00:00 2001 From: Igor Date: Wed, 22 Nov 2017 18:03:00 +0300 Subject: [PATCH] 17.11.2 --- build/index.html | 2 +- .../{app-ed924b138a.js => app-233be179d0.js} | 14 ++-- build/scripts/app-dd32b69813.js | 79 ------------------- build/scripts/app.js | 21 ++--- 4 files changed, 19 insertions(+), 97 deletions(-) rename build/scripts/{app-ed924b138a.js => app-233be179d0.js} (72%) delete mode 100644 build/scripts/app-dd32b69813.js diff --git a/build/index.html b/build/index.html index 3d494c1c..e6099bc4 100644 --- a/build/index.html +++ b/build/index.html @@ -1,3 +1,3 @@ Tabix.io
\ No newline at end of file +
\ No newline at end of file diff --git a/build/scripts/app-ed924b138a.js b/build/scripts/app-233be179d0.js similarity index 72% rename from build/scripts/app-ed924b138a.js rename to build/scripts/app-233be179d0.js index c0ed1c73..fc6cfc7f 100644 --- a/build/scripts/app-ed924b138a.js +++ b/build/scripts/app-233be179d0.js @@ -1,11 +1,11 @@ "use strict";function _toConsumableArray(e){if(Array.isArray(e)){for(var t=0,a=Array(e.length);t

404 not found

Back'),e.put("app/base/addVarsDialog.html",'

Mango (Fruit)

Add var (no space)
TextIntDateCode
CloseAdd
'),e.put("app/base/base.html",'
Open table
'),e.put("app/base/breadcrumbs.html",''),e.put("app/base/header.html",'
Requirements Chrome! SQL Metrics & Processes Settings Help Sign out [{{user}}]
'),e.put("app/base/helpDialogLogin.html",'

Tabix.io Build {{::vars.version}} [{{::vars.buildDate}}]

* Work only in "Google chrome" version up 55

* Clickhouse server version up v1.1.54164

* Not readonly CH user




https://tabix.ioOk
'),e.put("app/base/helpDialogRu.html",'

Tabix.io Build {{::vars.version}} [{{::vars.buildDate}}]

ClickHouse Руководство


Tabix Руководство

Hot keys

⌘ + Enter

Exec current query

⌘ + Shift + Enter

Exec all query

⌘ + Y

Drop current line

⌘ + ⇧ + F

Reformat

⌘ + ⇧ + Plus|Minus

свернуть все/развернуть

⌘ + Right|Left

переключает вкладки

⌘ + ⌥ + Up|Down

Copy lines Up/Down

⌥ + Up|Down

Move lines Up/Down

Ctrl + K

Remove to line end

⌘ + Backspace

Remove to linestart

Ace Editor Default Keyboard Shortcuts

DrawChart

DrawChart

DrawMap

DrawMap

https://tabix.ioOk
'),e.put("app/base/sidebar.html",'
'),e.put("app/base/sidebarhelper.html",'

{{ hist }}

'),e.put("app/dash/dash.html",' Raised and Accent ButtonKILL

vars.show:{{vars.show}}
vars.show:{{vars.show}}draw-widget
'),e.put("app/dash/edit.html",'
'),e.put("app/login/login.html",'
Requirements Chrome or Chromium engine Browser! Requirements & helpUi Theme{{theme.title}}
'),e.put("app/metrics/dialog.kill.html",'

Kill query

{{ q.elapsed }}

{{ q.query }}

{{ q.bytes_read }}

{{ q.hash }}

Cancel
'),e.put("app/metrics/metrics.html",'Processes
Overview
Metrics
'),e.put("app/metrics/metricschart.html",'

Metrics

{{interval == -1 ? (\'Refresh is disabled\') : interval +\' \'+(\'sec\')}}{{interval}}system.eventsRefreshReset
'),e.put("app/metrics/overview.html",'

Overview

'),e.put("app/metrics/processes.html",'

Processes

{{interval == -1 ? (\'Refresh is disabled\') : interval +\' \'+\'sec\'}}Word wrapLog ModeClusterRefreshResetKILL Query
'),e.put("app/render/WidgetsList.html",'
'),e.put("app/preference/preference.html",'

Preference & settings

{{theme}}{{theme}}Save sessionLive AutocompletionDisable auto-helpDisable hotKey left+rightUse WrapModeShow invisible charsApply
'),e.put("app/sql/PlotlyEditor.tmpl.html",'

PlotLy JavaScript editor ( alpha )

'),e.put("app/sql/renderResult.html",'
{{::tableData.data.progressQuery}}CSV with headersCSV without headersTSV with headersTSV without headersPinnedEdit Plotly chartTable
Draw
'), +!function(){var e=window.smi2=window.smi2||{};e.app={name:"SMI2",version:window.TabixVersion||"",buildDate:window.TabixBuildDate||""},angular.module(e.app.name,["ui.router","LocalStorageModule","angularScreenfull","ui.ace","ngScrollbars","angularResizable","ngSanitize","ngMaterial","funMetisMenu","ngCsv","cfp.hotkeys","ngHandsontable","ngCsvImport","gridstack-angular"])}(),angular.module("SMI2").run(["$templateCache",function(e){e.put("app/base/404.html",'

404 not found

Back
'),e.put("app/base/addVarsDialog.html",'

Mango (Fruit)

Add var (no space)
TextIntDateCode
CloseAdd
'),e.put("app/base/base.html",'
Open table
'),e.put("app/base/breadcrumbs.html",''),e.put("app/base/header.html",'
Requirements Chrome! SQL Metrics & Processes Settings Help Sign out [{{user}}]
'),e.put("app/base/helpDialogLogin.html",'

Tabix.io Build {{::vars.version}} [{{::vars.buildDate}}]

* Work only in "Google chrome" version up 55

* Clickhouse server version up v1.1.54164

* Not readonly CH user




https://tabix.ioOk
'),e.put("app/base/helpDialogRu.html",'

Tabix.io Build {{::vars.version}} [{{::vars.buildDate}}]

ClickHouse Руководство


Tabix Руководство

Hot keys

⌘ + Enter

Exec current query

⌘ + Shift + Enter

Exec all query

⌘ + Y

Drop current line

⌘ + ⇧ + F

Reformat

⌘ + ⇧ + Plus|Minus

свернуть все/развернуть

⌘ + Right|Left

переключает вкладки

⌘ + ⌥ + Up|Down

Copy lines Up/Down

⌥ + Up|Down

Move lines Up/Down

Ctrl + K

Remove to line end

⌘ + Backspace

Remove to linestart

Ace Editor Default Keyboard Shortcuts

DrawChart

DrawChart

DrawMap

DrawMap

https://tabix.ioOk
'),e.put("app/base/sidebar.html",'
'),e.put("app/base/sidebarhelper.html",'

{{ hist }}

'),e.put("app/dash/dash.html",' Raised and Accent ButtonKILL

vars.show:{{vars.show}}
vars.show:{{vars.show}}draw-widget
'),e.put("app/dash/edit.html",'
'),e.put("app/login/login.html",'
Requirements Chrome or Chromium engine Browser! Requirements & helpUi Theme{{theme.title}}
'),e.put("app/metrics/dialog.kill.html",'

Kill query

{{ q.elapsed }}

{{ q.query }}

{{ q.bytes_read }}

{{ q.hash }}

Cancel
'),e.put("app/metrics/metrics.html",'Processes
Overview
Metrics
'),e.put("app/metrics/metricschart.html",'

Metrics

{{interval == -1 ? (\'Refresh is disabled\') : interval +\' \'+(\'sec\')}}{{interval}}system.eventsRefreshReset
'),e.put("app/metrics/overview.html",'

Overview

'),e.put("app/metrics/processes.html",'

Processes

{{interval == -1 ? (\'Refresh is disabled\') : interval +\' \'+\'sec\'}}Word wrapLog ModeClusterRefreshResetKILL Query
'),e.put("app/preference/preference.html",'

Preference & settings

{{theme}}{{theme}}Save sessionLive AutocompletionDisable auto-helpDisable hotKey left+rightUse WrapModeShow invisible charsApply
'),e.put("app/render/WidgetsList.html",'
'),e.put("app/sql/PlotlyEditor.tmpl.html",'

PlotLy JavaScript editor ( alpha )

'),e.put("app/sql/renderResult.html",'
{{::tableData.data.progressQuery}}CSV with headersCSV without headersTSV with headersTSV without headersPinnedEdit Plotly chartTable
Draw
'), e.put("app/sql/showDialogUpload.html",'

Upload CSV to View

'),e.put("app/sql/sql.html",'
{{tab.name + (tab.changed ? \' *\' : \'\')}}
Make snippetAutoFormatExpandCollapseCollapse All
{{tab.buttonTitle}}Run current ⌘ + ⏎Full screenSave{{item.name}}Query log
USE {{::dbb.name}}{{vars.LastStatistics.elapsed| number:2}} sec.| {{vars.LastStatistics.rows_read| number}} rows.| {{vars.LastStatistics.bytes_read|filesize}}
..... {{tab.progress.query}}
'),e.put("app/table/table-container.html",'

{{vars.currentDatabase}} {{vars.currentTable}}

Structure
NameTypeDefault typeValueSizeCompress
{{$index + 1}}{{field[key]}}
Information
1Size{{vars.statistics.size}}
2Size,bytes{{vars.statistics.sizeBytes}}
3First row{{vars.statistics.minDate}}
4Last row{{vars.statistics.maxDate}}

SHOW CREATE TABLE
{{vars.createtable}}
Data
Data From {{vars.offset}} To {{vars.offset + vars.limit}}
No data
'),e.put("app/table/table.html",'
')}]),function(e,t){function a(e,t){var a=t.dbName,n=t.tableName;e.vars={dbName:a,tableName:n}}e.module(t.app.name).controller("TableController",a),a.$inject=["$scope","$stateParams"]}(angular,smi2),function(e,t){function a(t,a,n,r,i,s,o,c){t.tablewidget={},t.vars={columns:{},ugrid:{},sortColumn:!1,isDark:r.isDark(),createtable:{},data:null,grid:null,limit:100,offset:0,statistics:{},loading:!0,isRawStatistics:!1,rawstatistics:"",scrollConfig:{autoHideScrollbar:!1,theme:r.isDark()?"light":"dark",scrollButtons:{enable:!1},scrollInertia:100,advanced:{updateOnContentResize:!0}}},t.initContainer=function(){a.$watch("currentTable",function(e){e&&(t.vars.currentTable=a.currentTable,t.vars.currentDatabase=a.currentDatabase,t.init())})},t.onAfterInit=function(){},t.updateHandTable=function(){c.getInstance("hotTableContain").render()},t.initOnGo=function(){t.$parent.vars&&(o.get("tableSiedenav")&&s("tableSiedenav").close(),t.vars.currentTable=t.$parent.vars.tableName,t.vars.currentDatabase=t.$parent.vars.dbName,t.init())},t.load=function(){console.warn("LOAD DATA! IN TABLES"),t.vars.data=-1,n.query("\n select * from "+t.vars.currentDatabase+"."+t.vars.currentTable+" limit "+t.vars.offset+", "+t.vars.limit+"\n ").then(function(e){var a="ch";t.tablewidget=new WidgetTable(new DataProvider(e,a)),t.vars.loading=!1},function(e){t.vars.loading=!1,console.error("Error "+e)})},t.calcRawSize=function(){t.vars.isRawStatistics=!0,n.query("SELECT any(ignore(*)) FROM "+t.vars.currentDatabase+"."+t.vars.currentTable+" SAMPLE 1 / 10000 ").then(function(e){t.vars.rawstatistics=e.statistics},function(e){t.vars.rawstatistics=e.data})},t.init=function(){t.vars.loading=!0,t.vars.createtable="N/A",n.query("SHOW CREATE TABLE "+t.vars.currentDatabase+"."+t.vars.currentTable).then(function(e){t.vars.createtable=window.sqlFormatter.format(e.data[0].statement)}),n.query("SELECT table, formatReadableSize(sum(bytes)) as size, sum(bytes) as sizeBytes, min(min_date) as minDate, max(max_date) as maxDate FROM system.parts WHERE database = '"+t.vars.currentDatabase+"' AND ( table = '"+t.vars.currentTable+"' OR table = '"+t.vars.currentTable+"_sharded' ) GROUP BY table ").then(function(e){return t.vars.statistics=e&&e.data.length&&e.data[0]||{}}),n.query("SELECT * FROM system.columns WHERE database='"+t.vars.currentDatabase+"' AND table='"+t.vars.currentTable+"'").then(function(a){n.query("describe table "+t.vars.currentDatabase+"."+t.vars.currentTable).then(function(n){_.map(n.data,function(t){var n=_.find(a.data,{name:t.name});return _.merge(t,n),t.size="-",t.ratio="-",!e.isUndefined(t.default_kind)&&e.isUndefined(t.default_type)&&(t.default_type=t.default_kind),t.data_compressed_bytes&&(t.size=numbro(t.data_compressed_bytes).format("0.0 b")+" / "+numbro(t.data_uncompressed_bytes).format("0.0 b"),t.ratio=numbro(parseInt(t.data_uncompressed_bytes)/parseInt(t.data_compressed_bytes)).format("0.0")),t}),t.vars.columns=n,t.vars.sortColumn=!1;var r=0;n.data.forEach(function(e){3>r&&("Date"==e.type&&(t.vars.sortColumn=e.name),"DateTime"==e.type&&(t.vars.sortColumn=e.name)),r+=1}),t.load()})})},t.loadNext=function(){t.vars.loading=!0,t.vars.offset+=t.vars.limit,t.load()},t.loadPrev=function(){t.vars.offset>0&&(t.vars.loading=!0,t.vars.offset-=t.vars.limit,t.load())}}e.module(t.app.name).controller("TableContainerController",a),a.$inject=["$scope","$rootScope","API","ThemeService","$stateParams","$mdSidenav","$mdComponentRegistry","hotRegisterer"]}(angular,smi2),/* * Licensed under the Apache License, Version 2.0 Copyright 2017 Igor Strykhar,Ivan Kudinov,SMI2 LLC and other contributors */ -window.global_delimiter=";;",window.aceJSRules={builtinFunctions:[],lang:"en",dictionaries:[],fieldsList:[],tables:[]},function(e,t){function a(t,a,n,r,i,s,o,c,l,d,u,m,h,p,g){var f="sqlHistory2",b="saveTabs",v="sessionData",y=255;t.AceEditorInLoad=!1,t.vars={EditorIsInit:!1,sqlHistory:r.get(f)||[],dictionaries:[],isDictionariesLoad:!1,tabs:[],enableLiveAutocompletion:h.get("liveAutocompletion"),disableAutohelp:h.get("disableAutohelp"),disableHotKeyCmdLeft:h.get("disableHotKeyCmdLeft"),saveTabs:r.get(b)||!0,LastStatistics:!1,delimiters:[{name:";; Double",delimiter:";;"},{name:"; Single",delimiter:";"}],databasesList:[],searchQueryOnServer:"",currentTab:{},selectedTab:0,formats:[{name:"Table",sql:" format JSON",render:"html"},{name:"JSON compact",sql:" format JSONCompact"}],db:null,limitTimes:h.get("limitTimes"),limitRows:h.get("limitRows"),fontSize:h.get("fontSize"),theme:h.get("editorTheme")},t.vars.delimiter=r.get("delimiter")||";;",t.vars.format=t.vars.formats[0],t.vars.themes=["ambiance","eclipse","mono_industrial","tomorrow_night_blue","chaos","github","monokai","tomorrow_night_bright","chrome","idle_fingers","pastel_on_dark","tomorrow_night_eighties","clouds","iplastic","solarized_dark","tomorrow_night","clouds_midnight","katzenmilch","solarized_light","twilight","cobalt","kr_theme","sqlserver","vibrant_ink","crimson_editor","kuroir","terminal","xcode","dawn","merbivore","textmate","dreamweaver","merbivore_soft","tomorrow"],n.onbeforeunload=function(e){if(""!==t.vars.currentTab.sql&&"localhost"!=location.hostname){var a="Do you want to leave this page?";return"undefined"==typeof e&&(e=window.event),e&&(e.returnValue=a),a}};var w=t.$on("$stateChangeStart",function(e){var a="Do you want to leave this page?";e.defaultPrevented||""===t.vars.currentTab||confirm(a)||e.preventDefault()}),k=function(){if(t.vars.saveTabs){var e=t.vars.tabs.map(function(e){return e.editor?e.sql=e.editor.getValue():e.sql="",{name:e.name,sql:e.sql,buttonTitle:e.buttonTitle,format:e.format,delimiter:e.delimiter,results:[],editor:null,selectedResultTab:0}});r.set(v,e),console.info("Save session , localStorageService.set(SQL_SESSION_KEY)")}};t.$watch("$root.isInitDatabaseStructure",function(){t.vars.EditorIsInit=a.isInitDatabaseStructure}),t.InitDatabaseStructure=function(){console.warn(">>>>>>>>>>>>>>>InitDatabaseStructure<<<<<<<",a.isInitDatabaseStructure)},t.executeQuery=function(a,n,r){var s="result_overflow_mode=throw";t.vars.currentTab.loading=!0,t.vars.limitRows&&(s+="&max_result_rows="+t.vars.limitRows),t.vars.limitTimes&&(s+="&timeout_overflow_mode=throw&max_execution_time="+t.vars.limitTimes);var o=a.sql.replace(/(\r\n|\n|\r)$/gm,"").substr(0,130);t.vars.currentTab.progress.query=o;var d="";a.qid&&(d=" /*TABIX_QUERY_ID_"+a.qid+"*/ "),i.fetchQuery(d+a.sql,!0,a.format,s).then(function(i){var s=i;e.isObject(i)||(i={data:s,meta:null,rows:null,statistics:null}),i.error=!1,i.query=a,i.countAllQuery=n.length;var c={time:moment().format("HH:mm:ss")};e.isObject(i.statistics)&&Object.assign(c,i.statistics),c.query=o,_.isArray(t.vars.currentTab.statistics)&&t.vars.currentTab.statistics.push(c),t.vars.LastStatistics=c;var l=new DataProvider(i,"ch");l.progressQuery=o,r.widgets.tables.push(new WidgetTable(l)),"drawCommand"in a&&a.drawCommand.length?(l.countAll=a.drawCommand.length>i.countAllQuery?a.drawCommand.length:i.countAllQuery,console.info("query.drawCommand",a.drawCommand),a.drawCommand.forEach(function(e){r.widgets.draw.push(new WidgetDraw(l,e))})):r.widgets.draw.push(new WidgetDraw(l,!1)),r.data.push(a),t.$applyAsync(),a.index+1-1&&i>-1&&t.vars.currentTab.editor.gotoLine(s,i),console.log("move cursor to",s,i)}var d="ch";console.warn("ERROR",n);var u=new DataProvider(n,d);r.data.push(a),r.widgets.tables.push(new WidgetTable(u)),t.finalizeResult(r)})},t.renderResult=function(t){return t.echarts=!1,t.pivot=!1,t.charts=!1,t.selectedTabIndex=0,"string"==typeof t.error?t.result='
'+t.error+"
":e.isObject(t.data)?(t.result=i.dataToHtml(t),t.createtable=i.dataToCreateTable(t),t.pivot=!0,t.charts=!0):e.isString(t.data)?t.result='
'+t.data+"
":t.result='
'+e.toJson(t.data,!0)+"
",t},t.finalizeResult=function(e){if(t.vars.currentTab.loading=!1,t.vars.currentTab.progress=!1,e.data.find(function(e){return e.keyword&&-1!=["DROP","CREATE","ALTER"].indexOf(e.keyword.toUpperCase())}),t.$applyAsync(),t.vars.currentTab.statistics[0]){var a=DataProvider.convertArrayToDataProvider(t.vars.currentTab.statistics,"statistics");a.sort="time",a.sortOrder="desc",e.widgets.stats.push(new WidgetTable(a,!1))}},t.execute=function(n,s){t.$applyAsync(),console.groupCollapsed("Execute query"),t.vars.LastStatistics=!1,s.sql=s.editor.getValue();var o=s.sql,d=0,m=s.editor,h=[],p=m.getSelectedText();e.isUndefined(s.selectedTabResultIndex)&&(s.selectedTabResultIndex=0);var f={data:[],time:u("date")(new Date,"HH:mm:ss"),pinned:!1,widgets:{tables:[],pivot:[],draw:[],stats:[]}};if(""!==p&&null!==p&&(o=p),console.info("[EDITOR TEXT]> ",o),""===o||null===o)return void c.show(c.simple().content("SQL query is empty").theme(l.theme).position("bottom right"));s.results=[f],k();var b=window.global_delimiter;b||(b=";;"),m.session.$mode.splitByTokens(o,"constant.character.escape",b).forEach(function(t){if(!("current"==n&&d>0)){var s=[],o=t.sql;if(!(o.length<5)){if("current"==n&&!p){var c=m.selection.getCursor();if(!c||e.isUndefined(c))return;var l=t.range.compare(c.row,c.column);if(0!==l)return}var u=o.trim();-1==a.sqlLog.indexOf(u)&&(a.sqlLog.unshift(u),a.sqlLog.length>y&&a.sqlLog.splice(0,y),r.set("sqlLog",a.sqlLog));var f=m.session.$mode.replaceVars(o,g.get());o=f.sql;f.vars;if(console.log("replacedVars",f),m.session.$mode.findTokens(o,"invalid.illegal",!0)){var b=m.session.$mode.splitByTokens(o,"invalid.illegal",!0);o=b[0].sql,b.forEach(function(t){if(e.isDefined(t.keyword)&&t.keyword){var a=/DRAW_(\w+)/gim,n=a.exec(t.keyword);n&&n[1]&&s.push({drawtype:n[1].toLowerCase(),code:t.sql})}})}console.info("[SQL]>",o),s&&console.info("[DRAW]>",s);var v=null,w=!1,k=!1,x=null,C=m.session.$mode.findTokens(o,"storage",!0),S=m.session.$mode.findTokens(o,"keyword",!0);C.hasOwnProperty("value")?(v=!1,k=C.value):(v=" FORMAT JSON ",w=!0),S.hasOwnProperty("value")&&(x=S.value),"select"!==x&&(v=!1,w=!1),h.push({sql:o,index:d,format:v,setedformat:w,keyword:x,storage:k,drawCommand:s,itemRange:t.range,qid:i.makeQueryId()}),d++}}}),console.groupEnd("Execute query"),h.length&&(t.vars.currentTab.progress={},t.vars.currentTab.statistics||(t.vars.currentTab.statistics=[]),t.executeQuery(h[0],h,f))},t.setTheme=function(e){t.vars.theme=e,t.vars.tabs.forEach(function(t){return t.editor.setTheme("ace/theme/"+e)}),r.set("editorTheme",e)},t.reloadCache=function(){console.log("reloadCache"),i.resetDatabaseStructure(),c.show(c.simple().content("Reload page - for reset cache").theme(l.theme).position("bottom right"))},t.selectDatabase=function(e,a){e&&(i.setDatabase(e),t.vars.db!=e&&(t.vars.db=e,t.AceEditorInLoad||(t.aceLoadDatabaseFields(),t.aceApply(!1))))},t.insertWordInEditor=function(e){var a=t.vars.currentTab.editor,n=a.getCursorPosition();n.column+=e.length,a.clearSelection(),a.insert(e),t.vars.currentTab.sql=a.getValue(),d(function(){a.focus(),a.moveCursorToPosition(n)})},t.aceLoadDatabaseFields=function(){var e=t.vars.db;window.aceJSRules.fieldsList=[],i.databaseStructure(function(t){window.aceJSRules.fieldsList=t.getAllFieldsInDatabase(e)})},t.aceLoadDatabaseStructure=function(){var e=t.vars.db;window.aceJSRules.tables=[],i.databaseStructure(function(a){t.vars.databasesList=a.getDatabases(),Object.keys(a.getUniqueDatabaseTables()).forEach(function(e){window.aceJSRules.tables.push(e)}),window.aceJSRules.fieldsList=a.getAllFieldsInDatabase(e)})},t.loadInAce=function(e){e.session.setMode({path:"ace/mode/clickhouse"});for(var t in window.aceJSRules.builtinFunctions){var a=window.aceJSRules.builtinFunctions[t];e.session.$mode.$highlightRules.addCompletionsFunctions(a)}e.session.$mode.$highlightRules.addArrayCompletions(window.aceJSRules.tables,"[table]","table");for(var n in window.aceJSRules.dictionaries){var r=window.aceJSRules.dictionaries[n];e.session.$mode.$highlightRules.addCompletionsDictionaries(r)}for(var i in window.aceJSRules.fieldsList){var s=window.aceJSRules.fieldsList[i];e.session.$mode.$highlightRules.addCompletionsTableFiled(s)}var o=g.getCompletions(),c=p.getCompletions();e.session.$mode.$highlightRules.addArrayCompletions(o,"[var]","var"),e.session.$mode.$highlightRules.addArrayCompletions(c,"[snippet]","snippet"),e.session.bgTokenizer.start(0)},t.aceApply=function(e){e?(console.log(""),t.loadInAce(e)):t.vars.tabs.forEach(function(e){e.editor&&(console.log(""),t.loadInAce(e.editor))}),a.$watch("currentDatabase",t.selectDatabase)},t.changeRootSelectDatabase=function(e){a.currentDatabase!=e&&(a.currentDatabase=e)},t.aceLoadDictionaries=function(){t.vars.isDictionariesLoad||(window.aceJSRules.dictionaries=[],t.vars.dictionaries=[],window.aceJSRules.builtinFunctions=[],t.vars.isDictionariesLoad=!0,i.databaseStructure(function(e){e.getFunctions().forEach(function(e){if(window.aceJSRules.builtinFunctions.push({name:e.name,isaggr:e.is_aggregate,score:101,comb:!1,origin:e.name}),e.is_aggregate){var t={name:e.name+"If",isaggr:e.is_aggregate,score:3,comb:"If",origin:e.name};window.aceJSRules.builtinFunctions.push(t),t={name:e.name+"Array",isaggr:e.is_aggregate,score:2,comb:"Array",origin:e.name},window.aceJSRules.builtinFunctions.push(t),t={name:e.name+"State",isaggr:e.is_aggregate,score:1,comb:"State",origin:e.name},window.aceJSRules.builtinFunctions.push(t)}}),e.getDictionaries().forEach(function(e){var a=e.name;a=a.replace(/^.*\./gm,""),"news"!=a&&(a=a.replace(/s$/gm,"")),a=a?a.toLowerCase()+"_id":"ID";var n="dictGet"+e["attribute.types"]+"('"+e.name+"','"+e["attribute.names"]+"',to"+e.key+"( "+a+" ) ) AS "+e["attribute.names"]+",";window.aceJSRules.dictionaries.push({dic:n,title:"dic_"+e.name+"."+e["attribute.names"]}),t.vars.dictionaries.push({dic:n,title:e.name+"."+e["attribute.names"]+" as "+e["attribute.types"]})})}))};for(var x=function(e){t.vars.tabs.length>=e&&(t.vars.currentTab=t.vars.tabs[e],t.vars.selectedTab=e,d(function(){t.vars.currentTab.editor.focus()}))},C=function(){t.vars.selectedTab>0&&x(t.vars.selectedTab-1)},S=function(){t.vars.selectedTabD;D++)A(D);m.add({combo:t.vars.disableHotKeyCmdLeft?"ctrl+shift+alt+right":"ctrl+right",callback:S}),m.add({combo:t.vars.disableHotKeyCmdLeft?"ctrl+shift+alt+left":"ctrl+left",callback:C}),m.add({combo:"ctrl+shift+f",callback:T}),t.aceLoaded=function(e){t.AceEditorInLoad=!0,a.currentDatabase&&t.selectDatabase(a.currentDatabase),t.aceLoadDictionaries(),t.aceLoadDatabaseStructure(),t.aceLoadDatabaseFields();var n=t.vars.tabs.find(function(e){return!e.editor})||t.vars.currentTab;n.editor=e,e.$blockScrolling=1/0,e.setOptions({fontSize:t.vars.fontSize+"px",enableBasicAutocompletion:!0,behavioursEnabled:!0,wrapBehavioursEnabled:!0,highlightSelectedWord:!0,showGutter:!0,enableLiveAutocompletion:t.vars.enableLiveAutocompletion,liveAutocompletionDelay:500,liveAutocompletionThreshold:1}),e.setTheme("ace/theme/"+t.vars.theme),e.session.setUseWrapMode(h.get("useWrapMode")),e.commands.addCommand({name:"runCurrentCommand",bindKey:{win:"Ctrl-Enter",mac:"Command-Enter"},exec:function(){t.execute("current",n)}}),e.commands.addCommand({name:"removeLiness",bindKey:{win:"Ctrl-Y",mac:"Cmd-Y"},exec:function(e){e.removeLines()}}),e.commands.addCommand({name:"collapseAll",bindKey:{win:"Ctrl-Shift--",mac:"Command+Shift+-"},exec:function(e){e.session.$mode.collapseAll(e.session)}}),e.commands.addCommand({name:"unfold",bindKey:{win:"Ctrl-Shift-+",mac:"Command+Shift+="},exec:function(e){e.session.unfold()}}),e.commands.addCommand({name:"runAllCommand",bindKey:{win:"Shift-Ctrl-Enter",mac:"Shift-Command-Enter"},exec:function(){t.execute("all",n)}});for(var r=function(t){e.commands.addCommand({name:"selecttab"+t,bindKey:{win:"Ctrl-Shift-"+(t+1),mac:"Command-Shift-"+(t+1)},exec:function(){return x(t)}})},i=0;9>i;i++)r(i);e.commands.addCommand({name:"selectnexttab",bindKey:{win:t.vars.disableHotKeyCmdLeft?"Shift-Alt-Ctrl-Right":"Ctrl-Right",mac:t.vars.disableHotKeyCmdLeft?"Shift-Alt-Command-Right":"Command-Right"},exec:S}),e.commands.addCommand({name:"selectprevtab",bindKey:{win:t.vars.disableHotKeyCmdLeft?"Shift-Alt-Ctrl-Left":"Ctrl-Left",mac:t.vars.disableHotKeyCmdLeft?"Shift-Alt-Command-Left":"Command-Left"},exec:C}),e.commands.addCommand({name:"formatcode",bindKey:{win:"Ctrl-Shift-F",mac:"Command-Shift-F"},exec:T}),e.setValue(n.sql),e.clearSelection(),e.focus(),e.selection.moveTo(0,0),e.on("changeSelection",function(){d(function(){n.buttonTitle=""!==e.getSelectedText()?"Run selected ⌘ + ⏎":"Run all ⇧ + ⌘ + ⏎",n.originalSql&&(n.changed=n.originalSql!=n.sql)})}),t.AceEditorInLoad=!1,t.aceApply(e)},t.save=function(e,a){return o.show(o.prompt().title("Save SQL as?").placeholder("Title").initialValue(e.name).targetEvent(a).ok("Save").cancel("")).then(function(a){var n=t.vars.sqlHistory.findIndex(function(t){return t.name==e.name});-1!=n?(t.vars.sqlHistory[n].sql=e.sql,t.vars.sqlHistory[n].name=a):t.vars.sqlHistory.push({sql:e.sql,name:a}),e.originalSql=e.sql,e.name=a,r.set(f,t.vars.sqlHistory),k()})},t.load=function(e){t.vars.currentTab.sql=e.sql,t.vars.currentTab.originalSql=e.sql,t.vars.currentTab.name=e.name,t.vars.currentTab.editor.setValue(e.sql),t.aceApply(t.vars.currentTab.editor)},t.getExportData=function(t){return t.data.data.map(function(t){return Object.keys(t).map(function(a){return e.isArray(t[a])?t[a].join(", "):t[a]})})},t.getExportHeaders=function(e){return e.data.meta.map(function(e){return e.name})},t.addTab=function(){t.vars.currentTab={name:"new SQL",sql:"",buttonTitle:"Run ⌘ + ⏎",format:{},editor:null,results:[],selectedResultTab:0},t.vars.tabs.push(t.vars.currentTab),k()},t.changeTab=function(e){k(),t.vars.currentTab=e},t.removeTab=function(e,a){a.stopPropagation();var n=function(){t.vars.tabs.splice(t.vars.tabs.indexOf(e),1),t.vars.tabs.length==t.vars.selectedTab&&t.vars.selectedTab--};e.changed?o.show(o.confirm().title("SQL was changed. Save it before exit?").targetEvent(a).ok("Yes").cancel("No")).then(function(){var a=t.vars.sqlHistory.findIndex(function(t){return t.name==e.name});-1!=a&&(t.vars.sqlHistory[a].sql=e.sql,t.vars.sqlHistory[a].name=e.name),r.set(f,t.vars.sqlHistory),n()},n):n()},t.removeResult=function(e,t,a){},a.$on("handleBroadcastUpdateVarsAndSnippets",function(e,a){t.aceApply()}),a.$on("handleBroadcastInsertInActive",function(e,a){a.value&&t.insertWordInEditor(" "+a.value+" ")}),t.toggleSidenav=function(e){s(e).toggle()},t.removeHistory=function(e,a){a.preventDefault();var n=t.vars.sqlHistory.indexOf(e);-1!=n&&o.show(o.confirm().title("Delete "+e.name+"?").targetEvent(a).ok("Yes").cancel("No")).then(function(){t.vars.sqlHistory.splice(n,1),r.set(f,t.vars.sqlHistory)})},t.setSql=function(e){t.vars.currentTab.sql=e,t.toggleSidenav("log"),t.vars.currentTab.editor.setValue(e),d(function(){return t.vars.currentTab.editor.focus()},500)},t.changeTabName=function(e,a){a.stopPropagation(),o.show(o.prompt().title("Title tab").placeholder("title").initialValue(e.name).targetEvent(a).ok("Apply").cancel("Cancel")).then(function(a){var n=t.vars.sqlHistory.findIndex(function(t){return t.name==e.name});-1!=n&&(e.originalSql=e.sql,t.vars.sqlHistory[n].name=a,r.set(f,t.vars.sqlHistory)),e.name=a,k()})},t.vars.saveTabs?(t.vars.tabs=r.get(v),_.isArray(t.vars.tabs)||(t.vars.tabs=[]),t.vars.tabs.length>0?d(function(){return t.vars.currentTab=t.vars.tabs[0]},500):t.addTab()):(r.set(v,[]),t.addTab()),t.$on("$destroy",function(){i.setDatabase(a.currentDatabase),w(),n.onbeforeunload=null}),t.rightAceMenuList=[],t.showDialogUpload=function(t,a){function n(e,t){e.vars={UploadCsv:{content:null,header:!0,headerVisible:!0,separator:",",separatorVisible:!0,result:null,encoding:"ISO-8859-1",encodingVisible:!0,uploadButtonLabel:"Upload",callback:function(e){t.hide()}}},e.$watch("vars.UploadCsv.result",function(e){e&&t.hide(e)}),e.hide=function(){t.hide()},e.cancel=function(){t.cancel()}}n.$inject=["$scope","$mdDialog"],o.show({controller:n,templateUrl:"app/sql/showDialogUpload.html",parent:e.element(document.body),targetEvent:a,clickOutsideToClose:!0}).then(function(e){if(e&&t&&t.tables){var a=DataProvider.convertArrayToDataProvider(e,"csv");t.tables.push(new WidgetTable(a))}},function(){})},t.rightMenuProcess=function(e){var a=t.vars.currentTab.editor.session;if(t.vars.currentTab.editor.resize(),"Snippet"==e){var n=t.vars.currentTab.editor.getSelectedText();n&&(p.add(n),t.aceApply())}else"AutoFormat"==e?T():"Expand"==e?a.unfold():"Collapse All"==e?a.$mode.collapseAll(a):"Collapse"==e&&a.foldAll();t.vars.currentTab.editor.focus()}}e.module(t.app.name).controller("SqlController",a),a.$inject=["$scope","$rootScope","$window","localStorageService","API","$mdSidenav","$mdDialog","$mdToast","ThemeService","$timeout","$filter","hotkeys","Preference","Snippets","Variables"]}(angular,smi2),/* +window.global_delimiter=";;",window.aceJSRules={builtinFunctions:[],lang:"en",dictionaries:[],fieldsList:[],tables:[]},function(e,t){function a(t,a,n,r,i,s,o,c,l,d,u,m,h,p,g){var f="sqlHistory2",b="saveTabs",v="sessionData",y=255;t.AceEditorInLoad=!1,t.vars={EditorIsInit:!1,sqlHistory:r.get(f)||[],dictionaries:[],isDictionariesLoad:!1,tabs:[],enableLiveAutocompletion:h.get("liveAutocompletion"),disableAutohelp:h.get("disableAutohelp"),disableHotKeyCmdLeft:h.get("disableHotKeyCmdLeft"),saveTabs:r.get(b)||!0,LastStatistics:!1,delimiters:[{name:";; Double",delimiter:";;"},{name:"; Single",delimiter:";"}],databasesList:[],searchQueryOnServer:"",currentTab:{},selectedTab:0,formats:[{name:"Table",sql:" format JSON",render:"html"},{name:"JSON compact",sql:" format JSONCompact"}],db:null,limitTimes:h.get("limitTimes"),limitRows:h.get("limitRows"),fontSize:h.get("fontSize"),theme:h.get("editorTheme")},t.vars.delimiter=r.get("delimiter")||";;",t.vars.format=t.vars.formats[0],t.vars.themes=["ambiance","eclipse","mono_industrial","tomorrow_night_blue","chaos","github","monokai","tomorrow_night_bright","chrome","idle_fingers","pastel_on_dark","tomorrow_night_eighties","clouds","iplastic","solarized_dark","tomorrow_night","clouds_midnight","katzenmilch","solarized_light","twilight","cobalt","kr_theme","sqlserver","vibrant_ink","crimson_editor","kuroir","terminal","xcode","dawn","merbivore","textmate","dreamweaver","merbivore_soft","tomorrow"],n.onbeforeunload=function(e){if(""!==t.vars.currentTab.sql&&"localhost"!=location.hostname){var a="Do you want to leave this page?";return"undefined"==typeof e&&(e=window.event),e&&(e.returnValue=a),a}};var w=t.$on("$stateChangeStart",function(e){var a="Do you want to leave this page?";e.defaultPrevented||""===t.vars.currentTab||confirm(a)||e.preventDefault()}),k=function(){if(t.vars.saveTabs){var e=t.vars.tabs.map(function(e){return e.editor?e.sql=e.editor.getValue():e.sql="",{name:e.name,sql:e.sql,buttonTitle:e.buttonTitle,format:e.format,delimiter:e.delimiter,results:[],editor:null,selectedResultTab:0}});r.set(v,e),console.info("Save session , localStorageService.set(SQL_SESSION_KEY)")}};t.$watch("$root.isInitDatabaseStructure",function(){t.vars.EditorIsInit=a.isInitDatabaseStructure}),t.InitDatabaseStructure=function(){console.warn(">>>>>>>>>>>>>>>InitDatabaseStructure<<<<<<<",a.isInitDatabaseStructure)},t.executeQuery=function(a,n,r){var s="result_overflow_mode=throw";t.vars.currentTab.loading=!0,t.vars.limitRows&&(s+="&max_result_rows="+t.vars.limitRows),t.vars.limitTimes&&(s+="&timeout_overflow_mode=throw&max_execution_time="+t.vars.limitTimes);var o=a.sql.replace(/(\r\n|\n|\r)$/gm,"").substr(0,130);t.vars.currentTab.progress.query=o;var d="";a.qid&&(d=" /*TABIX_QUERY_ID_"+a.qid+"*/ "),i.fetchQuery(d+a.sql,!0,a.format,s).then(function(i){var s=i;e.isObject(i)||(i={data:s,meta:null,rows:null,statistics:null}),i.error=!1,i.query=a,i.countAllQuery=n.length;var c={time:moment().format("HH:mm:ss")};e.isObject(i.statistics)&&Object.assign(c,i.statistics),c.query=o,_.isArray(t.vars.currentTab.statistics)&&t.vars.currentTab.statistics.push(c),t.vars.LastStatistics=c;var l=new DataProvider(i,"ch");l.progressQuery=o,r.widgets.tables.push(new WidgetTable(l)),"drawCommand"in a&&a.drawCommand.length?(l.countAll=a.drawCommand.length>i.countAllQuery?a.drawCommand.length:i.countAllQuery,console.info("query.drawCommand",a.drawCommand),a.drawCommand.forEach(function(e){r.widgets.draw.push(new WidgetDraw(l,e))})):r.widgets.draw.push(new WidgetDraw(l,!1)),r.data.push(a),t.$applyAsync(),a.index+1-1&&i>-1&&t.vars.currentTab.editor.gotoLine(s,i),console.log("move cursor to",s,i)}var d="ch";console.warn("ERROR",n);var u=new DataProvider(n,d);r.data.push(a),r.widgets.tables.push(new WidgetTable(u)),t.finalizeResult(r)})},t.renderResult=function(t){return t.echarts=!1,t.pivot=!1,t.charts=!1,t.selectedTabIndex=0,"string"==typeof t.error?t.result='
'+t.error+"
":e.isObject(t.data)?(t.result=i.dataToHtml(t),t.createtable=i.dataToCreateTable(t),t.pivot=!0,t.charts=!0):e.isString(t.data)?t.result='
'+t.data+"
":t.result='
'+e.toJson(t.data,!0)+"
",t},t.finalizeResult=function(e){if(t.vars.currentTab.loading=!1,t.vars.currentTab.progress=!1,e.data.find(function(e){return e.keyword&&-1!=["DROP","CREATE","ALTER"].indexOf(e.keyword.toUpperCase())}),t.$applyAsync(),t.vars.currentTab.statistics[0]){var a=DataProvider.convertArrayToDataProvider(t.vars.currentTab.statistics,"statistics");a.sort="time",a.sortOrder="desc",e.widgets.stats.push(new WidgetTable(a,!1))}},t.execute=function(n,s){t.$applyAsync(),console.groupCollapsed("Execute query"),t.vars.LastStatistics=!1,s.sql=s.editor.getValue();var o=s.sql,d=0,m=s.editor,h=[],p=m.getSelectedText();e.isUndefined(s.selectedTabResultIndex)&&(s.selectedTabResultIndex=0);var f={data:[],time:u("date")(new Date,"HH:mm:ss"),pinned:!1,widgets:{tables:[],pivot:[],draw:[],stats:[]}};if(""!==p&&null!==p&&(o=p),console.info("[EDITOR TEXT]> ",o),""===o||null===o)return void c.show(c.simple().content("SQL query is empty").theme(l.theme).position("bottom right"));s.results=[f],k();var b=window.global_delimiter;b||(b=";;"),m.session.$mode.splitByTokens(o,"constant.character.escape",b).forEach(function(t){if(!("current"==n&&d>0)){var s=[],o=t.sql;if(!(o.length<5)){if("current"==n&&!p){var c=m.selection.getCursor();if(!c||e.isUndefined(c))return;var l=t.range.compare(c.row,c.column);if(0!==l)return}var u=o.trim();-1==a.sqlLog.indexOf(u)&&(a.sqlLog.unshift(u),a.sqlLog.length>y&&a.sqlLog.splice(0,y),r.set("sqlLog",a.sqlLog));var f=m.session.$mode.replaceVars(o,g.get());o=f.sql;f.vars;if(console.log("replacedVars",f),m.session.$mode.findTokens(o,"invalid.illegal",!0)){var b=m.session.$mode.splitByTokens(o,"invalid.illegal",!0);o=b[0].sql,b.forEach(function(t){if(e.isDefined(t.keyword)&&t.keyword){var a=/DRAW_(\w+)/gim,n=a.exec(t.keyword);n&&n[1]&&s.push({drawtype:n[1].toLowerCase(),code:t.sql})}})}console.info("[SQL]>",o),s&&console.info("[DRAW]>",s);var v=null,w=!1,k=!1,x=null,C=m.session.$mode.findTokens(o,"storage",!0),S=m.session.$mode.findTokens(o,"keyword",!0);C.hasOwnProperty("value")?(v=!1,k=C.value):(v=" FORMAT JSON ",w=!0),S.hasOwnProperty("value")&&(x=S.value),"select"!=x&&"with"!=x&&(v=!1,w=!1),h.push({sql:o,index:d,format:v,setedformat:w,keyword:x,storage:k,drawCommand:s,itemRange:t.range,qid:i.makeQueryId()}),d++}}}),console.groupEnd("Execute query"),h.length&&(t.vars.currentTab.progress={},t.vars.currentTab.statistics||(t.vars.currentTab.statistics=[]),t.executeQuery(h[0],h,f))},t.setTheme=function(e){t.vars.theme=e,t.vars.tabs.forEach(function(t){return t.editor.setTheme("ace/theme/"+e)}),r.set("editorTheme",e)},t.reloadCache=function(){console.log("reloadCache"),i.resetDatabaseStructure(),c.show(c.simple().content("Reload page - for reset cache").theme(l.theme).position("bottom right"))},t.selectDatabase=function(e,a){e&&(i.setDatabase(e),t.vars.db!=e&&(t.vars.db=e,t.AceEditorInLoad||(t.aceLoadDatabaseFields(),t.aceApply(!1))))},t.insertWordInEditor=function(e){var a=t.vars.currentTab.editor,n=a.getCursorPosition();n.column+=e.length,a.clearSelection(),a.insert(e),t.vars.currentTab.sql=a.getValue(),d(function(){a.focus(),a.moveCursorToPosition(n)})},t.aceLoadDatabaseFields=function(){var e=t.vars.db;window.aceJSRules.fieldsList=[],i.databaseStructure(function(t){window.aceJSRules.fieldsList=t.getAllFieldsInDatabase(e)})},t.aceLoadDatabaseStructure=function(){var e=t.vars.db;window.aceJSRules.tables=[],i.databaseStructure(function(a){t.vars.databasesList=a.getDatabases(),Object.keys(a.getUniqueDatabaseTables()).forEach(function(e){window.aceJSRules.tables.push(e)}),window.aceJSRules.fieldsList=a.getAllFieldsInDatabase(e)})},t.loadInAce=function(e){e.session.setMode({path:"ace/mode/clickhouse"});for(var t in window.aceJSRules.builtinFunctions){var a=window.aceJSRules.builtinFunctions[t];e.session.$mode.$highlightRules.addCompletionsFunctions(a)}e.session.$mode.$highlightRules.addArrayCompletions(window.aceJSRules.tables,"[table]","table");for(var n in window.aceJSRules.dictionaries){var r=window.aceJSRules.dictionaries[n];e.session.$mode.$highlightRules.addCompletionsDictionaries(r)}for(var i in window.aceJSRules.fieldsList){var s=window.aceJSRules.fieldsList[i];e.session.$mode.$highlightRules.addCompletionsTableFiled(s)}var o=g.getCompletions(),c=p.getCompletions();e.session.$mode.$highlightRules.addArrayCompletions(o,"[var]","var"),e.session.$mode.$highlightRules.addArrayCompletions(c,"[snippet]","snippet"),e.session.bgTokenizer.start(0)},t.aceApply=function(e){e?(console.log(""),t.loadInAce(e)):t.vars.tabs.forEach(function(e){e.editor&&(console.log(""),t.loadInAce(e.editor))}),a.$watch("currentDatabase",t.selectDatabase)},t.changeRootSelectDatabase=function(e){a.currentDatabase!=e&&(a.currentDatabase=e)},t.aceLoadDictionaries=function(){t.vars.isDictionariesLoad||(window.aceJSRules.dictionaries=[],t.vars.dictionaries=[],window.aceJSRules.builtinFunctions=[],t.vars.isDictionariesLoad=!0,i.databaseStructure(function(e){e.getFunctions().forEach(function(e){if(window.aceJSRules.builtinFunctions.push({name:e.name,isaggr:e.is_aggregate,score:101,comb:!1,origin:e.name}),e.is_aggregate){var t={name:e.name+"If",isaggr:e.is_aggregate,score:3,comb:"If",origin:e.name};window.aceJSRules.builtinFunctions.push(t),t={name:e.name+"Array",isaggr:e.is_aggregate,score:2,comb:"Array",origin:e.name},window.aceJSRules.builtinFunctions.push(t),t={name:e.name+"State",isaggr:e.is_aggregate,score:1,comb:"State",origin:e.name},window.aceJSRules.builtinFunctions.push(t)}}),e.getDictionaries().forEach(function(e){var a=e.name;a=a.replace(/^.*\./gm,""),"news"!=a&&(a=a.replace(/s$/gm,"")),a=a?a.toLowerCase()+"_id":"ID";var n="dictGet"+e["attribute.types"]+"('"+e.name+"','"+e["attribute.names"]+"',to"+e.key+"( "+a+" ) ) AS "+e["attribute.names"]+",";window.aceJSRules.dictionaries.push({dic:n,title:"dic_"+e.name+"."+e["attribute.names"]}),t.vars.dictionaries.push({dic:n,title:e.name+"."+e["attribute.names"]+" as "+e["attribute.types"]})})}))};for(var x=function(e){t.vars.tabs.length>=e&&(t.vars.currentTab=t.vars.tabs[e],t.vars.selectedTab=e,d(function(){t.vars.currentTab.editor.focus()}))},C=function(){t.vars.selectedTab>0&&x(t.vars.selectedTab-1)},S=function(){t.vars.selectedTabD;D++)A(D);m.add({combo:t.vars.disableHotKeyCmdLeft?"ctrl+shift+alt+right":"ctrl+right",callback:S}),m.add({combo:t.vars.disableHotKeyCmdLeft?"ctrl+shift+alt+left":"ctrl+left",callback:C}),m.add({combo:"ctrl+shift+f",callback:T}),t.aceLoaded=function(e){t.AceEditorInLoad=!0,a.currentDatabase&&t.selectDatabase(a.currentDatabase),t.aceLoadDictionaries(),t.aceLoadDatabaseStructure(),t.aceLoadDatabaseFields();var n=t.vars.tabs.find(function(e){return!e.editor})||t.vars.currentTab;n.editor=e,e.$blockScrolling=1/0,e.setOptions({fontSize:t.vars.fontSize+"px",enableBasicAutocompletion:!0,behavioursEnabled:!0,wrapBehavioursEnabled:!0,highlightSelectedWord:!0,showGutter:!0,enableLiveAutocompletion:t.vars.enableLiveAutocompletion,liveAutocompletionDelay:500,liveAutocompletionThreshold:1}),e.setTheme("ace/theme/"+t.vars.theme),e.session.setUseWrapMode(h.get("useWrapMode")),e.commands.addCommand({name:"runCurrentCommand",bindKey:{win:"Ctrl-Enter",mac:"Command-Enter"},exec:function(){t.execute("current",n)}}),e.commands.addCommand({name:"removeLiness",bindKey:{win:"Ctrl-Y",mac:"Cmd-Y"},exec:function(e){e.removeLines()}}),e.commands.addCommand({name:"collapseAll",bindKey:{win:"Ctrl-Shift--",mac:"Command+Shift+-"},exec:function(e){e.session.$mode.collapseAll(e.session)}}),e.commands.addCommand({name:"unfold",bindKey:{win:"Ctrl-Shift-+",mac:"Command+Shift+="},exec:function(e){e.session.unfold()}}),e.commands.addCommand({name:"runAllCommand",bindKey:{win:"Shift-Ctrl-Enter",mac:"Shift-Command-Enter"},exec:function(){t.execute("all",n)}});for(var r=function(t){e.commands.addCommand({name:"selecttab"+t,bindKey:{win:"Ctrl-Shift-"+(t+1),mac:"Command-Shift-"+(t+1)},exec:function(){return x(t)}})},i=0;9>i;i++)r(i);e.commands.addCommand({name:"selectnexttab",bindKey:{win:t.vars.disableHotKeyCmdLeft?"Shift-Alt-Ctrl-Right":"Ctrl-Right",mac:t.vars.disableHotKeyCmdLeft?"Shift-Alt-Command-Right":"Command-Right"},exec:S}),e.commands.addCommand({name:"selectprevtab",bindKey:{win:t.vars.disableHotKeyCmdLeft?"Shift-Alt-Ctrl-Left":"Ctrl-Left",mac:t.vars.disableHotKeyCmdLeft?"Shift-Alt-Command-Left":"Command-Left"},exec:C}),e.commands.addCommand({name:"formatcode",bindKey:{win:"Ctrl-Shift-F",mac:"Command-Shift-F"},exec:T}),e.setValue(n.sql),e.clearSelection(),e.focus(),e.selection.moveTo(0,0),e.on("changeSelection",function(){d(function(){n.buttonTitle=""!==e.getSelectedText()?"Run selected ⌘ + ⏎":"Run all ⇧ + ⌘ + ⏎",n.originalSql&&(n.changed=n.originalSql!=n.sql)})}),t.AceEditorInLoad=!1,t.aceApply(e)},t.save=function(e,a){return o.show(o.prompt().title("Save SQL as?").placeholder("Title").initialValue(e.name).targetEvent(a).ok("Save").cancel("")).then(function(a){var n=t.vars.sqlHistory.findIndex(function(t){return t.name==e.name});-1!=n?(t.vars.sqlHistory[n].sql=e.sql,t.vars.sqlHistory[n].name=a):t.vars.sqlHistory.push({sql:e.sql,name:a}),e.originalSql=e.sql,e.name=a,r.set(f,t.vars.sqlHistory),k()})},t.load=function(e){t.vars.currentTab.sql=e.sql,t.vars.currentTab.originalSql=e.sql,t.vars.currentTab.name=e.name,t.vars.currentTab.editor.setValue(e.sql),t.aceApply(t.vars.currentTab.editor)},t.getExportData=function(t){return t.data.data.map(function(t){return Object.keys(t).map(function(a){return e.isArray(t[a])?t[a].join(", "):t[a]})})},t.getExportHeaders=function(e){return e.data.meta.map(function(e){return e.name})},t.addTab=function(){t.vars.currentTab={name:"new SQL",sql:"",buttonTitle:"Run ⌘ + ⏎",format:{},editor:null,results:[],selectedResultTab:0},t.vars.tabs.push(t.vars.currentTab),k()},t.changeTab=function(e){k(),t.vars.currentTab=e},t.removeTab=function(e,a){a.stopPropagation();var n=function(){t.vars.tabs.splice(t.vars.tabs.indexOf(e),1),t.vars.tabs.length==t.vars.selectedTab&&t.vars.selectedTab--};e.changed?o.show(o.confirm().title("SQL was changed. Save it before exit?").targetEvent(a).ok("Yes").cancel("No")).then(function(){var a=t.vars.sqlHistory.findIndex(function(t){return t.name==e.name});-1!=a&&(t.vars.sqlHistory[a].sql=e.sql,t.vars.sqlHistory[a].name=e.name),r.set(f,t.vars.sqlHistory),n()},n):n()},t.removeResult=function(e,t,a){},a.$on("handleBroadcastUpdateVarsAndSnippets",function(e,a){t.aceApply()}),a.$on("handleBroadcastInsertInActive",function(e,a){a.value&&t.insertWordInEditor(" "+a.value+" ")}),t.toggleSidenav=function(e){s(e).toggle()},t.removeHistory=function(e,a){a.preventDefault();var n=t.vars.sqlHistory.indexOf(e);-1!=n&&o.show(o.confirm().title("Delete "+e.name+"?").targetEvent(a).ok("Yes").cancel("No")).then(function(){t.vars.sqlHistory.splice(n,1),r.set(f,t.vars.sqlHistory)})},t.setSql=function(e){t.vars.currentTab.sql=e,t.toggleSidenav("log"),t.vars.currentTab.editor.setValue(e),d(function(){return t.vars.currentTab.editor.focus()},500)},t.changeTabName=function(e,a){a.stopPropagation(),o.show(o.prompt().title("Title tab").placeholder("title").initialValue(e.name).targetEvent(a).ok("Apply").cancel("Cancel")).then(function(a){var n=t.vars.sqlHistory.findIndex(function(t){return t.name==e.name});-1!=n&&(e.originalSql=e.sql,t.vars.sqlHistory[n].name=a,r.set(f,t.vars.sqlHistory)),e.name=a,k()})},t.vars.saveTabs?(t.vars.tabs=r.get(v),_.isArray(t.vars.tabs)||(t.vars.tabs=[]),t.vars.tabs.length>0?d(function(){return t.vars.currentTab=t.vars.tabs[0]},500):t.addTab()):(r.set(v,[]),t.addTab()),t.$on("$destroy",function(){i.setDatabase(a.currentDatabase),w(),n.onbeforeunload=null}),t.rightAceMenuList=[],t.showDialogUpload=function(t,a){function n(e,t){e.vars={UploadCsv:{content:null,header:!0,headerVisible:!0,separator:",",separatorVisible:!0,result:null,encoding:"ISO-8859-1",encodingVisible:!0,uploadButtonLabel:"Upload",callback:function(e){t.hide()}}},e.$watch("vars.UploadCsv.result",function(e){e&&t.hide(e)}),e.hide=function(){t.hide()},e.cancel=function(){t.cancel()}}n.$inject=["$scope","$mdDialog"],o.show({controller:n,templateUrl:"app/sql/showDialogUpload.html",parent:e.element(document.body),targetEvent:a,clickOutsideToClose:!0}).then(function(e){if(e&&t&&t.tables){var a=DataProvider.convertArrayToDataProvider(e,"csv");t.tables.push(new WidgetTable(a))}},function(){})},t.rightMenuProcess=function(e){t.vars.currentTab.sql=t.vars.currentTab.editor.getValue();var a=t.vars.currentTab.editor.session;if(t.vars.currentTab.editor.resize(),"Snippet"==e){var n=t.vars.currentTab.editor.getSelectedText();n&&(p.add(n),t.aceApply())}else"AutoFormat"==e?T():"Expand"==e?a.unfold():"Collapse All"==e?a.$mode.collapseAll(a):"Collapse"==e&&a.foldAll();t.vars.currentTab.editor.focus()}}e.module(t.app.name).controller("SqlController",a),a.$inject=["$scope","$rootScope","$window","localStorageService","API","$mdSidenav","$mdDialog","$mdToast","ThemeService","$timeout","$filter","hotkeys","Preference","Snippets","Variables"]}(angular,smi2),/* * Licensed under the Apache License, Version 2.0 Copyright 2017 Igor Strykhar,SMI2 LLC and other contributors */ function(e,t,a){function n(t,a,n,r,i,s,o,c,l,d){function u(e,t){e.editor=!1,e.hide=function(){t.hide()},e.cancel=function(){t.cancel()},e.applyCode=function(){console.log("applyCODE")},e.aceLoadedEditor=function(t){e.editor=t,console.warn("aceLoadedEditor"),t.$blockScrolling=1/0,t.session.setUseWrapMode(!0),t.setOptions({fontSize:"14px",enableBasicAutocompletion:!0,behavioursEnabled:!0,wrapBehavioursEnabled:!0,highlightSelectedWord:!0,showGutter:!0,enableLiveAutocompletion:!0,liveAutocompletionDelay:500,liveAutocompletionThreshold:1}),t.commands.addCommand({name:"runCurrentCommand",bindKey:{win:"Ctrl-Enter",mac:"Command-Enter"},exec:function(){e.applyCode()}}),t.setTheme("ace/theme/cobalt"),t.setValue("{}"),t.clearSelection(),t.focus(),t.selection.moveTo(0,0),t.session.setMode({path:"ace/mode/javascript"})}}u.$inject=["$scope","$mdDialog"],t.tabsRender=!0,t.vars={rsw:0,uiTheme:l.themeObject,isChartReady:!1,staticGrid:!0,stackType:"false",isDark:l.isDark(),active:{table:!1,pivot:!1,draw:!1}},t.staticGrid=!0,t.gridStackOptions={cellHeight:200,verticalMargin:3,disableDrag:!0},t.switchStaticGrid=function(){t.vars.staticGrid=!t.vars.staticGrid,t.staticGrid=t.vars.staticGrid,console.info("staticGrid",t.staticGrid)},t.initNoTabs=function(){t.vars.active.table=!0,t.vars.active.draw=!0,t.vars.active.pivot=!0},t.initTableTab=function(){console.warn("initTableTab!!!!"),t.vars.active.table=!0},t.initDrawTab=function(){t.vars.active.draw=!0},t.onResizeStop=function(){},t.openEditor=function(a){o.show({controller:u,templateUrl:"app/sql/PlotlyEditor.tmpl.html",parent:e.element(document.body),locals:{w:a}}).then(function(e){t.status='You said the information was "'+e+'".'},function(){t.status="You cancelled the dialog."})},t.openEditorPlotLy=function(e){console.log("openEditorPlotLy",e),t.openEditor(e)},t.initPivotTab=function(){t.vars.active.pivot=!0}}e.module(t.app.name).controller("RenderCtrl",n),n.$inject=["$scope","$rootScope","$window","localStorageService","API","$mdSidenav","$mdDialog","$mdToast","ThemeService","$timeout"]}(angular,smi2,window.$),/* @@ -20,7 +20,7 @@ function(e,t){function a(e){var t=this;this.snippets={},this.constructor=functio function(e,t){function a(e,t){var a=this,n={limitRows:5e3,limitTimes:5,fontSize:14,editorTheme:"cobalt",theme:"dark",saveTabs:!0,liveAutocompletion:!0,disableAutohelp:!1,disableHotKeyCmdLeft:!0,delimiter:";;",liveAutocompletionDelay:500,liveAutocompletionThreshold:1,useWrapMode:!0,showInvisibles:!1},r=["ligth","dark"],i=["ambiance","eclipse","mono_industrial","tomorrow_night_blue","chaos","github","monokai","tomorrow_night_bright","chrome","idle_fingers","pastel_on_dark","tomorrow_night_eighties","clouds","iplastic","solarized_dark","tomorrow_night","clouds_midnight","katzenmilch","solarized_light","twilight","cobalt","kr_theme","sqlserver","vibrant_ink","crimson_editor","kuroir","terminal","xcode","dawn","merbivore","textmate","dreamweaver","merbivore_soft","tomorrow","dracula"];this.current={},this.constructor=function(){var t=e.get("UserPreference");a.current=_.merge(n,t)},this.constructor(),this.getThemes=function(){return r},this.getEditorThemes=function(){return i},this.apply=function(e){_.forEach(e,function(e,t){a.set(t,e)}),a.save()},this.save=function(){console.log("localStorageService,set",a.current),e.set("UserPreference",a.current)},this.getCurrentState=function(){return a.current},this.get=function(e){return n[e]},this.set=function(e,t){("limitRows"==e||"limitTimes"==e||"fontSize"==e||"liveAutocompletionDelay"==e||"liveAutocompletionThreshold"==e)&&(t=parseInt(t)),a.current[e]=t}}e.module(t.app.name).service("Preference",a),a.$inject=["localStorageService","ThemeService"]}(angular,smi2),function(e,t){function a(e,t){return{responseError:function(a){return 401==a.status&&t.get("$state").go("login"),e.reject(a)}}}e.module(t.app.name).service("HttpInterceptor",a),a.$inject=["$q","$injector"]}(angular,smi2),/* * Licensed under the Apache License, Version 2.0 Copyright 2017 Igor Strykhar,Ivan Kudinov,SMI2 LLC and other contributors */ -function(e,t){function a(t,a,n,r,i){var s=this,o="currentBaseConfig",c=new DatabaseStructure,l=null,d={},u=n.get(o);u&&u.host&&(d=u),this.setConnection=function(t){n.set(o,t),d=e.copy(t)},this.clear=function(){l=null,d={},n.set(o,{}),c=new DatabaseStructure},this.hashCode=function(e){return e.split("").reduce(function(e,t){return e=(e<<5)-e+t.charCodeAt(0),e&e},0)},this.DS_CacheKey=function(){var e="_databaseStructure:"+JSON.stringify(d);return e=s.hashCode(e)},this.DS_storeCache=function(e,t,a,r,i){var o={columns:e,tables:t,databases:a,dictionaries:r,functions:i,ttl:Date.now()};return n.set(s.DS_CacheKey(),o)},this.DS_fetchFromCache=function(){var e=n.get(s.DS_CacheKey());if(!e||!e.ttl)return!1;var t=(Date.now()-e.ttl)/36e5;return t>1.5?!1:e&&e.functions&&e.functions.length>1?(c.init(e.columns,e.tables,e.databases,e.dictionaries,e.functions),!0):!1},this.memory=function(e){},this.resetDatabaseStructure=function(){console.log("reset databaseStructure"),n.set("_databaseStructure:"+s.getHost()+":"+s.getLogin(),[])},this.databaseStructure=function(e,t){return!t&&c.isInit()?e(c):!t&&s.DS_fetchFromCache()&&c.isInit()?(console.info("restore from cache : database Structure!"),e(c)):(t&&(c=new DatabaseStructure),console.time("Load Database Structure!"),void s.fetchQuery("SELECT * FROM system.columns").then(function(t){s.fetchQuery("SELECT database,name,engine FROM system.tables").then(function(a){s.fetchQuery("SELECT name FROM system.databases").then(function(n){s.fetchQuery("SELECT name,key,attribute.names,attribute.types from system.dictionaries ARRAY JOIN attribute ORDER BY name,attribute.names",null).then(function(r){s.fetchQuery("SELECT name,is_aggregate from system.functions",null).then(function(i){return console.timeEnd("Load Database Structure!"),s.DS_storeCache(t.data,a.data,n.data,r.data,i.data),c.init(t.data,a.data,n.data,r.data,i.data),e(c)},function(e){throw e})},function(e){throw e})},function(e){throw e})},function(e){throw e})},function(e){throw e}))},this.getHost=function(){return d.host},this.getPassword=function(){return d.password},this.getLogin=function(){return d.login},this.makeQueryId=function(){for(var e="",t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",a=0;8>a;a++)e+=t.charAt(Math.floor(Math.random()*t.length));return e},this.isTabixServer=function(){return d.tabix&&d.tabix.server?!0:!1},this.tabixQuery=function(e){return console.info("[request]>",e),t(req).then(function(e){return defer.resolve(e.data)},function(e){return defer.reject(e)}),defer.promise},this._tabixRequest=function(t,a){var n={version:1,auth:{login:d.tabix.login,password:d.tabix.password,confid:d.tabix.confid}};t=Object.assign(n,t);var r=d.tabix.server+"/"+a;return{method:"POST",data:t,url:r,transformResponse:function(t,a,n){try{return JSON.parse(t)}catch(r){return t?t:"\nStatus:"+n+"\nHeaders:"+e.toJson(a())}}}},this.makeSqlQuery=function(e,t){var a="";return t!==!1?(t=t||" FoRmAt JSON","null"==t&&(t=""),a=e+"\n\n"+t):a=e,a},this.makeUrlRequest=function(e,t){var a="",n="";d.host.indexOf("://")>0||0==d.host.indexOf("/")||(n="http://"),a=n+d.host,a+="/?",d.rouser||(a+="add_http_cors_header=1&log_queries=1&output_format_json_quote_64bit_integers=1",d.NotCH1_1_54276||(a+="&output_format_json_quote_denormals=1"));return d.baseauth||(a+=d.password?"&user="+encodeURIComponent(d.login)+"&password="+encodeURIComponent(d.password):"&user="+encodeURIComponent(d.login)),e&&(a+="&database="+encodeURIComponent(l)),t&&(a+="&"+t),d.params&&(a+="&"+d.params),a},this.fetchQuery=function(e,t,a,n){var r=s.makeSqlQuery(e,a),i=s.makeUrlRequest(t,n),o={mode:"cors",method:"post",headers:{"Content-type":"application/x-www-form-urlencoded; charset=UTF-8"},body:r},c=new Request(i,o);return fetch(c).then(function(e){var t=e.headers.get("content-type");return t.includes("text/plain")&&200==e.status&&"ok"==e.statusText.toLowerCase()?"OK":t&&t.includes("application/json")&&e.status>=200&&e.status<300?Promise.resolve(e):e.text().then(Promise.reject.bind(Promise))}).then(function(e){return"OK"===e?"OK":e.json()},function(e){return Promise.reject(e)})},this.query=function(e,n,r,i){var o=a.defer(),c=s.makeSqlQuery(e,n),l=s.makeUrlRequest(r,i),u=!1;return s.isTabixServer()?u=s._tabixRequest({query:c},"query"):(u={method:"POST",data:c,headers:{"Content-Type":"application/x-www-form-urlencoded"},url:l,cache:!1},d.baseauth&&(u.headers.Authorization="Basic "+window.btoa(d.login+":"+d.password))),console.info("SQL>",l,c,u),t(u).then(function(e){return o.resolve(e.data)},function(e){return o.reject(e)}),o.promise},this.getConnectionInfo=function(){return d},this.setDatabase=function(e){return l=e},this.getDatabase=function(){return l},this.dataToCreateTable=function(e){var t="\nCREATE TABLE x (\n",a=[];return e.meta.forEach(function(e){return a.push(" "+e.name+" "+e.type)}),t+a.join(",\n")+"\n ) ENGINE = Log \n;;\n"},this.dataToHtml=function(e){var t='',a=[];return e.meta.forEach(function(e){t+="",a.push(e.name)}),e.data.forEach(function(e){t+="",a.forEach(function(a){t+=""}),t+=""}),t+="
"+r(e.name)+'\n
'+r(e.type)+"
\n
"+r(e[a])+"
"},this.dataToHandsontable=function(e){var t=[],a=[];return e.meta.forEach(function(e){t.push(e.name);var n={};switch(n.type="text",n.width=100,e.type){case"Date":n.width=90,n.type="date",n.dateFormat="MM/DD/YYYY";break;case"DateTime":n.width=150,n.type="time",n.timeFormat="HH:mm:ss";break;case"Int32":n.width=80,n.type="numeric";break;case"Float64":n.width=80,n.type="numeric",n.format="0,0.0000";break;case"UInt32":n.width=80,n.type="numeric";break;case"String":n.width=180}n.data=e.name,a.push(n)}),{colHeaders:t,columns:a,data:e.data,currentRowClassName:"currentRow",currentColClassName:"currentCol"}}}e.module(t.app.name).service("API",a),a.$inject=["$http","$q","localStorageService","$sanitize","ThemeService"]}(angular,smi2);var DatabaseStructure=function(){function e(){_classCallCheck(this,e),this._init=!1,this.uciq_fields=[],this.all_fields=[],this.all_db_fields=[],this.uciq_dbtables=[]}return _createClass(e,[{key:"init",value:function(e,t,a,n,r){var i=this;console.log("Try init DS...."),this._init||(this.columns=e,this.tables=t,this.databases=a,this.functions=r,this.dictionaries=n,this.columns.forEach(function(e){!angular.isUndefined(e.default_kind)&&angular.isUndefined(e.default_type)&&(e.default_type=e.default_kind),i.all_fields[e.database+"."+e.table]||(i.all_fields[e.database+"."+e.table]=[]),i.all_db_fields[e.database]||(i.all_db_fields[e.database]=[]),i.all_db_fields[e.database][e.table]||(i.all_db_fields[e.database][e.table]=[]),i.all_db_fields[e.database][e.table].push(e),i.all_fields[e.database+"."+e.table].push({name:e.name,type:e.type,active:!0}),i.uciq_fields[e.database]||(i.uciq_fields[e.database]=[]),i.uciq_fields[e.database].push(e),i.uciq_dbtables[e.database+"."+e.table]=1}),this._init=!0)}},{key:"isInit",value:function(){return this._init&&this.functions&&this.functions.length>1}},{key:"getTables",value:function(){return this.tables}},{key:"getDatabases",value:function(){return this.databases}},{key:"getFieldsByDatabase",value:function(e){return this.all_db_fields[e]}},{key:"getFunctions",value:function(){return this.functions}},{key:"getFields",value:function(){return this.all_fields}},{key:"getUniqueDatabaseTables",value:function(){return this.uciq_dbtables}},{key:"getAllFieldsInDatabase",value:function(e){return this.uciq_fields[e]}},{key:"getDictionaries",value:function(){return this.dictionaries}},{key:"getColumns",value:function(){return this.columns}}]),e}();/* +function(e,t){function a(t,a,n,r,i){var s=this,o="currentBaseConfig",c=new DatabaseStructure,l=null,d={},u=n.get(o);u&&u.host&&(d=u),this.setConnection=function(t){n.set(o,t),d=e.copy(t)},this.clear=function(){l=null,d={},n.set(o,{}),c=new DatabaseStructure},this.hashCode=function(e){return e.split("").reduce(function(e,t){return e=(e<<5)-e+t.charCodeAt(0),e&e},0)},this.DS_CacheKey=function(){var e="_databaseStructure:"+JSON.stringify(d);return e=s.hashCode(e)},this.DS_storeCache=function(e,t,a,r,i){var o={columns:e,tables:t,databases:a,dictionaries:r,functions:i,ttl:Date.now()};return n.set(s.DS_CacheKey(),o)},this.DS_fetchFromCache=function(){var e=n.get(s.DS_CacheKey());if(!e||!e.ttl)return!1;var t=(Date.now()-e.ttl)/36e5;return t>1.5?!1:e&&e.functions&&e.functions.length>1?(c.init(e.columns,e.tables,e.databases,e.dictionaries,e.functions),!0):!1},this.memory=function(e){},this.resetDatabaseStructure=function(){console.log("reset databaseStructure"),n.set("_databaseStructure:"+s.getHost()+":"+s.getLogin(),[])},this.databaseStructure=function(e,t){return!t&&c.isInit()?e(c):!t&&s.DS_fetchFromCache()&&c.isInit()?(console.info("restore from cache : database Structure!"),e(c)):(t&&(c=new DatabaseStructure),console.time("Load Database Structure!"),void s.fetchQuery("SELECT * FROM system.columns").then(function(t){s.fetchQuery("SELECT database,name,engine FROM system.tables").then(function(a){s.fetchQuery("SELECT name FROM system.databases").then(function(n){s.fetchQuery("SELECT name,key,attribute.names,attribute.types from system.dictionaries ARRAY JOIN attribute ORDER BY name,attribute.names",null).then(function(r){s.fetchQuery("SELECT name,is_aggregate from system.functions",null).then(function(i){return console.timeEnd("Load Database Structure!"),s.DS_storeCache(t.data,a.data,n.data,r.data,i.data),c.init(t.data,a.data,n.data,r.data,i.data),e(c)},function(e){throw e})},function(e){throw e})},function(e){throw e})},function(e){throw e})},function(e){throw e}))},this.getHost=function(){return d.host},this.getPassword=function(){return d.password},this.getLogin=function(){return d.login},this.makeQueryId=function(){for(var e="",t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",a=0;8>a;a++)e+=t.charAt(Math.floor(Math.random()*t.length));return e},this.isTabixServer=function(){return d.tabix&&d.tabix.server?!0:!1},this.tabixQuery=function(e){return console.info("[request]>",e),t(req).then(function(e){return defer.resolve(e.data)},function(e){return defer.reject(e)}),defer.promise},this._tabixRequest=function(t,a){var n={version:1,auth:{login:d.tabix.login,password:d.tabix.password,confid:d.tabix.confid}};t=Object.assign(n,t);var r=d.tabix.server+"/"+a;return{method:"POST",data:t,url:r,transformResponse:function(t,a,n){try{return JSON.parse(t)}catch(r){return t?t:"\nStatus:"+n+"\nHeaders:"+e.toJson(a())}}}},this.makeSqlQuery=function(e,t){var a="";return t!==!1?(t=t||" FoRmAt JSON","null"==t&&(t=""),a=e+"\n\n"+t):a=e,a},this.makeUrlRequest=function(e,t){var a="",n="";d.host.indexOf("://")>0||0==d.host.indexOf("/")||(n="http://"),a=n+d.host,a+="/?",a+="add_http_cors_header=1&log_queries=1&output_format_json_quote_64bit_integers=1",d.NotCH1_1_54276||(a+="&output_format_json_quote_denormals=1");return d.baseauth||(a+=d.password?"&user="+encodeURIComponent(d.login)+"&password="+encodeURIComponent(d.password):"&user="+encodeURIComponent(d.login)),e&&(a+="&database="+encodeURIComponent(l)),t&&(a+="&"+t),d.params&&(a+="&"+d.params),a},this.fetchQuery=function(e,t,a,n){var r=s.makeSqlQuery(e,a),i=s.makeUrlRequest(t,n),o={mode:"cors",method:"post",headers:{"Content-type":"application/x-www-form-urlencoded; charset=UTF-8"},body:r},c=new Request(i,o);return fetch(c).then(function(e){var t=e.headers.get("content-type");return t.includes("text/plain")&&200==e.status&&"ok"==e.statusText.toLowerCase()?"OK":t&&t.includes("application/json")&&e.status>=200&&e.status<300?Promise.resolve(e):e.text().then(Promise.reject.bind(Promise))}).then(function(e){return"OK"===e?"OK":e.json()},function(e){return Promise.reject(e)})},this.query=function(e,n,r,i){var o=a.defer(),c=s.makeSqlQuery(e,n),l=s.makeUrlRequest(r,i),u=!1;return s.isTabixServer()?u=s._tabixRequest({query:c},"query"):(u={method:"POST",data:c,headers:{"Content-Type":"application/x-www-form-urlencoded"},url:l,cache:!1},d.baseauth&&(u.headers.Authorization="Basic "+window.btoa(d.login+":"+d.password))),console.info("SQL>",l,c,u),t(u).then(function(e){return o.resolve(e.data)},function(e){return o.reject(e)}),o.promise},this.getConnectionInfo=function(){return d},this.setDatabase=function(e){return l=e},this.getDatabase=function(){return l},this.dataToCreateTable=function(e){var t="\nCREATE TABLE x (\n",a=[];return e.meta.forEach(function(e){return a.push(" "+e.name+" "+e.type)}),t+a.join(",\n")+"\n ) ENGINE = Log \n;;\n"},this.dataToHtml=function(e){var t='',a=[];return e.meta.forEach(function(e){t+="",a.push(e.name)}),e.data.forEach(function(e){t+="",a.forEach(function(a){t+=""}),t+=""}),t+="
"+r(e.name)+'\n
'+r(e.type)+"
\n
"+r(e[a])+"
"},this.dataToHandsontable=function(e){var t=[],a=[];return e.meta.forEach(function(e){t.push(e.name);var n={};switch(n.type="text",n.width=100,e.type){case"Date":n.width=90,n.type="date",n.dateFormat="MM/DD/YYYY";break;case"DateTime":n.width=150,n.type="time",n.timeFormat="HH:mm:ss";break;case"Int32":n.width=80,n.type="numeric";break;case"Float64":n.width=80,n.type="numeric",n.format="0,0.0000";break;case"UInt32":n.width=80,n.type="numeric";break;case"String":n.width=180}n.data=e.name,a.push(n)}),{colHeaders:t,columns:a,data:e.data,currentRowClassName:"currentRow",currentColClassName:"currentCol"}}}e.module(t.app.name).service("API",a),a.$inject=["$http","$q","localStorageService","$sanitize","ThemeService"]}(angular,smi2);var DatabaseStructure=function(){function e(){_classCallCheck(this,e),this._init=!1,this.uciq_fields=[],this.all_fields=[],this.all_db_fields=[],this.uciq_dbtables=[]}return _createClass(e,[{key:"init",value:function(e,t,a,n,r){var i=this;console.log("Try init DS...."),this._init||(this.columns=e,this.tables=t,this.databases=a,this.functions=r,this.dictionaries=n,this.columns.forEach(function(e){!angular.isUndefined(e.default_kind)&&angular.isUndefined(e.default_type)&&(e.default_type=e.default_kind),i.all_fields[e.database+"."+e.table]||(i.all_fields[e.database+"."+e.table]=[]),i.all_db_fields[e.database]||(i.all_db_fields[e.database]=[]),i.all_db_fields[e.database][e.table]||(i.all_db_fields[e.database][e.table]=[]),i.all_db_fields[e.database][e.table].push(e),i.all_fields[e.database+"."+e.table].push({name:e.name,type:e.type,active:!0}),i.uciq_fields[e.database]||(i.uciq_fields[e.database]=[]),i.uciq_fields[e.database].push(e),i.uciq_dbtables[e.database+"."+e.table]=1}),this._init=!0)}},{key:"isInit",value:function(){return this._init&&this.functions&&this.functions.length>1}},{key:"getTables",value:function(){return this.tables}},{key:"getDatabases",value:function(){return this.databases}},{key:"getFieldsByDatabase",value:function(e){return this.all_db_fields[e]}},{key:"getFunctions",value:function(){return this.functions}},{key:"getFields",value:function(){return this.all_fields}},{key:"getUniqueDatabaseTables",value:function(){return this.uciq_dbtables}},{key:"getAllFieldsInDatabase",value:function(e){return this.uciq_fields[e]}},{key:"getDictionaries",value:function(){return this.dictionaries}},{key:"getColumns",value:function(){return this.columns}}]),e}();/* * Copyright (C) 2017 IgorStrykhar in SMI2 * All rights reserved. */ @@ -40,8 +40,8 @@ var WidgetPivot=function(e){function t(e,a){_classCallCheck(this,t);var n=_possi var WidgetDraw=function(e){function t(e,a,n,r){_classCallCheck(this,t);var i=_possibleConstructorReturn(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e,a,n,r));return i.type="draw",i.error||i.text?_possibleConstructorReturn(i):(i.library=!1,i._list={PLOTLY:DrawPlotly,HEATMAP:DrawEchartsHeatmap,CALENDAR:DrawEchartsCalendar,RAW:DrawEchartsMap,BAR:DrawEchartsBar,RIVER:DrawEchartsRiver,MAP:DrawEchartsMap,GMAPS:DrawGoogleMap,TREEMAP:DrawEchartsTreemap,SANKEYS:DrawEchartsSunkeys,CHART:DrawEchartsChart,GRIDCHART:DrawEchartsGridChart,TEXT:DrawText,D3:DrawD3,C3:DrawC3},i.init=i.getChartClass(),i.sizeX||i.sizeY||(i.sizeX=6,i.sizeY=3,"TEXT"==i.drawType&&(i.sizeX=1,i.sizeY=2),console.info("this.data.countAll",i.data.countAll),1==i.data.countAll&&(i.sizeX=12,i.sizeY=3)),i)}return t.$inject=["DataProvider","draw","sizeX","sizeY"],_inherits(t,e),_createClass(t,[{key:"onResize",value:function(){this._draw&&this._draw.onResize()}},{key:"getChartClass",value:function(){return this.drawType||(this.drawType="CHART",console.error("Un support DrawType:null")),this._list[this.drawType]?!0:(console.error("Un support DrawType:"+this.drawType),!1)}},{key:"draw",get:function(){return this.drawType&&!this._draw&&(this._draw=new this._list[this.drawType](this,this.drawType)),this._draw}}]),t}(Widget);angular.module(smi2.app.name).service("WidgetDraw",WidgetDraw);/* * Licensed under the Apache License, Version 2.0 Copyright 2017 Igor Strykhar,SMI2 LLC and other contributors */ -var HandsTable=function(){function e(t,a,n){_classCallCheck(this,e),this.isDarkTheme=t,this.meta=a,this.Preset=n}return e.$inject=["isDark","metaData","Preset"],_createClass(e,[{key:"_handsRenderer",value:function(e,t,a,n,r,i,s){"numeric"==s.type?null==i||"-nan"==i||"inf"==i||"+nan"==i||"+inf"==i||"-inf"==i||"nan"==i?(null==i&&(arguments[5]="NULL"),t.style.color="black",t.style.background="red",Handsontable.renderers.TextRenderer.apply(this,arguments)):Handsontable.renderers.NumericRenderer.apply(this,arguments):"date"==s.type||"time"==s.type?(moment(new Date(i)).isValid()&&s.renderDateFormat&&(i=moment(i).format(s.renderDateFormat)),arguments[5]=i,Handsontable.renderers.TextRenderer.apply(this,arguments)):Handsontable.renderers.TextRenderer.apply(this,arguments),s.backgroundColor&&(t.style.backgroundColor=s.backgroundColor),s.color&&(t.style.color=s.color)}},{key:"countColumns",value:function(){return this.meta.length}},{key:"makeColumns",value:function(){var e=this,t=[],a=[],n={},r=0;return this.meta.forEach(function(i){n[i.name]=r,r++,t.push(i.name);var s={};switch(s.type="text",s.width=100,s.typeOriginal=i.type,s.isDark=e.isDarkTheme,i.type.includes("Int64")?(s.type="text",s.width=100):i.type.includes("Int")&&(s.width=80,s.type="numeric"),i.type){case"Date":s.width=90,s.type="date",s.dateFormat="YYYY-MM-DD";break;case"DateTime":s.width=150,s.type="time",s.timeFormat="YYYY-MM-DD HH:mm:ss";break;case"Float32":s.width=80,s.type="numeric",s.format="0.[0000000]";break;case"Float64":s.width=80,s.type="numeric",s.format="0.[0000000]";break;case"String":s.width=180}s.renderer=e._handsRenderer,s.data=i.name,a.push(s)}),{colHeaders:t,columns:a,colPositions:n}}},{key:"fecthContextMenu",value:function(){return{items:{columnformat:{name:"Column format",submenu:{items:[{name:"Reset",key:"columnformat:1",callback:function(t,a,n){e.makeFormat(this,"Reset")}},{name:"Money",key:"columnformat:2",callback:function(t,a,n){e.makeFormat(this,"Money")},disabled:function(){return!e.isFormatColl(this,"numeric")}},{name:"Human",key:"columnformat:3",callback:function(t,a,n){e.makeFormat(this,"Human")},disabled:function(){return!e.isFormatColl(this,"numeric")}},{name:"Bytes",key:"columnformat:4",callback:function(t,a,n){e.makeFormat(this,"Bytes")},disabled:function(){return!e.isFormatColl(this,"numeric")}},{name:"Percentages",key:"columnformat:5",callback:function(t,a,n){e.makeFormat(this,"Percentages")},disabled:function(){return!e.isFormatColl(this,"numeric")}},{name:"Time only",key:"columnformat:6",callback:function(t,a,n){e.makeFormat(this,"Time")},disabled:function(){return!e.isFormatColl(this,"Time")}},{name:"Date only",key:"columnformat:7",callback:function(t,a,n){e.makeFormat(this,"Date")},disabled:function(){return!e.isFormatColl(this,"Date")}},{name:"Date loc.",key:"columnformat:8",callback:function(t,a,n){e.makeFormat(this,"DateLoc")},disabled:function(){return!e.isFormatColl(this,"Date")}},{name:"Float",key:"columnformat:9",callback:function(t,a,n){e.makeFormat(this,"Float")},disabled:function(){return!e.isFormatColl(this,"numeric")}},{name:"Heatmaps",key:"columnformat:10",callback:function(t,a,n){e.makeHeatmaps(this,"Heatmaps")},disabled:function(){return!e.isFormatColl(this,"numeric")}},{name:"Negative & Positive",key:"columnformat:11",callback:function(t,a,n){e.makeHeatmaps(this,"NegaPosi")},disabled:function(){return!e.isFormatColl(this,"numeric")}}]}},style:{name:"Style",submenu:{items:[{name:"Normal",callback:function(t,a,n){e.makeStyle(this,"Normal")},key:"style:normal"},{name:"Bold",callback:function(t,a){e.makeStyle(this,"Bold")},key:"style:makebold"},{name:"Red color",callback:function(t,a){e.makeStyle(this,"Red")},key:"style:red"},{name:"Green color",callback:function(t,a){e.makeStyle(this,"Green")},key:"style:green"},{name:"Yellow color",callback:function(t,a){e.makeStyle(this,"Yellow")},key:"style:green"},{name:"Orange color",callback:function(t,a){e.makeStyle(this,"Orange")},key:"style:green"}]}},hsep1:"---------",copyTo:{name:"To Clipboard",submenu:{items:[{name:"Redmine Markdown",callback:function(t,a,n){console.info("copyToClipboard"),e.copyToClipboard(this,"Redmine")},key:"copyTo:1"},{name:"Redmine Markdown (full)",callback:function(t,a,n){console.info("copyToClipboard"),e.copyToClipboard(this,"Redmine",!0)},key:"copyTo:2"},{name:"WHERE col1 IN (val,val),col2 IN ...",callback:function(t,a,n){console.info("makeWhereIn"),e.makeWhereIn(this)},key:"copyTo:3"},{name:"Create TABLE...",callback:function(t,a,n){e.makeCreateTable(this)},key:"copyTo:4"}]}},hsep3:"---------",Transform:{name:"Transform",submenu:{items:[{name:"Transpose full table",callback:function(t,a,n){e.Transpose(this,"Transpose")},key:"Transform:1"}]}},undo:{},make_read_only:{},alignment:{},hsep4:"---------"}}}},{key:"makeSettings",value:function(){var e=this.makeColumns(),t={observeChanges:!1,observeDOMVisibility:!0,dropdownMenu:!0,manualColumnMove:!0,manualColumnResize:!0,rowHeaders:!0,colWidths:100,fillHandle:!1,stretchH:"all",customBorders:!0,isDark:this.isDarkTheme,filters:!0,columnSorting:!0,sortIndicator:!0,manualRowResize:!0,viewportColumnRenderingOffset:"auto",wordWrap:!1,autoColumnSize:{samplingRatio:23},columns:e.columns,colHeaders:e.colHeaders,contextMenu:this.fecthContextMenu(),currentRowClassName:this.isDarkTheme?"currentRowDark":"currentRowWhite",currentColClassName:"currentCol",renderAllRows:!1,visibleRows:1500};return this.Preset.sort&&this.Preset.sortOrder&&(t.columnSorting={column:e.colPositions[this.Preset.sort],sortOrder:"desc"==this.Preset.sortOrder.toLowerCase()?!1:!0}),t}}],[{key:"isDark",value:function(){return window.isDarkTheme}},{key:"makeHeatmaps",value:function(e,t){for(var a=e.getSelectedRange(),n=Math.min(a.from.col,a.to.col),r=Math.max(a.from.col,a.to.col),i="#a900e5",s="#3668ff",o=chroma.scale([i,s]),c=n;r>=c;c++){var l=e.countRows(),d=e.getDataAtCol(c),u=Math.min.apply(null,d),m=Math.max.apply(null,d);if(null!==u&&null!==m)for(var h=0;l>=h;h++){var p=parseFloat(e.getDataAtCell(h,c));if("Heatmaps"==t){var g=(p-u)/(m-u),f=o(g).hex(),b=e.getCellMeta(h,c);b&&e.setCellMeta(h,c,"backgroundColor",f)}if("NegaPosi"==t){var v=!1;0>p&&(v="#e27137"),p>0&&(v="#31b3e5");var y=e.getCellMeta(h,c);y&&v&&e.setCellMeta(h,c,"color",v)}}else console.warn("Can`t find Min&Max in column",c)}e.render()}},{key:"getSelected",value:function(e,t,a){var n=e.getSelectedRange(),r=!1;if(!n&&t||a)return{isSelection:!1,fromRow:0,toRow:e.countRows(),toCol:e.countCols(),fromCol:0};if(!n)return{isSelection:!1,fromRow:-1,toRow:-1,toCol:-1,fromCol:-1};var i=Math.min(n.from.col,n.to.col),s=Math.max(n.from.col,n.to.col),o=Math.min(n.from.row,n.to.row),c=Math.max(n.from.row,n.to.row);return{isSelection:r,fromRow:o,toRow:c,toCol:s,fromCol:i}}},{key:"makeFormat",value:function(t,a){for(var n=e.getSelected(t,!0),r=t.getSettings().columns,i=n.fromCol;i<=n.toCol;i++)switch(console.log("makeFormat for coll ="+i,a),a){case"Reset":r[i].format=!1,r[i].renderDateFormat=!1;break;case"Money":r[i].format="$0,0.00";break;case"Human":r[i].format="5a";break;case"Bytes":r[i].format="0.0b";break;case"Percentages":r[i].format="(0.00 %)";break;case"Time":r[i].renderDateFormat="HH:mm:ss";break;case"Date":r[i].renderDateFormat="YYYY-MM-DD";break;case"DateTime":r[i].renderDateFormat="YYYY-MM-DD HH:mm:ss";break;case"DateLoc":r[i].renderDateFormat="LLLL";break;case"Float":r[i].format="0.[0000000]"}t.updateSettings({columns:r}),t.render()}},{key:"isFormatColl",value:function(e,t){t=t.toLowerCase();for(var a=e.getSelectedRange(),n=Math.min(a.from.col,a.to.col),r=Math.max(a.from.col,a.to.col),i=e.getSettings().columns,s=n;r>=s;s++)if(!i[s].type.toLowerCase().includes(t))return!1;return!0}},{key:"pushToClipboardText",value:function(e){var t=document.createElement("textarea");t.style.width=0,t.style.height=0,t.style.border=0,t.style.position="absolute",t.style.top=0,document.body.append(t),t.value=e,t.focus(),t.select();try{document.execCommand("copy")}catch(a){console.log("Oops, unable to copy")}document.body.removeChild(t)}},{key:"makeCreateTable",value:function(t){for(var a=e.getSelected(t,!0),n="\nCREATE TABLE x (\n",r=[],i=t.getSettings().columns,s=a.fromCol;s<=a.toCol;s++){var o=i[s].typeOriginal;r.push(" "+t.colToProp(s)+" "+o)}n=n+r.join(",\n")+"\n)\nENGINE = TinyLog\n;;\n",console.log(n),e.pushToClipboardText(n)}},{key:"Transpose",value:function(t,a){var n=e.transpose(t.getSourceData()),r=[],i=[],s=!0,o=!1,c=void 0;try{for(var l,d=n.columns[Symbol.iterator]();!(s=(l=d.next()).done);s=!0){var u=l.value,m={};m.renderer=this._handsRenderer,m.data=u,m.type="text",m.width=100,i.push(m),r.push(u)}}catch(h){o=!0,c=h}finally{try{!s&&d["return"]&&d["return"]()}finally{if(o)throw c}}t.updateSettings({columns:i,colHeaders:r,data:n.data})}},{key:"transpose",value:function(e){var t=[],a=1,n=[];t.push(0);var r=!0,i=!1,s=void 0;try{for(var o,c=e[Symbol.iterator]();!(r=(o=c.next()).done);r=!0){var l=o.value,d=0,u=!0,m=!1,h=void 0;try{for(var p,g=Object.entries(l)[Symbol.iterator]();!(u=(p=g.next()).done);u=!0){var f=_slicedToArray(p.value,2),b=f[0],v=f[1];n[d]||(n[d]={}),1==a&&(n[d][0]=b),n[d][a]=v,d++}}catch(y){m=!0,h=y}finally{try{!u&&g["return"]&&g["return"]()}finally{if(m)throw h}}t.push(a),a++}}catch(y){i=!0,s=y}finally{try{!r&&c["return"]&&c["return"]()}finally{if(i)throw s}}return{data:n,columns:t}}},{key:"getPivotArray",value:function(e,t,a,n){for(var r={},i=[],s=[],o=0;o'+a+"":"")}},{key:"isDark",value:function(){return this.widget.isDark}},{key:"getError",value:function(){return this.errorMessage}},{key:"isExecutableCode",value:function(){return this.drawCodeObject&&this.drawCodeObject.type?this.drawCodeObject.exec:!1}},{key:"executableCode",value:function(){var e={};return this.isExecutableCode()&&(console.log(this.drawCodeObject.code),e=this.drawCodeObject.code.call(window,this.widget.data)),console.warn("executableCode:ResultFunction",e),e}},{key:"initChartByJsCode",value:function(){if(this.isExecutableCode()){var e=this.executableCode();return this.options=Object.assign(this.options,e),!0}return!1}},{key:"data",value:function(){return this.widget.data.data}},{key:"meta",value:function(){return this.widget.data.meta}},{key:"isNumericColumn",value:function(e){var t=this.getColumnPosition(e);if(!_.isUndefined(t)){var a=this.meta()[t].type;return a?(a=a.toLowerCase(),a.includes("int")||a.includes("float")?!0:!1):!1}}},{key:"isStringColumn",value:function(e){var t=this.getColumnPosition(e);if(!_.isUndefined(t)){var a=this.meta()[t].type;return a?(a=a.toLowerCase(),a.includes("string")||a.includes("enum")?!0:!1):!1}}},{key:"getColumnPosition",value:function(e){return parseInt(_.findKey(this.meta(),{name:e}))}},{key:"haveColumn",value:function(e){if(_.isNaN(e)||_.isNull(e)||_.isUndefined(e))return!1;var t=this.getColumnPosition(e);return _.isNaN(t)||_.isNull(t)||_.isUndefined(t)?!1:!0}},{key:"getColumnByType",value:function(e){var t=_.findIndex(this.meta(),{type:e});return 0>t?!1:this.getColumns(t)}},{key:"getDateTimeColumn",value:function(){return this.getColumnByType("DateTime")}},{key:"getDateColumn",value:function(){return this.getColumnByType("Date")}},{key:"getColumns",value:function(e){var t=_.map(this.meta(),"name");return _.isUndefined(e)?t:t[e]}},{key:"getFirstColumn",value:function(){return this.getColumns(0)}},{key:"getDrawCommandObject",value:function(){return this.drawCodeObject&&this.drawCodeObject.type?this.drawCodeObject.code:!1}},{key:"initDrawCodeObject",value:function initDrawCodeObject(){var drawCommand=this.widget.drawCommnads;if(!drawCommand)return[];var codeDrawText=!1;if(drawCommand&&drawCommand.code&&(codeDrawText=drawCommand.code),!codeDrawText)return[];var draw={code:!1,type:!1};if(_.isObject(codeDrawText))return draw={isok:!0,code:codeDrawText,type:"undefined"==typeof codeDrawText?"undefined":_typeof(codeDrawText),exec:!1};if("text"==drawCommand.drawtype.toLowerCase()){var obj=codeDrawText.trim();return draw={isok:!0,code:obj,type:"undefined"==typeof obj?"undefined":_typeof(obj),exec:!1}}for(var data={},columns=this.getColumns(),len=this.data().length,index=0;len>index;++index){var item=this.data()[index];for(var colPos in columns){var col=columns[colPos];data[col]||(data[col]=[]),data[col].push(item[col])}}try{var code="("+codeDrawText+")";console.log("CODE>>>",code);var _obj=eval(code),type="undefined"==typeof _obj?"undefined":_typeof(_obj);draw={isok:!0,code:_obj,type:type,exec:!!(_obj&&_obj.constructor&&_obj.call&&_obj.apply)}}catch(E){console.error("error eval ",codeDrawText,E)}return draw}}]),DrawBasicChart}(),DrawText=function(e){function t(e,a){_classCallCheck(this,t);var n=_possibleConstructorReturn(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));return n.type=a.toUpperCase(),n.library="text",n.widget.sizeX=0,n.widget.sizeY=0,n}return _inherits(t,e),_createClass(t,[{key:"preProcessor",value:function(){var e=this.getDrawCommandObject();this.init=this.applyText(e)}},{key:"applyText",value:function(e){return this.isDark()&&(this.widget.element[0].style.background="#404a59"),e?this.widget.element[0].innerHTML=Mustache.render(e,this.widget.data):this.widget.element[0].innerHTML="
"+JSON.stringify(this.widget.data,null,"	")+"
",!0}},{key:"onResize",value:function(){}}]),t}(DrawBasicChart),DrawPlotly=function(e){function t(e,a){_classCallCheck(this,t);var n=_possibleConstructorReturn(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));return n.type=a.toUpperCase(),n.library="plotly",n.chart=null,n.setWidgetSize(6,3),n}return _inherits(t,e),_createClass(t,[{key:"onResize",value:function(){if(this.plotly){var e=this.widget.getSizeElementHeight(),t=this.widget.getSizeElementWidth();(this.layout.height!=e||this.layout.width!=t)&&(this.layout.height=e,this.layout.width=t,this.relayout())}}},{key:"preProcessor",value:function(){return this.initChartByJsCode(),this.getError()?(console.error(this.getError()),this.chart.before("

"+this.getError()+"

"),!1):(this.isDark(),this.init=this.create(),void console.info("preProcessor",this.init))}},{key:"getElement",value:function(){return this.widget.element[0]}},{key:"relayout",value:function(){Plotly.relayout(this.getElement(),this.layout)}},{key:"editor",value:function(){console.info("editoreditoreditor")}},{key:"create",value:function(){var e=this.getDrawCommandObject();console.warn("CREATE DrawPlotly",e);var t={data:[],layout:{}};_.isObject(e)&&(_.isObject(e.trace)&&t.data.push(e.trace),_.isObject(e.trace1)&&t.data.push(e.trace1),_.isObject(e.trace2)&&t.data.push(e.trace2),_.isObject(e.trace3)&&t.data.push(e.trace3),_.isObject(e.trace4)&&t.data.push(e.trace4),_.isObject(e.layout)&&(t.layout=e.layout)),console.info(t);var a=[{x:[1,2],y:[1,2],type:"bar"}];console.log("CONS:",a),console.log("llll:",t);var n={editable:!1};this.layout=t.layout;var r=this.widget.getSizeElementHeight(),i=this.widget.getSizeElementWidth();return this.layout.height=r,this.layout.width=i,this.plotly=Plotly.plot(this.getElement(),t.data,this.layout,n),!0}},{key:"applyDarkTheme",value:function(){}}]),t}(DrawBasicChart),DrawGoogleMap=function(e){function t(e,a){_classCallCheck(this,t);var n=_possibleConstructorReturn(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));return n.type=a.toUpperCase(),n.library="gmaps",n._map=!1,n.mapOptions={zoom:4},n}return _inherits(t,e),_createClass(t,[{key:"onResize",value:function(){this._map&&google.maps.event.trigger(this._map,"resize")}},{key:"preProcessor",value:function(){this.loadGoogleMapJS(this)}},{key:"afterLoadMapProcessor",value:function(){if(this.initChartByJsCode()?this.init=!0:this.init=this.create(),this.getError())return console.error(this.getError()),this.chart.before("

"+this.getError()+"

"),!1;var e=this.getDrawCommandObject();e.raw&&(this.options=_.merge(this.options,e.raw)),this.isDark(),console.info("preProcessor",this.init,this.options)}},{key:"loadGoogleMapJS",value:function(e){if(window._sendGoogleMapLoad)return void this.afterLoadMapProcessor();window._sendGoogleMapLoad=!0,window._isGoogleMapLoaded=!1,console.info("YA_MAP>Start load map : api-maps.yandex.ru");var t=document.createElement("script");t.type="text/javascript",t.async=!0,t.src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCRQH39oyrPnfPPgADuOp0eSRsDHRUMyyY",t.charset="utf-8",t.onload=t.onreadystatechange=function(){t.readyState&&"complete"!==t.readyState&&"loaded"!==t.readyState||(t.onload=t.onreadystatechange=null,e.afterLoadMapProcessor(),window._isGoogleMapLoaded=!0)};var a=document.getElementsByTagName("script")[0];a.parentNode.insertBefore(t,a)}},{key:"getDarkStyle",value:function(){return[{featureType:"all",elementType:"labels.text.fill",stylers:[{color:"#ffffff"}]},{featureType:"all",elementType:"labels.text.stroke",stylers:[{color:"#000000"},{lightness:13}]},{featureType:"administrative",elementType:"geometry.fill",stylers:[{color:"#000000"}]},{featureType:"administrative",elementType:"geometry.stroke",stylers:[{color:"#144b53"},{lightness:14},{weight:1.4}]},{featureType:"landscape",elementType:"all",stylers:[{color:"#08304b"}]},{featureType:"poi",elementType:"geometry",stylers:[{color:"#0c4152"},{lightness:5}]},{featureType:"road.highway",elementType:"geometry.fill",stylers:[{color:"#000000"}]},{featureType:"road.highway",elementType:"geometry.stroke",stylers:[{color:"#0b434f"},{lightness:25}]},{featureType:"road.arterial",elementType:"geometry.fill",stylers:[{color:"#000000"}]},{featureType:"road.arterial",elementType:"geometry.stroke",stylers:[{color:"#0b3d51"},{lightness:16}]},{featureType:"road.local",elementType:"geometry",stylers:[{color:"#000000"}]},{featureType:"transit",elementType:"all",stylers:[{color:"#146474"}]},{featureType:"water",elementType:"all",stylers:[{color:"#021019"}]}]}},{key:"getLightStyle",value:function(){return[{featureType:"landscape",stylers:[{hue:"#FFBB00"},{saturation:43.400000000000006},{lightness:37.599999999999994},{gamma:1}]},{featureType:"road.highway",stylers:[{hue:"#FFC200"},{saturation:-61.8},{lightness:45.599999999999994},{gamma:1}]},{featureType:"road.arterial",stylers:[{hue:"#FF0300"},{saturation:-100},{lightness:51.19999999999999},{gamma:1}]},{featureType:"road.local",stylers:[{hue:"#FF0300"},{saturation:-100},{lightness:52},{gamma:1}]},{featureType:"water",stylers:[{hue:"#0078FF"},{saturation:-13.200000000000003},{lightness:2.4000000000000057},{gamma:1}]},{featureType:"poi",stylers:[{hue:"#00FF6A"},{saturation:-1.0989010989011234},{lightness:11.200000000000017},{gamma:1}]}]}},{key:"create",value:function(){console.warn("CREATE"),this._map=new google.maps.Map(this.widget.element[0],this.mapOptions);var e=this.getLightStyle();this.isDark()&&(e=this.getDarkStyle()),this._map.setOptions({styles:e});var t=this,a=this.getDrawCommandObject(),n={longitude:"longitude",latitude:"latitude",count:"count",title:"title"},r=new google.maps.LatLngBounds,i=0;a&&(n=Object.assign(n,a)),this.data().forEach(function(e,a){var s=parseInt(e[n.count]);s>i&&(i=s);var o={lat:e[n.latitude],lng:e[n.longitude]},c=!1;e[n.title]&&(c=new google.maps.InfoWindow({content:'
'+e[n.title]+"
"})),r.extend(o);var l=new google.maps.Marker({position:o,map:t._map,title:"Value:"+s});c&&l.addListener("click",function(){c.open(this._map,l)})}),this._map.fitBounds(r),this._map.panToBounds(r)}}]),t}(DrawBasicChart),DrawEcharts=function(e){function t(e,a){_classCallCheck(this,t);var n=_possibleConstructorReturn(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));return n.help="",n.type=a.toUpperCase(),n.library="echarts",n.preference={gridchart:!1,bar:!1},n.options={version:3,textStyle:{fontFamily:"Menlo"},toolbox:{show:!0,feature:{dataZoom:{yAxisIndex:"none",title:"data Zoom"},dataView:{readOnly:!1,title:"data View"},magicType:{type:["line","bar","stack","tiled"],title:{line:"line",bar:"bar",stack:"stack",tiled:"tiled"}},restore:{title:"Restore"},saveAsImage:{title:"Save as Image"}}}},n}return _inherits(t,e),_createClass(t,[{key:"onResize",value:function(){console.log("onResize Chart"),this.chart&&this.init&&this.chart.resize()}},{key:"preProcessor",value:function(){if(this.initChartByJsCode())this.init=!0;else try{this.init=this.create()}catch(e){this.setError(this.getError()+"\n\n\n"+e.name+":"+e.message+"\n"+e.stack)}if(this.getError())return console.error(this.getError()),!1;var t=this.getDrawCommandObject();t.raw&&(this.options=_.merge(this.options,t.raw)),this.isDark()&&(this.options.backgroundColor="#404a59"),this.chart.setOption(this.options),console.info("preProcessor",this.init,this.options)}},{key:"getParameterPath",value:function(){var e=this.getDrawCommandObject(),t={path:""};e&&(t=Object.assign(t,e));var a="";if(_.isString(e)?a=e:t.path&&(a=t.path),!a)return!1;for(var n=_.split(a,"."),r=0;rs;s+=1){var o=this.getColumns(s);if(!r&&this.isNumericColumn(o)){r=o;break}}t.date=n,t.value=r}if(!this.haveColumn(t.date)||!this.haveColumn(t.value))return this.setError("Not set date | value cols"),!1;var c=0,l=Number.MAX_VALUE,d=_.map(this.data(),function(e){var a=parseFloat(e[t.value]);return a&&a>c&&(c=a),a&&l>a&&(l=a),[e[t.date],a]});d=_.groupBy(d,function(e){var t=(""+e[0]).substring(0,4);return t});var u={tooltip:{position:"top"},calendar:[],series:[],visualMap:{min:l,max:c,calculable:!0,orient:"horizontal",left:"center",top:"top"}},m=60,h=0;return _.forEach(d,function(e,t){u.calendar.push({top:m,range:t,right:0,cellSize:["auto",20]}),u.series.push({type:"heatmap",coordinateSystem:"calendar",data:e,calendarIndex:h}),h+=1,m+=200}),this.options=Object.assign(u,this.options),!0}}]),t}(DrawEcharts),DrawEchartsTreemap=function(e){function t(){return _classCallCheck(this,t),_possibleConstructorReturn(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return _inherits(t,e),_createClass(t,[{key:"getLevelOption",value:function(){return[{itemStyle:{normal:{borderWidth:0,gapWidth:5}}},{itemStyle:{normal:{gapWidth:1}}},{colorSaturation:[.35,.5],itemStyle:{normal:{gapWidth:1,borderColorSaturation:.6}}}]}},{key:"buildTreeData",value:function(e,t){var a=[],n=this;return _.forEach(e,function(e,r){var i=t[r],s={};if(s.value=i.__value,_.isObject(e)){var o=n.buildTreeData(e,i);_.isArray(o)&&o.length&&(s.children=o)}s.name=r,a.push(s)}),a}},{key:"create",value:function(){var e=this.getDrawCommandObject(),t={path:"",title:"TreeMap",tooltip:"Usage",valueformat:!1};e&&(t=Object.assign(t,e));var a="";t.path&&(a=t.path),_.isString(e)&&(a=e);var n=_.split(a,"."),r=n.length;if(!r)return this.setError("Not set path"),!1;for(var i=0;r>i;i+=1)if(!this.haveColumn(n[i]))return this.setError("bad path, no column:"+n[i]),!1;if(!this.isNumericColumn(n[r-1]))return this.setError("bad column:"+n[r-1]+" must be number"),!1;var s={},o={};this.data().forEach(function(e){for(var t=e[n[r-1]],a=[],i=0;r-1>i;i+=1){a.push(e[n[i]]);var c=_.get(s,a.join("_"),0);_.set(s,a.join(".")+".__value",parseFloat(c)+parseFloat(t))}_.set(o,a.join("."),t)});var c=this.buildTreeData(o,s),l={tooltip:{trigger:"item"}},d=echarts.format;return l.series=[{type:"treemap",name:t.title,label:{show:!0,formatter:"{b}"},tooltip:{formatter:function(e){for(var a=e.value,n=[],r=e.treePathInfo,i=1;i'+d.encodeHTML(n.join("."))+"",t.tooltip+" : "+numbro(a).format(s)].join("")}},itemStyle:{normal:{borderColor:"#fff"}},levels:this.getLevelOption(),data:c}],this.options=Object.assign(l,this.options),!0}}]),t}(DrawEcharts),DrawEchartsSunkeys=function(e){function t(){return _classCallCheck(this,t),_possibleConstructorReturn(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return _inherits(t,e),_createClass(t,[{key:"create",value:function(){this.helpLink="https://tabix.io/doc/draw/Draw_Sankeys/",this.help="Default config : {path:''} or {value:'',source:'',target:''}, if empty path or not set, try auto create path, then find columns [String] : [Integer|Float] : [String] ";var e=this.getDrawCommandObject(),t={path:"",value:"value",source:"source",target:"target"};e&&(t=Object.assign(t,e));var a="";_.isString(e)?a=e:t.path?a=t.path:this.haveColumn(t.source)&&this.haveColumn(t.value)&&this.haveColumn(t.target)&&(a=t.source+"."+t.value+"."+t.target);var n=[];if(a)n=_.split(a,".");else{var r=!1,i=this.getColumns();for(var s in i){var o=i[s];this.isNumericColumn(o)&&r&&(n.push(o),r=!1),this.isStringColumn(o)&&!r&&(n.push(o),r=!0)}}if(console.log("patharr>",n),!n.length)return this.setError("The value of the variable 'path' - empty"),!1;if(!(1&n.length))return this.setError("The value of the variable 'path' must be odd"),!1;var c=[],l=[];this.data().forEach(function(e){for(var t=0;ta&&(a=s),e[t.destination.longitude]&&e[t.destination.latitude]){var o="";e[t.destination.name]&&(o=e[t.destination.name]),r.push({fromName:e[t.name],toName:o,coords:[[e[t.longitude],e[t.latitude]],[e[t.destination.longitude],e[t.destination.latitude]]]})}n.push({name:e[t.name],value:[e[t.longitude],e[t.latitude],s],label:{emphasis:{position:"right",show:!0}}})});var i=[{name:t.title,type:"effectScatter",coordinateSystem:"geo",data:n,showEffectOn:"render",rippleEffect:{brushType:"stroke"},symbolSize:function(e){return a?e[2]/a*15:e[2]/1e4},hoverAnimation:!0,label:{normal:{formatter:"{b}",position:"right",show:!0}},itemStyle:{normal:{color:"#f4e925",shadowBlur:10,shadowColor:"#333"}},zlevel:1}];if(r.length>0){var s="path://M1705.06,1318.313v-89.254l-319.9-221.799l0.073-208.063c0.521-84.662-26.629-121.796-63.961-121.491c-37.332-0.305-64.482,36.829-63.961,121.491l0.073,208.063l-319.9,221.799v89.254l330.343-157.288l12.238,241.308l-134.449,92.931l0.531,42.034l175.125-42.917l175.125,42.917l0.531-42.034l-134.449-92.931l12.238-241.308L1705.06,1318.313z"; -i.push({name:t.title,type:"lines",zlevel:1,effect:{show:!0,period:6,trailLength:.7,color:"#fff",symbolSize:3},lineStyle:{normal:{width:0,curveness:.2}},data:r}),i.push({name:t.title,type:"lines",zlevel:2,symbol:["none","arrow"],symbolSize:10,effect:{show:!0,period:6,trailLength:0,symbol:s,symbolSize:15},lineStyle:{normal:{width:1,opacity:.6,curveness:.2}},data:r})}var o={tooltip:{trigger:"item"},geo:{name:t.title,type:"map",map:"world",label:{emphasis:{show:!1}},visualMap:{show:!0,min:0,max:100,inRange:{symbolSize:[6,60]}},roam:!0,itemStyle:{normal:{areaColor:"#323c48",borderColor:"#404a59"},emphasis:{areaColor:"#2a333d"}}},series:i};return this.options=Object.assign(this.options,o),!0}}]),t}(DrawEcharts),DrawEchartsHeatmap=function(e){function t(){return _classCallCheck(this,t),_possibleConstructorReturn(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return _inherits(t,e),_createClass(t,[{key:"create",value:function(){var e=this.getParameterPath();if(!e)return this.setError("Not set path"),!1;var t={},a={},n={};this.data().forEach(function(r){_.set(t,r[e[0]],1),_.set(a,r[e[1]],1),_.set(n,r[e[0]]+"."+r[e[1]],parseFloat(r[e[2]]))});var r=[],i=_.keys(t),s=_.keys(a),o=0,c=0;_.mapKeys(t,function(e,t){_.mapKeys(a,function(e,a){var i=_.get(n,t+"."+a,"-");o>i&&(o=i),i>c&&(c=i),r.push([t,a,i])})});var l={tooltip:{position:"top"},animation:!1,grid:{height:"50%",y:"10%"},xAxis:{type:"category",data:i,splitArea:{show:!0}},yAxis:{type:"category",data:s,splitArea:{show:!0}},visualMap:{min:o,max:c,calculable:!0,orient:"horizontal",left:"center",bottom:"15%"},series:[{name:"Punch Card",type:"heatmap",data:r,label:{normal:{show:!0}},itemStyle:{emphasis:{shadowBlur:10,shadowColor:"rgba(0, 0, 0, 0.5)"}}}]};return this.options=Object.assign(l,this.options),!0}}]),t}(DrawEcharts),DrawEchartsChart=function(e){function t(){return _classCallCheck(this,t),_possibleConstructorReturn(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return _inherits(t,e),_createClass(t,[{key:"create",value:function(){console.log("DrawEchartsChart");var e=this.getDrawCommandObject(),t=this.preCreate(e),a=this.createChart(e),n={tooltip:{trigger:"axis",axisPointer:{type:"shadow"}},grid:{left:"3%",right:"4%",bottom:"3%",containLabel:!0}};return e.title&&this.applyTitle(e.title),this.applyDataZoom(),this.applyLegend(),this.options=Object.assign(a,this.options,n,t),this.postCreate(e),!0}},{key:"findDateTimeAxis",value:function(){var e=this.getDateTimeColumn();if(e)return e;var t=this.getDateColumn();return t?t:!1}},{key:"postCreate",value:function(e){return{}}},{key:"preCreate",value:function(e){return{}}},{key:"createChart",value:function(e){var t=this,a={autoAxis:!1,markLine:!0,stack:!1,path:!1,sort:!0,xAxis:!1,yAxis:!1};e&&(a=Object.assign(a,e));var n={},r=this.getColumns(),i=this.getFirstColumn(),s=i,o=this.findDateTimeAxis(),c={},l=[],d=[],u=[],m={},h=this.data();if(o&&(i=o),a.xAxis){if(!this.haveColumn(a.xAxis))throw"xAxis column not exists";s=a.xAxis}else a.sort&&(h=_.sortBy(h,i)),s=i;if(d=[{name:s,type:"category",data:[]}],a.yAxis)if(_.isString(a.yAxis)){if(!this.haveColumn(a.yAxis))throw"yAxis column not exists";n[a.yAxis]=1}else{if(!_.isArray(a.yAxis))throw"yAxis column must string or array";var p=void 0;for(p=0;pk&&!w?(_.isArray(y)||(y=[]),y.push(S),k++):this.isNumericColumn(S)&&x.push(S))}var A=h.length;for(console.log("DATA LEN",A,h),v=0;A>v;++v){var D=h[v];d[0].data.push(D[d[0].name])}for(d[0].data=_.uniq(d[0].data),console.log("xAxis[0].data.",d[0].data),v=0;A>v;++v){var R=h[v],I=function(e){var a=r[e],i=[s],o=!1;if(_.size(n)&&(o=_.isUndefined(n[a])),a!==s&&!o&&t.isNumericColumn(a)&&_.findIndex(y,a)<0){if(y)for(var c=0;c1){var q=_.groupBy(f,function(e){return Math.floor(e.median/1e3)});if(_.size(q)>1){var H=function(e){var t=q[e],n=_.map(t,"column").join(",");_.forEach(t,function(e){u[e.index].yAxisIndex=l.length,a.stack&&(u[e.index].stack=n,u[e.index].areaStyle={normal:{}})}),l.push({name:n,type:"value"})};for(var P in q)H(P)}}return l.length||(l=[{name:b,type:"value"}]),c.series=u,c.yAxis=l,c.xAxis=d,console.info("Make Chart Done : Options",c),c}}]),t}(DrawEcharts),DrawEchartsGridChart=function(e){function t(){return _classCallCheck(this,t),_possibleConstructorReturn(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return _inherits(t,e),_createClass(t,[{key:"preCreate",value:function(e){return this.preference.gridchart=!0,{}}},{key:"postCreate",value:function(e){var t=[],a=[],n=[],r=[],i=0;console.info("postCreate!!!!!!",this.options);var s=[],o=this.options.xAxis[0],c=this.options.yAxis[0];for(var l in this.options.series){l=parseInt(l);var d=this.options.series[l].name;this.options.series[l].xAxisIndex=l,this.options.series[l].yAxisIndex=i,console.log(d,this.options.series[l]),o.show=!1,o.gridIndex=l,c.gridIndex=l,c.show=!1,c.name=d,t.push({show:!0,borderWidth:0,shadowBlur:2}),n.push(_.clone(o)),a.push(_.clone(c)),r.push({textAlign:"center",text:d,textStyle:{fontSize:11,fontWeight:"normal"}}),s.push(l),i+=1}var u=Math.ceil(Math.sqrt(i));t.forEach(function(e,t){e.left=t%u/u*100+.5+"%",e.top=Math.floor(t/u)/u*100+.5+"%",e.width=1/u*100-1+"%",e.height=1/u*100-1+"%",r[t].left=parseFloat(e.left)+parseFloat(e.width)/2+"%",r[t].top=parseFloat(e.top)+"%"}),this.options.dataZoom&&this.options.dataZoom[0]&&(this.options.dataZoom[0].xAxisIndex=s),this.options.titles=r,this.options.grid=t,this.options.xAxis=n,this.options.yAxis=a}}]),t}(DrawEchartsChart),DrawEchartsBar=function(e){function t(){return _classCallCheck(this,t),_possibleConstructorReturn(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return _inherits(t,e),_createClass(t,[{key:"preCreate",value:function(e){return this.preference.bar=!0,{}}}]),t}(DrawEchartsChart),DrawD3=function(e){function t(e){_classCallCheck(this,t);var a=_possibleConstructorReturn(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));return a.library="d3",a}return _inherits(t,e),t}(DrawBasicChart),DrawC3=function(e){function t(e){_classCallCheck(this,t);var a=_possibleConstructorReturn(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));return a.library="c3",a.bindto=!1,a}return _inherits(t,e),_createClass(t,[{key:"onResize",value:function(){this.chart&&this.init}},{key:"preProcessor",value:function(){return console.log("preProcessor>c3.generate"),this.initChartByJsCode()?(console.log("c3.options>",this.options),this.bindto.className+=" c3",console.log("this.bindto.className",this.bindto.className),this.options.bindto=this.bindto,console.log("c3.options>",this.options),void(this.chart=c3.generate(this.options))):(console.error("C3.Init by code"),!1)}}]),t}(DrawBasicChart),DrawAMcharts=function(e){function t(e){_classCallCheck(this,t),console.warn("DrawAMcharts constructor");var a=_possibleConstructorReturn(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));return a.library="amchart",a}return _inherits(t,e),_createClass(t,[{key:"onResize",value:function(){this.makeLegend()}},{key:"preProcessor",value:function(){this.createChart()&&(this.init=!0),console.log("!preProcessor,done",this.init,this.options)}},{key:"createChart",value:function(){var e=this,t={},a=this.widget.data.meta,n=!1,r="",i="mm",s=[],o=0,c=[];a.forEach(function(a){if("DateTime"==a.type)n="YYYY-MM-DD JJ:NN:SS",r=a.name;else if("Date"==a.type)n="YYYY-MM-DD",i="DD",r=a.name;else{if(!r)return void(r=a.name);o+=1;var l=e.getChartGraph(a,t[a.name]);l.id="g"+o,"v1"!==l.valueAxis&&c.push(l.valueAxis),s.push(l)}});var l={theme:Widget.isDark?"dark":"light",color:Widget.isDark?"#eee":"#333",type:"serial",categoryField:r,valueAxes:[{id:"v1",axisAlpha:1,gridAlpha:.07,axisColor:Widget.isDark?"#eee":"#333",gridColor:Widget.isDark?"#eee":"#333",ignoreAxisWidth:!0}],balloon:{borderThickness:1,shadowAlpha:0},graphs:s,chartCursor:{valueLineEnabled:!0,valueLineBalloonEnabled:!0,cursorAlpha:0,zoomable:!1,valueZoomable:!0,valueLineAlpha:.5},chartScrollbar:{graph:"g1",gridAlpha:0,color:"#888888",scrollbarHeight:25,backgroundAlpha:0,selectedBackgroundAlpha:.1,selectedBackgroundColor:"#888888",graphFillAlpha:0,autoGridCount:!0,selectedGraphFillAlpha:0,graphLineAlpha:.2,graphLineColor:"#c2c2c2",selectedGraphLineColor:"#888888",selectedGraphLineAlpha:1},categoryAxis:{dashLength:1,minorGridEnabled:!0,axisColor:Widget.isDark?"#eee":"#333",gridColor:Widget.isDark?"#eee":"#333"},data:this.widget.data.data};if(l.categoryAxis.parseDates=!1,n&&(l.dataDateFormat=n,l.categoryAxis.parseDates=!0,l.categoryAxis.minPeriod=i),c){var d=0;c.forEach(function(e){d++;var t={id:e,axisAlpha:1,axisThickness:1,position:"right",ignoreAxisWidth:!0,offset:1*d};l.valueAxes.push(t)})}return this.options=l,this.init=!0,this.makeLegend(),!0}},{key:"makeLegend",value:function(){console.log("this.widget.sizeY",this.widget.sizeY),this.widget.sizeY<2?delete this.options.legend:this.options.legend={align:"center",equalWidths:!1,periodValueText:"total: [[value.sum]]",valueAlign:"left",valueText:"[[value]] ([[percents]]%)",valueWidth:100},console.warn(this.options)}},{key:"getChartGraph",value:function(e,t){var a=e.name,n=e.name,r="v1";a=a.replace(/_axis\d+/gm,"");var i=/.*_axis(\d+).*/i,s=n.match(i);s&&s[1]&&(r="v"+s[1]);var o={id:"g1",valueAxis:r,fillAlphas:.2,bullet:"round",bulletSize:8,hideBulletsCount:50,lineThickness:1,title:a,useLineColorForBulletBorder:!0,valueField:n,type:"smoothedLine",balloonText:"[[title]] [[category]]
[[value]]"};return t||(t={}),Object.assign(o,t)}}]),t}(DrawBasicChart),DataProvider=function(){function e(t,a){_classCallCheck(this,e),t.totals&&t.data&&t.data.push(t.totals),this.data=t.data,this.text=!1,this.progressQuery="",this.sort=!1,this.sortOrder=!1,t.error||angular.isObject(t.data)||(angular.isString(t.data)?this.text=t.data:this.text=angular.toJson(t.data,!0),this.text=this.text.replace(/&/g,"&").replace(//g,">")),a||(a="ch"),this.sourceType=a,this.meta=t.meta,t.query?this.query=t.query:this.query={index:0,drawCommands:!1},t.error?(this.error=t.error.replace("
","\n").replace(/&/g,"&").replace(//g,">"),this.error=this.error.replace("\\n","
")):this.error=!1,this.draw=this.query.drawCommands,this.rows=t.rows,this.position=this.query.index,this.countAll=t.countAllQuery}return e.$inject=["result","sourceType"],_createClass(e,[{key:"isText",value:function(){return this.text?!0:!1}},{key:"isError",value:function(){return this.error?!0:!1}},{key:"getError",value:function(){return this.error}},{key:"data",value:function(){return this.data}},{key:"meta",value:function(){return this.meta}},{key:"toString",value:function(){return"("+this.name+", "+this.y+")"}}],[{key:"convertArrayToDataProvider",value:function(t,a){var n={};return n.data=t,n.meta=[],n.error=!1,n.query={drawCommands:!1},n.rows=t.length,n.position=0,n.countAll=0,Object.keys(t[0]).map(function(e){return n.meta.push({name:e,type:"string"})}),new e(n,a)}}]),e}();angular.module(smi2.app.name).service("DataProvider",DataProvider),angular.module("ui.ace",[]).constant("uiAceConfig",{}).directive("uiAce",["uiAceConfig",function(e){if(angular.isUndefined(window.ace))throw new Error("ui-ace need ace to work... (o rly?)");return{restrict:"EA",link:function(t,a,n){var r=e.ace||{},i=angular.extend({},r,t.$eval(n.uiAce)),s=window.ace.edit(a[0]);console.time("Ace Load"),i.onLoad(s),console.timeEnd("Ace Load"),a.on("$destroy",function(){s.session.$stopWorker(),s.destroy()}),t.$watch(function(){return[a[0].offsetWidth,a[0].offsetHeight]},function(){s.resize(),s.renderer.updateFull()},!0)}}}]),/* +var HandsTable=function(){function e(t,a,n){_classCallCheck(this,e),this.isDarkTheme=t,this.meta=a,this.Preset=n}return e.$inject=["isDark","metaData","Preset"],_createClass(e,[{key:"_handsRenderer",value:function(e,t,a,n,r,i,s){"numeric"==s.type?null==i||"-nan"==i||"inf"==i||"+nan"==i||"+inf"==i||"-inf"==i||"nan"==i?(null==i&&(arguments[5]="NULL"),t.style.color="black",t.style.background="red",Handsontable.renderers.TextRenderer.apply(this,arguments)):Handsontable.renderers.NumericRenderer.apply(this,arguments):"date"==s.type||"time"==s.type?(moment(new Date(i)).isValid()&&s.renderDateFormat&&(i=moment(i).format(s.renderDateFormat)),arguments[5]=i,Handsontable.renderers.TextRenderer.apply(this,arguments)):Handsontable.renderers.TextRenderer.apply(this,arguments),s.backgroundColor&&(t.style.backgroundColor=s.backgroundColor),s.color&&(t.style.color=s.color)}},{key:"countColumns",value:function(){return this.meta.length}},{key:"makeColumns",value:function(){var e=this,t=[],a=[],n={},r=0;return this.meta.forEach(function(i){n[i.name]=r,r++,t.push(i.name);var s={};switch(s.type="text",s.width=100,s.typeOriginal=i.type,s.isDark=e.isDarkTheme,i.type.includes("Int64")?(s.type="text",s.width=100):i.type.includes("Int")&&(s.width=80,s.type="numeric"),i.type){case"Date":s.width=90,s.type="date",s.dateFormat="YYYY-MM-DD";break;case"DateTime":s.width=150,s.type="time",s.timeFormat="YYYY-MM-DD HH:mm:ss";break;case"Float32":s.width=80,s.type="numeric",s.format="0.[0000000]";break;case"Float64":s.width=80,s.type="numeric",s.format="0.[0000000]";break;case"String":s.width=180}s.renderer=e._handsRenderer,s.data=i.name,a.push(s)}),{colHeaders:t,columns:a,colPositions:n}}},{key:"fecthContextMenu",value:function(){return{items:{columnformat:{name:"Column format",submenu:{items:[{name:"Reset",key:"columnformat:1",callback:function(t,a,n){e.makeFormat(this,"Reset")}},{name:"Money",key:"columnformat:2",callback:function(t,a,n){e.makeFormat(this,"Money")},disabled:function(){return!e.isFormatColl(this,"numeric")}},{name:"Human",key:"columnformat:3",callback:function(t,a,n){e.makeFormat(this,"Human")},disabled:function(){return!e.isFormatColl(this,"numeric")}},{name:"Bytes",key:"columnformat:4",callback:function(t,a,n){e.makeFormat(this,"Bytes")},disabled:function(){return!e.isFormatColl(this,"numeric")}},{name:"Percentages",key:"columnformat:5",callback:function(t,a,n){e.makeFormat(this,"Percentages")},disabled:function(){return!e.isFormatColl(this,"numeric")}},{name:"Time only",key:"columnformat:6",callback:function(t,a,n){e.makeFormat(this,"Time")},disabled:function(){return!e.isFormatColl(this,"Time")}},{name:"Date only",key:"columnformat:7",callback:function(t,a,n){e.makeFormat(this,"Date")},disabled:function(){return!e.isFormatColl(this,"Date")}},{name:"Date loc.",key:"columnformat:8",callback:function(t,a,n){e.makeFormat(this,"DateLoc")},disabled:function(){return!e.isFormatColl(this,"Date")}},{name:"Float",key:"columnformat:9",callback:function(t,a,n){e.makeFormat(this,"Float")},disabled:function(){return!e.isFormatColl(this,"numeric")}},{name:"Heatmaps",key:"columnformat:10",callback:function(t,a,n){e.makeHeatmaps(this,"Heatmaps")},disabled:function(){return!e.isFormatColl(this,"numeric")}},{name:"Negative & Positive",key:"columnformat:11",callback:function(t,a,n){e.makeHeatmaps(this,"NegaPosi")},disabled:function(){return!e.isFormatColl(this,"numeric")}}]}},style:{name:"Style",submenu:{items:[{name:"Normal",callback:function(t,a,n){e.makeStyle(this,"Normal")},key:"style:normal"},{name:"Bold",callback:function(t,a){e.makeStyle(this,"Bold")},key:"style:makebold"},{name:"Red color",callback:function(t,a){e.makeStyle(this,"Red")},key:"style:red"},{name:"Green color",callback:function(t,a){e.makeStyle(this,"Green")},key:"style:green"},{name:"Yellow color",callback:function(t,a){e.makeStyle(this,"Yellow")},key:"style:green"},{name:"Orange color",callback:function(t,a){e.makeStyle(this,"Orange")},key:"style:green"}]}},hsep1:"---------",copyTo:{name:"To Clipboard",submenu:{items:[{name:"Redmine Markdown",callback:function(t,a,n){console.info("copyToClipboard"),e.copyToClipboard(this,"Redmine")},key:"copyTo:1"},{name:"Redmine Markdown (full)",callback:function(t,a,n){console.info("copyToClipboard"),e.copyToClipboard(this,"Redmine",!0)},key:"copyTo:2"},{name:"WHERE col1 IN (val,val),col2 IN ...",callback:function(t,a,n){console.info("makeWhereIn"),e.makeWhereIn(this)},key:"copyTo:3"},{name:"Create TABLE...",callback:function(t,a,n){e.makeCreateTable(this)},key:"copyTo:4"}]}},hsep3:"---------",Transform:{name:"Transform",submenu:{items:[{name:"Transpose full table",callback:function(t,a,n){e.Transpose(this,"Transpose")},key:"Transform:1"}]}},undo:{},make_read_only:{},alignment:{},hsep4:"---------"}}}},{key:"makeSettings",value:function(){var e=this.makeColumns(),t={observeChanges:!1,observeDOMVisibility:!0,dropdownMenu:!0,manualColumnMove:!0,manualColumnResize:!0,rowHeaders:!0,colWidths:100,fillHandle:!1,stretchH:"all",customBorders:!0,isDark:this.isDarkTheme,filters:!0,columnSorting:!0,sortIndicator:!0,manualRowResize:!0,viewportColumnRenderingOffset:"auto",wordWrap:!1,autoColumnSize:{samplingRatio:23},columns:e.columns,colHeaders:e.colHeaders,contextMenu:this.fecthContextMenu(),currentRowClassName:this.isDarkTheme?"currentRowDark":"currentRowWhite",currentColClassName:"currentCol",renderAllRows:!1,visibleRows:1500};return this.Preset.sort&&this.Preset.sortOrder&&(t.columnSorting={column:e.colPositions[this.Preset.sort],sortOrder:"desc"==this.Preset.sortOrder.toLowerCase()?!1:!0}),t}}],[{key:"isDark",value:function(){return window.isDarkTheme}},{key:"makeHeatmaps",value:function(e,t){for(var a=e.getSelectedRange(),n=Math.min(a.from.col,a.to.col),r=Math.max(a.from.col,a.to.col),i="#a900e5",s="#3668ff",o=chroma.scale([i,s]),c=n;r>=c;c++){var l=e.countRows(),d=e.getDataAtCol(c),u=Math.min.apply(null,d),m=Math.max.apply(null,d);if(null!==u&&null!==m)for(var h=0;l>=h;h++){var p=parseFloat(e.getDataAtCell(h,c));if("Heatmaps"==t){var g=(p-u)/(m-u),f=o(g).hex(),b=e.getCellMeta(h,c);b&&e.setCellMeta(h,c,"backgroundColor",f)}if("NegaPosi"==t){var v=!1;0>p&&(v="#e27137"),p>0&&(v="#31b3e5");var y=e.getCellMeta(h,c);y&&v&&e.setCellMeta(h,c,"color",v)}}else console.warn("Can`t find Min&Max in column",c)}e.render()}},{key:"getSelected",value:function(e,t,a){var n=e.getSelectedRange(),r=!1;if(!n&&t||a)return{isSelection:!1,fromRow:0,toRow:e.countRows(),toCol:e.countCols(),fromCol:0};if(!n)return{isSelection:!1,fromRow:-1,toRow:-1,toCol:-1,fromCol:-1};var i=Math.min(n.from.col,n.to.col),s=Math.max(n.from.col,n.to.col),o=Math.min(n.from.row,n.to.row),c=Math.max(n.from.row,n.to.row);return{isSelection:r,fromRow:o,toRow:c,toCol:s,fromCol:i}}},{key:"makeFormat",value:function(t,a){for(var n=e.getSelected(t,!0),r=t.getSettings().columns,i=n.fromCol;i<=n.toCol;i++)switch(console.log("makeFormat for coll ="+i,a),a){case"Reset":r[i].format=!1,r[i].renderDateFormat=!1;break;case"Money":r[i].format="$0,0.00";break;case"Human":r[i].format="5a";break;case"Bytes":r[i].format="0.0b";break;case"Percentages":r[i].format="(0.00 %)";break;case"Time":r[i].renderDateFormat="HH:mm:ss";break;case"Date":r[i].renderDateFormat="YYYY-MM-DD";break;case"DateTime":r[i].renderDateFormat="YYYY-MM-DD HH:mm:ss";break;case"DateLoc":r[i].renderDateFormat="LLLL";break;case"Float":r[i].format="0.[0000000]"}t.updateSettings({columns:r}),t.render()}},{key:"isFormatColl",value:function(e,t){t=t.toLowerCase();for(var a=e.getSelectedRange(),n=Math.min(a.from.col,a.to.col),r=Math.max(a.from.col,a.to.col),i=e.getSettings().columns,s=n;r>=s;s++)if(!i[s].type.toLowerCase().includes(t))return!1;return!0}},{key:"pushToClipboardText",value:function(e){var t=document.createElement("textarea");t.style.width=0,t.style.height=0,t.style.border=0,t.style.position="absolute",t.style.top=0,document.body.append(t),t.value=e,t.focus(),t.select();try{document.execCommand("copy")}catch(a){console.log("Oops, unable to copy")}document.body.removeChild(t)}},{key:"makeCreateTable",value:function(t){for(var a=e.getSelected(t,!0),n="\nCREATE TABLE x (\n",r=[],i=t.getSettings().columns,s=a.fromCol;s<=a.toCol;s++){var o=i[s].typeOriginal;r.push(" "+t.colToProp(s)+" "+o)}n=n+r.join(",\n")+"\n)\nENGINE = TinyLog\n;;\n",console.log(n),e.pushToClipboardText(n)}},{key:"Transpose",value:function(t,a){var n=e.transpose(t.getSourceData()),r=[],i=[],s=!0,o=!1,c=void 0;try{for(var l,d=n.columns[Symbol.iterator]();!(s=(l=d.next()).done);s=!0){var u=l.value,m={};m.renderer=this._handsRenderer,m.data=u,m.type="text",m.width=100,i.push(m),r.push(u)}}catch(h){o=!0,c=h}finally{try{!s&&d["return"]&&d["return"]()}finally{if(o)throw c}}t.updateSettings({columns:i,colHeaders:r,data:n.data})}},{key:"transpose",value:function(e){var t=[],a=1,n=[];t.push(0);var r=!0,i=!1,s=void 0;try{for(var o,c=e[Symbol.iterator]();!(r=(o=c.next()).done);r=!0){var l=o.value,d=0,u=!0,m=!1,h=void 0;try{for(var p,g=Object.entries(l)[Symbol.iterator]();!(u=(p=g.next()).done);u=!0){var f=_slicedToArray(p.value,2),b=f[0],v=f[1];n[d]||(n[d]={}),1==a&&(n[d][0]=b),n[d][a]=v,d++}}catch(y){m=!0,h=y}finally{try{!u&&g["return"]&&g["return"]()}finally{if(m)throw h}}t.push(a),a++}}catch(y){i=!0,s=y}finally{try{!r&&c["return"]&&c["return"]()}finally{if(i)throw s}}return{data:n,columns:t}}},{key:"getPivotArray",value:function(e,t,a,n){for(var r={},i=[],s=[],o=0;o'+a+"":"")}},{key:"isDark",value:function(){return this.widget.isDark}},{key:"getError",value:function(){return this.errorMessage}},{key:"isExecutableCode",value:function(){return this.drawCodeObject&&this.drawCodeObject.type?this.drawCodeObject.exec:!1}},{key:"executableCode",value:function(){var e={};return this.isExecutableCode()&&(console.log(this.drawCodeObject.code),e=this.drawCodeObject.code.call(window,this.widget.data)),console.warn("executableCode:ResultFunction",e),e}},{key:"initChartByJsCode",value:function(){if(this.isExecutableCode()){var e=this.executableCode();return this.options=Object.assign(this.options,e),!0}return!1}},{key:"data",value:function(){return this.widget.data.data}},{key:"meta",value:function(){return this.widget.data.meta}},{key:"isNumericColumn",value:function(e){var t=this.getColumnPosition(e);if(!_.isUndefined(t)){var a=this.meta()[t].type;return a?(a=a.toLowerCase(),a.includes("int")||a.includes("float")?!0:!1):!1}}},{key:"isStringColumn",value:function(e){var t=this.getColumnPosition(e);if(!_.isUndefined(t)){var a=this.meta()[t].type;return a?(a=a.toLowerCase(),a.includes("string")||a.includes("enum")?!0:!1):!1}}},{key:"getColumnPosition",value:function(e){return parseInt(_.findKey(this.meta(),{name:e}))}},{key:"haveColumn",value:function(e){if(_.isNaN(e)||_.isNull(e)||_.isUndefined(e))return!1;var t=this.getColumnPosition(e);return _.isNaN(t)||_.isNull(t)||_.isUndefined(t)?!1:!0}},{key:"getColumnByType",value:function(e){var t=_.findIndex(this.meta(),{type:e});return 0>t?!1:this.getColumns(t)}},{key:"getDateTimeColumn",value:function(){return this.getColumnByType("DateTime")}},{key:"getDateColumn",value:function(){return this.getColumnByType("Date")}},{key:"getColumns",value:function(e){var t=_.map(this.meta(),"name");return _.isUndefined(e)?t:t[e]}},{key:"getFirstColumn",value:function(){return this.getColumns(0)}},{key:"getDrawCommandObject",value:function(){return this.drawCodeObject&&this.drawCodeObject.type?this.drawCodeObject.code:!1}},{key:"initDrawCodeObject",value:function initDrawCodeObject(){var drawCommand=this.widget.drawCommnads;if(!drawCommand)return[];var codeDrawText=!1;if(drawCommand&&drawCommand.code&&(codeDrawText=drawCommand.code),!codeDrawText)return[];var draw={code:!1,type:!1};if(_.isObject(codeDrawText))return draw={isok:!0,code:codeDrawText,type:"undefined"==typeof codeDrawText?"undefined":_typeof(codeDrawText),exec:!1};if("text"==drawCommand.drawtype.toLowerCase()){var obj=codeDrawText.trim();return draw={isok:!0,code:obj,type:"undefined"==typeof obj?"undefined":_typeof(obj),exec:!1}}for(var data={},columns=this.getColumns(),len=this.data().length,index=0;len>index;++index){var item=this.data()[index];for(var colPos in columns){var col=columns[colPos];data[col]||(data[col]=[]),data[col].push(item[col])}}try{var code="("+codeDrawText+")",_obj=eval(code),type="undefined"==typeof _obj?"undefined":_typeof(_obj);draw={isok:!0,code:_obj,type:type,exec:!!(_obj&&_obj.constructor&&_obj.call&&_obj.apply)}}catch(E){console.error("error eval ",codeDrawText,E)}return draw}}]),DrawBasicChart}(),DrawText=function(e){function t(e,a){_classCallCheck(this,t);var n=_possibleConstructorReturn(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));return n.type=a.toUpperCase(),n.library="text",n.widget.sizeX=0,n.widget.sizeY=0,n}return _inherits(t,e),_createClass(t,[{key:"preProcessor",value:function(){var e=this.getDrawCommandObject();this.init=this.applyText(e)}},{key:"applyText",value:function(e){return this.isDark()&&(this.widget.element[0].style.background="#404a59"),e?this.widget.element[0].innerHTML=Mustache.render(e,this.widget.data):this.widget.element[0].innerHTML="
"+JSON.stringify(this.widget.data,null,"	")+"
",!0}},{key:"onResize",value:function(){}}]),t}(DrawBasicChart),DrawPlotly=function(e){function t(e,a){_classCallCheck(this,t);var n=_possibleConstructorReturn(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));return n.type=a.toUpperCase(),n.library="plotly",n.chart=null,n.setWidgetSize(6,3),n}return _inherits(t,e),_createClass(t,[{key:"onResize",value:function(){if(this.plotly){var e=this.widget.getSizeElementHeight(),t=this.widget.getSizeElementWidth();(this.layout.height!=e||this.layout.width!=t)&&(this.layout.height=e,this.layout.width=t,this.relayout())}}},{key:"preProcessor",value:function(){return this.initChartByJsCode(),this.getError()?(console.error(this.getError()),this.chart.before("

"+this.getError()+"

"),!1):(this.isDark(),this.init=this.create(),void console.info("preProcessor",this.init))}},{key:"getElement",value:function(){return this.widget.element[0]}},{key:"relayout",value:function(){Plotly.relayout(this.getElement(),this.layout)}},{key:"editor",value:function(){console.info("editoreditoreditor")}},{key:"create",value:function(){var e=this.getDrawCommandObject();console.warn("CREATE DrawPlotly",e);var t={data:[],layout:{}};_.isObject(e)&&(_.isObject(e.trace)&&t.data.push(e.trace),_.isObject(e.trace1)&&t.data.push(e.trace1),_.isObject(e.trace2)&&t.data.push(e.trace2),_.isObject(e.trace3)&&t.data.push(e.trace3),_.isObject(e.trace4)&&t.data.push(e.trace4),_.isObject(e.layout)&&(t.layout=e.layout)),console.info(t);var a=[{x:[1,2],y:[1,2],type:"bar"}];console.log("CONS:",a),console.log("llll:",t);var n={editable:!1};this.layout=t.layout;var r=this.widget.getSizeElementHeight(),i=this.widget.getSizeElementWidth();return this.layout.height=r,this.layout.width=i,this.plotly=Plotly.plot(this.getElement(),t.data,this.layout,n),!0}},{key:"applyDarkTheme",value:function(){}}]),t}(DrawBasicChart),DrawGoogleMap=function(e){function t(e,a){_classCallCheck(this,t);var n=_possibleConstructorReturn(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));return n.type=a.toUpperCase(),n.library="gmaps",n._map=!1,n.mapOptions={zoom:4},n}return _inherits(t,e),_createClass(t,[{key:"onResize",value:function(){this._map&&google.maps.event.trigger(this._map,"resize")}},{key:"preProcessor",value:function(){this.loadGoogleMapJS(this)}},{key:"afterLoadMapProcessor",value:function(){if(this.initChartByJsCode()?this.init=!0:this.init=this.create(),this.getError())return console.error(this.getError()),this.chart.before("

"+this.getError()+"

"),!1;var e=this.getDrawCommandObject();e.raw&&(this.options=_.merge(this.options,e.raw)),this.isDark(),console.info("preProcessor",this.init,this.options)}},{key:"loadGoogleMapJS",value:function(e){if(window._sendGoogleMapLoad)return void this.afterLoadMapProcessor();window._sendGoogleMapLoad=!0,window._isGoogleMapLoaded=!1,console.info("YA_MAP>Start load map : api-maps.yandex.ru");var t=document.createElement("script");t.type="text/javascript",t.async=!0,t.src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCRQH39oyrPnfPPgADuOp0eSRsDHRUMyyY",t.charset="utf-8",t.onload=t.onreadystatechange=function(){t.readyState&&"complete"!==t.readyState&&"loaded"!==t.readyState||(t.onload=t.onreadystatechange=null,e.afterLoadMapProcessor(),window._isGoogleMapLoaded=!0)};var a=document.getElementsByTagName("script")[0];a.parentNode.insertBefore(t,a)}},{key:"getDarkStyle",value:function(){return[{featureType:"all",elementType:"labels.text.fill",stylers:[{color:"#ffffff"}]},{featureType:"all",elementType:"labels.text.stroke",stylers:[{color:"#000000"},{lightness:13}]},{featureType:"administrative",elementType:"geometry.fill",stylers:[{color:"#000000"}]},{featureType:"administrative",elementType:"geometry.stroke",stylers:[{color:"#144b53"},{lightness:14},{weight:1.4}]},{featureType:"landscape",elementType:"all",stylers:[{color:"#08304b"}]},{featureType:"poi",elementType:"geometry",stylers:[{color:"#0c4152"},{lightness:5}]},{featureType:"road.highway",elementType:"geometry.fill",stylers:[{color:"#000000"}]},{featureType:"road.highway",elementType:"geometry.stroke",stylers:[{color:"#0b434f"},{lightness:25}]},{featureType:"road.arterial",elementType:"geometry.fill",stylers:[{color:"#000000"}]},{featureType:"road.arterial",elementType:"geometry.stroke",stylers:[{color:"#0b3d51"},{lightness:16}]},{featureType:"road.local",elementType:"geometry",stylers:[{color:"#000000"}]},{featureType:"transit",elementType:"all",stylers:[{color:"#146474"}]},{featureType:"water",elementType:"all",stylers:[{color:"#021019"}]}]}},{key:"getLightStyle",value:function(){return[{featureType:"landscape",stylers:[{hue:"#FFBB00"},{saturation:43.400000000000006},{lightness:37.599999999999994},{gamma:1}]},{featureType:"road.highway",stylers:[{hue:"#FFC200"},{saturation:-61.8},{lightness:45.599999999999994},{gamma:1}]},{featureType:"road.arterial",stylers:[{hue:"#FF0300"},{saturation:-100},{lightness:51.19999999999999},{gamma:1}]},{featureType:"road.local",stylers:[{hue:"#FF0300"},{saturation:-100},{lightness:52},{gamma:1}]},{featureType:"water",stylers:[{hue:"#0078FF"},{saturation:-13.200000000000003},{lightness:2.4000000000000057},{gamma:1}]},{featureType:"poi",stylers:[{hue:"#00FF6A"},{saturation:-1.0989010989011234},{lightness:11.200000000000017},{gamma:1}]}]}},{key:"create",value:function(){console.warn("CREATE"),this._map=new google.maps.Map(this.widget.element[0],this.mapOptions);var e=this.getLightStyle();this.isDark()&&(e=this.getDarkStyle()),this._map.setOptions({styles:e});var t=this,a=this.getDrawCommandObject(),n={longitude:"longitude",latitude:"latitude",count:"count",title:"title"},r=new google.maps.LatLngBounds,i=0;a&&(n=Object.assign(n,a)),this.data().forEach(function(e,a){var s=parseInt(e[n.count]);s>i&&(i=s);var o={lat:e[n.latitude],lng:e[n.longitude]},c=!1;e[n.title]&&(c=new google.maps.InfoWindow({content:'
'+e[n.title]+"
"})),r.extend(o);var l=new google.maps.Marker({position:o,map:t._map,title:"Value:"+s});c&&l.addListener("click",function(){c.open(this._map,l)})}),this._map.fitBounds(r),this._map.panToBounds(r)}}]),t}(DrawBasicChart),DrawEcharts=function(e){function t(e,a){_classCallCheck(this,t);var n=_possibleConstructorReturn(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));return n.help="",n.type=a.toUpperCase(),n.library="echarts",n.preference={gridchart:!1,bar:!1},n.options={version:3,textStyle:{fontFamily:"Menlo"},toolbox:{show:!0,feature:{dataZoom:{yAxisIndex:"none",title:"data Zoom"},dataView:{readOnly:!1,title:"data View"},magicType:{type:["line","bar","stack","tiled"],title:{line:"line",bar:"bar",stack:"stack",tiled:"tiled"}},restore:{title:"Restore"},saveAsImage:{title:"Save as Image"}}}},n}return _inherits(t,e),_createClass(t,[{key:"onResize",value:function(){console.log("onResize Chart"),this.chart&&this.init&&this.chart.resize()}},{key:"preProcessor",value:function(){if(this.initChartByJsCode())this.init=!0;else try{this.init=this.create()}catch(e){this.setError(this.getError()+"\n\n\n"+e.name+":"+e.message+"\n"+e.stack)}if(this.getError())return console.error(this.getError()),!1;var t=this.getDrawCommandObject();t.raw&&(this.options=_.merge(this.options,t.raw)),this.isDark()&&(this.options.backgroundColor="#404a59"),this.chart.setOption(this.options),console.info("preProcessor",this.init,this.options)}},{key:"getParameterPath",value:function(){var e=this.getDrawCommandObject(),t={path:""};e&&(t=Object.assign(t,e));var a="";if(_.isString(e)?a=e:t.path&&(a=t.path),!a)return!1;for(var n=_.split(a,"."),r=0;rs;s+=1){var o=this.getColumns(s);if(!r&&this.isNumericColumn(o)){r=o;break}}t.date=n,t.value=r}if(!this.haveColumn(t.date)||!this.haveColumn(t.value))return this.setError("Not set date | value cols"),!1;var c=0,l=Number.MAX_VALUE,d=_.map(this.data(),function(e){var a=parseFloat(e[t.value]);return a&&a>c&&(c=a),a&&l>a&&(l=a),[e[t.date],a]});d=_.groupBy(d,function(e){var t=(""+e[0]).substring(0,4);return t});var u={tooltip:{position:"top"},calendar:[],series:[],visualMap:{min:l,max:c,calculable:!0,orient:"horizontal",left:"center",top:"top"}},m=60,h=0;return _.forEach(d,function(e,t){u.calendar.push({top:m,range:t,right:0,cellSize:["auto",20]}),u.series.push({type:"heatmap",coordinateSystem:"calendar",data:e,calendarIndex:h}),h+=1,m+=200}),this.options=Object.assign(u,this.options),!0}}]),t}(DrawEcharts),DrawEchartsTreemap=function(e){function t(){return _classCallCheck(this,t),_possibleConstructorReturn(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return _inherits(t,e),_createClass(t,[{key:"getLevelOption",value:function(){return[{itemStyle:{normal:{borderWidth:0,gapWidth:5}}},{itemStyle:{normal:{gapWidth:1}}},{colorSaturation:[.35,.5],itemStyle:{normal:{gapWidth:1,borderColorSaturation:.6}}}]}},{key:"buildTreeData",value:function(e,t){var a=[],n=this;return _.forEach(e,function(e,r){var i=t[r],s={};if(s.value=i.__value,_.isObject(e)){var o=n.buildTreeData(e,i);_.isArray(o)&&o.length&&(s.children=o)}s.name=r,a.push(s)}),a}},{key:"create",value:function(){var e=this.getDrawCommandObject(),t={path:"",title:"TreeMap",tooltip:"Usage",valueformat:!1};e&&(t=Object.assign(t,e));var a="";t.path&&(a=t.path),_.isString(e)&&(a=e);var n=_.split(a,"."),r=n.length;if(!r)return this.setError("Not set path"),!1;for(var i=0;r>i;i+=1)if(!this.haveColumn(n[i]))return this.setError("bad path, no column:"+n[i]),!1;if(!this.isNumericColumn(n[r-1]))return this.setError("bad column:"+n[r-1]+" must be number"),!1;var s={},o={};this.data().forEach(function(e){for(var t=e[n[r-1]],a=[],i=0;r-1>i;i+=1){a.push(e[n[i]]);var c=_.get(s,a.join("_"),0);_.set(s,a.join(".")+".__value",parseFloat(c)+parseFloat(t))}_.set(o,a.join("."),t)});var c=this.buildTreeData(o,s),l={tooltip:{trigger:"item"}},d=echarts.format;return l.series=[{type:"treemap",name:t.title,label:{show:!0,formatter:"{b}"},tooltip:{formatter:function(e){for(var a=e.value,n=[],r=e.treePathInfo,i=1;i'+d.encodeHTML(n.join("."))+"",t.tooltip+" : "+numbro(a).format(s)].join("")}},itemStyle:{normal:{borderColor:"#fff"}},levels:this.getLevelOption(),data:c}],this.options=Object.assign(l,this.options),!0}}]),t}(DrawEcharts),DrawEchartsSunkeys=function(e){function t(){return _classCallCheck(this,t),_possibleConstructorReturn(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return _inherits(t,e),_createClass(t,[{key:"create",value:function(){this.helpLink="https://tabix.io/doc/draw/Draw_Sankeys/",this.help="Default config : {path:''} or {value:'',source:'',target:''}, if empty path or not set, try auto create path, then find columns [String] : [Integer|Float] : [String] ";var e=this.getDrawCommandObject(),t={path:"",value:"value",source:"source",target:"target"};e&&(t=Object.assign(t,e));var a="";_.isString(e)?a=e:t.path?a=t.path:this.haveColumn(t.source)&&this.haveColumn(t.value)&&this.haveColumn(t.target)&&(a=t.source+"."+t.value+"."+t.target);var n=[];if(a)n=_.split(a,".");else{var r=!1,i=this.getColumns();for(var s in i){var o=i[s];this.isNumericColumn(o)&&r&&(n.push(o),r=!1),this.isStringColumn(o)&&!r&&(n.push(o),r=!0)}}if(console.log("patharr>",n),!n.length)return this.setError("The value of the variable 'path' - empty"),!1;if(!(1&n.length))return this.setError("The value of the variable 'path' must be odd"),!1;var c=[],l=[];this.data().forEach(function(e){for(var t=0;ta&&(a=s),e[t.destination.longitude]&&e[t.destination.latitude]){var o="";e[t.destination.name]&&(o=e[t.destination.name]),r.push({fromName:e[t.name],toName:o,coords:[[e[t.longitude],e[t.latitude]],[e[t.destination.longitude],e[t.destination.latitude]]]})}n.push({name:e[t.name],value:[e[t.longitude],e[t.latitude],s],label:{emphasis:{position:"right",show:!0}}})});var i=[{name:t.title,type:"effectScatter",coordinateSystem:"geo",data:n,showEffectOn:"render",rippleEffect:{brushType:"stroke"},symbolSize:function(e){return a?e[2]/a*15:e[2]/1e4},hoverAnimation:!0,label:{normal:{formatter:"{b}",position:"right",show:!0}},itemStyle:{normal:{color:"#f4e925",shadowBlur:10,shadowColor:"#333"}},zlevel:1}];if(r.length>0){var s="path://M1705.06,1318.313v-89.254l-319.9-221.799l0.073-208.063c0.521-84.662-26.629-121.796-63.961-121.491c-37.332-0.305-64.482,36.829-63.961,121.491l0.073,208.063l-319.9,221.799v89.254l330.343-157.288l12.238,241.308l-134.449,92.931l0.531,42.034l175.125-42.917l175.125,42.917l0.531-42.034l-134.449-92.931l12.238-241.308L1705.06,1318.313z"; +i.push({name:t.title,type:"lines",zlevel:1,effect:{show:!0,period:6,trailLength:.7,color:"#fff",symbolSize:3},lineStyle:{normal:{width:0,curveness:.2}},data:r}),i.push({name:t.title,type:"lines",zlevel:2,symbol:["none","arrow"],symbolSize:10,effect:{show:!0,period:6,trailLength:0,symbol:s,symbolSize:15},lineStyle:{normal:{width:1,opacity:.6,curveness:.2}},data:r})}var o={tooltip:{trigger:"item"},geo:{name:t.title,type:"map",map:"world",label:{emphasis:{show:!1}},visualMap:{show:!0,min:0,max:100,inRange:{symbolSize:[6,60]}},roam:!0,itemStyle:{normal:{areaColor:"#323c48",borderColor:"#404a59"},emphasis:{areaColor:"#2a333d"}}},series:i};return this.options=Object.assign(this.options,o),!0}}]),t}(DrawEcharts),DrawEchartsHeatmap=function(e){function t(){return _classCallCheck(this,t),_possibleConstructorReturn(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return _inherits(t,e),_createClass(t,[{key:"create",value:function(){var e=this.getParameterPath();if(!e)return this.setError("Not set path"),!1;var t={},a={},n={};this.data().forEach(function(r){_.set(t,r[e[0]],1),_.set(a,r[e[1]],1),_.set(n,r[e[0]]+"."+r[e[1]],parseFloat(r[e[2]]))});var r=[],i=_.keys(t),s=_.keys(a),o=0,c=0;_.mapKeys(t,function(e,t){_.mapKeys(a,function(e,a){var i=_.get(n,t+"."+a,"-");o>i&&(o=i),i>c&&(c=i),r.push([t,a,i])})});var l={tooltip:{position:"top"},animation:!1,grid:{height:"50%",y:"10%"},xAxis:{type:"category",data:i,splitArea:{show:!0}},yAxis:{type:"category",data:s,splitArea:{show:!0}},visualMap:{min:o,max:c,calculable:!0,orient:"horizontal",left:"center",bottom:"15%"},series:[{name:"Punch Card",type:"heatmap",data:r,label:{normal:{show:!0}},itemStyle:{emphasis:{shadowBlur:10,shadowColor:"rgba(0, 0, 0, 0.5)"}}}]};return this.options=Object.assign(l,this.options),!0}}]),t}(DrawEcharts),DrawEchartsChart=function(e){function t(){return _classCallCheck(this,t),_possibleConstructorReturn(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return _inherits(t,e),_createClass(t,[{key:"create",value:function(){console.log("DrawEchartsChart");var e=this.getDrawCommandObject(),t=this.preCreate(e),a=this.createChart(e),n={tooltip:{trigger:"axis",axisPointer:{type:"shadow"}},grid:{left:"3%",right:"4%",bottom:"3%",containLabel:!0}};return e.title&&this.applyTitle(e.title),this.applyDataZoom(),this.applyLegend(),this.options=Object.assign(a,this.options,n,t),this.postCreate(e),!0}},{key:"findDateTimeAxis",value:function(){var e=this.getDateTimeColumn();if(e)return e;var t=this.getDateColumn();return t?t:!1}},{key:"postCreate",value:function(e){return{}}},{key:"preCreate",value:function(e){return{}}},{key:"createChart",value:function(e){var t=this,a={autoAxis:!1,markLine:!0,stack:!1,path:!1,sort:!0,xAxis:!1,yAxis:!1};e&&(a=Object.assign(a,e));var n={},r=this.getColumns(),i=this.getFirstColumn(),s=i,o=this.findDateTimeAxis(),c={},l=[],d=[],u=[],m={},h=this.data();if(o&&(i=o),a.xAxis){if(!this.haveColumn(a.xAxis))throw"xAxis column not exists";s=a.xAxis}else a.sort&&(h=_.sortBy(h,i)),s=i;if(d=[{name:s,type:"category",data:[]}],a.yAxis)if(_.isString(a.yAxis)){if(!this.haveColumn(a.yAxis))throw"yAxis column not exists";n[a.yAxis]=1}else{if(!_.isArray(a.yAxis))throw"yAxis column must string or array";var p=void 0;for(p=0;pk&&!w?(_.isArray(y)||(y=[]),y.push(S),k++):this.isNumericColumn(S)&&x.push(S))}var A=h.length;for(console.log("DATA LEN",A,h),v=0;A>v;++v){var D=h[v];d[0].data.push(D[d[0].name])}for(d[0].data=_.uniq(d[0].data),console.log("xAxis[0].data.",d[0].data),v=0;A>v;++v){var R=h[v],E=function(e){var a=r[e],i=[s],o=!1;if(_.size(n)&&(o=_.isUndefined(n[a])),a!==s&&!o&&t.isNumericColumn(a)&&_.findIndex(y,a)<0){if(y)for(var c=0;c1){var q=_.groupBy(f,function(e){return Math.floor(e.median/1e3)});if(_.size(q)>1){var P=function(e){var t=q[e],n=_.map(t,"column").join(",");_.forEach(t,function(e){u[e.index].yAxisIndex=l.length,a.stack&&(u[e.index].stack=n,u[e.index].areaStyle={normal:{}})}),l.push({name:n,type:"value"})};for(var H in q)P(H)}}return l.length||(l=[{name:b,type:"value"}]),c.series=u,c.yAxis=l,c.xAxis=d,console.info("Make Chart Done : Options",c),c}}]),t}(DrawEcharts),DrawEchartsGridChart=function(e){function t(){return _classCallCheck(this,t),_possibleConstructorReturn(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return _inherits(t,e),_createClass(t,[{key:"preCreate",value:function(e){return this.preference.gridchart=!0,{}}},{key:"postCreate",value:function(e){var t=[],a=[],n=[],r=[],i=0;console.info("postCreate!!!!!!",this.options);var s=[],o=this.options.xAxis[0],c=this.options.yAxis[0];for(var l in this.options.series){l=parseInt(l);var d=this.options.series[l].name;this.options.series[l].xAxisIndex=l,this.options.series[l].yAxisIndex=i,console.log(d,this.options.series[l]),o.show=!1,o.gridIndex=l,c.gridIndex=l,c.show=!1,c.name=d,t.push({show:!0,borderWidth:0,shadowBlur:2}),n.push(_.clone(o)),a.push(_.clone(c)),r.push({textAlign:"center",text:d,textStyle:{fontSize:11,fontWeight:"normal"}}),s.push(l),i+=1}var u=Math.ceil(Math.sqrt(i));t.forEach(function(e,t){e.left=t%u/u*100+.5+"%",e.top=Math.floor(t/u)/u*100+.5+"%",e.width=1/u*100-1+"%",e.height=1/u*100-1+"%",r[t].left=parseFloat(e.left)+parseFloat(e.width)/2+"%",r[t].top=parseFloat(e.top)+"%"}),this.options.dataZoom&&this.options.dataZoom[0]&&(this.options.dataZoom[0].xAxisIndex=s),this.options.titles=r,this.options.grid=t,this.options.xAxis=n,this.options.yAxis=a}}]),t}(DrawEchartsChart),DrawEchartsBar=function(e){function t(){return _classCallCheck(this,t),_possibleConstructorReturn(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return _inherits(t,e),_createClass(t,[{key:"preCreate",value:function(e){return this.preference.bar=!0,{}}}]),t}(DrawEchartsChart),DrawD3=function(e){function t(e){_classCallCheck(this,t);var a=_possibleConstructorReturn(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));return a.library="d3",a}return _inherits(t,e),t}(DrawBasicChart),DrawC3=function(e){function t(e){_classCallCheck(this,t);var a=_possibleConstructorReturn(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));return a.library="c3",a.bindto=!1,a}return _inherits(t,e),_createClass(t,[{key:"onResize",value:function(){this.chart&&this.init}},{key:"preProcessor",value:function(){return console.log("preProcessor>c3.generate"),this.initChartByJsCode()?(console.log("c3.options>",this.options),this.bindto.className+=" c3",console.log("this.bindto.className",this.bindto.className),this.options.bindto=this.bindto,console.log("c3.options>",this.options),void(this.chart=c3.generate(this.options))):(console.error("C3.Init by code"),!1)}}]),t}(DrawBasicChart),DrawAMcharts=function(e){function t(e){_classCallCheck(this,t),console.warn("DrawAMcharts constructor");var a=_possibleConstructorReturn(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));return a.library="amchart",a}return _inherits(t,e),_createClass(t,[{key:"onResize",value:function(){this.makeLegend()}},{key:"preProcessor",value:function(){this.createChart()&&(this.init=!0),console.log("!preProcessor,done",this.init,this.options)}},{key:"createChart",value:function(){var e=this,t={},a=this.widget.data.meta,n=!1,r="",i="mm",s=[],o=0,c=[];a.forEach(function(a){if("DateTime"==a.type)n="YYYY-MM-DD JJ:NN:SS",r=a.name;else if("Date"==a.type)n="YYYY-MM-DD",i="DD",r=a.name;else{if(!r)return void(r=a.name);o+=1;var l=e.getChartGraph(a,t[a.name]);l.id="g"+o,"v1"!==l.valueAxis&&c.push(l.valueAxis),s.push(l)}});var l={theme:Widget.isDark?"dark":"light",color:Widget.isDark?"#eee":"#333",type:"serial",categoryField:r,valueAxes:[{id:"v1",axisAlpha:1,gridAlpha:.07,axisColor:Widget.isDark?"#eee":"#333",gridColor:Widget.isDark?"#eee":"#333",ignoreAxisWidth:!0}],balloon:{borderThickness:1,shadowAlpha:0},graphs:s,chartCursor:{valueLineEnabled:!0,valueLineBalloonEnabled:!0,cursorAlpha:0,zoomable:!1,valueZoomable:!0,valueLineAlpha:.5},chartScrollbar:{graph:"g1",gridAlpha:0,color:"#888888",scrollbarHeight:25,backgroundAlpha:0,selectedBackgroundAlpha:.1,selectedBackgroundColor:"#888888",graphFillAlpha:0,autoGridCount:!0,selectedGraphFillAlpha:0,graphLineAlpha:.2,graphLineColor:"#c2c2c2",selectedGraphLineColor:"#888888",selectedGraphLineAlpha:1},categoryAxis:{dashLength:1,minorGridEnabled:!0,axisColor:Widget.isDark?"#eee":"#333",gridColor:Widget.isDark?"#eee":"#333"},data:this.widget.data.data};if(l.categoryAxis.parseDates=!1,n&&(l.dataDateFormat=n,l.categoryAxis.parseDates=!0,l.categoryAxis.minPeriod=i),c){var d=0;c.forEach(function(e){d++;var t={id:e,axisAlpha:1,axisThickness:1,position:"right",ignoreAxisWidth:!0,offset:1*d};l.valueAxes.push(t)})}return this.options=l,this.init=!0,this.makeLegend(),!0}},{key:"makeLegend",value:function(){console.log("this.widget.sizeY",this.widget.sizeY),this.widget.sizeY<2?delete this.options.legend:this.options.legend={align:"center",equalWidths:!1,periodValueText:"total: [[value.sum]]",valueAlign:"left",valueText:"[[value]] ([[percents]]%)",valueWidth:100},console.warn(this.options)}},{key:"getChartGraph",value:function(e,t){var a=e.name,n=e.name,r="v1";a=a.replace(/_axis\d+/gm,"");var i=/.*_axis(\d+).*/i,s=n.match(i);s&&s[1]&&(r="v"+s[1]);var o={id:"g1",valueAxis:r,fillAlphas:.2,bullet:"round",bulletSize:8,hideBulletsCount:50,lineThickness:1,title:a,useLineColorForBulletBorder:!0,valueField:n,type:"smoothedLine",balloonText:"[[title]] [[category]]
[[value]]"};return t||(t={}),Object.assign(o,t)}}]),t}(DrawBasicChart),DataProvider=function(){function e(t,a){_classCallCheck(this,e),t.totals&&t.data&&t.data.push(t.totals),this.data=t.data,this.text=!1,this.progressQuery="",this.sort=!1,this.sortOrder=!1,t.error||angular.isObject(t.data)||(angular.isString(t.data)?this.text=t.data:this.text=angular.toJson(t.data,!0),this.text=this.text.replace(/&/g,"&").replace(//g,">")),a||(a="ch"),this.sourceType=a,this.meta=t.meta,t.query?this.query=t.query:this.query={index:0,drawCommands:!1},t.error?(this.error=t.error.replace("
","\n").replace(/&/g,"&").replace(//g,">"),this.error=this.error.replace("\\n","
")):this.error=!1,this.draw=this.query.drawCommands,this.rows=t.rows,this.position=this.query.index,this.countAll=t.countAllQuery}return e.$inject=["result","sourceType"],_createClass(e,[{key:"isText",value:function(){return this.text?!0:!1}},{key:"isError",value:function(){return this.error?!0:!1}},{key:"getError",value:function(){return this.error}},{key:"data",value:function(){return this.data}},{key:"meta",value:function(){return this.meta}},{key:"toString",value:function(){return"("+this.name+", "+this.y+")"}}],[{key:"convertArrayToDataProvider",value:function(t,a){var n={};return n.data=t,n.meta=[],n.error=!1,n.query={drawCommands:!1},n.rows=t.length,n.position=0,n.countAll=0,Object.keys(t[0]).map(function(e){return n.meta.push({name:e,type:"string"})}),new e(n,a)}}]),e}();angular.module(smi2.app.name).service("DataProvider",DataProvider),angular.module("ui.ace",[]).constant("uiAceConfig",{}).directive("uiAce",["uiAceConfig",function(e){if(angular.isUndefined(window.ace))throw new Error("ui-ace need ace to work... (o rly?)");return{restrict:"EA",link:function(t,a,n){var r=e.ace||{},i=angular.extend({},r,t.$eval(n.uiAce)),s=window.ace.edit(a[0]);console.time("Ace Load"),i.onLoad(s),console.timeEnd("Ace Load"),a.on("$destroy",function(){s.session.$stopWorker(),s.destroy()}),t.$watch(function(){return[a[0].offsetWidth,a[0].offsetHeight]},function(){s.resize(),s.renderer.updateFull()},!0)}}}]),/* * Copyright (c) 2017. Smi2 */ angular.module(smi2.app.name).directive("pivot",[function(){return{restrict:"AE",scope:{data:"=",config:"=",editMode:"="},link:function(e,t,a){var n=$.extend($.pivotUtilities.renderers);null==e.config&&(e.config={rows:[],cols:[]}),e.renderPivotTable=function(){$(t).pivot(e.data,{renderers:n,rendererName:"Table",cols:e.config.cols,rows:e.config.rows,onRefresh:function(t){var a=JSON.parse(JSON.stringify(t));delete a.aggregators,delete a.renderers,delete a.derivedAttributes,delete a.rendererOptions,delete a.localeStrings,e.config=a,e.$apply()}})},e.renderPivotUITable=function(){$(t).pivotUI(e.data)},e.$watch("scope.editMode",function(t,a){console.log("watch"+e.editMode),t&&(e.editMode?e.renderPivotUITable():e.renderPivotTable())},!0),e.renderPivotUITable()}}}]),/** @@ -65,8 +65,8 @@ function(){angular.module("gridstack-angular",[]);var e=angular.module("gridstac */ function(e,t){function a(t,a,n){var r="";if("echarts"==t.draw.library){var i="macarons";t.isDark&&(i="dark"),t.draw.chart=echarts.init(a[0],i),r=!1}if("plotly"==t.draw.library&&(t.element=e.element('
 
'),r=!1),"c3"==t.draw.library){var s=document.createElement("div");t.draw.bindto=s,a[0].appendChild(s),r=!1}return"text"==t.draw.library&&(t.element=e.element('
 
'),r=!1),"d3"==t.draw.library&&console.info("DW:d3"),"gmaps"==t.draw.library&&(t.element=e.element('
 
'),r=!1),console.group("widget.draw.preProcessor"),console.time("widget.draw.preProcessor time took"),t.draw.preProcessor instanceof Function&&t.draw.preProcessor(),console.timeEnd("widget.draw.preProcessor time took"),console.groupEnd(),r}function n(t,n){return function(r,i,s){r.widget.type;if(console.time("drawWidget.buildLinkFunc"),r.widget.isDark=r.isdark,r.widget.preProcessor instanceof Function&&r.widget.preProcessor(),r.widget.error||r.widget.textformat||r.widget.text||r.widget.empty)return console.log("widget Have Error",r.widget.error),r.widget.error&&i.html("
"+r.widget.error+"
"),r.widget.text&&i.html("
"+r.widget.text+"
"),r.widget.empty&&i.html("NO DATA"),void i.addClass("grid-monospace");if("table"==r.widget.type&&(r.widget.element=e.element('
')),"draw"==r.widget.type){r.widget.element=!1;var o=a(r.widget,i,n);o&&(r.widget.element=e.element(o))}"pivot"==r.widget.type&&(r.widget.element=e.element('')),r.widget.element?(i.append(r.widget.element),t(r.widget.element)(r),r.widget.element.on("$destroy",r.widget.destroy(r.widget))):i.on("$destroy",r.widget.destroy(r.widget)),r.widget.postProcessor instanceof Function&&r.widget.postProcessor(),r.$watch(function(){return[i[0].offsetWidth,i[0].offsetHeight].join("x")},function(e){r.widget.scheduledResize()}),r.events={resize:function(e,t){n(function(){t.widget.scheduledResize()},300)}},n(function(){r.widget.scheduledResize()},300),console.timeEnd("drawWidget.buildLinkFunc")}}e.module(t.app.name).directive("drawWidget",["$compile","$timeout",function(e,t){return{restrict:"EA",template:'
',scope:{widget:"=widget",isdark:"=isdark"},replace:!0,link:n(e,t)}}])}(angular,smi2),angular.module("angularResizable",[]).directive("resizable",function(){function e(e){void 0===t?(t=e,setTimeout(function(){t(),t=void 0},100)):t=e}var t;return{restrict:"AE",scope:{rDirections:"=",rCenteredX:"=",rCenteredY:"=",rWidth:"=",rHeight:"=",rFlex:"=",rGrabber:"@",rDisabled:"@",rNoThrottle:"=",resizable:"@"},link:function(t,a,n){if("false"!==t.resizable){var r="flexBasis"in document.documentElement.style?"flexBasis":"webkitFlexBasis"in document.documentElement.style?"webkitFlexBasis":"msFlexPreferredSize"in document.documentElement.style?"msFlexPreferredSize":"flexBasis";t.$watch("rWidth",function(e){a[0].style[t.rFlex?r:"width"]=e!==!1?e+"px":""}),t.$watch("rHeight",function(e){a[0].style[t.rFlex?r:"height"]=e!==!1?e+"px":""}),a.addClass("resizable");var i,s,o,c,l,d=window.getComputedStyle(a[0],null),u=t.rDirections||["right"],m=t.rCenteredX?2:1,h=t.rCenteredY?2:1,p=t.rGrabber?t.rGrabber:"",g={},f=function(e){g.width=!1,g.height=!1,"x"===l?g.width=parseInt(a[0].style[t.rFlex?r:"width"]):g.height=parseInt(a[0].style[t.rFlex?r:"height"]),g.id=a[0].id,g.evt=e},b=function(e){return e.touches?e.touches[0].clientX:e.clientX},v=function(e){return e.touches?e.touches[0].clientY:e.clientY},y=function(n){function d(){t.$emit("angular-resizable.resizing",g)}var u,p="x"===l?o-b(n):o-v(n);switch(c){case"top":u=t.rFlex?r:"height",a[0].style[u]=s+p*h+"px";break;case"bottom":u=t.rFlex?r:"height",a[0].style[u]=s-p*h+"px";break;case"right":u=t.rFlex?r:"width",a[0].style[u]=i-p*m+"px";break;case"left":u=t.rFlex?r:"width",a[0].style[u]=i+p*m+"px"}f(n),t.rNoThrottle?d():e(d)},w=function C(e){f(),t.$emit("angular-resizable.resizeEnd",g),t.$apply(),document.removeEventListener("mouseup",C,!1),document.removeEventListener("mousemove",y,!1),document.removeEventListener("touchend",C,!1),document.removeEventListener("touchmove",y,!1),a.removeClass("no-transition")},k=function(e){var n={},i=!1,s=!1;n.width=parseInt(a[0].style[t.rFlex?r:"width"]),n.height=parseInt(a[0].style[t.rFlex?r:"height"]),"right"==c&&(n.width>10?(t.preState=n,i=0,s=0):(t.preState&&t.preState.width||(t.preState.width=100),s=t.preState.height,i=t.preState.width)),"bottom"==c&&(n.height>10?(t.preState=n,s=0):(t.preState&&t.preState.height||(t.preState.height=100),s=t.preState.height,i=t.preState.width)),i!==!1&&(a[0].style[t.rFlex?r:"width"]=i+"px"),s!==!1&&(a[0].style[t.rFlex?r:"height"]=s+"px"),t.$apply()},x=function(e,n){c=n,l="left"===c||"right"===c?"x":"y",o="x"===l?b(e):v(e),i=parseInt(d.getPropertyValue("width")),s=parseInt(d.getPropertyValue("height")),a.addClass("no-transition"),document.addEventListener("mouseup",w,!1),document.addEventListener("mousemove",y,!1),document.addEventListener("touchend",w,!1),document.addEventListener("touchmove",y,!1),e.stopPropagation&&e.stopPropagation(),e.preventDefault&&e.preventDefault(),e.cancelBubble=!0,e.returnValue=!1,f(e),t.$emit("angular-resizable.resizeStart",g),t.$apply()};u.forEach(function(e){var n=document.createElement("div");n.setAttribute("class","rg-"+e),n.innerHTML=p,a[0].appendChild(n),n.ondragstart=function(){return!1};var r=function(a){var n="true"===t.rDisabled;n||1!==a.which&&!a.touches||x(a,e)};n.addEventListener("dblclick",k,!1),n.addEventListener("mousedown",r,!1),n.addEventListener("touchstart",r,!1)})}}}});var csvImport=angular.module("ngCsvImport",[]);csvImport.directive("ngCsvImport",function(){return{restrict:"E",transclude:!0,replace:!0,scope:{content:"=?",header:"=?",headerVisible:"=?",separator:"=?",separatorVisible:"=?",result:"=?",encoding:"=?",encodingVisible:"=?",accept:"=?",acceptSize:"=?",acceptSizeExceedCallback:"=?",callback:"=?",mdButtonClass:"@?",mdInputClass:"@?",mdButtonTitle:"@?",mdSvgIcon:"@?",uploadButtonLabel:"="},template:function(e,t){var a=angular.isDefined(t.material),n=angular.isDefined(t.multiple);return'
Header
'+(a?'
':'')+'
Encoding
{{encoding}}
Seperator
'+(a?' {{mdButtonTitle}}':"")+"
"},link:function(e,t,a){if(e.separatorVisible=!!e.separatorVisible,e.headerVisible=!!e.headerVisible,e.acceptSize=e.acceptSize||Number.POSITIVE_INFINITY,e.material=angular.isDefined(a.material),e.multiple=angular.isDefined(a.multiple),e.multiple)throw new Error("Multiple attribute is not supported yet.");var n=angular.element(t[0].querySelector('input[type="file"]')),r=angular.element(t[0].querySelector("md-input-container"));if(e.material&&n){if(n.removeClass("ng-show"),n.addClass("ng-hide"),r){var i=angular.element(r[0].querySelector("div.md-errors-spacer"));i&&i.remove()}e.onClick=function(){n.click()}}angular.element(t[0].querySelector(".separator-input")).on("keyup",function(t){if(null!=e.content){var a={csv:e.content,header:e.header,separator:t.target.value,encoding:e.encoding};e.result=s(a),e.$apply(),"function"==typeof e.callback&&e.callback(t)}}),t.on("change",function(t){if(t.target.files&&t.target.files.length){if(t.target.files[0].size>e.acceptSize)return void("function"==typeof e.acceptSizeExceedCallback&&e.acceptSizeExceedCallback(t.target.files[0]));e.filename=t.target.files[0].name;var a=new FileReader;if(a.onload=function(a){e.$apply(function(){var n={csv:a.target.result.replace(/\r\n|\r/g,"\n"),header:e.header,separator:e.separator};e.content=n.csv,e.result=s(n),e.result.filename=e.filename,e.$$postDigest(function(){"function"==typeof e.callback&&e.callback(t)})})},"file"!==t.target.type||null==t.target.files&&null==t.srcElement.files){if(null!=e.content){var n={csv:e.content,header:!e.header,separator:e.separator};e.result=s(n),e.$$postDigest(function(){"function"==typeof e.callback&&e.callback(t)})}}else a.readAsText((t.srcElement||t.target).files[0],e.encoding)}});var s=function(e){var t=e.csv.split(new RegExp('\n(?![^"]*"(?:(?:[^"]*"){2})*[^"]*$)')),a=[],n=0,r=t[0].split(e.separator).length,i=[];e.header&&(i=t[0].split(e.separator),n=1);for(var s=n;s3e4&&(a=3e4),t.fetchQuery("SELECT now(),number,sin(number),sin(number),SHA1(toString(number)),SHA1(toString(number)) as xx from system.numbers limit "+a).then(function(t){var a="ch",n=new DataProvider(t,a);n.progressQuery="SQL";var r=new WidgetTable(n);e.w=r,e.vars.show=!0,e.vars.counter++,console.info("Load done",e.vars.counter,e.vars.show)})},e._widgetsx=[],e.removeResult=function(t,a,n){n.stopPropagation(),delete e.listDashboards[a]},e.inits=function(){e.listDashboards={}},e.inits(),e.moveWidget=function(){e.widgets[0].x=1,e.widgets[0].width=2,e.widgets[0].height=2},e.removeWidget=function(t){var a=e.widgets.indexOf(t);e.widgets.splice(a,1)},e.onChange=function(e,t){console.log("onChange event: "+e+" items:"+t)},e.onDragStart=function(e,t){console.log("onDragStart event: "+e+" ui:"+t)},e.onDragStop=function(e,t){console.log("onDragStop event: "+e+" ui:"+t)},e.onResizeStart=function(e,t){console.log("onResizeStart event: "+e+" ui:"+t)},e.onResizeStop=function(e,t){console.log("onResizeStop ",t.size)},e.onItemAdded=function(e){console.log("onItemAdded item: "+e)},e.onItemRemoved=function(e){console.log("onItemRemoved item: "+e)}}e.module(t.app.name).controller("DashController",a),a.$inject=["$scope","API","ThemeService","$interval","localStorageService","$mdDialog","$window","hotRegisterer"]}(angular,smi2),function(e,t){function a(t,a,n,r,i,s,o,c){t.vars={isDark:r.isDark(),historysql:a.sqlLog,charthelp:[],active:{chart:!0,history:!0,snippet:!0,vars:!0},snippets:o.snippets,variables:s.vars},t.vars.scrollConfig2={autoHideScrollbar:!1,theme:r.isDark()?"light":"dark",scrollButtons:{enable:!1},scrollInertia:400,setHeight:200,advanced:{updateOnContentResize:!0}},t.showAddVarsDialog=function(a){c.show({controller:["$scope","$mdDialog",function(e,t){e.v={name:"Var1",type:"text",value:""},e.close=function(){t.cancel()},e.add=function(e){t.hide(e)}}],templateUrl:"app/base/addVarsDialog.html",parent:e.element(document.body),targetEvent:a,clickOutsideToClose:!0}).then(function(e){e.name&&e.value&&e.type&&(s.addVar(e.type,e.name,e.value),t.broadcast())},function(){})},t.broadcast=function(){a.$emit("handleBroadcastUpdateVarsAndSnippets",{value:!0})},t.changed=function(e){s.update(e),t.broadcast()},t.showState=function(){console.warn(t.vars.variables)},t.addVar=function(){s.addVar("int","limit",1e3),t.broadcast()},t.actionHistory=function(e){a.$emit("handleBroadcastInsertInActive",{value:e})},t.dropSnippet=function(e){o.drop(e),t.broadcast()},t.dropVar=function(e){s.drop(e),t.broadcast()},t.init=function(){(!_.isObject(t.vars)||_.isUndefined(t.vars.variables.limit))&&s.addVar("int","limit",1e3)},t.init()}e.module(t.app.name).controller("SidebarHelperCtrl",a),a.$inject=["$scope","$rootScope","API","ThemeService","localStorageService","Variables","Snippets","$mdDialog"]}(angular,smi2),function(e,t){function a(e,t,a,n,r,i,s,o,c,l){e.vars={searchline:"",counter:0,loaded:!1,error:!1,databases:[]},e.vars.scrollConfig={autoHideScrollbar:!1,theme:r.isDark()?"light":"dark",scrollButtons:{enable:!1},scrollInertia:400,advanced:{updateOnContentResize:!0}},e.vars.metis={config:{toggle:!1,preventDefault:!1}},e.clickInsertField=function(e){t.$emit("handleBroadcastInsertInActive",{value:e.name})},e.clickAndSelect=function(a,n){return a.name==t.currentDatabase?(n.stopPropagation(),!1):void e.selectDatabase(a)},e.selectDatabase=function(e){console.time("sidebar.selectDatabase time took"),t.currentDatabase=e.name,s.show(s.simple().content("USE "+e.name+" database").theme(r.theme).position("bottom right")),console.timeEnd("sidebar.selectDatabase time took")},e.openTable=function(e){console.log("openTable!!!!!!!!!!!!!!!!!!!!!!!"),i("tableSiedenav").close(),t.currentDatabase!=e.database&&(s.show(s.simple().content("USE "+e.database+" database").theme(r.theme).position("bottom right")),t.currentDatabase=e.database),t.currentTable=e.name,i("tableSiedenav").open()},t.$on("handleBroadcastDatabases",function(){e.reLoad(!0),e.$applyAsync()}),e.updateDS=function(){n.databaseStructure(function(e){a.reload()},!0)},e.rightMenuProcessTable=function(e,a,r,i){console.log("rightMenuProcessTable",e,a,r),"InsertSQLDrop"==e&&(-1!==r.indexOf(".")&&(r='"'+r+'"'),t.$emit("handleBroadcastInsertInActive",{value:"DROP TABLE IF EXISTS "+a+"."+r})),"InsertName"==e&&t.$emit("handleBroadcastInsertInActive",{value:a+"."+r}),"InsertSQLDescribe"==e&&n.query("SHOW CREATE TABLE "+a+'."'+r+'"').then(function(e){var a=window.sqlFormatter.format(e.data[0].statement);t.$emit("handleBroadcastInsertInActive",{value:a})}),"OpenTables"==e&&(window.location="/#/database/"+a+"/table/"+r),"InsertDescribe"==e&&n.query("SELECT * FROM system.columns WHERE database='"+a+"' AND table='"+r+"'").then(function(e){var n=[],i=[];e.data.forEach(function(e){n.push(e.name),"Date"==e.type&&i.push(e.name+"=today()")}),-1!==r.indexOf(".")&&(r='"'+r+'"');var s="\nSELECT\n "+n.join(",\n ")+"\nFROM\n "+a+"."+r+"\n";i.length&&(s=s+"\nWHERE\n "+i.join("\n AND \n")),s+="\nLIMIT 100\n\n",console.log(s),t.$emit("handleBroadcastInsertInActive",{value:s})})},e.showAlertDatabaseStructure=function(e){o.show(o.alert().clickOutsideToClose(!0).title("Error on load database structure").textContent(e).ariaLabel("Error on load database structure").ok("OK")).then(function(e){n.clear(),a.go("login")})},e.reLoad=function(a){e.vars.loaded=!1,e.vars.error=!1,e.vars.databases=[],t.isInitDatabaseStructure=!1,n.fetchQuery("SELECT 1").then(function(r){e.$applyAsync(),n.databaseStructure(function(a){console.log("isInitDatabaseStructure-true"),t.isInitDatabaseStructure=Date.now(),e.$applyAsync(),console.log("databaseStructure - done");var n=a.getFields();e.vars.databases=a.getTables().reduce(function(e,t){var a=[{active:!0,value:"Select",key:"OpenTables",icon:"arrow-expand",db:t.database}],r=[{active:!0,value:"Open table",key:"OpenTables",icon:"arrow-expand",db:t.database,table:t.name},{active:!0,value:"Code Select from",key:"InsertDescribe",icon:"format-size",db:t.database,table:t.name},{active:!0,value:"Insert table name",key:"InsertName",icon:"bing",db:t.database,table:t.name},{active:!0,value:"Make SQL Describe",key:"InsertSQLDescribe",icon:"border-vertical",db:t.database,table:t.name},{active:!0,value:"Make SQL Drop",key:"InsertSQLDrop",icon:"delete",db:t.database,table:t.name}],i="table";t.engine.match(/Dictionary.*/)&&(i="library"),t.engine.match(/Distributed.*/)&&(i="soundcloud"),t.engine.match(/AggregatingMergeTree.*/)&&(i="cube"),t.engine.match(/MaterializedView.*/)&&(i="border-bottom"),t.engine.match(/SummingMergeTree.*/)&&(i="table-row-plus-after"),t.engine.match(/CollapsingMergeTree.*/)&&(i="table-row-height"),t.engine.match(/$Merge^/)&&(i="source-fork"),t.active=!0,t.classEngine=i,t.rightMenuListTable=r;var s=!0,o=!1,c=void 0;try{for(var l,d=e[Symbol.iterator]();!(s=(l=d.next()).done);s=!0){var u=l.value;if("-"!==t.name&&u.name==t.database)return u.tables.push({active:!0,database:t.database,name:t.name,engine:t.engine,classEngine:t.classEngine,fields:n[t.database+"."+t.name],rightMenuList:t.rightMenuListTable}),e}}catch(m){o=!0,c=m}finally{try{!s&&d["return"]&&d["return"]()}finally{if(o)throw c}}return[].concat(_toConsumableArray(e),[{name:t.database,rightMenuList:a,tables:[{active:!0,database:t.database,name:t.name,engine:t.engine,classEngine:t.classEngine,rightMenuList:t.rightMenuListTable,fields:n[t.database+"."+t.name]}]}])},[]),e.selectDatabase(e.vars.databases[0]),a.getDatabases().forEach(function(t){var a=!1;e.vars.databases.forEach(function(e){e.name==t.name&&(a=!0)}),a||e.vars.databases.push({name:t.name,tables:[],active:!0})}),c(function(){e.vars.loaded=!0,e.vars.error=!1,$("#sideBarMetismenu").metisMenu()},100)},a)},function(t){e.showAlertDatabaseStructure(t)})},e.reLoad()}e.module(t.app.name).controller("SidebarController",a),a.$inject=["$scope","$rootScope","$state","API","ThemeService","$mdSidenav","$mdToast","$mdDialog","$timeout","localStorageService"]}(angular,smi2),function(e,t){function a(a,n,r,i,s){a.user=r.getConnectionInfo().name,a.themes=i.list,a.isChrome=/Chrome/.test(navigator.userAgent),a.vars={disable_exit:window.global_tabix_disable_exit,hideExitButton:!window.global_tabix_disable_exit},a.help=function(a){function n(e,a){e.vars={version:t.app.version,buildDate:t.app.buildDate},e.hide=function(){a.hide()},e.cancel=function(){a.cancel()},e.answer=function(e){a.hide(e)}}n.$inject=["$scope","$mdDialog"],s.show({controller:n,templateUrl:"app/base/helpDialogRu.html",parent:e.element(document.body),targetEvent:a,clickOutsideToClose:!0})},a.logout=function(){r.clear(),n.go("login")},a.setUiTheme=function(e){i.set(e.name),window.location.reload()}}e.module(t.app.name).controller("HeaderController",a),a.$inject=["$scope","$state","API","ThemeService","$mdDialog"]}(angular,smi2),ace.define("ace/theme/dracula",["require","exports","module","ace/lib/dom"],function(e,t,a){t.isDark=!0,t.cssClass="ace-dracula",t.cssText="ace-dracula .ace_gutter {background: #282a36;color: rgb(144,145,148)}.ace-dracula .ace_print-margin {width: 1px;background: #e8e8e8}.ace-dracula {background-color: #282a36;color: #f8f8f2}.ace-dracula .ace_cursor {color: #f8f8f0}.ace-dracula .ace_marker-layer .ace_selection {background: #44475a}.ace-dracula.ace_multiselect .ace_selection.ace_start {box-shadow: 0 0 3px 0px #282a36;border-radius: 2px}.ace-dracula .ace_marker-layer .ace_step {background: rgb(198, 219, 174)}.ace-dracula .ace_marker-layer .ace_bracket {margin: -1px 0 0 -1px;border: 1px solid #3B3A32}.ace-dracula .ace_marker-layer .ace_active-line {background: #44475a}.ace-dracula .ace_gutter-active-line {background-color: #44475a}.ace-dracula .ace_marker-layer .ace_selected-word {border: 1px solid #44475a}.ace-dracula .ace_fold {background-color: #50fa7b;border-color: #f8f8f2}.ace-dracula .ace_keyword {color: #ff79c6}.ace-dracula .ace_constant.ace_language {color: #bd93f9}.ace-dracula .ace_constant.ace_numeric {color: #bd93f9}.ace-dracula .ace_constant.ace_character {color: #bd93f9}.ace-dracula .ace_constant.ace_character.ace_escape {color: #ff79c6}.ace-dracula .ace_constant.ace_other {color: #bd93f9}.ace-dracula .ace_support.ace_function {color: #8be9fd}.ace-dracula .ace_support.ace_constant {color: #6be5fd}.ace-dracula .ace_support.ace_class {font-style: italic;color: #66d9ef}.ace-dracula .ace_support.ace_type {font-style: italic;color: #66d9ef}.ace-dracula .ace_storage {color: #ff79c6}.ace-dracula .ace_storage.ace_type {font-style: italic;color: #8be9fd}.ace-dracula .ace_invalid {color: #F8F8F0;background-color: #ff79c6}.ace-dracula .ace_invalid.ace_deprecated {color: #F8F8F0;background-color: #bd93f9}.ace-dracula .ace_string {color: #f1fa8c}.ace-dracula .ace_comment {color: #6272a4}.ace-dracula .ace_variable {color: #50fa7b}.ace-dracula .ace_variable.ace_parameter {font-style: italic;color: #ffb86c}.ace-dracula .ace_entity.ace_other.ace_attribute-name {color: #50fa7b}.ace-dracula .ace_entity.ace_name.ace_function {color: #50fa7b}.ace-dracula .ace_entity.ace_name.ace_tag {color: #ff79c6}";var n=e("../lib/dom");n.importCssString(t.cssText,t.cssClass)}),ace.define("ace/mode/clickhouse",["require","exports","module","ace/lib/oop","ace/mode/text","ace/token_iterator","ace/mode/folding","ace/mode/clickhouse_FoldMode","ace/mode/clickhouse_highlight_rules"],function(e,t){var a=e("../lib/oop"),n=e("./text").Mode,r=e("./clickhouse_highlight_rules").ClickhouseHighlightRules,i=e("./clickhouse_FoldMode").FoldMode,s=e("./matching_brace_outdent").MatchingBraceOutdent,o=e("./behaviour/cstyle").CstyleBehaviour,c=function(){this.foldingRules=new i,this.$outdent=new s,this.$behaviour=new o,this.HighlightRules=r};a.inherits(c,n),function(){var t=this;this.lineCommentStart="--",this.getHighlightRule=function(){return t.session.$mode.$highlightRules},this.getCompletions=function(e,t,a,n){return t.$mode.$highlightRules.completions},this.$id="ace/mode/clickhouse",this.checkOutdent=function(e,t,a){return this.$outdent.checkOutdent(t,a)},this.autoOutdent=function(e,t,a){this.$outdent.autoOutdent(t,a)},this.findTokens=function(t,a,n){t=t.replace(/^(\r\n|\n|\r)/gm,"").replace(/(\r\n|\n|\r)$/gm,"");for(var r=e("ace/token_iterator").TokenIterator,i=e("ace/edit_session").EditSession,s=new i(t,this),o=new r(s,0,0),c=o.getCurrentToken(),l=[];c;){var d=c;if(d.row=o.getCurrentTokenRow(),d.col=o.getCurrentTokenColumn(),d.type==a&&(l.push(d),n))return d.value=d.value.toLowerCase(),d;c=o.stepForward()}return l},this.trim=function(e,t){return t!==!0&&"string"==typeof t&&t.length>0&&(e=e.replace("^("+t+")"," ").replace(t+"$"," "),e=e.replace(new RegExp("^"+t+"|"+t+"$","g")," ")),e},this.collapseAll=function(e){for(var t=e,a=t.foldWidgets,n=t.getLength(),r=0,i=r;n>i;i++)if(null==a[i]&&(a[i]=t.getFoldWidget(i)),"start"==a[i]){var s=t.getFoldWidgetRange(i);if(s&&s.end.row<=n&&s.start.row>=r){i=s.end.row;try{var o=t.addFold("...",s);o&&(o.collapseChildren=depth)}catch(t){}}}},this.replaceVars=function(e,t){var a={},n=this.fetchTokens(e);if(console.warn("Find tokens",n,t),n.vars.length>0)for(var r in n.vars){var i=n.vars[r],s=i;i=i.indexOf("{")>-1?i.replace("{","").replace("}",""):i.replace("$","").replace("@","").replace(":","");for(var o in t){var c=t[o];c.name.toLowerCase()==i.toLowerCase()&&(console.info(c.name.toLowerCase(),"==",i.toLowerCase()),e=e.replace(s,c.value))}}return{sql:e,tokens:n,vars:a}},this.fetchTokens=function(t){var a={groupby:[],where:[],vars:[],limit:-1},n=e("ace/token_iterator").TokenIterator,r=e("ace/edit_session").EditSession,i=new r(t,this);i.bgTokenizer.start(0);for(var s=new n(i,0,0),o=s.getCurrentToken();o;){var c=o;if(c.row=s.getCurrentTokenRow(),c.col=s.getCurrentTokenColumn(),"variable.language"==c.type&&c.value&&a.vars.push(c.value),"keyword"==c.type&&c.value.toLowerCase().includes("limit")!==!1){var l=c.value.toLowerCase().match(/LIMIT\W+(\d+)\W*\,\W*(\d+)/i);l||(l=c.value.toLowerCase().match(/LIMIT\W+(\d+)/i)),l[0]&&l[1]&&l[2]?a.limit={from:l[1],to:l[2]}:l[0]&&l[1]&&(a.limit={from:l[1],to:!1})}o=s.stepForward()}return console.info("Parse & Find tokens result",a),a},this.splitByTokens=function(t,a,n){var r=e("ace/token_iterator").TokenIterator,i=e("ace/edit_session").EditSession,s=e("ace/range").Range,o=new i(t,this);o.bgTokenizer.start(0);var c=new r(o,0,0),l=c.getCurrentToken();if(_.isUndefined(l)){var d=0;do d++,c=new r(o,d,0),l=c.getCurrentToken();while(100>d&&!l)}for(var u=[],m=0,h=0,p=!1,g=void 0,f=void 0;l;){var b=l;if(b.row=c.getCurrentTokenRow(),b.col=c.getCurrentTokenColumn(),b.type==a&&(n!==!0&&b.value==n||n===!0)){var v=0;n instanceof String&&(v=n.length),g=new s(m,h,b.row,b.col+v),f=o.getTextRange(g),m=b.row,h=b.col+v,f=this.trim(f,b.value),f.length>2&&("string"==typeof p&&(f=this.trim(f,p)),u.push({sql:f,range:g,keyword:p}),p=b.value)}l=c.stepForward()}return g=new s(m,h,Number.MAX_VALUE,Number.MAX_VALUE),f=o.getTextRange(g),f=this.trim(f,n),"string"==typeof p&&(f=this.trim(f,p)),f.length>2&&u.push({sql:f,range:g,keyword:p}),u}}.call(c.prototype),t.Mode=c}),ace.define("ace/ext/whitespace",["require","exports","module","ace/lib/lang"],function(e,t,a){var n=e("../lib/lang");t.$detectIndentation=function(e,t){function a(e){for(var t=0,a=e;ac;c++){var l=e[c];if(/^\s*[^*+\-\s]/.test(l)){if(" "==l[0])i++,s=-Number.MAX_VALUE;else{var d=l.match(/^ */)[0].length;if(d&&" "!=l[d]){var u=d-s;!(u>0)||s%u||d%u||(r[u]=(r[u]||0)+1),n[d]=(n[d]||0)+1}s=d}for(;o>c&&"\\"==l[l.length-1];)l=e[c++]}}for(var m=r.reduce(function(e,t){return e+t},0),h={score:0,length:0},p=0,c=1;12>c;c++){var g=a(c);1==c?(p=g,g=n[1]?.9:.8,n.length||(g=0)):g/=p,r[c]&&(g+=r[c]/m),g>h.score&&(h={score:g,length:c})}if(h.score&&h.score>1.4)var f=h.length;return i>p+1?((1==f||i/4>p||h.score<1.8)&&(f=void 0),{ch:" ",length:f}):p>i+1?{ch:" ",length:f}:void 0},t.detectIndentation=function(e){var a=e.getLines(0,1e3),n=t.$detectIndentation(a)||{};return n.ch&&e.setUseSoftTabs(" "==n.ch),n.length&&e.setTabSize(n.length),n},t.trimTrailingSpace=function(e,t){for(var a=e.getDocument(),n=a.getAllLines(),r=t?-1:0,i=0,s=n.length;s>i;i++){var o=n[i],c=o.search(/\s+$/);c>r&&a.removeInLine(i,c,o.length)}},t.convertIndentation=function(e,t,a){var r=e.getTabString()[0],i=e.getTabSize();a||(a=i),t||(t=r);for(var s=" "==t?t:n.stringRepeat(t,a),o=e.doc,c=o.getAllLines(),l={},d={},u=0,m=c.length;m>u;u++){var h=c[u],p=h.match(/^\s*/)[0];if(p){var g=e.$getStringScreenWidth(p)[0],f=Math.floor(g/i),b=g%i,v=l[f]||(l[f]=n.stringRepeat(s,f));v+=d[b]||(d[b]=n.stringRepeat(" ",b)),v!=p&&(o.removeInLine(u,0,p.length),o.insertInLine({row:u,column:0},v))}}e.setTabSize(a),e.setUseSoftTabs(" "==t)},t.$parseStringArg=function(e){var t={};/t/.test(e)?t.ch=" ":/s/.test(e)&&(t.ch=" ");var a=e.match(/\d+/);return a&&(t.length=parseInt(a[0],10)),t},t.$parseArg=function(e){return e?"string"==typeof e?t.$parseStringArg(e):"string"==typeof e.text?t.$parseStringArg(e.text):e:{}},t.commands=[{name:"detectIndentation",exec:function(e){t.detectIndentation(e.session)}},{name:"trimTrailingSpace",exec:function(e){t.trimTrailingSpace(e.session)}},{name:"convertIndentation",exec:function(e,a){var n=t.$parseArg(a);t.convertIndentation(e.session,n.ch,n.length)}},{name:"setIndentation",exec:function(e,a){var n=t.$parseArg(a);n.length&&e.session.setTabSize(n.length),n.ch&&e.session.setUseSoftTabs(" "==n.ch)}}]}),function(){ace.require(["ace/ext/whitespace"],function(){})}(),ace.define("ace/ext/statusbar",["require","exports","module","ace/lib/dom","ace/lib/lang"],function(e,t,a){var n=e("ace/lib/dom"),r=e("ace/lib/lang"),i=function(e,t){this.element=n.createElement("div"),this.element.className="ace_status-indicator",this.element.style.cssText="display: inline-block;",t.appendChild(this.element);var a=r.delayedCall(function(){this.updateStatus(e)}.bind(this)).schedule.bind(null,100);e.on("changeStatus",a),e.on("changeSelection",a),e.on("keyboardActivity",a)};(function(){this.updateStatus=function(e){function t(e,t){e&&a.push(e,t||"|")}var a=[];t(e.keyBinding.getStatusText(e)),e.commands.recording&&t("REC");var n=e.selection,r=n.lead;if(!n.isEmpty()){var i=e.getSelectionRange();t("("+(i.end.row-i.start.row)+":"+(i.end.column-i.start.column)+")"," ")}t(r.row+":"+r.column," "),n.rangeCount&&t("["+n.rangeCount+"]"," "),a.pop(),this.element.textContent=a.join("")}}).call(i.prototype),t.StatusBar=i}),function(){ace.require(["ace/ext/statusbar"],function(){})}(),ace.define("ace/ext/spellcheck",["require","exports","module","ace/lib/event","ace/editor","ace/config"],function(e,t,a){var n=e("../lib/event");t.contextMenuHandler=function(e){var t=e.target,a=t.textInput.getElement();if(t.selection.isEmpty()){var r=t.getCursorPosition(),i=t.session.getWordRange(r.row,r.column),s=t.session.getTextRange(i);if(t.session.tokenRe.lastIndex=0,t.session.tokenRe.test(s)){var o="",c=s+" "+o;a.value=c,a.setSelectionRange(s.length,s.length+1),a.setSelectionRange(0,0),a.setSelectionRange(0,s.length);var l=!1;n.addListener(a,"keydown",function d(){n.removeListener(a,"keydown",d),l=!0}),t.textInput.setInputHandler(function(e){if(console.log(e,c,a.selectionStart,a.selectionEnd),e==c)return"";if(0===e.lastIndexOf(c,0))return e.slice(c.length);if(e.substr(a.selectionEnd)==c)return e.slice(0,-c.length);if(e.slice(-2)==o){var n=e.slice(0,-2);if(" "==n.slice(-1))return l?n.substring(0,a.selectionEnd):(n=n.slice(0,-1),t.session.replace(i,n),"")}return e})}}};var r=e("../editor").Editor;e("../config").defineOptions(r.prototype,"editor",{spellcheck:{set:function(e){var a=this.textInput.getElement();a.spellcheck=!!e,e?this.on("nativecontextmenu",t.contextMenuHandler):this.removeListener("nativecontextmenu",t.contextMenuHandler)},value:!0}})}),function(){ace.require(["ace/ext/spellcheck"],function(){})}(),ace.define("ace/ext/menu_tools/element_generator",["require","exports","module"],function(e,t,a){a.exports.createOption=function(e){var t,a=document.createElement("option");for(t in e)e.hasOwnProperty(t)&&("selected"===t?a.setAttribute(t,e[t]):a[t]=e[t]);return a},a.exports.createCheckbox=function(e,t,a){var n=document.createElement("input");return n.setAttribute("type","checkbox"),n.setAttribute("id",e),n.setAttribute("name",e),n.setAttribute("value",t),n.setAttribute("class",a),t&&n.setAttribute("checked","checked"),n},a.exports.createInput=function(e,t,a){var n=document.createElement("input");return n.setAttribute("type","text"),n.setAttribute("id",e),n.setAttribute("name",e), n.setAttribute("value",t),n.setAttribute("class",a),n},a.exports.createLabel=function(e,t){var a=document.createElement("label");return a.setAttribute("for",t),a.textContent=e,a},a.exports.createSelection=function(e,t,n){var r=document.createElement("select");return r.setAttribute("id",e),r.setAttribute("name",e),r.setAttribute("class",n),t.forEach(function(e){r.appendChild(a.exports.createOption(e))}),r}}),ace.define("ace/ext/modelist",["require","exports","module"],function(e,t,a){function n(e){for(var t=c.text,a=e.split(/[\/\\]/).pop(),n=0;n +/g,">"),u=function(e,t,a){var r=n.createElement("div");r.innerHTML=d,this.element=r.firstChild,this.setSession=this.setSession.bind(this),this.$init(),this.setEditor(e)};(function(){this.setEditor=function(e){e.searchBox=this,e.renderer.scroller.appendChild(this.element),this.editor=e},this.setSession=function(e){this.searchRange=null,this.$syncOptions(!0)},this.$initElements=function(e){this.searchBox=e.querySelector(".ace_search_form"),this.replaceBox=e.querySelector(".ace_replace_form"),this.searchOption=e.querySelector("[action=searchInSelection]"),this.replaceOption=e.querySelector("[action=toggleReplace]"),this.regExpOption=e.querySelector("[action=toggleRegexpMode]"),this.caseSensitiveOption=e.querySelector("[action=toggleCaseSensitive]"),this.wholeWordOption=e.querySelector("[action=toggleWholeWords]"),this.searchInput=this.searchBox.querySelector(".ace_search_field"),this.replaceInput=this.replaceBox.querySelector(".ace_search_field"),this.searchCounter=e.querySelector(".ace_search_counter")},this.$init=function(){var e=this.element;this.$initElements(e);var t=this;i.addListener(e,"mousedown",function(e){setTimeout(function(){t.activeInput.focus()},0),i.stopPropagation(e)}),i.addListener(e,"click",function(e){var a=e.target||e.srcElement,n=a.getAttribute("action");n&&t[n]?t[n]():t.$searchBarKb.commands[n]&&t.$searchBarKb.commands[n].exec(t),i.stopPropagation(e)}),i.addCommandKeyListener(e,function(e,a,n){var r=c.keyCodeToString(n),s=t.$searchBarKb.findKeyCommand(a,r);s&&s.exec&&(s.exec(t),i.stopEvent(e))}),this.$onChange=r.delayedCall(function(){t.find(!1,!1)}),i.addListener(this.searchInput,"input",function(){t.$onChange.schedule(20)}),i.addListener(this.searchInput,"focus",function(){t.activeInput=t.searchInput,t.searchInput.value&&t.highlight()}),i.addListener(this.replaceInput,"focus",function(){t.activeInput=t.replaceInput,t.searchInput.value&&t.highlight()})},this.$closeSearchBarKb=new o([{bindKey:"Esc",name:"closeSearchBar",exec:function(e){e.searchBox.hide()}}]),this.$searchBarKb=new o,this.$searchBarKb.bindKeys({"Ctrl-f|Command-f":function(e){var t=e.isReplace=!e.isReplace;e.replaceBox.style.display=t?"":"none",e.replaceOption.checked=!1,e.$syncOptions(),e.searchInput.focus()},"Ctrl-H|Command-Option-F":function(e){e.replaceOption.checked=!0,e.$syncOptions(),e.replaceInput.focus()},"Ctrl-G|Command-G":function(e){e.findNext()},"Ctrl-Shift-G|Command-Shift-G":function(e){e.findPrev()},esc:function(e){setTimeout(function(){e.hide()})},Return:function(e){e.activeInput==e.replaceInput&&e.replace(),e.findNext()},"Shift-Return":function(e){e.activeInput==e.replaceInput&&e.replace(),e.findPrev()},"Alt-Return":function(e){e.activeInput==e.replaceInput&&e.replaceAll(),e.findAll()},Tab:function(e){(e.activeInput==e.replaceInput?e.searchInput:e.replaceInput).focus()}}),this.$searchBarKb.addCommands([{name:"toggleRegexpMode",bindKey:{win:"Alt-R|Alt-/",mac:"Ctrl-Alt-R|Ctrl-Alt-/"},exec:function(e){e.regExpOption.checked=!e.regExpOption.checked,e.$syncOptions()}},{name:"toggleCaseSensitive",bindKey:{win:"Alt-C|Alt-I",mac:"Ctrl-Alt-R|Ctrl-Alt-I"},exec:function(e){e.caseSensitiveOption.checked=!e.caseSensitiveOption.checked,e.$syncOptions()}},{name:"toggleWholeWords",bindKey:{win:"Alt-B|Alt-W",mac:"Ctrl-Alt-B|Ctrl-Alt-W"},exec:function(e){e.wholeWordOption.checked=!e.wholeWordOption.checked,e.$syncOptions()}},{name:"toggleReplace",exec:function(e){e.replaceOption.checked=!e.replaceOption.checked,e.$syncOptions()}},{name:"searchInSelection",exec:function(e){e.searchOption.checked=!e.searchRange,e.setSearchRange(e.searchOption.checked&&e.editor.getSelectionRange()),e.$syncOptions()}}]),this.setSearchRange=function(e){this.searchRange=e,e?this.searchRangeMarker=this.editor.session.addMarker(e,"ace_active-line"):this.searchRangeMarker&&(this.editor.session.removeMarker(this.searchRangeMarker),this.searchRangeMarker=null)},this.$syncOptions=function(e){n.setCssClass(this.replaceOption,"checked",this.searchRange),n.setCssClass(this.searchOption,"checked",this.searchOption.checked),this.replaceOption.textContent=this.replaceOption.checked?"-":"+",n.setCssClass(this.regExpOption,"checked",this.regExpOption.checked),n.setCssClass(this.wholeWordOption,"checked",this.wholeWordOption.checked),n.setCssClass(this.caseSensitiveOption,"checked",this.caseSensitiveOption.checked),this.replaceBox.style.display=this.replaceOption.checked?"":"none",this.find(!1,!1,e)},this.highlight=function(e){this.editor.session.highlight(e||this.editor.$search.$options.re),this.editor.renderer.updateBackMarkers()},this.find=function(e,t,a){var r=this.editor.find(this.searchInput.value,{skipCurrent:e,backwards:t,wrap:!0,regExp:this.regExpOption.checked,caseSensitive:this.caseSensitiveOption.checked,wholeWord:this.wholeWordOption.checked,preventScroll:a,range:this.searchRange}),i=!r&&this.searchInput.value;n.setCssClass(this.searchBox,"ace_nomatch",i),this.editor._emit("findSearchBox",{match:!i}),this.highlight(),this.updateCounter()},this.updateCounter=function(){var e=this.editor,t=e.$search.$options.re,a=0,n=0;if(t){var r=this.searchRange?e.session.getTextRange(this.searchRange):e.getValue(),i=e.session.doc.positionToIndex(e.selection.anchor);this.searchRange&&(i-=e.session.doc.positionToIndex(this.searchRange.start));for(var s,o=t.lastIndex=0;(s=t.exec(r))&&(a++,o=s.index,i>=o&&n++,!(a>l))&&(s[0]||(t.lastIndex=o+=1,!(o>=r.length))););}this.searchCounter.textContent=n+" of "+(a>l?l+"+":a)},this.findNext=function(){this.find(!0,!1)},this.findPrev=function(){this.find(!0,!0)},this.findAll=function(){var e=this.editor.findAll(this.searchInput.value,{regExp:this.regExpOption.checked,caseSensitive:this.caseSensitiveOption.checked,wholeWord:this.wholeWordOption.checked}),t=!e&&this.searchInput.value;n.setCssClass(this.searchBox,"ace_nomatch",t),this.editor._emit("findSearchBox",{match:!t}),this.highlight(),this.hide()},this.replace=function(){this.editor.getReadOnly()||this.editor.replace(this.replaceInput.value)},this.replaceAndFindNext=function(){this.editor.getReadOnly()||(this.editor.replace(this.replaceInput.value),this.findNext())},this.replaceAll=function(){this.editor.getReadOnly()||this.editor.replaceAll(this.replaceInput.value)},this.hide=function(){this.active=!1,this.setSearchRange(null),this.editor.off("changeSession",this.setSession),this.element.style.display="none",this.editor.keyBinding.removeKeyboardHandler(this.$closeSearchBarKb),this.editor.focus()},this.show=function(e,t){this.active=!0,this.editor.on("changeSession",this.setSession),this.element.style.display="",this.replaceOption.checked=t,e&&(this.searchInput.value=e),this.searchInput.focus(),this.searchInput.select(),this.editor.keyBinding.addKeyboardHandler(this.$closeSearchBarKb),this.$syncOptions(!0)},this.isFocused=function(){var e=document.activeElement;return e==this.searchInput||e==this.replaceInput}}).call(u.prototype),t.SearchBox=u,t.Search=function(e,t){var a=e.searchBox||new u(e);a.show(e.session.getTextRange(),t)}}),function(){ace.require(["ace/ext/searchbox"],function(){})}(),ace.define("ace/snippets",["require","exports","module","ace/lib/oop","ace/lib/event_emitter","ace/lib/lang","ace/range","ace/anchor","ace/keyboard/hash_handler","ace/tokenizer","ace/lib/dom","ace/editor"],function(e,t,a){var n=e("./lib/oop"),r=e("./lib/event_emitter").EventEmitter,i=e("./lib/lang"),s=e("./range").Range,o=e("./anchor").Anchor,c=e("./keyboard/hash_handler").HashHandler,l=e("./tokenizer").Tokenizer,d=s.comparePoints,u=function(){this.snippetMap={},this.snippetNameMap={}};(function(){n.implement(this,r),this.getTokenizer=function(){function e(e,t,a){return e=e.substr(1),/^\d+$/.test(e)&&!a.inFormatString?[{tabstopId:parseInt(e,10)}]:[{text:e}]}function t(e){return"(?:[^\\\\"+e+"]|\\\\.)"}return u.$tokenizer=new l({start:[{regex:/:/,onMatch:function(e,t,a){return a.length&&a[0].expectIf?(a[0].expectIf=!1,a[0].elseBranch=a[0],[a[0]]):":"}},{regex:/\\./,onMatch:function(e,t,a){var n=e[1];return"}"==n&&a.length?e=n:-1!="`$\\".indexOf(n)?e=n:a.inFormatString&&("n"==n?e="\n":"t"==n?e="\n":-1!="ulULE".indexOf(n)&&(e={changeCase:n,local:n>"a"})),[e]}},{regex:/}/,onMatch:function(e,t,a){return[a.length?a.shift():e]}},{regex:/\$(?:\d+|\w+)/,onMatch:e},{regex:/\$\{[\dA-Z_a-z]+/,onMatch:function(t,a,n){var r=e(t.substr(1),a,n);return n.unshift(r[0]),r},next:"snippetVar"},{regex:/\n/,token:"newline",merge:!1}],snippetVar:[{regex:"\\|"+t("\\|")+"*\\|",onMatch:function(e,t,a){a[0].choices=e.slice(1,-1).split(",")},next:"start"},{regex:"/("+t("/")+"+)/(?:("+t("/")+"*)/)(\\w*):?",onMatch:function(e,t,a){var n=a[0];return n.fmtString=e,e=this.splitRegex.exec(e),n.guard=e[1],n.fmt=e[2],n.flag=e[3],""},next:"start"},{regex:"`"+t("`")+"*`",onMatch:function(e,t,a){return a[0].code=e.splice(1,-1),""},next:"start"},{regex:"\\?",onMatch:function(e,t,a){a[0]&&(a[0].expectIf=!0)},next:"start"},{regex:"([^:}\\\\]|\\\\.)*:?",token:"",next:"start"}],formatString:[{regex:"/("+t("/")+"+)/",token:"regex"},{regex:"",onMatch:function(e,t,a){a.inFormatString=!0},next:"start"}]}),u.prototype.getTokenizer=function(){return u.$tokenizer},u.$tokenizer},this.tokenizeTmSnippet=function(e,t){return this.getTokenizer().getLineTokens(e,t).tokens.map(function(e){return e.value||e})},this.$getDefaultValue=function(e,t){if(/^[A-Z]\d+$/.test(t)){var a=t.substr(1);return(this.variables[t[0]+"__"]||{})[a]}if(/^\d+$/.test(t))return(this.variables.__||{})[t];if(t=t.replace(/^TM_/,""),e){var n=e.session;switch(t){case"CURRENT_WORD":var r=n.getWordRange();case"SELECTION":case"SELECTED_TEXT":return n.getTextRange(r);case"CURRENT_LINE":return n.getLine(e.getCursorPosition().row);case"PREV_LINE":return n.getLine(e.getCursorPosition().row-1);case"LINE_INDEX":return e.getCursorPosition().column;case"LINE_NUMBER":return e.getCursorPosition().row+1;case"SOFT_TABS":return n.getUseSoftTabs()?"YES":"NO";case"TAB_SIZE":return n.getTabSize();case"FILENAME":case"FILEPATH":return"";case"FULLNAME":return"Ace"}}},this.variables={},this.getVariableValue=function(e,t){return this.variables.hasOwnProperty(t)?this.variables[t](e,t)||"":this.$getDefaultValue(e,t)||""},this.tmStrFormat=function(e,t,a){var n=t.flag||"",r=t.guard;r=new RegExp(r,n.replace(/[^gi]/,""));var i=this.tokenizeTmSnippet(t.fmt,"formatString"),s=this,o=e.replace(r,function(){s.variables.__=arguments;for(var e=s.resolveVariables(i,a),t="E",n=0;n1?(v=t[t.length-1].length,b+=t.length-1):v+=e.length,y+=e}else e.start?e.end={row:b,column:v}:e.start={row:b,column:v}});var w=e.getSelectionRange(),k=e.session.replace(w,y),x=new m(e),C=e.inVirtualSelectionMode&&e.selection.index;x.addTabstops(c,w.start,k,C)},this.insertSnippet=function(e,t){var a=this;return e.inVirtualSelectionMode?a.insertSnippetForSelection(e,t):(e.forEachSelection(function(){a.insertSnippetForSelection(e,t)},null,{keepOrder:!0}),void(e.tabstopManager&&e.tabstopManager.tabNext()))},this.$getScope=function(e){var t=e.session.$mode.$id||"";if(t=t.split("/").pop(),"html"===t||"php"===t){"php"!==t||e.session.$mode.inlinePhp||(t="html");var a=e.getCursorPosition(),n=e.session.getState(a.row);"object"===("undefined"==typeof n?"undefined":_typeof(n))&&(n=n[0]),n.substring&&("js-"==n.substring(0,3)?t="javascript":"css-"==n.substring(0,4)?t="css":"php-"==n.substring(0,4)&&(t="php"))}return t},this.getActiveScopes=function(e){var t=this.$getScope(e),a=[t],n=this.snippetMap;return n[t]&&n[t].includeScopes&&a.push.apply(a,n[t].includeScopes),a.push("_"),a},this.expandWithTab=function(e,t){var a=this,n=e.forEachSelection(function(){return a.expandSnippetForSelection(e,t)},null,{keepOrder:!0});return n&&e.tabstopManager&&e.tabstopManager.tabNext(),n},this.expandSnippetForSelection=function(e,t){var a,n=e.getCursorPosition(),r=e.session.getLine(n.row),i=r.substring(0,n.column),s=r.substr(n.column),o=this.snippetMap;return this.getActiveScopes(e).some(function(e){var t=o[e];return t&&(a=this.findMatchingSnippet(t,i,s)),!!a},this),a?t&&t.dryRun?!0:(e.session.doc.removeInLine(n.row,n.column-a.replaceBefore.length,n.column+a.replaceAfter.length),this.variables.M__=a.matchBefore,this.variables.T__=a.matchAfter,this.insertSnippetForSelection(e,a.content),this.variables.M__=this.variables.T__=null,!0):!1},this.findMatchingSnippet=function(e,t,a){for(var n=e.length;n--;){var r=e[n];if((!r.startRe||r.startRe.test(t))&&(!r.endRe||r.endRe.test(a))&&(r.startRe||r.endRe))return r.matchBefore=r.startRe?r.startRe.exec(t):[""],r.matchAfter=r.endRe?r.endRe.exec(a):[""],r.replaceBefore=r.triggerRe?r.triggerRe.exec(t)[0]:"",r.replaceAfter=r.endTriggerRe?r.endTriggerRe.exec(a)[0]:"",r}},this.snippetMap={},this.snippetNameMap={},this.register=function(e,t){function a(e){return e&&!/^\^?\(.*\)\$?$|^\\b$/.test(e)&&(e="(?:"+e+")"),e||""}function n(e,t,n){return e=a(e),t=a(t),n?(e=t+e,e&&"$"!=e[e.length-1]&&(e+="$")):(e+=t,e&&"^"!=e[0]&&(e="^"+e)),new RegExp(e)}function r(e){e.scope||(e.scope=t||"_"),t=e.scope,s[t]||(s[t]=[],o[t]={});var a=o[t];if(e.name){var r=a[e.name];r&&c.unregister(r),a[e.name]=e}s[t].push(e),e.tabTrigger&&!e.trigger&&(!e.guard&&/^\w/.test(e.tabTrigger)&&(e.guard="\\b"),e.trigger=i.escapeRegExp(e.tabTrigger)),(e.trigger||e.guard||e.endTrigger||e.endGuard)&&(e.startRe=n(e.trigger,e.guard,!0),e.triggerRe=new RegExp(e.trigger,"",!0),e.endRe=n(e.endTrigger,e.endGuard,!0),e.endTriggerRe=new RegExp(e.endTrigger,"",!0))}var s=this.snippetMap,o=this.snippetNameMap,c=this;e||(e=[]),e&&e.content?r(e):Array.isArray(e)&&e.forEach(r),this._signal("registerSnippets",{scope:t})},this.unregister=function(e,t){function a(e){var a=r[e.scope||t];if(a&&a[e.name]){ -delete a[e.name];var i=n[e.scope||t],s=i&&i.indexOf(e);s>=0&&i.splice(s,1)}}var n=this.snippetMap,r=this.snippetNameMap;e.content?a(e):Array.isArray(e)&&e.forEach(a)},this.parseSnippetFile=function(e){e=e.replace(/\r/g,"");for(var t,a=[],n={},r=/^#.*|^({[\s\S]*})\s*$|^(\S+) (.*)$|^((?:\n*\t.*)+)/gm;t=r.exec(e);){if(t[1])try{n=JSON.parse(t[1]),a.push(n)}catch(i){}if(t[4])n.content=t[4].replace(/^\t/gm,""),a.push(n),n={};else{var s=t[2],o=t[3];if("regex"==s){var c=/\/((?:[^\/\\]|\\.)*)|$/g;n.guard=c.exec(o)[1],n.trigger=c.exec(o)[1],n.endTrigger=c.exec(o)[1],n.endGuard=c.exec(o)[1]}else"snippet"==s?(n.tabTrigger=o.match(/^\S*/)[0],n.name||(n.name=o)):n[s]=o}}return a},this.getSnippetByName=function(e,t){var a,n=this.snippetNameMap;return this.getActiveScopes(t).some(function(t){var r=n[t];return r&&(a=r[e]),!!a},this),a}}).call(u.prototype);var m=function(e){return e.tabstopManager?e.tabstopManager:(e.tabstopManager=this,this.$onChange=this.onChange.bind(this),this.$onChangeSelection=i.delayedCall(this.onChangeSelection.bind(this)).schedule,this.$onChangeSession=this.onChangeSession.bind(this),this.$onAfterExec=this.onAfterExec.bind(this),void this.attach(e))};(function(){this.attach=function(e){this.index=0,this.ranges=[],this.tabstops=[],this.$openTabstops=null,this.selectedTabstop=null,this.editor=e,this.editor.on("change",this.$onChange),this.editor.on("changeSelection",this.$onChangeSelection),this.editor.on("changeSession",this.$onChangeSession),this.editor.commands.on("afterExec",this.$onAfterExec),this.editor.keyBinding.addKeyboardHandler(this.keyboardHandler)},this.detach=function(){this.tabstops.forEach(this.removeTabstopMarkers,this),this.ranges=null,this.tabstops=null,this.selectedTabstop=null,this.editor.removeListener("change",this.$onChange),this.editor.removeListener("changeSelection",this.$onChangeSelection),this.editor.removeListener("changeSession",this.$onChangeSession),this.editor.commands.removeListener("afterExec",this.$onAfterExec),this.editor.keyBinding.removeKeyboardHandler(this.keyboardHandler),this.editor.tabstopManager=null,this.editor=null},this.onChange=function(e){var t="r"==e.action[0],a=e.start,n=e.end,r=a.row,i=n.row,s=i-r,o=n.column-a.column;if(t&&(s=-s,o=-o),!this.$inChange&&t){var c=this.selectedTabstop,l=c&&!c.some(function(e){return d(e.start,a)<=0&&d(e.end,n)>=0});if(l)return this.detach()}for(var u=this.ranges,m=0;m0?(this.removeRange(h),m--):(h.start.row==r&&h.start.column>a.column&&(h.start.column+=o),h.end.row==r&&h.end.column>=a.column&&(h.end.column+=o),h.start.row>=r&&(h.start.row+=s),h.end.row>=r&&(h.end.row+=s),d(h.start,h.end)>0&&this.removeRange(h)))}u.length||this.detach()},this.updateLinkedFields=function(){var e=this.selectedTabstop;if(e&&e.hasLinkedRanges){this.$inChange=!0;for(var a=this.editor.session,n=a.getTextRange(e.firstNonLinked),r=e.length;r--;){var i=e[r];if(i.linked){var s=t.snippetManager.tmStrFormat(n,i.original);a.replace(i,s)}}this.$inChange=!1}},this.onAfterExec=function(e){e.command&&!e.command.readOnly&&this.updateLinkedFields()},this.onChangeSelection=function(){if(this.editor){for(var e=this.editor.selection.lead,t=this.editor.selection.anchor,a=this.editor.selection.isEmpty(),n=this.ranges.length;n--;)if(!this.ranges[n].linked){var r=this.ranges[n].contains(e.row,e.column),i=a||this.ranges[n].contains(t.row,t.column);if(r&&i)return}this.detach()}},this.onChangeSession=function(){this.detach()},this.tabNext=function(e){var t=this.tabstops.length,a=this.index+(e||1);a=Math.min(Math.max(a,1),t),a==t&&(a=0),this.selectTabstop(a),0===a&&this.detach()},this.selectTabstop=function(e){this.$openTabstops=null;var t=this.tabstops[this.index];if(t&&this.addTabstopMarkers(t),this.index=e,t=this.tabstops[this.index],t&&t.length){if(this.selectedTabstop=t,this.editor.inVirtualSelectionMode)this.editor.selection.setRange(t.firstNonLinked);else{var a=this.editor.multiSelect;a.toSingleRange(t.firstNonLinked.clone());for(var n=t.length;n--;)t.hasLinkedRanges&&t[n].linked||a.addRange(t[n].clone(),!0);a.ranges[0]&&a.addRange(a.ranges[0].clone())}this.editor.keyBinding.addKeyboardHandler(this.keyboardHandler)}},this.addTabstops=function(e,t,a){if(this.$openTabstops||(this.$openTabstops=[]),!e[0]){var n=s.fromPoints(a,a);g(n.start,t),g(n.end,t),e[0]=[n],e[0].index=0}var r=this.index,i=[r+1,0],o=this.ranges;e.forEach(function(e,a){for(var n=this.$openTabstops[a]||e,r=e.length;r--;){var c=e[r],l=s.fromPoints(c.start,c.end||c.start);p(l.start,t),p(l.end,t),l.original=c,l.tabstop=n,o.push(l),n!=e?n.unshift(l):n[r]=l,c.fmtString?(l.linked=!0,n.hasLinkedRanges=!0):n.firstNonLinked||(n.firstNonLinked=l)}n.firstNonLinked||(n.hasLinkedRanges=!1),n===e&&(i.push(n),this.$openTabstops[a]=n),this.addTabstopMarkers(n)},this),i.length>2&&(this.tabstops.length&&i.push(i.splice(2,1)[0]),this.tabstops.splice.apply(this.tabstops,i))},this.addTabstopMarkers=function(e){var t=this.editor.session;e.forEach(function(e){e.markerId||(e.markerId=t.addMarker(e,"ace_snippet-marker","text"))})},this.removeTabstopMarkers=function(e){var t=this.editor.session;e.forEach(function(e){t.removeMarker(e.markerId),e.markerId=null})},this.removeRange=function(e){var t=e.tabstop.indexOf(e);e.tabstop.splice(t,1),t=this.ranges.indexOf(e),this.ranges.splice(t,1),this.editor.session.removeMarker(e.markerId),e.tabstop.length||(t=this.tabstops.indexOf(e.tabstop),-1!=t&&this.tabstops.splice(t,1),this.tabstops.length||this.detach())},this.keyboardHandler=new c,this.keyboardHandler.bindKeys({Tab:function(e){t.snippetManager&&t.snippetManager.expandWithTab(e)||e.tabstopManager.tabNext(1)},"Shift-Tab":function(e){e.tabstopManager.tabNext(-1)},Esc:function(e){e.tabstopManager.detach()},Return:function(e){return!1}})}).call(m.prototype);var h={};h.onChange=o.prototype.onChange,h.setPosition=function(e,t){this.pos.row=e,this.pos.column=t},h.update=function(e,t,a){this.$insertRight=a,this.pos=e,this.onChange(t)};var p=function(e,t){0==e.row&&(e.column+=t.column),e.row+=t.row},g=function(e,t){e.row==t.row&&(e.column-=t.column),e.row-=t.row};e("./lib/dom").importCssString(".ace_snippet-marker { -moz-box-sizing: border-box; box-sizing: border-box; background: rgba(194, 193, 208, 0.09); border: 1px dotted rgba(211, 208, 235, 0.62); position: absolute;}"),t.snippetManager=new u;var f=e("./editor").Editor;(function(){this.insertSnippet=function(e,a){return t.snippetManager.insertSnippet(this,e,a)},this.expandSnippet=function(e){return t.snippetManager.expandWithTab(this,e)}}).call(f.prototype)}),ace.define("ace/autocomplete/popup",["require","exports","module","ace/virtual_renderer","ace/editor","ace/range","ace/lib/event","ace/lib/lang","ace/lib/dom"],function(e,t,a){var n=e("../virtual_renderer").VirtualRenderer,r=e("../editor").Editor,i=e("../range").Range,s=e("../lib/event"),o=e("../lib/lang"),c=e("../lib/dom"),l=function(e){var t=new n(e);t.$maxLines=4;var a=new r(t);return a.setHighlightActiveLine(!1),a.setShowPrintMargin(!1),a.renderer.setShowGutter(!1),a.renderer.setHighlightGutterLine(!1),a.$mouseHandler.$focusWaitTimout=0,a.$highlightTagPending=!0,a},d=function(e){var t=c.createElement("div"),a=new l(t);e&&e.appendChild(t),t.style.display="none",a.renderer.content.style.cursor="default",a.renderer.setStyle("ace_autocomplete"),a.setOption("displayIndentGuides",!1),a.setOption("dragDelay",150);var n=function(){};a.focus=n,a.$isFocused=!0,a.renderer.$cursorLayer.restartTimer=n,a.renderer.$cursorLayer.element.style.opacity=0,a.renderer.$maxLines=8,a.renderer.$keepTextAreaAtCursor=!1,a.setHighlightActiveLine(!1),a.session.highlight(""),a.session.$searchHighlight.clazz="ace_highlight-marker",a.on("mousedown",function(e){var t=e.getDocumentPosition();a.selection.moveToPosition(t),u.start.row=u.end.row=t.row,e.stop()});var r,d=new i(-1,0,-1,1/0),u=new i(-1,0,-1,1/0);u.id=a.session.addMarker(u,"ace_active-line","fullLine"),a.setSelectOnHover=function(e){e?d.id&&(a.session.removeMarker(d.id),d.id=null):d.id=a.session.addMarker(d,"ace_line-hover","fullLine")},a.setSelectOnHover(!1),a.on("mousemove",function(e){if(!r)return void(r=e);if(r.x!=e.x||r.y!=e.y){r=e,r.scrollTop=a.renderer.scrollTop;var t=r.getDocumentPosition().row;d.start.row!=t&&(d.id||a.setRow(t),h(t))}}),a.renderer.on("beforeRender",function(){if(r&&-1!=d.start.row){r.$pos=null;var e=r.getDocumentPosition().row;d.id||a.setRow(e),h(e,!0)}}),a.renderer.on("afterRender",function(){var e=a.getRow(),t=a.renderer.$textLayer,n=t.element.childNodes[e-t.config.firstRow];n!=t.selectedNode&&(t.selectedNode&&c.removeCssClass(t.selectedNode,"ace_selected"),t.selectedNode=n,n&&c.addCssClass(n,"ace_selected"))});var m=function(){h(-1)},h=function(e,t){e!==d.start.row&&(d.start.row=d.end.row=e,t||a.session._emit("changeBackMarker"),a._emit("changeHoverMarker"))};a.getHoveredRow=function(){return d.start.row},s.addListener(a.container,"mouseout",m),a.on("hide",m),a.on("changeSelection",m),a.session.doc.getLength=function(){return a.data.length},a.session.doc.getLine=function(e){var t=a.data[e];return"string"==typeof t?t:t&&t.value||""};var p=a.session.bgTokenizer;return p.$tokenizeRow=function(e){var t=a.data[e],n=[];if(!t)return n;"string"==typeof t&&(t={value:t}),t.caption||(t.caption=t.value||t.name);var r,i,s=-1;t.iconClass&&n.push({type:"icon ace_icon-"+t.iconClass,value:" "});for(var o=0;oc-2&&(l=l.substr(0,c-t.caption.length-3)+"…"),n.push({type:"rightAlignedText",value:l})}return n},p.$updateOnChange=n,p.start=n,a.session.$computeWidth=function(){return this.screenWidth=0},a.$blockScrolling=1/0,a.isOpen=!1,a.isTopdown=!1,a.data=[],a.setData=function(e){a.setValue(o.stringRepeat("\n",e.length),-1),a.data=e||[],a.setRow(0)},a.getData=function(e){return a.data[e]},a.getRow=function(){return u.start.row},a.setRow=function(e){e=Math.max(0,Math.min(this.data.length,e)),u.start.row!=e&&(a.selection.clearSelection(),u.start.row=u.end.row=e||0,a.session._emit("changeBackMarker"),a.moveCursorTo(e||0,0),a.isOpen&&a._signal("select"))},a.on("changeSelection",function(){a.isOpen&&a.setRow(a.selection.lead.row),a.renderer.scrollCursorIntoView()}),a.hide=function(){this.container.style.display="none",this._signal("hide"),a.isOpen=!1},a.show=function(e,t,n){var i=this.container,s=window.innerHeight,o=window.innerWidth,c=this.renderer,l=c.$maxLines*t*1.4,d=e.top+this.$borderSize,u=d>s/2&&!n;u&&d+t+l>s?(c.$maxPixelHeight=d-2*this.$borderSize,i.style.top="",i.style.bottom=s-d+"px",a.isTopdown=!1):(d+=t,c.$maxPixelHeight=s-d-.2*t,i.style.top=d+"px",i.style.bottom="",a.isTopdown=!0),i.style.display="",this.renderer.$textLayer.checkForSizeChanges();var m=e.left;m+i.offsetWidth>o&&(m=o-i.offsetWidth),i.style.left=m+"px",this._signal("show"),r=null,a.isOpen=!0},a.getTextLeftOffset=function(){return this.$borderSize+this.renderer.$padding+this.$imageSize},a.$imageSize=0,a.$borderSize=1,a};c.importCssString(".ace_editor.ace_autocomplete .ace_marker-layer .ace_active-line { background-color: #CAD6FA; z-index: 1;}.ace_editor.ace_autocomplete .ace_line-hover { border: 1px solid #abbffe; margin-top: -1px; background: rgba(233,233,253,0.4);}.ace_editor.ace_autocomplete .ace_line-hover { position: absolute; z-index: 2;}.ace_editor.ace_autocomplete .ace_scroller { background: none; border: none; box-shadow: none;}.ace_rightAlignedText { color: gray; display: inline-block; position: absolute; right: 4px; text-align: right; z-index: -1;}.ace_editor.ace_autocomplete .ace_completion-highlight{ color: #000; text-shadow: 0 0 0.01em;}.ace_editor.ace_autocomplete { width: 280px; z-index: 200000; background: #fbfbfb; color: #444; border: 1px lightgray solid; position: fixed; box-shadow: 2px 3px 5px rgba(0,0,0,.2); line-height: 1.4;}"),t.AcePopup=d}),ace.define("ace/autocomplete/util",["require","exports","module"],function(e,t,a){t.parForEach=function(e,t,a){var n=0,r=e.length;0===r&&a();for(var i=0;r>i;i++)t(e[i],function(e,t){n++,n===r&&a(e,t)})};var n=/[a-zA-Z_0-9\$\-\u00A2-\uFFFF]/;t.retrievePrecedingIdentifier=function(e,t,a){a=a||n;for(var r=[],i=t-1;i>=0&&a.test(e[i]);i--)r.push(e[i]);return r.reverse().join("")},t.retrieveFollowingIdentifier=function(e,t,a){a=a||n;for(var r=[],i=t;i=t?a:t-1;break;case"down":t=t>=a?-1:t+1;break;case"start":t=0;break;case"end":t=a}this.popup.setRow(t)},this.insertMatch=function(e,t){if(e||(e=this.popup.getData(this.popup.getRow())),!e)return!1;if(e.completer&&e.completer.insertMatch)e.completer.insertMatch(this.editor,e);else{if(this.completions.filterText)for(var a,n=this.editor.selection.getAllRanges(),r=0;a=n[r];r++)a.start.column-=this.completions.filterText.length,this.editor.session.remove(a);e.snippet?c.insertSnippet(this.editor,e.snippet):this.editor.execCommand("insertstring",e.value||e)}this.detach()},this.commands={Up:function(e){e.completer.goTo("up")},Down:function(e){e.completer.goTo("down")},"Ctrl-Up|Ctrl-Home":function(e){e.completer.goTo("start")},"Ctrl-Down|Ctrl-End":function(e){e.completer.goTo("end")},Esc:function(e){e.completer.detach()},Return:function(e){return e.completer.insertMatch()},"Shift-Return":function(e){e.completer.insertMatch(null,{deleteSuffix:!0})},Tab:function(e){var t=e.completer.insertMatch();return t||e.tabstopManager?t:void e.completer.goTo("down")},PageUp:function(e){e.completer.popup.gotoPageUp()},PageDown:function(e){e.completer.popup.gotoPageDown()}},this.gatherCompletions=function(e,t){var a=e.getSession(),n=e.getCursorPosition(),r=(a.getLine(n.row),i.getCompletionPrefix(e));this.base=a.doc.createAnchor(n.row,n.column-r.length),this.base.$insertRight=!0;var s=[],o=e.completers.length;return e.completers.forEach(function(i,c){i.getCompletions(e,a,n,r,function(n,i){!n&&i&&(s=s.concat(i));var c=e.getCursorPosition();a.getLine(c.row);t(null,{prefix:r,matches:s,finished:0===--o})})}),!0},this.showPopup=function(e){this.editor&&this.detach(),this.activated=!0,this.editor=e,e.completer!=this&&(e.completer&&e.completer.detach(),e.completer=this),e.on("changeSelection",this.changeListener),e.on("blur",this.blurListener),e.on("mousedown",this.mousedownListener),e.on("mousewheel",this.mousewheelListener),this.updateCompletions()},this.updateCompletions=function(e){if(e&&this.base&&this.completions){var t=this.editor.getCursorPosition(),a=this.editor.session.getTextRange({start:this.base,end:t});if(a==this.completions.filterText)return;return this.completions.setFilter(a),this.completions.filtered.length&&(1!=this.completions.filtered.length||this.completions.filtered[0].value!=a||this.completions.filtered[0].snippet)?void this.openPopup(this.editor,a,e):this.detach()}var n=this.gatherCompletionsId;this.gatherCompletions(this.editor,function(t,a){var r=function(){return a.finished?this.detach():void 0}.bind(this),i=a.prefix,s=a&&a.matches;if(!s||!s.length)return r();if(0===i.indexOf(a.prefix)&&n==this.gatherCompletionsId){this.completions=new d(s),this.exactMatch&&(this.completions.exactMatch=!0),this.completions.setFilter(i);var o=this.completions.filtered;return o.length&&(1!=o.length||o[0].value!=i||o[0].snippet)?this.autoInsert&&1==o.length&&a.finished?this.insertMatch(o[0]):void this.openPopup(this.editor,i,e):r()}}.bind(this))},this.cancelContextMenu=function(){this.editor.$mouseHandler.cancelContextMenu()},this.updateDocTooltip=function(){var e=this.popup,t=e.data,a=t&&(t[e.getHoveredRow()]||t[e.getRow()]),n=null;return a&&this.editor&&this.popup.isOpen?(this.editor.completers.some(function(e){return e.getDocTooltip&&(n=e.getDocTooltip(a)),n}),n||(n=a),"string"==typeof n&&(n={docText:n}),n&&(n.docHTML||n.docText)?void this.showDocTooltip(n):this.hideDocTooltip()):this.hideDocTooltip()},this.showDocTooltip=function(e){this.tooltipNode||(this.tooltipNode=o.createElement("div"),this.tooltipNode.className="ace_tooltip ace_doc-tooltip",this.tooltipNode.style.margin=0,this.tooltipNode.style.pointerEvents="auto",this.tooltipNode.tabIndex=-1,this.tooltipNode.onblur=this.blurListener.bind(this));var t=this.tooltipNode;e.docHTML?t.innerHTML=e.docHTML:e.docText&&(t.textContent=e.docText),t.parentNode||document.body.appendChild(t);var a=this.popup,n=a.container.getBoundingClientRect();t.style.top=a.container.style.top,t.style.bottom=a.container.style.bottom,window.innerWidth-n.right<320?(t.style.right=window.innerWidth-n.left+"px",t.style.left=""):(t.style.left=n.right+1+"px",t.style.right=""),t.style.display="block"},this.hideDocTooltip=function(){if(this.tooltipTimer.cancel(),this.tooltipNode){var e=this.tooltipNode;this.editor.isFocused()||document.activeElement!=e||this.editor.focus(),this.tooltipNode=null,e.parentNode&&e.parentNode.removeChild(e)}}}).call(l.prototype),l.startCommand={name:"startAutocomplete",exec:function(e){e.completer||(e.completer=new l),e.completer.autoInsert=!1,e.completer.autoSelect=!0,e.completer.showPopup(e),e.completer.cancelContextMenu()},bindKey:"Ctrl-Space|Ctrl-Shift-Space|Alt-Space"};var d=function(e,t){this.all=e,this.filtered=e,this.filterText=t||"",this.exactMatch=!1};(function(){this.setFilter=function(e){if(e.length>this.filterText&&0===e.lastIndexOf(this.filterText,0))var t=this.filtered;else var t=this.all;this.filterText=e,t=this.filterCompletions(t,this.filterText),t=t.sort(function(e,t){return t.exactMatch-e.exactMatch||t.score-e.score});var a=null;t=t.filter(function(e){var t=e.snippet||e.caption||e.value;return t===a?!1:(a=t,!0)}),this.filtered=t},this.filterCompletions=function(e,t){var a=[],n=t.toUpperCase(),r=t.toLowerCase();e:for(var i,s=0;i=e[s];s++){var o=i.value||i.caption||i.snippet;if(o){var c,l,d=-1,u=0,m=0;if(this.exactMatch){if(t!==o.substr(0,t.length))continue e}else for(var h=0;h=0&&(0>g||g>p)?p:g,0>c)continue e;l=c-d-1,l>0&&(-1===d&&(m+=10),m+=l),u|=1<",s.escapeHTML(e.caption),"","
",s.escapeHTML(e.snippet)].join(""))}},u=[d,c,l];t.setCompleters=function(e){u.length=0,e&&u.push.apply(u,e)},t.addCompleter=function(e){u.push(e)},t.textCompleter=c,t.keyWordCompleter=l,t.snippetCompleter=d;var m,h={name:"expandSnippet",exec:function(e){return n.expandWithTab(e)},bindKey:"Tab"},p=function(e,t){g(t.session.$mode)},g=function k(e){var t=e.$id;n.files||(n.files={}),f(t),e.modes&&e.modes.forEach(k)},f=function x(e){if(e&&!n.files[e]){var t=e.replace("mode","snippets");n.files[e]={},i.loadModule(t,function(t){t&&(n.files[e]=t,!t.snippets&&t.snippetText&&(t.snippets=n.parseSnippetFile(t.snippetText)),n.register(t.snippets||[],t.scope),t.includeScopes&&(n.snippetMap[t.scope].includeScopes=t.includeScopes,t.includeScopes.forEach(function(e){x("ace/mode/"+e)})))})}},b=function(e){var t=e.editor,a=t.completer&&t.completer.activated;if("backspace"===e.command.name)a&&!o.getCompletionPrefix(t)&&t.completer.detach();else if("insertstring"===e.command.name){var n=o.getCompletionPrefix(t);n&&n.length>=t.$liveAutocompletionThreshold&&!a&&(t.completer||(t.completer=new r),t.completer.autoInsert=!1,t.completer.showPopup(t))}},v=s.delayedCall(function(){b(m)},0),y=function(e){m=e,v.delay(e.editor.$liveAutocompletionDelay)},w=e("../editor").Editor;e("../config").defineOptions(w.prototype,"editor",{enableBasicAutocompletion:{set:function(e){e?(this.completers||(this.completers=Array.isArray(e)?e:u),this.commands.addCommand(r.startCommand)):this.commands.removeCommand(r.startCommand)},value:!1},enableLiveAutocompletion:{set:function(e){e?(this.completers||(this.completers=Array.isArray(e)?e:u),this.commands.on("afterExec",y)):this.commands.removeListener("afterExec",y)},value:!1},liveAutocompletionThreshold:{value:0},liveAutocompletionDelay:{value:500},enableSnippets:{set:function(e){e?(this.commands.addCommand(h),this.on("changeMode",p),p(null,this)):(this.commands.removeCommand(h),this.off("changeMode",p))},value:!1}})}),function(){ace.require(["ace/ext/language_tools"],function(){})}(),ace.define("ace/ext/beautify/php_rules",["require","exports","module","ace/token_iterator"],function(e,t,a){e("ace/token_iterator").TokenIterator;t.newLines=[{type:"support.php_tag",value:""},{type:"paren.lparen",value:"{",indent:!0},{type:"paren.rparen",breakBefore:!0,value:"}",indent:!1},{type:"paren.rparen",breakBefore:!0,value:"})",indent:!1,dontBreak:!0},{type:"comment"},{type:"text",value:";"},{type:"text",value:":",context:"php"},{type:"keyword",value:"case",indent:!0,dontBreak:!0},{type:"keyword",value:"default",indent:!0,dontBreak:!0},{type:"keyword",value:"break",indent:!1,dontBreak:!0},{type:"punctuation.doctype.end",value:">"},{type:"meta.tag.punctuation.end",value:">"},{type:"meta.tag.punctuation.begin",value:"<",blockTag:!0,indent:!0,dontBreak:!0},{type:"meta.tag.punctuation.begin",value:""!=o.value?n="php":"support.php_tag"==o.type&&"?>"==o.value?n="html":"meta.tag.name.style"==o.type&&"css"!=n?n="css":"meta.tag.name.style"==o.type&&"css"==n?n="html":"meta.tag.name.script"==o.type&&"js"!=n?n="js":"meta.tag.name.script"==o.type&&"js"==n&&(n="html"),g=e.stepForward(),g&&0==g.type.indexOf("meta.tag.name")&&(s=g.value),"support.php_tag"==p.type&&"v;v++)u+=" ";break}if(h===!1)for(v in c)if(!(p.type!=c[v].type||c[v].value&&p.value!=c[v].value||c[v].blockTag&&-1!==d.indexOf(r)||c[v].context&&c[v].context!==n)){if(c[v].indent===!0&&m++,!c[v].dontBreak&&!f)for(u+="\n",v=0;m>v;v++)u+=" ";break}if(u+=b,"support.php_tag"==p.type&&"?>"==p.value&&(h=!1),i=r,p=o,o=g,null===o)break}else o=g;else o=e.stepForward();return u}}),ace.define("ace/ext/beautify",["require","exports","module","ace/token_iterator","ace/ext/beautify/php_rules"],function(e,t,a){var n=e("ace/token_iterator").TokenIterator,r=e("./beautify/php_rules").transform;t.beautify=function(e){var t=new n(e,0,0),a=(t.getCurrentToken(),e.$modeId.split("/").pop()),i=r(t,a);e.doc.setValue(i)},t.commands=[{name:"beautify",exec:function(e){t.beautify(e.session)},bindKey:"Ctrl-Shift-B"}]}),function(){ace.require(["ace/ext/beautify"],function(){})}(),ace.define("ace/mode/clickhouse_highlight_rules",["require","exports","$rootScope","module","ace/lib/oop","ace/snippets","ace/ext/language_tools","ace/mode/text_highlight_rules"],function(e,t,a){var n=e("../lib/oop"),r=e("./text_highlight_rules").TextHighlightRules,i=function(){var e=this,t="SELECT|CASE|THEN|DISTINCT|INSERT|UPDATE|DELETE|WHERE|AND|OR|OFFSET|HAVING|AS|FROM|WHEN|ELSE|END|TYPE|LEFT|RIGHT|JOIN|ON|OUTER|DESC|ASC|UNION|CREATE|TABLE|PRIMARY|KEY|FOREIGN|NOT|REFERENCES|DEFAULT|INNER|CROSS|NATURAL|DATABASE|DROP|GRANT|ANY|BETWEEN|ATTACH|DETACH|CAST|WITH|BIT_AND|BIT_OR|BIT_XOR|DESCRIBE|OPTIMIZE|PREWHERE|TOTALS|DATABASES|PROCESSLIST|SHOW|IF",a="IF\\W+NOT\\W+EXISTS|IF\\W+EXISTS|FORMAT\\W+Vertical|FORMAT\\W+JSONCompact|FORMAT\\W+JSONEachRow|FORMAT\\W+TSKV|FORMAT\\W+TabSeparatedWithNames|FORMAT\\W+TabSeparatedWithNamesAndTypes|FORMAT\\W+TabSeparatedRaw|FORMAT\\W+BlockTabSeparated|FORMAT\\W+CSVWithNames|FORMAT\\W+CSV|FORMAT\\W+JSON|FORMAT\\W+TabSeparated",n="true|false|NULL",r="sum|sumIf|avg|avgIf",i="date|integer|uint8|uint16|uint32|uint64|int8|int16|int32|int64|float32|float64|datetime|enum8|enum16|fixedstring|array|tuple|stringMergeTree|SummingMergeTree|ReplacingMergeTree|ReplicatedMergeTree|Buffer|ReplicatedCollapsingMergeTree|CollapsingMergeTree|AggregatingMergeTree|Merge|Memory|GraphiteMergeTree|ReplicatedAggregatingMergeTree|ReplicatedSummingMergeTree",s=["IF NOT EXISTS","IF EXISTS","GROUP BY","ORDER BY","UNION ALL","FORMAT JSON","FORMAT JSONCompact","FORMAT JSONEachRow","FORMAT TSV","FORMAT TabSeparated","FORMAT TabSeparatedWithNames","FORMAT TabSeparatedWithNamesAndTypes","FORMAT TabSeparatedRaw","FORMAT BlockTabSeparated","FORMAT TSKV","FORMAT CSV","FORMAT CSVWithNames","SYSTEM RELOAD DICTIONARY","SYSTEM RELOAD DICTIONARIES","SYSTEM DROP DNS CACHE","SYSTEM SHUTDOWN","SYSTEM KILL","CLEAR COLUMN IN PARTITION"],o=["DRAW_GMAPS","DRAW_PLOTLY","DRAW_CALENDAR","DRAW_TEXT","DRAW_HEATMAP","DRAW_CHART","DRAW_BAR","DRAW_GRIDCHART","DRAW_RIVER","DRAW_RAW","DRAW_SANKEYS","DRAW_TREEMAP","DRAW_C3","DRAW_MAP"],c="";if(window.aceJSRules&&window.aceJSRules.builtinFunctions){if(window.aceJSRules.builtinFunctions){var l=[];window.aceJSRules.builtinFunctions.forEach(function(e){l.push(e.name)}),r=l.join("|")}_.isArray(window.aceJSRules.tables)&&(c=window.aceJSRules.tables.join("|"))}var d="";d=window.global_delimiter?new RegExp(window.global_delimiter):new RegExp(";;");var u=[],m=t.toLowerCase();window.aceJSRules&&_.isArray(window.aceJSRules.fieldsList)&&window.aceJSRules.fieldsList.forEach(function(e){var t=e.name.toLowerCase()+"|";m.indexOf(t)>-1||u.push(e.name)});var h=this.createKeywordMapper({"support.function":r,keyword:t,"constant.language":n,"storage.type":i, -"markup.bold":c,"markup.heading":u.join("|")},"identifier",!0);this.$rules={start:[{token:"comment",regex:"--.*$",caseInsensitive:!0},{token:"comment.block",start:"```",end:"```"},{token:"keyword",regex:"GROUP\\W+BY|ON\\W+CLUSTER|ORDER\\W+BY|LIMIT\\W+\\d+\\W*,\\W*\\d+|LIMIT\\W+\\d+\\W+BY\\W+|LIMIT\\W+\\d+"},{token:"variable.language",regex:/\$[\w]+(?:\[[\w\]+]|[=\-]>\w+)?/},{token:"variable.language",regex:/@[\w]+(?:\[[\w\]+]|[=\-]>\w+)?/},{token:"variable.language",regex:/\:[\w]+(?:\[[\w\]+]|[=\-]>\w+)?/},{token:"variable.language",regex:/\{[\w]+(?:\[[\w\]+]|[=\-]>\w+)\}?/},{token:"comment",start:"/\\*",end:"\\*/"},{token:"constant",regex:'".*?"'},{token:"storage",regex:a},{token:"invalid.illegal",regex:o.join("|")},{token:"string",regex:"'.*?'"},{token:"constant.numeric",regex:"[+-]?\\d+(?:(?:\\.\\d*)?(?:[eE][+-]?\\d+)?)?\\b"},{token:h,regex:"[a-zA-Z_$][a-zA-Z0-9_$]*\\b"},{token:"constant.character.escape",regex:d},{token:"punctuation",regex:/[?:,;.]/},{token:"keyword.operator",regex:"\\+|\\-|\\/|\\/\\/|%|<@>|@>|<@|&|\\^|~|<|>|<=|=>|==|!=|<>|="},{token:"paren.lparen",regex:"[\\(\\{]"},{token:"paren.rparen",regex:"[\\)\\}]"},{token:"text",regex:"\\s+"}]},this.normalizeRules(),this.completions=[],this.getCompletions=function(){return e.completions},this.addCompletions=function(e,t,a,n,r,i,s){this.completions.push({name:e,value:t,caption:a,score:n,meta:r,iconClass:i,docHTML:s})},this.addCompletionsDictionaries=function(e){this.addCompletions(e.dic,e.dic,e.title,0,"dic","dict",this.makeCompletionsDocFunctions(e.title,e.dic))},this.addCompletionsFunctions=function(e){this.addCompletions(e.name,e.name+"( )",e.name+"( )",e.score,"function","function",this.makeCompletionsDocFunctions(e.name,e.origin,e.comb))},this.addCompletionsTableFiled=function(e){var t=e.table+"."+e.name,a=e.name,n="type:"+e.type+"

default_type:"+e.default_type+"
"+e.default_expression;this.addCompletions(t,a,a,100,e.type,"field",this.makeCompletionsdocHTML(t,n))},this.addArrayCompletions=function(e,t,a){var n=this;e.forEach(function(e){n.addCompletions(e,e,e,0,t,a,!1)})},this.setKeywords=function(e){console.log("setKeywords > ",e),this.keywordRule.onMatch=this.createKeywordMapper(e,"identifier")},this.makeCompletionsDocFunctions=function(e,t,a){if(!window.global_chFunctionsHelp)return!1;if(!window.global_chFunctionsHelp.functions)return!1;var n="",r=e;if("undefined"!=typeof window.global_chFunctionsHelp.functions[e]?r=e:"undefined"!=typeof window.global_chFunctionsHelp.functions[t]&&(r=t),"undefined"!=typeof window.global_chFunctionsHelp.functions[r]){var i="en",s=window.global_chFunctionsHelp.functions[r],o="",c="";s.desc&&(o=s.bracket,c=s.desc[i],c||(c=s.desc.en?s.desc.en:s.desc.ru)),c&&(c=c.replace(/\.\s*/gm,".
")),n=''+e+o+'
'+c+" "}else n=''+e+"( )
"+t;return n+'
'},this.makeCompletionsdocHTML=function(e,t){return'
'+e+"
"+t+"
"},this.addArrayCompletions(t.split("|"),"keyword","keyword"),this.addArrayCompletions(s,"keyword","keyword"),this.addArrayCompletions(o,"draw","draw"),this.addArrayCompletions(i.split("|"),"type","type")};n.inherits(i,r),t.ClickhouseHighlightRules=i}),ace.define("ace/mode/matching_brace_outdent",["require","exports","module","ace/range"],function(e,t,a){var n=e("ace/range").Range,r=function(){};(function(){this.checkOutdent=function(e,t){return/^\s+$/.test(e)?/^\s*\}/.test(t):!1},this.autoOutdent=function(e,t){var a=e.getLine(t),r=a.match(/^(\s*\})/);if(!r)return 0;var i=r[1].length,s=e.findMatchingBracket({row:t,column:i});if(!s||s.row==t)return 0;var o=this.$getIndent(e.getLine(s.row));e.replace(new n(t,0,t,i-1),o)},this.$getIndent=function(e){return e.match(/^\s*/)[0]}}).call(r.prototype),t.MatchingBraceOutdent=r}),ace.define("ace/mode/clickhouse_FoldMode",["$rootScope","require","exports","module","ace/lib/oop","ace/range","ace/mode/sqlserver","ace/mode/folding/cstyle"],function(e,t,a){var n=e("../lib/oop"),r=e("ace/mode/folding/cstyle").FoldMode,i=(e("ace/range").Range,e("ace/token_iterator").TokenIterator),s=t.FoldMode=function(){};n.inherits(s,r),function(){this.foldingRules="cStyle",this.foldingStartMarker=/\(|\{/,this.getFoldWidgetRange=function(e,t,a,n){for(var r=new i(e,a,0),s=r.getCurrentToken(),o=!1;s;){var c=s,l=r.getCurrentTokenPosition();if(s=r.stepForward(),"paren.lparen"!=c.type||"("!=c.value&&"{"!=c.value||(o=e.getBracketRange(l)),o)break}return o}}.call(s.prototype)}),window.global_chFunctionsHelp={functions:{corr:{bracket:"(x, y)",desc:{en:'Calculates the Pearson correlation coefficient: Σ((x - x̅)(y - y̅)) / sqrt(Σ((x - x̅)2) * Σ((y - y̅)2)).'}},stddevPop:{bracket:"(x)",desc:{en:"The result is equal to the square root of 'varPop(x)'."}},varPop:{bracket:"(x, y)",desc:{en:"Calculates the value of %%Σ((x - x̅)(y - y̅)) / n%%."}},argMin:{bracket:"(arg, val)",desc:{en:"Calculates the 'arg' value for a minimal 'val' value. If there are several different values of 'arg' for minimal values of 'val', the first of these values encountered is output."}},quantileExactWeighted:{bracket:"(level)(x, weight)",desc:{en:"Вычисляет квантиль уровня level точно."}},min:{bracket:"(v)",desc:{en:"Minimal execution speed in rows per second. Checked on every data block when 'timeout_before_checking_execution_speed' expires. If the execution speed is lower, an exception is thrown."}},varSamp:{bracket:"(x, y)",desc:{en:"Calculates the value of %%Σ((x - x̅)(y - y̅)) / (n - 1)%%.

Returns Float64. If n <= 1, it returns +∞."}},anyLast:{bracket:"(x)",desc:{en:"Selects the last value encountered.
The result is just as indeterminate as for the 'any' function."}},argMax:{bracket:"(arg, val)",desc:{en:"Calculates the 'arg' value for a maximum 'val' value. If there are several different values of 'arg' for maximum values of 'val', the first of these values encountered is output."}},count:{bracket:"()",desc:{en:"Counts the number of rows. "}},any:{bracket:"(x)",desc:{en:"Selects the last value encountered.
The result is just as indeterminate as for the 'any' function."}},avg:{bracket:"(x)",desc:{en:"Calculates the average.
Only works for numbers.
The result is always Float64."}},sequenceMatch:{bracket:"(pattern)(time, cond1, cond2, ...)",desc:{en:"Pattern matching for event chains.

'pattern' is a string containing a pattern to match."}},stddevSamp:{bracket:"(x)",desc:{en:"The result is equal to the square root of 'varSamp(x)'."}},medianDeterministic:{bracket:"(x, determinator)",desc:{en:"This function works similarly to the 'median' function - it approximates the median."}},quantilesTimingWeighted:{bracket:"(level1, level2, ...)(x, weight)",desc:{en:"Calculates the quantiles of all specified levels using the same algorithm as the 'medianTimingWeighted' function."}},uniq:{bracket:"(N)(x)",desc:{en:"Calculates the number of different argument values, if it is less than or equal to N.
If the number of different argument values is greater than N, it returns N + 1."}},covarSamp:{bracket:"(x, y)",desc:{en:"Calculates the value of %%Σ((x - x̅)(y - y̅)) / (n - 1)%%.

Returns Float64. If n <= 1, it returns +∞."}},max:{bracket:"(v)",desc:{en:"Maximum number of bytes (uncompressed data) that can be passed to a remote server or saved in a temporary table when using GLOBAL IN."}},quantileTDigest:{bracket:"(level)(x)",desc:{en:"t-digest"}},quantilesTiming:{bracket:"(level1, level2, ...)(x, weight)",desc:{en:"Calculates the quantiles of all specified levels using the same algorithm as the 'medianTimingWeighted' function."}},quantiles:{bracket:"(level1, level2, ...)(x, determinator)",desc:{en:"Calculates the quantiles of all specified levels using the same algorithm as the 'medianDeterministic' function."}},quantile:{bracket:"(level1, level2, ...)(x, determinator)",desc:{en:"Calculates the quantiles of all specified levels using the same algorithm as the 'medianDeterministic' function."}},groupArray:{bracket:"(x)",desc:{en:"Creates an array of argument values.
Values can be added to the array in any (indeterminate) order.

In some cases, you can rely on the order of execution. This applies to cases when SELECT comes from a subquery that uses ORDER BY."}},sum:{bracket:"(x)",desc:{en:"Calculates the sum.
Only works for numbers."}},median:{bracket:"(x, weight)",desc:{en:"Differs from the 'medianTiming' function in that it has a second argument - "weights". Weight is a non-negative integer.
The result is calculated as if the 'x' value were passed 'weight' number of times to the 'medianTiming' function."}},quantileTiming:{bracket:"(level)(x, weight)",desc:{en:"Calculates the quantile of 'level' using the same algorithm as the 'medianTimingWeighted' function."}},quantileTimingWeighted:{bracket:"(level)(x, weight)",desc:{en:"Calculates the quantile of 'level' using the same algorithm as the 'medianTimingWeighted' function."}},groupUniqArray:{bracket:"(x)",desc:{en:"Creates an array from different argument values. Memory consumption is the same as for the 'uniqExact' function."}},uniqHLL12:{bracket:"(x)",desc:{en:"Uses the HyperLogLog algorithm to approximate the number of different values of the argument. "}},covarPop:{bracket:"(x, y)",desc:{en:"Calculates the value of %%Σ((x - x̅)(y - y̅)) / n%%."}},sequenceCount:{bracket:"(pattern)(time, cond1, cond2, ...)",desc:{en:"sequenceMatch"}},quantileDeterministic:{bracket:"(level)(x, determinator)",desc:{en:"Calculates the quantile of 'level' using the same algorithm as the 'medianDeterministic' function."}},quantileExact:{bracket:"(level)(x, weight)",desc:{en:""}},quantilesDeterministic:{bracket:"(level1, level2, ...)(x, determinator)",desc:{en:"Calculates the quantiles of all specified levels using the same algorithm as the 'medianDeterministic' function."}},medianTiming:{bracket:"(x, weight)",desc:{en:"Differs from the 'medianTiming' function in that it has a second argument - "weights"."}},medianTimingWeighted:{bracket:"(x, weight)",desc:{ru:"",en:"Differs from the 'medianTiming' function in that it has a second argument - "weights"."}},uniqExact:{bracket:"(x)",desc:{en:"Calculates the number of different values of the argument, exactly.
There is no reason to fear approximations, so it's better to use the 'uniq' function.
You should use the 'uniqExact' function if you definitely need an exact result. "}},uniqCombined:{bracket:"(x)",desc:{en:""}},uniqUpTo:{bracket:"(N)(x)",desc:{en:"Calculates the number of different argument values, if it is less than or equal to N.
If the number of different argument values is greater than N, it returns N + 1."}},substring:{bracket:"(s, offset, length)",desc:{en:"The same as 'substring', but for Unicode code points. Works under the assumption that the string contains a set of bytes representing a UTF-8 encoded text. If this assumption is not met, it returns some result (it doesn't throw an exception)."}},notLike:{bracket:"(haystack, pattern), haystack NOT LIKE pattern operator",desc:{en:"The same thing as 'like', but negative."}},hostName:{bracket:"()",desc:{en:"Returns a string with the name of the host that this function was performed on. For distributed processing, this is the name of the remote server host, if the function is performed on a remote server."}},globalNotIn:{bracket:"(v)",desc:{en:"See the section "IN operators"."}},or:{bracket:"(v)",desc:{en:"The same thing as 'max_temporary_columns', but without counting constant columns.
Note that constant columns are formed fairly often when running a query, but they require approximately zero computing resources."}},extractAll:{bracket:"(haystack, pattern)",desc:{en:"Extracts all the fragments of a string using a regular expression. If 'haystack' doesn't match the 'pattern' regex, an empty string is returned. Returns an array of strings consisting of all matches to the regex."}},arrayFirst:{bracket:"(func, arr1, ...)",desc:{en:"Returns the index of the first element in the 'arr1' array for which 'func' returns something other than 0."}},notEquals:{bracket:"(v)",desc:{ru:"",en:""}},arrayExists:{bracket:"([func,] arr1, ...)",desc:{en:"Returns 1 if there is at least one element in 'arr' for which 'func' returns something other than 0. Otherwise, it returns 0."}},arrayCount:{bracket:"([func,] arr1, ...)",desc:{en:"Returns the number of elements in 'arr' for which 'func' returns something other than 0. If 'func' is not specified, it returns the number of non-zero items in the array."}},arrayMap:{bracket:"(func, arr1, ...)",desc:{en:"Returns an array obtained from the original application of the 'func' function to each element in the 'arr' array."}},now:{bracket:"(v)",desc:{en:"If the parameter is true, INSERT operation will skip columns with unknown names from input.
Otherwise, an exception will be generated, it is default behavior.
The parameter works only for JSONEachRow and TSKV input formats."}},intDiv:{bracket:"(a, b)",desc:{en:"Differs from 'intDiv' in that it returns zero when dividing by zero or when dividing a minimal negative number by minus one."}},topLevelDomain:{bracket:"(v)",desc:{en:"- Selects the top-level domain. Example: .ru."}},intHash32:{bracket:"(v)",desc:{en:"Calculates a 32-bit hash code from any type of integer.
This is a relatively fast non-cryptographic hash function of average quality for numbers."}},replaceOne:{bracket:"(haystack, pattern, replacement)",desc:{en:"Replaces the first occurrence, if it exists, of the 'pattern' substring in 'haystack' with the 'replacement' substring.
Hereafter, 'pattern' and 'replacement' must be constants."}},cityHash64:{bracket:"(v)",desc:{en:"Calculates CityHash64 from a string or a similar hash function for any number of any type of arguments.
For String-type arguments, CityHash is used. This is a fast non-cryptographic hash function for strings with decent quality"}},OSToRoot:{bracket:"(v)",desc:{en:"Accepts a UInt8 number - the ID of the operating system from the Yandex.Metrica dictionary. If any OS matches the passed number, it returns a UInt8 number - the ID of the corresponding root OS (for example, it converts Windows Vista to Windows). Otherwise, returns 0."}},sipHash128:{bracket:"(v)",desc:{en:"Calculates SipHash from a string.
Accepts a String-type argument. Returns FixedString(16).
Differs from sipHash64 in that the final xor-folding state is only done up to 128 bits."}},SHA1:{bracket:"(v)",desc:{en:"Calculates SHA-1, SHA-224, or SHA-256 from a string and returns the resulting set of bytes as FixedString(20), FixedString(28), or FixedString(32)."}},asin:{bracket:"(x)",desc:{en:"The arc sine."}},SHA256:{bracket:"(v)",desc:{en:"Calculates SHA-1, SHA-224, or SHA-256 from a string and returns the resulting set of bytes as FixedString(20), FixedString(28), or FixedString(32)."}},MD5:{bracket:"(v)",desc:{en:"Calculates the MD5 from a string and returns the resulting set of bytes as FixedString(16)."}},bitmaskToList:{bracket:"(num)",desc:{en:"Accepts an integer. Returns a string containing the list of powers of two that total the source number when summed. They are comma-separated without spaces in text format, in ascending order."}},array:{bracket:"(v)",desc:{en:"The -%%Array%% suffix can be appended to any aggregate function. In this case, the aggregate function takes arguments of the 'Array(T)' type (arrays) instead of 'T' type arguments. If the aggregate function accepts multiple arguments, this must be arrays of equal lengths. "}},dictGetStringOrDefault:{bracket:"(v)",desc:{ru:"%%dictGetT('dict_name', 'attr_name', id, default)%%
Аналогично функциям dictGetT, но значение по умолчанию берётся из последнего аргумента функции.",en:""}},greaterOrEquals:{bracket:"(v)",desc:{ru:"",en:""}},e:{bracket:"(v)",desc:{en:"What to do when the amount of data exceeds one of the limits: 'throw' or 'break'. By default, throw."}},runningDifference:{bracket:"(x)",desc:{en:"Calculates the difference between consecutive values in the data block.
Result of the function depends on the order of the data in the blocks.

It works only inside of the each processed block of data. Data splitting in the blocks is not explicitly controlled by the user. "}},not:{bracket:"(v)",desc:{ru:'Смотрите раздел "Операторы IN".',en:"See the section "IN operators"."}},intHash64:{bracket:"(v)",desc:{en:"Calculates a 64-bit hash code from any type of integer.
It works faster than intHash32. Average quality."}},acos:{bracket:"(x)",desc:{ru:"Арккосинус.",en:"The arc cosine."}},dictGetString:{bracket:"(v)",desc:{en:""}},and:{bracket:"(x, determinator)",desc:{en:"This function works similarly to the 'median' function - it approximates the median. However, in contrast to 'median', the result is deterministic and does not depend on the order of query execution.

To achieve this, the function takes a second argument - the "determinator". "}},dictGetDate:{bracket:"(v)",desc:{ru:"",en:""}},dictGetFloat32:{bracket:"(v)",desc:{ru:"",en:""}},dictGetInt8:{bracket:"(v)",desc:{ru:"",en:""}},dictGetUInt32:{bracket:"(v)",desc:{ru:"",en:""}},OSIn:{bracket:"(lhs, rhs)",desc:{en:"Checks whether the 'lhs' operating system belongs to the 'rhs' operating system."}},arrayFirstIndex:{bracket:"(func, arr1, ...)",desc:{en:"Returns the index of the first element in the 'arr1' array for which 'func' returns something other than 0."}},ceil:{bracket:"(x[, N])",desc:{en:"Returns the smallest round number that is greater than or equal to 'x'. In every other way, it is the same as the 'floor' function (see above)."}},fragment:{bracket:"(v)",desc:{en:"Removes the query-string and fragment identifier. The question mark and number sign are also removed."}},dictGetUInt8:{bracket:"(v)",desc:{ru:"",en:""}},dictHas:{bracket:"(v)",desc:{ru:"%%dictHas('dict_name', id)%%
- проверить наличие ключа в словаре. Возвращает значение типа UInt8, равное 0, если ключа нет и 1, если ключ есть.",en:""}},arraySum:{bracket:"([func,] arr1, ...)",desc:{en:"Returns the sum of the 'func' values. If the function is omitted, it just returns the sum of the array elements."}},emptyArrayDateTime:{bracket:"(v)",desc:{en:"Accepts zero arguments and returns an empty array of the appropriate type."}},intDivOrZero:{bracket:"(a, b)",desc:{en:"Differs from 'intDiv' in that it returns zero when dividing by zero or when dividing a minimal negative number by minus one."}},SEHierarchy:{bracket:"(v)",desc:{en:"Accepts a UInt8 number - the ID of the search engine from the Yandex.Metrica dictionary. Returns an array with a hierarchy of search engines. Similar to the 'regionHierarchy' function."}},regionToContinent:{bracket:"(id[, geobase])",desc:{en:"Converts a region to a continent. In every other way, this function is the same as 'regionToCity'.
Example: %%regionToContinent(toUInt32(213)) = 10001%% converts Moscow (213) to Eurasia (10001)."}},dictGetInt32:{bracket:"(v)",desc:{ru:"",en:""}},toInt8:{bracket:"(v)",desc:{en:"Functions for converting between numbers, strings (but not fixed strings), dates, and dates with times. All these functions accept one argument. "}},materialize:{bracket:"(x)",desc:{en:"Turns a constant into a full column containing just one value.
In ClickHouse, full columns and constants are represented differently in memory. Functions work differently for constant arguments and normal arguments (different code is executed), although the result is almost always the same. This function is for debugging this behavior."}},regionToCountry:{bracket:"(id[, geobase])",desc:{en:"Converts a region to a country. In every other way, this function is the same as 'regionToCity'.
Example: %%regionToCountry(toUInt32(213)) = 225%% converts Moscow (213) to Russia (225)."}},dictGetDateTime:{bracket:"(v)",desc:{ru:"",en:""}},xor:{bracket:"(v)",desc:{ru:"",en:""}},regionToCity:{bracket:"(id[, geobase])",desc:{en:"Accepts a UInt32 number - the region ID from the Yandex geobase. If this region is a city or part of a city, it returns the region ID for the appropriate city. Otherwise, returns 0."}},dictGetFloat64:{bracket:"(v)",desc:{ru:"",en:""}},timeSlot:{bracket:"(StartTime, Duration)",desc:{en:"For a time interval starting at 'StartTime' and continuing for 'Duration' seconds, it returns an array of moments in time, consisting of points from this interval rounded down to the half hour."}},toTime:{bracket:"(v)",desc:{en:"Converts a date with time to the date of the start of the Unix Epoch, while preserving the time."}},log2:{bracket:"(x)",desc:{en:"Accepts a numeric argument and returns a Float64 number close to the binary logarithm of the argument."}},toRelativeHourNum:{bracket:"(v)",desc:{en:"Converts a date with time or date to the number of the hour, starting from a certain fixed point in the past."}},toRelativeDayNum:{bracket:"(v)",desc:{en:"Converts a date with time or date to the number of the day, starting from a certain fixed point in the past."}},toRelativeWeekNum:{bracket:"(v)",desc:{en:"Converts a date with time or date to the number of the week, starting from a certain fixed point in the past."}},splitByString:{bracket:"(separator, s)",desc:{en:"The same as above, but it uses a string of multiple characters as the separator. The string must be non-empty."}},currentDatabase:{bracket:"()",desc:{en:"Returns the name of the current database.
You can use this function in table engine parameters in a CREATE TABLE query where you need to specify the database."}},toRelativeMonthNum:{bracket:"(v)",desc:{en:"Converts a date with time or date to the number of the month, starting from a certain fixed point in the past."}},visibleWidth:{bracket:"(x)",desc:{en:"Calculates the approximate width when outputting values to the console in text format (tab-separated). This function is used by the system for implementing Pretty formats."}},bitShiftRight:{bracket:"(a, b)",desc:{en:""}},toRelativeYearNum:{bracket:"(v)",desc:{en:"Converts a date with time or date to the number of the year, starting from a certain fixed point in the past."}},toStartOfHour:{bracket:"(v)",desc:{en:"Rounds down a date with time to the start of the hour."}},halfMD5:{bracket:"(v)",desc:{en:"Calculates the MD5 from a string. Then it takes the first 8 bytes of the hash and interprets them as UInt64 in big endian."}},toStartOfFiveMinute:{bracket:"(v)",desc:{en:""}},toUInt16OrZero:{bracket:"(v)",desc:{en:"Functions for converting between numbers, strings (but not fixed strings), dates, and dates with times. All these functions accept one argument."}},toMonday:{bracket:"(v)",desc:{en:"Rounds down a date or date with time to the nearest Monday.
Returns the date."}},IPv6NumToString:{bracket:"(x)",desc:{en:"Accepts a FixedString(16) value containing the IPv6 address in binary format. Returns a string containing this address in text format. "}},indexOf:{bracket:"(arr, x)",desc:{ru:"Возвращает индекс элемента x (начиная с 1), если он есть в массиве, или 0, если его нет.",en:"Returns the index of the 'x' element (starting from 1) if it is in the array, or 0 if it is not."}},today:{bracket:"(v)",desc:{ru:"Принимает ноль аргументов и возвращает текущую дату на один из моментов выполнения запроса.
То же самое, что toDate(now())",en:"Accepts zero arguments and returns the current date at one of the moments of request execution.
The same as 'toDate(now())'."}},emptyArrayToSingle:{bracket:"(v)",desc:{ru:"Принимает пустой массив и возвращает массив из одного элемента, равного значению по умолчанию.",en:"Accepts an empty array as argument and returns an array of one element equal to the default value."}},sleep:{bracket:"(seconds)",desc:{ru:"Спит seconds секунд на каждый блок данных. Можно указать как целое число, так и число с плавающей запятой.",en:"Sleeps 'seconds' seconds on each data block. You can specify an integer or a floating-point number."}},extract:{bracket:"(params, name)",desc:{en:"Parses the string in double quotes. The value is unescaped. If unescaping failed, it returns an empty string. Examples: "}},emptyArrayInt8:{bracket:"(v)",desc:{ru:"Принимает ноль аргументов и возвращает пустой массив соответствующего типа.",en:"Accepts zero arguments and returns an empty array of the appropriate type."}},regionToName:{bracket:"(id[, lang])",desc:{en:"Accepts a UInt32 number - the region ID from the Yandex geobase. A string with the name of the language can be passed as a second argument. Supported languages are: ru, en, ua, uk, by, kz, tr. If the second argument is omitted, the language 'ru' is used. "}},concat:{bracket:"(arr[, separator])",desc:{ru:"Склеивает строки, перечисленные в массиве, с разделителем separator.
separator - необязательный параметр, константная строка, по умолчанию равен пустой строке.
Возвращается строка.",en:"Concatenates strings from the array elements, using 'separator' as the separator.
'separator' is a string constant, an optional parameter. By default it is an empty string.
Returns a string."}},convertCharset:{bracket:"(s, from, to)",desc:{ru:"Возвращает сконвертированную из кодировки from в кодировку to строку s.",en:"Returns a string with the data %%s%% (encoded as %%from%% charset) that was converted to the %%to%% charset."}},toMonth:{bracket:"(v)",desc:{ru:"Переводит дату или дату-с-временем в число типа UInt8, содержащее номер месяца (1-12).",en:"Converts a date or date with time to a UInt8 number containing the month number (1-12)."}},IPv6StringToNum:{bracket:"(s)",desc:{ru:"Функция, обратная к IPv6NumToString. Если IPv6 адрес в неправильном формате, то возвращает строку из нулевых байт.
HEX может быть в любом регистре.",en:"The reverse function of IPv6NumToString. If the IPv6 address has an invalid format, it returns a string of null bytes.
HEX can be uppercase or lowercase."}},emptyArrayString:{bracket:"(v)",desc:{ru:"Принимает ноль аргументов и возвращает пустой массив соответствующего типа.",en:"Accepts zero arguments and returns an empty array of the appropriate type."}},uptime:{bracket:"()",desc:{ru:"Возвращает аптайм сервера в секундах.",en:"Returns server's uptime in seconds."}},blockSize:{bracket:"()",desc:{en:"Gets the size of the block.
In ClickHouse, queries are always run on blocks (sets of column parts). This function allows getting the size of the block that you called it for."}},toInt64OrZero:{bracket:"(v)",desc:{en:"Functions for converting between numbers, strings (but not fixed strings), dates, and dates with times. All these functions accept one argument. "}},pathFull:{bracket:"(v)",desc:{ru:"То же самое, но включая query string и fragment. Пример: /top/news.html?page=2#comments",en:"- The same as above, but including query-string and fragment. Example: /top/news.html?page=2#comments"}},emptyArrayDate:{bracket:"(v)",desc:{ru:"Принимает ноль аргументов и возвращает пустой массив соответствующего типа.",en:"Accepts zero arguments and returns an empty array of the appropriate type."}},emptyArrayInt64:{bracket:"(v)",desc:{ru:"Принимает ноль аргументов и возвращает пустой массив соответствующего типа.",en:"Accepts zero arguments and returns an empty array of the appropriate type."}},toInt32OrZero:{bracket:"(v)",desc:{en:"Functions for converting between numbers, strings (but not fixed strings), dates, and dates with times. All these functions accept one argument. "}},greater:{bracket:"(v)",desc:{ru:"",en:""}},emptyArrayInt32:{bracket:"(v)",desc:{ru:"Принимает ноль аргументов и возвращает пустой массив соответствующего типа.",en:"Accepts zero arguments and returns an empty array of the appropriate type."}},toString:{bracket:"(str)",desc:{ru:"Принимает значение типа FixedString(16). Возвращает строку из 36 символов в текстовом виде.",en:"Accepts a FixedString(16) value containing the UUID in the binary format. Returns a readable string containing the UUID in the text format."}},greatest:{bracket:"(a, b)",desc:{ru:"Возвращает наибольшее значение из a и b.",en:"Returns the greatest element of a and b."}},emptyArrayUInt64:{bracket:"(v)",desc:{ru:"Принимает ноль аргументов и возвращает пустой массив соответствующего типа.",en:"Accepts zero arguments and returns an empty array of the appropriate type."}},emptyArrayUInt32:{bracket:"(v)",desc:{ru:"Принимает ноль аргументов и возвращает пустой массив соответствующего типа.",en:"Accepts zero arguments and returns an empty array of the appropriate type."}},formatReadableSize:{bracket:"(x)",desc:{en:"Gets a size (number of bytes). Returns a string that contains rounded size with the suffix (KiB, MiB etc.).

Example:

%% "}},toInt16OrZero:{bracket:"(v)",desc:{en:"Functions for converting between numbers, strings (but not fixed strings), dates, and dates with times. All these functions accept one argument. "}},emptyArrayUInt8:{bracket:"(v)",desc:{ru:"Принимает ноль аргументов и возвращает пустой массив соответствующего типа.",en:"Accepts zero arguments and returns an empty array of the appropriate type."}},protocol:{bracket:"(v)",desc:{ru:"Возвращает протокол. Примеры: http, ftp, mailto, magnet...",en:"- Selects the protocol. Examples: http, ftp, mailto, magnet..."}},regionToPopulation:{bracket:"(id[, geobase])",desc:{en:"Gets the population for a region.
The population can be recorded in files with the geobase. See the section "External dictionaries".
If the population is not recorded for the region, it returns 0.
In the Yandex geobase, the population might be recorded for child regions, but not for parent regions."}},notIn:{bracket:"(v)",desc:{ru:'Смотрите раздел "Операторы IN".',en:"See the section "IN operators"."}},position:{bracket:"(haystack, needle)",desc:{en:"The same as 'position', but the position is returned in Unicode code points. Works under the assumption that the string contains a set of bytes representing a UTF-8 encoded text. If this assumption is not met, it returns some result (it doesn't throw an exception).
There's also positionCaseInsensitiveUTF8 function."}},arrayElement:{bracket:"(arr, n), arr[n] operator",desc:{en:"Get the element with the index 'n' from the array 'arr'.
'n' should be any integer type.
Indexes in an array begin from one.
Negative indexes are supported - in this case, it selects the corresponding element numbered from the end. "}},toStringCutToZero:{bracket:"(s)",desc:{en:"Accepts a String or FixedString argument. Returns a String that is cut to a first null byte occurrence."}},log:{bracket:"(x)",desc:{ru:"Принимает числовой аргумент, возвращает число типа Float64, близкое к десятичному логарифму от аргумента.",en:"Accepts a numeric argument and returns a Float64 number close to the decimal logarithm of the argument."}},SEIn:{bracket:"(lhs, rhs)",desc:{ru:"Проверяет принадлежность поисковой системы lhs поисковой системе rhs.",en:"Checks whether the 'lhs' search engine belongs to the 'rhs' search engine."}},replicate:{bracket:"(v)",desc:{en:"Create a MergeTree table with a different name. Move all the data from the directory with the ReplicatedMergeTree table data to the new table's data directory." +delete a[e.name];var i=n[e.scope||t],s=i&&i.indexOf(e);s>=0&&i.splice(s,1)}}var n=this.snippetMap,r=this.snippetNameMap;e.content?a(e):Array.isArray(e)&&e.forEach(a)},this.parseSnippetFile=function(e){e=e.replace(/\r/g,"");for(var t,a=[],n={},r=/^#.*|^({[\s\S]*})\s*$|^(\S+) (.*)$|^((?:\n*\t.*)+)/gm;t=r.exec(e);){if(t[1])try{n=JSON.parse(t[1]),a.push(n)}catch(i){}if(t[4])n.content=t[4].replace(/^\t/gm,""),a.push(n),n={};else{var s=t[2],o=t[3];if("regex"==s){var c=/\/((?:[^\/\\]|\\.)*)|$/g;n.guard=c.exec(o)[1],n.trigger=c.exec(o)[1],n.endTrigger=c.exec(o)[1],n.endGuard=c.exec(o)[1]}else"snippet"==s?(n.tabTrigger=o.match(/^\S*/)[0],n.name||(n.name=o)):n[s]=o}}return a},this.getSnippetByName=function(e,t){var a,n=this.snippetNameMap;return this.getActiveScopes(t).some(function(t){var r=n[t];return r&&(a=r[e]),!!a},this),a}}).call(u.prototype);var m=function(e){return e.tabstopManager?e.tabstopManager:(e.tabstopManager=this,this.$onChange=this.onChange.bind(this),this.$onChangeSelection=i.delayedCall(this.onChangeSelection.bind(this)).schedule,this.$onChangeSession=this.onChangeSession.bind(this),this.$onAfterExec=this.onAfterExec.bind(this),void this.attach(e))};(function(){this.attach=function(e){this.index=0,this.ranges=[],this.tabstops=[],this.$openTabstops=null,this.selectedTabstop=null,this.editor=e,this.editor.on("change",this.$onChange),this.editor.on("changeSelection",this.$onChangeSelection),this.editor.on("changeSession",this.$onChangeSession),this.editor.commands.on("afterExec",this.$onAfterExec),this.editor.keyBinding.addKeyboardHandler(this.keyboardHandler)},this.detach=function(){this.tabstops.forEach(this.removeTabstopMarkers,this),this.ranges=null,this.tabstops=null,this.selectedTabstop=null,this.editor.removeListener("change",this.$onChange),this.editor.removeListener("changeSelection",this.$onChangeSelection),this.editor.removeListener("changeSession",this.$onChangeSession),this.editor.commands.removeListener("afterExec",this.$onAfterExec),this.editor.keyBinding.removeKeyboardHandler(this.keyboardHandler),this.editor.tabstopManager=null,this.editor=null},this.onChange=function(e){var t="r"==e.action[0],a=e.start,n=e.end,r=a.row,i=n.row,s=i-r,o=n.column-a.column;if(t&&(s=-s,o=-o),!this.$inChange&&t){var c=this.selectedTabstop,l=c&&!c.some(function(e){return d(e.start,a)<=0&&d(e.end,n)>=0});if(l)return this.detach()}for(var u=this.ranges,m=0;m0?(this.removeRange(h),m--):(h.start.row==r&&h.start.column>a.column&&(h.start.column+=o),h.end.row==r&&h.end.column>=a.column&&(h.end.column+=o),h.start.row>=r&&(h.start.row+=s),h.end.row>=r&&(h.end.row+=s),d(h.start,h.end)>0&&this.removeRange(h)))}u.length||this.detach()},this.updateLinkedFields=function(){var e=this.selectedTabstop;if(e&&e.hasLinkedRanges){this.$inChange=!0;for(var a=this.editor.session,n=a.getTextRange(e.firstNonLinked),r=e.length;r--;){var i=e[r];if(i.linked){var s=t.snippetManager.tmStrFormat(n,i.original);a.replace(i,s)}}this.$inChange=!1}},this.onAfterExec=function(e){e.command&&!e.command.readOnly&&this.updateLinkedFields()},this.onChangeSelection=function(){if(this.editor){for(var e=this.editor.selection.lead,t=this.editor.selection.anchor,a=this.editor.selection.isEmpty(),n=this.ranges.length;n--;)if(!this.ranges[n].linked){var r=this.ranges[n].contains(e.row,e.column),i=a||this.ranges[n].contains(t.row,t.column);if(r&&i)return}this.detach()}},this.onChangeSession=function(){this.detach()},this.tabNext=function(e){var t=this.tabstops.length,a=this.index+(e||1);a=Math.min(Math.max(a,1),t),a==t&&(a=0),this.selectTabstop(a),0===a&&this.detach()},this.selectTabstop=function(e){this.$openTabstops=null;var t=this.tabstops[this.index];if(t&&this.addTabstopMarkers(t),this.index=e,t=this.tabstops[this.index],t&&t.length){if(this.selectedTabstop=t,this.editor.inVirtualSelectionMode)this.editor.selection.setRange(t.firstNonLinked);else{var a=this.editor.multiSelect;a.toSingleRange(t.firstNonLinked.clone());for(var n=t.length;n--;)t.hasLinkedRanges&&t[n].linked||a.addRange(t[n].clone(),!0);a.ranges[0]&&a.addRange(a.ranges[0].clone())}this.editor.keyBinding.addKeyboardHandler(this.keyboardHandler)}},this.addTabstops=function(e,t,a){if(this.$openTabstops||(this.$openTabstops=[]),!e[0]){var n=s.fromPoints(a,a);g(n.start,t),g(n.end,t),e[0]=[n],e[0].index=0}var r=this.index,i=[r+1,0],o=this.ranges;e.forEach(function(e,a){for(var n=this.$openTabstops[a]||e,r=e.length;r--;){var c=e[r],l=s.fromPoints(c.start,c.end||c.start);p(l.start,t),p(l.end,t),l.original=c,l.tabstop=n,o.push(l),n!=e?n.unshift(l):n[r]=l,c.fmtString?(l.linked=!0,n.hasLinkedRanges=!0):n.firstNonLinked||(n.firstNonLinked=l)}n.firstNonLinked||(n.hasLinkedRanges=!1),n===e&&(i.push(n),this.$openTabstops[a]=n),this.addTabstopMarkers(n)},this),i.length>2&&(this.tabstops.length&&i.push(i.splice(2,1)[0]),this.tabstops.splice.apply(this.tabstops,i))},this.addTabstopMarkers=function(e){var t=this.editor.session;e.forEach(function(e){e.markerId||(e.markerId=t.addMarker(e,"ace_snippet-marker","text"))})},this.removeTabstopMarkers=function(e){var t=this.editor.session;e.forEach(function(e){t.removeMarker(e.markerId),e.markerId=null})},this.removeRange=function(e){var t=e.tabstop.indexOf(e);e.tabstop.splice(t,1),t=this.ranges.indexOf(e),this.ranges.splice(t,1),this.editor.session.removeMarker(e.markerId),e.tabstop.length||(t=this.tabstops.indexOf(e.tabstop),-1!=t&&this.tabstops.splice(t,1),this.tabstops.length||this.detach())},this.keyboardHandler=new c,this.keyboardHandler.bindKeys({Tab:function(e){t.snippetManager&&t.snippetManager.expandWithTab(e)||e.tabstopManager.tabNext(1)},"Shift-Tab":function(e){e.tabstopManager.tabNext(-1)},Esc:function(e){e.tabstopManager.detach()},Return:function(e){return!1}})}).call(m.prototype);var h={};h.onChange=o.prototype.onChange,h.setPosition=function(e,t){this.pos.row=e,this.pos.column=t},h.update=function(e,t,a){this.$insertRight=a,this.pos=e,this.onChange(t)};var p=function(e,t){0==e.row&&(e.column+=t.column),e.row+=t.row},g=function(e,t){e.row==t.row&&(e.column-=t.column),e.row-=t.row};e("./lib/dom").importCssString(".ace_snippet-marker { -moz-box-sizing: border-box; box-sizing: border-box; background: rgba(194, 193, 208, 0.09); border: 1px dotted rgba(211, 208, 235, 0.62); position: absolute;}"),t.snippetManager=new u;var f=e("./editor").Editor;(function(){this.insertSnippet=function(e,a){return t.snippetManager.insertSnippet(this,e,a)},this.expandSnippet=function(e){return t.snippetManager.expandWithTab(this,e)}}).call(f.prototype)}),ace.define("ace/autocomplete/popup",["require","exports","module","ace/virtual_renderer","ace/editor","ace/range","ace/lib/event","ace/lib/lang","ace/lib/dom"],function(e,t,a){var n=e("../virtual_renderer").VirtualRenderer,r=e("../editor").Editor,i=e("../range").Range,s=e("../lib/event"),o=e("../lib/lang"),c=e("../lib/dom"),l=function(e){var t=new n(e);t.$maxLines=4;var a=new r(t);return a.setHighlightActiveLine(!1),a.setShowPrintMargin(!1),a.renderer.setShowGutter(!1),a.renderer.setHighlightGutterLine(!1),a.$mouseHandler.$focusWaitTimout=0,a.$highlightTagPending=!0,a},d=function(e){var t=c.createElement("div"),a=new l(t);e&&e.appendChild(t),t.style.display="none",a.renderer.content.style.cursor="default",a.renderer.setStyle("ace_autocomplete"),a.setOption("displayIndentGuides",!1),a.setOption("dragDelay",150);var n=function(){};a.focus=n,a.$isFocused=!0,a.renderer.$cursorLayer.restartTimer=n,a.renderer.$cursorLayer.element.style.opacity=0,a.renderer.$maxLines=8,a.renderer.$keepTextAreaAtCursor=!1,a.setHighlightActiveLine(!1),a.session.highlight(""),a.session.$searchHighlight.clazz="ace_highlight-marker",a.on("mousedown",function(e){var t=e.getDocumentPosition();a.selection.moveToPosition(t),u.start.row=u.end.row=t.row,e.stop()});var r,d=new i(-1,0,-1,1/0),u=new i(-1,0,-1,1/0);u.id=a.session.addMarker(u,"ace_active-line","fullLine"),a.setSelectOnHover=function(e){e?d.id&&(a.session.removeMarker(d.id),d.id=null):d.id=a.session.addMarker(d,"ace_line-hover","fullLine")},a.setSelectOnHover(!1),a.on("mousemove",function(e){if(!r)return void(r=e);if(r.x!=e.x||r.y!=e.y){r=e,r.scrollTop=a.renderer.scrollTop;var t=r.getDocumentPosition().row;d.start.row!=t&&(d.id||a.setRow(t),h(t))}}),a.renderer.on("beforeRender",function(){if(r&&-1!=d.start.row){r.$pos=null;var e=r.getDocumentPosition().row;d.id||a.setRow(e),h(e,!0)}}),a.renderer.on("afterRender",function(){var e=a.getRow(),t=a.renderer.$textLayer,n=t.element.childNodes[e-t.config.firstRow];n!=t.selectedNode&&(t.selectedNode&&c.removeCssClass(t.selectedNode,"ace_selected"),t.selectedNode=n,n&&c.addCssClass(n,"ace_selected"))});var m=function(){h(-1)},h=function(e,t){e!==d.start.row&&(d.start.row=d.end.row=e,t||a.session._emit("changeBackMarker"),a._emit("changeHoverMarker"))};a.getHoveredRow=function(){return d.start.row},s.addListener(a.container,"mouseout",m),a.on("hide",m),a.on("changeSelection",m),a.session.doc.getLength=function(){return a.data.length},a.session.doc.getLine=function(e){var t=a.data[e];return"string"==typeof t?t:t&&t.value||""};var p=a.session.bgTokenizer;return p.$tokenizeRow=function(e){var t=a.data[e],n=[];if(!t)return n;"string"==typeof t&&(t={value:t}),t.caption||(t.caption=t.value||t.name);var r,i,s=-1;t.iconClass&&n.push({type:"icon ace_icon-"+t.iconClass,value:" "});for(var o=0;oc-2&&(l=l.substr(0,c-t.caption.length-3)+"…"),n.push({type:"rightAlignedText",value:l})}return n},p.$updateOnChange=n,p.start=n,a.session.$computeWidth=function(){return this.screenWidth=0},a.$blockScrolling=1/0,a.isOpen=!1,a.isTopdown=!1,a.data=[],a.setData=function(e){a.setValue(o.stringRepeat("\n",e.length),-1),a.data=e||[],a.setRow(0)},a.getData=function(e){return a.data[e]},a.getRow=function(){return u.start.row},a.setRow=function(e){e=Math.max(0,Math.min(this.data.length,e)),u.start.row!=e&&(a.selection.clearSelection(),u.start.row=u.end.row=e||0,a.session._emit("changeBackMarker"),a.moveCursorTo(e||0,0),a.isOpen&&a._signal("select"))},a.on("changeSelection",function(){a.isOpen&&a.setRow(a.selection.lead.row),a.renderer.scrollCursorIntoView()}),a.hide=function(){this.container.style.display="none",this._signal("hide"),a.isOpen=!1},a.show=function(e,t,n){var i=this.container,s=window.innerHeight,o=window.innerWidth,c=this.renderer,l=c.$maxLines*t*1.4,d=e.top+this.$borderSize,u=d>s/2&&!n;u&&d+t+l>s?(c.$maxPixelHeight=d-2*this.$borderSize,i.style.top="",i.style.bottom=s-d+"px",a.isTopdown=!1):(d+=t,c.$maxPixelHeight=s-d-.2*t,i.style.top=d+"px",i.style.bottom="",a.isTopdown=!0),i.style.display="",this.renderer.$textLayer.checkForSizeChanges();var m=e.left;m+i.offsetWidth>o&&(m=o-i.offsetWidth),i.style.left=m+"px",this._signal("show"),r=null,a.isOpen=!0},a.getTextLeftOffset=function(){return this.$borderSize+this.renderer.$padding+this.$imageSize},a.$imageSize=0,a.$borderSize=1,a};c.importCssString(".ace_editor.ace_autocomplete .ace_marker-layer .ace_active-line { background-color: #CAD6FA; z-index: 1;}.ace_editor.ace_autocomplete .ace_line-hover { border: 1px solid #abbffe; margin-top: -1px; background: rgba(233,233,253,0.4);}.ace_editor.ace_autocomplete .ace_line-hover { position: absolute; z-index: 2;}.ace_editor.ace_autocomplete .ace_scroller { background: none; border: none; box-shadow: none;}.ace_rightAlignedText { color: gray; display: inline-block; position: absolute; right: 4px; text-align: right; z-index: -1;}.ace_editor.ace_autocomplete .ace_completion-highlight{ color: #000; text-shadow: 0 0 0.01em;}.ace_editor.ace_autocomplete { width: 280px; z-index: 200000; background: #fbfbfb; color: #444; border: 1px lightgray solid; position: fixed; box-shadow: 2px 3px 5px rgba(0,0,0,.2); line-height: 1.4;}"),t.AcePopup=d}),ace.define("ace/autocomplete/util",["require","exports","module"],function(e,t,a){t.parForEach=function(e,t,a){var n=0,r=e.length;0===r&&a();for(var i=0;r>i;i++)t(e[i],function(e,t){n++,n===r&&a(e,t)})};var n=/[a-zA-Z_0-9\$\-\u00A2-\uFFFF]/;t.retrievePrecedingIdentifier=function(e,t,a){a=a||n;for(var r=[],i=t-1;i>=0&&a.test(e[i]);i--)r.push(e[i]);return r.reverse().join("")},t.retrieveFollowingIdentifier=function(e,t,a){a=a||n;for(var r=[],i=t;i=t?a:t-1;break;case"down":t=t>=a?-1:t+1;break;case"start":t=0;break;case"end":t=a}this.popup.setRow(t)},this.insertMatch=function(e,t){if(e||(e=this.popup.getData(this.popup.getRow())),!e)return!1;if(e.completer&&e.completer.insertMatch)e.completer.insertMatch(this.editor,e);else{if(this.completions.filterText)for(var a,n=this.editor.selection.getAllRanges(),r=0;a=n[r];r++)a.start.column-=this.completions.filterText.length,this.editor.session.remove(a);e.snippet?c.insertSnippet(this.editor,e.snippet):this.editor.execCommand("insertstring",e.value||e)}this.detach()},this.commands={Up:function(e){e.completer.goTo("up")},Down:function(e){e.completer.goTo("down")},"Ctrl-Up|Ctrl-Home":function(e){e.completer.goTo("start")},"Ctrl-Down|Ctrl-End":function(e){e.completer.goTo("end")},Esc:function(e){e.completer.detach()},Return:function(e){return e.completer.insertMatch()},"Shift-Return":function(e){e.completer.insertMatch(null,{deleteSuffix:!0})},Tab:function(e){var t=e.completer.insertMatch();return t||e.tabstopManager?t:void e.completer.goTo("down")},PageUp:function(e){e.completer.popup.gotoPageUp()},PageDown:function(e){e.completer.popup.gotoPageDown()}},this.gatherCompletions=function(e,t){var a=e.getSession(),n=e.getCursorPosition(),r=(a.getLine(n.row),i.getCompletionPrefix(e));this.base=a.doc.createAnchor(n.row,n.column-r.length),this.base.$insertRight=!0;var s=[],o=e.completers.length;return e.completers.forEach(function(i,c){i.getCompletions(e,a,n,r,function(n,i){!n&&i&&(s=s.concat(i));var c=e.getCursorPosition();a.getLine(c.row);t(null,{prefix:r,matches:s,finished:0===--o})})}),!0},this.showPopup=function(e){this.editor&&this.detach(),this.activated=!0,this.editor=e,e.completer!=this&&(e.completer&&e.completer.detach(),e.completer=this),e.on("changeSelection",this.changeListener),e.on("blur",this.blurListener),e.on("mousedown",this.mousedownListener),e.on("mousewheel",this.mousewheelListener),this.updateCompletions()},this.updateCompletions=function(e){if(e&&this.base&&this.completions){var t=this.editor.getCursorPosition(),a=this.editor.session.getTextRange({start:this.base,end:t});if(a==this.completions.filterText)return;return this.completions.setFilter(a),this.completions.filtered.length&&(1!=this.completions.filtered.length||this.completions.filtered[0].value!=a||this.completions.filtered[0].snippet)?void this.openPopup(this.editor,a,e):this.detach()}var n=this.gatherCompletionsId;this.gatherCompletions(this.editor,function(t,a){var r=function(){return a.finished?this.detach():void 0}.bind(this),i=a.prefix,s=a&&a.matches;if(!s||!s.length)return r();if(0===i.indexOf(a.prefix)&&n==this.gatherCompletionsId){this.completions=new d(s),this.exactMatch&&(this.completions.exactMatch=!0),this.completions.setFilter(i);var o=this.completions.filtered;return o.length&&(1!=o.length||o[0].value!=i||o[0].snippet)?this.autoInsert&&1==o.length&&a.finished?this.insertMatch(o[0]):void this.openPopup(this.editor,i,e):r()}}.bind(this))},this.cancelContextMenu=function(){this.editor.$mouseHandler.cancelContextMenu()},this.updateDocTooltip=function(){var e=this.popup,t=e.data,a=t&&(t[e.getHoveredRow()]||t[e.getRow()]),n=null;return a&&this.editor&&this.popup.isOpen?(this.editor.completers.some(function(e){return e.getDocTooltip&&(n=e.getDocTooltip(a)),n}),n||(n=a),"string"==typeof n&&(n={docText:n}),n&&(n.docHTML||n.docText)?void this.showDocTooltip(n):this.hideDocTooltip()):this.hideDocTooltip()},this.showDocTooltip=function(e){this.tooltipNode||(this.tooltipNode=o.createElement("div"),this.tooltipNode.className="ace_tooltip ace_doc-tooltip",this.tooltipNode.style.margin=0,this.tooltipNode.style.pointerEvents="auto",this.tooltipNode.tabIndex=-1,this.tooltipNode.onblur=this.blurListener.bind(this));var t=this.tooltipNode;e.docHTML?t.innerHTML=e.docHTML:e.docText&&(t.textContent=e.docText),t.parentNode||document.body.appendChild(t);var a=this.popup,n=a.container.getBoundingClientRect();t.style.top=a.container.style.top,t.style.bottom=a.container.style.bottom,window.innerWidth-n.right<320?(t.style.right=window.innerWidth-n.left+"px",t.style.left=""):(t.style.left=n.right+1+"px",t.style.right=""),t.style.display="block"},this.hideDocTooltip=function(){if(this.tooltipTimer.cancel(),this.tooltipNode){var e=this.tooltipNode;this.editor.isFocused()||document.activeElement!=e||this.editor.focus(),this.tooltipNode=null,e.parentNode&&e.parentNode.removeChild(e)}}}).call(l.prototype),l.startCommand={name:"startAutocomplete",exec:function(e){e.completer||(e.completer=new l),e.completer.autoInsert=!1,e.completer.autoSelect=!0,e.completer.showPopup(e),e.completer.cancelContextMenu()},bindKey:"Ctrl-Space|Ctrl-Shift-Space|Alt-Space"};var d=function(e,t){this.all=e,this.filtered=e,this.filterText=t||"",this.exactMatch=!1};(function(){this.setFilter=function(e){if(e.length>this.filterText&&0===e.lastIndexOf(this.filterText,0))var t=this.filtered;else var t=this.all;this.filterText=e,t=this.filterCompletions(t,this.filterText),t=t.sort(function(e,t){return t.exactMatch-e.exactMatch||t.score-e.score});var a=null;t=t.filter(function(e){var t=e.snippet||e.caption||e.value;return t===a?!1:(a=t,!0)}),this.filtered=t},this.filterCompletions=function(e,t){var a=[],n=t.toUpperCase(),r=t.toLowerCase();e:for(var i,s=0;i=e[s];s++){var o=i.value||i.caption||i.snippet;if(o){var c,l,d=-1,u=0,m=0;if(this.exactMatch){if(t!==o.substr(0,t.length))continue e}else for(var h=0;h=0&&(0>g||g>p)?p:g,0>c)continue e;l=c-d-1,l>0&&(-1===d&&(m+=10),m+=l),u|=1<",s.escapeHTML(e.caption),"","
",s.escapeHTML(e.snippet)].join(""))}},u=[d,c,l];t.setCompleters=function(e){u.length=0,e&&u.push.apply(u,e)},t.addCompleter=function(e){u.push(e)},t.textCompleter=c,t.keyWordCompleter=l,t.snippetCompleter=d;var m,h={name:"expandSnippet",exec:function(e){return n.expandWithTab(e)},bindKey:"Tab"},p=function(e,t){g(t.session.$mode)},g=function k(e){var t=e.$id;n.files||(n.files={}),f(t),e.modes&&e.modes.forEach(k)},f=function x(e){if(e&&!n.files[e]){var t=e.replace("mode","snippets");n.files[e]={},i.loadModule(t,function(t){t&&(n.files[e]=t,!t.snippets&&t.snippetText&&(t.snippets=n.parseSnippetFile(t.snippetText)),n.register(t.snippets||[],t.scope),t.includeScopes&&(n.snippetMap[t.scope].includeScopes=t.includeScopes,t.includeScopes.forEach(function(e){x("ace/mode/"+e)})))})}},b=function(e){var t=e.editor,a=t.completer&&t.completer.activated;if("backspace"===e.command.name)a&&!o.getCompletionPrefix(t)&&t.completer.detach();else if("insertstring"===e.command.name){var n=o.getCompletionPrefix(t);n&&n.length>=t.$liveAutocompletionThreshold&&!a&&(t.completer||(t.completer=new r),t.completer.autoInsert=!1,t.completer.showPopup(t))}},v=s.delayedCall(function(){b(m)},0),y=function(e){m=e,v.delay(e.editor.$liveAutocompletionDelay)},w=e("../editor").Editor;e("../config").defineOptions(w.prototype,"editor",{enableBasicAutocompletion:{set:function(e){e?(this.completers||(this.completers=Array.isArray(e)?e:u),this.commands.addCommand(r.startCommand)):this.commands.removeCommand(r.startCommand)},value:!1},enableLiveAutocompletion:{set:function(e){e?(this.completers||(this.completers=Array.isArray(e)?e:u),this.commands.on("afterExec",y)):this.commands.removeListener("afterExec",y)},value:!1},liveAutocompletionThreshold:{value:0},liveAutocompletionDelay:{value:500},enableSnippets:{set:function(e){e?(this.commands.addCommand(h),this.on("changeMode",p),p(null,this)):(this.commands.removeCommand(h),this.off("changeMode",p))},value:!1}})}),function(){ace.require(["ace/ext/language_tools"],function(){})}(),ace.define("ace/ext/beautify/php_rules",["require","exports","module","ace/token_iterator"],function(e,t,a){e("ace/token_iterator").TokenIterator;t.newLines=[{type:"support.php_tag",value:""},{type:"paren.lparen",value:"{",indent:!0},{type:"paren.rparen",breakBefore:!0,value:"}",indent:!1},{type:"paren.rparen",breakBefore:!0,value:"})",indent:!1,dontBreak:!0},{type:"comment"},{type:"text",value:";"},{type:"text",value:":",context:"php"},{type:"keyword",value:"case",indent:!0,dontBreak:!0},{type:"keyword",value:"default",indent:!0,dontBreak:!0},{type:"keyword",value:"break",indent:!1,dontBreak:!0},{type:"punctuation.doctype.end",value:">"},{type:"meta.tag.punctuation.end",value:">"},{type:"meta.tag.punctuation.begin",value:"<",blockTag:!0,indent:!0,dontBreak:!0},{type:"meta.tag.punctuation.begin",value:""!=o.value?n="php":"support.php_tag"==o.type&&"?>"==o.value?n="html":"meta.tag.name.style"==o.type&&"css"!=n?n="css":"meta.tag.name.style"==o.type&&"css"==n?n="html":"meta.tag.name.script"==o.type&&"js"!=n?n="js":"meta.tag.name.script"==o.type&&"js"==n&&(n="html"),g=e.stepForward(),g&&0==g.type.indexOf("meta.tag.name")&&(s=g.value),"support.php_tag"==p.type&&"v;v++)u+=" ";break}if(h===!1)for(v in c)if(!(p.type!=c[v].type||c[v].value&&p.value!=c[v].value||c[v].blockTag&&-1!==d.indexOf(r)||c[v].context&&c[v].context!==n)){if(c[v].indent===!0&&m++,!c[v].dontBreak&&!f)for(u+="\n",v=0;m>v;v++)u+=" ";break}if(u+=b,"support.php_tag"==p.type&&"?>"==p.value&&(h=!1),i=r,p=o,o=g,null===o)break}else o=g;else o=e.stepForward();return u}}),ace.define("ace/ext/beautify",["require","exports","module","ace/token_iterator","ace/ext/beautify/php_rules"],function(e,t,a){var n=e("ace/token_iterator").TokenIterator,r=e("./beautify/php_rules").transform;t.beautify=function(e){var t=new n(e,0,0),a=(t.getCurrentToken(),e.$modeId.split("/").pop()),i=r(t,a);e.doc.setValue(i)},t.commands=[{name:"beautify",exec:function(e){t.beautify(e.session)},bindKey:"Ctrl-Shift-B"}]}),function(){ace.require(["ace/ext/beautify"],function(){})}(),ace.define("ace/mode/clickhouse_highlight_rules",["require","exports","$rootScope","module","ace/lib/oop","ace/snippets","ace/ext/language_tools","ace/mode/text_highlight_rules"],function(e,t,a){var n=e("../lib/oop"),r=e("./text_highlight_rules").TextHighlightRules,i=function(){var e=this,t="SELECT|CASE|THEN|DISTINCT|INSERT|UPDATE|DELETE|WHERE|AND|OR|OFFSET|HAVING|AS|FROM|WHEN|ELSE|END|TYPE|LEFT|RIGHT|JOIN|ON|OUTER|DESC|ASC|UNION|CREATE|TABLE|PRIMARY|KEY|FOREIGN|NOT|REFERENCES|DEFAULT|INNER|CROSS|NATURAL|DATABASE|DROP|GRANT|ANY|BETWEEN|ATTACH|DETACH|CAST|WITH|BIT_AND|BIT_OR|TO|BIT_XOR|DESCRIBE|OPTIMIZE|PREWHERE|TOTALS|DATABASES|PROCESSLIST|SHOW|IF",a="RENAME\\WTABLE|IF\\W+NOT\\W+EXISTS|IF\\W+EXISTS|FORMAT\\W+Vertical|FORMAT\\W+JSONCompact|FORMAT\\W+JSONEachRow|FORMAT\\W+TSKV|FORMAT\\W+TabSeparatedWithNames|FORMAT\\W+TabSeparatedWithNamesAndTypes|FORMAT\\W+TabSeparatedRaw|FORMAT\\W+BlockTabSeparated|FORMAT\\W+CSVWithNames|FORMAT\\W+CSV|FORMAT\\W+JSON|FORMAT\\W+TabSeparated",n="true|false|NULL",r="sum|sumIf|avg|avgIf",i="date|integer|uint8|uint16|uint32|uint64|int8|int16|int32|int64|float32|float64|datetime|enum8|enum16|fixedstring|array|tuple|stringMergeTree|SummingMergeTree|ReplacingMergeTree|ReplicatedMergeTree|Buffer|ReplicatedCollapsingMergeTree|CollapsingMergeTree|AggregatingMergeTree|Merge|Memory|GraphiteMergeTree|ReplicatedAggregatingMergeTree|ReplicatedSummingMergeTree",s=["IF NOT EXISTS","RENAME TABLE","IF EXISTS","GROUP BY","ORDER BY","UNION ALL","FORMAT JSON","FORMAT JSONCompact","FORMAT JSONEachRow","FORMAT TSV","FORMAT TabSeparated","FORMAT TabSeparatedWithNames","FORMAT TabSeparatedWithNamesAndTypes","FORMAT TabSeparatedRaw","FORMAT BlockTabSeparated","FORMAT TSKV","FORMAT CSV","FORMAT CSVWithNames","SYSTEM RELOAD DICTIONARY","SYSTEM RELOAD DICTIONARIES","SYSTEM DROP DNS CACHE","SYSTEM SHUTDOWN","SYSTEM KILL","CLEAR COLUMN IN PARTITION"],o=["DRAW_GMAPS","DRAW_PLOTLY","DRAW_CALENDAR","DRAW_TEXT","DRAW_HEATMAP","DRAW_CHART","DRAW_BAR","DRAW_GRIDCHART","DRAW_RIVER","DRAW_RAW","DRAW_SANKEYS","DRAW_TREEMAP","DRAW_C3","DRAW_MAP"],c="";if(window.aceJSRules&&window.aceJSRules.builtinFunctions){if(window.aceJSRules.builtinFunctions){var l=[];window.aceJSRules.builtinFunctions.forEach(function(e){l.push(e.name)}),r=l.join("|")}_.isArray(window.aceJSRules.tables)&&(c=window.aceJSRules.tables.join("|"))}var d="";d=window.global_delimiter?new RegExp(window.global_delimiter):new RegExp(";;");var u=[],m=t.toLowerCase();window.aceJSRules&&_.isArray(window.aceJSRules.fieldsList)&&window.aceJSRules.fieldsList.forEach(function(e){var t=e.name.toLowerCase()+"|";m.indexOf(t)>-1||u.push(e.name)});var h=this.createKeywordMapper({"support.function":r,keyword:t,"constant.language":n, +"storage.type":i,"markup.bold":c,"markup.heading":u.join("|")},"identifier",!0);this.$rules={start:[{token:"comment",regex:"--.*$",caseInsensitive:!0},{token:"comment.block",start:"```",end:"```"},{token:"keyword",regex:"GROUP\\W+BY|ON\\W+CLUSTER|ORDER\\W+BY|LIMIT\\W+\\d+\\W*,\\W*\\d+|LIMIT\\W+\\d+\\W+BY\\W+|LIMIT\\W+\\d+"},{token:"variable.language",regex:/\$[\w]+(?:\[[\w\]+]|[=\-]>\w+)?/},{token:"variable.language",regex:/@[\w]+(?:\[[\w\]+]|[=\-]>\w+)?/},{token:"variable.language",regex:/\:[\w]+(?:\[[\w\]+]|[=\-]>\w+)?/},{token:"variable.language",regex:/\{[\w]+(?:\[[\w\]+]|[=\-]>\w+)\}?/},{token:"comment",start:"/\\*",end:"\\*/"},{token:"constant",regex:'".*?"'},{token:"storage",regex:a},{token:"invalid.illegal",regex:o.join("|")},{token:"string",regex:"'.*?'"},{token:"constant.numeric",regex:"[+-]?\\d+(?:(?:\\.\\d*)?(?:[eE][+-]?\\d+)?)?\\b"},{token:h,regex:"[a-zA-Z_$][a-zA-Z0-9_$]*\\b"},{token:"constant.character.escape",regex:d},{token:"punctuation",regex:/[?:,;.]/},{token:"keyword.operator",regex:"\\+|\\-|\\/|\\/\\/|%|<@>|@>|<@|&|\\^|~|<|>|<=|=>|==|!=|<>|="},{token:"paren.lparen",regex:"[\\(\\{]"},{token:"paren.rparen",regex:"[\\)\\}]"},{token:"text",regex:"\\s+"}]},this.normalizeRules(),this.completions=[],this.getCompletions=function(){return e.completions},this.addCompletions=function(e,t,a,n,r,i,s){this.completions.push({name:e,value:t,caption:a,score:n,meta:r,iconClass:i,docHTML:s})},this.addCompletionsDictionaries=function(e){this.addCompletions(e.dic,e.dic,e.title,0,"dic","dict",this.makeCompletionsDocFunctions(e.title,e.dic))},this.addCompletionsFunctions=function(e){this.addCompletions(e.name,e.name+"( )",e.name+"( )",e.score,"function","function",this.makeCompletionsDocFunctions(e.name,e.origin,e.comb))},this.addCompletionsTableFiled=function(e){var t=e.table+"."+e.name,a=e.name,n="type:"+e.type+"

default_type:"+e.default_type+"
"+e.default_expression;this.addCompletions(t,a,a,100,e.type,"field",this.makeCompletionsdocHTML(t,n))},this.addArrayCompletions=function(e,t,a){var n=this;e.forEach(function(e){n.addCompletions(e,e,e,0,t,a,!1)})},this.setKeywords=function(e){console.log("setKeywords > ",e),this.keywordRule.onMatch=this.createKeywordMapper(e,"identifier")},this.makeCompletionsDocFunctions=function(e,t,a){if(!window.global_chFunctionsHelp)return!1;if(!window.global_chFunctionsHelp.functions)return!1;var n="",r=e;if("undefined"!=typeof window.global_chFunctionsHelp.functions[e]?r=e:"undefined"!=typeof window.global_chFunctionsHelp.functions[t]&&(r=t),"undefined"!=typeof window.global_chFunctionsHelp.functions[r]){var i="en",s=window.global_chFunctionsHelp.functions[r],o="",c="";s.desc&&(o=s.bracket,c=s.desc[i],c||(c=s.desc.en?s.desc.en:s.desc.ru)),c&&(c=c.replace(/\.\s*/gm,".
")),n=''+e+o+'
'+c+" "}else n=''+e+"( )
"+t;return n+'
'},this.makeCompletionsdocHTML=function(e,t){return'
'+e+"
"+t+"
"},this.addArrayCompletions(t.split("|"),"keyword","keyword"),this.addArrayCompletions(s,"keyword","keyword"),this.addArrayCompletions(o,"draw","draw"),this.addArrayCompletions(i.split("|"),"type","type")};n.inherits(i,r),t.ClickhouseHighlightRules=i}),ace.define("ace/mode/matching_brace_outdent",["require","exports","module","ace/range"],function(e,t,a){var n=e("ace/range").Range,r=function(){};(function(){this.checkOutdent=function(e,t){return/^\s+$/.test(e)?/^\s*\}/.test(t):!1},this.autoOutdent=function(e,t){var a=e.getLine(t),r=a.match(/^(\s*\})/);if(!r)return 0;var i=r[1].length,s=e.findMatchingBracket({row:t,column:i});if(!s||s.row==t)return 0;var o=this.$getIndent(e.getLine(s.row));e.replace(new n(t,0,t,i-1),o)},this.$getIndent=function(e){return e.match(/^\s*/)[0]}}).call(r.prototype),t.MatchingBraceOutdent=r}),ace.define("ace/mode/clickhouse_FoldMode",["$rootScope","require","exports","module","ace/lib/oop","ace/range","ace/mode/sqlserver","ace/mode/folding/cstyle"],function(e,t,a){var n=e("../lib/oop"),r=e("ace/mode/folding/cstyle").FoldMode,i=(e("ace/range").Range,e("ace/token_iterator").TokenIterator),s=t.FoldMode=function(){};n.inherits(s,r),function(){this.foldingRules="cStyle",this.foldingStartMarker=/\(|\{/,this.getFoldWidgetRange=function(e,t,a,n){for(var r=new i(e,a,0),s=r.getCurrentToken(),o=!1;s;){var c=s,l=r.getCurrentTokenPosition();if(s=r.stepForward(),"paren.lparen"!=c.type||"("!=c.value&&"{"!=c.value||(o=e.getBracketRange(l)),o)break}return o}}.call(s.prototype)}),window.global_chFunctionsHelp={functions:{corr:{bracket:"(x, y)",desc:{en:'Calculates the Pearson correlation coefficient: Σ((x - x̅)(y - y̅)) / sqrt(Σ((x - x̅)2) * Σ((y - y̅)2)).'}},stddevPop:{bracket:"(x)",desc:{en:"The result is equal to the square root of 'varPop(x)'."}},varPop:{bracket:"(x, y)",desc:{en:"Calculates the value of %%Σ((x - x̅)(y - y̅)) / n%%."}},argMin:{bracket:"(arg, val)",desc:{en:"Calculates the 'arg' value for a minimal 'val' value. If there are several different values of 'arg' for minimal values of 'val', the first of these values encountered is output."}},quantileExactWeighted:{bracket:"(level)(x, weight)",desc:{en:"Вычисляет квантиль уровня level точно."}},min:{bracket:"(v)",desc:{en:"Minimal execution speed in rows per second. Checked on every data block when 'timeout_before_checking_execution_speed' expires. If the execution speed is lower, an exception is thrown."}},varSamp:{bracket:"(x, y)",desc:{en:"Calculates the value of %%Σ((x - x̅)(y - y̅)) / (n - 1)%%.

Returns Float64. If n <= 1, it returns +∞."}},anyLast:{bracket:"(x)",desc:{en:"Selects the last value encountered.
The result is just as indeterminate as for the 'any' function."}},argMax:{bracket:"(arg, val)",desc:{en:"Calculates the 'arg' value for a maximum 'val' value. If there are several different values of 'arg' for maximum values of 'val', the first of these values encountered is output."}},count:{bracket:"()",desc:{en:"Counts the number of rows. "}},any:{bracket:"(x)",desc:{en:"Selects the last value encountered.
The result is just as indeterminate as for the 'any' function."}},avg:{bracket:"(x)",desc:{en:"Calculates the average.
Only works for numbers.
The result is always Float64."}},sequenceMatch:{bracket:"(pattern)(time, cond1, cond2, ...)",desc:{en:"Pattern matching for event chains.

'pattern' is a string containing a pattern to match."}},stddevSamp:{bracket:"(x)",desc:{en:"The result is equal to the square root of 'varSamp(x)'."}},medianDeterministic:{bracket:"(x, determinator)",desc:{en:"This function works similarly to the 'median' function - it approximates the median."}},quantilesTimingWeighted:{bracket:"(level1, level2, ...)(x, weight)",desc:{en:"Calculates the quantiles of all specified levels using the same algorithm as the 'medianTimingWeighted' function."}},uniq:{bracket:"(N)(x)",desc:{en:"Calculates the number of different argument values, if it is less than or equal to N.
If the number of different argument values is greater than N, it returns N + 1."}},covarSamp:{bracket:"(x, y)",desc:{en:"Calculates the value of %%Σ((x - x̅)(y - y̅)) / (n - 1)%%.

Returns Float64. If n <= 1, it returns +∞."}},max:{bracket:"(v)",desc:{en:"Maximum number of bytes (uncompressed data) that can be passed to a remote server or saved in a temporary table when using GLOBAL IN."}},quantileTDigest:{bracket:"(level)(x)",desc:{en:"t-digest"}},quantilesTiming:{bracket:"(level1, level2, ...)(x, weight)",desc:{en:"Calculates the quantiles of all specified levels using the same algorithm as the 'medianTimingWeighted' function."}},quantiles:{bracket:"(level1, level2, ...)(x, determinator)",desc:{en:"Calculates the quantiles of all specified levels using the same algorithm as the 'medianDeterministic' function."}},quantile:{bracket:"(level1, level2, ...)(x, determinator)",desc:{en:"Calculates the quantiles of all specified levels using the same algorithm as the 'medianDeterministic' function."}},groupArray:{bracket:"(x)",desc:{en:"Creates an array of argument values.
Values can be added to the array in any (indeterminate) order.

In some cases, you can rely on the order of execution. This applies to cases when SELECT comes from a subquery that uses ORDER BY."}},sum:{bracket:"(x)",desc:{en:"Calculates the sum.
Only works for numbers."}},median:{bracket:"(x, weight)",desc:{en:"Differs from the 'medianTiming' function in that it has a second argument - "weights". Weight is a non-negative integer.
The result is calculated as if the 'x' value were passed 'weight' number of times to the 'medianTiming' function."}},quantileTiming:{bracket:"(level)(x, weight)",desc:{en:"Calculates the quantile of 'level' using the same algorithm as the 'medianTimingWeighted' function."}},quantileTimingWeighted:{bracket:"(level)(x, weight)",desc:{en:"Calculates the quantile of 'level' using the same algorithm as the 'medianTimingWeighted' function."}},groupUniqArray:{bracket:"(x)",desc:{en:"Creates an array from different argument values. Memory consumption is the same as for the 'uniqExact' function."}},uniqHLL12:{bracket:"(x)",desc:{en:"Uses the HyperLogLog algorithm to approximate the number of different values of the argument. "}},covarPop:{bracket:"(x, y)",desc:{en:"Calculates the value of %%Σ((x - x̅)(y - y̅)) / n%%."}},sequenceCount:{bracket:"(pattern)(time, cond1, cond2, ...)",desc:{en:"sequenceMatch"}},quantileDeterministic:{bracket:"(level)(x, determinator)",desc:{en:"Calculates the quantile of 'level' using the same algorithm as the 'medianDeterministic' function."}},quantileExact:{bracket:"(level)(x, weight)",desc:{en:""}},quantilesDeterministic:{bracket:"(level1, level2, ...)(x, determinator)",desc:{en:"Calculates the quantiles of all specified levels using the same algorithm as the 'medianDeterministic' function."}},medianTiming:{bracket:"(x, weight)",desc:{en:"Differs from the 'medianTiming' function in that it has a second argument - "weights"."}},medianTimingWeighted:{bracket:"(x, weight)",desc:{ru:"",en:"Differs from the 'medianTiming' function in that it has a second argument - "weights"."}},uniqExact:{bracket:"(x)",desc:{en:"Calculates the number of different values of the argument, exactly.
There is no reason to fear approximations, so it's better to use the 'uniq' function.
You should use the 'uniqExact' function if you definitely need an exact result. "}},uniqCombined:{bracket:"(x)",desc:{en:""}},uniqUpTo:{bracket:"(N)(x)",desc:{en:"Calculates the number of different argument values, if it is less than or equal to N.
If the number of different argument values is greater than N, it returns N + 1."}},substring:{bracket:"(s, offset, length)",desc:{en:"The same as 'substring', but for Unicode code points. Works under the assumption that the string contains a set of bytes representing a UTF-8 encoded text. If this assumption is not met, it returns some result (it doesn't throw an exception)."}},notLike:{bracket:"(haystack, pattern), haystack NOT LIKE pattern operator",desc:{en:"The same thing as 'like', but negative."}},hostName:{bracket:"()",desc:{en:"Returns a string with the name of the host that this function was performed on. For distributed processing, this is the name of the remote server host, if the function is performed on a remote server."}},globalNotIn:{bracket:"(v)",desc:{en:"See the section "IN operators"."}},or:{bracket:"(v)",desc:{en:"The same thing as 'max_temporary_columns', but without counting constant columns.
Note that constant columns are formed fairly often when running a query, but they require approximately zero computing resources."}},extractAll:{bracket:"(haystack, pattern)",desc:{en:"Extracts all the fragments of a string using a regular expression. If 'haystack' doesn't match the 'pattern' regex, an empty string is returned. Returns an array of strings consisting of all matches to the regex."}},arrayFirst:{bracket:"(func, arr1, ...)",desc:{en:"Returns the index of the first element in the 'arr1' array for which 'func' returns something other than 0."}},notEquals:{bracket:"(v)",desc:{ru:"",en:""}},arrayExists:{bracket:"([func,] arr1, ...)",desc:{en:"Returns 1 if there is at least one element in 'arr' for which 'func' returns something other than 0. Otherwise, it returns 0."}},arrayCount:{bracket:"([func,] arr1, ...)",desc:{en:"Returns the number of elements in 'arr' for which 'func' returns something other than 0. If 'func' is not specified, it returns the number of non-zero items in the array."}},arrayMap:{bracket:"(func, arr1, ...)",desc:{en:"Returns an array obtained from the original application of the 'func' function to each element in the 'arr' array."}},now:{bracket:"(v)",desc:{en:"If the parameter is true, INSERT operation will skip columns with unknown names from input.
Otherwise, an exception will be generated, it is default behavior.
The parameter works only for JSONEachRow and TSKV input formats."}},intDiv:{bracket:"(a, b)",desc:{en:"Differs from 'intDiv' in that it returns zero when dividing by zero or when dividing a minimal negative number by minus one."}},topLevelDomain:{bracket:"(v)",desc:{en:"- Selects the top-level domain. Example: .ru."}},intHash32:{bracket:"(v)",desc:{en:"Calculates a 32-bit hash code from any type of integer.
This is a relatively fast non-cryptographic hash function of average quality for numbers."}},replaceOne:{bracket:"(haystack, pattern, replacement)",desc:{en:"Replaces the first occurrence, if it exists, of the 'pattern' substring in 'haystack' with the 'replacement' substring.
Hereafter, 'pattern' and 'replacement' must be constants."}},cityHash64:{bracket:"(v)",desc:{en:"Calculates CityHash64 from a string or a similar hash function for any number of any type of arguments.
For String-type arguments, CityHash is used. This is a fast non-cryptographic hash function for strings with decent quality"}},OSToRoot:{bracket:"(v)",desc:{en:"Accepts a UInt8 number - the ID of the operating system from the Yandex.Metrica dictionary. If any OS matches the passed number, it returns a UInt8 number - the ID of the corresponding root OS (for example, it converts Windows Vista to Windows). Otherwise, returns 0."}},sipHash128:{bracket:"(v)",desc:{en:"Calculates SipHash from a string.
Accepts a String-type argument. Returns FixedString(16).
Differs from sipHash64 in that the final xor-folding state is only done up to 128 bits."}},SHA1:{bracket:"(v)",desc:{en:"Calculates SHA-1, SHA-224, or SHA-256 from a string and returns the resulting set of bytes as FixedString(20), FixedString(28), or FixedString(32)."}},asin:{bracket:"(x)",desc:{en:"The arc sine."}},SHA256:{bracket:"(v)",desc:{en:"Calculates SHA-1, SHA-224, or SHA-256 from a string and returns the resulting set of bytes as FixedString(20), FixedString(28), or FixedString(32)."}},MD5:{bracket:"(v)",desc:{en:"Calculates the MD5 from a string and returns the resulting set of bytes as FixedString(16)."}},bitmaskToList:{bracket:"(num)",desc:{en:"Accepts an integer. Returns a string containing the list of powers of two that total the source number when summed. They are comma-separated without spaces in text format, in ascending order."}},array:{bracket:"(v)",desc:{en:"The -%%Array%% suffix can be appended to any aggregate function. In this case, the aggregate function takes arguments of the 'Array(T)' type (arrays) instead of 'T' type arguments. If the aggregate function accepts multiple arguments, this must be arrays of equal lengths. "}},dictGetStringOrDefault:{bracket:"(v)",desc:{ru:"%%dictGetT('dict_name', 'attr_name', id, default)%%
Аналогично функциям dictGetT, но значение по умолчанию берётся из последнего аргумента функции.",en:""}},greaterOrEquals:{bracket:"(v)",desc:{ru:"",en:""}},e:{bracket:"(v)",desc:{en:"What to do when the amount of data exceeds one of the limits: 'throw' or 'break'. By default, throw."}},runningDifference:{bracket:"(x)",desc:{en:"Calculates the difference between consecutive values in the data block.
Result of the function depends on the order of the data in the blocks.

It works only inside of the each processed block of data. Data splitting in the blocks is not explicitly controlled by the user. "}},not:{bracket:"(v)",desc:{ru:'Смотрите раздел "Операторы IN".',en:"See the section "IN operators"."}},intHash64:{bracket:"(v)",desc:{en:"Calculates a 64-bit hash code from any type of integer.
It works faster than intHash32. Average quality."}},acos:{bracket:"(x)",desc:{ru:"Арккосинус.",en:"The arc cosine."}},dictGetString:{bracket:"(v)",desc:{en:""}},and:{bracket:"(x, determinator)",desc:{en:"This function works similarly to the 'median' function - it approximates the median. However, in contrast to 'median', the result is deterministic and does not depend on the order of query execution.

To achieve this, the function takes a second argument - the "determinator". "}},dictGetDate:{bracket:"(v)",desc:{ru:"",en:""}},dictGetFloat32:{bracket:"(v)",desc:{ru:"",en:""}},dictGetInt8:{bracket:"(v)",desc:{ru:"",en:""}},dictGetUInt32:{bracket:"(v)",desc:{ru:"",en:""}},OSIn:{bracket:"(lhs, rhs)",desc:{en:"Checks whether the 'lhs' operating system belongs to the 'rhs' operating system."}},arrayFirstIndex:{bracket:"(func, arr1, ...)",desc:{en:"Returns the index of the first element in the 'arr1' array for which 'func' returns something other than 0."}},ceil:{bracket:"(x[, N])",desc:{en:"Returns the smallest round number that is greater than or equal to 'x'. In every other way, it is the same as the 'floor' function (see above)."}},fragment:{bracket:"(v)",desc:{en:"Removes the query-string and fragment identifier. The question mark and number sign are also removed."}},dictGetUInt8:{bracket:"(v)",desc:{ru:"",en:""}},dictHas:{bracket:"(v)",desc:{ru:"%%dictHas('dict_name', id)%%
- проверить наличие ключа в словаре. Возвращает значение типа UInt8, равное 0, если ключа нет и 1, если ключ есть.",en:""}},arraySum:{bracket:"([func,] arr1, ...)",desc:{en:"Returns the sum of the 'func' values. If the function is omitted, it just returns the sum of the array elements."}},emptyArrayDateTime:{bracket:"(v)",desc:{en:"Accepts zero arguments and returns an empty array of the appropriate type."}},intDivOrZero:{bracket:"(a, b)",desc:{en:"Differs from 'intDiv' in that it returns zero when dividing by zero or when dividing a minimal negative number by minus one."}},SEHierarchy:{bracket:"(v)",desc:{en:"Accepts a UInt8 number - the ID of the search engine from the Yandex.Metrica dictionary. Returns an array with a hierarchy of search engines. Similar to the 'regionHierarchy' function."}},regionToContinent:{bracket:"(id[, geobase])",desc:{en:"Converts a region to a continent. In every other way, this function is the same as 'regionToCity'.
Example: %%regionToContinent(toUInt32(213)) = 10001%% converts Moscow (213) to Eurasia (10001)."}},dictGetInt32:{bracket:"(v)",desc:{ru:"",en:""}},toInt8:{bracket:"(v)",desc:{en:"Functions for converting between numbers, strings (but not fixed strings), dates, and dates with times. All these functions accept one argument. "}},materialize:{bracket:"(x)",desc:{en:"Turns a constant into a full column containing just one value.
In ClickHouse, full columns and constants are represented differently in memory. Functions work differently for constant arguments and normal arguments (different code is executed), although the result is almost always the same. This function is for debugging this behavior."}},regionToCountry:{bracket:"(id[, geobase])",desc:{en:"Converts a region to a country. In every other way, this function is the same as 'regionToCity'.
Example: %%regionToCountry(toUInt32(213)) = 225%% converts Moscow (213) to Russia (225)."}},dictGetDateTime:{bracket:"(v)",desc:{ru:"",en:""}},xor:{bracket:"(v)",desc:{ru:"",en:""}},regionToCity:{bracket:"(id[, geobase])",desc:{en:"Accepts a UInt32 number - the region ID from the Yandex geobase. If this region is a city or part of a city, it returns the region ID for the appropriate city. Otherwise, returns 0."}},dictGetFloat64:{bracket:"(v)",desc:{ru:"",en:""}},timeSlot:{bracket:"(StartTime, Duration)",desc:{en:"For a time interval starting at 'StartTime' and continuing for 'Duration' seconds, it returns an array of moments in time, consisting of points from this interval rounded down to the half hour."}},toTime:{bracket:"(v)",desc:{en:"Converts a date with time to the date of the start of the Unix Epoch, while preserving the time."}},log2:{bracket:"(x)",desc:{en:"Accepts a numeric argument and returns a Float64 number close to the binary logarithm of the argument."}},toRelativeHourNum:{bracket:"(v)",desc:{en:"Converts a date with time or date to the number of the hour, starting from a certain fixed point in the past."}},toRelativeDayNum:{bracket:"(v)",desc:{en:"Converts a date with time or date to the number of the day, starting from a certain fixed point in the past."}},toRelativeWeekNum:{bracket:"(v)",desc:{en:"Converts a date with time or date to the number of the week, starting from a certain fixed point in the past."}},splitByString:{bracket:"(separator, s)",desc:{en:"The same as above, but it uses a string of multiple characters as the separator. The string must be non-empty."}},currentDatabase:{bracket:"()",desc:{en:"Returns the name of the current database.
You can use this function in table engine parameters in a CREATE TABLE query where you need to specify the database."}},toRelativeMonthNum:{bracket:"(v)",desc:{en:"Converts a date with time or date to the number of the month, starting from a certain fixed point in the past."}},visibleWidth:{bracket:"(x)",desc:{en:"Calculates the approximate width when outputting values to the console in text format (tab-separated). This function is used by the system for implementing Pretty formats."}},bitShiftRight:{bracket:"(a, b)",desc:{en:""}},toRelativeYearNum:{bracket:"(v)",desc:{en:"Converts a date with time or date to the number of the year, starting from a certain fixed point in the past."}},toStartOfHour:{bracket:"(v)",desc:{en:"Rounds down a date with time to the start of the hour."}},halfMD5:{bracket:"(v)",desc:{en:"Calculates the MD5 from a string. Then it takes the first 8 bytes of the hash and interprets them as UInt64 in big endian."}},toStartOfFiveMinute:{bracket:"(v)",desc:{en:""}},toUInt16OrZero:{bracket:"(v)",desc:{en:"Functions for converting between numbers, strings (but not fixed strings), dates, and dates with times. All these functions accept one argument."}},toMonday:{bracket:"(v)",desc:{en:"Rounds down a date or date with time to the nearest Monday.
Returns the date."}},IPv6NumToString:{bracket:"(x)",desc:{en:"Accepts a FixedString(16) value containing the IPv6 address in binary format. Returns a string containing this address in text format. "}},indexOf:{bracket:"(arr, x)",desc:{ru:"Возвращает индекс элемента x (начиная с 1), если он есть в массиве, или 0, если его нет.",en:"Returns the index of the 'x' element (starting from 1) if it is in the array, or 0 if it is not."}},today:{bracket:"(v)",desc:{ru:"Принимает ноль аргументов и возвращает текущую дату на один из моментов выполнения запроса.
То же самое, что toDate(now())",en:"Accepts zero arguments and returns the current date at one of the moments of request execution.
The same as 'toDate(now())'."}},emptyArrayToSingle:{bracket:"(v)",desc:{ru:"Принимает пустой массив и возвращает массив из одного элемента, равного значению по умолчанию.",en:"Accepts an empty array as argument and returns an array of one element equal to the default value."}},sleep:{bracket:"(seconds)",desc:{ru:"Спит seconds секунд на каждый блок данных. Можно указать как целое число, так и число с плавающей запятой.",en:"Sleeps 'seconds' seconds on each data block. You can specify an integer or a floating-point number."}},extract:{bracket:"(params, name)",desc:{en:"Parses the string in double quotes. The value is unescaped. If unescaping failed, it returns an empty string. Examples: "}},emptyArrayInt8:{bracket:"(v)",desc:{ru:"Принимает ноль аргументов и возвращает пустой массив соответствующего типа.",en:"Accepts zero arguments and returns an empty array of the appropriate type."}},regionToName:{bracket:"(id[, lang])",desc:{en:"Accepts a UInt32 number - the region ID from the Yandex geobase. A string with the name of the language can be passed as a second argument. Supported languages are: ru, en, ua, uk, by, kz, tr. If the second argument is omitted, the language 'ru' is used. "}},concat:{bracket:"(arr[, separator])",desc:{ru:"Склеивает строки, перечисленные в массиве, с разделителем separator.
separator - необязательный параметр, константная строка, по умолчанию равен пустой строке.
Возвращается строка.",en:"Concatenates strings from the array elements, using 'separator' as the separator.
'separator' is a string constant, an optional parameter. By default it is an empty string.
Returns a string."}},convertCharset:{bracket:"(s, from, to)",desc:{ru:"Возвращает сконвертированную из кодировки from в кодировку to строку s.",en:"Returns a string with the data %%s%% (encoded as %%from%% charset) that was converted to the %%to%% charset."}},toMonth:{bracket:"(v)",desc:{ru:"Переводит дату или дату-с-временем в число типа UInt8, содержащее номер месяца (1-12).",en:"Converts a date or date with time to a UInt8 number containing the month number (1-12)."}},IPv6StringToNum:{bracket:"(s)",desc:{ru:"Функция, обратная к IPv6NumToString. Если IPv6 адрес в неправильном формате, то возвращает строку из нулевых байт.
HEX может быть в любом регистре.",en:"The reverse function of IPv6NumToString. If the IPv6 address has an invalid format, it returns a string of null bytes.
HEX can be uppercase or lowercase."}},emptyArrayString:{bracket:"(v)",desc:{ru:"Принимает ноль аргументов и возвращает пустой массив соответствующего типа.",en:"Accepts zero arguments and returns an empty array of the appropriate type."}},uptime:{bracket:"()",desc:{ru:"Возвращает аптайм сервера в секундах.",en:"Returns server's uptime in seconds."}},blockSize:{bracket:"()",desc:{en:"Gets the size of the block.
In ClickHouse, queries are always run on blocks (sets of column parts). This function allows getting the size of the block that you called it for."}},toInt64OrZero:{bracket:"(v)",desc:{en:"Functions for converting between numbers, strings (but not fixed strings), dates, and dates with times. All these functions accept one argument. "}},pathFull:{bracket:"(v)",desc:{ru:"То же самое, но включая query string и fragment. Пример: /top/news.html?page=2#comments",en:"- The same as above, but including query-string and fragment. Example: /top/news.html?page=2#comments"}},emptyArrayDate:{bracket:"(v)",desc:{ru:"Принимает ноль аргументов и возвращает пустой массив соответствующего типа.",en:"Accepts zero arguments and returns an empty array of the appropriate type."}},emptyArrayInt64:{bracket:"(v)",desc:{ru:"Принимает ноль аргументов и возвращает пустой массив соответствующего типа.",en:"Accepts zero arguments and returns an empty array of the appropriate type."}},toInt32OrZero:{bracket:"(v)",desc:{en:"Functions for converting between numbers, strings (but not fixed strings), dates, and dates with times. All these functions accept one argument. "}},greater:{bracket:"(v)",desc:{ru:"",en:""}},emptyArrayInt32:{bracket:"(v)",desc:{ru:"Принимает ноль аргументов и возвращает пустой массив соответствующего типа.",en:"Accepts zero arguments and returns an empty array of the appropriate type."}},toString:{bracket:"(str)",desc:{ru:"Принимает значение типа FixedString(16). Возвращает строку из 36 символов в текстовом виде.",en:"Accepts a FixedString(16) value containing the UUID in the binary format. Returns a readable string containing the UUID in the text format."}},greatest:{bracket:"(a, b)",desc:{ru:"Возвращает наибольшее значение из a и b.",en:"Returns the greatest element of a and b."}},emptyArrayUInt64:{bracket:"(v)",desc:{ru:"Принимает ноль аргументов и возвращает пустой массив соответствующего типа.",en:"Accepts zero arguments and returns an empty array of the appropriate type."}},emptyArrayUInt32:{bracket:"(v)",desc:{ru:"Принимает ноль аргументов и возвращает пустой массив соответствующего типа.",en:"Accepts zero arguments and returns an empty array of the appropriate type."}},formatReadableSize:{bracket:"(x)",desc:{en:"Gets a size (number of bytes). Returns a string that contains rounded size with the suffix (KiB, MiB etc.).

Example:

%% "}},toInt16OrZero:{bracket:"(v)",desc:{en:"Functions for converting between numbers, strings (but not fixed strings), dates, and dates with times. All these functions accept one argument. "}},emptyArrayUInt8:{bracket:"(v)",desc:{ru:"Принимает ноль аргументов и возвращает пустой массив соответствующего типа.",en:"Accepts zero arguments and returns an empty array of the appropriate type."}},protocol:{bracket:"(v)",desc:{ru:"Возвращает протокол. Примеры: http, ftp, mailto, magnet...",en:"- Selects the protocol. Examples: http, ftp, mailto, magnet..."}},regionToPopulation:{bracket:"(id[, geobase])",desc:{en:"Gets the population for a region.
The population can be recorded in files with the geobase. See the section "External dictionaries".
If the population is not recorded for the region, it returns 0.
In the Yandex geobase, the population might be recorded for child regions, but not for parent regions."}},notIn:{bracket:"(v)",desc:{ru:'Смотрите раздел "Операторы IN".',en:"See the section "IN operators"."}},position:{bracket:"(haystack, needle)",desc:{en:"The same as 'position', but the position is returned in Unicode code points. Works under the assumption that the string contains a set of bytes representing a UTF-8 encoded text. If this assumption is not met, it returns some result (it doesn't throw an exception).
There's also positionCaseInsensitiveUTF8 function."}},arrayElement:{bracket:"(arr, n), arr[n] operator",desc:{en:"Get the element with the index 'n' from the array 'arr'.
'n' should be any integer type.
Indexes in an array begin from one.
Negative indexes are supported - in this case, it selects the corresponding element numbered from the end. "}},toStringCutToZero:{bracket:"(s)",desc:{en:"Accepts a String or FixedString argument. Returns a String that is cut to a first null byte occurrence."}},log:{bracket:"(x)",desc:{ru:"Принимает числовой аргумент, возвращает число типа Float64, близкое к десятичному логарифму от аргумента.",en:"Accepts a numeric argument and returns a Float64 number close to the decimal logarithm of the argument."}},SEIn:{bracket:"(lhs, rhs)",desc:{ru:"Проверяет принадлежность поисковой системы lhs поисковой системе rhs.",en:"Checks whether the 'lhs' search engine belongs to the 'rhs' search engine."}},replicate:{bracket:"(v)",desc:{en:"Create a MergeTree table with a different name. Move all the data from the directory with the ReplicatedMergeTree table data to the new table's data directory." }},sipHash64:{bracket:"(v)",desc:{en:'Calculates SipHash from a string.
Accepts a String-type argument. Returns UInt64.
SipHash is a cryptographic hash function. It works at least three times faster than MD5. For more information, see https://131002.net/siphash/'}},emptyArrayUInt16:{bracket:"(v)",desc:{en:"Accepts zero arguments and returns an empty array of the appropriate type."}},hex:{bracket:"(str)",desc:{en:"Accepts a string containing any number of hexadecimal digits, and returns a string containing the corresponding bytes. Supports both uppercase and lowercase letters A-F. The number of hexadecimal digits doesn't have to be even."}},regionToDistrict:{bracket:"(id[, geobase])",desc:{en:"Converts a region to a federal district (type 4 in the geobase). In every other way, this function is the same as 'regionToCity'. "}},arrayFilter:{bracket:"(func, arr1, ...)",desc:{en:"Returns an array containing only the elements in 'arr1' for which 'func' returns something other than 0.

Examples:

%%
SELECT arrayFilter(x -> x LIKE '%World%', ['Hello', 'abc World']) AS res "}},toStartOfQuarter:{bracket:"(v)",desc:{en:"Rounds down a date or date with time to the first day of the quarter.
The first day of the quarter is either 1 January, 1 April, 1 July, or 1 October. Returns the date."}},divide:{bracket:"(a, b), a / b operator",desc:{en:"Calculates the quotient of the numbers. The result type is always a floating-point type.
It is not integer division. For integer division, use the 'intDiv' function.
When dividing by zero you get 'inf', '-inf', or 'nan'."}},reverseUTF8:{bracket:"(v)",desc:{en:"Reverses a sequence of Unicode code points, assuming that the string contains a set of bytes representing a UTF-8 text. Otherwise, it does something else (it doesn't throw an exception)."}},toDate:{bracket:"(v)",desc:{en:"Functions for converting between numbers, strings (but not fixed strings), dates, and dates with times. All these functions accept one argument. "}},emptyArrayFloat64:{bracket:"(v)",desc:{en:"Accepts zero arguments and returns an empty array of the appropriate type."}},abs:{bracket:"(s, c)",desc:{en:"If the %%s%% string is non-empty and does not contain the %%c%% character at the end, it appends the %%c%% character to the end."}},yesterday:{bracket:"(v)",desc:{en:"Accepts zero arguments and returns yesterday's date at one of the moments of request execution.
The same as 'today() - 1'."}},toMinute:{bracket:"(v)",desc:{en:"Converts a date with time to a UInt8 number containing the number of the minute of the hour (0-59)."}},bitXor:{bracket:"(a, b)",desc:{en:""}},minus:{bracket:"(a, b), a - b operator",desc:{en:"Calculates the difference. The result is always signed.

You can also calculate whole numbers from a date or date with time. The idea is the same - see above for 'plus'."}},toDateTime:{bracket:"(v)",desc:{en:"Functions for converting between numbers, strings (but not fixed strings), dates, and dates with times. All these functions accept one argument. "}},modulo:{bracket:"(a, b), a % b operator",desc:{en:"Calculates the remainder after division.
If arguments are floating-point numbers, they are pre-converted to integers by dropping the decimal portion. The remainder is taken in the same sense as in C++. Truncated division is used for negative numbers.
An exception is thrown when dividing by zero or when dividing a minimal negative number by minus one."}},bitmaskToArray:{bracket:"(num)",desc:{en:"Accepts an integer. Returns an array of UInt64 numbers containing the list of powers of two that total the source number when summed. Numbers in the array are in ascending order."}},negate:{bracket:"(a), -a operator",desc:{en:"Calculates a number with the reverse sign. The result is always signed."}},emptyArrayFloat32:{bracket:"(v)",desc:{en:"Accepts zero arguments and returns an empty array of the appropriate type."}},range:{bracket:"(N)",desc:{en:"Returns an array of numbers from 0 to N-1.
Just in case, an exception is thrown if arrays with a total length of more than 100,000,000 elements are created in a data block."}},arrayAll:{bracket:"([func,] arr1, ...)",desc:{en:"Returns 1 if 'func' returns something other than 0 for all the elements in 'arr'. Otherwise, it returns 0."}},toInt32:{bracket:"(v)",desc:{en:"Functions for converting between numbers, strings (but not fixed strings), dates, and dates with times. All these functions accept one argument. "}},unhex:{bracket:"(str)",desc:{en:"Accepts a string containing any number of hexadecimal digits, and returns a string containing the corresponding bytes. Supports both uppercase and lowercase letters A-F. The number of hexadecimal digits doesn't have to be even. If it is odd, the last digit is interpreted as the younger half of the 00-0F byte. If the argument string contains anything other than hexadecimal digits, some implementation-defined result is returned (an exception isn't thrown).
If you want to convert the result to a number, you can use the functions 'reverse' and 'reinterpretAsType'."}},toFloat64:{bracket:"(v)",desc:{en:"Functions for converting between numbers, strings (but not fixed strings), dates, and dates with times. All these functions accept one argument. "}},bitAnd:{bracket:"(a, b)",desc:{ru:"",en:""}},toStartOfYear:{bracket:"(v)",desc:{en:"Rounds down a date or date with time to the first day of the year.
Returns the date."}},bitOr:{bracket:"(a, b)",desc:{ru:"",en:""}},SEToRoot:{bracket:"(v)",desc:{en:"Accepts a UInt8 number - the ID of the search engine from the Yandex.Metrica dictionary. If any search engine matches the passed number, it returns a UInt8 number - the ID of the corresponding root search engine (for example, it converts Yandex.Images to Yandex). Otherwise, returns 0."}},toRelativeMinuteNum:{bracket:"(v)",desc:{en:"Converts a date with time or date to the number of the minute, starting from a certain fixed point in the past."}},visitParamExtractInt:{bracket:"(params, name)",desc:{ru:"Аналогично для Int64.",en:"The same as for Int64."}},emptyArrayInt16:{bracket:"(v)",desc:{en:"Accepts zero arguments and returns an empty array of the appropriate type."}},visitParamExtractString:{bracket:"(params, name)",desc:{en:"Parses the string in double quotes. The value is unescaped. If unescaping failed, it returns an empty string. "}},arrayEnumerateUniq:{bracket:"(arr, ...)",desc:{en:"Returns an array the same size as the source array, indicating for each element what its position is among elements with the same value. "}},visitParamExtractUInt:{bracket:"(params, name)",desc:{en:"Parses UInt64 from the value of the field named 'name'. If this is a string field, it tries to parse a number from the beginning of the string. If the field doesn't exist, or it exists but doesn't contain a number, it returns 0."}},toTypeName:{bracket:"(x)",desc:{en:"Gets the type name. Returns a string containing the type name of the passed argument."}},empty:{bracket:"(v)",desc:{en:"Accepts an empty array as argument and returns an array of one element equal to the default value."}},multiply:{bracket:"(a, b), a * b operator",desc:{en:"Calculates the product of the numbers."}},has:{bracket:"('database', 'table', 'column')",desc:{ru:"",en:"Accepts constant String columns - database name, table name and column name. Returns constant UInt8 value, equal to 1 if column exists,
otherwise 0.
If table doesn't exist than exception is thrown.
For elements of nested data structure function checks existence of column. For nested data structure 0 is returned."}},bitNot:{bracket:"(a)",desc:{ru:"",en:""}},lessOrEquals:{bracket:"(v)",desc:{ru:"",en:"

greaterOrEquals, >= operator

"}},reinterpretAsInt64:{bracket:"(v)",desc:{en:""}},IPv4NumToString:{bracket:"(num)",desc:{en:"Similar to IPv4NumToString, but using %%xxx%% instead of the last octet. "}},bitShiftLeft:{bracket:"(a, b)",desc:{ru:"",en:""}},dictGetInt16:{bracket:"(v)",desc:{ru:"",en:""}},toUInt32OrZero:{bracket:"(v)",desc:{en:"Functions for converting between numbers, strings (but not fixed strings), dates, and dates with times. All these functions accept one argument. "}},regionIn:{bracket:"(lhs, rhs[, geobase])",desc:{en:"Checks whether a 'lhs' region belongs to a 'rhs' region. Returns a UInt8 number equal to 1 if it belongs, or 0 if it doesn't belong.
The relationship is reflexive - any region also belongs to itself."}},reinterpretAsUInt8:{bracket:"(v)",desc:{en:""}},dictIsIn:{bracket:"(v)",desc:{en:"%%dictIsIn('dict_name', child_id, ancestor_id)%%
- For the 'dict_name' hierarchical dictionary, finds out whether the 'child_id' key is located inside 'ancestor_id' (or matches 'ancestor_id'). Returns UInt8."}},toSecond:{bracket:"(v)",desc:{en:"Converts a date with time to a UInt8 number containing the number of the second in the minute (0-59).
Leap seconds are not accounted for."}},least:{bracket:"(a, b)",desc:{en:"Returns the least element of a and b."}},countEqual:{bracket:"(arr, x)",desc:{en:'Returns the number of elements in the array equal to 'x'. Equivalent to arrayCount(elem -> elem = x, arr).'}},IPv4StringToNum:{bracket:"(s)",desc:{en:"The reverse function of IPv4NumToString. If the IPv4 address has an invalid format, it returns 0."}},replaceRegexpAll:{bracket:"(haystack, pattern, replacement)",desc:{en:"This does the same thing, but replaces all the occurrences"}},SHA224:{bracket:"(v)",desc:{en:"Calculates SHA-1, SHA-224, or SHA-256 from a string and returns the resulting set of bytes as FixedString(20), FixedString(28), or FixedString(32).
The function works fairly slowly (SHA-1 processes about 5 million short strings per second per processor core, while SHA-224 and SHA-256 process about 2.2 million). "}},URLHash:{bracket:"(url[, N])",desc:{en:"A fast, decent-quality non-cryptographic hash function for a string obtained from a URL using some type of normalization.
URLHash(s) - Calculates a hash from a string without one of the trailing symbols /,? or # at the end, if present"}},equals:{bracket:"(v)",desc:{ru:"",en:"

greaterOrEquals, >= operator

"}},plus:{bracket:"(a, b), a + b operator",desc:{ru:"Вычисляет сумму чисел.

Также можно складывать целые числа с датой и датой-с-временем. В случае даты, прибавление целого числа означает прибавление соответствующего количества дней. В случае даты-с-временем - прибавление соответствующего количества секунд.",en:"Calculates the sum of the numbers.

You can also add whole numbers with a date or date and time. In the case of a date, adding a whole number means adding the corresponding number of days. For a date with time, it means adding the corresponding number of seconds."}},less:{bracket:"(v)",desc:{ru:"",en:"

greaterOrEquals, >= operator

"}},regionHierarchy:{bracket:"(id[, geobase])",desc:{en:"Accepts a UInt32 number - the region ID from the Yandex geobase. Returns an array of region IDs consisting of the passed region and all parents along the chain.
Example: %%regionHierarchy(toUInt32(213)) = [213,1,3,225,10001,10000]%%."}},toUInt64OrZero:{bracket:"(v)",desc:{en:"Functions for converting between numbers, strings (but not fixed strings), dates, and dates with times. All these functions accept one argument. "}},rowNumberInAllBlocks:{bracket:"()",desc:{en:"Returns an incremental row number within all blocks that were processed by this function."}},toDayOfWeek:{bracket:"(v)",desc:{en:"Converts a date or date with time to a UInt8 number containing the number of the day of the week (Monday is 1, and Sunday is 7)."}},bar:{bracket:"(v)",desc:{en:"Allows building a unicode-art diagram.

bar(x, min, max, width) - Draws a band with a width proportional to (x - min) and equal to 'width' characters when x"}},"if":{bracket:"(v)",desc:{en:"The suffix -%%If%% can be appended to the name of any aggregate function. In this case, the aggregate function accepts an extra argument - a condition (Uint8 type). "}},regionToArea:{bracket:"(id[, geobase])",desc:{en:"Converts a region to an area (type 5 in the geobase). In every other way, this function is the same as 'regionToCity'.──────────────────────────────────"}},dictGetUInt16:{bracket:"(v)",desc:{ru:"",en:""}},toUInt8:{bracket:"(v)",desc:{en:"Functions for converting between numbers, strings (but not fixed strings), dates, and dates with times. All these functions accept one argument. "}},toUInt16:{bracket:"(v)",desc:{en:"Functions for converting between numbers, strings (but not fixed strings), dates, and dates with times. All these functions accept one argument. "}},path:{bracket:"(URL)",desc:{en:"- The same thing, but without the protocol and host in the result. The / element (root) is not included."}},extractURLParameters:{bracket:"(URL)",desc:{ru:"Возвращает массив строк вида name=value, соответствующих параметрам URL. Значения никак не декодируются.",en:"- Gets an array of name=value strings corresponding to the URL parameters. The values are not decoded in any way."}},OSHierarchy:{bracket:"(v)",desc:{ru:"Принимает число типа UInt8 - идентификатор операционной системы из словаря Яндекс.Метрики. Возвращает массив с иерархией операционных систем. Аналогично функции regionHierarchy.",en:"Accepts a UInt8 number - the ID of the operating system from the Yandex.Metrica dictionary. Returns an array with a hierarchy of operating systems. Similar to the 'regionHierarchy' function."}},cutQueryStringAndFragment:{bracket:"(v)",desc:{ru:"Удаляет query string и fragment identifier. Знак вопроса и символ решётки тоже удаляются.",en:"Removes the query-string and fragment identifier. The question mark and number sign are also removed."}},timeSlots:{bracket:"(StartTime, Duration)",desc:{ru:"Для интервала времени, начинающегося в StartTime и продолжающегося Duration секунд, возвращает массив моментов времени, состоящий из округлений вниз до получаса точек из этого интервала.
Например, %%timeSlots(toDateTime('2012-01-01 12:20:00'), toUInt32(600)) = [toDateTime('2012-01-01 12:00:00'), toDateTime('2012-01-01 12:30:00')]%%.
Это нужно для поиска хитов, входящих в соответствующий визит.",en:"For a time interval starting at 'StartTime' and continuing for 'Duration' seconds, it returns an array of moments in time, consisting of points from this interval rounded down to the half hour.
For example, %%timeSlots(toDateTime('2012-01-01 12:20:00'), toUInt32(600)) = [toDateTime('2012-01-01 12:00:00'), toDateTime('2012-01-01 12:30:00')]%%.
This is necessary for searching for pageviews in the corresponding session."}},toUInt32:{bracket:"(v)",desc:{en:"Functions for converting between numbers, strings (but not fixed strings), dates, and dates with times. All these functions accept one argument. "}},toStartOfMinute:{bracket:"(v)",desc:{ru:"Округляет дату-с-временем вниз до начала минуты.",en:"Rounds down a date with time to the start of the minute."}},version:{bracket:"()",desc:{ru:"Возвращает версию сервера в виде строки.",en:"Returns server's version as a string."}},toUInt64:{bracket:"(v)",desc:{en:"Functions for converting between numbers, strings (but not fixed strings), dates, and dates with times. All these functions accept one argument. "}},toInt16:{bracket:"(v)",desc:{en:"Functions for converting between numbers, strings (but not fixed strings), dates, and dates with times. All these functions accept one argument. "}},reinterpretAsInt16:{bracket:"(v)",desc:{en:""}},toInt64:{bracket:"(v)",desc:{en:"Functions for converting between numbers, strings (but not fixed strings), dates, and dates with times. All these functions accept one argument. "}},toFixedString:{bracket:"(s, N)",desc:{ru:"Преобразует аргумент типа String в тип FixedString(N) (строку фиксированной длины N). N должно быть константой.
Если строка имеет меньше байт, чем N, то она дополняется нулевыми байтами справа. Если строка имеет больше байт, чем N - кидается исключение.",en:"Converts a String type argument to a FixedString(N) type (a string with fixed length N). N must be a constant. If the string has fewer bytes than N, it is passed with null bytes to the right. If the string has more bytes than N, an exception is thrown."}},toFloat32:{bracket:"(v)",desc:{en:"Functions for converting between numbers, strings (but not fixed strings), dates, and dates with times. All these functions accept one argument. "}},dictGetHierarchy:{bracket:"(v)",desc:{ru:"%%dictGetHierarchy('dict_name', id)%%
- для иерархического словаря dict_name - вернуть массив ключей словаря, начиная с id и продолжая цепочкой родительских элементов. Возвращает Array(UInt64).",en:"%%dictGetHierarchy('dict_name', id)%%
- For the 'dict_name' hierarchical dictionary, returns an array of dictionary keys starting from 'id' and continuing along the chain of parent elements. Returns Array(UInt64)."}},dictGetInt64:{bracket:"(v)",desc:{ru:"",en:""}},CAST:{bracket:"(x, t)",desc:{en:"Casts x to the t data type.
The syntax %%CAST(x AS t)%% is also supported.
"}},toRelativeSecondNum:{bracket:"(v)",desc:{ru:"Переводит дату-с-временем в номер секунды, начиная с некоторого фиксированного момента в прошлом.",en:"Converts a date with time or date to the number of the second, starting from a certain fixed point in the past."}},toUInt8OrZero:{bracket:"(v)",desc:{en:"Functions for converting between numbers, strings (but not fixed strings), dates, and dates with times. All these functions accept one argument. "}},toStartOfMonth:{bracket:"(v)",desc:{ru:"Округляет дату или дату-с-временем вниз до первого дня месяца.
Возвращается дата.",en:"Rounds down a date or date with time to the first day of the month.
Returns the date."}},rand64:{bracket:"(v)",desc:{ru:"Возвращает псевдослучайное число типа UInt64, равномерно распределённое среди всех чисел типа UInt64.
Используется linear congruential generator.",en:"Returns a pseudo-random UInt64 number, evenly distributed among all UInt64-type numbers.
Uses a linear congruential generator."}},toInt8OrZero:{bracket:"(v)",desc:{en:"Functions for converting between numbers, strings (but not fixed strings), dates, and dates with times. All these functions accept one argument. "}},toFloat32OrZero:{bracket:"(v)",desc:{en:"Functions for converting between numbers, strings (but not fixed strings), dates, and dates with times. All these functions accept one argument. "}},toYear:{bracket:"(v)",desc:{ru:"Переводит дату или дату-с-временем в число типа UInt16, содержащее номер года (AD).",en:"Converts a date or date with time to a UInt16 number containing the year number (AD)."}},atan:{bracket:"(x)",desc:{ru:"Арктангенс.",en:"The arc tangent."}},toFloat64OrZero:{bracket:"(v)",desc:{en:"Functions for converting between numbers, strings (but not fixed strings), dates, and dates with times. All these functions accept one argument. "}},arrayEnumerate:{bracket:"(arr, ...)",desc:{en:"Returns an array the same size as the source array, indicating for each element what its position is among elements with the same value.
"}},toDayOfMonth:{bracket:"(v)",desc:{en:"Converts a date or date with time to a UInt8 number containing the number of the day of the month (1-31)."}},dictGetUInt64:{bracket:"(v)",desc:{ru:"",en:""}},IPv4NumToStringClassC:{bracket:"(num)",desc:{en:"Similar to IPv4NumToString, but using %%xxx%% instead of the last octet. "}},reinterpretAsString:{bracket:"(v)",desc:{en:"This function accepts a number or date or date with time, and returns a string containing bytes representing the corresponding value in host order (little endian). Null bytes are dropped from the end. For example, a UInt32 type value of 255 is a string that is one byte long."}},toHour:{bracket:"(v)",desc:{en:"Converts a date with time to a UInt8 number containing the number of the hour in 24-hour time (0-23).
This function assumes that if clocks are moved ahead, it is by one hour and occurs at 2 a.m., and if clocks are moved back, it is by one hour and occurs at 3 a.m. (which is not always true - even in Moscow the clocks were once changed at a different time)."}},ignore:{bracket:"(...)",desc:{en:"A function that accepts any arguments and always returns 0.
However, the argument is still calculated. This can be used for benchmarks."}},arrayJoin:{bracket:"(v)",desc:{en:"This is a very unusual function.

Normal functions don't change a set of rows, but just change the values in each row (map). Aggregate functions compress a set of rows (fold or reduce).
The 'arrayJoin' function takes each row and generates a set of rows (unfold).

T"}},length:{bracket:"(v)",desc:{en:"Returns the length of a string in Unicode code points (not in characters), assuming that the string contains a set of bytes that make up UTF-8 encoded text. If this assumption is not met, it returns some result (it doesn't throw an exception).
The result type is UInt64."}},tuple:{bracket:"(tuple, n), operator x.N",desc:{en:"A function that allows getting columns from a tuple.
'N' is the column index, starting from 1. 'N' must be a constant. 'N' must be a strict postive integer no greater than the size of the tuple.
There is no cost to execute the function."}},extractURLParameterNames:{bracket:"(URL)",desc:{en:"- Gets an array of name=value strings corresponding to the names of URL parameters. The values are not decoded in any way."}},tupleElement:{bracket:"(tuple, n), operator x.N",desc:{en:"A function that allows getting columns from a tuple.
'N' is the column index, starting from 1. 'N' must be a constant. 'N' must be a strict postive integer no greater than the size of the tuple.
There is no cost to execute the function."}},"in":{bracket:"(v)",desc:{en:"What to do when the amount of data exceeds one of the limits: 'throw' or 'break'. By default, throw."}},globalIn:{bracket:"(v)",desc:{en:"See the section "IN operators"."}},isFinite:{bracket:"(x)",desc:{en:"Accepts Float32 and Float64 and returns UInt8 equal to 1 if the argument is not infinite and not a NaN, otherwise 0."}},isNaN:{bracket:"(x)",desc:{en:"Accepts Float32 and Float64 and returns UInt8 equal to 1 if the argument is a NaN, otherwise 0."}},isInfinite:{bracket:"(x)",desc:{en:"Accepts Float32 and Float64 and returns UInt8 equal to 1 if the argument is infinite, otherwise 0.
Note that 0 is returned for a NaN."}},transform:{bracket:"(v)",desc:{en:"Transforms a value according to the explicitly defined mapping of some elements to other ones.
There are two variations of this function:

1. %%transform(x, array_from, array_to, default)%% "}},rand:{bracket:"(v)",desc:{en:"Returns a pseudo-random UInt64 number, evenly distributed among all UInt64-type numbers.
Uses a linear congruential generator."}},reinterpretAsUInt16:{bracket:"(v)",desc:{en:""}},pi:{bracket:"(v)",desc:{en:"Maximum pipeline depth. Corresponds to the number of transformations that each data block goes through during query processing. Counted within the limits of a single server. If the pipeline depth is greater, an exception is thrown. By default, 1000."}},reinterpretAsUInt32:{bracket:"(v)",desc:{en:""}},reinterpretAsUInt64:{bracket:"(v)",desc:{en:""}},reinterpretAsInt8:{bracket:"(v)",desc:{en:""}},upperUTF8:{bracket:"(v)",desc:{en:"Converts a string to uppercase, assuming the string contains a set of bytes that make up a UTF-8 encoded text. It doesn't detect the language. So for Turkish the result might not be exactly correct. "}},reinterpretAsInt32:{bracket:"(v)",desc:{en:""}},reinterpretAsFloat32:{bracket:"(v)",desc:{en:""}},reinterpretAsFloat64:{bracket:"(v)",desc:{en:""}},reinterpretAsDate:{bracket:"(v)",desc:{en:""}},reinterpretAsDateTime:{bracket:"(v)",desc:{en:""}},roundToExp2:{bracket:"(num)",desc:{en:"Accepts a number. If the number is less than one, it returns 0. Otherwise, it rounds the number down to the nearest (whole non-negative) degree of two."}},upper:{bracket:"(v)",desc:{en:"Converts a string to uppercase, assuming the string contains a set of bytes that make up a UTF-8 encoded text. It doesn't detect the language. So for Turkish the result might not be exactly correct."}},positionUTF8:{bracket:"(haystack, needle)",desc:{en:"The same as 'position', but the position is returned in Unicode code points. Works under the assumption that the string contains a set of bytes representing a UTF-8 encoded text. If this assumption is not met, it returns some result (it doesn't throw an exception).
There's also positionCaseInsensitiveUTF8 function."}},roundDuration:{bracket:"(num)",desc:{en:"Accepts a number. If the number is less than one, it returns 0. Otherwise, it rounds the number down to numbers from the set: 1, 10, 30, 60, 120, 180, 240, 300, 600, 1200, 1800, 3600, 7200, 18000, 36000. This function is specific to Yandex.Metrica and used for implementing the report on session length."}},roundAge:{bracket:"(num)",desc:{en:"Accepts a number. If the number is less than 18, it returns 0. Otherwise, it rounds the number down to numbers from the set: 18, 25, 35, 45. This function is specific to Yandex.Metrica and used for implementing the report on user age."}},round:{bracket:"(num)",desc:{en:"Accepts a number. If the number is less than 18, it returns 0. Otherwise, it rounds the number down to numbers from the set: 18, 25, 35, 45. This function is specific to Yandex.Metrica and used for implementing the report on user age."}},floor:{bracket:"(x[, N])",desc:{en:"Returns a rounder number that is less than or equal to 'x'."}},notEmpty:{bracket:"(v)",desc:{en:"Returns 0 for an empty array, or 1 for a non-empty array.
The result type is UInt8.
The function also works for strings."}},lengthUTF8:{bracket:"(v)",desc:{en:"Returns the length of a string in Unicode code points (not in characters), assuming that the string contains a set of bytes that make up UTF-8 encoded text. If this assumption is not met, it returns some result (it doesn't throw an exception).
The result type is UInt64."}},lower:{bracket:"(v)",desc:{en:"Converts a string to lowercase, assuming the string contains a set of bytes that make up a UTF-8 encoded text. It doesn't detect the language. "}},lowerUTF8:{bracket:"(v)",desc:{en:"Converts a string to lowercase, assuming the string contains a set of bytes that make up a UTF-8 encoded text. It doesn't detect the language. "}},reverse:{bracket:"(v)",desc:{en:"Reverses a sequence of Unicode code points, assuming that the string contains a set of bytes representing a UTF-8 text. Otherwise, it does something else (it doesn't throw an exception)."}},URLPathHierarchy:{bracket:"(URL)",desc:{en:"- The same thing, but without the protocol and host in the result. The / element (root) is not included. "}},substringUTF8:{bracket:"(s, offset, length)",desc:{en:"The same as 'substring', but for Unicode code points. Works under the assumption that the string contains a set of bytes representing a UTF-8 encoded text. If this assumption is not met, it returns some result (it doesn't throw an exception)."}},appendTrailingCharIfAbsent:{bracket:"(s, c)",desc:{en:"If the %%s%% string is non-empty and does not contain the %%c%% character at the end, it appends the %%c%% character to the end."}},alphaTokens:{bracket:"(s)",desc:{en:"Selects substrings of consecutive bytes from the range a-z and A-Z.
Returns an array of selected substrings."}},splitByChar:{bracket:"(separator, s)",desc:{en:"Splits a string into substrings, using 'separator' as the separator.
'separator' must be a string constant consisting of exactly one character.
Returns an array of selected substrings"}},arrayStringConcat:{bracket:"(arr[, separator])",desc:{en:"Concatenates strings from the array elements, using 'separator' as the separator.
'separator' is a string constant, an optional parameter. By default it is an empty string.
Returns a string."}},replaceAll:{bracket:"(haystack, pattern, replacement)",desc:{en:"Replaces all occurrences of the 'pattern' substring in 'haystack' with the 'replacement' substring."}},replaceRegexpOne:{bracket:"(haystack, pattern, replacement)",desc:{en:"Replacement using the 'pattern' regular expression. A re2 regular expression. Replaces only the first occurrence, if it exists.
A pattern can be specified as 'replacement'. "}},cbrt:{bracket:"(x)",desc:{en:"Accepts a numeric argument and returns a Float64 number close to the cubic root of the argument."}},match:{bracket:"(pattern)(time, cond1, cond2, ...)",desc:{en:"Pattern matching for event chains.

'pattern' is a string containing a pattern to match. The pattern is similar to a regular expression."}},cutURLParameter:{bracket:"(URL, name)",desc:{en:"Removes the URL parameter named 'name', if present. This function works under the assumption that the parameter name is encoded in the URL exactly the same way as in the passed argument."}},like:{bracket:"(haystack, pattern), haystack NOT LIKE pattern operator",desc:{en:"The same thing as 'like', but negative."}},domain:{bracket:"(v)",desc:{en:"- Selects the part of the domain that includes top-level subdomains up to the "first significant subdomain" (see the explanation above).
For example, cutToFirstSignificantSubdomain('https://news.yandex.com.tr/') = 'yandex.com.tr'."}},domainWithoutWWW:{bracket:"(v)",desc:{en:"- Selects the domain and removes no more than one 'www.' from the beginning of it, if present."}},firstSignificantSubdomain:{bracket:"(v)",desc:{en:"- Selects the part of the domain that includes top-level subdomains up to the "first significant subdomain" (see the explanation above).
For example, cutToFirstSignificantSubdomain('https://news.yandex.com.tr/') = 'yandex.com.tr'."}},queryString:{bracket:"(v)",desc:{en:"Removes the query-string and fragment identifier. The question mark and number sign are also removed."}},queryStringAndFragment:{bracket:"(v)",desc:{en:"Removes the query-string and fragment identifier. The question mark and number sign are also removed."}},extractURLParameter:{bracket:"(URL)",desc:{en:"- Gets an array of name=value strings corresponding to the names of URL parameters. The values are not decoded in any way."}},URLHierarchy:{bracket:"(URL)",desc:{en:"- Gets an array containing the URL trimmed to the %%/%%, %%?%% characters in the path and query-string. Consecutive separator characters are counted as one. The cut is made in the position after all the consecutive separator characters. Example:"}},cutToFirstSignificantSubdomain:{bracket:"(v)",desc:{en:"- Selects the part of the domain that includes top-level subdomains up to the "first significant subdomain" (see the explanation above).
For example, cutToFirstSignificantSubdomain('https://news.yandex.com.tr/') = 'yandex.com.tr'."}},cutWWW:{bracket:"(v)",desc:{en:"Removes no more than one 'www.' from the beginning of the URL's domain, if present."}},cutQueryString:{bracket:"(v)",desc:{en:"Removes the query-string and fragment identifier. The question mark and number sign are also removed."}},cutFragment:{bracket:"(v)",desc:{en:"Removes the fragment identifier. The number sign is also removed."}},visitParamHas:{bracket:"(params, name)", desc:{en:"Checks whether there is a field with the 'name' name."}},visitParamExtractFloat:{bracket:"(params, name)",desc:{en:"The same as for Float64."}},visitParamExtractBool:{bracket:"(params, name)",desc:{en:"Parses a true/false value. The result is UInt8."}},visitParamExtractRaw:{bracket:"(params, name)",desc:{en:"Returns the value of a field, including separators."}},exp:{bracket:"(x)",desc:{en:"Accepts a numeric argument and returns a Float64 number close to 10x."}},exp2:{bracket:"(x)",desc:{en:"Accepts a numeric argument and returns a Float64 number close to 2x."}},exp10:{bracket:"(x)",desc:{en:"Accepts a numeric argument and returns a Float64 number close to 10x."}},tgamma:{bracket:"(x)",desc:{en:"Gamma function."}},log10:{bracket:"(x)",desc:{en:"Accepts a numeric argument and returns a Float64 number close to the decimal logarithm of the argument."}},sqrt:{bracket:"(x)",desc:{en:"Accepts a numeric argument and returns a Float64 number close to the square root of the argument."}},erf:{bracket:"(v)",desc:{en:"What to do when the amount of data exceeds one of the limits: 'throw' or 'break'. By default, throw."}},erfc:{bracket:"(x)",desc:{en:"Accepts a numeric argument and returns a Float64 number close to 1 - erf(x), but without loss of precision for large 'x' values."}},lgamma:{bracket:"(x)",desc:{en:"The logarithm of the gamma function."}},sin:{bracket:"(x)",desc:{en:"Accepts Float32 and Float64 and returns UInt8 equal to 1 if the argument is infinite, otherwise 0.
Note that 0 is returned for a NaN."}},cos:{bracket:"(x)",desc:{ru:"Арккосинус.",en:"The arc cosine."}},tan:{bracket:"(x)",desc:{ru:"Арктангенс.",en:"The arc tangent."}},pow:{bracket:"(x, y)",desc:{ru:"xy.",en:"xy."}}}},/* * Licensed under the Apache License, Version 2.0 Copyright 2017 Igor Strykhar,Ivan Kudinov,SMI2 LLC and other contributors diff --git a/build/scripts/app-dd32b69813.js b/build/scripts/app-dd32b69813.js deleted file mode 100644 index e28647a7..00000000 --- a/build/scripts/app-dd32b69813.js +++ /dev/null @@ -1,79 +0,0 @@ -"use strict";function _toConsumableArray(e){if(Array.isArray(e)){for(var t=0,a=Array(e.length);t

404 not found

Back'),e.put("app/base/addVarsDialog.html",'

Mango (Fruit)

Add var (no space)
TextIntDateCode
CloseAdd
'),e.put("app/base/base.html",'
Open table
'),e.put("app/base/breadcrumbs.html",''),e.put("app/base/header.html",'
Requirements Chrome! SQL Metrics & Processes Settings Help Sign out [{{user}}]
'),e.put("app/base/helpDialogLogin.html",'

Tabix.io Build {{::vars.version}} [{{::vars.buildDate}}]

* Work only in "Google chrome" version up 55

* Clickhouse server version up v1.1.54164

* Not readonly CH user




https://tabix.ioOk
'),e.put("app/base/helpDialogRu.html",'

Tabix.io Build {{::vars.version}} [{{::vars.buildDate}}]

ClickHouse Руководство


Tabix Руководство

Hot keys

⌘ + Enter

Exec current query

⌘ + Shift + Enter

Exec all query

⌘ + Y

Drop current line

⌘ + ⇧ + F

Reformat

⌘ + ⇧ + Plus|Minus

свернуть все/развернуть

⌘ + Right|Left

переключает вкладки

⌘ + ⌥ + Up|Down

Copy lines Up/Down

⌥ + Up|Down

Move lines Up/Down

Ctrl + K

Remove to line end

⌘ + Backspace

Remove to linestart

Ace Editor Default Keyboard Shortcuts

DrawChart

DrawChart

DrawMap

DrawMap

https://tabix.ioOk
'),e.put("app/base/sidebar.html",''),e.put("app/base/sidebarhelper.html",'

{{ hist }}

'),e.put("app/dash/dash.html",' Raised and Accent ButtonKILL

vars.show:{{vars.show}}
vars.show:{{vars.show}}draw-widget
'),e.put("app/dash/edit.html",'
'),e.put("app/login/login.html",'
Requirements Chrome or Chromium engine Browser! Requirements & helpUi Theme{{theme.title}}
'),e.put("app/render/WidgetsList.html",'
'),e.put("app/metrics/dialog.kill.html",'

Kill query

{{ q.elapsed }}

{{ q.query }}

{{ q.bytes_read }}

{{ q.hash }}

Cancel
'),e.put("app/metrics/metrics.html",'Processes
Overview
Metrics
'),e.put("app/metrics/metricschart.html",'

Metrics

{{interval == -1 ? (\'Refresh is disabled\') : interval +\' \'+(\'sec\')}}{{interval}}system.eventsRefreshReset
'),e.put("app/metrics/overview.html",'

Overview

'),e.put("app/metrics/processes.html",'

Processes

{{interval == -1 ? (\'Refresh is disabled\') : interval +\' \'+\'sec\'}}Word wrapLog ModeClusterRefreshResetKILL Query
'),e.put("app/preference/preference.html",'

Preference & settings

{{theme}}{{theme}}Save sessionLive AutocompletionDisable auto-helpDisable hotKey left+rightUse WrapModeShow invisible charsApply
'),e.put("app/sql/PlotlyEditor.tmpl.html",'

PlotLy JavaScript editor ( alpha )

'),e.put("app/sql/renderResult.html",'
{{::tableData.data.progressQuery}}CSV with headersCSV without headersTSV with headersTSV without headersPinnedEdit Plotly chartTable
Draw
'), -e.put("app/sql/showDialogUpload.html",'

Upload CSV to View

'),e.put("app/sql/sql.html",'
{{tab.name + (tab.changed ? \' *\' : \'\')}}
Make snippetAutoFormatExpandCollapseCollapse All
{{tab.buttonTitle}}Run current ⌘ + ⏎Full screenSave{{item.name}}Query log
USE {{::dbb.name}}{{vars.LastStatistics.elapsed| number:2}} sec.| {{vars.LastStatistics.rows_read| number}} rows.| {{vars.LastStatistics.bytes_read|filesize}}
..... {{tab.progress.query}}
'),e.put("app/table/table-container.html",'

{{vars.currentDatabase}} {{vars.currentTable}}

Structure
NameTypeDefault typeValueSizeCompress
{{$index + 1}}{{field[key]}}
Information
1Size{{vars.statistics.size}}
2Size,bytes{{vars.statistics.sizeBytes}}
3First row{{vars.statistics.minDate}}
4Last row{{vars.statistics.maxDate}}

SHOW CREATE TABLE
{{vars.createtable}}
Data
Data From {{vars.offset}} To {{vars.offset + vars.limit}}
No data
'),e.put("app/table/table.html",'
')}]),function(e,t){function a(e,t){var a=t.dbName,n=t.tableName;e.vars={dbName:a,tableName:n}}e.module(t.app.name).controller("TableController",a),a.$inject=["$scope","$stateParams"]}(angular,smi2),function(e,t){function a(t,a,n,r,i,s,o,c){t.tablewidget={},t.vars={columns:{},ugrid:{},sortColumn:!1,isDark:r.isDark(),createtable:{},data:null,grid:null,limit:100,offset:0,statistics:{},loading:!0,isRawStatistics:!1,rawstatistics:"",scrollConfig:{autoHideScrollbar:!1,theme:r.isDark()?"light":"dark",scrollButtons:{enable:!1},scrollInertia:100,advanced:{updateOnContentResize:!0}}},t.initContainer=function(){a.$watch("currentTable",function(e){e&&(t.vars.currentTable=a.currentTable,t.vars.currentDatabase=a.currentDatabase,t.init())})},t.onAfterInit=function(){},t.updateHandTable=function(){c.getInstance("hotTableContain").render()},t.initOnGo=function(){t.$parent.vars&&(o.get("tableSiedenav")&&s("tableSiedenav").close(),t.vars.currentTable=t.$parent.vars.tableName,t.vars.currentDatabase=t.$parent.vars.dbName,t.init())},t.load=function(){console.warn("LOAD DATA! IN TABLES"),t.vars.data=-1,n.query("\n select * from "+t.vars.currentDatabase+"."+t.vars.currentTable+" limit "+t.vars.offset+", "+t.vars.limit+"\n ").then(function(e){var a="ch";t.tablewidget=new WidgetTable(new DataProvider(e,a)),t.vars.loading=!1},function(e){t.vars.loading=!1,console.error("Error "+e)})},t.calcRawSize=function(){t.vars.isRawStatistics=!0,n.query("SELECT any(ignore(*)) FROM "+t.vars.currentDatabase+"."+t.vars.currentTable+" SAMPLE 1 / 10000 ").then(function(e){t.vars.rawstatistics=e.statistics},function(e){t.vars.rawstatistics=e.data})},t.init=function(){t.vars.loading=!0,t.vars.createtable="N/A",n.query("SHOW CREATE TABLE "+t.vars.currentDatabase+"."+t.vars.currentTable).then(function(e){t.vars.createtable=window.sqlFormatter.format(e.data[0].statement)}),n.query("SELECT table, formatReadableSize(sum(bytes)) as size, sum(bytes) as sizeBytes, min(min_date) as minDate, max(max_date) as maxDate FROM system.parts WHERE database = '"+t.vars.currentDatabase+"' AND ( table = '"+t.vars.currentTable+"' OR table = '"+t.vars.currentTable+"_sharded' ) GROUP BY table ").then(function(e){return t.vars.statistics=e&&e.data.length&&e.data[0]||{}}),n.query("SELECT * FROM system.columns WHERE database='"+t.vars.currentDatabase+"' AND table='"+t.vars.currentTable+"'").then(function(a){n.query("describe table "+t.vars.currentDatabase+"."+t.vars.currentTable).then(function(n){_.map(n.data,function(t){var n=_.find(a.data,{name:t.name});return _.merge(t,n),t.size="-",t.ratio="-",!e.isUndefined(t.default_kind)&&e.isUndefined(t.default_type)&&(t.default_type=t.default_kind),t.data_compressed_bytes&&(t.size=numbro(t.data_compressed_bytes).format("0.0 b")+" / "+numbro(t.data_uncompressed_bytes).format("0.0 b"),t.ratio=numbro(parseInt(t.data_uncompressed_bytes)/parseInt(t.data_compressed_bytes)).format("0.0")),t}),t.vars.columns=n,t.vars.sortColumn=!1;var r=0;n.data.forEach(function(e){3>r&&("Date"==e.type&&(t.vars.sortColumn=e.name),"DateTime"==e.type&&(t.vars.sortColumn=e.name)),r+=1}),t.load()})})},t.loadNext=function(){t.vars.loading=!0,t.vars.offset+=t.vars.limit,t.load()},t.loadPrev=function(){t.vars.offset>0&&(t.vars.loading=!0,t.vars.offset-=t.vars.limit,t.load())}}e.module(t.app.name).controller("TableContainerController",a),a.$inject=["$scope","$rootScope","API","ThemeService","$stateParams","$mdSidenav","$mdComponentRegistry","hotRegisterer"]}(angular,smi2),/* - * Licensed under the Apache License, Version 2.0 Copyright 2017 Igor Strykhar,Ivan Kudinov,SMI2 LLC and other contributors - */ -window.global_delimiter=";;",window.aceJSRules={builtinFunctions:[],lang:"en",dictionaries:[],fieldsList:[],tables:[]},function(e,t){function a(t,a,n,r,i,s,o,c,l,d,u,m,h,p,g){var f="sqlHistory2",b="saveTabs",v="sessionData",y=255;t.AceEditorInLoad=!1,t.vars={EditorIsInit:!1,sqlHistory:r.get(f)||[],dictionaries:[],isDictionariesLoad:!1,tabs:[],enableLiveAutocompletion:h.get("liveAutocompletion"),disableAutohelp:h.get("disableAutohelp"),disableHotKeyCmdLeft:h.get("disableHotKeyCmdLeft"),saveTabs:r.get(b)||!0,LastStatistics:!1,delimiters:[{name:";; Double",delimiter:";;"},{name:"; Single",delimiter:";"}],databasesList:[],searchQueryOnServer:"",currentTab:{},selectedTab:0,formats:[{name:"Table",sql:" format JSON",render:"html"},{name:"JSON compact",sql:" format JSONCompact"}],db:null,limitTimes:h.get("limitTimes"),limitRows:h.get("limitRows"),fontSize:h.get("fontSize"),theme:h.get("editorTheme")},t.vars.delimiter=r.get("delimiter")||";;",t.vars.format=t.vars.formats[0],t.vars.themes=["ambiance","eclipse","mono_industrial","tomorrow_night_blue","chaos","github","monokai","tomorrow_night_bright","chrome","idle_fingers","pastel_on_dark","tomorrow_night_eighties","clouds","iplastic","solarized_dark","tomorrow_night","clouds_midnight","katzenmilch","solarized_light","twilight","cobalt","kr_theme","sqlserver","vibrant_ink","crimson_editor","kuroir","terminal","xcode","dawn","merbivore","textmate","dreamweaver","merbivore_soft","tomorrow"],n.onbeforeunload=function(e){if(""!==t.vars.currentTab.sql&&"localhost"!=location.hostname){var a="Do you want to leave this page?";return"undefined"==typeof e&&(e=window.event),e&&(e.returnValue=a),a}};var w=t.$on("$stateChangeStart",function(e){var a="Do you want to leave this page?";e.defaultPrevented||""===t.vars.currentTab||confirm(a)||e.preventDefault()}),k=function(){if(t.vars.saveTabs){var e=t.vars.tabs.map(function(e){return e.editor?e.sql=e.editor.getValue():e.sql="",{name:e.name,sql:e.sql,buttonTitle:e.buttonTitle,format:e.format,delimiter:e.delimiter,results:[],editor:null,selectedResultTab:0}});r.set(v,e),console.info("Save session , localStorageService.set(SQL_SESSION_KEY)")}};t.$watch("$root.isInitDatabaseStructure",function(){t.vars.EditorIsInit=a.isInitDatabaseStructure}),t.InitDatabaseStructure=function(){console.warn(">>>>>>>>>>>>>>>InitDatabaseStructure<<<<<<<",a.isInitDatabaseStructure)},t.executeQuery=function(a,n,r){var s="result_overflow_mode=throw";t.vars.currentTab.loading=!0,t.vars.limitRows&&(s+="&max_result_rows="+t.vars.limitRows),t.vars.limitTimes&&(s+="&timeout_overflow_mode=throw&max_execution_time="+t.vars.limitTimes);var o=a.sql.replace(/(\r\n|\n|\r)$/gm,"").substr(0,130);t.vars.currentTab.progress.query=o;var d="";a.qid&&(d=" /*TABIX_QUERY_ID_"+a.qid+"*/ "),i.fetchQuery(d+a.sql,!0,a.format,s).then(function(i){var s=i;e.isObject(i)||(i={data:s,meta:null,rows:null,statistics:null}),i.error=!1,i.query=a,i.countAllQuery=n.length;var c={time:moment().format("HH:mm:ss")};e.isObject(i.statistics)&&Object.assign(c,i.statistics),c.query=o,_.isArray(t.vars.currentTab.statistics)&&t.vars.currentTab.statistics.push(c),t.vars.LastStatistics=c;var l=new DataProvider(i,"ch");l.progressQuery=o,r.widgets.tables.push(new WidgetTable(l)),"drawCommand"in a&&a.drawCommand.length?(l.countAll=a.drawCommand.length>i.countAllQuery?a.drawCommand.length:i.countAllQuery,console.info("query.drawCommand",a.drawCommand),a.drawCommand.forEach(function(e){r.widgets.draw.push(new WidgetDraw(l,e))})):r.widgets.draw.push(new WidgetDraw(l,!1)),r.data.push(a),t.$applyAsync(),a.index+1-1&&i>-1&&t.vars.currentTab.editor.gotoLine(s,i),console.log("move cursor to",s,i)}var d="ch";console.warn("ERROR",n);var u=new DataProvider(n,d);r.data.push(a),r.widgets.tables.push(new WidgetTable(u)),t.finalizeResult(r)})},t.renderResult=function(t){return t.echarts=!1,t.pivot=!1,t.charts=!1,t.selectedTabIndex=0,"string"==typeof t.error?t.result='
'+t.error+"
":e.isObject(t.data)?(t.result=i.dataToHtml(t),t.createtable=i.dataToCreateTable(t),t.pivot=!0,t.charts=!0):e.isString(t.data)?t.result='
'+t.data+"
":t.result='
'+e.toJson(t.data,!0)+"
",t},t.finalizeResult=function(e){if(t.vars.currentTab.loading=!1,t.vars.currentTab.progress=!1,e.data.find(function(e){return e.keyword&&-1!=["DROP","CREATE","ALTER"].indexOf(e.keyword.toUpperCase())}),t.$applyAsync(),t.vars.currentTab.statistics[0]){var a=DataProvider.convertArrayToDataProvider(t.vars.currentTab.statistics,"statistics");a.sort="time",a.sortOrder="desc",e.widgets.stats.push(new WidgetTable(a,!1))}},t.execute=function(n,s){t.$applyAsync(),console.groupCollapsed("Execute query"),t.vars.LastStatistics=!1,s.sql=s.editor.getValue();var o=s.sql,d=0,m=s.editor,h=[],p=m.getSelectedText();e.isUndefined(s.selectedTabResultIndex)&&(s.selectedTabResultIndex=0);var f={data:[],time:u("date")(new Date,"HH:mm:ss"),pinned:!1,widgets:{tables:[],pivot:[],draw:[],stats:[]}};if(""!==p&&null!==p&&(o=p),console.info("[EDITOR TEXT]> ",o),""===o||null===o)return void c.show(c.simple().content("SQL query is empty").theme(l.theme).position("bottom right"));s.results=[f],k();var b=window.global_delimiter;b||(b=";;"),m.session.$mode.splitByTokens(o,"constant.character.escape",b).forEach(function(t){if(!("current"==n&&d>0)){var s=[],o=t.sql;if(!(o.length<5)){if("current"==n&&!p){var c=m.selection.getCursor();if(!c||e.isUndefined(c))return;var l=t.range.compare(c.row,c.column);if(0!==l)return}var u=o.trim();-1==a.sqlLog.indexOf(u)&&(a.sqlLog.unshift(u),a.sqlLog.length>y&&a.sqlLog.splice(0,y),r.set("sqlLog",a.sqlLog));var f=m.session.$mode.replaceVars(o,g.get());o=f.sql;f.vars;if(console.log("replacedVars",f),m.session.$mode.findTokens(o,"invalid.illegal",!0)){var b=m.session.$mode.splitByTokens(o,"invalid.illegal",!0);o=b[0].sql,b.forEach(function(t){if(e.isDefined(t.keyword)&&t.keyword){var a=/DRAW_(\w+)/gim,n=a.exec(t.keyword);n&&n[1]&&s.push({drawtype:n[1].toLowerCase(),code:t.sql})}})}console.info("[SQL]>",o),s&&console.info("[DRAW]>",s);var v=null,w=!1,k=!1,x=null,C=m.session.$mode.findTokens(o,"storage",!0),S=m.session.$mode.findTokens(o,"keyword",!0);C.hasOwnProperty("value")?(v=!1,k=C.value):(v=" FORMAT JSON ",w=!0),S.hasOwnProperty("value")&&(x=S.value),"select"!==x&&(v=!1,w=!1),h.push({sql:o,index:d,format:v,setedformat:w,keyword:x,storage:k,drawCommand:s,itemRange:t.range,qid:i.makeQueryId()}),d++}}}),console.groupEnd("Execute query"),h.length&&(t.vars.currentTab.progress={},t.vars.currentTab.statistics||(t.vars.currentTab.statistics=[]),t.executeQuery(h[0],h,f))},t.setTheme=function(e){t.vars.theme=e,t.vars.tabs.forEach(function(t){return t.editor.setTheme("ace/theme/"+e)}),r.set("editorTheme",e)},t.reloadCache=function(){console.log("reloadCache"),i.resetDatabaseStructure(),c.show(c.simple().content("Reload page - for reset cache").theme(l.theme).position("bottom right"))},t.selectDatabase=function(e,a){e&&(i.setDatabase(e),t.vars.db!=e&&(t.vars.db=e,t.AceEditorInLoad||(t.aceLoadDatabaseFields(),t.aceApply(!1))))},t.insertWordInEditor=function(e){var a=t.vars.currentTab.editor,n=a.getCursorPosition();n.column+=e.length,a.clearSelection(),a.insert(e),t.vars.currentTab.sql=a.getValue(),d(function(){a.focus(),a.moveCursorToPosition(n)})},t.aceLoadDatabaseFields=function(){var e=t.vars.db;window.aceJSRules.fieldsList=[],i.databaseStructure(function(t){window.aceJSRules.fieldsList=t.getAllFieldsInDatabase(e)})},t.aceLoadDatabaseStructure=function(){var e=t.vars.db;window.aceJSRules.tables=[],i.databaseStructure(function(a){t.vars.databasesList=a.getDatabases(),Object.keys(a.getUniqueDatabaseTables()).forEach(function(e){window.aceJSRules.tables.push(e)}),window.aceJSRules.fieldsList=a.getAllFieldsInDatabase(e)})},t.loadInAce=function(e){e.session.setMode({path:"ace/mode/clickhouse"});for(var t in window.aceJSRules.builtinFunctions){var a=window.aceJSRules.builtinFunctions[t];e.session.$mode.$highlightRules.addCompletionsFunctions(a)}e.session.$mode.$highlightRules.addArrayCompletions(window.aceJSRules.tables,"[table]","table");for(var n in window.aceJSRules.dictionaries){var r=window.aceJSRules.dictionaries[n];e.session.$mode.$highlightRules.addCompletionsDictionaries(r)}for(var i in window.aceJSRules.fieldsList){var s=window.aceJSRules.fieldsList[i];e.session.$mode.$highlightRules.addCompletionsTableFiled(s)}var o=g.getCompletions(),c=p.getCompletions();e.session.$mode.$highlightRules.addArrayCompletions(o,"[var]","var"),e.session.$mode.$highlightRules.addArrayCompletions(c,"[snippet]","snippet"),e.session.bgTokenizer.start(0)},t.aceApply=function(e){e?(console.log(""),t.loadInAce(e)):t.vars.tabs.forEach(function(e){e.editor&&(console.log(""),t.loadInAce(e.editor))}),a.$watch("currentDatabase",t.selectDatabase)},t.changeRootSelectDatabase=function(e){a.currentDatabase!=e&&(a.currentDatabase=e)},t.aceLoadDictionaries=function(){t.vars.isDictionariesLoad||(window.aceJSRules.dictionaries=[],t.vars.dictionaries=[],window.aceJSRules.builtinFunctions=[],t.vars.isDictionariesLoad=!0,i.databaseStructure(function(e){e.getFunctions().forEach(function(e){if(window.aceJSRules.builtinFunctions.push({name:e.name,isaggr:e.is_aggregate,score:101,comb:!1,origin:e.name}),e.is_aggregate){var t={name:e.name+"If",isaggr:e.is_aggregate,score:3,comb:"If",origin:e.name};window.aceJSRules.builtinFunctions.push(t),t={name:e.name+"Array",isaggr:e.is_aggregate,score:2,comb:"Array",origin:e.name},window.aceJSRules.builtinFunctions.push(t),t={name:e.name+"State",isaggr:e.is_aggregate,score:1,comb:"State",origin:e.name},window.aceJSRules.builtinFunctions.push(t)}}),e.getDictionaries().forEach(function(e){var a=e.name;a=a.replace(/^.*\./gm,""),"news"!=a&&(a=a.replace(/s$/gm,"")),a=a?a.toLowerCase()+"_id":"ID";var n="dictGet"+e["attribute.types"]+"('"+e.name+"','"+e["attribute.names"]+"',to"+e.key+"( "+a+" ) ) AS "+e["attribute.names"]+",";window.aceJSRules.dictionaries.push({dic:n,title:"dic_"+e.name+"."+e["attribute.names"]}),t.vars.dictionaries.push({dic:n,title:e.name+"."+e["attribute.names"]+" as "+e["attribute.types"]})})}))};for(var x=function(e){t.vars.tabs.length>=e&&(t.vars.currentTab=t.vars.tabs[e],t.vars.selectedTab=e,d(function(){t.vars.currentTab.editor.focus()}))},C=function(){t.vars.selectedTab>0&&x(t.vars.selectedTab-1)},S=function(){t.vars.selectedTabD;D++)A(D);m.add({combo:t.vars.disableHotKeyCmdLeft?"ctrl+shift+alt+right":"ctrl+right",callback:S}),m.add({combo:t.vars.disableHotKeyCmdLeft?"ctrl+shift+alt+left":"ctrl+left",callback:C}),m.add({combo:"ctrl+shift+f",callback:T}),t.aceLoaded=function(e){t.AceEditorInLoad=!0,a.currentDatabase&&t.selectDatabase(a.currentDatabase),t.aceLoadDictionaries(),t.aceLoadDatabaseStructure(),t.aceLoadDatabaseFields();var n=t.vars.tabs.find(function(e){return!e.editor})||t.vars.currentTab;n.editor=e,e.$blockScrolling=1/0,e.setOptions({fontSize:t.vars.fontSize+"px",enableBasicAutocompletion:!0,behavioursEnabled:!0,wrapBehavioursEnabled:!0,highlightSelectedWord:!0,showGutter:!0,enableLiveAutocompletion:t.vars.enableLiveAutocompletion,liveAutocompletionDelay:500,liveAutocompletionThreshold:1}),e.setTheme("ace/theme/"+t.vars.theme),e.session.setUseWrapMode(h.get("useWrapMode")),e.commands.addCommand({name:"runCurrentCommand",bindKey:{win:"Ctrl-Enter",mac:"Command-Enter"},exec:function(){t.execute("current",n)}}),e.commands.addCommand({name:"removeLiness",bindKey:{win:"Ctrl-Y",mac:"Cmd-Y"},exec:function(e){e.removeLines()}}),e.commands.addCommand({name:"collapseAll",bindKey:{win:"Ctrl-Shift--",mac:"Command+Shift+-"},exec:function(e){e.session.$mode.collapseAll(e.session)}}),e.commands.addCommand({name:"unfold",bindKey:{win:"Ctrl-Shift-+",mac:"Command+Shift+="},exec:function(e){e.session.unfold()}}),e.commands.addCommand({name:"runAllCommand",bindKey:{win:"Shift-Ctrl-Enter",mac:"Shift-Command-Enter"},exec:function(){t.execute("all",n)}});for(var r=function(t){e.commands.addCommand({name:"selecttab"+t,bindKey:{win:"Ctrl-Shift-"+(t+1),mac:"Command-Shift-"+(t+1)},exec:function(){return x(t)}})},i=0;9>i;i++)r(i);e.commands.addCommand({name:"selectnexttab",bindKey:{win:t.vars.disableHotKeyCmdLeft?"Shift-Alt-Ctrl-Right":"Ctrl-Right",mac:t.vars.disableHotKeyCmdLeft?"Shift-Alt-Command-Right":"Command-Right"},exec:S}),e.commands.addCommand({name:"selectprevtab",bindKey:{win:t.vars.disableHotKeyCmdLeft?"Shift-Alt-Ctrl-Left":"Ctrl-Left",mac:t.vars.disableHotKeyCmdLeft?"Shift-Alt-Command-Left":"Command-Left"},exec:C}),e.commands.addCommand({name:"formatcode",bindKey:{win:"Ctrl-Shift-F",mac:"Command-Shift-F"},exec:T}),e.setValue(n.sql),e.clearSelection(),e.focus(),e.selection.moveTo(0,0),e.on("changeSelection",function(){d(function(){n.buttonTitle=""!==e.getSelectedText()?"Run selected ⌘ + ⏎":"Run all ⇧ + ⌘ + ⏎",n.originalSql&&(n.changed=n.originalSql!=n.sql)})}),t.AceEditorInLoad=!1,t.aceApply(e)},t.save=function(e,a){return o.show(o.prompt().title("Save SQL as?").placeholder("Title").initialValue(e.name).targetEvent(a).ok("Save").cancel("")).then(function(a){var n=t.vars.sqlHistory.findIndex(function(t){return t.name==e.name});-1!=n?(t.vars.sqlHistory[n].sql=e.sql,t.vars.sqlHistory[n].name=a):t.vars.sqlHistory.push({sql:e.sql,name:a}),e.originalSql=e.sql,e.name=a,r.set(f,t.vars.sqlHistory),k()})},t.load=function(e){t.vars.currentTab.sql=e.sql,t.vars.currentTab.originalSql=e.sql,t.vars.currentTab.name=e.name,t.vars.currentTab.editor.setValue(e.sql),t.aceApply(t.vars.currentTab.editor)},t.getExportData=function(t){return t.data.data.map(function(t){return Object.keys(t).map(function(a){return e.isArray(t[a])?t[a].join(", "):t[a]})})},t.getExportHeaders=function(e){return e.data.meta.map(function(e){return e.name})},t.addTab=function(){t.vars.currentTab={name:"new SQL",sql:"",buttonTitle:"Run ⌘ + ⏎",format:{},editor:null,results:[],selectedResultTab:0},t.vars.tabs.push(t.vars.currentTab),k()},t.changeTab=function(e){k(),t.vars.currentTab=e},t.removeTab=function(e,a){a.stopPropagation();var n=function(){t.vars.tabs.splice(t.vars.tabs.indexOf(e),1),t.vars.tabs.length==t.vars.selectedTab&&t.vars.selectedTab--};e.changed?o.show(o.confirm().title("SQL was changed. Save it before exit?").targetEvent(a).ok("Yes").cancel("No")).then(function(){var a=t.vars.sqlHistory.findIndex(function(t){return t.name==e.name});-1!=a&&(t.vars.sqlHistory[a].sql=e.sql,t.vars.sqlHistory[a].name=e.name),r.set(f,t.vars.sqlHistory),n()},n):n()},t.removeResult=function(e,t,a){},a.$on("handleBroadcastUpdateVarsAndSnippets",function(e,a){t.aceApply()}),a.$on("handleBroadcastInsertInActive",function(e,a){a.value&&t.insertWordInEditor(" "+a.value+" ")}),t.toggleSidenav=function(e){s(e).toggle()},t.removeHistory=function(e,a){a.preventDefault();var n=t.vars.sqlHistory.indexOf(e);-1!=n&&o.show(o.confirm().title("Delete "+e.name+"?").targetEvent(a).ok("Yes").cancel("No")).then(function(){t.vars.sqlHistory.splice(n,1),r.set(f,t.vars.sqlHistory)})},t.setSql=function(e){t.vars.currentTab.sql=e,t.toggleSidenav("log"),t.vars.currentTab.editor.setValue(e),d(function(){return t.vars.currentTab.editor.focus()},500)},t.changeTabName=function(e,a){a.stopPropagation(),o.show(o.prompt().title("Title tab").placeholder("title").initialValue(e.name).targetEvent(a).ok("Apply").cancel("Cancel")).then(function(a){var n=t.vars.sqlHistory.findIndex(function(t){return t.name==e.name});-1!=n&&(e.originalSql=e.sql,t.vars.sqlHistory[n].name=a,r.set(f,t.vars.sqlHistory)),e.name=a,k()})},t.vars.saveTabs?(t.vars.tabs=r.get(v),_.isArray(t.vars.tabs)||(t.vars.tabs=[]),t.vars.tabs.length>0?d(function(){return t.vars.currentTab=t.vars.tabs[0]},500):t.addTab()):(r.set(v,[]),t.addTab()),t.$on("$destroy",function(){i.setDatabase(a.currentDatabase),w(),n.onbeforeunload=null}),t.rightAceMenuList=[],t.showDialogUpload=function(t,a){function n(e,t){e.vars={UploadCsv:{content:null,header:!0,headerVisible:!0,separator:",",separatorVisible:!0,result:null,encoding:"ISO-8859-1",encodingVisible:!0,uploadButtonLabel:"Upload",callback:function(e){t.hide()}}},e.$watch("vars.UploadCsv.result",function(e){e&&t.hide(e)}),e.hide=function(){t.hide()},e.cancel=function(){t.cancel()}}n.$inject=["$scope","$mdDialog"],o.show({controller:n,templateUrl:"app/sql/showDialogUpload.html",parent:e.element(document.body),targetEvent:a,clickOutsideToClose:!0}).then(function(e){if(e&&t&&t.tables){var a=DataProvider.convertArrayToDataProvider(e,"csv");t.tables.push(new WidgetTable(a))}},function(){})},t.rightMenuProcess=function(e){var a=t.vars.currentTab.editor.session;if(t.vars.currentTab.editor.resize(),"Snippet"==e){var n=t.vars.currentTab.editor.getSelectedText();n&&(p.add(n),t.aceApply())}else"AutoFormat"==e?T():"Expand"==e?a.unfold():"Collapse All"==e?a.$mode.collapseAll(a):"Collapse"==e&&a.foldAll();t.vars.currentTab.editor.focus()}}e.module(t.app.name).controller("SqlController",a),a.$inject=["$scope","$rootScope","$window","localStorageService","API","$mdSidenav","$mdDialog","$mdToast","ThemeService","$timeout","$filter","hotkeys","Preference","Snippets","Variables"]}(angular,smi2),/* - * Licensed under the Apache License, Version 2.0 Copyright 2017 Igor Strykhar,SMI2 LLC and other contributors - */ -function(e,t,a){function n(t,a,n,r,i,s,o,c,l,d){function u(e,t){e.editor=!1,e.hide=function(){t.hide()},e.cancel=function(){t.cancel()},e.applyCode=function(){console.log("applyCODE")},e.aceLoadedEditor=function(t){e.editor=t,console.warn("aceLoadedEditor"),t.$blockScrolling=1/0,t.session.setUseWrapMode(!0),t.setOptions({fontSize:"14px",enableBasicAutocompletion:!0,behavioursEnabled:!0,wrapBehavioursEnabled:!0,highlightSelectedWord:!0,showGutter:!0,enableLiveAutocompletion:!0,liveAutocompletionDelay:500,liveAutocompletionThreshold:1}),t.commands.addCommand({name:"runCurrentCommand",bindKey:{win:"Ctrl-Enter",mac:"Command-Enter"},exec:function(){e.applyCode()}}),t.setTheme("ace/theme/cobalt"),t.setValue("{}"),t.clearSelection(),t.focus(),t.selection.moveTo(0,0),t.session.setMode({path:"ace/mode/javascript"})}}u.$inject=["$scope","$mdDialog"],t.tabsRender=!0,t.vars={rsw:0,uiTheme:l.themeObject,isChartReady:!1,staticGrid:!0,stackType:"false",isDark:l.isDark(),active:{table:!1,pivot:!1,draw:!1}},t.staticGrid=!0,t.gridStackOptions={cellHeight:200,verticalMargin:3,disableDrag:!0},t.switchStaticGrid=function(){t.vars.staticGrid=!t.vars.staticGrid,t.staticGrid=t.vars.staticGrid,console.info("staticGrid",t.staticGrid)},t.initNoTabs=function(){t.vars.active.table=!0,t.vars.active.draw=!0,t.vars.active.pivot=!0},t.initTableTab=function(){console.warn("initTableTab!!!!"),t.vars.active.table=!0},t.initDrawTab=function(){t.vars.active.draw=!0},t.onResizeStop=function(){},t.openEditor=function(a){o.show({controller:u,templateUrl:"app/sql/PlotlyEditor.tmpl.html",parent:e.element(document.body),locals:{w:a}}).then(function(e){t.status='You said the information was "'+e+'".'},function(){t.status="You cancelled the dialog."})},t.openEditorPlotLy=function(e){console.log("openEditorPlotLy",e),t.openEditor(e)},t.initPivotTab=function(){t.vars.active.pivot=!0}}e.module(t.app.name).controller("RenderCtrl",n),n.$inject=["$scope","$rootScope","$window","localStorageService","API","$mdSidenav","$mdDialog","$mdToast","ThemeService","$timeout"]}(angular,smi2,window.$),/* - * Licensed under the Apache License, Version 2.0 Copyright 2017 Igor Strykhar, SMI2 LLC and other contributors - */ -function(e,t){function a(e){var t=this,a={date:"calendar",text:"message-text-outline","int":"numeric",code:"cow"};this.vars={},this.getIcon=function(e){return a[e]},this.constructor=function(){var a=e.get("UserVariables");_.isObject(a)||(a={});for(var n in a){var r=a[n];t.vars[n]={id:n,name:r.name,title:r.name,value:r.value,typeEdit:"text",type:r.type,icon:t.getIcon(r.type)}}},this.constructor(),this.drop=function(e){delete t.vars[e]},this.update=function(e){console.info("Update value",e),t.apply()},this.getCompletions=function(){var e=[];for(var a in t.vars){var n=t.vars[a];e.push("$"+n.name)}return e},this.get=function(){return t.vars},this.addVar=function(e,a,n){var r=a;t.vars[r]={id:r,name:a,title:a,value:n,typeEdit:"text",type:e,icon:t.getIcon(e)},t.apply()},this.apply=function(){var a={};_.forEach(t.vars,function(e,t){var n={id:e.id,name:e.title,type:e.type,value:e.value};a[e.id]=n}),e.set("UserVariables",a)}}e.module(t.app.name).service("Variables",a),a.$inject=["localStorageService"]}(angular,smi2),function(e,t){function a(t,a){var n=t.get("themeName")||"dark",r=[{isDark:!1,name:"light",title:"Light theme"},{isDark:!0,name:"dark",title:"Dark theme"}],i=r.find(function(e){return e.name==n})||r[1];return i.isDark&&e.element("body").addClass("dark"),this.isDark=function(){return i.isDark},this.get=function(){return i},{isDark:function(){return i.isDark},list:r,set:function(e){console.warn(e,n),e!=n&&(console.log("localStorageService.set('themeName', ",e),t.set("themeName",e),a.reload(),window.location.reload())},get:function(){},theme:i.name,themeObject:i}}e.module(t.app.name).service("ThemeService",a),a.$inject=["localStorageService","$state"]}(angular,smi2),/* - * Licensed under the Apache License, Version 2.0 Copyright 2017 Igor Strykhar/SMI2 LLC and other contributors - */ -function(e,t){function a(e){var t=this;this.snippets={},this.constructor=function(){var a=e.get("UserSnippets");_.isObject(a)||(a={});for(var n in a){var r=a[n];t.snippets[n]={id:n,code:r.code,dt:r.dt}}console.log("UserSnippets",t.snippets)},this.constructor(),this.getCompletions=function(){var e=[];for(var a in t.snippets){var n=t.snippets[a];e.push(n.code)}return e},this.getSnippets=function(){return t.snippets},this.drop=function(e){delete t.snippets[e]},this.update=function(e){console.info("Update value",e),t.apply()},this.hashCode=function(e){return e.split("").reduce(function(e,t){return e=(e<<5)-e+t.charCodeAt(0),e&e},0)},this.add=function(e){e=e.trim();var a="SQL_"+Math.abs(t.hashCode(e));console.log("UserSnippets",e,a),t.snippets[a]={id:a,code:e,dt:Date.now()},t.apply()},this.apply=function(){var a={};_.forEach(t.snippets,function(e,t){var n={id:e.id,code:e.code,dt:e.dt};a[e.id]=n}),e.set("UserSnippets",a)}}e.module(t.app.name).service("Snippets",a),a.$inject=["localStorageService"]}(angular,smi2),/* - * Licensed under the Apache License, Version 2.0 Copyright 2017 Igor Strykhar,Ivan Kudinov,SMI2 LLC and other contributors - */ -function(e,t){function a(e,t){var a=this,n={limitRows:5e3,limitTimes:5,fontSize:14,editorTheme:"cobalt",theme:"dark",saveTabs:!0,liveAutocompletion:!0,disableAutohelp:!1,disableHotKeyCmdLeft:!0,delimiter:";;",liveAutocompletionDelay:500,liveAutocompletionThreshold:1,useWrapMode:!0,showInvisibles:!1},r=["ligth","dark"],i=["ambiance","eclipse","mono_industrial","tomorrow_night_blue","chaos","github","monokai","tomorrow_night_bright","chrome","idle_fingers","pastel_on_dark","tomorrow_night_eighties","clouds","iplastic","solarized_dark","tomorrow_night","clouds_midnight","katzenmilch","solarized_light","twilight","cobalt","kr_theme","sqlserver","vibrant_ink","crimson_editor","kuroir","terminal","xcode","dawn","merbivore","textmate","dreamweaver","merbivore_soft","tomorrow","dracula"];this.current={},this.constructor=function(){var t=e.get("UserPreference");a.current=_.merge(n,t)},this.constructor(),this.getThemes=function(){return r},this.getEditorThemes=function(){return i},this.apply=function(e){_.forEach(e,function(e,t){a.set(t,e)}),a.save()},this.save=function(){console.log("localStorageService,set",a.current),e.set("UserPreference",a.current)},this.getCurrentState=function(){return a.current},this.get=function(e){return n[e]},this.set=function(e,t){("limitRows"==e||"limitTimes"==e||"fontSize"==e||"liveAutocompletionDelay"==e||"liveAutocompletionThreshold"==e)&&(t=parseInt(t)),a.current[e]=t}}e.module(t.app.name).service("Preference",a),a.$inject=["localStorageService","ThemeService"]}(angular,smi2),function(e,t){function a(e,t){return{responseError:function(a){return 401==a.status&&t.get("$state").go("login"),e.reject(a)}}}e.module(t.app.name).service("HttpInterceptor",a),a.$inject=["$q","$injector"]}(angular,smi2),/* - * Licensed under the Apache License, Version 2.0 Copyright 2017 Igor Strykhar,Ivan Kudinov,SMI2 LLC and other contributors - */ -function(e,t){function a(t,a,n,r,i){var s=this,o="currentBaseConfig",c=new DatabaseStructure,l=null,d={},u=n.get(o);u&&u.host&&(d=u),this.setConnection=function(t){n.set(o,t),d=e.copy(t)},this.clear=function(){l=null,d={},n.set(o,{}),c=new DatabaseStructure},this.hashCode=function(e){return e.split("").reduce(function(e,t){return e=(e<<5)-e+t.charCodeAt(0),e&e},0)},this.DS_CacheKey=function(){var e="_databaseStructure:"+JSON.stringify(d);return e=s.hashCode(e)},this.DS_storeCache=function(e,t,a,r,i){var o={columns:e,tables:t,databases:a,dictionaries:r,functions:i,ttl:Date.now()};return n.set(s.DS_CacheKey(),o)},this.DS_fetchFromCache=function(){var e=n.get(s.DS_CacheKey());if(!e||!e.ttl)return!1;var t=(Date.now()-e.ttl)/36e5;return t>1.5?!1:e&&e.functions&&e.functions.length>1?(c.init(e.columns,e.tables,e.databases,e.dictionaries,e.functions),!0):!1},this.memory=function(e){},this.resetDatabaseStructure=function(){console.log("reset databaseStructure"),n.set("_databaseStructure:"+s.getHost()+":"+s.getLogin(),[])},this.databaseStructure=function(e,t){return!t&&c.isInit()?e(c):!t&&s.DS_fetchFromCache()&&c.isInit()?(console.info("restore from cache : database Structure!"),e(c)):(t&&(c=new DatabaseStructure),console.time("Load Database Structure!"),void s.fetchQuery("SELECT * FROM system.columns").then(function(t){s.fetchQuery("SELECT database,name,engine FROM system.tables").then(function(a){s.fetchQuery("SELECT name FROM system.databases").then(function(n){s.fetchQuery("SELECT name,key,attribute.names,attribute.types from system.dictionaries ARRAY JOIN attribute ORDER BY name,attribute.names",null).then(function(r){s.fetchQuery("SELECT name,is_aggregate from system.functions",null).then(function(i){return console.timeEnd("Load Database Structure!"),s.DS_storeCache(t.data,a.data,n.data,r.data,i.data),c.init(t.data,a.data,n.data,r.data,i.data),e(c)},function(e){throw e})},function(e){throw e})},function(e){throw e})},function(e){throw e})},function(e){throw e}))},this.getHost=function(){return d.host},this.getPassword=function(){return d.password},this.getLogin=function(){return d.login},this.makeQueryId=function(){for(var e="",t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",a=0;8>a;a++)e+=t.charAt(Math.floor(Math.random()*t.length));return e},this.isTabixServer=function(){return d.tabix&&d.tabix.server?!0:!1},this.tabixQuery=function(e){return console.info("[request]>",e),t(req).then(function(e){return defer.resolve(e.data)},function(e){return defer.reject(e)}),defer.promise},this._tabixRequest=function(t,a){var n={version:1,auth:{login:d.tabix.login,password:d.tabix.password,confid:d.tabix.confid}};t=Object.assign(n,t);var r=d.tabix.server+"/"+a;return{method:"POST",data:t,url:r,transformResponse:function(t,a,n){try{return JSON.parse(t)}catch(r){return t?t:"\nStatus:"+n+"\nHeaders:"+e.toJson(a())}}}},this.makeSqlQuery=function(e,t){var a="";return t!==!1?(t=t||" FoRmAt JSON","null"==t&&(t=""),a=e+"\n\n"+t):a=e,a},this.makeUrlRequest=function(e,t){var a="",n="";d.host.indexOf("://")>0||0==d.host.indexOf("/")||(n="http://"),a=n+d.host,a+="/?",d.rouser||(a+="add_http_cors_header=1&log_queries=1&output_format_json_quote_64bit_integers=1",d.NotCH1_1_54276||(a+="&output_format_json_quote_denormals=1"));return d.baseauth||(a+=d.password?"&user="+encodeURIComponent(d.login)+"&password="+encodeURIComponent(d.password):"&user="+encodeURIComponent(d.login)),e&&(a+="&database="+encodeURIComponent(l)),t&&(a+="&"+t),d.params&&(a+="&"+d.params),a},this.fetchQuery=function(e,t,a,n){var r=s.makeSqlQuery(e,a),i=s.makeUrlRequest(t,n),o={mode:"cors",method:"post",headers:{"Content-type":"application/x-www-form-urlencoded; charset=UTF-8"},body:r},c=new Request(i,o);return fetch(c).then(function(e){var t=e.headers.get("content-type");return t.includes("text/plain")&&200==e.status&&"ok"==e.statusText.toLowerCase()?"OK":t&&t.includes("application/json")&&e.status>=200&&e.status<300?Promise.resolve(e):e.text().then(Promise.reject.bind(Promise))}).then(function(e){return"OK"===e?"OK":e.json()},function(e){return Promise.reject(e)})},this.query=function(e,n,r,i){var o=a.defer(),c=s.makeSqlQuery(e,n),l=s.makeUrlRequest(r,i),u=!1;return s.isTabixServer()?u=s._tabixRequest({query:c},"query"):(u={method:"POST",data:c,headers:{"Content-Type":"application/x-www-form-urlencoded"},url:l,cache:!1},d.baseauth&&(u.headers.Authorization="Basic "+window.btoa(d.login+":"+d.password))),console.info("SQL>",l,c,u),t(u).then(function(e){return o.resolve(e.data)},function(e){return o.reject(e)}),o.promise},this.getConnectionInfo=function(){return d},this.setDatabase=function(e){return l=e},this.getDatabase=function(){return l},this.dataToCreateTable=function(e){var t="\nCREATE TABLE x (\n",a=[];return e.meta.forEach(function(e){return a.push(" "+e.name+" "+e.type)}),t+a.join(",\n")+"\n ) ENGINE = Log \n;;\n"},this.dataToHtml=function(e){var t='',a=[];return e.meta.forEach(function(e){t+="",a.push(e.name)}),e.data.forEach(function(e){t+="",a.forEach(function(a){t+=""}),t+=""}),t+="
"+r(e.name)+'\n
'+r(e.type)+"
\n
"+r(e[a])+"
"},this.dataToHandsontable=function(e){var t=[],a=[];return e.meta.forEach(function(e){t.push(e.name);var n={};switch(n.type="text",n.width=100,e.type){case"Date":n.width=90,n.type="date",n.dateFormat="MM/DD/YYYY";break;case"DateTime":n.width=150,n.type="time",n.timeFormat="HH:mm:ss";break;case"Int32":n.width=80,n.type="numeric";break;case"Float64":n.width=80,n.type="numeric",n.format="0,0.0000";break;case"UInt32":n.width=80,n.type="numeric";break;case"String":n.width=180}n.data=e.name,a.push(n)}),{colHeaders:t,columns:a,data:e.data,currentRowClassName:"currentRow",currentColClassName:"currentCol"}}}e.module(t.app.name).service("API",a),a.$inject=["$http","$q","localStorageService","$sanitize","ThemeService"]}(angular,smi2);var DatabaseStructure=function(){function e(){_classCallCheck(this,e),this._init=!1,this.uciq_fields=[],this.all_fields=[],this.all_db_fields=[],this.uciq_dbtables=[]}return _createClass(e,[{key:"init",value:function(e,t,a,n,r){var i=this;console.log("Try init DS...."),this._init||(this.columns=e,this.tables=t,this.databases=a,this.functions=r,this.dictionaries=n,this.columns.forEach(function(e){!angular.isUndefined(e.default_kind)&&angular.isUndefined(e.default_type)&&(e.default_type=e.default_kind),i.all_fields[e.database+"."+e.table]||(i.all_fields[e.database+"."+e.table]=[]),i.all_db_fields[e.database]||(i.all_db_fields[e.database]=[]),i.all_db_fields[e.database][e.table]||(i.all_db_fields[e.database][e.table]=[]),i.all_db_fields[e.database][e.table].push(e),i.all_fields[e.database+"."+e.table].push({name:e.name,type:e.type,active:!0}),i.uciq_fields[e.database]||(i.uciq_fields[e.database]=[]),i.uciq_fields[e.database].push(e),i.uciq_dbtables[e.database+"."+e.table]=1}),this._init=!0)}},{key:"isInit",value:function(){return this._init&&this.functions&&this.functions.length>1}},{key:"getTables",value:function(){return this.tables}},{key:"getDatabases",value:function(){return this.databases}},{key:"getFieldsByDatabase",value:function(e){return this.all_db_fields[e]}},{key:"getFunctions",value:function(){return this.functions}},{key:"getFields",value:function(){return this.all_fields}},{key:"getUniqueDatabaseTables",value:function(){return this.uciq_dbtables}},{key:"getAllFieldsInDatabase",value:function(e){return this.uciq_fields[e]}},{key:"getDictionaries",value:function(){return this.dictionaries}},{key:"getColumns",value:function(){return this.columns}}]),e}();/* - * Copyright (C) 2017 IgorStrykhar in SMI2 - * All rights reserved. - */ -!function(e,t,a){function n(e,t,a){e.vars={AceThemes:t.getEditorThemes(),Themes:t.getThemes()},e.state=t.getCurrentState(),e.apply=function(){t.apply(e.state),e.state=t.getCurrentState(),a.go("sql")},e.reloadCache=function(){}}e.module(t.app.name).controller("PreferenceController",n),n.$inject=["$scope","Preference","$state"]}(angular,smi2,window.$),function(e,t){function a(t,a,n,r,i,s,o){var c="proc.interval",l="proc.key";t.vars={queryesToKill:{},clusterMode:!0,logMode:!0,loading:!1,logData:{},cols:[],isClusterLoad:!1,clusterList:!1,isDark:n.isDark(),sort:/^[a-z0-9_]+$/.test(i.get(l))?i.get(l):null,interval:i.get(c)||-1,scrollConfig:{autoHideScrollbar:!1,theme:n.isDark()?"light":"dark",scrollButtons:{enable:!1},scrollInertia:100,advanced:{updateOnContentResize:!0}}},t.updateHandTable=function(){o.getInstance("hotTableProcesses").render()},t.table={wordWrap:!1,data:{},settings:{observeChanges:!1,manualColumnMove:!0,manualColumnResize:!0,autoWrapRow:!0,rowHeaders:!0,colWidths:70,dropdownMenu:!0,stretchH:"all",fillHandle:!1,preventOverflow:"horizontal",columnSorting:!0,sortIndicator:!0,manualRowResize:!0,viewportColumnRenderingOffset:"auto",autoColumnSize:{samplingRatio:23}}};var d=null;t.initClusterConfig=function(){var e="SELECT host_address,port FROM system.clusters GROUP BY host_address,port LIMIT 10";t.vars.clusterList=[],a.fetchQuery(e).then(function(e){e.data.forEach(function(e){t.vars.clusterList.push(e.host_address+":"+e.port)}),t.vars.isClusterLoad=!0,console.log("Cluster nodes list",t.vars.clusterList.join(","))},function(e){t.vars.isClusterLoad=!0,console.error("Error "+e)})},t.flush=function(){t.vars.logData={},t.table.data=[]},t.load=function(){var e="SELECT now() as dt, query, 1 as count, formatReadableSize(read_bytes) as bytes_read, \n formatReadableSize(written_bytes) as written_bytes, formatReadableSize(memory_usage) as memory_usage,\n read_rows,written_rows, round(elapsed,4) as elapsed , * , cityHash64(query) as hash, hostName()";t.vars.isClusterLoad&&t.vars.clusterList&&t.vars.clusterMode?e=e+" FROM remote('"+t.vars.clusterList.join(",")+"',system.processes, '"+a.getLogin()+"','"+a.getPassword()+"') ":e+=" FROM system.processes ",t.vars.logMode&&(e+=" /* 12XQWE3X1X2XASDF */ WHERE query not like '%12XQWE3X1X2XASDF%'"),a.fetchQuery(e).then(function(e){var n=a.dataToHandsontable(e);if(t.table.colHeaders=n.colHeaders,t.table.settings.columns=n.columns,t.table.settings.manualColumnResize=n.columns,t.table.settings.colWidths=n.colWidths,t.vars.logMode){n.data.forEach(function(e){if(t.vars.logData[e.hash]){var a=t.vars.logData[e.hash].count;t.vars.logData[e.hash].query_id!=e.query_id&&(a+=1),e.count=a,t.vars.logData[e.hash]=e}else e.count=1,t.vars.logData[e.hash]=e});var r=$.map(t.vars.logData,function(e,t){return[e]});t.table.data=r}else t.table.data=n.data;t.vars.data=!0,t.vars.loading=!1,t.updateHandTable()},function(e){t.vars.loading=!1,console.error("Error "+e)})},t.setInterval=function(){i.set(c,t.vars.interval),d&&(r.cancel(d),d=null),t.vars.interval>-1&&(d=r(t.load,1e3*t.vars.interval))},t.$on("$destroy",function(){t.vars.interval=-1,r.cancel(d),t.setInterval()}),t.initClusterConfig(),t.load(),t.vars.interval>-1&&t.setInterval(),t.dialogKill=function(n){var r="SELECT now() as dt,query,1 as count,\n \n formatReadableSize(read_bytes) as read_bytes, \n formatReadableSize(written_bytes) as written_bytes, \n formatReadableSize(memory_usage) as memory_usage,\n read_rows,written_rows,\n \n query_id as hash,\n round(elapsed,4) as elapsed \n FROM system.processes /* 12XQWE3X1X2XASDF */ WHERE query not like '%12XQWE3X1X2XASDF%' ORDER BY elapsed DESC";a.query(r).then(function(r){s.show({controller:["$scope",function(e){e.queryesToKill=r.data,e.kill=function(e){var t="KILL QUERY WHERE query_id='"+e.hash+"' SYNC",r=s.confirm().title(t+" ?").textContent(e.query).ariaLabel("Lucky day").targetEvent(n).ok("Please do it!").cancel("Sounds like a scam");s.show(r).then(function(){a.query(t,!1).then(function(e){s.show(s.alert().clickOutsideToClose(!0).title("Result: "+t).textContent(e).ariaLabel("Alert").ok("Ok!").targetEvent(n))},function(e){s.show(s.alert().clickOutsideToClose(!0).title("Error: "+t).textContent(e.data).ariaLabel("Error on Kill").ok("Ok!").targetEvent(n))})},function(){})},e.cancel=function(){s.cancel()}}],templateUrl:"app/metrics/dialog.kill.html",parent:e.element(document.body),targetEvent:n,clickOutsideToClose:!0}).then(function(e){t.status='You said the information was "'+e+'".'},function(){t.status="You cancelled the dialog."})})}}e.module(t.app.name).controller("ProcessesController",a),a.$inject=["$scope","API","ThemeService","$interval","localStorageService","$mdDialog","hotRegisterer"]}(angular,smi2),/* - * Copyright (C) 2017 IgorStrykhar in SMI2 - * All rights reserved. - */ -function(e,t,a){function n(e,t,a){e.widgets=[],e.staticGrid=!0,e.gridStackOptions={cellHeight:200,verticalMargin:0,disableDrag:!0},e.vars={uiTheme:a.themeObject,isDark:a.isDark()},e.initTab=function(){console.info("initPivotTab")},e.addWidgets=function(t){e.widgets.push(t),e.$applyAsync()},e.init=function(){console.info("Init OverviewController"),t.fetchQuery("SELECT * FROM system.build_options").then(function(t){e.addWidgets(new WidgetTable(new DataProvider(t)))}),t.fetchQuery("SELECT database,table,name, data_compressed_bytes, data_uncompressed_bytes FROM system.columns").then(function(t){var a={path:"database.table.name.data_compressed_bytes",title:"columns data_compressed_bytes",tooltip:"Size",valueformat:"0.00 b"},n={drawtype:"TREEMAP",code:a};e.addWidgets(new WidgetDraw(new DataProvider(t),n,6,6))}),t.fetchQuery("select toStartOfFiveMinute(modification_time) as dt,\n sum(bytes) as bytes from system.parts group by dt order by dt LIMIT 30000").then(function(t){var a={autoAxis:!0,markLine:!0,title:"system.parts bytes"},n={drawtype:"CHART",code:a};e.addWidgets(new WidgetDraw(new DataProvider(t),n,6,6))}),t.fetchQuery("select concat(database,'.',table) as table,sum(bytes) as bytes from system.parts\n group by table order by bytes desc LIMIT 3000").then(function(t){var a={title:"system.parts bytes"},n={drawtype:"BAR",code:a};e.addWidgets(new WidgetDraw(new DataProvider(t),n,6,2))}),t.fetchQuery("SELECT * FROM system.clusters").then(function(t){e.addWidgets(new WidgetTable(new DataProvider(t),2,6))})},e.init()}e.module(t.app.name).controller("OverviewController",n),n.$inject=["$scope","API","ThemeService"]}(angular,smi2,window.$),function(e,t){function a(t,a,n,r,i,s,o){var c="proc.metrica",l="proc.metrica_max";t.data=[],t.metrcisChart=!1,t.maxlength=i.get(l)||50,t.chartData={},t.orderKeys={},t.preState={},t.EChartOptions={},t.vars={logEvents:!1,initChart:!1,isDark:n.isDark(),interval:i.get(c)||-1,scrollConfig:{autoHideScrollbar:!1,theme:n.isDark()?"light":"dark",scrollButtons:{enable:!1},scrollInertia:100,advanced:{updateOnContentResize:!0}}},e.element(o).bind("resize",function(){t.metrcisChart&&t.vars.initChart&&t.metrcisChart.resize()}),t.initChart=function(e){if(t.vars.initChart){for(var a in e)if("time"!=a){t.chartData[a].length>t.maxlength&&t.chartData[a].shift();var r=parseInt(e[a]);r-parseInt(t.preState[a]);t.chartData[a].push([e.time,r])}return t.metrcisChart.setOption(t.EChartOptions),void(t.preState=e)}if(e.time){t.preState=e;var i=[],s=[],o=[],c=[],l=[],d=0,u=0;for(var m in e)if("time"!=m){t.orderKeys[m]=d;var h=parseInt(e[m]);t.chartData[m]=[],t.chartData[m].push([e.time,h]),i.push({show:!0,borderWidth:0,shadowBlur:2}),s.push({show:!1,type:"time",splitLine:{show:!1},gridIndex:d}),o.push({type:"value",show:!1,scale:!0,splitLine:{show:!1},name:"value",boundaryGap:[0,"100%"],min:"dataMin",max:"dataMax",gridIndex:d}),l.push({textAlign:"center",text:m,textStyle:{fontSize:10,fontWeight:"normal"}}),c.push({name:m,type:"line",data:t.chartData[m],xAxisIndex:d,yAxisIndex:u,showSymbol:!1,hoverAnimation:!1}),d+=1,u+=1}var p=Math.ceil(Math.sqrt(d));i.forEach(function(e,t){e.left=t%p/p*100+.5+"%",e.top=Math.floor(t/p)/p*100+.5+"%",e.width=1/p*100-2+"%",e.height=1/p*100-2+"%",l[t].left=parseFloat(e.left)+parseFloat(e.width)/2+"%",l[t].top=parseFloat(e.top)+"%"});var g={version:3,title:l.concat([{text:"Metrics",top:"bottom",left:"center"}]),toolbox:{show:!0,feature:{saveAsImage:{show:!0}}},width:"100%",group:"group",grid:i,xAxis:s,yAxis:o,series:c,tooltip:{showDelay:0,backgroundColor:"#2c343c",trigger:"axis",formatter:function(e){e=e[0];var t=new Date(e.value[0]),a=e.value[1],n=a;return e.seriesName.toLowerCase().includes("bytes")?a=numbro(a).format("0.0000b"):a>1e4&&(a=numbro(a).format("0.0000a")),e.seriesName+"

"+moment(t).format("h:mm:ss")+"
"+a+"
"+(n!=a?"
"+n+"
":"")},axisPointer:{animation:!1}}};t.vars.initChart=!0,t.EChartOptions=Object.assign(g,t.EChartOptions);var f="macarons";n.isDark()&&(f="dark"),t.metrcisChart=echarts.init(document.querySelector("#metrcisChart"),f),t.metrcisChart.setOption(t.EChartOptions),t.metrcisChart.resize()}};var d=null;t.$watch("vars.logEvents",function(){t.flushChart()},!0),t.flushChart=function(){t.vars.initChart&&(t.chartData={},t.metrcisChart.dispose(),t.EChartOptions={},t.vars.initChart=!1,t.load())},t.flush=function(){for(var e in t.chartData)for(var a=t.chartData[e].length,n=0;a-2>n;n++)t.chartData[e].shift();t.metrcisChart.setOption(t.EChartOptions),t.metrcisChart.resize(),t.load()},t.load=function(){t.vars.loading=!0;var e=" SELECT metric,toInt64(value) as value,'metrics' as type FROM system.metrics ORDER BY metric ";e+=" UNION ALL SELECT metric,toInt64(value) as value,'async' as type FROM system.asynchronous_metrics ORDER BY metric ",t.vars.logEvents&&(e+=" UNION ALL SELECT event as metric, toInt64( value) as value,'events' as type FROM system.events ORDER BY metric"),a.query(e).then(function(e){t.vars.loading=!1;var a={time:Date.now()};e.data.forEach(function(e){var t="";"events"==e.type&&(t=" "),a[e.metric+t]=e.value}),t.initChart(a)},function(e){t.vars.loading=!1,console.error("Error "+e)})},t.setMaxlength=function(){i.set(l,t.maxlength)},t.setInterval=function(){i.set(c,t.vars.interval),d&&(r.cancel(d),d=null),t.vars.interval>-1&&(d=r(t.load,1e3*t.vars.interval))},t.$on("$destroy",function(){t.vars.interval=-1,r.cancel(d),t.setInterval()}),t.load(),t.vars.interval>-1&&t.setInterval()}e.module(t.app.name).controller("MetricschartController",a),a.$inject=["$scope","API","ThemeService","$interval","localStorageService","$mdDialog","$window"]}(angular,smi2),function(e,t){function a(e,t,a,n,r,i,s){e.vars={uiTheme:a.themeObject,isDark:a.isDark(),selectedTabResultIndex:1,active:{Overview:!1,Chart:!1,Processes:!1}},e.initProcessesTab=function(t){e.vars.active.Processes=!0},e.initChartTab=function(t){e.vars.active.Chart=!0},e.initOverviewTab=function(t){e.vars.active.Overview=!0}}e.module(t.app.name).controller("MetricsController",a),a.$inject=["$scope","API","ThemeService","$interval","localStorageService","$mdDialog","$window"]}(angular,smi2),function(e,t){function a(a,n,r,i,s,o,c){var l="basesConfig";a.isChrome=/Chrome/.test(navigator.userAgent),a.vars={bases:r.get(l)||[],db:{},loading:!1,version:t.app.version,themes:o.list},a.loginCheckDone=function(){i.databaseStructure(function(e){return n.go("sql")},!0)},a.login=function(){if(a.vars.loading=!0,a.vars.db.id){for(var t=0;t=1024;)t/=1024,n++;return t.toFixed(+a)+" "+e[n]}})}(angular,smi2);/* - * Licensed under the Apache License, Version 2.0 Copyright 2017 Igor Strykhar,SMI2 LLC and other contributors - */ -var Widget=function(){function e(t){var a=arguments.length>1&&void 0!==arguments[1]?arguments[1]:!1,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:!1,r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:!1;_classCallCheck(this,e),this._scheduledResize=!1,this.data=t,this.drawCommnads=a,this._draw=!1,a&&this.drawCommnads.drawtype?this.drawType=this.drawCommnads.drawtype.toUpperCase():this.drawType=!1,this.error=this.data.error,this.text=this.data.text,this.name="Widget",this.element=!1,this.init=!1,_.isNumber(n)&&(this.sizeX=n),_.isNumber(r)&&(this.sizeY=r),this.type=!1;var i=angular.element("*[ng-app]").injector().get("ThemeService").isDark();this.isDark=i,window.isDarkTheme=i}return _createClass(e,[{key:"onDrag",value:function(){}},{key:"getSizeElementHeight",value:function(){return this.element[0].offsetHeight}},{key:"getSizeElementWidth",value:function(){return this.element[0].offsetWidth}},{key:"destroy",value:function(e){return console.info("Destroy widget is empty"),!1}},{key:"onResize",value:function(){}},{key:"scheduledResize",value:function(){if(!this._scheduledResize){this._scheduledResize=!0;var e=this;setTimeout(function(){e._scheduledResize=!1,e.onResize()},200)}}},{key:"toString",value:function(){return"("+this.name+", "+this.y+")"}}]),e}(),WidgetTable=function(e){function t(e,a,n,r){_classCallCheck(this,t);var i=_possibleConstructorReturn(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e,a,n,r));if(i.type="table",i.table={},i.sort=!1,i.hotId="hotIdTable"+Math.floor(1e7*Math.random()),i.handsonTable={},i.error)return i.sizeY=2,i.sizeX=12,i.init=!1,_possibleConstructorReturn(i);if(i.text)return i.sizeY=4,i.sizeX=12,i.init=!1,_possibleConstructorReturn(i);var s=new HandsTable(i.isDark,i.data.meta,{sort:!1,sortOrder:!1});if(i.table={settings:s.makeSettings()},i.table.settings.hotId=i.hotId,!i.sizeX&&!i.sizeY){var o=s.countColumns();i.initTableWSize(o)}return i.init=!0,i}return t.$inject=["DataProvider","draw","sizeX","sizeY"],_inherits(t,e),_createClass(t,[{key:"initTableWSize",value:function(e){var t=1;e>2&&(t=2),e>5&&(t=3),e>10&&(t=4),e>15&&(t=6),"statistics"==this.data.sourceType&&(t=6),this.sizeX=t,this.sizeY=1,this.data.rows>60&&(this.sizeY=1),this.data.rows>250&&(this.sizeY=2),this.data.rows>500&&(this.sizeY=3),1==this.data.countAll&&(this.sizeX=6,this.sizeY=3),this.sizeY=2*this.sizeY,this.sizeX=2*this.sizeX}},{key:"destroy",value:function(e){return function(){e.handsonTable.destroy(),e.handsonTable=null,e.data.data=null,e.settings=null,e.table=null,e.init=!1,e.element.html()}}},{key:"preProcessor",value:function(){}},{key:"postProcessor",value:function(){var e=this.table.settings;e.width=this.getSizeElementWidth(),e.height=this.getSizeElementHeight(),e.data=this.data.data,this.handsonTable=new Handsontable(this.element[0],e)}},{key:"onDrag",value:function(){this.onResize()}},{key:"onResize",value:function(e){if(this.init&&this.handsonTable){var t=this.getSizeElementWidth(),a=this.getSizeElementHeight();if(this.handsonTable.getSettings().width!=t||this.handsonTable.getSettings().height!=a)return this.handsonTable.updateSettings({width:t,height:a}),this.handsonTable.render(),!0}}}]),t}(Widget);angular.module(smi2.app.name).service("WidgetTable",WidgetTable);/* - * Licensed under the Apache License, Version 2.0 Copyright 2017 Igor Strykhar,Ivan Kudinov,SMI2 LLC and other contributors - */ -var WidgetPivot=function(e){function t(e,a){_classCallCheck(this,t);var n=_possibleConstructorReturn(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e,a));return n.type="pivot",n.error||n.text?_possibleConstructorReturn(n):(n.init=!0,n.renderers=$.extend($.pivotUtilities.renderers,$.pivotUtilities.c3_renderers,$.pivotUtilities.d3_renderers,$.pivotUtilities.export_renderers,$.pivotUtilities.subtotal_renderers),n.pivot={config:{dataClass:$.pivotUtilities.SubtotalPivotData,renderer:n.renderers}},1==n.data.countAll&&(n.sizeX=6,n.sizeY=3),n.sizeY=2*n.sizeY,n.sizeX=2*n.sizeX,n)}return t.$inject=["DataProvider","draw"],_inherits(t,e),t}(Widget);angular.module(smi2.app.name).service("WidgetPivot",WidgetPivot);/* - * Licensed under the Apache License, Version 2.0 Copyright 2017 Igor Strykhar,Ivan Kudinov,SMI2 LLC and other contributors - */ -var WidgetDraw=function(e){function t(e,a,n,r){_classCallCheck(this,t);var i=_possibleConstructorReturn(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e,a,n,r));return i.type="draw",i.error||i.text?_possibleConstructorReturn(i):(i.library=!1,i._list={PLOTLY:DrawPlotly,HEATMAP:DrawEchartsHeatmap,CALENDAR:DrawEchartsCalendar,RAW:DrawEchartsMap,BAR:DrawEchartsBar,RIVER:DrawEchartsRiver,MAP:DrawEchartsMap,GMAPS:DrawGoogleMap,TREEMAP:DrawEchartsTreemap,SANKEYS:DrawEchartsSunkeys,CHART:DrawEchartsChart,GRIDCHART:DrawEchartsGridChart,TEXT:DrawText,D3:DrawD3,C3:DrawC3},i.init=i.getChartClass(),i.sizeX||i.sizeY||(i.sizeX=6,i.sizeY=3,"TEXT"==i.drawType&&(i.sizeX=1,i.sizeY=2),console.info("this.data.countAll",i.data.countAll),1==i.data.countAll&&(i.sizeX=12,i.sizeY=3)),i)}return t.$inject=["DataProvider","draw","sizeX","sizeY"],_inherits(t,e),_createClass(t,[{key:"onResize",value:function(){this._draw&&this._draw.onResize()}},{key:"getChartClass",value:function(){return this.drawType||(this.drawType="CHART",console.error("Un support DrawType:null")),this._list[this.drawType]?!0:(console.error("Un support DrawType:"+this.drawType),!1)}},{key:"draw",get:function(){return this.drawType&&!this._draw&&(this._draw=new this._list[this.drawType](this,this.drawType)),this._draw}}]),t}(Widget);angular.module(smi2.app.name).service("WidgetDraw",WidgetDraw);/* - * Licensed under the Apache License, Version 2.0 Copyright 2017 Igor Strykhar,SMI2 LLC and other contributors - */ -var HandsTable=function(){function e(t,a,n){_classCallCheck(this,e),this.isDarkTheme=t,this.meta=a,this.Preset=n}return e.$inject=["isDark","metaData","Preset"],_createClass(e,[{key:"_handsRenderer",value:function(e,t,a,n,r,i,s){"numeric"==s.type?null==i||"-nan"==i||"inf"==i||"+nan"==i||"+inf"==i||"-inf"==i||"nan"==i?(null==i&&(arguments[5]="NULL"),t.style.color="black",t.style.background="red",Handsontable.renderers.TextRenderer.apply(this,arguments)):Handsontable.renderers.NumericRenderer.apply(this,arguments):"date"==s.type||"time"==s.type?(moment(new Date(i)).isValid()&&s.renderDateFormat&&(i=moment(i).format(s.renderDateFormat)),arguments[5]=i,Handsontable.renderers.TextRenderer.apply(this,arguments)):Handsontable.renderers.TextRenderer.apply(this,arguments),s.backgroundColor&&(t.style.backgroundColor=s.backgroundColor),s.color&&(t.style.color=s.color)}},{key:"countColumns",value:function(){return this.meta.length}},{key:"makeColumns",value:function(){var e=this,t=[],a=[],n={},r=0;return this.meta.forEach(function(i){n[i.name]=r,r++,t.push(i.name);var s={};switch(s.type="text",s.width=100,s.typeOriginal=i.type,s.isDark=e.isDarkTheme,i.type.includes("Int64")?(s.type="text",s.width=100):i.type.includes("Int")&&(s.width=80,s.type="numeric"),i.type){case"Date":s.width=90,s.type="date",s.dateFormat="YYYY-MM-DD";break;case"DateTime":s.width=150,s.type="time",s.timeFormat="YYYY-MM-DD HH:mm:ss";break;case"Float32":s.width=80,s.type="numeric",s.format="0.[0000000]";break;case"Float64":s.width=80,s.type="numeric",s.format="0.[0000000]";break;case"String":s.width=180}s.renderer=e._handsRenderer,s.data=i.name,a.push(s)}),{colHeaders:t,columns:a,colPositions:n}}},{key:"fecthContextMenu",value:function(){return{items:{columnformat:{name:"Column format",submenu:{items:[{name:"Reset",key:"columnformat:1",callback:function(t,a,n){e.makeFormat(this,"Reset")}},{name:"Money",key:"columnformat:2",callback:function(t,a,n){e.makeFormat(this,"Money")},disabled:function(){return!e.isFormatColl(this,"numeric")}},{name:"Human",key:"columnformat:3",callback:function(t,a,n){e.makeFormat(this,"Human")},disabled:function(){return!e.isFormatColl(this,"numeric")}},{name:"Bytes",key:"columnformat:4",callback:function(t,a,n){e.makeFormat(this,"Bytes")},disabled:function(){return!e.isFormatColl(this,"numeric")}},{name:"Percentages",key:"columnformat:5",callback:function(t,a,n){e.makeFormat(this,"Percentages")},disabled:function(){return!e.isFormatColl(this,"numeric")}},{name:"Time only",key:"columnformat:6",callback:function(t,a,n){e.makeFormat(this,"Time")},disabled:function(){return!e.isFormatColl(this,"Time")}},{name:"Date only",key:"columnformat:7",callback:function(t,a,n){e.makeFormat(this,"Date")},disabled:function(){return!e.isFormatColl(this,"Date")}},{name:"Date loc.",key:"columnformat:8",callback:function(t,a,n){e.makeFormat(this,"DateLoc")},disabled:function(){return!e.isFormatColl(this,"Date")}},{name:"Float",key:"columnformat:9",callback:function(t,a,n){e.makeFormat(this,"Float")},disabled:function(){return!e.isFormatColl(this,"numeric")}},{name:"Heatmaps",key:"columnformat:10",callback:function(t,a,n){e.makeHeatmaps(this,"Heatmaps")},disabled:function(){return!e.isFormatColl(this,"numeric")}},{name:"Negative & Positive",key:"columnformat:11",callback:function(t,a,n){e.makeHeatmaps(this,"NegaPosi")},disabled:function(){return!e.isFormatColl(this,"numeric")}}]}},style:{name:"Style",submenu:{items:[{name:"Normal",callback:function(t,a,n){e.makeStyle(this,"Normal")},key:"style:normal"},{name:"Bold",callback:function(t,a){e.makeStyle(this,"Bold")},key:"style:makebold"},{name:"Red color",callback:function(t,a){e.makeStyle(this,"Red")},key:"style:red"},{name:"Green color",callback:function(t,a){e.makeStyle(this,"Green")},key:"style:green"},{name:"Yellow color",callback:function(t,a){e.makeStyle(this,"Yellow")},key:"style:green"},{name:"Orange color",callback:function(t,a){e.makeStyle(this,"Orange")},key:"style:green"}]}},hsep1:"---------",copyTo:{name:"To Clipboard",submenu:{items:[{name:"Redmine Markdown",callback:function(t,a,n){console.info("copyToClipboard"),e.copyToClipboard(this,"Redmine")},key:"copyTo:1"},{name:"Redmine Markdown (full)",callback:function(t,a,n){console.info("copyToClipboard"),e.copyToClipboard(this,"Redmine",!0)},key:"copyTo:2"},{name:"WHERE col1 IN (val,val),col2 IN ...",callback:function(t,a,n){console.info("makeWhereIn"),e.makeWhereIn(this)},key:"copyTo:3"},{name:"Create TABLE...",callback:function(t,a,n){e.makeCreateTable(this)},key:"copyTo:4"}]}},hsep3:"---------",Transform:{name:"Transform",submenu:{items:[{name:"Transpose full table",callback:function(t,a,n){e.Transpose(this,"Transpose")},key:"Transform:1"}]}},undo:{},make_read_only:{},alignment:{},hsep4:"---------"}}}},{key:"makeSettings",value:function(){var e=this.makeColumns(),t={observeChanges:!1,observeDOMVisibility:!0,dropdownMenu:!0,manualColumnMove:!0,manualColumnResize:!0,rowHeaders:!0,colWidths:100,fillHandle:!1,stretchH:"all",customBorders:!0,isDark:this.isDarkTheme,filters:!0,columnSorting:!0,sortIndicator:!0,manualRowResize:!0,viewportColumnRenderingOffset:"auto",wordWrap:!1,autoColumnSize:{samplingRatio:23},columns:e.columns,colHeaders:e.colHeaders,contextMenu:this.fecthContextMenu(),currentRowClassName:this.isDarkTheme?"currentRowDark":"currentRowWhite",currentColClassName:"currentCol",renderAllRows:!1,visibleRows:1500};return this.Preset.sort&&this.Preset.sortOrder&&(t.columnSorting={column:e.colPositions[this.Preset.sort],sortOrder:"desc"==this.Preset.sortOrder.toLowerCase()?!1:!0}),t}}],[{key:"isDark",value:function(){return window.isDarkTheme}},{key:"makeHeatmaps",value:function(e,t){for(var a=e.getSelectedRange(),n=Math.min(a.from.col,a.to.col),r=Math.max(a.from.col,a.to.col),i="#a900e5",s="#3668ff",o=chroma.scale([i,s]),c=n;r>=c;c++){var l=e.countRows(),d=e.getDataAtCol(c),u=Math.min.apply(null,d),m=Math.max.apply(null,d);if(null!==u&&null!==m)for(var h=0;l>=h;h++){var p=parseFloat(e.getDataAtCell(h,c));if("Heatmaps"==t){var g=(p-u)/(m-u),f=o(g).hex(),b=e.getCellMeta(h,c);b&&e.setCellMeta(h,c,"backgroundColor",f)}if("NegaPosi"==t){var v=!1;0>p&&(v="#e27137"),p>0&&(v="#31b3e5");var y=e.getCellMeta(h,c);y&&v&&e.setCellMeta(h,c,"color",v)}}else console.warn("Can`t find Min&Max in column",c)}e.render()}},{key:"getSelected",value:function(e,t,a){var n=e.getSelectedRange(),r=!1;if(!n&&t||a)return{isSelection:!1,fromRow:0,toRow:e.countRows(),toCol:e.countCols(),fromCol:0};if(!n)return{isSelection:!1,fromRow:-1,toRow:-1,toCol:-1,fromCol:-1};var i=Math.min(n.from.col,n.to.col),s=Math.max(n.from.col,n.to.col),o=Math.min(n.from.row,n.to.row),c=Math.max(n.from.row,n.to.row);return{isSelection:r,fromRow:o,toRow:c,toCol:s,fromCol:i}}},{key:"makeFormat",value:function(t,a){for(var n=e.getSelected(t,!0),r=t.getSettings().columns,i=n.fromCol;i<=n.toCol;i++)switch(console.log("makeFormat for coll ="+i,a),a){case"Reset":r[i].format=!1,r[i].renderDateFormat=!1;break;case"Money":r[i].format="$0,0.00";break;case"Human":r[i].format="5a";break;case"Bytes":r[i].format="0.0b";break;case"Percentages":r[i].format="(0.00 %)";break;case"Time":r[i].renderDateFormat="HH:mm:ss";break;case"Date":r[i].renderDateFormat="YYYY-MM-DD";break;case"DateTime":r[i].renderDateFormat="YYYY-MM-DD HH:mm:ss";break;case"DateLoc":r[i].renderDateFormat="LLLL";break;case"Float":r[i].format="0.[0000000]"}t.updateSettings({columns:r}),t.render()}},{key:"isFormatColl",value:function(e,t){t=t.toLowerCase();for(var a=e.getSelectedRange(),n=Math.min(a.from.col,a.to.col),r=Math.max(a.from.col,a.to.col),i=e.getSettings().columns,s=n;r>=s;s++)if(!i[s].type.toLowerCase().includes(t))return!1;return!0}},{key:"pushToClipboardText",value:function(e){var t=document.createElement("textarea");t.style.width=0,t.style.height=0,t.style.border=0,t.style.position="absolute",t.style.top=0,document.body.append(t),t.value=e,t.focus(),t.select();try{document.execCommand("copy")}catch(a){console.log("Oops, unable to copy")}document.body.removeChild(t)}},{key:"makeCreateTable",value:function(t){for(var a=e.getSelected(t,!0),n="\nCREATE TABLE x (\n",r=[],i=t.getSettings().columns,s=a.fromCol;s<=a.toCol;s++){var o=i[s].typeOriginal;r.push(" "+t.colToProp(s)+" "+o)}n=n+r.join(",\n")+"\n)\nENGINE = TinyLog\n;;\n",console.log(n),e.pushToClipboardText(n)}},{key:"Transpose",value:function(t,a){var n=e.transpose(t.getSourceData()),r=[],i=[],s=!0,o=!1,c=void 0;try{for(var l,d=n.columns[Symbol.iterator]();!(s=(l=d.next()).done);s=!0){var u=l.value,m={};m.renderer=this._handsRenderer,m.data=u,m.type="text",m.width=100,i.push(m),r.push(u)}}catch(h){o=!0,c=h}finally{try{!s&&d["return"]&&d["return"]()}finally{if(o)throw c}}t.updateSettings({columns:i,colHeaders:r,data:n.data})}},{key:"transpose",value:function(e){var t=[],a=1,n=[];t.push(0);var r=!0,i=!1,s=void 0;try{for(var o,c=e[Symbol.iterator]();!(r=(o=c.next()).done);r=!0){var l=o.value,d=0,u=!0,m=!1,h=void 0;try{for(var p,g=Object.entries(l)[Symbol.iterator]();!(u=(p=g.next()).done);u=!0){var f=_slicedToArray(p.value,2),b=f[0],v=f[1];n[d]||(n[d]={}),1==a&&(n[d][0]=b),n[d][a]=v,d++}}catch(y){m=!0,h=y}finally{try{!u&&g["return"]&&g["return"]()}finally{if(m)throw h}}t.push(a),a++}}catch(y){i=!0,s=y}finally{try{!r&&c["return"]&&c["return"]()}finally{if(i)throw s}}return{data:n,columns:t}}},{key:"getPivotArray",value:function(e,t,a,n){for(var r={},i=[],s=[],o=0;o'+a+"":"")}},{key:"isDark",value:function(){return this.widget.isDark}},{key:"getError",value:function(){return this.errorMessage}},{key:"isExecutableCode",value:function(){return this.drawCodeObject&&this.drawCodeObject.type?this.drawCodeObject.exec:!1}},{key:"executableCode",value:function(){var e={};return this.isExecutableCode()&&(console.log(this.drawCodeObject.code),e=this.drawCodeObject.code.call(window,this.widget.data)),console.warn("executableCode:ResultFunction",e),e}},{key:"initChartByJsCode",value:function(){if(this.isExecutableCode()){var e=this.executableCode();return this.options=Object.assign(this.options,e),!0}return!1}},{key:"data",value:function(){return this.widget.data.data}},{key:"meta",value:function(){return this.widget.data.meta}},{key:"isNumericColumn",value:function(e){var t=this.getColumnPosition(e);if(!_.isUndefined(t)){var a=this.meta()[t].type;return a?(a=a.toLowerCase(),a.includes("int")||a.includes("float")?!0:!1):!1}}},{key:"isStringColumn",value:function(e){var t=this.getColumnPosition(e);if(!_.isUndefined(t)){var a=this.meta()[t].type;return a?(a=a.toLowerCase(),a.includes("string")||a.includes("enum")?!0:!1):!1}}},{key:"getColumnPosition",value:function(e){return parseInt(_.findKey(this.meta(),{name:e}))}},{key:"haveColumn",value:function(e){if(_.isNaN(e)||_.isNull(e)||_.isUndefined(e))return!1;var t=this.getColumnPosition(e);return _.isNaN(t)||_.isNull(t)||_.isUndefined(t)?!1:!0}},{key:"getColumnByType",value:function(e){var t=_.findIndex(this.meta(),{type:e});return 0>t?!1:this.getColumns(t)}},{key:"getDateTimeColumn",value:function(){return this.getColumnByType("DateTime")}},{key:"getDateColumn",value:function(){return this.getColumnByType("Date")}},{key:"getColumns",value:function(e){var t=_.map(this.meta(),"name");return _.isUndefined(e)?t:t[e]}},{key:"getFirstColumn",value:function(){return this.getColumns(0)}},{key:"getDrawCommandObject",value:function(){return this.drawCodeObject&&this.drawCodeObject.type?this.drawCodeObject.code:!1}},{key:"initDrawCodeObject",value:function initDrawCodeObject(){var drawCommand=this.widget.drawCommnads;if(!drawCommand)return[];var codeDrawText=!1;if(drawCommand&&drawCommand.code&&(codeDrawText=drawCommand.code),!codeDrawText)return[];var draw={code:!1,type:!1};if(_.isObject(codeDrawText))return draw={isok:!0,code:codeDrawText,type:"undefined"==typeof codeDrawText?"undefined":_typeof(codeDrawText),exec:!1};if("text"==drawCommand.drawtype.toLowerCase()){var obj=codeDrawText.trim();return draw={isok:!0,code:obj,type:"undefined"==typeof obj?"undefined":_typeof(obj),exec:!1}}for(var data={},columns=this.getColumns(),len=this.data().length,index=0;len>index;++index){var item=this.data()[index];for(var colPos in columns){var col=columns[colPos];data[col]||(data[col]=[]),data[col].push(item[col])}}try{var code="("+codeDrawText+")";console.log("CODE>>>",code);var _obj=eval(code),type="undefined"==typeof _obj?"undefined":_typeof(_obj);draw={isok:!0,code:_obj,type:type,exec:!!(_obj&&_obj.constructor&&_obj.call&&_obj.apply)}}catch(E){console.error("error eval ",codeDrawText,E)}return draw}}]),DrawBasicChart}(),DrawText=function(e){function t(e,a){_classCallCheck(this,t);var n=_possibleConstructorReturn(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));return n.type=a.toUpperCase(),n.library="text",n.widget.sizeX=0,n.widget.sizeY=0,n}return _inherits(t,e),_createClass(t,[{key:"preProcessor",value:function(){var e=this.getDrawCommandObject();this.init=this.applyText(e)}},{key:"applyText",value:function(e){return this.isDark()&&(this.widget.element[0].style.background="#404a59"),e?this.widget.element[0].innerHTML=Mustache.render(e,this.widget.data):this.widget.element[0].innerHTML="
"+JSON.stringify(this.widget.data,null,"	")+"
",!0}},{key:"onResize",value:function(){}}]),t}(DrawBasicChart),DrawPlotly=function(e){function t(e,a){_classCallCheck(this,t);var n=_possibleConstructorReturn(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));return n.type=a.toUpperCase(),n.library="plotly",n.chart=null,n.setWidgetSize(6,3),n}return _inherits(t,e),_createClass(t,[{key:"onResize",value:function(){if(this.plotly){var e=this.widget.getSizeElementHeight(),t=this.widget.getSizeElementWidth();(this.layout.height!=e||this.layout.width!=t)&&(this.layout.height=e,this.layout.width=t,this.relayout())}}},{key:"preProcessor",value:function(){return this.initChartByJsCode(),this.getError()?(console.error(this.getError()),this.chart.before("

"+this.getError()+"

"),!1):(this.isDark(),this.init=this.create(),void console.info("preProcessor",this.init))}},{key:"getElement",value:function(){return this.widget.element[0]}},{key:"relayout",value:function(){Plotly.relayout(this.getElement(),this.layout)}},{key:"editor",value:function(){console.info("editoreditoreditor")}},{key:"create",value:function(){var e=this.getDrawCommandObject();console.warn("CREATE DrawPlotly",e);var t={data:[],layout:{}};_.isObject(e)&&(_.isObject(e.trace)&&t.data.push(e.trace),_.isObject(e.trace1)&&t.data.push(e.trace1),_.isObject(e.trace2)&&t.data.push(e.trace2),_.isObject(e.trace3)&&t.data.push(e.trace3),_.isObject(e.trace4)&&t.data.push(e.trace4),_.isObject(e.layout)&&(t.layout=e.layout)),console.info(t);var a=[{x:[1,2],y:[1,2],type:"bar"}];console.log("CONS:",a),console.log("llll:",t);var n={editable:!1};this.layout=t.layout;var r=this.widget.getSizeElementHeight(),i=this.widget.getSizeElementWidth();return this.layout.height=r,this.layout.width=i,this.plotly=Plotly.plot(this.getElement(),t.data,this.layout,n),!0}},{key:"applyDarkTheme",value:function(){}}]),t}(DrawBasicChart),DrawGoogleMap=function(e){function t(e,a){_classCallCheck(this,t);var n=_possibleConstructorReturn(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));return n.type=a.toUpperCase(),n.library="gmaps",n._map=!1,n.mapOptions={zoom:4},n}return _inherits(t,e),_createClass(t,[{key:"onResize",value:function(){this._map&&google.maps.event.trigger(this._map,"resize")}},{key:"preProcessor",value:function(){this.loadGoogleMapJS(this)}},{key:"afterLoadMapProcessor",value:function(){if(this.initChartByJsCode()?this.init=!0:this.init=this.create(),this.getError())return console.error(this.getError()),this.chart.before("

"+this.getError()+"

"),!1;var e=this.getDrawCommandObject();e.raw&&(this.options=_.merge(this.options,e.raw)),this.isDark(),console.info("preProcessor",this.init,this.options)}},{key:"loadGoogleMapJS",value:function(e){if(window._sendGoogleMapLoad)return void this.afterLoadMapProcessor();window._sendGoogleMapLoad=!0,window._isGoogleMapLoaded=!1,console.info("YA_MAP>Start load map : api-maps.yandex.ru");var t=document.createElement("script");t.type="text/javascript",t.async=!0,t.src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCRQH39oyrPnfPPgADuOp0eSRsDHRUMyyY",t.charset="utf-8",t.onload=t.onreadystatechange=function(){t.readyState&&"complete"!==t.readyState&&"loaded"!==t.readyState||(t.onload=t.onreadystatechange=null,e.afterLoadMapProcessor(),window._isGoogleMapLoaded=!0)};var a=document.getElementsByTagName("script")[0];a.parentNode.insertBefore(t,a)}},{key:"getDarkStyle",value:function(){return[{featureType:"all",elementType:"labels.text.fill",stylers:[{color:"#ffffff"}]},{featureType:"all",elementType:"labels.text.stroke",stylers:[{color:"#000000"},{lightness:13}]},{featureType:"administrative",elementType:"geometry.fill",stylers:[{color:"#000000"}]},{featureType:"administrative",elementType:"geometry.stroke",stylers:[{color:"#144b53"},{lightness:14},{weight:1.4}]},{featureType:"landscape",elementType:"all",stylers:[{color:"#08304b"}]},{featureType:"poi",elementType:"geometry",stylers:[{color:"#0c4152"},{lightness:5}]},{featureType:"road.highway",elementType:"geometry.fill",stylers:[{color:"#000000"}]},{featureType:"road.highway",elementType:"geometry.stroke",stylers:[{color:"#0b434f"},{lightness:25}]},{featureType:"road.arterial",elementType:"geometry.fill",stylers:[{color:"#000000"}]},{featureType:"road.arterial",elementType:"geometry.stroke",stylers:[{color:"#0b3d51"},{lightness:16}]},{featureType:"road.local",elementType:"geometry",stylers:[{color:"#000000"}]},{featureType:"transit",elementType:"all",stylers:[{color:"#146474"}]},{featureType:"water",elementType:"all",stylers:[{color:"#021019"}]}]}},{key:"getLightStyle",value:function(){return[{featureType:"landscape",stylers:[{hue:"#FFBB00"},{saturation:43.400000000000006},{lightness:37.599999999999994},{gamma:1}]},{featureType:"road.highway",stylers:[{hue:"#FFC200"},{saturation:-61.8},{lightness:45.599999999999994},{gamma:1}]},{featureType:"road.arterial",stylers:[{hue:"#FF0300"},{saturation:-100},{lightness:51.19999999999999},{gamma:1}]},{featureType:"road.local",stylers:[{hue:"#FF0300"},{saturation:-100},{lightness:52},{gamma:1}]},{featureType:"water",stylers:[{hue:"#0078FF"},{saturation:-13.200000000000003},{lightness:2.4000000000000057},{gamma:1}]},{featureType:"poi",stylers:[{hue:"#00FF6A"},{saturation:-1.0989010989011234},{lightness:11.200000000000017},{gamma:1}]}]}},{key:"create",value:function(){console.warn("CREATE"),this._map=new google.maps.Map(this.widget.element[0],this.mapOptions);var e=this.getLightStyle();this.isDark()&&(e=this.getDarkStyle()),this._map.setOptions({styles:e});var t=this,a=this.getDrawCommandObject(),n={longitude:"longitude",latitude:"latitude",count:"count",title:"title"},r=new google.maps.LatLngBounds,i=0;a&&(n=Object.assign(n,a)),this.data().forEach(function(e,a){var s=parseInt(e[n.count]);s>i&&(i=s);var o={lat:e[n.latitude],lng:e[n.longitude]},c=!1;e[n.title]&&(c=new google.maps.InfoWindow({content:'
'+e[n.title]+"
"})),r.extend(o);var l=new google.maps.Marker({position:o,map:t._map,title:"Value:"+s});c&&l.addListener("click",function(){c.open(this._map,l)})}),this._map.fitBounds(r),this._map.panToBounds(r)}}]),t}(DrawBasicChart),DrawEcharts=function(e){function t(e,a){_classCallCheck(this,t);var n=_possibleConstructorReturn(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));return n.help="",n.type=a.toUpperCase(),n.library="echarts",n.preference={gridchart:!1,bar:!1},n.options={version:3,textStyle:{fontFamily:"Menlo"},toolbox:{show:!0,feature:{dataZoom:{yAxisIndex:"none",title:"data Zoom"},dataView:{readOnly:!1,title:"data View"},magicType:{type:["line","bar","stack","tiled"],title:{line:"line",bar:"bar",stack:"stack",tiled:"tiled"}},restore:{title:"Restore"},saveAsImage:{title:"Save as Image"}}}},n}return _inherits(t,e),_createClass(t,[{key:"onResize",value:function(){console.log("onResize Chart"),this.chart&&this.init&&this.chart.resize()}},{key:"preProcessor",value:function(){if(this.initChartByJsCode())this.init=!0;else try{this.init=this.create()}catch(e){this.setError(this.getError()+"\n\n\n"+e.name+":"+e.message+"\n"+e.stack)}if(this.getError())return console.error(this.getError()),!1;var t=this.getDrawCommandObject();t.raw&&(this.options=_.merge(this.options,t.raw)),this.isDark()&&(this.options.backgroundColor="#404a59"),this.chart.setOption(this.options),console.info("preProcessor",this.init,this.options)}},{key:"getParameterPath",value:function(){var e=this.getDrawCommandObject(),t={path:""};e&&(t=Object.assign(t,e));var a="";if(_.isString(e)?a=e:t.path&&(a=t.path),!a)return!1;for(var n=_.split(a,"."),r=0;rs;s+=1){var o=this.getColumns(s);if(!r&&this.isNumericColumn(o)){r=o;break}}t.date=n,t.value=r}if(!this.haveColumn(t.date)||!this.haveColumn(t.value))return this.setError("Not set date | value cols"),!1;var c=0,l=Number.MAX_VALUE,d=_.map(this.data(),function(e){var a=parseFloat(e[t.value]);return a&&a>c&&(c=a),a&&l>a&&(l=a),[e[t.date],a]});d=_.groupBy(d,function(e){var t=(""+e[0]).substring(0,4);return t});var u={tooltip:{position:"top"},calendar:[],series:[],visualMap:{min:l,max:c,calculable:!0,orient:"horizontal",left:"center",top:"top"}},m=60,h=0;return _.forEach(d,function(e,t){u.calendar.push({top:m,range:t,right:0,cellSize:["auto",20]}),u.series.push({type:"heatmap",coordinateSystem:"calendar",data:e,calendarIndex:h}),h+=1,m+=200}),this.options=Object.assign(u,this.options),!0}}]),t}(DrawEcharts),DrawEchartsTreemap=function(e){function t(){return _classCallCheck(this,t),_possibleConstructorReturn(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return _inherits(t,e),_createClass(t,[{key:"getLevelOption",value:function(){return[{itemStyle:{normal:{borderWidth:0,gapWidth:5}}},{itemStyle:{normal:{gapWidth:1}}},{colorSaturation:[.35,.5],itemStyle:{normal:{gapWidth:1,borderColorSaturation:.6}}}]}},{key:"buildTreeData",value:function(e,t){var a=[],n=this;return _.forEach(e,function(e,r){var i=t[r],s={};if(s.value=i.__value,_.isObject(e)){var o=n.buildTreeData(e,i);_.isArray(o)&&o.length&&(s.children=o)}s.name=r,a.push(s)}),a}},{key:"create",value:function(){var e=this.getDrawCommandObject(),t={path:"",title:"TreeMap",tooltip:"Usage",valueformat:!1};e&&(t=Object.assign(t,e));var a="";t.path&&(a=t.path),_.isString(e)&&(a=e);var n=_.split(a,"."),r=n.length;if(!r)return this.setError("Not set path"),!1;for(var i=0;r>i;i+=1)if(!this.haveColumn(n[i]))return this.setError("bad path, no column:"+n[i]),!1;if(!this.isNumericColumn(n[r-1]))return this.setError("bad column:"+n[r-1]+" must be number"),!1;var s={},o={};this.data().forEach(function(e){for(var t=e[n[r-1]],a=[],i=0;r-1>i;i+=1){a.push(e[n[i]]);var c=_.get(s,a.join("_"),0);_.set(s,a.join(".")+".__value",parseFloat(c)+parseFloat(t))}_.set(o,a.join("."),t)});var c=this.buildTreeData(o,s),l={tooltip:{trigger:"item"}},d=echarts.format;return l.series=[{type:"treemap",name:t.title,label:{show:!0,formatter:"{b}"},tooltip:{formatter:function(e){for(var a=e.value,n=[],r=e.treePathInfo,i=1;i'+d.encodeHTML(n.join("."))+"",t.tooltip+" : "+numbro(a).format(s)].join("")}},itemStyle:{normal:{borderColor:"#fff"}},levels:this.getLevelOption(),data:c}],this.options=Object.assign(l,this.options),!0}}]),t}(DrawEcharts),DrawEchartsSunkeys=function(e){function t(){return _classCallCheck(this,t),_possibleConstructorReturn(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return _inherits(t,e),_createClass(t,[{key:"create",value:function(){this.helpLink="https://tabix.io/doc/draw/Draw_Sankeys/",this.help="Default config : {path:''} or {value:'',source:'',target:''}, if empty path or not set, try auto create path, then find columns [String] : [Integer|Float] : [String] ";var e=this.getDrawCommandObject(),t={path:"",value:"value",source:"source",target:"target"};e&&(t=Object.assign(t,e));var a="";_.isString(e)?a=e:t.path?a=t.path:this.haveColumn(t.source)&&this.haveColumn(t.value)&&this.haveColumn(t.target)&&(a=t.source+"."+t.value+"."+t.target);var n=[];if(a)n=_.split(a,".");else{var r=!1,i=this.getColumns();for(var s in i){var o=i[s];this.isNumericColumn(o)&&r&&(n.push(o),r=!1),this.isStringColumn(o)&&!r&&(n.push(o),r=!0)}}if(console.log("patharr>",n),!n.length)return this.setError("The value of the variable 'path' - empty"),!1;if(!(1&n.length))return this.setError("The value of the variable 'path' must be odd"),!1;var c=[],l=[];this.data().forEach(function(e){for(var t=0;ta&&(a=s),e[t.destination.longitude]&&e[t.destination.latitude]){var o="";e[t.destination.name]&&(o=e[t.destination.name]),r.push({fromName:e[t.name],toName:o,coords:[[e[t.longitude],e[t.latitude]],[e[t.destination.longitude],e[t.destination.latitude]]]})}n.push({name:e[t.name],value:[e[t.longitude],e[t.latitude],s],label:{emphasis:{position:"right",show:!0}}})});var i=[{name:t.title,type:"effectScatter",coordinateSystem:"geo",data:n,showEffectOn:"render",rippleEffect:{brushType:"stroke"},symbolSize:function(e){return a?e[2]/a*15:e[2]/1e4},hoverAnimation:!0,label:{normal:{formatter:"{b}",position:"right",show:!0}},itemStyle:{normal:{color:"#f4e925",shadowBlur:10,shadowColor:"#333"}},zlevel:1}];if(r.length>0){var s="path://M1705.06,1318.313v-89.254l-319.9-221.799l0.073-208.063c0.521-84.662-26.629-121.796-63.961-121.491c-37.332-0.305-64.482,36.829-63.961,121.491l0.073,208.063l-319.9,221.799v89.254l330.343-157.288l12.238,241.308l-134.449,92.931l0.531,42.034l175.125-42.917l175.125,42.917l0.531-42.034l-134.449-92.931l12.238-241.308L1705.06,1318.313z"; -i.push({name:t.title,type:"lines",zlevel:1,effect:{show:!0,period:6,trailLength:.7,color:"#fff",symbolSize:3},lineStyle:{normal:{width:0,curveness:.2}},data:r}),i.push({name:t.title,type:"lines",zlevel:2,symbol:["none","arrow"],symbolSize:10,effect:{show:!0,period:6,trailLength:0,symbol:s,symbolSize:15},lineStyle:{normal:{width:1,opacity:.6,curveness:.2}},data:r})}var o={tooltip:{trigger:"item"},geo:{name:t.title,type:"map",map:"world",label:{emphasis:{show:!1}},visualMap:{show:!0,min:0,max:100,inRange:{symbolSize:[6,60]}},roam:!0,itemStyle:{normal:{areaColor:"#323c48",borderColor:"#404a59"},emphasis:{areaColor:"#2a333d"}}},series:i};return this.options=Object.assign(this.options,o),!0}}]),t}(DrawEcharts),DrawEchartsHeatmap=function(e){function t(){return _classCallCheck(this,t),_possibleConstructorReturn(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return _inherits(t,e),_createClass(t,[{key:"create",value:function(){var e=this.getParameterPath();if(!e)return this.setError("Not set path"),!1;var t={},a={},n={};this.data().forEach(function(r){_.set(t,r[e[0]],1),_.set(a,r[e[1]],1),_.set(n,r[e[0]]+"."+r[e[1]],parseFloat(r[e[2]]))});var r=[],i=_.keys(t),s=_.keys(a),o=0,c=0;_.mapKeys(t,function(e,t){_.mapKeys(a,function(e,a){var i=_.get(n,t+"."+a,"-");o>i&&(o=i),i>c&&(c=i),r.push([t,a,i])})});var l={tooltip:{position:"top"},animation:!1,grid:{height:"50%",y:"10%"},xAxis:{type:"category",data:i,splitArea:{show:!0}},yAxis:{type:"category",data:s,splitArea:{show:!0}},visualMap:{min:o,max:c,calculable:!0,orient:"horizontal",left:"center",bottom:"15%"},series:[{name:"Punch Card",type:"heatmap",data:r,label:{normal:{show:!0}},itemStyle:{emphasis:{shadowBlur:10,shadowColor:"rgba(0, 0, 0, 0.5)"}}}]};return this.options=Object.assign(l,this.options),!0}}]),t}(DrawEcharts),DrawEchartsChart=function(e){function t(){return _classCallCheck(this,t),_possibleConstructorReturn(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return _inherits(t,e),_createClass(t,[{key:"create",value:function(){console.log("DrawEchartsChart");var e=this.getDrawCommandObject(),t=this.preCreate(e),a=this.createChart(e),n={tooltip:{trigger:"axis",axisPointer:{type:"shadow"}},grid:{left:"3%",right:"4%",bottom:"3%",containLabel:!0}};return e.title&&this.applyTitle(e.title),this.applyDataZoom(),this.applyLegend(),this.options=Object.assign(a,this.options,n,t),this.postCreate(e),!0}},{key:"findDateTimeAxis",value:function(){var e=this.getDateTimeColumn();if(e)return e;var t=this.getDateColumn();return t?t:!1}},{key:"postCreate",value:function(e){return{}}},{key:"preCreate",value:function(e){return{}}},{key:"createChart",value:function(e){var t=this,a={autoAxis:!1,markLine:!0,stack:!1,path:!1,sort:!0,xAxis:!1,yAxis:!1};e&&(a=Object.assign(a,e));var n={},r=this.getColumns(),i=this.getFirstColumn(),s=i,o=this.findDateTimeAxis(),c={},l=[],d=[],u=[],m={},h=this.data();if(o&&(i=o),a.xAxis){if(!this.haveColumn(a.xAxis))throw"xAxis column not exists";s=a.xAxis}else a.sort&&(h=_.sortBy(h,i)),s=i;if(d=[{name:s,type:"category",data:[]}],a.yAxis)if(_.isString(a.yAxis)){if(!this.haveColumn(a.yAxis))throw"yAxis column not exists";n[a.yAxis]=1}else{if(!_.isArray(a.yAxis))throw"yAxis column must string or array";var p=void 0;for(p=0;pk&&!w?(_.isArray(y)||(y=[]),y.push(S),k++):this.isNumericColumn(S)&&x.push(S))}var A=h.length;for(console.log("DATA LEN",A,h),v=0;A>v;++v){var D=h[v];d[0].data.push(D[d[0].name])}for(d[0].data=_.uniq(d[0].data),console.log("xAxis[0].data.",d[0].data),v=0;A>v;++v){var R=h[v],I=function(e){var a=r[e],i=[s],o=!1;if(_.size(n)&&(o=_.isUndefined(n[a])),a!==s&&!o&&t.isNumericColumn(a)&&_.findIndex(y,a)<0){if(y)for(var c=0;c1){var q=_.groupBy(f,function(e){return Math.floor(e.median/1e3)});if(_.size(q)>1){var H=function(e){var t=q[e],n=_.map(t,"column").join(",");_.forEach(t,function(e){u[e.index].yAxisIndex=l.length,a.stack&&(u[e.index].stack=n,u[e.index].areaStyle={normal:{}})}),l.push({name:n,type:"value"})};for(var P in q)H(P)}}return l.length||(l=[{name:b,type:"value"}]),c.series=u,c.yAxis=l,c.xAxis=d,console.info("Make Chart Done : Options",c),c}}]),t}(DrawEcharts),DrawEchartsGridChart=function(e){function t(){return _classCallCheck(this,t),_possibleConstructorReturn(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return _inherits(t,e),_createClass(t,[{key:"preCreate",value:function(e){return this.preference.gridchart=!0,{}}},{key:"postCreate",value:function(e){var t=[],a=[],n=[],r=[],i=0;console.info("postCreate!!!!!!",this.options);var s=[],o=this.options.xAxis[0],c=this.options.yAxis[0];for(var l in this.options.series){l=parseInt(l);var d=this.options.series[l].name;this.options.series[l].xAxisIndex=l,this.options.series[l].yAxisIndex=i,console.log(d,this.options.series[l]),o.show=!1,o.gridIndex=l,c.gridIndex=l,c.show=!1,c.name=d,t.push({show:!0,borderWidth:0,shadowBlur:2}),n.push(_.clone(o)),a.push(_.clone(c)),r.push({textAlign:"center",text:d,textStyle:{fontSize:11,fontWeight:"normal"}}),s.push(l),i+=1}var u=Math.ceil(Math.sqrt(i));t.forEach(function(e,t){e.left=t%u/u*100+.5+"%",e.top=Math.floor(t/u)/u*100+.5+"%",e.width=1/u*100-1+"%",e.height=1/u*100-1+"%",r[t].left=parseFloat(e.left)+parseFloat(e.width)/2+"%",r[t].top=parseFloat(e.top)+"%"}),this.options.dataZoom&&this.options.dataZoom[0]&&(this.options.dataZoom[0].xAxisIndex=s),this.options.titles=r,this.options.grid=t,this.options.xAxis=n,this.options.yAxis=a}}]),t}(DrawEchartsChart),DrawEchartsBar=function(e){function t(){return _classCallCheck(this,t),_possibleConstructorReturn(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return _inherits(t,e),_createClass(t,[{key:"preCreate",value:function(e){return this.preference.bar=!0,{}}}]),t}(DrawEchartsChart),DrawD3=function(e){function t(e){_classCallCheck(this,t);var a=_possibleConstructorReturn(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));return a.library="d3",a}return _inherits(t,e),t}(DrawBasicChart),DrawC3=function(e){function t(e){_classCallCheck(this,t);var a=_possibleConstructorReturn(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));return a.library="c3",a.bindto=!1,a}return _inherits(t,e),_createClass(t,[{key:"onResize",value:function(){this.chart&&this.init}},{key:"preProcessor",value:function(){return console.log("preProcessor>c3.generate"),this.initChartByJsCode()?(console.log("c3.options>",this.options),this.bindto.className+=" c3",console.log("this.bindto.className",this.bindto.className),this.options.bindto=this.bindto,console.log("c3.options>",this.options),void(this.chart=c3.generate(this.options))):(console.error("C3.Init by code"),!1)}}]),t}(DrawBasicChart),DrawAMcharts=function(e){function t(e){_classCallCheck(this,t),console.warn("DrawAMcharts constructor");var a=_possibleConstructorReturn(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));return a.library="amchart",a}return _inherits(t,e),_createClass(t,[{key:"onResize",value:function(){this.makeLegend()}},{key:"preProcessor",value:function(){this.createChart()&&(this.init=!0),console.log("!preProcessor,done",this.init,this.options)}},{key:"createChart",value:function(){var e=this,t={},a=this.widget.data.meta,n=!1,r="",i="mm",s=[],o=0,c=[];a.forEach(function(a){if("DateTime"==a.type)n="YYYY-MM-DD JJ:NN:SS",r=a.name;else if("Date"==a.type)n="YYYY-MM-DD",i="DD",r=a.name;else{if(!r)return void(r=a.name);o+=1;var l=e.getChartGraph(a,t[a.name]);l.id="g"+o,"v1"!==l.valueAxis&&c.push(l.valueAxis),s.push(l)}});var l={theme:Widget.isDark?"dark":"light",color:Widget.isDark?"#eee":"#333",type:"serial",categoryField:r,valueAxes:[{id:"v1",axisAlpha:1,gridAlpha:.07,axisColor:Widget.isDark?"#eee":"#333",gridColor:Widget.isDark?"#eee":"#333",ignoreAxisWidth:!0}],balloon:{borderThickness:1,shadowAlpha:0},graphs:s,chartCursor:{valueLineEnabled:!0,valueLineBalloonEnabled:!0,cursorAlpha:0,zoomable:!1,valueZoomable:!0,valueLineAlpha:.5},chartScrollbar:{graph:"g1",gridAlpha:0,color:"#888888",scrollbarHeight:25,backgroundAlpha:0,selectedBackgroundAlpha:.1,selectedBackgroundColor:"#888888",graphFillAlpha:0,autoGridCount:!0,selectedGraphFillAlpha:0,graphLineAlpha:.2,graphLineColor:"#c2c2c2",selectedGraphLineColor:"#888888",selectedGraphLineAlpha:1},categoryAxis:{dashLength:1,minorGridEnabled:!0,axisColor:Widget.isDark?"#eee":"#333",gridColor:Widget.isDark?"#eee":"#333"},data:this.widget.data.data};if(l.categoryAxis.parseDates=!1,n&&(l.dataDateFormat=n,l.categoryAxis.parseDates=!0,l.categoryAxis.minPeriod=i),c){var d=0;c.forEach(function(e){d++;var t={id:e,axisAlpha:1,axisThickness:1,position:"right",ignoreAxisWidth:!0,offset:1*d};l.valueAxes.push(t)})}return this.options=l,this.init=!0,this.makeLegend(),!0}},{key:"makeLegend",value:function(){console.log("this.widget.sizeY",this.widget.sizeY),this.widget.sizeY<2?delete this.options.legend:this.options.legend={align:"center",equalWidths:!1,periodValueText:"total: [[value.sum]]",valueAlign:"left",valueText:"[[value]] ([[percents]]%)",valueWidth:100},console.warn(this.options)}},{key:"getChartGraph",value:function(e,t){var a=e.name,n=e.name,r="v1";a=a.replace(/_axis\d+/gm,"");var i=/.*_axis(\d+).*/i,s=n.match(i);s&&s[1]&&(r="v"+s[1]);var o={id:"g1",valueAxis:r,fillAlphas:.2,bullet:"round",bulletSize:8,hideBulletsCount:50,lineThickness:1,title:a,useLineColorForBulletBorder:!0,valueField:n,type:"smoothedLine",balloonText:"[[title]] [[category]]
[[value]]"};return t||(t={}),Object.assign(o,t)}}]),t}(DrawBasicChart),DataProvider=function(){function e(t,a){_classCallCheck(this,e),t.totals&&t.data&&t.data.push(t.totals),this.data=t.data,this.text=!1,this.progressQuery="",this.sort=!1,this.sortOrder=!1,t.error||angular.isObject(t.data)||(angular.isString(t.data)?this.text=t.data:this.text=angular.toJson(t.data,!0),this.text=this.text.replace(/&/g,"&").replace(//g,">")),a||(a="ch"),this.sourceType=a,this.meta=t.meta,t.query?this.query=t.query:this.query={index:0,drawCommands:!1},t.error?(this.error=t.error.replace("
","\n").replace(/&/g,"&").replace(//g,">"),this.error=this.error.replace("\\n","
")):this.error=!1,this.draw=this.query.drawCommands,this.rows=t.rows,this.position=this.query.index,this.countAll=t.countAllQuery}return e.$inject=["result","sourceType"],_createClass(e,[{key:"isText",value:function(){return this.text?!0:!1}},{key:"isError",value:function(){return this.error?!0:!1}},{key:"getError",value:function(){return this.error}},{key:"data",value:function(){return this.data}},{key:"meta",value:function(){return this.meta}},{key:"toString",value:function(){return"("+this.name+", "+this.y+")"}}],[{key:"convertArrayToDataProvider",value:function(t,a){var n={};return n.data=t,n.meta=[],n.error=!1,n.query={drawCommands:!1},n.rows=t.length,n.position=0,n.countAll=0,Object.keys(t[0]).map(function(e){return n.meta.push({name:e,type:"string"})}),new e(n,a)}}]),e}();angular.module(smi2.app.name).service("DataProvider",DataProvider),function(e,t){function a(t,a,n,r,i,s,o,c){t.vars={isDark:r.isDark(),historysql:a.sqlLog,charthelp:[],active:{chart:!0,history:!0,snippet:!0,vars:!0},snippets:o.snippets,variables:s.vars},t.vars.scrollConfig2={autoHideScrollbar:!1,theme:r.isDark()?"light":"dark",scrollButtons:{enable:!1},scrollInertia:400,setHeight:200,advanced:{updateOnContentResize:!0}},t.showAddVarsDialog=function(a){c.show({controller:["$scope","$mdDialog",function(e,t){e.v={name:"Var1",type:"text",value:""},e.close=function(){t.cancel()},e.add=function(e){t.hide(e)}}],templateUrl:"app/base/addVarsDialog.html",parent:e.element(document.body),targetEvent:a,clickOutsideToClose:!0}).then(function(e){e.name&&e.value&&e.type&&(s.addVar(e.type,e.name,e.value),t.broadcast())},function(){})},t.broadcast=function(){a.$emit("handleBroadcastUpdateVarsAndSnippets",{value:!0})},t.changed=function(e){s.update(e),t.broadcast()},t.showState=function(){console.warn(t.vars.variables)},t.addVar=function(){s.addVar("int","limit",1e3),t.broadcast()},t.actionHistory=function(e){a.$emit("handleBroadcastInsertInActive",{value:e})},t.dropSnippet=function(e){o.drop(e),t.broadcast()},t.dropVar=function(e){s.drop(e),t.broadcast()},t.init=function(){(!_.isObject(t.vars)||_.isUndefined(t.vars.variables.limit))&&s.addVar("int","limit",1e3)},t.init()}e.module(t.app.name).controller("SidebarHelperCtrl",a),a.$inject=["$scope","$rootScope","API","ThemeService","localStorageService","Variables","Snippets","$mdDialog"]}(angular,smi2),function(e,t){function a(e,t,a,n,r,i,s,o,c,l){e.vars={searchline:"",counter:0,loaded:!1,error:!1,databases:[]},e.vars.scrollConfig={autoHideScrollbar:!1,theme:r.isDark()?"light":"dark",scrollButtons:{enable:!1},scrollInertia:400,advanced:{updateOnContentResize:!0}},e.vars.metis={config:{toggle:!1,preventDefault:!1}},e.clickInsertField=function(e){t.$emit("handleBroadcastInsertInActive",{value:e.name})},e.clickAndSelect=function(a,n){return a.name==t.currentDatabase?(n.stopPropagation(),!1):void e.selectDatabase(a)},e.selectDatabase=function(e){console.time("sidebar.selectDatabase time took"),t.currentDatabase=e.name,s.show(s.simple().content("USE "+e.name+" database").theme(r.theme).position("bottom right")),console.timeEnd("sidebar.selectDatabase time took")},e.openTable=function(e){console.log("openTable!!!!!!!!!!!!!!!!!!!!!!!"),i("tableSiedenav").close(),t.currentDatabase!=e.database&&(s.show(s.simple().content("USE "+e.database+" database").theme(r.theme).position("bottom right")),t.currentDatabase=e.database),t.currentTable=e.name,i("tableSiedenav").open()},t.$on("handleBroadcastDatabases",function(){e.reLoad(!0),e.$applyAsync()}),e.updateDS=function(){n.databaseStructure(function(e){a.reload()},!0)},e.rightMenuProcessTable=function(e,a,r,i){console.log("rightMenuProcessTable",e,a,r),"InsertSQLDrop"==e&&(-1!==r.indexOf(".")&&(r='"'+r+'"'),t.$emit("handleBroadcastInsertInActive",{value:"DROP TABLE IF EXISTS "+a+"."+r})),"InsertName"==e&&t.$emit("handleBroadcastInsertInActive",{value:a+"."+r}),"InsertSQLDescribe"==e&&n.query("SHOW CREATE TABLE "+a+'."'+r+'"').then(function(e){var a=window.sqlFormatter.format(e.data[0].statement);t.$emit("handleBroadcastInsertInActive",{value:a})}),"OpenTables"==e&&(window.location="/#/database/"+a+"/table/"+r),"InsertDescribe"==e&&n.query("SELECT * FROM system.columns WHERE database='"+a+"' AND table='"+r+"'").then(function(e){var n=[],i=[];e.data.forEach(function(e){n.push(e.name),"Date"==e.type&&i.push(e.name+"=today()")}),-1!==r.indexOf(".")&&(r='"'+r+'"');var s="\nSELECT\n "+n.join(",\n ")+"\nFROM\n "+a+"."+r+"\n";i.length&&(s=s+"\nWHERE\n "+i.join("\n AND \n")),s+="\nLIMIT 100\n\n",console.log(s),t.$emit("handleBroadcastInsertInActive",{value:s})})},e.showAlertDatabaseStructure=function(e){o.show(o.alert().clickOutsideToClose(!0).title("Error on load database structure").textContent(e).ariaLabel("Error on load database structure").ok("OK")).then(function(e){n.clear(),a.go("login")})},e.reLoad=function(a){e.vars.loaded=!1,e.vars.error=!1,e.vars.databases=[],t.isInitDatabaseStructure=!1,n.fetchQuery("SELECT 1").then(function(r){e.$applyAsync(),n.databaseStructure(function(a){console.log("isInitDatabaseStructure-true"),t.isInitDatabaseStructure=Date.now(),e.$applyAsync(),console.log("databaseStructure - done");var n=a.getFields();e.vars.databases=a.getTables().reduce(function(e,t){var a=[{active:!0,value:"Select",key:"OpenTables",icon:"arrow-expand",db:t.database}],r=[{active:!0,value:"Open table",key:"OpenTables",icon:"arrow-expand",db:t.database,table:t.name},{active:!0,value:"Code Select from",key:"InsertDescribe",icon:"format-size",db:t.database,table:t.name},{active:!0,value:"Insert table name",key:"InsertName",icon:"bing",db:t.database,table:t.name},{active:!0,value:"Make SQL Describe",key:"InsertSQLDescribe",icon:"border-vertical",db:t.database,table:t.name},{active:!0,value:"Make SQL Drop",key:"InsertSQLDrop",icon:"delete",db:t.database,table:t.name}],i="table";t.engine.match(/Dictionary.*/)&&(i="library"),t.engine.match(/Distributed.*/)&&(i="soundcloud"),t.engine.match(/AggregatingMergeTree.*/)&&(i="cube"),t.engine.match(/MaterializedView.*/)&&(i="border-bottom"),t.engine.match(/SummingMergeTree.*/)&&(i="table-row-plus-after"),t.engine.match(/CollapsingMergeTree.*/)&&(i="table-row-height"),t.engine.match(/$Merge^/)&&(i="source-fork"),t.active=!0,t.classEngine=i,t.rightMenuListTable=r;var s=!0,o=!1,c=void 0;try{for(var l,d=e[Symbol.iterator]();!(s=(l=d.next()).done);s=!0){var u=l.value;if("-"!==t.name&&u.name==t.database)return u.tables.push({active:!0,database:t.database,name:t.name,engine:t.engine,classEngine:t.classEngine,fields:n[t.database+"."+t.name],rightMenuList:t.rightMenuListTable}),e}}catch(m){o=!0,c=m}finally{try{!s&&d["return"]&&d["return"]()}finally{if(o)throw c}}return[].concat(_toConsumableArray(e),[{name:t.database,rightMenuList:a,tables:[{active:!0,database:t.database,name:t.name,engine:t.engine,classEngine:t.classEngine,rightMenuList:t.rightMenuListTable,fields:n[t.database+"."+t.name]}]}])},[]),e.selectDatabase(e.vars.databases[0]),a.getDatabases().forEach(function(t){var a=!1;e.vars.databases.forEach(function(e){e.name==t.name&&(a=!0)}),a||e.vars.databases.push({name:t.name,tables:[],active:!0})}),c(function(){e.vars.loaded=!0,e.vars.error=!1,$("#sideBarMetismenu").metisMenu()},100)},a)},function(t){e.showAlertDatabaseStructure(t)})},e.reLoad()}e.module(t.app.name).controller("SidebarController",a),a.$inject=["$scope","$rootScope","$state","API","ThemeService","$mdSidenav","$mdToast","$mdDialog","$timeout","localStorageService"]}(angular,smi2),function(e,t){function a(a,n,r,i,s){a.user=r.getConnectionInfo().name,a.themes=i.list,a.isChrome=/Chrome/.test(navigator.userAgent),a.vars={disable_exit:window.global_tabix_disable_exit,hideExitButton:!window.global_tabix_disable_exit},a.help=function(a){function n(e,a){e.vars={version:t.app.version,buildDate:t.app.buildDate},e.hide=function(){a.hide()},e.cancel=function(){a.cancel()},e.answer=function(e){a.hide(e)}}n.$inject=["$scope","$mdDialog"],s.show({controller:n,templateUrl:"app/base/helpDialogRu.html",parent:e.element(document.body),targetEvent:a,clickOutsideToClose:!0})},a.logout=function(){r.clear(),n.go("login")},a.setUiTheme=function(e){i.set(e.name),window.location.reload()}}e.module(t.app.name).controller("HeaderController",a),a.$inject=["$scope","$state","API","ThemeService","$mdDialog"]}(angular,smi2),angular.module("ui.ace",[]).constant("uiAceConfig",{}).directive("uiAce",["uiAceConfig",function(e){if(angular.isUndefined(window.ace))throw new Error("ui-ace need ace to work... (o rly?)");return{restrict:"EA",link:function(t,a,n){var r=e.ace||{},i=angular.extend({},r,t.$eval(n.uiAce)),s=window.ace.edit(a[0]);console.time("Ace Load"),i.onLoad(s),console.timeEnd("Ace Load"),a.on("$destroy",function(){s.session.$stopWorker(),s.destroy()}),t.$watch(function(){return[a[0].offsetWidth,a[0].offsetHeight]},function(){s.resize(),s.renderer.updateFull()},!0)}}}]),/* - * Copyright (c) 2017. Smi2 - */ -angular.module(smi2.app.name).directive("pivot",[function(){return{restrict:"AE",scope:{data:"=",config:"=",editMode:"="},link:function(e,t,a){var n=$.extend($.pivotUtilities.renderers);null==e.config&&(e.config={rows:[],cols:[]}),e.renderPivotTable=function(){$(t).pivot(e.data,{renderers:n,rendererName:"Table",cols:e.config.cols,rows:e.config.rows,onRefresh:function(t){var a=JSON.parse(JSON.stringify(t));delete a.aggregators,delete a.renderers,delete a.derivedAttributes,delete a.rendererOptions,delete a.localeStrings,e.config=a,e.$apply()}})},e.renderPivotUITable=function(){$(t).pivotUI(e.data)},e.$watch("scope.editMode",function(t,a){console.log("watch"+e.editMode),t&&(e.editMode?e.renderPivotUITable():e.renderPivotTable())},!0),e.renderPivotUITable()}}}]),/** - * ng-handsontable 0.13.0 - * - * Copyright 2012-2015 Marcin Warpechowski - * Copyright 2015 Handsoncode sp. z o.o. - * Licensed under the MIT license. - * https://github.com/handsontable/ngHandsontable - * Date: Wed Oct 26 2016 10:00:05 GMT+0200 (CEST) -*/ -document.all&&!document.addEventListener&&(document.createElement("hot-table"),document.createElement("hot-column"),document.createElement("hot-autocomplete")),angular.module("ngHandsontable.services",[]),angular.module("ngHandsontable.directives",[]),angular.module("ngHandsontable",["ngHandsontable.services","ngHandsontable.directives"]),Handsontable.hooks.add("afterContextMenuShow",function(){Handsontable.EventManager.isHotTableEnv=!1}),function(){function e(e){return{parseAutoComplete:function(t,a,n){t.source=function(r,i){var s=this.instance.getSelected()[0],o=[],c=a[s];if(c){var l=t.optionList;if(l&&l.object){if(angular.isArray(l.object))o=l.object;else{var d=e(l.object)(c);if(angular.isArray(d))if(n)for(var u=0,m=d.length;m>u;u++){var h=d[u][l.property];null!==h&&void 0!==h&&o.push(h)}else o=d;else o=d}i(o)}}}}}}e.$inject=["$parse"],angular.module("ngHandsontable.services").factory("autoCompleteFactory",e)}(),function(){function e(){var e={};return{getInstance:function(t){return e[t]},registerInstance:function(t,a){e[t]=a},removeInstance:function(t){e[t]=void 0}}}e.$inject=[],angular.module("ngHandsontable.services").factory("hotRegisterer",e)}(),function(){function e(e){return e.replace(/[A-Z]/g,function(e){return"-"+e.charAt(0).toLowerCase()})}function t(e){return e.substr(0,1).toUpperCase()+e.substr(1,e.length-1)}function a(a){return{containerClassName:"handsontable-container",initializeHandsontable:function(e,t){var n,r=document.createElement("div");return r.className=this.containerClassName,t.hotId&&(r.id=t.hotId),e[0].appendChild(r),n=new Handsontable(r,t),t.hotId&&a.registerInstance(t.hotId,n),n},updateHandsontableSettings:function(e,t){e&&e.updateSettings(t)},renderHandsontable:function(e){e&&e.render()},mergeSettingsFromScope:function(e,t){var a,n,r,i=angular.extend({},t);for(e=e||{},angular.extend(i,t.settings||{}),a=this.getAvailableSettings(),n=0,r=a.length;r>n;n++)"undefined"!=typeof i[a[n]]&&(e[a[n]]=i[a[n]]);return e},mergeHooksFromScope:function(e,a){var n,r,i,s,o=angular.extend({},a);for(e=e||{},angular.extend(o,a.settings||{}),n=this.getAvailableHooks(),r=0,i=n.length;i>r;r++)s="on"+t(n[r]),("function"==typeof o[n[r]]||"function"==typeof o[s])&&(e[n[r]]=o[n[r]]||o[s]);return e},trimScopeDefinitionAccordingToAttrs:function(e,t){for(var a in e)e.hasOwnProperty(a)&&void 0===t[a]&&void 0===t[e[a].substr(1,e[a].length)]&&delete e[a];return e},getTableScopeDefinition:function(){var e={};return this.applyAvailableSettingsScopeDef(e),this.applyAvailableHooksScopeDef(e),e.datarows="=",e.dataschema="=",e.observeDomVisibility="=",e},getColumnScopeDefinition:function(){var e={};return this.applyAvailableSettingsScopeDef(e),e.data="@",e},applyAvailableSettingsScopeDef:function(e){var t,a,n;for(t=this.getAvailableSettings(),a=0,n=t.length;n>a;a++)e[t[a]]="=";return e},applyAvailableHooksScopeDef:function(e){var a,n,r;for(a=this.getAvailableHooks(),n=0,r=a.length;r>n;n++)e[a[n]]="=on"+t(a[n]);return e},getAvailableSettings:function(t){var a=Object.keys(Handsontable.DefaultSettings.prototype);return-1===a.indexOf("contextMenuCopyPaste")&&a.push("contextMenuCopyPaste"),-1===a.indexOf("handsontable")&&a.push("handsontable"),a.indexOf("settings")>=0&&a.splice(a.indexOf("settings"),1),t&&(a=a.map(e)),a},getAvailableHooks:function(t){var a=Handsontable.hooks.getRegistered();return t&&(a=a.map(function(t){return"on-"+e(t)})),a}}}a.$inject=["hotRegisterer"],angular.module("ngHandsontable.services").factory("settingFactory",a)}(),function(){function e(){return{restrict:"EA",scope:!0,require:"^hotColumn",link:function(e,t,a,n){var r=a.datarows;n.setColumnOptionList(r)}}}e.$inject=[],angular.module("ngHandsontable.directives").directive("hotAutocomplete",e)}(),function(){function e(e){return{restrict:"EA",require:"^hotTable",scope:{},controller:["$scope",function(e){this.setColumnOptionList=function(t){e.column||(e.column={});var a={},n=t.match(/^\s*([\s\S]+?)\s+in\s+([\s\S]+?)\s*$/);n?(a.property=n[1],a.object=n[2]):a.object=t.split(","),e.column.optionList=a}}],compile:function(t,a){var n=this;return this.scope=e.trimScopeDefinitionAccordingToAttrs(e.getColumnScopeDefinition(),a),angular.forEach(Object.keys(this.scope),function(e){n.$$isolateBindings[e]={attrName:e,collection:!1,mode:"data"===e?"@":"=",optional:!1}}),function(t,a,n,r){var i={};angular.forEach(Object.keys(n),function(e){"$"!==e.charAt(0)&&""===n[e]&&(i[e]=!0)}),e.mergeSettingsFromScope(i,t),t.column||(t.column={}),angular.extend(t.column,i),r.setColumnSetting(t.column),t.$on("$destroy",function(){r.removeColumnSetting(t.column)})}}}}e.$inject=["settingFactory"],angular.module("ngHandsontable.directives").directive("hotColumn",e)}(),function(){function e(e,t,a,n){return{restrict:"EA",scope:{},priority:-400,controller:["$scope",function(t){this.setColumnSetting=function(a){t.htSettings||(t.htSettings={}),t.htSettings.columns||(t.htSettings.columns=[]),t.htSettings.columns.push(a),e.updateHandsontableSettings(t.hotInstance,t.htSettings)},this.removeColumnSetting=function(a){t.htSettings.columns.indexOf(a)>-1&&(t.htSettings.columns.splice(t.htSettings.columns.indexOf(a),1),e.updateHandsontableSettings(t.hotInstance,t.htSettings))}}],compile:function(r,i){var s,o=this;return this.scope=e.trimScopeDefinitionAccordingToAttrs(e.getTableScopeDefinition(),i),s=Object.keys(this.scope),angular.forEach(s,function(e){var t=o.scope[e].charAt(0);o.$$isolateBindings[e]={attrName:o.scope[e].length>1?o.scope[e].substr(1,o.scope[e].length):e,collection:"datarows"===e,mode:t,optional:!1}}),function(r,i,o){if(r.settings=n(o.settings)(r.$parent),r.htSettings||(r.htSettings={}),angular.forEach(Object.keys(o),function(e){"$"!==e.charAt(0)&&""===o[e]&&(r.htSettings[e]=!0)}),e.mergeSettingsFromScope(r.htSettings,r),e.mergeHooksFromScope(r.htSettings,r),r.htSettings.data||(r.htSettings.data=r.datarows),r.htSettings.dataSchema=r.dataschema,r.htSettings.hotId=o.hotId,r.htSettings.observeDOMVisibility=r.observeDomVisibility,r.htSettings.columns)for(var c=0,l=r.htSettings.columns.length;l>c;c++){var d=r.htSettings.columns[c];if("autocomplete"===d.type&&d.optionList){if("string"==typeof d.optionList){var u={},m=d.optionList.match(/^\s*([\s\S]+?)\s+in\s+([\s\S]+?)\s*$/);m?(u.property=m[1],u.object=m[2]):u.object=u,d.optionList=u}t.parseAutoComplete(d,r.datarows,!0)}}var h=r.htSettings.afterChange;r.htSettings.afterChange=function(){h&&h.apply(this,arguments),a.$$phase||r.$apply()},r.hotInstance=e.initializeHandsontable(i,r.htSettings),angular.forEach(s,function(t){r.$watch(t,function(a,n){void 0!==a&&("datarows"===t?r.hotInstance.getSettings().data===a?e.renderHandsontable(r.hotInstance):(r.hotInstance.loadData(a),r.htSettings.data=a):a!==n&&(r.htSettings[t]=a,e.updateHandsontableSettings(r.hotInstance,r.htSettings)))},["datarows","columns","rowHeights","colWidths","rowHeaders","colHeaders"].indexOf(t)>=0)})}}}}e.$inject=["settingFactory","autoCompleteFactory","$rootScope","$parse"],angular.module("ngHandsontable.directives").directive("hotTable",e),angular.module("ngHandsontable.directives").directive("hotAutoDestroy",["hotRegisterer",function(e){return{restrict:"A",link:function(t,a,n){a.on("$destroy",function(){try{var t=e.getInstance(n.hotId);t?(console.info("hotInstance.destroy();"),t.destroy()):console.log("Failed to destroy hot-instance")}catch(a){console.log(a)}})}}}])}(),function(e,t){function a(e){return function(t,a,n){var r=e(n.ngRightClick);a.bind("contextmenu",function(e){t.$apply(function(){e.preventDefault(),r(t,{$event:e})})})}}e.module(t.app.name).directive("ngRightClick",a),a.$inject=["$parse"]}(angular,smi2),function(e,t){function a(){return{restrict:"A",require:"mdMenu",link:function(t,a,n,r){t.$mdOpenMousepointMenu=function(t){var a=e.element(t.currentTarget).offset();r.offsets=function(){return{left:t.pageX-a.left,top:t.pageY-a.top+8}},r.open(t)}}}}e.module(t.app.name).directive("mousepointMenu",a)}(angular,smi2),/** - * gridstack-angular - Angular Gridstack.js directive - * @version v0.6.0-dev - * @author Kevin Dietrich - * @link https://github.com/kdietrich/gridstack-angular#readme - * @license MIT - */ -function(){angular.module("gridstack-angular",[]);var e=angular.module("gridstack-angular");e.controller("GridstackController",["$scope",function(e){var t=this;e.$watch("staticGrid",function(e,a){e=!e,e?t.gridstackHandler.enable():t.gridstackHandler.disable(),t.gridstackHandler.commit()},!0),this.init=function(e,a){return t.gridstackHandler=e.gridstack(a).data("gridstack"),t.gridstackHandler},this.removeItem=function(e){return t.gridstackHandler?t.gridstackHandler.removeWidget(e,!1):null},this.addItem=function(e){return t.gridstackHandler?(t.gridstackHandler.makeWidget(e),e):null}}])}(),function(){var e=angular.module("gridstack-angular");e.directive("gridstack",["$timeout",function(e){return{restrict:"A",controller:"GridstackController",controllerAs:"$gridstack",bindToController:{onChange:"&",onDragStart:"&",onDragStop:"&",onResizeStart:"&",onResizeStop:"&",gridstackHandler:"=?",options:"=",staticGrid:"="},link:function(t,a,n,r,i){r.init(a,r.options),a.on("change",function(a,n){e(function(){t.$apply(),r.onChange({event:a,items:n})})}),a.on("dragstart",function(e,t){r.onDragStart({event:e,ui:t})}),a.on("dragstop",function(a,n){e(function(){t.$apply(),r.onDragStop({event:a,ui:n})})}),a.on("resizestart",function(e,t){r.onResizeStart({event:e,ui:t})}),a.on("resizestop",function(a,n){e(function(){t.$apply(),r.onResizeStop({event:a,ui:n})})})}}}])}(),function(){var e=angular.module("gridstack-angular");e.directive("gridstackItem",["$timeout",function(e){return{restrict:"A",require:"^gridstack",scope:{gridstackItem:"=",onItemAdded:"&",onItemRemoved:"&",gsItemId:"=?",gsItemX:"=",gsItemY:"=",gsItemWidth:"=",gsItemHeight:"=",gsItemAutopos:"="},link:function(t,a,n,r){t.gsItemId&&a.attr("data-gs-id",t.gsItemId),a.attr("data-gs-x",t.gsItemX),a.attr("data-gs-y",t.gsItemY),a.attr("data-gs-width",t.gsItemWidth),a.attr("data-gs-height",t.gsItemHeight),a.attr("data-gs-auto-position",t.gsItemAutopos);var i=(r.addItem(a),a.data("_gridstack_node"));e(function(){t.onItemAdded({item:i})}),t.$watchGroup(["gsItemX","gsItemY","gsItemWidth","gsItemHeight"],function(){(Number(a.attr("data-gs-x"))!==t.gsItemX||Number(a.attr("data-gs-y"))!==t.gsItemY||Number(a.attr("data-gs-width"))!==t.gsItemWidth||Number(a.attr("data-gs-height"))!==t.gsItemHeight)&&r.gridstackHandler.update(a,t.gsItemX,t.gsItemY,t.gsItemWidth,t.gsItemHeight)}),t.$watch(function(){return a.attr("data-gs-id")},function(e){t.gsItemId=e}),t.$watch(function(){return a.attr("data-gs-x")},function(e){t.gsItemX=Number(e)}),t.$watch(function(){return a.attr("data-gs-y")},function(e){t.gsItemY=Number(e)}),t.$watch(function(){return a.attr("data-gs-width")},function(e){t.gsItemWidth=Number(e)}),t.$watch(function(){return a.attr("data-gs-height")},function(e){t.gsItemHeight=Number(e)}),a.bind("$destroy",function(){var e=a.data("_gridstack_node");t.onItemRemoved({item:e}),r.removeItem(a)})}}}])}(),/* - * Licensed under the Apache License, Version 2.0 Copyright 2017 Igor Strykhar,Ivan Kudinov,SMI2 LLC and other contributors - */ -function(e,t){function a(t,a,n){var r="";if("echarts"==t.draw.library){var i="macarons";t.isDark&&(i="dark"),t.draw.chart=echarts.init(a[0],i),r=!1}if("plotly"==t.draw.library&&(t.element=e.element('
 
'),r=!1),"c3"==t.draw.library){var s=document.createElement("div");t.draw.bindto=s,a[0].appendChild(s),r=!1}return"text"==t.draw.library&&(t.element=e.element('
 
'),r=!1),"d3"==t.draw.library&&console.info("DW:d3"),"gmaps"==t.draw.library&&(t.element=e.element('
 
'),r=!1),console.group("widget.draw.preProcessor"),console.time("widget.draw.preProcessor time took"),t.draw.preProcessor instanceof Function&&t.draw.preProcessor(),console.timeEnd("widget.draw.preProcessor time took"),console.groupEnd(),r}function n(t,n){return function(r,i,s){r.widget.type;if(console.time("drawWidget.buildLinkFunc"),r.widget.isDark=r.isdark,r.widget.preProcessor instanceof Function&&r.widget.preProcessor(),r.widget.error||r.widget.textformat||r.widget.text||r.widget.empty)return console.log("widget Have Error",r.widget.error),r.widget.error&&i.html("
"+r.widget.error+"
"),r.widget.text&&i.html("
"+r.widget.text+"
"),r.widget.empty&&i.html("NO DATA"),void i.addClass("grid-monospace");if("table"==r.widget.type&&(r.widget.element=e.element('
')),"draw"==r.widget.type){r.widget.element=!1;var o=a(r.widget,i,n);o&&(r.widget.element=e.element(o))}"pivot"==r.widget.type&&(r.widget.element=e.element('')),r.widget.element?(i.append(r.widget.element),t(r.widget.element)(r),r.widget.element.on("$destroy",r.widget.destroy(r.widget))):i.on("$destroy",r.widget.destroy(r.widget)),r.widget.postProcessor instanceof Function&&r.widget.postProcessor(),r.$watch(function(){return[i[0].offsetWidth,i[0].offsetHeight].join("x")},function(e){r.widget.scheduledResize()}),r.events={resize:function(e,t){n(function(){t.widget.scheduledResize()},300)}},n(function(){r.widget.scheduledResize()},300),console.timeEnd("drawWidget.buildLinkFunc")}}e.module(t.app.name).directive("drawWidget",["$compile","$timeout",function(e,t){return{restrict:"EA",template:'
',scope:{widget:"=widget",isdark:"=isdark"},replace:!0,link:n(e,t)}}])}(angular,smi2),angular.module("angularResizable",[]).directive("resizable",function(){function e(e){void 0===t?(t=e,setTimeout(function(){t(),t=void 0},100)):t=e}var t;return{restrict:"AE",scope:{rDirections:"=",rCenteredX:"=",rCenteredY:"=",rWidth:"=",rHeight:"=",rFlex:"=",rGrabber:"@",rDisabled:"@",rNoThrottle:"=",resizable:"@"},link:function(t,a,n){if("false"!==t.resizable){var r="flexBasis"in document.documentElement.style?"flexBasis":"webkitFlexBasis"in document.documentElement.style?"webkitFlexBasis":"msFlexPreferredSize"in document.documentElement.style?"msFlexPreferredSize":"flexBasis";t.$watch("rWidth",function(e){a[0].style[t.rFlex?r:"width"]=e!==!1?e+"px":""}),t.$watch("rHeight",function(e){a[0].style[t.rFlex?r:"height"]=e!==!1?e+"px":""}),a.addClass("resizable");var i,s,o,c,l,d=window.getComputedStyle(a[0],null),u=t.rDirections||["right"],m=t.rCenteredX?2:1,h=t.rCenteredY?2:1,p=t.rGrabber?t.rGrabber:"",g={},f=function(e){g.width=!1,g.height=!1,"x"===l?g.width=parseInt(a[0].style[t.rFlex?r:"width"]):g.height=parseInt(a[0].style[t.rFlex?r:"height"]),g.id=a[0].id,g.evt=e},b=function(e){return e.touches?e.touches[0].clientX:e.clientX},v=function(e){return e.touches?e.touches[0].clientY:e.clientY},y=function(n){function d(){t.$emit("angular-resizable.resizing",g)}var u,p="x"===l?o-b(n):o-v(n);switch(c){case"top":u=t.rFlex?r:"height",a[0].style[u]=s+p*h+"px";break;case"bottom":u=t.rFlex?r:"height",a[0].style[u]=s-p*h+"px";break;case"right":u=t.rFlex?r:"width",a[0].style[u]=i-p*m+"px";break;case"left":u=t.rFlex?r:"width",a[0].style[u]=i+p*m+"px"}f(n),t.rNoThrottle?d():e(d)},w=function C(e){f(),t.$emit("angular-resizable.resizeEnd",g),t.$apply(),document.removeEventListener("mouseup",C,!1),document.removeEventListener("mousemove",y,!1),document.removeEventListener("touchend",C,!1),document.removeEventListener("touchmove",y,!1),a.removeClass("no-transition")},k=function(e){var n={},i=!1,s=!1;n.width=parseInt(a[0].style[t.rFlex?r:"width"]),n.height=parseInt(a[0].style[t.rFlex?r:"height"]),"right"==c&&(n.width>10?(t.preState=n,i=0,s=0):(t.preState&&t.preState.width||(t.preState.width=100),s=t.preState.height,i=t.preState.width)),"bottom"==c&&(n.height>10?(t.preState=n,s=0):(t.preState&&t.preState.height||(t.preState.height=100),s=t.preState.height,i=t.preState.width)),i!==!1&&(a[0].style[t.rFlex?r:"width"]=i+"px"),s!==!1&&(a[0].style[t.rFlex?r:"height"]=s+"px"),t.$apply()},x=function(e,n){c=n,l="left"===c||"right"===c?"x":"y",o="x"===l?b(e):v(e),i=parseInt(d.getPropertyValue("width")),s=parseInt(d.getPropertyValue("height")),a.addClass("no-transition"),document.addEventListener("mouseup",w,!1),document.addEventListener("mousemove",y,!1),document.addEventListener("touchend",w,!1),document.addEventListener("touchmove",y,!1),e.stopPropagation&&e.stopPropagation(),e.preventDefault&&e.preventDefault(),e.cancelBubble=!0,e.returnValue=!1,f(e),t.$emit("angular-resizable.resizeStart",g),t.$apply()};u.forEach(function(e){var n=document.createElement("div");n.setAttribute("class","rg-"+e),n.innerHTML=p,a[0].appendChild(n),n.ondragstart=function(){return!1};var r=function(a){var n="true"===t.rDisabled;n||1!==a.which&&!a.touches||x(a,e)};n.addEventListener("dblclick",k,!1),n.addEventListener("mousedown",r,!1),n.addEventListener("touchstart",r,!1)})}}}});var csvImport=angular.module("ngCsvImport",[]);csvImport.directive("ngCsvImport",function(){return{restrict:"E",transclude:!0,replace:!0,scope:{content:"=?",header:"=?",headerVisible:"=?",separator:"=?",separatorVisible:"=?",result:"=?",encoding:"=?",encodingVisible:"=?",accept:"=?",acceptSize:"=?",acceptSizeExceedCallback:"=?",callback:"=?",mdButtonClass:"@?",mdInputClass:"@?",mdButtonTitle:"@?",mdSvgIcon:"@?",uploadButtonLabel:"="},template:function(e,t){var a=angular.isDefined(t.material),n=angular.isDefined(t.multiple);return'
Header
'+(a?'
':'')+'
Encoding
{{encoding}}
Seperator
'+(a?' {{mdButtonTitle}}':"")+"
"},link:function(e,t,a){if(e.separatorVisible=!!e.separatorVisible,e.headerVisible=!!e.headerVisible,e.acceptSize=e.acceptSize||Number.POSITIVE_INFINITY,e.material=angular.isDefined(a.material),e.multiple=angular.isDefined(a.multiple),e.multiple)throw new Error("Multiple attribute is not supported yet.");var n=angular.element(t[0].querySelector('input[type="file"]')),r=angular.element(t[0].querySelector("md-input-container"));if(e.material&&n){if(n.removeClass("ng-show"),n.addClass("ng-hide"),r){var i=angular.element(r[0].querySelector("div.md-errors-spacer"));i&&i.remove()}e.onClick=function(){n.click()}}angular.element(t[0].querySelector(".separator-input")).on("keyup",function(t){if(null!=e.content){var a={csv:e.content,header:e.header,separator:t.target.value,encoding:e.encoding};e.result=s(a),e.$apply(),"function"==typeof e.callback&&e.callback(t)}}),t.on("change",function(t){if(t.target.files&&t.target.files.length){if(t.target.files[0].size>e.acceptSize)return void("function"==typeof e.acceptSizeExceedCallback&&e.acceptSizeExceedCallback(t.target.files[0]));e.filename=t.target.files[0].name;var a=new FileReader;if(a.onload=function(a){e.$apply(function(){var n={csv:a.target.result.replace(/\r\n|\r/g,"\n"),header:e.header,separator:e.separator};e.content=n.csv,e.result=s(n),e.result.filename=e.filename,e.$$postDigest(function(){"function"==typeof e.callback&&e.callback(t)})})},"file"!==t.target.type||null==t.target.files&&null==t.srcElement.files){if(null!=e.content){var n={csv:e.content,header:!e.header,separator:e.separator};e.result=s(n),e.$$postDigest(function(){"function"==typeof e.callback&&e.callback(t)})}}else a.readAsText((t.srcElement||t.target).files[0],e.encoding)}});var s=function(e){var t=e.csv.split(new RegExp('\n(?![^"]*"(?:(?:[^"]*"){2})*[^"]*$)')),a=[],n=0,r=t[0].split(e.separator).length,i=[];e.header&&(i=t[0].split(e.separator),n=1);for(var s=n;s3e4&&(a=3e4),t.fetchQuery("SELECT now(),number,sin(number),sin(number),SHA1(toString(number)),SHA1(toString(number)) as xx from system.numbers limit "+a).then(function(t){var a="ch",n=new DataProvider(t,a);n.progressQuery="SQL";var r=new WidgetTable(n);e.w=r,e.vars.show=!0,e.vars.counter++,console.info("Load done",e.vars.counter,e.vars.show)})},e._widgetsx=[],e.removeResult=function(t,a,n){n.stopPropagation(),delete e.listDashboards[a]},e.inits=function(){e.listDashboards={}},e.inits(),e.moveWidget=function(){e.widgets[0].x=1,e.widgets[0].width=2,e.widgets[0].height=2},e.removeWidget=function(t){var a=e.widgets.indexOf(t);e.widgets.splice(a,1)},e.onChange=function(e,t){console.log("onChange event: "+e+" items:"+t)},e.onDragStart=function(e,t){console.log("onDragStart event: "+e+" ui:"+t)},e.onDragStop=function(e,t){console.log("onDragStop event: "+e+" ui:"+t)},e.onResizeStart=function(e,t){console.log("onResizeStart event: "+e+" ui:"+t)},e.onResizeStop=function(e,t){console.log("onResizeStop ",t.size)},e.onItemAdded=function(e){console.log("onItemAdded item: "+e)},e.onItemRemoved=function(e){console.log("onItemRemoved item: "+e)}}e.module(t.app.name).controller("DashController",a),a.$inject=["$scope","API","ThemeService","$interval","localStorageService","$mdDialog","$window","hotRegisterer"]}(angular,smi2),ace.define("ace/theme/dracula",["require","exports","module","ace/lib/dom"],function(e,t,a){t.isDark=!0,t.cssClass="ace-dracula",t.cssText="ace-dracula .ace_gutter {background: #282a36;color: rgb(144,145,148)}.ace-dracula .ace_print-margin {width: 1px;background: #e8e8e8}.ace-dracula {background-color: #282a36;color: #f8f8f2}.ace-dracula .ace_cursor {color: #f8f8f0}.ace-dracula .ace_marker-layer .ace_selection {background: #44475a}.ace-dracula.ace_multiselect .ace_selection.ace_start {box-shadow: 0 0 3px 0px #282a36;border-radius: 2px}.ace-dracula .ace_marker-layer .ace_step {background: rgb(198, 219, 174)}.ace-dracula .ace_marker-layer .ace_bracket {margin: -1px 0 0 -1px;border: 1px solid #3B3A32}.ace-dracula .ace_marker-layer .ace_active-line {background: #44475a}.ace-dracula .ace_gutter-active-line {background-color: #44475a}.ace-dracula .ace_marker-layer .ace_selected-word {border: 1px solid #44475a}.ace-dracula .ace_fold {background-color: #50fa7b;border-color: #f8f8f2}.ace-dracula .ace_keyword {color: #ff79c6}.ace-dracula .ace_constant.ace_language {color: #bd93f9}.ace-dracula .ace_constant.ace_numeric {color: #bd93f9}.ace-dracula .ace_constant.ace_character {color: #bd93f9}.ace-dracula .ace_constant.ace_character.ace_escape {color: #ff79c6}.ace-dracula .ace_constant.ace_other {color: #bd93f9}.ace-dracula .ace_support.ace_function {color: #8be9fd}.ace-dracula .ace_support.ace_constant {color: #6be5fd}.ace-dracula .ace_support.ace_class {font-style: italic;color: #66d9ef}.ace-dracula .ace_support.ace_type {font-style: italic;color: #66d9ef}.ace-dracula .ace_storage {color: #ff79c6}.ace-dracula .ace_storage.ace_type {font-style: italic;color: #8be9fd}.ace-dracula .ace_invalid {color: #F8F8F0;background-color: #ff79c6}.ace-dracula .ace_invalid.ace_deprecated {color: #F8F8F0;background-color: #bd93f9}.ace-dracula .ace_string {color: #f1fa8c}.ace-dracula .ace_comment {color: #6272a4}.ace-dracula .ace_variable {color: #50fa7b}.ace-dracula .ace_variable.ace_parameter {font-style: italic;color: #ffb86c}.ace-dracula .ace_entity.ace_other.ace_attribute-name {color: #50fa7b}.ace-dracula .ace_entity.ace_name.ace_function {color: #50fa7b}.ace-dracula .ace_entity.ace_name.ace_tag {color: #ff79c6}";var n=e("../lib/dom");n.importCssString(t.cssText,t.cssClass)}),ace.define("ace/mode/clickhouse",["require","exports","module","ace/lib/oop","ace/mode/text","ace/token_iterator","ace/mode/folding","ace/mode/clickhouse_FoldMode","ace/mode/clickhouse_highlight_rules"],function(e,t){var a=e("../lib/oop"),n=e("./text").Mode,r=e("./clickhouse_highlight_rules").ClickhouseHighlightRules,i=e("./clickhouse_FoldMode").FoldMode,s=e("./matching_brace_outdent").MatchingBraceOutdent,o=e("./behaviour/cstyle").CstyleBehaviour,c=function(){this.foldingRules=new i,this.$outdent=new s,this.$behaviour=new o,this.HighlightRules=r};a.inherits(c,n),function(){var t=this;this.lineCommentStart="--",this.getHighlightRule=function(){return t.session.$mode.$highlightRules},this.getCompletions=function(e,t,a,n){return t.$mode.$highlightRules.completions},this.$id="ace/mode/clickhouse",this.checkOutdent=function(e,t,a){return this.$outdent.checkOutdent(t,a)},this.autoOutdent=function(e,t,a){this.$outdent.autoOutdent(t,a)},this.findTokens=function(t,a,n){t=t.replace(/^(\r\n|\n|\r)/gm,"").replace(/(\r\n|\n|\r)$/gm,"");for(var r=e("ace/token_iterator").TokenIterator,i=e("ace/edit_session").EditSession,s=new i(t,this),o=new r(s,0,0),c=o.getCurrentToken(),l=[];c;){var d=c;if(d.row=o.getCurrentTokenRow(),d.col=o.getCurrentTokenColumn(),d.type==a&&(l.push(d),n))return d.value=d.value.toLowerCase(),d;c=o.stepForward()}return l},this.trim=function(e,t){return t!==!0&&"string"==typeof t&&t.length>0&&(e=e.replace("^("+t+")"," ").replace(t+"$"," "),e=e.replace(new RegExp("^"+t+"|"+t+"$","g")," ")),e},this.collapseAll=function(e){for(var t=e,a=t.foldWidgets,n=t.getLength(),r=0,i=r;n>i;i++)if(null==a[i]&&(a[i]=t.getFoldWidget(i)),"start"==a[i]){var s=t.getFoldWidgetRange(i);if(s&&s.end.row<=n&&s.start.row>=r){i=s.end.row;try{var o=t.addFold("...",s);o&&(o.collapseChildren=depth)}catch(t){}}}},this.replaceVars=function(e,t){var a={},n=this.fetchTokens(e);if(console.warn("Find tokens",n,t),n.vars.length>0)for(var r in n.vars){var i=n.vars[r],s=i;i=i.indexOf("{")>-1?i.replace("{","").replace("}",""):i.replace("$","").replace("@","").replace(":","");for(var o in t){var c=t[o];c.name.toLowerCase()==i.toLowerCase()&&(console.info(c.name.toLowerCase(),"==",i.toLowerCase()),e=e.replace(s,c.value))}}return{sql:e,tokens:n,vars:a}},this.fetchTokens=function(t){var a={groupby:[],where:[],vars:[],limit:-1},n=e("ace/token_iterator").TokenIterator,r=e("ace/edit_session").EditSession,i=new r(t,this);i.bgTokenizer.start(0);for(var s=new n(i,0,0),o=s.getCurrentToken();o;){var c=o;if(c.row=s.getCurrentTokenRow(),c.col=s.getCurrentTokenColumn(),"variable.language"==c.type&&c.value&&a.vars.push(c.value),"keyword"==c.type&&c.value.toLowerCase().includes("limit")!==!1){var l=c.value.toLowerCase().match(/LIMIT\W+(\d+)\W*\,\W*(\d+)/i);l||(l=c.value.toLowerCase().match(/LIMIT\W+(\d+)/i)),l[0]&&l[1]&&l[2]?a.limit={from:l[1],to:l[2]}:l[0]&&l[1]&&(a.limit={from:l[1],to:!1})}o=s.stepForward()}return console.info("Parse & Find tokens result",a),a},this.splitByTokens=function(t,a,n){var r=e("ace/token_iterator").TokenIterator,i=e("ace/edit_session").EditSession,s=e("ace/range").Range,o=new i(t,this);o.bgTokenizer.start(0);var c=new r(o,0,0),l=c.getCurrentToken();if(_.isUndefined(l)){var d=0;do d++,c=new r(o,d,0),l=c.getCurrentToken();while(100>d&&!l)}for(var u=[],m=0,h=0,p=!1,g=void 0,f=void 0;l;){var b=l;if(b.row=c.getCurrentTokenRow(),b.col=c.getCurrentTokenColumn(),b.type==a&&(n!==!0&&b.value==n||n===!0)){var v=0;n instanceof String&&(v=n.length),g=new s(m,h,b.row,b.col+v),f=o.getTextRange(g),m=b.row,h=b.col+v,f=this.trim(f,b.value),f.length>2&&("string"==typeof p&&(f=this.trim(f,p)),u.push({sql:f,range:g,keyword:p}),p=b.value)}l=c.stepForward()}return g=new s(m,h,Number.MAX_VALUE,Number.MAX_VALUE),f=o.getTextRange(g),f=this.trim(f,n),"string"==typeof p&&(f=this.trim(f,p)),f.length>2&&u.push({sql:f,range:g,keyword:p}),u}}.call(c.prototype),t.Mode=c}),ace.define("ace/ext/whitespace",["require","exports","module","ace/lib/lang"],function(e,t,a){var n=e("../lib/lang");t.$detectIndentation=function(e,t){function a(e){for(var t=0,a=e;ac;c++){var l=e[c];if(/^\s*[^*+\-\s]/.test(l)){if(" "==l[0])i++,s=-Number.MAX_VALUE;else{var d=l.match(/^ */)[0].length;if(d&&" "!=l[d]){var u=d-s;!(u>0)||s%u||d%u||(r[u]=(r[u]||0)+1),n[d]=(n[d]||0)+1}s=d}for(;o>c&&"\\"==l[l.length-1];)l=e[c++]}}for(var m=r.reduce(function(e,t){return e+t},0),h={score:0,length:0},p=0,c=1;12>c;c++){var g=a(c);1==c?(p=g,g=n[1]?.9:.8,n.length||(g=0)):g/=p,r[c]&&(g+=r[c]/m),g>h.score&&(h={score:g,length:c})}if(h.score&&h.score>1.4)var f=h.length;return i>p+1?((1==f||i/4>p||h.score<1.8)&&(f=void 0),{ch:" ",length:f}):p>i+1?{ch:" ",length:f}:void 0},t.detectIndentation=function(e){var a=e.getLines(0,1e3),n=t.$detectIndentation(a)||{};return n.ch&&e.setUseSoftTabs(" "==n.ch),n.length&&e.setTabSize(n.length),n},t.trimTrailingSpace=function(e,t){for(var a=e.getDocument(),n=a.getAllLines(),r=t?-1:0,i=0,s=n.length;s>i;i++){var o=n[i],c=o.search(/\s+$/);c>r&&a.removeInLine(i,c,o.length)}},t.convertIndentation=function(e,t,a){var r=e.getTabString()[0],i=e.getTabSize();a||(a=i),t||(t=r);for(var s=" "==t?t:n.stringRepeat(t,a),o=e.doc,c=o.getAllLines(),l={},d={},u=0,m=c.length;m>u;u++){var h=c[u],p=h.match(/^\s*/)[0];if(p){var g=e.$getStringScreenWidth(p)[0],f=Math.floor(g/i),b=g%i,v=l[f]||(l[f]=n.stringRepeat(s,f));v+=d[b]||(d[b]=n.stringRepeat(" ",b)),v!=p&&(o.removeInLine(u,0,p.length),o.insertInLine({row:u,column:0},v))}}e.setTabSize(a),e.setUseSoftTabs(" "==t)},t.$parseStringArg=function(e){var t={};/t/.test(e)?t.ch=" ":/s/.test(e)&&(t.ch=" ");var a=e.match(/\d+/);return a&&(t.length=parseInt(a[0],10)),t},t.$parseArg=function(e){return e?"string"==typeof e?t.$parseStringArg(e):"string"==typeof e.text?t.$parseStringArg(e.text):e:{}},t.commands=[{name:"detectIndentation",exec:function(e){t.detectIndentation(e.session)}},{name:"trimTrailingSpace",exec:function(e){t.trimTrailingSpace(e.session)}},{name:"convertIndentation",exec:function(e,a){var n=t.$parseArg(a);t.convertIndentation(e.session,n.ch,n.length)}},{name:"setIndentation",exec:function(e,a){var n=t.$parseArg(a);n.length&&e.session.setTabSize(n.length),n.ch&&e.session.setUseSoftTabs(" "==n.ch)}}]}),function(){ace.require(["ace/ext/whitespace"],function(){})}(),ace.define("ace/ext/statusbar",["require","exports","module","ace/lib/dom","ace/lib/lang"],function(e,t,a){var n=e("ace/lib/dom"),r=e("ace/lib/lang"),i=function(e,t){this.element=n.createElement("div"),this.element.className="ace_status-indicator",this.element.style.cssText="display: inline-block;",t.appendChild(this.element);var a=r.delayedCall(function(){this.updateStatus(e)}.bind(this)).schedule.bind(null,100);e.on("changeStatus",a),e.on("changeSelection",a),e.on("keyboardActivity",a)};(function(){this.updateStatus=function(e){function t(e,t){e&&a.push(e,t||"|")}var a=[];t(e.keyBinding.getStatusText(e)),e.commands.recording&&t("REC");var n=e.selection,r=n.lead;if(!n.isEmpty()){var i=e.getSelectionRange();t("("+(i.end.row-i.start.row)+":"+(i.end.column-i.start.column)+")"," ")}t(r.row+":"+r.column," "),n.rangeCount&&t("["+n.rangeCount+"]"," "),a.pop(),this.element.textContent=a.join("")}}).call(i.prototype),t.StatusBar=i}),function(){ace.require(["ace/ext/statusbar"],function(){})}(),ace.define("ace/ext/spellcheck",["require","exports","module","ace/lib/event","ace/editor","ace/config"],function(e,t,a){var n=e("../lib/event");t.contextMenuHandler=function(e){var t=e.target,a=t.textInput.getElement();if(t.selection.isEmpty()){var r=t.getCursorPosition(),i=t.session.getWordRange(r.row,r.column),s=t.session.getTextRange(i);if(t.session.tokenRe.lastIndex=0,t.session.tokenRe.test(s)){var o="",c=s+" "+o;a.value=c,a.setSelectionRange(s.length,s.length+1),a.setSelectionRange(0,0),a.setSelectionRange(0,s.length);var l=!1;n.addListener(a,"keydown",function d(){n.removeListener(a,"keydown",d),l=!0}),t.textInput.setInputHandler(function(e){if(console.log(e,c,a.selectionStart,a.selectionEnd),e==c)return"";if(0===e.lastIndexOf(c,0))return e.slice(c.length);if(e.substr(a.selectionEnd)==c)return e.slice(0,-c.length);if(e.slice(-2)==o){var n=e.slice(0,-2);if(" "==n.slice(-1))return l?n.substring(0,a.selectionEnd):(n=n.slice(0,-1),t.session.replace(i,n),"")}return e})}}};var r=e("../editor").Editor;e("../config").defineOptions(r.prototype,"editor",{spellcheck:{set:function(e){var a=this.textInput.getElement();a.spellcheck=!!e,e?this.on("nativecontextmenu",t.contextMenuHandler):this.removeListener("nativecontextmenu",t.contextMenuHandler)},value:!0}})}),function(){ace.require(["ace/ext/spellcheck"],function(){})}(),ace.define("ace/ext/menu_tools/element_generator",["require","exports","module"],function(e,t,a){a.exports.createOption=function(e){var t,a=document.createElement("option");for(t in e)e.hasOwnProperty(t)&&("selected"===t?a.setAttribute(t,e[t]):a[t]=e[t]);return a},a.exports.createCheckbox=function(e,t,a){var n=document.createElement("input");return n.setAttribute("type","checkbox"),n.setAttribute("id",e),n.setAttribute("name",e),n.setAttribute("value",t),n.setAttribute("class",a),t&&n.setAttribute("checked","checked"),n},a.exports.createInput=function(e,t,a){var n=document.createElement("input");return n.setAttribute("type","text"),n.setAttribute("id",e),n.setAttribute("name",e),n.setAttribute("value",t),n.setAttribute("class",a),n},a.exports.createLabel=function(e,t){var a=document.createElement("label");return a.setAttribute("for",t),a.textContent=e,a},a.exports.createSelection=function(e,t,n){var r=document.createElement("select");return r.setAttribute("id",e),r.setAttribute("name",e),r.setAttribute("class",n),t.forEach(function(e){r.appendChild(a.exports.createOption(e))}),r}}),ace.define("ace/ext/modelist",["require","exports","module"],function(e,t,a){function n(e){for(var t=c.text,a=e.split(/[\/\\]/).pop(),n=0;n +/g,">"),u=function(e,t,a){var r=n.createElement("div");r.innerHTML=d,this.element=r.firstChild,this.setSession=this.setSession.bind(this),this.$init(),this.setEditor(e)};(function(){this.setEditor=function(e){e.searchBox=this,e.renderer.scroller.appendChild(this.element),this.editor=e},this.setSession=function(e){this.searchRange=null,this.$syncOptions(!0)},this.$initElements=function(e){this.searchBox=e.querySelector(".ace_search_form"),this.replaceBox=e.querySelector(".ace_replace_form"),this.searchOption=e.querySelector("[action=searchInSelection]"),this.replaceOption=e.querySelector("[action=toggleReplace]"),this.regExpOption=e.querySelector("[action=toggleRegexpMode]"),this.caseSensitiveOption=e.querySelector("[action=toggleCaseSensitive]"),this.wholeWordOption=e.querySelector("[action=toggleWholeWords]"),this.searchInput=this.searchBox.querySelector(".ace_search_field"),this.replaceInput=this.replaceBox.querySelector(".ace_search_field"),this.searchCounter=e.querySelector(".ace_search_counter")},this.$init=function(){var e=this.element;this.$initElements(e);var t=this;i.addListener(e,"mousedown",function(e){setTimeout(function(){t.activeInput.focus()},0),i.stopPropagation(e)}),i.addListener(e,"click",function(e){var a=e.target||e.srcElement,n=a.getAttribute("action");n&&t[n]?t[n]():t.$searchBarKb.commands[n]&&t.$searchBarKb.commands[n].exec(t),i.stopPropagation(e)}),i.addCommandKeyListener(e,function(e,a,n){var r=c.keyCodeToString(n),s=t.$searchBarKb.findKeyCommand(a,r);s&&s.exec&&(s.exec(t),i.stopEvent(e))}),this.$onChange=r.delayedCall(function(){t.find(!1,!1)}),i.addListener(this.searchInput,"input",function(){t.$onChange.schedule(20)}),i.addListener(this.searchInput,"focus",function(){t.activeInput=t.searchInput,t.searchInput.value&&t.highlight()}),i.addListener(this.replaceInput,"focus",function(){t.activeInput=t.replaceInput,t.searchInput.value&&t.highlight()})},this.$closeSearchBarKb=new o([{bindKey:"Esc",name:"closeSearchBar",exec:function(e){e.searchBox.hide()}}]),this.$searchBarKb=new o,this.$searchBarKb.bindKeys({"Ctrl-f|Command-f":function(e){var t=e.isReplace=!e.isReplace;e.replaceBox.style.display=t?"":"none",e.replaceOption.checked=!1,e.$syncOptions(),e.searchInput.focus()},"Ctrl-H|Command-Option-F":function(e){e.replaceOption.checked=!0,e.$syncOptions(),e.replaceInput.focus()},"Ctrl-G|Command-G":function(e){e.findNext()},"Ctrl-Shift-G|Command-Shift-G":function(e){e.findPrev()},esc:function(e){setTimeout(function(){e.hide()})},Return:function(e){e.activeInput==e.replaceInput&&e.replace(),e.findNext()},"Shift-Return":function(e){e.activeInput==e.replaceInput&&e.replace(),e.findPrev()},"Alt-Return":function(e){e.activeInput==e.replaceInput&&e.replaceAll(),e.findAll()},Tab:function(e){(e.activeInput==e.replaceInput?e.searchInput:e.replaceInput).focus()}}),this.$searchBarKb.addCommands([{name:"toggleRegexpMode",bindKey:{win:"Alt-R|Alt-/",mac:"Ctrl-Alt-R|Ctrl-Alt-/"},exec:function(e){e.regExpOption.checked=!e.regExpOption.checked,e.$syncOptions()}},{name:"toggleCaseSensitive",bindKey:{win:"Alt-C|Alt-I",mac:"Ctrl-Alt-R|Ctrl-Alt-I"},exec:function(e){e.caseSensitiveOption.checked=!e.caseSensitiveOption.checked,e.$syncOptions()}},{name:"toggleWholeWords",bindKey:{win:"Alt-B|Alt-W",mac:"Ctrl-Alt-B|Ctrl-Alt-W"},exec:function(e){e.wholeWordOption.checked=!e.wholeWordOption.checked,e.$syncOptions()}},{name:"toggleReplace",exec:function(e){e.replaceOption.checked=!e.replaceOption.checked,e.$syncOptions()}},{name:"searchInSelection",exec:function(e){e.searchOption.checked=!e.searchRange,e.setSearchRange(e.searchOption.checked&&e.editor.getSelectionRange()),e.$syncOptions()}}]),this.setSearchRange=function(e){this.searchRange=e,e?this.searchRangeMarker=this.editor.session.addMarker(e,"ace_active-line"):this.searchRangeMarker&&(this.editor.session.removeMarker(this.searchRangeMarker),this.searchRangeMarker=null)},this.$syncOptions=function(e){n.setCssClass(this.replaceOption,"checked",this.searchRange),n.setCssClass(this.searchOption,"checked",this.searchOption.checked),this.replaceOption.textContent=this.replaceOption.checked?"-":"+",n.setCssClass(this.regExpOption,"checked",this.regExpOption.checked),n.setCssClass(this.wholeWordOption,"checked",this.wholeWordOption.checked),n.setCssClass(this.caseSensitiveOption,"checked",this.caseSensitiveOption.checked),this.replaceBox.style.display=this.replaceOption.checked?"":"none",this.find(!1,!1,e)},this.highlight=function(e){this.editor.session.highlight(e||this.editor.$search.$options.re),this.editor.renderer.updateBackMarkers()},this.find=function(e,t,a){var r=this.editor.find(this.searchInput.value,{skipCurrent:e,backwards:t,wrap:!0,regExp:this.regExpOption.checked,caseSensitive:this.caseSensitiveOption.checked,wholeWord:this.wholeWordOption.checked,preventScroll:a,range:this.searchRange}),i=!r&&this.searchInput.value;n.setCssClass(this.searchBox,"ace_nomatch",i),this.editor._emit("findSearchBox",{match:!i}),this.highlight(),this.updateCounter()},this.updateCounter=function(){var e=this.editor,t=e.$search.$options.re,a=0,n=0;if(t){var r=this.searchRange?e.session.getTextRange(this.searchRange):e.getValue(),i=e.session.doc.positionToIndex(e.selection.anchor);this.searchRange&&(i-=e.session.doc.positionToIndex(this.searchRange.start));for(var s,o=t.lastIndex=0;(s=t.exec(r))&&(a++,o=s.index,i>=o&&n++,!(a>l))&&(s[0]||(t.lastIndex=o+=1,!(o>=r.length))););}this.searchCounter.textContent=n+" of "+(a>l?l+"+":a)},this.findNext=function(){this.find(!0,!1)},this.findPrev=function(){this.find(!0,!0)},this.findAll=function(){var e=this.editor.findAll(this.searchInput.value,{regExp:this.regExpOption.checked,caseSensitive:this.caseSensitiveOption.checked,wholeWord:this.wholeWordOption.checked}),t=!e&&this.searchInput.value;n.setCssClass(this.searchBox,"ace_nomatch",t),this.editor._emit("findSearchBox",{match:!t}),this.highlight(),this.hide()},this.replace=function(){this.editor.getReadOnly()||this.editor.replace(this.replaceInput.value)},this.replaceAndFindNext=function(){this.editor.getReadOnly()||(this.editor.replace(this.replaceInput.value),this.findNext())},this.replaceAll=function(){this.editor.getReadOnly()||this.editor.replaceAll(this.replaceInput.value)},this.hide=function(){this.active=!1,this.setSearchRange(null),this.editor.off("changeSession",this.setSession),this.element.style.display="none",this.editor.keyBinding.removeKeyboardHandler(this.$closeSearchBarKb),this.editor.focus()},this.show=function(e,t){this.active=!0,this.editor.on("changeSession",this.setSession),this.element.style.display="",this.replaceOption.checked=t,e&&(this.searchInput.value=e),this.searchInput.focus(),this.searchInput.select(),this.editor.keyBinding.addKeyboardHandler(this.$closeSearchBarKb),this.$syncOptions(!0)},this.isFocused=function(){var e=document.activeElement;return e==this.searchInput||e==this.replaceInput}}).call(u.prototype),t.SearchBox=u,t.Search=function(e,t){var a=e.searchBox||new u(e);a.show(e.session.getTextRange(),t)}}),function(){ace.require(["ace/ext/searchbox"],function(){})}(),ace.define("ace/snippets",["require","exports","module","ace/lib/oop","ace/lib/event_emitter","ace/lib/lang","ace/range","ace/anchor","ace/keyboard/hash_handler","ace/tokenizer","ace/lib/dom","ace/editor"],function(e,t,a){var n=e("./lib/oop"),r=e("./lib/event_emitter").EventEmitter,i=e("./lib/lang"),s=e("./range").Range,o=e("./anchor").Anchor,c=e("./keyboard/hash_handler").HashHandler,l=e("./tokenizer").Tokenizer,d=s.comparePoints,u=function(){this.snippetMap={},this.snippetNameMap={}};(function(){n.implement(this,r),this.getTokenizer=function(){function e(e,t,a){return e=e.substr(1),/^\d+$/.test(e)&&!a.inFormatString?[{tabstopId:parseInt(e,10)}]:[{text:e}]}function t(e){return"(?:[^\\\\"+e+"]|\\\\.)"}return u.$tokenizer=new l({start:[{regex:/:/,onMatch:function(e,t,a){return a.length&&a[0].expectIf?(a[0].expectIf=!1,a[0].elseBranch=a[0],[a[0]]):":"}},{regex:/\\./,onMatch:function(e,t,a){var n=e[1];return"}"==n&&a.length?e=n:-1!="`$\\".indexOf(n)?e=n:a.inFormatString&&("n"==n?e="\n":"t"==n?e="\n":-1!="ulULE".indexOf(n)&&(e={changeCase:n,local:n>"a"})),[e]}},{regex:/}/,onMatch:function(e,t,a){return[a.length?a.shift():e]}},{regex:/\$(?:\d+|\w+)/,onMatch:e},{regex:/\$\{[\dA-Z_a-z]+/,onMatch:function(t,a,n){var r=e(t.substr(1),a,n);return n.unshift(r[0]),r},next:"snippetVar"},{regex:/\n/,token:"newline",merge:!1}],snippetVar:[{regex:"\\|"+t("\\|")+"*\\|",onMatch:function(e,t,a){a[0].choices=e.slice(1,-1).split(",")},next:"start"},{regex:"/("+t("/")+"+)/(?:("+t("/")+"*)/)(\\w*):?",onMatch:function(e,t,a){var n=a[0];return n.fmtString=e,e=this.splitRegex.exec(e),n.guard=e[1],n.fmt=e[2],n.flag=e[3],""},next:"start"},{regex:"`"+t("`")+"*`",onMatch:function(e,t,a){return a[0].code=e.splice(1,-1),""},next:"start"},{regex:"\\?",onMatch:function(e,t,a){a[0]&&(a[0].expectIf=!0)},next:"start"},{regex:"([^:}\\\\]|\\\\.)*:?",token:"",next:"start"}],formatString:[{regex:"/("+t("/")+"+)/",token:"regex"},{regex:"",onMatch:function(e,t,a){a.inFormatString=!0},next:"start"}]}),u.prototype.getTokenizer=function(){return u.$tokenizer},u.$tokenizer},this.tokenizeTmSnippet=function(e,t){return this.getTokenizer().getLineTokens(e,t).tokens.map(function(e){return e.value||e})},this.$getDefaultValue=function(e,t){if(/^[A-Z]\d+$/.test(t)){var a=t.substr(1);return(this.variables[t[0]+"__"]||{})[a]}if(/^\d+$/.test(t))return(this.variables.__||{})[t];if(t=t.replace(/^TM_/,""),e){var n=e.session;switch(t){case"CURRENT_WORD":var r=n.getWordRange();case"SELECTION":case"SELECTED_TEXT":return n.getTextRange(r);case"CURRENT_LINE":return n.getLine(e.getCursorPosition().row);case"PREV_LINE":return n.getLine(e.getCursorPosition().row-1);case"LINE_INDEX":return e.getCursorPosition().column;case"LINE_NUMBER":return e.getCursorPosition().row+1;case"SOFT_TABS":return n.getUseSoftTabs()?"YES":"NO";case"TAB_SIZE":return n.getTabSize();case"FILENAME":case"FILEPATH":return"";case"FULLNAME":return"Ace"}}},this.variables={},this.getVariableValue=function(e,t){return this.variables.hasOwnProperty(t)?this.variables[t](e,t)||"":this.$getDefaultValue(e,t)||""},this.tmStrFormat=function(e,t,a){var n=t.flag||"",r=t.guard;r=new RegExp(r,n.replace(/[^gi]/,""));var i=this.tokenizeTmSnippet(t.fmt,"formatString"),s=this,o=e.replace(r,function(){s.variables.__=arguments;for(var e=s.resolveVariables(i,a),t="E",n=0;n1?(v=t[t.length-1].length,b+=t.length-1):v+=e.length,y+=e}else e.start?e.end={row:b,column:v}:e.start={row:b,column:v}});var w=e.getSelectionRange(),k=e.session.replace(w,y),x=new m(e),C=e.inVirtualSelectionMode&&e.selection.index;x.addTabstops(c,w.start,k,C)},this.insertSnippet=function(e,t){var a=this;return e.inVirtualSelectionMode?a.insertSnippetForSelection(e,t):(e.forEachSelection(function(){a.insertSnippetForSelection(e,t)},null,{keepOrder:!0}),void(e.tabstopManager&&e.tabstopManager.tabNext()))},this.$getScope=function(e){var t=e.session.$mode.$id||"";if(t=t.split("/").pop(),"html"===t||"php"===t){"php"!==t||e.session.$mode.inlinePhp||(t="html");var a=e.getCursorPosition(),n=e.session.getState(a.row);"object"===("undefined"==typeof n?"undefined":_typeof(n))&&(n=n[0]),n.substring&&("js-"==n.substring(0,3)?t="javascript":"css-"==n.substring(0,4)?t="css":"php-"==n.substring(0,4)&&(t="php"))}return t},this.getActiveScopes=function(e){var t=this.$getScope(e),a=[t],n=this.snippetMap;return n[t]&&n[t].includeScopes&&a.push.apply(a,n[t].includeScopes),a.push("_"),a},this.expandWithTab=function(e,t){var a=this,n=e.forEachSelection(function(){return a.expandSnippetForSelection(e,t)},null,{keepOrder:!0});return n&&e.tabstopManager&&e.tabstopManager.tabNext(),n},this.expandSnippetForSelection=function(e,t){var a,n=e.getCursorPosition(),r=e.session.getLine(n.row),i=r.substring(0,n.column),s=r.substr(n.column),o=this.snippetMap;return this.getActiveScopes(e).some(function(e){var t=o[e];return t&&(a=this.findMatchingSnippet(t,i,s)),!!a},this),a?t&&t.dryRun?!0:(e.session.doc.removeInLine(n.row,n.column-a.replaceBefore.length,n.column+a.replaceAfter.length),this.variables.M__=a.matchBefore,this.variables.T__=a.matchAfter,this.insertSnippetForSelection(e,a.content),this.variables.M__=this.variables.T__=null,!0):!1},this.findMatchingSnippet=function(e,t,a){for(var n=e.length;n--;){var r=e[n];if((!r.startRe||r.startRe.test(t))&&(!r.endRe||r.endRe.test(a))&&(r.startRe||r.endRe))return r.matchBefore=r.startRe?r.startRe.exec(t):[""],r.matchAfter=r.endRe?r.endRe.exec(a):[""],r.replaceBefore=r.triggerRe?r.triggerRe.exec(t)[0]:"",r.replaceAfter=r.endTriggerRe?r.endTriggerRe.exec(a)[0]:"",r}},this.snippetMap={},this.snippetNameMap={},this.register=function(e,t){function a(e){return e&&!/^\^?\(.*\)\$?$|^\\b$/.test(e)&&(e="(?:"+e+")"),e||""}function n(e,t,n){return e=a(e),t=a(t),n?(e=t+e,e&&"$"!=e[e.length-1]&&(e+="$")):(e+=t,e&&"^"!=e[0]&&(e="^"+e)),new RegExp(e)}function r(e){e.scope||(e.scope=t||"_"),t=e.scope,s[t]||(s[t]=[],o[t]={});var a=o[t];if(e.name){var r=a[e.name];r&&c.unregister(r),a[e.name]=e}s[t].push(e),e.tabTrigger&&!e.trigger&&(!e.guard&&/^\w/.test(e.tabTrigger)&&(e.guard="\\b"),e.trigger=i.escapeRegExp(e.tabTrigger)),(e.trigger||e.guard||e.endTrigger||e.endGuard)&&(e.startRe=n(e.trigger,e.guard,!0),e.triggerRe=new RegExp(e.trigger,"",!0),e.endRe=n(e.endTrigger,e.endGuard,!0),e.endTriggerRe=new RegExp(e.endTrigger,"",!0))}var s=this.snippetMap,o=this.snippetNameMap,c=this;e||(e=[]),e&&e.content?r(e):Array.isArray(e)&&e.forEach(r),this._signal("registerSnippets",{scope:t})},this.unregister=function(e,t){function a(e){var a=r[e.scope||t];if(a&&a[e.name]){delete a[e.name];var i=n[e.scope||t],s=i&&i.indexOf(e);s>=0&&i.splice(s,1)}}var n=this.snippetMap,r=this.snippetNameMap;e.content?a(e):Array.isArray(e)&&e.forEach(a)},this.parseSnippetFile=function(e){e=e.replace(/\r/g,"");for(var t,a=[],n={},r=/^#.*|^({[\s\S]*})\s*$|^(\S+) (.*)$|^((?:\n*\t.*)+)/gm;t=r.exec(e);){if(t[1])try{n=JSON.parse(t[1]),a.push(n)}catch(i){}if(t[4])n.content=t[4].replace(/^\t/gm,""),a.push(n),n={};else{var s=t[2],o=t[3];if("regex"==s){var c=/\/((?:[^\/\\]|\\.)*)|$/g;n.guard=c.exec(o)[1],n.trigger=c.exec(o)[1],n.endTrigger=c.exec(o)[1],n.endGuard=c.exec(o)[1]}else"snippet"==s?(n.tabTrigger=o.match(/^\S*/)[0],n.name||(n.name=o)):n[s]=o}}return a},this.getSnippetByName=function(e,t){var a,n=this.snippetNameMap;return this.getActiveScopes(t).some(function(t){var r=n[t];return r&&(a=r[e]),!!a},this),a}}).call(u.prototype);var m=function(e){return e.tabstopManager?e.tabstopManager:(e.tabstopManager=this,this.$onChange=this.onChange.bind(this),this.$onChangeSelection=i.delayedCall(this.onChangeSelection.bind(this)).schedule,this.$onChangeSession=this.onChangeSession.bind(this),this.$onAfterExec=this.onAfterExec.bind(this),void this.attach(e))};(function(){this.attach=function(e){this.index=0,this.ranges=[],this.tabstops=[],this.$openTabstops=null,this.selectedTabstop=null,this.editor=e,this.editor.on("change",this.$onChange),this.editor.on("changeSelection",this.$onChangeSelection),this.editor.on("changeSession",this.$onChangeSession),this.editor.commands.on("afterExec",this.$onAfterExec),this.editor.keyBinding.addKeyboardHandler(this.keyboardHandler)},this.detach=function(){this.tabstops.forEach(this.removeTabstopMarkers,this),this.ranges=null,this.tabstops=null,this.selectedTabstop=null,this.editor.removeListener("change",this.$onChange),this.editor.removeListener("changeSelection",this.$onChangeSelection),this.editor.removeListener("changeSession",this.$onChangeSession),this.editor.commands.removeListener("afterExec",this.$onAfterExec),this.editor.keyBinding.removeKeyboardHandler(this.keyboardHandler),this.editor.tabstopManager=null,this.editor=null},this.onChange=function(e){var t="r"==e.action[0],a=e.start,n=e.end,r=a.row,i=n.row,s=i-r,o=n.column-a.column;if(t&&(s=-s,o=-o),!this.$inChange&&t){var c=this.selectedTabstop,l=c&&!c.some(function(e){return d(e.start,a)<=0&&d(e.end,n)>=0});if(l)return this.detach()}for(var u=this.ranges,m=0;m0?(this.removeRange(h),m--):(h.start.row==r&&h.start.column>a.column&&(h.start.column+=o),h.end.row==r&&h.end.column>=a.column&&(h.end.column+=o),h.start.row>=r&&(h.start.row+=s),h.end.row>=r&&(h.end.row+=s),d(h.start,h.end)>0&&this.removeRange(h)))}u.length||this.detach()},this.updateLinkedFields=function(){var e=this.selectedTabstop;if(e&&e.hasLinkedRanges){this.$inChange=!0;for(var a=this.editor.session,n=a.getTextRange(e.firstNonLinked),r=e.length;r--;){var i=e[r];if(i.linked){var s=t.snippetManager.tmStrFormat(n,i.original);a.replace(i,s)}}this.$inChange=!1}},this.onAfterExec=function(e){e.command&&!e.command.readOnly&&this.updateLinkedFields()},this.onChangeSelection=function(){if(this.editor){for(var e=this.editor.selection.lead,t=this.editor.selection.anchor,a=this.editor.selection.isEmpty(),n=this.ranges.length;n--;)if(!this.ranges[n].linked){var r=this.ranges[n].contains(e.row,e.column),i=a||this.ranges[n].contains(t.row,t.column);if(r&&i)return}this.detach()}},this.onChangeSession=function(){this.detach()},this.tabNext=function(e){var t=this.tabstops.length,a=this.index+(e||1);a=Math.min(Math.max(a,1),t),a==t&&(a=0),this.selectTabstop(a),0===a&&this.detach()},this.selectTabstop=function(e){this.$openTabstops=null;var t=this.tabstops[this.index];if(t&&this.addTabstopMarkers(t),this.index=e,t=this.tabstops[this.index],t&&t.length){if(this.selectedTabstop=t,this.editor.inVirtualSelectionMode)this.editor.selection.setRange(t.firstNonLinked);else{var a=this.editor.multiSelect;a.toSingleRange(t.firstNonLinked.clone());for(var n=t.length;n--;)t.hasLinkedRanges&&t[n].linked||a.addRange(t[n].clone(),!0);a.ranges[0]&&a.addRange(a.ranges[0].clone())}this.editor.keyBinding.addKeyboardHandler(this.keyboardHandler)}},this.addTabstops=function(e,t,a){if(this.$openTabstops||(this.$openTabstops=[]),!e[0]){var n=s.fromPoints(a,a);g(n.start,t),g(n.end,t),e[0]=[n],e[0].index=0}var r=this.index,i=[r+1,0],o=this.ranges;e.forEach(function(e,a){for(var n=this.$openTabstops[a]||e,r=e.length;r--;){var c=e[r],l=s.fromPoints(c.start,c.end||c.start);p(l.start,t),p(l.end,t),l.original=c,l.tabstop=n,o.push(l),n!=e?n.unshift(l):n[r]=l,c.fmtString?(l.linked=!0,n.hasLinkedRanges=!0):n.firstNonLinked||(n.firstNonLinked=l)}n.firstNonLinked||(n.hasLinkedRanges=!1),n===e&&(i.push(n),this.$openTabstops[a]=n),this.addTabstopMarkers(n)},this),i.length>2&&(this.tabstops.length&&i.push(i.splice(2,1)[0]),this.tabstops.splice.apply(this.tabstops,i))},this.addTabstopMarkers=function(e){var t=this.editor.session;e.forEach(function(e){e.markerId||(e.markerId=t.addMarker(e,"ace_snippet-marker","text"))})},this.removeTabstopMarkers=function(e){var t=this.editor.session;e.forEach(function(e){t.removeMarker(e.markerId),e.markerId=null})},this.removeRange=function(e){var t=e.tabstop.indexOf(e);e.tabstop.splice(t,1),t=this.ranges.indexOf(e),this.ranges.splice(t,1),this.editor.session.removeMarker(e.markerId),e.tabstop.length||(t=this.tabstops.indexOf(e.tabstop),-1!=t&&this.tabstops.splice(t,1),this.tabstops.length||this.detach())},this.keyboardHandler=new c,this.keyboardHandler.bindKeys({Tab:function(e){t.snippetManager&&t.snippetManager.expandWithTab(e)||e.tabstopManager.tabNext(1)},"Shift-Tab":function(e){e.tabstopManager.tabNext(-1)},Esc:function(e){e.tabstopManager.detach()},Return:function(e){return!1}})}).call(m.prototype);var h={};h.onChange=o.prototype.onChange,h.setPosition=function(e,t){this.pos.row=e,this.pos.column=t},h.update=function(e,t,a){this.$insertRight=a,this.pos=e,this.onChange(t)};var p=function(e,t){0==e.row&&(e.column+=t.column),e.row+=t.row},g=function(e,t){e.row==t.row&&(e.column-=t.column),e.row-=t.row};e("./lib/dom").importCssString(".ace_snippet-marker { -moz-box-sizing: border-box; box-sizing: border-box; background: rgba(194, 193, 208, 0.09); border: 1px dotted rgba(211, 208, 235, 0.62); position: absolute;}"),t.snippetManager=new u;var f=e("./editor").Editor;(function(){this.insertSnippet=function(e,a){return t.snippetManager.insertSnippet(this,e,a)},this.expandSnippet=function(e){return t.snippetManager.expandWithTab(this,e)}}).call(f.prototype)}),ace.define("ace/autocomplete/popup",["require","exports","module","ace/virtual_renderer","ace/editor","ace/range","ace/lib/event","ace/lib/lang","ace/lib/dom"],function(e,t,a){var n=e("../virtual_renderer").VirtualRenderer,r=e("../editor").Editor,i=e("../range").Range,s=e("../lib/event"),o=e("../lib/lang"),c=e("../lib/dom"),l=function(e){var t=new n(e);t.$maxLines=4;var a=new r(t);return a.setHighlightActiveLine(!1),a.setShowPrintMargin(!1),a.renderer.setShowGutter(!1),a.renderer.setHighlightGutterLine(!1),a.$mouseHandler.$focusWaitTimout=0,a.$highlightTagPending=!0,a},d=function(e){var t=c.createElement("div"),a=new l(t);e&&e.appendChild(t),t.style.display="none",a.renderer.content.style.cursor="default",a.renderer.setStyle("ace_autocomplete"),a.setOption("displayIndentGuides",!1),a.setOption("dragDelay",150);var n=function(){}; -a.focus=n,a.$isFocused=!0,a.renderer.$cursorLayer.restartTimer=n,a.renderer.$cursorLayer.element.style.opacity=0,a.renderer.$maxLines=8,a.renderer.$keepTextAreaAtCursor=!1,a.setHighlightActiveLine(!1),a.session.highlight(""),a.session.$searchHighlight.clazz="ace_highlight-marker",a.on("mousedown",function(e){var t=e.getDocumentPosition();a.selection.moveToPosition(t),u.start.row=u.end.row=t.row,e.stop()});var r,d=new i(-1,0,-1,1/0),u=new i(-1,0,-1,1/0);u.id=a.session.addMarker(u,"ace_active-line","fullLine"),a.setSelectOnHover=function(e){e?d.id&&(a.session.removeMarker(d.id),d.id=null):d.id=a.session.addMarker(d,"ace_line-hover","fullLine")},a.setSelectOnHover(!1),a.on("mousemove",function(e){if(!r)return void(r=e);if(r.x!=e.x||r.y!=e.y){r=e,r.scrollTop=a.renderer.scrollTop;var t=r.getDocumentPosition().row;d.start.row!=t&&(d.id||a.setRow(t),h(t))}}),a.renderer.on("beforeRender",function(){if(r&&-1!=d.start.row){r.$pos=null;var e=r.getDocumentPosition().row;d.id||a.setRow(e),h(e,!0)}}),a.renderer.on("afterRender",function(){var e=a.getRow(),t=a.renderer.$textLayer,n=t.element.childNodes[e-t.config.firstRow];n!=t.selectedNode&&(t.selectedNode&&c.removeCssClass(t.selectedNode,"ace_selected"),t.selectedNode=n,n&&c.addCssClass(n,"ace_selected"))});var m=function(){h(-1)},h=function(e,t){e!==d.start.row&&(d.start.row=d.end.row=e,t||a.session._emit("changeBackMarker"),a._emit("changeHoverMarker"))};a.getHoveredRow=function(){return d.start.row},s.addListener(a.container,"mouseout",m),a.on("hide",m),a.on("changeSelection",m),a.session.doc.getLength=function(){return a.data.length},a.session.doc.getLine=function(e){var t=a.data[e];return"string"==typeof t?t:t&&t.value||""};var p=a.session.bgTokenizer;return p.$tokenizeRow=function(e){var t=a.data[e],n=[];if(!t)return n;"string"==typeof t&&(t={value:t}),t.caption||(t.caption=t.value||t.name);var r,i,s=-1;t.iconClass&&n.push({type:"icon ace_icon-"+t.iconClass,value:" "});for(var o=0;oc-2&&(l=l.substr(0,c-t.caption.length-3)+"…"),n.push({type:"rightAlignedText",value:l})}return n},p.$updateOnChange=n,p.start=n,a.session.$computeWidth=function(){return this.screenWidth=0},a.$blockScrolling=1/0,a.isOpen=!1,a.isTopdown=!1,a.data=[],a.setData=function(e){a.setValue(o.stringRepeat("\n",e.length),-1),a.data=e||[],a.setRow(0)},a.getData=function(e){return a.data[e]},a.getRow=function(){return u.start.row},a.setRow=function(e){e=Math.max(0,Math.min(this.data.length,e)),u.start.row!=e&&(a.selection.clearSelection(),u.start.row=u.end.row=e||0,a.session._emit("changeBackMarker"),a.moveCursorTo(e||0,0),a.isOpen&&a._signal("select"))},a.on("changeSelection",function(){a.isOpen&&a.setRow(a.selection.lead.row),a.renderer.scrollCursorIntoView()}),a.hide=function(){this.container.style.display="none",this._signal("hide"),a.isOpen=!1},a.show=function(e,t,n){var i=this.container,s=window.innerHeight,o=window.innerWidth,c=this.renderer,l=c.$maxLines*t*1.4,d=e.top+this.$borderSize,u=d>s/2&&!n;u&&d+t+l>s?(c.$maxPixelHeight=d-2*this.$borderSize,i.style.top="",i.style.bottom=s-d+"px",a.isTopdown=!1):(d+=t,c.$maxPixelHeight=s-d-.2*t,i.style.top=d+"px",i.style.bottom="",a.isTopdown=!0),i.style.display="",this.renderer.$textLayer.checkForSizeChanges();var m=e.left;m+i.offsetWidth>o&&(m=o-i.offsetWidth),i.style.left=m+"px",this._signal("show"),r=null,a.isOpen=!0},a.getTextLeftOffset=function(){return this.$borderSize+this.renderer.$padding+this.$imageSize},a.$imageSize=0,a.$borderSize=1,a};c.importCssString(".ace_editor.ace_autocomplete .ace_marker-layer .ace_active-line { background-color: #CAD6FA; z-index: 1;}.ace_editor.ace_autocomplete .ace_line-hover { border: 1px solid #abbffe; margin-top: -1px; background: rgba(233,233,253,0.4);}.ace_editor.ace_autocomplete .ace_line-hover { position: absolute; z-index: 2;}.ace_editor.ace_autocomplete .ace_scroller { background: none; border: none; box-shadow: none;}.ace_rightAlignedText { color: gray; display: inline-block; position: absolute; right: 4px; text-align: right; z-index: -1;}.ace_editor.ace_autocomplete .ace_completion-highlight{ color: #000; text-shadow: 0 0 0.01em;}.ace_editor.ace_autocomplete { width: 280px; z-index: 200000; background: #fbfbfb; color: #444; border: 1px lightgray solid; position: fixed; box-shadow: 2px 3px 5px rgba(0,0,0,.2); line-height: 1.4;}"),t.AcePopup=d}),ace.define("ace/autocomplete/util",["require","exports","module"],function(e,t,a){t.parForEach=function(e,t,a){var n=0,r=e.length;0===r&&a();for(var i=0;r>i;i++)t(e[i],function(e,t){n++,n===r&&a(e,t)})};var n=/[a-zA-Z_0-9\$\-\u00A2-\uFFFF]/;t.retrievePrecedingIdentifier=function(e,t,a){a=a||n;for(var r=[],i=t-1;i>=0&&a.test(e[i]);i--)r.push(e[i]);return r.reverse().join("")},t.retrieveFollowingIdentifier=function(e,t,a){a=a||n;for(var r=[],i=t;i=t?a:t-1;break;case"down":t=t>=a?-1:t+1;break;case"start":t=0;break;case"end":t=a}this.popup.setRow(t)},this.insertMatch=function(e,t){if(e||(e=this.popup.getData(this.popup.getRow())),!e)return!1;if(e.completer&&e.completer.insertMatch)e.completer.insertMatch(this.editor,e);else{if(this.completions.filterText)for(var a,n=this.editor.selection.getAllRanges(),r=0;a=n[r];r++)a.start.column-=this.completions.filterText.length,this.editor.session.remove(a);e.snippet?c.insertSnippet(this.editor,e.snippet):this.editor.execCommand("insertstring",e.value||e)}this.detach()},this.commands={Up:function(e){e.completer.goTo("up")},Down:function(e){e.completer.goTo("down")},"Ctrl-Up|Ctrl-Home":function(e){e.completer.goTo("start")},"Ctrl-Down|Ctrl-End":function(e){e.completer.goTo("end")},Esc:function(e){e.completer.detach()},Return:function(e){return e.completer.insertMatch()},"Shift-Return":function(e){e.completer.insertMatch(null,{deleteSuffix:!0})},Tab:function(e){var t=e.completer.insertMatch();return t||e.tabstopManager?t:void e.completer.goTo("down")},PageUp:function(e){e.completer.popup.gotoPageUp()},PageDown:function(e){e.completer.popup.gotoPageDown()}},this.gatherCompletions=function(e,t){var a=e.getSession(),n=e.getCursorPosition(),r=(a.getLine(n.row),i.getCompletionPrefix(e));this.base=a.doc.createAnchor(n.row,n.column-r.length),this.base.$insertRight=!0;var s=[],o=e.completers.length;return e.completers.forEach(function(i,c){i.getCompletions(e,a,n,r,function(n,i){!n&&i&&(s=s.concat(i));var c=e.getCursorPosition();a.getLine(c.row);t(null,{prefix:r,matches:s,finished:0===--o})})}),!0},this.showPopup=function(e){this.editor&&this.detach(),this.activated=!0,this.editor=e,e.completer!=this&&(e.completer&&e.completer.detach(),e.completer=this),e.on("changeSelection",this.changeListener),e.on("blur",this.blurListener),e.on("mousedown",this.mousedownListener),e.on("mousewheel",this.mousewheelListener),this.updateCompletions()},this.updateCompletions=function(e){if(e&&this.base&&this.completions){var t=this.editor.getCursorPosition(),a=this.editor.session.getTextRange({start:this.base,end:t});if(a==this.completions.filterText)return;return this.completions.setFilter(a),this.completions.filtered.length&&(1!=this.completions.filtered.length||this.completions.filtered[0].value!=a||this.completions.filtered[0].snippet)?void this.openPopup(this.editor,a,e):this.detach()}var n=this.gatherCompletionsId;this.gatherCompletions(this.editor,function(t,a){var r=function(){return a.finished?this.detach():void 0}.bind(this),i=a.prefix,s=a&&a.matches;if(!s||!s.length)return r();if(0===i.indexOf(a.prefix)&&n==this.gatherCompletionsId){this.completions=new d(s),this.exactMatch&&(this.completions.exactMatch=!0),this.completions.setFilter(i);var o=this.completions.filtered;return o.length&&(1!=o.length||o[0].value!=i||o[0].snippet)?this.autoInsert&&1==o.length&&a.finished?this.insertMatch(o[0]):void this.openPopup(this.editor,i,e):r()}}.bind(this))},this.cancelContextMenu=function(){this.editor.$mouseHandler.cancelContextMenu()},this.updateDocTooltip=function(){var e=this.popup,t=e.data,a=t&&(t[e.getHoveredRow()]||t[e.getRow()]),n=null;return a&&this.editor&&this.popup.isOpen?(this.editor.completers.some(function(e){return e.getDocTooltip&&(n=e.getDocTooltip(a)),n}),n||(n=a),"string"==typeof n&&(n={docText:n}),n&&(n.docHTML||n.docText)?void this.showDocTooltip(n):this.hideDocTooltip()):this.hideDocTooltip()},this.showDocTooltip=function(e){this.tooltipNode||(this.tooltipNode=o.createElement("div"),this.tooltipNode.className="ace_tooltip ace_doc-tooltip",this.tooltipNode.style.margin=0,this.tooltipNode.style.pointerEvents="auto",this.tooltipNode.tabIndex=-1,this.tooltipNode.onblur=this.blurListener.bind(this));var t=this.tooltipNode;e.docHTML?t.innerHTML=e.docHTML:e.docText&&(t.textContent=e.docText),t.parentNode||document.body.appendChild(t);var a=this.popup,n=a.container.getBoundingClientRect();t.style.top=a.container.style.top,t.style.bottom=a.container.style.bottom,window.innerWidth-n.right<320?(t.style.right=window.innerWidth-n.left+"px",t.style.left=""):(t.style.left=n.right+1+"px",t.style.right=""),t.style.display="block"},this.hideDocTooltip=function(){if(this.tooltipTimer.cancel(),this.tooltipNode){var e=this.tooltipNode;this.editor.isFocused()||document.activeElement!=e||this.editor.focus(),this.tooltipNode=null,e.parentNode&&e.parentNode.removeChild(e)}}}).call(l.prototype),l.startCommand={name:"startAutocomplete",exec:function(e){e.completer||(e.completer=new l),e.completer.autoInsert=!1,e.completer.autoSelect=!0,e.completer.showPopup(e),e.completer.cancelContextMenu()},bindKey:"Ctrl-Space|Ctrl-Shift-Space|Alt-Space"};var d=function(e,t){this.all=e,this.filtered=e,this.filterText=t||"",this.exactMatch=!1};(function(){this.setFilter=function(e){if(e.length>this.filterText&&0===e.lastIndexOf(this.filterText,0))var t=this.filtered;else var t=this.all;this.filterText=e,t=this.filterCompletions(t,this.filterText),t=t.sort(function(e,t){return t.exactMatch-e.exactMatch||t.score-e.score});var a=null;t=t.filter(function(e){var t=e.snippet||e.caption||e.value;return t===a?!1:(a=t,!0)}),this.filtered=t},this.filterCompletions=function(e,t){var a=[],n=t.toUpperCase(),r=t.toLowerCase();e:for(var i,s=0;i=e[s];s++){var o=i.value||i.caption||i.snippet;if(o){var c,l,d=-1,u=0,m=0;if(this.exactMatch){if(t!==o.substr(0,t.length))continue e}else for(var h=0;h=0&&(0>g||g>p)?p:g,0>c)continue e;l=c-d-1,l>0&&(-1===d&&(m+=10),m+=l),u|=1<",s.escapeHTML(e.caption),"","
",s.escapeHTML(e.snippet)].join(""))}},u=[d,c,l];t.setCompleters=function(e){u.length=0,e&&u.push.apply(u,e)},t.addCompleter=function(e){u.push(e)},t.textCompleter=c,t.keyWordCompleter=l,t.snippetCompleter=d;var m,h={name:"expandSnippet",exec:function(e){return n.expandWithTab(e)},bindKey:"Tab"},p=function(e,t){g(t.session.$mode)},g=function k(e){var t=e.$id;n.files||(n.files={}),f(t),e.modes&&e.modes.forEach(k)},f=function x(e){if(e&&!n.files[e]){var t=e.replace("mode","snippets");n.files[e]={},i.loadModule(t,function(t){t&&(n.files[e]=t,!t.snippets&&t.snippetText&&(t.snippets=n.parseSnippetFile(t.snippetText)),n.register(t.snippets||[],t.scope),t.includeScopes&&(n.snippetMap[t.scope].includeScopes=t.includeScopes,t.includeScopes.forEach(function(e){x("ace/mode/"+e)})))})}},b=function(e){var t=e.editor,a=t.completer&&t.completer.activated;if("backspace"===e.command.name)a&&!o.getCompletionPrefix(t)&&t.completer.detach();else if("insertstring"===e.command.name){var n=o.getCompletionPrefix(t);n&&n.length>=t.$liveAutocompletionThreshold&&!a&&(t.completer||(t.completer=new r),t.completer.autoInsert=!1,t.completer.showPopup(t))}},v=s.delayedCall(function(){b(m)},0),y=function(e){m=e,v.delay(e.editor.$liveAutocompletionDelay)},w=e("../editor").Editor;e("../config").defineOptions(w.prototype,"editor",{enableBasicAutocompletion:{set:function(e){e?(this.completers||(this.completers=Array.isArray(e)?e:u),this.commands.addCommand(r.startCommand)):this.commands.removeCommand(r.startCommand)},value:!1},enableLiveAutocompletion:{set:function(e){e?(this.completers||(this.completers=Array.isArray(e)?e:u),this.commands.on("afterExec",y)):this.commands.removeListener("afterExec",y)},value:!1},liveAutocompletionThreshold:{value:0},liveAutocompletionDelay:{value:500},enableSnippets:{set:function(e){e?(this.commands.addCommand(h),this.on("changeMode",p),p(null,this)):(this.commands.removeCommand(h),this.off("changeMode",p))},value:!1}})}),function(){ace.require(["ace/ext/language_tools"],function(){})}(),ace.define("ace/ext/beautify/php_rules",["require","exports","module","ace/token_iterator"],function(e,t,a){e("ace/token_iterator").TokenIterator;t.newLines=[{type:"support.php_tag",value:""},{type:"paren.lparen",value:"{",indent:!0},{type:"paren.rparen",breakBefore:!0,value:"}",indent:!1},{type:"paren.rparen",breakBefore:!0,value:"})",indent:!1,dontBreak:!0},{type:"comment"},{type:"text",value:";"},{type:"text",value:":",context:"php"},{type:"keyword",value:"case",indent:!0,dontBreak:!0},{type:"keyword",value:"default",indent:!0,dontBreak:!0},{type:"keyword",value:"break",indent:!1,dontBreak:!0},{type:"punctuation.doctype.end",value:">"},{type:"meta.tag.punctuation.end",value:">"},{type:"meta.tag.punctuation.begin",value:"<",blockTag:!0,indent:!0,dontBreak:!0},{type:"meta.tag.punctuation.begin",value:""!=o.value?n="php":"support.php_tag"==o.type&&"?>"==o.value?n="html":"meta.tag.name.style"==o.type&&"css"!=n?n="css":"meta.tag.name.style"==o.type&&"css"==n?n="html":"meta.tag.name.script"==o.type&&"js"!=n?n="js":"meta.tag.name.script"==o.type&&"js"==n&&(n="html"),g=e.stepForward(),g&&0==g.type.indexOf("meta.tag.name")&&(s=g.value),"support.php_tag"==p.type&&"v;v++)u+=" ";break}if(h===!1)for(v in c)if(!(p.type!=c[v].type||c[v].value&&p.value!=c[v].value||c[v].blockTag&&-1!==d.indexOf(r)||c[v].context&&c[v].context!==n)){if(c[v].indent===!0&&m++,!c[v].dontBreak&&!f)for(u+="\n",v=0;m>v;v++)u+=" ";break}if(u+=b,"support.php_tag"==p.type&&"?>"==p.value&&(h=!1),i=r,p=o,o=g,null===o)break}else o=g;else o=e.stepForward();return u}}),ace.define("ace/ext/beautify",["require","exports","module","ace/token_iterator","ace/ext/beautify/php_rules"],function(e,t,a){var n=e("ace/token_iterator").TokenIterator,r=e("./beautify/php_rules").transform;t.beautify=function(e){var t=new n(e,0,0),a=(t.getCurrentToken(),e.$modeId.split("/").pop()),i=r(t,a);e.doc.setValue(i)},t.commands=[{name:"beautify",exec:function(e){t.beautify(e.session)},bindKey:"Ctrl-Shift-B"}]}),function(){ace.require(["ace/ext/beautify"],function(){})}(),ace.define("ace/mode/clickhouse_highlight_rules",["require","exports","$rootScope","module","ace/lib/oop","ace/snippets","ace/ext/language_tools","ace/mode/text_highlight_rules"],function(e,t,a){var n=e("../lib/oop"),r=e("./text_highlight_rules").TextHighlightRules,i=function(){var e=this,t="SELECT|CASE|THEN|DISTINCT|INSERT|UPDATE|DELETE|WHERE|AND|OR|OFFSET|HAVING|AS|FROM|WHEN|ELSE|END|TYPE|LEFT|RIGHT|JOIN|ON|OUTER|DESC|ASC|UNION|CREATE|TABLE|PRIMARY|KEY|FOREIGN|NOT|REFERENCES|DEFAULT|INNER|CROSS|NATURAL|DATABASE|DROP|GRANT|ANY|BETWEEN|ATTACH|DETACH|CAST|WITH|BIT_AND|BIT_OR|BIT_XOR|DESCRIBE|OPTIMIZE|PREWHERE|TOTALS|DATABASES|PROCESSLIST|SHOW|IF",a="IF\\W+NOT\\W+EXISTS|IF\\W+EXISTS|FORMAT\\W+Vertical|FORMAT\\W+JSONCompact|FORMAT\\W+JSONEachRow|FORMAT\\W+TSKV|FORMAT\\W+TabSeparatedWithNames|FORMAT\\W+TabSeparatedWithNamesAndTypes|FORMAT\\W+TabSeparatedRaw|FORMAT\\W+BlockTabSeparated|FORMAT\\W+CSVWithNames|FORMAT\\W+CSV|FORMAT\\W+JSON|FORMAT\\W+TabSeparated",n="true|false|NULL",r="sum|sumIf|avg|avgIf",i="date|integer|uint8|uint16|uint32|uint64|int8|int16|int32|int64|float32|float64|datetime|enum8|enum16|fixedstring|array|tuple|stringMergeTree|SummingMergeTree|ReplacingMergeTree|ReplicatedMergeTree|Buffer|ReplicatedCollapsingMergeTree|CollapsingMergeTree|AggregatingMergeTree|Merge|Memory|GraphiteMergeTree|ReplicatedAggregatingMergeTree|ReplicatedSummingMergeTree",s=["IF NOT EXISTS","IF EXISTS","GROUP BY","ORDER BY","UNION ALL","FORMAT JSON","FORMAT JSONCompact","FORMAT JSONEachRow","FORMAT TSV","FORMAT TabSeparated","FORMAT TabSeparatedWithNames","FORMAT TabSeparatedWithNamesAndTypes","FORMAT TabSeparatedRaw","FORMAT BlockTabSeparated","FORMAT TSKV","FORMAT CSV","FORMAT CSVWithNames","SYSTEM RELOAD DICTIONARY","SYSTEM RELOAD DICTIONARIES","SYSTEM DROP DNS CACHE","SYSTEM SHUTDOWN","SYSTEM KILL","CLEAR COLUMN IN PARTITION"],o=["DRAW_GMAPS","DRAW_PLOTLY","DRAW_CALENDAR","DRAW_TEXT","DRAW_HEATMAP","DRAW_CHART","DRAW_BAR","DRAW_GRIDCHART","DRAW_RIVER","DRAW_RAW","DRAW_SANKEYS","DRAW_TREEMAP","DRAW_C3","DRAW_MAP"],c="";if(window.aceJSRules&&window.aceJSRules.builtinFunctions){if(window.aceJSRules.builtinFunctions){var l=[];window.aceJSRules.builtinFunctions.forEach(function(e){l.push(e.name)}),r=l.join("|")}_.isArray(window.aceJSRules.tables)&&(c=window.aceJSRules.tables.join("|"))}var d="";d=window.global_delimiter?new RegExp(window.global_delimiter):new RegExp(";;");var u=[],m=t.toLowerCase();window.aceJSRules&&_.isArray(window.aceJSRules.fieldsList)&&window.aceJSRules.fieldsList.forEach(function(e){var t=e.name.toLowerCase()+"|";m.indexOf(t)>-1||u.push(e.name)});var h=this.createKeywordMapper({"support.function":r,keyword:t,"constant.language":n,"storage.type":i,"markup.bold":c,"markup.heading":u.join("|")},"identifier",!0);this.$rules={start:[{token:"comment",regex:"--.*$",caseInsensitive:!0},{token:"comment.block",start:"```",end:"```"},{token:"keyword",regex:"GROUP\\W+BY|ON\\W+CLUSTER|ORDER\\W+BY|LIMIT\\W+\\d+\\W*,\\W*\\d+|LIMIT\\W+\\d+\\W+BY\\W+|LIMIT\\W+\\d+"},{token:"variable.language",regex:/\$[\w]+(?:\[[\w\]+]|[=\-]>\w+)?/},{token:"variable.language",regex:/@[\w]+(?:\[[\w\]+]|[=\-]>\w+)?/},{token:"variable.language",regex:/\:[\w]+(?:\[[\w\]+]|[=\-]>\w+)?/},{token:"variable.language",regex:/\{[\w]+(?:\[[\w\]+]|[=\-]>\w+)\}?/},{token:"comment",start:"/\\*",end:"\\*/"},{token:"constant",regex:'".*?"'},{token:"storage",regex:a},{token:"invalid.illegal",regex:o.join("|")},{token:"string",regex:"'.*?'"},{token:"constant.numeric",regex:"[+-]?\\d+(?:(?:\\.\\d*)?(?:[eE][+-]?\\d+)?)?\\b"},{token:h,regex:"[a-zA-Z_$][a-zA-Z0-9_$]*\\b"},{token:"constant.character.escape",regex:d},{token:"punctuation",regex:/[?:,;.]/},{token:"keyword.operator",regex:"\\+|\\-|\\/|\\/\\/|%|<@>|@>|<@|&|\\^|~|<|>|<=|=>|==|!=|<>|="},{token:"paren.lparen",regex:"[\\(\\{]"},{token:"paren.rparen",regex:"[\\)\\}]"},{token:"text",regex:"\\s+"}]},this.normalizeRules(),this.completions=[],this.getCompletions=function(){return e.completions},this.addCompletions=function(e,t,a,n,r,i,s){this.completions.push({name:e,value:t,caption:a,score:n,meta:r,iconClass:i,docHTML:s})},this.addCompletionsDictionaries=function(e){this.addCompletions(e.dic,e.dic,e.title,0,"dic","dict",this.makeCompletionsDocFunctions(e.title,e.dic))},this.addCompletionsFunctions=function(e){this.addCompletions(e.name,e.name+"( )",e.name+"( )",e.score,"function","function",this.makeCompletionsDocFunctions(e.name,e.origin,e.comb))},this.addCompletionsTableFiled=function(e){var t=e.table+"."+e.name,a=e.name,n="type:"+e.type+"

default_type:"+e.default_type+"
"+e.default_expression;this.addCompletions(t,a,a,100,e.type,"field",this.makeCompletionsdocHTML(t,n))},this.addArrayCompletions=function(e,t,a){var n=this;e.forEach(function(e){n.addCompletions(e,e,e,0,t,a,!1)})},this.setKeywords=function(e){console.log("setKeywords > ",e),this.keywordRule.onMatch=this.createKeywordMapper(e,"identifier")},this.makeCompletionsDocFunctions=function(e,t,a){if(!window.global_chFunctionsHelp)return!1;if(!window.global_chFunctionsHelp.functions)return!1;var n="",r=e;if("undefined"!=typeof window.global_chFunctionsHelp.functions[e]?r=e:"undefined"!=typeof window.global_chFunctionsHelp.functions[t]&&(r=t),"undefined"!=typeof window.global_chFunctionsHelp.functions[r]){var i="en",s=window.global_chFunctionsHelp.functions[r],o="",c="";s.desc&&(o=s.bracket,c=s.desc[i],c||(c=s.desc.en?s.desc.en:s.desc.ru)),c&&(c=c.replace(/\.\s*/gm,".
")),n=''+e+o+'
'+c+" "}else n=''+e+"( )
"+t;return n+'
'},this.makeCompletionsdocHTML=function(e,t){return'
'+e+"
"+t+"
"},this.addArrayCompletions(t.split("|"),"keyword","keyword"),this.addArrayCompletions(s,"keyword","keyword"),this.addArrayCompletions(o,"draw","draw"),this.addArrayCompletions(i.split("|"),"type","type")};n.inherits(i,r),t.ClickhouseHighlightRules=i}),ace.define("ace/mode/matching_brace_outdent",["require","exports","module","ace/range"],function(e,t,a){var n=e("ace/range").Range,r=function(){};(function(){this.checkOutdent=function(e,t){return/^\s+$/.test(e)?/^\s*\}/.test(t):!1},this.autoOutdent=function(e,t){var a=e.getLine(t),r=a.match(/^(\s*\})/);if(!r)return 0;var i=r[1].length,s=e.findMatchingBracket({row:t,column:i});if(!s||s.row==t)return 0;var o=this.$getIndent(e.getLine(s.row));e.replace(new n(t,0,t,i-1),o)},this.$getIndent=function(e){return e.match(/^\s*/)[0]}}).call(r.prototype),t.MatchingBraceOutdent=r}),ace.define("ace/mode/clickhouse_FoldMode",["$rootScope","require","exports","module","ace/lib/oop","ace/range","ace/mode/sqlserver","ace/mode/folding/cstyle"],function(e,t,a){var n=e("../lib/oop"),r=e("ace/mode/folding/cstyle").FoldMode,i=(e("ace/range").Range,e("ace/token_iterator").TokenIterator),s=t.FoldMode=function(){};n.inherits(s,r),function(){this.foldingRules="cStyle",this.foldingStartMarker=/\(|\{/,this.getFoldWidgetRange=function(e,t,a,n){for(var r=new i(e,a,0),s=r.getCurrentToken(),o=!1;s;){var c=s,l=r.getCurrentTokenPosition();if(s=r.stepForward(),"paren.lparen"!=c.type||"("!=c.value&&"{"!=c.value||(o=e.getBracketRange(l)),o)break}return o}}.call(s.prototype)}),window.global_chFunctionsHelp={functions:{corr:{bracket:"(x, y)",desc:{en:'Calculates the Pearson correlation coefficient: Σ((x - x̅)(y - y̅)) / sqrt(Σ((x - x̅)2) * Σ((y - y̅)2)).'}},stddevPop:{bracket:"(x)",desc:{en:"The result is equal to the square root of 'varPop(x)'."}},varPop:{bracket:"(x, y)",desc:{en:"Calculates the value of %%Σ((x - x̅)(y - y̅)) / n%%."}},argMin:{bracket:"(arg, val)",desc:{en:"Calculates the 'arg' value for a minimal 'val' value. If there are several different values of 'arg' for minimal values of 'val', the first of these values encountered is output."}},quantileExactWeighted:{bracket:"(level)(x, weight)",desc:{en:"Вычисляет квантиль уровня level точно."}},min:{bracket:"(v)",desc:{en:"Minimal execution speed in rows per second. Checked on every data block when 'timeout_before_checking_execution_speed' expires. If the execution speed is lower, an exception is thrown."}},varSamp:{bracket:"(x, y)",desc:{en:"Calculates the value of %%Σ((x - x̅)(y - y̅)) / (n - 1)%%.

Returns Float64. If n <= 1, it returns +∞."}},anyLast:{bracket:"(x)",desc:{en:"Selects the last value encountered.
The result is just as indeterminate as for the 'any' function."}},argMax:{bracket:"(arg, val)",desc:{en:"Calculates the 'arg' value for a maximum 'val' value. If there are several different values of 'arg' for maximum values of 'val', the first of these values encountered is output."}},count:{bracket:"()",desc:{en:"Counts the number of rows. "}},any:{bracket:"(x)",desc:{en:"Selects the last value encountered.
The result is just as indeterminate as for the 'any' function."}},avg:{bracket:"(x)",desc:{en:"Calculates the average.
Only works for numbers.
The result is always Float64."}},sequenceMatch:{bracket:"(pattern)(time, cond1, cond2, ...)",desc:{en:"Pattern matching for event chains.

'pattern' is a string containing a pattern to match."}},stddevSamp:{bracket:"(x)",desc:{en:"The result is equal to the square root of 'varSamp(x)'."}},medianDeterministic:{bracket:"(x, determinator)",desc:{en:"This function works similarly to the 'median' function - it approximates the median."}},quantilesTimingWeighted:{bracket:"(level1, level2, ...)(x, weight)",desc:{en:"Calculates the quantiles of all specified levels using the same algorithm as the 'medianTimingWeighted' function."}},uniq:{bracket:"(N)(x)",desc:{en:"Calculates the number of different argument values, if it is less than or equal to N.
If the number of different argument values is greater than N, it returns N + 1."}},covarSamp:{bracket:"(x, y)",desc:{en:"Calculates the value of %%Σ((x - x̅)(y - y̅)) / (n - 1)%%.

Returns Float64. If n <= 1, it returns +∞." -}},max:{bracket:"(v)",desc:{en:"Maximum number of bytes (uncompressed data) that can be passed to a remote server or saved in a temporary table when using GLOBAL IN."}},quantileTDigest:{bracket:"(level)(x)",desc:{en:"t-digest"}},quantilesTiming:{bracket:"(level1, level2, ...)(x, weight)",desc:{en:"Calculates the quantiles of all specified levels using the same algorithm as the 'medianTimingWeighted' function."}},quantiles:{bracket:"(level1, level2, ...)(x, determinator)",desc:{en:"Calculates the quantiles of all specified levels using the same algorithm as the 'medianDeterministic' function."}},quantile:{bracket:"(level1, level2, ...)(x, determinator)",desc:{en:"Calculates the quantiles of all specified levels using the same algorithm as the 'medianDeterministic' function."}},groupArray:{bracket:"(x)",desc:{en:"Creates an array of argument values.
Values can be added to the array in any (indeterminate) order.

In some cases, you can rely on the order of execution. This applies to cases when SELECT comes from a subquery that uses ORDER BY."}},sum:{bracket:"(x)",desc:{en:"Calculates the sum.
Only works for numbers."}},median:{bracket:"(x, weight)",desc:{en:"Differs from the 'medianTiming' function in that it has a second argument - "weights". Weight is a non-negative integer.
The result is calculated as if the 'x' value were passed 'weight' number of times to the 'medianTiming' function."}},quantileTiming:{bracket:"(level)(x, weight)",desc:{en:"Calculates the quantile of 'level' using the same algorithm as the 'medianTimingWeighted' function."}},quantileTimingWeighted:{bracket:"(level)(x, weight)",desc:{en:"Calculates the quantile of 'level' using the same algorithm as the 'medianTimingWeighted' function."}},groupUniqArray:{bracket:"(x)",desc:{en:"Creates an array from different argument values. Memory consumption is the same as for the 'uniqExact' function."}},uniqHLL12:{bracket:"(x)",desc:{en:"Uses the HyperLogLog algorithm to approximate the number of different values of the argument. "}},covarPop:{bracket:"(x, y)",desc:{en:"Calculates the value of %%Σ((x - x̅)(y - y̅)) / n%%."}},sequenceCount:{bracket:"(pattern)(time, cond1, cond2, ...)",desc:{en:"sequenceMatch"}},quantileDeterministic:{bracket:"(level)(x, determinator)",desc:{en:"Calculates the quantile of 'level' using the same algorithm as the 'medianDeterministic' function."}},quantileExact:{bracket:"(level)(x, weight)",desc:{en:""}},quantilesDeterministic:{bracket:"(level1, level2, ...)(x, determinator)",desc:{en:"Calculates the quantiles of all specified levels using the same algorithm as the 'medianDeterministic' function."}},medianTiming:{bracket:"(x, weight)",desc:{en:"Differs from the 'medianTiming' function in that it has a second argument - "weights"."}},medianTimingWeighted:{bracket:"(x, weight)",desc:{ru:"",en:"Differs from the 'medianTiming' function in that it has a second argument - "weights"."}},uniqExact:{bracket:"(x)",desc:{en:"Calculates the number of different values of the argument, exactly.
There is no reason to fear approximations, so it's better to use the 'uniq' function.
You should use the 'uniqExact' function if you definitely need an exact result. "}},uniqCombined:{bracket:"(x)",desc:{en:""}},uniqUpTo:{bracket:"(N)(x)",desc:{en:"Calculates the number of different argument values, if it is less than or equal to N.
If the number of different argument values is greater than N, it returns N + 1."}},substring:{bracket:"(s, offset, length)",desc:{en:"The same as 'substring', but for Unicode code points. Works under the assumption that the string contains a set of bytes representing a UTF-8 encoded text. If this assumption is not met, it returns some result (it doesn't throw an exception)."}},notLike:{bracket:"(haystack, pattern), haystack NOT LIKE pattern operator",desc:{en:"The same thing as 'like', but negative."}},hostName:{bracket:"()",desc:{en:"Returns a string with the name of the host that this function was performed on. For distributed processing, this is the name of the remote server host, if the function is performed on a remote server."}},globalNotIn:{bracket:"(v)",desc:{en:"See the section "IN operators"."}},or:{bracket:"(v)",desc:{en:"The same thing as 'max_temporary_columns', but without counting constant columns.
Note that constant columns are formed fairly often when running a query, but they require approximately zero computing resources."}},extractAll:{bracket:"(haystack, pattern)",desc:{en:"Extracts all the fragments of a string using a regular expression. If 'haystack' doesn't match the 'pattern' regex, an empty string is returned. Returns an array of strings consisting of all matches to the regex."}},arrayFirst:{bracket:"(func, arr1, ...)",desc:{en:"Returns the index of the first element in the 'arr1' array for which 'func' returns something other than 0."}},notEquals:{bracket:"(v)",desc:{ru:"",en:""}},arrayExists:{bracket:"([func,] arr1, ...)",desc:{en:"Returns 1 if there is at least one element in 'arr' for which 'func' returns something other than 0. Otherwise, it returns 0."}},arrayCount:{bracket:"([func,] arr1, ...)",desc:{en:"Returns the number of elements in 'arr' for which 'func' returns something other than 0. If 'func' is not specified, it returns the number of non-zero items in the array."}},arrayMap:{bracket:"(func, arr1, ...)",desc:{en:"Returns an array obtained from the original application of the 'func' function to each element in the 'arr' array."}},now:{bracket:"(v)",desc:{en:"If the parameter is true, INSERT operation will skip columns with unknown names from input.
Otherwise, an exception will be generated, it is default behavior.
The parameter works only for JSONEachRow and TSKV input formats."}},intDiv:{bracket:"(a, b)",desc:{en:"Differs from 'intDiv' in that it returns zero when dividing by zero or when dividing a minimal negative number by minus one."}},topLevelDomain:{bracket:"(v)",desc:{en:"- Selects the top-level domain. Example: .ru."}},intHash32:{bracket:"(v)",desc:{en:"Calculates a 32-bit hash code from any type of integer.
This is a relatively fast non-cryptographic hash function of average quality for numbers."}},replaceOne:{bracket:"(haystack, pattern, replacement)",desc:{en:"Replaces the first occurrence, if it exists, of the 'pattern' substring in 'haystack' with the 'replacement' substring.
Hereafter, 'pattern' and 'replacement' must be constants."}},cityHash64:{bracket:"(v)",desc:{en:"Calculates CityHash64 from a string or a similar hash function for any number of any type of arguments.
For String-type arguments, CityHash is used. This is a fast non-cryptographic hash function for strings with decent quality"}},OSToRoot:{bracket:"(v)",desc:{en:"Accepts a UInt8 number - the ID of the operating system from the Yandex.Metrica dictionary. If any OS matches the passed number, it returns a UInt8 number - the ID of the corresponding root OS (for example, it converts Windows Vista to Windows). Otherwise, returns 0."}},sipHash128:{bracket:"(v)",desc:{en:"Calculates SipHash from a string.
Accepts a String-type argument. Returns FixedString(16).
Differs from sipHash64 in that the final xor-folding state is only done up to 128 bits."}},SHA1:{bracket:"(v)",desc:{en:"Calculates SHA-1, SHA-224, or SHA-256 from a string and returns the resulting set of bytes as FixedString(20), FixedString(28), or FixedString(32)."}},asin:{bracket:"(x)",desc:{en:"The arc sine."}},SHA256:{bracket:"(v)",desc:{en:"Calculates SHA-1, SHA-224, or SHA-256 from a string and returns the resulting set of bytes as FixedString(20), FixedString(28), or FixedString(32)."}},MD5:{bracket:"(v)",desc:{en:"Calculates the MD5 from a string and returns the resulting set of bytes as FixedString(16)."}},bitmaskToList:{bracket:"(num)",desc:{en:"Accepts an integer. Returns a string containing the list of powers of two that total the source number when summed. They are comma-separated without spaces in text format, in ascending order."}},array:{bracket:"(v)",desc:{en:"The -%%Array%% suffix can be appended to any aggregate function. In this case, the aggregate function takes arguments of the 'Array(T)' type (arrays) instead of 'T' type arguments. If the aggregate function accepts multiple arguments, this must be arrays of equal lengths. "}},dictGetStringOrDefault:{bracket:"(v)",desc:{ru:"%%dictGetT('dict_name', 'attr_name', id, default)%%
Аналогично функциям dictGetT, но значение по умолчанию берётся из последнего аргумента функции.",en:""}},greaterOrEquals:{bracket:"(v)",desc:{ru:"",en:""}},e:{bracket:"(v)",desc:{en:"What to do when the amount of data exceeds one of the limits: 'throw' or 'break'. By default, throw."}},runningDifference:{bracket:"(x)",desc:{en:"Calculates the difference between consecutive values in the data block.
Result of the function depends on the order of the data in the blocks.

It works only inside of the each processed block of data. Data splitting in the blocks is not explicitly controlled by the user. "}},not:{bracket:"(v)",desc:{ru:'Смотрите раздел "Операторы IN".',en:"See the section "IN operators"."}},intHash64:{bracket:"(v)",desc:{en:"Calculates a 64-bit hash code from any type of integer.
It works faster than intHash32. Average quality."}},acos:{bracket:"(x)",desc:{ru:"Арккосинус.",en:"The arc cosine."}},dictGetString:{bracket:"(v)",desc:{en:""}},and:{bracket:"(x, determinator)",desc:{en:"This function works similarly to the 'median' function - it approximates the median. However, in contrast to 'median', the result is deterministic and does not depend on the order of query execution.

To achieve this, the function takes a second argument - the "determinator". "}},dictGetDate:{bracket:"(v)",desc:{ru:"",en:""}},dictGetFloat32:{bracket:"(v)",desc:{ru:"",en:""}},dictGetInt8:{bracket:"(v)",desc:{ru:"",en:""}},dictGetUInt32:{bracket:"(v)",desc:{ru:"",en:""}},OSIn:{bracket:"(lhs, rhs)",desc:{en:"Checks whether the 'lhs' operating system belongs to the 'rhs' operating system."}},arrayFirstIndex:{bracket:"(func, arr1, ...)",desc:{en:"Returns the index of the first element in the 'arr1' array for which 'func' returns something other than 0."}},ceil:{bracket:"(x[, N])",desc:{en:"Returns the smallest round number that is greater than or equal to 'x'. In every other way, it is the same as the 'floor' function (see above)."}},fragment:{bracket:"(v)",desc:{en:"Removes the query-string and fragment identifier. The question mark and number sign are also removed."}},dictGetUInt8:{bracket:"(v)",desc:{ru:"",en:""}},dictHas:{bracket:"(v)",desc:{ru:"%%dictHas('dict_name', id)%%
- проверить наличие ключа в словаре. Возвращает значение типа UInt8, равное 0, если ключа нет и 1, если ключ есть.",en:""}},arraySum:{bracket:"([func,] arr1, ...)",desc:{en:"Returns the sum of the 'func' values. If the function is omitted, it just returns the sum of the array elements."}},emptyArrayDateTime:{bracket:"(v)",desc:{en:"Accepts zero arguments and returns an empty array of the appropriate type."}},intDivOrZero:{bracket:"(a, b)",desc:{en:"Differs from 'intDiv' in that it returns zero when dividing by zero or when dividing a minimal negative number by minus one."}},SEHierarchy:{bracket:"(v)",desc:{en:"Accepts a UInt8 number - the ID of the search engine from the Yandex.Metrica dictionary. Returns an array with a hierarchy of search engines. Similar to the 'regionHierarchy' function."}},regionToContinent:{bracket:"(id[, geobase])",desc:{en:"Converts a region to a continent. In every other way, this function is the same as 'regionToCity'.
Example: %%regionToContinent(toUInt32(213)) = 10001%% converts Moscow (213) to Eurasia (10001)."}},dictGetInt32:{bracket:"(v)",desc:{ru:"",en:""}},toInt8:{bracket:"(v)",desc:{en:"Functions for converting between numbers, strings (but not fixed strings), dates, and dates with times. All these functions accept one argument. "}},materialize:{bracket:"(x)",desc:{en:"Turns a constant into a full column containing just one value.
In ClickHouse, full columns and constants are represented differently in memory. Functions work differently for constant arguments and normal arguments (different code is executed), although the result is almost always the same. This function is for debugging this behavior."}},regionToCountry:{bracket:"(id[, geobase])",desc:{en:"Converts a region to a country. In every other way, this function is the same as 'regionToCity'.
Example: %%regionToCountry(toUInt32(213)) = 225%% converts Moscow (213) to Russia (225)."}},dictGetDateTime:{bracket:"(v)",desc:{ru:"",en:""}},xor:{bracket:"(v)",desc:{ru:"",en:""}},regionToCity:{bracket:"(id[, geobase])",desc:{en:"Accepts a UInt32 number - the region ID from the Yandex geobase. If this region is a city or part of a city, it returns the region ID for the appropriate city. Otherwise, returns 0."}},dictGetFloat64:{bracket:"(v)",desc:{ru:"",en:""}},timeSlot:{bracket:"(StartTime, Duration)",desc:{en:"For a time interval starting at 'StartTime' and continuing for 'Duration' seconds, it returns an array of moments in time, consisting of points from this interval rounded down to the half hour."}},toTime:{bracket:"(v)",desc:{en:"Converts a date with time to the date of the start of the Unix Epoch, while preserving the time."}},log2:{bracket:"(x)",desc:{en:"Accepts a numeric argument and returns a Float64 number close to the binary logarithm of the argument."}},toRelativeHourNum:{bracket:"(v)",desc:{en:"Converts a date with time or date to the number of the hour, starting from a certain fixed point in the past."}},toRelativeDayNum:{bracket:"(v)",desc:{en:"Converts a date with time or date to the number of the day, starting from a certain fixed point in the past."}},toRelativeWeekNum:{bracket:"(v)",desc:{en:"Converts a date with time or date to the number of the week, starting from a certain fixed point in the past."}},splitByString:{bracket:"(separator, s)",desc:{en:"The same as above, but it uses a string of multiple characters as the separator. The string must be non-empty."}},currentDatabase:{bracket:"()",desc:{en:"Returns the name of the current database.
You can use this function in table engine parameters in a CREATE TABLE query where you need to specify the database."}},toRelativeMonthNum:{bracket:"(v)",desc:{en:"Converts a date with time or date to the number of the month, starting from a certain fixed point in the past."}},visibleWidth:{bracket:"(x)",desc:{en:"Calculates the approximate width when outputting values to the console in text format (tab-separated). This function is used by the system for implementing Pretty formats."}},bitShiftRight:{bracket:"(a, b)",desc:{en:""}},toRelativeYearNum:{bracket:"(v)",desc:{en:"Converts a date with time or date to the number of the year, starting from a certain fixed point in the past."}},toStartOfHour:{bracket:"(v)",desc:{en:"Rounds down a date with time to the start of the hour."}},halfMD5:{bracket:"(v)",desc:{en:"Calculates the MD5 from a string. Then it takes the first 8 bytes of the hash and interprets them as UInt64 in big endian."}},toStartOfFiveMinute:{bracket:"(v)",desc:{en:""}},toUInt16OrZero:{bracket:"(v)",desc:{en:"Functions for converting between numbers, strings (but not fixed strings), dates, and dates with times. All these functions accept one argument."}},toMonday:{bracket:"(v)",desc:{en:"Rounds down a date or date with time to the nearest Monday.
Returns the date."}},IPv6NumToString:{bracket:"(x)",desc:{en:"Accepts a FixedString(16) value containing the IPv6 address in binary format. Returns a string containing this address in text format. "}},indexOf:{bracket:"(arr, x)",desc:{ru:"Возвращает индекс элемента x (начиная с 1), если он есть в массиве, или 0, если его нет.",en:"Returns the index of the 'x' element (starting from 1) if it is in the array, or 0 if it is not."}},today:{bracket:"(v)",desc:{ru:"Принимает ноль аргументов и возвращает текущую дату на один из моментов выполнения запроса.
То же самое, что toDate(now())",en:"Accepts zero arguments and returns the current date at one of the moments of request execution.
The same as 'toDate(now())'."}},emptyArrayToSingle:{bracket:"(v)",desc:{ru:"Принимает пустой массив и возвращает массив из одного элемента, равного значению по умолчанию.",en:"Accepts an empty array as argument and returns an array of one element equal to the default value."}},sleep:{bracket:"(seconds)",desc:{ru:"Спит seconds секунд на каждый блок данных. Можно указать как целое число, так и число с плавающей запятой.",en:"Sleeps 'seconds' seconds on each data block. You can specify an integer or a floating-point number."}},extract:{bracket:"(params, name)",desc:{en:"Parses the string in double quotes. The value is unescaped. If unescaping failed, it returns an empty string. Examples: "}},emptyArrayInt8:{bracket:"(v)",desc:{ru:"Принимает ноль аргументов и возвращает пустой массив соответствующего типа.",en:"Accepts zero arguments and returns an empty array of the appropriate type."}},regionToName:{bracket:"(id[, lang])",desc:{en:"Accepts a UInt32 number - the region ID from the Yandex geobase. A string with the name of the language can be passed as a second argument. Supported languages are: ru, en, ua, uk, by, kz, tr. If the second argument is omitted, the language 'ru' is used. "}},concat:{bracket:"(arr[, separator])",desc:{ru:"Склеивает строки, перечисленные в массиве, с разделителем separator.
separator - необязательный параметр, константная строка, по умолчанию равен пустой строке.
Возвращается строка.",en:"Concatenates strings from the array elements, using 'separator' as the separator.
'separator' is a string constant, an optional parameter. By default it is an empty string.
Returns a string."}},convertCharset:{bracket:"(s, from, to)",desc:{ru:"Возвращает сконвертированную из кодировки from в кодировку to строку s.",en:"Returns a string with the data %%s%% (encoded as %%from%% charset) that was converted to the %%to%% charset."}},toMonth:{bracket:"(v)",desc:{ru:"Переводит дату или дату-с-временем в число типа UInt8, содержащее номер месяца (1-12).",en:"Converts a date or date with time to a UInt8 number containing the month number (1-12)."}},IPv6StringToNum:{bracket:"(s)",desc:{ru:"Функция, обратная к IPv6NumToString. Если IPv6 адрес в неправильном формате, то возвращает строку из нулевых байт.
HEX может быть в любом регистре.",en:"The reverse function of IPv6NumToString. If the IPv6 address has an invalid format, it returns a string of null bytes.
HEX can be uppercase or lowercase."}},emptyArrayString:{bracket:"(v)",desc:{ru:"Принимает ноль аргументов и возвращает пустой массив соответствующего типа.",en:"Accepts zero arguments and returns an empty array of the appropriate type."}},uptime:{bracket:"()",desc:{ru:"Возвращает аптайм сервера в секундах.",en:"Returns server's uptime in seconds."}},blockSize:{bracket:"()",desc:{en:"Gets the size of the block.
In ClickHouse, queries are always run on blocks (sets of column parts). This function allows getting the size of the block that you called it for."}},toInt64OrZero:{bracket:"(v)",desc:{en:"Functions for converting between numbers, strings (but not fixed strings), dates, and dates with times. All these functions accept one argument. "}},pathFull:{bracket:"(v)",desc:{ru:"То же самое, но включая query string и fragment. Пример: /top/news.html?page=2#comments",en:"- The same as above, but including query-string and fragment. Example: /top/news.html?page=2#comments"}},emptyArrayDate:{bracket:"(v)",desc:{ru:"Принимает ноль аргументов и возвращает пустой массив соответствующего типа.",en:"Accepts zero arguments and returns an empty array of the appropriate type."}},emptyArrayInt64:{bracket:"(v)",desc:{ru:"Принимает ноль аргументов и возвращает пустой массив соответствующего типа.",en:"Accepts zero arguments and returns an empty array of the appropriate type."}},toInt32OrZero:{bracket:"(v)",desc:{en:"Functions for converting between numbers, strings (but not fixed strings), dates, and dates with times. All these functions accept one argument. "}},greater:{bracket:"(v)",desc:{ru:"",en:""}},emptyArrayInt32:{bracket:"(v)",desc:{ru:"Принимает ноль аргументов и возвращает пустой массив соответствующего типа.",en:"Accepts zero arguments and returns an empty array of the appropriate type."}},toString:{bracket:"(str)",desc:{ru:"Принимает значение типа FixedString(16). Возвращает строку из 36 символов в текстовом виде.",en:"Accepts a FixedString(16) value containing the UUID in the binary format. Returns a readable string containing the UUID in the text format."}},greatest:{bracket:"(a, b)",desc:{ru:"Возвращает наибольшее значение из a и b.",en:"Returns the greatest element of a and b."}},emptyArrayUInt64:{bracket:"(v)",desc:{ru:"Принимает ноль аргументов и возвращает пустой массив соответствующего типа.",en:"Accepts zero arguments and returns an empty array of the appropriate type."}},emptyArrayUInt32:{bracket:"(v)",desc:{ru:"Принимает ноль аргументов и возвращает пустой массив соответствующего типа.",en:"Accepts zero arguments and returns an empty array of the appropriate type."}},formatReadableSize:{bracket:"(x)",desc:{en:"Gets a size (number of bytes). Returns a string that contains rounded size with the suffix (KiB, MiB etc.).

Example:

%% "}},toInt16OrZero:{bracket:"(v)",desc:{en:"Functions for converting between numbers, strings (but not fixed strings), dates, and dates with times. All these functions accept one argument. "}},emptyArrayUInt8:{bracket:"(v)",desc:{ru:"Принимает ноль аргументов и возвращает пустой массив соответствующего типа.",en:"Accepts zero arguments and returns an empty array of the appropriate type."}},protocol:{bracket:"(v)",desc:{ru:"Возвращает протокол. Примеры: http, ftp, mailto, magnet...",en:"- Selects the protocol. Examples: http, ftp, mailto, magnet..."}},regionToPopulation:{bracket:"(id[, geobase])",desc:{en:"Gets the population for a region.
The population can be recorded in files with the geobase. See the section "External dictionaries".
If the population is not recorded for the region, it returns 0.
In the Yandex geobase, the population might be recorded for child regions, but not for parent regions."}},notIn:{bracket:"(v)",desc:{ru:'Смотрите раздел "Операторы IN".',en:"See the section "IN operators"."}},position:{bracket:"(haystack, needle)",desc:{en:"The same as 'position', but the position is returned in Unicode code points. Works under the assumption that the string contains a set of bytes representing a UTF-8 encoded text. If this assumption is not met, it returns some result (it doesn't throw an exception).
There's also positionCaseInsensitiveUTF8 function."}},arrayElement:{bracket:"(arr, n), arr[n] operator",desc:{en:"Get the element with the index 'n' from the array 'arr'.
'n' should be any integer type.
Indexes in an array begin from one.
Negative indexes are supported - in this case, it selects the corresponding element numbered from the end. "}},toStringCutToZero:{bracket:"(s)",desc:{en:"Accepts a String or FixedString argument. Returns a String that is cut to a first null byte occurrence."}},log:{bracket:"(x)",desc:{ru:"Принимает числовой аргумент, возвращает число типа Float64, близкое к десятичному логарифму от аргумента.",en:"Accepts a numeric argument and returns a Float64 number close to the decimal logarithm of the argument."}},SEIn:{bracket:"(lhs, rhs)",desc:{ru:"Проверяет принадлежность поисковой системы lhs поисковой системе rhs.",en:"Checks whether the 'lhs' search engine belongs to the 'rhs' search engine."}},replicate:{bracket:"(v)",desc:{en:"Create a MergeTree table with a different name. Move all the data from the directory with the ReplicatedMergeTree table data to the new table's data directory."}},sipHash64:{bracket:"(v)",desc:{en:'Calculates SipHash from a string.
Accepts a String-type argument. Returns UInt64.
SipHash is a cryptographic hash function. It works at least three times faster than MD5. For more information, see https://131002.net/siphash/'}},emptyArrayUInt16:{bracket:"(v)",desc:{en:"Accepts zero arguments and returns an empty array of the appropriate type."}},hex:{bracket:"(str)",desc:{en:"Accepts a string containing any number of hexadecimal digits, and returns a string containing the corresponding bytes. Supports both uppercase and lowercase letters A-F. The number of hexadecimal digits doesn't have to be even."}},regionToDistrict:{bracket:"(id[, geobase])",desc:{en:"Converts a region to a federal district (type 4 in the geobase). In every other way, this function is the same as 'regionToCity'. "}},arrayFilter:{bracket:"(func, arr1, ...)",desc:{en:"Returns an array containing only the elements in 'arr1' for which 'func' returns something other than 0.

Examples:

%%
SELECT arrayFilter(x -> x LIKE '%World%', ['Hello', 'abc World']) AS res "}},toStartOfQuarter:{bracket:"(v)",desc:{en:"Rounds down a date or date with time to the first day of the quarter.
The first day of the quarter is either 1 January, 1 April, 1 July, or 1 October. Returns the date."}},divide:{bracket:"(a, b), a / b operator",desc:{en:"Calculates the quotient of the numbers. The result type is always a floating-point type.
It is not integer division. For integer division, use the 'intDiv' function.
When dividing by zero you get 'inf', '-inf', or 'nan'."}},reverseUTF8:{bracket:"(v)",desc:{en:"Reverses a sequence of Unicode code points, assuming that the string contains a set of bytes representing a UTF-8 text. Otherwise, it does something else (it doesn't throw an exception)."}},toDate:{bracket:"(v)",desc:{en:"Functions for converting between numbers, strings (but not fixed strings), dates, and dates with times. All these functions accept one argument. "}},emptyArrayFloat64:{bracket:"(v)",desc:{en:"Accepts zero arguments and returns an empty array of the appropriate type."}},abs:{bracket:"(s, c)",desc:{en:"If the %%s%% string is non-empty and does not contain the %%c%% character at the end, it appends the %%c%% character to the end."}},yesterday:{bracket:"(v)",desc:{en:"Accepts zero arguments and returns yesterday's date at one of the moments of request execution.
The same as 'today() - 1'."}},toMinute:{bracket:"(v)",desc:{en:"Converts a date with time to a UInt8 number containing the number of the minute of the hour (0-59)."}},bitXor:{bracket:"(a, b)",desc:{en:""}},minus:{bracket:"(a, b), a - b operator",desc:{en:"Calculates the difference. The result is always signed.

You can also calculate whole numbers from a date or date with time. The idea is the same - see above for 'plus'."}},toDateTime:{bracket:"(v)",desc:{en:"Functions for converting between numbers, strings (but not fixed strings), dates, and dates with times. All these functions accept one argument. "}},modulo:{bracket:"(a, b), a % b operator",desc:{en:"Calculates the remainder after division.
If arguments are floating-point numbers, they are pre-converted to integers by dropping the decimal portion. The remainder is taken in the same sense as in C++. Truncated division is used for negative numbers.
An exception is thrown when dividing by zero or when dividing a minimal negative number by minus one."}},bitmaskToArray:{bracket:"(num)",desc:{en:"Accepts an integer. Returns an array of UInt64 numbers containing the list of powers of two that total the source number when summed. Numbers in the array are in ascending order."}},negate:{bracket:"(a), -a operator",desc:{en:"Calculates a number with the reverse sign. The result is always signed."}},emptyArrayFloat32:{bracket:"(v)",desc:{en:"Accepts zero arguments and returns an empty array of the appropriate type."}},range:{bracket:"(N)",desc:{en:"Returns an array of numbers from 0 to N-1.
Just in case, an exception is thrown if arrays with a total length of more than 100,000,000 elements are created in a data block."}},arrayAll:{bracket:"([func,] arr1, ...)",desc:{en:"Returns 1 if 'func' returns something other than 0 for all the elements in 'arr'. Otherwise, it returns 0."}},toInt32:{bracket:"(v)",desc:{en:"Functions for converting between numbers, strings (but not fixed strings), dates, and dates with times. All these functions accept one argument. "}},unhex:{bracket:"(str)",desc:{en:"Accepts a string containing any number of hexadecimal digits, and returns a string containing the corresponding bytes. Supports both uppercase and lowercase letters A-F. The number of hexadecimal digits doesn't have to be even. If it is odd, the last digit is interpreted as the younger half of the 00-0F byte. If the argument string contains anything other than hexadecimal digits, some implementation-defined result is returned (an exception isn't thrown).
If you want to convert the result to a number, you can use the functions 'reverse' and 'reinterpretAsType'."}},toFloat64:{bracket:"(v)",desc:{en:"Functions for converting between numbers, strings (but not fixed strings), dates, and dates with times. All these functions accept one argument. "}},bitAnd:{bracket:"(a, b)",desc:{ru:"",en:""}},toStartOfYear:{bracket:"(v)",desc:{en:"Rounds down a date or date with time to the first day of the year.
Returns the date."}},bitOr:{bracket:"(a, b)",desc:{ru:"",en:""}},SEToRoot:{bracket:"(v)",desc:{en:"Accepts a UInt8 number - the ID of the search engine from the Yandex.Metrica dictionary. If any search engine matches the passed number, it returns a UInt8 number - the ID of the corresponding root search engine (for example, it converts Yandex.Images to Yandex). Otherwise, returns 0."}},toRelativeMinuteNum:{bracket:"(v)",desc:{en:"Converts a date with time or date to the number of the minute, starting from a certain fixed point in the past."}},visitParamExtractInt:{bracket:"(params, name)",desc:{ru:"Аналогично для Int64.",en:"The same as for Int64."}},emptyArrayInt16:{bracket:"(v)",desc:{en:"Accepts zero arguments and returns an empty array of the appropriate type."}},visitParamExtractString:{bracket:"(params, name)",desc:{en:"Parses the string in double quotes. The value is unescaped. If unescaping failed, it returns an empty string. "}},arrayEnumerateUniq:{bracket:"(arr, ...)",desc:{en:"Returns an array the same size as the source array, indicating for each element what its position is among elements with the same value. "}},visitParamExtractUInt:{bracket:"(params, name)",desc:{en:"Parses UInt64 from the value of the field named 'name'. If this is a string field, it tries to parse a number from the beginning of the string. If the field doesn't exist, or it exists but doesn't contain a number, it returns 0."}},toTypeName:{bracket:"(x)",desc:{en:"Gets the type name. Returns a string containing the type name of the passed argument."}},empty:{bracket:"(v)",desc:{en:"Accepts an empty array as argument and returns an array of one element equal to the default value."}},multiply:{bracket:"(a, b), a * b operator", -desc:{en:"Calculates the product of the numbers."}},has:{bracket:"('database', 'table', 'column')",desc:{ru:"",en:"Accepts constant String columns - database name, table name and column name. Returns constant UInt8 value, equal to 1 if column exists,
otherwise 0.
If table doesn't exist than exception is thrown.
For elements of nested data structure function checks existence of column. For nested data structure 0 is returned."}},bitNot:{bracket:"(a)",desc:{ru:"",en:""}},lessOrEquals:{bracket:"(v)",desc:{ru:"",en:"

greaterOrEquals, >= operator

"}},reinterpretAsInt64:{bracket:"(v)",desc:{en:""}},IPv4NumToString:{bracket:"(num)",desc:{en:"Similar to IPv4NumToString, but using %%xxx%% instead of the last octet. "}},bitShiftLeft:{bracket:"(a, b)",desc:{ru:"",en:""}},dictGetInt16:{bracket:"(v)",desc:{ru:"",en:""}},toUInt32OrZero:{bracket:"(v)",desc:{en:"Functions for converting between numbers, strings (but not fixed strings), dates, and dates with times. All these functions accept one argument. "}},regionIn:{bracket:"(lhs, rhs[, geobase])",desc:{en:"Checks whether a 'lhs' region belongs to a 'rhs' region. Returns a UInt8 number equal to 1 if it belongs, or 0 if it doesn't belong.
The relationship is reflexive - any region also belongs to itself."}},reinterpretAsUInt8:{bracket:"(v)",desc:{en:""}},dictIsIn:{bracket:"(v)",desc:{en:"%%dictIsIn('dict_name', child_id, ancestor_id)%%
- For the 'dict_name' hierarchical dictionary, finds out whether the 'child_id' key is located inside 'ancestor_id' (or matches 'ancestor_id'). Returns UInt8."}},toSecond:{bracket:"(v)",desc:{en:"Converts a date with time to a UInt8 number containing the number of the second in the minute (0-59).
Leap seconds are not accounted for."}},least:{bracket:"(a, b)",desc:{en:"Returns the least element of a and b."}},countEqual:{bracket:"(arr, x)",desc:{en:'Returns the number of elements in the array equal to 'x'. Equivalent to arrayCount(elem -> elem = x, arr).'}},IPv4StringToNum:{bracket:"(s)",desc:{en:"The reverse function of IPv4NumToString. If the IPv4 address has an invalid format, it returns 0."}},replaceRegexpAll:{bracket:"(haystack, pattern, replacement)",desc:{en:"This does the same thing, but replaces all the occurrences"}},SHA224:{bracket:"(v)",desc:{en:"Calculates SHA-1, SHA-224, or SHA-256 from a string and returns the resulting set of bytes as FixedString(20), FixedString(28), or FixedString(32).
The function works fairly slowly (SHA-1 processes about 5 million short strings per second per processor core, while SHA-224 and SHA-256 process about 2.2 million). "}},URLHash:{bracket:"(url[, N])",desc:{en:"A fast, decent-quality non-cryptographic hash function for a string obtained from a URL using some type of normalization.
URLHash(s) - Calculates a hash from a string without one of the trailing symbols /,? or # at the end, if present"}},equals:{bracket:"(v)",desc:{ru:"",en:"

greaterOrEquals, >= operator

"}},plus:{bracket:"(a, b), a + b operator",desc:{ru:"Вычисляет сумму чисел.

Также можно складывать целые числа с датой и датой-с-временем. В случае даты, прибавление целого числа означает прибавление соответствующего количества дней. В случае даты-с-временем - прибавление соответствующего количества секунд.",en:"Calculates the sum of the numbers.

You can also add whole numbers with a date or date and time. In the case of a date, adding a whole number means adding the corresponding number of days. For a date with time, it means adding the corresponding number of seconds."}},less:{bracket:"(v)",desc:{ru:"",en:"

greaterOrEquals, >= operator

"}},regionHierarchy:{bracket:"(id[, geobase])",desc:{en:"Accepts a UInt32 number - the region ID from the Yandex geobase. Returns an array of region IDs consisting of the passed region and all parents along the chain.
Example: %%regionHierarchy(toUInt32(213)) = [213,1,3,225,10001,10000]%%."}},toUInt64OrZero:{bracket:"(v)",desc:{en:"Functions for converting between numbers, strings (but not fixed strings), dates, and dates with times. All these functions accept one argument. "}},rowNumberInAllBlocks:{bracket:"()",desc:{en:"Returns an incremental row number within all blocks that were processed by this function."}},toDayOfWeek:{bracket:"(v)",desc:{en:"Converts a date or date with time to a UInt8 number containing the number of the day of the week (Monday is 1, and Sunday is 7)."}},bar:{bracket:"(v)",desc:{en:"Allows building a unicode-art diagram.

bar(x, min, max, width) - Draws a band with a width proportional to (x - min) and equal to 'width' characters when x"}},"if":{bracket:"(v)",desc:{en:"The suffix -%%If%% can be appended to the name of any aggregate function. In this case, the aggregate function accepts an extra argument - a condition (Uint8 type). "}},regionToArea:{bracket:"(id[, geobase])",desc:{en:"Converts a region to an area (type 5 in the geobase). In every other way, this function is the same as 'regionToCity'.──────────────────────────────────"}},dictGetUInt16:{bracket:"(v)",desc:{ru:"",en:""}},toUInt8:{bracket:"(v)",desc:{en:"Functions for converting between numbers, strings (but not fixed strings), dates, and dates with times. All these functions accept one argument. "}},toUInt16:{bracket:"(v)",desc:{en:"Functions for converting between numbers, strings (but not fixed strings), dates, and dates with times. All these functions accept one argument. "}},path:{bracket:"(URL)",desc:{en:"- The same thing, but without the protocol and host in the result. The / element (root) is not included."}},extractURLParameters:{bracket:"(URL)",desc:{ru:"Возвращает массив строк вида name=value, соответствующих параметрам URL. Значения никак не декодируются.",en:"- Gets an array of name=value strings corresponding to the URL parameters. The values are not decoded in any way."}},OSHierarchy:{bracket:"(v)",desc:{ru:"Принимает число типа UInt8 - идентификатор операционной системы из словаря Яндекс.Метрики. Возвращает массив с иерархией операционных систем. Аналогично функции regionHierarchy.",en:"Accepts a UInt8 number - the ID of the operating system from the Yandex.Metrica dictionary. Returns an array with a hierarchy of operating systems. Similar to the 'regionHierarchy' function."}},cutQueryStringAndFragment:{bracket:"(v)",desc:{ru:"Удаляет query string и fragment identifier. Знак вопроса и символ решётки тоже удаляются.",en:"Removes the query-string and fragment identifier. The question mark and number sign are also removed."}},timeSlots:{bracket:"(StartTime, Duration)",desc:{ru:"Для интервала времени, начинающегося в StartTime и продолжающегося Duration секунд, возвращает массив моментов времени, состоящий из округлений вниз до получаса точек из этого интервала.
Например, %%timeSlots(toDateTime('2012-01-01 12:20:00'), toUInt32(600)) = [toDateTime('2012-01-01 12:00:00'), toDateTime('2012-01-01 12:30:00')]%%.
Это нужно для поиска хитов, входящих в соответствующий визит.",en:"For a time interval starting at 'StartTime' and continuing for 'Duration' seconds, it returns an array of moments in time, consisting of points from this interval rounded down to the half hour.
For example, %%timeSlots(toDateTime('2012-01-01 12:20:00'), toUInt32(600)) = [toDateTime('2012-01-01 12:00:00'), toDateTime('2012-01-01 12:30:00')]%%.
This is necessary for searching for pageviews in the corresponding session."}},toUInt32:{bracket:"(v)",desc:{en:"Functions for converting between numbers, strings (but not fixed strings), dates, and dates with times. All these functions accept one argument. "}},toStartOfMinute:{bracket:"(v)",desc:{ru:"Округляет дату-с-временем вниз до начала минуты.",en:"Rounds down a date with time to the start of the minute."}},version:{bracket:"()",desc:{ru:"Возвращает версию сервера в виде строки.",en:"Returns server's version as a string."}},toUInt64:{bracket:"(v)",desc:{en:"Functions for converting between numbers, strings (but not fixed strings), dates, and dates with times. All these functions accept one argument. "}},toInt16:{bracket:"(v)",desc:{en:"Functions for converting between numbers, strings (but not fixed strings), dates, and dates with times. All these functions accept one argument. "}},reinterpretAsInt16:{bracket:"(v)",desc:{en:""}},toInt64:{bracket:"(v)",desc:{en:"Functions for converting between numbers, strings (but not fixed strings), dates, and dates with times. All these functions accept one argument. "}},toFixedString:{bracket:"(s, N)",desc:{ru:"Преобразует аргумент типа String в тип FixedString(N) (строку фиксированной длины N). N должно быть константой.
Если строка имеет меньше байт, чем N, то она дополняется нулевыми байтами справа. Если строка имеет больше байт, чем N - кидается исключение.",en:"Converts a String type argument to a FixedString(N) type (a string with fixed length N). N must be a constant. If the string has fewer bytes than N, it is passed with null bytes to the right. If the string has more bytes than N, an exception is thrown."}},toFloat32:{bracket:"(v)",desc:{en:"Functions for converting between numbers, strings (but not fixed strings), dates, and dates with times. All these functions accept one argument. "}},dictGetHierarchy:{bracket:"(v)",desc:{ru:"%%dictGetHierarchy('dict_name', id)%%
- для иерархического словаря dict_name - вернуть массив ключей словаря, начиная с id и продолжая цепочкой родительских элементов. Возвращает Array(UInt64).",en:"%%dictGetHierarchy('dict_name', id)%%
- For the 'dict_name' hierarchical dictionary, returns an array of dictionary keys starting from 'id' and continuing along the chain of parent elements. Returns Array(UInt64)."}},dictGetInt64:{bracket:"(v)",desc:{ru:"",en:""}},CAST:{bracket:"(x, t)",desc:{en:"Casts x to the t data type.
The syntax %%CAST(x AS t)%% is also supported.
"}},toRelativeSecondNum:{bracket:"(v)",desc:{ru:"Переводит дату-с-временем в номер секунды, начиная с некоторого фиксированного момента в прошлом.",en:"Converts a date with time or date to the number of the second, starting from a certain fixed point in the past."}},toUInt8OrZero:{bracket:"(v)",desc:{en:"Functions for converting between numbers, strings (but not fixed strings), dates, and dates with times. All these functions accept one argument. "}},toStartOfMonth:{bracket:"(v)",desc:{ru:"Округляет дату или дату-с-временем вниз до первого дня месяца.
Возвращается дата.",en:"Rounds down a date or date with time to the first day of the month.
Returns the date."}},rand64:{bracket:"(v)",desc:{ru:"Возвращает псевдослучайное число типа UInt64, равномерно распределённое среди всех чисел типа UInt64.
Используется linear congruential generator.",en:"Returns a pseudo-random UInt64 number, evenly distributed among all UInt64-type numbers.
Uses a linear congruential generator."}},toInt8OrZero:{bracket:"(v)",desc:{en:"Functions for converting between numbers, strings (but not fixed strings), dates, and dates with times. All these functions accept one argument. "}},toFloat32OrZero:{bracket:"(v)",desc:{en:"Functions for converting between numbers, strings (but not fixed strings), dates, and dates with times. All these functions accept one argument. "}},toYear:{bracket:"(v)",desc:{ru:"Переводит дату или дату-с-временем в число типа UInt16, содержащее номер года (AD).",en:"Converts a date or date with time to a UInt16 number containing the year number (AD)."}},atan:{bracket:"(x)",desc:{ru:"Арктангенс.",en:"The arc tangent."}},toFloat64OrZero:{bracket:"(v)",desc:{en:"Functions for converting between numbers, strings (but not fixed strings), dates, and dates with times. All these functions accept one argument. "}},arrayEnumerate:{bracket:"(arr, ...)",desc:{en:"Returns an array the same size as the source array, indicating for each element what its position is among elements with the same value.
"}},toDayOfMonth:{bracket:"(v)",desc:{en:"Converts a date or date with time to a UInt8 number containing the number of the day of the month (1-31)."}},dictGetUInt64:{bracket:"(v)",desc:{ru:"",en:""}},IPv4NumToStringClassC:{bracket:"(num)",desc:{en:"Similar to IPv4NumToString, but using %%xxx%% instead of the last octet. "}},reinterpretAsString:{bracket:"(v)",desc:{en:"This function accepts a number or date or date with time, and returns a string containing bytes representing the corresponding value in host order (little endian). Null bytes are dropped from the end. For example, a UInt32 type value of 255 is a string that is one byte long."}},toHour:{bracket:"(v)",desc:{en:"Converts a date with time to a UInt8 number containing the number of the hour in 24-hour time (0-23).
This function assumes that if clocks are moved ahead, it is by one hour and occurs at 2 a.m., and if clocks are moved back, it is by one hour and occurs at 3 a.m. (which is not always true - even in Moscow the clocks were once changed at a different time)."}},ignore:{bracket:"(...)",desc:{en:"A function that accepts any arguments and always returns 0.
However, the argument is still calculated. This can be used for benchmarks."}},arrayJoin:{bracket:"(v)",desc:{en:"This is a very unusual function.

Normal functions don't change a set of rows, but just change the values in each row (map). Aggregate functions compress a set of rows (fold or reduce).
The 'arrayJoin' function takes each row and generates a set of rows (unfold).

T"}},length:{bracket:"(v)",desc:{en:"Returns the length of a string in Unicode code points (not in characters), assuming that the string contains a set of bytes that make up UTF-8 encoded text. If this assumption is not met, it returns some result (it doesn't throw an exception).
The result type is UInt64."}},tuple:{bracket:"(tuple, n), operator x.N",desc:{en:"A function that allows getting columns from a tuple.
'N' is the column index, starting from 1. 'N' must be a constant. 'N' must be a strict postive integer no greater than the size of the tuple.
There is no cost to execute the function."}},extractURLParameterNames:{bracket:"(URL)",desc:{en:"- Gets an array of name=value strings corresponding to the names of URL parameters. The values are not decoded in any way."}},tupleElement:{bracket:"(tuple, n), operator x.N",desc:{en:"A function that allows getting columns from a tuple.
'N' is the column index, starting from 1. 'N' must be a constant. 'N' must be a strict postive integer no greater than the size of the tuple.
There is no cost to execute the function."}},"in":{bracket:"(v)",desc:{en:"What to do when the amount of data exceeds one of the limits: 'throw' or 'break'. By default, throw."}},globalIn:{bracket:"(v)",desc:{en:"See the section "IN operators"."}},isFinite:{bracket:"(x)",desc:{en:"Accepts Float32 and Float64 and returns UInt8 equal to 1 if the argument is not infinite and not a NaN, otherwise 0."}},isNaN:{bracket:"(x)",desc:{en:"Accepts Float32 and Float64 and returns UInt8 equal to 1 if the argument is a NaN, otherwise 0."}},isInfinite:{bracket:"(x)",desc:{en:"Accepts Float32 and Float64 and returns UInt8 equal to 1 if the argument is infinite, otherwise 0.
Note that 0 is returned for a NaN."}},transform:{bracket:"(v)",desc:{en:"Transforms a value according to the explicitly defined mapping of some elements to other ones.
There are two variations of this function:

1. %%transform(x, array_from, array_to, default)%% "}},rand:{bracket:"(v)",desc:{en:"Returns a pseudo-random UInt64 number, evenly distributed among all UInt64-type numbers.
Uses a linear congruential generator."}},reinterpretAsUInt16:{bracket:"(v)",desc:{en:""}},pi:{bracket:"(v)",desc:{en:"Maximum pipeline depth. Corresponds to the number of transformations that each data block goes through during query processing. Counted within the limits of a single server. If the pipeline depth is greater, an exception is thrown. By default, 1000."}},reinterpretAsUInt32:{bracket:"(v)",desc:{en:""}},reinterpretAsUInt64:{bracket:"(v)",desc:{en:""}},reinterpretAsInt8:{bracket:"(v)",desc:{en:""}},upperUTF8:{bracket:"(v)",desc:{en:"Converts a string to uppercase, assuming the string contains a set of bytes that make up a UTF-8 encoded text. It doesn't detect the language. So for Turkish the result might not be exactly correct. "}},reinterpretAsInt32:{bracket:"(v)",desc:{en:""}},reinterpretAsFloat32:{bracket:"(v)",desc:{en:""}},reinterpretAsFloat64:{bracket:"(v)",desc:{en:""}},reinterpretAsDate:{bracket:"(v)",desc:{en:""}},reinterpretAsDateTime:{bracket:"(v)",desc:{en:""}},roundToExp2:{bracket:"(num)",desc:{en:"Accepts a number. If the number is less than one, it returns 0. Otherwise, it rounds the number down to the nearest (whole non-negative) degree of two."}},upper:{bracket:"(v)",desc:{en:"Converts a string to uppercase, assuming the string contains a set of bytes that make up a UTF-8 encoded text. It doesn't detect the language. So for Turkish the result might not be exactly correct."}},positionUTF8:{bracket:"(haystack, needle)",desc:{en:"The same as 'position', but the position is returned in Unicode code points. Works under the assumption that the string contains a set of bytes representing a UTF-8 encoded text. If this assumption is not met, it returns some result (it doesn't throw an exception).
There's also positionCaseInsensitiveUTF8 function."}},roundDuration:{bracket:"(num)",desc:{en:"Accepts a number. If the number is less than one, it returns 0. Otherwise, it rounds the number down to numbers from the set: 1, 10, 30, 60, 120, 180, 240, 300, 600, 1200, 1800, 3600, 7200, 18000, 36000. This function is specific to Yandex.Metrica and used for implementing the report on session length."}},roundAge:{bracket:"(num)",desc:{en:"Accepts a number. If the number is less than 18, it returns 0. Otherwise, it rounds the number down to numbers from the set: 18, 25, 35, 45. This function is specific to Yandex.Metrica and used for implementing the report on user age."}},round:{bracket:"(num)",desc:{en:"Accepts a number. If the number is less than 18, it returns 0. Otherwise, it rounds the number down to numbers from the set: 18, 25, 35, 45. This function is specific to Yandex.Metrica and used for implementing the report on user age."}},floor:{bracket:"(x[, N])",desc:{en:"Returns a rounder number that is less than or equal to 'x'."}},notEmpty:{bracket:"(v)",desc:{en:"Returns 0 for an empty array, or 1 for a non-empty array.
The result type is UInt8.
The function also works for strings."}},lengthUTF8:{bracket:"(v)",desc:{en:"Returns the length of a string in Unicode code points (not in characters), assuming that the string contains a set of bytes that make up UTF-8 encoded text. If this assumption is not met, it returns some result (it doesn't throw an exception).
The result type is UInt64."}},lower:{bracket:"(v)",desc:{en:"Converts a string to lowercase, assuming the string contains a set of bytes that make up a UTF-8 encoded text. It doesn't detect the language. "}},lowerUTF8:{bracket:"(v)",desc:{en:"Converts a string to lowercase, assuming the string contains a set of bytes that make up a UTF-8 encoded text. It doesn't detect the language. "}},reverse:{bracket:"(v)",desc:{en:"Reverses a sequence of Unicode code points, assuming that the string contains a set of bytes representing a UTF-8 text. Otherwise, it does something else (it doesn't throw an exception)."}},URLPathHierarchy:{bracket:"(URL)",desc:{en:"- The same thing, but without the protocol and host in the result. The / element (root) is not included. "}},substringUTF8:{bracket:"(s, offset, length)",desc:{en:"The same as 'substring', but for Unicode code points. Works under the assumption that the string contains a set of bytes representing a UTF-8 encoded text. If this assumption is not met, it returns some result (it doesn't throw an exception)."}},appendTrailingCharIfAbsent:{bracket:"(s, c)",desc:{en:"If the %%s%% string is non-empty and does not contain the %%c%% character at the end, it appends the %%c%% character to the end."}},alphaTokens:{bracket:"(s)",desc:{en:"Selects substrings of consecutive bytes from the range a-z and A-Z.
Returns an array of selected substrings."}},splitByChar:{bracket:"(separator, s)",desc:{en:"Splits a string into substrings, using 'separator' as the separator.
'separator' must be a string constant consisting of exactly one character.
Returns an array of selected substrings"}},arrayStringConcat:{bracket:"(arr[, separator])",desc:{en:"Concatenates strings from the array elements, using 'separator' as the separator.
'separator' is a string constant, an optional parameter. By default it is an empty string.
Returns a string."}},replaceAll:{bracket:"(haystack, pattern, replacement)",desc:{en:"Replaces all occurrences of the 'pattern' substring in 'haystack' with the 'replacement' substring."}},replaceRegexpOne:{bracket:"(haystack, pattern, replacement)",desc:{en:"Replacement using the 'pattern' regular expression. A re2 regular expression. Replaces only the first occurrence, if it exists.
A pattern can be specified as 'replacement'. "}},cbrt:{bracket:"(x)",desc:{en:"Accepts a numeric argument and returns a Float64 number close to the cubic root of the argument."}},match:{bracket:"(pattern)(time, cond1, cond2, ...)",desc:{en:"Pattern matching for event chains.

'pattern' is a string containing a pattern to match. The pattern is similar to a regular expression."}},cutURLParameter:{bracket:"(URL, name)",desc:{en:"Removes the URL parameter named 'name', if present. This function works under the assumption that the parameter name is encoded in the URL exactly the same way as in the passed argument."}},like:{bracket:"(haystack, pattern), haystack NOT LIKE pattern operator",desc:{en:"The same thing as 'like', but negative."}},domain:{bracket:"(v)",desc:{en:"- Selects the part of the domain that includes top-level subdomains up to the "first significant subdomain" (see the explanation above).
For example, cutToFirstSignificantSubdomain('https://news.yandex.com.tr/') = 'yandex.com.tr'."}},domainWithoutWWW:{bracket:"(v)",desc:{en:"- Selects the domain and removes no more than one 'www.' from the beginning of it, if present."}},firstSignificantSubdomain:{bracket:"(v)",desc:{en:"- Selects the part of the domain that includes top-level subdomains up to the "first significant subdomain" (see the explanation above).
For example, cutToFirstSignificantSubdomain('https://news.yandex.com.tr/') = 'yandex.com.tr'."}},queryString:{bracket:"(v)",desc:{en:"Removes the query-string and fragment identifier. The question mark and number sign are also removed."}},queryStringAndFragment:{bracket:"(v)",desc:{en:"Removes the query-string and fragment identifier. The question mark and number sign are also removed."}},extractURLParameter:{bracket:"(URL)",desc:{en:"- Gets an array of name=value strings corresponding to the names of URL parameters. The values are not decoded in any way."}},URLHierarchy:{bracket:"(URL)",desc:{en:"- Gets an array containing the URL trimmed to the %%/%%, %%?%% characters in the path and query-string. Consecutive separator characters are counted as one. The cut is made in the position after all the consecutive separator characters. Example:"}},cutToFirstSignificantSubdomain:{bracket:"(v)",desc:{en:"- Selects the part of the domain that includes top-level subdomains up to the "first significant subdomain" (see the explanation above).
For example, cutToFirstSignificantSubdomain('https://news.yandex.com.tr/') = 'yandex.com.tr'."}},cutWWW:{bracket:"(v)",desc:{en:"Removes no more than one 'www.' from the beginning of the URL's domain, if present."}},cutQueryString:{bracket:"(v)",desc:{en:"Removes the query-string and fragment identifier. The question mark and number sign are also removed."}},cutFragment:{bracket:"(v)",desc:{en:"Removes the fragment identifier. The number sign is also removed."}},visitParamHas:{bracket:"(params, name)",desc:{en:"Checks whether there is a field with the 'name' name."}},visitParamExtractFloat:{bracket:"(params, name)",desc:{en:"The same as for Float64."}},visitParamExtractBool:{bracket:"(params, name)",desc:{en:"Parses a true/false value. The result is UInt8."}},visitParamExtractRaw:{bracket:"(params, name)",desc:{en:"Returns the value of a field, including separators."}},exp:{bracket:"(x)",desc:{en:"Accepts a numeric argument and returns a Float64 number close to 10x."}},exp2:{bracket:"(x)",desc:{en:"Accepts a numeric argument and returns a Float64 number close to 2x."}},exp10:{bracket:"(x)",desc:{en:"Accepts a numeric argument and returns a Float64 number close to 10x."}},tgamma:{bracket:"(x)",desc:{en:"Gamma function."}},log10:{bracket:"(x)",desc:{en:"Accepts a numeric argument and returns a Float64 number close to the decimal logarithm of the argument."}},sqrt:{bracket:"(x)",desc:{en:"Accepts a numeric argument and returns a Float64 number close to the square root of the argument."}},erf:{bracket:"(v)",desc:{en:"What to do when the amount of data exceeds one of the limits: 'throw' or 'break'. By default, throw."}},erfc:{bracket:"(x)",desc:{en:"Accepts a numeric argument and returns a Float64 number close to 1 - erf(x), but without loss of precision for large 'x' values."}},lgamma:{bracket:"(x)",desc:{en:"The logarithm of the gamma function."}},sin:{bracket:"(x)",desc:{en:"Accepts Float32 and Float64 and returns UInt8 equal to 1 if the argument is infinite, otherwise 0.
Note that 0 is returned for a NaN."}},cos:{bracket:"(x)",desc:{ru:"Арккосинус.",en:"The arc cosine."}},tan:{bracket:"(x)",desc:{ru:"Арктангенс.",en:"The arc tangent."}},pow:{bracket:"(x, y)",desc:{ru:"xy.",en:"xy."}}}},/* - * Licensed under the Apache License, Version 2.0 Copyright 2017 Igor Strykhar,Ivan Kudinov,SMI2 LLC and other contributors - */ -function(){angular.module(smi2.app.name).run(["$rootScope","$state","$mdTheming","ThemeService","localStorageService",function(e,t,a,n,r){e.breadcrumbs=[],e.currentDatabase=null;var i=e.$on("$stateChangeError",function(e,a,n,r,i,s){"notAuthorized"==s&&t.go("login")});e.$on("$destroy",function(){return i}),window.document.title="Tabix.IO ["+window.TabixBuildDate+"]",e.sqlLog=r.get("sqlLog")||[],e.$watch("sqlLog",function(e){r.set("sqlLog",e)}),e.isInitDatabaseStructure=!1,e.sidebar={letf_resizable_width:200,clickLetfResizable:function(){e.sidebar.letf_resizable_width<10?e.sidebar.letf_resizable_width=200:e.sidebar.letf_resizable_width=0}}}])}(),/* - * Licensed under the Apache License, Version 2.0 Copyright 2017 Igor Strykhar,Ivan Kudinov,SMI2 LLC and other contributors - */ -function(e,t){e.module(t.app.name).config(["$stateProvider",function(t){t.state("base",{"abstract":!0,resolve:{session:["$q","API",function(t,a){window.global_tabix_disable_exit=!1,_.isObject(window.global_tabix_default_settings)&&(_.isUndefined(window.global_tabix_default_settings.host)||_.isUndefined(window.global_tabix_default_settings.login)||(window.global_tabix_disable_exit=!0,a.setConnection(window.global_tabix_default_settings)));var n=t.defer();return e.isDefined(a.getConnectionInfo().host)?n.resolve():n.reject("notAuthorized"),n.promise}]},templateUrl:"app/base/base.html"}).state("layout",{parent:"base","abstract":!0,views:{header:{templateUrl:"app/base/header.html",controller:"HeaderController"},sidebar:{templateUrl:"app/base/sidebar.html",controller:"SidebarController"},main:{template:""}}}).state("layoutDash",{parent:"base","abstract":!0,views:{header:{templateUrl:"app/base/header.html",controller:"HeaderController"},main:{template:""}}}).state("dashboard",{parent:"layout",url:"",controller:["$state",function(e){e.go("sql")}]}).state("dash",{parent:"layout",url:"/dash",templateUrl:"app/dash/dash.html",controller:"DashController"}).state("edit",{parent:"layoutDash",url:"/edit",templateUrl:"app/dash/edit.html",controller:"EditController"}).state("preference",{parent:"layout",url:"/Preference",templateUrl:"app/preference/preference.html",controller:"PreferenceController"}).state("login",{url:"/login",templateUrl:"app/login/login.html",controller:"LoginController"}).state("sql",{parent:"layout",url:"/sql",templateUrl:"app/sql/sql.html",controller:"SqlController"}).state("table",{parent:"layout",url:"/database/{dbName}/table/{tableName}",templateUrl:"app/table/table.html",controller:"TableController"}).state("metrics",{parent:"layoutDash",url:"/metrics",templateUrl:"app/metrics/metrics.html",controller:"MetricsController"}).state("404",{parent:"layout",templateUrl:"app/base/404.html"})}])}(angular,smi2),/* - * Licensed under the Apache License, Version 2.0 Copyright 2017 Igor Strykhar,Ivan Kudinov,SMI2 LLC and other contributors - */ -function(e,t){e.module(t.app.name).config(["$locationProvider","$httpProvider","$sceProvider","$urlRouterProvider","ThemeServiceProvider","$mdThemingProvider",function(e,t,a,n,r,i){t.interceptors.push("HttpInterceptor"),a.enabled(!1);var s=!1;s=_.isFunction(r.$get[0])?r.$get[0]().isDark():r.$get().isDark(),console.log("isDark",s),s&&i.theme("default").dark().primaryPalette("blue").accentPalette("blue",{"default":"500"}),window.disableNgInspectWatchers=!1,n.otherwise(function(e){var t=e.get("$state");t.transitionTo("404")})}])}(angular,smi2); \ No newline at end of file diff --git a/build/scripts/app.js b/build/scripts/app.js index 03c28949..db7cf63a 100644 --- a/build/scripts/app.js +++ b/build/scripts/app.js @@ -587,11 +587,11 @@ T.push(K)}else if("l"===t.substr(0,1)){if(0>=D)throw"Logarithmic scales are only "use strict";function _toConsumableArray(e){if(Array.isArray(e)){for(var t=0,a=Array(e.length);t

404 not found

Back'),e.put("app/base/addVarsDialog.html",'

Mango (Fruit)

Add var (no space)
TextIntDateCode
CloseAdd
'),e.put("app/base/base.html",'
Open table
'),e.put("app/base/breadcrumbs.html",''),e.put("app/base/header.html",'
Requirements Chrome! SQL Metrics & Processes Settings Help Sign out [{{user}}]
'),e.put("app/base/helpDialogLogin.html",'

Tabix.io Build {{::vars.version}} [{{::vars.buildDate}}]

* Work only in "Google chrome" version up 55

* Clickhouse server version up v1.1.54164

* Not readonly CH user




https://tabix.ioOk
'),e.put("app/base/helpDialogRu.html",'

Tabix.io Build {{::vars.version}} [{{::vars.buildDate}}]

ClickHouse Руководство


Tabix Руководство

Hot keys

⌘ + Enter

Exec current query

⌘ + Shift + Enter

Exec all query

⌘ + Y

Drop current line

⌘ + ⇧ + F

Reformat

⌘ + ⇧ + Plus|Minus

свернуть все/развернуть

⌘ + Right|Left

переключает вкладки

⌘ + ⌥ + Up|Down

Copy lines Up/Down

⌥ + Up|Down

Move lines Up/Down

Ctrl + K

Remove to line end

⌘ + Backspace

Remove to linestart

Ace Editor Default Keyboard Shortcuts

DrawChart

DrawChart

DrawMap

DrawMap

https://tabix.ioOk
'),e.put("app/base/sidebar.html",''),e.put("app/base/sidebarhelper.html",'

{{ hist }}

'),e.put("app/dash/dash.html",' Raised and Accent ButtonKILL

vars.show:{{vars.show}}
vars.show:{{vars.show}}draw-widget
'),e.put("app/dash/edit.html",'
'),e.put("app/login/login.html",'
Requirements Chrome or Chromium engine Browser! Requirements & helpUi Theme{{theme.title}}
'),e.put("app/render/WidgetsList.html",'
'),e.put("app/metrics/dialog.kill.html",'

Kill query

{{ q.elapsed }}

{{ q.query }}

{{ q.bytes_read }}

{{ q.hash }}

Cancel
'),e.put("app/metrics/metrics.html",'Processes
Overview
Metrics
'),e.put("app/metrics/metricschart.html",'

Metrics

{{interval == -1 ? (\'Refresh is disabled\') : interval +\' \'+(\'sec\')}}{{interval}}system.eventsRefreshReset
'),e.put("app/metrics/overview.html",'

Overview

'),e.put("app/metrics/processes.html",'

Processes

{{interval == -1 ? (\'Refresh is disabled\') : interval +\' \'+\'sec\'}}Word wrapLog ModeClusterRefreshResetKILL Query
'),e.put("app/preference/preference.html",'

Preference & settings

{{theme}}{{theme}}Save sessionLive AutocompletionDisable auto-helpDisable hotKey left+rightUse WrapModeShow invisible charsApply
'),e.put("app/sql/PlotlyEditor.tmpl.html",'

PlotLy JavaScript editor ( alpha )

'),e.put("app/sql/renderResult.html",'
{{::tableData.data.progressQuery}}CSV with headersCSV without headersTSV with headersTSV without headersPinnedEdit Plotly chartTable
Draw
'), +!function(){var e=window.smi2=window.smi2||{};e.app={name:"SMI2",version:window.TabixVersion||"",buildDate:window.TabixBuildDate||""},angular.module(e.app.name,["ui.router","LocalStorageModule","angularScreenfull","ui.ace","ngScrollbars","angularResizable","ngSanitize","ngMaterial","funMetisMenu","ngCsv","cfp.hotkeys","ngHandsontable","ngCsvImport","gridstack-angular"])}(),angular.module("SMI2").run(["$templateCache",function(e){e.put("app/base/404.html",'

404 not found

Back
'),e.put("app/base/addVarsDialog.html",'

Mango (Fruit)

Add var (no space)
TextIntDateCode
CloseAdd
'),e.put("app/base/base.html",'
Open table
'),e.put("app/base/breadcrumbs.html",''),e.put("app/base/header.html",'
Requirements Chrome! SQL Metrics & Processes Settings Help Sign out [{{user}}]
'),e.put("app/base/helpDialogLogin.html",'

Tabix.io Build {{::vars.version}} [{{::vars.buildDate}}]

* Work only in "Google chrome" version up 55

* Clickhouse server version up v1.1.54164

* Not readonly CH user




https://tabix.ioOk
'),e.put("app/base/helpDialogRu.html",'

Tabix.io Build {{::vars.version}} [{{::vars.buildDate}}]

ClickHouse Руководство


Tabix Руководство

Hot keys

⌘ + Enter

Exec current query

⌘ + Shift + Enter

Exec all query

⌘ + Y

Drop current line

⌘ + ⇧ + F

Reformat

⌘ + ⇧ + Plus|Minus

свернуть все/развернуть

⌘ + Right|Left

переключает вкладки

⌘ + ⌥ + Up|Down

Copy lines Up/Down

⌥ + Up|Down

Move lines Up/Down

Ctrl + K

Remove to line end

⌘ + Backspace

Remove to linestart

Ace Editor Default Keyboard Shortcuts

DrawChart

DrawChart

DrawMap

DrawMap

https://tabix.ioOk
'),e.put("app/base/sidebar.html",''),e.put("app/base/sidebarhelper.html",'

{{ hist }}

'),e.put("app/dash/dash.html",' Raised and Accent ButtonKILL

vars.show:{{vars.show}}
vars.show:{{vars.show}}draw-widget
'),e.put("app/dash/edit.html",'
'),e.put("app/login/login.html",'
Requirements Chrome or Chromium engine Browser! Requirements & helpUi Theme{{theme.title}}
'),e.put("app/metrics/dialog.kill.html",'

Kill query

{{ q.elapsed }}

{{ q.query }}

{{ q.bytes_read }}

{{ q.hash }}

Cancel
'),e.put("app/metrics/metrics.html",'Processes
Overview
Metrics
'),e.put("app/metrics/metricschart.html",'

Metrics

{{interval == -1 ? (\'Refresh is disabled\') : interval +\' \'+(\'sec\')}}{{interval}}system.eventsRefreshReset
'),e.put("app/metrics/overview.html",'

Overview

'),e.put("app/metrics/processes.html",'

Processes

{{interval == -1 ? (\'Refresh is disabled\') : interval +\' \'+\'sec\'}}Word wrapLog ModeClusterRefreshResetKILL Query
'),e.put("app/preference/preference.html",'

Preference & settings

{{theme}}{{theme}}Save sessionLive AutocompletionDisable auto-helpDisable hotKey left+rightUse WrapModeShow invisible charsApply
'),e.put("app/render/WidgetsList.html",'
'),e.put("app/sql/PlotlyEditor.tmpl.html",'

PlotLy JavaScript editor ( alpha )

'),e.put("app/sql/renderResult.html",'
{{::tableData.data.progressQuery}}CSV with headersCSV without headersTSV with headersTSV without headersPinnedEdit Plotly chartTable
Draw
'), e.put("app/sql/showDialogUpload.html",'

Upload CSV to View

'),e.put("app/sql/sql.html",'
{{tab.name + (tab.changed ? \' *\' : \'\')}}
Make snippetAutoFormatExpandCollapseCollapse All
{{tab.buttonTitle}}Run current ⌘ + ⏎Full screenSave{{item.name}}Query log
USE {{::dbb.name}}{{vars.LastStatistics.elapsed| number:2}} sec.| {{vars.LastStatistics.rows_read| number}} rows.| {{vars.LastStatistics.bytes_read|filesize}}
..... {{tab.progress.query}}
'),e.put("app/table/table-container.html",'

{{vars.currentDatabase}} {{vars.currentTable}}

Structure
NameTypeDefault typeValueSizeCompress
{{$index + 1}}{{field[key]}}
Information
1Size{{vars.statistics.size}}
2Size,bytes{{vars.statistics.sizeBytes}}
3First row{{vars.statistics.minDate}}
4Last row{{vars.statistics.maxDate}}

SHOW CREATE TABLE
{{vars.createtable}}
Data
Data From {{vars.offset}} To {{vars.offset + vars.limit}}
No data
'),e.put("app/table/table.html",'
')}]),function(e,t){function a(e,t){var a=t.dbName,n=t.tableName;e.vars={dbName:a,tableName:n}}e.module(t.app.name).controller("TableController",a),a.$inject=["$scope","$stateParams"]}(angular,smi2),function(e,t){function a(t,a,n,r,i,s,o,c){t.tablewidget={},t.vars={columns:{},ugrid:{},sortColumn:!1,isDark:r.isDark(),createtable:{},data:null,grid:null,limit:100,offset:0,statistics:{},loading:!0,isRawStatistics:!1,rawstatistics:"",scrollConfig:{autoHideScrollbar:!1,theme:r.isDark()?"light":"dark",scrollButtons:{enable:!1},scrollInertia:100,advanced:{updateOnContentResize:!0}}},t.initContainer=function(){a.$watch("currentTable",function(e){e&&(t.vars.currentTable=a.currentTable,t.vars.currentDatabase=a.currentDatabase,t.init())})},t.onAfterInit=function(){},t.updateHandTable=function(){c.getInstance("hotTableContain").render()},t.initOnGo=function(){t.$parent.vars&&(o.get("tableSiedenav")&&s("tableSiedenav").close(),t.vars.currentTable=t.$parent.vars.tableName,t.vars.currentDatabase=t.$parent.vars.dbName,t.init())},t.load=function(){console.warn("LOAD DATA! IN TABLES"),t.vars.data=-1,n.query("\n select * from "+t.vars.currentDatabase+"."+t.vars.currentTable+" limit "+t.vars.offset+", "+t.vars.limit+"\n ").then(function(e){var a="ch";t.tablewidget=new WidgetTable(new DataProvider(e,a)),t.vars.loading=!1},function(e){t.vars.loading=!1,console.error("Error "+e)})},t.calcRawSize=function(){t.vars.isRawStatistics=!0,n.query("SELECT any(ignore(*)) FROM "+t.vars.currentDatabase+"."+t.vars.currentTable+" SAMPLE 1 / 10000 ").then(function(e){t.vars.rawstatistics=e.statistics},function(e){t.vars.rawstatistics=e.data})},t.init=function(){t.vars.loading=!0,t.vars.createtable="N/A",n.query("SHOW CREATE TABLE "+t.vars.currentDatabase+"."+t.vars.currentTable).then(function(e){t.vars.createtable=window.sqlFormatter.format(e.data[0].statement)}),n.query("SELECT table, formatReadableSize(sum(bytes)) as size, sum(bytes) as sizeBytes, min(min_date) as minDate, max(max_date) as maxDate FROM system.parts WHERE database = '"+t.vars.currentDatabase+"' AND ( table = '"+t.vars.currentTable+"' OR table = '"+t.vars.currentTable+"_sharded' ) GROUP BY table ").then(function(e){return t.vars.statistics=e&&e.data.length&&e.data[0]||{}}),n.query("SELECT * FROM system.columns WHERE database='"+t.vars.currentDatabase+"' AND table='"+t.vars.currentTable+"'").then(function(a){n.query("describe table "+t.vars.currentDatabase+"."+t.vars.currentTable).then(function(n){_.map(n.data,function(t){var n=_.find(a.data,{name:t.name});return _.merge(t,n),t.size="-",t.ratio="-",!e.isUndefined(t.default_kind)&&e.isUndefined(t.default_type)&&(t.default_type=t.default_kind),t.data_compressed_bytes&&(t.size=numbro(t.data_compressed_bytes).format("0.0 b")+" / "+numbro(t.data_uncompressed_bytes).format("0.0 b"),t.ratio=numbro(parseInt(t.data_uncompressed_bytes)/parseInt(t.data_compressed_bytes)).format("0.0")),t}),t.vars.columns=n,t.vars.sortColumn=!1;var r=0;n.data.forEach(function(e){3>r&&("Date"==e.type&&(t.vars.sortColumn=e.name),"DateTime"==e.type&&(t.vars.sortColumn=e.name)),r+=1}),t.load()})})},t.loadNext=function(){t.vars.loading=!0,t.vars.offset+=t.vars.limit,t.load()},t.loadPrev=function(){t.vars.offset>0&&(t.vars.loading=!0,t.vars.offset-=t.vars.limit,t.load())}}e.module(t.app.name).controller("TableContainerController",a),a.$inject=["$scope","$rootScope","API","ThemeService","$stateParams","$mdSidenav","$mdComponentRegistry","hotRegisterer"]}(angular,smi2),/* * Licensed under the Apache License, Version 2.0 Copyright 2017 Igor Strykhar,Ivan Kudinov,SMI2 LLC and other contributors */ -window.global_delimiter=";;",window.aceJSRules={builtinFunctions:[],lang:"en",dictionaries:[],fieldsList:[],tables:[]},function(e,t){function a(t,a,n,r,i,s,o,c,l,d,u,m,h,p,g){var f="sqlHistory2",b="saveTabs",v="sessionData",y=255;t.AceEditorInLoad=!1,t.vars={EditorIsInit:!1,sqlHistory:r.get(f)||[],dictionaries:[],isDictionariesLoad:!1,tabs:[],enableLiveAutocompletion:h.get("liveAutocompletion"),disableAutohelp:h.get("disableAutohelp"),disableHotKeyCmdLeft:h.get("disableHotKeyCmdLeft"),saveTabs:r.get(b)||!0,LastStatistics:!1,delimiters:[{name:";; Double",delimiter:";;"},{name:"; Single",delimiter:";"}],databasesList:[],searchQueryOnServer:"",currentTab:{},selectedTab:0,formats:[{name:"Table",sql:" format JSON",render:"html"},{name:"JSON compact",sql:" format JSONCompact"}],db:null,limitTimes:h.get("limitTimes"),limitRows:h.get("limitRows"),fontSize:h.get("fontSize"),theme:h.get("editorTheme")},t.vars.delimiter=r.get("delimiter")||";;",t.vars.format=t.vars.formats[0],t.vars.themes=["ambiance","eclipse","mono_industrial","tomorrow_night_blue","chaos","github","monokai","tomorrow_night_bright","chrome","idle_fingers","pastel_on_dark","tomorrow_night_eighties","clouds","iplastic","solarized_dark","tomorrow_night","clouds_midnight","katzenmilch","solarized_light","twilight","cobalt","kr_theme","sqlserver","vibrant_ink","crimson_editor","kuroir","terminal","xcode","dawn","merbivore","textmate","dreamweaver","merbivore_soft","tomorrow"],n.onbeforeunload=function(e){if(""!==t.vars.currentTab.sql&&"localhost"!=location.hostname){var a="Do you want to leave this page?";return"undefined"==typeof e&&(e=window.event),e&&(e.returnValue=a),a}};var w=t.$on("$stateChangeStart",function(e){var a="Do you want to leave this page?";e.defaultPrevented||""===t.vars.currentTab||confirm(a)||e.preventDefault()}),k=function(){if(t.vars.saveTabs){var e=t.vars.tabs.map(function(e){return e.editor?e.sql=e.editor.getValue():e.sql="",{name:e.name,sql:e.sql,buttonTitle:e.buttonTitle,format:e.format,delimiter:e.delimiter,results:[],editor:null,selectedResultTab:0}});r.set(v,e),console.info("Save session , localStorageService.set(SQL_SESSION_KEY)")}};t.$watch("$root.isInitDatabaseStructure",function(){t.vars.EditorIsInit=a.isInitDatabaseStructure}),t.InitDatabaseStructure=function(){console.warn(">>>>>>>>>>>>>>>InitDatabaseStructure<<<<<<<",a.isInitDatabaseStructure)},t.executeQuery=function(a,n,r){var s="result_overflow_mode=throw";t.vars.currentTab.loading=!0,t.vars.limitRows&&(s+="&max_result_rows="+t.vars.limitRows),t.vars.limitTimes&&(s+="&timeout_overflow_mode=throw&max_execution_time="+t.vars.limitTimes);var o=a.sql.replace(/(\r\n|\n|\r)$/gm,"").substr(0,130);t.vars.currentTab.progress.query=o;var d="";a.qid&&(d=" /*TABIX_QUERY_ID_"+a.qid+"*/ "),i.fetchQuery(d+a.sql,!0,a.format,s).then(function(i){var s=i;e.isObject(i)||(i={data:s,meta:null,rows:null,statistics:null}),i.error=!1,i.query=a,i.countAllQuery=n.length;var c={time:moment().format("HH:mm:ss")};e.isObject(i.statistics)&&Object.assign(c,i.statistics),c.query=o,_.isArray(t.vars.currentTab.statistics)&&t.vars.currentTab.statistics.push(c),t.vars.LastStatistics=c;var l=new DataProvider(i,"ch");l.progressQuery=o,r.widgets.tables.push(new WidgetTable(l)),"drawCommand"in a&&a.drawCommand.length?(l.countAll=a.drawCommand.length>i.countAllQuery?a.drawCommand.length:i.countAllQuery,console.info("query.drawCommand",a.drawCommand),a.drawCommand.forEach(function(e){r.widgets.draw.push(new WidgetDraw(l,e))})):r.widgets.draw.push(new WidgetDraw(l,!1)),r.data.push(a),t.$applyAsync(),a.index+1-1&&i>-1&&t.vars.currentTab.editor.gotoLine(s,i),console.log("move cursor to",s,i)}var d="ch";console.warn("ERROR",n);var u=new DataProvider(n,d);r.data.push(a),r.widgets.tables.push(new WidgetTable(u)),t.finalizeResult(r)})},t.renderResult=function(t){return t.echarts=!1,t.pivot=!1,t.charts=!1,t.selectedTabIndex=0,"string"==typeof t.error?t.result='
'+t.error+"
":e.isObject(t.data)?(t.result=i.dataToHtml(t),t.createtable=i.dataToCreateTable(t),t.pivot=!0,t.charts=!0):e.isString(t.data)?t.result='
'+t.data+"
":t.result='
'+e.toJson(t.data,!0)+"
",t},t.finalizeResult=function(e){if(t.vars.currentTab.loading=!1,t.vars.currentTab.progress=!1,e.data.find(function(e){return e.keyword&&-1!=["DROP","CREATE","ALTER"].indexOf(e.keyword.toUpperCase())}),t.$applyAsync(),t.vars.currentTab.statistics[0]){var a=DataProvider.convertArrayToDataProvider(t.vars.currentTab.statistics,"statistics");a.sort="time",a.sortOrder="desc",e.widgets.stats.push(new WidgetTable(a,!1))}},t.execute=function(n,s){t.$applyAsync(),console.groupCollapsed("Execute query"),t.vars.LastStatistics=!1,s.sql=s.editor.getValue();var o=s.sql,d=0,m=s.editor,h=[],p=m.getSelectedText();e.isUndefined(s.selectedTabResultIndex)&&(s.selectedTabResultIndex=0);var f={data:[],time:u("date")(new Date,"HH:mm:ss"),pinned:!1,widgets:{tables:[],pivot:[],draw:[],stats:[]}};if(""!==p&&null!==p&&(o=p),console.info("[EDITOR TEXT]> ",o),""===o||null===o)return void c.show(c.simple().content("SQL query is empty").theme(l.theme).position("bottom right"));s.results=[f],k();var b=window.global_delimiter;b||(b=";;"),m.session.$mode.splitByTokens(o,"constant.character.escape",b).forEach(function(t){if(!("current"==n&&d>0)){var s=[],o=t.sql;if(!(o.length<5)){if("current"==n&&!p){var c=m.selection.getCursor();if(!c||e.isUndefined(c))return;var l=t.range.compare(c.row,c.column);if(0!==l)return}var u=o.trim();-1==a.sqlLog.indexOf(u)&&(a.sqlLog.unshift(u),a.sqlLog.length>y&&a.sqlLog.splice(0,y),r.set("sqlLog",a.sqlLog));var f=m.session.$mode.replaceVars(o,g.get());o=f.sql;f.vars;if(console.log("replacedVars",f),m.session.$mode.findTokens(o,"invalid.illegal",!0)){var b=m.session.$mode.splitByTokens(o,"invalid.illegal",!0);o=b[0].sql,b.forEach(function(t){if(e.isDefined(t.keyword)&&t.keyword){var a=/DRAW_(\w+)/gim,n=a.exec(t.keyword);n&&n[1]&&s.push({drawtype:n[1].toLowerCase(),code:t.sql})}})}console.info("[SQL]>",o),s&&console.info("[DRAW]>",s);var v=null,w=!1,k=!1,x=null,C=m.session.$mode.findTokens(o,"storage",!0),S=m.session.$mode.findTokens(o,"keyword",!0);C.hasOwnProperty("value")?(v=!1,k=C.value):(v=" FORMAT JSON ",w=!0),S.hasOwnProperty("value")&&(x=S.value),"select"!==x&&(v=!1,w=!1),h.push({sql:o,index:d,format:v,setedformat:w,keyword:x,storage:k,drawCommand:s,itemRange:t.range,qid:i.makeQueryId()}),d++}}}),console.groupEnd("Execute query"),h.length&&(t.vars.currentTab.progress={},t.vars.currentTab.statistics||(t.vars.currentTab.statistics=[]),t.executeQuery(h[0],h,f))},t.setTheme=function(e){t.vars.theme=e,t.vars.tabs.forEach(function(t){return t.editor.setTheme("ace/theme/"+e)}),r.set("editorTheme",e)},t.reloadCache=function(){console.log("reloadCache"),i.resetDatabaseStructure(),c.show(c.simple().content("Reload page - for reset cache").theme(l.theme).position("bottom right"))},t.selectDatabase=function(e,a){e&&(i.setDatabase(e),t.vars.db!=e&&(t.vars.db=e,t.AceEditorInLoad||(t.aceLoadDatabaseFields(),t.aceApply(!1))))},t.insertWordInEditor=function(e){var a=t.vars.currentTab.editor,n=a.getCursorPosition();n.column+=e.length,a.clearSelection(),a.insert(e),t.vars.currentTab.sql=a.getValue(),d(function(){a.focus(),a.moveCursorToPosition(n)})},t.aceLoadDatabaseFields=function(){var e=t.vars.db;window.aceJSRules.fieldsList=[],i.databaseStructure(function(t){window.aceJSRules.fieldsList=t.getAllFieldsInDatabase(e)})},t.aceLoadDatabaseStructure=function(){var e=t.vars.db;window.aceJSRules.tables=[],i.databaseStructure(function(a){t.vars.databasesList=a.getDatabases(),Object.keys(a.getUniqueDatabaseTables()).forEach(function(e){window.aceJSRules.tables.push(e)}),window.aceJSRules.fieldsList=a.getAllFieldsInDatabase(e)})},t.loadInAce=function(e){e.session.setMode({path:"ace/mode/clickhouse"});for(var t in window.aceJSRules.builtinFunctions){var a=window.aceJSRules.builtinFunctions[t];e.session.$mode.$highlightRules.addCompletionsFunctions(a)}e.session.$mode.$highlightRules.addArrayCompletions(window.aceJSRules.tables,"[table]","table");for(var n in window.aceJSRules.dictionaries){var r=window.aceJSRules.dictionaries[n];e.session.$mode.$highlightRules.addCompletionsDictionaries(r)}for(var i in window.aceJSRules.fieldsList){var s=window.aceJSRules.fieldsList[i];e.session.$mode.$highlightRules.addCompletionsTableFiled(s)}var o=g.getCompletions(),c=p.getCompletions();e.session.$mode.$highlightRules.addArrayCompletions(o,"[var]","var"),e.session.$mode.$highlightRules.addArrayCompletions(c,"[snippet]","snippet"),e.session.bgTokenizer.start(0)},t.aceApply=function(e){e?(console.log(""),t.loadInAce(e)):t.vars.tabs.forEach(function(e){e.editor&&(console.log(""),t.loadInAce(e.editor))}),a.$watch("currentDatabase",t.selectDatabase)},t.changeRootSelectDatabase=function(e){a.currentDatabase!=e&&(a.currentDatabase=e)},t.aceLoadDictionaries=function(){t.vars.isDictionariesLoad||(window.aceJSRules.dictionaries=[],t.vars.dictionaries=[],window.aceJSRules.builtinFunctions=[],t.vars.isDictionariesLoad=!0,i.databaseStructure(function(e){e.getFunctions().forEach(function(e){if(window.aceJSRules.builtinFunctions.push({name:e.name,isaggr:e.is_aggregate,score:101,comb:!1,origin:e.name}),e.is_aggregate){var t={name:e.name+"If",isaggr:e.is_aggregate,score:3,comb:"If",origin:e.name};window.aceJSRules.builtinFunctions.push(t),t={name:e.name+"Array",isaggr:e.is_aggregate,score:2,comb:"Array",origin:e.name},window.aceJSRules.builtinFunctions.push(t),t={name:e.name+"State",isaggr:e.is_aggregate,score:1,comb:"State",origin:e.name},window.aceJSRules.builtinFunctions.push(t)}}),e.getDictionaries().forEach(function(e){var a=e.name;a=a.replace(/^.*\./gm,""),"news"!=a&&(a=a.replace(/s$/gm,"")),a=a?a.toLowerCase()+"_id":"ID";var n="dictGet"+e["attribute.types"]+"('"+e.name+"','"+e["attribute.names"]+"',to"+e.key+"( "+a+" ) ) AS "+e["attribute.names"]+",";window.aceJSRules.dictionaries.push({dic:n,title:"dic_"+e.name+"."+e["attribute.names"]}),t.vars.dictionaries.push({dic:n,title:e.name+"."+e["attribute.names"]+" as "+e["attribute.types"]})})}))};for(var x=function(e){t.vars.tabs.length>=e&&(t.vars.currentTab=t.vars.tabs[e],t.vars.selectedTab=e,d(function(){t.vars.currentTab.editor.focus()}))},C=function(){t.vars.selectedTab>0&&x(t.vars.selectedTab-1)},S=function(){t.vars.selectedTabD;D++)A(D);m.add({combo:t.vars.disableHotKeyCmdLeft?"ctrl+shift+alt+right":"ctrl+right",callback:S}),m.add({combo:t.vars.disableHotKeyCmdLeft?"ctrl+shift+alt+left":"ctrl+left",callback:C}),m.add({combo:"ctrl+shift+f",callback:T}),t.aceLoaded=function(e){t.AceEditorInLoad=!0,a.currentDatabase&&t.selectDatabase(a.currentDatabase),t.aceLoadDictionaries(),t.aceLoadDatabaseStructure(),t.aceLoadDatabaseFields();var n=t.vars.tabs.find(function(e){return!e.editor})||t.vars.currentTab;n.editor=e,e.$blockScrolling=1/0,e.setOptions({fontSize:t.vars.fontSize+"px",enableBasicAutocompletion:!0,behavioursEnabled:!0,wrapBehavioursEnabled:!0,highlightSelectedWord:!0,showGutter:!0,enableLiveAutocompletion:t.vars.enableLiveAutocompletion,liveAutocompletionDelay:500,liveAutocompletionThreshold:1}),e.setTheme("ace/theme/"+t.vars.theme),e.session.setUseWrapMode(h.get("useWrapMode")),e.commands.addCommand({name:"runCurrentCommand",bindKey:{win:"Ctrl-Enter",mac:"Command-Enter"},exec:function(){t.execute("current",n)}}),e.commands.addCommand({name:"removeLiness",bindKey:{win:"Ctrl-Y",mac:"Cmd-Y"},exec:function(e){e.removeLines()}}),e.commands.addCommand({name:"collapseAll",bindKey:{win:"Ctrl-Shift--",mac:"Command+Shift+-"},exec:function(e){e.session.$mode.collapseAll(e.session)}}),e.commands.addCommand({name:"unfold",bindKey:{win:"Ctrl-Shift-+",mac:"Command+Shift+="},exec:function(e){e.session.unfold()}}),e.commands.addCommand({name:"runAllCommand",bindKey:{win:"Shift-Ctrl-Enter",mac:"Shift-Command-Enter"},exec:function(){t.execute("all",n)}});for(var r=function(t){e.commands.addCommand({name:"selecttab"+t,bindKey:{win:"Ctrl-Shift-"+(t+1),mac:"Command-Shift-"+(t+1)},exec:function(){return x(t)}})},i=0;9>i;i++)r(i);e.commands.addCommand({name:"selectnexttab",bindKey:{win:t.vars.disableHotKeyCmdLeft?"Shift-Alt-Ctrl-Right":"Ctrl-Right",mac:t.vars.disableHotKeyCmdLeft?"Shift-Alt-Command-Right":"Command-Right"},exec:S}),e.commands.addCommand({name:"selectprevtab",bindKey:{win:t.vars.disableHotKeyCmdLeft?"Shift-Alt-Ctrl-Left":"Ctrl-Left",mac:t.vars.disableHotKeyCmdLeft?"Shift-Alt-Command-Left":"Command-Left"},exec:C}),e.commands.addCommand({name:"formatcode",bindKey:{win:"Ctrl-Shift-F",mac:"Command-Shift-F"},exec:T}),e.setValue(n.sql),e.clearSelection(),e.focus(),e.selection.moveTo(0,0),e.on("changeSelection",function(){d(function(){n.buttonTitle=""!==e.getSelectedText()?"Run selected ⌘ + ⏎":"Run all ⇧ + ⌘ + ⏎",n.originalSql&&(n.changed=n.originalSql!=n.sql)})}),t.AceEditorInLoad=!1,t.aceApply(e)},t.save=function(e,a){return o.show(o.prompt().title("Save SQL as?").placeholder("Title").initialValue(e.name).targetEvent(a).ok("Save").cancel("")).then(function(a){var n=t.vars.sqlHistory.findIndex(function(t){return t.name==e.name});-1!=n?(t.vars.sqlHistory[n].sql=e.sql,t.vars.sqlHistory[n].name=a):t.vars.sqlHistory.push({sql:e.sql,name:a}),e.originalSql=e.sql,e.name=a,r.set(f,t.vars.sqlHistory),k()})},t.load=function(e){t.vars.currentTab.sql=e.sql,t.vars.currentTab.originalSql=e.sql,t.vars.currentTab.name=e.name,t.vars.currentTab.editor.setValue(e.sql),t.aceApply(t.vars.currentTab.editor)},t.getExportData=function(t){return t.data.data.map(function(t){return Object.keys(t).map(function(a){return e.isArray(t[a])?t[a].join(", "):t[a]})})},t.getExportHeaders=function(e){return e.data.meta.map(function(e){return e.name})},t.addTab=function(){t.vars.currentTab={name:"new SQL",sql:"",buttonTitle:"Run ⌘ + ⏎",format:{},editor:null,results:[],selectedResultTab:0},t.vars.tabs.push(t.vars.currentTab),k()},t.changeTab=function(e){k(),t.vars.currentTab=e},t.removeTab=function(e,a){a.stopPropagation();var n=function(){t.vars.tabs.splice(t.vars.tabs.indexOf(e),1),t.vars.tabs.length==t.vars.selectedTab&&t.vars.selectedTab--};e.changed?o.show(o.confirm().title("SQL was changed. Save it before exit?").targetEvent(a).ok("Yes").cancel("No")).then(function(){var a=t.vars.sqlHistory.findIndex(function(t){return t.name==e.name});-1!=a&&(t.vars.sqlHistory[a].sql=e.sql,t.vars.sqlHistory[a].name=e.name),r.set(f,t.vars.sqlHistory),n()},n):n()},t.removeResult=function(e,t,a){},a.$on("handleBroadcastUpdateVarsAndSnippets",function(e,a){t.aceApply()}),a.$on("handleBroadcastInsertInActive",function(e,a){a.value&&t.insertWordInEditor(" "+a.value+" ")}),t.toggleSidenav=function(e){s(e).toggle()},t.removeHistory=function(e,a){a.preventDefault();var n=t.vars.sqlHistory.indexOf(e);-1!=n&&o.show(o.confirm().title("Delete "+e.name+"?").targetEvent(a).ok("Yes").cancel("No")).then(function(){t.vars.sqlHistory.splice(n,1),r.set(f,t.vars.sqlHistory)})},t.setSql=function(e){t.vars.currentTab.sql=e,t.toggleSidenav("log"),t.vars.currentTab.editor.setValue(e),d(function(){return t.vars.currentTab.editor.focus()},500)},t.changeTabName=function(e,a){a.stopPropagation(),o.show(o.prompt().title("Title tab").placeholder("title").initialValue(e.name).targetEvent(a).ok("Apply").cancel("Cancel")).then(function(a){var n=t.vars.sqlHistory.findIndex(function(t){return t.name==e.name});-1!=n&&(e.originalSql=e.sql,t.vars.sqlHistory[n].name=a,r.set(f,t.vars.sqlHistory)),e.name=a,k()})},t.vars.saveTabs?(t.vars.tabs=r.get(v),_.isArray(t.vars.tabs)||(t.vars.tabs=[]),t.vars.tabs.length>0?d(function(){return t.vars.currentTab=t.vars.tabs[0]},500):t.addTab()):(r.set(v,[]),t.addTab()),t.$on("$destroy",function(){i.setDatabase(a.currentDatabase),w(),n.onbeforeunload=null}),t.rightAceMenuList=[],t.showDialogUpload=function(t,a){function n(e,t){e.vars={UploadCsv:{content:null,header:!0,headerVisible:!0,separator:",",separatorVisible:!0,result:null,encoding:"ISO-8859-1",encodingVisible:!0,uploadButtonLabel:"Upload",callback:function(e){t.hide()}}},e.$watch("vars.UploadCsv.result",function(e){e&&t.hide(e)}),e.hide=function(){t.hide()},e.cancel=function(){t.cancel()}}n.$inject=["$scope","$mdDialog"],o.show({controller:n,templateUrl:"app/sql/showDialogUpload.html",parent:e.element(document.body),targetEvent:a,clickOutsideToClose:!0}).then(function(e){if(e&&t&&t.tables){var a=DataProvider.convertArrayToDataProvider(e,"csv");t.tables.push(new WidgetTable(a))}},function(){})},t.rightMenuProcess=function(e){var a=t.vars.currentTab.editor.session;if(t.vars.currentTab.editor.resize(),"Snippet"==e){var n=t.vars.currentTab.editor.getSelectedText();n&&(p.add(n),t.aceApply())}else"AutoFormat"==e?T():"Expand"==e?a.unfold():"Collapse All"==e?a.$mode.collapseAll(a):"Collapse"==e&&a.foldAll();t.vars.currentTab.editor.focus()}}e.module(t.app.name).controller("SqlController",a),a.$inject=["$scope","$rootScope","$window","localStorageService","API","$mdSidenav","$mdDialog","$mdToast","ThemeService","$timeout","$filter","hotkeys","Preference","Snippets","Variables"]}(angular,smi2),/* +window.global_delimiter=";;",window.aceJSRules={builtinFunctions:[],lang:"en",dictionaries:[],fieldsList:[],tables:[]},function(e,t){function a(t,a,n,r,i,s,o,c,l,d,u,m,h,p,g){var f="sqlHistory2",b="saveTabs",v="sessionData",y=255;t.AceEditorInLoad=!1,t.vars={EditorIsInit:!1,sqlHistory:r.get(f)||[],dictionaries:[],isDictionariesLoad:!1,tabs:[],enableLiveAutocompletion:h.get("liveAutocompletion"),disableAutohelp:h.get("disableAutohelp"),disableHotKeyCmdLeft:h.get("disableHotKeyCmdLeft"),saveTabs:r.get(b)||!0,LastStatistics:!1,delimiters:[{name:";; Double",delimiter:";;"},{name:"; Single",delimiter:";"}],databasesList:[],searchQueryOnServer:"",currentTab:{},selectedTab:0,formats:[{name:"Table",sql:" format JSON",render:"html"},{name:"JSON compact",sql:" format JSONCompact"}],db:null,limitTimes:h.get("limitTimes"),limitRows:h.get("limitRows"),fontSize:h.get("fontSize"),theme:h.get("editorTheme")},t.vars.delimiter=r.get("delimiter")||";;",t.vars.format=t.vars.formats[0],t.vars.themes=["ambiance","eclipse","mono_industrial","tomorrow_night_blue","chaos","github","monokai","tomorrow_night_bright","chrome","idle_fingers","pastel_on_dark","tomorrow_night_eighties","clouds","iplastic","solarized_dark","tomorrow_night","clouds_midnight","katzenmilch","solarized_light","twilight","cobalt","kr_theme","sqlserver","vibrant_ink","crimson_editor","kuroir","terminal","xcode","dawn","merbivore","textmate","dreamweaver","merbivore_soft","tomorrow"],n.onbeforeunload=function(e){if(""!==t.vars.currentTab.sql&&"localhost"!=location.hostname){var a="Do you want to leave this page?";return"undefined"==typeof e&&(e=window.event),e&&(e.returnValue=a),a}};var w=t.$on("$stateChangeStart",function(e){var a="Do you want to leave this page?";e.defaultPrevented||""===t.vars.currentTab||confirm(a)||e.preventDefault()}),k=function(){if(t.vars.saveTabs){var e=t.vars.tabs.map(function(e){return e.editor?e.sql=e.editor.getValue():e.sql="",{name:e.name,sql:e.sql,buttonTitle:e.buttonTitle,format:e.format,delimiter:e.delimiter,results:[],editor:null,selectedResultTab:0}});r.set(v,e),console.info("Save session , localStorageService.set(SQL_SESSION_KEY)")}};t.$watch("$root.isInitDatabaseStructure",function(){t.vars.EditorIsInit=a.isInitDatabaseStructure}),t.InitDatabaseStructure=function(){console.warn(">>>>>>>>>>>>>>>InitDatabaseStructure<<<<<<<",a.isInitDatabaseStructure)},t.executeQuery=function(a,n,r){var s="result_overflow_mode=throw";t.vars.currentTab.loading=!0,t.vars.limitRows&&(s+="&max_result_rows="+t.vars.limitRows),t.vars.limitTimes&&(s+="&timeout_overflow_mode=throw&max_execution_time="+t.vars.limitTimes);var o=a.sql.replace(/(\r\n|\n|\r)$/gm,"").substr(0,130);t.vars.currentTab.progress.query=o;var d="";a.qid&&(d=" /*TABIX_QUERY_ID_"+a.qid+"*/ "),i.fetchQuery(d+a.sql,!0,a.format,s).then(function(i){var s=i;e.isObject(i)||(i={data:s,meta:null,rows:null,statistics:null}),i.error=!1,i.query=a,i.countAllQuery=n.length;var c={time:moment().format("HH:mm:ss")};e.isObject(i.statistics)&&Object.assign(c,i.statistics),c.query=o,_.isArray(t.vars.currentTab.statistics)&&t.vars.currentTab.statistics.push(c),t.vars.LastStatistics=c;var l=new DataProvider(i,"ch");l.progressQuery=o,r.widgets.tables.push(new WidgetTable(l)),"drawCommand"in a&&a.drawCommand.length?(l.countAll=a.drawCommand.length>i.countAllQuery?a.drawCommand.length:i.countAllQuery,console.info("query.drawCommand",a.drawCommand),a.drawCommand.forEach(function(e){r.widgets.draw.push(new WidgetDraw(l,e))})):r.widgets.draw.push(new WidgetDraw(l,!1)),r.data.push(a),t.$applyAsync(),a.index+1-1&&i>-1&&t.vars.currentTab.editor.gotoLine(s,i),console.log("move cursor to",s,i)}var d="ch";console.warn("ERROR",n);var u=new DataProvider(n,d);r.data.push(a),r.widgets.tables.push(new WidgetTable(u)),t.finalizeResult(r)})},t.renderResult=function(t){return t.echarts=!1,t.pivot=!1,t.charts=!1,t.selectedTabIndex=0,"string"==typeof t.error?t.result='
'+t.error+"
":e.isObject(t.data)?(t.result=i.dataToHtml(t),t.createtable=i.dataToCreateTable(t),t.pivot=!0,t.charts=!0):e.isString(t.data)?t.result='
'+t.data+"
":t.result='
'+e.toJson(t.data,!0)+"
",t},t.finalizeResult=function(e){if(t.vars.currentTab.loading=!1,t.vars.currentTab.progress=!1,e.data.find(function(e){return e.keyword&&-1!=["DROP","CREATE","ALTER"].indexOf(e.keyword.toUpperCase())}),t.$applyAsync(),t.vars.currentTab.statistics[0]){var a=DataProvider.convertArrayToDataProvider(t.vars.currentTab.statistics,"statistics");a.sort="time",a.sortOrder="desc",e.widgets.stats.push(new WidgetTable(a,!1))}},t.execute=function(n,s){t.$applyAsync(),console.groupCollapsed("Execute query"),t.vars.LastStatistics=!1,s.sql=s.editor.getValue();var o=s.sql,d=0,m=s.editor,h=[],p=m.getSelectedText();e.isUndefined(s.selectedTabResultIndex)&&(s.selectedTabResultIndex=0);var f={data:[],time:u("date")(new Date,"HH:mm:ss"),pinned:!1,widgets:{tables:[],pivot:[],draw:[],stats:[]}};if(""!==p&&null!==p&&(o=p),console.info("[EDITOR TEXT]> ",o),""===o||null===o)return void c.show(c.simple().content("SQL query is empty").theme(l.theme).position("bottom right"));s.results=[f],k();var b=window.global_delimiter;b||(b=";;"),m.session.$mode.splitByTokens(o,"constant.character.escape",b).forEach(function(t){if(!("current"==n&&d>0)){var s=[],o=t.sql;if(!(o.length<5)){if("current"==n&&!p){var c=m.selection.getCursor();if(!c||e.isUndefined(c))return;var l=t.range.compare(c.row,c.column);if(0!==l)return}var u=o.trim();-1==a.sqlLog.indexOf(u)&&(a.sqlLog.unshift(u),a.sqlLog.length>y&&a.sqlLog.splice(0,y),r.set("sqlLog",a.sqlLog));var f=m.session.$mode.replaceVars(o,g.get());o=f.sql;f.vars;if(console.log("replacedVars",f),m.session.$mode.findTokens(o,"invalid.illegal",!0)){var b=m.session.$mode.splitByTokens(o,"invalid.illegal",!0);o=b[0].sql,b.forEach(function(t){if(e.isDefined(t.keyword)&&t.keyword){var a=/DRAW_(\w+)/gim,n=a.exec(t.keyword);n&&n[1]&&s.push({drawtype:n[1].toLowerCase(),code:t.sql})}})}console.info("[SQL]>",o),s&&console.info("[DRAW]>",s);var v=null,w=!1,k=!1,x=null,C=m.session.$mode.findTokens(o,"storage",!0),S=m.session.$mode.findTokens(o,"keyword",!0);C.hasOwnProperty("value")?(v=!1,k=C.value):(v=" FORMAT JSON ",w=!0),S.hasOwnProperty("value")&&(x=S.value),"select"!=x&&"with"!=x&&(v=!1,w=!1),h.push({sql:o,index:d,format:v,setedformat:w,keyword:x,storage:k,drawCommand:s,itemRange:t.range,qid:i.makeQueryId()}),d++}}}),console.groupEnd("Execute query"),h.length&&(t.vars.currentTab.progress={},t.vars.currentTab.statistics||(t.vars.currentTab.statistics=[]),t.executeQuery(h[0],h,f))},t.setTheme=function(e){t.vars.theme=e,t.vars.tabs.forEach(function(t){return t.editor.setTheme("ace/theme/"+e)}),r.set("editorTheme",e)},t.reloadCache=function(){console.log("reloadCache"),i.resetDatabaseStructure(),c.show(c.simple().content("Reload page - for reset cache").theme(l.theme).position("bottom right"))},t.selectDatabase=function(e,a){e&&(i.setDatabase(e),t.vars.db!=e&&(t.vars.db=e,t.AceEditorInLoad||(t.aceLoadDatabaseFields(),t.aceApply(!1))))},t.insertWordInEditor=function(e){var a=t.vars.currentTab.editor,n=a.getCursorPosition();n.column+=e.length,a.clearSelection(),a.insert(e),t.vars.currentTab.sql=a.getValue(),d(function(){a.focus(),a.moveCursorToPosition(n)})},t.aceLoadDatabaseFields=function(){var e=t.vars.db;window.aceJSRules.fieldsList=[],i.databaseStructure(function(t){window.aceJSRules.fieldsList=t.getAllFieldsInDatabase(e)})},t.aceLoadDatabaseStructure=function(){var e=t.vars.db;window.aceJSRules.tables=[],i.databaseStructure(function(a){t.vars.databasesList=a.getDatabases(),Object.keys(a.getUniqueDatabaseTables()).forEach(function(e){window.aceJSRules.tables.push(e)}),window.aceJSRules.fieldsList=a.getAllFieldsInDatabase(e)})},t.loadInAce=function(e){e.session.setMode({path:"ace/mode/clickhouse"});for(var t in window.aceJSRules.builtinFunctions){var a=window.aceJSRules.builtinFunctions[t];e.session.$mode.$highlightRules.addCompletionsFunctions(a)}e.session.$mode.$highlightRules.addArrayCompletions(window.aceJSRules.tables,"[table]","table");for(var n in window.aceJSRules.dictionaries){var r=window.aceJSRules.dictionaries[n];e.session.$mode.$highlightRules.addCompletionsDictionaries(r)}for(var i in window.aceJSRules.fieldsList){var s=window.aceJSRules.fieldsList[i];e.session.$mode.$highlightRules.addCompletionsTableFiled(s)}var o=g.getCompletions(),c=p.getCompletions();e.session.$mode.$highlightRules.addArrayCompletions(o,"[var]","var"),e.session.$mode.$highlightRules.addArrayCompletions(c,"[snippet]","snippet"),e.session.bgTokenizer.start(0)},t.aceApply=function(e){e?(console.log(""),t.loadInAce(e)):t.vars.tabs.forEach(function(e){e.editor&&(console.log(""),t.loadInAce(e.editor))}),a.$watch("currentDatabase",t.selectDatabase)},t.changeRootSelectDatabase=function(e){a.currentDatabase!=e&&(a.currentDatabase=e)},t.aceLoadDictionaries=function(){t.vars.isDictionariesLoad||(window.aceJSRules.dictionaries=[],t.vars.dictionaries=[],window.aceJSRules.builtinFunctions=[],t.vars.isDictionariesLoad=!0,i.databaseStructure(function(e){e.getFunctions().forEach(function(e){if(window.aceJSRules.builtinFunctions.push({name:e.name,isaggr:e.is_aggregate,score:101,comb:!1,origin:e.name}),e.is_aggregate){var t={name:e.name+"If",isaggr:e.is_aggregate,score:3,comb:"If",origin:e.name};window.aceJSRules.builtinFunctions.push(t),t={name:e.name+"Array",isaggr:e.is_aggregate,score:2,comb:"Array",origin:e.name},window.aceJSRules.builtinFunctions.push(t),t={name:e.name+"State",isaggr:e.is_aggregate,score:1,comb:"State",origin:e.name},window.aceJSRules.builtinFunctions.push(t)}}),e.getDictionaries().forEach(function(e){var a=e.name;a=a.replace(/^.*\./gm,""),"news"!=a&&(a=a.replace(/s$/gm,"")),a=a?a.toLowerCase()+"_id":"ID";var n="dictGet"+e["attribute.types"]+"('"+e.name+"','"+e["attribute.names"]+"',to"+e.key+"( "+a+" ) ) AS "+e["attribute.names"]+",";window.aceJSRules.dictionaries.push({dic:n,title:"dic_"+e.name+"."+e["attribute.names"]}),t.vars.dictionaries.push({dic:n,title:e.name+"."+e["attribute.names"]+" as "+e["attribute.types"]})})}))};for(var x=function(e){t.vars.tabs.length>=e&&(t.vars.currentTab=t.vars.tabs[e],t.vars.selectedTab=e,d(function(){t.vars.currentTab.editor.focus()}))},C=function(){t.vars.selectedTab>0&&x(t.vars.selectedTab-1)},S=function(){t.vars.selectedTabD;D++)A(D);m.add({combo:t.vars.disableHotKeyCmdLeft?"ctrl+shift+alt+right":"ctrl+right",callback:S}),m.add({combo:t.vars.disableHotKeyCmdLeft?"ctrl+shift+alt+left":"ctrl+left",callback:C}),m.add({combo:"ctrl+shift+f",callback:T}),t.aceLoaded=function(e){t.AceEditorInLoad=!0,a.currentDatabase&&t.selectDatabase(a.currentDatabase),t.aceLoadDictionaries(),t.aceLoadDatabaseStructure(),t.aceLoadDatabaseFields();var n=t.vars.tabs.find(function(e){return!e.editor})||t.vars.currentTab;n.editor=e,e.$blockScrolling=1/0,e.setOptions({fontSize:t.vars.fontSize+"px",enableBasicAutocompletion:!0,behavioursEnabled:!0,wrapBehavioursEnabled:!0,highlightSelectedWord:!0,showGutter:!0,enableLiveAutocompletion:t.vars.enableLiveAutocompletion,liveAutocompletionDelay:500,liveAutocompletionThreshold:1}),e.setTheme("ace/theme/"+t.vars.theme),e.session.setUseWrapMode(h.get("useWrapMode")),e.commands.addCommand({name:"runCurrentCommand",bindKey:{win:"Ctrl-Enter",mac:"Command-Enter"},exec:function(){t.execute("current",n)}}),e.commands.addCommand({name:"removeLiness",bindKey:{win:"Ctrl-Y",mac:"Cmd-Y"},exec:function(e){e.removeLines()}}),e.commands.addCommand({name:"collapseAll",bindKey:{win:"Ctrl-Shift--",mac:"Command+Shift+-"},exec:function(e){e.session.$mode.collapseAll(e.session)}}),e.commands.addCommand({name:"unfold",bindKey:{win:"Ctrl-Shift-+",mac:"Command+Shift+="},exec:function(e){e.session.unfold()}}),e.commands.addCommand({name:"runAllCommand",bindKey:{win:"Shift-Ctrl-Enter",mac:"Shift-Command-Enter"},exec:function(){t.execute("all",n)}});for(var r=function(t){e.commands.addCommand({name:"selecttab"+t,bindKey:{win:"Ctrl-Shift-"+(t+1),mac:"Command-Shift-"+(t+1)},exec:function(){return x(t)}})},i=0;9>i;i++)r(i);e.commands.addCommand({name:"selectnexttab",bindKey:{win:t.vars.disableHotKeyCmdLeft?"Shift-Alt-Ctrl-Right":"Ctrl-Right",mac:t.vars.disableHotKeyCmdLeft?"Shift-Alt-Command-Right":"Command-Right"},exec:S}),e.commands.addCommand({name:"selectprevtab",bindKey:{win:t.vars.disableHotKeyCmdLeft?"Shift-Alt-Ctrl-Left":"Ctrl-Left",mac:t.vars.disableHotKeyCmdLeft?"Shift-Alt-Command-Left":"Command-Left"},exec:C}),e.commands.addCommand({name:"formatcode",bindKey:{win:"Ctrl-Shift-F",mac:"Command-Shift-F"},exec:T}),e.setValue(n.sql),e.clearSelection(),e.focus(),e.selection.moveTo(0,0),e.on("changeSelection",function(){d(function(){n.buttonTitle=""!==e.getSelectedText()?"Run selected ⌘ + ⏎":"Run all ⇧ + ⌘ + ⏎",n.originalSql&&(n.changed=n.originalSql!=n.sql)})}),t.AceEditorInLoad=!1,t.aceApply(e)},t.save=function(e,a){return o.show(o.prompt().title("Save SQL as?").placeholder("Title").initialValue(e.name).targetEvent(a).ok("Save").cancel("")).then(function(a){var n=t.vars.sqlHistory.findIndex(function(t){return t.name==e.name});-1!=n?(t.vars.sqlHistory[n].sql=e.sql,t.vars.sqlHistory[n].name=a):t.vars.sqlHistory.push({sql:e.sql,name:a}),e.originalSql=e.sql,e.name=a,r.set(f,t.vars.sqlHistory),k()})},t.load=function(e){t.vars.currentTab.sql=e.sql,t.vars.currentTab.originalSql=e.sql,t.vars.currentTab.name=e.name,t.vars.currentTab.editor.setValue(e.sql),t.aceApply(t.vars.currentTab.editor)},t.getExportData=function(t){return t.data.data.map(function(t){return Object.keys(t).map(function(a){return e.isArray(t[a])?t[a].join(", "):t[a]})})},t.getExportHeaders=function(e){return e.data.meta.map(function(e){return e.name})},t.addTab=function(){t.vars.currentTab={name:"new SQL",sql:"",buttonTitle:"Run ⌘ + ⏎",format:{},editor:null,results:[],selectedResultTab:0},t.vars.tabs.push(t.vars.currentTab),k()},t.changeTab=function(e){k(),t.vars.currentTab=e},t.removeTab=function(e,a){a.stopPropagation();var n=function(){t.vars.tabs.splice(t.vars.tabs.indexOf(e),1),t.vars.tabs.length==t.vars.selectedTab&&t.vars.selectedTab--};e.changed?o.show(o.confirm().title("SQL was changed. Save it before exit?").targetEvent(a).ok("Yes").cancel("No")).then(function(){var a=t.vars.sqlHistory.findIndex(function(t){return t.name==e.name});-1!=a&&(t.vars.sqlHistory[a].sql=e.sql,t.vars.sqlHistory[a].name=e.name),r.set(f,t.vars.sqlHistory),n()},n):n()},t.removeResult=function(e,t,a){},a.$on("handleBroadcastUpdateVarsAndSnippets",function(e,a){t.aceApply()}),a.$on("handleBroadcastInsertInActive",function(e,a){a.value&&t.insertWordInEditor(" "+a.value+" ")}),t.toggleSidenav=function(e){s(e).toggle()},t.removeHistory=function(e,a){a.preventDefault();var n=t.vars.sqlHistory.indexOf(e);-1!=n&&o.show(o.confirm().title("Delete "+e.name+"?").targetEvent(a).ok("Yes").cancel("No")).then(function(){t.vars.sqlHistory.splice(n,1),r.set(f,t.vars.sqlHistory)})},t.setSql=function(e){t.vars.currentTab.sql=e,t.toggleSidenav("log"),t.vars.currentTab.editor.setValue(e),d(function(){return t.vars.currentTab.editor.focus()},500)},t.changeTabName=function(e,a){a.stopPropagation(),o.show(o.prompt().title("Title tab").placeholder("title").initialValue(e.name).targetEvent(a).ok("Apply").cancel("Cancel")).then(function(a){var n=t.vars.sqlHistory.findIndex(function(t){return t.name==e.name});-1!=n&&(e.originalSql=e.sql,t.vars.sqlHistory[n].name=a,r.set(f,t.vars.sqlHistory)),e.name=a,k()})},t.vars.saveTabs?(t.vars.tabs=r.get(v),_.isArray(t.vars.tabs)||(t.vars.tabs=[]),t.vars.tabs.length>0?d(function(){return t.vars.currentTab=t.vars.tabs[0]},500):t.addTab()):(r.set(v,[]),t.addTab()),t.$on("$destroy",function(){i.setDatabase(a.currentDatabase),w(),n.onbeforeunload=null}),t.rightAceMenuList=[],t.showDialogUpload=function(t,a){function n(e,t){e.vars={UploadCsv:{content:null,header:!0,headerVisible:!0,separator:",",separatorVisible:!0,result:null,encoding:"ISO-8859-1",encodingVisible:!0,uploadButtonLabel:"Upload",callback:function(e){t.hide()}}},e.$watch("vars.UploadCsv.result",function(e){e&&t.hide(e)}),e.hide=function(){t.hide()},e.cancel=function(){t.cancel()}}n.$inject=["$scope","$mdDialog"],o.show({controller:n,templateUrl:"app/sql/showDialogUpload.html",parent:e.element(document.body),targetEvent:a,clickOutsideToClose:!0}).then(function(e){if(e&&t&&t.tables){var a=DataProvider.convertArrayToDataProvider(e,"csv");t.tables.push(new WidgetTable(a))}},function(){})},t.rightMenuProcess=function(e){t.vars.currentTab.sql=t.vars.currentTab.editor.getValue();var a=t.vars.currentTab.editor.session;if(t.vars.currentTab.editor.resize(),"Snippet"==e){var n=t.vars.currentTab.editor.getSelectedText();n&&(p.add(n),t.aceApply())}else"AutoFormat"==e?T():"Expand"==e?a.unfold():"Collapse All"==e?a.$mode.collapseAll(a):"Collapse"==e&&a.foldAll();t.vars.currentTab.editor.focus()}}e.module(t.app.name).controller("SqlController",a),a.$inject=["$scope","$rootScope","$window","localStorageService","API","$mdSidenav","$mdDialog","$mdToast","ThemeService","$timeout","$filter","hotkeys","Preference","Snippets","Variables"]}(angular,smi2),/* * Licensed under the Apache License, Version 2.0 Copyright 2017 Igor Strykhar,SMI2 LLC and other contributors */ function(e,t,a){function n(t,a,n,r,i,s,o,c,l,d){function u(e,t){e.editor=!1,e.hide=function(){t.hide()},e.cancel=function(){t.cancel()},e.applyCode=function(){console.log("applyCODE")},e.aceLoadedEditor=function(t){e.editor=t,console.warn("aceLoadedEditor"),t.$blockScrolling=1/0,t.session.setUseWrapMode(!0),t.setOptions({fontSize:"14px",enableBasicAutocompletion:!0,behavioursEnabled:!0,wrapBehavioursEnabled:!0,highlightSelectedWord:!0,showGutter:!0,enableLiveAutocompletion:!0,liveAutocompletionDelay:500,liveAutocompletionThreshold:1}),t.commands.addCommand({name:"runCurrentCommand",bindKey:{win:"Ctrl-Enter",mac:"Command-Enter"},exec:function(){e.applyCode()}}),t.setTheme("ace/theme/cobalt"),t.setValue("{}"),t.clearSelection(),t.focus(),t.selection.moveTo(0,0),t.session.setMode({path:"ace/mode/javascript"})}}u.$inject=["$scope","$mdDialog"],t.tabsRender=!0,t.vars={rsw:0,uiTheme:l.themeObject,isChartReady:!1,staticGrid:!0,stackType:"false",isDark:l.isDark(),active:{table:!1,pivot:!1,draw:!1}},t.staticGrid=!0,t.gridStackOptions={cellHeight:200,verticalMargin:3,disableDrag:!0},t.switchStaticGrid=function(){t.vars.staticGrid=!t.vars.staticGrid,t.staticGrid=t.vars.staticGrid,console.info("staticGrid",t.staticGrid)},t.initNoTabs=function(){t.vars.active.table=!0,t.vars.active.draw=!0,t.vars.active.pivot=!0},t.initTableTab=function(){console.warn("initTableTab!!!!"),t.vars.active.table=!0},t.initDrawTab=function(){t.vars.active.draw=!0},t.onResizeStop=function(){},t.openEditor=function(a){o.show({controller:u,templateUrl:"app/sql/PlotlyEditor.tmpl.html",parent:e.element(document.body),locals:{w:a}}).then(function(e){t.status='You said the information was "'+e+'".'},function(){t.status="You cancelled the dialog."})},t.openEditorPlotLy=function(e){console.log("openEditorPlotLy",e),t.openEditor(e)},t.initPivotTab=function(){t.vars.active.pivot=!0}}e.module(t.app.name).controller("RenderCtrl",n),n.$inject=["$scope","$rootScope","$window","localStorageService","API","$mdSidenav","$mdDialog","$mdToast","ThemeService","$timeout"]}(angular,smi2,window.$),/* @@ -606,7 +606,7 @@ function(e,t){function a(e){var t=this;this.snippets={},this.constructor=functio function(e,t){function a(e,t){var a=this,n={limitRows:5e3,limitTimes:5,fontSize:14,editorTheme:"cobalt",theme:"dark",saveTabs:!0,liveAutocompletion:!0,disableAutohelp:!1,disableHotKeyCmdLeft:!0,delimiter:";;",liveAutocompletionDelay:500,liveAutocompletionThreshold:1,useWrapMode:!0,showInvisibles:!1},r=["ligth","dark"],i=["ambiance","eclipse","mono_industrial","tomorrow_night_blue","chaos","github","monokai","tomorrow_night_bright","chrome","idle_fingers","pastel_on_dark","tomorrow_night_eighties","clouds","iplastic","solarized_dark","tomorrow_night","clouds_midnight","katzenmilch","solarized_light","twilight","cobalt","kr_theme","sqlserver","vibrant_ink","crimson_editor","kuroir","terminal","xcode","dawn","merbivore","textmate","dreamweaver","merbivore_soft","tomorrow","dracula"];this.current={},this.constructor=function(){var t=e.get("UserPreference");a.current=_.merge(n,t)},this.constructor(),this.getThemes=function(){return r},this.getEditorThemes=function(){return i},this.apply=function(e){_.forEach(e,function(e,t){a.set(t,e)}),a.save()},this.save=function(){console.log("localStorageService,set",a.current),e.set("UserPreference",a.current)},this.getCurrentState=function(){return a.current},this.get=function(e){return n[e]},this.set=function(e,t){("limitRows"==e||"limitTimes"==e||"fontSize"==e||"liveAutocompletionDelay"==e||"liveAutocompletionThreshold"==e)&&(t=parseInt(t)),a.current[e]=t}}e.module(t.app.name).service("Preference",a),a.$inject=["localStorageService","ThemeService"]}(angular,smi2),function(e,t){function a(e,t){return{responseError:function(a){return 401==a.status&&t.get("$state").go("login"),e.reject(a)}}}e.module(t.app.name).service("HttpInterceptor",a),a.$inject=["$q","$injector"]}(angular,smi2),/* * Licensed under the Apache License, Version 2.0 Copyright 2017 Igor Strykhar,Ivan Kudinov,SMI2 LLC and other contributors */ -function(e,t){function a(t,a,n,r,i){var s=this,o="currentBaseConfig",c=new DatabaseStructure,l=null,d={},u=n.get(o);u&&u.host&&(d=u),this.setConnection=function(t){n.set(o,t),d=e.copy(t)},this.clear=function(){l=null,d={},n.set(o,{}),c=new DatabaseStructure},this.hashCode=function(e){return e.split("").reduce(function(e,t){return e=(e<<5)-e+t.charCodeAt(0),e&e},0)},this.DS_CacheKey=function(){var e="_databaseStructure:"+JSON.stringify(d);return e=s.hashCode(e)},this.DS_storeCache=function(e,t,a,r,i){var o={columns:e,tables:t,databases:a,dictionaries:r,functions:i,ttl:Date.now()};return n.set(s.DS_CacheKey(),o)},this.DS_fetchFromCache=function(){var e=n.get(s.DS_CacheKey());if(!e||!e.ttl)return!1;var t=(Date.now()-e.ttl)/36e5;return t>1.5?!1:e&&e.functions&&e.functions.length>1?(c.init(e.columns,e.tables,e.databases,e.dictionaries,e.functions),!0):!1},this.memory=function(e){},this.resetDatabaseStructure=function(){console.log("reset databaseStructure"),n.set("_databaseStructure:"+s.getHost()+":"+s.getLogin(),[])},this.databaseStructure=function(e,t){return!t&&c.isInit()?e(c):!t&&s.DS_fetchFromCache()&&c.isInit()?(console.info("restore from cache : database Structure!"),e(c)):(t&&(c=new DatabaseStructure),console.time("Load Database Structure!"),void s.fetchQuery("SELECT * FROM system.columns").then(function(t){s.fetchQuery("SELECT database,name,engine FROM system.tables").then(function(a){s.fetchQuery("SELECT name FROM system.databases").then(function(n){s.fetchQuery("SELECT name,key,attribute.names,attribute.types from system.dictionaries ARRAY JOIN attribute ORDER BY name,attribute.names",null).then(function(r){s.fetchQuery("SELECT name,is_aggregate from system.functions",null).then(function(i){return console.timeEnd("Load Database Structure!"),s.DS_storeCache(t.data,a.data,n.data,r.data,i.data),c.init(t.data,a.data,n.data,r.data,i.data),e(c)},function(e){throw e})},function(e){throw e})},function(e){throw e})},function(e){throw e})},function(e){throw e}))},this.getHost=function(){return d.host},this.getPassword=function(){return d.password},this.getLogin=function(){return d.login},this.makeQueryId=function(){for(var e="",t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",a=0;8>a;a++)e+=t.charAt(Math.floor(Math.random()*t.length));return e},this.isTabixServer=function(){return d.tabix&&d.tabix.server?!0:!1},this.tabixQuery=function(e){return console.info("[request]>",e),t(req).then(function(e){return defer.resolve(e.data)},function(e){return defer.reject(e)}),defer.promise},this._tabixRequest=function(t,a){var n={version:1,auth:{login:d.tabix.login,password:d.tabix.password,confid:d.tabix.confid}};t=Object.assign(n,t);var r=d.tabix.server+"/"+a;return{method:"POST",data:t,url:r,transformResponse:function(t,a,n){try{return JSON.parse(t)}catch(r){return t?t:"\nStatus:"+n+"\nHeaders:"+e.toJson(a())}}}},this.makeSqlQuery=function(e,t){var a="";return t!==!1?(t=t||" FoRmAt JSON","null"==t&&(t=""),a=e+"\n\n"+t):a=e,a},this.makeUrlRequest=function(e,t){var a="",n="";d.host.indexOf("://")>0||0==d.host.indexOf("/")||(n="http://"),a=n+d.host,a+="/?",d.rouser||(a+="add_http_cors_header=1&log_queries=1&output_format_json_quote_64bit_integers=1",d.NotCH1_1_54276||(a+="&output_format_json_quote_denormals=1"));return d.baseauth||(a+=d.password?"&user="+encodeURIComponent(d.login)+"&password="+encodeURIComponent(d.password):"&user="+encodeURIComponent(d.login)),e&&(a+="&database="+encodeURIComponent(l)),t&&(a+="&"+t),d.params&&(a+="&"+d.params),a},this.fetchQuery=function(e,t,a,n){var r=s.makeSqlQuery(e,a),i=s.makeUrlRequest(t,n),o={mode:"cors",method:"post",headers:{"Content-type":"application/x-www-form-urlencoded; charset=UTF-8"},body:r},c=new Request(i,o);return fetch(c).then(function(e){var t=e.headers.get("content-type");return t.includes("text/plain")&&200==e.status&&"ok"==e.statusText.toLowerCase()?"OK":t&&t.includes("application/json")&&e.status>=200&&e.status<300?Promise.resolve(e):e.text().then(Promise.reject.bind(Promise))}).then(function(e){return"OK"===e?"OK":e.json()},function(e){return Promise.reject(e)})},this.query=function(e,n,r,i){var o=a.defer(),c=s.makeSqlQuery(e,n),l=s.makeUrlRequest(r,i),u=!1;return s.isTabixServer()?u=s._tabixRequest({query:c},"query"):(u={method:"POST",data:c,headers:{"Content-Type":"application/x-www-form-urlencoded"},url:l,cache:!1},d.baseauth&&(u.headers.Authorization="Basic "+window.btoa(d.login+":"+d.password))),console.info("SQL>",l,c,u),t(u).then(function(e){return o.resolve(e.data)},function(e){return o.reject(e)}),o.promise},this.getConnectionInfo=function(){return d},this.setDatabase=function(e){return l=e},this.getDatabase=function(){return l},this.dataToCreateTable=function(e){var t="\nCREATE TABLE x (\n",a=[];return e.meta.forEach(function(e){return a.push(" "+e.name+" "+e.type)}),t+a.join(",\n")+"\n ) ENGINE = Log \n;;\n"},this.dataToHtml=function(e){var t='',a=[];return e.meta.forEach(function(e){t+="",a.push(e.name)}),e.data.forEach(function(e){t+="",a.forEach(function(a){t+=""}),t+=""}),t+="
"+r(e.name)+'\n
'+r(e.type)+"
\n
"+r(e[a])+"
"},this.dataToHandsontable=function(e){var t=[],a=[];return e.meta.forEach(function(e){t.push(e.name);var n={};switch(n.type="text",n.width=100,e.type){case"Date":n.width=90,n.type="date",n.dateFormat="MM/DD/YYYY";break;case"DateTime":n.width=150,n.type="time",n.timeFormat="HH:mm:ss";break;case"Int32":n.width=80,n.type="numeric";break;case"Float64":n.width=80,n.type="numeric",n.format="0,0.0000";break;case"UInt32":n.width=80,n.type="numeric";break;case"String":n.width=180}n.data=e.name,a.push(n)}),{colHeaders:t,columns:a,data:e.data,currentRowClassName:"currentRow",currentColClassName:"currentCol"}}}e.module(t.app.name).service("API",a),a.$inject=["$http","$q","localStorageService","$sanitize","ThemeService"]}(angular,smi2);var DatabaseStructure=function(){function e(){_classCallCheck(this,e),this._init=!1,this.uciq_fields=[],this.all_fields=[],this.all_db_fields=[],this.uciq_dbtables=[]}return _createClass(e,[{key:"init",value:function(e,t,a,n,r){var i=this;console.log("Try init DS...."),this._init||(this.columns=e,this.tables=t,this.databases=a,this.functions=r,this.dictionaries=n,this.columns.forEach(function(e){!angular.isUndefined(e.default_kind)&&angular.isUndefined(e.default_type)&&(e.default_type=e.default_kind),i.all_fields[e.database+"."+e.table]||(i.all_fields[e.database+"."+e.table]=[]),i.all_db_fields[e.database]||(i.all_db_fields[e.database]=[]),i.all_db_fields[e.database][e.table]||(i.all_db_fields[e.database][e.table]=[]),i.all_db_fields[e.database][e.table].push(e),i.all_fields[e.database+"."+e.table].push({name:e.name,type:e.type,active:!0}),i.uciq_fields[e.database]||(i.uciq_fields[e.database]=[]),i.uciq_fields[e.database].push(e),i.uciq_dbtables[e.database+"."+e.table]=1}),this._init=!0)}},{key:"isInit",value:function(){return this._init&&this.functions&&this.functions.length>1}},{key:"getTables",value:function(){return this.tables}},{key:"getDatabases",value:function(){return this.databases}},{key:"getFieldsByDatabase",value:function(e){return this.all_db_fields[e]}},{key:"getFunctions",value:function(){return this.functions}},{key:"getFields",value:function(){return this.all_fields}},{key:"getUniqueDatabaseTables",value:function(){return this.uciq_dbtables}},{key:"getAllFieldsInDatabase",value:function(e){return this.uciq_fields[e]}},{key:"getDictionaries",value:function(){return this.dictionaries}},{key:"getColumns",value:function(){return this.columns}}]),e}();/* +function(e,t){function a(t,a,n,r,i){var s=this,o="currentBaseConfig",c=new DatabaseStructure,l=null,d={},u=n.get(o);u&&u.host&&(d=u),this.setConnection=function(t){n.set(o,t),d=e.copy(t)},this.clear=function(){l=null,d={},n.set(o,{}),c=new DatabaseStructure},this.hashCode=function(e){return e.split("").reduce(function(e,t){return e=(e<<5)-e+t.charCodeAt(0),e&e},0)},this.DS_CacheKey=function(){var e="_databaseStructure:"+JSON.stringify(d);return e=s.hashCode(e)},this.DS_storeCache=function(e,t,a,r,i){var o={columns:e,tables:t,databases:a,dictionaries:r,functions:i,ttl:Date.now()};return n.set(s.DS_CacheKey(),o)},this.DS_fetchFromCache=function(){var e=n.get(s.DS_CacheKey());if(!e||!e.ttl)return!1;var t=(Date.now()-e.ttl)/36e5;return t>1.5?!1:e&&e.functions&&e.functions.length>1?(c.init(e.columns,e.tables,e.databases,e.dictionaries,e.functions),!0):!1},this.memory=function(e){},this.resetDatabaseStructure=function(){console.log("reset databaseStructure"),n.set("_databaseStructure:"+s.getHost()+":"+s.getLogin(),[])},this.databaseStructure=function(e,t){return!t&&c.isInit()?e(c):!t&&s.DS_fetchFromCache()&&c.isInit()?(console.info("restore from cache : database Structure!"),e(c)):(t&&(c=new DatabaseStructure),console.time("Load Database Structure!"),void s.fetchQuery("SELECT * FROM system.columns").then(function(t){s.fetchQuery("SELECT database,name,engine FROM system.tables").then(function(a){s.fetchQuery("SELECT name FROM system.databases").then(function(n){s.fetchQuery("SELECT name,key,attribute.names,attribute.types from system.dictionaries ARRAY JOIN attribute ORDER BY name,attribute.names",null).then(function(r){s.fetchQuery("SELECT name,is_aggregate from system.functions",null).then(function(i){return console.timeEnd("Load Database Structure!"),s.DS_storeCache(t.data,a.data,n.data,r.data,i.data),c.init(t.data,a.data,n.data,r.data,i.data),e(c)},function(e){throw e})},function(e){throw e})},function(e){throw e})},function(e){throw e})},function(e){throw e}))},this.getHost=function(){return d.host},this.getPassword=function(){return d.password},this.getLogin=function(){return d.login},this.makeQueryId=function(){for(var e="",t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",a=0;8>a;a++)e+=t.charAt(Math.floor(Math.random()*t.length));return e},this.isTabixServer=function(){return d.tabix&&d.tabix.server?!0:!1},this.tabixQuery=function(e){return console.info("[request]>",e),t(req).then(function(e){return defer.resolve(e.data)},function(e){return defer.reject(e)}),defer.promise},this._tabixRequest=function(t,a){var n={version:1,auth:{login:d.tabix.login,password:d.tabix.password,confid:d.tabix.confid}};t=Object.assign(n,t);var r=d.tabix.server+"/"+a;return{method:"POST",data:t,url:r,transformResponse:function(t,a,n){try{return JSON.parse(t)}catch(r){return t?t:"\nStatus:"+n+"\nHeaders:"+e.toJson(a())}}}},this.makeSqlQuery=function(e,t){var a="";return t!==!1?(t=t||" FoRmAt JSON","null"==t&&(t=""),a=e+"\n\n"+t):a=e,a},this.makeUrlRequest=function(e,t){var a="",n="";d.host.indexOf("://")>0||0==d.host.indexOf("/")||(n="http://"),a=n+d.host,a+="/?",a+="add_http_cors_header=1&log_queries=1&output_format_json_quote_64bit_integers=1",d.NotCH1_1_54276||(a+="&output_format_json_quote_denormals=1");return d.baseauth||(a+=d.password?"&user="+encodeURIComponent(d.login)+"&password="+encodeURIComponent(d.password):"&user="+encodeURIComponent(d.login)),e&&(a+="&database="+encodeURIComponent(l)),t&&(a+="&"+t),d.params&&(a+="&"+d.params),a},this.fetchQuery=function(e,t,a,n){var r=s.makeSqlQuery(e,a),i=s.makeUrlRequest(t,n),o={mode:"cors",method:"post",headers:{"Content-type":"application/x-www-form-urlencoded; charset=UTF-8"},body:r},c=new Request(i,o);return fetch(c).then(function(e){var t=e.headers.get("content-type");return t.includes("text/plain")&&200==e.status&&"ok"==e.statusText.toLowerCase()?"OK":t&&t.includes("application/json")&&e.status>=200&&e.status<300?Promise.resolve(e):e.text().then(Promise.reject.bind(Promise))}).then(function(e){return"OK"===e?"OK":e.json()},function(e){return Promise.reject(e)})},this.query=function(e,n,r,i){var o=a.defer(),c=s.makeSqlQuery(e,n),l=s.makeUrlRequest(r,i),u=!1;return s.isTabixServer()?u=s._tabixRequest({query:c},"query"):(u={method:"POST",data:c,headers:{"Content-Type":"application/x-www-form-urlencoded"},url:l,cache:!1},d.baseauth&&(u.headers.Authorization="Basic "+window.btoa(d.login+":"+d.password))),console.info("SQL>",l,c,u),t(u).then(function(e){return o.resolve(e.data)},function(e){return o.reject(e)}),o.promise},this.getConnectionInfo=function(){return d},this.setDatabase=function(e){return l=e},this.getDatabase=function(){return l},this.dataToCreateTable=function(e){var t="\nCREATE TABLE x (\n",a=[];return e.meta.forEach(function(e){return a.push(" "+e.name+" "+e.type)}),t+a.join(",\n")+"\n ) ENGINE = Log \n;;\n"},this.dataToHtml=function(e){var t='',a=[];return e.meta.forEach(function(e){t+="",a.push(e.name)}),e.data.forEach(function(e){t+="",a.forEach(function(a){t+=""}),t+=""}),t+="
"+r(e.name)+'\n
'+r(e.type)+"
\n
"+r(e[a])+"
"},this.dataToHandsontable=function(e){var t=[],a=[];return e.meta.forEach(function(e){t.push(e.name);var n={};switch(n.type="text",n.width=100,e.type){case"Date":n.width=90,n.type="date",n.dateFormat="MM/DD/YYYY";break;case"DateTime":n.width=150,n.type="time",n.timeFormat="HH:mm:ss";break;case"Int32":n.width=80,n.type="numeric";break;case"Float64":n.width=80,n.type="numeric",n.format="0,0.0000";break;case"UInt32":n.width=80,n.type="numeric";break;case"String":n.width=180}n.data=e.name,a.push(n)}),{colHeaders:t,columns:a,data:e.data,currentRowClassName:"currentRow",currentColClassName:"currentCol"}}}e.module(t.app.name).service("API",a),a.$inject=["$http","$q","localStorageService","$sanitize","ThemeService"]}(angular,smi2);var DatabaseStructure=function(){function e(){_classCallCheck(this,e),this._init=!1,this.uciq_fields=[],this.all_fields=[],this.all_db_fields=[],this.uciq_dbtables=[]}return _createClass(e,[{key:"init",value:function(e,t,a,n,r){var i=this;console.log("Try init DS...."),this._init||(this.columns=e,this.tables=t,this.databases=a,this.functions=r,this.dictionaries=n,this.columns.forEach(function(e){!angular.isUndefined(e.default_kind)&&angular.isUndefined(e.default_type)&&(e.default_type=e.default_kind),i.all_fields[e.database+"."+e.table]||(i.all_fields[e.database+"."+e.table]=[]),i.all_db_fields[e.database]||(i.all_db_fields[e.database]=[]),i.all_db_fields[e.database][e.table]||(i.all_db_fields[e.database][e.table]=[]),i.all_db_fields[e.database][e.table].push(e),i.all_fields[e.database+"."+e.table].push({name:e.name,type:e.type,active:!0}),i.uciq_fields[e.database]||(i.uciq_fields[e.database]=[]),i.uciq_fields[e.database].push(e),i.uciq_dbtables[e.database+"."+e.table]=1}),this._init=!0)}},{key:"isInit",value:function(){return this._init&&this.functions&&this.functions.length>1}},{key:"getTables",value:function(){return this.tables}},{key:"getDatabases",value:function(){return this.databases}},{key:"getFieldsByDatabase",value:function(e){return this.all_db_fields[e]}},{key:"getFunctions",value:function(){return this.functions}},{key:"getFields",value:function(){return this.all_fields}},{key:"getUniqueDatabaseTables",value:function(){return this.uciq_dbtables}},{key:"getAllFieldsInDatabase",value:function(e){return this.uciq_fields[e]}},{key:"getDictionaries",value:function(){return this.dictionaries}},{key:"getColumns",value:function(){return this.columns}}]),e}();/* * Copyright (C) 2017 IgorStrykhar in SMI2 * All rights reserved. */ @@ -626,8 +626,8 @@ var WidgetPivot=function(e){function t(e,a){_classCallCheck(this,t);var n=_possi var WidgetDraw=function(e){function t(e,a,n,r){_classCallCheck(this,t);var i=_possibleConstructorReturn(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e,a,n,r));return i.type="draw",i.error||i.text?_possibleConstructorReturn(i):(i.library=!1,i._list={PLOTLY:DrawPlotly,HEATMAP:DrawEchartsHeatmap,CALENDAR:DrawEchartsCalendar,RAW:DrawEchartsMap,BAR:DrawEchartsBar,RIVER:DrawEchartsRiver,MAP:DrawEchartsMap,GMAPS:DrawGoogleMap,TREEMAP:DrawEchartsTreemap,SANKEYS:DrawEchartsSunkeys,CHART:DrawEchartsChart,GRIDCHART:DrawEchartsGridChart,TEXT:DrawText,D3:DrawD3,C3:DrawC3},i.init=i.getChartClass(),i.sizeX||i.sizeY||(i.sizeX=6,i.sizeY=3,"TEXT"==i.drawType&&(i.sizeX=1,i.sizeY=2),console.info("this.data.countAll",i.data.countAll),1==i.data.countAll&&(i.sizeX=12,i.sizeY=3)),i)}return t.$inject=["DataProvider","draw","sizeX","sizeY"],_inherits(t,e),_createClass(t,[{key:"onResize",value:function(){this._draw&&this._draw.onResize()}},{key:"getChartClass",value:function(){return this.drawType||(this.drawType="CHART",console.error("Un support DrawType:null")),this._list[this.drawType]?!0:(console.error("Un support DrawType:"+this.drawType),!1)}},{key:"draw",get:function(){return this.drawType&&!this._draw&&(this._draw=new this._list[this.drawType](this,this.drawType)),this._draw}}]),t}(Widget);angular.module(smi2.app.name).service("WidgetDraw",WidgetDraw);/* * Licensed under the Apache License, Version 2.0 Copyright 2017 Igor Strykhar,SMI2 LLC and other contributors */ -var HandsTable=function(){function e(t,a,n){_classCallCheck(this,e),this.isDarkTheme=t,this.meta=a,this.Preset=n}return e.$inject=["isDark","metaData","Preset"],_createClass(e,[{key:"_handsRenderer",value:function(e,t,a,n,r,i,s){"numeric"==s.type?null==i||"-nan"==i||"inf"==i||"+nan"==i||"+inf"==i||"-inf"==i||"nan"==i?(null==i&&(arguments[5]="NULL"),t.style.color="black",t.style.background="red",Handsontable.renderers.TextRenderer.apply(this,arguments)):Handsontable.renderers.NumericRenderer.apply(this,arguments):"date"==s.type||"time"==s.type?(moment(new Date(i)).isValid()&&s.renderDateFormat&&(i=moment(i).format(s.renderDateFormat)),arguments[5]=i,Handsontable.renderers.TextRenderer.apply(this,arguments)):Handsontable.renderers.TextRenderer.apply(this,arguments),s.backgroundColor&&(t.style.backgroundColor=s.backgroundColor),s.color&&(t.style.color=s.color)}},{key:"countColumns",value:function(){return this.meta.length}},{key:"makeColumns",value:function(){var e=this,t=[],a=[],n={},r=0;return this.meta.forEach(function(i){n[i.name]=r,r++,t.push(i.name);var s={};switch(s.type="text",s.width=100,s.typeOriginal=i.type,s.isDark=e.isDarkTheme,i.type.includes("Int64")?(s.type="text",s.width=100):i.type.includes("Int")&&(s.width=80,s.type="numeric"),i.type){case"Date":s.width=90,s.type="date",s.dateFormat="YYYY-MM-DD";break;case"DateTime":s.width=150,s.type="time",s.timeFormat="YYYY-MM-DD HH:mm:ss";break;case"Float32":s.width=80,s.type="numeric",s.format="0.[0000000]";break;case"Float64":s.width=80,s.type="numeric",s.format="0.[0000000]";break;case"String":s.width=180}s.renderer=e._handsRenderer,s.data=i.name,a.push(s)}),{colHeaders:t,columns:a,colPositions:n}}},{key:"fecthContextMenu",value:function(){return{items:{columnformat:{name:"Column format",submenu:{items:[{name:"Reset",key:"columnformat:1",callback:function(t,a,n){e.makeFormat(this,"Reset")}},{name:"Money",key:"columnformat:2",callback:function(t,a,n){e.makeFormat(this,"Money")},disabled:function(){return!e.isFormatColl(this,"numeric")}},{name:"Human",key:"columnformat:3",callback:function(t,a,n){e.makeFormat(this,"Human")},disabled:function(){return!e.isFormatColl(this,"numeric")}},{name:"Bytes",key:"columnformat:4",callback:function(t,a,n){e.makeFormat(this,"Bytes")},disabled:function(){return!e.isFormatColl(this,"numeric")}},{name:"Percentages",key:"columnformat:5",callback:function(t,a,n){e.makeFormat(this,"Percentages")},disabled:function(){return!e.isFormatColl(this,"numeric")}},{name:"Time only",key:"columnformat:6",callback:function(t,a,n){e.makeFormat(this,"Time")},disabled:function(){return!e.isFormatColl(this,"Time")}},{name:"Date only",key:"columnformat:7",callback:function(t,a,n){e.makeFormat(this,"Date")},disabled:function(){return!e.isFormatColl(this,"Date")}},{name:"Date loc.",key:"columnformat:8",callback:function(t,a,n){e.makeFormat(this,"DateLoc")},disabled:function(){return!e.isFormatColl(this,"Date")}},{name:"Float",key:"columnformat:9",callback:function(t,a,n){e.makeFormat(this,"Float")},disabled:function(){return!e.isFormatColl(this,"numeric")}},{name:"Heatmaps",key:"columnformat:10",callback:function(t,a,n){e.makeHeatmaps(this,"Heatmaps")},disabled:function(){return!e.isFormatColl(this,"numeric")}},{name:"Negative & Positive",key:"columnformat:11",callback:function(t,a,n){e.makeHeatmaps(this,"NegaPosi")},disabled:function(){return!e.isFormatColl(this,"numeric")}}]}},style:{name:"Style",submenu:{items:[{name:"Normal",callback:function(t,a,n){e.makeStyle(this,"Normal")},key:"style:normal"},{name:"Bold",callback:function(t,a){e.makeStyle(this,"Bold")},key:"style:makebold"},{name:"Red color",callback:function(t,a){e.makeStyle(this,"Red")},key:"style:red"},{name:"Green color",callback:function(t,a){e.makeStyle(this,"Green")},key:"style:green"},{name:"Yellow color",callback:function(t,a){e.makeStyle(this,"Yellow")},key:"style:green"},{name:"Orange color",callback:function(t,a){e.makeStyle(this,"Orange")},key:"style:green"}]}},hsep1:"---------",copyTo:{name:"To Clipboard",submenu:{items:[{name:"Redmine Markdown",callback:function(t,a,n){console.info("copyToClipboard"),e.copyToClipboard(this,"Redmine")},key:"copyTo:1"},{name:"Redmine Markdown (full)",callback:function(t,a,n){console.info("copyToClipboard"),e.copyToClipboard(this,"Redmine",!0)},key:"copyTo:2"},{name:"WHERE col1 IN (val,val),col2 IN ...",callback:function(t,a,n){console.info("makeWhereIn"),e.makeWhereIn(this)},key:"copyTo:3"},{name:"Create TABLE...",callback:function(t,a,n){e.makeCreateTable(this)},key:"copyTo:4"}]}},hsep3:"---------",Transform:{name:"Transform",submenu:{items:[{name:"Transpose full table",callback:function(t,a,n){e.Transpose(this,"Transpose")},key:"Transform:1"}]}},undo:{},make_read_only:{},alignment:{},hsep4:"---------"}}}},{key:"makeSettings",value:function(){var e=this.makeColumns(),t={observeChanges:!1,observeDOMVisibility:!0,dropdownMenu:!0,manualColumnMove:!0,manualColumnResize:!0,rowHeaders:!0,colWidths:100,fillHandle:!1,stretchH:"all",customBorders:!0,isDark:this.isDarkTheme,filters:!0,columnSorting:!0,sortIndicator:!0,manualRowResize:!0,viewportColumnRenderingOffset:"auto",wordWrap:!1,autoColumnSize:{samplingRatio:23},columns:e.columns,colHeaders:e.colHeaders,contextMenu:this.fecthContextMenu(),currentRowClassName:this.isDarkTheme?"currentRowDark":"currentRowWhite",currentColClassName:"currentCol",renderAllRows:!1,visibleRows:1500};return this.Preset.sort&&this.Preset.sortOrder&&(t.columnSorting={column:e.colPositions[this.Preset.sort],sortOrder:"desc"==this.Preset.sortOrder.toLowerCase()?!1:!0}),t}}],[{key:"isDark",value:function(){return window.isDarkTheme}},{key:"makeHeatmaps",value:function(e,t){for(var a=e.getSelectedRange(),n=Math.min(a.from.col,a.to.col),r=Math.max(a.from.col,a.to.col),i="#a900e5",s="#3668ff",o=chroma.scale([i,s]),c=n;r>=c;c++){var l=e.countRows(),d=e.getDataAtCol(c),u=Math.min.apply(null,d),m=Math.max.apply(null,d);if(null!==u&&null!==m)for(var h=0;l>=h;h++){var p=parseFloat(e.getDataAtCell(h,c));if("Heatmaps"==t){var g=(p-u)/(m-u),f=o(g).hex(),b=e.getCellMeta(h,c);b&&e.setCellMeta(h,c,"backgroundColor",f)}if("NegaPosi"==t){var v=!1;0>p&&(v="#e27137"),p>0&&(v="#31b3e5");var y=e.getCellMeta(h,c);y&&v&&e.setCellMeta(h,c,"color",v)}}else console.warn("Can`t find Min&Max in column",c)}e.render()}},{key:"getSelected",value:function(e,t,a){var n=e.getSelectedRange(),r=!1;if(!n&&t||a)return{isSelection:!1,fromRow:0,toRow:e.countRows(),toCol:e.countCols(),fromCol:0};if(!n)return{isSelection:!1,fromRow:-1,toRow:-1,toCol:-1,fromCol:-1};var i=Math.min(n.from.col,n.to.col),s=Math.max(n.from.col,n.to.col),o=Math.min(n.from.row,n.to.row),c=Math.max(n.from.row,n.to.row);return{isSelection:r,fromRow:o,toRow:c,toCol:s,fromCol:i}}},{key:"makeFormat",value:function(t,a){for(var n=e.getSelected(t,!0),r=t.getSettings().columns,i=n.fromCol;i<=n.toCol;i++)switch(console.log("makeFormat for coll ="+i,a),a){case"Reset":r[i].format=!1,r[i].renderDateFormat=!1;break;case"Money":r[i].format="$0,0.00";break;case"Human":r[i].format="5a";break;case"Bytes":r[i].format="0.0b";break;case"Percentages":r[i].format="(0.00 %)";break;case"Time":r[i].renderDateFormat="HH:mm:ss";break;case"Date":r[i].renderDateFormat="YYYY-MM-DD";break;case"DateTime":r[i].renderDateFormat="YYYY-MM-DD HH:mm:ss";break;case"DateLoc":r[i].renderDateFormat="LLLL";break;case"Float":r[i].format="0.[0000000]"}t.updateSettings({columns:r}),t.render()}},{key:"isFormatColl",value:function(e,t){t=t.toLowerCase();for(var a=e.getSelectedRange(),n=Math.min(a.from.col,a.to.col),r=Math.max(a.from.col,a.to.col),i=e.getSettings().columns,s=n;r>=s;s++)if(!i[s].type.toLowerCase().includes(t))return!1;return!0}},{key:"pushToClipboardText",value:function(e){var t=document.createElement("textarea");t.style.width=0,t.style.height=0,t.style.border=0,t.style.position="absolute",t.style.top=0,document.body.append(t),t.value=e,t.focus(),t.select();try{document.execCommand("copy")}catch(a){console.log("Oops, unable to copy")}document.body.removeChild(t)}},{key:"makeCreateTable",value:function(t){for(var a=e.getSelected(t,!0),n="\nCREATE TABLE x (\n",r=[],i=t.getSettings().columns,s=a.fromCol;s<=a.toCol;s++){var o=i[s].typeOriginal;r.push(" "+t.colToProp(s)+" "+o)}n=n+r.join(",\n")+"\n)\nENGINE = TinyLog\n;;\n",console.log(n),e.pushToClipboardText(n)}},{key:"Transpose",value:function(t,a){var n=e.transpose(t.getSourceData()),r=[],i=[],s=!0,o=!1,c=void 0;try{for(var l,d=n.columns[Symbol.iterator]();!(s=(l=d.next()).done);s=!0){var u=l.value,m={};m.renderer=this._handsRenderer,m.data=u,m.type="text",m.width=100,i.push(m),r.push(u)}}catch(h){o=!0,c=h}finally{try{!s&&d["return"]&&d["return"]()}finally{if(o)throw c}}t.updateSettings({columns:i,colHeaders:r,data:n.data})}},{key:"transpose",value:function(e){var t=[],a=1,n=[];t.push(0);var r=!0,i=!1,s=void 0;try{for(var o,c=e[Symbol.iterator]();!(r=(o=c.next()).done);r=!0){var l=o.value,d=0,u=!0,m=!1,h=void 0;try{for(var p,g=Object.entries(l)[Symbol.iterator]();!(u=(p=g.next()).done);u=!0){var f=_slicedToArray(p.value,2),b=f[0],v=f[1];n[d]||(n[d]={}),1==a&&(n[d][0]=b),n[d][a]=v,d++}}catch(y){m=!0,h=y}finally{try{!u&&g["return"]&&g["return"]()}finally{if(m)throw h}}t.push(a),a++}}catch(y){i=!0,s=y}finally{try{!r&&c["return"]&&c["return"]()}finally{if(i)throw s}}return{data:n,columns:t}}},{key:"getPivotArray",value:function(e,t,a,n){for(var r={},i=[],s=[],o=0;o'+a+"":"")}},{key:"isDark",value:function(){return this.widget.isDark}},{key:"getError",value:function(){return this.errorMessage}},{key:"isExecutableCode",value:function(){return this.drawCodeObject&&this.drawCodeObject.type?this.drawCodeObject.exec:!1}},{key:"executableCode",value:function(){var e={};return this.isExecutableCode()&&(console.log(this.drawCodeObject.code),e=this.drawCodeObject.code.call(window,this.widget.data)),console.warn("executableCode:ResultFunction",e),e}},{key:"initChartByJsCode",value:function(){if(this.isExecutableCode()){var e=this.executableCode();return this.options=Object.assign(this.options,e),!0}return!1}},{key:"data",value:function(){return this.widget.data.data}},{key:"meta",value:function(){return this.widget.data.meta}},{key:"isNumericColumn",value:function(e){var t=this.getColumnPosition(e);if(!_.isUndefined(t)){var a=this.meta()[t].type;return a?(a=a.toLowerCase(),a.includes("int")||a.includes("float")?!0:!1):!1}}},{key:"isStringColumn",value:function(e){var t=this.getColumnPosition(e);if(!_.isUndefined(t)){var a=this.meta()[t].type;return a?(a=a.toLowerCase(),a.includes("string")||a.includes("enum")?!0:!1):!1}}},{key:"getColumnPosition",value:function(e){return parseInt(_.findKey(this.meta(),{name:e}))}},{key:"haveColumn",value:function(e){if(_.isNaN(e)||_.isNull(e)||_.isUndefined(e))return!1;var t=this.getColumnPosition(e);return _.isNaN(t)||_.isNull(t)||_.isUndefined(t)?!1:!0}},{key:"getColumnByType",value:function(e){var t=_.findIndex(this.meta(),{type:e});return 0>t?!1:this.getColumns(t)}},{key:"getDateTimeColumn",value:function(){return this.getColumnByType("DateTime")}},{key:"getDateColumn",value:function(){return this.getColumnByType("Date")}},{key:"getColumns",value:function(e){var t=_.map(this.meta(),"name");return _.isUndefined(e)?t:t[e]}},{key:"getFirstColumn",value:function(){return this.getColumns(0)}},{key:"getDrawCommandObject",value:function(){return this.drawCodeObject&&this.drawCodeObject.type?this.drawCodeObject.code:!1}},{key:"initDrawCodeObject",value:function initDrawCodeObject(){var drawCommand=this.widget.drawCommnads;if(!drawCommand)return[];var codeDrawText=!1;if(drawCommand&&drawCommand.code&&(codeDrawText=drawCommand.code),!codeDrawText)return[];var draw={code:!1,type:!1};if(_.isObject(codeDrawText))return draw={isok:!0,code:codeDrawText,type:"undefined"==typeof codeDrawText?"undefined":_typeof(codeDrawText),exec:!1};if("text"==drawCommand.drawtype.toLowerCase()){var obj=codeDrawText.trim();return draw={isok:!0,code:obj,type:"undefined"==typeof obj?"undefined":_typeof(obj),exec:!1}}for(var data={},columns=this.getColumns(),len=this.data().length,index=0;len>index;++index){var item=this.data()[index];for(var colPos in columns){var col=columns[colPos];data[col]||(data[col]=[]),data[col].push(item[col])}}try{var code="("+codeDrawText+")";console.log("CODE>>>",code);var _obj=eval(code),type="undefined"==typeof _obj?"undefined":_typeof(_obj);draw={isok:!0,code:_obj,type:type,exec:!!(_obj&&_obj.constructor&&_obj.call&&_obj.apply)}}catch(E){console.error("error eval ",codeDrawText,E)}return draw}}]),DrawBasicChart}(),DrawText=function(e){function t(e,a){_classCallCheck(this,t);var n=_possibleConstructorReturn(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));return n.type=a.toUpperCase(),n.library="text",n.widget.sizeX=0,n.widget.sizeY=0,n}return _inherits(t,e),_createClass(t,[{key:"preProcessor",value:function(){var e=this.getDrawCommandObject();this.init=this.applyText(e)}},{key:"applyText",value:function(e){return this.isDark()&&(this.widget.element[0].style.background="#404a59"),e?this.widget.element[0].innerHTML=Mustache.render(e,this.widget.data):this.widget.element[0].innerHTML="
"+JSON.stringify(this.widget.data,null,"	")+"
",!0}},{key:"onResize",value:function(){}}]),t}(DrawBasicChart),DrawPlotly=function(e){function t(e,a){_classCallCheck(this,t);var n=_possibleConstructorReturn(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));return n.type=a.toUpperCase(),n.library="plotly",n.chart=null,n.setWidgetSize(6,3),n}return _inherits(t,e),_createClass(t,[{key:"onResize",value:function(){if(this.plotly){var e=this.widget.getSizeElementHeight(),t=this.widget.getSizeElementWidth();(this.layout.height!=e||this.layout.width!=t)&&(this.layout.height=e,this.layout.width=t,this.relayout())}}},{key:"preProcessor",value:function(){return this.initChartByJsCode(),this.getError()?(console.error(this.getError()),this.chart.before("

"+this.getError()+"

"),!1):(this.isDark(),this.init=this.create(),void console.info("preProcessor",this.init))}},{key:"getElement",value:function(){return this.widget.element[0]}},{key:"relayout",value:function(){Plotly.relayout(this.getElement(),this.layout)}},{key:"editor",value:function(){console.info("editoreditoreditor")}},{key:"create",value:function(){var e=this.getDrawCommandObject();console.warn("CREATE DrawPlotly",e);var t={data:[],layout:{}};_.isObject(e)&&(_.isObject(e.trace)&&t.data.push(e.trace),_.isObject(e.trace1)&&t.data.push(e.trace1),_.isObject(e.trace2)&&t.data.push(e.trace2),_.isObject(e.trace3)&&t.data.push(e.trace3),_.isObject(e.trace4)&&t.data.push(e.trace4),_.isObject(e.layout)&&(t.layout=e.layout)),console.info(t);var a=[{x:[1,2],y:[1,2],type:"bar"}];console.log("CONS:",a),console.log("llll:",t);var n={editable:!1};this.layout=t.layout;var r=this.widget.getSizeElementHeight(),i=this.widget.getSizeElementWidth();return this.layout.height=r,this.layout.width=i,this.plotly=Plotly.plot(this.getElement(),t.data,this.layout,n),!0}},{key:"applyDarkTheme",value:function(){}}]),t}(DrawBasicChart),DrawGoogleMap=function(e){function t(e,a){_classCallCheck(this,t);var n=_possibleConstructorReturn(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));return n.type=a.toUpperCase(),n.library="gmaps",n._map=!1,n.mapOptions={zoom:4},n}return _inherits(t,e),_createClass(t,[{key:"onResize",value:function(){this._map&&google.maps.event.trigger(this._map,"resize")}},{key:"preProcessor",value:function(){this.loadGoogleMapJS(this)}},{key:"afterLoadMapProcessor",value:function(){if(this.initChartByJsCode()?this.init=!0:this.init=this.create(),this.getError())return console.error(this.getError()),this.chart.before("

"+this.getError()+"

"),!1;var e=this.getDrawCommandObject();e.raw&&(this.options=_.merge(this.options,e.raw)),this.isDark(),console.info("preProcessor",this.init,this.options)}},{key:"loadGoogleMapJS",value:function(e){if(window._sendGoogleMapLoad)return void this.afterLoadMapProcessor();window._sendGoogleMapLoad=!0,window._isGoogleMapLoaded=!1,console.info("YA_MAP>Start load map : api-maps.yandex.ru");var t=document.createElement("script");t.type="text/javascript",t.async=!0,t.src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCRQH39oyrPnfPPgADuOp0eSRsDHRUMyyY",t.charset="utf-8",t.onload=t.onreadystatechange=function(){t.readyState&&"complete"!==t.readyState&&"loaded"!==t.readyState||(t.onload=t.onreadystatechange=null,e.afterLoadMapProcessor(),window._isGoogleMapLoaded=!0)};var a=document.getElementsByTagName("script")[0];a.parentNode.insertBefore(t,a)}},{key:"getDarkStyle",value:function(){return[{featureType:"all",elementType:"labels.text.fill",stylers:[{color:"#ffffff"}]},{featureType:"all",elementType:"labels.text.stroke",stylers:[{color:"#000000"},{lightness:13}]},{featureType:"administrative",elementType:"geometry.fill",stylers:[{color:"#000000"}]},{featureType:"administrative",elementType:"geometry.stroke",stylers:[{color:"#144b53"},{lightness:14},{weight:1.4}]},{featureType:"landscape",elementType:"all",stylers:[{color:"#08304b"}]},{featureType:"poi",elementType:"geometry",stylers:[{color:"#0c4152"},{lightness:5}]},{featureType:"road.highway",elementType:"geometry.fill",stylers:[{color:"#000000"}]},{featureType:"road.highway",elementType:"geometry.stroke",stylers:[{color:"#0b434f"},{lightness:25}]},{featureType:"road.arterial",elementType:"geometry.fill",stylers:[{color:"#000000"}]},{featureType:"road.arterial",elementType:"geometry.stroke",stylers:[{color:"#0b3d51"},{lightness:16}]},{featureType:"road.local",elementType:"geometry",stylers:[{color:"#000000"}]},{featureType:"transit",elementType:"all",stylers:[{color:"#146474"}]},{featureType:"water",elementType:"all",stylers:[{color:"#021019"}]}]}},{key:"getLightStyle",value:function(){return[{featureType:"landscape",stylers:[{hue:"#FFBB00"},{saturation:43.400000000000006},{lightness:37.599999999999994},{gamma:1}]},{featureType:"road.highway",stylers:[{hue:"#FFC200"},{saturation:-61.8},{lightness:45.599999999999994},{gamma:1}]},{featureType:"road.arterial",stylers:[{hue:"#FF0300"},{saturation:-100},{lightness:51.19999999999999},{gamma:1}]},{featureType:"road.local",stylers:[{hue:"#FF0300"},{saturation:-100},{lightness:52},{gamma:1}]},{featureType:"water",stylers:[{hue:"#0078FF"},{saturation:-13.200000000000003},{lightness:2.4000000000000057},{gamma:1}]},{featureType:"poi",stylers:[{hue:"#00FF6A"},{saturation:-1.0989010989011234},{lightness:11.200000000000017},{gamma:1}]}]}},{key:"create",value:function(){console.warn("CREATE"),this._map=new google.maps.Map(this.widget.element[0],this.mapOptions);var e=this.getLightStyle();this.isDark()&&(e=this.getDarkStyle()),this._map.setOptions({styles:e});var t=this,a=this.getDrawCommandObject(),n={longitude:"longitude",latitude:"latitude",count:"count",title:"title"},r=new google.maps.LatLngBounds,i=0;a&&(n=Object.assign(n,a)),this.data().forEach(function(e,a){var s=parseInt(e[n.count]);s>i&&(i=s);var o={lat:e[n.latitude],lng:e[n.longitude]},c=!1;e[n.title]&&(c=new google.maps.InfoWindow({content:'
'+e[n.title]+"
"})),r.extend(o);var l=new google.maps.Marker({position:o,map:t._map,title:"Value:"+s});c&&l.addListener("click",function(){c.open(this._map,l)})}),this._map.fitBounds(r),this._map.panToBounds(r)}}]),t}(DrawBasicChart),DrawEcharts=function(e){function t(e,a){_classCallCheck(this,t);var n=_possibleConstructorReturn(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));return n.help="",n.type=a.toUpperCase(),n.library="echarts",n.preference={gridchart:!1,bar:!1},n.options={version:3,textStyle:{fontFamily:"Menlo"},toolbox:{show:!0,feature:{dataZoom:{yAxisIndex:"none",title:"data Zoom"},dataView:{readOnly:!1,title:"data View"},magicType:{type:["line","bar","stack","tiled"],title:{line:"line",bar:"bar",stack:"stack",tiled:"tiled"}},restore:{title:"Restore"},saveAsImage:{title:"Save as Image"}}}},n}return _inherits(t,e),_createClass(t,[{key:"onResize",value:function(){console.log("onResize Chart"),this.chart&&this.init&&this.chart.resize()}},{key:"preProcessor",value:function(){if(this.initChartByJsCode())this.init=!0;else try{this.init=this.create()}catch(e){this.setError(this.getError()+"\n\n\n"+e.name+":"+e.message+"\n"+e.stack)}if(this.getError())return console.error(this.getError()),!1;var t=this.getDrawCommandObject();t.raw&&(this.options=_.merge(this.options,t.raw)),this.isDark()&&(this.options.backgroundColor="#404a59"),this.chart.setOption(this.options),console.info("preProcessor",this.init,this.options)}},{key:"getParameterPath",value:function(){var e=this.getDrawCommandObject(),t={path:""};e&&(t=Object.assign(t,e));var a="";if(_.isString(e)?a=e:t.path&&(a=t.path),!a)return!1;for(var n=_.split(a,"."),r=0;rs;s+=1){var o=this.getColumns(s);if(!r&&this.isNumericColumn(o)){r=o;break}}t.date=n,t.value=r}if(!this.haveColumn(t.date)||!this.haveColumn(t.value))return this.setError("Not set date | value cols"),!1;var c=0,l=Number.MAX_VALUE,d=_.map(this.data(),function(e){var a=parseFloat(e[t.value]);return a&&a>c&&(c=a),a&&l>a&&(l=a),[e[t.date],a]});d=_.groupBy(d,function(e){var t=(""+e[0]).substring(0,4);return t});var u={tooltip:{position:"top"},calendar:[],series:[],visualMap:{min:l,max:c,calculable:!0,orient:"horizontal",left:"center",top:"top"}},m=60,h=0;return _.forEach(d,function(e,t){u.calendar.push({top:m,range:t,right:0,cellSize:["auto",20]}),u.series.push({type:"heatmap",coordinateSystem:"calendar",data:e,calendarIndex:h}),h+=1,m+=200}),this.options=Object.assign(u,this.options),!0}}]),t}(DrawEcharts),DrawEchartsTreemap=function(e){function t(){return _classCallCheck(this,t),_possibleConstructorReturn(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return _inherits(t,e),_createClass(t,[{key:"getLevelOption",value:function(){return[{itemStyle:{normal:{borderWidth:0,gapWidth:5}}},{itemStyle:{normal:{gapWidth:1}}},{colorSaturation:[.35,.5],itemStyle:{normal:{gapWidth:1,borderColorSaturation:.6}}}]}},{key:"buildTreeData",value:function(e,t){var a=[],n=this;return _.forEach(e,function(e,r){var i=t[r],s={};if(s.value=i.__value,_.isObject(e)){var o=n.buildTreeData(e,i);_.isArray(o)&&o.length&&(s.children=o)}s.name=r,a.push(s)}),a}},{key:"create",value:function(){var e=this.getDrawCommandObject(),t={path:"",title:"TreeMap",tooltip:"Usage",valueformat:!1};e&&(t=Object.assign(t,e));var a="";t.path&&(a=t.path),_.isString(e)&&(a=e);var n=_.split(a,"."),r=n.length;if(!r)return this.setError("Not set path"),!1;for(var i=0;r>i;i+=1)if(!this.haveColumn(n[i]))return this.setError("bad path, no column:"+n[i]),!1;if(!this.isNumericColumn(n[r-1]))return this.setError("bad column:"+n[r-1]+" must be number"),!1;var s={},o={};this.data().forEach(function(e){for(var t=e[n[r-1]],a=[],i=0;r-1>i;i+=1){a.push(e[n[i]]);var c=_.get(s,a.join("_"),0);_.set(s,a.join(".")+".__value",parseFloat(c)+parseFloat(t))}_.set(o,a.join("."),t)});var c=this.buildTreeData(o,s),l={tooltip:{trigger:"item"}},d=echarts.format;return l.series=[{type:"treemap",name:t.title,label:{show:!0,formatter:"{b}"},tooltip:{formatter:function(e){for(var a=e.value,n=[],r=e.treePathInfo,i=1;i'+d.encodeHTML(n.join("."))+"",t.tooltip+" : "+numbro(a).format(s)].join("")}},itemStyle:{normal:{borderColor:"#fff"}},levels:this.getLevelOption(),data:c}],this.options=Object.assign(l,this.options),!0}}]),t}(DrawEcharts),DrawEchartsSunkeys=function(e){function t(){return _classCallCheck(this,t),_possibleConstructorReturn(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return _inherits(t,e),_createClass(t,[{key:"create",value:function(){this.helpLink="https://tabix.io/doc/draw/Draw_Sankeys/",this.help="Default config : {path:''} or {value:'',source:'',target:''}, if empty path or not set, try auto create path, then find columns [String] : [Integer|Float] : [String] ";var e=this.getDrawCommandObject(),t={path:"",value:"value",source:"source",target:"target"};e&&(t=Object.assign(t,e));var a="";_.isString(e)?a=e:t.path?a=t.path:this.haveColumn(t.source)&&this.haveColumn(t.value)&&this.haveColumn(t.target)&&(a=t.source+"."+t.value+"."+t.target);var n=[];if(a)n=_.split(a,".");else{var r=!1,i=this.getColumns();for(var s in i){var o=i[s];this.isNumericColumn(o)&&r&&(n.push(o),r=!1),this.isStringColumn(o)&&!r&&(n.push(o),r=!0)}}if(console.log("patharr>",n),!n.length)return this.setError("The value of the variable 'path' - empty"),!1;if(!(1&n.length))return this.setError("The value of the variable 'path' must be odd"),!1;var c=[],l=[];this.data().forEach(function(e){for(var t=0;ta&&(a=s),e[t.destination.longitude]&&e[t.destination.latitude]){var o="";e[t.destination.name]&&(o=e[t.destination.name]),r.push({fromName:e[t.name],toName:o,coords:[[e[t.longitude],e[t.latitude]],[e[t.destination.longitude],e[t.destination.latitude]]]})}n.push({name:e[t.name],value:[e[t.longitude],e[t.latitude],s],label:{emphasis:{position:"right",show:!0}}})});var i=[{name:t.title,type:"effectScatter",coordinateSystem:"geo",data:n,showEffectOn:"render",rippleEffect:{brushType:"stroke"},symbolSize:function(e){return a?e[2]/a*15:e[2]/1e4},hoverAnimation:!0,label:{normal:{formatter:"{b}",position:"right",show:!0}},itemStyle:{normal:{color:"#f4e925",shadowBlur:10,shadowColor:"#333"}},zlevel:1}];if(r.length>0){var s="path://M1705.06,1318.313v-89.254l-319.9-221.799l0.073-208.063c0.521-84.662-26.629-121.796-63.961-121.491c-37.332-0.305-64.482,36.829-63.961,121.491l0.073,208.063l-319.9,221.799v89.254l330.343-157.288l12.238,241.308l-134.449,92.931l0.531,42.034l175.125-42.917l175.125,42.917l0.531-42.034l-134.449-92.931l12.238-241.308L1705.06,1318.313z"; -i.push({name:t.title,type:"lines",zlevel:1,effect:{show:!0,period:6,trailLength:.7,color:"#fff",symbolSize:3},lineStyle:{normal:{width:0,curveness:.2}},data:r}),i.push({name:t.title,type:"lines",zlevel:2,symbol:["none","arrow"],symbolSize:10,effect:{show:!0,period:6,trailLength:0,symbol:s,symbolSize:15},lineStyle:{normal:{width:1,opacity:.6,curveness:.2}},data:r})}var o={tooltip:{trigger:"item"},geo:{name:t.title,type:"map",map:"world",label:{emphasis:{show:!1}},visualMap:{show:!0,min:0,max:100,inRange:{symbolSize:[6,60]}},roam:!0,itemStyle:{normal:{areaColor:"#323c48",borderColor:"#404a59"},emphasis:{areaColor:"#2a333d"}}},series:i};return this.options=Object.assign(this.options,o),!0}}]),t}(DrawEcharts),DrawEchartsHeatmap=function(e){function t(){return _classCallCheck(this,t),_possibleConstructorReturn(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return _inherits(t,e),_createClass(t,[{key:"create",value:function(){var e=this.getParameterPath();if(!e)return this.setError("Not set path"),!1;var t={},a={},n={};this.data().forEach(function(r){_.set(t,r[e[0]],1),_.set(a,r[e[1]],1),_.set(n,r[e[0]]+"."+r[e[1]],parseFloat(r[e[2]]))});var r=[],i=_.keys(t),s=_.keys(a),o=0,c=0;_.mapKeys(t,function(e,t){_.mapKeys(a,function(e,a){var i=_.get(n,t+"."+a,"-");o>i&&(o=i),i>c&&(c=i),r.push([t,a,i])})});var l={tooltip:{position:"top"},animation:!1,grid:{height:"50%",y:"10%"},xAxis:{type:"category",data:i,splitArea:{show:!0}},yAxis:{type:"category",data:s,splitArea:{show:!0}},visualMap:{min:o,max:c,calculable:!0,orient:"horizontal",left:"center",bottom:"15%"},series:[{name:"Punch Card",type:"heatmap",data:r,label:{normal:{show:!0}},itemStyle:{emphasis:{shadowBlur:10,shadowColor:"rgba(0, 0, 0, 0.5)"}}}]};return this.options=Object.assign(l,this.options),!0}}]),t}(DrawEcharts),DrawEchartsChart=function(e){function t(){return _classCallCheck(this,t),_possibleConstructorReturn(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return _inherits(t,e),_createClass(t,[{key:"create",value:function(){console.log("DrawEchartsChart");var e=this.getDrawCommandObject(),t=this.preCreate(e),a=this.createChart(e),n={tooltip:{trigger:"axis",axisPointer:{type:"shadow"}},grid:{left:"3%",right:"4%",bottom:"3%",containLabel:!0}};return e.title&&this.applyTitle(e.title),this.applyDataZoom(),this.applyLegend(),this.options=Object.assign(a,this.options,n,t),this.postCreate(e),!0}},{key:"findDateTimeAxis",value:function(){var e=this.getDateTimeColumn();if(e)return e;var t=this.getDateColumn();return t?t:!1}},{key:"postCreate",value:function(e){return{}}},{key:"preCreate",value:function(e){return{}}},{key:"createChart",value:function(e){var t=this,a={autoAxis:!1,markLine:!0,stack:!1,path:!1,sort:!0,xAxis:!1,yAxis:!1};e&&(a=Object.assign(a,e));var n={},r=this.getColumns(),i=this.getFirstColumn(),s=i,o=this.findDateTimeAxis(),c={},l=[],d=[],u=[],m={},h=this.data();if(o&&(i=o),a.xAxis){if(!this.haveColumn(a.xAxis))throw"xAxis column not exists";s=a.xAxis}else a.sort&&(h=_.sortBy(h,i)),s=i;if(d=[{name:s,type:"category",data:[]}],a.yAxis)if(_.isString(a.yAxis)){if(!this.haveColumn(a.yAxis))throw"yAxis column not exists";n[a.yAxis]=1}else{if(!_.isArray(a.yAxis))throw"yAxis column must string or array";var p=void 0;for(p=0;pk&&!w?(_.isArray(y)||(y=[]),y.push(S),k++):this.isNumericColumn(S)&&x.push(S))}var A=h.length;for(console.log("DATA LEN",A,h),v=0;A>v;++v){var D=h[v];d[0].data.push(D[d[0].name])}for(d[0].data=_.uniq(d[0].data),console.log("xAxis[0].data.",d[0].data),v=0;A>v;++v){var R=h[v],I=function(e){var a=r[e],i=[s],o=!1;if(_.size(n)&&(o=_.isUndefined(n[a])),a!==s&&!o&&t.isNumericColumn(a)&&_.findIndex(y,a)<0){if(y)for(var c=0;c1){var q=_.groupBy(f,function(e){return Math.floor(e.median/1e3)});if(_.size(q)>1){var H=function(e){var t=q[e],n=_.map(t,"column").join(",");_.forEach(t,function(e){u[e.index].yAxisIndex=l.length,a.stack&&(u[e.index].stack=n,u[e.index].areaStyle={normal:{}})}),l.push({name:n,type:"value"})};for(var P in q)H(P)}}return l.length||(l=[{name:b,type:"value"}]),c.series=u,c.yAxis=l,c.xAxis=d,console.info("Make Chart Done : Options",c),c}}]),t}(DrawEcharts),DrawEchartsGridChart=function(e){function t(){return _classCallCheck(this,t),_possibleConstructorReturn(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return _inherits(t,e),_createClass(t,[{key:"preCreate",value:function(e){return this.preference.gridchart=!0,{}}},{key:"postCreate",value:function(e){var t=[],a=[],n=[],r=[],i=0;console.info("postCreate!!!!!!",this.options);var s=[],o=this.options.xAxis[0],c=this.options.yAxis[0];for(var l in this.options.series){l=parseInt(l);var d=this.options.series[l].name;this.options.series[l].xAxisIndex=l,this.options.series[l].yAxisIndex=i,console.log(d,this.options.series[l]),o.show=!1,o.gridIndex=l,c.gridIndex=l,c.show=!1,c.name=d,t.push({show:!0,borderWidth:0,shadowBlur:2}),n.push(_.clone(o)),a.push(_.clone(c)),r.push({textAlign:"center",text:d,textStyle:{fontSize:11,fontWeight:"normal"}}),s.push(l),i+=1}var u=Math.ceil(Math.sqrt(i));t.forEach(function(e,t){e.left=t%u/u*100+.5+"%",e.top=Math.floor(t/u)/u*100+.5+"%",e.width=1/u*100-1+"%",e.height=1/u*100-1+"%",r[t].left=parseFloat(e.left)+parseFloat(e.width)/2+"%",r[t].top=parseFloat(e.top)+"%"}),this.options.dataZoom&&this.options.dataZoom[0]&&(this.options.dataZoom[0].xAxisIndex=s),this.options.titles=r,this.options.grid=t,this.options.xAxis=n,this.options.yAxis=a}}]),t}(DrawEchartsChart),DrawEchartsBar=function(e){function t(){return _classCallCheck(this,t),_possibleConstructorReturn(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return _inherits(t,e),_createClass(t,[{key:"preCreate",value:function(e){return this.preference.bar=!0,{}}}]),t}(DrawEchartsChart),DrawD3=function(e){function t(e){_classCallCheck(this,t);var a=_possibleConstructorReturn(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));return a.library="d3",a}return _inherits(t,e),t}(DrawBasicChart),DrawC3=function(e){function t(e){_classCallCheck(this,t);var a=_possibleConstructorReturn(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));return a.library="c3",a.bindto=!1,a}return _inherits(t,e),_createClass(t,[{key:"onResize",value:function(){this.chart&&this.init}},{key:"preProcessor",value:function(){return console.log("preProcessor>c3.generate"),this.initChartByJsCode()?(console.log("c3.options>",this.options),this.bindto.className+=" c3",console.log("this.bindto.className",this.bindto.className),this.options.bindto=this.bindto,console.log("c3.options>",this.options),void(this.chart=c3.generate(this.options))):(console.error("C3.Init by code"),!1)}}]),t}(DrawBasicChart),DrawAMcharts=function(e){function t(e){_classCallCheck(this,t),console.warn("DrawAMcharts constructor");var a=_possibleConstructorReturn(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));return a.library="amchart",a}return _inherits(t,e),_createClass(t,[{key:"onResize",value:function(){this.makeLegend()}},{key:"preProcessor",value:function(){this.createChart()&&(this.init=!0),console.log("!preProcessor,done",this.init,this.options)}},{key:"createChart",value:function(){var e=this,t={},a=this.widget.data.meta,n=!1,r="",i="mm",s=[],o=0,c=[];a.forEach(function(a){if("DateTime"==a.type)n="YYYY-MM-DD JJ:NN:SS",r=a.name;else if("Date"==a.type)n="YYYY-MM-DD",i="DD",r=a.name;else{if(!r)return void(r=a.name);o+=1;var l=e.getChartGraph(a,t[a.name]);l.id="g"+o,"v1"!==l.valueAxis&&c.push(l.valueAxis),s.push(l)}});var l={theme:Widget.isDark?"dark":"light",color:Widget.isDark?"#eee":"#333",type:"serial",categoryField:r,valueAxes:[{id:"v1",axisAlpha:1,gridAlpha:.07,axisColor:Widget.isDark?"#eee":"#333",gridColor:Widget.isDark?"#eee":"#333",ignoreAxisWidth:!0}],balloon:{borderThickness:1,shadowAlpha:0},graphs:s,chartCursor:{valueLineEnabled:!0,valueLineBalloonEnabled:!0,cursorAlpha:0,zoomable:!1,valueZoomable:!0,valueLineAlpha:.5},chartScrollbar:{graph:"g1",gridAlpha:0,color:"#888888",scrollbarHeight:25,backgroundAlpha:0,selectedBackgroundAlpha:.1,selectedBackgroundColor:"#888888",graphFillAlpha:0,autoGridCount:!0,selectedGraphFillAlpha:0,graphLineAlpha:.2,graphLineColor:"#c2c2c2",selectedGraphLineColor:"#888888",selectedGraphLineAlpha:1},categoryAxis:{dashLength:1,minorGridEnabled:!0,axisColor:Widget.isDark?"#eee":"#333",gridColor:Widget.isDark?"#eee":"#333"},data:this.widget.data.data};if(l.categoryAxis.parseDates=!1,n&&(l.dataDateFormat=n,l.categoryAxis.parseDates=!0,l.categoryAxis.minPeriod=i),c){var d=0;c.forEach(function(e){d++;var t={id:e,axisAlpha:1,axisThickness:1,position:"right",ignoreAxisWidth:!0,offset:1*d};l.valueAxes.push(t)})}return this.options=l,this.init=!0,this.makeLegend(),!0}},{key:"makeLegend",value:function(){console.log("this.widget.sizeY",this.widget.sizeY),this.widget.sizeY<2?delete this.options.legend:this.options.legend={align:"center",equalWidths:!1,periodValueText:"total: [[value.sum]]",valueAlign:"left",valueText:"[[value]] ([[percents]]%)",valueWidth:100},console.warn(this.options)}},{key:"getChartGraph",value:function(e,t){var a=e.name,n=e.name,r="v1";a=a.replace(/_axis\d+/gm,"");var i=/.*_axis(\d+).*/i,s=n.match(i);s&&s[1]&&(r="v"+s[1]);var o={id:"g1",valueAxis:r,fillAlphas:.2,bullet:"round",bulletSize:8,hideBulletsCount:50,lineThickness:1,title:a,useLineColorForBulletBorder:!0,valueField:n,type:"smoothedLine",balloonText:"[[title]] [[category]]
[[value]]"};return t||(t={}),Object.assign(o,t)}}]),t}(DrawBasicChart),DataProvider=function(){function e(t,a){_classCallCheck(this,e),t.totals&&t.data&&t.data.push(t.totals),this.data=t.data,this.text=!1,this.progressQuery="",this.sort=!1,this.sortOrder=!1,t.error||angular.isObject(t.data)||(angular.isString(t.data)?this.text=t.data:this.text=angular.toJson(t.data,!0),this.text=this.text.replace(/&/g,"&").replace(//g,">")),a||(a="ch"),this.sourceType=a,this.meta=t.meta,t.query?this.query=t.query:this.query={index:0,drawCommands:!1},t.error?(this.error=t.error.replace("
","\n").replace(/&/g,"&").replace(//g,">"),this.error=this.error.replace("\\n","
")):this.error=!1,this.draw=this.query.drawCommands,this.rows=t.rows,this.position=this.query.index,this.countAll=t.countAllQuery}return e.$inject=["result","sourceType"],_createClass(e,[{key:"isText",value:function(){return this.text?!0:!1}},{key:"isError",value:function(){return this.error?!0:!1}},{key:"getError",value:function(){return this.error}},{key:"data",value:function(){return this.data}},{key:"meta",value:function(){return this.meta}},{key:"toString",value:function(){return"("+this.name+", "+this.y+")"}}],[{key:"convertArrayToDataProvider",value:function(t,a){var n={};return n.data=t,n.meta=[],n.error=!1,n.query={drawCommands:!1},n.rows=t.length,n.position=0,n.countAll=0,Object.keys(t[0]).map(function(e){return n.meta.push({name:e,type:"string"})}),new e(n,a)}}]),e}();angular.module(smi2.app.name).service("DataProvider",DataProvider),function(e,t){function a(t,a,n,r,i,s,o,c){t.vars={isDark:r.isDark(),historysql:a.sqlLog,charthelp:[],active:{chart:!0,history:!0,snippet:!0,vars:!0},snippets:o.snippets,variables:s.vars},t.vars.scrollConfig2={autoHideScrollbar:!1,theme:r.isDark()?"light":"dark",scrollButtons:{enable:!1},scrollInertia:400,setHeight:200,advanced:{updateOnContentResize:!0}},t.showAddVarsDialog=function(a){c.show({controller:["$scope","$mdDialog",function(e,t){e.v={name:"Var1",type:"text",value:""},e.close=function(){t.cancel()},e.add=function(e){t.hide(e)}}],templateUrl:"app/base/addVarsDialog.html",parent:e.element(document.body),targetEvent:a,clickOutsideToClose:!0}).then(function(e){e.name&&e.value&&e.type&&(s.addVar(e.type,e.name,e.value),t.broadcast())},function(){})},t.broadcast=function(){a.$emit("handleBroadcastUpdateVarsAndSnippets",{value:!0})},t.changed=function(e){s.update(e),t.broadcast()},t.showState=function(){console.warn(t.vars.variables)},t.addVar=function(){s.addVar("int","limit",1e3),t.broadcast()},t.actionHistory=function(e){a.$emit("handleBroadcastInsertInActive",{value:e})},t.dropSnippet=function(e){o.drop(e),t.broadcast()},t.dropVar=function(e){s.drop(e),t.broadcast()},t.init=function(){(!_.isObject(t.vars)||_.isUndefined(t.vars.variables.limit))&&s.addVar("int","limit",1e3)},t.init()}e.module(t.app.name).controller("SidebarHelperCtrl",a),a.$inject=["$scope","$rootScope","API","ThemeService","localStorageService","Variables","Snippets","$mdDialog"]}(angular,smi2),function(e,t){function a(e,t,a,n,r,i,s,o,c,l){e.vars={searchline:"",counter:0,loaded:!1,error:!1,databases:[]},e.vars.scrollConfig={autoHideScrollbar:!1,theme:r.isDark()?"light":"dark",scrollButtons:{enable:!1},scrollInertia:400,advanced:{updateOnContentResize:!0}},e.vars.metis={config:{toggle:!1,preventDefault:!1}},e.clickInsertField=function(e){t.$emit("handleBroadcastInsertInActive",{value:e.name})},e.clickAndSelect=function(a,n){return a.name==t.currentDatabase?(n.stopPropagation(),!1):void e.selectDatabase(a)},e.selectDatabase=function(e){console.time("sidebar.selectDatabase time took"),t.currentDatabase=e.name,s.show(s.simple().content("USE "+e.name+" database").theme(r.theme).position("bottom right")),console.timeEnd("sidebar.selectDatabase time took")},e.openTable=function(e){console.log("openTable!!!!!!!!!!!!!!!!!!!!!!!"),i("tableSiedenav").close(),t.currentDatabase!=e.database&&(s.show(s.simple().content("USE "+e.database+" database").theme(r.theme).position("bottom right")),t.currentDatabase=e.database),t.currentTable=e.name,i("tableSiedenav").open()},t.$on("handleBroadcastDatabases",function(){e.reLoad(!0),e.$applyAsync()}),e.updateDS=function(){n.databaseStructure(function(e){a.reload()},!0)},e.rightMenuProcessTable=function(e,a,r,i){console.log("rightMenuProcessTable",e,a,r),"InsertSQLDrop"==e&&(-1!==r.indexOf(".")&&(r='"'+r+'"'),t.$emit("handleBroadcastInsertInActive",{value:"DROP TABLE IF EXISTS "+a+"."+r})),"InsertName"==e&&t.$emit("handleBroadcastInsertInActive",{value:a+"."+r}),"InsertSQLDescribe"==e&&n.query("SHOW CREATE TABLE "+a+'."'+r+'"').then(function(e){var a=window.sqlFormatter.format(e.data[0].statement);t.$emit("handleBroadcastInsertInActive",{value:a})}),"OpenTables"==e&&(window.location="/#/database/"+a+"/table/"+r),"InsertDescribe"==e&&n.query("SELECT * FROM system.columns WHERE database='"+a+"' AND table='"+r+"'").then(function(e){var n=[],i=[];e.data.forEach(function(e){n.push(e.name),"Date"==e.type&&i.push(e.name+"=today()")}),-1!==r.indexOf(".")&&(r='"'+r+'"');var s="\nSELECT\n "+n.join(",\n ")+"\nFROM\n "+a+"."+r+"\n";i.length&&(s=s+"\nWHERE\n "+i.join("\n AND \n")),s+="\nLIMIT 100\n\n",console.log(s),t.$emit("handleBroadcastInsertInActive",{value:s})})},e.showAlertDatabaseStructure=function(e){o.show(o.alert().clickOutsideToClose(!0).title("Error on load database structure").textContent(e).ariaLabel("Error on load database structure").ok("OK")).then(function(e){n.clear(),a.go("login")})},e.reLoad=function(a){e.vars.loaded=!1,e.vars.error=!1,e.vars.databases=[],t.isInitDatabaseStructure=!1,n.fetchQuery("SELECT 1").then(function(r){e.$applyAsync(),n.databaseStructure(function(a){console.log("isInitDatabaseStructure-true"),t.isInitDatabaseStructure=Date.now(),e.$applyAsync(),console.log("databaseStructure - done");var n=a.getFields();e.vars.databases=a.getTables().reduce(function(e,t){var a=[{active:!0,value:"Select",key:"OpenTables",icon:"arrow-expand",db:t.database}],r=[{active:!0,value:"Open table",key:"OpenTables",icon:"arrow-expand",db:t.database,table:t.name},{active:!0,value:"Code Select from",key:"InsertDescribe",icon:"format-size",db:t.database,table:t.name},{active:!0,value:"Insert table name",key:"InsertName",icon:"bing",db:t.database,table:t.name},{active:!0,value:"Make SQL Describe",key:"InsertSQLDescribe",icon:"border-vertical",db:t.database,table:t.name},{active:!0,value:"Make SQL Drop",key:"InsertSQLDrop",icon:"delete",db:t.database,table:t.name}],i="table";t.engine.match(/Dictionary.*/)&&(i="library"),t.engine.match(/Distributed.*/)&&(i="soundcloud"),t.engine.match(/AggregatingMergeTree.*/)&&(i="cube"),t.engine.match(/MaterializedView.*/)&&(i="border-bottom"),t.engine.match(/SummingMergeTree.*/)&&(i="table-row-plus-after"),t.engine.match(/CollapsingMergeTree.*/)&&(i="table-row-height"),t.engine.match(/$Merge^/)&&(i="source-fork"),t.active=!0,t.classEngine=i,t.rightMenuListTable=r;var s=!0,o=!1,c=void 0;try{for(var l,d=e[Symbol.iterator]();!(s=(l=d.next()).done);s=!0){var u=l.value;if("-"!==t.name&&u.name==t.database)return u.tables.push({active:!0,database:t.database,name:t.name,engine:t.engine,classEngine:t.classEngine,fields:n[t.database+"."+t.name],rightMenuList:t.rightMenuListTable}),e}}catch(m){o=!0,c=m}finally{try{!s&&d["return"]&&d["return"]()}finally{if(o)throw c}}return[].concat(_toConsumableArray(e),[{name:t.database,rightMenuList:a,tables:[{active:!0,database:t.database,name:t.name,engine:t.engine,classEngine:t.classEngine,rightMenuList:t.rightMenuListTable,fields:n[t.database+"."+t.name]}]}])},[]),e.selectDatabase(e.vars.databases[0]),a.getDatabases().forEach(function(t){var a=!1;e.vars.databases.forEach(function(e){e.name==t.name&&(a=!0)}),a||e.vars.databases.push({name:t.name,tables:[],active:!0})}),c(function(){e.vars.loaded=!0,e.vars.error=!1,$("#sideBarMetismenu").metisMenu()},100)},a)},function(t){e.showAlertDatabaseStructure(t)})},e.reLoad()}e.module(t.app.name).controller("SidebarController",a),a.$inject=["$scope","$rootScope","$state","API","ThemeService","$mdSidenav","$mdToast","$mdDialog","$timeout","localStorageService"]}(angular,smi2),function(e,t){function a(a,n,r,i,s){a.user=r.getConnectionInfo().name,a.themes=i.list,a.isChrome=/Chrome/.test(navigator.userAgent),a.vars={disable_exit:window.global_tabix_disable_exit,hideExitButton:!window.global_tabix_disable_exit},a.help=function(a){function n(e,a){e.vars={version:t.app.version,buildDate:t.app.buildDate},e.hide=function(){a.hide()},e.cancel=function(){a.cancel()},e.answer=function(e){a.hide(e)}}n.$inject=["$scope","$mdDialog"],s.show({controller:n,templateUrl:"app/base/helpDialogRu.html",parent:e.element(document.body),targetEvent:a,clickOutsideToClose:!0})},a.logout=function(){r.clear(),n.go("login")},a.setUiTheme=function(e){i.set(e.name),window.location.reload()}}e.module(t.app.name).controller("HeaderController",a),a.$inject=["$scope","$state","API","ThemeService","$mdDialog"]}(angular,smi2),angular.module("ui.ace",[]).constant("uiAceConfig",{}).directive("uiAce",["uiAceConfig",function(e){if(angular.isUndefined(window.ace))throw new Error("ui-ace need ace to work... (o rly?)");return{restrict:"EA",link:function(t,a,n){var r=e.ace||{},i=angular.extend({},r,t.$eval(n.uiAce)),s=window.ace.edit(a[0]);console.time("Ace Load"),i.onLoad(s),console.timeEnd("Ace Load"),a.on("$destroy",function(){s.session.$stopWorker(),s.destroy()}),t.$watch(function(){return[a[0].offsetWidth,a[0].offsetHeight]},function(){s.resize(),s.renderer.updateFull()},!0)}}}]),/* +var HandsTable=function(){function e(t,a,n){_classCallCheck(this,e),this.isDarkTheme=t,this.meta=a,this.Preset=n}return e.$inject=["isDark","metaData","Preset"],_createClass(e,[{key:"_handsRenderer",value:function(e,t,a,n,r,i,s){"numeric"==s.type?null==i||"-nan"==i||"inf"==i||"+nan"==i||"+inf"==i||"-inf"==i||"nan"==i?(null==i&&(arguments[5]="NULL"),t.style.color="black",t.style.background="red",Handsontable.renderers.TextRenderer.apply(this,arguments)):Handsontable.renderers.NumericRenderer.apply(this,arguments):"date"==s.type||"time"==s.type?(moment(new Date(i)).isValid()&&s.renderDateFormat&&(i=moment(i).format(s.renderDateFormat)),arguments[5]=i,Handsontable.renderers.TextRenderer.apply(this,arguments)):Handsontable.renderers.TextRenderer.apply(this,arguments),s.backgroundColor&&(t.style.backgroundColor=s.backgroundColor),s.color&&(t.style.color=s.color)}},{key:"countColumns",value:function(){return this.meta.length}},{key:"makeColumns",value:function(){var e=this,t=[],a=[],n={},r=0;return this.meta.forEach(function(i){n[i.name]=r,r++,t.push(i.name);var s={};switch(s.type="text",s.width=100,s.typeOriginal=i.type,s.isDark=e.isDarkTheme,i.type.includes("Int64")?(s.type="text",s.width=100):i.type.includes("Int")&&(s.width=80,s.type="numeric"),i.type){case"Date":s.width=90,s.type="date",s.dateFormat="YYYY-MM-DD";break;case"DateTime":s.width=150,s.type="time",s.timeFormat="YYYY-MM-DD HH:mm:ss";break;case"Float32":s.width=80,s.type="numeric",s.format="0.[0000000]";break;case"Float64":s.width=80,s.type="numeric",s.format="0.[0000000]";break;case"String":s.width=180}s.renderer=e._handsRenderer,s.data=i.name,a.push(s)}),{colHeaders:t,columns:a,colPositions:n}}},{key:"fecthContextMenu",value:function(){return{items:{columnformat:{name:"Column format",submenu:{items:[{name:"Reset",key:"columnformat:1",callback:function(t,a,n){e.makeFormat(this,"Reset")}},{name:"Money",key:"columnformat:2",callback:function(t,a,n){e.makeFormat(this,"Money")},disabled:function(){return!e.isFormatColl(this,"numeric")}},{name:"Human",key:"columnformat:3",callback:function(t,a,n){e.makeFormat(this,"Human")},disabled:function(){return!e.isFormatColl(this,"numeric")}},{name:"Bytes",key:"columnformat:4",callback:function(t,a,n){e.makeFormat(this,"Bytes")},disabled:function(){return!e.isFormatColl(this,"numeric")}},{name:"Percentages",key:"columnformat:5",callback:function(t,a,n){e.makeFormat(this,"Percentages")},disabled:function(){return!e.isFormatColl(this,"numeric")}},{name:"Time only",key:"columnformat:6",callback:function(t,a,n){e.makeFormat(this,"Time")},disabled:function(){return!e.isFormatColl(this,"Time")}},{name:"Date only",key:"columnformat:7",callback:function(t,a,n){e.makeFormat(this,"Date")},disabled:function(){return!e.isFormatColl(this,"Date")}},{name:"Date loc.",key:"columnformat:8",callback:function(t,a,n){e.makeFormat(this,"DateLoc")},disabled:function(){return!e.isFormatColl(this,"Date")}},{name:"Float",key:"columnformat:9",callback:function(t,a,n){e.makeFormat(this,"Float")},disabled:function(){return!e.isFormatColl(this,"numeric")}},{name:"Heatmaps",key:"columnformat:10",callback:function(t,a,n){e.makeHeatmaps(this,"Heatmaps")},disabled:function(){return!e.isFormatColl(this,"numeric")}},{name:"Negative & Positive",key:"columnformat:11",callback:function(t,a,n){e.makeHeatmaps(this,"NegaPosi")},disabled:function(){return!e.isFormatColl(this,"numeric")}}]}},style:{name:"Style",submenu:{items:[{name:"Normal",callback:function(t,a,n){e.makeStyle(this,"Normal")},key:"style:normal"},{name:"Bold",callback:function(t,a){e.makeStyle(this,"Bold")},key:"style:makebold"},{name:"Red color",callback:function(t,a){e.makeStyle(this,"Red")},key:"style:red"},{name:"Green color",callback:function(t,a){e.makeStyle(this,"Green")},key:"style:green"},{name:"Yellow color",callback:function(t,a){e.makeStyle(this,"Yellow")},key:"style:green"},{name:"Orange color",callback:function(t,a){e.makeStyle(this,"Orange")},key:"style:green"}]}},hsep1:"---------",copyTo:{name:"To Clipboard",submenu:{items:[{name:"Redmine Markdown",callback:function(t,a,n){console.info("copyToClipboard"),e.copyToClipboard(this,"Redmine")},key:"copyTo:1"},{name:"Redmine Markdown (full)",callback:function(t,a,n){console.info("copyToClipboard"),e.copyToClipboard(this,"Redmine",!0)},key:"copyTo:2"},{name:"WHERE col1 IN (val,val),col2 IN ...",callback:function(t,a,n){console.info("makeWhereIn"),e.makeWhereIn(this)},key:"copyTo:3"},{name:"Create TABLE...",callback:function(t,a,n){e.makeCreateTable(this)},key:"copyTo:4"}]}},hsep3:"---------",Transform:{name:"Transform",submenu:{items:[{name:"Transpose full table",callback:function(t,a,n){e.Transpose(this,"Transpose")},key:"Transform:1"}]}},undo:{},make_read_only:{},alignment:{},hsep4:"---------"}}}},{key:"makeSettings",value:function(){var e=this.makeColumns(),t={observeChanges:!1,observeDOMVisibility:!0,dropdownMenu:!0,manualColumnMove:!0,manualColumnResize:!0,rowHeaders:!0,colWidths:100,fillHandle:!1,stretchH:"all",customBorders:!0,isDark:this.isDarkTheme,filters:!0,columnSorting:!0,sortIndicator:!0,manualRowResize:!0,viewportColumnRenderingOffset:"auto",wordWrap:!1,autoColumnSize:{samplingRatio:23},columns:e.columns,colHeaders:e.colHeaders,contextMenu:this.fecthContextMenu(),currentRowClassName:this.isDarkTheme?"currentRowDark":"currentRowWhite",currentColClassName:"currentCol",renderAllRows:!1,visibleRows:1500};return this.Preset.sort&&this.Preset.sortOrder&&(t.columnSorting={column:e.colPositions[this.Preset.sort],sortOrder:"desc"==this.Preset.sortOrder.toLowerCase()?!1:!0}),t}}],[{key:"isDark",value:function(){return window.isDarkTheme}},{key:"makeHeatmaps",value:function(e,t){for(var a=e.getSelectedRange(),n=Math.min(a.from.col,a.to.col),r=Math.max(a.from.col,a.to.col),i="#a900e5",s="#3668ff",o=chroma.scale([i,s]),c=n;r>=c;c++){var l=e.countRows(),d=e.getDataAtCol(c),u=Math.min.apply(null,d),m=Math.max.apply(null,d);if(null!==u&&null!==m)for(var h=0;l>=h;h++){var p=parseFloat(e.getDataAtCell(h,c));if("Heatmaps"==t){var g=(p-u)/(m-u),f=o(g).hex(),b=e.getCellMeta(h,c);b&&e.setCellMeta(h,c,"backgroundColor",f)}if("NegaPosi"==t){var v=!1;0>p&&(v="#e27137"),p>0&&(v="#31b3e5");var y=e.getCellMeta(h,c);y&&v&&e.setCellMeta(h,c,"color",v)}}else console.warn("Can`t find Min&Max in column",c)}e.render()}},{key:"getSelected",value:function(e,t,a){var n=e.getSelectedRange(),r=!1;if(!n&&t||a)return{isSelection:!1,fromRow:0,toRow:e.countRows(),toCol:e.countCols(),fromCol:0};if(!n)return{isSelection:!1,fromRow:-1,toRow:-1,toCol:-1,fromCol:-1};var i=Math.min(n.from.col,n.to.col),s=Math.max(n.from.col,n.to.col),o=Math.min(n.from.row,n.to.row),c=Math.max(n.from.row,n.to.row);return{isSelection:r,fromRow:o,toRow:c,toCol:s,fromCol:i}}},{key:"makeFormat",value:function(t,a){for(var n=e.getSelected(t,!0),r=t.getSettings().columns,i=n.fromCol;i<=n.toCol;i++)switch(console.log("makeFormat for coll ="+i,a),a){case"Reset":r[i].format=!1,r[i].renderDateFormat=!1;break;case"Money":r[i].format="$0,0.00";break;case"Human":r[i].format="5a";break;case"Bytes":r[i].format="0.0b";break;case"Percentages":r[i].format="(0.00 %)";break;case"Time":r[i].renderDateFormat="HH:mm:ss";break;case"Date":r[i].renderDateFormat="YYYY-MM-DD";break;case"DateTime":r[i].renderDateFormat="YYYY-MM-DD HH:mm:ss";break;case"DateLoc":r[i].renderDateFormat="LLLL";break;case"Float":r[i].format="0.[0000000]"}t.updateSettings({columns:r}),t.render()}},{key:"isFormatColl",value:function(e,t){t=t.toLowerCase();for(var a=e.getSelectedRange(),n=Math.min(a.from.col,a.to.col),r=Math.max(a.from.col,a.to.col),i=e.getSettings().columns,s=n;r>=s;s++)if(!i[s].type.toLowerCase().includes(t))return!1;return!0}},{key:"pushToClipboardText",value:function(e){var t=document.createElement("textarea");t.style.width=0,t.style.height=0,t.style.border=0,t.style.position="absolute",t.style.top=0,document.body.append(t),t.value=e,t.focus(),t.select();try{document.execCommand("copy")}catch(a){console.log("Oops, unable to copy")}document.body.removeChild(t)}},{key:"makeCreateTable",value:function(t){for(var a=e.getSelected(t,!0),n="\nCREATE TABLE x (\n",r=[],i=t.getSettings().columns,s=a.fromCol;s<=a.toCol;s++){var o=i[s].typeOriginal;r.push(" "+t.colToProp(s)+" "+o)}n=n+r.join(",\n")+"\n)\nENGINE = TinyLog\n;;\n",console.log(n),e.pushToClipboardText(n)}},{key:"Transpose",value:function(t,a){var n=e.transpose(t.getSourceData()),r=[],i=[],s=!0,o=!1,c=void 0;try{for(var l,d=n.columns[Symbol.iterator]();!(s=(l=d.next()).done);s=!0){var u=l.value,m={};m.renderer=this._handsRenderer,m.data=u,m.type="text",m.width=100,i.push(m),r.push(u)}}catch(h){o=!0,c=h}finally{try{!s&&d["return"]&&d["return"]()}finally{if(o)throw c}}t.updateSettings({columns:i,colHeaders:r,data:n.data})}},{key:"transpose",value:function(e){var t=[],a=1,n=[];t.push(0);var r=!0,i=!1,s=void 0;try{for(var o,c=e[Symbol.iterator]();!(r=(o=c.next()).done);r=!0){var l=o.value,d=0,u=!0,m=!1,h=void 0;try{for(var p,g=Object.entries(l)[Symbol.iterator]();!(u=(p=g.next()).done);u=!0){var f=_slicedToArray(p.value,2),b=f[0],v=f[1];n[d]||(n[d]={}),1==a&&(n[d][0]=b),n[d][a]=v,d++}}catch(y){m=!0,h=y}finally{try{!u&&g["return"]&&g["return"]()}finally{if(m)throw h}}t.push(a),a++}}catch(y){i=!0,s=y}finally{try{!r&&c["return"]&&c["return"]()}finally{if(i)throw s}}return{data:n,columns:t}}},{key:"getPivotArray",value:function(e,t,a,n){for(var r={},i=[],s=[],o=0;o'+a+"":"")}},{key:"isDark",value:function(){return this.widget.isDark}},{key:"getError",value:function(){return this.errorMessage}},{key:"isExecutableCode",value:function(){return this.drawCodeObject&&this.drawCodeObject.type?this.drawCodeObject.exec:!1}},{key:"executableCode",value:function(){var e={};return this.isExecutableCode()&&(console.log(this.drawCodeObject.code),e=this.drawCodeObject.code.call(window,this.widget.data)),console.warn("executableCode:ResultFunction",e),e}},{key:"initChartByJsCode",value:function(){if(this.isExecutableCode()){var e=this.executableCode();return this.options=Object.assign(this.options,e),!0}return!1}},{key:"data",value:function(){return this.widget.data.data}},{key:"meta",value:function(){return this.widget.data.meta}},{key:"isNumericColumn",value:function(e){var t=this.getColumnPosition(e);if(!_.isUndefined(t)){var a=this.meta()[t].type;return a?(a=a.toLowerCase(),a.includes("int")||a.includes("float")?!0:!1):!1}}},{key:"isStringColumn",value:function(e){var t=this.getColumnPosition(e);if(!_.isUndefined(t)){var a=this.meta()[t].type;return a?(a=a.toLowerCase(),a.includes("string")||a.includes("enum")?!0:!1):!1}}},{key:"getColumnPosition",value:function(e){return parseInt(_.findKey(this.meta(),{name:e}))}},{key:"haveColumn",value:function(e){if(_.isNaN(e)||_.isNull(e)||_.isUndefined(e))return!1;var t=this.getColumnPosition(e);return _.isNaN(t)||_.isNull(t)||_.isUndefined(t)?!1:!0}},{key:"getColumnByType",value:function(e){var t=_.findIndex(this.meta(),{type:e});return 0>t?!1:this.getColumns(t)}},{key:"getDateTimeColumn",value:function(){return this.getColumnByType("DateTime")}},{key:"getDateColumn",value:function(){return this.getColumnByType("Date")}},{key:"getColumns",value:function(e){var t=_.map(this.meta(),"name");return _.isUndefined(e)?t:t[e]}},{key:"getFirstColumn",value:function(){return this.getColumns(0)}},{key:"getDrawCommandObject",value:function(){return this.drawCodeObject&&this.drawCodeObject.type?this.drawCodeObject.code:!1}},{key:"initDrawCodeObject",value:function initDrawCodeObject(){var drawCommand=this.widget.drawCommnads;if(!drawCommand)return[];var codeDrawText=!1;if(drawCommand&&drawCommand.code&&(codeDrawText=drawCommand.code),!codeDrawText)return[];var draw={code:!1,type:!1};if(_.isObject(codeDrawText))return draw={isok:!0,code:codeDrawText,type:"undefined"==typeof codeDrawText?"undefined":_typeof(codeDrawText),exec:!1};if("text"==drawCommand.drawtype.toLowerCase()){var obj=codeDrawText.trim();return draw={isok:!0,code:obj,type:"undefined"==typeof obj?"undefined":_typeof(obj),exec:!1}}for(var data={},columns=this.getColumns(),len=this.data().length,index=0;len>index;++index){var item=this.data()[index];for(var colPos in columns){var col=columns[colPos];data[col]||(data[col]=[]),data[col].push(item[col])}}try{var code="("+codeDrawText+")",_obj=eval(code),type="undefined"==typeof _obj?"undefined":_typeof(_obj);draw={isok:!0,code:_obj,type:type,exec:!!(_obj&&_obj.constructor&&_obj.call&&_obj.apply)}}catch(E){console.error("error eval ",codeDrawText,E)}return draw}}]),DrawBasicChart}(),DrawText=function(e){function t(e,a){_classCallCheck(this,t);var n=_possibleConstructorReturn(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));return n.type=a.toUpperCase(),n.library="text",n.widget.sizeX=0,n.widget.sizeY=0,n}return _inherits(t,e),_createClass(t,[{key:"preProcessor",value:function(){var e=this.getDrawCommandObject();this.init=this.applyText(e)}},{key:"applyText",value:function(e){return this.isDark()&&(this.widget.element[0].style.background="#404a59"),e?this.widget.element[0].innerHTML=Mustache.render(e,this.widget.data):this.widget.element[0].innerHTML="
"+JSON.stringify(this.widget.data,null,"	")+"
",!0}},{key:"onResize",value:function(){}}]),t}(DrawBasicChart),DrawPlotly=function(e){function t(e,a){_classCallCheck(this,t);var n=_possibleConstructorReturn(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));return n.type=a.toUpperCase(),n.library="plotly",n.chart=null,n.setWidgetSize(6,3),n}return _inherits(t,e),_createClass(t,[{key:"onResize",value:function(){if(this.plotly){var e=this.widget.getSizeElementHeight(),t=this.widget.getSizeElementWidth();(this.layout.height!=e||this.layout.width!=t)&&(this.layout.height=e,this.layout.width=t,this.relayout())}}},{key:"preProcessor",value:function(){return this.initChartByJsCode(),this.getError()?(console.error(this.getError()),this.chart.before("

"+this.getError()+"

"),!1):(this.isDark(),this.init=this.create(),void console.info("preProcessor",this.init))}},{key:"getElement",value:function(){return this.widget.element[0]}},{key:"relayout",value:function(){Plotly.relayout(this.getElement(),this.layout)}},{key:"editor",value:function(){console.info("editoreditoreditor")}},{key:"create",value:function(){var e=this.getDrawCommandObject();console.warn("CREATE DrawPlotly",e);var t={data:[],layout:{}};_.isObject(e)&&(_.isObject(e.trace)&&t.data.push(e.trace),_.isObject(e.trace1)&&t.data.push(e.trace1),_.isObject(e.trace2)&&t.data.push(e.trace2),_.isObject(e.trace3)&&t.data.push(e.trace3),_.isObject(e.trace4)&&t.data.push(e.trace4),_.isObject(e.layout)&&(t.layout=e.layout)),console.info(t);var a=[{x:[1,2],y:[1,2],type:"bar"}];console.log("CONS:",a),console.log("llll:",t);var n={editable:!1};this.layout=t.layout;var r=this.widget.getSizeElementHeight(),i=this.widget.getSizeElementWidth();return this.layout.height=r,this.layout.width=i,this.plotly=Plotly.plot(this.getElement(),t.data,this.layout,n),!0}},{key:"applyDarkTheme",value:function(){}}]),t}(DrawBasicChart),DrawGoogleMap=function(e){function t(e,a){_classCallCheck(this,t);var n=_possibleConstructorReturn(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));return n.type=a.toUpperCase(),n.library="gmaps",n._map=!1,n.mapOptions={zoom:4},n}return _inherits(t,e),_createClass(t,[{key:"onResize",value:function(){this._map&&google.maps.event.trigger(this._map,"resize")}},{key:"preProcessor",value:function(){this.loadGoogleMapJS(this)}},{key:"afterLoadMapProcessor",value:function(){if(this.initChartByJsCode()?this.init=!0:this.init=this.create(),this.getError())return console.error(this.getError()),this.chart.before("

"+this.getError()+"

"),!1;var e=this.getDrawCommandObject();e.raw&&(this.options=_.merge(this.options,e.raw)),this.isDark(),console.info("preProcessor",this.init,this.options)}},{key:"loadGoogleMapJS",value:function(e){if(window._sendGoogleMapLoad)return void this.afterLoadMapProcessor();window._sendGoogleMapLoad=!0,window._isGoogleMapLoaded=!1,console.info("YA_MAP>Start load map : api-maps.yandex.ru");var t=document.createElement("script");t.type="text/javascript",t.async=!0,t.src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCRQH39oyrPnfPPgADuOp0eSRsDHRUMyyY",t.charset="utf-8",t.onload=t.onreadystatechange=function(){t.readyState&&"complete"!==t.readyState&&"loaded"!==t.readyState||(t.onload=t.onreadystatechange=null,e.afterLoadMapProcessor(),window._isGoogleMapLoaded=!0)};var a=document.getElementsByTagName("script")[0];a.parentNode.insertBefore(t,a)}},{key:"getDarkStyle",value:function(){return[{featureType:"all",elementType:"labels.text.fill",stylers:[{color:"#ffffff"}]},{featureType:"all",elementType:"labels.text.stroke",stylers:[{color:"#000000"},{lightness:13}]},{featureType:"administrative",elementType:"geometry.fill",stylers:[{color:"#000000"}]},{featureType:"administrative",elementType:"geometry.stroke",stylers:[{color:"#144b53"},{lightness:14},{weight:1.4}]},{featureType:"landscape",elementType:"all",stylers:[{color:"#08304b"}]},{featureType:"poi",elementType:"geometry",stylers:[{color:"#0c4152"},{lightness:5}]},{featureType:"road.highway",elementType:"geometry.fill",stylers:[{color:"#000000"}]},{featureType:"road.highway",elementType:"geometry.stroke",stylers:[{color:"#0b434f"},{lightness:25}]},{featureType:"road.arterial",elementType:"geometry.fill",stylers:[{color:"#000000"}]},{featureType:"road.arterial",elementType:"geometry.stroke",stylers:[{color:"#0b3d51"},{lightness:16}]},{featureType:"road.local",elementType:"geometry",stylers:[{color:"#000000"}]},{featureType:"transit",elementType:"all",stylers:[{color:"#146474"}]},{featureType:"water",elementType:"all",stylers:[{color:"#021019"}]}]}},{key:"getLightStyle",value:function(){return[{featureType:"landscape",stylers:[{hue:"#FFBB00"},{saturation:43.400000000000006},{lightness:37.599999999999994},{gamma:1}]},{featureType:"road.highway",stylers:[{hue:"#FFC200"},{saturation:-61.8},{lightness:45.599999999999994},{gamma:1}]},{featureType:"road.arterial",stylers:[{hue:"#FF0300"},{saturation:-100},{lightness:51.19999999999999},{gamma:1}]},{featureType:"road.local",stylers:[{hue:"#FF0300"},{saturation:-100},{lightness:52},{gamma:1}]},{featureType:"water",stylers:[{hue:"#0078FF"},{saturation:-13.200000000000003},{lightness:2.4000000000000057},{gamma:1}]},{featureType:"poi",stylers:[{hue:"#00FF6A"},{saturation:-1.0989010989011234},{lightness:11.200000000000017},{gamma:1}]}]}},{key:"create",value:function(){console.warn("CREATE"),this._map=new google.maps.Map(this.widget.element[0],this.mapOptions);var e=this.getLightStyle();this.isDark()&&(e=this.getDarkStyle()),this._map.setOptions({styles:e});var t=this,a=this.getDrawCommandObject(),n={longitude:"longitude",latitude:"latitude",count:"count",title:"title"},r=new google.maps.LatLngBounds,i=0;a&&(n=Object.assign(n,a)),this.data().forEach(function(e,a){var s=parseInt(e[n.count]);s>i&&(i=s);var o={lat:e[n.latitude],lng:e[n.longitude]},c=!1;e[n.title]&&(c=new google.maps.InfoWindow({content:'
'+e[n.title]+"
"})),r.extend(o);var l=new google.maps.Marker({position:o,map:t._map,title:"Value:"+s});c&&l.addListener("click",function(){c.open(this._map,l)})}),this._map.fitBounds(r),this._map.panToBounds(r)}}]),t}(DrawBasicChart),DrawEcharts=function(e){function t(e,a){_classCallCheck(this,t);var n=_possibleConstructorReturn(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));return n.help="",n.type=a.toUpperCase(),n.library="echarts",n.preference={gridchart:!1,bar:!1},n.options={version:3,textStyle:{fontFamily:"Menlo"},toolbox:{show:!0,feature:{dataZoom:{yAxisIndex:"none",title:"data Zoom"},dataView:{readOnly:!1,title:"data View"},magicType:{type:["line","bar","stack","tiled"],title:{line:"line",bar:"bar",stack:"stack",tiled:"tiled"}},restore:{title:"Restore"},saveAsImage:{title:"Save as Image"}}}},n}return _inherits(t,e),_createClass(t,[{key:"onResize",value:function(){console.log("onResize Chart"),this.chart&&this.init&&this.chart.resize()}},{key:"preProcessor",value:function(){if(this.initChartByJsCode())this.init=!0;else try{this.init=this.create()}catch(e){this.setError(this.getError()+"\n\n\n"+e.name+":"+e.message+"\n"+e.stack)}if(this.getError())return console.error(this.getError()),!1;var t=this.getDrawCommandObject();t.raw&&(this.options=_.merge(this.options,t.raw)),this.isDark()&&(this.options.backgroundColor="#404a59"),this.chart.setOption(this.options),console.info("preProcessor",this.init,this.options)}},{key:"getParameterPath",value:function(){var e=this.getDrawCommandObject(),t={path:""};e&&(t=Object.assign(t,e));var a="";if(_.isString(e)?a=e:t.path&&(a=t.path),!a)return!1;for(var n=_.split(a,"."),r=0;rs;s+=1){var o=this.getColumns(s);if(!r&&this.isNumericColumn(o)){r=o;break}}t.date=n,t.value=r}if(!this.haveColumn(t.date)||!this.haveColumn(t.value))return this.setError("Not set date | value cols"),!1;var c=0,l=Number.MAX_VALUE,d=_.map(this.data(),function(e){var a=parseFloat(e[t.value]);return a&&a>c&&(c=a),a&&l>a&&(l=a),[e[t.date],a]});d=_.groupBy(d,function(e){var t=(""+e[0]).substring(0,4);return t});var u={tooltip:{position:"top"},calendar:[],series:[],visualMap:{min:l,max:c,calculable:!0,orient:"horizontal",left:"center",top:"top"}},m=60,h=0;return _.forEach(d,function(e,t){u.calendar.push({top:m,range:t,right:0,cellSize:["auto",20]}),u.series.push({type:"heatmap",coordinateSystem:"calendar",data:e,calendarIndex:h}),h+=1,m+=200}),this.options=Object.assign(u,this.options),!0}}]),t}(DrawEcharts),DrawEchartsTreemap=function(e){function t(){return _classCallCheck(this,t),_possibleConstructorReturn(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return _inherits(t,e),_createClass(t,[{key:"getLevelOption",value:function(){return[{itemStyle:{normal:{borderWidth:0,gapWidth:5}}},{itemStyle:{normal:{gapWidth:1}}},{colorSaturation:[.35,.5],itemStyle:{normal:{gapWidth:1,borderColorSaturation:.6}}}]}},{key:"buildTreeData",value:function(e,t){var a=[],n=this;return _.forEach(e,function(e,r){var i=t[r],s={};if(s.value=i.__value,_.isObject(e)){var o=n.buildTreeData(e,i);_.isArray(o)&&o.length&&(s.children=o)}s.name=r,a.push(s)}),a}},{key:"create",value:function(){var e=this.getDrawCommandObject(),t={path:"",title:"TreeMap",tooltip:"Usage",valueformat:!1};e&&(t=Object.assign(t,e));var a="";t.path&&(a=t.path),_.isString(e)&&(a=e);var n=_.split(a,"."),r=n.length;if(!r)return this.setError("Not set path"),!1;for(var i=0;r>i;i+=1)if(!this.haveColumn(n[i]))return this.setError("bad path, no column:"+n[i]),!1;if(!this.isNumericColumn(n[r-1]))return this.setError("bad column:"+n[r-1]+" must be number"),!1;var s={},o={};this.data().forEach(function(e){for(var t=e[n[r-1]],a=[],i=0;r-1>i;i+=1){a.push(e[n[i]]);var c=_.get(s,a.join("_"),0);_.set(s,a.join(".")+".__value",parseFloat(c)+parseFloat(t))}_.set(o,a.join("."),t)});var c=this.buildTreeData(o,s),l={tooltip:{trigger:"item"}},d=echarts.format;return l.series=[{type:"treemap",name:t.title,label:{show:!0,formatter:"{b}"},tooltip:{formatter:function(e){for(var a=e.value,n=[],r=e.treePathInfo,i=1;i'+d.encodeHTML(n.join("."))+"",t.tooltip+" : "+numbro(a).format(s)].join("")}},itemStyle:{normal:{borderColor:"#fff"}},levels:this.getLevelOption(),data:c}],this.options=Object.assign(l,this.options),!0}}]),t}(DrawEcharts),DrawEchartsSunkeys=function(e){function t(){return _classCallCheck(this,t),_possibleConstructorReturn(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return _inherits(t,e),_createClass(t,[{key:"create",value:function(){this.helpLink="https://tabix.io/doc/draw/Draw_Sankeys/",this.help="Default config : {path:''} or {value:'',source:'',target:''}, if empty path or not set, try auto create path, then find columns [String] : [Integer|Float] : [String] ";var e=this.getDrawCommandObject(),t={path:"",value:"value",source:"source",target:"target"};e&&(t=Object.assign(t,e));var a="";_.isString(e)?a=e:t.path?a=t.path:this.haveColumn(t.source)&&this.haveColumn(t.value)&&this.haveColumn(t.target)&&(a=t.source+"."+t.value+"."+t.target);var n=[];if(a)n=_.split(a,".");else{var r=!1,i=this.getColumns();for(var s in i){var o=i[s];this.isNumericColumn(o)&&r&&(n.push(o),r=!1),this.isStringColumn(o)&&!r&&(n.push(o),r=!0)}}if(console.log("patharr>",n),!n.length)return this.setError("The value of the variable 'path' - empty"),!1;if(!(1&n.length))return this.setError("The value of the variable 'path' must be odd"),!1;var c=[],l=[];this.data().forEach(function(e){for(var t=0;ta&&(a=s),e[t.destination.longitude]&&e[t.destination.latitude]){var o="";e[t.destination.name]&&(o=e[t.destination.name]),r.push({fromName:e[t.name],toName:o,coords:[[e[t.longitude],e[t.latitude]],[e[t.destination.longitude],e[t.destination.latitude]]]})}n.push({name:e[t.name],value:[e[t.longitude],e[t.latitude],s],label:{emphasis:{position:"right",show:!0}}})});var i=[{name:t.title,type:"effectScatter",coordinateSystem:"geo",data:n,showEffectOn:"render",rippleEffect:{brushType:"stroke"},symbolSize:function(e){return a?e[2]/a*15:e[2]/1e4},hoverAnimation:!0,label:{normal:{formatter:"{b}",position:"right",show:!0}},itemStyle:{normal:{color:"#f4e925",shadowBlur:10,shadowColor:"#333"}},zlevel:1}];if(r.length>0){var s="path://M1705.06,1318.313v-89.254l-319.9-221.799l0.073-208.063c0.521-84.662-26.629-121.796-63.961-121.491c-37.332-0.305-64.482,36.829-63.961,121.491l0.073,208.063l-319.9,221.799v89.254l330.343-157.288l12.238,241.308l-134.449,92.931l0.531,42.034l175.125-42.917l175.125,42.917l0.531-42.034l-134.449-92.931l12.238-241.308L1705.06,1318.313z"; +i.push({name:t.title,type:"lines",zlevel:1,effect:{show:!0,period:6,trailLength:.7,color:"#fff",symbolSize:3},lineStyle:{normal:{width:0,curveness:.2}},data:r}),i.push({name:t.title,type:"lines",zlevel:2,symbol:["none","arrow"],symbolSize:10,effect:{show:!0,period:6,trailLength:0,symbol:s,symbolSize:15},lineStyle:{normal:{width:1,opacity:.6,curveness:.2}},data:r})}var o={tooltip:{trigger:"item"},geo:{name:t.title,type:"map",map:"world",label:{emphasis:{show:!1}},visualMap:{show:!0,min:0,max:100,inRange:{symbolSize:[6,60]}},roam:!0,itemStyle:{normal:{areaColor:"#323c48",borderColor:"#404a59"},emphasis:{areaColor:"#2a333d"}}},series:i};return this.options=Object.assign(this.options,o),!0}}]),t}(DrawEcharts),DrawEchartsHeatmap=function(e){function t(){return _classCallCheck(this,t),_possibleConstructorReturn(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return _inherits(t,e),_createClass(t,[{key:"create",value:function(){var e=this.getParameterPath();if(!e)return this.setError("Not set path"),!1;var t={},a={},n={};this.data().forEach(function(r){_.set(t,r[e[0]],1),_.set(a,r[e[1]],1),_.set(n,r[e[0]]+"."+r[e[1]],parseFloat(r[e[2]]))});var r=[],i=_.keys(t),s=_.keys(a),o=0,c=0;_.mapKeys(t,function(e,t){_.mapKeys(a,function(e,a){var i=_.get(n,t+"."+a,"-");o>i&&(o=i),i>c&&(c=i),r.push([t,a,i])})});var l={tooltip:{position:"top"},animation:!1,grid:{height:"50%",y:"10%"},xAxis:{type:"category",data:i,splitArea:{show:!0}},yAxis:{type:"category",data:s,splitArea:{show:!0}},visualMap:{min:o,max:c,calculable:!0,orient:"horizontal",left:"center",bottom:"15%"},series:[{name:"Punch Card",type:"heatmap",data:r,label:{normal:{show:!0}},itemStyle:{emphasis:{shadowBlur:10,shadowColor:"rgba(0, 0, 0, 0.5)"}}}]};return this.options=Object.assign(l,this.options),!0}}]),t}(DrawEcharts),DrawEchartsChart=function(e){function t(){return _classCallCheck(this,t),_possibleConstructorReturn(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return _inherits(t,e),_createClass(t,[{key:"create",value:function(){console.log("DrawEchartsChart");var e=this.getDrawCommandObject(),t=this.preCreate(e),a=this.createChart(e),n={tooltip:{trigger:"axis",axisPointer:{type:"shadow"}},grid:{left:"3%",right:"4%",bottom:"3%",containLabel:!0}};return e.title&&this.applyTitle(e.title),this.applyDataZoom(),this.applyLegend(),this.options=Object.assign(a,this.options,n,t),this.postCreate(e),!0}},{key:"findDateTimeAxis",value:function(){var e=this.getDateTimeColumn();if(e)return e;var t=this.getDateColumn();return t?t:!1}},{key:"postCreate",value:function(e){return{}}},{key:"preCreate",value:function(e){return{}}},{key:"createChart",value:function(e){var t=this,a={autoAxis:!1,markLine:!0,stack:!1,path:!1,sort:!0,xAxis:!1,yAxis:!1};e&&(a=Object.assign(a,e));var n={},r=this.getColumns(),i=this.getFirstColumn(),s=i,o=this.findDateTimeAxis(),c={},l=[],d=[],u=[],m={},h=this.data();if(o&&(i=o),a.xAxis){if(!this.haveColumn(a.xAxis))throw"xAxis column not exists";s=a.xAxis}else a.sort&&(h=_.sortBy(h,i)),s=i;if(d=[{name:s,type:"category",data:[]}],a.yAxis)if(_.isString(a.yAxis)){if(!this.haveColumn(a.yAxis))throw"yAxis column not exists";n[a.yAxis]=1}else{if(!_.isArray(a.yAxis))throw"yAxis column must string or array";var p=void 0;for(p=0;pk&&!w?(_.isArray(y)||(y=[]),y.push(S),k++):this.isNumericColumn(S)&&x.push(S))}var A=h.length;for(console.log("DATA LEN",A,h),v=0;A>v;++v){var D=h[v];d[0].data.push(D[d[0].name])}for(d[0].data=_.uniq(d[0].data),console.log("xAxis[0].data.",d[0].data),v=0;A>v;++v){var R=h[v],E=function(e){var a=r[e],i=[s],o=!1;if(_.size(n)&&(o=_.isUndefined(n[a])),a!==s&&!o&&t.isNumericColumn(a)&&_.findIndex(y,a)<0){if(y)for(var c=0;c1){var q=_.groupBy(f,function(e){return Math.floor(e.median/1e3)});if(_.size(q)>1){var P=function(e){var t=q[e],n=_.map(t,"column").join(",");_.forEach(t,function(e){u[e.index].yAxisIndex=l.length,a.stack&&(u[e.index].stack=n,u[e.index].areaStyle={normal:{}})}),l.push({name:n,type:"value"})};for(var H in q)P(H)}}return l.length||(l=[{name:b,type:"value"}]),c.series=u,c.yAxis=l,c.xAxis=d,console.info("Make Chart Done : Options",c),c}}]),t}(DrawEcharts),DrawEchartsGridChart=function(e){function t(){return _classCallCheck(this,t),_possibleConstructorReturn(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return _inherits(t,e),_createClass(t,[{key:"preCreate",value:function(e){return this.preference.gridchart=!0,{}}},{key:"postCreate",value:function(e){var t=[],a=[],n=[],r=[],i=0;console.info("postCreate!!!!!!",this.options);var s=[],o=this.options.xAxis[0],c=this.options.yAxis[0];for(var l in this.options.series){l=parseInt(l);var d=this.options.series[l].name;this.options.series[l].xAxisIndex=l,this.options.series[l].yAxisIndex=i,console.log(d,this.options.series[l]),o.show=!1,o.gridIndex=l,c.gridIndex=l,c.show=!1,c.name=d,t.push({show:!0,borderWidth:0,shadowBlur:2}),n.push(_.clone(o)),a.push(_.clone(c)),r.push({textAlign:"center",text:d,textStyle:{fontSize:11,fontWeight:"normal"}}),s.push(l),i+=1}var u=Math.ceil(Math.sqrt(i));t.forEach(function(e,t){e.left=t%u/u*100+.5+"%",e.top=Math.floor(t/u)/u*100+.5+"%",e.width=1/u*100-1+"%",e.height=1/u*100-1+"%",r[t].left=parseFloat(e.left)+parseFloat(e.width)/2+"%",r[t].top=parseFloat(e.top)+"%"}),this.options.dataZoom&&this.options.dataZoom[0]&&(this.options.dataZoom[0].xAxisIndex=s),this.options.titles=r,this.options.grid=t,this.options.xAxis=n,this.options.yAxis=a}}]),t}(DrawEchartsChart),DrawEchartsBar=function(e){function t(){return _classCallCheck(this,t),_possibleConstructorReturn(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return _inherits(t,e),_createClass(t,[{key:"preCreate",value:function(e){return this.preference.bar=!0,{}}}]),t}(DrawEchartsChart),DrawD3=function(e){function t(e){_classCallCheck(this,t);var a=_possibleConstructorReturn(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));return a.library="d3",a}return _inherits(t,e),t}(DrawBasicChart),DrawC3=function(e){function t(e){_classCallCheck(this,t);var a=_possibleConstructorReturn(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));return a.library="c3",a.bindto=!1,a}return _inherits(t,e),_createClass(t,[{key:"onResize",value:function(){this.chart&&this.init}},{key:"preProcessor",value:function(){return console.log("preProcessor>c3.generate"),this.initChartByJsCode()?(console.log("c3.options>",this.options),this.bindto.className+=" c3",console.log("this.bindto.className",this.bindto.className),this.options.bindto=this.bindto,console.log("c3.options>",this.options),void(this.chart=c3.generate(this.options))):(console.error("C3.Init by code"),!1)}}]),t}(DrawBasicChart),DrawAMcharts=function(e){function t(e){_classCallCheck(this,t),console.warn("DrawAMcharts constructor");var a=_possibleConstructorReturn(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));return a.library="amchart",a}return _inherits(t,e),_createClass(t,[{key:"onResize",value:function(){this.makeLegend()}},{key:"preProcessor",value:function(){this.createChart()&&(this.init=!0),console.log("!preProcessor,done",this.init,this.options)}},{key:"createChart",value:function(){var e=this,t={},a=this.widget.data.meta,n=!1,r="",i="mm",s=[],o=0,c=[];a.forEach(function(a){if("DateTime"==a.type)n="YYYY-MM-DD JJ:NN:SS",r=a.name;else if("Date"==a.type)n="YYYY-MM-DD",i="DD",r=a.name;else{if(!r)return void(r=a.name);o+=1;var l=e.getChartGraph(a,t[a.name]);l.id="g"+o,"v1"!==l.valueAxis&&c.push(l.valueAxis),s.push(l)}});var l={theme:Widget.isDark?"dark":"light",color:Widget.isDark?"#eee":"#333",type:"serial",categoryField:r,valueAxes:[{id:"v1",axisAlpha:1,gridAlpha:.07,axisColor:Widget.isDark?"#eee":"#333",gridColor:Widget.isDark?"#eee":"#333",ignoreAxisWidth:!0}],balloon:{borderThickness:1,shadowAlpha:0},graphs:s,chartCursor:{valueLineEnabled:!0,valueLineBalloonEnabled:!0,cursorAlpha:0,zoomable:!1,valueZoomable:!0,valueLineAlpha:.5},chartScrollbar:{graph:"g1",gridAlpha:0,color:"#888888",scrollbarHeight:25,backgroundAlpha:0,selectedBackgroundAlpha:.1,selectedBackgroundColor:"#888888",graphFillAlpha:0,autoGridCount:!0,selectedGraphFillAlpha:0,graphLineAlpha:.2,graphLineColor:"#c2c2c2",selectedGraphLineColor:"#888888",selectedGraphLineAlpha:1},categoryAxis:{dashLength:1,minorGridEnabled:!0,axisColor:Widget.isDark?"#eee":"#333",gridColor:Widget.isDark?"#eee":"#333"},data:this.widget.data.data};if(l.categoryAxis.parseDates=!1,n&&(l.dataDateFormat=n,l.categoryAxis.parseDates=!0,l.categoryAxis.minPeriod=i),c){var d=0;c.forEach(function(e){d++;var t={id:e,axisAlpha:1,axisThickness:1,position:"right",ignoreAxisWidth:!0,offset:1*d};l.valueAxes.push(t)})}return this.options=l,this.init=!0,this.makeLegend(),!0}},{key:"makeLegend",value:function(){console.log("this.widget.sizeY",this.widget.sizeY),this.widget.sizeY<2?delete this.options.legend:this.options.legend={align:"center",equalWidths:!1,periodValueText:"total: [[value.sum]]",valueAlign:"left",valueText:"[[value]] ([[percents]]%)",valueWidth:100},console.warn(this.options)}},{key:"getChartGraph",value:function(e,t){var a=e.name,n=e.name,r="v1";a=a.replace(/_axis\d+/gm,"");var i=/.*_axis(\d+).*/i,s=n.match(i);s&&s[1]&&(r="v"+s[1]);var o={id:"g1",valueAxis:r,fillAlphas:.2,bullet:"round",bulletSize:8,hideBulletsCount:50,lineThickness:1,title:a,useLineColorForBulletBorder:!0,valueField:n,type:"smoothedLine",balloonText:"[[title]] [[category]]
[[value]]"};return t||(t={}),Object.assign(o,t)}}]),t}(DrawBasicChart),DataProvider=function(){function e(t,a){_classCallCheck(this,e),t.totals&&t.data&&t.data.push(t.totals),this.data=t.data,this.text=!1,this.progressQuery="",this.sort=!1,this.sortOrder=!1,t.error||angular.isObject(t.data)||(angular.isString(t.data)?this.text=t.data:this.text=angular.toJson(t.data,!0),this.text=this.text.replace(/&/g,"&").replace(//g,">")),a||(a="ch"),this.sourceType=a,this.meta=t.meta,t.query?this.query=t.query:this.query={index:0,drawCommands:!1},t.error?(this.error=t.error.replace("
","\n").replace(/&/g,"&").replace(//g,">"),this.error=this.error.replace("\\n","
")):this.error=!1,this.draw=this.query.drawCommands,this.rows=t.rows,this.position=this.query.index,this.countAll=t.countAllQuery}return e.$inject=["result","sourceType"],_createClass(e,[{key:"isText",value:function(){return this.text?!0:!1}},{key:"isError",value:function(){return this.error?!0:!1}},{key:"getError",value:function(){return this.error}},{key:"data",value:function(){return this.data}},{key:"meta",value:function(){return this.meta}},{key:"toString",value:function(){return"("+this.name+", "+this.y+")"}}],[{key:"convertArrayToDataProvider",value:function(t,a){var n={};return n.data=t,n.meta=[],n.error=!1,n.query={drawCommands:!1},n.rows=t.length,n.position=0,n.countAll=0,Object.keys(t[0]).map(function(e){return n.meta.push({name:e,type:"string"})}),new e(n,a)}}]),e}();angular.module(smi2.app.name).service("DataProvider",DataProvider),angular.module("ui.ace",[]).constant("uiAceConfig",{}).directive("uiAce",["uiAceConfig",function(e){if(angular.isUndefined(window.ace))throw new Error("ui-ace need ace to work... (o rly?)");return{restrict:"EA",link:function(t,a,n){var r=e.ace||{},i=angular.extend({},r,t.$eval(n.uiAce)),s=window.ace.edit(a[0]);console.time("Ace Load"),i.onLoad(s),console.timeEnd("Ace Load"),a.on("$destroy",function(){s.session.$stopWorker(),s.destroy()}),t.$watch(function(){return[a[0].offsetWidth,a[0].offsetHeight]},function(){s.resize(),s.renderer.updateFull()},!0)}}}]),/* * Copyright (c) 2017. Smi2 */ angular.module(smi2.app.name).directive("pivot",[function(){return{restrict:"AE",scope:{data:"=",config:"=",editMode:"="},link:function(e,t,a){var n=$.extend($.pivotUtilities.renderers);null==e.config&&(e.config={rows:[],cols:[]}),e.renderPivotTable=function(){$(t).pivot(e.data,{renderers:n,rendererName:"Table",cols:e.config.cols,rows:e.config.rows,onRefresh:function(t){var a=JSON.parse(JSON.stringify(t));delete a.aggregators,delete a.renderers,delete a.derivedAttributes,delete a.rendererOptions,delete a.localeStrings,e.config=a,e.$apply()}})},e.renderPivotUITable=function(){$(t).pivotUI(e.data)},e.$watch("scope.editMode",function(t,a){console.log("watch"+e.editMode),t&&(e.editMode?e.renderPivotUITable():e.renderPivotTable())},!0),e.renderPivotUITable()}}}]),/** @@ -649,11 +649,12 @@ document.all&&!document.addEventListener&&(document.createElement("hot-table"),d function(){angular.module("gridstack-angular",[]);var e=angular.module("gridstack-angular");e.controller("GridstackController",["$scope",function(e){var t=this;e.$watch("staticGrid",function(e,a){e=!e,e?t.gridstackHandler.enable():t.gridstackHandler.disable(),t.gridstackHandler.commit()},!0),this.init=function(e,a){return t.gridstackHandler=e.gridstack(a).data("gridstack"),t.gridstackHandler},this.removeItem=function(e){return t.gridstackHandler?t.gridstackHandler.removeWidget(e,!1):null},this.addItem=function(e){return t.gridstackHandler?(t.gridstackHandler.makeWidget(e),e):null}}])}(),function(){var e=angular.module("gridstack-angular");e.directive("gridstack",["$timeout",function(e){return{restrict:"A",controller:"GridstackController",controllerAs:"$gridstack",bindToController:{onChange:"&",onDragStart:"&",onDragStop:"&",onResizeStart:"&",onResizeStop:"&",gridstackHandler:"=?",options:"=",staticGrid:"="},link:function(t,a,n,r,i){r.init(a,r.options),a.on("change",function(a,n){e(function(){t.$apply(),r.onChange({event:a,items:n})})}),a.on("dragstart",function(e,t){r.onDragStart({event:e,ui:t})}),a.on("dragstop",function(a,n){e(function(){t.$apply(),r.onDragStop({event:a,ui:n})})}),a.on("resizestart",function(e,t){r.onResizeStart({event:e,ui:t})}),a.on("resizestop",function(a,n){e(function(){t.$apply(),r.onResizeStop({event:a,ui:n})})})}}}])}(),function(){var e=angular.module("gridstack-angular");e.directive("gridstackItem",["$timeout",function(e){return{restrict:"A",require:"^gridstack",scope:{gridstackItem:"=",onItemAdded:"&",onItemRemoved:"&",gsItemId:"=?",gsItemX:"=",gsItemY:"=",gsItemWidth:"=",gsItemHeight:"=",gsItemAutopos:"="},link:function(t,a,n,r){t.gsItemId&&a.attr("data-gs-id",t.gsItemId),a.attr("data-gs-x",t.gsItemX),a.attr("data-gs-y",t.gsItemY),a.attr("data-gs-width",t.gsItemWidth),a.attr("data-gs-height",t.gsItemHeight),a.attr("data-gs-auto-position",t.gsItemAutopos);var i=(r.addItem(a),a.data("_gridstack_node"));e(function(){t.onItemAdded({item:i})}),t.$watchGroup(["gsItemX","gsItemY","gsItemWidth","gsItemHeight"],function(){(Number(a.attr("data-gs-x"))!==t.gsItemX||Number(a.attr("data-gs-y"))!==t.gsItemY||Number(a.attr("data-gs-width"))!==t.gsItemWidth||Number(a.attr("data-gs-height"))!==t.gsItemHeight)&&r.gridstackHandler.update(a,t.gsItemX,t.gsItemY,t.gsItemWidth,t.gsItemHeight)}),t.$watch(function(){return a.attr("data-gs-id")},function(e){t.gsItemId=e}),t.$watch(function(){return a.attr("data-gs-x")},function(e){t.gsItemX=Number(e)}),t.$watch(function(){return a.attr("data-gs-y")},function(e){t.gsItemY=Number(e)}),t.$watch(function(){return a.attr("data-gs-width")},function(e){t.gsItemWidth=Number(e)}),t.$watch(function(){return a.attr("data-gs-height")},function(e){t.gsItemHeight=Number(e)}),a.bind("$destroy",function(){var e=a.data("_gridstack_node");t.onItemRemoved({item:e}),r.removeItem(a)})}}}])}(),/* * Licensed under the Apache License, Version 2.0 Copyright 2017 Igor Strykhar,Ivan Kudinov,SMI2 LLC and other contributors */ -function(e,t){function a(t,a,n){var r="";if("echarts"==t.draw.library){var i="macarons";t.isDark&&(i="dark"),t.draw.chart=echarts.init(a[0],i),r=!1}if("plotly"==t.draw.library&&(t.element=e.element('
 
'),r=!1),"c3"==t.draw.library){var s=document.createElement("div");t.draw.bindto=s,a[0].appendChild(s),r=!1}return"text"==t.draw.library&&(t.element=e.element('
 
'),r=!1),"d3"==t.draw.library&&console.info("DW:d3"),"gmaps"==t.draw.library&&(t.element=e.element('
 
'),r=!1),console.group("widget.draw.preProcessor"),console.time("widget.draw.preProcessor time took"),t.draw.preProcessor instanceof Function&&t.draw.preProcessor(),console.timeEnd("widget.draw.preProcessor time took"),console.groupEnd(),r}function n(t,n){return function(r,i,s){r.widget.type;if(console.time("drawWidget.buildLinkFunc"),r.widget.isDark=r.isdark,r.widget.preProcessor instanceof Function&&r.widget.preProcessor(),r.widget.error||r.widget.textformat||r.widget.text||r.widget.empty)return console.log("widget Have Error",r.widget.error),r.widget.error&&i.html("
"+r.widget.error+"
"),r.widget.text&&i.html("
"+r.widget.text+"
"),r.widget.empty&&i.html("NO DATA"),void i.addClass("grid-monospace");if("table"==r.widget.type&&(r.widget.element=e.element('
')),"draw"==r.widget.type){r.widget.element=!1;var o=a(r.widget,i,n);o&&(r.widget.element=e.element(o))}"pivot"==r.widget.type&&(r.widget.element=e.element('')),r.widget.element?(i.append(r.widget.element),t(r.widget.element)(r),r.widget.element.on("$destroy",r.widget.destroy(r.widget))):i.on("$destroy",r.widget.destroy(r.widget)),r.widget.postProcessor instanceof Function&&r.widget.postProcessor(),r.$watch(function(){return[i[0].offsetWidth,i[0].offsetHeight].join("x")},function(e){r.widget.scheduledResize()}),r.events={resize:function(e,t){n(function(){t.widget.scheduledResize()},300)}},n(function(){r.widget.scheduledResize()},300),console.timeEnd("drawWidget.buildLinkFunc")}}e.module(t.app.name).directive("drawWidget",["$compile","$timeout",function(e,t){return{restrict:"EA",template:'
',scope:{widget:"=widget",isdark:"=isdark"},replace:!0,link:n(e,t)}}])}(angular,smi2),angular.module("angularResizable",[]).directive("resizable",function(){function e(e){void 0===t?(t=e,setTimeout(function(){t(),t=void 0},100)):t=e}var t;return{restrict:"AE",scope:{rDirections:"=",rCenteredX:"=",rCenteredY:"=",rWidth:"=",rHeight:"=",rFlex:"=",rGrabber:"@",rDisabled:"@",rNoThrottle:"=",resizable:"@"},link:function(t,a,n){if("false"!==t.resizable){var r="flexBasis"in document.documentElement.style?"flexBasis":"webkitFlexBasis"in document.documentElement.style?"webkitFlexBasis":"msFlexPreferredSize"in document.documentElement.style?"msFlexPreferredSize":"flexBasis";t.$watch("rWidth",function(e){a[0].style[t.rFlex?r:"width"]=e!==!1?e+"px":""}),t.$watch("rHeight",function(e){a[0].style[t.rFlex?r:"height"]=e!==!1?e+"px":""}),a.addClass("resizable");var i,s,o,c,l,d=window.getComputedStyle(a[0],null),u=t.rDirections||["right"],m=t.rCenteredX?2:1,h=t.rCenteredY?2:1,p=t.rGrabber?t.rGrabber:"",g={},f=function(e){g.width=!1,g.height=!1,"x"===l?g.width=parseInt(a[0].style[t.rFlex?r:"width"]):g.height=parseInt(a[0].style[t.rFlex?r:"height"]),g.id=a[0].id,g.evt=e},b=function(e){return e.touches?e.touches[0].clientX:e.clientX},v=function(e){return e.touches?e.touches[0].clientY:e.clientY},y=function(n){function d(){t.$emit("angular-resizable.resizing",g)}var u,p="x"===l?o-b(n):o-v(n);switch(c){case"top":u=t.rFlex?r:"height",a[0].style[u]=s+p*h+"px";break;case"bottom":u=t.rFlex?r:"height",a[0].style[u]=s-p*h+"px";break;case"right":u=t.rFlex?r:"width",a[0].style[u]=i-p*m+"px";break;case"left":u=t.rFlex?r:"width",a[0].style[u]=i+p*m+"px"}f(n),t.rNoThrottle?d():e(d)},w=function C(e){f(),t.$emit("angular-resizable.resizeEnd",g),t.$apply(),document.removeEventListener("mouseup",C,!1),document.removeEventListener("mousemove",y,!1),document.removeEventListener("touchend",C,!1),document.removeEventListener("touchmove",y,!1),a.removeClass("no-transition")},k=function(e){var n={},i=!1,s=!1;n.width=parseInt(a[0].style[t.rFlex?r:"width"]),n.height=parseInt(a[0].style[t.rFlex?r:"height"]),"right"==c&&(n.width>10?(t.preState=n,i=0,s=0):(t.preState&&t.preState.width||(t.preState.width=100),s=t.preState.height,i=t.preState.width)),"bottom"==c&&(n.height>10?(t.preState=n,s=0):(t.preState&&t.preState.height||(t.preState.height=100),s=t.preState.height,i=t.preState.width)),i!==!1&&(a[0].style[t.rFlex?r:"width"]=i+"px"),s!==!1&&(a[0].style[t.rFlex?r:"height"]=s+"px"),t.$apply()},x=function(e,n){c=n,l="left"===c||"right"===c?"x":"y",o="x"===l?b(e):v(e),i=parseInt(d.getPropertyValue("width")),s=parseInt(d.getPropertyValue("height")),a.addClass("no-transition"),document.addEventListener("mouseup",w,!1),document.addEventListener("mousemove",y,!1),document.addEventListener("touchend",w,!1),document.addEventListener("touchmove",y,!1),e.stopPropagation&&e.stopPropagation(),e.preventDefault&&e.preventDefault(),e.cancelBubble=!0,e.returnValue=!1,f(e),t.$emit("angular-resizable.resizeStart",g),t.$apply()};u.forEach(function(e){var n=document.createElement("div");n.setAttribute("class","rg-"+e),n.innerHTML=p,a[0].appendChild(n),n.ondragstart=function(){return!1};var r=function(a){var n="true"===t.rDisabled;n||1!==a.which&&!a.touches||x(a,e)};n.addEventListener("dblclick",k,!1),n.addEventListener("mousedown",r,!1),n.addEventListener("touchstart",r,!1)})}}}});var csvImport=angular.module("ngCsvImport",[]);csvImport.directive("ngCsvImport",function(){return{restrict:"E",transclude:!0,replace:!0,scope:{content:"=?",header:"=?",headerVisible:"=?",separator:"=?",separatorVisible:"=?",result:"=?",encoding:"=?",encodingVisible:"=?",accept:"=?",acceptSize:"=?",acceptSizeExceedCallback:"=?",callback:"=?",mdButtonClass:"@?",mdInputClass:"@?",mdButtonTitle:"@?",mdSvgIcon:"@?",uploadButtonLabel:"="},template:function(e,t){var a=angular.isDefined(t.material),n=angular.isDefined(t.multiple);return'
Header
'+(a?'
':'')+'
Encoding
{{encoding}}
Seperator
'+(a?' {{mdButtonTitle}}':"")+"
"},link:function(e,t,a){if(e.separatorVisible=!!e.separatorVisible,e.headerVisible=!!e.headerVisible,e.acceptSize=e.acceptSize||Number.POSITIVE_INFINITY,e.material=angular.isDefined(a.material),e.multiple=angular.isDefined(a.multiple),e.multiple)throw new Error("Multiple attribute is not supported yet.");var n=angular.element(t[0].querySelector('input[type="file"]')),r=angular.element(t[0].querySelector("md-input-container"));if(e.material&&n){if(n.removeClass("ng-show"),n.addClass("ng-hide"),r){var i=angular.element(r[0].querySelector("div.md-errors-spacer"));i&&i.remove()}e.onClick=function(){n.click()}}angular.element(t[0].querySelector(".separator-input")).on("keyup",function(t){if(null!=e.content){var a={csv:e.content,header:e.header,separator:t.target.value,encoding:e.encoding};e.result=s(a),e.$apply(),"function"==typeof e.callback&&e.callback(t)}}),t.on("change",function(t){if(t.target.files&&t.target.files.length){if(t.target.files[0].size>e.acceptSize)return void("function"==typeof e.acceptSizeExceedCallback&&e.acceptSizeExceedCallback(t.target.files[0]));e.filename=t.target.files[0].name;var a=new FileReader;if(a.onload=function(a){e.$apply(function(){var n={csv:a.target.result.replace(/\r\n|\r/g,"\n"),header:e.header,separator:e.separator};e.content=n.csv,e.result=s(n),e.result.filename=e.filename,e.$$postDigest(function(){"function"==typeof e.callback&&e.callback(t)})})},"file"!==t.target.type||null==t.target.files&&null==t.srcElement.files){if(null!=e.content){var n={csv:e.content,header:!e.header,separator:e.separator};e.result=s(n),e.$$postDigest(function(){"function"==typeof e.callback&&e.callback(t)})}}else a.readAsText((t.srcElement||t.target).files[0],e.encoding)}});var s=function(e){var t=e.csv.split(new RegExp('\n(?![^"]*"(?:(?:[^"]*"){2})*[^"]*$)')),a=[],n=0,r=t[0].split(e.separator).length,i=[];e.header&&(i=t[0].split(e.separator),n=1);for(var s=n;s3e4&&(a=3e4),t.fetchQuery("SELECT now(),number,sin(number),sin(number),SHA1(toString(number)),SHA1(toString(number)) as xx from system.numbers limit "+a).then(function(t){var a="ch",n=new DataProvider(t,a);n.progressQuery="SQL";var r=new WidgetTable(n);e.w=r,e.vars.show=!0,e.vars.counter++,console.info("Load done",e.vars.counter,e.vars.show)})},e._widgetsx=[],e.removeResult=function(t,a,n){n.stopPropagation(),delete e.listDashboards[a]},e.inits=function(){e.listDashboards={}},e.inits(),e.moveWidget=function(){e.widgets[0].x=1,e.widgets[0].width=2,e.widgets[0].height=2},e.removeWidget=function(t){var a=e.widgets.indexOf(t);e.widgets.splice(a,1)},e.onChange=function(e,t){console.log("onChange event: "+e+" items:"+t)},e.onDragStart=function(e,t){console.log("onDragStart event: "+e+" ui:"+t)},e.onDragStop=function(e,t){console.log("onDragStop event: "+e+" ui:"+t)},e.onResizeStart=function(e,t){console.log("onResizeStart event: "+e+" ui:"+t)},e.onResizeStop=function(e,t){console.log("onResizeStop ",t.size)},e.onItemAdded=function(e){console.log("onItemAdded item: "+e)},e.onItemRemoved=function(e){console.log("onItemRemoved item: "+e)}}e.module(t.app.name).controller("DashController",a),a.$inject=["$scope","API","ThemeService","$interval","localStorageService","$mdDialog","$window","hotRegisterer"]}(angular,smi2),ace.define("ace/theme/dracula",["require","exports","module","ace/lib/dom"],function(e,t,a){t.isDark=!0,t.cssClass="ace-dracula",t.cssText="ace-dracula .ace_gutter {background: #282a36;color: rgb(144,145,148)}.ace-dracula .ace_print-margin {width: 1px;background: #e8e8e8}.ace-dracula {background-color: #282a36;color: #f8f8f2}.ace-dracula .ace_cursor {color: #f8f8f0}.ace-dracula .ace_marker-layer .ace_selection {background: #44475a}.ace-dracula.ace_multiselect .ace_selection.ace_start {box-shadow: 0 0 3px 0px #282a36;border-radius: 2px}.ace-dracula .ace_marker-layer .ace_step {background: rgb(198, 219, 174)}.ace-dracula .ace_marker-layer .ace_bracket {margin: -1px 0 0 -1px;border: 1px solid #3B3A32}.ace-dracula .ace_marker-layer .ace_active-line {background: #44475a}.ace-dracula .ace_gutter-active-line {background-color: #44475a}.ace-dracula .ace_marker-layer .ace_selected-word {border: 1px solid #44475a}.ace-dracula .ace_fold {background-color: #50fa7b;border-color: #f8f8f2}.ace-dracula .ace_keyword {color: #ff79c6}.ace-dracula .ace_constant.ace_language {color: #bd93f9}.ace-dracula .ace_constant.ace_numeric {color: #bd93f9}.ace-dracula .ace_constant.ace_character {color: #bd93f9}.ace-dracula .ace_constant.ace_character.ace_escape {color: #ff79c6}.ace-dracula .ace_constant.ace_other {color: #bd93f9}.ace-dracula .ace_support.ace_function {color: #8be9fd}.ace-dracula .ace_support.ace_constant {color: #6be5fd}.ace-dracula .ace_support.ace_class {font-style: italic;color: #66d9ef}.ace-dracula .ace_support.ace_type {font-style: italic;color: #66d9ef}.ace-dracula .ace_storage {color: #ff79c6}.ace-dracula .ace_storage.ace_type {font-style: italic;color: #8be9fd}.ace-dracula .ace_invalid {color: #F8F8F0;background-color: #ff79c6}.ace-dracula .ace_invalid.ace_deprecated {color: #F8F8F0;background-color: #bd93f9}.ace-dracula .ace_string {color: #f1fa8c}.ace-dracula .ace_comment {color: #6272a4}.ace-dracula .ace_variable {color: #50fa7b}.ace-dracula .ace_variable.ace_parameter {font-style: italic;color: #ffb86c}.ace-dracula .ace_entity.ace_other.ace_attribute-name {color: #50fa7b}.ace-dracula .ace_entity.ace_name.ace_function {color: #50fa7b}.ace-dracula .ace_entity.ace_name.ace_tag {color: #ff79c6}";var n=e("../lib/dom");n.importCssString(t.cssText,t.cssClass)}),ace.define("ace/mode/clickhouse",["require","exports","module","ace/lib/oop","ace/mode/text","ace/token_iterator","ace/mode/folding","ace/mode/clickhouse_FoldMode","ace/mode/clickhouse_highlight_rules"],function(e,t){var a=e("../lib/oop"),n=e("./text").Mode,r=e("./clickhouse_highlight_rules").ClickhouseHighlightRules,i=e("./clickhouse_FoldMode").FoldMode,s=e("./matching_brace_outdent").MatchingBraceOutdent,o=e("./behaviour/cstyle").CstyleBehaviour,c=function(){this.foldingRules=new i,this.$outdent=new s,this.$behaviour=new o,this.HighlightRules=r};a.inherits(c,n),function(){var t=this;this.lineCommentStart="--",this.getHighlightRule=function(){return t.session.$mode.$highlightRules},this.getCompletions=function(e,t,a,n){return t.$mode.$highlightRules.completions},this.$id="ace/mode/clickhouse",this.checkOutdent=function(e,t,a){return this.$outdent.checkOutdent(t,a)},this.autoOutdent=function(e,t,a){this.$outdent.autoOutdent(t,a)},this.findTokens=function(t,a,n){t=t.replace(/^(\r\n|\n|\r)/gm,"").replace(/(\r\n|\n|\r)$/gm,"");for(var r=e("ace/token_iterator").TokenIterator,i=e("ace/edit_session").EditSession,s=new i(t,this),o=new r(s,0,0),c=o.getCurrentToken(),l=[];c;){var d=c;if(d.row=o.getCurrentTokenRow(),d.col=o.getCurrentTokenColumn(),d.type==a&&(l.push(d),n))return d.value=d.value.toLowerCase(),d;c=o.stepForward()}return l},this.trim=function(e,t){return t!==!0&&"string"==typeof t&&t.length>0&&(e=e.replace("^("+t+")"," ").replace(t+"$"," "),e=e.replace(new RegExp("^"+t+"|"+t+"$","g")," ")),e},this.collapseAll=function(e){for(var t=e,a=t.foldWidgets,n=t.getLength(),r=0,i=r;n>i;i++)if(null==a[i]&&(a[i]=t.getFoldWidget(i)),"start"==a[i]){var s=t.getFoldWidgetRange(i);if(s&&s.end.row<=n&&s.start.row>=r){i=s.end.row;try{var o=t.addFold("...",s);o&&(o.collapseChildren=depth)}catch(t){}}}},this.replaceVars=function(e,t){var a={},n=this.fetchTokens(e);if(console.warn("Find tokens",n,t),n.vars.length>0)for(var r in n.vars){var i=n.vars[r],s=i;i=i.indexOf("{")>-1?i.replace("{","").replace("}",""):i.replace("$","").replace("@","").replace(":","");for(var o in t){var c=t[o];c.name.toLowerCase()==i.toLowerCase()&&(console.info(c.name.toLowerCase(),"==",i.toLowerCase()),e=e.replace(s,c.value))}}return{sql:e,tokens:n,vars:a}},this.fetchTokens=function(t){var a={groupby:[],where:[],vars:[],limit:-1},n=e("ace/token_iterator").TokenIterator,r=e("ace/edit_session").EditSession,i=new r(t,this);i.bgTokenizer.start(0);for(var s=new n(i,0,0),o=s.getCurrentToken();o;){var c=o;if(c.row=s.getCurrentTokenRow(),c.col=s.getCurrentTokenColumn(),"variable.language"==c.type&&c.value&&a.vars.push(c.value),"keyword"==c.type&&c.value.toLowerCase().includes("limit")!==!1){var l=c.value.toLowerCase().match(/LIMIT\W+(\d+)\W*\,\W*(\d+)/i);l||(l=c.value.toLowerCase().match(/LIMIT\W+(\d+)/i)),l[0]&&l[1]&&l[2]?a.limit={from:l[1],to:l[2]}:l[0]&&l[1]&&(a.limit={from:l[1],to:!1})}o=s.stepForward()}return console.info("Parse & Find tokens result",a),a},this.splitByTokens=function(t,a,n){var r=e("ace/token_iterator").TokenIterator,i=e("ace/edit_session").EditSession,s=e("ace/range").Range,o=new i(t,this);o.bgTokenizer.start(0);var c=new r(o,0,0),l=c.getCurrentToken();if(_.isUndefined(l)){var d=0;do d++,c=new r(o,d,0),l=c.getCurrentToken();while(100>d&&!l)}for(var u=[],m=0,h=0,p=!1,g=void 0,f=void 0;l;){var b=l;if(b.row=c.getCurrentTokenRow(),b.col=c.getCurrentTokenColumn(),b.type==a&&(n!==!0&&b.value==n||n===!0)){var v=0;n instanceof String&&(v=n.length),g=new s(m,h,b.row,b.col+v),f=o.getTextRange(g),m=b.row,h=b.col+v,f=this.trim(f,b.value),f.length>2&&("string"==typeof p&&(f=this.trim(f,p)),u.push({sql:f,range:g,keyword:p}),p=b.value)}l=c.stepForward()}return g=new s(m,h,Number.MAX_VALUE,Number.MAX_VALUE),f=o.getTextRange(g),f=this.trim(f,n),"string"==typeof p&&(f=this.trim(f,p)),f.length>2&&u.push({sql:f,range:g,keyword:p}),u}}.call(c.prototype),t.Mode=c}),ace.define("ace/ext/whitespace",["require","exports","module","ace/lib/lang"],function(e,t,a){var n=e("../lib/lang");t.$detectIndentation=function(e,t){function a(e){for(var t=0,a=e;ac;c++){var l=e[c];if(/^\s*[^*+\-\s]/.test(l)){if(" "==l[0])i++,s=-Number.MAX_VALUE;else{var d=l.match(/^ */)[0].length;if(d&&" "!=l[d]){var u=d-s;!(u>0)||s%u||d%u||(r[u]=(r[u]||0)+1),n[d]=(n[d]||0)+1}s=d}for(;o>c&&"\\"==l[l.length-1];)l=e[c++]}}for(var m=r.reduce(function(e,t){return e+t},0),h={score:0,length:0},p=0,c=1;12>c;c++){var g=a(c);1==c?(p=g,g=n[1]?.9:.8,n.length||(g=0)):g/=p,r[c]&&(g+=r[c]/m),g>h.score&&(h={score:g,length:c})}if(h.score&&h.score>1.4)var f=h.length;return i>p+1?((1==f||i/4>p||h.score<1.8)&&(f=void 0),{ch:" ",length:f}):p>i+1?{ch:" ",length:f}:void 0},t.detectIndentation=function(e){var a=e.getLines(0,1e3),n=t.$detectIndentation(a)||{};return n.ch&&e.setUseSoftTabs(" "==n.ch),n.length&&e.setTabSize(n.length),n},t.trimTrailingSpace=function(e,t){for(var a=e.getDocument(),n=a.getAllLines(),r=t?-1:0,i=0,s=n.length;s>i;i++){var o=n[i],c=o.search(/\s+$/);c>r&&a.removeInLine(i,c,o.length)}},t.convertIndentation=function(e,t,a){var r=e.getTabString()[0],i=e.getTabSize();a||(a=i),t||(t=r);for(var s=" "==t?t:n.stringRepeat(t,a),o=e.doc,c=o.getAllLines(),l={},d={},u=0,m=c.length;m>u;u++){var h=c[u],p=h.match(/^\s*/)[0];if(p){var g=e.$getStringScreenWidth(p)[0],f=Math.floor(g/i),b=g%i,v=l[f]||(l[f]=n.stringRepeat(s,f));v+=d[b]||(d[b]=n.stringRepeat(" ",b)),v!=p&&(o.removeInLine(u,0,p.length),o.insertInLine({row:u,column:0},v))}}e.setTabSize(a),e.setUseSoftTabs(" "==t)},t.$parseStringArg=function(e){var t={};/t/.test(e)?t.ch=" ":/s/.test(e)&&(t.ch=" ");var a=e.match(/\d+/);return a&&(t.length=parseInt(a[0],10)),t},t.$parseArg=function(e){return e?"string"==typeof e?t.$parseStringArg(e):"string"==typeof e.text?t.$parseStringArg(e.text):e:{}},t.commands=[{name:"detectIndentation",exec:function(e){t.detectIndentation(e.session)}},{name:"trimTrailingSpace",exec:function(e){t.trimTrailingSpace(e.session)}},{name:"convertIndentation",exec:function(e,a){var n=t.$parseArg(a);t.convertIndentation(e.session,n.ch,n.length)}},{name:"setIndentation",exec:function(e,a){var n=t.$parseArg(a);n.length&&e.session.setTabSize(n.length),n.ch&&e.session.setUseSoftTabs(" "==n.ch)}}]}),function(){ace.require(["ace/ext/whitespace"],function(){})}(),ace.define("ace/ext/statusbar",["require","exports","module","ace/lib/dom","ace/lib/lang"],function(e,t,a){var n=e("ace/lib/dom"),r=e("ace/lib/lang"),i=function(e,t){this.element=n.createElement("div"),this.element.className="ace_status-indicator",this.element.style.cssText="display: inline-block;",t.appendChild(this.element);var a=r.delayedCall(function(){this.updateStatus(e)}.bind(this)).schedule.bind(null,100);e.on("changeStatus",a),e.on("changeSelection",a),e.on("keyboardActivity",a)};(function(){this.updateStatus=function(e){function t(e,t){e&&a.push(e,t||"|")}var a=[];t(e.keyBinding.getStatusText(e)),e.commands.recording&&t("REC");var n=e.selection,r=n.lead;if(!n.isEmpty()){var i=e.getSelectionRange();t("("+(i.end.row-i.start.row)+":"+(i.end.column-i.start.column)+")"," ")}t(r.row+":"+r.column," "),n.rangeCount&&t("["+n.rangeCount+"]"," "),a.pop(),this.element.textContent=a.join("")}}).call(i.prototype),t.StatusBar=i}),function(){ace.require(["ace/ext/statusbar"],function(){})}(),ace.define("ace/ext/spellcheck",["require","exports","module","ace/lib/event","ace/editor","ace/config"],function(e,t,a){var n=e("../lib/event");t.contextMenuHandler=function(e){var t=e.target,a=t.textInput.getElement();if(t.selection.isEmpty()){var r=t.getCursorPosition(),i=t.session.getWordRange(r.row,r.column),s=t.session.getTextRange(i);if(t.session.tokenRe.lastIndex=0,t.session.tokenRe.test(s)){var o="",c=s+" "+o;a.value=c,a.setSelectionRange(s.length,s.length+1),a.setSelectionRange(0,0),a.setSelectionRange(0,s.length);var l=!1;n.addListener(a,"keydown",function d(){n.removeListener(a,"keydown",d),l=!0}),t.textInput.setInputHandler(function(e){if(console.log(e,c,a.selectionStart,a.selectionEnd),e==c)return"";if(0===e.lastIndexOf(c,0))return e.slice(c.length);if(e.substr(a.selectionEnd)==c)return e.slice(0,-c.length);if(e.slice(-2)==o){var n=e.slice(0,-2);if(" "==n.slice(-1))return l?n.substring(0,a.selectionEnd):(n=n.slice(0,-1),t.session.replace(i,n),"")}return e})}}};var r=e("../editor").Editor;e("../config").defineOptions(r.prototype,"editor",{spellcheck:{set:function(e){var a=this.textInput.getElement();a.spellcheck=!!e,e?this.on("nativecontextmenu",t.contextMenuHandler):this.removeListener("nativecontextmenu",t.contextMenuHandler)},value:!0}})}),function(){ace.require(["ace/ext/spellcheck"],function(){})}(),ace.define("ace/ext/menu_tools/element_generator",["require","exports","module"],function(e,t,a){a.exports.createOption=function(e){var t,a=document.createElement("option");for(t in e)e.hasOwnProperty(t)&&("selected"===t?a.setAttribute(t,e[t]):a[t]=e[t]);return a},a.exports.createCheckbox=function(e,t,a){var n=document.createElement("input");return n.setAttribute("type","checkbox"),n.setAttribute("id",e),n.setAttribute("name",e),n.setAttribute("value",t),n.setAttribute("class",a),t&&n.setAttribute("checked","checked"),n},a.exports.createInput=function(e,t,a){var n=document.createElement("input");return n.setAttribute("type","text"),n.setAttribute("id",e),n.setAttribute("name",e),n.setAttribute("value",t),n.setAttribute("class",a),n},a.exports.createLabel=function(e,t){var a=document.createElement("label");return a.setAttribute("for",t),a.textContent=e,a},a.exports.createSelection=function(e,t,n){var r=document.createElement("select");return r.setAttribute("id",e),r.setAttribute("name",e),r.setAttribute("class",n),t.forEach(function(e){r.appendChild(a.exports.createOption(e))}),r}}),ace.define("ace/ext/modelist",["require","exports","module"],function(e,t,a){function n(e){for(var t=c.text,a=e.split(/[\/\\]/).pop(),n=0;n +/g,">"),u=function(e,t,a){var r=n.createElement("div");r.innerHTML=d,this.element=r.firstChild,this.setSession=this.setSession.bind(this),this.$init(),this.setEditor(e)};(function(){this.setEditor=function(e){e.searchBox=this,e.renderer.scroller.appendChild(this.element),this.editor=e},this.setSession=function(e){this.searchRange=null,this.$syncOptions(!0)},this.$initElements=function(e){this.searchBox=e.querySelector(".ace_search_form"),this.replaceBox=e.querySelector(".ace_replace_form"),this.searchOption=e.querySelector("[action=searchInSelection]"),this.replaceOption=e.querySelector("[action=toggleReplace]"),this.regExpOption=e.querySelector("[action=toggleRegexpMode]"),this.caseSensitiveOption=e.querySelector("[action=toggleCaseSensitive]"),this.wholeWordOption=e.querySelector("[action=toggleWholeWords]"),this.searchInput=this.searchBox.querySelector(".ace_search_field"),this.replaceInput=this.replaceBox.querySelector(".ace_search_field"),this.searchCounter=e.querySelector(".ace_search_counter")},this.$init=function(){var e=this.element;this.$initElements(e);var t=this;i.addListener(e,"mousedown",function(e){setTimeout(function(){t.activeInput.focus()},0),i.stopPropagation(e)}),i.addListener(e,"click",function(e){var a=e.target||e.srcElement,n=a.getAttribute("action");n&&t[n]?t[n]():t.$searchBarKb.commands[n]&&t.$searchBarKb.commands[n].exec(t),i.stopPropagation(e)}),i.addCommandKeyListener(e,function(e,a,n){var r=c.keyCodeToString(n),s=t.$searchBarKb.findKeyCommand(a,r);s&&s.exec&&(s.exec(t),i.stopEvent(e))}),this.$onChange=r.delayedCall(function(){t.find(!1,!1)}),i.addListener(this.searchInput,"input",function(){t.$onChange.schedule(20)}),i.addListener(this.searchInput,"focus",function(){t.activeInput=t.searchInput,t.searchInput.value&&t.highlight()}),i.addListener(this.replaceInput,"focus",function(){t.activeInput=t.replaceInput,t.searchInput.value&&t.highlight()})},this.$closeSearchBarKb=new o([{bindKey:"Esc",name:"closeSearchBar",exec:function(e){e.searchBox.hide()}}]),this.$searchBarKb=new o,this.$searchBarKb.bindKeys({"Ctrl-f|Command-f":function(e){var t=e.isReplace=!e.isReplace;e.replaceBox.style.display=t?"":"none",e.replaceOption.checked=!1,e.$syncOptions(),e.searchInput.focus()},"Ctrl-H|Command-Option-F":function(e){e.replaceOption.checked=!0,e.$syncOptions(),e.replaceInput.focus()},"Ctrl-G|Command-G":function(e){e.findNext()},"Ctrl-Shift-G|Command-Shift-G":function(e){e.findPrev()},esc:function(e){setTimeout(function(){e.hide()})},Return:function(e){e.activeInput==e.replaceInput&&e.replace(),e.findNext()},"Shift-Return":function(e){e.activeInput==e.replaceInput&&e.replace(),e.findPrev()},"Alt-Return":function(e){e.activeInput==e.replaceInput&&e.replaceAll(),e.findAll()},Tab:function(e){(e.activeInput==e.replaceInput?e.searchInput:e.replaceInput).focus()}}),this.$searchBarKb.addCommands([{name:"toggleRegexpMode",bindKey:{win:"Alt-R|Alt-/",mac:"Ctrl-Alt-R|Ctrl-Alt-/"},exec:function(e){e.regExpOption.checked=!e.regExpOption.checked,e.$syncOptions()}},{name:"toggleCaseSensitive",bindKey:{win:"Alt-C|Alt-I",mac:"Ctrl-Alt-R|Ctrl-Alt-I"},exec:function(e){e.caseSensitiveOption.checked=!e.caseSensitiveOption.checked,e.$syncOptions()}},{name:"toggleWholeWords",bindKey:{win:"Alt-B|Alt-W",mac:"Ctrl-Alt-B|Ctrl-Alt-W"},exec:function(e){e.wholeWordOption.checked=!e.wholeWordOption.checked,e.$syncOptions()}},{name:"toggleReplace",exec:function(e){e.replaceOption.checked=!e.replaceOption.checked,e.$syncOptions()}},{name:"searchInSelection",exec:function(e){e.searchOption.checked=!e.searchRange,e.setSearchRange(e.searchOption.checked&&e.editor.getSelectionRange()),e.$syncOptions()}}]),this.setSearchRange=function(e){this.searchRange=e,e?this.searchRangeMarker=this.editor.session.addMarker(e,"ace_active-line"):this.searchRangeMarker&&(this.editor.session.removeMarker(this.searchRangeMarker),this.searchRangeMarker=null)},this.$syncOptions=function(e){n.setCssClass(this.replaceOption,"checked",this.searchRange),n.setCssClass(this.searchOption,"checked",this.searchOption.checked),this.replaceOption.textContent=this.replaceOption.checked?"-":"+",n.setCssClass(this.regExpOption,"checked",this.regExpOption.checked),n.setCssClass(this.wholeWordOption,"checked",this.wholeWordOption.checked),n.setCssClass(this.caseSensitiveOption,"checked",this.caseSensitiveOption.checked),this.replaceBox.style.display=this.replaceOption.checked?"":"none",this.find(!1,!1,e)},this.highlight=function(e){this.editor.session.highlight(e||this.editor.$search.$options.re),this.editor.renderer.updateBackMarkers()},this.find=function(e,t,a){var r=this.editor.find(this.searchInput.value,{skipCurrent:e,backwards:t,wrap:!0,regExp:this.regExpOption.checked,caseSensitive:this.caseSensitiveOption.checked,wholeWord:this.wholeWordOption.checked,preventScroll:a,range:this.searchRange}),i=!r&&this.searchInput.value;n.setCssClass(this.searchBox,"ace_nomatch",i),this.editor._emit("findSearchBox",{match:!i}),this.highlight(),this.updateCounter()},this.updateCounter=function(){var e=this.editor,t=e.$search.$options.re,a=0,n=0;if(t){var r=this.searchRange?e.session.getTextRange(this.searchRange):e.getValue(),i=e.session.doc.positionToIndex(e.selection.anchor);this.searchRange&&(i-=e.session.doc.positionToIndex(this.searchRange.start));for(var s,o=t.lastIndex=0;(s=t.exec(r))&&(a++,o=s.index,i>=o&&n++,!(a>l))&&(s[0]||(t.lastIndex=o+=1,!(o>=r.length))););}this.searchCounter.textContent=n+" of "+(a>l?l+"+":a)},this.findNext=function(){this.find(!0,!1)},this.findPrev=function(){this.find(!0,!0)},this.findAll=function(){var e=this.editor.findAll(this.searchInput.value,{regExp:this.regExpOption.checked,caseSensitive:this.caseSensitiveOption.checked,wholeWord:this.wholeWordOption.checked}),t=!e&&this.searchInput.value;n.setCssClass(this.searchBox,"ace_nomatch",t),this.editor._emit("findSearchBox",{match:!t}),this.highlight(),this.hide()},this.replace=function(){this.editor.getReadOnly()||this.editor.replace(this.replaceInput.value)},this.replaceAndFindNext=function(){this.editor.getReadOnly()||(this.editor.replace(this.replaceInput.value),this.findNext())},this.replaceAll=function(){this.editor.getReadOnly()||this.editor.replaceAll(this.replaceInput.value)},this.hide=function(){this.active=!1,this.setSearchRange(null),this.editor.off("changeSession",this.setSession),this.element.style.display="none",this.editor.keyBinding.removeKeyboardHandler(this.$closeSearchBarKb),this.editor.focus()},this.show=function(e,t){this.active=!0,this.editor.on("changeSession",this.setSession),this.element.style.display="",this.replaceOption.checked=t,e&&(this.searchInput.value=e),this.searchInput.focus(),this.searchInput.select(),this.editor.keyBinding.addKeyboardHandler(this.$closeSearchBarKb),this.$syncOptions(!0)},this.isFocused=function(){var e=document.activeElement;return e==this.searchInput||e==this.replaceInput}}).call(u.prototype),t.SearchBox=u,t.Search=function(e,t){var a=e.searchBox||new u(e);a.show(e.session.getTextRange(),t)}}),function(){ace.require(["ace/ext/searchbox"],function(){})}(),ace.define("ace/snippets",["require","exports","module","ace/lib/oop","ace/lib/event_emitter","ace/lib/lang","ace/range","ace/anchor","ace/keyboard/hash_handler","ace/tokenizer","ace/lib/dom","ace/editor"],function(e,t,a){var n=e("./lib/oop"),r=e("./lib/event_emitter").EventEmitter,i=e("./lib/lang"),s=e("./range").Range,o=e("./anchor").Anchor,c=e("./keyboard/hash_handler").HashHandler,l=e("./tokenizer").Tokenizer,d=s.comparePoints,u=function(){this.snippetMap={},this.snippetNameMap={}};(function(){n.implement(this,r),this.getTokenizer=function(){function e(e,t,a){return e=e.substr(1),/^\d+$/.test(e)&&!a.inFormatString?[{tabstopId:parseInt(e,10)}]:[{text:e}]}function t(e){return"(?:[^\\\\"+e+"]|\\\\.)"}return u.$tokenizer=new l({start:[{regex:/:/,onMatch:function(e,t,a){return a.length&&a[0].expectIf?(a[0].expectIf=!1,a[0].elseBranch=a[0],[a[0]]):":"}},{regex:/\\./,onMatch:function(e,t,a){var n=e[1];return"}"==n&&a.length?e=n:-1!="`$\\".indexOf(n)?e=n:a.inFormatString&&("n"==n?e="\n":"t"==n?e="\n":-1!="ulULE".indexOf(n)&&(e={changeCase:n,local:n>"a"})),[e]}},{regex:/}/,onMatch:function(e,t,a){return[a.length?a.shift():e]}},{regex:/\$(?:\d+|\w+)/,onMatch:e},{regex:/\$\{[\dA-Z_a-z]+/,onMatch:function(t,a,n){var r=e(t.substr(1),a,n);return n.unshift(r[0]),r},next:"snippetVar"},{regex:/\n/,token:"newline",merge:!1}],snippetVar:[{regex:"\\|"+t("\\|")+"*\\|",onMatch:function(e,t,a){a[0].choices=e.slice(1,-1).split(",")},next:"start"},{regex:"/("+t("/")+"+)/(?:("+t("/")+"*)/)(\\w*):?",onMatch:function(e,t,a){var n=a[0];return n.fmtString=e,e=this.splitRegex.exec(e),n.guard=e[1],n.fmt=e[2],n.flag=e[3],""},next:"start"},{regex:"`"+t("`")+"*`",onMatch:function(e,t,a){return a[0].code=e.splice(1,-1),""},next:"start"},{regex:"\\?",onMatch:function(e,t,a){a[0]&&(a[0].expectIf=!0)},next:"start"},{regex:"([^:}\\\\]|\\\\.)*:?",token:"",next:"start"}],formatString:[{regex:"/("+t("/")+"+)/",token:"regex"},{regex:"",onMatch:function(e,t,a){a.inFormatString=!0},next:"start"}]}),u.prototype.getTokenizer=function(){return u.$tokenizer},u.$tokenizer},this.tokenizeTmSnippet=function(e,t){return this.getTokenizer().getLineTokens(e,t).tokens.map(function(e){return e.value||e})},this.$getDefaultValue=function(e,t){if(/^[A-Z]\d+$/.test(t)){var a=t.substr(1);return(this.variables[t[0]+"__"]||{})[a]}if(/^\d+$/.test(t))return(this.variables.__||{})[t];if(t=t.replace(/^TM_/,""),e){var n=e.session;switch(t){case"CURRENT_WORD":var r=n.getWordRange();case"SELECTION":case"SELECTED_TEXT":return n.getTextRange(r);case"CURRENT_LINE":return n.getLine(e.getCursorPosition().row);case"PREV_LINE":return n.getLine(e.getCursorPosition().row-1);case"LINE_INDEX":return e.getCursorPosition().column;case"LINE_NUMBER":return e.getCursorPosition().row+1;case"SOFT_TABS":return n.getUseSoftTabs()?"YES":"NO";case"TAB_SIZE":return n.getTabSize();case"FILENAME":case"FILEPATH":return"";case"FULLNAME":return"Ace"}}},this.variables={},this.getVariableValue=function(e,t){return this.variables.hasOwnProperty(t)?this.variables[t](e,t)||"":this.$getDefaultValue(e,t)||""},this.tmStrFormat=function(e,t,a){var n=t.flag||"",r=t.guard;r=new RegExp(r,n.replace(/[^gi]/,""));var i=this.tokenizeTmSnippet(t.fmt,"formatString"),s=this,o=e.replace(r,function(){s.variables.__=arguments;for(var e=s.resolveVariables(i,a),t="E",n=0;n1?(v=t[t.length-1].length,b+=t.length-1):v+=e.length,y+=e}else e.start?e.end={row:b,column:v}:e.start={row:b,column:v}});var w=e.getSelectionRange(),k=e.session.replace(w,y),x=new m(e),C=e.inVirtualSelectionMode&&e.selection.index;x.addTabstops(c,w.start,k,C)},this.insertSnippet=function(e,t){var a=this;return e.inVirtualSelectionMode?a.insertSnippetForSelection(e,t):(e.forEachSelection(function(){a.insertSnippetForSelection(e,t)},null,{keepOrder:!0}),void(e.tabstopManager&&e.tabstopManager.tabNext()))},this.$getScope=function(e){var t=e.session.$mode.$id||"";if(t=t.split("/").pop(),"html"===t||"php"===t){"php"!==t||e.session.$mode.inlinePhp||(t="html");var a=e.getCursorPosition(),n=e.session.getState(a.row);"object"===("undefined"==typeof n?"undefined":_typeof(n))&&(n=n[0]),n.substring&&("js-"==n.substring(0,3)?t="javascript":"css-"==n.substring(0,4)?t="css":"php-"==n.substring(0,4)&&(t="php"))}return t},this.getActiveScopes=function(e){var t=this.$getScope(e),a=[t],n=this.snippetMap;return n[t]&&n[t].includeScopes&&a.push.apply(a,n[t].includeScopes),a.push("_"),a},this.expandWithTab=function(e,t){var a=this,n=e.forEachSelection(function(){return a.expandSnippetForSelection(e,t)},null,{keepOrder:!0});return n&&e.tabstopManager&&e.tabstopManager.tabNext(),n},this.expandSnippetForSelection=function(e,t){var a,n=e.getCursorPosition(),r=e.session.getLine(n.row),i=r.substring(0,n.column),s=r.substr(n.column),o=this.snippetMap;return this.getActiveScopes(e).some(function(e){var t=o[e];return t&&(a=this.findMatchingSnippet(t,i,s)),!!a},this),a?t&&t.dryRun?!0:(e.session.doc.removeInLine(n.row,n.column-a.replaceBefore.length,n.column+a.replaceAfter.length),this.variables.M__=a.matchBefore,this.variables.T__=a.matchAfter,this.insertSnippetForSelection(e,a.content),this.variables.M__=this.variables.T__=null,!0):!1},this.findMatchingSnippet=function(e,t,a){for(var n=e.length;n--;){var r=e[n];if((!r.startRe||r.startRe.test(t))&&(!r.endRe||r.endRe.test(a))&&(r.startRe||r.endRe))return r.matchBefore=r.startRe?r.startRe.exec(t):[""],r.matchAfter=r.endRe?r.endRe.exec(a):[""],r.replaceBefore=r.triggerRe?r.triggerRe.exec(t)[0]:"",r.replaceAfter=r.endTriggerRe?r.endTriggerRe.exec(a)[0]:"",r}},this.snippetMap={},this.snippetNameMap={},this.register=function(e,t){function a(e){return e&&!/^\^?\(.*\)\$?$|^\\b$/.test(e)&&(e="(?:"+e+")"),e||""}function n(e,t,n){return e=a(e),t=a(t),n?(e=t+e,e&&"$"!=e[e.length-1]&&(e+="$")):(e+=t,e&&"^"!=e[0]&&(e="^"+e)),new RegExp(e)}function r(e){e.scope||(e.scope=t||"_"),t=e.scope,s[t]||(s[t]=[],o[t]={});var a=o[t];if(e.name){var r=a[e.name];r&&c.unregister(r),a[e.name]=e}s[t].push(e),e.tabTrigger&&!e.trigger&&(!e.guard&&/^\w/.test(e.tabTrigger)&&(e.guard="\\b"),e.trigger=i.escapeRegExp(e.tabTrigger)),(e.trigger||e.guard||e.endTrigger||e.endGuard)&&(e.startRe=n(e.trigger,e.guard,!0),e.triggerRe=new RegExp(e.trigger,"",!0),e.endRe=n(e.endTrigger,e.endGuard,!0),e.endTriggerRe=new RegExp(e.endTrigger,"",!0))}var s=this.snippetMap,o=this.snippetNameMap,c=this;e||(e=[]),e&&e.content?r(e):Array.isArray(e)&&e.forEach(r),this._signal("registerSnippets",{scope:t})},this.unregister=function(e,t){function a(e){var a=r[e.scope||t];if(a&&a[e.name]){delete a[e.name];var i=n[e.scope||t],s=i&&i.indexOf(e);s>=0&&i.splice(s,1)}}var n=this.snippetMap,r=this.snippetNameMap;e.content?a(e):Array.isArray(e)&&e.forEach(a)},this.parseSnippetFile=function(e){e=e.replace(/\r/g,"");for(var t,a=[],n={},r=/^#.*|^({[\s\S]*})\s*$|^(\S+) (.*)$|^((?:\n*\t.*)+)/gm;t=r.exec(e);){if(t[1])try{n=JSON.parse(t[1]),a.push(n)}catch(i){}if(t[4])n.content=t[4].replace(/^\t/gm,""),a.push(n),n={};else{var s=t[2],o=t[3];if("regex"==s){var c=/\/((?:[^\/\\]|\\.)*)|$/g;n.guard=c.exec(o)[1],n.trigger=c.exec(o)[1],n.endTrigger=c.exec(o)[1],n.endGuard=c.exec(o)[1]}else"snippet"==s?(n.tabTrigger=o.match(/^\S*/)[0],n.name||(n.name=o)):n[s]=o}}return a},this.getSnippetByName=function(e,t){var a,n=this.snippetNameMap;return this.getActiveScopes(t).some(function(t){var r=n[t];return r&&(a=r[e]),!!a},this),a}}).call(u.prototype);var m=function(e){return e.tabstopManager?e.tabstopManager:(e.tabstopManager=this,this.$onChange=this.onChange.bind(this),this.$onChangeSelection=i.delayedCall(this.onChangeSelection.bind(this)).schedule,this.$onChangeSession=this.onChangeSession.bind(this),this.$onAfterExec=this.onAfterExec.bind(this),void this.attach(e))};(function(){this.attach=function(e){this.index=0,this.ranges=[],this.tabstops=[],this.$openTabstops=null,this.selectedTabstop=null,this.editor=e,this.editor.on("change",this.$onChange),this.editor.on("changeSelection",this.$onChangeSelection),this.editor.on("changeSession",this.$onChangeSession),this.editor.commands.on("afterExec",this.$onAfterExec),this.editor.keyBinding.addKeyboardHandler(this.keyboardHandler)},this.detach=function(){this.tabstops.forEach(this.removeTabstopMarkers,this),this.ranges=null,this.tabstops=null,this.selectedTabstop=null,this.editor.removeListener("change",this.$onChange),this.editor.removeListener("changeSelection",this.$onChangeSelection),this.editor.removeListener("changeSession",this.$onChangeSession),this.editor.commands.removeListener("afterExec",this.$onAfterExec),this.editor.keyBinding.removeKeyboardHandler(this.keyboardHandler),this.editor.tabstopManager=null,this.editor=null},this.onChange=function(e){var t="r"==e.action[0],a=e.start,n=e.end,r=a.row,i=n.row,s=i-r,o=n.column-a.column;if(t&&(s=-s,o=-o),!this.$inChange&&t){var c=this.selectedTabstop,l=c&&!c.some(function(e){return d(e.start,a)<=0&&d(e.end,n)>=0});if(l)return this.detach()}for(var u=this.ranges,m=0;m0?(this.removeRange(h),m--):(h.start.row==r&&h.start.column>a.column&&(h.start.column+=o),h.end.row==r&&h.end.column>=a.column&&(h.end.column+=o),h.start.row>=r&&(h.start.row+=s),h.end.row>=r&&(h.end.row+=s),d(h.start,h.end)>0&&this.removeRange(h)))}u.length||this.detach()},this.updateLinkedFields=function(){var e=this.selectedTabstop;if(e&&e.hasLinkedRanges){this.$inChange=!0;for(var a=this.editor.session,n=a.getTextRange(e.firstNonLinked),r=e.length;r--;){var i=e[r];if(i.linked){var s=t.snippetManager.tmStrFormat(n,i.original);a.replace(i,s)}}this.$inChange=!1}},this.onAfterExec=function(e){e.command&&!e.command.readOnly&&this.updateLinkedFields()},this.onChangeSelection=function(){if(this.editor){for(var e=this.editor.selection.lead,t=this.editor.selection.anchor,a=this.editor.selection.isEmpty(),n=this.ranges.length;n--;)if(!this.ranges[n].linked){var r=this.ranges[n].contains(e.row,e.column),i=a||this.ranges[n].contains(t.row,t.column);if(r&&i)return}this.detach()}},this.onChangeSession=function(){this.detach()},this.tabNext=function(e){var t=this.tabstops.length,a=this.index+(e||1);a=Math.min(Math.max(a,1),t),a==t&&(a=0),this.selectTabstop(a),0===a&&this.detach()},this.selectTabstop=function(e){this.$openTabstops=null;var t=this.tabstops[this.index];if(t&&this.addTabstopMarkers(t),this.index=e,t=this.tabstops[this.index],t&&t.length){if(this.selectedTabstop=t,this.editor.inVirtualSelectionMode)this.editor.selection.setRange(t.firstNonLinked);else{var a=this.editor.multiSelect;a.toSingleRange(t.firstNonLinked.clone());for(var n=t.length;n--;)t.hasLinkedRanges&&t[n].linked||a.addRange(t[n].clone(),!0);a.ranges[0]&&a.addRange(a.ranges[0].clone())}this.editor.keyBinding.addKeyboardHandler(this.keyboardHandler)}},this.addTabstops=function(e,t,a){if(this.$openTabstops||(this.$openTabstops=[]),!e[0]){var n=s.fromPoints(a,a);g(n.start,t),g(n.end,t),e[0]=[n],e[0].index=0}var r=this.index,i=[r+1,0],o=this.ranges;e.forEach(function(e,a){for(var n=this.$openTabstops[a]||e,r=e.length;r--;){var c=e[r],l=s.fromPoints(c.start,c.end||c.start);p(l.start,t),p(l.end,t),l.original=c,l.tabstop=n,o.push(l),n!=e?n.unshift(l):n[r]=l,c.fmtString?(l.linked=!0,n.hasLinkedRanges=!0):n.firstNonLinked||(n.firstNonLinked=l)}n.firstNonLinked||(n.hasLinkedRanges=!1),n===e&&(i.push(n),this.$openTabstops[a]=n),this.addTabstopMarkers(n)},this),i.length>2&&(this.tabstops.length&&i.push(i.splice(2,1)[0]),this.tabstops.splice.apply(this.tabstops,i))},this.addTabstopMarkers=function(e){var t=this.editor.session;e.forEach(function(e){e.markerId||(e.markerId=t.addMarker(e,"ace_snippet-marker","text"))})},this.removeTabstopMarkers=function(e){var t=this.editor.session;e.forEach(function(e){t.removeMarker(e.markerId),e.markerId=null})},this.removeRange=function(e){var t=e.tabstop.indexOf(e);e.tabstop.splice(t,1),t=this.ranges.indexOf(e),this.ranges.splice(t,1),this.editor.session.removeMarker(e.markerId),e.tabstop.length||(t=this.tabstops.indexOf(e.tabstop),-1!=t&&this.tabstops.splice(t,1),this.tabstops.length||this.detach())},this.keyboardHandler=new c,this.keyboardHandler.bindKeys({Tab:function(e){t.snippetManager&&t.snippetManager.expandWithTab(e)||e.tabstopManager.tabNext(1)},"Shift-Tab":function(e){e.tabstopManager.tabNext(-1)},Esc:function(e){e.tabstopManager.detach()},Return:function(e){return!1}})}).call(m.prototype);var h={};h.onChange=o.prototype.onChange,h.setPosition=function(e,t){this.pos.row=e,this.pos.column=t},h.update=function(e,t,a){this.$insertRight=a,this.pos=e,this.onChange(t)};var p=function(e,t){0==e.row&&(e.column+=t.column),e.row+=t.row},g=function(e,t){e.row==t.row&&(e.column-=t.column),e.row-=t.row};e("./lib/dom").importCssString(".ace_snippet-marker { -moz-box-sizing: border-box; box-sizing: border-box; background: rgba(194, 193, 208, 0.09); border: 1px dotted rgba(211, 208, 235, 0.62); position: absolute;}"),t.snippetManager=new u;var f=e("./editor").Editor;(function(){this.insertSnippet=function(e,a){return t.snippetManager.insertSnippet(this,e,a)},this.expandSnippet=function(e){return t.snippetManager.expandWithTab(this,e)}}).call(f.prototype)}),ace.define("ace/autocomplete/popup",["require","exports","module","ace/virtual_renderer","ace/editor","ace/range","ace/lib/event","ace/lib/lang","ace/lib/dom"],function(e,t,a){var n=e("../virtual_renderer").VirtualRenderer,r=e("../editor").Editor,i=e("../range").Range,s=e("../lib/event"),o=e("../lib/lang"),c=e("../lib/dom"),l=function(e){var t=new n(e);t.$maxLines=4;var a=new r(t);return a.setHighlightActiveLine(!1),a.setShowPrintMargin(!1),a.renderer.setShowGutter(!1),a.renderer.setHighlightGutterLine(!1),a.$mouseHandler.$focusWaitTimout=0,a.$highlightTagPending=!0,a},d=function(e){var t=c.createElement("div"),a=new l(t);e&&e.appendChild(t),t.style.display="none",a.renderer.content.style.cursor="default",a.renderer.setStyle("ace_autocomplete"),a.setOption("displayIndentGuides",!1),a.setOption("dragDelay",150);var n=function(){}; -a.focus=n,a.$isFocused=!0,a.renderer.$cursorLayer.restartTimer=n,a.renderer.$cursorLayer.element.style.opacity=0,a.renderer.$maxLines=8,a.renderer.$keepTextAreaAtCursor=!1,a.setHighlightActiveLine(!1),a.session.highlight(""),a.session.$searchHighlight.clazz="ace_highlight-marker",a.on("mousedown",function(e){var t=e.getDocumentPosition();a.selection.moveToPosition(t),u.start.row=u.end.row=t.row,e.stop()});var r,d=new i(-1,0,-1,1/0),u=new i(-1,0,-1,1/0);u.id=a.session.addMarker(u,"ace_active-line","fullLine"),a.setSelectOnHover=function(e){e?d.id&&(a.session.removeMarker(d.id),d.id=null):d.id=a.session.addMarker(d,"ace_line-hover","fullLine")},a.setSelectOnHover(!1),a.on("mousemove",function(e){if(!r)return void(r=e);if(r.x!=e.x||r.y!=e.y){r=e,r.scrollTop=a.renderer.scrollTop;var t=r.getDocumentPosition().row;d.start.row!=t&&(d.id||a.setRow(t),h(t))}}),a.renderer.on("beforeRender",function(){if(r&&-1!=d.start.row){r.$pos=null;var e=r.getDocumentPosition().row;d.id||a.setRow(e),h(e,!0)}}),a.renderer.on("afterRender",function(){var e=a.getRow(),t=a.renderer.$textLayer,n=t.element.childNodes[e-t.config.firstRow];n!=t.selectedNode&&(t.selectedNode&&c.removeCssClass(t.selectedNode,"ace_selected"),t.selectedNode=n,n&&c.addCssClass(n,"ace_selected"))});var m=function(){h(-1)},h=function(e,t){e!==d.start.row&&(d.start.row=d.end.row=e,t||a.session._emit("changeBackMarker"),a._emit("changeHoverMarker"))};a.getHoveredRow=function(){return d.start.row},s.addListener(a.container,"mouseout",m),a.on("hide",m),a.on("changeSelection",m),a.session.doc.getLength=function(){return a.data.length},a.session.doc.getLine=function(e){var t=a.data[e];return"string"==typeof t?t:t&&t.value||""};var p=a.session.bgTokenizer;return p.$tokenizeRow=function(e){var t=a.data[e],n=[];if(!t)return n;"string"==typeof t&&(t={value:t}),t.caption||(t.caption=t.value||t.name);var r,i,s=-1;t.iconClass&&n.push({type:"icon ace_icon-"+t.iconClass,value:" "});for(var o=0;oc-2&&(l=l.substr(0,c-t.caption.length-3)+"…"),n.push({type:"rightAlignedText",value:l})}return n},p.$updateOnChange=n,p.start=n,a.session.$computeWidth=function(){return this.screenWidth=0},a.$blockScrolling=1/0,a.isOpen=!1,a.isTopdown=!1,a.data=[],a.setData=function(e){a.setValue(o.stringRepeat("\n",e.length),-1),a.data=e||[],a.setRow(0)},a.getData=function(e){return a.data[e]},a.getRow=function(){return u.start.row},a.setRow=function(e){e=Math.max(0,Math.min(this.data.length,e)),u.start.row!=e&&(a.selection.clearSelection(),u.start.row=u.end.row=e||0,a.session._emit("changeBackMarker"),a.moveCursorTo(e||0,0),a.isOpen&&a._signal("select"))},a.on("changeSelection",function(){a.isOpen&&a.setRow(a.selection.lead.row),a.renderer.scrollCursorIntoView()}),a.hide=function(){this.container.style.display="none",this._signal("hide"),a.isOpen=!1},a.show=function(e,t,n){var i=this.container,s=window.innerHeight,o=window.innerWidth,c=this.renderer,l=c.$maxLines*t*1.4,d=e.top+this.$borderSize,u=d>s/2&&!n;u&&d+t+l>s?(c.$maxPixelHeight=d-2*this.$borderSize,i.style.top="",i.style.bottom=s-d+"px",a.isTopdown=!1):(d+=t,c.$maxPixelHeight=s-d-.2*t,i.style.top=d+"px",i.style.bottom="",a.isTopdown=!0),i.style.display="",this.renderer.$textLayer.checkForSizeChanges();var m=e.left;m+i.offsetWidth>o&&(m=o-i.offsetWidth),i.style.left=m+"px",this._signal("show"),r=null,a.isOpen=!0},a.getTextLeftOffset=function(){return this.$borderSize+this.renderer.$padding+this.$imageSize},a.$imageSize=0,a.$borderSize=1,a};c.importCssString(".ace_editor.ace_autocomplete .ace_marker-layer .ace_active-line { background-color: #CAD6FA; z-index: 1;}.ace_editor.ace_autocomplete .ace_line-hover { border: 1px solid #abbffe; margin-top: -1px; background: rgba(233,233,253,0.4);}.ace_editor.ace_autocomplete .ace_line-hover { position: absolute; z-index: 2;}.ace_editor.ace_autocomplete .ace_scroller { background: none; border: none; box-shadow: none;}.ace_rightAlignedText { color: gray; display: inline-block; position: absolute; right: 4px; text-align: right; z-index: -1;}.ace_editor.ace_autocomplete .ace_completion-highlight{ color: #000; text-shadow: 0 0 0.01em;}.ace_editor.ace_autocomplete { width: 280px; z-index: 200000; background: #fbfbfb; color: #444; border: 1px lightgray solid; position: fixed; box-shadow: 2px 3px 5px rgba(0,0,0,.2); line-height: 1.4;}"),t.AcePopup=d}),ace.define("ace/autocomplete/util",["require","exports","module"],function(e,t,a){t.parForEach=function(e,t,a){var n=0,r=e.length;0===r&&a();for(var i=0;r>i;i++)t(e[i],function(e,t){n++,n===r&&a(e,t)})};var n=/[a-zA-Z_0-9\$\-\u00A2-\uFFFF]/;t.retrievePrecedingIdentifier=function(e,t,a){a=a||n;for(var r=[],i=t-1;i>=0&&a.test(e[i]);i--)r.push(e[i]);return r.reverse().join("")},t.retrieveFollowingIdentifier=function(e,t,a){a=a||n;for(var r=[],i=t;i=t?a:t-1;break;case"down":t=t>=a?-1:t+1;break;case"start":t=0;break;case"end":t=a}this.popup.setRow(t)},this.insertMatch=function(e,t){if(e||(e=this.popup.getData(this.popup.getRow())),!e)return!1;if(e.completer&&e.completer.insertMatch)e.completer.insertMatch(this.editor,e);else{if(this.completions.filterText)for(var a,n=this.editor.selection.getAllRanges(),r=0;a=n[r];r++)a.start.column-=this.completions.filterText.length,this.editor.session.remove(a);e.snippet?c.insertSnippet(this.editor,e.snippet):this.editor.execCommand("insertstring",e.value||e)}this.detach()},this.commands={Up:function(e){e.completer.goTo("up")},Down:function(e){e.completer.goTo("down")},"Ctrl-Up|Ctrl-Home":function(e){e.completer.goTo("start")},"Ctrl-Down|Ctrl-End":function(e){e.completer.goTo("end")},Esc:function(e){e.completer.detach()},Return:function(e){return e.completer.insertMatch()},"Shift-Return":function(e){e.completer.insertMatch(null,{deleteSuffix:!0})},Tab:function(e){var t=e.completer.insertMatch();return t||e.tabstopManager?t:void e.completer.goTo("down")},PageUp:function(e){e.completer.popup.gotoPageUp()},PageDown:function(e){e.completer.popup.gotoPageDown()}},this.gatherCompletions=function(e,t){var a=e.getSession(),n=e.getCursorPosition(),r=(a.getLine(n.row),i.getCompletionPrefix(e));this.base=a.doc.createAnchor(n.row,n.column-r.length),this.base.$insertRight=!0;var s=[],o=e.completers.length;return e.completers.forEach(function(i,c){i.getCompletions(e,a,n,r,function(n,i){!n&&i&&(s=s.concat(i));var c=e.getCursorPosition();a.getLine(c.row);t(null,{prefix:r,matches:s,finished:0===--o})})}),!0},this.showPopup=function(e){this.editor&&this.detach(),this.activated=!0,this.editor=e,e.completer!=this&&(e.completer&&e.completer.detach(),e.completer=this),e.on("changeSelection",this.changeListener),e.on("blur",this.blurListener),e.on("mousedown",this.mousedownListener),e.on("mousewheel",this.mousewheelListener),this.updateCompletions()},this.updateCompletions=function(e){if(e&&this.base&&this.completions){var t=this.editor.getCursorPosition(),a=this.editor.session.getTextRange({start:this.base,end:t});if(a==this.completions.filterText)return;return this.completions.setFilter(a),this.completions.filtered.length&&(1!=this.completions.filtered.length||this.completions.filtered[0].value!=a||this.completions.filtered[0].snippet)?void this.openPopup(this.editor,a,e):this.detach()}var n=this.gatherCompletionsId;this.gatherCompletions(this.editor,function(t,a){var r=function(){return a.finished?this.detach():void 0}.bind(this),i=a.prefix,s=a&&a.matches;if(!s||!s.length)return r();if(0===i.indexOf(a.prefix)&&n==this.gatherCompletionsId){this.completions=new d(s),this.exactMatch&&(this.completions.exactMatch=!0),this.completions.setFilter(i);var o=this.completions.filtered;return o.length&&(1!=o.length||o[0].value!=i||o[0].snippet)?this.autoInsert&&1==o.length&&a.finished?this.insertMatch(o[0]):void this.openPopup(this.editor,i,e):r()}}.bind(this))},this.cancelContextMenu=function(){this.editor.$mouseHandler.cancelContextMenu()},this.updateDocTooltip=function(){var e=this.popup,t=e.data,a=t&&(t[e.getHoveredRow()]||t[e.getRow()]),n=null;return a&&this.editor&&this.popup.isOpen?(this.editor.completers.some(function(e){return e.getDocTooltip&&(n=e.getDocTooltip(a)),n}),n||(n=a),"string"==typeof n&&(n={docText:n}),n&&(n.docHTML||n.docText)?void this.showDocTooltip(n):this.hideDocTooltip()):this.hideDocTooltip()},this.showDocTooltip=function(e){this.tooltipNode||(this.tooltipNode=o.createElement("div"),this.tooltipNode.className="ace_tooltip ace_doc-tooltip",this.tooltipNode.style.margin=0,this.tooltipNode.style.pointerEvents="auto",this.tooltipNode.tabIndex=-1,this.tooltipNode.onblur=this.blurListener.bind(this));var t=this.tooltipNode;e.docHTML?t.innerHTML=e.docHTML:e.docText&&(t.textContent=e.docText),t.parentNode||document.body.appendChild(t);var a=this.popup,n=a.container.getBoundingClientRect();t.style.top=a.container.style.top,t.style.bottom=a.container.style.bottom,window.innerWidth-n.right<320?(t.style.right=window.innerWidth-n.left+"px",t.style.left=""):(t.style.left=n.right+1+"px",t.style.right=""),t.style.display="block"},this.hideDocTooltip=function(){if(this.tooltipTimer.cancel(),this.tooltipNode){var e=this.tooltipNode;this.editor.isFocused()||document.activeElement!=e||this.editor.focus(),this.tooltipNode=null,e.parentNode&&e.parentNode.removeChild(e)}}}).call(l.prototype),l.startCommand={name:"startAutocomplete",exec:function(e){e.completer||(e.completer=new l),e.completer.autoInsert=!1,e.completer.autoSelect=!0,e.completer.showPopup(e),e.completer.cancelContextMenu()},bindKey:"Ctrl-Space|Ctrl-Shift-Space|Alt-Space"};var d=function(e,t){this.all=e,this.filtered=e,this.filterText=t||"",this.exactMatch=!1};(function(){this.setFilter=function(e){if(e.length>this.filterText&&0===e.lastIndexOf(this.filterText,0))var t=this.filtered;else var t=this.all;this.filterText=e,t=this.filterCompletions(t,this.filterText),t=t.sort(function(e,t){return t.exactMatch-e.exactMatch||t.score-e.score});var a=null;t=t.filter(function(e){var t=e.snippet||e.caption||e.value;return t===a?!1:(a=t,!0)}),this.filtered=t},this.filterCompletions=function(e,t){var a=[],n=t.toUpperCase(),r=t.toLowerCase();e:for(var i,s=0;i=e[s];s++){var o=i.value||i.caption||i.snippet;if(o){var c,l,d=-1,u=0,m=0;if(this.exactMatch){if(t!==o.substr(0,t.length))continue e}else for(var h=0;h=0&&(0>g||g>p)?p:g,0>c)continue e;l=c-d-1,l>0&&(-1===d&&(m+=10),m+=l),u|=1<",s.escapeHTML(e.caption),"","
",s.escapeHTML(e.snippet)].join(""))}},u=[d,c,l];t.setCompleters=function(e){u.length=0,e&&u.push.apply(u,e)},t.addCompleter=function(e){u.push(e)},t.textCompleter=c,t.keyWordCompleter=l,t.snippetCompleter=d;var m,h={name:"expandSnippet",exec:function(e){return n.expandWithTab(e)},bindKey:"Tab"},p=function(e,t){g(t.session.$mode)},g=function k(e){var t=e.$id;n.files||(n.files={}),f(t),e.modes&&e.modes.forEach(k)},f=function x(e){if(e&&!n.files[e]){var t=e.replace("mode","snippets");n.files[e]={},i.loadModule(t,function(t){t&&(n.files[e]=t,!t.snippets&&t.snippetText&&(t.snippets=n.parseSnippetFile(t.snippetText)),n.register(t.snippets||[],t.scope),t.includeScopes&&(n.snippetMap[t.scope].includeScopes=t.includeScopes,t.includeScopes.forEach(function(e){x("ace/mode/"+e)})))})}},b=function(e){var t=e.editor,a=t.completer&&t.completer.activated;if("backspace"===e.command.name)a&&!o.getCompletionPrefix(t)&&t.completer.detach();else if("insertstring"===e.command.name){var n=o.getCompletionPrefix(t);n&&n.length>=t.$liveAutocompletionThreshold&&!a&&(t.completer||(t.completer=new r),t.completer.autoInsert=!1,t.completer.showPopup(t))}},v=s.delayedCall(function(){b(m)},0),y=function(e){m=e,v.delay(e.editor.$liveAutocompletionDelay)},w=e("../editor").Editor;e("../config").defineOptions(w.prototype,"editor",{enableBasicAutocompletion:{set:function(e){e?(this.completers||(this.completers=Array.isArray(e)?e:u),this.commands.addCommand(r.startCommand)):this.commands.removeCommand(r.startCommand)},value:!1},enableLiveAutocompletion:{set:function(e){e?(this.completers||(this.completers=Array.isArray(e)?e:u),this.commands.on("afterExec",y)):this.commands.removeListener("afterExec",y)},value:!1},liveAutocompletionThreshold:{value:0},liveAutocompletionDelay:{value:500},enableSnippets:{set:function(e){e?(this.commands.addCommand(h),this.on("changeMode",p),p(null,this)):(this.commands.removeCommand(h),this.off("changeMode",p))},value:!1}})}),function(){ace.require(["ace/ext/language_tools"],function(){})}(),ace.define("ace/ext/beautify/php_rules",["require","exports","module","ace/token_iterator"],function(e,t,a){e("ace/token_iterator").TokenIterator;t.newLines=[{type:"support.php_tag",value:""},{type:"paren.lparen",value:"{",indent:!0},{type:"paren.rparen",breakBefore:!0,value:"}",indent:!1},{type:"paren.rparen",breakBefore:!0,value:"})",indent:!1,dontBreak:!0},{type:"comment"},{type:"text",value:";"},{type:"text",value:":",context:"php"},{type:"keyword",value:"case",indent:!0,dontBreak:!0},{type:"keyword",value:"default",indent:!0,dontBreak:!0},{type:"keyword",value:"break",indent:!1,dontBreak:!0},{type:"punctuation.doctype.end",value:">"},{type:"meta.tag.punctuation.end",value:">"},{type:"meta.tag.punctuation.begin",value:"<",blockTag:!0,indent:!0,dontBreak:!0},{type:"meta.tag.punctuation.begin",value:""!=o.value?n="php":"support.php_tag"==o.type&&"?>"==o.value?n="html":"meta.tag.name.style"==o.type&&"css"!=n?n="css":"meta.tag.name.style"==o.type&&"css"==n?n="html":"meta.tag.name.script"==o.type&&"js"!=n?n="js":"meta.tag.name.script"==o.type&&"js"==n&&(n="html"),g=e.stepForward(),g&&0==g.type.indexOf("meta.tag.name")&&(s=g.value),"support.php_tag"==p.type&&"v;v++)u+=" ";break}if(h===!1)for(v in c)if(!(p.type!=c[v].type||c[v].value&&p.value!=c[v].value||c[v].blockTag&&-1!==d.indexOf(r)||c[v].context&&c[v].context!==n)){if(c[v].indent===!0&&m++,!c[v].dontBreak&&!f)for(u+="\n",v=0;m>v;v++)u+=" ";break}if(u+=b,"support.php_tag"==p.type&&"?>"==p.value&&(h=!1),i=r,p=o,o=g,null===o)break}else o=g;else o=e.stepForward();return u}}),ace.define("ace/ext/beautify",["require","exports","module","ace/token_iterator","ace/ext/beautify/php_rules"],function(e,t,a){var n=e("ace/token_iterator").TokenIterator,r=e("./beautify/php_rules").transform;t.beautify=function(e){var t=new n(e,0,0),a=(t.getCurrentToken(),e.$modeId.split("/").pop()),i=r(t,a);e.doc.setValue(i)},t.commands=[{name:"beautify",exec:function(e){t.beautify(e.session)},bindKey:"Ctrl-Shift-B"}]}),function(){ace.require(["ace/ext/beautify"],function(){})}(),ace.define("ace/mode/clickhouse_highlight_rules",["require","exports","$rootScope","module","ace/lib/oop","ace/snippets","ace/ext/language_tools","ace/mode/text_highlight_rules"],function(e,t,a){var n=e("../lib/oop"),r=e("./text_highlight_rules").TextHighlightRules,i=function(){var e=this,t="SELECT|CASE|THEN|DISTINCT|INSERT|UPDATE|DELETE|WHERE|AND|OR|OFFSET|HAVING|AS|FROM|WHEN|ELSE|END|TYPE|LEFT|RIGHT|JOIN|ON|OUTER|DESC|ASC|UNION|CREATE|TABLE|PRIMARY|KEY|FOREIGN|NOT|REFERENCES|DEFAULT|INNER|CROSS|NATURAL|DATABASE|DROP|GRANT|ANY|BETWEEN|ATTACH|DETACH|CAST|WITH|BIT_AND|BIT_OR|BIT_XOR|DESCRIBE|OPTIMIZE|PREWHERE|TOTALS|DATABASES|PROCESSLIST|SHOW|IF",a="IF\\W+NOT\\W+EXISTS|IF\\W+EXISTS|FORMAT\\W+Vertical|FORMAT\\W+JSONCompact|FORMAT\\W+JSONEachRow|FORMAT\\W+TSKV|FORMAT\\W+TabSeparatedWithNames|FORMAT\\W+TabSeparatedWithNamesAndTypes|FORMAT\\W+TabSeparatedRaw|FORMAT\\W+BlockTabSeparated|FORMAT\\W+CSVWithNames|FORMAT\\W+CSV|FORMAT\\W+JSON|FORMAT\\W+TabSeparated",n="true|false|NULL",r="sum|sumIf|avg|avgIf",i="date|integer|uint8|uint16|uint32|uint64|int8|int16|int32|int64|float32|float64|datetime|enum8|enum16|fixedstring|array|tuple|stringMergeTree|SummingMergeTree|ReplacingMergeTree|ReplicatedMergeTree|Buffer|ReplicatedCollapsingMergeTree|CollapsingMergeTree|AggregatingMergeTree|Merge|Memory|GraphiteMergeTree|ReplicatedAggregatingMergeTree|ReplicatedSummingMergeTree",s=["IF NOT EXISTS","IF EXISTS","GROUP BY","ORDER BY","UNION ALL","FORMAT JSON","FORMAT JSONCompact","FORMAT JSONEachRow","FORMAT TSV","FORMAT TabSeparated","FORMAT TabSeparatedWithNames","FORMAT TabSeparatedWithNamesAndTypes","FORMAT TabSeparatedRaw","FORMAT BlockTabSeparated","FORMAT TSKV","FORMAT CSV","FORMAT CSVWithNames","SYSTEM RELOAD DICTIONARY","SYSTEM RELOAD DICTIONARIES","SYSTEM DROP DNS CACHE","SYSTEM SHUTDOWN","SYSTEM KILL","CLEAR COLUMN IN PARTITION"],o=["DRAW_GMAPS","DRAW_PLOTLY","DRAW_CALENDAR","DRAW_TEXT","DRAW_HEATMAP","DRAW_CHART","DRAW_BAR","DRAW_GRIDCHART","DRAW_RIVER","DRAW_RAW","DRAW_SANKEYS","DRAW_TREEMAP","DRAW_C3","DRAW_MAP"],c="";if(window.aceJSRules&&window.aceJSRules.builtinFunctions){if(window.aceJSRules.builtinFunctions){var l=[];window.aceJSRules.builtinFunctions.forEach(function(e){l.push(e.name)}),r=l.join("|")}_.isArray(window.aceJSRules.tables)&&(c=window.aceJSRules.tables.join("|"))}var d="";d=window.global_delimiter?new RegExp(window.global_delimiter):new RegExp(";;");var u=[],m=t.toLowerCase();window.aceJSRules&&_.isArray(window.aceJSRules.fieldsList)&&window.aceJSRules.fieldsList.forEach(function(e){var t=e.name.toLowerCase()+"|";m.indexOf(t)>-1||u.push(e.name)});var h=this.createKeywordMapper({"support.function":r,keyword:t,"constant.language":n,"storage.type":i,"markup.bold":c,"markup.heading":u.join("|")},"identifier",!0);this.$rules={start:[{token:"comment",regex:"--.*$",caseInsensitive:!0},{token:"comment.block",start:"```",end:"```"},{token:"keyword",regex:"GROUP\\W+BY|ON\\W+CLUSTER|ORDER\\W+BY|LIMIT\\W+\\d+\\W*,\\W*\\d+|LIMIT\\W+\\d+\\W+BY\\W+|LIMIT\\W+\\d+"},{token:"variable.language",regex:/\$[\w]+(?:\[[\w\]+]|[=\-]>\w+)?/},{token:"variable.language",regex:/@[\w]+(?:\[[\w\]+]|[=\-]>\w+)?/},{token:"variable.language",regex:/\:[\w]+(?:\[[\w\]+]|[=\-]>\w+)?/},{token:"variable.language",regex:/\{[\w]+(?:\[[\w\]+]|[=\-]>\w+)\}?/},{token:"comment",start:"/\\*",end:"\\*/"},{token:"constant",regex:'".*?"'},{token:"storage",regex:a},{token:"invalid.illegal",regex:o.join("|")},{token:"string",regex:"'.*?'"},{token:"constant.numeric",regex:"[+-]?\\d+(?:(?:\\.\\d*)?(?:[eE][+-]?\\d+)?)?\\b"},{token:h,regex:"[a-zA-Z_$][a-zA-Z0-9_$]*\\b"},{token:"constant.character.escape",regex:d},{token:"punctuation",regex:/[?:,;.]/},{token:"keyword.operator",regex:"\\+|\\-|\\/|\\/\\/|%|<@>|@>|<@|&|\\^|~|<|>|<=|=>|==|!=|<>|="},{token:"paren.lparen",regex:"[\\(\\{]"},{token:"paren.rparen",regex:"[\\)\\}]"},{token:"text",regex:"\\s+"}]},this.normalizeRules(),this.completions=[],this.getCompletions=function(){return e.completions},this.addCompletions=function(e,t,a,n,r,i,s){this.completions.push({name:e,value:t,caption:a,score:n,meta:r,iconClass:i,docHTML:s})},this.addCompletionsDictionaries=function(e){this.addCompletions(e.dic,e.dic,e.title,0,"dic","dict",this.makeCompletionsDocFunctions(e.title,e.dic))},this.addCompletionsFunctions=function(e){this.addCompletions(e.name,e.name+"( )",e.name+"( )",e.score,"function","function",this.makeCompletionsDocFunctions(e.name,e.origin,e.comb))},this.addCompletionsTableFiled=function(e){var t=e.table+"."+e.name,a=e.name,n="type:"+e.type+"

default_type:"+e.default_type+"
"+e.default_expression;this.addCompletions(t,a,a,100,e.type,"field",this.makeCompletionsdocHTML(t,n))},this.addArrayCompletions=function(e,t,a){var n=this;e.forEach(function(e){n.addCompletions(e,e,e,0,t,a,!1)})},this.setKeywords=function(e){console.log("setKeywords > ",e),this.keywordRule.onMatch=this.createKeywordMapper(e,"identifier")},this.makeCompletionsDocFunctions=function(e,t,a){if(!window.global_chFunctionsHelp)return!1;if(!window.global_chFunctionsHelp.functions)return!1;var n="",r=e;if("undefined"!=typeof window.global_chFunctionsHelp.functions[e]?r=e:"undefined"!=typeof window.global_chFunctionsHelp.functions[t]&&(r=t),"undefined"!=typeof window.global_chFunctionsHelp.functions[r]){var i="en",s=window.global_chFunctionsHelp.functions[r],o="",c="";s.desc&&(o=s.bracket,c=s.desc[i],c||(c=s.desc.en?s.desc.en:s.desc.ru)),c&&(c=c.replace(/\.\s*/gm,".
")),n=''+e+o+'
'+c+" "}else n=''+e+"( )
"+t;return n+'
'},this.makeCompletionsdocHTML=function(e,t){return'
'+e+"
"+t+"
"},this.addArrayCompletions(t.split("|"),"keyword","keyword"),this.addArrayCompletions(s,"keyword","keyword"),this.addArrayCompletions(o,"draw","draw"),this.addArrayCompletions(i.split("|"),"type","type")};n.inherits(i,r),t.ClickhouseHighlightRules=i}),ace.define("ace/mode/matching_brace_outdent",["require","exports","module","ace/range"],function(e,t,a){var n=e("ace/range").Range,r=function(){};(function(){this.checkOutdent=function(e,t){return/^\s+$/.test(e)?/^\s*\}/.test(t):!1},this.autoOutdent=function(e,t){var a=e.getLine(t),r=a.match(/^(\s*\})/);if(!r)return 0;var i=r[1].length,s=e.findMatchingBracket({row:t,column:i});if(!s||s.row==t)return 0;var o=this.$getIndent(e.getLine(s.row));e.replace(new n(t,0,t,i-1),o)},this.$getIndent=function(e){return e.match(/^\s*/)[0]}}).call(r.prototype),t.MatchingBraceOutdent=r}),ace.define("ace/mode/clickhouse_FoldMode",["$rootScope","require","exports","module","ace/lib/oop","ace/range","ace/mode/sqlserver","ace/mode/folding/cstyle"],function(e,t,a){var n=e("../lib/oop"),r=e("ace/mode/folding/cstyle").FoldMode,i=(e("ace/range").Range,e("ace/token_iterator").TokenIterator),s=t.FoldMode=function(){};n.inherits(s,r),function(){this.foldingRules="cStyle",this.foldingStartMarker=/\(|\{/,this.getFoldWidgetRange=function(e,t,a,n){for(var r=new i(e,a,0),s=r.getCurrentToken(),o=!1;s;){var c=s,l=r.getCurrentTokenPosition();if(s=r.stepForward(),"paren.lparen"!=c.type||"("!=c.value&&"{"!=c.value||(o=e.getBracketRange(l)),o)break}return o}}.call(s.prototype)}),window.global_chFunctionsHelp={functions:{corr:{bracket:"(x, y)",desc:{en:'Calculates the Pearson correlation coefficient: Σ((x - x̅)(y - y̅)) / sqrt(Σ((x - x̅)2) * Σ((y - y̅)2)).'}},stddevPop:{bracket:"(x)",desc:{en:"The result is equal to the square root of 'varPop(x)'."}},varPop:{bracket:"(x, y)",desc:{en:"Calculates the value of %%Σ((x - x̅)(y - y̅)) / n%%."}},argMin:{bracket:"(arg, val)",desc:{en:"Calculates the 'arg' value for a minimal 'val' value. If there are several different values of 'arg' for minimal values of 'val', the first of these values encountered is output."}},quantileExactWeighted:{bracket:"(level)(x, weight)",desc:{en:"Вычисляет квантиль уровня level точно."}},min:{bracket:"(v)",desc:{en:"Minimal execution speed in rows per second. Checked on every data block when 'timeout_before_checking_execution_speed' expires. If the execution speed is lower, an exception is thrown."}},varSamp:{bracket:"(x, y)",desc:{en:"Calculates the value of %%Σ((x - x̅)(y - y̅)) / (n - 1)%%.

Returns Float64. If n <= 1, it returns +∞."}},anyLast:{bracket:"(x)",desc:{en:"Selects the last value encountered.
The result is just as indeterminate as for the 'any' function."}},argMax:{bracket:"(arg, val)",desc:{en:"Calculates the 'arg' value for a maximum 'val' value. If there are several different values of 'arg' for maximum values of 'val', the first of these values encountered is output."}},count:{bracket:"()",desc:{en:"Counts the number of rows. "}},any:{bracket:"(x)",desc:{en:"Selects the last value encountered.
The result is just as indeterminate as for the 'any' function."}},avg:{bracket:"(x)",desc:{en:"Calculates the average.
Only works for numbers.
The result is always Float64."}},sequenceMatch:{bracket:"(pattern)(time, cond1, cond2, ...)",desc:{en:"Pattern matching for event chains.

'pattern' is a string containing a pattern to match."}},stddevSamp:{bracket:"(x)",desc:{en:"The result is equal to the square root of 'varSamp(x)'."}},medianDeterministic:{bracket:"(x, determinator)",desc:{en:"This function works similarly to the 'median' function - it approximates the median."}},quantilesTimingWeighted:{bracket:"(level1, level2, ...)(x, weight)",desc:{en:"Calculates the quantiles of all specified levels using the same algorithm as the 'medianTimingWeighted' function."}},uniq:{bracket:"(N)(x)",desc:{en:"Calculates the number of different argument values, if it is less than or equal to N.
If the number of different argument values is greater than N, it returns N + 1."}},covarSamp:{bracket:"(x, y)",desc:{en:"Calculates the value of %%Σ((x - x̅)(y - y̅)) / (n - 1)%%.

Returns Float64. If n <= 1, it returns +∞." -}},max:{bracket:"(v)",desc:{en:"Maximum number of bytes (uncompressed data) that can be passed to a remote server or saved in a temporary table when using GLOBAL IN."}},quantileTDigest:{bracket:"(level)(x)",desc:{en:"t-digest"}},quantilesTiming:{bracket:"(level1, level2, ...)(x, weight)",desc:{en:"Calculates the quantiles of all specified levels using the same algorithm as the 'medianTimingWeighted' function."}},quantiles:{bracket:"(level1, level2, ...)(x, determinator)",desc:{en:"Calculates the quantiles of all specified levels using the same algorithm as the 'medianDeterministic' function."}},quantile:{bracket:"(level1, level2, ...)(x, determinator)",desc:{en:"Calculates the quantiles of all specified levels using the same algorithm as the 'medianDeterministic' function."}},groupArray:{bracket:"(x)",desc:{en:"Creates an array of argument values.
Values can be added to the array in any (indeterminate) order.

In some cases, you can rely on the order of execution. This applies to cases when SELECT comes from a subquery that uses ORDER BY."}},sum:{bracket:"(x)",desc:{en:"Calculates the sum.
Only works for numbers."}},median:{bracket:"(x, weight)",desc:{en:"Differs from the 'medianTiming' function in that it has a second argument - "weights". Weight is a non-negative integer.
The result is calculated as if the 'x' value were passed 'weight' number of times to the 'medianTiming' function."}},quantileTiming:{bracket:"(level)(x, weight)",desc:{en:"Calculates the quantile of 'level' using the same algorithm as the 'medianTimingWeighted' function."}},quantileTimingWeighted:{bracket:"(level)(x, weight)",desc:{en:"Calculates the quantile of 'level' using the same algorithm as the 'medianTimingWeighted' function."}},groupUniqArray:{bracket:"(x)",desc:{en:"Creates an array from different argument values. Memory consumption is the same as for the 'uniqExact' function."}},uniqHLL12:{bracket:"(x)",desc:{en:"Uses the HyperLogLog algorithm to approximate the number of different values of the argument. "}},covarPop:{bracket:"(x, y)",desc:{en:"Calculates the value of %%Σ((x - x̅)(y - y̅)) / n%%."}},sequenceCount:{bracket:"(pattern)(time, cond1, cond2, ...)",desc:{en:"sequenceMatch"}},quantileDeterministic:{bracket:"(level)(x, determinator)",desc:{en:"Calculates the quantile of 'level' using the same algorithm as the 'medianDeterministic' function."}},quantileExact:{bracket:"(level)(x, weight)",desc:{en:""}},quantilesDeterministic:{bracket:"(level1, level2, ...)(x, determinator)",desc:{en:"Calculates the quantiles of all specified levels using the same algorithm as the 'medianDeterministic' function."}},medianTiming:{bracket:"(x, weight)",desc:{en:"Differs from the 'medianTiming' function in that it has a second argument - "weights"."}},medianTimingWeighted:{bracket:"(x, weight)",desc:{ru:"",en:"Differs from the 'medianTiming' function in that it has a second argument - "weights"."}},uniqExact:{bracket:"(x)",desc:{en:"Calculates the number of different values of the argument, exactly.
There is no reason to fear approximations, so it's better to use the 'uniq' function.
You should use the 'uniqExact' function if you definitely need an exact result. "}},uniqCombined:{bracket:"(x)",desc:{en:""}},uniqUpTo:{bracket:"(N)(x)",desc:{en:"Calculates the number of different argument values, if it is less than or equal to N.
If the number of different argument values is greater than N, it returns N + 1."}},substring:{bracket:"(s, offset, length)",desc:{en:"The same as 'substring', but for Unicode code points. Works under the assumption that the string contains a set of bytes representing a UTF-8 encoded text. If this assumption is not met, it returns some result (it doesn't throw an exception)."}},notLike:{bracket:"(haystack, pattern), haystack NOT LIKE pattern operator",desc:{en:"The same thing as 'like', but negative."}},hostName:{bracket:"()",desc:{en:"Returns a string with the name of the host that this function was performed on. For distributed processing, this is the name of the remote server host, if the function is performed on a remote server."}},globalNotIn:{bracket:"(v)",desc:{en:"See the section "IN operators"."}},or:{bracket:"(v)",desc:{en:"The same thing as 'max_temporary_columns', but without counting constant columns.
Note that constant columns are formed fairly often when running a query, but they require approximately zero computing resources."}},extractAll:{bracket:"(haystack, pattern)",desc:{en:"Extracts all the fragments of a string using a regular expression. If 'haystack' doesn't match the 'pattern' regex, an empty string is returned. Returns an array of strings consisting of all matches to the regex."}},arrayFirst:{bracket:"(func, arr1, ...)",desc:{en:"Returns the index of the first element in the 'arr1' array for which 'func' returns something other than 0."}},notEquals:{bracket:"(v)",desc:{ru:"",en:""}},arrayExists:{bracket:"([func,] arr1, ...)",desc:{en:"Returns 1 if there is at least one element in 'arr' for which 'func' returns something other than 0. Otherwise, it returns 0."}},arrayCount:{bracket:"([func,] arr1, ...)",desc:{en:"Returns the number of elements in 'arr' for which 'func' returns something other than 0. If 'func' is not specified, it returns the number of non-zero items in the array."}},arrayMap:{bracket:"(func, arr1, ...)",desc:{en:"Returns an array obtained from the original application of the 'func' function to each element in the 'arr' array."}},now:{bracket:"(v)",desc:{en:"If the parameter is true, INSERT operation will skip columns with unknown names from input.
Otherwise, an exception will be generated, it is default behavior.
The parameter works only for JSONEachRow and TSKV input formats."}},intDiv:{bracket:"(a, b)",desc:{en:"Differs from 'intDiv' in that it returns zero when dividing by zero or when dividing a minimal negative number by minus one."}},topLevelDomain:{bracket:"(v)",desc:{en:"- Selects the top-level domain. Example: .ru."}},intHash32:{bracket:"(v)",desc:{en:"Calculates a 32-bit hash code from any type of integer.
This is a relatively fast non-cryptographic hash function of average quality for numbers."}},replaceOne:{bracket:"(haystack, pattern, replacement)",desc:{en:"Replaces the first occurrence, if it exists, of the 'pattern' substring in 'haystack' with the 'replacement' substring.
Hereafter, 'pattern' and 'replacement' must be constants."}},cityHash64:{bracket:"(v)",desc:{en:"Calculates CityHash64 from a string or a similar hash function for any number of any type of arguments.
For String-type arguments, CityHash is used. This is a fast non-cryptographic hash function for strings with decent quality"}},OSToRoot:{bracket:"(v)",desc:{en:"Accepts a UInt8 number - the ID of the operating system from the Yandex.Metrica dictionary. If any OS matches the passed number, it returns a UInt8 number - the ID of the corresponding root OS (for example, it converts Windows Vista to Windows). Otherwise, returns 0."}},sipHash128:{bracket:"(v)",desc:{en:"Calculates SipHash from a string.
Accepts a String-type argument. Returns FixedString(16).
Differs from sipHash64 in that the final xor-folding state is only done up to 128 bits."}},SHA1:{bracket:"(v)",desc:{en:"Calculates SHA-1, SHA-224, or SHA-256 from a string and returns the resulting set of bytes as FixedString(20), FixedString(28), or FixedString(32)."}},asin:{bracket:"(x)",desc:{en:"The arc sine."}},SHA256:{bracket:"(v)",desc:{en:"Calculates SHA-1, SHA-224, or SHA-256 from a string and returns the resulting set of bytes as FixedString(20), FixedString(28), or FixedString(32)."}},MD5:{bracket:"(v)",desc:{en:"Calculates the MD5 from a string and returns the resulting set of bytes as FixedString(16)."}},bitmaskToList:{bracket:"(num)",desc:{en:"Accepts an integer. Returns a string containing the list of powers of two that total the source number when summed. They are comma-separated without spaces in text format, in ascending order."}},array:{bracket:"(v)",desc:{en:"The -%%Array%% suffix can be appended to any aggregate function. In this case, the aggregate function takes arguments of the 'Array(T)' type (arrays) instead of 'T' type arguments. If the aggregate function accepts multiple arguments, this must be arrays of equal lengths. "}},dictGetStringOrDefault:{bracket:"(v)",desc:{ru:"%%dictGetT('dict_name', 'attr_name', id, default)%%
Аналогично функциям dictGetT, но значение по умолчанию берётся из последнего аргумента функции.",en:""}},greaterOrEquals:{bracket:"(v)",desc:{ru:"",en:""}},e:{bracket:"(v)",desc:{en:"What to do when the amount of data exceeds one of the limits: 'throw' or 'break'. By default, throw."}},runningDifference:{bracket:"(x)",desc:{en:"Calculates the difference between consecutive values in the data block.
Result of the function depends on the order of the data in the blocks.

It works only inside of the each processed block of data. Data splitting in the blocks is not explicitly controlled by the user. "}},not:{bracket:"(v)",desc:{ru:'Смотрите раздел "Операторы IN".',en:"See the section "IN operators"."}},intHash64:{bracket:"(v)",desc:{en:"Calculates a 64-bit hash code from any type of integer.
It works faster than intHash32. Average quality."}},acos:{bracket:"(x)",desc:{ru:"Арккосинус.",en:"The arc cosine."}},dictGetString:{bracket:"(v)",desc:{en:""}},and:{bracket:"(x, determinator)",desc:{en:"This function works similarly to the 'median' function - it approximates the median. However, in contrast to 'median', the result is deterministic and does not depend on the order of query execution.

To achieve this, the function takes a second argument - the "determinator". "}},dictGetDate:{bracket:"(v)",desc:{ru:"",en:""}},dictGetFloat32:{bracket:"(v)",desc:{ru:"",en:""}},dictGetInt8:{bracket:"(v)",desc:{ru:"",en:""}},dictGetUInt32:{bracket:"(v)",desc:{ru:"",en:""}},OSIn:{bracket:"(lhs, rhs)",desc:{en:"Checks whether the 'lhs' operating system belongs to the 'rhs' operating system."}},arrayFirstIndex:{bracket:"(func, arr1, ...)",desc:{en:"Returns the index of the first element in the 'arr1' array for which 'func' returns something other than 0."}},ceil:{bracket:"(x[, N])",desc:{en:"Returns the smallest round number that is greater than or equal to 'x'. In every other way, it is the same as the 'floor' function (see above)."}},fragment:{bracket:"(v)",desc:{en:"Removes the query-string and fragment identifier. The question mark and number sign are also removed."}},dictGetUInt8:{bracket:"(v)",desc:{ru:"",en:""}},dictHas:{bracket:"(v)",desc:{ru:"%%dictHas('dict_name', id)%%
- проверить наличие ключа в словаре. Возвращает значение типа UInt8, равное 0, если ключа нет и 1, если ключ есть.",en:""}},arraySum:{bracket:"([func,] arr1, ...)",desc:{en:"Returns the sum of the 'func' values. If the function is omitted, it just returns the sum of the array elements."}},emptyArrayDateTime:{bracket:"(v)",desc:{en:"Accepts zero arguments and returns an empty array of the appropriate type."}},intDivOrZero:{bracket:"(a, b)",desc:{en:"Differs from 'intDiv' in that it returns zero when dividing by zero or when dividing a minimal negative number by minus one."}},SEHierarchy:{bracket:"(v)",desc:{en:"Accepts a UInt8 number - the ID of the search engine from the Yandex.Metrica dictionary. Returns an array with a hierarchy of search engines. Similar to the 'regionHierarchy' function."}},regionToContinent:{bracket:"(id[, geobase])",desc:{en:"Converts a region to a continent. In every other way, this function is the same as 'regionToCity'.
Example: %%regionToContinent(toUInt32(213)) = 10001%% converts Moscow (213) to Eurasia (10001)."}},dictGetInt32:{bracket:"(v)",desc:{ru:"",en:""}},toInt8:{bracket:"(v)",desc:{en:"Functions for converting between numbers, strings (but not fixed strings), dates, and dates with times. All these functions accept one argument. "}},materialize:{bracket:"(x)",desc:{en:"Turns a constant into a full column containing just one value.
In ClickHouse, full columns and constants are represented differently in memory. Functions work differently for constant arguments and normal arguments (different code is executed), although the result is almost always the same. This function is for debugging this behavior."}},regionToCountry:{bracket:"(id[, geobase])",desc:{en:"Converts a region to a country. In every other way, this function is the same as 'regionToCity'.
Example: %%regionToCountry(toUInt32(213)) = 225%% converts Moscow (213) to Russia (225)."}},dictGetDateTime:{bracket:"(v)",desc:{ru:"",en:""}},xor:{bracket:"(v)",desc:{ru:"",en:""}},regionToCity:{bracket:"(id[, geobase])",desc:{en:"Accepts a UInt32 number - the region ID from the Yandex geobase. If this region is a city or part of a city, it returns the region ID for the appropriate city. Otherwise, returns 0."}},dictGetFloat64:{bracket:"(v)",desc:{ru:"",en:""}},timeSlot:{bracket:"(StartTime, Duration)",desc:{en:"For a time interval starting at 'StartTime' and continuing for 'Duration' seconds, it returns an array of moments in time, consisting of points from this interval rounded down to the half hour."}},toTime:{bracket:"(v)",desc:{en:"Converts a date with time to the date of the start of the Unix Epoch, while preserving the time."}},log2:{bracket:"(x)",desc:{en:"Accepts a numeric argument and returns a Float64 number close to the binary logarithm of the argument."}},toRelativeHourNum:{bracket:"(v)",desc:{en:"Converts a date with time or date to the number of the hour, starting from a certain fixed point in the past."}},toRelativeDayNum:{bracket:"(v)",desc:{en:"Converts a date with time or date to the number of the day, starting from a certain fixed point in the past."}},toRelativeWeekNum:{bracket:"(v)",desc:{en:"Converts a date with time or date to the number of the week, starting from a certain fixed point in the past."}},splitByString:{bracket:"(separator, s)",desc:{en:"The same as above, but it uses a string of multiple characters as the separator. The string must be non-empty."}},currentDatabase:{bracket:"()",desc:{en:"Returns the name of the current database.
You can use this function in table engine parameters in a CREATE TABLE query where you need to specify the database."}},toRelativeMonthNum:{bracket:"(v)",desc:{en:"Converts a date with time or date to the number of the month, starting from a certain fixed point in the past."}},visibleWidth:{bracket:"(x)",desc:{en:"Calculates the approximate width when outputting values to the console in text format (tab-separated). This function is used by the system for implementing Pretty formats."}},bitShiftRight:{bracket:"(a, b)",desc:{en:""}},toRelativeYearNum:{bracket:"(v)",desc:{en:"Converts a date with time or date to the number of the year, starting from a certain fixed point in the past."}},toStartOfHour:{bracket:"(v)",desc:{en:"Rounds down a date with time to the start of the hour."}},halfMD5:{bracket:"(v)",desc:{en:"Calculates the MD5 from a string. Then it takes the first 8 bytes of the hash and interprets them as UInt64 in big endian."}},toStartOfFiveMinute:{bracket:"(v)",desc:{en:""}},toUInt16OrZero:{bracket:"(v)",desc:{en:"Functions for converting between numbers, strings (but not fixed strings), dates, and dates with times. All these functions accept one argument."}},toMonday:{bracket:"(v)",desc:{en:"Rounds down a date or date with time to the nearest Monday.
Returns the date."}},IPv6NumToString:{bracket:"(x)",desc:{en:"Accepts a FixedString(16) value containing the IPv6 address in binary format. Returns a string containing this address in text format. "}},indexOf:{bracket:"(arr, x)",desc:{ru:"Возвращает индекс элемента x (начиная с 1), если он есть в массиве, или 0, если его нет.",en:"Returns the index of the 'x' element (starting from 1) if it is in the array, or 0 if it is not."}},today:{bracket:"(v)",desc:{ru:"Принимает ноль аргументов и возвращает текущую дату на один из моментов выполнения запроса.
То же самое, что toDate(now())",en:"Accepts zero arguments and returns the current date at one of the moments of request execution.
The same as 'toDate(now())'."}},emptyArrayToSingle:{bracket:"(v)",desc:{ru:"Принимает пустой массив и возвращает массив из одного элемента, равного значению по умолчанию.",en:"Accepts an empty array as argument and returns an array of one element equal to the default value."}},sleep:{bracket:"(seconds)",desc:{ru:"Спит seconds секунд на каждый блок данных. Можно указать как целое число, так и число с плавающей запятой.",en:"Sleeps 'seconds' seconds on each data block. You can specify an integer or a floating-point number."}},extract:{bracket:"(params, name)",desc:{en:"Parses the string in double quotes. The value is unescaped. If unescaping failed, it returns an empty string. Examples: "}},emptyArrayInt8:{bracket:"(v)",desc:{ru:"Принимает ноль аргументов и возвращает пустой массив соответствующего типа.",en:"Accepts zero arguments and returns an empty array of the appropriate type."}},regionToName:{bracket:"(id[, lang])",desc:{en:"Accepts a UInt32 number - the region ID from the Yandex geobase. A string with the name of the language can be passed as a second argument. Supported languages are: ru, en, ua, uk, by, kz, tr. If the second argument is omitted, the language 'ru' is used. "}},concat:{bracket:"(arr[, separator])",desc:{ru:"Склеивает строки, перечисленные в массиве, с разделителем separator.
separator - необязательный параметр, константная строка, по умолчанию равен пустой строке.
Возвращается строка.",en:"Concatenates strings from the array elements, using 'separator' as the separator.
'separator' is a string constant, an optional parameter. By default it is an empty string.
Returns a string."}},convertCharset:{bracket:"(s, from, to)",desc:{ru:"Возвращает сконвертированную из кодировки from в кодировку to строку s.",en:"Returns a string with the data %%s%% (encoded as %%from%% charset) that was converted to the %%to%% charset."}},toMonth:{bracket:"(v)",desc:{ru:"Переводит дату или дату-с-временем в число типа UInt8, содержащее номер месяца (1-12).",en:"Converts a date or date with time to a UInt8 number containing the month number (1-12)."}},IPv6StringToNum:{bracket:"(s)",desc:{ru:"Функция, обратная к IPv6NumToString. Если IPv6 адрес в неправильном формате, то возвращает строку из нулевых байт.
HEX может быть в любом регистре.",en:"The reverse function of IPv6NumToString. If the IPv6 address has an invalid format, it returns a string of null bytes.
HEX can be uppercase or lowercase."}},emptyArrayString:{bracket:"(v)",desc:{ru:"Принимает ноль аргументов и возвращает пустой массив соответствующего типа.",en:"Accepts zero arguments and returns an empty array of the appropriate type."}},uptime:{bracket:"()",desc:{ru:"Возвращает аптайм сервера в секундах.",en:"Returns server's uptime in seconds."}},blockSize:{bracket:"()",desc:{en:"Gets the size of the block.
In ClickHouse, queries are always run on blocks (sets of column parts). This function allows getting the size of the block that you called it for."}},toInt64OrZero:{bracket:"(v)",desc:{en:"Functions for converting between numbers, strings (but not fixed strings), dates, and dates with times. All these functions accept one argument. "}},pathFull:{bracket:"(v)",desc:{ru:"То же самое, но включая query string и fragment. Пример: /top/news.html?page=2#comments",en:"- The same as above, but including query-string and fragment. Example: /top/news.html?page=2#comments"}},emptyArrayDate:{bracket:"(v)",desc:{ru:"Принимает ноль аргументов и возвращает пустой массив соответствующего типа.",en:"Accepts zero arguments and returns an empty array of the appropriate type."}},emptyArrayInt64:{bracket:"(v)",desc:{ru:"Принимает ноль аргументов и возвращает пустой массив соответствующего типа.",en:"Accepts zero arguments and returns an empty array of the appropriate type."}},toInt32OrZero:{bracket:"(v)",desc:{en:"Functions for converting between numbers, strings (but not fixed strings), dates, and dates with times. All these functions accept one argument. "}},greater:{bracket:"(v)",desc:{ru:"",en:""}},emptyArrayInt32:{bracket:"(v)",desc:{ru:"Принимает ноль аргументов и возвращает пустой массив соответствующего типа.",en:"Accepts zero arguments and returns an empty array of the appropriate type."}},toString:{bracket:"(str)",desc:{ru:"Принимает значение типа FixedString(16). Возвращает строку из 36 символов в текстовом виде.",en:"Accepts a FixedString(16) value containing the UUID in the binary format. Returns a readable string containing the UUID in the text format."}},greatest:{bracket:"(a, b)",desc:{ru:"Возвращает наибольшее значение из a и b.",en:"Returns the greatest element of a and b."}},emptyArrayUInt64:{bracket:"(v)",desc:{ru:"Принимает ноль аргументов и возвращает пустой массив соответствующего типа.",en:"Accepts zero arguments and returns an empty array of the appropriate type."}},emptyArrayUInt32:{bracket:"(v)",desc:{ru:"Принимает ноль аргументов и возвращает пустой массив соответствующего типа.",en:"Accepts zero arguments and returns an empty array of the appropriate type."}},formatReadableSize:{bracket:"(x)",desc:{en:"Gets a size (number of bytes). Returns a string that contains rounded size with the suffix (KiB, MiB etc.).

Example:

%% "}},toInt16OrZero:{bracket:"(v)",desc:{en:"Functions for converting between numbers, strings (but not fixed strings), dates, and dates with times. All these functions accept one argument. "}},emptyArrayUInt8:{bracket:"(v)",desc:{ru:"Принимает ноль аргументов и возвращает пустой массив соответствующего типа.",en:"Accepts zero arguments and returns an empty array of the appropriate type."}},protocol:{bracket:"(v)",desc:{ru:"Возвращает протокол. Примеры: http, ftp, mailto, magnet...",en:"- Selects the protocol. Examples: http, ftp, mailto, magnet..."}},regionToPopulation:{bracket:"(id[, geobase])",desc:{en:"Gets the population for a region.
The population can be recorded in files with the geobase. See the section "External dictionaries".
If the population is not recorded for the region, it returns 0.
In the Yandex geobase, the population might be recorded for child regions, but not for parent regions."}},notIn:{bracket:"(v)",desc:{ru:'Смотрите раздел "Операторы IN".',en:"See the section "IN operators"."}},position:{bracket:"(haystack, needle)",desc:{en:"The same as 'position', but the position is returned in Unicode code points. Works under the assumption that the string contains a set of bytes representing a UTF-8 encoded text. If this assumption is not met, it returns some result (it doesn't throw an exception).
There's also positionCaseInsensitiveUTF8 function."}},arrayElement:{bracket:"(arr, n), arr[n] operator",desc:{en:"Get the element with the index 'n' from the array 'arr'.
'n' should be any integer type.
Indexes in an array begin from one.
Negative indexes are supported - in this case, it selects the corresponding element numbered from the end. "}},toStringCutToZero:{bracket:"(s)",desc:{en:"Accepts a String or FixedString argument. Returns a String that is cut to a first null byte occurrence."}},log:{bracket:"(x)",desc:{ru:"Принимает числовой аргумент, возвращает число типа Float64, близкое к десятичному логарифму от аргумента.",en:"Accepts a numeric argument and returns a Float64 number close to the decimal logarithm of the argument."}},SEIn:{bracket:"(lhs, rhs)",desc:{ru:"Проверяет принадлежность поисковой системы lhs поисковой системе rhs.",en:"Checks whether the 'lhs' search engine belongs to the 'rhs' search engine."}},replicate:{bracket:"(v)",desc:{en:"Create a MergeTree table with a different name. Move all the data from the directory with the ReplicatedMergeTree table data to the new table's data directory."}},sipHash64:{bracket:"(v)",desc:{en:'Calculates SipHash from a string.
Accepts a String-type argument. Returns UInt64.
SipHash is a cryptographic hash function. It works at least three times faster than MD5. For more information, see https://131002.net/siphash/'}},emptyArrayUInt16:{bracket:"(v)",desc:{en:"Accepts zero arguments and returns an empty array of the appropriate type."}},hex:{bracket:"(str)",desc:{en:"Accepts a string containing any number of hexadecimal digits, and returns a string containing the corresponding bytes. Supports both uppercase and lowercase letters A-F. The number of hexadecimal digits doesn't have to be even."}},regionToDistrict:{bracket:"(id[, geobase])",desc:{en:"Converts a region to a federal district (type 4 in the geobase). In every other way, this function is the same as 'regionToCity'. "}},arrayFilter:{bracket:"(func, arr1, ...)",desc:{en:"Returns an array containing only the elements in 'arr1' for which 'func' returns something other than 0.

Examples:

%%
SELECT arrayFilter(x -> x LIKE '%World%', ['Hello', 'abc World']) AS res "}},toStartOfQuarter:{bracket:"(v)",desc:{en:"Rounds down a date or date with time to the first day of the quarter.
The first day of the quarter is either 1 January, 1 April, 1 July, or 1 October. Returns the date."}},divide:{bracket:"(a, b), a / b operator",desc:{en:"Calculates the quotient of the numbers. The result type is always a floating-point type.
It is not integer division. For integer division, use the 'intDiv' function.
When dividing by zero you get 'inf', '-inf', or 'nan'."}},reverseUTF8:{bracket:"(v)",desc:{en:"Reverses a sequence of Unicode code points, assuming that the string contains a set of bytes representing a UTF-8 text. Otherwise, it does something else (it doesn't throw an exception)."}},toDate:{bracket:"(v)",desc:{en:"Functions for converting between numbers, strings (but not fixed strings), dates, and dates with times. All these functions accept one argument. "}},emptyArrayFloat64:{bracket:"(v)",desc:{en:"Accepts zero arguments and returns an empty array of the appropriate type."}},abs:{bracket:"(s, c)",desc:{en:"If the %%s%% string is non-empty and does not contain the %%c%% character at the end, it appends the %%c%% character to the end."}},yesterday:{bracket:"(v)",desc:{en:"Accepts zero arguments and returns yesterday's date at one of the moments of request execution.
The same as 'today() - 1'."}},toMinute:{bracket:"(v)",desc:{en:"Converts a date with time to a UInt8 number containing the number of the minute of the hour (0-59)."}},bitXor:{bracket:"(a, b)",desc:{en:""}},minus:{bracket:"(a, b), a - b operator",desc:{en:"Calculates the difference. The result is always signed.

You can also calculate whole numbers from a date or date with time. The idea is the same - see above for 'plus'."}},toDateTime:{bracket:"(v)",desc:{en:"Functions for converting between numbers, strings (but not fixed strings), dates, and dates with times. All these functions accept one argument. "}},modulo:{bracket:"(a, b), a % b operator",desc:{en:"Calculates the remainder after division.
If arguments are floating-point numbers, they are pre-converted to integers by dropping the decimal portion. The remainder is taken in the same sense as in C++. Truncated division is used for negative numbers.
An exception is thrown when dividing by zero or when dividing a minimal negative number by minus one."}},bitmaskToArray:{bracket:"(num)",desc:{en:"Accepts an integer. Returns an array of UInt64 numbers containing the list of powers of two that total the source number when summed. Numbers in the array are in ascending order."}},negate:{bracket:"(a), -a operator",desc:{en:"Calculates a number with the reverse sign. The result is always signed."}},emptyArrayFloat32:{bracket:"(v)",desc:{en:"Accepts zero arguments and returns an empty array of the appropriate type."}},range:{bracket:"(N)",desc:{en:"Returns an array of numbers from 0 to N-1.
Just in case, an exception is thrown if arrays with a total length of more than 100,000,000 elements are created in a data block."}},arrayAll:{bracket:"([func,] arr1, ...)",desc:{en:"Returns 1 if 'func' returns something other than 0 for all the elements in 'arr'. Otherwise, it returns 0."}},toInt32:{bracket:"(v)",desc:{en:"Functions for converting between numbers, strings (but not fixed strings), dates, and dates with times. All these functions accept one argument. "}},unhex:{bracket:"(str)",desc:{en:"Accepts a string containing any number of hexadecimal digits, and returns a string containing the corresponding bytes. Supports both uppercase and lowercase letters A-F. The number of hexadecimal digits doesn't have to be even. If it is odd, the last digit is interpreted as the younger half of the 00-0F byte. If the argument string contains anything other than hexadecimal digits, some implementation-defined result is returned (an exception isn't thrown).
If you want to convert the result to a number, you can use the functions 'reverse' and 'reinterpretAsType'."}},toFloat64:{bracket:"(v)",desc:{en:"Functions for converting between numbers, strings (but not fixed strings), dates, and dates with times. All these functions accept one argument. "}},bitAnd:{bracket:"(a, b)",desc:{ru:"",en:""}},toStartOfYear:{bracket:"(v)",desc:{en:"Rounds down a date or date with time to the first day of the year.
Returns the date."}},bitOr:{bracket:"(a, b)",desc:{ru:"",en:""}},SEToRoot:{bracket:"(v)",desc:{en:"Accepts a UInt8 number - the ID of the search engine from the Yandex.Metrica dictionary. If any search engine matches the passed number, it returns a UInt8 number - the ID of the corresponding root search engine (for example, it converts Yandex.Images to Yandex). Otherwise, returns 0."}},toRelativeMinuteNum:{bracket:"(v)",desc:{en:"Converts a date with time or date to the number of the minute, starting from a certain fixed point in the past."}},visitParamExtractInt:{bracket:"(params, name)",desc:{ru:"Аналогично для Int64.",en:"The same as for Int64."}},emptyArrayInt16:{bracket:"(v)",desc:{en:"Accepts zero arguments and returns an empty array of the appropriate type."}},visitParamExtractString:{bracket:"(params, name)",desc:{en:"Parses the string in double quotes. The value is unescaped. If unescaping failed, it returns an empty string. "}},arrayEnumerateUniq:{bracket:"(arr, ...)",desc:{en:"Returns an array the same size as the source array, indicating for each element what its position is among elements with the same value. "}},visitParamExtractUInt:{bracket:"(params, name)",desc:{en:"Parses UInt64 from the value of the field named 'name'. If this is a string field, it tries to parse a number from the beginning of the string. If the field doesn't exist, or it exists but doesn't contain a number, it returns 0."}},toTypeName:{bracket:"(x)",desc:{en:"Gets the type name. Returns a string containing the type name of the passed argument."}},empty:{bracket:"(v)",desc:{en:"Accepts an empty array as argument and returns an array of one element equal to the default value."}},multiply:{bracket:"(a, b), a * b operator", -desc:{en:"Calculates the product of the numbers."}},has:{bracket:"('database', 'table', 'column')",desc:{ru:"",en:"Accepts constant String columns - database name, table name and column name. Returns constant UInt8 value, equal to 1 if column exists,
otherwise 0.
If table doesn't exist than exception is thrown.
For elements of nested data structure function checks existence of column. For nested data structure 0 is returned."}},bitNot:{bracket:"(a)",desc:{ru:"",en:""}},lessOrEquals:{bracket:"(v)",desc:{ru:"",en:"

greaterOrEquals, >= operator

"}},reinterpretAsInt64:{bracket:"(v)",desc:{en:""}},IPv4NumToString:{bracket:"(num)",desc:{en:"Similar to IPv4NumToString, but using %%xxx%% instead of the last octet. "}},bitShiftLeft:{bracket:"(a, b)",desc:{ru:"",en:""}},dictGetInt16:{bracket:"(v)",desc:{ru:"",en:""}},toUInt32OrZero:{bracket:"(v)",desc:{en:"Functions for converting between numbers, strings (but not fixed strings), dates, and dates with times. All these functions accept one argument. "}},regionIn:{bracket:"(lhs, rhs[, geobase])",desc:{en:"Checks whether a 'lhs' region belongs to a 'rhs' region. Returns a UInt8 number equal to 1 if it belongs, or 0 if it doesn't belong.
The relationship is reflexive - any region also belongs to itself."}},reinterpretAsUInt8:{bracket:"(v)",desc:{en:""}},dictIsIn:{bracket:"(v)",desc:{en:"%%dictIsIn('dict_name', child_id, ancestor_id)%%
- For the 'dict_name' hierarchical dictionary, finds out whether the 'child_id' key is located inside 'ancestor_id' (or matches 'ancestor_id'). Returns UInt8."}},toSecond:{bracket:"(v)",desc:{en:"Converts a date with time to a UInt8 number containing the number of the second in the minute (0-59).
Leap seconds are not accounted for."}},least:{bracket:"(a, b)",desc:{en:"Returns the least element of a and b."}},countEqual:{bracket:"(arr, x)",desc:{en:'Returns the number of elements in the array equal to 'x'. Equivalent to arrayCount(elem -> elem = x, arr).'}},IPv4StringToNum:{bracket:"(s)",desc:{en:"The reverse function of IPv4NumToString. If the IPv4 address has an invalid format, it returns 0."}},replaceRegexpAll:{bracket:"(haystack, pattern, replacement)",desc:{en:"This does the same thing, but replaces all the occurrences"}},SHA224:{bracket:"(v)",desc:{en:"Calculates SHA-1, SHA-224, or SHA-256 from a string and returns the resulting set of bytes as FixedString(20), FixedString(28), or FixedString(32).
The function works fairly slowly (SHA-1 processes about 5 million short strings per second per processor core, while SHA-224 and SHA-256 process about 2.2 million). "}},URLHash:{bracket:"(url[, N])",desc:{en:"A fast, decent-quality non-cryptographic hash function for a string obtained from a URL using some type of normalization.
URLHash(s) - Calculates a hash from a string without one of the trailing symbols /,? or # at the end, if present"}},equals:{bracket:"(v)",desc:{ru:"",en:"

greaterOrEquals, >= operator

"}},plus:{bracket:"(a, b), a + b operator",desc:{ru:"Вычисляет сумму чисел.

Также можно складывать целые числа с датой и датой-с-временем. В случае даты, прибавление целого числа означает прибавление соответствующего количества дней. В случае даты-с-временем - прибавление соответствующего количества секунд.",en:"Calculates the sum of the numbers.

You can also add whole numbers with a date or date and time. In the case of a date, adding a whole number means adding the corresponding number of days. For a date with time, it means adding the corresponding number of seconds."}},less:{bracket:"(v)",desc:{ru:"",en:"

greaterOrEquals, >= operator

"}},regionHierarchy:{bracket:"(id[, geobase])",desc:{en:"Accepts a UInt32 number - the region ID from the Yandex geobase. Returns an array of region IDs consisting of the passed region and all parents along the chain.
Example: %%regionHierarchy(toUInt32(213)) = [213,1,3,225,10001,10000]%%."}},toUInt64OrZero:{bracket:"(v)",desc:{en:"Functions for converting between numbers, strings (but not fixed strings), dates, and dates with times. All these functions accept one argument. "}},rowNumberInAllBlocks:{bracket:"()",desc:{en:"Returns an incremental row number within all blocks that were processed by this function."}},toDayOfWeek:{bracket:"(v)",desc:{en:"Converts a date or date with time to a UInt8 number containing the number of the day of the week (Monday is 1, and Sunday is 7)."}},bar:{bracket:"(v)",desc:{en:"Allows building a unicode-art diagram.

bar(x, min, max, width) - Draws a band with a width proportional to (x - min) and equal to 'width' characters when x"}},"if":{bracket:"(v)",desc:{en:"The suffix -%%If%% can be appended to the name of any aggregate function. In this case, the aggregate function accepts an extra argument - a condition (Uint8 type). "}},regionToArea:{bracket:"(id[, geobase])",desc:{en:"Converts a region to an area (type 5 in the geobase). In every other way, this function is the same as 'regionToCity'.──────────────────────────────────"}},dictGetUInt16:{bracket:"(v)",desc:{ru:"",en:""}},toUInt8:{bracket:"(v)",desc:{en:"Functions for converting between numbers, strings (but not fixed strings), dates, and dates with times. All these functions accept one argument. "}},toUInt16:{bracket:"(v)",desc:{en:"Functions for converting between numbers, strings (but not fixed strings), dates, and dates with times. All these functions accept one argument. "}},path:{bracket:"(URL)",desc:{en:"- The same thing, but without the protocol and host in the result. The / element (root) is not included."}},extractURLParameters:{bracket:"(URL)",desc:{ru:"Возвращает массив строк вида name=value, соответствующих параметрам URL. Значения никак не декодируются.",en:"- Gets an array of name=value strings corresponding to the URL parameters. The values are not decoded in any way."}},OSHierarchy:{bracket:"(v)",desc:{ru:"Принимает число типа UInt8 - идентификатор операционной системы из словаря Яндекс.Метрики. Возвращает массив с иерархией операционных систем. Аналогично функции regionHierarchy.",en:"Accepts a UInt8 number - the ID of the operating system from the Yandex.Metrica dictionary. Returns an array with a hierarchy of operating systems. Similar to the 'regionHierarchy' function."}},cutQueryStringAndFragment:{bracket:"(v)",desc:{ru:"Удаляет query string и fragment identifier. Знак вопроса и символ решётки тоже удаляются.",en:"Removes the query-string and fragment identifier. The question mark and number sign are also removed."}},timeSlots:{bracket:"(StartTime, Duration)",desc:{ru:"Для интервала времени, начинающегося в StartTime и продолжающегося Duration секунд, возвращает массив моментов времени, состоящий из округлений вниз до получаса точек из этого интервала.
Например, %%timeSlots(toDateTime('2012-01-01 12:20:00'), toUInt32(600)) = [toDateTime('2012-01-01 12:00:00'), toDateTime('2012-01-01 12:30:00')]%%.
Это нужно для поиска хитов, входящих в соответствующий визит.",en:"For a time interval starting at 'StartTime' and continuing for 'Duration' seconds, it returns an array of moments in time, consisting of points from this interval rounded down to the half hour.
For example, %%timeSlots(toDateTime('2012-01-01 12:20:00'), toUInt32(600)) = [toDateTime('2012-01-01 12:00:00'), toDateTime('2012-01-01 12:30:00')]%%.
This is necessary for searching for pageviews in the corresponding session."}},toUInt32:{bracket:"(v)",desc:{en:"Functions for converting between numbers, strings (but not fixed strings), dates, and dates with times. All these functions accept one argument. "}},toStartOfMinute:{bracket:"(v)",desc:{ru:"Округляет дату-с-временем вниз до начала минуты.",en:"Rounds down a date with time to the start of the minute."}},version:{bracket:"()",desc:{ru:"Возвращает версию сервера в виде строки.",en:"Returns server's version as a string."}},toUInt64:{bracket:"(v)",desc:{en:"Functions for converting between numbers, strings (but not fixed strings), dates, and dates with times. All these functions accept one argument. "}},toInt16:{bracket:"(v)",desc:{en:"Functions for converting between numbers, strings (but not fixed strings), dates, and dates with times. All these functions accept one argument. "}},reinterpretAsInt16:{bracket:"(v)",desc:{en:""}},toInt64:{bracket:"(v)",desc:{en:"Functions for converting between numbers, strings (but not fixed strings), dates, and dates with times. All these functions accept one argument. "}},toFixedString:{bracket:"(s, N)",desc:{ru:"Преобразует аргумент типа String в тип FixedString(N) (строку фиксированной длины N). N должно быть константой.
Если строка имеет меньше байт, чем N, то она дополняется нулевыми байтами справа. Если строка имеет больше байт, чем N - кидается исключение.",en:"Converts a String type argument to a FixedString(N) type (a string with fixed length N). N must be a constant. If the string has fewer bytes than N, it is passed with null bytes to the right. If the string has more bytes than N, an exception is thrown."}},toFloat32:{bracket:"(v)",desc:{en:"Functions for converting between numbers, strings (but not fixed strings), dates, and dates with times. All these functions accept one argument. "}},dictGetHierarchy:{bracket:"(v)",desc:{ru:"%%dictGetHierarchy('dict_name', id)%%
- для иерархического словаря dict_name - вернуть массив ключей словаря, начиная с id и продолжая цепочкой родительских элементов. Возвращает Array(UInt64).",en:"%%dictGetHierarchy('dict_name', id)%%
- For the 'dict_name' hierarchical dictionary, returns an array of dictionary keys starting from 'id' and continuing along the chain of parent elements. Returns Array(UInt64)."}},dictGetInt64:{bracket:"(v)",desc:{ru:"",en:""}},CAST:{bracket:"(x, t)",desc:{en:"Casts x to the t data type.
The syntax %%CAST(x AS t)%% is also supported.
"}},toRelativeSecondNum:{bracket:"(v)",desc:{ru:"Переводит дату-с-временем в номер секунды, начиная с некоторого фиксированного момента в прошлом.",en:"Converts a date with time or date to the number of the second, starting from a certain fixed point in the past."}},toUInt8OrZero:{bracket:"(v)",desc:{en:"Functions for converting between numbers, strings (but not fixed strings), dates, and dates with times. All these functions accept one argument. "}},toStartOfMonth:{bracket:"(v)",desc:{ru:"Округляет дату или дату-с-временем вниз до первого дня месяца.
Возвращается дата.",en:"Rounds down a date or date with time to the first day of the month.
Returns the date."}},rand64:{bracket:"(v)",desc:{ru:"Возвращает псевдослучайное число типа UInt64, равномерно распределённое среди всех чисел типа UInt64.
Используется linear congruential generator.",en:"Returns a pseudo-random UInt64 number, evenly distributed among all UInt64-type numbers.
Uses a linear congruential generator."}},toInt8OrZero:{bracket:"(v)",desc:{en:"Functions for converting between numbers, strings (but not fixed strings), dates, and dates with times. All these functions accept one argument. "}},toFloat32OrZero:{bracket:"(v)",desc:{en:"Functions for converting between numbers, strings (but not fixed strings), dates, and dates with times. All these functions accept one argument. "}},toYear:{bracket:"(v)",desc:{ru:"Переводит дату или дату-с-временем в число типа UInt16, содержащее номер года (AD).",en:"Converts a date or date with time to a UInt16 number containing the year number (AD)."}},atan:{bracket:"(x)",desc:{ru:"Арктангенс.",en:"The arc tangent."}},toFloat64OrZero:{bracket:"(v)",desc:{en:"Functions for converting between numbers, strings (but not fixed strings), dates, and dates with times. All these functions accept one argument. "}},arrayEnumerate:{bracket:"(arr, ...)",desc:{en:"Returns an array the same size as the source array, indicating for each element what its position is among elements with the same value.
"}},toDayOfMonth:{bracket:"(v)",desc:{en:"Converts a date or date with time to a UInt8 number containing the number of the day of the month (1-31)."}},dictGetUInt64:{bracket:"(v)",desc:{ru:"",en:""}},IPv4NumToStringClassC:{bracket:"(num)",desc:{en:"Similar to IPv4NumToString, but using %%xxx%% instead of the last octet. "}},reinterpretAsString:{bracket:"(v)",desc:{en:"This function accepts a number or date or date with time, and returns a string containing bytes representing the corresponding value in host order (little endian). Null bytes are dropped from the end. For example, a UInt32 type value of 255 is a string that is one byte long."}},toHour:{bracket:"(v)",desc:{en:"Converts a date with time to a UInt8 number containing the number of the hour in 24-hour time (0-23).
This function assumes that if clocks are moved ahead, it is by one hour and occurs at 2 a.m., and if clocks are moved back, it is by one hour and occurs at 3 a.m. (which is not always true - even in Moscow the clocks were once changed at a different time)."}},ignore:{bracket:"(...)",desc:{en:"A function that accepts any arguments and always returns 0.
However, the argument is still calculated. This can be used for benchmarks."}},arrayJoin:{bracket:"(v)",desc:{en:"This is a very unusual function.

Normal functions don't change a set of rows, but just change the values in each row (map). Aggregate functions compress a set of rows (fold or reduce).
The 'arrayJoin' function takes each row and generates a set of rows (unfold).

T"}},length:{bracket:"(v)",desc:{en:"Returns the length of a string in Unicode code points (not in characters), assuming that the string contains a set of bytes that make up UTF-8 encoded text. If this assumption is not met, it returns some result (it doesn't throw an exception).
The result type is UInt64."}},tuple:{bracket:"(tuple, n), operator x.N",desc:{en:"A function that allows getting columns from a tuple.
'N' is the column index, starting from 1. 'N' must be a constant. 'N' must be a strict postive integer no greater than the size of the tuple.
There is no cost to execute the function."}},extractURLParameterNames:{bracket:"(URL)",desc:{en:"- Gets an array of name=value strings corresponding to the names of URL parameters. The values are not decoded in any way."}},tupleElement:{bracket:"(tuple, n), operator x.N",desc:{en:"A function that allows getting columns from a tuple.
'N' is the column index, starting from 1. 'N' must be a constant. 'N' must be a strict postive integer no greater than the size of the tuple.
There is no cost to execute the function."}},"in":{bracket:"(v)",desc:{en:"What to do when the amount of data exceeds one of the limits: 'throw' or 'break'. By default, throw."}},globalIn:{bracket:"(v)",desc:{en:"See the section "IN operators"."}},isFinite:{bracket:"(x)",desc:{en:"Accepts Float32 and Float64 and returns UInt8 equal to 1 if the argument is not infinite and not a NaN, otherwise 0."}},isNaN:{bracket:"(x)",desc:{en:"Accepts Float32 and Float64 and returns UInt8 equal to 1 if the argument is a NaN, otherwise 0."}},isInfinite:{bracket:"(x)",desc:{en:"Accepts Float32 and Float64 and returns UInt8 equal to 1 if the argument is infinite, otherwise 0.
Note that 0 is returned for a NaN."}},transform:{bracket:"(v)",desc:{en:"Transforms a value according to the explicitly defined mapping of some elements to other ones.
There are two variations of this function:

1. %%transform(x, array_from, array_to, default)%% "}},rand:{bracket:"(v)",desc:{en:"Returns a pseudo-random UInt64 number, evenly distributed among all UInt64-type numbers.
Uses a linear congruential generator."}},reinterpretAsUInt16:{bracket:"(v)",desc:{en:""}},pi:{bracket:"(v)",desc:{en:"Maximum pipeline depth. Corresponds to the number of transformations that each data block goes through during query processing. Counted within the limits of a single server. If the pipeline depth is greater, an exception is thrown. By default, 1000."}},reinterpretAsUInt32:{bracket:"(v)",desc:{en:""}},reinterpretAsUInt64:{bracket:"(v)",desc:{en:""}},reinterpretAsInt8:{bracket:"(v)",desc:{en:""}},upperUTF8:{bracket:"(v)",desc:{en:"Converts a string to uppercase, assuming the string contains a set of bytes that make up a UTF-8 encoded text. It doesn't detect the language. So for Turkish the result might not be exactly correct. "}},reinterpretAsInt32:{bracket:"(v)",desc:{en:""}},reinterpretAsFloat32:{bracket:"(v)",desc:{en:""}},reinterpretAsFloat64:{bracket:"(v)",desc:{en:""}},reinterpretAsDate:{bracket:"(v)",desc:{en:""}},reinterpretAsDateTime:{bracket:"(v)",desc:{en:""}},roundToExp2:{bracket:"(num)",desc:{en:"Accepts a number. If the number is less than one, it returns 0. Otherwise, it rounds the number down to the nearest (whole non-negative) degree of two."}},upper:{bracket:"(v)",desc:{en:"Converts a string to uppercase, assuming the string contains a set of bytes that make up a UTF-8 encoded text. It doesn't detect the language. So for Turkish the result might not be exactly correct."}},positionUTF8:{bracket:"(haystack, needle)",desc:{en:"The same as 'position', but the position is returned in Unicode code points. Works under the assumption that the string contains a set of bytes representing a UTF-8 encoded text. If this assumption is not met, it returns some result (it doesn't throw an exception).
There's also positionCaseInsensitiveUTF8 function."}},roundDuration:{bracket:"(num)",desc:{en:"Accepts a number. If the number is less than one, it returns 0. Otherwise, it rounds the number down to numbers from the set: 1, 10, 30, 60, 120, 180, 240, 300, 600, 1200, 1800, 3600, 7200, 18000, 36000. This function is specific to Yandex.Metrica and used for implementing the report on session length."}},roundAge:{bracket:"(num)",desc:{en:"Accepts a number. If the number is less than 18, it returns 0. Otherwise, it rounds the number down to numbers from the set: 18, 25, 35, 45. This function is specific to Yandex.Metrica and used for implementing the report on user age."}},round:{bracket:"(num)",desc:{en:"Accepts a number. If the number is less than 18, it returns 0. Otherwise, it rounds the number down to numbers from the set: 18, 25, 35, 45. This function is specific to Yandex.Metrica and used for implementing the report on user age."}},floor:{bracket:"(x[, N])",desc:{en:"Returns a rounder number that is less than or equal to 'x'."}},notEmpty:{bracket:"(v)",desc:{en:"Returns 0 for an empty array, or 1 for a non-empty array.
The result type is UInt8.
The function also works for strings."}},lengthUTF8:{bracket:"(v)",desc:{en:"Returns the length of a string in Unicode code points (not in characters), assuming that the string contains a set of bytes that make up UTF-8 encoded text. If this assumption is not met, it returns some result (it doesn't throw an exception).
The result type is UInt64."}},lower:{bracket:"(v)",desc:{en:"Converts a string to lowercase, assuming the string contains a set of bytes that make up a UTF-8 encoded text. It doesn't detect the language. "}},lowerUTF8:{bracket:"(v)",desc:{en:"Converts a string to lowercase, assuming the string contains a set of bytes that make up a UTF-8 encoded text. It doesn't detect the language. "}},reverse:{bracket:"(v)",desc:{en:"Reverses a sequence of Unicode code points, assuming that the string contains a set of bytes representing a UTF-8 text. Otherwise, it does something else (it doesn't throw an exception)."}},URLPathHierarchy:{bracket:"(URL)",desc:{en:"- The same thing, but without the protocol and host in the result. The / element (root) is not included. "}},substringUTF8:{bracket:"(s, offset, length)",desc:{en:"The same as 'substring', but for Unicode code points. Works under the assumption that the string contains a set of bytes representing a UTF-8 encoded text. If this assumption is not met, it returns some result (it doesn't throw an exception)."}},appendTrailingCharIfAbsent:{bracket:"(s, c)",desc:{en:"If the %%s%% string is non-empty and does not contain the %%c%% character at the end, it appends the %%c%% character to the end."}},alphaTokens:{bracket:"(s)",desc:{en:"Selects substrings of consecutive bytes from the range a-z and A-Z.
Returns an array of selected substrings."}},splitByChar:{bracket:"(separator, s)",desc:{en:"Splits a string into substrings, using 'separator' as the separator.
'separator' must be a string constant consisting of exactly one character.
Returns an array of selected substrings"}},arrayStringConcat:{bracket:"(arr[, separator])",desc:{en:"Concatenates strings from the array elements, using 'separator' as the separator.
'separator' is a string constant, an optional parameter. By default it is an empty string.
Returns a string."}},replaceAll:{bracket:"(haystack, pattern, replacement)",desc:{en:"Replaces all occurrences of the 'pattern' substring in 'haystack' with the 'replacement' substring."}},replaceRegexpOne:{bracket:"(haystack, pattern, replacement)",desc:{en:"Replacement using the 'pattern' regular expression. A re2 regular expression. Replaces only the first occurrence, if it exists.
A pattern can be specified as 'replacement'. "}},cbrt:{bracket:"(x)",desc:{en:"Accepts a numeric argument and returns a Float64 number close to the cubic root of the argument."}},match:{bracket:"(pattern)(time, cond1, cond2, ...)",desc:{en:"Pattern matching for event chains.

'pattern' is a string containing a pattern to match. The pattern is similar to a regular expression."}},cutURLParameter:{bracket:"(URL, name)",desc:{en:"Removes the URL parameter named 'name', if present. This function works under the assumption that the parameter name is encoded in the URL exactly the same way as in the passed argument."}},like:{bracket:"(haystack, pattern), haystack NOT LIKE pattern operator",desc:{en:"The same thing as 'like', but negative."}},domain:{bracket:"(v)",desc:{en:"- Selects the part of the domain that includes top-level subdomains up to the "first significant subdomain" (see the explanation above).
For example, cutToFirstSignificantSubdomain('https://news.yandex.com.tr/') = 'yandex.com.tr'."}},domainWithoutWWW:{bracket:"(v)",desc:{en:"- Selects the domain and removes no more than one 'www.' from the beginning of it, if present."}},firstSignificantSubdomain:{bracket:"(v)",desc:{en:"- Selects the part of the domain that includes top-level subdomains up to the "first significant subdomain" (see the explanation above).
For example, cutToFirstSignificantSubdomain('https://news.yandex.com.tr/') = 'yandex.com.tr'."}},queryString:{bracket:"(v)",desc:{en:"Removes the query-string and fragment identifier. The question mark and number sign are also removed."}},queryStringAndFragment:{bracket:"(v)",desc:{en:"Removes the query-string and fragment identifier. The question mark and number sign are also removed."}},extractURLParameter:{bracket:"(URL)",desc:{en:"- Gets an array of name=value strings corresponding to the names of URL parameters. The values are not decoded in any way."}},URLHierarchy:{bracket:"(URL)",desc:{en:"- Gets an array containing the URL trimmed to the %%/%%, %%?%% characters in the path and query-string. Consecutive separator characters are counted as one. The cut is made in the position after all the consecutive separator characters. Example:"}},cutToFirstSignificantSubdomain:{bracket:"(v)",desc:{en:"- Selects the part of the domain that includes top-level subdomains up to the "first significant subdomain" (see the explanation above).
For example, cutToFirstSignificantSubdomain('https://news.yandex.com.tr/') = 'yandex.com.tr'."}},cutWWW:{bracket:"(v)",desc:{en:"Removes no more than one 'www.' from the beginning of the URL's domain, if present."}},cutQueryString:{bracket:"(v)",desc:{en:"Removes the query-string and fragment identifier. The question mark and number sign are also removed."}},cutFragment:{bracket:"(v)",desc:{en:"Removes the fragment identifier. The number sign is also removed."}},visitParamHas:{bracket:"(params, name)",desc:{en:"Checks whether there is a field with the 'name' name."}},visitParamExtractFloat:{bracket:"(params, name)",desc:{en:"The same as for Float64."}},visitParamExtractBool:{bracket:"(params, name)",desc:{en:"Parses a true/false value. The result is UInt8."}},visitParamExtractRaw:{bracket:"(params, name)",desc:{en:"Returns the value of a field, including separators."}},exp:{bracket:"(x)",desc:{en:"Accepts a numeric argument and returns a Float64 number close to 10x."}},exp2:{bracket:"(x)",desc:{en:"Accepts a numeric argument and returns a Float64 number close to 2x."}},exp10:{bracket:"(x)",desc:{en:"Accepts a numeric argument and returns a Float64 number close to 10x."}},tgamma:{bracket:"(x)",desc:{en:"Gamma function."}},log10:{bracket:"(x)",desc:{en:"Accepts a numeric argument and returns a Float64 number close to the decimal logarithm of the argument."}},sqrt:{bracket:"(x)",desc:{en:"Accepts a numeric argument and returns a Float64 number close to the square root of the argument."}},erf:{bracket:"(v)",desc:{en:"What to do when the amount of data exceeds one of the limits: 'throw' or 'break'. By default, throw."}},erfc:{bracket:"(x)",desc:{en:"Accepts a numeric argument and returns a Float64 number close to 1 - erf(x), but without loss of precision for large 'x' values."}},lgamma:{bracket:"(x)",desc:{en:"The logarithm of the gamma function."}},sin:{bracket:"(x)",desc:{en:"Accepts Float32 and Float64 and returns UInt8 equal to 1 if the argument is infinite, otherwise 0.
Note that 0 is returned for a NaN."}},cos:{bracket:"(x)",desc:{ru:"Арккосинус.",en:"The arc cosine."}},tan:{bracket:"(x)",desc:{ru:"Арктангенс.",en:"The arc tangent."}},pow:{bracket:"(x, y)",desc:{ru:"xy.",en:"xy."}}}},/* +function(e,t){function a(t,a,n){var r="";if("echarts"==t.draw.library){var i="macarons";t.isDark&&(i="dark"),t.draw.chart=echarts.init(a[0],i),r=!1}if("plotly"==t.draw.library&&(t.element=e.element('
 
'),r=!1),"c3"==t.draw.library){var s=document.createElement("div");t.draw.bindto=s,a[0].appendChild(s),r=!1}return"text"==t.draw.library&&(t.element=e.element('
 
'),r=!1),"d3"==t.draw.library&&console.info("DW:d3"),"gmaps"==t.draw.library&&(t.element=e.element('
 
'),r=!1),console.group("widget.draw.preProcessor"),console.time("widget.draw.preProcessor time took"),t.draw.preProcessor instanceof Function&&t.draw.preProcessor(),console.timeEnd("widget.draw.preProcessor time took"),console.groupEnd(),r}function n(t,n){return function(r,i,s){r.widget.type;if(console.time("drawWidget.buildLinkFunc"),r.widget.isDark=r.isdark,r.widget.preProcessor instanceof Function&&r.widget.preProcessor(),r.widget.error||r.widget.textformat||r.widget.text||r.widget.empty)return console.log("widget Have Error",r.widget.error),r.widget.error&&i.html("
"+r.widget.error+"
"),r.widget.text&&i.html("
"+r.widget.text+"
"),r.widget.empty&&i.html("NO DATA"),void i.addClass("grid-monospace");if("table"==r.widget.type&&(r.widget.element=e.element('
')),"draw"==r.widget.type){r.widget.element=!1;var o=a(r.widget,i,n);o&&(r.widget.element=e.element(o))}"pivot"==r.widget.type&&(r.widget.element=e.element('')),r.widget.element?(i.append(r.widget.element),t(r.widget.element)(r),r.widget.element.on("$destroy",r.widget.destroy(r.widget))):i.on("$destroy",r.widget.destroy(r.widget)),r.widget.postProcessor instanceof Function&&r.widget.postProcessor(),r.$watch(function(){return[i[0].offsetWidth,i[0].offsetHeight].join("x")},function(e){r.widget.scheduledResize()}),r.events={resize:function(e,t){n(function(){t.widget.scheduledResize()},300)}},n(function(){r.widget.scheduledResize()},300),console.timeEnd("drawWidget.buildLinkFunc")}}e.module(t.app.name).directive("drawWidget",["$compile","$timeout",function(e,t){return{restrict:"EA",template:'
',scope:{widget:"=widget",isdark:"=isdark"},replace:!0,link:n(e,t)}}])}(angular,smi2),angular.module("angularResizable",[]).directive("resizable",function(){function e(e){void 0===t?(t=e,setTimeout(function(){t(),t=void 0},100)):t=e}var t;return{restrict:"AE",scope:{rDirections:"=",rCenteredX:"=",rCenteredY:"=",rWidth:"=",rHeight:"=",rFlex:"=",rGrabber:"@",rDisabled:"@",rNoThrottle:"=",resizable:"@"},link:function(t,a,n){if("false"!==t.resizable){var r="flexBasis"in document.documentElement.style?"flexBasis":"webkitFlexBasis"in document.documentElement.style?"webkitFlexBasis":"msFlexPreferredSize"in document.documentElement.style?"msFlexPreferredSize":"flexBasis";t.$watch("rWidth",function(e){a[0].style[t.rFlex?r:"width"]=e!==!1?e+"px":""}),t.$watch("rHeight",function(e){a[0].style[t.rFlex?r:"height"]=e!==!1?e+"px":""}),a.addClass("resizable");var i,s,o,c,l,d=window.getComputedStyle(a[0],null),u=t.rDirections||["right"],m=t.rCenteredX?2:1,h=t.rCenteredY?2:1,p=t.rGrabber?t.rGrabber:"",g={},f=function(e){g.width=!1,g.height=!1,"x"===l?g.width=parseInt(a[0].style[t.rFlex?r:"width"]):g.height=parseInt(a[0].style[t.rFlex?r:"height"]),g.id=a[0].id,g.evt=e},b=function(e){return e.touches?e.touches[0].clientX:e.clientX},v=function(e){return e.touches?e.touches[0].clientY:e.clientY},y=function(n){function d(){t.$emit("angular-resizable.resizing",g)}var u,p="x"===l?o-b(n):o-v(n);switch(c){case"top":u=t.rFlex?r:"height",a[0].style[u]=s+p*h+"px";break;case"bottom":u=t.rFlex?r:"height",a[0].style[u]=s-p*h+"px";break;case"right":u=t.rFlex?r:"width",a[0].style[u]=i-p*m+"px";break;case"left":u=t.rFlex?r:"width",a[0].style[u]=i+p*m+"px"}f(n),t.rNoThrottle?d():e(d)},w=function C(e){f(),t.$emit("angular-resizable.resizeEnd",g),t.$apply(),document.removeEventListener("mouseup",C,!1),document.removeEventListener("mousemove",y,!1),document.removeEventListener("touchend",C,!1),document.removeEventListener("touchmove",y,!1),a.removeClass("no-transition")},k=function(e){var n={},i=!1,s=!1;n.width=parseInt(a[0].style[t.rFlex?r:"width"]),n.height=parseInt(a[0].style[t.rFlex?r:"height"]),"right"==c&&(n.width>10?(t.preState=n,i=0,s=0):(t.preState&&t.preState.width||(t.preState.width=100),s=t.preState.height,i=t.preState.width)),"bottom"==c&&(n.height>10?(t.preState=n,s=0):(t.preState&&t.preState.height||(t.preState.height=100),s=t.preState.height,i=t.preState.width)),i!==!1&&(a[0].style[t.rFlex?r:"width"]=i+"px"),s!==!1&&(a[0].style[t.rFlex?r:"height"]=s+"px"),t.$apply()},x=function(e,n){c=n,l="left"===c||"right"===c?"x":"y",o="x"===l?b(e):v(e),i=parseInt(d.getPropertyValue("width")),s=parseInt(d.getPropertyValue("height")),a.addClass("no-transition"),document.addEventListener("mouseup",w,!1),document.addEventListener("mousemove",y,!1),document.addEventListener("touchend",w,!1),document.addEventListener("touchmove",y,!1),e.stopPropagation&&e.stopPropagation(),e.preventDefault&&e.preventDefault(),e.cancelBubble=!0,e.returnValue=!1,f(e),t.$emit("angular-resizable.resizeStart",g),t.$apply()};u.forEach(function(e){var n=document.createElement("div");n.setAttribute("class","rg-"+e),n.innerHTML=p,a[0].appendChild(n),n.ondragstart=function(){return!1};var r=function(a){var n="true"===t.rDisabled;n||1!==a.which&&!a.touches||x(a,e)};n.addEventListener("dblclick",k,!1),n.addEventListener("mousedown",r,!1),n.addEventListener("touchstart",r,!1)})}}}});var csvImport=angular.module("ngCsvImport",[]);csvImport.directive("ngCsvImport",function(){return{restrict:"E",transclude:!0,replace:!0,scope:{content:"=?",header:"=?",headerVisible:"=?",separator:"=?",separatorVisible:"=?",result:"=?",encoding:"=?",encodingVisible:"=?",accept:"=?",acceptSize:"=?",acceptSizeExceedCallback:"=?",callback:"=?",mdButtonClass:"@?",mdInputClass:"@?",mdButtonTitle:"@?",mdSvgIcon:"@?",uploadButtonLabel:"="},template:function(e,t){var a=angular.isDefined(t.material),n=angular.isDefined(t.multiple);return'
Header
'+(a?'
':'')+'
Encoding
{{encoding}}
Seperator
'+(a?' {{mdButtonTitle}}':"")+"
"},link:function(e,t,a){if(e.separatorVisible=!!e.separatorVisible,e.headerVisible=!!e.headerVisible,e.acceptSize=e.acceptSize||Number.POSITIVE_INFINITY,e.material=angular.isDefined(a.material),e.multiple=angular.isDefined(a.multiple),e.multiple)throw new Error("Multiple attribute is not supported yet.");var n=angular.element(t[0].querySelector('input[type="file"]')),r=angular.element(t[0].querySelector("md-input-container"));if(e.material&&n){if(n.removeClass("ng-show"),n.addClass("ng-hide"),r){var i=angular.element(r[0].querySelector("div.md-errors-spacer"));i&&i.remove()}e.onClick=function(){n.click()}}angular.element(t[0].querySelector(".separator-input")).on("keyup",function(t){if(null!=e.content){var a={csv:e.content,header:e.header,separator:t.target.value,encoding:e.encoding};e.result=s(a),e.$apply(),"function"==typeof e.callback&&e.callback(t)}}),t.on("change",function(t){if(t.target.files&&t.target.files.length){if(t.target.files[0].size>e.acceptSize)return void("function"==typeof e.acceptSizeExceedCallback&&e.acceptSizeExceedCallback(t.target.files[0]));e.filename=t.target.files[0].name;var a=new FileReader;if(a.onload=function(a){e.$apply(function(){var n={csv:a.target.result.replace(/\r\n|\r/g,"\n"),header:e.header,separator:e.separator};e.content=n.csv,e.result=s(n),e.result.filename=e.filename,e.$$postDigest(function(){"function"==typeof e.callback&&e.callback(t)})})},"file"!==t.target.type||null==t.target.files&&null==t.srcElement.files){if(null!=e.content){var n={csv:e.content,header:!e.header,separator:e.separator};e.result=s(n),e.$$postDigest(function(){"function"==typeof e.callback&&e.callback(t)})}}else a.readAsText((t.srcElement||t.target).files[0],e.encoding)}});var s=function(e){var t=e.csv.split(new RegExp('\n(?![^"]*"(?:(?:[^"]*"){2})*[^"]*$)')),a=[],n=0,r=t[0].split(e.separator).length,i=[];e.header&&(i=t[0].split(e.separator),n=1);for(var s=n;s3e4&&(a=3e4),t.fetchQuery("SELECT now(),number,sin(number),sin(number),SHA1(toString(number)),SHA1(toString(number)) as xx from system.numbers limit "+a).then(function(t){var a="ch",n=new DataProvider(t,a);n.progressQuery="SQL";var r=new WidgetTable(n);e.w=r,e.vars.show=!0,e.vars.counter++,console.info("Load done",e.vars.counter,e.vars.show)})},e._widgetsx=[],e.removeResult=function(t,a,n){n.stopPropagation(),delete e.listDashboards[a]},e.inits=function(){e.listDashboards={}},e.inits(),e.moveWidget=function(){e.widgets[0].x=1,e.widgets[0].width=2,e.widgets[0].height=2},e.removeWidget=function(t){var a=e.widgets.indexOf(t);e.widgets.splice(a,1)},e.onChange=function(e,t){console.log("onChange event: "+e+" items:"+t)},e.onDragStart=function(e,t){console.log("onDragStart event: "+e+" ui:"+t)},e.onDragStop=function(e,t){console.log("onDragStop event: "+e+" ui:"+t)},e.onResizeStart=function(e,t){console.log("onResizeStart event: "+e+" ui:"+t)},e.onResizeStop=function(e,t){console.log("onResizeStop ",t.size)},e.onItemAdded=function(e){console.log("onItemAdded item: "+e)},e.onItemRemoved=function(e){console.log("onItemRemoved item: "+e)}}e.module(t.app.name).controller("DashController",a),a.$inject=["$scope","API","ThemeService","$interval","localStorageService","$mdDialog","$window","hotRegisterer"]}(angular,smi2),function(e,t){function a(t,a,n,r,i,s,o,c){t.vars={isDark:r.isDark(),historysql:a.sqlLog,charthelp:[],active:{chart:!0,history:!0,snippet:!0,vars:!0},snippets:o.snippets,variables:s.vars},t.vars.scrollConfig2={autoHideScrollbar:!1,theme:r.isDark()?"light":"dark",scrollButtons:{enable:!1},scrollInertia:400,setHeight:200,advanced:{updateOnContentResize:!0}},t.showAddVarsDialog=function(a){c.show({controller:["$scope","$mdDialog",function(e,t){e.v={name:"Var1",type:"text",value:""},e.close=function(){t.cancel()},e.add=function(e){t.hide(e)}}],templateUrl:"app/base/addVarsDialog.html",parent:e.element(document.body),targetEvent:a,clickOutsideToClose:!0}).then(function(e){e.name&&e.value&&e.type&&(s.addVar(e.type,e.name,e.value),t.broadcast())},function(){})},t.broadcast=function(){a.$emit("handleBroadcastUpdateVarsAndSnippets",{value:!0})},t.changed=function(e){s.update(e),t.broadcast()},t.showState=function(){console.warn(t.vars.variables)},t.addVar=function(){s.addVar("int","limit",1e3),t.broadcast()},t.actionHistory=function(e){a.$emit("handleBroadcastInsertInActive",{value:e})},t.dropSnippet=function(e){o.drop(e),t.broadcast()},t.dropVar=function(e){s.drop(e),t.broadcast()},t.init=function(){(!_.isObject(t.vars)||_.isUndefined(t.vars.variables.limit))&&s.addVar("int","limit",1e3)},t.init()}e.module(t.app.name).controller("SidebarHelperCtrl",a),a.$inject=["$scope","$rootScope","API","ThemeService","localStorageService","Variables","Snippets","$mdDialog"]}(angular,smi2),function(e,t){function a(e,t,a,n,r,i,s,o,c,l){e.vars={searchline:"",counter:0,loaded:!1,error:!1,databases:[]},e.vars.scrollConfig={autoHideScrollbar:!1,theme:r.isDark()?"light":"dark",scrollButtons:{enable:!1},scrollInertia:400,advanced:{updateOnContentResize:!0}},e.vars.metis={config:{toggle:!1,preventDefault:!1}},e.clickInsertField=function(e){t.$emit("handleBroadcastInsertInActive",{value:e.name})},e.clickAndSelect=function(a,n){return a.name==t.currentDatabase?(n.stopPropagation(),!1):void e.selectDatabase(a)},e.selectDatabase=function(e){console.time("sidebar.selectDatabase time took"),t.currentDatabase=e.name,s.show(s.simple().content("USE "+e.name+" database").theme(r.theme).position("bottom right")),console.timeEnd("sidebar.selectDatabase time took")},e.openTable=function(e){console.log("openTable!!!!!!!!!!!!!!!!!!!!!!!"),i("tableSiedenav").close(),t.currentDatabase!=e.database&&(s.show(s.simple().content("USE "+e.database+" database").theme(r.theme).position("bottom right")),t.currentDatabase=e.database),t.currentTable=e.name,i("tableSiedenav").open()},t.$on("handleBroadcastDatabases",function(){e.reLoad(!0),e.$applyAsync()}),e.updateDS=function(){n.databaseStructure(function(e){a.reload()},!0)},e.rightMenuProcessTable=function(e,a,r,i){console.log("rightMenuProcessTable",e,a,r),"InsertSQLDrop"==e&&(-1!==r.indexOf(".")&&(r='"'+r+'"'),t.$emit("handleBroadcastInsertInActive",{value:"DROP TABLE IF EXISTS "+a+"."+r})),"InsertName"==e&&t.$emit("handleBroadcastInsertInActive",{value:a+"."+r}),"InsertSQLDescribe"==e&&n.query("SHOW CREATE TABLE "+a+'."'+r+'"').then(function(e){var a=window.sqlFormatter.format(e.data[0].statement);t.$emit("handleBroadcastInsertInActive",{value:a})}),"OpenTables"==e&&(window.location="/#/database/"+a+"/table/"+r),"InsertDescribe"==e&&n.query("SELECT * FROM system.columns WHERE database='"+a+"' AND table='"+r+"'").then(function(e){var n=[],i=[];e.data.forEach(function(e){n.push(e.name),"Date"==e.type&&i.push(e.name+"=today()")}),-1!==r.indexOf(".")&&(r='"'+r+'"');var s="\nSELECT\n "+n.join(",\n ")+"\nFROM\n "+a+"."+r+"\n";i.length&&(s=s+"\nWHERE\n "+i.join("\n AND \n")),s+="\nLIMIT 100\n\n",console.log(s),t.$emit("handleBroadcastInsertInActive",{value:s})})},e.showAlertDatabaseStructure=function(e){o.show(o.alert().clickOutsideToClose(!0).title("Error on load database structure").textContent(e).ariaLabel("Error on load database structure").ok("OK")).then(function(e){n.clear(),a.go("login")})},e.reLoad=function(a){e.vars.loaded=!1,e.vars.error=!1,e.vars.databases=[],t.isInitDatabaseStructure=!1,n.fetchQuery("SELECT 1").then(function(r){e.$applyAsync(),n.databaseStructure(function(a){console.log("isInitDatabaseStructure-true"),t.isInitDatabaseStructure=Date.now(),e.$applyAsync(),console.log("databaseStructure - done");var n=a.getFields();e.vars.databases=a.getTables().reduce(function(e,t){var a=[{active:!0,value:"Select",key:"OpenTables",icon:"arrow-expand",db:t.database}],r=[{active:!0,value:"Open table",key:"OpenTables",icon:"arrow-expand",db:t.database,table:t.name},{active:!0,value:"Code Select from",key:"InsertDescribe",icon:"format-size",db:t.database,table:t.name},{active:!0,value:"Insert table name",key:"InsertName",icon:"bing",db:t.database,table:t.name},{active:!0,value:"Make SQL Describe",key:"InsertSQLDescribe",icon:"border-vertical",db:t.database,table:t.name},{active:!0,value:"Make SQL Drop",key:"InsertSQLDrop",icon:"delete",db:t.database,table:t.name}],i="table";t.engine.match(/Dictionary.*/)&&(i="library"),t.engine.match(/Distributed.*/)&&(i="soundcloud"),t.engine.match(/AggregatingMergeTree.*/)&&(i="cube"),t.engine.match(/MaterializedView.*/)&&(i="border-bottom"),t.engine.match(/SummingMergeTree.*/)&&(i="table-row-plus-after"),t.engine.match(/CollapsingMergeTree.*/)&&(i="table-row-height"),t.engine.match(/$Merge^/)&&(i="source-fork"),t.active=!0,t.classEngine=i,t.rightMenuListTable=r;var s=!0,o=!1,c=void 0;try{for(var l,d=e[Symbol.iterator]();!(s=(l=d.next()).done);s=!0){var u=l.value;if("-"!==t.name&&u.name==t.database)return u.tables.push({active:!0,database:t.database,name:t.name,engine:t.engine,classEngine:t.classEngine,fields:n[t.database+"."+t.name],rightMenuList:t.rightMenuListTable}),e}}catch(m){o=!0,c=m}finally{try{!s&&d["return"]&&d["return"]()}finally{if(o)throw c}}return[].concat(_toConsumableArray(e),[{name:t.database,rightMenuList:a,tables:[{active:!0,database:t.database,name:t.name,engine:t.engine,classEngine:t.classEngine,rightMenuList:t.rightMenuListTable,fields:n[t.database+"."+t.name]}]}])},[]),e.selectDatabase(e.vars.databases[0]),a.getDatabases().forEach(function(t){var a=!1;e.vars.databases.forEach(function(e){e.name==t.name&&(a=!0)}),a||e.vars.databases.push({name:t.name,tables:[],active:!0})}),c(function(){e.vars.loaded=!0,e.vars.error=!1,$("#sideBarMetismenu").metisMenu()},100)},a)},function(t){e.showAlertDatabaseStructure(t)})},e.reLoad()}e.module(t.app.name).controller("SidebarController",a),a.$inject=["$scope","$rootScope","$state","API","ThemeService","$mdSidenav","$mdToast","$mdDialog","$timeout","localStorageService"]}(angular,smi2),function(e,t){function a(a,n,r,i,s){a.user=r.getConnectionInfo().name,a.themes=i.list,a.isChrome=/Chrome/.test(navigator.userAgent),a.vars={disable_exit:window.global_tabix_disable_exit,hideExitButton:!window.global_tabix_disable_exit},a.help=function(a){function n(e,a){e.vars={version:t.app.version,buildDate:t.app.buildDate},e.hide=function(){a.hide()},e.cancel=function(){a.cancel()},e.answer=function(e){a.hide(e)}}n.$inject=["$scope","$mdDialog"],s.show({controller:n,templateUrl:"app/base/helpDialogRu.html",parent:e.element(document.body),targetEvent:a,clickOutsideToClose:!0})},a.logout=function(){r.clear(),n.go("login")},a.setUiTheme=function(e){i.set(e.name),window.location.reload()}}e.module(t.app.name).controller("HeaderController",a),a.$inject=["$scope","$state","API","ThemeService","$mdDialog"]}(angular,smi2),ace.define("ace/theme/dracula",["require","exports","module","ace/lib/dom"],function(e,t,a){t.isDark=!0,t.cssClass="ace-dracula",t.cssText="ace-dracula .ace_gutter {background: #282a36;color: rgb(144,145,148)}.ace-dracula .ace_print-margin {width: 1px;background: #e8e8e8}.ace-dracula {background-color: #282a36;color: #f8f8f2}.ace-dracula .ace_cursor {color: #f8f8f0}.ace-dracula .ace_marker-layer .ace_selection {background: #44475a}.ace-dracula.ace_multiselect .ace_selection.ace_start {box-shadow: 0 0 3px 0px #282a36;border-radius: 2px}.ace-dracula .ace_marker-layer .ace_step {background: rgb(198, 219, 174)}.ace-dracula .ace_marker-layer .ace_bracket {margin: -1px 0 0 -1px;border: 1px solid #3B3A32}.ace-dracula .ace_marker-layer .ace_active-line {background: #44475a}.ace-dracula .ace_gutter-active-line {background-color: #44475a}.ace-dracula .ace_marker-layer .ace_selected-word {border: 1px solid #44475a}.ace-dracula .ace_fold {background-color: #50fa7b;border-color: #f8f8f2}.ace-dracula .ace_keyword {color: #ff79c6}.ace-dracula .ace_constant.ace_language {color: #bd93f9}.ace-dracula .ace_constant.ace_numeric {color: #bd93f9}.ace-dracula .ace_constant.ace_character {color: #bd93f9}.ace-dracula .ace_constant.ace_character.ace_escape {color: #ff79c6}.ace-dracula .ace_constant.ace_other {color: #bd93f9}.ace-dracula .ace_support.ace_function {color: #8be9fd}.ace-dracula .ace_support.ace_constant {color: #6be5fd}.ace-dracula .ace_support.ace_class {font-style: italic;color: #66d9ef}.ace-dracula .ace_support.ace_type {font-style: italic;color: #66d9ef}.ace-dracula .ace_storage {color: #ff79c6}.ace-dracula .ace_storage.ace_type {font-style: italic;color: #8be9fd}.ace-dracula .ace_invalid {color: #F8F8F0;background-color: #ff79c6}.ace-dracula .ace_invalid.ace_deprecated {color: #F8F8F0;background-color: #bd93f9}.ace-dracula .ace_string {color: #f1fa8c}.ace-dracula .ace_comment {color: #6272a4}.ace-dracula .ace_variable {color: #50fa7b}.ace-dracula .ace_variable.ace_parameter {font-style: italic;color: #ffb86c}.ace-dracula .ace_entity.ace_other.ace_attribute-name {color: #50fa7b}.ace-dracula .ace_entity.ace_name.ace_function {color: #50fa7b}.ace-dracula .ace_entity.ace_name.ace_tag {color: #ff79c6}";var n=e("../lib/dom");n.importCssString(t.cssText,t.cssClass)}),ace.define("ace/mode/clickhouse",["require","exports","module","ace/lib/oop","ace/mode/text","ace/token_iterator","ace/mode/folding","ace/mode/clickhouse_FoldMode","ace/mode/clickhouse_highlight_rules"],function(e,t){var a=e("../lib/oop"),n=e("./text").Mode,r=e("./clickhouse_highlight_rules").ClickhouseHighlightRules,i=e("./clickhouse_FoldMode").FoldMode,s=e("./matching_brace_outdent").MatchingBraceOutdent,o=e("./behaviour/cstyle").CstyleBehaviour,c=function(){this.foldingRules=new i,this.$outdent=new s,this.$behaviour=new o,this.HighlightRules=r};a.inherits(c,n),function(){var t=this;this.lineCommentStart="--",this.getHighlightRule=function(){return t.session.$mode.$highlightRules},this.getCompletions=function(e,t,a,n){return t.$mode.$highlightRules.completions},this.$id="ace/mode/clickhouse",this.checkOutdent=function(e,t,a){return this.$outdent.checkOutdent(t,a)},this.autoOutdent=function(e,t,a){this.$outdent.autoOutdent(t,a)},this.findTokens=function(t,a,n){t=t.replace(/^(\r\n|\n|\r)/gm,"").replace(/(\r\n|\n|\r)$/gm,"");for(var r=e("ace/token_iterator").TokenIterator,i=e("ace/edit_session").EditSession,s=new i(t,this),o=new r(s,0,0),c=o.getCurrentToken(),l=[];c;){var d=c;if(d.row=o.getCurrentTokenRow(),d.col=o.getCurrentTokenColumn(),d.type==a&&(l.push(d),n))return d.value=d.value.toLowerCase(),d;c=o.stepForward()}return l},this.trim=function(e,t){return t!==!0&&"string"==typeof t&&t.length>0&&(e=e.replace("^("+t+")"," ").replace(t+"$"," "),e=e.replace(new RegExp("^"+t+"|"+t+"$","g")," ")),e},this.collapseAll=function(e){for(var t=e,a=t.foldWidgets,n=t.getLength(),r=0,i=r;n>i;i++)if(null==a[i]&&(a[i]=t.getFoldWidget(i)),"start"==a[i]){var s=t.getFoldWidgetRange(i);if(s&&s.end.row<=n&&s.start.row>=r){i=s.end.row;try{var o=t.addFold("...",s);o&&(o.collapseChildren=depth)}catch(t){}}}},this.replaceVars=function(e,t){var a={},n=this.fetchTokens(e);if(console.warn("Find tokens",n,t),n.vars.length>0)for(var r in n.vars){var i=n.vars[r],s=i;i=i.indexOf("{")>-1?i.replace("{","").replace("}",""):i.replace("$","").replace("@","").replace(":","");for(var o in t){var c=t[o];c.name.toLowerCase()==i.toLowerCase()&&(console.info(c.name.toLowerCase(),"==",i.toLowerCase()),e=e.replace(s,c.value))}}return{sql:e,tokens:n,vars:a}},this.fetchTokens=function(t){var a={groupby:[],where:[],vars:[],limit:-1},n=e("ace/token_iterator").TokenIterator,r=e("ace/edit_session").EditSession,i=new r(t,this);i.bgTokenizer.start(0);for(var s=new n(i,0,0),o=s.getCurrentToken();o;){var c=o;if(c.row=s.getCurrentTokenRow(),c.col=s.getCurrentTokenColumn(),"variable.language"==c.type&&c.value&&a.vars.push(c.value),"keyword"==c.type&&c.value.toLowerCase().includes("limit")!==!1){var l=c.value.toLowerCase().match(/LIMIT\W+(\d+)\W*\,\W*(\d+)/i);l||(l=c.value.toLowerCase().match(/LIMIT\W+(\d+)/i)),l[0]&&l[1]&&l[2]?a.limit={from:l[1],to:l[2]}:l[0]&&l[1]&&(a.limit={from:l[1],to:!1})}o=s.stepForward()}return console.info("Parse & Find tokens result",a),a},this.splitByTokens=function(t,a,n){var r=e("ace/token_iterator").TokenIterator,i=e("ace/edit_session").EditSession,s=e("ace/range").Range,o=new i(t,this);o.bgTokenizer.start(0);var c=new r(o,0,0),l=c.getCurrentToken();if(_.isUndefined(l)){var d=0;do d++,c=new r(o,d,0),l=c.getCurrentToken();while(100>d&&!l)}for(var u=[],m=0,h=0,p=!1,g=void 0,f=void 0;l;){var b=l;if(b.row=c.getCurrentTokenRow(),b.col=c.getCurrentTokenColumn(),b.type==a&&(n!==!0&&b.value==n||n===!0)){var v=0;n instanceof String&&(v=n.length),g=new s(m,h,b.row,b.col+v),f=o.getTextRange(g),m=b.row,h=b.col+v,f=this.trim(f,b.value),f.length>2&&("string"==typeof p&&(f=this.trim(f,p)),u.push({sql:f,range:g,keyword:p}),p=b.value)}l=c.stepForward()}return g=new s(m,h,Number.MAX_VALUE,Number.MAX_VALUE),f=o.getTextRange(g),f=this.trim(f,n),"string"==typeof p&&(f=this.trim(f,p)),f.length>2&&u.push({sql:f,range:g,keyword:p}),u}}.call(c.prototype),t.Mode=c}),ace.define("ace/ext/whitespace",["require","exports","module","ace/lib/lang"],function(e,t,a){var n=e("../lib/lang");t.$detectIndentation=function(e,t){function a(e){for(var t=0,a=e;ac;c++){var l=e[c];if(/^\s*[^*+\-\s]/.test(l)){if(" "==l[0])i++,s=-Number.MAX_VALUE;else{var d=l.match(/^ */)[0].length;if(d&&" "!=l[d]){var u=d-s;!(u>0)||s%u||d%u||(r[u]=(r[u]||0)+1),n[d]=(n[d]||0)+1}s=d}for(;o>c&&"\\"==l[l.length-1];)l=e[c++]}}for(var m=r.reduce(function(e,t){return e+t},0),h={score:0,length:0},p=0,c=1;12>c;c++){var g=a(c);1==c?(p=g,g=n[1]?.9:.8,n.length||(g=0)):g/=p,r[c]&&(g+=r[c]/m),g>h.score&&(h={score:g,length:c})}if(h.score&&h.score>1.4)var f=h.length;return i>p+1?((1==f||i/4>p||h.score<1.8)&&(f=void 0),{ch:" ",length:f}):p>i+1?{ch:" ",length:f}:void 0},t.detectIndentation=function(e){var a=e.getLines(0,1e3),n=t.$detectIndentation(a)||{};return n.ch&&e.setUseSoftTabs(" "==n.ch),n.length&&e.setTabSize(n.length),n},t.trimTrailingSpace=function(e,t){for(var a=e.getDocument(),n=a.getAllLines(),r=t?-1:0,i=0,s=n.length;s>i;i++){var o=n[i],c=o.search(/\s+$/);c>r&&a.removeInLine(i,c,o.length)}},t.convertIndentation=function(e,t,a){var r=e.getTabString()[0],i=e.getTabSize();a||(a=i),t||(t=r);for(var s=" "==t?t:n.stringRepeat(t,a),o=e.doc,c=o.getAllLines(),l={},d={},u=0,m=c.length;m>u;u++){var h=c[u],p=h.match(/^\s*/)[0];if(p){var g=e.$getStringScreenWidth(p)[0],f=Math.floor(g/i),b=g%i,v=l[f]||(l[f]=n.stringRepeat(s,f));v+=d[b]||(d[b]=n.stringRepeat(" ",b)),v!=p&&(o.removeInLine(u,0,p.length),o.insertInLine({row:u,column:0},v))}}e.setTabSize(a),e.setUseSoftTabs(" "==t)},t.$parseStringArg=function(e){var t={};/t/.test(e)?t.ch=" ":/s/.test(e)&&(t.ch=" ");var a=e.match(/\d+/);return a&&(t.length=parseInt(a[0],10)),t},t.$parseArg=function(e){return e?"string"==typeof e?t.$parseStringArg(e):"string"==typeof e.text?t.$parseStringArg(e.text):e:{}},t.commands=[{name:"detectIndentation",exec:function(e){t.detectIndentation(e.session)}},{name:"trimTrailingSpace",exec:function(e){t.trimTrailingSpace(e.session)}},{name:"convertIndentation",exec:function(e,a){var n=t.$parseArg(a);t.convertIndentation(e.session,n.ch,n.length)}},{name:"setIndentation",exec:function(e,a){var n=t.$parseArg(a);n.length&&e.session.setTabSize(n.length),n.ch&&e.session.setUseSoftTabs(" "==n.ch)}}]}),function(){ace.require(["ace/ext/whitespace"],function(){})}(),ace.define("ace/ext/statusbar",["require","exports","module","ace/lib/dom","ace/lib/lang"],function(e,t,a){var n=e("ace/lib/dom"),r=e("ace/lib/lang"),i=function(e,t){this.element=n.createElement("div"),this.element.className="ace_status-indicator",this.element.style.cssText="display: inline-block;",t.appendChild(this.element);var a=r.delayedCall(function(){this.updateStatus(e)}.bind(this)).schedule.bind(null,100);e.on("changeStatus",a),e.on("changeSelection",a),e.on("keyboardActivity",a)};(function(){this.updateStatus=function(e){function t(e,t){e&&a.push(e,t||"|")}var a=[];t(e.keyBinding.getStatusText(e)),e.commands.recording&&t("REC");var n=e.selection,r=n.lead;if(!n.isEmpty()){var i=e.getSelectionRange();t("("+(i.end.row-i.start.row)+":"+(i.end.column-i.start.column)+")"," ")}t(r.row+":"+r.column," "),n.rangeCount&&t("["+n.rangeCount+"]"," "),a.pop(),this.element.textContent=a.join("")}}).call(i.prototype),t.StatusBar=i}),function(){ace.require(["ace/ext/statusbar"],function(){})}(),ace.define("ace/ext/spellcheck",["require","exports","module","ace/lib/event","ace/editor","ace/config"],function(e,t,a){var n=e("../lib/event");t.contextMenuHandler=function(e){var t=e.target,a=t.textInput.getElement();if(t.selection.isEmpty()){var r=t.getCursorPosition(),i=t.session.getWordRange(r.row,r.column),s=t.session.getTextRange(i);if(t.session.tokenRe.lastIndex=0,t.session.tokenRe.test(s)){var o="",c=s+" "+o;a.value=c,a.setSelectionRange(s.length,s.length+1),a.setSelectionRange(0,0),a.setSelectionRange(0,s.length);var l=!1;n.addListener(a,"keydown",function d(){n.removeListener(a,"keydown",d),l=!0}),t.textInput.setInputHandler(function(e){if(console.log(e,c,a.selectionStart,a.selectionEnd),e==c)return"";if(0===e.lastIndexOf(c,0))return e.slice(c.length);if(e.substr(a.selectionEnd)==c)return e.slice(0,-c.length);if(e.slice(-2)==o){var n=e.slice(0,-2);if(" "==n.slice(-1))return l?n.substring(0,a.selectionEnd):(n=n.slice(0,-1),t.session.replace(i,n),"")}return e})}}};var r=e("../editor").Editor;e("../config").defineOptions(r.prototype,"editor",{spellcheck:{set:function(e){var a=this.textInput.getElement();a.spellcheck=!!e,e?this.on("nativecontextmenu",t.contextMenuHandler):this.removeListener("nativecontextmenu",t.contextMenuHandler)},value:!0}})}),function(){ace.require(["ace/ext/spellcheck"],function(){})}(),ace.define("ace/ext/menu_tools/element_generator",["require","exports","module"],function(e,t,a){a.exports.createOption=function(e){var t,a=document.createElement("option");for(t in e)e.hasOwnProperty(t)&&("selected"===t?a.setAttribute(t,e[t]):a[t]=e[t]);return a},a.exports.createCheckbox=function(e,t,a){var n=document.createElement("input");return n.setAttribute("type","checkbox"),n.setAttribute("id",e),n.setAttribute("name",e),n.setAttribute("value",t),n.setAttribute("class",a),t&&n.setAttribute("checked","checked"),n},a.exports.createInput=function(e,t,a){var n=document.createElement("input");return n.setAttribute("type","text"),n.setAttribute("id",e),n.setAttribute("name",e), +n.setAttribute("value",t),n.setAttribute("class",a),n},a.exports.createLabel=function(e,t){var a=document.createElement("label");return a.setAttribute("for",t),a.textContent=e,a},a.exports.createSelection=function(e,t,n){var r=document.createElement("select");return r.setAttribute("id",e),r.setAttribute("name",e),r.setAttribute("class",n),t.forEach(function(e){r.appendChild(a.exports.createOption(e))}),r}}),ace.define("ace/ext/modelist",["require","exports","module"],function(e,t,a){function n(e){for(var t=c.text,a=e.split(/[\/\\]/).pop(),n=0;n +/g,">"),u=function(e,t,a){var r=n.createElement("div");r.innerHTML=d,this.element=r.firstChild,this.setSession=this.setSession.bind(this),this.$init(),this.setEditor(e)};(function(){this.setEditor=function(e){e.searchBox=this,e.renderer.scroller.appendChild(this.element),this.editor=e},this.setSession=function(e){this.searchRange=null,this.$syncOptions(!0)},this.$initElements=function(e){this.searchBox=e.querySelector(".ace_search_form"),this.replaceBox=e.querySelector(".ace_replace_form"),this.searchOption=e.querySelector("[action=searchInSelection]"),this.replaceOption=e.querySelector("[action=toggleReplace]"),this.regExpOption=e.querySelector("[action=toggleRegexpMode]"),this.caseSensitiveOption=e.querySelector("[action=toggleCaseSensitive]"),this.wholeWordOption=e.querySelector("[action=toggleWholeWords]"),this.searchInput=this.searchBox.querySelector(".ace_search_field"),this.replaceInput=this.replaceBox.querySelector(".ace_search_field"),this.searchCounter=e.querySelector(".ace_search_counter")},this.$init=function(){var e=this.element;this.$initElements(e);var t=this;i.addListener(e,"mousedown",function(e){setTimeout(function(){t.activeInput.focus()},0),i.stopPropagation(e)}),i.addListener(e,"click",function(e){var a=e.target||e.srcElement,n=a.getAttribute("action");n&&t[n]?t[n]():t.$searchBarKb.commands[n]&&t.$searchBarKb.commands[n].exec(t),i.stopPropagation(e)}),i.addCommandKeyListener(e,function(e,a,n){var r=c.keyCodeToString(n),s=t.$searchBarKb.findKeyCommand(a,r);s&&s.exec&&(s.exec(t),i.stopEvent(e))}),this.$onChange=r.delayedCall(function(){t.find(!1,!1)}),i.addListener(this.searchInput,"input",function(){t.$onChange.schedule(20)}),i.addListener(this.searchInput,"focus",function(){t.activeInput=t.searchInput,t.searchInput.value&&t.highlight()}),i.addListener(this.replaceInput,"focus",function(){t.activeInput=t.replaceInput,t.searchInput.value&&t.highlight()})},this.$closeSearchBarKb=new o([{bindKey:"Esc",name:"closeSearchBar",exec:function(e){e.searchBox.hide()}}]),this.$searchBarKb=new o,this.$searchBarKb.bindKeys({"Ctrl-f|Command-f":function(e){var t=e.isReplace=!e.isReplace;e.replaceBox.style.display=t?"":"none",e.replaceOption.checked=!1,e.$syncOptions(),e.searchInput.focus()},"Ctrl-H|Command-Option-F":function(e){e.replaceOption.checked=!0,e.$syncOptions(),e.replaceInput.focus()},"Ctrl-G|Command-G":function(e){e.findNext()},"Ctrl-Shift-G|Command-Shift-G":function(e){e.findPrev()},esc:function(e){setTimeout(function(){e.hide()})},Return:function(e){e.activeInput==e.replaceInput&&e.replace(),e.findNext()},"Shift-Return":function(e){e.activeInput==e.replaceInput&&e.replace(),e.findPrev()},"Alt-Return":function(e){e.activeInput==e.replaceInput&&e.replaceAll(),e.findAll()},Tab:function(e){(e.activeInput==e.replaceInput?e.searchInput:e.replaceInput).focus()}}),this.$searchBarKb.addCommands([{name:"toggleRegexpMode",bindKey:{win:"Alt-R|Alt-/",mac:"Ctrl-Alt-R|Ctrl-Alt-/"},exec:function(e){e.regExpOption.checked=!e.regExpOption.checked,e.$syncOptions()}},{name:"toggleCaseSensitive",bindKey:{win:"Alt-C|Alt-I",mac:"Ctrl-Alt-R|Ctrl-Alt-I"},exec:function(e){e.caseSensitiveOption.checked=!e.caseSensitiveOption.checked,e.$syncOptions()}},{name:"toggleWholeWords",bindKey:{win:"Alt-B|Alt-W",mac:"Ctrl-Alt-B|Ctrl-Alt-W"},exec:function(e){e.wholeWordOption.checked=!e.wholeWordOption.checked,e.$syncOptions()}},{name:"toggleReplace",exec:function(e){e.replaceOption.checked=!e.replaceOption.checked,e.$syncOptions()}},{name:"searchInSelection",exec:function(e){e.searchOption.checked=!e.searchRange,e.setSearchRange(e.searchOption.checked&&e.editor.getSelectionRange()),e.$syncOptions()}}]),this.setSearchRange=function(e){this.searchRange=e,e?this.searchRangeMarker=this.editor.session.addMarker(e,"ace_active-line"):this.searchRangeMarker&&(this.editor.session.removeMarker(this.searchRangeMarker),this.searchRangeMarker=null)},this.$syncOptions=function(e){n.setCssClass(this.replaceOption,"checked",this.searchRange),n.setCssClass(this.searchOption,"checked",this.searchOption.checked),this.replaceOption.textContent=this.replaceOption.checked?"-":"+",n.setCssClass(this.regExpOption,"checked",this.regExpOption.checked),n.setCssClass(this.wholeWordOption,"checked",this.wholeWordOption.checked),n.setCssClass(this.caseSensitiveOption,"checked",this.caseSensitiveOption.checked),this.replaceBox.style.display=this.replaceOption.checked?"":"none",this.find(!1,!1,e)},this.highlight=function(e){this.editor.session.highlight(e||this.editor.$search.$options.re),this.editor.renderer.updateBackMarkers()},this.find=function(e,t,a){var r=this.editor.find(this.searchInput.value,{skipCurrent:e,backwards:t,wrap:!0,regExp:this.regExpOption.checked,caseSensitive:this.caseSensitiveOption.checked,wholeWord:this.wholeWordOption.checked,preventScroll:a,range:this.searchRange}),i=!r&&this.searchInput.value;n.setCssClass(this.searchBox,"ace_nomatch",i),this.editor._emit("findSearchBox",{match:!i}),this.highlight(),this.updateCounter()},this.updateCounter=function(){var e=this.editor,t=e.$search.$options.re,a=0,n=0;if(t){var r=this.searchRange?e.session.getTextRange(this.searchRange):e.getValue(),i=e.session.doc.positionToIndex(e.selection.anchor);this.searchRange&&(i-=e.session.doc.positionToIndex(this.searchRange.start));for(var s,o=t.lastIndex=0;(s=t.exec(r))&&(a++,o=s.index,i>=o&&n++,!(a>l))&&(s[0]||(t.lastIndex=o+=1,!(o>=r.length))););}this.searchCounter.textContent=n+" of "+(a>l?l+"+":a)},this.findNext=function(){this.find(!0,!1)},this.findPrev=function(){this.find(!0,!0)},this.findAll=function(){var e=this.editor.findAll(this.searchInput.value,{regExp:this.regExpOption.checked,caseSensitive:this.caseSensitiveOption.checked,wholeWord:this.wholeWordOption.checked}),t=!e&&this.searchInput.value;n.setCssClass(this.searchBox,"ace_nomatch",t),this.editor._emit("findSearchBox",{match:!t}),this.highlight(),this.hide()},this.replace=function(){this.editor.getReadOnly()||this.editor.replace(this.replaceInput.value)},this.replaceAndFindNext=function(){this.editor.getReadOnly()||(this.editor.replace(this.replaceInput.value),this.findNext())},this.replaceAll=function(){this.editor.getReadOnly()||this.editor.replaceAll(this.replaceInput.value)},this.hide=function(){this.active=!1,this.setSearchRange(null),this.editor.off("changeSession",this.setSession),this.element.style.display="none",this.editor.keyBinding.removeKeyboardHandler(this.$closeSearchBarKb),this.editor.focus()},this.show=function(e,t){this.active=!0,this.editor.on("changeSession",this.setSession),this.element.style.display="",this.replaceOption.checked=t,e&&(this.searchInput.value=e),this.searchInput.focus(),this.searchInput.select(),this.editor.keyBinding.addKeyboardHandler(this.$closeSearchBarKb),this.$syncOptions(!0)},this.isFocused=function(){var e=document.activeElement;return e==this.searchInput||e==this.replaceInput}}).call(u.prototype),t.SearchBox=u,t.Search=function(e,t){var a=e.searchBox||new u(e);a.show(e.session.getTextRange(),t)}}),function(){ace.require(["ace/ext/searchbox"],function(){})}(),ace.define("ace/snippets",["require","exports","module","ace/lib/oop","ace/lib/event_emitter","ace/lib/lang","ace/range","ace/anchor","ace/keyboard/hash_handler","ace/tokenizer","ace/lib/dom","ace/editor"],function(e,t,a){var n=e("./lib/oop"),r=e("./lib/event_emitter").EventEmitter,i=e("./lib/lang"),s=e("./range").Range,o=e("./anchor").Anchor,c=e("./keyboard/hash_handler").HashHandler,l=e("./tokenizer").Tokenizer,d=s.comparePoints,u=function(){this.snippetMap={},this.snippetNameMap={}};(function(){n.implement(this,r),this.getTokenizer=function(){function e(e,t,a){return e=e.substr(1),/^\d+$/.test(e)&&!a.inFormatString?[{tabstopId:parseInt(e,10)}]:[{text:e}]}function t(e){return"(?:[^\\\\"+e+"]|\\\\.)"}return u.$tokenizer=new l({start:[{regex:/:/,onMatch:function(e,t,a){return a.length&&a[0].expectIf?(a[0].expectIf=!1,a[0].elseBranch=a[0],[a[0]]):":"}},{regex:/\\./,onMatch:function(e,t,a){var n=e[1];return"}"==n&&a.length?e=n:-1!="`$\\".indexOf(n)?e=n:a.inFormatString&&("n"==n?e="\n":"t"==n?e="\n":-1!="ulULE".indexOf(n)&&(e={changeCase:n,local:n>"a"})),[e]}},{regex:/}/,onMatch:function(e,t,a){return[a.length?a.shift():e]}},{regex:/\$(?:\d+|\w+)/,onMatch:e},{regex:/\$\{[\dA-Z_a-z]+/,onMatch:function(t,a,n){var r=e(t.substr(1),a,n);return n.unshift(r[0]),r},next:"snippetVar"},{regex:/\n/,token:"newline",merge:!1}],snippetVar:[{regex:"\\|"+t("\\|")+"*\\|",onMatch:function(e,t,a){a[0].choices=e.slice(1,-1).split(",")},next:"start"},{regex:"/("+t("/")+"+)/(?:("+t("/")+"*)/)(\\w*):?",onMatch:function(e,t,a){var n=a[0];return n.fmtString=e,e=this.splitRegex.exec(e),n.guard=e[1],n.fmt=e[2],n.flag=e[3],""},next:"start"},{regex:"`"+t("`")+"*`",onMatch:function(e,t,a){return a[0].code=e.splice(1,-1),""},next:"start"},{regex:"\\?",onMatch:function(e,t,a){a[0]&&(a[0].expectIf=!0)},next:"start"},{regex:"([^:}\\\\]|\\\\.)*:?",token:"",next:"start"}],formatString:[{regex:"/("+t("/")+"+)/",token:"regex"},{regex:"",onMatch:function(e,t,a){a.inFormatString=!0},next:"start"}]}),u.prototype.getTokenizer=function(){return u.$tokenizer},u.$tokenizer},this.tokenizeTmSnippet=function(e,t){return this.getTokenizer().getLineTokens(e,t).tokens.map(function(e){return e.value||e})},this.$getDefaultValue=function(e,t){if(/^[A-Z]\d+$/.test(t)){var a=t.substr(1);return(this.variables[t[0]+"__"]||{})[a]}if(/^\d+$/.test(t))return(this.variables.__||{})[t];if(t=t.replace(/^TM_/,""),e){var n=e.session;switch(t){case"CURRENT_WORD":var r=n.getWordRange();case"SELECTION":case"SELECTED_TEXT":return n.getTextRange(r);case"CURRENT_LINE":return n.getLine(e.getCursorPosition().row);case"PREV_LINE":return n.getLine(e.getCursorPosition().row-1);case"LINE_INDEX":return e.getCursorPosition().column;case"LINE_NUMBER":return e.getCursorPosition().row+1;case"SOFT_TABS":return n.getUseSoftTabs()?"YES":"NO";case"TAB_SIZE":return n.getTabSize();case"FILENAME":case"FILEPATH":return"";case"FULLNAME":return"Ace"}}},this.variables={},this.getVariableValue=function(e,t){return this.variables.hasOwnProperty(t)?this.variables[t](e,t)||"":this.$getDefaultValue(e,t)||""},this.tmStrFormat=function(e,t,a){var n=t.flag||"",r=t.guard;r=new RegExp(r,n.replace(/[^gi]/,""));var i=this.tokenizeTmSnippet(t.fmt,"formatString"),s=this,o=e.replace(r,function(){s.variables.__=arguments;for(var e=s.resolveVariables(i,a),t="E",n=0;n1?(v=t[t.length-1].length,b+=t.length-1):v+=e.length,y+=e}else e.start?e.end={row:b,column:v}:e.start={row:b,column:v}});var w=e.getSelectionRange(),k=e.session.replace(w,y),x=new m(e),C=e.inVirtualSelectionMode&&e.selection.index;x.addTabstops(c,w.start,k,C)},this.insertSnippet=function(e,t){var a=this;return e.inVirtualSelectionMode?a.insertSnippetForSelection(e,t):(e.forEachSelection(function(){a.insertSnippetForSelection(e,t)},null,{keepOrder:!0}),void(e.tabstopManager&&e.tabstopManager.tabNext()))},this.$getScope=function(e){var t=e.session.$mode.$id||"";if(t=t.split("/").pop(),"html"===t||"php"===t){"php"!==t||e.session.$mode.inlinePhp||(t="html");var a=e.getCursorPosition(),n=e.session.getState(a.row);"object"===("undefined"==typeof n?"undefined":_typeof(n))&&(n=n[0]),n.substring&&("js-"==n.substring(0,3)?t="javascript":"css-"==n.substring(0,4)?t="css":"php-"==n.substring(0,4)&&(t="php"))}return t},this.getActiveScopes=function(e){var t=this.$getScope(e),a=[t],n=this.snippetMap;return n[t]&&n[t].includeScopes&&a.push.apply(a,n[t].includeScopes),a.push("_"),a},this.expandWithTab=function(e,t){var a=this,n=e.forEachSelection(function(){return a.expandSnippetForSelection(e,t)},null,{keepOrder:!0});return n&&e.tabstopManager&&e.tabstopManager.tabNext(),n},this.expandSnippetForSelection=function(e,t){var a,n=e.getCursorPosition(),r=e.session.getLine(n.row),i=r.substring(0,n.column),s=r.substr(n.column),o=this.snippetMap;return this.getActiveScopes(e).some(function(e){var t=o[e];return t&&(a=this.findMatchingSnippet(t,i,s)),!!a},this),a?t&&t.dryRun?!0:(e.session.doc.removeInLine(n.row,n.column-a.replaceBefore.length,n.column+a.replaceAfter.length),this.variables.M__=a.matchBefore,this.variables.T__=a.matchAfter,this.insertSnippetForSelection(e,a.content),this.variables.M__=this.variables.T__=null,!0):!1},this.findMatchingSnippet=function(e,t,a){for(var n=e.length;n--;){var r=e[n];if((!r.startRe||r.startRe.test(t))&&(!r.endRe||r.endRe.test(a))&&(r.startRe||r.endRe))return r.matchBefore=r.startRe?r.startRe.exec(t):[""],r.matchAfter=r.endRe?r.endRe.exec(a):[""],r.replaceBefore=r.triggerRe?r.triggerRe.exec(t)[0]:"",r.replaceAfter=r.endTriggerRe?r.endTriggerRe.exec(a)[0]:"",r}},this.snippetMap={},this.snippetNameMap={},this.register=function(e,t){function a(e){return e&&!/^\^?\(.*\)\$?$|^\\b$/.test(e)&&(e="(?:"+e+")"),e||""}function n(e,t,n){return e=a(e),t=a(t),n?(e=t+e,e&&"$"!=e[e.length-1]&&(e+="$")):(e+=t,e&&"^"!=e[0]&&(e="^"+e)),new RegExp(e)}function r(e){e.scope||(e.scope=t||"_"),t=e.scope,s[t]||(s[t]=[],o[t]={});var a=o[t];if(e.name){var r=a[e.name];r&&c.unregister(r),a[e.name]=e}s[t].push(e),e.tabTrigger&&!e.trigger&&(!e.guard&&/^\w/.test(e.tabTrigger)&&(e.guard="\\b"),e.trigger=i.escapeRegExp(e.tabTrigger)),(e.trigger||e.guard||e.endTrigger||e.endGuard)&&(e.startRe=n(e.trigger,e.guard,!0),e.triggerRe=new RegExp(e.trigger,"",!0),e.endRe=n(e.endTrigger,e.endGuard,!0),e.endTriggerRe=new RegExp(e.endTrigger,"",!0))}var s=this.snippetMap,o=this.snippetNameMap,c=this;e||(e=[]),e&&e.content?r(e):Array.isArray(e)&&e.forEach(r),this._signal("registerSnippets",{scope:t})},this.unregister=function(e,t){function a(e){var a=r[e.scope||t];if(a&&a[e.name]){ +delete a[e.name];var i=n[e.scope||t],s=i&&i.indexOf(e);s>=0&&i.splice(s,1)}}var n=this.snippetMap,r=this.snippetNameMap;e.content?a(e):Array.isArray(e)&&e.forEach(a)},this.parseSnippetFile=function(e){e=e.replace(/\r/g,"");for(var t,a=[],n={},r=/^#.*|^({[\s\S]*})\s*$|^(\S+) (.*)$|^((?:\n*\t.*)+)/gm;t=r.exec(e);){if(t[1])try{n=JSON.parse(t[1]),a.push(n)}catch(i){}if(t[4])n.content=t[4].replace(/^\t/gm,""),a.push(n),n={};else{var s=t[2],o=t[3];if("regex"==s){var c=/\/((?:[^\/\\]|\\.)*)|$/g;n.guard=c.exec(o)[1],n.trigger=c.exec(o)[1],n.endTrigger=c.exec(o)[1],n.endGuard=c.exec(o)[1]}else"snippet"==s?(n.tabTrigger=o.match(/^\S*/)[0],n.name||(n.name=o)):n[s]=o}}return a},this.getSnippetByName=function(e,t){var a,n=this.snippetNameMap;return this.getActiveScopes(t).some(function(t){var r=n[t];return r&&(a=r[e]),!!a},this),a}}).call(u.prototype);var m=function(e){return e.tabstopManager?e.tabstopManager:(e.tabstopManager=this,this.$onChange=this.onChange.bind(this),this.$onChangeSelection=i.delayedCall(this.onChangeSelection.bind(this)).schedule,this.$onChangeSession=this.onChangeSession.bind(this),this.$onAfterExec=this.onAfterExec.bind(this),void this.attach(e))};(function(){this.attach=function(e){this.index=0,this.ranges=[],this.tabstops=[],this.$openTabstops=null,this.selectedTabstop=null,this.editor=e,this.editor.on("change",this.$onChange),this.editor.on("changeSelection",this.$onChangeSelection),this.editor.on("changeSession",this.$onChangeSession),this.editor.commands.on("afterExec",this.$onAfterExec),this.editor.keyBinding.addKeyboardHandler(this.keyboardHandler)},this.detach=function(){this.tabstops.forEach(this.removeTabstopMarkers,this),this.ranges=null,this.tabstops=null,this.selectedTabstop=null,this.editor.removeListener("change",this.$onChange),this.editor.removeListener("changeSelection",this.$onChangeSelection),this.editor.removeListener("changeSession",this.$onChangeSession),this.editor.commands.removeListener("afterExec",this.$onAfterExec),this.editor.keyBinding.removeKeyboardHandler(this.keyboardHandler),this.editor.tabstopManager=null,this.editor=null},this.onChange=function(e){var t="r"==e.action[0],a=e.start,n=e.end,r=a.row,i=n.row,s=i-r,o=n.column-a.column;if(t&&(s=-s,o=-o),!this.$inChange&&t){var c=this.selectedTabstop,l=c&&!c.some(function(e){return d(e.start,a)<=0&&d(e.end,n)>=0});if(l)return this.detach()}for(var u=this.ranges,m=0;m0?(this.removeRange(h),m--):(h.start.row==r&&h.start.column>a.column&&(h.start.column+=o),h.end.row==r&&h.end.column>=a.column&&(h.end.column+=o),h.start.row>=r&&(h.start.row+=s),h.end.row>=r&&(h.end.row+=s),d(h.start,h.end)>0&&this.removeRange(h)))}u.length||this.detach()},this.updateLinkedFields=function(){var e=this.selectedTabstop;if(e&&e.hasLinkedRanges){this.$inChange=!0;for(var a=this.editor.session,n=a.getTextRange(e.firstNonLinked),r=e.length;r--;){var i=e[r];if(i.linked){var s=t.snippetManager.tmStrFormat(n,i.original);a.replace(i,s)}}this.$inChange=!1}},this.onAfterExec=function(e){e.command&&!e.command.readOnly&&this.updateLinkedFields()},this.onChangeSelection=function(){if(this.editor){for(var e=this.editor.selection.lead,t=this.editor.selection.anchor,a=this.editor.selection.isEmpty(),n=this.ranges.length;n--;)if(!this.ranges[n].linked){var r=this.ranges[n].contains(e.row,e.column),i=a||this.ranges[n].contains(t.row,t.column);if(r&&i)return}this.detach()}},this.onChangeSession=function(){this.detach()},this.tabNext=function(e){var t=this.tabstops.length,a=this.index+(e||1);a=Math.min(Math.max(a,1),t),a==t&&(a=0),this.selectTabstop(a),0===a&&this.detach()},this.selectTabstop=function(e){this.$openTabstops=null;var t=this.tabstops[this.index];if(t&&this.addTabstopMarkers(t),this.index=e,t=this.tabstops[this.index],t&&t.length){if(this.selectedTabstop=t,this.editor.inVirtualSelectionMode)this.editor.selection.setRange(t.firstNonLinked);else{var a=this.editor.multiSelect;a.toSingleRange(t.firstNonLinked.clone());for(var n=t.length;n--;)t.hasLinkedRanges&&t[n].linked||a.addRange(t[n].clone(),!0);a.ranges[0]&&a.addRange(a.ranges[0].clone())}this.editor.keyBinding.addKeyboardHandler(this.keyboardHandler)}},this.addTabstops=function(e,t,a){if(this.$openTabstops||(this.$openTabstops=[]),!e[0]){var n=s.fromPoints(a,a);g(n.start,t),g(n.end,t),e[0]=[n],e[0].index=0}var r=this.index,i=[r+1,0],o=this.ranges;e.forEach(function(e,a){for(var n=this.$openTabstops[a]||e,r=e.length;r--;){var c=e[r],l=s.fromPoints(c.start,c.end||c.start);p(l.start,t),p(l.end,t),l.original=c,l.tabstop=n,o.push(l),n!=e?n.unshift(l):n[r]=l,c.fmtString?(l.linked=!0,n.hasLinkedRanges=!0):n.firstNonLinked||(n.firstNonLinked=l)}n.firstNonLinked||(n.hasLinkedRanges=!1),n===e&&(i.push(n),this.$openTabstops[a]=n),this.addTabstopMarkers(n)},this),i.length>2&&(this.tabstops.length&&i.push(i.splice(2,1)[0]),this.tabstops.splice.apply(this.tabstops,i))},this.addTabstopMarkers=function(e){var t=this.editor.session;e.forEach(function(e){e.markerId||(e.markerId=t.addMarker(e,"ace_snippet-marker","text"))})},this.removeTabstopMarkers=function(e){var t=this.editor.session;e.forEach(function(e){t.removeMarker(e.markerId),e.markerId=null})},this.removeRange=function(e){var t=e.tabstop.indexOf(e);e.tabstop.splice(t,1),t=this.ranges.indexOf(e),this.ranges.splice(t,1),this.editor.session.removeMarker(e.markerId),e.tabstop.length||(t=this.tabstops.indexOf(e.tabstop),-1!=t&&this.tabstops.splice(t,1),this.tabstops.length||this.detach())},this.keyboardHandler=new c,this.keyboardHandler.bindKeys({Tab:function(e){t.snippetManager&&t.snippetManager.expandWithTab(e)||e.tabstopManager.tabNext(1)},"Shift-Tab":function(e){e.tabstopManager.tabNext(-1)},Esc:function(e){e.tabstopManager.detach()},Return:function(e){return!1}})}).call(m.prototype);var h={};h.onChange=o.prototype.onChange,h.setPosition=function(e,t){this.pos.row=e,this.pos.column=t},h.update=function(e,t,a){this.$insertRight=a,this.pos=e,this.onChange(t)};var p=function(e,t){0==e.row&&(e.column+=t.column),e.row+=t.row},g=function(e,t){e.row==t.row&&(e.column-=t.column),e.row-=t.row};e("./lib/dom").importCssString(".ace_snippet-marker { -moz-box-sizing: border-box; box-sizing: border-box; background: rgba(194, 193, 208, 0.09); border: 1px dotted rgba(211, 208, 235, 0.62); position: absolute;}"),t.snippetManager=new u;var f=e("./editor").Editor;(function(){this.insertSnippet=function(e,a){return t.snippetManager.insertSnippet(this,e,a)},this.expandSnippet=function(e){return t.snippetManager.expandWithTab(this,e)}}).call(f.prototype)}),ace.define("ace/autocomplete/popup",["require","exports","module","ace/virtual_renderer","ace/editor","ace/range","ace/lib/event","ace/lib/lang","ace/lib/dom"],function(e,t,a){var n=e("../virtual_renderer").VirtualRenderer,r=e("../editor").Editor,i=e("../range").Range,s=e("../lib/event"),o=e("../lib/lang"),c=e("../lib/dom"),l=function(e){var t=new n(e);t.$maxLines=4;var a=new r(t);return a.setHighlightActiveLine(!1),a.setShowPrintMargin(!1),a.renderer.setShowGutter(!1),a.renderer.setHighlightGutterLine(!1),a.$mouseHandler.$focusWaitTimout=0,a.$highlightTagPending=!0,a},d=function(e){var t=c.createElement("div"),a=new l(t);e&&e.appendChild(t),t.style.display="none",a.renderer.content.style.cursor="default",a.renderer.setStyle("ace_autocomplete"),a.setOption("displayIndentGuides",!1),a.setOption("dragDelay",150);var n=function(){};a.focus=n,a.$isFocused=!0,a.renderer.$cursorLayer.restartTimer=n,a.renderer.$cursorLayer.element.style.opacity=0,a.renderer.$maxLines=8,a.renderer.$keepTextAreaAtCursor=!1,a.setHighlightActiveLine(!1),a.session.highlight(""),a.session.$searchHighlight.clazz="ace_highlight-marker",a.on("mousedown",function(e){var t=e.getDocumentPosition();a.selection.moveToPosition(t),u.start.row=u.end.row=t.row,e.stop()});var r,d=new i(-1,0,-1,1/0),u=new i(-1,0,-1,1/0);u.id=a.session.addMarker(u,"ace_active-line","fullLine"),a.setSelectOnHover=function(e){e?d.id&&(a.session.removeMarker(d.id),d.id=null):d.id=a.session.addMarker(d,"ace_line-hover","fullLine")},a.setSelectOnHover(!1),a.on("mousemove",function(e){if(!r)return void(r=e);if(r.x!=e.x||r.y!=e.y){r=e,r.scrollTop=a.renderer.scrollTop;var t=r.getDocumentPosition().row;d.start.row!=t&&(d.id||a.setRow(t),h(t))}}),a.renderer.on("beforeRender",function(){if(r&&-1!=d.start.row){r.$pos=null;var e=r.getDocumentPosition().row;d.id||a.setRow(e),h(e,!0)}}),a.renderer.on("afterRender",function(){var e=a.getRow(),t=a.renderer.$textLayer,n=t.element.childNodes[e-t.config.firstRow];n!=t.selectedNode&&(t.selectedNode&&c.removeCssClass(t.selectedNode,"ace_selected"),t.selectedNode=n,n&&c.addCssClass(n,"ace_selected"))});var m=function(){h(-1)},h=function(e,t){e!==d.start.row&&(d.start.row=d.end.row=e,t||a.session._emit("changeBackMarker"),a._emit("changeHoverMarker"))};a.getHoveredRow=function(){return d.start.row},s.addListener(a.container,"mouseout",m),a.on("hide",m),a.on("changeSelection",m),a.session.doc.getLength=function(){return a.data.length},a.session.doc.getLine=function(e){var t=a.data[e];return"string"==typeof t?t:t&&t.value||""};var p=a.session.bgTokenizer;return p.$tokenizeRow=function(e){var t=a.data[e],n=[];if(!t)return n;"string"==typeof t&&(t={value:t}),t.caption||(t.caption=t.value||t.name);var r,i,s=-1;t.iconClass&&n.push({type:"icon ace_icon-"+t.iconClass,value:" "});for(var o=0;oc-2&&(l=l.substr(0,c-t.caption.length-3)+"…"),n.push({type:"rightAlignedText",value:l})}return n},p.$updateOnChange=n,p.start=n,a.session.$computeWidth=function(){return this.screenWidth=0},a.$blockScrolling=1/0,a.isOpen=!1,a.isTopdown=!1,a.data=[],a.setData=function(e){a.setValue(o.stringRepeat("\n",e.length),-1),a.data=e||[],a.setRow(0)},a.getData=function(e){return a.data[e]},a.getRow=function(){return u.start.row},a.setRow=function(e){e=Math.max(0,Math.min(this.data.length,e)),u.start.row!=e&&(a.selection.clearSelection(),u.start.row=u.end.row=e||0,a.session._emit("changeBackMarker"),a.moveCursorTo(e||0,0),a.isOpen&&a._signal("select"))},a.on("changeSelection",function(){a.isOpen&&a.setRow(a.selection.lead.row),a.renderer.scrollCursorIntoView()}),a.hide=function(){this.container.style.display="none",this._signal("hide"),a.isOpen=!1},a.show=function(e,t,n){var i=this.container,s=window.innerHeight,o=window.innerWidth,c=this.renderer,l=c.$maxLines*t*1.4,d=e.top+this.$borderSize,u=d>s/2&&!n;u&&d+t+l>s?(c.$maxPixelHeight=d-2*this.$borderSize,i.style.top="",i.style.bottom=s-d+"px",a.isTopdown=!1):(d+=t,c.$maxPixelHeight=s-d-.2*t,i.style.top=d+"px",i.style.bottom="",a.isTopdown=!0),i.style.display="",this.renderer.$textLayer.checkForSizeChanges();var m=e.left;m+i.offsetWidth>o&&(m=o-i.offsetWidth),i.style.left=m+"px",this._signal("show"),r=null,a.isOpen=!0},a.getTextLeftOffset=function(){return this.$borderSize+this.renderer.$padding+this.$imageSize},a.$imageSize=0,a.$borderSize=1,a};c.importCssString(".ace_editor.ace_autocomplete .ace_marker-layer .ace_active-line { background-color: #CAD6FA; z-index: 1;}.ace_editor.ace_autocomplete .ace_line-hover { border: 1px solid #abbffe; margin-top: -1px; background: rgba(233,233,253,0.4);}.ace_editor.ace_autocomplete .ace_line-hover { position: absolute; z-index: 2;}.ace_editor.ace_autocomplete .ace_scroller { background: none; border: none; box-shadow: none;}.ace_rightAlignedText { color: gray; display: inline-block; position: absolute; right: 4px; text-align: right; z-index: -1;}.ace_editor.ace_autocomplete .ace_completion-highlight{ color: #000; text-shadow: 0 0 0.01em;}.ace_editor.ace_autocomplete { width: 280px; z-index: 200000; background: #fbfbfb; color: #444; border: 1px lightgray solid; position: fixed; box-shadow: 2px 3px 5px rgba(0,0,0,.2); line-height: 1.4;}"),t.AcePopup=d}),ace.define("ace/autocomplete/util",["require","exports","module"],function(e,t,a){t.parForEach=function(e,t,a){var n=0,r=e.length;0===r&&a();for(var i=0;r>i;i++)t(e[i],function(e,t){n++,n===r&&a(e,t)})};var n=/[a-zA-Z_0-9\$\-\u00A2-\uFFFF]/;t.retrievePrecedingIdentifier=function(e,t,a){a=a||n;for(var r=[],i=t-1;i>=0&&a.test(e[i]);i--)r.push(e[i]);return r.reverse().join("")},t.retrieveFollowingIdentifier=function(e,t,a){a=a||n;for(var r=[],i=t;i=t?a:t-1;break;case"down":t=t>=a?-1:t+1;break;case"start":t=0;break;case"end":t=a}this.popup.setRow(t)},this.insertMatch=function(e,t){if(e||(e=this.popup.getData(this.popup.getRow())),!e)return!1;if(e.completer&&e.completer.insertMatch)e.completer.insertMatch(this.editor,e);else{if(this.completions.filterText)for(var a,n=this.editor.selection.getAllRanges(),r=0;a=n[r];r++)a.start.column-=this.completions.filterText.length,this.editor.session.remove(a);e.snippet?c.insertSnippet(this.editor,e.snippet):this.editor.execCommand("insertstring",e.value||e)}this.detach()},this.commands={Up:function(e){e.completer.goTo("up")},Down:function(e){e.completer.goTo("down")},"Ctrl-Up|Ctrl-Home":function(e){e.completer.goTo("start")},"Ctrl-Down|Ctrl-End":function(e){e.completer.goTo("end")},Esc:function(e){e.completer.detach()},Return:function(e){return e.completer.insertMatch()},"Shift-Return":function(e){e.completer.insertMatch(null,{deleteSuffix:!0})},Tab:function(e){var t=e.completer.insertMatch();return t||e.tabstopManager?t:void e.completer.goTo("down")},PageUp:function(e){e.completer.popup.gotoPageUp()},PageDown:function(e){e.completer.popup.gotoPageDown()}},this.gatherCompletions=function(e,t){var a=e.getSession(),n=e.getCursorPosition(),r=(a.getLine(n.row),i.getCompletionPrefix(e));this.base=a.doc.createAnchor(n.row,n.column-r.length),this.base.$insertRight=!0;var s=[],o=e.completers.length;return e.completers.forEach(function(i,c){i.getCompletions(e,a,n,r,function(n,i){!n&&i&&(s=s.concat(i));var c=e.getCursorPosition();a.getLine(c.row);t(null,{prefix:r,matches:s,finished:0===--o})})}),!0},this.showPopup=function(e){this.editor&&this.detach(),this.activated=!0,this.editor=e,e.completer!=this&&(e.completer&&e.completer.detach(),e.completer=this),e.on("changeSelection",this.changeListener),e.on("blur",this.blurListener),e.on("mousedown",this.mousedownListener),e.on("mousewheel",this.mousewheelListener),this.updateCompletions()},this.updateCompletions=function(e){if(e&&this.base&&this.completions){var t=this.editor.getCursorPosition(),a=this.editor.session.getTextRange({start:this.base,end:t});if(a==this.completions.filterText)return;return this.completions.setFilter(a),this.completions.filtered.length&&(1!=this.completions.filtered.length||this.completions.filtered[0].value!=a||this.completions.filtered[0].snippet)?void this.openPopup(this.editor,a,e):this.detach()}var n=this.gatherCompletionsId;this.gatherCompletions(this.editor,function(t,a){var r=function(){return a.finished?this.detach():void 0}.bind(this),i=a.prefix,s=a&&a.matches;if(!s||!s.length)return r();if(0===i.indexOf(a.prefix)&&n==this.gatherCompletionsId){this.completions=new d(s),this.exactMatch&&(this.completions.exactMatch=!0),this.completions.setFilter(i);var o=this.completions.filtered;return o.length&&(1!=o.length||o[0].value!=i||o[0].snippet)?this.autoInsert&&1==o.length&&a.finished?this.insertMatch(o[0]):void this.openPopup(this.editor,i,e):r()}}.bind(this))},this.cancelContextMenu=function(){this.editor.$mouseHandler.cancelContextMenu()},this.updateDocTooltip=function(){var e=this.popup,t=e.data,a=t&&(t[e.getHoveredRow()]||t[e.getRow()]),n=null;return a&&this.editor&&this.popup.isOpen?(this.editor.completers.some(function(e){return e.getDocTooltip&&(n=e.getDocTooltip(a)),n}),n||(n=a),"string"==typeof n&&(n={docText:n}),n&&(n.docHTML||n.docText)?void this.showDocTooltip(n):this.hideDocTooltip()):this.hideDocTooltip()},this.showDocTooltip=function(e){this.tooltipNode||(this.tooltipNode=o.createElement("div"),this.tooltipNode.className="ace_tooltip ace_doc-tooltip",this.tooltipNode.style.margin=0,this.tooltipNode.style.pointerEvents="auto",this.tooltipNode.tabIndex=-1,this.tooltipNode.onblur=this.blurListener.bind(this));var t=this.tooltipNode;e.docHTML?t.innerHTML=e.docHTML:e.docText&&(t.textContent=e.docText),t.parentNode||document.body.appendChild(t);var a=this.popup,n=a.container.getBoundingClientRect();t.style.top=a.container.style.top,t.style.bottom=a.container.style.bottom,window.innerWidth-n.right<320?(t.style.right=window.innerWidth-n.left+"px",t.style.left=""):(t.style.left=n.right+1+"px",t.style.right=""),t.style.display="block"},this.hideDocTooltip=function(){if(this.tooltipTimer.cancel(),this.tooltipNode){var e=this.tooltipNode;this.editor.isFocused()||document.activeElement!=e||this.editor.focus(),this.tooltipNode=null,e.parentNode&&e.parentNode.removeChild(e)}}}).call(l.prototype),l.startCommand={name:"startAutocomplete",exec:function(e){e.completer||(e.completer=new l),e.completer.autoInsert=!1,e.completer.autoSelect=!0,e.completer.showPopup(e),e.completer.cancelContextMenu()},bindKey:"Ctrl-Space|Ctrl-Shift-Space|Alt-Space"};var d=function(e,t){this.all=e,this.filtered=e,this.filterText=t||"",this.exactMatch=!1};(function(){this.setFilter=function(e){if(e.length>this.filterText&&0===e.lastIndexOf(this.filterText,0))var t=this.filtered;else var t=this.all;this.filterText=e,t=this.filterCompletions(t,this.filterText),t=t.sort(function(e,t){return t.exactMatch-e.exactMatch||t.score-e.score});var a=null;t=t.filter(function(e){var t=e.snippet||e.caption||e.value;return t===a?!1:(a=t,!0)}),this.filtered=t},this.filterCompletions=function(e,t){var a=[],n=t.toUpperCase(),r=t.toLowerCase();e:for(var i,s=0;i=e[s];s++){var o=i.value||i.caption||i.snippet;if(o){var c,l,d=-1,u=0,m=0;if(this.exactMatch){if(t!==o.substr(0,t.length))continue e}else for(var h=0;h=0&&(0>g||g>p)?p:g,0>c)continue e;l=c-d-1,l>0&&(-1===d&&(m+=10),m+=l),u|=1<",s.escapeHTML(e.caption),"","
",s.escapeHTML(e.snippet)].join(""))}},u=[d,c,l];t.setCompleters=function(e){u.length=0,e&&u.push.apply(u,e)},t.addCompleter=function(e){u.push(e)},t.textCompleter=c,t.keyWordCompleter=l,t.snippetCompleter=d;var m,h={name:"expandSnippet",exec:function(e){return n.expandWithTab(e)},bindKey:"Tab"},p=function(e,t){g(t.session.$mode)},g=function k(e){var t=e.$id;n.files||(n.files={}),f(t),e.modes&&e.modes.forEach(k)},f=function x(e){if(e&&!n.files[e]){var t=e.replace("mode","snippets");n.files[e]={},i.loadModule(t,function(t){t&&(n.files[e]=t,!t.snippets&&t.snippetText&&(t.snippets=n.parseSnippetFile(t.snippetText)),n.register(t.snippets||[],t.scope),t.includeScopes&&(n.snippetMap[t.scope].includeScopes=t.includeScopes,t.includeScopes.forEach(function(e){x("ace/mode/"+e)})))})}},b=function(e){var t=e.editor,a=t.completer&&t.completer.activated;if("backspace"===e.command.name)a&&!o.getCompletionPrefix(t)&&t.completer.detach();else if("insertstring"===e.command.name){var n=o.getCompletionPrefix(t);n&&n.length>=t.$liveAutocompletionThreshold&&!a&&(t.completer||(t.completer=new r),t.completer.autoInsert=!1,t.completer.showPopup(t))}},v=s.delayedCall(function(){b(m)},0),y=function(e){m=e,v.delay(e.editor.$liveAutocompletionDelay)},w=e("../editor").Editor;e("../config").defineOptions(w.prototype,"editor",{enableBasicAutocompletion:{set:function(e){e?(this.completers||(this.completers=Array.isArray(e)?e:u),this.commands.addCommand(r.startCommand)):this.commands.removeCommand(r.startCommand)},value:!1},enableLiveAutocompletion:{set:function(e){e?(this.completers||(this.completers=Array.isArray(e)?e:u),this.commands.on("afterExec",y)):this.commands.removeListener("afterExec",y)},value:!1},liveAutocompletionThreshold:{value:0},liveAutocompletionDelay:{value:500},enableSnippets:{set:function(e){e?(this.commands.addCommand(h),this.on("changeMode",p),p(null,this)):(this.commands.removeCommand(h),this.off("changeMode",p))},value:!1}})}),function(){ace.require(["ace/ext/language_tools"],function(){})}(),ace.define("ace/ext/beautify/php_rules",["require","exports","module","ace/token_iterator"],function(e,t,a){e("ace/token_iterator").TokenIterator;t.newLines=[{type:"support.php_tag",value:""},{type:"paren.lparen",value:"{",indent:!0},{type:"paren.rparen",breakBefore:!0,value:"}",indent:!1},{type:"paren.rparen",breakBefore:!0,value:"})",indent:!1,dontBreak:!0},{type:"comment"},{type:"text",value:";"},{type:"text",value:":",context:"php"},{type:"keyword",value:"case",indent:!0,dontBreak:!0},{type:"keyword",value:"default",indent:!0,dontBreak:!0},{type:"keyword",value:"break",indent:!1,dontBreak:!0},{type:"punctuation.doctype.end",value:">"},{type:"meta.tag.punctuation.end",value:">"},{type:"meta.tag.punctuation.begin",value:"<",blockTag:!0,indent:!0,dontBreak:!0},{type:"meta.tag.punctuation.begin",value:""!=o.value?n="php":"support.php_tag"==o.type&&"?>"==o.value?n="html":"meta.tag.name.style"==o.type&&"css"!=n?n="css":"meta.tag.name.style"==o.type&&"css"==n?n="html":"meta.tag.name.script"==o.type&&"js"!=n?n="js":"meta.tag.name.script"==o.type&&"js"==n&&(n="html"),g=e.stepForward(),g&&0==g.type.indexOf("meta.tag.name")&&(s=g.value),"support.php_tag"==p.type&&"v;v++)u+=" ";break}if(h===!1)for(v in c)if(!(p.type!=c[v].type||c[v].value&&p.value!=c[v].value||c[v].blockTag&&-1!==d.indexOf(r)||c[v].context&&c[v].context!==n)){if(c[v].indent===!0&&m++,!c[v].dontBreak&&!f)for(u+="\n",v=0;m>v;v++)u+=" ";break}if(u+=b,"support.php_tag"==p.type&&"?>"==p.value&&(h=!1),i=r,p=o,o=g,null===o)break}else o=g;else o=e.stepForward();return u}}),ace.define("ace/ext/beautify",["require","exports","module","ace/token_iterator","ace/ext/beautify/php_rules"],function(e,t,a){var n=e("ace/token_iterator").TokenIterator,r=e("./beautify/php_rules").transform;t.beautify=function(e){var t=new n(e,0,0),a=(t.getCurrentToken(),e.$modeId.split("/").pop()),i=r(t,a);e.doc.setValue(i)},t.commands=[{name:"beautify",exec:function(e){t.beautify(e.session)},bindKey:"Ctrl-Shift-B"}]}),function(){ace.require(["ace/ext/beautify"],function(){})}(),ace.define("ace/mode/clickhouse_highlight_rules",["require","exports","$rootScope","module","ace/lib/oop","ace/snippets","ace/ext/language_tools","ace/mode/text_highlight_rules"],function(e,t,a){var n=e("../lib/oop"),r=e("./text_highlight_rules").TextHighlightRules,i=function(){var e=this,t="SELECT|CASE|THEN|DISTINCT|INSERT|UPDATE|DELETE|WHERE|AND|OR|OFFSET|HAVING|AS|FROM|WHEN|ELSE|END|TYPE|LEFT|RIGHT|JOIN|ON|OUTER|DESC|ASC|UNION|CREATE|TABLE|PRIMARY|KEY|FOREIGN|NOT|REFERENCES|DEFAULT|INNER|CROSS|NATURAL|DATABASE|DROP|GRANT|ANY|BETWEEN|ATTACH|DETACH|CAST|WITH|BIT_AND|BIT_OR|TO|BIT_XOR|DESCRIBE|OPTIMIZE|PREWHERE|TOTALS|DATABASES|PROCESSLIST|SHOW|IF",a="RENAME\\WTABLE|IF\\W+NOT\\W+EXISTS|IF\\W+EXISTS|FORMAT\\W+Vertical|FORMAT\\W+JSONCompact|FORMAT\\W+JSONEachRow|FORMAT\\W+TSKV|FORMAT\\W+TabSeparatedWithNames|FORMAT\\W+TabSeparatedWithNamesAndTypes|FORMAT\\W+TabSeparatedRaw|FORMAT\\W+BlockTabSeparated|FORMAT\\W+CSVWithNames|FORMAT\\W+CSV|FORMAT\\W+JSON|FORMAT\\W+TabSeparated",n="true|false|NULL",r="sum|sumIf|avg|avgIf",i="date|integer|uint8|uint16|uint32|uint64|int8|int16|int32|int64|float32|float64|datetime|enum8|enum16|fixedstring|array|tuple|stringMergeTree|SummingMergeTree|ReplacingMergeTree|ReplicatedMergeTree|Buffer|ReplicatedCollapsingMergeTree|CollapsingMergeTree|AggregatingMergeTree|Merge|Memory|GraphiteMergeTree|ReplicatedAggregatingMergeTree|ReplicatedSummingMergeTree",s=["IF NOT EXISTS","RENAME TABLE","IF EXISTS","GROUP BY","ORDER BY","UNION ALL","FORMAT JSON","FORMAT JSONCompact","FORMAT JSONEachRow","FORMAT TSV","FORMAT TabSeparated","FORMAT TabSeparatedWithNames","FORMAT TabSeparatedWithNamesAndTypes","FORMAT TabSeparatedRaw","FORMAT BlockTabSeparated","FORMAT TSKV","FORMAT CSV","FORMAT CSVWithNames","SYSTEM RELOAD DICTIONARY","SYSTEM RELOAD DICTIONARIES","SYSTEM DROP DNS CACHE","SYSTEM SHUTDOWN","SYSTEM KILL","CLEAR COLUMN IN PARTITION"],o=["DRAW_GMAPS","DRAW_PLOTLY","DRAW_CALENDAR","DRAW_TEXT","DRAW_HEATMAP","DRAW_CHART","DRAW_BAR","DRAW_GRIDCHART","DRAW_RIVER","DRAW_RAW","DRAW_SANKEYS","DRAW_TREEMAP","DRAW_C3","DRAW_MAP"],c="";if(window.aceJSRules&&window.aceJSRules.builtinFunctions){if(window.aceJSRules.builtinFunctions){var l=[];window.aceJSRules.builtinFunctions.forEach(function(e){l.push(e.name)}),r=l.join("|")}_.isArray(window.aceJSRules.tables)&&(c=window.aceJSRules.tables.join("|"))}var d="";d=window.global_delimiter?new RegExp(window.global_delimiter):new RegExp(";;");var u=[],m=t.toLowerCase();window.aceJSRules&&_.isArray(window.aceJSRules.fieldsList)&&window.aceJSRules.fieldsList.forEach(function(e){var t=e.name.toLowerCase()+"|";m.indexOf(t)>-1||u.push(e.name)});var h=this.createKeywordMapper({"support.function":r,keyword:t,"constant.language":n, +"storage.type":i,"markup.bold":c,"markup.heading":u.join("|")},"identifier",!0);this.$rules={start:[{token:"comment",regex:"--.*$",caseInsensitive:!0},{token:"comment.block",start:"```",end:"```"},{token:"keyword",regex:"GROUP\\W+BY|ON\\W+CLUSTER|ORDER\\W+BY|LIMIT\\W+\\d+\\W*,\\W*\\d+|LIMIT\\W+\\d+\\W+BY\\W+|LIMIT\\W+\\d+"},{token:"variable.language",regex:/\$[\w]+(?:\[[\w\]+]|[=\-]>\w+)?/},{token:"variable.language",regex:/@[\w]+(?:\[[\w\]+]|[=\-]>\w+)?/},{token:"variable.language",regex:/\:[\w]+(?:\[[\w\]+]|[=\-]>\w+)?/},{token:"variable.language",regex:/\{[\w]+(?:\[[\w\]+]|[=\-]>\w+)\}?/},{token:"comment",start:"/\\*",end:"\\*/"},{token:"constant",regex:'".*?"'},{token:"storage",regex:a},{token:"invalid.illegal",regex:o.join("|")},{token:"string",regex:"'.*?'"},{token:"constant.numeric",regex:"[+-]?\\d+(?:(?:\\.\\d*)?(?:[eE][+-]?\\d+)?)?\\b"},{token:h,regex:"[a-zA-Z_$][a-zA-Z0-9_$]*\\b"},{token:"constant.character.escape",regex:d},{token:"punctuation",regex:/[?:,;.]/},{token:"keyword.operator",regex:"\\+|\\-|\\/|\\/\\/|%|<@>|@>|<@|&|\\^|~|<|>|<=|=>|==|!=|<>|="},{token:"paren.lparen",regex:"[\\(\\{]"},{token:"paren.rparen",regex:"[\\)\\}]"},{token:"text",regex:"\\s+"}]},this.normalizeRules(),this.completions=[],this.getCompletions=function(){return e.completions},this.addCompletions=function(e,t,a,n,r,i,s){this.completions.push({name:e,value:t,caption:a,score:n,meta:r,iconClass:i,docHTML:s})},this.addCompletionsDictionaries=function(e){this.addCompletions(e.dic,e.dic,e.title,0,"dic","dict",this.makeCompletionsDocFunctions(e.title,e.dic))},this.addCompletionsFunctions=function(e){this.addCompletions(e.name,e.name+"( )",e.name+"( )",e.score,"function","function",this.makeCompletionsDocFunctions(e.name,e.origin,e.comb))},this.addCompletionsTableFiled=function(e){var t=e.table+"."+e.name,a=e.name,n="type:"+e.type+"

default_type:"+e.default_type+"
"+e.default_expression;this.addCompletions(t,a,a,100,e.type,"field",this.makeCompletionsdocHTML(t,n))},this.addArrayCompletions=function(e,t,a){var n=this;e.forEach(function(e){n.addCompletions(e,e,e,0,t,a,!1)})},this.setKeywords=function(e){console.log("setKeywords > ",e),this.keywordRule.onMatch=this.createKeywordMapper(e,"identifier")},this.makeCompletionsDocFunctions=function(e,t,a){if(!window.global_chFunctionsHelp)return!1;if(!window.global_chFunctionsHelp.functions)return!1;var n="",r=e;if("undefined"!=typeof window.global_chFunctionsHelp.functions[e]?r=e:"undefined"!=typeof window.global_chFunctionsHelp.functions[t]&&(r=t),"undefined"!=typeof window.global_chFunctionsHelp.functions[r]){var i="en",s=window.global_chFunctionsHelp.functions[r],o="",c="";s.desc&&(o=s.bracket,c=s.desc[i],c||(c=s.desc.en?s.desc.en:s.desc.ru)),c&&(c=c.replace(/\.\s*/gm,".
")),n=''+e+o+'
'+c+" "}else n=''+e+"( )
"+t;return n+'
'},this.makeCompletionsdocHTML=function(e,t){return'
'+e+"
"+t+"
"},this.addArrayCompletions(t.split("|"),"keyword","keyword"),this.addArrayCompletions(s,"keyword","keyword"),this.addArrayCompletions(o,"draw","draw"),this.addArrayCompletions(i.split("|"),"type","type")};n.inherits(i,r),t.ClickhouseHighlightRules=i}),ace.define("ace/mode/matching_brace_outdent",["require","exports","module","ace/range"],function(e,t,a){var n=e("ace/range").Range,r=function(){};(function(){this.checkOutdent=function(e,t){return/^\s+$/.test(e)?/^\s*\}/.test(t):!1},this.autoOutdent=function(e,t){var a=e.getLine(t),r=a.match(/^(\s*\})/);if(!r)return 0;var i=r[1].length,s=e.findMatchingBracket({row:t,column:i});if(!s||s.row==t)return 0;var o=this.$getIndent(e.getLine(s.row));e.replace(new n(t,0,t,i-1),o)},this.$getIndent=function(e){return e.match(/^\s*/)[0]}}).call(r.prototype),t.MatchingBraceOutdent=r}),ace.define("ace/mode/clickhouse_FoldMode",["$rootScope","require","exports","module","ace/lib/oop","ace/range","ace/mode/sqlserver","ace/mode/folding/cstyle"],function(e,t,a){var n=e("../lib/oop"),r=e("ace/mode/folding/cstyle").FoldMode,i=(e("ace/range").Range,e("ace/token_iterator").TokenIterator),s=t.FoldMode=function(){};n.inherits(s,r),function(){this.foldingRules="cStyle",this.foldingStartMarker=/\(|\{/,this.getFoldWidgetRange=function(e,t,a,n){for(var r=new i(e,a,0),s=r.getCurrentToken(),o=!1;s;){var c=s,l=r.getCurrentTokenPosition();if(s=r.stepForward(),"paren.lparen"!=c.type||"("!=c.value&&"{"!=c.value||(o=e.getBracketRange(l)),o)break}return o}}.call(s.prototype)}),window.global_chFunctionsHelp={functions:{corr:{bracket:"(x, y)",desc:{en:'Calculates the Pearson correlation coefficient: Σ((x - x̅)(y - y̅)) / sqrt(Σ((x - x̅)2) * Σ((y - y̅)2)).'}},stddevPop:{bracket:"(x)",desc:{en:"The result is equal to the square root of 'varPop(x)'."}},varPop:{bracket:"(x, y)",desc:{en:"Calculates the value of %%Σ((x - x̅)(y - y̅)) / n%%."}},argMin:{bracket:"(arg, val)",desc:{en:"Calculates the 'arg' value for a minimal 'val' value. If there are several different values of 'arg' for minimal values of 'val', the first of these values encountered is output."}},quantileExactWeighted:{bracket:"(level)(x, weight)",desc:{en:"Вычисляет квантиль уровня level точно."}},min:{bracket:"(v)",desc:{en:"Minimal execution speed in rows per second. Checked on every data block when 'timeout_before_checking_execution_speed' expires. If the execution speed is lower, an exception is thrown."}},varSamp:{bracket:"(x, y)",desc:{en:"Calculates the value of %%Σ((x - x̅)(y - y̅)) / (n - 1)%%.

Returns Float64. If n <= 1, it returns +∞."}},anyLast:{bracket:"(x)",desc:{en:"Selects the last value encountered.
The result is just as indeterminate as for the 'any' function."}},argMax:{bracket:"(arg, val)",desc:{en:"Calculates the 'arg' value for a maximum 'val' value. If there are several different values of 'arg' for maximum values of 'val', the first of these values encountered is output."}},count:{bracket:"()",desc:{en:"Counts the number of rows. "}},any:{bracket:"(x)",desc:{en:"Selects the last value encountered.
The result is just as indeterminate as for the 'any' function."}},avg:{bracket:"(x)",desc:{en:"Calculates the average.
Only works for numbers.
The result is always Float64."}},sequenceMatch:{bracket:"(pattern)(time, cond1, cond2, ...)",desc:{en:"Pattern matching for event chains.

'pattern' is a string containing a pattern to match."}},stddevSamp:{bracket:"(x)",desc:{en:"The result is equal to the square root of 'varSamp(x)'."}},medianDeterministic:{bracket:"(x, determinator)",desc:{en:"This function works similarly to the 'median' function - it approximates the median."}},quantilesTimingWeighted:{bracket:"(level1, level2, ...)(x, weight)",desc:{en:"Calculates the quantiles of all specified levels using the same algorithm as the 'medianTimingWeighted' function."}},uniq:{bracket:"(N)(x)",desc:{en:"Calculates the number of different argument values, if it is less than or equal to N.
If the number of different argument values is greater than N, it returns N + 1."}},covarSamp:{bracket:"(x, y)",desc:{en:"Calculates the value of %%Σ((x - x̅)(y - y̅)) / (n - 1)%%.

Returns Float64. If n <= 1, it returns +∞."}},max:{bracket:"(v)",desc:{en:"Maximum number of bytes (uncompressed data) that can be passed to a remote server or saved in a temporary table when using GLOBAL IN."}},quantileTDigest:{bracket:"(level)(x)",desc:{en:"t-digest"}},quantilesTiming:{bracket:"(level1, level2, ...)(x, weight)",desc:{en:"Calculates the quantiles of all specified levels using the same algorithm as the 'medianTimingWeighted' function."}},quantiles:{bracket:"(level1, level2, ...)(x, determinator)",desc:{en:"Calculates the quantiles of all specified levels using the same algorithm as the 'medianDeterministic' function."}},quantile:{bracket:"(level1, level2, ...)(x, determinator)",desc:{en:"Calculates the quantiles of all specified levels using the same algorithm as the 'medianDeterministic' function."}},groupArray:{bracket:"(x)",desc:{en:"Creates an array of argument values.
Values can be added to the array in any (indeterminate) order.

In some cases, you can rely on the order of execution. This applies to cases when SELECT comes from a subquery that uses ORDER BY."}},sum:{bracket:"(x)",desc:{en:"Calculates the sum.
Only works for numbers."}},median:{bracket:"(x, weight)",desc:{en:"Differs from the 'medianTiming' function in that it has a second argument - "weights". Weight is a non-negative integer.
The result is calculated as if the 'x' value were passed 'weight' number of times to the 'medianTiming' function."}},quantileTiming:{bracket:"(level)(x, weight)",desc:{en:"Calculates the quantile of 'level' using the same algorithm as the 'medianTimingWeighted' function."}},quantileTimingWeighted:{bracket:"(level)(x, weight)",desc:{en:"Calculates the quantile of 'level' using the same algorithm as the 'medianTimingWeighted' function."}},groupUniqArray:{bracket:"(x)",desc:{en:"Creates an array from different argument values. Memory consumption is the same as for the 'uniqExact' function."}},uniqHLL12:{bracket:"(x)",desc:{en:"Uses the HyperLogLog algorithm to approximate the number of different values of the argument. "}},covarPop:{bracket:"(x, y)",desc:{en:"Calculates the value of %%Σ((x - x̅)(y - y̅)) / n%%."}},sequenceCount:{bracket:"(pattern)(time, cond1, cond2, ...)",desc:{en:"sequenceMatch"}},quantileDeterministic:{bracket:"(level)(x, determinator)",desc:{en:"Calculates the quantile of 'level' using the same algorithm as the 'medianDeterministic' function."}},quantileExact:{bracket:"(level)(x, weight)",desc:{en:""}},quantilesDeterministic:{bracket:"(level1, level2, ...)(x, determinator)",desc:{en:"Calculates the quantiles of all specified levels using the same algorithm as the 'medianDeterministic' function."}},medianTiming:{bracket:"(x, weight)",desc:{en:"Differs from the 'medianTiming' function in that it has a second argument - "weights"."}},medianTimingWeighted:{bracket:"(x, weight)",desc:{ru:"",en:"Differs from the 'medianTiming' function in that it has a second argument - "weights"."}},uniqExact:{bracket:"(x)",desc:{en:"Calculates the number of different values of the argument, exactly.
There is no reason to fear approximations, so it's better to use the 'uniq' function.
You should use the 'uniqExact' function if you definitely need an exact result. "}},uniqCombined:{bracket:"(x)",desc:{en:""}},uniqUpTo:{bracket:"(N)(x)",desc:{en:"Calculates the number of different argument values, if it is less than or equal to N.
If the number of different argument values is greater than N, it returns N + 1."}},substring:{bracket:"(s, offset, length)",desc:{en:"The same as 'substring', but for Unicode code points. Works under the assumption that the string contains a set of bytes representing a UTF-8 encoded text. If this assumption is not met, it returns some result (it doesn't throw an exception)."}},notLike:{bracket:"(haystack, pattern), haystack NOT LIKE pattern operator",desc:{en:"The same thing as 'like', but negative."}},hostName:{bracket:"()",desc:{en:"Returns a string with the name of the host that this function was performed on. For distributed processing, this is the name of the remote server host, if the function is performed on a remote server."}},globalNotIn:{bracket:"(v)",desc:{en:"See the section "IN operators"."}},or:{bracket:"(v)",desc:{en:"The same thing as 'max_temporary_columns', but without counting constant columns.
Note that constant columns are formed fairly often when running a query, but they require approximately zero computing resources."}},extractAll:{bracket:"(haystack, pattern)",desc:{en:"Extracts all the fragments of a string using a regular expression. If 'haystack' doesn't match the 'pattern' regex, an empty string is returned. Returns an array of strings consisting of all matches to the regex."}},arrayFirst:{bracket:"(func, arr1, ...)",desc:{en:"Returns the index of the first element in the 'arr1' array for which 'func' returns something other than 0."}},notEquals:{bracket:"(v)",desc:{ru:"",en:""}},arrayExists:{bracket:"([func,] arr1, ...)",desc:{en:"Returns 1 if there is at least one element in 'arr' for which 'func' returns something other than 0. Otherwise, it returns 0."}},arrayCount:{bracket:"([func,] arr1, ...)",desc:{en:"Returns the number of elements in 'arr' for which 'func' returns something other than 0. If 'func' is not specified, it returns the number of non-zero items in the array."}},arrayMap:{bracket:"(func, arr1, ...)",desc:{en:"Returns an array obtained from the original application of the 'func' function to each element in the 'arr' array."}},now:{bracket:"(v)",desc:{en:"If the parameter is true, INSERT operation will skip columns with unknown names from input.
Otherwise, an exception will be generated, it is default behavior.
The parameter works only for JSONEachRow and TSKV input formats."}},intDiv:{bracket:"(a, b)",desc:{en:"Differs from 'intDiv' in that it returns zero when dividing by zero or when dividing a minimal negative number by minus one."}},topLevelDomain:{bracket:"(v)",desc:{en:"- Selects the top-level domain. Example: .ru."}},intHash32:{bracket:"(v)",desc:{en:"Calculates a 32-bit hash code from any type of integer.
This is a relatively fast non-cryptographic hash function of average quality for numbers."}},replaceOne:{bracket:"(haystack, pattern, replacement)",desc:{en:"Replaces the first occurrence, if it exists, of the 'pattern' substring in 'haystack' with the 'replacement' substring.
Hereafter, 'pattern' and 'replacement' must be constants."}},cityHash64:{bracket:"(v)",desc:{en:"Calculates CityHash64 from a string or a similar hash function for any number of any type of arguments.
For String-type arguments, CityHash is used. This is a fast non-cryptographic hash function for strings with decent quality"}},OSToRoot:{bracket:"(v)",desc:{en:"Accepts a UInt8 number - the ID of the operating system from the Yandex.Metrica dictionary. If any OS matches the passed number, it returns a UInt8 number - the ID of the corresponding root OS (for example, it converts Windows Vista to Windows). Otherwise, returns 0."}},sipHash128:{bracket:"(v)",desc:{en:"Calculates SipHash from a string.
Accepts a String-type argument. Returns FixedString(16).
Differs from sipHash64 in that the final xor-folding state is only done up to 128 bits."}},SHA1:{bracket:"(v)",desc:{en:"Calculates SHA-1, SHA-224, or SHA-256 from a string and returns the resulting set of bytes as FixedString(20), FixedString(28), or FixedString(32)."}},asin:{bracket:"(x)",desc:{en:"The arc sine."}},SHA256:{bracket:"(v)",desc:{en:"Calculates SHA-1, SHA-224, or SHA-256 from a string and returns the resulting set of bytes as FixedString(20), FixedString(28), or FixedString(32)."}},MD5:{bracket:"(v)",desc:{en:"Calculates the MD5 from a string and returns the resulting set of bytes as FixedString(16)."}},bitmaskToList:{bracket:"(num)",desc:{en:"Accepts an integer. Returns a string containing the list of powers of two that total the source number when summed. They are comma-separated without spaces in text format, in ascending order."}},array:{bracket:"(v)",desc:{en:"The -%%Array%% suffix can be appended to any aggregate function. In this case, the aggregate function takes arguments of the 'Array(T)' type (arrays) instead of 'T' type arguments. If the aggregate function accepts multiple arguments, this must be arrays of equal lengths. "}},dictGetStringOrDefault:{bracket:"(v)",desc:{ru:"%%dictGetT('dict_name', 'attr_name', id, default)%%
Аналогично функциям dictGetT, но значение по умолчанию берётся из последнего аргумента функции.",en:""}},greaterOrEquals:{bracket:"(v)",desc:{ru:"",en:""}},e:{bracket:"(v)",desc:{en:"What to do when the amount of data exceeds one of the limits: 'throw' or 'break'. By default, throw."}},runningDifference:{bracket:"(x)",desc:{en:"Calculates the difference between consecutive values in the data block.
Result of the function depends on the order of the data in the blocks.

It works only inside of the each processed block of data. Data splitting in the blocks is not explicitly controlled by the user. "}},not:{bracket:"(v)",desc:{ru:'Смотрите раздел "Операторы IN".',en:"See the section "IN operators"."}},intHash64:{bracket:"(v)",desc:{en:"Calculates a 64-bit hash code from any type of integer.
It works faster than intHash32. Average quality."}},acos:{bracket:"(x)",desc:{ru:"Арккосинус.",en:"The arc cosine."}},dictGetString:{bracket:"(v)",desc:{en:""}},and:{bracket:"(x, determinator)",desc:{en:"This function works similarly to the 'median' function - it approximates the median. However, in contrast to 'median', the result is deterministic and does not depend on the order of query execution.

To achieve this, the function takes a second argument - the "determinator". "}},dictGetDate:{bracket:"(v)",desc:{ru:"",en:""}},dictGetFloat32:{bracket:"(v)",desc:{ru:"",en:""}},dictGetInt8:{bracket:"(v)",desc:{ru:"",en:""}},dictGetUInt32:{bracket:"(v)",desc:{ru:"",en:""}},OSIn:{bracket:"(lhs, rhs)",desc:{en:"Checks whether the 'lhs' operating system belongs to the 'rhs' operating system."}},arrayFirstIndex:{bracket:"(func, arr1, ...)",desc:{en:"Returns the index of the first element in the 'arr1' array for which 'func' returns something other than 0."}},ceil:{bracket:"(x[, N])",desc:{en:"Returns the smallest round number that is greater than or equal to 'x'. In every other way, it is the same as the 'floor' function (see above)."}},fragment:{bracket:"(v)",desc:{en:"Removes the query-string and fragment identifier. The question mark and number sign are also removed."}},dictGetUInt8:{bracket:"(v)",desc:{ru:"",en:""}},dictHas:{bracket:"(v)",desc:{ru:"%%dictHas('dict_name', id)%%
- проверить наличие ключа в словаре. Возвращает значение типа UInt8, равное 0, если ключа нет и 1, если ключ есть.",en:""}},arraySum:{bracket:"([func,] arr1, ...)",desc:{en:"Returns the sum of the 'func' values. If the function is omitted, it just returns the sum of the array elements."}},emptyArrayDateTime:{bracket:"(v)",desc:{en:"Accepts zero arguments and returns an empty array of the appropriate type."}},intDivOrZero:{bracket:"(a, b)",desc:{en:"Differs from 'intDiv' in that it returns zero when dividing by zero or when dividing a minimal negative number by minus one."}},SEHierarchy:{bracket:"(v)",desc:{en:"Accepts a UInt8 number - the ID of the search engine from the Yandex.Metrica dictionary. Returns an array with a hierarchy of search engines. Similar to the 'regionHierarchy' function."}},regionToContinent:{bracket:"(id[, geobase])",desc:{en:"Converts a region to a continent. In every other way, this function is the same as 'regionToCity'.
Example: %%regionToContinent(toUInt32(213)) = 10001%% converts Moscow (213) to Eurasia (10001)."}},dictGetInt32:{bracket:"(v)",desc:{ru:"",en:""}},toInt8:{bracket:"(v)",desc:{en:"Functions for converting between numbers, strings (but not fixed strings), dates, and dates with times. All these functions accept one argument. "}},materialize:{bracket:"(x)",desc:{en:"Turns a constant into a full column containing just one value.
In ClickHouse, full columns and constants are represented differently in memory. Functions work differently for constant arguments and normal arguments (different code is executed), although the result is almost always the same. This function is for debugging this behavior."}},regionToCountry:{bracket:"(id[, geobase])",desc:{en:"Converts a region to a country. In every other way, this function is the same as 'regionToCity'.
Example: %%regionToCountry(toUInt32(213)) = 225%% converts Moscow (213) to Russia (225)."}},dictGetDateTime:{bracket:"(v)",desc:{ru:"",en:""}},xor:{bracket:"(v)",desc:{ru:"",en:""}},regionToCity:{bracket:"(id[, geobase])",desc:{en:"Accepts a UInt32 number - the region ID from the Yandex geobase. If this region is a city or part of a city, it returns the region ID for the appropriate city. Otherwise, returns 0."}},dictGetFloat64:{bracket:"(v)",desc:{ru:"",en:""}},timeSlot:{bracket:"(StartTime, Duration)",desc:{en:"For a time interval starting at 'StartTime' and continuing for 'Duration' seconds, it returns an array of moments in time, consisting of points from this interval rounded down to the half hour."}},toTime:{bracket:"(v)",desc:{en:"Converts a date with time to the date of the start of the Unix Epoch, while preserving the time."}},log2:{bracket:"(x)",desc:{en:"Accepts a numeric argument and returns a Float64 number close to the binary logarithm of the argument."}},toRelativeHourNum:{bracket:"(v)",desc:{en:"Converts a date with time or date to the number of the hour, starting from a certain fixed point in the past."}},toRelativeDayNum:{bracket:"(v)",desc:{en:"Converts a date with time or date to the number of the day, starting from a certain fixed point in the past."}},toRelativeWeekNum:{bracket:"(v)",desc:{en:"Converts a date with time or date to the number of the week, starting from a certain fixed point in the past."}},splitByString:{bracket:"(separator, s)",desc:{en:"The same as above, but it uses a string of multiple characters as the separator. The string must be non-empty."}},currentDatabase:{bracket:"()",desc:{en:"Returns the name of the current database.
You can use this function in table engine parameters in a CREATE TABLE query where you need to specify the database."}},toRelativeMonthNum:{bracket:"(v)",desc:{en:"Converts a date with time or date to the number of the month, starting from a certain fixed point in the past."}},visibleWidth:{bracket:"(x)",desc:{en:"Calculates the approximate width when outputting values to the console in text format (tab-separated). This function is used by the system for implementing Pretty formats."}},bitShiftRight:{bracket:"(a, b)",desc:{en:""}},toRelativeYearNum:{bracket:"(v)",desc:{en:"Converts a date with time or date to the number of the year, starting from a certain fixed point in the past."}},toStartOfHour:{bracket:"(v)",desc:{en:"Rounds down a date with time to the start of the hour."}},halfMD5:{bracket:"(v)",desc:{en:"Calculates the MD5 from a string. Then it takes the first 8 bytes of the hash and interprets them as UInt64 in big endian."}},toStartOfFiveMinute:{bracket:"(v)",desc:{en:""}},toUInt16OrZero:{bracket:"(v)",desc:{en:"Functions for converting between numbers, strings (but not fixed strings), dates, and dates with times. All these functions accept one argument."}},toMonday:{bracket:"(v)",desc:{en:"Rounds down a date or date with time to the nearest Monday.
Returns the date."}},IPv6NumToString:{bracket:"(x)",desc:{en:"Accepts a FixedString(16) value containing the IPv6 address in binary format. Returns a string containing this address in text format. "}},indexOf:{bracket:"(arr, x)",desc:{ru:"Возвращает индекс элемента x (начиная с 1), если он есть в массиве, или 0, если его нет.",en:"Returns the index of the 'x' element (starting from 1) if it is in the array, or 0 if it is not."}},today:{bracket:"(v)",desc:{ru:"Принимает ноль аргументов и возвращает текущую дату на один из моментов выполнения запроса.
То же самое, что toDate(now())",en:"Accepts zero arguments and returns the current date at one of the moments of request execution.
The same as 'toDate(now())'."}},emptyArrayToSingle:{bracket:"(v)",desc:{ru:"Принимает пустой массив и возвращает массив из одного элемента, равного значению по умолчанию.",en:"Accepts an empty array as argument and returns an array of one element equal to the default value."}},sleep:{bracket:"(seconds)",desc:{ru:"Спит seconds секунд на каждый блок данных. Можно указать как целое число, так и число с плавающей запятой.",en:"Sleeps 'seconds' seconds on each data block. You can specify an integer or a floating-point number."}},extract:{bracket:"(params, name)",desc:{en:"Parses the string in double quotes. The value is unescaped. If unescaping failed, it returns an empty string. Examples: "}},emptyArrayInt8:{bracket:"(v)",desc:{ru:"Принимает ноль аргументов и возвращает пустой массив соответствующего типа.",en:"Accepts zero arguments and returns an empty array of the appropriate type."}},regionToName:{bracket:"(id[, lang])",desc:{en:"Accepts a UInt32 number - the region ID from the Yandex geobase. A string with the name of the language can be passed as a second argument. Supported languages are: ru, en, ua, uk, by, kz, tr. If the second argument is omitted, the language 'ru' is used. "}},concat:{bracket:"(arr[, separator])",desc:{ru:"Склеивает строки, перечисленные в массиве, с разделителем separator.
separator - необязательный параметр, константная строка, по умолчанию равен пустой строке.
Возвращается строка.",en:"Concatenates strings from the array elements, using 'separator' as the separator.
'separator' is a string constant, an optional parameter. By default it is an empty string.
Returns a string."}},convertCharset:{bracket:"(s, from, to)",desc:{ru:"Возвращает сконвертированную из кодировки from в кодировку to строку s.",en:"Returns a string with the data %%s%% (encoded as %%from%% charset) that was converted to the %%to%% charset."}},toMonth:{bracket:"(v)",desc:{ru:"Переводит дату или дату-с-временем в число типа UInt8, содержащее номер месяца (1-12).",en:"Converts a date or date with time to a UInt8 number containing the month number (1-12)."}},IPv6StringToNum:{bracket:"(s)",desc:{ru:"Функция, обратная к IPv6NumToString. Если IPv6 адрес в неправильном формате, то возвращает строку из нулевых байт.
HEX может быть в любом регистре.",en:"The reverse function of IPv6NumToString. If the IPv6 address has an invalid format, it returns a string of null bytes.
HEX can be uppercase or lowercase."}},emptyArrayString:{bracket:"(v)",desc:{ru:"Принимает ноль аргументов и возвращает пустой массив соответствующего типа.",en:"Accepts zero arguments and returns an empty array of the appropriate type."}},uptime:{bracket:"()",desc:{ru:"Возвращает аптайм сервера в секундах.",en:"Returns server's uptime in seconds."}},blockSize:{bracket:"()",desc:{en:"Gets the size of the block.
In ClickHouse, queries are always run on blocks (sets of column parts). This function allows getting the size of the block that you called it for."}},toInt64OrZero:{bracket:"(v)",desc:{en:"Functions for converting between numbers, strings (but not fixed strings), dates, and dates with times. All these functions accept one argument. "}},pathFull:{bracket:"(v)",desc:{ru:"То же самое, но включая query string и fragment. Пример: /top/news.html?page=2#comments",en:"- The same as above, but including query-string and fragment. Example: /top/news.html?page=2#comments"}},emptyArrayDate:{bracket:"(v)",desc:{ru:"Принимает ноль аргументов и возвращает пустой массив соответствующего типа.",en:"Accepts zero arguments and returns an empty array of the appropriate type."}},emptyArrayInt64:{bracket:"(v)",desc:{ru:"Принимает ноль аргументов и возвращает пустой массив соответствующего типа.",en:"Accepts zero arguments and returns an empty array of the appropriate type."}},toInt32OrZero:{bracket:"(v)",desc:{en:"Functions for converting between numbers, strings (but not fixed strings), dates, and dates with times. All these functions accept one argument. "}},greater:{bracket:"(v)",desc:{ru:"",en:""}},emptyArrayInt32:{bracket:"(v)",desc:{ru:"Принимает ноль аргументов и возвращает пустой массив соответствующего типа.",en:"Accepts zero arguments and returns an empty array of the appropriate type."}},toString:{bracket:"(str)",desc:{ru:"Принимает значение типа FixedString(16). Возвращает строку из 36 символов в текстовом виде.",en:"Accepts a FixedString(16) value containing the UUID in the binary format. Returns a readable string containing the UUID in the text format."}},greatest:{bracket:"(a, b)",desc:{ru:"Возвращает наибольшее значение из a и b.",en:"Returns the greatest element of a and b."}},emptyArrayUInt64:{bracket:"(v)",desc:{ru:"Принимает ноль аргументов и возвращает пустой массив соответствующего типа.",en:"Accepts zero arguments and returns an empty array of the appropriate type."}},emptyArrayUInt32:{bracket:"(v)",desc:{ru:"Принимает ноль аргументов и возвращает пустой массив соответствующего типа.",en:"Accepts zero arguments and returns an empty array of the appropriate type."}},formatReadableSize:{bracket:"(x)",desc:{en:"Gets a size (number of bytes). Returns a string that contains rounded size with the suffix (KiB, MiB etc.).

Example:

%% "}},toInt16OrZero:{bracket:"(v)",desc:{en:"Functions for converting between numbers, strings (but not fixed strings), dates, and dates with times. All these functions accept one argument. "}},emptyArrayUInt8:{bracket:"(v)",desc:{ru:"Принимает ноль аргументов и возвращает пустой массив соответствующего типа.",en:"Accepts zero arguments and returns an empty array of the appropriate type."}},protocol:{bracket:"(v)",desc:{ru:"Возвращает протокол. Примеры: http, ftp, mailto, magnet...",en:"- Selects the protocol. Examples: http, ftp, mailto, magnet..."}},regionToPopulation:{bracket:"(id[, geobase])",desc:{en:"Gets the population for a region.
The population can be recorded in files with the geobase. See the section "External dictionaries".
If the population is not recorded for the region, it returns 0.
In the Yandex geobase, the population might be recorded for child regions, but not for parent regions."}},notIn:{bracket:"(v)",desc:{ru:'Смотрите раздел "Операторы IN".',en:"See the section "IN operators"."}},position:{bracket:"(haystack, needle)",desc:{en:"The same as 'position', but the position is returned in Unicode code points. Works under the assumption that the string contains a set of bytes representing a UTF-8 encoded text. If this assumption is not met, it returns some result (it doesn't throw an exception).
There's also positionCaseInsensitiveUTF8 function."}},arrayElement:{bracket:"(arr, n), arr[n] operator",desc:{en:"Get the element with the index 'n' from the array 'arr'.
'n' should be any integer type.
Indexes in an array begin from one.
Negative indexes are supported - in this case, it selects the corresponding element numbered from the end. "}},toStringCutToZero:{bracket:"(s)",desc:{en:"Accepts a String or FixedString argument. Returns a String that is cut to a first null byte occurrence."}},log:{bracket:"(x)",desc:{ru:"Принимает числовой аргумент, возвращает число типа Float64, близкое к десятичному логарифму от аргумента.",en:"Accepts a numeric argument and returns a Float64 number close to the decimal logarithm of the argument."}},SEIn:{bracket:"(lhs, rhs)",desc:{ru:"Проверяет принадлежность поисковой системы lhs поисковой системе rhs.",en:"Checks whether the 'lhs' search engine belongs to the 'rhs' search engine."}},replicate:{bracket:"(v)",desc:{en:"Create a MergeTree table with a different name. Move all the data from the directory with the ReplicatedMergeTree table data to the new table's data directory." +}},sipHash64:{bracket:"(v)",desc:{en:'Calculates SipHash from a string.
Accepts a String-type argument. Returns UInt64.
SipHash is a cryptographic hash function. It works at least three times faster than MD5. For more information, see https://131002.net/siphash/'}},emptyArrayUInt16:{bracket:"(v)",desc:{en:"Accepts zero arguments and returns an empty array of the appropriate type."}},hex:{bracket:"(str)",desc:{en:"Accepts a string containing any number of hexadecimal digits, and returns a string containing the corresponding bytes. Supports both uppercase and lowercase letters A-F. The number of hexadecimal digits doesn't have to be even."}},regionToDistrict:{bracket:"(id[, geobase])",desc:{en:"Converts a region to a federal district (type 4 in the geobase). In every other way, this function is the same as 'regionToCity'. "}},arrayFilter:{bracket:"(func, arr1, ...)",desc:{en:"Returns an array containing only the elements in 'arr1' for which 'func' returns something other than 0.

Examples:

%%
SELECT arrayFilter(x -> x LIKE '%World%', ['Hello', 'abc World']) AS res "}},toStartOfQuarter:{bracket:"(v)",desc:{en:"Rounds down a date or date with time to the first day of the quarter.
The first day of the quarter is either 1 January, 1 April, 1 July, or 1 October. Returns the date."}},divide:{bracket:"(a, b), a / b operator",desc:{en:"Calculates the quotient of the numbers. The result type is always a floating-point type.
It is not integer division. For integer division, use the 'intDiv' function.
When dividing by zero you get 'inf', '-inf', or 'nan'."}},reverseUTF8:{bracket:"(v)",desc:{en:"Reverses a sequence of Unicode code points, assuming that the string contains a set of bytes representing a UTF-8 text. Otherwise, it does something else (it doesn't throw an exception)."}},toDate:{bracket:"(v)",desc:{en:"Functions for converting between numbers, strings (but not fixed strings), dates, and dates with times. All these functions accept one argument. "}},emptyArrayFloat64:{bracket:"(v)",desc:{en:"Accepts zero arguments and returns an empty array of the appropriate type."}},abs:{bracket:"(s, c)",desc:{en:"If the %%s%% string is non-empty and does not contain the %%c%% character at the end, it appends the %%c%% character to the end."}},yesterday:{bracket:"(v)",desc:{en:"Accepts zero arguments and returns yesterday's date at one of the moments of request execution.
The same as 'today() - 1'."}},toMinute:{bracket:"(v)",desc:{en:"Converts a date with time to a UInt8 number containing the number of the minute of the hour (0-59)."}},bitXor:{bracket:"(a, b)",desc:{en:""}},minus:{bracket:"(a, b), a - b operator",desc:{en:"Calculates the difference. The result is always signed.

You can also calculate whole numbers from a date or date with time. The idea is the same - see above for 'plus'."}},toDateTime:{bracket:"(v)",desc:{en:"Functions for converting between numbers, strings (but not fixed strings), dates, and dates with times. All these functions accept one argument. "}},modulo:{bracket:"(a, b), a % b operator",desc:{en:"Calculates the remainder after division.
If arguments are floating-point numbers, they are pre-converted to integers by dropping the decimal portion. The remainder is taken in the same sense as in C++. Truncated division is used for negative numbers.
An exception is thrown when dividing by zero or when dividing a minimal negative number by minus one."}},bitmaskToArray:{bracket:"(num)",desc:{en:"Accepts an integer. Returns an array of UInt64 numbers containing the list of powers of two that total the source number when summed. Numbers in the array are in ascending order."}},negate:{bracket:"(a), -a operator",desc:{en:"Calculates a number with the reverse sign. The result is always signed."}},emptyArrayFloat32:{bracket:"(v)",desc:{en:"Accepts zero arguments and returns an empty array of the appropriate type."}},range:{bracket:"(N)",desc:{en:"Returns an array of numbers from 0 to N-1.
Just in case, an exception is thrown if arrays with a total length of more than 100,000,000 elements are created in a data block."}},arrayAll:{bracket:"([func,] arr1, ...)",desc:{en:"Returns 1 if 'func' returns something other than 0 for all the elements in 'arr'. Otherwise, it returns 0."}},toInt32:{bracket:"(v)",desc:{en:"Functions for converting between numbers, strings (but not fixed strings), dates, and dates with times. All these functions accept one argument. "}},unhex:{bracket:"(str)",desc:{en:"Accepts a string containing any number of hexadecimal digits, and returns a string containing the corresponding bytes. Supports both uppercase and lowercase letters A-F. The number of hexadecimal digits doesn't have to be even. If it is odd, the last digit is interpreted as the younger half of the 00-0F byte. If the argument string contains anything other than hexadecimal digits, some implementation-defined result is returned (an exception isn't thrown).
If you want to convert the result to a number, you can use the functions 'reverse' and 'reinterpretAsType'."}},toFloat64:{bracket:"(v)",desc:{en:"Functions for converting between numbers, strings (but not fixed strings), dates, and dates with times. All these functions accept one argument. "}},bitAnd:{bracket:"(a, b)",desc:{ru:"",en:""}},toStartOfYear:{bracket:"(v)",desc:{en:"Rounds down a date or date with time to the first day of the year.
Returns the date."}},bitOr:{bracket:"(a, b)",desc:{ru:"",en:""}},SEToRoot:{bracket:"(v)",desc:{en:"Accepts a UInt8 number - the ID of the search engine from the Yandex.Metrica dictionary. If any search engine matches the passed number, it returns a UInt8 number - the ID of the corresponding root search engine (for example, it converts Yandex.Images to Yandex). Otherwise, returns 0."}},toRelativeMinuteNum:{bracket:"(v)",desc:{en:"Converts a date with time or date to the number of the minute, starting from a certain fixed point in the past."}},visitParamExtractInt:{bracket:"(params, name)",desc:{ru:"Аналогично для Int64.",en:"The same as for Int64."}},emptyArrayInt16:{bracket:"(v)",desc:{en:"Accepts zero arguments and returns an empty array of the appropriate type."}},visitParamExtractString:{bracket:"(params, name)",desc:{en:"Parses the string in double quotes. The value is unescaped. If unescaping failed, it returns an empty string. "}},arrayEnumerateUniq:{bracket:"(arr, ...)",desc:{en:"Returns an array the same size as the source array, indicating for each element what its position is among elements with the same value. "}},visitParamExtractUInt:{bracket:"(params, name)",desc:{en:"Parses UInt64 from the value of the field named 'name'. If this is a string field, it tries to parse a number from the beginning of the string. If the field doesn't exist, or it exists but doesn't contain a number, it returns 0."}},toTypeName:{bracket:"(x)",desc:{en:"Gets the type name. Returns a string containing the type name of the passed argument."}},empty:{bracket:"(v)",desc:{en:"Accepts an empty array as argument and returns an array of one element equal to the default value."}},multiply:{bracket:"(a, b), a * b operator",desc:{en:"Calculates the product of the numbers."}},has:{bracket:"('database', 'table', 'column')",desc:{ru:"",en:"Accepts constant String columns - database name, table name and column name. Returns constant UInt8 value, equal to 1 if column exists,
otherwise 0.
If table doesn't exist than exception is thrown.
For elements of nested data structure function checks existence of column. For nested data structure 0 is returned."}},bitNot:{bracket:"(a)",desc:{ru:"",en:""}},lessOrEquals:{bracket:"(v)",desc:{ru:"",en:"

greaterOrEquals, >= operator

"}},reinterpretAsInt64:{bracket:"(v)",desc:{en:""}},IPv4NumToString:{bracket:"(num)",desc:{en:"Similar to IPv4NumToString, but using %%xxx%% instead of the last octet. "}},bitShiftLeft:{bracket:"(a, b)",desc:{ru:"",en:""}},dictGetInt16:{bracket:"(v)",desc:{ru:"",en:""}},toUInt32OrZero:{bracket:"(v)",desc:{en:"Functions for converting between numbers, strings (but not fixed strings), dates, and dates with times. All these functions accept one argument. "}},regionIn:{bracket:"(lhs, rhs[, geobase])",desc:{en:"Checks whether a 'lhs' region belongs to a 'rhs' region. Returns a UInt8 number equal to 1 if it belongs, or 0 if it doesn't belong.
The relationship is reflexive - any region also belongs to itself."}},reinterpretAsUInt8:{bracket:"(v)",desc:{en:""}},dictIsIn:{bracket:"(v)",desc:{en:"%%dictIsIn('dict_name', child_id, ancestor_id)%%
- For the 'dict_name' hierarchical dictionary, finds out whether the 'child_id' key is located inside 'ancestor_id' (or matches 'ancestor_id'). Returns UInt8."}},toSecond:{bracket:"(v)",desc:{en:"Converts a date with time to a UInt8 number containing the number of the second in the minute (0-59).
Leap seconds are not accounted for."}},least:{bracket:"(a, b)",desc:{en:"Returns the least element of a and b."}},countEqual:{bracket:"(arr, x)",desc:{en:'Returns the number of elements in the array equal to 'x'. Equivalent to arrayCount(elem -> elem = x, arr).'}},IPv4StringToNum:{bracket:"(s)",desc:{en:"The reverse function of IPv4NumToString. If the IPv4 address has an invalid format, it returns 0."}},replaceRegexpAll:{bracket:"(haystack, pattern, replacement)",desc:{en:"This does the same thing, but replaces all the occurrences"}},SHA224:{bracket:"(v)",desc:{en:"Calculates SHA-1, SHA-224, or SHA-256 from a string and returns the resulting set of bytes as FixedString(20), FixedString(28), or FixedString(32).
The function works fairly slowly (SHA-1 processes about 5 million short strings per second per processor core, while SHA-224 and SHA-256 process about 2.2 million). "}},URLHash:{bracket:"(url[, N])",desc:{en:"A fast, decent-quality non-cryptographic hash function for a string obtained from a URL using some type of normalization.
URLHash(s) - Calculates a hash from a string without one of the trailing symbols /,? or # at the end, if present"}},equals:{bracket:"(v)",desc:{ru:"",en:"

greaterOrEquals, >= operator

"}},plus:{bracket:"(a, b), a + b operator",desc:{ru:"Вычисляет сумму чисел.

Также можно складывать целые числа с датой и датой-с-временем. В случае даты, прибавление целого числа означает прибавление соответствующего количества дней. В случае даты-с-временем - прибавление соответствующего количества секунд.",en:"Calculates the sum of the numbers.

You can also add whole numbers with a date or date and time. In the case of a date, adding a whole number means adding the corresponding number of days. For a date with time, it means adding the corresponding number of seconds."}},less:{bracket:"(v)",desc:{ru:"",en:"

greaterOrEquals, >= operator

"}},regionHierarchy:{bracket:"(id[, geobase])",desc:{en:"Accepts a UInt32 number - the region ID from the Yandex geobase. Returns an array of region IDs consisting of the passed region and all parents along the chain.
Example: %%regionHierarchy(toUInt32(213)) = [213,1,3,225,10001,10000]%%."}},toUInt64OrZero:{bracket:"(v)",desc:{en:"Functions for converting between numbers, strings (but not fixed strings), dates, and dates with times. All these functions accept one argument. "}},rowNumberInAllBlocks:{bracket:"()",desc:{en:"Returns an incremental row number within all blocks that were processed by this function."}},toDayOfWeek:{bracket:"(v)",desc:{en:"Converts a date or date with time to a UInt8 number containing the number of the day of the week (Monday is 1, and Sunday is 7)."}},bar:{bracket:"(v)",desc:{en:"Allows building a unicode-art diagram.

bar(x, min, max, width) - Draws a band with a width proportional to (x - min) and equal to 'width' characters when x"}},"if":{bracket:"(v)",desc:{en:"The suffix -%%If%% can be appended to the name of any aggregate function. In this case, the aggregate function accepts an extra argument - a condition (Uint8 type). "}},regionToArea:{bracket:"(id[, geobase])",desc:{en:"Converts a region to an area (type 5 in the geobase). In every other way, this function is the same as 'regionToCity'.──────────────────────────────────"}},dictGetUInt16:{bracket:"(v)",desc:{ru:"",en:""}},toUInt8:{bracket:"(v)",desc:{en:"Functions for converting between numbers, strings (but not fixed strings), dates, and dates with times. All these functions accept one argument. "}},toUInt16:{bracket:"(v)",desc:{en:"Functions for converting between numbers, strings (but not fixed strings), dates, and dates with times. All these functions accept one argument. "}},path:{bracket:"(URL)",desc:{en:"- The same thing, but without the protocol and host in the result. The / element (root) is not included."}},extractURLParameters:{bracket:"(URL)",desc:{ru:"Возвращает массив строк вида name=value, соответствующих параметрам URL. Значения никак не декодируются.",en:"- Gets an array of name=value strings corresponding to the URL parameters. The values are not decoded in any way."}},OSHierarchy:{bracket:"(v)",desc:{ru:"Принимает число типа UInt8 - идентификатор операционной системы из словаря Яндекс.Метрики. Возвращает массив с иерархией операционных систем. Аналогично функции regionHierarchy.",en:"Accepts a UInt8 number - the ID of the operating system from the Yandex.Metrica dictionary. Returns an array with a hierarchy of operating systems. Similar to the 'regionHierarchy' function."}},cutQueryStringAndFragment:{bracket:"(v)",desc:{ru:"Удаляет query string и fragment identifier. Знак вопроса и символ решётки тоже удаляются.",en:"Removes the query-string and fragment identifier. The question mark and number sign are also removed."}},timeSlots:{bracket:"(StartTime, Duration)",desc:{ru:"Для интервала времени, начинающегося в StartTime и продолжающегося Duration секунд, возвращает массив моментов времени, состоящий из округлений вниз до получаса точек из этого интервала.
Например, %%timeSlots(toDateTime('2012-01-01 12:20:00'), toUInt32(600)) = [toDateTime('2012-01-01 12:00:00'), toDateTime('2012-01-01 12:30:00')]%%.
Это нужно для поиска хитов, входящих в соответствующий визит.",en:"For a time interval starting at 'StartTime' and continuing for 'Duration' seconds, it returns an array of moments in time, consisting of points from this interval rounded down to the half hour.
For example, %%timeSlots(toDateTime('2012-01-01 12:20:00'), toUInt32(600)) = [toDateTime('2012-01-01 12:00:00'), toDateTime('2012-01-01 12:30:00')]%%.
This is necessary for searching for pageviews in the corresponding session."}},toUInt32:{bracket:"(v)",desc:{en:"Functions for converting between numbers, strings (but not fixed strings), dates, and dates with times. All these functions accept one argument. "}},toStartOfMinute:{bracket:"(v)",desc:{ru:"Округляет дату-с-временем вниз до начала минуты.",en:"Rounds down a date with time to the start of the minute."}},version:{bracket:"()",desc:{ru:"Возвращает версию сервера в виде строки.",en:"Returns server's version as a string."}},toUInt64:{bracket:"(v)",desc:{en:"Functions for converting between numbers, strings (but not fixed strings), dates, and dates with times. All these functions accept one argument. "}},toInt16:{bracket:"(v)",desc:{en:"Functions for converting between numbers, strings (but not fixed strings), dates, and dates with times. All these functions accept one argument. "}},reinterpretAsInt16:{bracket:"(v)",desc:{en:""}},toInt64:{bracket:"(v)",desc:{en:"Functions for converting between numbers, strings (but not fixed strings), dates, and dates with times. All these functions accept one argument. "}},toFixedString:{bracket:"(s, N)",desc:{ru:"Преобразует аргумент типа String в тип FixedString(N) (строку фиксированной длины N). N должно быть константой.
Если строка имеет меньше байт, чем N, то она дополняется нулевыми байтами справа. Если строка имеет больше байт, чем N - кидается исключение.",en:"Converts a String type argument to a FixedString(N) type (a string with fixed length N). N must be a constant. If the string has fewer bytes than N, it is passed with null bytes to the right. If the string has more bytes than N, an exception is thrown."}},toFloat32:{bracket:"(v)",desc:{en:"Functions for converting between numbers, strings (but not fixed strings), dates, and dates with times. All these functions accept one argument. "}},dictGetHierarchy:{bracket:"(v)",desc:{ru:"%%dictGetHierarchy('dict_name', id)%%
- для иерархического словаря dict_name - вернуть массив ключей словаря, начиная с id и продолжая цепочкой родительских элементов. Возвращает Array(UInt64).",en:"%%dictGetHierarchy('dict_name', id)%%
- For the 'dict_name' hierarchical dictionary, returns an array of dictionary keys starting from 'id' and continuing along the chain of parent elements. Returns Array(UInt64)."}},dictGetInt64:{bracket:"(v)",desc:{ru:"",en:""}},CAST:{bracket:"(x, t)",desc:{en:"Casts x to the t data type.
The syntax %%CAST(x AS t)%% is also supported.
"}},toRelativeSecondNum:{bracket:"(v)",desc:{ru:"Переводит дату-с-временем в номер секунды, начиная с некоторого фиксированного момента в прошлом.",en:"Converts a date with time or date to the number of the second, starting from a certain fixed point in the past."}},toUInt8OrZero:{bracket:"(v)",desc:{en:"Functions for converting between numbers, strings (but not fixed strings), dates, and dates with times. All these functions accept one argument. "}},toStartOfMonth:{bracket:"(v)",desc:{ru:"Округляет дату или дату-с-временем вниз до первого дня месяца.
Возвращается дата.",en:"Rounds down a date or date with time to the first day of the month.
Returns the date."}},rand64:{bracket:"(v)",desc:{ru:"Возвращает псевдослучайное число типа UInt64, равномерно распределённое среди всех чисел типа UInt64.
Используется linear congruential generator.",en:"Returns a pseudo-random UInt64 number, evenly distributed among all UInt64-type numbers.
Uses a linear congruential generator."}},toInt8OrZero:{bracket:"(v)",desc:{en:"Functions for converting between numbers, strings (but not fixed strings), dates, and dates with times. All these functions accept one argument. "}},toFloat32OrZero:{bracket:"(v)",desc:{en:"Functions for converting between numbers, strings (but not fixed strings), dates, and dates with times. All these functions accept one argument. "}},toYear:{bracket:"(v)",desc:{ru:"Переводит дату или дату-с-временем в число типа UInt16, содержащее номер года (AD).",en:"Converts a date or date with time to a UInt16 number containing the year number (AD)."}},atan:{bracket:"(x)",desc:{ru:"Арктангенс.",en:"The arc tangent."}},toFloat64OrZero:{bracket:"(v)",desc:{en:"Functions for converting between numbers, strings (but not fixed strings), dates, and dates with times. All these functions accept one argument. "}},arrayEnumerate:{bracket:"(arr, ...)",desc:{en:"Returns an array the same size as the source array, indicating for each element what its position is among elements with the same value.
"}},toDayOfMonth:{bracket:"(v)",desc:{en:"Converts a date or date with time to a UInt8 number containing the number of the day of the month (1-31)."}},dictGetUInt64:{bracket:"(v)",desc:{ru:"",en:""}},IPv4NumToStringClassC:{bracket:"(num)",desc:{en:"Similar to IPv4NumToString, but using %%xxx%% instead of the last octet. "}},reinterpretAsString:{bracket:"(v)",desc:{en:"This function accepts a number or date or date with time, and returns a string containing bytes representing the corresponding value in host order (little endian). Null bytes are dropped from the end. For example, a UInt32 type value of 255 is a string that is one byte long."}},toHour:{bracket:"(v)",desc:{en:"Converts a date with time to a UInt8 number containing the number of the hour in 24-hour time (0-23).
This function assumes that if clocks are moved ahead, it is by one hour and occurs at 2 a.m., and if clocks are moved back, it is by one hour and occurs at 3 a.m. (which is not always true - even in Moscow the clocks were once changed at a different time)."}},ignore:{bracket:"(...)",desc:{en:"A function that accepts any arguments and always returns 0.
However, the argument is still calculated. This can be used for benchmarks."}},arrayJoin:{bracket:"(v)",desc:{en:"This is a very unusual function.

Normal functions don't change a set of rows, but just change the values in each row (map). Aggregate functions compress a set of rows (fold or reduce).
The 'arrayJoin' function takes each row and generates a set of rows (unfold).

T"}},length:{bracket:"(v)",desc:{en:"Returns the length of a string in Unicode code points (not in characters), assuming that the string contains a set of bytes that make up UTF-8 encoded text. If this assumption is not met, it returns some result (it doesn't throw an exception).
The result type is UInt64."}},tuple:{bracket:"(tuple, n), operator x.N",desc:{en:"A function that allows getting columns from a tuple.
'N' is the column index, starting from 1. 'N' must be a constant. 'N' must be a strict postive integer no greater than the size of the tuple.
There is no cost to execute the function."}},extractURLParameterNames:{bracket:"(URL)",desc:{en:"- Gets an array of name=value strings corresponding to the names of URL parameters. The values are not decoded in any way."}},tupleElement:{bracket:"(tuple, n), operator x.N",desc:{en:"A function that allows getting columns from a tuple.
'N' is the column index, starting from 1. 'N' must be a constant. 'N' must be a strict postive integer no greater than the size of the tuple.
There is no cost to execute the function."}},"in":{bracket:"(v)",desc:{en:"What to do when the amount of data exceeds one of the limits: 'throw' or 'break'. By default, throw."}},globalIn:{bracket:"(v)",desc:{en:"See the section "IN operators"."}},isFinite:{bracket:"(x)",desc:{en:"Accepts Float32 and Float64 and returns UInt8 equal to 1 if the argument is not infinite and not a NaN, otherwise 0."}},isNaN:{bracket:"(x)",desc:{en:"Accepts Float32 and Float64 and returns UInt8 equal to 1 if the argument is a NaN, otherwise 0."}},isInfinite:{bracket:"(x)",desc:{en:"Accepts Float32 and Float64 and returns UInt8 equal to 1 if the argument is infinite, otherwise 0.
Note that 0 is returned for a NaN."}},transform:{bracket:"(v)",desc:{en:"Transforms a value according to the explicitly defined mapping of some elements to other ones.
There are two variations of this function:

1. %%transform(x, array_from, array_to, default)%% "}},rand:{bracket:"(v)",desc:{en:"Returns a pseudo-random UInt64 number, evenly distributed among all UInt64-type numbers.
Uses a linear congruential generator."}},reinterpretAsUInt16:{bracket:"(v)",desc:{en:""}},pi:{bracket:"(v)",desc:{en:"Maximum pipeline depth. Corresponds to the number of transformations that each data block goes through during query processing. Counted within the limits of a single server. If the pipeline depth is greater, an exception is thrown. By default, 1000."}},reinterpretAsUInt32:{bracket:"(v)",desc:{en:""}},reinterpretAsUInt64:{bracket:"(v)",desc:{en:""}},reinterpretAsInt8:{bracket:"(v)",desc:{en:""}},upperUTF8:{bracket:"(v)",desc:{en:"Converts a string to uppercase, assuming the string contains a set of bytes that make up a UTF-8 encoded text. It doesn't detect the language. So for Turkish the result might not be exactly correct. "}},reinterpretAsInt32:{bracket:"(v)",desc:{en:""}},reinterpretAsFloat32:{bracket:"(v)",desc:{en:""}},reinterpretAsFloat64:{bracket:"(v)",desc:{en:""}},reinterpretAsDate:{bracket:"(v)",desc:{en:""}},reinterpretAsDateTime:{bracket:"(v)",desc:{en:""}},roundToExp2:{bracket:"(num)",desc:{en:"Accepts a number. If the number is less than one, it returns 0. Otherwise, it rounds the number down to the nearest (whole non-negative) degree of two."}},upper:{bracket:"(v)",desc:{en:"Converts a string to uppercase, assuming the string contains a set of bytes that make up a UTF-8 encoded text. It doesn't detect the language. So for Turkish the result might not be exactly correct."}},positionUTF8:{bracket:"(haystack, needle)",desc:{en:"The same as 'position', but the position is returned in Unicode code points. Works under the assumption that the string contains a set of bytes representing a UTF-8 encoded text. If this assumption is not met, it returns some result (it doesn't throw an exception).
There's also positionCaseInsensitiveUTF8 function."}},roundDuration:{bracket:"(num)",desc:{en:"Accepts a number. If the number is less than one, it returns 0. Otherwise, it rounds the number down to numbers from the set: 1, 10, 30, 60, 120, 180, 240, 300, 600, 1200, 1800, 3600, 7200, 18000, 36000. This function is specific to Yandex.Metrica and used for implementing the report on session length."}},roundAge:{bracket:"(num)",desc:{en:"Accepts a number. If the number is less than 18, it returns 0. Otherwise, it rounds the number down to numbers from the set: 18, 25, 35, 45. This function is specific to Yandex.Metrica and used for implementing the report on user age."}},round:{bracket:"(num)",desc:{en:"Accepts a number. If the number is less than 18, it returns 0. Otherwise, it rounds the number down to numbers from the set: 18, 25, 35, 45. This function is specific to Yandex.Metrica and used for implementing the report on user age."}},floor:{bracket:"(x[, N])",desc:{en:"Returns a rounder number that is less than or equal to 'x'."}},notEmpty:{bracket:"(v)",desc:{en:"Returns 0 for an empty array, or 1 for a non-empty array.
The result type is UInt8.
The function also works for strings."}},lengthUTF8:{bracket:"(v)",desc:{en:"Returns the length of a string in Unicode code points (not in characters), assuming that the string contains a set of bytes that make up UTF-8 encoded text. If this assumption is not met, it returns some result (it doesn't throw an exception).
The result type is UInt64."}},lower:{bracket:"(v)",desc:{en:"Converts a string to lowercase, assuming the string contains a set of bytes that make up a UTF-8 encoded text. It doesn't detect the language. "}},lowerUTF8:{bracket:"(v)",desc:{en:"Converts a string to lowercase, assuming the string contains a set of bytes that make up a UTF-8 encoded text. It doesn't detect the language. "}},reverse:{bracket:"(v)",desc:{en:"Reverses a sequence of Unicode code points, assuming that the string contains a set of bytes representing a UTF-8 text. Otherwise, it does something else (it doesn't throw an exception)."}},URLPathHierarchy:{bracket:"(URL)",desc:{en:"- The same thing, but without the protocol and host in the result. The / element (root) is not included. "}},substringUTF8:{bracket:"(s, offset, length)",desc:{en:"The same as 'substring', but for Unicode code points. Works under the assumption that the string contains a set of bytes representing a UTF-8 encoded text. If this assumption is not met, it returns some result (it doesn't throw an exception)."}},appendTrailingCharIfAbsent:{bracket:"(s, c)",desc:{en:"If the %%s%% string is non-empty and does not contain the %%c%% character at the end, it appends the %%c%% character to the end."}},alphaTokens:{bracket:"(s)",desc:{en:"Selects substrings of consecutive bytes from the range a-z and A-Z.
Returns an array of selected substrings."}},splitByChar:{bracket:"(separator, s)",desc:{en:"Splits a string into substrings, using 'separator' as the separator.
'separator' must be a string constant consisting of exactly one character.
Returns an array of selected substrings"}},arrayStringConcat:{bracket:"(arr[, separator])",desc:{en:"Concatenates strings from the array elements, using 'separator' as the separator.
'separator' is a string constant, an optional parameter. By default it is an empty string.
Returns a string."}},replaceAll:{bracket:"(haystack, pattern, replacement)",desc:{en:"Replaces all occurrences of the 'pattern' substring in 'haystack' with the 'replacement' substring."}},replaceRegexpOne:{bracket:"(haystack, pattern, replacement)",desc:{en:"Replacement using the 'pattern' regular expression. A re2 regular expression. Replaces only the first occurrence, if it exists.
A pattern can be specified as 'replacement'. "}},cbrt:{bracket:"(x)",desc:{en:"Accepts a numeric argument and returns a Float64 number close to the cubic root of the argument."}},match:{bracket:"(pattern)(time, cond1, cond2, ...)",desc:{en:"Pattern matching for event chains.

'pattern' is a string containing a pattern to match. The pattern is similar to a regular expression."}},cutURLParameter:{bracket:"(URL, name)",desc:{en:"Removes the URL parameter named 'name', if present. This function works under the assumption that the parameter name is encoded in the URL exactly the same way as in the passed argument."}},like:{bracket:"(haystack, pattern), haystack NOT LIKE pattern operator",desc:{en:"The same thing as 'like', but negative."}},domain:{bracket:"(v)",desc:{en:"- Selects the part of the domain that includes top-level subdomains up to the "first significant subdomain" (see the explanation above).
For example, cutToFirstSignificantSubdomain('https://news.yandex.com.tr/') = 'yandex.com.tr'."}},domainWithoutWWW:{bracket:"(v)",desc:{en:"- Selects the domain and removes no more than one 'www.' from the beginning of it, if present."}},firstSignificantSubdomain:{bracket:"(v)",desc:{en:"- Selects the part of the domain that includes top-level subdomains up to the "first significant subdomain" (see the explanation above).
For example, cutToFirstSignificantSubdomain('https://news.yandex.com.tr/') = 'yandex.com.tr'."}},queryString:{bracket:"(v)",desc:{en:"Removes the query-string and fragment identifier. The question mark and number sign are also removed."}},queryStringAndFragment:{bracket:"(v)",desc:{en:"Removes the query-string and fragment identifier. The question mark and number sign are also removed."}},extractURLParameter:{bracket:"(URL)",desc:{en:"- Gets an array of name=value strings corresponding to the names of URL parameters. The values are not decoded in any way."}},URLHierarchy:{bracket:"(URL)",desc:{en:"- Gets an array containing the URL trimmed to the %%/%%, %%?%% characters in the path and query-string. Consecutive separator characters are counted as one. The cut is made in the position after all the consecutive separator characters. Example:"}},cutToFirstSignificantSubdomain:{bracket:"(v)",desc:{en:"- Selects the part of the domain that includes top-level subdomains up to the "first significant subdomain" (see the explanation above).
For example, cutToFirstSignificantSubdomain('https://news.yandex.com.tr/') = 'yandex.com.tr'."}},cutWWW:{bracket:"(v)",desc:{en:"Removes no more than one 'www.' from the beginning of the URL's domain, if present."}},cutQueryString:{bracket:"(v)",desc:{en:"Removes the query-string and fragment identifier. The question mark and number sign are also removed."}},cutFragment:{bracket:"(v)",desc:{en:"Removes the fragment identifier. The number sign is also removed."}},visitParamHas:{bracket:"(params, name)", +desc:{en:"Checks whether there is a field with the 'name' name."}},visitParamExtractFloat:{bracket:"(params, name)",desc:{en:"The same as for Float64."}},visitParamExtractBool:{bracket:"(params, name)",desc:{en:"Parses a true/false value. The result is UInt8."}},visitParamExtractRaw:{bracket:"(params, name)",desc:{en:"Returns the value of a field, including separators."}},exp:{bracket:"(x)",desc:{en:"Accepts a numeric argument and returns a Float64 number close to 10x."}},exp2:{bracket:"(x)",desc:{en:"Accepts a numeric argument and returns a Float64 number close to 2x."}},exp10:{bracket:"(x)",desc:{en:"Accepts a numeric argument and returns a Float64 number close to 10x."}},tgamma:{bracket:"(x)",desc:{en:"Gamma function."}},log10:{bracket:"(x)",desc:{en:"Accepts a numeric argument and returns a Float64 number close to the decimal logarithm of the argument."}},sqrt:{bracket:"(x)",desc:{en:"Accepts a numeric argument and returns a Float64 number close to the square root of the argument."}},erf:{bracket:"(v)",desc:{en:"What to do when the amount of data exceeds one of the limits: 'throw' or 'break'. By default, throw."}},erfc:{bracket:"(x)",desc:{en:"Accepts a numeric argument and returns a Float64 number close to 1 - erf(x), but without loss of precision for large 'x' values."}},lgamma:{bracket:"(x)",desc:{en:"The logarithm of the gamma function."}},sin:{bracket:"(x)",desc:{en:"Accepts Float32 and Float64 and returns UInt8 equal to 1 if the argument is infinite, otherwise 0.
Note that 0 is returned for a NaN."}},cos:{bracket:"(x)",desc:{ru:"Арккосинус.",en:"The arc cosine."}},tan:{bracket:"(x)",desc:{ru:"Арктангенс.",en:"The arc tangent."}},pow:{bracket:"(x, y)",desc:{ru:"xy.",en:"xy."}}}},/* * Licensed under the Apache License, Version 2.0 Copyright 2017 Igor Strykhar,Ivan Kudinov,SMI2 LLC and other contributors */ function(){angular.module(smi2.app.name).run(["$rootScope","$state","$mdTheming","ThemeService","localStorageService",function(e,t,a,n,r){e.breadcrumbs=[],e.currentDatabase=null;var i=e.$on("$stateChangeError",function(e,a,n,r,i,s){"notAuthorized"==s&&t.go("login")});e.$on("$destroy",function(){return i}),window.document.title="Tabix.IO ["+window.TabixBuildDate+"]",e.sqlLog=r.get("sqlLog")||[],e.$watch("sqlLog",function(e){r.set("sqlLog",e)}),e.isInitDatabaseStructure=!1,e.sidebar={letf_resizable_width:200,clickLetfResizable:function(){e.sidebar.letf_resizable_width<10?e.sidebar.letf_resizable_width=200:e.sidebar.letf_resizable_width=0}}}])}(),/*