Best JavaScript code snippet using wpt
DataSourceManager.js
Source:DataSourceManager.js  
1///////////////////////////////////////////////////////////////////////////2// Copyright © Esri. All Rights Reserved.3//4// Licensed under the Apache License Version 2.0 (the "License");5// you may not use this file except in compliance with the License.6// You may obtain a copy of the License at7//8//    http://www.apache.org/licenses/LICENSE-2.09//10// Unless required by applicable law or agreed to in writing, software11// distributed under the License is distributed on an "AS IS" BASIS,12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.13// See the License for the specific language governing permissions and14// limitations under the License.15///////////////////////////////////////////////////////////////////////////16define([17    'dojo/_base/declare',18    'dojo/_base/lang',19    'dojo/_base/array',20    'dojo/topic',21    'dojo/Evented',22    'dojo/when',23    './utils',24    'jimu/LayerInfos/LayerInfos',25    'jimu/portalUtils',26    'jimu/portalUrlUtils',27    'jimu/filterUtils',28    'esri/tasks/query',29    'esri/tasks/QueryTask',30    'esri/tasks/StatisticDefinition',31    './Query'32  ],33  function(declare, lang, array, topic, Evented, when, jimuUtils, LayerInfos, portalUtils, portalUrlUtils, FilterUtils,34  Query, QueryTask, StatisticDefinition, JimuQuery) {35    var dataSourceTypes = {36      Features: 'Features',37      FeatureStatistics: 'FeatureStatistics'38    };39    var resultRecordType = {40      all: 'all',41      serviceLimitation: 'serviceLimitation',42      custom: 'custom'43    };44    var instance = null,45      clazz = declare(Evented, {46        constructor: function() {47          this._listeners = [];48          this._refreshTimers = [];49          //key=data source id,50          //value=data51          //    {52          //      data: [] //feature array53          //    }.54          //  if it's feature layer, the feature.attributes are the same with fields:55          //  if it's statistics, the feature.attributes are from statistics56          this._dataStore = {};57          //key=data source id,58          //value=jimuQuery59          //cache jumuQuery here because there maybe pagenation60          this._jimuQueryObject = {};61          //key=data source id62          //value=widget id array63          this._dataSourceUsage = {};64          //key=item url65          //value=filter66          this._itemsFilter = {};67          this.filterUtils = new FilterUtils();68          if(window.isBuilder){69            topic.subscribe("app/mapLoaded", lang.hitch(this, this._onMapLoaded));70            topic.subscribe("app/mapChanged", lang.hitch(this, this._onMapChanged));71          }else{72            topic.subscribe("mapLoaded", lang.hitch(this, this._onMapLoaded));73            topic.subscribe("mapChanged", lang.hitch(this, this._onMapChanged));74          }75          if(window.isBuilder){76            topic.subscribe("app/appConfigLoaded", lang.hitch(this, this._onAppConfigLoaded));77            topic.subscribe("app/appConfigChanged", lang.hitch(this, this._onAppConfigChanged));78          }else{79            topic.subscribe("appConfigLoaded", lang.hitch(this, this._onAppConfigLoaded));80            topic.subscribe("appConfigChanged", lang.hitch(this, this._onAppConfigChanged));81          }82          topic.subscribe("updateDataSourceData", lang.hitch(this, this._onUpdataDataSourceData));83          if(window.isBuilder){84            //in builder, we need listen data source data change in map, so widget setting can read data85            topic.subscribe("app/dataSourceDataUpdated", lang.hitch(this, this._onDataSourceDataUpdatedInApp));86          }87        },88        getData: function(dsId){89          return this._dataStore[dsId];90        },91        getDataSourceConfig: function(dsId){92          return this.appConfig.dataSource.dataSources[dsId];93        },94        parseDataSourceId: function(id){95          var segs = id.split('~');96          var ret = {};97          if(segs.length < 2){98            console.error('Bad data source id:', id);99            return ret;100          }101          switch(segs[0]){102            case 'map': //map~<layerId>~<filterId>103              //layer id may contain "~"104              var lastPos = id.lastIndexOf('~');105              ret = {106                from: 'map',107                layerId: id.substring(4, lastPos)108              };109              return ret;110            case 'widget': //widget~<widgetId>~<dataSourceId>111              ret = {112                from: 'widget',113                widgetId: segs[1]114              };115              return ret;116            case 'external': //external~<id>117              ret = {118                from: 'external'119              };120              return ret;121            default:122              console.error('Bad data source id:', id);123          }124        },125        addDataSourceUsage: function(dsId, widgetId){126          if(!this._dataSourceUsage[dsId]){127            this._dataSourceUsage[dsId] = [widgetId];128            this._startOneDataSource(this.appConfig.dataSource.dataSources[dsId]);129          }else{130            if(this._dataSourceUsage[dsId].indexOf(widgetId) < 0){131              this._dataSourceUsage[dsId].push(widgetId);132            }133            if(this._dataSourceUsage[dsId].length === 1){134              this._startOneDataSource(this.appConfig.dataSource.dataSources[dsId]);135            }136          }137        },138        removeDataSourceUsage: function(dsId, widgetId){139          if(!this._dataSourceUsage[dsId]){140            return;141          }142          if(this._dataSourceUsage[dsId].indexOf(widgetId) >= 0){143            this._dataSourceUsage[dsId] = array.filter(this._dataSourceUsage[dsId], function(wid){144              return wid !== widgetId;145            });146          }147          // if(this._dataSourceUsage[dsId].length === 0){148          //   this._stopAndCleanOneDataSource(this.appConfig.dataSource.dataSources[dsId]);149          // }150        },151        _onUpdataDataSourceData: function(dsId, data){152          var ds = this.appConfig.dataSource.dataSources[dsId];153          if(!ds){154            console.error('Not found data source id:', dsId);155            return;156          }157          var idObj = this.parseDataSourceId(dsId);158          if(idObj.from !== 'widget'){159            console.error('Please update data source from widget only.', dsId);160            return;161          }162          this._updateDataSourceData(dsId, data);163        },164        _updateDataSourceData: function(dsId, data){165          this._dataStore[dsId] = data;166          topic.publish('dataSourceDataUpdated', dsId, data);167          this.emit('update', dsId, data);168        },169        _onDataSourceDataUpdatedInApp: function(dsId, data){170          this._updateDataSourceData(dsId, data);171        },172        _onMapLoaded: function(map) {173          this.map = map;174          if(window.isBuilder){175            return;176          }177          this._handleDataSourceConfigChange(this.appConfig, this.appConfig, 'mapLoaded');178        },179        _onMapChanged: function(map) {180          this.map = map;181          if(window.isBuilder){182            return;183          }184          this._handleDataSourceConfigChange(this.appConfig, this.appConfig, 'mapChanged');185        },186        _onAppConfigLoaded: function(_appConfig) {187          var appConfig = lang.clone(_appConfig);188          this.appConfig = appConfig;189        },190        _onAppConfigChanged: function(_appConfig, reason) {191          var appConfig = lang.clone(_appConfig);192          if(window.isBuilder){193            this.appConfig = appConfig;194            return;195          }196          if(reason === 'dataSourceChange'){197            this._handleDataSourceConfigChange(this.appConfig, appConfig, reason);198          }else if(reason === 'mapChange'){199            this._cleanForConfigChangedDataSource(this.appConfig, appConfig);200          }201          this.appConfig = appConfig;202        },203        _handleDataSourceConfigChange: function(oldAppConfig, newAppConfig, reason){204          if(oldAppConfig){205            this._removeListeners();206            this._removeTimers();207            this._cleanForConfigChangedDataSource(oldAppConfig, newAppConfig);208          }209          array.forEach(Object.keys(newAppConfig.dataSource.dataSources), function(dsId){210            newAppConfig.dataSource.dataSources[dsId].idObj = this.parseDataSourceId(dsId);211          }, this);212          this._listenDataSourceChange(newAppConfig.dataSource.dataSources);213          this._startRefreshTimer(newAppConfig.dataSource, reason);214          this._initStaticDataSource(newAppConfig.dataSource);215        },216        _cleanForConfigChangedDataSource: function(oldAppConfig, newAppConfig){217          var oldDss = oldAppConfig.dataSource.dataSources;218          var newDss = newAppConfig.dataSource.dataSources;219          array.forEach(Object.keys(oldDss), function(dsId){220            if(!newDss[dsId] ||221              (newDss[dsId] && !jimuUtils.isEqual(newDss[dsId], oldDss[dsId]))){222              delete this._jimuQueryObject[dsId];223              this._updateDataSourceData(dsId, {features: []});224              delete this._dataStore[dsId];225            }226          }, this);227        },228        _isGlobalRefresh: function(settings){229          return settings.unifiedRefreshInterval && settings.unifiedRefreshInterval > 0;230        },231        _startOneDataSource: function(ds){232          var interval;233          if(this._isGlobalRefresh(this.appConfig.dataSource.settings)){234            interval = this.appConfig.dataSource.settings.unifiedRefreshInterval;235          }else{236            interval = ds.refreshInterval;237          }238          if(ds.idObj.from === 'map'){239            this._listenMapDataSourceChange(ds);240          }else if(ds.idObj.from === 'external'){241            if(ds.filterByExtent){242              var listener = {};243              listener.handle = this.map.on('extent-change', lang.hitch(this, this._onLayerDataChange, ds));244              listener.dsId = ds.id;245              this._listeners.push(listener);246            }247          }248          if(ds.idObj.from === 'map' || ds.idObj.from === 'external'){249            this._refeshDataSource(ds);250            if(ds.isDynamic){251              var timer = {};252              timer.handle = setInterval(lang.hitch(this, this._refeshDataSource, ds), interval * 1000 * 60);253              timer.dsId = ds.id;254              this._refreshTimers.push(timer);255            }256          }257        },258        _stopAndCleanOneDataSource: function(ds){259          this._listeners =  array.filter(this._listeners, function(listener){260            if(listener.dsId === ds.id){261              listener.handle.remove();262              return false;263            }else{264              return true;265            }266          }, this);267          this._refreshTimers = array.filter(this._refreshTimers, function(timer){268            if(timer.dsId === ds.id){269              clearInterval(timer.handle);270              return false;271            }else{272              return true;273            }274          }, this);275          this._updateDataSourceData(ds.id, {features: []});276        },277        _listenDataSourceChange: function(dataSources){278          array.forEach(Object.keys(dataSources), function(dsId){279            var ds = dataSources[dsId];280            //data source from widget will changed by widget,281            if(ds.idObj.from === 'map'){282              this._listenMapDataSourceChange(ds);283            }else if(ds.idObj.from === 'external'){284              if(ds.filterByExtent){285                var listener = {};286                listener.handle = this.map.on('extent-change', lang.hitch(this, this._onLayerDataChange, ds));287                listener.dsId = ds.id;288                this._listeners.push(listener);289              }290            }291          }, this);292        },293        _listenMapDataSourceChange: function(ds){294          this._getLayerObject(ds.idObj.layerId).then(lang.hitch(this, function(layer){295            if(!layer){296              //means layer is not in map, this means layer is removed, or map is changed.297              console.error('Can not find layer that data source depends on.', ds.id);298              return;299            }300            var listener = {};301            listener.handle = layer.on('edits-complete', lang.hitch(this, this._onLayerDataChange, ds));302            listener.dsId = ds.id;303            this._listeners.push(listener);304            listener = {};305            listener.handle = this._getLayerInfo(ds.idObj.layerId)306              .on('filterChanged', lang.hitch(this, this._onLayerDataChange, ds));307            listener.dsId = ds.id;308            this._listeners.push(listener);309            if(ds.filterByExtent){310              listener = {};311              listener.handle = this.map.on('extent-change', lang.hitch(this, this._onLayerDataChange, ds));312              listener.dsId = ds.id;313              this._listeners.push(listener);314            }315            // //316            // if(layer.refreshInterval){317            //   ds.isDynamic = true;318            //   ds.refreshInterval = layer.refreshInterval;319            // }else{320            //   ds.isDynamic = false;321            //   ds.refreshInterval = 0;322            // }323          }));324        },325        _onLayerDataChange: function(ds){326          this._doQueryForDataSource(ds);327        },328        _doQueryForDataSource: function(ds){329          if(this.appConfig.mode !== 'config'){330            //in config mode, we don't care whether data source is ued, we always do query because data source may331            //be used by setting page.332            //when launch app, we query data only when data source is used.333            if(!this._dataSourceUsage[ds.id] || this._dataSourceUsage[ds.id].length === 0){334              return;335            }336          }337          this.doQuery(ds).then(lang.hitch(this, function(featureSet){338            this._updateDataSourceData(ds.id, {339              features: featureSet.features340            });341          }));342        },343        _getLayerObject: function(layerId){344          var layerInfo = LayerInfos.getInstanceSync().getLayerOrTableInfoById(layerId);345          if(layerInfo){346            return layerInfo.getLayerObject();347          }else{348            return when(null);349          }350        },351        _getLayerInfo: function(layerId){352          return LayerInfos.getInstanceSync().getLayerOrTableInfoById(layerId);353        },354        _startRefreshTimer: function(dataSource, reason){355          var dataSources = dataSource.dataSources;356          var dataSourceSettings = dataSource.settings;357          array.forEach(Object.keys(dataSources), function(dsId){358            var ds = dataSources[dsId];359            if(ds.idObj.from === 'widget' || !ds.isDynamic || !ds.url){360              return;361            }362            var interval;363            if(this._isGlobalRefresh(dataSourceSettings)){364              interval = dataSourceSettings.unifiedRefreshInterval;365            }else{366              interval = ds.refreshInterval;367            }368            if(reason === 'dataSourceChange'){369              if(ds.idObj.from === 'external' || ds.idObj.from === 'map'){370                //data source change will not trigger layer update-end event, so query here371                this._refeshDataSource(ds);372              }373            }else{374              if(ds.idObj.from === 'external'){375                //for ds from map, because we listen layer update-end event, so we don't do query here.376                this._refeshDataSource(ds);377              }378            }379            var timer = {380              handle: setInterval(lang.hitch(this, this._refeshDataSource, ds), interval * 1000 * 60),381              dsId: dataSource.id382            };383            this._refreshTimers.push(timer);384          }, this);385        },386        _initStaticDataSource: function(dataSource){387          array.forEach(Object.keys(dataSource.dataSources), function(dsId){388            var ds = dataSource.dataSources[dsId];389            if(ds.idObj.from === 'widget' || ds.isDynamic || !ds.url){390              return;391            }392            this._doQueryForDataSource(ds);393          }, this);394        },395        _refeshDataSource: function(ds){396          this._doQueryForDataSource(ds);397        },398        _getDataSourceFilter: function(ds){399          if(ds.idObj.from === 'map'){400            var layerInfo = LayerInfos.getInstanceSync().getLayerOrTableInfoById(ds.idObj.layerId);401            var webMapFilter;402            if(layerInfo){403              webMapFilter = layerInfo.getFilter();404            }405            var dsFilter = ds.filter? this._getFilterExpr(ds.filter, ds.url): '1=1';406            var filter;407            if(webMapFilter){408              filter = '(' + webMapFilter + ') and (' + dsFilter + ')';409            }else{410              filter = dsFilter;411            }412            return when(filter);413          }else if(ds.idObj.from === 'external'){414            if(ds.portalUrl && ds.itemId){415              return this._getFilterFromItem(ds.portalUrl, ds.itemId, ds.url)416              .then(lang.hitch(this, function(itemFilter){417                var dsFilter = ds.filter? this._getFilterExpr(ds.filter, ds.url): '1=1';418                if(itemFilter){419                  filter = '(' + itemFilter + ') and (' + dsFilter + ')';420                }else{421                  filter = dsFilter;422                }423                return filter;424              }));425            }else{426              return when(ds.filter? this._getFilterExpr(ds.filter, ds.url): '1=1');427            }428          }else{429            return when(ds.filter? this._getFilterExpr(ds.filter, ds.url): '1=1');430          }431        },432        _getFilterExpr: function(filterObj, url){433          if(this.filterUtils.hasVirtualDate(filterObj)){434            this.filterUtils.isHosted = jimuUtils.isHostedService(url);435            return this.filterUtils.getExprByFilterObj(filterObj);436          }else{437            return filterObj.expr;438          }439        },440        _getFilterFromItem: function(portalUrl, itemId, url){441          var key = portalUrlUtils.getItemUrl(portalUrl, itemId);442          if(this._itemsFilter[key]){443            return when(this._itemsFilter[key]);444          }445          var portal = portalUtils.getPortal(portalUrl);446          return portal.getItemById(itemId).then(lang.hitch(this, function(itemInfo){447            //for now, we see that only feature service item supports set filter448            if(itemInfo.type !== 'Feature Service'){449              this._itemsFilter[key] = null;450              return null;451            }452            return portal.getItemData(itemId).then(lang.hitch(this, function(itemData){453              var segs = url.split('/');454              var layerId = segs.pop();455              if(!layerId){//the url ends with '/'456                layerId = segs.pop();457              }458              if(!itemData.layers){459                this._itemsFilter[key] = null;460                return null;461              }462              var layer = itemData.layers.filter(function(layer){463                return layer.id + '' === layerId;464              })[0];465              if(!layer || !layer.layerDefinition){466                this._itemsFilter[key] = null;467                return null;468              }469              this._itemsFilter[key] = layer.layerDefinition.definitionExpression;470              return layer.layerDefinition.definitionExpression;471            }));472          }));473        },474        doQuery: function(ds){475          if(!ds.idObj){476            ds.idObj = this.parseDataSourceId(ds.id);477          }478          this.emit('begin-update', ds.id);479          return this._getQueryObjectFromDataSource(ds).then(lang.hitch(this, function(queryObj){480            var query, queryTask;481            if(ds.type === dataSourceTypes.Features){482              if(ds.resultRecordType === resultRecordType.serviceLimitation){483                query = queryObj;484                queryTask = new QueryTask(ds.url);485                return queryTask.execute(query);486              }else{487                //when data source is changed, the cache will be removed.488                var jimuQuery = this._jimuQueryObject[ds.id];489                if(jimuQuery){490                  //the query object may be changed in runtime491                  if(jimuQuery.url !== ds.url ||492                    !jimuUtils.isEqual(jimuQuery.query.toJson(), queryObj.toJson())){493                    delete this._jimuQueryObject[ds.id];494                    jimuQuery = null;495                  }496                }497                if(!jimuQuery){498                  var queryOptions = {};499                  queryOptions.url = ds.url;500                  queryOptions.query = queryObj;501                  if(ds.resultRecordType === resultRecordType.all){502                    jimuQuery = new JimuQuery(queryOptions);503                  }else{504                    queryOptions.pageSize = ds.resultRecordCount;505                    jimuQuery = new JimuQuery(queryOptions);506                  }507                  this._jimuQueryObject[ds.id] = jimuQuery;508                }509                if(ds.resultRecordType === resultRecordType.all){510                  return jimuQuery.getAllFeatures();511                }else{512                  return jimuQuery.queryByPage(1);513                }514              }515            }else{516              queryTask = new QueryTask(ds.url);517              query = new Query();518              return this._getDataSourceFilter(ds).then(lang.hitch(this, function(dsFilter){519                query.where = dsFilter;520                if (ds.filterByExtent) {521                  query.geometry = this.map.extent;522                }523                if(ds.dataSchema.groupByFields && ds.dataSchema.groupByFields.length > 0){524                  query.groupByFieldsForStatistics = ds.dataSchema.groupByFields;525                }526                if(ds.dataSchema.orderByFields && ds.dataSchema.orderByFields.length > 0){527                  query.orderByFields = ds.dataSchema.orderByFields;528                }529                query.outStatistics = ds.dataSchema.statistics.map(function(s){530                  var statName = s.onStatisticField + '_' + s.statisticType;531                  if(s.statisticType === 'count'){532                    statName = 'STAT_COUNT';533                  }534                  statName = jimuUtils.upperCaseString(statName);535                  var statisticDefinition = new StatisticDefinition();536                  statisticDefinition.statisticType = s.statisticType;537                  statisticDefinition.onStatisticField = s.onStatisticField;538                  statisticDefinition.outStatisticFieldName = statName;539                  return statisticDefinition;540                });541                return queryTask.execute(query);542              }));543            }544          }));545        },546        _getQueryObjectFromDataSource: function(ds){547          return this._getDataSourceFilter(ds).then(lang.hitch(this, function(dsFilter){548            var query = new Query();549            query.where = dsFilter;550            if(ds.filterByExtent){551              query.geometry = this.map.extent;552            }553            query.outFields = ds.dataSchema.fields.map(function(f){554              return f.name;555            });556            if(ds.dataSchema.orderByFields && ds.dataSchema.orderByFields.length > 0){557              query.orderByFields = ds.dataSchema.orderByFields;558            }559            query.returnGeometry = true;560            query.outSpatialReference = this.map.spatialReference;561            return when(query);562          }));563        },564        _removeListeners: function(){565          this._listeners.forEach(lang.hitch(this, function(listener){566            listener.handle.remove();567          }));568          this._listeners = [];569        },570        _removeTimers: function(){571          this._refreshTimers.forEach(lang.hitch(this, function(timer){572            clearInterval(timer.handle);573          }));574          this._refreshTimers = [];575        }576      });577    clazz.getInstance = function() {578      if (instance === null) {579        instance = new clazz();580        window._datasourceManager = instance;581      }582      return instance;583    };584    return clazz;...expr.js
Source:expr.js  
1// Copyright 2006 The Closure Library Authors. All Rights Reserved.2//3// Licensed under the Apache License, Version 2.0 (the "License");4// you may not use this file except in compliance with the License.5// You may obtain a copy of the License at6//7//      http://www.apache.org/licenses/LICENSE-2.08//9// Unless required by applicable law or agreed to in writing, software10// distributed under the License is distributed on an "AS-IS" BASIS,11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.12// See the License for the specific language governing permissions and13// limitations under the License.14/**15 * @fileoverview16 * Expression evaluation utilities. Expression format is very similar to XPath.17 *18 * Expression details:19 * - Of format A/B/C, which will evaluate getChildNode('A').getChildNode('B').20 *    getChildNodes('C')|getChildNodeValue('C')|getChildNode('C') depending on21 *    call22 * - If expression ends with '/name()', will get the name() of the node23 *    referenced by the preceding path.24 * - If expression ends with '/count()', will get the count() of the nodes that25 *    match the expression referenced by the preceding path.26 * - If expression ends with '?', the value is OK to evaluate to null. This is27 *    not enforced by the expression evaluation functions, instead it is28 *    provided as a flag for client code which may ignore depending on usage29 * - If expression has [INDEX], will use getChildNodes().getByIndex(INDEX)30 *31 */32goog.provide('goog.ds.Expr');33goog.require('goog.ds.BasicNodeList');34goog.require('goog.ds.EmptyNodeList');35goog.require('goog.string');36/**37 * Create a new expression. An expression uses a string expression language, and38 * from this string and a passed in DataNode can evaluate to a value, DataNode,39 * or a DataNodeList.40 *41 * @param {string=} opt_expr The string expression.42 * @constructor43 */44goog.ds.Expr = function(opt_expr) {45  if (opt_expr) {46    this.setSource_(opt_expr);47  }48};49/**50 * Set the source expression text & parse51 *52 * @param {string} expr The string expression source.53 * @param {Array=} opt_parts Array of the parts of an expression.54 * @param {goog.ds.Expr=} opt_childExpr Optional child of this expression,55 *   passed in as a hint for processing.56 * @param {goog.ds.Expr=} opt_prevExpr Optional preceding expression57 *   (i.e. $A/B/C is previous expression to B/C) passed in as a hint for58 *   processing.59 * @private60 */61goog.ds.Expr.prototype.setSource_ = function(expr, opt_parts,62    opt_childExpr, opt_prevExpr) {63  this.src_ = expr;64  if (!opt_childExpr && !opt_prevExpr) {65    // Check whether it can be empty66    if (goog.string.endsWith(expr, goog.ds.Expr.String_.CAN_BE_EMPTY)) {67      this.canBeEmpty_ = true;68      expr = expr.substring(0, expr.length - 1);69    }70    // Check whether this is an node function71    if (goog.string.endsWith(expr, '()')) {72      if (goog.string.endsWith(expr, goog.ds.Expr.String_.NAME_EXPR) ||73          goog.string.endsWith(expr, goog.ds.Expr.String_.COUNT_EXPR) ||74          goog.string.endsWith(expr, goog.ds.Expr.String_.POSITION_EXPR)) {75        var lastPos = expr.lastIndexOf(goog.ds.Expr.String_.SEPARATOR);76        if (lastPos != -1) {77          this.exprFn_ = expr.substring(lastPos + 1);78          expr = expr.substring(0, lastPos);79        } else {80          this.exprFn_ = expr;81          expr = goog.ds.Expr.String_.CURRENT_NODE_EXPR;82        }83        if (this.exprFn_ == goog.ds.Expr.String_.COUNT_EXPR) {84          this.isCount_ = true;85        }86      }87    }88  }89  // Split into component parts90  this.parts_ = opt_parts || expr.split('/');91  this.size_ = this.parts_.length;92  this.last_ = this.parts_[this.size_ - 1];93  this.root_ = this.parts_[0];94  if (this.size_ == 1) {95    this.rootExpr_ = this;96    this.isAbsolute_ = goog.string.startsWith(expr, '$');97  } else {98    this.rootExpr_ = goog.ds.Expr.createInternal_(this.root_, null,99        this, null);100    this.isAbsolute_ = this.rootExpr_.isAbsolute_;101    this.root_ = this.rootExpr_.root_;102  }103  if (this.size_ == 1 && !this.isAbsolute_) {104    // Check whether expression maps to current node, for convenience105    this.isCurrent_ = (expr == goog.ds.Expr.String_.CURRENT_NODE_EXPR ||106        expr == goog.ds.Expr.String_.EMPTY_EXPR);107    // Whether this expression is just an attribute (i.e. '@foo')108    this.isJustAttribute_ =109        goog.string.startsWith(expr, goog.ds.Expr.String_.ATTRIBUTE_START);110    // Check whether this is a common node expression111    this.isAllChildNodes_ = expr == goog.ds.Expr.String_.ALL_CHILD_NODES_EXPR;112    this.isAllAttributes_ = expr == goog.ds.Expr.String_.ALL_ATTRIBUTES_EXPR;113    this.isAllElements_ = expr == goog.ds.Expr.String_.ALL_ELEMENTS_EXPR;114  }115};116/**117 * Get the source data path for the expression118 * @return {string} The path.119 */120goog.ds.Expr.prototype.getSource = function() {121  return this.src_;122};123/**124 * Gets the last part of the expression.125 * @return {?string} Last part of the expression.126 */127goog.ds.Expr.prototype.getLast = function() {128  return this.last_;129};130/**131 * Gets the parent expression of this expression, or null if this is top level132 * @return {goog.ds.Expr} The parent.133 */134goog.ds.Expr.prototype.getParent = function() {135  if (!this.parentExprSet_) {136    if (this.size_ > 1) {137      this.parentExpr_ = goog.ds.Expr.createInternal_(null,138          this.parts_.slice(0, this.parts_.length - 1), this, null);139    }140    this.parentExprSet_ = true;141  }142  return this.parentExpr_;143};144/**145 * Gets the parent expression of this expression, or null if this is top level146 * @return {goog.ds.Expr} The parent.147 */148goog.ds.Expr.prototype.getNext = function() {149  if (!this.nextExprSet_) {150    if (this.size_ > 1) {151      this.nextExpr_ = goog.ds.Expr.createInternal_(null, this.parts_.slice(1),152          null, this);153    }154    this.nextExprSet_ = true;155  }156  return this.nextExpr_;157};158/**159 * Evaluate an expression on a data node, and return a value160 * Recursively walks through child nodes to evaluate161 * TODO(user) Support other expression functions162 *163 * @param {goog.ds.DataNode=} opt_ds Optional datasource to evaluate against.164 *     If not provided, evaluates against DataManager global root.165 * @return {*} Value of the node, or null if doesn't exist.166 */167goog.ds.Expr.prototype.getValue = function(opt_ds) {168  if (opt_ds == null) {169    opt_ds = goog.ds.DataManager.getInstance();170  } else if (this.isAbsolute_) {171    opt_ds = opt_ds.getDataRoot ? opt_ds.getDataRoot() :172        goog.ds.DataManager.getInstance();173  }174  if (this.isCount_) {175    var nodes = this.getNodes(opt_ds);176    return nodes.getCount();177  }178  if (this.size_ == 1) {179    return opt_ds.getChildNodeValue(this.root_);180  } else if (this.size_ == 0) {181    return opt_ds.get();182  }183  var nextDs = opt_ds.getChildNode(this.root_);184  if (nextDs == null) {185    return null;186  } else {187    return this.getNext().getValue(nextDs);188  }189};190/**191 * Evaluate an expression on a data node, and return matching nodes192 * Recursively walks through child nodes to evaluate193 *194 * @param {goog.ds.DataNode=} opt_ds Optional datasource to evaluate against.195 *     If not provided, evaluates against data root.196 * @param {boolean=} opt_canCreate If true, will try to create new nodes.197 * @return {goog.ds.DataNodeList} Matching nodes.198 */199goog.ds.Expr.prototype.getNodes = function(opt_ds, opt_canCreate) {200  return /** @type {goog.ds.DataNodeList} */(this.getNodes_(opt_ds,201      false, opt_canCreate));202};203/**204 * Evaluate an expression on a data node, and return the first matching node205 * Recursively walks through child nodes to evaluate206 *207 * @param {goog.ds.DataNode=} opt_ds Optional datasource to evaluate against.208 *     If not provided, evaluates against DataManager global root.209 * @param {boolean=} opt_canCreate If true, will try to create new nodes.210 * @return {goog.ds.DataNode} Matching nodes, or null if doesn't exist.211 */212goog.ds.Expr.prototype.getNode = function(opt_ds, opt_canCreate) {213  return /** @type {goog.ds.DataNode} */(this.getNodes_(opt_ds,214      true, opt_canCreate));215};216/**217 * Evaluate an expression on a data node, and return the first matching node218 * Recursively walks through child nodes to evaluate219 *220 * @param {goog.ds.DataNode=} opt_ds Optional datasource to evaluate against.221 *     If not provided, evaluates against DataManager global root.222 * @param {boolean=} opt_selectOne Whether to return single matching DataNode223 *     or matching nodes in DataNodeList.224 * @param {boolean=} opt_canCreate If true, will try to create new nodes.225 * @return {goog.ds.DataNode|goog.ds.DataNodeList} Matching node or nodes,226 *     depending on value of opt_selectOne.227 * @private228 */229goog.ds.Expr.prototype.getNodes_ = function(opt_ds, opt_selectOne,230    opt_canCreate) {231  if (opt_ds == null) {232    opt_ds = goog.ds.DataManager.getInstance();233  } else if (this.isAbsolute_) {234    opt_ds = opt_ds.getDataRoot ? opt_ds.getDataRoot() :235        goog.ds.DataManager.getInstance();236  }237  if (this.size_ == 0 && opt_selectOne) {238      return opt_ds;239  } else if (this.size_ == 0 && !opt_selectOne) {240    return new goog.ds.BasicNodeList([opt_ds]);241  } else if (this.size_ == 1) {242    if (opt_selectOne) {243      return opt_ds.getChildNode(this.root_, opt_canCreate);244    }245    else {246      var possibleListChild = opt_ds.getChildNode(this.root_);247      if (possibleListChild && possibleListChild.isList()) {248        return possibleListChild.getChildNodes();249      } else {250        return opt_ds.getChildNodes(this.root_);251      }252    }253  } else {254    var nextDs = opt_ds.getChildNode(this.root_, opt_canCreate);255    if (nextDs == null && opt_selectOne) {256      return null;257    } else if (nextDs == null && !opt_selectOne) {258      return new goog.ds.EmptyNodeList();259    }260    return this.getNext().getNodes_(nextDs, opt_selectOne, opt_canCreate);261  }262};263/**264 * Whether the expression can be null.265 *266 * @type {boolean}267 * @private268 */269goog.ds.Expr.prototype.canBeEmpty_ = false;270/**271 * The parsed paths in the expression272 *273 * @type {Array.<string>}274 * @private275 */276goog.ds.Expr.prototype.parts_ = [];277/**278 * Number of paths in the expression279 *280 * @type {?number}281 * @private282 */283goog.ds.Expr.prototype.size_ = null;284/**285 * The root node path in the expression286 *287 * @type {string}288 * @private289 */290goog.ds.Expr.prototype.root_;291/**292 * The last path in the expression293 *294 * @type {?string}295 * @private296 */297goog.ds.Expr.prototype.last_ = null;298/**299 * Whether the expression evaluates to current node300 *301 * @type {boolean}302 * @private303 */304goog.ds.Expr.prototype.isCurrent_ = false;305/**306 * Whether the expression is just an attribute307 *308 * @type {boolean}309 * @private310 */311goog.ds.Expr.prototype.isJustAttribute_ = false;312/**313 * Does this expression select all DOM-style child nodes (element and text)314 *315 * @type {boolean}316 * @private317 */318goog.ds.Expr.prototype.isAllChildNodes_ = false;319/**320 * Does this expression select all DOM-style attribute nodes (starts with '@')321 *322 * @type {boolean}323 * @private324 */325goog.ds.Expr.prototype.isAllAttributes_ = false;326/**327 * Does this expression select all DOM-style element child nodes328 *329 * @type {boolean}330 * @private331 */332goog.ds.Expr.prototype.isAllElements_ = false;333/**334 * The function used by this expression335 *336 * @type {?string}337 * @private338 */339goog.ds.Expr.prototype.exprFn_ = null;340/**341 * Cached value for the parent expression.342 * @type {goog.ds.Expr?}343 * @private344 */345goog.ds.Expr.prototype.parentExpr_ = null;346/**347 * Cached value for the next expression.348 * @type {goog.ds.Expr?}349 * @private350 */351goog.ds.Expr.prototype.nextExpr_ = null;352/**353 * Create an expression from a string, can use cached values354 *355 * @param {string} expr The expression string.356 * @return {goog.ds.Expr} The expression object.357 */358goog.ds.Expr.create = function(expr) {359  var result = goog.ds.Expr.cache_[expr];360  if (result == null) {361    result = new goog.ds.Expr(expr);362    goog.ds.Expr.cache_[expr] = result;363  }364  return result;365};366/**367 * Create an expression from a string, can use cached values368 * Uses hints from related expressions to help in creation369 *370 * @param {?string=} opt_expr The string expression source.371 * @param {Array=} opt_parts Array of the parts of an expression.372 * @param {goog.ds.Expr=} opt_childExpr Optional child of this expression,373 *   passed in as a hint for processing.374 * @param {goog.ds.Expr=} opt_prevExpr Optional preceding expression375 *   (i.e. $A/B/C is previous expression to B/C) passed in as a hint for376 *   processing.377 * @return {goog.ds.Expr} The expression object.378 * @private379 */380goog.ds.Expr.createInternal_ = function(opt_expr, opt_parts, opt_childExpr,381    opt_prevExpr) {382  var expr = opt_expr || opt_parts.join('/');383  var result = goog.ds.Expr.cache_[expr];384  if (result == null) {385    result = new goog.ds.Expr();386    result.setSource_(expr, opt_parts, opt_childExpr, opt_prevExpr);387    goog.ds.Expr.cache_[expr] = result;388  }389  return result;390};391/**392 * Cache of pre-parsed expressions393 * @private394 */395goog.ds.Expr.cache_ = {};396/**397 * Commonly used strings in expressions.398 * @enum {string}399 * @private400 */401goog.ds.Expr.String_ = {402  SEPARATOR: '/',403  CURRENT_NODE_EXPR: '.',404  EMPTY_EXPR: '',405  ATTRIBUTE_START: '@',406  ALL_CHILD_NODES_EXPR: '*|text()',407  ALL_ATTRIBUTES_EXPR: '@*',408  ALL_ELEMENTS_EXPR: '*',409  NAME_EXPR: 'name()',410  COUNT_EXPR: 'count()',411  POSITION_EXPR: 'position()',412  INDEX_START: '[',413  INDEX_END: ']',414  CAN_BE_EMPTY: '?'415};416/**417 * Standard expressions418 */419/**420 * The current node421 */422goog.ds.Expr.CURRENT = goog.ds.Expr.create(423    goog.ds.Expr.String_.CURRENT_NODE_EXPR);424/**425 * For DOM interop - all DOM child nodes (text + element).426 * Text nodes have dataName #text427 */428goog.ds.Expr.ALL_CHILD_NODES =429    goog.ds.Expr.create(goog.ds.Expr.String_.ALL_CHILD_NODES_EXPR);430/**431 * For DOM interop - all DOM element child nodes432 */433goog.ds.Expr.ALL_ELEMENTS =434    goog.ds.Expr.create(goog.ds.Expr.String_.ALL_ELEMENTS_EXPR);435/**436 * For DOM interop - all DOM attribute nodes437 * Attribute nodes have dataName starting with "@"438 */439goog.ds.Expr.ALL_ATTRIBUTES =440    goog.ds.Expr.create(goog.ds.Expr.String_.ALL_ATTRIBUTES_EXPR);441/**442 * Get the dataName of a node443 */444goog.ds.Expr.NAME = goog.ds.Expr.create(goog.ds.Expr.String_.NAME_EXPR);445/**446 * Get the count of nodes matching an expression447 */448goog.ds.Expr.COUNT = goog.ds.Expr.create(goog.ds.Expr.String_.COUNT_EXPR);449/**450 * Get the position of the "current" node in the current node list451 * This will only apply for datasources that support the concept of a current452 * node (none exist yet). This is similar to XPath position() and concept of453 * current node454 */...Ds.js
Source:Ds.js  
1if (loglvl) print("--> Ds.js");2var RPMNS_TYPE_RPMLIB = (1 << 9);3var GPSEE = require('rpmds');4var ds = new GPSEE.Ds('rpmlib');5ack("typeof ds;", "object");6ack("ds instanceof GPSEE.Ds;", true);7ack("ds.debug = 1;", 1);8ack("ds.debug = 0;", 0);9ack("ds.length", 25);10ack("ds.type", "Provides");11ack("ds.A", undefined);12ack("ds.buildtime = 1234;", 1234);13ack("ds.color = 4;", 4);14ack("ds.nopromote = 1;", 1);15ack("ds.nopromote = 0;", 0);16var deps = new Array();17var ix = 0;18for (let [key,val] in Iterator(ds)) {19  deps[ix++] = val;20}21ack("ix == ds.length", true);22ix = 023for (var [key,val] in Iterator(ds)) {24    ack("key == ix", true);25    ack("deps[ix] == val", true);26    ack("ds[ix] == val", true);27    ack("ds[ix] == deps[ix]", true);28    ix++;29}30ack("ix == ds.length", true);31ack("ds.ix = -1;", -1);32ack("ds[-1] == undefined", true);33ack("ds.N == undefined", true);34ack("ds.EVR == undefined", true);35ack("ds.F == undefined", true);36ack("ds.DNEVR == undefined", true);37ack("ds.NS == undefined", true);38ack("ds.refs == undefined", true);39ack("ds.result == undefined", true);40ack("ds.ix += 1;", 0);41ack("ds[0] != undefined", true);42ack("ds.ix", 0);43ack("ds.N == ds[0][0]", true);44ack("ds.N", "BuiltinAugeasScripts");45ack("ds.N == ds[0][0]", true);46ack("ds.EVR", "5.3-1");47ack("ds.EVR == ds[0][1]", true);48ack("ds.F", 16777224);49ack("ds.F == ds[0][2]", true);50ack("ds.DNEVR", "P rpmlib(BuiltinAugeasScripts) = 5.3-1");51ack("ds.NS == RPMNS_TYPE_RPMLIB", true);52ack("ds.refs += 1;", 1);53ack("ds.result = 1;", 1);54ack("ds.ix += 1;", 1);55ack("ds[1] != undefined", true);56ack("ds.ix", 1);57ack("ds.N", "BuiltinFiclScripts");58ack("ds.N == ds[1][0]", true);59ack("ds.EVR", "5.2-1");60ack("ds.EVR == ds[1][1]", true);61ack("ds.F", 16777224);62ack("ds.F == ds[1][2]", true);63ack("ds.DNEVR", "P rpmlib(BuiltinFiclScripts) = 5.2-1");64ack("ds.NS == RPMNS_TYPE_RPMLIB", true);65ack("ds.refs += 1;", 1);66ack("ds.result = 1;", 1);67// for (var [key,val] in Iterator(ds))68//     print("\t"+key+": "+val);69// print(JSON.stringify(ds));70delete ds;...Using AI Code Generation
1var wpt = require('webpagetest');2var wpt = new WebPageTest('www.webpagetest.org');3    if (err)4        console.log(err);5        console.log(data);6});71. Fork it (Using AI Code Generation
1var wptools = require('./wptools.js');2var page = wptools.page('Albert Einstein');3page.get(function(err, resp) {4  console.log(resp);5  console.log(resp.data);6  console.log(resp.data.extract);7  console.log(resp.data.image);8  console.log(resp.data.imageinfo[0].url);9});10var wptools = require('./wptools.js');11var page = wptools.page('Albert Einstein');12page.get(function(err, resp) {13  console.log(resp);14  console.log(resp.data);15  console.log(resp.data.extract);16  console.log(resp.data.image);17  console.log(resp.data.imageinfo[0].url);18});Using AI Code Generation
1var wptools = require('wptools');2var ds = require('wptools/lib/ds');3var article = wptools.page('Albert Einstein');4article.get(function(err, resp) {5  if (err) {6    console.log(err);7  } else {8    console.log(ds(resp));9  }10});11var wptools = require('wptools');12var ds = require('wptools/lib/ds');13var article = wptools.page('Albert Einstein');14article.get(function(err, resp) {15  if (err) {16    console.log(err);17  } else {18    console.log(ds(resp));19  }20});21var wptools = require('wptools');22var ds = require('wptools/lib/ds');23var article = wptools.page('Albert Einstein');24article.get(function(err, resp) {25  if (err) {26    console.log(err);27  } else {28    console.log(ds(resp));29  }30});31var wptools = require('wptools');32var ds = require('wptools/lib/ds');33var article = wptools.page('Albert Einstein');34article.get(function(err, resp) {35  if (err) {36    console.log(err);37  } else {38    console.log(ds(resp));39  }40});41var wptools = require('wptools');42var ds = require('wptools/lib/ds');43var article = wptools.page('Albert Einstein');44article.get(function(err, resp) {45  if (err) {46    console.log(err);47  } else {48    console.log(ds(resp));49  }50});51var wptools = require('wptools');52var ds = require('wptools/lib/ds');53var article = wptools.page('Albert Einstein');54article.get(function(err, resp) {55  if (err) {56    console.log(err);57  } else {58    console.log(ds(resp));59  }60});Using AI Code Generation
1var wptool = require('wptool');2var wptoolPath = 'C:\\wptool\\wptool.exe';3var ds = new wptool(wptoolPath);4ds.getDevices(function(err, devices) {5  console.log(devices);6});7var wptool = require('wptool');8var wptoolPath = 'C:\\wptool\\wptool.exe';9var ds = new wptool(wptoolPath);10ds.getDevices(function(err, devices) {11  console.log(devices);12});13var wptool = require('wptool');14var wptoolPath = 'C:\\wptool\\wptool.exe';15var ds = new wptool(wptoolPath);16ds.getDevices(function(err, devices) {17  console.log(devices);18});19var wptool = require('wptool');20var wptoolPath = 'C:\\wptool\\wptool.exe';21var ds = new wptool(wptoolPath);22ds.getDevices(function(err, devices) {23  console.log(devices);24});25var wptool = require('wptool');26var wptoolPath = 'C:\\wptool\\wptool.exe';27var ds = new wptool(wptoolPath);28ds.getDevices(function(err, devices) {29  console.log(devices);30});31var wptool = require('wptool');32var wptoolPath = 'C:\\wptool\\wptool.exe';33var ds = new wptool(wptoolPath);34ds.getDevices(function(err, devices) {35  console.log(devices);36});37var wptool = require('wptool');38var wptoolPath = 'C:\\wptool\\wptool.exe';39var ds = new wptool(wptoolPath);40ds.getDevices(function(err, devices) {Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
