How to use summarize method in Jest

Best JavaScript code snippet using jest

summarizer.js

Source:summarizer.js Github

copy

Full Screen

1'use strict';2const { extend, each, filter, map, omit, reduce } = require('underscore');3const async = require('async');4const mapLimit = (collection, iteratee, cb) => async.mapLimit(collection, 50, iteratee, cb);5// BigNumber6const BigNumber = require('bignumber.js');7BigNumber.config({ ERRORS: false });8const mconfigcb = require('abacus-metering-config');9const timewindow = require('abacus-timewindow');10const yieldable = require('abacus-yieldable');11const mconfig = yieldable(mconfigcb);12// Setup debug log13const debug = require('abacus-debug')('abacus-usage-reporting');14const edebug = require('abacus-debug')('e-abacus-usage-reporting');15// Get metering plan16const getMeteringPlan = function*(id, auth) {17 debug('Getting metering plan with id %s', id);18 const mplan = yield mconfig(id, auth);19 debug('Got metering plan %o', mplan);20 // Error when getting metering plan21 if (mplan.error) {22 debug('Error when getting metering plan %s: %s', id, mplan.reason);23 throw extend({ statusCode: 200 }, mplan);24 }25 return mplan.metering_plan;26};27const transformMapCb = (err, resource, accumulatedResult, cb) => {28 if (err) {29 cb(err);30 return;31 }32 cb(undefined, extend({}, resource, accumulatedResult));33};34// Traverse and calculate every single window + slack35const traverseWindows = (metric, end, time, processFn, summarizeFn) =>36 extend({}, metric, {37 windows: map(metric.windows, (window, windowIndex) =>38 map(window, (windowElement, windowElementIndex) => {39 // Calculate the from and to bounds of the window40 const bounds = timewindow.timeWindowBounds(end, timewindow.dimensions[windowIndex], -windowElementIndex);41 return processFn(metric, windowElement, summarizeFn, time, bounds);42 })43 )44 });45// Return the summarize function for a given metric46const summarizefn = (planId, metrics, metricName) => {47 const metric = filter(metrics, (m) => m.name === metricName)[0];48 if (!metric) {49 edebug('Plan change detected: metric %s missing from plan %s', metricName, planId);50 return () => 0;51 }52 return metric.summarizefn;53};54// Clone the metric and extend with a usage summary55// returns the result from summarize or null if sfn is undefined56const summarizeWindowElement = (metric, element, summaryFn, time, bounds) => {57 if (!element)58 return null;59 // Trying to reduce the report size. Not needed if no cost data in DB.60 const windowElement = omit(element, 'cost');61 if (!summaryFn)62 return extend({}, windowElement);63 try {64 return extend({}, windowElement, { summary: summaryFn(time, windowElement.quantity, bounds.from, bounds.to) });65 } catch (err) {66 edebug(`Failed to calculate summarize for metric ${metric}: %o`, err);67 return extend({}, windowElement, { summary: 0 });68 }69};70const summarizeMetric = (planId, metrics, summarizePlanFn) => (metric, cb) => {71 setImmediate(() => {72 const summarizeFunction = summarizefn(planId, metrics, metric.metric);73 try {74 debug(`Summarizing metric %o for plan ${planId}`, metric);75 cb(undefined, summarizePlanFn(metric, summarizeFunction));76 } catch (err) {77 edebug(`Failed to calculate summarize for plan ${planId}, metric ${metric.metric}: %o`, err);78 cb(err);79 }80 });81};82const summarizer = (time, aggregatedUsage, auth) => {83 // Calculates the summary for a metric under a plan, given the84 // metric object, query time, usage processed time, summarize function85 const summarizePlanMetric = (metric, sfn) =>86 traverseWindows(metric, aggregatedUsage.end, time, summarizeWindowElement, sfn);87 const summarizePlanMetrics = (planMetadata, meteringPlan, cb) => {88 const summarizeFunction = summarizeMetric(89 planMetadata.metering_plan_id,90 meteringPlan.metrics,91 summarizePlanMetric92 );93 mapLimit(planMetadata.aggregated_usage, summarizeFunction, (err, usage) => {94 transformMapCb(95 err,96 planMetadata,97 { aggregated_usage: usage },98 cb)99 ;100 });101 };102 const summarizePlan = (planMetadata, cb) => {103 // Find the metrics configured for the given metering plan104 const getMeteringPlanCb = yieldable.functioncb(getMeteringPlan);105 const planId = planMetadata.metering_plan_id;106 // Find the metrics configured for the given resource107 getMeteringPlanCb(planId, auth, (err, meteringPlan) => {108 if (err) {109 edebug('Could not obtain metering plan id %s due to: %o', planId, auth, err);110 cb(err);111 return;112 }113 summarizePlanMetrics(planMetadata, meteringPlan, cb);114 });115 };116 const resourceMetrics = (resource) => {117 const metrics = new Set();118 each(resource.plans, (plan) => each(plan.aggregated_usage, (metric) => metrics.add(metric.metric)));119 return [...metrics];120 };121 const aggregatePlanMetric = (planMetrics, windowIndex, slotIndex) => {122 const aggregatedResult = reduce(planMetrics, (aggregator, usage) => {123 // Only add the plan usage window if it is defined.124 if (usage && usage.windows[windowIndex][slotIndex] && usage.windows[windowIndex][slotIndex] !== null) {125 const quantity = typeof usage.windows[windowIndex][slotIndex].quantity !== 'number'126 ? 0127 : usage.windows[windowIndex][slotIndex].quantity;128 const summary = usage.windows[windowIndex][slotIndex].summary;129 return aggregator === null130 ? { quantity: quantity, summary: summary }131 : { quantity: aggregator.quantity + quantity, summary: aggregator.summary + summary };132 }133 return aggregator;134 }, null);135 return aggregatedResult !== null136 ? { quantity: aggregatedResult.quantity, summary: aggregatedResult.summary }137 : null;138 };139 const summarizeAggregatedMetric = (metric, plans) => {140 // Filter the plan metrics to only include the current metric141 const planMetrics = map(plans,142 (p) => filter(p.aggregated_usage, (m) => m.metric === metric && m.windows)[0]);143 const aggregateWindows = (windows) =>144 map(windows, (window, windowIndex) =>145 map(window, (slot, slotIndex) => aggregatePlanMetric(planMetrics, windowIndex, slotIndex)));146 return extend(147 { metric: metric },148 { windows: aggregateWindows(planMetrics[0].windows) }149 );150 };151 // Summarize the aggregated usage under a resource152 const summarizeResource = (resource, cb) => {153 debug('Summarizing resource %s', resource.resource_id);154 mapLimit(resource.plans, summarizePlan, (err, summarizedPlans) => {155 transformMapCb(156 err,157 resource,158 {159 aggregated_usage: map(160 resourceMetrics(resource),161 (metric) => summarizeAggregatedMetric(metric, summarizedPlans)162 ),163 plans: summarizedPlans164 },165 cb);166 });167 };168 const summarizeConsumer = (consumer, cb) => {169 debug('Summarizing consumer %s', consumer.consumer_id);170 mapLimit(consumer.resources, summarizeResource, (err, consumerAccum) => {171 transformMapCb(err, consumer, { resources: consumerAccum }, cb);172 });173 };174 const summarizeSpace = (space, cb) => {175 debug('Summarizing space %s', space.space_id);176 mapLimit(space.resources, summarizeResource, (err, resourceAccum) => {177 if (err) {178 edebug('Could not summarize space resources due to: %o', err);179 cb(err);180 return;181 }182 mapLimit(space.consumers, summarizeConsumer, (err, consumerAccum) => {183 transformMapCb(184 err,185 space,186 {187 resources: resourceAccum,188 consumers: consumerAccum189 },190 cb191 );192 });193 });194 };195 return {196 // Compute usage summaries for the given aggregated usage197 summarizeUsage: (cb) => {198 debug('Summarizing usage for time %o and aggregated usage %o', time, aggregatedUsage);199 mapLimit(aggregatedUsage.resources, summarizeResource, (err, resourcesAccum) => {200 debug('Summarizing aggregated usage for organization, %s', aggregatedUsage.organization_id);201 if (err) {202 edebug('Could not summarize resources due to: %o', err);203 cb(err);204 return;205 }206 mapLimit(aggregatedUsage.spaces, summarizeSpace, (err, spacesAccum) => {207 transformMapCb(208 err,209 aggregatedUsage,210 {211 resources: resourcesAccum,212 spaces: spacesAccum213 },214 cb215 );216 });217 });218 },219 summarizeInstanceUsage: function*() {220 debug('Summarizing instance usage for time %o and aggregated usage %o', time, aggregatedUsage);221 // Sets all quantities to their current quantity222 const setCurrentQuantity = (windows) => {223 each(windows, (w) => {224 each(w, (sw) => {225 if (sw) sw.quantity = sw.quantity.current;226 });227 });228 };229 // Find the metrics configured for the given metering plan230 const mplan = yield getMeteringPlan(aggregatedUsage.metering_plan_id, auth);231 const summarizedUsage = extend({}, aggregatedUsage, {232 accumulated_usage: map(aggregatedUsage.accumulated_usage, (m) => {233 setCurrentQuantity(m.windows);234 return summarizePlanMetric(235 m,236 summarizefn(aggregatedUsage.metering_plan_id, mplan.metrics, m.metric)237 );238 })239 });240 debug('Summarized instance usage %o', summarizedUsage);241 return summarizedUsage;242 }243 };244};245module.exports = summarizer;246module.exports.summarizeMetric = summarizeMetric;...

Full Screen

Full Screen

SummarizeBar.js

Source:SummarizeBar.js Github

copy

Full Screen

1import React, { useState } from 'react';2import PropTypes from 'prop-types';3import { Button } from '@material-ui/core';4import MenuItem from '@material-ui/core/MenuItem';5import Menu from '@material-ui/core/Menu';6import CloseIcon from '@material-ui/icons/Close';7import useStyles from './styles';8import GroupByList from './GroupByList';9const summarizes = [10 { id: 0, name: 'count', operation: 'COUNT', isNeedArgument: false, argument: '' },11 { id: 1, name: 'sum_of', operation: 'SUM', isNeedArgument: true, argument: '' },12 { id: 2, name: 'average_of', operation: 'AVG', isNeedArgument: true, argument: '' },13];14const SummarizeBar = ({ closeSidebar, currentVisualization, updateVisualization }) => {15 const classes = useStyles();16 const [currentSummarize, setCurrentSummarize] = useState(null);17 const [isSelectArgument, setIsSelectArgument] = useState(false);18 const [currentGroupBy, setCurrentGroupBy] = useState({ name: null, type: null, period: null, as: null });19 const [isSummarize, setIsSummarize] = useState(false);20 const [isInitializeSummarize, setIsInitializeSummarize] = useState(true);21 const [menuAnchorEl, setMenuAnchorEl] = useState(null);22 const isTableVisual = currentVisualization.type === 'TABLE';23 const handleMenuClick = (event) => {24 setMenuAnchorEl(event.currentTarget);25 };26 const nullGroupBy = () => {27 setCurrentGroupBy({ name: null, type: null, period: null, as: null });28 };29 const deleteSummarize = (e) => {30 e.stopPropagation();31 setIsSummarize(false);32 nullGroupBy();33 setIsSelectArgument(false);34 setCurrentSummarize(null);35 setIsInitializeSummarize(false);36 };37 const deleteGroupBy = (e) => {38 e.stopPropagation();39 nullGroupBy();40 };41 // initial summarize42 if (currentVisualization.config.isSummarize && isInitializeSummarize && !isSummarize) {43 setIsSummarize(true);44 setCurrentGroupBy(currentVisualization.config.summarize.groupBy);45 const summarizeIndex = summarizes.findIndex(46 (item) => item.name === currentVisualization.config.summarize.select.as47 );48 if (summarizes[summarizeIndex].isNeedArgument) {49 setCurrentSummarize({50 ...summarizes[summarizeIndex],51 argument: currentVisualization.config.summarize.select.column,52 });53 } else {54 setCurrentSummarize(summarizes[summarizeIndex]);55 }56 }57 const updateConfig = () => {58 const newConfig = { ...currentVisualization.config };59 if (isSummarize) {60 const groupByName = currentGroupBy.period61 ? `${currentGroupBy.name}_by_${currentGroupBy.period}`62 : currentGroupBy.name;63 newConfig.isSummarize = true;64 if (isTableVisual) {65 const summarizeColumns = [66 {67 id: currentSummarize.name,68 title: currentSummarize.name,69 type: 'number',70 visible: true,71 },72 {73 id: groupByName,74 title: groupByName,75 type: currentGroupBy.type,76 visible: true,77 },78 ];79 newConfig.summarizeColumns = summarizeColumns;80 } else {81 newConfig.axisData.XAxis.key = groupByName;82 newConfig.axisData.XAxis.label = groupByName;83 newConfig.axisData.YAxis.key = [currentSummarize.name];84 newConfig.axisData.YAxis.label = [currentSummarize.name];85 }86 const summarize = {87 select: {88 operation: currentSummarize.operation,89 column: currentSummarize.isNeedArgument ? currentSummarize.argument : '*',90 as: currentSummarize.name,91 },92 groupBy: {93 name: currentGroupBy.name,94 type: currentGroupBy.type,95 period: currentGroupBy.period,96 as: groupByName,97 },98 };99 newConfig.summarize = summarize;100 } else {101 if (isTableVisual) {102 delete newConfig.summarizeColumns;103 } else {104 newConfig.axisData.XAxis.key = newConfig.axisData.XAxis.availableKeys[0];105 newConfig.axisData.XAxis.label = newConfig.axisData.XAxis.availableKeys[0];106 newConfig.axisData.YAxis.key = [newConfig.axisData.YAxis.availableKeys[0]];107 newConfig.axisData.YAxis.label = [newConfig.axisData.YAxis.availableKeys[0]];108 }109 newConfig.summarize = {110 select: {},111 groupBy: '',112 };113 newConfig.isSummarize = false;114 }115 updateVisualization(newConfig);116 closeSidebar();117 };118 const selectSummarize = (summarize) => () => {119 if (summarize.isNeedArgument) {120 setCurrentSummarize(summarize);121 setIsSelectArgument(true);122 } else {123 setCurrentSummarize(summarize);124 setIsSummarize(true);125 setMenuAnchorEl(null);126 }127 };128 const selectArgument = (name) => () => {129 setCurrentSummarize({ ...currentSummarize, argument: name });130 setIsSummarize(true);131 setIsSelectArgument(false);132 setMenuAnchorEl(null);133 };134 const closeMenu = () => {135 setMenuAnchorEl(null);136 setIsSelectArgument(false);137 };138 return (139 <div style={{ width: '100%', display: 'flex', flexDirection: 'column' }}>140 <div>141 <h3>Summarize by</h3>142 {isSummarize && (143 <>144 <Button145 className={classes.summarizeByButton}146 color="primary"147 variant="outlined"148 fullWidth149 onClick={handleMenuClick}150 >151 {`${currentSummarize.name.replace('_', ' ')} ${currentSummarize.argument.replace('_', ' ')}`}152 <CloseIcon onClick={deleteSummarize} />153 </Button>154 </>155 )}156 {!isSummarize && (157 <>158 <Button color="primary" variant="outlined" fullWidth onClick={handleMenuClick}>159 Add a metric160 </Button>161 </>162 )}163 <Menu id="add-summarize" anchorEl={menuAnchorEl} keepMounted open={Boolean(menuAnchorEl)} onClose={closeMenu}>164 {!isSelectArgument &&165 summarizes.map((summarize) => (166 <MenuItem key={summarize.id} onClick={selectSummarize(summarize)}>167 {summarize.name.replace('_', ' ')}168 </MenuItem>169 ))}170 {isSelectArgument &&171 currentVisualization.schema172 .filter((column) => column.data_type === 'number')173 .map((column) => {174 return (175 <MenuItem key={column.column_name} onClick={selectArgument(column.column_name)}>176 {column.column_name.replace('_', ' ')}177 </MenuItem>178 );179 })}180 </Menu>181 </div>182 {isSummarize && (183 <div style={{ width: '100%', display: 'flex', flexDirection: 'column' }}>184 <h3>Group by</h3>185 {currentVisualization.schema.map((column) => (186 <GroupByList187 key={column.column_name}188 type={column.data_type}189 name={column.column_name}190 isActive={column.column_name === currentGroupBy.name}191 setCurrentGroupBy={setCurrentGroupBy}192 currentGroupBy={currentGroupBy}193 deleteGroupBy={deleteGroupBy}194 />195 ))}196 </div>197 )}198 <div className={classes.btnWrapper}>199 <Button200 color="primary"201 variant="contained"202 className={classes.summarizeDoneButton}203 disabled={isSummarize && !currentGroupBy.name}204 onClick={updateConfig}205 >206 Done207 </Button>208 </div>209 </div>210 );211};212SummarizeBar.propTypes = {213 currentVisualization: PropTypes.object,214 updateVisualization: PropTypes.func,215 closeSidebar: PropTypes.func,216};...

Full Screen

Full Screen

test_summarize.js

Source:test_summarize.js Github

copy

Full Screen

1'use strict'2const assert = require('assert')3const util = require('../libs/util')4const Summarize = require('../libs/summarize')5const TWO_ROWS = [{ones: 1, tens: 10},6 {ones: 2, tens: 20}]7const THREE_ROWS = [{ones: 3},8 {ones: 2},9 {ones: 2},10 {ones: 2},11 {ones: 1}]12describe('all', () => {13 it('requires a column name for all', (done) => {14 assert.throws(() => new Summarize.all(''),15 Error,16 `Should not be able to logical-and with empty column`)17 done()18 })19 it('does all on empty tables', (done) => {20 const op = new Summarize.all('name')21 assert.equal(op.run([]), util.MISSING,22 `Expected MISSING for empty table`)23 done()24 })25 it('does all on non-empty tables', (done) => {26 const op = new Summarize.all('name')27 assert.equal(op.run([{name: true}, {name: false}]),28 false,29 `Expected false`)30 done()31 })32})33describe('any', () => {34 it('requires a column name for any', (done) => {35 assert.throws(() => new Summarize.any(''),36 Error,37 `Should not be able to logical-or with empty column`)38 done()39 })40 it('does any on empty tables', (done) => {41 const op = new Summarize.any('name')42 assert.equal(op.run([]), util.MISSING,43 `Expected MISSING for empty table`)44 done()45 })46 it('does any on non-empty tables', (done) => {47 const op = new Summarize.any('name')48 assert.equal(op.run([{name: false}, {name: true}]), true,49 `Expected true`)50 done()51 })52})53describe('count', () => {54 it('requires a column name for count', (done) => {55 assert.throws(() => new Summarize.count(''),56 Error,57 `Should not be able to summarize empty column`)58 done()59 })60 it('counts empty tables', (done) => {61 const op = new Summarize.count('whatever')62 assert.equal(op.run([]), 0,63 `Expected zero rows`)64 done()65 })66 it('counts non-empty tables', (done) => {67 const op = new Summarize.count('whatever')68 assert.equal(op.run(TWO_ROWS), 2,69 `Expected two rows`)70 done()71 })72})73describe('maximum', () => {74 it('requires a valid column name for maximum', (done) => {75 assert.throws(() => new Summarize.maximum(147),76 Error,77 `Should not be able to summarize with integer for column name`)78 done()79 })80 it('finds maximum of empty tables', (done) => {81 const op = new Summarize.maximum('ones')82 assert.equal(op.run([]), util.MISSING,83 `Expected missing value`)84 done()85 })86 it('finds maximum of non-empty tables', (done) => {87 const op = new Summarize.maximum('ones')88 assert.equal(op.run(TWO_ROWS), 2,89 `Wrong value`)90 done()91 })92})93describe('mean', () => {94 it('requires a valid column name for mean', (done) => {95 assert.throws(() => new Summarize.mean(null),96 Error,97 `Should not be able to summarize with null column name`)98 done()99 })100 it('finds mean of empty tables', (done) => {101 const op = new Summarize.mean('ones')102 assert.equal(op.run([]), util.MISSING,103 `Expected missing value`)104 done()105 })106 it('finds mean of non-empty tables', (done) => {107 const op = new Summarize.mean('ones')108 assert.equal(op.run(TWO_ROWS), 1.5,109 `Wrong value`)110 done()111 })112})113describe('median', () => {114 it('requires a valid column name for median', (done) => {115 assert.throws(() => new Summarize.median(new Date()),116 Error,117 `Should not be able to summarize with date as column name`)118 done()119 })120 it('finds median of empty tables', (done) => {121 const op = new Summarize.median('ones')122 assert.equal(op.run([]), util.MISSING,123 `Expected missing value`)124 done()125 })126 it('finds median of non-empty tables', (done) => {127 const op = new Summarize.median('ones')128 assert.equal(op.run(TWO_ROWS), 1.5,129 `Wrong value`)130 done()131 })132 it('finds median of odd-sized tables', (done) => {133 const op = new Summarize.median('ones')134 assert.equal(op.run(THREE_ROWS), 2,135 `Wrong value`)136 done()137 })138})139describe('minimum', () => {140 it('requires a valid column name for minimum', (done) => {141 assert.throws(() => new Summarize.minimum(true),142 Error,143 `Should not be able to summarize with Boolean as column name`)144 done()145 })146 it('finds minimum of empty tables', (done) => {147 const op = new Summarize.minimum('ones')148 assert.equal(op.run([]), util.MISSING,149 `Expected missing value`)150 done()151 })152 it('finds minimum of non-empty tables', (done) => {153 const op = new Summarize.minimum('ones')154 assert.equal(op.run(TWO_ROWS), 1,155 `Wrong value`)156 done()157 })158 it('finds minimum of non-empty tables in reverse', (done) => {159 const temp = TWO_ROWS.slice().reverse()160 const op = new Summarize.minimum('ones')161 assert.equal(op.run(temp), 1,162 `Wrong value`)163 done()164 })165})166describe('standard deviation', () => {167 it('requires a valid column name for stdDev', (done) => {168 assert.throws(() => new Summarize.stdDev(util.MISSING),169 Error,170 `Should not be able to summarize with util.MISSING as column name`)171 done()172 })173 it('finds standard deviation of empty tables', (done) => {174 const op = new Summarize.stdDev('ones')175 assert.equal(op.run([]), util.MISSING,176 `Expected missing value`)177 done()178 })179 it('finds standard deviation of non-empty tables', (done) => {180 const op = new Summarize.stdDev('ones')181 assert.equal(op.run(TWO_ROWS), 0.5,182 `Wrong value`)183 done()184 })185})186describe('sum', () => {187 it('requires a valid column name for sum', (done) => {188 assert.throws(() => new Summarize.sum(''),189 Error,190 `Should not be able to summarize with empty column name`)191 done()192 })193 it('finds sum of empty tables', (done) => {194 const op = new Summarize.sum('ones')195 assert.equal(op.run([]), util.MISSING,196 `Expected missing value`)197 done()198 })199 it('finds sum of non-empty tables', (done) => {200 const op = new Summarize.sum('ones')201 assert.equal(op.run(TWO_ROWS), 3,202 `Wrong value`)203 done()204 })205})206describe('variance', () => {207 it('requires a valid column name for variance', (done) => {208 assert.throws(() => new Summarize.variance(77),209 Error,210 `Should not be able to summarize with number as column name`)211 done()212 })213 it('finds variance of empty tables', (done) => {214 const op = new Summarize.variance('ones')215 assert.equal(op.run([]), util.MISSING,216 `Expected missing value`)217 done()218 })219 it('finds variance of non-empty tables', (done) => {220 const op = new Summarize.variance('ones')221 assert.equal(op.run(TWO_ROWS), 0.25,222 `Wrong value`)223 done()224 })...

Full Screen

Full Screen

summarize.js

Source:summarize.js Github

copy

Full Screen

1'use strict'2const util = require('./util')3const stats = require('simple-statistics')4/**5 * Represent summarization as object.6 */7class SummarizeBase {8 /**9 * Construct.10 * @param {string} species Name of summarization function.11 * @param {string} column Which column to summarize.12 */13 constructor (species, column) {14 util.check(species && (typeof species === 'string') &&15 column && (typeof column === 'string'),16 `Require non-empty strings as species and column`)17 this.species = species18 this.column = column19 }20 run (rows, func) {21 util.check(typeof func === 'function',22 `Must provide callable function`)23 if (rows.length === 0) {24 return util.MISSING25 }26 return func(rows.map(row => row[this.column]))27 }28}29/**30 * Determine if all are true (logical and).31 */32class SummarizeAll extends SummarizeBase {33 constructor (column) {34 super('all', column)35 }36 run (rows) {37 return super.run(rows, (values) => values.every(x => x))38 }39}40/**41 * Determine if any are true (logical or).42 */43class SummarizeAny extends SummarizeBase {44 constructor (column) {45 super('any', column)46 }47 run (rows) {48 return super.run(rows, (values) => values.some(x => x))49 }50}51/**52 * Count rows.53 */54class SummarizeCount extends SummarizeBase {55 constructor (column) {56 super('count', column)57 }58 run (rows) {59 return rows.length60 }61}62/**63 * Find maximum value.64 */65class SummarizeMaximum extends SummarizeBase {66 constructor (column) {67 super('maximum', column)68 }69 run (rows) {70 return super.run(rows, stats.max)71 }72}73/**74 * Find the mean.75 */76class SummarizeMean extends SummarizeBase {77 constructor (column) {78 super('mean', column)79 }80 run (rows) {81 return super.run(rows, stats.mean)82 }83}84/**85 * Find the median.86 */87class SummarizeMedian extends SummarizeBase {88 constructor (column) {89 super('median', column)90 }91 run (rows) {92 return super.run(rows, stats.median)93 }94}95/**96 * Find the minimum.97 */98class SummarizeMinimum extends SummarizeBase {99 constructor (column) {100 super('minimum', column)101 }102 run (rows) {103 return super.run(rows, stats.min)104 }105}106/**107 * Find the standard deviation.108 */109class SummarizeStdDev extends SummarizeBase {110 constructor (column) {111 super('stdDev', column)112 }113 run (rows) {114 return super.run(rows, stats.standardDeviation)115 }116}117/**118 * Find the sum.119 */120class SummarizeSum extends SummarizeBase {121 constructor (column) {122 super('sum', column)123 }124 static Sum (values) {125 return values.reduce((total, v) => total + v, 0)126 }127 run (rows) {128 return super.run(rows, SummarizeSum.Sum)129 }130}131/**132 * Find the variance.133 */134class SummarizeVariance extends SummarizeBase {135 constructor (column) {136 super('variance', column)137 }138 run (rows) {139 return super.run(rows, stats.variance)140 }141}142module.exports = {143 base: SummarizeBase,144 all: SummarizeAll,145 any: SummarizeAny,146 count: SummarizeCount,147 maximum: SummarizeMaximum,148 mean: SummarizeMean,149 median: SummarizeMedian,150 minimum: SummarizeMinimum,151 stdDev: SummarizeStdDev,152 sum: SummarizeSum,153 variance: SummarizeVariance...

Full Screen

Full Screen

PivotTableSummarizeFunction.js

Source:PivotTableSummarizeFunction.js Github

copy

Full Screen

1exports.customForeign = function() {2 return SpreadsheetApp.PivotTableSummarizeFunction.CUSTOM;3}4exports.sumForeign = function() {5 return SpreadsheetApp.PivotTableSummarizeFunction.SUM;6}7exports.countaForeign = function() {8 return SpreadsheetApp.PivotTableSummarizeFunction.COUNTA;9}10exports.countForeign = function() {11 return SpreadsheetApp.PivotTableSummarizeFunction.COUNT;12}13exports.countuniqueForeign = function() {14 return SpreadsheetApp.PivotTableSummarizeFunction.COUNTUNIQUE;15}16exports.averageForeign = function() {17 return SpreadsheetApp.PivotTableSummarizeFunction.AVERAGE;18}19exports.maxForeign = function() {20 return SpreadsheetApp.PivotTableSummarizeFunction.MAX;21}22exports.minForeign = function() {23 return SpreadsheetApp.PivotTableSummarizeFunction.MIN;24}25exports.medianForeign = function() {26 return SpreadsheetApp.PivotTableSummarizeFunction.MEDIAN;27}28exports.productForeign = function() {29 return SpreadsheetApp.PivotTableSummarizeFunction.PRODUCT;30}31exports.stdevForeign = function() {32 return SpreadsheetApp.PivotTableSummarizeFunction.STDEV;33}34exports.stdevpForeign = function() {35 return SpreadsheetApp.PivotTableSummarizeFunction.STDEVP;36}37exports.varForeign = function() {38 return SpreadsheetApp.PivotTableSummarizeFunction.VAR;39}40exports.varpForeign = function() {41 return SpreadsheetApp.PivotTableSummarizeFunction.VARP;42}43exports.js2psImpl = (a) => (e) {44 switch (e) {45 case SpreadsheetApp.PivotTableSummarizeFunction.CUSTOM:46 return a[0];47 case SpreadsheetApp.PivotTableSummarizeFunction.SUM:48 return a[1];49 case SpreadsheetApp.PivotTableSummarizeFunction.COUNTA:50 return a[2];51 case SpreadsheetApp.PivotTableSummarizeFunction.COUNT:52 return a[3];53 case SpreadsheetApp.PivotTableSummarizeFunction.COUNTUNIQUE:54 return a[4];55 case SpreadsheetApp.PivotTableSummarizeFunction.AVERAGE:56 return a[5];57 case SpreadsheetApp.PivotTableSummarizeFunction.MAX:58 return a[6];59 case SpreadsheetApp.PivotTableSummarizeFunction.MIN:60 return a[7];61 case SpreadsheetApp.PivotTableSummarizeFunction.MEDIAN:62 return a[8];63 case SpreadsheetApp.PivotTableSummarizeFunction.PRODUCT:64 return a[9];65 case SpreadsheetApp.PivotTableSummarizeFunction.STDEV:66 return a[10];67 case SpreadsheetApp.PivotTableSummarizeFunction.STDEVP:68 return a[11];69 case SpreadsheetApp.PivotTableSummarizeFunction.VAR:70 return a[12];71 case SpreadsheetApp.PivotTableSummarizeFunction.VARP:72 return a[13];73 }...

Full Screen

Full Screen

test_plow-js_v2.1.x_connections.js

Source:test_plow-js_v2.1.x_connections.js Github

copy

Full Screen

...17const summarizeFinisher = (containsBar, containsBaz) => ({18 containsBar,19 containsBaz20});21plow.$summarize(summarizeOps, summarizeFinisher, { foo: ["baz"] }).containsBaz;22// $FlowExpectedError23plow.$summarize(summarizeOps, summarizeFinisher, { foo: ["baz"] }).foo;24plow.$summarize(summarizeOps, summarizeFinisher)({ foo: ["baz"] });25plow.$summarize(summarizeOps)(summarizeFinisher)({ foo: ["baz"] });26/**27 * `$traverse`28 */29plow.$traverse(x => x * 2, { foo: 1, bar: 3 });30// $FlowExpectedError31plow.$traverse(x => x * 2, { foo: 1, bar: 3 }) * 2;32plow.$traverse(x => x * 2)({ foo: 1, bar: 3 });33/**34 * `$log`35 */36plow.$log(["foo"], { foo: 1 }) * 2;...

Full Screen

Full Screen

constants.js

Source:constants.js Github

copy

Full Screen

1export const SUMMARIZE_SUMMARIZE_BEGIN = 'SUMMARIZE_SUMMARIZE_BEGIN';2export const SUMMARIZE_SUMMARIZE_SUCCESS = 'SUMMARIZE_SUMMARIZE_SUCCESS';3export const SUMMARIZE_SUMMARIZE_FAILURE = 'SUMMARIZE_SUMMARIZE_FAILURE';4export const SUMMARIZE_SUMMARIZE_DISMISS_ERROR = 'SUMMARIZE_SUMMARIZE_DISMISS_ERROR';5export const SUMMARIZE_LOAD_EXAMPLE_BEGIN = 'SUMMARIZE_LOAD_EXAMPLE_BEGIN';6export const SUMMARIZE_LOAD_EXAMPLE_SUCCESS = 'SUMMARIZE_LOAD_EXAMPLE_SUCCESS';7export const SUMMARIZE_LOAD_EXAMPLE_FAILURE = 'SUMMARIZE_LOAD_EXAMPLE_FAILURE';8export const SUMMARIZE_LOAD_EXAMPLE_DISMISS_ERROR = 'SUMMARIZE_LOAD_EXAMPLE_DISMISS_ERROR';9export const SUMMARIZE_RATE_SUMMARY_TEXT_BEGIN = 'SUMMARIZE_RATE_SUMMARY_TEXT_BEGIN';10export const SUMMARIZE_RATE_SUMMARY_TEXT_SUCCESS = 'SUMMARIZE_RATE_SUMMARY_TEXT_SUCCESS';11export const SUMMARIZE_RATE_SUMMARY_TEXT_FAILURE = 'SUMMARIZE_RATE_SUMMARY_TEXT_FAILURE';...

Full Screen

Full Screen

editor_plugin.js

Source:editor_plugin.js Github

copy

Full Screen

1(function() {2 tinymce.create('tinymce.plugins.summarize_posts', {3 init : function(ed, url){4 ed.addButton('summarize_posts', {5 title : 'Summarize Posts',6 onclick : function() {7 ed.execCommand(8 'mceInsertContent',9 false,10 show_summarize_posts() // <-- you must create this JS function!11 );12 },13 image: url + "/../images/summarize_posts_icon.png"14 });15 },16 getInfo : function() {17 return {18 longname : 'Summarize Posts',19 author : 'Everett Griffiths',20 authorurl : 'http://craftsmancoding.com',21 infourl : '',22 version : "0.8"23 };24 }25 });26 tinymce.PluginManager.add('summarize_posts', tinymce.plugins.summarize_posts);27 ...

Full Screen

Full Screen

Jest Testing Tutorial

LambdaTest’s Jest Testing Tutorial covers step-by-step guides around Jest with code examples to help you be proficient with the Jest framework. The Jest tutorial has chapters to help you learn right from the basics of Jest framework to code-based tutorials around testing react apps with Jest, perform snapshot testing, import ES modules and more.

Chapters

  1. What is Jest Framework
  2. Advantages of Jest - Jest has 3,898,000 GitHub repositories, as mentioned on its official website. Learn what makes Jest special and why Jest has gained popularity among the testing and developer community.
  3. Jest Installation - All the prerequisites and set up steps needed to help you start Jest automation testing.
  4. Using Jest with NodeJS Project - Learn how to leverage Jest framework to automate testing using a NodeJS Project.
  5. Writing First Test for Jest Framework - Get started with code-based tutorial to help you write and execute your first Jest framework testing script.
  6. Jest Vocabulary - Learn the industry renowned and official jargons of the Jest framework by digging deep into the Jest vocabulary.
  7. Unit Testing with Jest - Step-by-step tutorial to help you execute unit testing with Jest framework.
  8. Jest Basics - Learn about the most pivotal and basic features which makes Jest special.
  9. Jest Parameterized Tests - Avoid code duplication and fasten automation testing with Jest using parameterized tests. Parameterization allows you to trigger the same test scenario over different test configurations by incorporating parameters.
  10. Jest Matchers - Enforce assertions better with the help of matchers. Matchers help you compare the actual output with the expected one. Here is an example to see if the object is acquired from the correct class or not. -

|<p>it('check_object_of_Car', () => {</p><p> expect(newCar()).toBeInstanceOf(Car);</p><p> });</p>| | :- |

  1. Jest Hooks: Setup and Teardown - Learn how to set up conditions which needs to be followed by the test execution and incorporate a tear down function to free resources after the execution is complete.
  2. Jest Code Coverage - Unsure there is no code left unchecked in your application. Jest gives a specific flag called --coverage to help you generate code coverage.
  3. HTML Report Generation - Learn how to create a comprehensive HTML report based on your Jest test execution.
  4. Testing React app using Jest Framework - Learn how to test your react web-application with Jest framework in this detailed Jest tutorial.
  5. Test using LambdaTest cloud Selenium Grid - Run your Jest testing script over LambdaTest cloud-based platform and leverage parallel testing to help trim down your test execution time.
  6. Snapshot Testing for React Front Ends - Capture screenshots of your react based web-application and compare them automatically for visual anomalies with the help of Jest tutorial.
  7. Bonus: Import ES modules with Jest - ES modules are also known as ECMAScript modules. Learn how to best use them by importing in your Jest testing scripts.
  8. Jest vs Mocha vs Jasmine - Learn the key differences between the most popular JavaScript-based testing frameworks i.e. Jest, Mocha, and Jasmine.
  9. Jest FAQs(Frequently Asked Questions) - Explore the most commonly asked questions around Jest framework, with their answers.

Run Jest automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful