Пример #1
0
const getElementInTstamp = (tstampGetter, measureGetter) => (element) => {
  const tstamp = tstampGetter(element);

  const measures = _.spannedMeasures(element);
  const measure = measureGetter(measures);
  let elements = _.durationalsByTstamp(measure)[tstamp];

  if (isEmpty(elements)) throw new Error(`Could not find elements with tstamp=${tstamp}`);

  const staff = element.getAttribute('staff');
  if (staff) {
    elements = filter(flow(_.staffN, eq(staff)), elements);
    if (isEmpty(elements)) throw new Error(`Could not find elements with staff=${staff}`);
  }

  const layer = element.getAttribute('layer');
  if (layer) {
    elements = filter(flow(_.layerN, eq(layer)), elements);
    if (isEmpty(elements)) throw new Error(`Could not find elements with layer=${layer}`);
  }

  if (elements.length !== 1) throw new Error('Could not unambiguously determine element');

  return elements[0];
};
Пример #2
0
export const filterToQuery = (filter, search, transformFilter = f => f) => {
  // console.log('got filter', filter);
  // console.log('got search', search);

  // remove empty objects on filter
  const query = {
    ...!isEmpty(filter) && removeEmptyObjects(transformFilter(filter)),
    ...(!isEmpty(search) && !isEmpty(search.searchFields) && !isEmpty(search.searchTerm) && (
      createSearchQuery(search.searchFields, termToTermList(search.searchTerm))
    )),
  };
  return query;
};
Пример #3
0
  /**
   * Logs a message with an optional style.
   *
   * If message is an object, array, function, class, etc. it is converted to
   * a string using `JSON.stringify()`.
   *
   * @since 0.4.0
   *
   * @access private
   *
   * @param {*}      message The message to log.
   * @param {String} [style] A style to apply to the message.
   */
  _log(message, style) {
    // Bail if the style is 'debug' and debugging is disabled.
    if (style === 'debug' && !project.debug) {
      return
    }

    // Don't log anything if message is empty.
    if (isEmpty(message)) {
      return
    }

    const icon = getOr('', style, this.icons)
    const applyStyle = getOr(identity, style, this.styles)

    let output = message

    // Convert object-like messages to string.
    if (isObjectLike(output)) {
      output = JSON.stringify(output, null, JSON_TAB_WIDTH)
    }

    // Make sure the message is a string.
    output = String(output)

    // If the style has an associated icon, prepend it to the message.
    if (icon) {
      output = `${icon} ${output}`
    }

    // Apply the style to the message.
    output = applyStyle(output)

    // Log the message.
    console.log(output)
  }
Пример #4
0
 function everything(ps, truth) {
   if (isEmpty(ps)) {
     return truth
   } else {
     return every(argsArray, first(ps)) && everything(tail(ps), truth)
   }
 }
Пример #5
0
 function something(ps, truth) {
   if (isEmpty(ps)) {
     return truth
   } else {
     return some(argsArray, first(ps)) || something(tail(ps), truth)
   }
 }
Пример #6
0
    .then(accounts => {
      if (_.isEmpty(accounts)) return [schema]
      const account = _.find(r => r.code === accountCode, accounts)
      const mergedAccount = mergeAccount(schema, account)

      return updateAccounts(mergedAccount, accounts)
    })
Пример #7
0
function processCryptos (codes) {
  if (_.isEmpty(codes)) {
    logger.info('No cryptos selected. Exiting.')
    process.exit(0)
  }

  logger.info('Thanks! Installing: %s. Will take a while...', _.join(', ', codes))

  const goodVolume = doVolume.prepareVolume()

  if (!goodVolume) {
    logger.error('There was an error preparing the disk volume. Exiting.')
    process.exit(1)
  }

  const selectedCryptos = _.map(code => _.find(['code', code], cryptos), codes)
  _.forEach(setupCrypto, selectedCryptos)
  common.es('sudo service supervisor restart')

  const blockchainDir = coinUtils.blockchainDir()
  const backupDir = path.resolve(os.homedir(), 'backups')
  const rsyncCmd = `( \
    (crontab -l 2>/dev/null || echo -n "") | grep -v "@daily rsync ".*"wallet.dat"; \
    echo "@daily rsync -r --prune-empty-dirs --include='*/' \
                        --include='wallet.dat' \
                        --exclude='*' ${blockchainDir} ${backupDir} > /dev/null" \
  ) | crontab -`
  common.es(rsyncCmd)

  logger.info('Installation complete.')
}
Пример #8
0
const NutritionBody = ({nutrition}) => {
  if (_.isEmpty(_.pick(['protein','fats','carbs','fiber'], nutrition))) {
    return (
      <Card.Body style={{height: 140}} empty>
        <Image
          key='image'
          style={{ width: 20, height: 20}}
          source={Images['CirclePlus']}
        />
        <Text
          key='text'
          style={{color: 'grey', padding: 8, backgroundColor: 'transparent'}}>
          Add nutrition info
      </Text>
      </Card.Body>
    )
  }
  return (
    <Card.Body>
      <View style={styles['NutritionBody']}>
        <NutritionLegend {...nutrition} />
        <NutritionChart {...nutrition} />
      </View>
    </Card.Body>
  )
}
Пример #9
0
  renderItemsByType = (type) => {
    const items = _.flow(
      _.filter(_.overEvery([
        META.isParent,
        META.isType(type),
        ({ _meta }) => new RegExp(this.state.query, 'i').test(_meta.name),
      ])),
      _.sortBy('_meta.name'),
      _.map(({ _meta }) => {
        const route = `${_meta.type}s/${_.kebabCase(_meta.name)}`

        return (
          <Link to={route} className='item' activeClassName='active' key={_meta.name}>
            {_meta.name}
          </Link>
        )
      })
    )(stardust)

    return _.isEmpty(items) ? [] : (
      <div className='item' key={type}>
        <div className='header'>{_.capitalize(type)}s</div>
        <div className='menu'>{items}</div>
      </div>
    )
  }
Пример #10
0
  renderFork = () => {
    const { snippets, match, theme } = this.props;
    const snippet = get(match.params.id, snippets);

    return (
      !isEmpty(get('fork', snippet)) && (
        <UtilityIcon
          size={ 22 }
          color={ theme.baseAppColor }
          type="fork"
          title={ `This snippet is forked from ${get('fork.owner.login', snippet)}` }
          dropdown>
          <Fork className="list">
            <div>
              <h3>
                Forked from{' '}
                <img
                  src={ get('fork.owner.avatar_url', snippet) }
                  size={ 22 }
                  alt={ get('fork.owner.login', snippet) }/>
                <strong>{get('fork.owner.login', snippet)}</strong>
              </h3>
              <div>
                <Anchor href={ get('fork.html_url', snippet) }>view original snippet</Anchor>
              </div>
            </div>
          </Fork>
        </UtilityIcon>
      )
    );
  };
Пример #11
0
 (change) => (
   <li key={ change.version }>
     <ExternalLink
       href={ `${snippetUrl}/${snippetId}/revisions#diff-${change.version}` }>
       <History>
         <div className="changed">
           <strong>Changed:</strong>
           <span>{dateFormatToString(change.committed_at)}</span>
         </div>
         {!isEmpty(change.change_status) && (
           <div>
             <span>
               <Additions>+</Additions>
               <span>{change.change_status.additions}</span>
             </span>
             <span>
               <Deletions>-</Deletions>
               <span>{change.change_status.deletions}</span>
             </span>
           </div>
         )}
       </History>
     </ExternalLink>
   </li>
 ),
Пример #12
0
 .then(result => {
   if (isEmpty(result)) {
     return 0
   } else {
     return result[0].total
   }
 })
Пример #13
0
function unzip(pairs) {
  if (isEmpty(pairs)) {
    return [[], []]
  }

  return constructPair(first(pairs), unzip(tail(pairs)))
}
Пример #14
0
  const searchType = () => {
    if (!isEmpty(trim(filterText))) {
      return isTag(filterText) ? 'free text tag' : 'free text';
    }

    if (!isEmpty(filterTags)) {
      return (
        <span>
          {'tags '}{' '}
          {map(
            (tag) => (
              <Tag key={ tag }>
                {tag}
                &nbsp;
                <Icon
                  type="close"
                  clickable
                  size={ 12 }
                  onClick={ () => removeTag(tag) }
                  color={ theme.baseAppColor }/>
              </Tag>
            ),
            filterTags
          )}
        </span>
      );
    }

    if (!isEmpty(trim(filterLanguage))) {
      return `language: ${filterLanguage}`;
    }

    if (!isEmpty(filterStatus)) {
      return startCase(filterStatus);
    }

    if (filterTruncated === true) {
      return 'large files';
    }

    if (filterUntagged === true) {
      return 'untagged';
    }

    return '';
  };
Пример #15
0
Tape.prototype.headLeft = function () {
  var before = this.tape.before,
      after = this.tape.after;
  if (_.isEmpty(before)) {
    before.push(this.blank);
  }
  after.push(before.pop());
};
Пример #16
0
 render() {
   if (fp.isEmpty(this.props.session)) {
     return this.renderLoading();
   } else if (this.props.children == null) {
     return this.renderWelcome();
   }
   return this.renderChildren();
 }
Пример #17
0
Tape.prototype.headRight = function () {
  var before = this.tape.before,
      after = this.tape.after;
  before.push(after.pop());
  if (_.isEmpty(after)) {
    after.push(this.blank);
  }
};
Пример #18
0
  constructor(props, context) {
    super(props, context)
    this.state = {
      loading: false,
      display: !_.isEmpty(props.photo),
    }

    this.handleAddPhotoPress = this.handleAddPhotoPress.bind(this)
  }
Пример #19
0
function isSelector(selector) {
  if (!isString(selector) || isEmpty(selector)) {
    throw new Error(
      'The valid CSS selector should be non-empty string. ' +
      'Instead got `' + selector + '`'
    );
  }

  return selector;
}
Пример #20
0
function fetch (settings, cryptoCode) {
  const plugin = configManager.cryptoScoped(cryptoCode, settings.config).layer2

  if (_.isEmpty(plugin) || plugin === 'no-layer2') return Promise.resolve()

  const layer2 = ph.load(ph.LAYER2, plugin)
  const account = settings.accounts[plugin]

  return Promise.resolve({layer2, account})
}
Пример #21
0
 .then(() => {
   var type = this.get('type')
   if (type) return type
   const tagNames = this.relations.tags.map(t => t.get('name'))
   const typeNames = intersection(tagNames, ['request', 'offer'])
   if (!isEmpty(typeNames)) {
     return typeNames[0]
   } else {
     return 'discussion'
   }
 })
  /**
   * Add fixtures to all soccerSeasons
   *
   * @param {Array} soccerSeasons An array of mongoose Documents
   * @param {function} next The next middleware
   * @this mongoose.Query
   * @return {undefined}
   */
  async function addFixturesOnFind(soccerSeasons, next) {
    // Fixtures are not needed when all soccerseasons should be shown
    if (fp.isEmpty(this.getQuery())) { return next() }

    // Promise.all() to make sure that all addFixtures
    // calls are finished before continuing
    // See: https://github.com/tc39/ecmascript-asyncawait/issues/7
    await Promise.all(fp.map(fp.partial(addFixtures, [this]), soccerSeasons))

    return next()
  }
Пример #23
0
function update (t, tx, changes) {
  if (_.isEmpty(changes)) return Promise.resolve(tx)

  const dbChanges = toDb(changes)
  const sql = pgp.helpers.update(dbChanges, null, 'cash_out_txs') +
    pgp.as.format(' where id=$1', [tx.id])

  const newTx = _.merge(tx, changes)

  return t.none(sql)
    .then(() => newTx)
}
Пример #24
0
  getStarred = () => {
    const starred = filter({ star: true }, this.props.snippets);

    if (!isEmpty(this.state.searchStarred)) {
      return filter((starredSnippet) => {
        const regex = new RegExp(this.state.searchStarred, 'gi');

        return starredSnippet.description.match(regex);
      }, starred);
    }

    return starred;
  };
Пример #25
0
function requiredTiers (trader, dailyVolume) {
  function requiredTier (tier) {
    const activeKey = `${tier}VerificationActive`
    const thresholdKey = `${tier}VerificationThreshold`

    return trader[activeKey] &&
    dailyVolume.gte(trader[thresholdKey])
  }

  const _required = _.filter(requiredTier, TIERS)

  // Ensure that we always start with sms if any tiers required
  return _.isEmpty(_required)
    ? []
    : _.union(['sms'], _required)
}
Пример #26
0
function sendRadar (data) {
  const url = _.get(['coinAtmRadar', 'url'], options)

  if (_.isEmpty(url)) {
    return Promise.reject(new Error('Missing coinAtmRadar url!'))
  }

  const config = {
    url,
    method: 'post',
    data,
    timeout: TIMEOUT,
    maxContentLength: MAX_CONTENT_LENGTH
  }

  console.log('%j', data)

  return axios(config)
    .then(r => console.log(r.status))
}
Пример #27
0
  const renderTags = () => {
    let list = snippetsTags;

    if (!isEmpty(searchTags)) {
      list = filter((tag) => {
        const regex = new RegExp(searchTags, 'gi');

        return tag.tag.match(regex);
      }, snippetsTags);
    }

    return map((tagItem) => {
      const tag = get('tag', tagItem);
      const filesCount = get('size', tagItem);

      return (
        <Pill style={ linearGradient(filesCount) } key={ tag } onClick={ () => searchByTags(tag) }>
          {tag}
          <br />
          <strong>{filesCount}</strong> <small>snippets</small>
        </Pill>
      );
    }, list);
  };
Пример #28
0
 .then(log => (!_.isNil(log) && !_.isEmpty(log)) ? log : supportLogs.batch().then(_.first))
  const updateStore = async (storageOperations: StorageOperation[], state) => {
    const documentsToSave = filter({ action: STORAGE_ACTION_SAVE }, storageOperations);
    const documentsToRemove = filter({ action: STORAGE_ACTION_REMOVE }, storageOperations);

    const now = Date.now();
    const storageLocations = map(storageOperation => {
      const storageKey =
        get(['storageLocation', 'storageKey'], storageOperation) || generateStorageKey();

      return {
        id: storageKey,
        accountId: storageOperation.account.id,
        storageKey,
        title: storageOperation.document.title,
        lastModified: now,
      };
    }, documentsToSave);

    const saveOperations = flow(
      zip(storageLocations),
      map(([storageLocation, storageOperation]) => [
        storageLocation.storageKey,
        JSON.stringify(storageOperation.document),
      ])
    )(documentsToSave);

    const removeOperations = flow(
      map('storageLocation'),
      map('storageKey')
    )(documentsToRemove);

    // Update saved list of documents
    const previousStorageLocation = documentId =>
      get(['documentStorageLocations', documentId], state);

    const newStorageLocationsByDocumentId =
      fromPairs(zip(map('document.id', documentsToSave), storageLocations));

    const documentsByAccountId = groupBy(flow(
      previousStorageLocation,
      get('accountId')
    ), state.documents);

    const accountsToUpdate = flow(
      map('accountId'),
      uniq
    )(storageLocations);

    const newStorageLocationsForAccountsToUpdate = map(flow(
      propertyOf(documentsByAccountId),
      map(docId => newStorageLocationsByDocumentId[docId] || previousStorageLocation(docId))
    ), accountsToUpdate);

    const storageLocationOperations = flow(
      map(value => JSON.stringify(map(omit(['accountId']), value))),
      zip(accountsToUpdate)
    )(newStorageLocationsForAccountsToUpdate);

    await Promise.all(compact([
      !isEmpty(removeOperations) ? storage.multiRemove(removeOperations) : null,
      storage.multiSet(concat(saveOperations, storageLocationOperations)),
    ]));

    return storageLocations;
  };
Пример #30
0
const isBornTooLongSince = _.curry((days, dateObject, individual) => {
  if (!dateObject) return false
  if (_.isEmpty(individual.birthDatePeriods)) return false
  const isWithinSomeYears = _.partialRight(isDateWithinSomeDaysOfPeriod, [dateObject.date, days])
  return !_.some(isWithinSomeYears, individual.birthDatePeriods)
})