_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q22000
getTableColumnStyle
train
function getTableColumnStyle(tableColumn, tableStyle) { var tableColumnStyle; if (defined(tableColumn) && defined(tableStyle.columns)) { if (defined(tableStyle.columns[tableColumn.id])) { tableColumnStyle = clone(tableStyle.columns[tableColumn.id]); } else { // Also support column indices as keys into tableStyle.columns var tableStructure = tableColumn.parent; var columnIndex = tableStructure.columns.indexOf(tableColumn); if (defined(tableStyle.columns[columnIndex])) { tableColumnStyle = clone(tableStyle.columns[columnIndex]); } } } if (!defined(tableColumnStyle)) { return tableStyle; } // Copy defaults from tableStyle too. for (var propertyName in tableStyle) { if ( tableStyle.hasOwnProperty(propertyName) && tableColumnStyle.hasOwnProperty(propertyName) ) { if (!defined(tableColumnStyle[propertyName])) { tableColumnStyle[propertyName] = tableStyle[propertyName]; } } } return tableColumnStyle; }
javascript
{ "resource": "" }
q22001
getFractionalValue
train
function getFractionalValue(legendHelper, value) { var extremes = getExtremes( legendHelper.tableColumn, legendHelper.tableColumnStyle ); var f = extremes.maximum === extremes.minimum ? 0 : (value - extremes.minimum) / (extremes.maximum - extremes.minimum); if (legendHelper.tableColumnStyle.clampDisplayValue) { f = Math.max(0.0, Math.min(1.0, f)); } return f; }
javascript
{ "resource": "" }
q22002
RegionDataValue
train
function RegionDataValue( regionCodes, columnHeadings, table, singleSelectValues ) { this.regionCodes = regionCodes; this.columnHeadings = columnHeadings; this.table = table; this.singleSelectValues = singleSelectValues; }
javascript
{ "resource": "" }
q22003
loadTableFromCsv
train
function loadTableFromCsv(item, csvString) { var tableStyle = item._tableStyle; var options = { idColumnNames: item.idColumns, isSampled: item.isSampled, initialTimeSource: item.initialTimeSource, displayDuration: tableStyle.displayDuration, replaceWithNullValues: tableStyle.replaceWithNullValues, replaceWithZeroValues: tableStyle.replaceWithZeroValues, columnOptions: tableStyle.columns // may contain per-column replacements for these }; var tableStructure = new TableStructure(undefined, options); tableStructure.loadFromCsv(csvString); return item.initializeFromTableStructure(tableStructure); }
javascript
{ "resource": "" }
q22004
train
function(options) { if (!defined(options) || !defined(options.regionProvider)) { throw new DeveloperError("options.regionProvider is required."); } FunctionParameter.call(this, options); this._regionProvider = options.regionProvider; this.singleSelect = defaultValue(options.singleSelect, false); knockout.track(this, ["_regionProvider"]); }
javascript
{ "resource": "" }
q22005
recolorBillboard
train
function recolorBillboard(img, color) { var canvas = document.createElement("canvas"); canvas.width = img.width; canvas.height = img.height; // Copy the image contents to the canvas var context = canvas.getContext("2d"); context.drawImage(img, 0, 0); var image = context.getImageData(0, 0, canvas.width, canvas.height); var normClr = [color.red, color.green, color.blue, color.alpha]; var length = image.data.length; //pixel count * 4 for (var i = 0; i < length; i += 4) { for (var j = 0; j < 4; j++) { image.data[j + i] *= normClr[j]; } } context.putImageData(image, 0, 0); return canvas.toDataURL(); // return context.getImageData(0, 0, canvas.width, canvas.height); }
javascript
{ "resource": "" }
q22006
printWindow
train
function printWindow(windowToPrint) { const deferred = when.defer(); let printInProgressCount = 0; const timeout = setTimeout(function() { deferred.reject( new TerriaError({ title: "Error printing", message: "Printing did not start within 10 seconds. Maybe this web browser does not support printing?" }) ); }, 10000); function cancelTimeout() { clearTimeout(timeout); } function resolveIfZero() { if (printInProgressCount <= 0) { deferred.resolve(); } } if (windowToPrint.matchMedia) { windowToPrint.matchMedia("print").addListener(function(evt) { cancelTimeout(); if (evt.matches) { console.log("print media start"); ++printInProgressCount; } else { console.log("print media end"); --printInProgressCount; resolveIfZero(); } }); } windowToPrint.onbeforeprint = function() { cancelTimeout(); console.log("onbeforeprint"); ++printInProgressCount; }; windowToPrint.onafterprint = function() { cancelTimeout(); console.log("onafterprint"); --printInProgressCount; resolveIfZero(); }; // First try printing with execCommand, because, in IE11, `printWindow.print()` // prints the entire page instead of just the embedded iframe (if the window // is an iframe, anyway). const result = windowToPrint.document.execCommand("print", true, null); if (!result) { windowToPrint.print(); } return deferred.promise; }
javascript
{ "resource": "" }
q22007
train
function(options) { options = defaultValue(options, defaultValue.EMPTY_OBJECT); TableColumnStyle.call(this, options); /** * The name of the variable (column) to be used for region mapping. * @type {String} */ this.regionVariable = options.regionVariable; /** * The identifier of a region type, as used by RegionProviderList. * @type {String} */ this.regionType = options.regionType; /** * The name of the default variable (column) containing data to be used for scaling and coloring. * @type {String} */ this.dataVariable = options.dataVariable; /** * The column name or index to use as the time column. Defaults to the first one found. Pass null for none. * Pass an array of two, eg. [0, 1], to provide both start and end date columns. * @type {String|Integer|String[]|Integer[]|null} */ this.timeColumn = options.timeColumn; /** * The column name or index to use as the time column. Defaults to the first one found. Pass null for none. * Pass an array of two, eg. [0, 1], to provide both start and end date columns. * @type {String|Integer} */ this.xAxis = options.xAxis; /** * Column-specific styling, with the format { columnIdentifier1: tableColumnStyle1, columnIdentifier2: tableColumnStyle2, ... }, * where columnIdentifier is either the name or the column index (zero-based). * @type {Object} */ this.columns = objectToTableColumnStyle(options, []); // If any promises are created (thanks to colorPalette), they are lost here. }
javascript
{ "resource": "" }
q22008
prefilterAddresses
train
function prefilterAddresses(addressList) { var addressesPlusInd = { skipIndices: [], nullAddresses: 0, addresses: [] }; for (var i = 0; i < addressList.length; i++) { var address = addressList[i]; if (address === null) { addressesPlusInd.skipIndices.push(i); addressesPlusInd.nullAddresses++; continue; } if ( address.toLowerCase().indexOf("po box") !== -1 || address.toLowerCase().indexOf("post office box") !== -1 ) { addressesPlusInd.skipIndices.push(i); continue; } addressesPlusInd.addresses.push(address); } return addressesPlusInd; }
javascript
{ "resource": "" }
q22009
train
function( terria, tableStructure, tableStyle, name, isUpdating ) { this._guid = createGuid(); // Used internally to give features a globally unique id. this._name = name; this._isUpdating = isUpdating || false; this._hasFeaturePerRow = undefined; // If this changes, need to remove old features. this._changed = new CesiumEvent(); this._error = new CesiumEvent(); this._loading = new CesiumEvent(); this._entityCollection = new EntityCollection(this); this._entityCluster = new EntityCluster(); this._terria = terria; this._tableStructure = defined(tableStructure) ? tableStructure : new TableStructure(); if (defined(tableStyle) && !(tableStyle instanceof TableStyle)) { throw new DeveloperError("Please pass a TableStyle object."); } /** * Gets the TableStyle object showing how to style the data. * @memberof TableDataSource.prototype * @type {TableStyle} */ this.tableStyle = tableStyle; // Can be undefined. this._legendHelper = undefined; this._legendUrl = undefined; this._extent = undefined; this._rowObjects = undefined; // The most recent properties and descriptions are saved here. this._rowDescriptions = undefined; this.loadingData = false; // Track _tableStructure so that csvCatalogItem's concepts are maintained. // Track _legendUrl so that csvCatalogItem can update the legend if it changes. // Track _extent so that the TableCatalogItem's rectangle updates properly, which also feeds into catalog item's canZoomTo property. knockout.track(this, ["_tableStructure", "_legendUrl", "_extent"]); // Whenever the active item is changed, recalculate the legend and the display of all the entities. // This is triggered both on deactivation and on reactivation, ie. twice per change; it would be nicer to trigger once. knockout .getObservable(this._tableStructure, "activeItems") .subscribe(changedActiveItems.bind(null, this), this); }
javascript
{ "resource": "" }
q22010
hostInDomains
train
function hostInDomains(host, domains) { if (!defined(domains)) { return false; } host = host.toLowerCase(); for (var i = 0; i < domains.length; i++) { if (host.match("(^|\\.)" + domains[i] + "$")) { return true; } } return false; }
javascript
{ "resource": "" }
q22011
train
function(clock) { this.clock = clock; this._layerStack = []; knockout.track(this, ["_layerStack"]); /** * The highest time-series layer, or undefined if there are no time series layers. */ knockout.defineProperty(this, "topLayer", { get: function() { if (this._layerStack.length) { return this._layerStack[this._layerStack.length - 1]; } return undefined; } }); knockout.getObservable(this, "topLayer").subscribe(function(topLayer) { if (defined(topLayer)) { // If there's a top layer, make the clock track it. this.clock.setCatalogItem(this.topLayer); } else { // If there's no layers, stop the clock from running. this.clock.shouldAnimate = false; } }, this); }
javascript
{ "resource": "" }
q22012
triggerResize
train
function triggerResize() { try { window.dispatchEvent(new Event("resize")); } catch (e) { var evt = window.document.createEvent("UIEvents"); evt.initUIEvent("resize", true, false, window, 0); window.dispatchEvent(evt); } }
javascript
{ "resource": "" }
q22013
objectToLowercase
train
function objectToLowercase(obj) { var result = {}; for (var key in obj) { if (obj.hasOwnProperty(key)) { result[key.toLowerCase()] = obj[key]; } } return result; }
javascript
{ "resource": "" }
q22014
combineFilters
train
function combineFilters(filters) { var allFilters, returnFn; allFilters = filters .filter(function(filter) { return defined(filter); }) .reduce(function(filtersSoFar, thisFilter) { if (thisFilter._filterIndex) { // If a filter is an instance of this function just pull that filter's index into this one's. thisFilter._filterIndex.forEach( addToListUnique.bind(undefined, filtersSoFar) ); } else { // Otherwise add it. addToListUnique(filtersSoFar, thisFilter); } return filtersSoFar; }, []); returnFn = function() { var outerArgs = arguments; return !allFilters.some(function(filter) { return !filter.apply(this, outerArgs); }, this); }; returnFn._filterIndex = allFilters; return returnFn; }
javascript
{ "resource": "" }
q22015
propertyGetTimeValues
train
function propertyGetTimeValues(properties, currentTime) { // properties itself may be a time-varying "property" with a getValue function. // If not, check each of its properties for a getValue function; if it exists, use it to get the current value. if (!defined(properties)) { return; } var result = {}; if (typeof properties.getValue === "function") { return properties.getValue(currentTime); } for (var key in properties) { if (properties.hasOwnProperty(key)) { if (properties[key] && typeof properties[key].getValue === "function") { result[key] = properties[key].getValue(currentTime); } else { result[key] = properties[key]; } } } return result; }
javascript
{ "resource": "" }
q22016
gmlToGeoJson
train
function gmlToGeoJson(xml) { if (typeof xml === "string") { var parser = new DOMParser(); xml = parser.parseFromString(xml, "text/xml"); } var result = []; var featureCollection = xml.documentElement; var featureMembers = featureCollection.getElementsByTagNameNS( gmlNamespace, "featureMember" ); for ( var featureIndex = 0; featureIndex < featureMembers.length; ++featureIndex ) { var featureMember = featureMembers[featureIndex]; var properties = {}; getGmlPropertiesRecursively(featureMember, properties); var feature = { type: "Feature", geometry: getGmlGeometry(featureMember), properties: properties }; if (defined(feature.geometry)) { result.push(feature); } } return { type: "FeatureCollection", crs: { type: "EPSG", properties: { code: "4326" } }, features: result }; }
javascript
{ "resource": "" }
q22017
gml2coord
train
function gml2coord(posList) { var pnts = posList.split(/[ ,]+/).filter(isNotEmpty); var coords = []; for (var i = 0; i < pnts.length; i += 2) { coords.push([parseFloat(pnts[i + 1]), parseFloat(pnts[i])]); } return coords; }
javascript
{ "resource": "" }
q22018
train
function(terria) { if (!defined(terria)) { throw new DeveloperError("terria is required"); } this._terria = terria; this._shareKeyIndex = {}; this._group = new CatalogGroup(terria); this._group.name = "Root Group"; this._group.preserveOrder = true; /** * Gets or sets a flag indicating whether the catalog is currently loading. * @type {Boolean} */ this.isLoading = false; this._chartableItems = []; knockout.track(this, ["isLoading", "_chartableItems"]); knockout.defineProperty(this, "userAddedDataGroup", { get: this.upsertCatalogGroup.bind( this, CatalogGroup, USER_ADDED_CATEGORY_NAME, "The group for data that was added by the user via the Add Data panel." ) }); /** * Array of the items that should be shown as a chart. */ knockout.defineProperty(this, "chartableItems", { get: function() { return this._chartableItems; } }); }
javascript
{ "resource": "" }
q22019
train
function(options) { options = defaultValue(options, defaultValue.EMPTY_OBJECT); /** * All data values less than or equal to this are considered equal for the purpose of display. * @type {Float} */ this.minDisplayValue = options.minDisplayValue; /** * Minimum y value to display in charts; if not specified, minimum data value will be used. * @type {Float} */ this.yAxisMin = options.yAxisMin; /** * Maximum y value to display in charts; if not specified, maximum data value will be used. * @type {Float} */ this.yAxisMax = options.yAxisMax; /** * All data values greater than or equal to this are considered equal for the purpose of display. * @type {Float} */ this.maxDisplayValue = options.maxDisplayValue; /** * Display duration for each row in the table, in minutes. If not provided, this is estimated from the data. * @type {Float} */ this.displayDuration = options.displayDuration; /** * Values to replace with zero, eg. ['-', null]. * @type {Array} */ this.replaceWithZeroValues = options.replaceWithZeroValues; /** * Values to replace with null, eg. ['na', 'NA']. * @type {Array} */ this.replaceWithNullValues = options.replaceWithNullValues; /** * The css string for the color with which to display null values. * @type {String} */ this.nullColor = options.nullColor; /** * The legend label for null values. * @type {String} */ this.nullLabel = options.nullLabel; /** * The size of each point or billboard. * @type {Float} */ this.scale = options.scale; /** * Should points and billboards representing each feature be scaled by the size of their data variable? * @type {Boolean} */ this.scaleByValue = options.scaleByValue; /** * Display values that fall outside the display range as min and max colors. * @type {Boolean} */ this.clampDisplayValue = options.clampDisplayValue; /** * A string representing an image to display at each point, for lat-long datasets. * @type {String} */ this.imageUrl = options.imageUrl; /** * An object of { "myCol": "My column" } properties, defining which columns get displayed in feature info boxes * (when clicked on), and what label is used instead of the column's actual name. * @type {Object} */ this.featureInfoFields = options.featureInfoFields; /** * Color for column (css string) * @type {String} */ this.chartLineColor = options.chartLineColor; /** * Either the number of discrete colours that a color gradient should be quantised into (ie. an integer), or * an array of values specifying the boundaries between the color bins. * @type {Integer|Number[]} */ this.colorBins = options.colorBins; /** * The method for quantising colors: * * For numeric columns: "auto" (default), "ckmeans", "quantile" or "none" (equivalent to colorBins: 0). * * For enumerated columns: "auto" (default), "top", or "cycle" * @type {String} */ this.colorBinMethod = defaultValue(options.colorBinMethod, "auto"); /** * Gets or sets a string or {@link ColorMap} array, specifying how to map values to colors. Setting this property sets * {@link TableColumnStyle#colorPalette} to undefined. If this property is a string, it specifies a list of CSS colors separated by hyphens (-), * and the colors are evenly spaced over the range of values. For example, "red-white-hsl(240,50%,50%)". * @memberOf TableColumnStyle.prototype * @type {String|Array} * @see TableColumnStyle#colorPalette */ if (defined(options.colorMap)) { this.colorMap = new ColorMap(options.colorMap); } else { this.colorMap = undefined; } /** * Gets or sets the [ColorBrewer](http://colorbrewer2.org/) palette to use when mapping values to colors. Setting this * property sets {@link TableColumnStyle#colorMap} to undefined. This property is ignored if {@link TableColumnStyle#colorMap} is defined. * @memberOf TableColumnStyle.prototype * @type {String} * @see TableColumnStyle#colorMap */ this.colorPalette = options.colorPalette; // Only need this here so that updateFromJson sees colorPalette as a property. if (defined(options.colorPalette)) { // Note the promise created here is lost. var that = this; ColorMap.loadFromPalette(this.colorPalette).then(function(colorMap) { that.colorMap = colorMap; }); } /** * How many horizontal ticks to draw on the generated color ramp legend, not counting the top or bottom. * @type {Integer} */ this.legendTicks = defaultValue(options.legendTicks, 3); /** * Display name for this column. * @type {String} */ this.name = options.name; /** * Display name for the legend for this column (defaults to the column name). * @type {String} */ this.legendName = options.legendName; /** * The variable type of this column. * Converts strings, which are case-insensitive keys of VarType, to numbers. See TableStructure for further information. * @type {String|Number} */ this.type = options.type; /** * The units of this column. * @type {String} */ this.units = options.units; /** * Is this column active? * @type {Boolean} */ this.active = options.active; /** * A format string for this column. For numbers, this is passed as options to toLocaleString. * See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString . * @type {String|Number} */ this.format = options.format; }
javascript
{ "resource": "" }
q22020
train
function(options) { options = defaultValue(options, defaultValue.EMPTY_OBJECT); Concept.call(this, options.name || options.id); /** * Gets or sets the name of the concept item. This property is observable. * @type {String} */ this.id = options.id; /** * Gets the list of absCodes contained in this group. This property is observable. * @type {AbsConcept[]} */ this.items = []; /** * Gets or sets a value indicating whether this concept item is currently open. When an * item is open, its child items (if any) are visible. This property is observable. * @type {Boolean} */ this.isOpen = true; /** * Flag to say if this if this node is selectable. This property is observable. * @type {Boolean} */ this.isSelectable = false; /** * Flag to say if this if this concept only allows more than one active child. (Defaults to false.) * @type {Boolean} */ this.allowMultiple = defaultValue(options.allowMultiple, false); if (defined(options.codes)) { var anyActive = buildConceptTree(this, options.filter, this, options.codes); // If no codes were made active via the 'filter' parameter, activate the first one. if (!anyActive && this.items.length > 0) { this.items[0].isActive = true; } } knockout.track(this, ["items", "isOpen"]); // name, isSelectable already tracked by Concept // Returns a flat array of all the active AbsCodes under this concept (walking the tree). // For this calculation, a concept may be active independently of its children. knockout.defineProperty(this, "activeItems", { get: function() { return getActiveChildren(this); } }); knockout.getObservable(this, "activeItems").subscribe(function(activeItems) { options.activeItemsChangedCallback(this, activeItems); }, this); }
javascript
{ "resource": "" }
q22021
buildConceptTree
train
function buildConceptTree(parent, filter, concept, codes) { // Use natural sort for fields with included ages or incomes. codes.sort(function(a, b) { return naturalSort( a.description.replace(",", ""), b.description.replace(",", "") ); }); var anyActive = false; for (var i = 0; i < codes.length; ++i) { var parentCode = parent instanceof AbsCode ? parent.code : ""; if (codes[i].parentCode === parentCode) { var absCode = new AbsCode(codes[i].code, codes[i].description, concept); var codeFilter = concept.id + "." + absCode.code; if (defined(filter) && filter.indexOf(codeFilter) !== -1) { absCode.isActive = true; anyActive = true; } if (parentCode === "" && codes.length < 50) { absCode.isOpen = true; } absCode.parent = parent; parent.items.push(absCode); var anyChildrenActive = buildConceptTree(absCode, filter, concept, codes); anyActive = anyChildrenActive || anyActive; } } return anyActive; }
javascript
{ "resource": "" }
q22022
loadConceptIdsAndConceptNameMap
train
function loadConceptIdsAndConceptNameMap(item) { if (!defined(item._loadConceptIdsAndNameMapPromise)) { var parameters = { method: "GetDatasetConcepts", datasetid: item.datasetId, format: "json" }; var datasetConceptsUrl = item._baseUrl + "?" + objectToQuery(parameters); var loadDatasetConceptsPromise = loadJson(datasetConceptsUrl) .then(function(json) { item._conceptIds = json.concepts; if ( json.concepts.indexOf(item.regionConcept) === -1 || json.concepts.indexOf("REGIONTYPE") === -1 ) { throw new DeveloperError( "datasetId " + item.datasetId + " concepts [" + json.concepts.join(", ") + '] do not include "' + item.regionConcept + '" and "REGIONTYPE".' ); } }) .otherwise(throwLoadError.bind(null, item, "GetDatasetConcepts")); var loadConceptNamesPromise = loadJson(item.conceptNamesUrl).then(function( json ) { item._conceptNamesMap = json; }); item._loadConceptIdsAndNameMapPromise = when.all([ loadConceptNamesPromise, loadDatasetConceptsPromise ]); // item.concepts and item.conceptNameMap are now defined with the results. } return item._loadConceptIdsAndNameMapPromise; }
javascript
{ "resource": "" }
q22023
loadConcepts
train
function loadConcepts(item) { if (!defined(item._loadConceptsPromise)) { var absConcepts = []; var promises = item._conceptIds .filter(function(conceptId) { return item.conceptsNotToLoad.indexOf(conceptId) === -1; }) .map(function(conceptId) { var parameters = { method: "GetCodeListValue", datasetid: item.datasetId, concept: conceptId, format: "json" }; var conceptCodesUrl = item._baseUrl + "?" + objectToQuery(parameters); return loadJson(conceptCodesUrl) .then(function(json) { // If this is a region type, only include valid region codes (eg. AUS, SA4, but not GCCSA). // Valid region codes must have a total population data file, eg. data/2011Census_TOT_SA4.csv var codes = json.codes; if (conceptId === item.regionTypeConcept) { codes = codes.filter(function(absCode) { return allowedRegionCodes.indexOf(absCode.code) >= 0; }); } // We have loaded the file, process it into an AbsConcept. var concept = new AbsConcept({ id: conceptId, codes: codes, filter: item.filter, allowMultiple: !( conceptId === item.regionTypeConcept || item.uniqueValuedConcepts.indexOf(conceptId) >= 0 ), activeItemsChangedCallback: function() { // Close any picked features, as the description of any associated with this catalog item may change. item.terria.pickedFeatures = undefined; rebuildData(item); } }); // Give the concept its human-readable name. concept.name = getHumanReadableConceptName( item._conceptNamesMap, concept ); absConcepts.push(concept); }) .otherwise(throwLoadError.bind(null, item, "GetCodeListValue")); }); item._loadConceptsPromise = when.all(promises).then(function() { // All the AbsConcept objects have been created, we just need to order them correctly and save them. // Put the region type concept first. var makeFirst = item.regionTypeConcept; absConcepts.sort(function(a, b) { return a.id === makeFirst ? -1 : b.id === makeFirst ? 1 : a.name > b.name ? 1 : -1; }); item._concepts = absConcepts; }); } return item._loadConceptsPromise; }
javascript
{ "resource": "" }
q22024
getHumanReadableConceptName
train
function getHumanReadableConceptName(conceptNameMap, concept) { if (!defined(conceptNameMap[concept.name])) { return concept.name; // Default to the name given in the file. } if (typeof conceptNameMap[concept.name] === "string") { return conceptNameMap[concept.name]; } else { var codeMap = conceptNameMap[concept.name]; for (var j = 0; j < concept.items.length; j++) { if (defined(codeMap[concept.items[j].name])) { return codeMap[concept.items[j].name]; } } // Use the wildcard, if defined, or else fall back to the name in the file. return codeMap["*"] || concept.name; } }
javascript
{ "resource": "" }
q22025
getActiveRegionTypeCode
train
function getActiveRegionTypeCode(item) { // We always put the region first, and at most one is active. var activeRegions = item._concepts[0].activeItems; if (activeRegions.length === 1) { return activeRegions[0].code; } }
javascript
{ "resource": "" }
q22026
loadDataFiles
train
function loadDataFiles(item) { // An array of arrays, indexed by activeItemsPerConcept[conceptIndex][codeIndex]. var activeCodesPerConcept = item._concepts.map(function(concept) { return concept.activeItems; }); // If any one of the concepts has no active selection, there will be no files to load. for (var i = activeCodesPerConcept.length - 1; i >= 0; i--) { if (activeCodesPerConcept[i].length === 0) { return when(); } } // If there is no valid region selected (including when there are two!), stop. if (!defined(getActiveRegionTypeCode(item))) { return when(); } // Find every possible combination, taking a single code from each concept. var activeCombinations = arrayProduct(activeCodesPerConcept); // Construct the 'and' part of the requests by combining concept.id and the AbsCode.name, // eg. and=REGIONTYPE.SA4,AGE.A04,MEASURE.3 var andParameters = activeCombinations.map(function(codes) { return codes .map(function(code, index) { return code.concept.id + "." + code.code; }) .join(","); }); var loadDataPromises = andParameters.map(function(andParameter) { // Build a promise which resolves once this datafile has loaded (unless we have cached this promise already). // Note in the original there was different cacheing stuff... but not sure if it was being used? if (!defined(item._loadDataFilePromise[andParameter])) { var parameters = { method: "GetGenericData", datasetid: item.datasetId, and: andParameter, or: item.regionConcept, format: "csv" }; var url = item._baseUrl + "?" + objectToQuery(parameters); item._loadDataFilePromise[andParameter] = loadText(url).then( loadTableStructure.bind(undefined, item) ); } return item._loadDataFilePromise[andParameter]; }); var totalPopulationsUrl = item.regionPopulationsUrlPrefix + getActiveRegionTypeCode(item) + ".csv"; loadDataPromises.push( loadText(totalPopulationsUrl).then(loadTableStructure.bind(undefined, item)) ); return when.all(loadDataPromises).then(function(tableStructures) { return { tableStructures: tableStructures, activeCombinations: activeCombinations }; }); }
javascript
{ "resource": "" }
q22027
buildValueColumns
train
function buildValueColumns(item, tableStructures, activeCombinations) { // The tableStructures are from the raw data files, one per activeCombinations. return tableStructures.map(function(tableStructure, index) { var columnNames = tableStructure.getColumnNames(); // Check that the data is not blank, and that the column names are ["Time", "Value", "REGION" (or equivalent), "Description"] if (columnNames.length === 0) { throwLoadError(item, "GetGenericData"); } else if ( !arraysAreEqual(columnNames, [ "Time", "Value", item.regionConcept, "Description" ]) ) { throwDataColumnsError(item, columnNames); } var absCodes = activeCombinations[index]; // Pull out and clone the 'Value' column, and rename it to match all the codes except the region type, eg. Persons 0-4 years. var valueColumn = tableStructure.columns[columnNames.indexOf("Value")]; var valueName = absCodes .filter(function(absCode) { return absCode.concept.id !== item.regionTypeConcept; }) .map(function(absCode) { return absCode.name.trim(); }) .reverse() // It would be nice to specify a preferred order of codes here; reverse because "Persons 0-4 years" sounds better than "0-4 years Persons". .join(" "); valueColumn = new TableColumn( valueName, valueColumn.values, valueColumn.options ); return valueColumn; }); }
javascript
{ "resource": "" }
q22028
train
function(name, options) { options = defaultValue(options, defaultValue.EMPTY_OBJECT); DisplayVariablesConcept.call(this, name, { getColorCallback: options.getColorCallback, requireSomeActive: defaultValue(options.requireSomeActive, false) }); this.displayVariableTypes = defaultValue( options.displayVariableTypes, defaultDisplayVariableTypes ); this.shaveSeconds = defaultValue(options.shaveSeconds, defaultShaveSeconds); this.finalEndJulianDate = options.finalEndJulianDate; this.unallowedTypes = options.unallowedTypes; this.initialTimeSource = options.initialTimeSource; this.displayDuration = options.displayDuration; this.replaceWithNullValues = options.replaceWithNullValues; this.replaceWithZeroValues = options.replaceWithZeroValues; this.columnOptions = options.columnOptions; this.sourceFeature = options.sourceFeature; this.idColumnNames = options.idColumnNames; // Actually names, ids or indexes. this.isSampled = options.isSampled; /** * Gets or sets the active time column name, id or index. * If you pass an array of two such, eg. [0, 1], treats these as the start and end date column identifiers. * @type {String|Number|String[]|Number[]|undefined} */ this._activeTimeColumnNameIdOrIndex = undefined; // Track sourceFeature as it is shown on the NowViewing panel. // Track items so that charts can update live. (Already done by DisplayVariableConcept.) knockout.track(this, ["sourceFeature", "_activeTimeColumnNameIdOrIndex"]); /** * Gets the columnsByType for this structure, * an object whose keys are VarTypes, and whose values are arrays of TableColumn with matching type. * Only existing types are present (eg. columnsByType[VarType.ALT] may be undefined). * @memberOf TableStructure.prototype * @type {Object} */ knockout.defineProperty(this, "columnsByType", { get: function() { return getColumnsByType(this.items); } }); }
javascript
{ "resource": "" }
q22029
castToScalar
train
function castToScalar(value, state) { if (state.rowNum === 1) { // Don't cast column names return value; } else { var hasDot = /\./; var leadingZero = /^0[0-9]/; var numberWithThousands = /^[1-9]\d?\d?(,\d\d\d)+(\.\d+)?$/; if (numberWithThousands.test(value)) { value = value.replace(/,/g, ""); } if (isNaN(value)) { return value; } if (leadingZero.test(value)) { return value; } if (hasDot.test(value)) { return parseFloat(value); } var integer = parseInt(value, 10); if (isNaN(integer)) { return null; } return integer; } }
javascript
{ "resource": "" }
q22030
finishFromIndex
train
function finishFromIndex(timeColumn, index) { if (!defined(timeColumn.displayDuration)) { return timeColumn.finishJulianDates[index]; } else { return JulianDate.addMinutes( timeColumn.julianDates[index], timeColumn.displayDuration, endScratch ); } }
javascript
{ "resource": "" }
q22031
calculateAvailability
train
function calculateAvailability(timeColumn, index, endTime) { var startJulianDate = timeColumn.julianDates[index]; if (defined(startJulianDate)) { var finishJulianDate = finishFromIndex(timeColumn, index); return new TimeInterval({ start: timeColumn.julianDates[index], stop: finishJulianDate, isStopIncluded: JulianDate.equals(finishJulianDate, endTime), data: timeColumn.julianDates[index] // Stop overlapping intervals being collapsed into one interval unless they start at the same time }); } }
javascript
{ "resource": "" }
q22032
calculateTimeIntervals
train
function calculateTimeIntervals(timeColumn) { // First we find the last time for all of the data (this is an optomisation for the calculateAvailability operation. const endTime = timeColumn.values.reduce(function(latest, value, index) { const current = finishFromIndex(timeColumn, index); if ( !defined(latest) || (defined(current) && JulianDate.greaterThan(current, latest)) ) { return current; } return latest; }, finishFromIndex(timeColumn, 0)); return timeColumn.values.map(function(value, index) { return calculateAvailability(timeColumn, index, endTime); }); }
javascript
{ "resource": "" }
q22033
createClock
train
function createClock(timeColumn, tableStructure) { var availabilityCollection = new TimeIntervalCollection(); timeColumn._timeIntervals .filter(function(availability) { return defined(availability && availability.start); }) .forEach(function(availability) { availabilityCollection.addInterval(availability); }); if (!defined(timeColumn._clock)) { if ( availabilityCollection.length > 0 && !availabilityCollection.start.equals(Iso8601.MINIMUM_VALUE) ) { var startTime = availabilityCollection.start; var stopTime = availabilityCollection.stop; var totalSeconds = JulianDate.secondsDifference(stopTime, startTime); var multiplier = Math.round(totalSeconds / 120.0); if ( defined(tableStructure.idColumnNames) && tableStructure.idColumnNames.length > 0 ) { stopTime = timeColumn.julianDates.reduce((d1, d2) => JulianDate.greaterThan(d1, d2) ? d1 : d2 ); } var clock = new DataSourceClock(); clock.startTime = JulianDate.clone(startTime); clock.stopTime = JulianDate.clone(stopTime); clock.clockRange = ClockRange.LOOP_STOP; clock.multiplier = multiplier; clock.currentTime = JulianDate.clone(startTime); clock.clockStep = ClockStep.SYSTEM_CLOCK_MULTIPLIER; return clock; } } return timeColumn._clock; }
javascript
{ "resource": "" }
q22034
getIndexOfColumn
train
function getIndexOfColumn(tableStructure, column) { for (var i = 0; i < tableStructure.columns.length; i++) { if (tableStructure.columns[i] === column) { return i; } } }
javascript
{ "resource": "" }
q22035
getColumnWithNameOrId
train
function getColumnWithNameOrId(nameOrId, columns) { for (var i = 0; i < columns.length; i++) { if (columns[i].name === nameOrId || columns[i].id === nameOrId) { return columns[i]; } } }
javascript
{ "resource": "" }
q22036
getIdColumns
train
function getIdColumns(idColumnNames, columns) { if (!defined(idColumnNames)) { return []; } return idColumnNames.map(name => getColumnWithNameIdOrIndex(name, columns)); }
javascript
{ "resource": "" }
q22037
getIdMapping
train
function getIdMapping(idColumnNames, columns) { var idColumns = getIdColumns(idColumnNames, columns); if (idColumns.length === 0) { return {}; } return idColumns[0].values.reduce(function(result, value, rowNumber) { var idString = getIdStringForRowNumber(idColumns, rowNumber); if (!defined(result[idString])) { result[idString] = []; } result[idString].push(rowNumber); return result; }, {}); }
javascript
{ "resource": "" }
q22038
getSortedColumns
train
function getSortedColumns(tableStructure, sortColumn, compareFunction) { // With help from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort var mappedArray = sortColumn.julianDatesOrValues.map(function(value, i) { return { index: i, value: value }; }); if (!defined(compareFunction)) { if (sortColumn.type === VarType.TIME) { compareFunction = function(a, b) { if (defined(a) && defined(b)) { return JulianDate.compare(a, b); } return defined(a) ? -1 : defined(b) ? 1 : 0; // so that undefined > defined, ie. all undefined dates go to the end. }; } else { compareFunction = function(a, b) { return +(a > b) || +(a === b) - 1; }; } } mappedArray.sort(function(a, b) { return compareFunction(a.value, b.value); }); return tableStructure.columns.map(column => { var sortedValues = mappedArray.map(element => column.values[element.index]); return new TableColumn(column.name, sortedValues, column.getFullOptions()); }); }
javascript
{ "resource": "" }
q22039
getColumnOptions
train
function getColumnOptions(name, tableStructure, columnNumber) { var columnOptions = defaultValue.EMPTY_OBJECT; if (defined(tableStructure.columnOptions)) { columnOptions = defaultValue( tableStructure.columnOptions[name], defaultValue( tableStructure.columnOptions[columnNumber], defaultValue.EMPTY_OBJECT ) ); } var niceName = defaultValue(columnOptions.name, name); var type = getVarTypeFromString(columnOptions.type); var format = defaultValue(columnOptions.format, format); var displayDuration = defaultValue( columnOptions.displayDuration, tableStructure.displayDuration ); var replaceWithNullValues = defaultValue( columnOptions.replaceWithNullValues, tableStructure.replaceWithNullValues ); var replaceWithZeroValues = defaultValue( columnOptions.replaceWithZeroValues, tableStructure.replaceWithZeroValues ); var colOptions = { tableStructure: tableStructure, displayVariableTypes: tableStructure.displayVariableTypes, unallowedTypes: tableStructure.unallowedTypes, displayDuration: displayDuration, replaceWithNullValues: replaceWithNullValues, replaceWithZeroValues: replaceWithZeroValues, id: name, type: type, units: columnOptions.units, format: columnOptions.format, active: columnOptions.active, chartLineColor: columnOptions.chartLineColor, yAxisMin: columnOptions.yAxisMin, yAxisMax: columnOptions.yAxisMax }; return [niceName, colOptions]; }
javascript
{ "resource": "" }
q22040
areColumnsEqualLength
train
function areColumnsEqualLength(columns) { if (columns.length <= 1) { return true; } var firstLength = columns[0].values.length; var columnsWithTheSameLength = columns.slice(1).filter(function(column) { return column.values.length === firstLength; }); return columnsWithTheSameLength.length === columns.length - 1; }
javascript
{ "resource": "" }
q22041
train
function(name, options) { const that = this; name = defaultValue(name, "Display Variable"); options = defaultValue(options, defaultValue.EMPTY_OBJECT); VariableConcept.call(this, name, options); /** * Gets or sets a flag for whether more than one checkbox can be selected at a time. * Default false. * @type {Boolean} */ this.allowMultiple = defaultValue(options.allowMultiple, false); /** * Gets or sets a flag for whether at least one checkbox must be selected at all times. * Default false. * @type {Boolean} */ this.requireSomeActive = defaultValue(options.requireSomeActive, false); /** * Gets or sets a function with no arguments that returns a color for the VariableConcept. If undefined, no color is set (the default). * @type {Function} */ this.getColorCallback = options.getColorCallback; /** * Gets or sets the array of concepts contained in this group. * If options.items is present, each item's parent property is overridden with `this`. * @type {Concept[]} */ this.items = defaultValue(options.items, []); this.items.forEach(function(item) { item.parent = that; }); /** * Gets or sets a value indicating whether this concept item is currently open. When an * item is open, its child items (if any) are visible. Default true. * @type {Boolean} */ this.isOpen = defaultValue(options.isOpen, true); /** * Gets or sets a flag indicating whether this node is selectable. * @type {Boolean} */ this.isSelectable = defaultValue(options.isSelectable, false); /** * Gets or sets a list of child ids which cannot be selected at the same time as any other child. Defaults to []. * Only relevant with allowMultiple = true. * Eg. Suppose the child concepts have ids "10" for 10 year olds, etc, plus "ALL" for all ages, * "U21" and "21PLUS" for under and over 21 year olds. * Then by specifying ["ALL", "U21", "21PLUS"], when the user selects one of these values, any other values will be unselected. * And when the user selects any other value (eg. "10"), if any of these values were selected, they will be unselected. * @type {String[]} */ this.exclusiveChildIds = defaultValue(options.exclusiveChildIds, []); /** * Gets or sets a function which is called whenever a child item is successfully toggled. * Its sole argument is the toggled child item. * @type {Function} */ this.toggleActiveCallback = undefined; knockout.track(this, [ "items", "isOpen", "allowMultiple", "requireSomeActive" ]); /** * Gets an array of currently active/selected items. * @return {VariableConcept[]} Array of active/selected items. */ knockout.defineProperty(this, "activeItems", { get: function() { return this.items.filter(function(item) { return item.isActive; }); } }); }
javascript
{ "resource": "" }
q22042
getNestedNodes
train
function getNestedNodes(concept, condition) { if (condition(concept)) { return concept; } if (!concept.items) { return []; } return concept.items.map(child => getNestedNodes(child, condition)); }
javascript
{ "resource": "" }
q22043
train
function(options) { if (!defined(options) || !defined(options.regionProvider)) { throw new DeveloperError("options.regionProvider is required."); } FunctionParameter.call(this, options); this._regionProvider = options.regionProvider; }
javascript
{ "resource": "" }
q22044
setClockCurrentTime
train
function setClockCurrentTime(clock, initialTimeSource, stopTime) { if (!defined(clock)) { return; } // This is our default. Start at the nearest instant in time. var now = JulianDate.now(); _setTimeIfInRange(clock, now, stopTime); initialTimeSource = defaultValue(initialTimeSource, "present"); switch (initialTimeSource) { case "start": clock.currentTime = clock.startTime.clone(clock.currentTime); break; case "end": clock.currentTime = clock.stopTime.clone(clock.currentTime); break; case "present": // Set to present by default. break; default: // Note that if it's not an ISO8601 timestamp, it ends up being set to present. // Find out whether it's an ISO8601 timestamp. var timestamp; try { timestamp = JulianDate.fromIso8601(initialTimeSource); // Cesium no longer validates dates in the release build. // So convert to a JavaScript date as a cheesy means of checking if the date is valid. if (isNaN(JulianDate.toDate(timestamp))) { throw new Error("Invalid Date"); } } catch (e) { throw new TerriaError( "Invalid initialTimeSource specified in config file: " + initialTimeSource ); } if (defined(timestamp)) { _setTimeIfInRange(clock, timestamp); } } }
javascript
{ "resource": "" }
q22045
stripDuplicates
train
function stripDuplicates(results) { var i; var placeshash = {}; var stripped = []; for (i = 0; i < results.length; i++) { var lat = Number(results[i].location.split(",")[0]).toFixed(1); var lng = Number(results[i].location.split(",")[1]).toFixed(1); var hash = results[i].name + "_" + lat + " " + lng; if (!defined(placeshash[hash])) { placeshash[hash] = results[i]; stripped.push(results[i]); } } return stripped; }
javascript
{ "resource": "" }
q22046
train
function(options) { SearchProviderViewModel.call(this); options = defaultValue(options, defaultValue.EMPTY_OBJECT); this.terria = options.terria; var url = defaultValue( options.url, this.terria.configParameters.gnafSearchUrl ); this.name = NAME; this.gnafApi = defaultValue( options.gnafApi, new GnafApi(this.terria.corsProxy, url) ); this._geocodeInProgress = undefined; this.flightDurationSeconds = defaultValue(options.flightDurationSeconds, 1.5); }
javascript
{ "resource": "" }
q22047
getShareData
train
function getShareData(terria) { const initSources = terria.initSources.slice(); addUserAddedCatalog(terria, initSources); addSharedMembers(terria, initSources); addViewSettings(terria, initSources); addFeaturePicking(terria, initSources); addLocationMarker(terria, initSources); return { version: "0.0.05", initSources: initSources }; }
javascript
{ "resource": "" }
q22048
addUserAddedCatalog
train
function addUserAddedCatalog(terria, initSources) { const localDataFilterRemembering = rememberRejections( CatalogMember.itemFilters.noLocalData ); const userAddedCatalog = terria.catalog.serializeToJson({ itemFilter: combineFilters([ localDataFilterRemembering.filter, CatalogMember.itemFilters.userSuppliedOnly, function(item) { // If the parent has a URL then this item will just load from that, so don't bother serializing it. // Properties that change when an item is enabled like opacity will be included in the shared members // anyway. return !item.parent || !item.parent.url; } ]) }); // Add an init source with user-added catalog members. if (userAddedCatalog.length > 0) { initSources.push({ catalog: userAddedCatalog }); } return localDataFilterRemembering.rejections; }
javascript
{ "resource": "" }
q22049
addSharedMembers
train
function addSharedMembers(terria, initSources) { const catalogForSharing = flattenCatalog( terria.catalog.serializeToJson({ itemFilter: combineFilters([CatalogMember.itemFilters.noLocalData]), propertyFilter: combineFilters([ CatalogMember.propertyFilters.sharedOnly, function(property) { return property !== "name"; } ]) }) ) .filter(function(item) { return item.isEnabled || item.isOpen; }) .reduce(function(soFar, item) { soFar[item.id] = item; item.id = undefined; return soFar; }, {}); // Eliminate open groups without all ancestors open Object.keys(catalogForSharing).forEach(key => { const item = catalogForSharing[key]; const isGroupWithClosedParent = item.isOpen && item.parents.some(parentId => !catalogForSharing[parentId]); if (isGroupWithClosedParent) { catalogForSharing[key] = undefined; } }); if (Object.keys(catalogForSharing).length > 0) { initSources.push({ sharedCatalogMembers: catalogForSharing }); } }
javascript
{ "resource": "" }
q22050
addViewSettings
train
function addViewSettings(terria, initSources) { const cameraExtent = terria.currentViewer.getCurrentExtent(); // Add an init source with the camera position. const initialCamera = { west: CesiumMath.toDegrees(cameraExtent.west), south: CesiumMath.toDegrees(cameraExtent.south), east: CesiumMath.toDegrees(cameraExtent.east), north: CesiumMath.toDegrees(cameraExtent.north) }; if (defined(terria.cesium)) { const cesiumCamera = terria.cesium.scene.camera; initialCamera.position = cesiumCamera.positionWC; initialCamera.direction = cesiumCamera.directionWC; initialCamera.up = cesiumCamera.upWC; } const homeCamera = { west: CesiumMath.toDegrees(terria.homeView.rectangle.west), south: CesiumMath.toDegrees(terria.homeView.rectangle.south), east: CesiumMath.toDegrees(terria.homeView.rectangle.east), north: CesiumMath.toDegrees(terria.homeView.rectangle.north), position: terria.homeView.position, direction: terria.homeView.direction, up: terria.homeView.up }; const time = { dayNumber: terria.clock.currentTime.dayNumber, secondsOfDay: terria.clock.currentTime.secondsOfDay }; let viewerMode; switch (terria.viewerMode) { case ViewerMode.CesiumTerrain: viewerMode = "3d"; break; case ViewerMode.CesiumEllipsoid: viewerMode = "3dSmooth"; break; case ViewerMode.Leaflet: viewerMode = "2d"; break; } const terriaSettings = { initialCamera: initialCamera, homeCamera: homeCamera, baseMapName: terria.baseMap.name, viewerMode: viewerMode, currentTime: time }; if (terria.showSplitter) { terriaSettings.showSplitter = terria.showSplitter; terriaSettings.splitPosition = terria.splitPosition; } initSources.push(terriaSettings); }
javascript
{ "resource": "" }
q22051
addFeaturePicking
train
function addFeaturePicking(terria, initSources) { if ( defined(terria.pickedFeatures) && terria.pickedFeatures.features.length > 0 ) { const positionInRadians = Ellipsoid.WGS84.cartesianToCartographic( terria.pickedFeatures.pickPosition ); const pickedFeatures = { providerCoords: terria.pickedFeatures.providerCoords, pickCoords: { lat: CesiumMath.toDegrees(positionInRadians.latitude), lng: CesiumMath.toDegrees(positionInRadians.longitude), height: positionInRadians.height } }; if (defined(terria.selectedFeature)) { // Sometimes features have stable ids and sometimes they're randomly generated every time, so include both // id and name as a fallback. pickedFeatures.current = { name: terria.selectedFeature.name, hash: hashEntity(terria.selectedFeature, terria.clock) }; } // Remember the ids of vector features only, the raster ones we can reconstruct from providerCoords. pickedFeatures.entities = terria.pickedFeatures.features .filter(feature => !defined(feature.imageryLayer)) .map(entity => { return { name: entity.name, hash: hashEntity(entity, terria.clock) }; }); initSources.push({ pickedFeatures: pickedFeatures }); } }
javascript
{ "resource": "" }
q22052
addLocationMarker
train
function addLocationMarker(terria, initSources) { if (defined(terria.locationMarker)) { const position = terria.locationMarker.entities.values[0].position.getValue(); const positionDegrees = Ellipsoid.WGS84.cartesianToCartographic(position); initSources.push({ locationMarker: { name: terria.locationMarker.entities.values[0].name, latitude: CesiumMath.toDegrees(positionDegrees.latitude), longitude: CesiumMath.toDegrees(positionDegrees.longitude) } }); } }
javascript
{ "resource": "" }
q22053
rememberRejections
train
function rememberRejections(filterFn) { const rejections = []; return { filter: function(item) { const allowed = filterFn(item); if (!allowed) { rejections.push(item); } return allowed; }, rejections: rejections }; }
javascript
{ "resource": "" }
q22054
getAncestors
train
function getAncestors(member) { var parent = member.parent; var ancestors = []; while (defined(parent) && defined(parent.parent)) { ancestors = [parent].concat(ancestors); parent = parent.parent; } return ancestors; }
javascript
{ "resource": "" }
q22055
getBetterFileName
train
function getBetterFileName(dataUrlType, itemName, format) { let name = itemName; const extension = "." + format; // Only add the extension if it's not already there. if (name.indexOf(extension) !== name.length - extension.length) { name = name + extension; } // For local files, the file already exists on the user's computer with the original name, so give it a modified name. if (dataUrlType === "local") { name = "processed " + name; } return name; }
javascript
{ "resource": "" }
q22056
applyReplacements
train
function applyReplacements(regionProvider, s, replacementsProp) { if (!defined(s)) { return undefined; } var r; if (typeof s === "number") { r = String(s); } else { r = s.toLowerCase().trim(); } var replacements = regionProvider[replacementsProp]; if (replacements === undefined || replacements.length === 0) { return r; } if (regionProvider._appliedReplacements[replacementsProp][r] !== undefined) { return regionProvider._appliedReplacements[replacementsProp][r]; } replacements.forEach(function(rep) { r = r.replace(rep[2], rep[1]); }); regionProvider._appliedReplacements[replacementsProp][s] = r; return r; }
javascript
{ "resource": "" }
q22057
findRegionIndex
train
function findRegionIndex(regionProvider, code, disambigCode) { if (!defined(code) || code === "") { // Note a code of 0 is ok return -1; } var processedCode = applyReplacements( regionProvider, code, "dataReplacements" ); var id = regionProvider._idIndex[processedCode]; if (!defined(id)) { // didn't find anything return -1; } else if (typeof id === "number") { // found an unambiguous match return id; } else { var ids = id; // found an ambiguous match if (!defined(disambigCode)) { // we have an ambiguous value, but nothing with which to disambiguate. We pick the first, warn. console.warn("Ambiguous value found in region mapping: " + processedCode); return ids[0]; } var processedDisambigCode = applyReplacements( regionProvider, disambigCode, "disambigDataReplacements" ); // Check out each of the matching IDs to see if the disambiguation field matches the one we have. for (var i = 0; i < ids.length; i++) { if ( regionProvider.regions[ids[i]][regionProvider.disambigProp] === processedDisambigCode ) { return ids[i]; } } } return -1; }
javascript
{ "resource": "" }
q22058
getSourceData
train
function getSourceData(node, children) { const sourceData = node.attribs["data"]; if (sourceData) { return sourceData; } if (Array.isArray(children) && children.length > 0) { return children[0]; } return children; }
javascript
{ "resource": "" }
q22059
tableStructureFromStringData
train
function tableStructureFromStringData(stringData) { // sourceData can be either json (starts with a '[') or csv format (contains a true line feed or '\n'; \n is replaced with a real linefeed). if (!defined(stringData) || stringData.length < 2) { return; } // We prevent ALT, LON and LAT from being chosen, since we know this is a non-geo csv already. const result = new TableStructure("chart", { unallowedTypes: [VarType.ALT, VarType.LAT, VarType.LON] }); if (stringData[0] === "[") { // Treat as json. const json = JSON.parse(stringData.replace(/&quot;/g, '"')); return TableStructure.fromJson(json, result); } if (stringData.indexOf("\\n") >= 0 || stringData.indexOf("\n") >= 0) { // Treat as csv. return TableStructure.fromCsv(stringData.replace(/\\n/g, "\n"), result); } }
javascript
{ "resource": "" }
q22060
readJson
train
function readJson(file) { return when( readText(file), function(result) { try { return JSON.parse(result); } catch (e) { if (e instanceof SyntaxError) { return json5.parse(result); } else { throw e; } } }, function(e) { throw e; } ); }
javascript
{ "resource": "" }
q22061
train
function(options) { FunctionParameter.call(this, options); this.regionParameter = options.regionParameter; this.value = ""; this._subtype = undefined; }
javascript
{ "resource": "" }
q22062
train
function( terria, viewState, fileOrUrl, dataType, confirmConversion ) { function tryConversionService(newItem) { if (terria.configParameters.conversionServiceBaseUrl === false) { // Don't allow conversion service. Duplicated in OgrCatalogItem.js terria.error.raiseEvent( new TerriaError({ title: "Unsupported file type", message: "This file format is not supported by " + terria.appName + ". Supported file formats include: " + '<ul><li>.geojson</li><li>.kml, .kmz</li><li>.csv (in <a href="https://github.com/TerriaJS/nationalmap/wiki/csv-geo-au">csv-geo-au format</a>)</li></ul>' }) ); return undefined; } else if ( name.match( /\.(shp|jpg|jpeg|pdf|xlsx|xls|tif|tiff|png|txt|doc|docx|xml|json)$/ ) ) { terria.error.raiseEvent( new TerriaError({ title: "Unsupported file type", message: "This file format is not supported by " + terria.appName + ". Directly supported file formats include: " + '<ul><li>.geojson</li><li>.kml, .kmz</li><li>.csv (in <a href="https://github.com/TerriaJS/nationalmap/wiki/csv-geo-au">csv-geo-au format</a>)</li></ul>' + "File formats supported through the online conversion service include: " + '<ul><li>Shapefile (.zip)</li><li>MapInfo TAB (.zip)</li><li>Possibly other <a href="http://www.gdal.org/ogr_formats.html">OGR Vector Formats</a></li></ul>' }) ); return undefined; } return getConfirmation( terria, viewState, confirmConversion, "This file is not directly supported by " + terria.appName + ".\n\n" + "Do you want to try uploading it to the " + terria.appName + " conversion service? This may work for " + "small, zipped Esri Shapefiles or MapInfo TAB files." ).then(function(confirmed) { return confirmed ? loadItem(new OgrCatalogItem(terria), name, fileOrUrl) : undefined; }); } var isUrl = typeof fileOrUrl === "string"; dataType = defaultValue(dataType, "auto"); var name = isUrl ? fileOrUrl : fileOrUrl.name; if (dataType === "auto") { return when(createCatalogItemFromUrl(name, terria, isUrl)).then(function( newItem ) { //##Doesn't work for file uploads if (!defined(newItem)) { return tryConversionService(); } else { // It's a file or service we support directly // In some cases (web services), the item will already have been loaded by this point. return loadItem(newItem, name, fileOrUrl); } }); } else if (dataType === "other") { // user explicitly chose "Other (use conversion service)" return getConfirmation( terria, viewState, confirmConversion, "Ready to upload your file to the " + terria.appName + " conversion service?" ).then(function(confirmed) { return confirmed ? loadItem(createCatalogMemberFromType("ogr", terria), name, fileOrUrl) : undefined; }); } else { // User has provided a type, so we go with that. return loadItem( createCatalogMemberFromType(dataType, terria), name, fileOrUrl ); } }
javascript
{ "resource": "" }
q22063
drawTick
train
function drawTick(y) { barGroup.appendChild( svgElement( legend, "line", { x1: legend.itemWidth, x2: legend.itemWidth + 5, y1: y, y2: y }, "tick-mark" ) ); }
javascript
{ "resource": "" }
q22064
train
function(code, name, concept) { Concept.call(this, name); /** * Gets or sets the value of the abs code. * @type {String} */ this.code = code; /** * Gets the list of abs codes contained in this group. This property is observable. * @type {AbsCode[]} */ this.items = []; /** * Gets or sets the parent for a code. This property is observable. * @type {AbsCode|AbsConcept} */ this.parent = undefined; /** * Gets or sets the ultimate parent concept for a code. This property is observable. * @type {AbsConcept} */ this.concept = concept; /** * Flag to say if this if this concept only allows more than one active child. * Defaults to the same as concept. * Only meaningful if this concept has an items array. * @type {Boolean} */ this.allowMultiple = this.concept.allowMultiple; /** * Gets or sets a value indicating whether this abs code is currently open. When an * item is open, its child items (if any) are visible. This property is observable. * @type {Boolean} */ this.isOpen = false; /** * Gets or sets a value indicating whether this abs code is currently active. When a * code is active, it is included in the abs data query. This property is observable. * @type {Boolean} */ this.isActive = false; /** * Flag to say if this is selectable. This property is observable. * @type {Boolean} */ this.isSelectable = true; //for ko knockout.track(this, ["code", "items", "isOpen", "isActive"]); }
javascript
{ "resource": "" }
q22065
disposeSubscription
train
function disposeSubscription(component) { if (defined(component.__observeModelChangeSubscriptions)) { for ( let i = 0; i < component.__observeModelChangeSubscriptions.length; ++i ) { component.__observeModelChangeSubscriptions[i].dispose(); } component.__observeModelChangeSubscriptions = undefined; } }
javascript
{ "resource": "" }
q22066
train
function(options) { FunctionParameter.call(this, options); this._regionProviderPromise = undefined; this._regionProviderList = undefined; this.validRegionTypes = options.validRegionTypes; // Track this so that defaultValue can update once regionProviderList is known. knockout.track(this, ["_regionProviderList"]); /** * Gets the default region provider if the user has not specified one. If region-mapped data * is loaded on the map, this property returns the {@link RegionProvider} of the topmost * region-mapped catalog item. Otherwise, it returns the first region provider. If the * parameter has not yet been loaded, this property returns undefined. * @memberof RegionTypeParameter.prototype * @type {RegionProvider} */ overrideProperty(this, "defaultValue", { get: function() { if (defined(this._defaultValue)) { return this._defaultValue; } const nowViewingItems = this.terria.nowViewing.items; if (nowViewingItems.length > 0) { for (let i = 0; i < nowViewingItems.length; ++i) { const item = nowViewingItems[i]; if ( defined(item.regionMapping) && defined(item.regionMapping.regionDetails) && item.regionMapping.regionDetails.length > 0 ) { return item.regionMapping.regionDetails[0].regionProvider; } } } if ( defined(this._regionProviderList) && this._regionProviderList.length > 0 ) { return this._regionProviderList[0]; } // No defaults available; have we requested the region providers yet? this.load(); return undefined; } }); }
javascript
{ "resource": "" }
q22067
train
function(terria) { this._terria = terria; this._eventSubscriptions = new EventHelper(); /** * Gets the list of items that we are "now viewing". It is recommended that you use * the methods on this instance instead of manipulating the list of items directly. * This property is observable. * @type {CatalogItem[]} */ this.items = []; knockout.track(this, ["items"]); this.showNowViewingRequested = new CesiumEvent(); this._eventSubscriptions.add( this.terria.beforeViewerChanged, function() { beforeViewerChanged(this); }, this ); this._eventSubscriptions.add( this.terria.afterViewerChanged, function() { afterViewerChanged(this); }, this ); }
javascript
{ "resource": "" }
q22068
parseCustomHtmlToReact
train
function parseCustomHtmlToReact(html, context) { if (!defined(html) || html.length === 0) { return html; } return htmlToReactParser.parseWithInstructions( html, isValidNode, getProcessingInstructions(context || {}) ); }
javascript
{ "resource": "" }
q22069
train
function(observations, seriesKey, dimIdx, attrIdx) { if (observations === undefined || observations === null) return; // process each observation in object. for (var key in observations) { // convert key from string to an array of numbers var obsDimIdx = key.split(KEY_SEPARATOR).map(Number); obsDimIdx.forEach(updateObsKey); var value = observations[key]; if (value === null) continue; results.push( iterator.call( context, // String of dimension id values e.g. 'M.FI.P.2000' obsKey.join(KEY_SEPARATOR), // Same as obsKey but without obs level dims seriesKey, // observation value value[0], // Array of dimension indices e.g. [ 0, 4, 5, 18 ] dimIdx.concat(obsDimIdx), // Array of attribute indices e.g. [ 1, 92, 27 ] attrIdx.concat(value.slice(1)), // Array of dimension objects allDims, // Array of attribute objects allAttrs ) ); } }
javascript
{ "resource": "" }
q22070
train
function(dvi, di) { var dim = msg.structure.dimensions.series[di]; var pos = dimPosition(dim); seriesKey[pos] = obsKey[pos] = dim.values[dvi].id; }
javascript
{ "resource": "" }
q22071
train
function(series) { if (series === undefined || series === null) return; for (var key in series) { // Convert key from string into array of numbers var serDimIdx = key.split(KEY_SEPARATOR).map(Number); // Update series and obs keys serDimIdx.forEach(updateSeriesAndObsKeys); var value = series[key]; var serAttrIdx = []; if (Array.isArray(value.attributes)) { serAttrIdx = value.attributes; } processObservations( value.observations, seriesKey.join(KEY_SEPARATOR), dsDimIdx.concat(serDimIdx), dsAttrIdx.concat(serAttrIdx) ); } }
javascript
{ "resource": "" }
q22072
train
function(c, i, array) { if (c === undefined || c === null) return; // c is the component, type is dimension|attribute, // level is dataset|series|observation, i is index, // array is the component array failed += !iterator.call(context, c, type, level, i, array); }
javascript
{ "resource": "" }
q22073
train
function(v, i) { if (v === undefined || v === null) return; failed += !iterator.call(context, v, type, level, i); }
javascript
{ "resource": "" }
q22074
updateFromJson
train
function updateFromJson(target, json, options) { options = defaultValue(options, defaultValue.EMPTY_OBJECT); var promises = []; for (var propertyName in target) { if ( target.hasOwnProperty(propertyName) && shouldBeUpdated(target, propertyName, json) ) { if (target.updaters && target.updaters[propertyName]) { promises.push( target.updaters[propertyName](target, json, propertyName, options) ); } else { target[propertyName] = json[propertyName]; } } } return when.all(promises); }
javascript
{ "resource": "" }
q22075
shouldBeUpdated
train
function shouldBeUpdated(target, propertyName, json) { return ( json[propertyName] !== undefined && // Must have a value to update to propertyName.length > 0 && // Must have a name to update propertyName[0] !== "_" && // Must not be a private property (propertyName !== "id" || !defined(target.id)) ); // Must not be overwriting 'id' }
javascript
{ "resource": "" }
q22076
removeCurrentTimeSubscription
train
function removeCurrentTimeSubscription(catalogItem) { if (defined(catalogItem._removeCurrentTimeChange)) { catalogItem._removeCurrentTimeChange(); catalogItem._removeCurrentTimeChange = undefined; } }
javascript
{ "resource": "" }
q22077
updateCurrentTime
train
function updateCurrentTime(catalogItem, updatedTime) { if (defined(catalogItem.clock)) { catalogItem.clock.currentTime = JulianDate.clone(updatedTime); } }
javascript
{ "resource": "" }
q22078
useOwnClockChanged
train
function useOwnClockChanged(catalogItem) { // If we are changing the state, copy the time from the clock that was in use to the clock that will be in use. if (catalogItem._lastUseOwnClock !== catalogItem.useOwnClock) { // Check that both clocks are defined before syncing the time (they may not both be defined during load due to construction order). if ( defined(catalogItem.clock) && defined(catalogItem.terria) && defined(catalogItem.terria.clock) && defined(catalogItem.terria.clock.currentTime) ) { if (catalogItem.useOwnClock) { // This is probably not needed, since we should be doing it on update, but just do this here explicitly // to be sure it is immediately current before we change. updateCurrentTime(catalogItem, catalogItem.terria.clock.currentTime); } else { catalogItem.terria.clock.currentTime = JulianDate.clone( catalogItem.clock.currentTime ); } catalogItem._lastUseOwnClock = catalogItem.useOwnClock; catalogItem.useClock(); } } }
javascript
{ "resource": "" }
q22079
describeWithoutUnderscores
train
function describeWithoutUnderscores(properties, nameProperty) { var html = ""; for (var key in properties) { if (properties.hasOwnProperty(key)) { if (key === nameProperty || simpleStyleIdentifiers.indexOf(key) !== -1) { continue; } var value = properties[key]; if (typeof value === "object") { value = describeWithoutUnderscores(value); } else { value = formatPropertyValue(value); } key = key.replace(/_/g, " "); if (defined(value)) { html += "<tr><th>" + key + "</th><td>" + value + "</td></tr>"; } } } if (html.length > 0) { html = '<table class="cesium-infoBox-defaultTable"><tbody>' + html + "</tbody></table>"; } return html; }
javascript
{ "resource": "" }
q22080
reprojectPointList
train
function reprojectPointList(pts, code) { if (!(pts[0] instanceof Array)) { return Reproject.reprojectPoint(pts, code, "EPSG:4326"); } var pts_out = []; for (var i = 0; i < pts.length; i++) { pts_out.push(Reproject.reprojectPoint(pts[i], code, "EPSG:4326")); } return pts_out; }
javascript
{ "resource": "" }
q22081
filterValue
train
function filterValue(obj, prop, func) { for (var p in obj) { if (obj.hasOwnProperty(p) === false) { continue; } else if (p === prop) { if (func && typeof func === "function") { func(obj, prop); } } else if (typeof obj[p] === "object") { filterValue(obj[p], prop, func); } } }
javascript
{ "resource": "" }
q22082
filterArray
train
function filterArray(pts, func) { if (!(pts[0] instanceof Array) || !(pts[0][0] instanceof Array)) { pts = func(pts); return pts; } var result = new Array(pts.length); for (var i = 0; i < pts.length; i++) { result[i] = filterArray(pts[i], func); //at array of arrays of points } return result; }
javascript
{ "resource": "" }
q22083
train
function(terria) { CatalogFunction.call(this, terria); this.url = undefined; this.name = "Spatial Detailing"; this.description = "Predicts the characteristics of fine-grained regions by learning and exploiting correlations of coarse-grained data with Census characteristics."; this._regionTypeToPredictParameter = new RegionTypeParameter({ terria: this.terria, catalogFunction: this, id: "regionTypeToPredict", name: "Region Type to Predict", description: "The type of region for which to predict characteristics." }); this._coarseDataRegionTypeParameter = new RegionTypeParameter({ terria: this.terria, catalogFunction: this, id: "coarseDataRegionType", name: "Coarse Data Region Type", description: "The type of region with which the coarse-grained input characteristics are associated." }); this._isMeanAggregationParameter = new BooleanParameter({ terria: this.terria, catalogFunction: this, id: "isMeanAggregation", name: "Aggregation", description: "Specifies how coarse region values were aggregated. True if the value is the mean of the values across the region, or False if the value is the sum of the values across the region.", trueName: "Mean Aggregation", trueDescription: "Coarse region values are the mean of samples in the region. For example, average household income.", falseName: "Sum Aggregation", falseDescription: "Coarse region values are the sum of samples in the region. For example, total population.", defaultValue: true }); this._dataParameter = new RegionDataParameter({ terria: this.terria, catalogFunction: this, id: "data", name: "Characteristic to Predict", description: "The characteristic to predict for each region.", regionProvider: this._coarseDataRegionTypeParameter, singleSelect: true }); this._parameters = [ this._coarseDataRegionTypeParameter, this._regionTypeToPredictParameter, this._isMeanAggregationParameter, this._dataParameter ]; }
javascript
{ "resource": "" }
q22084
findSelectedData
train
function findSelectedData(data, x) { // For each chart line (pointArray), find the point with the closest x to the mouse. const closestXPoints = data.map(line => line.points.reduce((previous, current) => Math.abs(current.x - x) < Math.abs(previous.x - x) ? current : previous ) ); // Of those, find one with the closest x to the mouse. const closestXPoint = closestXPoints.reduce((previous, current) => Math.abs(current.x - x) < Math.abs(previous.x - x) ? current : previous ); const nearlyEqualX = thisPoint => Math.abs(thisPoint.x - closestXPoint.x) < threshold; // Only select the chart lines (pointArrays) which have their closest x to the mouse = the overall closest. const selectedPoints = closestXPoints.filter(nearlyEqualX); const isSelectedArray = closestXPoints.map(nearlyEqualX); const selectedData = data.filter((line, i) => isSelectedArray[i]); selectedData.forEach((line, i) => { line.point = selectedPoints[i]; }); // TODO: this adds the property to the original data - bad. return selectedData; }
javascript
{ "resource": "" }
q22085
train
function(corsProxy, overrideUrl) { this.url = corsProxy.getURLProxyIfNecessary( defaultValue(overrideUrl, DATA61_GNAF_SEARCH_URL) ); this.bulk_url = corsProxy.getURLProxyIfNecessary( defaultValue(overrideUrl, DATA61_GNAF_BULK_SEARCH_URL) ); }
javascript
{ "resource": "" }
q22086
convertLuceneHit
train
function convertLuceneHit(locational, item) { var jsonInfo = JSON.parse(item.json); return { score: item.score, locational: locational, name: item.d61Address .slice(0, 3) .filter(function(string) { return string.length > 0; }) .join(", "), flatNumber: sanitiseAddressNumber(jsonInfo.flat.number), level: sanitiseAddressNumber(jsonInfo.level.number), numberFirst: sanitiseAddressNumber(jsonInfo.numberFirst.number), numberLast: sanitiseAddressNumber(jsonInfo.numberLast.number), street: jsonInfo.street, localityName: jsonInfo.localityName, localityVariantNames: jsonInfo.localityVariant.map(function(locality) { return locality.localityName; }), state: { abbreviation: jsonInfo.stateAbbreviation, name: jsonInfo.stateName }, postCode: jsonInfo.postcode, location: { latitude: jsonInfo.location.lat, longitude: jsonInfo.location.lon } }; }
javascript
{ "resource": "" }
q22087
buildRequestData
train
function buildRequestData(searchTerm, maxResults) { var requestData = { numHits: maxResults, fuzzy: { maxEdits: 2, minLength: 5, prefixLength: 2 } }; if (searchTerm instanceof Array) { requestData["addresses"] = searchTerm.map(processAddress); } else { requestData["addr"] = processAddress(searchTerm); } return requestData; }
javascript
{ "resource": "" }
q22088
addBoundingBox
train
function addBoundingBox(requestData, rectangle) { requestData["box"] = { minLat: CesiumMath.toDegrees(rectangle.south), maxLon: CesiumMath.toDegrees(rectangle.east), maxLat: CesiumMath.toDegrees(rectangle.north), minLon: CesiumMath.toDegrees(rectangle.west) }; }
javascript
{ "resource": "" }
q22089
splitIntoBatches
train
function splitIntoBatches(arrayToSplit, batchSize) { var arrayBatches = []; var minSlice = 0; var finish = false; for (var maxSlice = batchSize; maxSlice < Infinity; maxSlice += batchSize) { if (maxSlice >= arrayToSplit.length) { maxSlice = arrayToSplit.length; finish = true; } arrayBatches.push(arrayToSplit.slice(minSlice, maxSlice)); minSlice = maxSlice; if (finish) { break; } } return arrayBatches; }
javascript
{ "resource": "" }
q22090
supportsWebGL
train
function supportsWebGL() { if (defined(result)) { return result; } //Check for webgl support and if not, then fall back to leaflet if (!window.WebGLRenderingContext) { // Browser has no idea what WebGL is. Suggest they // get a new browser by presenting the user with link to // http://get.webgl.org result = false; return result; } var canvas = document.createElement("canvas"); var webglOptions = { alpha: false, stencil: false, failIfMajorPerformanceCaveat: true }; var gl = canvas.getContext("webgl", webglOptions) || canvas.getContext("experimental-webgl", webglOptions); if (!gl) { // We couldn't get a WebGL context without a major performance caveat. Let's see if we can get one at all. webglOptions.failIfMajorPerformanceCaveat = false; gl = canvas.getContext("webgl", webglOptions) || canvas.getContext("experimental-webgl", webglOptions); if (!gl) { // No WebGL at all. result = false; } else { // We can do WebGL, but only with software rendering (or similar). result = "slow"; } } else { // WebGL is good to go! result = true; } return result; }
javascript
{ "resource": "" }
q22091
getParentIds
train
function getParentIds(catalogMember, parentIds) { parentIds = defaultValue(parentIds, []); if (defined(catalogMember.parent)) { return getParentIds( catalogMember.parent, parentIds.concat([catalogMember.uniqueId]) ); } return parentIds; }
javascript
{ "resource": "" }
q22092
createDataSourceForLatLong
train
function createDataSourceForLatLong(item, tableStructure) { // Create the TableDataSource and save it to item._dataSource. item._dataSource = new TableDataSource( item.terria, tableStructure, item._tableStyle, item.name, item.polling.seconds > 0 ); item._dataSource.changedEvent.addEventListener( dataChanged.bind(null, item), item ); // Activate a column. This needed to wait until we had a dataSource, so it can trigger the legendHelper build. item.activateColumnFromTableStyle(); ensureActiveColumn(tableStructure, item._tableStyle); item.startPolling(); return when(true); // We're done - nothing to wait for. }
javascript
{ "resource": "" }
q22093
train
function(terria, map) { GlobeOrMap.call(this, terria); /** * Gets or sets the Leaflet {@link Map} instance. * @type {Map} */ this.map = map; this.scene = new LeafletScene(map); /** * Gets or sets whether this viewer _can_ show a splitter. * @type {Boolean} */ this.canShowSplitter = true; /** * Gets the {@link LeafletDataSourceDisplay} used to render a {@link DataSource}. * @type {LeafletDataSourceDisplay} */ this.dataSourceDisplay = undefined; this._tweens = new TweenCollection(); this._tweensAreRunning = false; this._selectionIndicatorTween = undefined; this._selectionIndicatorIsAppearing = undefined; this._pickedFeatures = undefined; this._selectionIndicator = L.marker([0, 0], { icon: L.divIcon({ className: "", html: '<img src="' + selectionIndicatorUrl + '" width="50" height="50" alt="" />', iconSize: L.point(50, 50) }), zIndexOffset: 1, // We increment the z index so that the selection marker appears above the item. interactive: false, keyboard: false }); this._selectionIndicator.addTo(this.map); this._selectionIndicatorDomElement = this._selectionIndicator._icon.children[0]; this._dragboxcompleted = false; this._pauseMapInteractionCount = 0; this.scene.featureClicked.addEventListener( featurePicked.bind(undefined, this) ); var that = this; // if we receive dragboxend (see LeafletDragBox) and we are currently // accepting a rectangle, then return the box as the picked feature map.on("dragboxend", function(e) { var mapInteractionModeStack = that.terria.mapInteractionModeStack; if ( defined(mapInteractionModeStack) && mapInteractionModeStack.length > 0 ) { if ( mapInteractionModeStack[mapInteractionModeStack.length - 1] .drawRectangle && defined(e.dragBoxBounds) ) { var b = e.dragBoxBounds; mapInteractionModeStack[ mapInteractionModeStack.length - 1 ].pickedFeatures = Rectangle.fromDegrees( b.getWest(), b.getSouth(), b.getEast(), b.getNorth() ); } } that._dragboxcompleted = true; }); map.on("click", function(e) { if (!that._dragboxcompleted && that.map.dragging.enabled()) { pickFeatures(that, e.latlng); } that._dragboxcompleted = false; }); this._selectedFeatureSubscription = knockout .getObservable(this.terria, "selectedFeature") .subscribe(function() { selectFeature(this); }, this); this._splitterPositionSubscription = knockout .getObservable(this.terria, "splitPosition") .subscribe(function() { this.updateAllItemsForSplitter(); }, this); this._showSplitterSubscription = knockout .getObservable(terria, "showSplitter") .subscribe(function() { this.updateAllItemsForSplitter(); }, this); map.on("layeradd", function(e) { that.updateAllItemsForSplitter(); }); map.on("move", function(e) { that.updateAllItemsForSplitter(); }); this._initProgressEvent(); selectFeature(this); }
javascript
{ "resource": "" }
q22094
updateOneLayer
train
function updateOneLayer(item, currZIndex) { if (defined(item.imageryLayer) && defined(item.imageryLayer.setZIndex)) { if (item.supportsReordering) { item.imageryLayer.setZIndex(currZIndex.reorderable++); } else { item.imageryLayer.setZIndex(currZIndex.fixed++); } } }
javascript
{ "resource": "" }
q22095
nextLayerFromIndex
train
function nextLayerFromIndex(index) { const imageryProvider = catalogItem.createImageryProvider( catalogItem.intervals.get(index).data ); imageryProvider.enablePickFeatures = false; catalogItem._nextLayer = ImageryLayerCatalogItem.enableLayer( catalogItem, imageryProvider, 0.0 ); updateSplitDirection(catalogItem); ImageryLayerCatalogItem.showLayer(catalogItem, catalogItem._nextLayer); }
javascript
{ "resource": "" }
q22096
addItem
train
function addItem(resource, rootCkanGroup, itemData, extras, parent) { var item = rootCkanGroup.terria.catalog.shareKeyIndex[ parent.uniqueId + "/" + resource.id ]; var alreadyExists = defined(item); if (!alreadyExists) { item = createItemFromResource( resource, rootCkanGroup, itemData, extras, parent ); if (item) { parent.add(item); } } return item; }
javascript
{ "resource": "" }
q22097
getEsriGeometry
train
function getEsriGeometry(featureData, geometryType, spatialReference) { if (defined(featureData.features)) { // This is a FeatureCollection. return { type: "FeatureCollection", crs: esriSpatialReferenceToCrs(featureData.spatialReference), features: featureData.features.map(function(subFeatureData) { return getEsriGeometry(subFeatureData, geometryType); }) }; } var geoJsonFeature = { type: "Feature", geometry: undefined, properties: featureData.attributes }; if (defined(spatialReference)) { geoJsonFeature.crs = esriSpatialReferenceToCrs(spatialReference); } if (geometryType === "esriGeometryPolygon") { // There are a bunch of differences between Esri polygons and GeoJSON polygons. // For GeoJSON, see https://tools.ietf.org/html/rfc7946#section-3.1.6. // For Esri, see http://resources.arcgis.com/en/help/arcgis-rest-api/#/Geometry_objects/02r3000000n1000000/ // In particular: // 1. Esri polygons can actually be multiple polygons by using multiple outer rings. GeoJSON polygons // can only have one outer ring and we need to use a MultiPolygon to represent multiple outer rings. // 2. In Esri which rings are outer rings and which are holes is determined by the winding order of the // rings. In GeoJSON, the first ring is the outer ring and subsequent rings are holes. // 3. In Esri polygons, clockwise rings are exterior, counter-clockwise are interior. In GeoJSON, the first // (exterior) ring is expected to be counter-clockwise, though lots of implementations probably don't // enforce this. The spec says, "For backwards compatibility, parsers SHOULD NOT reject // Polygons that do not follow the right-hand rule." // Group rings into outer rings and holes/ const outerRings = []; const holes = []; featureData.geometry.rings.forEach(function(ring) { if ( computeRingWindingOrder(ring.map(p => new Point(...p))) === WindingOrder.CLOCKWISE ) { outerRings.push(ring); } else { holes.push(ring); } // Reverse the coordinate order along the way due to #3 above. ring.reverse(); }); if (outerRings.length === 0 && holes.length > 0) { // Well, this is pretty weird. We have holes but not outer ring? // Most likely scenario is that someone messed up the winding order. // So let's treat all the holes as outer rings instead. holes.forEach(hole => { hole.reverse(); }); outerRings.push(...holes); holes.length = 0; } // If there's only one outer ring, we can use a `Polygon` and things are simple. if (outerRings.length === 1) { geoJsonFeature.geometry = { type: "Polygon", coordinates: [outerRings[0], ...holes] }; } else { // Multiple (or zero!) outer rings, so we need to use a multipolygon, and we need // to figure out which outer ring contains each hole. geoJsonFeature.geometry = { type: "MultiPolygon", coordinates: outerRings.map(ring => [ ring, ...findHolesInRing(ring, holes) ]) }; } } else if (geometryType === "esriGeometryPoint") { geoJsonFeature.geometry = { type: "Point", coordinates: [featureData.geometry.x, featureData.geometry.y] }; } else if (geometryType === "esriGeometryPolyline") { geoJsonFeature.geometry = { type: "MultiLineString", coordinates: featureData.geometry.paths }; } else { return undefined; } return geoJsonFeature; }
javascript
{ "resource": "" }
q22098
train
function( element, toolName, options, interactionTypes ) { // If interactionTypes was passed in via options if (interactionTypes === undefined && Array.isArray(options)) { interactionTypes = options; options = null; } const tool = getToolForElement(element, toolName); if (tool) { _resolveInputConflicts(element, tool, options, interactionTypes); // Iterate over specific interaction types and set active // This is used as a secondary check on active tools to find the active "parts" of the tool tool.supportedInteractionTypes.forEach(interactionType => { if ( interactionTypes === undefined || interactionTypes.includes(interactionType) ) { options[`is${interactionType}Active`] = true; } else { options[`is${interactionType}Active`] = false; } }); if ( globalConfiguration.state.showSVGCursors && tool.supportedInteractionTypes.includes('Mouse') ) { _setToolCursorIfPrimary(element, options, tool); } } // Resume normal behavior setToolModeForElement('active', null, element, toolName, options); }
javascript
{ "resource": "" }
q22099
_resolveGenericInputConflicts
train
function _resolveGenericInputConflicts( interactionType, tool, element, options ) { const interactionTypeFlag = `is${interactionType}Active`; const activeToolWithActiveInteractionType = store.state.tools.find( t => t.element === element && t.mode === 'active' && t.options[interactionTypeFlag] === true ); if (activeToolWithActiveInteractionType) { logger.log( "Setting tool %s's %s to false", activeToolWithActiveInteractionType.name, interactionTypeFlag ); activeToolWithActiveInteractionType.options[interactionTypeFlag] = false; } }
javascript
{ "resource": "" }