language
stringclasses 6
values | original_string
stringlengths 25
887k
| text
stringlengths 25
887k
|
---|---|---|
JavaScript | static get options() {
const { prefix } = settings;
return {
selectorInit: '[data-file-demo-state-manager]',
selectorSelectedFile: `.${prefix}--file__selected-file`,
initEventNames: ['change', 'drop'],
};
} | static get options() {
const { prefix } = settings;
return {
selectorInit: '[data-file-demo-state-manager]',
selectorSelectedFile: `.${prefix}--file__selected-file`,
initEventNames: ['change', 'drop'],
};
} |
JavaScript | function useControllableState({
defaultValue,
name = 'custom',
onChange,
value,
}) {
const [state, internalSetState] = useState(value ?? defaultValue);
const controlled = useRef(null);
if (controlled.current === null) {
controlled.current = value !== undefined;
}
function setState(stateOrUpdater) {
const value =
typeof stateOrUpdater === 'function'
? stateOrUpdater(state)
: stateOrUpdater;
if (controlled.current === false) {
internalSetState(value);
}
if (onChange) {
onChange(value);
}
}
useEffect(() => {
const controlledValue = value !== undefined;
// Uncontrolled -> Controlled
// If the component prop is uncontrolled, the prop value should be undefined
if (controlled.current === false && controlledValue) {
warning(
false,
'A component is changing an uncontrolled %s component to be controlled. ' +
'This is likely caused by the value changing to a defined value ' +
'from undefined. Decide between using a controlled or uncontrolled ' +
'value for the lifetime of the component. ' +
'More info: https://reactjs.org/link/controlled-components',
name
);
}
// Controlled -> Uncontrolled
// If the component prop is controlled, the prop value should be defined
if (controlled.current === true && !controlledValue) {
warning(
false,
'A component is changing a controlled %s component to be uncontrolled. ' +
'This is likely caused by the value changing to an undefined value ' +
'from a defined one. Decide between using a controlled or ' +
'uncontrolled value for the lifetime of the component. ' +
'More info: https://reactjs.org/link/controlled-components',
name
);
}
}, [name, value]);
if (controlled.current === true) {
return [value, setState];
}
return [state, setState];
} | function useControllableState({
defaultValue,
name = 'custom',
onChange,
value,
}) {
const [state, internalSetState] = useState(value ?? defaultValue);
const controlled = useRef(null);
if (controlled.current === null) {
controlled.current = value !== undefined;
}
function setState(stateOrUpdater) {
const value =
typeof stateOrUpdater === 'function'
? stateOrUpdater(state)
: stateOrUpdater;
if (controlled.current === false) {
internalSetState(value);
}
if (onChange) {
onChange(value);
}
}
useEffect(() => {
const controlledValue = value !== undefined;
// Uncontrolled -> Controlled
// If the component prop is uncontrolled, the prop value should be undefined
if (controlled.current === false && controlledValue) {
warning(
false,
'A component is changing an uncontrolled %s component to be controlled. ' +
'This is likely caused by the value changing to a defined value ' +
'from undefined. Decide between using a controlled or uncontrolled ' +
'value for the lifetime of the component. ' +
'More info: https://reactjs.org/link/controlled-components',
name
);
}
// Controlled -> Uncontrolled
// If the component prop is controlled, the prop value should be defined
if (controlled.current === true && !controlledValue) {
warning(
false,
'A component is changing a controlled %s component to be uncontrolled. ' +
'This is likely caused by the value changing to an undefined value ' +
'from a defined one. Decide between using a controlled or ' +
'uncontrolled value for the lifetime of the component. ' +
'More info: https://reactjs.org/link/controlled-components',
name
);
}
}, [name, value]);
if (controlled.current === true) {
return [value, setState];
}
return [state, setState];
} |
JavaScript | function useContextMenu(trigger = document) {
const [open, setOpen] = useState(false);
const [position, setPosition] = useState([0, 0]);
function openContextMenu(e) {
e.preventDefault();
const { x, y } = e;
setPosition([x, y]);
setOpen(true);
}
function onClose() {
setOpen(false);
}
useEffect(() => {
if (
(trigger && trigger instanceof Element) ||
trigger instanceof Document ||
trigger instanceof Window
) {
trigger.addEventListener('contextmenu', openContextMenu);
return () => {
trigger.removeEventListener('contextmenu', openContextMenu);
};
}
}, [trigger]);
return {
open,
x: position[0],
y: position[1],
onClose,
};
} | function useContextMenu(trigger = document) {
const [open, setOpen] = useState(false);
const [position, setPosition] = useState([0, 0]);
function openContextMenu(e) {
e.preventDefault();
const { x, y } = e;
setPosition([x, y]);
setOpen(true);
}
function onClose() {
setOpen(false);
}
useEffect(() => {
if (
(trigger && trigger instanceof Element) ||
trigger instanceof Document ||
trigger instanceof Window
) {
trigger.addEventListener('contextmenu', openContextMenu);
return () => {
trigger.removeEventListener('contextmenu', openContextMenu);
};
}
}, [trigger]);
return {
open,
x: position[0],
y: position[1],
onClose,
};
} |
JavaScript | static get options() {
const { prefix } = settings;
return {
selectorInit: '[data-table-demo-expand-all-manager]',
selectorExpandHeader: `th.${prefix}--table-expand`,
selectorExpandCells: `td.${prefix}--table-expand`,
selectorExpandCellsExpanded: `td.${prefix}--table-expand[data-previous-value="collapsed"]`,
initEventNames: ['click'],
};
} | static get options() {
const { prefix } = settings;
return {
selectorInit: '[data-table-demo-expand-all-manager]',
selectorExpandHeader: `th.${prefix}--table-expand`,
selectorExpandCells: `td.${prefix}--table-expand`,
selectorExpandCellsExpanded: `td.${prefix}--table-expand[data-previous-value="collapsed"]`,
initEventNames: ['click'],
};
} |
JavaScript | static get options() {
const { prefix } = settings;
return {
selectorInit: '[data-inline-loading]',
selectorSpinner: '[data-inline-loading-spinner]',
selectorFinished: '[data-inline-loading-finished]',
selectorError: '[data-inline-loading-error]',
selectorTextActive: '[data-inline-loading-text-active]',
selectorTextFinished: '[data-inline-loading-text-finished]',
selectorTextError: '[data-inline-loading-text-error]',
classLoadingStop: `${prefix}--loading--stop`,
};
} | static get options() {
const { prefix } = settings;
return {
selectorInit: '[data-inline-loading]',
selectorSpinner: '[data-inline-loading-spinner]',
selectorFinished: '[data-inline-loading-finished]',
selectorError: '[data-inline-loading-error]',
selectorTextActive: '[data-inline-loading-text-active]',
selectorTextFinished: '[data-inline-loading-text-finished]',
selectorTextError: '[data-inline-loading-text-error]',
classLoadingStop: `${prefix}--loading--stop`,
};
} |
JavaScript | compute_(trace) {
// Parse the trace for our key events and sort them by timestamp. Note: sort
// *must* be stable to keep events correctly nested.
const keyEvents = trace.traceEvents
.filter(e => {
return e.cat.includes('blink.user_timing') ||
e.cat.includes('loading') ||
e.cat.includes('devtools.timeline') ||
e.name === 'TracingStartedInPage';
})
.stableSort((event0, event1) => event0.ts - event1.ts);
// The first TracingStartedInPage in the trace is definitely our renderer thread of interest
// Beware: the tracingStartedInPage event can appear slightly after a navigationStart
const startedInPageEvt = keyEvents.find(e => e.name === 'TracingStartedInPage');
// Filter to just events matching the frame ID for sanity
const frameEvents = keyEvents.filter(e => e.args.frame === startedInPageEvt.args.data.page);
// Our navStart will be the last frame navigation in the trace
const navigationStart = frameEvents.filter(e => e.name === 'navigationStart').pop();
if (!navigationStart) throw new Error('navigationStart was not found in the trace');
// Find our first paint of this frame
const firstPaint = frameEvents.find(e => e.name === 'firstPaint' && e.ts > navigationStart.ts);
// FCP will follow at/after the FP
const firstContentfulPaint = frameEvents.find(
e => e.name === 'firstContentfulPaint' && e.ts > navigationStart.ts
);
// fMP will follow at/after the FP
let firstMeaningfulPaint = frameEvents.find(
e => e.name === 'firstMeaningfulPaint' && e.ts > navigationStart.ts
);
let fmpFellBack = false;
// If there was no firstMeaningfulPaint event found in the trace, the network idle detection
// may have not been triggered before Lighthouse finished tracing.
// In this case, we'll use the last firstMeaningfulPaintCandidate we can find.
// However, if no candidates were found (a bogus trace, likely), we fail.
if (!firstMeaningfulPaint) {
const fmpCand = 'firstMeaningfulPaintCandidate';
fmpFellBack = true;
log.verbose('trace-of-tab', `No firstMeaningfulPaint found, falling back to last ${fmpCand}`);
const lastCandidate = frameEvents.filter(e => e.name === fmpCand).pop();
if (!lastCandidate) {
log.verbose('trace-of-tab', 'No `firstMeaningfulPaintCandidate` events found in trace');
}
firstMeaningfulPaint = lastCandidate;
}
const onLoad = frameEvents.find(e => e.name === 'loadEventEnd' && e.ts > navigationStart.ts);
const domContentLoaded = frameEvents.find(
e => e.name === 'domContentLoadedEventEnd' && e.ts > navigationStart.ts
);
// subset all trace events to just our tab's process (incl threads other than main)
// stable-sort events to keep them correctly nested.
const processEvents = trace.traceEvents
.filter(e => e.pid === startedInPageEvt.pid)
.stableSort((event0, event1) => event0.ts - event1.ts);
const mainThreadEvents = processEvents
.filter(e => e.tid === startedInPageEvt.tid);
const traceEnd = trace.traceEvents.reduce((max, evt) => {
return max.ts > evt.ts ? max : evt;
});
const metrics = {
navigationStart,
firstPaint,
firstContentfulPaint,
firstMeaningfulPaint,
traceEnd: {ts: traceEnd.ts + (traceEnd.dur || 0)},
onLoad,
domContentLoaded,
};
const timings = {};
const timestamps = {};
Object.keys(metrics).forEach(metric => {
timestamps[metric] = metrics[metric] && metrics[metric].ts;
timings[metric] = (timestamps[metric] - navigationStart.ts) / 1000;
});
return {
timings,
timestamps,
processEvents,
mainThreadEvents,
startedInPageEvt,
navigationStartEvt: navigationStart,
firstPaintEvt: firstPaint,
firstContentfulPaintEvt: firstContentfulPaint,
firstMeaningfulPaintEvt: firstMeaningfulPaint,
onLoadEvt: onLoad,
fmpFellBack,
};
} | compute_(trace) {
// Parse the trace for our key events and sort them by timestamp. Note: sort
// *must* be stable to keep events correctly nested.
const keyEvents = trace.traceEvents
.filter(e => {
return e.cat.includes('blink.user_timing') ||
e.cat.includes('loading') ||
e.cat.includes('devtools.timeline') ||
e.name === 'TracingStartedInPage';
})
.stableSort((event0, event1) => event0.ts - event1.ts);
// The first TracingStartedInPage in the trace is definitely our renderer thread of interest
// Beware: the tracingStartedInPage event can appear slightly after a navigationStart
const startedInPageEvt = keyEvents.find(e => e.name === 'TracingStartedInPage');
// Filter to just events matching the frame ID for sanity
const frameEvents = keyEvents.filter(e => e.args.frame === startedInPageEvt.args.data.page);
// Our navStart will be the last frame navigation in the trace
const navigationStart = frameEvents.filter(e => e.name === 'navigationStart').pop();
if (!navigationStart) throw new Error('navigationStart was not found in the trace');
// Find our first paint of this frame
const firstPaint = frameEvents.find(e => e.name === 'firstPaint' && e.ts > navigationStart.ts);
// FCP will follow at/after the FP
const firstContentfulPaint = frameEvents.find(
e => e.name === 'firstContentfulPaint' && e.ts > navigationStart.ts
);
// fMP will follow at/after the FP
let firstMeaningfulPaint = frameEvents.find(
e => e.name === 'firstMeaningfulPaint' && e.ts > navigationStart.ts
);
let fmpFellBack = false;
// If there was no firstMeaningfulPaint event found in the trace, the network idle detection
// may have not been triggered before Lighthouse finished tracing.
// In this case, we'll use the last firstMeaningfulPaintCandidate we can find.
// However, if no candidates were found (a bogus trace, likely), we fail.
if (!firstMeaningfulPaint) {
const fmpCand = 'firstMeaningfulPaintCandidate';
fmpFellBack = true;
log.verbose('trace-of-tab', `No firstMeaningfulPaint found, falling back to last ${fmpCand}`);
const lastCandidate = frameEvents.filter(e => e.name === fmpCand).pop();
if (!lastCandidate) {
log.verbose('trace-of-tab', 'No `firstMeaningfulPaintCandidate` events found in trace');
}
firstMeaningfulPaint = lastCandidate;
}
const onLoad = frameEvents.find(e => e.name === 'loadEventEnd' && e.ts > navigationStart.ts);
const domContentLoaded = frameEvents.find(
e => e.name === 'domContentLoadedEventEnd' && e.ts > navigationStart.ts
);
// subset all trace events to just our tab's process (incl threads other than main)
// stable-sort events to keep them correctly nested.
const processEvents = trace.traceEvents
.filter(e => e.pid === startedInPageEvt.pid)
.stableSort((event0, event1) => event0.ts - event1.ts);
const mainThreadEvents = processEvents
.filter(e => e.tid === startedInPageEvt.tid);
const traceEnd = trace.traceEvents.reduce((max, evt) => {
return max.ts > evt.ts ? max : evt;
});
const metrics = {
navigationStart,
firstPaint,
firstContentfulPaint,
firstMeaningfulPaint,
traceEnd: {ts: traceEnd.ts + (traceEnd.dur || 0)},
onLoad,
domContentLoaded,
};
const timings = {};
const timestamps = {};
Object.keys(metrics).forEach(metric => {
timestamps[metric] = metrics[metric] && metrics[metric].ts;
timings[metric] = (timestamps[metric] - navigationStart.ts) / 1000;
});
return {
timings,
timestamps,
processEvents,
mainThreadEvents,
startedInPageEvt,
navigationStartEvt: navigationStart,
firstPaintEvt: firstPaint,
firstContentfulPaintEvt: firstContentfulPaint,
firstMeaningfulPaintEvt: firstMeaningfulPaint,
onLoadEvt: onLoad,
fmpFellBack,
};
} |
JavaScript | _initializeNetworkRecords() {
this._networkRecords = [];
this._graph.getRootNode().traverse(node => {
if (node.type === Node.TYPES.NETWORK) {
this._networkRecords.push(node.record);
}
});
} | _initializeNetworkRecords() {
this._networkRecords = [];
this._graph.getRootNode().traverse(node => {
if (node.type === Node.TYPES.NETWORK) {
this._networkRecords.push(node.record);
}
});
} |
JavaScript | _initializeNetworkConnections() {
const connections = new Map();
const recordsByConnection = groupBy(
this._networkRecords,
record => record.connectionId
);
for (const [connectionId, records] of recordsByConnection.entries()) {
const isTLS = TLS_SCHEMES.includes(records[0].parsedURL.scheme);
// We'll approximate how much time the server for a connection took to respond after receiving
// the request by computing the minimum TTFB time for requests on that connection.
// TTFB = one way latency + server response time + one way latency
// Even though TTFB is greater than server response time, the RTT is underaccounted for by
// not varying per-server and so the difference roughly evens out.
// TODO(patrickhulce): investigate a way to identify per-server RTT
let estimatedResponseTime = Math.min(...records.map(Estimator.getTTFB));
// If we couldn't find a TTFB for the requests, use the fallback TTFB instead.
if (!Number.isFinite(estimatedResponseTime)) {
estimatedResponseTime = this._fallbackTTFB;
}
const connection = new TcpConnection(
this._rtt,
this._throughput,
estimatedResponseTime,
isTLS
);
connections.set(connectionId, connection);
}
this._connections = connections;
return connections;
} | _initializeNetworkConnections() {
const connections = new Map();
const recordsByConnection = groupBy(
this._networkRecords,
record => record.connectionId
);
for (const [connectionId, records] of recordsByConnection.entries()) {
const isTLS = TLS_SCHEMES.includes(records[0].parsedURL.scheme);
// We'll approximate how much time the server for a connection took to respond after receiving
// the request by computing the minimum TTFB time for requests on that connection.
// TTFB = one way latency + server response time + one way latency
// Even though TTFB is greater than server response time, the RTT is underaccounted for by
// not varying per-server and so the difference roughly evens out.
// TODO(patrickhulce): investigate a way to identify per-server RTT
let estimatedResponseTime = Math.min(...records.map(Estimator.getTTFB));
// If we couldn't find a TTFB for the requests, use the fallback TTFB instead.
if (!Number.isFinite(estimatedResponseTime)) {
estimatedResponseTime = this._fallbackTTFB;
}
const connection = new TcpConnection(
this._rtt,
this._throughput,
estimatedResponseTime,
isTLS
);
connections.set(connectionId, connection);
}
this._connections = connections;
return connections;
} |
JavaScript | _initializeAuxiliaryData() {
this._nodeTiming = new Map();
this._nodesCompleted = new Set();
this._nodesInProgress = new Set();
this._nodesInQueue = new Set(); // TODO: replace this with priority queue
this._connectionsInUse = new Set();
} | _initializeAuxiliaryData() {
this._nodeTiming = new Map();
this._nodesCompleted = new Set();
this._nodesInProgress = new Set();
this._nodesInQueue = new Set(); // TODO: replace this with priority queue
this._connectionsInUse = new Set();
} |
JavaScript | _updateNetworkCapacity() {
for (const connection of this._connectionsInUse) {
connection.setThroughput(this._throughput / this._nodesInProgress.size);
}
} | _updateNetworkCapacity() {
for (const connection of this._connectionsInUse) {
connection.setThroughput(this._throughput / this._nodesInProgress.size);
}
} |
JavaScript | _estimateTimeRemaining(node) {
if (node.type !== Node.TYPES.NETWORK) throw new Error('Unsupported');
const timingData = this._nodeTiming.get(node);
const connection = this._connections.get(node.record.connectionId);
const calculation = connection.simulateDownloadUntil(
node.record.transferSize - timingData.bytesDownloaded,
timingData.timeElapsed
);
const estimate = calculation.timeElapsed + timingData.timeElapsedOvershoot;
timingData.estimatedTimeElapsed = estimate;
return estimate;
} | _estimateTimeRemaining(node) {
if (node.type !== Node.TYPES.NETWORK) throw new Error('Unsupported');
const timingData = this._nodeTiming.get(node);
const connection = this._connections.get(node.record.connectionId);
const calculation = connection.simulateDownloadUntil(
node.record.transferSize - timingData.bytesDownloaded,
timingData.timeElapsed
);
const estimate = calculation.timeElapsed + timingData.timeElapsedOvershoot;
timingData.estimatedTimeElapsed = estimate;
return estimate;
} |
JavaScript | _findNextNodeCompletionTime() {
let minimumTime = Infinity;
for (const node of this._nodesInProgress) {
minimumTime = Math.min(minimumTime, this._estimateTimeRemaining(node));
}
return minimumTime;
} | _findNextNodeCompletionTime() {
let minimumTime = Infinity;
for (const node of this._nodesInProgress) {
minimumTime = Math.min(minimumTime, this._estimateTimeRemaining(node));
}
return minimumTime;
} |
JavaScript | _updateProgressMadeInTimePeriod(node, timePeriodLength, totalElapsedTime) {
if (node.type !== Node.TYPES.NETWORK) throw new Error('Unsupported');
const timingData = this._nodeTiming.get(node);
const connection = this._connections.get(node.record.connectionId);
const calculation = connection.simulateDownloadUntil(
node.record.transferSize - timingData.bytesDownloaded,
timingData.timeElapsed,
timePeriodLength - timingData.timeElapsedOvershoot
);
connection.setCongestionWindow(calculation.congestionWindow);
if (timingData.estimatedTimeElapsed === timePeriodLength) {
timingData.endTime = totalElapsedTime;
connection.setWarmed(true);
this._connectionsInUse.delete(connection);
this._nodesCompleted.add(node);
this._nodesInProgress.delete(node);
for (const dependent of node.getDependents()) {
this._enqueueNodeIfPossible(dependent);
}
} else {
timingData.timeElapsed += calculation.timeElapsed;
timingData.timeElapsedOvershoot += calculation.timeElapsed - timePeriodLength;
timingData.bytesDownloaded += calculation.bytesDownloaded;
}
} | _updateProgressMadeInTimePeriod(node, timePeriodLength, totalElapsedTime) {
if (node.type !== Node.TYPES.NETWORK) throw new Error('Unsupported');
const timingData = this._nodeTiming.get(node);
const connection = this._connections.get(node.record.connectionId);
const calculation = connection.simulateDownloadUntil(
node.record.transferSize - timingData.bytesDownloaded,
timingData.timeElapsed,
timePeriodLength - timingData.timeElapsedOvershoot
);
connection.setCongestionWindow(calculation.congestionWindow);
if (timingData.estimatedTimeElapsed === timePeriodLength) {
timingData.endTime = totalElapsedTime;
connection.setWarmed(true);
this._connectionsInUse.delete(connection);
this._nodesCompleted.add(node);
this._nodesInProgress.delete(node);
for (const dependent of node.getDependents()) {
this._enqueueNodeIfPossible(dependent);
}
} else {
timingData.timeElapsed += calculation.timeElapsed;
timingData.timeElapsedOvershoot += calculation.timeElapsed - timePeriodLength;
timingData.bytesDownloaded += calculation.bytesDownloaded;
}
} |
JavaScript | estimate() {
// initialize all the necessary data containers
this._initializeNetworkRecords();
this._initializeNetworkConnections();
this._initializeAuxiliaryData();
const nodesInQueue = this._nodesInQueue;
const nodesInProgress = this._nodesInProgress;
// add root node to queue
nodesInQueue.add(this._graph.getRootNode());
let depth = 0;
let totalElapsedTime = 0;
while (nodesInQueue.size || nodesInProgress.size) {
depth++;
// move all possible queued nodes to in progress
for (const node of nodesInQueue) {
this._startNodeIfPossible(node, totalElapsedTime);
}
// set the available throughput for all connections based on # inflight
this._updateNetworkCapacity();
// find the time that the next node will finish
const minimumTime = this._findNextNodeCompletionTime();
totalElapsedTime += minimumTime;
// update how far each node will progress until that point
for (const node of nodesInProgress) {
this._updateProgressMadeInTimePeriod(
node,
minimumTime,
totalElapsedTime
);
}
if (depth > 10000) {
throw new Error('Maximum depth exceeded: estimate');
}
}
return totalElapsedTime;
} | estimate() {
// initialize all the necessary data containers
this._initializeNetworkRecords();
this._initializeNetworkConnections();
this._initializeAuxiliaryData();
const nodesInQueue = this._nodesInQueue;
const nodesInProgress = this._nodesInProgress;
// add root node to queue
nodesInQueue.add(this._graph.getRootNode());
let depth = 0;
let totalElapsedTime = 0;
while (nodesInQueue.size || nodesInProgress.size) {
depth++;
// move all possible queued nodes to in progress
for (const node of nodesInQueue) {
this._startNodeIfPossible(node, totalElapsedTime);
}
// set the available throughput for all connections based on # inflight
this._updateNetworkCapacity();
// find the time that the next node will finish
const minimumTime = this._findNextNodeCompletionTime();
totalElapsedTime += minimumTime;
// update how far each node will progress until that point
for (const node of nodesInProgress) {
this._updateProgressMadeInTimePeriod(
node,
minimumTime,
totalElapsedTime
);
}
if (depth > 10000) {
throw new Error('Maximum depth exceeded: estimate');
}
}
return totalElapsedTime;
} |
JavaScript | function isType(type) {
return function(obj) {
return {}.toString.call(obj) == "[object " + type + "]";
}
} | function isType(type) {
return function(obj) {
return {}.toString.call(obj) == "[object " + type + "]";
}
} |
JavaScript | function normalize(path) {
var last = path.length - 1;
var lastC = path.charAt(last);
// If the uri ends with `#`, just return it without '#'
if (lastC === "#") {
return path.substring(0, last);
}
return (path.substring(last - 2) === ".js" ||
path.indexOf("?") > 0 ||
lastC === "/") ? path : path + ".js"
} | function normalize(path) {
var last = path.length - 1;
var lastC = path.charAt(last);
// If the uri ends with `#`, just return it without '#'
if (lastC === "#") {
return path.substring(0, last);
}
return (path.substring(last - 2) === ".js" ||
path.indexOf("?") > 0 ||
lastC === "/") ? path : path + ".js"
} |
JavaScript | function testPlayerVersion() {
var b = doc.getElementsByTagName("body")[0];
var o = createElement(OBJECT);
o.setAttribute("type", FLASH_MIME_TYPE);
var t = b.appendChild(o);
if (t) {
var counter = 0;
(function () {
if (typeof t.GetVariable != UNDEF) {
var d = t.GetVariable("$version");
if (d) {
d = d.split(" ")[1].split(",");
ua.pv = [parseInt(d[0], 10), parseInt(d[1], 10), parseInt(d[2], 10)];
}
}
else if (counter < 10) {
counter++;
setTimeout(arguments.callee, 10);
return;
}
b.removeChild(o);
t = null;
matchVersions();
})();
}
else {
matchVersions();
}
} | function testPlayerVersion() {
var b = doc.getElementsByTagName("body")[0];
var o = createElement(OBJECT);
o.setAttribute("type", FLASH_MIME_TYPE);
var t = b.appendChild(o);
if (t) {
var counter = 0;
(function () {
if (typeof t.GetVariable != UNDEF) {
var d = t.GetVariable("$version");
if (d) {
d = d.split(" ")[1].split(",");
ua.pv = [parseInt(d[0], 10), parseInt(d[1], 10), parseInt(d[2], 10)];
}
}
else if (counter < 10) {
counter++;
setTimeout(arguments.callee, 10);
return;
}
b.removeChild(o);
t = null;
matchVersions();
})();
}
else {
matchVersions();
}
} |
JavaScript | function matchVersions() {
var rl = regObjArr.length;
if (rl > 0) {
for (var i = 0; i < rl; i++) { // for each registered object element
var id = regObjArr[i].id;
var cb = regObjArr[i].callbackFn;
var cbObj = {success: false, id: id};
if (ua.pv[0] > 0) {
var obj = getElementById(id);
if (obj) {
if (hasPlayerVersion(regObjArr[i].swfVersion) && !(ua.wk && ua.wk < 312)) { // Flash Player version >= published SWF version: Houston, we have a match!
setVisibility(id, true);
if (cb) {
cbObj.success = true;
cbObj.ref = getObjectById(id);
cb(cbObj);
}
}
else if (regObjArr[i].expressInstall && canExpressInstall()) { // show the Adobe Express Install dialog if set by the web page author and if supported
var att = {};
att.data = regObjArr[i].expressInstall;
att.width = obj.getAttribute("width") || "0";
att.height = obj.getAttribute("height") || "0";
if (obj.getAttribute("class")) {
att.styleclass = obj.getAttribute("class");
}
if (obj.getAttribute("align")) {
att.align = obj.getAttribute("align");
}
// parse HTML object param element's name-value pairs
var par = {};
var p = obj.getElementsByTagName("param");
var pl = p.length;
for (var j = 0; j < pl; j++) {
if (p[j].getAttribute("name").toLowerCase() != "movie") {
par[p[j].getAttribute("name")] = p[j].getAttribute("value");
}
}
showExpressInstall(att, par, id, cb);
}
else { // Flash Player and SWF version mismatch or an older Webkit engine that ignores the HTML object element's nested param elements: display alternative content instead of SWF
displayAltContent(obj);
if (cb) {
cb(cbObj);
}
}
}
}
else { // if no Flash Player is installed or the fp version cannot be detected we let the HTML object element do its job (either show a SWF or alternative content)
setVisibility(id, true);
if (cb) {
var o = getObjectById(id); // test whether there is an HTML object element or not
if (o && typeof o.SetVariable != UNDEF) {
cbObj.success = true;
cbObj.ref = o;
}
cb(cbObj);
}
}
}
}
} | function matchVersions() {
var rl = regObjArr.length;
if (rl > 0) {
for (var i = 0; i < rl; i++) { // for each registered object element
var id = regObjArr[i].id;
var cb = regObjArr[i].callbackFn;
var cbObj = {success: false, id: id};
if (ua.pv[0] > 0) {
var obj = getElementById(id);
if (obj) {
if (hasPlayerVersion(regObjArr[i].swfVersion) && !(ua.wk && ua.wk < 312)) { // Flash Player version >= published SWF version: Houston, we have a match!
setVisibility(id, true);
if (cb) {
cbObj.success = true;
cbObj.ref = getObjectById(id);
cb(cbObj);
}
}
else if (regObjArr[i].expressInstall && canExpressInstall()) { // show the Adobe Express Install dialog if set by the web page author and if supported
var att = {};
att.data = regObjArr[i].expressInstall;
att.width = obj.getAttribute("width") || "0";
att.height = obj.getAttribute("height") || "0";
if (obj.getAttribute("class")) {
att.styleclass = obj.getAttribute("class");
}
if (obj.getAttribute("align")) {
att.align = obj.getAttribute("align");
}
// parse HTML object param element's name-value pairs
var par = {};
var p = obj.getElementsByTagName("param");
var pl = p.length;
for (var j = 0; j < pl; j++) {
if (p[j].getAttribute("name").toLowerCase() != "movie") {
par[p[j].getAttribute("name")] = p[j].getAttribute("value");
}
}
showExpressInstall(att, par, id, cb);
}
else { // Flash Player and SWF version mismatch or an older Webkit engine that ignores the HTML object element's nested param elements: display alternative content instead of SWF
displayAltContent(obj);
if (cb) {
cb(cbObj);
}
}
}
}
else { // if no Flash Player is installed or the fp version cannot be detected we let the HTML object element do its job (either show a SWF or alternative content)
setVisibility(id, true);
if (cb) {
var o = getObjectById(id); // test whether there is an HTML object element or not
if (o && typeof o.SetVariable != UNDEF) {
cbObj.success = true;
cbObj.ref = o;
}
cb(cbObj);
}
}
}
}
} |
JavaScript | function displayAltContent(obj) {
if (ua.ie && ua.win && obj.readyState != 4) {
// IE only: when a SWF is loading (AND: not available in cache) wait for the readyState of the object element to become 4 before removing it,
// because you cannot properly cancel a loading SWF file without breaking browser load references, also obj.onreadystatechange doesn't work
var el = createElement("div");
obj.parentNode.insertBefore(el, obj); // insert placeholder div that will be replaced by the alternative content
el.parentNode.replaceChild(abstractAltContent(obj), el);
obj.style.display = "none";
(function () {
if (obj.readyState == 4) {
obj.parentNode.removeChild(obj);
}
else {
setTimeout(arguments.callee, 10);
}
})();
}
else {
obj.parentNode.replaceChild(abstractAltContent(obj), obj);
}
} | function displayAltContent(obj) {
if (ua.ie && ua.win && obj.readyState != 4) {
// IE only: when a SWF is loading (AND: not available in cache) wait for the readyState of the object element to become 4 before removing it,
// because you cannot properly cancel a loading SWF file without breaking browser load references, also obj.onreadystatechange doesn't work
var el = createElement("div");
obj.parentNode.insertBefore(el, obj); // insert placeholder div that will be replaced by the alternative content
el.parentNode.replaceChild(abstractAltContent(obj), el);
obj.style.display = "none";
(function () {
if (obj.readyState == 4) {
obj.parentNode.removeChild(obj);
}
else {
setTimeout(arguments.callee, 10);
}
})();
}
else {
obj.parentNode.replaceChild(abstractAltContent(obj), obj);
}
} |
JavaScript | function createSWF(attObj, parObj, id) {
var r, el = getElementById(id);
if (ua.wk && ua.wk < 312) {
return r;
}
if (el) {
if (typeof attObj.id == UNDEF) { // if no 'id' is defined for the object element, it will inherit the 'id' from the alternative content
attObj.id = id;
}
if (ua.ie && ua.win) { // Internet Explorer + the HTML object element + W3C DOM methods do not combine: fall back to outerHTML
var att = "";
for (var i in attObj) {
if (attObj[i] != Object.prototype[i]) { // filter out prototype additions from other potential libraries
if (i.toLowerCase() == "data") {
parObj.movie = attObj[i];
}
else if (i.toLowerCase() == "styleclass") { // 'class' is an ECMA4 reserved keyword
att += ' class="' + attObj[i] + '"';
}
else if (i.toLowerCase() != "classid") {
att += ' ' + i + '="' + attObj[i] + '"';
}
}
}
var par = "";
for (var j in parObj) {
if (parObj[j] != Object.prototype[j]) { // filter out prototype additions from other potential libraries
par += '<param name="' + j + '" value="' + parObj[j] + '" />';
}
}
el.outerHTML = '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"' + att + '>' + par + '</object>';
objIdArr[objIdArr.length] = attObj.id; // stored to fix object 'leaks' on unload (dynamic publishing only)
r = getElementById(attObj.id);
}
else { // well-behaving browsers
var o = createElement(OBJECT);
o.setAttribute("type", FLASH_MIME_TYPE);
for (var m in attObj) {
if (attObj[m] != Object.prototype[m]) { // filter out prototype additions from other potential libraries
if (m.toLowerCase() == "styleclass") { // 'class' is an ECMA4 reserved keyword
o.setAttribute("class", attObj[m]);
}
else if (m.toLowerCase() != "classid") { // filter out IE specific attribute
o.setAttribute(m, attObj[m]);
}
}
}
for (var n in parObj) {
if (parObj[n] != Object.prototype[n] && n.toLowerCase() != "movie") { // filter out prototype additions from other potential libraries and IE specific param element
createObjParam(o, n, parObj[n]);
}
}
el.parentNode.replaceChild(o, el);
r = o;
}
}
return r;
} | function createSWF(attObj, parObj, id) {
var r, el = getElementById(id);
if (ua.wk && ua.wk < 312) {
return r;
}
if (el) {
if (typeof attObj.id == UNDEF) { // if no 'id' is defined for the object element, it will inherit the 'id' from the alternative content
attObj.id = id;
}
if (ua.ie && ua.win) { // Internet Explorer + the HTML object element + W3C DOM methods do not combine: fall back to outerHTML
var att = "";
for (var i in attObj) {
if (attObj[i] != Object.prototype[i]) { // filter out prototype additions from other potential libraries
if (i.toLowerCase() == "data") {
parObj.movie = attObj[i];
}
else if (i.toLowerCase() == "styleclass") { // 'class' is an ECMA4 reserved keyword
att += ' class="' + attObj[i] + '"';
}
else if (i.toLowerCase() != "classid") {
att += ' ' + i + '="' + attObj[i] + '"';
}
}
}
var par = "";
for (var j in parObj) {
if (parObj[j] != Object.prototype[j]) { // filter out prototype additions from other potential libraries
par += '<param name="' + j + '" value="' + parObj[j] + '" />';
}
}
el.outerHTML = '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"' + att + '>' + par + '</object>';
objIdArr[objIdArr.length] = attObj.id; // stored to fix object 'leaks' on unload (dynamic publishing only)
r = getElementById(attObj.id);
}
else { // well-behaving browsers
var o = createElement(OBJECT);
o.setAttribute("type", FLASH_MIME_TYPE);
for (var m in attObj) {
if (attObj[m] != Object.prototype[m]) { // filter out prototype additions from other potential libraries
if (m.toLowerCase() == "styleclass") { // 'class' is an ECMA4 reserved keyword
o.setAttribute("class", attObj[m]);
}
else if (m.toLowerCase() != "classid") { // filter out IE specific attribute
o.setAttribute(m, attObj[m]);
}
}
}
for (var n in parObj) {
if (parObj[n] != Object.prototype[n] && n.toLowerCase() != "movie") { // filter out prototype additions from other potential libraries and IE specific param element
createObjParam(o, n, parObj[n]);
}
}
el.parentNode.replaceChild(o, el);
r = o;
}
}
return r;
} |
JavaScript | function removeSWF(id) {
var obj = getElementById(id);
if (obj && obj.nodeName == "OBJECT") {
if (ua.ie && ua.win) {
obj.style.display = "none";
(function () {
if (obj.readyState == 4) {
removeObjectInIE(id);
}
else {
setTimeout(arguments.callee, 10);
}
})();
}
else {
obj.parentNode.removeChild(obj);
}
}
} | function removeSWF(id) {
var obj = getElementById(id);
if (obj && obj.nodeName == "OBJECT") {
if (ua.ie && ua.win) {
obj.style.display = "none";
(function () {
if (obj.readyState == 4) {
removeObjectInIE(id);
}
else {
setTimeout(arguments.callee, 10);
}
})();
}
else {
obj.parentNode.removeChild(obj);
}
}
} |
JavaScript | function checkCanConfigure(configOptionName) {
if (initialized) {
handleError("AjaxAppender: configuration option '" +
configOptionName +
"' may not be set after the appender has been initialized");
return false;
}
return true;
} | function checkCanConfigure(configOptionName) {
if (initialized) {
handleError("AjaxAppender: configuration option '" +
configOptionName +
"' may not be set after the appender has been initialized");
return false;
}
return true;
} |
JavaScript | function to(promise) {
return promise.then(data => {
return [null, data];
})
.catch(err => [err]);
} | function to(promise) {
return promise.then(data => {
return [null, data];
})
.catch(err => [err]);
} |
JavaScript | function start() {
return __awaiter(this, void 0, void 0, function* () {
// Run Config Validator check
const areConfigsValid = yield validation_1.validateConfigs();
if (areConfigsValid) {
run();
}
});
} | function start() {
return __awaiter(this, void 0, void 0, function* () {
// Run Config Validator check
const areConfigsValid = yield validation_1.validateConfigs();
if (areConfigsValid) {
run();
}
});
} |
JavaScript | function validateConfigs() {
return __awaiter(this, void 0, void 0, function* () {
const configs = yield getFilenames(pathToConfigs);
const schemas = yield getFilenames(pathToSchemas);
return yield configs.map((configName) => {
const expectedSchemaName = getExpectedSchemaName(configName);
const schemaIndex = schemas.indexOf(expectedSchemaName);
// Compare schema name to config name
if (schemaIndex !== undefined) {
const config = require(pathToConfigs + '/' + configName);
const schema = require(pathToSchemas + '/' + schemas[schemaIndex]);
const result = validate(config, schema);
if (!result) {
console.log(configName + ' does not match its\' schema.');
}
return result;
}
console.log('Schema for ' + configName + ' was not found; Assuming correct.');
return true;
})
.reduce((stack, current) => stack && current);
});
} | function validateConfigs() {
return __awaiter(this, void 0, void 0, function* () {
const configs = yield getFilenames(pathToConfigs);
const schemas = yield getFilenames(pathToSchemas);
return yield configs.map((configName) => {
const expectedSchemaName = getExpectedSchemaName(configName);
const schemaIndex = schemas.indexOf(expectedSchemaName);
// Compare schema name to config name
if (schemaIndex !== undefined) {
const config = require(pathToConfigs + '/' + configName);
const schema = require(pathToSchemas + '/' + schemas[schemaIndex]);
const result = validate(config, schema);
if (!result) {
console.log(configName + ' does not match its\' schema.');
}
return result;
}
console.log('Schema for ' + configName + ' was not found; Assuming correct.');
return true;
})
.reduce((stack, current) => stack && current);
});
} |
JavaScript | static fromConfig(config) {
let result = new ContainerConfig();
if (config == null)
return result;
let names = config.getSectionNames();
for (let i = 0; i < names.length; i++) {
let componentConfig = config.getSection(names[i]);
result.push(ComponentConfig_1.ComponentConfig.fromConfig(componentConfig));
}
return result;
} | static fromConfig(config) {
let result = new ContainerConfig();
if (config == null)
return result;
let names = config.getSectionNames();
for (let i = 0; i < names.length; i++) {
let componentConfig = config.getSection(names[i]);
result.push(ComponentConfig_1.ComponentConfig.fromConfig(componentConfig));
}
return result;
} |
JavaScript | open(correlationId) {
return __awaiter(this, void 0, void 0, function* () {
if (!this._opened) {
let components = this.getAll();
yield pip_services3_commons_nodex_1.Opener.open(correlationId, components);
this._opened = true;
}
});
} | open(correlationId) {
return __awaiter(this, void 0, void 0, function* () {
if (!this._opened) {
let components = this.getAll();
yield pip_services3_commons_nodex_1.Opener.open(correlationId, components);
this._opened = true;
}
});
} |
JavaScript | close(correlationId) {
return __awaiter(this, void 0, void 0, function* () {
if (this._opened) {
let components = this.getAll();
yield pip_services3_commons_nodex_2.Closer.close(correlationId, components);
this._opened = false;
}
});
} | close(correlationId) {
return __awaiter(this, void 0, void 0, function* () {
if (this._opened) {
let components = this.getAll();
yield pip_services3_commons_nodex_2.Closer.close(correlationId, components);
this._opened = false;
}
});
} |
JavaScript | put(locator, component) {
super.put(locator, component);
if (this._opened) {
pip_services3_commons_nodex_1.Opener.openOne(null, component);
}
} | put(locator, component) {
super.put(locator, component);
if (this._opened) {
pip_services3_commons_nodex_1.Opener.openOne(null, component);
}
} |
JavaScript | remove(locator) {
let component = super.remove(locator);
if (this._opened) {
pip_services3_commons_nodex_2.Closer.closeOne(null, component);
}
return component;
} | remove(locator) {
let component = super.remove(locator);
if (this._opened) {
pip_services3_commons_nodex_2.Closer.closeOne(null, component);
}
return component;
} |
JavaScript | removeAll(locator) {
let components = super.removeAll(locator);
if (this._opened) {
pip_services3_commons_nodex_2.Closer.close(null, components);
}
return components;
} | removeAll(locator) {
let components = super.removeAll(locator);
if (this._opened) {
pip_services3_commons_nodex_2.Closer.close(null, components);
}
return components;
} |
JavaScript | open(correlationId) {
return __awaiter(this, void 0, void 0, function* () {
if (this._references != null) {
throw new pip_services3_commons_nodex_2.InvalidStateException(correlationId, "ALREADY_OPENED", "Container was already opened");
}
try {
this._logger.trace(correlationId, "Starting container.");
// Create references with configured components
this._references = new ContainerReferences_1.ContainerReferences();
this.initReferences(this._references);
this._references.putFromConfig(this._config);
this.setReferences(this._references);
// Get custom description if available
let infoDescriptor = new pip_services3_commons_nodex_1.Descriptor("*", "context-info", "*", "*", "*");
this._info = this._references.getOneOptional(infoDescriptor);
yield this._references.open(correlationId);
// Get reference to logger
this._logger = new pip_services3_components_nodex_2.CompositeLogger(this._references);
this._logger.info(correlationId, "Container %s started.", this._info.name);
}
catch (ex) {
this._logger.fatal(correlationId, ex, "Failed to start container");
yield this.close(correlationId);
throw ex;
}
});
} | open(correlationId) {
return __awaiter(this, void 0, void 0, function* () {
if (this._references != null) {
throw new pip_services3_commons_nodex_2.InvalidStateException(correlationId, "ALREADY_OPENED", "Container was already opened");
}
try {
this._logger.trace(correlationId, "Starting container.");
// Create references with configured components
this._references = new ContainerReferences_1.ContainerReferences();
this.initReferences(this._references);
this._references.putFromConfig(this._config);
this.setReferences(this._references);
// Get custom description if available
let infoDescriptor = new pip_services3_commons_nodex_1.Descriptor("*", "context-info", "*", "*", "*");
this._info = this._references.getOneOptional(infoDescriptor);
yield this._references.open(correlationId);
// Get reference to logger
this._logger = new pip_services3_components_nodex_2.CompositeLogger(this._references);
this._logger.info(correlationId, "Container %s started.", this._info.name);
}
catch (ex) {
this._logger.fatal(correlationId, ex, "Failed to start container");
yield this.close(correlationId);
throw ex;
}
});
} |
JavaScript | close(correlationId) {
return __awaiter(this, void 0, void 0, function* () {
// Skip if container wasn't opened
if (this._references == null) {
return null;
}
try {
this._logger.trace(correlationId, "Stopping %s container", this._info.name);
// Unset references for child container
this.unsetReferences();
// Close and dereference components
yield this._references.close(correlationId);
this._references = null;
this._logger.info(correlationId, "Container %s stopped", this._info.name);
}
catch (ex) {
this._logger.error(correlationId, ex, "Failed to stop container");
throw ex;
}
});
} | close(correlationId) {
return __awaiter(this, void 0, void 0, function* () {
// Skip if container wasn't opened
if (this._references == null) {
return null;
}
try {
this._logger.trace(correlationId, "Stopping %s container", this._info.name);
// Unset references for child container
this.unsetReferences();
// Close and dereference components
yield this._references.close(correlationId);
this._references = null;
this._logger.info(correlationId, "Container %s stopped", this._info.name);
}
catch (ex) {
this._logger.error(correlationId, ex, "Failed to stop container");
throw ex;
}
});
} |
JavaScript | putFromConfig(config) {
for (let i = 0; i < config.length; i++) {
let componentConfig = config[i];
let component;
let locator;
try {
// Create component dynamically
if (componentConfig.type != null) {
locator = componentConfig.type;
component = pip_services3_commons_nodex_1.TypeReflector.createInstanceByDescriptor(componentConfig.type);
}
// Or create component statically
else if (componentConfig.descriptor != null) {
locator = componentConfig.descriptor;
let factory = this._builder.findFactory(locator);
component = this._builder.create(locator, factory);
if (component == null) {
throw new pip_services3_commons_nodex_2.ReferenceException(null, locator);
}
locator = this._builder.clarifyLocator(locator, factory);
}
// Check that component was created
if (component == null) {
throw new pip_services3_components_nodex_1.CreateException("CANNOT_CREATE_COMPONENT", "Cannot create component")
.withDetails("config", config);
}
// Add component to the list
this._references.put(locator, component);
if (component.configure) {
// Configure component
let configurable = component;
configurable.configure(componentConfig.config);
}
// Set references to factories
if (component.canCreate && component.create) {
let referenceable = component;
referenceable.setReferences(this);
}
}
catch (ex) {
throw new pip_services3_commons_nodex_2.ReferenceException(null, locator)
.withCause(ex);
}
}
} | putFromConfig(config) {
for (let i = 0; i < config.length; i++) {
let componentConfig = config[i];
let component;
let locator;
try {
// Create component dynamically
if (componentConfig.type != null) {
locator = componentConfig.type;
component = pip_services3_commons_nodex_1.TypeReflector.createInstanceByDescriptor(componentConfig.type);
}
// Or create component statically
else if (componentConfig.descriptor != null) {
locator = componentConfig.descriptor;
let factory = this._builder.findFactory(locator);
component = this._builder.create(locator, factory);
if (component == null) {
throw new pip_services3_commons_nodex_2.ReferenceException(null, locator);
}
locator = this._builder.clarifyLocator(locator, factory);
}
// Check that component was created
if (component == null) {
throw new pip_services3_components_nodex_1.CreateException("CANNOT_CREATE_COMPONENT", "Cannot create component")
.withDetails("config", config);
}
// Add component to the list
this._references.put(locator, component);
if (component.configure) {
// Configure component
let configurable = component;
configurable.configure(componentConfig.config);
}
// Set references to factories
if (component.canCreate && component.create) {
let referenceable = component;
referenceable.setReferences(this);
}
}
catch (ex) {
throw new pip_services3_commons_nodex_2.ReferenceException(null, locator)
.withCause(ex);
}
}
} |
JavaScript | static fromConfig(config) {
let descriptor = pip_services3_commons_nodex_1.Descriptor.fromString(config.getAsNullableString("descriptor"));
let type = pip_services3_commons_nodex_2.TypeDescriptor.fromString(config.getAsNullableString("type"));
if (descriptor == null && type == null) {
throw new pip_services3_commons_nodex_3.ConfigException(null, "BAD_CONFIG", "Component configuration must have descriptor or type");
}
return new ComponentConfig(descriptor, type, config);
} | static fromConfig(config) {
let descriptor = pip_services3_commons_nodex_1.Descriptor.fromString(config.getAsNullableString("descriptor"));
let type = pip_services3_commons_nodex_2.TypeDescriptor.fromString(config.getAsNullableString("type"));
if (descriptor == null && type == null) {
throw new pip_services3_commons_nodex_3.ConfigException(null, "BAD_CONFIG", "Component configuration must have descriptor or type");
}
return new ComponentConfig(descriptor, type, config);
} |
JavaScript | open(correlationId) {
return __awaiter(this, void 0, void 0, function* () {
yield this._linker.open(correlationId);
yield this._runner.open(correlationId);
});
} | open(correlationId) {
return __awaiter(this, void 0, void 0, function* () {
yield this._linker.open(correlationId);
yield this._runner.open(correlationId);
});
} |
JavaScript | close(correlationId) {
return __awaiter(this, void 0, void 0, function* () {
yield this._runner.close(correlationId);
yield this._linker.close(correlationId);
});
} | close(correlationId) {
return __awaiter(this, void 0, void 0, function* () {
yield this._runner.close(correlationId);
yield this._linker.close(correlationId);
});
} |
JavaScript | run(args) {
if (this.showHelp(args)) {
this.printHelp();
return;
}
let correlationId = this._info.name;
let path = this.getConfigPath(args);
let parameters = this.getParameters(args);
this.readConfigFromFile(correlationId, path, parameters);
this.captureErrors(correlationId);
this.captureExit(correlationId);
this.open(correlationId);
} | run(args) {
if (this.showHelp(args)) {
this.printHelp();
return;
}
let correlationId = this._info.name;
let path = this.getConfigPath(args);
let parameters = this.getParameters(args);
this.readConfigFromFile(correlationId, path, parameters);
this.captureErrors(correlationId);
this.captureExit(correlationId);
this.open(correlationId);
} |
JavaScript | static readFromFile(correlationId, path, parameters) {
if (path == null) {
throw new pip_services3_commons_nodex_1.ConfigException(correlationId, "NO_PATH", "Missing config file path");
}
let ext = path.split('.').pop();
if (ext == "json") {
return ContainerConfigReader.readFromJsonFile(correlationId, path, parameters);
}
if (ext == "yaml" || ext == "yml") {
return ContainerConfigReader.readFromYamlFile(correlationId, path, parameters);
}
// By default read as JSON
return ContainerConfigReader.readFromJsonFile(correlationId, path, parameters);
} | static readFromFile(correlationId, path, parameters) {
if (path == null) {
throw new pip_services3_commons_nodex_1.ConfigException(correlationId, "NO_PATH", "Missing config file path");
}
let ext = path.split('.').pop();
if (ext == "json") {
return ContainerConfigReader.readFromJsonFile(correlationId, path, parameters);
}
if (ext == "yaml" || ext == "yml") {
return ContainerConfigReader.readFromYamlFile(correlationId, path, parameters);
}
// By default read as JSON
return ContainerConfigReader.readFromJsonFile(correlationId, path, parameters);
} |
JavaScript | open(correlationId) {
return __awaiter(this, void 0, void 0, function* () {
if (!this._opened) {
this._opened = true;
let components = this.getAll();
pip_services3_commons_nodex_1.Referencer.setReferences(this.topReferences, components);
}
});
} | open(correlationId) {
return __awaiter(this, void 0, void 0, function* () {
if (!this._opened) {
this._opened = true;
let components = this.getAll();
pip_services3_commons_nodex_1.Referencer.setReferences(this.topReferences, components);
}
});
} |
JavaScript | close(correlationId) {
return __awaiter(this, void 0, void 0, function* () {
if (this._opened) {
this._opened = false;
let components = this.getAll();
pip_services3_commons_nodex_1.Referencer.unsetReferences(components);
}
});
} | close(correlationId) {
return __awaiter(this, void 0, void 0, function* () {
if (this._opened) {
this._opened = false;
let components = this.getAll();
pip_services3_commons_nodex_1.Referencer.unsetReferences(components);
}
});
} |
JavaScript | put(locator, component) {
super.put(locator, component);
if (this._opened) {
pip_services3_commons_nodex_1.Referencer.setReferencesForOne(this.topReferences, component);
}
} | put(locator, component) {
super.put(locator, component);
if (this._opened) {
pip_services3_commons_nodex_1.Referencer.setReferencesForOne(this.topReferences, component);
}
} |
JavaScript | remove(locator) {
let component = super.remove(locator);
if (this._opened) {
pip_services3_commons_nodex_1.Referencer.unsetReferencesForOne(component);
}
return component;
} | remove(locator) {
let component = super.remove(locator);
if (this._opened) {
pip_services3_commons_nodex_1.Referencer.unsetReferencesForOne(component);
}
return component;
} |
JavaScript | removeAll(locator) {
let components = super.removeAll(locator);
if (this._opened) {
pip_services3_commons_nodex_1.Referencer.unsetReferences(components);
}
return components;
} | removeAll(locator) {
let components = super.removeAll(locator);
if (this._opened) {
pip_services3_commons_nodex_1.Referencer.unsetReferences(components);
}
return components;
} |
JavaScript | function onListening() {
const addr = server.address();
const bind = typeof addr === 'string' ? `pipe ${addr}` : `port ${addr.port}`;
debug(`Listening on ${bind}`);
logger.info(
`Server Listening on ${bind} (use port ${process.env.CLIENT_PORT}/api as a proxy)`,
);
} | function onListening() {
const addr = server.address();
const bind = typeof addr === 'string' ? `pipe ${addr}` : `port ${addr.port}`;
debug(`Listening on ${bind}`);
logger.info(
`Server Listening on ${bind} (use port ${process.env.CLIENT_PORT}/api as a proxy)`,
);
} |
JavaScript | function updateOpenshiftDedicated() {
let $privateChecks = $('#private .iaas-check');
if ( $('#openshift-dedicated').prop('checked') ) {
$privateChecks
.prop('checked', false)
.prop('disabled', true)
.addClass('locked')
.change();
} else {
$privateChecks
.removeClass('locked')
.prop('disabled', false);
}
} | function updateOpenshiftDedicated() {
let $privateChecks = $('#private .iaas-check');
if ( $('#openshift-dedicated').prop('checked') ) {
$privateChecks
.prop('checked', false)
.prop('disabled', true)
.addClass('locked')
.change();
} else {
$privateChecks
.removeClass('locked')
.prop('disabled', false);
}
} |
JavaScript | function menuexpand(x){
x.classList.toggle("change");
var y=document.getElementsByClassName("nav-item");
var i;
for(i=0;i<y.length;i++)
{
y[i].classList.toggle("show");
}
} | function menuexpand(x){
x.classList.toggle("change");
var y=document.getElementsByClassName("nav-item");
var i;
for(i=0;i<y.length;i++)
{
y[i].classList.toggle("show");
}
} |
JavaScript | function initMap() {
//The center location of our map.
var centerOfMap = new google.maps.LatLng(-6.200000, 106.816666);
//Map options.
var options = {
center: centerOfMap, //Set center.
zoom: 7 //The zoom value.
};
//Create the map object.
map = new google.maps.Map(document.getElementById('map'), options);
//Listen for any clicks on the map.
google.maps.event.addListener(map, 'click', function(event) {
//Get the location that the user clicked.
var clickedLocation = event.latLng;
//If the marker hasn't been added.
if(marker === false){
//Create the marker.
marker = new google.maps.Marker({
position: clickedLocation,
map: map,
draggable: true //make it draggable
});
//Listen for drag events!
google.maps.event.addListener(marker, 'dragend', function(event){
markerLocation();
});
} else{
//Marker has already been added, so just change its location.
marker.setPosition(clickedLocation);
}
//Get the marker's location.
markerLocation();
});
} | function initMap() {
//The center location of our map.
var centerOfMap = new google.maps.LatLng(-6.200000, 106.816666);
//Map options.
var options = {
center: centerOfMap, //Set center.
zoom: 7 //The zoom value.
};
//Create the map object.
map = new google.maps.Map(document.getElementById('map'), options);
//Listen for any clicks on the map.
google.maps.event.addListener(map, 'click', function(event) {
//Get the location that the user clicked.
var clickedLocation = event.latLng;
//If the marker hasn't been added.
if(marker === false){
//Create the marker.
marker = new google.maps.Marker({
position: clickedLocation,
map: map,
draggable: true //make it draggable
});
//Listen for drag events!
google.maps.event.addListener(marker, 'dragend', function(event){
markerLocation();
});
} else{
//Marker has already been added, so just change its location.
marker.setPosition(clickedLocation);
}
//Get the marker's location.
markerLocation();
});
} |
JavaScript | function html(fragment) {
if (typeof fragment !== 'string') {
var element = this.nodeType ? this : this[0];
return element ? element.innerHTML : undefined;
}
_util.each(this, function (element) {
return element.innerHTML = fragment;
});
return this;
} | function html(fragment) {
if (typeof fragment !== 'string') {
var element = this.nodeType ? this : this[0];
return element ? element.innerHTML : undefined;
}
_util.each(this, function (element) {
return element.innerHTML = fragment;
});
return this;
} |
JavaScript | function triggerForPath(element, type) {
var params = arguments.length <= 2 || arguments[2] === undefined ? {} : arguments[2];
params.bubbles = false;
var event = new CustomEvent(type, params);
event._target = element;
do {
dispatchEvent(element, event);
} while (element = element.parentNode);
} | function triggerForPath(element, type) {
var params = arguments.length <= 2 || arguments[2] === undefined ? {} : arguments[2];
params.bubbles = false;
var event = new CustomEvent(type, params);
event._target = element;
do {
dispatchEvent(element, event);
} while (element = element.parentNode);
} |
JavaScript | function data(key, value) {
if (typeof key === 'string' && typeof value === 'undefined') {
var element = this.nodeType ? this : this[0];
return element && element[DATAKEYPROP] ? element[DATAKEYPROP][key] : undefined;
}
_util.each(this, function (element) {
element[DATAKEYPROP] = element[DATAKEYPROP] || {};
element[DATAKEYPROP][key] = value;
});
return this;
} | function data(key, value) {
if (typeof key === 'string' && typeof value === 'undefined') {
var element = this.nodeType ? this : this[0];
return element && element[DATAKEYPROP] ? element[DATAKEYPROP][key] : undefined;
}
_util.each(this, function (element) {
element[DATAKEYPROP] = element[DATAKEYPROP] || {};
element[DATAKEYPROP][key] = value;
});
return this;
} |
JavaScript | function prop(key, value) {
if (typeof key === 'string' && typeof value === 'undefined') {
var element = this.nodeType ? this : this[0];
return element && element ? element[key] : undefined;
}
_util.each(this, function (element) {
return element[key] = value;
});
return this;
} | function prop(key, value) {
if (typeof key === 'string' && typeof value === 'undefined') {
var element = this.nodeType ? this : this[0];
return element && element ? element[key] : undefined;
}
_util.each(this, function (element) {
return element[key] = value;
});
return this;
} |
JavaScript | function css(key, value) {
var styleProps = undefined,
prop = undefined,
val = undefined;
if (typeof key === 'string') {
key = camelize(key);
if (typeof value === 'undefined') {
var element = this.nodeType ? this : this[0];
if (element) {
val = element.style[key];
return isNumeric(val) ? parseFloat(val) : val;
}
return undefined;
}
styleProps = {};
styleProps[key] = value;
} else {
styleProps = key;
for (prop in styleProps) {
val = styleProps[prop];
delete styleProps[prop];
styleProps[camelize(prop)] = val;
}
}
_util.each(this, function (element) {
for (prop in styleProps) {
if (styleProps[prop] || styleProps[prop] === 0) {
element.style[prop] = styleProps[prop];
} else {
element.style.removeProperty(dasherize(prop));
}
}
});
return this;
} | function css(key, value) {
var styleProps = undefined,
prop = undefined,
val = undefined;
if (typeof key === 'string') {
key = camelize(key);
if (typeof value === 'undefined') {
var element = this.nodeType ? this : this[0];
if (element) {
val = element.style[key];
return isNumeric(val) ? parseFloat(val) : val;
}
return undefined;
}
styleProps = {};
styleProps[key] = value;
} else {
styleProps = key;
for (prop in styleProps) {
val = styleProps[prop];
delete styleProps[prop];
styleProps[camelize(prop)] = val;
}
}
_util.each(this, function (element) {
for (prop in styleProps) {
if (styleProps[prop] || styleProps[prop] === 0) {
element.style[prop] = styleProps[prop];
} else {
element.style.removeProperty(dasherize(prop));
}
}
});
return this;
} |
JavaScript | function children(selector) {
var nodes = [];
_util.each(this, function (element) {
if (element.children) {
_util.each(element.children, function (child) {
if (!selector || selector && _index.matches(child, selector)) {
nodes.push(child);
}
});
}
});
return _index.$(nodes);
} | function children(selector) {
var nodes = [];
_util.each(this, function (element) {
if (element.children) {
_util.each(element.children, function (child) {
if (!selector || selector && _index.matches(child, selector)) {
nodes.push(child);
}
});
}
});
return _index.$(nodes);
} |
JavaScript | function parent(selector) {
var nodes = [];
_util.each(this, function (element) {
if (!selector || selector && _index.matches(element.parentNode, selector)) {
nodes.push(element.parentNode);
}
});
return _index.$(nodes);
} | function parent(selector) {
var nodes = [];
_util.each(this, function (element) {
if (!selector || selector && _index.matches(element.parentNode, selector)) {
nodes.push(element.parentNode);
}
});
return _index.$(nodes);
} |
JavaScript | function siblings(selector) {
var nodes = [];
_util.each(this, function (element) {
_util.each(element.parentNode.children, function (sibling) {
if (sibling !== element && (!selector || selector && _index.matches(sibling, selector))) {
nodes.push(sibling);
}
});
});
return _index.$(nodes);
} | function siblings(selector) {
var nodes = [];
_util.each(this, function (element) {
_util.each(element.parentNode.children, function (sibling) {
if (sibling !== element && (!selector || selector && _index.matches(sibling, selector))) {
nodes.push(sibling);
}
});
});
return _index.$(nodes);
} |
JavaScript | function attr(key, value) {
if (typeof key === 'string' && typeof value === 'undefined') {
var element = this.nodeType ? this : this[0];
return element ? element.getAttribute(key) : undefined;
}
_util.each(this, function (element) {
if (typeof key === 'object') {
for (var _attr in key) {
element.setAttribute(_attr, key[_attr]);
}
} else {
element.setAttribute(key, value);
}
});
return this;
} | function attr(key, value) {
if (typeof key === 'string' && typeof value === 'undefined') {
var element = this.nodeType ? this : this[0];
return element ? element.getAttribute(key) : undefined;
}
_util.each(this, function (element) {
if (typeof key === 'object') {
for (var _attr in key) {
element.setAttribute(_attr, key[_attr]);
}
} else {
element.setAttribute(key, value);
}
});
return this;
} |
JavaScript | function hasClass(value) {
return (this.nodeType ? [this] : this).some(function (element) {
return element.classList.contains(value);
});
} | function hasClass(value) {
return (this.nodeType ? [this] : this).some(function (element) {
return element.classList.contains(value);
});
} |
JavaScript | function _createDb(indexDb) {
var newDb = new Database();
newDb.originalDb = indexDb;
for (var i = 0; i < newDb.originalDb.objectStoreNames.length; i++) {
var tblName = newDb.originalDb.objectStoreNames[i],
objectStore = indexDb.transaction(tblName, "readonly").objectStore(tblName);
newDb[tblName] = _createEntityTable(objectStore, newDb);
}
return newDb;
} | function _createDb(indexDb) {
var newDb = new Database();
newDb.originalDb = indexDb;
for (var i = 0; i < newDb.originalDb.objectStoreNames.length; i++) {
var tblName = newDb.originalDb.objectStoreNames[i],
objectStore = indexDb.transaction(tblName, "readonly").objectStore(tblName);
newDb[tblName] = _createEntityTable(objectStore, newDb);
}
return newDb;
} |
JavaScript | function _createEntityTable(objectStore, database) {
var newTable = new Table(objectStore.name, database);
this[objectStore.name] = newTable;
return newTable;
} | function _createEntityTable(objectStore, database) {
var newTable = new Table(objectStore.name, database);
this[objectStore.name] = newTable;
return newTable;
} |
JavaScript | function TarUtils() {
var _del = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : _del3.default;
var _os = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : _os3.default;
var _tar = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : _tarFs2.default;
var _process = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : process;
_classCallCheck(this, TarUtils);
this._del = _del;
this._os = _os;
this._process = _process;
this._tar = _tar;
} | function TarUtils() {
var _del = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : _del3.default;
var _os = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : _os3.default;
var _tar = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : _tarFs2.default;
var _process = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : process;
_classCallCheck(this, TarUtils);
this._del = _del;
this._os = _os;
this._process = _process;
this._tar = _tar;
} |
JavaScript | async function serializeSkill(url) {
let settings = { method: "Get" };
const response = await fetch(url, settings)
const json = await response.json();
return new Skill(
json["id"],
json["name"],
json["tools"],
json["projects"],
json["featured-article"],
json["articles"],
json["style"]
);
} | async function serializeSkill(url) {
let settings = { method: "Get" };
const response = await fetch(url, settings)
const json = await response.json();
return new Skill(
json["id"],
json["name"],
json["tools"],
json["projects"],
json["featured-article"],
json["articles"],
json["style"]
);
} |
JavaScript | async function serializeProject(url) {
let settings = { method: "Get" };
const response = await fetch(url, settings)
const json = await response.json();
return new Project(
json["id"],
json["role"],
json["name"],
json["logo"],
json["discord-icon"],
json["version"],
json["skill"],
json["screenshots"],
json["madeWith"],
json["description"],
json["download-link"],
json["website"],
json["promo-video"],
json["featured-article"],
json["articles"],
json["style"]
);
} | async function serializeProject(url) {
let settings = { method: "Get" };
const response = await fetch(url, settings)
const json = await response.json();
return new Project(
json["id"],
json["role"],
json["name"],
json["logo"],
json["discord-icon"],
json["version"],
json["skill"],
json["screenshots"],
json["madeWith"],
json["description"],
json["download-link"],
json["website"],
json["promo-video"],
json["featured-article"],
json["articles"],
json["style"]
);
} |
JavaScript | async function serializeArticle(url) {
let settings = { method: "Get" };
const response = await fetch(url, settings);
const json = await response.json();
return new Article(
json["id"],
json["name"],
json["description"],
json["cover"],
json["redirect"],
json["isVisible"],
json["skills"],
json["tools"],
json["content"],
json["style"]
);
} | async function serializeArticle(url) {
let settings = { method: "Get" };
const response = await fetch(url, settings);
const json = await response.json();
return new Article(
json["id"],
json["name"],
json["description"],
json["cover"],
json["redirect"],
json["isVisible"],
json["skills"],
json["tools"],
json["content"],
json["style"]
);
} |
JavaScript | async function serializeArticles() {
let settings = { method: "Get" };
const response = await fetch("https://www.kekesi.dev/api/article/INDEX.json", settings)
const json = await response.json();
return json;
} | async function serializeArticles() {
let settings = { method: "Get" };
const response = await fetch("https://www.kekesi.dev/api/article/INDEX.json", settings)
const json = await response.json();
return json;
} |
JavaScript | async function serializeProjectBundle(url) {
let settings = { method: "Get" };
const response = await fetch(url, settings)
const json = await response.json();
return new ProjectBundle(
json["id"],
json["name"],
json["projects"],
json["style"]
);
} | async function serializeProjectBundle(url) {
let settings = { method: "Get" };
const response = await fetch(url, settings)
const json = await response.json();
return new ProjectBundle(
json["id"],
json["name"],
json["projects"],
json["style"]
);
} |
JavaScript | function serializeURL(url, type, list) {
let settings = { method: "Get" };
fetch(url, settings)
.then(res => res.json())
.then((json) => {
for (let i = 0; i < json.length; i++) {
list.push(new URL(json[i]["id"], type, json[i]["location"]));
}
});
} | function serializeURL(url, type, list) {
let settings = { method: "Get" };
fetch(url, settings)
.then(res => res.json())
.then((json) => {
for (let i = 0; i < json.length; i++) {
list.push(new URL(json[i]["id"], type, json[i]["location"]));
}
});
} |
JavaScript | async function serializeImage(url) {
let settings = { method: "Get" };
const response = await fetch(url, settings)
const json = await response.json();
if (json["copyright"] !== null) {
setCopyright(json["name"], json["copyright"], json["copyright-link"]);
}
return new Image(
json["id"],
json["name"],
json["url"],
json["description"],
json["width"],
json["height"],
json["copyright"],
json["copyright-link"]
);
} | async function serializeImage(url) {
let settings = { method: "Get" };
const response = await fetch(url, settings)
const json = await response.json();
if (json["copyright"] !== null) {
setCopyright(json["name"], json["copyright"], json["copyright-link"]);
}
return new Image(
json["id"],
json["name"],
json["url"],
json["description"],
json["width"],
json["height"],
json["copyright"],
json["copyright-link"]
);
} |
JavaScript | function offscreen() {
var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
DOMParserFallback = _ref.DOMParser;
var preset = {
window: null,
ignoreAnimation: true,
ignoreMouse: true,
DOMParser: DOMParserFallback,
createCanvas: function createCanvas(width, height) {
return new OffscreenCanvas(width, height);
},
createImage: function createImage(url) {
return (0,_babel_runtime_corejs3_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_13__.default)( /*#__PURE__*/_babel_runtime_corejs3_regenerator__WEBPACK_IMPORTED_MODULE_12___default().mark(function _callee() {
var response, blob, img;
return _babel_runtime_corejs3_regenerator__WEBPACK_IMPORTED_MODULE_12___default().wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
_context.next = 2;
return fetch(url);
case 2:
response = _context.sent;
_context.next = 5;
return response.blob();
case 5:
blob = _context.sent;
_context.next = 8;
return createImageBitmap(blob);
case 8:
img = _context.sent;
return _context.abrupt("return", img);
case 10:
case "end":
return _context.stop();
}
}
}, _callee);
}))();
}
};
if (typeof DOMParser !== 'undefined' || typeof DOMParserFallback === 'undefined') {
_babel_runtime_corejs3_core_js_stable_reflect_delete_property__WEBPACK_IMPORTED_MODULE_39___default()(preset, 'DOMParser');
}
return preset;
} | function offscreen() {
var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
DOMParserFallback = _ref.DOMParser;
var preset = {
window: null,
ignoreAnimation: true,
ignoreMouse: true,
DOMParser: DOMParserFallback,
createCanvas: function createCanvas(width, height) {
return new OffscreenCanvas(width, height);
},
createImage: function createImage(url) {
return (0,_babel_runtime_corejs3_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_13__.default)( /*#__PURE__*/_babel_runtime_corejs3_regenerator__WEBPACK_IMPORTED_MODULE_12___default().mark(function _callee() {
var response, blob, img;
return _babel_runtime_corejs3_regenerator__WEBPACK_IMPORTED_MODULE_12___default().wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
_context.next = 2;
return fetch(url);
case 2:
response = _context.sent;
_context.next = 5;
return response.blob();
case 5:
blob = _context.sent;
_context.next = 8;
return createImageBitmap(blob);
case 8:
img = _context.sent;
return _context.abrupt("return", img);
case 10:
case "end":
return _context.stop();
}
}
}, _callee);
}))();
}
};
if (typeof DOMParser !== 'undefined' || typeof DOMParserFallback === 'undefined') {
_babel_runtime_corejs3_core_js_stable_reflect_delete_property__WEBPACK_IMPORTED_MODULE_39___default()(preset, 'DOMParser');
}
return preset;
} |
JavaScript | function sCurve(length, rotation) {
var curve = new Float32Array(length),
i,
phase = rotation > 0 ? Math.PI / 2 : -(Math.PI / 2);
for (i = 0; i < length; ++i) {
curve[i] = Math.sin(Math.PI * i / length - phase) / 2 + 0.5;
}
return curve;
} | function sCurve(length, rotation) {
var curve = new Float32Array(length),
i,
phase = rotation > 0 ? Math.PI / 2 : -(Math.PI / 2);
for (i = 0; i < length; ++i) {
curve[i] = Math.sin(Math.PI * i / length - phase) / 2 + 0.5;
}
return curve;
} |
JavaScript | function logarithmic(length, base, rotation) {
var curve = new Float32Array(length),
index,
x = 0,
i;
for (i = 0; i < length; i++) {
//index for the curve array.
index = rotation > 0 ? i : length - 1 - i;
x = i / length;
curve[index] = Math.log(1 + base * x) / Math.log(1 + base);
}
return curve;
} | function logarithmic(length, base, rotation) {
var curve = new Float32Array(length),
index,
x = 0,
i;
for (i = 0; i < length; i++) {
//index for the curve array.
index = rotation > 0 ? i : length - 1 - i;
x = i / length;
curve[index] = Math.log(1 + base * x) / Math.log(1 + base);
}
return curve;
} |
JavaScript | function extractPeaks(channel, samplesPerPixel, bits) {
var i;
var chanLength = channel.length;
var numPeaks = Math.ceil(chanLength / samplesPerPixel);
var start;
var end;
var segment;
var max;
var min;
var extrema;
//create interleaved array of min,max
var peaks = makeTypedArray(bits, numPeaks * 2);
for (i = 0; i < numPeaks; i++) {
start = i * samplesPerPixel;
end =
(i + 1) * samplesPerPixel > chanLength
? chanLength
: (i + 1) * samplesPerPixel;
segment = channel.subarray(start, end);
extrema = findMinMax(segment);
min = convert(extrema.min, bits);
max = convert(extrema.max, bits);
peaks[i * 2] = min;
peaks[i * 2 + 1] = max;
}
return peaks;
} | function extractPeaks(channel, samplesPerPixel, bits) {
var i;
var chanLength = channel.length;
var numPeaks = Math.ceil(chanLength / samplesPerPixel);
var start;
var end;
var segment;
var max;
var min;
var extrema;
//create interleaved array of min,max
var peaks = makeTypedArray(bits, numPeaks * 2);
for (i = 0; i < numPeaks; i++) {
start = i * samplesPerPixel;
end =
(i + 1) * samplesPerPixel > chanLength
? chanLength
: (i + 1) * samplesPerPixel;
segment = channel.subarray(start, end);
extrema = findMinMax(segment);
min = convert(extrema.min, bits);
max = convert(extrema.max, bits);
peaks[i * 2] = min;
peaks[i * 2 + 1] = max;
}
return peaks;
} |
JavaScript | load() {
return new Promise((resolve, reject) => {
if (
this.src.type.match(/audio.*/) ||
// added for problems with Firefox mime types + ogg.
this.src.type.match(/video\/ogg/)
) {
const fr = new FileReader();
fr.readAsArrayBuffer(this.src);
fr.addEventListener("progress", (e) => {
super.fileProgress(e);
});
fr.addEventListener("load", (e) => {
const decoderPromise = super.fileLoad(e);
decoderPromise
.then((audioBuffer) => {
resolve(audioBuffer);
})
.catch(reject);
});
fr.addEventListener("error", reject);
} else {
reject(Error(`Unsupported file type ${this.src.type}`));
}
});
} | load() {
return new Promise((resolve, reject) => {
if (
this.src.type.match(/audio.*/) ||
// added for problems with Firefox mime types + ogg.
this.src.type.match(/video\/ogg/)
) {
const fr = new FileReader();
fr.readAsArrayBuffer(this.src);
fr.addEventListener("progress", (e) => {
super.fileProgress(e);
});
fr.addEventListener("load", (e) => {
const decoderPromise = super.fileLoad(e);
decoderPromise
.then((audioBuffer) => {
resolve(audioBuffer);
})
.catch(reject);
});
fr.addEventListener("error", reject);
} else {
reject(Error(`Unsupported file type ${this.src.type}`));
}
});
} |
JavaScript | load() {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.open("GET", this.src, true);
xhr.responseType = "arraybuffer";
xhr.send();
xhr.addEventListener("progress", (e) => {
super.fileProgress(e);
});
xhr.addEventListener("load", (e) => {
const decoderPromise = super.fileLoad(e);
decoderPromise
.then((audioBuffer) => {
resolve(audioBuffer);
})
.catch(reject);
});
xhr.addEventListener("error", () => {
reject(Error(`Track ${this.src} failed to load`));
});
});
} | load() {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.open("GET", this.src, true);
xhr.responseType = "arraybuffer";
xhr.send();
xhr.addEventListener("progress", (e) => {
super.fileProgress(e);
});
xhr.addEventListener("load", (e) => {
const decoderPromise = super.fileLoad(e);
decoderPromise
.then((audioBuffer) => {
resolve(audioBuffer);
})
.catch(reject);
});
xhr.addEventListener("error", () => {
reject(Error(`Track ${this.src} failed to load`));
});
});
} |
JavaScript | load() {
return new Promise((resolve, reject) => {
if (!this.trackInfo.peaksSrc)
resolve(undefined);
const xhr = new XMLHttpRequest();
xhr.open("GET", this.trackInfo.peaksSrc, true);
xhr.responseType = "json";
xhr.send();
xhr.addEventListener("progress", (e) => {
super.fileProgress(e);
});
xhr.addEventListener("load", (e) => {
const decoderPromise = super.fileLoad(e);
decoderPromise
.then((waveformBuffer) => {
var element = document.createElement("audio");
element.className = "audio";
element.setAttribute("preload", "metadata");
var source = document.createElement("source");
source.setAttribute("src", this.trackInfo.src);
source.setAttribute("type", "audio/mpeg");
element.appendChild(source);
var container = document.getElementById("prerendered_waveforms");
container.appendChild(element);
element.onloadedmetadata = function () {
resolve(waveformBuffer);
}
})
.catch(reject);
});
xhr.addEventListener("error", () => {
reject(Error(`Track ${this.src} failed to load`));
});
});
} | load() {
return new Promise((resolve, reject) => {
if (!this.trackInfo.peaksSrc)
resolve(undefined);
const xhr = new XMLHttpRequest();
xhr.open("GET", this.trackInfo.peaksSrc, true);
xhr.responseType = "json";
xhr.send();
xhr.addEventListener("progress", (e) => {
super.fileProgress(e);
});
xhr.addEventListener("load", (e) => {
const decoderPromise = super.fileLoad(e);
decoderPromise
.then((waveformBuffer) => {
var element = document.createElement("audio");
element.className = "audio";
element.setAttribute("preload", "metadata");
var source = document.createElement("source");
source.setAttribute("src", this.trackInfo.src);
source.setAttribute("type", "audio/mpeg");
element.appendChild(source);
var container = document.getElementById("prerendered_waveforms");
container.appendChild(element);
element.onloadedmetadata = function () {
resolve(waveformBuffer);
}
})
.catch(reject);
});
xhr.addEventListener("error", () => {
reject(Error(`Track ${this.src} failed to load`));
});
});
} |
JavaScript | static formatTime(milliseconds) {
const seconds = milliseconds / 1000;
let s = seconds % 60;
const m = (seconds - s) / 60;
if (s < 10) {
s = `0${s}`;
}
return `${m}:${s}`;
} | static formatTime(milliseconds) {
const seconds = milliseconds / 1000;
let s = seconds % 60;
const m = (seconds - s) / 60;
if (s < 10) {
s = `0${s}`;
}
return `${m}:${s}`;
} |
JavaScript | trim(start, end) {
const trackStart = this.getStartTime();
const trackEnd = this.getEndTime();
const offset = this.cueIn - trackStart;
if (
(trackStart <= start && trackEnd >= start) ||
(trackStart <= end && trackEnd >= end)
) {
const cueIn = start < trackStart ? trackStart : start;
const cueOut = end > trackEnd ? trackEnd : end;
this.setCues(cueIn + offset, cueOut + offset);
if (start > trackStart) {
this.setStartTime(start);
}
}
} | trim(start, end) {
const trackStart = this.getStartTime();
const trackEnd = this.getEndTime();
const offset = this.cueIn - trackStart;
if (
(trackStart <= start && trackEnd >= start) ||
(trackStart <= end && trackEnd >= end)
) {
const cueIn = start < trackStart ? trackStart : start;
const cueOut = end > trackEnd ? trackEnd : end;
this.setCues(cueIn + offset, cueOut + offset);
if (start > trackStart) {
this.setStartTime(start);
}
}
} |
JavaScript | schedulePlay(now, startTime, endTime, config) {
let start;
let duration;
let when = now;
let segment = endTime ? endTime - startTime : undefined;
const defaultOptions = {
shouldPlay: true,
masterGain: 1,
isOffline: false,
};
const options = lodash_assign_default()({}, defaultOptions, config);
const playoutSystem = options.isOffline
? this.offlinePlayout
: this.playout;
// 1) track has no content to play.
// 2) track does not play in this selection.
if (
this.endTime <= startTime ||
(segment && startTime + segment < this.startTime)
) {
// return a resolved promise since this track is technically "stopped".
return Promise.resolve();
}
// track should have something to play if it gets here.
// the track starts in the future or on the cursor position
if (this.startTime >= startTime) {
start = 0;
// schedule additional delay for this audio node.
when += this.startTime - startTime;
if (endTime) {
segment -= this.startTime - startTime;
duration = Math.min(segment, this.duration);
} else {
duration = this.duration;
}
} else {
start = startTime - this.startTime;
if (endTime) {
duration = Math.min(segment, this.duration - start);
} else {
duration = this.duration - start;
}
}
start += this.cueIn;
const relPos = startTime - this.startTime;
const sourcePromise = playoutSystem.setUpSource();
// param relPos: cursor position in seconds relative to this track.
// can be negative if the cursor is placed before the start of this track etc.
lodash_forown_default()(this.fades, (fade) => {
let fadeStart;
let fadeDuration;
// only apply fade if it's ahead of the cursor.
if (relPos < fade.end) {
if (relPos <= fade.start) {
fadeStart = now + (fade.start - relPos);
fadeDuration = fade.end - fade.start;
} else if (relPos > fade.start && relPos < fade.end) {
fadeStart = now - (relPos - fade.start);
fadeDuration = fade.end - fade.start;
}
switch (fade.type) {
case fade_maker/* FADEIN */.Y1: {
playoutSystem.applyFadeIn(fadeStart, fadeDuration, fade.shape);
break;
}
case fade_maker/* FADEOUT */.h7: {
playoutSystem.applyFadeOut(fadeStart, fadeDuration, fade.shape);
break;
}
default: {
throw new Error("Invalid fade type saved on track.");
}
}
}
});
playoutSystem.setVolumeGainLevel(this.gain);
playoutSystem.setShouldPlay(options.shouldPlay);
playoutSystem.setMasterGainLevel(options.masterGain);
playoutSystem.setStereoPanValue(this.stereoPan);
if (!(playoutSystem instanceof PrerenderedPlayout ))
playoutSystem.play(when, start, duration);
return sourcePromise;
} | schedulePlay(now, startTime, endTime, config) {
let start;
let duration;
let when = now;
let segment = endTime ? endTime - startTime : undefined;
const defaultOptions = {
shouldPlay: true,
masterGain: 1,
isOffline: false,
};
const options = lodash_assign_default()({}, defaultOptions, config);
const playoutSystem = options.isOffline
? this.offlinePlayout
: this.playout;
// 1) track has no content to play.
// 2) track does not play in this selection.
if (
this.endTime <= startTime ||
(segment && startTime + segment < this.startTime)
) {
// return a resolved promise since this track is technically "stopped".
return Promise.resolve();
}
// track should have something to play if it gets here.
// the track starts in the future or on the cursor position
if (this.startTime >= startTime) {
start = 0;
// schedule additional delay for this audio node.
when += this.startTime - startTime;
if (endTime) {
segment -= this.startTime - startTime;
duration = Math.min(segment, this.duration);
} else {
duration = this.duration;
}
} else {
start = startTime - this.startTime;
if (endTime) {
duration = Math.min(segment, this.duration - start);
} else {
duration = this.duration - start;
}
}
start += this.cueIn;
const relPos = startTime - this.startTime;
const sourcePromise = playoutSystem.setUpSource();
// param relPos: cursor position in seconds relative to this track.
// can be negative if the cursor is placed before the start of this track etc.
lodash_forown_default()(this.fades, (fade) => {
let fadeStart;
let fadeDuration;
// only apply fade if it's ahead of the cursor.
if (relPos < fade.end) {
if (relPos <= fade.start) {
fadeStart = now + (fade.start - relPos);
fadeDuration = fade.end - fade.start;
} else if (relPos > fade.start && relPos < fade.end) {
fadeStart = now - (relPos - fade.start);
fadeDuration = fade.end - fade.start;
}
switch (fade.type) {
case fade_maker/* FADEIN */.Y1: {
playoutSystem.applyFadeIn(fadeStart, fadeDuration, fade.shape);
break;
}
case fade_maker/* FADEOUT */.h7: {
playoutSystem.applyFadeOut(fadeStart, fadeDuration, fade.shape);
break;
}
default: {
throw new Error("Invalid fade type saved on track.");
}
}
}
});
playoutSystem.setVolumeGainLevel(this.gain);
playoutSystem.setShouldPlay(options.shouldPlay);
playoutSystem.setMasterGainLevel(options.masterGain);
playoutSystem.setStereoPanValue(this.stereoPan);
if (!(playoutSystem instanceof PrerenderedPlayout ))
playoutSystem.play(when, start, duration);
return sourcePromise;
} |
JavaScript | play(when, start, duration) {
if (this.audio && this.audio.paused) {
this.audio.currentTime = start;
this.audio.play();
} else if(!this.audio) {
console.log("Error: No audio to start!");
}
//this.source.start(when, start, duration);
} | play(when, start, duration) {
if (this.audio && this.audio.paused) {
this.audio.currentTime = start;
this.audio.play();
} else if(!this.audio) {
console.log("Error: No audio to start!");
}
//this.source.start(when, start, duration);
} |
JavaScript | function findMinMax(array) {
let min = Infinity;
let max = -Infinity;
let curr;
for (let i = 0; i < array.length; i += 1) {
curr = array[i];
if (min > curr) {
min = curr;
}
if (max < curr) {
max = curr;
}
}
return {
min,
max,
};
} | function findMinMax(array) {
let min = Infinity;
let max = -Infinity;
let curr;
for (let i = 0; i < array.length; i += 1) {
curr = array[i];
if (min > curr) {
min = curr;
}
if (max < curr) {
max = curr;
}
}
return {
min,
max,
};
} |
JavaScript | function extractPeaks(channel, samplesPerPixel, bits) {
const chanLength = channel.length;
const numPeaks = Math.ceil(chanLength / samplesPerPixel);
let start;
let end;
let segment;
let max;
let min;
let extrema;
// create interleaved array of min,max
const peaks = new self[`Int${bits}Array`](numPeaks * 2);
for (let i = 0; i < numPeaks; i += 1) {
start = i * samplesPerPixel;
end =
(i + 1) * samplesPerPixel > chanLength
? chanLength
: (i + 1) * samplesPerPixel;
segment = channel.subarray(start, end);
extrema = findMinMax(segment);
min = convert(extrema.min, bits);
max = convert(extrema.max, bits);
peaks[i * 2] = min;
peaks[i * 2 + 1] = max;
}
return peaks;
} | function extractPeaks(channel, samplesPerPixel, bits) {
const chanLength = channel.length;
const numPeaks = Math.ceil(chanLength / samplesPerPixel);
let start;
let end;
let segment;
let max;
let min;
let extrema;
// create interleaved array of min,max
const peaks = new self[`Int${bits}Array`](numPeaks * 2);
for (let i = 0; i < numPeaks; i += 1) {
start = i * samplesPerPixel;
end =
(i + 1) * samplesPerPixel > chanLength
? chanLength
: (i + 1) * samplesPerPixel;
segment = channel.subarray(start, end);
extrema = findMinMax(segment);
min = convert(extrema.min, bits);
max = convert(extrema.max, bits);
peaks[i * 2] = min;
peaks[i * 2 + 1] = max;
}
return peaks;
} |
JavaScript | function audioPeaks(source, samplesPerPixel = 10000, bits = 8) {
if ([8, 16, 32].indexOf(bits) < 0) {
throw new Error("Invalid number of bits specified for peaks.");
}
const peaks = [];
const start = 0;
const end = source.length;
peaks.push(
extractPeaks(source.subarray(start, end), samplesPerPixel, bits)
);
const length = peaks[0].length / 2;
return {
bits,
length,
data: peaks,
};
} | function audioPeaks(source, samplesPerPixel = 10000, bits = 8) {
if ([8, 16, 32].indexOf(bits) < 0) {
throw new Error("Invalid number of bits specified for peaks.");
}
const peaks = [];
const start = 0;
const end = source.length;
peaks.push(
extractPeaks(source.subarray(start, end), samplesPerPixel, bits)
);
const length = peaks[0].length / 2;
return {
bits,
length,
data: peaks,
};
} |
JavaScript | updateEditor(cursor) {
const currentTime = this.ac.currentTime;
const selection = this.getTimeSelection();
const cursorPos = cursor || this.cursor;
const elapsed = currentTime - this.lastDraw;
if ((!this.isPrerenderedPaused || this.isPlaying()) &&
(cursorPos + elapsed <
(this.isSegmentSelection() ? selection.end : this.duration))
) {
const playbackSeconds = cursorPos + elapsed;
this.ee.emit("timeupdate", playbackSeconds);
this.animationRequest = window.requestAnimationFrame(() => {
this.updateEditor(playbackSeconds);
});
this.playbackSeconds = playbackSeconds;
this.draw(this.render());
this.lastDraw = currentTime;
} else {
if (
cursorPos + elapsed >=
(this.isSegmentSelection() ? selection.end : this.duration)
) {
this.ee.emit("finished");
}
this.stopAnimation();
this.resetDrawTimer = setTimeout(() => {
this.pausedAt = undefined;
this.lastSeeked = undefined;
this.setState(this.getState());
this.playbackSeconds = 0;
this.draw(this.render());
}, 0);
}
} | updateEditor(cursor) {
const currentTime = this.ac.currentTime;
const selection = this.getTimeSelection();
const cursorPos = cursor || this.cursor;
const elapsed = currentTime - this.lastDraw;
if ((!this.isPrerenderedPaused || this.isPlaying()) &&
(cursorPos + elapsed <
(this.isSegmentSelection() ? selection.end : this.duration))
) {
const playbackSeconds = cursorPos + elapsed;
this.ee.emit("timeupdate", playbackSeconds);
this.animationRequest = window.requestAnimationFrame(() => {
this.updateEditor(playbackSeconds);
});
this.playbackSeconds = playbackSeconds;
this.draw(this.render());
this.lastDraw = currentTime;
} else {
if (
cursorPos + elapsed >=
(this.isSegmentSelection() ? selection.end : this.duration)
) {
this.ee.emit("finished");
}
this.stopAnimation();
this.resetDrawTimer = setTimeout(() => {
this.pausedAt = undefined;
this.lastSeeked = undefined;
this.setState(this.getState());
this.playbackSeconds = 0;
this.draw(this.render());
}, 0);
}
} |
JavaScript | load() {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.open("GET", this.src, true);
xhr.responseType = "arraybuffer";
xhr.send();
xhr.addEventListener("progress", (e) => {
super.fileProgress(e);
});
xhr.addEventListener("load", (e) => {
const decoderPromise = super.fileLoad(e);
decoderPromise
.then((audioBuffer) => {
resolve(audioBuffer);
})
.catch(reject);
});
xhr.addEventListener("error", () => {
reject(Error(`Track ${this.src} failed to load`));
});
});
} | load() {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.open("GET", this.src, true);
xhr.responseType = "arraybuffer";
xhr.send();
xhr.addEventListener("progress", (e) => {
super.fileProgress(e);
});
xhr.addEventListener("load", (e) => {
const decoderPromise = super.fileLoad(e);
decoderPromise
.then((audioBuffer) => {
resolve(audioBuffer);
})
.catch(reject);
});
xhr.addEventListener("error", () => {
reject(Error(`Track ${this.src} failed to load`));
});
});
} |
JavaScript | function serialize( obj ) {
var serialized = [],
prop;
for ( prop in obj ) {
if ( obj.hasOwnProperty( prop ) ) { // eslint-disable-line no-prototype-builtins
serialized.push( prop + '=' + encodeURIComponent( obj[ prop ] ) );
}
}
return serialized.join( '&' );
} | function serialize( obj ) {
var serialized = [],
prop;
for ( prop in obj ) {
if ( obj.hasOwnProperty( prop ) ) { // eslint-disable-line no-prototype-builtins
serialized.push( prop + '=' + encodeURIComponent( obj[ prop ] ) );
}
}
return serialized.join( '&' );
} |
JavaScript | function clearTypeAhead() {
setTimeout( function () {
var searchScript = document.getElementById( 'api_opensearch' );
typeAheadEl.innerHTML = '';
if ( searchScript ) {
searchScript.src = false;
}
ssActiveIndex.clear();
}, 300 );
} | function clearTypeAhead() {
setTimeout( function () {
var searchScript = document.getElementById( 'api_opensearch' );
typeAheadEl.innerHTML = '';
if ( searchScript ) {
searchScript.src = false;
}
ssActiveIndex.clear();
}, 300 );
} |
JavaScript | function forceLinkFollow( e ) {
var el = e.relatedTarget;
if ( el && /suggestion-link/.test( el.className ) ) {
window.location = el.href;
}
} | function forceLinkFollow( e ) {
var el = e.relatedTarget;
if ( el && /suggestion-link/.test( el.className ) ) {
window.location = el.href;
}
} |
JavaScript | function loadQueryScript( string, lang ) {
var script = document.getElementById( 'api_opensearch' ),
docHead = document.getElementsByTagName( 'head' )[ 0 ],
hostname,
callbackIndex,
searchQuery;
// Variables declared in parent function.
searchLang = encodeURIComponent( lang ) || 'en';
searchString = encodeURIComponent( string );
if ( searchString.length === 0 ) {
clearTypeAhead();
return;
}
hostname = '//' + searchLang + '.wikipedia.org/w/api.php?';
// If script already exists, remove it.
if ( script ) {
docHead.removeChild( script );
}
script = document.createElement( 'script' );
script.id = 'api_opensearch';
callbackIndex = window.callbackStack.addCallback( window.portalOpensearchCallback );
searchQuery = {
action: 'query',
format: 'json',
generator: 'prefixsearch',
prop: 'pageprops|pageimages|description',
redirects: '',
ppprop: 'displaytitle',
piprop: 'thumbnail',
pithumbsize: thumbnailSize,
pilimit: maxSearchResults,
gpssearch: string,
gpsnamespace: 0,
gpslimit: maxSearchResults,
callback: 'callbackStack.queue[' + callbackIndex + ']'
};
script.src = hostname + serialize( searchQuery );
docHead.appendChild( script );
} | function loadQueryScript( string, lang ) {
var script = document.getElementById( 'api_opensearch' ),
docHead = document.getElementsByTagName( 'head' )[ 0 ],
hostname,
callbackIndex,
searchQuery;
// Variables declared in parent function.
searchLang = encodeURIComponent( lang ) || 'en';
searchString = encodeURIComponent( string );
if ( searchString.length === 0 ) {
clearTypeAhead();
return;
}
hostname = '//' + searchLang + '.wikipedia.org/w/api.php?';
// If script already exists, remove it.
if ( script ) {
docHead.removeChild( script );
}
script = document.createElement( 'script' );
script.id = 'api_opensearch';
callbackIndex = window.callbackStack.addCallback( window.portalOpensearchCallback );
searchQuery = {
action: 'query',
format: 'json',
generator: 'prefixsearch',
prop: 'pageprops|pageimages|description',
redirects: '',
ppprop: 'displaytitle',
piprop: 'thumbnail',
pithumbsize: thumbnailSize,
pilimit: maxSearchResults,
gpssearch: string,
gpsnamespace: 0,
gpslimit: maxSearchResults,
callback: 'callbackStack.queue[' + callbackIndex + ']'
};
script.src = hostname + serialize( searchQuery );
docHead.appendChild( script );
} |
JavaScript | function highlightTitle( title, searchString ) {
var sanitizedSearchString = mw.html.escape( mw.RegExp.escape( searchString ) ),
searchRegex = new RegExp( sanitizedSearchString, 'i' ),
startHighlightIndex = title.search( searchRegex ),
formattedTitle = mw.html.escape( title ),
endHighlightIndex,
strong,
beforeHighlight,
aferHighlight;
if ( startHighlightIndex >= 0 ) {
endHighlightIndex = startHighlightIndex + sanitizedSearchString.length;
strong = title.substring( startHighlightIndex, endHighlightIndex );
beforeHighlight = title.substring( 0, startHighlightIndex );
aferHighlight = title.substring( endHighlightIndex, title.length );
formattedTitle = beforeHighlight + mw.html.element( 'em', { class: 'suggestion-highlight' }, strong ) + aferHighlight;
}
return formattedTitle;
} // END highlightTitle | function highlightTitle( title, searchString ) {
var sanitizedSearchString = mw.html.escape( mw.RegExp.escape( searchString ) ),
searchRegex = new RegExp( sanitizedSearchString, 'i' ),
startHighlightIndex = title.search( searchRegex ),
formattedTitle = mw.html.escape( title ),
endHighlightIndex,
strong,
beforeHighlight,
aferHighlight;
if ( startHighlightIndex >= 0 ) {
endHighlightIndex = startHighlightIndex + sanitizedSearchString.length;
strong = title.substring( startHighlightIndex, endHighlightIndex );
beforeHighlight = title.substring( 0, startHighlightIndex );
aferHighlight = title.substring( endHighlightIndex, title.length );
formattedTitle = beforeHighlight + mw.html.element( 'em', { class: 'suggestion-highlight' }, strong ) + aferHighlight;
}
return formattedTitle;
} // END highlightTitle |
JavaScript | function generateTemplateString( suggestions ) {
var string = '<div class="suggestions-dropdown">',
suggestionLink,
suggestionThumbnail,
suggestionText,
suggestionTitle,
suggestionDescription,
page,
sanitizedThumbURL = false,
descriptionText = '',
pageDescription = '',
i;
for ( i = 0; i < suggestions.length; i++ ) {
if ( !suggestions[ i ] ) {
continue;
}
page = suggestions[ i ];
pageDescription = page.description || '';
// Ensure that the value from the previous iteration isn't used
sanitizedThumbURL = false;
if ( page.thumbnail && page.thumbnail.source ) {
sanitizedThumbURL = page.thumbnail.source.replace( /"/g, '%22' );
sanitizedThumbURL = sanitizedThumbURL.replace( /'/g, '%27' );
}
// Ensure that the value from the previous iteration isn't used
descriptionText = '';
// Check if description exists
if ( pageDescription ) {
// If the description is an array, use the first item
if ( typeof pageDescription === 'object' && pageDescription[ 0 ] ) {
descriptionText = pageDescription[ 0 ].toString();
} else {
// Otherwise, use the description as is.
descriptionText = pageDescription.toString();
}
}
suggestionDescription = mw.html.element( 'p', { class: 'suggestion-description' }, descriptionText );
suggestionTitle = mw.html.element( 'h3', { class: 'suggestion-title' }, new mw.html.Raw( highlightTitle( page.title, searchString ) ) );
suggestionText = mw.html.element( 'div', { class: 'suggestion-text' }, new mw.html.Raw( suggestionTitle + suggestionDescription ) );
suggestionThumbnail = mw.html.element( 'div', {
class: 'suggestion-thumbnail',
style: ( sanitizedThumbURL ) ? 'background-image:url(' + sanitizedThumbURL + ')' : false
}, '' );
suggestionLink = mw.html.element( 'a', {
class: 'suggestion-link',
href: 'https://' + searchLang + '.wikipedia.org/wiki/' + encodeURIComponent( page.title.replace( / /gi, '_' ) )
}, new mw.html.Raw( suggestionText + suggestionThumbnail ) );
string += suggestionLink;
}
string += '</div>';
return string;
} // END generateTemplateString | function generateTemplateString( suggestions ) {
var string = '<div class="suggestions-dropdown">',
suggestionLink,
suggestionThumbnail,
suggestionText,
suggestionTitle,
suggestionDescription,
page,
sanitizedThumbURL = false,
descriptionText = '',
pageDescription = '',
i;
for ( i = 0; i < suggestions.length; i++ ) {
if ( !suggestions[ i ] ) {
continue;
}
page = suggestions[ i ];
pageDescription = page.description || '';
// Ensure that the value from the previous iteration isn't used
sanitizedThumbURL = false;
if ( page.thumbnail && page.thumbnail.source ) {
sanitizedThumbURL = page.thumbnail.source.replace( /"/g, '%22' );
sanitizedThumbURL = sanitizedThumbURL.replace( /'/g, '%27' );
}
// Ensure that the value from the previous iteration isn't used
descriptionText = '';
// Check if description exists
if ( pageDescription ) {
// If the description is an array, use the first item
if ( typeof pageDescription === 'object' && pageDescription[ 0 ] ) {
descriptionText = pageDescription[ 0 ].toString();
} else {
// Otherwise, use the description as is.
descriptionText = pageDescription.toString();
}
}
suggestionDescription = mw.html.element( 'p', { class: 'suggestion-description' }, descriptionText );
suggestionTitle = mw.html.element( 'h3', { class: 'suggestion-title' }, new mw.html.Raw( highlightTitle( page.title, searchString ) ) );
suggestionText = mw.html.element( 'div', { class: 'suggestion-text' }, new mw.html.Raw( suggestionTitle + suggestionDescription ) );
suggestionThumbnail = mw.html.element( 'div', {
class: 'suggestion-thumbnail',
style: ( sanitizedThumbURL ) ? 'background-image:url(' + sanitizedThumbURL + ')' : false
}, '' );
suggestionLink = mw.html.element( 'a', {
class: 'suggestion-link',
href: 'https://' + searchLang + '.wikipedia.org/wiki/' + encodeURIComponent( page.title.replace( / /gi, '_' ) )
}, new mw.html.Raw( suggestionText + suggestionThumbnail ) );
string += suggestionLink;
}
string += '</div>';
return string;
} // END generateTemplateString |
JavaScript | function debounce(fn, wait) {
let timeout;
return (...args) => {
let context = this;
clearTimeout(timeout);
timeout = setTimeout(() => fn.apply(context, args), wait);
};
} | function debounce(fn, wait) {
let timeout;
return (...args) => {
let context = this;
clearTimeout(timeout);
timeout = setTimeout(() => fn.apply(context, args), wait);
};
} |
JavaScript | function digitSumInverse(sum, numberLength) {
var lookup = [];
for (var i = 0; i <= sum; i++) {
lookup[i] = [];
}
// Initialize cache
for (var i = 0; i <= sum; i++) {
for (var j = 0; j <= numberLength; j++) {
lookup[i][j] = -1;
}
}
// My recursive function that uses the cache
function countDigitsRec (tempSum, n) {
var count = 0;
// If the sum of all digits sum up to the given sum
if (n == 0) {
return tempSum == 0 ? 1 : 0;
}
// If the sum and digit combination is stored in cache,
// return that instead of recomputing it.
if (lookup [tempSum][n] != -1) {
return lookup[tempSum][n];
}
// For each digit from 0-9, recursively compute their
for (var i = 0; i <= 9; i++) {
if (tempSum - i >= 0) {
count += countDigitsRec(tempSum - i, n - 1);
}
}
return lookup[tempSum][n] = count;
}
// Main function
var finalCount = 0;
if (sum == 0) {
return 1;
}
return countDigitsRec(sum, numberLength);
} | function digitSumInverse(sum, numberLength) {
var lookup = [];
for (var i = 0; i <= sum; i++) {
lookup[i] = [];
}
// Initialize cache
for (var i = 0; i <= sum; i++) {
for (var j = 0; j <= numberLength; j++) {
lookup[i][j] = -1;
}
}
// My recursive function that uses the cache
function countDigitsRec (tempSum, n) {
var count = 0;
// If the sum of all digits sum up to the given sum
if (n == 0) {
return tempSum == 0 ? 1 : 0;
}
// If the sum and digit combination is stored in cache,
// return that instead of recomputing it.
if (lookup [tempSum][n] != -1) {
return lookup[tempSum][n];
}
// For each digit from 0-9, recursively compute their
for (var i = 0; i <= 9; i++) {
if (tempSum - i >= 0) {
count += countDigitsRec(tempSum - i, n - 1);
}
}
return lookup[tempSum][n] = count;
}
// Main function
var finalCount = 0;
if (sum == 0) {
return 1;
}
return countDigitsRec(sum, numberLength);
} |
JavaScript | function countDigitsRec (tempSum, n) {
var count = 0;
// If the sum of all digits sum up to the given sum
if (n == 0) {
return tempSum == 0 ? 1 : 0;
}
// If the sum and digit combination is stored in cache,
// return that instead of recomputing it.
if (lookup [tempSum][n] != -1) {
return lookup[tempSum][n];
}
// For each digit from 0-9, recursively compute their
for (var i = 0; i <= 9; i++) {
if (tempSum - i >= 0) {
count += countDigitsRec(tempSum - i, n - 1);
}
}
return lookup[tempSum][n] = count;
} | function countDigitsRec (tempSum, n) {
var count = 0;
// If the sum of all digits sum up to the given sum
if (n == 0) {
return tempSum == 0 ? 1 : 0;
}
// If the sum and digit combination is stored in cache,
// return that instead of recomputing it.
if (lookup [tempSum][n] != -1) {
return lookup[tempSum][n];
}
// For each digit from 0-9, recursively compute their
for (var i = 0; i <= 9; i++) {
if (tempSum - i >= 0) {
count += countDigitsRec(tempSum - i, n - 1);
}
}
return lookup[tempSum][n] = count;
} |
JavaScript | function deepClone(obj) {
var copied;
if (Array.isArray(obj)) {
copied = [];
} else if (typeof obj === 'object' && obj !== null) {
copied = {};
} else {
return obj;
}
for (var p in obj) {
copied[p] = deepClone(obj[p]);
}
return copied;
} | function deepClone(obj) {
var copied;
if (Array.isArray(obj)) {
copied = [];
} else if (typeof obj === 'object' && obj !== null) {
copied = {};
} else {
return obj;
}
for (var p in obj) {
copied[p] = deepClone(obj[p]);
}
return copied;
} |
JavaScript | function renderLicenseBadge(license, link) {
if (license === "MIT") {
let licenseBadge =
`[](${link})`;
return licenseBadge;
} else if (license === "APACHE 2.0") {
let licenseBadge =
`[](${link})`;
return licenseBadge;
} else if (license === "GPL 3.0") {
let licenseBadge =
`[](${link})`;
return licenseBadge;
} else if (license === "BSD 3") {
let licenseBadge =
`[](${link})`;
return licenseBadge;
} else if (license === "None") {
let licenseBadge = "";
return licenseBadge;
}
} | function renderLicenseBadge(license, link) {
if (license === "MIT") {
let licenseBadge =
`[](${link})`;
return licenseBadge;
} else if (license === "APACHE 2.0") {
let licenseBadge =
`[](${link})`;
return licenseBadge;
} else if (license === "GPL 3.0") {
let licenseBadge =
`[](${link})`;
return licenseBadge;
} else if (license === "BSD 3") {
let licenseBadge =
`[](${link})`;
return licenseBadge;
} else if (license === "None") {
let licenseBadge = "";
return licenseBadge;
}
} |
JavaScript | function renderLicenseLink(license) {
if (license === "MIT") {
let licenseLink =
"https://opensource.org/licenses/MIT";
return licenseLink;
} else if (license === "APACHE 2.0") {
let licenseLink =
"https://opensource.org/licenses/Apache-2.0";
return licenseLink;
} else if (license === "GPL 3.0") {
let licenseLink =
"https://www.gnu.org/licenses/gpl-3.0";
return licenseLink;
} else if (license === "BSD 3") {
let licenseLink =
"https://opensource.org/licenses/BSD-3-Clause";
return licenseLink;
} else if (license === "None") {
let licenseLink = "";
return licenseLink;
}
} | function renderLicenseLink(license) {
if (license === "MIT") {
let licenseLink =
"https://opensource.org/licenses/MIT";
return licenseLink;
} else if (license === "APACHE 2.0") {
let licenseLink =
"https://opensource.org/licenses/Apache-2.0";
return licenseLink;
} else if (license === "GPL 3.0") {
let licenseLink =
"https://www.gnu.org/licenses/gpl-3.0";
return licenseLink;
} else if (license === "BSD 3") {
let licenseLink =
"https://opensource.org/licenses/BSD-3-Clause";
return licenseLink;
} else if (license === "None") {
let licenseLink = "";
return licenseLink;
}
} |
JavaScript | function renderLicenseSection(license, name) {
if (license === "MIT") {
let licenseInfo = `
Copyright 2021 ${name}
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
`;
return licenseInfo;
} else if (license === "APACHE 2.0") {
let licenseInfo = `
Copyright 2021 ${name}
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
`;
return licenseInfo;
} else if (license === "GPL 3.0") {
let licenseInfo = `
Copyright 2021 ${name}
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
`;
return licenseInfo;
} else if (license === "BSD 3") {
let licenseInfo = `
Copyright 2021 ${name}
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
`;
return licenseInfo;
} else if (license === "None") {
let licenseInfo = "";
return licenseInfo;
}
} | function renderLicenseSection(license, name) {
if (license === "MIT") {
let licenseInfo = `
Copyright 2021 ${name}
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
`;
return licenseInfo;
} else if (license === "APACHE 2.0") {
let licenseInfo = `
Copyright 2021 ${name}
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
`;
return licenseInfo;
} else if (license === "GPL 3.0") {
let licenseInfo = `
Copyright 2021 ${name}
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
`;
return licenseInfo;
} else if (license === "BSD 3") {
let licenseInfo = `
Copyright 2021 ${name}
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
`;
return licenseInfo;
} else if (license === "None") {
let licenseInfo = "";
return licenseInfo;
}
} |
JavaScript | function generateMarkdown(data) {
const licenseLink = renderLicenseLink(data.licenseType);
const licenseBadge = renderLicenseBadge(data.licenseType, licenseLink);
const licenseInfo = renderLicenseSection(data.licenseType, data.userName);
const contentOfMarkdown = `
# ${data.projectName}
${licenseBadge}
## Description
${data.description}
## Table of Contents
* [Installation](#installation)
* [Usage](#usage)
* [Tests](#tests)
* [Contributing](#contributing)
* [Questions](#questions)
* [License](#license)
## Installation
To install the necessary dependencies, run the following command:
\`\`\`
${data.depCommand}
\`\`\`
## Usage
${data.usage}
## Tests
To run tests, run the following command.
\`\`\`
${data.testCommand}
\`\`\`
## Contributing
${data.contributions}
## Questions
If you have any questions about the repo, open an issue or contact me directly at ${data.userEmail}. You can find more of my work at my [GitHub](https://github.com/${data.gitHub})
## License
${licenseInfo}
${licenseLink}
`;
return contentOfMarkdown;
} | function generateMarkdown(data) {
const licenseLink = renderLicenseLink(data.licenseType);
const licenseBadge = renderLicenseBadge(data.licenseType, licenseLink);
const licenseInfo = renderLicenseSection(data.licenseType, data.userName);
const contentOfMarkdown = `
# ${data.projectName}
${licenseBadge}
## Description
${data.description}
## Table of Contents
* [Installation](#installation)
* [Usage](#usage)
* [Tests](#tests)
* [Contributing](#contributing)
* [Questions](#questions)
* [License](#license)
## Installation
To install the necessary dependencies, run the following command:
\`\`\`
${data.depCommand}
\`\`\`
## Usage
${data.usage}
## Tests
To run tests, run the following command.
\`\`\`
${data.testCommand}
\`\`\`
## Contributing
${data.contributions}
## Questions
If you have any questions about the repo, open an issue or contact me directly at ${data.userEmail}. You can find more of my work at my [GitHub](https://github.com/${data.gitHub})
## License
${licenseInfo}
${licenseLink}
`;
return contentOfMarkdown;
} |
JavaScript | function writeToFile(fileName, data) {
fs.writeFile(fileName, data, (err) =>
err ? console.log(err) : console.log("README successfully created!")
);
} | function writeToFile(fileName, data) {
fs.writeFile(fileName, data, (err) =>
err ? console.log(err) : console.log("README successfully created!")
);
} |
JavaScript | function init() {
console.log("This function has begun");
inquirer.prompt(questionsForUser).then((response) => {
const newFile = "./Generated/README.md";
const newMarkDown = generateMarkdown(response);
writeToFile(newFile, newMarkDown);
console.log("Your new README can be found in the Generated folder.")
});
} | function init() {
console.log("This function has begun");
inquirer.prompt(questionsForUser).then((response) => {
const newFile = "./Generated/README.md";
const newMarkDown = generateMarkdown(response);
writeToFile(newFile, newMarkDown);
console.log("Your new README can be found in the Generated folder.")
});
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.