Ejemplo n.º 1
0
 aggregates[method] = (data, field) => {
   let values = data.map(row => row[field]);
   if (isArray(values) && isArray(values[0])) {
     values = flattenDeep(values);
   }
   return simpleStatistics[method](values);
 };
Ejemplo n.º 2
0
function transform(dataView, options) {
  options = assign({}, DEFAULT_OPTIONS, options);

  const as = options.as;
  if (!isArray(as) || as.length !== 2) {
    throw new TypeError('Invalid as: must be an array with two strings!');
  }
  const xField = as[0];
  const yField = as[1];

  const fields = getFields(options);
  if (!isArray(fields) && fields.length !== 2) {
    throw new TypeError('Invalid fields: must be an array with two strings!');
  }
  const x = fields[0];
  const y = fields[1];

  const rows = dataView.rows;
  const data = rows.map(row => [ row[x], row[y] ]);
  const voronoi = d3Voronoi.voronoi();
  if (options.extend) {
    voronoi.extent(options.extend);
  }
  if (options.size) {
    voronoi.size(options.size);
  }
  const polygons = voronoi(data).polygons();
  rows.forEach((row, i) => {
    const polygon = polygons[i].filter(point => !!point); // some points are null
    row[xField] = polygon.map(point => point[0]);
    row[yField] = polygon.map(point => point[1]);
  });
}
Ejemplo n.º 3
0
  /**
   * judge if param 'item' selected
   *
   * @param {object} state - next state marked selected item or items
   * @param {object} coord - coordinate for seleted judging
   * @param {object} item - option object after uniformed
   * @param {number} i - index of option in options list
   * @memberof Select
   * */
  locateSelected(state, coord, item, i) {
    const { value, index } = coord;

    if (isArray(value) && value.indexOf(item.value) > -1) {
      // rerender 去重
      if (!state.sItems.find(selected => selected.value === item.value)) {
        state.sItems.push(item);
      }
    } else if (isArray(value) && value.length === 0) {
      // 多选重置
      state.sItem = {};
      state.sItems = [];
    } else if (typeof value === 'object' && isEqual(value, item.value)) {
      state.sItem = item;
    } else if (
      (typeof value !== 'undefined' &&
        typeof value !== 'object' &&
        `${item.value}` === `${value}`) ||
      (index !== 'undefined' && `${i}` === `${index}`)
    ) {
      state.sItem = item;
    } else if (!value && !index && value !== 0) {
      // github#406 修复option-value为假值数字0时的异常重置。
      // 单选重置
      state.sItem = {};
      state.sItems = [];
    }
  }
Ejemplo n.º 4
0
      var errorDomain = keys.reduce(function (prevErrorArr, k) {
        var errorValue = getValueByDataKey(entry, k, 0);
        var lowerValue = mainValue[0] - Math.abs(_isArray(errorValue) ? errorValue[0] : errorValue);
        var upperValue = mainValue[1] + Math.abs(_isArray(errorValue) ? errorValue[1] : errorValue);

        return [Math.min(lowerValue, prevErrorArr[0]), Math.max(upperValue, prevErrorArr[1])];
      }, [Infinity, -Infinity]);
Ejemplo n.º 5
0
export default ((def) => (state = def, action) => {
    switch (action.type) {
        case BUCKETS_EDIT_FIELD:
            return { ...state, [action.payload.key]: action.payload.value }
        case BUCKETS_EDIT_REQUEST:
            return def;
        case BUCKETS_EDIT_SUCCESS:
            return action.payload;
        case IMAGES_LIST_REMOVE:
            if ((state.thumbnails && isArray(state.thumbnails)) ||
                (state.banners && isArray(state.banners))) {

                var indexThumbnail = state.thumbnails.indexOf(action.payload);
                var indexBanner = state.banners.indexOf(action.payload);

                if ((indexThumbnail > -1) || (indexBanner > -1)) {

                    state.thumbnails.splice(indexThumbnail, 1);
                    state.banners.splice(indexBanner, 1);

                    return {...state};
                }
            }
        // case BUCKETS_EDIT_FAILURE:
        //     return action.payload;
        // case BUCKETS_EDIT_SAVE:
        //     return action.payload;
        default:
            return state;
    }
})(false);
Ejemplo n.º 6
0
ArrayTransformer.prototype.parse = function(value) {
    if (!value && typeof value !== 'number')
        return [];

    if (isArray(value))
        return value;

    let result = value;

    if (typeof value !== 'string')
        value = value + '';

    if (this._mode === MODE_JSON || this._mode === MODE_ANY)
        result = parseJSON(value);

    if (!isArray(result))
        result = null;

    if (this._mode === MODE_SEPARATOR || (this._mode === MODE_ANY && !result))
        result = value.split(this._separator);

    if (!isArray(result))
        result = [];

    return result;
};
function parseChildren (child, parent) {
  if (isString(child)) {
    parent.name = child || ''
    return
  }

  if (isArray(child)) {
    forEach(child, x => parseChildren(x, parent))
    return
  }

  if (!isObject(child)) return

  const {props} = child
  const type = camelCase(child.type)
  const node = omit(props, 'children')

  if (isEmpty(node) && !isObject(props.children) && !isArray(props.children)) {
    if (type === 'title') {
      parent.title = {
        text: props.children
      }
    } else {
      parent[type] = props.children === undefined
        ? true
        : props.children
    }

    return
  }

  forEach(node, (value, name) => {
    if (looksLikeAnEventHandler(name)) {
      node.events = node.events || {}
      node.events[lowerCase(name.slice(2))] = value
    }
  })

  if (parent.isRoot && includes(seriesTypes, type)) {
    node.type = type
    node.isSeries = true
    parent.series = parent.series || []
    parent.series.push(node)
  } else if (parent.isSeries && type === 'point') {
    parent.data = parent.data || []
    parent.data.push(node)
  } else {
    parent[type] = node
  }

  if (isArray(props.children)) {
    forEach(props.children, children =>
      parseChildren(children, node))
  } else {
    parseChildren(props.children, node)
  }
}
Ejemplo n.º 8
0
  constructor(props) {
    super(props);

    this.state = {
      value: isArray(props.value) ? props.value : [],
      options: isArray(props.options) ? props.options : [],
      onChangeValue: [],
      activeId: 1,
      open: false
    };
  }
Ejemplo n.º 9
0
async function createRowStream(source, encoding, parserOptions) {
  const parser = csv.parse({ltrim: true, relax_column_count: true, ...parserOptions})
  let stream

  // Stream factory
  if (isFunction(source)) {
    stream = source()

  // Node stream
  } else if (source.readable) {
    stream = source

  // Inline source
  } else if (isArray(source)) {
    stream = new Readable({objectMode: true})
    for (const row of source) stream.push(row)
    stream.push(null)

  // Remote source
  // For now only utf-8 encoding is supported:
  // https://github.com/axios/axios/issues/332
  } else if (helpers.isRemotePath(source)) {
    if (config.IS_BROWSER) {
      const response = await axios.get(source)
      stream = new Readable()
      stream.push(response.data)
      stream.push(null)
    } else {
      const response = await axios.get(source, {responseType: 'stream'})
      stream = response.data
    }

  // Local source
  } else {
    if (config.IS_BROWSER) {
      throw new TableSchemaError('Local paths are not supported in the browser')
    } else {
      stream = fs.createReadStream(source)
      stream.setEncoding(encoding)
    }
  }

  // Parse CSV unless it's already parsed
  if (!isArray(source)) {
    if (parserOptions.delimiter === undefined) {
      const csvDelimiterDetector = createCsvDelimiterDetector(parser)
      stream.pipe(csvDelimiterDetector)
    }
    stream = stream.pipe(parser)
  }

  return stream
}
Ejemplo n.º 10
0
createStore.merge = function merge(one, two) {
  if (one === undefined || one === null) {
    return two;
  } else if (two === undefined || two === null) {
    return one;
  } else if (_isObject(one) && _isObject(two)) {
    return _extend(one, two);
  } else if (_isArray(one) && _isArray(two)) {
    return one.concat(two);
  }
  // If types cannot be merged (strings, numbers, etc), simply override the value.
  return two;
};
Ejemplo n.º 11
0
function _transformInplaceBatch(A, B) {
  if (!isArray(A)) {
    A = [A];
  }
  if (!isArray(B)) {
    B = [B];
  }
  for (var i = 0; i < A.length; i++) {
    var a = A[i];
    for (var j = 0; j < B.length; j++) {
      var b = B[j];
      _transformInplaceSingle(a,b);
    }
  }
}
 Object.keys(_obj).forEach((key) => {
     let param = _obj[key];
     if (isObject(param) || isArray(param)) {
         param = JSON.stringify(param);
         _obj[key] = param;
     }
 });
Ejemplo n.º 13
0
module.exports = function arrify(value) {
	if (value == null) {
		return [];
	}

	return isArray(value) ? value : [value];
};
Ejemplo n.º 14
0
  update(id, data, ...args) {
    if (isArray(data)) {
      return Promise.reject('Not replacing multiple records. Did you mean `patch`?');
    }

    delete data[this.id];

    return this.Model
      .where({id})
      .fetch()
      .then(instance => {
        if (!instance) {
          throw new errors.NotFound(`No record found for id '${id}'`);
          return
        }

        const copy = {};
        Object.keys(instance.toJSON()).forEach(key => {
          // NOTE (EK): Make sure that we don't waterline created fields to null
          // just because a user didn't pass them in.
          if ((key === 'id') || (key === 'updated_at' || key === 'created_at') && typeof data[key] === 'undefined') {
            return;
          }

          if (typeof data[key] === 'undefined') {
            copy[key] = null;
          } else {
            copy[key] = data[key];
          }
        });

        return this.patch(id, copy, {});
    })
    .catch(utils.errorHandler);
  }
Ejemplo n.º 15
0
UsedKeywords.prototype.updateKeywordUsage = function( keyword, response ) {
	if ( response && _isArray( response ) ) {
		this._keywordUsage[ keyword ] = response;
		this._plugin.updateKeywordUsage( this._keywordUsage );
		this._app.analyzeTimer();
	}
};
Ejemplo n.º 16
0
  /**
   * Adds a contains all filter to the query. Requires `field` to contain all
   * members of `list`.
   * http://docs.mongodb.org/manual/reference/operator/all/
   *
   * @param   {String}  field     Field.
   * @param   {Array}   values    List of values.
   * @throws  {Error}             `values` must be of type: `Array`.
   * @returns {Query}             The query.
   */
  containsAll(field, values) {
    if (!isArray(values)) {
      values = [values];
    }

    return this.addFilter(field, '$all', values);
  }
Ejemplo n.º 17
0
    setColumns: function setColumns(columns) {
        this.columnSettings.filteredColumns = isArray(columns) ? columns : [columns];

        this.setState({
            filteredColumns: this.columnSettings.filteredColumns
        });
    },
Ejemplo n.º 18
0
export default (def => (state = def, action) => {
    switch (action.type) {
        case CONTACTFORM_LIST_REQUEST:
            return def;
        case CONTACTFORM_LIST_READ:

            if (isArray(state)) {

                return state.map(c => {

                    if (c.id === action.payload) {

                        c.read = 1;
                    }

                    return c;
                })
            }

        case CONTACTFORM_LIST_SUCCESS:
            return action.payload;
        // case CONTACTFORM_LIST_FAILURE:
        //     return action.payload;
        // case CONTACTFORM_LIST_REMOVE:
        //     return state.filter(item => (item.id != action.payload));
        default:
            return state;
    }
})(false);
Ejemplo n.º 19
0
Archivo: auto.js Proyecto: CowLeo/async
    forOwn(tasks, function (task, key) {
        if (!isArray(task)) {
            // no dependencies
            enqueueTask(key, [task]);
            readyToCheck.push(key);
            return;
        }

        var dependencies = task.slice(0, task.length - 1);
        var remainingDependencies = dependencies.length;
        if (remainingDependencies === 0) {
            enqueueTask(key, task);
            readyToCheck.push(key);
            return;
        }
        uncheckedDependencies[key] = remainingDependencies;

        arrayEach(dependencies, function (dependencyName) {
            if (!tasks[dependencyName]) {
                throw new Error('async.auto task `' + key +
                    '` has a non-existent dependency in ' +
                    dependencies.join(', '));
            }
            addListener(dependencyName, function () {
                remainingDependencies--;
                if (remainingDependencies === 0) {
                    enqueueTask(key, task);
                }
            });
        });
    });
Ejemplo n.º 20
0
    function _insert(q, data, priority, callback) {
        if (callback != null && typeof callback !== 'function') {
            throw new Error('task callback must be a function');
        }
        q.started = true;
        if (!isArray(data)) {
            data = [data];
        }
        if (data.length === 0) {
            // call drain immediately if there are no tasks
            return setImmediate(function() {
                q.drain();
            });
        }
        arrayEach(data, function(task) {
            var item = {
                data: task,
                priority: priority,
                callback: typeof callback === 'function' ? callback : noop
            };

            q.tasks.splice(_binarySearch(q.tasks, item, _compareTasks) + 1, 0, item);

            setImmediate(q.process);
        });
    }
Ejemplo n.º 21
0
  this.get = function(path) {
    if (this.nodes === null) {
      this.nodes = {};
      this.nodes['body'] = new Container(this, {
        type: 'container',
        id: 'body',
        nodes: []
      });
      var propEls = this.el.findAll('*[data-path]');
      for (var i = 0; i < propEls.length; i++) {
        var propEl = propEls[i];
        var nodeId = propEl.getAttribute('data-path').split('.')[0];
        this.nodes[nodeId] = new Paragraph(this, {
          type: 'paragraph',
          id: nodeId,
          content: propEl.textContent
        });
        this.nodes['body'].nodes.push(nodeId);
      }
    }

    if (!isArray(path)) {
      path = [path];
    }
    var result = get(this.nodes, path);
    return result;
  };
Ejemplo n.º 22
0
  constructor(options) {
    this.pluginDescriptor = this.buildPluginDescriptor();

    this.options = assign(
      {
        assetProcessors: [],
        canPrint: true
      },
      options || {}
    );

    this.phaseAssetProcessors = {};
    each(PHASE_LIST, (phase)  => {
      this.phaseAssetProcessors[phase] = [];
    });

    if (!isArray(this.options.assetProcessors)) {
      throw new Error('LastCallWebpackPlugin Error: invalid options.assetProcessors (must be an Array).');
    }
    each(this.options.assetProcessors, (processor, index) => {
      ensureAssetProcessor(processor, index);
      this.phaseAssetProcessors[processor.phase].push(processor);
    });

    this.resetInternalState();
  }
Ejemplo n.º 23
0
  var rects = displayedData.map(function (entry, index) {
    var value = void 0,
        x = void 0,
        y = void 0,
        width = void 0,
        height = void 0;

    if (stackedData) {
      value = truncateByDomain(stackedData[dataStartIndex + index], stackedDomain);
    } else {
      value = getValueByDataKey(entry, dataKey);

      if (!_isArray(value)) {
        value = [baseValue, value];
      }
    }

    if (layout === 'horizontal') {
      x = getCateCoordinateOfBar({
        axis: xAxis,
        ticks: xAxisTicks,
        bandSize: bandSize,
        offset: pos.offset,
        entry: entry,
        index: index
      });
      y = yAxis.scale(value[1]);
      width = pos.size;
      height = yAxis.scale(value[0]) - yAxis.scale(value[1]);

      if (Math.abs(minPointSize) > 0 && Math.abs(height) < Math.abs(minPointSize)) {
        var delta = mathSign(height || minPointSize) * (Math.abs(minPointSize) - Math.abs(height));

        y -= delta;
        height += delta;
      }
    } else {
      x = xAxis.scale(value[0]);
      y = getCateCoordinateOfBar({
        axis: yAxis,
        ticks: yAxisTicks,
        bandSize: bandSize,
        offset: pos.offset,
        entry: entry,
        index: index
      });
      width = xAxis.scale(value[1]) - xAxis.scale(value[0]);
      height = pos.size;

      if (Math.abs(minPointSize) > 0 && Math.abs(width) < Math.abs(minPointSize)) {
        var _delta = mathSign(width || minPointSize) * (Math.abs(minPointSize) - Math.abs(width));
        width += _delta;
      }
    }

    return _extends({}, entry, {
      x: x, y: y, width: width, height: height, value: stackedData ? value : value[1],
      payload: entry
    }, cells && cells[index] && cells[index].props);
  });
Ejemplo n.º 24
0
  notContainedIn(field, values) {
    if (!isArray(values)) {
      values = [values];
    }

    return this.addFilter(field, '$nin', values);
  }
Ejemplo n.º 25
0
Archivo: base.js Proyecto: AlexZ33/g2
 processAxis(view, facet) {
   const viewOptions = view.get('options');
   const geoms = view.get('geoms');
   if ((!viewOptions.coord.type || viewOptions.coord.type === 'rect') && geoms.length) {
     const field = geoms[0].get('attrOptions').position.field;
     const fields = isArray(field) ? field : field.split('*').map(function(str) {
       return str.trim();
     });
     const xField = fields[0];
     const yField = fields[1];
     if (isNil(viewOptions.axes)) {
       viewOptions.axes = {};
     }
     const axes = viewOptions.axes;
     if (axes !== false) {
       if (xField && axes[xField] !== false) {
         axes[xField] = axes[xField] || {};
         this.setXAxis(xField, axes, facet);
       }
       if (yField && axes[yField] !== false) {
         axes[yField] = axes[yField] || {};
         this.setYAxis(yField, axes, facet);
       }
     }
   }
 }
Ejemplo n.º 26
0
  appendEvents(id, events) {
    if (!isArray(events)) events = [ events ]
    let agg = this.store[id]

    if(!agg) {
      agg = {
        id: id,
        events: []
      }
      this.store[id] = agg
    }

    let version = agg.events.length

    each(events, ev => {
      version += 1
      let descriptor = new EventDescriptor(id, ev, version)
      agg.events.push(descriptor)

      this.emitter.emit(ev.eventName, descriptor)

      each(this.eventLoggers, log => {
        log(ev.eventName, descriptor)
      })
    })
  }
Ejemplo n.º 27
0
    forOwn(tasks, function (taskFn, key) {
        var params;

        if (isArray(taskFn)) {
            params = clone(taskFn);
            taskFn = params.pop();

            newTasks[key] = params.concat(newTask);
        } else if (taskFn.length === 0) {
            throw new Error("autoInject task functions require explicit parameters.");
        } else if (taskFn.length === 1) {
            // no dependencies, use the function as-is
            newTasks[key] = taskFn;
        } else {
            params = parseParams(taskFn);
            params.pop();

            newTasks[key] = params.concat(newTask);
        }

        function newTask(results, taskCb) {
            var newArgs = arrayMap(params, function (name) {
                return results[name];
            });
            newArgs.push(taskCb);
            taskFn.apply(null, newArgs);
        }
    });
Ejemplo n.º 28
0
export default  function(tasks, cb) {
    cb = once(cb || noop);
    if (!isArray(tasks)) return cb(new Error('First argument to waterfall must be an array of functions'));
    if (!tasks.length) return cb();
    var taskIndex = 0;

    function nextTask(args) {
        if (taskIndex === tasks.length) {
            return cb.apply(null, [null].concat(args));
        }

        var taskCallback = onlyOnce(rest(function(err, args) {
            if (err) {
                return cb.apply(null, [err].concat(args));
            }
            nextTask(args);
        }));

        args.push(taskCallback);

        var task = tasks[taskIndex++];
        task.apply(null, args);
    }

    nextTask([]);
}
Ejemplo n.º 29
0
    q.push = function(data, priority, callback) {
        if (callback != null && typeof callback !== 'function') {
            throw new Error('task callback must be a function');
        }
        q.started = true;
        if (!isArray(data)) {
            data = [data];
        }
        if (data.length === 0) {
            // call drain immediately if there are no tasks
            return setImmediate(function() {
                q.drain();
            });
        }

        var nextNode = q._tasks.head;
        while (nextNode && priority >= nextNode.priority) {
            nextNode = nextNode.next;
        }

        arrayEach(data, function(task) {
            var item = {
                data: task,
                priority: priority,
                callback: typeof callback === 'function' ? callback : noop
            };

            if (nextNode) {
                q._tasks.insertBefore(nextNode, item);
            } else {
                q._tasks.push(item);
            }
        });
        setImmediate(q.process);
    };
Ejemplo n.º 30
0
    forOwn(tasks, function (taskFn, key) {
        var params;
        var fnIsAsync = isAsync(taskFn);
        var hasNoDeps =
            (!fnIsAsync && taskFn.length === 1) ||
            (fnIsAsync && taskFn.length === 0);

        if (isArray(taskFn)) {
            params = taskFn.slice(0, -1);
            taskFn = taskFn[taskFn.length - 1];

            newTasks[key] = params.concat(params.length > 0 ? newTask : taskFn);
        } else if (hasNoDeps) {
            // no dependencies, use the function as-is
            newTasks[key] = taskFn;
        } else {
            params = parseParams(taskFn);
            if (taskFn.length === 0 && !fnIsAsync && params.length === 0) {
                throw new Error("autoInject task functions require explicit parameters.");
            }

            // remove callback param
            if (!fnIsAsync) params.pop();

            newTasks[key] = params.concat(newTask);
        }

        function newTask(results, taskCb) {
            var newArgs = arrayMap(params, function (name) {
                return results[name];
            });
            newArgs.push(taskCb);
            wrapAsync(taskFn).apply(null, newArgs);
        }
    });