static defaultProps = { ...VictoryCursorContainer.defaultProps, cursorLabelComponent: <VictoryLabel/>, cursorComponent: <LineSegment/> }; // overrides all web events with native specific events static defaultEvents = (props) => { return [{ target: "parent", eventHandlers: { onTouchStart: (evt, targetProps) => { return props.disable ? {} : CursorHelpers.onMouseMove(evt, targetProps); }, onTouchMove: (evt, targetProps) => { return props.disable ? {} : CursorHelpers.onMouseMove(evt, targetProps); }, onTouchEnd: (evt, targetProps) => { return props.disable ? {} : CursorHelpers.onTouchEnd(evt, targetProps); } } }]; }; }; const combinedMixin = flow(originalCursorMixin, nativeCursorMixin); export const cursorContainerMixin = (base) => combinedMixin(base); export default cursorContainerMixin(VictoryContainer);
import _ from "lodash"; import log from "npmlog"; // clear logs between tests afterEach(() => { log.record.length = 0; }); const getVisibleMessages = _.flow( (list) => _.filter(list, (m) => { // select all info, warn, and error logs return log.levels[m.level] >= log.levels.info; }), (list) => _.map(list, "message"), // remove empty logs ("newline") _.compact ); export default function loggingOutput() { return getVisibleMessages(log.record); }
const pageSiteId = get( props, 'page.site_ID' ); const site = getSite( state, pageSiteId ); const siteSlugOrId = get( site, 'slug' ) || get( site, 'ID', null ); const selectedSiteId = getSelectedSiteId( state ); const isPreviewable = false !== isSitePreviewable( state, pageSiteId ) && site && site.ID === selectedSiteId; return { hasStaticFrontPage: hasStaticFrontPage( state, pageSiteId ), isFrontPage: isFrontPage( state, pageSiteId, props.page.ID ), isPostsPage: isPostsPage( state, pageSiteId, props.page.ID ), isPreviewable, previewURL: getPreviewURL( props.page ), site, siteSlugOrId, }; }; const mapDispatch = { setPreviewUrl, setLayoutFocus, recordEvent, recordMoreOptions: partial( recordEvent, 'Clicked More Options Menu' ), recordPageTitle: partial( recordEvent, 'Clicked Page Title' ), recordEditPage: partial( recordEvent, 'Clicked Edit Page' ), recordViewPage: partial( recordEvent, 'Clicked View Page' ), recordStatsPage: partial( recordEvent, 'Clicked Stats Page' ), }; export default flow( localize, updatePostStatus, connect( mapState, mapDispatch ) )( Page );
import _ from 'lodash'; import { __dirname as root } from './package_json'; import { join, normalize } from 'path'; module.exports = _.flow(_.partial(join, root), normalize);
return [{ target: "parent", eventHandlers: { onTouchStart: (evt, targetProps) => { return props.disable ? {} : VoronoiHelpers.onMouseMove(evt, targetProps); }, onTouchMove: (evt, targetProps) => { return props.disable ? {} : VoronoiHelpers.onMouseMove(evt, targetProps); }, onTouchEnd: (evt, targetProps) => { return props.disable ? {} : VoronoiHelpers.onMouseLeave(evt, targetProps); } } }, { target: "data", eventHandlers: props.disable ? {} : { onTouchStart: () => null, onTouchMove: () => null, onTouchEnd: () => null } }]; }; }; const combinedMixin = flow(originalVoronoiMixin, nativeVoronoiMixin); export const voronoiContainerMixin = (base) => combinedMixin(base); export default voronoiContainerMixin(VictoryContainer);
export const pickRefNodes = curry((deep, graph, refs) => { if (!refs) return {} if (deep) return mapValues(refs, flow(getGraphNode(graph), buildFullEntity(deep - 1, graph))) // eslint-disable-line return mapValues(refs, getGraphNode(graph)) })
export const createMainFramer = document => flow( createFrame(document, mainId), mountFrame(document), writeContentToFrame );
return convertDimensionalWithDefault(_.result(input, dim, _.result(defaults, dim))); })), _.zipObject(nondimensional, _.map(nondimensional, function (nondim) { return _.result(input, nondim, _.result(defaults, nondim)); })) ); } //todo - might want to make each type explicit, rather than implicit use of _.identity //only include special conversions, otherwise just use value (_.identity) converterField.container = function (input, fieldObj) { return _.result(input, 'containerName'); }; converterField.aliquot = _.flow(autoUtils.flattenAliquots, _.first); converterField['aliquot+'] = autoUtils.flattenAliquots; //future - need to handle differently, but right now this basically is just aliquot+ converterField['aliquot++'] = autoUtils.flattenAliquots; converterField.columnVolumes = function (input) { return _.flatten(_.map(input, function (colVol) { return _.map(colVol.columns, function (col) { return { column: parseInt(col, 10), volume: convertDimensionalWithDefault(colVol.volume, {unit: 'microliter', value: '100'}) }; }); }));
update: function (data, options) { options = _.assign(this._options, options) var margin = options.margin var svg = this._svg var h = this._height var w = this._width - margin.left - margin.right var dataHeight = h / 3 var yScale = d3.scale.ordinal() .domain(_(data).flatten().map(options.y).uniq().value()) .rangeRoundBands([dataHeight, 0]) var y = _.flow(options.y, yScale) var xScale = options.scale() .domain(options.domain(data)) .range([0, w]) var x = _.flow(options.marker, xScale) var width = _.flow(options.value, xScale) var measureHeight = _.isFinite(yScale.rangeBand()) ? yScale.rangeBand() * 0.5 : 0 var rectStartPosition = this._height - dataHeight - measureHeight + margin.top var isEmpty = !_(data).map(options.value).all(_.isFinite) svg.select('.x.axis').attr('transform', 'translate(0, ' + rectStartPosition + ')') // Draw qualitative ranges if (!(isEmpty || _.isEmpty(options.thresholds) || _.isEmpty(options.targets))) { var tick = svg.select('.x.axis').selectAll('.tick').data(data) tick.enter() .append('g') .attr({ 'class': 'tick' }) .style('fill', options.axisFill) tick.exit().remove() var rect = tick.selectAll('rect').data(function (d) { return isEmpty ? [] : [d] }) rect.enter().append('rect') .style('fill', 'inherit') rect .attr({ 'height': dataHeight, 'width': w, 'ry': 5 }) } else { svg.select('.x.axis') .call(qualitativeAxis() .height(dataHeight) .width(w) .scale(xScale) .threshold(d3.scale.threshold() .domain([]) .range(['']) ) .colors(['#F2F2F2', '#F2F2F2']) ) } svg.select('.data') .call(qualitativeAxis() .height(dataHeight) .width(w) .scale(xScale) .threshold(d3.scale.threshold().domain(options.thresholds).range(options.targets)) ) var g = svg.select('.data') .attr('transform', 'translate(' + margin.left + ', ' + rectStartPosition + ')') // Draw value var bar = g.selectAll('.bar').data(data) bar.enter().append('g') bar .attr({ 'class': 'bar', 'y': y }) .style('fill', options.dataFill) bar.exit().remove() var value = bar.selectAll('.value').data(function (d) { return isEmpty ? [] : [d] }) var valueAttr = { 'class': 'value', 'height': yScale.rangeBand(), 'ry': 5 } value.enter() .append('rect') .attr(valueAttr) .style({ 'fill': 'inherit', 'stroke': '#fff' }) value.attr(valueAttr) .transition() .duration(500) .attr('width', width) value.exit().remove() // Draw comparitive measure var measure = bar.selectAll('.comparative-measure') .data(function (d) { var v = options.value(d) var m = options.marker(d) return _.isFinite(v) && _.isFinite(m) ? [d] : [] }) var initAttr = { 'class': 'comparative-measure', 'width': 3, 'height': yScale.rangeBand() + measureHeight, 'y': -measureHeight / 2 } measure.enter().append('rect').attr(initAttr) .style('fill', 'inherit') measure.attr(initAttr).attr('x', x) measure.exit().remove() var legend = svg.select('.legend').attr('transform', 'translate(0, ' + options.fontSize + ')') let noDataColor = '#B9C3CB' var title = legend.selectAll('.title').data(data) title.enter().append('text') .attr({ 'class': 'title', 'text-anchor': 'start' }) .style({ 'font-size': options.fontSize, 'fill': d => { return _.isFinite(options.value(d)) ? options.dataFill(d) : noDataColor } }) .text(d => { return options.indicatorName(d) }) .on('mousemove', d => { var evt = d3.event var render = function () { return ( <Tooltip left={evt.pageX} top={evt.pageY}> <div> <h3>{options.indicatorName(d)}</h3> <p>{options.indicatorDescription(d)}</p> </div> </Tooltip> ) } if (this.layer) { this.layer._render = render } else { this.layer = new Layer(document.body, render) } this.layer.render() }) .on('mouseout', d => { if (this.layer) { this.layer.destroy() this.layer = null } }) title.exit().remove() var label = legend.selectAll('.label').data(data) label.enter().append('text') .attr({ 'class': 'label', 'x': w, 'text-anchor': 'end', 'fill': options.dataFill }) .style('font-size', options.fontSize) .text(d => { var v = options.value(d) return _.isFinite(v) ? [options.format(v)] : [] }) label.exit().remove() var compareValue = bar.selectAll('.comparative-text') .data(function (d) { var v = options.value(d) var text = options.valueText(v) return !_.isUndefined(text) ? width(d) > options.fontSize * 2 ? [text] : [text.slice(0, 1)] : '' }) compareValue.enter().append('text') .attr('class', 'comparative-text') compareValue .attr({ 'x': 4, 'y': 0, 'text-anchor': 'start', 'transform': 'translate(0, ' + ((yScale.rangeBand() + measureHeight) / 2) + ')', 'fill': '#FFFFFF' }) .style('font-size', options.fontSize - 2) .text(d => { return d }) compareValue.exit().remove() },
* * Handles the following state keys: * - edits: an object describing changes to be made to the current post, in * the format accepted by the WP REST API * - blocksByUid: post content blocks keyed by UID * - blockOrder: list of block UIDs in order * * @param {Object} state Current state * @param {Object} action Dispatched action * @return {Object} Updated state */ export const editor = flow( [ combineReducers, // Track undo history, starting at editor initialization. partialRight( withHistory, { resetTypes: [ 'SETUP_EDITOR' ] } ), // Track whether changes exist, starting at editor initialization and // resetting at each post save. partialRight( withChangeDetection, { resetTypes: [ 'SETUP_EDITOR', 'RESET_POST' ] } ), ] )( { edits( state = {}, action ) { switch ( action.type ) { case 'EDIT_POST': case 'SETUP_NEW_POST': return reduce( action.edits, ( result, value, key ) => { // Only assign into result if not already same value if ( value !== state[ key ] ) { // Avoid mutating original state by creating shallow // clone. Should only occur once per reduce. if ( result === state ) { result = { ...state };
import { flow, assign, camelCase, isEmpty, isObject, isString, } from 'lodash'; export function enhance(xs = [], source = {}) { return xs.map(x => assign({}, source, x)); } export const isExisty = x => { // Return false on empty Objects if (isObject(x) && isEmpty(x)) return false; // Return false on empty Strings if (isString(x) && isEmpty(x)) return false; // Intentional use of loose equality operator (Fogus) return x != null; // eslint-disable-line eqeqeq }; export const capitalizeFirstCharacter = x => x.charAt(0).toUpperCase() + x.slice(1); export const classify = flow(camelCase, capitalizeFirstCharacter);
uri: coalitionProbabilities, transform: _.flow(csv, coalitionDataParse), maxAge: shortMaxAge }); } function mapArticleURLbyID(rows) { return _.reduce(rows,function(o, d){ if (d.articleurl) { o[d.id] = d.articleurl; } return o; }, {}); } var indexById = _.flow(tsv, _.partial(_.indexBy, _, 'id')); var indexByONSid = _.flow(tsv, _.partial(_.indexBy, _, 'ons_id')); var battlegroundSpreadsheets = [ {uri: 'http://bertha.ig.ft.com/view/publish/gss/0Ak6OnV5xs-BudHhZMTFlTTdITjFLS01IZnRvUlpIcWc/ConstituencyGroups?exp=60', transform: JSON.parse, maxAge: fiveMins}, {uri: 'http://interactive.ftdata.co.uk/data/ge15-battlegrounds/resultnow.tsv', transform: indexById, maxAge: longMaxAge}, {uri: forecast.prediction + '?vkey', transform: indexById, maxAge: fiveMins}, {uri: 'http://interactive.ftdata.co.uk/data/ge15-battlegrounds/coordinates.tsv', transform: indexById, maxAge: longMaxAge}, {uri: 'http://interactive.ftdata.co.uk/data/ge15-battlegrounds/details.tsv', transform: indexByONSid, maxAge: longMaxAge}, {uri: 'http://bertha.ig.ft.com/view/publish/gss/0Ak6OnV5xs-BudHhZMTFlTTdITjFLS01IZnRvUlpIcWc/ConstituencyStories?exp=60', transform: _.flow(JSON.parse, mapArticleURLbyID), maxAge: fiveMins} ];
content => `${htmlCatch}<script>${content}${jsCatch}</script>` ); const wrapInStyle = partial( transformContents, content => `${htmlCatch}<style>${content}</style>` ); const setExtToHTML = partial(setExt, 'html'); const padContentWithJsCatch = partial(compileHeadTail, jsCatch); const padContentWithHTMLCatch = partial(compileHeadTail, htmlCatch); export const jsToHtml = cond([ [ matchesProperty('ext', 'js'), flow( padContentWithJsCatch, wrapInScript, setExtToHTML ) ], [stubTrue, identity] ]); export const cssToHtml = cond([ [ matchesProperty('ext', 'css'), flow( padContentWithHTMLCatch, wrapInStyle, setExtToHTML ) ],
const externalBlock = { type: "Block", value: "*\n * External dependencies\n " }; const internalBlock = { type: "Block", value: "*\n * Internal dependencies\n " }; const getPragmaDocblock = text => docblock.print( { pragmas: docblock.parse( docblock.extract( text ) ) } ); /** * Removes the extra newlines between two import statements */ const removeExtraNewlines = str => str.replace(/(import.*\n)\n+(import)/g, '$1$2'); /** * Adds a newline in between the last import of external deps + the internal deps docblock */ const addNewlineBeforeDocBlock = str => str.replace( /(import.*\n)(\/\*\*)/, '$1\n$2' ); const srcModifications = _.flow( [ removeExtraNewlines, addNewlineBeforeDocBlock, _.trimStart ] ); const isExternal = importNode => externalDependenciesSet.has( importNode.source.value.split('/')[ 0 ] ); /** * * @param {Array} importNodes the import nodes to sort * @returns {Array} the sorted set of import nodes */ const sortImports = importNodes => _.sortBy( importNodes, node => node.source.value ); module.exports = function ( file, api ) { const j = api.jscodeshift; const srcWithoutDocblock = docblock.strip( file.source ); const newDocblock = getPragmaDocblock( file.source );
update: function (data, options) { options = _.extend(this._options, options) var margin = options.margin var self = this var w = Math.max(options.headers.length * options.cellSize, 0) var h = Math.max(data.length * options.cellSize, 0) var svg = this._svg .attr({ 'viewBox': '0 0 ' + (w + margin.left + margin.right) + ' ' + (h + margin.top + margin.bottom), 'width': (w + margin.left + margin.right), 'height': (h + margin.top + margin.bottom) }) .datum(data) var xScale = d3.scale.ordinal() .domain(_.map(options.headers, options.headerText)) .rangeBands([0, w], 0.1) var x = _.flow(options.column, xScale) var sortCol = this.sortCol var sortValue = _.partial(options.sortValue.bind(this), _, sortCol) var yScale = d3.scale.ordinal() .domain(_(data).sortBy(sortValue, this).map(options.seriesName).value()) .rangeBands([0, h], 0.1) var y = _.flow(options.seriesName, yScale) var transform = function (d, i) { return 'translate(0, ' + y(d) + ')' } var fill = options.scale svg.select('.margin') .attr('transform', 'translate(' + margin.left + ', ' + margin.top + ')') var g = svg.select('.data') g.on('mouseout', function () { self._onRowOut.apply(self) }) var row = g.selectAll('.row').data(data) row.enter().append('g') .attr({ 'class': 'row', 'transform': transform }) row.exit() .transition().duration(300) .style('opacity', 0) .remove() row.on('mouseover', function (d, i) { self._onRowOver([d, i]) }) .transition() .duration(750) .attr('transform', transform) // Add cells to each row var cell = row.selectAll('.cell').data(options.values) cell.transition() .duration(500) .style('fill', fill) .attr({ 'height': yScale.rangeBand(), 'width': xScale.rangeBand(), 'x': x }) cell.enter().append('rect') .attr({ 'class': 'cell', 'height': yScale.rangeBand(), 'x': x, 'width': xScale.rangeBand() }) .style({ 'opacity': 0, 'fill': fill }) .transition() .duration(500) .style('opacity', 1) cell.exit() .transition() .duration(300) .style('opacity', 0) .remove() cell .attr('id', d => [d.location.name, d.indicator.short_name].join('-')) .style('cursor', _.isFunction(options.onClick) ? 'pointer' : 'initial') .on('mousemove', options.onMouseMove) .on('mouseout', options.onMouseOut) .on('click', options.onClick) svg.select('.x.axis') .transition().duration(500) .call(d3.svg.axis() .scale(xScale) .orient('top') .outerTickSize(0)) svg.selectAll('.x.axis text') .style({ 'text-anchor': 'start', 'font-size': options.fontSize, 'fontWeight': function (d) { return (d === sortCol) ? 'bold' : 'normal' } }) .attr('transform', 'translate(' + (xScale.rangeBand() / 2) + ', 0) rotate(-45)') .on('click', function (d, i) { self._setSort(d, i) }) .on('mouseover', function (d, i) { options.onColumnHeadOver(d, i, this) }) .on('mouseout', function (d, i) { options.onColumnHeadOut(d, i, this) }) svg.select('.y.axis') .transition().duration(500) .call(d3.svg.axis() .scale(yScale) .orient('left') .outerTickSize(0)) svg.selectAll('.y.axis text') .style('font-size', options.fontSize) .on('click', function (d, i) { options.onRowClick(d, i, this) }) if (options.legend) { svg.select('.legend') .call(options.legend) .attr('transform', function () { var bbox = this.getBoundingClientRect() var dx = w + margin.right - bbox.width + 10 var dy = 0 return 'translate(' + dx + ', ' + dy + ')' }) } else { svg.select('.legend').selectAll('*').remove() } },
const SERVER = "https://echo-radial.herokuapp.com"; const API_PATH = ""; const REQUEST_SESSION = 'shared-todo-application-number-1-1-1-destruct'; const DEFAULT_HEADERS = { 'REQUEST_SESSION': REQUEST_SESSION, 'Accept': 'application/json', 'Content-Type': 'application/json' } function getJSON(response) { return response.json(); } const model_name = _.snakeCase; const plural_model_name = _.flow(model_name, i.pluralize.bind(i)); function construct_path({model, path, id}) { if (path) return path; if (model) return _.compact([plural_model_name(model), id]).join('/'); return null; } function construct_api_path({model=null, server=null, api_path=null, id=null, path = null}) { server = server ? server : SERVER; api_path = api_path ? api_path : API_PATH; let path_function = (this && this.path_function) ? this.path_function : construct_path; return _.compact([server + api_path, path_function({model, path, id})]).join('/'); }
import { curry, filter, flow, get, identity, isEmpty, mapValues, nthArg, property } from 'lodash' import { merge } from 'cape-lodash' import { createSelector } from 'reselect' import { select, simpleSelector } from 'cape-select' import { getPath, REF, REFS, rmRefs } from './helpers' export const GRAPH_KEY = 'graph2' const fpSelect = curry(select, 2) export const selectGraph = property(GRAPH_KEY) export const entityTypeSelector = fpSelect(selectGraph) export const entitySelector = flow(getPath, fpSelect(selectGraph)) export const getEntity = curry((state, entity) => entitySelector(entity)(state)) export const getGraphNode = curry((graph, node) => get(graph, getPath(node), node)) export const pickRefNodes = curry((deep, graph, refs) => { if (!refs) return {} if (deep) return mapValues(refs, flow(getGraphNode(graph), buildFullEntity(deep - 1, graph))) // eslint-disable-line return mapValues(refs, getGraphNode(graph)) }) // Get one level of REF fields. export const buildFullEntity = curry((deep, graph, node) => { if (!node || (isEmpty(node[REF]) && isEmpty(node[REFS]))) return rmRefs(node) const getPredRefs = predRefs => mapValues(predRefs, flow(getGraphNode(graph), deep ? buildFullEntity(deep, graph) : identity) ) return merge( rmRefs(node), pickRefNodes(deep, graph, node[REF]), node[REFS] ? mapValues(node[REFS], getPredRefs) : {} ) })
return compose(this, fn); }; var sum = (a, b) => a + b; var half = (a) => a / 2; var addAndHalf = half.compose(sum); var x = addAndHalf(20, 10); log(x); var fromCharCode = String.fromCharCode.bind(String); var getCharCode = (s) => s.charCodeAt(0); var add1 = (x) => x + 1; var subtract1 = (x) => x - 1; var nextChar = (c) => fromCharCode(c.charCodeAt(0) + 1); var nextChar1 = fromCharCode.compose(add1.compose(getCharCode)) var nextChar2 = composeN(fromCharCode, add1, getCharCode); var prevChar = fromCharCode.compose(subtract1.compose(getCharCode)); var _prevChar = _.flowRight([fromCharCode, subtract1, getCharCode]); var _prevChar1 = _.flow(getCharCode, subtract1, fromCharCode); log(nextChar('a')); log(nextChar1('a')); log(nextChar2('a')); log(prevChar('x')); log(_prevChar('x')); log(_prevChar1('x'));
const getPredRefs = predRefs => mapValues(predRefs, flow(getGraphNode(graph), deep ? buildFullEntity(deep, graph) : identity) )
function parseFunctionRule(f) { return _.flow(f, parseRule); }
update: function (values, options) { options = _.assign(this._options, options) var margin = options.margin values = _(values) .filter(d => { var v = options.value(d) return _.isFinite(v) && v > 0 }) .sortBy(options.value) .reverse() .value() let data = [] if (values.length === 1) { // assume single indicator respresenting perentage data.push({ value: Math.round(values[0].value * 100) / 100 }) data.push({ value: 1 - data[0].value }) } else { data = values } var w = this._width - margin.left - margin.right var h = this._height - margin.top - margin.bottom var s = Math.min(w, h) var svg = this._svg svg.select('.margin') .attr('transform', 'translate(' + margin.left + ', ' + margin.top + ')') var xPosition = options.notInCenter ? w / 4 : w / 2 var yPosition = options.notInCenter ? h / 3 : h / 2 let g = svg.select('.data') .attr('transform', 'translate(' + xPosition + ', ' + yPosition + ')') let fill = color.map(data.map(options.name), options.color) if (options.chartInDashboard) { var legendText = _(data) .map(d => { return options.name(d) }) .reverse() .value() var legend = svg.select('.legend').selectAll('*') .data(legendText) legend.enter().append('g') .attr('class', 'series') .attr('transform', function (d, i) { return 'translate(0,' + i * 15 + ')' }) legend.append('rect') .attr({ 'x': w + 18, 'y': 0, 'width': 12, 'height': 12 }) .style({ 'fill': fill }) legend.append('text') .attr({ 'x': w + 18, 'y': 0, 'dx': -5, 'dy': 9 }) .style({ 'text-anchor': 'end', 'fill': '#999999' }) .text(d => { return d }) legend.exit().remove() } if (options.percentage) { var annotation = svg.select('.annotation').selectAll('.percentage').data([options.percentage]) annotation.enter().append('text') annotation.attr('class', 'percentage') .attr({'x': xPosition, 'y': yPosition, 'dy': 5}) .style({ 'text-anchor': 'middle', 'opacity': d => { return d === '0%' ? 0 : 1 } }) .text(d => { return d }) annotation.exit().remove() } var arc = d3.svg.arc() .innerRadius(s / 2 * options.innerRadius) .outerRadius(s / 2 * options.outerRadius) svg.select('.bg') .datum({ startAngle: 0, endAngle: 2 * Math.PI }) .attr('d', arc) var scale = d3.scale.linear() .domain(options.domain(data, options)) .range([0, 2 * Math.PI]) var pie = d3.layout.stack() .values(function (d) { return [d] }) .x(options.name) .y(options.value) .out(function (d, y0, y) { d.startAngle = scale(y0) d.endAngle = scale(y0 + y) }) var slice = g.selectAll('.slice').data(pie(_.cloneDeep(data))) slice.enter() .append('path') .attr('class', 'slice') slice.attr({ 'd': arc, 'fill': _.flow(options.name, fill), 'stroke': '#fff' }).on('mousemove', d => { var evt = d3.event var render = function () { let tip = options.name(d) ? `${options.name(d)}: ${options.yFormat(options.value(d))}` : options.yFormat(options.value(d)) return ( <Tooltip left={evt.pageX} top={evt.pageY}> <div> <p>{tip}</p> </div> </Tooltip> ) } if (this.layer) { this.layer._render = render } else { this.layer = new Layer(document.body, render) } this.layer.render() }) .on('mouseout', d => { if (this.layer) { this.layer.destroy() this.layer = null } }) slice.exit().remove() }
export const ArtworkContextAuctionType = create(Sale.type, { name: "ArtworkContextAuction", isTypeOf: ({ context_type }) => context_type === "Auction", }) export const ArtworkContextPartnerShowType = create(PartnerShow.type, { name: "ArtworkContextPartnerShow", isTypeOf: ({ context_type }) => context_type === "PartnerShow", }) export const ArtworkContextType = new GraphQLUnionType({ name: "ArtworkContext", types: [ArtworkContextAuctionType, ArtworkContextFairType, ArtworkContextPartnerShowType, ArtworkContextSaleType], }) const choose = flow(compact, first) export default { type: ArtworkContextType, description: "Returns the associated Fair/Sale/PartnerShow", resolve: ( { id, sale_ids }, options, request, { rootValue: { salesLoader, relatedFairsLoader, relatedShowsLoader } } ) => { let sale_promise = Promise.resolve(null) if (sale_ids && sale_ids.length > 0) { sale_promise = salesLoader(id, { id: sale_ids }).then(first).then(sale => { if (!sale) return null return assign({ context_type: sale.is_auction ? "Auction" : "Sale" }, sale)
// This file is part of MusicBrainz, the open internet music database. // Copyright (C) 2014 MetaBrainz Foundation // Licensed under the GPL version 2, or (at your option) any later version: // http://www.gnu.org/licenses/gpl-2.0.txt import ko from 'knockout'; import _ from 'lodash'; import nonEmpty from '../../common/utility/nonEmpty'; import parseIntegerOrNull from '../../common/utility/parseIntegerOrNull'; function conflict(a, b, prop) { return nonEmpty(a[prop]) && nonEmpty(b[prop]) && a[prop] !== b[prop]; } var unwrapInteger = _.flow(ko.unwrap, parseIntegerOrNull); function mergeDates(a, b) { a = _.mapValues(a, unwrapInteger); b = _.mapValues(b, unwrapInteger); if (conflict(a, b, 'year') || conflict(a, b, 'month') || conflict(a, b, 'day')) { return null; } return { year: nonEmpty(a.year) ? a.year : b.year, month: nonEmpty(a.month) ? a.month : b.month, day: nonEmpty(a.day) ? a.day : b.day }; }
/** * External dependencies */ import { flow } from 'lodash'; /** * Internal dependencies */ import reactTestEnvSetup from 'react-test-env'; const useFakeDom = flow( [ reactTestEnvSetup.useFakeDom, () => { // While it may not be the case that `page` is loaded in the context of // a DOM-dependent test, if it is, we must ensure that it's uncached // after the test finishes, since it stores a reference to the document // at the time of module load which will no longer exist after the // document is destroyed. after( () => delete require.cache[ require.resolve( 'page' ) ] ); } ] ); useFakeDom.withContainer = reactTestEnvSetup.useFakeDom.withContainer; useFakeDom.getContainer = reactTestEnvSetup.useFakeDom.getContainer; export default useFakeDom;
export function initUsersApi(server) { const callWithRequest = getClient(server).callWithRequest; const routePreCheckLicenseFn = routePreCheckLicense(server); server.route({ method: 'GET', path: '/api/security/v1/users', handler(request, reply) { return callWithRequest(request, 'shield.getUser').then( (response) => reply(_.values(response)), _.flow(wrapError, reply) ); }, config: { pre: [routePreCheckLicenseFn] } }); server.route({ method: 'GET', path: '/api/security/v1/users/{username}', handler(request, reply) { const username = request.params.username; return callWithRequest(request, 'shield.getUser', { username }).then( (response) => { if (response[username]) return reply(response[username]); return reply(Boom.notFound()); }, _.flow(wrapError, reply)); }, config: { pre: [routePreCheckLicenseFn] } }); server.route({ method: 'POST', path: '/api/security/v1/users/{username}', handler(request, reply) { const username = request.params.username; const body = _(request.payload).omit(['username', 'enabled']).omit(_.isNull); return callWithRequest(request, 'shield.putUser', { username, body }).then( () => reply(request.payload), _.flow(wrapError, reply)); }, config: { validate: { payload: userSchema }, pre: [routePreCheckLicenseFn] } }); server.route({ method: 'DELETE', path: '/api/security/v1/users/{username}', handler(request, reply) { const username = request.params.username; return callWithRequest(request, 'shield.deleteUser', { username }).then( () => reply().code(204), _.flow(wrapError, reply)); }, config: { pre: [routePreCheckLicenseFn] } }); server.route({ method: 'POST', path: '/api/security/v1/users/{username}/password', async handler(request, reply) { const username = request.params.username; const { password, newPassword } = request.payload; const isCurrentUser = username === request.auth.credentials.username; // If user tries to change own password, let's check if old password is valid first. if (isCurrentUser) { try { await server.plugins.security.getUser( BasicCredentials.decorateRequest(request, username, password) ); } catch(err) { return reply(Boom.unauthorized(err)); } } try { const body = { password: newPassword }; await callWithRequest(request, 'shield.changePassword', { username, body }); // Now we authenticate user with the new password again updating current session if any. if (isCurrentUser) { const authenticationResult = await server.plugins.security.authenticate( BasicCredentials.decorateRequest(request, username, newPassword) ); if (!authenticationResult.succeeded()) { return reply(Boom.unauthorized((authenticationResult.error))); } } } catch(err) { return reply(wrapError(err)); } return reply().code(204); }, config: { validate: { payload: { password: Joi.string(), newPassword: Joi.string().required() } }, pre: [routePreCheckLicenseFn] } }); }
let { includes, flow, escapeRegExp } = require('lodash'); let { isString, isArray, isPlainObject, get } = require('lodash'); let { keys } = require('lodash'); let fromRoot = require('../utils/fromRoot'); let asRegExp = flow( escapeRegExp, function (path) { let last = path.slice(-1); if (last === '/' || last === '\\') { // match a directory explicitly return path + '.*'; } else { // match a directory or files or just the absolute path return path + '(?:\\.js$|$|\\\\|\\/)?'; } }, RegExp ); let arr = v => [].concat(v || []); module.exports = class UiBundlerEnv { constructor(workingDir) { // the location that bundle entry files and all compiles files will // be written this.workingDir = workingDir; // the context that the bundler is running in, this is not officially // used for anything but it is serialized into the entry file to ensure
import _ from 'lodash'; import ansicolors from 'ansicolors'; export const green = _.flow(ansicolors.black, ansicolors.bgGreen); export const red = _.flow(ansicolors.white, ansicolors.bgRed); export const yellow = _.flow(ansicolors.black, ansicolors.bgYellow);
const strmatch = require('str-match')() function response (data, output) { return { data, output } } /** * Detect mast size with symbol * @example * 4m → 400 */ const REGEX_MAST_SIZE = /\d{1}m/i const REGEX_MAST_SIZE_SYMBOL = /m/i const normalizeSizeSymbol = flow([ str => replace(str, REGEX_MAST_SIZE_SYMBOL, '00'), toNumber ]) function sizeSymbol (str) { const size = strmatch(str, REGEX_MAST_SIZE) if (!size.test) return return response(normalizeSizeSymbol(size.match), size.output) } /** * Detect mast size * @example * 400 → 400 */ const REGEX_MAST_SIZE_NUMBER = /\d{3}/
} from './styles.css' class App extends Component { render () { const {children} = this.props return ( <div className={appWrapper}> <Header title="elevenohthree" /> <main className={appMain}> <div className={appMainWrapper}> {children} </div> </main> <Footer /> </div> ) } } App.propTypes = { children: PropTypes.element.isRequired } const mapStateToProps = (state) => ({}) const mapDispatchToProps = (dispatch) => ({}) export default flow( connect(mapStateToProps, mapDispatchToProps) )(App)
function defaultColumnChart (data, options, svg, h, w, topLegendHeight) { var margin = options.margin var dataMarginLeft = 25 var domain if (_.isFunction(options.domain)) { domain = options.domain(data) } else { domain = _(data).map(options.values).flatten().map(options.x).value() } var xScale = d3.scale.ordinal() .domain(domain) .rangeBands([0, w], options.padding) var dataXScale = d3.scale.ordinal() .domain(domain) .rangeBands([dataMarginLeft, w], options.padding) var x = _.flow(options.x, dataXScale) var range if (_.isFunction(options.range)) { range = options.range(data) } else { range = d3.extent(_(data).map(options.values).flatten().value(), d => { return options.y0(d) + options.y(d) }) // Make sure we always have at least a 0 baseline range[0] = Math.min(0, range[0]) } var yScale = options.yScale() .domain(range) .range([h, 0]) var y = d => { return yScale(options.y0(d) + options.y(d)) } var height = d => { var y0 = options.y0(d) var y = options.y(d) return yScale(y0) - yScale(y0 + y) } var g = svg.select('.data').attr('transform', 'translate(0, 0)') var series = g.selectAll('.bar').data(data) svg.select('.bg') .attr({ 'height': h + margin.top + topLegendHeight, 'width': w, 'x': margin.left }) series.enter().append('g') .attr('class', 'bar') let fill = color.map(data.map(options.name), options.color) series.style({ 'fill': _.flow(options.name, fill), 'stroke': '#fff' }) series.exit().remove() var hover = d3.dispatch('over', 'out') var column = series.selectAll('rect').data(options.values) column.enter() .append('rect') .style('fill', 'inherit') column.attr({ 'height': d => { return _.isFinite(height(d)) ? height(d) : 0 }, 'width': xScale.rangeBand(), 'x': x, 'y': d => { return _.isFinite(y(d)) ? y(d) : 0 } }) .on('mouseover', hover.over) .on('mouseout', hover.out) column.exit().remove() svg.select('.x.axis') .attr('transform', 'translate(0,' + h + ')') .call(d3.svg.axis() .orient('bottom') .tickSize(0) .tickPadding(4) .tickValues(_.filter(dataXScale.domain(), function (d, i, domain) { // Include every fourth tick value unless that tick is within three // ticks of the last value. Always include the last tick. We have to // do this manually because D3 ignores the ticks() value for // ordinal scales return (i % 4 === 0 && i + 3 < domain.length) || (i + 1) === domain.length })) .tickFormat(options.xFormat) .scale(dataXScale)) svg.select('.x.axis').selectAll('text').attr('y', 9) svg.select('.x.axis').selectAll('.domain').data([0]) .attr('d', 'M' + 0 + ',' + 0 + 'V0H' + w + 'V' + 0) svg.select('.y.axis') .attr('transform', 'translate(0, 0)') .call(d3.svg.axis() .orient('right') .tickFormat(options.yFormat) .tickSize(w) .ticks(2) .scale(yScale)) svg.selectAll('.y.axis .tick text') .attr({ 'dx': -w, 'dy': 10 }) d3.select(svg.selectAll('.y.axis text')[0][0]).attr('visibility', 'hidden') if (options.xLabel || options.yLabel) { svg.call(axisLabel() .data(options.xLabel, options.yLabel) .width(w) .height(h) .margin(options.margin)) } var fmt = _.flow(options.y, options.yFormat) var seriesLabel = label() .addClass('series') .width(w) .height(h) .align(false) var legendText = _(data) .map(d => { return options.name(d) }) .reverse() .value() var legend = svg.select('.legend').selectAll('*') .data(legendText) legend.enter().append('g') .attr('class', 'series') .attr('transform', function (d, i) { return 'translate(0,' + i * 15 + ')' }) legend.append('rect') .attr({ 'x': w - 12, 'y': -25, 'width': 12, 'height': 12 }) .style({ 'fill': fill }) legend.append('text') .attr({ 'x': w - 12, 'y': -25, 'dx': -5, 'dy': 9 }) .style({ 'text-anchor': 'end', 'fill': '#999999' }) .text(d => { return d }) legend.exit().remove() var timeout = null hover.on('out', function () { timeout = window.setTimeout(function () { timeout = null g.selectAll('rect') .transition() .duration(300) .style('opacity', 1) svg.selectAll('.x.axis text').style('opacity', 1) svg.select('.annotation').selectAll('*').remove() }, 200) }) hover.on('over', d => { if (_.isNumber(timeout)) { window.clearTimeout(timeout) timeout = null } g.selectAll('rect') .transition() .duration(500) .style('opacity', function (e) { return options.x(d) === options.x(e) ? 1 : 0.5 }) svg.selectAll('.x.axis text').style('opacity', 0) var annotations = _(data) .map(function (s) { return _.assign({}, _.find(options.values(s), function (e) { return options.x(d) === options.x(e) }), { name: options.name(s) } ) }) .map(d => { return { text: d.name + ' ' + fmt(d), x: x(d), y: y(d), defined: _.isFinite(d.value) } }) .tap(list => { if (_(list).some(item => (item.y >= h || item.y < 50))) { list.forEach(item => { item.y = 50 }) } }) .each(item => { item.y = 50 }) .value() svg.select('.annotation').selectAll('.series.label') .data(annotations) .call(seriesLabel.align(true)) .style('text-anchor', d => { return options.fontSize * d.text.length / 3 > d.x ? 'start' : 'end' }) var axisLabel = svg.select('.annotation') .selectAll('.axis.label') .data([options.x(d)]) axisLabel.enter() .append('text') .attr('class', 'axis label') .style('text-anchor', 'middle') axisLabel .attr({ 'transform': 'translate(' + x(d) + ', ' + (h + margin.bottom) + ')', 'dx': xScale.rangeBand() / 2, 'dy': '0.45em' }) .text(options.xFormat) }) }