fetchSite = async () => {
    this.setState({ loading: true });
    const res = await request('getSite', 'GET');
    this.setState({ loading: false });
    if (!res.success) return;

    const siteConfig = safeGet(res, 'data.site');
    this.setState({
      siteConfig,
    });
  }
Example #2
0
  var Get = through2.ctor(options, function (chunk, encoding, cb) {
    var out = get(chunk, propPath, defaultValue);

    // Pushing a zero-byte string in object mode will end the reading process.
    // In most instances this behviour is not desired.
    // https://nodejs.org/api/stream.html#stream_stream_push
    if (options.excludeZBS && out === ZERO_BYTE_STRING) return cb();

    this.push(out);
    return cb();
  });
Example #3
0
                            paths.forEach(function(name) {
                                var pathValue;

                                // If the doc is a query, this is a findAndUpdate
                                if (isQuery) {
                                    pathValue = get(doc, '_update.' + name) || get(doc, '_update.$set.' + name);
                                } else {
                                    pathValue = get(doc, isSubdocument ? name.split('.').pop() : name);
                                }

                                // Wrap with case-insensitivity
                                if (path.options && path.options.uniqueCaseInsensitive) {
                                    pathValue = new RegExp('^' + pathValue + '$', 'i');
                                }

                                var condition = {};
                                condition[name] = pathValue;

                                conditions.push(condition);
                            });
Example #4
0
const DateField = ({ elStyle, locales, options, record, showTime = false, source }) => {
    if (!record) return null;
    const value = get(record, source);
    if (value == null) return null;
    const date = value instanceof Date ? value : new Date(value);
    const dateString = showTime ?
        (toLocaleStringSupportsLocales ? date.toLocaleString(locales, options) : date.toLocaleString()) :
        (toLocaleStringSupportsLocales ? date.toLocaleDateString(locales, options) : date.toLocaleDateString());

    return <span style={elStyle}>{dateString}</span>;
};
 }).fail(function(xhr, status, error){
     $osf.unblock();
     var errorMessage = lodashGet(xhr, 'responseJSON.message') || ('There was a problem trying to add the contributor. ' + osfLanguage.REFRESH_OR_SUPPORT);
     $osf.growl('Could not add contributor', errorMessage);
     Raven.captureMessage('Error adding contributors', {
         extra: {
             url: url,
             status: status,
             error: error
         }
     });
 });
module.exports = function applyWriteConcern(schema, options) {
  const writeConcern = get(schema, 'options.writeConcern', {});
  if (!('w' in options) && writeConcern.w != null) {
    options.w = writeConcern.w;
  }
  if (!('j' in options) && writeConcern.j != null) {
    options.j = writeConcern.j;
  }
  if (!('wtimeout' in options) && writeConcern.wtimeout != null) {
    options.wtimeout = writeConcern.wtimeout;
  }
};
      Object.entries(this.result).reduce((acc, [parameter, object]) => {
        const reducerObject = get(object, `routes[${action.type}]`);

        if (reducerObject && reducerObject.reducerKey === reducerKey) {
          const urlParam = get(action, `meta.query[${parameter}]`);
          const decodedValue = reducerObject.decode(urlParam);
          return {
            ...acc,
            [reducerObject.stateKey]: isUndefined(urlParam) ?
              reducerObject.defaultValue :
              decodedValue
          };
        }
        const reducerObj = Object
          .values(object.routes)
          .find((obj) => obj.reducerKey === reducerKey);
        return {
          ...acc,
          ...reducerObj ? { [reducerObj.stateKey]: reducerObj.defaultValue } : {}
        };
      }, {}) : {});
Example #8
0
 request.fail(function(xhr, status, error){
     $osf.unblock();
     var errorMessage = lodashGet(xhr, 'responseJSON.message') || ('There was a problem trying to ' + trigger + ' the request from the user. ' + osfLanguage.REFRESH_OR_SUPPORT);
     $osf.growl('Could not '+ trigger + ' access request', errorMessage);
     Raven.captureMessage('Could not ' + trigger + ' access request', {
         extra: {
             url: requestUrl,
             status: status,
             error: error
         }
     });
 });
Example #9
0
async function getLoginToken(name) {
  const response = await request(app)
    .post('/graphql')
    .send({
      query: GQL.rootLogInUser,
      variables: {
        name,
        password: 'example1',
      },
    })
  return get(response, 'body.data.logIn.jwtToken')
}
Example #10
0
                            .forEach((key) => {
                                const item = items[key];

                                if (item.data) {
                                    const itemData = item.data;
                                    const value = get(filteredData, itemData.path);

                                    if (value !== undefined) {
                                        saveData[itemData.path] = value;
                                    }
                                }
                            });
Example #11
0
  lookupWebpack(prefix) {
    const projectPath = atom.project.getPaths()[0];
    if (!projectPath) {
      return Promise.resolve([]);
    }

    const vendors = atom.config.get('autocomplete-modules.vendors');
    const webpackConfig = this.fetchWebpackConfig(projectPath);

    const webpackRoot = get(webpackConfig, 'resolve.root', '');
    let moduleSearchPaths = get(webpackConfig, 'resolve.modulesDirectories', []);
    moduleSearchPaths = moduleSearchPaths.filter(
      (item) => vendors.indexOf(item) === -1
    );

    return Promise.all(moduleSearchPaths.map(
      (searchPath) => this.lookupLocal(prefix, path.join(webpackRoot, searchPath))
    )).then(
      (suggestions) => [].concat(...suggestions)
    );
  }
Example #12
0
function typify(key, value, types) {
  if (!types) {
    return value;
  }

  const transform = vtypes[get(types, key)];
  if (transform) {
    return transform(value)
  } else {
    return guessType(value)
  }
}
Example #13
0
  let analyzePath = function(path, type) {
    if (typeof type.selected !== 'boolean') return;

    var plusPath = '+' + path;
    if (fields && plusPath in fields) {
      // forced inclusion
      delete fields[plusPath];

      // if there are other fields being included, add this one
      // if no other included fields, leave this out (implied inclusion)
      if (exclude === false && keys.length > 1 && !~keys.indexOf(path)) {
        fields[path] = 1;
      }

      return;
    }

    // check for parent exclusions
    let pieces = path.split('.');
    let root = pieces[0];
    if (~excluded.indexOf(root)) {
      return;
    }

    // Special case: if user has included a parent path of a discriminator key,
    // don't explicitly project in the discriminator key because that will
    // project out everything else under the parent path
    if (!exclude && get(type, 'options.$skipDiscriminatorCheck', false)) {
      let cur = '';
      for (let i = 0; i < pieces.length; ++i) {
        cur += (cur.length === 0 ? '' : '.') + pieces[i];
        const projection = get(fields, cur, false);
        if (projection && typeof projection !== 'object') {
          return;
        }
      }
    }

    (type.selected ? selected : excluded).push(path);
  };
Example #14
0
function getNameAndVersion (opts, dir, cb) {
  var pkg = require(path.join(dir, 'package.json'))
  if (!pkg) return cb(Error(`no package.json file found in ${dir}`))

  // Name and version provided, no need to infer
  if (opts.name && opts.version) return cb(null)

  // Infer name from package.json
  opts.name = opts.name || prop(pkg, 'productName') || prop(pkg, 'name')

  // Infer electron version from package.json
  var electronVersion = prop(pkg, 'dependencies.electron') || prop(pkg, 'devDependencies.electron')
  var electronPrebuiltVersion = prop(pkg, 'dependencies.electron-prebuilt') || prop(pkg, 'devDependencies.electron-prebuilt')
  opts.version = opts.version || electronVersion || electronPrebuiltVersion

  if (!electronVersion && !electronPrebuiltVersion) return cb(null)

  var packageName = electronVersion ? 'electron' : 'electron-prebuilt'
  resolve(packageName, {basedir: dir}, function (err, res, pkg) {
    if (err) return cb(err)
    debug('Inferring target Electron version from `' + packageName + '` dependency or devDependency in package.json')
    opts.version = pkg.version
    return cb(null)
  })
}
Example #15
0
	get(path){
		if(this.cache && this.cache.has(path))
			return this.cache.get(path)

		let value=get(this,path)

		if(value==undefined)
			value=this._getFromBasedOn(...arguments)

		this.cache && this.cache.set(path,value)

		return value
	}
Example #16
0
 config.forEach( cmd => {
   const command = _get(optionMap, cmd);
   if (command) {
     if (command.hasOwnProperty('action')) {
       newConfig.plugins.push(command.action);
     }
     newConfig['toolbarElements'][cmd] = command;
   } else if (cmd.hasOwnProperty('action') &&
       cmd.hasOwnProperty('display')) {
     newConfig.plugins.push(cmd.action);
     newConfig.toolbarElements[cmd.command] = cmd;
   }
 });
Example #17
0
    (props) => ({
      changeField(fieldName, newFieldValue, shouldSave = true, ...other) {
        const newFormData = set({ ...props.formData }, fieldName, newFieldValue);
        props.setFormData(newFormData);

        if (shouldSave && props.autosave && _.isFunction(props.onFormChange)) {
          props.onFormChange(fieldName, newFieldValue, ...other);
        }
      },
      getField(fieldName) {
        return get(props.formData, fieldName);
      },
    }),
Example #18
0
  }, (error, response, body) => {
    if (error) return callback(error)

    if (isEmpty(get(body, 'error'))) {
      _plugin.log(JSON.stringify({
        title: 'Data inserted to ServiceNow table.',
        data: data
      }))
      callback()
    } else {
      callback(body.error)
    }
  })
Example #19
0
          this.on('saving', (model, attrs, options) => {
            let field = get(this, 'bcrypt.field')

            if (model.hasChanged(field) && options.bcrypt !== false) {
              let password = model.get(field)

              if (password !== null && typeof password !== 'undefined') {
                return hashAndStore(password, field, model)
              } else if (this.bcrypt.allowEmptyPassword !== true) {
                throw new this.constructor.EmptyPasswordDetected()
              }
            }
          })
Example #20
0
export default function addResponse({ kind, path, lhs, rhs }) {
  const match = kind === 'N'
              && path.length === 5
              && path[0] === 'paths'
              && path[3] === 'responses';
  if (match) {
    const pathId = path[1];
    const method = path[2];
    const responseId = path[4];
    const definition = get(rhs, ['schema', '$ref']);
    return `${pathId} (${method}) - Response ${responseId} added to ${definition || rhs}`;
  }
  return false;
}
  onBitrate(newBitrate) {
    var bitrate = parseInt(get(newBitrate, 'bitrate', 0), 10)
    var now = this._now()

    if (this._metrics.extra.bitratesHistory.length > 0) {
      var beforeLast = this._metrics.extra.bitratesHistory[this._metrics.extra.bitratesHistory.length-1]
      beforeLast.end = now
      beforeLast.time = now - beforeLast.start
    }

    this._metrics.extra.bitratesHistory.push({start: this._now(), bitrate: bitrate})

    this._inc('changeLevel')
  }
    return ret.replaceWith(function(p) {
        var body = p.node.body.body;
        var len = body.length;
        var b = body[len - 1];

        if (b.type === 'ExpressionStatement' &&
            get(b, 'expression.callee.name') === 'applyCtx') {
              body[len - 1] = (j.returnStatement(b.expression));
        } else {
            body.push(j.returnStatement(j.callExpression(j.identifier('applyNext'), [])));
        }

        return j.functionExpression(p.node.id, [], p.node.body)
      });
Example #23
0
  walk(node, parent) {
    const hash = parent ? this.hashNode(parent) : undefined
    const id = format('%s-%s', node, hash)

    if (hash && includes(this.walked, id)) {
      return null
    }

    if (parent) {
      this.walked.push(id)
    }

    return get(this.condense, node, node)
  }
Example #24
0
  gulp.task('scripts:bundle', () => {
    const production = environment === 'production';
    const watching = gutil.env.watching;
    const errorHandler = notify.onError();

    const buildDir = config.build;
    const scriptsDir = config['scripts_dir'];

    const webpackConfig = getConfig(scriptsDir, {production});

    const scripts = site.scripts.filter(script => script.bundle);
    const compress = get(config, 'scripts.minify.settings') || MINIFY_DEFAULTS;

    const tasks = [];

    for (const script of scripts) {
      const webpackConfigCopy = clonedeep(webpackConfig);

      webpackConfigCopy.output = {path: buildDir, filename: script.destination};

      tasks.push(gulp.src(script.path, {cwd: scriptsDir, base: scriptsDir})
        .pipe(gulpIf(watching, plumber({errorHandler})))
        .pipe(webpackStream(webpackConfigCopy, webpack))
        .pipe(gulpIf(!production, sourcemaps.init({loadMaps: true})))
        .pipe(through.obj(function (file, enc, cb) {
          // Dont pipe through any source map files as it will be handled
          // by gulp-sourcemaps
          const isSourceMap = /\.map$/.test(file.path);
          if (!isSourceMap) {
            this.push(file);
          }
          cb();
        }))
        .pipe(plugins.init({velvet, filepath: script.filepath}))
        .pipe(gulpIf(script.minify, uglify({compress})))
        .pipe(gulpIf(script.revision, plugins.hash()))
        .pipe(plugins.destination())
        .pipe(gulpIf(!production, sourcemaps.write('.'))));
    }

    if (!tasks.length) {
      return gulp.src('.').pipe(gutil.noop());
    }

    return merge(tasks)
      .pipe(size({title: TASK_NAME}))
      .pipe(gulp.dest(buildDir))
      .pipe(plugins.revisionManifest({base: buildDir, merge: true}))
      .pipe(gulp.dest(buildDir));
  });
			function updateMountCache(path) {
				const mount = mounts[path];

				const ownState = _get(newState, path);
				const viewedState = getViewedState(path);

				if (ownState !== mount.cache.ownState ||
					viewedState !== mount.cache.viewedState
				) {
					// either the mount's own state or its viewed state have changed,
					// so recalculate its merged state
					updateCachedState(path, ownState);
				}
			}
                        paths.forEach(function(name) {
                            var pathValue;

                            // If the doc is a query, this is a findAndUpdate
                            if (isQuery) {
                                pathValue = get(doc, '_update.' + name);
                            } else {
                                pathValue = get(doc, isSubdocument ? name.split('.').pop() : name);
                            }

                            // Wrap with case-insensitivity
                            if (path.options && path.options.uniqueCaseInsensitive) {
                                // Excaping some symbols to make sure that some
                                // symbols will not be interpretated as regExp expression
                                pathValue = escapeRegExp(pathValue);
                                pathValue = new RegExp('^' + pathValue + '$', 'i');
                            }

                            var condition = {};
                            condition[name] = pathValue;

                            conditions.push(condition);
                        });
Example #27
0
Parser.prototype.walk = function (node, parent) {
  var hash = parent ? hashNode(parent) : undefined;
  var id = format('%s-%s', node, hash);

  if (hash && includes(this.walked, id)) {
    return;
  }

  if (parent) {
    this.walked.push(id);
  }

  return get(this.condense, node, node);
};
Embedded.prototype.cast = function(val, doc, init, priorVal) {
  if (val && val.$isSingleNested) {
    return val;
  }

  if (val != null && (typeof val !== 'object' || Array.isArray(val))) {
    throw new ObjectExpectedError(this.path, val);
  }

  let Constructor = this.caster;
  const discriminatorKey = Constructor.schema.options.discriminatorKey;
  if (val != null &&
      Constructor.discriminators &&
      typeof val[discriminatorKey] === 'string') {
    if (Constructor.discriminators[val[discriminatorKey]]) {
      Constructor = Constructor.discriminators[val[discriminatorKey]];
    } else {
      const constructorByValue = getDiscriminatorByValue(Constructor, val[discriminatorKey]);
      if (constructorByValue) {
        Constructor = constructorByValue;
      }
    }
  }

  let subdoc;

  // Only pull relevant selected paths and pull out the base path
  const parentSelected = get(doc, '$__.selected', {});
  const path = this.path;
  const selected = Object.keys(parentSelected).reduce((obj, key) => {
    if (key.startsWith(path + '.')) {
      obj[key.substr(path.length + 1)] = parentSelected[key];
    }
    return obj;
  }, {});

  if (init) {
    subdoc = new Constructor(void 0, selected, doc);
    subdoc.init(val);
  } else {
    if (Object.keys(val).length === 0) {
      return new Constructor({}, selected, doc);
    }

    return new Constructor(val, selected, doc, undefined, { priorDoc: priorVal });
  }

  return subdoc;
};
Example #29
0
File: index.js Project: sives/Plio
  _loadMore(sortDir) {
    const {
      loading,
      priorLimit,
      followingLimit,
      dispatch,
      messages = [],
      lastMessageId,
    } = this.props;

    if (loading) return;

    const sort = { createdAt: sortDir };
    const message = sortDir > 0 ? _.last(messages) : _.first(messages);

    const dispatchAll = () => {
      const actions = ((() => {
        const _at = FlowRouter.getQueryParam('at');
        const setSortDir = setSort(sort);
        const incFollowingLimit = setFollowingLimit(followingLimit + MESSAGES_PER_PAGE_LIMIT);
        const incPriorLimit = setPriorLimit(priorLimit + MESSAGES_PER_PAGE_LIMIT);

        const _actions = _at
          ? [setSortDir, sortDir > 0 ? incFollowingLimit : incPriorLimit]
          : [setSortDir, incFollowingLimit];

        return _actions;
      })());

      return dispatch(batchActions(actions));
    };

    if (sortDir < 0) {
      // upscroll
      if (messages.length < MESSAGES_PER_PAGE_LIMIT * 2) return;

      if ($(this.loaderOlder).isAlmostVisible()) {
        dispatchAll();
      }
    } else {
      // downscroll
      if ($(this.loaderNewer).isAlmostVisible()) {
        // load if the last message of discussion is not equal to the last rendered message
        if (!Object.is(get(message, '_id'), lastMessageId)) {
          dispatchAll();
        }
      }
    }
  }
Example #30
0
module.exports = async function(
  videoDir,
  videoPath,
  index,
  videoMetrics,
  timingMetrics,
  options
) {
  const newStart = videoMetrics.videoRecordingStart / 1000;
  let tmpFile = path.join(videoDir, 'tmp.mp4');

  // if there's no orange (too slow instance like travis?)
  // we don't wanna cut
  if (videoMetrics.videoRecordingStart > 0) {
    await removeOrange(
      videoPath,
      tmpFile,
      newStart,
      videoMetrics.visualMetrics,
      options
    );
  } else {
    log.error(
      'The video recording start is zero, either no orange is there in the video or VisualMetrics failed: %j',
      videoMetrics
    );
    tmpFile = videoPath;
  }

  if (get(options, 'videoParams.keepOriginalVideo', false)) {
    const originalFile = path.join(videoDir, index + '-original.mp4');
    await rename(videoPath, originalFile);
  }

  if (options.videoParams.addTimer) {
    const tmpFile2 = path.join(videoDir, 'tmp2.mp4');
    await addTextToVideo(
      tmpFile,
      tmpFile2,
      videoMetrics,
      timingMetrics,
      options
    );
    await rename(tmpFile2, videoPath);
    await unlink(tmpFile);
  } else {
    await rename(tmpFile, videoPath);
  }
};