<commit_before>var conn = require('./conn.js');
var logger = (require('../logging/vip-winston')).Logger;

var endOfLine = require('os').EOL;
var delim = ',';

var makeCSVSafe = function(value){
  value = value && value.toString() || '';
  // the delim is in our value we need to put quotes around our value
  if(value.indexOf(delim)!==-1){

    // if we are putting quotes around our value, we need to escape any existing quotes first
    value = value.replace(/"/g, '""');

    value = '"' + value + '"';
  }

  return value;
}

var makeCSVRow = function(values) {
  return values.map(makeCSVSafe).join(delim) + endOfLine;
}

var header = ["Feed", "Severity", "Scope", "ID", "Error Type", "Error Data"];

var csvFilename = function(feedId, scope) {
  scopeName = scope || "Full";
  return feedId.replace(/ /g, '-') + "-" + scopeName + "ErrorReport.csv";
}

var errorReport = function(innerJoins, where, params, scope) {
  var errorQuery = "SELECT v.* FROM validations v INNER JOIN results r ON r.id = v.results_id " +
      innerJoins +
      " WHERE r.public_id=$1 " +
      (where ? " AND " + where : "") +
      " ORDER BY v.scope, v.identifier";
  return function(req, res) {
    var feedid = decodeURIComponent(req.params.feedid);

    try {
      conn.query(function(client) {
        var queryParams = ['feedid'].concat(params).map(function(param) { return decodeURIComponent(req.params[param]); });

        res.header("Content-Disposition", "attachment; filename=" + csvFilename(feedid, scope));
        res.setHeader('Content-type', 'text/csv');
        res.charset = 'UTF-8';

        res.write(makeCSVRow(header));

        var query = client.query(errorQuery, queryParams);

        query.on("row", function(row, result) {
          res.write(makeCSVRow([feedid, row.severity, row.scope, row.identifier, row.error_type, row.error_data]));
        });

        query.on("end", function(result) {
          res.end();
        });

        query.on("error", function(e) {
          logger.error("Generating an error report for '" + feedid + "' caused " + e.message);
          // If the query doesn't return anything before we hit our connection's
          // timeout, we'll only have added CSV headers to the response.
          res.end();
        });
      });
    }
    catch (e) {}
  }
}

var xmlTreeValidationQuery =
"SELECT v.severity, v.scope, v.path, x.value AS identifier, \
        v.error_type, v.error_data \
 FROM xml_tree_validations v \
 LEFT JOIN xml_tree_values x \
        ON x.path = subpath(v.path,0,4) || 'id' AND x.results_id = v.results_id \
 INNER JOIN results r ON r.id = v.results_id \
 WHERE r.public_id = $1";

var scopedXmlTreeValidationQuery = function(elementTypes) {
  return "SELECT v.severity, v.scope, v.path, x.value AS identifier, \
        v.error_type, v.error_data \
 FROM xml_tree_validations v \
 LEFT JOIN xml_tree_values x \
        ON x.path = subpath(v.path,0,4) || 'id' AND x.results_id = v.results_id \
 INNER JOIN results r ON r.id = v.results_id \
 WHERE r.public_id = $1 AND v.path ~ 'VipObject.0." + elementTypes.join("|") + ".*'";
}

var scopedXmlTreeValidationErrorReport = function() {
  var elementTypes = Array.prototype.slice.call(arguments);

  return function(req, res) {
    var header = ["Feed", "Severity", "Scope", "Path", "ID", "Error Type", "Error Data"];
    var feedid = decodeURIComponent(req.params.feedid);

    conn.query(function(client) {
      res.header("Content-Disposition", "attachment; filename=" + csvFilename(feedid, elementTypes[0]));
      res.setHeader('Content-type', 'text/csv');
      res.charset = 'UTF-8';

      res.write(makeCSVRow(header));

      var query = client.query(scopedXmlTreeValidationQuery(elementTypes), [feedid]);

      query.on("row", function(row, result) {
        res.write(makeCSVRow([feedid,
                              row.severity,
                              row.scope,
                              row.path,
                              row.identifier,
                              row.error_type,
                              row.error_data]));
      });

      query.on("end", function(result) {
        res.end();
      });
    });
  };
}

var xmlTreeValidationErrorReport = function(req, res) {
  var header = ["Feed", "Severity", "Scope", "Path", "ID", "Error Type", "Error Data"];
  var feedid = decodeURIComponent(req.params.feedid);

  conn.query(function(client) {
    res.header("Content-Disposition", "attachment; filename=" + csvFilename(feedid));
    res.setHeader('Content-type', 'text/csv');
    res.charset = 'UTF-8';

    res.write(makeCSVRow(header));

    var query = client.query(xmlTreeValidationQuery, [feedid]);

    query.on("row", function(row, result) {
      res.write(makeCSVRow([feedid,
                            row.severity,
                            row.scope,
                            row.path,
                            row.identifier,
                            row.error_type,
                            row.error_data]));
    });

    query.on("end", function(result) {
      res.end();
    });
  });
}

var xmlTreeLocalityErrorReport = function(req, res) {
  var header = ["Feed", "Severity", "Scope", "Path", "ID", "Error Type", "Error Data"];
  var feedid = decodeURIComponent(req.params.publicId);
  var localityid = decodeURIComponent(req.params.localityId)
  conn.query(function(client) {

    res.header("Content-Disposition", "attachment; filename=" + csvFilename(feedid));
    res.setHeader('Content-type', 'text/csv');
    res.charset = 'UTF-8';

    res.write(makeCSVRow(header));

    var query = client.query('select * from v5_dashboard.locality_error_report($1, $2)', [feedid, localityid]);

    query.on("row", function(row, result) {
      res.write(makeCSVRow([feedid,
                            row.severity,
                            row.scope,
                            row.path,
                            row.identifier,
                            row.error_type,
                            row.error_data]));
    });

    query.on("end", function(result) {
      res.end();
    });
  });

}

var pollingLocationAddressReport = function(req, res) {
  var header = ["Locality Name", "Precinct Name", "Address Location Name", "Address Line 1", "Address Line 2", "Address Line 3", "Address City", "Address State",  "Address Zip", "Polling Location Id"];
  var feedid = decodeURIComponent(req.params.feedid);
  conn.query(function(client) {

    res.header("Content-Disposition", "attachment; filename=" + csvFilename(feedid));
    res.setHeader('Content-type', 'text/csv');
    res.charset = 'UTF-8';

    res.write(makeCSVRow(header));

    var query = client.query('select * from v3_dashboard.polling_location_readable_report($1)', [feedid]);

    query.on("row", function(row, result) {
      res.write(makeCSVRow([row.locality_name,
                            row.precinct_name,
                            row.address_location_name,
                            row.address_line1,
                            row.address_line2,
                            row.address_line3,
                            row.address_city,
                            row.address_state,
                            row.address_zip,
                            row.polling_location_id]));
    });

    query.on("end", function(result) {
      res.end();
    });
  });

}

module.exports = {
  xmlTreeLocalityErrorReport: xmlTreeLocalityErrorReport,
  errorReport: errorReport,
  fullErrorReport: errorReport("", "", []),
  scopedErrorReport: function(scope) {
    return errorReport("", "v.scope = '" + scope + "'", [], scope);
  },
  xmlTreeValidationErrorReport: xmlTreeValidationErrorReport,
  scopedXmlTreeValidationErrorReport: scopedXmlTreeValidationErrorReport,
  pollingLocationAddressReport: pollingLocationAddressReport
}
<commit_msg>fix parameter name for locality error report request<commit_after>var conn = require('./conn.js');
var logger = (require('../logging/vip-winston')).Logger;

var endOfLine = require('os').EOL;
var delim = ',';

var makeCSVSafe = function(value){
  value = value && value.toString() || '';
  // the delim is in our value we need to put quotes around our value
  if(value.indexOf(delim)!==-1){

    // if we are putting quotes around our value, we need to escape any existing quotes first
    value = value.replace(/"/g, '""');

    value = '"' + value + '"';
  }

  return value;
}

var makeCSVRow = function(values) {
  return values.map(makeCSVSafe).join(delim) + endOfLine;
}

var header = ["Feed", "Severity", "Scope", "ID", "Error Type", "Error Data"];

var csvFilename = function(feedId, scope) {
  scopeName = scope || "Full";
  return feedId.replace(/ /g, '-') + "-" + scopeName + "ErrorReport.csv";
}

var errorReport = function(innerJoins, where, params, scope) {
  var errorQuery = "SELECT v.* FROM validations v INNER JOIN results r ON r.id = v.results_id " +
      innerJoins +
      " WHERE r.public_id=$1 " +
      (where ? " AND " + where : "") +
      " ORDER BY v.scope, v.identifier";
  return function(req, res) {
    var feedid = decodeURIComponent(req.params.feedid);

    try {
      conn.query(function(client) {
        var queryParams = ['feedid'].concat(params).map(function(param) { return decodeURIComponent(req.params[param]); });

        res.header("Content-Disposition", "attachment; filename=" + csvFilename(feedid, scope));
        res.setHeader('Content-type', 'text/csv');
        res.charset = 'UTF-8';

        res.write(makeCSVRow(header));

        var query = client.query(errorQuery, queryParams);

        query.on("row", function(row, result) {
          res.write(makeCSVRow([feedid, row.severity, row.scope, row.identifier, row.error_type, row.error_data]));
        });

        query.on("end", function(result) {
          res.end();
        });

        query.on("error", function(e) {
          logger.error("Generating an error report for '" + feedid + "' caused " + e.message);
          // If the query doesn't return anything before we hit our connection's
          // timeout, we'll only have added CSV headers to the response.
          res.end();
        });
      });
    }
    catch (e) {}
  }
}

var xmlTreeValidationQuery =
"SELECT v.severity, v.scope, v.path, x.value AS identifier, \
        v.error_type, v.error_data \
 FROM xml_tree_validations v \
 LEFT JOIN xml_tree_values x \
        ON x.path = subpath(v.path,0,4) || 'id' AND x.results_id = v.results_id \
 INNER JOIN results r ON r.id = v.results_id \
 WHERE r.public_id = $1";

var scopedXmlTreeValidationQuery = function(elementTypes) {
  return "SELECT v.severity, v.scope, v.path, x.value AS identifier, \
        v.error_type, v.error_data \
 FROM xml_tree_validations v \
 LEFT JOIN xml_tree_values x \
        ON x.path = subpath(v.path,0,4) || 'id' AND x.results_id = v.results_id \
 INNER JOIN results r ON r.id = v.results_id \
 WHERE r.public_id = $1 AND v.path ~ 'VipObject.0." + elementTypes.join("|") + ".*'";
}

var scopedXmlTreeValidationErrorReport = function() {
  var elementTypes = Array.prototype.slice.call(arguments);

  return function(req, res) {
    var header = ["Feed", "Severity", "Scope", "Path", "ID", "Error Type", "Error Data"];
    var feedid = decodeURIComponent(req.params.feedid);

    conn.query(function(client) {
      res.header("Content-Disposition", "attachment; filename=" + csvFilename(feedid, elementTypes[0]));
      res.setHeader('Content-type', 'text/csv');
      res.charset = 'UTF-8';

      res.write(makeCSVRow(header));

      var query = client.query(scopedXmlTreeValidationQuery(elementTypes), [feedid]);

      query.on("row", function(row, result) {
        res.write(makeCSVRow([feedid,
                              row.severity,
                              row.scope,
                              row.path,
                              row.identifier,
                              row.error_type,
                              row.error_data]));
      });

      query.on("end", function(result) {
        res.end();
      });
    });
  };
}

var xmlTreeValidationErrorReport = function(req, res) {
  var header = ["Feed", "Severity", "Scope", "Path", "ID", "Error Type", "Error Data"];
  var feedid = decodeURIComponent(req.params.feedid);

  conn.query(function(client) {
    res.header("Content-Disposition", "attachment; filename=" + csvFilename(feedid));
    res.setHeader('Content-type', 'text/csv');
    res.charset = 'UTF-8';

    res.write(makeCSVRow(header));

    var query = client.query(xmlTreeValidationQuery, [feedid]);

    query.on("row", function(row, result) {
      res.write(makeCSVRow([feedid,
                            row.severity,
                            row.scope,
                            row.path,
                            row.identifier,
                            row.error_type,
                            row.error_data]));
    });

    query.on("end", function(result) {
      res.end();
    });
  });
}

var xmlTreeLocalityErrorReport = function(req, res) {
  var header = ["Feed", "Severity", "Scope", "Path", "ID", "Error Type", "Error Data"];
  var feedid = decodeURIComponent(req.params.feedid);
  var localityid = decodeURIComponent(req.params.localityId)
  conn.query(function(client) {

    res.header("Content-Disposition", "attachment; filename=" + csvFilename(feedid));
    res.setHeader('Content-type', 'text/csv');
    res.charset = 'UTF-8';

    res.write(makeCSVRow(header));

    var query = client.query('select * from v5_dashboard.locality_error_report($1, $2)', [feedid, localityid]);

    query.on("row", function(row, result) {
      res.write(makeCSVRow([feedid,
                            row.severity,
                            row.scope,
                            row.path,
                            row.identifier,
                            row.error_type,
                            row.error_data]));
    });

    query.on("end", function(result) {
      res.end();
    });
  });

}

var pollingLocationAddressReport = function(req, res) {
  var header = ["Locality Name", "Precinct Name", "Address Location Name", "Address Line 1", "Address Line 2", "Address Line 3", "Address City", "Address State",  "Address Zip", "Polling Location Id"];
  var feedid = decodeURIComponent(req.params.feedid);
  conn.query(function(client) {

    res.header("Content-Disposition", "attachment; filename=" + csvFilename(feedid));
    res.setHeader('Content-type', 'text/csv');
    res.charset = 'UTF-8';

    res.write(makeCSVRow(header));

    var query = client.query('select * from v3_dashboard.polling_location_readable_report($1)', [feedid]);

    query.on("row", function(row, result) {
      res.write(makeCSVRow([row.locality_name,
                            row.precinct_name,
                            row.address_location_name,
                            row.address_line1,
                            row.address_line2,
                            row.address_line3,
                            row.address_city,
                            row.address_state,
                            row.address_zip,
                            row.polling_location_id]));
    });

    query.on("end", function(result) {
      res.end();
    });
  });

}

module.exports = {
  xmlTreeLocalityErrorReport: xmlTreeLocalityErrorReport,
  errorReport: errorReport,
  fullErrorReport: errorReport("", "", []),
  scopedErrorReport: function(scope) {
    return errorReport("", "v.scope = '" + scope + "'", [], scope);
  },
  xmlTreeValidationErrorReport: xmlTreeValidationErrorReport,
  scopedXmlTreeValidationErrorReport: scopedXmlTreeValidationErrorReport,
  pollingLocationAddressReport: pollingLocationAddressReport
}
<|endoftext|>


<commit_before>import { Meteor } from 'meteor/meteor';
import { ReactiveVar } from 'meteor/reactive-var';
import { Tracker } from 'meteor/tracker';
import { Reload } from 'meteor/reload';
import { Template } from 'meteor/templating';
import { TAPi18n } from 'meteor/rocketchat:tap-i18n';
import _ from 'underscore';
import s from 'underscore.string';
import toastr from 'toastr';

import { t, handleError, getUserPreference } from '../../utils';
import { modal, SideNav } from '../../ui-utils';
import { KonchatNotification } from '../../ui';
import { settings } from '../../settings';
import { CustomSounds } from '../../custom-sounds/client';

const notificationLabels = {
	all: 'All_messages',
	mentions: 'Mentions',
	nothing: 'Nothing',
};

const emailLabels = {
	nothing: 'Email_Notification_Mode_Disabled',
	mentions: 'Email_Notification_Mode_All',
};

function checkedSelected(property, value, defaultValue = undefined) {
	if (defaultValue && defaultValue.hash) {
		defaultValue = undefined;
	}
	return getUserPreference(Meteor.userId(), property, defaultValue) === value;
}

Template.accountPreferences.helpers({
	audioAssets() {
		return (CustomSounds && CustomSounds.getList && CustomSounds.getList()) || [];
	},
	newMessageNotification() {
		return getUserPreference(Meteor.userId(), 'newMessageNotification');
	},
	newRoomNotification() {
		return getUserPreference(Meteor.userId(), 'newRoomNotification');
	},
	muteFocusedConversations() {
		return getUserPreference(Meteor.userId(), 'muteFocusedConversations');
	},
	languages() {
		const languages = TAPi18n.getLanguages();

		const result = Object.entries(languages)
			.map(([key, language]) => ({ ...language, key }))
			.sort((a, b) => a.key - b.key);

		result.unshift({
			name: 'Default',
			en: 'Default',
			key: '',
		});

		return result;
	},
	isUserLanguage(key) {
		const languageKey = Meteor.user().language;
		return typeof languageKey === 'string' && languageKey.toLowerCase() === key.toLowerCase();
	},
	ifThenElse(condition, val, not = '') {
		return condition ? val : not;
	},
	checked(property, value, defaultValue = undefined) {
		return checkedSelected(property, value, defaultValue);
	},
	selected(property, value, defaultValue = undefined) {
		return checkedSelected(property, value, defaultValue);
	},
	highlights() {
		const userHighlights = getUserPreference(Meteor.userId(), 'highlights');
		return userHighlights ? userHighlights.join(',\n') : undefined;
	},
	desktopNotificationEnabled() {
		return KonchatNotification.notificationStatus.get() === 'granted' || (window.Notification && Notification.permission === 'granted');
	},
	desktopNotificationDisabled() {
		return KonchatNotification.notificationStatus.get() === 'denied' || (window.Notification && Notification.permission === 'denied');
	},
	desktopNotificationDuration() {
		const userPref = getUserPreference(Meteor.userId(), 'desktopNotificationDuration', 'undefined');
		return userPref !== 'undefined' ? userPref : undefined;
	},
	defaultDesktopNotificationDuration() {
		return settings.get('Accounts_Default_User_Preferences_desktopNotificationDuration');
	},
	desktopNotificationRequireInteraction() {
		const userPref = getUserPreference(Meteor.userId(), 'desktopNotificationRequireInteraction', 'undefined');
		return userPref !== 'undefined' ? userPref : undefined;
	},
	defaultDesktopNotificationRequireInteraction() {
		return settings.get('Accounts_Default_User_Preferences_desktopNotificationRequireInteraction');
	},
	idleTimeLimit() {
		return getUserPreference(Meteor.userId(), 'idleTimeLimit');
	},
	defaultIdleTimeLimit() {
		return settings.get('Accounts_Default_User_Preferences_idleTimeLimit');
	},
	defaultDesktopNotification() {
		return notificationLabels[settings.get('Accounts_Default_User_Preferences_desktopNotifications')];
	},
	defaultMobileNotification() {
		return notificationLabels[settings.get('Accounts_Default_User_Preferences_mobileNotifications')];
	},
	defaultEmailNotification() {
		return emailLabels[settings.get('Accounts_Default_User_Preferences_emailNotificationMode')];
	},
	showRoles() {
		return settings.get('UI_DisplayRoles');
	},
	userDataDownloadEnabled() {
		return settings.get('UserData_EnableDownload') !== false;
	},
	notificationsSoundVolume() {
		return getUserPreference(Meteor.userId(), 'notificationsSoundVolume');
	},
	emailNotificationsAllowed() {
		return settings.get('Accounts_AllowEmailNotifications');
	},
	dontAskAgainList() {
		return getUserPreference(Meteor.userId(), 'dontAskAgainList');
	},
});

Template.accountPreferences.onCreated(function() {
	const settingsTemplate = this.parentTemplate(3);

	if (settingsTemplate.child == null) {
		settingsTemplate.child = [];
	}

	settingsTemplate.child.push(this);

	this.useEmojis = new ReactiveVar(getUserPreference(Meteor.userId(), 'useEmojis'));

	let instance = this;

	this.autorun(() => {
		if (instance.useEmojis && instance.useEmojis.get()) {
			Tracker.afterFlush(() => $('#convertAsciiEmoji').show());
		} else {
			Tracker.afterFlush(() => $('#convertAsciiEmoji').hide());
		}
	});

	this.clearForm = function() {
		this.find('#language').value = Meteor._localStorage.getItem('userLanguage');
	};

	this.shouldUpdateLocalStorageSetting = function(setting, newValue) {
		return Meteor._localStorage.getItem(setting) !== newValue;
	};

	this.save = function() {
		instance = this;
		const data = {};

		data.newRoomNotification = $('select[name=newRoomNotification]').val();
		data.newMessageNotification = $('select[name=newMessageNotification]').val();
		data.clockMode = parseInt($('select[name=clockMode]').val());
		data.useEmojis = JSON.parse($('input[name=useEmojis]:checked').val());
		data.convertAsciiEmoji = JSON.parse($('input[name=convertAsciiEmoji]:checked').val());
		data.saveMobileBandwidth = JSON.parse($('input[name=saveMobileBandwidth]:checked').val());
		data.collapseMediaByDefault = JSON.parse($('input[name=collapseMediaByDefault]:checked').val());
		data.muteFocusedConversations = JSON.parse($('#muteFocusedConversations').find('input:checked').val());
		data.hideUsernames = JSON.parse($('#hideUsernames').find('input:checked').val());
		data.messageViewMode = parseInt($('#messageViewMode').find('select').val());
		data.hideFlexTab = JSON.parse($('#hideFlexTab').find('input:checked').val());
		data.hideAvatars = JSON.parse($('#hideAvatars').find('input:checked').val());
		data.sidebarHideAvatar = JSON.parse($('#sidebarHideAvatar').find('input:checked').val());
		data.sendOnEnter = $('#sendOnEnter').find('select').val();
		data.autoImageLoad = JSON.parse($('input[name=autoImageLoad]:checked').val());
		data.emailNotificationMode = $('select[name=emailNotificationMode]').val();
		data.desktopNotificationDuration = $('input[name=desktopNotificationDuration]').val() === '' ? settings.get('Accounts_Default_User_Preferences_desktopNotificationDuration') : parseInt($('input[name=desktopNotificationDuration]').val());
		data.desktopNotifications = $('#desktopNotifications').find('select').val();
		data.mobileNotifications = $('#mobileNotifications').find('select').val();
		data.unreadAlert = JSON.parse($('#unreadAlert').find('input:checked').val());
		data.sidebarShowDiscussion = JSON.parse($('#sidebarShowDiscussion').find('input:checked').val());
		data.notificationsSoundVolume = parseInt($('#notificationsSoundVolume').val());
		data.highlights = _.compact(_.map($('[name=highlights]').val().split(/,|\n/), function(e) {
			return s.trim(e);
		}));
		data.dontAskAgainList = Array.from(document.getElementById('dont-ask').options).map((option) => ({ action: option.value, label: option.text }));

		let reload = false;

		if (settings.get('UI_DisplayRoles')) {
			data.hideRoles = JSON.parse($('#hideRoles').find('input:checked').val());
		}

		if ($('input[name=desktopNotificationRequireInteraction]:checked').val() === undefined) {
			data.desktopNotificationRequireInteraction = settings.get('Accounts_Default_User_Preferences_desktopNotificationRequireInteraction');
		} else {
			data.desktopNotificationRequireInteraction = JSON.parse($('input[name=desktopNotificationRequireInteraction]:checked').val());
		}

		// if highlights changed we need page reload
		const highlights = getUserPreference(Meteor.userId(), 'highlights');
		if (highlights && highlights.join('\n') !== data.highlights.join('\n')) {
			reload = true;
		}

		const selectedLanguage = $('#language').val();
		if (this.shouldUpdateLocalStorageSetting('userLanguage', selectedLanguage)) {
			Meteor._localStorage.setItem('userLanguage', selectedLanguage);
			data.language = selectedLanguage;
			reload = true;
		}

		const enableAutoAway = JSON.parse($('#enableAutoAway').find('input:checked').val());
		data.enableAutoAway = enableAutoAway;
		if (this.shouldUpdateLocalStorageSetting('enableAutoAway', enableAutoAway)) {
			Meteor._localStorage.setItem('enableAutoAway', enableAutoAway);
			reload = true;
		}

		const idleTimeLimit = $('input[name=idleTimeLimit]').val() === '' ? settings.get('Accounts_Default_User_Preferences_idleTimeLimit') : parseInt($('input[name=idleTimeLimit]').val());
		data.idleTimeLimit = idleTimeLimit;
		if (this.shouldUpdateLocalStorageSetting('idleTimeLimit', idleTimeLimit)) {
			Meteor._localStorage.setItem('idleTimeLimit', idleTimeLimit);
			reload = true;
		}

		Meteor.call('saveUserPreferences', data, function(error, results) {
			if (results) {
				toastr.success(t('Preferences_saved'));
				instance.clearForm();
				if (reload) {
					setTimeout(function() {
						if (Meteor._reload && Meteor._reload.reload) { // make it compatible with old meteor
							Meteor._reload.reload();
						} else {
							Reload._reload();
						}
					}, 1000);
				}
			}
			if (error) {
				return handleError(error);
			}
		});
	};

	this.downloadMyData = function(fullExport = false) {
		Meteor.call('requestDataDownload', { fullExport }, function(error, results) {
			if (results) {
				if (results.requested) {
					modal.open({
						title: t('UserDataDownload_Requested'),
						text: t('UserDataDownload_Requested_Text', { pending_operations: results.pendingOperationsBeforeMyRequest }),
						type: 'success',
						html: true,
					});

					return true;
				}

				if (results.exportOperation) {
					if (results.exportOperation.status === 'completed') {
						const text = results.url
							? TAPi18n.__('UserDataDownload_CompletedRequestExistedWithLink_Text', { download_link: results.url })
							: t('UserDataDownload_CompletedRequestExisted_Text');

						modal.open({
							title: t('UserDataDownload_Requested'),
							text,
							type: 'success',
							html: true,
						});

						return true;
					}

					modal.open({
						title: t('UserDataDownload_Requested'),
						text: t('UserDataDownload_RequestExisted_Text', { pending_operations: results.pendingOperationsBeforeMyRequest }),
						type: 'success',
						html: true,
					});
					return true;
				}

				modal.open({
					title: t('UserDataDownload_Requested'),
					type: 'success',
				});
				return true;
			}

			if (error) {
				return handleError(error);
			}
		});
	};

	this.exportMyData = function() {
		this.downloadMyData(true);
	};
});

Template.accountPreferences.onRendered(function() {
	Tracker.afterFlush(function() {
		SideNav.setFlex('accountFlex');
		SideNav.openFlex();
	});
});

Template.accountPreferences.events({
	'click .rc-header__section-button .save'(e, t) {
		t.save();
	},
	'change input[name=useEmojis]'(e, t) {
		t.useEmojis.set($(e.currentTarget).val() === '1');
	},
	'click .download-my-data'(e, t) {
		e.preventDefault();
		t.downloadMyData();
	},
	'click .export-my-data'(e, t) {
		e.preventDefault();
		t.exportMyData();
	},
	'click .js-test-notifications'(e) {
		e.preventDefault();
		KonchatNotification.notify({
			duration: $('input[name=desktopNotificationDuration]').val(),
			payload: { sender: { username: 'rocket.cat' },
			},
			title: TAPi18n.__('Desktop_Notification_Test'),
			text: TAPi18n.__('This_is_a_desktop_notification'),
		});
	},
	'click .js-enable-notifications'() {
		KonchatNotification.getDesktopPermission();
	},
	'change .audio'(e) {
		e.preventDefault();
		const audio = $(e.currentTarget).val();
		if (audio === 'none') {
			return;
		}
		if (audio) {
			CustomSounds.play(audio);
		}
	},
	'click .js-dont-ask-remove'(e) {
		e.preventDefault();
		const selectEl = document.getElementById('dont-ask');
		const { options } = selectEl;
		const selectedOption = selectEl.value;
		const optionIndex = Array.from(options).findIndex((option) => option.value === selectedOption);

		selectEl.remove(optionIndex);
	},
});
<commit_msg>[FIX] remove multiple options from dontAskMeAgain (#17514)<commit_after>import { Meteor } from 'meteor/meteor';
import { ReactiveVar } from 'meteor/reactive-var';
import { Tracker } from 'meteor/tracker';
import { Reload } from 'meteor/reload';
import { Template } from 'meteor/templating';
import { TAPi18n } from 'meteor/rocketchat:tap-i18n';
import _ from 'underscore';
import s from 'underscore.string';
import toastr from 'toastr';

import { t, handleError, getUserPreference } from '../../utils';
import { modal, SideNav } from '../../ui-utils';
import { KonchatNotification } from '../../ui';
import { settings } from '../../settings';
import { CustomSounds } from '../../custom-sounds/client';

const notificationLabels = {
	all: 'All_messages',
	mentions: 'Mentions',
	nothing: 'Nothing',
};

const emailLabels = {
	nothing: 'Email_Notification_Mode_Disabled',
	mentions: 'Email_Notification_Mode_All',
};

function checkedSelected(property, value, defaultValue = undefined) {
	if (defaultValue && defaultValue.hash) {
		defaultValue = undefined;
	}
	return getUserPreference(Meteor.userId(), property, defaultValue) === value;
}

Template.accountPreferences.helpers({
	audioAssets() {
		return (CustomSounds && CustomSounds.getList && CustomSounds.getList()) || [];
	},
	newMessageNotification() {
		return getUserPreference(Meteor.userId(), 'newMessageNotification');
	},
	newRoomNotification() {
		return getUserPreference(Meteor.userId(), 'newRoomNotification');
	},
	muteFocusedConversations() {
		return getUserPreference(Meteor.userId(), 'muteFocusedConversations');
	},
	languages() {
		const languages = TAPi18n.getLanguages();

		const result = Object.entries(languages)
			.map(([key, language]) => ({ ...language, key }))
			.sort((a, b) => a.key - b.key);

		result.unshift({
			name: 'Default',
			en: 'Default',
			key: '',
		});

		return result;
	},
	isUserLanguage(key) {
		const languageKey = Meteor.user().language;
		return typeof languageKey === 'string' && languageKey.toLowerCase() === key.toLowerCase();
	},
	ifThenElse(condition, val, not = '') {
		return condition ? val : not;
	},
	checked(property, value, defaultValue = undefined) {
		return checkedSelected(property, value, defaultValue);
	},
	selected(property, value, defaultValue = undefined) {
		return checkedSelected(property, value, defaultValue);
	},
	highlights() {
		const userHighlights = getUserPreference(Meteor.userId(), 'highlights');
		return userHighlights ? userHighlights.join(',\n') : undefined;
	},
	desktopNotificationEnabled() {
		return KonchatNotification.notificationStatus.get() === 'granted' || (window.Notification && Notification.permission === 'granted');
	},
	desktopNotificationDisabled() {
		return KonchatNotification.notificationStatus.get() === 'denied' || (window.Notification && Notification.permission === 'denied');
	},
	desktopNotificationDuration() {
		const userPref = getUserPreference(Meteor.userId(), 'desktopNotificationDuration', 'undefined');
		return userPref !== 'undefined' ? userPref : undefined;
	},
	defaultDesktopNotificationDuration() {
		return settings.get('Accounts_Default_User_Preferences_desktopNotificationDuration');
	},
	desktopNotificationRequireInteraction() {
		const userPref = getUserPreference(Meteor.userId(), 'desktopNotificationRequireInteraction', 'undefined');
		return userPref !== 'undefined' ? userPref : undefined;
	},
	defaultDesktopNotificationRequireInteraction() {
		return settings.get('Accounts_Default_User_Preferences_desktopNotificationRequireInteraction');
	},
	idleTimeLimit() {
		return getUserPreference(Meteor.userId(), 'idleTimeLimit');
	},
	defaultIdleTimeLimit() {
		return settings.get('Accounts_Default_User_Preferences_idleTimeLimit');
	},
	defaultDesktopNotification() {
		return notificationLabels[settings.get('Accounts_Default_User_Preferences_desktopNotifications')];
	},
	defaultMobileNotification() {
		return notificationLabels[settings.get('Accounts_Default_User_Preferences_mobileNotifications')];
	},
	defaultEmailNotification() {
		return emailLabels[settings.get('Accounts_Default_User_Preferences_emailNotificationMode')];
	},
	showRoles() {
		return settings.get('UI_DisplayRoles');
	},
	userDataDownloadEnabled() {
		return settings.get('UserData_EnableDownload') !== false;
	},
	notificationsSoundVolume() {
		return getUserPreference(Meteor.userId(), 'notificationsSoundVolume');
	},
	emailNotificationsAllowed() {
		return settings.get('Accounts_AllowEmailNotifications');
	},
	dontAskAgainList() {
		return getUserPreference(Meteor.userId(), 'dontAskAgainList');
	},
});

Template.accountPreferences.onCreated(function() {
	const settingsTemplate = this.parentTemplate(3);

	if (settingsTemplate.child == null) {
		settingsTemplate.child = [];
	}

	settingsTemplate.child.push(this);

	this.useEmojis = new ReactiveVar(getUserPreference(Meteor.userId(), 'useEmojis'));

	let instance = this;

	this.autorun(() => {
		if (instance.useEmojis && instance.useEmojis.get()) {
			Tracker.afterFlush(() => $('#convertAsciiEmoji').show());
		} else {
			Tracker.afterFlush(() => $('#convertAsciiEmoji').hide());
		}
	});

	this.clearForm = function() {
		this.find('#language').value = Meteor._localStorage.getItem('userLanguage');
	};

	this.shouldUpdateLocalStorageSetting = function(setting, newValue) {
		return Meteor._localStorage.getItem(setting) !== newValue;
	};

	this.save = function() {
		instance = this;
		const data = {};

		data.newRoomNotification = $('select[name=newRoomNotification]').val();
		data.newMessageNotification = $('select[name=newMessageNotification]').val();
		data.clockMode = parseInt($('select[name=clockMode]').val());
		data.useEmojis = JSON.parse($('input[name=useEmojis]:checked').val());
		data.convertAsciiEmoji = JSON.parse($('input[name=convertAsciiEmoji]:checked').val());
		data.saveMobileBandwidth = JSON.parse($('input[name=saveMobileBandwidth]:checked').val());
		data.collapseMediaByDefault = JSON.parse($('input[name=collapseMediaByDefault]:checked').val());
		data.muteFocusedConversations = JSON.parse($('#muteFocusedConversations').find('input:checked').val());
		data.hideUsernames = JSON.parse($('#hideUsernames').find('input:checked').val());
		data.messageViewMode = parseInt($('#messageViewMode').find('select').val());
		data.hideFlexTab = JSON.parse($('#hideFlexTab').find('input:checked').val());
		data.hideAvatars = JSON.parse($('#hideAvatars').find('input:checked').val());
		data.sidebarHideAvatar = JSON.parse($('#sidebarHideAvatar').find('input:checked').val());
		data.sendOnEnter = $('#sendOnEnter').find('select').val();
		data.autoImageLoad = JSON.parse($('input[name=autoImageLoad]:checked').val());
		data.emailNotificationMode = $('select[name=emailNotificationMode]').val();
		data.desktopNotificationDuration = $('input[name=desktopNotificationDuration]').val() === '' ? settings.get('Accounts_Default_User_Preferences_desktopNotificationDuration') : parseInt($('input[name=desktopNotificationDuration]').val());
		data.desktopNotifications = $('#desktopNotifications').find('select').val();
		data.mobileNotifications = $('#mobileNotifications').find('select').val();
		data.unreadAlert = JSON.parse($('#unreadAlert').find('input:checked').val());
		data.sidebarShowDiscussion = JSON.parse($('#sidebarShowDiscussion').find('input:checked').val());
		data.notificationsSoundVolume = parseInt($('#notificationsSoundVolume').val());
		data.highlights = _.compact(_.map($('[name=highlights]').val().split(/,|\n/), function(e) {
			return s.trim(e);
		}));
		data.dontAskAgainList = Array.from(document.getElementById('dont-ask').options).map((option) => ({ action: option.value, label: option.text }));

		let reload = false;

		if (settings.get('UI_DisplayRoles')) {
			data.hideRoles = JSON.parse($('#hideRoles').find('input:checked').val());
		}

		if ($('input[name=desktopNotificationRequireInteraction]:checked').val() === undefined) {
			data.desktopNotificationRequireInteraction = settings.get('Accounts_Default_User_Preferences_desktopNotificationRequireInteraction');
		} else {
			data.desktopNotificationRequireInteraction = JSON.parse($('input[name=desktopNotificationRequireInteraction]:checked').val());
		}

		// if highlights changed we need page reload
		const highlights = getUserPreference(Meteor.userId(), 'highlights');
		if (highlights && highlights.join('\n') !== data.highlights.join('\n')) {
			reload = true;
		}

		const selectedLanguage = $('#language').val();
		if (this.shouldUpdateLocalStorageSetting('userLanguage', selectedLanguage)) {
			Meteor._localStorage.setItem('userLanguage', selectedLanguage);
			data.language = selectedLanguage;
			reload = true;
		}

		const enableAutoAway = JSON.parse($('#enableAutoAway').find('input:checked').val());
		data.enableAutoAway = enableAutoAway;
		if (this.shouldUpdateLocalStorageSetting('enableAutoAway', enableAutoAway)) {
			Meteor._localStorage.setItem('enableAutoAway', enableAutoAway);
			reload = true;
		}

		const idleTimeLimit = $('input[name=idleTimeLimit]').val() === '' ? settings.get('Accounts_Default_User_Preferences_idleTimeLimit') : parseInt($('input[name=idleTimeLimit]').val());
		data.idleTimeLimit = idleTimeLimit;
		if (this.shouldUpdateLocalStorageSetting('idleTimeLimit', idleTimeLimit)) {
			Meteor._localStorage.setItem('idleTimeLimit', idleTimeLimit);
			reload = true;
		}

		Meteor.call('saveUserPreferences', data, function(error, results) {
			if (results) {
				toastr.success(t('Preferences_saved'));
				instance.clearForm();
				if (reload) {
					setTimeout(function() {
						if (Meteor._reload && Meteor._reload.reload) { // make it compatible with old meteor
							Meteor._reload.reload();
						} else {
							Reload._reload();
						}
					}, 1000);
				}
			}
			if (error) {
				return handleError(error);
			}
		});
	};

	this.downloadMyData = function(fullExport = false) {
		Meteor.call('requestDataDownload', { fullExport }, function(error, results) {
			if (results) {
				if (results.requested) {
					modal.open({
						title: t('UserDataDownload_Requested'),
						text: t('UserDataDownload_Requested_Text', { pending_operations: results.pendingOperationsBeforeMyRequest }),
						type: 'success',
						html: true,
					});

					return true;
				}

				if (results.exportOperation) {
					if (results.exportOperation.status === 'completed') {
						const text = results.url
							? TAPi18n.__('UserDataDownload_CompletedRequestExistedWithLink_Text', { download_link: results.url })
							: t('UserDataDownload_CompletedRequestExisted_Text');

						modal.open({
							title: t('UserDataDownload_Requested'),
							text,
							type: 'success',
							html: true,
						});

						return true;
					}

					modal.open({
						title: t('UserDataDownload_Requested'),
						text: t('UserDataDownload_RequestExisted_Text', { pending_operations: results.pendingOperationsBeforeMyRequest }),
						type: 'success',
						html: true,
					});
					return true;
				}

				modal.open({
					title: t('UserDataDownload_Requested'),
					type: 'success',
				});
				return true;
			}

			if (error) {
				return handleError(error);
			}
		});
	};

	this.exportMyData = function() {
		this.downloadMyData(true);
	};
});

Template.accountPreferences.onRendered(function() {
	Tracker.afterFlush(function() {
		SideNav.setFlex('accountFlex');
		SideNav.openFlex();
	});
});

Template.accountPreferences.events({
	'click .rc-header__section-button .save'(e, t) {
		t.save();
	},
	'change input[name=useEmojis]'(e, t) {
		t.useEmojis.set($(e.currentTarget).val() === '1');
	},
	'click .download-my-data'(e, t) {
		e.preventDefault();
		t.downloadMyData();
	},
	'click .export-my-data'(e, t) {
		e.preventDefault();
		t.exportMyData();
	},
	'click .js-test-notifications'(e) {
		e.preventDefault();
		KonchatNotification.notify({
			duration: $('input[name=desktopNotificationDuration]').val(),
			payload: { sender: { username: 'rocket.cat' },
			},
			title: TAPi18n.__('Desktop_Notification_Test'),
			text: TAPi18n.__('This_is_a_desktop_notification'),
		});
	},
	'click .js-enable-notifications'() {
		KonchatNotification.getDesktopPermission();
	},
	'change .audio'(e) {
		e.preventDefault();
		const audio = $(e.currentTarget).val();
		if (audio === 'none') {
			return;
		}
		if (audio) {
			CustomSounds.play(audio);
		}
	},
	'click .js-dont-ask-remove'(e) {
		e.preventDefault();
		const selectEl = document.getElementById('dont-ask');
		for (let i = selectEl.options.length - 1; i >= 0; i--) {
			if (selectEl.options[i].selected) {
				selectEl.remove(i);
			}
		}
	},
});
<|endoftext|>


<commit_before>import React from 'react';
import JsDiff from 'diff';
import { blue50, blue800, red50, red800, black, fullWhite } from 'material-ui/styles/colors';

import CommentBodyText from '/imports/ui/components/commentary/comments/CommentBodyText';

/*
	helpers
*/

const stripHTMLFromText = (htmlText) => {
	const tempElem = document.createElement('div');
	tempElem.innerHTML = htmlText;
	return tempElem.textContent || tempElem.innerText || '';
};

const getRevisionDiff = (comment, revisionIndex) => {
	// build the diff view and return a DOM node
	const baseRevision = comment.revisions[revisionIndex];
	const newRevision = comment.revisions[comment.revisions.length - 1];

	const revisionDiff = document.createElement('comment-diff');

	const baseRevisionText = stripHTMLFromText(baseRevision.text);
	const newRevisionText = stripHTMLFromText(newRevision.text);

	const diff = JsDiff.diffWordsWithSpace(baseRevisionText, newRevisionText);

	diff.forEach((part) => {
		// green for additions, red for deletions
		let color = black;
		let background = fullWhite;
		const span = document.createElement('span');

		if (part.added) {
			color = blue800;
			background = blue50;
		} else if (part.removed) {
			color = red800;
			background = red50;
			span.style.textDecoration = 'line-through';
		}

		span.style.color = color;
		span.style.background = background;
		span.style.padding = '0px';

		span.appendChild(document
			.createTextNode(part.value));
		revisionDiff.appendChild(span);
	});

	return revisionDiff;
};

/*
	BEGIN CommentBody
*/
const CommentBody = (props) => {

	if (props.revisionIndex === props.comment.revisions.length - 1) {
		return (
			<CommentBodyText
				text={props.comment.revisions[props.revisionIndex].text}
				onTextClick={props.onTextClick}
				createRevisionMarkup
				searchTerm={props.searchTerm}
			/>
		);
	}

	return (
		<CommentBodyText
			text={getRevisionDiff(props.comment, props.revisionIndex).innerHTML}
			searchTerm={props.searchTerm}
		/>
	);
};
CommentBody.propTypes = {
	comment: React.PropTypes.shape({
		revisions: React.PropTypes.arrayOf(React.PropTypes.shape({
			text: React.PropTypes.string.isRequired,
		})),
	}).isRequired,
	revisionIndex: React.PropTypes.number.isRequired,
	onTextClick: React.PropTypes.func,
	searchTerm: React.PropTypes.string
};
CommentBody.defaultProps = {
	onTextClick: null,
};
/*
	END CommentBody
*/

export default CommentBody;
<commit_msg>only use revision diff markup for the revisions following the most recent<commit_after>import React from 'react';
import JsDiff from 'diff';
import { blue50, blue800, red50, red800, black, fullWhite } from 'material-ui/styles/colors';

import CommentBodyText from '/imports/ui/components/commentary/comments/CommentBodyText';

/*
	helpers
*/

const stripHTMLFromText = (htmlText) => {
	const tempElem = document.createElement('div');
	tempElem.innerHTML = htmlText;
	return tempElem.textContent || tempElem.innerText || '';
};

const getRevisionDiff = (comment, revisionIndex) => {
	// build the diff view and return a DOM node
	const baseRevision = comment.revisions[revisionIndex];
	const newRevision = comment.revisions[comment.revisions.length - 1];

	const revisionDiff = document.createElement('comment-diff');

	const baseRevisionText = stripHTMLFromText(baseRevision.text);
	const newRevisionText = stripHTMLFromText(newRevision.text);

	const diff = JsDiff.diffWordsWithSpace(baseRevisionText, newRevisionText);

	diff.forEach((part) => {
		// green for additions, red for deletions
		let color = black;
		let background = fullWhite;
		const span = document.createElement('span');

		if (part.added) {
			color = blue800;
			background = blue50;
		} else if (part.removed) {
			color = red800;
			background = red50;
			span.style.textDecoration = 'line-through';
		}

		span.style.color = color;
		span.style.background = background;
		span.style.padding = '0px';

		span.appendChild(document
			.createTextNode(part.value));
		revisionDiff.appendChild(span);
	});

	return revisionDiff;
};

/*
	BEGIN CommentBody
*/
const CommentBody = (props) => {

	if (props.revisionIndex === 0) {
		return (
			<CommentBodyText
				text={props.comment.revisions[props.revisionIndex].text}
				onTextClick={props.onTextClick}
				createRevisionMarkup
				searchTerm={props.searchTerm}
			/>
		);
	}

	return (
		<CommentBodyText
			text={getRevisionDiff(props.comment, props.revisionIndex).innerHTML}
			searchTerm={props.searchTerm}
		/>
	);
};
CommentBody.propTypes = {
	comment: React.PropTypes.shape({
		revisions: React.PropTypes.arrayOf(React.PropTypes.shape({
			text: React.PropTypes.string.isRequired,
		})),
	}).isRequired,
	revisionIndex: React.PropTypes.number.isRequired,
	onTextClick: React.PropTypes.func,
	searchTerm: React.PropTypes.string
};
CommentBody.defaultProps = {
	onTextClick: null,
};
/*
	END CommentBody
*/

export default CommentBody;
<|endoftext|>


<commit_before>register_namespace('player.control');

player.control.start = function(type, name) {
    ui.show_loader_fullscreen();
    player.playlist.clear();
    player.station.set(type, name);
    player.station.current.add_to_playlist(function(){
        player.playlist.current_track_num = 0;
        ui.hide_loader_fullscreen();
        ui.go_to_page('player');
        bridge.started();
        userdata.recent_stations.add(type, name);
        ui.update_track_info();
        ui.update_station_info();
        player.audio.set_file(player.playlist.get_current_track().mp3_url);
        player.audio.play();
        ui.update_track_controls();
        player.station.current.add_to_playlist();
        if (config.mode == 'vk') {
            network.vkontakte.callMethod('setLocation', type+'/'+util.string.urlencode(name));
        }
    });
};

player.control.stop = function() {
    ui.go_to_page('tune');
    bridge.stopped();
    player.audio.stop();
    if (config.mode == 'vk') {
        network.vkontakte.callMethod('setLocation', '');
    }
};

player.control.next = function() {
    function do_next() {
        player.playlist.current_track_num++;
        ui.update_track_info();
        player.audio.set_file(player.playlist.get_current_track().mp3_url);
        player.audio.play();
        ui.update_playlist()
        ui.update_track_controls();
        player.station.current.add_to_playlist();
    }
    if (player.playlist.playlist.length == player.playlist.current_track_num + 1) {
        player.station.current.add_to_playlist(do_next);
    } else {
        do_next();
    }
};

player.control.navigate = function(to) {
    player.playlist.current_track_num = parseInt(to);
    if (player.playlist.current_track_num < 0) {
        player.playlist.current_track_num = 0;
    }
    ui.update_track_info();
    player.audio.set_file(player.playlist.get_current_track().mp3_url);
    player.audio.play();
    ui.update_playlist();
    ui.update_track_controls();

};

player.control.previous = function() {
    player.control.navigate(player.playlist.current_track_num - 1);
};

player.control.pause = function() {
    player.audio.pause();
    ui.update_track_controls();
};

player.control.is_playing = function() {
    return player.audio.is_playing();
};<commit_msg>Закрываем результат поиска после старта.<commit_after>register_namespace('player.control');

player.control.start = function(type, name) {
    ui.show_loader_fullscreen();
    player.playlist.clear();
    player.station.set(type, name);
    player.station.current.add_to_playlist(function(){
        player.playlist.current_track_num = 0;
        ui.hide_loader_fullscreen();
        ui.go_to_page('player');
        $('#search-widget__clear').click();
        bridge.started();
        userdata.recent_stations.add(type, name);
        ui.update_track_info();
        ui.update_station_info();
        player.audio.set_file(player.playlist.get_current_track().mp3_url);
        player.audio.play();
        ui.update_track_controls();
        player.station.current.add_to_playlist();
        if (config.mode == 'vk') {
            network.vkontakte.callMethod('setLocation', type+'/'+util.string.urlencode(name));
        }
    });
};

player.control.stop = function() {
    ui.go_to_page('tune');
    bridge.stopped();
    player.audio.stop();
    if (config.mode == 'vk') {
        network.vkontakte.callMethod('setLocation', '');
    }
};

player.control.next = function() {
    function do_next() {
        player.playlist.current_track_num++;
        ui.update_track_info();
        player.audio.set_file(player.playlist.get_current_track().mp3_url);
        player.audio.play();
        ui.update_playlist()
        ui.update_track_controls();
        player.station.current.add_to_playlist();
    }
    if (player.playlist.playlist.length == player.playlist.current_track_num + 1) {
        player.station.current.add_to_playlist(do_next);
    } else {
        do_next();
    }
};

player.control.navigate = function(to) {
    player.playlist.current_track_num = parseInt(to);
    if (player.playlist.current_track_num < 0) {
        player.playlist.current_track_num = 0;
    }
    ui.update_track_info();
    player.audio.set_file(player.playlist.get_current_track().mp3_url);
    player.audio.play();
    ui.update_playlist();
    ui.update_track_controls();

};

player.control.previous = function() {
    player.control.navigate(player.playlist.current_track_num - 1);
};

player.control.pause = function() {
    player.audio.pause();
    ui.update_track_controls();
};

player.control.is_playing = function() {
    return player.audio.is_playing();
};<|endoftext|>


<commit_before>class wsConnection{
	constructor(){
		this.clientURL = 'ws://casadev.net:8000';
		this.clientProtocol = 'cec-protocol';

		this.client = new WebSocket(this.clientURL, this.clientProtocol);
		this.callbacks = {};
		this.client.addEventListener('message', (e)=>this.receiveMessage(e));
	}

	parseData(data){
		try{
			return JSON.parse(data)
		}catch(e){
			return undefined;
		}
	}

	onMessage(type, cb){
		this.callbacks[type] = cb;
	}

	receiveMessage(event){
		let msg = this.parseData(event.data)
		this.callbacks[msg.type](msg.data)
	}

	createMessage(action, data){
		return JSON.stringify({action, data});
	}

	cecAction(action, data){
		let msg = this.createMessage(action, data)
		this.client.send(msg)
	}
}

module.exports = new wsConnection()<commit_msg>update ws endpoint<commit_after>class wsConnection{
	constructor(){
		this.clientURL = 'ws://cec.casadev.net';
		this.clientProtocol = 'cec-protocol';

		this.client = new WebSocket(this.clientURL, this.clientProtocol);
		this.callbacks = {};
		this.client.addEventListener('message', (e)=>this.receiveMessage(e));
	}

	parseData(data){
		try{
			return JSON.parse(data)
		}catch(e){
			return undefined;
		}
	}

	onMessage(type, cb){
		this.callbacks[type] = cb;
	}

	receiveMessage(event){
		let msg = this.parseData(event.data)
		this.callbacks[msg.type](msg.data)
	}

	createMessage(action, data){
		return JSON.stringify({action, data});
	}

	cecAction(action, data){
		let msg = this.createMessage(action, data)
		this.client.send(msg)
	}
}

module.exports = new wsConnection()<|endoftext|>


<commit_before>App.addChild('MixPanel', {
  el: 'body',

  activate: function(){
    this.VISIT_MIN_TIME = 10000;
    this.user = null;
    this.controller = this.$el.data('controller');
    this.action = this.$el.data('action');
    this.user = this.$el.data('user');
    if(window.mixpanel){
      this.detectLogin();
      this.startTracking();
      this.trackFacebookShare();
      if(FB) {
        this.trackOnFacebookLike();
      }
    }
  },

  startTracking: function(){
    var self = this;
    this.trackPageVisit('projects', 'show', 'Visited project page');
    this.trackPageVisit('explore', 'index', 'Explored projects');
    this.trackPageLoad('contributions', 'show', 'Finished contribution');
    this.trackPageLoad('contributions', 'edit', 'Selected reward');
  },

  trackPageLoad: function(controller, action, text){
    var self = this;
    this.trackOnPage(controller, action, function(){
      self.track(text);
    });
  },

  trackPageVisit: function(controller, action, text){
    var self = this;
    this.trackOnPage(controller, action, function(){
      self.trackVisit(text);
    });
  },

  trackOnPage: function(controller, action, callback){
    if(this.controller == controller && this.action == action){
      callback();
    }
  },

  trackFacebookShare: function(event) {
    var self = this;
    $('a#facebook_share').on('click', function(event){
      self.trackFB('FB Like for project', event.currentTarget);
    });
  },

  trackOnFacebookLike: function() {
    var self = this;

    FB.Event.subscribe('edge.create', function(url, html_element){
      self.trackFB('FB Like for project', html_element)
    });

    FB.Event.subscribe('edge.remove', function(url, html_element){
      self.trackFB('FB Unlike for project', html_element)
    });
  },

  trackFB: function(text, element) {
    this.track(text, { ref: $(element).data('title') });
  },

  onLogin: function(){
    mixpanel.alias(this.user.id);
    if(this.user.sign_in_count == 1){
      this.track("Signed up");
    }
    else{
      this.track("Logged in");
    }
  },

  detectLogin: function(){
    if(this.user){
      if(this.user.id != store.get('user_id')){
        this.onLogin();
        store.set('user_id', this.user.id);
      }
    }
    else{
      store.set('user_id', null);
    }
  },

  identifyUser: function(){
    if (this.user){
      mixpanel.name_tag(this.user.email);
      mixpanel.identify(this.user.id);
      mixpanel.people.set({
        "$email": this.user.email,
        "$created": this.user.created_at,
        "$last_login": this.user.last_sign_in_at,
        "contributions": this.user.total_contributed_projects
      });
    }
  },

  track: function(text, options){
    this.identifyUser();
    var opt             = options || {};
    var obj             = $(this);
    var ref             = (obj.attr('href') != undefined) ? obj.attr('href') : (opt.ref ? opt.ref : null);
    var default_options = {
      'page name':          document.title,
      'user_id':            null,
      'created':            null,
      'last_login':         null,
      'contributions':      null,
      'has_contributions':  null,
      'project':            ref,
      'url':                window.location
    };
    if(this.user){
      default_options.user_id = this.user.id;
      default_options.created = this.user.created_at;
      default_options.last_login = this.user.last_sign_in_at;
      default_options.contributions = this.user.total_contributed_projects;
      default_options.has_contributions = (this.user.total_contributed_projects > 0);
    }
    var opt     = $.fn.extend(default_options, opt);

    mixpanel.track(text, opt);
  },

  mixPanelEvent: function(target, event, text, options){
    var self = this;
    this.$(target).on(event, function(){
      self.track(text, options);
    });
  },

  trackVisit: function(eventName){
    var self = this;
    window.setTimeout(function(){
      self.track(eventName);
    }, this.VISIT_MIN_TIME);
  }
});
<commit_msg>we dont need of this parameter<commit_after>App.addChild('MixPanel', {
  el: 'body',

  activate: function(){
    this.VISIT_MIN_TIME = 10000;
    this.user = null;
    this.controller = this.$el.data('controller');
    this.action = this.$el.data('action');
    this.user = this.$el.data('user');
    if(window.mixpanel){
      this.detectLogin();
      this.startTracking();
      this.trackFacebookShare();
      if(FB) {
        this.trackOnFacebookLike();
      }
    }
  },

  startTracking: function(){
    var self = this;
    this.trackPageVisit('projects', 'show', 'Visited project page');
    this.trackPageVisit('explore', 'index', 'Explored projects');
    this.trackPageLoad('contributions', 'show', 'Finished contribution');
    this.trackPageLoad('contributions', 'edit', 'Selected reward');
  },

  trackPageLoad: function(controller, action, text){
    var self = this;
    this.trackOnPage(controller, action, function(){
      self.track(text);
    });
  },

  trackPageVisit: function(controller, action, text){
    var self = this;
    this.trackOnPage(controller, action, function(){
      self.trackVisit(text);
    });
  },

  trackOnPage: function(controller, action, callback){
    if(this.controller == controller && this.action == action){
      callback();
    }
  },

  trackFacebookShare: function() {
    var self = this;
    $('a#facebook_share').on('click', function(event){
      self.trackFB('FB Like for project', event.currentTarget);
    });
  },

  trackOnFacebookLike: function() {
    var self = this;

    FB.Event.subscribe('edge.create', function(url, html_element){
      self.trackFB('FB Like for project', html_element)
    });

    FB.Event.subscribe('edge.remove', function(url, html_element){
      self.trackFB('FB Unlike for project', html_element)
    });
  },

  trackFB: function(text, element) {
    this.track(text, { ref: $(element).data('title') });
  },

  onLogin: function(){
    mixpanel.alias(this.user.id);
    if(this.user.sign_in_count == 1){
      this.track("Signed up");
    }
    else{
      this.track("Logged in");
    }
  },

  detectLogin: function(){
    if(this.user){
      if(this.user.id != store.get('user_id')){
        this.onLogin();
        store.set('user_id', this.user.id);
      }
    }
    else{
      store.set('user_id', null);
    }
  },

  identifyUser: function(){
    if (this.user){
      mixpanel.name_tag(this.user.email);
      mixpanel.identify(this.user.id);
      mixpanel.people.set({
        "$email": this.user.email,
        "$created": this.user.created_at,
        "$last_login": this.user.last_sign_in_at,
        "contributions": this.user.total_contributed_projects
      });
    }
  },

  track: function(text, options){
    this.identifyUser();
    var opt             = options || {};
    var obj             = $(this);
    var ref             = (obj.attr('href') != undefined) ? obj.attr('href') : (opt.ref ? opt.ref : null);
    var default_options = {
      'page name':          document.title,
      'user_id':            null,
      'created':            null,
      'last_login':         null,
      'contributions':      null,
      'has_contributions':  null,
      'project':            ref,
      'url':                window.location
    };
    if(this.user){
      default_options.user_id = this.user.id;
      default_options.created = this.user.created_at;
      default_options.last_login = this.user.last_sign_in_at;
      default_options.contributions = this.user.total_contributed_projects;
      default_options.has_contributions = (this.user.total_contributed_projects > 0);
    }
    var opt     = $.fn.extend(default_options, opt);

    mixpanel.track(text, opt);
  },

  mixPanelEvent: function(target, event, text, options){
    var self = this;
    this.$(target).on(event, function(){
      self.track(text, options);
    });
  },

  trackVisit: function(eventName){
    var self = this;
    window.setTimeout(function(){
      self.track(eventName);
    }, this.VISIT_MIN_TIME);
  }
});
<|endoftext|>


<commit_before>angular.module('voteApp').controller('editElectionController', function($scope, apiService) {

    $scope.alternatives = [];
    $scope.formFeedback = '';

    apiService.getElection()
        .success(function(data) {
            $scope.alternatives = data.alternatives;
        });

    $scope.addAlternative = function(alternative) {
        apiService.addAlternative(alternative.title)
            .success(function(data) {
                $scope.alternatives.push(data);
                $scope.formFeedback = 'Alternativ lagret';
            })
        .error(function(data, status) {
                $scope.formFeedback = 'Noe gikk galt med lagring av alternativ';
            });
    };

});
<commit_msg>Fix indent<commit_after>angular.module('voteApp').controller('editElectionController', function($scope, apiService) {

    $scope.alternatives = [];
    $scope.formFeedback = '';

    apiService.getElection()
        .success(function(data) {
            $scope.alternatives = data.alternatives;
        });

    $scope.addAlternative = function(alternative) {
        apiService.addAlternative(alternative.title)
            .success(function(data) {
                $scope.alternatives.push(data);
                $scope.formFeedback = 'Alternativ lagret';
            })
            .error(function(data, status) {
                $scope.formFeedback = 'Noe gikk galt med lagring av alternativ';
            });
    };

});
<|endoftext|>


<commit_before>// Email address
(function(){
  var words = [
    'hamster',
    'paraphernalia',
    'perluette',

    // http://marvin.cs.uidaho.edu/misspell.html
    'accessible',
    'accidentally',
    'definitely',
    'fuchsia',
    'mayonnaise',
    'mosquito',
    'occurrence',
    'orangutan',
    'pamphlet',
    'syllable',
    'vinaigrette',
    'wildebeest',
    'zucchini',
    'xylophone',
  ]

  // http://stackoverflow.com/questions/11935175/sampling-a-random-subset-from-an-array
  var word = words[Math.floor(Math.random()*words.length)]
  var chainsaw=[word,'thomaslevine.com'].join('@')
  var epost = document.getElementById("e-post")
  if (epost){
    epost.innerHTML=chainsaw
  }
})()

$(function(){
  setTimeout(function(){
    $('#feedback').fadeIn()
  }, 30 * 1000)
})
<commit_msg>longer wait<commit_after>// Email address
(function(){
  var words = [
    'hamster',
    'paraphernalia',
    'perluette',

    // http://marvin.cs.uidaho.edu/misspell.html
    'accessible',
    'accidentally',
    'definitely',
    'fuchsia',
    'mayonnaise',
    'mosquito',
    'occurrence',
    'orangutan',
    'pamphlet',
    'syllable',
    'vinaigrette',
    'wildebeest',
    'zucchini',
    'xylophone',
  ]

  // http://stackoverflow.com/questions/11935175/sampling-a-random-subset-from-an-array
  var word = words[Math.floor(Math.random()*words.length)]
  var chainsaw=[word,'thomaslevine.com'].join('@')
  var epost = document.getElementById("e-post")
  if (epost){
    epost.innerHTML=chainsaw
  }
})()

$(function(){
  setTimeout(function(){
    $('#feedback').fadeIn()
  }, 2 * 60 * 1000)
})
<|endoftext|>


<commit_before>/*global one*/
one.include('lib:one/color.js');

one.color.Interpolator = function (startColor, endColor, minValue, maxValue) {
    startColor = one.color.parse(startColor).rgb();
    endColor = one.color.parse(endColor).rgb();
    if (maxValue === minValue) {
        return function () {
            return startColor;
        };
    }
    var deltaR = endColor._red - startColor._red,
        deltaG = endColor._green - startColor._green,
        deltaB = endColor._blue - startColor._blue;
    return function (value) {
        var intensity = (value - minValue) / (maxValue - minValue);
        return new one.color.RGB(
            startColor._red + deltaR * intensity,
            startColor._green + deltaG * intensity,
            startColor._blue + deltaB * intensity
        );
    };
};
<commit_msg>Fixed one.color.Interpolator.<commit_after>/*global one*/
one.include('lib:one/color.js');

one.color.Interpolator = function (startColor, endColor, minValue, maxValue) {
    startColor = one.color(startColor).rgb();
    endColor = one.color(endColor).rgb();
    if (maxValue === minValue) {
        return function () {
            return startColor;
        };
    }
    var deltaR = endColor._red - startColor._red,
        deltaG = endColor._green - startColor._green,
        deltaB = endColor._blue - startColor._blue;
    return function (value) {
        var intensity = (value - minValue) / (maxValue - minValue);
        return new one.color.RGB(
            startColor._red + deltaR * intensity,
            startColor._green + deltaG * intensity,
            startColor._blue + deltaB * intensity
        );
    };
};
<|endoftext|>


<commit_before>/*
===============================================================================================

    Unify Project

    Homepage: unify-project.org
    License: MIT + Apache (V2)
    Copyright: 2012, Sebastian Fastner, Mainz, Germany, http://unify-training.com

===============================================================================================
*/

core.Class("unify.theme.Theme", {
  construct : function(theme) {
    var colors = this.__colors = {};
    var fonts = this.__fonts = {};
    var styles = this.__styles = {};

    this.__styleCache = {};

    this._parse(theme, colors, fonts, styles);
  },

  members : {
    __styleCache : null,

    /* PUBLIC API */

    name : function() {
      return this.__name;
    },

    resolveColor : function(name) {
      var result = this.__colors[name] || null;
      if (core.Env.getValue("debug")) {
        if (!result) {
          console.warn("Color " + name + " not found!");
        }
      }
      return result;
    },

    resolveFont : function(name) {
      var result = this.__fonts[name] || null;
      if (core.Env.getValue("debug")) {
        if (!result) {
          console.warn("Font " + name + " not found!");
        }
      }
      return result;
    },

    __runFunctionsFromArray : function(arrayOrFnt, states) {
      var res;

      if (typeof(arrayOrFnt) == "function") {
        res = arrayOrFnt(states);
      } else {
        res = {};
        for (var i=0,ii=arrayOrFnt.length; i<ii; i++) {
          var aof = arrayOrFnt[i];

          if (aof) {
            var r = this.__runFunctionsFromArray(aof, states);
            var k = Object.keys(r);
            for (var j=0, jj=k.length; j<jj; j++) {
              var key = k[j];
              res[key] = r[key];
            }
          }
        }
      }

      return res;
    },

    resolveStyle : function(name, states) {
      states = states || {};
      var id = name + "-" + Object.keys(states).sort().join("-");
      var result = this.__styleCache[id];
      if (result) {
        return result;
      }

      var style = this.__styles[name];

      if (!style) {
        if (core.Env.getValue("debug") && style !== null) {
          console.log("No style '" + name + "' found");
        }
        return null;
      }

      var styles = this.__runFunctionsFromArray(style, states);

      var colorTags = ["color", "backgroundColor", "borderColor", "borderTopColor", "borderLeftColor", "borderRightColor", "borderBottomColor"];
      for (var i=0,ii=colorTags.length; i<ii; i++) {
        var tag = colorTags[i];
        if (styles[tag]) {
          styles[tag] = this.resolveColor(styles[tag]);
        }
      }
      var textColor = styles.font && styles.font.textColor;
      var color = styles.font && styles.font.color;
      if (textColor) {
        styles.font.textColor = this.resolveColor(textColor);
      }
      if (color) {
        styles.font.color = this.resolveColor(color);
      }

      // Cache only if not in debug mode
      this.__styleCache[id] = styles;

      return styles;
    },

    getParsedTheme : function() {
      return {
        colors: this.__colors,
        fonts: this.__fonts,
        styles: this.__styles
      };
    },

    /* PRIVATE */

    __colors : null,
    __fonts : null,
    __styles : null,
    __name : null,

    _parse : function(theme, themeColors, themeFonts, themeStyles) {
      if (core.Env.getValue("debug")) {
        if (!theme) {
          throw new Error("No theme given!");
        }
      }

      var keys;
      var i;
      var ii;

      var name = theme.name;
      if (name) {
        this.__name = name;
      }

      if (theme.include) {
        var includedTheme = theme.include.getParsedTheme();
        var colors = includedTheme.colors;
        var fonts = includedTheme.fonts;
        var styles = includedTheme.styles;
        var key;

        for (key in colors) {
          themeColors[key] = colors[key];
        }
        for (key in fonts) {
          themeFonts[key] = fonts[key];
        }
        for (key in styles) {
          themeStyles[key] = styles[key];
        }
      }

      var colors = theme.colors;
      if (colors) {
        keys = Object.keys(colors);
        var colorMap = themeColors;

        for (i=0,ii=keys.length; i<ii; i++) {
          var colorName = keys[i];
          var color = colors[colorName];

          colorMap[colorName] = color;
        }
      }

      var fonts = theme.fonts;
      if (fonts) {
        keys = Object.keys(fonts);
        var fontMap = themeFonts;

        for (i=0,ii=keys.length; i<ii; i++) {
          var fontName = keys[i];
          var font = this.__parseFont(fonts[fontName]);

          fontMap[fontName] = font;
        }
      }

      var styles = theme.styles;
      if (styles) {
        this.__parseStyles(styles, themeStyles);
      }
    },

    __parseFont : function(font) {
      var def = {
        fontSize: "16px",
        fontStyle: "normal",
        fontWeight: "normal",
        textDecoration: "none",
        lineHeight: 1.0
      };

      if (font.family) {
        def.fontFamily = font.family;
      }
      if (font.size) {
        def.fontSize = font.size + "px";
      }
      if (font.style) {
        def.fontStyle = font.style;
      }
      if (font.weight) {
        def.fontWeight = font.weight;
      }
      if (font.decoration) {
        def.textDecoration = font.decoration;
      }
      if (font.lineHeight) {
        def.lineHeight = font.lineHeight;
      }
      if (font.src) {
        def.fontObject = new lowland.bom.Font(font.src);
      }

      return def;
    },

    __parseStyles : function(styles, themeStyles) {
      var styleMap = themeStyles;

      var includeHelper = [];
      var includes = {};
      var childControls = [];

      var keys = Object.keys(styles);
      for (var i=0,ii=keys.length; i<ii; i++) {
        var key = keys[i];
        var value = styles[key];

        var slashPos = key.indexOf("/");
        if (slashPos > -1) {
          var first = key.substring(0, slashPos);
          var second = key.substring(slashPos+1);

          childControls.push({main: first, control: second});
        }

        if (typeof value == "string") {
          // construct is "a" : "b"

          includeHelper.push({
            key: key,
            include: value
          });
        } else {
          if (value.include) {
            includeHelper.push({
              key: key,
              include: value.include
            });
          }
          if (value.style) {
            if (styleMap[key]) {
              styleMap[key] = [styleMap[key], value.style];
            } else {
              styleMap[key] = value.style;
            }
          } else {
            styleMap[key] = null;
          }
        }
      }

      var task;

      for (i=0,ii=includeHelper.length; i<ii; i++) {
        task = includeHelper[i];

        if (includes[task.include]) {
          includes[task.include].push(task.key);
        } else {
          includes[task.include] = [task.key];
        }

        var keyFnt = styleMap[task.key];
        if (keyFnt) {
          styleMap[task.key] = [styleMap[task.include], keyFnt];
        } else {
          styleMap[task.key] = styleMap[task.include];
        }
      }

      for (i=0,ii=childControls.length; i<ii; i++) {
        task = childControls[i];
        var nFnt = styleMap[task.main + "/" + task.control];

        var incl = includes[task.main];
        if (incl) {
          for (var j=0,jj=incl.length; j<jj; j++) {
            var origName = incl[j] + "/" + task.control;
            var sm = styleMap[origName];

            if (!sm) {
              // Set only if no styling is set by developer
              styleMap[origName] = nFnt;
            }
          }
        }
      }
    }

  }
});<commit_msg>Added possibility to include more than one base style in theme<commit_after>/*
===============================================================================================

    Unify Project

    Homepage: unify-project.org
    License: MIT + Apache (V2)
    Copyright: 2012, Sebastian Fastner, Mainz, Germany, http://unify-training.com

===============================================================================================
*/

core.Class("unify.theme.Theme", {
  construct : function(theme) {
    var colors = this.__colors = {};
    var fonts = this.__fonts = {};
    var styles = this.__styles = {};

    this.__styleCache = {};

    this._parse(theme, colors, fonts, styles);
  },

  members : {
    __styleCache : null,

    /* PUBLIC API */

    name : function() {
      return this.__name;
    },

    resolveColor : function(name) {
      var result = this.__colors[name] || null;
      if (core.Env.getValue("debug")) {
        if (!result) {
          console.warn("Color " + name + " not found!");
        }
      }
      return result;
    },

    resolveFont : function(name) {
      var result = this.__fonts[name] || null;
      if (core.Env.getValue("debug")) {
        if (!result) {
          console.warn("Font " + name + " not found!");
        }
      }
      return result;
    },

    __runFunctionsFromArray : function(arrayOrFnt, states) {
      var res;

      if (typeof(arrayOrFnt) == "function") {
        res = arrayOrFnt(states);
      } else {
        res = {};
        for (var i=0,ii=arrayOrFnt.length; i<ii; i++) {
          var aof = arrayOrFnt[i];

          if (aof) {
            var r = this.__runFunctionsFromArray(aof, states);
            var k = Object.keys(r);
            for (var j=0, jj=k.length; j<jj; j++) {
              var key = k[j];
              res[key] = r[key];
            }
          }
        }
      }

      return res;
    },

    resolveStyle : function(name, states) {
      states = states || {};
      var id = name + "-" + Object.keys(states).sort().join("-");
      var result = this.__styleCache[id];
      if (result) {
        return result;
      }

      var style = this.__styles[name];

      if (!style) {
        if (core.Env.getValue("debug") && style !== null) {
          console.log("No style '" + name + "' found");
        }
        return null;
      }

      var styles = this.__runFunctionsFromArray(style, states);

      var colorTags = ["color", "backgroundColor", "borderColor", "borderTopColor", "borderLeftColor", "borderRightColor", "borderBottomColor"];
      for (var i=0,ii=colorTags.length; i<ii; i++) {
        var tag = colorTags[i];
        if (styles[tag]) {
          styles[tag] = this.resolveColor(styles[tag]);
        }
      }
      var textColor = styles.font && styles.font.textColor;
      var color = styles.font && styles.font.color;
      if (textColor) {
        styles.font.textColor = this.resolveColor(textColor);
      }
      if (color) {
        styles.font.color = this.resolveColor(color);
      }

      // Cache only if not in debug mode
      this.__styleCache[id] = styles;

      return styles;
    },

    getParsedTheme : function() {
      return {
        colors: this.__colors,
        fonts: this.__fonts,
        styles: this.__styles
      };
    },

    /* PRIVATE */

    __colors : null,
    __fonts : null,
    __styles : null,
    __name : null,

    _parse : function(theme, themeColors, themeFonts, themeStyles) {
      if (core.Env.getValue("debug")) {
        if (!theme) {
          throw new Error("No theme given!");
        }
      }

      var keys;
      var i;
      var ii;

      var name = theme.name;
      if (name) {
        this.__name = name;
      }

      if (theme.include) {
        var includedTheme = theme.include.getParsedTheme();
        var colors = includedTheme.colors;
        var fonts = includedTheme.fonts;
        var styles = includedTheme.styles;
        var key;

        for (key in colors) {
          themeColors[key] = colors[key];
        }
        for (key in fonts) {
          themeFonts[key] = fonts[key];
        }
        for (key in styles) {
          themeStyles[key] = styles[key];
        }
      }

      var colors = theme.colors;
      if (colors) {
        keys = Object.keys(colors);
        var colorMap = themeColors;

        for (i=0,ii=keys.length; i<ii; i++) {
          var colorName = keys[i];
          var color = colors[colorName];

          colorMap[colorName] = color;
        }
      }

      var fonts = theme.fonts;
      if (fonts) {
        keys = Object.keys(fonts);
        var fontMap = themeFonts;

        for (i=0,ii=keys.length; i<ii; i++) {
          var fontName = keys[i];
          var font = this.__parseFont(fonts[fontName]);

          fontMap[fontName] = font;
        }
      }

      var styles = theme.styles;
      if (styles) {
        this.__parseStyles(styles, themeStyles);
      }
    },

    __parseFont : function(font) {
      var def = {
        fontSize: "16px",
        fontStyle: "normal",
        fontWeight: "normal",
        textDecoration: "none",
        lineHeight: 1.0
      };

      if (font.family) {
        def.fontFamily = font.family;
      }
      if (font.size) {
        def.fontSize = font.size + "px";
      }
      if (font.style) {
        def.fontStyle = font.style;
      }
      if (font.weight) {
        def.fontWeight = font.weight;
      }
      if (font.decoration) {
        def.textDecoration = font.decoration;
      }
      if (font.lineHeight) {
        def.lineHeight = font.lineHeight;
      }
      if (font.src) {
        def.fontObject = new lowland.bom.Font(font.src);
      }

      return def;
    },

    __parseStyles : function(styles, themeStyles) {
      var styleMap = themeStyles;

      var includeHelper = [];
      var includes = {};
      var childControls = [];

      var keys = Object.keys(styles);
      for (var i=0,ii=keys.length; i<ii; i++) {
        var key = keys[i];
        var value = styles[key];

        var slashPos = key.indexOf("/");
        if (slashPos > -1) {
          var first = key.substring(0, slashPos);
          var second = key.substring(slashPos+1);

          childControls.push({main: first, control: second});
        }

        if (typeof value == "string") {
          // construct is "a" : "b"

          includeHelper.push({
            key: key,
            include: value
          });
        } else {
          if (value.include) {
            if (typeof value.include === 'string') {
              value.include = [ value.include ];
            }

            for (var k = 0, l = value.include.length; k < l; k++) {
              includeHelper.push({
                key: key,
                include: value.include[k]
              });
            }
          }
          if (value.style) {
            if (styleMap[key]) {
              styleMap[key] = [styleMap[key], value.style];
            } else {
              styleMap[key] = value.style;
            }
          } else {
            styleMap[key] = null;
          }
        }
      }

      var task;

      for (i=0,ii=includeHelper.length; i<ii; i++) {
        task = includeHelper[i];

        if (includes[task.include]) {
          includes[task.include].push(task.key);
        } else {
          includes[task.include] = [task.key];
        }

        var keyFnt = styleMap[task.key];
        if (keyFnt) {
          styleMap[task.key] = [styleMap[task.include], keyFnt];
        } else {
          styleMap[task.key] = styleMap[task.include];
        }
      }

      for (i=0,ii=childControls.length; i<ii; i++) {
        task = childControls[i];
        var nFnt = styleMap[task.main + "/" + task.control];

        var incl = includes[task.main];
        if (incl) {
          for (var j=0,jj=incl.length; j<jj; j++) {
            var origName = incl[j] + "/" + task.control;
            var sm = styleMap[origName];

            if (!sm) {
              // Set only if no styling is set by developer
              styleMap[origName] = nFnt;
            }
          }
        }
      }
    }

  }
});<|endoftext|>


<commit_before>// construct query string
var params = d3.select("h1#api_key");
if (!params.empty()) {
  var api_key = params.attr('data-api_key');
  var uid_type = params.attr('data-uid_type');
  var uid = params.attr('data-uid');
  var query = encodeURI("/api/v5/articles?api_key=" + api_key + "&ids=" + uid + "&type=" + uid_type);
}

// load the data from the ALM API
if (query) {
  d3.json(query, function(error, json) {
    if (error) return console.warn(error);

    eventViz(json);
  });
}

// add data to page
function eventViz(json) {
  data = json['data'];

  d3.select.select("#loading").remove();

  // keep only sources with events
  data = data.filter(function(d) { return d.events.length > 0; });

  for (var i=0; i<data.length; i++) {
    item = data[i];
  }

  // d3.select("#update_date").html(formatTime(inputTime.parse(data["update_date"])));

  // // Summary table
  // d3.select("#response_count").html(numberWithDelimiter(data["responses"]["count"]));

  // d3.select("#average_count").html(numberWithDelimiter(data["responses"]["average"]));
  // d3.select("#maximum_count").html(numberWithDelimiter(data["responses"]["maximum"]));

  // d3.select("#article_count").html(numberWithDelimiter(data["article_count"]));
  // d3.select("#event_count").html(numberWithDelimiter(data["event_count"]));
};
<commit_msg>first d3 code to show events<commit_after>// construct query string
var params = d3.select("h1#api_key");
if (!params.empty()) {
  var api_key = params.attr('data-api_key');
  var uid_type = params.attr('data-uid_type');
  var uid = params.attr('data-uid');
  var query = encodeURI("/api/v5/articles?api_key=" + api_key + "&ids=" + uid + "&type=" + uid_type);
}

// load the data from the ALM API
if (query) {
  d3.json(query, function(error, json) {
    if (error) return console.warn(error);

    eventViz(json);
  });
}

// add data to page
function eventViz(json) {
  data = json['data'];

  d3.select.select("#loading").remove();

  // keep only sources with events
  data = data.filter(function(d) { return d.events.length > 0; });

  for (var i=0; i<data.length; i++) {
    item = data[i];
    console.log(item.events[0]);
  }

  // d3.select("#update_date").html(formatTime(inputTime.parse(data["update_date"])));

  // // Summary table
  // d3.select("#response_count").html(numberWithDelimiter(data["responses"]["count"]));

  // d3.select("#average_count").html(numberWithDelimiter(data["responses"]["average"]));
  // d3.select("#maximum_count").html(numberWithDelimiter(data["responses"]["maximum"]));

  // d3.select("#article_count").html(numberWithDelimiter(data["article_count"]));
  // d3.select("#event_count").html(numberWithDelimiter(data["event_count"]));
};
<|endoftext|>