language
stringclasses 6
values | original_string
stringlengths 25
887k
| text
stringlengths 25
887k
|
---|---|---|
JavaScript | function processed_content_to_code(processed, location, file_basename) {
// Convert the preprocessed code and its sourcemap to a MappedCode
let decoded_map;
if (processed.map) {
decoded_map = decode_map(processed);
// offset only segments pointing at original component source
const source_index = decoded_map.sources.indexOf(file_basename);
if (source_index !== -1) {
sourcemap_add_offset(decoded_map, location, source_index);
}
}
return MappedCode.from_processed(processed.code, decoded_map);
} | function processed_content_to_code(processed, location, file_basename) {
// Convert the preprocessed code and its sourcemap to a MappedCode
let decoded_map;
if (processed.map) {
decoded_map = decode_map(processed);
// offset only segments pointing at original component source
const source_index = decoded_map.sources.indexOf(file_basename);
if (source_index !== -1) {
sourcemap_add_offset(decoded_map, location, source_index);
}
}
return MappedCode.from_processed(processed.code, decoded_map);
} |
JavaScript | function processed_tag_to_code(processed, tag_name, attributes, source) {
const { file_basename, get_location } = source;
const build_mapped_code = (code, offset) => MappedCode.from_source(slice_source(code, offset, source));
const tag_open = `<${tag_name}${attributes || ''}>`;
const tag_close = `</${tag_name}>`;
const tag_open_code = build_mapped_code(tag_open, 0);
const tag_close_code = build_mapped_code(tag_close, tag_open.length + source.source.length);
parse_attached_sourcemap(processed, tag_name);
const content_code = processed_content_to_code(processed, get_location(tag_open.length), file_basename);
return tag_open_code.concat(content_code).concat(tag_close_code);
} | function processed_tag_to_code(processed, tag_name, attributes, source) {
const { file_basename, get_location } = source;
const build_mapped_code = (code, offset) => MappedCode.from_source(slice_source(code, offset, source));
const tag_open = `<${tag_name}${attributes || ''}>`;
const tag_close = `</${tag_name}>`;
const tag_open_code = build_mapped_code(tag_open, 0);
const tag_close_code = build_mapped_code(tag_close, tag_open.length + source.source.length);
parse_attached_sourcemap(processed, tag_name);
const content_code = processed_content_to_code(processed, get_location(tag_open.length), file_basename);
return tag_open_code.concat(content_code).concat(tag_close_code);
} |
JavaScript | async function process_tag(tag_name, preprocessor, source) {
const { filename, source: markup } = source;
const tag_regex = tag_name === 'style'
? /<!--[^]*?-->|<style(\s[^]*?)?(?:>([^]*?)<\/style>|\/>)/gi
: /<!--[^]*?-->|<script(\s[^]*?)?(?:>([^]*?)<\/script>|\/>)/gi;
const dependencies = [];
async function process_single_tag(tag_with_content, attributes = '', content = '', tag_offset) {
const no_change = () => MappedCode.from_source(slice_source(tag_with_content, tag_offset, source));
if (!attributes && !content)
return no_change();
const processed = await preprocessor({
content: content || '',
attributes: parse_tag_attributes(attributes || ''),
markup,
filename
});
if (!processed)
return no_change();
if (processed.dependencies)
dependencies.push(...processed.dependencies);
if (!processed.map && processed.code === content)
return no_change();
return processed_tag_to_code(processed, tag_name, attributes, slice_source(content, tag_offset, source));
}
const { string, map } = await replace_in_code(tag_regex, process_single_tag, source);
return { string, map, dependencies };
} | async function process_tag(tag_name, preprocessor, source) {
const { filename, source: markup } = source;
const tag_regex = tag_name === 'style'
? /<!--[^]*?-->|<style(\s[^]*?)?(?:>([^]*?)<\/style>|\/>)/gi
: /<!--[^]*?-->|<script(\s[^]*?)?(?:>([^]*?)<\/script>|\/>)/gi;
const dependencies = [];
async function process_single_tag(tag_with_content, attributes = '', content = '', tag_offset) {
const no_change = () => MappedCode.from_source(slice_source(tag_with_content, tag_offset, source));
if (!attributes && !content)
return no_change();
const processed = await preprocessor({
content: content || '',
attributes: parse_tag_attributes(attributes || ''),
markup,
filename
});
if (!processed)
return no_change();
if (processed.dependencies)
dependencies.push(...processed.dependencies);
if (!processed.map && processed.code === content)
return no_change();
return processed_tag_to_code(processed, tag_name, attributes, slice_source(content, tag_offset, source));
}
const { string, map } = await replace_in_code(tag_regex, process_single_tag, source);
return { string, map, dependencies };
} |
JavaScript | function _luminance(color) {
color = this._decomposeColor(color);
if (color.type.indexOf('rgb') > -1) {
var rgb = color.values.map(function (val) {
val /= 255; // normalized
return val <= 0.03928 ? val / 12.92 : Math.pow((val + 0.055) / 1.055, 2.4);
});
return 0.2126 * rgb[0] + 0.7152 * rgb[1] + 0.0722 * rgb[2];
} else {
var message = 'Calculating the relative luminance is not available for ' + 'HSL and HSLA.';
console.error(message);
return -1;
}
} | function _luminance(color) {
color = this._decomposeColor(color);
if (color.type.indexOf('rgb') > -1) {
var rgb = color.values.map(function (val) {
val /= 255; // normalized
return val <= 0.03928 ? val / 12.92 : Math.pow((val + 0.055) / 1.055, 2.4);
});
return 0.2126 * rgb[0] + 0.7152 * rgb[1] + 0.0722 * rgb[2];
} else {
var message = 'Calculating the relative luminance is not available for ' + 'HSL and HSLA.';
console.error(message);
return -1;
}
} |
JavaScript | function _convertColorToString(color, additonalValue) {
var str = color.type + '(' + parseInt(color.values[0]) + ',' + parseInt(color.values[1]) + ',' + parseInt(color.values[2]);
if (additonalValue !== undefined) {
str += ',' + additonalValue + ')';
} else if (color.values.length === 4) {
str += ',' + color.values[3] + ')';
} else {
str += ')';
}
return str;
} | function _convertColorToString(color, additonalValue) {
var str = color.type + '(' + parseInt(color.values[0]) + ',' + parseInt(color.values[1]) + ',' + parseInt(color.values[2]);
if (additonalValue !== undefined) {
str += ',' + additonalValue + ')';
} else if (color.values.length === 4) {
str += ',' + color.values[3] + ')';
} else {
str += ')';
}
return str;
} |
JavaScript | function _convertHexToRGB(color) {
if (color.length === 4) {
var extendedColor = '#';
for (var i = 1; i < color.length; i++) {
extendedColor += color.charAt(i) + color.charAt(i);
}
color = extendedColor;
}
var values = {
r: parseInt(color.substr(1, 2), 16),
g: parseInt(color.substr(3, 2), 16),
b: parseInt(color.substr(5, 2), 16)
};
return 'rgb(' + values.r + ',' + values.g + ',' + values.b + ')';
} | function _convertHexToRGB(color) {
if (color.length === 4) {
var extendedColor = '#';
for (var i = 1; i < color.length; i++) {
extendedColor += color.charAt(i) + color.charAt(i);
}
color = extendedColor;
}
var values = {
r: parseInt(color.substr(1, 2), 16),
g: parseInt(color.substr(3, 2), 16),
b: parseInt(color.substr(5, 2), 16)
};
return 'rgb(' + values.r + ',' + values.g + ',' + values.b + ')';
} |
JavaScript | function _decomposeColor(color) {
if (color.charAt(0) === '#') {
return this._decomposeColor(this._convertHexToRGB(color));
}
var marker = color.indexOf('(');
var type = color.substring(0, marker);
var values = color.substring(marker + 1, color.length - 1).split(',');
return { type: type, values: values };
} | function _decomposeColor(color) {
if (color.charAt(0) === '#') {
return this._decomposeColor(this._convertHexToRGB(color));
}
var marker = color.indexOf('(');
var type = color.substring(0, marker);
var values = color.substring(marker + 1, color.length - 1).split(',');
return { type: type, values: values };
} |
JavaScript | function lighten(color, amount) {
color = this._decomposeColor(color);
if (color.type.indexOf('hsl') > -1) {
color.values[2] += amount;
return this._decomposeColor(this._convertColorToString(color));
} else if (color.type.indexOf('rgb') > -1) {
for (var i = 0; i < 3; i++) {
color.values[i] *= 1 + amount;
if (color.values[i] > 255) color.values[i] = 255;
}
}
if (color.type.indexOf('a') <= -1) color.type += 'a';
return this._convertColorToString(color, '0.15');
} | function lighten(color, amount) {
color = this._decomposeColor(color);
if (color.type.indexOf('hsl') > -1) {
color.values[2] += amount;
return this._decomposeColor(this._convertColorToString(color));
} else if (color.type.indexOf('rgb') > -1) {
for (var i = 0; i < 3; i++) {
color.values[i] *= 1 + amount;
if (color.values[i] > 255) color.values[i] = 255;
}
}
if (color.type.indexOf('a') <= -1) color.type += 'a';
return this._convertColorToString(color, '0.15');
} |
JavaScript | function contrastRatioLevel(background, foreground) {
var levels = {
'fail': {
range: [0, 3],
color: 'hsl(0, 100%, 40%)'
},
'aa-large': {
range: [3, 4.5],
color: 'hsl(40, 100%, 45%)'
},
'aa': {
range: [4.5, 7],
color: 'hsl(80, 60%, 45%)'
},
'aaa': {
range: [7, 22],
color: 'hsl(95, 60%, 41%)'
}
};
var ratio = this.contrastRatio(background, foreground);
for (var level in levels) {
var range = levels[level].range;
if (ratio >= range[0] && ratio <= range[1]) return level;
}
} | function contrastRatioLevel(background, foreground) {
var levels = {
'fail': {
range: [0, 3],
color: 'hsl(0, 100%, 40%)'
},
'aa-large': {
range: [3, 4.5],
color: 'hsl(40, 100%, 45%)'
},
'aa': {
range: [4.5, 7],
color: 'hsl(80, 60%, 45%)'
},
'aaa': {
range: [7, 22],
color: 'hsl(95, 60%, 41%)'
}
};
var ratio = this.contrastRatio(background, foreground);
for (var level in levels) {
var range = levels[level].range;
if (ratio >= range[0] && ratio <= range[1]) return level;
}
} |
JavaScript | function ensureDirection(muiTheme, style) {
if (true) {
if (style.didFlip) {
console.warn(new Error('You\'re calling `ensureDirection` on the same style object twice.'));
}
style = _utilsImmutabilityHelper2['default'].merge({
didFlip: 'true'
}, style);
}
// Left to right is the default. No need to flip anything.
if (!muiTheme.isRtl) return style;
var flippedAttributes = {
// Keys and their replacements.
right: 'left',
left: 'right',
marginRight: 'marginLeft',
marginLeft: 'marginRight',
paddingRight: 'paddingLeft',
paddingLeft: 'paddingRight',
borderRight: 'borderLeft',
borderLeft: 'borderRight'
};
var newStyle = {};
Object.keys(style).forEach(function (attribute) {
var value = style[attribute];
var key = attribute;
if (flippedAttributes.hasOwnProperty(attribute)) {
key = flippedAttributes[attribute];
}
switch (attribute) {
case 'float':
case 'textAlign':
if (value === 'right') {
value = 'left';
} else if (value === 'left') {
value = 'right';
}
break;
case 'direction':
if (value === 'ltr') {
value = 'rtl';
} else if (value === 'rtl') {
value = 'ltr';
}
break;
case 'transform':
var matches = undefined;
if (matches = value.match(reTranslate)) {
value = value.replace(matches[0], matches[1] + -parseFloat(matches[4]));
}
if (matches = value.match(reSkew)) {
value = value.replace(matches[0], matches[1] + -parseFloat(matches[4]) + matches[5] + matches[6] ? ',' + -parseFloat(matches[7]) + matches[8] : '');
}
break;
case 'transformOrigin':
if (value.indexOf('right') > -1) {
value = value.replace('right', 'left');
} else if (value.indexOf('left') > -1) {
value = value.replace('left', 'right');
}
break;
}
newStyle[key] = value;
});
return newStyle;
} | function ensureDirection(muiTheme, style) {
if (true) {
if (style.didFlip) {
console.warn(new Error('You\'re calling `ensureDirection` on the same style object twice.'));
}
style = _utilsImmutabilityHelper2['default'].merge({
didFlip: 'true'
}, style);
}
// Left to right is the default. No need to flip anything.
if (!muiTheme.isRtl) return style;
var flippedAttributes = {
// Keys and their replacements.
right: 'left',
left: 'right',
marginRight: 'marginLeft',
marginLeft: 'marginRight',
paddingRight: 'paddingLeft',
paddingLeft: 'paddingRight',
borderRight: 'borderLeft',
borderLeft: 'borderRight'
};
var newStyle = {};
Object.keys(style).forEach(function (attribute) {
var value = style[attribute];
var key = attribute;
if (flippedAttributes.hasOwnProperty(attribute)) {
key = flippedAttributes[attribute];
}
switch (attribute) {
case 'float':
case 'textAlign':
if (value === 'right') {
value = 'left';
} else if (value === 'left') {
value = 'right';
}
break;
case 'direction':
if (value === 'ltr') {
value = 'rtl';
} else if (value === 'rtl') {
value = 'ltr';
}
break;
case 'transform':
var matches = undefined;
if (matches = value.match(reTranslate)) {
value = value.replace(matches[0], matches[1] + -parseFloat(matches[4]));
}
if (matches = value.match(reSkew)) {
value = value.replace(matches[0], matches[1] + -parseFloat(matches[4]) + matches[5] + matches[6] ? ',' + -parseFloat(matches[7]) + matches[8] : '');
}
break;
case 'transformOrigin':
if (value.indexOf('right') > -1) {
value = value.replace('right', 'left');
} else if (value.indexOf('left') > -1) {
value = value.replace('left', 'right');
}
break;
}
newStyle[key] = value;
});
return newStyle;
} |
JavaScript | function computeNextEntry(reducer, action, state, error) {
if (error) {
return {
state: state,
error: 'Interrupted by an error up the chain'
};
}
var nextState = state;
var nextError = undefined;
try {
nextState = reducer(state, action);
} catch (err) {
nextError = err.toString();
if ((typeof window === 'undefined' ? 'undefined' : _typeof(window)) === 'object' && typeof window.chrome !== 'undefined') {
// In Chrome, rethrowing provides better source map support
setTimeout(function () {
throw err;
});
} else {
console.error(err.stack || err);
}
}
return {
state: nextState,
error: nextError
};
} | function computeNextEntry(reducer, action, state, error) {
if (error) {
return {
state: state,
error: 'Interrupted by an error up the chain'
};
}
var nextState = state;
var nextError = undefined;
try {
nextState = reducer(state, action);
} catch (err) {
nextError = err.toString();
if ((typeof window === 'undefined' ? 'undefined' : _typeof(window)) === 'object' && typeof window.chrome !== 'undefined') {
// In Chrome, rethrowing provides better source map support
setTimeout(function () {
throw err;
});
} else {
console.error(err.stack || err);
}
}
return {
state: nextState,
error: nextError
};
} |
JavaScript | function liftReducerWith(reducer, initialCommittedState, monitorReducer) {
var initialLiftedState = {
monitorState: monitorReducer(undefined, {}),
nextActionId: 1,
actionsById: { 0: liftAction(INIT_ACTION) },
stagedActionIds: [0],
skippedActionIds: [],
committedState: initialCommittedState,
currentStateIndex: 0,
computedStates: []
};
/**
* Manages how the history actions modify the history state.
*/
return function () {
var liftedState = arguments.length <= 0 || arguments[0] === undefined ? initialLiftedState : arguments[0];
var liftedAction = arguments[1];
var monitorState = liftedState.monitorState;
var actionsById = liftedState.actionsById;
var nextActionId = liftedState.nextActionId;
var stagedActionIds = liftedState.stagedActionIds;
var skippedActionIds = liftedState.skippedActionIds;
var committedState = liftedState.committedState;
var currentStateIndex = liftedState.currentStateIndex;
var computedStates = liftedState.computedStates;
// By default, agressively recompute every state whatever happens.
// This has O(n) performance, so we'll override this to a sensible
// value whenever we feel like we don't have to recompute the states.
var minInvalidatedStateIndex = 0;
switch (liftedAction.type) {
case ActionTypes.RESET:
{
// Get back to the state the store was created with.
actionsById = { 0: liftAction(INIT_ACTION) };
nextActionId = 1;
stagedActionIds = [0];
skippedActionIds = [];
committedState = initialCommittedState;
currentStateIndex = 0;
computedStates = [];
break;
}
case ActionTypes.COMMIT:
{
// Consider the last committed state the new starting point.
// Squash any staged actions into a single committed state.
actionsById = { 0: liftAction(INIT_ACTION) };
nextActionId = 1;
stagedActionIds = [0];
skippedActionIds = [];
committedState = computedStates[currentStateIndex].state;
currentStateIndex = 0;
computedStates = [];
break;
}
case ActionTypes.ROLLBACK:
{
// Forget about any staged actions.
// Start again from the last committed state.
actionsById = { 0: liftAction(INIT_ACTION) };
nextActionId = 1;
stagedActionIds = [0];
skippedActionIds = [];
currentStateIndex = 0;
computedStates = [];
break;
}
case ActionTypes.TOGGLE_ACTION:
{
var _ret = (function () {
// Toggle whether an action with given ID is skipped.
// Being skipped means it is a no-op during the computation.
var actionId = liftedAction.id;
var index = skippedActionIds.indexOf(actionId);
if (index === -1) {
skippedActionIds = [actionId].concat(skippedActionIds);
} else {
skippedActionIds = skippedActionIds.filter(function (id) {
return id !== actionId;
});
}
// Optimization: we know history before this action hasn't changed
minInvalidatedStateIndex = stagedActionIds.indexOf(actionId);
return 'break';
})();
if (_ret === 'break') break;
}
case ActionTypes.JUMP_TO_STATE:
{
// Without recomputing anything, move the pointer that tell us
// which state is considered the current one. Useful for sliders.
currentStateIndex = liftedAction.index;
// Optimization: we know the history has not changed.
minInvalidatedStateIndex = Infinity;
break;
}
case ActionTypes.SWEEP:
{
// Forget any actions that are currently being skipped.
stagedActionIds = (0, _difference2.default)(stagedActionIds, skippedActionIds);
skippedActionIds = [];
currentStateIndex = Math.min(currentStateIndex, stagedActionIds.length - 1);
break;
}
case ActionTypes.PERFORM_ACTION:
{
if (currentStateIndex === stagedActionIds.length - 1) {
currentStateIndex++;
}
var actionId = nextActionId++;
// Mutation! This is the hottest path, and we optimize on purpose.
// It is safe because we set a new key in a cache dictionary.
actionsById[actionId] = liftedAction;
stagedActionIds = [].concat(stagedActionIds, [actionId]);
// Optimization: we know that only the new action needs computing.
minInvalidatedStateIndex = stagedActionIds.length - 1;
break;
}
case ActionTypes.IMPORT_STATE:
{
var _liftedAction$nextLif = liftedAction.nextLiftedState;
// Completely replace everything.
monitorState = _liftedAction$nextLif.monitorState;
actionsById = _liftedAction$nextLif.actionsById;
nextActionId = _liftedAction$nextLif.nextActionId;
stagedActionIds = _liftedAction$nextLif.stagedActionIds;
skippedActionIds = _liftedAction$nextLif.skippedActionIds;
committedState = _liftedAction$nextLif.committedState;
currentStateIndex = _liftedAction$nextLif.currentStateIndex;
computedStates = _liftedAction$nextLif.computedStates;
break;
}
case '@@redux/INIT':
{
// Always recompute states on hot reload and init.
minInvalidatedStateIndex = 0;
break;
}
default:
{
// If the action is not recognized, it's a monitor action.
// Optimization: a monitor action can't change history.
minInvalidatedStateIndex = Infinity;
break;
}
}
computedStates = recomputeStates(computedStates, minInvalidatedStateIndex, reducer, committedState, actionsById, stagedActionIds, skippedActionIds);
monitorState = monitorReducer(monitorState, liftedAction);
return {
monitorState: monitorState,
actionsById: actionsById,
nextActionId: nextActionId,
stagedActionIds: stagedActionIds,
skippedActionIds: skippedActionIds,
committedState: committedState,
currentStateIndex: currentStateIndex,
computedStates: computedStates
};
};
} | function liftReducerWith(reducer, initialCommittedState, monitorReducer) {
var initialLiftedState = {
monitorState: monitorReducer(undefined, {}),
nextActionId: 1,
actionsById: { 0: liftAction(INIT_ACTION) },
stagedActionIds: [0],
skippedActionIds: [],
committedState: initialCommittedState,
currentStateIndex: 0,
computedStates: []
};
/**
* Manages how the history actions modify the history state.
*/
return function () {
var liftedState = arguments.length <= 0 || arguments[0] === undefined ? initialLiftedState : arguments[0];
var liftedAction = arguments[1];
var monitorState = liftedState.monitorState;
var actionsById = liftedState.actionsById;
var nextActionId = liftedState.nextActionId;
var stagedActionIds = liftedState.stagedActionIds;
var skippedActionIds = liftedState.skippedActionIds;
var committedState = liftedState.committedState;
var currentStateIndex = liftedState.currentStateIndex;
var computedStates = liftedState.computedStates;
// By default, agressively recompute every state whatever happens.
// This has O(n) performance, so we'll override this to a sensible
// value whenever we feel like we don't have to recompute the states.
var minInvalidatedStateIndex = 0;
switch (liftedAction.type) {
case ActionTypes.RESET:
{
// Get back to the state the store was created with.
actionsById = { 0: liftAction(INIT_ACTION) };
nextActionId = 1;
stagedActionIds = [0];
skippedActionIds = [];
committedState = initialCommittedState;
currentStateIndex = 0;
computedStates = [];
break;
}
case ActionTypes.COMMIT:
{
// Consider the last committed state the new starting point.
// Squash any staged actions into a single committed state.
actionsById = { 0: liftAction(INIT_ACTION) };
nextActionId = 1;
stagedActionIds = [0];
skippedActionIds = [];
committedState = computedStates[currentStateIndex].state;
currentStateIndex = 0;
computedStates = [];
break;
}
case ActionTypes.ROLLBACK:
{
// Forget about any staged actions.
// Start again from the last committed state.
actionsById = { 0: liftAction(INIT_ACTION) };
nextActionId = 1;
stagedActionIds = [0];
skippedActionIds = [];
currentStateIndex = 0;
computedStates = [];
break;
}
case ActionTypes.TOGGLE_ACTION:
{
var _ret = (function () {
// Toggle whether an action with given ID is skipped.
// Being skipped means it is a no-op during the computation.
var actionId = liftedAction.id;
var index = skippedActionIds.indexOf(actionId);
if (index === -1) {
skippedActionIds = [actionId].concat(skippedActionIds);
} else {
skippedActionIds = skippedActionIds.filter(function (id) {
return id !== actionId;
});
}
// Optimization: we know history before this action hasn't changed
minInvalidatedStateIndex = stagedActionIds.indexOf(actionId);
return 'break';
})();
if (_ret === 'break') break;
}
case ActionTypes.JUMP_TO_STATE:
{
// Without recomputing anything, move the pointer that tell us
// which state is considered the current one. Useful for sliders.
currentStateIndex = liftedAction.index;
// Optimization: we know the history has not changed.
minInvalidatedStateIndex = Infinity;
break;
}
case ActionTypes.SWEEP:
{
// Forget any actions that are currently being skipped.
stagedActionIds = (0, _difference2.default)(stagedActionIds, skippedActionIds);
skippedActionIds = [];
currentStateIndex = Math.min(currentStateIndex, stagedActionIds.length - 1);
break;
}
case ActionTypes.PERFORM_ACTION:
{
if (currentStateIndex === stagedActionIds.length - 1) {
currentStateIndex++;
}
var actionId = nextActionId++;
// Mutation! This is the hottest path, and we optimize on purpose.
// It is safe because we set a new key in a cache dictionary.
actionsById[actionId] = liftedAction;
stagedActionIds = [].concat(stagedActionIds, [actionId]);
// Optimization: we know that only the new action needs computing.
minInvalidatedStateIndex = stagedActionIds.length - 1;
break;
}
case ActionTypes.IMPORT_STATE:
{
var _liftedAction$nextLif = liftedAction.nextLiftedState;
// Completely replace everything.
monitorState = _liftedAction$nextLif.monitorState;
actionsById = _liftedAction$nextLif.actionsById;
nextActionId = _liftedAction$nextLif.nextActionId;
stagedActionIds = _liftedAction$nextLif.stagedActionIds;
skippedActionIds = _liftedAction$nextLif.skippedActionIds;
committedState = _liftedAction$nextLif.committedState;
currentStateIndex = _liftedAction$nextLif.currentStateIndex;
computedStates = _liftedAction$nextLif.computedStates;
break;
}
case '@@redux/INIT':
{
// Always recompute states on hot reload and init.
minInvalidatedStateIndex = 0;
break;
}
default:
{
// If the action is not recognized, it's a monitor action.
// Optimization: a monitor action can't change history.
minInvalidatedStateIndex = Infinity;
break;
}
}
computedStates = recomputeStates(computedStates, minInvalidatedStateIndex, reducer, committedState, actionsById, stagedActionIds, skippedActionIds);
monitorState = monitorReducer(monitorState, liftedAction);
return {
monitorState: monitorState,
actionsById: actionsById,
nextActionId: nextActionId,
stagedActionIds: stagedActionIds,
skippedActionIds: skippedActionIds,
committedState: committedState,
currentStateIndex: currentStateIndex,
computedStates: computedStates
};
};
} |
JavaScript | function CoreLayout(_ref) {
var children = _ref.children;
return React.createElement(
'div',
{ className: 'page-container' },
React.createElement(
'div',
{ className: 'view-container' },
children
)
);
} | function CoreLayout(_ref) {
var children = _ref.children;
return React.createElement(
'div',
{ className: 'page-container' },
React.createElement(
'div',
{ className: 'view-container' },
children
)
);
} |
JavaScript | function onPlayerStateChange(event) {
if (event.data == YT.PlayerState.ENDED) {
that.playNext.bind(that)();
}
} | function onPlayerStateChange(event) {
if (event.data == YT.PlayerState.ENDED) {
that.playNext.bind(that)();
}
} |
JavaScript | function Prefixer() {
var _this = this;
var userAgent = arguments.length <= 0 || arguments[0] === undefined ? defaultUserAgent : arguments[0];
_classCallCheck(this, Prefixer);
this._userAgent = userAgent;
this._browserInfo = (0, _getBrowserInformation2['default'])(userAgent);
// Checks if the userAgent was resolved correctly
if (this._browserInfo && this._browserInfo.prefix) {
this.cssPrefix = this._browserInfo.prefix.CSS;
this.jsPrefix = this._browserInfo.prefix.inline;
this.prefixedKeyframes = (0, _getPrefixedKeyframes2['default'])(this._browserInfo);
} else {
this._hasPropsRequiringPrefix = false;
warn('Either the global navigator was undefined or an invalid userAgent was provided.', 'Using a valid userAgent? Please let us know and create an issue at https://github.com/rofrischmann/inline-style-prefixer/issues');
return false;
}
var data = this._browserInfo.browser && _caniuseData2['default'][this._browserInfo.browser];
if (data) {
this._requiresPrefix = Object.keys(data).filter(function (key) {
return data[key] >= _this._browserInfo.version;
}).reduce(function (result, name) {
result[name] = true;
return result;
}, {});
this._hasPropsRequiringPrefix = Object.keys(this._requiresPrefix).length > 0;
} else {
this._hasPropsRequiringPrefix = false;
warn('Your userAgent seems to be not supported by inline-style-prefixer. Feel free to open an issue.');
return false;
}
} | function Prefixer() {
var _this = this;
var userAgent = arguments.length <= 0 || arguments[0] === undefined ? defaultUserAgent : arguments[0];
_classCallCheck(this, Prefixer);
this._userAgent = userAgent;
this._browserInfo = (0, _getBrowserInformation2['default'])(userAgent);
// Checks if the userAgent was resolved correctly
if (this._browserInfo && this._browserInfo.prefix) {
this.cssPrefix = this._browserInfo.prefix.CSS;
this.jsPrefix = this._browserInfo.prefix.inline;
this.prefixedKeyframes = (0, _getPrefixedKeyframes2['default'])(this._browserInfo);
} else {
this._hasPropsRequiringPrefix = false;
warn('Either the global navigator was undefined or an invalid userAgent was provided.', 'Using a valid userAgent? Please let us know and create an issue at https://github.com/rofrischmann/inline-style-prefixer/issues');
return false;
}
var data = this._browserInfo.browser && _caniuseData2['default'][this._browserInfo.browser];
if (data) {
this._requiresPrefix = Object.keys(data).filter(function (key) {
return data[key] >= _this._browserInfo.version;
}).reduce(function (result, name) {
result[name] = true;
return result;
}, {});
this._hasPropsRequiringPrefix = Object.keys(this._requiresPrefix).length > 0;
} else {
this._hasPropsRequiringPrefix = false;
warn('Your userAgent seems to be not supported by inline-style-prefixer. Feel free to open an issue.');
return false;
}
} |
JavaScript | function shouldComponentUpdate(nextProps, nextState, nextContext) {
//If either the props or state have changed, component should update
if (!(0, _utilsShallowEqual2['default'])(this.props, nextProps) || !(0, _utilsShallowEqual2['default'])(this.state, nextState)) {
return true;
}
//If current theme and next theme are both undefined, do not update
if (!this.context.muiTheme && !nextContext.muiTheme) {
return false;
}
//If both themes exist, compare keys only if current theme is not static
if (this.context.muiTheme && nextContext.muiTheme) {
return !this.context.muiTheme['static'] && !relevantContextKeysEqual(this.constructor, this.context.muiTheme, nextContext.muiTheme);
}
//At this point it is guaranteed that exactly one theme is undefined so simply update
return true;
} | function shouldComponentUpdate(nextProps, nextState, nextContext) {
//If either the props or state have changed, component should update
if (!(0, _utilsShallowEqual2['default'])(this.props, nextProps) || !(0, _utilsShallowEqual2['default'])(this.state, nextState)) {
return true;
}
//If current theme and next theme are both undefined, do not update
if (!this.context.muiTheme && !nextContext.muiTheme) {
return false;
}
//If both themes exist, compare keys only if current theme is not static
if (this.context.muiTheme && nextContext.muiTheme) {
return !this.context.muiTheme['static'] && !relevantContextKeysEqual(this.constructor, this.context.muiTheme, nextContext.muiTheme);
}
//At this point it is guaranteed that exactly one theme is undefined so simply update
return true;
} |
JavaScript | function componentWillReceiveProps(nextProps, nextContext) {
this._setTooltipPosition();
var newMuiTheme = nextContext.muiTheme ? nextContext.muiTheme : this.state.muiTheme;
this.setState({ muiTheme: newMuiTheme });
} | function componentWillReceiveProps(nextProps, nextContext) {
this._setTooltipPosition();
var newMuiTheme = nextContext.muiTheme ? nextContext.muiTheme : this.state.muiTheme;
this.setState({ muiTheme: newMuiTheme });
} |
JavaScript | function onPlayerStateChange(event) {
if (event.data == YT.PlayerState.ENDED) {
var next = that.props.tracks.payload.results.sort(function (a, b) {
return a.trackNumber - b.trackNumber;
})[that.state.track.index + 1];
that.chooseTrack({ t: next, index: that.state.track.index + 1 });
}
} | function onPlayerStateChange(event) {
if (event.data == YT.PlayerState.ENDED) {
var next = that.props.tracks.payload.results.sort(function (a, b) {
return a.trackNumber - b.trackNumber;
})[that.state.track.index + 1];
that.chooseTrack({ t: next, index: that.state.track.index + 1 });
}
} |
JavaScript | function onPlayerStateChange(event) {
if (event.data == YT.PlayerState.ENDED) {
that.playNext.bind(that)();
}
} | function onPlayerStateChange(event) {
if (event.data == YT.PlayerState.ENDED) {
that.playNext.bind(that)();
}
} |
JavaScript | function parseLocalStorage(){
var previousProductsArr =JSON.parse(localStorage.getItem('savedProducts'))
//console.log(previousProductsArr);
// this funtcion will update the newly created objects with the old literation values
update(previousProductsArr);
} | function parseLocalStorage(){
var previousProductsArr =JSON.parse(localStorage.getItem('savedProducts'))
//console.log(previousProductsArr);
// this funtcion will update the newly created objects with the old literation values
update(previousProductsArr);
} |
JavaScript | activate(nTiles) {
let num = int(nTiles);
for (let n = 0; n < num; n++) {
// this.tiles[int(random(0, this.tiles.length))].activateState();
random(this.tiles).activateState();
}
} | activate(nTiles) {
let num = int(nTiles);
for (let n = 0; n < num; n++) {
// this.tiles[int(random(0, this.tiles.length))].activateState();
random(this.tiles).activateState();
}
} |
JavaScript | update() {
let ignoreList = [];
for (let iy = 0; iy < this.rows; iy++) {
for (let ix = 0; ix < this.cols; ix++) {
let currentTile = ix + iy * this.cols; // current tile index
if (this.tiles[currentTile].inTransition()) {
this.tiles[currentTile].updateState();
} else if (this.tiles[currentTile].inActiveState() &&
random() < PROB_MOVEMENT &&
!ignoreList.includes(currentTile)) {
let options = [] // available tiles to move to
for (let t of this.tiles[currentTile].validTiles) {
if (this.tiles[t.id].inNonActiveState()) {
options.push(t);
}
}
if (options.length > 0) {
let choice = random(options);
let newTile = choice.id;
this.tiles[currentTile].setTransitionState(true, choice.dir);
this.tiles[newTile].setTransitionState(false, choice.dir);
// new tile should not be considered for starting a transition
ignoreList.push(newTile);
}
}
}
}
} | update() {
let ignoreList = [];
for (let iy = 0; iy < this.rows; iy++) {
for (let ix = 0; ix < this.cols; ix++) {
let currentTile = ix + iy * this.cols; // current tile index
if (this.tiles[currentTile].inTransition()) {
this.tiles[currentTile].updateState();
} else if (this.tiles[currentTile].inActiveState() &&
random() < PROB_MOVEMENT &&
!ignoreList.includes(currentTile)) {
let options = [] // available tiles to move to
for (let t of this.tiles[currentTile].validTiles) {
if (this.tiles[t.id].inNonActiveState()) {
options.push(t);
}
}
if (options.length > 0) {
let choice = random(options);
let newTile = choice.id;
this.tiles[currentTile].setTransitionState(true, choice.dir);
this.tiles[newTile].setTransitionState(false, choice.dir);
// new tile should not be considered for starting a transition
ignoreList.push(newTile);
}
}
}
}
} |
JavaScript | function arrow(base, vec, myColor, weight) {
if (!weight) weight = 3;
if (vec.mag() > 0) {
push();
stroke(myColor);
strokeWeight(weight);
fill(myColor);
translate(base.x, base.y);
line(0, 0, vec.x, vec.y);
rotate(vec.heading());
let arrowSize = 7;
translate(vec.mag() - arrowSize, 0);
triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);
pop();
}
} | function arrow(base, vec, myColor, weight) {
if (!weight) weight = 3;
if (vec.mag() > 0) {
push();
stroke(myColor);
strokeWeight(weight);
fill(myColor);
translate(base.x, base.y);
line(0, 0, vec.x, vec.y);
rotate(vec.heading());
let arrowSize = 7;
translate(vec.mag() - arrowSize, 0);
triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);
pop();
}
} |
JavaScript | async function likePost(id){
await service.like(id);
let res= await service.like_count(id);
let div=document.getElementById("count"+id);
div.innerText=res;
} | async function likePost(id){
await service.like(id);
let res= await service.like_count(id);
let div=document.getElementById("count"+id);
div.innerText=res;
} |
JavaScript | createHTicks(store) {
const tickValues = this.getHTickValues(store);
// Limits labels on the ticks so they fit in the view.
const labelFreq = Math.ceil(tickValues.length / 10);
return tickValues.filter((val, i) => i % labelFreq == 0)
.map((val) => this.formatTick(val, formatter.formatTime(
val + store.absStart)));
} | createHTicks(store) {
const tickValues = this.getHTickValues(store);
// Limits labels on the ticks so they fit in the view.
const labelFreq = Math.ceil(tickValues.length / 10);
return tickValues.filter((val, i) => i % labelFreq == 0)
.map((val) => this.formatTick(val, formatter.formatTime(
val + store.absStart)));
} |
JavaScript | createVTicks(store) {
const tickDisplayValues = this.getVTickDisplayValues(store);
return tickDisplayValues.map((val, i) => this.formatTick(
this.getRenderOffset(i + 1, store), val));
} | createVTicks(store) {
const tickDisplayValues = this.getVTickDisplayValues(store);
return tickDisplayValues.map((val, i) => this.formatTick(
this.getRenderOffset(i + 1, store), val));
} |
JavaScript | createDataTable(store) {
const numSeries = store.chunkGraphData.cols.length - 1;
const dataTable = new DataTable();
dataTable.addColumn('number', 'seconds');
for (let i = 0; i < numSeries; i++) {
dataTable.addColumn('number', 'placeholder');
}
const axisData = array.range(0, (this.getNumSecs(store) + 1))
.map((i) => [i + this.getStart(store)]);
const colData = array.range(0, numSeries)
.map((x, i) => (numSeries - i - 1) * store.seriesHeight);
const rowData = axisData.map(x => x.concat(colData));
dataTable.addRows(rowData);
return dataTable;
} | createDataTable(store) {
const numSeries = store.chunkGraphData.cols.length - 1;
const dataTable = new DataTable();
dataTable.addColumn('number', 'seconds');
for (let i = 0; i < numSeries; i++) {
dataTable.addColumn('number', 'placeholder');
}
const axisData = array.range(0, (this.getNumSecs(store) + 1))
.map((i) => [i + this.getStart(store)]);
const colData = array.range(0, numSeries)
.map((x, i) => (numSeries - i - 1) * store.seriesHeight);
const rowData = axisData.map(x => x.concat(colData));
dataTable.addRows(rowData);
return dataTable;
} |
JavaScript | updateChartOptions(store) {
const percentage = this.height[store.predictionMode];
const parentHeight = this.getParent().clientHeight;
const containerHeight = Math.ceil(
percentage * parentHeight) - 2 * marginHeight;
this.setOption('height', containerHeight);
const chartPercentage = 1 - axisLabelHeight / containerHeight;
this.setOption('chartArea.height',
`${Math.floor(100 * chartPercentage)}%`);
this.setOption('hAxis.ticks', this.createHTicks(store));
this.setOption('vAxis.ticks', this.createVTicks(store));
} | updateChartOptions(store) {
const percentage = this.height[store.predictionMode];
const parentHeight = this.getParent().clientHeight;
const containerHeight = Math.ceil(
percentage * parentHeight) - 2 * marginHeight;
this.setOption('height', containerHeight);
const chartPercentage = 1 - axisLabelHeight / containerHeight;
this.setOption('chartArea.height',
`${Math.floor(100 * chartPercentage)}%`);
this.setOption('hAxis.ticks', this.createHTicks(store));
this.setOption('vAxis.ticks', this.createVTicks(store));
} |
JavaScript | clearChart_() {
if (this.chart) {
this.chart.clearChart();
}
} | clearChart_() {
if (this.chart) {
this.chart.clearChart();
}
} |
JavaScript | registerChartEventListener(eventType, eventHandler) {
this.chartListeners.push({
type: eventType,
handler: eventHandler,
});
} | registerChartEventListener(eventType, eventHandler) {
this.chartListeners.push({
type: eventType,
handler: eventHandler,
});
} |
JavaScript | removeChartEventListeners() {
if (this.chart) {
gvizEvents.removeAllListeners(this.getChart());
}
} | removeChartEventListeners() {
if (this.chart) {
gvizEvents.removeAllListeners(this.getChart());
}
} |
JavaScript | addChartEventListeners() {
if (this.chart && !this.listenersRegistered_) {
this.chartListeners.forEach((chartListener) => {
gvizEvents.addListener(this.getChart(), chartListener.type,
chartListener.handler);
});
this.listenersRegistered_ = true;
}
} | addChartEventListeners() {
if (this.chart && !this.listenersRegistered_) {
this.chartListeners.forEach((chartListener) => {
gvizEvents.addListener(this.getChart(), chartListener.type,
chartListener.handler);
});
this.listenersRegistered_ = true;
}
} |
JavaScript | drawContent(store) {
this.updateChartOptions(store);
this.getContainer().style.height = `${this.getOption('height')}px`;
// TODO(b/161803357): Remove cast to unknown type. Found (DataTable|null),
// required (google.visualization.DataTable|google.visualization.DataView).
this.chart.draw(/** @type {?} */ (this.dataTable), this.chartOptions);
} | drawContent(store) {
this.updateChartOptions(store);
this.getContainer().style.height = `${this.getOption('height')}px`;
// TODO(b/161803357): Remove cast to unknown type. Found (DataTable|null),
// required (google.visualization.DataTable|google.visualization.DataView).
this.chart.draw(/** @type {?} */ (this.dataTable), this.chartOptions);
} |
JavaScript | registerResizeHandler_(store) {
if (this.redrawHandler) {
events.unlisten(window, EventType.RESIZE, this.redrawHandler);
}
this.redrawHandler = () => {
this.drawContent(store);
this.drawOverlay(store);
};
events.listen(window, EventType.RESIZE, this.redrawHandler);
} | registerResizeHandler_(store) {
if (this.redrawHandler) {
events.unlisten(window, EventType.RESIZE, this.redrawHandler);
}
this.redrawHandler = () => {
this.drawContent(store);
this.drawOverlay(store);
};
events.listen(window, EventType.RESIZE, this.redrawHandler);
} |
JavaScript | createUpdateDataAndRedrawHandler_(store) {
this.updateDataAndRedrawHandler = () => {
this.clearChart_();
this.dataTable = this.createDataTable(store);
this.drawContent(store);
this.drawOverlay(store);
};
} | createUpdateDataAndRedrawHandler_(store) {
this.updateDataAndRedrawHandler = () => {
this.clearChart_();
this.dataTable = this.createDataTable(store);
this.drawContent(store);
this.drawOverlay(store);
};
} |
JavaScript | handleChartData(store, changedProperties) {
const visible = this.shouldBeVisible(store);
this.setVisibility_(visible);
if (!visible) {
return;
}
this.initChart();
this.registerResizeHandler_(store);
this.createUpdateDataAndRedrawHandler_(store);
const shouldUpdateData =
!this.dataTable || this.shouldUpdateData(store, changedProperties);
const shouldRedrawContent =
shouldUpdateData || this.shouldRedrawContent(store, changedProperties);
const shouldRedrawOverlay = shouldRedrawContent ||
this.shouldRedrawOverlay(store, changedProperties);
if (shouldUpdateData) {
this.clearChart_();
this.dataTable = this.createDataTable(store);
}
if (shouldRedrawContent) {
this.drawContent(store);
}
if (shouldRedrawOverlay) {
this.drawOverlay(store);
}
this.addChartEventListeners();
} | handleChartData(store, changedProperties) {
const visible = this.shouldBeVisible(store);
this.setVisibility_(visible);
if (!visible) {
return;
}
this.initChart();
this.registerResizeHandler_(store);
this.createUpdateDataAndRedrawHandler_(store);
const shouldUpdateData =
!this.dataTable || this.shouldUpdateData(store, changedProperties);
const shouldRedrawContent =
shouldUpdateData || this.shouldRedrawContent(store, changedProperties);
const shouldRedrawOverlay = shouldRedrawContent ||
this.shouldRedrawOverlay(store, changedProperties);
if (shouldUpdateData) {
this.clearChart_();
this.dataTable = this.createDataTable(store);
}
if (shouldRedrawContent) {
this.drawContent(store);
}
if (shouldRedrawOverlay) {
this.drawOverlay(store);
}
this.addChartEventListeners();
} |
JavaScript | drawOverlay(store) {
if (!this.overlayId) {
return;
}
this.sizeAndPositionOverlay();
this.drawOverlayLayers(store);
} | drawOverlay(store) {
if (!this.overlayId) {
return;
}
this.sizeAndPositionOverlay();
this.drawOverlayLayers(store);
} |
JavaScript | sizeAndPositionOverlay() {
const canvas = this.getCanvas();
const chartArea = this.getChartLayoutInterface().getChartAreaBoundingBox();
// Position canvas over chart area
const container = this.getContainer();
canvas.style.top = `${chartArea.top + container.offsetTop}px`;
canvas.style.left = `${chartArea.left + container.offsetLeft}px`;
canvas.width = chartArea.width;
canvas.height = chartArea.height;
} | sizeAndPositionOverlay() {
const canvas = this.getCanvas();
const chartArea = this.getChartLayoutInterface().getChartAreaBoundingBox();
// Position canvas over chart area
const container = this.getContainer();
canvas.style.top = `${chartArea.top + container.offsetTop}px`;
canvas.style.left = `${chartArea.left + container.offsetLeft}px`;
canvas.width = chartArea.width;
canvas.height = chartArea.height;
} |
JavaScript | drawOverlayLayers(store) {
const canvas = this.getCanvas();
const context = this.getContext();
context.clearRect(0, 0, canvas.width, canvas.height);
const cli = this.getChartLayoutInterface();
const chartArea = cli.getChartAreaBoundingBox();
/** @type {!OverlayElement} */
const defaultConfig = {
height: chartArea.height,
top: 0,
minWidth: 5,
};
const drawElement = (element) => {
/** @type {!OverlayElement} */
const drawConfig = Object.assign({}, defaultConfig, element);
const startX = cli.getXLocation(drawConfig.startX) - chartArea.left;
const endX = cli.getXLocation(drawConfig.endX) - chartArea.left;
const width = Math.max(endX - startX, drawConfig.minWidth);
if (drawConfig.fill) {
context.fillStyle = drawConfig.color;
context.fillRect(startX, drawConfig.top, width, drawConfig.height);
} else {
context.strokeStyle = drawConfig.color;
context.lineWidth = 8;
context.strokeRect(startX, drawConfig.top, width, drawConfig.height);
}
};
this.overlayLayers.forEach((layer) => {
const layerElements = layer.getElementsToDraw(store, chartArea);
layerElements.forEach(drawElement);
});
if (this.highlightViewportStyle) {
drawElement(Object.assign({}, this.highlightViewportStyle, {
startX: store.chunkStart,
endX: store.chunkStart + store.chunkDuration,
}));
}
} | drawOverlayLayers(store) {
const canvas = this.getCanvas();
const context = this.getContext();
context.clearRect(0, 0, canvas.width, canvas.height);
const cli = this.getChartLayoutInterface();
const chartArea = cli.getChartAreaBoundingBox();
/** @type {!OverlayElement} */
const defaultConfig = {
height: chartArea.height,
top: 0,
minWidth: 5,
};
const drawElement = (element) => {
/** @type {!OverlayElement} */
const drawConfig = Object.assign({}, defaultConfig, element);
const startX = cli.getXLocation(drawConfig.startX) - chartArea.left;
const endX = cli.getXLocation(drawConfig.endX) - chartArea.left;
const width = Math.max(endX - startX, drawConfig.minWidth);
if (drawConfig.fill) {
context.fillStyle = drawConfig.color;
context.fillRect(startX, drawConfig.top, width, drawConfig.height);
} else {
context.strokeStyle = drawConfig.color;
context.lineWidth = 8;
context.strokeRect(startX, drawConfig.top, width, drawConfig.height);
}
};
this.overlayLayers.forEach((layer) => {
const layerElements = layer.getElementsToDraw(store, chartArea);
layerElements.forEach(drawElement);
});
if (this.highlightViewportStyle) {
drawElement(Object.assign({}, this.highlightViewportStyle, {
startX: store.chunkStart,
endX: store.chunkStart + store.chunkDuration,
}));
}
} |
JavaScript | parseFragment() {
const fragmentData = {};
const hash = location.hash.substring(1);
if (hash) {
const assignments = hash.split('&');
assignments.forEach((assignment) => {
const elements = assignment.split('=');
if (elements.length < 2) {
Dispatcher.getInstance().sendAction({
actionType: Dispatcher.ActionType.ERROR,
data: {
message: 'Bad Fragment',
},
});
}
fragmentData[elements[0]] = decodeURIComponent(
elements.slice(1).join('='));
});
}
const actionData = {};
Store.RequestProperties.forEach((storeParam) => {
const param = storeParam.toLowerCase();
const valid = (param in fragmentData &&
(fragmentData[param] == 0 || fragmentData[param]));
actionData[param] = valid ? fragmentData[param] : null;
});
return /** @type {!Dispatcher.FragmentData} */ (actionData);
} | parseFragment() {
const fragmentData = {};
const hash = location.hash.substring(1);
if (hash) {
const assignments = hash.split('&');
assignments.forEach((assignment) => {
const elements = assignment.split('=');
if (elements.length < 2) {
Dispatcher.getInstance().sendAction({
actionType: Dispatcher.ActionType.ERROR,
data: {
message: 'Bad Fragment',
},
});
}
fragmentData[elements[0]] = decodeURIComponent(
elements.slice(1).join('='));
});
}
const actionData = {};
Store.RequestProperties.forEach((storeParam) => {
const param = storeParam.toLowerCase();
const valid = (param in fragmentData &&
(fragmentData[param] == 0 || fragmentData[param]));
actionData[param] = valid ? fragmentData[param] : null;
});
return /** @type {!Dispatcher.FragmentData} */ (actionData);
} |
JavaScript | makeDataRequest() {
const fragmentData = this.parseFragment();
Dispatcher.getInstance().sendAction({
actionType: Dispatcher.ActionType.WINDOW_LOCATION_PENDING_REQUEST,
data: fragmentData,
});
} | makeDataRequest() {
const fragmentData = this.parseFragment();
Dispatcher.getInstance().sendAction({
actionType: Dispatcher.ActionType.WINDOW_LOCATION_PENDING_REQUEST,
data: fragmentData,
});
} |
JavaScript | handleRequestParams(store, changedProperties) {
if (!store.chunkGraphData) {
return;
}
const fileParamDirty = Store.FileRequestProperties.some(
(param) => changedProperties.includes(param));
const assignments = Store.RequestProperties.map((param) => {
const key = param.toLowerCase();
let value = store[param];
if (Store.FileRequestProperties.includes(param)) {
value = value ? value : '';
} else if (Store.ListRequestProperties.includes(param)) {
value = value ? value.join(',') : '';
}
return `${key}=${value}`;
});
const url = '#' + assignments.join('&');
if (fileParamDirty) {
history.pushState({}, '', url);
} else {
history.replaceState({}, '', url);
}
} | handleRequestParams(store, changedProperties) {
if (!store.chunkGraphData) {
return;
}
const fileParamDirty = Store.FileRequestProperties.some(
(param) => changedProperties.includes(param));
const assignments = Store.RequestProperties.map((param) => {
const key = param.toLowerCase();
let value = store[param];
if (Store.FileRequestProperties.includes(param)) {
value = value ? value : '';
} else if (Store.ListRequestProperties.includes(param)) {
value = value ? value.join(',') : '';
}
return `${key}=${value}`;
});
const url = '#' + assignments.join('&');
if (fileParamDirty) {
history.pushState({}, '', url);
} else {
history.replaceState({}, '', url);
}
} |
JavaScript | printToConsole() {
console.log("Histogram of counts (total: " +
this.totalObservations_ + "): ");
for (let i = 1; i < this.histogram_.length; ++i) {
console.log("\t" + this.vocab_.symbols_[i] + ": " + this.histogram_[i]);
}
} | printToConsole() {
console.log("Histogram of counts (total: " +
this.totalObservations_ + "): ");
for (let i = 1; i < this.histogram_.length; ++i) {
console.log("\t" + this.vocab_.symbols_[i] + ": " + this.histogram_[i]);
}
} |
JavaScript | function mockDomWithFileInput(fileContent) {
const mockFileBlob = new Blob([fileContent], {
type: 'application/json'
});
const mockInput = {
files: [mockFileBlob],
};
const mockGetElement =
mockControl.createMethodMock(document, 'getElementById');
mockGetElement(mockmatchers.isString).$anyTimes().$does((id) => {
if (id === 'uploader-file-input') {
return mockInput;
}
switch (id) {
case 'uploader-file-input':
return mockInput;
case 'uploader-text-display':
return document.createElement('input');
case 'uploader-modal':
default:
return document.createElement('div');
}
});
} | function mockDomWithFileInput(fileContent) {
const mockFileBlob = new Blob([fileContent], {
type: 'application/json'
});
const mockInput = {
files: [mockFileBlob],
};
const mockGetElement =
mockControl.createMethodMock(document, 'getElementById');
mockGetElement(mockmatchers.isString).$anyTimes().$does((id) => {
if (id === 'uploader-file-input') {
return mockInput;
}
switch (id) {
case 'uploader-file-input':
return mockInput;
case 'uploader-text-display':
return document.createElement('input');
case 'uploader-modal':
default:
return document.createElement('div');
}
});
} |
JavaScript | function formatDuration(sec) {
if (sec <= 0.1) {
const milliseconds = Math.floor(sec * 1000);
return `${milliseconds} ms`;
}
return `${sec.toFixed(1)} s`;
} | function formatDuration(sec) {
if (sec <= 0.1) {
const milliseconds = Math.floor(sec * 1000);
return `${milliseconds} ms`;
}
return `${sec.toFixed(1)} s`;
} |
JavaScript | selectFileType(fileType) {
const dropdownNewText = this.dropdownTextByType_[fileType];
if (!dropdownNewText) {
log.error(this.logger_, `File type not recognized: ${fileType}`);
return;
}
if (fileType === this.fileTypeSelected_) {
return;
}
const dropdownElement = document.querySelector('#file-menu-dropdown > div');
dom.setTextContent(dropdownElement, dropdownNewText);
const menuId = `${fileType}-file-menu`;
document.querySelectorAll('.file-menu').forEach((menu) => {
if (menu.id === menuId) {
menu.classList.remove('hidden');
} else {
menu.classList.add('hidden');
}
});
this.fileTypeSelected_ = fileType;
} | selectFileType(fileType) {
const dropdownNewText = this.dropdownTextByType_[fileType];
if (!dropdownNewText) {
log.error(this.logger_, `File type not recognized: ${fileType}`);
return;
}
if (fileType === this.fileTypeSelected_) {
return;
}
const dropdownElement = document.querySelector('#file-menu-dropdown > div');
dom.setTextContent(dropdownElement, dropdownNewText);
const menuId = `${fileType}-file-menu`;
document.querySelectorAll('.file-menu').forEach((menu) => {
if (menu.id === menuId) {
menu.classList.remove('hidden');
} else {
menu.classList.add('hidden');
}
});
this.fileTypeSelected_ = fileType;
} |
JavaScript | handleFileMetadata(store) {
const patientId = store.patientId;
dom.setTextContent(document.querySelector('#patient-id > div'),
patientId == null ? '' : patientId);
if (store.absStart != null) {
const startTime = formatter.formatDateAndTime(store.absStart);
dom.setTextContent(document.querySelector('#start-time > div'), startTime);
}
} | handleFileMetadata(store) {
const patientId = store.patientId;
dom.setTextContent(document.querySelector('#patient-id > div'),
patientId == null ? '' : patientId);
if (store.absStart != null) {
const startTime = formatter.formatDateAndTime(store.absStart);
dom.setTextContent(document.querySelector('#start-time > div'), startTime);
}
} |
JavaScript | updateInputWithStore(store, storeKey, inputId) {
const inputElement = this.getInputElement(inputId);
const storeValue = store[storeKey];
if (storeKey != null && inputElement.value != storeValue) {
inputElement.value = storeValue;
}
} | updateInputWithStore(store, storeKey, inputId) {
const inputElement = this.getInputElement(inputId);
const storeValue = store[storeKey];
if (storeKey != null && inputElement.value != storeValue) {
inputElement.value = storeValue;
}
} |
JavaScript | handleFileParams(store) {
this.updateInputWithStore(store, 'tfExSSTablePath', 'input-tfex-sstable');
this.updateInputWithStore(store, 'predictionSSTablePath', 'input-prediction-sstable');
this.updateInputWithStore(store, 'sstableKey', 'input-key');
this.updateInputWithStore(store, 'edfPath', 'input-edf');
this.updateInputWithStore(store, 'tfExFilePath', 'input-tfex-path');
this.updateInputWithStore(store, 'predictionFilePath', 'input-prediction-path');
if (store.tfExSSTablePath) {
this.selectFileType(FileInputType.SSTABLE);
} else if (store.tfExFilePath) {
this.selectFileType(FileInputType.TF_EXAMPLE);
} else if (store.edfPath) {
this.selectFileType(FileInputType.EDF);
}
} | handleFileParams(store) {
this.updateInputWithStore(store, 'tfExSSTablePath', 'input-tfex-sstable');
this.updateInputWithStore(store, 'predictionSSTablePath', 'input-prediction-sstable');
this.updateInputWithStore(store, 'sstableKey', 'input-key');
this.updateInputWithStore(store, 'edfPath', 'input-edf');
this.updateInputWithStore(store, 'tfExFilePath', 'input-tfex-path');
this.updateInputWithStore(store, 'predictionFilePath', 'input-prediction-path');
if (store.tfExSSTablePath) {
this.selectFileType(FileInputType.SSTABLE);
} else if (store.tfExFilePath) {
this.selectFileType(FileInputType.TF_EXAMPLE);
} else if (store.edfPath) {
this.selectFileType(FileInputType.EDF);
}
} |
JavaScript | loadFile() {
const fileParams = this.getMenusData();
let actionType;
let actionData;
if (!fileParams) {
actionType = Dispatcher.ActionType.ERROR;
actionData = {
message: 'Missing required field(s)',
};
} else {
actionType = Dispatcher.ActionType.MENU_FILE_LOAD;
actionData = fileParams;
}
Dispatcher.getInstance().sendAction({
actionType,
data: actionData,
});
} | loadFile() {
const fileParams = this.getMenusData();
let actionType;
let actionData;
if (!fileParams) {
actionType = Dispatcher.ActionType.ERROR;
actionData = {
message: 'Missing required field(s)',
};
} else {
actionType = Dispatcher.ActionType.MENU_FILE_LOAD;
actionData = fileParams;
}
Dispatcher.getInstance().sendAction({
actionType,
data: actionData,
});
} |
JavaScript | handleLoadingStatus(store) {
switch (store.loadingStatus) {
case Store.LoadingStatus.NO_DATA:
utils.hideMDLSpinner(this.loadingSpinnerId);
utils.showElement(this.submitButtonId);
utils.showElement(this.fileMenuModalId);
break;
case Store.LoadingStatus.LOADING:
utils.showMDLSpinner(this.loadingSpinnerId);
utils.hideElement(this.submitButtonId);
break;
case Store.LoadingStatus.LOADED:
const displayFilePath =
store.sstableKey || store.edfPath || store.tfExFilePath || '';
dom.setTextContent(
document.querySelector('#display-file-path'), displayFilePath);
utils.hideMDLSpinner(this.loadingSpinnerId);
utils.showElement(this.submitButtonId);
utils.hideElement(this.fileMenuModalId);
this.changeTypingStatus(false);
break;
case Store.LoadingStatus.RELOADING:
utils.showMDLSpinner(this.reloadingSpinnerId);
break;
case Store.LoadingStatus.RELOADED:
utils.hideMDLSpinner(this.reloadingSpinnerId);
break;
}
} | handleLoadingStatus(store) {
switch (store.loadingStatus) {
case Store.LoadingStatus.NO_DATA:
utils.hideMDLSpinner(this.loadingSpinnerId);
utils.showElement(this.submitButtonId);
utils.showElement(this.fileMenuModalId);
break;
case Store.LoadingStatus.LOADING:
utils.showMDLSpinner(this.loadingSpinnerId);
utils.hideElement(this.submitButtonId);
break;
case Store.LoadingStatus.LOADED:
const displayFilePath =
store.sstableKey || store.edfPath || store.tfExFilePath || '';
dom.setTextContent(
document.querySelector('#display-file-path'), displayFilePath);
utils.hideMDLSpinner(this.loadingSpinnerId);
utils.showElement(this.submitButtonId);
utils.hideElement(this.fileMenuModalId);
this.changeTypingStatus(false);
break;
case Store.LoadingStatus.RELOADING:
utils.showMDLSpinner(this.reloadingSpinnerId);
break;
case Store.LoadingStatus.RELOADED:
utils.hideMDLSpinner(this.reloadingSpinnerId);
break;
}
} |
JavaScript | display(errorInfo) {
const text = errorInfo ? errorInfo.message : 'Unknown Error';
const notificationSnackbar = /** @type {!MaterialSnackbarElement} */ (document.querySelector('#notification-snackbar'));
notificationSnackbar.MaterialSnackbar.showSnackbar({
message: text,
timeout: 5000,
});
} | display(errorInfo) {
const text = errorInfo ? errorInfo.message : 'Unknown Error';
const notificationSnackbar = /** @type {!MaterialSnackbarElement} */ (document.querySelector('#notification-snackbar'));
notificationSnackbar.MaterialSnackbar.showSnackbar({
message: text,
timeout: 5000,
});
} |
JavaScript | drawWaveEvents(store, chartArea) {
return store.waveEvents.map(
(waveEvent) => ({
fill: true,
color: 'rgb(34, 139, 34)', // green
startX: waveEvent.startTime,
endX: waveEvent.startTime + waveEvent.duration,
top: chartArea.height * this.overlayMarkerPercentage_,
}));
} | drawWaveEvents(store, chartArea) {
return store.waveEvents.map(
(waveEvent) => ({
fill: true,
color: 'rgb(34, 139, 34)', // green
startX: waveEvent.startTime,
endX: waveEvent.startTime + waveEvent.duration,
top: chartArea.height * this.overlayMarkerPercentage_,
}));
} |
JavaScript | drawSimilarPatterns(store, chartArea) {
if (!store.similarPatternsUnseen) {
return [];
}
return store.similarPatternsUnseen.map(
(similarPattern) => ({
fill: true,
color: 'rgb(255, 140, 0)', // orange
startX: similarPattern.startTime,
endX: similarPattern.startTime + similarPattern.duration,
top: chartArea.height * this.overlayMarkerPercentage_,
}));
} | drawSimilarPatterns(store, chartArea) {
if (!store.similarPatternsUnseen) {
return [];
}
return store.similarPatternsUnseen.map(
(similarPattern) => ({
fill: true,
color: 'rgb(255, 140, 0)', // orange
startX: similarPattern.startTime,
endX: similarPattern.startTime + similarPattern.duration,
top: chartArea.height * this.overlayMarkerPercentage_,
}));
} |
JavaScript | drawWaveEventDraft(store, chartArea) {
if (!store.waveEventDraft) {
return [];
}
return [{
fill: true,
color: 'rgba(255, 70, 71)', // red
startX: store.waveEventDraft.startTime,
endX: store.waveEventDraft.startTime + store.waveEventDraft.duration,
top: chartArea.height * this.overlayMarkerPercentage_,
}];
} | drawWaveEventDraft(store, chartArea) {
if (!store.waveEventDraft) {
return [];
}
return [{
fill: true,
color: 'rgba(255, 70, 71)', // red
startX: store.waveEventDraft.startTime,
endX: store.waveEventDraft.startTime + store.waveEventDraft.duration,
top: chartArea.height * this.overlayMarkerPercentage_,
}];
} |
JavaScript | registerListener(properties, id, callback) {
this.registeredListeners.push({
properties: properties,
id: id,
callback: callback,
});
} | registerListener(properties, id, callback) {
this.registeredListeners.push({
properties: properties,
id: id,
callback: callback,
});
} |
JavaScript | emitChange(newStoreData) {
const changedProperties = [];
for (let prop in newStoreData) {
const oldValue = this.storeData[prop];
const newValue = newStoreData[prop];
if (JSON.stringify(oldValue) !== JSON.stringify(newValue)) {
changedProperties.push(prop);
this.storeData[prop] = newValue;
}
}
if (!changedProperties || changedProperties.length === 0) {
log.info(this.logger_, 'No property changed');
return;
}
const changeId = `[${Date.now() % 10000}]`;
log.info(
this.logger_,
`${changeId} Emitting chunk data store change for properties... ${
changedProperties.toString()}`);
this.registeredListeners.forEach((listener) => {
const propertyTriggers = listener.properties.filter(
prop => changedProperties.includes(prop));
if (propertyTriggers.length > 0) {
log.info(
this.logger_,
`${changeId} ... to ${listener.id} view (${
propertyTriggers.toString()})`);
listener.callback(Object.assign({}, this.storeData), changedProperties);
}
});
} | emitChange(newStoreData) {
const changedProperties = [];
for (let prop in newStoreData) {
const oldValue = this.storeData[prop];
const newValue = newStoreData[prop];
if (JSON.stringify(oldValue) !== JSON.stringify(newValue)) {
changedProperties.push(prop);
this.storeData[prop] = newValue;
}
}
if (!changedProperties || changedProperties.length === 0) {
log.info(this.logger_, 'No property changed');
return;
}
const changeId = `[${Date.now() % 10000}]`;
log.info(
this.logger_,
`${changeId} Emitting chunk data store change for properties... ${
changedProperties.toString()}`);
this.registeredListeners.forEach((listener) => {
const propertyTriggers = listener.properties.filter(
prop => changedProperties.includes(prop));
if (propertyTriggers.length > 0) {
log.info(
this.logger_,
`${changeId} ... to ${listener.id} view (${
propertyTriggers.toString()})`);
listener.callback(Object.assign({}, this.storeData), changedProperties);
}
});
} |
JavaScript | newError(message) {
return {
message,
timestamp: Date.now(),
};
} | newError(message) {
return {
message,
timestamp: Date.now(),
};
} |
JavaScript | addWaveEvent_(waveEvent) {
const length = this.storeData.waveEvents.length;
const lastId = length > 0 ? this.storeData.waveEvents[length - 1].id : 0;
return [
...this.storeData.waveEvents,
Object.assign({}, waveEvent, {
id: lastId + 1,
}),
];
} | addWaveEvent_(waveEvent) {
const length = this.storeData.waveEvents.length;
const lastId = length > 0 ? this.storeData.waveEvents[length - 1].id : 0;
return [
...this.storeData.waveEvents,
Object.assign({}, waveEvent, {
id: lastId + 1,
}),
];
} |
JavaScript | createSimilarPatternWithStatus_(similarPattern, status) {
return /** @type {!SimilarPattern} */ (Object.assign({}, similarPattern, {
status,
}));
} | createSimilarPatternWithStatus_(similarPattern, status) {
return /** @type {!SimilarPattern} */ (Object.assign({}, similarPattern, {
status,
}));
} |
JavaScript | addAcceptedPattern_(similarPattern) {
const acceptedPattern = this.createSimilarPatternWithStatus_(
similarPattern, SimilarPatternStatus.ACCEPTED);
return [
...this.storeData.similarPatternsSeen,
acceptedPattern,
];
} | addAcceptedPattern_(similarPattern) {
const acceptedPattern = this.createSimilarPatternWithStatus_(
similarPattern, SimilarPatternStatus.ACCEPTED);
return [
...this.storeData.similarPatternsSeen,
acceptedPattern,
];
} |
JavaScript | addRejectedPattern_(similarPattern) {
const rejectedPattern = this.createSimilarPatternWithStatus_(
similarPattern, SimilarPatternStatus.REJECTED);
return [
...this.storeData.similarPatternsSeen,
rejectedPattern,
];
} | addRejectedPattern_(similarPattern) {
const rejectedPattern = this.createSimilarPatternWithStatus_(
similarPattern, SimilarPatternStatus.REJECTED);
return [
...this.storeData.similarPatternsSeen,
rejectedPattern,
];
} |
JavaScript | handleAddWaveEvent(waveEvent) {
const /** !PartialStoreData */ newStoreData = {
waveEvents: this.addWaveEvent_(waveEvent),
waveEventDraft: null,
};
if (this.storeData.similarPatternEdit) {
const originalPattern = this.storeData.similarPatternEdit;
newStoreData.similarPatternsSeen = this.addAcceptedPattern_(
/** @type {!SimilarPattern} */ (Object.assign({}, originalPattern, {
startTime: waveEvent.startTime,
duration: waveEvent.duration,
channelList: [...waveEvent.channelList],
})));
newStoreData.similarPatternEdit = null;
}
return newStoreData;
} | handleAddWaveEvent(waveEvent) {
const /** !PartialStoreData */ newStoreData = {
waveEvents: this.addWaveEvent_(waveEvent),
waveEventDraft: null,
};
if (this.storeData.similarPatternEdit) {
const originalPattern = this.storeData.similarPatternEdit;
newStoreData.similarPatternsSeen = this.addAcceptedPattern_(
/** @type {!SimilarPattern} */ (Object.assign({}, originalPattern, {
startTime: waveEvent.startTime,
duration: waveEvent.duration,
channelList: [...waveEvent.channelList],
})));
newStoreData.similarPatternEdit = null;
}
return newStoreData;
} |
JavaScript | handleDeleteWaveEvent(data) {
const /** !PartialStoreData */ newStoreData = {
waveEvents: this.storeData.waveEvents.filter(wave => wave.id !== data.id),
};
if (this.storeData.similarPatternTemplate &&
data.id === this.storeData.similarPatternTemplate.id) {
newStoreData.similarPatternTemplate = null;
newStoreData.similarPatternResultRank = 0;
newStoreData.similarPatternTemplate = null;
newStoreData.similarPatternEdit = null;
newStoreData.similarPatternsUnseen = [];
newStoreData.similarPatternsSeen = [];
}
if (this.storeData.similarityCurveTemplate &&
data.id === this.storeData.similarityCurveTemplate.id) {
newStoreData.similarityCurveTemplate = null;
newStoreData.similarityCurveResult = null;
}
return newStoreData;
} | handleDeleteWaveEvent(data) {
const /** !PartialStoreData */ newStoreData = {
waveEvents: this.storeData.waveEvents.filter(wave => wave.id !== data.id),
};
if (this.storeData.similarPatternTemplate &&
data.id === this.storeData.similarPatternTemplate.id) {
newStoreData.similarPatternTemplate = null;
newStoreData.similarPatternResultRank = 0;
newStoreData.similarPatternTemplate = null;
newStoreData.similarPatternEdit = null;
newStoreData.similarPatternsUnseen = [];
newStoreData.similarPatternsSeen = [];
}
if (this.storeData.similarityCurveTemplate &&
data.id === this.storeData.similarityCurveTemplate.id) {
newStoreData.similarityCurveTemplate = null;
newStoreData.similarityCurveResult = null;
}
return newStoreData;
} |
JavaScript | handleClickGraph(data) {
return {
graphPointClick: data,
};
} | handleClickGraph(data) {
return {
graphPointClick: data,
};
} |
JavaScript | handleImportStore(data) {
const /** !PartialStoreData */ newStoreData = {};
Object.values(Property).forEach((propertyName) => {
if (propertyName in data) {
newStoreData[propertyName] = data[propertyName];
}
});
return newStoreData;
} | handleImportStore(data) {
const /** !PartialStoreData */ newStoreData = {};
Object.values(Property).forEach((propertyName) => {
if (propertyName in data) {
newStoreData[propertyName] = data[propertyName];
}
});
return newStoreData;
} |
JavaScript | handleRequestResponseOk(data) {
const /** !PartialStoreData */ newStoreData = {};
const waveformChunk = data.getWaveformChunk();
newStoreData.chunkGraphData = /** @type {!DataTableInput} */ (JSON.parse(
assertString(waveformChunk.getWaveformDatatable())));
newStoreData.channelIds =
waveformChunk.getChannelDataIdsList()
.map(
channelDataId =>
this.convertChannelDataIdToIndexStr(channelDataId))
.filter(channelStr => channelStr);
newStoreData.samplingFreq = waveformChunk.getSamplingFreq();
const waveformMeta = data.getWaveformMetadata();
newStoreData.absStart = waveformMeta.getAbsStart();
newStoreData.annotations = waveformMeta.getLabelsList().map((label) => {
return {
labelText: label.getLabelText(),
startTime: label.getStartTime(),
duration: 0,
channelList: [],
};
});
newStoreData.fileType = waveformMeta.getFileType();
newStoreData.indexChannelMap = assertInstanceof(
waveformMeta.getChannelDictMap(), JspbMap);
newStoreData.numSecs = waveformMeta.getNumSecs();
newStoreData.patientId = waveformMeta.getPatientId();
newStoreData.sstableKey = waveformMeta.getSstableKey() || null;
if (data.hasPredictionChunk() &&
data.getPredictionChunk().getChunkStart() != null &&
data.getPredictionChunk().getChunkDuration() != null) {
const predictionChunk = data.getPredictionChunk();
newStoreData.attributionMaps = predictionChunk.getAttributionDataMap();
newStoreData.predictionChunkSize = assertNumber(
predictionChunk.getChunkDuration());
newStoreData.predictionChunkStart = assertNumber(
predictionChunk.getChunkStart());
} else {
newStoreData.attributionMaps = null;
newStoreData.predictionChunkSize = null;
newStoreData.predictionChunkStart = null;
}
if (data.hasPredictionMetadata()) {
const predictionMeta = data.getPredictionMetadata();
newStoreData.chunkScores = predictionMeta.getChunkScoresList();
} else {
newStoreData.chunkScores = null;
}
const wasFirstLoad = this.storeData.loadingStatus === LoadingStatus.LOADING;
newStoreData.loadingStatus =
wasFirstLoad ? LoadingStatus.LOADED : LoadingStatus.RELOADED;
return newStoreData;
} | handleRequestResponseOk(data) {
const /** !PartialStoreData */ newStoreData = {};
const waveformChunk = data.getWaveformChunk();
newStoreData.chunkGraphData = /** @type {!DataTableInput} */ (JSON.parse(
assertString(waveformChunk.getWaveformDatatable())));
newStoreData.channelIds =
waveformChunk.getChannelDataIdsList()
.map(
channelDataId =>
this.convertChannelDataIdToIndexStr(channelDataId))
.filter(channelStr => channelStr);
newStoreData.samplingFreq = waveformChunk.getSamplingFreq();
const waveformMeta = data.getWaveformMetadata();
newStoreData.absStart = waveformMeta.getAbsStart();
newStoreData.annotations = waveformMeta.getLabelsList().map((label) => {
return {
labelText: label.getLabelText(),
startTime: label.getStartTime(),
duration: 0,
channelList: [],
};
});
newStoreData.fileType = waveformMeta.getFileType();
newStoreData.indexChannelMap = assertInstanceof(
waveformMeta.getChannelDictMap(), JspbMap);
newStoreData.numSecs = waveformMeta.getNumSecs();
newStoreData.patientId = waveformMeta.getPatientId();
newStoreData.sstableKey = waveformMeta.getSstableKey() || null;
if (data.hasPredictionChunk() &&
data.getPredictionChunk().getChunkStart() != null &&
data.getPredictionChunk().getChunkDuration() != null) {
const predictionChunk = data.getPredictionChunk();
newStoreData.attributionMaps = predictionChunk.getAttributionDataMap();
newStoreData.predictionChunkSize = assertNumber(
predictionChunk.getChunkDuration());
newStoreData.predictionChunkStart = assertNumber(
predictionChunk.getChunkStart());
} else {
newStoreData.attributionMaps = null;
newStoreData.predictionChunkSize = null;
newStoreData.predictionChunkStart = null;
}
if (data.hasPredictionMetadata()) {
const predictionMeta = data.getPredictionMetadata();
newStoreData.chunkScores = predictionMeta.getChunkScoresList();
} else {
newStoreData.chunkScores = null;
}
const wasFirstLoad = this.storeData.loadingStatus === LoadingStatus.LOADING;
newStoreData.loadingStatus =
wasFirstLoad ? LoadingStatus.LOADED : LoadingStatus.RELOADED;
return newStoreData;
} |
JavaScript | handleWindowLocationPendingRequest(data) {
const /** !PartialStoreData */ newStoreData = {};
/**
* Parse a string to number.
* If is not a number returns 0
*/
const numberParser = (string) => Number(string) || 0;
/**
* Split a string separated by commas into an array.
*/
const stringToArray = (str) => str ? str.split(',') : [];
/**
* Update a key from newStoreData with the value from incoming data.
*/
const updateKey = (storeKey, parser = undefined) => {
const dataKey = storeKey.toLowerCase();
const newValue = data[dataKey];
if (newValue && this.storeData[storeKey] != newValue) {
newStoreData[storeKey] = parser ? parser(newValue) : newValue;
}
};
updateKey(Property.TFEX_SSTABLE_PATH);
updateKey(Property.PREDICTION_SSTABLE_PATH);
updateKey(Property.SSTABLE_KEY);
updateKey(Property.EDF_PATH);
updateKey(Property.TFEX_FILE_PATH);
updateKey(Property.PREDICTION_FILE_PATH);
updateKey(Property.CHUNK_START, numberParser);
updateKey(Property.CHUNK_DURATION, numberParser);
updateKey(Property.CHANNEL_IDS, stringToArray);
updateKey(Property.LOW_CUT, numberParser);
updateKey(Property.HIGH_CUT, numberParser);
updateKey(Property.NOTCH, numberParser);
return newStoreData;
} | handleWindowLocationPendingRequest(data) {
const /** !PartialStoreData */ newStoreData = {};
/**
* Parse a string to number.
* If is not a number returns 0
*/
const numberParser = (string) => Number(string) || 0;
/**
* Split a string separated by commas into an array.
*/
const stringToArray = (str) => str ? str.split(',') : [];
/**
* Update a key from newStoreData with the value from incoming data.
*/
const updateKey = (storeKey, parser = undefined) => {
const dataKey = storeKey.toLowerCase();
const newValue = data[dataKey];
if (newValue && this.storeData[storeKey] != newValue) {
newStoreData[storeKey] = parser ? parser(newValue) : newValue;
}
};
updateKey(Property.TFEX_SSTABLE_PATH);
updateKey(Property.PREDICTION_SSTABLE_PATH);
updateKey(Property.SSTABLE_KEY);
updateKey(Property.EDF_PATH);
updateKey(Property.TFEX_FILE_PATH);
updateKey(Property.PREDICTION_FILE_PATH);
updateKey(Property.CHUNK_START, numberParser);
updateKey(Property.CHUNK_DURATION, numberParser);
updateKey(Property.CHANNEL_IDS, stringToArray);
updateKey(Property.LOW_CUT, numberParser);
updateKey(Property.HIGH_CUT, numberParser);
updateKey(Property.NOTCH, numberParser);
return newStoreData;
} |
JavaScript | handleError(data) {
return {
error: this.newError(data.message),
};
} | handleError(data) {
return {
error: this.newError(data.message),
};
} |
JavaScript | handleRequestResponseError(data) {
const error = this.newError(data.message);
const wasFirstLoad = this.storeData.loadingStatus === LoadingStatus.LOADING;
const loadingStatus =
wasFirstLoad ? LoadingStatus.NO_DATA : LoadingStatus.RELOADED;
return {
error,
loadingStatus,
};
} | handleRequestResponseError(data) {
const error = this.newError(data.message);
const wasFirstLoad = this.storeData.loadingStatus === LoadingStatus.LOADING;
const loadingStatus =
wasFirstLoad ? LoadingStatus.NO_DATA : LoadingStatus.RELOADED;
return {
error,
loadingStatus,
};
} |
JavaScript | handleRequestStart(data) {
const isFirstLoad = this.storeData.loadingStatus === LoadingStatus.NO_DATA;
const loadingStatus = (isFirstLoad || data.fileParamDirty) ?
LoadingStatus.LOADING :
LoadingStatus.RELOADING;
return {
loadingStatus,
};
} | handleRequestStart(data) {
const isFirstLoad = this.storeData.loadingStatus === LoadingStatus.NO_DATA;
const loadingStatus = (isFirstLoad || data.fileParamDirty) ?
LoadingStatus.LOADING :
LoadingStatus.RELOADING;
return {
loadingStatus,
};
} |
JavaScript | handleChangeTypingStatus(data) {
return {
isTyping: data.isTyping,
};
} | handleChangeTypingStatus(data) {
return {
isTyping: data.isTyping,
};
} |
JavaScript | saveFinishedTrial_() {
return {
template: /** @type {!Annotation} */ (
this.storeData.similarPatternTemplate),
seen: this.storeData.similarPatternsSeen,
unseen: this.storeData.similarPatternsUnseen,
};
} | saveFinishedTrial_() {
return {
template: /** @type {!Annotation} */ (
this.storeData.similarPatternTemplate),
seen: this.storeData.similarPatternsSeen,
unseen: this.storeData.similarPatternsUnseen,
};
} |
JavaScript | handleSimilarPatternsRequest(data) {
const /** !PartialStoreData */ newStoreData = {
similarPatternTemplate: data,
similarPatternEdit: null,
similarPatternsSeen: [],
similarPatternsUnseen: [],
};
const prevTemplate = this.storeData.similarPatternTemplate;
if (prevTemplate && prevTemplate.id === data.id) {
newStoreData.similarPatternResultRank = this.increaseSimilarityRank_();
} else {
newStoreData.similarPatternResultRank = 0;
}
if (prevTemplate && prevTemplate.id !== data.id) {
newStoreData.similarPatternPastTrials = [
...this.storeData.similarPatternPastTrials,
this.saveFinishedTrial_(),
];
}
return newStoreData;
} | handleSimilarPatternsRequest(data) {
const /** !PartialStoreData */ newStoreData = {
similarPatternTemplate: data,
similarPatternEdit: null,
similarPatternsSeen: [],
similarPatternsUnseen: [],
};
const prevTemplate = this.storeData.similarPatternTemplate;
if (prevTemplate && prevTemplate.id === data.id) {
newStoreData.similarPatternResultRank = this.increaseSimilarityRank_();
} else {
newStoreData.similarPatternResultRank = 0;
}
if (prevTemplate && prevTemplate.id !== data.id) {
newStoreData.similarPatternPastTrials = [
...this.storeData.similarPatternPastTrials,
this.saveFinishedTrial_(),
];
}
return newStoreData;
} |
JavaScript | handleSimilarPatternsRequestMore() {
if (!this.storeData.similarPatternTemplate) {
return null;
}
return {
similarPatternResultRank: this.increaseSimilarityRank_(),
};
} | handleSimilarPatternsRequestMore() {
if (!this.storeData.similarPatternTemplate) {
return null;
}
return {
similarPatternResultRank: this.increaseSimilarityRank_(),
};
} |
JavaScript | handleSearchSimilarSettings(data) {
const oldSettings = this.storeData.similarPatternSettings;
return {
similarPatternSettings: /** @type {!SimilaritySettings} */ (
Object.assign({}, oldSettings, data)),
};
} | handleSearchSimilarSettings(data) {
const oldSettings = this.storeData.similarPatternSettings;
return {
similarPatternSettings: /** @type {!SimilaritySettings} */ (
Object.assign({}, oldSettings, data)),
};
} |
JavaScript | handleSimilarPatternsResponseOk(data) {
const templatePattern = this.storeData.similarPatternTemplate;
const newUnseen = data.getSimilarPatternsList().map(
(similarPattern) => /** @type {!SimilarPattern} */ (Object.assign(
{},
similarPattern.toObject(),
{
status: SimilarPatternStatus.UNSEEN,
channelList: [...templatePattern.channelList],
},
)));
return {
similarPatternError: null,
similarPatternsUnseen: [
...this.storeData.similarPatternsUnseen,
...newUnseen,
],
};
} | handleSimilarPatternsResponseOk(data) {
const templatePattern = this.storeData.similarPatternTemplate;
const newUnseen = data.getSimilarPatternsList().map(
(similarPattern) => /** @type {!SimilarPattern} */ (Object.assign(
{},
similarPattern.toObject(),
{
status: SimilarPatternStatus.UNSEEN,
channelList: [...templatePattern.channelList],
},
)));
return {
similarPatternError: null,
similarPatternsUnseen: [
...this.storeData.similarPatternsUnseen,
...newUnseen,
],
};
} |
JavaScript | handleSimilarPatternsResponseError(data) {
return {
similarPatternError: this.newError(data.message),
};
} | handleSimilarPatternsResponseError(data) {
return {
similarPatternError: this.newError(data.message),
};
} |
JavaScript | handleSimilarPatternAccept(data) {
const templatePattern = this.storeData.similarPatternTemplate;
const waveEvents = this.addWaveEvent_({
labelText: templatePattern.labelText,
startTime: data.startTime,
duration: data.duration,
channelList: data.channelList,
});
return {
waveEvents,
similarPatternsUnseen: this.removeSimilarPatternFromUnseen_(data),
similarPatternsSeen: this.addAcceptedPattern_(data),
};
} | handleSimilarPatternAccept(data) {
const templatePattern = this.storeData.similarPatternTemplate;
const waveEvents = this.addWaveEvent_({
labelText: templatePattern.labelText,
startTime: data.startTime,
duration: data.duration,
channelList: data.channelList,
});
return {
waveEvents,
similarPatternsUnseen: this.removeSimilarPatternFromUnseen_(data),
similarPatternsSeen: this.addAcceptedPattern_(data),
};
} |
JavaScript | handleSimilarPatternEdit(data) {
return {
similarPatternEdit: this.createSimilarPatternWithStatus_(
data, SimilarPatternStatus.EDITING),
similarPatternsUnseen: this.removeSimilarPatternFromUnseen_(data),
};
} | handleSimilarPatternEdit(data) {
return {
similarPatternEdit: this.createSimilarPatternWithStatus_(
data, SimilarPatternStatus.EDITING),
similarPatternsUnseen: this.removeSimilarPatternFromUnseen_(data),
};
} |
JavaScript | handleSimilarPatternReject(data) {
return {
similarPatternsUnseen: this.removeSimilarPatternFromUnseen_(data),
similarPatternsSeen: this.addRejectedPattern_(data),
};
} | handleSimilarPatternReject(data) {
return {
similarPatternsUnseen: this.removeSimilarPatternFromUnseen_(data),
similarPatternsSeen: this.addRejectedPattern_(data),
};
} |
JavaScript | handleSimilarPatternRejectAll() {
const rejectedPatterns =
this.storeData.similarPatternsUnseen.map((similarPattern) => {
return this.createSimilarPatternWithStatus_(
similarPattern, SimilarPatternStatus.REJECTED);
});
return {
similarPatternsUnseen: [],
similarPatternsSeen: [
...this.storeData.similarPatternsSeen,
...rejectedPatterns,
],
};
} | handleSimilarPatternRejectAll() {
const rejectedPatterns =
this.storeData.similarPatternsUnseen.map((similarPattern) => {
return this.createSimilarPatternWithStatus_(
similarPattern, SimilarPatternStatus.REJECTED);
});
return {
similarPatternsUnseen: [],
similarPatternsSeen: [
...this.storeData.similarPatternsSeen,
...rejectedPatterns,
],
};
} |
JavaScript | handleSimilarityCurveClear() {
return {
similarityCurveTemplate: null,
similarityCurveResult: null,
};
} | handleSimilarityCurveClear() {
return {
similarityCurveTemplate: null,
similarityCurveResult: null,
};
} |
JavaScript | handleSimilarityCurveRequest(data) {
return {
similarityCurveTemplate: data,
similarityCurveResult: null,
};
} | handleSimilarityCurveRequest(data) {
return {
similarityCurveTemplate: data,
similarityCurveResult: null,
};
} |
JavaScript | handleSimilarityCurveResponseOk(data) {
return {
similarityCurveResult: data.getScoresList(),
};
} | handleSimilarityCurveResponseOk(data) {
return {
similarityCurveResult: data.getScoresList(),
};
} |
JavaScript | handleSimilarityCurveResponseError(data) {
return {
similarityCurveResult: null,
error: this.newError(data.message),
};
} | handleSimilarityCurveResponseError(data) {
return {
similarityCurveResult: null,
error: this.newError(data.message),
};
} |
JavaScript | handleToolBarGridlines(data) {
assertNumber(data.selectedValue);
return {
timeScale: data.selectedValue,
};
} | handleToolBarGridlines(data) {
assertNumber(data.selectedValue);
return {
timeScale: data.selectedValue,
};
} |
JavaScript | handleToolBarHighCut(data) {
assertNumber(data.selectedValue);
return {
highCut: data.selectedValue,
};
} | handleToolBarHighCut(data) {
assertNumber(data.selectedValue);
return {
highCut: data.selectedValue,
};
} |
JavaScript | handleToolBarLowCut(data) {
assertNumber(data.selectedValue);
return {
lowCut: data.selectedValue,
};
} | handleToolBarLowCut(data) {
assertNumber(data.selectedValue);
return {
lowCut: data.selectedValue,
};
} |
JavaScript | handleToolBarMontage(data) {
assertArray(data.selectedValue);
return {
channelIds: data.selectedValue,
};
} | handleToolBarMontage(data) {
assertArray(data.selectedValue);
return {
channelIds: data.selectedValue,
};
} |
JavaScript | handleToolBarNextChunk() {
return {
chunkStart: this.storeData.chunkStart + this.storeData.chunkDuration,
};
} | handleToolBarNextChunk() {
return {
chunkStart: this.storeData.chunkStart + this.storeData.chunkDuration,
};
} |
JavaScript | handleToolBarShiftSecs(data) {
return {
chunkStart: this.storeData.chunkStart + data.time,
};
} | handleToolBarShiftSecs(data) {
return {
chunkStart: this.storeData.chunkStart + data.time,
};
} |
JavaScript | handleToolBarNotch(data) {
assertNumber(data.selectedValue);
return {
notch: data.selectedValue,
};
} | handleToolBarNotch(data) {
assertNumber(data.selectedValue);
return {
notch: data.selectedValue,
};
} |
JavaScript | handleToolBarPrevChunk() {
return {
chunkStart: this.storeData.chunkStart - this.storeData.chunkDuration,
};
} | handleToolBarPrevChunk() {
return {
chunkStart: this.storeData.chunkStart - this.storeData.chunkDuration,
};
} |
JavaScript | handleToolBarSensitivity(data) {
assertNumber(data.selectedValue);
return {
sensitivity: data.selectedValue,
};
} | handleToolBarSensitivity(data) {
assertNumber(data.selectedValue);
return {
sensitivity: data.selectedValue,
};
} |
JavaScript | handleToolBarZoom(data) {
assertNumber(data.selectedValue);
return {
chunkDuration: data.selectedValue,
};
} | handleToolBarZoom(data) {
assertNumber(data.selectedValue);
return {
chunkDuration: data.selectedValue,
};
} |
JavaScript | handlePredictionChunkRequest(data) {
return {
chunkStart: Math.round(data.time),
};
} | handlePredictionChunkRequest(data) {
return {
chunkStart: Math.round(data.time),
};
} |
JavaScript | handlePredictionModeSelection(data) {
const mode = assertString(data.selectedValue);
assert(Object.values(PredictionMode).includes(mode));
return {
predictionMode: /** @type {!PredictionMode} */(mode),
};
} | handlePredictionModeSelection(data) {
const mode = assertString(data.selectedValue);
assert(Object.values(PredictionMode).includes(mode));
return {
predictionMode: /** @type {!PredictionMode} */(mode),
};
} |
JavaScript | handlePredictionLabelSelection(data) {
return {
label: assertString(data.selectedValue),
};
} | handlePredictionLabelSelection(data) {
return {
label: assertString(data.selectedValue),
};
} |
JavaScript | handleAnnotationSelection(data) {
return {
chunkStart: Math.round(data.time - this.storeData.chunkDuration / 2),
};
} | handleAnnotationSelection(data) {
return {
chunkStart: Math.round(data.time - this.storeData.chunkDuration / 2),
};
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.