Esempio n. 1
0
function extractRequirementNames(data: {}) {
	// Create the lists of requirement titles and abbreviations for the parser.
	// Because we allow both full titles ("Biblical Studies") and shorthand
	// abbreviations ("BTS-B") all glommed together into one string ("Biblical
	// Studies (BTS-B)"), we need a method of splitting those apart so the
	// PEG's ReferenceExpression can correctly reference them.
	const requirements = Object.keys(data).filter(isRequirementName)
	const abbreviations = fromPairs(
		requirements.map(req => [req.replace(requirementNameRegex, '$2'), req]),
	)
	const titles = fromPairs(
		requirements.map(req => [req.replace(requirementNameRegex, '$1'), req]),
	)
	return {abbreviations, titles}
}
Esempio n. 2
0
	function iterateTree(tree, level=0, index=0) {
		let tag = tree.shift();
		const key = onGenerateKey(tag, index);

		const props = (tree.length && isPlainObject(tree[0])) ?
		Object.assign(tree.shift(), { key: key }) :
		{ key: key };

		if (level === 0 && className) {
			props.className = className;
		}

		const children = tree.map(
			(branch, idx) => Array.isArray(branch) ?
			iterateTree(branch, level + 1, idx) :
			branch
		);

		tag = tags[tag] || tag;

		if (isString(props.style)) {
			props.style = zipObject(
				props.style.split(';')
				.map(prop => prop.split(':'))
				.map(keyVal => [camelCase(keyVal[0].trim()), keyVal[1].trim()])
			);
		}

		return (typeof onIterate === 'function') ?
		onIterate(tag, props, children, level) :
		React.createElement(tag, props, children);
	}
Esempio n. 3
0
export const testExclusionsWhoseSwitchExists = (
    participations: Participations
): Participations => {
    const pairs: Array<[string, { variant: string }]> = toPairs(
        participations
    ).filter(
        ([testId, { variant: variantId }]) =>
            variantId === NOT_IN_TEST && testSwitchExists(testId)
    );
    return fromPairs(pairs);
};
Esempio n. 4
0
    global.shipp.db.query(query.query, context, function(err, result) {

      if ("undefined" !== typeof query.idx) {
        if (!result.length) return next(new Error("Result not found"), null);
        result = result[query.idx];
      }

      results = Object.assign(results, (query.key) ? pair([[query.key, result]]) : result);
      if (--remaining === 0) next(err, results);

    });
export function alterForEvaluation(course: Course): TrimmedCourse {
	course = {...course}

	for (let [fromKey, toKey] of mapping.entries()) {
		if (course.hasOwnProperty(fromKey)) {
			course[toKey] = course[fromKey]
		}
	}

	let pairs = toPairs(course).filter(([key]) => whitelist.has(key))
	return (fromPairs(pairs): any)
}
function getFormData( { form, selectedPurchase, selectedSite } ) {
	const inputs = fromPairs(
		toArray( form.elements )
			.filter( ( element ) => {
				return ( element.type === 'radio' ) ? element.checked : true;
			} )
			.map( ( element ) => [ element.name, element.value ] )
	);

	// add product_id, blog_id
	inputs.product_id = selectedPurchase.productId;
	inputs.blog_id = selectedSite.ID;
	return inputs;
}
function getOrderedFields ({sort, query: {metrics, dimensions}}) {
  sort = fromPairs(sort)

  const ordered = sort._fields_

  if (isEmpty(ordered)) {
    return {dimensions, metrics}
  }

  const index = field => {
    const i = ordered.indexOf(field)

    return i <= 0
      ? Infinity
      : i
  }

  return {
    dimensions: orderBy(dimensions, index),
    metrics: orderBy(metrics, index)
  }
}
Esempio n. 8
0
/**
 * Helper for performing a metadata operation on the currently edited post.
 * Accepts a key, value, and operation, where key may be a string or array
 * of string keys. Alternatively, specify an object of key value pairs as the
 * first parameter. Dispatches an `EDIT_POST` action.
 *
 * @param  {(String|String[]|Object)} key       The metadata key(s) or object
 *                                              of metadata key-value pairs
 * @param  {*}                        value     The metadata value
 * @param  {String}                   operation The metadata operation to
 *                                              perform (`add`, `update`,
 *                                              or `delete`)
 */
function handleMetadataOperation( key, value, operation ) {
	var post = PostEditStore.get(),
		metadata;

	if ( 'string' === typeof key || Array.isArray( key ) ) {
		// Normalize a string or array of string keys to an object of key value
		// pairs. To accomodate both, we coerce the key into an array before
		// mapping to pull the object pairs.
		key = fromPairs( [].concat( key ).map( ( meta ) => [ meta, value ] ) );
	}

	// Overwrite duplicates based on key
	metadata = ( post.metadata || [] ).filter( ( meta ) => ! key.hasOwnProperty( meta.key ) );

	Object.keys( key ).forEach( function( objectKey ) {
		// `update` is a sufficient operation for new metadata, as it will add
		// the metadata if it does not already exist. Similarly, we're not
		// concerned with deleting a key which was added during previous edits,
		// since this will effectively noop.
		var meta = {
			key: objectKey,
			operation: operation
		};

		if ( 'delete' !== operation ) {
			meta.value = key[ objectKey ];
		}

		metadata.push( meta );
	} );

	Dispatcher.handleViewAction( {
		type: 'EDIT_POST',
		post: {
			metadata: metadata
		}
	} );
}
  function convertBranch (tkns, nested) {
    let branch = []

    if (!nested) {
      branch.push('html')
    }

    function getNext () {
      return convertBranch(tkns, true)
    }

    let token = tkns.shift()
    while (token && token.nesting !== -1) {
      const attrs = token.attrs && fromPairs(sortBy(token.attrs))
      const children = token.children && convertBranch(token.children.slice(), true)
      const rule = convertRules[camelCase(token.type)] || convertRules.default

      branch = branch.concat(
        rule(token, attrs, children, options, getNext)
      )
      token = tkns.shift()
    }
    return branch
  }
Esempio n. 10
0
	function convertBranch(tkns, nested) {
		let branch = [];

		if (!nested) {
			branch.push('html');
		}

		function getNext() {
			return convertBranch(tkns, true);
		}

		let token = tkns.shift();
		while (token && token.nesting !== -1) {
			const attrs = token.attrs && zipObject(sortBy(token.attrs, 0));
			const children = token.children && convertBranch(token.children.slice(), true);
			const rule = convertRules[camelCase(token.type)] || convertRules.default;

			branch = branch.concat(
				rule(token, attrs, children, options, getNext)
			);
			token = tkns.shift();
		}
		return branch;
	}
Esempio n. 11
0
export function enhanceHanson(data: HansonFile): ParsedHansonFile {
	if (typeof data !== 'object') {
		throw new Error('data was not an object!')
	}

	// Ensure that a result, message, or filter key exists.
	// If filter's the only one, it's going to filter the list of courses
	// available to the child requirements when this is evaluated.
	if (!('result' in data)) {
		throw new TypeError('"result" is a required key')
	}

	Object.keys(data).forEach(key => {
		if (!isRequirementName(key) && !topLevelWhitelist.has(key)) {
			const whitelistStr = quoteAndJoin(topLevelWhitelist)
			throw new TypeError(
				`only [${whitelistStr}] keys are allowed, and '${key}' is not one of them. All requirement names must begin with an uppercase letter or a number.`,
			)
		}
	})

	// because this only runs at the top level, we know
	// that we'll have a name to use
	let slug = data.slug || makeAreaSlug(data.name || '')

	if (data.revision && typeof data.revision !== 'string') {
		let rev = data.revision
		let msg = `"revision" must be a string. Try wrapping it in single quotes. "${rev}" is a ${typeof rev}.`
		throw new TypeError(msg)
	}

	let {abbreviations, titles} = extractRequirementNames(data)
	let result = parseWithPeg(data.result, {
		abbreviations,
		titles,
		startRule: 'Result',
	})

	let enhanced = toPairs(data).map(([key, value]) => {
		if (isRequirementName(key)) {
			return [key, enhanceRequirement(value)]
		}
		return [key, value]
	})

	let requirements: Mapped<ParsedHansonRequirement> = fromPairs(enhanced)
	let {name, type, revision, dateAdded, 'available through': available} = data

	let returnValue: ParsedHansonFile = {
		...requirements,
		$type: 'requirement',
		name,
		type,
		revision,
		slug,
		result,
	}

	if (dateAdded) {
		returnValue.dateAdded = dateAdded
	}

	if (available) {
		returnValue['available through'] = available
	}

	return returnValue
}
Esempio n. 12
0
	resObj = resObj.map(item =>
		fromPairs(toPairs(item).filter(([key]) => key !== 'Sp Comparison'))
Esempio n. 13
0
		.then(oldItems => fromPairs(oldItems.map(item => [item.clbid, null])))
Esempio n. 14
0
		.then(oldItems =>
			fromPairs(oldItems.map(item => [item.sourcePath, null])),
Esempio n. 15
0
  render: function render() {
    var _this = this;

    this.verifyProps();
    var that = this;
    var columnStyles = null;

    if (this.props.useGriddleStyles) {
      columnStyles = {
        margin: "0px",
        padding: that.props.paddingHeight + "px 5px " + that.props.paddingHeight + "px 5px",
        height: that.props.rowHeight ? this.props.rowHeight - that.props.paddingHeight * 2 + "px" : null,
        backgroundColor: "#FFF",
        borderTopColor: "#DDD",
        color: "#222"
      };
    }

    var columns = this.props.columnSettings.getColumns();

    // make sure that all the columns we need have default empty values
    // otherwise they will get clipped
    var defaultValues = fromPairs(columns, []);

    // creates a 'view' on top the data so we will not alter the original data but will allow us to add default values to missing columns
    var dataView = assign({}, this.props.data);

    defaults(dataView, defaultValues);
    var data = toPairs(deep.pick(dataView, without(columns, 'children')));
    var nodes = data.map(function (col, index) {
      var returnValue = null;
      var meta = _this.props.columnSettings.getColumnMetadataByName(col[0]);

      //todo: Make this not as ridiculous looking
      var firstColAppend = index === 0 && _this.props.hasChildren && _this.props.showChildren === false && _this.props.useGriddleIcons ? React.createElement('span', { style: _this.props.useGriddleStyles ? { fontSize: "10px", marginRight: "5px" } : null }, _this.props.parentRowCollapsedComponent) : index === 0 && _this.props.hasChildren && _this.props.showChildren && _this.props.useGriddleIcons ? React.createElement('span', { style: _this.props.useGriddleStyles ? { fontSize: "10px" } : null }, _this.props.parentRowExpandedComponent) : "";

      if (index === 0 && _this.props.isChildRow && _this.props.useGriddleStyles) {
        columnStyles = assign(columnStyles, { paddingLeft: 10 });
      }

      if (_this.props.columnSettings.hasColumnMetadata() && typeof meta !== 'undefined' && meta !== null) {
        if (typeof meta.customComponent !== 'undefined' && meta.customComponent !== null) {
          var customComponent = React.createElement(meta.customComponent, { data: col[1], rowData: dataView, metadata: meta });
          returnValue = React.createElement('td', { onClick: _this.handleClick, className: meta.cssClassName, key: index, style: columnStyles }, customComponent);
        } else {
          returnValue = React.createElement('td', { onClick: _this.handleClick, className: meta.cssClassName, key: index, style: columnStyles }, firstColAppend, col[1]);
        }
      }

      return returnValue || React.createElement('td', { onClick: _this.handleClick, key: index, style: columnStyles }, firstColAppend, col[1]);
    });

    if (nodes && this.props.multipleSelectionSettings && this.props.multipleSelectionSettings.isMultipleSelection) {
      var selectedRowIds = this.props.multipleSelectionSettings.getSelectedRowIds();

      nodes.unshift(React.createElement('td', { key: 'selection', style: columnStyles }, React.createElement('input', {
        type: 'checkbox',
        checked: this.props.multipleSelectionSettings.getIsRowChecked(dataView),
        onChange: this.handleSelectionChange,
        ref: 'selected' })));
    }

    //Get the row from the row settings.
    var className = that.props.rowSettings && that.props.rowSettings.getBodyRowMetadataClass(that.props.data) || "standard-row";

    if (that.props.isChildRow) {
      className = "child-row";
    } else if (that.props.hasChildren) {
      className = that.props.showChildren ? this.props.parentRowExpandedClassName : this.props.parentRowCollapsedClassName;
    }
    return React.createElement('tr', { onClick: this.props.multipleSelectionSettings && this.props.multipleSelectionSettings.isMultipleSelection ? this.handleSelectClick : null, className: className }, nodes);
  }
Esempio n. 16
0
async function main({ pipeline: pipelineName, filepath, data, options }) {
	let start = now()

	try {
		if (!data) {
			data = await loadFile(filepath)
		}

		let { steps, options: defaults } = PIPELINES[pipelineName]
		defaults = fromPairs(
			toPairs(defaults).map(([key, value]) => [key, value.default])
		)
		options = { ...defaults, ...options }

		let cache = new Cache({ filepath, contents: data, pipelineName, options })

		for (let step of steps) {
			step.output.forEach(key => stageStart({ stage: key }))

			let inputs = step.input.map(key => cache.get(key))
			let outputs = step.output.map(key => [key, cache.get(key)])

			// eslint-disable-next-line no-unused-vars
			if (outputs.filter(([k, v]) => v).length > 0) {
				// If we have cached results, let's just load them into memory and use them
				// instead of re-computing the results
				outputs.forEach(([key, value]) => {
					cache.set(key, value)
					stageComplete({
						stage: key,
						result: value,
						timeTaken: now() - start,
						cached: true,
					})
				})
				start = now()
				continue
			}

			let results = await Promise.all(await step.transform(inputs, options))

			// assert(results.length === step.output.length)
			zip(step.output, results).forEach(([key, result]) => {
				// store the results in the cache
				cache.set(key, result)

				// send the results over the bridge
				stageComplete({
					stage: key,
					result,
					timeTaken: now() - start,
					cached: false,
				})
			})

			start = now()
		}
	} catch (err) {
		console.error(err)
		error({ error: serializeError(err), timeTaken: now() - start })
	} finally {
		exit()
	}
}
const pkg = require('./packages/reactabular/package.json');

const TARGET = process.env.npm_lifecycle_event || '';
const ROOT_PATH = path.resolve(__dirname);
const config = {
  paths: {
    build: path.join(ROOT_PATH, 'build'),
    dist: path.join(ROOT_PATH, 'dist'),
    src: path.join(ROOT_PATH, 'packages'),
    ghPages: path.join(ROOT_PATH, 'gh-pages'),
    documentation: path.join(ROOT_PATH, 'docs'),
    'js-yaml': path.join(ROOT_PATH, 'node_modules', 'js-yaml')
  }
};
const packages = fromPairs(fs.readdirSync('packages').map(p => [
  p, path.join(config.paths.src, p, 'src')
]));

process.env.BABEL_ENV = TARGET;

const common = {
  entry: config.paths.documentation,
  resolve: {
    extensions: ['', '.js', '.jsx', '.md', '.css', '.png', '.jpg'],
    alias: {
      'js-yaml/dist/js-yaml.min.js': config.paths['js-yaml'],
      'js-yaml': config.paths['js-yaml'],
      // Reactabular aliases so that documentation and tests work
      ...packages
    }
  },
	distObj = distObj.map(row => {
		let pairs = toPairs(row)
		pairs = pairs.map(([key, value]) => [key.replace(/_/g, ' '), value])
		return fromPairs(pairs)
	})
Esempio n. 19
0
function enhanceRequirement(
	value: string | HansonRequirement,
): ParsedHansonRequirement {
	// 1. adds 'result' key, if missing
	// 2. parses the 'result' and 'filter' keys
	// 3. throws if it encounters any lowercase keys not in the whitelist
	// 4. throws if it cannot find any of the required keys

	// expand simple strings into {result: string} objects
	if (typeof value === 'string') {
		value = {result: value, filter: null, declare: {}}
	}

	if (typeof value !== 'object') {
		throw new Error('data was not an object!')
	}

	let keys = Object.keys(value)

	// Ensure that a result, message, or filter key exists.
	// If filter's the only one, it's going to filter the list of courses
	// available to the child requirements when this is evaluated.
	const oneOfTheseKeysMustExist = new Set(['result', 'message', 'filter'])
	if (!keys.some(key => oneOfTheseKeysMustExist.has(key))) {
		let requiredKeys = quoteAndJoin(oneOfTheseKeysMustExist)
		let existingKeys = quoteAndJoin(keys)
		throw new TypeError(
			`could not find any of [${requiredKeys}] in [${existingKeys}].`,
		)
	}

	keys.forEach(key => {
		if (!isRequirementName(key) && !lowerLevelWhitelist.has(key)) {
			const whitelistStr = quoteAndJoin(lowerLevelWhitelist)
			throw new TypeError(
				`only [${whitelistStr}] keys are allowed, and '${key}' is not one of them. All requirement names must begin with an uppercase letter or a number.`,
			)
		}
	})

	// Create the lists of requirement titles and abbreviations for the parser.
	let {abbreviations, titles} = extractRequirementNames(value)

	// We load the list of variables with the keys listed in the `declare` key
	// into the declaredVariables map. They're defined as a [string: string]
	// mapping.
	let {declare: variables = {}, result, filter, ...requirements} = value

	let parsedFilter = filter
		? parseWithPeg(filter, {
				abbreviations,
				titles,
				variables,
				startRule: 'Filter',
		  })
		: null

	let parsedResult = result
		? parseWithPeg(result, {
				abbreviations,
				titles,
				variables,
				startRule: 'Result',
		  })
		: null

	let enhanced = toPairs(requirements).map(
		([key, value]: [string, HansonRequirement]) => {
			if (lowerLevelWhitelist.has(key)) {
				return [key, value]
			}

			return [key, enhanceRequirement(value)]
		},
	)

	let returnedValue: ParsedHansonRequirement = {
		...fromPairs(enhanced),
		$type: 'requirement',
	}

	if (parsedResult) {
		returnedValue.result = parsedResult
	}

	if (parsedFilter) {
		returnedValue.filter = parsedFilter
	}

	return returnedValue
}