language
stringclasses 6
values | original_string
stringlengths 25
887k
| text
stringlengths 25
887k
|
---|---|---|
JavaScript | function updateContentProperty(content, props) {
return tslib_1.__awaiter(this, void 0, void 0, function* () {
const conf = __1.default.getConfluence();
try {
return yield conf.api.content.upsertContentProperty(content, types_1.CUSTOM_PROP_NAME, props, true);
}
catch (e) {
__1.logger("Unable to upsert the content property because: " + e.message);
return null;
}
});
} | function updateContentProperty(content, props) {
return tslib_1.__awaiter(this, void 0, void 0, function* () {
const conf = __1.default.getConfluence();
try {
return yield conf.api.content.upsertContentProperty(content, types_1.CUSTOM_PROP_NAME, props, true);
}
catch (e) {
__1.logger("Unable to upsert the content property because: " + e.message);
return null;
}
});
} |
JavaScript | function validateOwnerData(owner) {
return owner && nexus_extend_1.getNestedVal(owner, "userId") &&
nexus_extend_1.getNestedVal(owner, "userEmail") &&
nexus_extend_1.getNestedVal(owner, "displayName");
} | function validateOwnerData(owner) {
return owner && nexus_extend_1.getNestedVal(owner, "userId") &&
nexus_extend_1.getNestedVal(owner, "userEmail") &&
nexus_extend_1.getNestedVal(owner, "displayName");
} |
JavaScript | loadConnections(config, subApp) {
return [
{
name: "nexus-conn-confluence",
config: {
host: config.CONFLUENCE_HOST,
username: config.CONFLUENCE_USERNAME,
apiToken: config.CONFLUENCE_API_KEY
},
},
{
name: "nexus-conn-slack",
config: {
appId: config.SLACK_APP_ID,
clientId: config.SLACK_CLIENT_ID,
clientSecret: config.SLACK_CLIENT_SECRET,
signingSecret: config.SLACK_SIGNING_SECRET,
commands: [{
command: "dox",
subCommandListeners: commands_1.subCommands
}],
eventListeners: events_1.events,
incomingWebhooks: [],
subApp,
}
},
{
name: "nexus-conn-github",
config: {
apiToken: config.GITHUB_API_TOKEN,
baseUrl: config.GITHUB_BASE_URL
}
},
{
name: "nexus-conn-sendgrid",
config: {
apiKey: config.SENDGRID_API_KEY
}
}
];
} | loadConnections(config, subApp) {
return [
{
name: "nexus-conn-confluence",
config: {
host: config.CONFLUENCE_HOST,
username: config.CONFLUENCE_USERNAME,
apiToken: config.CONFLUENCE_API_KEY
},
},
{
name: "nexus-conn-slack",
config: {
appId: config.SLACK_APP_ID,
clientId: config.SLACK_CLIENT_ID,
clientSecret: config.SLACK_CLIENT_SECRET,
signingSecret: config.SLACK_SIGNING_SECRET,
commands: [{
command: "dox",
subCommandListeners: commands_1.subCommands
}],
eventListeners: events_1.events,
incomingWebhooks: [],
subApp,
}
},
{
name: "nexus-conn-github",
config: {
apiToken: config.GITHUB_API_TOKEN,
baseUrl: config.GITHUB_BASE_URL
}
},
{
name: "nexus-conn-sendgrid",
config: {
apiKey: config.SENDGRID_API_KEY
}
}
];
} |
JavaScript | _checkSwipeArea(point) {
const { initialPosition, swipeArea } = this.props;
if (!swipeArea || Object.keys(swipeArea).length === 0) return true;
const _pointY = point.y + initialPosition.y;
if (_pointY > swipeArea.y && _pointY <= swipeArea.y + swipeArea.height) {
return true;
}
return false;
} | _checkSwipeArea(point) {
const { initialPosition, swipeArea } = this.props;
if (!swipeArea || Object.keys(swipeArea).length === 0) return true;
const _pointY = point.y + initialPosition.y;
if (_pointY > swipeArea.y && _pointY <= swipeArea.y + swipeArea.height) {
return true;
}
return false;
} |
JavaScript | _handleMoving(point) {
if (!this.props.swipeEnabled) return;
let hasSelected = false;
this._moodLayouts.forEach(mood => {
if (
!hasSelected &&
mood.x + mood.width >= point.x + this.props.initialPosition.x
) {
if (this._checkSwipeArea(point)) {
this.setState({ selectedMood: mood.id });
hasSelected = true;
} else {
this.setState({ selectedMood: null });
hasSelected = false;
}
}
});
this.props.onSwipe && this.props.onSwipe(true, hasSelected);
} | _handleMoving(point) {
if (!this.props.swipeEnabled) return;
let hasSelected = false;
this._moodLayouts.forEach(mood => {
if (
!hasSelected &&
mood.x + mood.width >= point.x + this.props.initialPosition.x
) {
if (this._checkSwipeArea(point)) {
this.setState({ selectedMood: mood.id });
hasSelected = true;
} else {
this.setState({ selectedMood: null });
hasSelected = false;
}
}
});
this.props.onSwipe && this.props.onSwipe(true, hasSelected);
} |
JavaScript | _handleRelease() {
this.props.onSwipe && this.props.onSwipe(false, false);
this.props.onSwipeRelease &&
this.props.onSwipeRelease(this.state.selectedMood);
this.setState({
selectedMood: null
});
} | _handleRelease() {
this.props.onSwipe && this.props.onSwipe(false, false);
this.props.onSwipeRelease &&
this.props.onSwipeRelease(this.state.selectedMood);
this.setState({
selectedMood: null
});
} |
JavaScript | _updateSelectedMood(selectedMood) {
this.setState({ selectedMood }, () => {
this._handleRelease();
});
} | _updateSelectedMood(selectedMood) {
this.setState({ selectedMood }, () => {
this._handleRelease();
});
} |
JavaScript | function formControlFocus(inputFocusColor, inputFocusBg, inputFocusBorderColor) {
return css`
&:focus {
color: ${inputFocusColor};
background-color: ${inputFocusBg};
border-color: ${inputFocusBorderColor};
outline: 0;
}
`;
} | function formControlFocus(inputFocusColor, inputFocusBg, inputFocusBorderColor) {
return css`
&:focus {
color: ${inputFocusColor};
background-color: ${inputFocusBg};
border-color: ${inputFocusBorderColor};
outline: 0;
}
`;
} |
JavaScript | function renderPagination(wizard, options, state)
{
if (options.enablePagination)
{
var pagination = "<{0} class=\"actions {1}\"><ul role=\"menu\" aria-label=\"{2}\">{3}</ul></{0}>",
buttonTemplate = "<li><a href=\"#{0}\" role=\"menuitem\" id={0}1>{1}</a></li>",
// buttonTemplate = "<li><button onclick= 'test(\"#{0}\")' id={0}1 role=\"menuitem\">{1}</button><li>",
buttons = "";
if (!options.forceMoveForward)
{
buttons += buttonTemplate.format("previous", options.labels.previous);
}
buttons += buttonTemplate.format("next", options.labels.next);
if (options.enableFinishButton)
{
buttons += buttonTemplate.format("finish", options.labels.finish);
}
if (options.enableCancelButton)
{
buttons += buttonTemplate.format("cancel", options.labels.cancel);
}
wizard.append(pagination.format(options.actionContainerTag, options.clearFixCssClass,
options.labels.pagination, buttons));
refreshPagination(wizard, options, state);
loadAsyncContent(wizard, options, state);
}
} | function renderPagination(wizard, options, state)
{
if (options.enablePagination)
{
var pagination = "<{0} class=\"actions {1}\"><ul role=\"menu\" aria-label=\"{2}\">{3}</ul></{0}>",
buttonTemplate = "<li><a href=\"#{0}\" role=\"menuitem\" id={0}1>{1}</a></li>",
// buttonTemplate = "<li><button onclick= 'test(\"#{0}\")' id={0}1 role=\"menuitem\">{1}</button><li>",
buttons = "";
if (!options.forceMoveForward)
{
buttons += buttonTemplate.format("previous", options.labels.previous);
}
buttons += buttonTemplate.format("next", options.labels.next);
if (options.enableFinishButton)
{
buttons += buttonTemplate.format("finish", options.labels.finish);
}
if (options.enableCancelButton)
{
buttons += buttonTemplate.format("cancel", options.labels.cancel);
}
wizard.append(pagination.format(options.actionContainerTag, options.clearFixCssClass,
options.labels.pagination, buttons));
refreshPagination(wizard, options, state);
loadAsyncContent(wizard, options, state);
}
} |
JavaScript | function renderTemplate(template, substitutes)
{
var matches = template.match(/#([a-z]*)#/gi);
for (var i = 0; i < matches.length; i++)
{
var match = matches[i],
key = match.substring(1, match.length - 1);
if (substitutes[key] === undefined)
{
throwError("The key '{0}' does not exist in the substitute collection!", key);
}
template = template.replace(match, substitutes[key]);
}
return template;
} | function renderTemplate(template, substitutes)
{
var matches = template.match(/#([a-z]*)#/gi);
for (var i = 0; i < matches.length; i++)
{
var match = matches[i],
key = match.substring(1, match.length - 1);
if (substitutes[key] === undefined)
{
throwError("The key '{0}' does not exist in the substitute collection!", key);
}
template = template.replace(match, substitutes[key]);
}
return template;
} |
JavaScript | function renderTitle(wizard, options, state, header, index)
{
var uniqueId = getUniqueId(wizard),
uniqueStepId = uniqueId + _tabSuffix + index,
uniqueBodyId = uniqueId + _tabpanelSuffix + index,
uniqueHeaderId = uniqueId + _titleSuffix + index,
stepCollection = wizard.find(".steps > ul"),
title = renderTemplate(options.titleTemplate, {
index: index + 1,
title: header.html()
}),
stepItem = $("<li role=\"tab\"><a id=\"" + uniqueStepId + "\" href=\"#" + uniqueHeaderId +
"\" aria-controls=\"" + uniqueBodyId + "\">" + title + "</a></li>");
stepItem._enableAria(options.enableAllSteps || state.currentIndex > index);
if (state.currentIndex > index)
{
stepItem.addClass("done");
}
header._id(uniqueHeaderId).attr("tabindex", "-1").addClass("title");
if (index === 0)
{
stepCollection.prepend(stepItem);
}
else
{
stepCollection.find("li").eq(index - 1).after(stepItem);
}
// Set the "first" class to the new first step button
if (index === 0)
{
stepCollection.find("li").removeClass("first").eq(index).addClass("first");
}
// Set the "last" class to the new last step button
if (index === (state.stepCount - 1))
{
stepCollection.find("li").removeClass("last").eq(index).addClass("last");
}
// Register click event
stepItem.children("a").bind("click" + getEventNamespace(wizard), stepClickHandler);
} | function renderTitle(wizard, options, state, header, index)
{
var uniqueId = getUniqueId(wizard),
uniqueStepId = uniqueId + _tabSuffix + index,
uniqueBodyId = uniqueId + _tabpanelSuffix + index,
uniqueHeaderId = uniqueId + _titleSuffix + index,
stepCollection = wizard.find(".steps > ul"),
title = renderTemplate(options.titleTemplate, {
index: index + 1,
title: header.html()
}),
stepItem = $("<li role=\"tab\"><a id=\"" + uniqueStepId + "\" href=\"#" + uniqueHeaderId +
"\" aria-controls=\"" + uniqueBodyId + "\">" + title + "</a></li>");
stepItem._enableAria(options.enableAllSteps || state.currentIndex > index);
if (state.currentIndex > index)
{
stepItem.addClass("done");
}
header._id(uniqueHeaderId).attr("tabindex", "-1").addClass("title");
if (index === 0)
{
stepCollection.prepend(stepItem);
}
else
{
stepCollection.find("li").eq(index - 1).after(stepItem);
}
// Set the "first" class to the new first step button
if (index === 0)
{
stepCollection.find("li").removeClass("first").eq(index).addClass("first");
}
// Set the "last" class to the new last step button
if (index === (state.stepCount - 1))
{
stepCollection.find("li").removeClass("last").eq(index).addClass("last");
}
// Register click event
stepItem.children("a").bind("click" + getEventNamespace(wizard), stepClickHandler);
} |
JavaScript | function prepareElement() {
$ELEMENT.
// Store the picker data by component name.
data(NAME, P).
// Add the “input” class name.
addClass(CLASSES.input).
// Remove the tabindex.
attr('tabindex', -1).
// If there’s a `data-value`, update the value of the element.
val($ELEMENT.data('value') ? P.get('select', SETTINGS.format) : ELEMENT.value);
// Only bind keydown events if the element isn’t editable.
if (!SETTINGS.editable) {
$ELEMENT.
// On focus/click, focus onto the root to open it up.
on('focus.' + STATE.id + ' click.' + STATE.id, function (event) {
event.preventDefault();
P.$root.eq(0).focus();
}).
// Handle keyboard event based on the picker being opened or not.
on('keydown.' + STATE.id, handleKeydownEvent);
}
// Update the aria attributes.
aria(ELEMENT, {
haspopup: true,
expanded: false,
readonly: false,
owns: ELEMENT.id + '_root'
});
} | function prepareElement() {
$ELEMENT.
// Store the picker data by component name.
data(NAME, P).
// Add the “input” class name.
addClass(CLASSES.input).
// Remove the tabindex.
attr('tabindex', -1).
// If there’s a `data-value`, update the value of the element.
val($ELEMENT.data('value') ? P.get('select', SETTINGS.format) : ELEMENT.value);
// Only bind keydown events if the element isn’t editable.
if (!SETTINGS.editable) {
$ELEMENT.
// On focus/click, focus onto the root to open it up.
on('focus.' + STATE.id + ' click.' + STATE.id, function (event) {
event.preventDefault();
P.$root.eq(0).focus();
}).
// Handle keyboard event based on the picker being opened or not.
on('keydown.' + STATE.id, handleKeydownEvent);
}
// Update the aria attributes.
aria(ELEMENT, {
haspopup: true,
expanded: false,
readonly: false,
owns: ELEMENT.id + '_root'
});
} |
JavaScript | function prepareElementRoot() {
P.$root.on({
// For iOS8.
keydown: handleKeydownEvent,
// When something within the root is focused, stop from bubbling
// to the doc and remove the “focused” state from the root.
focusin: function (event) {
P.$root.removeClass(CLASSES.focused);
event.stopPropagation();
},
// When something within the root holder is clicked, stop it
// from bubbling to the doc.
'mousedown click': function (event) {
var target = event.target;
// Make sure the target isn’t the root holder so it can bubble up.
if (target != P.$root.children()[0]) {
event.stopPropagation();
// * For mousedown events, cancel the default action in order to
// prevent cases where focus is shifted onto external elements
// when using things like jQuery mobile or MagnificPopup (ref: #249 & #120).
// Also, for Firefox, don’t prevent action on the `option` element.
if (event.type == 'mousedown' && !$(target).is('input, select, textarea, button, option')) {
event.preventDefault();
// Re-focus onto the root so that users can click away
// from elements focused within the picker.
P.$root.eq(0).focus();
}
}
}
}).
// Add/remove the “target” class on focus and blur.
on({
focus: function () {
$ELEMENT.addClass(CLASSES.target);
},
blur: function () {
$ELEMENT.removeClass(CLASSES.target);
}
}).
// Open the picker and adjust the root “focused” state
on('focus.toOpen', handleFocusToOpenEvent).
// If there’s a click on an actionable element, carry out the actions.
on('click', '[data-pick], [data-nav], [data-clear], [data-close]', function () {
var $target = $(this),
targetData = $target.data(),
targetDisabled = $target.hasClass(CLASSES.navDisabled) || $target.hasClass(CLASSES.disabled),
// * For IE, non-focusable elements can be active elements as well
// (http://stackoverflow.com/a/2684561).
activeElement = getActiveElement();
activeElement = activeElement && (activeElement.type || activeElement.href) && activeElement;
// If it’s disabled or nothing inside is actively focused, re-focus the element.
if (targetDisabled || activeElement && !$.contains(P.$root[0], activeElement)) {
P.$root.eq(0).focus();
}
// If something is superficially changed, update the `highlight` based on the `nav`.
if (!targetDisabled && targetData.nav) {
P.set('highlight', P.component.item.highlight, { nav: targetData.nav });
}
// If something is picked, set `select` then close with focus.
else if (!targetDisabled && 'pick' in targetData) {
P.set('select', targetData.pick);
if (SETTINGS.closeOnSelect) {
P.close(true);
}
}
// If a “clear” button is pressed, empty the values and close with focus.
else if (targetData.clear) {
P.clear();
if (SETTINGS.closeOnSelect) {
P.close(true);
}
} else if (targetData.close) {
P.close(true);
}
}); //P.$root
aria(P.$root[0], 'hidden', true);
} | function prepareElementRoot() {
P.$root.on({
// For iOS8.
keydown: handleKeydownEvent,
// When something within the root is focused, stop from bubbling
// to the doc and remove the “focused” state from the root.
focusin: function (event) {
P.$root.removeClass(CLASSES.focused);
event.stopPropagation();
},
// When something within the root holder is clicked, stop it
// from bubbling to the doc.
'mousedown click': function (event) {
var target = event.target;
// Make sure the target isn’t the root holder so it can bubble up.
if (target != P.$root.children()[0]) {
event.stopPropagation();
// * For mousedown events, cancel the default action in order to
// prevent cases where focus is shifted onto external elements
// when using things like jQuery mobile or MagnificPopup (ref: #249 & #120).
// Also, for Firefox, don’t prevent action on the `option` element.
if (event.type == 'mousedown' && !$(target).is('input, select, textarea, button, option')) {
event.preventDefault();
// Re-focus onto the root so that users can click away
// from elements focused within the picker.
P.$root.eq(0).focus();
}
}
}
}).
// Add/remove the “target” class on focus and blur.
on({
focus: function () {
$ELEMENT.addClass(CLASSES.target);
},
blur: function () {
$ELEMENT.removeClass(CLASSES.target);
}
}).
// Open the picker and adjust the root “focused” state
on('focus.toOpen', handleFocusToOpenEvent).
// If there’s a click on an actionable element, carry out the actions.
on('click', '[data-pick], [data-nav], [data-clear], [data-close]', function () {
var $target = $(this),
targetData = $target.data(),
targetDisabled = $target.hasClass(CLASSES.navDisabled) || $target.hasClass(CLASSES.disabled),
// * For IE, non-focusable elements can be active elements as well
// (http://stackoverflow.com/a/2684561).
activeElement = getActiveElement();
activeElement = activeElement && (activeElement.type || activeElement.href) && activeElement;
// If it’s disabled or nothing inside is actively focused, re-focus the element.
if (targetDisabled || activeElement && !$.contains(P.$root[0], activeElement)) {
P.$root.eq(0).focus();
}
// If something is superficially changed, update the `highlight` based on the `nav`.
if (!targetDisabled && targetData.nav) {
P.set('highlight', P.component.item.highlight, { nav: targetData.nav });
}
// If something is picked, set `select` then close with focus.
else if (!targetDisabled && 'pick' in targetData) {
P.set('select', targetData.pick);
if (SETTINGS.closeOnSelect) {
P.close(true);
}
}
// If a “clear” button is pressed, empty the values and close with focus.
else if (targetData.clear) {
P.clear();
if (SETTINGS.closeOnSelect) {
P.close(true);
}
} else if (targetData.close) {
P.close(true);
}
}); //P.$root
aria(P.$root[0], 'hidden', true);
} |
JavaScript | function prepareElementHidden() {
var name;
if (SETTINGS.hiddenName === true) {
name = ELEMENT.name;
ELEMENT.name = '';
} else {
name = [typeof SETTINGS.hiddenPrefix == 'string' ? SETTINGS.hiddenPrefix : '', typeof SETTINGS.hiddenSuffix == 'string' ? SETTINGS.hiddenSuffix : '_submit'];
name = name[0] + ELEMENT.name + name[1];
}
P._hidden = $('<input ' + 'type=hidden ' +
// Create the name using the original input’s with a prefix and suffix.
'name="' + name + '"' + (
// If the element has a value, set the hidden value as well.
$ELEMENT.data('value') || ELEMENT.value ? ' value="' + P.get('select', SETTINGS.formatSubmit) + '"' : '') + '>')[0];
$ELEMENT.
// If the value changes, update the hidden input with the correct format.
on('change.' + STATE.id, function () {
P._hidden.value = ELEMENT.value ? P.get('select', SETTINGS.formatSubmit) : '';
});
// Insert the hidden input as specified in the settings.
if (SETTINGS.container) $(SETTINGS.container).append(P._hidden);else $ELEMENT.before(P._hidden);
} | function prepareElementHidden() {
var name;
if (SETTINGS.hiddenName === true) {
name = ELEMENT.name;
ELEMENT.name = '';
} else {
name = [typeof SETTINGS.hiddenPrefix == 'string' ? SETTINGS.hiddenPrefix : '', typeof SETTINGS.hiddenSuffix == 'string' ? SETTINGS.hiddenSuffix : '_submit'];
name = name[0] + ELEMENT.name + name[1];
}
P._hidden = $('<input ' + 'type=hidden ' +
// Create the name using the original input’s with a prefix and suffix.
'name="' + name + '"' + (
// If the element has a value, set the hidden value as well.
$ELEMENT.data('value') || ELEMENT.value ? ' value="' + P.get('select', SETTINGS.formatSubmit) + '"' : '') + '>')[0];
$ELEMENT.
// If the value changes, update the hidden input with the correct format.
on('change.' + STATE.id, function () {
P._hidden.value = ELEMENT.value ? P.get('select', SETTINGS.formatSubmit) : '';
});
// Insert the hidden input as specified in the settings.
if (SETTINGS.container) $(SETTINGS.container).append(P._hidden);else $ELEMENT.before(P._hidden);
} |
JavaScript | function Producer(conf, topicConf) {
if (!(this instanceof Producer)) {
return new Producer(conf, topicConf);
}
/**
* Producer message. This is sent to the wrapper, not received from it
*
* @typedef {object} Producer~Message
* @property {string|buffer} message - The buffer to send to Kafka.
* @property {Topic} topic - The Kafka topic to produce to.
* @property {number} partition - The partition to produce to. Defaults to
* the partitioner
* @property {string} key - The key string to use for the message.
* @see Consumer~Message
*/
var gTopic = conf.topic || false;
var gPart = conf.partition || null;
var dr_cb = conf.dr_cb || conf.dr_msg_cb || null;
var dr_copy_payload = conf.dr_msg_cb || false;
// delete keys we don't want to pass on
delete conf.topic;
delete conf.partition;
delete conf.dr_cb;
delete conf.dr_msg_cb;
// client is an initialized consumer object
// @see NodeKafka::Consumer::Init
Client.call(this, conf, Kafka.Producer, topicConf);
var self = this;
// Delete these keys after saving them in vars
this.globalConfig = conf;
this.topicConfig = topicConf;
this.defaultTopic = gTopic || null;
this.defaultPartition = gPart == null ? -1 : gPart;
this.sentMessages = 0;
this.createdTopics = {};
if (dr_cb) {
this._client.onDeliveryReport(function onDeliveryReport(err, report) {
if (err) {
self.emit('error', LibrdKafkaError.create(err));
}
self.emit('delivery-report', err, report);
}, dr_copy_payload);
if (typeof dr_cb === 'function') {
self.on('delivery-report', dr_cb);
}
}
} | function Producer(conf, topicConf) {
if (!(this instanceof Producer)) {
return new Producer(conf, topicConf);
}
/**
* Producer message. This is sent to the wrapper, not received from it
*
* @typedef {object} Producer~Message
* @property {string|buffer} message - The buffer to send to Kafka.
* @property {Topic} topic - The Kafka topic to produce to.
* @property {number} partition - The partition to produce to. Defaults to
* the partitioner
* @property {string} key - The key string to use for the message.
* @see Consumer~Message
*/
var gTopic = conf.topic || false;
var gPart = conf.partition || null;
var dr_cb = conf.dr_cb || conf.dr_msg_cb || null;
var dr_copy_payload = conf.dr_msg_cb || false;
// delete keys we don't want to pass on
delete conf.topic;
delete conf.partition;
delete conf.dr_cb;
delete conf.dr_msg_cb;
// client is an initialized consumer object
// @see NodeKafka::Consumer::Init
Client.call(this, conf, Kafka.Producer, topicConf);
var self = this;
// Delete these keys after saving them in vars
this.globalConfig = conf;
this.topicConfig = topicConf;
this.defaultTopic = gTopic || null;
this.defaultPartition = gPart == null ? -1 : gPart;
this.sentMessages = 0;
this.createdTopics = {};
if (dr_cb) {
this._client.onDeliveryReport(function onDeliveryReport(err, report) {
if (err) {
self.emit('error', LibrdKafkaError.create(err));
}
self.emit('delivery-report', err, report);
}, dr_copy_payload);
if (typeof dr_cb === 'function') {
self.on('delivery-report', dr_cb);
}
}
} |
JavaScript | function maybeTopic(name) {
// create or get topic
var topic;
if (typeof(name) === 'string') {
if (this.createdTopics[name]) {
topic = this.createdTopics[name];
} else {
topic = this.createdTopics[name] = this.Topic(name, this.topicConfig || undefined);
}
return topic;
} else {
// this may be what we want
return name;
}
} | function maybeTopic(name) {
// create or get topic
var topic;
if (typeof(name) === 'string') {
if (this.createdTopics[name]) {
topic = this.createdTopics[name];
} else {
topic = this.createdTopics[name] = this.Topic(name, this.topicConfig || undefined);
}
return topic;
} else {
// this may be what we want
return name;
}
} |
JavaScript | function KafkaConsumer(conf, topicConf) {
if (!(this instanceof KafkaConsumer)) {
return new KafkaConsumer(conf, topicConf);
}
var onRebalance = conf.rebalance_cb;
var self = this;
// If rebalance is undefined we don't want any part of this
if (onRebalance && typeof onRebalance === 'boolean') {
conf.rebalance_cb = function(e) {
// That's it
if (e.code === 500 /*CODES.REBALANCE.PARTITION_ASSIGNMENT*/) {
self.assign(e.assignment);
} else if (e.code === 501 /*CODES.REBALANCE.PARTITION_UNASSIGNMENT*/) {
self.unassign(e.assignment);
}
};
} else if (onRebalance && typeof onRebalance === 'function') {
/*
* Once this is opted in to, that's it. It's going to manually rebalance
* forever. There is no way to unset config values in librdkafka, just
* a way to override them.
*/
conf.rebalance_cb = function(e) {
self.emit('rebalance', e);
onRebalance.call(self, e);
};
}
/**
* KafkaConsumer message.
*
* This is the representation of a message read from Kafka.
*
* @typedef {object} KafkaConsumer~Message
* @property {buffer} value - the message buffer from Kafka.
* @property {string} topic - the topic name
* @property {number} partition - the partition on the topic the
* message was on
* @property {number} offset - the offset of the message
* @property {string} key - the message key
* @property {number} size - message size, in bytes.
*/
Client.call(this, conf, Kafka.KafkaConsumer, topicConf);
this.globalConfig = conf;
this.topicConfig = topicConf;
this._consumeTimeout = 1000;
} | function KafkaConsumer(conf, topicConf) {
if (!(this instanceof KafkaConsumer)) {
return new KafkaConsumer(conf, topicConf);
}
var onRebalance = conf.rebalance_cb;
var self = this;
// If rebalance is undefined we don't want any part of this
if (onRebalance && typeof onRebalance === 'boolean') {
conf.rebalance_cb = function(e) {
// That's it
if (e.code === 500 /*CODES.REBALANCE.PARTITION_ASSIGNMENT*/) {
self.assign(e.assignment);
} else if (e.code === 501 /*CODES.REBALANCE.PARTITION_UNASSIGNMENT*/) {
self.unassign(e.assignment);
}
};
} else if (onRebalance && typeof onRebalance === 'function') {
/*
* Once this is opted in to, that's it. It's going to manually rebalance
* forever. There is no way to unset config values in librdkafka, just
* a way to override them.
*/
conf.rebalance_cb = function(e) {
self.emit('rebalance', e);
onRebalance.call(self, e);
};
}
/**
* KafkaConsumer message.
*
* This is the representation of a message read from Kafka.
*
* @typedef {object} KafkaConsumer~Message
* @property {buffer} value - the message buffer from Kafka.
* @property {string} topic - the topic name
* @property {number} partition - the partition on the topic the
* message was on
* @property {number} offset - the offset of the message
* @property {string} key - the message key
* @property {number} size - message size, in bytes.
*/
Client.call(this, conf, Kafka.KafkaConsumer, topicConf);
this.globalConfig = conf;
this.topicConfig = topicConf;
this._consumeTimeout = 1000;
} |
JavaScript | function synthesizeItemKeyDiffs(diffs, baseItems, compareItems) {
/** @type {Array<LHCI.AuditDiff>} */
const itemKeyDiffs = [];
for (const diff of diffs) {
if (diff.type !== 'itemAddition' && diff.type !== 'itemRemoval') continue;
const item =
diff.type === 'itemAddition'
? compareItems[diff.compareItemIndex]
: baseItems[diff.baseItemIndex];
for (const key of Object.keys(item)) {
const baseValue = diff.type === 'itemAddition' ? 0 : item[key];
const compareValue = diff.type === 'itemAddition' ? item[key] : 0;
if (typeof compareValue !== 'number' || typeof baseValue !== 'number') continue;
const itemIndexKeyName = diff.type === 'itemAddition' ? 'compareItemIndex' : 'baseItemIndex';
const itemIndexValue =
diff.type === 'itemAddition' ? diff.compareItemIndex : diff.baseItemIndex;
itemKeyDiffs.push(
createAuditDiff({
auditId: diff.auditId,
type: 'itemDelta',
itemKey: key,
[itemIndexKeyName]: itemIndexValue,
baseValue,
compareValue,
})
);
}
}
return itemKeyDiffs;
} | function synthesizeItemKeyDiffs(diffs, baseItems, compareItems) {
/** @type {Array<LHCI.AuditDiff>} */
const itemKeyDiffs = [];
for (const diff of diffs) {
if (diff.type !== 'itemAddition' && diff.type !== 'itemRemoval') continue;
const item =
diff.type === 'itemAddition'
? compareItems[diff.compareItemIndex]
: baseItems[diff.baseItemIndex];
for (const key of Object.keys(item)) {
const baseValue = diff.type === 'itemAddition' ? 0 : item[key];
const compareValue = diff.type === 'itemAddition' ? item[key] : 0;
if (typeof compareValue !== 'number' || typeof baseValue !== 'number') continue;
const itemIndexKeyName = diff.type === 'itemAddition' ? 'compareItemIndex' : 'baseItemIndex';
const itemIndexValue =
diff.type === 'itemAddition' ? diff.compareItemIndex : diff.baseItemIndex;
itemKeyDiffs.push(
createAuditDiff({
auditId: diff.auditId,
type: 'itemDelta',
itemKey: key,
[itemIndexKeyName]: itemIndexValue,
baseValue,
compareValue,
})
);
}
}
return itemKeyDiffs;
} |
JavaScript | function deepPruneItemForKeySerialization(item) {
if (typeof item !== 'object') return item;
if (item === null) return item;
if (Array.isArray(item)) {
return item.map(entry => deepPruneItemForKeySerialization(entry));
} else {
const itemAsRecord = /** @type {Record<string, unknown>} */ (item);
const keys = Object.keys(item);
const keysToKeep = keys.filter(key => !key.startsWith('_'));
/** @type {Record<string, any>} */
const copy = {};
for (const key of keysToKeep) {
copy[key] = deepPruneItemForKeySerialization(itemAsRecord[key]);
}
return copy;
}
} | function deepPruneItemForKeySerialization(item) {
if (typeof item !== 'object') return item;
if (item === null) return item;
if (Array.isArray(item)) {
return item.map(entry => deepPruneItemForKeySerialization(entry));
} else {
const itemAsRecord = /** @type {Record<string, unknown>} */ (item);
const keys = Object.keys(item);
const keysToKeep = keys.filter(key => !key.startsWith('_'));
/** @type {Record<string, any>} */
const copy = {};
for (const key of keysToKeep) {
copy[key] = deepPruneItemForKeySerialization(itemAsRecord[key]);
}
return copy;
}
} |
JavaScript | function recursivelyReplaceDotInKeyName(object) {
if (typeof object !== 'object' || !object) return;
for (const [key, value] of Object.entries(object)) {
recursivelyReplaceDotInKeyName(value);
if (!key.includes('.')) continue;
delete object[key];
object[key.replace(/\./g, ':')] = value;
}
} | function recursivelyReplaceDotInKeyName(object) {
if (typeof object !== 'object' || !object) return;
for (const [key, value] of Object.entries(object)) {
recursivelyReplaceDotInKeyName(value);
if (!key.includes('.')) continue;
delete object[key];
object[key.replace(/\./g, ':')] = value;
}
} |
JavaScript | function merge(v1, v2) {
if (Array.isArray(v1)) {
if (!Array.isArray(v2)) return v2;
for (let i = 0; i < Math.max(v1.length, v2.length); i++) {
v1[i] = i < v2.length ? merge(v1[i], v2[i]) : v1[i];
}
return v1;
} else if (typeof v1 === 'object' && v1 !== null) {
if (typeof v2 !== 'object' || v2 === null) return v2;
/** @type {Record<string, *>} */
const o1 = v1;
/** @type {Record<string, *>} */
const o2 = v2;
const o1Keys = new Set(Object.keys(o1));
const o2Keys = new Set(Object.keys(o2));
for (const key of new Set([...o1Keys, ...o2Keys])) {
o1[key] = key in o2 ? merge(o1[key], o2[key]) : o1[key];
}
return v1;
} else {
return v2;
}
} | function merge(v1, v2) {
if (Array.isArray(v1)) {
if (!Array.isArray(v2)) return v2;
for (let i = 0; i < Math.max(v1.length, v2.length); i++) {
v1[i] = i < v2.length ? merge(v1[i], v2[i]) : v1[i];
}
return v1;
} else if (typeof v1 === 'object' && v1 !== null) {
if (typeof v2 !== 'object' || v2 === null) return v2;
/** @type {Record<string, *>} */
const o1 = v1;
/** @type {Record<string, *>} */
const o2 = v2;
const o1Keys = new Set(Object.keys(o1));
const o2Keys = new Set(Object.keys(o2));
for (const key of new Set([...o1Keys, ...o2Keys])) {
o1[key] = key in o2 ? merge(o1[key], o2[key]) : o1[key];
}
return v1;
} else {
return v2;
}
} |
JavaScript | startCase(s) {
return kebabCase(s)
.split('-')
.map(word => `${word.slice(0, 1).toUpperCase()}${word.slice(1)}`)
.join(' ');
} | startCase(s) {
return kebabCase(s)
.split('-')
.map(word => `${word.slice(0, 1).toUpperCase()}${word.slice(1)}`)
.join(' ');
} |
JavaScript | uniqBy(items, keyFn) {
/** @type {Set<TKey>} */
const seen = new Set();
/** @type {Array<TArr>} */
const out = [];
for (const item of items) {
const key = keyFn(item);
if (seen.has(key)) continue;
seen.add(key);
out.push(item);
}
return out;
} | uniqBy(items, keyFn) {
/** @type {Set<TKey>} */
const seen = new Set();
/** @type {Array<TArr>} */
const out = [];
for (const item of items) {
const key = keyFn(item);
if (seen.has(key)) continue;
seen.add(key);
out.push(item);
}
return out;
} |
JavaScript | function mergeInCommandSpecificEnvironments(argv, command) {
return {
...argv,
...(argv[command] || {}),
};
} | function mergeInCommandSpecificEnvironments(argv, command) {
return {
...argv,
...(argv[command] || {}),
};
} |
JavaScript | generateAdminToken() {
return crypto
.randomBytes(30)
.toString('base64')
.replace(/[^a-z0-9]/gi, 'l');
} | generateAdminToken() {
return crypto
.randomBytes(30)
.toString('base64')
.replace(/[^a-z0-9]/gi, 'l');
} |
JavaScript | function partial(f) {
var as = slice(arguments, 1);
var has_ = indexOf(as, _) !== -1;
return function() {
var rest = slice(arguments);
// Don't waste time checking for placeholders if there aren't any.
var args = has_ ? take(as.length, function(i) {
var a = as[i];
return a === _ ? rest.shift() : a;
}) : as;
return f.apply(this, rest.length ? args.concat(rest) : args);
};
} | function partial(f) {
var as = slice(arguments, 1);
var has_ = indexOf(as, _) !== -1;
return function() {
var rest = slice(arguments);
// Don't waste time checking for placeholders if there aren't any.
var args = has_ ? take(as.length, function(i) {
var a = as[i];
return a === _ ? rest.shift() : a;
}) : as;
return f.apply(this, rest.length ? args.concat(rest) : args);
};
} |
JavaScript | function flattenTo(obj, result, prefix, level) {
forOwn(obj, function (value, key) {
var nestedPrefix = prefix ? prefix + '.' + key : key;
if (level !== 0 && isPlainObject(value)) {
flattenTo(value, result, nestedPrefix, level - 1);
} else {
result[nestedPrefix] = value;
}
});
return result;
} | function flattenTo(obj, result, prefix, level) {
forOwn(obj, function (value, key) {
var nestedPrefix = prefix ? prefix + '.' + key : key;
if (level !== 0 && isPlainObject(value)) {
flattenTo(value, result, nestedPrefix, level - 1);
} else {
result[nestedPrefix] = value;
}
});
return result;
} |
JavaScript | function flatten(obj, level) {
if (obj == null) {
return {};
}
level = level == null ? -1 : level;
return flattenTo(obj, {}, '', level);
} | function flatten(obj, level) {
if (obj == null) {
return {};
}
level = level == null ? -1 : level;
return flattenTo(obj, {}, '', level);
} |
JavaScript | function Type(check, name) {
var self = this;
if (!(self instanceof Type)) {
throw new Error("Type constructor cannot be invoked without 'new'");
}
// Unfortunately we can't elegantly reuse isFunction and isString,
// here, because this code is executed while defining those types.
if (objToStr.call(check) !== funObjStr) {
throw new Error(check + " is not a function");
}
// The `name` parameter can be either a function or a string.
var nameObjStr = objToStr.call(name);
if (!(nameObjStr === funObjStr ||
nameObjStr === strObjStr)) {
throw new Error(name + " is neither a function nor a string");
}
Object.defineProperties(self, {
name: { value: name },
check: {
value: function(value, deep) {
var result = check.call(self, value, deep);
if (!result && deep && objToStr.call(deep) === funObjStr)
deep(self, value);
return result;
}
}
});
} | function Type(check, name) {
var self = this;
if (!(self instanceof Type)) {
throw new Error("Type constructor cannot be invoked without 'new'");
}
// Unfortunately we can't elegantly reuse isFunction and isString,
// here, because this code is executed while defining those types.
if (objToStr.call(check) !== funObjStr) {
throw new Error(check + " is not a function");
}
// The `name` parameter can be either a function or a string.
var nameObjStr = objToStr.call(name);
if (!(nameObjStr === funObjStr ||
nameObjStr === strObjStr)) {
throw new Error(name + " is neither a function nor a string");
}
Object.defineProperties(self, {
name: { value: name },
check: {
value: function(value, deep) {
var result = check.call(self, value, deep);
if (!result && deep && objToStr.call(deep) === funObjStr)
deep(self, value);
return result;
}
}
});
} |
JavaScript | function toType(from, name) {
// The toType function should of course be idempotent.
if (from instanceof Type)
return from;
// The Def type is used as a helper for constructing compound
// interface types for AST nodes.
if (from instanceof Def)
return from.type;
// Support [ElemType] syntax.
if (isArray.check(from))
return Type.fromArray(from);
// Support { someField: FieldType, ... } syntax.
if (isObject.check(from))
return Type.fromObject(from);
if (isFunction.check(from)) {
var bicfIndex = builtInCtorFns.indexOf(from);
if (bicfIndex >= 0) {
return builtInCtorTypes[bicfIndex];
}
// If isFunction.check(from), and from is not a built-in
// constructor, assume from is a binary predicate function we can
// use to define the type.
return new Type(from, name);
}
// As a last resort, toType returns a type that matches any value that
// is === from. This is primarily useful for literal values like
// toType(null), but it has the additional advantage of allowing
// toType to be a total function.
return new Type(function(value) {
return value === from;
}, isUndefined.check(name) ? function() {
return from + "";
} : name);
} | function toType(from, name) {
// The toType function should of course be idempotent.
if (from instanceof Type)
return from;
// The Def type is used as a helper for constructing compound
// interface types for AST nodes.
if (from instanceof Def)
return from.type;
// Support [ElemType] syntax.
if (isArray.check(from))
return Type.fromArray(from);
// Support { someField: FieldType, ... } syntax.
if (isObject.check(from))
return Type.fromObject(from);
if (isFunction.check(from)) {
var bicfIndex = builtInCtorFns.indexOf(from);
if (bicfIndex >= 0) {
return builtInCtorTypes[bicfIndex];
}
// If isFunction.check(from), and from is not a built-in
// constructor, assume from is a binary predicate function we can
// use to define the type.
return new Type(from, name);
}
// As a last resort, toType returns a type that matches any value that
// is === from. This is primarily useful for literal values like
// toType(null), but it has the additional advantage of allowing
// toType to be a total function.
return new Type(function(value) {
return value === from;
}, isUndefined.check(name) ? function() {
return from + "";
} : name);
} |
JavaScript | function wrapExpressionBuilderWithStatement(typeName) {
var wrapperName = getStatementBuilderName(typeName);
// skip if the builder already exists
if (builders[wrapperName]) return;
// the builder function to wrap with builders.ExpressionStatement
var wrapped = builders[getBuilderName(typeName)];
// skip if there is nothing to wrap
if (!wrapped) return;
builders[wrapperName] = function() {
return builders.expressionStatement(wrapped.apply(builders, arguments));
};
} | function wrapExpressionBuilderWithStatement(typeName) {
var wrapperName = getStatementBuilderName(typeName);
// skip if the builder already exists
if (builders[wrapperName]) return;
// the builder function to wrap with builders.ExpressionStatement
var wrapped = builders[getBuilderName(typeName)];
// skip if there is nothing to wrap
if (!wrapped) return;
builders[wrapperName] = function() {
return builders.expressionStatement(wrapped.apply(builders, arguments));
};
} |
JavaScript | function after(closure, times){
return function () {
if (--times <= 0) closure();
};
} | function after(closure, times){
return function () {
if (--times <= 0) closure();
};
} |
JavaScript | function omit(obj, var_keys){
var keys = typeof arguments[1] !== 'string'? arguments[1] : slice(arguments, 1),
out = {};
for (var property in obj) {
if (obj.hasOwnProperty(property) && !contains(keys, property)) {
out[property] = obj[property];
}
}
return out;
} | function omit(obj, var_keys){
var keys = typeof arguments[1] !== 'string'? arguments[1] : slice(arguments, 1),
out = {};
for (var property in obj) {
if (obj.hasOwnProperty(property) && !contains(keys, property)) {
out[property] = obj[property];
}
}
return out;
} |
JavaScript | function ancestor(node, visitors, base, state) {
if (!base) base = exports.base
if (!state) state = []
;(function c(node, st, override) {
let type = override || node.type, found = visitors[type]
if (node != st[st.length - 1]) {
st = st.slice()
st.push(node)
}
base[type](node, st, c)
if (found) found(node, st)
})(node, state)
} | function ancestor(node, visitors, base, state) {
if (!base) base = exports.base
if (!state) state = []
;(function c(node, st, override) {
let type = override || node.type, found = visitors[type]
if (node != st[st.length - 1]) {
st = st.slice()
st.push(node)
}
base[type](node, st, c)
if (found) found(node, st)
})(node, state)
} |
JavaScript | function findNodeAt(node, start, end, test, base, state) {
test = makeTest(test)
if (!base) base = exports.base
try {
;(function c(node, st, override) {
let type = override || node.type
if ((start == null || node.start <= start) &&
(end == null || node.end >= end))
base[type](node, st, c)
if (test(type, node) &&
(start == null || node.start == start) &&
(end == null || node.end == end))
throw new Found(node, st)
})(node, state)
} catch (e) {
if (e instanceof Found) return e
throw e
}
} | function findNodeAt(node, start, end, test, base, state) {
test = makeTest(test)
if (!base) base = exports.base
try {
;(function c(node, st, override) {
let type = override || node.type
if ((start == null || node.start <= start) &&
(end == null || node.end >= end))
base[type](node, st, c)
if (test(type, node) &&
(start == null || node.start == start) &&
(end == null || node.end == end))
throw new Found(node, st)
})(node, state)
} catch (e) {
if (e instanceof Found) return e
throw e
}
} |
JavaScript | function findNodeAround(node, pos, test, base, state) {
test = makeTest(test)
if (!base) base = exports.base
try {
;(function c(node, st, override) {
let type = override || node.type
if (node.start > pos || node.end < pos) return
base[type](node, st, c)
if (test(type, node)) throw new Found(node, st)
})(node, state)
} catch (e) {
if (e instanceof Found) return e
throw e
}
} | function findNodeAround(node, pos, test, base, state) {
test = makeTest(test)
if (!base) base = exports.base
try {
;(function c(node, st, override) {
let type = override || node.type
if (node.start > pos || node.end < pos) return
base[type](node, st, c)
if (test(type, node)) throw new Found(node, st)
})(node, state)
} catch (e) {
if (e instanceof Found) return e
throw e
}
} |
JavaScript | function findNodeAfter(node, pos, test, base, state) {
test = makeTest(test)
if (!base) base = exports.base
try {
;(function c(node, st, override) {
if (node.end < pos) return
let type = override || node.type
if (node.start >= pos && test(type, node)) throw new Found(node, st)
base[type](node, st, c)
})(node, state)
} catch (e) {
if (e instanceof Found) return e
throw e
}
} | function findNodeAfter(node, pos, test, base, state) {
test = makeTest(test)
if (!base) base = exports.base
try {
;(function c(node, st, override) {
if (node.end < pos) return
let type = override || node.type
if (node.start >= pos && test(type, node)) throw new Found(node, st)
base[type](node, st, c)
})(node, state)
} catch (e) {
if (e instanceof Found) return e
throw e
}
} |
JavaScript | function findNodeBefore(node, pos, test, base, state) {
test = makeTest(test)
if (!base) base = exports.base
let max
;(function c(node, st, override) {
if (node.start > pos) return
let type = override || node.type
if (node.end <= pos && (!max || max.node.end < node.end) && test(type, node))
max = new Found(node, st)
base[type](node, st, c)
})(node, state)
return max
} | function findNodeBefore(node, pos, test, base, state) {
test = makeTest(test)
if (!base) base = exports.base
let max
;(function c(node, st, override) {
if (node.start > pos) return
let type = override || node.type
if (node.end <= pos && (!max || max.node.end < node.end) && test(type, node))
max = new Found(node, st)
base[type](node, st, c)
})(node, state)
return max
} |
JavaScript | function cleanUpNodesAfterPrune(remainingNodePath) {
if (n.VariableDeclaration.check(remainingNodePath.node)) {
var declarations = remainingNodePath.get('declarations').value;
if (!declarations || declarations.length === 0) {
return remainingNodePath.prune();
}
} else if (n.ExpressionStatement.check(remainingNodePath.node)) {
if (!remainingNodePath.get('expression').value) {
return remainingNodePath.prune();
}
} else if (n.IfStatement.check(remainingNodePath.node)) {
cleanUpIfStatementAfterPrune(remainingNodePath);
}
return remainingNodePath;
} | function cleanUpNodesAfterPrune(remainingNodePath) {
if (n.VariableDeclaration.check(remainingNodePath.node)) {
var declarations = remainingNodePath.get('declarations').value;
if (!declarations || declarations.length === 0) {
return remainingNodePath.prune();
}
} else if (n.ExpressionStatement.check(remainingNodePath.node)) {
if (!remainingNodePath.get('expression').value) {
return remainingNodePath.prune();
}
} else if (n.IfStatement.check(remainingNodePath.node)) {
cleanUpIfStatementAfterPrune(remainingNodePath);
}
return remainingNodePath;
} |
JavaScript | function deepOwnEqual(a, b) {
// if arrays of objects, recurse down to the objects
if(Array.isArray(a) && Array.isArray(b)) {
assert.deepEqual(a.length, b.length, 'Arrays have different lengths')
for(var i=0; i<a.length; i++) {
deepOwnEqual(a[i], b[i])
}
}
// compare all the object properties
else {
var aKeys = Object.keys(a);
var bKeys = Object.keys(b);
assert.deepEqual(aKeys, bKeys, 'Objects have different keys');
aKeys.forEach(function(key) {
assert.deepEqual(a[key], b[key], 'Expected values of "' + key + '" property to be equal in each object')
});
}
} | function deepOwnEqual(a, b) {
// if arrays of objects, recurse down to the objects
if(Array.isArray(a) && Array.isArray(b)) {
assert.deepEqual(a.length, b.length, 'Arrays have different lengths')
for(var i=0; i<a.length; i++) {
deepOwnEqual(a[i], b[i])
}
}
// compare all the object properties
else {
var aKeys = Object.keys(a);
var bKeys = Object.keys(b);
assert.deepEqual(aKeys, bKeys, 'Objects have different keys');
aKeys.forEach(function(key) {
assert.deepEqual(a[key], b[key], 'Expected values of "' + key + '" property to be equal in each object')
});
}
} |
JavaScript | function isExternalStackEntry (entry) {
return (entry ? true : false) &&
// entries related to jasmine and karma-jasmine:
!/\/(jasmine-core|karma-jasmine)\//.test(entry) &&
// karma specifics, e.g. "at http://localhost:7018/karma.js:185"
!/\/(karma.js|context.html):/.test(entry)
} | function isExternalStackEntry (entry) {
return (entry ? true : false) &&
// entries related to jasmine and karma-jasmine:
!/\/(jasmine-core|karma-jasmine)\//.test(entry) &&
// karma specifics, e.g. "at http://localhost:7018/karma.js:185"
!/\/(karma.js|context.html):/.test(entry)
} |
JavaScript | function formatFailedStep (step) {
// Safari seems to have no stack trace,
// so we just return the error message:
if (!step.stack) { return step.message; }
var relevantMessage = []
var relevantStack = []
// Remove the message prior to processing the stack to prevent issues like
// https://github.com/karma-runner/karma-jasmine/issues/79
var stack = step.stack.replace('Error: ' + step.message, '')
var dirtyRelevantStack = getRelevantStackFrom(stack)
// PhantomJS returns multiline error message for errors coming from specs
// (for example when calling a non-existing function). This error is present
// in both `step.message` and `step.stack` at the same time, but stack seems
// preferable, so we iterate relevant stack, compare it to message:
for (var i = 0; i < dirtyRelevantStack.length; i += 1) {
if (step.message && step.message.indexOf(dirtyRelevantStack[i]) === -1) {
// Stack entry is not in the message,
// we consider it to be a relevant stack:
relevantStack.push(dirtyRelevantStack[i])
} else {
// Stack entry is already in the message,
// we consider it to be a suitable message alternative:
relevantMessage.push(dirtyRelevantStack[i])
}
}
// In most cases the above will leave us with an empty message...
if (relevantMessage.length === 0) {
// Let's reuse the original message:
relevantMessage.push(step.message)
// Now we probably have a repetition case where:
// relevantMessage: ["Expected true to be false."]
// relevantStack: ["Error: Expected true to be false.", ...]
if (relevantStack.length && relevantStack[0].indexOf(step.message) !== -1) {
// The message seems preferable, so we remove the first value from
// the stack to get rid of repetition :
relevantStack.shift()
}
}
// Example output:
// --------------------
// Chrome 40.0.2214 (Mac OS X 10.9.5) xxx should return false 1 FAILED
// Expected true to be false
// at /foo/bar/baz.spec.js:22:13
// at /foo/bar/baz.js:18:29
return relevantMessage.concat(relevantStack).join('\n')
} | function formatFailedStep (step) {
// Safari seems to have no stack trace,
// so we just return the error message:
if (!step.stack) { return step.message; }
var relevantMessage = []
var relevantStack = []
// Remove the message prior to processing the stack to prevent issues like
// https://github.com/karma-runner/karma-jasmine/issues/79
var stack = step.stack.replace('Error: ' + step.message, '')
var dirtyRelevantStack = getRelevantStackFrom(stack)
// PhantomJS returns multiline error message for errors coming from specs
// (for example when calling a non-existing function). This error is present
// in both `step.message` and `step.stack` at the same time, but stack seems
// preferable, so we iterate relevant stack, compare it to message:
for (var i = 0; i < dirtyRelevantStack.length; i += 1) {
if (step.message && step.message.indexOf(dirtyRelevantStack[i]) === -1) {
// Stack entry is not in the message,
// we consider it to be a relevant stack:
relevantStack.push(dirtyRelevantStack[i])
} else {
// Stack entry is already in the message,
// we consider it to be a suitable message alternative:
relevantMessage.push(dirtyRelevantStack[i])
}
}
// In most cases the above will leave us with an empty message...
if (relevantMessage.length === 0) {
// Let's reuse the original message:
relevantMessage.push(step.message)
// Now we probably have a repetition case where:
// relevantMessage: ["Expected true to be false."]
// relevantStack: ["Error: Expected true to be false.", ...]
if (relevantStack.length && relevantStack[0].indexOf(step.message) !== -1) {
// The message seems preferable, so we remove the first value from
// the stack to get rid of repetition :
relevantStack.shift()
}
}
// Example output:
// --------------------
// Chrome 40.0.2214 (Mac OS X 10.9.5) xxx should return false 1 FAILED
// Expected true to be false
// at /foo/bar/baz.spec.js:22:13
// at /foo/bar/baz.js:18:29
return relevantMessage.concat(relevantStack).join('\n')
} |
JavaScript | function KarmaReporter (tc, jasmineEnv) {
var currentSuite = new SuiteNode()
/**
* @param suite
* @returns {boolean} Return true if it is system jasmine top level suite
*/
function isTopLevelSuite (suite) {
return suite.description === 'Jasmine_TopLevel_Suite'
}
/**
* Jasmine 2.0 dispatches the following events:
*
* - jasmineStarted
* - jasmineDone
* - suiteStarted
* - suiteDone
* - specStarted
* - specDone
*/
this.jasmineStarted = function (data) {
// TODO(vojta): Do not send spec names when polling.
tc.info({
total: data.totalSpecsDefined,
specs: getAllSpecNames(jasmineEnv.topSuite())
})
}
this.jasmineDone = function () {
tc.complete({
coverage: window.__coverage__
})
}
this.suiteStarted = function (result) {
if (!isTopLevelSuite(result)) {
currentSuite = currentSuite.addChild(result.description)
}
}
this.suiteDone = function (result) {
// In the case of xdescribe, only "suiteDone" is fired.
// We need to skip that.
if (result.description !== currentSuite.name) {
return
}
currentSuite = currentSuite.parent
}
this.specStarted = function (specResult) {
specResult.startTime = new Date().getTime()
}
this.specDone = function (specResult) {
var skipped = specResult.status === 'disabled' || specResult.status === 'pending'
var result = {
description: specResult.description,
id: specResult.id,
log: [],
skipped: skipped,
success: specResult.failedExpectations.length === 0,
suite: [],
time: skipped ? 0 : new Date().getTime() - specResult.startTime,
executedExpectationsCount: specResult.failedExpectations.length + specResult.passedExpectations.length
}
// generate ordered list of (nested) suite names
var suitePointer = currentSuite
while (suitePointer.parent) {
result.suite.unshift(suitePointer.name)
suitePointer = suitePointer.parent
}
if (!result.success) {
var steps = specResult.failedExpectations
for (var i = 0, l = steps.length; i < l; i++) {
result.log.push(formatFailedStep(steps[i]))
}
}
tc.result(result)
delete specResult.startTime
}
} | function KarmaReporter (tc, jasmineEnv) {
var currentSuite = new SuiteNode()
/**
* @param suite
* @returns {boolean} Return true if it is system jasmine top level suite
*/
function isTopLevelSuite (suite) {
return suite.description === 'Jasmine_TopLevel_Suite'
}
/**
* Jasmine 2.0 dispatches the following events:
*
* - jasmineStarted
* - jasmineDone
* - suiteStarted
* - suiteDone
* - specStarted
* - specDone
*/
this.jasmineStarted = function (data) {
// TODO(vojta): Do not send spec names when polling.
tc.info({
total: data.totalSpecsDefined,
specs: getAllSpecNames(jasmineEnv.topSuite())
})
}
this.jasmineDone = function () {
tc.complete({
coverage: window.__coverage__
})
}
this.suiteStarted = function (result) {
if (!isTopLevelSuite(result)) {
currentSuite = currentSuite.addChild(result.description)
}
}
this.suiteDone = function (result) {
// In the case of xdescribe, only "suiteDone" is fired.
// We need to skip that.
if (result.description !== currentSuite.name) {
return
}
currentSuite = currentSuite.parent
}
this.specStarted = function (specResult) {
specResult.startTime = new Date().getTime()
}
this.specDone = function (specResult) {
var skipped = specResult.status === 'disabled' || specResult.status === 'pending'
var result = {
description: specResult.description,
id: specResult.id,
log: [],
skipped: skipped,
success: specResult.failedExpectations.length === 0,
suite: [],
time: skipped ? 0 : new Date().getTime() - specResult.startTime,
executedExpectationsCount: specResult.failedExpectations.length + specResult.passedExpectations.length
}
// generate ordered list of (nested) suite names
var suitePointer = currentSuite
while (suitePointer.parent) {
result.suite.unshift(suitePointer.name)
suitePointer = suitePointer.parent
}
if (!result.success) {
var steps = specResult.failedExpectations
for (var i = 0, l = steps.length; i < l; i++) {
result.log.push(formatFailedStep(steps[i]))
}
}
tc.result(result)
delete specResult.startTime
}
} |
JavaScript | function handleUncaughtExceptions(error) {
if (!error || !error.stack) {
console.log('Uncaught exception:', error);
} else {
var source = getErrorSource(error);
if (source !== null) console.log(source);
console.log(error.stack);
}
process.exit(1);
} | function handleUncaughtExceptions(error) {
if (!error || !error.stack) {
console.log('Uncaught exception:', error);
} else {
var source = getErrorSource(error);
if (source !== null) console.log(source);
console.log(error.stack);
}
process.exit(1);
} |
JavaScript | function _rmdirRecursiveSync(root) {
var dirs = [root];
do {
var
dir = dirs.pop(),
deferred = false,
files = fs.readdirSync(dir);
for (var i = 0, length = files.length; i < length; i++) {
var
file = path.join(dir, files[i]),
stat = fs.lstatSync(file); // lstat so we don't recurse into symlinked directories
if (stat.isDirectory()) {
if (!deferred) {
deferred = true;
dirs.push(dir);
}
dirs.push(file);
} else {
fs.unlinkSync(file);
}
}
if (!deferred) {
fs.rmdirSync(dir);
}
} while (dirs.length !== 0);
} | function _rmdirRecursiveSync(root) {
var dirs = [root];
do {
var
dir = dirs.pop(),
deferred = false,
files = fs.readdirSync(dir);
for (var i = 0, length = files.length; i < length; i++) {
var
file = path.join(dir, files[i]),
stat = fs.lstatSync(file); // lstat so we don't recurse into symlinked directories
if (stat.isDirectory()) {
if (!deferred) {
deferred = true;
dirs.push(dir);
}
dirs.push(file);
} else {
fs.unlinkSync(file);
}
}
if (!deferred) {
fs.rmdirSync(dir);
}
} while (dirs.length !== 0);
} |
JavaScript | function _prepareTmpFileRemoveCallback(name, fd, opts) {
var removeCallback = _prepareRemoveCallback(function _removeCallback(fdPath) {
try {
fs.closeSync(fdPath[0]);
}
catch (e) {
// under some node/windows related circumstances, a temporary file
// may have not be created as expected or the file was already closed
// by the user, in which case we will simply ignore the error
if (e.errno != -_c.EBADF && e.errno != -c.ENOENT) {
// reraise any unanticipated error
throw e;
}
}
fs.unlinkSync(fdPath[1]);
}, [fd, name]);
if (!opts.keep) {
_removeObjects.unshift(removeCallback);
}
return removeCallback;
} | function _prepareTmpFileRemoveCallback(name, fd, opts) {
var removeCallback = _prepareRemoveCallback(function _removeCallback(fdPath) {
try {
fs.closeSync(fdPath[0]);
}
catch (e) {
// under some node/windows related circumstances, a temporary file
// may have not be created as expected or the file was already closed
// by the user, in which case we will simply ignore the error
if (e.errno != -_c.EBADF && e.errno != -c.ENOENT) {
// reraise any unanticipated error
throw e;
}
}
fs.unlinkSync(fdPath[1]);
}, [fd, name]);
if (!opts.keep) {
_removeObjects.unshift(removeCallback);
}
return removeCallback;
} |
JavaScript | function _garbageCollector() {
if (_uncaughtException && !_gracefulCleanup) {
return;
}
for (var i = 0, length = _removeObjects.length; i < length; i++) {
try {
_removeObjects[i].call(null);
} catch (e) {
// already removed?
}
}
} | function _garbageCollector() {
if (_uncaughtException && !_gracefulCleanup) {
return;
}
for (var i = 0, length = _removeObjects.length; i < length; i++) {
try {
_removeObjects[i].call(null);
} catch (e) {
// already removed?
}
}
} |
JavaScript | function mkStartFunc(server) {
return function() {
return server.start();
};
} | function mkStartFunc(server) {
return function() {
return server.start();
};
} |
JavaScript | function testParsingLongStackTrace() {
var longArg = goog.string.buildString(
'(', goog.string.repeat('x', 1000000), ')');
var stackTrace = goog.string.buildString(
'shortFrame()@:0\n',
'longFrame',
longArg,
'@http://google.com/somescript:0\n');
var frames = webdriver.stacktrace.parse_(stackTrace);
assertEquals('number of returned frames', 2, frames.length);
var expected = new webdriver.stacktrace.Frame('', 'shortFrame', '', '');
assertStackFrame('short frame', frames[0], expected);
expected = new webdriver.stacktrace.Frame(
'', 'longFrame', '', 'http://google.com/somescript:0');
assertStackFrame('exception name only', frames[1], expected);
} | function testParsingLongStackTrace() {
var longArg = goog.string.buildString(
'(', goog.string.repeat('x', 1000000), ')');
var stackTrace = goog.string.buildString(
'shortFrame()@:0\n',
'longFrame',
longArg,
'@http://google.com/somescript:0\n');
var frames = webdriver.stacktrace.parse_(stackTrace);
assertEquals('number of returned frames', 2, frames.length);
var expected = new webdriver.stacktrace.Frame('', 'shortFrame', '', '');
assertStackFrame('short frame', frames[0], expected);
expected = new webdriver.stacktrace.Frame(
'', 'longFrame', '', 'http://google.com/somescript:0');
assertStackFrame('exception name only', frames[1], expected);
} |
JavaScript | function read(req, res, next, parse, debug, options) {
var length
var stream
// flag as parsed
req._body = true
var opts = options || {}
try {
stream = contentstream(req, debug, opts.inflate)
length = stream.length
stream.length = undefined
} catch (err) {
return next(err)
}
opts.length = length
var encoding = opts.encoding !== null
? opts.encoding || 'utf-8'
: null
var verify = opts.verify
opts.encoding = verify
? null
: encoding
// read body
debug('read body')
getBody(stream, opts, function (err, body) {
if (err) {
// default to 400
setErrorStatus(err, 400)
// echo back charset
if (err.type === 'encoding.unsupported') {
err = createError(415, 'unsupported charset "' + encoding.toUpperCase() + '"', {
charset: encoding.toLowerCase()
})
}
// read off entire request
stream.resume()
onFinished(req, function onfinished() {
next(err)
})
return
}
// verify
if (verify) {
try {
debug('verify body')
verify(req, res, body, encoding)
} catch (err) {
// default to 403
setErrorStatus(err, 403)
next(err)
return
}
}
// parse
var str
try {
debug('parse body')
str = typeof body !== 'string' && encoding !== null
? iconv.decode(body, encoding)
: body
req.body = parse(str)
} catch (err) {
err.body = str === undefined
? body
: str
// default to 400
setErrorStatus(err, 400)
next(err)
return
}
next()
})
} | function read(req, res, next, parse, debug, options) {
var length
var stream
// flag as parsed
req._body = true
var opts = options || {}
try {
stream = contentstream(req, debug, opts.inflate)
length = stream.length
stream.length = undefined
} catch (err) {
return next(err)
}
opts.length = length
var encoding = opts.encoding !== null
? opts.encoding || 'utf-8'
: null
var verify = opts.verify
opts.encoding = verify
? null
: encoding
// read body
debug('read body')
getBody(stream, opts, function (err, body) {
if (err) {
// default to 400
setErrorStatus(err, 400)
// echo back charset
if (err.type === 'encoding.unsupported') {
err = createError(415, 'unsupported charset "' + encoding.toUpperCase() + '"', {
charset: encoding.toLowerCase()
})
}
// read off entire request
stream.resume()
onFinished(req, function onfinished() {
next(err)
})
return
}
// verify
if (verify) {
try {
debug('verify body')
verify(req, res, body, encoding)
} catch (err) {
// default to 403
setErrorStatus(err, 403)
next(err)
return
}
}
// parse
var str
try {
debug('parse body')
str = typeof body !== 'string' && encoding !== null
? iconv.decode(body, encoding)
: body
req.body = parse(str)
} catch (err) {
err.body = str === undefined
? body
: str
// default to 400
setErrorStatus(err, 400)
next(err)
return
}
next()
})
} |
JavaScript | function contentstream(req, debug, inflate) {
var encoding = (req.headers['content-encoding'] || 'identity').toLowerCase()
var length = req.headers['content-length']
var stream
debug('content-encoding "%s"', encoding)
if (inflate === false && encoding !== 'identity') {
throw createError(415, 'content encoding unsupported')
}
switch (encoding) {
case 'deflate':
stream = zlib.createInflate()
debug('inflate body')
req.pipe(stream)
break
case 'gzip':
stream = zlib.createGunzip()
debug('gunzip body')
req.pipe(stream)
break
case 'identity':
stream = req
stream.length = length
break
default:
throw createError(415, 'unsupported content encoding "' + encoding + '"', {
encoding: encoding
})
}
return stream
} | function contentstream(req, debug, inflate) {
var encoding = (req.headers['content-encoding'] || 'identity').toLowerCase()
var length = req.headers['content-length']
var stream
debug('content-encoding "%s"', encoding)
if (inflate === false && encoding !== 'identity') {
throw createError(415, 'content encoding unsupported')
}
switch (encoding) {
case 'deflate':
stream = zlib.createInflate()
debug('inflate body')
req.pipe(stream)
break
case 'gzip':
stream = zlib.createGunzip()
debug('gunzip body')
req.pipe(stream)
break
case 'identity':
stream = req
stream.length = length
break
default:
throw createError(415, 'unsupported content encoding "' + encoding + '"', {
encoding: encoding
})
}
return stream
} |
JavaScript | function reverse(array) {
var copy = array.slice();
copy.reverse();
return copy;
} | function reverse(array) {
var copy = array.slice();
copy.reverse();
return copy;
} |
JavaScript | function globalResolve(module) {
var modulePath, dirname
var prefix = rc('npm').prefix
if (isWin32) {
dirname = prefix || path.dirname(process.execPath)
}
else {
prefix = prefix || path.join(process.execPath, '../..')
dirname = path.join(prefix, 'lib')
}
dirname = path.join(dirname, 'node_modules')
modulePath = resolveFn(module, dirname)
return modulePath
} | function globalResolve(module) {
var modulePath, dirname
var prefix = rc('npm').prefix
if (isWin32) {
dirname = prefix || path.dirname(process.execPath)
}
else {
prefix = prefix || path.join(process.execPath, '../..')
dirname = path.join(prefix, 'lib')
}
dirname = path.join(dirname, 'node_modules')
modulePath = resolveFn(module, dirname)
return modulePath
} |
JavaScript | function isExcluded(url, config) {
var excludeURLs = config.excludeURLs || [];
for (var i = 0; i < excludeURLs.length; i++) {
if (typeof excludeURLs[i] == typeof '') {
if (url == excludeURLs[i]) {
return true;
}
} else {
if (excludeURLs[i].test(url)) {
return true;
}
}
}
return false;
} | function isExcluded(url, config) {
var excludeURLs = config.excludeURLs || [];
for (var i = 0; i < excludeURLs.length; i++) {
if (typeof excludeURLs[i] == typeof '') {
if (url == excludeURLs[i]) {
return true;
}
} else {
if (excludeURLs[i].test(url)) {
return true;
}
}
}
return false;
} |
JavaScript | function isMessageToIgnore(message) {
if (message == 'It is against Angular best practices to instantiate a ' +
'controller on the window. This behavior is deprecated in Angular ' +
'1.3.0') {
return true; // An ngHint bug, see http://git.io/S3yySQ
}
var module = /^Module "(\w*)" was created but never loaded\.$/.exec(
message);
if (module != null) {
module = module[1];
if (ngHintNames[module] != null) {
return true; // An ngHint module
}
if ((module == 'protractorBaseModule_') || (module ==
'protractorNgHintCaptureModule_')) {
return true; // A protractor module
}
}
return false;
} | function isMessageToIgnore(message) {
if (message == 'It is against Angular best practices to instantiate a ' +
'controller on the window. This behavior is deprecated in Angular ' +
'1.3.0') {
return true; // An ngHint bug, see http://git.io/S3yySQ
}
var module = /^Module "(\w*)" was created but never loaded\.$/.exec(
message);
if (module != null) {
module = module[1];
if (ngHintNames[module] != null) {
return true; // An ngHint module
}
if ((module == 'protractorBaseModule_') || (module ==
'protractorNgHintCaptureModule_')) {
return true; // A protractor module
}
}
return false;
} |
JavaScript | function teardown() {
var self = this;
// Get logged data
return browser.executeScript_(function() {
return localStorage.getItem('ngHintLog_protractor') || '{}';
}, 'get ngHintLog').then(function(ngHintLog) {
ngHintLog = JSON.parse(ngHintLog);
// Get a list of all the modules we tested against
var modulesUsed = _.union.apply(_, [_.values(ngHintNames)].concat(
_.values(ngHintLog).map(Object.keys)));
// Check log
var testOut = {failedCount: 0, specResults: []};
for (url in ngHintLog) {
if (!isExcluded(url, self.config)) {
for (var i = 0; i < modulesUsed.length; i++) {
var resultInfo = {specName: 'Angular Hint Test: ' + modulesUsed[i] +
' (' + url + ')'};
var passed = true;
// Fill in the test details
var messages = ngHintLog[url][modulesUsed[i]];
if (messages) {
for (var message in messages) {
if (!isMessageToIgnore(message)) {
(self.config.asTests !== false ? self.addFailure :
self.addWarning)(messages[message] + ' -- ' + message,
resultInfo);
passed = false;
}
}
}
if (passed) {
self.addSuccess(resultInfo);
}
}
}
}
});
} | function teardown() {
var self = this;
// Get logged data
return browser.executeScript_(function() {
return localStorage.getItem('ngHintLog_protractor') || '{}';
}, 'get ngHintLog').then(function(ngHintLog) {
ngHintLog = JSON.parse(ngHintLog);
// Get a list of all the modules we tested against
var modulesUsed = _.union.apply(_, [_.values(ngHintNames)].concat(
_.values(ngHintLog).map(Object.keys)));
// Check log
var testOut = {failedCount: 0, specResults: []};
for (url in ngHintLog) {
if (!isExcluded(url, self.config)) {
for (var i = 0; i < modulesUsed.length; i++) {
var resultInfo = {specName: 'Angular Hint Test: ' + modulesUsed[i] +
' (' + url + ')'};
var passed = true;
// Fill in the test details
var messages = ngHintLog[url][modulesUsed[i]];
if (messages) {
for (var message in messages) {
if (!isMessageToIgnore(message)) {
(self.config.asTests !== false ? self.addFailure :
self.addWarning)(messages[message] + ' -- ' + message,
resultInfo);
passed = false;
}
}
}
if (passed) {
self.addSuccess(resultInfo);
}
}
}
}
});
} |
JavaScript | function memoize(fn, resolver) {
if (!isFunction(fn) || (resolver && !isFunction(resolver))) {
throw new TypeError('Expected a function');
}
var memoized = function() {
var cache = memoized.cache,
key = resolver ? resolver.apply(this, arguments) : arguments[0];
if (hasOwn(cache, key)) {
return cache[key];
}
var result = fn.apply(this, arguments);
cache[key] = result;
return result;
};
memoized.cache = {};
return memoized;
} | function memoize(fn, resolver) {
if (!isFunction(fn) || (resolver && !isFunction(resolver))) {
throw new TypeError('Expected a function');
}
var memoized = function() {
var cache = memoized.cache,
key = resolver ? resolver.apply(this, arguments) : arguments[0];
if (hasOwn(cache, key)) {
return cache[key];
}
var result = fn.apply(this, arguments);
cache[key] = result;
return result;
};
memoized.cache = {};
return memoized;
} |
JavaScript | function resolve (value, key) {
// resolve before/after from root or parent if it isn't present on the current node
if (!value._parent) return undefined;
// Immediate parent
if (value._parent._default && value._parent._default[key]) return value._parent._default[key];
// Root
var root = value._parent._parent;
if (!root) return undefined;
return root._default ? root._default[key] : undefined;
} | function resolve (value, key) {
// resolve before/after from root or parent if it isn't present on the current node
if (!value._parent) return undefined;
// Immediate parent
if (value._parent._default && value._parent._default[key]) return value._parent._default[key];
// Root
var root = value._parent._parent;
if (!root) return undefined;
return root._default ? root._default[key] : undefined;
} |
JavaScript | function iconStyle(files, useIcons) {
if (!useIcons) return '';
var className;
var i;
var iconName;
var list = [];
var rules = {};
var selector;
var selectors = {};
var style = '';
for (i = 0; i < files.length; i++) {
var file = files[i];
var isDir = file.stat && file.stat.isDirectory();
var icon = isDir
? { className: 'icon-directory', fileName: icons.folder }
: iconLookup(file.name);
var iconName = icon.fileName;
selector = '#files .' + icon.className + ' .name';
if (!rules[iconName]) {
rules[iconName] = 'background-image: url(data:image/png;base64,' + load(iconName) + ');'
selectors[iconName] = [];
list.push(iconName);
}
if (selectors[iconName].indexOf(selector) === -1) {
selectors[iconName].push(selector);
}
}
for (i = 0; i < list.length; i++) {
iconName = list[i];
style += selectors[iconName].join(',\n') + ' {\n ' + rules[iconName] + '\n}\n';
}
return style;
} | function iconStyle(files, useIcons) {
if (!useIcons) return '';
var className;
var i;
var iconName;
var list = [];
var rules = {};
var selector;
var selectors = {};
var style = '';
for (i = 0; i < files.length; i++) {
var file = files[i];
var isDir = file.stat && file.stat.isDirectory();
var icon = isDir
? { className: 'icon-directory', fileName: icons.folder }
: iconLookup(file.name);
var iconName = icon.fileName;
selector = '#files .' + icon.className + ' .name';
if (!rules[iconName]) {
rules[iconName] = 'background-image: url(data:image/png;base64,' + load(iconName) + ');'
selectors[iconName] = [];
list.push(iconName);
}
if (selectors[iconName].indexOf(selector) === -1) {
selectors[iconName].push(selector);
}
}
for (i = 0; i < list.length; i++) {
iconName = list[i];
style += selectors[iconName].join(',\n') + ' {\n ' + rules[iconName] + '\n}\n';
}
return style;
} |
JavaScript | function decode(queryStr, shouldTypecast) {
var queryArr = (queryStr || '').replace('?', '').split('&'),
reg = /([^=]+)=(.+)/,
i = -1,
obj = {},
equalIndex, cur, pValue, pName;
while ((cur = queryArr[++i])) {
equalIndex = cur.indexOf('=');
pName = cur.substring(0, equalIndex);
pValue = decodeURIComponent(cur.substring(equalIndex + 1));
if (shouldTypecast !== false) {
pValue = typecast(pValue);
}
if (hasOwn(obj, pName)){
if(isArray(obj[pName])){
obj[pName].push(pValue);
} else {
obj[pName] = [obj[pName], pValue];
}
} else {
obj[pName] = pValue;
}
}
return obj;
} | function decode(queryStr, shouldTypecast) {
var queryArr = (queryStr || '').replace('?', '').split('&'),
reg = /([^=]+)=(.+)/,
i = -1,
obj = {},
equalIndex, cur, pValue, pName;
while ((cur = queryArr[++i])) {
equalIndex = cur.indexOf('=');
pName = cur.substring(0, equalIndex);
pValue = decodeURIComponent(cur.substring(equalIndex + 1));
if (shouldTypecast !== false) {
pValue = typecast(pValue);
}
if (hasOwn(obj, pName)){
if(isArray(obj[pName])){
obj[pName].push(pValue);
} else {
obj[pName] = [obj[pName], pValue];
}
} else {
obj[pName] = pValue;
}
}
return obj;
} |
JavaScript | function GroupMembersForDN (opts, dn, callback, stack) {
this.opts = opts
this.dn = dn
this.callback = callback
this.stack = stack || new Map()
} | function GroupMembersForDN (opts, dn, callback, stack) {
this.opts = opts
this.dn = dn
this.callback = callback
this.stack = stack || new Map()
} |
JavaScript | function generateSid () {
const encodeLookup = '0123456789ABCDEF'
const decodeLookup = []
let j = 0
while (j < 10) decodeLookup[0x30 + j] = j++
while (j < 16) decodeLookup[0x61 - 10 + j] = j++
let rawSid = '010500000000000515000000'
for (let i = 0; i < 28; i++) {
rawSid += encodeLookup.charAt(
Math.floor(Math.random() * encodeLookup.length)
)
}
rawSid = rawSid + '0000'
const sizeof = rawSid.length >> 1
const length = sizeof << 1
const array = new Uint8Array(sizeof)
let n = 0
let i = 0
while (i < length) {
array[n++] =
(decodeLookup[rawSid.charCodeAt(i++)] << 4) |
decodeLookup[rawSid.charCodeAt(i++)]
}
return Buffer.from(array)
} | function generateSid () {
const encodeLookup = '0123456789ABCDEF'
const decodeLookup = []
let j = 0
while (j < 10) decodeLookup[0x30 + j] = j++
while (j < 16) decodeLookup[0x61 - 10 + j] = j++
let rawSid = '010500000000000515000000'
for (let i = 0; i < 28; i++) {
rawSid += encodeLookup.charAt(
Math.floor(Math.random() * encodeLookup.length)
)
}
rawSid = rawSid + '0000'
const sizeof = rawSid.length >> 1
const length = sizeof << 1
const array = new Uint8Array(sizeof)
let n = 0
let i = 0
while (i < length) {
array[n++] =
(decodeLookup[rawSid.charCodeAt(i++)] << 4) |
decodeLookup[rawSid.charCodeAt(i++)]
}
return Buffer.from(array)
} |
JavaScript | function UsersFinder (opts, includeMembership, callback) {
this.opts = opts
this.includeMembership = includeMembership
this.callback = callback
this.users = []
} | function UsersFinder (opts, includeMembership, callback) {
this.opts = opts
this.includeMembership = includeMembership
this.callback = callback
this.users = []
} |
JavaScript | function findUsers (opts, includeMembership, callback) {
let _opts = opts
let _inclMembership = includeMembership
let _cb = callback
if (typeof includeMembership === 'function') {
_cb = includeMembership
_inclMembership = false
}
if (typeof opts === 'function') {
_cb = opts
_opts = ''
}
if (typeof opts === 'string' && opts.length > 0) {
_opts = {
filter: '(&' + defaultUserFilter + utils.getCompoundFilter(opts) + ')'
}
}
log.trace('findUsers(%j,%s)', _opts, _inclMembership)
const finder = new UsersFinder(_opts, _inclMembership, _cb)
return finder.find()
} | function findUsers (opts, includeMembership, callback) {
let _opts = opts
let _inclMembership = includeMembership
let _cb = callback
if (typeof includeMembership === 'function') {
_cb = includeMembership
_inclMembership = false
}
if (typeof opts === 'function') {
_cb = opts
_opts = ''
}
if (typeof opts === 'string' && opts.length > 0) {
_opts = {
filter: '(&' + defaultUserFilter + utils.getCompoundFilter(opts) + ')'
}
}
log.trace('findUsers(%j,%s)', _opts, _inclMembership)
const finder = new UsersFinder(_opts, _inclMembership, _cb)
return finder.find()
} |
JavaScript | function FakeRDN (name) {
ldap.RDN.apply(this)
this.attrs.dn = {
name: 'dn',
order: 0,
value: name
}
this.spLead = 0
this.spTrail = 0
} | function FakeRDN (name) {
ldap.RDN.apply(this)
this.attrs.dn = {
name: 'dn',
order: 0,
value: name
}
this.spLead = 0
this.spTrail = 0
} |
JavaScript | function handleAddDay() {
let mk_special = specialDay;
let flag = 0;
let fk_day = day;
for (// eslint-disable-next-line
var i in mk_special) {
// If the insert special day is exist, add the work time
if (mk_special.hasOwnProperty(fk_day)) {
mk_special[fk_day].push({ "open": start, "close": end });
flag = 1;
break;
}
}
// If the insert special day is none, add new work time
if (flag === 0) {
let fk_day1 = {};
fk_day1[fk_day] = [{ "open": start, "close": end }];
mk_special = Object.assign(fk_day1, mk_special);
}
handleChange(mk_special)
setOpen(false)
} | function handleAddDay() {
let mk_special = specialDay;
let flag = 0;
let fk_day = day;
for (// eslint-disable-next-line
var i in mk_special) {
// If the insert special day is exist, add the work time
if (mk_special.hasOwnProperty(fk_day)) {
mk_special[fk_day].push({ "open": start, "close": end });
flag = 1;
break;
}
}
// If the insert special day is none, add new work time
if (flag === 0) {
let fk_day1 = {};
fk_day1[fk_day] = [{ "open": start, "close": end }];
mk_special = Object.assign(fk_day1, mk_special);
}
handleChange(mk_special)
setOpen(false)
} |
JavaScript | function handleDelete(date, flag) {
let fk_specialDay = specialDay;
if (flag === 1) {
Object.keys(fk_specialDay).forEach(item => {
if (date === item) {
delete fk_specialDay[item];
}
})
} else {
let value = date.split("||");
Object.keys(fk_specialDay).forEach(item => {
if (item === value[0]) {
delete fk_specialDay[item][value[1]];
}
})
}
handleChange(fk_specialDay)
} | function handleDelete(date, flag) {
let fk_specialDay = specialDay;
if (flag === 1) {
Object.keys(fk_specialDay).forEach(item => {
if (date === item) {
delete fk_specialDay[item];
}
})
} else {
let value = date.split("||");
Object.keys(fk_specialDay).forEach(item => {
if (item === value[0]) {
delete fk_specialDay[item][value[1]];
}
})
}
handleChange(fk_specialDay)
} |
JavaScript | function updateTime(e) {
let value = e.target.id.split("||");
let fk_specialDay = specialDay;
Object.keys(fk_specialDay).forEach(function (key) {
if (key === value[0]) {
fk_specialDay[key][value[1]][value[2]] = e.target.value;
}
});
setEnd(e.target.value)
} | function updateTime(e) {
let value = e.target.id.split("||");
let fk_specialDay = specialDay;
Object.keys(fk_specialDay).forEach(function (key) {
if (key === value[0]) {
fk_specialDay[key][value[1]][value[2]] = e.target.value;
}
});
setEnd(e.target.value)
} |
JavaScript | function PropsTimeToHMS() {
let fk_state = JSON.parse(props.data);
for (var key in fk_state) {
// eslint-disable-next-line
fk_state[key].forEach((element, i) => {
fk_state[key][i].open = secondsToHms(fk_state[key][i].open);
fk_state[key][i].close = secondsToHms(fk_state[key][i].close);
})
}
setSpecialDay(fk_state);
} | function PropsTimeToHMS() {
let fk_state = JSON.parse(props.data);
for (var key in fk_state) {
// eslint-disable-next-line
fk_state[key].forEach((element, i) => {
fk_state[key][i].open = secondsToHms(fk_state[key][i].open);
fk_state[key][i].close = secondsToHms(fk_state[key][i].close);
})
}
setSpecialDay(fk_state);
} |
JavaScript | function TimeToSeconds(time) {
let value = time.split(":");
var second = Number(value[0]) * 3600 + Number(value[1]) * 60;
return second;
} | function TimeToSeconds(time) {
let value = time.split(":");
var second = Number(value[0]) * 3600 + Number(value[1]) * 60;
return second;
} |
JavaScript | function input_bikes_map(widget_config, parent_el, params) {
self.log('input_bikes_map with', params);
// Add some guide text
var config_info1 = document.createElement('p');
var config_info_text = "This widget displays a map, it's location will be used to retrieve shared bikes " +
"(from ofo and mobike) located nearby which will be shown to users";
config_info_text += " 'Main Title' is any text to appear in bold at the top of the map.";
config_info1.appendChild(document.createTextNode(config_info_text));
parent_el.appendChild(config_info1);
var config_table = document.createElement('table');
config_table.className = 'config_input_stop_timetable';
parent_el.appendChild(config_table);
var config_tbody = document.createElement('tbody');
config_table.appendChild(config_tbody);
// Each config_input(...) will return a .value() callback function for the input data
// TITLE
var title_result = widget_config.input(config_tbody, 'string',
{ text: 'Main Title:', title: 'The main title at the top of the widget, e.g. bus stop name' },
params.title);
// MAP
self.log('configure() calling widget_config.input', 'with', params.map);
var bikes_map_result = widget_config.input(config_tbody, 'leaflet_map',
{ text: 'Map:', title: "Click select map view" },
{ map: params.map });
// value() is the function for this input element that returns its value
var value_fn = function () {
var config_params = {};
// title
config_params.title = title_result.value();
// map
config_params.map = bikes_map_result.value().map;
self.log(self.widget_id, 'input_bikes_map returning params:', config_params);
return config_params;
};
var config_fn = function () {
return { title: title_result.value() };
};
return { valid: function () { return true; }, //debug - still to be implemented,
config: config_fn,
value: value_fn };
} // end input_bikes_map) | function input_bikes_map(widget_config, parent_el, params) {
self.log('input_bikes_map with', params);
// Add some guide text
var config_info1 = document.createElement('p');
var config_info_text = "This widget displays a map, it's location will be used to retrieve shared bikes " +
"(from ofo and mobike) located nearby which will be shown to users";
config_info_text += " 'Main Title' is any text to appear in bold at the top of the map.";
config_info1.appendChild(document.createTextNode(config_info_text));
parent_el.appendChild(config_info1);
var config_table = document.createElement('table');
config_table.className = 'config_input_stop_timetable';
parent_el.appendChild(config_table);
var config_tbody = document.createElement('tbody');
config_table.appendChild(config_tbody);
// Each config_input(...) will return a .value() callback function for the input data
// TITLE
var title_result = widget_config.input(config_tbody, 'string',
{ text: 'Main Title:', title: 'The main title at the top of the widget, e.g. bus stop name' },
params.title);
// MAP
self.log('configure() calling widget_config.input', 'with', params.map);
var bikes_map_result = widget_config.input(config_tbody, 'leaflet_map',
{ text: 'Map:', title: "Click select map view" },
{ map: params.map });
// value() is the function for this input element that returns its value
var value_fn = function () {
var config_params = {};
// title
config_params.title = title_result.value();
// map
config_params.map = bikes_map_result.value().map;
self.log(self.widget_id, 'input_bikes_map returning params:', config_params);
return config_params;
};
var config_fn = function () {
return { title: title_result.value() };
};
return { valid: function () { return true; }, //debug - still to be implemented,
config: config_fn,
value: value_fn };
} // end input_bikes_map) |
JavaScript | show_node_information(voronoi_viz, acp_id, START, END) {
document.getElementById("line_graph").style.opacity = 1;
document.getElementById("line_graph").innerHTML = ICON_LOADING;
//if no date provided, make the date "today"
if (START == undefined) {
START = new Date().toISOString().slice(0, 10)
}
//show node data and metadata in bottom left corner
voronoi_viz.hud.show_node_metadata(voronoi_viz, acp_id)
voronoi_viz.hud.get_node_data(voronoi_viz, acp_id, START, END)
} | show_node_information(voronoi_viz, acp_id, START, END) {
document.getElementById("line_graph").style.opacity = 1;
document.getElementById("line_graph").innerHTML = ICON_LOADING;
//if no date provided, make the date "today"
if (START == undefined) {
START = new Date().toISOString().slice(0, 10)
}
//show node data and metadata in bottom left corner
voronoi_viz.hud.show_node_metadata(voronoi_viz, acp_id)
voronoi_viz.hud.get_node_data(voronoi_viz, acp_id, START, END)
} |
JavaScript | hide_all(voronoi_viz) {
document.getElementById("selected_cell").style.opacity = 0;
document.getElementById("datepicker").style.opacity = 0;
voronoi_viz.set_nav_date_visible(0);
//deselect all cells
voronoi_viz.hud.deselect_all();
} | hide_all(voronoi_viz) {
document.getElementById("selected_cell").style.opacity = 0;
document.getElementById("datepicker").style.opacity = 0;
voronoi_viz.set_nav_date_visible(0);
//deselect all cells
voronoi_viz.hud.deselect_all();
} |
JavaScript | show_datepicker(voronoi_viz) {
$('input[name="datefilter"]').daterangepicker({
showDropdowns: true,
timePicker: true,
format: 'dd/mm/yy',
locale: {
format: 'DD/MM/YYYY'
},
timePickerIncrement: 15,
opens: "center"
}, function (start, end, label) {
console.log('New date range selected: ' + start.format('YYYY-MM-DD') + ' to ' + end.format('YYYY-MM-DD') +
' (predefined range: ' + label + ')');
let start_date = start.format('YYYY-MM-DD');
let end_date = end.format('YYYY-MM-DD');
voronoi_viz.update_url(voronoi_viz.site_db.selected_site.node_acp_id, start_date)
voronoi_viz.hud.show_node_information(voronoi_viz, voronoi_viz.site_db.selected_site.node_acp_id, start_date, end_date);
});
$('input[name="datefilter"]').on('apply.daterangepicker', function (ev, picker) {
$(this).val(picker.startDate.format('YYYY-MM-DD') + ' - ' + picker.endDate.format('YYYY-MM-DD'));
let start_date = picker.startDate.format('YYYY-MM-DD');
console.log('START DATE HERE', start_date)
let end_date = picker.endDate.format('YYYY-MM-DD')
console.log('applied', start_date, end_date)
voronoi_viz.update_url(voronoi_viz.site_db.selected_site.node_acp_id, start_date)
voronoi_viz.hud.show_node_information(voronoi_viz, voronoi_viz.site_db.selected_site.node_acp_id, start_date, end_date);
});
$('input[name="datefilter"]').on('cancel.daterangepicker', function (ev, picker) {
$(this).val('');
});
} | show_datepicker(voronoi_viz) {
$('input[name="datefilter"]').daterangepicker({
showDropdowns: true,
timePicker: true,
format: 'dd/mm/yy',
locale: {
format: 'DD/MM/YYYY'
},
timePickerIncrement: 15,
opens: "center"
}, function (start, end, label) {
console.log('New date range selected: ' + start.format('YYYY-MM-DD') + ' to ' + end.format('YYYY-MM-DD') +
' (predefined range: ' + label + ')');
let start_date = start.format('YYYY-MM-DD');
let end_date = end.format('YYYY-MM-DD');
voronoi_viz.update_url(voronoi_viz.site_db.selected_site.node_acp_id, start_date)
voronoi_viz.hud.show_node_information(voronoi_viz, voronoi_viz.site_db.selected_site.node_acp_id, start_date, end_date);
});
$('input[name="datefilter"]').on('apply.daterangepicker', function (ev, picker) {
$(this).val(picker.startDate.format('YYYY-MM-DD') + ' - ' + picker.endDate.format('YYYY-MM-DD'));
let start_date = picker.startDate.format('YYYY-MM-DD');
console.log('START DATE HERE', start_date)
let end_date = picker.endDate.format('YYYY-MM-DD')
console.log('applied', start_date, end_date)
voronoi_viz.update_url(voronoi_viz.site_db.selected_site.node_acp_id, start_date)
voronoi_viz.hud.show_node_information(voronoi_viz, voronoi_viz.site_db.selected_site.node_acp_id, start_date, end_date);
});
$('input[name="datefilter"]').on('cancel.daterangepicker', function (ev, picker) {
$(this).val('');
});
} |
JavaScript | show_node_metadata(voronoi_viz, site_id) {
//find the requested site_id in the SITE_DB
let site = voronoi_viz.site_db.all.find(x => x.node_acp_id == site_id);
voronoi_viz.hud.get_site_metadata(voronoi_viz, site)
} | show_node_metadata(voronoi_viz, site_id) {
//find the requested site_id in the SITE_DB
let site = voronoi_viz.site_db.all.find(x => x.node_acp_id == site_id);
voronoi_viz.hud.get_site_metadata(voronoi_viz, site)
} |
JavaScript | restructure_hist_data(voronoi_viz, unstr_fetched_data) {
let structured_data = []
unstr_fetched_data.forEach(item => {
let elements = item.request_data;
elements.forEach(element => {
let link_length = voronoi_viz.site_db.all_links.find(x => x.acp_id === element.id).length;
//ignoring entries that have a longer travel time than 500, so to avoid spikes in data.
if ((element.travelTime < 500) && (element.travelTime > 0)) {
structured_data.push({
'id': element.id,
'acp_id': element.id.replace('|', '_'),
"ts": element.acp_ts,
"travel_time": element.travelTime,
"normal_travel_time": element.normalTravelTime,
"speed": (link_length / element.travelTime) * voronoi_viz.tools.TO_MPH,
"normal_speed": (link_length / element.normalTravelTime) * voronoi_viz.tools.TO_MPH,
"time": element.time.slice(11, 20),
"date": element.time.slice(0, 10),
"length": link_length
})
}
})
})
return structured_data;
} | restructure_hist_data(voronoi_viz, unstr_fetched_data) {
let structured_data = []
unstr_fetched_data.forEach(item => {
let elements = item.request_data;
elements.forEach(element => {
let link_length = voronoi_viz.site_db.all_links.find(x => x.acp_id === element.id).length;
//ignoring entries that have a longer travel time than 500, so to avoid spikes in data.
if ((element.travelTime < 500) && (element.travelTime > 0)) {
structured_data.push({
'id': element.id,
'acp_id': element.id.replace('|', '_'),
"ts": element.acp_ts,
"travel_time": element.travelTime,
"normal_travel_time": element.normalTravelTime,
"speed": (link_length / element.travelTime) * voronoi_viz.tools.TO_MPH,
"normal_speed": (link_length / element.normalTravelTime) * voronoi_viz.tools.TO_MPH,
"time": element.time.slice(11, 20),
"date": element.time.slice(0, 10),
"length": link_length
})
}
})
})
return structured_data;
} |
JavaScript | restructure_to_sublists(old_list) {
let new_list = []
let new_sublist = [];
//create a separate array for used acp_ids as
//sometimes there are doubles that will create
//problems for the scatter plot.
//Doubles appear beacause some links have "-fixed"
//clones in the API, so we just avoid them.
let past_ids = [];
let temp_id = old_list[0].acp_id;
//iterate over a list of fetched readings that have
//all acp_id's in a single list
for (let i = 0; i < old_list.length; i++) {
let current_id = old_list[i].acp_id;
//ignore the doubled link readings
if (past_ids.includes(current_id)) {
continue;
}
//new acp_id incoming, start a new list
if (current_id != temp_id) {
//put the last value to past ids to ensure
//we don't have duplicates
past_ids.push(temp_id)
temp_id = current_id;
//sort the new sublist by ts
new_list.push(new_sublist.sort((a, b) => a.ts - b.ts))
new_sublist = [];
}
//push items with the same acp_id to a single list
new_sublist.push(old_list[i]);
}
//the last unique acp_id does not get pushed by itself
//since no new entry follows, so we do it here instead.
new_list.push(new_sublist.sort((a, b) => a.ts - b.ts))
//returns a list of lists containing unique acp_ids in each
return new_list;
} | restructure_to_sublists(old_list) {
let new_list = []
let new_sublist = [];
//create a separate array for used acp_ids as
//sometimes there are doubles that will create
//problems for the scatter plot.
//Doubles appear beacause some links have "-fixed"
//clones in the API, so we just avoid them.
let past_ids = [];
let temp_id = old_list[0].acp_id;
//iterate over a list of fetched readings that have
//all acp_id's in a single list
for (let i = 0; i < old_list.length; i++) {
let current_id = old_list[i].acp_id;
//ignore the doubled link readings
if (past_ids.includes(current_id)) {
continue;
}
//new acp_id incoming, start a new list
if (current_id != temp_id) {
//put the last value to past ids to ensure
//we don't have duplicates
past_ids.push(temp_id)
temp_id = current_id;
//sort the new sublist by ts
new_list.push(new_sublist.sort((a, b) => a.ts - b.ts))
new_sublist = [];
}
//push items with the same acp_id to a single list
new_sublist.push(old_list[i]);
}
//the last unique acp_id does not get pushed by itself
//since no new entry follows, so we do it here instead.
new_list.push(new_sublist.sort((a, b) => a.ts - b.ts))
//returns a list of lists containing unique acp_ids in each
return new_list;
} |
JavaScript | async await_promises(voronoi_viz, cond1, cond2) {
//console.log('waiting to resolve promises');
await voronoi_viz.hud.waitForCondition({
asked: cond1,
asnwered: cond2
})
//console.log('promises have been resolved');
} | async await_promises(voronoi_viz, cond1, cond2) {
//console.log('waiting to resolve promises');
await voronoi_viz.hud.waitForCondition({
asked: cond1,
asnwered: cond2
})
//console.log('promises have been resolved');
} |
JavaScript | function print_items(items_el, items_xml) {
log('print_items',items_xml);
// Convert to regular Array
var items = Array.prototype.slice.call(items_xml, 0);
// If the config includes a sort tag, then pre-sort the items on this tag
if (self.params.items && self.params.items.sort ) {
// Find the format of the sort tag from the item list (e.g. 'iso8601')
var sort_format = null;
for (var i=0; i<self.params.item.length; i++) {
if (self.params.item[i].tag == self.params.items.sort) {
// sort tag found in params.item, so use format
sort_format = self.params.item[i].format;
}
}
var sort_order = null;
if (self.params.items && self.params.items.sort_order) {
sort_order = self.params.items.sort_order;
}
log('print_items','sorting',self.params.items.sort, sort_format, sort_order);
// sort_compare will return a sort function based on the tag name and format
var sort_fn = sort_compare(self.params.items.sort, sort_format);
// To implement ascending (for events) and descending (for news)
// we'll either give sort_fn to Array.sort(), or create a
// function that reverses sort_fn by swapping the arguments.
if (sort_order == "ascending") {
items.sort( sort_fn );
} else {
items.sort( function(a,b) { return sort_fn(b,a); } );
}
}
// Print the sorted items
for (var i = 0; i < items.length; i++) {
print_item(items_el, items[i]);
}
} | function print_items(items_el, items_xml) {
log('print_items',items_xml);
// Convert to regular Array
var items = Array.prototype.slice.call(items_xml, 0);
// If the config includes a sort tag, then pre-sort the items on this tag
if (self.params.items && self.params.items.sort ) {
// Find the format of the sort tag from the item list (e.g. 'iso8601')
var sort_format = null;
for (var i=0; i<self.params.item.length; i++) {
if (self.params.item[i].tag == self.params.items.sort) {
// sort tag found in params.item, so use format
sort_format = self.params.item[i].format;
}
}
var sort_order = null;
if (self.params.items && self.params.items.sort_order) {
sort_order = self.params.items.sort_order;
}
log('print_items','sorting',self.params.items.sort, sort_format, sort_order);
// sort_compare will return a sort function based on the tag name and format
var sort_fn = sort_compare(self.params.items.sort, sort_format);
// To implement ascending (for events) and descending (for news)
// we'll either give sort_fn to Array.sort(), or create a
// function that reverses sort_fn by swapping the arguments.
if (sort_order == "ascending") {
items.sort( sort_fn );
} else {
items.sort( function(a,b) { return sort_fn(b,a); } );
}
}
// Print the sorted items
for (var i = 0; i < items.length; i++) {
print_item(items_el, items[i]);
}
} |
JavaScript | function safe(dirty) {
return sanitizeHtml(dirty, {
allowedTags: [ 'p', 'a', 'ul', 'ol', 'li', 'b', 'i', 'strong',
'em', 'strike', 'code', 'hr', 'br', 'div', 'table', 'thead',
'caption', 'tbody', 'tr', 'th', 'td', 'pre', 'img'],
allowedAttributes: {
'a': [ 'href' ],
'img': [ 'src' ],
}
});
} | function safe(dirty) {
return sanitizeHtml(dirty, {
allowedTags: [ 'p', 'a', 'ul', 'ol', 'li', 'b', 'i', 'strong',
'em', 'strike', 'code', 'hr', 'br', 'div', 'table', 'thead',
'caption', 'tbody', 'tr', 'th', 'td', 'pre', 'img'],
allowedAttributes: {
'a': [ 'href' ],
'img': [ 'src' ],
}
});
} |
JavaScript | function input_rss_choice(parent_el, feed_type, click_fn) {
// <tr><td><label>Feed type:</label></td>
// <td><input type="radio" name="rss_type" value="news"/>News<br/>...</td>
// </tr>
var tr = document.createElement('tr');
parent_el.appendChild(tr);
var td = document.createElement('td');
td.className = 'widget_config_property_name';
tr.appendChild(td);
var label = document.createElement('label');
td.appendChild(label);
label.title = 'RSS feed type. Default (news) sorts on pubDate. Events sorts on ev:startdate';
label.innerHTML = 'Feed type:';
td = document.createElement('td');
td.className = 'widget_config_property_value';
tr.appendChild(td);
add_radio_button(td, 'rss_type', 'news', 'News', feed_type, click_fn);
add_radio_button(td, 'rss_type', 'events', 'Events', feed_type, click_fn);
add_radio_button(td, 'rss_type', 'talks.cam', 'Talks.cam', feed_type, click_fn);
add_radio_button(td, 'rss_type', 'custom', 'Custom', feed_type, click_fn);
} | function input_rss_choice(parent_el, feed_type, click_fn) {
// <tr><td><label>Feed type:</label></td>
// <td><input type="radio" name="rss_type" value="news"/>News<br/>...</td>
// </tr>
var tr = document.createElement('tr');
parent_el.appendChild(tr);
var td = document.createElement('td');
td.className = 'widget_config_property_name';
tr.appendChild(td);
var label = document.createElement('label');
td.appendChild(label);
label.title = 'RSS feed type. Default (news) sorts on pubDate. Events sorts on ev:startdate';
label.innerHTML = 'Feed type:';
td = document.createElement('td');
td.className = 'widget_config_property_value';
tr.appendChild(td);
add_radio_button(td, 'rss_type', 'news', 'News', feed_type, click_fn);
add_radio_button(td, 'rss_type', 'events', 'Events', feed_type, click_fn);
add_radio_button(td, 'rss_type', 'talks.cam', 'Talks.cam', feed_type, click_fn);
add_radio_button(td, 'rss_type', 'custom', 'Custom', feed_type, click_fn);
} |
JavaScript | function input_rss_custom(custom_div, params) {
// clear out any existing content
while (custom_div.firstChild) {
custom_div.removeChild(custom_div.firstChild);
}
// "title" "style"
var title_style_result = widget_config.input( custom_div,
'string',
{ text: 'Title style:',
title: 'The CSS style properties to apply to the main RSS feed title'
},
params.title ? params.title.style : DEFAULT_PARAMS[feed_type].title.style);
// "items" "tag"
var items_tag_result = widget_config.input( custom_div,
'string',
{ text: 'Items tag:',
title: 'The RSS XML tag that contains the items, usually "items"'
},
params.items ? params.items.tag : DEFAULT_PARAMS[feed_type].items.tag);
// "items" "sort"
var items_sort_result = widget_config.input( custom_div,
'string',
{ text: 'Item sort tag:',
title: 'The RSS XML tag that contains the item property to sort on, usually "pubDate"'
},
params.items ? params.items.sort : DEFAULT_PARAMS[feed_type].items.sort);
// "items" "sort_order"
var items_sort_order_result = widget_config.input( custom_div,
'select',
{ text: 'Item sort order:',
title: 'e.g. ascending for dates means earliest at top of list (useful for events)',
options: [ { value: 'descending', text: 'Descending' },
{ value: 'ascending', text: 'Ascending' }
]
},
params.items ? params.items.sort_order : DEFAULT_PARAMS[feed_type].items.sort_order);
// "item" textarea JSON input
var item_result = widget_config.input( custom_div,
'string',
{ text: 'Item format:',
title: 'Input your item format definition',
format: 'textarea'
},
// pretty-print JSON into input textarea
params.item ? JSON.stringify(params.item,null,2) : JSON.stringify(DEFAULT_PARAMS[feed_type].item,null,2));
var value_fn = function () {
var params = { title: { style: title_style_result.value() },
items: { tag: items_tag_result.value(),
sort: items_sort_result.value(),
sort_order: items_sort_order_result.value()
},
item: JSON.parse(item_result.value())
};
return params;
}
var valid_fn = function () {
try {
JSON.parse(item_result.value());
}
catch (e) {
log('input_rss_custom','valid_fn','item format JSON error');
item_result.element.style['background-color'] = '#ff8888';
return false;
}
log('input_rss_custom','valid_fn','item JSON format OK');
return true;
}
return { value: value_fn,
valid: valid_fn
};
}// end input_rss_custom() | function input_rss_custom(custom_div, params) {
// clear out any existing content
while (custom_div.firstChild) {
custom_div.removeChild(custom_div.firstChild);
}
// "title" "style"
var title_style_result = widget_config.input( custom_div,
'string',
{ text: 'Title style:',
title: 'The CSS style properties to apply to the main RSS feed title'
},
params.title ? params.title.style : DEFAULT_PARAMS[feed_type].title.style);
// "items" "tag"
var items_tag_result = widget_config.input( custom_div,
'string',
{ text: 'Items tag:',
title: 'The RSS XML tag that contains the items, usually "items"'
},
params.items ? params.items.tag : DEFAULT_PARAMS[feed_type].items.tag);
// "items" "sort"
var items_sort_result = widget_config.input( custom_div,
'string',
{ text: 'Item sort tag:',
title: 'The RSS XML tag that contains the item property to sort on, usually "pubDate"'
},
params.items ? params.items.sort : DEFAULT_PARAMS[feed_type].items.sort);
// "items" "sort_order"
var items_sort_order_result = widget_config.input( custom_div,
'select',
{ text: 'Item sort order:',
title: 'e.g. ascending for dates means earliest at top of list (useful for events)',
options: [ { value: 'descending', text: 'Descending' },
{ value: 'ascending', text: 'Ascending' }
]
},
params.items ? params.items.sort_order : DEFAULT_PARAMS[feed_type].items.sort_order);
// "item" textarea JSON input
var item_result = widget_config.input( custom_div,
'string',
{ text: 'Item format:',
title: 'Input your item format definition',
format: 'textarea'
},
// pretty-print JSON into input textarea
params.item ? JSON.stringify(params.item,null,2) : JSON.stringify(DEFAULT_PARAMS[feed_type].item,null,2));
var value_fn = function () {
var params = { title: { style: title_style_result.value() },
items: { tag: items_tag_result.value(),
sort: items_sort_result.value(),
sort_order: items_sort_order_result.value()
},
item: JSON.parse(item_result.value())
};
return params;
}
var valid_fn = function () {
try {
JSON.parse(item_result.value());
}
catch (e) {
log('input_rss_custom','valid_fn','item format JSON error');
item_result.element.style['background-color'] = '#ff8888';
return false;
}
log('input_rss_custom','valid_fn','item JSON format OK');
return true;
}
return { value: value_fn,
valid: valid_fn
};
}// end input_rss_custom() |
JavaScript | function add_radio_button(parent_el, name, value, text, value_selected, click_fn) {
var label = document.createElement('label');
parent_el.appendChild(label);
var input = document.createElement('input');
input.style['vertical-align'] = 'middle';
input.onclick = function () { return click_fn(value);};
label.appendChild(input);
input.type = 'radio';
input.name = name;
input.value = value;
if (value == value_selected) {
input.checked = 'checked';
}
label.appendChild(document.createTextNode(text));
parent_el.appendChild(document.createElement('br'));
} | function add_radio_button(parent_el, name, value, text, value_selected, click_fn) {
var label = document.createElement('label');
parent_el.appendChild(label);
var input = document.createElement('input');
input.style['vertical-align'] = 'middle';
input.onclick = function () { return click_fn(value);};
label.appendChild(input);
input.type = 'radio';
input.name = name;
input.value = value;
if (value == value_selected) {
input.checked = 'checked';
}
label.appendChild(document.createTextNode(text));
parent_el.appendChild(document.createElement('br'));
} |
JavaScript | function Weather(widget_id) {
'use strict';
//var DEBUG = ' weather_log';
var self = this;
self.widget_id = widget_id;
var WEATHER_OPTIONS = [ { value: '310042', text: 'Cambridge' },
{ value: '324249', text: 'Ely' },
{ value: '351524', text: 'Fulbourn' },
{ value: '324061', text: 'Huntingdon' },
{ value: '310105', text: 'Luton' },
{ value: '310120', text: 'Peterborough' },
{ value: '353656', text: 'Stansted' },
{ value: '353330', text: 'St. Neots' }
];
var refresh_timer;
this.display = function(config, params) {
this.config = config;
this.params = params;
var container = document.getElementById(self.config.container_id);
this.widget_error = document.createElement('h1');
this.widget_error.classList.add('widget_error');
this.widget_error.textContent = 'No connection - retrying';
container.appendChild(self.widget_error);
this.content_area = document.createElement('div');
this.content_area.classList.add('content_area');
container.appendChild(self.content_area);
this.do_load();
};
/*this.reload = function() {
this.log("Running StationBoard.reload", this.container);
this.do_load();
}*/
this.do_load = function () {
self.log(self.widget_id, 'Running Weather.do_load');
var url = '/smartpanel/weather/2?location=' + this.params.location;
self.log(self.widget_id, 'do_load URI', url);
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.onreadystatechange = function() {
if(xhr.readyState === XMLHttpRequest.DONE) {
if (xhr.status !== 200) {
self.log(self.widget_id, 'Error loading weather', xhr.status, xhr.statusText);
self.widget_error.style.display = 'block';
}
else {
self.content_area.innerHTML = xhr.responseText;
self.widget_error.style.display = 'none';
}
refresh_timer = setTimeout(function () { self.do_load(); }, 60000);
}
};
xhr.send();
self.log(self.widget_id,'do_load done');
};
this.close = function () {
self.log('closing Weather widget');
if (refresh_timer) {
self.log('clearTimeout(refresh_timer)');
window.clearTimeout(refresh_timer);
}
};
this.log = function() {
if ((typeof DEBUG !== 'undefined') && DEBUG.indexOf('weather_log') >= 0) {
console.log.apply(console, arguments);
}
};
// ************************************************************************************
// ***************** Widget Configuration ********************************************
// ************************************************************************************
//
// THIS IS THE METHOD CALLED BY THE WIDGET FRAMEWORK TO CONFIGURE THIS WIDGET
//
// config:
// container_id
// static_url
// height
// width
// settings:
// SMARTPANEL_TRANSPORT_API
//
// params:
// ( as needed by the active widget )
//
// returns
// { valid: function () -> true,
// value: function () -> params as provided by user,
// config: function () -> { title: suitable title for config layout }
// }
//
this.configure = function (config, params) {
var widget_config = new WidgetConfig(config);
var config_div = document.getElementById(config.container_id);
// Empty the 'container' div (i.e. remove loading GIF or prior content)
while (config_div.firstChild) {
config_div.removeChild(config_div.firstChild);
}
config_div.style.display = 'block';
// Create HTML for configuration form
//
var config_title = document.createElement('h1');
config_title.innerHTML = 'Configure Weather';
config_div.appendChild(config_title);
var config_form = document.createElement('form');
var input_result = input_weather(widget_config, config_form, params);
config_div.appendChild(config_form);
return input_result;
} // end this.configure()
// Input the Weather parameters
function input_weather(widget_config, parent_el, params) {
var config_table = document.createElement('table');
var config_tbody = document.createElement('tbody');
// Location select
//
var location_result = widget_config.input( parent_el,
'select',
{ text: 'Location:',
title: 'Choose your weather location from the dropdown',
options: WEATHER_OPTIONS
},
params.location
);
config_table.appendChild(config_tbody);
// append this input table to the DOM object originally given in parent_el
parent_el.appendChild(config_table);
// value() is the function for this input element that returns its value
var value_fn = function () {
var config_params = {};
// location
config_params.location = location_result.value();
self.log(self.widget_id,'returning params:',config_params);
return config_params;
};
var config_fn = function () {
var weather_text = 'Location';
var weather_value = location_result.value();
for (var i=0; i<WEATHER_OPTIONS.length; i++) {
if (WEATHER_OPTIONS[i].value === weather_value) {
weather_text = WEATHER_OPTIONS[i].text;
break;
}
}
return { title: weather_text + " Weather" };
};
return { valid: function () { return true; }, //debug - still to be implemented,
config: config_fn,
value: value_fn };
}// end input_weather()
self.log(self.widget_id, 'Instantiated Weather');
} | function Weather(widget_id) {
'use strict';
//var DEBUG = ' weather_log';
var self = this;
self.widget_id = widget_id;
var WEATHER_OPTIONS = [ { value: '310042', text: 'Cambridge' },
{ value: '324249', text: 'Ely' },
{ value: '351524', text: 'Fulbourn' },
{ value: '324061', text: 'Huntingdon' },
{ value: '310105', text: 'Luton' },
{ value: '310120', text: 'Peterborough' },
{ value: '353656', text: 'Stansted' },
{ value: '353330', text: 'St. Neots' }
];
var refresh_timer;
this.display = function(config, params) {
this.config = config;
this.params = params;
var container = document.getElementById(self.config.container_id);
this.widget_error = document.createElement('h1');
this.widget_error.classList.add('widget_error');
this.widget_error.textContent = 'No connection - retrying';
container.appendChild(self.widget_error);
this.content_area = document.createElement('div');
this.content_area.classList.add('content_area');
container.appendChild(self.content_area);
this.do_load();
};
/*this.reload = function() {
this.log("Running StationBoard.reload", this.container);
this.do_load();
}*/
this.do_load = function () {
self.log(self.widget_id, 'Running Weather.do_load');
var url = '/smartpanel/weather/2?location=' + this.params.location;
self.log(self.widget_id, 'do_load URI', url);
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.onreadystatechange = function() {
if(xhr.readyState === XMLHttpRequest.DONE) {
if (xhr.status !== 200) {
self.log(self.widget_id, 'Error loading weather', xhr.status, xhr.statusText);
self.widget_error.style.display = 'block';
}
else {
self.content_area.innerHTML = xhr.responseText;
self.widget_error.style.display = 'none';
}
refresh_timer = setTimeout(function () { self.do_load(); }, 60000);
}
};
xhr.send();
self.log(self.widget_id,'do_load done');
};
this.close = function () {
self.log('closing Weather widget');
if (refresh_timer) {
self.log('clearTimeout(refresh_timer)');
window.clearTimeout(refresh_timer);
}
};
this.log = function() {
if ((typeof DEBUG !== 'undefined') && DEBUG.indexOf('weather_log') >= 0) {
console.log.apply(console, arguments);
}
};
// ************************************************************************************
// ***************** Widget Configuration ********************************************
// ************************************************************************************
//
// THIS IS THE METHOD CALLED BY THE WIDGET FRAMEWORK TO CONFIGURE THIS WIDGET
//
// config:
// container_id
// static_url
// height
// width
// settings:
// SMARTPANEL_TRANSPORT_API
//
// params:
// ( as needed by the active widget )
//
// returns
// { valid: function () -> true,
// value: function () -> params as provided by user,
// config: function () -> { title: suitable title for config layout }
// }
//
this.configure = function (config, params) {
var widget_config = new WidgetConfig(config);
var config_div = document.getElementById(config.container_id);
// Empty the 'container' div (i.e. remove loading GIF or prior content)
while (config_div.firstChild) {
config_div.removeChild(config_div.firstChild);
}
config_div.style.display = 'block';
// Create HTML for configuration form
//
var config_title = document.createElement('h1');
config_title.innerHTML = 'Configure Weather';
config_div.appendChild(config_title);
var config_form = document.createElement('form');
var input_result = input_weather(widget_config, config_form, params);
config_div.appendChild(config_form);
return input_result;
} // end this.configure()
// Input the Weather parameters
function input_weather(widget_config, parent_el, params) {
var config_table = document.createElement('table');
var config_tbody = document.createElement('tbody');
// Location select
//
var location_result = widget_config.input( parent_el,
'select',
{ text: 'Location:',
title: 'Choose your weather location from the dropdown',
options: WEATHER_OPTIONS
},
params.location
);
config_table.appendChild(config_tbody);
// append this input table to the DOM object originally given in parent_el
parent_el.appendChild(config_table);
// value() is the function for this input element that returns its value
var value_fn = function () {
var config_params = {};
// location
config_params.location = location_result.value();
self.log(self.widget_id,'returning params:',config_params);
return config_params;
};
var config_fn = function () {
var weather_text = 'Location';
var weather_value = location_result.value();
for (var i=0; i<WEATHER_OPTIONS.length; i++) {
if (WEATHER_OPTIONS[i].value === weather_value) {
weather_text = WEATHER_OPTIONS[i].text;
break;
}
}
return { title: weather_text + " Weather" };
};
return { valid: function () { return true; }, //debug - still to be implemented,
config: config_fn,
value: value_fn };
}// end input_weather()
self.log(self.widget_id, 'Instantiated Weather');
} |
JavaScript | function input_iframe_area(widget_config, parent_el, params) {
self.log(widget_id,'input_iframe_area with',params);
// Add some guide text
var config_info1 = document.createElement('p');
var config_info_text = "This widget displays a web page of your choice.";
config_info_text += " Enter the selected URL, e.g. http://people.ds.cam.ac.uk/jw35/.";
config_info_text += " Note the page must be happy showing within an 'iframe' on the smartpanel.";
config_info1.appendChild(document.createTextNode(config_info_text));
parent_el.appendChild(config_info1);
var config_info2 = document.createElement('p');
config_info_text = "'Scale' shrinks or magnifies the web page, e.g. 0.5 will shrink to half size, 2 will magnify.";
config_info2.appendChild(document.createTextNode(config_info_text));
parent_el.appendChild(config_info2);
var config_info3 = document.createElement('p');
config_info_text = "Offset X and Y are used to 'shift' the iframe view to an area of the source page."+
"'Offset X' shifts the iframe to the right (relative to the page), and similarly 'Offset Y' shifts the iframe downwards, e.g."+
"20,20 will move the top-left corner of the iframe diagonally into the web page by 20px";
config_info3.appendChild(document.createTextNode(config_info_text));
parent_el.appendChild(config_info3);
var config_table = document.createElement('table');
config_table.className = 'config_input_iframe_area';
parent_el.appendChild(config_table);
var config_tbody = document.createElement('tbody');
config_table.appendChild(config_tbody);
// Each config_input(...) will return a .value() callback function for the input data
// URL
//
var url_result = widget_config.input( config_tbody,
'string',
{ text: 'Website URL:',
title: 'The web address of the page you want to display, e.g. http://people.ds.cam.ac.uk/jw35/'
},
params.url);
// SCALE
//
var scale_result = widget_config.input( config_tbody,
'number',
{ text: 'Scale:',
title: 'E.g. 0.5 will display page at half normal size, 2 will magnify to double'
},
params.scale);
// OFFSETX
//
var offsetx_result = widget_config.input( config_tbody,
'number',
{ text: 'X Offset:',
title: 'E.g. 300 will shift the iframe right into the page by 300px'
},
params.offsetx);
// OFFSETY
//
var offsety_result = widget_config.input( config_tbody,
'number',
{ text: 'Y Offset:',
title: 'E.g. 100 will shift the iframe down the page by 100px'
},
params.offsety);
// value() is the function for this input element that returns its value
var value_fn = function () {
var config_params = {};
// url
config_params.url = url_result.value();
config_params.scale = scale_result.value();
config_params.offsetx = offsetx_result.value();
config_params.offsety = offsety_result.value();
self.log(self.widget_id,'input_iframe_area returning params:',config_params);
return config_params;
}
var config_fn = function () {
return { title: url_result.value() };
};
return { valid: function () { return true; }, //debug - still to be implemented,
config: config_fn,
value: value_fn };
}// end input_stop-timetable() | function input_iframe_area(widget_config, parent_el, params) {
self.log(widget_id,'input_iframe_area with',params);
// Add some guide text
var config_info1 = document.createElement('p');
var config_info_text = "This widget displays a web page of your choice.";
config_info_text += " Enter the selected URL, e.g. http://people.ds.cam.ac.uk/jw35/.";
config_info_text += " Note the page must be happy showing within an 'iframe' on the smartpanel.";
config_info1.appendChild(document.createTextNode(config_info_text));
parent_el.appendChild(config_info1);
var config_info2 = document.createElement('p');
config_info_text = "'Scale' shrinks or magnifies the web page, e.g. 0.5 will shrink to half size, 2 will magnify.";
config_info2.appendChild(document.createTextNode(config_info_text));
parent_el.appendChild(config_info2);
var config_info3 = document.createElement('p');
config_info_text = "Offset X and Y are used to 'shift' the iframe view to an area of the source page."+
"'Offset X' shifts the iframe to the right (relative to the page), and similarly 'Offset Y' shifts the iframe downwards, e.g."+
"20,20 will move the top-left corner of the iframe diagonally into the web page by 20px";
config_info3.appendChild(document.createTextNode(config_info_text));
parent_el.appendChild(config_info3);
var config_table = document.createElement('table');
config_table.className = 'config_input_iframe_area';
parent_el.appendChild(config_table);
var config_tbody = document.createElement('tbody');
config_table.appendChild(config_tbody);
// Each config_input(...) will return a .value() callback function for the input data
// URL
//
var url_result = widget_config.input( config_tbody,
'string',
{ text: 'Website URL:',
title: 'The web address of the page you want to display, e.g. http://people.ds.cam.ac.uk/jw35/'
},
params.url);
// SCALE
//
var scale_result = widget_config.input( config_tbody,
'number',
{ text: 'Scale:',
title: 'E.g. 0.5 will display page at half normal size, 2 will magnify to double'
},
params.scale);
// OFFSETX
//
var offsetx_result = widget_config.input( config_tbody,
'number',
{ text: 'X Offset:',
title: 'E.g. 300 will shift the iframe right into the page by 300px'
},
params.offsetx);
// OFFSETY
//
var offsety_result = widget_config.input( config_tbody,
'number',
{ text: 'Y Offset:',
title: 'E.g. 100 will shift the iframe down the page by 100px'
},
params.offsety);
// value() is the function for this input element that returns its value
var value_fn = function () {
var config_params = {};
// url
config_params.url = url_result.value();
config_params.scale = scale_result.value();
config_params.offsetx = offsetx_result.value();
config_params.offsety = offsety_result.value();
self.log(self.widget_id,'input_iframe_area returning params:',config_params);
return config_params;
}
var config_fn = function () {
return { title: url_result.value() };
};
return { valid: function () { return true; }, //debug - still to be implemented,
config: config_fn,
value: value_fn };
}// end input_stop-timetable() |
JavaScript | function load_data() {
var headers = {
Authorization: 'Token ' + self.config.settings.SMARTPANEL_API_TOKEN
};
$.when(
$.get({
url: self.config.settings.SMARTPANEL_API_ENDPOINT + 'traffic/btjourney/site/',
headers: headers,
dataType: 'json',
}),
$.get({
url: self.config.settings.SMARTPANEL_API_ENDPOINT + 'traffic/btjourney/link/',
headers: headers,
dataType: 'json',
}),
$.get({
url: self.config.settings.SMARTPANEL_API_ENDPOINT + 'traffic/btjourney/route/',
headers: headers,
dataType: 'json',
}),
$.get({
url: self.config.settings.SMARTPANEL_API_ENDPOINT + 'traffic/btjourney/latest/',
headers: headers,
dataType: 'json',
})
)
.done(function(site_response, link_response, route_response, journey_response) {
var sites = site_response[0].site_list;
var links = link_response[0].link_list.concat(route_response[0].route_list);
var journeys = journey_response[0].request_data;
draw_sites(sites);
process_journeys(journeys, links, sites);
// The underlying API updates journey times every 5 minutes.
// Schedule an update 5 and-a-bit minutes from the last
// timestamp if that looks believable, and in a minute
// otherwise.
var timestamp = journey_response[0].ts * 1000;
var now = Date.now();
var delta = timestamp - now + (5.25*60000);
if (delta <= 0 || delta > 10*60000) {
delta = 60000;
}
setTimeout(load_data, delta);
})
// If anything went wrong, try again in a minute
.fail(function(){
console.log('API call failed - default reschedule');
setTimeout(load_data, 60000);
});
} | function load_data() {
var headers = {
Authorization: 'Token ' + self.config.settings.SMARTPANEL_API_TOKEN
};
$.when(
$.get({
url: self.config.settings.SMARTPANEL_API_ENDPOINT + 'traffic/btjourney/site/',
headers: headers,
dataType: 'json',
}),
$.get({
url: self.config.settings.SMARTPANEL_API_ENDPOINT + 'traffic/btjourney/link/',
headers: headers,
dataType: 'json',
}),
$.get({
url: self.config.settings.SMARTPANEL_API_ENDPOINT + 'traffic/btjourney/route/',
headers: headers,
dataType: 'json',
}),
$.get({
url: self.config.settings.SMARTPANEL_API_ENDPOINT + 'traffic/btjourney/latest/',
headers: headers,
dataType: 'json',
})
)
.done(function(site_response, link_response, route_response, journey_response) {
var sites = site_response[0].site_list;
var links = link_response[0].link_list.concat(route_response[0].route_list);
var journeys = journey_response[0].request_data;
draw_sites(sites);
process_journeys(journeys, links, sites);
// The underlying API updates journey times every 5 minutes.
// Schedule an update 5 and-a-bit minutes from the last
// timestamp if that looks believable, and in a minute
// otherwise.
var timestamp = journey_response[0].ts * 1000;
var now = Date.now();
var delta = timestamp - now + (5.25*60000);
if (delta <= 0 || delta > 10*60000) {
delta = 60000;
}
setTimeout(load_data, delta);
})
// If anything went wrong, try again in a minute
.fail(function(){
console.log('API call failed - default reschedule');
setTimeout(load_data, 60000);
});
} |
JavaScript | function draw_sites(sites) {
// Add markers for new sites
for (var i = 0; i < sites.length; ++i) {
var site = sites[i];
if (site_index[site.id] === undefined) {
var marker = L.circleMarker([site.location.lat, site.location.lng], SITE_OPTIONS)
.addTo(sites_layer);
marker.properties = { 'site': site };
site_index[site.id] = marker;
}
}
// Remove markers for sites that have gone away
for (var site_id in site_index) {
if (find_object(sites, site_id) === undefined) {
site_index[site_id].delete();
delete site_index[site.id];
}
}
} | function draw_sites(sites) {
// Add markers for new sites
for (var i = 0; i < sites.length; ++i) {
var site = sites[i];
if (site_index[site.id] === undefined) {
var marker = L.circleMarker([site.location.lat, site.location.lng], SITE_OPTIONS)
.addTo(sites_layer);
marker.properties = { 'site': site };
site_index[site.id] = marker;
}
}
// Remove markers for sites that have gone away
for (var site_id in site_index) {
if (find_object(sites, site_id) === undefined) {
site_index[site_id].delete();
delete site_index[site.id];
}
}
} |
JavaScript | function process_journeys(journeys, links, sites) {
for (var i = 0; i < journeys.length; ++i) {
var journey = journeys[i];
// Try to get the Leaflet polyline for the coresponding route
var line = link_index[journey.id];
// Add a polyline to the map if missing
if (line === undefined) {
line = draw_line(journey.id, links, sites);
}
// The addition could have failed
if (line !== undefined) {
line.properties.journey = journey;
}
}
// Remove polylines for links without journeys
for (var link_id in link_index) {
if (find_object(journeys, link_id) === undefined) {
link_index[link_id].delete();
delete link_index[link_id];
}
}
update_line_colours();
} | function process_journeys(journeys, links, sites) {
for (var i = 0; i < journeys.length; ++i) {
var journey = journeys[i];
// Try to get the Leaflet polyline for the coresponding route
var line = link_index[journey.id];
// Add a polyline to the map if missing
if (line === undefined) {
line = draw_line(journey.id, links, sites);
}
// The addition could have failed
if (line !== undefined) {
line.properties.journey = journey;
}
}
// Remove polylines for links without journeys
for (var link_id in link_index) {
if (find_object(journeys, link_id) === undefined) {
link_index[link_id].delete();
delete link_index[link_id];
}
}
update_line_colours();
} |
JavaScript | function draw_line(link_id, links, sites) {
var line = undefined;
var link = find_object(links, link_id);
if (link === undefined) {
console.log('Can\'t find link with id ' + link_id);
}
else {
var layer = link.sites.length <= 2 ? links_layer : routes_layer;
// Accumulate points
var points = [];
for (var j = 0; j < link.sites.length; ++j) {
var site = find_object(sites, link.sites[j]);
if (site) {
points.push([site.location.lat, site.location.lng]);
}
}
line = L.polyline(points, NORMAL_LINE)
.setStyle({color: NORMAL_COLOUR})
.addTo(layer);
line.properties = { 'link': link };
// Remember the polyline for the future
link_index[link_id] = line;
}
return line;
} | function draw_line(link_id, links, sites) {
var line = undefined;
var link = find_object(links, link_id);
if (link === undefined) {
console.log('Can\'t find link with id ' + link_id);
}
else {
var layer = link.sites.length <= 2 ? links_layer : routes_layer;
// Accumulate points
var points = [];
for (var j = 0; j < link.sites.length; ++j) {
var site = find_object(sites, link.sites[j]);
if (site) {
points.push([site.location.lat, site.location.lng]);
}
}
line = L.polyline(points, NORMAL_LINE)
.setStyle({color: NORMAL_COLOUR})
.addTo(layer);
line.properties = { 'link': link };
// Remember the polyline for the future
link_index[link_id] = line;
}
return line;
} |
JavaScript | function update_actual_speed(line) {
var journey = line.properties.journey;
var link = line.properties.link;
var time = journey.travelTime;
var speed = (link.length / time) * TO_MPH;
var choice;
if (time === null) {
choice = BROKEN_COLOUR;
}
else if (speed < 5) {
choice = VERY_SLOW_COLOUR;
}
else if (speed < 10) {
choice = SLOW_COLOUR;
}
else if (speed < 20) {
choice = MEDIUM_COLOUR;
}
else {
choice = FAST_COLOUR;
}
line.setStyle({color: choice});
} | function update_actual_speed(line) {
var journey = line.properties.journey;
var link = line.properties.link;
var time = journey.travelTime;
var speed = (link.length / time) * TO_MPH;
var choice;
if (time === null) {
choice = BROKEN_COLOUR;
}
else if (speed < 5) {
choice = VERY_SLOW_COLOUR;
}
else if (speed < 10) {
choice = SLOW_COLOUR;
}
else if (speed < 20) {
choice = MEDIUM_COLOUR;
}
else {
choice = FAST_COLOUR;
}
line.setStyle({color: choice});
} |
JavaScript | find_neighbors(voronoi_viz){ //data is in all_links
this.neighbors = [];
let tempTravelTime, normalTravelTime, travelTime; //temp
//iterate over all of the links
for (let i = 0; i < voronoi_viz.site_db.all_links.length; i++) {
//check if the source site matches our initial node
if (this.node_id == voronoi_viz.site_db.all_links[i].sites[0]) { //from this id
//try obtaining travel time and normal travel time. if travel time is undefined, select normal travel time instead.
try {
tempTravelTime = voronoi_viz.site_db.all_journeys.find(x => x.id === voronoi_viz.site_db.all_links[i].id).travelTime;
normalTravelTime = voronoi_viz.site_db.all_journeys.find(x => x.id === voronoi_viz.site_db.all_links[i].id).normalTravelTime;
travelTime = tempTravelTime == undefined || null ? normalTravelTime : tempTravelTime;
} catch (err) {
travelTime = undefined;
normalTravelTime = undefined;
}
//console.log(tempTravelTime, travelTime);
//find a link that has the same to/from nodes to acquire a unique id
let link = voronoi_viz.site_db.find_links(voronoi_viz, this.node_id, voronoi_viz.site_db.all_links[i].sites[1]);//to this id
this.neighbors.push({
"links": {
"out": link.out,
"in": link.in
},
"name": voronoi_viz.site_db.all_links[i].name,
"id": voronoi_viz.site_db.all_links[i].sites[1], //to this id
"site": this.get_name_from_id(voronoi_viz, voronoi_viz.site_db.all_links[i].sites[1]),
"travelTime": travelTime,
"normalTravelTime": normalTravelTime,
"dist": voronoi_viz.site_db.all_links[i].length
});
}
}
} | find_neighbors(voronoi_viz){ //data is in all_links
this.neighbors = [];
let tempTravelTime, normalTravelTime, travelTime; //temp
//iterate over all of the links
for (let i = 0; i < voronoi_viz.site_db.all_links.length; i++) {
//check if the source site matches our initial node
if (this.node_id == voronoi_viz.site_db.all_links[i].sites[0]) { //from this id
//try obtaining travel time and normal travel time. if travel time is undefined, select normal travel time instead.
try {
tempTravelTime = voronoi_viz.site_db.all_journeys.find(x => x.id === voronoi_viz.site_db.all_links[i].id).travelTime;
normalTravelTime = voronoi_viz.site_db.all_journeys.find(x => x.id === voronoi_viz.site_db.all_links[i].id).normalTravelTime;
travelTime = tempTravelTime == undefined || null ? normalTravelTime : tempTravelTime;
} catch (err) {
travelTime = undefined;
normalTravelTime = undefined;
}
//console.log(tempTravelTime, travelTime);
//find a link that has the same to/from nodes to acquire a unique id
let link = voronoi_viz.site_db.find_links(voronoi_viz, this.node_id, voronoi_viz.site_db.all_links[i].sites[1]);//to this id
this.neighbors.push({
"links": {
"out": link.out,
"in": link.in
},
"name": voronoi_viz.site_db.all_links[i].name,
"id": voronoi_viz.site_db.all_links[i].sites[1], //to this id
"site": this.get_name_from_id(voronoi_viz, voronoi_viz.site_db.all_links[i].sites[1]),
"travelTime": travelTime,
"normalTravelTime": normalTravelTime,
"dist": voronoi_viz.site_db.all_links[i].length
});
}
}
} |
JavaScript | compute_travel_time(voronoi_viz) {
let avg = [];
let sum = 0;
//iterate over all of the neighours
for (let i = 0; i < this.neighbors.length; i++) {
let link = this.neighbors[i].links.out.id;
//iterate over all of the journeys that exist within neighours
for (let u = 0; u < voronoi_viz.site_db.all_journeys.length; u++) {
if (link == voronoi_viz.site_db.all_journeys[u].id) {
avg.push(voronoi_viz.site_db.all_journeys[u].travelTime);
}
}
}
for (let i = 0; i < avg.length; i++) {
sum += avg[i];
}
this.travelTime = sum / avg.length;
} | compute_travel_time(voronoi_viz) {
let avg = [];
let sum = 0;
//iterate over all of the neighours
for (let i = 0; i < this.neighbors.length; i++) {
let link = this.neighbors[i].links.out.id;
//iterate over all of the journeys that exist within neighours
for (let u = 0; u < voronoi_viz.site_db.all_journeys.length; u++) {
if (link == voronoi_viz.site_db.all_journeys[u].id) {
avg.push(voronoi_viz.site_db.all_journeys[u].travelTime);
}
}
}
for (let i = 0; i < avg.length; i++) {
sum += avg[i];
}
this.travelTime = sum / avg.length;
} |
JavaScript | compute_travel_speed(voronoi_viz) {
let currentAverage = [];
let historicalAverage = [];
//iterate over all of the neighours
for (let i = 0; i < this.neighbors.length; i++) {
let link = this.neighbors[i].links.out.id;
let dist = this.neighbors[i].dist;
//iterate over all of the journeys that exist within neighours
for (let u = 0; u < voronoi_viz.site_db.all_journeys.length; u++) {
if (link == voronoi_viz.site_db.all_journeys[u].id) {
let travelTime = voronoi_viz.site_db.all_journeys[u].travelTime;
let historicalTime = voronoi_viz.site_db.all_journeys[u].normalTravelTime;
let currentSpeed = (dist / travelTime) * voronoi_viz.tools.TO_MPH;
let historicalSpeed = (dist / historicalTime) * voronoi_viz.tools.TO_MPH;
if (currentSpeed == Infinity || historicalSpeed == Infinity) {
continue;
}
historicalAverage.push(historicalSpeed);
currentAverage.push(currentSpeed);
}
}
}
if (historicalAverage.length > 0) {
let historicalSum = historicalAverage.reduce((previous, current) => current += previous);
this.historicalSpeed = historicalSum / historicalAverage.length;
}
if (currentAverage.length > 0) {
let currentSum = currentAverage.reduce((previous, current) => current += previous);
this.travelSpeed = currentSum / currentAverage.length;
}
//if this.travelSpeed or this.historicalSpeed are null, we get 0 and thus fill in the
//cell as the neutral yellow-orange color
this.speedDeviation = this.travelSpeed - this.historicalSpeed;
} | compute_travel_speed(voronoi_viz) {
let currentAverage = [];
let historicalAverage = [];
//iterate over all of the neighours
for (let i = 0; i < this.neighbors.length; i++) {
let link = this.neighbors[i].links.out.id;
let dist = this.neighbors[i].dist;
//iterate over all of the journeys that exist within neighours
for (let u = 0; u < voronoi_viz.site_db.all_journeys.length; u++) {
if (link == voronoi_viz.site_db.all_journeys[u].id) {
let travelTime = voronoi_viz.site_db.all_journeys[u].travelTime;
let historicalTime = voronoi_viz.site_db.all_journeys[u].normalTravelTime;
let currentSpeed = (dist / travelTime) * voronoi_viz.tools.TO_MPH;
let historicalSpeed = (dist / historicalTime) * voronoi_viz.tools.TO_MPH;
if (currentSpeed == Infinity || historicalSpeed == Infinity) {
continue;
}
historicalAverage.push(historicalSpeed);
currentAverage.push(currentSpeed);
}
}
}
if (historicalAverage.length > 0) {
let historicalSum = historicalAverage.reduce((previous, current) => current += previous);
this.historicalSpeed = historicalSum / historicalAverage.length;
}
if (currentAverage.length > 0) {
let currentSum = currentAverage.reduce((previous, current) => current += previous);
this.travelSpeed = currentSum / currentAverage.length;
}
//if this.travelSpeed or this.historicalSpeed are null, we get 0 and thus fill in the
//cell as the neutral yellow-orange color
this.speedDeviation = this.travelSpeed - this.historicalSpeed;
} |
JavaScript | function input_google_map_list(widget_config, parent_el, current_maps) {
self.log(widget_id,'input_map_list called with', current_maps);
var row = document.createElement('tr');
parent_el.appendChild(row);
// create TD to hold 'name' prompt for field
var td_name = document.createElement('td');
td_name.className = 'widget_config_property_name';
var label = document.createElement('label');
//label.htmlFor = id;
label.title = 'Configure one or more maps';
label.appendChild(document.createTextNode('Traffic Maps:'));
td_name.appendChild(label);
row.appendChild(td_name);
// create TD to hold 'value' destination_list
var td_value = document.createElement('td');
td_value.className = 'widget_config_property_value';
row.appendChild(td_value);
var maps_table = document.createElement('table');
maps_table.className = 'config_traffic_maps_table';
maps_table.style['border-collapse'] = 'separate';
maps_table.style['padding'] = '5px';
td_value.appendChild(maps_table);
var tbody = document.createElement('tbody');
maps_table.appendChild(tbody);
var map_values = [];
if (current_maps) {
for (var i=0; i<current_maps.length; i++) {
var map = current_maps[i];
map_values.push(input_google_map(widget_config, tbody, map));
}
} else {
map_values.push(input_google_map(widget_config, tbody, null));
}
// create (+) add an element button
var plus_url = self.config.static_url + 'images/plus.png';
var plus_img = document.createElement('img');
plus_img.setAttribute('src', plus_url);
plus_img.setAttribute('alt', 'Add');
plus_img.setAttribute('title', 'Add another map');
plus_img.className = 'widget_config_plus';
// now set the onlclick callback for the (+) button to add another destination input element
var plus_onclick = function () {
self.log(widget_id,'TrafficMap input_map_list plus_onclick called');
map_values.push(input_google_map(widget_config, tbody,null));
}
plus_img.onclick = plus_onclick;
td_value.appendChild(plus_img);
function value_fn () {
var list_result = [];
for (var i=0; i<map_values.length; i++) {
if (map_values[i].value()) {
list_result.push(map_values[i].value());
}
}
return list_result;
};
return { value: value_fn,
valid: function () { return true; },
element: row
};
} // end input_google_map_list | function input_google_map_list(widget_config, parent_el, current_maps) {
self.log(widget_id,'input_map_list called with', current_maps);
var row = document.createElement('tr');
parent_el.appendChild(row);
// create TD to hold 'name' prompt for field
var td_name = document.createElement('td');
td_name.className = 'widget_config_property_name';
var label = document.createElement('label');
//label.htmlFor = id;
label.title = 'Configure one or more maps';
label.appendChild(document.createTextNode('Traffic Maps:'));
td_name.appendChild(label);
row.appendChild(td_name);
// create TD to hold 'value' destination_list
var td_value = document.createElement('td');
td_value.className = 'widget_config_property_value';
row.appendChild(td_value);
var maps_table = document.createElement('table');
maps_table.className = 'config_traffic_maps_table';
maps_table.style['border-collapse'] = 'separate';
maps_table.style['padding'] = '5px';
td_value.appendChild(maps_table);
var tbody = document.createElement('tbody');
maps_table.appendChild(tbody);
var map_values = [];
if (current_maps) {
for (var i=0; i<current_maps.length; i++) {
var map = current_maps[i];
map_values.push(input_google_map(widget_config, tbody, map));
}
} else {
map_values.push(input_google_map(widget_config, tbody, null));
}
// create (+) add an element button
var plus_url = self.config.static_url + 'images/plus.png';
var plus_img = document.createElement('img');
plus_img.setAttribute('src', plus_url);
plus_img.setAttribute('alt', 'Add');
plus_img.setAttribute('title', 'Add another map');
plus_img.className = 'widget_config_plus';
// now set the onlclick callback for the (+) button to add another destination input element
var plus_onclick = function () {
self.log(widget_id,'TrafficMap input_map_list plus_onclick called');
map_values.push(input_google_map(widget_config, tbody,null));
}
plus_img.onclick = plus_onclick;
td_value.appendChild(plus_img);
function value_fn () {
var list_result = [];
for (var i=0; i<map_values.length; i++) {
if (map_values[i].value()) {
list_result.push(map_values[i].value());
}
}
return list_result;
};
return { value: value_fn,
valid: function () { return true; },
element: row
};
} // end input_google_map_list |
JavaScript | function usage_ok(config) {
var data;
if (localStorage.getItem(USAGE_RECORD_KEY)) {
data = JSON.parse(localStorage.getItem(USAGE_RECORD_KEY));
// Set to 0 if the day has changed
if (data.day !== moment().format('YYYY-MM-DD')) {
data.day = moment().format('YYYY-MM-DD');
data.count = 0;
}
}
else {
data = {
day: moment().format('YYYY-MM-DD'),
count: 0
};
}
data.count += 1;
localStorage.setItem(USAGE_RECORD_KEY, JSON.stringify(data));
var actual_limit = config.map_reload_limit !== undefined
? config.map_reload_limit
: config.settings.SMARTPANEL_TRAFFIC_MAP_RELOAD_LIMIT_DEFAULT;
if (data.count > actual_limit) {
send_beacon({
event: 'google_usage_limit_exceeded',
count: data.count,
limit: actual_limit,
layout: config.layout_id,
display: config.display_id
});
return(false);
}
send_beacon({
event: 'google_api_call',
count: data.count,
limit: actual_limit,
layout: config.layout_id,
display: config.display_id
});
return(true);
} | function usage_ok(config) {
var data;
if (localStorage.getItem(USAGE_RECORD_KEY)) {
data = JSON.parse(localStorage.getItem(USAGE_RECORD_KEY));
// Set to 0 if the day has changed
if (data.day !== moment().format('YYYY-MM-DD')) {
data.day = moment().format('YYYY-MM-DD');
data.count = 0;
}
}
else {
data = {
day: moment().format('YYYY-MM-DD'),
count: 0
};
}
data.count += 1;
localStorage.setItem(USAGE_RECORD_KEY, JSON.stringify(data));
var actual_limit = config.map_reload_limit !== undefined
? config.map_reload_limit
: config.settings.SMARTPANEL_TRAFFIC_MAP_RELOAD_LIMIT_DEFAULT;
if (data.count > actual_limit) {
send_beacon({
event: 'google_usage_limit_exceeded',
count: data.count,
limit: actual_limit,
layout: config.layout_id,
display: config.display_id
});
return(false);
}
send_beacon({
event: 'google_api_call',
count: data.count,
limit: actual_limit,
layout: config.layout_id,
display: config.display_id
});
return(true);
} |
JavaScript | function load_data() {
var headers = {
Authorization: 'Token ' + API_TOKEN
};
$.when(
$.get({
url: '/api/v1/traffic/btjourney/site/',
headers: headers,
dataType: 'json',
}),
$.get({
url: '/api/v1/traffic/btjourney/link/',
headers: headers,
dataType: 'json',
}),
$.get({
url: '/api/v1/traffic/btjourney/route/',
headers: headers,
dataType: 'json',
}),
$.get({
url: '/api/v1/traffic/btjourney/latest/',
headers: headers,
dataType: 'json',
})
)
.done(function(site_response, link_response, route_response, journey_response) {
var sites = site_response[0].site_list;
var links = link_response[0].link_list.concat(route_response[0].route_list);
var journeys = journey_response[0].request_data;
draw_sites(sites);
process_journeys(journeys, links, sites);
// Display the data's timestamp on the clock
var timestamp = journey_response[0].ts * 1000;
clock.update(new Date(timestamp));
if (first_time) {
// Scale map to fit
var region = sites_layer.getBounds().extend(links_layer);
map.fitBounds(region);
// Cancel the spinner
spinner.style.display = 'none';
first_time = false;
}
// The underlying API updates journey times every 5 minutes.
// Schedule an update 5 and-a-bit minutes from the last
// timestamp if that looks believable, and in a minute
// otherwise.
var now = Date.now();
var delta = timestamp - now + (5.25*60000);
if (delta <= 0 || delta > 10*60000) {
delta = 60000;
}
console.log('Timestamp was ' + new Date(timestamp));
console.log('Delta is ' + delta);
console.log('Now is ' + new Date(now));
console.log('Next at ' + new Date(now + delta));
setTimeout(load_data, delta);
})
// If anything went wrong, try again in a minute
.fail(function(){
console.log('API call failed - default reschedule');
setTimeout(load_data, 60000);
});
} | function load_data() {
var headers = {
Authorization: 'Token ' + API_TOKEN
};
$.when(
$.get({
url: '/api/v1/traffic/btjourney/site/',
headers: headers,
dataType: 'json',
}),
$.get({
url: '/api/v1/traffic/btjourney/link/',
headers: headers,
dataType: 'json',
}),
$.get({
url: '/api/v1/traffic/btjourney/route/',
headers: headers,
dataType: 'json',
}),
$.get({
url: '/api/v1/traffic/btjourney/latest/',
headers: headers,
dataType: 'json',
})
)
.done(function(site_response, link_response, route_response, journey_response) {
var sites = site_response[0].site_list;
var links = link_response[0].link_list.concat(route_response[0].route_list);
var journeys = journey_response[0].request_data;
draw_sites(sites);
process_journeys(journeys, links, sites);
// Display the data's timestamp on the clock
var timestamp = journey_response[0].ts * 1000;
clock.update(new Date(timestamp));
if (first_time) {
// Scale map to fit
var region = sites_layer.getBounds().extend(links_layer);
map.fitBounds(region);
// Cancel the spinner
spinner.style.display = 'none';
first_time = false;
}
// The underlying API updates journey times every 5 minutes.
// Schedule an update 5 and-a-bit minutes from the last
// timestamp if that looks believable, and in a minute
// otherwise.
var now = Date.now();
var delta = timestamp - now + (5.25*60000);
if (delta <= 0 || delta > 10*60000) {
delta = 60000;
}
console.log('Timestamp was ' + new Date(timestamp));
console.log('Delta is ' + delta);
console.log('Now is ' + new Date(now));
console.log('Next at ' + new Date(now + delta));
setTimeout(load_data, delta);
})
// If anything went wrong, try again in a minute
.fail(function(){
console.log('API call failed - default reschedule');
setTimeout(load_data, 60000);
});
} |
JavaScript | function draw_sites(sites) {
// Add markers for new sites
for (var i = 0; i < sites.length; ++i) {
var site = sites[i];
if (site_index[site.id] === undefined) {
var marker = L.circleMarker([site.location.lat, site.location.lng], SITE_OPTIONS)
.bindPopup(site_popup, {maxWidth: 500})
.addTo(sites_layer);
marker.properties = { 'site': site };
site_index[site.id] = marker;
}
}
// Remove markers for sites that have gone away
for (var site_id in site_index) {
if (find_object(sites, site_id) === undefined) {
site_index[site_id].delete();
delete site_index[site.id];
}
}
} | function draw_sites(sites) {
// Add markers for new sites
for (var i = 0; i < sites.length; ++i) {
var site = sites[i];
if (site_index[site.id] === undefined) {
var marker = L.circleMarker([site.location.lat, site.location.lng], SITE_OPTIONS)
.bindPopup(site_popup, {maxWidth: 500})
.addTo(sites_layer);
marker.properties = { 'site': site };
site_index[site.id] = marker;
}
}
// Remove markers for sites that have gone away
for (var site_id in site_index) {
if (find_object(sites, site_id) === undefined) {
site_index[site_id].delete();
delete site_index[site.id];
}
}
} |
JavaScript | function process_journeys(journeys, links, sites) {
for (var i = 0; i < journeys.length; ++i) {
var journey = journeys[i];
// Try to get the Leaflet polyline for the coresponding route
var line = link_index[journey.id];
// Add a polyline to the map if missing
if (line === undefined) {
line = draw_line(journey.id, links, sites);
}
// The addition could have failed
if (line !== undefined) {
line.properties.journey = journey;
}
}
// Remove polylines for links without journeys
for (var link_id in link_index) {
if (find_object(journeys, link_id) === undefined) {
link_index[link_id].delete();
delete link_index[link_id];
}
}
update_line_colours();
} | function process_journeys(journeys, links, sites) {
for (var i = 0; i < journeys.length; ++i) {
var journey = journeys[i];
// Try to get the Leaflet polyline for the coresponding route
var line = link_index[journey.id];
// Add a polyline to the map if missing
if (line === undefined) {
line = draw_line(journey.id, links, sites);
}
// The addition could have failed
if (line !== undefined) {
line.properties.journey = journey;
}
}
// Remove polylines for links without journeys
for (var link_id in link_index) {
if (find_object(journeys, link_id) === undefined) {
link_index[link_id].delete();
delete link_index[link_id];
}
}
update_line_colours();
} |
JavaScript | function draw_line(link_id, links, sites) {
var line = undefined;
var link = find_object(links, link_id);
if (link === undefined) {
console.log('Can\'t find link with id ' + link_id);
}
else {
var layer = link.sites.length <= 2 ? links_layer : routes_layer;
// Accumulate points
var points = [];
for (var j = 0; j < link.sites.length; ++j) {
var site = find_object(sites, link.sites[j]);
if (site) {
points.push([site.location.lat, site.location.lng]);
}
}
line = L.polyline(points, NORMAL_LINE)
.setStyle({color: NORMAL_COLOUR})
.bindPopup(line_popup, {maxWidth: 500})
.on('click', line_highlight)
.addTo(layer);
line.properties = { 'link': link };
// Remember the polyline for the future
link_index[link_id] = line;
// Add routes to the map individually, because they can overlap each other
if (layer === routes_layer) {
layer_control.addOverlay(line, link.name);
}
}
return line;
} | function draw_line(link_id, links, sites) {
var line = undefined;
var link = find_object(links, link_id);
if (link === undefined) {
console.log('Can\'t find link with id ' + link_id);
}
else {
var layer = link.sites.length <= 2 ? links_layer : routes_layer;
// Accumulate points
var points = [];
for (var j = 0; j < link.sites.length; ++j) {
var site = find_object(sites, link.sites[j]);
if (site) {
points.push([site.location.lat, site.location.lng]);
}
}
line = L.polyline(points, NORMAL_LINE)
.setStyle({color: NORMAL_COLOUR})
.bindPopup(line_popup, {maxWidth: 500})
.on('click', line_highlight)
.addTo(layer);
line.properties = { 'link': link };
// Remember the polyline for the future
link_index[link_id] = line;
// Add routes to the map individually, because they can overlap each other
if (layer === routes_layer) {
layer_control.addOverlay(line, link.name);
}
}
return line;
} |
JavaScript | function update_relative_speed(line) {
var journey = line.properties.journey;
var choice;
// Missing
if (!journey.travelTime) {
choice = BROKEN_COLOUR;
}
// Worse than normal
else if (journey.travelTime > 1.2*journey.normalTravelTime) {
choice = SLOW_COLOUR;
}
// Better then normal
else if (journey.travelTime < 0.8*journey.normalTravelTime) {
choice = FAST_COLOUR;
}
// Normal(ish)
else {
choice = NORMAL_COLOUR;
}
line.setStyle({color: choice});
} | function update_relative_speed(line) {
var journey = line.properties.journey;
var choice;
// Missing
if (!journey.travelTime) {
choice = BROKEN_COLOUR;
}
// Worse than normal
else if (journey.travelTime > 1.2*journey.normalTravelTime) {
choice = SLOW_COLOUR;
}
// Better then normal
else if (journey.travelTime < 0.8*journey.normalTravelTime) {
choice = FAST_COLOUR;
}
// Normal(ish)
else {
choice = NORMAL_COLOUR;
}
line.setStyle({color: choice});
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.