hunk
dict | file
stringlengths 0
11.8M
| file_path
stringlengths 2
234
| label
int64 0
1
| commit_url
stringlengths 74
103
| dependency_score
sequencelengths 5
5
|
---|---|---|---|---|---|
{
"id": 4,
"code_window": [
"\tif (isNew && !note.title) {\n",
"\t\tnote.title = Note.defaultTitle(note);\n",
"\t\ttitleWasAutoAssigned = true;\n",
"\t}\n",
"\n",
"\t// Save only the properties that have changed\n",
"\t// let diff = null;\n",
"\t// if (!isNew) {\n",
"\t// \tdiff = BaseModel.diffObjects(comp.state.lastSavedNote, note);\n",
"\t// \tdiff.type_ = note.type_;\n",
"\t// \tdiff.id = note.id;\n",
"\t// } else {\n",
"\t// \tdiff = Object.assign({}, note);\n",
"\t// }\n",
"\n",
"\t// const savedNote = await Note.save(diff);\n",
"\n",
"\tlet options = {};\n",
"\tif (!isNew) {\n",
"\t\toptions.fields = BaseModel.diffObjectsFields(comp.state.lastSavedNote, note);\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "ReactNativeClient/lib/components/shared/note-screen-shared.js",
"type": "replace",
"edit_start_line_idx": 38
} | const BaseSyncTarget = require('lib/BaseSyncTarget.js');
const SyncTargetOneDrive = require('lib/SyncTargetOneDrive.js');
const { _ } = require('lib/locale.js');
const { OneDriveApi } = require('lib/onedrive-api.js');
const Setting = require('lib/models/Setting.js');
const { parameters } = require('lib/parameters.js');
const { FileApi } = require('lib/file-api.js');
const { Synchronizer } = require('lib/synchronizer.js');
const { FileApiDriverOneDrive } = require('lib/file-api-driver-onedrive.js');
class SyncTargetOneDriveDev extends SyncTargetOneDrive {
static id() {
return 4;
}
static targetName() {
return 'onedrive_dev';
}
static label() {
return _('OneDrive Dev (For testing only)');
}
syncTargetId() {
return SyncTargetOneDriveDev.id();
}
oneDriveParameters() {
return parameters('dev').oneDrive;
}
}
const staticSelf = SyncTargetOneDriveDev;
module.exports = SyncTargetOneDriveDev; | ReactNativeClient/lib/SyncTargetOneDriveDev.js | 0 | https://github.com/laurent22/joplin/commit/1d7f30d441e2c0fb82bfd0750d3a4203c9636390 | [
0.00027164729544892907,
0.0001935606705956161,
0.00016581537784077227,
0.0001683899899944663,
0.00004510422149905935
] |
{
"id": 4,
"code_window": [
"\tif (isNew && !note.title) {\n",
"\t\tnote.title = Note.defaultTitle(note);\n",
"\t\ttitleWasAutoAssigned = true;\n",
"\t}\n",
"\n",
"\t// Save only the properties that have changed\n",
"\t// let diff = null;\n",
"\t// if (!isNew) {\n",
"\t// \tdiff = BaseModel.diffObjects(comp.state.lastSavedNote, note);\n",
"\t// \tdiff.type_ = note.type_;\n",
"\t// \tdiff.id = note.id;\n",
"\t// } else {\n",
"\t// \tdiff = Object.assign({}, note);\n",
"\t// }\n",
"\n",
"\t// const savedNote = await Note.save(diff);\n",
"\n",
"\tlet options = {};\n",
"\tif (!isNew) {\n",
"\t\toptions.fields = BaseModel.diffObjectsFields(comp.state.lastSavedNote, note);\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "ReactNativeClient/lib/components/shared/note-screen-shared.js",
"type": "replace",
"edit_start_line_idx": 38
} | function promiseChain(chain, defaultValue = null) {
let output = new Promise((resolve, reject) => { resolve(defaultValue); });
for (let i = 0; i < chain.length; i++) {
let f = chain[i];
output = output.then(f);
}
return output;
}
function promiseWhile(callback) {
let isDone = false;
function done() {
isDone = true;
}
let iterationDone = false;
let p = callback(done).then(() => {
iterationDone = true;
});
let iid = setInterval(() => {
if (iterationDone) {
if (isDone) {
clearInterval(iid);
return;
}
iterationDone = false;
callback(done).then(() => {
iterationDone = true;
});
}
}, 100);
}
module.exports = { promiseChain, promiseWhile }; | ReactNativeClient/lib/promise-utils.js | 0 | https://github.com/laurent22/joplin/commit/1d7f30d441e2c0fb82bfd0750d3a4203c9636390 | [
0.0001717756676953286,
0.00016705610323697329,
0.00016472881543450058,
0.00016585997946094722,
0.0000028524357276182855
] |
{
"id": 0,
"code_window": [
"#!/usr/bin/env python\n",
"from panoramix import app, config\n",
"from subprocess import Popen\n",
"\n",
"\n",
"if __name__ == \"__main__\":\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"import argparse\n"
],
"file_path": "panoramix/bin/panoramix",
"type": "add",
"edit_start_line_idx": 3
} | from datetime import datetime
import json
import logging
from flask import request, redirect, flash, Response
from flask.ext.appbuilder.models.sqla.interface import SQLAInterface
from flask.ext.appbuilder import ModelView, CompactCRUDMixin, BaseView, expose
from flask.ext.appbuilder.security.decorators import has_access
from pydruid.client import doublesum
from wtforms.validators import ValidationError
from flask.ext.appbuilder.actions import action
from panoramix import appbuilder, db, models, viz, utils, app
def validate_json(form, field):
try:
json.loads(field.data)
except Exception as e:
raise ValidationError("Json isn't valid")
class DeleteMixin(object):
@action("muldelete", "Delete", "Delete all Really?", "fa-trash", single=False)
def muldelete(self, items):
self.datamodel.delete_all(items)
self.update_redirect()
return redirect(self.get_redirect())
class TableColumnInlineView(CompactCRUDMixin, ModelView):
datamodel = SQLAInterface(models.TableColumn)
can_delete = False
edit_columns = [
'column_name', 'description', 'table', 'groupby', 'filterable',
'count_distinct', 'sum', 'min', 'max']
list_columns = [
'column_name', 'type', 'groupby', 'filterable', 'count_distinct',
'sum', 'min', 'max']
page_size = 100
appbuilder.add_view_no_menu(TableColumnInlineView)
class ColumnInlineView(CompactCRUDMixin, ModelView):
datamodel = SQLAInterface(models.Column)
edit_columns = [
'column_name', 'description', 'datasource', 'groupby',
'count_distinct', 'sum', 'min', 'max']
list_columns = [
'column_name', 'type', 'groupby', 'filterable', 'count_distinct',
'sum', 'min', 'max']
can_delete = False
page_size = 100
def post_update(self, col):
col.generate_metrics()
def post_update(self, col):
col.generate_metrics()
appbuilder.add_view_no_menu(ColumnInlineView)
class SqlMetricInlineView(CompactCRUDMixin, ModelView):
datamodel = SQLAInterface(models.SqlMetric)
list_columns = ['metric_name', 'verbose_name', 'metric_type' ]
edit_columns = [
'metric_name', 'description', 'verbose_name', 'metric_type',
'table', 'expression']
add_columns = edit_columns
page_size = 100
appbuilder.add_view_no_menu(SqlMetricInlineView)
class MetricInlineView(CompactCRUDMixin, ModelView):
datamodel = SQLAInterface(models.Metric)
list_columns = ['metric_name', 'verbose_name', 'metric_type' ]
edit_columns = [
'metric_name', 'description', 'verbose_name', 'metric_type',
'datasource', 'json']
add_columns = [
'metric_name', 'verbose_name', 'metric_type', 'datasource', 'json']
page_size = 100
validators_columns = {
'json': [validate_json],
}
appbuilder.add_view_no_menu(MetricInlineView)
class ClusterModelView(ModelView, DeleteMixin):
datamodel = SQLAInterface(models.Cluster)
add_columns = [
'cluster_name',
'coordinator_host', 'coordinator_port', 'coordinator_endpoint',
'broker_host', 'broker_port', 'broker_endpoint',
]
edit_columns = add_columns
list_columns = ['cluster_name', 'metadata_last_refreshed']
appbuilder.add_view(
ClusterModelView,
"Druid Clusters",
icon="fa-server",
category="Admin",
category_icon='fa-cogs',)
class DatabaseView(ModelView, DeleteMixin):
datamodel = SQLAInterface(models.Database)
list_columns = ['database_name']
add_columns = ['database_name', 'sqlalchemy_uri']
edit_columns = add_columns
appbuilder.add_view(
DatabaseView,
"Databases",
icon="fa-database",
category="Admin",
category_icon='fa-cogs',)
class TableView(ModelView, DeleteMixin):
datamodel = SQLAInterface(models.Table)
list_columns = ['table_link', 'database']
add_columns = ['table_name', 'database', 'default_endpoint']
edit_columns = ['table_name', 'database', 'main_datetime_column', 'default_endpoint']
related_views = [TableColumnInlineView, SqlMetricInlineView]
def post_add(self, table):
table.fetch_metadata()
def post_update(self, table):
table.fetch_metadata()
appbuilder.add_view(
TableView,
"Tables",
icon='fa-table',)
class DatasourceModelView(ModelView, DeleteMixin):
datamodel = SQLAInterface(models.Datasource)
list_columns = [
'datasource_link', 'cluster', 'owner', 'is_featured', 'is_hidden']
related_views = [ColumnInlineView, MetricInlineView]
edit_columns = [
'datasource_name', 'cluster', 'description', 'owner',
'is_featured', 'is_hidden', 'default_endpoint']
page_size = 100
base_order = ('datasource_name', 'asc')
def post_add(self, datasource):
datasource.generate_metrics()
def post_update(self, datasource):
datasource.generate_metrics()
appbuilder.add_view(
DatasourceModelView,
"Druid Datasources",
icon="fa-cube")
@app.route('/health')
def health():
return "OK"
@app.route('/ping')
def ping():
return "OK"
class Panoramix(BaseView):
@has_access
@expose("/table/<table_id>/")
def table(self, table_id):
table = (
db.session
.query(models.Table)
.filter_by(id=table_id)
.first()
)
viz_type = request.args.get("viz_type")
if not viz_type and table.default_endpoint:
return redirect(table.default_endpoint)
if not viz_type:
viz_type = "table"
obj = viz.viz_types[viz_type](
table,
form_data=request.args, view=self)
if request.args.get("json"):
return Response(
json.dumps(obj.get_query(), indent=4),
status=200,
mimetype="application/json")
if not hasattr(obj, 'df') or obj.df is None or obj.df.empty:
pass
#return obj.render_no_data()
return obj.render()
@has_access
@expose("/datasource/<datasource_name>/")
def datasource(self, datasource_name):
viz_type = request.args.get("viz_type")
datasource = (
db.session
.query(models.Datasource)
.filter_by(datasource_name=datasource_name)
.first()
)
if not viz_type and datasource.default_endpoint:
return redirect(datasource.default_endpoint)
if not viz_type:
viz_type = "table"
obj = viz.viz_types[viz_type](
datasource,
form_data=request.args, view=self)
if request.args.get("json"):
return Response(
json.dumps(obj.get_query(), indent=4),
status=200,
mimetype="application/json")
if not hasattr(obj, 'df') or obj.df is None or obj.df.empty:
return obj.render_no_data()
return obj.render()
@has_access
@expose("/refresh_datasources/")
def refresh_datasources(self):
session = db.session()
for cluster in session.query(models.Cluster).all():
cluster.refresh_datasources()
cluster.metadata_last_refreshed = datetime.now()
flash(
"Refreshed metadata from cluster "
"[" + cluster.cluster_name + "]",
'info')
session.commit()
return redirect("/datasourcemodelview/list/")
@expose("/autocomplete/<datasource>/<column>/")
def autocomplete(self, datasource, column):
client = utils.get_pydruid_client()
top = client.topn(
datasource=datasource,
granularity='all',
intervals='2013-10-04/2020-10-10',
aggregations={"count": doublesum("count")},
dimension=column,
metric='count',
threshold=1000,
)
values = sorted([d[column] for d in top[0]['result']])
return json.dumps(values)
appbuilder.add_view_no_menu(Panoramix)
appbuilder.add_link(
"Refresh Druid Metadata",
href='/panoramix/refresh_datasources/',
category='Admin',
category_icon='fa-cogs',
icon="fa-cog")
#models.Metric.__table__.drop(db.engine)
db.create_all()
| panoramix/views.py | 1 | https://github.com/apache/superset/commit/6dd81a3e95a9d67be743815ff9bfcd465278b3e9 | [
0.008700026199221611,
0.000517527514602989,
0.00016609119484201074,
0.00017258504522033036,
0.0016074854647740722
] |
{
"id": 0,
"code_window": [
"#!/usr/bin/env python\n",
"from panoramix import app, config\n",
"from subprocess import Popen\n",
"\n",
"\n",
"if __name__ == \"__main__\":\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"import argparse\n"
],
"file_path": "panoramix/bin/panoramix",
"type": "add",
"edit_start_line_idx": 3
} | /*
Highcharts JS v4.1.7 (2015-06-26)
(c) 2009-2014 Torstein Honsi
License: www.highcharts.com/license
*/
(function(k,D){function K(a,b,c){this.init.call(this,a,b,c)}var P=k.arrayMin,Q=k.arrayMax,t=k.each,H=k.extend,o=k.merge,R=k.map,q=k.pick,x=k.pInt,p=k.getOptions().plotOptions,h=k.seriesTypes,v=k.extendClass,L=k.splat,u=k.wrap,M=k.Axis,y=k.Tick,I=k.Point,S=k.Pointer,T=k.CenteredSeriesMixin,z=k.TrackerMixin,s=k.Series,w=Math,E=w.round,B=w.floor,N=w.max,U=k.Color,r=function(){};H(K.prototype,{init:function(a,b,c){var d=this,e=d.defaultOptions;d.chart=b;d.options=a=o(e,b.angular?{background:{}}:void 0,
a);(a=a.background)&&t([].concat(L(a)).reverse(),function(a){var b=a.backgroundColor,g=c.userOptions,a=o(d.defaultBackgroundOptions,a);if(b)a.backgroundColor=b;a.color=a.backgroundColor;c.options.plotBands.unshift(a);g.plotBands=g.plotBands||[];g.plotBands.unshift(a)})},defaultOptions:{center:["50%","50%"],size:"85%",startAngle:0},defaultBackgroundOptions:{shape:"circle",borderWidth:1,borderColor:"silver",backgroundColor:{linearGradient:{x1:0,y1:0,x2:0,y2:1},stops:[[0,"#FFF"],[1,"#DDD"]]},from:-Number.MAX_VALUE,
innerRadius:0,to:Number.MAX_VALUE,outerRadius:"105%"}});var G=M.prototype,y=y.prototype,V={getOffset:r,redraw:function(){this.isDirty=!1},render:function(){this.isDirty=!1},setScale:r,setCategories:r,setTitle:r},O={isRadial:!0,defaultRadialGaugeOptions:{labels:{align:"center",x:0,y:null},minorGridLineWidth:0,minorTickInterval:"auto",minorTickLength:10,minorTickPosition:"inside",minorTickWidth:1,tickLength:10,tickPosition:"inside",tickWidth:2,title:{rotation:0},zIndex:2},defaultRadialXOptions:{gridLineWidth:1,
labels:{align:null,distance:15,x:0,y:null},maxPadding:0,minPadding:0,showLastLabel:!1,tickLength:0},defaultRadialYOptions:{gridLineInterpolation:"circle",labels:{align:"right",x:-3,y:-2},showLastLabel:!1,title:{x:4,text:null,rotation:90}},setOptions:function(a){a=this.options=o(this.defaultOptions,this.defaultRadialOptions,a);if(!a.plotBands)a.plotBands=[]},getOffset:function(){G.getOffset.call(this);this.chart.axisOffset[this.side]=0;this.center=this.pane.center=T.getCenter.call(this.pane)},getLinePath:function(a,
b){var c=this.center,b=q(b,c[2]/2-this.offset);return this.chart.renderer.symbols.arc(this.left+c[0],this.top+c[1],b,b,{start:this.startAngleRad,end:this.endAngleRad,open:!0,innerR:0})},setAxisTranslation:function(){G.setAxisTranslation.call(this);if(this.center)this.transA=this.isCircular?(this.endAngleRad-this.startAngleRad)/(this.max-this.min||1):this.center[2]/2/(this.max-this.min||1),this.minPixelPadding=this.isXAxis?this.transA*this.minPointOffset:0},beforeSetTickPositions:function(){this.autoConnect&&
(this.max+=this.categories&&1||this.pointRange||this.closestPointRange||0)},setAxisSize:function(){G.setAxisSize.call(this);if(this.isRadial){this.center=this.pane.center=k.CenteredSeriesMixin.getCenter.call(this.pane);if(this.isCircular)this.sector=this.endAngleRad-this.startAngleRad;this.len=this.width=this.height=this.center[2]*q(this.sector,1)/2}},getPosition:function(a,b){return this.postTranslate(this.isCircular?this.translate(a):0,q(this.isCircular?b:this.translate(a),this.center[2]/2)-this.offset)},
postTranslate:function(a,b){var c=this.chart,d=this.center,a=this.startAngleRad+a;return{x:c.plotLeft+d[0]+Math.cos(a)*b,y:c.plotTop+d[1]+Math.sin(a)*b}},getPlotBandPath:function(a,b,c){var d=this.center,e=this.startAngleRad,f=d[2]/2,i=[q(c.outerRadius,"100%"),c.innerRadius,q(c.thickness,10)],g=/%$/,l,m=this.isCircular;this.options.gridLineInterpolation==="polygon"?d=this.getPlotLinePath(a).concat(this.getPlotLinePath(b,!0)):(a=Math.max(a,this.min),b=Math.min(b,this.max),m||(i[0]=this.translate(a),
i[1]=this.translate(b)),i=R(i,function(a){g.test(a)&&(a=x(a,10)*f/100);return a}),c.shape==="circle"||!m?(a=-Math.PI/2,b=Math.PI*1.5,l=!0):(a=e+this.translate(a),b=e+this.translate(b)),d=this.chart.renderer.symbols.arc(this.left+d[0],this.top+d[1],i[0],i[0],{start:Math.min(a,b),end:Math.max(a,b),innerR:q(i[1],i[0]-i[2]),open:l}));return d},getPlotLinePath:function(a,b){var c=this,d=c.center,e=c.chart,f=c.getPosition(a),i,g,l;c.isCircular?l=["M",d[0]+e.plotLeft,d[1]+e.plotTop,"L",f.x,f.y]:c.options.gridLineInterpolation===
"circle"?(a=c.translate(a))&&(l=c.getLinePath(0,a)):(t(e.xAxis,function(a){a.pane===c.pane&&(i=a)}),l=[],a=c.translate(a),d=i.tickPositions,i.autoConnect&&(d=d.concat([d[0]])),b&&(d=[].concat(d).reverse()),t(d,function(f,c){g=i.getPosition(f,a);l.push(c?"L":"M",g.x,g.y)}));return l},getTitlePosition:function(){var a=this.center,b=this.chart,c=this.options.title;return{x:b.plotLeft+a[0]+(c.x||0),y:b.plotTop+a[1]-{high:0.5,middle:0.25,low:0}[c.align]*a[2]+(c.y||0)}}};u(G,"init",function(a,b,c){var j;
var d=b.angular,e=b.polar,f=c.isX,i=d&&f,g,l;l=b.options;var m=c.pane||0;if(d){if(H(this,i?V:O),g=!f)this.defaultRadialOptions=this.defaultRadialGaugeOptions}else if(e)H(this,O),this.defaultRadialOptions=(g=f)?this.defaultRadialXOptions:o(this.defaultYAxisOptions,this.defaultRadialYOptions);a.call(this,b,c);if(!i&&(d||e)){a=this.options;if(!b.panes)b.panes=[];this.pane=(j=b.panes[m]=b.panes[m]||new K(L(l.pane)[m],b,this),m=j);m=m.options;b.inverted=!1;l.chart.zoomType=null;this.startAngleRad=b=(m.startAngle-
90)*Math.PI/180;this.endAngleRad=l=(q(m.endAngle,m.startAngle+360)-90)*Math.PI/180;this.offset=a.offset||0;if((this.isCircular=g)&&c.max===D&&l-b===2*Math.PI)this.autoConnect=!0}});u(y,"getPosition",function(a,b,c,d,e){var f=this.axis;return f.getPosition?f.getPosition(c):a.call(this,b,c,d,e)});u(y,"getLabelPosition",function(a,b,c,d,e,f,i,g,l){var m=this.axis,j=f.y,n=20,h=f.align,A=(m.translate(this.pos)+m.startAngleRad+Math.PI/2)/Math.PI*180%360;m.isRadial?(a=m.getPosition(this.pos,m.center[2]/
2+q(f.distance,-25)),f.rotation==="auto"?d.attr({rotation:A}):j===null&&(j=m.chart.renderer.fontMetrics(d.styles.fontSize).b-d.getBBox().height/2),h===null&&(m.isCircular?(this.label.getBBox().width>m.len*m.tickInterval/(m.max-m.min)&&(n=0),h=A>n&&A<180-n?"left":A>180+n&&A<360-n?"right":"center"):h="center",d.attr({align:h})),a.x+=f.x,a.y+=j):a=a.call(this,b,c,d,e,f,i,g,l);return a});u(y,"getMarkPath",function(a,b,c,d,e,f,i){var g=this.axis;g.isRadial?(a=g.getPosition(this.pos,g.center[2]/2+d),b=
["M",b,c,"L",a.x,a.y]):b=a.call(this,b,c,d,e,f,i);return b});p.arearange=o(p.area,{lineWidth:1,marker:null,threshold:null,tooltip:{pointFormat:'<span style="color:{series.color}">\u25CF</span> {series.name}: <b>{point.low}</b> - <b>{point.high}</b><br/>'},trackByArea:!0,dataLabels:{align:null,verticalAlign:null,xLow:0,xHigh:0,yLow:0,yHigh:0},states:{hover:{halo:!1}}});h.arearange=v(h.area,{type:"arearange",pointArrayMap:["low","high"],toYData:function(a){return[a.low,a.high]},pointValKey:"low",deferTranslatePolar:!0,
highToXY:function(a){var b=this.chart,c=this.xAxis.postTranslate(a.rectPlotX,this.yAxis.len-a.plotHigh);a.plotHighX=c.x-b.plotLeft;a.plotHigh=c.y-b.plotTop},getSegments:function(){var a=this;t(a.points,function(b){if(!a.options.connectNulls&&(b.low===null||b.high===null))b.y=null;else if(b.low===null&&b.high!==null)b.y=b.high});s.prototype.getSegments.call(this)},translate:function(){var a=this,b=a.yAxis;h.area.prototype.translate.apply(a);t(a.points,function(a){var d=a.low,e=a.high,f=a.plotY;e===
null&&d===null?a.y=null:d===null?(a.plotLow=a.plotY=null,a.plotHigh=b.translate(e,0,1,0,1)):e===null?(a.plotLow=f,a.plotHigh=null):(a.plotLow=f,a.plotHigh=b.translate(e,0,1,0,1))});this.chart.polar&&t(this.points,function(c){a.highToXY(c)})},getSegmentPath:function(a){var b,c=[],d=a.length,e=s.prototype.getSegmentPath,f,i;i=this.options;var g=i.step;for(b=HighchartsAdapter.grep(a,function(a){return a.plotLow!==null});d--;)f=a[d],f.plotHigh!==null&&c.push({plotX:f.plotHighX||f.plotX,plotY:f.plotHigh});
a=e.call(this,b);if(g)g===!0&&(g="left"),i.step={left:"right",center:"center",right:"left"}[g];c=e.call(this,c);i.step=g;i=[].concat(a,c);this.chart.polar||(c[0]="L");this.areaPath=this.areaPath.concat(a,c);return i},drawDataLabels:function(){var a=this.data,b=a.length,c,d=[],e=s.prototype,f=this.options.dataLabels,i=f.align,g,l,m=this.chart.inverted;if(f.enabled||this._hasPointLabels){for(c=b;c--;)if(g=a[c])if(l=g.plotHigh>g.plotLow,g.y=g.high,g._plotY=g.plotY,g.plotY=g.plotHigh,d[c]=g.dataLabel,
g.dataLabel=g.dataLabelUpper,g.below=l,m){if(!i)f.align=l?"right":"left";f.x=f.xHigh}else f.y=f.yHigh;e.drawDataLabels&&e.drawDataLabels.apply(this,arguments);for(c=b;c--;)if(g=a[c])if(l=g.plotHigh>g.plotLow,g.dataLabelUpper=g.dataLabel,g.dataLabel=d[c],g.y=g.low,g.plotY=g._plotY,g.below=!l,m){if(!i)f.align=l?"left":"right";f.x=f.xLow}else f.y=f.yLow;e.drawDataLabels&&e.drawDataLabels.apply(this,arguments)}f.align=i},alignDataLabel:function(){h.column.prototype.alignDataLabel.apply(this,arguments)},
setStackedPoints:r,getSymbol:r,drawPoints:r});p.areasplinerange=o(p.arearange);h.areasplinerange=v(h.arearange,{type:"areasplinerange",getPointSpline:h.spline.prototype.getPointSpline});(function(){var a=h.column.prototype;p.columnrange=o(p.column,p.arearange,{lineWidth:1,pointRange:null});h.columnrange=v(h.arearange,{type:"columnrange",translate:function(){var b=this,c=b.yAxis,d;a.translate.apply(b);t(b.points,function(a){var f=a.shapeArgs,i=b.options.minPointLength,g;a.tooltipPos=null;a.plotHigh=
d=c.translate(a.high,0,1,0,1);a.plotLow=a.plotY;g=d;a=a.plotY-d;Math.abs(a)<i?(i-=a,a+=i,g-=i/2):a<0&&(a*=-1,g-=a);f.height=a;f.y=g})},directTouch:!0,trackerGroups:["group","dataLabelsGroup"],drawGraph:r,pointAttrToOptions:a.pointAttrToOptions,drawPoints:a.drawPoints,drawTracker:a.drawTracker,animate:a.animate,getColumnMetrics:a.getColumnMetrics})})();p.gauge=o(p.line,{dataLabels:{enabled:!0,defer:!1,y:15,borderWidth:1,borderColor:"silver",borderRadius:3,crop:!1,verticalAlign:"top",zIndex:2},dial:{},
pivot:{},tooltip:{headerFormat:""},showInLegend:!1});z={type:"gauge",pointClass:v(I,{setState:function(a){this.state=a}}),angular:!0,drawGraph:r,fixedBox:!0,forceDL:!0,trackerGroups:["group","dataLabelsGroup"],translate:function(){var a=this.yAxis,b=this.options,c=a.center;this.generatePoints();t(this.points,function(d){var e=o(b.dial,d.dial),f=x(q(e.radius,80))*c[2]/200,i=x(q(e.baseLength,70))*f/100,g=x(q(e.rearLength,10))*f/100,l=e.baseWidth||3,m=e.topWidth||1,j=b.overshoot,n=a.startAngleRad+a.translate(d.y,
null,null,null,!0);j&&typeof j==="number"?(j=j/180*Math.PI,n=Math.max(a.startAngleRad-j,Math.min(a.endAngleRad+j,n))):b.wrap===!1&&(n=Math.max(a.startAngleRad,Math.min(a.endAngleRad,n)));n=n*180/Math.PI;d.shapeType="path";d.shapeArgs={d:e.path||["M",-g,-l/2,"L",i,-l/2,f,-m/2,f,m/2,i,l/2,-g,l/2,"z"],translateX:c[0],translateY:c[1],rotation:n};d.plotX=c[0];d.plotY=c[1]})},drawPoints:function(){var a=this,b=a.yAxis.center,c=a.pivot,d=a.options,e=d.pivot,f=a.chart.renderer;t(a.points,function(c){var b=
c.graphic,e=c.shapeArgs,m=e.d,j=o(d.dial,c.dial);b?(b.animate(e),e.d=m):c.graphic=f[c.shapeType](e).attr({stroke:j.borderColor||"none","stroke-width":j.borderWidth||0,fill:j.backgroundColor||"black",rotation:e.rotation}).add(a.group)});c?c.animate({translateX:b[0],translateY:b[1]}):a.pivot=f.circle(0,0,q(e.radius,5)).attr({"stroke-width":e.borderWidth||0,stroke:e.borderColor||"silver",fill:e.backgroundColor||"black"}).translate(b[0],b[1]).add(a.group)},animate:function(a){var b=this;if(!a)t(b.points,
function(a){var d=a.graphic;d&&(d.attr({rotation:b.yAxis.startAngleRad*180/Math.PI}),d.animate({rotation:a.shapeArgs.rotation},b.options.animation))}),b.animate=null},render:function(){this.group=this.plotGroup("group","series",this.visible?"visible":"hidden",this.options.zIndex,this.chart.seriesGroup);s.prototype.render.call(this);this.group.clip(this.chart.clipRect)},setData:function(a,b){s.prototype.setData.call(this,a,!1);this.processData();this.generatePoints();q(b,!0)&&this.chart.redraw()},
drawTracker:z&&z.drawTrackerPoint};h.gauge=v(h.line,z);p.boxplot=o(p.column,{fillColor:"#FFFFFF",lineWidth:1,medianWidth:2,states:{hover:{brightness:-0.3}},threshold:null,tooltip:{pointFormat:'<span style="color:{point.color}">\u25CF</span> <b> {series.name}</b><br/>Maximum: {point.high}<br/>Upper quartile: {point.q3}<br/>Median: {point.median}<br/>Lower quartile: {point.q1}<br/>Minimum: {point.low}<br/>'},whiskerLength:"50%",whiskerWidth:2});h.boxplot=v(h.column,{type:"boxplot",pointArrayMap:["low","q1",
"median","q3","high"],toYData:function(a){return[a.low,a.q1,a.median,a.q3,a.high]},pointValKey:"high",pointAttrToOptions:{fill:"fillColor",stroke:"color","stroke-width":"lineWidth"},drawDataLabels:r,translate:function(){var a=this.yAxis,b=this.pointArrayMap;h.column.prototype.translate.apply(this);t(this.points,function(c){t(b,function(b){c[b]!==null&&(c[b+"Plot"]=a.translate(c[b],0,1,0,1))})})},drawPoints:function(){var a=this,b=a.points,c=a.options,d=a.chart.renderer,e,f,i,g,l,m,j,n,h,A,k,J,p,o,
u,r,v,s,w,x,z,y,F=a.doQuartiles!==!1,C=parseInt(a.options.whiskerLength,10)/100;t(b,function(b){h=b.graphic;z=b.shapeArgs;k={};o={};r={};y=b.color||a.color;if(b.plotY!==D)if(e=b.pointAttr[b.selected?"selected":""],v=z.width,s=B(z.x),w=s+v,x=E(v/2),f=B(F?b.q1Plot:b.lowPlot),i=B(F?b.q3Plot:b.lowPlot),g=B(b.highPlot),l=B(b.lowPlot),k.stroke=b.stemColor||c.stemColor||y,k["stroke-width"]=q(b.stemWidth,c.stemWidth,c.lineWidth),k.dashstyle=b.stemDashStyle||c.stemDashStyle,o.stroke=b.whiskerColor||c.whiskerColor||
y,o["stroke-width"]=q(b.whiskerWidth,c.whiskerWidth,c.lineWidth),r.stroke=b.medianColor||c.medianColor||y,r["stroke-width"]=q(b.medianWidth,c.medianWidth,c.lineWidth),j=k["stroke-width"]%2/2,n=s+x+j,A=["M",n,i,"L",n,g,"M",n,f,"L",n,l],F&&(j=e["stroke-width"]%2/2,n=B(n)+j,f=B(f)+j,i=B(i)+j,s+=j,w+=j,J=["M",s,i,"L",s,f,"L",w,f,"L",w,i,"L",s,i,"z"]),C&&(j=o["stroke-width"]%2/2,g+=j,l+=j,p=["M",n-x*C,g,"L",n+x*C,g,"M",n-x*C,l,"L",n+x*C,l]),j=r["stroke-width"]%2/2,m=E(b.medianPlot)+j,u=["M",s,m,"L",w,
m],h)b.stem.animate({d:A}),C&&b.whiskers.animate({d:p}),F&&b.box.animate({d:J}),b.medianShape.animate({d:u});else{b.graphic=h=d.g().add(a.group);b.stem=d.path(A).attr(k).add(h);if(C)b.whiskers=d.path(p).attr(o).add(h);if(F)b.box=d.path(J).attr(e).add(h);b.medianShape=d.path(u).attr(r).add(h)}})},setStackedPoints:r});p.errorbar=o(p.boxplot,{color:"#000000",grouping:!1,linkedTo:":previous",tooltip:{pointFormat:'<span style="color:{point.color}">\u25CF</span> {series.name}: <b>{point.low}</b> - <b>{point.high}</b><br/>'},
whiskerWidth:null});h.errorbar=v(h.boxplot,{type:"errorbar",pointArrayMap:["low","high"],toYData:function(a){return[a.low,a.high]},pointValKey:"high",doQuartiles:!1,drawDataLabels:h.arearange?h.arearange.prototype.drawDataLabels:r,getColumnMetrics:function(){return this.linkedParent&&this.linkedParent.columnMetrics||h.column.prototype.getColumnMetrics.call(this)}});p.waterfall=o(p.column,{lineWidth:1,lineColor:"#333",dashStyle:"dot",borderColor:"#333",dataLabels:{inside:!0},states:{hover:{lineWidthPlus:0}}});
h.waterfall=v(h.column,{type:"waterfall",upColorProp:"fill",pointValKey:"y",translate:function(){var a=this.options,b=this.yAxis,c,d,e,f,i,g,l,m,j,n=a.threshold,k=a.stacking;h.column.prototype.translate.apply(this);l=m=n;d=this.points;for(c=0,a=d.length;c<a;c++){e=d[c];g=this.processedYData[c];f=e.shapeArgs;j=(i=k&&b.stacks[(this.negStacks&&g<n?"-":"")+this.stackKey])?i[e.x].points[this.index+","+c]:[0,g];if(e.isSum)e.y=g;else if(e.isIntermediateSum)e.y=g-m;i=N(l,l+e.y)+j[0];f.y=b.translate(i,0,1);
if(e.isSum)f.y=b.translate(j[1],0,1),f.height=Math.min(b.translate(j[0],0,1),b.len)-f.y;else if(e.isIntermediateSum)f.y=b.translate(j[1],0,1),f.height=Math.min(b.translate(m,0,1),b.len)-f.y,m=j[1];else{if(l!==0)f.height=g>0?b.translate(l,0,1)-f.y:b.translate(l,0,1)-b.translate(l-g,0,1);l+=g}f.height<0&&(f.y+=f.height,f.height*=-1);e.plotY=f.y=E(f.y)-this.borderWidth%2/2;f.height=N(E(f.height),0.001);e.yBottom=f.y+f.height;f=e.plotY+(e.negative?f.height:0);this.chart.inverted?e.tooltipPos[0]=b.len-
f:e.tooltipPos[1]=f}},processData:function(a){var b=this.yData,c=this.options.data,d,e=b.length,f,i,g,l,m,j;i=f=g=l=this.options.threshold||0;for(j=0;j<e;j++)m=b[j],d=c&&c[j]?c[j]:{},m==="sum"||d.isSum?b[j]=i:m==="intermediateSum"||d.isIntermediateSum?b[j]=f:(i+=m,f+=m),g=Math.min(i,g),l=Math.max(i,l);s.prototype.processData.call(this,a);this.dataMin=g;this.dataMax=l},toYData:function(a){if(a.isSum)return a.x===0?null:"sum";else if(a.isIntermediateSum)return a.x===0?null:"intermediateSum";return a.y},
getAttribs:function(){h.column.prototype.getAttribs.apply(this,arguments);var a=this,b=a.options,c=b.states,d=b.upColor||a.color,b=k.Color(d).brighten(0.1).get(),e=o(a.pointAttr),f=a.upColorProp;e[""][f]=d;e.hover[f]=c.hover.upColor||b;e.select[f]=c.select.upColor||d;t(a.points,function(b){if(!b.options.color)b.y>0?(b.pointAttr=e,b.color=d):b.pointAttr=a.pointAttr})},getGraphPath:function(){var a=this.data,b=a.length,c=E(this.options.lineWidth+this.borderWidth)%2/2,d=[],e,f,i;for(i=1;i<b;i++)f=a[i].shapeArgs,
e=a[i-1].shapeArgs,f=["M",e.x+e.width,e.y+c,"L",f.x,e.y+c],a[i-1].y<0&&(f[2]+=e.height,f[5]+=e.height),d=d.concat(f);return d},getExtremes:r,drawGraph:s.prototype.drawGraph});p.polygon=o(p.scatter,{marker:{enabled:!1}});h.polygon=v(h.scatter,{type:"polygon",fillGraph:!0,getSegmentPath:function(a){return s.prototype.getSegmentPath.call(this,a).concat("z")},drawGraph:s.prototype.drawGraph,drawLegendSymbol:k.LegendSymbolMixin.drawRectangle});p.bubble=o(p.scatter,{dataLabels:{formatter:function(){return this.point.z},
inside:!0,verticalAlign:"middle"},marker:{lineColor:null,lineWidth:1},minSize:8,maxSize:"20%",states:{hover:{halo:{size:5}}},tooltip:{pointFormat:"({point.x}, {point.y}), Size: {point.z}"},turboThreshold:0,zThreshold:0,zoneAxis:"z"});z=v(I,{haloPath:function(){return I.prototype.haloPath.call(this,this.shapeArgs.r+this.series.options.states.hover.halo.size)},ttBelow:!1});h.bubble=v(h.scatter,{type:"bubble",pointClass:z,pointArrayMap:["y","z"],parallelArrays:["x","y","z"],trackerGroups:["group","dataLabelsGroup"],
bubblePadding:!0,zoneAxis:"z",pointAttrToOptions:{stroke:"lineColor","stroke-width":"lineWidth",fill:"fillColor"},applyOpacity:function(a){var b=this.options.marker,c=q(b.fillOpacity,0.5),a=a||b.fillColor||this.color;c!==1&&(a=U(a).setOpacity(c).get("rgba"));return a},convertAttribs:function(){var a=s.prototype.convertAttribs.apply(this,arguments);a.fill=this.applyOpacity(a.fill);return a},getRadii:function(a,b,c,d){var e,f,i,g=this.zData,l=[],m=this.options.sizeBy!=="width";for(f=0,e=g.length;f<
e;f++)i=b-a,i=i>0?(g[f]-a)/(b-a):0.5,m&&i>=0&&(i=Math.sqrt(i)),l.push(w.ceil(c+i*(d-c))/2);this.radii=l},animate:function(a){var b=this.options.animation;if(!a)t(this.points,function(a){var d=a.graphic,a=a.shapeArgs;d&&a&&(d.attr("r",1),d.animate({r:a.r},b))}),this.animate=null},translate:function(){var a,b=this.data,c,d,e=this.radii;h.scatter.prototype.translate.call(this);for(a=b.length;a--;)c=b[a],d=e?e[a]:0,d>=this.minPxSize/2?(c.shapeType="circle",c.shapeArgs={x:c.plotX,y:c.plotY,r:d},c.dlBox=
{x:c.plotX-d,y:c.plotY-d,width:2*d,height:2*d}):c.shapeArgs=c.plotY=c.dlBox=D},drawLegendSymbol:function(a,b){var c=x(a.itemStyle.fontSize)/2;b.legendSymbol=this.chart.renderer.circle(c,a.baseline-c,c).attr({zIndex:3}).add(b.legendGroup);b.legendSymbol.isMarker=!0},drawPoints:h.column.prototype.drawPoints,alignDataLabel:h.column.prototype.alignDataLabel,buildKDTree:r,applyZones:r});M.prototype.beforePadding=function(){var a=this,b=this.len,c=this.chart,d=0,e=b,f=this.isXAxis,i=f?"xData":"yData",g=
this.min,l={},m=w.min(c.plotWidth,c.plotHeight),j=Number.MAX_VALUE,n=-Number.MAX_VALUE,h=this.max-g,k=b/h,p=[];t(this.series,function(b){var g=b.options;if(b.bubblePadding&&(b.visible||!c.options.chart.ignoreHiddenSeries))if(a.allowZoomOutside=!0,p.push(b),f)t(["minSize","maxSize"],function(a){var b=g[a],f=/%$/.test(b),b=x(b);l[a]=f?m*b/100:b}),b.minPxSize=l.minSize,b=b.zData,b.length&&(j=q(g.zMin,w.min(j,w.max(P(b),g.displayNegative===!1?g.zThreshold:-Number.MAX_VALUE))),n=q(g.zMax,w.max(n,Q(b))))});
t(p,function(a){var b=a[i],c=b.length,m;f&&a.getRadii(j,n,l.minSize,l.maxSize);if(h>0)for(;c--;)typeof b[c]==="number"&&(m=a.radii[c],d=Math.min((b[c]-g)*k-m,d),e=Math.max((b[c]-g)*k+m,e))});p.length&&h>0&&q(this.options.min,this.userMin)===D&&q(this.options.max,this.userMax)===D&&(e-=b,k*=(b+d-e)/b,this.min+=d/k,this.max+=e/k)};(function(){function a(a,b,c){a.call(this,b,c);if(this.chart.polar)this.closeSegment=function(a){var b=this.xAxis.center;a.push("L",b[0],b[1])},this.closedStacks=!0}function b(a,
b){var c=this.chart,d=this.options.animation,e=this.group,j=this.markerGroup,n=this.xAxis.center,h=c.plotLeft,k=c.plotTop;if(c.polar){if(c.renderer.isSVG)d===!0&&(d={}),b?(c={translateX:n[0]+h,translateY:n[1]+k,scaleX:0.001,scaleY:0.001},e.attr(c),j&&j.attr(c)):(c={translateX:h,translateY:k,scaleX:1,scaleY:1},e.animate(c,d),j&&j.animate(c,d),this.animate=null)}else a.call(this,b)}var c=s.prototype,d=S.prototype,e;c.searchPointByAngle=function(a){var b=this.chart,c=this.xAxis.pane.center;return this.searchKDTree({clientX:180+
Math.atan2(a.chartX-c[0]-b.plotLeft,a.chartY-c[1]-b.plotTop)*(-180/Math.PI)})};u(c,"buildKDTree",function(a){if(this.chart.polar)this.kdByAngle?this.searchPoint=this.searchPointByAngle:this.kdDimensions=2;a.apply(this)});c.toXY=function(a){var b,c=this.chart,d=a.plotX;b=a.plotY;a.rectPlotX=d;a.rectPlotY=b;b=this.xAxis.postTranslate(a.plotX,this.yAxis.len-b);a.plotX=a.polarPlotX=b.x-c.plotLeft;a.plotY=a.polarPlotY=b.y-c.plotTop;this.kdByAngle?(c=(d/Math.PI*180+this.xAxis.pane.options.startAngle)%360,
c<0&&(c+=360),a.clientX=c):a.clientX=a.plotX};h.area&&u(h.area.prototype,"init",a);h.areaspline&&u(h.areaspline.prototype,"init",a);h.spline&&u(h.spline.prototype,"getPointSpline",function(a,b,c,d){var e,j,n,h,k,p,o;if(this.chart.polar){e=c.plotX;j=c.plotY;a=b[d-1];n=b[d+1];this.connectEnds&&(a||(a=b[b.length-2]),n||(n=b[1]));if(a&&n)h=a.plotX,k=a.plotY,b=n.plotX,p=n.plotY,h=(1.5*e+h)/2.5,k=(1.5*j+k)/2.5,n=(1.5*e+b)/2.5,o=(1.5*j+p)/2.5,b=Math.sqrt(Math.pow(h-e,2)+Math.pow(k-j,2)),p=Math.sqrt(Math.pow(n-
e,2)+Math.pow(o-j,2)),h=Math.atan2(k-j,h-e),k=Math.atan2(o-j,n-e),o=Math.PI/2+(h+k)/2,Math.abs(h-o)>Math.PI/2&&(o-=Math.PI),h=e+Math.cos(o)*b,k=j+Math.sin(o)*b,n=e+Math.cos(Math.PI+o)*p,o=j+Math.sin(Math.PI+o)*p,c.rightContX=n,c.rightContY=o;d?(c=["C",a.rightContX||a.plotX,a.rightContY||a.plotY,h||e,k||j,e,j],a.rightContX=a.rightContY=null):c=["M",e,j]}else c=a.call(this,b,c,d);return c});u(c,"translate",function(a){var b=this.chart;a.call(this);if(b.polar&&(this.kdByAngle=b.tooltip&&b.tooltip.shared,
!this.preventPostTranslate)){a=this.points;for(b=a.length;b--;)this.toXY(a[b])}});u(c,"getSegmentPath",function(a,b){var c=this.points;if(this.chart.polar&&this.options.connectEnds!==!1&&b[b.length-1]===c[c.length-1]&&c[0].y!==null)this.connectEnds=!0,b=[].concat(b,[c[0]]);return a.call(this,b)});u(c,"animate",b);if(h.column)e=h.column.prototype,u(e,"animate",b),u(e,"translate",function(a){var b=this.xAxis,c=this.yAxis.len,d=b.center,e=b.startAngleRad,j=this.chart.renderer,h,k;this.preventPostTranslate=
!0;a.call(this);if(b.isRadial){b=this.points;for(k=b.length;k--;)h=b[k],a=h.barX+e,h.shapeType="path",h.shapeArgs={d:j.symbols.arc(d[0],d[1],c-h.plotY,null,{start:a,end:a+h.pointWidth,innerR:c-q(h.yBottom,c)})},this.toXY(h),h.tooltipPos=[h.plotX,h.plotY],h.ttBelow=h.plotY>d[1]}}),u(e,"alignDataLabel",function(a,b,d,e,h,j){if(this.chart.polar){a=b.rectPlotX/Math.PI*180;if(e.align===null)e.align=a>20&&a<160?"left":a>200&&a<340?"right":"center";if(e.verticalAlign===null)e.verticalAlign=a<45||a>315?"bottom":
a>135&&a<225?"top":"middle";c.alignDataLabel.call(this,b,d,e,h,j)}else a.call(this,b,d,e,h,j)});u(d,"getCoordinates",function(a,b){var c=this.chart,d={xAxis:[],yAxis:[]};c.polar?t(c.axes,function(a){var e=a.isXAxis,f=a.center,h=b.chartX-f[0]-c.plotLeft,f=b.chartY-f[1]-c.plotTop;d[e?"xAxis":"yAxis"].push({axis:a,value:a.translate(e?Math.PI-Math.atan2(h,f):Math.sqrt(Math.pow(h,2)+Math.pow(f,2)),!0)})}):d=a.call(this,b);return d})})()})(Highcharts);
| panoramix/static/highcharts-more.js | 0 | https://github.com/apache/superset/commit/6dd81a3e95a9d67be743815ff9bfcd465278b3e9 | [
0.0012795549118891358,
0.0004954938194714487,
0.00016437498561572284,
0.00016700119886081666,
0.0004717254196293652
] |
{
"id": 0,
"code_window": [
"#!/usr/bin/env python\n",
"from panoramix import app, config\n",
"from subprocess import Popen\n",
"\n",
"\n",
"if __name__ == \"__main__\":\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"import argparse\n"
],
"file_path": "panoramix/bin/panoramix",
"type": "add",
"edit_start_line_idx": 3
} | Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
| LICENSE.txt | 0 | https://github.com/apache/superset/commit/6dd81a3e95a9d67be743815ff9bfcd465278b3e9 | [
0.00017987718456424773,
0.00017383391968905926,
0.00016300866263918579,
0.00017427974671591073,
0.000003530716639943421
] |
{
"id": 0,
"code_window": [
"#!/usr/bin/env python\n",
"from panoramix import app, config\n",
"from subprocess import Popen\n",
"\n",
"\n",
"if __name__ == \"__main__\":\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"import argparse\n"
],
"file_path": "panoramix/bin/panoramix",
"type": "add",
"edit_start_line_idx": 3
} | /*! DataTables Bootstrap 3 integration
* ©2011-2014 SpryMedia Ltd - datatables.net/license
*/
/**
* DataTables integration for Bootstrap 3. This requires Bootstrap 3 and
* DataTables 1.10 or newer.
*
* This file sets the defaults and adds options to DataTables to style its
* controls using Bootstrap. See http://datatables.net/manual/styling/bootstrap
* for further information.
*/
(function(window, document, undefined){
var factory = function( $, DataTable ) {
"use strict";
/* Set the defaults for DataTables initialisation */
$.extend( true, DataTable.defaults, {
dom:
"<'row'<'col-sm-6'l><'col-sm-6'f>>" +
"<'row'<'col-sm-12'tr>>" +
"<'row'<'col-sm-5'i><'col-sm-7'p>>",
renderer: 'bootstrap'
} );
/* Default class modification */
$.extend( DataTable.ext.classes, {
sWrapper: "dataTables_wrapper form-inline dt-bootstrap",
sFilterInput: "form-control input-sm",
sLengthSelect: "form-control input-sm"
} );
/* Bootstrap paging button renderer */
DataTable.ext.renderer.pageButton.bootstrap = function ( settings, host, idx, buttons, page, pages ) {
var api = new DataTable.Api( settings );
var classes = settings.oClasses;
var lang = settings.oLanguage.oPaginate;
var btnDisplay, btnClass, counter=0;
var attach = function( container, buttons ) {
var i, ien, node, button;
var clickHandler = function ( e ) {
e.preventDefault();
if ( !$(e.currentTarget).hasClass('disabled') ) {
api.page( e.data.action ).draw( false );
}
};
for ( i=0, ien=buttons.length ; i<ien ; i++ ) {
button = buttons[i];
if ( $.isArray( button ) ) {
attach( container, button );
}
else {
btnDisplay = '';
btnClass = '';
switch ( button ) {
case 'ellipsis':
btnDisplay = '…';
btnClass = 'disabled';
break;
case 'first':
btnDisplay = lang.sFirst;
btnClass = button + (page > 0 ?
'' : ' disabled');
break;
case 'previous':
btnDisplay = lang.sPrevious;
btnClass = button + (page > 0 ?
'' : ' disabled');
break;
case 'next':
btnDisplay = lang.sNext;
btnClass = button + (page < pages-1 ?
'' : ' disabled');
break;
case 'last':
btnDisplay = lang.sLast;
btnClass = button + (page < pages-1 ?
'' : ' disabled');
break;
default:
btnDisplay = button + 1;
btnClass = page === button ?
'active' : '';
break;
}
if ( btnDisplay ) {
node = $('<li>', {
'class': classes.sPageButton+' '+btnClass,
'id': idx === 0 && typeof button === 'string' ?
settings.sTableId +'_'+ button :
null
} )
.append( $('<a>', {
'href': '#',
'aria-controls': settings.sTableId,
'data-dt-idx': counter,
'tabindex': settings.iTabIndex
} )
.html( btnDisplay )
)
.appendTo( container );
settings.oApi._fnBindAction(
node, {action: button}, clickHandler
);
counter++;
}
}
}
};
// IE9 throws an 'unknown error' if document.activeElement is used
// inside an iframe or frame.
var activeEl;
try {
// Because this approach is destroying and recreating the paging
// elements, focus is lost on the select button which is bad for
// accessibility. So we want to restore focus once the draw has
// completed
activeEl = $(document.activeElement).data('dt-idx');
}
catch (e) {}
attach(
$(host).empty().html('<ul class="pagination"/>').children('ul'),
buttons
);
if ( activeEl ) {
$(host).find( '[data-dt-idx='+activeEl+']' ).focus();
}
};
/*
* TableTools Bootstrap compatibility
* Required TableTools 2.1+
*/
if ( DataTable.TableTools ) {
// Set the classes that TableTools uses to something suitable for Bootstrap
$.extend( true, DataTable.TableTools.classes, {
"container": "DTTT btn-group",
"buttons": {
"normal": "btn btn-default",
"disabled": "disabled"
},
"collection": {
"container": "DTTT_dropdown dropdown-menu",
"buttons": {
"normal": "",
"disabled": "disabled"
}
},
"print": {
"info": "DTTT_print_info"
},
"select": {
"row": "active"
}
} );
// Have the collection use a bootstrap compatible drop down
$.extend( true, DataTable.TableTools.DEFAULTS.oTags, {
"collection": {
"container": "ul",
"button": "li",
"liner": "a"
}
} );
}
}; // /factory
// Define as an AMD module if possible
if ( typeof define === 'function' && define.amd ) {
define( ['jquery', 'datatables'], factory );
}
else if ( typeof exports === 'object' ) {
// Node/CommonJS
factory( require('jquery'), require('datatables') );
}
else if ( jQuery ) {
// Otherwise simply initialise as normal, stopping multiple evaluation
factory( jQuery, jQuery.fn.dataTable );
}
})(window, document);
| panoramix/static/dataTables.bootstrap.js | 0 | https://github.com/apache/superset/commit/6dd81a3e95a9d67be743815ff9bfcd465278b3e9 | [
0.00017325644148513675,
0.0001689366763457656,
0.0001633233914617449,
0.00016905719530768692,
0.0000026074105790030444
] |
{
"id": 1,
"code_window": [
"\n",
"\n",
"if __name__ == \"__main__\":\n",
" if config.DEBUG:\n",
" app.run(\n",
" host='0.0.0.0',\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep"
],
"after_edit": [
" parser = argparse.ArgumentParser(\n",
" description='Start a Panoramix web server')\n",
" parser.add_argument(\n",
" '-d', '--debug', action='store_true',\n",
" help=\"Start the web server in debug mode\")\n",
" parser.add_argument(\n",
" '-p', '--port', default=config.PANORAMIX_WEBSERVER_PORT,\n",
" help=\"Specify the port on which to run the web server\")\n",
" args = parser.parse_args()\n",
" args.debug = args.debug or config.DEBUG\n",
" if args.debug:\n"
],
"file_path": "panoramix/bin/panoramix",
"type": "replace",
"edit_start_line_idx": 6
} | from datetime import datetime
import json
import logging
from flask import request, redirect, flash, Response
from flask.ext.appbuilder.models.sqla.interface import SQLAInterface
from flask.ext.appbuilder import ModelView, CompactCRUDMixin, BaseView, expose
from flask.ext.appbuilder.security.decorators import has_access
from pydruid.client import doublesum
from wtforms.validators import ValidationError
from flask.ext.appbuilder.actions import action
from panoramix import appbuilder, db, models, viz, utils, app
def validate_json(form, field):
try:
json.loads(field.data)
except Exception as e:
raise ValidationError("Json isn't valid")
class DeleteMixin(object):
@action("muldelete", "Delete", "Delete all Really?", "fa-trash", single=False)
def muldelete(self, items):
self.datamodel.delete_all(items)
self.update_redirect()
return redirect(self.get_redirect())
class TableColumnInlineView(CompactCRUDMixin, ModelView):
datamodel = SQLAInterface(models.TableColumn)
can_delete = False
edit_columns = [
'column_name', 'description', 'table', 'groupby', 'filterable',
'count_distinct', 'sum', 'min', 'max']
list_columns = [
'column_name', 'type', 'groupby', 'filterable', 'count_distinct',
'sum', 'min', 'max']
page_size = 100
appbuilder.add_view_no_menu(TableColumnInlineView)
class ColumnInlineView(CompactCRUDMixin, ModelView):
datamodel = SQLAInterface(models.Column)
edit_columns = [
'column_name', 'description', 'datasource', 'groupby',
'count_distinct', 'sum', 'min', 'max']
list_columns = [
'column_name', 'type', 'groupby', 'filterable', 'count_distinct',
'sum', 'min', 'max']
can_delete = False
page_size = 100
def post_update(self, col):
col.generate_metrics()
def post_update(self, col):
col.generate_metrics()
appbuilder.add_view_no_menu(ColumnInlineView)
class SqlMetricInlineView(CompactCRUDMixin, ModelView):
datamodel = SQLAInterface(models.SqlMetric)
list_columns = ['metric_name', 'verbose_name', 'metric_type' ]
edit_columns = [
'metric_name', 'description', 'verbose_name', 'metric_type',
'table', 'expression']
add_columns = edit_columns
page_size = 100
appbuilder.add_view_no_menu(SqlMetricInlineView)
class MetricInlineView(CompactCRUDMixin, ModelView):
datamodel = SQLAInterface(models.Metric)
list_columns = ['metric_name', 'verbose_name', 'metric_type' ]
edit_columns = [
'metric_name', 'description', 'verbose_name', 'metric_type',
'datasource', 'json']
add_columns = [
'metric_name', 'verbose_name', 'metric_type', 'datasource', 'json']
page_size = 100
validators_columns = {
'json': [validate_json],
}
appbuilder.add_view_no_menu(MetricInlineView)
class ClusterModelView(ModelView, DeleteMixin):
datamodel = SQLAInterface(models.Cluster)
add_columns = [
'cluster_name',
'coordinator_host', 'coordinator_port', 'coordinator_endpoint',
'broker_host', 'broker_port', 'broker_endpoint',
]
edit_columns = add_columns
list_columns = ['cluster_name', 'metadata_last_refreshed']
appbuilder.add_view(
ClusterModelView,
"Druid Clusters",
icon="fa-server",
category="Admin",
category_icon='fa-cogs',)
class DatabaseView(ModelView, DeleteMixin):
datamodel = SQLAInterface(models.Database)
list_columns = ['database_name']
add_columns = ['database_name', 'sqlalchemy_uri']
edit_columns = add_columns
appbuilder.add_view(
DatabaseView,
"Databases",
icon="fa-database",
category="Admin",
category_icon='fa-cogs',)
class TableView(ModelView, DeleteMixin):
datamodel = SQLAInterface(models.Table)
list_columns = ['table_link', 'database']
add_columns = ['table_name', 'database', 'default_endpoint']
edit_columns = ['table_name', 'database', 'main_datetime_column', 'default_endpoint']
related_views = [TableColumnInlineView, SqlMetricInlineView]
def post_add(self, table):
table.fetch_metadata()
def post_update(self, table):
table.fetch_metadata()
appbuilder.add_view(
TableView,
"Tables",
icon='fa-table',)
class DatasourceModelView(ModelView, DeleteMixin):
datamodel = SQLAInterface(models.Datasource)
list_columns = [
'datasource_link', 'cluster', 'owner', 'is_featured', 'is_hidden']
related_views = [ColumnInlineView, MetricInlineView]
edit_columns = [
'datasource_name', 'cluster', 'description', 'owner',
'is_featured', 'is_hidden', 'default_endpoint']
page_size = 100
base_order = ('datasource_name', 'asc')
def post_add(self, datasource):
datasource.generate_metrics()
def post_update(self, datasource):
datasource.generate_metrics()
appbuilder.add_view(
DatasourceModelView,
"Druid Datasources",
icon="fa-cube")
@app.route('/health')
def health():
return "OK"
@app.route('/ping')
def ping():
return "OK"
class Panoramix(BaseView):
@has_access
@expose("/table/<table_id>/")
def table(self, table_id):
table = (
db.session
.query(models.Table)
.filter_by(id=table_id)
.first()
)
viz_type = request.args.get("viz_type")
if not viz_type and table.default_endpoint:
return redirect(table.default_endpoint)
if not viz_type:
viz_type = "table"
obj = viz.viz_types[viz_type](
table,
form_data=request.args, view=self)
if request.args.get("json"):
return Response(
json.dumps(obj.get_query(), indent=4),
status=200,
mimetype="application/json")
if not hasattr(obj, 'df') or obj.df is None or obj.df.empty:
pass
#return obj.render_no_data()
return obj.render()
@has_access
@expose("/datasource/<datasource_name>/")
def datasource(self, datasource_name):
viz_type = request.args.get("viz_type")
datasource = (
db.session
.query(models.Datasource)
.filter_by(datasource_name=datasource_name)
.first()
)
if not viz_type and datasource.default_endpoint:
return redirect(datasource.default_endpoint)
if not viz_type:
viz_type = "table"
obj = viz.viz_types[viz_type](
datasource,
form_data=request.args, view=self)
if request.args.get("json"):
return Response(
json.dumps(obj.get_query(), indent=4),
status=200,
mimetype="application/json")
if not hasattr(obj, 'df') or obj.df is None or obj.df.empty:
return obj.render_no_data()
return obj.render()
@has_access
@expose("/refresh_datasources/")
def refresh_datasources(self):
session = db.session()
for cluster in session.query(models.Cluster).all():
cluster.refresh_datasources()
cluster.metadata_last_refreshed = datetime.now()
flash(
"Refreshed metadata from cluster "
"[" + cluster.cluster_name + "]",
'info')
session.commit()
return redirect("/datasourcemodelview/list/")
@expose("/autocomplete/<datasource>/<column>/")
def autocomplete(self, datasource, column):
client = utils.get_pydruid_client()
top = client.topn(
datasource=datasource,
granularity='all',
intervals='2013-10-04/2020-10-10',
aggregations={"count": doublesum("count")},
dimension=column,
metric='count',
threshold=1000,
)
values = sorted([d[column] for d in top[0]['result']])
return json.dumps(values)
appbuilder.add_view_no_menu(Panoramix)
appbuilder.add_link(
"Refresh Druid Metadata",
href='/panoramix/refresh_datasources/',
category='Admin',
category_icon='fa-cogs',
icon="fa-cog")
#models.Metric.__table__.drop(db.engine)
db.create_all()
| panoramix/views.py | 1 | https://github.com/apache/superset/commit/6dd81a3e95a9d67be743815ff9bfcd465278b3e9 | [
0.006208558101207018,
0.0005773159791715443,
0.00016560348740313202,
0.00017146424215752631,
0.0012340393150225282
] |
{
"id": 1,
"code_window": [
"\n",
"\n",
"if __name__ == \"__main__\":\n",
" if config.DEBUG:\n",
" app.run(\n",
" host='0.0.0.0',\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep"
],
"after_edit": [
" parser = argparse.ArgumentParser(\n",
" description='Start a Panoramix web server')\n",
" parser.add_argument(\n",
" '-d', '--debug', action='store_true',\n",
" help=\"Start the web server in debug mode\")\n",
" parser.add_argument(\n",
" '-p', '--port', default=config.PANORAMIX_WEBSERVER_PORT,\n",
" help=\"Specify the port on which to run the web server\")\n",
" args = parser.parse_args()\n",
" args.debug = args.debug or config.DEBUG\n",
" if args.debug:\n"
],
"file_path": "panoramix/bin/panoramix",
"type": "replace",
"edit_start_line_idx": 6
} | .select2-container{box-sizing:border-box;display:inline-block;margin:0;position:relative;vertical-align:middle;}.select2-container .select2-selection--single{box-sizing:border-box;cursor:pointer;display:block;height:28px;user-select:none;-webkit-user-select:none;}.select2-container .select2-selection--single .select2-selection__rendered{display:block;padding-left:8px;padding-right:20px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;}.select2-container[dir="rtl"] .select2-selection--single .select2-selection__rendered{padding-right:8px;padding-left:20px;}.select2-container .select2-selection--multiple{box-sizing:border-box;cursor:pointer;display:block;min-height:32px;user-select:none;-webkit-user-select:none;}.select2-container .select2-selection--multiple .select2-selection__rendered{display:inline-block;overflow:hidden;padding-left:8px;text-overflow:ellipsis;white-space:nowrap;}.select2-container .select2-search--inline{float:left;}.select2-container .select2-search--inline .select2-search__field{box-sizing:border-box;border:none;font-size:100%;margin-top:5px;}.select2-container .select2-search--inline .select2-search__field::-webkit-search-cancel-button{-webkit-appearance:none;}.select2-dropdown{background-color:white;border:1px solid #aaa;border-radius:4px;box-sizing:border-box;display:block;position:absolute;left:-100000px;width:100%;z-index:1051;}.select2-results{display:block;}.select2-results__options{list-style:none;margin:0;padding:0;}.select2-results__option{padding:6px;user-select:none;-webkit-user-select:none;}.select2-results__option[aria-selected]{cursor:pointer;}.select2-container--open .select2-dropdown{left:0;}.select2-container--open .select2-dropdown--above{border-bottom:none;border-bottom-left-radius:0;border-bottom-right-radius:0;}.select2-container--open .select2-dropdown--below{border-top:none;border-top-left-radius:0;border-top-right-radius:0;}.select2-search--dropdown{display:block;padding:4px;}.select2-search--dropdown .select2-search__field{padding:4px;width:100%;box-sizing:border-box;}.select2-search--dropdown .select2-search__field::-webkit-search-cancel-button{-webkit-appearance:none;}.select2-search--dropdown.select2-search--hide{display:none;}.select2-close-mask{border:0;margin:0;padding:0;display:block;position:fixed;left:0;top:0;min-height:100%;min-width:100%;height:auto;width:auto;opacity:0;z-index:99;background-color:#fff;filter:alpha(opacity=0);}.select2-hidden-accessible{border:0;clip:rect(0 0 0 0);height:1px;margin:-1px;overflow:hidden;padding:0;position:absolute;width:1px;}.select2-container--default .select2-selection--single{background-color:#fff;border:1px solid #aaa;border-radius:4px;}.select2-container--default .select2-selection--single .select2-selection__rendered{color:#444;line-height:28px;}.select2-container--default .select2-selection--single .select2-selection__clear{cursor:pointer;float:right;font-weight:bold;}.select2-container--default .select2-selection--single .select2-selection__placeholder{color:#999;}.select2-container--default .select2-selection--single .select2-selection__arrow{height:26px;position:absolute;top:1px;right:1px;width:20px;}.select2-container--default .select2-selection--single .select2-selection__arrow b{border-color:#888 transparent transparent transparent;border-style:solid;border-width:5px 4px 0 4px;height:0;left:50%;margin-left:-4px;margin-top:-2px;position:absolute;top:50%;width:0;}.select2-container--default[dir="rtl"] .select2-selection--single .select2-selection__clear{float:left;}.select2-container--default[dir="rtl"] .select2-selection--single .select2-selection__arrow{left:1px;right:auto;}.select2-container--default.select2-container--disabled .select2-selection--single{background-color:#eee;cursor:default;}.select2-container--default.select2-container--disabled .select2-selection--single .select2-selection__clear{display:none;}.select2-container--default.select2-container--open .select2-selection--single .select2-selection__arrow b{border-color:transparent transparent #888 transparent;border-width:0 4px 5px 4px;}.select2-container--default .select2-selection--multiple{background-color:white;border:1px solid #aaa;border-radius:4px;cursor:text;}.select2-container--default .select2-selection--multiple .select2-selection__rendered{box-sizing:border-box;list-style:none;margin:0;padding:0 5px;width:100%;}.select2-container--default .select2-selection--multiple .select2-selection__placeholder{color:#999;margin-top:5px;float:left;}.select2-container--default .select2-selection--multiple .select2-selection__clear{cursor:pointer;float:right;font-weight:bold;margin-top:5px;margin-right:10px;}.select2-container--default .select2-selection--multiple .select2-selection__choice{background-color:#e4e4e4;border:1px solid #aaa;border-radius:4px;cursor:default;float:left;margin-right:5px;margin-top:5px;padding:0 5px;}.select2-container--default .select2-selection--multiple .select2-selection__choice__remove{color:#999;cursor:pointer;display:inline-block;font-weight:bold;margin-right:2px;}.select2-container--default .select2-selection--multiple .select2-selection__choice__remove:hover{color:#333;}.select2-container--default[dir="rtl"] .select2-selection--multiple .select2-selection__choice,.select2-container--default[dir="rtl"] .select2-selection--multiple .select2-selection__placeholder{float:right;}.select2-container--default[dir="rtl"] .select2-selection--multiple .select2-selection__choice{margin-left:5px;margin-right:auto;}.select2-container--default[dir="rtl"] .select2-selection--multiple .select2-selection__choice__remove{margin-left:2px;margin-right:auto;}.select2-container--default.select2-container--focus .select2-selection--multiple{border:solid black 1px;outline:0;}.select2-container--default.select2-container--disabled .select2-selection--multiple{background-color:#eee;cursor:default;}.select2-container--default.select2-container--disabled .select2-selection__choice__remove{display:none;}.select2-container--default.select2-container--open.select2-container--above .select2-selection--single,.select2-container--default.select2-container--open.select2-container--above .select2-selection--multiple{border-top-left-radius:0;border-top-right-radius:0;}.select2-container--default.select2-container--open.select2-container--below .select2-selection--single,.select2-container--default.select2-container--open.select2-container--below .select2-selection--multiple{border-bottom-left-radius:0;border-bottom-right-radius:0;}.select2-container--default .select2-search--dropdown .select2-search__field{border:1px solid #aaa;}.select2-container--default .select2-search--inline .select2-search__field{background:transparent;border:none;outline:0;}.select2-container--default .select2-results>.select2-results__options{max-height:200px;overflow-y:auto;}.select2-container--default .select2-results__option[role=group]{padding:0;}.select2-container--default .select2-results__option[aria-disabled=true]{color:#999;}.select2-container--default .select2-results__option[aria-selected=true]{background-color:#ddd;}.select2-container--default .select2-results__option .select2-results__option{padding-left:1em;}.select2-container--default .select2-results__option .select2-results__option .select2-results__group{padding-left:0;}.select2-container--default .select2-results__option .select2-results__option .select2-results__option{margin-left:-1em;padding-left:2em;}.select2-container--default .select2-results__option .select2-results__option .select2-results__option .select2-results__option{margin-left:-2em;padding-left:3em;}.select2-container--default .select2-results__option .select2-results__option .select2-results__option .select2-results__option .select2-results__option{margin-left:-3em;padding-left:4em;}.select2-container--default .select2-results__option .select2-results__option .select2-results__option .select2-results__option .select2-results__option .select2-results__option{margin-left:-4em;padding-left:5em;}.select2-container--default .select2-results__option .select2-results__option .select2-results__option .select2-results__option .select2-results__option .select2-results__option .select2-results__option{margin-left:-5em;padding-left:6em;}.select2-container--default .select2-results__option--highlighted[aria-selected]{background-color:#5897fb;color:white;}.select2-container--default .select2-results__group{cursor:default;display:block;padding:6px;}.select2-container--classic .select2-selection--single{background-color:#f6f6f6;border:1px solid #aaa;border-radius:4px;outline:0;background-image:-webkit-linear-gradient(top, #ffffff 50%, #eeeeee 100%);background-image:-o-linear-gradient(top, #ffffff 50%, #eeeeee 100%);background-image:linear-gradient(to bottom, #ffffff 50%, #eeeeee 100%);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffff', endColorstr='#eeeeee', GradientType=0);}.select2-container--classic .select2-selection--single:focus{border:1px solid #5897fb;}.select2-container--classic .select2-selection--single .select2-selection__rendered{color:#444;line-height:28px;}.select2-container--classic .select2-selection--single .select2-selection__clear{cursor:pointer;float:right;font-weight:bold;margin-right:10px;}.select2-container--classic .select2-selection--single .select2-selection__placeholder{color:#999;}.select2-container--classic .select2-selection--single .select2-selection__arrow{background-color:#ddd;border:none;border-left:1px solid #aaa;border-top-right-radius:4px;border-bottom-right-radius:4px;height:26px;position:absolute;top:1px;right:1px;width:20px;background-image:-webkit-linear-gradient(top, #eeeeee 50%, #cccccc 100%);background-image:-o-linear-gradient(top, #eeeeee 50%, #cccccc 100%);background-image:linear-gradient(to bottom, #eeeeee 50%, #cccccc 100%);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#eeeeee', endColorstr='#cccccc', GradientType=0);}.select2-container--classic .select2-selection--single .select2-selection__arrow b{border-color:#888 transparent transparent transparent;border-style:solid;border-width:5px 4px 0 4px;height:0;left:50%;margin-left:-4px;margin-top:-2px;position:absolute;top:50%;width:0;}.select2-container--classic[dir="rtl"] .select2-selection--single .select2-selection__clear{float:left;}.select2-container--classic[dir="rtl"] .select2-selection--single .select2-selection__arrow{border:none;border-right:1px solid #aaa;border-radius:0;border-top-left-radius:4px;border-bottom-left-radius:4px;left:1px;right:auto;}.select2-container--classic.select2-container--open .select2-selection--single{border:1px solid #5897fb;}.select2-container--classic.select2-container--open .select2-selection--single .select2-selection__arrow{background:transparent;border:none;}.select2-container--classic.select2-container--open .select2-selection--single .select2-selection__arrow b{border-color:transparent transparent #888 transparent;border-width:0 4px 5px 4px;}.select2-container--classic.select2-container--open.select2-container--above .select2-selection--single{border-top:none;border-top-left-radius:0;border-top-right-radius:0;background-image:-webkit-linear-gradient(top, #ffffff 0%, #eeeeee 50%);background-image:-o-linear-gradient(top, #ffffff 0%, #eeeeee 50%);background-image:linear-gradient(to bottom, #ffffff 0%, #eeeeee 50%);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffff', endColorstr='#eeeeee', GradientType=0);}.select2-container--classic.select2-container--open.select2-container--below .select2-selection--single{border-bottom:none;border-bottom-left-radius:0;border-bottom-right-radius:0;background-image:-webkit-linear-gradient(top, #eeeeee 50%, #ffffff 100%);background-image:-o-linear-gradient(top, #eeeeee 50%, #ffffff 100%);background-image:linear-gradient(to bottom, #eeeeee 50%, #ffffff 100%);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#eeeeee', endColorstr='#ffffff', GradientType=0);}.select2-container--classic .select2-selection--multiple{background-color:white;border:1px solid #aaa;border-radius:4px;cursor:text;outline:0;}.select2-container--classic .select2-selection--multiple:focus{border:1px solid #5897fb;}.select2-container--classic .select2-selection--multiple .select2-selection__rendered{list-style:none;margin:0;padding:0 5px;}.select2-container--classic .select2-selection--multiple .select2-selection__clear{display:none;}.select2-container--classic .select2-selection--multiple .select2-selection__choice{background-color:#e4e4e4;border:1px solid #aaa;border-radius:4px;cursor:default;float:left;margin-right:5px;margin-top:5px;padding:0 5px;}.select2-container--classic .select2-selection--multiple .select2-selection__choice__remove{color:#888;cursor:pointer;display:inline-block;font-weight:bold;margin-right:2px;}.select2-container--classic .select2-selection--multiple .select2-selection__choice__remove:hover{color:#555;}.select2-container--classic[dir="rtl"] .select2-selection--multiple .select2-selection__choice{float:right;}.select2-container--classic[dir="rtl"] .select2-selection--multiple .select2-selection__choice{margin-left:5px;margin-right:auto;}.select2-container--classic[dir="rtl"] .select2-selection--multiple .select2-selection__choice__remove{margin-left:2px;margin-right:auto;}.select2-container--classic.select2-container--open .select2-selection--multiple{border:1px solid #5897fb;}.select2-container--classic.select2-container--open.select2-container--above .select2-selection--multiple{border-top:none;border-top-left-radius:0;border-top-right-radius:0;}.select2-container--classic.select2-container--open.select2-container--below .select2-selection--multiple{border-bottom:none;border-bottom-left-radius:0;border-bottom-right-radius:0;}.select2-container--classic .select2-search--dropdown .select2-search__field{border:1px solid #aaa;outline:0;}.select2-container--classic .select2-search--inline .select2-search__field{outline:0;}.select2-container--classic .select2-dropdown{background-color:white;border:1px solid transparent;}.select2-container--classic .select2-dropdown--above{border-bottom:none;}.select2-container--classic .select2-dropdown--below{border-top:none;}.select2-container--classic .select2-results>.select2-results__options{max-height:200px;overflow-y:auto;}.select2-container--classic .select2-results__option[role=group]{padding:0;}.select2-container--classic .select2-results__option[aria-disabled=true]{color:grey;}.select2-container--classic .select2-results__option--highlighted[aria-selected]{background-color:#3875d7;color:white;}.select2-container--classic .select2-results__group{cursor:default;display:block;padding:6px;}.select2-container--classic.select2-container--open .select2-dropdown{border-color:#5897fb;} | panoramix/static/select2.min.css | 0 | https://github.com/apache/superset/commit/6dd81a3e95a9d67be743815ff9bfcd465278b3e9 | [
0.00016419359599240124,
0.00016419359599240124,
0.00016419359599240124,
0.00016419359599240124,
0
] |
{
"id": 1,
"code_window": [
"\n",
"\n",
"if __name__ == \"__main__\":\n",
" if config.DEBUG:\n",
" app.run(\n",
" host='0.0.0.0',\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep"
],
"after_edit": [
" parser = argparse.ArgumentParser(\n",
" description='Start a Panoramix web server')\n",
" parser.add_argument(\n",
" '-d', '--debug', action='store_true',\n",
" help=\"Start the web server in debug mode\")\n",
" parser.add_argument(\n",
" '-p', '--port', default=config.PANORAMIX_WEBSERVER_PORT,\n",
" help=\"Specify the port on which to run the web server\")\n",
" args = parser.parse_args()\n",
" args.debug = args.debug or config.DEBUG\n",
" if args.debug:\n"
],
"file_path": "panoramix/bin/panoramix",
"type": "replace",
"edit_start_line_idx": 6
} | recursive-include panoramix/templates *
recursive-include panoramix/static *
| MANIFEST.in | 0 | https://github.com/apache/superset/commit/6dd81a3e95a9d67be743815ff9bfcd465278b3e9 | [
0.00016772661183495075,
0.00016772661183495075,
0.00016772661183495075,
0.00016772661183495075,
0
] |
{
"id": 1,
"code_window": [
"\n",
"\n",
"if __name__ == \"__main__\":\n",
" if config.DEBUG:\n",
" app.run(\n",
" host='0.0.0.0',\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep"
],
"after_edit": [
" parser = argparse.ArgumentParser(\n",
" description='Start a Panoramix web server')\n",
" parser.add_argument(\n",
" '-d', '--debug', action='store_true',\n",
" help=\"Start the web server in debug mode\")\n",
" parser.add_argument(\n",
" '-p', '--port', default=config.PANORAMIX_WEBSERVER_PORT,\n",
" help=\"Specify the port on which to run the web server\")\n",
" args = parser.parse_args()\n",
" args.debug = args.debug or config.DEBUG\n",
" if args.debug:\n"
],
"file_path": "panoramix/bin/panoramix",
"type": "replace",
"edit_start_line_idx": 6
} | table.dataTable{width:100%;margin:0 auto;clear:both;border-collapse:separate;border-spacing:0}table.dataTable thead th,table.dataTable tfoot th{font-weight:bold}table.dataTable thead th,table.dataTable thead td{padding:10px 18px;border-bottom:1px solid #111}table.dataTable thead th:active,table.dataTable thead td:active{outline:none}table.dataTable tfoot th,table.dataTable tfoot td{padding:10px 18px 6px 18px;border-top:1px solid #111}table.dataTable thead .sorting,table.dataTable thead .sorting_asc,table.dataTable thead .sorting_desc{cursor:pointer;*cursor:hand}table.dataTable thead .sorting,table.dataTable thead .sorting_asc,table.dataTable thead .sorting_desc,table.dataTable thead .sorting_asc_disabled,table.dataTable thead .sorting_desc_disabled{background-repeat:no-repeat;background-position:center right}table.dataTable thead .sorting{background-image:url("../images/sort_both.png")}table.dataTable thead .sorting_asc{background-image:url("../images/sort_asc.png")}table.dataTable thead .sorting_desc{background-image:url("../images/sort_desc.png")}table.dataTable thead .sorting_asc_disabled{background-image:url("../images/sort_asc_disabled.png")}table.dataTable thead .sorting_desc_disabled{background-image:url("../images/sort_desc_disabled.png")}table.dataTable tbody tr{background-color:#fff}table.dataTable tbody tr.selected{background-color:#B0BED9}table.dataTable tbody th,table.dataTable tbody td{padding:8px 10px}table.dataTable.row-border tbody th,table.dataTable.row-border tbody td,table.dataTable.display tbody th,table.dataTable.display tbody td{border-top:1px solid #ddd}table.dataTable.row-border tbody tr:first-child th,table.dataTable.row-border tbody tr:first-child td,table.dataTable.display tbody tr:first-child th,table.dataTable.display tbody tr:first-child td{border-top:none}table.dataTable.cell-border tbody th,table.dataTable.cell-border tbody td{border-top:1px solid #ddd;border-right:1px solid #ddd}table.dataTable.cell-border tbody tr th:first-child,table.dataTable.cell-border tbody tr td:first-child{border-left:1px solid #ddd}table.dataTable.cell-border tbody tr:first-child th,table.dataTable.cell-border tbody tr:first-child td{border-top:none}table.dataTable.stripe tbody tr.odd,table.dataTable.display tbody tr.odd{background-color:#f9f9f9}table.dataTable.stripe tbody tr.odd.selected,table.dataTable.display tbody tr.odd.selected{background-color:#abb9d3}table.dataTable.hover tbody tr:hover,table.dataTable.display tbody tr:hover{background-color:#f5f5f5}table.dataTable.hover tbody tr:hover.selected,table.dataTable.display tbody tr:hover.selected{background-color:#a9b7d1}table.dataTable.order-column tbody tr>.sorting_1,table.dataTable.order-column tbody tr>.sorting_2,table.dataTable.order-column tbody tr>.sorting_3,table.dataTable.display tbody tr>.sorting_1,table.dataTable.display tbody tr>.sorting_2,table.dataTable.display tbody tr>.sorting_3{background-color:#f9f9f9}table.dataTable.order-column tbody tr.selected>.sorting_1,table.dataTable.order-column tbody tr.selected>.sorting_2,table.dataTable.order-column tbody tr.selected>.sorting_3,table.dataTable.display tbody tr.selected>.sorting_1,table.dataTable.display tbody tr.selected>.sorting_2,table.dataTable.display tbody tr.selected>.sorting_3{background-color:#acbad4}table.dataTable.display tbody tr.odd>.sorting_1,table.dataTable.order-column.stripe tbody tr.odd>.sorting_1{background-color:#f1f1f1}table.dataTable.display tbody tr.odd>.sorting_2,table.dataTable.order-column.stripe tbody tr.odd>.sorting_2{background-color:#f3f3f3}table.dataTable.display tbody tr.odd>.sorting_3,table.dataTable.order-column.stripe tbody tr.odd>.sorting_3{background-color:#f5f5f5}table.dataTable.display tbody tr.odd.selected>.sorting_1,table.dataTable.order-column.stripe tbody tr.odd.selected>.sorting_1{background-color:#a6b3cd}table.dataTable.display tbody tr.odd.selected>.sorting_2,table.dataTable.order-column.stripe tbody tr.odd.selected>.sorting_2{background-color:#a7b5ce}table.dataTable.display tbody tr.odd.selected>.sorting_3,table.dataTable.order-column.stripe tbody tr.odd.selected>.sorting_3{background-color:#a9b6d0}table.dataTable.display tbody tr.even>.sorting_1,table.dataTable.order-column.stripe tbody tr.even>.sorting_1{background-color:#f9f9f9}table.dataTable.display tbody tr.even>.sorting_2,table.dataTable.order-column.stripe tbody tr.even>.sorting_2{background-color:#fbfbfb}table.dataTable.display tbody tr.even>.sorting_3,table.dataTable.order-column.stripe tbody tr.even>.sorting_3{background-color:#fdfdfd}table.dataTable.display tbody tr.even.selected>.sorting_1,table.dataTable.order-column.stripe tbody tr.even.selected>.sorting_1{background-color:#acbad4}table.dataTable.display tbody tr.even.selected>.sorting_2,table.dataTable.order-column.stripe tbody tr.even.selected>.sorting_2{background-color:#adbbd6}table.dataTable.display tbody tr.even.selected>.sorting_3,table.dataTable.order-column.stripe tbody tr.even.selected>.sorting_3{background-color:#afbdd8}table.dataTable.display tbody tr:hover>.sorting_1,table.dataTable.order-column.hover tbody tr:hover>.sorting_1{background-color:#eaeaea}table.dataTable.display tbody tr:hover>.sorting_2,table.dataTable.order-column.hover tbody tr:hover>.sorting_2{background-color:#ebebeb}table.dataTable.display tbody tr:hover>.sorting_3,table.dataTable.order-column.hover tbody tr:hover>.sorting_3{background-color:#eee}table.dataTable.display tbody tr:hover.selected>.sorting_1,table.dataTable.order-column.hover tbody tr:hover.selected>.sorting_1{background-color:#a1aec7}table.dataTable.display tbody tr:hover.selected>.sorting_2,table.dataTable.order-column.hover tbody tr:hover.selected>.sorting_2{background-color:#a2afc8}table.dataTable.display tbody tr:hover.selected>.sorting_3,table.dataTable.order-column.hover tbody tr:hover.selected>.sorting_3{background-color:#a4b2cb}table.dataTable.no-footer{border-bottom:1px solid #111}table.dataTable.nowrap th,table.dataTable.nowrap td{white-space:nowrap}table.dataTable.compact thead th,table.dataTable.compact thead td{padding:4px 17px 4px 4px}table.dataTable.compact tfoot th,table.dataTable.compact tfoot td{padding:4px}table.dataTable.compact tbody th,table.dataTable.compact tbody td{padding:4px}table.dataTable th.dt-left,table.dataTable td.dt-left{text-align:left}table.dataTable th.dt-center,table.dataTable td.dt-center,table.dataTable td.dataTables_empty{text-align:center}table.dataTable th.dt-right,table.dataTable td.dt-right{text-align:right}table.dataTable th.dt-justify,table.dataTable td.dt-justify{text-align:justify}table.dataTable th.dt-nowrap,table.dataTable td.dt-nowrap{white-space:nowrap}table.dataTable thead th.dt-head-left,table.dataTable thead td.dt-head-left,table.dataTable tfoot th.dt-head-left,table.dataTable tfoot td.dt-head-left{text-align:left}table.dataTable thead th.dt-head-center,table.dataTable thead td.dt-head-center,table.dataTable tfoot th.dt-head-center,table.dataTable tfoot td.dt-head-center{text-align:center}table.dataTable thead th.dt-head-right,table.dataTable thead td.dt-head-right,table.dataTable tfoot th.dt-head-right,table.dataTable tfoot td.dt-head-right{text-align:right}table.dataTable thead th.dt-head-justify,table.dataTable thead td.dt-head-justify,table.dataTable tfoot th.dt-head-justify,table.dataTable tfoot td.dt-head-justify{text-align:justify}table.dataTable thead th.dt-head-nowrap,table.dataTable thead td.dt-head-nowrap,table.dataTable tfoot th.dt-head-nowrap,table.dataTable tfoot td.dt-head-nowrap{white-space:nowrap}table.dataTable tbody th.dt-body-left,table.dataTable tbody td.dt-body-left{text-align:left}table.dataTable tbody th.dt-body-center,table.dataTable tbody td.dt-body-center{text-align:center}table.dataTable tbody th.dt-body-right,table.dataTable tbody td.dt-body-right{text-align:right}table.dataTable tbody th.dt-body-justify,table.dataTable tbody td.dt-body-justify{text-align:justify}table.dataTable tbody th.dt-body-nowrap,table.dataTable tbody td.dt-body-nowrap{white-space:nowrap}table.dataTable,table.dataTable th,table.dataTable td{-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box}.dataTables_wrapper{position:relative;clear:both;*zoom:1;zoom:1}.dataTables_wrapper .dataTables_length{float:left}.dataTables_wrapper .dataTables_filter{float:right;text-align:right}.dataTables_wrapper .dataTables_filter input{margin-left:0.5em}.dataTables_wrapper .dataTables_info{clear:both;float:left;padding-top:0.755em}.dataTables_wrapper .dataTables_paginate{float:right;text-align:right;padding-top:0.25em}.dataTables_wrapper .dataTables_paginate .paginate_button{box-sizing:border-box;display:inline-block;min-width:1.5em;padding:0.5em 1em;margin-left:2px;text-align:center;text-decoration:none !important;cursor:pointer;*cursor:hand;color:#333 !important;border:1px solid transparent}.dataTables_wrapper .dataTables_paginate .paginate_button.current,.dataTables_wrapper .dataTables_paginate .paginate_button.current:hover{color:#333 !important;border:1px solid #cacaca;background-color:#fff;background:-webkit-gradient(linear, left top, left bottom, color-stop(0%, #fff), color-stop(100%, #dcdcdc));background:-webkit-linear-gradient(top, #fff 0%, #dcdcdc 100%);background:-moz-linear-gradient(top, #fff 0%, #dcdcdc 100%);background:-ms-linear-gradient(top, #fff 0%, #dcdcdc 100%);background:-o-linear-gradient(top, #fff 0%, #dcdcdc 100%);background:linear-gradient(to bottom, #fff 0%, #dcdcdc 100%)}.dataTables_wrapper .dataTables_paginate .paginate_button.disabled,.dataTables_wrapper .dataTables_paginate .paginate_button.disabled:hover,.dataTables_wrapper .dataTables_paginate .paginate_button.disabled:active{cursor:default;color:#666 !important;border:1px solid transparent;background:transparent;box-shadow:none}.dataTables_wrapper .dataTables_paginate .paginate_button:hover{color:white !important;border:1px solid #111;background-color:#585858;background:-webkit-gradient(linear, left top, left bottom, color-stop(0%, #585858), color-stop(100%, #111));background:-webkit-linear-gradient(top, #585858 0%, #111 100%);background:-moz-linear-gradient(top, #585858 0%, #111 100%);background:-ms-linear-gradient(top, #585858 0%, #111 100%);background:-o-linear-gradient(top, #585858 0%, #111 100%);background:linear-gradient(to bottom, #585858 0%, #111 100%)}.dataTables_wrapper .dataTables_paginate .paginate_button:active{outline:none;background-color:#2b2b2b;background:-webkit-gradient(linear, left top, left bottom, color-stop(0%, #2b2b2b), color-stop(100%, #0c0c0c));background:-webkit-linear-gradient(top, #2b2b2b 0%, #0c0c0c 100%);background:-moz-linear-gradient(top, #2b2b2b 0%, #0c0c0c 100%);background:-ms-linear-gradient(top, #2b2b2b 0%, #0c0c0c 100%);background:-o-linear-gradient(top, #2b2b2b 0%, #0c0c0c 100%);background:linear-gradient(to bottom, #2b2b2b 0%, #0c0c0c 100%);box-shadow:inset 0 0 3px #111}.dataTables_wrapper .dataTables_paginate .ellipsis{padding:0 1em}.dataTables_wrapper .dataTables_processing{position:absolute;top:50%;left:50%;width:100%;height:40px;margin-left:-50%;margin-top:-25px;padding-top:20px;text-align:center;font-size:1.2em;background-color:white;background:-webkit-gradient(linear, left top, right top, color-stop(0%, rgba(255,255,255,0)), color-stop(25%, rgba(255,255,255,0.9)), color-stop(75%, rgba(255,255,255,0.9)), color-stop(100%, rgba(255,255,255,0)));background:-webkit-linear-gradient(left, rgba(255,255,255,0) 0%, rgba(255,255,255,0.9) 25%, rgba(255,255,255,0.9) 75%, rgba(255,255,255,0) 100%);background:-moz-linear-gradient(left, rgba(255,255,255,0) 0%, rgba(255,255,255,0.9) 25%, rgba(255,255,255,0.9) 75%, rgba(255,255,255,0) 100%);background:-ms-linear-gradient(left, rgba(255,255,255,0) 0%, rgba(255,255,255,0.9) 25%, rgba(255,255,255,0.9) 75%, rgba(255,255,255,0) 100%);background:-o-linear-gradient(left, rgba(255,255,255,0) 0%, rgba(255,255,255,0.9) 25%, rgba(255,255,255,0.9) 75%, rgba(255,255,255,0) 100%);background:linear-gradient(to right, rgba(255,255,255,0) 0%, rgba(255,255,255,0.9) 25%, rgba(255,255,255,0.9) 75%, rgba(255,255,255,0) 100%)}.dataTables_wrapper .dataTables_length,.dataTables_wrapper .dataTables_filter,.dataTables_wrapper .dataTables_info,.dataTables_wrapper .dataTables_processing,.dataTables_wrapper .dataTables_paginate{color:#333}.dataTables_wrapper .dataTables_scroll{clear:both}.dataTables_wrapper .dataTables_scroll div.dataTables_scrollBody{*margin-top:-1px;-webkit-overflow-scrolling:touch}.dataTables_wrapper .dataTables_scroll div.dataTables_scrollBody th>div.dataTables_sizing,.dataTables_wrapper .dataTables_scroll div.dataTables_scrollBody td>div.dataTables_sizing{height:0;overflow:hidden;margin:0 !important;padding:0 !important}.dataTables_wrapper.no-footer .dataTables_scrollBody{border-bottom:1px solid #111}.dataTables_wrapper.no-footer div.dataTables_scrollHead table,.dataTables_wrapper.no-footer div.dataTables_scrollBody table{border-bottom:none}.dataTables_wrapper:after{visibility:hidden;display:block;content:"";clear:both;height:0}@media screen and (max-width: 767px){.dataTables_wrapper .dataTables_info,.dataTables_wrapper .dataTables_paginate{float:none;text-align:center}.dataTables_wrapper .dataTables_paginate{margin-top:0.5em}}@media screen and (max-width: 640px){.dataTables_wrapper .dataTables_length,.dataTables_wrapper .dataTables_filter{float:none;text-align:center}.dataTables_wrapper .dataTables_filter{margin-top:0.5em}}
| panoramix/static/jquery.dataTables.min.css | 0 | https://github.com/apache/superset/commit/6dd81a3e95a9d67be743815ff9bfcd465278b3e9 | [
0.00016680698900017887,
0.00016680698900017887,
0.00016680698900017887,
0.00016680698900017887,
0
] |
{
"id": 2,
"code_window": [
" app.run(\n",
" host='0.0.0.0',\n",
" port=int(config.PANORAMIX_WEBSERVER_PORT),\n",
" debug=True)\n",
" else:\n",
" cmd = (\n"
],
"labels": [
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" port=int(args.port),\n"
],
"file_path": "panoramix/bin/panoramix",
"type": "replace",
"edit_start_line_idx": 9
} | #!/usr/bin/env python
from panoramix import app, config
from subprocess import Popen
if __name__ == "__main__":
if config.DEBUG:
app.run(
host='0.0.0.0',
port=int(config.PANORAMIX_WEBSERVER_PORT),
debug=True)
else:
cmd = (
"gunicorn "
"-w 8 "
"-b 0.0.0.0:{config.PANORAMIX_WEBSERVER_PORT} "
"panoramix:app").format(**locals())
print("Starting server with command: " + cmd)
Popen(cmd, shell=True).wait()
| panoramix/bin/panoramix | 1 | https://github.com/apache/superset/commit/6dd81a3e95a9d67be743815ff9bfcd465278b3e9 | [
0.9954336285591125,
0.9442424774169922,
0.893051266670227,
0.9442424774169922,
0.05119118094444275
] |
{
"id": 2,
"code_window": [
" app.run(\n",
" host='0.0.0.0',\n",
" port=int(config.PANORAMIX_WEBSERVER_PORT),\n",
" debug=True)\n",
" else:\n",
" cmd = (\n"
],
"labels": [
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" port=int(args.port),\n"
],
"file_path": "panoramix/bin/panoramix",
"type": "replace",
"edit_start_line_idx": 9
} | # TODO
* in/notin filters autocomplete
* DRUID: Allow for post aggregations (ratios!)
* compare time ranges
* csv export out of table view
* Save / bookmark / url shortener
* SQL: Find a way to manage granularity
* Create ~/.panoramix/ to host DB and config, generate default config there
| TODO.md | 0 | https://github.com/apache/superset/commit/6dd81a3e95a9d67be743815ff9bfcd465278b3e9 | [
0.00033563157194294035,
0.00033563157194294035,
0.00033563157194294035,
0.00033563157194294035,
0
] |
{
"id": 2,
"code_window": [
" app.run(\n",
" host='0.0.0.0',\n",
" port=int(config.PANORAMIX_WEBSERVER_PORT),\n",
" debug=True)\n",
" else:\n",
" cmd = (\n"
],
"labels": [
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" port=int(args.port),\n"
],
"file_path": "panoramix/bin/panoramix",
"type": "replace",
"edit_start_line_idx": 9
} | {% extends "appbuilder/base.html" %}
{% block content %}
<div class="container">
<div class="jumbotron">
<h1>Panoramix</h1>
<p>Panoramix is an interactive visualization platform built on top of Druid.io</p>
</div>
<div class="text-center">
<img width="250" src="/static/tux_panoramix.png">
</div>
</div>
{% endblock %}
| panoramix/templates/index.html | 0 | https://github.com/apache/superset/commit/6dd81a3e95a9d67be743815ff9bfcd465278b3e9 | [
0.0001680523855611682,
0.0001671447535045445,
0.00016623710689600557,
0.0001671447535045445,
9.076393325813115e-7
] |
{
"id": 2,
"code_window": [
" app.run(\n",
" host='0.0.0.0',\n",
" port=int(config.PANORAMIX_WEBSERVER_PORT),\n",
" debug=True)\n",
" else:\n",
" cmd = (\n"
],
"labels": [
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" port=int(args.port),\n"
],
"file_path": "panoramix/bin/panoramix",
"type": "replace",
"edit_start_line_idx": 9
} | div.dataTables_length label {
font-weight: normal;
text-align: left;
white-space: nowrap;
}
div.dataTables_length select {
width: 75px;
display: inline-block;
}
div.dataTables_filter {
text-align: right;
}
div.dataTables_filter label {
font-weight: normal;
white-space: nowrap;
text-align: left;
}
div.dataTables_filter input {
margin-left: 0.5em;
display: inline-block;
width: auto;
}
div.dataTables_info {
padding-top: 8px;
white-space: nowrap;
}
div.dataTables_paginate {
margin: 0;
white-space: nowrap;
text-align: right;
}
div.dataTables_paginate ul.pagination {
margin: 2px 0;
white-space: nowrap;
}
@media screen and (max-width: 767px) {
div.dataTables_wrapper > div.row > div,
div.dataTables_length,
div.dataTables_filter,
div.dataTables_info,
div.dataTables_paginate {
text-align: center;
}
div.DTTT {
margin-bottom: 0.5em;
}
}
table.dataTable td,
table.dataTable th {
-webkit-box-sizing: content-box;
-moz-box-sizing: content-box;
box-sizing: content-box;
}
table.dataTable {
clear: both;
margin-top: 6px !important;
margin-bottom: 6px !important;
max-width: none !important;
}
table.dataTable thead .sorting,
table.dataTable thead .sorting_asc,
table.dataTable thead .sorting_desc,
table.dataTable thead .sorting_asc_disabled,
table.dataTable thead .sorting_desc_disabled {
cursor: pointer;
position: relative;
}
table.dataTable thead .sorting:after,
table.dataTable thead .sorting_asc:after,
table.dataTable thead .sorting_desc:after {
position: absolute;
top: 8px;
right: 8px;
display: block;
font-family: 'Glyphicons Halflings';
opacity: 0.5;
}
table.dataTable thead .sorting:after {
opacity: 0.2;
content: "\e150"; /* sort */
}
table.dataTable thead .sorting_asc:after {
content: "\e155"; /* sort-by-attributes */
}
table.dataTable thead .sorting_desc:after {
content: "\e156"; /* sort-by-attributes-alt */
}
div.dataTables_scrollBody table.dataTable thead .sorting:after,
div.dataTables_scrollBody table.dataTable thead .sorting_asc:after,
div.dataTables_scrollBody table.dataTable thead .sorting_desc:after {
display: none;
}
table.dataTable thead .sorting_asc_disabled:after,
table.dataTable thead .sorting_desc_disabled:after {
color: #eee;
}
table.dataTable thead > tr > th {
padding-right: 30px;
}
table.dataTable th:active {
outline: none;
}
/* Condensed */
table.dataTable.table-condensed thead > tr > th {
padding-right: 20px;
}
table.dataTable.table-condensed thead .sorting:after,
table.dataTable.table-condensed thead .sorting_asc:after,
table.dataTable.table-condensed thead .sorting_desc:after {
top: 6px;
right: 6px;
}
/* Scrolling */
div.dataTables_scrollHead table {
margin-bottom: 0 !important;
border-bottom-left-radius: 0;
border-bottom-right-radius: 0;
}
div.dataTables_scrollHead table thead tr:last-child th:first-child,
div.dataTables_scrollHead table thead tr:last-child td:first-child {
border-bottom-left-radius: 0 !important;
border-bottom-right-radius: 0 !important;
}
div.dataTables_scrollBody table {
border-top: none;
margin-top: 0 !important;
margin-bottom: 0 !important;
}
div.dataTables_scrollBody tbody tr:first-child th,
div.dataTables_scrollBody tbody tr:first-child td {
border-top: none;
}
div.dataTables_scrollFoot table {
margin-top: 0 !important;
border-top: none;
}
/* Frustratingly the border-collapse:collapse used by Bootstrap makes the column
width calculations when using scrolling impossible to align columns. We have
to use separate
*/
table.table-bordered.dataTable {
border-collapse: separate !important;
}
table.table-bordered thead th,
table.table-bordered thead td {
border-left-width: 0;
border-top-width: 0;
}
table.table-bordered tbody th,
table.table-bordered tbody td {
border-left-width: 0;
border-bottom-width: 0;
}
table.table-bordered tfoot th,
table.table-bordered tfoot td {
border-left-width: 0;
border-bottom-width: 0;
}
table.table-bordered th:last-child,
table.table-bordered td:last-child {
border-right-width: 0;
}
div.dataTables_scrollHead table.table-bordered {
border-bottom-width: 0;
}
/*
* TableTools styles
*/
.table.dataTable tbody tr.active td,
.table.dataTable tbody tr.active th {
background-color: #08C;
color: white;
}
.table.dataTable tbody tr.active:hover td,
.table.dataTable tbody tr.active:hover th {
background-color: #0075b0 !important;
}
.table.dataTable tbody tr.active th > a,
.table.dataTable tbody tr.active td > a {
color: white;
}
.table-striped.dataTable tbody tr.active:nth-child(odd) td,
.table-striped.dataTable tbody tr.active:nth-child(odd) th {
background-color: #017ebc;
}
table.DTTT_selectable tbody tr {
cursor: pointer;
}
div.DTTT .btn:hover {
text-decoration: none !important;
}
ul.DTTT_dropdown.dropdown-menu {
z-index: 2003;
}
ul.DTTT_dropdown.dropdown-menu a {
color: #333 !important; /* needed only when demo_page.css is included */
}
ul.DTTT_dropdown.dropdown-menu li {
position: relative;
}
ul.DTTT_dropdown.dropdown-menu li:hover a {
background-color: #0088cc;
color: white !important;
}
div.DTTT_collection_background {
z-index: 2002;
}
/* TableTools information display */
div.DTTT_print_info {
position: fixed;
top: 50%;
left: 50%;
width: 400px;
height: 150px;
margin-left: -200px;
margin-top: -75px;
text-align: center;
color: #333;
padding: 10px 30px;
opacity: 0.95;
background-color: white;
border: 1px solid rgba(0, 0, 0, 0.2);
border-radius: 6px;
-webkit-box-shadow: 0 3px 7px rgba(0, 0, 0, 0.5);
box-shadow: 0 3px 7px rgba(0, 0, 0, 0.5);
}
div.DTTT_print_info h6 {
font-weight: normal;
font-size: 28px;
line-height: 28px;
margin: 1em;
}
div.DTTT_print_info p {
font-size: 14px;
line-height: 20px;
}
div.dataTables_processing {
position: absolute;
top: 50%;
left: 50%;
width: 100%;
height: 60px;
margin-left: -50%;
margin-top: -25px;
padding-top: 20px;
padding-bottom: 20px;
text-align: center;
font-size: 1.2em;
background-color: white;
background: -webkit-gradient(linear, left top, right top, color-stop(0%, rgba(255,255,255,0)), color-stop(25%, rgba(255,255,255,0.9)), color-stop(75%, rgba(255,255,255,0.9)), color-stop(100%, rgba(255,255,255,0)));
background: -webkit-linear-gradient(left, rgba(255,255,255,0) 0%, rgba(255,255,255,0.9) 25%, rgba(255,255,255,0.9) 75%, rgba(255,255,255,0) 100%);
background: -moz-linear-gradient(left, rgba(255,255,255,0) 0%, rgba(255,255,255,0.9) 25%, rgba(255,255,255,0.9) 75%, rgba(255,255,255,0) 100%);
background: -ms-linear-gradient(left, rgba(255,255,255,0) 0%, rgba(255,255,255,0.9) 25%, rgba(255,255,255,0.9) 75%, rgba(255,255,255,0) 100%);
background: -o-linear-gradient(left, rgba(255,255,255,0) 0%, rgba(255,255,255,0.9) 25%, rgba(255,255,255,0.9) 75%, rgba(255,255,255,0) 100%);
background: linear-gradient(to right, rgba(255,255,255,0) 0%, rgba(255,255,255,0.9) 25%, rgba(255,255,255,0.9) 75%, rgba(255,255,255,0) 100%);
}
/*
* FixedColumns styles
*/
div.DTFC_LeftHeadWrapper table,
div.DTFC_LeftFootWrapper table,
div.DTFC_RightHeadWrapper table,
div.DTFC_RightFootWrapper table,
table.DTFC_Cloned tr.even {
background-color: white;
margin-bottom: 0;
}
div.DTFC_RightHeadWrapper table ,
div.DTFC_LeftHeadWrapper table {
border-bottom: none !important;
margin-bottom: 0 !important;
border-top-right-radius: 0 !important;
border-bottom-left-radius: 0 !important;
border-bottom-right-radius: 0 !important;
}
div.DTFC_RightHeadWrapper table thead tr:last-child th:first-child,
div.DTFC_RightHeadWrapper table thead tr:last-child td:first-child,
div.DTFC_LeftHeadWrapper table thead tr:last-child th:first-child,
div.DTFC_LeftHeadWrapper table thead tr:last-child td:first-child {
border-bottom-left-radius: 0 !important;
border-bottom-right-radius: 0 !important;
}
div.DTFC_RightBodyWrapper table,
div.DTFC_LeftBodyWrapper table {
border-top: none;
margin: 0 !important;
}
div.DTFC_RightBodyWrapper tbody tr:first-child th,
div.DTFC_RightBodyWrapper tbody tr:first-child td,
div.DTFC_LeftBodyWrapper tbody tr:first-child th,
div.DTFC_LeftBodyWrapper tbody tr:first-child td {
border-top: none;
}
div.DTFC_RightFootWrapper table,
div.DTFC_LeftFootWrapper table {
border-top: none;
margin-top: 0 !important;
}
div.DTFC_LeftBodyWrapper table.dataTable thead .sorting:after,
div.DTFC_LeftBodyWrapper table.dataTable thead .sorting_asc:after,
div.DTFC_LeftBodyWrapper table.dataTable thead .sorting_desc:after,
div.DTFC_RightBodyWrapper table.dataTable thead .sorting:after,
div.DTFC_RightBodyWrapper table.dataTable thead .sorting_asc:after,
div.DTFC_RightBodyWrapper table.dataTable thead .sorting_desc:after {
display: none;
}
/*
* FixedHeader styles
*/
div.FixedHeader_Cloned table {
margin: 0 !important
}
| panoramix/static/dataTables.bootstrap.css | 0 | https://github.com/apache/superset/commit/6dd81a3e95a9d67be743815ff9bfcd465278b3e9 | [
0.000178021946339868,
0.00017196187400259078,
0.0001644351868890226,
0.00017170811770483851,
0.000003232857125112787
] |
{
"id": 3,
"code_window": [
" else:\n",
" cmd = (\n",
" \"gunicorn \"\n",
" \"-w 8 \"\n",
" \"-b 0.0.0.0:{config.PANORAMIX_WEBSERVER_PORT} \"\n",
" \"panoramix:app\").format(**locals())\n",
" print(\"Starting server with command: \" + cmd)\n",
" Popen(cmd, shell=True).wait()"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" \"-b 0.0.0.0:{args.port} \"\n"
],
"file_path": "panoramix/bin/panoramix",
"type": "replace",
"edit_start_line_idx": 15
} | #!/usr/bin/env python
from panoramix import app, config
from subprocess import Popen
if __name__ == "__main__":
if config.DEBUG:
app.run(
host='0.0.0.0',
port=int(config.PANORAMIX_WEBSERVER_PORT),
debug=True)
else:
cmd = (
"gunicorn "
"-w 8 "
"-b 0.0.0.0:{config.PANORAMIX_WEBSERVER_PORT} "
"panoramix:app").format(**locals())
print("Starting server with command: " + cmd)
Popen(cmd, shell=True).wait()
| panoramix/bin/panoramix | 1 | https://github.com/apache/superset/commit/6dd81a3e95a9d67be743815ff9bfcd465278b3e9 | [
0.998336911201477,
0.5029416084289551,
0.0075463163666427135,
0.5029416084289551,
0.495395302772522
] |
{
"id": 3,
"code_window": [
" else:\n",
" cmd = (\n",
" \"gunicorn \"\n",
" \"-w 8 \"\n",
" \"-b 0.0.0.0:{config.PANORAMIX_WEBSERVER_PORT} \"\n",
" \"panoramix:app\").format(**locals())\n",
" print(\"Starting server with command: \" + cmd)\n",
" Popen(cmd, shell=True).wait()"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" \"-b 0.0.0.0:{args.port} \"\n"
],
"file_path": "panoramix/bin/panoramix",
"type": "replace",
"edit_start_line_idx": 15
} | /*! DataTables Bootstrap 3 integration
* ©2011-2014 SpryMedia Ltd - datatables.net/license
*/
/**
* DataTables integration for Bootstrap 3. This requires Bootstrap 3 and
* DataTables 1.10 or newer.
*
* This file sets the defaults and adds options to DataTables to style its
* controls using Bootstrap. See http://datatables.net/manual/styling/bootstrap
* for further information.
*/
(function(window, document, undefined){
var factory = function( $, DataTable ) {
"use strict";
/* Set the defaults for DataTables initialisation */
$.extend( true, DataTable.defaults, {
dom:
"<'row'<'col-sm-6'l><'col-sm-6'f>>" +
"<'row'<'col-sm-12'tr>>" +
"<'row'<'col-sm-5'i><'col-sm-7'p>>",
renderer: 'bootstrap'
} );
/* Default class modification */
$.extend( DataTable.ext.classes, {
sWrapper: "dataTables_wrapper form-inline dt-bootstrap",
sFilterInput: "form-control input-sm",
sLengthSelect: "form-control input-sm"
} );
/* Bootstrap paging button renderer */
DataTable.ext.renderer.pageButton.bootstrap = function ( settings, host, idx, buttons, page, pages ) {
var api = new DataTable.Api( settings );
var classes = settings.oClasses;
var lang = settings.oLanguage.oPaginate;
var btnDisplay, btnClass, counter=0;
var attach = function( container, buttons ) {
var i, ien, node, button;
var clickHandler = function ( e ) {
e.preventDefault();
if ( !$(e.currentTarget).hasClass('disabled') ) {
api.page( e.data.action ).draw( false );
}
};
for ( i=0, ien=buttons.length ; i<ien ; i++ ) {
button = buttons[i];
if ( $.isArray( button ) ) {
attach( container, button );
}
else {
btnDisplay = '';
btnClass = '';
switch ( button ) {
case 'ellipsis':
btnDisplay = '…';
btnClass = 'disabled';
break;
case 'first':
btnDisplay = lang.sFirst;
btnClass = button + (page > 0 ?
'' : ' disabled');
break;
case 'previous':
btnDisplay = lang.sPrevious;
btnClass = button + (page > 0 ?
'' : ' disabled');
break;
case 'next':
btnDisplay = lang.sNext;
btnClass = button + (page < pages-1 ?
'' : ' disabled');
break;
case 'last':
btnDisplay = lang.sLast;
btnClass = button + (page < pages-1 ?
'' : ' disabled');
break;
default:
btnDisplay = button + 1;
btnClass = page === button ?
'active' : '';
break;
}
if ( btnDisplay ) {
node = $('<li>', {
'class': classes.sPageButton+' '+btnClass,
'id': idx === 0 && typeof button === 'string' ?
settings.sTableId +'_'+ button :
null
} )
.append( $('<a>', {
'href': '#',
'aria-controls': settings.sTableId,
'data-dt-idx': counter,
'tabindex': settings.iTabIndex
} )
.html( btnDisplay )
)
.appendTo( container );
settings.oApi._fnBindAction(
node, {action: button}, clickHandler
);
counter++;
}
}
}
};
// IE9 throws an 'unknown error' if document.activeElement is used
// inside an iframe or frame.
var activeEl;
try {
// Because this approach is destroying and recreating the paging
// elements, focus is lost on the select button which is bad for
// accessibility. So we want to restore focus once the draw has
// completed
activeEl = $(document.activeElement).data('dt-idx');
}
catch (e) {}
attach(
$(host).empty().html('<ul class="pagination"/>').children('ul'),
buttons
);
if ( activeEl ) {
$(host).find( '[data-dt-idx='+activeEl+']' ).focus();
}
};
/*
* TableTools Bootstrap compatibility
* Required TableTools 2.1+
*/
if ( DataTable.TableTools ) {
// Set the classes that TableTools uses to something suitable for Bootstrap
$.extend( true, DataTable.TableTools.classes, {
"container": "DTTT btn-group",
"buttons": {
"normal": "btn btn-default",
"disabled": "disabled"
},
"collection": {
"container": "DTTT_dropdown dropdown-menu",
"buttons": {
"normal": "",
"disabled": "disabled"
}
},
"print": {
"info": "DTTT_print_info"
},
"select": {
"row": "active"
}
} );
// Have the collection use a bootstrap compatible drop down
$.extend( true, DataTable.TableTools.DEFAULTS.oTags, {
"collection": {
"container": "ul",
"button": "li",
"liner": "a"
}
} );
}
}; // /factory
// Define as an AMD module if possible
if ( typeof define === 'function' && define.amd ) {
define( ['jquery', 'datatables'], factory );
}
else if ( typeof exports === 'object' ) {
// Node/CommonJS
factory( require('jquery'), require('datatables') );
}
else if ( jQuery ) {
// Otherwise simply initialise as normal, stopping multiple evaluation
factory( jQuery, jQuery.fn.dataTable );
}
})(window, document);
| panoramix/static/dataTables.bootstrap.js | 0 | https://github.com/apache/superset/commit/6dd81a3e95a9d67be743815ff9bfcd465278b3e9 | [
0.00017152212967630476,
0.00016685310401953757,
0.00016060154302977026,
0.0001667870965320617,
0.0000025064966848731274
] |
{
"id": 3,
"code_window": [
" else:\n",
" cmd = (\n",
" \"gunicorn \"\n",
" \"-w 8 \"\n",
" \"-b 0.0.0.0:{config.PANORAMIX_WEBSERVER_PORT} \"\n",
" \"panoramix:app\").format(**locals())\n",
" print(\"Starting server with command: \" + cmd)\n",
" Popen(cmd, shell=True).wait()"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" \"-b 0.0.0.0:{args.port} \"\n"
],
"file_path": "panoramix/bin/panoramix",
"type": "replace",
"edit_start_line_idx": 15
} | [python: **.py]
[jinja2: **/templates/**.html]
encoding = utf-8
| babel/babel.cfg | 0 | https://github.com/apache/superset/commit/6dd81a3e95a9d67be743815ff9bfcd465278b3e9 | [
0.00017085517174564302,
0.00017085517174564302,
0.00017085517174564302,
0.00017085517174564302,
0
] |
{
"id": 3,
"code_window": [
" else:\n",
" cmd = (\n",
" \"gunicorn \"\n",
" \"-w 8 \"\n",
" \"-b 0.0.0.0:{config.PANORAMIX_WEBSERVER_PORT} \"\n",
" \"panoramix:app\").format(**locals())\n",
" print(\"Starting server with command: \" + cmd)\n",
" Popen(cmd, shell=True).wait()"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" \"-b 0.0.0.0:{args.port} \"\n"
],
"file_path": "panoramix/bin/panoramix",
"type": "replace",
"edit_start_line_idx": 15
} | recursive-include panoramix/templates *
recursive-include panoramix/static *
| MANIFEST.in | 0 | https://github.com/apache/superset/commit/6dd81a3e95a9d67be743815ff9bfcd465278b3e9 | [
0.00018520595040172338,
0.00018520595040172338,
0.00018520595040172338,
0.00018520595040172338,
0
] |
{
"id": 4,
"code_window": [
" def __repr__(self):\n",
" return self.column_name\n",
"\n",
"class Cluster(Model, AuditMixin):\n",
" __tablename__ = 'clusters'\n",
" id = Column(Integer, primary_key=True)\n",
" cluster_name = Column(String(255), unique=True)\n",
" coordinator_host = Column(String(256))\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" @property\n",
" def isnum(self):\n",
" return self.type in ('LONG', 'DOUBLE', 'FLOAT')\n",
"\n"
],
"file_path": "panoramix/models.py",
"type": "add",
"edit_start_line_idx": 392
} | #!/usr/bin/env python
from panoramix import app, config
from subprocess import Popen
if __name__ == "__main__":
if config.DEBUG:
app.run(
host='0.0.0.0',
port=int(config.PANORAMIX_WEBSERVER_PORT),
debug=True)
else:
cmd = (
"gunicorn "
"-w 8 "
"-b 0.0.0.0:{config.PANORAMIX_WEBSERVER_PORT} "
"panoramix:app").format(**locals())
print("Starting server with command: " + cmd)
Popen(cmd, shell=True).wait()
| panoramix/bin/panoramix | 1 | https://github.com/apache/superset/commit/6dd81a3e95a9d67be743815ff9bfcd465278b3e9 | [
0.00016746197070460767,
0.00016656510706525296,
0.00016566824342589825,
0.00016656510706525296,
8.968636393547058e-7
] |
{
"id": 4,
"code_window": [
" def __repr__(self):\n",
" return self.column_name\n",
"\n",
"class Cluster(Model, AuditMixin):\n",
" __tablename__ = 'clusters'\n",
" id = Column(Integer, primary_key=True)\n",
" cluster_name = Column(String(255), unique=True)\n",
" coordinator_host = Column(String(256))\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" @property\n",
" def isnum(self):\n",
" return self.type in ('LONG', 'DOUBLE', 'FLOAT')\n",
"\n"
],
"file_path": "panoramix/models.py",
"type": "add",
"edit_start_line_idx": 392
} | Panoramix
=========
Panoramix is a data exploration platform designed to be visual, intuitive
and interactive.
Buzz Phrases
------------
* Analytics at the speed of thought!
* Instantaneous learning curve
* Realtime analytics when querying [Druid.io](http://druid.io)
* Extentsible to infinity

Database Support
----------------
Panoramix was originally designed on to of Druid.io, but quickly broadened
its scope to support other databases through the use of SqlAlchemy, a Python
ORM that is compatible with
[many external databases](http://docs.sqlalchemy.org/en/rel_1_0/core/engines.html).
What's Druid?
-------------
From their website at http://druid.io
*Druid is an open-source analytics data store designed for
business intelligence (OLAP) queries on event data. Druid provides low
latency (real-time) data ingestion, flexible data exploration,
and fast data aggregation. Existing Druid deployments have scaled to
trillions of events and petabytes of data. Druid is best used to
power analytic dashboards and applications.*
Panoramix
---------
Panoramix's main goal is to make it easy to slice, dice and visualize data
out of Druid. It empowers its user to perform **analytics
at the speed of thought**.
Panoramix started as a hackathon project at Airbnb in while running a POC
(proof of concept) on using Druid.
Panoramix provides:
* A way to query intuitively a Druid dataset, allowing for grouping, filtering
limiting and defining a time granularity
* Many charts and visualization to analyze your data, as well as a flexible
way to extend the visualization capabilities
* An extensible, high granularity security model allowing intricate rules
on who can access which features, and integration with major
authentication providers (through Flask AppBuiler)
* A simple semantic layer, allowing to control how Druid datasources are
displayed in the UI,
by defining which fields should show up in which dropdown and which
aggregation and function (metrics) are made available to the user
Installation
------------
Follow these few simple steps to install Panoramix
```
# Install panoramix
pip install panoramix
# Create an admin user
fabmanager create-admin --app panoramix
# Clone the github repo
git clone https://github.com/mistercrunch/panoramix.git
# Start the web server
panoramix
```
After installation, you should be able to point your browser to the right
hostname:port [http://localhost:8088](http://localhost:8088), login using
the credential you entered while creating the admin account, and navigate to
`Menu -> Admin -> Refresh Metadata`. This action should bring in all of
your datasources for Panoramix to be aware of, and they should show up in
`Menu -> Datasources`, from where you can start playing with your data!
Configuration
-------------
To configure your application, you need to create a file (module)
`panoramix_config.py` and make sure it is in your PYTHONPATH. Here are some
of the parameters you can copy / paste in that configuration module:
```
#---------------------------------------------------------
# Panoramix specifix config
#---------------------------------------------------------
ROW_LIMIT = 5000
WEBSERVER_THREADS = 8
PANORAMIX_WEBSERVER_PORT = 8088
#---------------------------------------------------------
#---------------------------------------------------------
# Flask App Builder configuration
#---------------------------------------------------------
# Your App secret key
SECRET_KEY = '\2\1thisismyscretkey\1\2\e\y\y\h'
# The SQLAlchemy connection string.
SQLALCHEMY_DATABASE_URI = 'sqlite:///tmp/panoramix.db'
# Flask-WTF flag for CSRF
CSRF_ENABLED = True
# Whether to run the web server in debug mode or not
DEBUG = True
```
This file also allows you to define configuration parameters used by
Flask App Builder, the web framework used by Panoramix. Please consult
the [Flask App Builder Documentation](http://flask-appbuilder.readthedocs.org/en/latest/config.html) for more information on how to configure Panoramix.
* From the UI, enter the information about your clusters in the
``Admin->Clusters`` menu by hitting the + sign.
* Once the Druid cluster connection information is entered, hit the
``Admin->Refresh Metadata`` menu item to populate
* Navigate to your datasources
More screenshots
----------------



| README.md | 0 | https://github.com/apache/superset/commit/6dd81a3e95a9d67be743815ff9bfcd465278b3e9 | [
0.001577472547069192,
0.00026821292703971267,
0.00016133091412484646,
0.00016780509031377733,
0.00036314153112471104
] |
{
"id": 4,
"code_window": [
" def __repr__(self):\n",
" return self.column_name\n",
"\n",
"class Cluster(Model, AuditMixin):\n",
" __tablename__ = 'clusters'\n",
" id = Column(Integer, primary_key=True)\n",
" cluster_name = Column(String(255), unique=True)\n",
" coordinator_host = Column(String(256))\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" @property\n",
" def isnum(self):\n",
" return self.type in ('LONG', 'DOUBLE', 'FLOAT')\n",
"\n"
],
"file_path": "panoramix/models.py",
"type": "add",
"edit_start_line_idx": 392
} | .select2-container{box-sizing:border-box;display:inline-block;margin:0;position:relative;vertical-align:middle;}.select2-container .select2-selection--single{box-sizing:border-box;cursor:pointer;display:block;height:28px;user-select:none;-webkit-user-select:none;}.select2-container .select2-selection--single .select2-selection__rendered{display:block;padding-left:8px;padding-right:20px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;}.select2-container[dir="rtl"] .select2-selection--single .select2-selection__rendered{padding-right:8px;padding-left:20px;}.select2-container .select2-selection--multiple{box-sizing:border-box;cursor:pointer;display:block;min-height:32px;user-select:none;-webkit-user-select:none;}.select2-container .select2-selection--multiple .select2-selection__rendered{display:inline-block;overflow:hidden;padding-left:8px;text-overflow:ellipsis;white-space:nowrap;}.select2-container .select2-search--inline{float:left;}.select2-container .select2-search--inline .select2-search__field{box-sizing:border-box;border:none;font-size:100%;margin-top:5px;}.select2-container .select2-search--inline .select2-search__field::-webkit-search-cancel-button{-webkit-appearance:none;}.select2-dropdown{background-color:white;border:1px solid #aaa;border-radius:4px;box-sizing:border-box;display:block;position:absolute;left:-100000px;width:100%;z-index:1051;}.select2-results{display:block;}.select2-results__options{list-style:none;margin:0;padding:0;}.select2-results__option{padding:6px;user-select:none;-webkit-user-select:none;}.select2-results__option[aria-selected]{cursor:pointer;}.select2-container--open .select2-dropdown{left:0;}.select2-container--open .select2-dropdown--above{border-bottom:none;border-bottom-left-radius:0;border-bottom-right-radius:0;}.select2-container--open .select2-dropdown--below{border-top:none;border-top-left-radius:0;border-top-right-radius:0;}.select2-search--dropdown{display:block;padding:4px;}.select2-search--dropdown .select2-search__field{padding:4px;width:100%;box-sizing:border-box;}.select2-search--dropdown .select2-search__field::-webkit-search-cancel-button{-webkit-appearance:none;}.select2-search--dropdown.select2-search--hide{display:none;}.select2-close-mask{border:0;margin:0;padding:0;display:block;position:fixed;left:0;top:0;min-height:100%;min-width:100%;height:auto;width:auto;opacity:0;z-index:99;background-color:#fff;filter:alpha(opacity=0);}.select2-hidden-accessible{border:0;clip:rect(0 0 0 0);height:1px;margin:-1px;overflow:hidden;padding:0;position:absolute;width:1px;}.select2-container--default .select2-selection--single{background-color:#fff;border:1px solid #aaa;border-radius:4px;}.select2-container--default .select2-selection--single .select2-selection__rendered{color:#444;line-height:28px;}.select2-container--default .select2-selection--single .select2-selection__clear{cursor:pointer;float:right;font-weight:bold;}.select2-container--default .select2-selection--single .select2-selection__placeholder{color:#999;}.select2-container--default .select2-selection--single .select2-selection__arrow{height:26px;position:absolute;top:1px;right:1px;width:20px;}.select2-container--default .select2-selection--single .select2-selection__arrow b{border-color:#888 transparent transparent transparent;border-style:solid;border-width:5px 4px 0 4px;height:0;left:50%;margin-left:-4px;margin-top:-2px;position:absolute;top:50%;width:0;}.select2-container--default[dir="rtl"] .select2-selection--single .select2-selection__clear{float:left;}.select2-container--default[dir="rtl"] .select2-selection--single .select2-selection__arrow{left:1px;right:auto;}.select2-container--default.select2-container--disabled .select2-selection--single{background-color:#eee;cursor:default;}.select2-container--default.select2-container--disabled .select2-selection--single .select2-selection__clear{display:none;}.select2-container--default.select2-container--open .select2-selection--single .select2-selection__arrow b{border-color:transparent transparent #888 transparent;border-width:0 4px 5px 4px;}.select2-container--default .select2-selection--multiple{background-color:white;border:1px solid #aaa;border-radius:4px;cursor:text;}.select2-container--default .select2-selection--multiple .select2-selection__rendered{box-sizing:border-box;list-style:none;margin:0;padding:0 5px;width:100%;}.select2-container--default .select2-selection--multiple .select2-selection__placeholder{color:#999;margin-top:5px;float:left;}.select2-container--default .select2-selection--multiple .select2-selection__clear{cursor:pointer;float:right;font-weight:bold;margin-top:5px;margin-right:10px;}.select2-container--default .select2-selection--multiple .select2-selection__choice{background-color:#e4e4e4;border:1px solid #aaa;border-radius:4px;cursor:default;float:left;margin-right:5px;margin-top:5px;padding:0 5px;}.select2-container--default .select2-selection--multiple .select2-selection__choice__remove{color:#999;cursor:pointer;display:inline-block;font-weight:bold;margin-right:2px;}.select2-container--default .select2-selection--multiple .select2-selection__choice__remove:hover{color:#333;}.select2-container--default[dir="rtl"] .select2-selection--multiple .select2-selection__choice,.select2-container--default[dir="rtl"] .select2-selection--multiple .select2-selection__placeholder{float:right;}.select2-container--default[dir="rtl"] .select2-selection--multiple .select2-selection__choice{margin-left:5px;margin-right:auto;}.select2-container--default[dir="rtl"] .select2-selection--multiple .select2-selection__choice__remove{margin-left:2px;margin-right:auto;}.select2-container--default.select2-container--focus .select2-selection--multiple{border:solid black 1px;outline:0;}.select2-container--default.select2-container--disabled .select2-selection--multiple{background-color:#eee;cursor:default;}.select2-container--default.select2-container--disabled .select2-selection__choice__remove{display:none;}.select2-container--default.select2-container--open.select2-container--above .select2-selection--single,.select2-container--default.select2-container--open.select2-container--above .select2-selection--multiple{border-top-left-radius:0;border-top-right-radius:0;}.select2-container--default.select2-container--open.select2-container--below .select2-selection--single,.select2-container--default.select2-container--open.select2-container--below .select2-selection--multiple{border-bottom-left-radius:0;border-bottom-right-radius:0;}.select2-container--default .select2-search--dropdown .select2-search__field{border:1px solid #aaa;}.select2-container--default .select2-search--inline .select2-search__field{background:transparent;border:none;outline:0;}.select2-container--default .select2-results>.select2-results__options{max-height:200px;overflow-y:auto;}.select2-container--default .select2-results__option[role=group]{padding:0;}.select2-container--default .select2-results__option[aria-disabled=true]{color:#999;}.select2-container--default .select2-results__option[aria-selected=true]{background-color:#ddd;}.select2-container--default .select2-results__option .select2-results__option{padding-left:1em;}.select2-container--default .select2-results__option .select2-results__option .select2-results__group{padding-left:0;}.select2-container--default .select2-results__option .select2-results__option .select2-results__option{margin-left:-1em;padding-left:2em;}.select2-container--default .select2-results__option .select2-results__option .select2-results__option .select2-results__option{margin-left:-2em;padding-left:3em;}.select2-container--default .select2-results__option .select2-results__option .select2-results__option .select2-results__option .select2-results__option{margin-left:-3em;padding-left:4em;}.select2-container--default .select2-results__option .select2-results__option .select2-results__option .select2-results__option .select2-results__option .select2-results__option{margin-left:-4em;padding-left:5em;}.select2-container--default .select2-results__option .select2-results__option .select2-results__option .select2-results__option .select2-results__option .select2-results__option .select2-results__option{margin-left:-5em;padding-left:6em;}.select2-container--default .select2-results__option--highlighted[aria-selected]{background-color:#5897fb;color:white;}.select2-container--default .select2-results__group{cursor:default;display:block;padding:6px;}.select2-container--classic .select2-selection--single{background-color:#f6f6f6;border:1px solid #aaa;border-radius:4px;outline:0;background-image:-webkit-linear-gradient(top, #ffffff 50%, #eeeeee 100%);background-image:-o-linear-gradient(top, #ffffff 50%, #eeeeee 100%);background-image:linear-gradient(to bottom, #ffffff 50%, #eeeeee 100%);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffff', endColorstr='#eeeeee', GradientType=0);}.select2-container--classic .select2-selection--single:focus{border:1px solid #5897fb;}.select2-container--classic .select2-selection--single .select2-selection__rendered{color:#444;line-height:28px;}.select2-container--classic .select2-selection--single .select2-selection__clear{cursor:pointer;float:right;font-weight:bold;margin-right:10px;}.select2-container--classic .select2-selection--single .select2-selection__placeholder{color:#999;}.select2-container--classic .select2-selection--single .select2-selection__arrow{background-color:#ddd;border:none;border-left:1px solid #aaa;border-top-right-radius:4px;border-bottom-right-radius:4px;height:26px;position:absolute;top:1px;right:1px;width:20px;background-image:-webkit-linear-gradient(top, #eeeeee 50%, #cccccc 100%);background-image:-o-linear-gradient(top, #eeeeee 50%, #cccccc 100%);background-image:linear-gradient(to bottom, #eeeeee 50%, #cccccc 100%);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#eeeeee', endColorstr='#cccccc', GradientType=0);}.select2-container--classic .select2-selection--single .select2-selection__arrow b{border-color:#888 transparent transparent transparent;border-style:solid;border-width:5px 4px 0 4px;height:0;left:50%;margin-left:-4px;margin-top:-2px;position:absolute;top:50%;width:0;}.select2-container--classic[dir="rtl"] .select2-selection--single .select2-selection__clear{float:left;}.select2-container--classic[dir="rtl"] .select2-selection--single .select2-selection__arrow{border:none;border-right:1px solid #aaa;border-radius:0;border-top-left-radius:4px;border-bottom-left-radius:4px;left:1px;right:auto;}.select2-container--classic.select2-container--open .select2-selection--single{border:1px solid #5897fb;}.select2-container--classic.select2-container--open .select2-selection--single .select2-selection__arrow{background:transparent;border:none;}.select2-container--classic.select2-container--open .select2-selection--single .select2-selection__arrow b{border-color:transparent transparent #888 transparent;border-width:0 4px 5px 4px;}.select2-container--classic.select2-container--open.select2-container--above .select2-selection--single{border-top:none;border-top-left-radius:0;border-top-right-radius:0;background-image:-webkit-linear-gradient(top, #ffffff 0%, #eeeeee 50%);background-image:-o-linear-gradient(top, #ffffff 0%, #eeeeee 50%);background-image:linear-gradient(to bottom, #ffffff 0%, #eeeeee 50%);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffff', endColorstr='#eeeeee', GradientType=0);}.select2-container--classic.select2-container--open.select2-container--below .select2-selection--single{border-bottom:none;border-bottom-left-radius:0;border-bottom-right-radius:0;background-image:-webkit-linear-gradient(top, #eeeeee 50%, #ffffff 100%);background-image:-o-linear-gradient(top, #eeeeee 50%, #ffffff 100%);background-image:linear-gradient(to bottom, #eeeeee 50%, #ffffff 100%);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#eeeeee', endColorstr='#ffffff', GradientType=0);}.select2-container--classic .select2-selection--multiple{background-color:white;border:1px solid #aaa;border-radius:4px;cursor:text;outline:0;}.select2-container--classic .select2-selection--multiple:focus{border:1px solid #5897fb;}.select2-container--classic .select2-selection--multiple .select2-selection__rendered{list-style:none;margin:0;padding:0 5px;}.select2-container--classic .select2-selection--multiple .select2-selection__clear{display:none;}.select2-container--classic .select2-selection--multiple .select2-selection__choice{background-color:#e4e4e4;border:1px solid #aaa;border-radius:4px;cursor:default;float:left;margin-right:5px;margin-top:5px;padding:0 5px;}.select2-container--classic .select2-selection--multiple .select2-selection__choice__remove{color:#888;cursor:pointer;display:inline-block;font-weight:bold;margin-right:2px;}.select2-container--classic .select2-selection--multiple .select2-selection__choice__remove:hover{color:#555;}.select2-container--classic[dir="rtl"] .select2-selection--multiple .select2-selection__choice{float:right;}.select2-container--classic[dir="rtl"] .select2-selection--multiple .select2-selection__choice{margin-left:5px;margin-right:auto;}.select2-container--classic[dir="rtl"] .select2-selection--multiple .select2-selection__choice__remove{margin-left:2px;margin-right:auto;}.select2-container--classic.select2-container--open .select2-selection--multiple{border:1px solid #5897fb;}.select2-container--classic.select2-container--open.select2-container--above .select2-selection--multiple{border-top:none;border-top-left-radius:0;border-top-right-radius:0;}.select2-container--classic.select2-container--open.select2-container--below .select2-selection--multiple{border-bottom:none;border-bottom-left-radius:0;border-bottom-right-radius:0;}.select2-container--classic .select2-search--dropdown .select2-search__field{border:1px solid #aaa;outline:0;}.select2-container--classic .select2-search--inline .select2-search__field{outline:0;}.select2-container--classic .select2-dropdown{background-color:white;border:1px solid transparent;}.select2-container--classic .select2-dropdown--above{border-bottom:none;}.select2-container--classic .select2-dropdown--below{border-top:none;}.select2-container--classic .select2-results>.select2-results__options{max-height:200px;overflow-y:auto;}.select2-container--classic .select2-results__option[role=group]{padding:0;}.select2-container--classic .select2-results__option[aria-disabled=true]{color:grey;}.select2-container--classic .select2-results__option--highlighted[aria-selected]{background-color:#3875d7;color:white;}.select2-container--classic .select2-results__group{cursor:default;display:block;padding:6px;}.select2-container--classic.select2-container--open .select2-dropdown{border-color:#5897fb;} | panoramix/static/select2.min.css | 0 | https://github.com/apache/superset/commit/6dd81a3e95a9d67be743815ff9bfcd465278b3e9 | [
0.00017025379929691553,
0.00017025379929691553,
0.00017025379929691553,
0.00017025379929691553,
0
] |
{
"id": 4,
"code_window": [
" def __repr__(self):\n",
" return self.column_name\n",
"\n",
"class Cluster(Model, AuditMixin):\n",
" __tablename__ = 'clusters'\n",
" id = Column(Integer, primary_key=True)\n",
" cluster_name = Column(String(255), unique=True)\n",
" coordinator_host = Column(String(256))\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" @property\n",
" def isnum(self):\n",
" return self.type in ('LONG', 'DOUBLE', 'FLOAT')\n",
"\n"
],
"file_path": "panoramix/models.py",
"type": "add",
"edit_start_line_idx": 392
} | /*! Select2 4.0.0 | https://github.com/select2/select2/blob/master/LICENSE.md */!function(a){"function"==typeof define&&define.amd?define(["jquery"],a):a("object"==typeof exports?require("jquery"):jQuery)}(function(a){var b=function(){if(a&&a.fn&&a.fn.select2&&a.fn.select2.amd)var b=a.fn.select2.amd;var b;return function(){if(!b||!b.requirejs){b?c=b:b={};var a,c,d;!function(b){function e(a,b){return u.call(a,b)}function f(a,b){var c,d,e,f,g,h,i,j,k,l,m,n=b&&b.split("/"),o=s.map,p=o&&o["*"]||{};if(a&&"."===a.charAt(0))if(b){for(n=n.slice(0,n.length-1),a=a.split("/"),g=a.length-1,s.nodeIdCompat&&w.test(a[g])&&(a[g]=a[g].replace(w,"")),a=n.concat(a),k=0;k<a.length;k+=1)if(m=a[k],"."===m)a.splice(k,1),k-=1;else if(".."===m){if(1===k&&(".."===a[2]||".."===a[0]))break;k>0&&(a.splice(k-1,2),k-=2)}a=a.join("/")}else 0===a.indexOf("./")&&(a=a.substring(2));if((n||p)&&o){for(c=a.split("/"),k=c.length;k>0;k-=1){if(d=c.slice(0,k).join("/"),n)for(l=n.length;l>0;l-=1)if(e=o[n.slice(0,l).join("/")],e&&(e=e[d])){f=e,h=k;break}if(f)break;!i&&p&&p[d]&&(i=p[d],j=k)}!f&&i&&(f=i,h=j),f&&(c.splice(0,h,f),a=c.join("/"))}return a}function g(a,c){return function(){return n.apply(b,v.call(arguments,0).concat([a,c]))}}function h(a){return function(b){return f(b,a)}}function i(a){return function(b){q[a]=b}}function j(a){if(e(r,a)){var c=r[a];delete r[a],t[a]=!0,m.apply(b,c)}if(!e(q,a)&&!e(t,a))throw new Error("No "+a);return q[a]}function k(a){var b,c=a?a.indexOf("!"):-1;return c>-1&&(b=a.substring(0,c),a=a.substring(c+1,a.length)),[b,a]}function l(a){return function(){return s&&s.config&&s.config[a]||{}}}var m,n,o,p,q={},r={},s={},t={},u=Object.prototype.hasOwnProperty,v=[].slice,w=/\.js$/;o=function(a,b){var c,d=k(a),e=d[0];return a=d[1],e&&(e=f(e,b),c=j(e)),e?a=c&&c.normalize?c.normalize(a,h(b)):f(a,b):(a=f(a,b),d=k(a),e=d[0],a=d[1],e&&(c=j(e))),{f:e?e+"!"+a:a,n:a,pr:e,p:c}},p={require:function(a){return g(a)},exports:function(a){var b=q[a];return"undefined"!=typeof b?b:q[a]={}},module:function(a){return{id:a,uri:"",exports:q[a],config:l(a)}}},m=function(a,c,d,f){var h,k,l,m,n,s,u=[],v=typeof d;if(f=f||a,"undefined"===v||"function"===v){for(c=!c.length&&d.length?["require","exports","module"]:c,n=0;n<c.length;n+=1)if(m=o(c[n],f),k=m.f,"require"===k)u[n]=p.require(a);else if("exports"===k)u[n]=p.exports(a),s=!0;else if("module"===k)h=u[n]=p.module(a);else if(e(q,k)||e(r,k)||e(t,k))u[n]=j(k);else{if(!m.p)throw new Error(a+" missing "+k);m.p.load(m.n,g(f,!0),i(k),{}),u[n]=q[k]}l=d?d.apply(q[a],u):void 0,a&&(h&&h.exports!==b&&h.exports!==q[a]?q[a]=h.exports:l===b&&s||(q[a]=l))}else a&&(q[a]=d)},a=c=n=function(a,c,d,e,f){if("string"==typeof a)return p[a]?p[a](c):j(o(a,c).f);if(!a.splice){if(s=a,s.deps&&n(s.deps,s.callback),!c)return;c.splice?(a=c,c=d,d=null):a=b}return c=c||function(){},"function"==typeof d&&(d=e,e=f),e?m(b,a,c,d):setTimeout(function(){m(b,a,c,d)},4),n},n.config=function(a){return n(a)},a._defined=q,d=function(a,b,c){b.splice||(c=b,b=[]),e(q,a)||e(r,a)||(r[a]=[a,b,c])},d.amd={jQuery:!0}}(),b.requirejs=a,b.require=c,b.define=d}}(),b.define("almond",function(){}),b.define("jquery",[],function(){var b=a||$;return null==b&&console&&console.error&&console.error("Select2: An instance of jQuery or a jQuery-compatible library was not found. Make sure that you are including jQuery before Select2 on your web page."),b}),b.define("select2/utils",["jquery"],function(a){function b(a){var b=a.prototype,c=[];for(var d in b){var e=b[d];"function"==typeof e&&"constructor"!==d&&c.push(d)}return c}var c={};c.Extend=function(a,b){function c(){this.constructor=a}var d={}.hasOwnProperty;for(var e in b)d.call(b,e)&&(a[e]=b[e]);return c.prototype=b.prototype,a.prototype=new c,a.__super__=b.prototype,a},c.Decorate=function(a,c){function d(){var b=Array.prototype.unshift,d=c.prototype.constructor.length,e=a.prototype.constructor;d>0&&(b.call(arguments,a.prototype.constructor),e=c.prototype.constructor),e.apply(this,arguments)}function e(){this.constructor=d}var f=b(c),g=b(a);c.displayName=a.displayName,d.prototype=new e;for(var h=0;h<g.length;h++){var i=g[h];d.prototype[i]=a.prototype[i]}for(var j=(function(a){var b=function(){};a in d.prototype&&(b=d.prototype[a]);var e=c.prototype[a];return function(){var a=Array.prototype.unshift;return a.call(arguments,b),e.apply(this,arguments)}}),k=0;k<f.length;k++){var l=f[k];d.prototype[l]=j(l)}return d};var d=function(){this.listeners={}};return d.prototype.on=function(a,b){this.listeners=this.listeners||{},a in this.listeners?this.listeners[a].push(b):this.listeners[a]=[b]},d.prototype.trigger=function(a){var b=Array.prototype.slice;this.listeners=this.listeners||{},a in this.listeners&&this.invoke(this.listeners[a],b.call(arguments,1)),"*"in this.listeners&&this.invoke(this.listeners["*"],arguments)},d.prototype.invoke=function(a,b){for(var c=0,d=a.length;d>c;c++)a[c].apply(this,b)},c.Observable=d,c.generateChars=function(a){for(var b="",c=0;a>c;c++){var d=Math.floor(36*Math.random());b+=d.toString(36)}return b},c.bind=function(a,b){return function(){a.apply(b,arguments)}},c._convertData=function(a){for(var b in a){var c=b.split("-"),d=a;if(1!==c.length){for(var e=0;e<c.length;e++){var f=c[e];f=f.substring(0,1).toLowerCase()+f.substring(1),f in d||(d[f]={}),e==c.length-1&&(d[f]=a[b]),d=d[f]}delete a[b]}}return a},c.hasScroll=function(b,c){var d=a(c),e=c.style.overflowX,f=c.style.overflowY;return e!==f||"hidden"!==f&&"visible"!==f?"scroll"===e||"scroll"===f?!0:d.innerHeight()<c.scrollHeight||d.innerWidth()<c.scrollWidth:!1},c.escapeMarkup=function(a){var b={"\\":"\","&":"&","<":"<",">":">",'"':""","'":"'","/":"/"};return"string"!=typeof a?a:String(a).replace(/[&<>"'\/\\]/g,function(a){return b[a]})},c.appendMany=function(b,c){if("1.7"===a.fn.jquery.substr(0,3)){var d=a();a.map(c,function(a){d=d.add(a)}),c=d}b.append(c)},c}),b.define("select2/results",["jquery","./utils"],function(a,b){function c(a,b,d){this.$element=a,this.data=d,this.options=b,c.__super__.constructor.call(this)}return b.Extend(c,b.Observable),c.prototype.render=function(){var b=a('<ul class="select2-results__options" role="tree"></ul>');return this.options.get("multiple")&&b.attr("aria-multiselectable","true"),this.$results=b,b},c.prototype.clear=function(){this.$results.empty()},c.prototype.displayMessage=function(b){var c=this.options.get("escapeMarkup");this.clear(),this.hideLoading();var d=a('<li role="treeitem" class="select2-results__option"></li>'),e=this.options.get("translations").get(b.message);d.append(c(e(b.args))),this.$results.append(d)},c.prototype.append=function(a){this.hideLoading();var b=[];if(null==a.results||0===a.results.length)return void(0===this.$results.children().length&&this.trigger("results:message",{message:"noResults"}));a.results=this.sort(a.results);for(var c=0;c<a.results.length;c++){var d=a.results[c],e=this.option(d);b.push(e)}this.$results.append(b)},c.prototype.position=function(a,b){var c=b.find(".select2-results");c.append(a)},c.prototype.sort=function(a){var b=this.options.get("sorter");return b(a)},c.prototype.setClasses=function(){var b=this;this.data.current(function(c){var d=a.map(c,function(a){return a.id.toString()}),e=b.$results.find(".select2-results__option[aria-selected]");e.each(function(){var b=a(this),c=a.data(this,"data"),e=""+c.id;null!=c.element&&c.element.selected||null==c.element&&a.inArray(e,d)>-1?b.attr("aria-selected","true"):b.attr("aria-selected","false")});var f=e.filter("[aria-selected=true]");f.length>0?f.first().trigger("mouseenter"):e.first().trigger("mouseenter")})},c.prototype.showLoading=function(a){this.hideLoading();var b=this.options.get("translations").get("searching"),c={disabled:!0,loading:!0,text:b(a)},d=this.option(c);d.className+=" loading-results",this.$results.prepend(d)},c.prototype.hideLoading=function(){this.$results.find(".loading-results").remove()},c.prototype.option=function(b){var c=document.createElement("li");c.className="select2-results__option";var d={role:"treeitem","aria-selected":"false"};b.disabled&&(delete d["aria-selected"],d["aria-disabled"]="true"),null==b.id&&delete d["aria-selected"],null!=b._resultId&&(c.id=b._resultId),b.title&&(c.title=b.title),b.children&&(d.role="group",d["aria-label"]=b.text,delete d["aria-selected"]);for(var e in d){var f=d[e];c.setAttribute(e,f)}if(b.children){var g=a(c),h=document.createElement("strong");h.className="select2-results__group";{a(h)}this.template(b,h);for(var i=[],j=0;j<b.children.length;j++){var k=b.children[j],l=this.option(k);i.push(l)}var m=a("<ul></ul>",{"class":"select2-results__options select2-results__options--nested"});m.append(i),g.append(h),g.append(m)}else this.template(b,c);return a.data(c,"data",b),c},c.prototype.bind=function(b){var c=this,d=b.id+"-results";this.$results.attr("id",d),b.on("results:all",function(a){c.clear(),c.append(a.data),b.isOpen()&&c.setClasses()}),b.on("results:append",function(a){c.append(a.data),b.isOpen()&&c.setClasses()}),b.on("query",function(a){c.showLoading(a)}),b.on("select",function(){b.isOpen()&&c.setClasses()}),b.on("unselect",function(){b.isOpen()&&c.setClasses()}),b.on("open",function(){c.$results.attr("aria-expanded","true"),c.$results.attr("aria-hidden","false"),c.setClasses(),c.ensureHighlightVisible()}),b.on("close",function(){c.$results.attr("aria-expanded","false"),c.$results.attr("aria-hidden","true"),c.$results.removeAttr("aria-activedescendant")}),b.on("results:toggle",function(){var a=c.getHighlightedResults();0!==a.length&&a.trigger("mouseup")}),b.on("results:select",function(){var a=c.getHighlightedResults();if(0!==a.length){var b=a.data("data");"true"==a.attr("aria-selected")?c.trigger("close"):c.trigger("select",{data:b})}}),b.on("results:previous",function(){var a=c.getHighlightedResults(),b=c.$results.find("[aria-selected]"),d=b.index(a);if(0!==d){var e=d-1;0===a.length&&(e=0);var f=b.eq(e);f.trigger("mouseenter");var g=c.$results.offset().top,h=f.offset().top,i=c.$results.scrollTop()+(h-g);0===e?c.$results.scrollTop(0):0>h-g&&c.$results.scrollTop(i)}}),b.on("results:next",function(){var a=c.getHighlightedResults(),b=c.$results.find("[aria-selected]"),d=b.index(a),e=d+1;if(!(e>=b.length)){var f=b.eq(e);f.trigger("mouseenter");var g=c.$results.offset().top+c.$results.outerHeight(!1),h=f.offset().top+f.outerHeight(!1),i=c.$results.scrollTop()+h-g;0===e?c.$results.scrollTop(0):h>g&&c.$results.scrollTop(i)}}),b.on("results:focus",function(a){a.element.addClass("select2-results__option--highlighted")}),b.on("results:message",function(a){c.displayMessage(a)}),a.fn.mousewheel&&this.$results.on("mousewheel",function(a){var b=c.$results.scrollTop(),d=c.$results.get(0).scrollHeight-c.$results.scrollTop()+a.deltaY,e=a.deltaY>0&&b-a.deltaY<=0,f=a.deltaY<0&&d<=c.$results.height();e?(c.$results.scrollTop(0),a.preventDefault(),a.stopPropagation()):f&&(c.$results.scrollTop(c.$results.get(0).scrollHeight-c.$results.height()),a.preventDefault(),a.stopPropagation())}),this.$results.on("mouseup",".select2-results__option[aria-selected]",function(b){var d=a(this),e=d.data("data");return"true"===d.attr("aria-selected")?void(c.options.get("multiple")?c.trigger("unselect",{originalEvent:b,data:e}):c.trigger("close")):void c.trigger("select",{originalEvent:b,data:e})}),this.$results.on("mouseenter",".select2-results__option[aria-selected]",function(){var b=a(this).data("data");c.getHighlightedResults().removeClass("select2-results__option--highlighted"),c.trigger("results:focus",{data:b,element:a(this)})})},c.prototype.getHighlightedResults=function(){var a=this.$results.find(".select2-results__option--highlighted");return a},c.prototype.destroy=function(){this.$results.remove()},c.prototype.ensureHighlightVisible=function(){var a=this.getHighlightedResults();if(0!==a.length){var b=this.$results.find("[aria-selected]"),c=b.index(a),d=this.$results.offset().top,e=a.offset().top,f=this.$results.scrollTop()+(e-d),g=e-d;f-=2*a.outerHeight(!1),2>=c?this.$results.scrollTop(0):(g>this.$results.outerHeight()||0>g)&&this.$results.scrollTop(f)}},c.prototype.template=function(b,c){var d=this.options.get("templateResult"),e=this.options.get("escapeMarkup"),f=d(b);null==f?c.style.display="none":"string"==typeof f?c.innerHTML=e(f):a(c).append(f)},c}),b.define("select2/keys",[],function(){var a={BACKSPACE:8,TAB:9,ENTER:13,SHIFT:16,CTRL:17,ALT:18,ESC:27,SPACE:32,PAGE_UP:33,PAGE_DOWN:34,END:35,HOME:36,LEFT:37,UP:38,RIGHT:39,DOWN:40,DELETE:46};return a}),b.define("select2/selection/base",["jquery","../utils","../keys"],function(a,b,c){function d(a,b){this.$element=a,this.options=b,d.__super__.constructor.call(this)}return b.Extend(d,b.Observable),d.prototype.render=function(){var b=a('<span class="select2-selection" role="combobox" aria-autocomplete="list" aria-haspopup="true" aria-expanded="false"></span>');return this._tabindex=0,null!=this.$element.data("old-tabindex")?this._tabindex=this.$element.data("old-tabindex"):null!=this.$element.attr("tabindex")&&(this._tabindex=this.$element.attr("tabindex")),b.attr("title",this.$element.attr("title")),b.attr("tabindex",this._tabindex),this.$selection=b,b},d.prototype.bind=function(a){var b=this,d=(a.id+"-container",a.id+"-results");this.container=a,this.$selection.on("focus",function(a){b.trigger("focus",a)}),this.$selection.on("blur",function(a){b.trigger("blur",a)}),this.$selection.on("keydown",function(a){b.trigger("keypress",a),a.which===c.SPACE&&a.preventDefault()}),a.on("results:focus",function(a){b.$selection.attr("aria-activedescendant",a.data._resultId)}),a.on("selection:update",function(a){b.update(a.data)}),a.on("open",function(){b.$selection.attr("aria-expanded","true"),b.$selection.attr("aria-owns",d),b._attachCloseHandler(a)}),a.on("close",function(){b.$selection.attr("aria-expanded","false"),b.$selection.removeAttr("aria-activedescendant"),b.$selection.removeAttr("aria-owns"),b.$selection.focus(),b._detachCloseHandler(a)}),a.on("enable",function(){b.$selection.attr("tabindex",b._tabindex)}),a.on("disable",function(){b.$selection.attr("tabindex","-1")})},d.prototype._attachCloseHandler=function(b){a(document.body).on("mousedown.select2."+b.id,function(b){var c=a(b.target),d=c.closest(".select2"),e=a(".select2.select2-container--open");e.each(function(){var b=a(this);if(this!=d[0]){var c=b.data("element");c.select2("close")}})})},d.prototype._detachCloseHandler=function(b){a(document.body).off("mousedown.select2."+b.id)},d.prototype.position=function(a,b){var c=b.find(".selection");c.append(a)},d.prototype.destroy=function(){this._detachCloseHandler(this.container)},d.prototype.update=function(){throw new Error("The `update` method must be defined in child classes.")},d}),b.define("select2/selection/single",["jquery","./base","../utils","../keys"],function(a,b,c){function d(){d.__super__.constructor.apply(this,arguments)}return c.Extend(d,b),d.prototype.render=function(){var a=d.__super__.render.call(this);return a.addClass("select2-selection--single"),a.html('<span class="select2-selection__rendered"></span><span class="select2-selection__arrow" role="presentation"><b role="presentation"></b></span>'),a},d.prototype.bind=function(a){var b=this;d.__super__.bind.apply(this,arguments);var c=a.id+"-container";this.$selection.find(".select2-selection__rendered").attr("id",c),this.$selection.attr("aria-labelledby",c),this.$selection.on("mousedown",function(a){1===a.which&&b.trigger("toggle",{originalEvent:a})}),this.$selection.on("focus",function(){}),this.$selection.on("blur",function(){}),a.on("selection:update",function(a){b.update(a.data)})},d.prototype.clear=function(){this.$selection.find(".select2-selection__rendered").empty()},d.prototype.display=function(a){var b=this.options.get("templateSelection"),c=this.options.get("escapeMarkup");return c(b(a))},d.prototype.selectionContainer=function(){return a("<span></span>")},d.prototype.update=function(a){if(0===a.length)return void this.clear();var b=a[0],c=this.display(b),d=this.$selection.find(".select2-selection__rendered");d.empty().append(c),d.prop("title",b.title||b.text)},d}),b.define("select2/selection/multiple",["jquery","./base","../utils"],function(a,b,c){function d(){d.__super__.constructor.apply(this,arguments)}return c.Extend(d,b),d.prototype.render=function(){var a=d.__super__.render.call(this);return a.addClass("select2-selection--multiple"),a.html('<ul class="select2-selection__rendered"></ul>'),a},d.prototype.bind=function(){var b=this;d.__super__.bind.apply(this,arguments),this.$selection.on("click",function(a){b.trigger("toggle",{originalEvent:a})}),this.$selection.on("click",".select2-selection__choice__remove",function(c){var d=a(this),e=d.parent(),f=e.data("data");b.trigger("unselect",{originalEvent:c,data:f})})},d.prototype.clear=function(){this.$selection.find(".select2-selection__rendered").empty()},d.prototype.display=function(a){var b=this.options.get("templateSelection"),c=this.options.get("escapeMarkup");return c(b(a))},d.prototype.selectionContainer=function(){var b=a('<li class="select2-selection__choice"><span class="select2-selection__choice__remove" role="presentation">×</span></li>');return b},d.prototype.update=function(a){if(this.clear(),0!==a.length){for(var b=[],d=0;d<a.length;d++){var e=a[d],f=this.display(e),g=this.selectionContainer();g.append(f),g.prop("title",e.title||e.text),g.data("data",e),b.push(g)}var h=this.$selection.find(".select2-selection__rendered");c.appendMany(h,b)}},d}),b.define("select2/selection/placeholder",["../utils"],function(){function a(a,b,c){this.placeholder=this.normalizePlaceholder(c.get("placeholder")),a.call(this,b,c)}return a.prototype.normalizePlaceholder=function(a,b){return"string"==typeof b&&(b={id:"",text:b}),b},a.prototype.createPlaceholder=function(a,b){var c=this.selectionContainer();return c.html(this.display(b)),c.addClass("select2-selection__placeholder").removeClass("select2-selection__choice"),c},a.prototype.update=function(a,b){var c=1==b.length&&b[0].id!=this.placeholder.id,d=b.length>1;if(d||c)return a.call(this,b);this.clear();var e=this.createPlaceholder(this.placeholder);this.$selection.find(".select2-selection__rendered").append(e)},a}),b.define("select2/selection/allowClear",["jquery","../keys"],function(a,b){function c(){}return c.prototype.bind=function(a,b,c){var d=this;a.call(this,b,c),null==this.placeholder&&this.options.get("debug")&&window.console&&console.error&&console.error("Select2: The `allowClear` option should be used in combination with the `placeholder` option."),this.$selection.on("mousedown",".select2-selection__clear",function(a){d._handleClear(a)}),b.on("keypress",function(a){d._handleKeyboardClear(a,b)})},c.prototype._handleClear=function(a,b){if(!this.options.get("disabled")){var c=this.$selection.find(".select2-selection__clear");if(0!==c.length){b.stopPropagation();for(var d=c.data("data"),e=0;e<d.length;e++){var f={data:d[e]};if(this.trigger("unselect",f),f.prevented)return}this.$element.val(this.placeholder.id).trigger("change"),this.trigger("toggle")}}},c.prototype._handleKeyboardClear=function(a,c,d){d.isOpen()||(c.which==b.DELETE||c.which==b.BACKSPACE)&&this._handleClear(c)},c.prototype.update=function(b,c){if(b.call(this,c),!(this.$selection.find(".select2-selection__placeholder").length>0||0===c.length)){var d=a('<span class="select2-selection__clear">×</span>');d.data("data",c),this.$selection.find(".select2-selection__rendered").prepend(d)}},c}),b.define("select2/selection/search",["jquery","../utils","../keys"],function(a,b,c){function d(a,b,c){a.call(this,b,c)}return d.prototype.render=function(b){var c=a('<li class="select2-search select2-search--inline"><input class="select2-search__field" type="search" tabindex="-1" autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false" role="textbox" /></li>');this.$searchContainer=c,this.$search=c.find("input");var d=b.call(this);return d},d.prototype.bind=function(a,b,d){var e=this;a.call(this,b,d),b.on("open",function(){e.$search.attr("tabindex",0),e.$search.focus()}),b.on("close",function(){e.$search.attr("tabindex",-1),e.$search.val(""),e.$search.focus()}),b.on("enable",function(){e.$search.prop("disabled",!1)}),b.on("disable",function(){e.$search.prop("disabled",!0)}),this.$selection.on("focusin",".select2-search--inline",function(a){e.trigger("focus",a)}),this.$selection.on("focusout",".select2-search--inline",function(a){e.trigger("blur",a)}),this.$selection.on("keydown",".select2-search--inline",function(a){a.stopPropagation(),e.trigger("keypress",a),e._keyUpPrevented=a.isDefaultPrevented();var b=a.which;if(b===c.BACKSPACE&&""===e.$search.val()){var d=e.$searchContainer.prev(".select2-selection__choice");if(d.length>0){var f=d.data("data");e.searchRemoveChoice(f),a.preventDefault()}}}),this.$selection.on("input",".select2-search--inline",function(){e.$selection.off("keyup.search")}),this.$selection.on("keyup.search input",".select2-search--inline",function(a){e.handleSearch(a)})},d.prototype.createPlaceholder=function(a,b){this.$search.attr("placeholder",b.text)},d.prototype.update=function(a,b){this.$search.attr("placeholder",""),a.call(this,b),this.$selection.find(".select2-selection__rendered").append(this.$searchContainer),this.resizeSearch()},d.prototype.handleSearch=function(){if(this.resizeSearch(),!this._keyUpPrevented){var a=this.$search.val();this.trigger("query",{term:a})}this._keyUpPrevented=!1},d.prototype.searchRemoveChoice=function(a,b){this.trigger("unselect",{data:b}),this.trigger("open"),this.$search.val(b.text+" ")},d.prototype.resizeSearch=function(){this.$search.css("width","25px");var a="";if(""!==this.$search.attr("placeholder"))a=this.$selection.find(".select2-selection__rendered").innerWidth();else{var b=this.$search.val().length+1;a=.75*b+"em"}this.$search.css("width",a)},d}),b.define("select2/selection/eventRelay",["jquery"],function(a){function b(){}return b.prototype.bind=function(b,c,d){var e=this,f=["open","opening","close","closing","select","selecting","unselect","unselecting"],g=["opening","closing","selecting","unselecting"];b.call(this,c,d),c.on("*",function(b,c){if(-1!==a.inArray(b,f)){c=c||{};var d=a.Event("select2:"+b,{params:c});e.$element.trigger(d),-1!==a.inArray(b,g)&&(c.prevented=d.isDefaultPrevented())}})},b}),b.define("select2/translation",["jquery","require"],function(a,b){function c(a){this.dict=a||{}}return c.prototype.all=function(){return this.dict},c.prototype.get=function(a){return this.dict[a]},c.prototype.extend=function(b){this.dict=a.extend({},b.all(),this.dict)},c._cache={},c.loadPath=function(a){if(!(a in c._cache)){var d=b(a);c._cache[a]=d}return new c(c._cache[a])},c}),b.define("select2/diacritics",[],function(){var a={"Ⓐ":"A","A":"A","À":"A","Á":"A","Â":"A","Ầ":"A","Ấ":"A","Ẫ":"A","Ẩ":"A","Ã":"A","Ā":"A","Ă":"A","Ằ":"A","Ắ":"A","Ẵ":"A","Ẳ":"A","Ȧ":"A","Ǡ":"A","Ä":"A","Ǟ":"A","Ả":"A","Å":"A","Ǻ":"A","Ǎ":"A","Ȁ":"A","Ȃ":"A","Ạ":"A","Ậ":"A","Ặ":"A","Ḁ":"A","Ą":"A","Ⱥ":"A","Ɐ":"A","Ꜳ":"AA","Æ":"AE","Ǽ":"AE","Ǣ":"AE","Ꜵ":"AO","Ꜷ":"AU","Ꜹ":"AV","Ꜻ":"AV","Ꜽ":"AY","Ⓑ":"B","B":"B","Ḃ":"B","Ḅ":"B","Ḇ":"B","Ƀ":"B","Ƃ":"B","Ɓ":"B","Ⓒ":"C","C":"C","Ć":"C","Ĉ":"C","Ċ":"C","Č":"C","Ç":"C","Ḉ":"C","Ƈ":"C","Ȼ":"C","Ꜿ":"C","Ⓓ":"D","D":"D","Ḋ":"D","Ď":"D","Ḍ":"D","Ḑ":"D","Ḓ":"D","Ḏ":"D","Đ":"D","Ƌ":"D","Ɗ":"D","Ɖ":"D","Ꝺ":"D","DZ":"DZ","DŽ":"DZ","Dz":"Dz","Dž":"Dz","Ⓔ":"E","E":"E","È":"E","É":"E","Ê":"E","Ề":"E","Ế":"E","Ễ":"E","Ể":"E","Ẽ":"E","Ē":"E","Ḕ":"E","Ḗ":"E","Ĕ":"E","Ė":"E","Ë":"E","Ẻ":"E","Ě":"E","Ȅ":"E","Ȇ":"E","Ẹ":"E","Ệ":"E","Ȩ":"E","Ḝ":"E","Ę":"E","Ḙ":"E","Ḛ":"E","Ɛ":"E","Ǝ":"E","Ⓕ":"F","F":"F","Ḟ":"F","Ƒ":"F","Ꝼ":"F","Ⓖ":"G","G":"G","Ǵ":"G","Ĝ":"G","Ḡ":"G","Ğ":"G","Ġ":"G","Ǧ":"G","Ģ":"G","Ǥ":"G","Ɠ":"G","Ꞡ":"G","Ᵹ":"G","Ꝿ":"G","Ⓗ":"H","H":"H","Ĥ":"H","Ḣ":"H","Ḧ":"H","Ȟ":"H","Ḥ":"H","Ḩ":"H","Ḫ":"H","Ħ":"H","Ⱨ":"H","Ⱶ":"H","Ɥ":"H","Ⓘ":"I","I":"I","Ì":"I","Í":"I","Î":"I","Ĩ":"I","Ī":"I","Ĭ":"I","İ":"I","Ï":"I","Ḯ":"I","Ỉ":"I","Ǐ":"I","Ȉ":"I","Ȋ":"I","Ị":"I","Į":"I","Ḭ":"I","Ɨ":"I","Ⓙ":"J","J":"J","Ĵ":"J","Ɉ":"J","Ⓚ":"K","K":"K","Ḱ":"K","Ǩ":"K","Ḳ":"K","Ķ":"K","Ḵ":"K","Ƙ":"K","Ⱪ":"K","Ꝁ":"K","Ꝃ":"K","Ꝅ":"K","Ꞣ":"K","Ⓛ":"L","L":"L","Ŀ":"L","Ĺ":"L","Ľ":"L","Ḷ":"L","Ḹ":"L","Ļ":"L","Ḽ":"L","Ḻ":"L","Ł":"L","Ƚ":"L","Ɫ":"L","Ⱡ":"L","Ꝉ":"L","Ꝇ":"L","Ꞁ":"L","LJ":"LJ","Lj":"Lj","Ⓜ":"M","M":"M","Ḿ":"M","Ṁ":"M","Ṃ":"M","Ɱ":"M","Ɯ":"M","Ⓝ":"N","N":"N","Ǹ":"N","Ń":"N","Ñ":"N","Ṅ":"N","Ň":"N","Ṇ":"N","Ņ":"N","Ṋ":"N","Ṉ":"N","Ƞ":"N","Ɲ":"N","Ꞑ":"N","Ꞥ":"N","NJ":"NJ","Nj":"Nj","Ⓞ":"O","O":"O","Ò":"O","Ó":"O","Ô":"O","Ồ":"O","Ố":"O","Ỗ":"O","Ổ":"O","Õ":"O","Ṍ":"O","Ȭ":"O","Ṏ":"O","Ō":"O","Ṑ":"O","Ṓ":"O","Ŏ":"O","Ȯ":"O","Ȱ":"O","Ö":"O","Ȫ":"O","Ỏ":"O","Ő":"O","Ǒ":"O","Ȍ":"O","Ȏ":"O","Ơ":"O","Ờ":"O","Ớ":"O","Ỡ":"O","Ở":"O","Ợ":"O","Ọ":"O","Ộ":"O","Ǫ":"O","Ǭ":"O","Ø":"O","Ǿ":"O","Ɔ":"O","Ɵ":"O","Ꝋ":"O","Ꝍ":"O","Ƣ":"OI","Ꝏ":"OO","Ȣ":"OU","Ⓟ":"P","P":"P","Ṕ":"P","Ṗ":"P","Ƥ":"P","Ᵽ":"P","Ꝑ":"P","Ꝓ":"P","Ꝕ":"P","Ⓠ":"Q","Q":"Q","Ꝗ":"Q","Ꝙ":"Q","Ɋ":"Q","Ⓡ":"R","R":"R","Ŕ":"R","Ṙ":"R","Ř":"R","Ȑ":"R","Ȓ":"R","Ṛ":"R","Ṝ":"R","Ŗ":"R","Ṟ":"R","Ɍ":"R","Ɽ":"R","Ꝛ":"R","Ꞧ":"R","Ꞃ":"R","Ⓢ":"S","S":"S","ẞ":"S","Ś":"S","Ṥ":"S","Ŝ":"S","Ṡ":"S","Š":"S","Ṧ":"S","Ṣ":"S","Ṩ":"S","Ș":"S","Ş":"S","Ȿ":"S","Ꞩ":"S","Ꞅ":"S","Ⓣ":"T","T":"T","Ṫ":"T","Ť":"T","Ṭ":"T","Ț":"T","Ţ":"T","Ṱ":"T","Ṯ":"T","Ŧ":"T","Ƭ":"T","Ʈ":"T","Ⱦ":"T","Ꞇ":"T","Ꜩ":"TZ","Ⓤ":"U","U":"U","Ù":"U","Ú":"U","Û":"U","Ũ":"U","Ṹ":"U","Ū":"U","Ṻ":"U","Ŭ":"U","Ü":"U","Ǜ":"U","Ǘ":"U","Ǖ":"U","Ǚ":"U","Ủ":"U","Ů":"U","Ű":"U","Ǔ":"U","Ȕ":"U","Ȗ":"U","Ư":"U","Ừ":"U","Ứ":"U","Ữ":"U","Ử":"U","Ự":"U","Ụ":"U","Ṳ":"U","Ų":"U","Ṷ":"U","Ṵ":"U","Ʉ":"U","Ⓥ":"V","V":"V","Ṽ":"V","Ṿ":"V","Ʋ":"V","Ꝟ":"V","Ʌ":"V","Ꝡ":"VY","Ⓦ":"W","W":"W","Ẁ":"W","Ẃ":"W","Ŵ":"W","Ẇ":"W","Ẅ":"W","Ẉ":"W","Ⱳ":"W","Ⓧ":"X","X":"X","Ẋ":"X","Ẍ":"X","Ⓨ":"Y","Y":"Y","Ỳ":"Y","Ý":"Y","Ŷ":"Y","Ỹ":"Y","Ȳ":"Y","Ẏ":"Y","Ÿ":"Y","Ỷ":"Y","Ỵ":"Y","Ƴ":"Y","Ɏ":"Y","Ỿ":"Y","Ⓩ":"Z","Z":"Z","Ź":"Z","Ẑ":"Z","Ż":"Z","Ž":"Z","Ẓ":"Z","Ẕ":"Z","Ƶ":"Z","Ȥ":"Z","Ɀ":"Z","Ⱬ":"Z","Ꝣ":"Z","ⓐ":"a","a":"a","ẚ":"a","à":"a","á":"a","â":"a","ầ":"a","ấ":"a","ẫ":"a","ẩ":"a","ã":"a","ā":"a","ă":"a","ằ":"a","ắ":"a","ẵ":"a","ẳ":"a","ȧ":"a","ǡ":"a","ä":"a","ǟ":"a","ả":"a","å":"a","ǻ":"a","ǎ":"a","ȁ":"a","ȃ":"a","ạ":"a","ậ":"a","ặ":"a","ḁ":"a","ą":"a","ⱥ":"a","ɐ":"a","ꜳ":"aa","æ":"ae","ǽ":"ae","ǣ":"ae","ꜵ":"ao","ꜷ":"au","ꜹ":"av","ꜻ":"av","ꜽ":"ay","ⓑ":"b","b":"b","ḃ":"b","ḅ":"b","ḇ":"b","ƀ":"b","ƃ":"b","ɓ":"b","ⓒ":"c","c":"c","ć":"c","ĉ":"c","ċ":"c","č":"c","ç":"c","ḉ":"c","ƈ":"c","ȼ":"c","ꜿ":"c","ↄ":"c","ⓓ":"d","d":"d","ḋ":"d","ď":"d","ḍ":"d","ḑ":"d","ḓ":"d","ḏ":"d","đ":"d","ƌ":"d","ɖ":"d","ɗ":"d","ꝺ":"d","dz":"dz","dž":"dz","ⓔ":"e","e":"e","è":"e","é":"e","ê":"e","ề":"e","ế":"e","ễ":"e","ể":"e","ẽ":"e","ē":"e","ḕ":"e","ḗ":"e","ĕ":"e","ė":"e","ë":"e","ẻ":"e","ě":"e","ȅ":"e","ȇ":"e","ẹ":"e","ệ":"e","ȩ":"e","ḝ":"e","ę":"e","ḙ":"e","ḛ":"e","ɇ":"e","ɛ":"e","ǝ":"e","ⓕ":"f","f":"f","ḟ":"f","ƒ":"f","ꝼ":"f","ⓖ":"g","g":"g","ǵ":"g","ĝ":"g","ḡ":"g","ğ":"g","ġ":"g","ǧ":"g","ģ":"g","ǥ":"g","ɠ":"g","ꞡ":"g","ᵹ":"g","ꝿ":"g","ⓗ":"h","h":"h","ĥ":"h","ḣ":"h","ḧ":"h","ȟ":"h","ḥ":"h","ḩ":"h","ḫ":"h","ẖ":"h","ħ":"h","ⱨ":"h","ⱶ":"h","ɥ":"h","ƕ":"hv","ⓘ":"i","i":"i","ì":"i","í":"i","î":"i","ĩ":"i","ī":"i","ĭ":"i","ï":"i","ḯ":"i","ỉ":"i","ǐ":"i","ȉ":"i","ȋ":"i","ị":"i","į":"i","ḭ":"i","ɨ":"i","ı":"i","ⓙ":"j","j":"j","ĵ":"j","ǰ":"j","ɉ":"j","ⓚ":"k","k":"k","ḱ":"k","ǩ":"k","ḳ":"k","ķ":"k","ḵ":"k","ƙ":"k","ⱪ":"k","ꝁ":"k","ꝃ":"k","ꝅ":"k","ꞣ":"k","ⓛ":"l","l":"l","ŀ":"l","ĺ":"l","ľ":"l","ḷ":"l","ḹ":"l","ļ":"l","ḽ":"l","ḻ":"l","ſ":"l","ł":"l","ƚ":"l","ɫ":"l","ⱡ":"l","ꝉ":"l","ꞁ":"l","ꝇ":"l","lj":"lj","ⓜ":"m","m":"m","ḿ":"m","ṁ":"m","ṃ":"m","ɱ":"m","ɯ":"m","ⓝ":"n","n":"n","ǹ":"n","ń":"n","ñ":"n","ṅ":"n","ň":"n","ṇ":"n","ņ":"n","ṋ":"n","ṉ":"n","ƞ":"n","ɲ":"n","ʼn":"n","ꞑ":"n","ꞥ":"n","nj":"nj","ⓞ":"o","o":"o","ò":"o","ó":"o","ô":"o","ồ":"o","ố":"o","ỗ":"o","ổ":"o","õ":"o","ṍ":"o","ȭ":"o","ṏ":"o","ō":"o","ṑ":"o","ṓ":"o","ŏ":"o","ȯ":"o","ȱ":"o","ö":"o","ȫ":"o","ỏ":"o","ő":"o","ǒ":"o","ȍ":"o","ȏ":"o","ơ":"o","ờ":"o","ớ":"o","ỡ":"o","ở":"o","ợ":"o","ọ":"o","ộ":"o","ǫ":"o","ǭ":"o","ø":"o","ǿ":"o","ɔ":"o","ꝋ":"o","ꝍ":"o","ɵ":"o","ƣ":"oi","ȣ":"ou","ꝏ":"oo","ⓟ":"p","p":"p","ṕ":"p","ṗ":"p","ƥ":"p","ᵽ":"p","ꝑ":"p","ꝓ":"p","ꝕ":"p","ⓠ":"q","q":"q","ɋ":"q","ꝗ":"q","ꝙ":"q","ⓡ":"r","r":"r","ŕ":"r","ṙ":"r","ř":"r","ȑ":"r","ȓ":"r","ṛ":"r","ṝ":"r","ŗ":"r","ṟ":"r","ɍ":"r","ɽ":"r","ꝛ":"r","ꞧ":"r","ꞃ":"r","ⓢ":"s","s":"s","ß":"s","ś":"s","ṥ":"s","ŝ":"s","ṡ":"s","š":"s","ṧ":"s","ṣ":"s","ṩ":"s","ș":"s","ş":"s","ȿ":"s","ꞩ":"s","ꞅ":"s","ẛ":"s","ⓣ":"t","t":"t","ṫ":"t","ẗ":"t","ť":"t","ṭ":"t","ț":"t","ţ":"t","ṱ":"t","ṯ":"t","ŧ":"t","ƭ":"t","ʈ":"t","ⱦ":"t","ꞇ":"t","ꜩ":"tz","ⓤ":"u","u":"u","ù":"u","ú":"u","û":"u","ũ":"u","ṹ":"u","ū":"u","ṻ":"u","ŭ":"u","ü":"u","ǜ":"u","ǘ":"u","ǖ":"u","ǚ":"u","ủ":"u","ů":"u","ű":"u","ǔ":"u","ȕ":"u","ȗ":"u","ư":"u","ừ":"u","ứ":"u","ữ":"u","ử":"u","ự":"u","ụ":"u","ṳ":"u","ų":"u","ṷ":"u","ṵ":"u","ʉ":"u","ⓥ":"v","v":"v","ṽ":"v","ṿ":"v","ʋ":"v","ꝟ":"v","ʌ":"v","ꝡ":"vy","ⓦ":"w","w":"w","ẁ":"w","ẃ":"w","ŵ":"w","ẇ":"w","ẅ":"w","ẘ":"w","ẉ":"w","ⱳ":"w","ⓧ":"x","x":"x","ẋ":"x","ẍ":"x","ⓨ":"y","y":"y","ỳ":"y","ý":"y","ŷ":"y","ỹ":"y","ȳ":"y","ẏ":"y","ÿ":"y","ỷ":"y","ẙ":"y","ỵ":"y","ƴ":"y","ɏ":"y","ỿ":"y","ⓩ":"z","z":"z","ź":"z","ẑ":"z","ż":"z","ž":"z","ẓ":"z","ẕ":"z","ƶ":"z","ȥ":"z","ɀ":"z","ⱬ":"z","ꝣ":"z","Ά":"Α","Έ":"Ε","Ή":"Η","Ί":"Ι","Ϊ":"Ι","Ό":"Ο","Ύ":"Υ","Ϋ":"Υ","Ώ":"Ω","ά":"α","έ":"ε","ή":"η","ί":"ι","ϊ":"ι","ΐ":"ι","ό":"ο","ύ":"υ","ϋ":"υ","ΰ":"υ","ω":"ω","ς":"σ"};return a}),b.define("select2/data/base",["../utils"],function(a){function b(){b.__super__.constructor.call(this)}return a.Extend(b,a.Observable),b.prototype.current=function(){throw new Error("The `current` method must be defined in child classes.")},b.prototype.query=function(){throw new Error("The `query` method must be defined in child classes.")},b.prototype.bind=function(){},b.prototype.destroy=function(){},b.prototype.generateResultId=function(b,c){var d=b.id+"-result-";return d+=a.generateChars(4),d+=null!=c.id?"-"+c.id.toString():"-"+a.generateChars(4)},b}),b.define("select2/data/select",["./base","../utils","jquery"],function(a,b,c){function d(a,b){this.$element=a,this.options=b,d.__super__.constructor.call(this)}return b.Extend(d,a),d.prototype.current=function(a){var b=[],d=this;this.$element.find(":selected").each(function(){var a=c(this),e=d.item(a);b.push(e)}),a(b)},d.prototype.select=function(a){var b=this;if(a.selected=!0,c(a.element).is("option"))return a.element.selected=!0,void this.$element.trigger("change");if(this.$element.prop("multiple"))this.current(function(d){var e=[];a=[a],a.push.apply(a,d);for(var f=0;f<a.length;f++){var g=a[f].id;-1===c.inArray(g,e)&&e.push(g)}b.$element.val(e),b.$element.trigger("change")});else{var d=a.id;this.$element.val(d),this.$element.trigger("change")}},d.prototype.unselect=function(a){var b=this;if(this.$element.prop("multiple"))return a.selected=!1,c(a.element).is("option")?(a.element.selected=!1,void this.$element.trigger("change")):void this.current(function(d){for(var e=[],f=0;f<d.length;f++){var g=d[f].id;g!==a.id&&-1===c.inArray(g,e)&&e.push(g)}b.$element.val(e),b.$element.trigger("change")})},d.prototype.bind=function(a){var b=this;this.container=a,a.on("select",function(a){b.select(a.data)}),a.on("unselect",function(a){b.unselect(a.data)})},d.prototype.destroy=function(){this.$element.find("*").each(function(){c.removeData(this,"data")})},d.prototype.query=function(a,b){var d=[],e=this,f=this.$element.children();f.each(function(){var b=c(this);if(b.is("option")||b.is("optgroup")){var f=e.item(b),g=e.matches(a,f);null!==g&&d.push(g)}}),b({results:d})},d.prototype.addOptions=function(a){b.appendMany(this.$element,a)},d.prototype.option=function(a){var b;a.children?(b=document.createElement("optgroup"),b.label=a.text):(b=document.createElement("option"),void 0!==b.textContent?b.textContent=a.text:b.innerText=a.text),a.id&&(b.value=a.id),a.disabled&&(b.disabled=!0),a.selected&&(b.selected=!0),a.title&&(b.title=a.title);var d=c(b),e=this._normalizeItem(a);return e.element=b,c.data(b,"data",e),d},d.prototype.item=function(a){var b={};
if(b=c.data(a[0],"data"),null!=b)return b;if(a.is("option"))b={id:a.val(),text:a.text(),disabled:a.prop("disabled"),selected:a.prop("selected"),title:a.prop("title")};else if(a.is("optgroup")){b={text:a.prop("label"),children:[],title:a.prop("title")};for(var d=a.children("option"),e=[],f=0;f<d.length;f++){var g=c(d[f]),h=this.item(g);e.push(h)}b.children=e}return b=this._normalizeItem(b),b.element=a[0],c.data(a[0],"data",b),b},d.prototype._normalizeItem=function(a){c.isPlainObject(a)||(a={id:a,text:a}),a=c.extend({},{text:""},a);var b={selected:!1,disabled:!1};return null!=a.id&&(a.id=a.id.toString()),null!=a.text&&(a.text=a.text.toString()),null==a._resultId&&a.id&&null!=this.container&&(a._resultId=this.generateResultId(this.container,a)),c.extend({},b,a)},d.prototype.matches=function(a,b){var c=this.options.get("matcher");return c(a,b)},d}),b.define("select2/data/array",["./select","../utils","jquery"],function(a,b,c){function d(a,b){var c=b.get("data")||[];d.__super__.constructor.call(this,a,b),this.addOptions(this.convertToOptions(c))}return b.Extend(d,a),d.prototype.select=function(a){var b=this.$element.find("option").filter(function(b,c){return c.value==a.id.toString()});0===b.length&&(b=this.option(a),this.addOptions(b)),d.__super__.select.call(this,a)},d.prototype.convertToOptions=function(a){function d(a){return function(){return c(this).val()==a.id}}for(var e=this,f=this.$element.find("option"),g=f.map(function(){return e.item(c(this)).id}).get(),h=[],i=0;i<a.length;i++){var j=this._normalizeItem(a[i]);if(c.inArray(j.id,g)>=0){var k=f.filter(d(j)),l=this.item(k),m=(c.extend(!0,{},l,j),this.option(l));k.replaceWith(m)}else{var n=this.option(j);if(j.children){var o=this.convertToOptions(j.children);b.appendMany(n,o)}h.push(n)}}return h},d}),b.define("select2/data/ajax",["./array","../utils","jquery"],function(a,b,c){function d(b,c){this.ajaxOptions=this._applyDefaults(c.get("ajax")),null!=this.ajaxOptions.processResults&&(this.processResults=this.ajaxOptions.processResults),a.__super__.constructor.call(this,b,c)}return b.Extend(d,a),d.prototype._applyDefaults=function(a){var b={data:function(a){return{q:a.term}},transport:function(a,b,d){var e=c.ajax(a);return e.then(b),e.fail(d),e}};return c.extend({},b,a,!0)},d.prototype.processResults=function(a){return a},d.prototype.query=function(a,b){function d(){var d=f.transport(f,function(d){var f=e.processResults(d,a);e.options.get("debug")&&window.console&&console.error&&(f&&f.results&&c.isArray(f.results)||console.error("Select2: The AJAX results did not return an array in the `results` key of the response.")),b(f)},function(){});e._request=d}var e=this;null!=this._request&&(c.isFunction(this._request.abort)&&this._request.abort(),this._request=null);var f=c.extend({type:"GET"},this.ajaxOptions);"function"==typeof f.url&&(f.url=f.url(a)),"function"==typeof f.data&&(f.data=f.data(a)),this.ajaxOptions.delay&&""!==a.term?(this._queryTimeout&&window.clearTimeout(this._queryTimeout),this._queryTimeout=window.setTimeout(d,this.ajaxOptions.delay)):d()},d}),b.define("select2/data/tags",["jquery"],function(a){function b(b,c,d){var e=d.get("tags"),f=d.get("createTag");if(void 0!==f&&(this.createTag=f),b.call(this,c,d),a.isArray(e))for(var g=0;g<e.length;g++){var h=e[g],i=this._normalizeItem(h),j=this.option(i);this.$element.append(j)}}return b.prototype.query=function(a,b,c){function d(a,f){for(var g=a.results,h=0;h<g.length;h++){var i=g[h],j=null!=i.children&&!d({results:i.children},!0),k=i.text===b.term;if(k||j)return f?!1:(a.data=g,void c(a))}if(f)return!0;var l=e.createTag(b);if(null!=l){var m=e.option(l);m.attr("data-select2-tag",!0),e.addOptions([m]),e.insertTag(g,l)}a.results=g,c(a)}var e=this;return this._removeOldTags(),null==b.term||null!=b.page?void a.call(this,b,c):void a.call(this,b,d)},b.prototype.createTag=function(b,c){var d=a.trim(c.term);return""===d?null:{id:d,text:d}},b.prototype.insertTag=function(a,b,c){b.unshift(c)},b.prototype._removeOldTags=function(){var b=(this._lastTag,this.$element.find("option[data-select2-tag]"));b.each(function(){this.selected||a(this).remove()})},b}),b.define("select2/data/tokenizer",["jquery"],function(a){function b(a,b,c){var d=c.get("tokenizer");void 0!==d&&(this.tokenizer=d),a.call(this,b,c)}return b.prototype.bind=function(a,b,c){a.call(this,b,c),this.$search=b.dropdown.$search||b.selection.$search||c.find(".select2-search__field")},b.prototype.query=function(a,b,c){function d(a){e.select(a)}var e=this;b.term=b.term||"";var f=this.tokenizer(b,this.options,d);f.term!==b.term&&(this.$search.length&&(this.$search.val(f.term),this.$search.focus()),b.term=f.term),a.call(this,b,c)},b.prototype.tokenizer=function(b,c,d,e){for(var f=d.get("tokenSeparators")||[],g=c.term,h=0,i=this.createTag||function(a){return{id:a.term,text:a.term}};h<g.length;){var j=g[h];if(-1!==a.inArray(j,f)){var k=g.substr(0,h),l=a.extend({},c,{term:k}),m=i(l);e(m),g=g.substr(h+1)||"",h=0}else h++}return{term:g}},b}),b.define("select2/data/minimumInputLength",[],function(){function a(a,b,c){this.minimumInputLength=c.get("minimumInputLength"),a.call(this,b,c)}return a.prototype.query=function(a,b,c){return b.term=b.term||"",b.term.length<this.minimumInputLength?void this.trigger("results:message",{message:"inputTooShort",args:{minimum:this.minimumInputLength,input:b.term,params:b}}):void a.call(this,b,c)},a}),b.define("select2/data/maximumInputLength",[],function(){function a(a,b,c){this.maximumInputLength=c.get("maximumInputLength"),a.call(this,b,c)}return a.prototype.query=function(a,b,c){return b.term=b.term||"",this.maximumInputLength>0&&b.term.length>this.maximumInputLength?void this.trigger("results:message",{message:"inputTooLong",args:{maximum:this.maximumInputLength,input:b.term,params:b}}):void a.call(this,b,c)},a}),b.define("select2/data/maximumSelectionLength",[],function(){function a(a,b,c){this.maximumSelectionLength=c.get("maximumSelectionLength"),a.call(this,b,c)}return a.prototype.query=function(a,b,c){var d=this;this.current(function(e){var f=null!=e?e.length:0;return d.maximumSelectionLength>0&&f>=d.maximumSelectionLength?void d.trigger("results:message",{message:"maximumSelected",args:{maximum:d.maximumSelectionLength}}):void a.call(d,b,c)})},a}),b.define("select2/dropdown",["jquery","./utils"],function(a,b){function c(a,b){this.$element=a,this.options=b,c.__super__.constructor.call(this)}return b.Extend(c,b.Observable),c.prototype.render=function(){var b=a('<span class="select2-dropdown"><span class="select2-results"></span></span>');return b.attr("dir",this.options.get("dir")),this.$dropdown=b,b},c.prototype.position=function(){},c.prototype.destroy=function(){this.$dropdown.remove()},c}),b.define("select2/dropdown/search",["jquery","../utils"],function(a){function b(){}return b.prototype.render=function(b){var c=b.call(this),d=a('<span class="select2-search select2-search--dropdown"><input class="select2-search__field" type="search" tabindex="-1" autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false" role="textbox" /></span>');return this.$searchContainer=d,this.$search=d.find("input"),c.prepend(d),c},b.prototype.bind=function(b,c,d){var e=this;b.call(this,c,d),this.$search.on("keydown",function(a){e.trigger("keypress",a),e._keyUpPrevented=a.isDefaultPrevented()}),this.$search.on("input",function(){a(this).off("keyup")}),this.$search.on("keyup input",function(a){e.handleSearch(a)}),c.on("open",function(){e.$search.attr("tabindex",0),e.$search.focus(),window.setTimeout(function(){e.$search.focus()},0)}),c.on("close",function(){e.$search.attr("tabindex",-1),e.$search.val("")}),c.on("results:all",function(a){if(null==a.query.term||""===a.query.term){var b=e.showSearch(a);b?e.$searchContainer.removeClass("select2-search--hide"):e.$searchContainer.addClass("select2-search--hide")}})},b.prototype.handleSearch=function(){if(!this._keyUpPrevented){var a=this.$search.val();this.trigger("query",{term:a})}this._keyUpPrevented=!1},b.prototype.showSearch=function(){return!0},b}),b.define("select2/dropdown/hidePlaceholder",[],function(){function a(a,b,c,d){this.placeholder=this.normalizePlaceholder(c.get("placeholder")),a.call(this,b,c,d)}return a.prototype.append=function(a,b){b.results=this.removePlaceholder(b.results),a.call(this,b)},a.prototype.normalizePlaceholder=function(a,b){return"string"==typeof b&&(b={id:"",text:b}),b},a.prototype.removePlaceholder=function(a,b){for(var c=b.slice(0),d=b.length-1;d>=0;d--){var e=b[d];this.placeholder.id===e.id&&c.splice(d,1)}return c},a}),b.define("select2/dropdown/infiniteScroll",["jquery"],function(a){function b(a,b,c,d){this.lastParams={},a.call(this,b,c,d),this.$loadingMore=this.createLoadingMore(),this.loading=!1}return b.prototype.append=function(a,b){this.$loadingMore.remove(),this.loading=!1,a.call(this,b),this.showLoadingMore(b)&&this.$results.append(this.$loadingMore)},b.prototype.bind=function(b,c,d){var e=this;b.call(this,c,d),c.on("query",function(a){e.lastParams=a,e.loading=!0}),c.on("query:append",function(a){e.lastParams=a,e.loading=!0}),this.$results.on("scroll",function(){var b=a.contains(document.documentElement,e.$loadingMore[0]);if(!e.loading&&b){var c=e.$results.offset().top+e.$results.outerHeight(!1),d=e.$loadingMore.offset().top+e.$loadingMore.outerHeight(!1);c+50>=d&&e.loadMore()}})},b.prototype.loadMore=function(){this.loading=!0;var b=a.extend({},{page:1},this.lastParams);b.page++,this.trigger("query:append",b)},b.prototype.showLoadingMore=function(a,b){return b.pagination&&b.pagination.more},b.prototype.createLoadingMore=function(){var b=a('<li class="option load-more" role="treeitem"></li>'),c=this.options.get("translations").get("loadingMore");return b.html(c(this.lastParams)),b},b}),b.define("select2/dropdown/attachBody",["jquery","../utils"],function(a,b){function c(a,b,c){this.$dropdownParent=c.get("dropdownParent")||document.body,a.call(this,b,c)}return c.prototype.bind=function(a,b,c){var d=this,e=!1;a.call(this,b,c),b.on("open",function(){d._showDropdown(),d._attachPositioningHandler(b),e||(e=!0,b.on("results:all",function(){d._positionDropdown(),d._resizeDropdown()}),b.on("results:append",function(){d._positionDropdown(),d._resizeDropdown()}))}),b.on("close",function(){d._hideDropdown(),d._detachPositioningHandler(b)}),this.$dropdownContainer.on("mousedown",function(a){a.stopPropagation()})},c.prototype.position=function(a,b,c){b.attr("class",c.attr("class")),b.removeClass("select2"),b.addClass("select2-container--open"),b.css({position:"absolute",top:-999999}),this.$container=c},c.prototype.render=function(b){var c=a("<span></span>"),d=b.call(this);return c.append(d),this.$dropdownContainer=c,c},c.prototype._hideDropdown=function(){this.$dropdownContainer.detach()},c.prototype._attachPositioningHandler=function(c){var d=this,e="scroll.select2."+c.id,f="resize.select2."+c.id,g="orientationchange.select2."+c.id,h=this.$container.parents().filter(b.hasScroll);h.each(function(){a(this).data("select2-scroll-position",{x:a(this).scrollLeft(),y:a(this).scrollTop()})}),h.on(e,function(){var b=a(this).data("select2-scroll-position");a(this).scrollTop(b.y)}),a(window).on(e+" "+f+" "+g,function(){d._positionDropdown(),d._resizeDropdown()})},c.prototype._detachPositioningHandler=function(c){var d="scroll.select2."+c.id,e="resize.select2."+c.id,f="orientationchange.select2."+c.id,g=this.$container.parents().filter(b.hasScroll);g.off(d),a(window).off(d+" "+e+" "+f)},c.prototype._positionDropdown=function(){var b=a(window),c=this.$dropdown.hasClass("select2-dropdown--above"),d=this.$dropdown.hasClass("select2-dropdown--below"),e=null,f=(this.$container.position(),this.$container.offset());f.bottom=f.top+this.$container.outerHeight(!1);var g={height:this.$container.outerHeight(!1)};g.top=f.top,g.bottom=f.top+g.height;var h={height:this.$dropdown.outerHeight(!1)},i={top:b.scrollTop(),bottom:b.scrollTop()+b.height()},j=i.top<f.top-h.height,k=i.bottom>f.bottom+h.height,l={left:f.left,top:g.bottom};c||d||(e="below"),k||!j||c?!j&&k&&c&&(e="below"):e="above",("above"==e||c&&"below"!==e)&&(l.top=g.top-h.height),null!=e&&(this.$dropdown.removeClass("select2-dropdown--below select2-dropdown--above").addClass("select2-dropdown--"+e),this.$container.removeClass("select2-container--below select2-container--above").addClass("select2-container--"+e)),this.$dropdownContainer.css(l)},c.prototype._resizeDropdown=function(){this.$dropdownContainer.width();var a={width:this.$container.outerWidth(!1)+"px"};this.options.get("dropdownAutoWidth")&&(a.minWidth=a.width,a.width="auto"),this.$dropdown.css(a)},c.prototype._showDropdown=function(){this.$dropdownContainer.appendTo(this.$dropdownParent),this._positionDropdown(),this._resizeDropdown()},c}),b.define("select2/dropdown/minimumResultsForSearch",[],function(){function a(b){for(var c=0,d=0;d<b.length;d++){var e=b[d];e.children?c+=a(e.children):c++}return c}function b(a,b,c,d){this.minimumResultsForSearch=c.get("minimumResultsForSearch"),this.minimumResultsForSearch<0&&(this.minimumResultsForSearch=1/0),a.call(this,b,c,d)}return b.prototype.showSearch=function(b,c){return a(c.data.results)<this.minimumResultsForSearch?!1:b.call(this,c)},b}),b.define("select2/dropdown/selectOnClose",[],function(){function a(){}return a.prototype.bind=function(a,b,c){var d=this;a.call(this,b,c),b.on("close",function(){d._handleSelectOnClose()})},a.prototype._handleSelectOnClose=function(){var a=this.getHighlightedResults();a.length<1||this.trigger("select",{data:a.data("data")})},a}),b.define("select2/dropdown/closeOnSelect",[],function(){function a(){}return a.prototype.bind=function(a,b,c){var d=this;a.call(this,b,c),b.on("select",function(a){d._selectTriggered(a)}),b.on("unselect",function(a){d._selectTriggered(a)})},a.prototype._selectTriggered=function(a,b){var c=b.originalEvent;c&&c.ctrlKey||this.trigger("close")},a}),b.define("select2/i18n/en",[],function(){return{errorLoading:function(){return"The results could not be loaded."},inputTooLong:function(a){var b=a.input.length-a.maximum,c="Please delete "+b+" character";return 1!=b&&(c+="s"),c},inputTooShort:function(a){var b=a.minimum-a.input.length,c="Please enter "+b+" or more characters";return c},loadingMore:function(){return"Loading more results…"},maximumSelected:function(a){var b="You can only select "+a.maximum+" item";return 1!=a.maximum&&(b+="s"),b},noResults:function(){return"No results found"},searching:function(){return"Searching…"}}}),b.define("select2/defaults",["jquery","require","./results","./selection/single","./selection/multiple","./selection/placeholder","./selection/allowClear","./selection/search","./selection/eventRelay","./utils","./translation","./diacritics","./data/select","./data/array","./data/ajax","./data/tags","./data/tokenizer","./data/minimumInputLength","./data/maximumInputLength","./data/maximumSelectionLength","./dropdown","./dropdown/search","./dropdown/hidePlaceholder","./dropdown/infiniteScroll","./dropdown/attachBody","./dropdown/minimumResultsForSearch","./dropdown/selectOnClose","./dropdown/closeOnSelect","./i18n/en"],function(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,A,B,C){function D(){this.reset()}D.prototype.apply=function(l){if(l=a.extend({},this.defaults,l),null==l.dataAdapter){if(l.dataAdapter=null!=l.ajax?o:null!=l.data?n:m,l.minimumInputLength>0&&(l.dataAdapter=j.Decorate(l.dataAdapter,r)),l.maximumInputLength>0&&(l.dataAdapter=j.Decorate(l.dataAdapter,s)),l.maximumSelectionLength>0&&(l.dataAdapter=j.Decorate(l.dataAdapter,t)),l.tags&&(l.dataAdapter=j.Decorate(l.dataAdapter,p)),(null!=l.tokenSeparators||null!=l.tokenizer)&&(l.dataAdapter=j.Decorate(l.dataAdapter,q)),null!=l.query){var C=b(l.amdBase+"compat/query");l.dataAdapter=j.Decorate(l.dataAdapter,C)}if(null!=l.initSelection){var D=b(l.amdBase+"compat/initSelection");l.dataAdapter=j.Decorate(l.dataAdapter,D)}}if(null==l.resultsAdapter&&(l.resultsAdapter=c,null!=l.ajax&&(l.resultsAdapter=j.Decorate(l.resultsAdapter,x)),null!=l.placeholder&&(l.resultsAdapter=j.Decorate(l.resultsAdapter,w)),l.selectOnClose&&(l.resultsAdapter=j.Decorate(l.resultsAdapter,A))),null==l.dropdownAdapter){if(l.multiple)l.dropdownAdapter=u;else{var E=j.Decorate(u,v);l.dropdownAdapter=E}if(0!==l.minimumResultsForSearch&&(l.dropdownAdapter=j.Decorate(l.dropdownAdapter,z)),l.closeOnSelect&&(l.dropdownAdapter=j.Decorate(l.dropdownAdapter,B)),null!=l.dropdownCssClass||null!=l.dropdownCss||null!=l.adaptDropdownCssClass){var F=b(l.amdBase+"compat/dropdownCss");l.dropdownAdapter=j.Decorate(l.dropdownAdapter,F)}l.dropdownAdapter=j.Decorate(l.dropdownAdapter,y)}if(null==l.selectionAdapter){if(l.selectionAdapter=l.multiple?e:d,null!=l.placeholder&&(l.selectionAdapter=j.Decorate(l.selectionAdapter,f)),l.allowClear&&(l.selectionAdapter=j.Decorate(l.selectionAdapter,g)),l.multiple&&(l.selectionAdapter=j.Decorate(l.selectionAdapter,h)),null!=l.containerCssClass||null!=l.containerCss||null!=l.adaptContainerCssClass){var G=b(l.amdBase+"compat/containerCss");l.selectionAdapter=j.Decorate(l.selectionAdapter,G)}l.selectionAdapter=j.Decorate(l.selectionAdapter,i)}if("string"==typeof l.language)if(l.language.indexOf("-")>0){var H=l.language.split("-"),I=H[0];l.language=[l.language,I]}else l.language=[l.language];if(a.isArray(l.language)){var J=new k;l.language.push("en");for(var K=l.language,L=0;L<K.length;L++){var M=K[L],N={};try{N=k.loadPath(M)}catch(O){try{M=this.defaults.amdLanguageBase+M,N=k.loadPath(M)}catch(P){l.debug&&window.console&&console.warn&&console.warn('Select2: The language file for "'+M+'" could not be automatically loaded. A fallback will be used instead.');continue}}J.extend(N)}l.translations=J}else{var Q=k.loadPath(this.defaults.amdLanguageBase+"en"),R=new k(l.language);R.extend(Q),l.translations=R}return l},D.prototype.reset=function(){function b(a){function b(a){return l[a]||a}return a.replace(/[^\u0000-\u007E]/g,b)}function c(d,e){if(""===a.trim(d.term))return e;if(e.children&&e.children.length>0){for(var f=a.extend(!0,{},e),g=e.children.length-1;g>=0;g--){var h=e.children[g],i=c(d,h);null==i&&f.children.splice(g,1)}return f.children.length>0?f:c(d,f)}var j=b(e.text).toUpperCase(),k=b(d.term).toUpperCase();return j.indexOf(k)>-1?e:null}this.defaults={amdBase:"./",amdLanguageBase:"./i18n/",closeOnSelect:!0,debug:!1,dropdownAutoWidth:!1,escapeMarkup:j.escapeMarkup,language:C,matcher:c,minimumInputLength:0,maximumInputLength:0,maximumSelectionLength:0,minimumResultsForSearch:0,selectOnClose:!1,sorter:function(a){return a},templateResult:function(a){return a.text},templateSelection:function(a){return a.text},theme:"default",width:"resolve"}},D.prototype.set=function(b,c){var d=a.camelCase(b),e={};e[d]=c;var f=j._convertData(e);a.extend(this.defaults,f)};var E=new D;return E}),b.define("select2/options",["require","jquery","./defaults","./utils"],function(a,b,c,d){function e(b,e){if(this.options=b,null!=e&&this.fromElement(e),this.options=c.apply(this.options),e&&e.is("input")){var f=a(this.get("amdBase")+"compat/inputData");this.options.dataAdapter=d.Decorate(this.options.dataAdapter,f)}}return e.prototype.fromElement=function(a){var c=["select2"];null==this.options.multiple&&(this.options.multiple=a.prop("multiple")),null==this.options.disabled&&(this.options.disabled=a.prop("disabled")),null==this.options.language&&(a.prop("lang")?this.options.language=a.prop("lang").toLowerCase():a.closest("[lang]").prop("lang")&&(this.options.language=a.closest("[lang]").prop("lang"))),null==this.options.dir&&(this.options.dir=a.prop("dir")?a.prop("dir"):a.closest("[dir]").prop("dir")?a.closest("[dir]").prop("dir"):"ltr"),a.prop("disabled",this.options.disabled),a.prop("multiple",this.options.multiple),a.data("select2Tags")&&(this.options.debug&&window.console&&console.warn&&console.warn('Select2: The `data-select2-tags` attribute has been changed to use the `data-data` and `data-tags="true"` attributes and will be removed in future versions of Select2.'),a.data("data",a.data("select2Tags")),a.data("tags",!0)),a.data("ajaxUrl")&&(this.options.debug&&window.console&&console.warn&&console.warn("Select2: The `data-ajax-url` attribute has been changed to `data-ajax--url` and support for the old attribute will be removed in future versions of Select2."),a.attr("ajax--url",a.data("ajaxUrl")),a.data("ajax--url",a.data("ajaxUrl")));var e={};e=b.fn.jquery&&"1."==b.fn.jquery.substr(0,2)&&a[0].dataset?b.extend(!0,{},a[0].dataset,a.data()):a.data();var f=b.extend(!0,{},e);f=d._convertData(f);for(var g in f)b.inArray(g,c)>-1||(b.isPlainObject(this.options[g])?b.extend(this.options[g],f[g]):this.options[g]=f[g]);return this},e.prototype.get=function(a){return this.options[a]},e.prototype.set=function(a,b){this.options[a]=b},e}),b.define("select2/core",["jquery","./options","./utils","./keys"],function(a,b,c,d){var e=function(a,c){null!=a.data("select2")&&a.data("select2").destroy(),this.$element=a,this.id=this._generateId(a),c=c||{},this.options=new b(c,a),e.__super__.constructor.call(this);var d=a.attr("tabindex")||0;a.data("old-tabindex",d),a.attr("tabindex","-1");var f=this.options.get("dataAdapter");this.dataAdapter=new f(a,this.options);var g=this.render();this._placeContainer(g);var h=this.options.get("selectionAdapter");this.selection=new h(a,this.options),this.$selection=this.selection.render(),this.selection.position(this.$selection,g);var i=this.options.get("dropdownAdapter");this.dropdown=new i(a,this.options),this.$dropdown=this.dropdown.render(),this.dropdown.position(this.$dropdown,g);var j=this.options.get("resultsAdapter");this.results=new j(a,this.options,this.dataAdapter),this.$results=this.results.render(),this.results.position(this.$results,this.$dropdown);var k=this;this._bindAdapters(),this._registerDomEvents(),this._registerDataEvents(),this._registerSelectionEvents(),this._registerDropdownEvents(),this._registerResultsEvents(),this._registerEvents(),this.dataAdapter.current(function(a){k.trigger("selection:update",{data:a})}),a.addClass("select2-hidden-accessible"),a.attr("aria-hidden","true"),this._syncAttributes(),a.data("select2",this)};return c.Extend(e,c.Observable),e.prototype._generateId=function(a){var b="";return b=null!=a.attr("id")?a.attr("id"):null!=a.attr("name")?a.attr("name")+"-"+c.generateChars(2):c.generateChars(4),b="select2-"+b},e.prototype._placeContainer=function(a){a.insertAfter(this.$element);var b=this._resolveWidth(this.$element,this.options.get("width"));null!=b&&a.css("width",b)},e.prototype._resolveWidth=function(a,b){var c=/^width:(([-+]?([0-9]*\.)?[0-9]+)(px|em|ex|%|in|cm|mm|pt|pc))/i;if("resolve"==b){var d=this._resolveWidth(a,"style");return null!=d?d:this._resolveWidth(a,"element")}if("element"==b){var e=a.outerWidth(!1);return 0>=e?"auto":e+"px"}if("style"==b){var f=a.attr("style");if("string"!=typeof f)return null;for(var g=f.split(";"),h=0,i=g.length;i>h;h+=1){var j=g[h].replace(/\s/g,""),k=j.match(c);if(null!==k&&k.length>=1)return k[1]}return null}return b},e.prototype._bindAdapters=function(){this.dataAdapter.bind(this,this.$container),this.selection.bind(this,this.$container),this.dropdown.bind(this,this.$container),this.results.bind(this,this.$container)},e.prototype._registerDomEvents=function(){var b=this;this.$element.on("change.select2",function(){b.dataAdapter.current(function(a){b.trigger("selection:update",{data:a})})}),this._sync=c.bind(this._syncAttributes,this),this.$element[0].attachEvent&&this.$element[0].attachEvent("onpropertychange",this._sync);var d=window.MutationObserver||window.WebKitMutationObserver||window.MozMutationObserver;null!=d?(this._observer=new d(function(c){a.each(c,b._sync)}),this._observer.observe(this.$element[0],{attributes:!0,subtree:!1})):this.$element[0].addEventListener&&this.$element[0].addEventListener("DOMAttrModified",b._sync,!1)},e.prototype._registerDataEvents=function(){var a=this;this.dataAdapter.on("*",function(b,c){a.trigger(b,c)})},e.prototype._registerSelectionEvents=function(){var b=this,c=["toggle"];this.selection.on("toggle",function(){b.toggleDropdown()}),this.selection.on("*",function(d,e){-1===a.inArray(d,c)&&b.trigger(d,e)})},e.prototype._registerDropdownEvents=function(){var a=this;this.dropdown.on("*",function(b,c){a.trigger(b,c)})},e.prototype._registerResultsEvents=function(){var a=this;this.results.on("*",function(b,c){a.trigger(b,c)})},e.prototype._registerEvents=function(){var a=this;this.on("open",function(){a.$container.addClass("select2-container--open")}),this.on("close",function(){a.$container.removeClass("select2-container--open")}),this.on("enable",function(){a.$container.removeClass("select2-container--disabled")}),this.on("disable",function(){a.$container.addClass("select2-container--disabled")}),this.on("focus",function(){a.$container.addClass("select2-container--focus")}),this.on("blur",function(){a.$container.removeClass("select2-container--focus")}),this.on("query",function(b){a.isOpen()||a.trigger("open"),this.dataAdapter.query(b,function(c){a.trigger("results:all",{data:c,query:b})})}),this.on("query:append",function(b){this.dataAdapter.query(b,function(c){a.trigger("results:append",{data:c,query:b})})}),this.on("keypress",function(b){var c=b.which;a.isOpen()?c===d.ENTER?(a.trigger("results:select"),b.preventDefault()):c===d.SPACE&&b.ctrlKey?(a.trigger("results:toggle"),b.preventDefault()):c===d.UP?(a.trigger("results:previous"),b.preventDefault()):c===d.DOWN?(a.trigger("results:next"),b.preventDefault()):(c===d.ESC||c===d.TAB)&&(a.close(),b.preventDefault()):(c===d.ENTER||c===d.SPACE||(c===d.DOWN||c===d.UP)&&b.altKey)&&(a.open(),b.preventDefault())})},e.prototype._syncAttributes=function(){this.options.set("disabled",this.$element.prop("disabled")),this.options.get("disabled")?(this.isOpen()&&this.close(),this.trigger("disable")):this.trigger("enable")},e.prototype.trigger=function(a,b){var c=e.__super__.trigger,d={open:"opening",close:"closing",select:"selecting",unselect:"unselecting"};if(a in d){var f=d[a],g={prevented:!1,name:a,args:b};if(c.call(this,f,g),g.prevented)return void(b.prevented=!0)}c.call(this,a,b)},e.prototype.toggleDropdown=function(){this.options.get("disabled")||(this.isOpen()?this.close():this.open())},e.prototype.open=function(){this.isOpen()||(this.trigger("query",{}),this.trigger("open"))},e.prototype.close=function(){this.isOpen()&&this.trigger("close")},e.prototype.isOpen=function(){return this.$container.hasClass("select2-container--open")},e.prototype.enable=function(a){this.options.get("debug")&&window.console&&console.warn&&console.warn('Select2: The `select2("enable")` method has been deprecated and will be removed in later Select2 versions. Use $element.prop("disabled") instead.'),(null==a||0===a.length)&&(a=[!0]);var b=!a[0];this.$element.prop("disabled",b)},e.prototype.data=function(){this.options.get("debug")&&arguments.length>0&&window.console&&console.warn&&console.warn('Select2: Data can no longer be set using `select2("data")`. You should consider setting the value instead using `$element.val()`.');var a=[];return this.dataAdapter.current(function(b){a=b}),a},e.prototype.val=function(b){if(this.options.get("debug")&&window.console&&console.warn&&console.warn('Select2: The `select2("val")` method has been deprecated and will be removed in later Select2 versions. Use $element.val() instead.'),null==b||0===b.length)return this.$element.val();var c=b[0];a.isArray(c)&&(c=a.map(c,function(a){return a.toString()})),this.$element.val(c).trigger("change")},e.prototype.destroy=function(){this.$container.remove(),this.$element[0].detachEvent&&this.$element[0].detachEvent("onpropertychange",this._sync),null!=this._observer?(this._observer.disconnect(),this._observer=null):this.$element[0].removeEventListener&&this.$element[0].removeEventListener("DOMAttrModified",this._sync,!1),this._sync=null,this.$element.off(".select2"),this.$element.attr("tabindex",this.$element.data("old-tabindex")),this.$element.removeClass("select2-hidden-accessible"),this.$element.attr("aria-hidden","false"),this.$element.removeData("select2"),this.dataAdapter.destroy(),this.selection.destroy(),this.dropdown.destroy(),this.results.destroy(),this.dataAdapter=null,this.selection=null,this.dropdown=null,this.results=null},e.prototype.render=function(){var b=a('<span class="select2 select2-container"><span class="selection"></span><span class="dropdown-wrapper" aria-hidden="true"></span></span>');return b.attr("dir",this.options.get("dir")),this.$container=b,this.$container.addClass("select2-container--"+this.options.get("theme")),b.data("element",this.$element),b},e}),b.define("jquery.select2",["jquery","require","./select2/core","./select2/defaults"],function(a,b,c,d){if(b("jquery.mousewheel"),null==a.fn.select2){var e=["open","close","destroy"];a.fn.select2=function(b){if(b=b||{},"object"==typeof b)return this.each(function(){{var d=a.extend({},b,!0);new c(a(this),d)}}),this;if("string"==typeof b){var d=this.data("select2");null==d&&window.console&&console.error&&console.error("The select2('"+b+"') method was called on an element that is not using Select2.");var f=Array.prototype.slice.call(arguments,1),g=d[b](f);return a.inArray(b,e)>-1?this:g}throw new Error("Invalid arguments for Select2: "+b)}}return null==a.fn.select2.defaults&&(a.fn.select2.defaults=d),c}),b.define("jquery.mousewheel",["jquery"],function(a){return a}),{define:b.define,require:b.require}}(),c=b.require("jquery.select2");return a.fn.select2.amd=b,c}); | static/select2.min.js | 0 | https://github.com/apache/superset/commit/6dd81a3e95a9d67be743815ff9bfcd465278b3e9 | [
0.00017048137669917196,
0.00017048137669917196,
0.00017048137669917196,
0.00017048137669917196,
0
] |
{
"id": 5,
"code_window": [
"class TableColumnInlineView(CompactCRUDMixin, ModelView):\n",
" datamodel = SQLAInterface(models.TableColumn)\n",
" can_delete = False\n",
" edit_columns = [\n",
" 'column_name', 'description', 'table', 'groupby', 'filterable',\n",
" 'count_distinct', 'sum', 'min', 'max']\n",
" list_columns = [\n",
" 'column_name', 'type', 'groupby', 'filterable', 'count_distinct',\n",
" 'sum', 'min', 'max']\n",
" page_size = 100\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" 'column_name', 'description', 'groupby', 'filterable', 'table',\n"
],
"file_path": "panoramix/views.py",
"type": "replace",
"edit_start_line_idx": 32
} | from flask.ext.appbuilder import Model
from datetime import timedelta
from flask.ext.appbuilder.models.mixins import AuditMixin
from flask import request, redirect, flash, Response
from sqlalchemy import Column, Integer, String, ForeignKey, Text, Boolean, DateTime
from sqlalchemy import create_engine, MetaData, desc
from sqlalchemy import Table as sqlaTable
from sqlalchemy.orm import relationship
from dateutil.parser import parse
from pydruid import client
from pydruid.utils.filters import Dimension, Filter
from pandas import read_sql_query
from sqlalchemy.sql import table, literal_column
from sqlalchemy import select, and_, text, String
from copy import deepcopy, copy
from collections import namedtuple
from datetime import datetime
import logging
import json
import sqlparse
import requests
import textwrap
from panoramix import db, get_session
QueryResult = namedtuple('namedtuple', ['df', 'query', 'duration'])
class Queryable(object):
@property
def column_names(self):
return sorted([c.column_name for c in self.columns])
@property
def groupby_column_names(self):
return sorted([c.column_name for c in self.columns if c.groupby])
@property
def filterable_column_names(self):
return sorted([c.column_name for c in self.columns if c.filterable])
class Database(Model, AuditMixin):
__tablename__ = 'dbs'
id = Column(Integer, primary_key=True)
database_name = Column(String(255), unique=True)
sqlalchemy_uri = Column(String(1024))
def __repr__(self):
return self.database_name
def get_sqla_engine(self):
return create_engine(self.sqlalchemy_uri)
def get_table(self, table_name):
meta = MetaData()
return sqlaTable(
table_name, meta,
autoload=True,
autoload_with=self.get_sqla_engine())
class Table(Model, Queryable, AuditMixin):
__tablename__ = 'tables'
id = Column(Integer, primary_key=True)
table_name = Column(String(255), unique=True)
main_datetime_column_id = Column(Integer, ForeignKey('table_columns.id'))
main_datetime_column = relationship(
'TableColumn', foreign_keys=[main_datetime_column_id])
default_endpoint = Column(Text)
database_id = Column(Integer, ForeignKey('dbs.id'), nullable=False)
database = relationship(
'Database', backref='tables', foreign_keys=[database_id])
baselink = "tableview"
@property
def name(self):
return self.table_name
@property
def table_link(self):
url = "/panoramix/table/{}/".format(self.id)
return '<a href="{url}">{self.table_name}</a>'.format(**locals())
@property
def metrics_combo(self):
return sorted(
[
(m.metric_name, m.verbose_name)
for m in self.metrics],
key=lambda x: x[1])
def query_bkp(
self, groupby, metrics,
granularity,
from_dttm, to_dttm,
limit_spec=None,
filter=None,
is_timeseries=True,
timeseries_limit=15, row_limit=None):
"""
Unused, legacy way of querying by building a SQL string without
using the sqlalchemy expression API (new approach which supports
all dialects)
"""
from pandas import read_sql_query
qry_start_dttm = datetime.now()
metrics_exprs = [
"{} AS {}".format(m.expression, m.metric_name)
for m in self.metrics if m.metric_name in metrics]
from_dttm_iso = from_dttm.isoformat()
to_dttm_iso = to_dttm.isoformat()
if metrics:
main_metric_expr = [m.expression for m in self.metrics if m.metric_name == metrics[0]][0]
else:
main_metric_expr = "COUNT(*)"
select_exprs = []
groupby_exprs = []
if groupby:
select_exprs = copy(groupby)
groupby_exprs = [s for s in groupby]
inner_groupby_exprs = [s for s in groupby]
select_exprs += metrics_exprs
if granularity != "all":
select_exprs += ['ds as timestamp']
groupby_exprs += ['ds']
select_exprs = ",\n".join(select_exprs)
groupby_exprs = ",\n".join(groupby_exprs)
where_clause = [
"ds >= '{from_dttm_iso}'",
"ds < '{to_dttm_iso}'"
]
for col, op, eq in filter:
if op in ('in', 'not in'):
l = ["'{}'".format(s) for s in eq.split(",")]
l = ", ".join(l)
op = op.upper()
where_clause.append(
"{col} {op} ({l})".format(**locals())
)
where_clause = " AND\n".join(where_clause).format(**locals())
on_clause = " AND ".join(["{g} = __{g}".format(g=g) for g in groupby])
limiting_join = ""
if timeseries_limit and groupby:
inner_select = ", ".join(["{g} as __{g}".format(g=g) for g in inner_groupby_exprs])
inner_groupby_exprs = ", ".join(inner_groupby_exprs)
limiting_join = (
"JOIN ( \n"
" SELECT {inner_select} \n"
" FROM {self.table_name} \n"
" WHERE \n"
" {where_clause}\n"
" GROUP BY {inner_groupby_exprs}\n"
" ORDER BY {main_metric_expr} DESC\n"
" LIMIT {timeseries_limit}\n"
") z ON {on_clause}\n"
).format(**locals())
sql = (
"SELECT\n"
" {select_exprs}\n"
"FROM {self.table_name}\n"
"{limiting_join}"
"WHERE\n"
" {where_clause}\n"
"GROUP BY\n"
" {groupby_exprs}\n"
).format(**locals())
df = read_sql_query(
sql=sql,
con=self.database.get_sqla_engine()
)
textwrap.dedent(sql)
return QueryResult(
df=df, duration=datetime.now() - qry_start_dttm, query=sql)
def query(
self, groupby, metrics,
granularity,
from_dttm, to_dttm,
limit_spec=None,
filter=None,
is_timeseries=True,
timeseries_limit=15, row_limit=None):
qry_start_dttm = datetime.now()
timestamp = literal_column(
self.main_datetime_column.column_name).label('timestamp')
metrics_exprs = [
literal_column(m.expression).label(m.metric_name)
for m in self.metrics if m.metric_name in metrics]
if metrics:
main_metric_expr = literal_column(
[m.expression for m in self.metrics if m.metric_name == metrics[0]][0])
else:
main_metric_expr = literal_column("COUNT(*)")
select_exprs = []
groupby_exprs = []
if groupby:
select_exprs = [literal_column(s) for s in groupby]
groupby_exprs = [literal_column(s) for s in groupby]
inner_groupby_exprs = [literal_column(s).label('__' + s) for s in groupby]
if granularity != "all":
select_exprs += [timestamp]
groupby_exprs += [timestamp]
select_exprs += metrics_exprs
qry = select(select_exprs)
from_clause = table(self.table_name)
qry = qry.group_by(*groupby_exprs)
where_clause_and = [
timestamp >= from_dttm.isoformat(),
timestamp < to_dttm.isoformat(),
]
for col, op, eq in filter:
if op in ('in', 'not in'):
values = eq.split(",")
cond = literal_column(col).in_(values)
if op == 'not in':
cond = ~cond
where_clause_and.append(cond)
qry = qry.where(and_(*where_clause_and))
qry = qry.order_by(desc(main_metric_expr))
qry = qry.limit(row_limit)
if timeseries_limit and groupby:
subq = select(inner_groupby_exprs)
subq = subq.select_from(table(self.table_name))
subq = subq.where(and_(*where_clause_and))
subq = subq.group_by(*inner_groupby_exprs)
subq = subq.order_by(desc(main_metric_expr))
subq = subq.limit(timeseries_limit)
on_clause = []
for gb in groupby:
on_clause.append(literal_column(gb)==literal_column("__" + gb))
from_clause = from_clause.join(subq.alias(), and_(*on_clause))
qry = qry.select_from(from_clause)
engine = self.database.get_sqla_engine()
sql = str(qry.compile(engine, compile_kwargs={"literal_binds": True}))
df = read_sql_query(
sql=sql,
con=engine
)
sql = sqlparse.format(sql, reindent=True)
return QueryResult(
df=df, duration=datetime.now() - qry_start_dttm, query=sql)
def fetch_metadata(self):
try:
table = self.database.get_table(self.table_name)
except Exception as e:
flash(str(e))
flash(
"Table doesn't seem to exist in the specified database, "
"couldn't fetch column information", "danger")
return
TC = TableColumn
M = SqlMetric
metrics = []
any_date_col = None
for col in table.columns:
try:
datatype = str(col.type)
except Exception as e:
datatype = "UNKNOWN"
dbcol = (
db.session
.query(TC)
.filter(TC.table==self)
.filter(TC.column_name==col.name)
.first()
)
db.session.flush()
if not dbcol:
dbcol = TableColumn(column_name=col.name)
if (
str(datatype).startswith('VARCHAR') or
str(datatype).startswith('STRING')):
dbcol.groupby = True
dbcol.filterable = True
db.session.merge(self)
self.columns.append(dbcol)
if not any_date_col and 'date' in datatype.lower():
any_date_col = dbcol
if dbcol.sum:
metrics.append(M(
metric_name='sum__' + dbcol.column_name,
verbose_name='sum__' + dbcol.column_name,
metric_type='sum',
expression="SUM({})".format(dbcol.column_name)
))
if dbcol.max:
metrics.append(M(
metric_name='max__' + dbcol.column_name,
verbose_name='max__' + dbcol.column_name,
metric_type='max',
expression="MAX({})".format(dbcol.column_name)
))
if dbcol.min:
metrics.append(M(
metric_name='min__' + dbcol.column_name,
verbose_name='min__' + dbcol.column_name,
metric_type='min',
expression="MIN({})".format(dbcol.column_name)
))
if dbcol.count_distinct:
metrics.append(M(
metric_name='count_distinct__' + dbcol.column_name,
verbose_name='count_distinct__' + dbcol.column_name,
metric_type='count_distinct',
expression="COUNT(DISTINCT {})".format(dbcol.column_name)
))
dbcol.type = datatype
db.session.merge(self)
db.session.commit()
metrics.append(M(
metric_name='count',
verbose_name='COUNT(*)',
metric_type='count',
expression="COUNT(*)"
))
for metric in metrics:
m = (
db.session.query(M)
.filter(M.metric_name==metric.metric_name)
.filter(M.table==self)
.first()
)
metric.table = self
if not m:
db.session.add(metric)
db.session.commit()
if not self.main_datetime_column:
self.main_datetime_column = any_date_col
class SqlMetric(Model, AuditMixin):
__tablename__ = 'sql_metrics'
id = Column(Integer, primary_key=True)
metric_name = Column(String(512))
verbose_name = Column(String(1024))
metric_type = Column(String(32))
table_id = Column(Integer,ForeignKey('tables.id'))
table = relationship(
'Table', backref='metrics', foreign_keys=[table_id])
expression = Column(Text)
description = Column(Text)
class TableColumn(Model, AuditMixin):
__tablename__ = 'table_columns'
id = Column(Integer, primary_key=True)
table_id = Column(Integer, ForeignKey('tables.id'))
table = relationship('Table', backref='columns', foreign_keys=[table_id])
column_name = Column(String(256))
is_dttm = Column(Boolean, default=True)
is_active = Column(Boolean, default=True)
type = Column(String(32), default='')
groupby = Column(Boolean, default=False)
count_distinct = Column(Boolean, default=False)
sum = Column(Boolean, default=False)
max = Column(Boolean, default=False)
min = Column(Boolean, default=False)
filterable = Column(Boolean, default=False)
description = Column(Text, default='')
def __repr__(self):
return self.column_name
class Cluster(Model, AuditMixin):
__tablename__ = 'clusters'
id = Column(Integer, primary_key=True)
cluster_name = Column(String(255), unique=True)
coordinator_host = Column(String(256))
coordinator_port = Column(Integer)
coordinator_endpoint = Column(String(256))
broker_host = Column(String(256))
broker_port = Column(Integer)
broker_endpoint = Column(String(256))
metadata_last_refreshed = Column(DateTime)
def __repr__(self):
return self.cluster_name
def get_pydruid_client(self):
cli = client.PyDruid(
"http://{0}:{1}/".format(self.broker_host, self.broker_port),
self.broker_endpoint)
return cli
def refresh_datasources(self):
endpoint = (
"http://{self.coordinator_host}:{self.coordinator_port}/"
"{self.coordinator_endpoint}/datasources"
).format(self=self)
datasources = json.loads(requests.get(endpoint).text)
for datasource in datasources:
Datasource.sync_to_db(datasource, self)
class Datasource(Model, AuditMixin, Queryable):
baselink = "datasourcemodelview"
__tablename__ = 'datasources'
id = Column(Integer, primary_key=True)
datasource_name = Column(String(255), unique=True)
is_featured = Column(Boolean, default=False)
is_hidden = Column(Boolean, default=False)
description = Column(Text)
default_endpoint = Column(Text)
user_id = Column(Integer, ForeignKey('ab_user.id'))
owner = relationship('User', backref='datasources', foreign_keys=[user_id])
cluster_name = Column(String(255),
ForeignKey('clusters.cluster_name'))
cluster = relationship('Cluster', backref='datasources', foreign_keys=[cluster_name])
@property
def metrics_combo(self):
return sorted(
[(m.metric_name, m.verbose_name) for m in self.metrics],
key=lambda x: x[1])
@property
def name(self):
return self.datasource_name
def __repr__(self):
return self.datasource_name
@property
def datasource_link(self):
url = "/panoramix/datasource/{}/".format(self.datasource_name)
return '<a href="{url}">{self.datasource_name}</a>'.format(**locals())
def get_metric_obj(self, metric_name):
return [
m.json_obj for m in self.metrics
if m.metric_name == metric_name
][0]
def latest_metadata(self):
client = self.cluster.get_pydruid_client()
results = client.time_boundary(datasource=self.datasource_name)
if not results:
return
max_time = results[0]['result']['minTime']
max_time = parse(max_time)
intervals = (max_time - timedelta(seconds=1)).isoformat() + '/'
intervals += (max_time + timedelta(seconds=1)).isoformat()
segment_metadata = client.segment_metadata(
datasource=self.datasource_name,
intervals=intervals)
if segment_metadata:
return segment_metadata[-1]['columns']
def generate_metrics(self):
for col in self.columns:
col.generate_metrics()
@classmethod
def sync_to_db(cls, name, cluster):
session = get_session()
datasource = session.query(cls).filter_by(datasource_name=name).first()
if not datasource:
datasource = cls(datasource_name=name)
session.add(datasource)
datasource.cluster = cluster
cols = datasource.latest_metadata()
if not cols:
return
for col in cols:
col_obj = (
session
.query(Column)
.filter_by(datasource_name=name, column_name=col)
.first()
)
datatype = cols[col]['type']
if not col_obj:
col_obj = Column(datasource_name=name, column_name=col)
session.add(col_obj)
if datatype == "STRING":
col_obj.groupby = True
col_obj.filterable = True
if col_obj:
col_obj.type = cols[col]['type']
col_obj.datasource = datasource
col_obj.generate_metrics()
#session.commit()
def query(
self, groupby, metrics,
granularity,
from_dttm, to_dttm,
limit_spec=None,
filter=None,
is_timeseries=True,
timeseries_limit=None,
row_limit=None):
qry_start_dttm = datetime.now()
query_str = ""
aggregations = {
m.metric_name: m.json_obj
for m in self.metrics if m.metric_name in metrics
}
if not isinstance(granularity, basestring):
granularity = {"type": "duration", "duration": granularity}
qry = dict(
datasource=self.datasource_name,
dimensions=groupby,
aggregations=aggregations,
granularity=granularity,
intervals= from_dttm.isoformat() + '/' + to_dttm.isoformat(),
)
filters = None
for col, op, eq in filter:
cond = None
if op == '==':
cond = Dimension(col)==eq
elif op == '!=':
cond = ~(Dimension(col)==eq)
elif op in ('in', 'not in'):
fields = []
splitted = eq.split(',')
if len(splitted) > 1:
for s in eq.split(','):
s = s.strip()
fields.append(Filter.build_filter(Dimension(col)==s))
cond = Filter(type="or", fields=fields)
else:
cond = Dimension(col)==eq
if op == 'not in':
cond = ~cond
if filters:
filters = Filter(type="and", fields=[
Filter.build_filter(cond),
Filter.build_filter(filters)
])
else:
filters = cond
if filters:
qry['filter'] = filters
client = self.cluster.get_pydruid_client()
orig_filters = filters
if timeseries_limit and is_timeseries:
# Limit on the number of timeseries, doing a two-phases query
pre_qry = deepcopy(qry)
pre_qry['granularity'] = "all"
pre_qry['limit_spec'] = {
"type": "default",
"limit": timeseries_limit,
"columns": [{
"dimension": metrics[0] if metrics else self.metrics[0],
"direction": "descending",
}],
}
client.groupby(**pre_qry)
query_str += "// Two phase query\n// Phase 1\n"
query_str += json.dumps(client.query_dict, indent=2) + "\n"
query_str += "//\nPhase 2 (built based on phase one's results)\n"
df = client.export_pandas()
if not df is None and not df.empty:
dims = qry['dimensions']
filters = []
for index, row in df.iterrows():
fields = []
for dim in dims:
f = Filter.build_filter(Dimension(dim) == row[dim])
fields.append(f)
if len(fields) > 1:
filt = Filter(type="and", fields=fields)
filters.append(Filter.build_filter(filt))
elif fields:
filters.append(fields[0])
if filters:
ff = Filter(type="or", fields=filters)
if not orig_filters:
qry['filter'] = ff
else:
qry['filter'] = Filter(type="and", fields=[
Filter.build_filter(ff),
Filter.build_filter(orig_filters)])
qry['limit_spec'] = None
if row_limit:
qry['limit_spec'] = {
"type": "default",
"limit": row_limit,
"columns": [{
"dimension": metrics[0] if metrics else self.metrics[0],
"direction": "descending",
}],
}
client.groupby(**qry)
query_str += json.dumps(client.query_dict, indent=2)
df = client.export_pandas()
return QueryResult(
df=df,
query=query_str,
duration=datetime.now() - qry_start_dttm)
#class Metric(Model, AuditMixin):
class Metric(Model):
__tablename__ = 'metrics'
id = Column(Integer, primary_key=True)
metric_name = Column(String(512))
verbose_name = Column(String(1024))
metric_type = Column(String(32))
datasource_name = Column(
String(256),
ForeignKey('datasources.datasource_name'))
datasource = relationship('Datasource', backref='metrics')
json = Column(Text)
description = Column(Text)
@property
def json_obj(self):
try:
obj = json.loads(self.json)
except Exception as e:
obj = {}
return obj
class Column(Model, AuditMixin):
__tablename__ = 'columns'
id = Column(Integer, primary_key=True)
datasource_name = Column(
String(256),
ForeignKey('datasources.datasource_name'))
datasource = relationship('Datasource', backref='columns')
column_name = Column(String(256))
is_active = Column(Boolean, default=True)
type = Column(String(32))
groupby = Column(Boolean, default=False)
count_distinct = Column(Boolean, default=False)
sum = Column(Boolean, default=False)
max = Column(Boolean, default=False)
min = Column(Boolean, default=False)
filterable = Column(Boolean, default=False)
description = Column(Text)
def __repr__(self):
return self.column_name
@property
def isnum(self):
return self.type in ('LONG', 'DOUBLE', 'FLOAT')
def generate_metrics(self):
M = Metric
metrics = []
metrics.append(Metric(
metric_name='count',
verbose_name='COUNT(*)',
metric_type='count',
json=json.dumps({'type': 'count', 'name': 'count'})
))
# Somehow we need to reassign this for UDAFs
corrected_type = 'DOUBLE' if self.type in ('DOUBLE', 'FLOAT') else self.type
if self.sum and self.isnum:
mt = corrected_type.lower() + 'Sum'
name='sum__' + self.column_name
metrics.append(Metric(
metric_name=name,
metric_type='sum',
verbose_name='SUM({})'.format(self.column_name),
json=json.dumps({
'type': mt, 'name': name, 'fieldName': self.column_name})
))
if self.min and self.isnum:
mt = corrected_type.lower() + 'Min'
name='min__' + self.column_name
metrics.append(Metric(
metric_name=name,
metric_type='min',
verbose_name='MIN({})'.format(self.column_name),
json=json.dumps({
'type': mt, 'name': name, 'fieldName': self.column_name})
))
if self.max and self.isnum:
mt = corrected_type.lower() + 'Max'
name='max__' + self.column_name
metrics.append(Metric(
metric_name=name,
metric_type='max',
verbose_name='MAX({})'.format(self.column_name),
json=json.dumps({
'type': mt, 'name': name, 'fieldName': self.column_name})
))
if self.count_distinct:
mt = 'count_distinct'
name='count_distinct__' + self.column_name
metrics.append(Metric(
metric_name=name,
verbose_name='COUNT(DISTINCT {})'.format(self.column_name),
metric_type='count_distinct',
json=json.dumps({
'type': 'cardinality',
'name': name,
'fieldNames': [self.column_name]})
))
session = get_session()
for metric in metrics:
m = (
session.query(M)
.filter(M.metric_name==metric.metric_name)
.filter(M.datasource_name==self.datasource_name)
.filter(Cluster.cluster_name==self.datasource.cluster_name)
.first()
)
metric.datasource_name = self.datasource_name
if not m:
session.add(metric)
session.commit()
| panoramix/models.py | 1 | https://github.com/apache/superset/commit/6dd81a3e95a9d67be743815ff9bfcd465278b3e9 | [
0.9844096899032593,
0.06298036873340607,
0.00016588717699050903,
0.0008164314785972238,
0.19654081761837006
] |
{
"id": 5,
"code_window": [
"class TableColumnInlineView(CompactCRUDMixin, ModelView):\n",
" datamodel = SQLAInterface(models.TableColumn)\n",
" can_delete = False\n",
" edit_columns = [\n",
" 'column_name', 'description', 'table', 'groupby', 'filterable',\n",
" 'count_distinct', 'sum', 'min', 'max']\n",
" list_columns = [\n",
" 'column_name', 'type', 'groupby', 'filterable', 'count_distinct',\n",
" 'sum', 'min', 'max']\n",
" page_size = 100\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" 'column_name', 'description', 'groupby', 'filterable', 'table',\n"
],
"file_path": "panoramix/views.py",
"type": "replace",
"edit_start_line_idx": 32
} | /*! DataTables Bootstrap 3 integration
* ©2011-2014 SpryMedia Ltd - datatables.net/license
*/
/**
* DataTables integration for Bootstrap 3. This requires Bootstrap 3 and
* DataTables 1.10 or newer.
*
* This file sets the defaults and adds options to DataTables to style its
* controls using Bootstrap. See http://datatables.net/manual/styling/bootstrap
* for further information.
*/
(function(window, document, undefined){
var factory = function( $, DataTable ) {
"use strict";
/* Set the defaults for DataTables initialisation */
$.extend( true, DataTable.defaults, {
dom:
"<'row'<'col-sm-6'l><'col-sm-6'f>>" +
"<'row'<'col-sm-12'tr>>" +
"<'row'<'col-sm-5'i><'col-sm-7'p>>",
renderer: 'bootstrap'
} );
/* Default class modification */
$.extend( DataTable.ext.classes, {
sWrapper: "dataTables_wrapper form-inline dt-bootstrap",
sFilterInput: "form-control input-sm",
sLengthSelect: "form-control input-sm"
} );
/* Bootstrap paging button renderer */
DataTable.ext.renderer.pageButton.bootstrap = function ( settings, host, idx, buttons, page, pages ) {
var api = new DataTable.Api( settings );
var classes = settings.oClasses;
var lang = settings.oLanguage.oPaginate;
var btnDisplay, btnClass, counter=0;
var attach = function( container, buttons ) {
var i, ien, node, button;
var clickHandler = function ( e ) {
e.preventDefault();
if ( !$(e.currentTarget).hasClass('disabled') ) {
api.page( e.data.action ).draw( false );
}
};
for ( i=0, ien=buttons.length ; i<ien ; i++ ) {
button = buttons[i];
if ( $.isArray( button ) ) {
attach( container, button );
}
else {
btnDisplay = '';
btnClass = '';
switch ( button ) {
case 'ellipsis':
btnDisplay = '…';
btnClass = 'disabled';
break;
case 'first':
btnDisplay = lang.sFirst;
btnClass = button + (page > 0 ?
'' : ' disabled');
break;
case 'previous':
btnDisplay = lang.sPrevious;
btnClass = button + (page > 0 ?
'' : ' disabled');
break;
case 'next':
btnDisplay = lang.sNext;
btnClass = button + (page < pages-1 ?
'' : ' disabled');
break;
case 'last':
btnDisplay = lang.sLast;
btnClass = button + (page < pages-1 ?
'' : ' disabled');
break;
default:
btnDisplay = button + 1;
btnClass = page === button ?
'active' : '';
break;
}
if ( btnDisplay ) {
node = $('<li>', {
'class': classes.sPageButton+' '+btnClass,
'id': idx === 0 && typeof button === 'string' ?
settings.sTableId +'_'+ button :
null
} )
.append( $('<a>', {
'href': '#',
'aria-controls': settings.sTableId,
'data-dt-idx': counter,
'tabindex': settings.iTabIndex
} )
.html( btnDisplay )
)
.appendTo( container );
settings.oApi._fnBindAction(
node, {action: button}, clickHandler
);
counter++;
}
}
}
};
// IE9 throws an 'unknown error' if document.activeElement is used
// inside an iframe or frame.
var activeEl;
try {
// Because this approach is destroying and recreating the paging
// elements, focus is lost on the select button which is bad for
// accessibility. So we want to restore focus once the draw has
// completed
activeEl = $(document.activeElement).data('dt-idx');
}
catch (e) {}
attach(
$(host).empty().html('<ul class="pagination"/>').children('ul'),
buttons
);
if ( activeEl ) {
$(host).find( '[data-dt-idx='+activeEl+']' ).focus();
}
};
/*
* TableTools Bootstrap compatibility
* Required TableTools 2.1+
*/
if ( DataTable.TableTools ) {
// Set the classes that TableTools uses to something suitable for Bootstrap
$.extend( true, DataTable.TableTools.classes, {
"container": "DTTT btn-group",
"buttons": {
"normal": "btn btn-default",
"disabled": "disabled"
},
"collection": {
"container": "DTTT_dropdown dropdown-menu",
"buttons": {
"normal": "",
"disabled": "disabled"
}
},
"print": {
"info": "DTTT_print_info"
},
"select": {
"row": "active"
}
} );
// Have the collection use a bootstrap compatible drop down
$.extend( true, DataTable.TableTools.DEFAULTS.oTags, {
"collection": {
"container": "ul",
"button": "li",
"liner": "a"
}
} );
}
}; // /factory
// Define as an AMD module if possible
if ( typeof define === 'function' && define.amd ) {
define( ['jquery', 'datatables'], factory );
}
else if ( typeof exports === 'object' ) {
// Node/CommonJS
factory( require('jquery'), require('datatables') );
}
else if ( jQuery ) {
// Otherwise simply initialise as normal, stopping multiple evaluation
factory( jQuery, jQuery.fn.dataTable );
}
})(window, document);
| panoramix/static/dataTables.bootstrap.js | 0 | https://github.com/apache/superset/commit/6dd81a3e95a9d67be743815ff9bfcd465278b3e9 | [
0.00017186871264129877,
0.000167866688570939,
0.0001611557963769883,
0.000168108002981171,
0.000002405568693575333
] |
{
"id": 5,
"code_window": [
"class TableColumnInlineView(CompactCRUDMixin, ModelView):\n",
" datamodel = SQLAInterface(models.TableColumn)\n",
" can_delete = False\n",
" edit_columns = [\n",
" 'column_name', 'description', 'table', 'groupby', 'filterable',\n",
" 'count_distinct', 'sum', 'min', 'max']\n",
" list_columns = [\n",
" 'column_name', 'type', 'groupby', 'filterable', 'count_distinct',\n",
" 'sum', 'min', 'max']\n",
" page_size = 100\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" 'column_name', 'description', 'groupby', 'filterable', 'table',\n"
],
"file_path": "panoramix/views.py",
"type": "replace",
"edit_start_line_idx": 32
} | /*
Highcharts JS v4.1.7 (2015-06-26)
(c) 2009-2014 Torstein Honsi
License: www.highcharts.com/license
*/
(function(){function z(){var a,b=arguments,c,d={},e=function(a,b){var c,d;typeof a!=="object"&&(a={});for(d in b)b.hasOwnProperty(d)&&(c=b[d],a[d]=c&&typeof c==="object"&&Object.prototype.toString.call(c)!=="[object Array]"&&d!=="renderTo"&&typeof c.nodeType!=="number"?e(a[d]||{},c):b[d]);return a};b[0]===!0&&(d=b[1],b=Array.prototype.slice.call(b,2));c=b.length;for(a=0;a<c;a++)d=e(d,b[a]);return d}function D(a,b){return parseInt(a,b||10)}function Da(a){return typeof a==="string"}function da(a){return a&&
typeof a==="object"}function Ha(a){return Object.prototype.toString.call(a)==="[object Array]"}function ra(a){return typeof a==="number"}function Ea(a){return W.log(a)/W.LN10}function ia(a){return W.pow(10,a)}function ja(a,b){for(var c=a.length;c--;)if(a[c]===b){a.splice(c,1);break}}function q(a){return a!==y&&a!==null}function J(a,b,c){var d,e;if(Da(b))q(c)?a.setAttribute(b,c):a&&a.getAttribute&&(e=a.getAttribute(b));else if(q(b)&&da(b))for(d in b)a.setAttribute(d,b[d]);return e}function sa(a){return Ha(a)?
a:[a]}function L(a,b){if(ya&&!ca&&b&&b.opacity!==y)b.filter="alpha(opacity="+b.opacity*100+")";x(a.style,b)}function $(a,b,c,d,e){a=B.createElement(a);b&&x(a,b);e&&L(a,{padding:0,border:P,margin:0});c&&L(a,c);d&&d.appendChild(a);return a}function ka(a,b){var c=function(){return y};c.prototype=new a;x(c.prototype,b);return c}function Ia(a,b){return Array((b||2)+1-String(a).length).join(0)+a}function Wa(a){return(eb&&eb(a)||ob||0)*6E4}function Ja(a,b){for(var c="{",d=!1,e,f,g,h,i,j=[];(c=a.indexOf(c))!==
-1;){e=a.slice(0,c);if(d){f=e.split(":");g=f.shift().split(".");i=g.length;e=b;for(h=0;h<i;h++)e=e[g[h]];if(f.length)f=f.join(":"),g=/\.([0-9])/,h=T.lang,i=void 0,/f$/.test(f)?(i=(i=f.match(g))?i[1]:-1,e!==null&&(e=A.numberFormat(e,i,h.decimalPoint,f.indexOf(",")>-1?h.thousandsSep:""))):e=Oa(f,e)}j.push(e);a=a.slice(c+1);c=(d=!d)?"}":"{"}j.push(a);return j.join("")}function pb(a){return W.pow(10,V(W.log(a)/W.LN10))}function qb(a,b,c,d,e){var f,g=a,c=p(c,1);f=a/c;b||(b=[1,2,2.5,5,10],d===!1&&(c===
1?b=[1,2,5,10]:c<=0.1&&(b=[1/c])));for(d=0;d<b.length;d++)if(g=b[d],e&&g*c>=a||!e&&f<=(b[d]+(b[d+1]||b[d]))/2)break;g*=c;return g}function rb(a,b){var c=a.length,d,e;for(e=0;e<c;e++)a[e].ss_i=e;a.sort(function(a,c){d=b(a,c);return d===0?a.ss_i-c.ss_i:d});for(e=0;e<c;e++)delete a[e].ss_i}function Pa(a){for(var b=a.length,c=a[0];b--;)a[b]<c&&(c=a[b]);return c}function Fa(a){for(var b=a.length,c=a[0];b--;)a[b]>c&&(c=a[b]);return c}function Qa(a,b){for(var c in a)a[c]&&a[c]!==b&&a[c].destroy&&a[c].destroy(),
delete a[c]}function Ra(a){fb||(fb=$(Ka));a&&fb.appendChild(a);fb.innerHTML=""}function la(a,b){var c="Highcharts error #"+a+": www.highcharts.com/errors/"+a;if(b)throw c;K.console&&console.log(c)}function ea(a){return parseFloat(a.toPrecision(14))}function Sa(a,b){za=p(a,b.animation)}function Db(){var a=T.global,b=a.useUTC,c=b?"getUTC":"get",d=b?"setUTC":"set";Aa=a.Date||window.Date;ob=b&&a.timezoneOffset;eb=b&&a.getTimezoneOffset;gb=function(a,c,d,h,i,j){var k;b?(k=Aa.UTC.apply(0,arguments),k+=
Wa(k)):k=(new Aa(a,c,p(d,1),p(h,0),p(i,0),p(j,0))).getTime();return k};sb=c+"Minutes";tb=c+"Hours";ub=c+"Day";Xa=c+"Date";Ya=c+"Month";Za=c+"FullYear";Eb=d+"Milliseconds";Fb=d+"Seconds";Gb=d+"Minutes";Hb=d+"Hours";vb=d+"Date";wb=d+"Month";xb=d+"FullYear"}function Q(){}function Ta(a,b,c,d){this.axis=a;this.pos=b;this.type=c||"";this.isNew=!0;!c&&!d&&this.addLabel()}function Ib(a,b,c,d,e){var f=a.chart.inverted;this.axis=a;this.isNegative=c;this.options=b;this.x=d;this.total=null;this.points={};this.stack=
e;this.alignOptions={align:b.align||(f?c?"left":"right":"center"),verticalAlign:b.verticalAlign||(f?"middle":c?"bottom":"top"),y:p(b.y,f?4:c?14:-6),x:p(b.x,f?c?-6:6:0)};this.textAlign=b.textAlign||(f?c?"right":"left":"center")}var y,B=document,K=window,W=Math,r=W.round,V=W.floor,ta=W.ceil,u=W.max,C=W.min,O=W.abs,X=W.cos,aa=W.sin,ma=W.PI,ha=ma*2/360,Ba=navigator.userAgent,Jb=K.opera,ya=/(msie|trident)/i.test(Ba)&&!Jb,hb=B.documentMode===8,ib=/AppleWebKit/.test(Ba),La=/Firefox/.test(Ba),Kb=/(Mobile|Android|Windows Phone)/.test(Ba),
Ca="http://www.w3.org/2000/svg",ca=!!B.createElementNS&&!!B.createElementNS(Ca,"svg").createSVGRect,Ob=La&&parseInt(Ba.split("Firefox/")[1],10)<4,fa=!ca&&!ya&&!!B.createElement("canvas").getContext,$a,ab,Lb={},yb=0,fb,T,Oa,za,zb,E,na=function(){return y},Y=[],bb=0,Ka="div",P="none",Pb=/^[0-9]+$/,jb=["plotTop","marginRight","marginBottom","plotLeft"],Qb="stroke-width",Aa,gb,ob,eb,sb,tb,ub,Xa,Ya,Za,Eb,Fb,Gb,Hb,vb,wb,xb,M={},A;A=K.Highcharts=K.Highcharts?la(16,!0):{};A.seriesTypes=M;var x=A.extend=function(a,
b){var c;a||(a={});for(c in b)a[c]=b[c];return a},p=A.pick=function(){var a=arguments,b,c,d=a.length;for(b=0;b<d;b++)if(c=a[b],c!==y&&c!==null)return c},cb=A.wrap=function(a,b,c){var d=a[b];a[b]=function(){var a=Array.prototype.slice.call(arguments);a.unshift(d);return c.apply(this,a)}};Oa=function(a,b,c){if(!q(b)||isNaN(b))return"Invalid date";var a=p(a,"%Y-%m-%d %H:%M:%S"),d=new Aa(b-Wa(b)),e,f=d[tb](),g=d[ub](),h=d[Xa](),i=d[Ya](),j=d[Za](),k=T.lang,l=k.weekdays,d=x({a:l[g].substr(0,3),A:l[g],
d:Ia(h),e:h,w:g,b:k.shortMonths[i],B:k.months[i],m:Ia(i+1),y:j.toString().substr(2,2),Y:j,H:Ia(f),I:Ia(f%12||12),l:f%12||12,M:Ia(d[sb]()),p:f<12?"AM":"PM",P:f<12?"am":"pm",S:Ia(d.getSeconds()),L:Ia(r(b%1E3),3)},A.dateFormats);for(e in d)for(;a.indexOf("%"+e)!==-1;)a=a.replace("%"+e,typeof d[e]==="function"?d[e](b):d[e]);return c?a.substr(0,1).toUpperCase()+a.substr(1):a};E={millisecond:1,second:1E3,minute:6E4,hour:36E5,day:864E5,week:6048E5,month:24192E5,year:314496E5};A.numberFormat=function(a,b,
c,d){var e=T.lang,a=+a||0,f=b===-1?C((a.toString().split(".")[1]||"").length,20):isNaN(b=O(b))?2:b,b=c===void 0?e.decimalPoint:c,d=d===void 0?e.thousandsSep:d,e=a<0?"-":"",c=String(D(a=O(a).toFixed(f))),g=c.length>3?c.length%3:0;return e+(g?c.substr(0,g)+d:"")+c.substr(g).replace(/(\d{3})(?=\d)/g,"$1"+d)+(f?b+O(a-c).toFixed(f).slice(2):"")};zb={init:function(a,b,c){var b=b||"",d=a.shift,e=b.indexOf("C")>-1,f=e?7:3,g,b=b.split(" "),c=[].concat(c),h,i,j=function(a){for(g=a.length;g--;)a[g]==="M"&&a.splice(g+
1,0,a[g+1],a[g+2],a[g+1],a[g+2])};e&&(j(b),j(c));a.isArea&&(h=b.splice(b.length-6,6),i=c.splice(c.length-6,6));if(d<=c.length/f&&b.length===c.length)for(;d--;)c=[].concat(c).splice(0,f).concat(c);a.shift=0;if(b.length)for(a=c.length;b.length<a;)d=[].concat(b).splice(b.length-f,f),e&&(d[f-6]=d[f-2],d[f-5]=d[f-1]),b=b.concat(d);h&&(b=b.concat(h),c=c.concat(i));return[b,c]},step:function(a,b,c,d){var e=[],f=a.length;if(c===1)e=d;else if(f===b.length&&c<1)for(;f--;)d=parseFloat(a[f]),e[f]=isNaN(d)?a[f]:
c*parseFloat(b[f]-d)+d;else e=b;return e}};(function(a){K.HighchartsAdapter=K.HighchartsAdapter||a&&{init:function(b){var c=a.fx;a.extend(a.easing,{easeOutQuad:function(a,b,c,g,h){return-g*(b/=h)*(b-2)+c}});a.each(["cur","_default","width","height","opacity"],function(b,e){var f=c.step,g;e==="cur"?f=c.prototype:e==="_default"&&a.Tween&&(f=a.Tween.propHooks[e],e="set");(g=f[e])&&(f[e]=function(a){var c,a=b?a:this;if(a.prop!=="align")return c=a.elem,c.attr?c.attr(a.prop,e==="cur"?y:a.now):g.apply(this,
arguments)})});cb(a.cssHooks.opacity,"get",function(a,b,c){return b.attr?b.opacity||0:a.call(this,b,c)});this.addAnimSetter("d",function(a){var c=a.elem,f;if(!a.started)f=b.init(c,c.d,c.toD),a.start=f[0],a.end=f[1],a.started=!0;c.attr("d",b.step(a.start,a.end,a.pos,c.toD))});this.each=Array.prototype.forEach?function(a,b){return Array.prototype.forEach.call(a,b)}:function(a,b){var c,g=a.length;for(c=0;c<g;c++)if(b.call(a[c],a[c],c,a)===!1)return c};a.fn.highcharts=function(){var a="Chart",b=arguments,
c,g;if(this[0]){Da(b[0])&&(a=b[0],b=Array.prototype.slice.call(b,1));c=b[0];if(c!==y)c.chart=c.chart||{},c.chart.renderTo=this[0],new A[a](c,b[1]),g=this;c===y&&(g=Y[J(this[0],"data-highcharts-chart")])}return g}},addAnimSetter:function(b,c){a.Tween?a.Tween.propHooks[b]={set:c}:a.fx.step[b]=c},getScript:a.getScript,inArray:a.inArray,adapterRun:function(b,c){return a(b)[c]()},grep:a.grep,map:function(a,c){for(var d=[],e=0,f=a.length;e<f;e++)d[e]=c.call(a[e],a[e],e,a);return d},offset:function(b){return a(b).offset()},
addEvent:function(b,c,d){a(b).bind(c,d)},removeEvent:function(b,c,d){var e=B.removeEventListener?"removeEventListener":"detachEvent";B[e]&&b&&!b[e]&&(b[e]=function(){});a(b).unbind(c,d)},fireEvent:function(b,c,d,e){var f=a.Event(c),g="detached"+c,h;!ya&&d&&(delete d.layerX,delete d.layerY,delete d.returnValue);x(f,d);b[c]&&(b[g]=b[c],b[c]=null);a.each(["preventDefault","stopPropagation"],function(a,b){var c=f[b];f[b]=function(){try{c.call(f)}catch(a){b==="preventDefault"&&(h=!0)}}});a(b).trigger(f);
b[g]&&(b[c]=b[g],b[g]=null);e&&!f.isDefaultPrevented()&&!h&&e(f)},washMouseEvent:function(a){var c=a.originalEvent||a;if(c.pageX===y)c.pageX=a.pageX,c.pageY=a.pageY;return c},animate:function(b,c,d){var e=a(b);if(!b.style)b.style={};if(c.d)b.toD=c.d,c.d=1;e.stop();c.opacity!==y&&b.attr&&(c.opacity+="px");b.hasAnim=1;e.animate(c,d)},stop:function(b){b.hasAnim&&a(b).stop()}}})(K.jQuery);var U=K.HighchartsAdapter,F=U||{};U&&U.init.call(U,zb);var kb=F.adapterRun,Rb=F.getScript,Ma=F.inArray,o=A.each=F.each,
lb=F.grep,Sb=F.offset,Ua=F.map,H=F.addEvent,Z=F.removeEvent,I=F.fireEvent,Tb=F.washMouseEvent,mb=F.animate,db=F.stop;T={colors:"#7cb5ec,#434348,#90ed7d,#f7a35c,#8085e9,#f15c80,#e4d354,#2b908f,#f45b5b,#91e8e1".split(","),symbols:["circle","diamond","square","triangle","triangle-down"],lang:{loading:"Loading...",months:"January,February,March,April,May,June,July,August,September,October,November,December".split(","),shortMonths:"Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec".split(","),weekdays:"Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday".split(","),
decimalPoint:".",numericSymbols:"k,M,G,T,P,E".split(","),resetZoom:"Reset zoom",resetZoomTitle:"Reset zoom level 1:1",thousandsSep:" "},global:{useUTC:!0,canvasToolsURL:"http://code.highcharts.com/4.1.7/modules/canvas-tools.js",VMLRadialGradientURL:"http://code.highcharts.com/4.1.7/gfx/vml-radial-gradient.png"},chart:{borderColor:"#4572A7",borderRadius:0,defaultSeriesType:"line",ignoreHiddenSeries:!0,spacing:[10,10,15,10],backgroundColor:"#FFFFFF",plotBorderColor:"#C0C0C0",resetZoomButton:{theme:{zIndex:20},
position:{align:"right",x:-10,y:10}}},title:{text:"Chart title",align:"center",margin:15,style:{color:"#333333",fontSize:"18px"}},subtitle:{text:"",align:"center",style:{color:"#555555"}},plotOptions:{line:{allowPointSelect:!1,showCheckbox:!1,animation:{duration:1E3},events:{},lineWidth:2,marker:{lineWidth:0,radius:4,lineColor:"#FFFFFF",states:{hover:{enabled:!0,lineWidthPlus:1,radiusPlus:2},select:{fillColor:"#FFFFFF",lineColor:"#000000",lineWidth:2}}},point:{events:{}},dataLabels:{align:"center",
formatter:function(){return this.y===null?"":A.numberFormat(this.y,-1)},style:{color:"contrast",fontSize:"11px",fontWeight:"bold",textShadow:"0 0 6px contrast, 0 0 3px contrast"},verticalAlign:"bottom",x:0,y:0,padding:5},cropThreshold:300,pointRange:0,states:{hover:{lineWidthPlus:1,marker:{},halo:{size:10,opacity:0.25}},select:{marker:{}}},stickyTracking:!0,turboThreshold:1E3}},labels:{style:{position:"absolute",color:"#3E576F"}},legend:{enabled:!0,align:"center",layout:"horizontal",labelFormatter:function(){return this.name},
borderColor:"#909090",borderRadius:0,navigation:{activeColor:"#274b6d",inactiveColor:"#CCC"},shadow:!1,itemStyle:{color:"#333333",fontSize:"12px",fontWeight:"bold"},itemHoverStyle:{color:"#000"},itemHiddenStyle:{color:"#CCC"},itemCheckboxStyle:{position:"absolute",width:"13px",height:"13px"},symbolPadding:5,verticalAlign:"bottom",x:0,y:0,title:{style:{fontWeight:"bold"}}},loading:{labelStyle:{fontWeight:"bold",position:"relative",top:"45%"},style:{position:"absolute",backgroundColor:"white",opacity:0.5,
textAlign:"center"}},tooltip:{enabled:!0,animation:ca,backgroundColor:"rgba(249, 249, 249, .85)",borderWidth:1,borderRadius:3,dateTimeLabelFormats:{millisecond:"%A, %b %e, %H:%M:%S.%L",second:"%A, %b %e, %H:%M:%S",minute:"%A, %b %e, %H:%M",hour:"%A, %b %e, %H:%M",day:"%A, %b %e, %Y",week:"Week from %A, %b %e, %Y",month:"%B %Y",year:"%Y"},footerFormat:"",headerFormat:'<span style="font-size: 10px">{point.key}</span><br/>',pointFormat:'<span style="color:{point.color}">\u25CF</span> {series.name}: <b>{point.y}</b><br/>',
shadow:!0,snap:Kb?25:10,style:{color:"#333333",cursor:"default",fontSize:"12px",padding:"8px",whiteSpace:"nowrap"}},credits:{enabled:!0,text:"Highcharts.com",href:"http://www.highcharts.com",position:{align:"right",x:-10,verticalAlign:"bottom",y:-5},style:{cursor:"pointer",color:"#909090",fontSize:"9px"}}};var ba=T.plotOptions,U=ba.line;Db();var Ub=/rgba\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]?(?:\.[0-9]+)?)\s*\)/,Vb=/#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/,
Wb=/rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/,oa=function(a){var b=[],c,d;(function(a){a&&a.stops?d=Ua(a.stops,function(a){return oa(a[1])}):(c=Ub.exec(a))?b=[D(c[1]),D(c[2]),D(c[3]),parseFloat(c[4],10)]:(c=Vb.exec(a))?b=[D(c[1],16),D(c[2],16),D(c[3],16),1]:(c=Wb.exec(a))&&(b=[D(c[1]),D(c[2]),D(c[3]),1])})(a);return{get:function(c){var f;d?(f=z(a),f.stops=[].concat(f.stops),o(d,function(a,b){f.stops[b]=[f.stops[b][0],a.get(c)]})):f=b&&!isNaN(b[0])?c==="rgb"?"rgb("+b[0]+","+
b[1]+","+b[2]+")":c==="a"?b[3]:"rgba("+b.join(",")+")":a;return f},brighten:function(a){if(d)o(d,function(b){b.brighten(a)});else if(ra(a)&&a!==0){var c;for(c=0;c<3;c++)b[c]+=D(a*255),b[c]<0&&(b[c]=0),b[c]>255&&(b[c]=255)}return this},rgba:b,setOpacity:function(a){b[3]=a;return this},raw:a}};Q.prototype={opacity:1,textProps:"fontSize,fontWeight,fontFamily,fontStyle,color,lineHeight,width,textDecoration,textShadow".split(","),init:function(a,b){this.element=b==="span"?$(b):B.createElementNS(Ca,b);
this.renderer=a},animate:function(a,b,c){b=p(b,za,!0);db(this);if(b){b=z(b,{});if(c)b.complete=c;mb(this,a,b)}else this.attr(a),c&&c();return this},colorGradient:function(a,b,c){var d=this.renderer,e,f,g,h,i,j,k,l,m,n,v=[];a.linearGradient?f="linearGradient":a.radialGradient&&(f="radialGradient");if(f){g=a[f];h=d.gradients;j=a.stops;m=c.radialReference;Ha(g)&&(a[f]=g={x1:g[0],y1:g[1],x2:g[2],y2:g[3],gradientUnits:"userSpaceOnUse"});f==="radialGradient"&&m&&!q(g.gradientUnits)&&(g=z(g,{cx:m[0]-m[2]/
2+g.cx*m[2],cy:m[1]-m[2]/2+g.cy*m[2],r:g.r*m[2],gradientUnits:"userSpaceOnUse"}));for(n in g)n!=="id"&&v.push(n,g[n]);for(n in j)v.push(j[n]);v=v.join(",");h[v]?a=h[v].attr("id"):(g.id=a="highcharts-"+yb++,h[v]=i=d.createElement(f).attr(g).add(d.defs),i.stops=[],o(j,function(a){a[1].indexOf("rgba")===0?(e=oa(a[1]),k=e.get("rgb"),l=e.get("a")):(k=a[1],l=1);a=d.createElement("stop").attr({offset:a[0],"stop-color":k,"stop-opacity":l}).add(i);i.stops.push(a)}));c.setAttribute(b,"url("+d.url+"#"+a+")")}},
applyTextShadow:function(a){var b=this.element,c,d=a.indexOf("contrast")!==-1,e={},f=this.renderer.forExport||b.style.textShadow!==y&&!ya;if(d)e.textShadow=a=a.replace(/contrast/g,this.renderer.getContrast(b.style.fill));if(ib)e.textRendering="geometricPrecision";f?L(b,e):(this.fakeTS=!0,this.ySetter=this.xSetter,c=[].slice.call(b.getElementsByTagName("tspan")),o(a.split(/\s?,\s?/g),function(a){var d=b.firstChild,e,f,a=a.split(" ");e=a[a.length-1];(f=a[a.length-2])&&o(c,function(a,c){var g;c===0&&
(a.setAttribute("x",b.getAttribute("x")),c=b.getAttribute("y"),a.setAttribute("y",c||0),c===null&&b.setAttribute("y",0));g=a.cloneNode(1);J(g,{"class":"highcharts-text-shadow",fill:e,stroke:e,"stroke-opacity":1/u(D(f),3),"stroke-width":f,"stroke-linejoin":"round"});b.insertBefore(g,d)})}))},attr:function(a,b){var c,d,e=this.element,f,g=this,h;typeof a==="string"&&b!==y&&(c=a,a={},a[c]=b);if(typeof a==="string")g=(this[a+"Getter"]||this._defaultGetter).call(this,a,e);else{for(c in a){d=a[c];h=!1;this.symbolName&&
/^(x|y|width|height|r|start|end|innerR|anchorX|anchorY)/.test(c)&&(f||(this.symbolAttr(a),f=!0),h=!0);if(this.rotation&&(c==="x"||c==="y"))this.doTransform=!0;h||(this[c+"Setter"]||this._defaultSetter).call(this,d,c,e);this.shadows&&/^(width|height|visibility|x|y|d|transform|cx|cy|r)$/.test(c)&&this.updateShadows(c,d)}if(this.doTransform)this.updateTransform(),this.doTransform=!1}return g},updateShadows:function(a,b){for(var c=this.shadows,d=c.length;d--;)c[d].setAttribute(a,a==="height"?u(b-(c[d].cutHeight||
0),0):a==="d"?this.d:b)},addClass:function(a){var b=this.element,c=J(b,"class")||"";c.indexOf(a)===-1&&J(b,"class",c+" "+a);return this},symbolAttr:function(a){var b=this;o("x,y,r,start,end,width,height,innerR,anchorX,anchorY".split(","),function(c){b[c]=p(a[c],b[c])});b.attr({d:b.renderer.symbols[b.symbolName](b.x,b.y,b.width,b.height,b)})},clip:function(a){return this.attr("clip-path",a?"url("+this.renderer.url+"#"+a.id+")":P)},crisp:function(a){var b,c={},d,e=a.strokeWidth||this.strokeWidth||0;
d=r(e)%2/2;a.x=V(a.x||this.x||0)+d;a.y=V(a.y||this.y||0)+d;a.width=V((a.width||this.width||0)-2*d);a.height=V((a.height||this.height||0)-2*d);a.strokeWidth=e;for(b in a)this[b]!==a[b]&&(this[b]=c[b]=a[b]);return c},css:function(a){var b=this.styles,c={},d=this.element,e,f,g="";e=!b;if(a&&a.color)a.fill=a.color;if(b)for(f in a)a[f]!==b[f]&&(c[f]=a[f],e=!0);if(e){e=this.textWidth=a&&a.width&&d.nodeName.toLowerCase()==="text"&&D(a.width)||this.textWidth;b&&(a=x(b,c));this.styles=a;e&&(fa||!ca&&this.renderer.forExport)&&
delete a.width;if(ya&&!ca)L(this.element,a);else{b=function(a,b){return"-"+b.toLowerCase()};for(f in a)g+=f.replace(/([A-Z])/g,b)+":"+a[f]+";";J(d,"style",g)}e&&this.added&&this.renderer.buildText(this)}return this},on:function(a,b){var c=this,d=c.element;ab&&a==="click"?(d.ontouchstart=function(a){c.touchEventFired=Aa.now();a.preventDefault();b.call(d,a)},d.onclick=function(a){(Ba.indexOf("Android")===-1||Aa.now()-(c.touchEventFired||0)>1100)&&b.call(d,a)}):d["on"+a]=b;return this},setRadialReference:function(a){this.element.radialReference=
a;return this},translate:function(a,b){return this.attr({translateX:a,translateY:b})},invert:function(){this.inverted=!0;this.updateTransform();return this},updateTransform:function(){var a=this.translateX||0,b=this.translateY||0,c=this.scaleX,d=this.scaleY,e=this.inverted,f=this.rotation,g=this.element;e&&(a+=this.attr("width"),b+=this.attr("height"));a=["translate("+a+","+b+")"];e?a.push("rotate(90) scale(-1,1)"):f&&a.push("rotate("+f+" "+(g.getAttribute("x")||0)+" "+(g.getAttribute("y")||0)+")");
(q(c)||q(d))&&a.push("scale("+p(c,1)+" "+p(d,1)+")");a.length&&g.setAttribute("transform",a.join(" "))},toFront:function(){var a=this.element;a.parentNode.appendChild(a);return this},align:function(a,b,c){var d,e,f,g,h={};e=this.renderer;f=e.alignedObjects;if(a){if(this.alignOptions=a,this.alignByTranslate=b,!c||Da(c))this.alignTo=d=c||"renderer",ja(f,this),f.push(this),c=null}else a=this.alignOptions,b=this.alignByTranslate,d=this.alignTo;c=p(c,e[d],e);d=a.align;e=a.verticalAlign;f=(c.x||0)+(a.x||
0);g=(c.y||0)+(a.y||0);if(d==="right"||d==="center")f+=(c.width-(a.width||0))/{right:1,center:2}[d];h[b?"translateX":"x"]=r(f);if(e==="bottom"||e==="middle")g+=(c.height-(a.height||0))/({bottom:1,middle:2}[e]||1);h[b?"translateY":"y"]=r(g);this[this.placed?"animate":"attr"](h);this.placed=!0;this.alignAttr=h;return this},getBBox:function(a){var b,c=this.renderer,d,e=this.rotation,f=this.element,g=this.styles,h=e*ha;d=this.textStr;var i,j=f.style,k,l;d!==y&&(l=["",e||0,g&&g.fontSize,f.style.width].join(","),
l=d===""||Pb.test(d)?"num:"+d.toString().length+l:d+l);l&&!a&&(b=c.cache[l]);if(!b){if(f.namespaceURI===Ca||c.forExport){try{k=this.fakeTS&&function(a){o(f.querySelectorAll(".highcharts-text-shadow"),function(b){b.style.display=a})},La&&j.textShadow?(i=j.textShadow,j.textShadow=""):k&&k(P),b=f.getBBox?x({},f.getBBox()):{width:f.offsetWidth,height:f.offsetHeight},i?j.textShadow=i:k&&k("")}catch(m){}if(!b||b.width<0)b={width:0,height:0}}else b=this.htmlGetBBox();if(c.isSVG){a=b.width;d=b.height;if(ya&&
g&&g.fontSize==="11px"&&d.toPrecision(3)==="16.9")b.height=d=14;if(e)b.width=O(d*aa(h))+O(a*X(h)),b.height=O(d*X(h))+O(a*aa(h))}c.cache[l]=b}return b},show:function(a){a&&this.element.namespaceURI===Ca?this.element.removeAttribute("visibility"):this.attr({visibility:a?"inherit":"visible"});return this},hide:function(){return this.attr({visibility:"hidden"})},fadeOut:function(a){var b=this;b.animate({opacity:0},{duration:a||150,complete:function(){b.attr({y:-9999})}})},add:function(a){var b=this.renderer,
c=this.element,d;if(a)this.parentGroup=a;this.parentInverted=a&&a.inverted;this.textStr!==void 0&&b.buildText(this);this.added=!0;if(!a||a.handleZ||this.zIndex)d=this.zIndexSetter();d||(a?a.element:b.box).appendChild(c);if(this.onAdd)this.onAdd();return this},safeRemoveChild:function(a){var b=a.parentNode;b&&b.removeChild(a)},destroy:function(){var a=this,b=a.element||{},c=a.shadows,d=a.renderer.isSVG&&b.nodeName==="SPAN"&&a.parentGroup,e,f;b.onclick=b.onmouseout=b.onmouseover=b.onmousemove=b.point=
null;db(a);if(a.clipPath)a.clipPath=a.clipPath.destroy();if(a.stops){for(f=0;f<a.stops.length;f++)a.stops[f]=a.stops[f].destroy();a.stops=null}a.safeRemoveChild(b);for(c&&o(c,function(b){a.safeRemoveChild(b)});d&&d.div&&d.div.childNodes.length===0;)b=d.parentGroup,a.safeRemoveChild(d.div),delete d.div,d=b;a.alignTo&&ja(a.renderer.alignedObjects,a);for(e in a)delete a[e];return null},shadow:function(a,b,c){var d=[],e,f,g=this.element,h,i,j,k;if(a){i=p(a.width,3);j=(a.opacity||0.15)/i;k=this.parentInverted?
"(-1,-1)":"("+p(a.offsetX,1)+", "+p(a.offsetY,1)+")";for(e=1;e<=i;e++){f=g.cloneNode(0);h=i*2+1-2*e;J(f,{isShadow:"true",stroke:a.color||"black","stroke-opacity":j*e,"stroke-width":h,transform:"translate"+k,fill:P});if(c)J(f,"height",u(J(f,"height")-h,0)),f.cutHeight=h;b?b.element.appendChild(f):g.parentNode.insertBefore(f,g);d.push(f)}this.shadows=d}return this},xGetter:function(a){this.element.nodeName==="circle"&&(a={x:"cx",y:"cy"}[a]||a);return this._defaultGetter(a)},_defaultGetter:function(a){a=
p(this[a],this.element?this.element.getAttribute(a):null,0);/^[\-0-9\.]+$/.test(a)&&(a=parseFloat(a));return a},dSetter:function(a,b,c){a&&a.join&&(a=a.join(" "));/(NaN| {2}|^$)/.test(a)&&(a="M 0 0");c.setAttribute(b,a);this[b]=a},dashstyleSetter:function(a){var b;if(a=a&&a.toLowerCase()){a=a.replace("shortdashdotdot","3,1,1,1,1,1,").replace("shortdashdot","3,1,1,1").replace("shortdot","1,1,").replace("shortdash","3,1,").replace("longdash","8,3,").replace(/dot/g,"1,3,").replace("dash","4,3,").replace(/,$/,
"").split(",");for(b=a.length;b--;)a[b]=D(a[b])*this["stroke-width"];a=a.join(",").replace("NaN","none");this.element.setAttribute("stroke-dasharray",a)}},alignSetter:function(a){this.element.setAttribute("text-anchor",{left:"start",center:"middle",right:"end"}[a])},opacitySetter:function(a,b,c){this[b]=a;c.setAttribute(b,a)},titleSetter:function(a){var b=this.element.getElementsByTagName("title")[0];b||(b=B.createElementNS(Ca,"title"),this.element.appendChild(b));b.appendChild(B.createTextNode(String(p(a),
"").replace(/<[^>]*>/g,"")))},textSetter:function(a){if(a!==this.textStr)delete this.bBox,this.textStr=a,this.added&&this.renderer.buildText(this)},fillSetter:function(a,b,c){typeof a==="string"?c.setAttribute(b,a):a&&this.colorGradient(a,b,c)},zIndexSetter:function(a,b){var c=this.renderer,d=this.parentGroup,c=(d||c).element||c.box,e,f,g=this.element,h;e=this.added;var i;q(a)&&(g.setAttribute(b,a),a=+a,this[b]===a&&(e=!1),this[b]=a);if(e){if((a=this.zIndex)&&d)d.handleZ=!0;d=c.childNodes;for(i=0;i<
d.length&&!h;i++)if(e=d[i],f=J(e,"zIndex"),e!==g&&(D(f)>a||!q(a)&&q(f)))c.insertBefore(g,e),h=!0;h||c.appendChild(g)}return h},_defaultSetter:function(a,b,c){c.setAttribute(b,a)}};Q.prototype.yGetter=Q.prototype.xGetter;Q.prototype.translateXSetter=Q.prototype.translateYSetter=Q.prototype.rotationSetter=Q.prototype.verticalAlignSetter=Q.prototype.scaleXSetter=Q.prototype.scaleYSetter=function(a,b){this[b]=a;this.doTransform=!0};Q.prototype["stroke-widthSetter"]=Q.prototype.strokeSetter=function(a,
b,c){this[b]=a;if(this.stroke&&this["stroke-width"])this.strokeWidth=this["stroke-width"],Q.prototype.fillSetter.call(this,this.stroke,"stroke",c),c.setAttribute("stroke-width",this["stroke-width"]),this.hasStroke=!0;else if(b==="stroke-width"&&a===0&&this.hasStroke)c.removeAttribute("stroke"),this.hasStroke=!1};var ua=function(){this.init.apply(this,arguments)};ua.prototype={Element:Q,init:function(a,b,c,d,e){var f=location,g,d=this.createElement("svg").attr({version:"1.1"}).css(this.getStyle(d));
g=d.element;a.appendChild(g);a.innerHTML.indexOf("xmlns")===-1&&J(g,"xmlns",Ca);this.isSVG=!0;this.box=g;this.boxWrapper=d;this.alignedObjects=[];this.url=(La||ib)&&B.getElementsByTagName("base").length?f.href.replace(/#.*?$/,"").replace(/([\('\)])/g,"\\$1").replace(/ /g,"%20"):"";this.createElement("desc").add().element.appendChild(B.createTextNode("Created with Highcharts 4.1.7"));this.defs=this.createElement("defs").add();this.forExport=e;this.gradients={};this.cache={};this.setSize(b,c,!1);var h;
if(La&&a.getBoundingClientRect)this.subPixelFix=b=function(){L(a,{left:0,top:0});h=a.getBoundingClientRect();L(a,{left:ta(h.left)-h.left+"px",top:ta(h.top)-h.top+"px"})},b(),H(K,"resize",b)},getStyle:function(a){return this.style=x({fontFamily:'"Lucida Grande", "Lucida Sans Unicode", Arial, Helvetica, sans-serif',fontSize:"12px"},a)},isHidden:function(){return!this.boxWrapper.getBBox().width},destroy:function(){var a=this.defs;this.box=null;this.boxWrapper=this.boxWrapper.destroy();Qa(this.gradients||
{});this.gradients=null;if(a)this.defs=a.destroy();this.subPixelFix&&Z(K,"resize",this.subPixelFix);return this.alignedObjects=null},createElement:function(a){var b=new this.Element;b.init(this,a);return b},draw:function(){},buildText:function(a){for(var b=a.element,c=this,d=c.forExport,e=p(a.textStr,"").toString(),f=e.indexOf("<")!==-1,g=b.childNodes,h,i,j=J(b,"x"),k=a.styles,l=a.textWidth,m=k&&k.lineHeight,n=k&&k.textShadow,v=k&&k.textOverflow==="ellipsis",s=g.length,S=l&&!a.added&&this.box,N=function(a){return m?
D(m):c.fontMetrics(/(px|em)$/.test(a&&a.style.fontSize)?a.style.fontSize:k&&k.fontSize||c.style.fontSize||12,a).h},t=function(a){return a.replace(/</g,"<").replace(/>/g,">")};s--;)b.removeChild(g[s]);!f&&!n&&!v&&e.indexOf(" ")===-1?b.appendChild(B.createTextNode(t(e))):(h=/<.*style="([^"]+)".*>/,i=/<.*href="(http[^"]+)".*>/,S&&S.appendChild(b),e=f?e.replace(/<(b|strong)>/g,'<span style="font-weight:bold">').replace(/<(i|em)>/g,'<span style="font-style:italic">').replace(/<a/g,"<span").replace(/<\/(b|strong|i|em|a)>/g,
"</span>").split(/<br.*?>/g):[e],e[e.length-1]===""&&e.pop(),o(e,function(e,f){var g,m=0,e=e.replace(/<span/g,"|||<span").replace(/<\/span>/g,"</span>|||");g=e.split("|||");o(g,function(e){if(e!==""||g.length===1){var n={},s=B.createElementNS(Ca,"tspan"),p;h.test(e)&&(p=e.match(h)[1].replace(/(;| |^)color([ :])/,"$1fill$2"),J(s,"style",p));i.test(e)&&!d&&(J(s,"onclick",'location.href="'+e.match(i)[1]+'"'),L(s,{cursor:"pointer"}));e=t(e.replace(/<(.|\n)*?>/g,"")||" ");if(e!==" "){s.appendChild(B.createTextNode(e));
if(m)n.dx=0;else if(f&&j!==null)n.x=j;J(s,n);b.appendChild(s);!m&&f&&(!ca&&d&&L(s,{display:"block"}),J(s,"dy",N(s)));if(l){for(var n=e.replace(/([^\^])-/g,"$1- ").split(" "),o=g.length>1||f||n.length>1&&k.whiteSpace!=="nowrap",S,w,q,u=[],y=N(s),r=1,x=a.rotation,z=e,C=z.length;(o||v)&&(n.length||u.length);)a.rotation=0,S=a.getBBox(!0),q=S.width,!ca&&c.forExport&&(q=c.measureSpanWidth(s.firstChild.data,a.styles)),S=q>l,w===void 0&&(w=S),v&&w?(C/=2,z===""||!S&&C<0.5?n=[]:(S&&(w=!0),z=e.substring(0,z.length+
(S?-1:1)*ta(C)),n=[z+(l>3?"…":"")],s.removeChild(s.firstChild))):!S||n.length===1?(n=u,u=[],n.length&&(r++,s=B.createElementNS(Ca,"tspan"),J(s,{dy:y,x:j}),p&&J(s,"style",p),b.appendChild(s)),q>l&&(l=q)):(s.removeChild(s.firstChild),u.unshift(n.pop())),n.length&&s.appendChild(B.createTextNode(n.join(" ").replace(/- /g,"-")));w&&a.attr("title",a.textStr);a.rotation=x}m++}}})}),S&&S.removeChild(b),n&&a.applyTextShadow&&a.applyTextShadow(n))},getContrast:function(a){a=oa(a).rgba;return a[0]+a[1]+a[2]>
384?"#000000":"#FFFFFF"},button:function(a,b,c,d,e,f,g,h,i){var j=this.label(a,b,c,i,null,null,null,null,"button"),k=0,l,m,n,v,s,p,a={x1:0,y1:0,x2:0,y2:1},e=z({"stroke-width":1,stroke:"#CCCCCC",fill:{linearGradient:a,stops:[[0,"#FEFEFE"],[1,"#F6F6F6"]]},r:2,padding:5,style:{color:"black"}},e);n=e.style;delete e.style;f=z(e,{stroke:"#68A",fill:{linearGradient:a,stops:[[0,"#FFF"],[1,"#ACF"]]}},f);v=f.style;delete f.style;g=z(e,{stroke:"#68A",fill:{linearGradient:a,stops:[[0,"#9BD"],[1,"#CDF"]]}},g);
s=g.style;delete g.style;h=z(e,{style:{color:"#CCC"}},h);p=h.style;delete h.style;H(j.element,ya?"mouseover":"mouseenter",function(){k!==3&&j.attr(f).css(v)});H(j.element,ya?"mouseout":"mouseleave",function(){k!==3&&(l=[e,f,g][k],m=[n,v,s][k],j.attr(l).css(m))});j.setState=function(a){(j.state=k=a)?a===2?j.attr(g).css(s):a===3&&j.attr(h).css(p):j.attr(e).css(n)};return j.on("click",function(){k!==3&&d.call(j)}).attr(e).css(x({cursor:"default"},n))},crispLine:function(a,b){a[1]===a[4]&&(a[1]=a[4]=
r(a[1])-b%2/2);a[2]===a[5]&&(a[2]=a[5]=r(a[2])+b%2/2);return a},path:function(a){var b={fill:P};Ha(a)?b.d=a:da(a)&&x(b,a);return this.createElement("path").attr(b)},circle:function(a,b,c){a=da(a)?a:{x:a,y:b,r:c};b=this.createElement("circle");b.xSetter=function(a){this.element.setAttribute("cx",a)};b.ySetter=function(a){this.element.setAttribute("cy",a)};return b.attr(a)},arc:function(a,b,c,d,e,f){if(da(a))b=a.y,c=a.r,d=a.innerR,e=a.start,f=a.end,a=a.x;a=this.symbol("arc",a||0,b||0,c||0,c||0,{innerR:d||
0,start:e||0,end:f||0});a.r=c;return a},rect:function(a,b,c,d,e,f){var e=da(a)?a.r:e,g=this.createElement("rect"),a=da(a)?a:a===y?{}:{x:a,y:b,width:u(c,0),height:u(d,0)};if(f!==y)a.strokeWidth=f,a=g.crisp(a);if(e)a.r=e;g.rSetter=function(a){J(this.element,{rx:a,ry:a})};return g.attr(a)},setSize:function(a,b,c){var d=this.alignedObjects,e=d.length;this.width=a;this.height=b;for(this.boxWrapper[p(c,!0)?"animate":"attr"]({width:a,height:b});e--;)d[e].align()},g:function(a){var b=this.createElement("g");
return q(a)?b.attr({"class":"highcharts-"+a}):b},image:function(a,b,c,d,e){var f={preserveAspectRatio:P};arguments.length>1&&x(f,{x:b,y:c,width:d,height:e});f=this.createElement("image").attr(f);f.element.setAttributeNS?f.element.setAttributeNS("http://www.w3.org/1999/xlink","href",a):f.element.setAttribute("hc-svg-href",a);return f},symbol:function(a,b,c,d,e,f){var g,h=this.symbols[a],h=h&&h(r(b),r(c),d,e,f),i=/^url\((.*?)\)$/,j,k;if(h)g=this.path(h),x(g,{symbolName:a,x:b,y:c,width:d,height:e}),
f&&x(g,f);else if(i.test(a))k=function(a,b){a.element&&(a.attr({width:b[0],height:b[1]}),a.alignByTranslate||a.translate(r((d-b[0])/2),r((e-b[1])/2)))},j=a.match(i)[1],a=Lb[j]||f&&f.width&&f.height&&[f.width,f.height],g=this.image(j).attr({x:b,y:c}),g.isImg=!0,a?k(g,a):(g.attr({width:0,height:0}),$("img",{onload:function(){k(g,Lb[j]=[this.width,this.height])},src:j}));return g},symbols:{circle:function(a,b,c,d){var e=0.166*c;return["M",a+c/2,b,"C",a+c+e,b,a+c+e,b+d,a+c/2,b+d,"C",a-e,b+d,a-e,b,a+c/
2,b,"Z"]},square:function(a,b,c,d){return["M",a,b,"L",a+c,b,a+c,b+d,a,b+d,"Z"]},triangle:function(a,b,c,d){return["M",a+c/2,b,"L",a+c,b+d,a,b+d,"Z"]},"triangle-down":function(a,b,c,d){return["M",a,b,"L",a+c,b,a+c/2,b+d,"Z"]},diamond:function(a,b,c,d){return["M",a+c/2,b,"L",a+c,b+d/2,a+c/2,b+d,a,b+d/2,"Z"]},arc:function(a,b,c,d,e){var f=e.start,c=e.r||c||d,g=e.end-0.001,d=e.innerR,h=e.open,i=X(f),j=aa(f),k=X(g),g=aa(g),e=e.end-f<ma?0:1;return["M",a+c*i,b+c*j,"A",c,c,0,e,1,a+c*k,b+c*g,h?"M":"L",a+d*
k,b+d*g,"A",d,d,0,e,0,a+d*i,b+d*j,h?"":"Z"]},callout:function(a,b,c,d,e){var f=C(e&&e.r||0,c,d),g=f+6,h=e&&e.anchorX,e=e&&e.anchorY,i;i=["M",a+f,b,"L",a+c-f,b,"C",a+c,b,a+c,b,a+c,b+f,"L",a+c,b+d-f,"C",a+c,b+d,a+c,b+d,a+c-f,b+d,"L",a+f,b+d,"C",a,b+d,a,b+d,a,b+d-f,"L",a,b+f,"C",a,b,a,b,a+f,b];h&&h>c&&e>b+g&&e<b+d-g?i.splice(13,3,"L",a+c,e-6,a+c+6,e,a+c,e+6,a+c,b+d-f):h&&h<0&&e>b+g&&e<b+d-g?i.splice(33,3,"L",a,e+6,a-6,e,a,e-6,a,b+f):e&&e>d&&h>a+g&&h<a+c-g?i.splice(23,3,"L",h+6,b+d,h,b+d+6,h-6,b+d,a+
f,b+d):e&&e<0&&h>a+g&&h<a+c-g&&i.splice(3,3,"L",h-6,b,h,b-6,h+6,b,c-f,b);return i}},clipRect:function(a,b,c,d){var e="highcharts-"+yb++,f=this.createElement("clipPath").attr({id:e}).add(this.defs),a=this.rect(a,b,c,d,0).add(f);a.id=e;a.clipPath=f;a.count=0;return a},text:function(a,b,c,d){var e=fa||!ca&&this.forExport,f={};if(d&&!this.forExport)return this.html(a,b,c);f.x=Math.round(b||0);if(c)f.y=Math.round(c);if(a||a===0)f.text=a;a=this.createElement("text").attr(f);e&&a.css({position:"absolute"});
if(!d)a.xSetter=function(a,b,c){var d=c.getElementsByTagName("tspan"),e,f=c.getAttribute(b),m;for(m=0;m<d.length;m++)e=d[m],e.getAttribute(b)===f&&e.setAttribute(b,a);c.setAttribute(b,a)};return a},fontMetrics:function(a,b){var c,d,a=a||this.style.fontSize;b&&K.getComputedStyle&&(b=b.element||b,a=(c=K.getComputedStyle(b,""))&&c.fontSize);a=/px/.test(a)?D(a):/em/.test(a)?parseFloat(a)*12:12;c=a<24?a+3:r(a*1.2);d=r(c*0.8);return{h:c,b:d,f:a}},rotCorr:function(a,b,c){var d=a;b&&c&&(d=u(d*X(b*ha),4));
return{x:-a/3*aa(b*ha),y:d}},label:function(a,b,c,d,e,f,g,h,i){function j(){var a,b;a=v.element.style;p=(ga===void 0||u===void 0||n.styles.textAlign)&&q(v.textStr)&&v.getBBox();n.width=(ga||p.width||0)+2*t+w;n.height=(u||p.height||0)+2*t;A=t+m.fontMetrics(a&&a.fontSize,v).b;if(D){if(!s)a=r(-N*t)+B,b=(h?-A:0)+B,n.box=s=d?m.symbol(d,a,b,n.width,n.height,G):m.rect(a,b,n.width,n.height,0,G[Qb]),s.attr("fill",P).add(n);s.isImg||s.attr(x({width:r(n.width),height:r(n.height)},G));G=null}}function k(){var a=
n.styles,a=a&&a.textAlign,b=w+t*(1-N),c;c=h?0:A;if(q(ga)&&p&&(a==="center"||a==="right"))b+={center:0.5,right:1}[a]*(ga-p.width);if(b!==v.x||c!==v.y)v.attr("x",b),c!==y&&v.attr("y",c);v.x=b;v.y=c}function l(a,b){s?s.attr(a,b):G[a]=b}var m=this,n=m.g(i),v=m.text("",0,0,g).attr({zIndex:1}),s,p,N=0,t=3,w=0,ga,u,Ab,C,B=0,G={},A,D;n.onAdd=function(){v.add(n);n.attr({text:a||a===0?a:"",x:b,y:c});s&&q(e)&&n.attr({anchorX:e,anchorY:f})};n.widthSetter=function(a){ga=a};n.heightSetter=function(a){u=a};n.paddingSetter=
function(a){if(q(a)&&a!==t)t=n.padding=a,k()};n.paddingLeftSetter=function(a){q(a)&&a!==w&&(w=a,k())};n.alignSetter=function(a){N={left:0,center:0.5,right:1}[a]};n.textSetter=function(a){a!==y&&v.textSetter(a);j();k()};n["stroke-widthSetter"]=function(a,b){a&&(D=!0);B=a%2/2;l(b,a)};n.strokeSetter=n.fillSetter=n.rSetter=function(a,b){b==="fill"&&a&&(D=!0);l(b,a)};n.anchorXSetter=function(a,b){e=a;l(b,r(a)-B-Ab)};n.anchorYSetter=function(a,b){f=a;l(b,a-C)};n.xSetter=function(a){n.x=a;N&&(a-=N*((ga||
p.width)+t));Ab=r(a);n.attr("translateX",Ab)};n.ySetter=function(a){C=n.y=r(a);n.attr("translateY",C)};var F=n.css;return x(n,{css:function(a){if(a){var b={},a=z(a);o(n.textProps,function(c){a[c]!==y&&(b[c]=a[c],delete a[c])});v.css(b)}return F.call(n,a)},getBBox:function(){return{width:p.width+2*t,height:p.height+2*t,x:p.x-t,y:p.y-t}},shadow:function(a){s&&s.shadow(a);return n},destroy:function(){Z(n.element,"mouseenter");Z(n.element,"mouseleave");v&&(v=v.destroy());s&&(s=s.destroy());Q.prototype.destroy.call(n);
n=m=j=k=l=null}})}};$a=ua;x(Q.prototype,{htmlCss:function(a){var b=this.element;if(b=a&&b.tagName==="SPAN"&&a.width)delete a.width,this.textWidth=b,this.updateTransform();if(a&&a.textOverflow==="ellipsis")a.whiteSpace="nowrap",a.overflow="hidden";this.styles=x(this.styles,a);L(this.element,a);return this},htmlGetBBox:function(){var a=this.element;if(a.nodeName==="text")a.style.position="absolute";return{x:a.offsetLeft,y:a.offsetTop,width:a.offsetWidth,height:a.offsetHeight}},htmlUpdateTransform:function(){if(this.added){var a=
this.renderer,b=this.element,c=this.translateX||0,d=this.translateY||0,e=this.x||0,f=this.y||0,g=this.textAlign||"left",h={left:0,center:0.5,right:1}[g],i=this.shadows,j=this.styles;L(b,{marginLeft:c,marginTop:d});i&&o(i,function(a){L(a,{marginLeft:c+1,marginTop:d+1})});this.inverted&&o(b.childNodes,function(c){a.invertChild(c,b)});if(b.tagName==="SPAN"){var k=this.rotation,l,m=D(this.textWidth),n=[k,g,b.innerHTML,this.textWidth].join(",");if(n!==this.cTT){l=a.fontMetrics(b.style.fontSize).b;q(k)&&
this.setSpanRotation(k,h,l);i=p(this.elemWidth,b.offsetWidth);if(i>m&&/[ \-]/.test(b.textContent||b.innerText))L(b,{width:m+"px",display:"block",whiteSpace:j&&j.whiteSpace||"normal"}),i=m;this.getSpanCorrection(i,l,h,k,g)}L(b,{left:e+(this.xCorr||0)+"px",top:f+(this.yCorr||0)+"px"});if(ib)l=b.offsetHeight;this.cTT=n}}else this.alignOnAdd=!0},setSpanRotation:function(a,b,c){var d={},e=ya?"-ms-transform":ib?"-webkit-transform":La?"MozTransform":Jb?"-o-transform":"";d[e]=d.transform="rotate("+a+"deg)";
d[e+(La?"Origin":"-origin")]=d.transformOrigin=b*100+"% "+c+"px";L(this.element,d)},getSpanCorrection:function(a,b,c){this.xCorr=-a*c;this.yCorr=-b}});x(ua.prototype,{html:function(a,b,c){var d=this.createElement("span"),e=d.element,f=d.renderer;d.textSetter=function(a){a!==e.innerHTML&&delete this.bBox;e.innerHTML=this.textStr=a};d.xSetter=d.ySetter=d.alignSetter=d.rotationSetter=function(a,b){b==="align"&&(b="textAlign");d[b]=a;d.htmlUpdateTransform()};d.attr({text:a,x:r(b),y:r(c)}).css({position:"absolute",
fontFamily:this.style.fontFamily,fontSize:this.style.fontSize});e.style.whiteSpace="nowrap";d.css=d.htmlCss;if(f.isSVG)d.add=function(a){var b,c=f.box.parentNode,j=[];if(this.parentGroup=a){if(b=a.div,!b){for(;a;)j.push(a),a=a.parentGroup;o(j.reverse(),function(a){var d,e=J(a.element,"class");e&&(e={className:e});b=a.div=a.div||$(Ka,e,{position:"absolute",left:(a.translateX||0)+"px",top:(a.translateY||0)+"px"},b||c);d=b.style;x(a,{translateXSetter:function(b,c){d.left=b+"px";a[c]=b;a.doTransform=
!0},translateYSetter:function(b,c){d.top=b+"px";a[c]=b;a.doTransform=!0},visibilitySetter:function(a,b){d[b]=a}})})}}else b=c;b.appendChild(e);d.added=!0;d.alignOnAdd&&d.htmlUpdateTransform();return d};return d}});if(!ca&&!fa){F={init:function(a,b){var c=["<",b,' filled="f" stroked="f"'],d=["position: ","absolute",";"],e=b===Ka;(b==="shape"||e)&&d.push("left:0;top:0;width:1px;height:1px;");d.push("visibility: ",e?"hidden":"visible");c.push(' style="',d.join(""),'"/>');if(b)c=e||b==="span"||b==="img"?
c.join(""):a.prepVML(c),this.element=$(c);this.renderer=a},add:function(a){var b=this.renderer,c=this.element,d=b.box,d=a?a.element||a:d;a&&a.inverted&&b.invertChild(c,d);d.appendChild(c);this.added=!0;this.alignOnAdd&&!this.deferUpdateTransform&&this.updateTransform();if(this.onAdd)this.onAdd();return this},updateTransform:Q.prototype.htmlUpdateTransform,setSpanRotation:function(){var a=this.rotation,b=X(a*ha),c=aa(a*ha);L(this.element,{filter:a?["progid:DXImageTransform.Microsoft.Matrix(M11=",b,
", M12=",-c,", M21=",c,", M22=",b,", sizingMethod='auto expand')"].join(""):P})},getSpanCorrection:function(a,b,c,d,e){var f=d?X(d*ha):1,g=d?aa(d*ha):0,h=p(this.elemHeight,this.element.offsetHeight),i;this.xCorr=f<0&&-a;this.yCorr=g<0&&-h;i=f*g<0;this.xCorr+=g*b*(i?1-c:c);this.yCorr-=f*b*(d?i?c:1-c:1);e&&e!=="left"&&(this.xCorr-=a*c*(f<0?-1:1),d&&(this.yCorr-=h*c*(g<0?-1:1)),L(this.element,{textAlign:e}))},pathToVML:function(a){for(var b=a.length,c=[];b--;)if(ra(a[b]))c[b]=r(a[b]*10)-5;else if(a[b]===
"Z")c[b]="x";else if(c[b]=a[b],a.isArc&&(a[b]==="wa"||a[b]==="at"))c[b+5]===c[b+7]&&(c[b+7]+=a[b+7]>a[b+5]?1:-1),c[b+6]===c[b+8]&&(c[b+8]+=a[b+8]>a[b+6]?1:-1);return c.join(" ")||"x"},clip:function(a){var b=this,c;a?(c=a.members,ja(c,b),c.push(b),b.destroyClip=function(){ja(c,b)},a=a.getCSS(b)):(b.destroyClip&&b.destroyClip(),a={clip:hb?"inherit":"rect(auto)"});return b.css(a)},css:Q.prototype.htmlCss,safeRemoveChild:function(a){a.parentNode&&Ra(a)},destroy:function(){this.destroyClip&&this.destroyClip();
return Q.prototype.destroy.apply(this)},on:function(a,b){this.element["on"+a]=function(){var a=K.event;a.target=a.srcElement;b(a)};return this},cutOffPath:function(a,b){var c,a=a.split(/[ ,]/);c=a.length;if(c===9||c===11)a[c-4]=a[c-2]=D(a[c-2])-10*b;return a.join(" ")},shadow:function(a,b,c){var d=[],e,f=this.element,g=this.renderer,h,i=f.style,j,k=f.path,l,m,n,v;k&&typeof k.value!=="string"&&(k="x");m=k;if(a){n=p(a.width,3);v=(a.opacity||0.15)/n;for(e=1;e<=3;e++){l=n*2+1-2*e;c&&(m=this.cutOffPath(k.value,
l+0.5));j=['<shape isShadow="true" strokeweight="',l,'" filled="false" path="',m,'" coordsize="10 10" style="',f.style.cssText,'" />'];h=$(g.prepVML(j),null,{left:D(i.left)+p(a.offsetX,1),top:D(i.top)+p(a.offsetY,1)});if(c)h.cutOff=l+1;j=['<stroke color="',a.color||"black",'" opacity="',v*e,'"/>'];$(g.prepVML(j),null,null,h);b?b.element.appendChild(h):f.parentNode.insertBefore(h,f);d.push(h)}this.shadows=d}return this},updateShadows:na,setAttr:function(a,b){hb?this.element[a]=b:this.element.setAttribute(a,
b)},classSetter:function(a){this.element.className=a},dashstyleSetter:function(a,b,c){(c.getElementsByTagName("stroke")[0]||$(this.renderer.prepVML(["<stroke/>"]),null,null,c))[b]=a||"solid";this[b]=a},dSetter:function(a,b,c){var d=this.shadows,a=a||[];this.d=a.join&&a.join(" ");c.path=a=this.pathToVML(a);if(d)for(c=d.length;c--;)d[c].path=d[c].cutOff?this.cutOffPath(a,d[c].cutOff):a;this.setAttr(b,a)},fillSetter:function(a,b,c){var d=c.nodeName;if(d==="SPAN")c.style.color=a;else if(d!=="IMG")c.filled=
a!==P,this.setAttr("fillcolor",this.renderer.color(a,c,b,this))},opacitySetter:na,rotationSetter:function(a,b,c){c=c.style;this[b]=c[b]=a;c.left=-r(aa(a*ha)+1)+"px";c.top=r(X(a*ha))+"px"},strokeSetter:function(a,b,c){this.setAttr("strokecolor",this.renderer.color(a,c,b))},"stroke-widthSetter":function(a,b,c){c.stroked=!!a;this[b]=a;ra(a)&&(a+="px");this.setAttr("strokeweight",a)},titleSetter:function(a,b){this.setAttr(b,a)},visibilitySetter:function(a,b,c){a==="inherit"&&(a="visible");this.shadows&&
o(this.shadows,function(c){c.style[b]=a});c.nodeName==="DIV"&&(a=a==="hidden"?"-999em":0,hb||(c.style[b]=a?"visible":"hidden"),b="top");c.style[b]=a},xSetter:function(a,b,c){this[b]=a;b==="x"?b="left":b==="y"&&(b="top");this.updateClipping?(this[b]=a,this.updateClipping()):c.style[b]=a},zIndexSetter:function(a,b,c){c.style[b]=a}};A.VMLElement=F=ka(Q,F);F.prototype.ySetter=F.prototype.widthSetter=F.prototype.heightSetter=F.prototype.xSetter;var Na={Element:F,isIE8:Ba.indexOf("MSIE 8.0")>-1,init:function(a,
b,c,d){var e;this.alignedObjects=[];d=this.createElement(Ka).css(x(this.getStyle(d),{position:"relative"}));e=d.element;a.appendChild(d.element);this.isVML=!0;this.box=e;this.boxWrapper=d;this.cache={};this.setSize(b,c,!1);if(!B.namespaces.hcv){B.namespaces.add("hcv","urn:schemas-microsoft-com:vml");try{B.createStyleSheet().cssText="hcv\\:fill, hcv\\:path, hcv\\:shape, hcv\\:stroke{ behavior:url(#default#VML); display: inline-block; } "}catch(f){B.styleSheets[0].cssText+="hcv\\:fill, hcv\\:path, hcv\\:shape, hcv\\:stroke{ behavior:url(#default#VML); display: inline-block; } "}}},
isHidden:function(){return!this.box.offsetWidth},clipRect:function(a,b,c,d){var e=this.createElement(),f=da(a);return x(e,{members:[],count:0,left:(f?a.x:a)+1,top:(f?a.y:b)+1,width:(f?a.width:c)-1,height:(f?a.height:d)-1,getCSS:function(a){var b=a.element,c=b.nodeName,a=a.inverted,d=this.top-(c==="shape"?b.offsetTop:0),e=this.left,b=e+this.width,f=d+this.height,d={clip:"rect("+r(a?e:d)+"px,"+r(a?f:b)+"px,"+r(a?b:f)+"px,"+r(a?d:e)+"px)"};!a&&hb&&c==="DIV"&&x(d,{width:b+"px",height:f+"px"});return d},
updateClipping:function(){o(e.members,function(a){a.element&&a.css(e.getCSS(a))})}})},color:function(a,b,c,d){var e=this,f,g=/^rgba/,h,i,j=P;a&&a.linearGradient?i="gradient":a&&a.radialGradient&&(i="pattern");if(i){var k,l,m=a.linearGradient||a.radialGradient,n,v,s,p,N,t="",a=a.stops,w,ga=[],q=function(){h=['<fill colors="'+ga.join(",")+'" opacity="',s,'" o:opacity2="',v,'" type="',i,'" ',t,'focus="100%" method="any" />'];$(e.prepVML(h),null,null,b)};n=a[0];w=a[a.length-1];n[0]>0&&a.unshift([0,n[1]]);
w[0]<1&&a.push([1,w[1]]);o(a,function(a,b){g.test(a[1])?(f=oa(a[1]),k=f.get("rgb"),l=f.get("a")):(k=a[1],l=1);ga.push(a[0]*100+"% "+k);b?(s=l,p=k):(v=l,N=k)});if(c==="fill")if(i==="gradient")c=m.x1||m[0]||0,a=m.y1||m[1]||0,n=m.x2||m[2]||0,m=m.y2||m[3]||0,t='angle="'+(90-W.atan((m-a)/(n-c))*180/ma)+'"',q();else{var j=m.r,u=j*2,y=j*2,r=m.cx,x=m.cy,C=b.radialReference,z,j=function(){C&&(z=d.getBBox(),r+=(C[0]-z.x)/z.width-0.5,x+=(C[1]-z.y)/z.height-0.5,u*=C[2]/z.width,y*=C[2]/z.height);t='src="'+T.global.VMLRadialGradientURL+
'" size="'+u+","+y+'" origin="0.5,0.5" position="'+r+","+x+'" color2="'+N+'" ';q()};d.added?j():d.onAdd=j;j=p}else j=k}else if(g.test(a)&&b.tagName!=="IMG")f=oa(a),h=["<",c,' opacity="',f.get("a"),'"/>'],$(this.prepVML(h),null,null,b),j=f.get("rgb");else{j=b.getElementsByTagName(c);if(j.length)j[0].opacity=1,j[0].type="solid";j=a}return j},prepVML:function(a){var b=this.isIE8,a=a.join("");b?(a=a.replace("/>",' xmlns="urn:schemas-microsoft-com:vml" />'),a=a.indexOf('style="')===-1?a.replace("/>",' style="display:inline-block;behavior:url(#default#VML);" />'):
a.replace('style="','style="display:inline-block;behavior:url(#default#VML);')):a=a.replace("<","<hcv:");return a},text:ua.prototype.html,path:function(a){var b={coordsize:"10 10"};Ha(a)?b.d=a:da(a)&&x(b,a);return this.createElement("shape").attr(b)},circle:function(a,b,c){var d=this.symbol("circle");if(da(a))c=a.r,b=a.y,a=a.x;d.isCircle=!0;d.r=c;return d.attr({x:a,y:b})},g:function(a){var b;a&&(b={className:"highcharts-"+a,"class":"highcharts-"+a});return this.createElement(Ka).attr(b)},image:function(a,
b,c,d,e){var f=this.createElement("img").attr({src:a});arguments.length>1&&f.attr({x:b,y:c,width:d,height:e});return f},createElement:function(a){return a==="rect"?this.symbol(a):ua.prototype.createElement.call(this,a)},invertChild:function(a,b){var c=this,d=b.style,e=a.tagName==="IMG"&&a.style;L(a,{flip:"x",left:D(d.width)-(e?D(e.top):1),top:D(d.height)-(e?D(e.left):1),rotation:-90});o(a.childNodes,function(b){c.invertChild(b,a)})},symbols:{arc:function(a,b,c,d,e){var f=e.start,g=e.end,h=e.r||c||
d,c=e.innerR,d=X(f),i=aa(f),j=X(g),k=aa(g);if(g-f===0)return["x"];f=["wa",a-h,b-h,a+h,b+h,a+h*d,b+h*i,a+h*j,b+h*k];e.open&&!c&&f.push("e","M",a,b);f.push("at",a-c,b-c,a+c,b+c,a+c*j,b+c*k,a+c*d,b+c*i,"x","e");f.isArc=!0;return f},circle:function(a,b,c,d,e){e&&(c=d=2*e.r);e&&e.isCircle&&(a-=c/2,b-=d/2);return["wa",a,b,a+c,b+d,a+c,b+d/2,a+c,b+d/2,"e"]},rect:function(a,b,c,d,e){return ua.prototype.symbols[!q(e)||!e.r?"square":"callout"].call(0,a,b,c,d,e)}}};A.VMLRenderer=F=function(){this.init.apply(this,
arguments)};F.prototype=z(ua.prototype,Na);$a=F}ua.prototype.measureSpanWidth=function(a,b){var c=B.createElement("span"),d;d=B.createTextNode(a);c.appendChild(d);L(c,b);this.box.appendChild(c);d=c.offsetWidth;Ra(c);return d};var Mb;if(fa)A.CanVGRenderer=F=function(){Ca="http://www.w3.org/1999/xhtml"},F.prototype.symbols={},Mb=function(){function a(){var a=b.length,d;for(d=0;d<a;d++)b[d]();b=[]}var b=[];return{push:function(c,d){b.length===0&&Rb(d,a);b.push(c)}}}(),$a=F;Ta.prototype={addLabel:function(){var a=
this.axis,b=a.options,c=a.chart,d=a.categories,e=a.names,f=this.pos,g=b.labels,h=a.tickPositions,i=f===h[0],j=f===h[h.length-1],e=d?p(d[f],e[f],f):f,d=this.label,h=h.info,k;a.isDatetimeAxis&&h&&(k=b.dateTimeLabelFormats[h.higherRanks[f]||h.unitName]);this.isFirst=i;this.isLast=j;b=a.labelFormatter.call({axis:a,chart:c,isFirst:i,isLast:j,dateTimeLabelFormat:k,value:a.isLog?ea(ia(e)):e});q(d)?d&&d.attr({text:b}):(this.labelLength=(this.label=d=q(b)&&g.enabled?c.renderer.text(b,0,0,g.useHTML).css(z(g.style)).add(a.labelGroup):
null)&&d.getBBox().width,this.rotation=0)},getLabelSize:function(){return this.label?this.label.getBBox()[this.axis.horiz?"height":"width"]:0},handleOverflow:function(a){var b=this.axis,c=a.x,d=b.chart.chartWidth,e=b.chart.spacing,f=p(b.labelLeft,C(b.pos,e[3])),e=p(b.labelRight,u(b.pos+b.len,d-e[1])),g=this.label,h=this.rotation,i={left:0,center:0.5,right:1}[b.labelAlign],j=g.getBBox().width,k=b.slotWidth,l=1,m,n={};if(h)h<0&&c-i*j<f?m=r(c/X(h*ha)-f):h>0&&c+i*j>e&&(m=r((d-c)/X(h*ha)));else if(d=c+
(1-i)*j,c-i*j<f?k=a.x+k*(1-i)-f:d>e&&(k=e-a.x+k*i,l=-1),k=C(b.slotWidth,k),k<b.slotWidth&&b.labelAlign==="center"&&(a.x+=l*(b.slotWidth-k-i*(b.slotWidth-C(j,k)))),j>k||b.autoRotation&&g.styles.width)m=k;if(m){n.width=m;if(!b.options.labels.style.textOverflow)n.textOverflow="ellipsis";g.css(n)}},getPosition:function(a,b,c,d){var e=this.axis,f=e.chart,g=d&&f.oldChartHeight||f.chartHeight;return{x:a?e.translate(b+c,null,null,d)+e.transB:e.left+e.offset+(e.opposite?(d&&f.oldChartWidth||f.chartWidth)-
e.right-e.left:0),y:a?g-e.bottom+e.offset-(e.opposite?e.height:0):g-e.translate(b+c,null,null,d)-e.transB}},getLabelPosition:function(a,b,c,d,e,f,g,h){var i=this.axis,j=i.transA,k=i.reversed,l=i.staggerLines,m=i.tickRotCorr||{x:0,y:0},c=p(e.y,m.y+(i.side===2?8:-(c.getBBox().height/2))),a=a+e.x+m.x-(f&&d?f*j*(k?-1:1):0),b=b+c-(f&&!d?f*j*(k?1:-1):0);l&&(b+=g/(h||1)%l*(i.labelOffset/l));return{x:a,y:r(b)}},getMarkPath:function(a,b,c,d,e,f){return f.crispLine(["M",a,b,"L",a+(e?0:-c),b+(e?c:0)],d)},render:function(a,
b,c){var d=this.axis,e=d.options,f=d.chart.renderer,g=d.horiz,h=this.type,i=this.label,j=this.pos,k=e.labels,l=this.gridLine,m=h?h+"Grid":"grid",n=h?h+"Tick":"tick",v=e[m+"LineWidth"],s=e[m+"LineColor"],o=e[m+"LineDashStyle"],N=e[n+"Length"],m=e[n+"Width"]||0,t=e[n+"Color"],w=e[n+"Position"],n=this.mark,ga=k.step,q=!0,u=d.tickmarkOffset,r=this.getPosition(g,j,u,b),x=r.x,r=r.y,z=g&&x===d.pos+d.len||!g&&r===d.pos?-1:1,c=p(c,1);this.isActive=!0;if(v){j=d.getPlotLinePath(j+u,v*z,b,!0);if(l===y){l={stroke:s,
"stroke-width":v};if(o)l.dashstyle=o;if(!h)l.zIndex=1;if(b)l.opacity=0;this.gridLine=l=v?f.path(j).attr(l).add(d.gridGroup):null}if(!b&&l&&j)l[this.isNew?"attr":"animate"]({d:j,opacity:c})}if(m&&N)w==="inside"&&(N=-N),d.opposite&&(N=-N),h=this.getMarkPath(x,r,N,m*z,g,f),n?n.animate({d:h,opacity:c}):this.mark=f.path(h).attr({stroke:t,"stroke-width":m,opacity:c}).add(d.axisGroup);if(i&&!isNaN(x))i.xy=r=this.getLabelPosition(x,r,i,g,k,u,a,ga),this.isFirst&&!this.isLast&&!p(e.showFirstLabel,1)||this.isLast&&
!this.isFirst&&!p(e.showLastLabel,1)?q=!1:g&&!d.isRadial&&!k.step&&!k.rotation&&!b&&c!==0&&this.handleOverflow(r),ga&&a%ga&&(q=!1),q&&!isNaN(r.y)?(r.opacity=c,i[this.isNew?"attr":"animate"](r),this.isNew=!1):i.attr("y",-9999)},destroy:function(){Qa(this,this.axis)}};A.PlotLineOrBand=function(a,b){this.axis=a;if(b)this.options=b,this.id=b.id};A.PlotLineOrBand.prototype={render:function(){var a=this,b=a.axis,c=b.horiz,d=a.options,e=d.label,f=a.label,g=d.width,h=d.to,i=d.from,j=q(i)&&q(h),k=d.value,
l=d.dashStyle,m=a.svgElem,n=[],v,s=d.color,p=d.zIndex,o=d.events,t={},w=b.chart.renderer;b.isLog&&(i=Ea(i),h=Ea(h),k=Ea(k));if(g){if(n=b.getPlotLinePath(k,g),t={stroke:s,"stroke-width":g},l)t.dashstyle=l}else if(j){n=b.getPlotBandPath(i,h,d);if(s)t.fill=s;if(d.borderWidth)t.stroke=d.borderColor,t["stroke-width"]=d.borderWidth}else return;if(q(p))t.zIndex=p;if(m)if(n)m.animate({d:n},null,m.onGetPath);else{if(m.hide(),m.onGetPath=function(){m.show()},f)a.label=f=f.destroy()}else if(n&&n.length&&(a.svgElem=
m=w.path(n).attr(t).add(),o))for(v in d=function(b){m.on(b,function(c){o[b].apply(a,[c])})},o)d(v);if(e&&q(e.text)&&n&&n.length&&b.width>0&&b.height>0){e=z({align:c&&j&&"center",x:c?!j&&4:10,verticalAlign:!c&&j&&"middle",y:c?j?16:10:j?6:-4,rotation:c&&!j&&90},e);if(!f){t={align:e.textAlign||e.align,rotation:e.rotation};if(q(p))t.zIndex=p;a.label=f=w.text(e.text,0,0,e.useHTML).attr(t).css(e.style).add()}b=[n[1],n[4],j?n[6]:n[1]];j=[n[2],n[5],j?n[7]:n[2]];n=Pa(b);c=Pa(j);f.align(e,!1,{x:n,y:c,width:Fa(b)-
n,height:Fa(j)-c});f.show()}else f&&f.hide();return a},destroy:function(){ja(this.axis.plotLinesAndBands,this);delete this.axis;Qa(this)}};var va=A.Axis=function(){this.init.apply(this,arguments)};va.prototype={defaultOptions:{dateTimeLabelFormats:{millisecond:"%H:%M:%S.%L",second:"%H:%M:%S",minute:"%H:%M",hour:"%H:%M",day:"%e. %b",week:"%e. %b",month:"%b '%y",year:"%Y"},endOnTick:!1,gridLineColor:"#D8D8D8",labels:{enabled:!0,style:{color:"#606060",cursor:"default",fontSize:"11px"},x:0,y:15},lineColor:"#C0D0E0",
lineWidth:1,minPadding:0.01,maxPadding:0.01,minorGridLineColor:"#E0E0E0",minorGridLineWidth:1,minorTickColor:"#A0A0A0",minorTickLength:2,minorTickPosition:"outside",startOfWeek:1,startOnTick:!1,tickColor:"#C0D0E0",tickLength:10,tickmarkPlacement:"between",tickPixelInterval:100,tickPosition:"outside",tickWidth:1,title:{align:"middle",style:{color:"#707070"}},type:"linear"},defaultYAxisOptions:{endOnTick:!0,gridLineWidth:1,tickPixelInterval:72,showLastLabel:!0,labels:{x:-8,y:3},lineWidth:0,maxPadding:0.05,
minPadding:0.05,startOnTick:!0,tickWidth:0,title:{rotation:270,text:"Values"},stackLabels:{enabled:!1,formatter:function(){return A.numberFormat(this.total,-1)},style:z(ba.line.dataLabels.style,{color:"#000000"})}},defaultLeftAxisOptions:{labels:{x:-15,y:null},title:{rotation:270}},defaultRightAxisOptions:{labels:{x:15,y:null},title:{rotation:90}},defaultBottomAxisOptions:{labels:{autoRotation:[-45],x:0,y:null},title:{rotation:0}},defaultTopAxisOptions:{labels:{autoRotation:[-45],x:0,y:-15},title:{rotation:0}},
init:function(a,b){var c=b.isX;this.horiz=a.inverted?!c:c;this.coll=(this.isXAxis=c)?"xAxis":"yAxis";this.opposite=b.opposite;this.side=b.side||(this.horiz?this.opposite?0:2:this.opposite?1:3);this.setOptions(b);var d=this.options,e=d.type;this.labelFormatter=d.labels.formatter||this.defaultLabelFormatter;this.userOptions=b;this.minPixelPadding=0;this.chart=a;this.reversed=d.reversed;this.zoomEnabled=d.zoomEnabled!==!1;this.categories=d.categories||e==="category";this.names=this.names||[];this.isLog=
e==="logarithmic";this.isDatetimeAxis=e==="datetime";this.isLinked=q(d.linkedTo);this.ticks={};this.labelEdge=[];this.minorTicks={};this.plotLinesAndBands=[];this.alternateBands={};this.len=0;this.minRange=this.userMinRange=d.minRange||d.maxZoom;this.range=d.range;this.offset=d.offset||0;this.stacks={};this.oldStacks={};this.min=this.max=null;this.crosshair=p(d.crosshair,sa(a.options.tooltip.crosshairs)[c?0:1],!1);var f,d=this.options.events;Ma(this,a.axes)===-1&&(c&&!this.isColorAxis?a.axes.splice(a.xAxis.length,
0,this):a.axes.push(this),a[this.coll].push(this));this.series=this.series||[];if(a.inverted&&c&&this.reversed===y)this.reversed=!0;this.removePlotLine=this.removePlotBand=this.removePlotBandOrLine;for(f in d)H(this,f,d[f]);if(this.isLog)this.val2lin=Ea,this.lin2val=ia},setOptions:function(a){this.options=z(this.defaultOptions,this.isXAxis?{}:this.defaultYAxisOptions,[this.defaultTopAxisOptions,this.defaultRightAxisOptions,this.defaultBottomAxisOptions,this.defaultLeftAxisOptions][this.side],z(T[this.coll],
a))},defaultLabelFormatter:function(){var a=this.axis,b=this.value,c=a.categories,d=this.dateTimeLabelFormat,e=T.lang.numericSymbols,f=e&&e.length,g,h=a.options.labels.format,a=a.isLog?b:a.tickInterval;if(h)g=Ja(h,this);else if(c)g=b;else if(d)g=Oa(d,b);else if(f&&a>=1E3)for(;f--&&g===y;)c=Math.pow(1E3,f+1),a>=c&&b*10%c===0&&e[f]!==null&&(g=A.numberFormat(b/c,-1)+e[f]);g===y&&(g=O(b)>=1E4?A.numberFormat(b,-1):A.numberFormat(b,-1,y,""));return g},getSeriesExtremes:function(){var a=this,b=a.chart;a.hasVisibleSeries=
!1;a.dataMin=a.dataMax=a.ignoreMinPadding=a.ignoreMaxPadding=null;a.buildStacks&&a.buildStacks();o(a.series,function(c){if(c.visible||!b.options.chart.ignoreHiddenSeries){var d;d=c.options.threshold;var e;a.hasVisibleSeries=!0;a.isLog&&d<=0&&(d=null);if(a.isXAxis){if(d=c.xData,d.length)a.dataMin=C(p(a.dataMin,d[0]),Pa(d)),a.dataMax=u(p(a.dataMax,d[0]),Fa(d))}else{c.getExtremes();e=c.dataMax;c=c.dataMin;if(q(c)&&q(e))a.dataMin=C(p(a.dataMin,c),c),a.dataMax=u(p(a.dataMax,e),e);if(q(d))if(a.dataMin>=
d)a.dataMin=d,a.ignoreMinPadding=!0;else if(a.dataMax<d)a.dataMax=d,a.ignoreMaxPadding=!0}}})},translate:function(a,b,c,d,e,f){var g=this.linkedParent||this,h=1,i=0,j=d?g.oldTransA:g.transA,d=d?g.oldMin:g.min,k=g.minPixelPadding,e=(g.doPostTranslate||g.isLog&&e)&&g.lin2val;if(!j)j=g.transA;if(c)h*=-1,i=g.len;g.reversed&&(h*=-1,i-=h*(g.sector||g.len));b?(a=a*h+i,a-=k,a=a/j+d,e&&(a=g.lin2val(a))):(e&&(a=g.val2lin(a)),f==="between"&&(f=0.5),a=h*(a-d)*j+i+h*k+(ra(f)?j*f*g.pointRange:0));return a},toPixels:function(a,
b){return this.translate(a,!1,!this.horiz,null,!0)+(b?0:this.pos)},toValue:function(a,b){return this.translate(a-(b?0:this.pos),!0,!this.horiz,null,!0)},getPlotLinePath:function(a,b,c,d,e){var f=this.chart,g=this.left,h=this.top,i,j,k=c&&f.oldChartHeight||f.chartHeight,l=c&&f.oldChartWidth||f.chartWidth,m;i=this.transB;var n=function(a,b,c){if(a<b||a>c)d?a=C(u(b,a),c):m=!0;return a},e=p(e,this.translate(a,null,null,c)),a=c=r(e+i);i=j=r(k-e-i);isNaN(e)?m=!0:this.horiz?(i=h,j=k-this.bottom,a=c=n(a,
g,g+this.width)):(a=g,c=l-this.right,i=j=n(i,h,h+this.height));return m&&!d?null:f.renderer.crispLine(["M",a,i,"L",c,j],b||1)},getLinearTickPositions:function(a,b,c){var d,e=ea(V(b/a)*a),f=ea(ta(c/a)*a),g=[];if(b===c&&ra(b))return[b];for(b=e;b<=f;){g.push(b);b=ea(b+a);if(b===d)break;d=b}return g},getMinorTickPositions:function(){var a=this.options,b=this.tickPositions,c=this.minorTickInterval,d=[],e,f=this.min;e=this.max;var g=e-f;if(g&&g/c<this.len/3)if(this.isLog){a=b.length;for(e=1;e<a;e++)d=d.concat(this.getLogTickPositions(c,
b[e-1],b[e],!0))}else if(this.isDatetimeAxis&&a.minorTickInterval==="auto")d=d.concat(this.getTimeTicks(this.normalizeTimeTickInterval(c),f,e,a.startOfWeek));else for(b=f+(b[0]-f)%c;b<=e;b+=c)d.push(b);this.trimTicks(d);return d},adjustForMinRange:function(){var a=this.options,b=this.min,c=this.max,d,e=this.dataMax-this.dataMin>=this.minRange,f,g,h,i,j;if(this.isXAxis&&this.minRange===y&&!this.isLog)q(a.min)||q(a.max)?this.minRange=null:(o(this.series,function(a){i=a.xData;for(g=j=a.xIncrement?1:
i.length-1;g>0;g--)if(h=i[g]-i[g-1],f===y||h<f)f=h}),this.minRange=C(f*5,this.dataMax-this.dataMin));if(c-b<this.minRange){var k=this.minRange;d=(k-c+b)/2;d=[b-d,p(a.min,b-d)];if(e)d[2]=this.dataMin;b=Fa(d);c=[b+k,p(a.max,b+k)];if(e)c[2]=this.dataMax;c=Pa(c);c-b<k&&(d[0]=c-k,d[1]=p(a.min,c-k),b=Fa(d))}this.min=b;this.max=c},setAxisTranslation:function(a){var b=this,c=b.max-b.min,d=b.axisPointRange||0,e,f=0,g=0,h=b.linkedParent,i=!!b.categories,j=b.transA,k=b.isXAxis;if(k||i||d)if(h?(f=h.minPointOffset,
g=h.pointRangePadding):o(b.series,function(a){var h=i?1:k?a.pointRange:b.axisPointRange||0,j=a.options.pointPlacement,v=a.closestPointRange;h>c&&(h=0);d=u(d,h);b.single||(f=u(f,Da(j)?0:h/2),g=u(g,j==="on"?0:h));!a.noSharedTooltip&&q(v)&&(e=q(e)?C(e,v):v)}),h=b.ordinalSlope&&e?b.ordinalSlope/e:1,b.minPointOffset=f*=h,b.pointRangePadding=g*=h,b.pointRange=C(d,c),k)b.closestPointRange=e;if(a)b.oldTransA=j;b.translationSlope=b.transA=j=b.len/(c+g||1);b.transB=b.horiz?b.left:b.bottom;b.minPixelPadding=
j*f},setTickInterval:function(a){var b=this,c=b.chart,d=b.options,e=b.isLog,f=b.isDatetimeAxis,g=b.isXAxis,h=b.isLinked,i=d.maxPadding,j=d.minPadding,k=d.tickInterval,l=d.tickPixelInterval,m=b.categories;!f&&!m&&!h&&this.getTickAmount();h?(b.linkedParent=c[b.coll][d.linkedTo],c=b.linkedParent.getExtremes(),b.min=p(c.min,c.dataMin),b.max=p(c.max,c.dataMax),d.type!==b.linkedParent.options.type&&la(11,1)):(b.min=p(b.userMin,d.min,b.dataMin),b.max=p(b.userMax,d.max,b.dataMax));if(e)!a&&C(b.min,p(b.dataMin,
b.min))<=0&&la(10,1),b.min=ea(Ea(b.min)),b.max=ea(Ea(b.max));if(b.range&&q(b.max))b.userMin=b.min=u(b.min,b.max-b.range),b.userMax=b.max,b.range=null;b.beforePadding&&b.beforePadding();b.adjustForMinRange();if(!m&&!b.axisPointRange&&!b.usePercentage&&!h&&q(b.min)&&q(b.max)&&(c=b.max-b.min)){if(!q(d.min)&&!q(b.userMin)&&j&&(b.dataMin<0||!b.ignoreMinPadding))b.min-=c*j;if(!q(d.max)&&!q(b.userMax)&&i&&(b.dataMax>0||!b.ignoreMaxPadding))b.max+=c*i}if(ra(d.floor))b.min=u(b.min,d.floor);if(ra(d.ceiling))b.max=
C(b.max,d.ceiling);b.tickInterval=b.min===b.max||b.min===void 0||b.max===void 0?1:h&&!k&&l===b.linkedParent.options.tickPixelInterval?k=b.linkedParent.tickInterval:p(k,this.tickAmount?(b.max-b.min)/u(this.tickAmount-1,1):void 0,m?1:(b.max-b.min)*l/u(b.len,l));g&&!a&&o(b.series,function(a){a.processData(b.min!==b.oldMin||b.max!==b.oldMax)});b.setAxisTranslation(!0);b.beforeSetTickPositions&&b.beforeSetTickPositions();if(b.postProcessTickInterval)b.tickInterval=b.postProcessTickInterval(b.tickInterval);
if(b.pointRange)b.tickInterval=u(b.pointRange,b.tickInterval);a=p(d.minTickInterval,b.isDatetimeAxis&&b.closestPointRange);if(!k&&b.tickInterval<a)b.tickInterval=a;if(!f&&!e&&!k)b.tickInterval=qb(b.tickInterval,null,pb(b.tickInterval),p(d.allowDecimals,!(b.tickInterval>0.5&&b.tickInterval<5&&b.max>1E3&&b.max<9999)),!!this.tickAmount);if(!this.tickAmount&&this.len)b.tickInterval=b.unsquish();this.setTickPositions()},setTickPositions:function(){var a=this.options,b,c=a.tickPositions,d=a.tickPositioner,
e=a.startOnTick,f=a.endOnTick,g;this.tickmarkOffset=this.categories&&a.tickmarkPlacement==="between"&&this.tickInterval===1?0.5:0;this.minorTickInterval=a.minorTickInterval==="auto"&&this.tickInterval?this.tickInterval/5:a.minorTickInterval;this.tickPositions=b=c&&c.slice();if(!b&&(this.tickPositions=b=this.isDatetimeAxis?this.getTimeTicks(this.normalizeTimeTickInterval(this.tickInterval,a.units),this.min,this.max,a.startOfWeek,this.ordinalPositions,this.closestPointRange,!0):this.isLog?this.getLogTickPositions(this.tickInterval,
this.min,this.max):this.getLinearTickPositions(this.tickInterval,this.min,this.max),d&&(d=d.apply(this,[this.min,this.max]))))this.tickPositions=b=d;if(!this.isLinked)this.trimTicks(b,e,f),this.min===this.max&&q(this.min)&&!this.tickAmount&&(g=!0,this.min-=0.5,this.max+=0.5),this.single=g,!c&&!d&&this.adjustTickAmount()},trimTicks:function(a,b,c){var d=a[0],e=a[a.length-1],f=this.minPointOffset||0;b?this.min=d:this.min-f>d&&a.shift();c?this.max=e:this.max+f<e&&a.pop();a.length===0&&q(d)&&a.push((e+
d)/2)},getTickAmount:function(){var a={},b,c=this.options,d=c.tickAmount,e=c.tickPixelInterval;!q(c.tickInterval)&&this.len<e&&!this.isRadial&&!this.isLog&&c.startOnTick&&c.endOnTick&&(d=2);!d&&this.chart.options.chart.alignTicks!==!1&&c.alignTicks!==!1&&(o(this.chart[this.coll],function(c){var d=c.options,e=c.horiz,d=[e?d.left:d.top,e?d.width:d.height,d.pane].join(",");a[d]?c.series.length&&(b=!0):a[d]=1}),b&&(d=ta(this.len/e)+1));if(d<4)this.finalTickAmt=d,d=5;this.tickAmount=d},adjustTickAmount:function(){var a=
this.tickInterval,b=this.tickPositions,c=this.tickAmount,d=this.finalTickAmt,e=b&&b.length;if(e<c){for(;b.length<c;)b.push(ea(b[b.length-1]+a));this.transA*=(e-1)/(c-1);this.max=b[b.length-1]}else e>c&&(this.tickInterval*=2,this.setTickPositions());if(q(d)){for(a=c=b.length;a--;)(d===3&&a%2===1||d<=2&&a>0&&a<c-1)&&b.splice(a,1);this.finalTickAmt=y}},setScale:function(){var a=this.stacks,b,c,d,e;this.oldMin=this.min;this.oldMax=this.max;this.oldAxisLength=this.len;this.setAxisSize();e=this.len!==this.oldAxisLength;
o(this.series,function(a){if(a.isDirtyData||a.isDirty||a.xAxis.isDirty)d=!0});if(e||d||this.isLinked||this.forceRedraw||this.userMin!==this.oldUserMin||this.userMax!==this.oldUserMax){if(!this.isXAxis)for(b in a)for(c in a[b])a[b][c].total=null,a[b][c].cum=0;this.forceRedraw=!1;this.getSeriesExtremes();this.setTickInterval();this.oldUserMin=this.userMin;this.oldUserMax=this.userMax;if(!this.isDirty)this.isDirty=e||this.min!==this.oldMin||this.max!==this.oldMax}else if(!this.isXAxis){if(this.oldStacks)a=
this.stacks=this.oldStacks;for(b in a)for(c in a[b])a[b][c].cum=a[b][c].total}},setExtremes:function(a,b,c,d,e){var f=this,g=f.chart,c=p(c,!0);o(f.series,function(a){delete a.kdTree});e=x(e,{min:a,max:b});I(f,"setExtremes",e,function(){f.userMin=a;f.userMax=b;f.eventArgs=e;f.isDirtyExtremes=!0;c&&g.redraw(d)})},zoom:function(a,b){var c=this.dataMin,d=this.dataMax,e=this.options;this.allowZoomOutside||(q(c)&&a<=C(c,p(e.min,c))&&(a=y),q(d)&&b>=u(d,p(e.max,d))&&(b=y));this.displayBtn=a!==y||b!==y;this.setExtremes(a,
b,!1,y,{trigger:"zoom"});return!0},setAxisSize:function(){var a=this.chart,b=this.options,c=b.offsetLeft||0,d=this.horiz,e=p(b.width,a.plotWidth-c+(b.offsetRight||0)),f=p(b.height,a.plotHeight),g=p(b.top,a.plotTop),b=p(b.left,a.plotLeft+c),c=/%$/;c.test(f)&&(f=parseFloat(f)/100*a.plotHeight);c.test(g)&&(g=parseFloat(g)/100*a.plotHeight+a.plotTop);this.left=b;this.top=g;this.width=e;this.height=f;this.bottom=a.chartHeight-f-g;this.right=a.chartWidth-e-b;this.len=u(d?e:f,0);this.pos=d?b:g},getExtremes:function(){var a=
this.isLog;return{min:a?ea(ia(this.min)):this.min,max:a?ea(ia(this.max)):this.max,dataMin:this.dataMin,dataMax:this.dataMax,userMin:this.userMin,userMax:this.userMax}},getThreshold:function(a){var b=this.isLog,c=b?ia(this.min):this.min,b=b?ia(this.max):this.max;a===null?a=b<0?b:c:c>a?a=c:b<a&&(a=b);return this.translate(a,0,1,0,1)},autoLabelAlign:function(a){a=(p(a,0)-this.side*90+720)%360;return a>15&&a<165?"right":a>195&&a<345?"left":"center"},unsquish:function(){var a=this.ticks,b=this.options.labels,
c=this.horiz,d=this.tickInterval,e=d,f=this.len/(((this.categories?1:0)+this.max-this.min)/d),g,h=b.rotation,i=this.chart.renderer.fontMetrics(b.style.fontSize,a[0]&&a[0].label),j,k=Number.MAX_VALUE,l,m=function(a){a/=f||1;a=a>1?ta(a):1;return a*d};c?(l=q(h)?[h]:f<p(b.autoRotationLimit,80)&&!b.staggerLines&&!b.step&&b.autoRotation)&&o(l,function(a){var b;if(a===h||a&&a>=-90&&a<=90)j=m(O(i.h/aa(ha*a))),b=j+O(a/360),b<k&&(k=b,g=a,e=j)}):e=m(i.h);this.autoRotation=l;this.labelRotation=g;return e},renderUnsquish:function(){var a=
this.chart,b=a.renderer,c=this.tickPositions,d=this.ticks,e=this.options.labels,f=this.horiz,g=a.margin,h=this.categories?c.length:c.length-1,i=this.slotWidth=f&&!e.step&&!e.rotation&&(this.staggerLines||1)*a.plotWidth/h||!f&&(g[3]&&g[3]-a.spacing[3]||a.chartWidth*0.33),j=u(1,r(i-2*(e.padding||5))),k={},g=b.fontMetrics(e.style.fontSize,d[0]&&d[0].label),h=e.style.textOverflow,l,m=0;if(!Da(e.rotation))k.rotation=e.rotation;if(this.autoRotation)o(c,function(a){if((a=d[a])&&a.labelLength>m)m=a.labelLength}),
m>j&&m>g.h?k.rotation=this.labelRotation:this.labelRotation=0;else if(i&&(l={width:j+"px"},!h)){l.textOverflow="clip";for(i=c.length;!f&&i--;)if(j=c[i],j=d[j].label)if(j.styles.textOverflow==="ellipsis"&&j.css({textOverflow:"clip"}),j.getBBox().height>this.len/c.length-(g.h-g.f))j.specCss={textOverflow:"ellipsis"}}if(k.rotation&&(l={width:(m>a.chartHeight*0.5?a.chartHeight*0.33:a.chartHeight)+"px"},!h))l.textOverflow="ellipsis";this.labelAlign=k.align=e.align||this.autoLabelAlign(this.labelRotation);
o(c,function(a){var b=(a=d[a])&&a.label;if(b)l&&b.css(z(l,b.specCss)),delete b.specCss,b.attr(k),a.rotation=k.rotation});this.tickRotCorr=b.rotCorr(g.b,this.labelRotation||0,this.side===2)},hasData:function(){return this.hasVisibleSeries||q(this.min)&&q(this.max)&&!!this.tickPositions},getOffset:function(){var a=this,b=a.chart,c=b.renderer,d=a.options,e=a.tickPositions,f=a.ticks,g=a.horiz,h=a.side,i=b.inverted?[1,0,3,2][h]:h,j,k,l=0,m,n=0,v=d.title,s=d.labels,S=0,N=b.axisOffset,b=b.clipOffset,t=[-1,
1,1,-1][h],w;j=a.hasData();a.showAxis=k=j||p(d.showEmpty,!0);a.staggerLines=a.horiz&&s.staggerLines;if(!a.axisGroup)a.gridGroup=c.g("grid").attr({zIndex:d.gridZIndex||1}).add(),a.axisGroup=c.g("axis").attr({zIndex:d.zIndex||2}).add(),a.labelGroup=c.g("axis-labels").attr({zIndex:s.zIndex||7}).addClass("highcharts-"+a.coll.toLowerCase()+"-labels").add();if(j||a.isLinked){if(o(e,function(b){f[b]?f[b].addLabel():f[b]=new Ta(a,b)}),a.renderUnsquish(),o(e,function(b){if(h===0||h===2||{1:"left",3:"right"}[h]===
a.labelAlign)S=u(f[b].getLabelSize(),S)}),a.staggerLines)S*=a.staggerLines,a.labelOffset=S}else for(w in f)f[w].destroy(),delete f[w];if(v&&v.text&&v.enabled!==!1){if(!a.axisTitle)a.axisTitle=c.text(v.text,0,0,v.useHTML).attr({zIndex:7,rotation:v.rotation||0,align:v.textAlign||{low:"left",middle:"center",high:"right"}[v.align]}).addClass("highcharts-"+this.coll.toLowerCase()+"-title").css(v.style).add(a.axisGroup),a.axisTitle.isNew=!0;if(k)l=a.axisTitle.getBBox()[g?"height":"width"],m=v.offset,n=
q(m)?0:p(v.margin,g?5:10);a.axisTitle[k?"show":"hide"]()}a.offset=t*p(d.offset,N[h]);a.tickRotCorr=a.tickRotCorr||{x:0,y:0};c=h===2?a.tickRotCorr.y:0;g=S+n+(S&&t*(g?p(s.y,a.tickRotCorr.y+8):s.x)-c);a.axisTitleMargin=p(m,g);N[h]=u(N[h],a.axisTitleMargin+l+t*a.offset,g);l=V(d.lineWidth/2)*2;d.offset&&(l=u(0,l-d.offset));b[i]=u(b[i],l)},getLinePath:function(a){var b=this.chart,c=this.opposite,d=this.offset,e=this.horiz,f=this.left+(c?this.width:0)+d,d=b.chartHeight-this.bottom-(c?this.height:0)+d;c&&
(a*=-1);return b.renderer.crispLine(["M",e?this.left:f,e?d:this.top,"L",e?b.chartWidth-this.right:f,e?d:b.chartHeight-this.bottom],a)},getTitlePosition:function(){var a=this.horiz,b=this.left,c=this.top,d=this.len,e=this.options.title,f=a?b:c,g=this.opposite,h=this.offset,i=e.x||0,j=e.y||0,k=D(e.style.fontSize||12),d={low:f+(a?0:d),middle:f+d/2,high:f+(a?d:0)}[e.align],b=(a?c+this.height:b)+(a?1:-1)*(g?-1:1)*this.axisTitleMargin+(this.side===2?k:0);return{x:a?d+i:b+(g?this.width:0)+h+i,y:a?b+j-(g?
this.height:0)+h:d+j}},render:function(){var a=this,b=a.chart,c=b.renderer,d=a.options,e=a.isLog,f=a.isLinked,g=a.tickPositions,h=a.axisTitle,i=a.ticks,j=a.minorTicks,k=a.alternateBands,l=d.stackLabels,m=d.alternateGridColor,n=a.tickmarkOffset,v=d.lineWidth,s,p=b.hasRendered&&q(a.oldMin)&&!isNaN(a.oldMin),N=a.showAxis,t,w;a.labelEdge.length=0;a.overlap=!1;o([i,j,k],function(a){for(var b in a)a[b].isActive=!1});if(a.hasData()||f){a.minorTickInterval&&!a.categories&&o(a.getMinorTickPositions(),function(b){j[b]||
(j[b]=new Ta(a,b,"minor"));p&&j[b].isNew&&j[b].render(null,!0);j[b].render(null,!1,1)});if(g.length&&(o(g,function(b,c){if(!f||b>=a.min&&b<=a.max)i[b]||(i[b]=new Ta(a,b)),p&&i[b].isNew&&i[b].render(c,!0,0.1),i[b].render(c)}),n&&(a.min===0||a.single)))i[-1]||(i[-1]=new Ta(a,-1,null,!0)),i[-1].render(-1);m&&o(g,function(b,c){if(c%2===0&&b<a.max)k[b]||(k[b]=new A.PlotLineOrBand(a)),t=b+n,w=g[c+1]!==y?g[c+1]+n:a.max,k[b].options={from:e?ia(t):t,to:e?ia(w):w,color:m},k[b].render(),k[b].isActive=!0});if(!a._addedPlotLB)o((d.plotLines||
[]).concat(d.plotBands||[]),function(b){a.addPlotBandOrLine(b)}),a._addedPlotLB=!0}o([i,j,k],function(a){var c,d,e=[],f=za?za.duration||500:0,g=function(){for(d=e.length;d--;)a[e[d]]&&!a[e[d]].isActive&&(a[e[d]].destroy(),delete a[e[d]])};for(c in a)if(!a[c].isActive)a[c].render(c,!1,0),a[c].isActive=!1,e.push(c);a===k||!b.hasRendered||!f?g():f&&setTimeout(g,f)});if(v)s=a.getLinePath(v),a.axisLine?a.axisLine.animate({d:s}):a.axisLine=c.path(s).attr({stroke:d.lineColor,"stroke-width":v,zIndex:7}).add(a.axisGroup),
a.axisLine[N?"show":"hide"]();if(h&&N)h[h.isNew?"attr":"animate"](a.getTitlePosition()),h.isNew=!1;l&&l.enabled&&a.renderStackTotals();a.isDirty=!1},redraw:function(){this.render();o(this.plotLinesAndBands,function(a){a.render()});o(this.series,function(a){a.isDirty=!0})},destroy:function(a){var b=this,c=b.stacks,d,e=b.plotLinesAndBands;a||Z(b);for(d in c)Qa(c[d]),c[d]=null;o([b.ticks,b.minorTicks,b.alternateBands],function(a){Qa(a)});for(a=e.length;a--;)e[a].destroy();o("stackTotalGroup,axisLine,axisTitle,axisGroup,cross,gridGroup,labelGroup".split(","),
function(a){b[a]&&(b[a]=b[a].destroy())});this.cross&&this.cross.destroy()},drawCrosshair:function(a,b){var c,d=this.crosshair,e=d.animation;if(!this.crosshair||(q(b)||!p(this.crosshair.snap,!0))===!1||b&&b.series&&b.series[this.coll]!==this)this.hideCrosshair();else if(p(d.snap,!0)?q(b)&&(c=this.isXAxis?b.plotX:this.len-b.plotY):c=this.horiz?a.chartX-this.pos:this.len-a.chartY+this.pos,c=this.isRadial?this.getPlotLinePath(this.isXAxis?b.x:p(b.stackY,b.y))||null:this.getPlotLinePath(null,null,null,
null,c)||null,c===null)this.hideCrosshair();else if(this.cross)this.cross.attr({visibility:"visible"})[e?"animate":"attr"]({d:c},e);else{e=this.categories&&!this.isRadial;e={"stroke-width":d.width||(e?this.transA:1),stroke:d.color||(e?"rgba(155,200,255,0.2)":"#C0C0C0"),zIndex:d.zIndex||2};if(d.dashStyle)e.dashstyle=d.dashStyle;this.cross=this.chart.renderer.path(c).attr(e).add()}},hideCrosshair:function(){this.cross&&this.cross.hide()}};x(va.prototype,{getPlotBandPath:function(a,b){var c=this.getPlotLinePath(b,
null,null,!0),d=this.getPlotLinePath(a,null,null,!0);d&&c&&d.toString()!==c.toString()?d.push(c[4],c[5],c[1],c[2]):d=null;return d},addPlotBand:function(a){return this.addPlotBandOrLine(a,"plotBands")},addPlotLine:function(a){return this.addPlotBandOrLine(a,"plotLines")},addPlotBandOrLine:function(a,b){var c=(new A.PlotLineOrBand(this,a)).render(),d=this.userOptions;c&&(b&&(d[b]=d[b]||[],d[b].push(a)),this.plotLinesAndBands.push(c));return c},removePlotBandOrLine:function(a){for(var b=this.plotLinesAndBands,
c=this.options,d=this.userOptions,e=b.length;e--;)b[e].id===a&&b[e].destroy();o([c.plotLines||[],d.plotLines||[],c.plotBands||[],d.plotBands||[]],function(b){for(e=b.length;e--;)b[e].id===a&&ja(b,b[e])})}});va.prototype.getTimeTicks=function(a,b,c,d){var e=[],f={},g=T.global.useUTC,h,i=new Aa(b-Wa(b)),j=a.unitRange,k=a.count;if(q(b)){i[Eb](j>=E.second?0:k*V(i.getMilliseconds()/k));if(j>=E.second)i[Fb](j>=E.minute?0:k*V(i.getSeconds()/k));if(j>=E.minute)i[Gb](j>=E.hour?0:k*V(i[sb]()/k));if(j>=E.hour)i[Hb](j>=
E.day?0:k*V(i[tb]()/k));if(j>=E.day)i[vb](j>=E.month?1:k*V(i[Xa]()/k));j>=E.month&&(i[wb](j>=E.year?0:k*V(i[Ya]()/k)),h=i[Za]());j>=E.year&&(h-=h%k,i[xb](h));if(j===E.week)i[vb](i[Xa]()-i[ub]()+p(d,1));b=1;if(ob||eb)i=i.getTime(),i=new Aa(i+Wa(i));h=i[Za]();for(var d=i.getTime(),l=i[Ya](),m=i[Xa](),n=(E.day+(g?Wa(i):i.getTimezoneOffset()*6E4))%E.day;d<c;)e.push(d),j===E.year?d=gb(h+b*k,0):j===E.month?d=gb(h,l+b*k):!g&&(j===E.day||j===E.week)?d=gb(h,l,m+b*k*(j===E.day?1:7)):d+=j*k,b++;e.push(d);o(lb(e,
function(a){return j<=E.hour&&a%E.day===n}),function(a){f[a]="day"})}e.info=x(a,{higherRanks:f,totalRange:j*k});return e};va.prototype.normalizeTimeTickInterval=function(a,b){var c=b||[["millisecond",[1,2,5,10,20,25,50,100,200,500]],["second",[1,2,5,10,15,30]],["minute",[1,2,5,10,15,30]],["hour",[1,2,3,4,6,8,12]],["day",[1,2]],["week",[1,2]],["month",[1,2,3,4,6]],["year",null]],d=c[c.length-1],e=E[d[0]],f=d[1],g;for(g=0;g<c.length;g++)if(d=c[g],e=E[d[0]],f=d[1],c[g+1]&&a<=(e*f[f.length-1]+E[c[g+1][0]])/
2)break;e===E.year&&a<5*e&&(f=[1,2,5]);c=qb(a/e,f,d[0]==="year"?u(pb(a/e),1):1);return{unitRange:e,count:c,unitName:d[0]}};va.prototype.getLogTickPositions=function(a,b,c,d){var e=this.options,f=this.len,g=[];if(!d)this._minorAutoInterval=null;if(a>=0.5)a=r(a),g=this.getLinearTickPositions(a,b,c);else if(a>=0.08)for(var f=V(b),h,i,j,k,l,e=a>0.3?[1,2,4]:a>0.15?[1,2,4,6,8]:[1,2,3,4,5,6,7,8,9];f<c+1&&!l;f++){i=e.length;for(h=0;h<i&&!l;h++)j=Ea(ia(f)*e[h]),j>b&&(!d||k<=c)&&k!==y&&g.push(k),k>c&&(l=!0),
k=j}else if(b=ia(b),c=ia(c),a=e[d?"minorTickInterval":"tickInterval"],a=p(a==="auto"?null:a,this._minorAutoInterval,(c-b)*(e.tickPixelInterval/(d?5:1))/((d?f/this.tickPositions.length:f)||1)),a=qb(a,null,pb(a)),g=Ua(this.getLinearTickPositions(a,b,c),Ea),!d)this._minorAutoInterval=a/5;if(!d)this.tickInterval=a;return g};var Nb=A.Tooltip=function(){this.init.apply(this,arguments)};Nb.prototype={init:function(a,b){var c=b.borderWidth,d=b.style,e=D(d.padding);this.chart=a;this.options=b;this.crosshairs=
[];this.now={x:0,y:0};this.isHidden=!0;this.label=a.renderer.label("",0,0,b.shape||"callout",null,null,b.useHTML,null,"tooltip").attr({padding:e,fill:b.backgroundColor,"stroke-width":c,r:b.borderRadius,zIndex:8}).css(d).css({padding:0}).add().attr({y:-9999});fa||this.label.shadow(b.shadow);this.shared=b.shared},destroy:function(){if(this.label)this.label=this.label.destroy();clearTimeout(this.hideTimer);clearTimeout(this.tooltipTimeout)},move:function(a,b,c,d){var e=this,f=e.now,g=e.options.animation!==
!1&&!e.isHidden&&(O(a-f.x)>1||O(b-f.y)>1),h=e.followPointer||e.len>1;x(f,{x:g?(2*f.x+a)/3:a,y:g?(f.y+b)/2:b,anchorX:h?y:g?(2*f.anchorX+c)/3:c,anchorY:h?y:g?(f.anchorY+d)/2:d});e.label.attr(f);if(g)clearTimeout(this.tooltipTimeout),this.tooltipTimeout=setTimeout(function(){e&&e.move(a,b,c,d)},32)},hide:function(a){var b=this;clearTimeout(this.hideTimer);if(!this.isHidden)this.hideTimer=setTimeout(function(){b.label.fadeOut();b.isHidden=!0},p(a,this.options.hideDelay,500))},getAnchor:function(a,b){var c,
d=this.chart,e=d.inverted,f=d.plotTop,g=d.plotLeft,h=0,i=0,j,k,a=sa(a);c=a[0].tooltipPos;this.followPointer&&b&&(b.chartX===y&&(b=d.pointer.normalize(b)),c=[b.chartX-d.plotLeft,b.chartY-f]);c||(o(a,function(a){j=a.series.yAxis;k=a.series.xAxis;h+=a.plotX+(!e&&k?k.left-g:0);i+=(a.plotLow?(a.plotLow+a.plotHigh)/2:a.plotY)+(!e&&j?j.top-f:0)}),h/=a.length,i/=a.length,c=[e?d.plotWidth-i:h,this.shared&&!e&&a.length>1&&b?b.chartY-f:e?d.plotHeight-h:i]);return Ua(c,r)},getPosition:function(a,b,c){var d=this.chart,
e=this.distance,f={},g=c.h||0,h,i=["y",d.chartHeight,b,c.plotY+d.plotTop],j=["x",d.chartWidth,a,c.plotX+d.plotLeft],k=p(c.ttBelow,d.inverted&&!c.negative||!d.inverted&&c.negative),l=function(a,b,c,d){var h=c<d-e,i=d+e+c<b,j=d-e-c;d+=e;if(k&&i)f[a]=d;else if(!k&&h)f[a]=j;else if(h)f[a]=j-g<0?j:j-g;else if(i)f[a]=d+g+c>b?d:d+g;else return!1},m=function(a,b,c,d){if(d<e||d>b-e)return!1;else f[a]=d<c/2?1:d>b-c/2?b-c-2:d-c/2},n=function(a){var b=i;i=j;j=b;h=a},v=function(){l.apply(0,i)!==!1?m.apply(0,j)===
!1&&!h&&(n(!0),v()):h?f.x=f.y=0:(n(!0),v())};(d.inverted||this.len>1)&&n();v();return f},defaultFormatter:function(a){var b=this.points||sa(this),c;c=[a.tooltipFooterHeaderFormatter(b[0])];c=c.concat(a.bodyFormatter(b));c.push(a.tooltipFooterHeaderFormatter(b[0],!0));return c.join("")},refresh:function(a,b){var c=this.chart,d=this.label,e=this.options,f,g,h,i={},j,k=[];j=e.formatter||this.defaultFormatter;var i=c.hoverPoints,l,m=this.shared;clearTimeout(this.hideTimer);this.followPointer=sa(a)[0].series.tooltipOptions.followPointer;
h=this.getAnchor(a,b);f=h[0];g=h[1];m&&(!a.series||!a.series.noSharedTooltip)?(c.hoverPoints=a,i&&o(i,function(a){a.setState()}),o(a,function(a){a.setState("hover");k.push(a.getLabelConfig())}),i={x:a[0].category,y:a[0].y},i.points=k,this.len=k.length,a=a[0]):i=a.getLabelConfig();j=j.call(i,this);i=a.series;this.distance=p(i.tooltipOptions.distance,16);j===!1?this.hide():(this.isHidden&&(db(d),d.attr("opacity",1).show()),d.attr({text:j}),l=e.borderColor||a.color||i.color||"#606060",d.attr({stroke:l}),
this.updatePosition({plotX:f,plotY:g,negative:a.negative,ttBelow:a.ttBelow,h:h[2]||0}),this.isHidden=!1);I(c,"tooltipRefresh",{text:j,x:f+c.plotLeft,y:g+c.plotTop,borderColor:l})},updatePosition:function(a){var b=this.chart,c=this.label,c=(this.options.positioner||this.getPosition).call(this,c.width,c.height,a);this.move(r(c.x),r(c.y||0),a.plotX+b.plotLeft,a.plotY+b.plotTop)},getXDateFormat:function(a,b,c){var d,b=b.dateTimeLabelFormats,e=c&&c.closestPointRange,f,g={millisecond:15,second:12,minute:9,
hour:6,day:3},h,i="millisecond";if(e){h=Oa("%m-%d %H:%M:%S.%L",a.x);for(f in E){if(e===E.week&&+Oa("%w",a.x)===c.options.startOfWeek&&h.substr(6)==="00:00:00.000"){f="week";break}else if(E[f]>e){f=i;break}else if(g[f]&&h.substr(g[f])!=="01-01 00:00:00.000".substr(g[f]))break;f!=="week"&&(i=f)}f&&(d=b[f])}else d=b.day;return d||b.year},tooltipFooterHeaderFormatter:function(a,b){var c=b?"footer":"header",d=a.series,e=d.tooltipOptions,f=e.xDateFormat,g=d.xAxis,h=g&&g.options.type==="datetime"&&ra(a.key),
c=e[c+"Format"];h&&!f&&(f=this.getXDateFormat(a,e,g));h&&f&&(c=c.replace("{point.key}","{point.key:"+f+"}"));return Ja(c,{point:a,series:d})},bodyFormatter:function(a){return Ua(a,function(a){var c=a.series.tooltipOptions;return(c.pointFormatter||a.point.tooltipFormatter).call(a.point,c.pointFormat)})}};var pa;ab=B.documentElement.ontouchstart!==y;var Va=A.Pointer=function(a,b){this.init(a,b)};Va.prototype={init:function(a,b){var c=b.chart,d=c.events,e=fa?"":c.zoomType,c=a.inverted,f;this.options=
b;this.chart=a;this.zoomX=f=/x/.test(e);this.zoomY=e=/y/.test(e);this.zoomHor=f&&!c||e&&c;this.zoomVert=e&&!c||f&&c;this.hasZoom=f||e;this.runChartClick=d&&!!d.click;this.pinchDown=[];this.lastValidTouch={};if(A.Tooltip&&b.tooltip.enabled)a.tooltip=new Nb(a,b.tooltip),this.followTouchMove=p(b.tooltip.followTouchMove,!0);this.setDOMEvents()},normalize:function(a,b){var c,d,a=a||window.event,a=Tb(a);if(!a.target)a.target=a.srcElement;d=a.touches?a.touches.length?a.touches.item(0):a.changedTouches[0]:
a;if(!b)this.chartPosition=b=Sb(this.chart.container);d.pageX===y?(c=u(a.x,a.clientX-b.left),d=a.y):(c=d.pageX-b.left,d=d.pageY-b.top);return x(a,{chartX:r(c),chartY:r(d)})},getCoordinates:function(a){var b={xAxis:[],yAxis:[]};o(this.chart.axes,function(c){b[c.isXAxis?"xAxis":"yAxis"].push({axis:c,value:c.toValue(a[c.horiz?"chartX":"chartY"])})});return b},runPointActions:function(a){var b=this.chart,c=b.series,d=b.tooltip,e=d?d.shared:!1,f=b.hoverPoint,g=b.hoverSeries,h,i=b.chartWidth,j,k,l=[],m,
n;if(!e&&!g)for(h=0;h<c.length;h++)if(c[h].directTouch||!c[h].options.stickyTracking)c=[];!e&&g&&g.directTouch&&f?m=f:(o(c,function(b){j=b.noSharedTooltip&&e;k=!e&&b.directTouch;b.visible&&!j&&!k&&p(b.options.enableMouseTracking,!0)&&(n=b.searchPoint(a,!j&&b.kdDimensions===1))&&l.push(n)}),o(l,function(a){if(a&&typeof a.dist==="number"&&a.dist<i)i=a.dist,m=a}));if(m&&(m!==this.prevKDPoint||d&&d.isHidden)){if(e&&!m.series.noSharedTooltip){for(h=l.length;h--;)(l[h].clientX!==m.clientX||l[h].series.noSharedTooltip)&&
l.splice(h,1);l.length&&d&&d.refresh(l,a);o(l,function(b){if(b!==m)b.onMouseOver(a)});(g&&g.directTouch&&f||m).onMouseOver(a)}else d&&d.refresh(m,a),m.onMouseOver(a);this.prevKDPoint=m}else c=g&&g.tooltipOptions.followPointer,d&&c&&!d.isHidden&&(c=d.getAnchor([{}],a),d.updatePosition({plotX:c[0],plotY:c[1]}));if(d&&!this._onDocumentMouseMove)this._onDocumentMouseMove=function(a){if(Y[pa])Y[pa].pointer.onDocumentMouseMove(a)},H(B,"mousemove",this._onDocumentMouseMove);o(b.axes,function(b){b.drawCrosshair(a,
p(m,f))})},reset:function(a,b){var c=this.chart,d=c.hoverSeries,e=c.hoverPoint,f=c.hoverPoints,g=c.tooltip,h=g&&g.shared?f:e;(a=a&&g&&h)&&sa(h)[0].plotX===y&&(a=!1);if(a)g.refresh(h),e&&(e.setState(e.state,!0),o(c.axes,function(a){p(a.options.crosshair&&a.options.crosshair.snap,!0)?a.drawCrosshair(null,e):a.hideCrosshair()}));else{if(e)e.onMouseOut();f&&o(f,function(a){a.setState()});if(d)d.onMouseOut();g&&g.hide(b);if(this._onDocumentMouseMove)Z(B,"mousemove",this._onDocumentMouseMove),this._onDocumentMouseMove=
null;o(c.axes,function(a){a.hideCrosshair()});this.hoverX=c.hoverPoints=c.hoverPoint=null}},scaleGroups:function(a,b){var c=this.chart,d;o(c.series,function(e){d=a||e.getPlotBox();e.xAxis&&e.xAxis.zoomEnabled&&(e.group.attr(d),e.markerGroup&&(e.markerGroup.attr(d),e.markerGroup.clip(b?c.clipRect:null)),e.dataLabelsGroup&&e.dataLabelsGroup.attr(d))});c.clipRect.attr(b||c.clipBox)},dragStart:function(a){var b=this.chart;b.mouseIsDown=a.type;b.cancelClick=!1;b.mouseDownX=this.mouseDownX=a.chartX;b.mouseDownY=
this.mouseDownY=a.chartY},drag:function(a){var b=this.chart,c=b.options.chart,d=a.chartX,e=a.chartY,f=this.zoomHor,g=this.zoomVert,h=b.plotLeft,i=b.plotTop,j=b.plotWidth,k=b.plotHeight,l,m=this.mouseDownX,n=this.mouseDownY,v=c.panKey&&a[c.panKey+"Key"];d<h?d=h:d>h+j&&(d=h+j);e<i?e=i:e>i+k&&(e=i+k);this.hasDragged=Math.sqrt(Math.pow(m-d,2)+Math.pow(n-e,2));if(this.hasDragged>10){l=b.isInsidePlot(m-h,n-i);if(b.hasCartesianSeries&&(this.zoomX||this.zoomY)&&l&&!v&&!this.selectionMarker)this.selectionMarker=
b.renderer.rect(h,i,f?1:j,g?1:k,0).attr({fill:c.selectionMarkerFill||"rgba(69,114,167,0.25)",zIndex:7}).add();this.selectionMarker&&f&&(d-=m,this.selectionMarker.attr({width:O(d),x:(d>0?0:d)+m}));this.selectionMarker&&g&&(d=e-n,this.selectionMarker.attr({height:O(d),y:(d>0?0:d)+n}));l&&!this.selectionMarker&&c.panning&&b.pan(a,c.panning)}},drop:function(a){var b=this,c=this.chart,d=this.hasPinched;if(this.selectionMarker){var e={xAxis:[],yAxis:[],originalEvent:a.originalEvent||a},f=this.selectionMarker,
g=f.attr?f.attr("x"):f.x,h=f.attr?f.attr("y"):f.y,i=f.attr?f.attr("width"):f.width,j=f.attr?f.attr("height"):f.height,k;if(this.hasDragged||d)o(c.axes,function(c){if(c.zoomEnabled&&q(c.min)&&(d||b[{xAxis:"zoomX",yAxis:"zoomY"}[c.coll]])){var f=c.horiz,n=a.type==="touchend"?c.minPixelPadding:0,v=c.toValue((f?g:h)+n),f=c.toValue((f?g+i:h+j)-n);e[c.coll].push({axis:c,min:C(v,f),max:u(v,f)});k=!0}}),k&&I(c,"selection",e,function(a){c.zoom(x(a,d?{animation:!1}:null))});this.selectionMarker=this.selectionMarker.destroy();
d&&this.scaleGroups()}if(c)L(c.container,{cursor:c._cursor}),c.cancelClick=this.hasDragged>10,c.mouseIsDown=this.hasDragged=this.hasPinched=!1,this.pinchDown=[]},onContainerMouseDown:function(a){a=this.normalize(a);a.preventDefault&&a.preventDefault();this.dragStart(a)},onDocumentMouseUp:function(a){Y[pa]&&Y[pa].pointer.drop(a)},onDocumentMouseMove:function(a){var b=this.chart,c=this.chartPosition,a=this.normalize(a,c);c&&!this.inClass(a.target,"highcharts-tracker")&&!b.isInsidePlot(a.chartX-b.plotLeft,
a.chartY-b.plotTop)&&this.reset()},onContainerMouseLeave:function(){var a=Y[pa];if(a)a.pointer.reset(),a.pointer.chartPosition=null},onContainerMouseMove:function(a){var b=this.chart;pa=b.index;a=this.normalize(a);a.returnValue=!1;b.mouseIsDown==="mousedown"&&this.drag(a);(this.inClass(a.target,"highcharts-tracker")||b.isInsidePlot(a.chartX-b.plotLeft,a.chartY-b.plotTop))&&!b.openMenu&&this.runPointActions(a)},inClass:function(a,b){for(var c;a;){if(c=J(a,"class"))if(c.indexOf(b)!==-1)return!0;else if(c.indexOf("highcharts-container")!==
-1)return!1;a=a.parentNode}},onTrackerMouseOut:function(a){var b=this.chart.hoverSeries,c=(a=a.relatedTarget||a.toElement)&&a.point&&a.point.series;if(b&&!b.options.stickyTracking&&!this.inClass(a,"highcharts-tooltip")&&c!==b)b.onMouseOut()},onContainerClick:function(a){var b=this.chart,c=b.hoverPoint,d=b.plotLeft,e=b.plotTop,a=this.normalize(a);a.originalEvent=a;b.cancelClick||(c&&this.inClass(a.target,"highcharts-tracker")?(I(c.series,"click",x(a,{point:c})),b.hoverPoint&&c.firePointEvent("click",
a)):(x(a,this.getCoordinates(a)),b.isInsidePlot(a.chartX-d,a.chartY-e)&&I(b,"click",a)))},setDOMEvents:function(){var a=this,b=a.chart.container;b.onmousedown=function(b){a.onContainerMouseDown(b)};b.onmousemove=function(b){a.onContainerMouseMove(b)};b.onclick=function(b){a.onContainerClick(b)};H(b,"mouseleave",a.onContainerMouseLeave);bb===1&&H(B,"mouseup",a.onDocumentMouseUp);if(ab)b.ontouchstart=function(b){a.onContainerTouchStart(b)},b.ontouchmove=function(b){a.onContainerTouchMove(b)},bb===1&&
H(B,"touchend",a.onDocumentTouchEnd)},destroy:function(){var a;Z(this.chart.container,"mouseleave",this.onContainerMouseLeave);bb||(Z(B,"mouseup",this.onDocumentMouseUp),Z(B,"touchend",this.onDocumentTouchEnd));clearInterval(this.tooltipTimeout);for(a in this)this[a]=null}};x(A.Pointer.prototype,{pinchTranslate:function(a,b,c,d,e,f){(this.zoomHor||this.pinchHor)&&this.pinchTranslateDirection(!0,a,b,c,d,e,f);(this.zoomVert||this.pinchVert)&&this.pinchTranslateDirection(!1,a,b,c,d,e,f)},pinchTranslateDirection:function(a,
b,c,d,e,f,g,h){var i=this.chart,j=a?"x":"y",k=a?"X":"Y",l="chart"+k,m=a?"width":"height",n=i["plot"+(a?"Left":"Top")],v,s,p=h||1,o=i.inverted,t=i.bounds[a?"h":"v"],w=b.length===1,q=b[0][l],u=c[0][l],r=!w&&b[1][l],y=!w&&c[1][l],x,c=function(){!w&&O(q-r)>20&&(p=h||O(u-y)/O(q-r));s=(n-u)/p+q;v=i["plot"+(a?"Width":"Height")]/p};c();b=s;b<t.min?(b=t.min,x=!0):b+v>t.max&&(b=t.max-v,x=!0);x?(u-=0.8*(u-g[j][0]),w||(y-=0.8*(y-g[j][1])),c()):g[j]=[u,y];o||(f[j]=s-n,f[m]=v);f=o?1/p:p;e[m]=v;e[j]=b;d[o?a?"scaleY":
"scaleX":"scale"+k]=p;d["translate"+k]=f*n+(u-f*q)},pinch:function(a){var b=this,c=b.chart,d=b.pinchDown,e=a.touches,f=e.length,g=b.lastValidTouch,h=b.hasZoom,i=b.selectionMarker,j={},k=f===1&&(b.inClass(a.target,"highcharts-tracker")&&c.runTrackerClick||b.runChartClick),l={};if(f>1)b.initiated=!0;h&&b.initiated&&!k&&a.preventDefault();Ua(e,function(a){return b.normalize(a)});if(a.type==="touchstart")o(e,function(a,b){d[b]={chartX:a.chartX,chartY:a.chartY}}),g.x=[d[0].chartX,d[1]&&d[1].chartX],g.y=
[d[0].chartY,d[1]&&d[1].chartY],o(c.axes,function(a){if(a.zoomEnabled){var b=c.bounds[a.horiz?"h":"v"],d=a.minPixelPadding,e=a.toPixels(p(a.options.min,a.dataMin)),f=a.toPixels(p(a.options.max,a.dataMax)),g=C(e,f),e=u(e,f);b.min=C(a.pos,g-d);b.max=u(a.pos+a.len,e+d)}}),b.res=!0;else if(d.length){if(!i)b.selectionMarker=i=x({destroy:na},c.plotBox);b.pinchTranslate(d,e,j,i,l,g);b.hasPinched=h;b.scaleGroups(j,l);if(!h&&b.followTouchMove&&f===1)this.runPointActions(b.normalize(a));else if(b.res)b.res=
!1,this.reset(!1,0)}},touch:function(a,b){var c=this.chart;pa=c.index;a.touches.length===1?(a=this.normalize(a),c.isInsidePlot(a.chartX-c.plotLeft,a.chartY-c.plotTop)&&!c.openMenu?(b&&this.runPointActions(a),this.pinch(a)):b&&this.reset()):a.touches.length===2&&this.pinch(a)},onContainerTouchStart:function(a){this.touch(a,!0)},onContainerTouchMove:function(a){this.touch(a)},onDocumentTouchEnd:function(a){Y[pa]&&Y[pa].pointer.drop(a)}});if(K.PointerEvent||K.MSPointerEvent){var wa={},Bb=!!K.PointerEvent,
Xb=function(){var a,b=[];b.item=function(a){return this[a]};for(a in wa)wa.hasOwnProperty(a)&&b.push({pageX:wa[a].pageX,pageY:wa[a].pageY,target:wa[a].target});return b},Cb=function(a,b,c,d){a=a.originalEvent||a;if((a.pointerType==="touch"||a.pointerType===a.MSPOINTER_TYPE_TOUCH)&&Y[pa])d(a),d=Y[pa].pointer,d[b]({type:c,target:a.currentTarget,preventDefault:na,touches:Xb()})};x(Va.prototype,{onContainerPointerDown:function(a){Cb(a,"onContainerTouchStart","touchstart",function(a){wa[a.pointerId]={pageX:a.pageX,
pageY:a.pageY,target:a.currentTarget}})},onContainerPointerMove:function(a){Cb(a,"onContainerTouchMove","touchmove",function(a){wa[a.pointerId]={pageX:a.pageX,pageY:a.pageY};if(!wa[a.pointerId].target)wa[a.pointerId].target=a.currentTarget})},onDocumentPointerUp:function(a){Cb(a,"onDocumentTouchEnd","touchend",function(a){delete wa[a.pointerId]})},batchMSEvents:function(a){a(this.chart.container,Bb?"pointerdown":"MSPointerDown",this.onContainerPointerDown);a(this.chart.container,Bb?"pointermove":
"MSPointerMove",this.onContainerPointerMove);a(B,Bb?"pointerup":"MSPointerUp",this.onDocumentPointerUp)}});cb(Va.prototype,"init",function(a,b,c){a.call(this,b,c);this.hasZoom&&L(b.container,{"-ms-touch-action":P,"touch-action":P})});cb(Va.prototype,"setDOMEvents",function(a){a.apply(this);(this.hasZoom||this.followTouchMove)&&this.batchMSEvents(H)});cb(Va.prototype,"destroy",function(a){this.batchMSEvents(Z);a.call(this)})}var nb=A.Legend=function(a,b){this.init(a,b)};nb.prototype={init:function(a,
b){var c=this,d=b.itemStyle,e=b.itemMarginTop||0;this.options=b;if(b.enabled)c.itemStyle=d,c.itemHiddenStyle=z(d,b.itemHiddenStyle),c.itemMarginTop=e,c.padding=d=p(b.padding,8),c.initialItemX=d,c.initialItemY=d-5,c.maxItemWidth=0,c.chart=a,c.itemHeight=0,c.symbolWidth=p(b.symbolWidth,16),c.pages=[],c.render(),H(c.chart,"endResize",function(){c.positionCheckboxes()})},colorizeItem:function(a,b){var c=this.options,d=a.legendItem,e=a.legendLine,f=a.legendSymbol,g=this.itemHiddenStyle.color,c=b?c.itemStyle.color:
g,h=b?a.legendColor||a.color||"#CCC":g,g=a.options&&a.options.marker,i={fill:h},j;d&&d.css({fill:c,color:c});e&&e.attr({stroke:h});if(f){if(g&&f.isMarker)for(j in i.stroke=h,g=a.convertAttribs(g),g)d=g[j],d!==y&&(i[j]=d);f.attr(i)}},positionItem:function(a){var b=this.options,c=b.symbolPadding,b=!b.rtl,d=a._legendItemPos,e=d[0],d=d[1],f=a.checkbox;(a=a.legendGroup)&&a.element&&a.translate(b?e:this.legendWidth-e-2*c-4,d);if(f)f.x=e,f.y=d},destroyItem:function(a){var b=a.checkbox;o(["legendItem","legendLine",
"legendSymbol","legendGroup"],function(b){a[b]&&(a[b]=a[b].destroy())});b&&Ra(a.checkbox)},destroy:function(){var a=this.group,b=this.box;if(b)this.box=b.destroy();if(a)this.group=a.destroy()},positionCheckboxes:function(a){var b=this.group.alignAttr,c,d=this.clipHeight||this.legendHeight;if(b)c=b.translateY,o(this.allItems,function(e){var f=e.checkbox,g;f&&(g=c+f.y+(a||0)+3,L(f,{left:b.translateX+e.checkboxOffset+f.x-20+"px",top:g+"px",display:g>c-6&&g<c+d-6?"":P}))})},renderTitle:function(){var a=
this.padding,b=this.options.title,c=0;if(b.text){if(!this.title)this.title=this.chart.renderer.label(b.text,a-3,a-4,null,null,null,null,null,"legend-title").attr({zIndex:1}).css(b.style).add(this.group);a=this.title.getBBox();c=a.height;this.offsetWidth=a.width;this.contentGroup.attr({translateY:c})}this.titleHeight=c},setText:function(a){var b=this.options;a.legendItem.attr({text:b.labelFormat?Ja(b.labelFormat,a):b.labelFormatter.call(a)})},renderItem:function(a){var b=this.chart,c=b.renderer,d=
this.options,e=d.layout==="horizontal",f=this.symbolWidth,g=d.symbolPadding,h=this.itemStyle,i=this.itemHiddenStyle,j=this.padding,k=e?p(d.itemDistance,20):0,l=!d.rtl,m=d.width,n=d.itemMarginBottom||0,v=this.itemMarginTop,s=this.initialItemX,o=a.legendItem,q=a.series&&a.series.drawLegendSymbol?a.series:a,t=q.options,t=this.createCheckboxForItem&&t&&t.showCheckbox,w=d.useHTML;if(!o){a.legendGroup=c.g("legend-item").attr({zIndex:1}).add(this.scrollGroup);a.legendItem=o=c.text("",l?f+g:-g,this.baseline||
0,w).css(z(a.visible?h:i)).attr({align:l?"left":"right",zIndex:2}).add(a.legendGroup);if(!this.baseline)this.fontMetrics=c.fontMetrics(h.fontSize,o),this.baseline=this.fontMetrics.f+3+v,o.attr("y",this.baseline);q.drawLegendSymbol(this,a);this.setItemEvents&&this.setItemEvents(a,o,w,h,i);this.colorizeItem(a,a.visible);t&&this.createCheckboxForItem(a)}this.setText(a);c=o.getBBox();f=a.checkboxOffset=d.itemWidth||a.legendItemWidth||f+g+c.width+k+(t?20:0);this.itemHeight=g=r(a.legendItemHeight||c.height);
if(e&&this.itemX-s+f>(m||b.chartWidth-2*j-s-d.x))this.itemX=s,this.itemY+=v+this.lastLineHeight+n,this.lastLineHeight=0;this.maxItemWidth=u(this.maxItemWidth,f);this.lastItemY=v+this.itemY+n;this.lastLineHeight=u(g,this.lastLineHeight);a._legendItemPos=[this.itemX,this.itemY];e?this.itemX+=f:(this.itemY+=v+g+n,this.lastLineHeight=g);this.offsetWidth=m||u((e?this.itemX-s-k:f)+j,this.offsetWidth)},getAllItems:function(){var a=[];o(this.chart.series,function(b){var c=b.options;if(p(c.showInLegend,!q(c.linkedTo)?
y:!1,!0))a=a.concat(b.legendItems||(c.legendType==="point"?b.data:b))});return a},adjustMargins:function(a,b){var c=this.chart,d=this.options,e=d.align[0]+d.verticalAlign[0]+d.layout[0];this.display&&!d.floating&&o([/(lth|ct|rth)/,/(rtv|rm|rbv)/,/(rbh|cb|lbh)/,/(lbv|lm|ltv)/],function(f,g){f.test(e)&&!q(a[g])&&(c[jb[g]]=u(c[jb[g]],c.legend[(g+1)%2?"legendHeight":"legendWidth"]+[1,-1,-1,1][g]*d[g%2?"x":"y"]+p(d.margin,12)+b[g]))})},render:function(){var a=this,b=a.chart,c=b.renderer,d=a.group,e,f,
g,h,i=a.box,j=a.options,k=a.padding,l=j.borderWidth,m=j.backgroundColor;a.itemX=a.initialItemX;a.itemY=a.initialItemY;a.offsetWidth=0;a.lastItemY=0;if(!d)a.group=d=c.g("legend").attr({zIndex:7}).add(),a.contentGroup=c.g().attr({zIndex:1}).add(d),a.scrollGroup=c.g().add(a.contentGroup);a.renderTitle();e=a.getAllItems();rb(e,function(a,b){return(a.options&&a.options.legendIndex||0)-(b.options&&b.options.legendIndex||0)});j.reversed&&e.reverse();a.allItems=e;a.display=f=!!e.length;a.lastLineHeight=0;
o(e,function(b){a.renderItem(b)});g=(j.width||a.offsetWidth)+k;h=a.lastItemY+a.lastLineHeight+a.titleHeight;h=a.handleOverflow(h);h+=k;if(l||m){if(i){if(g>0&&h>0)i[i.isNew?"attr":"animate"](i.crisp({width:g,height:h})),i.isNew=!1}else a.box=i=c.rect(0,0,g,h,j.borderRadius,l||0).attr({stroke:j.borderColor,"stroke-width":l||0,fill:m||P}).add(d).shadow(j.shadow),i.isNew=!0;i[f?"show":"hide"]()}a.legendWidth=g;a.legendHeight=h;o(e,function(b){a.positionItem(b)});f&&d.align(x({width:g,height:h},j),!0,
"spacingBox");b.isResizing||this.positionCheckboxes()},handleOverflow:function(a){var b=this,c=this.chart,d=c.renderer,e=this.options,f=e.y,f=c.spacingBox.height+(e.verticalAlign==="top"?-f:f)-this.padding,g=e.maxHeight,h,i=this.clipRect,j=e.navigation,k=p(j.animation,!0),l=j.arrowSize||12,m=this.nav,n=this.pages,v=this.padding,s,q=this.allItems,N=function(a){i.attr({height:a});if(b.contentGroup.div)b.contentGroup.div.style.clip="rect("+v+"px,9999px,"+(v+a)+"px,0)"};e.layout==="horizontal"&&(f/=2);
g&&(f=C(f,g));n.length=0;if(a>f){this.clipHeight=h=u(f-20-this.titleHeight-v,0);this.currentPage=p(this.currentPage,1);this.fullHeight=a;o(q,function(a,b){var c=a._legendItemPos[1],d=r(a.legendItem.getBBox().height),e=n.length;if(!e||c-n[e-1]>h&&(s||c)!==n[e-1])n.push(s||c),e++;b===q.length-1&&c+d-n[e-1]>h&&n.push(c);c!==s&&(s=c)});if(!i)i=b.clipRect=d.clipRect(0,v,9999,0),b.contentGroup.clip(i);N(h);if(!m)this.nav=m=d.g().attr({zIndex:1}).add(this.group),this.up=d.symbol("triangle",0,0,l,l).on("click",
function(){b.scroll(-1,k)}).add(m),this.pager=d.text("",15,10).css(j.style).add(m),this.down=d.symbol("triangle-down",0,0,l,l).on("click",function(){b.scroll(1,k)}).add(m);b.scroll(0);a=f}else if(m)N(c.chartHeight),m.hide(),this.scrollGroup.attr({translateY:1}),this.clipHeight=0;return a},scroll:function(a,b){var c=this.pages,d=c.length,e=this.currentPage+a,f=this.clipHeight,g=this.options.navigation,h=g.activeColor,g=g.inactiveColor,i=this.pager,j=this.padding;e>d&&(e=d);if(e>0)b!==y&&Sa(b,this.chart),
this.nav.attr({translateX:j,translateY:f+this.padding+7+this.titleHeight,visibility:"visible"}),this.up.attr({fill:e===1?g:h}).css({cursor:e===1?"default":"pointer"}),i.attr({text:e+"/"+d}),this.down.attr({x:18+this.pager.getBBox().width,fill:e===d?g:h}).css({cursor:e===d?"default":"pointer"}),c=-c[e-1]+this.initialItemY,this.scrollGroup.animate({translateY:c}),this.currentPage=e,this.positionCheckboxes(c)}};Na=A.LegendSymbolMixin={drawRectangle:function(a,b){var c=a.options.symbolHeight||a.fontMetrics.f;
b.legendSymbol=this.chart.renderer.rect(0,a.baseline-c+1,a.symbolWidth,c,a.options.symbolRadius||0).attr({zIndex:3}).add(b.legendGroup)},drawLineMarker:function(a){var b=this.options,c=b.marker,d;d=a.symbolWidth;var e=this.chart.renderer,f=this.legendGroup,a=a.baseline-r(a.fontMetrics.b*0.3),g;if(b.lineWidth){g={"stroke-width":b.lineWidth};if(b.dashStyle)g.dashstyle=b.dashStyle;this.legendLine=e.path(["M",0,a,"L",d,a]).attr(g).add(f)}if(c&&c.enabled!==!1)b=c.radius,this.legendSymbol=d=e.symbol(this.symbol,
d/2-b,a-b,2*b,2*b).add(f),d.isMarker=!0}};(/Trident\/7\.0/.test(Ba)||La)&&cb(nb.prototype,"positionItem",function(a,b){var c=this,d=function(){b._legendItemPos&&a.call(c,b)};d();setTimeout(d)});F=A.Chart=function(){this.init.apply(this,arguments)};F.prototype={callbacks:[],init:function(a,b){var c,d=a.series;a.series=null;c=z(T,a);c.series=a.series=d;this.userOptions=a;d=c.chart;this.margin=this.splashArray("margin",d);this.spacing=this.splashArray("spacing",d);var e=d.events;this.bounds={h:{},v:{}};
this.callback=b;this.isResizing=0;this.options=c;this.axes=[];this.series=[];this.hasCartesianSeries=d.showAxes;var f=this,g;f.index=Y.length;Y.push(f);bb++;d.reflow!==!1&&H(f,"load",function(){f.initReflow()});if(e)for(g in e)H(f,g,e[g]);f.xAxis=[];f.yAxis=[];f.animation=fa?!1:p(d.animation,!0);f.pointCount=f.colorCounter=f.symbolCounter=0;f.firstRender()},initSeries:function(a){var b=this.options.chart;(b=M[a.type||b.type||b.defaultSeriesType])||la(17,!0);b=new b;b.init(this,a);return b},isInsidePlot:function(a,
b,c){var d=c?b:a,a=c?a:b;return d>=0&&d<=this.plotWidth&&a>=0&&a<=this.plotHeight},redraw:function(a){var b=this.axes,c=this.series,d=this.pointer,e=this.legend,f=this.isDirtyLegend,g,h,i=this.hasCartesianSeries,j=this.isDirtyBox,k=c.length,l=k,m=this.renderer,n=m.isHidden(),p=[];Sa(a,this);n&&this.cloneRenderTo();for(this.layOutTitles();l--;)if(a=c[l],a.options.stacking&&(g=!0,a.isDirty)){h=!0;break}if(h)for(l=k;l--;)if(a=c[l],a.options.stacking)a.isDirty=!0;o(c,function(a){a.isDirty&&a.options.legendType===
"point"&&(a.updateTotals&&a.updateTotals(),f=!0)});if(f&&e.options.enabled)e.render(),this.isDirtyLegend=!1;g&&this.getStacks();if(i&&!this.isResizing)this.maxTicks=null,o(b,function(a){a.setScale()});this.getMargins();i&&(o(b,function(a){a.isDirty&&(j=!0)}),o(b,function(a){if(a.isDirtyExtremes)a.isDirtyExtremes=!1,p.push(function(){I(a,"afterSetExtremes",x(a.eventArgs,a.getExtremes()));delete a.eventArgs});(j||g)&&a.redraw()}));j&&this.drawChartBox();o(c,function(a){a.isDirty&&a.visible&&(!a.isCartesian||
a.xAxis)&&a.redraw()});d&&d.reset(!0);m.draw();I(this,"redraw");n&&this.cloneRenderTo(!0);o(p,function(a){a.call()})},get:function(a){var b=this.axes,c=this.series,d,e;for(d=0;d<b.length;d++)if(b[d].options.id===a)return b[d];for(d=0;d<c.length;d++)if(c[d].options.id===a)return c[d];for(d=0;d<c.length;d++){e=c[d].points||[];for(b=0;b<e.length;b++)if(e[b].id===a)return e[b]}return null},getAxes:function(){var a=this,b=this.options,c=b.xAxis=sa(b.xAxis||{}),b=b.yAxis=sa(b.yAxis||{});o(c,function(a,
b){a.index=b;a.isX=!0});o(b,function(a,b){a.index=b});c=c.concat(b);o(c,function(b){new va(a,b)})},getSelectedPoints:function(){var a=[];o(this.series,function(b){a=a.concat(lb(b.points||[],function(a){return a.selected}))});return a},getSelectedSeries:function(){return lb(this.series,function(a){return a.selected})},getStacks:function(){var a=this;o(a.yAxis,function(a){if(a.stacks&&a.hasVisibleSeries)a.oldStacks=a.stacks});o(a.series,function(b){if(b.options.stacking&&(b.visible===!0||a.options.chart.ignoreHiddenSeries===
!1))b.stackKey=b.type+p(b.options.stack,"")})},setTitle:function(a,b,c){var g;var d=this,e=d.options,f;f=e.title=z(e.title,a);g=e.subtitle=z(e.subtitle,b),e=g;o([["title",a,f],["subtitle",b,e]],function(a){var b=a[0],c=d[b],e=a[1],a=a[2];c&&e&&(d[b]=c=c.destroy());a&&a.text&&!c&&(d[b]=d.renderer.text(a.text,0,0,a.useHTML).attr({align:a.align,"class":"highcharts-"+b,zIndex:a.zIndex||4}).css(a.style).add())});d.layOutTitles(c)},layOutTitles:function(a){var b=0,c=this.title,d=this.subtitle,e=this.options,
f=e.title,e=e.subtitle,g=this.renderer,h=this.spacingBox.width-44;if(c&&(c.css({width:(f.width||h)+"px"}).align(x({y:g.fontMetrics(f.style.fontSize,c).b-3},f),!1,"spacingBox"),!f.floating&&!f.verticalAlign))b=c.getBBox().height;d&&(d.css({width:(e.width||h)+"px"}).align(x({y:b+(f.margin-13)+g.fontMetrics(f.style.fontSize,d).b},e),!1,"spacingBox"),!e.floating&&!e.verticalAlign&&(b=ta(b+d.getBBox().height)));c=this.titleOffset!==b;this.titleOffset=b;if(!this.isDirtyBox&&c)this.isDirtyBox=c,this.hasRendered&&
p(a,!0)&&this.isDirtyBox&&this.redraw()},getChartSize:function(){var a=this.options.chart,b=a.width,a=a.height,c=this.renderToClone||this.renderTo;if(!q(b))this.containerWidth=kb(c,"width");if(!q(a))this.containerHeight=kb(c,"height");this.chartWidth=u(0,b||this.containerWidth||600);this.chartHeight=u(0,p(a,this.containerHeight>19?this.containerHeight:400))},cloneRenderTo:function(a){var b=this.renderToClone,c=this.container;a?b&&(this.renderTo.appendChild(c),Ra(b),delete this.renderToClone):(c&&
c.parentNode===this.renderTo&&this.renderTo.removeChild(c),this.renderToClone=b=this.renderTo.cloneNode(0),L(b,{position:"absolute",top:"-9999px",display:"block"}),b.style.setProperty&&b.style.setProperty("display","block","important"),B.body.appendChild(b),c&&b.appendChild(c))},getContainer:function(){var a,b=this.options.chart,c,d,e;this.renderTo=a=b.renderTo;e="highcharts-"+yb++;if(Da(a))this.renderTo=a=B.getElementById(a);a||la(13,!0);c=D(J(a,"data-highcharts-chart"));!isNaN(c)&&Y[c]&&Y[c].hasRendered&&
Y[c].destroy();J(a,"data-highcharts-chart",this.index);a.innerHTML="";!b.skipClone&&!a.offsetWidth&&this.cloneRenderTo();this.getChartSize();c=this.chartWidth;d=this.chartHeight;this.container=a=$(Ka,{className:"highcharts-container"+(b.className?" "+b.className:""),id:e},x({position:"relative",overflow:"hidden",width:c+"px",height:d+"px",textAlign:"left",lineHeight:"normal",zIndex:0,"-webkit-tap-highlight-color":"rgba(0,0,0,0)"},b.style),this.renderToClone||a);this._cursor=a.style.cursor;this.renderer=
b.forExport?new ua(a,c,d,b.style,!0):new $a(a,c,d,b.style);fa&&this.renderer.create(this,a,c,d);this.renderer.chartIndex=this.index},getMargins:function(a){var b=this.spacing,c=this.margin,d=this.titleOffset;this.resetMargins();if(d&&!q(c[0]))this.plotTop=u(this.plotTop,d+this.options.title.margin+b[0]);this.legend.adjustMargins(c,b);this.extraBottomMargin&&(this.marginBottom+=this.extraBottomMargin);this.extraTopMargin&&(this.plotTop+=this.extraTopMargin);a||this.getAxisMargins()},getAxisMargins:function(){var a=
this,b=a.axisOffset=[0,0,0,0],c=a.margin;a.hasCartesianSeries&&o(a.axes,function(a){a.getOffset()});o(jb,function(d,e){q(c[e])||(a[d]+=b[e])});a.setChartSize()},reflow:function(a){var b=this,c=b.options.chart,d=b.renderTo,e=c.width||kb(d,"width"),f=c.height||kb(d,"height"),c=a?a.target:K,d=function(){if(b.container)b.setSize(e,f,!1),b.hasUserSize=null};if(!b.hasUserSize&&!b.isPrinting&&e&&f&&(c===K||c===B)){if(e!==b.containerWidth||f!==b.containerHeight)clearTimeout(b.reflowTimeout),a?b.reflowTimeout=
setTimeout(d,100):d();b.containerWidth=e;b.containerHeight=f}},initReflow:function(){var a=this,b=function(b){a.reflow(b)};H(K,"resize",b);H(a,"destroy",function(){Z(K,"resize",b)})},setSize:function(a,b,c){var d=this,e,f,g;d.isResizing+=1;g=function(){d&&I(d,"endResize",null,function(){d.isResizing-=1})};Sa(c,d);d.oldChartHeight=d.chartHeight;d.oldChartWidth=d.chartWidth;if(q(a))d.chartWidth=e=u(0,r(a)),d.hasUserSize=!!e;if(q(b))d.chartHeight=f=u(0,r(b));(za?mb:L)(d.container,{width:e+"px",height:f+
"px"},za);d.setChartSize(!0);d.renderer.setSize(e,f,c);d.maxTicks=null;o(d.axes,function(a){a.isDirty=!0;a.setScale()});o(d.series,function(a){a.isDirty=!0});d.isDirtyLegend=!0;d.isDirtyBox=!0;d.layOutTitles();d.getMargins();d.redraw(c);d.oldChartHeight=null;I(d,"resize");za===!1?g():setTimeout(g,za&&za.duration||500)},setChartSize:function(a){var b=this.inverted,c=this.renderer,d=this.chartWidth,e=this.chartHeight,f=this.options.chart,g=this.spacing,h=this.clipOffset,i,j,k,l;this.plotLeft=i=r(this.plotLeft);
this.plotTop=j=r(this.plotTop);this.plotWidth=k=u(0,r(d-i-this.marginRight));this.plotHeight=l=u(0,r(e-j-this.marginBottom));this.plotSizeX=b?l:k;this.plotSizeY=b?k:l;this.plotBorderWidth=f.plotBorderWidth||0;this.spacingBox=c.spacingBox={x:g[3],y:g[0],width:d-g[3]-g[1],height:e-g[0]-g[2]};this.plotBox=c.plotBox={x:i,y:j,width:k,height:l};d=2*V(this.plotBorderWidth/2);b=ta(u(d,h[3])/2);c=ta(u(d,h[0])/2);this.clipBox={x:b,y:c,width:V(this.plotSizeX-u(d,h[1])/2-b),height:u(0,V(this.plotSizeY-u(d,h[2])/
2-c))};a||o(this.axes,function(a){a.setAxisSize();a.setAxisTranslation()})},resetMargins:function(){var a=this;o(jb,function(b,c){a[b]=p(a.margin[c],a.spacing[c])});a.axisOffset=[0,0,0,0];a.clipOffset=[0,0,0,0]},drawChartBox:function(){var a=this.options.chart,b=this.renderer,c=this.chartWidth,d=this.chartHeight,e=this.chartBackground,f=this.plotBackground,g=this.plotBorder,h=this.plotBGImage,i=a.borderWidth||0,j=a.backgroundColor,k=a.plotBackgroundColor,l=a.plotBackgroundImage,m=a.plotBorderWidth||
0,n,p=this.plotLeft,o=this.plotTop,q=this.plotWidth,u=this.plotHeight,t=this.plotBox,w=this.clipRect,r=this.clipBox;n=i+(a.shadow?8:0);if(i||j)if(e)e.animate(e.crisp({width:c-n,height:d-n}));else{e={fill:j||P};if(i)e.stroke=a.borderColor,e["stroke-width"]=i;this.chartBackground=b.rect(n/2,n/2,c-n,d-n,a.borderRadius,i).attr(e).addClass("highcharts-background").add().shadow(a.shadow)}if(k)f?f.animate(t):this.plotBackground=b.rect(p,o,q,u,0).attr({fill:k}).add().shadow(a.plotShadow);if(l)h?h.animate(t):
this.plotBGImage=b.image(l,p,o,q,u).add();w?w.animate({width:r.width,height:r.height}):this.clipRect=b.clipRect(r);if(m)g?g.animate(g.crisp({x:p,y:o,width:q,height:u,strokeWidth:-m})):this.plotBorder=b.rect(p,o,q,u,0,-m).attr({stroke:a.plotBorderColor,"stroke-width":m,fill:P,zIndex:1}).add();this.isDirtyBox=!1},propFromSeries:function(){var a=this,b=a.options.chart,c,d=a.options.series,e,f;o(["inverted","angular","polar"],function(g){c=M[b.type||b.defaultSeriesType];f=a[g]||b[g]||c&&c.prototype[g];
for(e=d&&d.length;!f&&e--;)(c=M[d[e].type])&&c.prototype[g]&&(f=!0);a[g]=f})},linkSeries:function(){var a=this,b=a.series;o(b,function(a){a.linkedSeries.length=0});o(b,function(b){var d=b.options.linkedTo;if(Da(d)&&(d=d===":previous"?a.series[b.index-1]:a.get(d)))d.linkedSeries.push(b),b.linkedParent=d})},renderSeries:function(){o(this.series,function(a){a.translate();a.render()})},renderLabels:function(){var a=this,b=a.options.labels;b.items&&o(b.items,function(c){var d=x(b.style,c.style),e=D(d.left)+
a.plotLeft,f=D(d.top)+a.plotTop+12;delete d.left;delete d.top;a.renderer.text(c.html,e,f).attr({zIndex:2}).css(d).add()})},render:function(){var a=this.axes,b=this.renderer,c=this.options,d,e,f,g;this.setTitle();this.legend=new nb(this,c.legend);this.getStacks();this.getMargins(!0);this.setChartSize();d=this.plotWidth;e=this.plotHeight-=13;o(a,function(a){a.setScale()});this.getAxisMargins();f=d/this.plotWidth>1.1;g=e/this.plotHeight>1.1;if(f||g)this.maxTicks=null,o(a,function(a){(a.horiz&&f||!a.horiz&&
g)&&a.setTickInterval(!0)}),this.getMargins();this.drawChartBox();this.hasCartesianSeries&&o(a,function(a){a.render()});if(!this.seriesGroup)this.seriesGroup=b.g("series-group").attr({zIndex:3}).add();this.renderSeries();this.renderLabels();this.showCredits(c.credits);this.hasRendered=!0},showCredits:function(a){if(a.enabled&&!this.credits)this.credits=this.renderer.text(a.text,0,0).on("click",function(){if(a.href)location.href=a.href}).attr({align:a.position.align,zIndex:8}).css(a.style).add().align(a.position)},
destroy:function(){var a=this,b=a.axes,c=a.series,d=a.container,e,f=d&&d.parentNode;I(a,"destroy");Y[a.index]=y;bb--;a.renderTo.removeAttribute("data-highcharts-chart");Z(a);for(e=b.length;e--;)b[e]=b[e].destroy();for(e=c.length;e--;)c[e]=c[e].destroy();o("title,subtitle,chartBackground,plotBackground,plotBGImage,plotBorder,seriesGroup,clipRect,credits,pointer,scroller,rangeSelector,legend,resetZoomButton,tooltip,renderer".split(","),function(b){var c=a[b];c&&c.destroy&&(a[b]=c.destroy())});if(d)d.innerHTML=
"",Z(d),f&&Ra(d);for(e in a)delete a[e]},isReadyToRender:function(){var a=this;return!ca&&K==K.top&&B.readyState!=="complete"||fa&&!K.canvg?(fa?Mb.push(function(){a.firstRender()},a.options.global.canvasToolsURL):B.attachEvent("onreadystatechange",function(){B.detachEvent("onreadystatechange",a.firstRender);B.readyState==="complete"&&a.firstRender()}),!1):!0},firstRender:function(){var a=this,b=a.options,c=a.callback;if(a.isReadyToRender()){a.getContainer();I(a,"init");a.resetMargins();a.setChartSize();
a.propFromSeries();a.getAxes();o(b.series||[],function(b){a.initSeries(b)});a.linkSeries();I(a,"beforeRender");if(A.Pointer)a.pointer=new Va(a,b);a.render();a.renderer.draw();c&&c.apply(a,[a]);o(a.callbacks,function(b){a.index!==y&&b.apply(a,[a])});I(a,"load");a.cloneRenderTo(!0)}},splashArray:function(a,b){var c=b[a],c=da(c)?c:[c,c,c,c];return[p(b[a+"Top"],c[0]),p(b[a+"Right"],c[1]),p(b[a+"Bottom"],c[2]),p(b[a+"Left"],c[3])]}};var Yb=A.CenteredSeriesMixin={getCenter:function(){var a=this.options,
b=this.chart,c=2*(a.slicedOffset||0),d=b.plotWidth-2*c,b=b.plotHeight-2*c,e=a.center,e=[p(e[0],"50%"),p(e[1],"50%"),a.size||"100%",a.innerSize||0],f=C(d,b),g,h;for(g=0;g<4;++g)h=e[g],a=g<2||g===2&&/%$/.test(h),e[g]=(/%$/.test(h)?[d,b,f,e[2]][g]*parseFloat(h)/100:parseFloat(h))+(a?c:0);return e}},Ga=function(){};Ga.prototype={init:function(a,b,c){this.series=a;this.color=a.color;this.applyOptions(b,c);this.pointAttr={};if(a.options.colorByPoint&&(b=a.options.colors||a.chart.options.colors,this.color=
this.color||b[a.colorCounter++],a.colorCounter===b.length))a.colorCounter=0;a.chart.pointCount++;return this},applyOptions:function(a,b){var c=this.series,d=c.options.pointValKey||c.pointValKey,a=Ga.prototype.optionsToObject.call(this,a);x(this,a);this.options=this.options?x(this.options,a):a;if(d)this.y=this[d];if(this.x===y&&c)this.x=b===y?c.autoIncrement():b;return this},optionsToObject:function(a){var b={},c=this.series,d=c.options.keys,e=d||c.pointArrayMap||["y"],f=e.length,g=0,h=0;if(typeof a===
"number"||a===null)b[e[0]]=a;else if(Ha(a)){if(!d&&a.length>f){c=typeof a[0];if(c==="string")b.name=a[0];else if(c==="number")b.x=a[0];g++}for(;h<f;)b[e[h++]]=a[g++]}else if(typeof a==="object"){b=a;if(a.dataLabels)c._hasPointLabels=!0;if(a.marker)c._hasPointMarkers=!0}return b},destroy:function(){var a=this.series.chart,b=a.hoverPoints,c;a.pointCount--;if(b&&(this.setState(),ja(b,this),!b.length))a.hoverPoints=null;if(this===a.hoverPoint)this.onMouseOut();if(this.graphic||this.dataLabel)Z(this),
this.destroyElements();this.legendItem&&a.legend.destroyItem(this);for(c in this)this[c]=null},destroyElements:function(){for(var a="graphic,dataLabel,dataLabelUpper,group,connector,shadowGroup".split(","),b,c=6;c--;)b=a[c],this[b]&&(this[b]=this[b].destroy())},getLabelConfig:function(){return{x:this.category,y:this.y,key:this.name||this.category,series:this.series,point:this,percentage:this.percentage,total:this.total||this.stackTotal}},tooltipFormatter:function(a){var b=this.series,c=b.tooltipOptions,
d=p(c.valueDecimals,""),e=c.valuePrefix||"",f=c.valueSuffix||"";o(b.pointArrayMap||["y"],function(b){b="{point."+b;if(e||f)a=a.replace(b+"}",e+b+"}"+f);a=a.replace(b+"}",b+":,."+d+"f}")});return Ja(a,{point:this,series:this.series})},firePointEvent:function(a,b,c){var d=this,e=this.series.options;(e.point.events[a]||d.options&&d.options.events&&d.options.events[a])&&this.importEvents();a==="click"&&e.allowPointSelect&&(c=function(a){d.select&&d.select(null,a.ctrlKey||a.metaKey||a.shiftKey)});I(this,
a,b,c)}};var R=A.Series=function(){};R.prototype={isCartesian:!0,type:"line",pointClass:Ga,sorted:!0,requireSorting:!0,pointAttrToOptions:{stroke:"lineColor","stroke-width":"lineWidth",fill:"fillColor",r:"radius"},axisTypes:["xAxis","yAxis"],colorCounter:0,parallelArrays:["x","y"],init:function(a,b){var c=this,d,e,f=a.series,g=function(a,b){return p(a.options.index,a._i)-p(b.options.index,b._i)};c.chart=a;c.options=b=c.setOptions(b);c.linkedSeries=[];c.bindAxes();x(c,{name:b.name,state:"",pointAttr:{},
visible:b.visible!==!1,selected:b.selected===!0});if(fa)b.animation=!1;e=b.events;for(d in e)H(c,d,e[d]);if(e&&e.click||b.point&&b.point.events&&b.point.events.click||b.allowPointSelect)a.runTrackerClick=!0;c.getColor();c.getSymbol();o(c.parallelArrays,function(a){c[a+"Data"]=[]});c.setData(b.data,!1);if(c.isCartesian)a.hasCartesianSeries=!0;f.push(c);c._i=f.length-1;rb(f,g);this.yAxis&&rb(this.yAxis.series,g);o(f,function(a,b){a.index=b;a.name=a.name||"Series "+(b+1)})},bindAxes:function(){var a=
this,b=a.options,c=a.chart,d;o(a.axisTypes||[],function(e){o(c[e],function(c){d=c.options;if(b[e]===d.index||b[e]!==y&&b[e]===d.id||b[e]===y&&d.index===0)c.series.push(a),a[e]=c,c.isDirty=!0});!a[e]&&a.optionalAxis!==e&&la(18,!0)})},updateParallelArrays:function(a,b){var c=a.series,d=arguments;o(c.parallelArrays,typeof b==="number"?function(d){var f=d==="y"&&c.toYData?c.toYData(a):a[d];c[d+"Data"][b]=f}:function(a){Array.prototype[b].apply(c[a+"Data"],Array.prototype.slice.call(d,2))})},autoIncrement:function(){var a=
this.options,b=this.xIncrement,c,d=a.pointIntervalUnit,b=p(b,a.pointStart,0);this.pointInterval=c=p(this.pointInterval,a.pointInterval,1);if(d==="month"||d==="year")a=new Aa(b),a=d==="month"?+a[wb](a[Ya]()+c):+a[xb](a[Za]()+c),c=a-b;this.xIncrement=b+c;return b},getSegments:function(){var a=-1,b=[],c,d=this.points,e=d.length;if(e)if(this.options.connectNulls){for(c=e;c--;)d[c].y===null&&d.splice(c,1);d.length&&(b=[d])}else o(d,function(c,g){c.y===null?(g>a+1&&b.push(d.slice(a+1,g)),a=g):g===e-1&&
b.push(d.slice(a+1,g+1))});this.segments=b},setOptions:function(a){var b=this.chart,c=b.options.plotOptions,b=b.userOptions||{},d=b.plotOptions||{},e=c[this.type];this.userOptions=a;c=z(e,c.series,a);this.tooltipOptions=z(T.tooltip,T.plotOptions[this.type].tooltip,b.tooltip,d.series&&d.series.tooltip,d[this.type]&&d[this.type].tooltip,a.tooltip);e.marker===null&&delete c.marker;this.zoneAxis=c.zoneAxis;a=this.zones=(c.zones||[]).slice();if((c.negativeColor||c.negativeFillColor)&&!c.zones)a.push({value:c[this.zoneAxis+
"Threshold"]||c.threshold||0,color:c.negativeColor,fillColor:c.negativeFillColor});a.length&&q(a[a.length-1].value)&&a.push({color:this.color,fillColor:this.fillColor});return c},getCyclic:function(a,b,c){var d=this.userOptions,e="_"+a+"Index",f=a+"Counter";b||(q(d[e])?b=d[e]:(d[e]=b=this.chart[f]%c.length,this.chart[f]+=1),b=c[b]);this[a]=b},getColor:function(){this.options.colorByPoint||this.getCyclic("color",this.options.color||ba[this.type].color,this.chart.options.colors)},getSymbol:function(){var a=
this.options.marker;this.getCyclic("symbol",a.symbol,this.chart.options.symbols);if(/^url/.test(this.symbol))a.radius=0},drawLegendSymbol:Na.drawLineMarker,setData:function(a,b,c,d){var e=this,f=e.points,g=f&&f.length||0,h,i=e.options,j=e.chart,k=null,l=e.xAxis,m=l&&!!l.categories,n=i.turboThreshold,v=this.xData,s=this.yData,q=(h=e.pointArrayMap)&&h.length,a=a||[];h=a.length;b=p(b,!0);if(d!==!1&&h&&g===h&&!e.cropped&&!e.hasGroupedData&&e.visible)o(a,function(a,b){f[b].update&&f[b].update(a,!1,null,
!1)});else{e.xIncrement=null;e.pointRange=m?1:i.pointRange;e.colorCounter=0;o(this.parallelArrays,function(a){e[a+"Data"].length=0});if(n&&h>n){for(c=0;k===null&&c<h;)k=a[c],c++;if(ra(k)){m=p(i.pointStart,0);i=p(i.pointInterval,1);for(c=0;c<h;c++)v[c]=m,s[c]=a[c],m+=i;e.xIncrement=m}else if(Ha(k))if(q)for(c=0;c<h;c++)i=a[c],v[c]=i[0],s[c]=i.slice(1,q+1);else for(c=0;c<h;c++)i=a[c],v[c]=i[0],s[c]=i[1];else la(12)}else for(c=0;c<h;c++)if(a[c]!==y&&(i={series:e},e.pointClass.prototype.applyOptions.apply(i,
[a[c]]),e.updateParallelArrays(i,c),m&&i.name))l.names[i.x]=i.name;Da(s[0])&&la(14,!0);e.data=[];e.options.data=a;for(c=g;c--;)f[c]&&f[c].destroy&&f[c].destroy();if(l)l.minRange=l.userMinRange;e.isDirty=e.isDirtyData=j.isDirtyBox=!0;c=!1}b&&j.redraw(c)},processData:function(a){var b=this.xData,c=this.yData,d=b.length,e;e=0;var f,g,h=this.xAxis,i,j=this.options;i=j.cropThreshold;var k=this.isCartesian,l,m;if(k&&!this.isDirty&&!h.isDirty&&!this.yAxis.isDirty&&!a)return!1;if(h)a=h.getExtremes(),l=a.min,
m=a.max;if(k&&this.sorted&&(!i||d>i||this.forceCrop))if(b[d-1]<l||b[0]>m)b=[],c=[];else if(b[0]<l||b[d-1]>m)e=this.cropData(this.xData,this.yData,l,m),b=e.xData,c=e.yData,e=e.start,f=!0;for(i=b.length-1;i>=0;i--)d=b[i]-b[i-1],d>0&&(g===y||d<g)?g=d:d<0&&this.requireSorting&&la(15);this.cropped=f;this.cropStart=e;this.processedXData=b;this.processedYData=c;if(j.pointRange===null)this.pointRange=g||1;this.closestPointRange=g},cropData:function(a,b,c,d){var e=a.length,f=0,g=e,h=p(this.cropShoulder,1),
i;for(i=0;i<e;i++)if(a[i]>=c){f=u(0,i-h);break}for(;i<e;i++)if(a[i]>d){g=i+h;break}return{xData:a.slice(f,g),yData:b.slice(f,g),start:f,end:g}},generatePoints:function(){var a=this.options.data,b=this.data,c,d=this.processedXData,e=this.processedYData,f=this.pointClass,g=d.length,h=this.cropStart||0,i,j=this.hasGroupedData,k,l=[],m;if(!b&&!j)b=[],b.length=a.length,b=this.data=b;for(m=0;m<g;m++)i=h+m,j?l[m]=(new f).init(this,[d[m]].concat(sa(e[m]))):(b[i]?k=b[i]:a[i]!==y&&(b[i]=k=(new f).init(this,
a[i],d[m])),l[m]=k),l[m].index=i;if(b&&(g!==(c=b.length)||j))for(m=0;m<c;m++)if(m===h&&!j&&(m+=g),b[m])b[m].destroyElements(),b[m].plotX=y;this.data=b;this.points=l},getExtremes:function(a){var b=this.yAxis,c=this.processedXData,d,e=[],f=0;d=this.xAxis.getExtremes();var g=d.min,h=d.max,i,j,k,l,a=a||this.stackedYData||this.processedYData;d=a.length;for(l=0;l<d;l++)if(j=c[l],k=a[l],i=k!==null&&k!==y&&(!b.isLog||k.length||k>0),j=this.getExtremesFromAll||this.options.getExtremesFromAll||this.cropped||
(c[l+1]||j)>=g&&(c[l-1]||j)<=h,i&&j)if(i=k.length)for(;i--;)k[i]!==null&&(e[f++]=k[i]);else e[f++]=k;this.dataMin=Pa(e);this.dataMax=Fa(e)},translate:function(){this.processedXData||this.processData();this.generatePoints();for(var a=this.options,b=a.stacking,c=this.xAxis,d=c.categories,e=this.yAxis,f=this.points,g=f.length,h=!!this.modifyValue,i=a.pointPlacement,j=i==="between"||ra(i),k=a.threshold,l=a.startFromThreshold?k:0,m,n,v,o=Number.MAX_VALUE,a=0;a<g;a++){var r=f[a],x=r.x,t=r.y;n=r.low;var w=
b&&e.stacks[(this.negStacks&&t<(l?0:k)?"-":"")+this.stackKey];if(e.isLog&&t!==null&&t<=0)r.y=t=null,la(10);r.plotX=m=C(u(-1E5,c.translate(x,0,0,0,1,i,this.type==="flags")),1E5);if(b&&this.visible&&w&&w[x])w=w[x],t=w.points[this.index+","+a],n=t[0],t=t[1],n===l&&(n=p(k,e.min)),e.isLog&&n<=0&&(n=null),r.total=r.stackTotal=w.total,r.percentage=w.total&&r.y/w.total*100,r.stackY=t,w.setOffset(this.pointXOffset||0,this.barW||0);r.yBottom=q(n)?e.translate(n,0,1,0,1):null;h&&(t=this.modifyValue(t,r));r.plotY=
n=typeof t==="number"&&t!==Infinity?C(u(-1E5,e.translate(t,0,1,0,1)),1E5):y;r.isInside=n!==y&&n>=0&&n<=e.len&&m>=0&&m<=c.len;r.clientX=j?c.translate(x,0,0,0,1):m;r.negative=r.y<(k||0);r.category=d&&d[r.x]!==y?d[r.x]:r.x;a&&(o=C(o,O(m-v)));v=m}this.closestPointRangePx=o;this.getSegments()},setClip:function(a){var b=this.chart,c=b.renderer,d=b.inverted,e=this.clipBox,f=e||b.clipBox,g=this.sharedClipKey||["_sharedClip",a&&a.duration,a&&a.easing,f.height].join(","),h=b[g],i=b[g+"m"];if(!h){if(a)f.width=
0,b[g+"m"]=i=c.clipRect(-99,d?-b.plotLeft:-b.plotTop,99,d?b.chartWidth:b.chartHeight);b[g]=h=c.clipRect(f)}a&&(h.count+=1);if(this.options.clip!==!1)this.group.clip(a||e?h:b.clipRect),this.markerGroup.clip(i),this.sharedClipKey=g;a||(h.count-=1,h.count<=0&&g&&b[g]&&(e||(b[g]=b[g].destroy()),b[g+"m"]&&(b[g+"m"]=b[g+"m"].destroy())))},animate:function(a){var b=this.chart,c=this.options.animation,d;if(c&&!da(c))c=ba[this.type].animation;a?this.setClip(c):(d=this.sharedClipKey,(a=b[d])&&a.animate({width:b.plotSizeX},
c),b[d+"m"]&&b[d+"m"].animate({width:b.plotSizeX+99},c),this.animate=null)},afterAnimate:function(){this.setClip();I(this,"afterAnimate")},drawPoints:function(){var a,b=this.points,c=this.chart,d,e,f,g,h,i,j,k,l=this.options.marker,m=this.pointAttr[""],n,v,o,r=this.markerGroup,q=p(l.enabled,this.xAxis.isRadial,this.closestPointRangePx>2*l.radius);if(l.enabled!==!1||this._hasPointMarkers)for(f=b.length;f--;)if(g=b[f],d=V(g.plotX),e=g.plotY,k=g.graphic,n=g.marker||{},v=!!g.marker,a=q&&n.enabled===y||
n.enabled,o=g.isInside,a&&e!==y&&!isNaN(e)&&g.y!==null)if(a=g.pointAttr[g.selected?"select":""]||m,h=a.r,i=p(n.symbol,this.symbol),j=i.indexOf("url")===0,k)k[o?"show":"hide"](!0).animate(x({x:d-h,y:e-h},k.symbolName?{width:2*h,height:2*h}:{}));else{if(o&&(h>0||j))g.graphic=c.renderer.symbol(i,d-h,e-h,2*h,2*h,v?n:l).attr(a).add(r)}else if(k)g.graphic=k.destroy()},convertAttribs:function(a,b,c,d){var e=this.pointAttrToOptions,f,g,h={},a=a||{},b=b||{},c=c||{},d=d||{};for(f in e)g=e[f],h[f]=p(a[g],b[f],
c[f],d[f]);return h},getAttribs:function(){var a=this,b=a.options,c=ba[a.type].marker?b.marker:b,d=c.states,e=d.hover,f,g=a.color,h=a.options.negativeColor;f={stroke:g,fill:g};var i=a.points||[],j,k=[],l,m=a.pointAttrToOptions;l=a.hasPointSpecificOptions;var n=c.lineColor,p=c.fillColor;j=b.turboThreshold;var s=a.zones,r=a.zoneAxis||"y",u;b.marker?(e.radius=e.radius||c.radius+e.radiusPlus,e.lineWidth=e.lineWidth||c.lineWidth+e.lineWidthPlus):(e.color=e.color||oa(e.color||g).brighten(e.brightness).get(),
e.negativeColor=e.negativeColor||oa(e.negativeColor||h).brighten(e.brightness).get());k[""]=a.convertAttribs(c,f);o(["hover","select"],function(b){k[b]=a.convertAttribs(d[b],k[""])});a.pointAttr=k;g=i.length;if(!j||g<j||l)for(;g--;){j=i[g];if((c=j.options&&j.options.marker||j.options)&&c.enabled===!1)c.radius=0;if(s.length){l=0;for(f=s[l];j[r]>=f.value;)f=s[++l];j.color=j.fillColor=f.color}l=b.colorByPoint||j.color;if(j.options)for(u in m)q(c[m[u]])&&(l=!0);if(l){c=c||{};l=[];d=c.states||{};f=d.hover=
d.hover||{};if(!b.marker)f.color=f.color||!j.options.color&&e[j.negative&&h?"negativeColor":"color"]||oa(j.color).brighten(f.brightness||e.brightness).get();f={color:j.color};if(!p)f.fillColor=j.color;if(!n)f.lineColor=j.color;c.hasOwnProperty("color")&&!c.color&&delete c.color;l[""]=a.convertAttribs(x(f,c),k[""]);l.hover=a.convertAttribs(d.hover,k.hover,l[""]);l.select=a.convertAttribs(d.select,k.select,l[""])}else l=k;j.pointAttr=l}},destroy:function(){var a=this,b=a.chart,c=/AppleWebKit\/533/.test(Ba),
d,e=a.data||[],f,g,h;I(a,"destroy");Z(a);o(a.axisTypes||[],function(b){if(h=a[b])ja(h.series,a),h.isDirty=h.forceRedraw=!0});a.legendItem&&a.chart.legend.destroyItem(a);for(d=e.length;d--;)(f=e[d])&&f.destroy&&f.destroy();a.points=null;clearTimeout(a.animationTimeout);for(g in a)a[g]instanceof Q&&!a[g].survive&&(d=c&&g==="group"?"hide":"destroy",a[g][d]());if(b.hoverSeries===a)b.hoverSeries=null;ja(b.series,a);for(g in a)delete a[g]},getSegmentPath:function(a){var b=this,c=[],d=b.options.step;o(a,
function(e,f){var g=e.plotX,h=e.plotY,i;b.getPointSpline?c.push.apply(c,b.getPointSpline(a,e,f)):(c.push(f?"L":"M"),d&&f&&(i=a[f-1],d==="right"?c.push(i.plotX,h):d==="center"?c.push((i.plotX+g)/2,i.plotY,(i.plotX+g)/2,h):c.push(g,i.plotY)),c.push(e.plotX,e.plotY))});return c},getGraphPath:function(){var a=this,b=[],c,d=[];o(a.segments,function(e){c=a.getSegmentPath(e);e.length>1?b=b.concat(c):d.push(e[0])});a.singlePoints=d;return a.graphPath=b},drawGraph:function(){var a=this,b=this.options,c=[["graph",
b.lineColor||this.color,b.dashStyle]],d=b.lineWidth,e=b.linecap!=="square",f=this.getGraphPath(),g=this.fillGraph&&this.color||P;o(this.zones,function(d,e){c.push(["zoneGraph"+e,d.color||a.color,d.dashStyle||b.dashStyle])});o(c,function(c,i){var j=c[0],k=a[j];if(k)db(k),k.animate({d:f});else if((d||g)&&f.length)k={stroke:c[1],"stroke-width":d,fill:g,zIndex:1},c[2]?k.dashstyle=c[2]:e&&(k["stroke-linecap"]=k["stroke-linejoin"]="round"),a[j]=a.chart.renderer.path(f).attr(k).add(a.group).shadow(i<2&&
b.shadow)})},applyZones:function(){var a=this,b=this.chart,c=b.renderer,d=this.zones,e,f,g=this.clips||[],h,i=this.graph,j=this.area,k=u(b.chartWidth,b.chartHeight),l=this[(this.zoneAxis||"y")+"Axis"],m,n=l.reversed,v=b.inverted,s=l.horiz,q,x,t,w=!1;if(d.length&&(i||j))i&&i.hide(),j&&j.hide(),m=l.getExtremes(),o(d,function(d,o){e=n?s?b.plotWidth:0:s?0:l.toPixels(m.min);e=C(u(p(f,e),0),k);f=C(u(r(l.toPixels(p(d.value,m.max),!0)),0),k);w&&(e=f=l.toPixels(m.max));q=Math.abs(e-f);x=C(e,f);t=u(e,f);if(l.isXAxis){if(h=
{x:v?t:x,y:0,width:q,height:k},!s)h.x=b.plotHeight-h.x}else if(h={x:0,y:v?t:x,width:k,height:q},s)h.y=b.plotWidth-h.y;b.inverted&&c.isVML&&(h=l.isXAxis?{x:0,y:n?x:t,height:h.width,width:b.chartWidth}:{x:h.y-b.plotLeft-b.spacingBox.x,y:0,width:h.height,height:b.chartHeight});g[o]?g[o].animate(h):(g[o]=c.clipRect(h),i&&a["zoneGraph"+o].clip(g[o]),j&&a["zoneArea"+o].clip(g[o]));w=d.value>m.max}),this.clips=g},invertGroups:function(){function a(){var a={width:b.yAxis.len,height:b.xAxis.len};o(["group",
"markerGroup"],function(c){b[c]&&b[c].attr(a).invert()})}var b=this,c=b.chart;if(b.xAxis)H(c,"resize",a),H(b,"destroy",function(){Z(c,"resize",a)}),a(),b.invertGroups=a},plotGroup:function(a,b,c,d,e){var f=this[a],g=!f;g&&(this[a]=f=this.chart.renderer.g(b).attr({visibility:c,zIndex:d||0.1}).add(e));f[g?"attr":"animate"](this.getPlotBox());return f},getPlotBox:function(){var a=this.chart,b=this.xAxis,c=this.yAxis;if(a.inverted)b=c,c=this.xAxis;return{translateX:b?b.left:a.plotLeft,translateY:c?c.top:
a.plotTop,scaleX:1,scaleY:1}},render:function(){var a=this,b=a.chart,c,d=a.options,e=(c=d.animation)&&!!a.animate&&b.renderer.isSVG&&p(c.duration,500)||0,f=a.visible?"visible":"hidden",g=d.zIndex,h=a.hasRendered,i=b.seriesGroup;c=a.plotGroup("group","series",f,g,i);a.markerGroup=a.plotGroup("markerGroup","markers",f,g,i);e&&a.animate(!0);a.getAttribs();c.inverted=a.isCartesian?b.inverted:!1;a.drawGraph&&(a.drawGraph(),a.applyZones());o(a.points,function(a){a.redraw&&a.redraw()});a.drawDataLabels&&
a.drawDataLabels();a.visible&&a.drawPoints();a.drawTracker&&a.options.enableMouseTracking!==!1&&a.drawTracker();b.inverted&&a.invertGroups();d.clip!==!1&&!a.sharedClipKey&&!h&&c.clip(b.clipRect);e&&a.animate();if(!h)e?a.animationTimeout=setTimeout(function(){a.afterAnimate()},e):a.afterAnimate();a.isDirty=a.isDirtyData=!1;a.hasRendered=!0},redraw:function(){var a=this.chart,b=this.isDirtyData,c=this.isDirty,d=this.group,e=this.xAxis,f=this.yAxis;d&&(a.inverted&&d.attr({width:a.plotWidth,height:a.plotHeight}),
d.animate({translateX:p(e&&e.left,a.plotLeft),translateY:p(f&&f.top,a.plotTop)}));this.translate();this.render();b&&I(this,"updatedData");(c||b)&&delete this.kdTree},kdDimensions:1,kdAxisArray:["clientX","plotY"],searchPoint:function(a,b){var c=this.xAxis,d=this.yAxis,e=this.chart.inverted;return this.searchKDTree({clientX:e?c.len-a.chartY+c.pos:a.chartX-c.pos,plotY:e?d.len-a.chartX+d.pos:a.chartY-d.pos},b)},buildKDTree:function(){function a(b,d,g){var h,i;if(i=b&&b.length)return h=c.kdAxisArray[d%
g],b.sort(function(a,b){return a[h]-b[h]}),i=Math.floor(i/2),{point:b[i],left:a(b.slice(0,i),d+1,g),right:a(b.slice(i+1),d+1,g)}}function b(){var b=lb(c.points,function(a){return a.y!==null});c.kdTree=a(b,d,d)}var c=this,d=c.kdDimensions;delete c.kdTree;c.options.kdSync?b():setTimeout(b)},searchKDTree:function(a,b){function c(a,b,j,k){var l=b.point,m=d.kdAxisArray[j%k],n,p,o=l;p=q(a[e])&&q(l[e])?Math.pow(a[e]-l[e],2):null;n=q(a[f])&&q(l[f])?Math.pow(a[f]-l[f],2):null;n=(p||0)+(n||0);l.dist=q(n)?Math.sqrt(n):
Number.MAX_VALUE;l.distX=q(p)?Math.sqrt(p):Number.MAX_VALUE;m=a[m]-l[m];n=m<0?"left":"right";p=m<0?"right":"left";b[n]&&(n=c(a,b[n],j+1,k),o=n[g]<o[g]?n:l);b[p]&&Math.sqrt(m*m)<o[g]&&(a=c(a,b[p],j+1,k),o=a[g]<o[g]?a:o);return o}var d=this,e=this.kdAxisArray[0],f=this.kdAxisArray[1],g=b?"distX":"dist";this.kdTree||this.buildKDTree();if(this.kdTree)return c(a,this.kdTree,this.kdDimensions,this.kdDimensions)}};Ib.prototype={destroy:function(){Qa(this,this.axis)},render:function(a){var b=this.options,
c=b.format,c=c?Ja(c,this):b.formatter.call(this);this.label?this.label.attr({text:c,visibility:"hidden"}):this.label=this.axis.chart.renderer.text(c,null,null,b.useHTML).css(b.style).attr({align:this.textAlign,rotation:b.rotation,visibility:"hidden"}).add(a)},setOffset:function(a,b){var c=this.axis,d=c.chart,e=d.inverted,f=c.reversed,f=this.isNegative&&!f||!this.isNegative&&f,g=c.translate(c.usePercentage?100:this.total,0,0,0,1),c=c.translate(0),c=O(g-c),h=d.xAxis[0].translate(this.x)+a,i=d.plotHeight,
f={x:e?f?g:g-c:h,y:e?i-h-b:f?i-g-c:i-g,width:e?c:b,height:e?b:c};if(e=this.label)e.align(this.alignOptions,null,f),f=e.alignAttr,e[this.options.crop===!1||d.isInsidePlot(f.x,f.y)?"show":"hide"](!0)}};va.prototype.buildStacks=function(){var a=this.series,b=p(this.options.reversedStacks,!0),c=a.length;if(!this.isXAxis){for(this.usePercentage=!1;c--;)a[b?c:a.length-c-1].setStackedPoints();if(this.usePercentage)for(c=0;c<a.length;c++)a[c].setPercentStacks()}};va.prototype.renderStackTotals=function(){var a=
this.chart,b=a.renderer,c=this.stacks,d,e,f=this.stackTotalGroup;if(!f)this.stackTotalGroup=f=b.g("stack-labels").attr({visibility:"visible",zIndex:6}).add();f.translate(a.plotLeft,a.plotTop);for(d in c)for(e in a=c[d],a)a[e].render(f)};R.prototype.setStackedPoints=function(){if(this.options.stacking&&!(this.visible!==!0&&this.chart.options.chart.ignoreHiddenSeries!==!1)){var a=this.processedXData,b=this.processedYData,c=[],d=b.length,e=this.options,f=e.threshold,g=e.startFromThreshold?f:0,h=e.stack,
e=e.stacking,i=this.stackKey,j="-"+i,k=this.negStacks,l=this.yAxis,m=l.stacks,n=l.oldStacks,o,s,q,r,t,w;for(r=0;r<d;r++){t=a[r];w=b[r];q=this.index+","+r;s=(o=k&&w<(g?0:f))?j:i;m[s]||(m[s]={});if(!m[s][t])n[s]&&n[s][t]?(m[s][t]=n[s][t],m[s][t].total=null):m[s][t]=new Ib(l,l.options.stackLabels,o,t,h);s=m[s][t];s.points[q]=[p(s.cum,g)];e==="percent"?(o=o?i:j,k&&m[o]&&m[o][t]?(o=m[o][t],s.total=o.total=u(o.total,s.total)+O(w)||0):s.total=ea(s.total+(O(w)||0))):s.total=ea(s.total+(w||0));s.cum=p(s.cum,
g)+(w||0);s.points[q].push(s.cum);c[r]=s.cum}if(e==="percent")l.usePercentage=!0;this.stackedYData=c;l.oldStacks={}}};R.prototype.setPercentStacks=function(){var a=this,b=a.stackKey,c=a.yAxis.stacks,d=a.processedXData;o([b,"-"+b],function(b){var e;for(var f=d.length,g,h;f--;)if(g=d[f],e=(h=c[b]&&c[b][g])&&h.points[a.index+","+f],g=e)h=h.total?100/h.total:0,g[0]=ea(g[0]*h),g[1]=ea(g[1]*h),a.stackedYData[f]=g[1]})};x(F.prototype,{addSeries:function(a,b,c){var d,e=this;a&&(b=p(b,!0),I(e,"addSeries",
{options:a},function(){d=e.initSeries(a);e.isDirtyLegend=!0;e.linkSeries();b&&e.redraw(c)}));return d},addAxis:function(a,b,c,d){var e=b?"xAxis":"yAxis",f=this.options;new va(this,z(a,{index:this[e].length,isX:b}));f[e]=sa(f[e]||{});f[e].push(a);p(c,!0)&&this.redraw(d)},showLoading:function(a){var b=this,c=b.options,d=b.loadingDiv,e=c.loading,f=function(){d&&L(d,{left:b.plotLeft+"px",top:b.plotTop+"px",width:b.plotWidth+"px",height:b.plotHeight+"px"})};if(!d)b.loadingDiv=d=$(Ka,{className:"highcharts-loading"},
x(e.style,{zIndex:10,display:P}),b.container),b.loadingSpan=$("span",null,e.labelStyle,d),H(b,"redraw",f);b.loadingSpan.innerHTML=a||c.lang.loading;if(!b.loadingShown)L(d,{opacity:0,display:""}),mb(d,{opacity:e.style.opacity},{duration:e.showDuration||0}),b.loadingShown=!0;f()},hideLoading:function(){var a=this.options,b=this.loadingDiv;b&&mb(b,{opacity:0},{duration:a.loading.hideDuration||100,complete:function(){L(b,{display:P})}});this.loadingShown=!1}});x(Ga.prototype,{update:function(a,b,c,d){function e(){f.applyOptions(a);
if(f.y===null&&h)f.graphic=h.destroy();if(da(a)&&!Ha(a))f.redraw=function(){if(h)if(a&&a.marker&&a.marker.symbol)f.graphic=h.destroy();else h.attr(f.pointAttr[f.state||""])[f.visible===!1?"hide":"show"]();if(a&&a.dataLabels&&f.dataLabel)f.dataLabel=f.dataLabel.destroy();f.redraw=null};i=f.index;g.updateParallelArrays(f,i);if(l&&f.name)l[f.x]=f.name;k.data[i]=f.options;g.isDirty=g.isDirtyData=!0;if(!g.fixedBox&&g.hasCartesianSeries)j.isDirtyBox=!0;if(k.legendType==="point")j.isDirtyLegend=!0;b&&j.redraw(c)}
var f=this,g=f.series,h=f.graphic,i,j=g.chart,k=g.options,l=g.xAxis&&g.xAxis.names,b=p(b,!0);d===!1?e():f.firePointEvent("update",{options:a},e)},remove:function(a,b){this.series.removePoint(Ma(this,this.series.data),a,b)}});x(R.prototype,{addPoint:function(a,b,c,d){var e=this,f=e.options,g=e.data,h=e.graph,i=e.area,j=e.chart,k=e.xAxis&&e.xAxis.names,l=h&&h.shift||0,m=["graph","area"],h=f.data,n,v=e.xData;Sa(d,j);if(c){for(d=e.zones.length;d--;)m.push("zoneGraph"+d,"zoneArea"+d);o(m,function(a){if(e[a])e[a].shift=
l+1})}if(i)i.isArea=!0;b=p(b,!0);i={series:e};e.pointClass.prototype.applyOptions.apply(i,[a]);m=i.x;d=v.length;if(e.requireSorting&&m<v[d-1])for(n=!0;d&&v[d-1]>m;)d--;e.updateParallelArrays(i,"splice",d,0,0);e.updateParallelArrays(i,d);if(k&&i.name)k[m]=i.name;h.splice(d,0,a);n&&(e.data.splice(d,0,null),e.processData());f.legendType==="point"&&e.generatePoints();c&&(g[0]&&g[0].remove?g[0].remove(!1):(g.shift(),e.updateParallelArrays(i,"shift"),h.shift()));e.isDirty=!0;e.isDirtyData=!0;b&&(e.getAttribs(),
j.redraw())},removePoint:function(a,b,c){var d=this,e=d.data,f=e[a],g=d.points,h=d.chart,i=function(){e.length===g.length&&g.splice(a,1);e.splice(a,1);d.options.data.splice(a,1);d.updateParallelArrays(f||{series:d},"splice",a,1);f&&f.destroy();d.isDirty=!0;d.isDirtyData=!0;b&&h.redraw()};Sa(c,h);b=p(b,!0);f?f.firePointEvent("remove",null,i):i()},remove:function(a,b){var c=this,d=c.chart,a=p(a,!0);if(!c.isRemoving)c.isRemoving=!0,I(c,"remove",null,function(){c.destroy();d.isDirtyLegend=d.isDirtyBox=
!0;d.linkSeries();a&&d.redraw(b)});c.isRemoving=!1},update:function(a,b){var c=this,d=this.chart,e=this.userOptions,f=this.type,g=M[f].prototype,h=["group","markerGroup","dataLabelsGroup"],i;if(a.type&&a.type!==f||a.zIndex!==void 0)h.length=0;o(h,function(a){h[a]=c[a];delete c[a]});a=z(e,{animation:!1,index:this.index,pointStart:this.xData[0]},{data:this.options.data},a);this.remove(!1);for(i in g)this[i]=y;x(this,M[a.type||f].prototype);o(h,function(a){c[a]=h[a]});this.init(d,a);d.linkSeries();p(b,
!0)&&d.redraw(!1)}});x(va.prototype,{update:function(a,b){var c=this.chart,a=c.options[this.coll][this.options.index]=z(this.userOptions,a);this.destroy(!0);this._addedPlotLB=this.chart._labelPanes=y;this.init(c,x(a,{events:y}));c.isDirtyBox=!0;p(b,!0)&&c.redraw()},remove:function(a){for(var b=this.chart,c=this.coll,d=this.series,e=d.length;e--;)d[e]&&d[e].remove(!1);ja(b.axes,this);ja(b[c],this);b.options[c].splice(this.options.index,1);o(b[c],function(a,b){a.options.index=b});this.destroy();b.isDirtyBox=
!0;p(a,!0)&&b.redraw()},setTitle:function(a,b){this.update({title:a},b)},setCategories:function(a,b){this.update({categories:a},b)}});var xa=ka(R);M.line=xa;ba.area=z(U,{threshold:0});var qa=ka(R,{type:"area",getSegments:function(){var a=this,b=[],c=[],d=[],e=this.xAxis,f=this.yAxis,g=f.stacks[this.stackKey],h={},i,j,k=this.points,l=this.options.connectNulls,m,n;if(this.options.stacking&&!this.cropped){for(m=0;m<k.length;m++)h[k[m].x]=k[m];for(n in g)g[n].total!==null&&d.push(+n);d.sort(function(a,
b){return a-b});o(d,function(b){var d=0,k;if(!l||h[b]&&h[b].y!==null)if(h[b])c.push(h[b]);else{for(m=a.index;m<=f.series.length;m++)if(k=g[b].points[m+","+b]){d=k[1];break}i=e.translate(b);j=f.toPixels(d,!0);c.push({y:null,plotX:i,clientX:i,plotY:j,yBottom:j,onMouseOver:na})}});c.length&&b.push(c)}else R.prototype.getSegments.call(this),b=this.segments;this.segments=b},getSegmentPath:function(a){var b=R.prototype.getSegmentPath.call(this,a),c=[].concat(b),d,e=this.options;d=b.length;var f=this.yAxis.getThreshold(e.threshold),
g;d===3&&c.push("L",b[1],b[2]);if(e.stacking&&!this.closedStacks)for(d=a.length-1;d>=0;d--)g=p(a[d].yBottom,f),d<a.length-1&&e.step&&c.push(a[d+1].plotX,g),c.push(a[d].plotX,g);else this.closeSegment(c,a,f);this.areaPath=this.areaPath.concat(c);return b},closeSegment:function(a,b,c){a.push("L",b[b.length-1].plotX,c,"L",b[0].plotX,c)},drawGraph:function(){this.areaPath=[];R.prototype.drawGraph.apply(this);var a=this,b=this.areaPath,c=this.options,d=[["area",this.color,c.fillColor]];o(this.zones,function(b,
f){d.push(["zoneArea"+f,b.color||a.color,b.fillColor||c.fillColor])});o(d,function(d){var f=d[0],g=a[f];g?g.animate({d:b}):a[f]=a.chart.renderer.path(b).attr({fill:p(d[2],oa(d[1]).setOpacity(p(c.fillOpacity,0.75)).get()),zIndex:0}).add(a.group)})},drawLegendSymbol:Na.drawRectangle});M.area=qa;ba.spline=z(U);xa=ka(R,{type:"spline",getPointSpline:function(a,b,c){var d=b.plotX,e=b.plotY,f=a[c-1],g=a[c+1],h,i,j,k;if(f&&g){a=f.plotY;j=g.plotX;var g=g.plotY,l;h=(1.5*d+f.plotX)/2.5;i=(1.5*e+a)/2.5;j=(1.5*
d+j)/2.5;k=(1.5*e+g)/2.5;l=(k-i)*(j-d)/(j-h)+e-k;i+=l;k+=l;i>a&&i>e?(i=u(a,e),k=2*e-i):i<a&&i<e&&(i=C(a,e),k=2*e-i);k>g&&k>e?(k=u(g,e),i=2*e-k):k<g&&k<e&&(k=C(g,e),i=2*e-k);b.rightContX=j;b.rightContY=k}c?(b=["C",f.rightContX||f.plotX,f.rightContY||f.plotY,h||d,i||e,d,e],f.rightContX=f.rightContY=null):b=["M",d,e];return b}});M.spline=xa;ba.areaspline=z(ba.area);qa=qa.prototype;xa=ka(xa,{type:"areaspline",closedStacks:!0,getSegmentPath:qa.getSegmentPath,closeSegment:qa.closeSegment,drawGraph:qa.drawGraph,
drawLegendSymbol:Na.drawRectangle});M.areaspline=xa;ba.column=z(U,{borderColor:"#FFFFFF",borderRadius:0,groupPadding:0.2,marker:null,pointPadding:0.1,minPointLength:0,cropThreshold:50,pointRange:null,states:{hover:{brightness:0.1,shadow:!1,halo:!1},select:{color:"#C0C0C0",borderColor:"#000000",shadow:!1}},dataLabels:{align:null,verticalAlign:null,y:null},startFromThreshold:!0,stickyTracking:!1,tooltip:{distance:6},threshold:0});xa=ka(R,{type:"column",pointAttrToOptions:{stroke:"borderColor",fill:"color",
r:"borderRadius"},cropShoulder:0,directTouch:!0,trackerGroups:["group","dataLabelsGroup"],negStacks:!0,init:function(){R.prototype.init.apply(this,arguments);var a=this,b=a.chart;b.hasRendered&&o(b.series,function(b){if(b.type===a.type)b.isDirty=!0})},getColumnMetrics:function(){var a=this,b=a.options,c=a.xAxis,d=a.yAxis,e=c.reversed,f,g={},h,i=0;b.grouping===!1?i=1:o(a.chart.series,function(b){var c=b.options,e=b.yAxis;if(b.type===a.type&&b.visible&&d.len===e.len&&d.pos===e.pos)c.stacking?(f=b.stackKey,
g[f]===y&&(g[f]=i++),h=g[f]):c.grouping!==!1&&(h=i++),b.columnIndex=h});var c=C(O(c.transA)*(c.ordinalSlope||b.pointRange||c.closestPointRange||c.tickInterval||1),c.len),j=c*b.groupPadding,k=(c-2*j)/i,l=b.pointWidth,b=q(l)?(k-l)/2:k*b.pointPadding,l=p(l,k-2*b);return a.columnMetrics={width:l,offset:b+(j+((e?i-(a.columnIndex||0):a.columnIndex)||0)*k-c/2)*(e?-1:1)}},translate:function(){var a=this,b=a.chart,c=a.options,d=a.borderWidth=p(c.borderWidth,a.closestPointRange*a.xAxis.transA<2?0:1),e=a.yAxis,
f=a.translatedThreshold=e.getThreshold(c.threshold),g=p(c.minPointLength,5),h=a.getColumnMetrics(),i=h.width,j=a.barW=u(i,1+2*d),k=a.pointXOffset=h.offset,l=-(d%2?0.5:0),m=d%2?0.5:1;b.inverted&&(f-=0.5,b.renderer.isVML&&(m+=1));c.pointPadding&&(j=ta(j));R.prototype.translate.apply(a);o(a.points,function(c){var d=p(c.yBottom,f),h=999+O(d),h=C(u(-h,c.plotY),e.len+h),o=c.plotX+k,q=j,t=C(h,d),w,x;w=u(h,d)-t;O(w)<g&&g&&(w=g,x=!e.reversed&&!c.negative||e.reversed&&c.negative,t=r(O(t-f)>g?d-g:f-(x?g:0)));
c.barX=o;c.pointWidth=i;q=r(o+q)+l;o=r(o)+l;q-=o;d=O(t)<0.5;w=C(r(t+w)+m,9E4);t=r(t)+m;w-=t;d&&(t-=1,w+=1);c.tooltipPos=b.inverted?[e.len+e.pos-b.plotLeft-h,a.xAxis.len-o-q/2,w]:[o+q/2,h+e.pos-b.plotTop,w];c.shapeType="rect";c.shapeArgs={x:o,y:t,width:q,height:w}})},getSymbol:na,drawLegendSymbol:Na.drawRectangle,drawGraph:na,drawPoints:function(){var a=this,b=this.chart,c=a.options,d=b.renderer,e=c.animationLimit||250,f,g;o(a.points,function(h){var i=h.plotY,j=h.graphic;if(i!==y&&!isNaN(i)&&h.y!==
null)f=h.shapeArgs,i=q(a.borderWidth)?{"stroke-width":a.borderWidth}:{},g=h.pointAttr[h.selected?"select":""]||a.pointAttr[""],j?(db(j),j.attr(i)[b.pointCount<e?"animate":"attr"](z(f))):h.graphic=d[h.shapeType](f).attr(i).attr(g).add(a.group).shadow(c.shadow,null,c.stacking&&!c.borderRadius);else if(j)h.graphic=j.destroy()})},animate:function(a){var b=this.yAxis,c=this.options,d=this.chart.inverted,e={};if(ca)a?(e.scaleY=0.001,a=C(b.pos+b.len,u(b.pos,b.toPixels(c.threshold))),d?e.translateX=a-b.len:
e.translateY=a,this.group.attr(e)):(e.scaleY=1,e[d?"translateX":"translateY"]=b.pos,this.group.animate(e,this.options.animation),this.animate=null)},remove:function(){var a=this,b=a.chart;b.hasRendered&&o(b.series,function(b){if(b.type===a.type)b.isDirty=!0});R.prototype.remove.apply(a,arguments)}});M.column=xa;ba.bar=z(ba.column);qa=ka(xa,{type:"bar",inverted:!0});M.bar=qa;ba.scatter=z(U,{lineWidth:0,marker:{enabled:!0},tooltip:{headerFormat:'<span style="color:{series.color}">\u25CF</span> <span style="font-size: 10px;"> {series.name}</span><br/>',
pointFormat:"x: <b>{point.x}</b><br/>y: <b>{point.y}</b><br/>"}});qa=ka(R,{type:"scatter",sorted:!1,requireSorting:!1,noSharedTooltip:!0,trackerGroups:["group","markerGroup","dataLabelsGroup"],takeOrdinalPosition:!1,kdDimensions:2,drawGraph:function(){this.options.lineWidth&&R.prototype.drawGraph.call(this)}});M.scatter=qa;ba.pie=z(U,{borderColor:"#FFFFFF",borderWidth:1,center:[null,null],clip:!1,colorByPoint:!0,dataLabels:{distance:30,enabled:!0,formatter:function(){return this.point.name},x:0},
ignoreHiddenPoint:!0,legendType:"point",marker:null,size:null,showInLegend:!1,slicedOffset:10,states:{hover:{brightness:0.1,shadow:!1}},stickyTracking:!1,tooltip:{followPointer:!0}});U={type:"pie",isCartesian:!1,pointClass:ka(Ga,{init:function(){Ga.prototype.init.apply(this,arguments);var a=this,b;x(a,{visible:a.visible!==!1,name:p(a.name,"Slice")});b=function(b){a.slice(b.type==="select")};H(a,"select",b);H(a,"unselect",b);return a},setVisible:function(a,b){var c=this,d=c.series,e=d.chart,f=d.options.ignoreHiddenPoint,
b=p(b,f);if(a!==c.visible){c.visible=c.options.visible=a=a===y?!c.visible:a;d.options.data[Ma(c,d.data)]=c.options;o(["graphic","dataLabel","connector","shadowGroup"],function(b){if(c[b])c[b][a?"show":"hide"](!0)});c.legendItem&&e.legend.colorizeItem(c,a);!a&&c.state==="hover"&&c.setState("");if(f)d.isDirty=!0;b&&e.redraw()}},slice:function(a,b,c){var d=this.series;Sa(c,d.chart);p(b,!0);this.sliced=this.options.sliced=a=q(a)?a:!this.sliced;d.options.data[Ma(this,d.data)]=this.options;a=a?this.slicedTranslation:
{translateX:0,translateY:0};this.graphic.animate(a);this.shadowGroup&&this.shadowGroup.animate(a)},haloPath:function(a){var b=this.shapeArgs,c=this.series.chart;return this.sliced||!this.visible?[]:this.series.chart.renderer.symbols.arc(c.plotLeft+b.x,c.plotTop+b.y,b.r+a,b.r+a,{innerR:this.shapeArgs.r,start:b.start,end:b.end})}}),requireSorting:!1,directTouch:!0,noSharedTooltip:!0,trackerGroups:["group","dataLabelsGroup"],axisTypes:[],pointAttrToOptions:{stroke:"borderColor","stroke-width":"borderWidth",
fill:"color"},getColor:na,animate:function(a){var b=this,c=b.points,d=b.startAngleRad;if(!a)o(c,function(a){var c=a.graphic,g=a.shapeArgs;c&&(c.attr({r:a.startR||b.center[3]/2,start:d,end:d}),c.animate({r:g.r,start:g.start,end:g.end},b.options.animation))}),b.animate=null},setData:function(a,b,c,d){R.prototype.setData.call(this,a,!1,c,d);this.processData();this.generatePoints();p(b,!0)&&this.chart.redraw(c)},updateTotals:function(){var a,b=0,c=this.points,d=c.length,e,f=this.options.ignoreHiddenPoint;
for(a=0;a<d;a++)e=c[a],b+=f&&!e.visible?0:e.y;this.total=b;for(a=0;a<d;a++)e=c[a],e.percentage=b>0&&(e.visible||!f)?e.y/b*100:0,e.total=b},generatePoints:function(){R.prototype.generatePoints.call(this);this.updateTotals()},translate:function(a){this.generatePoints();var b=0,c=this.options,d=c.slicedOffset,e=d+c.borderWidth,f,g,h,i=c.startAngle||0,j=this.startAngleRad=ma/180*(i-90),i=(this.endAngleRad=ma/180*(p(c.endAngle,i+360)-90))-j,k=this.points,l=c.dataLabels.distance,c=c.ignoreHiddenPoint,m,
n=k.length,o;if(!a)this.center=a=this.getCenter();this.getX=function(b,c){h=W.asin(C((b-a[1])/(a[2]/2+l),1));return a[0]+(c?-1:1)*X(h)*(a[2]/2+l)};for(m=0;m<n;m++){o=k[m];f=j+b*i;if(!c||o.visible)b+=o.percentage/100;g=j+b*i;o.shapeType="arc";o.shapeArgs={x:a[0],y:a[1],r:a[2]/2,innerR:a[3]/2,start:r(f*1E3)/1E3,end:r(g*1E3)/1E3};h=(g+f)/2;h>1.5*ma?h-=2*ma:h<-ma/2&&(h+=2*ma);o.slicedTranslation={translateX:r(X(h)*d),translateY:r(aa(h)*d)};f=X(h)*a[2]/2;g=aa(h)*a[2]/2;o.tooltipPos=[a[0]+f*0.7,a[1]+g*
0.7];o.half=h<-ma/2||h>ma/2?1:0;o.angle=h;e=C(e,l/2);o.labelPos=[a[0]+f+X(h)*l,a[1]+g+aa(h)*l,a[0]+f+X(h)*e,a[1]+g+aa(h)*e,a[0]+f,a[1]+g,l<0?"center":o.half?"right":"left",h]}},drawGraph:null,drawPoints:function(){var a=this,b=a.chart.renderer,c,d,e=a.options.shadow,f,g,h;if(e&&!a.shadowGroup)a.shadowGroup=b.g("shadow").add(a.group);o(a.points,function(i){d=i.graphic;g=i.shapeArgs;f=i.shadowGroup;if(e&&!f)f=i.shadowGroup=b.g("shadow").add(a.shadowGroup);c=i.sliced?i.slicedTranslation:{translateX:0,
translateY:0};f&&f.attr(c);if(d)d.animate(x(g,c));else{h={"stroke-linejoin":"round"};if(!i.visible)h.visibility="hidden";i.graphic=d=b[i.shapeType](g).setRadialReference(a.center).attr(i.pointAttr[i.selected?"select":""]).attr(h).attr(c).add(a.group).shadow(e,f)}})},searchPoint:na,sortByAngle:function(a,b){a.sort(function(a,d){return a.angle!==void 0&&(d.angle-a.angle)*b})},drawLegendSymbol:Na.drawRectangle,getCenter:Yb.getCenter,getSymbol:na};U=ka(R,U);M.pie=U;R.prototype.drawDataLabels=function(){var a=
this,b=a.options,c=b.cursor,d=b.dataLabels,e=a.points,f,g,h=a.hasRendered||0,i,j,k=a.chart.renderer;if(d.enabled||a._hasPointLabels)a.dlProcessOptions&&a.dlProcessOptions(d),j=a.plotGroup("dataLabelsGroup","data-labels",d.defer?"hidden":"visible",d.zIndex||6),p(d.defer,!0)&&(j.attr({opacity:+h}),h||H(a,"afterAnimate",function(){a.visible&&j.show();j[b.animation?"animate":"attr"]({opacity:1},{duration:200})})),g=d,o(e,function(e){var h,n=e.dataLabel,o,s,r=e.connector,u=!0,t,w={};f=e.dlOptions||e.options&&
e.options.dataLabels;h=p(f&&f.enabled,g.enabled);if(n&&!h)e.dataLabel=n.destroy();else if(h){d=z(g,f);t=d.style;h=d.rotation;o=e.getLabelConfig();i=d.format?Ja(d.format,o):d.formatter.call(o,d);t.color=p(d.color,t.color,a.color,"black");if(n)if(q(i))n.attr({text:i}),u=!1;else{if(e.dataLabel=n=n.destroy(),r)e.connector=r.destroy()}else if(q(i)){n={fill:d.backgroundColor,stroke:d.borderColor,"stroke-width":d.borderWidth,r:d.borderRadius||0,rotation:h,padding:d.padding,zIndex:1};if(t.color==="contrast")w.color=
d.inside||d.distance<0||b.stacking?k.getContrast(e.color||a.color):"#000000";if(c)w.cursor=c;for(s in n)n[s]===y&&delete n[s];n=e.dataLabel=k[h?"text":"label"](i,0,-999,d.shape,null,null,d.useHTML).attr(n).css(x(t,w)).add(j).shadow(d.shadow)}n&&a.alignDataLabel(e,n,d,null,u)}})};R.prototype.alignDataLabel=function(a,b,c,d,e){var f=this.chart,g=f.inverted,h=p(a.plotX,-999),i=p(a.plotY,-999),j=b.getBBox(),k=f.renderer.fontMetrics(c.style.fontSize).b,l=this.visible&&(a.series.forceDL||f.isInsidePlot(h,
r(i),g)||d&&f.isInsidePlot(h,g?d.x+1:d.y+d.height-1,g));if(l)d=x({x:g?f.plotWidth-i:h,y:r(g?f.plotHeight-h:i),width:0,height:0},d),x(c,{width:j.width,height:j.height}),c.rotation?(a=f.renderer.rotCorr(k,c.rotation),b[e?"attr":"animate"]({x:d.x+c.x+d.width/2+a.x,y:d.y+c.y+d.height/2}).attr({align:c.align})):(b.align(c,null,d),g=b.alignAttr,p(c.overflow,"justify")==="justify"?this.justifyDataLabel(b,c,g,j,d,e):p(c.crop,!0)&&(l=f.isInsidePlot(g.x,g.y)&&f.isInsidePlot(g.x+j.width,g.y+j.height)),c.shape&&
b.attr({anchorX:a.plotX,anchorY:a.plotY}));if(!l)b.attr({y:-999}),b.placed=!1};R.prototype.justifyDataLabel=function(a,b,c,d,e,f){var g=this.chart,h=b.align,i=b.verticalAlign,j,k,l=a.box?0:a.padding||0;j=c.x+l;if(j<0)h==="right"?b.align="left":b.x=-j,k=!0;j=c.x+d.width-l;if(j>g.plotWidth)h==="left"?b.align="right":b.x=g.plotWidth-j,k=!0;j=c.y+l;if(j<0)i==="bottom"?b.verticalAlign="top":b.y=-j,k=!0;j=c.y+d.height-l;if(j>g.plotHeight)i==="top"?b.verticalAlign="bottom":b.y=g.plotHeight-j,k=!0;if(k)a.placed=
!f,a.align(b,null,e)};if(M.pie)M.pie.prototype.drawDataLabels=function(){var a=this,b=a.data,c,d=a.chart,e=a.options.dataLabels,f=p(e.connectorPadding,10),g=p(e.connectorWidth,1),h=d.plotWidth,i=d.plotHeight,j,k,l=p(e.softConnector,!0),m=e.distance,n=a.center,q=n[2]/2,s=n[1],x=m>0,y,t,w,z=[[],[]],B,A,D,F,G,E=[0,0,0,0],L=function(a,b){return b.y-a.y};if(a.visible&&(e.enabled||a._hasPointLabels)){R.prototype.drawDataLabels.apply(a);o(b,function(a){a.dataLabel&&a.visible&&z[a.half].push(a)});for(F=2;F--;){var I=
[],M=[],H=z[F],K=H.length,J;if(K){a.sortByAngle(H,F-0.5);for(G=b=0;!b&&H[G];)b=H[G]&&H[G].dataLabel&&(H[G].dataLabel.getBBox().height||21),G++;if(m>0){t=C(s+q+m,d.plotHeight);for(G=u(0,s-q-m);G<=t;G+=b)I.push(G);t=I.length;if(K>t){c=[].concat(H);c.sort(L);for(G=K;G--;)c[G].rank=G;for(G=K;G--;)H[G].rank>=t&&H.splice(G,1);K=H.length}for(G=0;G<K;G++){c=H[G];w=c.labelPos;c=9999;var Q,P;for(P=0;P<t;P++)Q=O(I[P]-w[1]),Q<c&&(c=Q,J=P);if(J<G&&I[G]!==null)J=G;else for(t<K-G+J&&I[G]!==null&&(J=t-K+G);I[J]===
null;)J++;M.push({i:J,y:I[J]});I[J]=null}M.sort(L)}for(G=0;G<K;G++){c=H[G];w=c.labelPos;y=c.dataLabel;D=c.visible===!1?"hidden":"inherit";c=w[1];if(m>0){if(t=M.pop(),J=t.i,A=t.y,c>A&&I[J+1]!==null||c<A&&I[J-1]!==null)A=C(u(0,c),d.plotHeight)}else A=c;B=e.justify?n[0]+(F?-1:1)*(q+m):a.getX(A===s-q-m||A===s+q+m?c:A,F);y._attr={visibility:D,align:w[6]};y._pos={x:B+e.x+({left:f,right:-f}[w[6]]||0),y:A+e.y-10};y.connX=B;y.connY=A;if(this.options.size===null)t=y.width,B-t<f?E[3]=u(r(t-B+f),E[3]):B+t>h-
f&&(E[1]=u(r(B+t-h+f),E[1])),A-b/2<0?E[0]=u(r(-A+b/2),E[0]):A+b/2>i&&(E[2]=u(r(A+b/2-i),E[2]))}}}if(Fa(E)===0||this.verifyDataLabelOverflow(E))this.placeDataLabels(),x&&g&&o(this.points,function(b){j=b.connector;w=b.labelPos;if((y=b.dataLabel)&&y._pos&&b.visible)D=y._attr.visibility,B=y.connX,A=y.connY,k=l?["M",B+(w[6]==="left"?5:-5),A,"C",B,A,2*w[2]-w[4],2*w[3]-w[5],w[2],w[3],"L",w[4],w[5]]:["M",B+(w[6]==="left"?5:-5),A,"L",w[2],w[3],"L",w[4],w[5]],j?(j.animate({d:k}),j.attr("visibility",D)):b.connector=
j=a.chart.renderer.path(k).attr({"stroke-width":g,stroke:e.connectorColor||b.color||"#606060",visibility:D}).add(a.dataLabelsGroup);else if(j)b.connector=j.destroy()})}},M.pie.prototype.placeDataLabels=function(){o(this.points,function(a){var b=a.dataLabel;if(b&&a.visible)(a=b._pos)?(b.attr(b._attr),b[b.moved?"animate":"attr"](a),b.moved=!0):b&&b.attr({y:-999})})},M.pie.prototype.alignDataLabel=na,M.pie.prototype.verifyDataLabelOverflow=function(a){var b=this.center,c=this.options,d=c.center,e=c.minSize||
80,f=e,g;d[0]!==null?f=u(b[2]-u(a[1],a[3]),e):(f=u(b[2]-a[1]-a[3],e),b[0]+=(a[3]-a[1])/2);d[1]!==null?f=u(C(f,b[2]-u(a[0],a[2])),e):(f=u(C(f,b[2]-a[0]-a[2]),e),b[1]+=(a[0]-a[2])/2);f<b[2]?(b[2]=f,b[3]=/%$/.test(c.innerSize||0)?f*parseFloat(c.innerSize||0)/100:parseFloat(c.innerSize||0),this.translate(b),o(this.points,function(a){if(a.dataLabel)a.dataLabel._pos=null}),this.drawDataLabels&&this.drawDataLabels()):g=!0;return g};if(M.column)M.column.prototype.alignDataLabel=function(a,b,c,d,e){var f=
this.chart.inverted,g=a.series,h=a.dlBox||a.shapeArgs,i=p(a.below,a.plotY>p(this.translatedThreshold,g.yAxis.len)),j=p(c.inside,!!this.options.stacking);if(h&&(d=z(h),f&&(d={x:g.yAxis.len-d.y-d.height,y:g.xAxis.len-d.x-d.width,width:d.height,height:d.width}),!j))f?(d.x+=i?0:d.width,d.width=0):(d.y+=i?d.height:0,d.height=0);c.align=p(c.align,!f||j?"center":i?"right":"left");c.verticalAlign=p(c.verticalAlign,f||j?"middle":i?"top":"bottom");R.prototype.alignDataLabel.call(this,a,b,c,d,e)};(function(a){var b=
a.Chart,c=a.each,d=a.pick,e=HighchartsAdapter.addEvent;b.prototype.callbacks.push(function(a){function b(){var e=[];c(a.series,function(a){var b=a.options.dataLabels;(b.enabled||a._hasPointLabels)&&!b.allowOverlap&&a.visible&&c(a.points,function(a){if(a.dataLabel)a.dataLabel.labelrank=d(a.labelrank,a.shapeArgs&&a.shapeArgs.height),e.push(a.dataLabel)})});a.hideOverlappingLabels(e)}b();e(a,"redraw",b)});b.prototype.hideOverlappingLabels=function(a){var b=a.length,c,d,e,k;for(d=0;d<b;d++)if(c=a[d])c.oldOpacity=
c.opacity,c.newOpacity=1;a.sort(function(a,b){return b.labelrank-a.labelrank});for(d=0;d<b;d++){e=a[d];for(c=d+1;c<b;++c)if(k=a[c],e&&k&&e.placed&&k.placed&&e.newOpacity!==0&&k.newOpacity!==0&&!(k.alignAttr.x>e.alignAttr.x+e.width||k.alignAttr.x+k.width<e.alignAttr.x||k.alignAttr.y>e.alignAttr.y+e.height||k.alignAttr.y+k.height<e.alignAttr.y))(e.labelrank<k.labelrank?e:k).newOpacity=0}for(d=0;d<b;d++)if(c=a[d]){if(c.oldOpacity!==c.newOpacity&&c.placed)c.alignAttr.opacity=c.newOpacity,c[c.isOld&&c.newOpacity?
"animate":"attr"](c.alignAttr);c.isOld=!0}}})(A);U=A.TrackerMixin={drawTrackerPoint:function(){var a=this,b=a.chart,c=b.pointer,d=a.options.cursor,e=d&&{cursor:d},f=function(a){for(var c=a.target,d;c&&!d;)d=c.point,c=c.parentNode;if(d!==y&&d!==b.hoverPoint)d.onMouseOver(a)};o(a.points,function(a){if(a.graphic)a.graphic.element.point=a;if(a.dataLabel)a.dataLabel.element.point=a});if(!a._hasTracking)o(a.trackerGroups,function(b){if(a[b]&&(a[b].addClass("highcharts-tracker").on("mouseover",f).on("mouseout",
function(a){c.onTrackerMouseOut(a)}).css(e),ab))a[b].on("touchstart",f)}),a._hasTracking=!0},drawTrackerGraph:function(){var a=this,b=a.options,c=b.trackByArea,d=[].concat(c?a.areaPath:a.graphPath),e=d.length,f=a.chart,g=f.pointer,h=f.renderer,i=f.options.tooltip.snap,j=a.tracker,k=b.cursor,l=k&&{cursor:k},k=a.singlePoints,m,n=function(){if(f.hoverSeries!==a)a.onMouseOver()},p="rgba(192,192,192,"+(ca?1.0E-4:0.002)+")";if(e&&!c)for(m=e+1;m--;)d[m]==="M"&&d.splice(m+1,0,d[m+1]-i,d[m+2],"L"),(m&&d[m]===
"M"||m===e)&&d.splice(m,0,"L",d[m-2]+i,d[m-1]);for(m=0;m<k.length;m++)e=k[m],d.push("M",e.plotX-i,e.plotY,"L",e.plotX+i,e.plotY);j?j.attr({d:d}):(a.tracker=h.path(d).attr({"stroke-linejoin":"round",visibility:a.visible?"visible":"hidden",stroke:p,fill:c?p:P,"stroke-width":b.lineWidth+(c?0:2*i),zIndex:2}).add(a.group),o([a.tracker,a.markerGroup],function(a){a.addClass("highcharts-tracker").on("mouseover",n).on("mouseout",function(a){g.onTrackerMouseOut(a)}).css(l);if(ab)a.on("touchstart",n)}))}};if(M.column)xa.prototype.drawTracker=
U.drawTrackerPoint;if(M.pie)M.pie.prototype.drawTracker=U.drawTrackerPoint;if(M.scatter)qa.prototype.drawTracker=U.drawTrackerPoint;x(nb.prototype,{setItemEvents:function(a,b,c,d,e){var f=this;(c?b:a.legendGroup).on("mouseover",function(){a.setState("hover");b.css(f.options.itemHoverStyle)}).on("mouseout",function(){b.css(a.visible?d:e);a.setState()}).on("click",function(b){var c=function(){a.setVisible()},b={browserEvent:b};a.firePointEvent?a.firePointEvent("legendItemClick",b,c):I(a,"legendItemClick",
b,c)})},createCheckboxForItem:function(a){a.checkbox=$("input",{type:"checkbox",checked:a.selected,defaultChecked:a.selected},this.options.itemCheckboxStyle,this.chart.container);H(a.checkbox,"click",function(b){I(a.series||a,"checkboxClick",{checked:b.target.checked,item:a},function(){a.select()})})}});T.legend.itemStyle.cursor="pointer";x(F.prototype,{showResetZoom:function(){var a=this,b=T.lang,c=a.options.chart.resetZoomButton,d=c.theme,e=d.states,f=c.relativeTo==="chart"?null:"plotBox";this.resetZoomButton=
a.renderer.button(b.resetZoom,null,null,function(){a.zoomOut()},d,e&&e.hover).attr({align:c.position.align,title:b.resetZoomTitle}).add().align(c.position,!1,f)},zoomOut:function(){var a=this;I(a,"selection",{resetSelection:!0},function(){a.zoom()})},zoom:function(a){var b,c=this.pointer,d=!1,e;!a||a.resetSelection?o(this.axes,function(a){b=a.zoom()}):o(a.xAxis.concat(a.yAxis),function(a){var e=a.axis,h=e.isXAxis;if(c[h?"zoomX":"zoomY"]||c[h?"pinchX":"pinchY"])b=e.zoom(a.min,a.max),e.displayBtn&&
(d=!0)});e=this.resetZoomButton;if(d&&!e)this.showResetZoom();else if(!d&&da(e))this.resetZoomButton=e.destroy();b&&this.redraw(p(this.options.chart.animation,a&&a.animation,this.pointCount<100))},pan:function(a,b){var c=this,d=c.hoverPoints,e;d&&o(d,function(a){a.setState()});o(b==="xy"?[1,0]:[1],function(b){var d=a[b?"chartX":"chartY"],h=c[b?"xAxis":"yAxis"][0],i=c[b?"mouseDownX":"mouseDownY"],j=(h.pointRange||0)/2,k=h.getExtremes(),l=h.toValue(i-d,!0)+j,j=h.toValue(i+c[b?"plotWidth":"plotHeight"]-
d,!0)-j,i=i>d;if(h.series.length&&(i||l>C(k.dataMin,k.min))&&(!i||j<u(k.dataMax,k.max)))h.setExtremes(l,j,!1,!1,{trigger:"pan"}),e=!0;c[b?"mouseDownX":"mouseDownY"]=d});e&&c.redraw(!1);L(c.container,{cursor:"move"})}});x(Ga.prototype,{select:function(a,b){var c=this,d=c.series,e=d.chart,a=p(a,!c.selected);c.firePointEvent(a?"select":"unselect",{accumulate:b},function(){c.selected=c.options.selected=a;d.options.data[Ma(c,d.data)]=c.options;c.setState(a&&"select");b||o(e.getSelectedPoints(),function(a){if(a.selected&&
a!==c)a.selected=a.options.selected=!1,d.options.data[Ma(a,d.data)]=a.options,a.setState(""),a.firePointEvent("unselect")})})},onMouseOver:function(a){var b=this.series,c=b.chart,d=c.tooltip,e=c.hoverPoint;if(c.hoverSeries!==b)b.onMouseOver();if(e&&e!==this)e.onMouseOut();if(this.series)this.firePointEvent("mouseOver"),d&&(!d.shared||b.noSharedTooltip)&&d.refresh(this,a),this.setState("hover"),c.hoverPoint=this},onMouseOut:function(){var a=this.series.chart,b=a.hoverPoints;this.firePointEvent("mouseOut");
if(!b||Ma(this,b)===-1)this.setState(),a.hoverPoint=null},importEvents:function(){if(!this.hasImportedEvents){var a=z(this.series.options.point,this.options).events,b;this.events=a;for(b in a)H(this,b,a[b]);this.hasImportedEvents=!0}},setState:function(a,b){var c=this.plotX,d=this.plotY,e=this.series,f=e.options.states,g=ba[e.type].marker&&e.options.marker,h=g&&!g.enabled,i=g&&g.states[a],j=i&&i.enabled===!1,k=e.stateMarkerGraphic,l=this.marker||{},m=e.chart,n=e.halo,o,a=a||"";o=this.pointAttr[a]||
e.pointAttr[a];if(!(a===this.state&&!b||this.selected&&a!=="select"||f[a]&&f[a].enabled===!1||a&&(j||h&&i.enabled===!1)||a&&l.states&&l.states[a]&&l.states[a].enabled===!1)){if(this.graphic)g=g&&this.graphic.symbolName&&o.r,this.graphic.attr(z(o,g?{x:c-g,y:d-g,width:2*g,height:2*g}:{})),k&&k.hide();else{if(a&&i)if(g=i.radius,l=l.symbol||e.symbol,k&&k.currentSymbol!==l&&(k=k.destroy()),k)k[b?"animate":"attr"]({x:c-g,y:d-g});else if(l)e.stateMarkerGraphic=k=m.renderer.symbol(l,c-g,d-g,2*g,2*g).attr(o).add(e.markerGroup),
k.currentSymbol=l;if(k)k[a&&m.isInsidePlot(c,d,m.inverted)?"show":"hide"](),k.element.point=this}if((c=f[a]&&f[a].halo)&&c.size){if(!n)e.halo=n=m.renderer.path().add(m.seriesGroup);n.attr(x({fill:oa(this.color||e.color).setOpacity(c.opacity).get()},c.attributes))[b?"animate":"attr"]({d:this.haloPath(c.size)})}else n&&n.attr({d:[]});this.state=a}},haloPath:function(a){var b=this.series,c=b.chart,d=b.getPlotBox(),e=c.inverted;return c.renderer.symbols.circle(d.translateX+(e?b.yAxis.len-this.plotY:this.plotX)-
a,d.translateY+(e?b.xAxis.len-this.plotX:this.plotY)-a,a*2,a*2)}});x(R.prototype,{onMouseOver:function(){var a=this.chart,b=a.hoverSeries;if(b&&b!==this)b.onMouseOut();this.options.events.mouseOver&&I(this,"mouseOver");this.setState("hover");a.hoverSeries=this},onMouseOut:function(){var a=this.options,b=this.chart,c=b.tooltip,d=b.hoverPoint;b.hoverSeries=null;if(d)d.onMouseOut();this&&a.events.mouseOut&&I(this,"mouseOut");c&&!a.stickyTracking&&(!c.shared||this.noSharedTooltip)&&c.hide();this.setState()},
setState:function(a){var b=this.options,c=this.graph,d=b.states,e=b.lineWidth,b=0,a=a||"";if(this.state!==a&&(this.state=a,!(d[a]&&d[a].enabled===!1)&&(a&&(e=d[a].lineWidth||e+(d[a].lineWidthPlus||0)),c&&!c.dashstyle))){a={"stroke-width":e};for(c.attr(a);this["zoneGraph"+b];)this["zoneGraph"+b].attr(a),b+=1}},setVisible:function(a,b){var c=this,d=c.chart,e=c.legendItem,f,g=d.options.chart.ignoreHiddenSeries,h=c.visible;f=(c.visible=a=c.userOptions.visible=a===y?!h:a)?"show":"hide";o(["group","dataLabelsGroup",
"markerGroup","tracker"],function(a){if(c[a])c[a][f]()});if(d.hoverSeries===c||(d.hoverPoint&&d.hoverPoint.series)===c)c.onMouseOut();e&&d.legend.colorizeItem(c,a);c.isDirty=!0;c.options.stacking&&o(d.series,function(a){if(a.options.stacking&&a.visible)a.isDirty=!0});o(c.linkedSeries,function(b){b.setVisible(a,!1)});if(g)d.isDirtyBox=!0;b!==!1&&d.redraw();I(c,f)},show:function(){this.setVisible(!0)},hide:function(){this.setVisible(!1)},select:function(a){this.selected=a=a===y?!this.selected:a;if(this.checkbox)this.checkbox.checked=
a;I(this,a?"select":"unselect")},drawTracker:U.drawTrackerGraph});x(A,{Color:oa,Point:Ga,Tick:Ta,Renderer:$a,SVGElement:Q,SVGRenderer:ua,arrayMin:Pa,arrayMax:Fa,charts:Y,dateFormat:Oa,error:la,format:Ja,pathAnim:zb,getOptions:function(){return T},hasBidiBug:Ob,isTouchDevice:Kb,setOptions:function(a){T=z(!0,T,a);Db();return T},addEvent:H,removeEvent:Z,createElement:$,discardElement:Ra,css:L,each:o,map:Ua,merge:z,splat:sa,extendClass:ka,pInt:D,svg:ca,canvas:fa,vml:!ca&&!fa,product:"Highcharts",version:"4.1.7"})})();
| panoramix/static/highcharts.js | 0 | https://github.com/apache/superset/commit/6dd81a3e95a9d67be743815ff9bfcd465278b3e9 | [
0.00017372194270137697,
0.00016905521624721587,
0.0001665131567278877,
0.00016842262994032353,
0.0000019062200635744375
] |
{
"id": 5,
"code_window": [
"class TableColumnInlineView(CompactCRUDMixin, ModelView):\n",
" datamodel = SQLAInterface(models.TableColumn)\n",
" can_delete = False\n",
" edit_columns = [\n",
" 'column_name', 'description', 'table', 'groupby', 'filterable',\n",
" 'count_distinct', 'sum', 'min', 'max']\n",
" list_columns = [\n",
" 'column_name', 'type', 'groupby', 'filterable', 'count_distinct',\n",
" 'sum', 'min', 'max']\n",
" page_size = 100\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" 'column_name', 'description', 'groupby', 'filterable', 'table',\n"
],
"file_path": "panoramix/views.py",
"type": "replace",
"edit_start_line_idx": 32
} | /*! DataTables 1.10.7
* ©2008-2015 SpryMedia Ltd - datatables.net/license
*/
(function(Ea,Q,k){var P=function(h){function W(a){var b,c,e={};h.each(a,function(d){if((b=d.match(/^([^A-Z]+?)([A-Z])/))&&-1!=="a aa ai ao as b fn i m o s ".indexOf(b[1]+" "))c=d.replace(b[0],b[2].toLowerCase()),e[c]=d,"o"===b[1]&&W(a[d])});a._hungarianMap=e}function H(a,b,c){a._hungarianMap||W(a);var e;h.each(b,function(d){e=a._hungarianMap[d];if(e!==k&&(c||b[e]===k))"o"===e.charAt(0)?(b[e]||(b[e]={}),h.extend(!0,b[e],b[d]),H(a[e],b[e],c)):b[e]=b[d]})}function P(a){var b=m.defaults.oLanguage,c=a.sZeroRecords;
!a.sEmptyTable&&(c&&"No data available in table"===b.sEmptyTable)&&E(a,a,"sZeroRecords","sEmptyTable");!a.sLoadingRecords&&(c&&"Loading..."===b.sLoadingRecords)&&E(a,a,"sZeroRecords","sLoadingRecords");a.sInfoThousands&&(a.sThousands=a.sInfoThousands);(a=a.sDecimal)&&db(a)}function eb(a){A(a,"ordering","bSort");A(a,"orderMulti","bSortMulti");A(a,"orderClasses","bSortClasses");A(a,"orderCellsTop","bSortCellsTop");A(a,"order","aaSorting");A(a,"orderFixed","aaSortingFixed");A(a,"paging","bPaginate");
A(a,"pagingType","sPaginationType");A(a,"pageLength","iDisplayLength");A(a,"searching","bFilter");if(a=a.aoSearchCols)for(var b=0,c=a.length;b<c;b++)a[b]&&H(m.models.oSearch,a[b])}function fb(a){A(a,"orderable","bSortable");A(a,"orderData","aDataSort");A(a,"orderSequence","asSorting");A(a,"orderDataType","sortDataType");var b=a.aDataSort;b&&!h.isArray(b)&&(a.aDataSort=[b])}function gb(a){var a=a.oBrowser,b=h("<div/>").css({position:"absolute",top:0,left:0,height:1,width:1,overflow:"hidden"}).append(h("<div/>").css({position:"absolute",
top:1,left:1,width:100,overflow:"scroll"}).append(h('<div class="test"/>').css({width:"100%",height:10}))).appendTo("body"),c=b.find(".test");a.bScrollOversize=100===c[0].offsetWidth;a.bScrollbarLeft=1!==Math.round(c.offset().left);b.remove()}function hb(a,b,c,e,d,f){var g,j=!1;c!==k&&(g=c,j=!0);for(;e!==d;)a.hasOwnProperty(e)&&(g=j?b(g,a[e],e,a):a[e],j=!0,e+=f);return g}function Fa(a,b){var c=m.defaults.column,e=a.aoColumns.length,c=h.extend({},m.models.oColumn,c,{nTh:b?b:Q.createElement("th"),sTitle:c.sTitle?
c.sTitle:b?b.innerHTML:"",aDataSort:c.aDataSort?c.aDataSort:[e],mData:c.mData?c.mData:e,idx:e});a.aoColumns.push(c);c=a.aoPreSearchCols;c[e]=h.extend({},m.models.oSearch,c[e]);ka(a,e,h(b).data())}function ka(a,b,c){var b=a.aoColumns[b],e=a.oClasses,d=h(b.nTh);if(!b.sWidthOrig){b.sWidthOrig=d.attr("width")||null;var f=(d.attr("style")||"").match(/width:\s*(\d+[pxem%]+)/);f&&(b.sWidthOrig=f[1])}c!==k&&null!==c&&(fb(c),H(m.defaults.column,c),c.mDataProp!==k&&!c.mData&&(c.mData=c.mDataProp),c.sType&&
(b._sManualType=c.sType),c.className&&!c.sClass&&(c.sClass=c.className),h.extend(b,c),E(b,c,"sWidth","sWidthOrig"),c.iDataSort!==k&&(b.aDataSort=[c.iDataSort]),E(b,c,"aDataSort"));var g=b.mData,j=R(g),i=b.mRender?R(b.mRender):null,c=function(a){return"string"===typeof a&&-1!==a.indexOf("@")};b._bAttrSrc=h.isPlainObject(g)&&(c(g.sort)||c(g.type)||c(g.filter));b.fnGetData=function(a,b,c){var e=j(a,b,k,c);return i&&b?i(e,b,a,c):e};b.fnSetData=function(a,b,c){return S(g)(a,b,c)};"number"!==typeof g&&
(a._rowReadObject=!0);a.oFeatures.bSort||(b.bSortable=!1,d.addClass(e.sSortableNone));a=-1!==h.inArray("asc",b.asSorting);c=-1!==h.inArray("desc",b.asSorting);!b.bSortable||!a&&!c?(b.sSortingClass=e.sSortableNone,b.sSortingClassJUI=""):a&&!c?(b.sSortingClass=e.sSortableAsc,b.sSortingClassJUI=e.sSortJUIAscAllowed):!a&&c?(b.sSortingClass=e.sSortableDesc,b.sSortingClassJUI=e.sSortJUIDescAllowed):(b.sSortingClass=e.sSortable,b.sSortingClassJUI=e.sSortJUI)}function X(a){if(!1!==a.oFeatures.bAutoWidth){var b=
a.aoColumns;Ga(a);for(var c=0,e=b.length;c<e;c++)b[c].nTh.style.width=b[c].sWidth}b=a.oScroll;(""!==b.sY||""!==b.sX)&&Y(a);w(a,null,"column-sizing",[a])}function la(a,b){var c=Z(a,"bVisible");return"number"===typeof c[b]?c[b]:null}function $(a,b){var c=Z(a,"bVisible"),c=h.inArray(b,c);return-1!==c?c:null}function aa(a){return Z(a,"bVisible").length}function Z(a,b){var c=[];h.map(a.aoColumns,function(a,d){a[b]&&c.push(d)});return c}function Ha(a){var b=a.aoColumns,c=a.aoData,e=m.ext.type.detect,d,
f,g,j,i,h,l,q,n;d=0;for(f=b.length;d<f;d++)if(l=b[d],n=[],!l.sType&&l._sManualType)l.sType=l._sManualType;else if(!l.sType){g=0;for(j=e.length;g<j;g++){i=0;for(h=c.length;i<h;i++){n[i]===k&&(n[i]=x(a,i,d,"type"));q=e[g](n[i],a);if(!q&&g!==e.length-1)break;if("html"===q)break}if(q){l.sType=q;break}}l.sType||(l.sType="string")}}function ib(a,b,c,e){var d,f,g,j,i,o,l=a.aoColumns;if(b)for(d=b.length-1;0<=d;d--){o=b[d];var q=o.targets!==k?o.targets:o.aTargets;h.isArray(q)||(q=[q]);f=0;for(g=q.length;f<
g;f++)if("number"===typeof q[f]&&0<=q[f]){for(;l.length<=q[f];)Fa(a);e(q[f],o)}else if("number"===typeof q[f]&&0>q[f])e(l.length+q[f],o);else if("string"===typeof q[f]){j=0;for(i=l.length;j<i;j++)("_all"==q[f]||h(l[j].nTh).hasClass(q[f]))&&e(j,o)}}if(c){d=0;for(a=c.length;d<a;d++)e(d,c[d])}}function K(a,b,c,e){var d=a.aoData.length,f=h.extend(!0,{},m.models.oRow,{src:c?"dom":"data"});f._aData=b;a.aoData.push(f);for(var b=a.aoColumns,f=0,g=b.length;f<g;f++)c&&Ia(a,d,f,x(a,d,f)),b[f].sType=null;a.aiDisplayMaster.push(d);
(c||!a.oFeatures.bDeferRender)&&Ja(a,d,c,e);return d}function ma(a,b){var c;b instanceof h||(b=h(b));return b.map(function(b,d){c=na(a,d);return K(a,c.data,d,c.cells)})}function x(a,b,c,e){var d=a.iDraw,f=a.aoColumns[c],g=a.aoData[b]._aData,j=f.sDefaultContent,c=f.fnGetData(g,e,{settings:a,row:b,col:c});if(c===k)return a.iDrawError!=d&&null===j&&(I(a,0,"Requested unknown parameter "+("function"==typeof f.mData?"{function}":"'"+f.mData+"'")+" for row "+b,4),a.iDrawError=d),j;if((c===g||null===c)&&
null!==j)c=j;else if("function"===typeof c)return c.call(g);return null===c&&"display"==e?"":c}function Ia(a,b,c,e){a.aoColumns[c].fnSetData(a.aoData[b]._aData,e,{settings:a,row:b,col:c})}function Ka(a){return h.map(a.match(/(\\.|[^\.])+/g),function(a){return a.replace(/\\./g,".")})}function R(a){if(h.isPlainObject(a)){var b={};h.each(a,function(a,c){c&&(b[a]=R(c))});return function(a,c,f,g){var j=b[c]||b._;return j!==k?j(a,c,f,g):a}}if(null===a)return function(a){return a};if("function"===typeof a)return function(b,
c,f,g){return a(b,c,f,g)};if("string"===typeof a&&(-1!==a.indexOf(".")||-1!==a.indexOf("[")||-1!==a.indexOf("("))){var c=function(a,b,f){var g,j;if(""!==f){j=Ka(f);for(var i=0,h=j.length;i<h;i++){f=j[i].match(ba);g=j[i].match(T);if(f){j[i]=j[i].replace(ba,"");""!==j[i]&&(a=a[j[i]]);g=[];j.splice(0,i+1);j=j.join(".");i=0;for(h=a.length;i<h;i++)g.push(c(a[i],b,j));a=f[0].substring(1,f[0].length-1);a=""===a?g:g.join(a);break}else if(g){j[i]=j[i].replace(T,"");a=a[j[i]]();continue}if(null===a||a[j[i]]===
k)return k;a=a[j[i]]}}return a};return function(b,d){return c(b,d,a)}}return function(b){return b[a]}}function S(a){if(h.isPlainObject(a))return S(a._);if(null===a)return function(){};if("function"===typeof a)return function(b,e,d){a(b,"set",e,d)};if("string"===typeof a&&(-1!==a.indexOf(".")||-1!==a.indexOf("[")||-1!==a.indexOf("("))){var b=function(a,e,d){var d=Ka(d),f;f=d[d.length-1];for(var g,j,i=0,h=d.length-1;i<h;i++){g=d[i].match(ba);j=d[i].match(T);if(g){d[i]=d[i].replace(ba,"");a[d[i]]=[];
f=d.slice();f.splice(0,i+1);g=f.join(".");j=0;for(h=e.length;j<h;j++)f={},b(f,e[j],g),a[d[i]].push(f);return}j&&(d[i]=d[i].replace(T,""),a=a[d[i]](e));if(null===a[d[i]]||a[d[i]]===k)a[d[i]]={};a=a[d[i]]}if(f.match(T))a[f.replace(T,"")](e);else a[f.replace(ba,"")]=e};return function(c,e){return b(c,e,a)}}return function(b,e){b[a]=e}}function La(a){return D(a.aoData,"_aData")}function oa(a){a.aoData.length=0;a.aiDisplayMaster.length=0;a.aiDisplay.length=0}function pa(a,b,c){for(var e=-1,d=0,f=a.length;d<
f;d++)a[d]==b?e=d:a[d]>b&&a[d]--; -1!=e&&c===k&&a.splice(e,1)}function ca(a,b,c,e){var d=a.aoData[b],f,g=function(c,f){for(;c.childNodes.length;)c.removeChild(c.firstChild);c.innerHTML=x(a,b,f,"display")};if("dom"===c||(!c||"auto"===c)&&"dom"===d.src)d._aData=na(a,d,e,e===k?k:d._aData).data;else{var j=d.anCells;if(j)if(e!==k)g(j[e],e);else{c=0;for(f=j.length;c<f;c++)g(j[c],c)}}d._aSortData=null;d._aFilterData=null;g=a.aoColumns;if(e!==k)g[e].sType=null;else{c=0;for(f=g.length;c<f;c++)g[c].sType=null;
Ma(d)}}function na(a,b,c,e){var d=[],f=b.firstChild,g,j=0,i,o=a.aoColumns,l=a._rowReadObject,e=e||l?{}:[],q=function(a,b){if("string"===typeof a){var c=a.indexOf("@");-1!==c&&(c=a.substring(c+1),S(a)(e,b.getAttribute(c)))}},a=function(a){if(c===k||c===j)g=o[j],i=h.trim(a.innerHTML),g&&g._bAttrSrc?(S(g.mData._)(e,i),q(g.mData.sort,a),q(g.mData.type,a),q(g.mData.filter,a)):l?(g._setter||(g._setter=S(g.mData)),g._setter(e,i)):e[j]=i;j++};if(f)for(;f;){b=f.nodeName.toUpperCase();if("TD"==b||"TH"==b)a(f),
d.push(f);f=f.nextSibling}else{d=b.anCells;f=0;for(b=d.length;f<b;f++)a(d[f])}return{data:e,cells:d}}function Ja(a,b,c,e){var d=a.aoData[b],f=d._aData,g=[],j,i,h,l,q;if(null===d.nTr){j=c||Q.createElement("tr");d.nTr=j;d.anCells=g;j._DT_RowIndex=b;Ma(d);l=0;for(q=a.aoColumns.length;l<q;l++){h=a.aoColumns[l];i=c?e[l]:Q.createElement(h.sCellType);g.push(i);if(!c||h.mRender||h.mData!==l)i.innerHTML=x(a,b,l,"display");h.sClass&&(i.className+=" "+h.sClass);h.bVisible&&!c?j.appendChild(i):!h.bVisible&&c&&
i.parentNode.removeChild(i);h.fnCreatedCell&&h.fnCreatedCell.call(a.oInstance,i,x(a,b,l),f,b,l)}w(a,"aoRowCreatedCallback",null,[j,f,b])}d.nTr.setAttribute("role","row")}function Ma(a){var b=a.nTr,c=a._aData;if(b){c.DT_RowId&&(b.id=c.DT_RowId);if(c.DT_RowClass){var e=c.DT_RowClass.split(" ");a.__rowc=a.__rowc?Na(a.__rowc.concat(e)):e;h(b).removeClass(a.__rowc.join(" ")).addClass(c.DT_RowClass)}c.DT_RowAttr&&h(b).attr(c.DT_RowAttr);c.DT_RowData&&h(b).data(c.DT_RowData)}}function jb(a){var b,c,e,d,
f,g=a.nTHead,j=a.nTFoot,i=0===h("th, td",g).length,o=a.oClasses,l=a.aoColumns;i&&(d=h("<tr/>").appendTo(g));b=0;for(c=l.length;b<c;b++)f=l[b],e=h(f.nTh).addClass(f.sClass),i&&e.appendTo(d),a.oFeatures.bSort&&(e.addClass(f.sSortingClass),!1!==f.bSortable&&(e.attr("tabindex",a.iTabIndex).attr("aria-controls",a.sTableId),Oa(a,f.nTh,b))),f.sTitle!=e.html()&&e.html(f.sTitle),Pa(a,"header")(a,e,f,o);i&&da(a.aoHeader,g);h(g).find(">tr").attr("role","row");h(g).find(">tr>th, >tr>td").addClass(o.sHeaderTH);
h(j).find(">tr>th, >tr>td").addClass(o.sFooterTH);if(null!==j){a=a.aoFooter[0];b=0;for(c=a.length;b<c;b++)f=l[b],f.nTf=a[b].cell,f.sClass&&h(f.nTf).addClass(f.sClass)}}function ea(a,b,c){var e,d,f,g=[],j=[],i=a.aoColumns.length,o;if(b){c===k&&(c=!1);e=0;for(d=b.length;e<d;e++){g[e]=b[e].slice();g[e].nTr=b[e].nTr;for(f=i-1;0<=f;f--)!a.aoColumns[f].bVisible&&!c&&g[e].splice(f,1);j.push([])}e=0;for(d=g.length;e<d;e++){if(a=g[e].nTr)for(;f=a.firstChild;)a.removeChild(f);f=0;for(b=g[e].length;f<b;f++)if(o=
i=1,j[e][f]===k){a.appendChild(g[e][f].cell);for(j[e][f]=1;g[e+i]!==k&&g[e][f].cell==g[e+i][f].cell;)j[e+i][f]=1,i++;for(;g[e][f+o]!==k&&g[e][f].cell==g[e][f+o].cell;){for(c=0;c<i;c++)j[e+c][f+o]=1;o++}h(g[e][f].cell).attr("rowspan",i).attr("colspan",o)}}}}function M(a){var b=w(a,"aoPreDrawCallback","preDraw",[a]);if(-1!==h.inArray(!1,b))C(a,!1);else{var b=[],c=0,e=a.asStripeClasses,d=e.length,f=a.oLanguage,g=a.iInitDisplayStart,j="ssp"==B(a),i=a.aiDisplay;a.bDrawing=!0;g!==k&&-1!==g&&(a._iDisplayStart=
j?g:g>=a.fnRecordsDisplay()?0:g,a.iInitDisplayStart=-1);var g=a._iDisplayStart,o=a.fnDisplayEnd();if(a.bDeferLoading)a.bDeferLoading=!1,a.iDraw++,C(a,!1);else if(j){if(!a.bDestroying&&!kb(a))return}else a.iDraw++;if(0!==i.length){f=j?a.aoData.length:o;for(j=j?0:g;j<f;j++){var l=i[j],q=a.aoData[l];null===q.nTr&&Ja(a,l);l=q.nTr;if(0!==d){var n=e[c%d];q._sRowStripe!=n&&(h(l).removeClass(q._sRowStripe).addClass(n),q._sRowStripe=n)}w(a,"aoRowCallback",null,[l,q._aData,c,j]);b.push(l);c++}}else c=f.sZeroRecords,
1==a.iDraw&&"ajax"==B(a)?c=f.sLoadingRecords:f.sEmptyTable&&0===a.fnRecordsTotal()&&(c=f.sEmptyTable),b[0]=h("<tr/>",{"class":d?e[0]:""}).append(h("<td />",{valign:"top",colSpan:aa(a),"class":a.oClasses.sRowEmpty}).html(c))[0];w(a,"aoHeaderCallback","header",[h(a.nTHead).children("tr")[0],La(a),g,o,i]);w(a,"aoFooterCallback","footer",[h(a.nTFoot).children("tr")[0],La(a),g,o,i]);e=h(a.nTBody);e.children().detach();e.append(h(b));w(a,"aoDrawCallback","draw",[a]);a.bSorted=!1;a.bFiltered=!1;a.bDrawing=
!1}}function N(a,b){var c=a.oFeatures,e=c.bFilter;c.bSort&&lb(a);e?fa(a,a.oPreviousSearch):a.aiDisplay=a.aiDisplayMaster.slice();!0!==b&&(a._iDisplayStart=0);a._drawHold=b;M(a);a._drawHold=!1}function mb(a){var b=a.oClasses,c=h(a.nTable),c=h("<div/>").insertBefore(c),e=a.oFeatures,d=h("<div/>",{id:a.sTableId+"_wrapper","class":b.sWrapper+(a.nTFoot?"":" "+b.sNoFooter)});a.nHolding=c[0];a.nTableWrapper=d[0];a.nTableReinsertBefore=a.nTable.nextSibling;for(var f=a.sDom.split(""),g,j,i,o,l,q,n=0;n<f.length;n++){g=
null;j=f[n];if("<"==j){i=h("<div/>")[0];o=f[n+1];if("'"==o||'"'==o){l="";for(q=2;f[n+q]!=o;)l+=f[n+q],q++;"H"==l?l=b.sJUIHeader:"F"==l&&(l=b.sJUIFooter);-1!=l.indexOf(".")?(o=l.split("."),i.id=o[0].substr(1,o[0].length-1),i.className=o[1]):"#"==l.charAt(0)?i.id=l.substr(1,l.length-1):i.className=l;n+=q}d.append(i);d=h(i)}else if(">"==j)d=d.parent();else if("l"==j&&e.bPaginate&&e.bLengthChange)g=nb(a);else if("f"==j&&e.bFilter)g=ob(a);else if("r"==j&&e.bProcessing)g=pb(a);else if("t"==j)g=qb(a);else if("i"==
j&&e.bInfo)g=rb(a);else if("p"==j&&e.bPaginate)g=sb(a);else if(0!==m.ext.feature.length){i=m.ext.feature;q=0;for(o=i.length;q<o;q++)if(j==i[q].cFeature){g=i[q].fnInit(a);break}}g&&(i=a.aanFeatures,i[j]||(i[j]=[]),i[j].push(g),d.append(g))}c.replaceWith(d)}function da(a,b){var c=h(b).children("tr"),e,d,f,g,j,i,o,l,q,n;a.splice(0,a.length);f=0;for(i=c.length;f<i;f++)a.push([]);f=0;for(i=c.length;f<i;f++){e=c[f];for(d=e.firstChild;d;){if("TD"==d.nodeName.toUpperCase()||"TH"==d.nodeName.toUpperCase()){l=
1*d.getAttribute("colspan");q=1*d.getAttribute("rowspan");l=!l||0===l||1===l?1:l;q=!q||0===q||1===q?1:q;g=0;for(j=a[f];j[g];)g++;o=g;n=1===l?!0:!1;for(j=0;j<l;j++)for(g=0;g<q;g++)a[f+g][o+j]={cell:d,unique:n},a[f+g].nTr=e}d=d.nextSibling}}}function qa(a,b,c){var e=[];c||(c=a.aoHeader,b&&(c=[],da(c,b)));for(var b=0,d=c.length;b<d;b++)for(var f=0,g=c[b].length;f<g;f++)if(c[b][f].unique&&(!e[f]||!a.bSortCellsTop))e[f]=c[b][f].cell;return e}function ra(a,b,c){w(a,"aoServerParams","serverParams",[b]);
if(b&&h.isArray(b)){var e={},d=/(.*?)\[\]$/;h.each(b,function(a,b){var c=b.name.match(d);c?(c=c[0],e[c]||(e[c]=[]),e[c].push(b.value)):e[b.name]=b.value});b=e}var f,g=a.ajax,j=a.oInstance,i=function(b){w(a,null,"xhr",[a,b,a.jqXHR]);c(b)};if(h.isPlainObject(g)&&g.data){f=g.data;var o=h.isFunction(f)?f(b,a):f,b=h.isFunction(f)&&o?o:h.extend(!0,b,o);delete g.data}o={data:b,success:function(b){var c=b.error||b.sError;c&&I(a,0,c);a.json=b;i(b)},dataType:"json",cache:!1,type:a.sServerMethod,error:function(b,
c){var f=w(a,null,"xhr",[a,null,a.jqXHR]);-1===h.inArray(!0,f)&&("parsererror"==c?I(a,0,"Invalid JSON response",1):4===b.readyState&&I(a,0,"Ajax error",7));C(a,!1)}};a.oAjaxData=b;w(a,null,"preXhr",[a,b]);a.fnServerData?a.fnServerData.call(j,a.sAjaxSource,h.map(b,function(a,b){return{name:b,value:a}}),i,a):a.sAjaxSource||"string"===typeof g?a.jqXHR=h.ajax(h.extend(o,{url:g||a.sAjaxSource})):h.isFunction(g)?a.jqXHR=g.call(j,b,i,a):(a.jqXHR=h.ajax(h.extend(o,g)),g.data=f)}function kb(a){return a.bAjaxDataGet?
(a.iDraw++,C(a,!0),ra(a,tb(a),function(b){ub(a,b)}),!1):!0}function tb(a){var b=a.aoColumns,c=b.length,e=a.oFeatures,d=a.oPreviousSearch,f=a.aoPreSearchCols,g,j=[],i,o,l,q=U(a);g=a._iDisplayStart;i=!1!==e.bPaginate?a._iDisplayLength:-1;var n=function(a,b){j.push({name:a,value:b})};n("sEcho",a.iDraw);n("iColumns",c);n("sColumns",D(b,"sName").join(","));n("iDisplayStart",g);n("iDisplayLength",i);var k={draw:a.iDraw,columns:[],order:[],start:g,length:i,search:{value:d.sSearch,regex:d.bRegex}};for(g=
0;g<c;g++)o=b[g],l=f[g],i="function"==typeof o.mData?"function":o.mData,k.columns.push({data:i,name:o.sName,searchable:o.bSearchable,orderable:o.bSortable,search:{value:l.sSearch,regex:l.bRegex}}),n("mDataProp_"+g,i),e.bFilter&&(n("sSearch_"+g,l.sSearch),n("bRegex_"+g,l.bRegex),n("bSearchable_"+g,o.bSearchable)),e.bSort&&n("bSortable_"+g,o.bSortable);e.bFilter&&(n("sSearch",d.sSearch),n("bRegex",d.bRegex));e.bSort&&(h.each(q,function(a,b){k.order.push({column:b.col,dir:b.dir});n("iSortCol_"+a,b.col);
n("sSortDir_"+a,b.dir)}),n("iSortingCols",q.length));b=m.ext.legacy.ajax;return null===b?a.sAjaxSource?j:k:b?j:k}function ub(a,b){var c=sa(a,b),e=b.sEcho!==k?b.sEcho:b.draw,d=b.iTotalRecords!==k?b.iTotalRecords:b.recordsTotal,f=b.iTotalDisplayRecords!==k?b.iTotalDisplayRecords:b.recordsFiltered;if(e){if(1*e<a.iDraw)return;a.iDraw=1*e}oa(a);a._iRecordsTotal=parseInt(d,10);a._iRecordsDisplay=parseInt(f,10);e=0;for(d=c.length;e<d;e++)K(a,c[e]);a.aiDisplay=a.aiDisplayMaster.slice();a.bAjaxDataGet=!1;
M(a);a._bInitComplete||ta(a,b);a.bAjaxDataGet=!0;C(a,!1)}function sa(a,b){var c=h.isPlainObject(a.ajax)&&a.ajax.dataSrc!==k?a.ajax.dataSrc:a.sAjaxDataProp;return"data"===c?b.aaData||b[c]:""!==c?R(c)(b):b}function ob(a){var b=a.oClasses,c=a.sTableId,e=a.oLanguage,d=a.oPreviousSearch,f=a.aanFeatures,g='<input type="search" class="'+b.sFilterInput+'"/>',j=e.sSearch,j=j.match(/_INPUT_/)?j.replace("_INPUT_",g):j+g,b=h("<div/>",{id:!f.f?c+"_filter":null,"class":b.sFilter}).append(h("<label/>").append(j)),
f=function(){var b=!this.value?"":this.value;b!=d.sSearch&&(fa(a,{sSearch:b,bRegex:d.bRegex,bSmart:d.bSmart,bCaseInsensitive:d.bCaseInsensitive}),a._iDisplayStart=0,M(a))},g=null!==a.searchDelay?a.searchDelay:"ssp"===B(a)?400:0,i=h("input",b).val(d.sSearch).attr("placeholder",e.sSearchPlaceholder).bind("keyup.DT search.DT input.DT paste.DT cut.DT",g?ua(f,g):f).bind("keypress.DT",function(a){if(13==a.keyCode)return!1}).attr("aria-controls",c);h(a.nTable).on("search.dt.DT",function(b,c){if(a===c)try{i[0]!==
Q.activeElement&&i.val(d.sSearch)}catch(f){}});return b[0]}function fa(a,b,c){var e=a.oPreviousSearch,d=a.aoPreSearchCols,f=function(a){e.sSearch=a.sSearch;e.bRegex=a.bRegex;e.bSmart=a.bSmart;e.bCaseInsensitive=a.bCaseInsensitive};Ha(a);if("ssp"!=B(a)){vb(a,b.sSearch,c,b.bEscapeRegex!==k?!b.bEscapeRegex:b.bRegex,b.bSmart,b.bCaseInsensitive);f(b);for(b=0;b<d.length;b++)wb(a,d[b].sSearch,b,d[b].bEscapeRegex!==k?!d[b].bEscapeRegex:d[b].bRegex,d[b].bSmart,d[b].bCaseInsensitive);xb(a)}else f(b);a.bFiltered=
!0;w(a,null,"search",[a])}function xb(a){for(var b=m.ext.search,c=a.aiDisplay,e,d,f=0,g=b.length;f<g;f++){for(var j=[],i=0,h=c.length;i<h;i++)d=c[i],e=a.aoData[d],b[f](a,e._aFilterData,d,e._aData,i)&&j.push(d);c.length=0;c.push.apply(c,j)}}function wb(a,b,c,e,d,f){if(""!==b)for(var g=a.aiDisplay,e=Qa(b,e,d,f),d=g.length-1;0<=d;d--)b=a.aoData[g[d]]._aFilterData[c],e.test(b)||g.splice(d,1)}function vb(a,b,c,e,d,f){var e=Qa(b,e,d,f),d=a.oPreviousSearch.sSearch,f=a.aiDisplayMaster,g;0!==m.ext.search.length&&
(c=!0);g=yb(a);if(0>=b.length)a.aiDisplay=f.slice();else{if(g||c||d.length>b.length||0!==b.indexOf(d)||a.bSorted)a.aiDisplay=f.slice();b=a.aiDisplay;for(c=b.length-1;0<=c;c--)e.test(a.aoData[b[c]]._sFilterRow)||b.splice(c,1)}}function Qa(a,b,c,e){a=b?a:va(a);c&&(a="^(?=.*?"+h.map(a.match(/"[^"]+"|[^ ]+/g)||[""],function(a){if('"'===a.charAt(0))var b=a.match(/^"(.*)"$/),a=b?b[1]:a;return a.replace('"',"")}).join(")(?=.*?")+").*$");return RegExp(a,e?"i":"")}function va(a){return a.replace(Yb,"\\$1")}
function yb(a){var b=a.aoColumns,c,e,d,f,g,j,i,h,l=m.ext.type.search;c=!1;e=0;for(f=a.aoData.length;e<f;e++)if(h=a.aoData[e],!h._aFilterData){j=[];d=0;for(g=b.length;d<g;d++)c=b[d],c.bSearchable?(i=x(a,e,d,"filter"),l[c.sType]&&(i=l[c.sType](i)),null===i&&(i=""),"string"!==typeof i&&i.toString&&(i=i.toString())):i="",i.indexOf&&-1!==i.indexOf("&")&&(wa.innerHTML=i,i=Zb?wa.textContent:wa.innerText),i.replace&&(i=i.replace(/[\r\n]/g,"")),j.push(i);h._aFilterData=j;h._sFilterRow=j.join(" ");c=!0}return c}
function zb(a){return{search:a.sSearch,smart:a.bSmart,regex:a.bRegex,caseInsensitive:a.bCaseInsensitive}}function Ab(a){return{sSearch:a.search,bSmart:a.smart,bRegex:a.regex,bCaseInsensitive:a.caseInsensitive}}function rb(a){var b=a.sTableId,c=a.aanFeatures.i,e=h("<div/>",{"class":a.oClasses.sInfo,id:!c?b+"_info":null});c||(a.aoDrawCallback.push({fn:Bb,sName:"information"}),e.attr("role","status").attr("aria-live","polite"),h(a.nTable).attr("aria-describedby",b+"_info"));return e[0]}function Bb(a){var b=
a.aanFeatures.i;if(0!==b.length){var c=a.oLanguage,e=a._iDisplayStart+1,d=a.fnDisplayEnd(),f=a.fnRecordsTotal(),g=a.fnRecordsDisplay(),j=g?c.sInfo:c.sInfoEmpty;g!==f&&(j+=" "+c.sInfoFiltered);j+=c.sInfoPostFix;j=Cb(a,j);c=c.fnInfoCallback;null!==c&&(j=c.call(a.oInstance,a,e,d,f,g,j));h(b).html(j)}}function Cb(a,b){var c=a.fnFormatNumber,e=a._iDisplayStart+1,d=a._iDisplayLength,f=a.fnRecordsDisplay(),g=-1===d;return b.replace(/_START_/g,c.call(a,e)).replace(/_END_/g,c.call(a,a.fnDisplayEnd())).replace(/_MAX_/g,
c.call(a,a.fnRecordsTotal())).replace(/_TOTAL_/g,c.call(a,f)).replace(/_PAGE_/g,c.call(a,g?1:Math.ceil(e/d))).replace(/_PAGES_/g,c.call(a,g?1:Math.ceil(f/d)))}function ga(a){var b,c,e=a.iInitDisplayStart,d=a.aoColumns,f;c=a.oFeatures;if(a.bInitialised){mb(a);jb(a);ea(a,a.aoHeader);ea(a,a.aoFooter);C(a,!0);c.bAutoWidth&&Ga(a);b=0;for(c=d.length;b<c;b++)f=d[b],f.sWidth&&(f.nTh.style.width=s(f.sWidth));N(a);d=B(a);"ssp"!=d&&("ajax"==d?ra(a,[],function(c){var f=sa(a,c);for(b=0;b<f.length;b++)K(a,f[b]);
a.iInitDisplayStart=e;N(a);C(a,!1);ta(a,c)},a):(C(a,!1),ta(a)))}else setTimeout(function(){ga(a)},200)}function ta(a,b){a._bInitComplete=!0;b&&X(a);w(a,"aoInitComplete","init",[a,b])}function Ra(a,b){var c=parseInt(b,10);a._iDisplayLength=c;Sa(a);w(a,null,"length",[a,c])}function nb(a){for(var b=a.oClasses,c=a.sTableId,e=a.aLengthMenu,d=h.isArray(e[0]),f=d?e[0]:e,e=d?e[1]:e,d=h("<select/>",{name:c+"_length","aria-controls":c,"class":b.sLengthSelect}),g=0,j=f.length;g<j;g++)d[0][g]=new Option(e[g],
f[g]);var i=h("<div><label/></div>").addClass(b.sLength);a.aanFeatures.l||(i[0].id=c+"_length");i.children().append(a.oLanguage.sLengthMenu.replace("_MENU_",d[0].outerHTML));h("select",i).val(a._iDisplayLength).bind("change.DT",function(){Ra(a,h(this).val());M(a)});h(a.nTable).bind("length.dt.DT",function(b,c,f){a===c&&h("select",i).val(f)});return i[0]}function sb(a){var b=a.sPaginationType,c=m.ext.pager[b],e="function"===typeof c,d=function(a){M(a)},b=h("<div/>").addClass(a.oClasses.sPaging+b)[0],
f=a.aanFeatures;e||c.fnInit(a,b,d);f.p||(b.id=a.sTableId+"_paginate",a.aoDrawCallback.push({fn:function(a){if(e){var b=a._iDisplayStart,i=a._iDisplayLength,h=a.fnRecordsDisplay(),l=-1===i,b=l?0:Math.ceil(b/i),i=l?1:Math.ceil(h/i),h=c(b,i),q,l=0;for(q=f.p.length;l<q;l++)Pa(a,"pageButton")(a,f.p[l],l,h,b,i)}else c.fnUpdate(a,d)},sName:"pagination"}));return b}function Ta(a,b,c){var e=a._iDisplayStart,d=a._iDisplayLength,f=a.fnRecordsDisplay();0===f||-1===d?e=0:"number"===typeof b?(e=b*d,e>f&&(e=0)):
"first"==b?e=0:"previous"==b?(e=0<=d?e-d:0,0>e&&(e=0)):"next"==b?e+d<f&&(e+=d):"last"==b?e=Math.floor((f-1)/d)*d:I(a,0,"Unknown paging action: "+b,5);b=a._iDisplayStart!==e;a._iDisplayStart=e;b&&(w(a,null,"page",[a]),c&&M(a));return b}function pb(a){return h("<div/>",{id:!a.aanFeatures.r?a.sTableId+"_processing":null,"class":a.oClasses.sProcessing}).html(a.oLanguage.sProcessing).insertBefore(a.nTable)[0]}function C(a,b){a.oFeatures.bProcessing&&h(a.aanFeatures.r).css("display",b?"block":"none");w(a,
null,"processing",[a,b])}function qb(a){var b=h(a.nTable);b.attr("role","grid");var c=a.oScroll;if(""===c.sX&&""===c.sY)return a.nTable;var e=c.sX,d=c.sY,f=a.oClasses,g=b.children("caption"),j=g.length?g[0]._captionSide:null,i=h(b[0].cloneNode(!1)),o=h(b[0].cloneNode(!1)),l=b.children("tfoot");c.sX&&"100%"===b.attr("width")&&b.removeAttr("width");l.length||(l=null);c=h("<div/>",{"class":f.sScrollWrapper}).append(h("<div/>",{"class":f.sScrollHead}).css({overflow:"hidden",position:"relative",border:0,
width:e?!e?null:s(e):"100%"}).append(h("<div/>",{"class":f.sScrollHeadInner}).css({"box-sizing":"content-box",width:c.sXInner||"100%"}).append(i.removeAttr("id").css("margin-left",0).append("top"===j?g:null).append(b.children("thead"))))).append(h("<div/>",{"class":f.sScrollBody}).css({overflow:"auto",height:!d?null:s(d),width:!e?null:s(e)}).append(b));l&&c.append(h("<div/>",{"class":f.sScrollFoot}).css({overflow:"hidden",border:0,width:e?!e?null:s(e):"100%"}).append(h("<div/>",{"class":f.sScrollFootInner}).append(o.removeAttr("id").css("margin-left",
0).append("bottom"===j?g:null).append(b.children("tfoot")))));var b=c.children(),q=b[0],f=b[1],n=l?b[2]:null;if(e)h(f).on("scroll.DT",function(){var a=this.scrollLeft;q.scrollLeft=a;l&&(n.scrollLeft=a)});a.nScrollHead=q;a.nScrollBody=f;a.nScrollFoot=n;a.aoDrawCallback.push({fn:Y,sName:"scrolling"});return c[0]}function Y(a){var b=a.oScroll,c=b.sX,e=b.sXInner,d=b.sY,f=b.iBarWidth,g=h(a.nScrollHead),j=g[0].style,i=g.children("div"),o=i[0].style,l=i.children("table"),i=a.nScrollBody,q=h(i),n=i.style,
k=h(a.nScrollFoot).children("div"),p=k.children("table"),m=h(a.nTHead),r=h(a.nTable),t=r[0],O=t.style,L=a.nTFoot?h(a.nTFoot):null,ha=a.oBrowser,w=ha.bScrollOversize,v,u,y,x,z,A=[],B=[],C=[],D,E=function(a){a=a.style;a.paddingTop="0";a.paddingBottom="0";a.borderTopWidth="0";a.borderBottomWidth="0";a.height=0};r.children("thead, tfoot").remove();z=m.clone().prependTo(r);v=m.find("tr");y=z.find("tr");z.find("th, td").removeAttr("tabindex");L&&(x=L.clone().prependTo(r),u=L.find("tr"),x=x.find("tr"));
c||(n.width="100%",g[0].style.width="100%");h.each(qa(a,z),function(b,c){D=la(a,b);c.style.width=a.aoColumns[D].sWidth});L&&G(function(a){a.style.width=""},x);b.bCollapse&&""!==d&&(n.height=q[0].offsetHeight+m[0].offsetHeight+"px");g=r.outerWidth();if(""===c){if(O.width="100%",w&&(r.find("tbody").height()>i.offsetHeight||"scroll"==q.css("overflow-y")))O.width=s(r.outerWidth()-f)}else""!==e?O.width=s(e):g==q.width()&&q.height()<r.height()?(O.width=s(g-f),r.outerWidth()>g-f&&(O.width=s(g))):O.width=
s(g);g=r.outerWidth();G(E,y);G(function(a){C.push(a.innerHTML);A.push(s(h(a).css("width")))},y);G(function(a,b){a.style.width=A[b]},v);h(y).height(0);L&&(G(E,x),G(function(a){B.push(s(h(a).css("width")))},x),G(function(a,b){a.style.width=B[b]},u),h(x).height(0));G(function(a,b){a.innerHTML='<div class="dataTables_sizing" style="height:0;overflow:hidden;">'+C[b]+"</div>";a.style.width=A[b]},y);L&&G(function(a,b){a.innerHTML="";a.style.width=B[b]},x);if(r.outerWidth()<g){u=i.scrollHeight>i.offsetHeight||
"scroll"==q.css("overflow-y")?g+f:g;if(w&&(i.scrollHeight>i.offsetHeight||"scroll"==q.css("overflow-y")))O.width=s(u-f);(""===c||""!==e)&&I(a,1,"Possible column misalignment",6)}else u="100%";n.width=s(u);j.width=s(u);L&&(a.nScrollFoot.style.width=s(u));!d&&w&&(n.height=s(t.offsetHeight+f));d&&b.bCollapse&&(n.height=s(d),b=c&&t.offsetWidth>i.offsetWidth?f:0,t.offsetHeight<i.offsetHeight&&(n.height=s(t.offsetHeight+b)));b=r.outerWidth();l[0].style.width=s(b);o.width=s(b);l=r.height()>i.clientHeight||
"scroll"==q.css("overflow-y");ha="padding"+(ha.bScrollbarLeft?"Left":"Right");o[ha]=l?f+"px":"0px";L&&(p[0].style.width=s(b),k[0].style.width=s(b),k[0].style[ha]=l?f+"px":"0px");q.scroll();if((a.bSorted||a.bFiltered)&&!a._drawHold)i.scrollTop=0}function G(a,b,c){for(var e=0,d=0,f=b.length,g,j;d<f;){g=b[d].firstChild;for(j=c?c[d].firstChild:null;g;)1===g.nodeType&&(c?a(g,j,e):a(g,e),e++),g=g.nextSibling,j=c?j.nextSibling:null;d++}}function Ga(a){var b=a.nTable,c=a.aoColumns,e=a.oScroll,d=e.sY,f=e.sX,
g=e.sXInner,j=c.length,e=Z(a,"bVisible"),i=h("th",a.nTHead),o=b.getAttribute("width"),l=b.parentNode,k=!1,n,m;(n=b.style.width)&&-1!==n.indexOf("%")&&(o=n);for(n=0;n<e.length;n++)m=c[e[n]],null!==m.sWidth&&(m.sWidth=Db(m.sWidthOrig,l),k=!0);if(!k&&!f&&!d&&j==aa(a)&&j==i.length)for(n=0;n<j;n++)c[n].sWidth=s(i.eq(n).width());else{j=h(b).clone().css("visibility","hidden").removeAttr("id");j.find("tbody tr").remove();var p=h("<tr/>").appendTo(j.find("tbody"));j.find("tfoot th, tfoot td").css("width",
"");i=qa(a,j.find("thead")[0]);for(n=0;n<e.length;n++)m=c[e[n]],i[n].style.width=null!==m.sWidthOrig&&""!==m.sWidthOrig?s(m.sWidthOrig):"";if(a.aoData.length)for(n=0;n<e.length;n++)k=e[n],m=c[k],h(Eb(a,k)).clone(!1).append(m.sContentPadding).appendTo(p);j.appendTo(l);f&&g?j.width(g):f?(j.css("width","auto"),j.width()<l.offsetWidth&&j.width(l.offsetWidth)):d?j.width(l.offsetWidth):o&&j.width(o);Fb(a,j[0]);if(f){for(n=g=0;n<e.length;n++)m=c[e[n]],d=h(i[n]).outerWidth(),g+=null===m.sWidthOrig?d:parseInt(m.sWidth,
10)+d-h(i[n]).width();j.width(s(g));b.style.width=s(g)}for(n=0;n<e.length;n++)if(m=c[e[n]],d=h(i[n]).width())m.sWidth=s(d);b.style.width=s(j.css("width"));j.remove()}o&&(b.style.width=s(o));if((o||f)&&!a._reszEvt)b=function(){h(Ea).bind("resize.DT-"+a.sInstance,ua(function(){X(a)}))},a.oBrowser.bScrollOversize?setTimeout(b,1E3):b(),a._reszEvt=!0}function ua(a,b){var c=b!==k?b:200,e,d;return function(){var b=this,g=+new Date,j=arguments;e&&g<e+c?(clearTimeout(d),d=setTimeout(function(){e=k;a.apply(b,
j)},c)):(e=g,a.apply(b,j))}}function Db(a,b){if(!a)return 0;var c=h("<div/>").css("width",s(a)).appendTo(b||Q.body),e=c[0].offsetWidth;c.remove();return e}function Fb(a,b){var c=a.oScroll;if(c.sX||c.sY)c=!c.sX?c.iBarWidth:0,b.style.width=s(h(b).outerWidth()-c)}function Eb(a,b){var c=Gb(a,b);if(0>c)return null;var e=a.aoData[c];return!e.nTr?h("<td/>").html(x(a,c,b,"display"))[0]:e.anCells[b]}function Gb(a,b){for(var c,e=-1,d=-1,f=0,g=a.aoData.length;f<g;f++)c=x(a,f,b,"display")+"",c=c.replace($b,""),
c.length>e&&(e=c.length,d=f);return d}function s(a){return null===a?"0px":"number"==typeof a?0>a?"0px":a+"px":a.match(/\d$/)?a+"px":a}function Hb(){var a=m.__scrollbarWidth;if(a===k){var b=h("<p/>").css({position:"absolute",top:0,left:0,width:"100%",height:150,padding:0,overflow:"scroll",visibility:"hidden"}).appendTo("body"),a=b[0].offsetWidth-b[0].clientWidth;m.__scrollbarWidth=a;b.remove()}return a}function U(a){var b,c,e=[],d=a.aoColumns,f,g,j,i;b=a.aaSortingFixed;c=h.isPlainObject(b);var o=[];
f=function(a){a.length&&!h.isArray(a[0])?o.push(a):o.push.apply(o,a)};h.isArray(b)&&f(b);c&&b.pre&&f(b.pre);f(a.aaSorting);c&&b.post&&f(b.post);for(a=0;a<o.length;a++){i=o[a][0];f=d[i].aDataSort;b=0;for(c=f.length;b<c;b++)g=f[b],j=d[g].sType||"string",o[a]._idx===k&&(o[a]._idx=h.inArray(o[a][1],d[g].asSorting)),e.push({src:i,col:g,dir:o[a][1],index:o[a]._idx,type:j,formatter:m.ext.type.order[j+"-pre"]})}return e}function lb(a){var b,c,e=[],d=m.ext.type.order,f=a.aoData,g=0,j,i=a.aiDisplayMaster,h;
Ha(a);h=U(a);b=0;for(c=h.length;b<c;b++)j=h[b],j.formatter&&g++,Ib(a,j.col);if("ssp"!=B(a)&&0!==h.length){b=0;for(c=i.length;b<c;b++)e[i[b]]=b;g===h.length?i.sort(function(a,b){var c,d,g,j,i=h.length,k=f[a]._aSortData,m=f[b]._aSortData;for(g=0;g<i;g++)if(j=h[g],c=k[j.col],d=m[j.col],c=c<d?-1:c>d?1:0,0!==c)return"asc"===j.dir?c:-c;c=e[a];d=e[b];return c<d?-1:c>d?1:0}):i.sort(function(a,b){var c,g,j,i,k=h.length,m=f[a]._aSortData,r=f[b]._aSortData;for(j=0;j<k;j++)if(i=h[j],c=m[i.col],g=r[i.col],i=d[i.type+
"-"+i.dir]||d["string-"+i.dir],c=i(c,g),0!==c)return c;c=e[a];g=e[b];return c<g?-1:c>g?1:0})}a.bSorted=!0}function Jb(a){for(var b,c,e=a.aoColumns,d=U(a),a=a.oLanguage.oAria,f=0,g=e.length;f<g;f++){c=e[f];var j=c.asSorting;b=c.sTitle.replace(/<.*?>/g,"");var i=c.nTh;i.removeAttribute("aria-sort");c.bSortable&&(0<d.length&&d[0].col==f?(i.setAttribute("aria-sort","asc"==d[0].dir?"ascending":"descending"),c=j[d[0].index+1]||j[0]):c=j[0],b+="asc"===c?a.sSortAscending:a.sSortDescending);i.setAttribute("aria-label",
b)}}function Ua(a,b,c,e){var d=a.aaSorting,f=a.aoColumns[b].asSorting,g=function(a,b){var c=a._idx;c===k&&(c=h.inArray(a[1],f));return c+1<f.length?c+1:b?null:0};"number"===typeof d[0]&&(d=a.aaSorting=[d]);c&&a.oFeatures.bSortMulti?(c=h.inArray(b,D(d,"0")),-1!==c?(b=g(d[c],!0),null===b&&1===d.length&&(b=0),null===b?d.splice(c,1):(d[c][1]=f[b],d[c]._idx=b)):(d.push([b,f[0],0]),d[d.length-1]._idx=0)):d.length&&d[0][0]==b?(b=g(d[0]),d.length=1,d[0][1]=f[b],d[0]._idx=b):(d.length=0,d.push([b,f[0]]),d[0]._idx=
0);N(a);"function"==typeof e&&e(a)}function Oa(a,b,c,e){var d=a.aoColumns[c];Va(b,{},function(b){!1!==d.bSortable&&(a.oFeatures.bProcessing?(C(a,!0),setTimeout(function(){Ua(a,c,b.shiftKey,e);"ssp"!==B(a)&&C(a,!1)},0)):Ua(a,c,b.shiftKey,e))})}function xa(a){var b=a.aLastSort,c=a.oClasses.sSortColumn,e=U(a),d=a.oFeatures,f,g;if(d.bSort&&d.bSortClasses){d=0;for(f=b.length;d<f;d++)g=b[d].src,h(D(a.aoData,"anCells",g)).removeClass(c+(2>d?d+1:3));d=0;for(f=e.length;d<f;d++)g=e[d].src,h(D(a.aoData,"anCells",
g)).addClass(c+(2>d?d+1:3))}a.aLastSort=e}function Ib(a,b){var c=a.aoColumns[b],e=m.ext.order[c.sSortDataType],d;e&&(d=e.call(a.oInstance,a,b,$(a,b)));for(var f,g=m.ext.type.order[c.sType+"-pre"],j=0,i=a.aoData.length;j<i;j++)if(c=a.aoData[j],c._aSortData||(c._aSortData=[]),!c._aSortData[b]||e)f=e?d[j]:x(a,j,b,"sort"),c._aSortData[b]=g?g(f):f}function ya(a){if(a.oFeatures.bStateSave&&!a.bDestroying){var b={time:+new Date,start:a._iDisplayStart,length:a._iDisplayLength,order:h.extend(!0,[],a.aaSorting),
search:zb(a.oPreviousSearch),columns:h.map(a.aoColumns,function(b,e){return{visible:b.bVisible,search:zb(a.aoPreSearchCols[e])}})};w(a,"aoStateSaveParams","stateSaveParams",[a,b]);a.oSavedState=b;a.fnStateSaveCallback.call(a.oInstance,a,b)}}function Kb(a){var b,c,e=a.aoColumns;if(a.oFeatures.bStateSave){var d=a.fnStateLoadCallback.call(a.oInstance,a);if(d&&d.time&&(b=w(a,"aoStateLoadParams","stateLoadParams",[a,d]),-1===h.inArray(!1,b)&&(b=a.iStateDuration,!(0<b&&d.time<+new Date-1E3*b)&&e.length===
d.columns.length))){a.oLoadedState=h.extend(!0,{},d);d.start!==k&&(a._iDisplayStart=d.start,a.iInitDisplayStart=d.start);d.length!==k&&(a._iDisplayLength=d.length);d.order!==k&&(a.aaSorting=[],h.each(d.order,function(b,c){a.aaSorting.push(c[0]>=e.length?[0,c[1]]:c)}));d.search!==k&&h.extend(a.oPreviousSearch,Ab(d.search));b=0;for(c=d.columns.length;b<c;b++){var f=d.columns[b];f.visible!==k&&(e[b].bVisible=f.visible);f.search!==k&&h.extend(a.aoPreSearchCols[b],Ab(f.search))}w(a,"aoStateLoaded","stateLoaded",
[a,d])}}}function za(a){var b=m.settings,a=h.inArray(a,D(b,"nTable"));return-1!==a?b[a]:null}function I(a,b,c,e){c="DataTables warning: "+(null!==a?"table id="+a.sTableId+" - ":"")+c;e&&(c+=". For more information about this error, please see http://datatables.net/tn/"+e);if(b)Ea.console&&console.log&&console.log(c);else if(b=m.ext,b=b.sErrMode||b.errMode,w(a,null,"error",[a,e,c]),"alert"==b)alert(c);else{if("throw"==b)throw Error(c);"function"==typeof b&&b(a,e,c)}}function E(a,b,c,e){h.isArray(c)?
h.each(c,function(c,f){h.isArray(f)?E(a,b,f[0],f[1]):E(a,b,f)}):(e===k&&(e=c),b[c]!==k&&(a[e]=b[c]))}function Lb(a,b,c){var e,d;for(d in b)b.hasOwnProperty(d)&&(e=b[d],h.isPlainObject(e)?(h.isPlainObject(a[d])||(a[d]={}),h.extend(!0,a[d],e)):a[d]=c&&"data"!==d&&"aaData"!==d&&h.isArray(e)?e.slice():e);return a}function Va(a,b,c){h(a).bind("click.DT",b,function(b){a.blur();c(b)}).bind("keypress.DT",b,function(a){13===a.which&&(a.preventDefault(),c(a))}).bind("selectstart.DT",function(){return!1})}function z(a,
b,c,e){c&&a[b].push({fn:c,sName:e})}function w(a,b,c,e){var d=[];b&&(d=h.map(a[b].slice().reverse(),function(b){return b.fn.apply(a.oInstance,e)}));null!==c&&(b=h.Event(c+".dt"),h(a.nTable).trigger(b,e),d.push(b.result));return d}function Sa(a){var b=a._iDisplayStart,c=a.fnDisplayEnd(),e=a._iDisplayLength;b>=c&&(b=c-e);b-=b%e;if(-1===e||0>b)b=0;a._iDisplayStart=b}function Pa(a,b){var c=a.renderer,e=m.ext.renderer[b];return h.isPlainObject(c)&&c[b]?e[c[b]]||e._:"string"===typeof c?e[c]||e._:e._}function B(a){return a.oFeatures.bServerSide?
"ssp":a.ajax||a.sAjaxSource?"ajax":"dom"}function Wa(a,b){var c=[],c=Mb.numbers_length,e=Math.floor(c/2);b<=c?c=V(0,b):a<=e?(c=V(0,c-2),c.push("ellipsis"),c.push(b-1)):(a>=b-1-e?c=V(b-(c-2),b):(c=V(a-e+2,a+e-1),c.push("ellipsis"),c.push(b-1)),c.splice(0,0,"ellipsis"),c.splice(0,0,0));c.DT_el="span";return c}function db(a){h.each({num:function(b){return Aa(b,a)},"num-fmt":function(b){return Aa(b,a,Xa)},"html-num":function(b){return Aa(b,a,Ba)},"html-num-fmt":function(b){return Aa(b,a,Ba,Xa)}},function(b,
c){u.type.order[b+a+"-pre"]=c;b.match(/^html\-/)&&(u.type.search[b+a]=u.type.search.html)})}function Nb(a){return function(){var b=[za(this[m.ext.iApiIndex])].concat(Array.prototype.slice.call(arguments));return m.ext.internal[a].apply(this,b)}}var m,u,t,r,v,Ya={},Ob=/[\r\n]/g,Ba=/<.*?>/g,ac=/^[\w\+\-]/,bc=/[\w\+\-]$/,Yb=RegExp("(\\/|\\.|\\*|\\+|\\?|\\||\\(|\\)|\\[|\\]|\\{|\\}|\\\\|\\$|\\^|\\-)","g"),Xa=/[',$\u00a3\u20ac\u00a5%\u2009\u202F\u20BD\u20a9\u20BArfk]/gi,J=function(a){return!a||!0===a||
"-"===a?!0:!1},Pb=function(a){var b=parseInt(a,10);return!isNaN(b)&&isFinite(a)?b:null},Qb=function(a,b){Ya[b]||(Ya[b]=RegExp(va(b),"g"));return"string"===typeof a&&"."!==b?a.replace(/\./g,"").replace(Ya[b],"."):a},Za=function(a,b,c){var e="string"===typeof a;if(J(a))return!0;b&&e&&(a=Qb(a,b));c&&e&&(a=a.replace(Xa,""));return!isNaN(parseFloat(a))&&isFinite(a)},Rb=function(a,b,c){return J(a)?!0:!(J(a)||"string"===typeof a)?null:Za(a.replace(Ba,""),b,c)?!0:null},D=function(a,b,c){var e=[],d=0,f=a.length;
if(c!==k)for(;d<f;d++)a[d]&&a[d][b]&&e.push(a[d][b][c]);else for(;d<f;d++)a[d]&&e.push(a[d][b]);return e},ia=function(a,b,c,e){var d=[],f=0,g=b.length;if(e!==k)for(;f<g;f++)a[b[f]][c]&&d.push(a[b[f]][c][e]);else for(;f<g;f++)d.push(a[b[f]][c]);return d},V=function(a,b){var c=[],e;b===k?(b=0,e=a):(e=b,b=a);for(var d=b;d<e;d++)c.push(d);return c},Sb=function(a){for(var b=[],c=0,e=a.length;c<e;c++)a[c]&&b.push(a[c]);return b},Na=function(a){var b=[],c,e,d=a.length,f,g=0;e=0;a:for(;e<d;e++){c=a[e];for(f=
0;f<g;f++)if(b[f]===c)continue a;b.push(c);g++}return b},A=function(a,b,c){a[b]!==k&&(a[c]=a[b])},ba=/\[.*?\]$/,T=/\(\)$/,wa=h("<div>")[0],Zb=wa.textContent!==k,$b=/<.*?>/g;m=function(a){this.$=function(a,b){return this.api(!0).$(a,b)};this._=function(a,b){return this.api(!0).rows(a,b).data()};this.api=function(a){return a?new t(za(this[u.iApiIndex])):new t(this)};this.fnAddData=function(a,b){var c=this.api(!0),e=h.isArray(a)&&(h.isArray(a[0])||h.isPlainObject(a[0]))?c.rows.add(a):c.row.add(a);(b===
k||b)&&c.draw();return e.flatten().toArray()};this.fnAdjustColumnSizing=function(a){var b=this.api(!0).columns.adjust(),c=b.settings()[0],e=c.oScroll;a===k||a?b.draw(!1):(""!==e.sX||""!==e.sY)&&Y(c)};this.fnClearTable=function(a){var b=this.api(!0).clear();(a===k||a)&&b.draw()};this.fnClose=function(a){this.api(!0).row(a).child.hide()};this.fnDeleteRow=function(a,b,c){var e=this.api(!0),a=e.rows(a),d=a.settings()[0],h=d.aoData[a[0][0]];a.remove();b&&b.call(this,d,h);(c===k||c)&&e.draw();return h};
this.fnDestroy=function(a){this.api(!0).destroy(a)};this.fnDraw=function(a){this.api(!0).draw(a)};this.fnFilter=function(a,b,c,e,d,h){d=this.api(!0);null===b||b===k?d.search(a,c,e,h):d.column(b).search(a,c,e,h);d.draw()};this.fnGetData=function(a,b){var c=this.api(!0);if(a!==k){var e=a.nodeName?a.nodeName.toLowerCase():"";return b!==k||"td"==e||"th"==e?c.cell(a,b).data():c.row(a).data()||null}return c.data().toArray()};this.fnGetNodes=function(a){var b=this.api(!0);return a!==k?b.row(a).node():b.rows().nodes().flatten().toArray()};
this.fnGetPosition=function(a){var b=this.api(!0),c=a.nodeName.toUpperCase();return"TR"==c?b.row(a).index():"TD"==c||"TH"==c?(a=b.cell(a).index(),[a.row,a.columnVisible,a.column]):null};this.fnIsOpen=function(a){return this.api(!0).row(a).child.isShown()};this.fnOpen=function(a,b,c){return this.api(!0).row(a).child(b,c).show().child()[0]};this.fnPageChange=function(a,b){var c=this.api(!0).page(a);(b===k||b)&&c.draw(!1)};this.fnSetColumnVis=function(a,b,c){a=this.api(!0).column(a).visible(b);(c===
k||c)&&a.columns.adjust().draw()};this.fnSettings=function(){return za(this[u.iApiIndex])};this.fnSort=function(a){this.api(!0).order(a).draw()};this.fnSortListener=function(a,b,c){this.api(!0).order.listener(a,b,c)};this.fnUpdate=function(a,b,c,e,d){var h=this.api(!0);c===k||null===c?h.row(b).data(a):h.cell(b,c).data(a);(d===k||d)&&h.columns.adjust();(e===k||e)&&h.draw();return 0};this.fnVersionCheck=u.fnVersionCheck;var b=this,c=a===k,e=this.length;c&&(a={});this.oApi=this.internal=u.internal;for(var d in m.ext.internal)d&&
(this[d]=Nb(d));this.each(function(){var d={},d=1<e?Lb(d,a,!0):a,g=0,j,i=this.getAttribute("id"),o=!1,l=m.defaults,q=h(this);if("table"!=this.nodeName.toLowerCase())I(null,0,"Non-table node initialisation ("+this.nodeName+")",2);else{eb(l);fb(l.column);H(l,l,!0);H(l.column,l.column,!0);H(l,h.extend(d,q.data()));var n=m.settings,g=0;for(j=n.length;g<j;g++){var r=n[g];if(r.nTable==this||r.nTHead.parentNode==this||r.nTFoot&&r.nTFoot.parentNode==this){g=d.bRetrieve!==k?d.bRetrieve:l.bRetrieve;if(c||g)return r.oInstance;
if(d.bDestroy!==k?d.bDestroy:l.bDestroy){r.oInstance.fnDestroy();break}else{I(r,0,"Cannot reinitialise DataTable",3);return}}if(r.sTableId==this.id){n.splice(g,1);break}}if(null===i||""===i)this.id=i="DataTables_Table_"+m.ext._unique++;var p=h.extend(!0,{},m.models.oSettings,{sDestroyWidth:q[0].style.width,sInstance:i,sTableId:i});p.nTable=this;p.oApi=b.internal;p.oInit=d;n.push(p);p.oInstance=1===b.length?b:q.dataTable();eb(d);d.oLanguage&&P(d.oLanguage);d.aLengthMenu&&!d.iDisplayLength&&(d.iDisplayLength=
h.isArray(d.aLengthMenu[0])?d.aLengthMenu[0][0]:d.aLengthMenu[0]);d=Lb(h.extend(!0,{},l),d);E(p.oFeatures,d,"bPaginate bLengthChange bFilter bSort bSortMulti bInfo bProcessing bAutoWidth bSortClasses bServerSide bDeferRender".split(" "));E(p,d,["asStripeClasses","ajax","fnServerData","fnFormatNumber","sServerMethod","aaSorting","aaSortingFixed","aLengthMenu","sPaginationType","sAjaxSource","sAjaxDataProp","iStateDuration","sDom","bSortCellsTop","iTabIndex","fnStateLoadCallback","fnStateSaveCallback",
"renderer","searchDelay",["iCookieDuration","iStateDuration"],["oSearch","oPreviousSearch"],["aoSearchCols","aoPreSearchCols"],["iDisplayLength","_iDisplayLength"],["bJQueryUI","bJUI"]]);E(p.oScroll,d,[["sScrollX","sX"],["sScrollXInner","sXInner"],["sScrollY","sY"],["bScrollCollapse","bCollapse"]]);E(p.oLanguage,d,"fnInfoCallback");z(p,"aoDrawCallback",d.fnDrawCallback,"user");z(p,"aoServerParams",d.fnServerParams,"user");z(p,"aoStateSaveParams",d.fnStateSaveParams,"user");z(p,"aoStateLoadParams",
d.fnStateLoadParams,"user");z(p,"aoStateLoaded",d.fnStateLoaded,"user");z(p,"aoRowCallback",d.fnRowCallback,"user");z(p,"aoRowCreatedCallback",d.fnCreatedRow,"user");z(p,"aoHeaderCallback",d.fnHeaderCallback,"user");z(p,"aoFooterCallback",d.fnFooterCallback,"user");z(p,"aoInitComplete",d.fnInitComplete,"user");z(p,"aoPreDrawCallback",d.fnPreDrawCallback,"user");i=p.oClasses;d.bJQueryUI?(h.extend(i,m.ext.oJUIClasses,d.oClasses),d.sDom===l.sDom&&"lfrtip"===l.sDom&&(p.sDom='<"H"lfr>t<"F"ip>'),p.renderer)?
h.isPlainObject(p.renderer)&&!p.renderer.header&&(p.renderer.header="jqueryui"):p.renderer="jqueryui":h.extend(i,m.ext.classes,d.oClasses);q.addClass(i.sTable);if(""!==p.oScroll.sX||""!==p.oScroll.sY)p.oScroll.iBarWidth=Hb();!0===p.oScroll.sX&&(p.oScroll.sX="100%");p.iInitDisplayStart===k&&(p.iInitDisplayStart=d.iDisplayStart,p._iDisplayStart=d.iDisplayStart);null!==d.iDeferLoading&&(p.bDeferLoading=!0,g=h.isArray(d.iDeferLoading),p._iRecordsDisplay=g?d.iDeferLoading[0]:d.iDeferLoading,p._iRecordsTotal=
g?d.iDeferLoading[1]:d.iDeferLoading);var t=p.oLanguage;h.extend(!0,t,d.oLanguage);""!==t.sUrl&&(h.ajax({dataType:"json",url:t.sUrl,success:function(a){P(a);H(l.oLanguage,a);h.extend(true,t,a);ga(p)},error:function(){ga(p)}}),o=!0);null===d.asStripeClasses&&(p.asStripeClasses=[i.sStripeOdd,i.sStripeEven]);var g=p.asStripeClasses,s=q.children("tbody").find("tr").eq(0);-1!==h.inArray(!0,h.map(g,function(a){return s.hasClass(a)}))&&(h("tbody tr",this).removeClass(g.join(" ")),p.asDestroyStripes=g.slice());
n=[];g=this.getElementsByTagName("thead");0!==g.length&&(da(p.aoHeader,g[0]),n=qa(p));if(null===d.aoColumns){r=[];g=0;for(j=n.length;g<j;g++)r.push(null)}else r=d.aoColumns;g=0;for(j=r.length;g<j;g++)Fa(p,n?n[g]:null);ib(p,d.aoColumnDefs,r,function(a,b){ka(p,a,b)});if(s.length){var u=function(a,b){return a.getAttribute("data-"+b)!==null?b:null};h.each(na(p,s[0]).cells,function(a,b){var c=p.aoColumns[a];if(c.mData===a){var d=u(b,"sort")||u(b,"order"),e=u(b,"filter")||u(b,"search");if(d!==null||e!==
null){c.mData={_:a+".display",sort:d!==null?a+".@data-"+d:k,type:d!==null?a+".@data-"+d:k,filter:e!==null?a+".@data-"+e:k};ka(p,a)}}})}var v=p.oFeatures;d.bStateSave&&(v.bStateSave=!0,Kb(p,d),z(p,"aoDrawCallback",ya,"state_save"));if(d.aaSorting===k){n=p.aaSorting;g=0;for(j=n.length;g<j;g++)n[g][1]=p.aoColumns[g].asSorting[0]}xa(p);v.bSort&&z(p,"aoDrawCallback",function(){if(p.bSorted){var a=U(p),b={};h.each(a,function(a,c){b[c.src]=c.dir});w(p,null,"order",[p,a,b]);Jb(p)}});z(p,"aoDrawCallback",
function(){(p.bSorted||B(p)==="ssp"||v.bDeferRender)&&xa(p)},"sc");gb(p);g=q.children("caption").each(function(){this._captionSide=q.css("caption-side")});j=q.children("thead");0===j.length&&(j=h("<thead/>").appendTo(this));p.nTHead=j[0];j=q.children("tbody");0===j.length&&(j=h("<tbody/>").appendTo(this));p.nTBody=j[0];j=q.children("tfoot");if(0===j.length&&0<g.length&&(""!==p.oScroll.sX||""!==p.oScroll.sY))j=h("<tfoot/>").appendTo(this);0===j.length||0===j.children().length?q.addClass(i.sNoFooter):
0<j.length&&(p.nTFoot=j[0],da(p.aoFooter,p.nTFoot));if(d.aaData)for(g=0;g<d.aaData.length;g++)K(p,d.aaData[g]);else(p.bDeferLoading||"dom"==B(p))&&ma(p,h(p.nTBody).children("tr"));p.aiDisplay=p.aiDisplayMaster.slice();p.bInitialised=!0;!1===o&&ga(p)}});b=null;return this};var Tb=[],y=Array.prototype,cc=function(a){var b,c,e=m.settings,d=h.map(e,function(a){return a.nTable});if(a){if(a.nTable&&a.oApi)return[a];if(a.nodeName&&"table"===a.nodeName.toLowerCase())return b=h.inArray(a,d),-1!==b?[e[b]]:
null;if(a&&"function"===typeof a.settings)return a.settings().toArray();"string"===typeof a?c=h(a):a instanceof h&&(c=a)}else return[];if(c)return c.map(function(){b=h.inArray(this,d);return-1!==b?e[b]:null}).toArray()};t=function(a,b){if(!(this instanceof t))return new t(a,b);var c=[],e=function(a){(a=cc(a))&&c.push.apply(c,a)};if(h.isArray(a))for(var d=0,f=a.length;d<f;d++)e(a[d]);else e(a);this.context=Na(c);b&&this.push.apply(this,b.toArray?b.toArray():b);this.selector={rows:null,cols:null,opts:null};
t.extend(this,this,Tb)};m.Api=t;t.prototype={any:function(){return 0!==this.flatten().length},concat:y.concat,context:[],each:function(a){for(var b=0,c=this.length;b<c;b++)a.call(this,this[b],b,this);return this},eq:function(a){var b=this.context;return b.length>a?new t(b[a],this[a]):null},filter:function(a){var b=[];if(y.filter)b=y.filter.call(this,a,this);else for(var c=0,e=this.length;c<e;c++)a.call(this,this[c],c,this)&&b.push(this[c]);return new t(this.context,b)},flatten:function(){var a=[];
return new t(this.context,a.concat.apply(a,this.toArray()))},join:y.join,indexOf:y.indexOf||function(a,b){for(var c=b||0,e=this.length;c<e;c++)if(this[c]===a)return c;return-1},iterator:function(a,b,c,e){var d=[],f,g,h,i,o,l=this.context,q,n,m=this.selector;"string"===typeof a&&(e=c,c=b,b=a,a=!1);g=0;for(h=l.length;g<h;g++){var p=new t(l[g]);if("table"===b)f=c.call(p,l[g],g),f!==k&&d.push(f);else if("columns"===b||"rows"===b)f=c.call(p,l[g],this[g],g),f!==k&&d.push(f);else if("column"===b||"column-rows"===
b||"row"===b||"cell"===b){n=this[g];"column-rows"===b&&(q=Ca(l[g],m.opts));i=0;for(o=n.length;i<o;i++)f=n[i],f="cell"===b?c.call(p,l[g],f.row,f.column,g,i):c.call(p,l[g],f,g,i,q),f!==k&&d.push(f)}}return d.length||e?(a=new t(l,a?d.concat.apply([],d):d),b=a.selector,b.rows=m.rows,b.cols=m.cols,b.opts=m.opts,a):this},lastIndexOf:y.lastIndexOf||function(a,b){return this.indexOf.apply(this.toArray.reverse(),arguments)},length:0,map:function(a){var b=[];if(y.map)b=y.map.call(this,a,this);else for(var c=
0,e=this.length;c<e;c++)b.push(a.call(this,this[c],c));return new t(this.context,b)},pluck:function(a){return this.map(function(b){return b[a]})},pop:y.pop,push:y.push,reduce:y.reduce||function(a,b){return hb(this,a,b,0,this.length,1)},reduceRight:y.reduceRight||function(a,b){return hb(this,a,b,this.length-1,-1,-1)},reverse:y.reverse,selector:null,shift:y.shift,sort:y.sort,splice:y.splice,toArray:function(){return y.slice.call(this)},to$:function(){return h(this)},toJQuery:function(){return h(this)},
unique:function(){return new t(this.context,Na(this))},unshift:y.unshift};t.extend=function(a,b,c){if(c.length&&b&&(b instanceof t||b.__dt_wrapper)){var e,d,f,g=function(a,b,c){return function(){var d=b.apply(a,arguments);t.extend(d,d,c.methodExt);return d}};e=0;for(d=c.length;e<d;e++)f=c[e],b[f.name]="function"===typeof f.val?g(a,f.val,f):h.isPlainObject(f.val)?{}:f.val,b[f.name].__dt_wrapper=!0,t.extend(a,b[f.name],f.propExt)}};t.register=r=function(a,b){if(h.isArray(a))for(var c=0,e=a.length;c<
e;c++)t.register(a[c],b);else for(var d=a.split("."),f=Tb,g,j,c=0,e=d.length;c<e;c++){g=(j=-1!==d[c].indexOf("()"))?d[c].replace("()",""):d[c];var i;a:{i=0;for(var o=f.length;i<o;i++)if(f[i].name===g){i=f[i];break a}i=null}i||(i={name:g,val:{},methodExt:[],propExt:[]},f.push(i));c===e-1?i.val=b:f=j?i.methodExt:i.propExt}};t.registerPlural=v=function(a,b,c){t.register(a,c);t.register(b,function(){var a=c.apply(this,arguments);return a===this?this:a instanceof t?a.length?h.isArray(a[0])?new t(a.context,
a[0]):a[0]:k:a})};r("tables()",function(a){var b;if(a){b=t;var c=this.context;if("number"===typeof a)a=[c[a]];else var e=h.map(c,function(a){return a.nTable}),a=h(e).filter(a).map(function(){var a=h.inArray(this,e);return c[a]}).toArray();b=new b(a)}else b=this;return b});r("table()",function(a){var a=this.tables(a),b=a.context;return b.length?new t(b[0]):a});v("tables().nodes()","table().node()",function(){return this.iterator("table",function(a){return a.nTable},1)});v("tables().body()","table().body()",
function(){return this.iterator("table",function(a){return a.nTBody},1)});v("tables().header()","table().header()",function(){return this.iterator("table",function(a){return a.nTHead},1)});v("tables().footer()","table().footer()",function(){return this.iterator("table",function(a){return a.nTFoot},1)});v("tables().containers()","table().container()",function(){return this.iterator("table",function(a){return a.nTableWrapper},1)});r("draw()",function(a){return this.iterator("table",function(b){N(b,
!1===a)})});r("page()",function(a){return a===k?this.page.info().page:this.iterator("table",function(b){Ta(b,a)})});r("page.info()",function(){if(0===this.context.length)return k;var a=this.context[0],b=a._iDisplayStart,c=a._iDisplayLength,e=a.fnRecordsDisplay(),d=-1===c;return{page:d?0:Math.floor(b/c),pages:d?1:Math.ceil(e/c),start:b,end:a.fnDisplayEnd(),length:c,recordsTotal:a.fnRecordsTotal(),recordsDisplay:e}});r("page.len()",function(a){return a===k?0!==this.context.length?this.context[0]._iDisplayLength:
k:this.iterator("table",function(b){Ra(b,a)})});var Ub=function(a,b,c){if(c){var e=new t(a);e.one("draw",function(){c(e.ajax.json())})}"ssp"==B(a)?N(a,b):(C(a,!0),ra(a,[],function(c){oa(a);for(var c=sa(a,c),e=0,g=c.length;e<g;e++)K(a,c[e]);N(a,b);C(a,!1)}))};r("ajax.json()",function(){var a=this.context;if(0<a.length)return a[0].json});r("ajax.params()",function(){var a=this.context;if(0<a.length)return a[0].oAjaxData});r("ajax.reload()",function(a,b){return this.iterator("table",function(c){Ub(c,
!1===b,a)})});r("ajax.url()",function(a){var b=this.context;if(a===k){if(0===b.length)return k;b=b[0];return b.ajax?h.isPlainObject(b.ajax)?b.ajax.url:b.ajax:b.sAjaxSource}return this.iterator("table",function(b){h.isPlainObject(b.ajax)?b.ajax.url=a:b.ajax=a})});r("ajax.url().load()",function(a,b){return this.iterator("table",function(c){Ub(c,!1===b,a)})});var $a=function(a,b,c,e,d){var f=[],g,j,i,o,l,q;i=typeof b;if(!b||"string"===i||"function"===i||b.length===k)b=[b];i=0;for(o=b.length;i<o;i++){j=
b[i]&&b[i].split?b[i].split(","):[b[i]];l=0;for(q=j.length;l<q;l++)(g=c("string"===typeof j[l]?h.trim(j[l]):j[l]))&&g.length&&f.push.apply(f,g)}a=u.selector[a];if(a.length){i=0;for(o=a.length;i<o;i++)f=a[i](e,d,f)}return f},ab=function(a){a||(a={});a.filter&&a.search===k&&(a.search=a.filter);return h.extend({search:"none",order:"current",page:"all"},a)},bb=function(a){for(var b=0,c=a.length;b<c;b++)if(0<a[b].length)return a[0]=a[b],a[0].length=1,a.length=1,a.context=[a.context[b]],a;a.length=0;return a},
Ca=function(a,b){var c,e,d,f=[],g=a.aiDisplay;c=a.aiDisplayMaster;var j=b.search;e=b.order;d=b.page;if("ssp"==B(a))return"removed"===j?[]:V(0,c.length);if("current"==d){c=a._iDisplayStart;for(e=a.fnDisplayEnd();c<e;c++)f.push(g[c])}else if("current"==e||"applied"==e)f="none"==j?c.slice():"applied"==j?g.slice():h.map(c,function(a){return-1===h.inArray(a,g)?a:null});else if("index"==e||"original"==e){c=0;for(e=a.aoData.length;c<e;c++)"none"==j?f.push(c):(d=h.inArray(c,g),(-1===d&&"removed"==j||0<=d&&
"applied"==j)&&f.push(c))}return f};r("rows()",function(a,b){a===k?a="":h.isPlainObject(a)&&(b=a,a="");var b=ab(b),c=this.iterator("table",function(c){var d=b;return $a("row",a,function(a){var b=Pb(a);if(b!==null&&!d)return[b];var j=Ca(c,d);if(b!==null&&h.inArray(b,j)!==-1)return[b];if(!a)return j;if(typeof a==="function")return h.map(j,function(b){var d=c.aoData[b];return a(b,d._aData,d.nTr)?b:null});b=Sb(ia(c.aoData,j,"nTr"));return a.nodeName&&h.inArray(a,b)!==-1?[a._DT_RowIndex]:h(b).filter(a).map(function(){return this._DT_RowIndex}).toArray()},
c,d)},1);c.selector.rows=a;c.selector.opts=b;return c});r("rows().nodes()",function(){return this.iterator("row",function(a,b){return a.aoData[b].nTr||k},1)});r("rows().data()",function(){return this.iterator(!0,"rows",function(a,b){return ia(a.aoData,b,"_aData")},1)});v("rows().cache()","row().cache()",function(a){return this.iterator("row",function(b,c){var e=b.aoData[c];return"search"===a?e._aFilterData:e._aSortData},1)});v("rows().invalidate()","row().invalidate()",function(a){return this.iterator("row",
function(b,c){ca(b,c,a)})});v("rows().indexes()","row().index()",function(){return this.iterator("row",function(a,b){return b},1)});v("rows().remove()","row().remove()",function(){var a=this;return this.iterator("row",function(b,c,e){var d=b.aoData;d.splice(c,1);for(var f=0,g=d.length;f<g;f++)null!==d[f].nTr&&(d[f].nTr._DT_RowIndex=f);h.inArray(c,b.aiDisplay);pa(b.aiDisplayMaster,c);pa(b.aiDisplay,c);pa(a[e],c,!1);Sa(b)})});r("rows.add()",function(a){var b=this.iterator("table",function(b){var c,
f,g,h=[];f=0;for(g=a.length;f<g;f++)c=a[f],c.nodeName&&"TR"===c.nodeName.toUpperCase()?h.push(ma(b,c)[0]):h.push(K(b,c));return h},1),c=this.rows(-1);c.pop();c.push.apply(c,b.toArray());return c});r("row()",function(a,b){return bb(this.rows(a,b))});r("row().data()",function(a){var b=this.context;if(a===k)return b.length&&this.length?b[0].aoData[this[0]]._aData:k;b[0].aoData[this[0]]._aData=a;ca(b[0],this[0],"data");return this});r("row().node()",function(){var a=this.context;return a.length&&this.length?
a[0].aoData[this[0]].nTr||null:null});r("row.add()",function(a){a instanceof h&&a.length&&(a=a[0]);var b=this.iterator("table",function(b){return a.nodeName&&"TR"===a.nodeName.toUpperCase()?ma(b,a)[0]:K(b,a)});return this.row(b[0])});var cb=function(a,b){var c=a.context;c.length&&(c=c[0].aoData[b!==k?b:a[0]],c._details&&(c._details.remove(),c._detailsShow=k,c._details=k))},Vb=function(a,b){var c=a.context;if(c.length&&a.length){var e=c[0].aoData[a[0]];if(e._details){(e._detailsShow=b)?e._details.insertAfter(e.nTr):
e._details.detach();var d=c[0],f=new t(d),g=d.aoData;f.off("draw.dt.DT_details column-visibility.dt.DT_details destroy.dt.DT_details");0<D(g,"_details").length&&(f.on("draw.dt.DT_details",function(a,b){d===b&&f.rows({page:"current"}).eq(0).each(function(a){a=g[a];a._detailsShow&&a._details.insertAfter(a.nTr)})}),f.on("column-visibility.dt.DT_details",function(a,b){if(d===b)for(var c,e=aa(b),f=0,h=g.length;f<h;f++)c=g[f],c._details&&c._details.children("td[colspan]").attr("colspan",e)}),f.on("destroy.dt.DT_details",
function(a,b){if(d===b)for(var c=0,e=g.length;c<e;c++)g[c]._details&&cb(f,c)}))}}};r("row().child()",function(a,b){var c=this.context;if(a===k)return c.length&&this.length?c[0].aoData[this[0]]._details:k;if(!0===a)this.child.show();else if(!1===a)cb(this);else if(c.length&&this.length){var e=c[0],c=c[0].aoData[this[0]],d=[],f=function(a,b){if(h.isArray(a)||a instanceof h)for(var c=0,k=a.length;c<k;c++)f(a[c],b);else a.nodeName&&"tr"===a.nodeName.toLowerCase()?d.push(a):(c=h("<tr><td/></tr>").addClass(b),
h("td",c).addClass(b).html(a)[0].colSpan=aa(e),d.push(c[0]))};f(a,b);c._details&&c._details.remove();c._details=h(d);c._detailsShow&&c._details.insertAfter(c.nTr)}return this});r(["row().child.show()","row().child().show()"],function(){Vb(this,!0);return this});r(["row().child.hide()","row().child().hide()"],function(){Vb(this,!1);return this});r(["row().child.remove()","row().child().remove()"],function(){cb(this);return this});r("row().child.isShown()",function(){var a=this.context;return a.length&&
this.length?a[0].aoData[this[0]]._detailsShow||!1:!1});var dc=/^(.+):(name|visIdx|visible)$/,Wb=function(a,b,c,e,d){for(var c=[],e=0,f=d.length;e<f;e++)c.push(x(a,d[e],b));return c};r("columns()",function(a,b){a===k?a="":h.isPlainObject(a)&&(b=a,a="");var b=ab(b),c=this.iterator("table",function(c){var d=a,f=b,g=c.aoColumns,j=D(g,"sName"),i=D(g,"nTh");return $a("column",d,function(a){var b=Pb(a);if(a==="")return V(g.length);if(b!==null)return[b>=0?b:g.length+b];if(typeof a==="function"){var d=Ca(c,
f);return h.map(g,function(b,f){return a(f,Wb(c,f,0,0,d),i[f])?f:null})}var k=typeof a==="string"?a.match(dc):"";if(k)switch(k[2]){case "visIdx":case "visible":b=parseInt(k[1],10);if(b<0){var m=h.map(g,function(a,b){return a.bVisible?b:null});return[m[m.length+b]]}return[la(c,b)];case "name":return h.map(j,function(a,b){return a===k[1]?b:null})}else return h(i).filter(a).map(function(){return h.inArray(this,i)}).toArray()},c,f)},1);c.selector.cols=a;c.selector.opts=b;return c});v("columns().header()",
"column().header()",function(){return this.iterator("column",function(a,b){return a.aoColumns[b].nTh},1)});v("columns().footer()","column().footer()",function(){return this.iterator("column",function(a,b){return a.aoColumns[b].nTf},1)});v("columns().data()","column().data()",function(){return this.iterator("column-rows",Wb,1)});v("columns().dataSrc()","column().dataSrc()",function(){return this.iterator("column",function(a,b){return a.aoColumns[b].mData},1)});v("columns().cache()","column().cache()",
function(a){return this.iterator("column-rows",function(b,c,e,d,f){return ia(b.aoData,f,"search"===a?"_aFilterData":"_aSortData",c)},1)});v("columns().nodes()","column().nodes()",function(){return this.iterator("column-rows",function(a,b,c,e,d){return ia(a.aoData,d,"anCells",b)},1)});v("columns().visible()","column().visible()",function(a,b){return this.iterator("column",function(c,e){if(a===k)return c.aoColumns[e].bVisible;var d=c.aoColumns,f=d[e],g=c.aoData,j,i,m;if(a!==k&&f.bVisible!==a){if(a){var l=
h.inArray(!0,D(d,"bVisible"),e+1);j=0;for(i=g.length;j<i;j++)m=g[j].nTr,d=g[j].anCells,m&&m.insertBefore(d[e],d[l]||null)}else h(D(c.aoData,"anCells",e)).detach();f.bVisible=a;ea(c,c.aoHeader);ea(c,c.aoFooter);if(b===k||b)X(c),(c.oScroll.sX||c.oScroll.sY)&&Y(c);w(c,null,"column-visibility",[c,e,a]);ya(c)}})});v("columns().indexes()","column().index()",function(a){return this.iterator("column",function(b,c){return"visible"===a?$(b,c):c},1)});r("columns.adjust()",function(){return this.iterator("table",
function(a){X(a)},1)});r("column.index()",function(a,b){if(0!==this.context.length){var c=this.context[0];if("fromVisible"===a||"toData"===a)return la(c,b);if("fromData"===a||"toVisible"===a)return $(c,b)}});r("column()",function(a,b){return bb(this.columns(a,b))});r("cells()",function(a,b,c){h.isPlainObject(a)&&(a.row===k?(c=a,a=null):(c=b,b=null));h.isPlainObject(b)&&(c=b,b=null);if(null===b||b===k)return this.iterator("table",function(b){var d=a,e=ab(c),f=b.aoData,g=Ca(b,e),i=Sb(ia(f,g,"anCells")),
j=h([].concat.apply([],i)),l,m=b.aoColumns.length,o,r,t,s,u,v;return $a("cell",d,function(a){var c=typeof a==="function";if(a===null||a===k||c){o=[];r=0;for(t=g.length;r<t;r++){l=g[r];for(s=0;s<m;s++){u={row:l,column:s};if(c){v=b.aoData[l];a(u,x(b,l,s),v.anCells?v.anCells[s]:null)&&o.push(u)}else o.push(u)}}return o}return h.isPlainObject(a)?[a]:j.filter(a).map(function(a,b){l=b.parentNode._DT_RowIndex;return{row:l,column:h.inArray(b,f[l].anCells)}}).toArray()},b,e)});var e=this.columns(b,c),d=this.rows(a,
c),f,g,j,i,m,l=this.iterator("table",function(a,b){f=[];g=0;for(j=d[b].length;g<j;g++){i=0;for(m=e[b].length;i<m;i++)f.push({row:d[b][g],column:e[b][i]})}return f},1);h.extend(l.selector,{cols:b,rows:a,opts:c});return l});v("cells().nodes()","cell().node()",function(){return this.iterator("cell",function(a,b,c){return(a=a.aoData[b].anCells)?a[c]:k},1)});r("cells().data()",function(){return this.iterator("cell",function(a,b,c){return x(a,b,c)},1)});v("cells().cache()","cell().cache()",function(a){a=
"search"===a?"_aFilterData":"_aSortData";return this.iterator("cell",function(b,c,e){return b.aoData[c][a][e]},1)});v("cells().render()","cell().render()",function(a){return this.iterator("cell",function(b,c,e){return x(b,c,e,a)},1)});v("cells().indexes()","cell().index()",function(){return this.iterator("cell",function(a,b,c){return{row:b,column:c,columnVisible:$(a,c)}},1)});v("cells().invalidate()","cell().invalidate()",function(a){return this.iterator("cell",function(b,c,e){ca(b,c,a,e)})});r("cell()",
function(a,b,c){return bb(this.cells(a,b,c))});r("cell().data()",function(a){var b=this.context,c=this[0];if(a===k)return b.length&&c.length?x(b[0],c[0].row,c[0].column):k;Ia(b[0],c[0].row,c[0].column,a);ca(b[0],c[0].row,"data",c[0].column);return this});r("order()",function(a,b){var c=this.context;if(a===k)return 0!==c.length?c[0].aaSorting:k;"number"===typeof a?a=[[a,b]]:h.isArray(a[0])||(a=Array.prototype.slice.call(arguments));return this.iterator("table",function(b){b.aaSorting=a.slice()})});
r("order.listener()",function(a,b,c){return this.iterator("table",function(e){Oa(e,a,b,c)})});r(["columns().order()","column().order()"],function(a){var b=this;return this.iterator("table",function(c,e){var d=[];h.each(b[e],function(b,c){d.push([c,a])});c.aaSorting=d})});r("search()",function(a,b,c,e){var d=this.context;return a===k?0!==d.length?d[0].oPreviousSearch.sSearch:k:this.iterator("table",function(d){d.oFeatures.bFilter&&fa(d,h.extend({},d.oPreviousSearch,{sSearch:a+"",bRegex:null===b?!1:
b,bSmart:null===c?!0:c,bCaseInsensitive:null===e?!0:e}),1)})});v("columns().search()","column().search()",function(a,b,c,e){return this.iterator("column",function(d,f){var g=d.aoPreSearchCols;if(a===k)return g[f].sSearch;d.oFeatures.bFilter&&(h.extend(g[f],{sSearch:a+"",bRegex:null===b?!1:b,bSmart:null===c?!0:c,bCaseInsensitive:null===e?!0:e}),fa(d,d.oPreviousSearch,1))})});r("state()",function(){return this.context.length?this.context[0].oSavedState:null});r("state.clear()",function(){return this.iterator("table",
function(a){a.fnStateSaveCallback.call(a.oInstance,a,{})})});r("state.loaded()",function(){return this.context.length?this.context[0].oLoadedState:null});r("state.save()",function(){return this.iterator("table",function(a){ya(a)})});m.versionCheck=m.fnVersionCheck=function(a){for(var b=m.version.split("."),a=a.split("."),c,e,d=0,f=a.length;d<f;d++)if(c=parseInt(b[d],10)||0,e=parseInt(a[d],10)||0,c!==e)return c>e;return!0};m.isDataTable=m.fnIsDataTable=function(a){var b=h(a).get(0),c=!1;h.each(m.settings,
function(a,d){var f=d.nScrollHead?h("table",d.nScrollHead)[0]:null,g=d.nScrollFoot?h("table",d.nScrollFoot)[0]:null;if(d.nTable===b||f===b||g===b)c=!0});return c};m.tables=m.fnTables=function(a){return h.map(m.settings,function(b){if(!a||a&&h(b.nTable).is(":visible"))return b.nTable})};m.util={throttle:ua,escapeRegex:va};m.camelToHungarian=H;r("$()",function(a,b){var c=this.rows(b).nodes(),c=h(c);return h([].concat(c.filter(a).toArray(),c.find(a).toArray()))});h.each(["on","one","off"],function(a,
b){r(b+"()",function(){var a=Array.prototype.slice.call(arguments);a[0].match(/\.dt\b/)||(a[0]+=".dt");var e=h(this.tables().nodes());e[b].apply(e,a);return this})});r("clear()",function(){return this.iterator("table",function(a){oa(a)})});r("settings()",function(){return new t(this.context,this.context)});r("init()",function(){var a=this.context;return a.length?a[0].oInit:null});r("data()",function(){return this.iterator("table",function(a){return D(a.aoData,"_aData")}).flatten()});r("destroy()",
function(a){a=a||!1;return this.iterator("table",function(b){var c=b.nTableWrapper.parentNode,e=b.oClasses,d=b.nTable,f=b.nTBody,g=b.nTHead,j=b.nTFoot,i=h(d),f=h(f),k=h(b.nTableWrapper),l=h.map(b.aoData,function(a){return a.nTr}),q;b.bDestroying=!0;w(b,"aoDestroyCallback","destroy",[b]);a||(new t(b)).columns().visible(!0);k.unbind(".DT").find(":not(tbody *)").unbind(".DT");h(Ea).unbind(".DT-"+b.sInstance);d!=g.parentNode&&(i.children("thead").detach(),i.append(g));j&&d!=j.parentNode&&(i.children("tfoot").detach(),
i.append(j));i.detach();k.detach();b.aaSorting=[];b.aaSortingFixed=[];xa(b);h(l).removeClass(b.asStripeClasses.join(" "));h("th, td",g).removeClass(e.sSortable+" "+e.sSortableAsc+" "+e.sSortableDesc+" "+e.sSortableNone);b.bJUI&&(h("th span."+e.sSortIcon+", td span."+e.sSortIcon,g).detach(),h("th, td",g).each(function(){var a=h("div."+e.sSortJUIWrapper,this);h(this).append(a.contents());a.detach()}));!a&&c&&c.insertBefore(d,b.nTableReinsertBefore);f.children().detach();f.append(l);i.css("width",b.sDestroyWidth).removeClass(e.sTable);
(q=b.asDestroyStripes.length)&&f.children().each(function(a){h(this).addClass(b.asDestroyStripes[a%q])});c=h.inArray(b,m.settings);-1!==c&&m.settings.splice(c,1)})});h.each(["column","row","cell"],function(a,b){r(b+"s().every()",function(a){return this.iterator(b,function(e,d,f){a.call((new t(e))[b](d,f))})})});r("i18n()",function(a,b,c){var e=this.context[0],a=R(a)(e.oLanguage);a===k&&(a=b);c!==k&&h.isPlainObject(a)&&(a=a[c]!==k?a[c]:a._);return a.replace("%d",c)});m.version="1.10.7";m.settings=
[];m.models={};m.models.oSearch={bCaseInsensitive:!0,sSearch:"",bRegex:!1,bSmart:!0};m.models.oRow={nTr:null,anCells:null,_aData:[],_aSortData:null,_aFilterData:null,_sFilterRow:null,_sRowStripe:"",src:null};m.models.oColumn={idx:null,aDataSort:null,asSorting:null,bSearchable:null,bSortable:null,bVisible:null,_sManualType:null,_bAttrSrc:!1,fnCreatedCell:null,fnGetData:null,fnSetData:null,mData:null,mRender:null,nTh:null,nTf:null,sClass:null,sContentPadding:null,sDefaultContent:null,sName:null,sSortDataType:"std",
sSortingClass:null,sSortingClassJUI:null,sTitle:null,sType:null,sWidth:null,sWidthOrig:null};m.defaults={aaData:null,aaSorting:[[0,"asc"]],aaSortingFixed:[],ajax:null,aLengthMenu:[10,25,50,100],aoColumns:null,aoColumnDefs:null,aoSearchCols:[],asStripeClasses:null,bAutoWidth:!0,bDeferRender:!1,bDestroy:!1,bFilter:!0,bInfo:!0,bJQueryUI:!1,bLengthChange:!0,bPaginate:!0,bProcessing:!1,bRetrieve:!1,bScrollCollapse:!1,bServerSide:!1,bSort:!0,bSortMulti:!0,bSortCellsTop:!1,bSortClasses:!0,bStateSave:!1,
fnCreatedRow:null,fnDrawCallback:null,fnFooterCallback:null,fnFormatNumber:function(a){return a.toString().replace(/\B(?=(\d{3})+(?!\d))/g,this.oLanguage.sThousands)},fnHeaderCallback:null,fnInfoCallback:null,fnInitComplete:null,fnPreDrawCallback:null,fnRowCallback:null,fnServerData:null,fnServerParams:null,fnStateLoadCallback:function(a){try{return JSON.parse((-1===a.iStateDuration?sessionStorage:localStorage).getItem("DataTables_"+a.sInstance+"_"+location.pathname))}catch(b){}},fnStateLoadParams:null,
fnStateLoaded:null,fnStateSaveCallback:function(a,b){try{(-1===a.iStateDuration?sessionStorage:localStorage).setItem("DataTables_"+a.sInstance+"_"+location.pathname,JSON.stringify(b))}catch(c){}},fnStateSaveParams:null,iStateDuration:7200,iDeferLoading:null,iDisplayLength:10,iDisplayStart:0,iTabIndex:0,oClasses:{},oLanguage:{oAria:{sSortAscending:": activate to sort column ascending",sSortDescending:": activate to sort column descending"},oPaginate:{sFirst:"First",sLast:"Last",sNext:"Next",sPrevious:"Previous"},
sEmptyTable:"No data available in table",sInfo:"Showing _START_ to _END_ of _TOTAL_ entries",sInfoEmpty:"Showing 0 to 0 of 0 entries",sInfoFiltered:"(filtered from _MAX_ total entries)",sInfoPostFix:"",sDecimal:"",sThousands:",",sLengthMenu:"Show _MENU_ entries",sLoadingRecords:"Loading...",sProcessing:"Processing...",sSearch:"Search:",sSearchPlaceholder:"",sUrl:"",sZeroRecords:"No matching records found"},oSearch:h.extend({},m.models.oSearch),sAjaxDataProp:"data",sAjaxSource:null,sDom:"lfrtip",searchDelay:null,
sPaginationType:"simple_numbers",sScrollX:"",sScrollXInner:"",sScrollY:"",sServerMethod:"GET",renderer:null};W(m.defaults);m.defaults.column={aDataSort:null,iDataSort:-1,asSorting:["asc","desc"],bSearchable:!0,bSortable:!0,bVisible:!0,fnCreatedCell:null,mData:null,mRender:null,sCellType:"td",sClass:"",sContentPadding:"",sDefaultContent:null,sName:"",sSortDataType:"std",sTitle:null,sType:null,sWidth:null};W(m.defaults.column);m.models.oSettings={oFeatures:{bAutoWidth:null,bDeferRender:null,bFilter:null,
bInfo:null,bLengthChange:null,bPaginate:null,bProcessing:null,bServerSide:null,bSort:null,bSortMulti:null,bSortClasses:null,bStateSave:null},oScroll:{bCollapse:null,iBarWidth:0,sX:null,sXInner:null,sY:null},oLanguage:{fnInfoCallback:null},oBrowser:{bScrollOversize:!1,bScrollbarLeft:!1},ajax:null,aanFeatures:[],aoData:[],aiDisplay:[],aiDisplayMaster:[],aoColumns:[],aoHeader:[],aoFooter:[],oPreviousSearch:{},aoPreSearchCols:[],aaSorting:null,aaSortingFixed:[],asStripeClasses:null,asDestroyStripes:[],
sDestroyWidth:0,aoRowCallback:[],aoHeaderCallback:[],aoFooterCallback:[],aoDrawCallback:[],aoRowCreatedCallback:[],aoPreDrawCallback:[],aoInitComplete:[],aoStateSaveParams:[],aoStateLoadParams:[],aoStateLoaded:[],sTableId:"",nTable:null,nTHead:null,nTFoot:null,nTBody:null,nTableWrapper:null,bDeferLoading:!1,bInitialised:!1,aoOpenRows:[],sDom:null,searchDelay:null,sPaginationType:"two_button",iStateDuration:0,aoStateSave:[],aoStateLoad:[],oSavedState:null,oLoadedState:null,sAjaxSource:null,sAjaxDataProp:null,
bAjaxDataGet:!0,jqXHR:null,json:k,oAjaxData:k,fnServerData:null,aoServerParams:[],sServerMethod:null,fnFormatNumber:null,aLengthMenu:null,iDraw:0,bDrawing:!1,iDrawError:-1,_iDisplayLength:10,_iDisplayStart:0,_iRecordsTotal:0,_iRecordsDisplay:0,bJUI:null,oClasses:{},bFiltered:!1,bSorted:!1,bSortCellsTop:null,oInit:null,aoDestroyCallback:[],fnRecordsTotal:function(){return"ssp"==B(this)?1*this._iRecordsTotal:this.aiDisplayMaster.length},fnRecordsDisplay:function(){return"ssp"==B(this)?1*this._iRecordsDisplay:
this.aiDisplay.length},fnDisplayEnd:function(){var a=this._iDisplayLength,b=this._iDisplayStart,c=b+a,e=this.aiDisplay.length,d=this.oFeatures,f=d.bPaginate;return d.bServerSide?!1===f||-1===a?b+e:Math.min(b+a,this._iRecordsDisplay):!f||c>e||-1===a?e:c},oInstance:null,sInstance:null,iTabIndex:0,nScrollHead:null,nScrollFoot:null,aLastSort:[],oPlugins:{}};m.ext=u={buttons:{},classes:{},errMode:"alert",feature:[],search:[],selector:{cell:[],column:[],row:[]},internal:{},legacy:{ajax:null},pager:{},renderer:{pageButton:{},
header:{}},order:{},type:{detect:[],search:{},order:{}},_unique:0,fnVersionCheck:m.fnVersionCheck,iApiIndex:0,oJUIClasses:{},sVersion:m.version};h.extend(u,{afnFiltering:u.search,aTypes:u.type.detect,ofnSearch:u.type.search,oSort:u.type.order,afnSortData:u.order,aoFeatures:u.feature,oApi:u.internal,oStdClasses:u.classes,oPagination:u.pager});h.extend(m.ext.classes,{sTable:"dataTable",sNoFooter:"no-footer",sPageButton:"paginate_button",sPageButtonActive:"current",sPageButtonDisabled:"disabled",sStripeOdd:"odd",
sStripeEven:"even",sRowEmpty:"dataTables_empty",sWrapper:"dataTables_wrapper",sFilter:"dataTables_filter",sInfo:"dataTables_info",sPaging:"dataTables_paginate paging_",sLength:"dataTables_length",sProcessing:"dataTables_processing",sSortAsc:"sorting_asc",sSortDesc:"sorting_desc",sSortable:"sorting",sSortableAsc:"sorting_asc_disabled",sSortableDesc:"sorting_desc_disabled",sSortableNone:"sorting_disabled",sSortColumn:"sorting_",sFilterInput:"",sLengthSelect:"",sScrollWrapper:"dataTables_scroll",sScrollHead:"dataTables_scrollHead",
sScrollHeadInner:"dataTables_scrollHeadInner",sScrollBody:"dataTables_scrollBody",sScrollFoot:"dataTables_scrollFoot",sScrollFootInner:"dataTables_scrollFootInner",sHeaderTH:"",sFooterTH:"",sSortJUIAsc:"",sSortJUIDesc:"",sSortJUI:"",sSortJUIAscAllowed:"",sSortJUIDescAllowed:"",sSortJUIWrapper:"",sSortIcon:"",sJUIHeader:"",sJUIFooter:""});var Da="",Da="",F=Da+"ui-state-default",ja=Da+"css_right ui-icon ui-icon-",Xb=Da+"fg-toolbar ui-toolbar ui-widget-header ui-helper-clearfix";h.extend(m.ext.oJUIClasses,
m.ext.classes,{sPageButton:"fg-button ui-button "+F,sPageButtonActive:"ui-state-disabled",sPageButtonDisabled:"ui-state-disabled",sPaging:"dataTables_paginate fg-buttonset ui-buttonset fg-buttonset-multi ui-buttonset-multi paging_",sSortAsc:F+" sorting_asc",sSortDesc:F+" sorting_desc",sSortable:F+" sorting",sSortableAsc:F+" sorting_asc_disabled",sSortableDesc:F+" sorting_desc_disabled",sSortableNone:F+" sorting_disabled",sSortJUIAsc:ja+"triangle-1-n",sSortJUIDesc:ja+"triangle-1-s",sSortJUI:ja+"carat-2-n-s",
sSortJUIAscAllowed:ja+"carat-1-n",sSortJUIDescAllowed:ja+"carat-1-s",sSortJUIWrapper:"DataTables_sort_wrapper",sSortIcon:"DataTables_sort_icon",sScrollHead:"dataTables_scrollHead "+F,sScrollFoot:"dataTables_scrollFoot "+F,sHeaderTH:F,sFooterTH:F,sJUIHeader:Xb+" ui-corner-tl ui-corner-tr",sJUIFooter:Xb+" ui-corner-bl ui-corner-br"});var Mb=m.ext.pager;h.extend(Mb,{simple:function(){return["previous","next"]},full:function(){return["first","previous","next","last"]},simple_numbers:function(a,b){return["previous",
Wa(a,b),"next"]},full_numbers:function(a,b){return["first","previous",Wa(a,b),"next","last"]},_numbers:Wa,numbers_length:7});h.extend(!0,m.ext.renderer,{pageButton:{_:function(a,b,c,e,d,f){var g=a.oClasses,j=a.oLanguage.oPaginate,i,k,l=0,m=function(b,e){var n,r,t,s,u=function(b){Ta(a,b.data.action,true)};n=0;for(r=e.length;n<r;n++){s=e[n];if(h.isArray(s)){t=h("<"+(s.DT_el||"div")+"/>").appendTo(b);m(t,s)}else{k=i="";switch(s){case "ellipsis":b.append('<span class="ellipsis">…</span>');break;
case "first":i=j.sFirst;k=s+(d>0?"":" "+g.sPageButtonDisabled);break;case "previous":i=j.sPrevious;k=s+(d>0?"":" "+g.sPageButtonDisabled);break;case "next":i=j.sNext;k=s+(d<f-1?"":" "+g.sPageButtonDisabled);break;case "last":i=j.sLast;k=s+(d<f-1?"":" "+g.sPageButtonDisabled);break;default:i=s+1;k=d===s?g.sPageButtonActive:""}if(i){t=h("<a>",{"class":g.sPageButton+" "+k,"aria-controls":a.sTableId,"data-dt-idx":l,tabindex:a.iTabIndex,id:c===0&&typeof s==="string"?a.sTableId+"_"+s:null}).html(i).appendTo(b);
Va(t,{action:s},u);l++}}}},n;try{n=h(Q.activeElement).data("dt-idx")}catch(r){}m(h(b).empty(),e);n&&h(b).find("[data-dt-idx="+n+"]").focus()}}});h.extend(m.ext.type.detect,[function(a,b){var c=b.oLanguage.sDecimal;return Za(a,c)?"num"+c:null},function(a){if(a&&!(a instanceof Date)&&(!ac.test(a)||!bc.test(a)))return null;var b=Date.parse(a);return null!==b&&!isNaN(b)||J(a)?"date":null},function(a,b){var c=b.oLanguage.sDecimal;return Za(a,c,!0)?"num-fmt"+c:null},function(a,b){var c=b.oLanguage.sDecimal;
return Rb(a,c)?"html-num"+c:null},function(a,b){var c=b.oLanguage.sDecimal;return Rb(a,c,!0)?"html-num-fmt"+c:null},function(a){return J(a)||"string"===typeof a&&-1!==a.indexOf("<")?"html":null}]);h.extend(m.ext.type.search,{html:function(a){return J(a)?a:"string"===typeof a?a.replace(Ob," ").replace(Ba,""):""},string:function(a){return J(a)?a:"string"===typeof a?a.replace(Ob," "):a}});var Aa=function(a,b,c,e){if(0!==a&&(!a||"-"===a))return-Infinity;b&&(a=Qb(a,b));a.replace&&(c&&(a=a.replace(c,"")),
e&&(a=a.replace(e,"")));return 1*a};h.extend(u.type.order,{"date-pre":function(a){return Date.parse(a)||0},"html-pre":function(a){return J(a)?"":a.replace?a.replace(/<.*?>/g,"").toLowerCase():a+""},"string-pre":function(a){return J(a)?"":"string"===typeof a?a.toLowerCase():!a.toString?"":a.toString()},"string-asc":function(a,b){return a<b?-1:a>b?1:0},"string-desc":function(a,b){return a<b?1:a>b?-1:0}});db("");h.extend(!0,m.ext.renderer,{header:{_:function(a,b,c,e){h(a.nTable).on("order.dt.DT",function(d,
f,g,h){if(a===f){d=c.idx;b.removeClass(c.sSortingClass+" "+e.sSortAsc+" "+e.sSortDesc).addClass(h[d]=="asc"?e.sSortAsc:h[d]=="desc"?e.sSortDesc:c.sSortingClass)}})},jqueryui:function(a,b,c,e){h("<div/>").addClass(e.sSortJUIWrapper).append(b.contents()).append(h("<span/>").addClass(e.sSortIcon+" "+c.sSortingClassJUI)).appendTo(b);h(a.nTable).on("order.dt.DT",function(d,f,g,h){if(a===f){d=c.idx;b.removeClass(e.sSortAsc+" "+e.sSortDesc).addClass(h[d]=="asc"?e.sSortAsc:h[d]=="desc"?e.sSortDesc:c.sSortingClass);
b.find("span."+e.sSortIcon).removeClass(e.sSortJUIAsc+" "+e.sSortJUIDesc+" "+e.sSortJUI+" "+e.sSortJUIAscAllowed+" "+e.sSortJUIDescAllowed).addClass(h[d]=="asc"?e.sSortJUIAsc:h[d]=="desc"?e.sSortJUIDesc:c.sSortingClassJUI)}})}}});m.render={number:function(a,b,c,e){return{display:function(d){if("number"!==typeof d&&"string"!==typeof d)return d;var f=0>d?"-":"",d=Math.abs(parseFloat(d)),g=parseInt(d,10),d=c?b+(d-g).toFixed(c).substring(2):"";return f+(e||"")+g.toString().replace(/\B(?=(\d{3})+(?!\d))/g,
a)+d}}}};h.extend(m.ext.internal,{_fnExternApiFunc:Nb,_fnBuildAjax:ra,_fnAjaxUpdate:kb,_fnAjaxParameters:tb,_fnAjaxUpdateDraw:ub,_fnAjaxDataSrc:sa,_fnAddColumn:Fa,_fnColumnOptions:ka,_fnAdjustColumnSizing:X,_fnVisibleToColumnIndex:la,_fnColumnIndexToVisible:$,_fnVisbleColumns:aa,_fnGetColumns:Z,_fnColumnTypes:Ha,_fnApplyColumnDefs:ib,_fnHungarianMap:W,_fnCamelToHungarian:H,_fnLanguageCompat:P,_fnBrowserDetect:gb,_fnAddData:K,_fnAddTr:ma,_fnNodeToDataIndex:function(a,b){return b._DT_RowIndex!==k?b._DT_RowIndex:
null},_fnNodeToColumnIndex:function(a,b,c){return h.inArray(c,a.aoData[b].anCells)},_fnGetCellData:x,_fnSetCellData:Ia,_fnSplitObjNotation:Ka,_fnGetObjectDataFn:R,_fnSetObjectDataFn:S,_fnGetDataMaster:La,_fnClearTable:oa,_fnDeleteIndex:pa,_fnInvalidate:ca,_fnGetRowElements:na,_fnCreateTr:Ja,_fnBuildHead:jb,_fnDrawHead:ea,_fnDraw:M,_fnReDraw:N,_fnAddOptionsHtml:mb,_fnDetectHeader:da,_fnGetUniqueThs:qa,_fnFeatureHtmlFilter:ob,_fnFilterComplete:fa,_fnFilterCustom:xb,_fnFilterColumn:wb,_fnFilter:vb,_fnFilterCreateSearch:Qa,
_fnEscapeRegex:va,_fnFilterData:yb,_fnFeatureHtmlInfo:rb,_fnUpdateInfo:Bb,_fnInfoMacros:Cb,_fnInitialise:ga,_fnInitComplete:ta,_fnLengthChange:Ra,_fnFeatureHtmlLength:nb,_fnFeatureHtmlPaginate:sb,_fnPageChange:Ta,_fnFeatureHtmlProcessing:pb,_fnProcessingDisplay:C,_fnFeatureHtmlTable:qb,_fnScrollDraw:Y,_fnApplyToChildren:G,_fnCalculateColumnWidths:Ga,_fnThrottle:ua,_fnConvertToWidth:Db,_fnScrollingWidthAdjust:Fb,_fnGetWidestNode:Eb,_fnGetMaxLenString:Gb,_fnStringToCss:s,_fnScrollBarWidth:Hb,_fnSortFlatten:U,
_fnSort:lb,_fnSortAria:Jb,_fnSortListener:Ua,_fnSortAttachListener:Oa,_fnSortingClasses:xa,_fnSortData:Ib,_fnSaveState:ya,_fnLoadState:Kb,_fnSettingsFromNode:za,_fnLog:I,_fnMap:E,_fnBindAction:Va,_fnCallbackReg:z,_fnCallbackFire:w,_fnLengthOverflow:Sa,_fnRenderer:Pa,_fnDataSource:B,_fnRowAttributes:Ma,_fnCalculateEnd:function(){}});h.fn.dataTable=m;h.fn.dataTableSettings=m.settings;h.fn.dataTableExt=m.ext;h.fn.DataTable=function(a){return h(this).dataTable(a).api()};h.each(m,function(a,b){h.fn.DataTable[a]=
b});return h.fn.dataTable};"function"===typeof define&&define.amd?define("datatables",["jquery"],P):"object"===typeof exports?module.exports=P(require("jquery")):jQuery&&!jQuery.fn.dataTable&&P(jQuery)})(window,document);
| panoramix/static/jquery.dataTables.min.js | 0 | https://github.com/apache/superset/commit/6dd81a3e95a9d67be743815ff9bfcd465278b3e9 | [
0.0005412243772298098,
0.00022389426885638386,
0.0001659691333770752,
0.00017072995251510292,
0.00009577579476172104
] |
{
"id": 6,
"code_window": [
" list_columns = ['metric_name', 'verbose_name', 'metric_type' ]\n",
" edit_columns = [\n",
" 'metric_name', 'description', 'verbose_name', 'metric_type',\n",
" 'table', 'expression']\n",
" add_columns = edit_columns\n",
" page_size = 100\n",
"appbuilder.add_view_no_menu(SqlMetricInlineView)\n",
"\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" 'expression', 'table',]\n"
],
"file_path": "panoramix/views.py",
"type": "replace",
"edit_start_line_idx": 65
} | #!/usr/bin/env python
from panoramix import app, config
from subprocess import Popen
if __name__ == "__main__":
if config.DEBUG:
app.run(
host='0.0.0.0',
port=int(config.PANORAMIX_WEBSERVER_PORT),
debug=True)
else:
cmd = (
"gunicorn "
"-w 8 "
"-b 0.0.0.0:{config.PANORAMIX_WEBSERVER_PORT} "
"panoramix:app").format(**locals())
print("Starting server with command: " + cmd)
Popen(cmd, shell=True).wait()
| panoramix/bin/panoramix | 1 | https://github.com/apache/superset/commit/6dd81a3e95a9d67be743815ff9bfcd465278b3e9 | [
0.0001674353115959093,
0.00016705255256965756,
0.00016666979354340583,
0.00016705255256965756,
3.827590262517333e-7
] |
{
"id": 6,
"code_window": [
" list_columns = ['metric_name', 'verbose_name', 'metric_type' ]\n",
" edit_columns = [\n",
" 'metric_name', 'description', 'verbose_name', 'metric_type',\n",
" 'table', 'expression']\n",
" add_columns = edit_columns\n",
" page_size = 100\n",
"appbuilder.add_view_no_menu(SqlMetricInlineView)\n",
"\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" 'expression', 'table',]\n"
],
"file_path": "panoramix/views.py",
"type": "replace",
"edit_start_line_idx": 65
} | # Contributing
Contributions are welcome and are greatly appreciated! Every
little bit helps, and credit will always be given.
You can contribute in many ways:
## Types of Contributions
### Report Bugs
Report bugs through Gihub
If you are reporting a bug, please include:
- Your operating system name and version.
- Any details about your local setup that might be helpful in
troubleshooting.
- Detailed steps to reproduce the bug.
### Fix Bugs
Look through the GitHub issues for bugs. Anything tagged with "bug" is
open to whoever wants to implement it.
### Implement Features
Look through the GitHub issues for features. Anything tagged with
"feature" is open to whoever wants to implement it.
We've created the operators, hooks, macros and executors we needed, but we
made sure that this part of Airflow is extensible. New operators,
hooks and operators are very welcomed!
### Documentation
Airflow could always use better documentation,
whether as part of the official Airflow docs,
in docstrings, `docs/*.rst` or even on the web as blog posts or
articles.
### Submit Feedback
The best way to send feedback is to file an issue on Github.
If you are proposing a feature:
- Explain in detail how it would work.
- Keep the scope as narrow as possible, to make it easier to
implement.
- Remember that this is a volunteer-driven project, and that
contributions are welcome :)
## Latests Documentation
[API Documentation](http://pythonhosted.com/airflow)
## Testing
Install development requirements:
pip install -r requirements.txt
Tests can then be run with:
./run_unit_tests.sh
Lint the project with:
flake8 changes tests
## API documentation
Generate the documentation with:
cd docs && ./build.sh
## Pull Request Guidelines
Before you submit a pull request from your forked repo, check that it
meets these guidelines:
1. The pull request should include tests, either as doctests,
unit tests, or both.
2. If the pull request adds functionality, the docs should be updated
as part of the same PR. Doc string are often sufficient, make
sure to follow the sphinx compatible standards.
3. The pull request should work for Python 2.6, 2.7, and ideally python 3.3.
`from __future__ import ` will be required in every `.py` file soon.
4. Code will be reviewed by re running the unittests, flake8 and syntax
should be as rigorous as the core Python project.
5. Please rebase and resolve all conflicts before submitting.
| CONTRIBUTING.md | 0 | https://github.com/apache/superset/commit/6dd81a3e95a9d67be743815ff9bfcd465278b3e9 | [
0.0001751683885231614,
0.00017043700790964067,
0.00016301176219712943,
0.00017122772987931967,
0.0000033225758215849055
] |
{
"id": 6,
"code_window": [
" list_columns = ['metric_name', 'verbose_name', 'metric_type' ]\n",
" edit_columns = [\n",
" 'metric_name', 'description', 'verbose_name', 'metric_type',\n",
" 'table', 'expression']\n",
" add_columns = edit_columns\n",
" page_size = 100\n",
"appbuilder.add_view_no_menu(SqlMetricInlineView)\n",
"\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" 'expression', 'table',]\n"
],
"file_path": "panoramix/views.py",
"type": "replace",
"edit_start_line_idx": 65
} | recursive-include panoramix/templates *
recursive-include panoramix/static *
| MANIFEST.in | 0 | https://github.com/apache/superset/commit/6dd81a3e95a9d67be743815ff9bfcd465278b3e9 | [
0.00017000186198856682,
0.00017000186198856682,
0.00017000186198856682,
0.00017000186198856682,
0
] |
{
"id": 6,
"code_window": [
" list_columns = ['metric_name', 'verbose_name', 'metric_type' ]\n",
" edit_columns = [\n",
" 'metric_name', 'description', 'verbose_name', 'metric_type',\n",
" 'table', 'expression']\n",
" add_columns = edit_columns\n",
" page_size = 100\n",
"appbuilder.add_view_no_menu(SqlMetricInlineView)\n",
"\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" 'expression', 'table',]\n"
],
"file_path": "panoramix/views.py",
"type": "replace",
"edit_start_line_idx": 65
} |
{% set menu = appbuilder.menu %}
{% set languages = appbuilder.languages %}
<div class="navbar navbar-static-top {{menu.extra_classes}}" role="navigation">
<div class="container-fluid">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
{% if appbuilder.app_icon %}
<a class="navbar-brand" style="padding:10px;" href="{{appbuilder.get_url_for_index}}">
<img width="30" src="{{appbuilder.app_icon}}" >
</a>
{% endif %}
<span class="navbar-brand">
<a href="{{appbuilder.get_url_for_index}}">
{{ appbuilder.app_name }}
</a>
</span>
</div>
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav">
{% include 'appbuilder/navbar_menu.html' %}
</ul>
<ul class="nav navbar-nav navbar-right">
{% include 'appbuilder/navbar_right.html' %}
</ul>
</div>
</div>
</div>
| panoramix/templates/appbuilder/navbar.html | 0 | https://github.com/apache/superset/commit/6dd81a3e95a9d67be743815ff9bfcd465278b3e9 | [
0.00017930506146512926,
0.000174354063346982,
0.00016982527449727058,
0.0001741429732646793,
0.0000042293177102692425
] |
{
"id": 0,
"code_window": [
"\t}\n",
"\n",
"\trowCount := 0\n",
"\ttimeIndex := -1\n",
"\tmetricIndex := -1\n",
"\n",
"\t// check columns of resultset: a column named time is mandatory\n",
"\t// the first text column is treated as metric name unless a column named metric is present\n",
"\tfor i, col := range columnNames {\n",
"\t\tfor _, tc := range e.timeColumnNames {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tmetricPrefix := false\n",
"\tvar metricPrefixValue string\n"
],
"file_path": "pkg/tsdb/sql_engine.go",
"type": "add",
"edit_start_line_idx": 231
} | package tsdb
import (
"container/list"
"context"
"database/sql"
"fmt"
"math"
"strings"
"sync"
"time"
"github.com/grafana/grafana/pkg/log"
"github.com/grafana/grafana/pkg/components/null"
"github.com/go-xorm/core"
"github.com/go-xorm/xorm"
"github.com/grafana/grafana/pkg/components/simplejson"
"github.com/grafana/grafana/pkg/models"
)
// SqlMacroEngine interpolates macros into sql. It takes in the Query to have access to query context and
// timeRange to be able to generate queries that use from and to.
type SqlMacroEngine interface {
Interpolate(query *Query, timeRange *TimeRange, sql string) (string, error)
}
// SqlTableRowTransformer transforms a query result row to RowValues with proper types.
type SqlTableRowTransformer interface {
Transform(columnTypes []*sql.ColumnType, rows *core.Rows) (RowValues, error)
}
type engineCacheType struct {
cache map[int64]*xorm.Engine
versions map[int64]int
sync.Mutex
}
var engineCache = engineCacheType{
cache: make(map[int64]*xorm.Engine),
versions: make(map[int64]int),
}
var NewXormEngine = func(driverName string, connectionString string) (*xorm.Engine, error) {
return xorm.NewEngine(driverName, connectionString)
}
type sqlQueryEndpoint struct {
macroEngine SqlMacroEngine
rowTransformer SqlTableRowTransformer
engine *xorm.Engine
timeColumnNames []string
metricColumnTypes []string
log log.Logger
}
type SqlQueryEndpointConfiguration struct {
DriverName string
Datasource *models.DataSource
ConnectionString string
TimeColumnNames []string
MetricColumnTypes []string
}
var NewSqlQueryEndpoint = func(config *SqlQueryEndpointConfiguration, rowTransformer SqlTableRowTransformer, macroEngine SqlMacroEngine, log log.Logger) (TsdbQueryEndpoint, error) {
queryEndpoint := sqlQueryEndpoint{
rowTransformer: rowTransformer,
macroEngine: macroEngine,
timeColumnNames: []string{"time"},
log: log,
}
if len(config.TimeColumnNames) > 0 {
queryEndpoint.timeColumnNames = config.TimeColumnNames
}
engineCache.Lock()
defer engineCache.Unlock()
if engine, present := engineCache.cache[config.Datasource.Id]; present {
if version := engineCache.versions[config.Datasource.Id]; version == config.Datasource.Version {
queryEndpoint.engine = engine
return &queryEndpoint, nil
}
}
engine, err := NewXormEngine(config.DriverName, config.ConnectionString)
if err != nil {
return nil, err
}
engine.SetMaxOpenConns(10)
engine.SetMaxIdleConns(10)
engineCache.versions[config.Datasource.Id] = config.Datasource.Version
engineCache.cache[config.Datasource.Id] = engine
queryEndpoint.engine = engine
return &queryEndpoint, nil
}
const rowLimit = 1000000
// Query is the main function for the SqlQueryEndpoint
func (e *sqlQueryEndpoint) Query(ctx context.Context, dsInfo *models.DataSource, tsdbQuery *TsdbQuery) (*Response, error) {
result := &Response{
Results: make(map[string]*QueryResult),
}
session := e.engine.NewSession()
defer session.Close()
db := session.DB()
for _, query := range tsdbQuery.Queries {
rawSQL := query.Model.Get("rawSql").MustString()
if rawSQL == "" {
continue
}
queryResult := &QueryResult{Meta: simplejson.New(), RefId: query.RefId}
result.Results[query.RefId] = queryResult
rawSQL, err := e.macroEngine.Interpolate(query, tsdbQuery.TimeRange, rawSQL)
if err != nil {
queryResult.Error = err
continue
}
queryResult.Meta.Set("sql", rawSQL)
rows, err := db.Query(rawSQL)
if err != nil {
queryResult.Error = err
continue
}
defer rows.Close()
format := query.Model.Get("format").MustString("time_series")
switch format {
case "time_series":
err := e.transformToTimeSeries(query, rows, queryResult, tsdbQuery)
if err != nil {
queryResult.Error = err
continue
}
case "table":
err := e.transformToTable(query, rows, queryResult, tsdbQuery)
if err != nil {
queryResult.Error = err
continue
}
}
}
return result, nil
}
func (e *sqlQueryEndpoint) transformToTable(query *Query, rows *core.Rows, result *QueryResult, tsdbQuery *TsdbQuery) error {
columnNames, err := rows.Columns()
columnCount := len(columnNames)
if err != nil {
return err
}
rowCount := 0
timeIndex := -1
table := &Table{
Columns: make([]TableColumn, columnCount),
Rows: make([]RowValues, 0),
}
for i, name := range columnNames {
table.Columns[i].Text = name
for _, tc := range e.timeColumnNames {
if name == tc {
timeIndex = i
break
}
}
}
columnTypes, err := rows.ColumnTypes()
if err != nil {
return err
}
for ; rows.Next(); rowCount++ {
if rowCount > rowLimit {
return fmt.Errorf("query row limit exceeded, limit %d", rowLimit)
}
values, err := e.rowTransformer.Transform(columnTypes, rows)
if err != nil {
return err
}
// converts column named time to unix timestamp in milliseconds
// to make native mssql datetime types and epoch dates work in
// annotation and table queries.
ConvertSqlTimeColumnToEpochMs(values, timeIndex)
table.Rows = append(table.Rows, values)
}
result.Tables = append(result.Tables, table)
result.Meta.Set("rowCount", rowCount)
return nil
}
func (e *sqlQueryEndpoint) transformToTimeSeries(query *Query, rows *core.Rows, result *QueryResult, tsdbQuery *TsdbQuery) error {
pointsBySeries := make(map[string]*TimeSeries)
seriesByQueryOrder := list.New()
columnNames, err := rows.Columns()
if err != nil {
return err
}
columnTypes, err := rows.ColumnTypes()
if err != nil {
return err
}
rowCount := 0
timeIndex := -1
metricIndex := -1
// check columns of resultset: a column named time is mandatory
// the first text column is treated as metric name unless a column named metric is present
for i, col := range columnNames {
for _, tc := range e.timeColumnNames {
if col == tc {
timeIndex = i
continue
}
}
switch col {
case "metric":
metricIndex = i
default:
if metricIndex == -1 {
columnType := columnTypes[i].DatabaseTypeName()
for _, mct := range e.metricColumnTypes {
if columnType == mct {
metricIndex = i
continue
}
}
}
}
}
if timeIndex == -1 {
return fmt.Errorf("Found no column named %s", strings.Join(e.timeColumnNames, " or "))
}
fillMissing := query.Model.Get("fill").MustBool(false)
var fillInterval float64
fillValue := null.Float{}
if fillMissing {
fillInterval = query.Model.Get("fillInterval").MustFloat64() * 1000
if !query.Model.Get("fillNull").MustBool(false) {
fillValue.Float64 = query.Model.Get("fillValue").MustFloat64()
fillValue.Valid = true
}
}
for rows.Next() {
var timestamp float64
var value null.Float
var metric string
if rowCount > rowLimit {
return fmt.Errorf("query row limit exceeded, limit %d", rowLimit)
}
values, err := e.rowTransformer.Transform(columnTypes, rows)
if err != nil {
return err
}
// converts column named time to unix timestamp in milliseconds to make
// native mysql datetime types and epoch dates work in
// annotation and table queries.
ConvertSqlTimeColumnToEpochMs(values, timeIndex)
switch columnValue := values[timeIndex].(type) {
case int64:
timestamp = float64(columnValue)
case float64:
timestamp = columnValue
default:
return fmt.Errorf("Invalid type for column time, must be of type timestamp or unix timestamp, got: %T %v", columnValue, columnValue)
}
if metricIndex >= 0 {
if columnValue, ok := values[metricIndex].(string); ok {
metric = columnValue
} else {
return fmt.Errorf("Column metric must be of type %s. metric column name: %s type: %s but datatype is %T", strings.Join(e.metricColumnTypes, ", "), columnNames[metricIndex], columnTypes[metricIndex].DatabaseTypeName(), values[metricIndex])
}
}
for i, col := range columnNames {
if i == timeIndex || i == metricIndex {
continue
}
if value, err = ConvertSqlValueColumnToFloat(col, values[i]); err != nil {
return err
}
if metricIndex == -1 {
metric = col
}
series, exist := pointsBySeries[metric]
if !exist {
series = &TimeSeries{Name: metric}
pointsBySeries[metric] = series
seriesByQueryOrder.PushBack(metric)
}
if fillMissing {
var intervalStart float64
if !exist {
intervalStart = float64(tsdbQuery.TimeRange.MustGetFrom().UnixNano() / 1e6)
} else {
intervalStart = series.Points[len(series.Points)-1][1].Float64 + fillInterval
}
// align interval start
intervalStart = math.Floor(intervalStart/fillInterval) * fillInterval
for i := intervalStart; i < timestamp; i += fillInterval {
series.Points = append(series.Points, TimePoint{fillValue, null.FloatFrom(i)})
rowCount++
}
}
series.Points = append(series.Points, TimePoint{value, null.FloatFrom(timestamp)})
e.log.Debug("Rows", "metric", metric, "time", timestamp, "value", value)
}
}
for elem := seriesByQueryOrder.Front(); elem != nil; elem = elem.Next() {
key := elem.Value.(string)
result.Series = append(result.Series, pointsBySeries[key])
if fillMissing {
series := pointsBySeries[key]
// fill in values from last fetched value till interval end
intervalStart := series.Points[len(series.Points)-1][1].Float64
intervalEnd := float64(tsdbQuery.TimeRange.MustGetTo().UnixNano() / 1e6)
// align interval start
intervalStart = math.Floor(intervalStart/fillInterval) * fillInterval
for i := intervalStart + fillInterval; i < intervalEnd; i += fillInterval {
series.Points = append(series.Points, TimePoint{fillValue, null.FloatFrom(i)})
rowCount++
}
}
}
result.Meta.Set("rowCount", rowCount)
return nil
}
// ConvertSqlTimeColumnToEpochMs converts column named time to unix timestamp in milliseconds
// to make native datetime types and epoch dates work in annotation and table queries.
func ConvertSqlTimeColumnToEpochMs(values RowValues, timeIndex int) {
if timeIndex >= 0 {
switch value := values[timeIndex].(type) {
case time.Time:
values[timeIndex] = float64(value.UnixNano()) / float64(time.Millisecond)
case *time.Time:
if value != nil {
values[timeIndex] = float64((*value).UnixNano()) / float64(time.Millisecond)
}
case int64:
values[timeIndex] = int64(EpochPrecisionToMs(float64(value)))
case *int64:
if value != nil {
values[timeIndex] = int64(EpochPrecisionToMs(float64(*value)))
}
case uint64:
values[timeIndex] = int64(EpochPrecisionToMs(float64(value)))
case *uint64:
if value != nil {
values[timeIndex] = int64(EpochPrecisionToMs(float64(*value)))
}
case int32:
values[timeIndex] = int64(EpochPrecisionToMs(float64(value)))
case *int32:
if value != nil {
values[timeIndex] = int64(EpochPrecisionToMs(float64(*value)))
}
case uint32:
values[timeIndex] = int64(EpochPrecisionToMs(float64(value)))
case *uint32:
if value != nil {
values[timeIndex] = int64(EpochPrecisionToMs(float64(*value)))
}
case float64:
values[timeIndex] = EpochPrecisionToMs(value)
case *float64:
if value != nil {
values[timeIndex] = EpochPrecisionToMs(*value)
}
case float32:
values[timeIndex] = EpochPrecisionToMs(float64(value))
case *float32:
if value != nil {
values[timeIndex] = EpochPrecisionToMs(float64(*value))
}
}
}
}
// ConvertSqlValueColumnToFloat converts timeseries value column to float.
func ConvertSqlValueColumnToFloat(columnName string, columnValue interface{}) (null.Float, error) {
var value null.Float
switch typedValue := columnValue.(type) {
case int:
value = null.FloatFrom(float64(typedValue))
case *int:
if typedValue == nil {
value.Valid = false
} else {
value = null.FloatFrom(float64(*typedValue))
}
case int64:
value = null.FloatFrom(float64(typedValue))
case *int64:
if typedValue == nil {
value.Valid = false
} else {
value = null.FloatFrom(float64(*typedValue))
}
case int32:
value = null.FloatFrom(float64(typedValue))
case *int32:
if typedValue == nil {
value.Valid = false
} else {
value = null.FloatFrom(float64(*typedValue))
}
case int16:
value = null.FloatFrom(float64(typedValue))
case *int16:
if typedValue == nil {
value.Valid = false
} else {
value = null.FloatFrom(float64(*typedValue))
}
case int8:
value = null.FloatFrom(float64(typedValue))
case *int8:
if typedValue == nil {
value.Valid = false
} else {
value = null.FloatFrom(float64(*typedValue))
}
case uint:
value = null.FloatFrom(float64(typedValue))
case *uint:
if typedValue == nil {
value.Valid = false
} else {
value = null.FloatFrom(float64(*typedValue))
}
case uint64:
value = null.FloatFrom(float64(typedValue))
case *uint64:
if typedValue == nil {
value.Valid = false
} else {
value = null.FloatFrom(float64(*typedValue))
}
case uint32:
value = null.FloatFrom(float64(typedValue))
case *uint32:
if typedValue == nil {
value.Valid = false
} else {
value = null.FloatFrom(float64(*typedValue))
}
case uint16:
value = null.FloatFrom(float64(typedValue))
case *uint16:
if typedValue == nil {
value.Valid = false
} else {
value = null.FloatFrom(float64(*typedValue))
}
case uint8:
value = null.FloatFrom(float64(typedValue))
case *uint8:
if typedValue == nil {
value.Valid = false
} else {
value = null.FloatFrom(float64(*typedValue))
}
case float64:
value = null.FloatFrom(typedValue)
case *float64:
value = null.FloatFromPtr(typedValue)
case float32:
value = null.FloatFrom(float64(typedValue))
case *float32:
if typedValue == nil {
value.Valid = false
} else {
value = null.FloatFrom(float64(*typedValue))
}
case nil:
value.Valid = false
default:
return null.NewFloat(0, false), fmt.Errorf("Value column must have numeric datatype, column: %s type: %T value: %v", columnName, typedValue, typedValue)
}
return value, nil
}
| pkg/tsdb/sql_engine.go | 1 | https://github.com/grafana/grafana/commit/7905c29875a29d230af476e41cb070b13bc9de73 | [
0.9991034865379333,
0.18267934024333954,
0.0001677397231105715,
0.000606094894465059,
0.3690902888774872
] |
{
"id": 0,
"code_window": [
"\t}\n",
"\n",
"\trowCount := 0\n",
"\ttimeIndex := -1\n",
"\tmetricIndex := -1\n",
"\n",
"\t// check columns of resultset: a column named time is mandatory\n",
"\t// the first text column is treated as metric name unless a column named metric is present\n",
"\tfor i, col := range columnNames {\n",
"\t\tfor _, tc := range e.timeColumnNames {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tmetricPrefix := false\n",
"\tvar metricPrefixValue string\n"
],
"file_path": "pkg/tsdb/sql_engine.go",
"type": "add",
"edit_start_line_idx": 231
} | // Copyright 2018 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// +build linux
// +build gccgo
// +build 386 arm
package unix
import (
"syscall"
"unsafe"
)
func seek(fd int, offset int64, whence int) (newoffset int64, err syscall.Errno) {
offsetLow := uint32(offset & 0xffffffff)
offsetHigh := uint32((offset >> 32) & 0xffffffff)
_, _, err = Syscall6(SYS__LLSEEK, uintptr(fd), uintptr(offsetHigh), uintptr(offsetLow), uintptr(unsafe.Pointer(&newoffset)), uintptr(whence), 0)
return newoffset, err
}
| vendor/golang.org/x/sys/unix/syscall_linux_gccgo.go | 0 | https://github.com/grafana/grafana/commit/7905c29875a29d230af476e41cb070b13bc9de73 | [
0.00040223804535344243,
0.00025403767358511686,
0.0001799200545065105,
0.0001799548917915672,
0.00010479349293746054
] |
{
"id": 0,
"code_window": [
"\t}\n",
"\n",
"\trowCount := 0\n",
"\ttimeIndex := -1\n",
"\tmetricIndex := -1\n",
"\n",
"\t// check columns of resultset: a column named time is mandatory\n",
"\t// the first text column is treated as metric name unless a column named metric is present\n",
"\tfor i, col := range columnNames {\n",
"\t\tfor _, tc := range e.timeColumnNames {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tmetricPrefix := false\n",
"\tvar metricPrefixValue string\n"
],
"file_path": "pkg/tsdb/sql_engine.go",
"type": "add",
"edit_start_line_idx": 231
} | package defaults
import (
"github.com/aws/aws-sdk-go/internal/shareddefaults"
)
// SharedCredentialsFilename returns the SDK's default file path
// for the shared credentials file.
//
// Builds the shared config file path based on the OS's platform.
//
// - Linux/Unix: $HOME/.aws/credentials
// - Windows: %USERPROFILE%\.aws\credentials
func SharedCredentialsFilename() string {
return shareddefaults.SharedCredentialsFilename()
}
// SharedConfigFilename returns the SDK's default file path for
// the shared config file.
//
// Builds the shared config file path based on the OS's platform.
//
// - Linux/Unix: $HOME/.aws/config
// - Windows: %USERPROFILE%\.aws\config
func SharedConfigFilename() string {
return shareddefaults.SharedConfigFilename()
}
| vendor/github.com/aws/aws-sdk-go/aws/defaults/shared_config.go | 0 | https://github.com/grafana/grafana/commit/7905c29875a29d230af476e41cb070b13bc9de73 | [
0.0001748901850078255,
0.00017236860003322363,
0.0001699976419331506,
0.00017221795860677958,
0.0000020002103156002704
] |
{
"id": 0,
"code_window": [
"\t}\n",
"\n",
"\trowCount := 0\n",
"\ttimeIndex := -1\n",
"\tmetricIndex := -1\n",
"\n",
"\t// check columns of resultset: a column named time is mandatory\n",
"\t// the first text column is treated as metric name unless a column named metric is present\n",
"\tfor i, col := range columnNames {\n",
"\t\tfor _, tc := range e.timeColumnNames {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tmetricPrefix := false\n",
"\tvar metricPrefixValue string\n"
],
"file_path": "pkg/tsdb/sql_engine.go",
"type": "add",
"edit_start_line_idx": 231
} | // linux/mksysnum.pl -Wall -Werror -static -I/tmp/include -m32 /tmp/include/asm/unistd.h
// Code generated by the command above; see README.md. DO NOT EDIT.
// +build 386,linux
package unix
const (
SYS_RESTART_SYSCALL = 0
SYS_EXIT = 1
SYS_FORK = 2
SYS_READ = 3
SYS_WRITE = 4
SYS_OPEN = 5
SYS_CLOSE = 6
SYS_WAITPID = 7
SYS_CREAT = 8
SYS_LINK = 9
SYS_UNLINK = 10
SYS_EXECVE = 11
SYS_CHDIR = 12
SYS_TIME = 13
SYS_MKNOD = 14
SYS_CHMOD = 15
SYS_LCHOWN = 16
SYS_BREAK = 17
SYS_OLDSTAT = 18
SYS_LSEEK = 19
SYS_GETPID = 20
SYS_MOUNT = 21
SYS_UMOUNT = 22
SYS_SETUID = 23
SYS_GETUID = 24
SYS_STIME = 25
SYS_PTRACE = 26
SYS_ALARM = 27
SYS_OLDFSTAT = 28
SYS_PAUSE = 29
SYS_UTIME = 30
SYS_STTY = 31
SYS_GTTY = 32
SYS_ACCESS = 33
SYS_NICE = 34
SYS_FTIME = 35
SYS_SYNC = 36
SYS_KILL = 37
SYS_RENAME = 38
SYS_MKDIR = 39
SYS_RMDIR = 40
SYS_DUP = 41
SYS_PIPE = 42
SYS_TIMES = 43
SYS_PROF = 44
SYS_BRK = 45
SYS_SETGID = 46
SYS_GETGID = 47
SYS_SIGNAL = 48
SYS_GETEUID = 49
SYS_GETEGID = 50
SYS_ACCT = 51
SYS_UMOUNT2 = 52
SYS_LOCK = 53
SYS_IOCTL = 54
SYS_FCNTL = 55
SYS_MPX = 56
SYS_SETPGID = 57
SYS_ULIMIT = 58
SYS_OLDOLDUNAME = 59
SYS_UMASK = 60
SYS_CHROOT = 61
SYS_USTAT = 62
SYS_DUP2 = 63
SYS_GETPPID = 64
SYS_GETPGRP = 65
SYS_SETSID = 66
SYS_SIGACTION = 67
SYS_SGETMASK = 68
SYS_SSETMASK = 69
SYS_SETREUID = 70
SYS_SETREGID = 71
SYS_SIGSUSPEND = 72
SYS_SIGPENDING = 73
SYS_SETHOSTNAME = 74
SYS_SETRLIMIT = 75
SYS_GETRLIMIT = 76
SYS_GETRUSAGE = 77
SYS_GETTIMEOFDAY = 78
SYS_SETTIMEOFDAY = 79
SYS_GETGROUPS = 80
SYS_SETGROUPS = 81
SYS_SELECT = 82
SYS_SYMLINK = 83
SYS_OLDLSTAT = 84
SYS_READLINK = 85
SYS_USELIB = 86
SYS_SWAPON = 87
SYS_REBOOT = 88
SYS_READDIR = 89
SYS_MMAP = 90
SYS_MUNMAP = 91
SYS_TRUNCATE = 92
SYS_FTRUNCATE = 93
SYS_FCHMOD = 94
SYS_FCHOWN = 95
SYS_GETPRIORITY = 96
SYS_SETPRIORITY = 97
SYS_PROFIL = 98
SYS_STATFS = 99
SYS_FSTATFS = 100
SYS_IOPERM = 101
SYS_SOCKETCALL = 102
SYS_SYSLOG = 103
SYS_SETITIMER = 104
SYS_GETITIMER = 105
SYS_STAT = 106
SYS_LSTAT = 107
SYS_FSTAT = 108
SYS_OLDUNAME = 109
SYS_IOPL = 110
SYS_VHANGUP = 111
SYS_IDLE = 112
SYS_VM86OLD = 113
SYS_WAIT4 = 114
SYS_SWAPOFF = 115
SYS_SYSINFO = 116
SYS_IPC = 117
SYS_FSYNC = 118
SYS_SIGRETURN = 119
SYS_CLONE = 120
SYS_SETDOMAINNAME = 121
SYS_UNAME = 122
SYS_MODIFY_LDT = 123
SYS_ADJTIMEX = 124
SYS_MPROTECT = 125
SYS_SIGPROCMASK = 126
SYS_CREATE_MODULE = 127
SYS_INIT_MODULE = 128
SYS_DELETE_MODULE = 129
SYS_GET_KERNEL_SYMS = 130
SYS_QUOTACTL = 131
SYS_GETPGID = 132
SYS_FCHDIR = 133
SYS_BDFLUSH = 134
SYS_SYSFS = 135
SYS_PERSONALITY = 136
SYS_AFS_SYSCALL = 137
SYS_SETFSUID = 138
SYS_SETFSGID = 139
SYS__LLSEEK = 140
SYS_GETDENTS = 141
SYS__NEWSELECT = 142
SYS_FLOCK = 143
SYS_MSYNC = 144
SYS_READV = 145
SYS_WRITEV = 146
SYS_GETSID = 147
SYS_FDATASYNC = 148
SYS__SYSCTL = 149
SYS_MLOCK = 150
SYS_MUNLOCK = 151
SYS_MLOCKALL = 152
SYS_MUNLOCKALL = 153
SYS_SCHED_SETPARAM = 154
SYS_SCHED_GETPARAM = 155
SYS_SCHED_SETSCHEDULER = 156
SYS_SCHED_GETSCHEDULER = 157
SYS_SCHED_YIELD = 158
SYS_SCHED_GET_PRIORITY_MAX = 159
SYS_SCHED_GET_PRIORITY_MIN = 160
SYS_SCHED_RR_GET_INTERVAL = 161
SYS_NANOSLEEP = 162
SYS_MREMAP = 163
SYS_SETRESUID = 164
SYS_GETRESUID = 165
SYS_VM86 = 166
SYS_QUERY_MODULE = 167
SYS_POLL = 168
SYS_NFSSERVCTL = 169
SYS_SETRESGID = 170
SYS_GETRESGID = 171
SYS_PRCTL = 172
SYS_RT_SIGRETURN = 173
SYS_RT_SIGACTION = 174
SYS_RT_SIGPROCMASK = 175
SYS_RT_SIGPENDING = 176
SYS_RT_SIGTIMEDWAIT = 177
SYS_RT_SIGQUEUEINFO = 178
SYS_RT_SIGSUSPEND = 179
SYS_PREAD64 = 180
SYS_PWRITE64 = 181
SYS_CHOWN = 182
SYS_GETCWD = 183
SYS_CAPGET = 184
SYS_CAPSET = 185
SYS_SIGALTSTACK = 186
SYS_SENDFILE = 187
SYS_GETPMSG = 188
SYS_PUTPMSG = 189
SYS_VFORK = 190
SYS_UGETRLIMIT = 191
SYS_MMAP2 = 192
SYS_TRUNCATE64 = 193
SYS_FTRUNCATE64 = 194
SYS_STAT64 = 195
SYS_LSTAT64 = 196
SYS_FSTAT64 = 197
SYS_LCHOWN32 = 198
SYS_GETUID32 = 199
SYS_GETGID32 = 200
SYS_GETEUID32 = 201
SYS_GETEGID32 = 202
SYS_SETREUID32 = 203
SYS_SETREGID32 = 204
SYS_GETGROUPS32 = 205
SYS_SETGROUPS32 = 206
SYS_FCHOWN32 = 207
SYS_SETRESUID32 = 208
SYS_GETRESUID32 = 209
SYS_SETRESGID32 = 210
SYS_GETRESGID32 = 211
SYS_CHOWN32 = 212
SYS_SETUID32 = 213
SYS_SETGID32 = 214
SYS_SETFSUID32 = 215
SYS_SETFSGID32 = 216
SYS_PIVOT_ROOT = 217
SYS_MINCORE = 218
SYS_MADVISE = 219
SYS_GETDENTS64 = 220
SYS_FCNTL64 = 221
SYS_GETTID = 224
SYS_READAHEAD = 225
SYS_SETXATTR = 226
SYS_LSETXATTR = 227
SYS_FSETXATTR = 228
SYS_GETXATTR = 229
SYS_LGETXATTR = 230
SYS_FGETXATTR = 231
SYS_LISTXATTR = 232
SYS_LLISTXATTR = 233
SYS_FLISTXATTR = 234
SYS_REMOVEXATTR = 235
SYS_LREMOVEXATTR = 236
SYS_FREMOVEXATTR = 237
SYS_TKILL = 238
SYS_SENDFILE64 = 239
SYS_FUTEX = 240
SYS_SCHED_SETAFFINITY = 241
SYS_SCHED_GETAFFINITY = 242
SYS_SET_THREAD_AREA = 243
SYS_GET_THREAD_AREA = 244
SYS_IO_SETUP = 245
SYS_IO_DESTROY = 246
SYS_IO_GETEVENTS = 247
SYS_IO_SUBMIT = 248
SYS_IO_CANCEL = 249
SYS_FADVISE64 = 250
SYS_EXIT_GROUP = 252
SYS_LOOKUP_DCOOKIE = 253
SYS_EPOLL_CREATE = 254
SYS_EPOLL_CTL = 255
SYS_EPOLL_WAIT = 256
SYS_REMAP_FILE_PAGES = 257
SYS_SET_TID_ADDRESS = 258
SYS_TIMER_CREATE = 259
SYS_TIMER_SETTIME = 260
SYS_TIMER_GETTIME = 261
SYS_TIMER_GETOVERRUN = 262
SYS_TIMER_DELETE = 263
SYS_CLOCK_SETTIME = 264
SYS_CLOCK_GETTIME = 265
SYS_CLOCK_GETRES = 266
SYS_CLOCK_NANOSLEEP = 267
SYS_STATFS64 = 268
SYS_FSTATFS64 = 269
SYS_TGKILL = 270
SYS_UTIMES = 271
SYS_FADVISE64_64 = 272
SYS_VSERVER = 273
SYS_MBIND = 274
SYS_GET_MEMPOLICY = 275
SYS_SET_MEMPOLICY = 276
SYS_MQ_OPEN = 277
SYS_MQ_UNLINK = 278
SYS_MQ_TIMEDSEND = 279
SYS_MQ_TIMEDRECEIVE = 280
SYS_MQ_NOTIFY = 281
SYS_MQ_GETSETATTR = 282
SYS_KEXEC_LOAD = 283
SYS_WAITID = 284
SYS_ADD_KEY = 286
SYS_REQUEST_KEY = 287
SYS_KEYCTL = 288
SYS_IOPRIO_SET = 289
SYS_IOPRIO_GET = 290
SYS_INOTIFY_INIT = 291
SYS_INOTIFY_ADD_WATCH = 292
SYS_INOTIFY_RM_WATCH = 293
SYS_MIGRATE_PAGES = 294
SYS_OPENAT = 295
SYS_MKDIRAT = 296
SYS_MKNODAT = 297
SYS_FCHOWNAT = 298
SYS_FUTIMESAT = 299
SYS_FSTATAT64 = 300
SYS_UNLINKAT = 301
SYS_RENAMEAT = 302
SYS_LINKAT = 303
SYS_SYMLINKAT = 304
SYS_READLINKAT = 305
SYS_FCHMODAT = 306
SYS_FACCESSAT = 307
SYS_PSELECT6 = 308
SYS_PPOLL = 309
SYS_UNSHARE = 310
SYS_SET_ROBUST_LIST = 311
SYS_GET_ROBUST_LIST = 312
SYS_SPLICE = 313
SYS_SYNC_FILE_RANGE = 314
SYS_TEE = 315
SYS_VMSPLICE = 316
SYS_MOVE_PAGES = 317
SYS_GETCPU = 318
SYS_EPOLL_PWAIT = 319
SYS_UTIMENSAT = 320
SYS_SIGNALFD = 321
SYS_TIMERFD_CREATE = 322
SYS_EVENTFD = 323
SYS_FALLOCATE = 324
SYS_TIMERFD_SETTIME = 325
SYS_TIMERFD_GETTIME = 326
SYS_SIGNALFD4 = 327
SYS_EVENTFD2 = 328
SYS_EPOLL_CREATE1 = 329
SYS_DUP3 = 330
SYS_PIPE2 = 331
SYS_INOTIFY_INIT1 = 332
SYS_PREADV = 333
SYS_PWRITEV = 334
SYS_RT_TGSIGQUEUEINFO = 335
SYS_PERF_EVENT_OPEN = 336
SYS_RECVMMSG = 337
SYS_FANOTIFY_INIT = 338
SYS_FANOTIFY_MARK = 339
SYS_PRLIMIT64 = 340
SYS_NAME_TO_HANDLE_AT = 341
SYS_OPEN_BY_HANDLE_AT = 342
SYS_CLOCK_ADJTIME = 343
SYS_SYNCFS = 344
SYS_SENDMMSG = 345
SYS_SETNS = 346
SYS_PROCESS_VM_READV = 347
SYS_PROCESS_VM_WRITEV = 348
SYS_KCMP = 349
SYS_FINIT_MODULE = 350
SYS_SCHED_SETATTR = 351
SYS_SCHED_GETATTR = 352
SYS_RENAMEAT2 = 353
SYS_SECCOMP = 354
SYS_GETRANDOM = 355
SYS_MEMFD_CREATE = 356
SYS_BPF = 357
SYS_EXECVEAT = 358
SYS_SOCKET = 359
SYS_SOCKETPAIR = 360
SYS_BIND = 361
SYS_CONNECT = 362
SYS_LISTEN = 363
SYS_ACCEPT4 = 364
SYS_GETSOCKOPT = 365
SYS_SETSOCKOPT = 366
SYS_GETSOCKNAME = 367
SYS_GETPEERNAME = 368
SYS_SENDTO = 369
SYS_SENDMSG = 370
SYS_RECVFROM = 371
SYS_RECVMSG = 372
SYS_SHUTDOWN = 373
SYS_USERFAULTFD = 374
SYS_MEMBARRIER = 375
SYS_MLOCK2 = 376
SYS_COPY_FILE_RANGE = 377
SYS_PREADV2 = 378
SYS_PWRITEV2 = 379
SYS_PKEY_MPROTECT = 380
SYS_PKEY_ALLOC = 381
SYS_PKEY_FREE = 382
SYS_STATX = 383
SYS_ARCH_PRCTL = 384
)
| vendor/golang.org/x/sys/unix/zsysnum_linux_386.go | 0 | https://github.com/grafana/grafana/commit/7905c29875a29d230af476e41cb070b13bc9de73 | [
0.00021715936600230634,
0.000176025481778197,
0.0001616891095181927,
0.00016836883150972426,
0.000013711740393773653
] |
{
"id": 1,
"code_window": [
"\t\t\t\t}\n",
"\t\t\t}\n",
"\t\t}\n",
"\t}\n",
"\n",
"\tif timeIndex == -1 {\n",
"\t\treturn fmt.Errorf(\"Found no column named %s\", strings.Join(e.timeColumnNames, \" or \"))\n",
"\t}\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t// use metric column as prefix with multiple value columns\n",
"\tif metricIndex != -1 && len(columnNames) > 3 {\n",
"\t\tmetricPrefix = true\n",
"\t}\n",
"\n"
],
"file_path": "pkg/tsdb/sql_engine.go",
"type": "add",
"edit_start_line_idx": 258
} | package tsdb
import (
"container/list"
"context"
"database/sql"
"fmt"
"math"
"strings"
"sync"
"time"
"github.com/grafana/grafana/pkg/log"
"github.com/grafana/grafana/pkg/components/null"
"github.com/go-xorm/core"
"github.com/go-xorm/xorm"
"github.com/grafana/grafana/pkg/components/simplejson"
"github.com/grafana/grafana/pkg/models"
)
// SqlMacroEngine interpolates macros into sql. It takes in the Query to have access to query context and
// timeRange to be able to generate queries that use from and to.
type SqlMacroEngine interface {
Interpolate(query *Query, timeRange *TimeRange, sql string) (string, error)
}
// SqlTableRowTransformer transforms a query result row to RowValues with proper types.
type SqlTableRowTransformer interface {
Transform(columnTypes []*sql.ColumnType, rows *core.Rows) (RowValues, error)
}
type engineCacheType struct {
cache map[int64]*xorm.Engine
versions map[int64]int
sync.Mutex
}
var engineCache = engineCacheType{
cache: make(map[int64]*xorm.Engine),
versions: make(map[int64]int),
}
var NewXormEngine = func(driverName string, connectionString string) (*xorm.Engine, error) {
return xorm.NewEngine(driverName, connectionString)
}
type sqlQueryEndpoint struct {
macroEngine SqlMacroEngine
rowTransformer SqlTableRowTransformer
engine *xorm.Engine
timeColumnNames []string
metricColumnTypes []string
log log.Logger
}
type SqlQueryEndpointConfiguration struct {
DriverName string
Datasource *models.DataSource
ConnectionString string
TimeColumnNames []string
MetricColumnTypes []string
}
var NewSqlQueryEndpoint = func(config *SqlQueryEndpointConfiguration, rowTransformer SqlTableRowTransformer, macroEngine SqlMacroEngine, log log.Logger) (TsdbQueryEndpoint, error) {
queryEndpoint := sqlQueryEndpoint{
rowTransformer: rowTransformer,
macroEngine: macroEngine,
timeColumnNames: []string{"time"},
log: log,
}
if len(config.TimeColumnNames) > 0 {
queryEndpoint.timeColumnNames = config.TimeColumnNames
}
engineCache.Lock()
defer engineCache.Unlock()
if engine, present := engineCache.cache[config.Datasource.Id]; present {
if version := engineCache.versions[config.Datasource.Id]; version == config.Datasource.Version {
queryEndpoint.engine = engine
return &queryEndpoint, nil
}
}
engine, err := NewXormEngine(config.DriverName, config.ConnectionString)
if err != nil {
return nil, err
}
engine.SetMaxOpenConns(10)
engine.SetMaxIdleConns(10)
engineCache.versions[config.Datasource.Id] = config.Datasource.Version
engineCache.cache[config.Datasource.Id] = engine
queryEndpoint.engine = engine
return &queryEndpoint, nil
}
const rowLimit = 1000000
// Query is the main function for the SqlQueryEndpoint
func (e *sqlQueryEndpoint) Query(ctx context.Context, dsInfo *models.DataSource, tsdbQuery *TsdbQuery) (*Response, error) {
result := &Response{
Results: make(map[string]*QueryResult),
}
session := e.engine.NewSession()
defer session.Close()
db := session.DB()
for _, query := range tsdbQuery.Queries {
rawSQL := query.Model.Get("rawSql").MustString()
if rawSQL == "" {
continue
}
queryResult := &QueryResult{Meta: simplejson.New(), RefId: query.RefId}
result.Results[query.RefId] = queryResult
rawSQL, err := e.macroEngine.Interpolate(query, tsdbQuery.TimeRange, rawSQL)
if err != nil {
queryResult.Error = err
continue
}
queryResult.Meta.Set("sql", rawSQL)
rows, err := db.Query(rawSQL)
if err != nil {
queryResult.Error = err
continue
}
defer rows.Close()
format := query.Model.Get("format").MustString("time_series")
switch format {
case "time_series":
err := e.transformToTimeSeries(query, rows, queryResult, tsdbQuery)
if err != nil {
queryResult.Error = err
continue
}
case "table":
err := e.transformToTable(query, rows, queryResult, tsdbQuery)
if err != nil {
queryResult.Error = err
continue
}
}
}
return result, nil
}
func (e *sqlQueryEndpoint) transformToTable(query *Query, rows *core.Rows, result *QueryResult, tsdbQuery *TsdbQuery) error {
columnNames, err := rows.Columns()
columnCount := len(columnNames)
if err != nil {
return err
}
rowCount := 0
timeIndex := -1
table := &Table{
Columns: make([]TableColumn, columnCount),
Rows: make([]RowValues, 0),
}
for i, name := range columnNames {
table.Columns[i].Text = name
for _, tc := range e.timeColumnNames {
if name == tc {
timeIndex = i
break
}
}
}
columnTypes, err := rows.ColumnTypes()
if err != nil {
return err
}
for ; rows.Next(); rowCount++ {
if rowCount > rowLimit {
return fmt.Errorf("query row limit exceeded, limit %d", rowLimit)
}
values, err := e.rowTransformer.Transform(columnTypes, rows)
if err != nil {
return err
}
// converts column named time to unix timestamp in milliseconds
// to make native mssql datetime types and epoch dates work in
// annotation and table queries.
ConvertSqlTimeColumnToEpochMs(values, timeIndex)
table.Rows = append(table.Rows, values)
}
result.Tables = append(result.Tables, table)
result.Meta.Set("rowCount", rowCount)
return nil
}
func (e *sqlQueryEndpoint) transformToTimeSeries(query *Query, rows *core.Rows, result *QueryResult, tsdbQuery *TsdbQuery) error {
pointsBySeries := make(map[string]*TimeSeries)
seriesByQueryOrder := list.New()
columnNames, err := rows.Columns()
if err != nil {
return err
}
columnTypes, err := rows.ColumnTypes()
if err != nil {
return err
}
rowCount := 0
timeIndex := -1
metricIndex := -1
// check columns of resultset: a column named time is mandatory
// the first text column is treated as metric name unless a column named metric is present
for i, col := range columnNames {
for _, tc := range e.timeColumnNames {
if col == tc {
timeIndex = i
continue
}
}
switch col {
case "metric":
metricIndex = i
default:
if metricIndex == -1 {
columnType := columnTypes[i].DatabaseTypeName()
for _, mct := range e.metricColumnTypes {
if columnType == mct {
metricIndex = i
continue
}
}
}
}
}
if timeIndex == -1 {
return fmt.Errorf("Found no column named %s", strings.Join(e.timeColumnNames, " or "))
}
fillMissing := query.Model.Get("fill").MustBool(false)
var fillInterval float64
fillValue := null.Float{}
if fillMissing {
fillInterval = query.Model.Get("fillInterval").MustFloat64() * 1000
if !query.Model.Get("fillNull").MustBool(false) {
fillValue.Float64 = query.Model.Get("fillValue").MustFloat64()
fillValue.Valid = true
}
}
for rows.Next() {
var timestamp float64
var value null.Float
var metric string
if rowCount > rowLimit {
return fmt.Errorf("query row limit exceeded, limit %d", rowLimit)
}
values, err := e.rowTransformer.Transform(columnTypes, rows)
if err != nil {
return err
}
// converts column named time to unix timestamp in milliseconds to make
// native mysql datetime types and epoch dates work in
// annotation and table queries.
ConvertSqlTimeColumnToEpochMs(values, timeIndex)
switch columnValue := values[timeIndex].(type) {
case int64:
timestamp = float64(columnValue)
case float64:
timestamp = columnValue
default:
return fmt.Errorf("Invalid type for column time, must be of type timestamp or unix timestamp, got: %T %v", columnValue, columnValue)
}
if metricIndex >= 0 {
if columnValue, ok := values[metricIndex].(string); ok {
metric = columnValue
} else {
return fmt.Errorf("Column metric must be of type %s. metric column name: %s type: %s but datatype is %T", strings.Join(e.metricColumnTypes, ", "), columnNames[metricIndex], columnTypes[metricIndex].DatabaseTypeName(), values[metricIndex])
}
}
for i, col := range columnNames {
if i == timeIndex || i == metricIndex {
continue
}
if value, err = ConvertSqlValueColumnToFloat(col, values[i]); err != nil {
return err
}
if metricIndex == -1 {
metric = col
}
series, exist := pointsBySeries[metric]
if !exist {
series = &TimeSeries{Name: metric}
pointsBySeries[metric] = series
seriesByQueryOrder.PushBack(metric)
}
if fillMissing {
var intervalStart float64
if !exist {
intervalStart = float64(tsdbQuery.TimeRange.MustGetFrom().UnixNano() / 1e6)
} else {
intervalStart = series.Points[len(series.Points)-1][1].Float64 + fillInterval
}
// align interval start
intervalStart = math.Floor(intervalStart/fillInterval) * fillInterval
for i := intervalStart; i < timestamp; i += fillInterval {
series.Points = append(series.Points, TimePoint{fillValue, null.FloatFrom(i)})
rowCount++
}
}
series.Points = append(series.Points, TimePoint{value, null.FloatFrom(timestamp)})
e.log.Debug("Rows", "metric", metric, "time", timestamp, "value", value)
}
}
for elem := seriesByQueryOrder.Front(); elem != nil; elem = elem.Next() {
key := elem.Value.(string)
result.Series = append(result.Series, pointsBySeries[key])
if fillMissing {
series := pointsBySeries[key]
// fill in values from last fetched value till interval end
intervalStart := series.Points[len(series.Points)-1][1].Float64
intervalEnd := float64(tsdbQuery.TimeRange.MustGetTo().UnixNano() / 1e6)
// align interval start
intervalStart = math.Floor(intervalStart/fillInterval) * fillInterval
for i := intervalStart + fillInterval; i < intervalEnd; i += fillInterval {
series.Points = append(series.Points, TimePoint{fillValue, null.FloatFrom(i)})
rowCount++
}
}
}
result.Meta.Set("rowCount", rowCount)
return nil
}
// ConvertSqlTimeColumnToEpochMs converts column named time to unix timestamp in milliseconds
// to make native datetime types and epoch dates work in annotation and table queries.
func ConvertSqlTimeColumnToEpochMs(values RowValues, timeIndex int) {
if timeIndex >= 0 {
switch value := values[timeIndex].(type) {
case time.Time:
values[timeIndex] = float64(value.UnixNano()) / float64(time.Millisecond)
case *time.Time:
if value != nil {
values[timeIndex] = float64((*value).UnixNano()) / float64(time.Millisecond)
}
case int64:
values[timeIndex] = int64(EpochPrecisionToMs(float64(value)))
case *int64:
if value != nil {
values[timeIndex] = int64(EpochPrecisionToMs(float64(*value)))
}
case uint64:
values[timeIndex] = int64(EpochPrecisionToMs(float64(value)))
case *uint64:
if value != nil {
values[timeIndex] = int64(EpochPrecisionToMs(float64(*value)))
}
case int32:
values[timeIndex] = int64(EpochPrecisionToMs(float64(value)))
case *int32:
if value != nil {
values[timeIndex] = int64(EpochPrecisionToMs(float64(*value)))
}
case uint32:
values[timeIndex] = int64(EpochPrecisionToMs(float64(value)))
case *uint32:
if value != nil {
values[timeIndex] = int64(EpochPrecisionToMs(float64(*value)))
}
case float64:
values[timeIndex] = EpochPrecisionToMs(value)
case *float64:
if value != nil {
values[timeIndex] = EpochPrecisionToMs(*value)
}
case float32:
values[timeIndex] = EpochPrecisionToMs(float64(value))
case *float32:
if value != nil {
values[timeIndex] = EpochPrecisionToMs(float64(*value))
}
}
}
}
// ConvertSqlValueColumnToFloat converts timeseries value column to float.
func ConvertSqlValueColumnToFloat(columnName string, columnValue interface{}) (null.Float, error) {
var value null.Float
switch typedValue := columnValue.(type) {
case int:
value = null.FloatFrom(float64(typedValue))
case *int:
if typedValue == nil {
value.Valid = false
} else {
value = null.FloatFrom(float64(*typedValue))
}
case int64:
value = null.FloatFrom(float64(typedValue))
case *int64:
if typedValue == nil {
value.Valid = false
} else {
value = null.FloatFrom(float64(*typedValue))
}
case int32:
value = null.FloatFrom(float64(typedValue))
case *int32:
if typedValue == nil {
value.Valid = false
} else {
value = null.FloatFrom(float64(*typedValue))
}
case int16:
value = null.FloatFrom(float64(typedValue))
case *int16:
if typedValue == nil {
value.Valid = false
} else {
value = null.FloatFrom(float64(*typedValue))
}
case int8:
value = null.FloatFrom(float64(typedValue))
case *int8:
if typedValue == nil {
value.Valid = false
} else {
value = null.FloatFrom(float64(*typedValue))
}
case uint:
value = null.FloatFrom(float64(typedValue))
case *uint:
if typedValue == nil {
value.Valid = false
} else {
value = null.FloatFrom(float64(*typedValue))
}
case uint64:
value = null.FloatFrom(float64(typedValue))
case *uint64:
if typedValue == nil {
value.Valid = false
} else {
value = null.FloatFrom(float64(*typedValue))
}
case uint32:
value = null.FloatFrom(float64(typedValue))
case *uint32:
if typedValue == nil {
value.Valid = false
} else {
value = null.FloatFrom(float64(*typedValue))
}
case uint16:
value = null.FloatFrom(float64(typedValue))
case *uint16:
if typedValue == nil {
value.Valid = false
} else {
value = null.FloatFrom(float64(*typedValue))
}
case uint8:
value = null.FloatFrom(float64(typedValue))
case *uint8:
if typedValue == nil {
value.Valid = false
} else {
value = null.FloatFrom(float64(*typedValue))
}
case float64:
value = null.FloatFrom(typedValue)
case *float64:
value = null.FloatFromPtr(typedValue)
case float32:
value = null.FloatFrom(float64(typedValue))
case *float32:
if typedValue == nil {
value.Valid = false
} else {
value = null.FloatFrom(float64(*typedValue))
}
case nil:
value.Valid = false
default:
return null.NewFloat(0, false), fmt.Errorf("Value column must have numeric datatype, column: %s type: %T value: %v", columnName, typedValue, typedValue)
}
return value, nil
}
| pkg/tsdb/sql_engine.go | 1 | https://github.com/grafana/grafana/commit/7905c29875a29d230af476e41cb070b13bc9de73 | [
0.9966647028923035,
0.022311685606837273,
0.00016506717656739056,
0.00018540579185355455,
0.13429826498031616
] |
{
"id": 1,
"code_window": [
"\t\t\t\t}\n",
"\t\t\t}\n",
"\t\t}\n",
"\t}\n",
"\n",
"\tif timeIndex == -1 {\n",
"\t\treturn fmt.Errorf(\"Found no column named %s\", strings.Join(e.timeColumnNames, \" or \"))\n",
"\t}\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t// use metric column as prefix with multiple value columns\n",
"\tif metricIndex != -1 && len(columnNames) > 3 {\n",
"\t\tmetricPrefix = true\n",
"\t}\n",
"\n"
],
"file_path": "pkg/tsdb/sql_engine.go",
"type": "add",
"edit_start_line_idx": 258
} | {
"type": "datasource",
"name": "Prometheus",
"id": "prometheus",
"includes": [
{
"type": "dashboard",
"name": "Prometheus Stats",
"path": "dashboards/prometheus_stats.json"
},
{
"type": "dashboard",
"name": "Prometheus 2.0 Stats",
"path": "dashboards/prometheus_2_stats.json"
},
{
"type": "dashboard",
"name": "Grafana Stats",
"path": "dashboards/grafana_stats.json"
}
],
"metrics": true,
"alerting": true,
"annotations": true,
"explore": true,
"queryOptions": {
"minInterval": true
},
"info": {
"description": "Prometheus Data Source for Grafana",
"author": {
"name": "Grafana Project",
"url": "https://grafana.com"
},
"logos": {
"small": "img/prometheus_logo.svg",
"large": "img/prometheus_logo.svg"
},
"links": [
{
"name": "Prometheus",
"url": "https://prometheus.io/"
}
],
"version": "5.0.0"
}
} | public/app/plugins/datasource/prometheus/plugin.json | 0 | https://github.com/grafana/grafana/commit/7905c29875a29d230af476e41cb070b13bc9de73 | [
0.00017518342065159231,
0.00017367427062708884,
0.00017158707487396896,
0.00017406648839823902,
0.0000012403647815517616
] |
{
"id": 1,
"code_window": [
"\t\t\t\t}\n",
"\t\t\t}\n",
"\t\t}\n",
"\t}\n",
"\n",
"\tif timeIndex == -1 {\n",
"\t\treturn fmt.Errorf(\"Found no column named %s\", strings.Join(e.timeColumnNames, \" or \"))\n",
"\t}\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t// use metric column as prefix with multiple value columns\n",
"\tif metricIndex != -1 && len(columnNames) > 3 {\n",
"\t\tmetricPrefix = true\n",
"\t}\n",
"\n"
],
"file_path": "pkg/tsdb/sql_engine.go",
"type": "add",
"edit_start_line_idx": 258
} | # This source code was written by the Go contributors.
# The master list of contributors is in the main Go distribution,
# visible at http://tip.golang.org/CONTRIBUTORS.
| vendor/golang.org/x/sys/CONTRIBUTORS | 0 | https://github.com/grafana/grafana/commit/7905c29875a29d230af476e41cb070b13bc9de73 | [
0.00017523572023492306,
0.00017523572023492306,
0.00017523572023492306,
0.00017523572023492306,
0
] |
{
"id": 1,
"code_window": [
"\t\t\t\t}\n",
"\t\t\t}\n",
"\t\t}\n",
"\t}\n",
"\n",
"\tif timeIndex == -1 {\n",
"\t\treturn fmt.Errorf(\"Found no column named %s\", strings.Join(e.timeColumnNames, \" or \"))\n",
"\t}\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t// use metric column as prefix with multiple value columns\n",
"\tif metricIndex != -1 && len(columnNames) > 3 {\n",
"\t\tmetricPrefix = true\n",
"\t}\n",
"\n"
],
"file_path": "pkg/tsdb/sql_engine.go",
"type": "add",
"edit_start_line_idx": 258
} | // TODO: under unit test
package reporting
import (
"bytes"
"encoding/json"
"fmt"
"strings"
)
type JsonReporter struct {
out *Printer
currentKey []string
current *ScopeResult
index map[string]*ScopeResult
scopes []*ScopeResult
}
func (self *JsonReporter) depth() int { return len(self.currentKey) }
func (self *JsonReporter) BeginStory(story *StoryReport) {}
func (self *JsonReporter) Enter(scope *ScopeReport) {
self.currentKey = append(self.currentKey, scope.Title)
ID := strings.Join(self.currentKey, "|")
if _, found := self.index[ID]; !found {
next := newScopeResult(scope.Title, self.depth(), scope.File, scope.Line)
self.scopes = append(self.scopes, next)
self.index[ID] = next
}
self.current = self.index[ID]
}
func (self *JsonReporter) Report(report *AssertionResult) {
self.current.Assertions = append(self.current.Assertions, report)
}
func (self *JsonReporter) Exit() {
self.currentKey = self.currentKey[:len(self.currentKey)-1]
}
func (self *JsonReporter) EndStory() {
self.report()
self.reset()
}
func (self *JsonReporter) report() {
scopes := []string{}
for _, scope := range self.scopes {
serialized, err := json.Marshal(scope)
if err != nil {
self.out.Println(jsonMarshalFailure)
panic(err)
}
var buffer bytes.Buffer
json.Indent(&buffer, serialized, "", " ")
scopes = append(scopes, buffer.String())
}
self.out.Print(fmt.Sprintf("%s\n%s,\n%s\n", OpenJson, strings.Join(scopes, ","), CloseJson))
}
func (self *JsonReporter) reset() {
self.scopes = []*ScopeResult{}
self.index = map[string]*ScopeResult{}
self.currentKey = nil
}
func (self *JsonReporter) Write(content []byte) (written int, err error) {
self.current.Output += string(content)
return len(content), nil
}
func NewJsonReporter(out *Printer) *JsonReporter {
self := new(JsonReporter)
self.out = out
self.reset()
return self
}
const OpenJson = ">->->OPEN-JSON->->->" // "⌦"
const CloseJson = "<-<-<-CLOSE-JSON<-<-<" // "⌫"
const jsonMarshalFailure = `
GOCONVEY_JSON_MARSHALL_FAILURE: There was an error when attempting to convert test results to JSON.
Please file a bug report and reference the code that caused this failure if possible.
Here's the panic:
`
| vendor/github.com/smartystreets/goconvey/convey/reporting/json.go | 0 | https://github.com/grafana/grafana/commit/7905c29875a29d230af476e41cb070b13bc9de73 | [
0.00020502762345131487,
0.00017498547094874084,
0.0001679873385000974,
0.00017270835814997554,
0.000010886083146033343
] |
{
"id": 2,
"code_window": [
"\n",
"\t\tif metricIndex >= 0 {\n",
"\t\t\tif columnValue, ok := values[metricIndex].(string); ok {\n",
"\t\t\t\tmetric = columnValue\n",
"\t\t\t} else {\n",
"\t\t\t\treturn fmt.Errorf(\"Column metric must be of type %s. metric column name: %s type: %s but datatype is %T\", strings.Join(e.metricColumnTypes, \", \"), columnNames[metricIndex], columnTypes[metricIndex].DatabaseTypeName(), values[metricIndex])\n",
"\t\t\t}\n",
"\t\t}\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t\tif metricPrefix {\n",
"\t\t\t\t\tmetricPrefixValue = columnValue\n",
"\t\t\t\t} else {\n",
"\t\t\t\t\tmetric = columnValue\n",
"\t\t\t\t}\n"
],
"file_path": "pkg/tsdb/sql_engine.go",
"type": "replace",
"edit_start_line_idx": 303
} | package tsdb
import (
"container/list"
"context"
"database/sql"
"fmt"
"math"
"strings"
"sync"
"time"
"github.com/grafana/grafana/pkg/log"
"github.com/grafana/grafana/pkg/components/null"
"github.com/go-xorm/core"
"github.com/go-xorm/xorm"
"github.com/grafana/grafana/pkg/components/simplejson"
"github.com/grafana/grafana/pkg/models"
)
// SqlMacroEngine interpolates macros into sql. It takes in the Query to have access to query context and
// timeRange to be able to generate queries that use from and to.
type SqlMacroEngine interface {
Interpolate(query *Query, timeRange *TimeRange, sql string) (string, error)
}
// SqlTableRowTransformer transforms a query result row to RowValues with proper types.
type SqlTableRowTransformer interface {
Transform(columnTypes []*sql.ColumnType, rows *core.Rows) (RowValues, error)
}
type engineCacheType struct {
cache map[int64]*xorm.Engine
versions map[int64]int
sync.Mutex
}
var engineCache = engineCacheType{
cache: make(map[int64]*xorm.Engine),
versions: make(map[int64]int),
}
var NewXormEngine = func(driverName string, connectionString string) (*xorm.Engine, error) {
return xorm.NewEngine(driverName, connectionString)
}
type sqlQueryEndpoint struct {
macroEngine SqlMacroEngine
rowTransformer SqlTableRowTransformer
engine *xorm.Engine
timeColumnNames []string
metricColumnTypes []string
log log.Logger
}
type SqlQueryEndpointConfiguration struct {
DriverName string
Datasource *models.DataSource
ConnectionString string
TimeColumnNames []string
MetricColumnTypes []string
}
var NewSqlQueryEndpoint = func(config *SqlQueryEndpointConfiguration, rowTransformer SqlTableRowTransformer, macroEngine SqlMacroEngine, log log.Logger) (TsdbQueryEndpoint, error) {
queryEndpoint := sqlQueryEndpoint{
rowTransformer: rowTransformer,
macroEngine: macroEngine,
timeColumnNames: []string{"time"},
log: log,
}
if len(config.TimeColumnNames) > 0 {
queryEndpoint.timeColumnNames = config.TimeColumnNames
}
engineCache.Lock()
defer engineCache.Unlock()
if engine, present := engineCache.cache[config.Datasource.Id]; present {
if version := engineCache.versions[config.Datasource.Id]; version == config.Datasource.Version {
queryEndpoint.engine = engine
return &queryEndpoint, nil
}
}
engine, err := NewXormEngine(config.DriverName, config.ConnectionString)
if err != nil {
return nil, err
}
engine.SetMaxOpenConns(10)
engine.SetMaxIdleConns(10)
engineCache.versions[config.Datasource.Id] = config.Datasource.Version
engineCache.cache[config.Datasource.Id] = engine
queryEndpoint.engine = engine
return &queryEndpoint, nil
}
const rowLimit = 1000000
// Query is the main function for the SqlQueryEndpoint
func (e *sqlQueryEndpoint) Query(ctx context.Context, dsInfo *models.DataSource, tsdbQuery *TsdbQuery) (*Response, error) {
result := &Response{
Results: make(map[string]*QueryResult),
}
session := e.engine.NewSession()
defer session.Close()
db := session.DB()
for _, query := range tsdbQuery.Queries {
rawSQL := query.Model.Get("rawSql").MustString()
if rawSQL == "" {
continue
}
queryResult := &QueryResult{Meta: simplejson.New(), RefId: query.RefId}
result.Results[query.RefId] = queryResult
rawSQL, err := e.macroEngine.Interpolate(query, tsdbQuery.TimeRange, rawSQL)
if err != nil {
queryResult.Error = err
continue
}
queryResult.Meta.Set("sql", rawSQL)
rows, err := db.Query(rawSQL)
if err != nil {
queryResult.Error = err
continue
}
defer rows.Close()
format := query.Model.Get("format").MustString("time_series")
switch format {
case "time_series":
err := e.transformToTimeSeries(query, rows, queryResult, tsdbQuery)
if err != nil {
queryResult.Error = err
continue
}
case "table":
err := e.transformToTable(query, rows, queryResult, tsdbQuery)
if err != nil {
queryResult.Error = err
continue
}
}
}
return result, nil
}
func (e *sqlQueryEndpoint) transformToTable(query *Query, rows *core.Rows, result *QueryResult, tsdbQuery *TsdbQuery) error {
columnNames, err := rows.Columns()
columnCount := len(columnNames)
if err != nil {
return err
}
rowCount := 0
timeIndex := -1
table := &Table{
Columns: make([]TableColumn, columnCount),
Rows: make([]RowValues, 0),
}
for i, name := range columnNames {
table.Columns[i].Text = name
for _, tc := range e.timeColumnNames {
if name == tc {
timeIndex = i
break
}
}
}
columnTypes, err := rows.ColumnTypes()
if err != nil {
return err
}
for ; rows.Next(); rowCount++ {
if rowCount > rowLimit {
return fmt.Errorf("query row limit exceeded, limit %d", rowLimit)
}
values, err := e.rowTransformer.Transform(columnTypes, rows)
if err != nil {
return err
}
// converts column named time to unix timestamp in milliseconds
// to make native mssql datetime types and epoch dates work in
// annotation and table queries.
ConvertSqlTimeColumnToEpochMs(values, timeIndex)
table.Rows = append(table.Rows, values)
}
result.Tables = append(result.Tables, table)
result.Meta.Set("rowCount", rowCount)
return nil
}
func (e *sqlQueryEndpoint) transformToTimeSeries(query *Query, rows *core.Rows, result *QueryResult, tsdbQuery *TsdbQuery) error {
pointsBySeries := make(map[string]*TimeSeries)
seriesByQueryOrder := list.New()
columnNames, err := rows.Columns()
if err != nil {
return err
}
columnTypes, err := rows.ColumnTypes()
if err != nil {
return err
}
rowCount := 0
timeIndex := -1
metricIndex := -1
// check columns of resultset: a column named time is mandatory
// the first text column is treated as metric name unless a column named metric is present
for i, col := range columnNames {
for _, tc := range e.timeColumnNames {
if col == tc {
timeIndex = i
continue
}
}
switch col {
case "metric":
metricIndex = i
default:
if metricIndex == -1 {
columnType := columnTypes[i].DatabaseTypeName()
for _, mct := range e.metricColumnTypes {
if columnType == mct {
metricIndex = i
continue
}
}
}
}
}
if timeIndex == -1 {
return fmt.Errorf("Found no column named %s", strings.Join(e.timeColumnNames, " or "))
}
fillMissing := query.Model.Get("fill").MustBool(false)
var fillInterval float64
fillValue := null.Float{}
if fillMissing {
fillInterval = query.Model.Get("fillInterval").MustFloat64() * 1000
if !query.Model.Get("fillNull").MustBool(false) {
fillValue.Float64 = query.Model.Get("fillValue").MustFloat64()
fillValue.Valid = true
}
}
for rows.Next() {
var timestamp float64
var value null.Float
var metric string
if rowCount > rowLimit {
return fmt.Errorf("query row limit exceeded, limit %d", rowLimit)
}
values, err := e.rowTransformer.Transform(columnTypes, rows)
if err != nil {
return err
}
// converts column named time to unix timestamp in milliseconds to make
// native mysql datetime types and epoch dates work in
// annotation and table queries.
ConvertSqlTimeColumnToEpochMs(values, timeIndex)
switch columnValue := values[timeIndex].(type) {
case int64:
timestamp = float64(columnValue)
case float64:
timestamp = columnValue
default:
return fmt.Errorf("Invalid type for column time, must be of type timestamp or unix timestamp, got: %T %v", columnValue, columnValue)
}
if metricIndex >= 0 {
if columnValue, ok := values[metricIndex].(string); ok {
metric = columnValue
} else {
return fmt.Errorf("Column metric must be of type %s. metric column name: %s type: %s but datatype is %T", strings.Join(e.metricColumnTypes, ", "), columnNames[metricIndex], columnTypes[metricIndex].DatabaseTypeName(), values[metricIndex])
}
}
for i, col := range columnNames {
if i == timeIndex || i == metricIndex {
continue
}
if value, err = ConvertSqlValueColumnToFloat(col, values[i]); err != nil {
return err
}
if metricIndex == -1 {
metric = col
}
series, exist := pointsBySeries[metric]
if !exist {
series = &TimeSeries{Name: metric}
pointsBySeries[metric] = series
seriesByQueryOrder.PushBack(metric)
}
if fillMissing {
var intervalStart float64
if !exist {
intervalStart = float64(tsdbQuery.TimeRange.MustGetFrom().UnixNano() / 1e6)
} else {
intervalStart = series.Points[len(series.Points)-1][1].Float64 + fillInterval
}
// align interval start
intervalStart = math.Floor(intervalStart/fillInterval) * fillInterval
for i := intervalStart; i < timestamp; i += fillInterval {
series.Points = append(series.Points, TimePoint{fillValue, null.FloatFrom(i)})
rowCount++
}
}
series.Points = append(series.Points, TimePoint{value, null.FloatFrom(timestamp)})
e.log.Debug("Rows", "metric", metric, "time", timestamp, "value", value)
}
}
for elem := seriesByQueryOrder.Front(); elem != nil; elem = elem.Next() {
key := elem.Value.(string)
result.Series = append(result.Series, pointsBySeries[key])
if fillMissing {
series := pointsBySeries[key]
// fill in values from last fetched value till interval end
intervalStart := series.Points[len(series.Points)-1][1].Float64
intervalEnd := float64(tsdbQuery.TimeRange.MustGetTo().UnixNano() / 1e6)
// align interval start
intervalStart = math.Floor(intervalStart/fillInterval) * fillInterval
for i := intervalStart + fillInterval; i < intervalEnd; i += fillInterval {
series.Points = append(series.Points, TimePoint{fillValue, null.FloatFrom(i)})
rowCount++
}
}
}
result.Meta.Set("rowCount", rowCount)
return nil
}
// ConvertSqlTimeColumnToEpochMs converts column named time to unix timestamp in milliseconds
// to make native datetime types and epoch dates work in annotation and table queries.
func ConvertSqlTimeColumnToEpochMs(values RowValues, timeIndex int) {
if timeIndex >= 0 {
switch value := values[timeIndex].(type) {
case time.Time:
values[timeIndex] = float64(value.UnixNano()) / float64(time.Millisecond)
case *time.Time:
if value != nil {
values[timeIndex] = float64((*value).UnixNano()) / float64(time.Millisecond)
}
case int64:
values[timeIndex] = int64(EpochPrecisionToMs(float64(value)))
case *int64:
if value != nil {
values[timeIndex] = int64(EpochPrecisionToMs(float64(*value)))
}
case uint64:
values[timeIndex] = int64(EpochPrecisionToMs(float64(value)))
case *uint64:
if value != nil {
values[timeIndex] = int64(EpochPrecisionToMs(float64(*value)))
}
case int32:
values[timeIndex] = int64(EpochPrecisionToMs(float64(value)))
case *int32:
if value != nil {
values[timeIndex] = int64(EpochPrecisionToMs(float64(*value)))
}
case uint32:
values[timeIndex] = int64(EpochPrecisionToMs(float64(value)))
case *uint32:
if value != nil {
values[timeIndex] = int64(EpochPrecisionToMs(float64(*value)))
}
case float64:
values[timeIndex] = EpochPrecisionToMs(value)
case *float64:
if value != nil {
values[timeIndex] = EpochPrecisionToMs(*value)
}
case float32:
values[timeIndex] = EpochPrecisionToMs(float64(value))
case *float32:
if value != nil {
values[timeIndex] = EpochPrecisionToMs(float64(*value))
}
}
}
}
// ConvertSqlValueColumnToFloat converts timeseries value column to float.
func ConvertSqlValueColumnToFloat(columnName string, columnValue interface{}) (null.Float, error) {
var value null.Float
switch typedValue := columnValue.(type) {
case int:
value = null.FloatFrom(float64(typedValue))
case *int:
if typedValue == nil {
value.Valid = false
} else {
value = null.FloatFrom(float64(*typedValue))
}
case int64:
value = null.FloatFrom(float64(typedValue))
case *int64:
if typedValue == nil {
value.Valid = false
} else {
value = null.FloatFrom(float64(*typedValue))
}
case int32:
value = null.FloatFrom(float64(typedValue))
case *int32:
if typedValue == nil {
value.Valid = false
} else {
value = null.FloatFrom(float64(*typedValue))
}
case int16:
value = null.FloatFrom(float64(typedValue))
case *int16:
if typedValue == nil {
value.Valid = false
} else {
value = null.FloatFrom(float64(*typedValue))
}
case int8:
value = null.FloatFrom(float64(typedValue))
case *int8:
if typedValue == nil {
value.Valid = false
} else {
value = null.FloatFrom(float64(*typedValue))
}
case uint:
value = null.FloatFrom(float64(typedValue))
case *uint:
if typedValue == nil {
value.Valid = false
} else {
value = null.FloatFrom(float64(*typedValue))
}
case uint64:
value = null.FloatFrom(float64(typedValue))
case *uint64:
if typedValue == nil {
value.Valid = false
} else {
value = null.FloatFrom(float64(*typedValue))
}
case uint32:
value = null.FloatFrom(float64(typedValue))
case *uint32:
if typedValue == nil {
value.Valid = false
} else {
value = null.FloatFrom(float64(*typedValue))
}
case uint16:
value = null.FloatFrom(float64(typedValue))
case *uint16:
if typedValue == nil {
value.Valid = false
} else {
value = null.FloatFrom(float64(*typedValue))
}
case uint8:
value = null.FloatFrom(float64(typedValue))
case *uint8:
if typedValue == nil {
value.Valid = false
} else {
value = null.FloatFrom(float64(*typedValue))
}
case float64:
value = null.FloatFrom(typedValue)
case *float64:
value = null.FloatFromPtr(typedValue)
case float32:
value = null.FloatFrom(float64(typedValue))
case *float32:
if typedValue == nil {
value.Valid = false
} else {
value = null.FloatFrom(float64(*typedValue))
}
case nil:
value.Valid = false
default:
return null.NewFloat(0, false), fmt.Errorf("Value column must have numeric datatype, column: %s type: %T value: %v", columnName, typedValue, typedValue)
}
return value, nil
}
| pkg/tsdb/sql_engine.go | 1 | https://github.com/grafana/grafana/commit/7905c29875a29d230af476e41cb070b13bc9de73 | [
0.9984025359153748,
0.02041919343173504,
0.00016074709128588438,
0.00020635180408135056,
0.13437853753566742
] |
{
"id": 2,
"code_window": [
"\n",
"\t\tif metricIndex >= 0 {\n",
"\t\t\tif columnValue, ok := values[metricIndex].(string); ok {\n",
"\t\t\t\tmetric = columnValue\n",
"\t\t\t} else {\n",
"\t\t\t\treturn fmt.Errorf(\"Column metric must be of type %s. metric column name: %s type: %s but datatype is %T\", strings.Join(e.metricColumnTypes, \", \"), columnNames[metricIndex], columnTypes[metricIndex].DatabaseTypeName(), values[metricIndex])\n",
"\t\t\t}\n",
"\t\t}\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t\tif metricPrefix {\n",
"\t\t\t\t\tmetricPrefixValue = columnValue\n",
"\t\t\t\t} else {\n",
"\t\t\t\t\tmetric = columnValue\n",
"\t\t\t\t}\n"
],
"file_path": "pkg/tsdb/sql_engine.go",
"type": "replace",
"edit_start_line_idx": 303
} | // Package pq is a pure Go Postgres driver for the database/sql package.
package pq
import (
"path/filepath"
"syscall"
)
// Perform Windows user name lookup identically to libpq.
//
// The PostgreSQL code makes use of the legacy Win32 function
// GetUserName, and that function has not been imported into stock Go.
// GetUserNameEx is available though, the difference being that a
// wider range of names are available. To get the output to be the
// same as GetUserName, only the base (or last) component of the
// result is returned.
func userCurrent() (string, error) {
pw_name := make([]uint16, 128)
pwname_size := uint32(len(pw_name)) - 1
err := syscall.GetUserNameEx(syscall.NameSamCompatible, &pw_name[0], &pwname_size)
if err != nil {
return "", ErrCouldNotDetectUsername
}
s := syscall.UTF16ToString(pw_name)
u := filepath.Base(s)
return u, nil
}
| vendor/github.com/lib/pq/user_windows.go | 0 | https://github.com/grafana/grafana/commit/7905c29875a29d230af476e41cb070b13bc9de73 | [
0.00017565461166668683,
0.00016941357171162963,
0.00016293887165375054,
0.00016964723181445152,
0.000005193807737668976
] |
{
"id": 2,
"code_window": [
"\n",
"\t\tif metricIndex >= 0 {\n",
"\t\t\tif columnValue, ok := values[metricIndex].(string); ok {\n",
"\t\t\t\tmetric = columnValue\n",
"\t\t\t} else {\n",
"\t\t\t\treturn fmt.Errorf(\"Column metric must be of type %s. metric column name: %s type: %s but datatype is %T\", strings.Join(e.metricColumnTypes, \", \"), columnNames[metricIndex], columnTypes[metricIndex].DatabaseTypeName(), values[metricIndex])\n",
"\t\t\t}\n",
"\t\t}\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t\tif metricPrefix {\n",
"\t\t\t\t\tmetricPrefixValue = columnValue\n",
"\t\t\t\t} else {\n",
"\t\t\t\t\tmetric = columnValue\n",
"\t\t\t\t}\n"
],
"file_path": "pkg/tsdb/sql_engine.go",
"type": "replace",
"edit_start_line_idx": 303
} | import React, { PureComponent } from 'react';
import Explore from './Explore';
export default class Wrapper extends PureComponent<any, any> {
state = {
initialState: null,
split: false,
};
handleChangeSplit = (split, initialState) => {
this.setState({ split, initialState });
};
render() {
// State overrides for props from first Explore
const { initialState, split } = this.state;
return (
<div className="explore-wrapper">
<Explore {...this.props} position="left" onChangeSplit={this.handleChangeSplit} split={split} />
{split ? (
<Explore
{...this.props}
initialState={initialState}
onChangeSplit={this.handleChangeSplit}
position="right"
split={split}
/>
) : null}
</div>
);
}
}
| public/app/containers/Explore/Wrapper.tsx | 0 | https://github.com/grafana/grafana/commit/7905c29875a29d230af476e41cb070b13bc9de73 | [
0.00017619223217479885,
0.000173956184880808,
0.00017208057397510856,
0.0001737759739626199,
0.0000014655348650194355
] |
{
"id": 2,
"code_window": [
"\n",
"\t\tif metricIndex >= 0 {\n",
"\t\t\tif columnValue, ok := values[metricIndex].(string); ok {\n",
"\t\t\t\tmetric = columnValue\n",
"\t\t\t} else {\n",
"\t\t\t\treturn fmt.Errorf(\"Column metric must be of type %s. metric column name: %s type: %s but datatype is %T\", strings.Join(e.metricColumnTypes, \", \"), columnNames[metricIndex], columnTypes[metricIndex].DatabaseTypeName(), values[metricIndex])\n",
"\t\t\t}\n",
"\t\t}\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t\tif metricPrefix {\n",
"\t\t\t\t\tmetricPrefixValue = columnValue\n",
"\t\t\t\t} else {\n",
"\t\t\t\t\tmetric = columnValue\n",
"\t\t\t\t}\n"
],
"file_path": "pkg/tsdb/sql_engine.go",
"type": "replace",
"edit_start_line_idx": 303
} | .page-header-canvas {
background: $page-header-bg;
box-shadow: $page-header-shadow;
border-bottom: 1px solid $page-header-border-color;
}
.page-header {
padding: 2.5rem 0 0 0;
.btn {
float: right;
margin-left: 1rem;
// better align icons
.fa {
position: relative;
top: 1px;
}
}
}
.page-header__inner {
flex-grow: 1;
display: flex;
margin-bottom: 2.5rem;
}
.page-header__title {
font-size: $font-size-h2;
margin-bottom: 1px;
padding-top: $spacer;
}
.page-header__img {
position: relative;
top: 10px;
height: 50px;
}
.page-header__icon {
font-size: 50px;
width: 50px;
height: 50px;
position: relative;
&.fa {
top: 10px;
}
&.gicon {
top: 10px;
}
&.icon-gf {
top: 3px;
}
}
.page-header__logo {
margin: 0 $spacer;
}
.page-header__sub-title {
color: $text-muted;
}
.page-header-stamps-type {
color: $link-color-disabled;
text-transform: uppercase;
}
.page-header__select-nav {
margin-bottom: 10px;
max-width: 100%;
@include media-breakpoint-up(lg) {
display: none;
}
}
.page-header__tabs {
display: none;
@include media-breakpoint-up(lg) {
display: block;
}
}
.page-breadcrumbs {
display: flex;
padding: 10px 0;
line-height: 0.5;
}
.breadcrumb {
display: inline-block;
box-shadow: 0 0 15px 1px rgba(0, 0, 0, 0.35);
overflow: hidden;
border-radius: 5px;
counter-reset: flag;
}
.breadcrumb-item {
@include gradientBar($btn-inverse-bg, $btn-inverse-bg-hl, $btn-inverse-text-color);
text-decoration: none;
outline: none;
display: block;
float: left;
font-size: 12px;
line-height: 30px;
padding: 0 7px 0 37px;
position: relative;
box-shadow: $card-shadow;
&:first-child {
padding-left: 10px;
border-radius: 5px 0 0 5px; /*to match with the parent's radius*/
font-size: 18px;
}
&:first-child::before {
left: 14px;
}
&:last-child {
border-radius: 0 5px 5px 0; /*this was to prevent glitches on hover*/
padding-right: 20px;
}
&.active,
&:hover {
background: #333;
background: linear-gradient(#333, #000);
}
&.active::after,
&:hover::after {
background: #333;
background: linear-gradient(135deg, #333, #000);
}
&::after {
content: '';
position: absolute;
top: 0;
right: -14px; // half of square's length
// same dimension as the line-height of .breadcrumb-item
width: 30px;
height: 30px;
transform: scale(0.707) rotate(45deg);
// we need to prevent the arrows from getting buried under the next link
z-index: 1;
// background same as links but the gradient will be rotated to compensate with the transform applied
background: linear-gradient(135deg, $btn-inverse-bg, $btn-inverse-bg-hl);
// stylish arrow design using box shadow
box-shadow: 2px -2px 0 2px rgb(35, 31, 31), 3px -3px 0 2px rgba(255, 255, 255, 0.1);
// 5px - for rounded arrows and
// 50px - to prevent hover glitches on the border created using shadows*/
border-radius: 0 5px 0 50px;
}
// we dont need an arrow after the last link
&:last-child::after {
content: none;
}
}
| public/sass/components/_page_header.scss | 0 | https://github.com/grafana/grafana/commit/7905c29875a29d230af476e41cb070b13bc9de73 | [
0.00017984493752010167,
0.0001740111329127103,
0.00016542784578632563,
0.00017428809951525182,
0.0000036585504403774394
] |
{
"id": 3,
"code_window": [
"\n",
"\t\t\tif metricIndex == -1 {\n",
"\t\t\t\tmetric = col\n",
"\t\t\t}\n",
"\n",
"\t\t\tseries, exist := pointsBySeries[metric]\n",
"\t\t\tif !exist {\n",
"\t\t\t\tseries = &TimeSeries{Name: metric}\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t} else if metricPrefix {\n",
"\t\t\t\tmetric = metricPrefixValue + \" \" + col\n"
],
"file_path": "pkg/tsdb/sql_engine.go",
"type": "add",
"edit_start_line_idx": 320
} | package tsdb
import (
"container/list"
"context"
"database/sql"
"fmt"
"math"
"strings"
"sync"
"time"
"github.com/grafana/grafana/pkg/log"
"github.com/grafana/grafana/pkg/components/null"
"github.com/go-xorm/core"
"github.com/go-xorm/xorm"
"github.com/grafana/grafana/pkg/components/simplejson"
"github.com/grafana/grafana/pkg/models"
)
// SqlMacroEngine interpolates macros into sql. It takes in the Query to have access to query context and
// timeRange to be able to generate queries that use from and to.
type SqlMacroEngine interface {
Interpolate(query *Query, timeRange *TimeRange, sql string) (string, error)
}
// SqlTableRowTransformer transforms a query result row to RowValues with proper types.
type SqlTableRowTransformer interface {
Transform(columnTypes []*sql.ColumnType, rows *core.Rows) (RowValues, error)
}
type engineCacheType struct {
cache map[int64]*xorm.Engine
versions map[int64]int
sync.Mutex
}
var engineCache = engineCacheType{
cache: make(map[int64]*xorm.Engine),
versions: make(map[int64]int),
}
var NewXormEngine = func(driverName string, connectionString string) (*xorm.Engine, error) {
return xorm.NewEngine(driverName, connectionString)
}
type sqlQueryEndpoint struct {
macroEngine SqlMacroEngine
rowTransformer SqlTableRowTransformer
engine *xorm.Engine
timeColumnNames []string
metricColumnTypes []string
log log.Logger
}
type SqlQueryEndpointConfiguration struct {
DriverName string
Datasource *models.DataSource
ConnectionString string
TimeColumnNames []string
MetricColumnTypes []string
}
var NewSqlQueryEndpoint = func(config *SqlQueryEndpointConfiguration, rowTransformer SqlTableRowTransformer, macroEngine SqlMacroEngine, log log.Logger) (TsdbQueryEndpoint, error) {
queryEndpoint := sqlQueryEndpoint{
rowTransformer: rowTransformer,
macroEngine: macroEngine,
timeColumnNames: []string{"time"},
log: log,
}
if len(config.TimeColumnNames) > 0 {
queryEndpoint.timeColumnNames = config.TimeColumnNames
}
engineCache.Lock()
defer engineCache.Unlock()
if engine, present := engineCache.cache[config.Datasource.Id]; present {
if version := engineCache.versions[config.Datasource.Id]; version == config.Datasource.Version {
queryEndpoint.engine = engine
return &queryEndpoint, nil
}
}
engine, err := NewXormEngine(config.DriverName, config.ConnectionString)
if err != nil {
return nil, err
}
engine.SetMaxOpenConns(10)
engine.SetMaxIdleConns(10)
engineCache.versions[config.Datasource.Id] = config.Datasource.Version
engineCache.cache[config.Datasource.Id] = engine
queryEndpoint.engine = engine
return &queryEndpoint, nil
}
const rowLimit = 1000000
// Query is the main function for the SqlQueryEndpoint
func (e *sqlQueryEndpoint) Query(ctx context.Context, dsInfo *models.DataSource, tsdbQuery *TsdbQuery) (*Response, error) {
result := &Response{
Results: make(map[string]*QueryResult),
}
session := e.engine.NewSession()
defer session.Close()
db := session.DB()
for _, query := range tsdbQuery.Queries {
rawSQL := query.Model.Get("rawSql").MustString()
if rawSQL == "" {
continue
}
queryResult := &QueryResult{Meta: simplejson.New(), RefId: query.RefId}
result.Results[query.RefId] = queryResult
rawSQL, err := e.macroEngine.Interpolate(query, tsdbQuery.TimeRange, rawSQL)
if err != nil {
queryResult.Error = err
continue
}
queryResult.Meta.Set("sql", rawSQL)
rows, err := db.Query(rawSQL)
if err != nil {
queryResult.Error = err
continue
}
defer rows.Close()
format := query.Model.Get("format").MustString("time_series")
switch format {
case "time_series":
err := e.transformToTimeSeries(query, rows, queryResult, tsdbQuery)
if err != nil {
queryResult.Error = err
continue
}
case "table":
err := e.transformToTable(query, rows, queryResult, tsdbQuery)
if err != nil {
queryResult.Error = err
continue
}
}
}
return result, nil
}
func (e *sqlQueryEndpoint) transformToTable(query *Query, rows *core.Rows, result *QueryResult, tsdbQuery *TsdbQuery) error {
columnNames, err := rows.Columns()
columnCount := len(columnNames)
if err != nil {
return err
}
rowCount := 0
timeIndex := -1
table := &Table{
Columns: make([]TableColumn, columnCount),
Rows: make([]RowValues, 0),
}
for i, name := range columnNames {
table.Columns[i].Text = name
for _, tc := range e.timeColumnNames {
if name == tc {
timeIndex = i
break
}
}
}
columnTypes, err := rows.ColumnTypes()
if err != nil {
return err
}
for ; rows.Next(); rowCount++ {
if rowCount > rowLimit {
return fmt.Errorf("query row limit exceeded, limit %d", rowLimit)
}
values, err := e.rowTransformer.Transform(columnTypes, rows)
if err != nil {
return err
}
// converts column named time to unix timestamp in milliseconds
// to make native mssql datetime types and epoch dates work in
// annotation and table queries.
ConvertSqlTimeColumnToEpochMs(values, timeIndex)
table.Rows = append(table.Rows, values)
}
result.Tables = append(result.Tables, table)
result.Meta.Set("rowCount", rowCount)
return nil
}
func (e *sqlQueryEndpoint) transformToTimeSeries(query *Query, rows *core.Rows, result *QueryResult, tsdbQuery *TsdbQuery) error {
pointsBySeries := make(map[string]*TimeSeries)
seriesByQueryOrder := list.New()
columnNames, err := rows.Columns()
if err != nil {
return err
}
columnTypes, err := rows.ColumnTypes()
if err != nil {
return err
}
rowCount := 0
timeIndex := -1
metricIndex := -1
// check columns of resultset: a column named time is mandatory
// the first text column is treated as metric name unless a column named metric is present
for i, col := range columnNames {
for _, tc := range e.timeColumnNames {
if col == tc {
timeIndex = i
continue
}
}
switch col {
case "metric":
metricIndex = i
default:
if metricIndex == -1 {
columnType := columnTypes[i].DatabaseTypeName()
for _, mct := range e.metricColumnTypes {
if columnType == mct {
metricIndex = i
continue
}
}
}
}
}
if timeIndex == -1 {
return fmt.Errorf("Found no column named %s", strings.Join(e.timeColumnNames, " or "))
}
fillMissing := query.Model.Get("fill").MustBool(false)
var fillInterval float64
fillValue := null.Float{}
if fillMissing {
fillInterval = query.Model.Get("fillInterval").MustFloat64() * 1000
if !query.Model.Get("fillNull").MustBool(false) {
fillValue.Float64 = query.Model.Get("fillValue").MustFloat64()
fillValue.Valid = true
}
}
for rows.Next() {
var timestamp float64
var value null.Float
var metric string
if rowCount > rowLimit {
return fmt.Errorf("query row limit exceeded, limit %d", rowLimit)
}
values, err := e.rowTransformer.Transform(columnTypes, rows)
if err != nil {
return err
}
// converts column named time to unix timestamp in milliseconds to make
// native mysql datetime types and epoch dates work in
// annotation and table queries.
ConvertSqlTimeColumnToEpochMs(values, timeIndex)
switch columnValue := values[timeIndex].(type) {
case int64:
timestamp = float64(columnValue)
case float64:
timestamp = columnValue
default:
return fmt.Errorf("Invalid type for column time, must be of type timestamp or unix timestamp, got: %T %v", columnValue, columnValue)
}
if metricIndex >= 0 {
if columnValue, ok := values[metricIndex].(string); ok {
metric = columnValue
} else {
return fmt.Errorf("Column metric must be of type %s. metric column name: %s type: %s but datatype is %T", strings.Join(e.metricColumnTypes, ", "), columnNames[metricIndex], columnTypes[metricIndex].DatabaseTypeName(), values[metricIndex])
}
}
for i, col := range columnNames {
if i == timeIndex || i == metricIndex {
continue
}
if value, err = ConvertSqlValueColumnToFloat(col, values[i]); err != nil {
return err
}
if metricIndex == -1 {
metric = col
}
series, exist := pointsBySeries[metric]
if !exist {
series = &TimeSeries{Name: metric}
pointsBySeries[metric] = series
seriesByQueryOrder.PushBack(metric)
}
if fillMissing {
var intervalStart float64
if !exist {
intervalStart = float64(tsdbQuery.TimeRange.MustGetFrom().UnixNano() / 1e6)
} else {
intervalStart = series.Points[len(series.Points)-1][1].Float64 + fillInterval
}
// align interval start
intervalStart = math.Floor(intervalStart/fillInterval) * fillInterval
for i := intervalStart; i < timestamp; i += fillInterval {
series.Points = append(series.Points, TimePoint{fillValue, null.FloatFrom(i)})
rowCount++
}
}
series.Points = append(series.Points, TimePoint{value, null.FloatFrom(timestamp)})
e.log.Debug("Rows", "metric", metric, "time", timestamp, "value", value)
}
}
for elem := seriesByQueryOrder.Front(); elem != nil; elem = elem.Next() {
key := elem.Value.(string)
result.Series = append(result.Series, pointsBySeries[key])
if fillMissing {
series := pointsBySeries[key]
// fill in values from last fetched value till interval end
intervalStart := series.Points[len(series.Points)-1][1].Float64
intervalEnd := float64(tsdbQuery.TimeRange.MustGetTo().UnixNano() / 1e6)
// align interval start
intervalStart = math.Floor(intervalStart/fillInterval) * fillInterval
for i := intervalStart + fillInterval; i < intervalEnd; i += fillInterval {
series.Points = append(series.Points, TimePoint{fillValue, null.FloatFrom(i)})
rowCount++
}
}
}
result.Meta.Set("rowCount", rowCount)
return nil
}
// ConvertSqlTimeColumnToEpochMs converts column named time to unix timestamp in milliseconds
// to make native datetime types and epoch dates work in annotation and table queries.
func ConvertSqlTimeColumnToEpochMs(values RowValues, timeIndex int) {
if timeIndex >= 0 {
switch value := values[timeIndex].(type) {
case time.Time:
values[timeIndex] = float64(value.UnixNano()) / float64(time.Millisecond)
case *time.Time:
if value != nil {
values[timeIndex] = float64((*value).UnixNano()) / float64(time.Millisecond)
}
case int64:
values[timeIndex] = int64(EpochPrecisionToMs(float64(value)))
case *int64:
if value != nil {
values[timeIndex] = int64(EpochPrecisionToMs(float64(*value)))
}
case uint64:
values[timeIndex] = int64(EpochPrecisionToMs(float64(value)))
case *uint64:
if value != nil {
values[timeIndex] = int64(EpochPrecisionToMs(float64(*value)))
}
case int32:
values[timeIndex] = int64(EpochPrecisionToMs(float64(value)))
case *int32:
if value != nil {
values[timeIndex] = int64(EpochPrecisionToMs(float64(*value)))
}
case uint32:
values[timeIndex] = int64(EpochPrecisionToMs(float64(value)))
case *uint32:
if value != nil {
values[timeIndex] = int64(EpochPrecisionToMs(float64(*value)))
}
case float64:
values[timeIndex] = EpochPrecisionToMs(value)
case *float64:
if value != nil {
values[timeIndex] = EpochPrecisionToMs(*value)
}
case float32:
values[timeIndex] = EpochPrecisionToMs(float64(value))
case *float32:
if value != nil {
values[timeIndex] = EpochPrecisionToMs(float64(*value))
}
}
}
}
// ConvertSqlValueColumnToFloat converts timeseries value column to float.
func ConvertSqlValueColumnToFloat(columnName string, columnValue interface{}) (null.Float, error) {
var value null.Float
switch typedValue := columnValue.(type) {
case int:
value = null.FloatFrom(float64(typedValue))
case *int:
if typedValue == nil {
value.Valid = false
} else {
value = null.FloatFrom(float64(*typedValue))
}
case int64:
value = null.FloatFrom(float64(typedValue))
case *int64:
if typedValue == nil {
value.Valid = false
} else {
value = null.FloatFrom(float64(*typedValue))
}
case int32:
value = null.FloatFrom(float64(typedValue))
case *int32:
if typedValue == nil {
value.Valid = false
} else {
value = null.FloatFrom(float64(*typedValue))
}
case int16:
value = null.FloatFrom(float64(typedValue))
case *int16:
if typedValue == nil {
value.Valid = false
} else {
value = null.FloatFrom(float64(*typedValue))
}
case int8:
value = null.FloatFrom(float64(typedValue))
case *int8:
if typedValue == nil {
value.Valid = false
} else {
value = null.FloatFrom(float64(*typedValue))
}
case uint:
value = null.FloatFrom(float64(typedValue))
case *uint:
if typedValue == nil {
value.Valid = false
} else {
value = null.FloatFrom(float64(*typedValue))
}
case uint64:
value = null.FloatFrom(float64(typedValue))
case *uint64:
if typedValue == nil {
value.Valid = false
} else {
value = null.FloatFrom(float64(*typedValue))
}
case uint32:
value = null.FloatFrom(float64(typedValue))
case *uint32:
if typedValue == nil {
value.Valid = false
} else {
value = null.FloatFrom(float64(*typedValue))
}
case uint16:
value = null.FloatFrom(float64(typedValue))
case *uint16:
if typedValue == nil {
value.Valid = false
} else {
value = null.FloatFrom(float64(*typedValue))
}
case uint8:
value = null.FloatFrom(float64(typedValue))
case *uint8:
if typedValue == nil {
value.Valid = false
} else {
value = null.FloatFrom(float64(*typedValue))
}
case float64:
value = null.FloatFrom(typedValue)
case *float64:
value = null.FloatFromPtr(typedValue)
case float32:
value = null.FloatFrom(float64(typedValue))
case *float32:
if typedValue == nil {
value.Valid = false
} else {
value = null.FloatFrom(float64(*typedValue))
}
case nil:
value.Valid = false
default:
return null.NewFloat(0, false), fmt.Errorf("Value column must have numeric datatype, column: %s type: %T value: %v", columnName, typedValue, typedValue)
}
return value, nil
}
| pkg/tsdb/sql_engine.go | 1 | https://github.com/grafana/grafana/commit/7905c29875a29d230af476e41cb070b13bc9de73 | [
0.9978502988815308,
0.10982666909694672,
0.00016582645184826106,
0.00017502755508758128,
0.30870553851127625
] |
{
"id": 3,
"code_window": [
"\n",
"\t\t\tif metricIndex == -1 {\n",
"\t\t\t\tmetric = col\n",
"\t\t\t}\n",
"\n",
"\t\t\tseries, exist := pointsBySeries[metric]\n",
"\t\t\tif !exist {\n",
"\t\t\t\tseries = &TimeSeries{Name: metric}\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t} else if metricPrefix {\n",
"\t\t\t\tmetric = metricPrefixValue + \" \" + col\n"
],
"file_path": "pkg/tsdb/sql_engine.go",
"type": "add",
"edit_start_line_idx": 320
} | import angular from 'angular';
import _ from 'lodash';
import { QueryCtrl } from 'app/plugins/sdk';
import { PromCompleter } from './completer';
import './mode-prometheus';
import './snippets/prometheus';
class PrometheusQueryCtrl extends QueryCtrl {
static templateUrl = 'partials/query.editor.html';
metric: any;
resolutions: any;
formats: any;
instant: any;
oldTarget: any;
suggestMetrics: any;
getMetricsAutocomplete: any;
linkToPrometheus: any;
/** @ngInject */
constructor($scope, $injector, private templateSrv) {
super($scope, $injector);
var target = this.target;
target.expr = target.expr || '';
target.intervalFactor = target.intervalFactor || 1;
target.format = target.format || this.getDefaultFormat();
this.metric = '';
this.resolutions = _.map([1, 2, 3, 4, 5, 10], function(f) {
return { factor: f, label: '1/' + f };
});
this.formats = [
{ text: 'Time series', value: 'time_series' },
{ text: 'Table', value: 'table' },
{ text: 'Heatmap', value: 'heatmap' },
];
this.instant = false;
this.updateLink();
}
getCompleter(query) {
return new PromCompleter(this.datasource, this.templateSrv);
}
getDefaultFormat() {
if (this.panelCtrl.panel.type === 'table') {
return 'table';
} else if (this.panelCtrl.panel.type === 'heatmap') {
return 'heatmap';
}
return 'time_series';
}
refreshMetricData() {
if (!_.isEqual(this.oldTarget, this.target)) {
this.oldTarget = angular.copy(this.target);
this.panelCtrl.refresh();
this.updateLink();
}
}
updateLink() {
var range = this.panelCtrl.range;
if (!range) {
return;
}
var rangeDiff = Math.ceil((range.to.valueOf() - range.from.valueOf()) / 1000);
var endTime = range.to.utc().format('YYYY-MM-DD HH:mm');
var expr = {
'g0.expr': this.templateSrv.replace(
this.target.expr,
this.panelCtrl.panel.scopedVars,
this.datasource.interpolateQueryExpr
),
'g0.range_input': rangeDiff + 's',
'g0.end_input': endTime,
'g0.step_input': this.target.step,
'g0.stacked': this.panelCtrl.panel.stack ? 1 : 0,
'g0.tab': 0,
};
var args = _.map(expr, (v, k) => {
return k + '=' + encodeURIComponent(v);
}).join('&');
this.linkToPrometheus = this.datasource.directUrl + '/graph?' + args;
}
getCollapsedText() {
return this.target.expr;
}
}
export { PrometheusQueryCtrl };
| public/app/plugins/datasource/prometheus/query_ctrl.ts | 0 | https://github.com/grafana/grafana/commit/7905c29875a29d230af476e41cb070b13bc9de73 | [
0.00033650273690000176,
0.00018911830557044595,
0.0001634332147659734,
0.00017331965500488877,
0.00004925430766888894
] |
{
"id": 3,
"code_window": [
"\n",
"\t\t\tif metricIndex == -1 {\n",
"\t\t\t\tmetric = col\n",
"\t\t\t}\n",
"\n",
"\t\t\tseries, exist := pointsBySeries[metric]\n",
"\t\t\tif !exist {\n",
"\t\t\t\tseries = &TimeSeries{Name: metric}\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t} else if metricPrefix {\n",
"\t\t\t\tmetric = metricPrefixValue + \" \" + col\n"
],
"file_path": "pkg/tsdb/sql_engine.go",
"type": "add",
"edit_start_line_idx": 320
} |
<div class="search-backdrop" ng-if="ctrl.isOpen"></div>
<div class="search-container" ng-if="ctrl.isOpen">
<div class="search-field-wrapper">
<div class="search-field-icon pointer" ng-click="ctrl.closeSearch()"><i class="fa fa-search"></i></div>
<input type="text" placeholder="Find dashboards by name" give-focus="ctrl.giveSearchFocus" tabindex="1"
ng-keydown="ctrl.keyDown($event)"
ng-model="ctrl.query.query"
ng-model-options="{ debounce: 500 }"
spellcheck='false'
ng-change="ctrl.search()"
/>
<div class="search-field-spacer"></div>
</div>
<div class="search-dropdown">
<div class="search-dropdown__col_1">
<div class="search-results-scroller">
<div class="search-results-container" grafana-scrollbar>
<h6 ng-show="!ctrl.isLoading && ctrl.results.length === 0">No dashboards matching your query were found.</h6>
<dashboard-search-results
results="ctrl.results"
on-tag-selected="ctrl.filterByTag($tag)"
on-folder-expanding="ctrl.folderExpanding()"
on-folder-expanded="ctrl.folderExpanded($folder)" />
</div>
</div>
</div>
<div class="search-dropdown__col_2">
<div class="search-filter-box" ng-click="ctrl.onFilterboxClick()">
<div class="search-filter-box__header">
<i class="fa fa-filter"></i>
Filter by:
<a class="pointer pull-right small" ng-click="ctrl.clearSearchFilter()">
<i class="fa fa-remove"></i> Clear
</a>
</div>
<tag-filter tags="ctrl.query.tag" tagOptions="ctrl.getTags" onSelect="ctrl.onTagSelect">
</tag-filter>
</div>
<div class="search-filter-box" ng-if="ctrl.isEditor || ctrl.hasEditPermissionInFolders">
<a href="dashboard/new" class="search-filter-box-link">
<i class="gicon gicon-dashboard-new"></i> New dashboard
</a>
<a href="dashboards/folder/new" class="search-filter-box-link" ng-if="ctrl.isEditor">
<i class="gicon gicon-folder-new"></i> New folder
</a>
<a href="dashboard/import" class="search-filter-box-link" ng-if="ctrl.isEditor || ctrl.hasEditPermissionInFolders">
<i class="gicon gicon-dashboard-import"></i> Import dashboard
</a>
<a class="search-filter-box-link" target="_blank" href="https://grafana.com/dashboards?utm_source=grafana_search">
<img src="public/img/icn-dashboard-tiny.svg" width="20" /> Find dashboards on Grafana.com
</a>
</div>
</div>
</div>
</div>
| public/app/core/components/search/search.html | 0 | https://github.com/grafana/grafana/commit/7905c29875a29d230af476e41cb070b13bc9de73 | [
0.0001771598617779091,
0.00017082516569644213,
0.00016637967200949788,
0.00017045455751940608,
0.000002978892780447495
] |
{
"id": 3,
"code_window": [
"\n",
"\t\t\tif metricIndex == -1 {\n",
"\t\t\t\tmetric = col\n",
"\t\t\t}\n",
"\n",
"\t\t\tseries, exist := pointsBySeries[metric]\n",
"\t\t\tif !exist {\n",
"\t\t\t\tseries = &TimeSeries{Name: metric}\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t} else if metricPrefix {\n",
"\t\t\t\tmetric = metricPrefixValue + \" \" + col\n"
],
"file_path": "pkg/tsdb/sql_engine.go",
"type": "add",
"edit_start_line_idx": 320
} | dn: ou=groups,dc=grafana,dc=org
ou: Groups
objectclass: top
objectclass: organizationalUnit
dn: ou=users,dc=grafana,dc=org
ou: Users
objectclass: top
objectclass: organizationalUnit
| docker/blocks/openldap/prepopulate/1_units.ldif | 0 | https://github.com/grafana/grafana/commit/7905c29875a29d230af476e41cb070b13bc9de73 | [
0.00017573803779669106,
0.00017573803779669106,
0.00017573803779669106,
0.00017573803779669106,
0
] |
{
"id": 4,
"code_window": [
"\t\t<pre class=\"gf-form-pre alert alert-info\">Time series:\n",
"- return column named <i>time</i> (UTC in seconds or timestamp)\n",
"- return column(s) with numeric datatype as values\n",
"- (Optional: return column named <i>metric</i> to represent the series name. If no column named metric is found the column name of the value column is used as series name)\n",
"\n",
"Table:\n",
"- return any set of columns\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"Optional: \n",
" - return column named <i>metric</i> to represent the series name. \n",
" - If multiple value columns are returned the metric column is used as prefix. \n",
" - If no column named metric is found the column name of the value column is used as series name\n"
],
"file_path": "public/app/plugins/datasource/postgres/partials/query.editor.html",
"type": "replace",
"edit_start_line_idx": 42
} | <query-editor-row query-ctrl="ctrl" can-collapse="false">
<div class="gf-form-inline">
<div class="gf-form gf-form--grow">
<code-editor content="ctrl.target.rawSql" datasource="ctrl.datasource" on-change="ctrl.panelCtrl.refresh()" data-mode="sql">
</code-editor>
</div>
</div>
<div class="gf-form-inline">
<div class="gf-form">
<label class="gf-form-label query-keyword">Format as</label>
<div class="gf-form-select-wrapper">
<select class="gf-form-input gf-size-auto" ng-model="ctrl.target.format" ng-options="f.value as f.text for f in ctrl.formats" ng-change="ctrl.refresh()"></select>
</div>
</div>
<div class="gf-form">
<label class="gf-form-label query-keyword" ng-click="ctrl.showHelp = !ctrl.showHelp">
Show Help
<i class="fa fa-caret-down" ng-show="ctrl.showHelp"></i>
<i class="fa fa-caret-right" ng-hide="ctrl.showHelp"></i>
</label>
</div>
<div class="gf-form" ng-show="ctrl.lastQueryMeta">
<label class="gf-form-label query-keyword" ng-click="ctrl.showLastQuerySQL = !ctrl.showLastQuerySQL">
Generated SQL
<i class="fa fa-caret-down" ng-show="ctrl.showLastQuerySQL"></i>
<i class="fa fa-caret-right" ng-hide="ctrl.showLastQuerySQL"></i>
</label>
</div>
<div class="gf-form gf-form--grow">
<div class="gf-form-label gf-form-label--grow"></div>
</div>
</div>
<div class="gf-form" ng-show="ctrl.showLastQuerySQL">
<pre class="gf-form-pre">{{ctrl.lastQueryMeta.sql}}</pre>
</div>
<div class="gf-form" ng-show="ctrl.showHelp">
<pre class="gf-form-pre alert alert-info">Time series:
- return column named <i>time</i> (UTC in seconds or timestamp)
- return column(s) with numeric datatype as values
- (Optional: return column named <i>metric</i> to represent the series name. If no column named metric is found the column name of the value column is used as series name)
Table:
- return any set of columns
Macros:
- $__time(column) -> column as "time"
- $__timeEpoch -> extract(epoch from column) as "time"
- $__timeFilter(column) -> column BETWEEN '2017-04-21T05:01:17Z' AND '2017-04-21T05:01:17Z'
- $__unixEpochFilter(column) -> column >= 1492750877 AND column <= 1492750877
- $__timeGroup(column,'5m') -> (extract(epoch from column)/300)::bigint*300 AS time
Example of group by and order by with $__timeGroup:
SELECT
$__timeGroup(date_time_col, '1h'),
sum(value) as value
FROM yourtable
GROUP BY time
ORDER BY time
Or build your own conditionals using these macros which just return the values:
- $__timeFrom() -> '2017-04-21T05:01:17Z'
- $__timeTo() -> '2017-04-21T05:01:17Z'
- $__unixEpochFrom() -> 1492750877
- $__unixEpochTo() -> 1492750877
</pre>
</div>
</div>
<div class="gf-form" ng-show="ctrl.lastQueryError">
<pre class="gf-form-pre alert alert-error">{{ctrl.lastQueryError}}</pre>
</div>
</query-editor-row>
| public/app/plugins/datasource/postgres/partials/query.editor.html | 1 | https://github.com/grafana/grafana/commit/7905c29875a29d230af476e41cb070b13bc9de73 | [
0.9954985976219177,
0.12579722702503204,
0.0001675929524935782,
0.00024679189664311707,
0.3287228047847748
] |
{
"id": 4,
"code_window": [
"\t\t<pre class=\"gf-form-pre alert alert-info\">Time series:\n",
"- return column named <i>time</i> (UTC in seconds or timestamp)\n",
"- return column(s) with numeric datatype as values\n",
"- (Optional: return column named <i>metric</i> to represent the series name. If no column named metric is found the column name of the value column is used as series name)\n",
"\n",
"Table:\n",
"- return any set of columns\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"Optional: \n",
" - return column named <i>metric</i> to represent the series name. \n",
" - If multiple value columns are returned the metric column is used as prefix. \n",
" - If no column named metric is found the column name of the value column is used as series name\n"
],
"file_path": "public/app/plugins/datasource/postgres/partials/query.editor.html",
"type": "replace",
"edit_start_line_idx": 42
} | +++
title = "What's New in Grafana v4.5"
description = "Feature & improvement highlights for Grafana v4.5"
keywords = ["grafana", "new", "documentation", "4.5"]
type = "docs"
[menu.docs]
name = "Version 4.5"
identifier = "v4.5"
parent = "whatsnew"
weight = -4
+++
# What's New in Grafana v4.5
## Highlights
### New prometheus query editor
The new query editor has full syntax highlighting. As well as auto complete for metrics, functions, and range vectors. There is also integrated function docs right from the query editor!
{{< docs-imagebox img="/img/docs/v45/prometheus_query_editor_still.png" class="docs-image--block" animated-gif="/img/docs/v45/prometheus_query_editor.gif" >}}
### Elasticsearch: Add ad-hoc filters from the table panel
{{< docs-imagebox img="/img/docs/v45/elastic_ad_hoc_filters.png" class="docs-image--block" >}}
### Table cell links!
Create column styles that turn cells into links that use the value in the cell (or other other row values) to generate a url to another dashboard or system:

### Query Inspector
Query Inspector is a new feature that shows query requests and responses. This can be helpful if a graph is not shown or shows something very different than what you expected.
More information [here](https://community.grafana.com/t/using-grafanas-query-inspector-to-troubleshoot-issues/2630).

## Changelog
### New Features
* **Table panel**: Render cell values as links that can have an url template that uses variables from current table row. [#3754](https://github.com/grafana/grafana/issues/3754)
* **Elasticsearch**: Add ad hoc filters directly by clicking values in table panel [#8052](https://github.com/grafana/grafana/issues/8052).
* **MySQL**: New rich query editor with syntax highlighting
* **Prometheus**: New rich query editor with syntax highlighting, metric & range auto complete and integrated function docs. [#5117](https://github.com/grafana/grafana/issues/5117)
### Enhancements
* **GitHub OAuth**: Support for GitHub organizations with 100+ teams. [#8846](https://github.com/grafana/grafana/issues/8846), thx [@skwashd](https://github.com/skwashd)
* **Graphite**: Calls to Graphite api /metrics/find now include panel or dashboad time range (from & until) in most cases, [#8055](https://github.com/grafana/grafana/issues/8055)
* **Graphite**: Added new graphite 1.0 functions, available if you set version to 1.0.x in data source settings. New Functions: mapSeries, reduceSeries, isNonNull, groupByNodes, offsetToZero, grep, weightedAverage, removeEmptySeries, aggregateLine, averageOutsidePercentile, delay, exponentialMovingAverage, fallbackSeries, integralByInterval, interpolate, invert, linearRegression, movingMin, movingMax, movingSum, multiplySeriesWithWildcards, pow, powSeries, removeBetweenPercentile, squareRoot, timeSlice, closes [#8261](https://github.com/grafana/grafana/issues/8261)
- **Elasticsearch**: Ad-hoc filters now use query phrase match filters instead of term filters, works on non keyword/raw fields [#9095](https://github.com/grafana/grafana/issues/9095).
### Breaking change
* **InfluxDB/Elasticsearch**: The panel & data source option named "Group by time interval" is now named "Min time interval" and does now always define a lower limit for the auto group by time. Without having to use `>` prefix (that prefix still works). This should in theory have close to zero actual impact on existing dashboards. It does mean that if you used this setting to define a hard group by time interval of, say "1d", if you zoomed to a time range wide enough the time range could increase above the "1d" range as the setting is now always considered a lower limit.
This option is now rennamed (and moved to Options sub section above your queries):

Datas source selection & options & help are now above your metric queries.

### Minor Changes
* **InfluxDB**: Change time range filter for absolute time ranges to be inclusive instead of exclusive [#8319](https://github.com/grafana/grafana/issues/8319), thx [@Oxydros](https://github.com/Oxydros)
* **InfluxDB**: Added parenthesis around tag filters in queries [#9131](https://github.com/grafana/grafana/pull/9131)
## Bug Fixes
* **Modals**: Maintain scroll position after opening/leaving modal [#8800](https://github.com/grafana/grafana/issues/8800)
* **Templating**: You cannot select data source variables as data source for other template variables [#7510](https://github.com/grafana/grafana/issues/7510)
| docs/sources/guides/whats-new-in-v4-5.md | 0 | https://github.com/grafana/grafana/commit/7905c29875a29d230af476e41cb070b13bc9de73 | [
0.0002092688373522833,
0.00017324658983852714,
0.00016374504775740206,
0.00016887474339455366,
0.00001399171924276743
] |
{
"id": 4,
"code_window": [
"\t\t<pre class=\"gf-form-pre alert alert-info\">Time series:\n",
"- return column named <i>time</i> (UTC in seconds or timestamp)\n",
"- return column(s) with numeric datatype as values\n",
"- (Optional: return column named <i>metric</i> to represent the series name. If no column named metric is found the column name of the value column is used as series name)\n",
"\n",
"Table:\n",
"- return any set of columns\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"Optional: \n",
" - return column named <i>metric</i> to represent the series name. \n",
" - If multiple value columns are returned the metric column is used as prefix. \n",
" - If no column named metric is found the column name of the value column is used as series name\n"
],
"file_path": "public/app/plugins/datasource/postgres/partials/query.editor.html",
"type": "replace",
"edit_start_line_idx": 42
} | package notifiers
import (
"testing"
"github.com/grafana/grafana/pkg/components/simplejson"
m "github.com/grafana/grafana/pkg/models"
. "github.com/smartystreets/goconvey/convey"
)
func TestHipChatNotifier(t *testing.T) {
Convey("HipChat notifier tests", t, func() {
Convey("Parsing alert notification from settings", func() {
Convey("empty settings should return error", func() {
json := `{ }`
settingsJSON, _ := simplejson.NewJson([]byte(json))
model := &m.AlertNotification{
Name: "ops",
Type: "hipchat",
Settings: settingsJSON,
}
_, err := NewHipChatNotifier(model)
So(err, ShouldNotBeNil)
})
Convey("from settings", func() {
json := `
{
"url": "http://google.com"
}`
settingsJSON, _ := simplejson.NewJson([]byte(json))
model := &m.AlertNotification{
Name: "ops",
Type: "hipchat",
Settings: settingsJSON,
}
not, err := NewHipChatNotifier(model)
hipchatNotifier := not.(*HipChatNotifier)
So(err, ShouldBeNil)
So(hipchatNotifier.Name, ShouldEqual, "ops")
So(hipchatNotifier.Type, ShouldEqual, "hipchat")
So(hipchatNotifier.Url, ShouldEqual, "http://google.com")
So(hipchatNotifier.ApiKey, ShouldEqual, "")
So(hipchatNotifier.RoomId, ShouldEqual, "")
})
Convey("from settings with Recipient and Mention", func() {
json := `
{
"url": "http://www.hipchat.com",
"apikey": "1234",
"roomid": "1234"
}`
settingsJSON, _ := simplejson.NewJson([]byte(json))
model := &m.AlertNotification{
Name: "ops",
Type: "hipchat",
Settings: settingsJSON,
}
not, err := NewHipChatNotifier(model)
hipchatNotifier := not.(*HipChatNotifier)
So(err, ShouldBeNil)
So(hipchatNotifier.Name, ShouldEqual, "ops")
So(hipchatNotifier.Type, ShouldEqual, "hipchat")
So(hipchatNotifier.Url, ShouldEqual, "http://www.hipchat.com")
So(hipchatNotifier.ApiKey, ShouldEqual, "1234")
So(hipchatNotifier.RoomId, ShouldEqual, "1234")
})
})
})
}
| pkg/services/alerting/notifiers/hipchat_test.go | 0 | https://github.com/grafana/grafana/commit/7905c29875a29d230af476e41cb070b13bc9de73 | [
0.0003059171431232244,
0.00020041287643834949,
0.00016611478349659592,
0.00016997155034914613,
0.000050454167649149895
] |
{
"id": 4,
"code_window": [
"\t\t<pre class=\"gf-form-pre alert alert-info\">Time series:\n",
"- return column named <i>time</i> (UTC in seconds or timestamp)\n",
"- return column(s) with numeric datatype as values\n",
"- (Optional: return column named <i>metric</i> to represent the series name. If no column named metric is found the column name of the value column is used as series name)\n",
"\n",
"Table:\n",
"- return any set of columns\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"Optional: \n",
" - return column named <i>metric</i> to represent the series name. \n",
" - If multiple value columns are returned the metric column is used as prefix. \n",
" - If no column named metric is found the column name of the value column is used as series name\n"
],
"file_path": "public/app/plugins/datasource/postgres/partials/query.editor.html",
"type": "replace",
"edit_start_line_idx": 42
} | // Package pq is a pure Go Postgres driver for the database/sql package.
package pq
import (
"path/filepath"
"syscall"
)
// Perform Windows user name lookup identically to libpq.
//
// The PostgreSQL code makes use of the legacy Win32 function
// GetUserName, and that function has not been imported into stock Go.
// GetUserNameEx is available though, the difference being that a
// wider range of names are available. To get the output to be the
// same as GetUserName, only the base (or last) component of the
// result is returned.
func userCurrent() (string, error) {
pw_name := make([]uint16, 128)
pwname_size := uint32(len(pw_name)) - 1
err := syscall.GetUserNameEx(syscall.NameSamCompatible, &pw_name[0], &pwname_size)
if err != nil {
return "", ErrCouldNotDetectUsername
}
s := syscall.UTF16ToString(pw_name)
u := filepath.Base(s)
return u, nil
}
| vendor/github.com/lib/pq/user_windows.go | 0 | https://github.com/grafana/grafana/commit/7905c29875a29d230af476e41cb070b13bc9de73 | [
0.00017061473045032471,
0.00016934408631641418,
0.00016685629088897258,
0.00017056122305803,
0.000001759269139256503
] |
{
"id": 0,
"code_window": [
"\tGetAlertRuleByUID(ctx context.Context, query *models.GetAlertRuleByUIDQuery) error\n",
"\tListAlertRules(ctx context.Context, query *models.ListAlertRulesQuery) error\n",
"\tGetRuleGroupInterval(ctx context.Context, orgID int64, namespaceUID string, ruleGroup string) (int64, error)\n",
"\tInsertAlertRules(ctx context.Context, rule []models.AlertRule) (map[string]int64, error)\n",
"\tUpdateRuleGroup(ctx context.Context, orgID int64, namespaceUID string, ruleGroup string, interval int64) error\n",
"\tUpdateAlertRules(ctx context.Context, rule []store.UpdateRule) error\n",
"\tDeleteAlertRulesByUID(ctx context.Context, orgID int64, ruleUID ...string) error\n",
"}"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "pkg/services/ngalert/provisioning/persist.go",
"type": "replace",
"edit_start_line_idx": 36
} | package provisioning
import (
"context"
"github.com/grafana/grafana/pkg/services/ngalert/models"
"github.com/grafana/grafana/pkg/services/ngalert/store"
)
// AMStore is a store of Alertmanager configurations.
//go:generate mockery --name AMConfigStore --structname MockAMConfigStore --inpackage --filename persist_mock.go --with-expecter
type AMConfigStore interface {
GetLatestAlertmanagerConfiguration(ctx context.Context, query *models.GetLatestAlertmanagerConfigurationQuery) error
UpdateAlertmanagerConfiguration(ctx context.Context, cmd *models.SaveAlertmanagerConfigurationCmd) error
}
// ProvisioningStore is a store of provisioning data for arbitrary objects.
//go:generate mockery --name ProvisioningStore --structname MockProvisioningStore --inpackage --filename provisioning_store_mock.go --with-expecter
type ProvisioningStore interface {
GetProvenance(ctx context.Context, o models.Provisionable, org int64) (models.Provenance, error)
GetProvenances(ctx context.Context, org int64, resourceType string) (map[string]models.Provenance, error)
SetProvenance(ctx context.Context, o models.Provisionable, org int64, p models.Provenance) error
DeleteProvenance(ctx context.Context, o models.Provisionable, org int64) error
}
// TransactionManager represents the ability to issue and close transactions through contexts.
type TransactionManager interface {
InTransaction(ctx context.Context, work func(ctx context.Context) error) error
}
// RuleStore represents the ability to persist and query alert rules.
type RuleStore interface {
GetAlertRuleByUID(ctx context.Context, query *models.GetAlertRuleByUIDQuery) error
ListAlertRules(ctx context.Context, query *models.ListAlertRulesQuery) error
GetRuleGroupInterval(ctx context.Context, orgID int64, namespaceUID string, ruleGroup string) (int64, error)
InsertAlertRules(ctx context.Context, rule []models.AlertRule) (map[string]int64, error)
UpdateRuleGroup(ctx context.Context, orgID int64, namespaceUID string, ruleGroup string, interval int64) error
UpdateAlertRules(ctx context.Context, rule []store.UpdateRule) error
DeleteAlertRulesByUID(ctx context.Context, orgID int64, ruleUID ...string) error
}
| pkg/services/ngalert/provisioning/persist.go | 1 | https://github.com/grafana/grafana/commit/ed6a8877371211e9466fa780e940b485ac9a64d2 | [
0.968231201171875,
0.19378569722175598,
0.00016610750753898174,
0.00017311096598859876,
0.3872227668762207
] |
{
"id": 0,
"code_window": [
"\tGetAlertRuleByUID(ctx context.Context, query *models.GetAlertRuleByUIDQuery) error\n",
"\tListAlertRules(ctx context.Context, query *models.ListAlertRulesQuery) error\n",
"\tGetRuleGroupInterval(ctx context.Context, orgID int64, namespaceUID string, ruleGroup string) (int64, error)\n",
"\tInsertAlertRules(ctx context.Context, rule []models.AlertRule) (map[string]int64, error)\n",
"\tUpdateRuleGroup(ctx context.Context, orgID int64, namespaceUID string, ruleGroup string, interval int64) error\n",
"\tUpdateAlertRules(ctx context.Context, rule []store.UpdateRule) error\n",
"\tDeleteAlertRulesByUID(ctx context.Context, orgID int64, ruleUID ...string) error\n",
"}"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "pkg/services/ngalert/provisioning/persist.go",
"type": "replace",
"edit_start_line_idx": 36
} | import { css } from '@emotion/react';
import { GrafanaTheme2 } from '@grafana/data';
import 'ol/ol.css';
/**
* Will be loaded *after* the css above
*/
export function getGlobalStyles(theme: GrafanaTheme2) {
// NOTE: this works with
// node_modules/ol/ol.css
// use !important;
// This file keeps the rules
// .ol-box {
// border: 2px solid blue;
// }
// .ol-scale-step-marker {
// background-color: #000000;
// }
// .ol-scale-step-text {
// color: #000000;
// text-shadow: -2px 0 #FFFFFF, 0 2px #FFFFFF, 2px 0 #FFFFFF, 0 -2px #FFFFFF;
// }
// .ol-scale-text {
// color: #000000;
// text-shadow: -2px 0 #FFFFFF, 0 2px #FFFFFF, 2px 0 #FFFFFF, 0 -2px #FFFFFF;
// }
// .ol-scale-singlebar {
// border: 1px solid black;
// }
// .ol-viewport, .ol-unselectable {
// -webkit-tap-highlight-color: rgba(0,0,0,0);
// }
// .ol-overviewmap .ol-overviewmap-map {
// border: 1px solid #7b98bc;
// }
// .ol-overviewmap:not(.ol-collapsed) {
// background: rgba(255,255,255,0.8);
// }
// .ol-overviewmap-box {
// border: 2px dotted rgba(0,60,136,0.7);
// }
return css`
.ol-scale-line {
background: ${theme.colors.border.weak}; // rgba(0,60,136,0.3);
}
.ol-scale-line-inner {
border: 1px solid ${theme.colors.text.primary}; // #eee;
border-top: 0px;
color: ${theme.colors.text.primary}; // #eee;
}
.ol-control {
background-color: ${theme.colors.background.secondary}; //rgba(255,255,255,0.4);
}
.ol-control:hover {
background-color: ${theme.colors.action.hover}; // rgba(255,255,255,0.6);
}
.ol-control button {
color: ${theme.colors.secondary.text}; // white;
background-color: ${theme.colors.secondary.main}; // rgba(0,60,136,0.5);
}
.ol-control button:hover {
background-color: ${theme.colors.secondary.shade}; // rgba(0,60,136,0.5);
}
.ol-control button:focus {
background-color: ${theme.colors.secondary.main}; // rgba(0,60,136,0.5);
}
.ol-attribution ul {
color: ${theme.colors.text.primary}; // #000;
text-shadow: none;
}
.ol-attribution:not(.ol-collapsed) {
background-color: ${theme.colors.background.secondary}; // rgba(255,255,255,0.8);
}
`;
}
| public/app/plugins/panel/geomap/globalStyles.ts | 0 | https://github.com/grafana/grafana/commit/ed6a8877371211e9466fa780e940b485ac9a64d2 | [
0.00017964783182833344,
0.00017651573580224067,
0.0001738207065500319,
0.00017576183017808944,
0.0000019848027932312107
] |
{
"id": 0,
"code_window": [
"\tGetAlertRuleByUID(ctx context.Context, query *models.GetAlertRuleByUIDQuery) error\n",
"\tListAlertRules(ctx context.Context, query *models.ListAlertRulesQuery) error\n",
"\tGetRuleGroupInterval(ctx context.Context, orgID int64, namespaceUID string, ruleGroup string) (int64, error)\n",
"\tInsertAlertRules(ctx context.Context, rule []models.AlertRule) (map[string]int64, error)\n",
"\tUpdateRuleGroup(ctx context.Context, orgID int64, namespaceUID string, ruleGroup string, interval int64) error\n",
"\tUpdateAlertRules(ctx context.Context, rule []store.UpdateRule) error\n",
"\tDeleteAlertRulesByUID(ctx context.Context, orgID int64, ruleUID ...string) error\n",
"}"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "pkg/services/ngalert/provisioning/persist.go",
"type": "replace",
"edit_start_line_idx": 36
} | #!/bin/bash
##
## Common variable declarations
##
DOCKER_IMAGE_NAME="grafana/grafana-plugin-ci:1.4.1-alpine"
| packages/grafana-toolkit/docker/grafana-plugin-ci-alpine/common.sh | 0 | https://github.com/grafana/grafana/commit/ed6a8877371211e9466fa780e940b485ac9a64d2 | [
0.00017280767497140914,
0.00017280767497140914,
0.00017280767497140914,
0.00017280767497140914,
0
] |
{
"id": 0,
"code_window": [
"\tGetAlertRuleByUID(ctx context.Context, query *models.GetAlertRuleByUIDQuery) error\n",
"\tListAlertRules(ctx context.Context, query *models.ListAlertRulesQuery) error\n",
"\tGetRuleGroupInterval(ctx context.Context, orgID int64, namespaceUID string, ruleGroup string) (int64, error)\n",
"\tInsertAlertRules(ctx context.Context, rule []models.AlertRule) (map[string]int64, error)\n",
"\tUpdateRuleGroup(ctx context.Context, orgID int64, namespaceUID string, ruleGroup string, interval int64) error\n",
"\tUpdateAlertRules(ctx context.Context, rule []store.UpdateRule) error\n",
"\tDeleteAlertRulesByUID(ctx context.Context, orgID int64, ruleUID ...string) error\n",
"}"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "pkg/services/ngalert/provisioning/persist.go",
"type": "replace",
"edit_start_line_idx": 36
} | import { css } from '@emotion/css';
import React, { FC } from 'react';
import { GrafanaTheme2 } from '@grafana/data';
import { LinkButton, useStyles2 } from '@grafana/ui';
import { contextSrv } from 'app/core/services/context_srv';
import { AlertmanagerAlert, AlertState } from 'app/plugins/datasource/alertmanager/types';
import { AccessControlAction } from 'app/types';
import { getInstancesPermissions } from '../../utils/access-control';
import { isGrafanaRulesSource } from '../../utils/datasource';
import { makeAMLink, makeLabelBasedSilenceLink } from '../../utils/misc';
import { AnnotationDetailsField } from '../AnnotationDetailsField';
import { Authorize } from '../Authorize';
interface AmNotificationsAlertDetailsProps {
alertManagerSourceName: string;
alert: AlertmanagerAlert;
}
export const AlertDetails: FC<AmNotificationsAlertDetailsProps> = ({ alert, alertManagerSourceName }) => {
const styles = useStyles2(getStyles);
const instancePermissions = getInstancesPermissions(alertManagerSourceName);
// For Grafana Managed alerts the Generator URL redirects to the alert rule edit page, so update permission is required
// For external alert manager the Generator URL redirects to an external service which we don't control
const isGrafanaSource = isGrafanaRulesSource(alertManagerSourceName);
const isSeeSourceButtonEnabled = isGrafanaSource
? contextSrv.hasPermission(AccessControlAction.AlertingRuleRead)
: true;
return (
<>
<div className={styles.actionsRow}>
<Authorize actions={[instancePermissions.update, instancePermissions.create]} fallback={contextSrv.isEditor}>
{alert.status.state === AlertState.Suppressed && (
<LinkButton
href={`${makeAMLink(
'/alerting/silences',
alertManagerSourceName
)}&silenceIds=${alert.status.silencedBy.join(',')}`}
className={styles.button}
icon={'bell'}
size={'sm'}
>
Manage silences
</LinkButton>
)}
{alert.status.state === AlertState.Active && (
<LinkButton
href={makeLabelBasedSilenceLink(alertManagerSourceName, alert.labels)}
className={styles.button}
icon={'bell-slash'}
size={'sm'}
>
Silence
</LinkButton>
)}
</Authorize>
{isSeeSourceButtonEnabled && alert.generatorURL && (
<LinkButton className={styles.button} href={alert.generatorURL} icon={'chart-line'} size={'sm'}>
See source
</LinkButton>
)}
</div>
{Object.entries(alert.annotations).map(([annotationKey, annotationValue]) => (
<AnnotationDetailsField key={annotationKey} annotationKey={annotationKey} value={annotationValue} />
))}
<div className={styles.receivers}>
Receivers:{' '}
{alert.receivers
.map(({ name }) => name)
.filter((name) => !!name)
.join(', ')}
</div>
</>
);
};
const getStyles = (theme: GrafanaTheme2) => ({
button: css`
& + & {
margin-left: ${theme.spacing(1)};
}
`,
actionsRow: css`
padding: ${theme.spacing(2, 0)} !important;
border-bottom: 1px solid ${theme.colors.border.medium};
`,
receivers: css`
padding: ${theme.spacing(1, 0)};
`,
});
| public/app/features/alerting/unified/components/alert-groups/AlertDetails.tsx | 0 | https://github.com/grafana/grafana/commit/ed6a8877371211e9466fa780e940b485ac9a64d2 | [
0.0002144738391507417,
0.00017663744802121073,
0.00017007060523610562,
0.00017278117593377829,
0.000012792300367436837
] |
{
"id": 1,
"code_window": [
"\tListAlertRules(ctx context.Context, query *ngmodels.ListAlertRulesQuery) error\n",
"\t// GetRuleGroups returns the unique rule groups across all organizations.\n",
"\tGetRuleGroups(ctx context.Context, query *ngmodels.ListRuleGroupsQuery) error\n",
"\tGetRuleGroupInterval(ctx context.Context, orgID int64, namespaceUID string, ruleGroup string) (int64, error)\n",
"\t// UpdateRuleGroup will update the interval for all rules in the group.\n",
"\tUpdateRuleGroup(ctx context.Context, orgID int64, namespaceUID string, ruleGroup string, interval int64) error\n",
"\tGetUserVisibleNamespaces(context.Context, int64, *models.SignedInUser) (map[string]*models.Folder, error)\n",
"\tGetNamespaceByTitle(context.Context, string, int64, *models.SignedInUser, bool) (*models.Folder, error)\n",
"\t// InsertAlertRules will insert all alert rules passed into the function\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "pkg/services/ngalert/store/alert_rule.go",
"type": "replace",
"edit_start_line_idx": 49
} | package store
import (
"context"
"errors"
"fmt"
"strings"
"github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/services/guardian"
apimodels "github.com/grafana/grafana/pkg/services/ngalert/api/tooling/definitions"
ngmodels "github.com/grafana/grafana/pkg/services/ngalert/models"
"github.com/grafana/grafana/pkg/services/sqlstore"
"github.com/grafana/grafana/pkg/services/sqlstore/searchstore"
"github.com/grafana/grafana/pkg/util"
)
// AlertRuleMaxTitleLength is the maximum length of the alert rule title
const AlertRuleMaxTitleLength = 190
// AlertRuleMaxRuleGroupNameLength is the maximum length of the alert rule group name
const AlertRuleMaxRuleGroupNameLength = 190
type UpdateRuleGroupCmd struct {
OrgID int64
NamespaceUID string
RuleGroupConfig apimodels.PostableRuleGroupConfig
}
type UpdateRule struct {
Existing *ngmodels.AlertRule
New ngmodels.AlertRule
}
var (
ErrAlertRuleGroupNotFound = errors.New("rulegroup not found")
)
// RuleStore is the interface for persisting alert rules and instances
type RuleStore interface {
DeleteAlertRulesByUID(ctx context.Context, orgID int64, ruleUID ...string) error
DeleteAlertInstancesByRuleUID(ctx context.Context, orgID int64, ruleUID string) error
GetAlertRuleByUID(ctx context.Context, query *ngmodels.GetAlertRuleByUIDQuery) error
GetAlertRulesGroupByRuleUID(ctx context.Context, query *ngmodels.GetAlertRulesGroupByRuleUIDQuery) error
GetAlertRulesForScheduling(ctx context.Context, query *ngmodels.GetAlertRulesForSchedulingQuery) error
ListAlertRules(ctx context.Context, query *ngmodels.ListAlertRulesQuery) error
// GetRuleGroups returns the unique rule groups across all organizations.
GetRuleGroups(ctx context.Context, query *ngmodels.ListRuleGroupsQuery) error
GetRuleGroupInterval(ctx context.Context, orgID int64, namespaceUID string, ruleGroup string) (int64, error)
// UpdateRuleGroup will update the interval for all rules in the group.
UpdateRuleGroup(ctx context.Context, orgID int64, namespaceUID string, ruleGroup string, interval int64) error
GetUserVisibleNamespaces(context.Context, int64, *models.SignedInUser) (map[string]*models.Folder, error)
GetNamespaceByTitle(context.Context, string, int64, *models.SignedInUser, bool) (*models.Folder, error)
// InsertAlertRules will insert all alert rules passed into the function
// and return the map of uuid to id.
InsertAlertRules(ctx context.Context, rule []ngmodels.AlertRule) (map[string]int64, error)
UpdateAlertRules(ctx context.Context, rule []UpdateRule) error
}
func getAlertRuleByUID(sess *sqlstore.DBSession, alertRuleUID string, orgID int64) (*ngmodels.AlertRule, error) {
// we consider optionally enabling some caching
alertRule := ngmodels.AlertRule{OrgID: orgID, UID: alertRuleUID}
has, err := sess.Get(&alertRule)
if err != nil {
return nil, err
}
if !has {
return nil, ngmodels.ErrAlertRuleNotFound
}
return &alertRule, nil
}
// DeleteAlertRulesByUID is a handler for deleting an alert rule.
func (st DBstore) DeleteAlertRulesByUID(ctx context.Context, orgID int64, ruleUID ...string) error {
logger := st.Logger.New("org_id", orgID, "rule_uids", ruleUID)
return st.SQLStore.WithTransactionalDbSession(ctx, func(sess *sqlstore.DBSession) error {
rows, err := sess.Table("alert_rule").Where("org_id = ?", orgID).In("uid", ruleUID).Delete(ngmodels.AlertRule{})
if err != nil {
return err
}
logger.Debug("deleted alert rules", "count", rows)
rows, err = sess.Table("alert_rule_version").Where("rule_org_id = ?", orgID).In("rule_uid", ruleUID).Delete(ngmodels.AlertRule{})
if err != nil {
return err
}
logger.Debug("deleted alert rule versions", "count", rows)
rows, err = sess.Table("alert_instance").Where("rule_org_id = ?", orgID).In("rule_uid", ruleUID).Delete(ngmodels.AlertRule{})
if err != nil {
return err
}
logger.Debug("deleted alert instances", "count", rows)
return nil
})
}
// DeleteAlertInstanceByRuleUID is a handler for deleting alert instances by alert rule UID when a rule has been updated
func (st DBstore) DeleteAlertInstancesByRuleUID(ctx context.Context, orgID int64, ruleUID string) error {
return st.SQLStore.WithTransactionalDbSession(ctx, func(sess *sqlstore.DBSession) error {
_, err := sess.Exec("DELETE FROM alert_instance WHERE rule_org_id = ? AND rule_uid = ?", orgID, ruleUID)
if err != nil {
return err
}
return nil
})
}
// GetAlertRuleByUID is a handler for retrieving an alert rule from that database by its UID and organisation ID.
// It returns ngmodels.ErrAlertRuleNotFound if no alert rule is found for the provided ID.
func (st DBstore) GetAlertRuleByUID(ctx context.Context, query *ngmodels.GetAlertRuleByUIDQuery) error {
return st.SQLStore.WithDbSession(ctx, func(sess *sqlstore.DBSession) error {
alertRule, err := getAlertRuleByUID(sess, query.UID, query.OrgID)
if err != nil {
return err
}
query.Result = alertRule
return nil
})
}
// GetAlertRulesGroupByRuleUID is a handler for retrieving a group of alert rules from that database by UID and organisation ID of one of rules that belong to that group.
func (st DBstore) GetAlertRulesGroupByRuleUID(ctx context.Context, query *ngmodels.GetAlertRulesGroupByRuleUIDQuery) error {
return st.SQLStore.WithDbSession(ctx, func(sess *sqlstore.DBSession) error {
var result []*ngmodels.AlertRule
err := sess.Table("alert_rule").Alias("A").Join(
"INNER",
"alert_rule AS B", "A.org_id = B.org_id AND A.namespace_uid = B.namespace_uid AND A.rule_group = B.rule_group AND B.uid = ?", query.UID,
).Where("A.org_id = ?", query.OrgID).Select("A.*").Find(&result)
if err != nil {
return err
}
query.Result = result
return nil
})
}
// InsertAlertRules is a handler for creating/updating alert rules.
func (st DBstore) InsertAlertRules(ctx context.Context, rules []ngmodels.AlertRule) (map[string]int64, error) {
ids := make(map[string]int64, len(rules))
return ids, st.SQLStore.WithTransactionalDbSession(ctx, func(sess *sqlstore.DBSession) error {
newRules := make([]ngmodels.AlertRule, 0, len(rules))
ruleVersions := make([]ngmodels.AlertRuleVersion, 0, len(rules))
for i := range rules {
r := rules[i]
if r.UID == "" {
uid, err := GenerateNewAlertRuleUID(sess, r.OrgID, r.Title)
if err != nil {
return fmt.Errorf("failed to generate UID for alert rule %q: %w", r.Title, err)
}
r.UID = uid
}
r.Version = 1
if err := st.validateAlertRule(r); err != nil {
return err
}
if err := (&r).PreSave(TimeNow); err != nil {
return err
}
newRules = append(newRules, r)
ruleVersions = append(ruleVersions, ngmodels.AlertRuleVersion{
RuleUID: r.UID,
RuleOrgID: r.OrgID,
RuleNamespaceUID: r.NamespaceUID,
RuleGroup: r.RuleGroup,
ParentVersion: 0,
Version: r.Version,
Created: r.Updated,
Condition: r.Condition,
Title: r.Title,
Data: r.Data,
IntervalSeconds: r.IntervalSeconds,
NoDataState: r.NoDataState,
ExecErrState: r.ExecErrState,
For: r.For,
Annotations: r.Annotations,
Labels: r.Labels,
})
}
if len(newRules) > 0 {
// we have to insert the rules one by one as otherwise we are
// not able to fetch the inserted id as it's not supported by xorm
for i := range newRules {
if _, err := sess.Insert(&newRules[i]); err != nil {
if st.SQLStore.Dialect.IsUniqueConstraintViolation(err) {
return ngmodels.ErrAlertRuleUniqueConstraintViolation
}
return fmt.Errorf("failed to create new rules: %w", err)
}
ids[newRules[i].UID] = newRules[i].ID
}
}
if len(ruleVersions) > 0 {
if _, err := sess.Insert(&ruleVersions); err != nil {
return fmt.Errorf("failed to create new rule versions: %w", err)
}
}
return nil
})
}
// UpdateAlertRules is a handler for updating alert rules.
func (st DBstore) UpdateAlertRules(ctx context.Context, rules []UpdateRule) error {
return st.SQLStore.WithTransactionalDbSession(ctx, func(sess *sqlstore.DBSession) error {
ruleVersions := make([]ngmodels.AlertRuleVersion, 0, len(rules))
for _, r := range rules {
var parentVersion int64
r.New.ID = r.Existing.ID
r.New.Version = r.Existing.Version + 1
if err := st.validateAlertRule(r.New); err != nil {
return err
}
if err := (&r.New).PreSave(TimeNow); err != nil {
return err
}
// no way to update multiple rules at once
if _, err := sess.ID(r.Existing.ID).AllCols().Update(r.New); err != nil {
if st.SQLStore.Dialect.IsUniqueConstraintViolation(err) {
return ngmodels.ErrAlertRuleUniqueConstraintViolation
}
return fmt.Errorf("failed to update rule [%s] %s: %w", r.New.UID, r.New.Title, err)
}
parentVersion = r.Existing.Version
ruleVersions = append(ruleVersions, ngmodels.AlertRuleVersion{
RuleOrgID: r.New.OrgID,
RuleUID: r.New.UID,
RuleNamespaceUID: r.New.NamespaceUID,
RuleGroup: r.New.RuleGroup,
ParentVersion: parentVersion,
Version: r.New.Version,
Created: r.New.Updated,
Condition: r.New.Condition,
Title: r.New.Title,
Data: r.New.Data,
IntervalSeconds: r.New.IntervalSeconds,
NoDataState: r.New.NoDataState,
ExecErrState: r.New.ExecErrState,
For: r.New.For,
Annotations: r.New.Annotations,
Labels: r.New.Labels,
})
}
if len(ruleVersions) > 0 {
if _, err := sess.Insert(&ruleVersions); err != nil {
return fmt.Errorf("failed to create new rule versions: %w", err)
}
}
return nil
})
}
// GetOrgAlertRules is a handler for retrieving alert rules of specific organisation.
func (st DBstore) ListAlertRules(ctx context.Context, query *ngmodels.ListAlertRulesQuery) error {
return st.SQLStore.WithDbSession(ctx, func(sess *sqlstore.DBSession) error {
q := sess.Table("alert_rule")
if query.OrgID >= 0 {
q = q.Where("org_id = ?", query.OrgID)
}
if query.DashboardUID != "" {
q = q.Where("dashboard_uid = ?", query.DashboardUID)
if query.PanelID != 0 {
q = q.Where("panel_id = ?", query.PanelID)
}
}
if len(query.NamespaceUIDs) > 0 {
args := make([]interface{}, 0, len(query.NamespaceUIDs))
in := make([]string, 0, len(query.NamespaceUIDs))
for _, namespaceUID := range query.NamespaceUIDs {
args = append(args, namespaceUID)
in = append(in, "?")
}
q = q.Where(fmt.Sprintf("namespace_uid IN (%s)", strings.Join(in, ",")), args...)
}
if query.RuleGroup != "" {
q = q.Where("rule_group = ?", query.RuleGroup)
}
q = q.OrderBy("id ASC")
alertRules := make([]*ngmodels.AlertRule, 0)
if err := q.Find(&alertRules); err != nil {
return err
}
query.Result = alertRules
return nil
})
}
func (st DBstore) GetRuleGroups(ctx context.Context, query *ngmodels.ListRuleGroupsQuery) error {
return st.SQLStore.WithDbSession(ctx, func(sess *sqlstore.DBSession) error {
ruleGroups := make([]string, 0)
if err := sess.Table("alert_rule").Distinct("rule_group").Find(&ruleGroups); err != nil {
return err
}
query.Result = ruleGroups
return nil
})
}
func (st DBstore) GetRuleGroupInterval(ctx context.Context, orgID int64, namespaceUID string, ruleGroup string) (int64, error) {
var interval int64 = 0
return interval, st.SQLStore.WithDbSession(ctx, func(sess *sqlstore.DBSession) error {
ruleGroups := make([]ngmodels.AlertRule, 0)
err := sess.Find(
&ruleGroups,
ngmodels.AlertRule{OrgID: orgID, RuleGroup: ruleGroup, NamespaceUID: namespaceUID},
)
if len(ruleGroups) == 0 {
return ErrAlertRuleGroupNotFound
}
interval = ruleGroups[0].IntervalSeconds
return err
})
}
func (st DBstore) UpdateRuleGroup(ctx context.Context, orgID int64, namespaceUID string, ruleGroup string, interval int64) error {
return st.SQLStore.WithDbSession(ctx, func(sess *sqlstore.DBSession) error {
_, err := sess.Update(
ngmodels.AlertRule{IntervalSeconds: interval},
ngmodels.AlertRule{OrgID: orgID, RuleGroup: ruleGroup, NamespaceUID: namespaceUID},
)
return err
})
}
// GetNamespaces returns the folders that are visible to the user and have at least one alert in it
func (st DBstore) GetUserVisibleNamespaces(ctx context.Context, orgID int64, user *models.SignedInUser) (map[string]*models.Folder, error) {
namespaceMap := make(map[string]*models.Folder)
searchQuery := models.FindPersistedDashboardsQuery{
OrgId: orgID,
SignedInUser: user,
Type: searchstore.TypeAlertFolder,
Limit: -1,
Permission: models.PERMISSION_VIEW,
Sort: models.SortOption{},
Filters: []interface{}{
searchstore.FolderWithAlertsFilter{},
},
}
var page int64 = 1
for {
query := searchQuery
query.Page = page
proj, err := st.DashboardService.FindDashboards(ctx, &query)
if err != nil {
return nil, err
}
if len(proj) == 0 {
break
}
for _, hit := range proj {
if !hit.IsFolder {
continue
}
namespaceMap[hit.UID] = &models.Folder{
Id: hit.ID,
Uid: hit.UID,
Title: hit.Title,
}
}
page += 1
}
return namespaceMap, nil
}
// GetNamespaceByTitle is a handler for retrieving a namespace by its title. Alerting rules follow a Grafana folder-like structure which we call namespaces.
func (st DBstore) GetNamespaceByTitle(ctx context.Context, namespace string, orgID int64, user *models.SignedInUser, withCanSave bool) (*models.Folder, error) {
folder, err := st.FolderService.GetFolderByTitle(ctx, user, orgID, namespace)
if err != nil {
return nil, err
}
// if access control is disabled, check that the user is allowed to save in the folder.
if withCanSave && st.AccessControl.IsDisabled() {
g := guardian.New(ctx, folder.Id, orgID, user)
if canSave, err := g.CanSave(); err != nil || !canSave {
if err != nil {
st.Logger.Error("checking can save permission has failed", "userId", user.UserId, "username", user.Login, "namespace", namespace, "orgId", orgID, "err", err)
}
return nil, ngmodels.ErrCannotEditNamespace
}
}
return folder, nil
}
// GetAlertRulesForScheduling returns a short version of all alert rules except those that belong to an excluded list of organizations
func (st DBstore) GetAlertRulesForScheduling(ctx context.Context, query *ngmodels.GetAlertRulesForSchedulingQuery) error {
return st.SQLStore.WithDbSession(ctx, func(sess *sqlstore.DBSession) error {
alerts := make([]*ngmodels.SchedulableAlertRule, 0)
q := sess.Table("alert_rule")
if len(query.ExcludeOrgIDs) > 0 {
excludeOrgs := make([]interface{}, 0, len(query.ExcludeOrgIDs))
for _, orgID := range query.ExcludeOrgIDs {
excludeOrgs = append(excludeOrgs, orgID)
}
q = q.NotIn("org_id", excludeOrgs...)
}
if err := q.Find(&alerts); err != nil {
return err
}
query.Result = alerts
return nil
})
}
// GenerateNewAlertRuleUID generates a unique UID for a rule.
// This is set as a variable so that the tests can override it.
// The ruleTitle is only used by the mocked functions.
var GenerateNewAlertRuleUID = func(sess *sqlstore.DBSession, orgID int64, ruleTitle string) (string, error) {
for i := 0; i < 3; i++ {
uid := util.GenerateShortUID()
exists, err := sess.Where("org_id=? AND uid=?", orgID, uid).Get(&ngmodels.AlertRule{})
if err != nil {
return "", err
}
if !exists {
return uid, nil
}
}
return "", ngmodels.ErrAlertRuleFailedGenerateUniqueUID
}
// validateAlertRule validates the alert rule interval and organisation.
func (st DBstore) validateAlertRule(alertRule ngmodels.AlertRule) error {
if len(alertRule.Data) == 0 {
return fmt.Errorf("%w: no queries or expressions are found", ngmodels.ErrAlertRuleFailedValidation)
}
if alertRule.Title == "" {
return fmt.Errorf("%w: title is empty", ngmodels.ErrAlertRuleFailedValidation)
}
if err := ngmodels.ValidateRuleGroupInterval(alertRule.IntervalSeconds, int64(st.BaseInterval.Seconds())); err != nil {
return err
}
// enfore max name length in SQLite
if len(alertRule.Title) > AlertRuleMaxTitleLength {
return fmt.Errorf("%w: name length should not be greater than %d", ngmodels.ErrAlertRuleFailedValidation, AlertRuleMaxTitleLength)
}
// enfore max rule group name length in SQLite
if len(alertRule.RuleGroup) > AlertRuleMaxRuleGroupNameLength {
return fmt.Errorf("%w: rule group name length should not be greater than %d", ngmodels.ErrAlertRuleFailedValidation, AlertRuleMaxRuleGroupNameLength)
}
if alertRule.OrgID == 0 {
return fmt.Errorf("%w: no organisation is found", ngmodels.ErrAlertRuleFailedValidation)
}
if alertRule.DashboardUID == nil && alertRule.PanelID != nil {
return fmt.Errorf("%w: cannot have Panel ID without a Dashboard UID", ngmodels.ErrAlertRuleFailedValidation)
}
if _, err := ngmodels.ErrStateFromString(string(alertRule.ExecErrState)); err != nil {
return err
}
if _, err := ngmodels.NoDataStateFromString(string(alertRule.NoDataState)); err != nil {
return err
}
return nil
}
| pkg/services/ngalert/store/alert_rule.go | 1 | https://github.com/grafana/grafana/commit/ed6a8877371211e9466fa780e940b485ac9a64d2 | [
0.9959509372711182,
0.05360744521021843,
0.0001674166414886713,
0.0020055801142007113,
0.1904444396495819
] |
{
"id": 1,
"code_window": [
"\tListAlertRules(ctx context.Context, query *ngmodels.ListAlertRulesQuery) error\n",
"\t// GetRuleGroups returns the unique rule groups across all organizations.\n",
"\tGetRuleGroups(ctx context.Context, query *ngmodels.ListRuleGroupsQuery) error\n",
"\tGetRuleGroupInterval(ctx context.Context, orgID int64, namespaceUID string, ruleGroup string) (int64, error)\n",
"\t// UpdateRuleGroup will update the interval for all rules in the group.\n",
"\tUpdateRuleGroup(ctx context.Context, orgID int64, namespaceUID string, ruleGroup string, interval int64) error\n",
"\tGetUserVisibleNamespaces(context.Context, int64, *models.SignedInUser) (map[string]*models.Folder, error)\n",
"\tGetNamespaceByTitle(context.Context, string, int64, *models.SignedInUser, bool) (*models.Folder, error)\n",
"\t// InsertAlertRules will insert all alert rules passed into the function\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "pkg/services/ngalert/store/alert_rule.go",
"type": "replace",
"edit_start_line_idx": 49
} | //
// Modals
// --------------------------------------------------
// Background
.modal-backdrop {
position: fixed;
top: 0;
right: 0;
bottom: 0;
left: 0;
z-index: $zindex-modal-backdrop;
background-color: $modal-backdrop-bg;
}
.modal-backdrop,
.modal-backdrop.fade.in {
@include opacity(70);
}
// Base modal
.modal {
position: fixed;
z-index: $zindex-modal;
width: 100%;
background: $page-bg;
@include box-shadow(0 3px 7px rgba(0, 0, 0, 0.3));
@include background-clip(padding-box);
outline: none;
max-width: 750px;
left: 0;
right: 0;
margin-left: auto;
margin-right: auto;
top: 10%;
}
.modal-header {
background: $page-header-bg;
box-shadow: $page-header-shadow;
border-bottom: 1px solid $page-header-border-color;
display: flex;
align-items: center;
justify-content: space-between;
}
.modal-header-title {
font-size: $font-size-lg;
float: left;
padding-top: $space-sm;
margin: 0 $space-md;
}
.modal-header-close {
float: right;
padding: 9px $spacer;
}
// Body (where all modal content resides)
.modal-body {
position: relative;
}
.modal-content {
padding: $spacer * 2;
&--has-scroll {
max-height: calc(100vh - 400px);
position: relative;
}
}
// Remove bottom margin if need be
.modal-form {
margin-bottom: 0;
}
// Footer (for actions)
.modal-footer {
padding: 14px 15px 15px;
border-top: 1px solid $panel-bg;
background-color: $panel-bg;
text-align: right; // right align buttons
@include clearfix(); // clear it in case folks use .pull-* classes on buttons
}
.modal--narrow {
max-width: 500px;
}
.confirm-modal {
max-width: 500px;
.confirm-modal-icon {
padding-top: 41px;
font-size: 280%;
color: $green-base;
padding-bottom: 20px;
}
.confirm-modal-text {
font-size: $font-size-h4;
color: $link-color;
margin-bottom: $spacer * 2;
padding-top: $spacer;
}
.confirm-modal-text2 {
font-size: $font-size-base;
padding-top: $spacer;
}
.confirm-modal-buttons {
margin-bottom: $spacer;
button {
margin-right: calc($spacer/2);
}
}
.modal-content-confirm-text {
margin-bottom: $space-xl;
span {
text-align: center;
}
}
}
.share-modal-body {
.share-modal-options {
margin: 11px 0px 33px 0px;
display: inline-block;
}
.share-modal-big-icon {
margin-right: 8px;
margin-top: -7px;
}
.share-modal-info-text {
margin-top: 5px;
strong {
color: $text-color-emphasis;
font-weight: $font-weight-semi-bold;
}
}
.share-modal-header {
display: flex;
margin: 0px 0 22px 0;
}
.share-modal-content {
flex-grow: 1;
}
.share-modal-link {
max-width: 716px;
white-space: nowrap;
overflow: hidden;
display: block;
text-overflow: ellipsis;
}
}
| public/sass/components/_modals.scss | 0 | https://github.com/grafana/grafana/commit/ed6a8877371211e9466fa780e940b485ac9a64d2 | [
0.0001765766937751323,
0.00017346683307550848,
0.0001690534845693037,
0.000173647262272425,
0.000002050507191597717
] |
{
"id": 1,
"code_window": [
"\tListAlertRules(ctx context.Context, query *ngmodels.ListAlertRulesQuery) error\n",
"\t// GetRuleGroups returns the unique rule groups across all organizations.\n",
"\tGetRuleGroups(ctx context.Context, query *ngmodels.ListRuleGroupsQuery) error\n",
"\tGetRuleGroupInterval(ctx context.Context, orgID int64, namespaceUID string, ruleGroup string) (int64, error)\n",
"\t// UpdateRuleGroup will update the interval for all rules in the group.\n",
"\tUpdateRuleGroup(ctx context.Context, orgID int64, namespaceUID string, ruleGroup string, interval int64) error\n",
"\tGetUserVisibleNamespaces(context.Context, int64, *models.SignedInUser) (map[string]*models.Folder, error)\n",
"\tGetNamespaceByTitle(context.Context, string, int64, *models.SignedInUser, bool) (*models.Folder, error)\n",
"\t// InsertAlertRules will insert all alert rules passed into the function\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "pkg/services/ngalert/store/alert_rule.go",
"type": "replace",
"edit_start_line_idx": 49
} | #!/bin/bash
# Temporary - remove this script once the dashboard schema are mature
# Remove the appropriate ellipses from the schema to check for unspecified
# fields in the artifacts (validating "open")
# Run from root of grafana repo
CMD=${CLI:-bin/darwin-amd64/grafana-cli}
FILES=$(grep -rl '"schemaVersion": 30' devenv)
for DASH in ${FILES}; do echo "${DASH}"; ${CMD} cue validate-resource --dashboard "${DASH}"; done
| scripts/validate-devenv-dashboards.sh | 0 | https://github.com/grafana/grafana/commit/ed6a8877371211e9466fa780e940b485ac9a64d2 | [
0.0001724628236843273,
0.00017225233023054898,
0.00017204185132868588,
0.00017225233023054898,
2.1048617782071233e-7
] |
{
"id": 1,
"code_window": [
"\tListAlertRules(ctx context.Context, query *ngmodels.ListAlertRulesQuery) error\n",
"\t// GetRuleGroups returns the unique rule groups across all organizations.\n",
"\tGetRuleGroups(ctx context.Context, query *ngmodels.ListRuleGroupsQuery) error\n",
"\tGetRuleGroupInterval(ctx context.Context, orgID int64, namespaceUID string, ruleGroup string) (int64, error)\n",
"\t// UpdateRuleGroup will update the interval for all rules in the group.\n",
"\tUpdateRuleGroup(ctx context.Context, orgID int64, namespaceUID string, ruleGroup string, interval int64) error\n",
"\tGetUserVisibleNamespaces(context.Context, int64, *models.SignedInUser) (map[string]*models.Folder, error)\n",
"\tGetNamespaceByTitle(context.Context, string, int64, *models.SignedInUser, bool) (*models.Folder, error)\n",
"\t// InsertAlertRules will insert all alert rules passed into the function\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "pkg/services/ngalert/store/alert_rule.go",
"type": "replace",
"edit_start_line_idx": 49
} | ---
aliases:
- /docs/grafana/latest/release-notes/release-notes-8-4-1/
hide_menu: true
title: Release notes for Grafana 8.4.1
---
<!-- Auto generated by update changelog github action -->
# Release notes for Grafana 8.4.1
### Features and enhancements
- **Cloudwatch:** Add support for AWS/PrivateLink\* metrics and dimensions. [#45515](https://github.com/grafana/grafana/pull/45515), [@szymonpk](https://github.com/szymonpk)
- **Configuration:** Add ability to customize okta login button name and icon. [#44079](https://github.com/grafana/grafana/pull/44079), [@DanCech](https://github.com/DanCech)
- **Tempo:** Switch out Select with AsyncSelect component to get loading state in Tempo Search. [#45110](https://github.com/grafana/grafana/pull/45110), [@CatPerry](https://github.com/CatPerry)
### Bug fixes
- **Alerting:** Fix migrations by making send_alerts_to field nullable. [#45572](https://github.com/grafana/grafana/pull/45572), [@santihernandezc](https://github.com/santihernandezc)
| docs/sources/release-notes/release-notes-8-4-1.md | 0 | https://github.com/grafana/grafana/commit/ed6a8877371211e9466fa780e940b485ac9a64d2 | [
0.0001740880834404379,
0.00017102946003433317,
0.00016644220158923417,
0.00017255806596949697,
0.000003303268613308319
] |
{
"id": 2,
"code_window": [
"\t\treturn err\n",
"\t})\n",
"}\n",
"\n",
"func (st DBstore) UpdateRuleGroup(ctx context.Context, orgID int64, namespaceUID string, ruleGroup string, interval int64) error {\n",
"\treturn st.SQLStore.WithDbSession(ctx, func(sess *sqlstore.DBSession) error {\n",
"\t\t_, err := sess.Update(\n",
"\t\t\tngmodels.AlertRule{IntervalSeconds: interval},\n",
"\t\t\tngmodels.AlertRule{OrgID: orgID, RuleGroup: ruleGroup, NamespaceUID: namespaceUID},\n",
"\t\t)\n",
"\t\treturn err\n",
"\t})\n",
"}\n",
"\n",
"// GetNamespaces returns the folders that are visible to the user and have at least one alert in it\n",
"func (st DBstore) GetUserVisibleNamespaces(ctx context.Context, orgID int64, user *models.SignedInUser) (map[string]*models.Folder, error) {\n",
"\tnamespaceMap := make(map[string]*models.Folder)\n",
"\n",
"\tsearchQuery := models.FindPersistedDashboardsQuery{\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "pkg/services/ngalert/store/alert_rule.go",
"type": "replace",
"edit_start_line_idx": 321
} | package provisioning
import (
"context"
"github.com/grafana/grafana/pkg/services/ngalert/models"
"github.com/grafana/grafana/pkg/services/ngalert/store"
)
// AMStore is a store of Alertmanager configurations.
//go:generate mockery --name AMConfigStore --structname MockAMConfigStore --inpackage --filename persist_mock.go --with-expecter
type AMConfigStore interface {
GetLatestAlertmanagerConfiguration(ctx context.Context, query *models.GetLatestAlertmanagerConfigurationQuery) error
UpdateAlertmanagerConfiguration(ctx context.Context, cmd *models.SaveAlertmanagerConfigurationCmd) error
}
// ProvisioningStore is a store of provisioning data for arbitrary objects.
//go:generate mockery --name ProvisioningStore --structname MockProvisioningStore --inpackage --filename provisioning_store_mock.go --with-expecter
type ProvisioningStore interface {
GetProvenance(ctx context.Context, o models.Provisionable, org int64) (models.Provenance, error)
GetProvenances(ctx context.Context, org int64, resourceType string) (map[string]models.Provenance, error)
SetProvenance(ctx context.Context, o models.Provisionable, org int64, p models.Provenance) error
DeleteProvenance(ctx context.Context, o models.Provisionable, org int64) error
}
// TransactionManager represents the ability to issue and close transactions through contexts.
type TransactionManager interface {
InTransaction(ctx context.Context, work func(ctx context.Context) error) error
}
// RuleStore represents the ability to persist and query alert rules.
type RuleStore interface {
GetAlertRuleByUID(ctx context.Context, query *models.GetAlertRuleByUIDQuery) error
ListAlertRules(ctx context.Context, query *models.ListAlertRulesQuery) error
GetRuleGroupInterval(ctx context.Context, orgID int64, namespaceUID string, ruleGroup string) (int64, error)
InsertAlertRules(ctx context.Context, rule []models.AlertRule) (map[string]int64, error)
UpdateRuleGroup(ctx context.Context, orgID int64, namespaceUID string, ruleGroup string, interval int64) error
UpdateAlertRules(ctx context.Context, rule []store.UpdateRule) error
DeleteAlertRulesByUID(ctx context.Context, orgID int64, ruleUID ...string) error
}
| pkg/services/ngalert/provisioning/persist.go | 1 | https://github.com/grafana/grafana/commit/ed6a8877371211e9466fa780e940b485ac9a64d2 | [
0.9990853071212769,
0.19998250901699066,
0.00016325004980899394,
0.000172336571267806,
0.3995513916015625
] |
{
"id": 2,
"code_window": [
"\t\treturn err\n",
"\t})\n",
"}\n",
"\n",
"func (st DBstore) UpdateRuleGroup(ctx context.Context, orgID int64, namespaceUID string, ruleGroup string, interval int64) error {\n",
"\treturn st.SQLStore.WithDbSession(ctx, func(sess *sqlstore.DBSession) error {\n",
"\t\t_, err := sess.Update(\n",
"\t\t\tngmodels.AlertRule{IntervalSeconds: interval},\n",
"\t\t\tngmodels.AlertRule{OrgID: orgID, RuleGroup: ruleGroup, NamespaceUID: namespaceUID},\n",
"\t\t)\n",
"\t\treturn err\n",
"\t})\n",
"}\n",
"\n",
"// GetNamespaces returns the folders that are visible to the user and have at least one alert in it\n",
"func (st DBstore) GetUserVisibleNamespaces(ctx context.Context, orgID int64, user *models.SignedInUser) (map[string]*models.Folder, error) {\n",
"\tnamespaceMap := make(map[string]*models.Folder)\n",
"\n",
"\tsearchQuery := models.FindPersistedDashboardsQuery{\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "pkg/services/ngalert/store/alert_rule.go",
"type": "replace",
"edit_start_line_idx": 321
} | import { css, cx } from '@emotion/css';
import React from 'react';
import { GrafanaTheme2 } from '@grafana/data';
import { selectors } from '@grafana/e2e-selectors';
import { IconButton, IconName, useStyles2 } from '@grafana/ui';
interface QueryOperationActionProps {
icon: IconName;
title: string;
onClick: (e: React.MouseEvent) => void;
disabled?: boolean;
active?: boolean;
}
export const QueryOperationAction: React.FC<QueryOperationActionProps> = ({
icon,
active,
disabled,
title,
onClick,
}) => {
const styles = useStyles2(getStyles);
return (
<div className={cx(styles.icon, active && styles.active)}>
<IconButton
name={icon}
title={title}
className={styles.icon}
disabled={!!disabled}
onClick={onClick}
type="button"
aria-label={selectors.components.QueryEditorRow.actionButton(title)}
/>
</div>
);
};
QueryOperationAction.displayName = 'QueryOperationAction';
const getStyles = (theme: GrafanaTheme2) => {
return {
icon: css`
display: flex;
position: relative;
color: ${theme.colors.text.secondary};
`,
active: css`
&::before {
display: block;
content: ' ';
position: absolute;
left: -1px;
right: 2px;
height: 3px;
border-radius: 2px;
bottom: -8px;
background-image: ${theme.colors.gradients.brandHorizontal} !important;
}
`,
};
};
| public/app/core/components/QueryOperationRow/QueryOperationAction.tsx | 0 | https://github.com/grafana/grafana/commit/ed6a8877371211e9466fa780e940b485ac9a64d2 | [
0.00017435055633541197,
0.0001710535871097818,
0.00016511535795871168,
0.00017110168118961155,
0.000002953710463771131
] |
{
"id": 2,
"code_window": [
"\t\treturn err\n",
"\t})\n",
"}\n",
"\n",
"func (st DBstore) UpdateRuleGroup(ctx context.Context, orgID int64, namespaceUID string, ruleGroup string, interval int64) error {\n",
"\treturn st.SQLStore.WithDbSession(ctx, func(sess *sqlstore.DBSession) error {\n",
"\t\t_, err := sess.Update(\n",
"\t\t\tngmodels.AlertRule{IntervalSeconds: interval},\n",
"\t\t\tngmodels.AlertRule{OrgID: orgID, RuleGroup: ruleGroup, NamespaceUID: namespaceUID},\n",
"\t\t)\n",
"\t\treturn err\n",
"\t})\n",
"}\n",
"\n",
"// GetNamespaces returns the folders that are visible to the user and have at least one alert in it\n",
"func (st DBstore) GetUserVisibleNamespaces(ctx context.Context, orgID int64, user *models.SignedInUser) (map[string]*models.Folder, error) {\n",
"\tnamespaceMap := make(map[string]*models.Folder)\n",
"\n",
"\tsearchQuery := models.FindPersistedDashboardsQuery{\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "pkg/services/ngalert/store/alert_rule.go",
"type": "replace",
"edit_start_line_idx": 321
} | import { css, cx } from '@emotion/css';
import React, { ChangeEvent } from 'react';
import { FixedSizeList } from 'react-window';
import { GrafanaTheme } from '@grafana/data';
import {
Button,
HorizontalGroup,
Input,
Label,
LoadingPlaceholder,
stylesFactory,
withTheme,
BrowserLabel as PromLabel,
} from '@grafana/ui';
import PromQlLanguageProvider from '../language_provider';
import { escapeLabelValueInExactSelector, escapeLabelValueInRegexSelector } from '../language_utils';
// Hard limit on labels to render
const EMPTY_SELECTOR = '{}';
const METRIC_LABEL = '__name__';
const LIST_ITEM_SIZE = 25;
export interface BrowserProps {
languageProvider: PromQlLanguageProvider;
onChange: (selector: string) => void;
theme: GrafanaTheme;
autoSelect?: number;
hide?: () => void;
lastUsedLabels: string[];
storeLastUsedLabels: (labels: string[]) => void;
deleteLastUsedLabels: () => void;
}
interface BrowserState {
labels: SelectableLabel[];
labelSearchTerm: string;
metricSearchTerm: string;
status: string;
error: string;
validationStatus: string;
valueSearchTerm: string;
}
interface FacettableValue {
name: string;
selected?: boolean;
details?: string;
}
export interface SelectableLabel {
name: string;
selected?: boolean;
loading?: boolean;
values?: FacettableValue[];
hidden?: boolean;
facets?: number;
}
export function buildSelector(labels: SelectableLabel[]): string {
let singleMetric = '';
const selectedLabels = [];
for (const label of labels) {
if ((label.name === METRIC_LABEL || label.selected) && label.values && label.values.length > 0) {
const selectedValues = label.values.filter((value) => value.selected).map((value) => value.name);
if (selectedValues.length > 1) {
selectedLabels.push(`${label.name}=~"${selectedValues.map(escapeLabelValueInRegexSelector).join('|')}"`);
} else if (selectedValues.length === 1) {
if (label.name === METRIC_LABEL) {
singleMetric = selectedValues[0];
} else {
selectedLabels.push(`${label.name}="${escapeLabelValueInExactSelector(selectedValues[0])}"`);
}
}
}
}
return [singleMetric, '{', selectedLabels.join(','), '}'].join('');
}
export function facetLabels(
labels: SelectableLabel[],
possibleLabels: Record<string, string[]>,
lastFacetted?: string
): SelectableLabel[] {
return labels.map((label) => {
const possibleValues = possibleLabels[label.name];
if (possibleValues) {
let existingValues: FacettableValue[];
if (label.name === lastFacetted && label.values) {
// Facetting this label, show all values
existingValues = label.values;
} else {
// Keep selection in other facets
const selectedValues: Set<string> = new Set(
label.values?.filter((value) => value.selected).map((value) => value.name) || []
);
// Values for this label have not been requested yet, let's use the facetted ones as the initial values
existingValues = possibleValues.map((value) => ({ name: value, selected: selectedValues.has(value) }));
}
return {
...label,
loading: false,
values: existingValues,
hidden: !possibleValues,
facets: existingValues.length,
};
}
// Label is facetted out, hide all values
return { ...label, loading: false, hidden: !possibleValues, values: undefined, facets: 0 };
});
}
const getStyles = stylesFactory((theme: GrafanaTheme) => ({
wrapper: css`
background-color: ${theme.colors.bg2};
padding: ${theme.spacing.sm};
width: 100%;
`,
list: css`
margin-top: ${theme.spacing.sm};
display: flex;
flex-wrap: wrap;
max-height: 200px;
overflow: auto;
align-content: flex-start;
`,
section: css`
& + & {
margin: ${theme.spacing.md} 0;
}
position: relative;
`,
selector: css`
font-family: ${theme.typography.fontFamily.monospace};
margin-bottom: ${theme.spacing.sm};
`,
status: css`
padding: ${theme.spacing.xs};
color: ${theme.colors.textSemiWeak};
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
/* using absolute positioning because flex interferes with ellipsis */
position: absolute;
width: 50%;
right: 0;
text-align: right;
transition: opacity 100ms linear;
opacity: 0;
`,
statusShowing: css`
opacity: 1;
`,
error: css`
color: ${theme.palette.brandDanger};
`,
valueList: css`
margin-right: ${theme.spacing.sm};
`,
valueListWrapper: css`
border-left: 1px solid ${theme.colors.border2};
margin: ${theme.spacing.sm} 0;
padding: ${theme.spacing.sm} 0 ${theme.spacing.sm} ${theme.spacing.sm};
`,
valueListArea: css`
display: flex;
flex-wrap: wrap;
margin-top: ${theme.spacing.sm};
`,
valueTitle: css`
margin-left: -${theme.spacing.xs};
margin-bottom: ${theme.spacing.sm};
`,
validationStatus: css`
padding: ${theme.spacing.xs};
margin-bottom: ${theme.spacing.sm};
color: ${theme.colors.textStrong};
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
`,
}));
/**
* TODO #33976: Remove duplicated code. The component is very similar to LokiLabelBrowser.tsx. Check if it's possible
* to create a single, generic component.
*/
export class UnthemedPrometheusMetricsBrowser extends React.Component<BrowserProps, BrowserState> {
valueListsRef = React.createRef<HTMLDivElement>();
state: BrowserState = {
labels: [] as SelectableLabel[],
labelSearchTerm: '',
metricSearchTerm: '',
status: 'Ready',
error: '',
validationStatus: '',
valueSearchTerm: '',
};
onChangeLabelSearch = (event: ChangeEvent<HTMLInputElement>) => {
this.setState({ labelSearchTerm: event.target.value });
};
onChangeMetricSearch = (event: ChangeEvent<HTMLInputElement>) => {
this.setState({ metricSearchTerm: event.target.value });
};
onChangeValueSearch = (event: ChangeEvent<HTMLInputElement>) => {
this.setState({ valueSearchTerm: event.target.value });
};
onClickRunQuery = () => {
const selector = buildSelector(this.state.labels);
this.props.onChange(selector);
};
onClickRunRateQuery = () => {
const selector = buildSelector(this.state.labels);
const query = `rate(${selector}[$__interval])`;
this.props.onChange(query);
};
onClickClear = () => {
this.setState((state) => {
const labels: SelectableLabel[] = state.labels.map((label) => ({
...label,
values: undefined,
selected: false,
loading: false,
hidden: false,
facets: undefined,
}));
return {
labels,
labelSearchTerm: '',
metricSearchTerm: '',
status: '',
error: '',
validationStatus: '',
valueSearchTerm: '',
};
});
this.props.deleteLastUsedLabels();
// Get metrics
this.fetchValues(METRIC_LABEL, EMPTY_SELECTOR);
};
onClickLabel = (name: string, value: string | undefined, event: React.MouseEvent<HTMLElement>) => {
const label = this.state.labels.find((l) => l.name === name);
if (!label) {
return;
}
// Toggle selected state
const selected = !label.selected;
let nextValue: Partial<SelectableLabel> = { selected };
if (label.values && !selected) {
// Deselect all values if label was deselected
const values = label.values.map((value) => ({ ...value, selected: false }));
nextValue = { ...nextValue, facets: 0, values };
}
// Resetting search to prevent empty results
this.setState({ labelSearchTerm: '' });
this.updateLabelState(name, nextValue, '', () => this.doFacettingForLabel(name));
};
onClickValue = (name: string, value: string | undefined, event: React.MouseEvent<HTMLElement>) => {
const label = this.state.labels.find((l) => l.name === name);
if (!label || !label.values) {
return;
}
// Resetting search to prevent empty results
this.setState({ labelSearchTerm: '' });
// Toggling value for selected label, leaving other values intact
const values = label.values.map((v) => ({ ...v, selected: v.name === value ? !v.selected : v.selected }));
this.updateLabelState(name, { values }, '', () => this.doFacetting(name));
};
onClickMetric = (name: string, value: string | undefined, event: React.MouseEvent<HTMLElement>) => {
// Finding special metric label
const label = this.state.labels.find((l) => l.name === name);
if (!label || !label.values) {
return;
}
// Resetting search to prevent empty results
this.setState({ metricSearchTerm: '' });
// Toggling value for selected label, leaving other values intact
const values = label.values.map((v) => ({
...v,
selected: v.name === value || v.selected ? !v.selected : v.selected,
}));
// Toggle selected state of special metrics label
const selected = values.some((v) => v.selected);
this.updateLabelState(name, { selected, values }, '', () => this.doFacetting(name));
};
onClickValidate = () => {
const selector = buildSelector(this.state.labels);
this.validateSelector(selector);
};
updateLabelState(name: string, updatedFields: Partial<SelectableLabel>, status = '', cb?: () => void) {
this.setState((state) => {
const labels: SelectableLabel[] = state.labels.map((label) => {
if (label.name === name) {
return { ...label, ...updatedFields };
}
return label;
});
// New status overrides errors
const error = status ? '' : state.error;
return { labels, status, error, validationStatus: '' };
}, cb);
}
componentDidMount() {
const { languageProvider, lastUsedLabels } = this.props;
if (languageProvider) {
const selectedLabels: string[] = lastUsedLabels;
languageProvider.start().then(() => {
let rawLabels: string[] = languageProvider.getLabelKeys();
// Get metrics
this.fetchValues(METRIC_LABEL, EMPTY_SELECTOR);
// Auto-select previously selected labels
const labels: SelectableLabel[] = rawLabels.map((label, i, arr) => ({
name: label,
selected: selectedLabels.includes(label),
loading: false,
}));
// Pre-fetch values for selected labels
this.setState({ labels }, () => {
this.state.labels.forEach((label) => {
if (label.selected) {
this.fetchValues(label.name, EMPTY_SELECTOR);
}
});
});
});
}
}
doFacettingForLabel(name: string) {
const label = this.state.labels.find((l) => l.name === name);
if (!label) {
return;
}
const selectedLabels = this.state.labels.filter((label) => label.selected).map((label) => label.name);
this.props.storeLastUsedLabels(selectedLabels);
if (label.selected) {
// Refetch values for newly selected label...
if (!label.values) {
this.fetchValues(name, buildSelector(this.state.labels));
}
} else {
// Only need to facet when deselecting labels
this.doFacetting();
}
}
doFacetting = (lastFacetted?: string) => {
const selector = buildSelector(this.state.labels);
if (selector === EMPTY_SELECTOR) {
// Clear up facetting
const labels: SelectableLabel[] = this.state.labels.map((label) => {
return { ...label, facets: 0, values: undefined, hidden: false };
});
this.setState({ labels }, () => {
// Get fresh set of values
this.state.labels.forEach(
(label) => (label.selected || label.name === METRIC_LABEL) && this.fetchValues(label.name, selector)
);
});
} else {
// Do facetting
this.fetchSeries(selector, lastFacetted);
}
};
async fetchValues(name: string, selector: string) {
const { languageProvider } = this.props;
this.updateLabelState(name, { loading: true }, `Fetching values for ${name}`);
try {
let rawValues = await languageProvider.getLabelValues(name);
// If selector changed, clear loading state and discard result by returning early
if (selector !== buildSelector(this.state.labels)) {
this.updateLabelState(name, { loading: false });
return;
}
const values: FacettableValue[] = [];
const { metricsMetadata } = languageProvider;
for (const labelValue of rawValues) {
const value: FacettableValue = { name: labelValue };
// Adding type/help text to metrics
if (name === METRIC_LABEL && metricsMetadata) {
const meta = metricsMetadata[labelValue];
if (meta) {
value.details = `(${meta.type}) ${meta.help}`;
}
}
values.push(value);
}
this.updateLabelState(name, { values, loading: false });
} catch (error) {
console.error(error);
}
}
async fetchSeries(selector: string, lastFacetted?: string) {
const { languageProvider } = this.props;
if (lastFacetted) {
this.updateLabelState(lastFacetted, { loading: true }, `Facetting labels for ${selector}`);
}
try {
const possibleLabels = await languageProvider.fetchSeriesLabels(selector, true);
// If selector changed, clear loading state and discard result by returning early
if (selector !== buildSelector(this.state.labels)) {
if (lastFacetted) {
this.updateLabelState(lastFacetted, { loading: false });
}
return;
}
if (Object.keys(possibleLabels).length === 0) {
this.setState({ error: `Empty results, no matching label for ${selector}` });
return;
}
const labels: SelectableLabel[] = facetLabels(this.state.labels, possibleLabels, lastFacetted);
this.setState({ labels, error: '' });
if (lastFacetted) {
this.updateLabelState(lastFacetted, { loading: false });
}
} catch (error) {
console.error(error);
}
}
async validateSelector(selector: string) {
const { languageProvider } = this.props;
this.setState({ validationStatus: `Validating selector ${selector}`, error: '' });
const streams = await languageProvider.fetchSeries(selector);
this.setState({ validationStatus: `Selector is valid (${streams.length} series found)` });
}
render() {
const { theme } = this.props;
const { labels, labelSearchTerm, metricSearchTerm, status, error, validationStatus, valueSearchTerm } = this.state;
const styles = getStyles(theme);
if (labels.length === 0) {
return (
<div className={styles.wrapper}>
<LoadingPlaceholder text="Loading labels..." />
</div>
);
}
// Filter metrics
let metrics = labels.find((label) => label.name === METRIC_LABEL);
if (metrics && metricSearchTerm) {
metrics = {
...metrics,
values: metrics.values?.filter((value) => value.selected || value.name.includes(metricSearchTerm)),
};
}
// Filter labels
let nonMetricLabels = labels.filter((label) => !label.hidden && label.name !== METRIC_LABEL);
if (labelSearchTerm) {
nonMetricLabels = nonMetricLabels.filter((label) => label.selected || label.name.includes(labelSearchTerm));
}
// Filter non-metric label values
let selectedLabels = nonMetricLabels.filter((label) => label.selected && label.values);
if (valueSearchTerm) {
selectedLabels = selectedLabels.map((label) => ({
...label,
values: label.values?.filter((value) => value.selected || value.name.includes(valueSearchTerm)),
}));
}
const selector = buildSelector(this.state.labels);
const empty = selector === EMPTY_SELECTOR;
const metricCount = metrics?.values?.length || 0;
return (
<div className={styles.wrapper}>
<HorizontalGroup align="flex-start" spacing="lg">
<div>
<div className={styles.section}>
<Label description="Once a metric is selected only possible labels are shown.">1. Select a metric</Label>
<div>
<Input
onChange={this.onChangeMetricSearch}
aria-label="Filter expression for metric"
value={metricSearchTerm}
/>
</div>
<div role="list" className={styles.valueListWrapper}>
<FixedSizeList
height={Math.min(450, metricCount * LIST_ITEM_SIZE)}
itemCount={metricCount}
itemSize={LIST_ITEM_SIZE}
itemKey={(i) => (metrics!.values as FacettableValue[])[i].name}
width={300}
className={styles.valueList}
>
{({ index, style }) => {
const value = metrics?.values?.[index];
if (!value) {
return null;
}
return (
<div style={style}>
<PromLabel
name={metrics!.name}
value={value?.name}
title={value.details}
active={value?.selected}
onClick={this.onClickMetric}
searchTerm={metricSearchTerm}
/>
</div>
);
}}
</FixedSizeList>
</div>
</div>
</div>
<div>
<div className={styles.section}>
<Label description="Once label values are selected, only possible label combinations are shown.">
2. Select labels to search in
</Label>
<div>
<Input
onChange={this.onChangeLabelSearch}
aria-label="Filter expression for label"
value={labelSearchTerm}
/>
</div>
{/* Using fixed height here to prevent jumpy layout */}
<div className={styles.list} style={{ height: 120 }}>
{nonMetricLabels.map((label) => (
<PromLabel
key={label.name}
name={label.name}
loading={label.loading}
active={label.selected}
hidden={label.hidden}
facets={label.facets}
onClick={this.onClickLabel}
searchTerm={labelSearchTerm}
/>
))}
</div>
</div>
<div className={styles.section}>
<Label description="Use the search field to find values across selected labels.">
3. Select (multiple) values for your labels
</Label>
<div>
<Input
onChange={this.onChangeValueSearch}
aria-label="Filter expression for label values"
value={valueSearchTerm}
/>
</div>
<div className={styles.valueListArea} ref={this.valueListsRef}>
{selectedLabels.map((label) => (
<div
role="list"
key={label.name}
aria-label={`Values for ${label.name}`}
className={styles.valueListWrapper}
>
<div className={styles.valueTitle}>
<PromLabel
name={label.name}
loading={label.loading}
active={label.selected}
hidden={label.hidden}
//If no facets, we want to show number of all label values
facets={label.facets || label.values?.length}
onClick={this.onClickLabel}
/>
</div>
<FixedSizeList
height={Math.min(200, LIST_ITEM_SIZE * (label.values?.length || 0))}
itemCount={label.values?.length || 0}
itemSize={28}
itemKey={(i) => (label.values as FacettableValue[])[i].name}
width={200}
className={styles.valueList}
>
{({ index, style }) => {
const value = label.values?.[index];
if (!value) {
return null;
}
return (
<div style={style}>
<PromLabel
name={label.name}
value={value?.name}
active={value?.selected}
onClick={this.onClickValue}
searchTerm={valueSearchTerm}
/>
</div>
);
}}
</FixedSizeList>
</div>
))}
</div>
</div>
</div>
</HorizontalGroup>
<div className={styles.section}>
<Label>4. Resulting selector</Label>
<div aria-label="selector" className={styles.selector}>
{selector}
</div>
{validationStatus && <div className={styles.validationStatus}>{validationStatus}</div>}
<HorizontalGroup>
<Button aria-label="Use selector for query button" disabled={empty} onClick={this.onClickRunQuery}>
Use query
</Button>
<Button
aria-label="Use selector as metrics button"
variant="secondary"
disabled={empty}
onClick={this.onClickRunRateQuery}
>
Use as rate query
</Button>
<Button
aria-label="Validate submit button"
variant="secondary"
disabled={empty}
onClick={this.onClickValidate}
>
Validate selector
</Button>
<Button aria-label="Selector clear button" variant="secondary" onClick={this.onClickClear}>
Clear
</Button>
<div className={cx(styles.status, (status || error) && styles.statusShowing)}>
<span className={error ? styles.error : ''}>{error || status}</span>
</div>
</HorizontalGroup>
</div>
</div>
);
}
}
export const PrometheusMetricsBrowser = withTheme(UnthemedPrometheusMetricsBrowser);
| public/app/plugins/datasource/prometheus/components/PrometheusMetricsBrowser.tsx | 0 | https://github.com/grafana/grafana/commit/ed6a8877371211e9466fa780e940b485ac9a64d2 | [
0.00017738805036060512,
0.00017099564138334244,
0.0001618489040993154,
0.0001708782510831952,
0.0000027359094474377343
] |
{
"id": 2,
"code_window": [
"\t\treturn err\n",
"\t})\n",
"}\n",
"\n",
"func (st DBstore) UpdateRuleGroup(ctx context.Context, orgID int64, namespaceUID string, ruleGroup string, interval int64) error {\n",
"\treturn st.SQLStore.WithDbSession(ctx, func(sess *sqlstore.DBSession) error {\n",
"\t\t_, err := sess.Update(\n",
"\t\t\tngmodels.AlertRule{IntervalSeconds: interval},\n",
"\t\t\tngmodels.AlertRule{OrgID: orgID, RuleGroup: ruleGroup, NamespaceUID: namespaceUID},\n",
"\t\t)\n",
"\t\treturn err\n",
"\t})\n",
"}\n",
"\n",
"// GetNamespaces returns the folders that are visible to the user and have at least one alert in it\n",
"func (st DBstore) GetUserVisibleNamespaces(ctx context.Context, orgID int64, user *models.SignedInUser) (map[string]*models.Folder, error) {\n",
"\tnamespaceMap := make(map[string]*models.Folder)\n",
"\n",
"\tsearchQuery := models.FindPersistedDashboardsQuery{\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "pkg/services/ngalert/store/alert_rule.go",
"type": "replace",
"edit_start_line_idx": 321
} | import { Placement, VirtualElement } from '@popperjs/core';
import React, { PureComponent } from 'react';
import { Manager, Popper as ReactPopper, PopperArrowProps } from 'react-popper';
import Transition from 'react-transition-group/Transition';
import { Portal } from '../Portal/Portal';
import { PopoverContent } from './types';
const defaultTransitionStyles = {
transitionProperty: 'opacity',
transitionDuration: '200ms',
transitionTimingFunction: 'linear',
opacity: 0,
};
const transitionStyles: { [key: string]: object } = {
exited: { opacity: 0 },
entering: { opacity: 0 },
entered: { opacity: 1, transitionDelay: '0s' },
exiting: { opacity: 0, transitionDelay: '500ms' },
};
export type RenderPopperArrowFn = (props: { arrowProps: PopperArrowProps; placement: string }) => JSX.Element;
interface Props extends React.HTMLAttributes<HTMLDivElement> {
show: boolean;
placement?: Placement;
content: PopoverContent;
referenceElement: HTMLElement | VirtualElement;
wrapperClassName?: string;
renderArrow?: RenderPopperArrowFn;
}
class Popover extends PureComponent<Props> {
render() {
const {
content,
show,
placement,
onMouseEnter,
onMouseLeave,
className,
wrapperClassName,
renderArrow,
referenceElement,
onKeyDown,
} = this.props;
return (
<Manager>
<Transition in={show} timeout={100} mountOnEnter={true} unmountOnExit={true}>
{(transitionState) => {
return (
<Portal>
<ReactPopper
placement={placement}
referenceElement={referenceElement}
modifiers={[
{ name: 'preventOverflow', enabled: true, options: { rootBoundary: 'viewport' } },
{
name: 'eventListeners',
options: { scroll: true, resize: true },
},
]}
>
{({ ref, style, placement, arrowProps, update }) => {
return (
<div
onMouseEnter={onMouseEnter}
onMouseLeave={onMouseLeave}
onKeyDown={onKeyDown}
ref={ref}
style={{
...style,
...defaultTransitionStyles,
...transitionStyles[transitionState],
}}
data-placement={placement}
className={`${wrapperClassName}`}
>
<div className={className}>
{typeof content === 'string' && content}
{React.isValidElement(content) && React.cloneElement(content)}
{typeof content === 'function' &&
content({
updatePopperPosition: update,
})}
{renderArrow &&
renderArrow({
arrowProps,
placement,
})}
</div>
</div>
);
}}
</ReactPopper>
</Portal>
);
}}
</Transition>
</Manager>
);
}
}
export { Popover };
| packages/grafana-ui/src/components/Tooltip/Popover.tsx | 0 | https://github.com/grafana/grafana/commit/ed6a8877371211e9466fa780e940b485ac9a64d2 | [
0.00017549841140862554,
0.0001713418314466253,
0.0001677587570156902,
0.00017106907034758478,
0.000002120468252542196
] |
{
"id": 0,
"code_window": [
"}\n",
"\n",
"export const enum ConfiguredInputType {\n",
"\tPrompt,\n",
"\tPick\n",
"}\n",
"\n",
"export interface ConfiguredInput {\n",
"\tid: string;\n",
"\tdescription: string;\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tPromptString,\n",
"\tPickString\n"
],
"file_path": "src/vs/workbench/services/configurationResolver/common/configurationResolver.ts",
"type": "replace",
"edit_start_line_idx": 43
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { URI as uri } from 'vs/base/common/uri';
import * as nls from 'vs/nls';
import * as paths from 'vs/base/common/paths';
import * as platform from 'vs/base/common/platform';
import * as Objects from 'vs/base/common/objects';
import * as Types from 'vs/base/common/types';
import { Schemas } from 'vs/base/common/network';
import { TPromise } from 'vs/base/common/winjs.base';
import { sequence } from 'vs/base/common/async';
import { toResource } from 'vs/workbench/common/editor';
import { IStringDictionary, forEach, fromMap } from 'vs/base/common/collections';
import { IEnvironmentService } from 'vs/platform/environment/common/environment';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { ICommandService } from 'vs/platform/commands/common/commands';
import { IWorkspaceFolder, IWorkspaceContextService, WorkbenchState } from 'vs/platform/workspace/common/workspace';
import { IEditorService } from 'vs/workbench/services/editor/common/editorService';
import { AbstractVariableResolverService } from 'vs/workbench/services/configurationResolver/node/variableResolver';
import { isCodeEditor } from 'vs/editor/browser/editorBrowser';
import { DiffEditorInput } from 'vs/workbench/common/editor/diffEditorInput';
import { IQuickInputService, IInputOptions, IQuickPickItem, IPickOptions } from 'vs/platform/quickinput/common/quickInput';
import { ConfiguredInput, ConfiguredInputType } from 'vs/workbench/services/configurationResolver/common/configurationResolver';
export class ConfigurationResolverService extends AbstractVariableResolverService {
constructor(
envVariables: platform.IProcessEnvironment,
@IEditorService editorService: IEditorService,
@IEnvironmentService environmentService: IEnvironmentService,
@IConfigurationService private configurationService: IConfigurationService,
@ICommandService private commandService: ICommandService,
@IWorkspaceContextService private workspaceContextService: IWorkspaceContextService,
@IQuickInputService private quickInputService: IQuickInputService
) {
super({
getFolderUri: (folderName: string): uri => {
const folder = workspaceContextService.getWorkspace().folders.filter(f => f.name === folderName).pop();
return folder ? folder.uri : undefined;
},
getWorkspaceFolderCount: (): number => {
return workspaceContextService.getWorkspace().folders.length;
},
getConfigurationValue: (folderUri: uri, suffix: string) => {
return configurationService.getValue<string>(suffix, folderUri ? { resource: folderUri } : undefined);
},
getExecPath: () => {
return environmentService['execPath'];
},
getFilePath: (): string | undefined => {
let activeEditor = editorService.activeEditor;
if (activeEditor instanceof DiffEditorInput) {
activeEditor = activeEditor.modifiedInput;
}
const fileResource = toResource(activeEditor, { filter: Schemas.file });
if (!fileResource) {
return undefined;
}
return paths.normalize(fileResource.fsPath, true);
},
getSelectedText: (): string | undefined => {
const activeTextEditorWidget = editorService.activeTextEditorWidget;
if (isCodeEditor(activeTextEditorWidget)) {
const editorModel = activeTextEditorWidget.getModel();
const editorSelection = activeTextEditorWidget.getSelection();
if (editorModel && editorSelection) {
return editorModel.getValueInRange(editorSelection);
}
}
return undefined;
},
getLineNumber: (): string => {
const activeTextEditorWidget = editorService.activeTextEditorWidget;
if (isCodeEditor(activeTextEditorWidget)) {
const lineNumber = activeTextEditorWidget.getSelection().positionLineNumber;
return String(lineNumber);
}
return undefined;
}
}, envVariables);
}
public resolveWithInteractionReplace(folder: IWorkspaceFolder, config: any, section?: string, variables?: IStringDictionary<string>): TPromise<any> {
// resolve any non-interactive variables
config = this.resolveAny(folder, config);
// resolve input variables in the order in which they are encountered
return this.resolveWithInteraction(folder, config, section, variables).then(mapping => {
// finally substitute evaluated command variables (if there are any)
if (mapping.size > 0) {
return this.resolveAny(folder, config, fromMap(mapping));
} else {
return config;
}
});
}
public resolveWithInteraction(folder: IWorkspaceFolder, config: any, section?: string, variables?: IStringDictionary<string>): TPromise<Map<string, string>> {
// resolve any non-interactive variables
const resolved = this.resolveAnyMap(folder, config);
config = resolved.newConfig;
const allVariableMapping: Map<string, string> = resolved.resolvedVariables;
// resolve input variables in the order in which they are encountered
return this.resolveWithInputs(folder, config, section).then(inputMapping => {
if (!this.updateMapping(inputMapping, allVariableMapping)) {
return undefined;
}
// resolve commands in the order in which they are encountered
return this.resolveWithCommands(config, variables).then(commandMapping => {
if (!this.updateMapping(commandMapping, allVariableMapping)) {
return undefined;
}
return allVariableMapping;
});
});
}
/**
* Add all items from newMapping to fullMapping. Returns false if newMapping is undefined.
*/
private updateMapping(newMapping: IStringDictionary<string>, fullMapping: Map<string, string>): boolean {
if (!newMapping) {
return false;
}
forEach(newMapping, (entry) => {
fullMapping.set(entry.key, entry.value);
});
return true;
}
/**
* Finds and executes all command variables in the given configuration and returns their values as a dictionary.
* Please note: this method does not substitute the command variables (so the configuration is not modified).
* The returned dictionary can be passed to "resolvePlatform" for the substitution.
* See #6569.
* @param configuration
* @param variableToCommandMap Aliases for commands
*/
private resolveWithCommands(configuration: any, variableToCommandMap: IStringDictionary<string>): TPromise<IStringDictionary<string>> {
if (!configuration) {
return TPromise.as(undefined);
}
// use an array to preserve order of first appearance
const cmd_var = /\${command:(.*?)}/g;
const commands: string[] = [];
this.findVariables(cmd_var, configuration, commands);
let cancelled = false;
const commandValueMapping: IStringDictionary<string> = Object.create(null);
const factory: { (): TPromise<any> }[] = commands.map(commandVariable => {
return () => {
let commandId = variableToCommandMap ? variableToCommandMap[commandVariable] : undefined;
if (!commandId) {
// Just launch any command if the interactive variable is not contributed by the adapter #12735
commandId = commandVariable;
}
return this.commandService.executeCommand<string>(commandId, configuration).then(result => {
if (typeof result === 'string') {
commandValueMapping['command:' + commandVariable] = result;
} else if (Types.isUndefinedOrNull(result)) {
cancelled = true;
} else {
throw new Error(nls.localize('stringsOnlySupported', "Command '{0}' did not return a string result. Only strings are supported as results for commands used for variable substitution.", commandVariable));
}
});
};
});
return sequence(factory).then(() => cancelled ? undefined : commandValueMapping);
}
/**
* Resolves all inputs in a configuration and returns a map that maps the unresolved input to the resolved input.
* Does not do replacement of inputs.
* @param folder
* @param config
* @param section
*/
public resolveWithInputs(folder: IWorkspaceFolder, config: any, section: string): Promise<IStringDictionary<string>> {
if (!config) {
return Promise.resolve(undefined);
} else if (folder && section) {
// Get all the possible inputs
let result = this.workspaceContextService.getWorkbenchState() !== WorkbenchState.EMPTY
? Objects.deepClone(this.configurationService.getValue<any>(section, { resource: folder.uri }))
: undefined;
let inputsArray = result ? this.parseConfigurationInputs(result.inputs) : undefined;
const inputs = new Map<string, ConfiguredInput>();
if (inputsArray) {
inputsArray.forEach(input => {
inputs.set(input.id, input);
});
// use an array to preserve order of first appearance
const input_var = /\${input:(.*?)}/g;
const commands: string[] = [];
this.findVariables(input_var, config, commands);
let cancelled = false;
const commandValueMapping: IStringDictionary<string> = Object.create(null);
const factory: { (): Promise<any> }[] = commands.map(commandVariable => {
return () => {
return this.showUserInput(commandVariable, inputs).then(resolvedValue => {
if (resolvedValue) {
commandValueMapping['input:' + commandVariable] = resolvedValue;
}
});
};
}, reason => {
return Promise.reject(reason);
});
return sequence(factory).then(() => cancelled ? undefined : commandValueMapping);
}
}
return Promise.resolve(Object.create(null));
}
/**
* Takes the provided input info and shows the quick pick so the user can provide the value for the input
* @param commandVariable Name of the input.
* @param inputs Information about each possible input.
* @param commandValueMapping
*/
private showUserInput(commandVariable: string, inputs: Map<string, ConfiguredInput>): Promise<string> {
if (inputs && inputs.has(commandVariable)) {
const input = inputs.get(commandVariable);
if (input.type === ConfiguredInputType.Prompt) {
let inputOptions: IInputOptions = { prompt: input.description };
if (input.default) {
inputOptions.value = input.default;
}
return this.quickInputService.input(inputOptions).then(resolvedInput => {
return resolvedInput ? resolvedInput : input.default;
});
} else { // input.type === ConfiguredInputType.pick
let picks = new Array<IQuickPickItem>();
if (input.options) {
input.options.forEach(pickOption => {
let item: IQuickPickItem = { label: pickOption };
if (input.default && (pickOption === input.default)) {
item.description = nls.localize('defaultInputValue', "Default");
picks.unshift(item);
} else {
picks.push(item);
}
});
}
let pickOptions: IPickOptions<IQuickPickItem> = { placeHolder: input.description };
return this.quickInputService.pick(picks, pickOptions, undefined).then(resolvedInput => {
return resolvedInput ? resolvedInput.label : input.default;
});
}
}
return Promise.resolve(undefined);
}
/**
* Finds all variables in object using cmdVar and pushes them into commands.
* @param cmdVar Regex to use for finding variables.
* @param object object is searched for variables.
* @param commands All found variables are returned in commands.
*/
private findVariables(cmdVar: RegExp, object: any, commands: string[]) {
if (!object) {
return;
} else if (typeof object === 'string') {
let matches;
while ((matches = cmdVar.exec(object)) !== null) {
if (matches.length === 2) {
const command = matches[1];
if (commands.indexOf(command) < 0) {
commands.push(command);
}
}
}
} else if (Types.isArray(object)) {
object.forEach(value => {
this.findVariables(cmdVar, value, commands);
});
} else {
Object.keys(object).forEach(key => {
const value = object[key];
this.findVariables(cmdVar, value, commands);
});
}
}
/**
* Converts an array of inputs into an actaul array of typed, ConfiguredInputs.
* @param object Array of something that should look like inputs.
*/
private parseConfigurationInputs(object: any[]): ConfiguredInput[] | undefined {
let inputs = new Array<ConfiguredInput>();
if (object) {
object.forEach(item => {
if (Types.isString(item.id) && Types.isString(item.description) && Types.isString(item.type)) {
let type: ConfiguredInputType;
switch (item.type) {
case 'prompt': type = ConfiguredInputType.Prompt; break;
case 'pick': type = ConfiguredInputType.Pick; break;
default: {
throw new Error(nls.localize('unknownInputTypeProvided', "Input '{0}' can only be of type 'prompt' or 'pick'.", item.id));
}
}
let options: string[];
if (type === ConfiguredInputType.Pick) {
if (Types.isStringArray(item.options)) {
options = item.options;
} else {
throw new Error(nls.localize('pickRequiresOptions', "Input '{0}' is of type 'pick' and must include 'options'.", item.id));
}
}
inputs.push({ id: item.id, description: item.description, type, default: item.default, options });
}
});
}
return inputs;
}
} | src/vs/workbench/services/configurationResolver/electron-browser/configurationResolverService.ts | 1 | https://github.com/microsoft/vscode/commit/51ef43a02382fb972b15d5b935515b69bb637a3a | [
0.9992812275886536,
0.17679283022880554,
0.0001659409754211083,
0.00018242256192024797,
0.38066044449806213
] |
{
"id": 0,
"code_window": [
"}\n",
"\n",
"export const enum ConfiguredInputType {\n",
"\tPrompt,\n",
"\tPick\n",
"}\n",
"\n",
"export interface ConfiguredInput {\n",
"\tid: string;\n",
"\tdescription: string;\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tPromptString,\n",
"\tPickString\n"
],
"file_path": "src/vs/workbench/services/configurationResolver/common/configurationResolver.ts",
"type": "replace",
"edit_start_line_idx": 43
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { Registry } from 'vs/platform/registry/common/platform';
import { IPanel } from 'vs/workbench/common/panel';
import { Composite, CompositeDescriptor, CompositeRegistry } from 'vs/workbench/browser/composite';
import { Action } from 'vs/base/common/actions';
import { IPanelService } from 'vs/workbench/services/panel/common/panelService';
import { IPartService, Parts } from 'vs/workbench/services/part/common/partService';
import { IConstructorSignature0 } from 'vs/platform/instantiation/common/instantiation';
import { isAncestor } from 'vs/base/browser/dom';
export abstract class Panel extends Composite implements IPanel { }
/**
* A panel descriptor is a leightweight descriptor of a panel in the workbench.
*/
export class PanelDescriptor extends CompositeDescriptor<Panel> {
constructor(ctor: IConstructorSignature0<Panel>, id: string, name: string, cssClass?: string, order?: number, _commandId?: string) {
super(ctor, id, name, cssClass, order, _commandId);
}
}
export class PanelRegistry extends CompositeRegistry<Panel> {
private defaultPanelId: string;
/**
* Registers a panel to the platform.
*/
registerPanel(descriptor: PanelDescriptor): void {
super.registerComposite(descriptor);
}
/**
* Returns an array of registered panels known to the platform.
*/
getPanels(): PanelDescriptor[] {
return this.getComposites() as PanelDescriptor[];
}
/**
* Sets the id of the panel that should open on startup by default.
*/
setDefaultPanelId(id: string): void {
this.defaultPanelId = id;
}
/**
* Gets the id of the panel that should open on startup by default.
*/
getDefaultPanelId(): string {
return this.defaultPanelId;
}
}
/**
* A reusable action to toggle a panel with a specific id depending on focus.
*/
export abstract class TogglePanelAction extends Action {
private panelId: string;
constructor(
id: string,
label: string,
panelId: string,
protected panelService: IPanelService,
private partService: IPartService,
cssClass?: string
) {
super(id, label, cssClass);
this.panelId = panelId;
}
run(): Thenable<any> {
if (this.isPanelFocused()) {
this.partService.setPanelHidden(true);
} else {
this.panelService.openPanel(this.panelId, true);
}
return Promise.resolve(null);
}
private isPanelActive(): boolean {
const activePanel = this.panelService.getActivePanel();
return activePanel && activePanel.getId() === this.panelId;
}
private isPanelFocused(): boolean {
const activeElement = document.activeElement;
return this.isPanelActive() && activeElement && isAncestor(activeElement, this.partService.getContainer(Parts.PANEL_PART));
}
}
export const Extensions = {
Panels: 'workbench.contributions.panels'
};
Registry.add(Extensions.Panels, new PanelRegistry());
| src/vs/workbench/browser/panel.ts | 0 | https://github.com/microsoft/vscode/commit/51ef43a02382fb972b15d5b935515b69bb637a3a | [
0.00024260890495497733,
0.00017992009816225618,
0.0001646002201596275,
0.00017238932196050882,
0.00002047076304734219
] |
{
"id": 0,
"code_window": [
"}\n",
"\n",
"export const enum ConfiguredInputType {\n",
"\tPrompt,\n",
"\tPick\n",
"}\n",
"\n",
"export interface ConfiguredInput {\n",
"\tid: string;\n",
"\tdescription: string;\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tPromptString,\n",
"\tPickString\n"
],
"file_path": "src/vs/workbench/services/configurationResolver/common/configurationResolver.ts",
"type": "replace",
"edit_start_line_idx": 43
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { createDecorator } from 'vs/platform/instantiation/common/instantiation';
export const FOLDER_CONFIG_FOLDER_NAME = '.vscode';
export const FOLDER_SETTINGS_NAME = 'settings';
export const FOLDER_SETTINGS_PATH = `${FOLDER_CONFIG_FOLDER_NAME}/${FOLDER_SETTINGS_NAME}.json`;
export const IWorkspaceConfigurationService = createDecorator<IWorkspaceConfigurationService>('configurationService');
export interface IWorkspaceConfigurationService extends IConfigurationService {
}
export const defaultSettingsSchemaId = 'vscode://schemas/settings/default';
export const userSettingsSchemaId = 'vscode://schemas/settings/user';
export const workspaceSettingsSchemaId = 'vscode://schemas/settings/workspace';
export const folderSettingsSchemaId = 'vscode://schemas/settings/folder';
export const launchSchemaId = 'vscode://schemas/launch';
export const TASKS_CONFIGURATION_KEY = 'tasks';
export const LAUNCH_CONFIGURATION_KEY = 'launch';
export const WORKSPACE_STANDALONE_CONFIGURATIONS = Object.create(null);
WORKSPACE_STANDALONE_CONFIGURATIONS[TASKS_CONFIGURATION_KEY] = `${FOLDER_CONFIG_FOLDER_NAME}/${TASKS_CONFIGURATION_KEY}.json`;
WORKSPACE_STANDALONE_CONFIGURATIONS[LAUNCH_CONFIGURATION_KEY] = `${FOLDER_CONFIG_FOLDER_NAME}/${LAUNCH_CONFIGURATION_KEY}.json`;
| src/vs/workbench/services/configuration/common/configuration.ts | 0 | https://github.com/microsoft/vscode/commit/51ef43a02382fb972b15d5b935515b69bb637a3a | [
0.0002389222790952772,
0.00019293399236630648,
0.00016800864250399172,
0.00017187101184390485,
0.00003255684714531526
] |
{
"id": 0,
"code_window": [
"}\n",
"\n",
"export const enum ConfiguredInputType {\n",
"\tPrompt,\n",
"\tPick\n",
"}\n",
"\n",
"export interface ConfiguredInput {\n",
"\tid: string;\n",
"\tdescription: string;\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tPromptString,\n",
"\tPickString\n"
],
"file_path": "src/vs/workbench/services/configurationResolver/common/configurationResolver.ts",
"type": "replace",
"edit_start_line_idx": 43
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as assert from 'assert';
import { IViewLineTokens, LineTokens } from 'vs/editor/common/core/lineTokens';
import { MetadataConsts } from 'vs/editor/common/modes';
suite('LineTokens', () => {
interface ILineToken {
startIndex: number;
foreground: number;
}
function createLineTokens(text: string, tokens: ILineToken[]): LineTokens {
let binTokens = new Uint32Array(tokens.length << 1);
for (let i = 0, len = tokens.length; i < len; i++) {
binTokens[(i << 1)] = (i + 1 < len ? tokens[i + 1].startIndex : text.length);
binTokens[(i << 1) + 1] = (
tokens[i].foreground << MetadataConsts.FOREGROUND_OFFSET
) >>> 0;
}
return new LineTokens(binTokens, text);
}
function createTestLineTokens(): LineTokens {
return createLineTokens(
'Hello world, this is a lovely day',
[
{ startIndex: 0, foreground: 1 }, // Hello_
{ startIndex: 6, foreground: 2 }, // world,_
{ startIndex: 13, foreground: 3 }, // this_
{ startIndex: 18, foreground: 4 }, // is_
{ startIndex: 21, foreground: 5 }, // a_
{ startIndex: 23, foreground: 6 }, // lovely_
{ startIndex: 30, foreground: 7 }, // day
]
);
}
test('basics', () => {
const lineTokens = createTestLineTokens();
assert.equal(lineTokens.getLineContent(), 'Hello world, this is a lovely day');
assert.equal(lineTokens.getLineContent().length, 33);
assert.equal(lineTokens.getCount(), 7);
assert.equal(lineTokens.getStartOffset(0), 0);
assert.equal(lineTokens.getEndOffset(0), 6);
assert.equal(lineTokens.getStartOffset(1), 6);
assert.equal(lineTokens.getEndOffset(1), 13);
assert.equal(lineTokens.getStartOffset(2), 13);
assert.equal(lineTokens.getEndOffset(2), 18);
assert.equal(lineTokens.getStartOffset(3), 18);
assert.equal(lineTokens.getEndOffset(3), 21);
assert.equal(lineTokens.getStartOffset(4), 21);
assert.equal(lineTokens.getEndOffset(4), 23);
assert.equal(lineTokens.getStartOffset(5), 23);
assert.equal(lineTokens.getEndOffset(5), 30);
assert.equal(lineTokens.getStartOffset(6), 30);
assert.equal(lineTokens.getEndOffset(6), 33);
});
test('findToken', () => {
const lineTokens = createTestLineTokens();
assert.equal(lineTokens.findTokenIndexAtOffset(0), 0);
assert.equal(lineTokens.findTokenIndexAtOffset(1), 0);
assert.equal(lineTokens.findTokenIndexAtOffset(2), 0);
assert.equal(lineTokens.findTokenIndexAtOffset(3), 0);
assert.equal(lineTokens.findTokenIndexAtOffset(4), 0);
assert.equal(lineTokens.findTokenIndexAtOffset(5), 0);
assert.equal(lineTokens.findTokenIndexAtOffset(6), 1);
assert.equal(lineTokens.findTokenIndexAtOffset(7), 1);
assert.equal(lineTokens.findTokenIndexAtOffset(8), 1);
assert.equal(lineTokens.findTokenIndexAtOffset(9), 1);
assert.equal(lineTokens.findTokenIndexAtOffset(10), 1);
assert.equal(lineTokens.findTokenIndexAtOffset(11), 1);
assert.equal(lineTokens.findTokenIndexAtOffset(12), 1);
assert.equal(lineTokens.findTokenIndexAtOffset(13), 2);
assert.equal(lineTokens.findTokenIndexAtOffset(14), 2);
assert.equal(lineTokens.findTokenIndexAtOffset(15), 2);
assert.equal(lineTokens.findTokenIndexAtOffset(16), 2);
assert.equal(lineTokens.findTokenIndexAtOffset(17), 2);
assert.equal(lineTokens.findTokenIndexAtOffset(18), 3);
assert.equal(lineTokens.findTokenIndexAtOffset(19), 3);
assert.equal(lineTokens.findTokenIndexAtOffset(20), 3);
assert.equal(lineTokens.findTokenIndexAtOffset(21), 4);
assert.equal(lineTokens.findTokenIndexAtOffset(22), 4);
assert.equal(lineTokens.findTokenIndexAtOffset(23), 5);
assert.equal(lineTokens.findTokenIndexAtOffset(24), 5);
assert.equal(lineTokens.findTokenIndexAtOffset(25), 5);
assert.equal(lineTokens.findTokenIndexAtOffset(26), 5);
assert.equal(lineTokens.findTokenIndexAtOffset(27), 5);
assert.equal(lineTokens.findTokenIndexAtOffset(28), 5);
assert.equal(lineTokens.findTokenIndexAtOffset(29), 5);
assert.equal(lineTokens.findTokenIndexAtOffset(30), 6);
assert.equal(lineTokens.findTokenIndexAtOffset(31), 6);
assert.equal(lineTokens.findTokenIndexAtOffset(32), 6);
assert.equal(lineTokens.findTokenIndexAtOffset(33), 6);
assert.equal(lineTokens.findTokenIndexAtOffset(34), 6);
});
interface ITestViewLineToken {
endIndex: number;
foreground: number;
}
function assertViewLineTokens(_actual: IViewLineTokens, expected: ITestViewLineToken[]): void {
let actual: ITestViewLineToken[] = [];
for (let i = 0, len = _actual.getCount(); i < len; i++) {
actual[i] = {
endIndex: _actual.getEndOffset(i),
foreground: _actual.getForeground(i)
};
}
assert.deepEqual(actual, expected);
}
test('inflate', () => {
const lineTokens = createTestLineTokens();
assertViewLineTokens(lineTokens.inflate(), [
{ endIndex: 6, foreground: 1 },
{ endIndex: 13, foreground: 2 },
{ endIndex: 18, foreground: 3 },
{ endIndex: 21, foreground: 4 },
{ endIndex: 23, foreground: 5 },
{ endIndex: 30, foreground: 6 },
{ endIndex: 33, foreground: 7 },
]);
});
test('sliceAndInflate', () => {
const lineTokens = createTestLineTokens();
assertViewLineTokens(lineTokens.sliceAndInflate(0, 33, 0), [
{ endIndex: 6, foreground: 1 },
{ endIndex: 13, foreground: 2 },
{ endIndex: 18, foreground: 3 },
{ endIndex: 21, foreground: 4 },
{ endIndex: 23, foreground: 5 },
{ endIndex: 30, foreground: 6 },
{ endIndex: 33, foreground: 7 },
]);
assertViewLineTokens(lineTokens.sliceAndInflate(0, 32, 0), [
{ endIndex: 6, foreground: 1 },
{ endIndex: 13, foreground: 2 },
{ endIndex: 18, foreground: 3 },
{ endIndex: 21, foreground: 4 },
{ endIndex: 23, foreground: 5 },
{ endIndex: 30, foreground: 6 },
{ endIndex: 32, foreground: 7 },
]);
assertViewLineTokens(lineTokens.sliceAndInflate(0, 30, 0), [
{ endIndex: 6, foreground: 1 },
{ endIndex: 13, foreground: 2 },
{ endIndex: 18, foreground: 3 },
{ endIndex: 21, foreground: 4 },
{ endIndex: 23, foreground: 5 },
{ endIndex: 30, foreground: 6 }
]);
assertViewLineTokens(lineTokens.sliceAndInflate(0, 30, 1), [
{ endIndex: 7, foreground: 1 },
{ endIndex: 14, foreground: 2 },
{ endIndex: 19, foreground: 3 },
{ endIndex: 22, foreground: 4 },
{ endIndex: 24, foreground: 5 },
{ endIndex: 31, foreground: 6 }
]);
assertViewLineTokens(lineTokens.sliceAndInflate(6, 18, 0), [
{ endIndex: 7, foreground: 2 },
{ endIndex: 12, foreground: 3 }
]);
assertViewLineTokens(lineTokens.sliceAndInflate(7, 18, 0), [
{ endIndex: 6, foreground: 2 },
{ endIndex: 11, foreground: 3 }
]);
assertViewLineTokens(lineTokens.sliceAndInflate(6, 17, 0), [
{ endIndex: 7, foreground: 2 },
{ endIndex: 11, foreground: 3 }
]);
assertViewLineTokens(lineTokens.sliceAndInflate(6, 19, 0), [
{ endIndex: 7, foreground: 2 },
{ endIndex: 12, foreground: 3 },
{ endIndex: 13, foreground: 4 },
]);
});
});
| src/vs/editor/test/common/core/lineTokens.test.ts | 0 | https://github.com/microsoft/vscode/commit/51ef43a02382fb972b15d5b935515b69bb637a3a | [
0.00017673586262390018,
0.0001732897071633488,
0.00016976697952486575,
0.00017367408145219088,
0.0000018014144416156341
] |
{
"id": 1,
"code_window": [
"\t\t\t\t\t},\n",
"\t\t\t\t\ttype: {\n",
"\t\t\t\t\t\ttype: 'string',\n",
"\t\t\t\t\t\tdescription: nls.localize('JsonSchema.input.type', 'The input\\'s type. Use prompt for free string input and selection for choosing from values'),\n",
"\t\t\t\t\t\tenum: ['prompt', 'pick']\n",
"\t\t\t\t\t},\n",
"\t\t\t\t\tdescription: {\n",
"\t\t\t\t\t\ttype: 'string',\n",
"\t\t\t\t\t\tdescription: nls.localize('JsonSchema.input.description', 'Description to show for for using input.'),\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t\t\t\tdescription: nls.localize('JsonSchema.input.type', 'The input\\'s type. Use promptString for free string input and pickString for choosing from string values'),\n",
"\t\t\t\t\t\tenum: ['promptString', 'pickString']\n"
],
"file_path": "src/vs/workbench/services/configurationResolver/common/configurationResolverSchema.ts",
"type": "replace",
"edit_start_line_idx": 23
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { URI as uri } from 'vs/base/common/uri';
import * as nls from 'vs/nls';
import * as paths from 'vs/base/common/paths';
import * as platform from 'vs/base/common/platform';
import * as Objects from 'vs/base/common/objects';
import * as Types from 'vs/base/common/types';
import { Schemas } from 'vs/base/common/network';
import { TPromise } from 'vs/base/common/winjs.base';
import { sequence } from 'vs/base/common/async';
import { toResource } from 'vs/workbench/common/editor';
import { IStringDictionary, forEach, fromMap } from 'vs/base/common/collections';
import { IEnvironmentService } from 'vs/platform/environment/common/environment';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { ICommandService } from 'vs/platform/commands/common/commands';
import { IWorkspaceFolder, IWorkspaceContextService, WorkbenchState } from 'vs/platform/workspace/common/workspace';
import { IEditorService } from 'vs/workbench/services/editor/common/editorService';
import { AbstractVariableResolverService } from 'vs/workbench/services/configurationResolver/node/variableResolver';
import { isCodeEditor } from 'vs/editor/browser/editorBrowser';
import { DiffEditorInput } from 'vs/workbench/common/editor/diffEditorInput';
import { IQuickInputService, IInputOptions, IQuickPickItem, IPickOptions } from 'vs/platform/quickinput/common/quickInput';
import { ConfiguredInput, ConfiguredInputType } from 'vs/workbench/services/configurationResolver/common/configurationResolver';
export class ConfigurationResolverService extends AbstractVariableResolverService {
constructor(
envVariables: platform.IProcessEnvironment,
@IEditorService editorService: IEditorService,
@IEnvironmentService environmentService: IEnvironmentService,
@IConfigurationService private configurationService: IConfigurationService,
@ICommandService private commandService: ICommandService,
@IWorkspaceContextService private workspaceContextService: IWorkspaceContextService,
@IQuickInputService private quickInputService: IQuickInputService
) {
super({
getFolderUri: (folderName: string): uri => {
const folder = workspaceContextService.getWorkspace().folders.filter(f => f.name === folderName).pop();
return folder ? folder.uri : undefined;
},
getWorkspaceFolderCount: (): number => {
return workspaceContextService.getWorkspace().folders.length;
},
getConfigurationValue: (folderUri: uri, suffix: string) => {
return configurationService.getValue<string>(suffix, folderUri ? { resource: folderUri } : undefined);
},
getExecPath: () => {
return environmentService['execPath'];
},
getFilePath: (): string | undefined => {
let activeEditor = editorService.activeEditor;
if (activeEditor instanceof DiffEditorInput) {
activeEditor = activeEditor.modifiedInput;
}
const fileResource = toResource(activeEditor, { filter: Schemas.file });
if (!fileResource) {
return undefined;
}
return paths.normalize(fileResource.fsPath, true);
},
getSelectedText: (): string | undefined => {
const activeTextEditorWidget = editorService.activeTextEditorWidget;
if (isCodeEditor(activeTextEditorWidget)) {
const editorModel = activeTextEditorWidget.getModel();
const editorSelection = activeTextEditorWidget.getSelection();
if (editorModel && editorSelection) {
return editorModel.getValueInRange(editorSelection);
}
}
return undefined;
},
getLineNumber: (): string => {
const activeTextEditorWidget = editorService.activeTextEditorWidget;
if (isCodeEditor(activeTextEditorWidget)) {
const lineNumber = activeTextEditorWidget.getSelection().positionLineNumber;
return String(lineNumber);
}
return undefined;
}
}, envVariables);
}
public resolveWithInteractionReplace(folder: IWorkspaceFolder, config: any, section?: string, variables?: IStringDictionary<string>): TPromise<any> {
// resolve any non-interactive variables
config = this.resolveAny(folder, config);
// resolve input variables in the order in which they are encountered
return this.resolveWithInteraction(folder, config, section, variables).then(mapping => {
// finally substitute evaluated command variables (if there are any)
if (mapping.size > 0) {
return this.resolveAny(folder, config, fromMap(mapping));
} else {
return config;
}
});
}
public resolveWithInteraction(folder: IWorkspaceFolder, config: any, section?: string, variables?: IStringDictionary<string>): TPromise<Map<string, string>> {
// resolve any non-interactive variables
const resolved = this.resolveAnyMap(folder, config);
config = resolved.newConfig;
const allVariableMapping: Map<string, string> = resolved.resolvedVariables;
// resolve input variables in the order in which they are encountered
return this.resolveWithInputs(folder, config, section).then(inputMapping => {
if (!this.updateMapping(inputMapping, allVariableMapping)) {
return undefined;
}
// resolve commands in the order in which they are encountered
return this.resolveWithCommands(config, variables).then(commandMapping => {
if (!this.updateMapping(commandMapping, allVariableMapping)) {
return undefined;
}
return allVariableMapping;
});
});
}
/**
* Add all items from newMapping to fullMapping. Returns false if newMapping is undefined.
*/
private updateMapping(newMapping: IStringDictionary<string>, fullMapping: Map<string, string>): boolean {
if (!newMapping) {
return false;
}
forEach(newMapping, (entry) => {
fullMapping.set(entry.key, entry.value);
});
return true;
}
/**
* Finds and executes all command variables in the given configuration and returns their values as a dictionary.
* Please note: this method does not substitute the command variables (so the configuration is not modified).
* The returned dictionary can be passed to "resolvePlatform" for the substitution.
* See #6569.
* @param configuration
* @param variableToCommandMap Aliases for commands
*/
private resolveWithCommands(configuration: any, variableToCommandMap: IStringDictionary<string>): TPromise<IStringDictionary<string>> {
if (!configuration) {
return TPromise.as(undefined);
}
// use an array to preserve order of first appearance
const cmd_var = /\${command:(.*?)}/g;
const commands: string[] = [];
this.findVariables(cmd_var, configuration, commands);
let cancelled = false;
const commandValueMapping: IStringDictionary<string> = Object.create(null);
const factory: { (): TPromise<any> }[] = commands.map(commandVariable => {
return () => {
let commandId = variableToCommandMap ? variableToCommandMap[commandVariable] : undefined;
if (!commandId) {
// Just launch any command if the interactive variable is not contributed by the adapter #12735
commandId = commandVariable;
}
return this.commandService.executeCommand<string>(commandId, configuration).then(result => {
if (typeof result === 'string') {
commandValueMapping['command:' + commandVariable] = result;
} else if (Types.isUndefinedOrNull(result)) {
cancelled = true;
} else {
throw new Error(nls.localize('stringsOnlySupported', "Command '{0}' did not return a string result. Only strings are supported as results for commands used for variable substitution.", commandVariable));
}
});
};
});
return sequence(factory).then(() => cancelled ? undefined : commandValueMapping);
}
/**
* Resolves all inputs in a configuration and returns a map that maps the unresolved input to the resolved input.
* Does not do replacement of inputs.
* @param folder
* @param config
* @param section
*/
public resolveWithInputs(folder: IWorkspaceFolder, config: any, section: string): Promise<IStringDictionary<string>> {
if (!config) {
return Promise.resolve(undefined);
} else if (folder && section) {
// Get all the possible inputs
let result = this.workspaceContextService.getWorkbenchState() !== WorkbenchState.EMPTY
? Objects.deepClone(this.configurationService.getValue<any>(section, { resource: folder.uri }))
: undefined;
let inputsArray = result ? this.parseConfigurationInputs(result.inputs) : undefined;
const inputs = new Map<string, ConfiguredInput>();
if (inputsArray) {
inputsArray.forEach(input => {
inputs.set(input.id, input);
});
// use an array to preserve order of first appearance
const input_var = /\${input:(.*?)}/g;
const commands: string[] = [];
this.findVariables(input_var, config, commands);
let cancelled = false;
const commandValueMapping: IStringDictionary<string> = Object.create(null);
const factory: { (): Promise<any> }[] = commands.map(commandVariable => {
return () => {
return this.showUserInput(commandVariable, inputs).then(resolvedValue => {
if (resolvedValue) {
commandValueMapping['input:' + commandVariable] = resolvedValue;
}
});
};
}, reason => {
return Promise.reject(reason);
});
return sequence(factory).then(() => cancelled ? undefined : commandValueMapping);
}
}
return Promise.resolve(Object.create(null));
}
/**
* Takes the provided input info and shows the quick pick so the user can provide the value for the input
* @param commandVariable Name of the input.
* @param inputs Information about each possible input.
* @param commandValueMapping
*/
private showUserInput(commandVariable: string, inputs: Map<string, ConfiguredInput>): Promise<string> {
if (inputs && inputs.has(commandVariable)) {
const input = inputs.get(commandVariable);
if (input.type === ConfiguredInputType.Prompt) {
let inputOptions: IInputOptions = { prompt: input.description };
if (input.default) {
inputOptions.value = input.default;
}
return this.quickInputService.input(inputOptions).then(resolvedInput => {
return resolvedInput ? resolvedInput : input.default;
});
} else { // input.type === ConfiguredInputType.pick
let picks = new Array<IQuickPickItem>();
if (input.options) {
input.options.forEach(pickOption => {
let item: IQuickPickItem = { label: pickOption };
if (input.default && (pickOption === input.default)) {
item.description = nls.localize('defaultInputValue', "Default");
picks.unshift(item);
} else {
picks.push(item);
}
});
}
let pickOptions: IPickOptions<IQuickPickItem> = { placeHolder: input.description };
return this.quickInputService.pick(picks, pickOptions, undefined).then(resolvedInput => {
return resolvedInput ? resolvedInput.label : input.default;
});
}
}
return Promise.resolve(undefined);
}
/**
* Finds all variables in object using cmdVar and pushes them into commands.
* @param cmdVar Regex to use for finding variables.
* @param object object is searched for variables.
* @param commands All found variables are returned in commands.
*/
private findVariables(cmdVar: RegExp, object: any, commands: string[]) {
if (!object) {
return;
} else if (typeof object === 'string') {
let matches;
while ((matches = cmdVar.exec(object)) !== null) {
if (matches.length === 2) {
const command = matches[1];
if (commands.indexOf(command) < 0) {
commands.push(command);
}
}
}
} else if (Types.isArray(object)) {
object.forEach(value => {
this.findVariables(cmdVar, value, commands);
});
} else {
Object.keys(object).forEach(key => {
const value = object[key];
this.findVariables(cmdVar, value, commands);
});
}
}
/**
* Converts an array of inputs into an actaul array of typed, ConfiguredInputs.
* @param object Array of something that should look like inputs.
*/
private parseConfigurationInputs(object: any[]): ConfiguredInput[] | undefined {
let inputs = new Array<ConfiguredInput>();
if (object) {
object.forEach(item => {
if (Types.isString(item.id) && Types.isString(item.description) && Types.isString(item.type)) {
let type: ConfiguredInputType;
switch (item.type) {
case 'prompt': type = ConfiguredInputType.Prompt; break;
case 'pick': type = ConfiguredInputType.Pick; break;
default: {
throw new Error(nls.localize('unknownInputTypeProvided', "Input '{0}' can only be of type 'prompt' or 'pick'.", item.id));
}
}
let options: string[];
if (type === ConfiguredInputType.Pick) {
if (Types.isStringArray(item.options)) {
options = item.options;
} else {
throw new Error(nls.localize('pickRequiresOptions', "Input '{0}' is of type 'pick' and must include 'options'.", item.id));
}
}
inputs.push({ id: item.id, description: item.description, type, default: item.default, options });
}
});
}
return inputs;
}
} | src/vs/workbench/services/configurationResolver/electron-browser/configurationResolverService.ts | 1 | https://github.com/microsoft/vscode/commit/51ef43a02382fb972b15d5b935515b69bb637a3a | [
0.0006088974187150598,
0.0001891616266220808,
0.00016377485007978976,
0.0001698642154224217,
0.0000764377909945324
] |
{
"id": 1,
"code_window": [
"\t\t\t\t\t},\n",
"\t\t\t\t\ttype: {\n",
"\t\t\t\t\t\ttype: 'string',\n",
"\t\t\t\t\t\tdescription: nls.localize('JsonSchema.input.type', 'The input\\'s type. Use prompt for free string input and selection for choosing from values'),\n",
"\t\t\t\t\t\tenum: ['prompt', 'pick']\n",
"\t\t\t\t\t},\n",
"\t\t\t\t\tdescription: {\n",
"\t\t\t\t\t\ttype: 'string',\n",
"\t\t\t\t\t\tdescription: nls.localize('JsonSchema.input.description', 'Description to show for for using input.'),\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t\t\t\tdescription: nls.localize('JsonSchema.input.type', 'The input\\'s type. Use promptString for free string input and pickString for choosing from string values'),\n",
"\t\t\t\t\t\tenum: ['promptString', 'pickString']\n"
],
"file_path": "src/vs/workbench/services/configurationResolver/common/configurationResolverSchema.ts",
"type": "replace",
"edit_start_line_idx": 23
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as vscode from 'vscode';
import * as nls from 'vscode-nls';
import * as Proto from '../protocol';
import { ITypeScriptServiceClient } from '../typescriptService';
import API from '../utils/api';
import { Command, CommandManager } from '../utils/commandManager';
import { VersionDependentRegistration } from '../utils/dependentRegistration';
import * as typeconverts from '../utils/typeConverters';
import FileConfigurationManager from './fileConfigurationManager';
import TelemetryReporter from '../utils/telemetry';
import { nulToken } from '../utils/cancellation';
const localize = nls.loadMessageBundle();
class OrganizeImportsCommand implements Command {
public static readonly Id = '_typescript.organizeImports';
public readonly id = OrganizeImportsCommand.Id;
constructor(
private readonly client: ITypeScriptServiceClient,
private readonly telemetryReporter: TelemetryReporter,
) { }
public async execute(file: string): Promise<boolean> {
/* __GDPR__
"organizeImports.execute" : {
"${include}": [
"${TypeScriptCommonProperties}"
]
}
*/
this.telemetryReporter.logTelemetry('organizeImports.execute', {});
const args: Proto.OrganizeImportsRequestArgs = {
scope: {
type: 'file',
args: {
file
}
}
};
const response = await this.client.execute('organizeImports', args, nulToken);
if (response.type !== 'response' || !response.body) {
return false;
}
const edits = typeconverts.WorkspaceEdit.fromFileCodeEdits(this.client, response.body);
return vscode.workspace.applyEdit(edits);
}
}
export class OrganizeImportsCodeActionProvider implements vscode.CodeActionProvider {
public constructor(
private readonly client: ITypeScriptServiceClient,
commandManager: CommandManager,
private readonly fileConfigManager: FileConfigurationManager,
telemetryReporter: TelemetryReporter,
) {
commandManager.register(new OrganizeImportsCommand(client, telemetryReporter));
}
public readonly metadata: vscode.CodeActionProviderMetadata = {
providedCodeActionKinds: [vscode.CodeActionKind.SourceOrganizeImports]
};
public provideCodeActions(
document: vscode.TextDocument,
_range: vscode.Range,
context: vscode.CodeActionContext,
token: vscode.CancellationToken
): vscode.CodeAction[] {
const file = this.client.toPath(document.uri);
if (!file) {
return [];
}
if (!context.only || !context.only.contains(vscode.CodeActionKind.SourceOrganizeImports)) {
return [];
}
this.fileConfigManager.ensureConfigurationForDocument(document, token);
const action = new vscode.CodeAction(
localize('oraganizeImportsAction.title', "Organize Imports"),
vscode.CodeActionKind.SourceOrganizeImports);
action.command = { title: '', command: OrganizeImportsCommand.Id, arguments: [file] };
return [action];
}
}
export function register(
selector: vscode.DocumentSelector,
client: ITypeScriptServiceClient,
commandManager: CommandManager,
fileConfigurationManager: FileConfigurationManager,
telemetryReporter: TelemetryReporter,
) {
return new VersionDependentRegistration(client, API.v280, () => {
const organizeImportsProvider = new OrganizeImportsCodeActionProvider(client, commandManager, fileConfigurationManager, telemetryReporter);
return vscode.languages.registerCodeActionsProvider(selector,
organizeImportsProvider,
organizeImportsProvider.metadata);
});
}
| extensions/typescript-language-features/src/features/organizeImports.ts | 0 | https://github.com/microsoft/vscode/commit/51ef43a02382fb972b15d5b935515b69bb637a3a | [
0.00017332089191768318,
0.0001706193870631978,
0.0001662791328271851,
0.00017122059944085777,
0.0000019991546196251875
] |
{
"id": 1,
"code_window": [
"\t\t\t\t\t},\n",
"\t\t\t\t\ttype: {\n",
"\t\t\t\t\t\ttype: 'string',\n",
"\t\t\t\t\t\tdescription: nls.localize('JsonSchema.input.type', 'The input\\'s type. Use prompt for free string input and selection for choosing from values'),\n",
"\t\t\t\t\t\tenum: ['prompt', 'pick']\n",
"\t\t\t\t\t},\n",
"\t\t\t\t\tdescription: {\n",
"\t\t\t\t\t\ttype: 'string',\n",
"\t\t\t\t\t\tdescription: nls.localize('JsonSchema.input.description', 'Description to show for for using input.'),\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t\t\t\tdescription: nls.localize('JsonSchema.input.type', 'The input\\'s type. Use promptString for free string input and pickString for choosing from string values'),\n",
"\t\t\t\t\t\tenum: ['promptString', 'pickString']\n"
],
"file_path": "src/vs/workbench/services/configurationResolver/common/configurationResolverSchema.ts",
"type": "replace",
"edit_start_line_idx": 23
} | package main
import (
"encoding/base64"
"fmt"
)
func main() {
dnsName := "test-vm-from-go"
storageAccount := "mystorageaccount"
c := make(chan int)
client, err := management.ClientFromPublishSettingsFile("path/to/downloaded.publishsettings", "")
if err != nil {
panic(err)
}
// create virtual machine
role := vmutils.NewVMConfiguration(dnsName, vmSize)
vmutils.ConfigureDeploymentFromPlatformImage(
&role,
vmImage,
fmt.Sprintf("http://%s.blob.core.windows.net/sdktest/%s.vhd", storageAccount, dnsName),
"")
} | extensions/go/test/colorize-fixtures/test.go | 0 | https://github.com/microsoft/vscode/commit/51ef43a02382fb972b15d5b935515b69bb637a3a | [
0.0001712992088869214,
0.00017122330609709024,
0.00017107980966102332,
0.00017129088519141078,
1.0152075446967501e-7
] |
{
"id": 1,
"code_window": [
"\t\t\t\t\t},\n",
"\t\t\t\t\ttype: {\n",
"\t\t\t\t\t\ttype: 'string',\n",
"\t\t\t\t\t\tdescription: nls.localize('JsonSchema.input.type', 'The input\\'s type. Use prompt for free string input and selection for choosing from values'),\n",
"\t\t\t\t\t\tenum: ['prompt', 'pick']\n",
"\t\t\t\t\t},\n",
"\t\t\t\t\tdescription: {\n",
"\t\t\t\t\t\ttype: 'string',\n",
"\t\t\t\t\t\tdescription: nls.localize('JsonSchema.input.description', 'Description to show for for using input.'),\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t\t\t\tdescription: nls.localize('JsonSchema.input.type', 'The input\\'s type. Use promptString for free string input and pickString for choosing from string values'),\n",
"\t\t\t\t\t\tenum: ['promptString', 'pickString']\n"
],
"file_path": "src/vs/workbench/services/configurationResolver/common/configurationResolverSchema.ts",
"type": "replace",
"edit_start_line_idx": 23
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
.context-view {
position: absolute;
z-index: 2000;
} | src/vs/base/browser/ui/contextview/contextview.css | 0 | https://github.com/microsoft/vscode/commit/51ef43a02382fb972b15d5b935515b69bb637a3a | [
0.0001720259606372565,
0.0001720259606372565,
0.0001720259606372565,
0.0001720259606372565,
0
] |
{
"id": 2,
"code_window": [
"\t */\n",
"\tprivate showUserInput(commandVariable: string, inputs: Map<string, ConfiguredInput>): Promise<string> {\n",
"\t\tif (inputs && inputs.has(commandVariable)) {\n",
"\t\t\tconst input = inputs.get(commandVariable);\n",
"\t\t\tif (input.type === ConfiguredInputType.Prompt) {\n",
"\t\t\t\tlet inputOptions: IInputOptions = { prompt: input.description };\n",
"\t\t\t\tif (input.default) {\n",
"\t\t\t\t\tinputOptions.value = input.default;\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\tif (input.type === ConfiguredInputType.PromptString) {\n"
],
"file_path": "src/vs/workbench/services/configurationResolver/electron-browser/configurationResolverService.ts",
"type": "replace",
"edit_start_line_idx": 236
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { URI as uri } from 'vs/base/common/uri';
import * as nls from 'vs/nls';
import * as paths from 'vs/base/common/paths';
import * as platform from 'vs/base/common/platform';
import * as Objects from 'vs/base/common/objects';
import * as Types from 'vs/base/common/types';
import { Schemas } from 'vs/base/common/network';
import { TPromise } from 'vs/base/common/winjs.base';
import { sequence } from 'vs/base/common/async';
import { toResource } from 'vs/workbench/common/editor';
import { IStringDictionary, forEach, fromMap } from 'vs/base/common/collections';
import { IEnvironmentService } from 'vs/platform/environment/common/environment';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { ICommandService } from 'vs/platform/commands/common/commands';
import { IWorkspaceFolder, IWorkspaceContextService, WorkbenchState } from 'vs/platform/workspace/common/workspace';
import { IEditorService } from 'vs/workbench/services/editor/common/editorService';
import { AbstractVariableResolverService } from 'vs/workbench/services/configurationResolver/node/variableResolver';
import { isCodeEditor } from 'vs/editor/browser/editorBrowser';
import { DiffEditorInput } from 'vs/workbench/common/editor/diffEditorInput';
import { IQuickInputService, IInputOptions, IQuickPickItem, IPickOptions } from 'vs/platform/quickinput/common/quickInput';
import { ConfiguredInput, ConfiguredInputType } from 'vs/workbench/services/configurationResolver/common/configurationResolver';
export class ConfigurationResolverService extends AbstractVariableResolverService {
constructor(
envVariables: platform.IProcessEnvironment,
@IEditorService editorService: IEditorService,
@IEnvironmentService environmentService: IEnvironmentService,
@IConfigurationService private configurationService: IConfigurationService,
@ICommandService private commandService: ICommandService,
@IWorkspaceContextService private workspaceContextService: IWorkspaceContextService,
@IQuickInputService private quickInputService: IQuickInputService
) {
super({
getFolderUri: (folderName: string): uri => {
const folder = workspaceContextService.getWorkspace().folders.filter(f => f.name === folderName).pop();
return folder ? folder.uri : undefined;
},
getWorkspaceFolderCount: (): number => {
return workspaceContextService.getWorkspace().folders.length;
},
getConfigurationValue: (folderUri: uri, suffix: string) => {
return configurationService.getValue<string>(suffix, folderUri ? { resource: folderUri } : undefined);
},
getExecPath: () => {
return environmentService['execPath'];
},
getFilePath: (): string | undefined => {
let activeEditor = editorService.activeEditor;
if (activeEditor instanceof DiffEditorInput) {
activeEditor = activeEditor.modifiedInput;
}
const fileResource = toResource(activeEditor, { filter: Schemas.file });
if (!fileResource) {
return undefined;
}
return paths.normalize(fileResource.fsPath, true);
},
getSelectedText: (): string | undefined => {
const activeTextEditorWidget = editorService.activeTextEditorWidget;
if (isCodeEditor(activeTextEditorWidget)) {
const editorModel = activeTextEditorWidget.getModel();
const editorSelection = activeTextEditorWidget.getSelection();
if (editorModel && editorSelection) {
return editorModel.getValueInRange(editorSelection);
}
}
return undefined;
},
getLineNumber: (): string => {
const activeTextEditorWidget = editorService.activeTextEditorWidget;
if (isCodeEditor(activeTextEditorWidget)) {
const lineNumber = activeTextEditorWidget.getSelection().positionLineNumber;
return String(lineNumber);
}
return undefined;
}
}, envVariables);
}
public resolveWithInteractionReplace(folder: IWorkspaceFolder, config: any, section?: string, variables?: IStringDictionary<string>): TPromise<any> {
// resolve any non-interactive variables
config = this.resolveAny(folder, config);
// resolve input variables in the order in which they are encountered
return this.resolveWithInteraction(folder, config, section, variables).then(mapping => {
// finally substitute evaluated command variables (if there are any)
if (mapping.size > 0) {
return this.resolveAny(folder, config, fromMap(mapping));
} else {
return config;
}
});
}
public resolveWithInteraction(folder: IWorkspaceFolder, config: any, section?: string, variables?: IStringDictionary<string>): TPromise<Map<string, string>> {
// resolve any non-interactive variables
const resolved = this.resolveAnyMap(folder, config);
config = resolved.newConfig;
const allVariableMapping: Map<string, string> = resolved.resolvedVariables;
// resolve input variables in the order in which they are encountered
return this.resolveWithInputs(folder, config, section).then(inputMapping => {
if (!this.updateMapping(inputMapping, allVariableMapping)) {
return undefined;
}
// resolve commands in the order in which they are encountered
return this.resolveWithCommands(config, variables).then(commandMapping => {
if (!this.updateMapping(commandMapping, allVariableMapping)) {
return undefined;
}
return allVariableMapping;
});
});
}
/**
* Add all items from newMapping to fullMapping. Returns false if newMapping is undefined.
*/
private updateMapping(newMapping: IStringDictionary<string>, fullMapping: Map<string, string>): boolean {
if (!newMapping) {
return false;
}
forEach(newMapping, (entry) => {
fullMapping.set(entry.key, entry.value);
});
return true;
}
/**
* Finds and executes all command variables in the given configuration and returns their values as a dictionary.
* Please note: this method does not substitute the command variables (so the configuration is not modified).
* The returned dictionary can be passed to "resolvePlatform" for the substitution.
* See #6569.
* @param configuration
* @param variableToCommandMap Aliases for commands
*/
private resolveWithCommands(configuration: any, variableToCommandMap: IStringDictionary<string>): TPromise<IStringDictionary<string>> {
if (!configuration) {
return TPromise.as(undefined);
}
// use an array to preserve order of first appearance
const cmd_var = /\${command:(.*?)}/g;
const commands: string[] = [];
this.findVariables(cmd_var, configuration, commands);
let cancelled = false;
const commandValueMapping: IStringDictionary<string> = Object.create(null);
const factory: { (): TPromise<any> }[] = commands.map(commandVariable => {
return () => {
let commandId = variableToCommandMap ? variableToCommandMap[commandVariable] : undefined;
if (!commandId) {
// Just launch any command if the interactive variable is not contributed by the adapter #12735
commandId = commandVariable;
}
return this.commandService.executeCommand<string>(commandId, configuration).then(result => {
if (typeof result === 'string') {
commandValueMapping['command:' + commandVariable] = result;
} else if (Types.isUndefinedOrNull(result)) {
cancelled = true;
} else {
throw new Error(nls.localize('stringsOnlySupported', "Command '{0}' did not return a string result. Only strings are supported as results for commands used for variable substitution.", commandVariable));
}
});
};
});
return sequence(factory).then(() => cancelled ? undefined : commandValueMapping);
}
/**
* Resolves all inputs in a configuration and returns a map that maps the unresolved input to the resolved input.
* Does not do replacement of inputs.
* @param folder
* @param config
* @param section
*/
public resolveWithInputs(folder: IWorkspaceFolder, config: any, section: string): Promise<IStringDictionary<string>> {
if (!config) {
return Promise.resolve(undefined);
} else if (folder && section) {
// Get all the possible inputs
let result = this.workspaceContextService.getWorkbenchState() !== WorkbenchState.EMPTY
? Objects.deepClone(this.configurationService.getValue<any>(section, { resource: folder.uri }))
: undefined;
let inputsArray = result ? this.parseConfigurationInputs(result.inputs) : undefined;
const inputs = new Map<string, ConfiguredInput>();
if (inputsArray) {
inputsArray.forEach(input => {
inputs.set(input.id, input);
});
// use an array to preserve order of first appearance
const input_var = /\${input:(.*?)}/g;
const commands: string[] = [];
this.findVariables(input_var, config, commands);
let cancelled = false;
const commandValueMapping: IStringDictionary<string> = Object.create(null);
const factory: { (): Promise<any> }[] = commands.map(commandVariable => {
return () => {
return this.showUserInput(commandVariable, inputs).then(resolvedValue => {
if (resolvedValue) {
commandValueMapping['input:' + commandVariable] = resolvedValue;
}
});
};
}, reason => {
return Promise.reject(reason);
});
return sequence(factory).then(() => cancelled ? undefined : commandValueMapping);
}
}
return Promise.resolve(Object.create(null));
}
/**
* Takes the provided input info and shows the quick pick so the user can provide the value for the input
* @param commandVariable Name of the input.
* @param inputs Information about each possible input.
* @param commandValueMapping
*/
private showUserInput(commandVariable: string, inputs: Map<string, ConfiguredInput>): Promise<string> {
if (inputs && inputs.has(commandVariable)) {
const input = inputs.get(commandVariable);
if (input.type === ConfiguredInputType.Prompt) {
let inputOptions: IInputOptions = { prompt: input.description };
if (input.default) {
inputOptions.value = input.default;
}
return this.quickInputService.input(inputOptions).then(resolvedInput => {
return resolvedInput ? resolvedInput : input.default;
});
} else { // input.type === ConfiguredInputType.pick
let picks = new Array<IQuickPickItem>();
if (input.options) {
input.options.forEach(pickOption => {
let item: IQuickPickItem = { label: pickOption };
if (input.default && (pickOption === input.default)) {
item.description = nls.localize('defaultInputValue', "Default");
picks.unshift(item);
} else {
picks.push(item);
}
});
}
let pickOptions: IPickOptions<IQuickPickItem> = { placeHolder: input.description };
return this.quickInputService.pick(picks, pickOptions, undefined).then(resolvedInput => {
return resolvedInput ? resolvedInput.label : input.default;
});
}
}
return Promise.resolve(undefined);
}
/**
* Finds all variables in object using cmdVar and pushes them into commands.
* @param cmdVar Regex to use for finding variables.
* @param object object is searched for variables.
* @param commands All found variables are returned in commands.
*/
private findVariables(cmdVar: RegExp, object: any, commands: string[]) {
if (!object) {
return;
} else if (typeof object === 'string') {
let matches;
while ((matches = cmdVar.exec(object)) !== null) {
if (matches.length === 2) {
const command = matches[1];
if (commands.indexOf(command) < 0) {
commands.push(command);
}
}
}
} else if (Types.isArray(object)) {
object.forEach(value => {
this.findVariables(cmdVar, value, commands);
});
} else {
Object.keys(object).forEach(key => {
const value = object[key];
this.findVariables(cmdVar, value, commands);
});
}
}
/**
* Converts an array of inputs into an actaul array of typed, ConfiguredInputs.
* @param object Array of something that should look like inputs.
*/
private parseConfigurationInputs(object: any[]): ConfiguredInput[] | undefined {
let inputs = new Array<ConfiguredInput>();
if (object) {
object.forEach(item => {
if (Types.isString(item.id) && Types.isString(item.description) && Types.isString(item.type)) {
let type: ConfiguredInputType;
switch (item.type) {
case 'prompt': type = ConfiguredInputType.Prompt; break;
case 'pick': type = ConfiguredInputType.Pick; break;
default: {
throw new Error(nls.localize('unknownInputTypeProvided', "Input '{0}' can only be of type 'prompt' or 'pick'.", item.id));
}
}
let options: string[];
if (type === ConfiguredInputType.Pick) {
if (Types.isStringArray(item.options)) {
options = item.options;
} else {
throw new Error(nls.localize('pickRequiresOptions', "Input '{0}' is of type 'pick' and must include 'options'.", item.id));
}
}
inputs.push({ id: item.id, description: item.description, type, default: item.default, options });
}
});
}
return inputs;
}
} | src/vs/workbench/services/configurationResolver/electron-browser/configurationResolverService.ts | 1 | https://github.com/microsoft/vscode/commit/51ef43a02382fb972b15d5b935515b69bb637a3a | [
0.9989998936653137,
0.17176176607608795,
0.00016608991427347064,
0.0001979074440896511,
0.3680991232395172
] |
{
"id": 2,
"code_window": [
"\t */\n",
"\tprivate showUserInput(commandVariable: string, inputs: Map<string, ConfiguredInput>): Promise<string> {\n",
"\t\tif (inputs && inputs.has(commandVariable)) {\n",
"\t\t\tconst input = inputs.get(commandVariable);\n",
"\t\t\tif (input.type === ConfiguredInputType.Prompt) {\n",
"\t\t\t\tlet inputOptions: IInputOptions = { prompt: input.description };\n",
"\t\t\t\tif (input.default) {\n",
"\t\t\t\t\tinputOptions.value = input.default;\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\tif (input.type === ConfiguredInputType.PromptString) {\n"
],
"file_path": "src/vs/workbench/services/configurationResolver/electron-browser/configurationResolverService.ts",
"type": "replace",
"edit_start_line_idx": 236
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
interface NodeRequire {
toUrl(path: string): string;
(dependencies: string[], callback: (...args: any[]) => any, errorback?: (err: any) => void): any;
config(data: any): any;
}
declare var require: NodeRequire; | src/typings/require-monaco.d.ts | 0 | https://github.com/microsoft/vscode/commit/51ef43a02382fb972b15d5b935515b69bb637a3a | [
0.00017413489695172757,
0.00016974794561974704,
0.0001653609797358513,
0.00016974794561974704,
0.000004386958607938141
] |
{
"id": 2,
"code_window": [
"\t */\n",
"\tprivate showUserInput(commandVariable: string, inputs: Map<string, ConfiguredInput>): Promise<string> {\n",
"\t\tif (inputs && inputs.has(commandVariable)) {\n",
"\t\t\tconst input = inputs.get(commandVariable);\n",
"\t\t\tif (input.type === ConfiguredInputType.Prompt) {\n",
"\t\t\t\tlet inputOptions: IInputOptions = { prompt: input.description };\n",
"\t\t\t\tif (input.default) {\n",
"\t\t\t\t\tinputOptions.value = input.default;\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\tif (input.type === ConfiguredInputType.PromptString) {\n"
],
"file_path": "src/vs/workbench/services/configurationResolver/electron-browser/configurationResolverService.ts",
"type": "replace",
"edit_start_line_idx": 236
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { mergeSort } from 'vs/base/common/arrays';
import { CancellationToken } from 'vs/base/common/cancellation';
import { illegalArgument, onUnexpectedExternalError } from 'vs/base/common/errors';
import { URI } from 'vs/base/common/uri';
import { registerLanguageCommand } from 'vs/editor/browser/editorExtensions';
import { ITextModel } from 'vs/editor/common/model';
import { CodeLensProvider, CodeLensProviderRegistry, ICodeLensSymbol } from 'vs/editor/common/modes';
import { IModelService } from 'vs/editor/common/services/modelService';
export interface ICodeLensData {
symbol: ICodeLensSymbol;
provider: CodeLensProvider;
}
export function getCodeLensData(model: ITextModel, token: CancellationToken): Promise<ICodeLensData[]> {
const symbols: ICodeLensData[] = [];
const provider = CodeLensProviderRegistry.ordered(model);
const promises = provider.map(provider => Promise.resolve(provider.provideCodeLenses(model, token)).then(result => {
if (Array.isArray(result)) {
for (let symbol of result) {
symbols.push({ symbol, provider });
}
}
}).catch(onUnexpectedExternalError));
return Promise.all(promises).then(() => {
return mergeSort(symbols, (a, b) => {
// sort by lineNumber, provider-rank, and column
if (a.symbol.range.startLineNumber < b.symbol.range.startLineNumber) {
return -1;
} else if (a.symbol.range.startLineNumber > b.symbol.range.startLineNumber) {
return 1;
} else if (provider.indexOf(a.provider) < provider.indexOf(b.provider)) {
return -1;
} else if (provider.indexOf(a.provider) > provider.indexOf(b.provider)) {
return 1;
} else if (a.symbol.range.startColumn < b.symbol.range.startColumn) {
return -1;
} else if (a.symbol.range.startColumn > b.symbol.range.startColumn) {
return 1;
} else {
return 0;
}
});
});
}
registerLanguageCommand('_executeCodeLensProvider', function (accessor, args) {
let { resource, itemResolveCount } = args;
if (!(resource instanceof URI)) {
throw illegalArgument();
}
const model = accessor.get(IModelService).getModel(resource);
if (!model) {
throw illegalArgument();
}
const result: ICodeLensSymbol[] = [];
return getCodeLensData(model, CancellationToken.None).then(value => {
let resolve: Thenable<any>[] = [];
for (const item of value) {
if (typeof itemResolveCount === 'undefined' || Boolean(item.symbol.command)) {
result.push(item.symbol);
} else if (itemResolveCount-- > 0 && item.provider.resolveCodeLens) {
resolve.push(Promise.resolve(item.provider.resolveCodeLens(model, item.symbol, CancellationToken.None)).then(symbol => result.push(symbol || item.symbol)));
}
}
return Promise.all(resolve);
}).then(() => {
return result;
});
});
| src/vs/editor/contrib/codelens/codelens.ts | 0 | https://github.com/microsoft/vscode/commit/51ef43a02382fb972b15d5b935515b69bb637a3a | [
0.00017607382324058563,
0.0001725934853311628,
0.00016824335034471005,
0.00017340188787784427,
0.0000026882855763687985
] |
{
"id": 2,
"code_window": [
"\t */\n",
"\tprivate showUserInput(commandVariable: string, inputs: Map<string, ConfiguredInput>): Promise<string> {\n",
"\t\tif (inputs && inputs.has(commandVariable)) {\n",
"\t\t\tconst input = inputs.get(commandVariable);\n",
"\t\t\tif (input.type === ConfiguredInputType.Prompt) {\n",
"\t\t\t\tlet inputOptions: IInputOptions = { prompt: input.description };\n",
"\t\t\t\tif (input.default) {\n",
"\t\t\t\t\tinputOptions.value = input.default;\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\tif (input.type === ConfiguredInputType.PromptString) {\n"
],
"file_path": "src/vs/workbench/services/configurationResolver/electron-browser/configurationResolverService.ts",
"type": "replace",
"edit_start_line_idx": 236
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as assert from 'assert';
import { Range } from 'vs/editor/common/core/range';
import { DefaultEndOfLine } from 'vs/editor/common/model';
import { IValidatedEditOperation, PieceTreeTextBuffer } from 'vs/editor/common/model/pieceTreeTextBuffer/pieceTreeTextBuffer';
import { createTextBufferFactory } from 'vs/editor/common/model/textModel';
suite('PieceTreeTextBuffer._getInverseEdits', () => {
function editOp(startLineNumber: number, startColumn: number, endLineNumber: number, endColumn: number, text: string[]): IValidatedEditOperation {
return {
sortIndex: 0,
identifier: null,
range: new Range(startLineNumber, startColumn, endLineNumber, endColumn),
rangeOffset: 0,
rangeLength: 0,
lines: text,
forceMoveMarkers: false,
isAutoWhitespaceEdit: false
};
}
function inverseEditOp(startLineNumber: number, startColumn: number, endLineNumber: number, endColumn: number): Range {
return new Range(startLineNumber, startColumn, endLineNumber, endColumn);
}
function assertInverseEdits(ops: IValidatedEditOperation[], expected: Range[]): void {
let actual = PieceTreeTextBuffer._getInverseEditRanges(ops);
assert.deepEqual(actual, expected);
}
test('single insert', () => {
assertInverseEdits(
[
editOp(1, 1, 1, 1, ['hello'])
],
[
inverseEditOp(1, 1, 1, 6)
]
);
});
test('Bug 19872: Undo is funky', () => {
assertInverseEdits(
[
editOp(2, 1, 2, 2, ['']),
editOp(3, 1, 4, 2, [''])
],
[
inverseEditOp(2, 1, 2, 1),
inverseEditOp(3, 1, 3, 1)
]
);
});
test('two single unrelated inserts', () => {
assertInverseEdits(
[
editOp(1, 1, 1, 1, ['hello']),
editOp(2, 1, 2, 1, ['world'])
],
[
inverseEditOp(1, 1, 1, 6),
inverseEditOp(2, 1, 2, 6)
]
);
});
test('two single inserts 1', () => {
assertInverseEdits(
[
editOp(1, 1, 1, 1, ['hello']),
editOp(1, 2, 1, 2, ['world'])
],
[
inverseEditOp(1, 1, 1, 6),
inverseEditOp(1, 7, 1, 12)
]
);
});
test('two single inserts 2', () => {
assertInverseEdits(
[
editOp(1, 1, 1, 1, ['hello']),
editOp(1, 4, 1, 4, ['world'])
],
[
inverseEditOp(1, 1, 1, 6),
inverseEditOp(1, 9, 1, 14)
]
);
});
test('multiline insert', () => {
assertInverseEdits(
[
editOp(1, 1, 1, 1, ['hello', 'world'])
],
[
inverseEditOp(1, 1, 2, 6)
]
);
});
test('two unrelated multiline inserts', () => {
assertInverseEdits(
[
editOp(1, 1, 1, 1, ['hello', 'world']),
editOp(2, 1, 2, 1, ['how', 'are', 'you?']),
],
[
inverseEditOp(1, 1, 2, 6),
inverseEditOp(3, 1, 5, 5),
]
);
});
test('two multiline inserts 1', () => {
assertInverseEdits(
[
editOp(1, 1, 1, 1, ['hello', 'world']),
editOp(1, 2, 1, 2, ['how', 'are', 'you?']),
],
[
inverseEditOp(1, 1, 2, 6),
inverseEditOp(2, 7, 4, 5),
]
);
});
test('single delete', () => {
assertInverseEdits(
[
editOp(1, 1, 1, 6, null)
],
[
inverseEditOp(1, 1, 1, 1)
]
);
});
test('two single unrelated deletes', () => {
assertInverseEdits(
[
editOp(1, 1, 1, 6, null),
editOp(2, 1, 2, 6, null)
],
[
inverseEditOp(1, 1, 1, 1),
inverseEditOp(2, 1, 2, 1)
]
);
});
test('two single deletes 1', () => {
assertInverseEdits(
[
editOp(1, 1, 1, 6, null),
editOp(1, 7, 1, 12, null)
],
[
inverseEditOp(1, 1, 1, 1),
inverseEditOp(1, 2, 1, 2)
]
);
});
test('two single deletes 2', () => {
assertInverseEdits(
[
editOp(1, 1, 1, 6, null),
editOp(1, 9, 1, 14, null)
],
[
inverseEditOp(1, 1, 1, 1),
inverseEditOp(1, 4, 1, 4)
]
);
});
test('multiline delete', () => {
assertInverseEdits(
[
editOp(1, 1, 2, 6, null)
],
[
inverseEditOp(1, 1, 1, 1)
]
);
});
test('two unrelated multiline deletes', () => {
assertInverseEdits(
[
editOp(1, 1, 2, 6, null),
editOp(3, 1, 5, 5, null),
],
[
inverseEditOp(1, 1, 1, 1),
inverseEditOp(2, 1, 2, 1),
]
);
});
test('two multiline deletes 1', () => {
assertInverseEdits(
[
editOp(1, 1, 2, 6, null),
editOp(2, 7, 4, 5, null),
],
[
inverseEditOp(1, 1, 1, 1),
inverseEditOp(1, 2, 1, 2),
]
);
});
test('single replace', () => {
assertInverseEdits(
[
editOp(1, 1, 1, 6, ['Hello world'])
],
[
inverseEditOp(1, 1, 1, 12)
]
);
});
test('two replaces', () => {
assertInverseEdits(
[
editOp(1, 1, 1, 6, ['Hello world']),
editOp(1, 7, 1, 8, ['How are you?']),
],
[
inverseEditOp(1, 1, 1, 12),
inverseEditOp(1, 13, 1, 25)
]
);
});
test('many edits', () => {
assertInverseEdits(
[
editOp(1, 2, 1, 2, ['', ' ']),
editOp(1, 5, 1, 6, ['']),
editOp(1, 9, 1, 9, ['', ''])
],
[
inverseEditOp(1, 2, 2, 3),
inverseEditOp(2, 6, 2, 6),
inverseEditOp(2, 9, 3, 1)
]
);
});
});
suite('PieceTreeTextBuffer._toSingleEditOperation', () => {
function editOp(startLineNumber: number, startColumn: number, endLineNumber: number, endColumn: number, rangeOffset: number, rangeLength: number, text: string[]): IValidatedEditOperation {
return {
sortIndex: 0,
identifier: null,
range: new Range(startLineNumber, startColumn, endLineNumber, endColumn),
rangeOffset: rangeOffset,
rangeLength: rangeLength,
lines: text,
forceMoveMarkers: false,
isAutoWhitespaceEdit: false
};
}
function testToSingleEditOperation(original: string[], edits: IValidatedEditOperation[], expected: IValidatedEditOperation): void {
const textBuffer = <PieceTreeTextBuffer>createTextBufferFactory(original.join('\n')).create(DefaultEndOfLine.LF);
const actual = textBuffer._toSingleEditOperation(edits);
assert.deepEqual(actual, expected);
}
test('one edit op is unchanged', () => {
testToSingleEditOperation(
[
'My First Line',
'\t\tMy Second Line',
' Third Line',
'',
'1'
],
[
editOp(1, 3, 1, 3, 2, 0, [' new line', 'No longer'])
],
editOp(1, 3, 1, 3, 2, 0, [' new line', 'No longer'])
);
});
test('two edits on one line', () => {
testToSingleEditOperation([
'My First Line',
'\t\tMy Second Line',
' Third Line',
'',
'1'
], [
editOp(1, 1, 1, 3, 0, 2, ['Your']),
editOp(1, 4, 1, 4, 3, 0, ['Interesting ']),
editOp(2, 3, 2, 6, 16, 3, null)
],
editOp(1, 1, 2, 6, 0, 19, [
'Your Interesting First Line',
'\t\t'
]));
});
test('insert multiple newlines', () => {
testToSingleEditOperation(
[
'My First Line',
'\t\tMy Second Line',
' Third Line',
'',
'1'
],
[
editOp(1, 3, 1, 3, 2, 0, ['', '', '', '', '']),
editOp(3, 15, 3, 15, 45, 0, ['a', 'b'])
],
editOp(1, 3, 3, 15, 2, 43, [
'',
'',
'',
'',
' First Line',
'\t\tMy Second Line',
' Third Linea',
'b'
])
);
});
test('delete empty text', () => {
testToSingleEditOperation(
[
'My First Line',
'\t\tMy Second Line',
' Third Line',
'',
'1'
],
[
editOp(1, 1, 1, 1, 0, 0, [''])
],
editOp(1, 1, 1, 1, 0, 0, [''])
);
});
test('two unrelated edits', () => {
testToSingleEditOperation(
[
'My First Line',
'\t\tMy Second Line',
' Third Line',
'',
'123'
],
[
editOp(2, 1, 2, 3, 14, 2, ['\t']),
editOp(3, 1, 3, 5, 31, 4, [''])
],
editOp(2, 1, 3, 5, 14, 21, ['\tMy Second Line', ''])
);
});
test('many edits', () => {
testToSingleEditOperation(
[
'{"x" : 1}'
],
[
editOp(1, 2, 1, 2, 1, 0, ['\n ']),
editOp(1, 5, 1, 6, 4, 1, ['']),
editOp(1, 9, 1, 9, 8, 0, ['\n'])
],
editOp(1, 2, 1, 9, 1, 7, [
'',
' "x": 1',
''
])
);
});
test('many edits reversed', () => {
testToSingleEditOperation(
[
'{',
' "x": 1',
'}'
],
[
editOp(1, 2, 2, 3, 1, 3, ['']),
editOp(2, 6, 2, 6, 7, 0, [' ']),
editOp(2, 9, 3, 1, 10, 1, [''])
],
editOp(1, 2, 3, 1, 1, 10, ['"x" : 1'])
);
});
test('replacing newlines 1', () => {
testToSingleEditOperation(
[
'{',
'"a": true,',
'',
'"b": true',
'}'
],
[
editOp(1, 2, 2, 1, 1, 1, ['', '\t']),
editOp(2, 11, 4, 1, 12, 2, ['', '\t'])
],
editOp(1, 2, 4, 1, 1, 13, [
'',
'\t"a": true,',
'\t'
])
);
});
test('replacing newlines 2', () => {
testToSingleEditOperation(
[
'some text',
'some more text',
'now comes an empty line',
'',
'after empty line',
'and the last line'
],
[
editOp(1, 5, 3, 1, 4, 21, [' text', 'some more text', 'some more text']),
editOp(3, 2, 4, 1, 26, 23, ['o more lines', 'asd', 'asd', 'asd']),
editOp(5, 1, 5, 6, 50, 5, ['zzzzzzzz']),
editOp(5, 11, 6, 16, 60, 22, ['1', '2', '3', '4'])
],
editOp(1, 5, 6, 16, 4, 78, [
' text',
'some more text',
'some more textno more lines',
'asd',
'asd',
'asd',
'zzzzzzzz empt1',
'2',
'3',
'4'
])
);
});
test('advanced', () => {
testToSingleEditOperation(
[
' { "d": [',
' null',
' ] /*comment*/',
' ,"e": /*comment*/ [null] }',
],
[
editOp(1, 1, 1, 2, 0, 1, ['']),
editOp(1, 3, 1, 10, 2, 7, ['', ' ']),
editOp(1, 16, 2, 14, 15, 14, ['', ' ']),
editOp(2, 18, 3, 9, 33, 9, ['', ' ']),
editOp(3, 22, 4, 9, 55, 9, ['']),
editOp(4, 10, 4, 10, 65, 0, ['', ' ']),
editOp(4, 28, 4, 28, 83, 0, ['', ' ']),
editOp(4, 32, 4, 32, 87, 0, ['', ' ']),
editOp(4, 33, 4, 34, 88, 1, ['', ''])
],
editOp(1, 1, 4, 34, 0, 89, [
'{',
' "d": [',
' null',
' ] /*comment*/,',
' "e": /*comment*/ [',
' null',
' ]',
''
])
);
});
test('advanced simplified', () => {
testToSingleEditOperation(
[
' abc',
' ,def'
],
[
editOp(1, 1, 1, 4, 0, 3, ['']),
editOp(1, 7, 2, 2, 6, 2, ['']),
editOp(2, 3, 2, 3, 9, 0, ['', ''])
],
editOp(1, 1, 2, 3, 0, 9, [
'abc,',
''
])
);
});
});
| src/vs/editor/test/common/model/linesTextBuffer/linesTextBuffer.test.ts | 0 | https://github.com/microsoft/vscode/commit/51ef43a02382fb972b15d5b935515b69bb637a3a | [
0.00017559649131726474,
0.0001731513621052727,
0.00016766824410296977,
0.0001735930418362841,
0.0000016115145626827143
] |
{
"id": 3,
"code_window": [
"\t\t\t\tif (Types.isString(item.id) && Types.isString(item.description) && Types.isString(item.type)) {\n",
"\t\t\t\t\tlet type: ConfiguredInputType;\n",
"\t\t\t\t\tswitch (item.type) {\n",
"\t\t\t\t\t\tcase 'prompt': type = ConfiguredInputType.Prompt; break;\n",
"\t\t\t\t\t\tcase 'pick': type = ConfiguredInputType.Pick; break;\n",
"\t\t\t\t\t\tdefault: {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"keep"
],
"after_edit": [
"\t\t\t\t\t\tcase 'promptString': type = ConfiguredInputType.PromptString; break;\n",
"\t\t\t\t\t\tcase 'pickString': type = ConfiguredInputType.PickString; break;\n"
],
"file_path": "src/vs/workbench/services/configurationResolver/electron-browser/configurationResolverService.ts",
"type": "replace",
"edit_start_line_idx": 309
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as nls from 'vs/nls';
import { IJSONSchema } from 'vs/base/common/jsonSchema';
export const inputsSchema: IJSONSchema = {
definitions: {
inputs: {
type: 'array',
description: nls.localize('JsonSchema.inputs', 'User inputs. Used for prompting for user input.'),
items: {
type: 'object',
required: ['id', 'type', 'description'],
additionalProperties: false,
properties: {
id: {
type: 'string',
description: nls.localize('JsonSchema.input.id', "The input\'s id")
},
type: {
type: 'string',
description: nls.localize('JsonSchema.input.type', 'The input\'s type. Use prompt for free string input and selection for choosing from values'),
enum: ['prompt', 'pick']
},
description: {
type: 'string',
description: nls.localize('JsonSchema.input.description', 'Description to show for for using input.'),
},
default: {
type: 'string',
description: nls.localize('JsonSchema.input.default', 'Default value for the input.'),
},
options: {
type: 'array',
description: nls.localize('JsonSchema.input.options', 'Options to select from.'),
items: {
type: 'string'
}
}
}
}
}
}
};
| src/vs/workbench/services/configurationResolver/common/configurationResolverSchema.ts | 1 | https://github.com/microsoft/vscode/commit/51ef43a02382fb972b15d5b935515b69bb637a3a | [
0.00017598435806576163,
0.00016818600124679506,
0.0001651463535381481,
0.00016595647321082652,
0.000004083834483026294
] |
{
"id": 3,
"code_window": [
"\t\t\t\tif (Types.isString(item.id) && Types.isString(item.description) && Types.isString(item.type)) {\n",
"\t\t\t\t\tlet type: ConfiguredInputType;\n",
"\t\t\t\t\tswitch (item.type) {\n",
"\t\t\t\t\t\tcase 'prompt': type = ConfiguredInputType.Prompt; break;\n",
"\t\t\t\t\t\tcase 'pick': type = ConfiguredInputType.Pick; break;\n",
"\t\t\t\t\t\tdefault: {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"keep"
],
"after_edit": [
"\t\t\t\t\t\tcase 'promptString': type = ConfiguredInputType.PromptString; break;\n",
"\t\t\t\t\t\tcase 'pickString': type = ConfiguredInputType.PickString; break;\n"
],
"file_path": "src/vs/workbench/services/configurationResolver/electron-browser/configurationResolverService.ts",
"type": "replace",
"edit_start_line_idx": 309
} | <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><style>.icon-canvas-transparent{opacity:0;fill:#f6f6f6}.icon-vs-out{fill:#f6f6f6}.icon-vs-bg{fill:#424242}.icon-vs-fg{fill:#f0eff1}</style><path class="icon-canvas-transparent" d="M16 16H0V0h16v16z" id="canvas"/><path class="icon-vs-out" d="M16 5V2H9V1H0v14h13v-3h3V9h-1V6H9V5h7zm-8 7V9h1v3H8z" id="outline"/><path class="icon-vs-fg" d="M2 3h5v1H2V3z" id="iconFg"/><g id="iconBg"><path class="icon-vs-bg" d="M15 4h-5V3h5v1zm-1 3h-2v1h2V7zm-4 0H1v1h9V7zm2 6H1v1h11v-1zm-5-3H1v1h6v-1zm8 0h-5v1h5v-1zM8 2v3H1V2h7zM7 3H2v1h5V3z"/></g></svg> | src/vs/editor/contrib/documentSymbols/media/IntelliSenseKeyword_16x.svg | 0 | https://github.com/microsoft/vscode/commit/51ef43a02382fb972b15d5b935515b69bb637a3a | [
0.0001643254654482007,
0.0001643254654482007,
0.0001643254654482007,
0.0001643254654482007,
0
] |
{
"id": 3,
"code_window": [
"\t\t\t\tif (Types.isString(item.id) && Types.isString(item.description) && Types.isString(item.type)) {\n",
"\t\t\t\t\tlet type: ConfiguredInputType;\n",
"\t\t\t\t\tswitch (item.type) {\n",
"\t\t\t\t\t\tcase 'prompt': type = ConfiguredInputType.Prompt; break;\n",
"\t\t\t\t\t\tcase 'pick': type = ConfiguredInputType.Pick; break;\n",
"\t\t\t\t\t\tdefault: {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"keep"
],
"after_edit": [
"\t\t\t\t\t\tcase 'promptString': type = ConfiguredInputType.PromptString; break;\n",
"\t\t\t\t\t\tcase 'pickString': type = ConfiguredInputType.PickString; break;\n"
],
"file_path": "src/vs/workbench/services/configurationResolver/electron-browser/configurationResolverService.ts",
"type": "replace",
"edit_start_line_idx": 309
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define([], function() {
return {
load: function(name, req, load) {
load({});
}
};
});
| test/css.mock.js | 0 | https://github.com/microsoft/vscode/commit/51ef43a02382fb972b15d5b935515b69bb637a3a | [
0.0001736495760269463,
0.00017313173157162964,
0.00017261387256439775,
0.00017313173157162964,
5.17851731274277e-7
] |
{
"id": 3,
"code_window": [
"\t\t\t\tif (Types.isString(item.id) && Types.isString(item.description) && Types.isString(item.type)) {\n",
"\t\t\t\t\tlet type: ConfiguredInputType;\n",
"\t\t\t\t\tswitch (item.type) {\n",
"\t\t\t\t\t\tcase 'prompt': type = ConfiguredInputType.Prompt; break;\n",
"\t\t\t\t\t\tcase 'pick': type = ConfiguredInputType.Pick; break;\n",
"\t\t\t\t\t\tdefault: {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"keep"
],
"after_edit": [
"\t\t\t\t\t\tcase 'promptString': type = ConfiguredInputType.PromptString; break;\n",
"\t\t\t\t\t\tcase 'pickString': type = ConfiguredInputType.PickString; break;\n"
],
"file_path": "src/vs/workbench/services/configurationResolver/electron-browser/configurationResolverService.ts",
"type": "replace",
"edit_start_line_idx": 309
} | <svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M7.065 13H15v2H2.056v-2h5.009zm3.661-12H7.385L8.44 2.061 7.505 3H15V1h-4.274zM3.237 9H2.056v2H15V9H3.237zm4.208-4l.995 1-.995 1H15V5H7.445z" fill="#424242"/><path d="M5.072 4.03L7.032 6 5.978 7.061l-1.96-1.97-1.961 1.97L1 6l1.96-1.97L1 2.061 2.056 1l1.96 1.97L5.977 1l1.057 1.061L5.072 4.03z" fill="#A1260D"/></svg> | src/vs/workbench/parts/preferences/browser/media/clear.svg | 0 | https://github.com/microsoft/vscode/commit/51ef43a02382fb972b15d5b935515b69bb637a3a | [
0.00017088482854887843,
0.00017088482854887843,
0.00017088482854887843,
0.00017088482854887843,
0
] |
{
"id": 4,
"code_window": [
"\t\t\t\t\t\tdefault: {\n",
"\t\t\t\t\t\t\tthrow new Error(nls.localize('unknownInputTypeProvided', \"Input '{0}' can only be of type 'prompt' or 'pick'.\", item.id));\n",
"\t\t\t\t\t\t}\n",
"\t\t\t\t\t}\n",
"\t\t\t\t\tlet options: string[];\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t\t\t\t\tthrow new Error(nls.localize('unknownInputTypeProvided', \"Input '{0}' can only be of type 'promptString' or 'pickString'.\", item.id));\n"
],
"file_path": "src/vs/workbench/services/configurationResolver/electron-browser/configurationResolverService.ts",
"type": "replace",
"edit_start_line_idx": 312
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { URI as uri } from 'vs/base/common/uri';
import * as nls from 'vs/nls';
import * as paths from 'vs/base/common/paths';
import * as platform from 'vs/base/common/platform';
import * as Objects from 'vs/base/common/objects';
import * as Types from 'vs/base/common/types';
import { Schemas } from 'vs/base/common/network';
import { TPromise } from 'vs/base/common/winjs.base';
import { sequence } from 'vs/base/common/async';
import { toResource } from 'vs/workbench/common/editor';
import { IStringDictionary, forEach, fromMap } from 'vs/base/common/collections';
import { IEnvironmentService } from 'vs/platform/environment/common/environment';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { ICommandService } from 'vs/platform/commands/common/commands';
import { IWorkspaceFolder, IWorkspaceContextService, WorkbenchState } from 'vs/platform/workspace/common/workspace';
import { IEditorService } from 'vs/workbench/services/editor/common/editorService';
import { AbstractVariableResolverService } from 'vs/workbench/services/configurationResolver/node/variableResolver';
import { isCodeEditor } from 'vs/editor/browser/editorBrowser';
import { DiffEditorInput } from 'vs/workbench/common/editor/diffEditorInput';
import { IQuickInputService, IInputOptions, IQuickPickItem, IPickOptions } from 'vs/platform/quickinput/common/quickInput';
import { ConfiguredInput, ConfiguredInputType } from 'vs/workbench/services/configurationResolver/common/configurationResolver';
export class ConfigurationResolverService extends AbstractVariableResolverService {
constructor(
envVariables: platform.IProcessEnvironment,
@IEditorService editorService: IEditorService,
@IEnvironmentService environmentService: IEnvironmentService,
@IConfigurationService private configurationService: IConfigurationService,
@ICommandService private commandService: ICommandService,
@IWorkspaceContextService private workspaceContextService: IWorkspaceContextService,
@IQuickInputService private quickInputService: IQuickInputService
) {
super({
getFolderUri: (folderName: string): uri => {
const folder = workspaceContextService.getWorkspace().folders.filter(f => f.name === folderName).pop();
return folder ? folder.uri : undefined;
},
getWorkspaceFolderCount: (): number => {
return workspaceContextService.getWorkspace().folders.length;
},
getConfigurationValue: (folderUri: uri, suffix: string) => {
return configurationService.getValue<string>(suffix, folderUri ? { resource: folderUri } : undefined);
},
getExecPath: () => {
return environmentService['execPath'];
},
getFilePath: (): string | undefined => {
let activeEditor = editorService.activeEditor;
if (activeEditor instanceof DiffEditorInput) {
activeEditor = activeEditor.modifiedInput;
}
const fileResource = toResource(activeEditor, { filter: Schemas.file });
if (!fileResource) {
return undefined;
}
return paths.normalize(fileResource.fsPath, true);
},
getSelectedText: (): string | undefined => {
const activeTextEditorWidget = editorService.activeTextEditorWidget;
if (isCodeEditor(activeTextEditorWidget)) {
const editorModel = activeTextEditorWidget.getModel();
const editorSelection = activeTextEditorWidget.getSelection();
if (editorModel && editorSelection) {
return editorModel.getValueInRange(editorSelection);
}
}
return undefined;
},
getLineNumber: (): string => {
const activeTextEditorWidget = editorService.activeTextEditorWidget;
if (isCodeEditor(activeTextEditorWidget)) {
const lineNumber = activeTextEditorWidget.getSelection().positionLineNumber;
return String(lineNumber);
}
return undefined;
}
}, envVariables);
}
public resolveWithInteractionReplace(folder: IWorkspaceFolder, config: any, section?: string, variables?: IStringDictionary<string>): TPromise<any> {
// resolve any non-interactive variables
config = this.resolveAny(folder, config);
// resolve input variables in the order in which they are encountered
return this.resolveWithInteraction(folder, config, section, variables).then(mapping => {
// finally substitute evaluated command variables (if there are any)
if (mapping.size > 0) {
return this.resolveAny(folder, config, fromMap(mapping));
} else {
return config;
}
});
}
public resolveWithInteraction(folder: IWorkspaceFolder, config: any, section?: string, variables?: IStringDictionary<string>): TPromise<Map<string, string>> {
// resolve any non-interactive variables
const resolved = this.resolveAnyMap(folder, config);
config = resolved.newConfig;
const allVariableMapping: Map<string, string> = resolved.resolvedVariables;
// resolve input variables in the order in which they are encountered
return this.resolveWithInputs(folder, config, section).then(inputMapping => {
if (!this.updateMapping(inputMapping, allVariableMapping)) {
return undefined;
}
// resolve commands in the order in which they are encountered
return this.resolveWithCommands(config, variables).then(commandMapping => {
if (!this.updateMapping(commandMapping, allVariableMapping)) {
return undefined;
}
return allVariableMapping;
});
});
}
/**
* Add all items from newMapping to fullMapping. Returns false if newMapping is undefined.
*/
private updateMapping(newMapping: IStringDictionary<string>, fullMapping: Map<string, string>): boolean {
if (!newMapping) {
return false;
}
forEach(newMapping, (entry) => {
fullMapping.set(entry.key, entry.value);
});
return true;
}
/**
* Finds and executes all command variables in the given configuration and returns their values as a dictionary.
* Please note: this method does not substitute the command variables (so the configuration is not modified).
* The returned dictionary can be passed to "resolvePlatform" for the substitution.
* See #6569.
* @param configuration
* @param variableToCommandMap Aliases for commands
*/
private resolveWithCommands(configuration: any, variableToCommandMap: IStringDictionary<string>): TPromise<IStringDictionary<string>> {
if (!configuration) {
return TPromise.as(undefined);
}
// use an array to preserve order of first appearance
const cmd_var = /\${command:(.*?)}/g;
const commands: string[] = [];
this.findVariables(cmd_var, configuration, commands);
let cancelled = false;
const commandValueMapping: IStringDictionary<string> = Object.create(null);
const factory: { (): TPromise<any> }[] = commands.map(commandVariable => {
return () => {
let commandId = variableToCommandMap ? variableToCommandMap[commandVariable] : undefined;
if (!commandId) {
// Just launch any command if the interactive variable is not contributed by the adapter #12735
commandId = commandVariable;
}
return this.commandService.executeCommand<string>(commandId, configuration).then(result => {
if (typeof result === 'string') {
commandValueMapping['command:' + commandVariable] = result;
} else if (Types.isUndefinedOrNull(result)) {
cancelled = true;
} else {
throw new Error(nls.localize('stringsOnlySupported', "Command '{0}' did not return a string result. Only strings are supported as results for commands used for variable substitution.", commandVariable));
}
});
};
});
return sequence(factory).then(() => cancelled ? undefined : commandValueMapping);
}
/**
* Resolves all inputs in a configuration and returns a map that maps the unresolved input to the resolved input.
* Does not do replacement of inputs.
* @param folder
* @param config
* @param section
*/
public resolveWithInputs(folder: IWorkspaceFolder, config: any, section: string): Promise<IStringDictionary<string>> {
if (!config) {
return Promise.resolve(undefined);
} else if (folder && section) {
// Get all the possible inputs
let result = this.workspaceContextService.getWorkbenchState() !== WorkbenchState.EMPTY
? Objects.deepClone(this.configurationService.getValue<any>(section, { resource: folder.uri }))
: undefined;
let inputsArray = result ? this.parseConfigurationInputs(result.inputs) : undefined;
const inputs = new Map<string, ConfiguredInput>();
if (inputsArray) {
inputsArray.forEach(input => {
inputs.set(input.id, input);
});
// use an array to preserve order of first appearance
const input_var = /\${input:(.*?)}/g;
const commands: string[] = [];
this.findVariables(input_var, config, commands);
let cancelled = false;
const commandValueMapping: IStringDictionary<string> = Object.create(null);
const factory: { (): Promise<any> }[] = commands.map(commandVariable => {
return () => {
return this.showUserInput(commandVariable, inputs).then(resolvedValue => {
if (resolvedValue) {
commandValueMapping['input:' + commandVariable] = resolvedValue;
}
});
};
}, reason => {
return Promise.reject(reason);
});
return sequence(factory).then(() => cancelled ? undefined : commandValueMapping);
}
}
return Promise.resolve(Object.create(null));
}
/**
* Takes the provided input info and shows the quick pick so the user can provide the value for the input
* @param commandVariable Name of the input.
* @param inputs Information about each possible input.
* @param commandValueMapping
*/
private showUserInput(commandVariable: string, inputs: Map<string, ConfiguredInput>): Promise<string> {
if (inputs && inputs.has(commandVariable)) {
const input = inputs.get(commandVariable);
if (input.type === ConfiguredInputType.Prompt) {
let inputOptions: IInputOptions = { prompt: input.description };
if (input.default) {
inputOptions.value = input.default;
}
return this.quickInputService.input(inputOptions).then(resolvedInput => {
return resolvedInput ? resolvedInput : input.default;
});
} else { // input.type === ConfiguredInputType.pick
let picks = new Array<IQuickPickItem>();
if (input.options) {
input.options.forEach(pickOption => {
let item: IQuickPickItem = { label: pickOption };
if (input.default && (pickOption === input.default)) {
item.description = nls.localize('defaultInputValue', "Default");
picks.unshift(item);
} else {
picks.push(item);
}
});
}
let pickOptions: IPickOptions<IQuickPickItem> = { placeHolder: input.description };
return this.quickInputService.pick(picks, pickOptions, undefined).then(resolvedInput => {
return resolvedInput ? resolvedInput.label : input.default;
});
}
}
return Promise.resolve(undefined);
}
/**
* Finds all variables in object using cmdVar and pushes them into commands.
* @param cmdVar Regex to use for finding variables.
* @param object object is searched for variables.
* @param commands All found variables are returned in commands.
*/
private findVariables(cmdVar: RegExp, object: any, commands: string[]) {
if (!object) {
return;
} else if (typeof object === 'string') {
let matches;
while ((matches = cmdVar.exec(object)) !== null) {
if (matches.length === 2) {
const command = matches[1];
if (commands.indexOf(command) < 0) {
commands.push(command);
}
}
}
} else if (Types.isArray(object)) {
object.forEach(value => {
this.findVariables(cmdVar, value, commands);
});
} else {
Object.keys(object).forEach(key => {
const value = object[key];
this.findVariables(cmdVar, value, commands);
});
}
}
/**
* Converts an array of inputs into an actaul array of typed, ConfiguredInputs.
* @param object Array of something that should look like inputs.
*/
private parseConfigurationInputs(object: any[]): ConfiguredInput[] | undefined {
let inputs = new Array<ConfiguredInput>();
if (object) {
object.forEach(item => {
if (Types.isString(item.id) && Types.isString(item.description) && Types.isString(item.type)) {
let type: ConfiguredInputType;
switch (item.type) {
case 'prompt': type = ConfiguredInputType.Prompt; break;
case 'pick': type = ConfiguredInputType.Pick; break;
default: {
throw new Error(nls.localize('unknownInputTypeProvided', "Input '{0}' can only be of type 'prompt' or 'pick'.", item.id));
}
}
let options: string[];
if (type === ConfiguredInputType.Pick) {
if (Types.isStringArray(item.options)) {
options = item.options;
} else {
throw new Error(nls.localize('pickRequiresOptions', "Input '{0}' is of type 'pick' and must include 'options'.", item.id));
}
}
inputs.push({ id: item.id, description: item.description, type, default: item.default, options });
}
});
}
return inputs;
}
} | src/vs/workbench/services/configurationResolver/electron-browser/configurationResolverService.ts | 1 | https://github.com/microsoft/vscode/commit/51ef43a02382fb972b15d5b935515b69bb637a3a | [
0.9973043203353882,
0.08769736438989639,
0.00016418905579485,
0.00017455278430134058,
0.2807619869709015
] |
{
"id": 4,
"code_window": [
"\t\t\t\t\t\tdefault: {\n",
"\t\t\t\t\t\t\tthrow new Error(nls.localize('unknownInputTypeProvided', \"Input '{0}' can only be of type 'prompt' or 'pick'.\", item.id));\n",
"\t\t\t\t\t\t}\n",
"\t\t\t\t\t}\n",
"\t\t\t\t\tlet options: string[];\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t\t\t\t\tthrow new Error(nls.localize('unknownInputTypeProvided', \"Input '{0}' can only be of type 'promptString' or 'pickString'.\", item.id));\n"
],
"file_path": "src/vs/workbench/services/configurationResolver/electron-browser/configurationResolverService.ts",
"type": "replace",
"edit_start_line_idx": 312
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
.monaco-toolbar .toolbar-toggle-more {
display: inline-block;
padding: 0;
}
.vs .monaco-toolbar .action-label.toolbar-toggle-more {
background-image: url('ellipsis.svg');
}
.hc-black .monaco-toolbar .action-label.toolbar-toggle-more,
.vs-dark .monaco-toolbar .action-label.toolbar-toggle-more {
background-image: url('ellipsis-inverse.svg');
} | src/vs/base/browser/ui/toolbar/toolbar.css | 0 | https://github.com/microsoft/vscode/commit/51ef43a02382fb972b15d5b935515b69bb637a3a | [
0.00017568493785802275,
0.00017381025827489793,
0.00017193559324368834,
0.00017381025827489793,
0.0000018746723071672022
] |
{
"id": 4,
"code_window": [
"\t\t\t\t\t\tdefault: {\n",
"\t\t\t\t\t\t\tthrow new Error(nls.localize('unknownInputTypeProvided', \"Input '{0}' can only be of type 'prompt' or 'pick'.\", item.id));\n",
"\t\t\t\t\t\t}\n",
"\t\t\t\t\t}\n",
"\t\t\t\t\tlet options: string[];\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t\t\t\t\tthrow new Error(nls.localize('unknownInputTypeProvided', \"Input '{0}' can only be of type 'promptString' or 'pickString'.\", item.id));\n"
],
"file_path": "src/vs/workbench/services/configurationResolver/electron-browser/configurationResolverService.ts",
"type": "replace",
"edit_start_line_idx": 312
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as dom from 'vs/base/browser/dom';
import { FastDomNode, createFastDomNode } from 'vs/base/browser/fastDomNode';
import { IMouseEvent } from 'vs/base/browser/mouseEvent';
import { IOverviewRulerLayoutInfo, SmoothScrollableElement } from 'vs/base/browser/ui/scrollbar/scrollableElement';
import { ScrollableElementChangeOptions, ScrollableElementCreationOptions } from 'vs/base/browser/ui/scrollbar/scrollableElementOptions';
import { PartFingerprint, PartFingerprints, ViewPart } from 'vs/editor/browser/view/viewPart';
import { INewScrollPosition } from 'vs/editor/common/editorCommon';
import { RenderingContext, RestrictedRenderingContext } from 'vs/editor/common/view/renderingContext';
import { ViewContext } from 'vs/editor/common/view/viewContext';
import * as viewEvents from 'vs/editor/common/view/viewEvents';
import { getThemeTypeSelector } from 'vs/platform/theme/common/themeService';
export class EditorScrollbar extends ViewPart {
private scrollbar: SmoothScrollableElement;
private scrollbarDomNode: FastDomNode<HTMLElement>;
constructor(
context: ViewContext,
linesContent: FastDomNode<HTMLElement>,
viewDomNode: FastDomNode<HTMLElement>,
overflowGuardDomNode: FastDomNode<HTMLElement>
) {
super(context);
const editor = this._context.configuration.editor;
const configScrollbarOpts = editor.viewInfo.scrollbar;
let scrollbarOptions: ScrollableElementCreationOptions = {
listenOnDomNode: viewDomNode.domNode,
className: 'editor-scrollable' + ' ' + getThemeTypeSelector(context.theme.type),
useShadows: false,
lazyRender: true,
vertical: configScrollbarOpts.vertical,
horizontal: configScrollbarOpts.horizontal,
verticalHasArrows: configScrollbarOpts.verticalHasArrows,
horizontalHasArrows: configScrollbarOpts.horizontalHasArrows,
verticalScrollbarSize: configScrollbarOpts.verticalScrollbarSize,
verticalSliderSize: configScrollbarOpts.verticalSliderSize,
horizontalScrollbarSize: configScrollbarOpts.horizontalScrollbarSize,
horizontalSliderSize: configScrollbarOpts.horizontalSliderSize,
handleMouseWheel: configScrollbarOpts.handleMouseWheel,
arrowSize: configScrollbarOpts.arrowSize,
mouseWheelScrollSensitivity: configScrollbarOpts.mouseWheelScrollSensitivity,
};
this.scrollbar = this._register(new SmoothScrollableElement(linesContent.domNode, scrollbarOptions, this._context.viewLayout.scrollable));
PartFingerprints.write(this.scrollbar.getDomNode(), PartFingerprint.ScrollableElement);
this.scrollbarDomNode = createFastDomNode(this.scrollbar.getDomNode());
this.scrollbarDomNode.setPosition('absolute');
this._setLayout();
// When having a zone widget that calls .focus() on one of its dom elements,
// the browser will try desperately to reveal that dom node, unexpectedly
// changing the .scrollTop of this.linesContent
let onBrowserDesperateReveal = (domNode: HTMLElement, lookAtScrollTop: boolean, lookAtScrollLeft: boolean) => {
let newScrollPosition: INewScrollPosition = {};
if (lookAtScrollTop) {
let deltaTop = domNode.scrollTop;
if (deltaTop) {
newScrollPosition.scrollTop = this._context.viewLayout.getCurrentScrollTop() + deltaTop;
domNode.scrollTop = 0;
}
}
if (lookAtScrollLeft) {
let deltaLeft = domNode.scrollLeft;
if (deltaLeft) {
newScrollPosition.scrollLeft = this._context.viewLayout.getCurrentScrollLeft() + deltaLeft;
domNode.scrollLeft = 0;
}
}
this._context.viewLayout.setScrollPositionNow(newScrollPosition);
};
// I've seen this happen both on the view dom node & on the lines content dom node.
this._register(dom.addDisposableListener(viewDomNode.domNode, 'scroll', (e: Event) => onBrowserDesperateReveal(viewDomNode.domNode, true, true)));
this._register(dom.addDisposableListener(linesContent.domNode, 'scroll', (e: Event) => onBrowserDesperateReveal(linesContent.domNode, true, false)));
this._register(dom.addDisposableListener(overflowGuardDomNode.domNode, 'scroll', (e: Event) => onBrowserDesperateReveal(overflowGuardDomNode.domNode, true, false)));
this._register(dom.addDisposableListener(this.scrollbarDomNode.domNode, 'scroll', (e: Event) => onBrowserDesperateReveal(this.scrollbarDomNode.domNode, true, false)));
}
public dispose(): void {
super.dispose();
}
private _setLayout(): void {
const layoutInfo = this._context.configuration.editor.layoutInfo;
this.scrollbarDomNode.setLeft(layoutInfo.contentLeft);
const side = this._context.configuration.editor.viewInfo.minimap.side;
if (side === 'right') {
this.scrollbarDomNode.setWidth(layoutInfo.contentWidth + layoutInfo.minimapWidth);
} else {
this.scrollbarDomNode.setWidth(layoutInfo.contentWidth);
}
this.scrollbarDomNode.setHeight(layoutInfo.contentHeight);
}
public getOverviewRulerLayoutInfo(): IOverviewRulerLayoutInfo {
return this.scrollbar.getOverviewRulerLayoutInfo();
}
public getDomNode(): FastDomNode<HTMLElement> {
return this.scrollbarDomNode;
}
public delegateVerticalScrollbarMouseDown(browserEvent: IMouseEvent): void {
this.scrollbar.delegateVerticalScrollbarMouseDown(browserEvent);
}
// --- begin event handlers
public onConfigurationChanged(e: viewEvents.ViewConfigurationChangedEvent): boolean {
if (e.viewInfo) {
const editor = this._context.configuration.editor;
let newOpts: ScrollableElementChangeOptions = {
handleMouseWheel: editor.viewInfo.scrollbar.handleMouseWheel,
mouseWheelScrollSensitivity: editor.viewInfo.scrollbar.mouseWheelScrollSensitivity
};
this.scrollbar.updateOptions(newOpts);
}
if (e.layoutInfo) {
this._setLayout();
}
return true;
}
public onScrollChanged(e: viewEvents.ViewScrollChangedEvent): boolean {
return true;
}
public onThemeChanged(e: viewEvents.ViewThemeChangedEvent): boolean {
this.scrollbar.updateClassName('editor-scrollable' + ' ' + getThemeTypeSelector(this._context.theme.type));
return true;
}
// --- end event handlers
public prepareRender(ctx: RenderingContext): void {
// Nothing to do
}
public render(ctx: RestrictedRenderingContext): void {
this.scrollbar.renderNow();
}
}
| src/vs/editor/browser/viewParts/editorScrollbar/editorScrollbar.ts | 0 | https://github.com/microsoft/vscode/commit/51ef43a02382fb972b15d5b935515b69bb637a3a | [
0.000277259066933766,
0.0001811307156458497,
0.0001643679424887523,
0.00017011808813549578,
0.00003200200808350928
] |
{
"id": 4,
"code_window": [
"\t\t\t\t\t\tdefault: {\n",
"\t\t\t\t\t\t\tthrow new Error(nls.localize('unknownInputTypeProvided', \"Input '{0}' can only be of type 'prompt' or 'pick'.\", item.id));\n",
"\t\t\t\t\t\t}\n",
"\t\t\t\t\t}\n",
"\t\t\t\t\tlet options: string[];\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t\t\t\t\tthrow new Error(nls.localize('unknownInputTypeProvided', \"Input '{0}' can only be of type 'promptString' or 'pickString'.\", item.id));\n"
],
"file_path": "src/vs/workbench/services/configurationResolver/electron-browser/configurationResolverService.ts",
"type": "replace",
"edit_start_line_idx": 312
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as fs from 'fs';
import * as path from 'path';
import * as vscode from 'vscode';
import * as nls from 'vscode-nls';
import * as Proto from '../protocol';
import { ITypeScriptServiceClient } from '../typescriptService';
import API from '../utils/api';
import * as fileSchemes from '../utils/fileSchemes';
import { isTypeScriptDocument } from '../utils/languageModeIds';
import { escapeRegExp } from '../utils/regexp';
import * as typeConverters from '../utils/typeConverters';
import FileConfigurationManager from './fileConfigurationManager';
import { VersionDependentRegistration } from '../utils/dependentRegistration';
import { nulToken } from '../utils/cancellation';
const localize = nls.loadMessageBundle();
const updateImportsOnFileMoveName = 'updateImportsOnFileMove.enabled';
enum UpdateImportsOnFileMoveSetting {
Prompt = 'prompt',
Always = 'always',
Never = 'never',
}
class UpdateImportsOnFileRenameHandler {
private readonly _onDidRenameSub: vscode.Disposable;
public constructor(
private readonly client: ITypeScriptServiceClient,
private readonly fileConfigurationManager: FileConfigurationManager,
private readonly _handles: (uri: vscode.Uri) => Promise<boolean>,
) {
this._onDidRenameSub = vscode.workspace.onDidRenameFile(e => {
this.doRename(e.oldUri, e.newUri);
});
}
public dispose() {
this._onDidRenameSub.dispose();
}
private async doRename(
oldResource: vscode.Uri,
newResource: vscode.Uri,
): Promise<void> {
const targetResource = await this.getTargetResource(newResource);
if (!targetResource) {
return;
}
const targetFile = this.client.toPath(targetResource);
if (!targetFile) {
return;
}
const newFile = this.client.toPath(newResource);
if (!newFile) {
return;
}
const oldFile = this.client.toPath(oldResource);
if (!oldFile) {
return;
}
const document = await vscode.workspace.openTextDocument(targetResource);
const config = this.getConfiguration(document);
const setting = config.get<UpdateImportsOnFileMoveSetting>(updateImportsOnFileMoveName);
if (setting === UpdateImportsOnFileMoveSetting.Never) {
return;
}
// Make sure TS knows about file
this.client.bufferSyncSupport.closeResource(oldResource);
this.client.bufferSyncSupport.openTextDocument(document);
if (this.client.apiVersion.lt(API.v300) && !fs.lstatSync(newResource.fsPath).isDirectory()) {
// Workaround for https://github.com/Microsoft/vscode/issues/52967
// Never attempt to update import paths if the file does not contain something the looks like an export
try {
const response = await this.client.execute('navtree', { file: newFile }, nulToken);
if (response.type !== 'response' || !response.body) {
return;
}
const hasExport = (node: Proto.NavigationTree): boolean => {
return !!node.kindModifiers.match(/\bexports?\b/g) || !!(node.childItems && node.childItems.some(hasExport));
};
if (!hasExport(response.body)) {
return;
}
} catch {
// noop
}
}
const edits = await this.getEditsForFileRename(targetFile, document, oldFile, newFile);
if (!edits || !edits.size) {
return;
}
if (await this.confirmActionWithUser(newResource, document)) {
await vscode.workspace.applyEdit(edits);
}
}
private async confirmActionWithUser(
newResource: vscode.Uri,
newDocument: vscode.TextDocument
): Promise<boolean> {
const config = this.getConfiguration(newDocument);
const setting = config.get<UpdateImportsOnFileMoveSetting>(updateImportsOnFileMoveName);
switch (setting) {
case UpdateImportsOnFileMoveSetting.Always:
return true;
case UpdateImportsOnFileMoveSetting.Never:
return false;
case UpdateImportsOnFileMoveSetting.Prompt:
default:
return this.promptUser(newResource, newDocument);
}
}
private getConfiguration(newDocument: vscode.TextDocument) {
return vscode.workspace.getConfiguration(isTypeScriptDocument(newDocument) ? 'typescript' : 'javascript', newDocument.uri);
}
private async promptUser(
newResource: vscode.Uri,
newDocument: vscode.TextDocument
): Promise<boolean> {
enum Choice {
None = 0,
Accept = 1,
Reject = 2,
Always = 3,
Never = 4,
}
interface Item extends vscode.MessageItem {
choice: Choice;
}
const response = await vscode.window.showInformationMessage<Item>(
localize('prompt', "Update imports for moved file: '{0}'?", path.basename(newResource.fsPath)), {
modal: true,
}, {
title: localize('reject.title', "No"),
choice: Choice.Reject,
isCloseAffordance: true,
}, {
title: localize('accept.title', "Yes"),
choice: Choice.Accept,
}, {
title: localize('always.title', "Always automatically update imports"),
choice: Choice.Always,
}, {
title: localize('never.title', "Never automatically update imports"),
choice: Choice.Never,
});
if (!response) {
return false;
}
switch (response.choice) {
case Choice.Accept:
{
return true;
}
case Choice.Reject:
{
return false;
}
case Choice.Always:
{
const config = this.getConfiguration(newDocument);
config.update(
updateImportsOnFileMoveName,
UpdateImportsOnFileMoveSetting.Always,
vscode.ConfigurationTarget.Global);
return true;
}
case Choice.Never:
{
const config = this.getConfiguration(newDocument);
config.update(
updateImportsOnFileMoveName,
UpdateImportsOnFileMoveSetting.Never,
vscode.ConfigurationTarget.Global);
return false;
}
}
return false;
}
private async getTargetResource(resource: vscode.Uri): Promise<vscode.Uri | undefined> {
if (resource.scheme !== fileSchemes.file) {
return undefined;
}
const isDirectory = fs.lstatSync(resource.fsPath).isDirectory();
if (isDirectory && this.client.apiVersion.gte(API.v300)) {
return resource;
}
if (isDirectory && this.client.apiVersion.gte(API.v292)) {
const files = await vscode.workspace.findFiles({
base: resource.fsPath,
pattern: '**/*.{ts,tsx,js,jsx}',
}, '**/node_modules/**', 1);
return files[0];
}
return (await this._handles(resource)) ? resource : undefined;
}
private async getEditsForFileRename(
targetResource: string,
document: vscode.TextDocument,
oldFile: string,
newFile: string,
) {
const isDirectoryRename = fs.lstatSync(newFile).isDirectory();
await this.fileConfigurationManager.setGlobalConfigurationFromDocument(document, nulToken);
const args: Proto.GetEditsForFileRenameRequestArgs & { file: string } = {
file: targetResource,
oldFilePath: oldFile,
newFilePath: newFile,
};
const response = await this.client.execute('getEditsForFileRename', args, nulToken);
if (response.type !== 'response') {
return;
}
if (!response.body) {
return;
}
const edits: Proto.FileCodeEdits[] = [];
for (const edit of response.body) {
// Workaround for https://github.com/Microsoft/vscode/issues/52675
if (this.client.apiVersion.lt(API.v300)) {
if ((edit as Proto.FileCodeEdits).fileName.match(/[\/\\]node_modules[\/\\]/gi)) {
continue;
}
for (const change of (edit as Proto.FileCodeEdits).textChanges) {
if (change.newText.match(/\/node_modules\//gi)) {
continue;
}
}
}
edits.push(await this.fixEdit(edit, isDirectoryRename, oldFile, newFile));
}
return typeConverters.WorkspaceEdit.fromFileCodeEdits(this.client, edits);
}
private async fixEdit(
edit: Proto.FileCodeEdits,
isDirectoryRename: boolean,
oldFile: string,
newFile: string,
): Promise<Proto.FileCodeEdits> {
if (!isDirectoryRename || this.client.apiVersion.gte(API.v300)) {
return edit;
}
const document = await vscode.workspace.openTextDocument(edit.fileName);
const oldFileRe = new RegExp('/' + escapeRegExp(path.basename(oldFile)) + '/');
// Workaround for https://github.com/Microsoft/TypeScript/issues/24968
const textChanges = edit.textChanges.map((change): Proto.CodeEdit => {
const existingText = document.getText(typeConverters.Range.fromTextSpan(change));
const existingMatch = existingText.match(oldFileRe);
if (!existingMatch) {
return change;
}
const match = new RegExp('/' + escapeRegExp(path.basename(newFile)) + '/(.+)$', 'g').exec(change.newText);
if (!match) {
return change;
}
return {
newText: change.newText.slice(0, -match[1].length),
start: change.start,
end: {
line: change.end.line,
offset: change.end.offset - match[1].length,
},
};
});
return {
fileName: edit.fileName,
textChanges,
};
}
}
export function register(
client: ITypeScriptServiceClient,
fileConfigurationManager: FileConfigurationManager,
handles: (uri: vscode.Uri) => Promise<boolean>,
) {
return new VersionDependentRegistration(client, API.v290, () =>
new UpdateImportsOnFileRenameHandler(client, fileConfigurationManager, handles));
} | extensions/typescript-language-features/src/features/updatePathsOnRename.ts | 0 | https://github.com/microsoft/vscode/commit/51ef43a02382fb972b15d5b935515b69bb637a3a | [
0.001405571703799069,
0.0002413711918052286,
0.00016450043767690659,
0.00017294037388637662,
0.0002702079073060304
] |
{
"id": 5,
"code_window": [
"\t\t\t\t\t\t}\n",
"\t\t\t\t\t}\n",
"\t\t\t\t\tlet options: string[];\n",
"\t\t\t\t\tif (type === ConfiguredInputType.Pick) {\n",
"\t\t\t\t\t\tif (Types.isStringArray(item.options)) {\n",
"\t\t\t\t\t\t\toptions = item.options;\n",
"\t\t\t\t\t\t} else {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t\t\tif (type === ConfiguredInputType.PickString) {\n"
],
"file_path": "src/vs/workbench/services/configurationResolver/electron-browser/configurationResolverService.ts",
"type": "replace",
"edit_start_line_idx": 316
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { URI as uri } from 'vs/base/common/uri';
import * as nls from 'vs/nls';
import * as paths from 'vs/base/common/paths';
import * as platform from 'vs/base/common/platform';
import * as Objects from 'vs/base/common/objects';
import * as Types from 'vs/base/common/types';
import { Schemas } from 'vs/base/common/network';
import { TPromise } from 'vs/base/common/winjs.base';
import { sequence } from 'vs/base/common/async';
import { toResource } from 'vs/workbench/common/editor';
import { IStringDictionary, forEach, fromMap } from 'vs/base/common/collections';
import { IEnvironmentService } from 'vs/platform/environment/common/environment';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { ICommandService } from 'vs/platform/commands/common/commands';
import { IWorkspaceFolder, IWorkspaceContextService, WorkbenchState } from 'vs/platform/workspace/common/workspace';
import { IEditorService } from 'vs/workbench/services/editor/common/editorService';
import { AbstractVariableResolverService } from 'vs/workbench/services/configurationResolver/node/variableResolver';
import { isCodeEditor } from 'vs/editor/browser/editorBrowser';
import { DiffEditorInput } from 'vs/workbench/common/editor/diffEditorInput';
import { IQuickInputService, IInputOptions, IQuickPickItem, IPickOptions } from 'vs/platform/quickinput/common/quickInput';
import { ConfiguredInput, ConfiguredInputType } from 'vs/workbench/services/configurationResolver/common/configurationResolver';
export class ConfigurationResolverService extends AbstractVariableResolverService {
constructor(
envVariables: platform.IProcessEnvironment,
@IEditorService editorService: IEditorService,
@IEnvironmentService environmentService: IEnvironmentService,
@IConfigurationService private configurationService: IConfigurationService,
@ICommandService private commandService: ICommandService,
@IWorkspaceContextService private workspaceContextService: IWorkspaceContextService,
@IQuickInputService private quickInputService: IQuickInputService
) {
super({
getFolderUri: (folderName: string): uri => {
const folder = workspaceContextService.getWorkspace().folders.filter(f => f.name === folderName).pop();
return folder ? folder.uri : undefined;
},
getWorkspaceFolderCount: (): number => {
return workspaceContextService.getWorkspace().folders.length;
},
getConfigurationValue: (folderUri: uri, suffix: string) => {
return configurationService.getValue<string>(suffix, folderUri ? { resource: folderUri } : undefined);
},
getExecPath: () => {
return environmentService['execPath'];
},
getFilePath: (): string | undefined => {
let activeEditor = editorService.activeEditor;
if (activeEditor instanceof DiffEditorInput) {
activeEditor = activeEditor.modifiedInput;
}
const fileResource = toResource(activeEditor, { filter: Schemas.file });
if (!fileResource) {
return undefined;
}
return paths.normalize(fileResource.fsPath, true);
},
getSelectedText: (): string | undefined => {
const activeTextEditorWidget = editorService.activeTextEditorWidget;
if (isCodeEditor(activeTextEditorWidget)) {
const editorModel = activeTextEditorWidget.getModel();
const editorSelection = activeTextEditorWidget.getSelection();
if (editorModel && editorSelection) {
return editorModel.getValueInRange(editorSelection);
}
}
return undefined;
},
getLineNumber: (): string => {
const activeTextEditorWidget = editorService.activeTextEditorWidget;
if (isCodeEditor(activeTextEditorWidget)) {
const lineNumber = activeTextEditorWidget.getSelection().positionLineNumber;
return String(lineNumber);
}
return undefined;
}
}, envVariables);
}
public resolveWithInteractionReplace(folder: IWorkspaceFolder, config: any, section?: string, variables?: IStringDictionary<string>): TPromise<any> {
// resolve any non-interactive variables
config = this.resolveAny(folder, config);
// resolve input variables in the order in which they are encountered
return this.resolveWithInteraction(folder, config, section, variables).then(mapping => {
// finally substitute evaluated command variables (if there are any)
if (mapping.size > 0) {
return this.resolveAny(folder, config, fromMap(mapping));
} else {
return config;
}
});
}
public resolveWithInteraction(folder: IWorkspaceFolder, config: any, section?: string, variables?: IStringDictionary<string>): TPromise<Map<string, string>> {
// resolve any non-interactive variables
const resolved = this.resolveAnyMap(folder, config);
config = resolved.newConfig;
const allVariableMapping: Map<string, string> = resolved.resolvedVariables;
// resolve input variables in the order in which they are encountered
return this.resolveWithInputs(folder, config, section).then(inputMapping => {
if (!this.updateMapping(inputMapping, allVariableMapping)) {
return undefined;
}
// resolve commands in the order in which they are encountered
return this.resolveWithCommands(config, variables).then(commandMapping => {
if (!this.updateMapping(commandMapping, allVariableMapping)) {
return undefined;
}
return allVariableMapping;
});
});
}
/**
* Add all items from newMapping to fullMapping. Returns false if newMapping is undefined.
*/
private updateMapping(newMapping: IStringDictionary<string>, fullMapping: Map<string, string>): boolean {
if (!newMapping) {
return false;
}
forEach(newMapping, (entry) => {
fullMapping.set(entry.key, entry.value);
});
return true;
}
/**
* Finds and executes all command variables in the given configuration and returns their values as a dictionary.
* Please note: this method does not substitute the command variables (so the configuration is not modified).
* The returned dictionary can be passed to "resolvePlatform" for the substitution.
* See #6569.
* @param configuration
* @param variableToCommandMap Aliases for commands
*/
private resolveWithCommands(configuration: any, variableToCommandMap: IStringDictionary<string>): TPromise<IStringDictionary<string>> {
if (!configuration) {
return TPromise.as(undefined);
}
// use an array to preserve order of first appearance
const cmd_var = /\${command:(.*?)}/g;
const commands: string[] = [];
this.findVariables(cmd_var, configuration, commands);
let cancelled = false;
const commandValueMapping: IStringDictionary<string> = Object.create(null);
const factory: { (): TPromise<any> }[] = commands.map(commandVariable => {
return () => {
let commandId = variableToCommandMap ? variableToCommandMap[commandVariable] : undefined;
if (!commandId) {
// Just launch any command if the interactive variable is not contributed by the adapter #12735
commandId = commandVariable;
}
return this.commandService.executeCommand<string>(commandId, configuration).then(result => {
if (typeof result === 'string') {
commandValueMapping['command:' + commandVariable] = result;
} else if (Types.isUndefinedOrNull(result)) {
cancelled = true;
} else {
throw new Error(nls.localize('stringsOnlySupported', "Command '{0}' did not return a string result. Only strings are supported as results for commands used for variable substitution.", commandVariable));
}
});
};
});
return sequence(factory).then(() => cancelled ? undefined : commandValueMapping);
}
/**
* Resolves all inputs in a configuration and returns a map that maps the unresolved input to the resolved input.
* Does not do replacement of inputs.
* @param folder
* @param config
* @param section
*/
public resolveWithInputs(folder: IWorkspaceFolder, config: any, section: string): Promise<IStringDictionary<string>> {
if (!config) {
return Promise.resolve(undefined);
} else if (folder && section) {
// Get all the possible inputs
let result = this.workspaceContextService.getWorkbenchState() !== WorkbenchState.EMPTY
? Objects.deepClone(this.configurationService.getValue<any>(section, { resource: folder.uri }))
: undefined;
let inputsArray = result ? this.parseConfigurationInputs(result.inputs) : undefined;
const inputs = new Map<string, ConfiguredInput>();
if (inputsArray) {
inputsArray.forEach(input => {
inputs.set(input.id, input);
});
// use an array to preserve order of first appearance
const input_var = /\${input:(.*?)}/g;
const commands: string[] = [];
this.findVariables(input_var, config, commands);
let cancelled = false;
const commandValueMapping: IStringDictionary<string> = Object.create(null);
const factory: { (): Promise<any> }[] = commands.map(commandVariable => {
return () => {
return this.showUserInput(commandVariable, inputs).then(resolvedValue => {
if (resolvedValue) {
commandValueMapping['input:' + commandVariable] = resolvedValue;
}
});
};
}, reason => {
return Promise.reject(reason);
});
return sequence(factory).then(() => cancelled ? undefined : commandValueMapping);
}
}
return Promise.resolve(Object.create(null));
}
/**
* Takes the provided input info and shows the quick pick so the user can provide the value for the input
* @param commandVariable Name of the input.
* @param inputs Information about each possible input.
* @param commandValueMapping
*/
private showUserInput(commandVariable: string, inputs: Map<string, ConfiguredInput>): Promise<string> {
if (inputs && inputs.has(commandVariable)) {
const input = inputs.get(commandVariable);
if (input.type === ConfiguredInputType.Prompt) {
let inputOptions: IInputOptions = { prompt: input.description };
if (input.default) {
inputOptions.value = input.default;
}
return this.quickInputService.input(inputOptions).then(resolvedInput => {
return resolvedInput ? resolvedInput : input.default;
});
} else { // input.type === ConfiguredInputType.pick
let picks = new Array<IQuickPickItem>();
if (input.options) {
input.options.forEach(pickOption => {
let item: IQuickPickItem = { label: pickOption };
if (input.default && (pickOption === input.default)) {
item.description = nls.localize('defaultInputValue', "Default");
picks.unshift(item);
} else {
picks.push(item);
}
});
}
let pickOptions: IPickOptions<IQuickPickItem> = { placeHolder: input.description };
return this.quickInputService.pick(picks, pickOptions, undefined).then(resolvedInput => {
return resolvedInput ? resolvedInput.label : input.default;
});
}
}
return Promise.resolve(undefined);
}
/**
* Finds all variables in object using cmdVar and pushes them into commands.
* @param cmdVar Regex to use for finding variables.
* @param object object is searched for variables.
* @param commands All found variables are returned in commands.
*/
private findVariables(cmdVar: RegExp, object: any, commands: string[]) {
if (!object) {
return;
} else if (typeof object === 'string') {
let matches;
while ((matches = cmdVar.exec(object)) !== null) {
if (matches.length === 2) {
const command = matches[1];
if (commands.indexOf(command) < 0) {
commands.push(command);
}
}
}
} else if (Types.isArray(object)) {
object.forEach(value => {
this.findVariables(cmdVar, value, commands);
});
} else {
Object.keys(object).forEach(key => {
const value = object[key];
this.findVariables(cmdVar, value, commands);
});
}
}
/**
* Converts an array of inputs into an actaul array of typed, ConfiguredInputs.
* @param object Array of something that should look like inputs.
*/
private parseConfigurationInputs(object: any[]): ConfiguredInput[] | undefined {
let inputs = new Array<ConfiguredInput>();
if (object) {
object.forEach(item => {
if (Types.isString(item.id) && Types.isString(item.description) && Types.isString(item.type)) {
let type: ConfiguredInputType;
switch (item.type) {
case 'prompt': type = ConfiguredInputType.Prompt; break;
case 'pick': type = ConfiguredInputType.Pick; break;
default: {
throw new Error(nls.localize('unknownInputTypeProvided', "Input '{0}' can only be of type 'prompt' or 'pick'.", item.id));
}
}
let options: string[];
if (type === ConfiguredInputType.Pick) {
if (Types.isStringArray(item.options)) {
options = item.options;
} else {
throw new Error(nls.localize('pickRequiresOptions', "Input '{0}' is of type 'pick' and must include 'options'.", item.id));
}
}
inputs.push({ id: item.id, description: item.description, type, default: item.default, options });
}
});
}
return inputs;
}
} | src/vs/workbench/services/configurationResolver/electron-browser/configurationResolverService.ts | 1 | https://github.com/microsoft/vscode/commit/51ef43a02382fb972b15d5b935515b69bb637a3a | [
0.998075008392334,
0.03422686085104942,
0.0001640974951442331,
0.00017502097762189806,
0.1696464568376541
] |
{
"id": 5,
"code_window": [
"\t\t\t\t\t\t}\n",
"\t\t\t\t\t}\n",
"\t\t\t\t\tlet options: string[];\n",
"\t\t\t\t\tif (type === ConfiguredInputType.Pick) {\n",
"\t\t\t\t\t\tif (Types.isStringArray(item.options)) {\n",
"\t\t\t\t\t\t\toptions = item.options;\n",
"\t\t\t\t\t\t} else {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t\t\tif (type === ConfiguredInputType.PickString) {\n"
],
"file_path": "src/vs/workbench/services/configurationResolver/electron-browser/configurationResolverService.ts",
"type": "replace",
"edit_start_line_idx": 316
} | {
"information_for_contributors": [
"This file has been converted from https://github.com/tgjones/shaders-tmLanguage/blob/master/grammars/hlsl.json",
"If you want to provide a fix or improvement, please create a pull request against the original repository.",
"Once accepted there, we are happy to receive an update request."
],
"version": "https://github.com/tgjones/shaders-tmLanguage/commit/cd1ef40f549f9ce2b9e6b73498688de114a85382",
"name": "HLSL",
"scopeName": "source.hlsl",
"patterns": [
{
"name": "comment.line.block.hlsl",
"begin": "/\\*",
"end": "\\*/"
},
{
"name": "comment.line.double-slash.hlsl",
"begin": "//",
"end": "$"
},
{
"name": "constant.numeric.hlsl",
"match": "\\b([0-9]+\\.?[0-9]*)\\b"
},
{
"name": "constant.numeric.hlsl",
"match": "\\b(\\.[0-9]+)\\b"
},
{
"name": "constant.numeric.hex.hlsl",
"match": "\\b(0x[0-9A-F]+)\\b"
},
{
"name": "constant.language.hlsl",
"match": "\\b(false|true)\\b"
},
{
"name": "keyword.preprocessor.hlsl",
"match": "^\\s*#\\s*(define|elif|else|endif|ifdef|ifndef|if|undef|include|line|error|pragma)"
},
{
"name": "keyword.control.hlsl",
"match": "\\b(break|case|continue|default|discard|do|else|for|if|return|switch|while)\\b"
},
{
"name": "keyword.control.fx.hlsl",
"match": "\\b(compile)\\b"
},
{
"name": "keyword.typealias.hlsl",
"match": "\\b(typedef)\\b"
},
{
"name": "storage.type.basic.hlsl",
"match": "\\b(bool([1-4](x[1-4])?)?|double([1-4](x[1-4])?)?|dword|float([1-4](x[1-4])?)?|half([1-4](x[1-4])?)?|int([1-4](x[1-4])?)?|matrix|min10float([1-4](x[1-4])?)?|min12int([1-4](x[1-4])?)?|min16float([1-4](x[1-4])?)?|min16int([1-4](x[1-4])?)?|min16uint([1-4](x[1-4])?)?|unsigned|uint([1-4](x[1-4])?)?|vector|void)\\b"
},
{
"name": "support.function.hlsl",
"match": "\\b([a-zA-Z_][a-zA-Z0-9_]*)(?=[\\s]*\\()"
},
{
"name": "support.variable.semantic.hlsl",
"match": "(?<=\\:\\s|\\:)(?i:BINORMAL[0-9]*|BLENDINDICES[0-9]*|BLENDWEIGHT[0-9]*|COLOR[0-9]*|NORMAL[0-9]*|POSITIONT|POSITION|PSIZE[0-9]*|TANGENT[0-9]*|TEXCOORD[0-9]*|FOG|TESSFACTOR[0-9]*|VFACE|VPOS|DEPTH[0-9]*)\\b"
},
{
"name": "support.variable.semantic.sm4.hlsl",
"match": "(?<=\\:\\s|\\:)(?i:SV_ClipDistance[0-9]*|SV_CullDistance[0-9]*|SV_Coverage|SV_Depth|SV_DepthGreaterEqual[0-9]*|SV_DepthLessEqual[0-9]*|SV_InstanceID|SV_IsFrontFace|SV_Position|SV_RenderTargetArrayIndex|SV_SampleIndex|SV_StencilRef|SV_Target[0-7]?|SV_VertexID|SV_ViewportArrayIndex)\\b"
},
{
"name": "support.variable.semantic.sm5.hlsl",
"match": "(?<=\\:\\s|\\:)(?i:SV_DispatchThreadID|SV_DomainLocation|SV_GroupID|SV_GroupIndex|SV_GroupThreadID|SV_GSInstanceID|SV_InsideTessFactor|SV_OutputControlPointID|SV_TessFactor)\\b"
},
{
"name": "support.variable.semantic.sm5_1.hlsl",
"match": "(?<=\\:\\s|\\:)(?i:SV_InnerCoverage|SV_StencilRef)\\b"
},
{
"name": "storage.modifier.hlsl",
"match": "\\b(column_major|const|export|extern|globallycoherent|groupshared|inline|inout|in|out|precise|row_major|shared|static|uniform|volatile)\\b"
},
{
"name": "storage.modifier.float.hlsl",
"match": "\\b(snorm|unorm)\\b"
},
{
"name": "storage.modifier.postfix.hlsl",
"match": "\\b(packoffset|register)\\b"
},
{
"name": "storage.modifier.interpolation.hlsl",
"match": "\\b(centroid|linear|nointerpolation|noperspective|sample)\\b"
},
{
"name": "storage.modifier.geometryshader.hlsl",
"match": "\\b(lineadj|line|point|triangle|triangleadj)\\b"
},
{
"name": "support.type.other.hlsl",
"match": "\\b(string)\\b"
},
{
"name": "support.type.object.hlsl",
"match": "\\b(AppendStructuredBuffer|Buffer|ByteAddressBuffer|ConstantBuffer|ConsumeStructuredBuffer|InputPatch|OutputPatch)\\b"
},
{
"name": "support.type.object.rasterizerordered.hlsl",
"match": "\\b(RasterizerOrderedBuffer|RasterizerOrderedByteAddressBuffer|RasterizerOrderedStructuredBuffer|RasterizerOrderedTexture1D|RasterizerOrderedTexture1DArray|RasterizerOrderedTexture2D|RasterizerOrderedTexture2DArray|RasterizerOrderedTexture3D)\\b"
},
{
"name": "support.type.object.rw.hlsl",
"match": "\\b(RWBuffer|RWByteAddressBuffer|RWStructuredBuffer|RWTexture1D|RWTexture1DArray|RWTexture2D|RWTexture2DArray|RWTexture3D)\\b"
},
{
"name": "support.type.object.geometryshader.hlsl",
"match": "\\b(LineStream|PointStream|TriangleStream)\\b"
},
{
"name": "support.type.sampler.legacy.hlsl",
"match": "\\b(sampler|sampler1D|sampler2D|sampler3D|samplerCUBE|sampler_state)\\b"
},
{
"name": "support.type.sampler.hlsl",
"match": "\\b(SamplerState|SamplerComparisonState)\\b"
},
{
"name": "support.type.texture.legacy.hlsl",
"match": "\\b(texture2D|textureCUBE)\\b"
},
{
"name": "support.type.texture.hlsl",
"match": "\\b(Texture1D|Texture1DArray|Texture2D|Texture2DArray|Texture2DMS|Texture2DMSArray|Texture3D|TextureCube|TextureCubeArray)\\b"
},
{
"name": "storage.type.structured.hlsl",
"match": "\\b(cbuffer|class|interface|namespace|struct|tbuffer)\\b"
},
{
"name": "support.constant.property-value.fx.hlsl",
"match": "\\b(FALSE|TRUE|NULL)\\b"
},
{
"name": "support.type.fx.hlsl",
"match": "\\b(BlendState|DepthStencilState|RasterizerState)\\b"
},
{
"name": "storage.type.fx.technique.hlsl",
"match": "\\b(technique|Technique|technique10|technique11|pass)\\b"
},
{
"name": "meta.object-literal.key.fx.blendstate.hlsl",
"match": "\\b(AlphaToCoverageEnable|BlendEnable|SrcBlend|DestBlend|BlendOp|SrcBlendAlpha|DestBlendAlpha|BlendOpAlpha|RenderTargetWriteMask)\\b"
},
{
"name": "meta.object-literal.key.fx.depthstencilstate.hlsl",
"match": "\\b(DepthEnable|DepthWriteMask|DepthFunc|StencilEnable|StencilReadMask|StencilWriteMask|FrontFaceStencilFail|FrontFaceStencilZFail|FrontFaceStencilPass|FrontFaceStencilFunc|BackFaceStencilFail|BackFaceStencilZFail|BackFaceStencilPass|BackFaceStencilFunc)\\b"
},
{
"name": "meta.object-literal.key.fx.rasterizerstate.hlsl",
"match": "\\b(FillMode|CullMode|FrontCounterClockwise|DepthBias|DepthBiasClamp|SlopeScaleDepthBias|ZClipEnable|ScissorEnable|MultiSampleEnable|AntiAliasedLineEnable)\\b"
},
{
"name": "meta.object-literal.key.fx.samplerstate.hlsl",
"match": "\\b(Filter|AddressU|AddressV|AddressW|MipLODBias|MaxAnisotropy|ComparisonFunc|BorderColor|MinLOD|MaxLOD)\\b"
},
{
"name": "support.constant.property-value.fx.blend.hlsl",
"match": "\\b(?i:ZERO|ONE|SRC_COLOR|INV_SRC_COLOR|SRC_ALPHA|INV_SRC_ALPHA|DEST_ALPHA|INV_DEST_ALPHA|DEST_COLOR|INV_DEST_COLOR|SRC_ALPHA_SAT|BLEND_FACTOR|INV_BLEND_FACTOR|SRC1_COLOR|INV_SRC1_COLOR|SRC1_ALPHA|INV_SRC1_ALPHA)\\b"
},
{
"name": "support.constant.property-value.fx.blendop.hlsl",
"match": "\\b(?i:ADD|SUBTRACT|REV_SUBTRACT|MIN|MAX)\\b"
},
{
"name": "support.constant.property-value.fx.depthwritemask.hlsl",
"match": "\\b(?i:ALL)\\b"
},
{
"name": "support.constant.property-value.fx.comparisonfunc.hlsl",
"match": "\\b(?i:NEVER|LESS|EQUAL|LESS_EQUAL|GREATER|NOT_EQUAL|GREATER_EQUAL|ALWAYS)\\b"
},
{
"name": "support.constant.property-value.fx.stencilop.hlsl",
"match": "\\b(?i:KEEP|REPLACE|INCR_SAT|DECR_SAT|INVERT|INCR|DECR)\\b"
},
{
"name": "support.constant.property-value.fx.fillmode.hlsl",
"match": "\\b(?i:WIREFRAME|SOLID)\\b"
},
{
"name": "support.constant.property-value.fx.cullmode.hlsl",
"match": "\\b(?i:NONE|FRONT|BACK)\\b"
},
{
"name": "support.constant.property-value.fx.filter.hlsl",
"match": "\\b(?i:MIN_MAG_MIP_POINT|MIN_MAG_POINT_MIP_LINEAR|MIN_POINT_MAG_LINEAR_MIP_POINT|MIN_POINT_MAG_MIP_LINEAR|MIN_LINEAR_MAG_MIP_POINT|MIN_LINEAR_MAG_POINT_MIP_LINEAR|MIN_MAG_LINEAR_MIP_POINT|MIN_MAG_MIP_LINEAR|ANISOTROPIC|COMPARISON_MIN_MAG_MIP_POINT|COMPARISON_MIN_MAG_POINT_MIP_LINEAR|COMPARISON_MIN_POINT_MAG_LINEAR_MIP_POINT|COMPARISON_MIN_POINT_MAG_MIP_LINEAR|COMPARISON_MIN_LINEAR_MAG_MIP_POINT|COMPARISON_MIN_LINEAR_MAG_POINT_MIP_LINEAR|COMPARISON_MIN_MAG_LINEAR_MIP_POINT|COMPARISON_MIN_MAG_MIP_LINEAR|COMPARISON_ANISOTROPIC|TEXT_1BIT)\\b"
},
{
"name": "support.constant.property-value.fx.textureaddressmode.hlsl",
"match": "\\b(?i:WRAP|MIRROR|CLAMP|BORDER|MIRROR_ONCE)\\b"
},
{
"name": "string.quoted.double.hlsl",
"begin": "\"",
"end": "\"",
"patterns": [
{
"name": "constant.character.escape.hlsl",
"match": "\\\\."
}
]
}
]
} | extensions/hlsl/syntaxes/hlsl.tmLanguage.json | 0 | https://github.com/microsoft/vscode/commit/51ef43a02382fb972b15d5b935515b69bb637a3a | [
0.00017608876805752516,
0.0001731867087073624,
0.00017018789367284626,
0.00017335693701170385,
0.000001341789015896211
] |
{
"id": 5,
"code_window": [
"\t\t\t\t\t\t}\n",
"\t\t\t\t\t}\n",
"\t\t\t\t\tlet options: string[];\n",
"\t\t\t\t\tif (type === ConfiguredInputType.Pick) {\n",
"\t\t\t\t\t\tif (Types.isStringArray(item.options)) {\n",
"\t\t\t\t\t\t\toptions = item.options;\n",
"\t\t\t\t\t\t} else {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t\t\tif (type === ConfiguredInputType.PickString) {\n"
],
"file_path": "src/vs/workbench/services/configurationResolver/electron-browser/configurationResolverService.ts",
"type": "replace",
"edit_start_line_idx": 316
} | <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" enable-background="new 0 0 16 16" height="16" width="16"><circle fill="#424242" cx="8" cy="8" r="4"/></svg> | src/vs/workbench/browser/parts/editor/media/close-dirty.svg | 0 | https://github.com/microsoft/vscode/commit/51ef43a02382fb972b15d5b935515b69bb637a3a | [
0.00017370637215208262,
0.00017370637215208262,
0.00017370637215208262,
0.00017370637215208262,
0
] |
{
"id": 5,
"code_window": [
"\t\t\t\t\t\t}\n",
"\t\t\t\t\t}\n",
"\t\t\t\t\tlet options: string[];\n",
"\t\t\t\t\tif (type === ConfiguredInputType.Pick) {\n",
"\t\t\t\t\t\tif (Types.isStringArray(item.options)) {\n",
"\t\t\t\t\t\t\toptions = item.options;\n",
"\t\t\t\t\t\t} else {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t\t\tif (type === ConfiguredInputType.PickString) {\n"
],
"file_path": "src/vs/workbench/services/configurationResolver/electron-browser/configurationResolverService.ts",
"type": "replace",
"edit_start_line_idx": 316
} | steps:
- task: NodeTool@0
inputs:
versionSpec: "8.12.0"
- task: geeklearningio.gl-vsts-tasks-yarn.yarn-installer-task.YarnInstaller@2
inputs:
versionSpec: "1.10.1"
- task: UsePythonVersion@0
inputs:
versionSpec: '2.x'
addToPath: true
- powershell: |
. build/azure-pipelines/win32/exec.ps1
$ErrorActionPreference = "Stop"
"machine monacotools.visualstudio.com password $(VSO_PAT)" | Out-File "$env:USERPROFILE\_netrc" -Encoding ASCII
$env:npm_config_arch="$(VSCODE_ARCH)"
$env:CHILD_CONCURRENCY="1"
$env:VSCODE_MIXIN_PASSWORD="$(VSCODE_MIXIN_PASSWORD)"
exec { yarn }
exec { npm run gulp -- hygiene }
exec { npm run monaco-compile-check }
exec { npm run strict-null-check }
exec { npm run gulp -- mixin }
exec { node build/azure-pipelines/common/installDistro.js }
exec { node build/lib/builtInExtensions.js }
- powershell: |
. build/azure-pipelines/win32/exec.ps1
$ErrorActionPreference = "Stop"
$env:VSCODE_MIXIN_PASSWORD="$(VSCODE_MIXIN_PASSWORD)"
exec { npm run gulp -- "vscode-win32-$(VSCODE_ARCH)-min" }
exec { npm run gulp -- "vscode-win32-$(VSCODE_ARCH)-inno-updater" }
name: build
- powershell: |
. build/azure-pipelines/win32/exec.ps1
$ErrorActionPreference = "Stop"
exec { npm run gulp -- "electron-$(VSCODE_ARCH)" }
exec { .\scripts\test.bat --build --tfs "Unit Tests" }
# yarn smoketest -- --build "$(agent.builddirectory)\VSCode-win32-$(VSCODE_ARCH)"
name: test
- task: SFP.build-tasks.custom-build-task-1.EsrpCodeSigning@1
inputs:
ConnectedServiceName: 'ESRP CodeSign'
FolderPath: '$(agent.builddirectory)/VSCode-win32-$(VSCODE_ARCH)'
Pattern: '*.dll,*.exe,*.node'
signConfigType: inlineSignParams
inlineOperation: |
[
{
"keyCode": "CP-230012",
"operationSetCode": "SigntoolSign",
"parameters": [
{
"parameterName": "OpusName",
"parameterValue": "VS Code"
},
{
"parameterName": "OpusInfo",
"parameterValue": "https://code.visualstudio.com/"
},
{
"parameterName": "Append",
"parameterValue": "/as"
},
{
"parameterName": "FileDigest",
"parameterValue": "/fd \"SHA256\""
},
{
"parameterName": "PageHash",
"parameterValue": "/NPH"
},
{
"parameterName": "TimeStamp",
"parameterValue": "/tr \"http://rfc3161.gtm.corp.microsoft.com/TSS/HttpTspServer\" /td sha256"
}
],
"toolName": "sign",
"toolVersion": "1.0"
},
{
"keyCode": "CP-230012",
"operationSetCode": "SigntoolVerify",
"parameters": [
{
"parameterName": "VerifyAll",
"parameterValue": "/all"
}
],
"toolName": "sign",
"toolVersion": "1.0"
}
]
SessionTimeout: 120
- task: NuGetCommand@2
displayName: Install ESRPClient.exe
inputs:
restoreSolution: 'build\azure-pipelines\win32\ESRPClient\packages.config'
feedsToUse: config
nugetConfigPath: 'build\azure-pipelines\win32\ESRPClient\NuGet.config'
externalFeedCredentials: 3fc0b7f7-da09-4ae7-a9c8-d69824b1819b
restoreDirectory: packages
- task: ESRPImportCertTask@1
displayName: Import ESRP Request Signing Certificate
inputs:
ESRP: 'ESRP CodeSign'
- powershell: |
$ErrorActionPreference = "Stop"
.\build\azure-pipelines\win32\import-esrp-auth-cert.ps1 -AuthCertificateBase64 $(ESRP_AUTH_CERTIFICATE) -AuthCertificateKey $(ESRP_AUTH_CERTIFICATE_KEY)
displayName: Import ESRP Auth Certificate
- powershell: |
. build/azure-pipelines/win32/exec.ps1
$ErrorActionPreference = "Stop"
exec { npm run gulp -- "vscode-win32-$(VSCODE_ARCH)-archive" "vscode-win32-$(VSCODE_ARCH)-system-setup" "vscode-win32-$(VSCODE_ARCH)-user-setup" --sign }
$Repo = "$(pwd)"
$Root = "$Repo\.."
$SystemExe = "$Repo\.build\win32-$(VSCODE_ARCH)\system-setup\VSCodeSetup.exe"
$UserExe = "$Repo\.build\win32-$(VSCODE_ARCH)\user-setup\VSCodeSetup.exe"
$Zip = "$Repo\.build\win32-$(VSCODE_ARCH)\archive\VSCode-win32-$(VSCODE_ARCH).zip"
$Build = "$Root\VSCode-win32-$(VSCODE_ARCH)"
# get version
$PackageJson = Get-Content -Raw -Path "$Build\resources\app\package.json" | ConvertFrom-Json
$Version = $PackageJson.version
$Quality = "$env:VSCODE_QUALITY"
$env:AZURE_STORAGE_ACCESS_KEY_2 = "$(AZURE_STORAGE_ACCESS_KEY_2)"
$env:MOONCAKE_STORAGE_ACCESS_KEY = "$(MOONCAKE_STORAGE_ACCESS_KEY)"
$env:AZURE_DOCUMENTDB_MASTERKEY = "$(AZURE_DOCUMENTDB_MASTERKEY)"
$assetPlatform = if ("$(VSCODE_ARCH)" -eq "ia32") { "win32" } else { "win32-x64" }
exec { node build/azure-pipelines/common/publish.js $Quality "$global:assetPlatform-archive" archive "VSCode-win32-$(VSCODE_ARCH)-$Version.zip" $Version true $Zip }
exec { node build/azure-pipelines/common/publish.js $Quality "$global:assetPlatform" setup "VSCodeSetup-$(VSCODE_ARCH)-$Version.exe" $Version true $SystemExe }
exec { node build/azure-pipelines/common/publish.js $Quality "$global:assetPlatform-user" setup "VSCodeUserSetup-$(VSCODE_ARCH)-$Version.exe" $Version true $UserExe }
# publish hockeyapp symbols
$hockeyAppId = if ("$(VSCODE_ARCH)" -eq "ia32") { "$(VSCODE_HOCKEYAPP_ID_WIN32)" } else { "$(VSCODE_HOCKEYAPP_ID_WIN64)" }
exec { node build/azure-pipelines/common/symbols.js "$(VSCODE_MIXIN_PASSWORD)" "$(VSCODE_HOCKEYAPP_TOKEN)" "$(VSCODE_ARCH)" $hockeyAppId }
- task: ms.vss-governance-buildtask.governance-build-task-component-detection.ComponentGovernanceComponentDetection@0
displayName: 'Component Detection'
continueOnError: true
| build/azure-pipelines/win32/product-build-win32.yml | 0 | https://github.com/microsoft/vscode/commit/51ef43a02382fb972b15d5b935515b69bb637a3a | [
0.00017817613843362778,
0.00017281860345974565,
0.00016690387565176934,
0.00017335849406663328,
0.0000028876554551970912
] |
{
"id": 6,
"code_window": [
"\t\t\t\t\t\tif (Types.isStringArray(item.options)) {\n",
"\t\t\t\t\t\t\toptions = item.options;\n",
"\t\t\t\t\t\t} else {\n",
"\t\t\t\t\t\t\tthrow new Error(nls.localize('pickRequiresOptions', \"Input '{0}' is of type 'pick' and must include 'options'.\", item.id));\n",
"\t\t\t\t\t\t}\n",
"\t\t\t\t\t}\n",
"\t\t\t\t\tinputs.push({ id: item.id, description: item.description, type, default: item.default, options });\n",
"\t\t\t\t}\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t\t\t\t\tthrow new Error(nls.localize('pickStringRequiresOptions', \"Input '{0}' is of type 'pickString' and must include 'options'.\", item.id));\n"
],
"file_path": "src/vs/workbench/services/configurationResolver/electron-browser/configurationResolverService.ts",
"type": "replace",
"edit_start_line_idx": 320
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { URI as uri } from 'vs/base/common/uri';
import * as nls from 'vs/nls';
import * as paths from 'vs/base/common/paths';
import * as platform from 'vs/base/common/platform';
import * as Objects from 'vs/base/common/objects';
import * as Types from 'vs/base/common/types';
import { Schemas } from 'vs/base/common/network';
import { TPromise } from 'vs/base/common/winjs.base';
import { sequence } from 'vs/base/common/async';
import { toResource } from 'vs/workbench/common/editor';
import { IStringDictionary, forEach, fromMap } from 'vs/base/common/collections';
import { IEnvironmentService } from 'vs/platform/environment/common/environment';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { ICommandService } from 'vs/platform/commands/common/commands';
import { IWorkspaceFolder, IWorkspaceContextService, WorkbenchState } from 'vs/platform/workspace/common/workspace';
import { IEditorService } from 'vs/workbench/services/editor/common/editorService';
import { AbstractVariableResolverService } from 'vs/workbench/services/configurationResolver/node/variableResolver';
import { isCodeEditor } from 'vs/editor/browser/editorBrowser';
import { DiffEditorInput } from 'vs/workbench/common/editor/diffEditorInput';
import { IQuickInputService, IInputOptions, IQuickPickItem, IPickOptions } from 'vs/platform/quickinput/common/quickInput';
import { ConfiguredInput, ConfiguredInputType } from 'vs/workbench/services/configurationResolver/common/configurationResolver';
export class ConfigurationResolverService extends AbstractVariableResolverService {
constructor(
envVariables: platform.IProcessEnvironment,
@IEditorService editorService: IEditorService,
@IEnvironmentService environmentService: IEnvironmentService,
@IConfigurationService private configurationService: IConfigurationService,
@ICommandService private commandService: ICommandService,
@IWorkspaceContextService private workspaceContextService: IWorkspaceContextService,
@IQuickInputService private quickInputService: IQuickInputService
) {
super({
getFolderUri: (folderName: string): uri => {
const folder = workspaceContextService.getWorkspace().folders.filter(f => f.name === folderName).pop();
return folder ? folder.uri : undefined;
},
getWorkspaceFolderCount: (): number => {
return workspaceContextService.getWorkspace().folders.length;
},
getConfigurationValue: (folderUri: uri, suffix: string) => {
return configurationService.getValue<string>(suffix, folderUri ? { resource: folderUri } : undefined);
},
getExecPath: () => {
return environmentService['execPath'];
},
getFilePath: (): string | undefined => {
let activeEditor = editorService.activeEditor;
if (activeEditor instanceof DiffEditorInput) {
activeEditor = activeEditor.modifiedInput;
}
const fileResource = toResource(activeEditor, { filter: Schemas.file });
if (!fileResource) {
return undefined;
}
return paths.normalize(fileResource.fsPath, true);
},
getSelectedText: (): string | undefined => {
const activeTextEditorWidget = editorService.activeTextEditorWidget;
if (isCodeEditor(activeTextEditorWidget)) {
const editorModel = activeTextEditorWidget.getModel();
const editorSelection = activeTextEditorWidget.getSelection();
if (editorModel && editorSelection) {
return editorModel.getValueInRange(editorSelection);
}
}
return undefined;
},
getLineNumber: (): string => {
const activeTextEditorWidget = editorService.activeTextEditorWidget;
if (isCodeEditor(activeTextEditorWidget)) {
const lineNumber = activeTextEditorWidget.getSelection().positionLineNumber;
return String(lineNumber);
}
return undefined;
}
}, envVariables);
}
public resolveWithInteractionReplace(folder: IWorkspaceFolder, config: any, section?: string, variables?: IStringDictionary<string>): TPromise<any> {
// resolve any non-interactive variables
config = this.resolveAny(folder, config);
// resolve input variables in the order in which they are encountered
return this.resolveWithInteraction(folder, config, section, variables).then(mapping => {
// finally substitute evaluated command variables (if there are any)
if (mapping.size > 0) {
return this.resolveAny(folder, config, fromMap(mapping));
} else {
return config;
}
});
}
public resolveWithInteraction(folder: IWorkspaceFolder, config: any, section?: string, variables?: IStringDictionary<string>): TPromise<Map<string, string>> {
// resolve any non-interactive variables
const resolved = this.resolveAnyMap(folder, config);
config = resolved.newConfig;
const allVariableMapping: Map<string, string> = resolved.resolvedVariables;
// resolve input variables in the order in which they are encountered
return this.resolveWithInputs(folder, config, section).then(inputMapping => {
if (!this.updateMapping(inputMapping, allVariableMapping)) {
return undefined;
}
// resolve commands in the order in which they are encountered
return this.resolveWithCommands(config, variables).then(commandMapping => {
if (!this.updateMapping(commandMapping, allVariableMapping)) {
return undefined;
}
return allVariableMapping;
});
});
}
/**
* Add all items from newMapping to fullMapping. Returns false if newMapping is undefined.
*/
private updateMapping(newMapping: IStringDictionary<string>, fullMapping: Map<string, string>): boolean {
if (!newMapping) {
return false;
}
forEach(newMapping, (entry) => {
fullMapping.set(entry.key, entry.value);
});
return true;
}
/**
* Finds and executes all command variables in the given configuration and returns their values as a dictionary.
* Please note: this method does not substitute the command variables (so the configuration is not modified).
* The returned dictionary can be passed to "resolvePlatform" for the substitution.
* See #6569.
* @param configuration
* @param variableToCommandMap Aliases for commands
*/
private resolveWithCommands(configuration: any, variableToCommandMap: IStringDictionary<string>): TPromise<IStringDictionary<string>> {
if (!configuration) {
return TPromise.as(undefined);
}
// use an array to preserve order of first appearance
const cmd_var = /\${command:(.*?)}/g;
const commands: string[] = [];
this.findVariables(cmd_var, configuration, commands);
let cancelled = false;
const commandValueMapping: IStringDictionary<string> = Object.create(null);
const factory: { (): TPromise<any> }[] = commands.map(commandVariable => {
return () => {
let commandId = variableToCommandMap ? variableToCommandMap[commandVariable] : undefined;
if (!commandId) {
// Just launch any command if the interactive variable is not contributed by the adapter #12735
commandId = commandVariable;
}
return this.commandService.executeCommand<string>(commandId, configuration).then(result => {
if (typeof result === 'string') {
commandValueMapping['command:' + commandVariable] = result;
} else if (Types.isUndefinedOrNull(result)) {
cancelled = true;
} else {
throw new Error(nls.localize('stringsOnlySupported', "Command '{0}' did not return a string result. Only strings are supported as results for commands used for variable substitution.", commandVariable));
}
});
};
});
return sequence(factory).then(() => cancelled ? undefined : commandValueMapping);
}
/**
* Resolves all inputs in a configuration and returns a map that maps the unresolved input to the resolved input.
* Does not do replacement of inputs.
* @param folder
* @param config
* @param section
*/
public resolveWithInputs(folder: IWorkspaceFolder, config: any, section: string): Promise<IStringDictionary<string>> {
if (!config) {
return Promise.resolve(undefined);
} else if (folder && section) {
// Get all the possible inputs
let result = this.workspaceContextService.getWorkbenchState() !== WorkbenchState.EMPTY
? Objects.deepClone(this.configurationService.getValue<any>(section, { resource: folder.uri }))
: undefined;
let inputsArray = result ? this.parseConfigurationInputs(result.inputs) : undefined;
const inputs = new Map<string, ConfiguredInput>();
if (inputsArray) {
inputsArray.forEach(input => {
inputs.set(input.id, input);
});
// use an array to preserve order of first appearance
const input_var = /\${input:(.*?)}/g;
const commands: string[] = [];
this.findVariables(input_var, config, commands);
let cancelled = false;
const commandValueMapping: IStringDictionary<string> = Object.create(null);
const factory: { (): Promise<any> }[] = commands.map(commandVariable => {
return () => {
return this.showUserInput(commandVariable, inputs).then(resolvedValue => {
if (resolvedValue) {
commandValueMapping['input:' + commandVariable] = resolvedValue;
}
});
};
}, reason => {
return Promise.reject(reason);
});
return sequence(factory).then(() => cancelled ? undefined : commandValueMapping);
}
}
return Promise.resolve(Object.create(null));
}
/**
* Takes the provided input info and shows the quick pick so the user can provide the value for the input
* @param commandVariable Name of the input.
* @param inputs Information about each possible input.
* @param commandValueMapping
*/
private showUserInput(commandVariable: string, inputs: Map<string, ConfiguredInput>): Promise<string> {
if (inputs && inputs.has(commandVariable)) {
const input = inputs.get(commandVariable);
if (input.type === ConfiguredInputType.Prompt) {
let inputOptions: IInputOptions = { prompt: input.description };
if (input.default) {
inputOptions.value = input.default;
}
return this.quickInputService.input(inputOptions).then(resolvedInput => {
return resolvedInput ? resolvedInput : input.default;
});
} else { // input.type === ConfiguredInputType.pick
let picks = new Array<IQuickPickItem>();
if (input.options) {
input.options.forEach(pickOption => {
let item: IQuickPickItem = { label: pickOption };
if (input.default && (pickOption === input.default)) {
item.description = nls.localize('defaultInputValue', "Default");
picks.unshift(item);
} else {
picks.push(item);
}
});
}
let pickOptions: IPickOptions<IQuickPickItem> = { placeHolder: input.description };
return this.quickInputService.pick(picks, pickOptions, undefined).then(resolvedInput => {
return resolvedInput ? resolvedInput.label : input.default;
});
}
}
return Promise.resolve(undefined);
}
/**
* Finds all variables in object using cmdVar and pushes them into commands.
* @param cmdVar Regex to use for finding variables.
* @param object object is searched for variables.
* @param commands All found variables are returned in commands.
*/
private findVariables(cmdVar: RegExp, object: any, commands: string[]) {
if (!object) {
return;
} else if (typeof object === 'string') {
let matches;
while ((matches = cmdVar.exec(object)) !== null) {
if (matches.length === 2) {
const command = matches[1];
if (commands.indexOf(command) < 0) {
commands.push(command);
}
}
}
} else if (Types.isArray(object)) {
object.forEach(value => {
this.findVariables(cmdVar, value, commands);
});
} else {
Object.keys(object).forEach(key => {
const value = object[key];
this.findVariables(cmdVar, value, commands);
});
}
}
/**
* Converts an array of inputs into an actaul array of typed, ConfiguredInputs.
* @param object Array of something that should look like inputs.
*/
private parseConfigurationInputs(object: any[]): ConfiguredInput[] | undefined {
let inputs = new Array<ConfiguredInput>();
if (object) {
object.forEach(item => {
if (Types.isString(item.id) && Types.isString(item.description) && Types.isString(item.type)) {
let type: ConfiguredInputType;
switch (item.type) {
case 'prompt': type = ConfiguredInputType.Prompt; break;
case 'pick': type = ConfiguredInputType.Pick; break;
default: {
throw new Error(nls.localize('unknownInputTypeProvided', "Input '{0}' can only be of type 'prompt' or 'pick'.", item.id));
}
}
let options: string[];
if (type === ConfiguredInputType.Pick) {
if (Types.isStringArray(item.options)) {
options = item.options;
} else {
throw new Error(nls.localize('pickRequiresOptions', "Input '{0}' is of type 'pick' and must include 'options'.", item.id));
}
}
inputs.push({ id: item.id, description: item.description, type, default: item.default, options });
}
});
}
return inputs;
}
} | src/vs/workbench/services/configurationResolver/electron-browser/configurationResolverService.ts | 1 | https://github.com/microsoft/vscode/commit/51ef43a02382fb972b15d5b935515b69bb637a3a | [
0.9911341071128845,
0.04153480753302574,
0.00016234305803664029,
0.00017121192649938166,
0.1790829598903656
] |
{
"id": 6,
"code_window": [
"\t\t\t\t\t\tif (Types.isStringArray(item.options)) {\n",
"\t\t\t\t\t\t\toptions = item.options;\n",
"\t\t\t\t\t\t} else {\n",
"\t\t\t\t\t\t\tthrow new Error(nls.localize('pickRequiresOptions', \"Input '{0}' is of type 'pick' and must include 'options'.\", item.id));\n",
"\t\t\t\t\t\t}\n",
"\t\t\t\t\t}\n",
"\t\t\t\t\tinputs.push({ id: item.id, description: item.description, type, default: item.default, options });\n",
"\t\t\t\t}\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t\t\t\t\tthrow new Error(nls.localize('pickStringRequiresOptions', \"Input '{0}' is of type 'pickString' and must include 'options'.\", item.id));\n"
],
"file_path": "src/vs/workbench/services/configurationResolver/electron-browser/configurationResolverService.ts",
"type": "replace",
"edit_start_line_idx": 320
} | isUSStandard: true
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
| HW Code combination | Key | KeyCode combination | Pri | UI label | User settings | Electron accelerator | Dispatching string | WYSIWYG |
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
| KeyA | a | A | | A | a | A | [KeyA] | |
| Ctrl+KeyA | a | Ctrl+A | | Ctrl+A | ctrl+a | Ctrl+A | ctrl+[KeyA] | |
| Shift+KeyA | A | Shift+A | | Shift+A | shift+a | Shift+A | shift+[KeyA] | |
| Ctrl+Shift+KeyA | A | Ctrl+Shift+A | | Ctrl+Shift+A | ctrl+shift+a | Ctrl+Shift+A | ctrl+shift+[KeyA] | |
| Alt+KeyA | a | Alt+A | | Alt+A | alt+a | Alt+A | alt+[KeyA] | |
| Ctrl+Alt+KeyA | å | Ctrl+Alt+A | | Ctrl+Alt+A | ctrl+alt+a | Ctrl+Alt+A | ctrl+alt+[KeyA] | |
| Shift+Alt+KeyA | A | Shift+Alt+A | | Shift+Alt+A | shift+alt+a | Shift+Alt+A | shift+alt+[KeyA] | |
| Ctrl+Shift+Alt+KeyA | Å | Ctrl+Shift+Alt+A | | Ctrl+Shift+Alt+A | ctrl+shift+alt+a | Ctrl+Shift+Alt+A | ctrl+shift+alt+[KeyA] | |
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
| KeyB | b | B | | B | b | B | [KeyB] | |
| Ctrl+KeyB | b | Ctrl+B | | Ctrl+B | ctrl+b | Ctrl+B | ctrl+[KeyB] | |
| Shift+KeyB | B | Shift+B | | Shift+B | shift+b | Shift+B | shift+[KeyB] | |
| Ctrl+Shift+KeyB | B | Ctrl+Shift+B | | Ctrl+Shift+B | ctrl+shift+b | Ctrl+Shift+B | ctrl+shift+[KeyB] | |
| Alt+KeyB | b | Alt+B | | Alt+B | alt+b | Alt+B | alt+[KeyB] | |
| Ctrl+Alt+KeyB | ∫ | Ctrl+Alt+B | | Ctrl+Alt+B | ctrl+alt+b | Ctrl+Alt+B | ctrl+alt+[KeyB] | |
| Shift+Alt+KeyB | B | Shift+Alt+B | | Shift+Alt+B | shift+alt+b | Shift+Alt+B | shift+alt+[KeyB] | |
| Ctrl+Shift+Alt+KeyB | ı | Ctrl+Shift+Alt+B | | Ctrl+Shift+Alt+B | ctrl+shift+alt+b | Ctrl+Shift+Alt+B | ctrl+shift+alt+[KeyB] | |
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
| KeyC | c | C | | C | c | C | [KeyC] | |
| Ctrl+KeyC | c | Ctrl+C | | Ctrl+C | ctrl+c | Ctrl+C | ctrl+[KeyC] | |
| Shift+KeyC | C | Shift+C | | Shift+C | shift+c | Shift+C | shift+[KeyC] | |
| Ctrl+Shift+KeyC | C | Ctrl+Shift+C | | Ctrl+Shift+C | ctrl+shift+c | Ctrl+Shift+C | ctrl+shift+[KeyC] | |
| Alt+KeyC | c | Alt+C | | Alt+C | alt+c | Alt+C | alt+[KeyC] | |
| Ctrl+Alt+KeyC | ç | Ctrl+Alt+C | | Ctrl+Alt+C | ctrl+alt+c | Ctrl+Alt+C | ctrl+alt+[KeyC] | |
| Shift+Alt+KeyC | C | Shift+Alt+C | | Shift+Alt+C | shift+alt+c | Shift+Alt+C | shift+alt+[KeyC] | |
| Ctrl+Shift+Alt+KeyC | Ç | Ctrl+Shift+Alt+C | | Ctrl+Shift+Alt+C | ctrl+shift+alt+c | Ctrl+Shift+Alt+C | ctrl+shift+alt+[KeyC] | |
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
| KeyD | d | D | | D | d | D | [KeyD] | |
| Ctrl+KeyD | d | Ctrl+D | | Ctrl+D | ctrl+d | Ctrl+D | ctrl+[KeyD] | |
| Shift+KeyD | D | Shift+D | | Shift+D | shift+d | Shift+D | shift+[KeyD] | |
| Ctrl+Shift+KeyD | D | Ctrl+Shift+D | | Ctrl+Shift+D | ctrl+shift+d | Ctrl+Shift+D | ctrl+shift+[KeyD] | |
| Alt+KeyD | d | Alt+D | | Alt+D | alt+d | Alt+D | alt+[KeyD] | |
| Ctrl+Alt+KeyD | ∂ | Ctrl+Alt+D | | Ctrl+Alt+D | ctrl+alt+d | Ctrl+Alt+D | ctrl+alt+[KeyD] | |
| Shift+Alt+KeyD | D | Shift+Alt+D | | Shift+Alt+D | shift+alt+d | Shift+Alt+D | shift+alt+[KeyD] | |
| Ctrl+Shift+Alt+KeyD | Î | Ctrl+Shift+Alt+D | | Ctrl+Shift+Alt+D | ctrl+shift+alt+d | Ctrl+Shift+Alt+D | ctrl+shift+alt+[KeyD] | |
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
| HW Code combination | Key | KeyCode combination | Pri | UI label | User settings | Electron accelerator | Dispatching string | WYSIWYG |
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
| KeyE | e | E | | E | e | E | [KeyE] | |
| Ctrl+KeyE | e | Ctrl+E | | Ctrl+E | ctrl+e | Ctrl+E | ctrl+[KeyE] | |
| Shift+KeyE | E | Shift+E | | Shift+E | shift+e | Shift+E | shift+[KeyE] | |
| Ctrl+Shift+KeyE | E | Ctrl+Shift+E | | Ctrl+Shift+E | ctrl+shift+e | Ctrl+Shift+E | ctrl+shift+[KeyE] | |
| Alt+KeyE | e | Alt+E | | Alt+E | alt+e | Alt+E | alt+[KeyE] | |
| Ctrl+Alt+KeyE | ´ | Ctrl+Alt+E | | Ctrl+Alt+E | ctrl+alt+e | Ctrl+Alt+E | ctrl+alt+[KeyE] | |
| Shift+Alt+KeyE | E | Shift+Alt+E | | Shift+Alt+E | shift+alt+e | Shift+Alt+E | shift+alt+[KeyE] | |
| Ctrl+Shift+Alt+KeyE | ´ | Ctrl+Shift+Alt+E | | Ctrl+Shift+Alt+E | ctrl+shift+alt+e | Ctrl+Shift+Alt+E | ctrl+shift+alt+[KeyE] | |
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
| KeyF | f | F | | F | f | F | [KeyF] | |
| Ctrl+KeyF | f | Ctrl+F | | Ctrl+F | ctrl+f | Ctrl+F | ctrl+[KeyF] | |
| Shift+KeyF | F | Shift+F | | Shift+F | shift+f | Shift+F | shift+[KeyF] | |
| Ctrl+Shift+KeyF | F | Ctrl+Shift+F | | Ctrl+Shift+F | ctrl+shift+f | Ctrl+Shift+F | ctrl+shift+[KeyF] | |
| Alt+KeyF | f | Alt+F | | Alt+F | alt+f | Alt+F | alt+[KeyF] | |
| Ctrl+Alt+KeyF | ƒ | Ctrl+Alt+F | | Ctrl+Alt+F | ctrl+alt+f | Ctrl+Alt+F | ctrl+alt+[KeyF] | |
| Shift+Alt+KeyF | F | Shift+Alt+F | | Shift+Alt+F | shift+alt+f | Shift+Alt+F | shift+alt+[KeyF] | |
| Ctrl+Shift+Alt+KeyF | Ï | Ctrl+Shift+Alt+F | | Ctrl+Shift+Alt+F | ctrl+shift+alt+f | Ctrl+Shift+Alt+F | ctrl+shift+alt+[KeyF] | |
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
| KeyG | g | G | | G | g | G | [KeyG] | |
| Ctrl+KeyG | g | Ctrl+G | | Ctrl+G | ctrl+g | Ctrl+G | ctrl+[KeyG] | |
| Shift+KeyG | G | Shift+G | | Shift+G | shift+g | Shift+G | shift+[KeyG] | |
| Ctrl+Shift+KeyG | G | Ctrl+Shift+G | | Ctrl+Shift+G | ctrl+shift+g | Ctrl+Shift+G | ctrl+shift+[KeyG] | |
| Alt+KeyG | g | Alt+G | | Alt+G | alt+g | Alt+G | alt+[KeyG] | |
| Ctrl+Alt+KeyG | © | Ctrl+Alt+G | | Ctrl+Alt+G | ctrl+alt+g | Ctrl+Alt+G | ctrl+alt+[KeyG] | |
| Shift+Alt+KeyG | G | Shift+Alt+G | | Shift+Alt+G | shift+alt+g | Shift+Alt+G | shift+alt+[KeyG] | |
| Ctrl+Shift+Alt+KeyG | ˝ | Ctrl+Shift+Alt+G | | Ctrl+Shift+Alt+G | ctrl+shift+alt+g | Ctrl+Shift+Alt+G | ctrl+shift+alt+[KeyG] | |
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
| KeyH | h | H | | H | h | H | [KeyH] | |
| Ctrl+KeyH | h | Ctrl+H | | Ctrl+H | ctrl+h | Ctrl+H | ctrl+[KeyH] | |
| Shift+KeyH | H | Shift+H | | Shift+H | shift+h | Shift+H | shift+[KeyH] | |
| Ctrl+Shift+KeyH | H | Ctrl+Shift+H | | Ctrl+Shift+H | ctrl+shift+h | Ctrl+Shift+H | ctrl+shift+[KeyH] | |
| Alt+KeyH | h | Alt+H | | Alt+H | alt+h | Alt+H | alt+[KeyH] | |
| Ctrl+Alt+KeyH | ˙ | Ctrl+Alt+H | | Ctrl+Alt+H | ctrl+alt+h | Ctrl+Alt+H | ctrl+alt+[KeyH] | |
| Shift+Alt+KeyH | H | Shift+Alt+H | | Shift+Alt+H | shift+alt+h | Shift+Alt+H | shift+alt+[KeyH] | |
| Ctrl+Shift+Alt+KeyH | Ó | Ctrl+Shift+Alt+H | | Ctrl+Shift+Alt+H | ctrl+shift+alt+h | Ctrl+Shift+Alt+H | ctrl+shift+alt+[KeyH] | |
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
| HW Code combination | Key | KeyCode combination | Pri | UI label | User settings | Electron accelerator | Dispatching string | WYSIWYG |
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
| KeyI | i | I | | I | i | I | [KeyI] | |
| Ctrl+KeyI | i | Ctrl+I | | Ctrl+I | ctrl+i | Ctrl+I | ctrl+[KeyI] | |
| Shift+KeyI | I | Shift+I | | Shift+I | shift+i | Shift+I | shift+[KeyI] | |
| Ctrl+Shift+KeyI | I | Ctrl+Shift+I | | Ctrl+Shift+I | ctrl+shift+i | Ctrl+Shift+I | ctrl+shift+[KeyI] | |
| Alt+KeyI | i | Alt+I | | Alt+I | alt+i | Alt+I | alt+[KeyI] | |
| Ctrl+Alt+KeyI | ˆ | Ctrl+Alt+I | | Ctrl+Alt+I | ctrl+alt+i | Ctrl+Alt+I | ctrl+alt+[KeyI] | |
| Shift+Alt+KeyI | I | Shift+Alt+I | | Shift+Alt+I | shift+alt+i | Shift+Alt+I | shift+alt+[KeyI] | |
| Ctrl+Shift+Alt+KeyI | ˆ | Ctrl+Shift+Alt+I | | Ctrl+Shift+Alt+I | ctrl+shift+alt+i | Ctrl+Shift+Alt+I | ctrl+shift+alt+[KeyI] | |
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
| KeyJ | j | J | | J | j | J | [KeyJ] | |
| Ctrl+KeyJ | j | Ctrl+J | | Ctrl+J | ctrl+j | Ctrl+J | ctrl+[KeyJ] | |
| Shift+KeyJ | J | Shift+J | | Shift+J | shift+j | Shift+J | shift+[KeyJ] | |
| Ctrl+Shift+KeyJ | J | Ctrl+Shift+J | | Ctrl+Shift+J | ctrl+shift+j | Ctrl+Shift+J | ctrl+shift+[KeyJ] | |
| Alt+KeyJ | j | Alt+J | | Alt+J | alt+j | Alt+J | alt+[KeyJ] | |
| Ctrl+Alt+KeyJ | ∆ | Ctrl+Alt+J | | Ctrl+Alt+J | ctrl+alt+j | Ctrl+Alt+J | ctrl+alt+[KeyJ] | |
| Shift+Alt+KeyJ | J | Shift+Alt+J | | Shift+Alt+J | shift+alt+j | Shift+Alt+J | shift+alt+[KeyJ] | |
| Ctrl+Shift+Alt+KeyJ | Ô | Ctrl+Shift+Alt+J | | Ctrl+Shift+Alt+J | ctrl+shift+alt+j | Ctrl+Shift+Alt+J | ctrl+shift+alt+[KeyJ] | |
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
| KeyK | k | K | | K | k | K | [KeyK] | |
| Ctrl+KeyK | k | Ctrl+K | | Ctrl+K | ctrl+k | Ctrl+K | ctrl+[KeyK] | |
| Shift+KeyK | K | Shift+K | | Shift+K | shift+k | Shift+K | shift+[KeyK] | |
| Ctrl+Shift+KeyK | K | Ctrl+Shift+K | | Ctrl+Shift+K | ctrl+shift+k | Ctrl+Shift+K | ctrl+shift+[KeyK] | |
| Alt+KeyK | k | Alt+K | | Alt+K | alt+k | Alt+K | alt+[KeyK] | |
| Ctrl+Alt+KeyK | ˚ | Ctrl+Alt+K | | Ctrl+Alt+K | ctrl+alt+k | Ctrl+Alt+K | ctrl+alt+[KeyK] | |
| Shift+Alt+KeyK | K | Shift+Alt+K | | Shift+Alt+K | shift+alt+k | Shift+Alt+K | shift+alt+[KeyK] | |
| Ctrl+Shift+Alt+KeyK | | Ctrl+Shift+Alt+K | | Ctrl+Shift+Alt+K | ctrl+shift+alt+k | Ctrl+Shift+Alt+K | ctrl+shift+alt+[KeyK] | |
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
| KeyL | l | L | | L | l | L | [KeyL] | |
| Ctrl+KeyL | l | Ctrl+L | | Ctrl+L | ctrl+l | Ctrl+L | ctrl+[KeyL] | |
| Shift+KeyL | L | Shift+L | | Shift+L | shift+l | Shift+L | shift+[KeyL] | |
| Ctrl+Shift+KeyL | L | Ctrl+Shift+L | | Ctrl+Shift+L | ctrl+shift+l | Ctrl+Shift+L | ctrl+shift+[KeyL] | |
| Alt+KeyL | l | Alt+L | | Alt+L | alt+l | Alt+L | alt+[KeyL] | |
| Ctrl+Alt+KeyL | ¬ | Ctrl+Alt+L | | Ctrl+Alt+L | ctrl+alt+l | Ctrl+Alt+L | ctrl+alt+[KeyL] | |
| Shift+Alt+KeyL | L | Shift+Alt+L | | Shift+Alt+L | shift+alt+l | Shift+Alt+L | shift+alt+[KeyL] | |
| Ctrl+Shift+Alt+KeyL | Ò | Ctrl+Shift+Alt+L | | Ctrl+Shift+Alt+L | ctrl+shift+alt+l | Ctrl+Shift+Alt+L | ctrl+shift+alt+[KeyL] | |
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
| HW Code combination | Key | KeyCode combination | Pri | UI label | User settings | Electron accelerator | Dispatching string | WYSIWYG |
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
| KeyM | m | M | | M | m | M | [KeyM] | |
| Ctrl+KeyM | m | Ctrl+M | | Ctrl+M | ctrl+m | Ctrl+M | ctrl+[KeyM] | |
| Shift+KeyM | M | Shift+M | | Shift+M | shift+m | Shift+M | shift+[KeyM] | |
| Ctrl+Shift+KeyM | M | Ctrl+Shift+M | | Ctrl+Shift+M | ctrl+shift+m | Ctrl+Shift+M | ctrl+shift+[KeyM] | |
| Alt+KeyM | m | Alt+M | | Alt+M | alt+m | Alt+M | alt+[KeyM] | |
| Ctrl+Alt+KeyM | µ | Ctrl+Alt+M | | Ctrl+Alt+M | ctrl+alt+m | Ctrl+Alt+M | ctrl+alt+[KeyM] | |
| Shift+Alt+KeyM | M | Shift+Alt+M | | Shift+Alt+M | shift+alt+m | Shift+Alt+M | shift+alt+[KeyM] | |
| Ctrl+Shift+Alt+KeyM | Â | Ctrl+Shift+Alt+M | | Ctrl+Shift+Alt+M | ctrl+shift+alt+m | Ctrl+Shift+Alt+M | ctrl+shift+alt+[KeyM] | |
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
| KeyN | n | N | | N | n | N | [KeyN] | |
| Ctrl+KeyN | n | Ctrl+N | | Ctrl+N | ctrl+n | Ctrl+N | ctrl+[KeyN] | |
| Shift+KeyN | N | Shift+N | | Shift+N | shift+n | Shift+N | shift+[KeyN] | |
| Ctrl+Shift+KeyN | N | Ctrl+Shift+N | | Ctrl+Shift+N | ctrl+shift+n | Ctrl+Shift+N | ctrl+shift+[KeyN] | |
| Alt+KeyN | n | Alt+N | | Alt+N | alt+n | Alt+N | alt+[KeyN] | |
| Ctrl+Alt+KeyN | ˜ | Ctrl+Alt+N | | Ctrl+Alt+N | ctrl+alt+n | Ctrl+Alt+N | ctrl+alt+[KeyN] | |
| Shift+Alt+KeyN | N | Shift+Alt+N | | Shift+Alt+N | shift+alt+n | Shift+Alt+N | shift+alt+[KeyN] | |
| Ctrl+Shift+Alt+KeyN | ˜ | Ctrl+Shift+Alt+N | | Ctrl+Shift+Alt+N | ctrl+shift+alt+n | Ctrl+Shift+Alt+N | ctrl+shift+alt+[KeyN] | |
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
| KeyO | o | O | | O | o | O | [KeyO] | |
| Ctrl+KeyO | o | Ctrl+O | | Ctrl+O | ctrl+o | Ctrl+O | ctrl+[KeyO] | |
| Shift+KeyO | O | Shift+O | | Shift+O | shift+o | Shift+O | shift+[KeyO] | |
| Ctrl+Shift+KeyO | O | Ctrl+Shift+O | | Ctrl+Shift+O | ctrl+shift+o | Ctrl+Shift+O | ctrl+shift+[KeyO] | |
| Alt+KeyO | o | Alt+O | | Alt+O | alt+o | Alt+O | alt+[KeyO] | |
| Ctrl+Alt+KeyO | ø | Ctrl+Alt+O | | Ctrl+Alt+O | ctrl+alt+o | Ctrl+Alt+O | ctrl+alt+[KeyO] | |
| Shift+Alt+KeyO | O | Shift+Alt+O | | Shift+Alt+O | shift+alt+o | Shift+Alt+O | shift+alt+[KeyO] | |
| Ctrl+Shift+Alt+KeyO | Ø | Ctrl+Shift+Alt+O | | Ctrl+Shift+Alt+O | ctrl+shift+alt+o | Ctrl+Shift+Alt+O | ctrl+shift+alt+[KeyO] | |
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
| KeyP | p | P | | P | p | P | [KeyP] | |
| Ctrl+KeyP | p | Ctrl+P | | Ctrl+P | ctrl+p | Ctrl+P | ctrl+[KeyP] | |
| Shift+KeyP | P | Shift+P | | Shift+P | shift+p | Shift+P | shift+[KeyP] | |
| Ctrl+Shift+KeyP | P | Ctrl+Shift+P | | Ctrl+Shift+P | ctrl+shift+p | Ctrl+Shift+P | ctrl+shift+[KeyP] | |
| Alt+KeyP | p | Alt+P | | Alt+P | alt+p | Alt+P | alt+[KeyP] | |
| Ctrl+Alt+KeyP | π | Ctrl+Alt+P | | Ctrl+Alt+P | ctrl+alt+p | Ctrl+Alt+P | ctrl+alt+[KeyP] | |
| Shift+Alt+KeyP | P | Shift+Alt+P | | Shift+Alt+P | shift+alt+p | Shift+Alt+P | shift+alt+[KeyP] | |
| Ctrl+Shift+Alt+KeyP | ∏ | Ctrl+Shift+Alt+P | | Ctrl+Shift+Alt+P | ctrl+shift+alt+p | Ctrl+Shift+Alt+P | ctrl+shift+alt+[KeyP] | |
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
| HW Code combination | Key | KeyCode combination | Pri | UI label | User settings | Electron accelerator | Dispatching string | WYSIWYG |
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
| KeyQ | q | Q | | Q | q | Q | [KeyQ] | |
| Ctrl+KeyQ | q | Ctrl+Q | | Ctrl+Q | ctrl+q | Ctrl+Q | ctrl+[KeyQ] | |
| Shift+KeyQ | Q | Shift+Q | | Shift+Q | shift+q | Shift+Q | shift+[KeyQ] | |
| Ctrl+Shift+KeyQ | Q | Ctrl+Shift+Q | | Ctrl+Shift+Q | ctrl+shift+q | Ctrl+Shift+Q | ctrl+shift+[KeyQ] | |
| Alt+KeyQ | q | Alt+Q | | Alt+Q | alt+q | Alt+Q | alt+[KeyQ] | |
| Ctrl+Alt+KeyQ | œ | Ctrl+Alt+Q | | Ctrl+Alt+Q | ctrl+alt+q | Ctrl+Alt+Q | ctrl+alt+[KeyQ] | |
| Shift+Alt+KeyQ | Q | Shift+Alt+Q | | Shift+Alt+Q | shift+alt+q | Shift+Alt+Q | shift+alt+[KeyQ] | |
| Ctrl+Shift+Alt+KeyQ | Œ | Ctrl+Shift+Alt+Q | | Ctrl+Shift+Alt+Q | ctrl+shift+alt+q | Ctrl+Shift+Alt+Q | ctrl+shift+alt+[KeyQ] | |
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
| KeyR | r | R | | R | r | R | [KeyR] | |
| Ctrl+KeyR | r | Ctrl+R | | Ctrl+R | ctrl+r | Ctrl+R | ctrl+[KeyR] | |
| Shift+KeyR | R | Shift+R | | Shift+R | shift+r | Shift+R | shift+[KeyR] | |
| Ctrl+Shift+KeyR | R | Ctrl+Shift+R | | Ctrl+Shift+R | ctrl+shift+r | Ctrl+Shift+R | ctrl+shift+[KeyR] | |
| Alt+KeyR | r | Alt+R | | Alt+R | alt+r | Alt+R | alt+[KeyR] | |
| Ctrl+Alt+KeyR | ® | Ctrl+Alt+R | | Ctrl+Alt+R | ctrl+alt+r | Ctrl+Alt+R | ctrl+alt+[KeyR] | |
| Shift+Alt+KeyR | R | Shift+Alt+R | | Shift+Alt+R | shift+alt+r | Shift+Alt+R | shift+alt+[KeyR] | |
| Ctrl+Shift+Alt+KeyR | ‰ | Ctrl+Shift+Alt+R | | Ctrl+Shift+Alt+R | ctrl+shift+alt+r | Ctrl+Shift+Alt+R | ctrl+shift+alt+[KeyR] | |
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
| KeyS | s | S | | S | s | S | [KeyS] | |
| Ctrl+KeyS | s | Ctrl+S | | Ctrl+S | ctrl+s | Ctrl+S | ctrl+[KeyS] | |
| Shift+KeyS | S | Shift+S | | Shift+S | shift+s | Shift+S | shift+[KeyS] | |
| Ctrl+Shift+KeyS | S | Ctrl+Shift+S | | Ctrl+Shift+S | ctrl+shift+s | Ctrl+Shift+S | ctrl+shift+[KeyS] | |
| Alt+KeyS | s | Alt+S | | Alt+S | alt+s | Alt+S | alt+[KeyS] | |
| Ctrl+Alt+KeyS | ß | Ctrl+Alt+S | | Ctrl+Alt+S | ctrl+alt+s | Ctrl+Alt+S | ctrl+alt+[KeyS] | |
| Shift+Alt+KeyS | S | Shift+Alt+S | | Shift+Alt+S | shift+alt+s | Shift+Alt+S | shift+alt+[KeyS] | |
| Ctrl+Shift+Alt+KeyS | Í | Ctrl+Shift+Alt+S | | Ctrl+Shift+Alt+S | ctrl+shift+alt+s | Ctrl+Shift+Alt+S | ctrl+shift+alt+[KeyS] | |
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
| KeyT | t | T | | T | t | T | [KeyT] | |
| Ctrl+KeyT | t | Ctrl+T | | Ctrl+T | ctrl+t | Ctrl+T | ctrl+[KeyT] | |
| Shift+KeyT | T | Shift+T | | Shift+T | shift+t | Shift+T | shift+[KeyT] | |
| Ctrl+Shift+KeyT | T | Ctrl+Shift+T | | Ctrl+Shift+T | ctrl+shift+t | Ctrl+Shift+T | ctrl+shift+[KeyT] | |
| Alt+KeyT | t | Alt+T | | Alt+T | alt+t | Alt+T | alt+[KeyT] | |
| Ctrl+Alt+KeyT | † | Ctrl+Alt+T | | Ctrl+Alt+T | ctrl+alt+t | Ctrl+Alt+T | ctrl+alt+[KeyT] | |
| Shift+Alt+KeyT | T | Shift+Alt+T | | Shift+Alt+T | shift+alt+t | Shift+Alt+T | shift+alt+[KeyT] | |
| Ctrl+Shift+Alt+KeyT | ˇ | Ctrl+Shift+Alt+T | | Ctrl+Shift+Alt+T | ctrl+shift+alt+t | Ctrl+Shift+Alt+T | ctrl+shift+alt+[KeyT] | |
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
| HW Code combination | Key | KeyCode combination | Pri | UI label | User settings | Electron accelerator | Dispatching string | WYSIWYG |
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
| KeyU | u | U | | U | u | U | [KeyU] | |
| Ctrl+KeyU | u | Ctrl+U | | Ctrl+U | ctrl+u | Ctrl+U | ctrl+[KeyU] | |
| Shift+KeyU | U | Shift+U | | Shift+U | shift+u | Shift+U | shift+[KeyU] | |
| Ctrl+Shift+KeyU | U | Ctrl+Shift+U | | Ctrl+Shift+U | ctrl+shift+u | Ctrl+Shift+U | ctrl+shift+[KeyU] | |
| Alt+KeyU | u | Alt+U | | Alt+U | alt+u | Alt+U | alt+[KeyU] | |
| Ctrl+Alt+KeyU | ¨ | Ctrl+Alt+U | | Ctrl+Alt+U | ctrl+alt+u | Ctrl+Alt+U | ctrl+alt+[KeyU] | |
| Shift+Alt+KeyU | U | Shift+Alt+U | | Shift+Alt+U | shift+alt+u | Shift+Alt+U | shift+alt+[KeyU] | |
| Ctrl+Shift+Alt+KeyU | ¨ | Ctrl+Shift+Alt+U | | Ctrl+Shift+Alt+U | ctrl+shift+alt+u | Ctrl+Shift+Alt+U | ctrl+shift+alt+[KeyU] | |
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
| KeyV | v | V | | V | v | V | [KeyV] | |
| Ctrl+KeyV | v | Ctrl+V | | Ctrl+V | ctrl+v | Ctrl+V | ctrl+[KeyV] | |
| Shift+KeyV | V | Shift+V | | Shift+V | shift+v | Shift+V | shift+[KeyV] | |
| Ctrl+Shift+KeyV | V | Ctrl+Shift+V | | Ctrl+Shift+V | ctrl+shift+v | Ctrl+Shift+V | ctrl+shift+[KeyV] | |
| Alt+KeyV | v | Alt+V | | Alt+V | alt+v | Alt+V | alt+[KeyV] | |
| Ctrl+Alt+KeyV | √ | Ctrl+Alt+V | | Ctrl+Alt+V | ctrl+alt+v | Ctrl+Alt+V | ctrl+alt+[KeyV] | |
| Shift+Alt+KeyV | V | Shift+Alt+V | | Shift+Alt+V | shift+alt+v | Shift+Alt+V | shift+alt+[KeyV] | |
| Ctrl+Shift+Alt+KeyV | ◊ | Ctrl+Shift+Alt+V | | Ctrl+Shift+Alt+V | ctrl+shift+alt+v | Ctrl+Shift+Alt+V | ctrl+shift+alt+[KeyV] | |
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
| KeyW | w | W | | W | w | W | [KeyW] | |
| Ctrl+KeyW | w | Ctrl+W | | Ctrl+W | ctrl+w | Ctrl+W | ctrl+[KeyW] | |
| Shift+KeyW | W | Shift+W | | Shift+W | shift+w | Shift+W | shift+[KeyW] | |
| Ctrl+Shift+KeyW | W | Ctrl+Shift+W | | Ctrl+Shift+W | ctrl+shift+w | Ctrl+Shift+W | ctrl+shift+[KeyW] | |
| Alt+KeyW | w | Alt+W | | Alt+W | alt+w | Alt+W | alt+[KeyW] | |
| Ctrl+Alt+KeyW | ∑ | Ctrl+Alt+W | | Ctrl+Alt+W | ctrl+alt+w | Ctrl+Alt+W | ctrl+alt+[KeyW] | |
| Shift+Alt+KeyW | W | Shift+Alt+W | | Shift+Alt+W | shift+alt+w | Shift+Alt+W | shift+alt+[KeyW] | |
| Ctrl+Shift+Alt+KeyW | „ | Ctrl+Shift+Alt+W | | Ctrl+Shift+Alt+W | ctrl+shift+alt+w | Ctrl+Shift+Alt+W | ctrl+shift+alt+[KeyW] | |
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
| KeyX | x | X | | X | x | X | [KeyX] | |
| Ctrl+KeyX | x | Ctrl+X | | Ctrl+X | ctrl+x | Ctrl+X | ctrl+[KeyX] | |
| Shift+KeyX | X | Shift+X | | Shift+X | shift+x | Shift+X | shift+[KeyX] | |
| Ctrl+Shift+KeyX | X | Ctrl+Shift+X | | Ctrl+Shift+X | ctrl+shift+x | Ctrl+Shift+X | ctrl+shift+[KeyX] | |
| Alt+KeyX | x | Alt+X | | Alt+X | alt+x | Alt+X | alt+[KeyX] | |
| Ctrl+Alt+KeyX | ≈ | Ctrl+Alt+X | | Ctrl+Alt+X | ctrl+alt+x | Ctrl+Alt+X | ctrl+alt+[KeyX] | |
| Shift+Alt+KeyX | X | Shift+Alt+X | | Shift+Alt+X | shift+alt+x | Shift+Alt+X | shift+alt+[KeyX] | |
| Ctrl+Shift+Alt+KeyX | ˛ | Ctrl+Shift+Alt+X | | Ctrl+Shift+Alt+X | ctrl+shift+alt+x | Ctrl+Shift+Alt+X | ctrl+shift+alt+[KeyX] | |
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
| HW Code combination | Key | KeyCode combination | Pri | UI label | User settings | Electron accelerator | Dispatching string | WYSIWYG |
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
| KeyY | y | Y | | Y | y | Y | [KeyY] | |
| Ctrl+KeyY | y | Ctrl+Y | | Ctrl+Y | ctrl+y | Ctrl+Y | ctrl+[KeyY] | |
| Shift+KeyY | Y | Shift+Y | | Shift+Y | shift+y | Shift+Y | shift+[KeyY] | |
| Ctrl+Shift+KeyY | Y | Ctrl+Shift+Y | | Ctrl+Shift+Y | ctrl+shift+y | Ctrl+Shift+Y | ctrl+shift+[KeyY] | |
| Alt+KeyY | y | Alt+Y | | Alt+Y | alt+y | Alt+Y | alt+[KeyY] | |
| Ctrl+Alt+KeyY | ¥ | Ctrl+Alt+Y | | Ctrl+Alt+Y | ctrl+alt+y | Ctrl+Alt+Y | ctrl+alt+[KeyY] | |
| Shift+Alt+KeyY | Y | Shift+Alt+Y | | Shift+Alt+Y | shift+alt+y | Shift+Alt+Y | shift+alt+[KeyY] | |
| Ctrl+Shift+Alt+KeyY | Á | Ctrl+Shift+Alt+Y | | Ctrl+Shift+Alt+Y | ctrl+shift+alt+y | Ctrl+Shift+Alt+Y | ctrl+shift+alt+[KeyY] | |
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
| KeyZ | z | Z | | Z | z | Z | [KeyZ] | |
| Ctrl+KeyZ | z | Ctrl+Z | | Ctrl+Z | ctrl+z | Ctrl+Z | ctrl+[KeyZ] | |
| Shift+KeyZ | Z | Shift+Z | | Shift+Z | shift+z | Shift+Z | shift+[KeyZ] | |
| Ctrl+Shift+KeyZ | Z | Ctrl+Shift+Z | | Ctrl+Shift+Z | ctrl+shift+z | Ctrl+Shift+Z | ctrl+shift+[KeyZ] | |
| Alt+KeyZ | z | Alt+Z | | Alt+Z | alt+z | Alt+Z | alt+[KeyZ] | |
| Ctrl+Alt+KeyZ | Ω | Ctrl+Alt+Z | | Ctrl+Alt+Z | ctrl+alt+z | Ctrl+Alt+Z | ctrl+alt+[KeyZ] | |
| Shift+Alt+KeyZ | Z | Shift+Alt+Z | | Shift+Alt+Z | shift+alt+z | Shift+Alt+Z | shift+alt+[KeyZ] | |
| Ctrl+Shift+Alt+KeyZ | ¸ | Ctrl+Shift+Alt+Z | | Ctrl+Shift+Alt+Z | ctrl+shift+alt+z | Ctrl+Shift+Alt+Z | ctrl+shift+alt+[KeyZ] | |
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
| Digit1 | 1 | 1 | | 1 | 1 | 1 | [Digit1] | |
| Ctrl+Digit1 | 1 | Ctrl+1 | | Ctrl+1 | ctrl+1 | Ctrl+1 | ctrl+[Digit1] | |
| Shift+Digit1 | ! | Shift+1 | | Shift+1 | shift+1 | Shift+1 | shift+[Digit1] | |
| Ctrl+Shift+Digit1 | ! | Ctrl+Shift+1 | | Ctrl+Shift+1 | ctrl+shift+1 | Ctrl+Shift+1 | ctrl+shift+[Digit1] | |
| Alt+Digit1 | 1 | Alt+1 | | Alt+1 | alt+1 | Alt+1 | alt+[Digit1] | |
| Ctrl+Alt+Digit1 | ¡ | Ctrl+Alt+1 | | Ctrl+Alt+1 | ctrl+alt+1 | Ctrl+Alt+1 | ctrl+alt+[Digit1] | |
| Shift+Alt+Digit1 | ! | Shift+Alt+1 | | Shift+Alt+1 | shift+alt+1 | Shift+Alt+1 | shift+alt+[Digit1] | |
| Ctrl+Shift+Alt+Digit1 | ⁄ | Ctrl+Shift+Alt+1 | | Ctrl+Shift+Alt+1 | ctrl+shift+alt+1 | Ctrl+Shift+Alt+1 | ctrl+shift+alt+[Digit1] | |
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
| Digit2 | 2 | 2 | | 2 | 2 | 2 | [Digit2] | |
| Ctrl+Digit2 | 2 | Ctrl+2 | | Ctrl+2 | ctrl+2 | Ctrl+2 | ctrl+[Digit2] | |
| Shift+Digit2 | @ | Shift+2 | | Shift+2 | shift+2 | Shift+2 | shift+[Digit2] | |
| Ctrl+Shift+Digit2 | @ | Ctrl+Shift+2 | | Ctrl+Shift+2 | ctrl+shift+2 | Ctrl+Shift+2 | ctrl+shift+[Digit2] | |
| Alt+Digit2 | 2 | Alt+2 | | Alt+2 | alt+2 | Alt+2 | alt+[Digit2] | |
| Ctrl+Alt+Digit2 | ™ | Ctrl+Alt+2 | | Ctrl+Alt+2 | ctrl+alt+2 | Ctrl+Alt+2 | ctrl+alt+[Digit2] | |
| Shift+Alt+Digit2 | @ | Shift+Alt+2 | | Shift+Alt+2 | shift+alt+2 | Shift+Alt+2 | shift+alt+[Digit2] | |
| Ctrl+Shift+Alt+Digit2 | € | Ctrl+Shift+Alt+2 | | Ctrl+Shift+Alt+2 | ctrl+shift+alt+2 | Ctrl+Shift+Alt+2 | ctrl+shift+alt+[Digit2] | |
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
| HW Code combination | Key | KeyCode combination | Pri | UI label | User settings | Electron accelerator | Dispatching string | WYSIWYG |
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
| Digit3 | 3 | 3 | | 3 | 3 | 3 | [Digit3] | |
| Ctrl+Digit3 | 3 | Ctrl+3 | | Ctrl+3 | ctrl+3 | Ctrl+3 | ctrl+[Digit3] | |
| Shift+Digit3 | # | Shift+3 | | Shift+3 | shift+3 | Shift+3 | shift+[Digit3] | |
| Ctrl+Shift+Digit3 | # | Ctrl+Shift+3 | | Ctrl+Shift+3 | ctrl+shift+3 | Ctrl+Shift+3 | ctrl+shift+[Digit3] | |
| Alt+Digit3 | 3 | Alt+3 | | Alt+3 | alt+3 | Alt+3 | alt+[Digit3] | |
| Ctrl+Alt+Digit3 | £ | Ctrl+Alt+3 | | Ctrl+Alt+3 | ctrl+alt+3 | Ctrl+Alt+3 | ctrl+alt+[Digit3] | |
| Shift+Alt+Digit3 | # | Shift+Alt+3 | | Shift+Alt+3 | shift+alt+3 | Shift+Alt+3 | shift+alt+[Digit3] | |
| Ctrl+Shift+Alt+Digit3 | ‹ | Ctrl+Shift+Alt+3 | | Ctrl+Shift+Alt+3 | ctrl+shift+alt+3 | Ctrl+Shift+Alt+3 | ctrl+shift+alt+[Digit3] | |
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
| Digit4 | 4 | 4 | | 4 | 4 | 4 | [Digit4] | |
| Ctrl+Digit4 | 4 | Ctrl+4 | | Ctrl+4 | ctrl+4 | Ctrl+4 | ctrl+[Digit4] | |
| Shift+Digit4 | $ | Shift+4 | | Shift+4 | shift+4 | Shift+4 | shift+[Digit4] | |
| Ctrl+Shift+Digit4 | $ | Ctrl+Shift+4 | | Ctrl+Shift+4 | ctrl+shift+4 | Ctrl+Shift+4 | ctrl+shift+[Digit4] | |
| Alt+Digit4 | 4 | Alt+4 | | Alt+4 | alt+4 | Alt+4 | alt+[Digit4] | |
| Ctrl+Alt+Digit4 | ¢ | Ctrl+Alt+4 | | Ctrl+Alt+4 | ctrl+alt+4 | Ctrl+Alt+4 | ctrl+alt+[Digit4] | |
| Shift+Alt+Digit4 | $ | Shift+Alt+4 | | Shift+Alt+4 | shift+alt+4 | Shift+Alt+4 | shift+alt+[Digit4] | |
| Ctrl+Shift+Alt+Digit4 | › | Ctrl+Shift+Alt+4 | | Ctrl+Shift+Alt+4 | ctrl+shift+alt+4 | Ctrl+Shift+Alt+4 | ctrl+shift+alt+[Digit4] | |
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
| Digit5 | 5 | 5 | | 5 | 5 | 5 | [Digit5] | |
| Ctrl+Digit5 | 5 | Ctrl+5 | | Ctrl+5 | ctrl+5 | Ctrl+5 | ctrl+[Digit5] | |
| Shift+Digit5 | % | Shift+5 | | Shift+5 | shift+5 | Shift+5 | shift+[Digit5] | |
| Ctrl+Shift+Digit5 | % | Ctrl+Shift+5 | | Ctrl+Shift+5 | ctrl+shift+5 | Ctrl+Shift+5 | ctrl+shift+[Digit5] | |
| Alt+Digit5 | 5 | Alt+5 | | Alt+5 | alt+5 | Alt+5 | alt+[Digit5] | |
| Ctrl+Alt+Digit5 | ∞ | Ctrl+Alt+5 | | Ctrl+Alt+5 | ctrl+alt+5 | Ctrl+Alt+5 | ctrl+alt+[Digit5] | |
| Shift+Alt+Digit5 | % | Shift+Alt+5 | | Shift+Alt+5 | shift+alt+5 | Shift+Alt+5 | shift+alt+[Digit5] | |
| Ctrl+Shift+Alt+Digit5 | fi | Ctrl+Shift+Alt+5 | | Ctrl+Shift+Alt+5 | ctrl+shift+alt+5 | Ctrl+Shift+Alt+5 | ctrl+shift+alt+[Digit5] | |
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
| Digit6 | 6 | 6 | | 6 | 6 | 6 | [Digit6] | |
| Ctrl+Digit6 | 6 | Ctrl+6 | | Ctrl+6 | ctrl+6 | Ctrl+6 | ctrl+[Digit6] | |
| Shift+Digit6 | ^ | Shift+6 | | Shift+6 | shift+6 | Shift+6 | shift+[Digit6] | |
| Ctrl+Shift+Digit6 | ^ | Ctrl+Shift+6 | | Ctrl+Shift+6 | ctrl+shift+6 | Ctrl+Shift+6 | ctrl+shift+[Digit6] | |
| Alt+Digit6 | 6 | Alt+6 | | Alt+6 | alt+6 | Alt+6 | alt+[Digit6] | |
| Ctrl+Alt+Digit6 | § | Ctrl+Alt+6 | | Ctrl+Alt+6 | ctrl+alt+6 | Ctrl+Alt+6 | ctrl+alt+[Digit6] | |
| Shift+Alt+Digit6 | ^ | Shift+Alt+6 | | Shift+Alt+6 | shift+alt+6 | Shift+Alt+6 | shift+alt+[Digit6] | |
| Ctrl+Shift+Alt+Digit6 | fl | Ctrl+Shift+Alt+6 | | Ctrl+Shift+Alt+6 | ctrl+shift+alt+6 | Ctrl+Shift+Alt+6 | ctrl+shift+alt+[Digit6] | |
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
| HW Code combination | Key | KeyCode combination | Pri | UI label | User settings | Electron accelerator | Dispatching string | WYSIWYG |
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
| Digit7 | 7 | 7 | | 7 | 7 | 7 | [Digit7] | |
| Ctrl+Digit7 | 7 | Ctrl+7 | | Ctrl+7 | ctrl+7 | Ctrl+7 | ctrl+[Digit7] | |
| Shift+Digit7 | & | Shift+7 | | Shift+7 | shift+7 | Shift+7 | shift+[Digit7] | |
| Ctrl+Shift+Digit7 | & | Ctrl+Shift+7 | | Ctrl+Shift+7 | ctrl+shift+7 | Ctrl+Shift+7 | ctrl+shift+[Digit7] | |
| Alt+Digit7 | 7 | Alt+7 | | Alt+7 | alt+7 | Alt+7 | alt+[Digit7] | |
| Ctrl+Alt+Digit7 | ¶ | Ctrl+Alt+7 | | Ctrl+Alt+7 | ctrl+alt+7 | Ctrl+Alt+7 | ctrl+alt+[Digit7] | |
| Shift+Alt+Digit7 | & | Shift+Alt+7 | | Shift+Alt+7 | shift+alt+7 | Shift+Alt+7 | shift+alt+[Digit7] | |
| Ctrl+Shift+Alt+Digit7 | ‡ | Ctrl+Shift+Alt+7 | | Ctrl+Shift+Alt+7 | ctrl+shift+alt+7 | Ctrl+Shift+Alt+7 | ctrl+shift+alt+[Digit7] | |
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
| Digit8 | 8 | 8 | | 8 | 8 | 8 | [Digit8] | |
| Ctrl+Digit8 | 8 | Ctrl+8 | | Ctrl+8 | ctrl+8 | Ctrl+8 | ctrl+[Digit8] | |
| Shift+Digit8 | * | Shift+8 | | Shift+8 | shift+8 | Shift+8 | shift+[Digit8] | |
| Ctrl+Shift+Digit8 | * | Ctrl+Shift+8 | | Ctrl+Shift+8 | ctrl+shift+8 | Ctrl+Shift+8 | ctrl+shift+[Digit8] | |
| Alt+Digit8 | 8 | Alt+8 | | Alt+8 | alt+8 | Alt+8 | alt+[Digit8] | |
| Ctrl+Alt+Digit8 | • | Ctrl+Alt+8 | | Ctrl+Alt+8 | ctrl+alt+8 | Ctrl+Alt+8 | ctrl+alt+[Digit8] | |
| Shift+Alt+Digit8 | * | Shift+Alt+8 | | Shift+Alt+8 | shift+alt+8 | Shift+Alt+8 | shift+alt+[Digit8] | |
| Ctrl+Shift+Alt+Digit8 | ° | Ctrl+Shift+Alt+8 | | Ctrl+Shift+Alt+8 | ctrl+shift+alt+8 | Ctrl+Shift+Alt+8 | ctrl+shift+alt+[Digit8] | |
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
| Digit9 | 9 | 9 | | 9 | 9 | 9 | [Digit9] | |
| Ctrl+Digit9 | 9 | Ctrl+9 | | Ctrl+9 | ctrl+9 | Ctrl+9 | ctrl+[Digit9] | |
| Shift+Digit9 | ( | Shift+9 | | Shift+9 | shift+9 | Shift+9 | shift+[Digit9] | |
| Ctrl+Shift+Digit9 | ( | Ctrl+Shift+9 | | Ctrl+Shift+9 | ctrl+shift+9 | Ctrl+Shift+9 | ctrl+shift+[Digit9] | |
| Alt+Digit9 | 9 | Alt+9 | | Alt+9 | alt+9 | Alt+9 | alt+[Digit9] | |
| Ctrl+Alt+Digit9 | ª | Ctrl+Alt+9 | | Ctrl+Alt+9 | ctrl+alt+9 | Ctrl+Alt+9 | ctrl+alt+[Digit9] | |
| Shift+Alt+Digit9 | ( | Shift+Alt+9 | | Shift+Alt+9 | shift+alt+9 | Shift+Alt+9 | shift+alt+[Digit9] | |
| Ctrl+Shift+Alt+Digit9 | · | Ctrl+Shift+Alt+9 | | Ctrl+Shift+Alt+9 | ctrl+shift+alt+9 | Ctrl+Shift+Alt+9 | ctrl+shift+alt+[Digit9] | |
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
| Digit0 | 0 | 0 | | 0 | 0 | 0 | [Digit0] | |
| Ctrl+Digit0 | 0 | Ctrl+0 | | Ctrl+0 | ctrl+0 | Ctrl+0 | ctrl+[Digit0] | |
| Shift+Digit0 | ) | Shift+0 | | Shift+0 | shift+0 | Shift+0 | shift+[Digit0] | |
| Ctrl+Shift+Digit0 | ) | Ctrl+Shift+0 | | Ctrl+Shift+0 | ctrl+shift+0 | Ctrl+Shift+0 | ctrl+shift+[Digit0] | |
| Alt+Digit0 | 0 | Alt+0 | | Alt+0 | alt+0 | Alt+0 | alt+[Digit0] | |
| Ctrl+Alt+Digit0 | º | Ctrl+Alt+0 | | Ctrl+Alt+0 | ctrl+alt+0 | Ctrl+Alt+0 | ctrl+alt+[Digit0] | |
| Shift+Alt+Digit0 | ) | Shift+Alt+0 | | Shift+Alt+0 | shift+alt+0 | Shift+Alt+0 | shift+alt+[Digit0] | |
| Ctrl+Shift+Alt+Digit0 | ‚ | Ctrl+Shift+Alt+0 | | Ctrl+Shift+Alt+0 | ctrl+shift+alt+0 | Ctrl+Shift+Alt+0 | ctrl+shift+alt+[Digit0] | |
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
| HW Code combination | Key | KeyCode combination | Pri | UI label | User settings | Electron accelerator | Dispatching string | WYSIWYG |
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
| Minus | - | - | | - | - | - | [Minus] | |
| Ctrl+Minus | - | Ctrl+- | | Ctrl+- | ctrl+- | Ctrl+- | ctrl+[Minus] | |
| Shift+Minus | _ | Shift+- | | Shift+- | shift+- | Shift+- | shift+[Minus] | |
| Ctrl+Shift+Minus | _ | Ctrl+Shift+- | | Ctrl+Shift+- | ctrl+shift+- | Ctrl+Shift+- | ctrl+shift+[Minus] | |
| Alt+Minus | - | Alt+- | | Alt+- | alt+- | Alt+- | alt+[Minus] | |
| Ctrl+Alt+Minus | – | Ctrl+Alt+- | | Ctrl+Alt+- | ctrl+alt+- | Ctrl+Alt+- | ctrl+alt+[Minus] | |
| Shift+Alt+Minus | _ | Shift+Alt+- | | Shift+Alt+- | shift+alt+- | Shift+Alt+- | shift+alt+[Minus] | |
| Ctrl+Shift+Alt+Minus | — | Ctrl+Shift+Alt+- | | Ctrl+Shift+Alt+- | ctrl+shift+alt+- | Ctrl+Shift+Alt+- | ctrl+shift+alt+[Minus] | |
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
| Equal | = | = | | = | = | = | [Equal] | |
| Ctrl+Equal | = | Ctrl+= | | Ctrl+= | ctrl+= | Ctrl+= | ctrl+[Equal] | |
| Shift+Equal | + | Shift+= | | Shift+= | shift+= | Shift+= | shift+[Equal] | |
| Ctrl+Shift+Equal | + | Ctrl+Shift+= | | Ctrl+Shift+= | ctrl+shift+= | Ctrl+Shift+= | ctrl+shift+[Equal] | |
| Alt+Equal | = | Alt+= | | Alt+= | alt+= | Alt+= | alt+[Equal] | |
| Ctrl+Alt+Equal | ≠ | Ctrl+Alt+= | | Ctrl+Alt+= | ctrl+alt+= | Ctrl+Alt+= | ctrl+alt+[Equal] | |
| Shift+Alt+Equal | + | Shift+Alt+= | | Shift+Alt+= | shift+alt+= | Shift+Alt+= | shift+alt+[Equal] | |
| Ctrl+Shift+Alt+Equal | ± | Ctrl+Shift+Alt+= | | Ctrl+Shift+Alt+= | ctrl+shift+alt+= | Ctrl+Shift+Alt+= | ctrl+shift+alt+[Equal] | |
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
| BracketLeft | [ | [ | | [ | [ | [ | [BracketLeft] | |
| Ctrl+BracketLeft | [ | Ctrl+[ | | Ctrl+[ | ctrl+[ | Ctrl+[ | ctrl+[BracketLeft] | |
| Shift+BracketLeft | { | Shift+[ | | Shift+[ | shift+[ | Shift+[ | shift+[BracketLeft] | |
| Ctrl+Shift+BracketLeft | { | Ctrl+Shift+[ | | Ctrl+Shift+[ | ctrl+shift+[ | Ctrl+Shift+[ | ctrl+shift+[BracketLeft] | |
| Alt+BracketLeft | [ | Alt+[ | | Alt+[ | alt+[ | Alt+[ | alt+[BracketLeft] | |
| Ctrl+Alt+BracketLeft | “ | Ctrl+Alt+[ | | Ctrl+Alt+[ | ctrl+alt+[ | Ctrl+Alt+[ | ctrl+alt+[BracketLeft] | |
| Shift+Alt+BracketLeft | { | Shift+Alt+[ | | Shift+Alt+[ | shift+alt+[ | Shift+Alt+[ | shift+alt+[BracketLeft] | |
| Ctrl+Shift+Alt+BracketLeft | ” | Ctrl+Shift+Alt+[ | | Ctrl+Shift+Alt+[ | ctrl+shift+alt+[ | Ctrl+Shift+Alt+[ | ctrl+shift+alt+[BracketLeft] | |
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
| BracketRight | ] | ] | | ] | ] | ] | [BracketRight] | |
| Ctrl+BracketRight | ] | Ctrl+] | | Ctrl+] | ctrl+] | Ctrl+] | ctrl+[BracketRight] | |
| Shift+BracketRight | } | Shift+] | | Shift+] | shift+] | Shift+] | shift+[BracketRight] | |
| Ctrl+Shift+BracketRight | } | Ctrl+Shift+] | | Ctrl+Shift+] | ctrl+shift+] | Ctrl+Shift+] | ctrl+shift+[BracketRight] | |
| Alt+BracketRight | ] | Alt+] | | Alt+] | alt+] | Alt+] | alt+[BracketRight] | |
| Ctrl+Alt+BracketRight | ‘ | Ctrl+Alt+] | | Ctrl+Alt+] | ctrl+alt+] | Ctrl+Alt+] | ctrl+alt+[BracketRight] | |
| Shift+Alt+BracketRight | } | Shift+Alt+] | | Shift+Alt+] | shift+alt+] | Shift+Alt+] | shift+alt+[BracketRight] | |
| Ctrl+Shift+Alt+BracketRight | ’ | Ctrl+Shift+Alt+] | | Ctrl+Shift+Alt+] | ctrl+shift+alt+] | Ctrl+Shift+Alt+] | ctrl+shift+alt+[BracketRight] | |
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
| HW Code combination | Key | KeyCode combination | Pri | UI label | User settings | Electron accelerator | Dispatching string | WYSIWYG |
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
| Backslash | \ | \ | | \ | \ | \ | [Backslash] | |
| Ctrl+Backslash | \ | Ctrl+\ | | Ctrl+\ | ctrl+\ | Ctrl+\ | ctrl+[Backslash] | |
| Shift+Backslash | | | Shift+\ | | Shift+\ | shift+\ | Shift+\ | shift+[Backslash] | |
| Ctrl+Shift+Backslash | | | Ctrl+Shift+\ | | Ctrl+Shift+\ | ctrl+shift+\ | Ctrl+Shift+\ | ctrl+shift+[Backslash] | |
| Alt+Backslash | \ | Alt+\ | | Alt+\ | alt+\ | Alt+\ | alt+[Backslash] | |
| Ctrl+Alt+Backslash | « | Ctrl+Alt+\ | | Ctrl+Alt+\ | ctrl+alt+\ | Ctrl+Alt+\ | ctrl+alt+[Backslash] | |
| Shift+Alt+Backslash | | | Shift+Alt+\ | | Shift+Alt+\ | shift+alt+\ | Shift+Alt+\ | shift+alt+[Backslash] | |
| Ctrl+Shift+Alt+Backslash | » | Ctrl+Shift+Alt+\ | | Ctrl+Shift+Alt+\ | ctrl+shift+alt+\ | Ctrl+Shift+Alt+\ | ctrl+shift+alt+[Backslash] | |
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
| IntlHash | --- | | | null | null | null | null | |
| Ctrl+IntlHash | --- | | | null | null | null | null | |
| Shift+IntlHash | --- | | | null | null | null | null | |
| Ctrl+Shift+IntlHash | --- | | | null | null | null | null | |
| Alt+IntlHash | --- | | | null | null | null | null | |
| Ctrl+Alt+IntlHash | --- | | | null | null | null | null | |
| Shift+Alt+IntlHash | --- | | | null | null | null | null | |
| Ctrl+Shift+Alt+IntlHash | --- | | | null | null | null | null | |
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
| Semicolon | ; | ; | | ; | ; | ; | [Semicolon] | |
| Ctrl+Semicolon | ; | Ctrl+; | | Ctrl+; | ctrl+; | Ctrl+; | ctrl+[Semicolon] | |
| Shift+Semicolon | : | Shift+; | | Shift+; | shift+; | Shift+; | shift+[Semicolon] | |
| Ctrl+Shift+Semicolon | : | Ctrl+Shift+; | | Ctrl+Shift+; | ctrl+shift+; | Ctrl+Shift+; | ctrl+shift+[Semicolon] | |
| Alt+Semicolon | ; | Alt+; | | Alt+; | alt+; | Alt+; | alt+[Semicolon] | |
| Ctrl+Alt+Semicolon | … | Ctrl+Alt+; | | Ctrl+Alt+; | ctrl+alt+; | Ctrl+Alt+; | ctrl+alt+[Semicolon] | |
| Shift+Alt+Semicolon | : | Shift+Alt+; | | Shift+Alt+; | shift+alt+; | Shift+Alt+; | shift+alt+[Semicolon] | |
| Ctrl+Shift+Alt+Semicolon | Ú | Ctrl+Shift+Alt+; | | Ctrl+Shift+Alt+; | ctrl+shift+alt+; | Ctrl+Shift+Alt+; | ctrl+shift+alt+[Semicolon] | |
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
| Quote | ' | ' | | ' | ' | ' | [Quote] | |
| Ctrl+Quote | ' | Ctrl+' | | Ctrl+' | ctrl+' | Ctrl+' | ctrl+[Quote] | |
| Shift+Quote | " | Shift+' | | Shift+' | shift+' | Shift+' | shift+[Quote] | |
| Ctrl+Shift+Quote | " | Ctrl+Shift+' | | Ctrl+Shift+' | ctrl+shift+' | Ctrl+Shift+' | ctrl+shift+[Quote] | |
| Alt+Quote | ' | Alt+' | | Alt+' | alt+' | Alt+' | alt+[Quote] | |
| Ctrl+Alt+Quote | æ | Ctrl+Alt+' | | Ctrl+Alt+' | ctrl+alt+' | Ctrl+Alt+' | ctrl+alt+[Quote] | |
| Shift+Alt+Quote | " | Shift+Alt+' | | Shift+Alt+' | shift+alt+' | Shift+Alt+' | shift+alt+[Quote] | |
| Ctrl+Shift+Alt+Quote | Æ | Ctrl+Shift+Alt+' | | Ctrl+Shift+Alt+' | ctrl+shift+alt+' | Ctrl+Shift+Alt+' | ctrl+shift+alt+[Quote] | |
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
| HW Code combination | Key | KeyCode combination | Pri | UI label | User settings | Electron accelerator | Dispatching string | WYSIWYG |
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
| Backquote | ` | ` | | ` | ` | ` | [Backquote] | |
| Ctrl+Backquote | ` | Ctrl+` | | Ctrl+` | ctrl+` | Ctrl+` | ctrl+[Backquote] | |
| Shift+Backquote | ~ | Shift+` | | Shift+` | shift+` | Shift+` | shift+[Backquote] | |
| Ctrl+Shift+Backquote | ~ | Ctrl+Shift+` | | Ctrl+Shift+` | ctrl+shift+` | Ctrl+Shift+` | ctrl+shift+[Backquote] | |
| Alt+Backquote | ` | Alt+` | | Alt+` | alt+` | Alt+` | alt+[Backquote] | |
| Ctrl+Alt+Backquote | ` | Ctrl+Alt+` | | Ctrl+Alt+` | ctrl+alt+` | Ctrl+Alt+` | ctrl+alt+[Backquote] | |
| Shift+Alt+Backquote | ~ | Shift+Alt+` | | Shift+Alt+` | shift+alt+` | Shift+Alt+` | shift+alt+[Backquote] | |
| Ctrl+Shift+Alt+Backquote | ` | Ctrl+Shift+Alt+` | | Ctrl+Shift+Alt+` | ctrl+shift+alt+` | Ctrl+Shift+Alt+` | ctrl+shift+alt+[Backquote] | |
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
| Comma | , | , | | , | , | , | [Comma] | |
| Ctrl+Comma | , | Ctrl+, | | Ctrl+, | ctrl+, | Ctrl+, | ctrl+[Comma] | |
| Shift+Comma | < | Shift+, | | Shift+, | shift+, | Shift+, | shift+[Comma] | |
| Ctrl+Shift+Comma | < | Ctrl+Shift+, | | Ctrl+Shift+, | ctrl+shift+, | Ctrl+Shift+, | ctrl+shift+[Comma] | |
| Alt+Comma | , | Alt+, | | Alt+, | alt+, | Alt+, | alt+[Comma] | |
| Ctrl+Alt+Comma | ≤ | Ctrl+Alt+, | | Ctrl+Alt+, | ctrl+alt+, | Ctrl+Alt+, | ctrl+alt+[Comma] | |
| Shift+Alt+Comma | < | Shift+Alt+, | | Shift+Alt+, | shift+alt+, | Shift+Alt+, | shift+alt+[Comma] | |
| Ctrl+Shift+Alt+Comma | ¯ | Ctrl+Shift+Alt+, | | Ctrl+Shift+Alt+, | ctrl+shift+alt+, | Ctrl+Shift+Alt+, | ctrl+shift+alt+[Comma] | |
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
| Period | . | . | | . | . | . | [Period] | |
| Ctrl+Period | . | Ctrl+. | | Ctrl+. | ctrl+. | Ctrl+. | ctrl+[Period] | |
| Shift+Period | > | Shift+. | | Shift+. | shift+. | Shift+. | shift+[Period] | |
| Ctrl+Shift+Period | > | Ctrl+Shift+. | | Ctrl+Shift+. | ctrl+shift+. | Ctrl+Shift+. | ctrl+shift+[Period] | |
| Alt+Period | . | Alt+. | | Alt+. | alt+. | Alt+. | alt+[Period] | |
| Ctrl+Alt+Period | ≥ | Ctrl+Alt+. | | Ctrl+Alt+. | ctrl+alt+. | Ctrl+Alt+. | ctrl+alt+[Period] | |
| Shift+Alt+Period | > | Shift+Alt+. | | Shift+Alt+. | shift+alt+. | Shift+Alt+. | shift+alt+[Period] | |
| Ctrl+Shift+Alt+Period | ˘ | Ctrl+Shift+Alt+. | | Ctrl+Shift+Alt+. | ctrl+shift+alt+. | Ctrl+Shift+Alt+. | ctrl+shift+alt+[Period] | |
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
| Slash | / | / | | / | / | / | [Slash] | |
| Ctrl+Slash | / | Ctrl+/ | | Ctrl+/ | ctrl+/ | Ctrl+/ | ctrl+[Slash] | |
| Shift+Slash | ? | Shift+/ | | Shift+/ | shift+/ | Shift+/ | shift+[Slash] | |
| Ctrl+Shift+Slash | ? | Ctrl+Shift+/ | | Ctrl+Shift+/ | ctrl+shift+/ | Ctrl+Shift+/ | ctrl+shift+[Slash] | |
| Alt+Slash | / | Alt+/ | | Alt+/ | alt+/ | Alt+/ | alt+[Slash] | |
| Ctrl+Alt+Slash | ÷ | Ctrl+Alt+/ | | Ctrl+Alt+/ | ctrl+alt+/ | Ctrl+Alt+/ | ctrl+alt+[Slash] | |
| Shift+Alt+Slash | ? | Shift+Alt+/ | | Shift+Alt+/ | shift+alt+/ | Shift+Alt+/ | shift+alt+[Slash] | |
| Ctrl+Shift+Alt+Slash | ¿ | Ctrl+Shift+Alt+/ | | Ctrl+Shift+Alt+/ | ctrl+shift+alt+/ | Ctrl+Shift+Alt+/ | ctrl+shift+alt+[Slash] | |
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
| HW Code combination | Key | KeyCode combination | Pri | UI label | User settings | Electron accelerator | Dispatching string | WYSIWYG |
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
| ArrowUp | --- | UpArrow | | UpArrow | up | Up | [ArrowUp] | |
| Ctrl+ArrowUp | --- | Ctrl+UpArrow | | Ctrl+UpArrow | ctrl+up | Ctrl+Up | ctrl+[ArrowUp] | |
| Shift+ArrowUp | --- | Shift+UpArrow | | Shift+UpArrow | shift+up | Shift+Up | shift+[ArrowUp] | |
| Ctrl+Shift+ArrowUp | --- | Ctrl+Shift+UpArrow | | Ctrl+Shift+UpArrow | ctrl+shift+up | Ctrl+Shift+Up | ctrl+shift+[ArrowUp] | |
| Alt+ArrowUp | --- | Alt+UpArrow | | Alt+UpArrow | alt+up | Alt+Up | alt+[ArrowUp] | |
| Ctrl+Alt+ArrowUp | --- | Ctrl+Alt+UpArrow | | Ctrl+Alt+UpArrow | ctrl+alt+up | Ctrl+Alt+Up | ctrl+alt+[ArrowUp] | |
| Shift+Alt+ArrowUp | --- | Shift+Alt+UpArrow | | Shift+Alt+UpArrow | shift+alt+up | Shift+Alt+Up | shift+alt+[ArrowUp] | |
| Ctrl+Shift+Alt+ArrowUp | --- | Ctrl+Shift+Alt+UpArrow | | Ctrl+Shift+Alt+UpArrow | ctrl+shift+alt+up | Ctrl+Shift+Alt+Up | ctrl+shift+alt+[ArrowUp] | |
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
| Numpad0 | --- | NumPad0 | | NumPad0 | numpad0 | null | [Numpad0] | |
| Ctrl+Numpad0 | --- | Ctrl+NumPad0 | | Ctrl+NumPad0 | ctrl+numpad0 | null | ctrl+[Numpad0] | |
| Shift+Numpad0 | --- | Shift+NumPad0 | | Shift+NumPad0 | shift+numpad0 | null | shift+[Numpad0] | |
| Ctrl+Shift+Numpad0 | --- | Ctrl+Shift+NumPad0 | | Ctrl+Shift+NumPad0 | ctrl+shift+numpad0 | null | ctrl+shift+[Numpad0] | |
| Alt+Numpad0 | --- | Alt+NumPad0 | | Alt+NumPad0 | alt+numpad0 | null | alt+[Numpad0] | |
| Ctrl+Alt+Numpad0 | --- | Ctrl+Alt+NumPad0 | | Ctrl+Alt+NumPad0 | ctrl+alt+numpad0 | null | ctrl+alt+[Numpad0] | |
| Shift+Alt+Numpad0 | --- | Shift+Alt+NumPad0 | | Shift+Alt+NumPad0 | shift+alt+numpad0 | null | shift+alt+[Numpad0] | |
| Ctrl+Shift+Alt+Numpad0 | --- | Ctrl+Shift+Alt+NumPad0 | | Ctrl+Shift+Alt+NumPad0 | ctrl+shift+alt+numpad0 | null | ctrl+shift+alt+[Numpad0] | |
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
| IntlBackslash | § | | | § | [IntlBackslash] | null | [IntlBackslash] | NO |
| Ctrl+IntlBackslash | § | | | Ctrl+§ | ctrl+[IntlBackslash] | null | ctrl+[IntlBackslash] | NO |
| Shift+IntlBackslash | ± | | | Shift+§ | shift+[IntlBackslash] | null | shift+[IntlBackslash] | NO |
| Ctrl+Shift+IntlBackslash | ± | | | Ctrl+Shift+§ | ctrl+shift+[IntlBackslash] | null | ctrl+shift+[IntlBackslash] | NO |
| Alt+IntlBackslash | § | | | Alt+§ | alt+[IntlBackslash] | null | alt+[IntlBackslash] | NO |
| Ctrl+Alt+IntlBackslash | § | | | Ctrl+Alt+§ | ctrl+alt+[IntlBackslash] | null | ctrl+alt+[IntlBackslash] | NO |
| Shift+Alt+IntlBackslash | ± | | | Shift+Alt+§ | shift+alt+[IntlBackslash] | null | shift+alt+[IntlBackslash] | NO |
| Ctrl+Shift+Alt+IntlBackslash | ± | | | Ctrl+Shift+Alt+§ | ctrl+shift+alt+[IntlBackslash] | null | ctrl+shift+alt+[IntlBackslash] | NO |
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
| IntlRo | --- | | | null | [IntlRo] | null | [IntlRo] | NO |
| Ctrl+IntlRo | --- | | | null | ctrl+[IntlRo] | null | ctrl+[IntlRo] | NO |
| Shift+IntlRo | --- | | | null | shift+[IntlRo] | null | shift+[IntlRo] | NO |
| Ctrl+Shift+IntlRo | --- | | | null | ctrl+shift+[IntlRo] | null | ctrl+shift+[IntlRo] | NO |
| Alt+IntlRo | --- | | | null | alt+[IntlRo] | null | alt+[IntlRo] | NO |
| Ctrl+Alt+IntlRo | --- | | | null | ctrl+alt+[IntlRo] | null | ctrl+alt+[IntlRo] | NO |
| Shift+Alt+IntlRo | --- | | | null | shift+alt+[IntlRo] | null | shift+alt+[IntlRo] | NO |
| Ctrl+Shift+Alt+IntlRo | --- | | | null | ctrl+shift+alt+[IntlRo] | null | ctrl+shift+alt+[IntlRo] | NO |
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
| HW Code combination | Key | KeyCode combination | Pri | UI label | User settings | Electron accelerator | Dispatching string | WYSIWYG |
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
| IntlYen | --- | | | null | [IntlYen] | null | [IntlYen] | NO |
| Ctrl+IntlYen | --- | | | null | ctrl+[IntlYen] | null | ctrl+[IntlYen] | NO |
| Shift+IntlYen | --- | | | null | shift+[IntlYen] | null | shift+[IntlYen] | NO |
| Ctrl+Shift+IntlYen | --- | | | null | ctrl+shift+[IntlYen] | null | ctrl+shift+[IntlYen] | NO |
| Alt+IntlYen | --- | | | null | alt+[IntlYen] | null | alt+[IntlYen] | NO |
| Ctrl+Alt+IntlYen | --- | | | null | ctrl+alt+[IntlYen] | null | ctrl+alt+[IntlYen] | NO |
| Shift+Alt+IntlYen | --- | | | null | shift+alt+[IntlYen] | null | shift+alt+[IntlYen] | NO |
| Ctrl+Shift+Alt+IntlYen | --- | | | null | ctrl+shift+alt+[IntlYen] | null | ctrl+shift+alt+[IntlYen] | NO |
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | src/vs/workbench/services/keybinding/test/mac_en_us.txt | 0 | https://github.com/microsoft/vscode/commit/51ef43a02382fb972b15d5b935515b69bb637a3a | [
0.00017927479348145425,
0.00017487221339251846,
0.00016750494251027703,
0.0001749260409269482,
0.0000017989111711358419
] |
{
"id": 6,
"code_window": [
"\t\t\t\t\t\tif (Types.isStringArray(item.options)) {\n",
"\t\t\t\t\t\t\toptions = item.options;\n",
"\t\t\t\t\t\t} else {\n",
"\t\t\t\t\t\t\tthrow new Error(nls.localize('pickRequiresOptions', \"Input '{0}' is of type 'pick' and must include 'options'.\", item.id));\n",
"\t\t\t\t\t\t}\n",
"\t\t\t\t\t}\n",
"\t\t\t\t\tinputs.push({ id: item.id, description: item.description, type, default: item.default, options });\n",
"\t\t\t\t}\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t\t\t\t\tthrow new Error(nls.localize('pickStringRequiresOptions', \"Input '{0}' is of type 'pickString' and must include 'options'.\", item.id));\n"
],
"file_path": "src/vs/workbench/services/configurationResolver/electron-browser/configurationResolverService.ts",
"type": "replace",
"edit_start_line_idx": 320
} | {
"comments": {
"lineComment": "#"
},
"brackets": [
["{", "}"],
["[", "]"],
["(", ")"]
],
"autoClosingPairs": [
["{", "}"],
["[", "]"],
["(", ")"],
["\"", "\""],
["'", "'"],
["`", "`"]
],
"surroundingPairs": [
["{", "}"],
["[", "]"],
["(", ")"],
["\"", "\""],
["'", "'"],
["`", "`"]
]
} | extensions/perl/perl6.language-configuration.json | 0 | https://github.com/microsoft/vscode/commit/51ef43a02382fb972b15d5b935515b69bb637a3a | [
0.00017367109830956906,
0.00017066625878214836,
0.00016867011436261237,
0.0001696575927780941,
0.000002162641749237082
] |
{
"id": 6,
"code_window": [
"\t\t\t\t\t\tif (Types.isStringArray(item.options)) {\n",
"\t\t\t\t\t\t\toptions = item.options;\n",
"\t\t\t\t\t\t} else {\n",
"\t\t\t\t\t\t\tthrow new Error(nls.localize('pickRequiresOptions', \"Input '{0}' is of type 'pick' and must include 'options'.\", item.id));\n",
"\t\t\t\t\t\t}\n",
"\t\t\t\t\t}\n",
"\t\t\t\t\tinputs.push({ id: item.id, description: item.description, type, default: item.default, options });\n",
"\t\t\t\t}\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t\t\t\t\tthrow new Error(nls.localize('pickStringRequiresOptions', \"Input '{0}' is of type 'pickString' and must include 'options'.\", item.id));\n"
],
"file_path": "src/vs/workbench/services/configurationResolver/electron-browser/configurationResolverService.ts",
"type": "replace",
"edit_start_line_idx": 320
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { ExtensionContext, languages, IndentAction } from 'vscode';
export function activate(_context: ExtensionContext): any {
languages.setLanguageConfiguration('python', {
onEnterRules: [
{
beforeText: /^\s*(?:def|class|for|if|elif|else|while|try|with|finally|except|async).*?:\s*$/,
action: { indentAction: IndentAction.Indent }
}
]
});
} | extensions/python/src/pythonMain.ts | 0 | https://github.com/microsoft/vscode/commit/51ef43a02382fb972b15d5b935515b69bb637a3a | [
0.00017566581664141268,
0.0001742069434840232,
0.00017274805577471852,
0.0001742069434840232,
0.0000014588804333470762
] |
{
"id": 0,
"code_window": [
"\n",
"\t\t\t\tthis.nativeHostMainService?.openExternal(undefined, url);\n",
"\t\t\t});\n",
"\n",
"\t\t\tsession.defaultSession.setPermissionRequestHandler((webContents, permission /* 'media' | 'geolocation' | 'notifications' | 'midiSysex' | 'pointerLock' | 'fullscreen' | 'openExternal' */, callback) => {\n",
"\t\t\t\treturn callback(false);\n",
"\t\t\t});\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\tconst webviewFrameUrl = 'about:blank?webviewFrame';\n",
"\n",
"\t\t\tsession.defaultSession.setPermissionRequestHandler((_webContents, permission /* 'media' | 'geolocation' | 'notifications' | 'midiSysex' | 'pointerLock' | 'fullscreen' | 'openExternal' */, callback, details) => {\n",
"\t\t\t\tif (details.requestingUrl === webviewFrameUrl) {\n",
"\t\t\t\t\treturn callback(permission === 'clipboard-read');\n",
"\t\t\t\t}\n"
],
"file_path": "src/vs/code/electron-main/app.ts",
"type": "replace",
"edit_start_line_idx": 227
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { release } from 'os';
import { statSync } from 'fs';
import { app, ipcMain, systemPreferences, contentTracing, protocol, BrowserWindow, dialog, session } from 'electron';
import { IProcessEnvironment, isWindows, isMacintosh, isLinux, isLinuxSnap } from 'vs/base/common/platform';
import { WindowsMainService } from 'vs/platform/windows/electron-main/windowsMainService';
import { IWindowOpenable } from 'vs/platform/windows/common/windows';
import { ILifecycleMainService, LifecycleMainPhase } from 'vs/platform/lifecycle/electron-main/lifecycleMainService';
import { resolveShellEnv } from 'vs/platform/environment/node/shellEnv';
import { IUpdateService } from 'vs/platform/update/common/update';
import { UpdateChannel } from 'vs/platform/update/common/updateIpc';
import { getDelayedChannel, StaticRouter, ProxyChannel } from 'vs/base/parts/ipc/common/ipc';
import { Server as ElectronIPCServer } from 'vs/base/parts/ipc/electron-main/ipc.electron';
import { Server as NodeIPCServer } from 'vs/base/parts/ipc/node/ipc.net';
import { Client as MessagePortClient } from 'vs/base/parts/ipc/electron-main/ipc.mp';
import { SharedProcess } from 'vs/platform/sharedProcess/electron-main/sharedProcess';
import { LaunchMainService, ILaunchMainService } from 'vs/platform/launch/electron-main/launchMainService';
import { IInstantiationService, ServicesAccessor } from 'vs/platform/instantiation/common/instantiation';
import { ServiceCollection } from 'vs/platform/instantiation/common/serviceCollection';
import { SyncDescriptor } from 'vs/platform/instantiation/common/descriptors';
import { ILoggerService, ILogService } from 'vs/platform/log/common/log';
import { IStateService } from 'vs/platform/state/node/state';
import { IEnvironmentMainService } from 'vs/platform/environment/electron-main/environmentMainService';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { IOpenURLOptions, IURLService } from 'vs/platform/url/common/url';
import { URLHandlerChannelClient, URLHandlerRouter } from 'vs/platform/url/common/urlIpc';
import { ITelemetryService, machineIdKey } from 'vs/platform/telemetry/common/telemetry';
import { NullTelemetryService } from 'vs/platform/telemetry/common/telemetryUtils';
import { TelemetryAppenderClient } from 'vs/platform/telemetry/common/telemetryIpc';
import { TelemetryService, ITelemetryServiceConfig } from 'vs/platform/telemetry/common/telemetryService';
import { resolveCommonProperties } from 'vs/platform/telemetry/common/commonProperties';
import product from 'vs/platform/product/common/product';
import { ProxyAuthHandler } from 'vs/code/electron-main/auth';
import { FileProtocolHandler } from 'vs/code/electron-main/protocol';
import { Disposable } from 'vs/base/common/lifecycle';
import { IWindowsMainService, ICodeWindow, OpenContext, WindowError } from 'vs/platform/windows/electron-main/windows';
import { URI } from 'vs/base/common/uri';
import { hasWorkspaceFileExtension, IWorkspacesService } from 'vs/platform/workspaces/common/workspaces';
import { WorkspacesMainService } from 'vs/platform/workspaces/electron-main/workspacesMainService';
import { getMachineId } from 'vs/base/node/id';
import { Win32UpdateService } from 'vs/platform/update/electron-main/updateService.win32';
import { LinuxUpdateService } from 'vs/platform/update/electron-main/updateService.linux';
import { DarwinUpdateService } from 'vs/platform/update/electron-main/updateService.darwin';
import { IssueMainService, IIssueMainService } from 'vs/platform/issue/electron-main/issueMainService';
import { LoggerChannel, LogLevelChannel } from 'vs/platform/log/common/logIpc';
import { setUnexpectedErrorHandler, onUnexpectedError } from 'vs/base/common/errors';
import { ElectronURLListener } from 'vs/platform/url/electron-main/electronUrlListener';
import { serve as serveDriver } from 'vs/platform/driver/electron-main/driver';
import { IMenubarMainService, MenubarMainService } from 'vs/platform/menubar/electron-main/menubarMainService';
import { RunOnceScheduler } from 'vs/base/common/async';
import { registerContextMenuListener } from 'vs/base/parts/contextmenu/electron-main/contextmenu';
import { sep, posix, join, isAbsolute } from 'vs/base/common/path';
import { joinPath } from 'vs/base/common/resources';
import { localize } from 'vs/nls';
import { Schemas } from 'vs/base/common/network';
import { SnapUpdateService } from 'vs/platform/update/electron-main/updateService.snap';
import { IStorageMainService, StorageMainService } from 'vs/platform/storage/electron-main/storageMainService';
import { StorageDatabaseChannel } from 'vs/platform/storage/electron-main/storageIpc';
import { BackupMainService } from 'vs/platform/backup/electron-main/backupMainService';
import { IBackupMainService } from 'vs/platform/backup/electron-main/backup';
import { WorkspacesHistoryMainService, IWorkspacesHistoryMainService } from 'vs/platform/workspaces/electron-main/workspacesHistoryMainService';
import { NativeURLService } from 'vs/platform/url/common/urlService';
import { WorkspacesManagementMainService, IWorkspacesManagementMainService } from 'vs/platform/workspaces/electron-main/workspacesManagementMainService';
import { IDiagnosticsService } from 'vs/platform/diagnostics/common/diagnostics';
import { ElectronExtensionHostDebugBroadcastChannel } from 'vs/platform/debug/electron-main/extensionHostDebugIpc';
import { INativeHostMainService, NativeHostMainService } from 'vs/platform/native/electron-main/nativeHostMainService';
import { IDialogMainService, DialogMainService } from 'vs/platform/dialogs/electron-main/dialogMainService';
import { withNullAsUndefined } from 'vs/base/common/types';
import { mnemonicButtonLabel, getPathLabel } from 'vs/base/common/labels';
import { WebviewMainService } from 'vs/platform/webview/electron-main/webviewMainService';
import { IWebviewManagerService } from 'vs/platform/webview/common/webviewManagerService';
import { IFileService } from 'vs/platform/files/common/files';
import { stripComments } from 'vs/base/common/json';
import { generateUuid } from 'vs/base/common/uuid';
import { VSBuffer } from 'vs/base/common/buffer';
import { EncryptionMainService, IEncryptionMainService } from 'vs/platform/encryption/electron-main/encryptionMainService';
import { ActiveWindowManager } from 'vs/platform/windows/node/windowTracker';
import { IKeyboardLayoutMainService, KeyboardLayoutMainService } from 'vs/platform/keyboardLayout/electron-main/keyboardLayoutMainService';
import { NativeParsedArgs } from 'vs/platform/environment/common/argv';
import { DisplayMainService, IDisplayMainService } from 'vs/platform/display/electron-main/displayMainService';
import { isLaunchedFromCli } from 'vs/platform/environment/node/argvHelper';
import { isEqualOrParent } from 'vs/base/common/extpath';
import { CancellationToken, CancellationTokenSource } from 'vs/base/common/cancellation';
import { IExtensionUrlTrustService } from 'vs/platform/extensionManagement/common/extensionUrlTrust';
import { ExtensionUrlTrustService } from 'vs/platform/extensionManagement/node/extensionUrlTrustService';
import { once } from 'vs/base/common/functional';
/**
* The main VS Code application. There will only ever be one instance,
* even if the user starts many instances (e.g. from the command line).
*/
export class CodeApplication extends Disposable {
private windowsMainService: IWindowsMainService | undefined;
private nativeHostMainService: INativeHostMainService | undefined;
constructor(
private readonly mainProcessNodeIpcServer: NodeIPCServer,
private readonly userEnv: IProcessEnvironment,
@IInstantiationService private readonly mainInstantiationService: IInstantiationService,
@ILogService private readonly logService: ILogService,
@IEnvironmentMainService private readonly environmentMainService: IEnvironmentMainService,
@ILifecycleMainService private readonly lifecycleMainService: ILifecycleMainService,
@IConfigurationService private readonly configurationService: IConfigurationService,
@IStateService private readonly stateService: IStateService,
@IFileService private readonly fileService: IFileService
) {
super();
this.registerListeners();
}
private registerListeners(): void {
// We handle uncaught exceptions here to prevent electron from opening a dialog to the user
setUnexpectedErrorHandler(err => this.onUnexpectedError(err));
process.on('uncaughtException', err => this.onUnexpectedError(err));
process.on('unhandledRejection', (reason: unknown) => onUnexpectedError(reason));
// Dispose on shutdown
this.lifecycleMainService.onWillShutdown(() => this.dispose());
// Contextmenu via IPC support
registerContextMenuListener();
// Accessibility change event
app.on('accessibility-support-changed', (event, accessibilitySupportEnabled) => {
this.windowsMainService?.sendToAll('vscode:accessibilitySupportChanged', accessibilitySupportEnabled);
});
// macOS dock activate
app.on('activate', (event, hasVisibleWindows) => {
this.logService.trace('app#activate');
// Mac only event: open new window when we get activated
if (!hasVisibleWindows) {
this.windowsMainService?.openEmptyWindow({ context: OpenContext.DOCK });
}
});
//#region Security related measures (https://electronjs.org/docs/tutorial/security)
//
// !!! DO NOT CHANGE without consulting the documentation !!!
//
app.on('remote-require', (event, sender, module) => {
this.logService.trace('app#on(remote-require): prevented');
event.preventDefault();
});
app.on('remote-get-global', (event, sender, module) => {
this.logService.trace(`app#on(remote-get-global): prevented on ${module}`);
event.preventDefault();
});
app.on('remote-get-builtin', (event, sender, module) => {
this.logService.trace(`app#on(remote-get-builtin): prevented on ${module}`);
if (module !== 'clipboard') {
event.preventDefault();
}
});
app.on('remote-get-current-window', event => {
this.logService.trace(`app#on(remote-get-current-window): prevented`);
event.preventDefault();
});
app.on('remote-get-current-web-contents', event => {
if (this.environmentMainService.args.driver) {
return; // the driver needs access to web contents
}
this.logService.trace(`app#on(remote-get-current-web-contents): prevented`);
event.preventDefault();
});
app.on('web-contents-created', (event, contents) => {
contents.on('will-attach-webview', (event, webPreferences, params) => {
const isValidWebviewSource = (source: string | undefined): boolean => {
if (!source) {
return false;
}
const uri = URI.parse(source);
if (uri.scheme === Schemas.vscodeWebview) {
return uri.path === '/index.html' || uri.path === '/electron-browser/index.html';
}
const srcUri = uri.fsPath.toLowerCase();
const rootUri = URI.file(this.environmentMainService.appRoot).fsPath.toLowerCase();
return srcUri.startsWith(rootUri + sep);
};
// Ensure defaults
delete webPreferences.preload;
webPreferences.nodeIntegration = false;
// Verify URLs being loaded
// https://github.com/electron/electron/issues/21553
if (isValidWebviewSource(params.src) && isValidWebviewSource((webPreferences as { preloadURL: string }).preloadURL)) {
return;
}
delete (webPreferences as { preloadURL: string | undefined }).preloadURL; // https://github.com/electron/electron/issues/21553
// Otherwise prevent loading
this.logService.error('webContents#web-contents-created: Prevented webview attach');
event.preventDefault();
});
contents.on('will-navigate', event => {
this.logService.error('webContents#will-navigate: Prevented webcontent navigation');
event.preventDefault();
});
contents.on('new-window', (event, url) => {
event.preventDefault(); // prevent code that wants to open links
this.nativeHostMainService?.openExternal(undefined, url);
});
session.defaultSession.setPermissionRequestHandler((webContents, permission /* 'media' | 'geolocation' | 'notifications' | 'midiSysex' | 'pointerLock' | 'fullscreen' | 'openExternal' */, callback) => {
return callback(false);
});
session.defaultSession.setPermissionCheckHandler((webContents, permission /* 'media' */) => {
return false;
});
});
//#endregion
let macOpenFileURIs: IWindowOpenable[] = [];
let runningTimeout: NodeJS.Timeout | null = null;
app.on('open-file', (event, path) => {
this.logService.trace('app#open-file: ', path);
event.preventDefault();
// Keep in array because more might come!
macOpenFileURIs.push(this.getWindowOpenableFromPathSync(path));
// Clear previous handler if any
if (runningTimeout !== null) {
clearTimeout(runningTimeout);
runningTimeout = null;
}
// Handle paths delayed in case more are coming!
runningTimeout = setTimeout(() => {
this.windowsMainService?.open({
context: OpenContext.DOCK /* can also be opening from finder while app is running */,
cli: this.environmentMainService.args,
urisToOpen: macOpenFileURIs,
gotoLineMode: false,
preferNewWindow: true /* dropping on the dock or opening from finder prefers to open in a new window */
});
macOpenFileURIs = [];
runningTimeout = null;
}, 100);
});
app.on('new-window-for-tab', () => {
this.windowsMainService?.openEmptyWindow({ context: OpenContext.DESKTOP }); //macOS native tab "+" button
});
//#region Bootstrap IPC Handlers
let slowShellResolveWarningShown = false;
ipcMain.on('vscode:fetchShellEnv', async event => {
// DO NOT remove: not only usual windows are fetching the
// shell environment but also shared process, issue reporter
// etc, so we need to reply via `webContents` always
const webContents = event.sender;
let replied = false;
function acceptShellEnv(env: NodeJS.ProcessEnv): void {
clearTimeout(shellEnvSlowWarningHandle);
clearTimeout(shellEnvTimeoutErrorHandle);
if (!replied) {
replied = true;
if (!webContents.isDestroyed()) {
webContents.send('vscode:acceptShellEnv', env);
}
}
}
// Handle slow shell environment resolve calls:
// - a warning after 3s but continue to resolve (only once in active window)
// - an error after 10s and stop trying to resolve (in every window where this happens)
const cts = new CancellationTokenSource();
const shellEnvSlowWarningHandle = setTimeout(() => {
if (!slowShellResolveWarningShown) {
this.windowsMainService?.sendToFocused('vscode:showShellEnvSlowWarning', cts.token);
slowShellResolveWarningShown = true;
}
}, 3000);
const window = this.windowsMainService?.getWindowByWebContents(event.sender); // Note: this can be `undefined` for the shared process!!
const shellEnvTimeoutErrorHandle = setTimeout(() => {
cts.dispose(true);
window?.sendWhenReady('vscode:showShellEnvTimeoutError', CancellationToken.None);
acceptShellEnv({});
}, 10000);
// Prefer to use the args and env from the target window
// when resolving the shell env. It is possible that
// a first window was opened from the UI but a second
// from the CLI and that has implications for whether to
// resolve the shell environment or not.
//
// Window can be undefined for e.g. the shared process
// that is not part of our windows registry!
let args: NativeParsedArgs;
let env: NodeJS.ProcessEnv;
if (window?.config) {
args = window.config;
env = { ...process.env, ...window.config.userEnv };
} else {
args = this.environmentMainService.args;
env = process.env;
}
// Resolve shell env
const shellEnv = await resolveShellEnv(this.logService, args, env);
acceptShellEnv(shellEnv);
});
ipcMain.handle('vscode:writeNlsFile', async (event, path: unknown, data: unknown) => {
const uri = this.validateNlsPath([path]);
if (!uri || typeof data !== 'string') {
throw new Error('Invalid operation (vscode:writeNlsFile)');
}
return this.fileService.writeFile(uri, VSBuffer.fromString(data));
});
ipcMain.handle('vscode:readNlsFile', async (event, ...paths: unknown[]) => {
const uri = this.validateNlsPath(paths);
if (!uri) {
throw new Error('Invalid operation (vscode:readNlsFile)');
}
return (await this.fileService.readFile(uri)).value.toString();
});
ipcMain.on('vscode:toggleDevTools', event => event.sender.toggleDevTools());
ipcMain.on('vscode:openDevTools', event => event.sender.openDevTools());
ipcMain.on('vscode:reloadWindow', event => event.sender.reload());
//#endregion
}
private validateNlsPath(pathSegments: unknown[]): URI | undefined {
let path: string | undefined = undefined;
for (const pathSegment of pathSegments) {
if (typeof pathSegment === 'string') {
if (typeof path !== 'string') {
path = pathSegment;
} else {
path = join(path, pathSegment);
}
}
}
if (typeof path !== 'string' || !isAbsolute(path) || !isEqualOrParent(path, this.environmentMainService.cachedLanguagesPath, !isLinux)) {
return undefined;
}
return URI.file(path);
}
private onUnexpectedError(err: Error): void {
if (err) {
// take only the message and stack property
const friendlyError = {
message: `[uncaught exception in main]: ${err.message}`,
stack: err.stack
};
// handle on client side
this.windowsMainService?.sendToFocused('vscode:reportError', JSON.stringify(friendlyError));
}
this.logService.error(`[uncaught exception in main]: ${err}`);
if (err.stack) {
this.logService.error(err.stack);
}
}
async startup(): Promise<void> {
this.logService.debug('Starting VS Code');
this.logService.debug(`from: ${this.environmentMainService.appRoot}`);
this.logService.debug('args:', this.environmentMainService.args);
// Make sure we associate the program with the app user model id
// This will help Windows to associate the running program with
// any shortcut that is pinned to the taskbar and prevent showing
// two icons in the taskbar for the same app.
const win32AppUserModelId = product.win32AppUserModelId;
if (isWindows && win32AppUserModelId) {
app.setAppUserModelId(win32AppUserModelId);
}
// Fix native tabs on macOS 10.13
// macOS enables a compatibility patch for any bundle ID beginning with
// "com.microsoft.", which breaks native tabs for VS Code when using this
// identifier (from the official build).
// Explicitly opt out of the patch here before creating any windows.
// See: https://github.com/microsoft/vscode/issues/35361#issuecomment-399794085
try {
if (isMacintosh && this.configurationService.getValue<boolean>('window.nativeTabs') === true && !systemPreferences.getUserDefault('NSUseImprovedLayoutPass', 'boolean')) {
systemPreferences.setUserDefault('NSUseImprovedLayoutPass', 'boolean', true as any);
}
} catch (error) {
this.logService.error(error);
}
// Setup Protocol Handler
const fileProtocolHandler = this._register(this.mainInstantiationService.createInstance(FileProtocolHandler));
// Main process server (electron IPC based)
const mainProcessElectronServer = new ElectronIPCServer();
// Resolve unique machine ID
this.logService.trace('Resolving machine identifier...');
const machineId = await this.resolveMachineId();
this.logService.trace(`Resolved machine identifier: ${machineId}`);
// Shared process
const { sharedProcess, sharedProcessReady, sharedProcessClient } = this.setupSharedProcess(machineId);
// Services
const appInstantiationService = await this.initServices(machineId, sharedProcess, sharedProcessReady);
// Create driver
if (this.environmentMainService.driverHandle) {
const server = await serveDriver(mainProcessElectronServer, this.environmentMainService.driverHandle, this.environmentMainService, appInstantiationService);
this.logService.info('Driver started at:', this.environmentMainService.driverHandle);
this._register(server);
}
// Setup Auth Handler
this._register(appInstantiationService.createInstance(ProxyAuthHandler));
// Init Channels
appInstantiationService.invokeFunction(accessor => this.initChannels(accessor, mainProcessElectronServer, sharedProcessClient));
// Open Windows
const windows = appInstantiationService.invokeFunction(accessor => this.openFirstWindow(accessor, mainProcessElectronServer, fileProtocolHandler));
// Post Open Windows Tasks
appInstantiationService.invokeFunction(accessor => this.afterWindowOpen(accessor, sharedProcess));
// Tracing: Stop tracing after windows are ready if enabled
if (this.environmentMainService.args.trace) {
appInstantiationService.invokeFunction(accessor => this.stopTracingEventually(accessor, windows));
}
}
private async resolveMachineId(): Promise<string> {
// We cache the machineId for faster lookups on startup
// and resolve it only once initially if not cached or we need to replace the macOS iBridge device
let machineId = this.stateService.getItem<string>(machineIdKey);
if (!machineId || (isMacintosh && machineId === '6c9d2bc8f91b89624add29c0abeae7fb42bf539fa1cdb2e3e57cd668fa9bcead')) {
machineId = await getMachineId();
this.stateService.setItem(machineIdKey, machineId);
}
return machineId;
}
private setupSharedProcess(machineId: string): { sharedProcess: SharedProcess, sharedProcessReady: Promise<MessagePortClient>, sharedProcessClient: Promise<MessagePortClient> } {
const sharedProcess = this.mainInstantiationService.createInstance(SharedProcess, machineId, this.userEnv);
const sharedProcessClient = (async () => {
this.logService.trace('Main->SharedProcess#connect');
const port = await sharedProcess.connect();
this.logService.trace('Main->SharedProcess#connect: connection established');
return new MessagePortClient(port, 'main');
})();
const sharedProcessReady = (async () => {
await sharedProcess.whenReady();
return sharedProcessClient;
})();
// Spawn shared process after the first window has opened and 3s have passed
this.lifecycleMainService.when(LifecycleMainPhase.AfterWindowOpen).then(() => {
this._register(new RunOnceScheduler(async () => {
sharedProcess.spawn(await resolveShellEnv(this.logService, this.environmentMainService.args, process.env));
}, 3000)).schedule();
});
return { sharedProcess, sharedProcessReady, sharedProcessClient };
}
private async initServices(machineId: string, sharedProcess: SharedProcess, sharedProcessReady: Promise<MessagePortClient>): Promise<IInstantiationService> {
const services = new ServiceCollection();
// Update
switch (process.platform) {
case 'win32':
services.set(IUpdateService, new SyncDescriptor(Win32UpdateService));
break;
case 'linux':
if (isLinuxSnap) {
services.set(IUpdateService, new SyncDescriptor(SnapUpdateService, [process.env['SNAP'], process.env['SNAP_REVISION']]));
} else {
services.set(IUpdateService, new SyncDescriptor(LinuxUpdateService));
}
break;
case 'darwin':
services.set(IUpdateService, new SyncDescriptor(DarwinUpdateService));
break;
}
// Windows
services.set(IWindowsMainService, new SyncDescriptor(WindowsMainService, [machineId, this.userEnv]));
// Dialogs
services.set(IDialogMainService, new SyncDescriptor(DialogMainService));
// Launch
services.set(ILaunchMainService, new SyncDescriptor(LaunchMainService));
// Diagnostics
services.set(IDiagnosticsService, ProxyChannel.toService(getDelayedChannel(sharedProcessReady.then(client => client.getChannel('diagnostics')))));
// Issues
services.set(IIssueMainService, new SyncDescriptor(IssueMainService, [machineId, this.userEnv]));
// Encryption
services.set(IEncryptionMainService, new SyncDescriptor(EncryptionMainService, [machineId]));
// Keyboard Layout
services.set(IKeyboardLayoutMainService, new SyncDescriptor(KeyboardLayoutMainService));
// Display
services.set(IDisplayMainService, new SyncDescriptor(DisplayMainService));
// Native Host
services.set(INativeHostMainService, new SyncDescriptor(NativeHostMainService, [sharedProcess]));
// Webview Manager
services.set(IWebviewManagerService, new SyncDescriptor(WebviewMainService));
// Workspaces
services.set(IWorkspacesService, new SyncDescriptor(WorkspacesMainService));
services.set(IWorkspacesManagementMainService, new SyncDescriptor(WorkspacesManagementMainService));
services.set(IWorkspacesHistoryMainService, new SyncDescriptor(WorkspacesHistoryMainService));
// Menubar
services.set(IMenubarMainService, new SyncDescriptor(MenubarMainService));
// Extension URL Trust
services.set(IExtensionUrlTrustService, new SyncDescriptor(ExtensionUrlTrustService));
// Storage
services.set(IStorageMainService, new SyncDescriptor(StorageMainService));
// Backups
const backupMainService = new BackupMainService(this.environmentMainService, this.configurationService, this.logService);
services.set(IBackupMainService, backupMainService);
// URL handling
services.set(IURLService, new SyncDescriptor(NativeURLService));
// Telemetry
if (!this.environmentMainService.isExtensionDevelopment && !this.environmentMainService.args['disable-telemetry'] && !!product.enableTelemetry) {
const channel = getDelayedChannel(sharedProcessReady.then(client => client.getChannel('telemetryAppender')));
const appender = new TelemetryAppenderClient(channel);
const commonProperties = resolveCommonProperties(this.fileService, release(), process.arch, product.commit, product.version, machineId, product.msftInternalDomains, this.environmentMainService.installSourcePath);
const piiPaths = [this.environmentMainService.appRoot, this.environmentMainService.extensionsPath];
const config: ITelemetryServiceConfig = { appender, commonProperties, piiPaths, sendErrorTelemetry: true };
services.set(ITelemetryService, new SyncDescriptor(TelemetryService, [config]));
} else {
services.set(ITelemetryService, NullTelemetryService);
}
// Init services that require it
await backupMainService.initialize();
return this.mainInstantiationService.createChild(services);
}
private initChannels(accessor: ServicesAccessor, mainProcessElectronServer: ElectronIPCServer, sharedProcessClient: Promise<MessagePortClient>): void {
// Launch: this one is explicitly registered to the node.js
// server because when a second instance starts up, that is
// the only possible connection between the first and the
// second instance. Electron IPC does not work across apps.
const launchChannel = ProxyChannel.fromService(accessor.get(ILaunchMainService), { disableMarshalling: true });
this.mainProcessNodeIpcServer.registerChannel('launch', launchChannel);
// Update
const updateChannel = new UpdateChannel(accessor.get(IUpdateService));
mainProcessElectronServer.registerChannel('update', updateChannel);
// Issues
const issueChannel = ProxyChannel.fromService(accessor.get(IIssueMainService));
mainProcessElectronServer.registerChannel('issue', issueChannel);
// Encryption
const encryptionChannel = ProxyChannel.fromService(accessor.get(IEncryptionMainService));
mainProcessElectronServer.registerChannel('encryption', encryptionChannel);
// Keyboard Layout
const keyboardLayoutChannel = ProxyChannel.fromService(accessor.get(IKeyboardLayoutMainService));
mainProcessElectronServer.registerChannel('keyboardLayout', keyboardLayoutChannel);
// Display
const displayChannel = ProxyChannel.fromService(accessor.get(IDisplayMainService));
mainProcessElectronServer.registerChannel('display', displayChannel);
// Native host (main & shared process)
this.nativeHostMainService = accessor.get(INativeHostMainService);
const nativeHostChannel = ProxyChannel.fromService(this.nativeHostMainService);
mainProcessElectronServer.registerChannel('nativeHost', nativeHostChannel);
sharedProcessClient.then(client => client.registerChannel('nativeHost', nativeHostChannel));
// Workspaces
const workspacesChannel = ProxyChannel.fromService(accessor.get(IWorkspacesService));
mainProcessElectronServer.registerChannel('workspaces', workspacesChannel);
// Menubar
const menubarChannel = ProxyChannel.fromService(accessor.get(IMenubarMainService));
mainProcessElectronServer.registerChannel('menubar', menubarChannel);
// URL handling
const urlChannel = ProxyChannel.fromService(accessor.get(IURLService));
mainProcessElectronServer.registerChannel('url', urlChannel);
// Extension URL Trust
const extensionUrlTrustChannel = ProxyChannel.fromService(accessor.get(IExtensionUrlTrustService));
mainProcessElectronServer.registerChannel('extensionUrlTrust', extensionUrlTrustChannel);
// Webview Manager
const webviewChannel = ProxyChannel.fromService(accessor.get(IWebviewManagerService));
mainProcessElectronServer.registerChannel('webview', webviewChannel);
// Storage (main & shared process)
const storageChannel = this._register(new StorageDatabaseChannel(this.logService, accessor.get(IStorageMainService)));
mainProcessElectronServer.registerChannel('storage', storageChannel);
sharedProcessClient.then(client => client.registerChannel('storage', storageChannel));
// Log Level (main & shared process)
const logLevelChannel = new LogLevelChannel(accessor.get(ILogService));
mainProcessElectronServer.registerChannel('logLevel', logLevelChannel);
sharedProcessClient.then(client => client.registerChannel('logLevel', logLevelChannel));
// Logger
const loggerChannel = new LoggerChannel(accessor.get(ILoggerService),);
mainProcessElectronServer.registerChannel('logger', loggerChannel);
// Extension Host Debug Broadcasting
const electronExtensionHostDebugBroadcastChannel = new ElectronExtensionHostDebugBroadcastChannel(accessor.get(IWindowsMainService));
mainProcessElectronServer.registerChannel('extensionhostdebugservice', electronExtensionHostDebugBroadcastChannel);
}
private openFirstWindow(accessor: ServicesAccessor, mainProcessElectronServer: ElectronIPCServer, fileProtocolHandler: FileProtocolHandler): ICodeWindow[] {
const windowsMainService = this.windowsMainService = accessor.get(IWindowsMainService);
const urlService = accessor.get(IURLService);
const nativeHostMainService = accessor.get(INativeHostMainService);
// Signal phase: ready (services set)
this.lifecycleMainService.phase = LifecycleMainPhase.Ready;
// Forward windows main service to protocol handler
fileProtocolHandler.injectWindowsMainService(this.windowsMainService);
// Check for initial URLs to handle from protocol link invocations
const pendingWindowOpenablesFromProtocolLinks: IWindowOpenable[] = [];
const pendingProtocolLinksToHandle = [
// Windows/Linux: protocol handler invokes CLI with --open-url
...this.environmentMainService.args['open-url'] ? this.environmentMainService.args._urls || [] : [],
// macOS: open-url events
...((<any>global).getOpenUrls() || []) as string[]
].map(url => {
try {
return { uri: URI.parse(url), url };
} catch {
return null;
}
}).filter((obj): obj is { uri: URI, url: string } => {
if (!obj) {
return false;
}
// If URI should be blocked, filter it out
if (this.shouldBlockURI(obj.uri)) {
return false;
}
// Filter out any protocol link that wants to open as window so that
// we open the right set of windows on startup and not restore the
// previous workspace too.
const windowOpenable = this.getWindowOpenableFromProtocolLink(obj.uri);
if (windowOpenable) {
pendingWindowOpenablesFromProtocolLinks.push(windowOpenable);
return false;
}
return true;
});
// Create a URL handler to open file URIs in the active window
// or open new windows. The URL handler will be invoked from
// protocol invocations outside of VSCode.
const app = this;
const environmentService = this.environmentMainService;
urlService.registerHandler({
async handleURL(uri: URI, options?: IOpenURLOptions): Promise<boolean> {
// If URI should be blocked, behave as if it's handled
if (app.shouldBlockURI(uri)) {
return true;
}
// Check for URIs to open in window
const windowOpenableFromProtocolLink = app.getWindowOpenableFromProtocolLink(uri);
if (windowOpenableFromProtocolLink) {
const [window] = windowsMainService.open({
context: OpenContext.API,
cli: { ...environmentService.args },
urisToOpen: [windowOpenableFromProtocolLink],
gotoLineMode: true
});
window.focus(); // this should help ensuring that the right window gets focus when multiple are opened
return true;
}
// If we have not yet handled the URI and we have no window opened (macOS only)
// we first open a window and then try to open that URI within that window
if (isMacintosh && windowsMainService.getWindowCount() === 0) {
const [window] = windowsMainService.open({
context: OpenContext.API,
cli: { ...environmentService.args },
forceEmpty: true,
gotoLineMode: true
});
await window.ready();
return urlService.open(uri, options);
}
return false;
}
});
// Create a URL handler which forwards to the last active window
const activeWindowManager = this._register(new ActiveWindowManager({
onDidOpenWindow: nativeHostMainService.onDidOpenWindow,
onDidFocusWindow: nativeHostMainService.onDidFocusWindow,
getActiveWindowId: () => nativeHostMainService.getActiveWindowId(-1)
}));
const activeWindowRouter = new StaticRouter(ctx => activeWindowManager.getActiveClientId().then(id => ctx === id));
const urlHandlerRouter = new URLHandlerRouter(activeWindowRouter);
const urlHandlerChannel = mainProcessElectronServer.getChannel('urlHandler', urlHandlerRouter);
urlService.registerHandler(new URLHandlerChannelClient(urlHandlerChannel));
// Watch Electron URLs and forward them to the UrlService
this._register(new ElectronURLListener(pendingProtocolLinksToHandle, urlService, windowsMainService, this.environmentMainService));
// Open our first window
const args = this.environmentMainService.args;
const macOpenFiles: string[] = (<any>global).macOpenFiles;
const context = isLaunchedFromCli(process.env) ? OpenContext.CLI : OpenContext.DESKTOP;
const hasCliArgs = args._.length;
const hasFolderURIs = !!args['folder-uri'];
const hasFileURIs = !!args['file-uri'];
const noRecentEntry = args['skip-add-to-recently-opened'] === true;
const waitMarkerFileURI = args.wait && args.waitMarkerFilePath ? URI.file(args.waitMarkerFilePath) : undefined;
// check for a pending window to open from URI
// e.g. when running code with --open-uri from
// a protocol handler
if (pendingWindowOpenablesFromProtocolLinks.length > 0) {
return windowsMainService.open({
context,
cli: args,
urisToOpen: pendingWindowOpenablesFromProtocolLinks,
gotoLineMode: true,
initialStartup: true
});
}
// new window if "-n"
if (args['new-window'] && !hasCliArgs && !hasFolderURIs && !hasFileURIs) {
return windowsMainService.open({
context,
cli: args,
forceNewWindow: true,
forceEmpty: true,
noRecentEntry,
waitMarkerFileURI,
initialStartup: true
});
}
// mac: open-file event received on startup
if (macOpenFiles.length && !hasCliArgs && !hasFolderURIs && !hasFileURIs) {
return windowsMainService.open({
context: OpenContext.DOCK,
cli: args,
urisToOpen: macOpenFiles.map(file => this.getWindowOpenableFromPathSync(file)),
noRecentEntry,
waitMarkerFileURI,
initialStartup: true
});
}
// default: read paths from cli
return windowsMainService.open({
context,
cli: args,
forceNewWindow: args['new-window'] || (!hasCliArgs && args['unity-launch']),
diffMode: args.diff,
noRecentEntry,
waitMarkerFileURI,
gotoLineMode: args.goto,
initialStartup: true
});
}
private shouldBlockURI(uri: URI): boolean {
if (uri.authority === Schemas.file && isWindows) {
const res = dialog.showMessageBoxSync({
title: product.nameLong,
type: 'question',
buttons: [
mnemonicButtonLabel(localize({ key: 'open', comment: ['&& denotes a mnemonic'] }, "&&Yes")),
mnemonicButtonLabel(localize({ key: 'cancel', comment: ['&& denotes a mnemonic'] }, "&&No")),
],
cancelId: 1,
message: localize('confirmOpenMessage', "An external application wants to open '{0}' in {1}. Do you want to open this file or folder?", getPathLabel(uri.fsPath, this.environmentMainService), product.nameShort),
detail: localize('confirmOpenDetail', "If you did not initiate this request, it may represent an attempted attack on your system. Unless you took an explicit action to initiate this request, you should press 'No'"),
noLink: true
});
if (res === 1) {
return true;
}
}
return false;
}
private getWindowOpenableFromProtocolLink(uri: URI): IWindowOpenable | undefined {
if (!uri.path) {
return undefined;
}
// File path
if (uri.authority === Schemas.file) {
// we configure as fileUri, but later validation will
// make sure to open as folder or workspace if possible
return { fileUri: URI.file(uri.fsPath) };
}
// Remote path
else if (uri.authority === Schemas.vscodeRemote) {
// Example conversion:
// From: vscode://vscode-remote/wsl+ubuntu/mnt/c/GitDevelopment/monaco
// To: vscode-remote://wsl+ubuntu/mnt/c/GitDevelopment/monaco
const secondSlash = uri.path.indexOf(posix.sep, 1 /* skip over the leading slash */);
if (secondSlash !== -1) {
const authority = uri.path.substring(1, secondSlash);
const path = uri.path.substring(secondSlash);
const remoteUri = URI.from({ scheme: Schemas.vscodeRemote, authority, path, query: uri.query, fragment: uri.fragment });
if (hasWorkspaceFileExtension(path)) {
return { workspaceUri: remoteUri };
} else {
return { folderUri: remoteUri };
}
}
}
return undefined;
}
private getWindowOpenableFromPathSync(path: string): IWindowOpenable {
try {
const fileStat = statSync(path);
if (fileStat.isDirectory()) {
return { folderUri: URI.file(path) };
}
if (hasWorkspaceFileExtension(path)) {
return { workspaceUri: URI.file(path) };
}
} catch (error) {
// ignore errors
}
return { fileUri: URI.file(path) };
}
private async afterWindowOpen(accessor: ServicesAccessor, sharedProcess: SharedProcess): Promise<void> {
// Signal phase: after window open
this.lifecycleMainService.phase = LifecycleMainPhase.AfterWindowOpen;
// Observe shared process for errors
const telemetryService = accessor.get(ITelemetryService);
this._register(sharedProcess.onDidError(e => {
// Logging
onUnexpectedError(new Error(e.message));
// Telemetry
type SharedProcessErrorClassification = {
type: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true };
};
type SharedProcessErrorEvent = {
type: WindowError;
};
telemetryService.publicLog2<SharedProcessErrorEvent, SharedProcessErrorClassification>('sharedprocesserror', { type: e.type });
}));
// Windows: install mutex
const win32MutexName = product.win32MutexName;
if (isWindows && win32MutexName) {
try {
const WindowsMutex = (require.__$__nodeRequire('windows-mutex') as typeof import('windows-mutex')).Mutex;
const mutex = new WindowsMutex(win32MutexName);
once(this.lifecycleMainService.onWillShutdown)(() => mutex.release());
} catch (error) {
this.logService.error(error);
}
}
// Remote Authorities
protocol.registerHttpProtocol(Schemas.vscodeRemoteResource, (request, callback) => {
callback({
url: request.url.replace(/^vscode-remote-resource:/, 'http:'),
method: request.method
});
});
// Initialize update service
const updateService = accessor.get(IUpdateService);
if (updateService instanceof Win32UpdateService || updateService instanceof LinuxUpdateService || updateService instanceof DarwinUpdateService) {
updateService.initialize();
}
// Start to fetch shell environment (if needed) after window has opened
resolveShellEnv(this.logService, this.environmentMainService.args, process.env);
// If enable-crash-reporter argv is undefined then this is a fresh start,
// based on telemetry.enableCrashreporter settings, generate a UUID which
// will be used as crash reporter id and also update the json file.
try {
const argvContent = await this.fileService.readFile(this.environmentMainService.argvResource);
const argvString = argvContent.value.toString();
const argvJSON = JSON.parse(stripComments(argvString));
if (argvJSON['enable-crash-reporter'] === undefined) {
const enableCrashReporter = this.configurationService.getValue<boolean>('telemetry.enableCrashReporter') ?? true;
const additionalArgvContent = [
'',
' // Allows to disable crash reporting.',
' // Should restart the app if the value is changed.',
` "enable-crash-reporter": ${enableCrashReporter},`,
'',
' // Unique id used for correlating crash reports sent from this instance.',
' // Do not edit this value.',
` "crash-reporter-id": "${generateUuid()}"`,
'}'
];
const newArgvString = argvString.substring(0, argvString.length - 2).concat(',\n', additionalArgvContent.join('\n'));
await this.fileService.writeFile(this.environmentMainService.argvResource, VSBuffer.fromString(newArgvString));
}
} catch (error) {
this.logService.error(error);
}
}
private stopTracingEventually(accessor: ServicesAccessor, windows: ICodeWindow[]): void {
this.logService.info(`Tracing: waiting for windows to get ready...`);
const dialogMainService = accessor.get(IDialogMainService);
let recordingStopped = false;
const stopRecording = async (timeout: boolean) => {
if (recordingStopped) {
return;
}
recordingStopped = true; // only once
const path = await contentTracing.stopRecording(joinPath(this.environmentMainService.userHome, `${product.applicationName}-${Math.random().toString(16).slice(-4)}.trace.txt`).fsPath);
if (!timeout) {
dialogMainService.showMessageBox({
type: 'info',
message: localize('trace.message', "Successfully created trace."),
detail: localize('trace.detail', "Please create an issue and manually attach the following file:\n{0}", path),
buttons: [localize('trace.ok', "OK")]
}, withNullAsUndefined(BrowserWindow.getFocusedWindow()));
} else {
this.logService.info(`Tracing: data recorded (after 30s timeout) to ${path}`);
}
};
// Wait up to 30s before creating the trace anyways
const timeoutHandle = setTimeout(() => stopRecording(true), 30000);
// Wait for all windows to get ready and stop tracing then
Promise.all(windows.map(window => window.ready())).then(() => {
clearTimeout(timeoutHandle);
stopRecording(false);
});
}
}
| src/vs/code/electron-main/app.ts | 1 | https://github.com/microsoft/vscode/commit/608e8791ff194e81a10ac0d963471922ddc9b6e0 | [
0.9887017011642456,
0.01018182560801506,
0.00015967727813404053,
0.00016873767890501767,
0.09607116132974625
] |
{
"id": 0,
"code_window": [
"\n",
"\t\t\t\tthis.nativeHostMainService?.openExternal(undefined, url);\n",
"\t\t\t});\n",
"\n",
"\t\t\tsession.defaultSession.setPermissionRequestHandler((webContents, permission /* 'media' | 'geolocation' | 'notifications' | 'midiSysex' | 'pointerLock' | 'fullscreen' | 'openExternal' */, callback) => {\n",
"\t\t\t\treturn callback(false);\n",
"\t\t\t});\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\tconst webviewFrameUrl = 'about:blank?webviewFrame';\n",
"\n",
"\t\t\tsession.defaultSession.setPermissionRequestHandler((_webContents, permission /* 'media' | 'geolocation' | 'notifications' | 'midiSysex' | 'pointerLock' | 'fullscreen' | 'openExternal' */, callback, details) => {\n",
"\t\t\t\tif (details.requestingUrl === webviewFrameUrl) {\n",
"\t\t\t\t\treturn callback(permission === 'clipboard-read');\n",
"\t\t\t\t}\n"
],
"file_path": "src/vs/code/electron-main/app.ts",
"type": "replace",
"edit_start_line_idx": 227
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as nls from 'vs/nls';
import { IJSONSchema } from 'vs/base/common/jsonSchema';
import { IConfigurationNode, IConfigurationRegistry, Extensions } from 'vs/platform/configuration/common/configurationRegistry';
import { workbenchConfigurationNodeBase } from 'vs/workbench/common/configuration';
import { Registry } from 'vs/platform/registry/common/platform';
import { ICustomEditorInfo, IEditorService, IOpenEditorOverrideHandler, IOpenEditorOverrideEntry } from 'vs/workbench/services/editor/common/editorService';
import { IEditorInput, IEditorPane, IEditorInputFactoryRegistry, Extensions as EditorExtensions, EditorResourceAccessor, EditorOptions } from 'vs/workbench/common/editor';
import { ITextEditorOptions, IEditorOptions } from 'vs/platform/editor/common/editor';
import { IEditorGroup, IEditorGroupsService, OpenEditorContext, preferredSideBySideGroupDirection } from 'vs/workbench/services/editor/common/editorGroupsService';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { IKeyMods, IQuickInputService, IQuickPickItem } from 'vs/platform/quickinput/common/quickInput';
import { URI } from 'vs/base/common/uri';
import { extname, basename, isEqual } from 'vs/base/common/resources';
import { Codicon } from 'vs/base/common/codicons';
import { ServicesAccessor } from 'vs/platform/instantiation/common/instantiation';
import { firstOrDefault } from 'vs/base/common/arrays';
/**
* Id of the default editor for open with.
*/
export const DEFAULT_EDITOR_ID = 'default';
/**
* Try to open an resource with a given editor.
*
* @param input Resource to open.
* @param id Id of the editor to use. If not provided, the user is prompted for which editor to use.
*/
export async function openEditorWith(
accessor: ServicesAccessor,
input: IEditorInput,
id: string | undefined,
options: IEditorOptions | ITextEditorOptions | undefined,
group: IEditorGroup,
): Promise<IEditorPane | undefined> {
const editorService = accessor.get(IEditorService);
const editorGroupsService = accessor.get(IEditorGroupsService);
const configurationService = accessor.get(IConfigurationService);
const quickInputService = accessor.get(IQuickInputService);
const resource = input.resource;
if (!resource) {
return;
}
const overrideOptions = { ...options, override: id };
const allEditorOverrides = getAllAvailableEditors(resource, id, overrideOptions, group, editorService);
if (!allEditorOverrides.length) {
return;
}
let overrideToUse;
if (typeof id === 'string') {
overrideToUse = allEditorOverrides.find(([_, entry]) => entry.id === id);
} else if (allEditorOverrides.length === 1) {
overrideToUse = allEditorOverrides[0];
}
if (overrideToUse) {
return overrideToUse[0].open(input, overrideOptions, group, OpenEditorContext.NEW_EDITOR)?.override;
}
// Prompt
const originalResource = EditorResourceAccessor.getOriginalUri(input) || resource;
const resourceExt = extname(originalResource);
const items: (IQuickPickItem & { handler: IOpenEditorOverrideHandler })[] = allEditorOverrides.map(([handler, entry]) => {
return {
handler: handler,
id: entry.id,
label: entry.label,
description: entry.active ? nls.localize('promptOpenWith.currentlyActive', 'Currently Active') : undefined,
detail: entry.detail,
buttons: resourceExt ? [{
iconClass: Codicon.gear.classNames,
tooltip: nls.localize('promptOpenWith.setDefaultTooltip', "Set as default editor for '{0}' files", resourceExt)
}] : undefined
};
});
type QuickPickItem = IQuickPickItem & {
readonly handler: IOpenEditorOverrideHandler;
};
const picker = quickInputService.createQuickPick<QuickPickItem>();
picker.items = items;
if (items.length) {
picker.selectedItems = [items[0]];
}
picker.placeholder = nls.localize('promptOpenWith.placeHolder', "Select editor for '{0}'", basename(originalResource));
picker.canAcceptInBackground = true;
type PickedResult = {
readonly item: QuickPickItem;
readonly keyMods?: IKeyMods;
readonly openInBackground: boolean;
};
function openEditor(picked: PickedResult) {
const targetGroup = getTargetGroup(group, picked.keyMods, configurationService, editorGroupsService);
const openOptions: IEditorOptions = {
...options,
override: picked.item.id,
preserveFocus: picked.openInBackground || options?.preserveFocus,
};
return picked.item.handler.open(input, openOptions, targetGroup, OpenEditorContext.NEW_EDITOR)?.override;
}
let picked: PickedResult | undefined;
try {
picked = await new Promise<PickedResult | undefined>(resolve => {
picker.onDidAccept(e => {
if (picker.selectedItems.length === 1) {
const result: PickedResult = {
item: picker.selectedItems[0],
keyMods: picker.keyMods,
openInBackground: e.inBackground
};
if (e.inBackground) {
openEditor(result);
} else {
resolve(result);
}
} else {
resolve(undefined);
}
});
picker.onDidTriggerItemButton(e => {
const pick = e.item;
const id = pick.id;
resolve({ item: pick, openInBackground: false }); // open the view
picker.dispose();
// And persist the setting
if (pick && id) {
const newAssociation: CustomEditorAssociation = { viewType: id, filenamePattern: '*' + resourceExt };
const currentAssociations = [...configurationService.getValue<CustomEditorsAssociations>(customEditorsAssociationsSettingId)];
// First try updating existing association
for (let i = 0; i < currentAssociations.length; ++i) {
const existing = currentAssociations[i];
if (existing.filenamePattern === newAssociation.filenamePattern) {
currentAssociations.splice(i, 1, newAssociation);
configurationService.updateValue(customEditorsAssociationsSettingId, currentAssociations);
return;
}
}
// Otherwise, create a new one
currentAssociations.unshift(newAssociation);
configurationService.updateValue(customEditorsAssociationsSettingId, currentAssociations);
}
});
picker.show();
});
} finally {
picker.dispose();
}
if (!picked) {
return undefined;
}
return openEditor(picked);
}
const builtinProviderDisplayName = nls.localize('builtinProviderDisplayName', "Built-in");
export const defaultEditorOverrideEntry = Object.freeze({
id: DEFAULT_EDITOR_ID,
label: nls.localize('promptOpenWith.defaultEditor.displayName', "Text Editor"),
detail: builtinProviderDisplayName
});
/**
* Get the group to open the editor in by looking at the pressed keys from the picker.
*/
function getTargetGroup(
startingGroup: IEditorGroup,
keyMods: IKeyMods | undefined,
configurationService: IConfigurationService,
editorGroupsService: IEditorGroupsService,
) {
if (keyMods?.alt || keyMods?.ctrlCmd) {
const direction = preferredSideBySideGroupDirection(configurationService);
const targetGroup = editorGroupsService.findGroup({ direction }, startingGroup.id);
return targetGroup ?? editorGroupsService.addGroup(startingGroup, direction);
}
return startingGroup;
}
/**
* Get a list of all available editors, including the default text editor.
*/
export function getAllAvailableEditors(
resource: URI,
id: string | undefined,
options: IEditorOptions | ITextEditorOptions | undefined,
group: IEditorGroup,
editorService: IEditorService
): Array<[IOpenEditorOverrideHandler, IOpenEditorOverrideEntry]> {
const fileEditorInputFactory = Registry.as<IEditorInputFactoryRegistry>(EditorExtensions.EditorInputFactories).getFileEditorInputFactory();
const overrides = editorService.getEditorOverrides(resource, options, group);
if (!overrides.some(([_, entry]) => entry.id === DEFAULT_EDITOR_ID)) {
overrides.unshift([
{
open: (input: IEditorInput, options: IEditorOptions | ITextEditorOptions | undefined, group: IEditorGroup) => {
const resource = EditorResourceAccessor.getOriginalUri(input);
if (!resource) {
return;
}
const fileEditorInput = editorService.createEditorInput({ resource, forceFile: true });
const textOptions: IEditorOptions | ITextEditorOptions = options ? { ...options, override: false } : { override: false };
return {
override: (async () => {
// Try to replace existing editors for resource
const existingEditor = firstOrDefault(editorService.findEditors(resource, group));
if (existingEditor && !fileEditorInput.matches(existingEditor)) {
await editorService.replaceEditors([{
editor: existingEditor,
replacement: fileEditorInput,
options: options ? EditorOptions.create(options) : undefined,
}], group);
}
return editorService.openEditor(fileEditorInput, textOptions, group);
})()
};
}
},
{
...defaultEditorOverrideEntry,
active: fileEditorInputFactory.isFileEditorInput(editorService.activeEditor) && isEqual(editorService.activeEditor.resource, resource),
}]);
}
return overrides;
}
export const customEditorsAssociationsSettingId = 'workbench.editorAssociations';
export const viewTypeSchemaAddition: IJSONSchema = {
type: 'string',
enum: []
};
export type CustomEditorAssociation = {
readonly viewType: string;
readonly filenamePattern?: string;
};
export type CustomEditorsAssociations = readonly CustomEditorAssociation[];
export const editorAssociationsConfigurationNode: IConfigurationNode = {
...workbenchConfigurationNodeBase,
properties: {
[customEditorsAssociationsSettingId]: {
type: 'array',
markdownDescription: nls.localize('editor.editorAssociations', "Configure which editor to use for specific file types."),
items: {
type: 'object',
defaultSnippets: [{
body: {
'viewType': '$1',
'filenamePattern': '$2'
}
}],
properties: {
'viewType': {
anyOf: [
{
type: 'string',
description: nls.localize('editor.editorAssociations.viewType', "The unique id of the editor to use."),
},
viewTypeSchemaAddition
]
},
'filenamePattern': {
type: 'string',
description: nls.localize('editor.editorAssociations.filenamePattern', "Glob pattern specifying which files the editor should be used for."),
}
}
}
}
}
};
export const DEFAULT_CUSTOM_EDITOR: ICustomEditorInfo = {
id: 'default',
displayName: nls.localize('promptOpenWith.defaultEditor.displayName', "Text Editor"),
providerDisplayName: builtinProviderDisplayName
};
export function updateViewTypeSchema(enumValues: string[], enumDescriptions: string[]): void {
viewTypeSchemaAddition.enum = enumValues;
viewTypeSchemaAddition.enumDescriptions = enumDescriptions;
Registry.as<IConfigurationRegistry>(Extensions.Configuration)
.notifyConfigurationSchemaUpdated(editorAssociationsConfigurationNode);
}
| src/vs/workbench/services/editor/common/editorOpenWith.ts | 0 | https://github.com/microsoft/vscode/commit/608e8791ff194e81a10ac0d963471922ddc9b6e0 | [
0.00017757421301212162,
0.00017218974244315177,
0.00016043471987359226,
0.0001731316006043926,
0.000003731304104803712
] |
{
"id": 0,
"code_window": [
"\n",
"\t\t\t\tthis.nativeHostMainService?.openExternal(undefined, url);\n",
"\t\t\t});\n",
"\n",
"\t\t\tsession.defaultSession.setPermissionRequestHandler((webContents, permission /* 'media' | 'geolocation' | 'notifications' | 'midiSysex' | 'pointerLock' | 'fullscreen' | 'openExternal' */, callback) => {\n",
"\t\t\t\treturn callback(false);\n",
"\t\t\t});\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\tconst webviewFrameUrl = 'about:blank?webviewFrame';\n",
"\n",
"\t\t\tsession.defaultSession.setPermissionRequestHandler((_webContents, permission /* 'media' | 'geolocation' | 'notifications' | 'midiSysex' | 'pointerLock' | 'fullscreen' | 'openExternal' */, callback, details) => {\n",
"\t\t\t\tif (details.requestingUrl === webviewFrameUrl) {\n",
"\t\t\t\t\treturn callback(permission === 'clipboard-read');\n",
"\t\t\t\t}\n"
],
"file_path": "src/vs/code/electron-main/app.ts",
"type": "replace",
"edit_start_line_idx": 227
} | # THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY.
# yarn lockfile v1
"@types/node@^12.19.9":
version "12.19.9"
resolved "https://registry.yarnpkg.com/@types/node/-/node-12.19.9.tgz#990ad687ad8b26ef6dcc34a4f69c33d40c95b679"
integrity sha512-yj0DOaQeUrk3nJ0bd3Y5PeDRJ6W0r+kilosLA+dzF3dola/o9hxhMSg2sFvVcA2UHS5JSOsZp4S0c1OEXc4m1Q==
"@types/p-limit@^2.2.0":
version "2.2.0"
resolved "https://registry.yarnpkg.com/@types/p-limit/-/p-limit-2.2.0.tgz#94a608e9b258a6c6156a13d1a14fd720dba70b97"
integrity sha512-fGFbybl1r0oE9mqgfc2EHHUin9ZL5rbQIexWI6jYRU1ADVn4I3LHzT+g/kpPpZsfp8PB94CQ655pfAjNF8LP6A==
dependencies:
p-limit "*"
p-limit@*, p-limit@^3.0.2:
version "3.0.2"
resolved "https://registry.yarnpkg.com/p-limit/-/p-limit-3.0.2.tgz#1664e010af3cadc681baafd3e2a437be7b0fb5fe"
integrity sha512-iwqZSOoWIW+Ew4kAGUlN16J4M7OB3ysMLSZtnhmqx7njIHFPlxWBX8xo3lVTyFVq6mI/lL9qt2IsN1sHwaxJkg==
dependencies:
p-try "^2.0.0"
p-try@^2.0.0:
version "2.2.0"
resolved "https://registry.yarnpkg.com/p-try/-/p-try-2.2.0.tgz#cb2868540e313d61de58fafbe35ce9004d5540e6"
integrity sha512-R4nPAVTAU0B9D35/Gk3uJf/7XYbQcyohSKdvAxIRSNghFl4e71hVoGnBNQz9cWaXxO2I10KTC+3jMdvvoKw6dQ==
| extensions/vscode-custom-editor-tests/yarn.lock | 0 | https://github.com/microsoft/vscode/commit/608e8791ff194e81a10ac0d963471922ddc9b6e0 | [
0.000172589483554475,
0.00016902247443795204,
0.0001644519652472809,
0.00017002600361593068,
0.000003397066393517889
] |
{
"id": 0,
"code_window": [
"\n",
"\t\t\t\tthis.nativeHostMainService?.openExternal(undefined, url);\n",
"\t\t\t});\n",
"\n",
"\t\t\tsession.defaultSession.setPermissionRequestHandler((webContents, permission /* 'media' | 'geolocation' | 'notifications' | 'midiSysex' | 'pointerLock' | 'fullscreen' | 'openExternal' */, callback) => {\n",
"\t\t\t\treturn callback(false);\n",
"\t\t\t});\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\tconst webviewFrameUrl = 'about:blank?webviewFrame';\n",
"\n",
"\t\t\tsession.defaultSession.setPermissionRequestHandler((_webContents, permission /* 'media' | 'geolocation' | 'notifications' | 'midiSysex' | 'pointerLock' | 'fullscreen' | 'openExternal' */, callback, details) => {\n",
"\t\t\t\tif (details.requestingUrl === webviewFrameUrl) {\n",
"\t\t\t\t\treturn callback(permission === 'clipboard-read');\n",
"\t\t\t\t}\n"
],
"file_path": "src/vs/code/electron-main/app.ts",
"type": "replace",
"edit_start_line_idx": 227
} | <!DOCTYPE html>
<html>
<head id='headID'>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<title>Strada </title>
<link href="site.css" rel="stylesheet" type="text/css" />
<script src="jquery-1.4.1.js"></script>
<script src="../compiler/dtree.js" type="text/javascript"></script>
<script src="../compiler/typescript.js" type="text/javascript"></script>
<script type="text/javascript">
// Compile strada source into resulting javascript
function compile(prog, libText) {
var outfile = {
source: "",
Write: function (s) { this.source += s; },
WriteLine: function (s) { this.source += s + "\r"; },
}
var parseErrors = []
var compiler=new Tools.TypeScriptCompiler(outfile,true);
compiler.setErrorCallback(function(start,len, message) { parseErrors.push({start:start, len:len, message:message}); });
compiler.addUnit(libText,"lib.ts");
compiler.addUnit(prog,"input.ts");
compiler.typeCheck();
compiler.emit();
if(parseErrors.length > 0 ) {
//throw new Error(parseErrors);
}
while(outfile.source[0] == '/' && outfile.source[1] == '/' && outfile.source[2] == ' ') {
outfile.source = outfile.source.slice(outfile.source.indexOf('\r')+1);
}
var errorPrefix = "";
for(var i = 0;i<parseErrors.length;i++) {
errorPrefix += "// Error: (" + parseErrors[i].start + "," + parseErrors[i].len + ") " + parseErrors[i].message + "\r";
}
return errorPrefix + outfile.source;
}
</script>
<script type="text/javascript">
var libText = "";
$.get("../compiler/lib.ts", function(newLibText) {
libText = newLibText;
});
// execute the javascript in the compiledOutput pane
function execute() {
$('#compilation').text("Running...");
var txt = $('#compiledOutput').val();
var res;
try {
var ret = eval(txt);
res = "Ran successfully!";
} catch(e) {
res = "Exception thrown: " + e;
}
$('#compilation').text(String(res));
}
// recompile the stradaSrc and populate the compiledOutput pane
function srcUpdated() {
var newText = $('#stradaSrc').val();
var compiledSource;
try {
compiledSource = compile(newText, libText);
} catch (e) {
compiledSource = "//Parse error"
for(var i in e)
compiledSource += "\r// " + e[i];
}
$('#compiledOutput').val(compiledSource);
}
// Populate the stradaSrc pane with one of the built in samples
function exampleSelectionChanged() {
var examples = document.getElementById('examples');
var selectedExample = examples.options[examples.selectedIndex].value;
if (selectedExample != "") {
$.get('examples/' + selectedExample, function (srcText) {
$('#stradaSrc').val(srcText);
setTimeout(srcUpdated,100);
}, function (err) {
console.log(err);
});
}
}
</script>
</head>
<body>
<h1>TypeScript</h1>
<br />
<select id="examples" onchange='exampleSelectionChanged()'>
<option value="">Select...</option>
<option value="small.ts">Small</option>
<option value="employee.ts">Employees</option>
<option value="conway.ts">Conway Game of Life</option>
<option value="typescript.ts">TypeScript Compiler</option>
</select>
<div>
<textarea id='stradaSrc' rows='40' cols='80' onchange='srcUpdated()' onkeyup='srcUpdated()' spellcheck="false">
//Type your TypeScript here...
</textarea>
<textarea id='compiledOutput' rows='40' cols='80' spellcheck="false">
//Compiled code will show up here...
</textarea>
<br />
<button onclick='execute()'/>Run</button>
<div id='compilation'>Press 'run' to execute code...</div>
<div id='results'>...write your results into #results...</div>
</div>
<div id='bod' style='display:none'></div>
</body>
</html>
| src/vs/workbench/services/textfile/test/electron-browser/fixtures/index.html | 0 | https://github.com/microsoft/vscode/commit/608e8791ff194e81a10ac0d963471922ddc9b6e0 | [
0.00017847980780061334,
0.0001751238596625626,
0.00017310369003098458,
0.00017475700587965548,
0.0000014706843103340361
] |
{
"id": 1,
"code_window": [
"\t\t\t\treturn callback(false);\n",
"\t\t\t});\n",
"\n",
"\t\t\tsession.defaultSession.setPermissionCheckHandler((webContents, permission /* 'media' */) => {\n",
"\t\t\t\treturn false;\n",
"\t\t\t});\n",
"\t\t});\n",
"\n",
"\t\t//#endregion\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\tsession.defaultSession.setPermissionCheckHandler((_webContents, permission /* 'media' */, _origin, details) => {\n",
"\t\t\t\tif (details.requestingUrl === webviewFrameUrl) {\n",
"\t\t\t\t\treturn permission === 'clipboard-read';\n",
"\t\t\t\t}\n"
],
"file_path": "src/vs/code/electron-main/app.ts",
"type": "replace",
"edit_start_line_idx": 231
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { release } from 'os';
import { statSync } from 'fs';
import { app, ipcMain, systemPreferences, contentTracing, protocol, BrowserWindow, dialog, session } from 'electron';
import { IProcessEnvironment, isWindows, isMacintosh, isLinux, isLinuxSnap } from 'vs/base/common/platform';
import { WindowsMainService } from 'vs/platform/windows/electron-main/windowsMainService';
import { IWindowOpenable } from 'vs/platform/windows/common/windows';
import { ILifecycleMainService, LifecycleMainPhase } from 'vs/platform/lifecycle/electron-main/lifecycleMainService';
import { resolveShellEnv } from 'vs/platform/environment/node/shellEnv';
import { IUpdateService } from 'vs/platform/update/common/update';
import { UpdateChannel } from 'vs/platform/update/common/updateIpc';
import { getDelayedChannel, StaticRouter, ProxyChannel } from 'vs/base/parts/ipc/common/ipc';
import { Server as ElectronIPCServer } from 'vs/base/parts/ipc/electron-main/ipc.electron';
import { Server as NodeIPCServer } from 'vs/base/parts/ipc/node/ipc.net';
import { Client as MessagePortClient } from 'vs/base/parts/ipc/electron-main/ipc.mp';
import { SharedProcess } from 'vs/platform/sharedProcess/electron-main/sharedProcess';
import { LaunchMainService, ILaunchMainService } from 'vs/platform/launch/electron-main/launchMainService';
import { IInstantiationService, ServicesAccessor } from 'vs/platform/instantiation/common/instantiation';
import { ServiceCollection } from 'vs/platform/instantiation/common/serviceCollection';
import { SyncDescriptor } from 'vs/platform/instantiation/common/descriptors';
import { ILoggerService, ILogService } from 'vs/platform/log/common/log';
import { IStateService } from 'vs/platform/state/node/state';
import { IEnvironmentMainService } from 'vs/platform/environment/electron-main/environmentMainService';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { IOpenURLOptions, IURLService } from 'vs/platform/url/common/url';
import { URLHandlerChannelClient, URLHandlerRouter } from 'vs/platform/url/common/urlIpc';
import { ITelemetryService, machineIdKey } from 'vs/platform/telemetry/common/telemetry';
import { NullTelemetryService } from 'vs/platform/telemetry/common/telemetryUtils';
import { TelemetryAppenderClient } from 'vs/platform/telemetry/common/telemetryIpc';
import { TelemetryService, ITelemetryServiceConfig } from 'vs/platform/telemetry/common/telemetryService';
import { resolveCommonProperties } from 'vs/platform/telemetry/common/commonProperties';
import product from 'vs/platform/product/common/product';
import { ProxyAuthHandler } from 'vs/code/electron-main/auth';
import { FileProtocolHandler } from 'vs/code/electron-main/protocol';
import { Disposable } from 'vs/base/common/lifecycle';
import { IWindowsMainService, ICodeWindow, OpenContext, WindowError } from 'vs/platform/windows/electron-main/windows';
import { URI } from 'vs/base/common/uri';
import { hasWorkspaceFileExtension, IWorkspacesService } from 'vs/platform/workspaces/common/workspaces';
import { WorkspacesMainService } from 'vs/platform/workspaces/electron-main/workspacesMainService';
import { getMachineId } from 'vs/base/node/id';
import { Win32UpdateService } from 'vs/platform/update/electron-main/updateService.win32';
import { LinuxUpdateService } from 'vs/platform/update/electron-main/updateService.linux';
import { DarwinUpdateService } from 'vs/platform/update/electron-main/updateService.darwin';
import { IssueMainService, IIssueMainService } from 'vs/platform/issue/electron-main/issueMainService';
import { LoggerChannel, LogLevelChannel } from 'vs/platform/log/common/logIpc';
import { setUnexpectedErrorHandler, onUnexpectedError } from 'vs/base/common/errors';
import { ElectronURLListener } from 'vs/platform/url/electron-main/electronUrlListener';
import { serve as serveDriver } from 'vs/platform/driver/electron-main/driver';
import { IMenubarMainService, MenubarMainService } from 'vs/platform/menubar/electron-main/menubarMainService';
import { RunOnceScheduler } from 'vs/base/common/async';
import { registerContextMenuListener } from 'vs/base/parts/contextmenu/electron-main/contextmenu';
import { sep, posix, join, isAbsolute } from 'vs/base/common/path';
import { joinPath } from 'vs/base/common/resources';
import { localize } from 'vs/nls';
import { Schemas } from 'vs/base/common/network';
import { SnapUpdateService } from 'vs/platform/update/electron-main/updateService.snap';
import { IStorageMainService, StorageMainService } from 'vs/platform/storage/electron-main/storageMainService';
import { StorageDatabaseChannel } from 'vs/platform/storage/electron-main/storageIpc';
import { BackupMainService } from 'vs/platform/backup/electron-main/backupMainService';
import { IBackupMainService } from 'vs/platform/backup/electron-main/backup';
import { WorkspacesHistoryMainService, IWorkspacesHistoryMainService } from 'vs/platform/workspaces/electron-main/workspacesHistoryMainService';
import { NativeURLService } from 'vs/platform/url/common/urlService';
import { WorkspacesManagementMainService, IWorkspacesManagementMainService } from 'vs/platform/workspaces/electron-main/workspacesManagementMainService';
import { IDiagnosticsService } from 'vs/platform/diagnostics/common/diagnostics';
import { ElectronExtensionHostDebugBroadcastChannel } from 'vs/platform/debug/electron-main/extensionHostDebugIpc';
import { INativeHostMainService, NativeHostMainService } from 'vs/platform/native/electron-main/nativeHostMainService';
import { IDialogMainService, DialogMainService } from 'vs/platform/dialogs/electron-main/dialogMainService';
import { withNullAsUndefined } from 'vs/base/common/types';
import { mnemonicButtonLabel, getPathLabel } from 'vs/base/common/labels';
import { WebviewMainService } from 'vs/platform/webview/electron-main/webviewMainService';
import { IWebviewManagerService } from 'vs/platform/webview/common/webviewManagerService';
import { IFileService } from 'vs/platform/files/common/files';
import { stripComments } from 'vs/base/common/json';
import { generateUuid } from 'vs/base/common/uuid';
import { VSBuffer } from 'vs/base/common/buffer';
import { EncryptionMainService, IEncryptionMainService } from 'vs/platform/encryption/electron-main/encryptionMainService';
import { ActiveWindowManager } from 'vs/platform/windows/node/windowTracker';
import { IKeyboardLayoutMainService, KeyboardLayoutMainService } from 'vs/platform/keyboardLayout/electron-main/keyboardLayoutMainService';
import { NativeParsedArgs } from 'vs/platform/environment/common/argv';
import { DisplayMainService, IDisplayMainService } from 'vs/platform/display/electron-main/displayMainService';
import { isLaunchedFromCli } from 'vs/platform/environment/node/argvHelper';
import { isEqualOrParent } from 'vs/base/common/extpath';
import { CancellationToken, CancellationTokenSource } from 'vs/base/common/cancellation';
import { IExtensionUrlTrustService } from 'vs/platform/extensionManagement/common/extensionUrlTrust';
import { ExtensionUrlTrustService } from 'vs/platform/extensionManagement/node/extensionUrlTrustService';
import { once } from 'vs/base/common/functional';
/**
* The main VS Code application. There will only ever be one instance,
* even if the user starts many instances (e.g. from the command line).
*/
export class CodeApplication extends Disposable {
private windowsMainService: IWindowsMainService | undefined;
private nativeHostMainService: INativeHostMainService | undefined;
constructor(
private readonly mainProcessNodeIpcServer: NodeIPCServer,
private readonly userEnv: IProcessEnvironment,
@IInstantiationService private readonly mainInstantiationService: IInstantiationService,
@ILogService private readonly logService: ILogService,
@IEnvironmentMainService private readonly environmentMainService: IEnvironmentMainService,
@ILifecycleMainService private readonly lifecycleMainService: ILifecycleMainService,
@IConfigurationService private readonly configurationService: IConfigurationService,
@IStateService private readonly stateService: IStateService,
@IFileService private readonly fileService: IFileService
) {
super();
this.registerListeners();
}
private registerListeners(): void {
// We handle uncaught exceptions here to prevent electron from opening a dialog to the user
setUnexpectedErrorHandler(err => this.onUnexpectedError(err));
process.on('uncaughtException', err => this.onUnexpectedError(err));
process.on('unhandledRejection', (reason: unknown) => onUnexpectedError(reason));
// Dispose on shutdown
this.lifecycleMainService.onWillShutdown(() => this.dispose());
// Contextmenu via IPC support
registerContextMenuListener();
// Accessibility change event
app.on('accessibility-support-changed', (event, accessibilitySupportEnabled) => {
this.windowsMainService?.sendToAll('vscode:accessibilitySupportChanged', accessibilitySupportEnabled);
});
// macOS dock activate
app.on('activate', (event, hasVisibleWindows) => {
this.logService.trace('app#activate');
// Mac only event: open new window when we get activated
if (!hasVisibleWindows) {
this.windowsMainService?.openEmptyWindow({ context: OpenContext.DOCK });
}
});
//#region Security related measures (https://electronjs.org/docs/tutorial/security)
//
// !!! DO NOT CHANGE without consulting the documentation !!!
//
app.on('remote-require', (event, sender, module) => {
this.logService.trace('app#on(remote-require): prevented');
event.preventDefault();
});
app.on('remote-get-global', (event, sender, module) => {
this.logService.trace(`app#on(remote-get-global): prevented on ${module}`);
event.preventDefault();
});
app.on('remote-get-builtin', (event, sender, module) => {
this.logService.trace(`app#on(remote-get-builtin): prevented on ${module}`);
if (module !== 'clipboard') {
event.preventDefault();
}
});
app.on('remote-get-current-window', event => {
this.logService.trace(`app#on(remote-get-current-window): prevented`);
event.preventDefault();
});
app.on('remote-get-current-web-contents', event => {
if (this.environmentMainService.args.driver) {
return; // the driver needs access to web contents
}
this.logService.trace(`app#on(remote-get-current-web-contents): prevented`);
event.preventDefault();
});
app.on('web-contents-created', (event, contents) => {
contents.on('will-attach-webview', (event, webPreferences, params) => {
const isValidWebviewSource = (source: string | undefined): boolean => {
if (!source) {
return false;
}
const uri = URI.parse(source);
if (uri.scheme === Schemas.vscodeWebview) {
return uri.path === '/index.html' || uri.path === '/electron-browser/index.html';
}
const srcUri = uri.fsPath.toLowerCase();
const rootUri = URI.file(this.environmentMainService.appRoot).fsPath.toLowerCase();
return srcUri.startsWith(rootUri + sep);
};
// Ensure defaults
delete webPreferences.preload;
webPreferences.nodeIntegration = false;
// Verify URLs being loaded
// https://github.com/electron/electron/issues/21553
if (isValidWebviewSource(params.src) && isValidWebviewSource((webPreferences as { preloadURL: string }).preloadURL)) {
return;
}
delete (webPreferences as { preloadURL: string | undefined }).preloadURL; // https://github.com/electron/electron/issues/21553
// Otherwise prevent loading
this.logService.error('webContents#web-contents-created: Prevented webview attach');
event.preventDefault();
});
contents.on('will-navigate', event => {
this.logService.error('webContents#will-navigate: Prevented webcontent navigation');
event.preventDefault();
});
contents.on('new-window', (event, url) => {
event.preventDefault(); // prevent code that wants to open links
this.nativeHostMainService?.openExternal(undefined, url);
});
session.defaultSession.setPermissionRequestHandler((webContents, permission /* 'media' | 'geolocation' | 'notifications' | 'midiSysex' | 'pointerLock' | 'fullscreen' | 'openExternal' */, callback) => {
return callback(false);
});
session.defaultSession.setPermissionCheckHandler((webContents, permission /* 'media' */) => {
return false;
});
});
//#endregion
let macOpenFileURIs: IWindowOpenable[] = [];
let runningTimeout: NodeJS.Timeout | null = null;
app.on('open-file', (event, path) => {
this.logService.trace('app#open-file: ', path);
event.preventDefault();
// Keep in array because more might come!
macOpenFileURIs.push(this.getWindowOpenableFromPathSync(path));
// Clear previous handler if any
if (runningTimeout !== null) {
clearTimeout(runningTimeout);
runningTimeout = null;
}
// Handle paths delayed in case more are coming!
runningTimeout = setTimeout(() => {
this.windowsMainService?.open({
context: OpenContext.DOCK /* can also be opening from finder while app is running */,
cli: this.environmentMainService.args,
urisToOpen: macOpenFileURIs,
gotoLineMode: false,
preferNewWindow: true /* dropping on the dock or opening from finder prefers to open in a new window */
});
macOpenFileURIs = [];
runningTimeout = null;
}, 100);
});
app.on('new-window-for-tab', () => {
this.windowsMainService?.openEmptyWindow({ context: OpenContext.DESKTOP }); //macOS native tab "+" button
});
//#region Bootstrap IPC Handlers
let slowShellResolveWarningShown = false;
ipcMain.on('vscode:fetchShellEnv', async event => {
// DO NOT remove: not only usual windows are fetching the
// shell environment but also shared process, issue reporter
// etc, so we need to reply via `webContents` always
const webContents = event.sender;
let replied = false;
function acceptShellEnv(env: NodeJS.ProcessEnv): void {
clearTimeout(shellEnvSlowWarningHandle);
clearTimeout(shellEnvTimeoutErrorHandle);
if (!replied) {
replied = true;
if (!webContents.isDestroyed()) {
webContents.send('vscode:acceptShellEnv', env);
}
}
}
// Handle slow shell environment resolve calls:
// - a warning after 3s but continue to resolve (only once in active window)
// - an error after 10s and stop trying to resolve (in every window where this happens)
const cts = new CancellationTokenSource();
const shellEnvSlowWarningHandle = setTimeout(() => {
if (!slowShellResolveWarningShown) {
this.windowsMainService?.sendToFocused('vscode:showShellEnvSlowWarning', cts.token);
slowShellResolveWarningShown = true;
}
}, 3000);
const window = this.windowsMainService?.getWindowByWebContents(event.sender); // Note: this can be `undefined` for the shared process!!
const shellEnvTimeoutErrorHandle = setTimeout(() => {
cts.dispose(true);
window?.sendWhenReady('vscode:showShellEnvTimeoutError', CancellationToken.None);
acceptShellEnv({});
}, 10000);
// Prefer to use the args and env from the target window
// when resolving the shell env. It is possible that
// a first window was opened from the UI but a second
// from the CLI and that has implications for whether to
// resolve the shell environment or not.
//
// Window can be undefined for e.g. the shared process
// that is not part of our windows registry!
let args: NativeParsedArgs;
let env: NodeJS.ProcessEnv;
if (window?.config) {
args = window.config;
env = { ...process.env, ...window.config.userEnv };
} else {
args = this.environmentMainService.args;
env = process.env;
}
// Resolve shell env
const shellEnv = await resolveShellEnv(this.logService, args, env);
acceptShellEnv(shellEnv);
});
ipcMain.handle('vscode:writeNlsFile', async (event, path: unknown, data: unknown) => {
const uri = this.validateNlsPath([path]);
if (!uri || typeof data !== 'string') {
throw new Error('Invalid operation (vscode:writeNlsFile)');
}
return this.fileService.writeFile(uri, VSBuffer.fromString(data));
});
ipcMain.handle('vscode:readNlsFile', async (event, ...paths: unknown[]) => {
const uri = this.validateNlsPath(paths);
if (!uri) {
throw new Error('Invalid operation (vscode:readNlsFile)');
}
return (await this.fileService.readFile(uri)).value.toString();
});
ipcMain.on('vscode:toggleDevTools', event => event.sender.toggleDevTools());
ipcMain.on('vscode:openDevTools', event => event.sender.openDevTools());
ipcMain.on('vscode:reloadWindow', event => event.sender.reload());
//#endregion
}
private validateNlsPath(pathSegments: unknown[]): URI | undefined {
let path: string | undefined = undefined;
for (const pathSegment of pathSegments) {
if (typeof pathSegment === 'string') {
if (typeof path !== 'string') {
path = pathSegment;
} else {
path = join(path, pathSegment);
}
}
}
if (typeof path !== 'string' || !isAbsolute(path) || !isEqualOrParent(path, this.environmentMainService.cachedLanguagesPath, !isLinux)) {
return undefined;
}
return URI.file(path);
}
private onUnexpectedError(err: Error): void {
if (err) {
// take only the message and stack property
const friendlyError = {
message: `[uncaught exception in main]: ${err.message}`,
stack: err.stack
};
// handle on client side
this.windowsMainService?.sendToFocused('vscode:reportError', JSON.stringify(friendlyError));
}
this.logService.error(`[uncaught exception in main]: ${err}`);
if (err.stack) {
this.logService.error(err.stack);
}
}
async startup(): Promise<void> {
this.logService.debug('Starting VS Code');
this.logService.debug(`from: ${this.environmentMainService.appRoot}`);
this.logService.debug('args:', this.environmentMainService.args);
// Make sure we associate the program with the app user model id
// This will help Windows to associate the running program with
// any shortcut that is pinned to the taskbar and prevent showing
// two icons in the taskbar for the same app.
const win32AppUserModelId = product.win32AppUserModelId;
if (isWindows && win32AppUserModelId) {
app.setAppUserModelId(win32AppUserModelId);
}
// Fix native tabs on macOS 10.13
// macOS enables a compatibility patch for any bundle ID beginning with
// "com.microsoft.", which breaks native tabs for VS Code when using this
// identifier (from the official build).
// Explicitly opt out of the patch here before creating any windows.
// See: https://github.com/microsoft/vscode/issues/35361#issuecomment-399794085
try {
if (isMacintosh && this.configurationService.getValue<boolean>('window.nativeTabs') === true && !systemPreferences.getUserDefault('NSUseImprovedLayoutPass', 'boolean')) {
systemPreferences.setUserDefault('NSUseImprovedLayoutPass', 'boolean', true as any);
}
} catch (error) {
this.logService.error(error);
}
// Setup Protocol Handler
const fileProtocolHandler = this._register(this.mainInstantiationService.createInstance(FileProtocolHandler));
// Main process server (electron IPC based)
const mainProcessElectronServer = new ElectronIPCServer();
// Resolve unique machine ID
this.logService.trace('Resolving machine identifier...');
const machineId = await this.resolveMachineId();
this.logService.trace(`Resolved machine identifier: ${machineId}`);
// Shared process
const { sharedProcess, sharedProcessReady, sharedProcessClient } = this.setupSharedProcess(machineId);
// Services
const appInstantiationService = await this.initServices(machineId, sharedProcess, sharedProcessReady);
// Create driver
if (this.environmentMainService.driverHandle) {
const server = await serveDriver(mainProcessElectronServer, this.environmentMainService.driverHandle, this.environmentMainService, appInstantiationService);
this.logService.info('Driver started at:', this.environmentMainService.driverHandle);
this._register(server);
}
// Setup Auth Handler
this._register(appInstantiationService.createInstance(ProxyAuthHandler));
// Init Channels
appInstantiationService.invokeFunction(accessor => this.initChannels(accessor, mainProcessElectronServer, sharedProcessClient));
// Open Windows
const windows = appInstantiationService.invokeFunction(accessor => this.openFirstWindow(accessor, mainProcessElectronServer, fileProtocolHandler));
// Post Open Windows Tasks
appInstantiationService.invokeFunction(accessor => this.afterWindowOpen(accessor, sharedProcess));
// Tracing: Stop tracing after windows are ready if enabled
if (this.environmentMainService.args.trace) {
appInstantiationService.invokeFunction(accessor => this.stopTracingEventually(accessor, windows));
}
}
private async resolveMachineId(): Promise<string> {
// We cache the machineId for faster lookups on startup
// and resolve it only once initially if not cached or we need to replace the macOS iBridge device
let machineId = this.stateService.getItem<string>(machineIdKey);
if (!machineId || (isMacintosh && machineId === '6c9d2bc8f91b89624add29c0abeae7fb42bf539fa1cdb2e3e57cd668fa9bcead')) {
machineId = await getMachineId();
this.stateService.setItem(machineIdKey, machineId);
}
return machineId;
}
private setupSharedProcess(machineId: string): { sharedProcess: SharedProcess, sharedProcessReady: Promise<MessagePortClient>, sharedProcessClient: Promise<MessagePortClient> } {
const sharedProcess = this.mainInstantiationService.createInstance(SharedProcess, machineId, this.userEnv);
const sharedProcessClient = (async () => {
this.logService.trace('Main->SharedProcess#connect');
const port = await sharedProcess.connect();
this.logService.trace('Main->SharedProcess#connect: connection established');
return new MessagePortClient(port, 'main');
})();
const sharedProcessReady = (async () => {
await sharedProcess.whenReady();
return sharedProcessClient;
})();
// Spawn shared process after the first window has opened and 3s have passed
this.lifecycleMainService.when(LifecycleMainPhase.AfterWindowOpen).then(() => {
this._register(new RunOnceScheduler(async () => {
sharedProcess.spawn(await resolveShellEnv(this.logService, this.environmentMainService.args, process.env));
}, 3000)).schedule();
});
return { sharedProcess, sharedProcessReady, sharedProcessClient };
}
private async initServices(machineId: string, sharedProcess: SharedProcess, sharedProcessReady: Promise<MessagePortClient>): Promise<IInstantiationService> {
const services = new ServiceCollection();
// Update
switch (process.platform) {
case 'win32':
services.set(IUpdateService, new SyncDescriptor(Win32UpdateService));
break;
case 'linux':
if (isLinuxSnap) {
services.set(IUpdateService, new SyncDescriptor(SnapUpdateService, [process.env['SNAP'], process.env['SNAP_REVISION']]));
} else {
services.set(IUpdateService, new SyncDescriptor(LinuxUpdateService));
}
break;
case 'darwin':
services.set(IUpdateService, new SyncDescriptor(DarwinUpdateService));
break;
}
// Windows
services.set(IWindowsMainService, new SyncDescriptor(WindowsMainService, [machineId, this.userEnv]));
// Dialogs
services.set(IDialogMainService, new SyncDescriptor(DialogMainService));
// Launch
services.set(ILaunchMainService, new SyncDescriptor(LaunchMainService));
// Diagnostics
services.set(IDiagnosticsService, ProxyChannel.toService(getDelayedChannel(sharedProcessReady.then(client => client.getChannel('diagnostics')))));
// Issues
services.set(IIssueMainService, new SyncDescriptor(IssueMainService, [machineId, this.userEnv]));
// Encryption
services.set(IEncryptionMainService, new SyncDescriptor(EncryptionMainService, [machineId]));
// Keyboard Layout
services.set(IKeyboardLayoutMainService, new SyncDescriptor(KeyboardLayoutMainService));
// Display
services.set(IDisplayMainService, new SyncDescriptor(DisplayMainService));
// Native Host
services.set(INativeHostMainService, new SyncDescriptor(NativeHostMainService, [sharedProcess]));
// Webview Manager
services.set(IWebviewManagerService, new SyncDescriptor(WebviewMainService));
// Workspaces
services.set(IWorkspacesService, new SyncDescriptor(WorkspacesMainService));
services.set(IWorkspacesManagementMainService, new SyncDescriptor(WorkspacesManagementMainService));
services.set(IWorkspacesHistoryMainService, new SyncDescriptor(WorkspacesHistoryMainService));
// Menubar
services.set(IMenubarMainService, new SyncDescriptor(MenubarMainService));
// Extension URL Trust
services.set(IExtensionUrlTrustService, new SyncDescriptor(ExtensionUrlTrustService));
// Storage
services.set(IStorageMainService, new SyncDescriptor(StorageMainService));
// Backups
const backupMainService = new BackupMainService(this.environmentMainService, this.configurationService, this.logService);
services.set(IBackupMainService, backupMainService);
// URL handling
services.set(IURLService, new SyncDescriptor(NativeURLService));
// Telemetry
if (!this.environmentMainService.isExtensionDevelopment && !this.environmentMainService.args['disable-telemetry'] && !!product.enableTelemetry) {
const channel = getDelayedChannel(sharedProcessReady.then(client => client.getChannel('telemetryAppender')));
const appender = new TelemetryAppenderClient(channel);
const commonProperties = resolveCommonProperties(this.fileService, release(), process.arch, product.commit, product.version, machineId, product.msftInternalDomains, this.environmentMainService.installSourcePath);
const piiPaths = [this.environmentMainService.appRoot, this.environmentMainService.extensionsPath];
const config: ITelemetryServiceConfig = { appender, commonProperties, piiPaths, sendErrorTelemetry: true };
services.set(ITelemetryService, new SyncDescriptor(TelemetryService, [config]));
} else {
services.set(ITelemetryService, NullTelemetryService);
}
// Init services that require it
await backupMainService.initialize();
return this.mainInstantiationService.createChild(services);
}
private initChannels(accessor: ServicesAccessor, mainProcessElectronServer: ElectronIPCServer, sharedProcessClient: Promise<MessagePortClient>): void {
// Launch: this one is explicitly registered to the node.js
// server because when a second instance starts up, that is
// the only possible connection between the first and the
// second instance. Electron IPC does not work across apps.
const launchChannel = ProxyChannel.fromService(accessor.get(ILaunchMainService), { disableMarshalling: true });
this.mainProcessNodeIpcServer.registerChannel('launch', launchChannel);
// Update
const updateChannel = new UpdateChannel(accessor.get(IUpdateService));
mainProcessElectronServer.registerChannel('update', updateChannel);
// Issues
const issueChannel = ProxyChannel.fromService(accessor.get(IIssueMainService));
mainProcessElectronServer.registerChannel('issue', issueChannel);
// Encryption
const encryptionChannel = ProxyChannel.fromService(accessor.get(IEncryptionMainService));
mainProcessElectronServer.registerChannel('encryption', encryptionChannel);
// Keyboard Layout
const keyboardLayoutChannel = ProxyChannel.fromService(accessor.get(IKeyboardLayoutMainService));
mainProcessElectronServer.registerChannel('keyboardLayout', keyboardLayoutChannel);
// Display
const displayChannel = ProxyChannel.fromService(accessor.get(IDisplayMainService));
mainProcessElectronServer.registerChannel('display', displayChannel);
// Native host (main & shared process)
this.nativeHostMainService = accessor.get(INativeHostMainService);
const nativeHostChannel = ProxyChannel.fromService(this.nativeHostMainService);
mainProcessElectronServer.registerChannel('nativeHost', nativeHostChannel);
sharedProcessClient.then(client => client.registerChannel('nativeHost', nativeHostChannel));
// Workspaces
const workspacesChannel = ProxyChannel.fromService(accessor.get(IWorkspacesService));
mainProcessElectronServer.registerChannel('workspaces', workspacesChannel);
// Menubar
const menubarChannel = ProxyChannel.fromService(accessor.get(IMenubarMainService));
mainProcessElectronServer.registerChannel('menubar', menubarChannel);
// URL handling
const urlChannel = ProxyChannel.fromService(accessor.get(IURLService));
mainProcessElectronServer.registerChannel('url', urlChannel);
// Extension URL Trust
const extensionUrlTrustChannel = ProxyChannel.fromService(accessor.get(IExtensionUrlTrustService));
mainProcessElectronServer.registerChannel('extensionUrlTrust', extensionUrlTrustChannel);
// Webview Manager
const webviewChannel = ProxyChannel.fromService(accessor.get(IWebviewManagerService));
mainProcessElectronServer.registerChannel('webview', webviewChannel);
// Storage (main & shared process)
const storageChannel = this._register(new StorageDatabaseChannel(this.logService, accessor.get(IStorageMainService)));
mainProcessElectronServer.registerChannel('storage', storageChannel);
sharedProcessClient.then(client => client.registerChannel('storage', storageChannel));
// Log Level (main & shared process)
const logLevelChannel = new LogLevelChannel(accessor.get(ILogService));
mainProcessElectronServer.registerChannel('logLevel', logLevelChannel);
sharedProcessClient.then(client => client.registerChannel('logLevel', logLevelChannel));
// Logger
const loggerChannel = new LoggerChannel(accessor.get(ILoggerService),);
mainProcessElectronServer.registerChannel('logger', loggerChannel);
// Extension Host Debug Broadcasting
const electronExtensionHostDebugBroadcastChannel = new ElectronExtensionHostDebugBroadcastChannel(accessor.get(IWindowsMainService));
mainProcessElectronServer.registerChannel('extensionhostdebugservice', electronExtensionHostDebugBroadcastChannel);
}
private openFirstWindow(accessor: ServicesAccessor, mainProcessElectronServer: ElectronIPCServer, fileProtocolHandler: FileProtocolHandler): ICodeWindow[] {
const windowsMainService = this.windowsMainService = accessor.get(IWindowsMainService);
const urlService = accessor.get(IURLService);
const nativeHostMainService = accessor.get(INativeHostMainService);
// Signal phase: ready (services set)
this.lifecycleMainService.phase = LifecycleMainPhase.Ready;
// Forward windows main service to protocol handler
fileProtocolHandler.injectWindowsMainService(this.windowsMainService);
// Check for initial URLs to handle from protocol link invocations
const pendingWindowOpenablesFromProtocolLinks: IWindowOpenable[] = [];
const pendingProtocolLinksToHandle = [
// Windows/Linux: protocol handler invokes CLI with --open-url
...this.environmentMainService.args['open-url'] ? this.environmentMainService.args._urls || [] : [],
// macOS: open-url events
...((<any>global).getOpenUrls() || []) as string[]
].map(url => {
try {
return { uri: URI.parse(url), url };
} catch {
return null;
}
}).filter((obj): obj is { uri: URI, url: string } => {
if (!obj) {
return false;
}
// If URI should be blocked, filter it out
if (this.shouldBlockURI(obj.uri)) {
return false;
}
// Filter out any protocol link that wants to open as window so that
// we open the right set of windows on startup and not restore the
// previous workspace too.
const windowOpenable = this.getWindowOpenableFromProtocolLink(obj.uri);
if (windowOpenable) {
pendingWindowOpenablesFromProtocolLinks.push(windowOpenable);
return false;
}
return true;
});
// Create a URL handler to open file URIs in the active window
// or open new windows. The URL handler will be invoked from
// protocol invocations outside of VSCode.
const app = this;
const environmentService = this.environmentMainService;
urlService.registerHandler({
async handleURL(uri: URI, options?: IOpenURLOptions): Promise<boolean> {
// If URI should be blocked, behave as if it's handled
if (app.shouldBlockURI(uri)) {
return true;
}
// Check for URIs to open in window
const windowOpenableFromProtocolLink = app.getWindowOpenableFromProtocolLink(uri);
if (windowOpenableFromProtocolLink) {
const [window] = windowsMainService.open({
context: OpenContext.API,
cli: { ...environmentService.args },
urisToOpen: [windowOpenableFromProtocolLink],
gotoLineMode: true
});
window.focus(); // this should help ensuring that the right window gets focus when multiple are opened
return true;
}
// If we have not yet handled the URI and we have no window opened (macOS only)
// we first open a window and then try to open that URI within that window
if (isMacintosh && windowsMainService.getWindowCount() === 0) {
const [window] = windowsMainService.open({
context: OpenContext.API,
cli: { ...environmentService.args },
forceEmpty: true,
gotoLineMode: true
});
await window.ready();
return urlService.open(uri, options);
}
return false;
}
});
// Create a URL handler which forwards to the last active window
const activeWindowManager = this._register(new ActiveWindowManager({
onDidOpenWindow: nativeHostMainService.onDidOpenWindow,
onDidFocusWindow: nativeHostMainService.onDidFocusWindow,
getActiveWindowId: () => nativeHostMainService.getActiveWindowId(-1)
}));
const activeWindowRouter = new StaticRouter(ctx => activeWindowManager.getActiveClientId().then(id => ctx === id));
const urlHandlerRouter = new URLHandlerRouter(activeWindowRouter);
const urlHandlerChannel = mainProcessElectronServer.getChannel('urlHandler', urlHandlerRouter);
urlService.registerHandler(new URLHandlerChannelClient(urlHandlerChannel));
// Watch Electron URLs and forward them to the UrlService
this._register(new ElectronURLListener(pendingProtocolLinksToHandle, urlService, windowsMainService, this.environmentMainService));
// Open our first window
const args = this.environmentMainService.args;
const macOpenFiles: string[] = (<any>global).macOpenFiles;
const context = isLaunchedFromCli(process.env) ? OpenContext.CLI : OpenContext.DESKTOP;
const hasCliArgs = args._.length;
const hasFolderURIs = !!args['folder-uri'];
const hasFileURIs = !!args['file-uri'];
const noRecentEntry = args['skip-add-to-recently-opened'] === true;
const waitMarkerFileURI = args.wait && args.waitMarkerFilePath ? URI.file(args.waitMarkerFilePath) : undefined;
// check for a pending window to open from URI
// e.g. when running code with --open-uri from
// a protocol handler
if (pendingWindowOpenablesFromProtocolLinks.length > 0) {
return windowsMainService.open({
context,
cli: args,
urisToOpen: pendingWindowOpenablesFromProtocolLinks,
gotoLineMode: true,
initialStartup: true
});
}
// new window if "-n"
if (args['new-window'] && !hasCliArgs && !hasFolderURIs && !hasFileURIs) {
return windowsMainService.open({
context,
cli: args,
forceNewWindow: true,
forceEmpty: true,
noRecentEntry,
waitMarkerFileURI,
initialStartup: true
});
}
// mac: open-file event received on startup
if (macOpenFiles.length && !hasCliArgs && !hasFolderURIs && !hasFileURIs) {
return windowsMainService.open({
context: OpenContext.DOCK,
cli: args,
urisToOpen: macOpenFiles.map(file => this.getWindowOpenableFromPathSync(file)),
noRecentEntry,
waitMarkerFileURI,
initialStartup: true
});
}
// default: read paths from cli
return windowsMainService.open({
context,
cli: args,
forceNewWindow: args['new-window'] || (!hasCliArgs && args['unity-launch']),
diffMode: args.diff,
noRecentEntry,
waitMarkerFileURI,
gotoLineMode: args.goto,
initialStartup: true
});
}
private shouldBlockURI(uri: URI): boolean {
if (uri.authority === Schemas.file && isWindows) {
const res = dialog.showMessageBoxSync({
title: product.nameLong,
type: 'question',
buttons: [
mnemonicButtonLabel(localize({ key: 'open', comment: ['&& denotes a mnemonic'] }, "&&Yes")),
mnemonicButtonLabel(localize({ key: 'cancel', comment: ['&& denotes a mnemonic'] }, "&&No")),
],
cancelId: 1,
message: localize('confirmOpenMessage', "An external application wants to open '{0}' in {1}. Do you want to open this file or folder?", getPathLabel(uri.fsPath, this.environmentMainService), product.nameShort),
detail: localize('confirmOpenDetail', "If you did not initiate this request, it may represent an attempted attack on your system. Unless you took an explicit action to initiate this request, you should press 'No'"),
noLink: true
});
if (res === 1) {
return true;
}
}
return false;
}
private getWindowOpenableFromProtocolLink(uri: URI): IWindowOpenable | undefined {
if (!uri.path) {
return undefined;
}
// File path
if (uri.authority === Schemas.file) {
// we configure as fileUri, but later validation will
// make sure to open as folder or workspace if possible
return { fileUri: URI.file(uri.fsPath) };
}
// Remote path
else if (uri.authority === Schemas.vscodeRemote) {
// Example conversion:
// From: vscode://vscode-remote/wsl+ubuntu/mnt/c/GitDevelopment/monaco
// To: vscode-remote://wsl+ubuntu/mnt/c/GitDevelopment/monaco
const secondSlash = uri.path.indexOf(posix.sep, 1 /* skip over the leading slash */);
if (secondSlash !== -1) {
const authority = uri.path.substring(1, secondSlash);
const path = uri.path.substring(secondSlash);
const remoteUri = URI.from({ scheme: Schemas.vscodeRemote, authority, path, query: uri.query, fragment: uri.fragment });
if (hasWorkspaceFileExtension(path)) {
return { workspaceUri: remoteUri };
} else {
return { folderUri: remoteUri };
}
}
}
return undefined;
}
private getWindowOpenableFromPathSync(path: string): IWindowOpenable {
try {
const fileStat = statSync(path);
if (fileStat.isDirectory()) {
return { folderUri: URI.file(path) };
}
if (hasWorkspaceFileExtension(path)) {
return { workspaceUri: URI.file(path) };
}
} catch (error) {
// ignore errors
}
return { fileUri: URI.file(path) };
}
private async afterWindowOpen(accessor: ServicesAccessor, sharedProcess: SharedProcess): Promise<void> {
// Signal phase: after window open
this.lifecycleMainService.phase = LifecycleMainPhase.AfterWindowOpen;
// Observe shared process for errors
const telemetryService = accessor.get(ITelemetryService);
this._register(sharedProcess.onDidError(e => {
// Logging
onUnexpectedError(new Error(e.message));
// Telemetry
type SharedProcessErrorClassification = {
type: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true };
};
type SharedProcessErrorEvent = {
type: WindowError;
};
telemetryService.publicLog2<SharedProcessErrorEvent, SharedProcessErrorClassification>('sharedprocesserror', { type: e.type });
}));
// Windows: install mutex
const win32MutexName = product.win32MutexName;
if (isWindows && win32MutexName) {
try {
const WindowsMutex = (require.__$__nodeRequire('windows-mutex') as typeof import('windows-mutex')).Mutex;
const mutex = new WindowsMutex(win32MutexName);
once(this.lifecycleMainService.onWillShutdown)(() => mutex.release());
} catch (error) {
this.logService.error(error);
}
}
// Remote Authorities
protocol.registerHttpProtocol(Schemas.vscodeRemoteResource, (request, callback) => {
callback({
url: request.url.replace(/^vscode-remote-resource:/, 'http:'),
method: request.method
});
});
// Initialize update service
const updateService = accessor.get(IUpdateService);
if (updateService instanceof Win32UpdateService || updateService instanceof LinuxUpdateService || updateService instanceof DarwinUpdateService) {
updateService.initialize();
}
// Start to fetch shell environment (if needed) after window has opened
resolveShellEnv(this.logService, this.environmentMainService.args, process.env);
// If enable-crash-reporter argv is undefined then this is a fresh start,
// based on telemetry.enableCrashreporter settings, generate a UUID which
// will be used as crash reporter id and also update the json file.
try {
const argvContent = await this.fileService.readFile(this.environmentMainService.argvResource);
const argvString = argvContent.value.toString();
const argvJSON = JSON.parse(stripComments(argvString));
if (argvJSON['enable-crash-reporter'] === undefined) {
const enableCrashReporter = this.configurationService.getValue<boolean>('telemetry.enableCrashReporter') ?? true;
const additionalArgvContent = [
'',
' // Allows to disable crash reporting.',
' // Should restart the app if the value is changed.',
` "enable-crash-reporter": ${enableCrashReporter},`,
'',
' // Unique id used for correlating crash reports sent from this instance.',
' // Do not edit this value.',
` "crash-reporter-id": "${generateUuid()}"`,
'}'
];
const newArgvString = argvString.substring(0, argvString.length - 2).concat(',\n', additionalArgvContent.join('\n'));
await this.fileService.writeFile(this.environmentMainService.argvResource, VSBuffer.fromString(newArgvString));
}
} catch (error) {
this.logService.error(error);
}
}
private stopTracingEventually(accessor: ServicesAccessor, windows: ICodeWindow[]): void {
this.logService.info(`Tracing: waiting for windows to get ready...`);
const dialogMainService = accessor.get(IDialogMainService);
let recordingStopped = false;
const stopRecording = async (timeout: boolean) => {
if (recordingStopped) {
return;
}
recordingStopped = true; // only once
const path = await contentTracing.stopRecording(joinPath(this.environmentMainService.userHome, `${product.applicationName}-${Math.random().toString(16).slice(-4)}.trace.txt`).fsPath);
if (!timeout) {
dialogMainService.showMessageBox({
type: 'info',
message: localize('trace.message', "Successfully created trace."),
detail: localize('trace.detail', "Please create an issue and manually attach the following file:\n{0}", path),
buttons: [localize('trace.ok', "OK")]
}, withNullAsUndefined(BrowserWindow.getFocusedWindow()));
} else {
this.logService.info(`Tracing: data recorded (after 30s timeout) to ${path}`);
}
};
// Wait up to 30s before creating the trace anyways
const timeoutHandle = setTimeout(() => stopRecording(true), 30000);
// Wait for all windows to get ready and stop tracing then
Promise.all(windows.map(window => window.ready())).then(() => {
clearTimeout(timeoutHandle);
stopRecording(false);
});
}
}
| src/vs/code/electron-main/app.ts | 1 | https://github.com/microsoft/vscode/commit/608e8791ff194e81a10ac0d963471922ddc9b6e0 | [
0.8444176316261292,
0.008422626182436943,
0.00016256983508355916,
0.00017022342944983393,
0.08199770748615265
] |
{
"id": 1,
"code_window": [
"\t\t\t\treturn callback(false);\n",
"\t\t\t});\n",
"\n",
"\t\t\tsession.defaultSession.setPermissionCheckHandler((webContents, permission /* 'media' */) => {\n",
"\t\t\t\treturn false;\n",
"\t\t\t});\n",
"\t\t});\n",
"\n",
"\t\t//#endregion\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\tsession.defaultSession.setPermissionCheckHandler((_webContents, permission /* 'media' */, _origin, details) => {\n",
"\t\t\t\tif (details.requestingUrl === webviewFrameUrl) {\n",
"\t\t\t\t\treturn permission === 'clipboard-read';\n",
"\t\t\t\t}\n"
],
"file_path": "src/vs/code/electron-main/app.ts",
"type": "replace",
"edit_start_line_idx": 231
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
export const EMPTY_ELEMENTS: string[] = ['area', 'base', 'br', 'col', 'embed', 'hr', 'img', 'input', 'keygen', 'link', 'menuitem', 'meta', 'param', 'source', 'track', 'wbr'];
| extensions/html-language-features/client/src/htmlEmptyTagsShared.ts | 0 | https://github.com/microsoft/vscode/commit/608e8791ff194e81a10ac0d963471922ddc9b6e0 | [
0.00016820050950627774,
0.00016820050950627774,
0.00016820050950627774,
0.00016820050950627774,
0
] |
{
"id": 1,
"code_window": [
"\t\t\t\treturn callback(false);\n",
"\t\t\t});\n",
"\n",
"\t\t\tsession.defaultSession.setPermissionCheckHandler((webContents, permission /* 'media' */) => {\n",
"\t\t\t\treturn false;\n",
"\t\t\t});\n",
"\t\t});\n",
"\n",
"\t\t//#endregion\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\tsession.defaultSession.setPermissionCheckHandler((_webContents, permission /* 'media' */, _origin, details) => {\n",
"\t\t\t\tif (details.requestingUrl === webviewFrameUrl) {\n",
"\t\t\t\t\treturn permission === 'clipboard-read';\n",
"\t\t\t\t}\n"
],
"file_path": "src/vs/code/electron-main/app.ts",
"type": "replace",
"edit_start_line_idx": 231
} | <svg width="14px" height="14px" viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg">
<rect fill="#969696" x="0" y="0" width="100" height="100" rx="35" ry="35"/>
<text x="50" y="75" font-size="75" text-anchor="middle" style="font-family: Menlo, Monaco, Consolas, "Droid Sans Mono", "Inconsolata", "Courier New", monospace, "Droid Sans Fallback";" fill="white">
I
</text>
</svg> | extensions/git/resources/icons/light/status-ignored.svg | 0 | https://github.com/microsoft/vscode/commit/608e8791ff194e81a10ac0d963471922ddc9b6e0 | [
0.00017140719864983112,
0.00017140719864983112,
0.00017140719864983112,
0.00017140719864983112,
0
] |
{
"id": 1,
"code_window": [
"\t\t\t\treturn callback(false);\n",
"\t\t\t});\n",
"\n",
"\t\t\tsession.defaultSession.setPermissionCheckHandler((webContents, permission /* 'media' */) => {\n",
"\t\t\t\treturn false;\n",
"\t\t\t});\n",
"\t\t});\n",
"\n",
"\t\t//#endregion\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\tsession.defaultSession.setPermissionCheckHandler((_webContents, permission /* 'media' */, _origin, details) => {\n",
"\t\t\t\tif (details.requestingUrl === webviewFrameUrl) {\n",
"\t\t\t\t\treturn permission === 'clipboard-read';\n",
"\t\t\t\t}\n"
],
"file_path": "src/vs/code/electron-main/app.ts",
"type": "replace",
"edit_start_line_idx": 231
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { Disposable } from 'vs/base/common/lifecycle';
import { IAccessibilityService, AccessibilitySupport, CONTEXT_ACCESSIBILITY_MODE_ENABLED } from 'vs/platform/accessibility/common/accessibility';
import { Event, Emitter } from 'vs/base/common/event';
import { IContextKey, IContextKeyService } from 'vs/platform/contextkey/common/contextkey';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
export class AccessibilityService extends Disposable implements IAccessibilityService {
declare readonly _serviceBrand: undefined;
private _accessibilityModeEnabledContext: IContextKey<boolean>;
protected _accessibilitySupport = AccessibilitySupport.Unknown;
protected readonly _onDidChangeScreenReaderOptimized = new Emitter<void>();
constructor(
@IContextKeyService private readonly _contextKeyService: IContextKeyService,
@IConfigurationService protected readonly _configurationService: IConfigurationService,
) {
super();
this._accessibilityModeEnabledContext = CONTEXT_ACCESSIBILITY_MODE_ENABLED.bindTo(this._contextKeyService);
const updateContextKey = () => this._accessibilityModeEnabledContext.set(this.isScreenReaderOptimized());
this._register(this._configurationService.onDidChangeConfiguration(e => {
if (e.affectsConfiguration('editor.accessibilitySupport')) {
updateContextKey();
this._onDidChangeScreenReaderOptimized.fire();
}
}));
updateContextKey();
this.onDidChangeScreenReaderOptimized(() => updateContextKey());
}
get onDidChangeScreenReaderOptimized(): Event<void> {
return this._onDidChangeScreenReaderOptimized.event;
}
isScreenReaderOptimized(): boolean {
const config = this._configurationService.getValue('editor.accessibilitySupport');
return config === 'on' || (config === 'auto' && this._accessibilitySupport === AccessibilitySupport.Enabled);
}
getAccessibilitySupport(): AccessibilitySupport {
return this._accessibilitySupport;
}
alwaysUnderlineAccessKeys(): Promise<boolean> {
return Promise.resolve(false);
}
setAccessibilitySupport(accessibilitySupport: AccessibilitySupport): void {
if (this._accessibilitySupport === accessibilitySupport) {
return;
}
this._accessibilitySupport = accessibilitySupport;
this._onDidChangeScreenReaderOptimized.fire();
}
}
| src/vs/platform/accessibility/common/accessibilityService.ts | 0 | https://github.com/microsoft/vscode/commit/608e8791ff194e81a10ac0d963471922ddc9b6e0 | [
0.00027643158682622015,
0.0001857732277130708,
0.000166194949997589,
0.00017029778973665088,
0.00003712682882905938
] |
{
"id": 2,
"code_window": [
"\t\tthis.portMappingProvider = this._register(new WebviewPortMappingProvider(tunnelService));\n",
"\n",
"\t\tconst sess = session.fromPartition(webviewPartitionId);\n",
"\t\tsess.setPermissionRequestHandler((webContents, permission /* 'media' | 'geolocation' | 'notifications' | 'midiSysex' | 'pointerLock' | 'fullscreen' | 'openExternal' */, callback) => {\n",
"\t\t\treturn callback(false);\n",
"\t\t});\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tsess.setPermissionRequestHandler((_webContents, permission, callback) => {\n",
"\t\t\tif (permission === 'clipboard-read') {\n",
"\t\t\t\treturn callback(true);\n",
"\t\t\t}\n",
"\n"
],
"file_path": "src/vs/platform/webview/electron-main/webviewMainService.ts",
"type": "replace",
"edit_start_line_idx": 37
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
// @ts-check
/**
* @typedef {{
* postMessage: (channel: string, data?: any) => void,
* onMessage: (channel: string, handler: any) => void,
* focusIframeOnCreate?: boolean,
* ready?: Promise<void>,
* onIframeLoaded?: (iframe: HTMLIFrameElement) => void,
* fakeLoad?: boolean,
* rewriteCSP: (existingCSP: string, endpoint?: string) => string,
* onElectron?: boolean
* }} WebviewHost
*/
(function () {
'use strict';
const isSafari = navigator.vendor && navigator.vendor.indexOf('Apple') > -1 &&
navigator.userAgent &&
navigator.userAgent.indexOf('CriOS') === -1 &&
navigator.userAgent.indexOf('FxiOS') === -1;
/**
* Use polling to track focus of main webview and iframes within the webview
*
* @param {Object} handlers
* @param {() => void} handlers.onFocus
* @param {() => void} handlers.onBlur
*/
const trackFocus = ({ onFocus, onBlur }) => {
const interval = 50;
let isFocused = document.hasFocus();
setInterval(() => {
const isCurrentlyFocused = document.hasFocus();
if (isCurrentlyFocused === isFocused) {
return;
}
isFocused = isCurrentlyFocused;
if (isCurrentlyFocused) {
onFocus();
} else {
onBlur();
}
}, interval);
};
const getActiveFrame = () => {
return /** @type {HTMLIFrameElement} */ (document.getElementById('active-frame'));
};
const getPendingFrame = () => {
return /** @type {HTMLIFrameElement} */ (document.getElementById('pending-frame'));
};
const defaultCssRules = `
html {
scrollbar-color: var(--vscode-scrollbarSlider-background) var(--vscode-editor-background);
}
body {
background-color: transparent;
color: var(--vscode-editor-foreground);
font-family: var(--vscode-font-family);
font-weight: var(--vscode-font-weight);
font-size: var(--vscode-font-size);
margin: 0;
padding: 0 20px;
}
img {
max-width: 100%;
max-height: 100%;
}
a {
color: var(--vscode-textLink-foreground);
}
a:hover {
color: var(--vscode-textLink-activeForeground);
}
a:focus,
input:focus,
select:focus,
textarea:focus {
outline: 1px solid -webkit-focus-ring-color;
outline-offset: -1px;
}
code {
color: var(--vscode-textPreformat-foreground);
}
blockquote {
background: var(--vscode-textBlockQuote-background);
border-color: var(--vscode-textBlockQuote-border);
}
kbd {
color: var(--vscode-editor-foreground);
border-radius: 3px;
vertical-align: middle;
padding: 1px 3px;
background-color: hsla(0,0%,50%,.17);
border: 1px solid rgba(71,71,71,.4);
border-bottom-color: rgba(88,88,88,.4);
box-shadow: inset 0 -1px 0 rgba(88,88,88,.4);
}
.vscode-light kbd {
background-color: hsla(0,0%,87%,.5);
border: 1px solid hsla(0,0%,80%,.7);
border-bottom-color: hsla(0,0%,73%,.7);
box-shadow: inset 0 -1px 0 hsla(0,0%,73%,.7);
}
::-webkit-scrollbar {
width: 10px;
height: 10px;
}
::-webkit-scrollbar-corner {
background-color: var(--vscode-editor-background);
}
::-webkit-scrollbar-thumb {
background-color: var(--vscode-scrollbarSlider-background);
}
::-webkit-scrollbar-thumb:hover {
background-color: var(--vscode-scrollbarSlider-hoverBackground);
}
::-webkit-scrollbar-thumb:active {
background-color: var(--vscode-scrollbarSlider-activeBackground);
}`;
/**
* @param {boolean} allowMultipleAPIAcquire
* @param {*} [state]
* @return {string}
*/
function getVsCodeApiScript(allowMultipleAPIAcquire, state) {
const encodedState = state ? encodeURIComponent(state) : undefined;
return `
globalThis.acquireVsCodeApi = (function() {
const originalPostMessage = window.parent.postMessage.bind(window.parent);
const targetOrigin = '*';
let acquired = false;
let state = ${state ? `JSON.parse(decodeURIComponent("${encodedState}"))` : undefined};
return () => {
if (acquired && !${allowMultipleAPIAcquire}) {
throw new Error('An instance of the VS Code API has already been acquired');
}
acquired = true;
return Object.freeze({
postMessage: function(msg) {
return originalPostMessage({ command: 'onmessage', data: msg }, targetOrigin);
},
setState: function(newState) {
state = newState;
originalPostMessage({ command: 'do-update-state', data: JSON.stringify(newState) }, targetOrigin);
return newState;
},
getState: function() {
return state;
}
});
};
})();
delete window.parent;
delete window.top;
delete window.frameElement;
`;
}
/**
* @param {WebviewHost} host
*/
function createWebviewManager(host) {
// state
let firstLoad = true;
let loadTimeout;
let pendingMessages = [];
const initData = {
initialScrollProgress: undefined,
};
/**
* @param {HTMLDocument?} document
* @param {HTMLElement?} body
*/
const applyStyles = (document, body) => {
if (!document) {
return;
}
if (body) {
body.classList.remove('vscode-light', 'vscode-dark', 'vscode-high-contrast');
body.classList.add(initData.activeTheme);
body.dataset.vscodeThemeKind = initData.activeTheme;
body.dataset.vscodeThemeName = initData.themeName || '';
}
if (initData.styles) {
const documentStyle = document.documentElement.style;
// Remove stale properties
for (let i = documentStyle.length - 1; i >= 0; i--) {
const property = documentStyle[i];
// Don't remove properties that the webview might have added separately
if (property && property.startsWith('--vscode-')) {
documentStyle.removeProperty(property);
}
}
// Re-add new properties
for (const variable of Object.keys(initData.styles)) {
documentStyle.setProperty(`--${variable}`, initData.styles[variable]);
}
}
};
/**
* @param {MouseEvent} event
*/
const handleInnerClick = (event) => {
if (!event || !event.view || !event.view.document) {
return;
}
let baseElement = event.view.document.getElementsByTagName('base')[0];
/** @type {any} */
let node = event.target;
while (node) {
if (node.tagName && node.tagName.toLowerCase() === 'a' && node.href) {
if (node.getAttribute('href') === '#') {
event.view.scrollTo(0, 0);
} else if (node.hash && (node.getAttribute('href') === node.hash || (baseElement && node.href.indexOf(baseElement.href) >= 0))) {
let scrollTarget = event.view.document.getElementById(node.hash.substr(1, node.hash.length - 1));
if (scrollTarget) {
scrollTarget.scrollIntoView();
}
} else {
host.postMessage('did-click-link', node.href.baseVal || node.href);
}
event.preventDefault();
break;
}
node = node.parentNode;
}
};
/**
* @param {MouseEvent} event
*/
const handleAuxClick =
(event) => {
// Prevent middle clicks opening a broken link in the browser
if (!event.view || !event.view.document) {
return;
}
if (event.button === 1) {
let node = /** @type {any} */ (event.target);
while (node) {
if (node.tagName && node.tagName.toLowerCase() === 'a' && node.href) {
event.preventDefault();
break;
}
node = node.parentNode;
}
}
};
/**
* @param {KeyboardEvent} e
*/
const handleInnerKeydown = (e) => {
// If the keypress would trigger a browser event, such as copy or paste,
// make sure we block the browser from dispatching it. Instead VS Code
// handles these events and will dispatch a copy/paste back to the webview
// if needed
if (isUndoRedo(e)) {
e.preventDefault();
} else if (isCopyPasteOrCut(e)) {
if (host.onElectron) {
e.preventDefault();
} else {
return; // let the browser handle this
}
}
host.postMessage('did-keydown', {
key: e.key,
keyCode: e.keyCode,
code: e.code,
shiftKey: e.shiftKey,
altKey: e.altKey,
ctrlKey: e.ctrlKey,
metaKey: e.metaKey,
repeat: e.repeat
});
};
/**
* @param {KeyboardEvent} e
* @return {boolean}
*/
function isCopyPasteOrCut(e) {
const hasMeta = e.ctrlKey || e.metaKey;
const shiftInsert = e.shiftKey && e.key.toLowerCase() === 'insert';
return (hasMeta && ['c', 'v', 'x'].includes(e.key.toLowerCase())) || shiftInsert;
}
/**
* @param {KeyboardEvent} e
* @return {boolean}
*/
function isUndoRedo(e) {
const hasMeta = e.ctrlKey || e.metaKey;
return hasMeta && ['z', 'y'].includes(e.key.toLowerCase());
}
let isHandlingScroll = false;
const handleWheel = (event) => {
if (isHandlingScroll) {
return;
}
host.postMessage('did-scroll-wheel', {
deltaMode: event.deltaMode,
deltaX: event.deltaX,
deltaY: event.deltaY,
deltaZ: event.deltaZ,
detail: event.detail,
type: event.type
});
};
const handleInnerScroll = (event) => {
if (!event.target || !event.target.body) {
return;
}
if (isHandlingScroll) {
return;
}
const progress = event.currentTarget.scrollY / event.target.body.clientHeight;
if (isNaN(progress)) {
return;
}
isHandlingScroll = true;
window.requestAnimationFrame(() => {
try {
host.postMessage('did-scroll', progress);
} catch (e) {
// noop
}
isHandlingScroll = false;
});
};
/**
* @return {string}
*/
function toContentHtml(data) {
const options = data.options;
const text = data.contents;
const newDocument = new DOMParser().parseFromString(text, 'text/html');
newDocument.querySelectorAll('a').forEach(a => {
if (!a.title) {
a.title = a.getAttribute('href');
}
});
// apply default script
if (options.allowScripts) {
const defaultScript = newDocument.createElement('script');
defaultScript.id = '_vscodeApiScript';
defaultScript.textContent = getVsCodeApiScript(options.allowMultipleAPIAcquire, data.state);
newDocument.head.prepend(defaultScript);
}
// apply default styles
const defaultStyles = newDocument.createElement('style');
defaultStyles.id = '_defaultStyles';
defaultStyles.textContent = defaultCssRules;
newDocument.head.prepend(defaultStyles);
applyStyles(newDocument, newDocument.body);
// Check for CSP
const csp = newDocument.querySelector('meta[http-equiv="Content-Security-Policy"]');
if (!csp) {
host.postMessage('no-csp-found');
} else {
try {
csp.setAttribute('content', host.rewriteCSP(csp.getAttribute('content'), data.endpoint));
} catch (e) {
console.error(`Could not rewrite csp: ${e}`);
}
}
// set DOCTYPE for newDocument explicitly as DOMParser.parseFromString strips it off
// and DOCTYPE is needed in the iframe to ensure that the user agent stylesheet is correctly overridden
return '<!DOCTYPE html>\n' + newDocument.documentElement.outerHTML;
}
document.addEventListener('DOMContentLoaded', () => {
const idMatch = document.location.search.match(/\bid=([\w-]+)/);
const ID = idMatch ? idMatch[1] : undefined;
if (!document.body) {
return;
}
host.onMessage('styles', (_event, data) => {
initData.styles = data.styles;
initData.activeTheme = data.activeTheme;
initData.themeName = data.themeName;
const target = getActiveFrame();
if (!target) {
return;
}
if (target.contentDocument) {
applyStyles(target.contentDocument, target.contentDocument.body);
}
});
// propagate focus
host.onMessage('focus', () => {
const activeFrame = getActiveFrame();
if (!activeFrame || !activeFrame.contentWindow) {
// Focus the top level webview instead
window.focus();
return;
}
if (document.activeElement === activeFrame) {
// We are already focused on the iframe (or one of its children) so no need
// to refocus.
return;
}
activeFrame.contentWindow.focus();
});
// update iframe-contents
let updateId = 0;
host.onMessage('content', async (_event, data) => {
const currentUpdateId = ++updateId;
await host.ready;
if (currentUpdateId !== updateId) {
return;
}
const options = data.options;
const newDocument = toContentHtml(data);
const frame = getActiveFrame();
const wasFirstLoad = firstLoad;
// keep current scrollY around and use later
let setInitialScrollPosition;
if (firstLoad) {
firstLoad = false;
setInitialScrollPosition = (body, window) => {
if (!isNaN(initData.initialScrollProgress)) {
if (window.scrollY === 0) {
window.scroll(0, body.clientHeight * initData.initialScrollProgress);
}
}
};
} else {
const scrollY = frame && frame.contentDocument && frame.contentDocument.body ? frame.contentWindow.scrollY : 0;
setInitialScrollPosition = (body, window) => {
if (window.scrollY === 0) {
window.scroll(0, scrollY);
}
};
}
// Clean up old pending frames and set current one as new one
const previousPendingFrame = getPendingFrame();
if (previousPendingFrame) {
previousPendingFrame.setAttribute('id', '');
document.body.removeChild(previousPendingFrame);
}
if (!wasFirstLoad) {
pendingMessages = [];
}
const newFrame = document.createElement('iframe');
newFrame.setAttribute('id', 'pending-frame');
newFrame.setAttribute('frameborder', '0');
newFrame.setAttribute('sandbox', options.allowScripts ? 'allow-scripts allow-forms allow-same-origin allow-pointer-lock allow-downloads' : 'allow-same-origin allow-pointer-lock');
if (host.fakeLoad) {
// We should just be able to use srcdoc, but I wasn't
// seeing the service worker applying properly.
// Fake load an empty on the correct origin and then write real html
// into it to get around this.
newFrame.src = `./fake.html?id=${ID}`;
}
newFrame.style.cssText = 'display: block; margin: 0; overflow: hidden; position: absolute; width: 100%; height: 100%; visibility: hidden';
document.body.appendChild(newFrame);
if (!host.fakeLoad) {
// write new content onto iframe
newFrame.contentDocument.open();
}
/**
* @param {Document} contentDocument
*/
function onFrameLoaded(contentDocument) {
// Workaround for https://bugs.chromium.org/p/chromium/issues/detail?id=978325
setTimeout(() => {
if (host.fakeLoad) {
contentDocument.open();
contentDocument.write(newDocument);
contentDocument.close();
hookupOnLoadHandlers(newFrame);
}
if (contentDocument) {
applyStyles(contentDocument, contentDocument.body);
}
}, 0);
}
if (host.fakeLoad && !options.allowScripts && isSafari) {
// On Safari for iframes with scripts disabled, the `DOMContentLoaded` never seems to be fired.
// Use polling instead.
const interval = setInterval(() => {
// If the frame is no longer mounted, loading has stopped
if (!newFrame.parentElement) {
clearInterval(interval);
return;
}
if (newFrame.contentDocument.readyState !== 'loading') {
clearInterval(interval);
onFrameLoaded(newFrame.contentDocument);
}
}, 10);
} else {
newFrame.contentWindow.addEventListener('DOMContentLoaded', e => {
const contentDocument = e.target ? (/** @type {HTMLDocument} */ (e.target)) : undefined;
onFrameLoaded(contentDocument);
});
}
/**
* @param {Document} contentDocument
* @param {Window} contentWindow
*/
const onLoad = (contentDocument, contentWindow) => {
if (contentDocument && contentDocument.body) {
// Workaround for https://github.com/microsoft/vscode/issues/12865
// check new scrollY and reset if necessary
setInitialScrollPosition(contentDocument.body, contentWindow);
}
const newFrame = getPendingFrame();
if (newFrame && newFrame.contentDocument && newFrame.contentDocument === contentDocument) {
const oldActiveFrame = getActiveFrame();
if (oldActiveFrame) {
document.body.removeChild(oldActiveFrame);
}
// Styles may have changed since we created the element. Make sure we re-style
applyStyles(newFrame.contentDocument, newFrame.contentDocument.body);
newFrame.setAttribute('id', 'active-frame');
newFrame.style.visibility = 'visible';
if (host.focusIframeOnCreate) {
newFrame.contentWindow.focus();
}
contentWindow.addEventListener('scroll', handleInnerScroll);
contentWindow.addEventListener('wheel', handleWheel);
if (document.hasFocus()) {
contentWindow.focus();
}
pendingMessages.forEach((data) => {
contentWindow.postMessage(data, '*');
});
pendingMessages = [];
}
host.postMessage('did-load');
};
/**
* @param {HTMLIFrameElement} newFrame
*/
function hookupOnLoadHandlers(newFrame) {
clearTimeout(loadTimeout);
loadTimeout = undefined;
loadTimeout = setTimeout(() => {
clearTimeout(loadTimeout);
loadTimeout = undefined;
onLoad(newFrame.contentDocument, newFrame.contentWindow);
}, 200);
newFrame.contentWindow.addEventListener('load', function (e) {
const contentDocument = /** @type {Document} */ (e.target);
if (loadTimeout) {
clearTimeout(loadTimeout);
loadTimeout = undefined;
onLoad(contentDocument, this);
}
});
// Bubble out various events
newFrame.contentWindow.addEventListener('click', handleInnerClick);
newFrame.contentWindow.addEventListener('auxclick', handleAuxClick);
newFrame.contentWindow.addEventListener('keydown', handleInnerKeydown);
newFrame.contentWindow.addEventListener('contextmenu', e => e.preventDefault());
if (host.onIframeLoaded) {
host.onIframeLoaded(newFrame);
}
}
if (!host.fakeLoad) {
hookupOnLoadHandlers(newFrame);
}
if (!host.fakeLoad) {
newFrame.contentDocument.write(newDocument);
newFrame.contentDocument.close();
}
host.postMessage('did-set-content', undefined);
});
// Forward message to the embedded iframe
host.onMessage('message', (_event, data) => {
const pending = getPendingFrame();
if (!pending) {
const target = getActiveFrame();
if (target) {
target.contentWindow.postMessage(data, '*');
return;
}
}
pendingMessages.push(data);
});
host.onMessage('initial-scroll-position', (_event, progress) => {
initData.initialScrollProgress = progress;
});
host.onMessage('execCommand', (_event, data) => {
const target = getActiveFrame();
if (!target) {
return;
}
target.contentDocument.execCommand(data);
});
trackFocus({
onFocus: () => host.postMessage('did-focus'),
onBlur: () => host.postMessage('did-blur')
});
// signal ready
host.postMessage('webview-ready', {});
});
}
if (typeof module !== 'undefined') {
module.exports = createWebviewManager;
} else {
(/** @type {any} */ (window)).createWebviewManager = createWebviewManager;
}
}());
| src/vs/workbench/contrib/webview/browser/pre/main.js | 1 | https://github.com/microsoft/vscode/commit/608e8791ff194e81a10ac0d963471922ddc9b6e0 | [
0.0002250574907520786,
0.00017337648023385555,
0.00016465609951410443,
0.0001731945958454162,
0.000006810041213611839
] |
{
"id": 2,
"code_window": [
"\t\tthis.portMappingProvider = this._register(new WebviewPortMappingProvider(tunnelService));\n",
"\n",
"\t\tconst sess = session.fromPartition(webviewPartitionId);\n",
"\t\tsess.setPermissionRequestHandler((webContents, permission /* 'media' | 'geolocation' | 'notifications' | 'midiSysex' | 'pointerLock' | 'fullscreen' | 'openExternal' */, callback) => {\n",
"\t\t\treturn callback(false);\n",
"\t\t});\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tsess.setPermissionRequestHandler((_webContents, permission, callback) => {\n",
"\t\t\tif (permission === 'clipboard-read') {\n",
"\t\t\t\treturn callback(true);\n",
"\t\t\t}\n",
"\n"
],
"file_path": "src/vs/platform/webview/electron-main/webviewMainService.ts",
"type": "replace",
"edit_start_line_idx": 37
} | # THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY.
# yarn lockfile v1
| extensions/less/yarn.lock | 0 | https://github.com/microsoft/vscode/commit/608e8791ff194e81a10ac0d963471922ddc9b6e0 | [
0.00017404825484845787,
0.00017404825484845787,
0.00017404825484845787,
0.00017404825484845787,
0
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.