_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q46100
date_jsonSchema
train
function date_jsonSchema(name) { var result = simpleType_jsonSchema.call(this, name); result.type = 'string'; result.format = 'date-time'; return result; }
javascript
{ "resource": "" }
q46101
array_jsonSchema
train
function array_jsonSchema(name) { var result = {}; var itemName; itemName = 'itemOf_' + name; result.type = 'array'; if (this.options.required) result.__required = true; if (this.schema) { result.items = this.schema.jsonSchema(itemName); } else { result.items = this.caster.jsonSchema(itemName); } if (result.items.__required) { result.minItems = 1; } __processOptions(result, this.options); delete result.items.__required; return result; }
javascript
{ "resource": "" }
q46102
mixed_jsonSchema
train
function mixed_jsonSchema(name) { var result = __describe(name, this.options.type); __processOptions(result, this.options); return result; }
javascript
{ "resource": "" }
q46103
model_jsonSchema
train
function model_jsonSchema(fields, populate, readonly) { var jsonSchema = this.schema.jsonSchema(this.modelName); if (populate != null) { jsonSchema = __populate.call(this, jsonSchema, populate); }; __excludedPaths(this.schema, fields).forEach( __delPath.bind(null, jsonSchema) ); if (readonly) { __excludedReadonlyPaths(jsonSchema, readonly); } if (fields) __removeRequired(jsonSchema); return jsonSchema; }
javascript
{ "resource": "" }
q46104
query_jsonSchema
train
function query_jsonSchema() { let populate = this._mongooseOptions.populate; if (populate) { populate = Object.keys(populate).map(k => populate[k]); } let jsonSchema = this.model.jsonSchema( this._fields, populate ); delete jsonSchema.required; if (this.op.indexOf('findOne') === 0) return jsonSchema; delete jsonSchema.title; jsonSchema = { title: 'List of ' + plural(this.model.modelName), type: 'array', items: jsonSchema }; if (this.options.limit) { jsonSchema.maxItems = this.options.limit } return jsonSchema; }
javascript
{ "resource": "" }
q46105
callbackified
train
function callbackified() { var args = []; for (var i = 0; i < arguments.length; i++) { args.push(arguments[i]); } var maybeCb = args.pop(); if (typeof maybeCb !== 'function') { throw new TypeError('The last argument must be of type Function'); } var self = this; var cb = function() { return maybeCb.apply(self, arguments); }; // In true node style we process the callback on `nextTick` with all the // implications (stack, `uncaughtException`, `async_hooks`) original.apply(this, args) .then(function(ret) { process.nextTick(cb.bind(null, null, ret)) }, function(rej) { process.nextTick(callbackifyOnRejected.bind(null, rej, cb)) }); }
javascript
{ "resource": "" }
q46106
typeFromSchemaResponse
train
function typeFromSchemaResponse(schema, parseOptions) { var schemaType = avro.parse(schema); //check if the schema has been previouisly parsed and added to the registry if(typeof parseOptions.registry === 'object' && typeof parseOptions.registry[schemaType.name] !== 'undefined'){ return parseOptions.registry[schemaType.name]; } return avro.parse(schema, parseOptions); }
javascript
{ "resource": "" }
q46107
train
function() { var content = '', files = []; if (this.$element[0].files === undefined) { files[0] = { 'name' : this.$element[0] && this.$element[0].value }; } else { files = this.$element[0].files; } for (var i = 0; i < files.length; i++) { content += files[i].name.split("\\").pop() + ', '; } if (content !== '') { this.$elementFilestyle.find(':text').val(content.replace(/\, $/g, '')); } else { this.$elementFilestyle.find(':text').val(''); } return files; }
javascript
{ "resource": "" }
q46108
Edge
train
function Edge(current, next) { /** * @type {Object} */ this.current = current; /** * @type {Object} */ this.next = next; /** * @type {Object} */ this._inNormal = this.inwardsNormal(); /** * @type {Object} */ this._outNormal = this.outwardsNormal(); }
javascript
{ "resource": "" }
q46109
isPlatformModifierKeyOnly
train
function isPlatformModifierKeyOnly(event) { return !event.altKey && (olHas.MAC ? event.metaKey : event.ctrlKey) && !event.shiftKey; }
javascript
{ "resource": "" }
q46110
isShiftKeyOnly
train
function isShiftKeyOnly(event) { return ( !event.altKey && !(event.metaKey || event.ctrlKey) && event.shiftKey); }
javascript
{ "resource": "" }
q46111
messagePopoverComponent
train
function messagePopoverComponent() { return { restrict: 'A', scope: true, controller: 'NgeoPopoverController as popoverCtrl', link: (scope, elem, attrs, ngeoPopoverCtrl) => { if (!ngeoPopoverCtrl) { throw new Error('Missing ngeoPopoverCtrl'); } ngeoPopoverCtrl.anchorElm.on('inserted.bs.popover', () => { ngeoPopoverCtrl.bodyElm.show(); ngeoPopoverCtrl.shown = true; }); ngeoPopoverCtrl.anchorElm.popover({ container: 'body', html: true, content: ngeoPopoverCtrl.bodyElm, boundary: 'viewport', placement: attrs['ngeoPopoverPlacement'] || 'right' }); if (attrs['ngeoPopoverDismiss']) { $(attrs['ngeoPopoverDismiss']).on('scroll', () => { ngeoPopoverCtrl.dismissPopover(); }); } scope.$on('$destroy', () => { ngeoPopoverCtrl.anchorElm.popover('dispose'); ngeoPopoverCtrl.anchorElm.unbind('inserted.bs.popover'); ngeoPopoverCtrl.anchorElm.unbind('hidden.bs.popover'); }); } }; }
javascript
{ "resource": "" }
q46112
PopoverController
train
function PopoverController($scope) { /** * The state of the popover (displayed or not) * @type {boolean} */ this.shown = false; /** * @type {?JQuery} */ this.anchorElm = null; /** * @type {?JQuery} */ this.bodyElm = null; const clickHandler = (clickEvent) => { if (!this.anchorElm) { throw new Error('Missing anchorElm'); } if (!this.bodyElm) { throw new Error('Missing bodyElm'); } if (this.anchorElm[0] !== clickEvent.target && this.bodyElm.parent()[0] !== clickEvent.target && this.bodyElm.parent().find(clickEvent.target).length === 0 && this.shown) { this.dismissPopover(); } }; document.body.addEventListener('click', clickHandler); $scope.$on('$destroy', () => { document.body.removeEventListener('click', clickHandler); }); }
javascript
{ "resource": "" }
q46113
encodeNumber_
train
function encodeNumber_(num) { let encodedNumber = ''; while (num >= 0x20) { encodedNumber += CHAR64_.charAt( 0x20 | (num & 0x1f)); num >>= 5; } encodedNumber += CHAR64_.charAt(num); return encodedNumber; }
javascript
{ "resource": "" }
q46114
setStyleProperties_
train
function setStyleProperties_(text, feature) { const properties = getStyleProperties_(text, feature); const geometry = feature.getGeometry(); // Deal with legacy properties if (geometry instanceof olGeomPoint) { if (properties.isLabel || properties[ngeoFormatFeatureProperties.IS_TEXT]) { delete properties.strokeColor; delete properties.fillColor; } else { delete properties.fontColor; delete properties.fontSize; } } else { delete properties.fontColor; if (geometry instanceof olGeomLineString) { delete properties.fillColor; delete properties.fillOpacity; } } // Convert font size from px to pt if (properties.fontSize) { const fontSizeStr = /** @type {string} */(properties.fontSize); /** @type {number} */ let fontSize = parseFloat(fontSizeStr); if (fontSizeStr.indexOf('px') !== -1) { fontSize = Math.round(fontSize / 1.333333); } properties.fontSize = fontSize; } // Convert legacy properties const clone = {}; for (const key in properties) { const value = properties[key]; if (LegacyProperties_[key]) { clone[LegacyProperties_[key]] = value; } else { clone[key] = value; } } feature.setProperties(clone); }
javascript
{ "resource": "" }
q46115
castValue_
train
function castValue_(key, value) { const numProperties = [ ngeoFormatFeatureProperties.ANGLE, ngeoFormatFeatureProperties.OPACITY, ngeoFormatFeatureProperties.SIZE, ngeoFormatFeatureProperties.STROKE, 'pointRadius', 'strokeWidth' ]; const boolProperties = [ ngeoFormatFeatureProperties.IS_CIRCLE, ngeoFormatFeatureProperties.IS_RECTANGLE, ngeoFormatFeatureProperties.IS_TEXT, ngeoFormatFeatureProperties.SHOW_MEASURE, ngeoFormatFeatureProperties.SHOW_LABEL, 'isCircle', 'isRectangle', 'isLabel', 'showMeasure', 'showLabel' ]; if (numProperties.includes(key)) { return +value; } else if (boolProperties.includes(key)) { return (value === 'true') ? true : false; } else { return value; } }
javascript
{ "resource": "" }
q46116
getStyleProperties_
train
function getStyleProperties_(text, feature) { const parts = text.split('\''); /** @type {Object<string, boolean|number|string>} */ const properties = {}; for (let i = 0; i < parts.length; ++i) { const part = decodeURIComponent(parts[i]); const keyVal = part.split('*'); console.assert(keyVal.length === 2); const key = keyVal[0]; const val = keyVal[1]; properties[key] = castValue_(key, val); } return properties; }
javascript
{ "resource": "" }
q46117
mobileMeasureLenthComponent
train
function mobileMeasureLenthComponent(gmfMobileMeasureLengthTemplateUrl) { return { restrict: 'A', scope: { 'active': '=gmfMobileMeasurelengthActive', 'precision': '<?gmfMobileMeasurelengthPrecision', 'map': '=gmfMobileMeasurelengthMap', 'sketchStyle': '=?gmfMobileMeasurelengthSketchstyle' }, controller: 'GmfMobileMeasureLengthController as ctrl', bindToController: true, templateUrl: gmfMobileMeasureLengthTemplateUrl, /** * @param {angular.IScope} scope Scope. * @param {JQuery} element Element. * @param {angular.IAttributes} attrs Attributes. * @param {angular.IController=} controller Controller. */ link: (scope, element, attrs, controller) => { if (!controller) { throw new Error('Missing controller'); } controller.init(); } }; }
javascript
{ "resource": "" }
q46118
contextualDataComponent
train
function contextualDataComponent() { return { restrict: 'A', scope: false, controller: 'GmfContextualdataController as cdCtrl', bindToController: { 'map': '<gmfContextualdataMap', 'projections': '<gmfContextualdataProjections', 'callback': '<gmfContextualdataCallback' }, /** * @param {angular.IScope} scope Scope. * @param {JQuery} element Element. * @param {angular.IAttributes} attrs Attributes. * @param {angular.IController=} controller Controller. */ link: (scope, element, attrs, controller) => { if (!controller) { throw new Error('Missing controller'); } controller.init(); } }; }
javascript
{ "resource": "" }
q46119
messagePopopComponent
train
function messagePopopComponent(ngeoPopupTemplateUrl) { return { restrict: 'A', templateUrl: ngeoPopupTemplateUrl, /** * @param {angular.IScope} scope Scope. * @param {JQuery} element Element. * @param {angular.IAttributes} attrs Attributes. */ link: (scope, element, attrs) => { element.addClass('popover'); /** * @param {JQueryEventObject} evt Event. */ scope['close'] = function(evt) { if (evt) { evt.stopPropagation(); evt.preventDefault(); } element.addClass('hidden'); }; // Watch the open property scope.$watch('open', (newVal, oldVal) => { element.css('display', newVal ? 'block' : 'none'); }); } }; }
javascript
{ "resource": "" }
q46120
queryMapComponent
train
function queryMapComponent(ngeoMapQuerent, ngeoQueryKeyboard, $injector) { return { restrict: 'A', scope: false, link: (scope, elem, attrs) => { const map = scope.$eval(attrs['ngeoMapQueryMap']); /** @type {Array<import('ol/events.js').EventsKey>} */ const listenerKeys_ = []; /** * Called when the map is clicked while this controller is active. Issue * a request to the query service using the coordinate that was clicked. * @param {Event|import("ol/events/Event.js").default} evt The map browser event being fired. */ const handleMapClick_ = function(evt) { if (evt instanceof MapBrowserEvent) { const action = ngeoQueryKeyboard.action; const coordinate = evt.coordinate; ngeoMapQuerent.issue({ action, coordinate, map }); } }; /** * Called when the pointer is moved while this controller is active. * Change the mouse pointer when hovering a non-transparent pixel on the * map. * @param {Event|import("ol/events/Event.js").default} evt The map browser event being fired. */ const handlePointerMove_ = function(evt) { if (evt instanceof MapBrowserEvent && !evt.dragging) { const pixel = map.getEventPixel(evt.originalEvent); const queryable = function(layer) { const visible = layer.get('visible'); const sourceids = layer.get('querySourceIds'); return visible && !!sourceids; }; const hit = map.forEachLayerAtPixel(pixel, () => true, undefined, queryable); map.getTargetElement().style.cursor = hit ? 'pointer' : ''; } }; /** * Listen to the map events. */ const activate_ = function() { listenerKeys_.push( olEventsListen(map, 'singleclick', handleMapClick_) ); const queryOptions = /** @type {import('ngeo/query/MapQuerent.js').QueryOptions} */ ( $injector.has('ngeoQueryOptions') ? $injector.get('ngeoQueryOptions') : {} ); if (queryOptions.cursorHover) { listenerKeys_.push( olEventsListen(map, 'pointermove', handlePointerMove_) ); } }; /** * Unlisten the map events. */ const deactivate_ = function() { for (const lk of listenerKeys_) { olEventsUnlistenByKey(lk); } listenerKeys_.length = 0; if (scope.$eval(attrs['ngeoMapQueryAutoclear']) !== false) { ngeoMapQuerent.clear(); } }; // watch 'active' property -> activate/deactivate accordingly scope.$watch(attrs['ngeoMapQueryActive'], (newVal, oldVal) => { if (newVal) { activate_(); } else { deactivate_(); } } ); } }; }
javascript
{ "resource": "" }
q46121
train
function(evt) { if (evt instanceof MapBrowserEvent) { const action = ngeoQueryKeyboard.action; const coordinate = evt.coordinate; ngeoMapQuerent.issue({ action, coordinate, map }); } }
javascript
{ "resource": "" }
q46122
train
function(evt) { if (evt instanceof MapBrowserEvent && !evt.dragging) { const pixel = map.getEventPixel(evt.originalEvent); const queryable = function(layer) { const visible = layer.get('visible'); const sourceids = layer.get('querySourceIds'); return visible && !!sourceids; }; const hit = map.forEachLayerAtPixel(pixel, () => true, undefined, queryable); map.getTargetElement().style.cursor = hit ? 'pointer' : ''; } }
javascript
{ "resource": "" }
q46123
train
function() { listenerKeys_.push( olEventsListen(map, 'singleclick', handleMapClick_) ); const queryOptions = /** @type {import('ngeo/query/MapQuerent.js').QueryOptions} */ ( $injector.has('ngeoQueryOptions') ? $injector.get('ngeoQueryOptions') : {} ); if (queryOptions.cursorHover) { listenerKeys_.push( olEventsListen(map, 'pointermove', handlePointerMove_) ); } }
javascript
{ "resource": "" }
q46124
train
function() { for (const lk of listenerKeys_) { olEventsUnlistenByKey(lk); } listenerKeys_.length = 0; if (scope.$eval(attrs['ngeoMapQueryAutoclear']) !== false) { ngeoMapQuerent.clear(); } }
javascript
{ "resource": "" }
q46125
getQueryableLayersInfoFromThemes
train
function getQueryableLayersInfoFromThemes( themes, ogcServers ) { const queryableLayersInfo = []; let theme; let group; let nodes; for (let i = 0, ii = themes.length; i < ii; i++) { theme = /** @type {import('gmf/themes.js').GmfTheme} */ (themes[i]); for (let j = 0, jj = theme.children.length; j < jj; j++) { group = /** @type {import('gmf/themes.js').GmfGroup} */ (theme.children[j]); // Skip groups that don't have an ogcServer set if (!group.ogcServer) { continue; } nodes = []; getFlatNodes(group, nodes); for (let k = 0, kk = nodes.length; k < kk; k++) { const nodeGroup = /** @type {import('gmf/themes.js').GmfGroup} */ (nodes[k]); // Skip groups within groups if (nodeGroup.children && nodeGroup.children.length) { continue; } const nodeWMS = /** @type {import('gmf/themes.js').GmfLayerWMS} */ (nodes[k]); if (nodeWMS.childLayers && nodeWMS.childLayers[0] && nodeWMS.childLayers[0].queryable ) { queryableLayersInfo.push({ layerNode: nodeWMS, ogcServer: ogcServers[group.ogcServer] }); } } } } return queryableLayersInfo; }
javascript
{ "resource": "" }
q46126
datePickerComponent
train
function datePickerComponent(ngeoDatePickerTemplateUrl, $timeout) { return { scope: { onDateSelected: '&', time: '=' }, bindToController: true, controller: 'ngeoDatePickerController as datepickerCtrl', restrict: 'AE', templateUrl: ngeoDatePickerTemplateUrl, link: (scope, element, attrs, ctrl) => { if (!ctrl) { throw new Error('Missing ctrl'); } ctrl.init(); const lang = ctrl.gettextCatalog_.getCurrentLanguage(); $.datepicker.setDefaults($.datepicker.regional[lang]); ctrl.sdateOptions = angular.extend({}, ctrl.sdateOptions, { 'minDate': ctrl.initialMinDate, 'maxDate': ctrl.initialMaxDate, 'onClose': (selectedDate) => { if (selectedDate) { $(element[0]).find('input[name="edate"]').datepicker('option', 'minDate', selectedDate); } } }); ctrl.edateOptions = angular.extend({}, ctrl.edateOptions, { 'minDate': ctrl.initialMinDate, 'maxDate': ctrl.initialMaxDate, 'onClose': (selectedDate) => { if (selectedDate) { $(element[0]).find('input[name="sdate"]').datepicker('option', 'maxDate', selectedDate); } } }); angular.element('body').on('hidden.bs.popover', () => { const dp = angular.element('#ui-datepicker-div'); if (dp && dp.css('display') === 'block') { $(element[0]).find('input[name$="date"]').datepicker('hide'); } }); $timeout(() => { angular.element('#ui-datepicker-div').on('click', (e) => { e.stopPropagation(); }); }); } }; }
javascript
{ "resource": "" }
q46127
Controller
train
function Controller($scope, ngeoTime, gettextCatalog) { /** * @type {import("ngeo/misc/Time.js").Time} * @private */ this.ngeoTime_ = ngeoTime; /** * @type {?import('ngeo/datasource/OGC.js').TimeProperty} */ this.time = null; /** * The gettext catalog * @type {!angular.gettext.gettextCatalog} * @private */ this.gettextCatalog_ = gettextCatalog; /** * If the component is used to select a date range * @type {boolean} */ this.isModeRange = false; /** * Function called after date(s) changed/selected * @type {?function({time: {start: number, end: ?number}}): void} */ this.onDateSelected = null; /** * Initial min date for the datepicker * @type {?Date} */ this.initialMinDate = null; /** * Initial max date for the datepickeronDateSelected * @type {?Date} */ this.initialMaxDate = null; /** * Datepicker options for the second datepicker (only for range mode) * @type {Object} */ this.edateOptions = { 'changeMonth': true, 'changeYear': true }; /** * Datepicker options for the first datepicker * @type {Object} */ this.sdateOptions = { 'changeMonth': true, 'changeYear': true }; /** * Start date model for the first date picker * @type {?Date} */ this.sdate = null; /** * End date model for the second datepicker (only for range mode) * @type {?Date} */ this.edate = null; $scope.$watchGroup(['datepickerCtrl.sdate', 'datepickerCtrl.edate'], (newDates, oldDates) => { if (!this.onDateSelected) { throw new Error('Missing onDateSelected'); } const sDate = newDates[0]; const eDate = newDates[1]; if (angular.isDate(sDate) && (!this.isModeRange || angular.isDate(eDate))) { const start = this.ngeoTime_.getTime(sDate); const end = this.ngeoTime_.getTime(eDate); if (!start) { throw new Error('Missing start'); } this.onDateSelected({ time: { start, end, } }); } }); }
javascript
{ "resource": "" }
q46128
train
function(type, key, opt_childKey) { return ( /** * @param {Object} item * @return {any} */ function(item) { if (opt_childKey !== undefined) { item = item[opt_childKey]; } return item[key]; }); }
javascript
{ "resource": "" }
q46129
profileElevationComponent
train
function profileElevationComponent(ngeoDebounce) { return { restrict: 'A', /** * @param {angular.IScope} scope Scope. * @param {JQuery} element Element. * @param {angular.IAttributes} attrs Attributes. */ link: (scope, element, attrs) => { const optionsAttr = attrs['ngeoProfileOptions']; console.assert(optionsAttr !== undefined); const selection = d3select(element[0]); let profile, elevationData, poiData; scope.$watchCollection(optionsAttr, (newVal) => { /** @type {ProfileOptions} */ const options = Object.assign({}, newVal); if (options !== undefined) { // proxy the hoverCallback and outCallbackin order to be able to // call $applyAsync // // We're using $applyAsync here because the callback may be // called inside the Angular context. For example, it's the case // when the user hover's the line geometry on the map and the // profileHighlight property is changed. // // For that reason we use $applyAsync instead of $apply here. if (options.hoverCallback !== undefined) { const origHoverCallback = options.hoverCallback; options.hoverCallback = function(...args) { origHoverCallback(...args); scope.$applyAsync(); }; } if (options.outCallback !== undefined) { const origOutCallback = options.outCallback; options.outCallback = function() { origOutCallback(); scope.$applyAsync(); }; } profile = ngeoProfileD3Elevation(options); refreshData(); } }); scope.$watch(attrs['ngeoProfile'], (newVal, oldVal) => { elevationData = newVal; refreshData(); }); scope.$watch(attrs['ngeoProfilePois'], (newVal, oldVal) => { poiData = newVal; refreshData(); }); scope.$watch(attrs['ngeoProfileHighlight'], (newVal, oldVal) => { if (newVal === undefined) { return; } if (newVal > 0) { profile.highlight(newVal); } else { profile.clearHighlight(); } }); olEvents.listen(window, 'resize', ngeoDebounce(refreshData, 50, true)); /** * @param {Event|import("ol/events/Event.js").default=} evt Event */ function refreshData(evt) { if (profile !== undefined) { selection.datum(elevationData).call(profile); if (elevationData !== undefined) { profile.showPois(poiData); } } } } }; }
javascript
{ "resource": "" }
q46130
sortableComponent
train
function sortableComponent($timeout) { return { restrict: 'A', /** * @param {angular.IScope} scope Scope. * @param {JQuery} element Element. * @param {angular.IAttributes} attrs Attributes. */ link: (scope, element, attrs) => { const sortable = /** @type {Array} */ (scope.$eval(attrs['ngeoSortable'])) || []; console.assert(Array.isArray(sortable)); scope.$watchCollection(() => sortable, () => { sortable.length && $timeout(resetUpDragDrop, 0); }); const optionsObject = scope.$eval(attrs['ngeoSortableOptions']); const options = getOptions(optionsObject); const callbackFn = scope.$eval(attrs['ngeoSortableCallback']); const callbackCtx = scope.$eval(attrs['ngeoSortableCallbackCtx']); /** * This function resets drag&drop for the list. It is called each * time the sortable array changes (see $watchCollection above). */ function resetUpDragDrop() { // Add an index to the sortable to allow sorting of the // underlying data. const children = element.children(); for (let i = 0; i < children.length; ++i) { angular.element(children[i]).data('idx', i); } const sortableElement = $(element); // the element is already sortable; reset it. if (sortableElement.data('ui-sortable')) { sortableElement.off('sortupdate'); sortableElement.sortable('destroy'); } const sortableOptions = { 'axis': 'y', 'classes': { 'ui-sortable-helper': options['draggerClassName'] } }; // CSS class of the handle if (options['handleClassName']) { sortableOptions['handle'] = `.${options['handleClassName']}`; } // Placeholder for the item being dragged in the sortable list if (options['placeholderClassName']) { sortableOptions['placeholder'] = options['placeholderClassName']; sortableOptions['forcePlaceholderSize'] = true; } sortableElement.sortable(sortableOptions); // This event is triggered when the user stopped sorting and // the DOM position (i.e. order in the sortable list) has changed. sortableElement.on('sortupdate', (event, ui) => { const oldIndex = $(ui.item[0]).data('idx'); const newIndex = ui.item.index(); // Update (data)-index on dom element to its new position $(ui.item[0]).data('idx', newIndex); // Move dragged item to new position scope.$apply(() => { sortable.splice(newIndex, 0, sortable.splice(oldIndex, 1)[0]); }); // Call the callback function if it exists. if (callbackFn instanceof Function) { callbackFn.apply(callbackCtx, [element, sortable]); } }); } /** * @param {?} options Options after expression evaluation. * @return {!miscSortableOptions} Options object. * @private */ function getOptions(options) { let ret; const defaultHandleClassName = 'ngeo-sortable-handle'; if (options === undefined) { ret = {'handleClassName': defaultHandleClassName}; } else { if (options['handleClassName'] === undefined) { options['handleClassName'] = defaultHandleClassName; } ret = /** @type {miscSortableOptions} */ (options); } return ret; } } }; }
javascript
{ "resource": "" }
q46131
NumberFilter
train
function NumberFilter($locale) { const formats = $locale.NUMBER_FORMATS; /** * @param {number} number The number to format. * @param {number=} opt_precision The used precision, default is 3. * @return {string} The formatted string. */ const result = function(number, opt_precision) { const groupSep = formats.GROUP_SEP; const decimalSep = formats.DECIMAL_SEP; if (opt_precision === undefined) { opt_precision = 3; } if (number === Infinity) { return '\u221e'; } else if (number === -Infinity) { return '-\u221e'; } else if (number === 0) { // 0 will creates infinity values return '0'; } const sign = number < 0; number = Math.abs(number); const nb_decimal = opt_precision - Math.floor(Math.log(number) / Math.log(10)) - 1; const factor = Math.pow(10, nb_decimal); number = Math.round(number * factor); let decimal = ''; const unit = Math.floor(number / factor); if (nb_decimal > 0) { let str_number = `${number}`; // 0 padding while (str_number.length < nb_decimal) { str_number = `0${str_number}`; } decimal = str_number.substring(str_number.length - nb_decimal); while (decimal[decimal.length - 1] === '0') { decimal = decimal.substring(0, decimal.length - 1); } } const groups = []; let str_unit = `${unit}`; while (str_unit.length > 3) { const index = str_unit.length - 3; groups.unshift(str_unit.substring(index)); str_unit = str_unit.substring(0, index); } groups.unshift(str_unit); return (sign ? '-' : '') + groups.join(groupSep) + ( decimal.length === 0 ? '' : decimalSep + decimal ); }; return result; }
javascript
{ "resource": "" }
q46132
UnitPrefixFilter
train
function UnitPrefixFilter($filter) { const numberFilter = $filter('ngeoNumber'); const standardPrefix = ['', 'k', 'M', 'G', 'T', 'P']; const binaryPrefix = ['', 'Ki', 'Mi', 'Gi', 'Ti', 'Pi']; /** * @param {number} number The number to format. * @param {string=} opt_unit The unit to used, default is ''. * @param {string=} opt_type (unit|square|binary) the type of units, default is 'unit'. * @param {number=} opt_precision The used precision, default is 3. * @return {string} The formatted string. */ const result = function(number, opt_unit, opt_type, opt_precision) { if (opt_unit === undefined) { opt_unit = ''; } let divisor = 1000; let prefix = standardPrefix; if (opt_type === 'square') { divisor = 1000000; } else if (opt_type === 'binary') { divisor = 1024; prefix = binaryPrefix; } let index = 0; const index_max = prefix.length - 1; while (number >= divisor && index < index_max) { number = number / divisor; index++; } const postfix = prefix[index] + opt_unit; const space = postfix.length == 0 ? '' : '\u00a0'; return numberFilter(number, opt_precision) + space + postfix; }; return result; }
javascript
{ "resource": "" }
q46133
NumberCoordinatesFilter
train
function NumberCoordinatesFilter($filter) { /** * @param {import("ol/coordinate.js").Coordinate} coordinates Array of two numbers. * @param {(number|string)=} opt_fractionDigits Optional number of digit. * Default to 0. * @param {string=} opt_template Optional template. Default to '{x} {y}'. * Where "{x}" will be replaced by the easting coordinate and "{y}" by the * northing one. Note: Use a html entity to use the semicolon symbol * into a template. * @return {string} Number formatted coordinates. */ const filterFn = function(coordinates, opt_fractionDigits, opt_template) { const template = opt_template ? opt_template : '{x} {y}'; const x = coordinates[0]; const y = coordinates[1]; const fractionDigits = parseInt(/** @type {string} */(opt_fractionDigits), 10) | 0; const x_str = $filter('number')(x, fractionDigits); const y_str = $filter('number')(y, fractionDigits); return template.replace('{x}', x_str).replace('{y}', y_str); }; return filterFn; }
javascript
{ "resource": "" }
q46134
DMSCoordinatesFilter
train
function DMSCoordinatesFilter() { const degreesToStringHDMS = function(degrees, hemispheres, fractionDigits) { const normalizedDegrees = modulo(degrees + 180, 360) - 180; const dms = Math.abs(3600 * normalizedDegrees); const d = Math.floor(dms / 3600); const m = Math.floor((dms / 60) % 60); const s = (dms % 60); return `${d}\u00b0 ${ padNumber(m, 2)}\u2032 ${ padNumber(s, 2, fractionDigits)}\u2033 ${ hemispheres.charAt(normalizedDegrees < 0 ? 1 : 0)}`; }; /** * @param {import("ol/coordinate.js").Coordinate} coordinates Array of two numbers. * @param {(number|string)=} opt_fractionDigits Optional number of digit. * Default to 0. * @param {string=} opt_template Optional template. Default to * '{x} {y}'. Where "{x}" will be replaced by the easting * coordinate, {y} by the northing one. Note: Use a html entity to use the * semicolon symbol into a template. * @return {string} DMS formatted coordinates. */ const filterFn = function(coordinates, opt_fractionDigits, opt_template) { const fractionDigits = parseInt(/** @type {string} */(opt_fractionDigits), 10) | 0; const template = opt_template ? opt_template : '{x} {y}'; const xdms = degreesToStringHDMS(coordinates[0], 'EW', fractionDigits); const ydms = degreesToStringHDMS(coordinates[1], 'NS', fractionDigits); return template.replace('{x}', xdms).replace('{y}', ydms); }; return filterFn; }
javascript
{ "resource": "" }
q46135
trustHtmlAutoFilter
train
function trustHtmlAutoFilter($sce, ngeoStringToHtmlReplacements) { return function(input) { if (input !== undefined && input !== null) { if (typeof input === 'string') { for (const replacement of ngeoStringToHtmlReplacements) { if (input.match(replacement.expression)) { input = replacement.template.replace(/\$1/g, input); break; } } return $sce.trustAsHtml(`${input}`); } else { return $sce.trustAsHtml(`${input}`); } } else { return $sce.trustAsHtml('&nbsp;'); } }; }
javascript
{ "resource": "" }
q46136
DurationFilter
train
function DurationFilter(gettextCatalog) { // time unit enum const TimeUnits = Object.freeze({ SECONDS: Symbol('seconds'), MINUTES: Symbol('minutes'), HOURS: Symbol('hours'), DAYS: Symbol('days') }); /** * @param {number} amount Amount of time. * @param {symbol} unit Unit of time. * @return {string} formatted and translated string */ const pluralize = function(amount, unit) { let formattedUnit = ''; switch (unit) { case TimeUnits.SECONDS: formattedUnit = gettextCatalog.getPlural(amount, 'second', 'seconds'); break; case TimeUnits.MINUTES: formattedUnit = gettextCatalog.getPlural(amount, 'minute', 'minutes'); break; case TimeUnits.HOURS: formattedUnit = gettextCatalog.getPlural(amount, 'hour', 'hours'); break; case TimeUnits.DAYS: formattedUnit = gettextCatalog.getPlural(amount, 'day', 'days'); break; default: break; } return `${amount} ${formattedUnit}`; }; /** * @param {number} duration The duration in seconds. * @return {string} The formatted string. */ const result = function(duration) { // round to next integer duration = Math.round(duration); // just seconds let output; if (duration < 60) { return pluralize(duration, TimeUnits.SECONDS); } // minutes (+ seconds) let remainder = duration % 60; // seconds duration = Math.floor(duration / 60); // minutes if (duration < 60) { // less than an hour output = pluralize(duration, TimeUnits.MINUTES); if (remainder > 0) { output += ` ${pluralize(remainder, TimeUnits.SECONDS)}`; } return output; } // hours (+ minutes) remainder = duration % 60; // minutes duration = Math.floor(duration / 60); // hours if (duration < 24) { // less than a day output = pluralize(duration, TimeUnits.HOURS); if (remainder > 0) { output += ` ${pluralize(remainder, TimeUnits.MINUTES)}`; } return output; } // days (+ hours) remainder = duration % 24; // hours duration = Math.floor(duration / 24); // days output = pluralize(duration, TimeUnits.DAYS); if (remainder > 0) { output += ` ${pluralize(remainder, TimeUnits.HOURS)}`; } return output; }; return result; }
javascript
{ "resource": "" }
q46137
train
function(item) { if ('values' in item && layerName in item.values && item.values[layerName]) { return parseFloat(item.values[layerName]); } throw new Error('Unexpected'); }
javascript
{ "resource": "" }
q46138
rasterComponent
train
function rasterComponent() { return { restrict: 'A', controller: 'GmfElevationController as ctrl', bindToController: true, scope: { 'active': '<gmfElevationActive', 'elevation': '=gmfElevationElevation', 'layersconfig': '=gmfElevationLayersconfig', 'loading': '=?gmfElevationLoading', 'layer': '<gmfElevationLayer', 'map': '=gmfElevationMap' }, link: (scope, element, attr) => { const ctrl = scope['ctrl']; // Watch active or not. scope.$watch(() => ctrl.active, (active) => { ctrl.toggleActive_(active); }); // Watch current layer. scope.$watch(() => ctrl.layer, (layer) => { ctrl.layer = layer; ctrl.elevation = null; }); } }; }
javascript
{ "resource": "" }
q46139
factory
train
function factory() { /** * @param {string} content The file content. * @param {string} fileName The file name. * @param {string=} opt_fileType The file type. If not given, * `text/plain;charset=utf-8` is used. */ function download(content, fileName, opt_fileType) { // Safari does not properly work with FileSaver. Using the the type 'text/plain' // makes it a least possible to show the file content so that users can // do a manual download with "Save as". // See also: https://github.com/eligrey/FileSaver.js/issues/12 /** @type {string} */ const fileType = opt_fileType !== undefined && !isSafari() ? opt_fileType : 'text/plain;charset=utf-8'; const blob = new Blob([content], {type: fileType}); saveAs(blob, fileName); } return download; }
javascript
{ "resource": "" }
q46140
Controller
train
function Controller(ngeoWMSTime) { /** * @type {import("ngeo/misc/WMSTime.js").WMSTime} * @private */ this.ngeoWMSTime_ = ngeoWMSTime; /** * Function called after date(s) changed/selected * @type {Function} */ this.onDateSelected = () => undefined; /** * A time object for directive initialization * @type {?import('ngeo/datasource/OGC.js').TimeProperty} */ this.time = null; /** * If the component is used to select a date range * @type {boolean} */ this.isModeRange = false; /** * Minimal value of the slider (time in ms) * @type {number} */ this.minValue = -1; /** * Maximal value of the slider (time in ms) * @type {number} */ this.maxValue = 999999; /** * Used when WMS time object has a property 'values' instead of an interval * @type {?Array<number>} */ this.timeValueList = null; /** * Default Slider options (used by ui-slider directive) * @type {?{ * range : boolean, * min : number, * max : number * }} */ this.sliderOptions = null; /** * Model for the ui-slider directive (date in ms format) * @type {Array<number>|number} */ this.dates = []; }
javascript
{ "resource": "" }
q46141
colorPickerComponent
train
function colorPickerComponent(ngeoColorpickerTemplateUrl) { return { restrict: 'A', scope: { colors: '<?ngeoColorpicker', color: '=?ngeoColorpickerColor' }, controller: 'NgeoColorpickerController as ctrl', bindToController: true, templateUrl: ngeoColorpickerTemplateUrl }; }
javascript
{ "resource": "" }
q46142
mobileNavigationComponent
train
function mobileNavigationComponent() { return { restrict: 'A', controller: 'gmfMobileNavController as navCtrl', bindToController: true, scope: true, /** * @param {angular.IScope} scope Scope. * @param {JQuery} element Element. * @param {angular.IAttributes} attrs Attributes. * @param {angular.IController=} navCtrl Controller. */ link: (scope, element, attrs, navCtrl) => { if (!navCtrl) { throw new Error('Missing navCtrl'); } navCtrl.init(element); } }; }
javascript
{ "resource": "" }
q46143
mobileMeasureAreaComponent
train
function mobileMeasureAreaComponent(gmfMobileMeasureAreaTemplateUrl) { return { restrict: 'A', scope: { 'active': '=gmfMobileMeasureareaActive', 'precision': '<?gmfMobileMeasureareaPrecision', 'map': '=gmfMobileMeasureareaMap', 'sketchStyle': '=?gmfMobileMeasureareaSketchstyle' }, controller: 'GmfMobileMeasureAreaController as ctrl', bindToController: true, templateUrl: gmfMobileMeasureAreaTemplateUrl, /** * @param {angular.IScope} scope Scope. * @param {JQuery} element Element. * @param {angular.IAttributes} attrs Attributes. * @param {angular.IController=} controller Controller. */ link: (scope, element, attrs, controller) => { if (!controller) { throw new Error('Missing controller'); } controller.init(); } }; }
javascript
{ "resource": "" }
q46144
debounce
train
function debounce(func, wait, invokeApply, $timeout) { /** * @type {?angular.IPromise} */ let timeout = null; return /** @type {T} */( /** * @this {any} The context */ function(...args) { const context = this; const later = function() { timeout = null; func.apply(context, args); }; if (timeout !== null) { $timeout.cancel(timeout); } timeout = $timeout(later, wait, invokeApply); } ); }
javascript
{ "resource": "" }
q46145
factory
train
function factory($timeout) { /** @type {function(T, number, boolean, angular.ITimeoutService): T} */ const deb = debounce; return (func, wait, invokeApply) => { return deb(func, wait, invokeApply, $timeout); }; }
javascript
{ "resource": "" }
q46146
mapResizeComponent
train
function mapResizeComponent($window) { const /** @type {number} */ duration = 1000; return { restrict: 'A', /** * @param {angular.IScope} scope Scope. * @param {JQuery} element Element. * @param {angular.IAttributes} attrs Attributes. */ link: (scope, element, attrs) => { const attr = 'ngeoResizemap'; const prop = attrs[attr]; const map = scope.$eval(prop); console.assert(map instanceof olMap); const stateExpr = attrs['ngeoResizemapState']; console.assert(stateExpr !== undefined); let start; let animationDelayKey; const animationDelay = () => { map.updateSize(); map.renderSync(); if (Date.now() - start < duration) { animationDelayKey = $window.requestAnimationFrame(animationDelay); } }; // Make sure the map is resized when the animation ends. // It may help in case the animation didn't start correctly. element.on('transitionend', () => { map.updateSize(); map.renderSync(); }); scope.$watch(stateExpr, (newVal, oldVal) => { if (newVal != oldVal) { start = Date.now(); $window.cancelAnimationFrame(animationDelayKey); animationDelayKey = $window.requestAnimationFrame(animationDelay); } }); } }; }
javascript
{ "resource": "" }
q46147
LocationFactory
train
function LocationFactory($rootScope, $window) { const history = $window.history; const service = new StatemanagerLocation($window.location, $window.history); let lastUri = service.getUriString(); $rootScope.$watch(() => { const newUri = service.getUriString(); if (lastUri !== newUri) { $rootScope.$evalAsync(() => { lastUri = newUri; if (history !== undefined && history.replaceState !== undefined) { replaceState(history, newUri); } $rootScope.$broadcast('ngeoLocationChange'); }); } }); return service; }
javascript
{ "resource": "" }
q46148
toXY
train
function toXY(coordinates, nesting) { if (nesting === 0) { return /** @type {Array<T>} */(coordinatesToXY0(/** @type {Coordinate} */(coordinates))); } else { for (let i = 0, ii = coordinates.length; i < ii; i++) { // @ts-ignore: TypeScript is not able to do recurtion with deferent type in generic coordinates[i] = toXY(coordinates[i], nesting - 1); } } return coordinates; }
javascript
{ "resource": "" }
q46149
mapComponent
train
function mapComponent($window) { return { restrict: 'A', /** * @param {angular.IScope} scope Scope. * @param {JQuery} element Element. * @param {angular.IAttributes} attrs Attributes. */ link: (scope, element, attrs) => { // Get the 'ol.Map' object from attributes and manage it accordingly const attr = 'ngeoMap'; const prop = attrs[attr]; const map = scope.$eval(prop); console.assert(map instanceof olMap); map.setTarget(element[0]); // Get the 'window resize' attributes, which are optional. If defined, // the browser window 'resize' event is listened to update the size of // the map when fired. A transition option is also available to let any // animation that may occur on the div of the map to smootly resize the // map while in progress. const manageResizeAttr = 'ngeoMapManageResize'; const manageResizeProp = attrs[manageResizeAttr]; const manageResize = scope.$eval(manageResizeProp); if (manageResize) { const resizeTransitionAttr = 'ngeoMapResizeTransition'; const resizeTransitionProp = attrs[resizeTransitionAttr]; const resizeTransition = /** @type {number|undefined} */ ( scope.$eval(resizeTransitionProp)); olEvents.listen( $window, 'resize', () => { if (resizeTransition) { // Resize with transition const start = Date.now(); let loop = true; const adjustSize = function() { map.updateSize(); map.renderSync(); if (loop) { $window.requestAnimationFrame(adjustSize); } if (Date.now() - start > resizeTransition) { loop = false; } }; adjustSize(); } else { // A single plain resize map.updateSize(); } } ); } } }; }
javascript
{ "resource": "" }
q46150
handleEvent_
train
function handleEvent_(evt) { if (evt.type != 'pointermove' || evt.dragging) { return true; } const helpMsg = this.sketchFeature === null ? this.startMsg : this.continueMsg; if (!helpMsg) { throw new Error('Missing helpMsg'); } if (this.displayHelpTooltip_) { if (!this.helpTooltipElement_) { throw new Error('Missing helpTooltipElement'); } if (!this.helpTooltipOverlay_) { throw new Error('Missing helpTooltipOverlay'); } olDom.removeChildren(this.helpTooltipElement_); this.helpTooltipElement_.appendChild(helpMsg); this.helpTooltipOverlay_.setPosition(evt.coordinate); } return true; }
javascript
{ "resource": "" }
q46151
controlComponent
train
function controlComponent() { return { restrict: 'A', /** * @param {angular.IScope} scope Scope. * @param {JQuery} element Element. * @param {angular.IAttributes} attrs Attributes. */ link: (scope, element, attrs) => { const control = /** @type {import('ol/control/Control.js').default} */ (scope.$eval(attrs['ngeoControl'])); console.assert(control instanceof olControlControl); const map = /** @type {import('ol/Map.js').default} */ (scope.$eval(attrs['ngeoControlMap'])); console.assert(map instanceof olMap); control.setTarget(element[0]); map.addControl(control); } }; }
javascript
{ "resource": "" }
q46152
queryBboxComponent
train
function queryBboxComponent($rootScope, ngeoMapQuerent, ngeoQueryKeyboard) { return { restrict: 'A', scope: false, link: (scope, elem, attrs) => { /** * @type {import("ol/Map.js").default} */ const map = scope.$eval(attrs['ngeoBboxQueryMap']); let active; const interaction = new olInteractionDragBox({ condition: platformModifierKeyOnly, onBoxEnd: VOID }); /** * Called when a bbox is drawn while this controller is active. Issue * a request to the query service using the extent that was drawn. * @param {!olInteractionDragBox} interaction Drag box interaction */ const handleBoxEnd = function(interaction) { const action = ngeoQueryKeyboard.action; const extent = interaction.getGeometry().getExtent(); const limit = scope.$eval(attrs['ngeoBboxQueryLimit']); ngeoMapQuerent.issue({ action, extent, limit, map }); }; interaction.on('boxend', handleBoxEnd.bind(undefined, interaction)); // watch 'active' property -> activate/deactivate accordingly scope.$watch(attrs['ngeoBboxQueryActive'], (newVal, oldVal) => { active = newVal; if (newVal) { // activate map.addInteraction(interaction); } else { // deactivate map.removeInteraction(interaction); if (scope.$eval(attrs['ngeoBboxQueryAutoclear']) !== false) { ngeoMapQuerent.clear(); } } } ); // This second interaction is not given any condition and is // automatically added to the map while the user presses the // keys to either ADD or REMOVE const interactionWithoutCondition = new olInteractionDragBox({ onBoxEnd: VOID }); interactionWithoutCondition.on( 'boxend', handleBoxEnd.bind(undefined, interactionWithoutCondition)); let added = false; $rootScope.$watch( () => ngeoQueryKeyboard.action, (newVal, oldVal) => { // No need to do anything if directive is not active if (!active) { return; } if (newVal === ngeoQueryAction.REPLACE) { if (added) { map.removeInteraction(interactionWithoutCondition); added = false; } } else { if (!added) { map.addInteraction(interactionWithoutCondition); added = true; } } } ); } }; }
javascript
{ "resource": "" }
q46153
train
function(interaction) { const action = ngeoQueryKeyboard.action; const extent = interaction.getGeometry().getExtent(); const limit = scope.$eval(attrs['ngeoBboxQueryLimit']); ngeoMapQuerent.issue({ action, extent, limit, map }); }
javascript
{ "resource": "" }
q46154
ourAddresses
train
function ourAddresses (peerInfo) { const ourPeerId = peerInfo.id.toB58String() return peerInfo.multiaddrs.toArray() .reduce((ourAddrs, addr) => { const peerId = addr.getPeerId() addr = addr.toString() const otherAddr = peerId ? addr.slice(0, addr.lastIndexOf(`/ipfs/${peerId}`)) : `${addr}/ipfs/${ourPeerId}` return ourAddrs.concat([addr, otherAddr]) }, []) .filter(a => Boolean(a)) .concat(`/ipfs/${ourPeerId}`) }
javascript
{ "resource": "" }
q46155
getPeerInfo
train
function getPeerInfo (peer, peerBook) { let peerInfo // Already a PeerInfo instance, // add to the peer book and return the latest value if (PeerInfo.isPeerInfo(peer)) { return peerBook.put(peer) } // Attempt to convert from Multiaddr instance (not string) if (multiaddr.isMultiaddr(peer)) { const peerIdB58Str = peer.getPeerId() try { peerInfo = peerBook.get(peerIdB58Str) } catch (err) { peerInfo = new PeerInfo(PeerId.createFromB58String(peerIdB58Str)) } peerInfo.multiaddrs.add(peer) return peerInfo } // Attempt to convert from PeerId if (PeerId.isPeerId(peer)) { const peerIdB58Str = peer.toB58String() try { return peerBook.get(peerIdB58Str) } catch (err) { throw new Error(`Couldnt get PeerInfo for ${peerIdB58Str}`) } } throw new Error('peer type not recognized') }
javascript
{ "resource": "" }
q46156
connect
train
function connect (peerInfo, options, callback) { if (typeof options === 'function') { callback = options options = null } options = { useFSM: false, priority: PRIORITY_LOW, ...options } _dial({ peerInfo, protocol: null, options, callback }) }
javascript
{ "resource": "" }
q46157
dialFSM
train
function dialFSM (peerInfo, protocol, callback) { _dial({ peerInfo, protocol, options: { useFSM: true, priority: PRIORITY_HIGH }, callback }) }
javascript
{ "resource": "" }
q46158
VkontakteAuthorizationError
train
function VkontakteAuthorizationError(message, type, code, status) { Error.call(this); Error.captureStackTrace(this, arguments.callee); this.name = 'VkontakteAuthorizationError'; this.message = message; this.type = type; this.code = code || 'server_error'; this.status = status || 500; }
javascript
{ "resource": "" }
q46159
isMouseInFirstHalf
train
function isMouseInFirstHalf(event, targetNode, relativeToParent) { var mousePointer = horizontal ? (event.offsetX || event.layerX) : (event.offsetY || event.layerY); var targetSize = horizontal ? targetNode.offsetWidth : targetNode.offsetHeight; var targetPosition = horizontal ? targetNode.offsetLeft : targetNode.offsetTop; targetPosition = relativeToParent ? targetPosition : 0; return mousePointer < targetPosition + targetSize / 2; }
javascript
{ "resource": "" }
q46160
isDropAllowed
train
function isDropAllowed(event) { // Disallow drop from external source unless it's allowed explicitly. if (!dndDragTypeWorkaround.isDragging && !externalSources) return false; // Check mimetype. Usually we would use a custom drag type instead of Text, but IE doesn't // support that. if (!hasTextMimetype(event.dataTransfer.types)) return false; // Now check the dnd-allowed-types against the type of the incoming element. For drops from // external sources we don't know the type, so it will need to be checked via dnd-drop. if (attr.dndAllowedTypes && dndDragTypeWorkaround.isDragging) { var allowed = scope.$eval(attr.dndAllowedTypes); if (angular.isArray(allowed) && allowed.indexOf(dndDragTypeWorkaround.dragType) === -1) { return false; } } // Check whether droping is disabled completely if (attr.dndDisableIf && scope.$eval(attr.dndDisableIf)) return false; return true; }
javascript
{ "resource": "" }
q46161
hasTextMimetype
train
function hasTextMimetype(types) { if (!types) return true; for (var i = 0; i < types.length; i++) { if (types[i] === 'Text' || types[i] === 'text/plain') return true; } return false; }
javascript
{ "resource": "" }
q46162
getColor
train
function getColor(country) { if (!country || !country["region-code"]) { return "#FFF"; } var colors = continentProperties[country["region-code"]].colors; var index = country["alpha-3"].charCodeAt(0) % colors.length ; return colors[index]; }
javascript
{ "resource": "" }
q46163
train
function(collection, cb, ignoreCollection, cbName) { if (!ignoreCollection) { if (!lHlp.isDefined(collection) || !lHlp.isDefined(cb)) { return true; } } if (!lHlp.isFunction(cb)) { cbName = lHlp.defaultTo(cb, 'cb'); $log.error(errorHeader + cbName + ' is not a function'); return true; } return false; }
javascript
{ "resource": "" }
q46164
updateWidth
train
function updateWidth() { if (isNaN(attrs.width)) { element.css('width', attrs.width); } else { element.css('width', attrs.width + 'px'); } }
javascript
{ "resource": "" }
q46165
_set
train
function _set(obj, key, vORf) { obj && (obj[key] = _.is_fn(vORf) ? vORf(obj[key]) : vORf); }
javascript
{ "resource": "" }
q46166
train
function( popup, modify_a_href ) { var textbox = document.createElement('input'); textbox.placeholder = 'www.example.com'; if( modify_a_href ) textbox.value = modify_a_href.href; textbox.style.width = '20em'; textbox.style.maxWidth = parseInt(node_container.offsetWidth *2/3) + 'px'; textbox.autofocus = true; if( modify_a_href ) addEvent( textbox, 'input', function( e ) { var url = textbox.value.trim(); if( url ) modify_a_href.href = url; }); addEvent( textbox, 'keypress', function( e ) { var key = e.which || e.keyCode; if( key != 13 ) return; var url = textbox.value.trim(); if( modify_a_href ) ; else if( url ) { var url_scheme = url; if( ! /^[a-z0-9]+:\/\//.test(url) ) url_scheme = "http://" + url; if( commands.getSelectedHTML() ) commands.insertLink( url_scheme ); else { // Encode html entities - http://stackoverflow.com/questions/5499078/fastest-method-to-escape-html-tags-as-html-entities var htmlencode = function( text ) { return text.replace(/[&<>"]/g, function(tag) { var charsToReplace = { '&':'&amp;', '<':'&lt;', '>':'&gt;', '"':'&quot;' }; return charsToReplace[tag] || tag; }); } commands.insertHTML( '<a href="' + htmlencode(url_scheme) + '">' + htmlencode(url) + '</a>' ); } } commands.closePopup().collapseSelection(); node_contenteditable.focus(); }); popup.appendChild( textbox ); // set focus window.setTimeout( function() { textbox.focus(); add_class_focus(); }, 1 ); }
javascript
{ "resource": "" }
q46167
train
function( popup, left, top ) // left+top relative to container { // Test parents, el.getBoundingClientRect() does not work within 'position:fixed' var node = node_container, popup_parent = node.offsetParent; while( node ) { var node_style = getComputedStyle( node ); if( node_style['position'] != 'static' ) break; left += node.offsetLeft; top += node.offsetTop; popup_parent = node; node = node.offsetParent; } // Move popup as high as possible in the DOM tree popup_parent.appendChild( popup ); // Trim to viewport var rect = popup_parent.getBoundingClientRect(); var documentElement = document.documentElement; var viewport_width = Math.min( window.innerWidth, Math.max(documentElement.offsetWidth, documentElement.scrollWidth) ); var viewport_height = window.innerHeight; var popup_width = popup.offsetWidth; // accurate to integer var popup_height = popup.offsetHeight; if( rect.left + left < 1 ) left = 1 - rect.left; else if( rect.left + left + popup_width > viewport_width - 1 ) left = Math.max( 1 - rect.left, viewport_width - 1 - rect.left - popup_width ); if( rect.top + top < 1 ) top = 1 - rect.top; else if( rect.top + top + popup_height > viewport_height - 1 ) top = Math.max( 1 - rect.top, viewport_height - 1 - rect.top - popup_height ); // Set offset popup.style.left = parseInt(left) + 'px'; popup.style.top = parseInt(top) + 'px'; }
javascript
{ "resource": "" }
q46168
train
function( url, filename ) { var html = '<img id="wysiwyg-insert-image" src="" alt=""' + (filename ? ' title="'+html_encode(filename)+'"' : '') + '>'; wysiwygeditor.insertHTML( html ).closePopup().collapseSelection(); var $image = $('#wysiwyg-insert-image').removeAttr('id'); if( max_imagesize ) { $image.css({maxWidth: max_imagesize[0]+'px', maxHeight: max_imagesize[1]+'px'}) .load( function() { $image.css({maxWidth: '', maxHeight: ''}); // Resize $image to fit "clip-image" var image_width = $image.width(), image_height = $image.height(); if( image_width > max_imagesize[0] || image_height > max_imagesize[1] ) { if( (image_width/image_height) > (max_imagesize[0]/max_imagesize[1]) ) { image_height = parseInt(image_height / image_width * max_imagesize[0]); image_width = max_imagesize[0]; } else { image_width = parseInt(image_width / image_height * max_imagesize[1]); image_height = max_imagesize[1]; } $image.prop('width',image_width) .prop('height',image_height); } }); } $image.prop('src', url); }
javascript
{ "resource": "" }
q46169
train
function( file ) { // Only process image files if( typeof(filter_imageType) === 'function' && ! filter_imageType(file) ) return; else if( ! file.type.match(filter_imageType) ) return; var reader = new FileReader(); reader.onload = function(event) { var dataurl = event.target.result; insert_image_wysiwyg( dataurl, file.name ); }; // Read in the image file as a data URL reader.readAsDataURL( file ); }
javascript
{ "resource": "" }
q46170
train
function( url, html ) { url = $.trim(url||''); html = $.trim(html||''); var website_url = false; if( url.length && ! html.length ) website_url = url; else if( html.indexOf('<') == -1 && html.indexOf('>') == -1 && html.match(/^(?:https?:\/)?\/?(?:[^:\/\s]+)(?:(?:\/\w+)*\/)(?:[\w\-\.]+[^#?\s]+)(?:.*)?(?:#[\w\-]+)?$/) ) website_url = html; if( website_url && video_from_url ) html = video_from_url( website_url ) || ''; if( ! html.length && website_url ) html = '<video src="' + html_encode(website_url) + '">'; wysiwygeditor.insertHTML( html ).closePopup().collapseSelection(); }
javascript
{ "resource": "" }
q46171
train
function( button ) { var $element = $('<a/>').addClass( 'wysiwyg-toolbar-icon' ) .prop('href','#') .prop('unselectable','on') .append(button.image); // pass other properties as "prop()" $.each( button, function( name, value ) { switch( name ) { // classes case 'class': $element.addClass( value ); break; // special meaning case 'image': case 'html': case 'popup': case 'click': case 'showstatic': case 'showselection': break; default: // button.title, ... $element.attr( name, value ); break; } }); return $element; }
javascript
{ "resource": "" }
q46172
train
function() { var $toolbar = $('<div/>').addClass( 'wysiwyg-toolbar' ).addClass( toolbar_top ? 'wysiwyg-toolbar-top' : 'wysiwyg-toolbar-bottom' ); if( toolbar_focus ) $toolbar.hide().addClass( 'wysiwyg-toolbar-focus' ); // Add buttons to the toolbar add_buttons_to_toolbar( $toolbar, false, function() { // Open a popup from the toolbar var $popup = $(wysiwygeditor.openPopup()); // if wrong popup -> create a new one if( $popup.hasClass('wysiwyg-popup') && $popup.hasClass('wysiwyg-popuphover') ) $popup = $(wysiwygeditor.closePopup().openPopup()); if( ! $popup.hasClass('wysiwyg-popup') ) // add classes + content $popup.addClass( 'wysiwyg-popup' ); return $popup; }, function( $popup, target, overwrite_offset ) { // Popup position var $button = $(target); var popup_width = $popup.outerWidth(); // Point is the top/bottom-center of the button var left = $button.offset().left - $container.offset().left + parseInt($button.width() / 2) - parseInt(popup_width / 2); var top = $button.offset().top - $container.offset().top; if( toolbar_top ) top += $button.outerHeight(); else top -= $popup.outerHeight(); if( overwrite_offset ) { left = overwrite_offset.left; top = overwrite_offset.top; } popup_position( $popup, $container, left, top ); }); if( toolbar_top ) $container.prepend( $toolbar ); else $container.append( $toolbar ); }
javascript
{ "resource": "" }
q46173
isParent
train
function isParent(possibleParent, elem) { if(!elem || elem.nodeName === 'HTML') { return false; } if(elem.parentNode === possibleParent) { return true; } return isParent(possibleParent, elem.parentNode); }
javascript
{ "resource": "" }
q46174
insertBefore
train
function insertBefore(targetElement, targetScope) { // Ensure the placeholder is visible in the target (unless it's a table row) if (placeHolder.css('display') !== 'table-row') { placeHolder.css('display', 'block'); } if (!targetScope.sortableScope.options.clone) { targetElement[0].parentNode.insertBefore(placeHolder[0], targetElement[0]); dragItemInfo.moveTo(targetScope.sortableScope, targetScope.index()); } }
javascript
{ "resource": "" }
q46175
insertAfter
train
function insertAfter(targetElement, targetScope) { // Ensure the placeholder is visible in the target (unless it's a table row) if (placeHolder.css('display') !== 'table-row') { placeHolder.css('display', 'block'); } if (!targetScope.sortableScope.options.clone) { targetElement.after(placeHolder); dragItemInfo.moveTo(targetScope.sortableScope, targetScope.index() + 1); } }
javascript
{ "resource": "" }
q46176
fetchScope
train
function fetchScope(element) { var scope; while (!scope && element.length) { scope = element.data('_scope'); if (!scope) { element = element.parent(); } } return scope; }
javascript
{ "resource": "" }
q46177
rollbackDragChanges
train
function rollbackDragChanges() { if (!scope.itemScope.sortableScope.cloning) { placeElement.replaceWith(scope.itemScope.element); } placeHolder.remove(); dragElement.remove(); dragElement = null; dragHandled = false; containment.css('cursor', ''); containment.removeClass('as-sortable-un-selectable'); }
javascript
{ "resource": "" }
q46178
train
function (event) { var obj = event; if (event.targetTouches !== undefined) { obj = event.targetTouches.item(0); } else if (event.originalEvent !== undefined && event.originalEvent.targetTouches !== undefined) { obj = event.originalEvent.targetTouches.item(0); } return obj; }
javascript
{ "resource": "" }
q46179
train
function (event) { var touchInvalid = false; if (event.touches !== undefined && event.touches.length > 1) { touchInvalid = true; } else if (event.originalEvent !== undefined && event.originalEvent.touches !== undefined && event.originalEvent.touches.length > 1) { touchInvalid = true; } return touchInvalid; }
javascript
{ "resource": "" }
q46180
train
function (event, target, scrollableContainer) { var pos = {}; pos.offsetX = event.pageX - this.offset(target, scrollableContainer).left; pos.offsetY = event.pageY - this.offset(target, scrollableContainer).top; pos.startX = pos.lastX = event.pageX; pos.startY = pos.lastY = event.pageY; pos.nowX = pos.nowY = pos.distX = pos.distY = pos.dirAx = 0; pos.dirX = pos.dirY = pos.lastDirX = pos.lastDirY = pos.distAxX = pos.distAxY = 0; return pos; }
javascript
{ "resource": "" }
q46181
train
function (pos, event) { // mouse position last events pos.lastX = pos.nowX; pos.lastY = pos.nowY; // mouse position this events pos.nowX = event.pageX; pos.nowY = event.pageY; // distance mouse moved between events pos.distX = pos.nowX - pos.lastX; pos.distY = pos.nowY - pos.lastY; // direction mouse was moving pos.lastDirX = pos.dirX; pos.lastDirY = pos.dirY; // direction mouse is now moving (on both axis) pos.dirX = pos.distX === 0 ? 0 : pos.distX > 0 ? 1 : -1; pos.dirY = pos.distY === 0 ? 0 : pos.distY > 0 ? 1 : -1; // axis mouse is now moving on var newAx = Math.abs(pos.distX) > Math.abs(pos.distY) ? 1 : 0; // calc distance moved on this axis (and direction) if (pos.dirAx !== newAx) { pos.distAxX = 0; pos.distAxY = 0; } else { pos.distAxX += Math.abs(pos.distX); if (pos.dirX !== 0 && pos.dirX !== pos.lastDirX) { pos.distAxX = 0; } pos.distAxY += Math.abs(pos.distY); if (pos.dirY !== 0 && pos.dirY !== pos.lastDirY) { pos.distAxY = 0; } } pos.dirAx = newAx; }
javascript
{ "resource": "" }
q46182
train
function (event, element, pos, container, containerPositioning, scrollableContainer) { var bounds; var useRelative = (containerPositioning === 'relative'); element.x = event.pageX - pos.offsetX; element.y = event.pageY - pos.offsetY; if (container) { bounds = this.offset(container, scrollableContainer); if (useRelative) { // reduce positioning by bounds element.x -= bounds.left; element.y -= bounds.top; // reset bounds bounds.left = 0; bounds.top = 0; } if (element.x < bounds.left) { element.x = bounds.left; } else if (element.x >= bounds.width + bounds.left - this.offset(element).width) { element.x = bounds.width + bounds.left - this.offset(element).width; } if (element.y < bounds.top) { element.y = bounds.top; } else if (element.y >= bounds.height + bounds.top - this.offset(element).height) { element.y = bounds.height + bounds.top - this.offset(element).height; } } element.css({ 'left': element.x + 'px', 'top': element.y + 'px' }); this.calculatePosition(pos, event); }
javascript
{ "resource": "" }
q46183
train
function (item) { return { index: item.index(), parent: item.sortableScope, source: item, targetElement: null, targetElementOffset: null, sourceInfo: { index: item.index(), itemScope: item.itemScope, sortableScope: item.sortableScope }, canMove: function(itemPosition, targetElement, targetElementOffset) { // return true if targetElement has been changed since last call if (this.targetElement !== targetElement) { this.targetElement = targetElement; this.targetElementOffset = targetElementOffset; return true; } // return true if mouse is moving in the last moving direction of targetElement if (itemPosition.dirX * (targetElementOffset.left - this.targetElementOffset.left) > 0 || itemPosition.dirY * (targetElementOffset.top - this.targetElementOffset.top) > 0) { this.targetElementOffset = targetElementOffset; return true; } // return false otherwise return false; }, moveTo: function (parent, index) { // move the item to a new position this.parent = parent; // if the source item is in the same parent, the target index is after the source index and we're not cloning if (this.isSameParent() && this.source.index() < index && !this.sourceInfo.sortableScope.cloning) { index = index - 1; } this.index = index; }, isSameParent: function () { return this.parent.element === this.sourceInfo.sortableScope.element; }, isOrderChanged: function () { return this.index !== this.sourceInfo.index; }, eventArgs: function () { return { source: this.sourceInfo, dest: { index: this.index, sortableScope: this.parent } }; }, apply: function () { if (!this.sourceInfo.sortableScope.cloning) { // if not cloning, remove the item from the source model. this.sourceInfo.sortableScope.removeItem(this.sourceInfo.index); // if the dragged item is not already there, insert the item. This avoids ng-repeat dupes error if (this.parent.options.allowDuplicates || this.parent.modelValue.indexOf(this.source.modelValue) < 0) { this.parent.insertItem(this.index, this.source.modelValue); } } else if (!this.parent.options.clone) { // prevent drop inside sortables that specify options.clone = true // clone the model value as well this.parent.insertItem(this.index, angular.copy(this.source.modelValue)); } } }; }
javascript
{ "resource": "" }
q46184
train
function (el, selector) { el = el[0]; var matches = Element.matches || Element.prototype.mozMatchesSelector || Element.prototype.msMatchesSelector || Element.prototype.oMatchesSelector || Element.prototype.webkitMatchesSelector; while ((el = el.parentElement) && !matches.call(el, selector)) { } return el ? angular.element(el) : angular.element(document.body); }
javascript
{ "resource": "" }
q46185
printResultFor
train
function printResultFor(node, op) { return function printResult(err, res) { if (err) node.error(op + ' error: ' + err.toString()); if (res) node.log(op + ' status: ' + res.constructor.name); }; }
javascript
{ "resource": "" }
q46186
train
function(factor, animate, originLeft, originTop, callback) { let self = this self.zoomTo(self.__zoomLevel * factor, animate, originLeft, originTop, callback) }
javascript
{ "resource": "" }
q46187
train
function(event, element, elementType) { // code to be run when a click occurs if (elementType === 'new-todo-input') { if (event.keyCode === ENTER_KEY) { var todoTitle = (element.value).trim(); if (todoTitle.length) { var newTodoId = todosDB.add(todoTitle); context.broadcast('todoadded', { id: newTodoId }); // Clear input afterwards element.value = ''; } event.preventDefault(); event.stopPropagation(); } } }
javascript
{ "resource": "" }
q46188
nodeExec
train
function nodeExec(args) { args = arguments; // make linting happy var code = nodeCLI.exec.apply(nodeCLI, args).code; if (code !== 0) { exit(code); } }
javascript
{ "resource": "" }
q46189
getSourceDirectories
train
function getSourceDirectories() { var dirs = [ 'lib', 'src', 'app' ], result = []; dirs.forEach(function(dir) { if (test('-d', dir)) { result.push(dir); } }); return result; }
javascript
{ "resource": "" }
q46190
getVersionTags
train
function getVersionTags() { var tags = exec('git tag', { silent: true }).output.trim().split(/\n/g); return tags.reduce(function(list, tag) { if (semver.valid(tag)) { list.push(tag); } return list; }, []).sort(semver.compare); }
javascript
{ "resource": "" }
q46191
generateDistFiles
train
function generateDistFiles(config) { // Delete package.json from the cache since it can get updated by npm version delete require.cache[require.resolve('./package.json')]; var pkg = require('./package.json'), distFilename = DIST_DIR + config.name + '.js', minDistFilename = distFilename.replace(/\.js$/, '.min.js'), minDistSourcemapFilename = minDistFilename + '.map', distTestingFilename = DIST_DIR + config.name + '-testing' + '.js'; // Add copyrights and version info var versionComment = '/*! ' + config.name + ' v' + pkg.version + ' */\n', testingVersionComment = '/*! ' + config.name + '-testing v' + pkg.version + ' */\n', copyrightComment = cat('./config/copyright.txt'); // concatenate files together and add version/copyright notices (versionComment + copyrightComment + cat(config.files)).to(distFilename); (testingVersionComment + copyrightComment + cat(config.testingFiles)).to(distTestingFilename); // create minified version with source maps var result = uglifyjs.minify(distFilename, { output: { comments: /^!/ }, outSourceMap: path.basename(minDistSourcemapFilename) }); result.code.to(minDistFilename); result.map.to(minDistSourcemapFilename); // create filenames with version in them cp(distFilename, distFilename.replace('.js', '-' + pkg.version + '.js')); cp(minDistFilename, minDistFilename.replace('.min.js', '-' + pkg.version + '.min.js')); cp(distTestingFilename, distTestingFilename.replace('.js', '-' + pkg.version + '.js')); }
javascript
{ "resource": "" }
q46192
dist
train
function dist() { if (test('-d', DIST_DIR)) { rm('-r', DIST_DIR + '*'); } else { mkdir(DIST_DIR); } [{ name: DIST_NATIVE_NAME, files: SRC_NATIVE_FILES, testingFiles: TESTING_NATIVE_FILES }, { name: DIST_JQUERY_NAME, files: SRC_JQUERY_FILES, testingFiles: TESTING_JQUERY_FILES }, { name: DIST_NAME, files: SRC_NATIVE_FILES, testingFiles: TESTING_NATIVE_FILES }].forEach(function(config){ generateDistFiles(config); }); }
javascript
{ "resource": "" }
q46193
reset
train
function reset() { globalConfig = {}; modules = {}; services = {}; behaviors = {}; instances = {}; initialized = false; for (var i = 0; i < exports.length; i++) { delete application[exports[i]]; delete Box.Context.prototype[exports[i]]; } exports = []; }
javascript
{ "resource": "" }
q46194
callModuleMethod
train
function callModuleMethod(instance, method) { if (typeof instance[method] === 'function') { // Getting the rest of the parameters (the ones other than instance and method) instance[method].apply(instance, Array.prototype.slice.call(arguments, 2)); } }
javascript
{ "resource": "" }
q46195
bindEventType
train
function bindEventType(element, type, handlers) { function eventHandler(event) { var targetElement = getNearestTypeElement(event.target), elementType = targetElement ? targetElement.getAttribute('data-type') : ''; for (var i = 0; i < handlers.length; i++) { handlers[i](event, targetElement, elementType); } return true; } $(element).on(type, eventHandler); return eventHandler; }
javascript
{ "resource": "" }
q46196
train
function(root) { var me = this, $root = $(root); $root.find(MODULE_SELECTOR).each(function(idx, element) { me.start(element); }); }
javascript
{ "resource": "" }
q46197
train
function(config) { if (initialized) { error(new Error('Cannot set global configuration after application initialization')); return; } for (var prop in config) { if (config.hasOwnProperty(prop)) { globalConfig[prop] = config[prop]; } } }
javascript
{ "resource": "" }
q46198
train
function() { var baseUrl = context.getGlobal('location').pathname; routerService = context.getService('router'); routerService.init([ baseUrl, baseUrl + 'active', baseUrl + 'completed' ]); }
javascript
{ "resource": "" }
q46199
train
function(serviceName, application) { var serviceData = services[serviceName]; if (serviceData) { return services[serviceName].creator(application); } return null; }
javascript
{ "resource": "" }