export const cParams = ls =>
  keyBy(map(isArray(ls) ? concat(ls) : concat(get(ls, 'parameters', [])),
    ({key, value}) => ({
      key,
      value,
      id: randomString()
    })), 'id')
示例#2
0
	makeFunctionBody: function(dependencies, factory, moduleName) {
		var beforeRequires = [];
		var depIds = this.getDependenciesIds(dependencies);

		var moduleRequires = this.makeStealRequires(
			depIds,
			this.getFactoryParamsNames(factory)
		);

		// sets module.id if "module" is a dependency
		// e.g: define(["module"], fn)
		if (includes(depIds, "module")) {
			beforeRequires = estemplate.compile("module.id = <%= name %>;")({
				name: b.literal(moduleName)
			}).body;
		}

		var body = this.transformDynamicImports(this.getBlockBody(factory));

		// if the factory function has a explicit return,
		// transform it into `stealModule.exports = returnArgument`
		var returnStatementIndex = this.getIndexOfReturnStatement(body);
		if (returnStatementIndex !== -1) {
			body[returnStatementIndex] = this.makeStealModuleExports(
				body[returnStatementIndex].argument
			);
		}

		return concat(beforeRequires, moduleRequires, body);
	},
示例#3
0
const mapStateToProps = function(state, ownProps) {
  const formId = ownProps.formId

  // get saved & server provided errors, concat them together
  let errors = null
  if (state.rform[formId] && state.rform[formId].errors) {
    errors = state.rform[formId].errors[ownProps.attribute] || []
  }
  errors = compact(concat(errors, ownProps.serverErrors))

  let value = ownProps.defaultValue
  const attrs = state.rform[ownProps.formId]
  if (
    attrs && ownProps.submodel && attrs[ownProps.submodel] &&
    !isNil(attrs[ownProps.submodel][ownProps.attribute])
  ) {
    value = Number(attrs[ownProps.submodel][ownProps.attribute])
  } else if (attrs && !isNil(attrs[ownProps.attribute])) {
    value = Number(attrs[ownProps.attribute])
  }

  return {
    errors,
    value,
  }
}
示例#4
0
  return dispatch => {
    const menuRoot = [{
      disabled: true,
      index: 0,
      labelKey: 'projects-label',
      level: 0,
      // TODO change to real route when page is done
      route: '#projects',
      titleText: 'disabled because projects page does not exist'
    }]

    const menuProject = [{
      index: 1,
      disabled: true,
      labelText: projectName || '',
      titleText: projectName || ''
    }]


    let menu
    if (projectName) {
      menu = flattenDeep(concat(menuRoot, menuProject))
    } else {
      menu = menuRoot
    }

    return dispatch(setMenu(menu))
  }
示例#5
0
 eos(connection).getTableRows(query).then((results) => {
   let { rows } = results;
   // If previous rows were returned
   if (previous) {
     // slice last element to avoid dupes
     previous.pop();
     // merge arrays
     rows = concat(previous, rows);
   }
   // if there are missing results
   if (results.more) {
     // recurse
     return dispatch(getProducers(rows));
   }
   const { globals } = getState();
   const { current } = globals;
   let backupMinimumPercent = false;
   let tokensToProducersForVotes = false;
   if (globals && globals.eos) {
     const supply = parseFloat(globals.eos.supply);
     // yearly inflation
     const inflation = 0.04879;
     // Tokens per year
     const tokensPerYear = supply * inflation;
     // Tokens per day
     const tokensPerDay = tokensPerYear / 365;
     // 1/5th of inflation
     const tokensToProducers = tokensPerDay * 0.2;
     // 75% rewards based on votes
     tokensToProducersForVotes = tokensToProducers * 0.75;
     // Percentage required to earn 100 tokens/day (break point for backups)
     backupMinimumPercent = 100 / tokensToProducersForVotes;
   }
   const data = rows
     .filter((p) => (p.producer_key !== 'EOS1111111111111111111111111111111114T1Anm'))
     .map((producer) => {
       const votes = parseInt(producer.total_votes, 10);
       const percent = votes / current.total_producer_vote_weight;
       const isBackup = (backupMinimumPercent && percent > backupMinimumPercent);
       return Object.assign({}, {
         isBackup,
         key: `${producer.owner}-${producer.total_votes}`,
         last_produced_block_time: producer.last_produced_block_time,
         owner: producer.owner,
         percent,
         producer_key: producer.producer_key,
         url: producer.url,
         votes
       });
     });
   const list = sortBy(data, 'votes').reverse();
   return dispatch({
     type: types.GET_PRODUCERS_SUCCESS,
     payload: {
       list
     }
   });
 }).catch((err) => dispatch({
示例#6
0
 .spread((rheactorjsCommands, ausgabenCommands) => {
   let commands = _concat(rheactorjsCommands, ausgabenCommands)
   if (!process.argv.slice(2).length || !commands.includes(process.argv.slice(2)[0])) {
     makeRed(backend.appName)
     program.outputHelp(makeRed)
     process.exit(1)
   } else {
     program.parse(process.argv)
   }
 })
          function(childrenDoc, cbNext) {
            // Remove all the ancestors that now are not ancestors
            let newAncestors = _dropWhile(childrenDoc[ancestors], function(elementId) {
              return elementId.toString() !== doc[id].toString();
            });
            childrenDoc[ancestors] = _concat(doc[ancestors], newAncestors);

            childrenDoc.save(function(err, data) {
              cbNext(err, data);
            });
          },
示例#8
0
	makeAstFromNestedDefine: function(moduleId, moduleName, programBody) {
		return this.slimWrapperTemplate(moduleName)({
			moduleId: b.literal(moduleId),
			params: this.slimFunctionParams[3],
			body: concat(
				this.amdDefineShim.start({}).body,
				programBody,
				this.amdDefineShim.end({}).body
			)
		});
	},
示例#9
0
 ImagePicker.showImagePicker(this.options, (response) => {
   if (response.didCancel) {
     console.log('User cancelled image picker')
   } else if (response.error) {
     console.log('ImagePicker Error: ', response.error)
   } else {
     return this.props.onChange &&
     this.props.onChange(concat(this.props.files, response), response)
   }
   return false
 })
示例#10
0
  renderChildren($$, node, level) {

    let rubrics = this.state.rubrics
    let isSelected = node.selected
    let hasSelectedChildren = rubrics.hasSelectedChildren(node.id)
    let isExpanded = node.expanded || isSelected || hasSelectedChildren
    let childNodes = rubrics.getChildren(node.id)
    let hideExpand = isEmpty(childNodes)
    let childrenEls = []

    if(isExpanded) {
      childrenEls = map(childNodes, function(сhildNode) {
        return this.renderChildren($$, сhildNode, level + 1)
      }.bind(this))
    }

    let el = $$('div').addClass('se-tree-node').ref(node.id)
      .on('click', this._expandNode.bind(this, node.id))

    el.addClass('level-' + level)

    if(!hideExpand) {
      let expandedIcon = isExpanded ? 'expanded' : 'collapsed'
      el.append(
        this.context.iconProvider.renderIcon($$, expandedIcon).addClass('expansion')
      )
    }

    if(level !== 1) {
      let selectedIcon = isSelected ? 'checked' : 'unchecked'
      if(isSelected) el.addClass('sm-selected')
      el.append(
        this.context.iconProvider.renderIcon($$, selectedIcon).addClass('selection')
          .on('click', this._selectNode.bind(this, node.id))
      )
    }

    el.append($$('span').addClass('se-tree-node-name').append(node.name))

    if(node.description) {
      let helpIcon = node.help ? 'helper-on' : 'helper-off'

      el.append(
        this.context.iconProvider.renderIcon($$, helpIcon).addClass('help')
          .on('click', this._toggleHelp.bind(this, node.id))
      )
      if(node.help) {
        el.append($$('div').addClass('se-node-help').append(node.description))
      }
    }

    return concat(el, childrenEls);
  }
示例#11
0
 flattenCommentsAndStatusChanges(comments = [], statusChanges = []) {
   let m_comments = comments.map(c => {
     return { type: "comment", data: c, created: c.created };
   });
   let m_statusChanges = statusChanges.map(sc => {
     return { type: "status", data: sc, created: sc.created };
   });
   let all = concat(m_comments, m_statusChanges);
   return all.sort(function(a, b) {
     return a.created < b.created ? -1 : a.created > b.created ? 1 : 0;
   });
 }
示例#12
0
      .map(([cartResponse, nextDrawDate]) => {
        if (!cartResponse || !cartResponse.lineItems) {
          this.setCartCountCookie(0);
          return {};
        }

        let items = map(cartResponse.lineItems, item => {
          let frequency = item.rate.recurrence.display;
          let itemConfig = omit(item.itemfields, ['self', 'links']);
          let giftStartDate = frequency !== 'Single' ?
            startMonth(itemConfig['recurring-day-of-month'], itemConfig['recurring-start-month'], nextDrawDate) : null;
          let giftStartDateDaysFromNow = giftStartDate ? giftStartDate.diff(new Date(), 'days') : 0;

          return {
            uri: item.self.uri,
            code: item.itemCode.code,
            displayName: item.itemDefinition['display-name'],
            price: item.rate.cost.display,
            config: itemConfig,
            frequency: frequency,
            amount: item.rate.cost.amount,
            designationNumber: item.itemCode['product-code'],
            productUri: item.item.self.uri,
            giftStartDate: giftStartDate,
            giftStartDateDaysFromNow: giftStartDateDaysFromNow,
            giftStartDateWarning: giftStartDateDaysFromNow >= 275
          };
        });

        let frequencyTotals = concat({
            frequency: 'Single',
            amount: cartResponse.total && cartResponse.total.cost.amount,
            total: cartResponse.total && cartResponse.total.cost.display
          },
          map(cartResponse.rateTotals, rateTotal => {
            return {
              frequency: rateTotal.recurrence.display,
              amount: rateTotal.cost.amount,
              total: rateTotal.cost.display
            };
          })
        );

        //set cart item count cookie
        this.setCartCountCookie(items.length);

        return {
          id: this.hateoasHelperService.getLink(cartResponse.total, 'cart').split('/').pop(),
          items: items.reverse(), // Show most recent cart items first
          frequencyTotals: frequencyTotals,
          cartTotal: frequencyTotals[0].amount
        };
      });
示例#13
0
const timeline = ( state = [], action ) => {
	switch ( action.type ) {
		case SERIALIZE:
			return [];
		case DESERIALIZE:
			return state;
		case HAPPYCHAT_RECEIVE_EVENT:
			const event = timeline_event( {}, action );
			const existing = find( state, ( { id } ) => event.id === id );
			return existing ? state : concat( state, [ event ] );
	}
	return state;
};
示例#14
0
let runCommand = function (cmd) {
  cmd.action.apply(null, _concat(backend, [].slice.call(arguments, 1)))
    .then(() => {
      emitterActive
        .then(() => {
          process.exit(0)
        })
    })
    .catch((err) => {
      console.error(makeRed(err.message))
      process.exit(1)
    })
}
示例#15
0
文件: Feed.js 项目: data4society/mpro
    request('GET', url, null, function(err, results) {
      if (err) {
        console.error('ERROR', err)
        return
      }
      let items
      if(this.state.pagination) {
        items = concat(this.state.items, results.records)
      } else {
        items = results.records
      }

      this.extendState({
        items: items,
        total: results.total
      })
    }.bind(this))  
示例#16
0
 eos(connection).getTableRows(query).then((results) => {
   let { rows } = results;
   // If previous rows were returned
   if (previous) {
     // slice last element to avoid dupes
     previous.pop();
     // merge arrays
     rows = concat(previous, rows);
   }
   // if there are missing results
   if (results.more) {
     return dispatch(getReferendums(rows));
   }
   dispatch(getVoteInfo(scope, settings.account));
   // dispatch(getVoteInfo(scope, settings.account));
   const data = rows
     .map((proposal) => {
       const {
         proposal_json,
         proposal_name,
         title
       } = proposal;
       let json = false;
       let valid = true;
       try {
         json = JSON.parse(proposal_json);
       } catch (err) {
         valid = false;
       }
       return {
         json,
         proposal_json,
         proposal_name,
         title,
         valid
       };
     });
   const proposals = sortBy(data, 'proposal_name');
   return dispatch({
     type: types.SYSTEM_GOVERNANCE_GET_PROPOSALS_SUCCESS,
     payload: {
       proposals,
       scope
     }
   });
 }).catch((err) => dispatch({
示例#17
0
const user_sockets = ( state = {}, action ) => {
	const { user, socket_id } = action;
	switch ( action.type ) {
		case UPDATE_IDENTITY:
			return assign( {}, state, set( {}, user.id, concat(
				get( state, user.id, [] ), socket_id )
			) );
		case REMOVE_USER_SOCKET:
			const sockets = get( state, user.id, [] );
			return assign( {}, state, set( {}, user.id, reject( sockets, socket_id ) ) );
		case REMOVE_USER:
			return omit( state, user.id );
		case SERIALIZE:
			return {};
		default:
			return state;
	}
};
示例#18
0
  getInvalidPermutation = createTask((dimensions, metrics) => {
    const {attributes} = this.context
    const selected = concat(dimensions, metrics)
    const isSelected = id => includes(selected, id)
    let invalidPermutation

    function checkForConflict (id) {
      const currentAttribute = find(attributes, {id})
      const deniedAttributeId = find(currentAttribute.incompatible, isSelected)

      if (deniedAttributeId) {
        invalidPermutation = [currentAttribute, find(attributes, {id: deniedAttributeId})]

        return false
      }
    }

    forEach(selected, checkForConflict)

    return invalidPermutation
  })
registerPromiseWorker(function ({ jsSpec, resolvedSpec, specStr, mode }) {
  let boundGetLineNumber = getLineNumberForPath.bind(null, specStr)

  if(!modes[mode]) {
    return console.error("WARNING: Validation plugin was supplied an invalid mode. Skipping validation.")
  }

  let settings = modes[mode]

  let inputs = {
    jsSpec,
    resolvedSpec,
    specStr,
    settings,
    getLineNumberForPath: boundGetLineNumber
  }

  let perfArray = []
  let LOG_VALIDATION_PERF = process.env.NODE_ENV !== "production"

  let markStep = (step) => perfArray.push({ step, stamp: getTimestamp() })
  markStep("origin")

  // Generate errors based on the spec
  let structuralValidationResult = settings.runStructural ? validate(inputs) : []
  markStep("structural")

  let combinedErrors = concat([], structuralValidationResult)
  markStep("combine")

  if(LOG_VALIDATION_PERF) {
    perfArray.forEach((el, i) => {
      if(i === 0) return
      // eslint-disable-next-line no-console
      console.log(`${el.step} took ${el.stamp - perfArray[i-1].stamp}ms`)
    })
  }

  return combinedErrors
})
示例#20
0
  getChildContext () {
    const {attributes, draft} = this.context
    const selected = pick(attributes, concat(draft.module.dimensions, draft.module.metrics))
    const selectable = {}
    const isIdSelected = selected.id || size(draft.module.filters.id) === 1

    forEach(attributes, (attr, key) => {
      const isAvailable = selected[key] || (
        (
          !attr.requires_id || isIdSelected
        ) && (
          !attr.pairs_with || isEmpty(diff(map(filter(selected, 'is_breakdown'), 'id'), attr.pairs_with))
        )
      )

      if (isAvailable) {
        selectable[key] = attr
      }
    })

    return {selectable}
  }
示例#21
0
文件: data.js 项目: Vizzuality/gfw
export const getMeansData = (data, latest) => {
  const minYear = minBy(data, 'year').year;
  const maxYear = maxBy(data, 'year').year;
  const grouped = groupBy(data, 'week');
  const centralMeans = Object.keys(grouped).map(d => {
    const weekData = grouped[d];
    return meanBy(weekData, 'count');
  });
  const leftYears = data.filter(d => d.year !== maxYear);
  const rightYears = data.filter(d => d.year !== minYear);
  const leftMeans = meanData(getYearsObj(leftYears, -6));
  const rightMeans = meanData(getYearsObj(rightYears, 0, 6));
  const allMeans = concat(leftMeans, centralMeans, rightMeans);
  const smoothedMeans = runningMean(allMeans, 12);
  const translatedMeans = translateMeans(smoothedMeans, latest);
  const pastYear = data.slice(-52);
  const parsedData = pastYear.map((d, i) => ({
    ...d,
    mean: translatedMeans[i]
  }));
  return parsedData;
};
示例#22
0
 render() {
   let { title, description, keywords, meta, script } = this.props;
   let extraMetas = map(meta, (content, name) => ({ name, content }));
   return (
     <Helmet
       title={title}
       meta={concat(
         [
           {
             name: 'description',
             content: description,
           },
           {
             name: 'keywords',
             content: keywords,
           },
         ],
         extraMetas
       )}
       script={script}
     />
   );
 }
示例#23
0
      }, function(err, results) {
        if (err) {
          this.setState({
            error: new Err('ApiList.LoadingError', {
              message: 'Public APIs could not be loaded.',
              cause: err
            })
          });
          console.error('ERROR', err)
          return
        }

        if(pagination) {
          items = concat(this.state.items, results.records)
        } else {
          items = results.records
        }

        self.extendState({
          items: items,
          totalItems: results.total
        });
      }.bind(this))
示例#24
0
 add = id => {
   this.setState({
     selected: concat(this.state.selected, id)
   })
 }
示例#25
0
const push = (newApp, ls) => concat(ls, newApp)
示例#26
0
const plugins = gulpLoadPlugins();

const files = {
  server : {
    js : ['server/**/*.js', 'common/**/*.js'],
    tests : ['server/**/*.test.js'],
    statics : [],
    jsons : [],
    dist : ['dist/server'],
    misc : ['package.json', '.gitignore', '.env', '.npmrc'],
    all () {
      return concat(
        this.js,
        this.tests,
        this.statics,
        this.jsons,
        this.dist,
        this.misc
      );
    }
  },
  client : {
    js : ['client/**/*.js', 'common/**/*.js'],
    tests : ['client/**/*.test.js'],
    statics : ['client/public/**', ...exclude(['client/public/**/*.json', 'client/public/**/*.html'])],
    jsons : ['client/public/**/*.json'],
    dist : ['dist/client'],
    misc : [],
    all () {
      return concat(
        this.js,
示例#27
0
 return map(b, function(y) {
   return concat(x, [y]);
 });
const push = (newLocation, ls) => concat(ls, newLocation)
示例#29
0
// Copy pasted tests from iflow-lodash
var nums: number[] = [1, 2, 3, 4, 5, 6];
var num: number;
var string: string;
var bool: boolean;

var nativeSquares: number[];
var directSquares: number[];

var nativeStrings: string[];
var directStrings: string[];

var allNums: number[];
var numsAndStrList: Array<number | string>;
var mixedList: Array<mixed>;
allNums = concat(nums, nums, nums);
numsAndStrList = concat(nums, "123", "456");
numsAndStrList = concat(nums, ["123", "456"]);
numsAndStrList = concat(nums, [[1, 2, 3], "456"]);
mixedList = concat(nums, [[1, 2, 3], "456"]);

// Array#map, lodash.map, lodash#map
nativeSquares = nums.map(function(num) {
  return num * num;
});
directSquares = map(nums, function(num) {
  return num * num;
});

num = first(nums);
示例#30
0
                <Input
                  type='number'
                  label='kpiGoal'
                  name='kpi_goal'
                  value={kpi_goal}
                  format={this.getKPIFormat()}
                  onChange={this.onChangeInput}/>)}

              {this.isConnectedToDash() && (
                <AutoSuggest
                  disabled={this.state.isLoadingDashCampaigns}
                  placeholder={messages.dashCampaignLabel}
                  onChange={this.onChangeDashCampaign}
                  selected={dashCampaign ? this.normalizeDashCampaignOption(dashCampaign) : null}
                  options={concat({
                    value: this.CREATE_OPTION_FLAG,
                    text: messages.newDashCampaign
                  }, map(company.dashCampaigns, this.normalizeDashCampaignOption))}/>
              )}

              {hasAnalytics
                ? (
                  <AutoSuggest
                    selected={gaSegment ? this.normalizeAutoSuggestOption(gaSegment) : null}
                    onChange={this.onChangeSegment}
                    placeholder={messages.gaSegmentLabel}
                    options={this.getSegments()}/>
                ) : null}

              {isAnalytics && !gaSegment ? (
                <p style={{wordBreak: 'break-all'}}>
                  <Message>defaultGASegmentAlert</Message>