<commit_before>// This file is required by the index.html file and will
// be executed in the renderer process for that window.
// All of the Node.js APIs are available in this process.

const sharp = require('sharp');
const _ = require('underscore');
const path = require('path');
const url = require('url');
const appVersion = require('electron').remote.app.getVersion();

const version = "0.1";

var imageSelector = document.querySelector("#image-selector");
var convertButton = document.querySelector("#convert-button");
var statusText = document.querySelector("#status-text");
var loader = document.querySelector("#loader");

var layers = {'logo-landscape': __dirname + '/assets/images/logo-landscape.png',
              'logo-portrait': __dirname + '/assets/images/logo-portrait.png'};

console.log(layers);

var converted = 0;
var files = [];
var images = [];

function updateStatus (status) {
  statusText.innerText = status;
};

function handleFileSelection () {
  converted = 0;
  files = imageSelector.files;
  console.log(files);
  if (files.length == 0) {
    convertButton.disabled = true;
    updateStatus("Vali logotamiseks mõned pildid.");
  } else if (files.length == 1) {
    convertButton.disabled = false;
    updateStatus("1 pilt logotamiseks valitud.");
  } else {
    convertButton.disabled = false;
    updateStatus(files.length + " pilti logotamiseks valitud.");
  }
};

function pasteLogo (image) {
  image.metadata().then(function(metadata) {
    console.log(metadata);
    if (metadata.width > metadata.height) {
      return image.overlayWith(layers['logo-landscape'], {top: 0, left: 750});
    } else {
      return image.overlayWith(layers['logo-portrait'], {top: 0, left: 468});
    }
  }).then(function (i) {
    return i;
  });
};

function writeImage(imageInfo) {
  var p = imageInfo[0];
  var image = imageInfo[1];
  var ext = path.extname(p);
  var dir = path.dirname(p);
  var base = path.basename(imageInfo[0], ext);
  var to = path.join(dir, base + "-logo") + ext;
  return image.jpeg({quality: 100}).webp({quality: 100}).tiff({quality: 100}).toFile(to);
};

function convertImages () {
  if (_.isEmpty(files)) {
    updateStatus("Vali logotamiseks mõned pildid.");
    return;
  }

  toggleProgressSpinner();
  convertButton.disabled = true;
  // images = _.map(files, function (f) { return [f.path, sharp(f.path)]; });
  // images = _.map(images, function(i) { return [i[0], pasteLogo(i[1])]; });
  // console.log(images);
  // var processes = _.map(images, writeImage);
  var processes = _.map(files, process);
  Promise.all(processes).then(function (values) {
    updateStatus(values.length + " pilti logotatud!");
    toggleProgressSpinner();
  }, function (reason) {
       console.log(reason);
       updateStatus("Midagi läks valesti. Mõni pilt jäi logotamata!");
       toggleProgressSpinner();
     });
};

function process(file) {
  var filePath = file.path;
  const image = sharp(filePath);

  image.metadata().then(function(metadata) {
    console.log(filePath, metadata);
    if (metadata.width > metadata.height) {
      return image.overlayWith(layers['logo-landscape'], {top: 0, left: 750});
    } else {
      return image.overlayWith(layers['logo-portrait'], {top: 0, left: 468});
    }
  }).then(function(newImage) {
    var ext = path.extname(filePath);
    var dir = path.dirname(filePath);
    var base = path.basename(filePath, ext);
    var to = path.join(dir, base + "-logo") + ext;
    return newImage.
      jpeg({quality: 100}).
      webp({quality: 100}).
      tiff({quality: 100}).
      toFile(to);
  });
};

function toggleProgressSpinner () {
  statusText.classList.toggle("is-hidden");
  loader.classList.toggle("is-hidden");
};

imageSelector.onchange = handleFileSelection;
convertButton.onclick = convertImages;

var title = document.getElementsByTagName("title")[0];
title.innerText = "Logotaja ver. " + appVersion;
<commit_msg>Resize before.<commit_after>// This file is required by the index.html file and will
// be executed in the renderer process for that window.
// All of the Node.js APIs are available in this process.

const sharp = require('sharp');
const _ = require('underscore');
const path = require('path');
const url = require('url');
const appVersion = require('electron').remote.app.getVersion();

const version = "0.1";

var imageSelector = document.querySelector("#image-selector");
var convertButton = document.querySelector("#convert-button");
var statusText = document.querySelector("#status-text");
var loader = document.querySelector("#loader");

var layers = {'logo-landscape': __dirname + '/assets/images/logo-landscape.png',
              'logo-portrait': __dirname + '/assets/images/logo-portrait.png'};

console.log(layers);

var converted = 0;
var files = [];
var images = [];

function updateStatus (status) {
  statusText.innerText = status;
};

function handleFileSelection () {
  converted = 0;
  files = imageSelector.files;
  console.log(files);
  if (files.length == 0) {
    convertButton.disabled = true;
    updateStatus("Vali logotamiseks mõned pildid.");
  } else if (files.length == 1) {
    convertButton.disabled = false;
    updateStatus("1 pilt logotamiseks valitud.");
  } else {
    convertButton.disabled = false;
    updateStatus(files.length + " pilti logotamiseks valitud.");
  }
};

function pasteLogo (image) {
  image.metadata().then(function(metadata) {
    console.log(metadata);
    if (metadata.width > metadata.height) {
      return image.overlayWith(layers['logo-landscape'], {top: 0, left: 750});
    } else {
      return image.overlayWith(layers['logo-portrait'], {top: 0, left: 468});
    }
  }).then(function (i) {
    return i;
  });
};

function writeImage(imageInfo) {
  var p = imageInfo[0];
  var image = imageInfo[1];
  var ext = path.extname(p);
  var dir = path.dirname(p);
  var base = path.basename(imageInfo[0], ext);
  var to = path.join(dir, base + "-logo") + ext;
  return image.jpeg({quality: 100}).webp({quality: 100}).tiff({quality: 100}).toFile(to);
};

function convertImages () {
  if (_.isEmpty(files)) {
    updateStatus("Vali logotamiseks mõned pildid.");
    return;
  }

  toggleProgressSpinner();
  convertButton.disabled = true;
  // images = _.map(files, function (f) { return [f.path, sharp(f.path)]; });
  // images = _.map(images, function(i) { return [i[0], pasteLogo(i[1])]; });
  // console.log(images);
  // var processes = _.map(images, writeImage);
  var processes = _.map(files, process);
  Promise.all(processes).then(function (values) {
    updateStatus(values.length + " pilti logotatud!");
    toggleProgressSpinner();
  }, function (reason) {
       console.log(reason);
       updateStatus("Midagi läks valesti. Mõni pilt jäi logotamata!");
       toggleProgressSpinner();
     });
};

function process(file) {
  var filePath = file.path;
  const image = sharp(filePath);

  image.metadata().then(function(metadata) {
    console.log(filePath, metadata);
    if (metadata.width > metadata.height) {
      return image
             .resize(1000, null, {})
             .overlayWith(layers['logo-landscape'], {top: 0, left: 750});
    } else {
      return image
             .resize(null, 1000, {})
             .overlayWith(layers['logo-portrait'], {top: 0, left: 468});
    }
  }).then(function(newImage) {
    var ext = path.extname(filePath);
    var dir = path.dirname(filePath);
    var base = path.basename(filePath, ext);
    var to = path.join(dir, base + "-logo") + ext;
    return newImage.
      jpeg({quality: 100}).
      webp({quality: 100}).
      tiff({quality: 100}).
      toFile(to);
  });
};

function toggleProgressSpinner () {
  statusText.classList.toggle("is-hidden");
  loader.classList.toggle("is-hidden");
};

imageSelector.onchange = handleFileSelection;
convertButton.onclick = convertImages;

var title = document.getElementsByTagName("title")[0];
title.innerText = "Logotaja ver. " + appVersion;
<|endoftext|>


<commit_before>export default class {

  constructor(storage, validator) {
    this.storage = storage;
    this.packageValidator = validator;
  }

  /*
  * First validates if package is valid
  * Adds a version to the package in filesystem or creates a new package
  * Sends a 201 to let npm know package was published
  */
  process(httpRequest, httpResponse) {
    let packageData = httpRequest.body;

    if (!packageData._attachments) {
      if (this.deprecateUpdater(packageData)) {
        httpResponse.status(200).send({
          ok: "packageJson udpated"
        });
        return;
      }
    }

    // Error checking
    if (this.packageValidator.doesPackageExist(packageData.name)) {
      try {
        if (this.packageValidator.doesVersionExist(packageData.name, packageData['dist-tags']['latest'])) {
          httpResponse.send("422, cannot publish, version already exists");
          return;
        }
      } catch (err) {
        httpResponse.send("422, cannot publish, filesystem error");
        return;
      }

      let distTag;
      for (let key in packageData['dist-tags']) {
        distTag = key;
      }

      if (this.packageValidator.hasDistTag(packageData.name, distTag)) {
        if (!this.packageValidator.isVersionHigher(packageData.name, packageData['dist-tags'][distTag], distTag)) {
          httpResponse.send("423, cannot publish, given version is invalid");
          return;
        }
      }

      try {
        this.storage.writePackage(packageData);
      } catch (err) {
        httpResponse.send("421, " + err.toString());
        return;
      }
    }

    // Package doesn't exist yet
    else {
      try {
        this.storage.writeNewPackage(packageData);
      } catch (err) {
        httpResponse.send("421, " + err.toString());
        return;
      }
    }

    httpResponse.status(201);
    httpResponse.send({
      ok: "package published"
    });
  }

  deprecateUpdater(packageData) {
    return this.storage.updatePackageJson(packageData.name, packageData);
  }

}<commit_msg>Make package publish route asynchronous<commit_after>export default class {

  constructor(storage, validator) {
    this.storage = storage;
    this.packageValidator = validator;
  }

  /*
  * First validates if package is valid
  * Adds a version to the package in filesystem or creates a new package
  * Sends a 201 to let npm know package was published
  */
  process(httpRequest, httpResponse) {
    return new Promise((resolve, reject) => {
    let packageData = httpRequest.body;

    if (!packageData._attachments) {
      this.deprecateUpdater(packageData).then((result) => {
        if (result) {
          httpResponse.status(200).send({
            ok: "packageJson updated"
          });
          resolve();
        } else {
          reject("420, error: cannot update");
        }
      });
    }

    this.packageValidator.doesPackageExist(packageData.name)
      .then((result) => {
      if (result === true) {
        this.packageValidator.doesVersionExist(packageData.name, packageData['dist-tags']['latest'])
          .then((result) => {
          if (result === true) {
            reject("422, cannot publish, version already exists");
          } else {

            let distTag;
            for (let key in packageData['dist-tags']) {
              distTag = key;
            }

            this.packageValidator.hasDistTag(packageData.name, distTag).then((result) =>  {
              if (result === true) {
                this.packageValidator.isVersionHigher(packageData.name, packageData['dist-tags'][distTag], distTag).then((result) => {
                  if (result === false) {
                    reject("423, cannot publish, given version is invalid");
                  }
                  else {
                    this.storage.writePackage(packageData)
                      .then((result) => {
                        if (result === true) {
                          httpResponse.status(201);
                          httpResponse.send({
                            ok: "package published"
                          });
                          resolve()
                        } else {
                          reject("421, error while writing package");
                        }
                      });
                  }
                })
              } else {
                reject("423, cannot publish, given version is invalid");
              }
            });
          }});

      } else {
        this.storage.writeNewPackage(packageData)
          .then((result) => {
            if (result === true) {
              httpResponse.status(201);
              httpResponse.send({
                ok: "package published"
              });
              resolve();
            } else {
              reject("421, error while writing package");
            }
          })
        }
      });
    }).catch((err) => {
      httpResponse.send(err);
    })
  }

  deprecateUpdater(packageData) {
    return new Promise((resolve) => {
      this.storage.updatePackageJson(packageData.name, packageData).then((data) => {
        resolve(data);
      })
    });
  }

}<|endoftext|>


<commit_before>// This file is required by the index.html file and will
// be executed in the renderer process for that window.
// All of the Node.js APIs are available in this process.
<commit_msg>Remove unused renderer.js<commit_after><|endoftext|>


<commit_before>import React, {Component} from 'react';
import {Table} from 'react-bootstrap';
import {connect} from 'react-redux';
import _ from 'lodash';

class ResultsTable extends Component {

  render() {
    const notVoted = _.difference(this.props.users, this.props.results.map(x => x['userName']));
    return (

            User
            Vote

          {_sortedResults(this.props.results).map(x => _renderVoteRow(x))}
          {notVoted.map((x) => _renderUserRow(x))}

    );
  }
}

function _sortedResults(results) {
  const voteFreqs = _.countBy(results, x => x['estimateValue']);
  const countedResults = results.map(x => ({...x, ...{'count': voteFreqs[parseInt(x['estimateValue'], 10)]}}));
  return _.orderBy(countedResults, ['count', 'estimateValue', 'userName']);
}

function _renderUserRow(data) {
  return (

      {_.startCase(data)}
      -

  )
}

function _renderVoteRow(data) {
  return (

      {_.startCase(data.userName)}
      {data.estimateValue}

  )
}

function mapStateToProps(state) {
  return {
    results: state.results,
    users: state.users
  };
}

export default connect(mapStateToProps)(ResultsTable);
<commit_msg>rework ordering<commit_after>import React, {Component} from 'react';
import {Table} from 'react-bootstrap';
import {connect} from 'react-redux';
import _ from 'lodash';

class ResultsTable extends Component {

  render() {
    const notVoted = _.difference(this.props.users, this.props.results.map(x => x['userName']));
    return (

            User
            Vote

          {_sortedResults(this.props.results).map(x => _renderVoteRow(x))}
          {notVoted.map((x) => _renderUserRow(x))}

    );
  }
}

function _sortedResults(results) {
  const voteFreqs = _.countBy(results, x => x['estimateValue']);
  const countedResults = results.map(x => ({...x, ...{'count': voteFreqs[parseInt(x['estimateValue'], 10)]}}));
  return _.orderBy(countedResults, ['count', 'estimateValue', 'userName'], ['asc', 'asc', 'asc']);
}

function _renderUserRow(data) {
  return (

      {_.startCase(data)}
      -

  )
}

function _renderVoteRow(data) {
  return (

      {_.startCase(data.userName)}
      {data.estimateValue}

  )
}

function mapStateToProps(state) {
  return {
    results: state.results,
    users: state.users
  };
}

export default connect(mapStateToProps)(ResultsTable);
<|endoftext|>


<commit_before>import { Mongo } from 'meteor/mongo';

// patient_demographic is a collection with basic patient info
export const Patients = new Mongo.Collection('patient_demographic');

// datasample_second is a collection with patient data samples (per second)
export const Datasample_second = new Mongo.Collection('datasample_second');

// Explicitly deny any writes in the patient_demographic collection.
// This application is a "read only" app to display info, not to modify data
Patients.deny({
	insert : function(userid, doc){
		return true;
	}

	,update : function(userId, doc, fields, modifier){
		return true;
	}

	,remove : function(userId, doc){
		return true;
	}
});

// Explicitly deny any writes in the datasample_second collection.
// This application is a "read only" app to display info, not to modify data
Datasample_second.deny({
	insert : function(userid, doc){
		return true;
	}

	,update : function(userId, doc, fields, modifier){
		return true;
	}

	,remove : function(userId, doc){
		return true;
	}
});

if (Meteor.isServer) {

// Publication
  Meteor.publish('patients_demo', function patientsPublication() {
    return Patients.find();
  });

  Meteor.publish('datasample_second', function datasample_secondPublication() {
    return Datasample_second.find();
  });
}<commit_msg>New collection 'Assesment'<commit_after>import { Mongo } from 'meteor/mongo';

// patient_demographic is a collection with basic patient info
export const Patients = new Mongo.Collection('patient_demographic');

// datasample_second is a collection with patient data samples (per second)
export const Datasample_second = new Mongo.Collection('datasample_second');

//assesment is a doctor/user generated assesment (as opposed to a system-generated assesment)
export const Assesment = new Mongo.Collection('assesment');

// Explicitly deny any writes in the patient_demographic collection.
// This application is a "read only" app to display info, not to modify data
Patients.deny({
	insert : function(userid, doc){
		return true;
	}

	,update : function(userId, doc, fields, modifier){
		return true;
	}

	,remove : function(userId, doc){
		return true;
	}
});

// Explicitly deny any writes in the datasample_second collection.
// This application is a "read only" app to display info, not to modify data
Datasample_second.deny({
	insert : function(userid, doc){
		return true;
	}

	,update : function(userId, doc, fields, modifier){
		return true;
	}

	,remove : function(userId, doc){
		return true;
	}
});

if (Meteor.isServer) {

// Publication
  Meteor.publish('patients_demo', function patientsPublication() {
    return Patients.find();
  });

  Meteor.publish('datasample_second', function datasample_secondPublication() {
    return Datasample_second.find();
  });
}<|endoftext|>


<commit_before>var click = device.mobile() ? 'touchstart' : 'click';
$(function() {
	// 侧边栏操作按钮
	$(document).on(click, '#guide', function() {
		$(this).toggleClass('toggled');
		$('#sidebar').toggleClass('toggled');
	});
	// 侧边栏二级菜单
	$(document).on('click', '.sub-menu a', function() {
		$(this).next().slideToggle(200);
		$(this).parent().toggleClass('toggled');
	});
	// 个人资料
	$(document).on('click', '.s-profile a', function() {
		$(this).next().slideToggle(200);
		$(this).parent().toggleClass('toggled');
	});
	// Waves初始化
	Waves.displayEffect();
	// 滚动条初始化
	$('#sidebar').mCustomScrollbar({
		theme: 'minimal-dark',
		scrollInertia: 100,
		axis: 'yx',
		mouseWheel: {
			enable: true,
			axis: 'y',
			preventDefault: true
		}
	});
	// 切换系统
	$('.switch-systems').click(function () {
		var systemid = $(this).attr('systemid');
		var systemname = $(this).attr('systemname');
		var systemtitle = $(this).attr('systemtitle');
		$('.system_menus').hide(0, function () {
			$('.system_' + systemid).show();
		});
		$('body').attr("id", systemname);
		$('#system_title').text(systemtitle);
		$.cookie('zheng-upms-systemid', systemid);
		$.cookie('zheng-upms-systemname', systemname);
		$.cookie('zheng-upms-systemtitle', systemtitle);
	});
	// 显示cookie菜单
	var systemid = $.cookie('zheng-upms-systemid') || 1;
	var systemname = $.cookie('zheng-upms-systemname') || 'zheng-upms';
	var systemtitle = $.cookie('zheng-upms-systemtitle') || '权限管理系统';
	$('.system_menus').hide(0, function () {
		$('.system_' + systemid).show();
	});
	$('body').attr('id', systemname);
	$('#system_title').text(systemtitle);
});
// iframe高度自适应
function changeFrameHeight(ifm) {
	ifm.height = document.documentElement.clientHeight - 118;
}
function resizeFrameHeight() {
	$('.tab_iframe').css('height', document.documentElement.clientHeight - 118);
	$('md-tab-content').css('left', '0');
}
window.onresize = function() {
	resizeFrameHeight();
	initScrollShow();
	initScrollState();
}

// ========== 选项卡操作 ==========
$(function() {
	// 选项卡点击
	$(document).on('click', '.content_tab li', function() {
		// 切换选项卡
		$('.content_tab li').removeClass('cur');
		$(this).addClass('cur');
		// 切换iframe
		$('.iframe').removeClass('cur');
		$('#iframe_' + $(this).data('index')).addClass('cur');
		var marginLeft = ($('#tabs').css('marginLeft').replace('px', ''));
		// 滚动到可视区域:在左侧
		if ($(this).position().left < marginLeft) {
			var left = $('.content_tab>ul').scrollLeft() + $(this).position().left - marginLeft;
			$('.content_tab>ul').animate({scrollLeft: left}, 200, function() {
				initScrollState();
			});
		}
		// 滚动到可视区域:在右侧
		if(($(this).position().left + $(this).width() - marginLeft) > document.getElementById('tabs').clientWidth) {
			var left = $('.content_tab>ul').scrollLeft() + (($(this).position().left + $(this).width() - marginLeft) - document.getElementById('tabs').clientWidth);
			$('.content_tab>ul').animate({scrollLeft: left}, 200, function() {
				initScrollState();
			});
		}
	});
	// 控制选项卡滚动位置
	$(document).on('click', '.tab_left>a', function() {
		$('.content_tab>ul').animate({scrollLeft: $('.content_tab>ul').scrollLeft() - 300}, 200, function() {
			initScrollState();
		});
	});
	// 向右箭头
	$(document).on('click', '.tab_right>a', function() {
		$('.content_tab>ul').animate({scrollLeft: $('.content_tab>ul').scrollLeft() + 300}, 200, function() {
			initScrollState();
		});
	});
	// 初始化箭头状态

	// 选项卡右键菜单
	var menu = new BootstrapMenu('.tabs li', {
		fetchElementData: function(item) {
			return item;
		},
		actionsGroups: [
			['close', 'refresh'],
			['closeOther', 'closeAll'],
			['closeRight', 'closeLeft']
		],
		actions: {
			close: {
				name: '关闭',
				iconClass: 'zmdi zmdi-close',
				onClick: function(item) {
					Tab.closeTab($(item));
				}
			},
			closeOther: {
				name: '关闭其他',
				iconClass: 'zmdi zmdi-arrow-split',
				onClick: function(item) {
					var index = $(item).data('index');
					$('.content_tab li').each(function() {
						if ($(this).data('index') != index) {
							Tab.closeTab($(this));
						}
					});
				}
			},
			closeAll: {
				name: '关闭全部',
				iconClass: 'zmdi zmdi-swap',
				onClick: function() {
					$('.content_tab li').each(function() {
						Tab.closeTab($(this));
					});
				}
			},
			closeRight: {
				name: '关闭右侧所有',
				iconClass: 'zmdi zmdi-arrow-right',
				onClick: function(item) {
					var index = $(item).data('index');
					$($('.content_tab li').toArray().reverse()).each(function() {
						if ($(this).data('index') != index) {
							Tab.closeTab($(this));
						} else {
							return false;
						}
					});
				}
			},
			closeLeft: {
				name: '关闭左侧所有',
				iconClass: 'zmdi zmdi-arrow-left',
				onClick: function(item) {
					var index = $(item).data('index');
					$('.content_tab li').each(function() {
						if ($(this).data('index') != index) {
							Tab.closeTab($(this));
						} else {
							return false;
						}
					});
				}
			},
			refresh: {
				name: '刷新',
				iconClass: 'zmdi zmdi-refresh',
				onClick: function(item) {
					var index = $(item).data('index');
					var $iframe = $('#iframe_' + index).find('iframe');
					$iframe.attr('src', $iframe.attr('src'));
				}
			}
		}
	});
});
// 选项卡对象
var Tab = {
	addTab: function(title, url) {
		var index = url.replace(/\./g, '_').replace(/\//g, '_').replace(/:/g, '_').replace(/\?/g, '_').replace(/,/g, '_').replace(/=/g, '_').replace(/&/g, '_');
		// 如果存在选项卡，则激活，否则创建新选项卡
		if ($('#tab_' + index).length == 0) {
			// 添加选项卡
			$('.content_tab li').removeClass('cur');
			var tab = '
' + title + '
';//<
			$('.content_tab>ul').append(tab);
			// 添加iframe
			$('.iframe').removeClass('cur');
			var iframe = '

';
			$('.content_main').append(iframe);
			initScrollShow();
			$('.content_tab>ul').animate({scrollLeft: document.getElementById('tabs').scrollWidth - document.getElementById('tabs').clientWidth}, 200, function() {
				initScrollState();
			});
		} else {
			$('#tab_' + index).trigger('click');
		}
		// 关闭侧边栏
		$('#guide').trigger(click);
	},
	closeTab: function($item) {
		var closeable = $item.data('closeable');
		if (closeable != false) {
			// 如果当前时激活状态则关闭后激活左边选项卡
			if($item.hasClass('cur')) {
				$item.prev().trigger('click');
			}
			// 关闭当前选项卡
			var index = $item.data('index');
			$('#iframe_' + index).remove();
			$item.remove();
		}
		initScrollShow();
	}
}
function initScrollShow() {
	if (document.getElementById('tabs').scrollWidth > document.getElementById('tabs').clientWidth) {
		$('.content_tab').addClass('scroll');
	} else {
		$('.content_tab').removeClass('scroll');
	}
}
function initScrollState() {
	if ($('.content_tab>ul').scrollLeft() == 0) {
		$('.tab_left>a').removeClass('active');
	} else {
		$('.tab_left>a').addClass('active');
	}
	if (($('.content_tab>ul').scrollLeft() + document.getElementById('tabs').clientWidth) >= document.getElementById('tabs').scrollWidth) {
		$('.tab_right>a').removeClass('active');
	} else {
		$('.tab_right>a').addClass('active');
	}
}

function fullPage() {

	if ($.util.supportsFullScreen) {
		if ($.util.isFullScreen()) {
			$.util.cancelFullScreen();
		} else {
			$.util.requestFullScreen();
		}
	} else {
		alert("当前浏览器不支持全屏 API，请更换至最新的 Chrome/Firefox/Safari 浏览器或通过 F11 快捷键进行操作。");
	}
}<commit_msg>修正默认主题不显示问题<commit_after>var click = device.mobile() ? 'touchstart' : 'click';
$(function() {
	// 侧边栏操作按钮
	$(document).on(click, '#guide', function() {
		$(this).toggleClass('toggled');
		$('#sidebar').toggleClass('toggled');
	});
	// 侧边栏二级菜单
	$(document).on('click', '.sub-menu a', function() {
		$(this).next().slideToggle(200);
		$(this).parent().toggleClass('toggled');
	});
	// 个人资料
	$(document).on('click', '.s-profile a', function() {
		$(this).next().slideToggle(200);
		$(this).parent().toggleClass('toggled');
	});
	// Waves初始化
	Waves.displayEffect();
	// 滚动条初始化
	$('#sidebar').mCustomScrollbar({
		theme: 'minimal-dark',
		scrollInertia: 100,
		axis: 'yx',
		mouseWheel: {
			enable: true,
			axis: 'y',
			preventDefault: true
		}
	});
	// 切换系统
	$('.switch-systems').click(function () {
		var systemid = $(this).attr('systemid');
		var systemname = $(this).attr('systemname');
		var systemtitle = $(this).attr('systemtitle');
		$('.system_menus').hide(0, function () {
			$('.system_' + systemid).show();
		});
		$('body').attr("id", systemname);
		$('#system_title').text(systemtitle);
		$.cookie('zheng-upms-systemid', systemid);
		$.cookie('zheng-upms-systemname', systemname);
		$.cookie('zheng-upms-systemtitle', systemtitle);
	});
	// 显示cookie菜单
	var systemid = $.cookie('zheng-upms-systemid') || 1;
	var systemname = $.cookie('zheng-upms-systemname') || 'zheng-upms-server';
	var systemtitle = $.cookie('zheng-upms-systemtitle') || '权限管理系统';
	$('.system_menus').hide(0, function () {
		$('.system_' + systemid).show();
	});
	$('body').attr('id', systemname);
	$('#system_title').text(systemtitle);
});
// iframe高度自适应
function changeFrameHeight(ifm) {
	ifm.height = document.documentElement.clientHeight - 118;
}
function resizeFrameHeight() {
	$('.tab_iframe').css('height', document.documentElement.clientHeight - 118);
	$('md-tab-content').css('left', '0');
}
window.onresize = function() {
	resizeFrameHeight();
	initScrollShow();
	initScrollState();
}

// ========== 选项卡操作 ==========
$(function() {
	// 选项卡点击
	$(document).on('click', '.content_tab li', function() {
		// 切换选项卡
		$('.content_tab li').removeClass('cur');
		$(this).addClass('cur');
		// 切换iframe
		$('.iframe').removeClass('cur');
		$('#iframe_' + $(this).data('index')).addClass('cur');
		var marginLeft = ($('#tabs').css('marginLeft').replace('px', ''));
		// 滚动到可视区域:在左侧
		if ($(this).position().left < marginLeft) {
			var left = $('.content_tab>ul').scrollLeft() + $(this).position().left - marginLeft;
			$('.content_tab>ul').animate({scrollLeft: left}, 200, function() {
				initScrollState();
			});
		}
		// 滚动到可视区域:在右侧
		if(($(this).position().left + $(this).width() - marginLeft) > document.getElementById('tabs').clientWidth) {
			var left = $('.content_tab>ul').scrollLeft() + (($(this).position().left + $(this).width() - marginLeft) - document.getElementById('tabs').clientWidth);
			$('.content_tab>ul').animate({scrollLeft: left}, 200, function() {
				initScrollState();
			});
		}
	});
	// 控制选项卡滚动位置
	$(document).on('click', '.tab_left>a', function() {
		$('.content_tab>ul').animate({scrollLeft: $('.content_tab>ul').scrollLeft() - 300}, 200, function() {
			initScrollState();
		});
	});
	// 向右箭头
	$(document).on('click', '.tab_right>a', function() {
		$('.content_tab>ul').animate({scrollLeft: $('.content_tab>ul').scrollLeft() + 300}, 200, function() {
			initScrollState();
		});
	});
	// 初始化箭头状态

	// 选项卡右键菜单
	var menu = new BootstrapMenu('.tabs li', {
		fetchElementData: function(item) {
			return item;
		},
		actionsGroups: [
			['close', 'refresh'],
			['closeOther', 'closeAll'],
			['closeRight', 'closeLeft']
		],
		actions: {
			close: {
				name: '关闭',
				iconClass: 'zmdi zmdi-close',
				onClick: function(item) {
					Tab.closeTab($(item));
				}
			},
			closeOther: {
				name: '关闭其他',
				iconClass: 'zmdi zmdi-arrow-split',
				onClick: function(item) {
					var index = $(item).data('index');
					$('.content_tab li').each(function() {
						if ($(this).data('index') != index) {
							Tab.closeTab($(this));
						}
					});
				}
			},
			closeAll: {
				name: '关闭全部',
				iconClass: 'zmdi zmdi-swap',
				onClick: function() {
					$('.content_tab li').each(function() {
						Tab.closeTab($(this));
					});
				}
			},
			closeRight: {
				name: '关闭右侧所有',
				iconClass: 'zmdi zmdi-arrow-right',
				onClick: function(item) {
					var index = $(item).data('index');
					$($('.content_tab li').toArray().reverse()).each(function() {
						if ($(this).data('index') != index) {
							Tab.closeTab($(this));
						} else {
							return false;
						}
					});
				}
			},
			closeLeft: {
				name: '关闭左侧所有',
				iconClass: 'zmdi zmdi-arrow-left',
				onClick: function(item) {
					var index = $(item).data('index');
					$('.content_tab li').each(function() {
						if ($(this).data('index') != index) {
							Tab.closeTab($(this));
						} else {
							return false;
						}
					});
				}
			},
			refresh: {
				name: '刷新',
				iconClass: 'zmdi zmdi-refresh',
				onClick: function(item) {
					var index = $(item).data('index');
					var $iframe = $('#iframe_' + index).find('iframe');
					$iframe.attr('src', $iframe.attr('src'));
				}
			}
		}
	});
});
// 选项卡对象
var Tab = {
	addTab: function(title, url) {
		var index = url.replace(/\./g, '_').replace(/\//g, '_').replace(/:/g, '_').replace(/\?/g, '_').replace(/,/g, '_').replace(/=/g, '_').replace(/&/g, '_');
		// 如果存在选项卡，则激活，否则创建新选项卡
		if ($('#tab_' + index).length == 0) {
			// 添加选项卡
			$('.content_tab li').removeClass('cur');
			var tab = '
' + title + '
';//<
			$('.content_tab>ul').append(tab);
			// 添加iframe
			$('.iframe').removeClass('cur');
			var iframe = '

';
			$('.content_main').append(iframe);
			initScrollShow();
			$('.content_tab>ul').animate({scrollLeft: document.getElementById('tabs').scrollWidth - document.getElementById('tabs').clientWidth}, 200, function() {
				initScrollState();
			});
		} else {
			$('#tab_' + index).trigger('click');
		}
		// 关闭侧边栏
		$('#guide').trigger(click);
	},
	closeTab: function($item) {
		var closeable = $item.data('closeable');
		if (closeable != false) {
			// 如果当前时激活状态则关闭后激活左边选项卡
			if($item.hasClass('cur')) {
				$item.prev().trigger('click');
			}
			// 关闭当前选项卡
			var index = $item.data('index');
			$('#iframe_' + index).remove();
			$item.remove();
		}
		initScrollShow();
	}
}
function initScrollShow() {
	if (document.getElementById('tabs').scrollWidth > document.getElementById('tabs').clientWidth) {
		$('.content_tab').addClass('scroll');
	} else {
		$('.content_tab').removeClass('scroll');
	}
}
function initScrollState() {
	if ($('.content_tab>ul').scrollLeft() == 0) {
		$('.tab_left>a').removeClass('active');
	} else {
		$('.tab_left>a').addClass('active');
	}
	if (($('.content_tab>ul').scrollLeft() + document.getElementById('tabs').clientWidth) >= document.getElementById('tabs').scrollWidth) {
		$('.tab_right>a').removeClass('active');
	} else {
		$('.tab_right>a').addClass('active');
	}
}

function fullPage() {

	if ($.util.supportsFullScreen) {
		if ($.util.isFullScreen()) {
			$.util.cancelFullScreen();
		} else {
			$.util.requestFullScreen();
		}
	} else {
		alert("当前浏览器不支持全屏 API，请更换至最新的 Chrome/Firefox/Safari 浏览器或通过 F11 快捷键进行操作。");
	}
}<|endoftext|>


<commit_before>/*
 * Copyright (c) 2013 - present Adobe Systems Incorporated. All rights reserved.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 *
 */

define(function (require, exports, module) {
    "use strict";

    var AppInit              = brackets.getModule("utils/AppInit"),
        PreferencesManager   = brackets.getModule("preferences/PreferencesManager"),
        Strings              = brackets.getModule("strings"),
        FileViewController   = brackets.getModule("project/FileViewController"),
        ExtensionUtils       = brackets.getModule("utils/ExtensionUtils"),
        NodeDomain           = brackets.getModule("utils/NodeDomain"),
        FileUtils            = brackets.getModule("file/FileUtils"),
        GraphicsFile         = require("GraphicsFile");

    /**
     * @private
     * @type {string} fullPath of the OpenWithExternalEditor Domain implementation
     */
    var _domainPath = ExtensionUtils.getModulePath(module, "node/OpenWithExternalApplicationDomain");

    /**
     * @private
     * @type {NodeDomain}
     */
    var _nodeDomain = new NodeDomain("OpenWithExternalApplication", _domainPath);

    var extensionToExtApplicationMap = {};

    function convertUnixPathToWindowsPath(path) {
        if (brackets.platform === "win" && path && path[1] === ":" && path[2] === "/") {
           path = path.replace(RegExp('/','g'), '\\');
        }
        return path;
    }

    function _openWithExternalApplication(event, path) {
        _nodeDomain.exec("open", {
            path: convertUnixPathToWindowsPath(path),
            app: extensionToExtApplicationMap[FileUtils.getFileExtension(path).toLowerCase()]
        });
    }

    PreferencesManager.definePreference("externalApplications", "object", {}, {
        description: Strings.DESCRIPTION_EXTERNAL_APPLICATION_ASSOCIATE
    });

    PreferencesManager.on("change", "externalApplications", function () {
        extensionToExtApplicationMap = PreferencesManager.get("externalApplications");
        FileUtils.addExtensionToExternalAppList(Object.keys(extensionToExtApplicationMap));
    });

    FileViewController.on("openWithExternalApplication", _openWithExternalApplication);

    AppInit.appReady(function () {

        GraphicsFile.init(_nodeDomain);
        extensionToExtApplicationMap = PreferencesManager.get("externalApplications");
        FileUtils.addExtensionToExternalAppList(Object.keys(extensionToExtApplicationMap));
    });
});
<commit_msg>Netwrk path also need to be converted to windows style<commit_after>/*
 * Copyright (c) 2013 - present Adobe Systems Incorporated. All rights reserved.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 *
 */

define(function (require, exports, module) {
    "use strict";

    var AppInit              = brackets.getModule("utils/AppInit"),
        PreferencesManager   = brackets.getModule("preferences/PreferencesManager"),
        Strings              = brackets.getModule("strings"),
        FileViewController   = brackets.getModule("project/FileViewController"),
        ExtensionUtils       = brackets.getModule("utils/ExtensionUtils"),
        NodeDomain           = brackets.getModule("utils/NodeDomain"),
        FileUtils            = brackets.getModule("file/FileUtils"),
        GraphicsFile         = require("GraphicsFile");

    /**
     * @private
     * @type {string} fullPath of the OpenWithExternalEditor Domain implementation
     */
    var _domainPath = ExtensionUtils.getModulePath(module, "node/OpenWithExternalApplicationDomain");

    /**
     * @private
     * @type {NodeDomain}
     */
    var _nodeDomain = new NodeDomain("OpenWithExternalApplication", _domainPath);

    var extensionToExtApplicationMap = {};

    function convertUnixPathToWindowsPath(path) {
        if (brackets.platform === "win"
        && path && ((path[1] === ":" && path[2] === "/") || (path[0] === "/" && path[1] === "/"))) {
           path = path.replace(RegExp('/','g'), '\\');
        }
        return path;
    }

    function _openWithExternalApplication(event, path) {
        _nodeDomain.exec("open", {
            path: convertUnixPathToWindowsPath(path),
            app: extensionToExtApplicationMap[FileUtils.getFileExtension(path).toLowerCase()]
        });
    }

    PreferencesManager.definePreference("externalApplications", "object", {}, {
        description: Strings.DESCRIPTION_EXTERNAL_APPLICATION_ASSOCIATE
    });

    PreferencesManager.on("change", "externalApplications", function () {
        extensionToExtApplicationMap = PreferencesManager.get("externalApplications");
        FileUtils.addExtensionToExternalAppList(Object.keys(extensionToExtApplicationMap));
    });

    FileViewController.on("openWithExternalApplication", _openWithExternalApplication);

    AppInit.appReady(function () {

        GraphicsFile.init(_nodeDomain);
        extensionToExtApplicationMap = PreferencesManager.get("externalApplications");
        FileUtils.addExtensionToExternalAppList(Object.keys(extensionToExtApplicationMap));
    });
});
<|endoftext|>


<commit_before>import Em from 'ember';
import ArraySlice from 'array-slice';
var computed = Em.computed;
var get = Em.get;
var set = Em.set;

var ArrayPager = ArraySlice.extend({
	// 1-based
	page: computed('offset', 'limit', {
		get: function () {
			var limit = get(this, 'limit');
			var offset = get(this, 'offset') || 0;
			return Math.ceil(offset / limit) || 1;
		},
		set: function (key, page) {
			var limit = get(this, 'limit');
			var offset = get(this, 'offset');
			// no negative pages
			page = Math.max(page - 1, 0);
			offset = (limit * page) || 0;
			set(this, 'offset', offset);
			return page + 1;
		}
	}),

	// 1-based
	pages: computed('content.length', 'limit', {
		get: function () {
			var limit = get(this, 'limit');
			var length = get(this, 'content.length');
			var pages = Math.ceil(length / limit) || 1;
			if (pages === Infinity) {
				pages = 0;
			}
			return pages;
		}
	})
});

ArrayPager.computed = {
	page: function (prop, page, limit) {
		return computed({
			get: function () {
				return ArrayPager.create({
					content: get(this, prop),
					page: page,
					limit: limit
				});
			}
		});
	}
};

export default ArrayPager;
<commit_msg>Alias math functions<commit_after>import Em from 'ember';
import ArraySlice from 'array-slice';
var computed = Em.computed;
var get = Em.get;
var set = Em.set;
var max = Math.max;
var ceil = Math.ceil;

var ArrayPager = ArraySlice.extend({
	// 1-based
	page: computed('offset', 'limit', {
		get: function () {
			var limit = get(this, 'limit');
			var offset = get(this, 'offset') || 0;
			return ceil(offset / limit) || 1;
		},
		set: function (key, page) {
			var limit = get(this, 'limit');
			var offset = get(this, 'offset');
			// no negative pages
			page = max(page - 1, 0);
			offset = (limit * page) || 0;
			set(this, 'offset', offset);
			return page + 1;
		}
	}),

	// 1-based
	pages: computed('content.length', 'limit', {
		get: function () {
			var limit = get(this, 'limit');
			var length = get(this, 'content.length');
			var pages = ceil(length / limit) || 1;
			if (pages === Infinity) {
				pages = 0;
			}
			return pages;
		}
	})
});

ArrayPager.computed = {
	page: function (prop, page, limit) {
		return computed({
			get: function () {
				return ArrayPager.create({
					content: get(this, prop),
					page: page,
					limit: limit
				});
			}
		});
	}
};

export default ArrayPager;
<|endoftext|>


<commit_before>(function(App, window){
	"use strict";
	var Module = function(App){
		this.a = App;

		var t = this;
		this.getUserData(function(r){
			t.render_personalinfo(r);

			t.fill_menu_helper();
			t.main_btn_func();
			t.main_mnu_func();
			t.build_menu();
			t.logout_init();

			t.a.loaded = true;

			if(t.a._url.match(/(backend)/gi) == null && t.a._url.match(/(login)/gi) === null){
				window.Application.loadCategory(t.a._url);
			}
		});
	};

	Module.prototype.logout_init = function() {
		var elm = document.getElementById('logout');
		elm._t = this;
		elm.addEventListener('click', function(){
			this._t.logout(function(){
				location.reload();
			});
		}, false);
	};

	Module.prototype.logout = function(callback) {
		var j = {
			url: this.a._data.rest+'Members/',
			mode: 'DELETE',
			div: undefined,
			cache: true,
			response: 'object',
			headerValue: 'application/json'
		}

		new Vi(j).ajax(callback);
	};

	Module.prototype.getUserData = function(callback) {
		callback = (typeof callback === 'function') ? callback : function(){};

		 /*jso_ensureTokens({
			"uvicate": []
		});*/

		jso_dump();

		var id = getCookie(this.a._data.id);
		$.oajax({
			url: this.a._data.rest+'Users/'+id,
			jso_provider: "uvicate",
			jso_allowia: false,
			jso_scopes: ["profile"],
			dataType: 'json',
			success: function(data) {
				callback(data);
			}
		});
	};

	Module.prototype.render_personalinfo = function(data) {
		this.a._user = data;

		var holder = document.getElementById('signed-in-as');
		var t = data.fullname
		holder.innerHTML = '';
		holder.appendChild(document.createTextNode(t));

		var img = Application.getGravatarImg(data.basic.email, 40);
		var imgholder = document.getElementById('image-signed-in');
		imgholder.src = img;
	};

	Module.prototype.fill_menu_helper = function() {
		var helper = document.getElementById('menu-helper');
		helper.innerHTML = '';

		var btn = document.createElement('button');
		btn.id = 'main-menu-btn';
		btn.className = 'btn btn-default';
		helper.appendChild(btn);

		var i = document.createElement('i');
		i.className = 'glyphicon glyphicon-home';
		btn.appendChild(i);

		var s = document.createElement('span');
		s.setAttribute('data-ltag', 'dashboard');
		var t = this.a.current.getText('dashboard');
		s.appendChild(document.createTextNode(' '+t));
		btn.appendChild(s);
	};

	Module.prototype.main_btn_func = function() {
		var btn = document.getElementById('main-menu-btn');
		btn._t = this;
		btn._target = document.getElementById('main-menu-holder');
		btn.onmouseover = function(){
			$(this._target).addClass('anim-menu-active');
			$(this._target).addClass('a-b');
		};
	};

	Module.prototype.main_mnu_func = function() {
		var menu = document.getElementById('main-menu-holder');
		menu._t = this;

		$(menu).mouseleave(function(){
			$(this).removeClass('anim-menu-active');
			$(this).removeClass('a-b');
		})
	};

	Module.prototype.build_menu = function() {
		var categories = this.a._data.modules;
		var container = document.getElementById('main-menu');

		var banned = ['login', 'backend'];
		for(var c in categories){
			if(categories.hasOwnProperty(c) && banned.indexOf(c) < 0){
				var elm = document.createElement('li');
				var a = document.createElement('a');
				a.setAttribute('data-module', c);
				elm.appendChild(a);

				var t = this.a.current.getText(c);

				var icon = document.createElement('i');
				if(categories[c].hasOwnProperty('i'))
					icon.className = categories[c].i;

				a.appendChild(icon);

				a.addEventListener('click', function(){
					var cat = this.getAttribute('data-module');
					window.Application.loadCategory(cat);
				}, false);

				var span = document.createElement('span');
				span.setAttribute('data-ltag', c);
				span.appendChild(document.createTextNode(' '+t));
				a.appendChild(span);

				container.appendChild(elm);
			}
		}
	};

	function getCookie(c_name){
		var c_value = document.cookie;
		var c_start = c_value.indexOf(" " + c_name + "=");
		if (c_start == -1){
			c_start = c_value.indexOf(c_name + "=");
		}

		if (c_start == -1){
			c_value = null;
		}else {
			c_start = c_value.indexOf("=", c_start) + 1;
			var c_end = c_value.indexOf(";", c_start);
			if (c_end == -1){
				c_end = c_value.length;
			}
			c_value = unescape(c_value.substring(c_start,c_end));
		}

		return c_value;
	}

	var m = new Module(App);
})(App, window);<commit_msg>Wipe all tokens on logout<commit_after>(function(App, window){
	"use strict";
	var Module = function(App){
		this.a = App;

		var t = this;
		this.getUserData(function(r){
			t.render_personalinfo(r);

			t.fill_menu_helper();
			t.main_btn_func();
			t.main_mnu_func();
			t.build_menu();
			t.logout_init();

			t.a.loaded = true;

			if(t.a._url.match(/(backend)/gi) == null && t.a._url.match(/(login)/gi) === null){
				window.Application.loadCategory(t.a._url);
			}
		});
	};

	Module.prototype.logout_init = function() {
		var elm = document.getElementById('logout');
		elm._t = this;
		elm.addEventListener('click', function(){
			this._t.logout(function(){
				location.reload();
			});
		}, false);
	};

	Module.prototype.logout = function(callback) {
		var j = {
			url: this.a._data.rest+'Members/',
			mode: 'DELETE',
			div: undefined,
			cache: true,
			response: 'object',
			headerValue: 'application/json'
		}

		jso_wipe();
		new Vi(j).ajax(callback);
	};

	Module.prototype.getUserData = function(callback) {
		callback = (typeof callback === 'function') ? callback : function(){};

		jso_dump();

		var id = getCookie(this.a._data.id);
		$.oajax({
			url: this.a._data.rest+'Users/'+id,
			jso_provider: "uvicate",
			jso_allowia: false,
			jso_scopes: ["profile"],
			dataType: 'json',
			success: function(data) {
				callback(data);
			}
		});
	};

	Module.prototype.render_personalinfo = function(data) {
		this.a._user = data;

		var holder = document.getElementById('signed-in-as');
		var t = data.fullname
		holder.innerHTML = '';
		holder.appendChild(document.createTextNode(t));

		var img = Application.getGravatarImg(data.basic.email, 40);
		var imgholder = document.getElementById('image-signed-in');
		imgholder.src = img;
	};

	Module.prototype.fill_menu_helper = function() {
		var helper = document.getElementById('menu-helper');
		helper.innerHTML = '';

		var btn = document.createElement('button');
		btn.id = 'main-menu-btn';
		btn.className = 'btn btn-default';
		helper.appendChild(btn);

		var i = document.createElement('i');
		i.className = 'glyphicon glyphicon-home';
		btn.appendChild(i);

		var s = document.createElement('span');
		s.setAttribute('data-ltag', 'dashboard');
		var t = this.a.current.getText('dashboard');
		s.appendChild(document.createTextNode(' '+t));
		btn.appendChild(s);
	};

	Module.prototype.main_btn_func = function() {
		var btn = document.getElementById('main-menu-btn');
		btn._t = this;
		btn._target = document.getElementById('main-menu-holder');
		btn.onmouseover = function(){
			$(this._target).addClass('anim-menu-active');
			$(this._target).addClass('a-b');
		};
	};

	Module.prototype.main_mnu_func = function() {
		var menu = document.getElementById('main-menu-holder');
		menu._t = this;

		$(menu).mouseleave(function(){
			$(this).removeClass('anim-menu-active');
			$(this).removeClass('a-b');
		})
	};

	Module.prototype.build_menu = function() {
		var categories = this.a._data.modules;
		var container = document.getElementById('main-menu');

		var banned = ['login', 'backend'];
		for(var c in categories){
			if(categories.hasOwnProperty(c) && banned.indexOf(c) < 0){
				var elm = document.createElement('li');
				var a = document.createElement('a');
				a.setAttribute('data-module', c);
				elm.appendChild(a);

				var t = this.a.current.getText(c);

				var icon = document.createElement('i');
				if(categories[c].hasOwnProperty('i'))
					icon.className = categories[c].i;

				a.appendChild(icon);

				a.addEventListener('click', function(){
					var cat = this.getAttribute('data-module');
					window.Application.loadCategory(cat);
				}, false);

				var span = document.createElement('span');
				span.setAttribute('data-ltag', c);
				span.appendChild(document.createTextNode(' '+t));
				a.appendChild(span);

				container.appendChild(elm);
			}
		}
	};

	function getCookie(c_name){
		var c_value = document.cookie;
		var c_start = c_value.indexOf(" " + c_name + "=");
		if (c_start == -1){
			c_start = c_value.indexOf(c_name + "=");
		}

		if (c_start == -1){
			c_value = null;
		}else {
			c_start = c_value.indexOf("=", c_start) + 1;
			var c_end = c_value.indexOf(";", c_start);
			if (c_end == -1){
				c_end = c_value.length;
			}
			c_value = unescape(c_value.substring(c_start,c_end));
		}

		return c_value;
	}

	var m = new Module(App);
})(App, window);<|endoftext|>


<commit_before>/*
 * This Source Code is subject to the terms of the Mozilla Public License
 * version 2.0 (the 'License'). You can obtain a copy of the License at
 * http://mozilla.org/MPL/2.0/.
 */

/* global TelemetryController */

const {Cu} = require('chrome');

Cu.import('resource://gre/modules/TelemetryController.jsm');

const { AddonManager } = require('resource://gre/modules/AddonManager.jsm');
const Events = require('sdk/system/events');
const PrefsService = require('sdk/preferences/service');
const self = require('sdk/self');
const store = require('sdk/simple-storage').storage;

const seedrandom = require('seedrandom');

// Event type for receiving pings from experiments
const EVENT_SEND_METRIC = 'testpilot::send-metric';
const EVENT_RECEIVE_VARIANT_DEFS = 'testpilot::register-variants';
const EVENT_SEND_VARIANTS = 'testpilot::receive-variants';

// List of preferences we'll override on install & restore on uninstall
const PREFERENCE_OVERRIDES = {
  'toolkit.telemetry.enabled': true,
  'datareporting.healthreport.uploadEnabled': true
};

// nsIObserver message subjects.
const TELEMETRY_TESTPILOT = 'testpilot';
const TELEMETRY_EXPERIMENT = 'testpilottest';

const variantMaker = {
  makeTest: function(test) {
    let summedWeight = 0;
    const variants = [];
    test.variants.forEach(variant => {
      summedWeight += variant.weight;
      for (let i = 0; i < variant.weight; i++) {
        variants.push(variant.value);
      }
    });
    const seed = `${test.name}_${store.clientUUID}`;
    return variants[Math.floor(seedrandom(seed)() * summedWeight)];
  },

  parseTests: function(tests) {
    const results = {};
    Object.keys(tests).forEach(key => {
      results[key] = this.makeTest(tests[key]);
    });
    return results;
  }
};

function makeTimestamp(time) {
  const timestamp = typeof time !== 'undefined' ?  time : Date.now();
  return Math.round((timestamp - store.browserLoadedTimestamp) / 1000);
}

const Metrics = module.exports = {

  init: function() {
    store.browserLoadedTimestamp = Date.now();
    Events.on(EVENT_SEND_METRIC, Metrics.onExperimentPing);
    Events.on(EVENT_RECEIVE_VARIANT_DEFS, Metrics.onReceiveVariantDefs);
  },

  onEnable: function() {
    Metrics.pingTelemetry(self.id, 'enabled', Date.now());
    Metrics.prefs.backup();
  },

  onDisable: function() {
    Metrics.pingTelemetry(self.id, 'disabled', Date.now());
    Metrics.prefs.restore();
  },

  prefs: {
    // Backup existing preference settings and then override.
    backup: function() {
      store.metricsPrefsBackup = {};
      Object.keys(PREFERENCE_OVERRIDES).forEach(name => {
        store.metricsPrefsBackup[name] = PrefsService.get(name);
        PrefsService.set(name, PREFERENCE_OVERRIDES[name]);
      });
    },

    // Restore previous preference settings before override.
    restore: function() {
      if (store.metricsPrefsBackup) {
        Object.keys(PREFERENCE_OVERRIDES).forEach(name => {
          PrefsService.set(name, store.metricsPrefsBackup[name]);
        });
      }
    }
  },

  destroy: function() {
    Events.off(EVENT_SEND_METRIC, Metrics.onExperimentPing);
    Events.off(EVENT_RECEIVE_VARIANT_DEFS, Metrics.onReceiveVariantDefs);
  },

  pingTelemetry: function(object, eventName, eventTimestamp) {
    const payload = {
      timestamp: makeTimestamp(),
      test: self.id,
      version: self.version,
      events: [
        {
          timestamp: makeTimestamp(eventTimestamp),
          event: eventName,
          object: object
        }
      ]
    };
    TelemetryController.submitExternalPing(
      TELEMETRY_TESTPILOT,
      payload,
      { addClientId: true, addEnvironment: true }
    );
  },

  experimentEnabled: function(addonId) {
    Metrics.pingTelemetry(addonId, 'enabled', Date.now());
  },

  experimentDisabled: function(addonId) {
    Metrics.pingTelemetry(addonId, 'disabled', Date.now());
  },

  onReceiveVariantDefs: function(ev) {
    if (!store.experimentVariants) {
      store.experimentVariants = {};
    }

    const { subject, data } = ev;
    const dataParsed = variantMaker.parseTests(JSON.parse(data));

    store.experimentVariants[subject] = dataParsed;
    Events.emit(EVENT_SEND_VARIANTS, {
      data: JSON.stringify(dataParsed),
      subject: self.id
    });
  },

  onExperimentPing: function(ev) {
    const timestamp = Date.now();
    const { subject, data } = ev;

    AddonManager.getAddonByID(subject, addon => {
      const payload = {
        test: subject,
        version: addon.version,
        timestamp: makeTimestamp(timestamp),
        variants: (
          (store.experimentVariants && subject in store.experimentVariants) ?
          store.experimentVariants[subject] : null
        ),
        payload: JSON.parse(data)
      };
      TelemetryController.submitExternalPing(
        TELEMETRY_EXPERIMENT, payload,
        { addClientId: true, addEnvironment: true }
      );
    });
  }
};
<commit_msg>Use browser start time for metrics timestamps<commit_after>/*
 * This Source Code is subject to the terms of the Mozilla Public License
 * version 2.0 (the 'License'). You can obtain a copy of the License at
 * http://mozilla.org/MPL/2.0/.
 */

/* global TelemetryController, Services */

const {Cu} = require('chrome');

Cu.import('resource://gre/modules/Services.jsm');
Cu.import('resource://gre/modules/TelemetryController.jsm');

const { AddonManager } = require('resource://gre/modules/AddonManager.jsm');
const Events = require('sdk/system/events');
const PrefsService = require('sdk/preferences/service');
const self = require('sdk/self');
const store = require('sdk/simple-storage').storage;

const seedrandom = require('seedrandom');

// Event type for receiving pings from experiments
const EVENT_SEND_METRIC = 'testpilot::send-metric';
const EVENT_RECEIVE_VARIANT_DEFS = 'testpilot::register-variants';
const EVENT_SEND_VARIANTS = 'testpilot::receive-variants';

// List of preferences we'll override on install & restore on uninstall
const PREFERENCE_OVERRIDES = {
  'toolkit.telemetry.enabled': true,
  'datareporting.healthreport.uploadEnabled': true
};

// nsIObserver message subjects.
const TELEMETRY_TESTPILOT = 'testpilot';
const TELEMETRY_EXPERIMENT = 'testpilottest';

const variantMaker = {
  makeTest: function(test) {
    let summedWeight = 0;
    const variants = [];
    test.variants.forEach(variant => {
      summedWeight += variant.weight;
      for (let i = 0; i < variant.weight; i++) {
        variants.push(variant.value);
      }
    });
    const seed = `${test.name}_${store.clientUUID}`;
    return variants[Math.floor(seedrandom(seed)() * summedWeight)];
  },

  parseTests: function(tests) {
    const results = {};
    Object.keys(tests).forEach(key => {
      results[key] = this.makeTest(tests[key]);
    });
    return results;
  }
};

function makeTimestamp(time) {
  const timestamp = typeof time !== 'undefined' ?  time : Date.now();
  return Math.round((timestamp - Services.startup.getStartupInfo().process) / 1000);
}

const Metrics = module.exports = {

  init: function() {
    Events.on(EVENT_SEND_METRIC, Metrics.onExperimentPing);
    Events.on(EVENT_RECEIVE_VARIANT_DEFS, Metrics.onReceiveVariantDefs);
  },

  onEnable: function() {
    Metrics.pingTelemetry(self.id, 'enabled', Date.now());
    Metrics.prefs.backup();
  },

  onDisable: function() {
    Metrics.pingTelemetry(self.id, 'disabled', Date.now());
    Metrics.prefs.restore();
  },

  prefs: {
    // Backup existing preference settings and then override.
    backup: function() {
      store.metricsPrefsBackup = {};
      Object.keys(PREFERENCE_OVERRIDES).forEach(name => {
        store.metricsPrefsBackup[name] = PrefsService.get(name);
        PrefsService.set(name, PREFERENCE_OVERRIDES[name]);
      });
    },

    // Restore previous preference settings before override.
    restore: function() {
      if (store.metricsPrefsBackup) {
        Object.keys(PREFERENCE_OVERRIDES).forEach(name => {
          PrefsService.set(name, store.metricsPrefsBackup[name]);
        });
      }
    }
  },

  destroy: function() {
    Events.off(EVENT_SEND_METRIC, Metrics.onExperimentPing);
    Events.off(EVENT_RECEIVE_VARIANT_DEFS, Metrics.onReceiveVariantDefs);
  },

  pingTelemetry: function(object, eventName, eventTimestamp) {
    const payload = {
      timestamp: makeTimestamp(),
      test: self.id,
      version: self.version,
      events: [
        {
          timestamp: makeTimestamp(eventTimestamp),
          event: eventName,
          object: object
        }
      ]
    };
    TelemetryController.submitExternalPing(
      TELEMETRY_TESTPILOT,
      payload,
      { addClientId: true, addEnvironment: true }
    );
  },

  experimentEnabled: function(addonId) {
    Metrics.pingTelemetry(addonId, 'enabled', Date.now());
  },

  experimentDisabled: function(addonId) {
    Metrics.pingTelemetry(addonId, 'disabled', Date.now());
  },

  onReceiveVariantDefs: function(ev) {
    if (!store.experimentVariants) {
      store.experimentVariants = {};
    }

    const { subject, data } = ev;
    const dataParsed = variantMaker.parseTests(JSON.parse(data));

    store.experimentVariants[subject] = dataParsed;
    Events.emit(EVENT_SEND_VARIANTS, {
      data: JSON.stringify(dataParsed),
      subject: self.id
    });
  },

  onExperimentPing: function(ev) {
    const timestamp = Date.now();
    const { subject, data } = ev;

    AddonManager.getAddonByID(subject, addon => {
      const payload = {
        test: subject,
        version: addon.version,
        timestamp: makeTimestamp(timestamp),
        variants: (
          (store.experimentVariants && subject in store.experimentVariants) ?
          store.experimentVariants[subject] : null
        ),
        payload: JSON.parse(data)
      };
      TelemetryController.submitExternalPing(
        TELEMETRY_EXPERIMENT, payload,
        { addClientId: true, addEnvironment: true }
      );
    });
  }
};
<|endoftext|>


<commit_before>"use strict";

var SuperJS = require('../../index');

var Promise = require('bluebird');
var path = require('path');

/**
 * The base controller class is the basic building block for controllers.
 *
 * @exports Controller
 * @namespace SuperJS
 * @extends SuperJS.Class
 */

module.exports = SuperJS.Class.extend({

  init: function(app) {

    //store reference to express
    this.app = app;

  },

  //can be overridden by the controller extension to manipulate the request or response
  beforeAction: function(req) {

    //return promise
    return new Promise(function(resolve, reject) {
      resolve({});
    });

  },

  //verify the request by transforming, validating, and sanitizing parameters
  verifyRequest: function(req) {

    //maintain reference to the currrent instance
    var self = this;

    //return promise which is resolved or rejected depending on completion
    return new Promise(function (resolve, reject) {

      //maintain context object of parameters
      var parameters = {};

      //maintain list of closures which contain promises for each process
      var transforms = [];
      var validations = [];
      var sanitizations = [];
      var modelValidations = [];

      //loop through all the parameters for this action and
      //append transforms, validations, and sanitizations to their respective lists
      for (var param in self.blueprint.actions[req.action].params) {

        //store the parameters value
        parameters[param] = req.param(param);

        //set value to default if its not passed
        if( typeof parameters[param] === 'undefined' ) {
          parameters[param] = self.blueprint.actions[req.action].params[param].default;
        }

        //setup transforms
        transforms = transforms.concat(self.app.services.transform.setup(self.blueprint.actions[req.action].params[param].transform, parameters, param));

        //setup validations
        validations = validations.concat(self.app.services.validate.setup(self.blueprint.actions[req.action].params[param].validate, param, parameters[param], 'parameter'));

        //setup sanitizations
        //sanitizations = sanitizations.concat(self.app.services.sanitize.setup(self.blueprint.actions[req.action].params[param].sanitize, parameters, param));

        if( self.blueprint.actions[req.action].params[param].model ) {

          //if the parameter is a model but the value is null/undefined, default parameter to empty object
          if( Object.keys(self.blueprint.actions[req.action].params[param].model.validate).length > 0 && !parameters[param]) {
            parameters[param] = {};
          }

          //loop through model validations
          for( var attribute in self.blueprint.actions[req.action].params[param].model.validate ) {

            //set attribute value to default if its not passed
            if( Object.keys(parameters[param]).indexOf(attribute) === -1 ) {
              parameters[param][attribute] = self.app.models[self.name].attributes[attribute].defaultsTo;
            }

            //don't run validations if the attribute has not been provided and its not required
            if( self.blueprint.actions[req.action].params[param].model.validate[attribute].required === true || typeof parameters[param][attribute] !== 'undefined' ) {
              modelValidations = modelValidations.concat(self.app.services.validate.setup(self.blueprint.actions[req.action].params[param].model.validate[attribute], attribute, parameters[param][attribute], 'attribute'));
            }

          }

        }
      }

      var numberOfValidations = validations.length + modelValidations.length;
      self.app.log.debug("performing " + transforms.length + " transforms, " + numberOfValidations + " validations, and " + sanitizations.length + " sanitizations...");

      //exceute transforms
      self.app.services.transform.process(transforms)

        //execute validations
        .then(function() {
          return self.app.services.validate.process(validations);
        })

        //exectute sanitizations
        //.then(function() {
        //  return self.services.sanitize.process(sanitizations)
        //})

        //execute validations
        .then(function() {
          return self.app.services.validate.process(modelValidations);
        })

        //resolve if all passed without errors
        .then(function() {

          //store the parameters on the request object
          req.parameters = parameters;
          self.app.log.debug('verified parameters:', parameters);

          resolve();
        })

        //reject if we caught any errors
        .catch(function(err) {

          reject(err);
        });

    });

  },

  Describe: function(req) {

    //maintain reference to instance
    var self = this;

    //return promise to resolve or reject
    return new Promise(function(resolve, reject) {

      //package response
      var response = {meta: {success: true}, blueprint: self.blueprint};

      //resolve response
      resolve(response);

    });

  },

  //can be overridden by the controller extension to manipulate the request or response
  afterAction: function(req, response, next) {

    //return promise
    return new Promise(function(resolve, reject) {
      resolve({});
    });
  }

});<commit_msg>Updated validations setup execution to reflect change in passing context.<commit_after>"use strict";

var SuperJS = require('../../index');

var Promise = require('bluebird');
var path = require('path');

/**
 * The base controller class is the basic building block for controllers.
 *
 * @exports Controller
 * @namespace SuperJS
 * @extends SuperJS.Class
 */

module.exports = SuperJS.Class.extend({

  init: function(app) {

    //store reference to express
    this.app = app;

  },

  //can be overridden by the controller extension to manipulate the request or response
  beforeAction: function(req) {

    //return promise
    return new Promise(function(resolve, reject) {
      resolve({});
    });

  },

  //verify the request by transforming, validating, and sanitizing parameters
  verifyRequest: function(req) {

    //maintain reference to the currrent instance
    var self = this;

    //return promise which is resolved or rejected depending on completion
    return new Promise(function (resolve, reject) {

      //maintain context object of parameters
      var parameters = {};

      //maintain list of closures which contain promises for each process
      var transforms = [];
      var validations = [];
      var sanitizations = [];
      var modelValidations = [];

      //loop through all the parameters for this action and
      //append transforms, validations, and sanitizations to their respective lists
      for (var param in self.blueprint.actions[req.action].params) {

        //store the parameters value
        parameters[param] = req.param(param);

        //set value to default if its not passed
        if( typeof parameters[param] === 'undefined' ) {
          parameters[param] = self.blueprint.actions[req.action].params[param].default;
        }

        //setup transforms
        transforms = transforms.concat(self.app.services.transform.setup(self.blueprint.actions[req.action].params[param].transform, parameters, param));

        //setup validations
        validations = validations.concat(self.app.services.validate.setup(self.blueprint.actions[req.action].params[param].validate, parameters, param, 'parameter'));

        //setup sanitizations
        //sanitizations = sanitizations.concat(self.app.services.sanitize.setup(self.blueprint.actions[req.action].params[param].sanitize, parameters, param));

        if( self.blueprint.actions[req.action].params[param].model ) {

          //if the parameter is a model but the value is null/undefined, default parameter to empty object
          if( Object.keys(self.blueprint.actions[req.action].params[param].model.validate).length > 0 && !parameters[param]) {
            parameters[param] = {};
          }

          //loop through model validations
          for( var attribute in self.blueprint.actions[req.action].params[param].model.validate ) {

            //set attribute value to default if its not passed
            if( Object.keys(parameters[param]).indexOf(attribute) === -1 ) {
              parameters[param][attribute] = self.app.models[self.name].attributes[attribute].defaultsTo;
            }

            //don't run validations if the attribute has not been provided and its not required
            if( self.blueprint.actions[req.action].params[param].model.validate[attribute].required === true || typeof parameters[param][attribute] !== 'undefined' ) {
              modelValidations = modelValidations.concat(self.app.services.validate.setup(self.blueprint.actions[req.action].params[param].model.validate[attribute], attribute, parameters[param][attribute], 'attribute'));
            }

          }

        }
      }

      var numberOfValidations = validations.length + modelValidations.length;
      self.app.log.debug("performing " + transforms.length + " transforms, " + numberOfValidations + " validations, and " + sanitizations.length + " sanitizations...");

      //exceute transforms
      self.app.services.transform.process(transforms)

        //execute validations
        .then(function() {
          return self.app.services.validate.process(validations);
        })

        //exectute sanitizations
        //.then(function() {
        //  return self.services.sanitize.process(sanitizations)
        //})

        //execute validations
        .then(function() {
          return self.app.services.validate.process(modelValidations);
        })

        //resolve if all passed without errors
        .then(function() {

          //store the parameters on the request object
          req.parameters = parameters;
          self.app.log.debug('verified parameters:', parameters);

          resolve();
        })

        //reject if we caught any errors
        .catch(function(err) {

          reject(err);
        });

    });

  },

  Describe: function(req) {

    //maintain reference to instance
    var self = this;

    //return promise to resolve or reject
    return new Promise(function(resolve, reject) {

      //package response
      var response = {meta: {success: true}, blueprint: self.blueprint};

      //resolve response
      resolve(response);

    });

  },

  //can be overridden by the controller extension to manipulate the request or response
  afterAction: function(req, response, next) {

    //return promise
    return new Promise(function(resolve, reject) {
      resolve({});
    });
  }

});<|endoftext|>


<commit_before>import Ember from 'ember';
import { create, createCollection } from './utils';

const c = Ember.computed;

export default Ember.Mixin.create({
  /*
   * decorate model
   * @param alias[String]
   * @return Object
   * USAGE:

   // With default decorator:
   var record = this.store.find('modelName', id);
   return record.decorate();

   // With specific decorator:
   var record = this.store.find('modelName', id);
   return record.decorate('decoratorName');
  */
  decorate: function(alias) {
    return create.bind(this)(this, alias);
  },

  /*
   * Decorate record in hasMany relation
   * @param collcetionKey[String]
   * @param alias[String]
   * @return Array
   * Usage:

   // with default decorator:
   childrens: DS.hasmany('childrens'),
   decoratedChildrens: this.decorateHasMany('childrens')

   // with specified decorator:
   childrens: DS.hasmany('childrens'),
   decoratedChildrens: this.decorateHasMany('childrens', 'decoratorname')
  */
  decorateHasMany: function(collectionKey, alias) {
    return c(collectionKey, function() {
      var collection = this.get(collectionName);
      createCollection.bind(this)(collection, alias);
    });
  },

  /*
   * Decorate record in belongsTo relation
   * @param modelName[String]
   * @param alias[String]
   * @return Object
   * USAGE:

   // with default decorator:
   childrens: DS.belongsTo('parent'),
   decoratedParent: this.decorateBelongsTo('parent')

   // with specified decorator:
   childrens: ds.belongsTo('parent'),
   decoratedParent: this.decoraBelonsTo('parent', 'decoratorname')
  */
  decorateBelongsTo: function(modelName, alias) {
    return c(modelName, function() {
      var model = this.get(modelName);
      return create.bind(this)(model, alias);
    });
  }
});
<commit_msg>fix naming in comments (capitals)<commit_after>import Ember from 'ember';
import { create, createCollection } from './utils';

const c = Ember.computed;

export default Ember.Mixin.create({
  /*
   * decorate model
   * @param alias[String]
   * @return Object
   * USAGE:

   // With default decorator:
   var record = this.store.find('modelName', id);
   return record.decorate();

   // With specific decorator:
   var record = this.store.find('modelName', id);
   return record.decorate('decoratorName');
  */
  decorate: function(alias) {
    return create.bind(this)(this, alias);
  },

  /*
   * Decorate record in hasMany relation
   * @param collcetionKey[String]
   * @param alias[String]
   * @return Array
   * Usage:

   // with default decorator:
   childrens: DS.hasmany('childrens'),
   decoratedChildrens: this.decorateHasMany('childrens')

   // with specified decorator:
   childrens: DS.hasmany('childrens'),
   decoratedChildrens: this.decorateHasMany('childrens', 'decoratorName')
  */
  decorateHasMany: function(collectionKey, alias) {
    return c(collectionKey, function() {
      var collection = this.get(collectionName);
      createCollection.bind(this)(collection, alias);
    });
  },

  /*
   * Decorate record in belongsTo relation
   * @param modelName[String]
   * @param alias[String]
   * @return Object
   * USAGE:

   // with default decorator:
   childrens: DS.belongsTo('parent'),
   decoratedParent: this.decorateBelongsTo('parent')

   // with specified decorator:
   childrens: ds.belongsTo('parent'),
   decoratedParent: this.decoraBelonsTo('parent', 'decoratorName')
  */
  decorateBelongsTo: function(modelName, alias) {
    return c(modelName, function() {
      var model = this.get(modelName);
      return create.bind(this)(model, alias);
    });
  }
});
<|endoftext|>


<commit_before>import DocumentsError  from './error';
import Base from './assert-base';

let {
  assert,
  notBlank_,
  notBlank,
  isString_,
  isString,
  isObject_,
  isObject,
  isClass_,
  isClass,
  isFunction_,
  isFunction,
  isArray_,
  isArray,
  isArrayProxy_,
  isArrayProxy,
  isArrayOrArrayProxy_,
  isArrayOrArrayProxy,
  isBoolean_,
  isBoolean,
  isOneOf
} = Base(DocumentsError);

export {
  assert,
  notBlank_,
  notBlank,
  isString_,
  isString,
  isObject_,
  isObject,
  isClass_,
  isClass,
  isFunction_,
  isFunction,
  isArray_,
  isArray,
  isArrayProxy_,
  isArrayProxy,
  isArrayOrArrayProxy_,
  isArrayOrArrayProxy,
  isBoolean_,
  isBoolean,
  isOneOf
}

export default assert;
<commit_msg>forward assert.isInstance<commit_after>import DocumentsError  from './error';
import Base from './assert-base';

let {
  assert,
  notBlank_,
  notBlank,
  isString_,
  isString,
  isObject_,
  isObject,
  isInstance_,
  isInstance,
  isClass_,
  isClass,
  isFunction_,
  isFunction,
  isArray_,
  isArray,
  isArrayProxy_,
  isArrayProxy,
  isArrayOrArrayProxy_,
  isArrayOrArrayProxy,
  isBoolean_,
  isBoolean,
  isOneOf
} = Base(DocumentsError);

export {
  assert,
  notBlank_,
  notBlank,
  isString_,
  isString,
  isObject_,
  isObject,
  isInstance_,
  isInstance,
  isClass_,
  isClass,
  isFunction_,
  isFunction,
  isArray_,
  isArray,
  isArrayProxy_,
  isArrayProxy,
  isArrayOrArrayProxy_,
  isArrayOrArrayProxy,
  isBoolean_,
  isBoolean,
  isOneOf
}

export default assert;
<|endoftext|>


<commit_before>Template.buildingsView.helpers({
    "allBldgs": function () {
        return Buildings.find();    // TODO limit fields
    }
});

Template.buildingsGrid.events({
    "mousedown .node": function(event) {
        var externalUrl = $(event.currentTarget).attr("href");
        if (externalUrl) {
            window.open(externalUrl, '_blank');
        }
    }
});

Template.buildingsGrid.rendered = function () {
    var WIDTH = 1200,
        HEIGHT = 400,
        BOUNDING_WIDTH = 1220,
        BOUNDING_HEIGHT = 420,
        SQUARE_WIDTH = 10,
        SQUARE_HEIGHT = 10;

    var self = this;

    var dom = {};
    dom.svg = d3.select("#display").append("svg")
        .attr("width", BOUNDING_WIDTH)
        .attr("height", BOUNDING_HEIGHT)
        .append("g")
        .call(d3.behavior.zoom().scaleExtent([0.8, 60]).on("zoom", zoom))
        .append("g");

    dom.svg.append("rect")
        .attr("class", "overlay")
        .attr("width", BOUNDING_WIDTH)
        .attr("height", BOUNDING_HEIGHT)
        .attr("fill", "lightblue");

    var xScale = d3.scale.linear().domain([0, FLOOR_W * SQUARE_WIDTH]).range([0, WIDTH]);
    var yScale = d3.scale.linear().domain([0, FLOOR_H * SQUARE_HEIGHT]).range([0, HEIGHT]);

    if (!self.handle) {
        self.handle = Meteor.autorun(function () {
            var bldgs = Buildings.find();
            var squares = [];
            bldgs.forEach(function (b) {
                squares.push(b);
            });

            dom.nodes = dom.svg.selectAll('.node')
                .data(squares)
                .enter()
                .append("g")
                .attr("class", "node")
                .attr("xlink:href", function(d) {
                    if (d.payload.external_url) {
                        return d.payload.external_url;
                    }
                    else {
                        return "";
                    }
                });

            dom.nodes
                .append('rect')
                .attr({
                    x: function (d) {
                        return xScale(d.x * SQUARE_WIDTH)
                    },
                    y: function (d) {
                        return yScale(d.y * SQUARE_WIDTH)
                    },
                    width: xScale(SQUARE_WIDTH),
                    height: yScale(SQUARE_WIDTH),
                    stroke: 'none',
                    fill: function (d) {
                        if (d.contentType)
                            return "white";
                    }
                });

            dom.nodes
                .append("foreignObject")
                .attr({
                    width: xScale(SQUARE_WIDTH),
                    height: yScale(SQUARE_WIDTH),
                    x: function (d) {
                        return xScale(d.x * SQUARE_WIDTH)
                    },
                    y: function (d) {
                        return yScale(d.y * SQUARE_WIDTH)
                    },
                    fill: 'none'
                })
                .append("xhtml:body").append("xhtml:p")
                .style({
                    "color": function (d) {
                        if (d.payload.external_url)
                            return "red";
                        else
                            return "navy"
                    },
                    "font-size": "0.6px"
                })
                .html(function (d) {
                    if (d.contentType == 'twitter-social-post') {
                        return d.payload.text;
                    }
                    else if (d.contentType == 'daily-feed') {
                        return d.key;
                    }
                    else {
                        return "";
                    }
                });

        });
    }
    function zoom() {
        dom.svg.attr("transform", "translate(" + d3.event.translate + ")scale(" + d3.event.scale + ")");
    }
};<commit_msg>drill in from days<commit_after>Template.buildingsView.helpers({
    "allBldgs": function () {
        return Buildings.find();    // TODO limit fields
    }
});

Template.buildingsGrid.events({
    "mousedown .node": function(event) {
        var externalUrl = $(event.currentTarget).attr("href");
        if (externalUrl) {
            var target = '_top';
            if (externalUrl.length > 4 && externalUrl.substr(0, 4) == "http")
                target = '_blank';
            window.open(externalUrl, target);
        }
    }
});

Template.buildingsGrid.rendered = function () {
    var WIDTH = 1200,
        HEIGHT = 400,
        BOUNDING_WIDTH = 1220,
        BOUNDING_HEIGHT = 420,
        SQUARE_WIDTH = 10,
        SQUARE_HEIGHT = 10;

    var self = this;

    var dom = {};
    dom.svg = d3.select("#display").append("svg")
        .attr("width", BOUNDING_WIDTH)
        .attr("height", BOUNDING_HEIGHT)
        .append("g")
        .call(d3.behavior.zoom().scaleExtent([0.8, 60]).on("zoom", zoom))
        .append("g");

    dom.svg.append("rect")
        .attr("class", "overlay")
        .attr("width", BOUNDING_WIDTH)
        .attr("height", BOUNDING_HEIGHT)
        .attr("fill", "lightblue");

    var xScale = d3.scale.linear().domain([0, FLOOR_W * SQUARE_WIDTH]).range([0, WIDTH]);
    var yScale = d3.scale.linear().domain([0, FLOOR_H * SQUARE_HEIGHT]).range([0, HEIGHT]);

    if (!self.handle) {
        self.handle = Meteor.autorun(function () {
            var bldgs = Buildings.find();
            var squares = [];
            bldgs.forEach(function (b) {
                squares.push(b);
            });

            dom.nodes = dom.svg.selectAll('.node')
                .data(squares)
                .enter()
                .append("g")
                .attr("class", "node")
                .attr("xlink:href", function(d) {
                    if (d.payload.external_url) {
                        return d.payload.external_url;
                    }
                    else {
                        // if no external link, link to the 1st flr of the bldg
                        return "/buildings/" + d.address + "-l0";
                    }
                });

            dom.nodes
                .append('rect')
                .attr({
                    x: function (d) {
                        return xScale(d.x * SQUARE_WIDTH)
                    },
                    y: function (d) {
                        return yScale(d.y * SQUARE_WIDTH)
                    },
                    width: xScale(SQUARE_WIDTH),
                    height: yScale(SQUARE_WIDTH),
                    stroke: 'none',
                    fill: function (d) {
                        if (d.contentType)
                            return "white";
                    }
                });

            dom.nodes
                .append("foreignObject")
                .attr({
                    width: xScale(SQUARE_WIDTH),
                    height: yScale(SQUARE_WIDTH),
                    x: function (d) {
                        return xScale(d.x * SQUARE_WIDTH)
                    },
                    y: function (d) {
                        return yScale(d.y * SQUARE_WIDTH)
                    },
                    fill: 'none'
                })
                .append("xhtml:body").append("xhtml:p")
                .style({
                    "color": function (d) {
                        if (d.payload.external_url)
                            return "red";
                        else
                            return "navy"
                    },
                    "font-size": "0.6px"
                })
                .html(function (d) {
                    if (d.contentType == 'twitter-social-post') {
                        return d.payload.text;
                    }
                    else if (d.contentType == 'daily-feed') {
                        return d.key;
                    }
                    else {
                        return "";
                    }
                });

        });
    }
    function zoom() {
        dom.svg.attr("transform", "translate(" + d3.event.translate + ")scale(" + d3.event.scale + ")");
    }
};<|endoftext|>


<commit_before>/**
 * InvertedIndex Class
 * @class
 */
class InvertedIndex {

  /**
   * class constructor
   * @constructor
   */
  constructor() {
    this.indexMap = {};
  }

  /**
   * Sanitizes text by removing invalid symbols.
   *
   * @param {Array} indexes - String to sanitize
   * @return {Array} array of words without special characters or symbols.
   */
  sanitize(indexes) {
    return indexes.map(word => word.toLowerCase()
      .replace(/[^A-Za-z0-9]/g, ''));
  }

  /*
   * Verify File Checks
   */
  verifyFile(fileContent) {
    if (fileContent[0] && fileContent[0].title) {
      return fileContent;
    } else {
      return false;
    }
  }

  /**
   * Create File Index
   *
   * @param {String} fileName - Uploaded file
   * @param {String} fileContent - Contents of the Json file.
   */
  createIndex(fileName, fileContent) {
    const completeIndex = [];
    if (this.verifyFile(fileContent)) {
      for (const value of fileContent) {
        const title = value.title;
        const text = value.text;
        const mergeWords = title + ' ' + text;
        completeIndex.push(this.sanitize(mergeWords.split(' ')));
      }
    } else {
      return false;
    }
    this.storeIndex(fileName, completeIndex);
  }

  /**
   * Stores the File Index
   *
   * @param {String} fileName
   * @param {String} fileContents
   */
  storeIndex(fileName, completeIndex) {
    const wordIndex = {};
    for (const pos in completeIndex) {
      let posToInt = parseInt(pos);
      completeIndex[pos].forEach((word) => {
        if (wordIndex[word]) {
          if (wordIndex[word].indexOf(posToInt) === -1) {
            wordIndex[word].push(posToInt);
          }
        } else {
          wordIndex[word] = [posToInt];
        }
      });
    }
    this.indexMap[fileName] = wordIndex;
  }

  /**
   * Get File Index
   *
   * @param {String} fileName
   * @return {Object} returns file contents
   */
  getIndex(fileName) {
    return this.indexMap[fileName];
  }

  /**
   * Search a File
   *
   * @param {String} fileName
   * @param {String} terms
   * @return {Object} returns search results
   */

  /**
   * Search a File
   *
   * @param {String} fileName
   * @param {String} terms
   * @return {Object} returns search results
   */
  searchaFile(fileName, terms) {
    const searchResult = {};
    const sanitizeQuery = this.sanitize(terms);
    const allFiles = this.indexMap;

    searchResult[fileName] = {};
    sanitizeQuery.forEach((term) => {
      if (allFiles[fileName][term]) {
        searchResult[fileName][term] = allFiles[fileName][term];
      } else {
        searchResult[fileName][term] = [];
      }
    });
    return searchResult;
  }

  /**
   * Search Index for 1 or multiple files
   *
   * @param {String} fileName
   * @param {String} terms
   * @return {Array} returns search results
   *  */

  searchIndex(fileName, terms) {
    const searchResult = [];
    const allFiles = this.indexMap;
    let query = [];

    for (let i = 1; i < arguments.length; i+=1) {
      if (Array.isArray(arguments[i])) {
        query = query.concat(arguments[i]);
      } else {
        query.push(arguments[i]);
      }
    }

    if (fileName === 'all') {
      for (const file in allFiles) {
        const search = this.searchaFile(file, query);
        searchResult.push(search);
      }
    } else {
      const search = this.searchaFile(fileName, query);
      searchResult.push(search);
    }
    return searchResult;
  }
}
<commit_msg>app(format): Address format issues in inverted index class<commit_after>/**
 * InvertedIndex Class
 * @class
 */
class InvertedIndex {

  /**
   * class constructor
   * @constructor
   */
  constructor() {
    this.indexMap = {};
  }

  /**
   * Sanitizes text by removing invalid symbols.
   *
   * @param {Array} indexes - String to sanitize
   * @return {Array} array of words without special characters or symbols.
   */
  sanitize(indexes) {
    return indexes.map(word => word.toLowerCase()
      .replace(/[^A-Za-z0-9]/g, ''));
  }

  /*
   * Verify File Checks
   */
  verifyFile(fileContent) {
    if (fileContent[0] && fileContent[0].title) {
      return fileContent;
    } else {
      return false;
    }
  }

  /**
   * Create File Index
   *
   * @param {String} fileName - Uploaded file
   * @param {String} fileContent - Contents of the Json file.
   */
  createIndex(fileName, fileContent) {
    const completeIndex = [];
    if (this.verifyFile(fileContent)) {
      for (const value of fileContent) {
        const title = value.title;
        const text = value.text;
        const mergeWords = title + ' ' + text;
        completeIndex.push(this.sanitize(mergeWords.split(' ')));
      }
    } else {
      return false;
    }
    this.storeIndex(fileName, completeIndex);
  }

  /**
   * Stores the File Index
   *
   * @param {String} fileName
   * @param {String} fileContents
   */
  storeIndex(fileName, completeIndex) {
    const wordIndex = {};
    for (const pos in completeIndex) {
      let posToInt = parseInt(pos);
      completeIndex[pos].forEach((word) => {
        if (wordIndex[word]) {
          if (wordIndex[word].indexOf(posToInt) === -1) {
            wordIndex[word].push(posToInt);
          }
        } else {
          wordIndex[word] = [posToInt];
        }
      });
    }
    this.indexMap[fileName] = wordIndex;
  }

  /**
   * Get File Index
   *
   * @param {String} fileName
   * @return {Object} returns file contents
   */
  getIndex(fileName) {
    return this.indexMap[fileName];
  }

  /**
   * Search a File
   *
   * @param {String} fileName
   * @param {String} terms
   * @return {Object} returns search results
   */
  searchaFile(fileName, terms) {
    const searchResult = {};
    const sanitizeQuery = this.sanitize(terms);
    const allFiles = this.indexMap;

    searchResult[fileName] = {};
    sanitizeQuery.forEach((term) => {
      if (allFiles[fileName][term]) {
        searchResult[fileName][term] = allFiles[fileName][term];
      } else {
        searchResult[fileName][term] = [];
      }
    });
    return searchResult;
  }

  /**
   * Search Index for 1 or multiple files
   *
   * @param {String} fileName
   * @param {String} terms
   * @return {Array} returns search results
   */
  searchIndex(fileName, terms) {
    const searchResult = [];
    const allFiles = this.indexMap;
    let query = [];

    for (let i = 1; i < arguments.length; i += 1) {
      if (Array.isArray(arguments[i])) {
        query = query.concat(arguments[i]);
      } else {
        query.push(arguments[i]);
      }
    }
    if (fileName === 'all') {
      for (const file in allFiles) {
        const search = this.searchaFile(file, query);
        searchResult.push(search);
      }
    } else {
      const search = this.searchaFile(fileName, query);
      searchResult.push(search);
    }
    return searchResult;
  }
}<|endoftext|>


<commit_before>const path = require('path')
const webpack = require('webpack')
const ExtractTextPlugin = require('extract-text-webpack-plugin')

const srcPath = path.resolve('./src')
const imagePath = path.resolve('./dist/images')
const vendorPath = path.resolve('./vendor')

const DEV = 'development'

if (!process.env.BUILD_ENV) {
  process.env.BUILD_ENV = DEV
}

const toString = x => JSON.stringify(x);

const Sparks = {
  buildEnv: toString(process.env.BUILD_ENV),
  firebase: {
    databaseURL: toString(process.env.FIREBASE_DATABASE_URL),
    apiKey: toString(process.env.FIREBASE_API_KEY),
    authDomain: toString(process.env.FIREBASE_AUTH_DOMAIN),
    storageBucket: toString(process.env.FIREBASE_STORAGE_BUCKET),
    messagingSenderId: toString(process.env.FIREBASE_MESSAGING_SENDER_ID),
  }
}

const basePlugins = [
  new webpack.EnvironmentPlugin([
    'BUILD_ENV',
    'FIREBASE_DATABASE_URL',
    'FIREBASE_API_KEY',
    'FIREBASE_AUTH_DOMAIN',
    'FIREBASE_STORAGE_BUCKET',
    'FIREBASE_MESSAGING_SENDER_ID'
  ]),
  new webpack.DefinePlugin({ Sparks }),
  new ExtractTextPlugin({filename: 'styles.css', allChunks: true })
]

const prodPlugins = [
  new webpack.optimize.UglifyJsPlugin({ minimize: true })
]

const devPlugins = [
]

const plugins = process.env.BUILD_ENV === DEV
  ? basePlugins.concat(devPlugins)
  : basePlugins.concat(prodPlugins)

const TSLoader = {
  test: /\.ts$/,
  loader: 'awesome-typescript-loader',
  exclude: /node_modules/
}

const SASSLoader = {
  test: /\.scss$/,
  loader: ExtractTextPlugin.extract({
    fallbackLoader: 'style-loader',
    loader: 'css-loader?modules&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]' +
    '!postcss-loader' +
    '!sass-loader?outputStyle=expanded'
  })
}

const CSSLoader = {
  test: /\.css$/,
  loader: ExtractTextPlugin.extract({
    fallbackLoader: 'style-loader',
    loader: 'css-loader?modules&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]' +
    '!postcss-loader'
  }),
}

const ImageLoader = {
  test: /\.(jpe?g|png|gif|svg)$/i,
  loaders: [
    'file?hash=sha512&digest=hex&name=[hash].[ext]',
    'image-webpack?bypassOnDebug&optimizationLevel=7&interlaced=false',
  ],
}

const environmentOptions = process.env.BUILD_ENV === 'production'
  ? { }
  : {
    debug: true,
    devtool: 'source-map',
  }

module.exports = {
  plugins,

  debug: process.env.BUILD_ENV === DEV,
  devtool: process.env.BUILD_ENV === DEV ? 'source-map': '',

  entry: [
    path.join(srcPath, 'app.ts'),
  ],

  output: {
    path: './dist',
    filename: 'bundle.js',
    publicPath: 'http://localhost:8080/',
  },

  devServer: {
    contentBase: path.resolve('./dist'),
    historyApiFallback: true,
  },

  output: {
    path: path.resolve('./dist'),
    filename: 'bundle.js',
    publicPath: 'http://localhost:8080/',
  },

  devServer: {
    contentBase: path.resolve('./dist'),
    historyApiFallback: true,
  },

  module: {
    loaders: [
      TSLoader,
      SASSLoader,
      CSSLoader,
      ImageLoader,
    ],
  },

  mainFields: ['jsnext:main', 'main'],

  resolve: {
    extensions: ['.ts', '.js'],
    alias: {
      // You can not get in-editor typings with aliases
      // component: srcPath + '/component',
      // page: srcPath + '/page',
      // driver: srcPath + '/driver',
      // module: srcPath + '/module',
      // util: srcPath + '/util',
      // remote: srcPath + '/remote',
      // translation: srcPath + '/translation',
      // images: imagePath,
      // surface: vendorPath + '/surface',
    },
  },
}
<commit_msg>chore(webpack): fix webpack config for later versions<commit_after>const path = require('path')
const webpack = require('webpack')
const ExtractTextPlugin = require('extract-text-webpack-plugin')

const srcPath = path.resolve('./src')
const imagePath = path.resolve('./dist/images')
const vendorPath = path.resolve('./vendor')

const DEV = 'development'

if (!process.env.BUILD_ENV) {
  process.env.BUILD_ENV = DEV
}

const toString = x => JSON.stringify(x);

const Sparks = {
  buildEnv: toString(process.env.BUILD_ENV),
  firebase: {
    databaseURL: toString(process.env.FIREBASE_DATABASE_URL),
    apiKey: toString(process.env.FIREBASE_API_KEY),
    authDomain: toString(process.env.FIREBASE_AUTH_DOMAIN),
    storageBucket: toString(process.env.FIREBASE_STORAGE_BUCKET),
    messagingSenderId: toString(process.env.FIREBASE_MESSAGING_SENDER_ID),
  }
}

const basePlugins = [
  new webpack.EnvironmentPlugin([
    'BUILD_ENV',
    'FIREBASE_DATABASE_URL',
    'FIREBASE_API_KEY',
    'FIREBASE_AUTH_DOMAIN',
    'FIREBASE_STORAGE_BUCKET',
    'FIREBASE_MESSAGING_SENDER_ID'
  ]),
  new webpack.DefinePlugin({ Sparks }),
  new ExtractTextPlugin({filename: 'styles.css', allChunks: true })
]

const prodPlugins = [
  new webpack.optimize.UglifyJsPlugin({ minimize: true })
]

const devPlugins = [
]

const plugins = process.env.BUILD_ENV === DEV
  ? basePlugins.concat(devPlugins)
  : basePlugins.concat(prodPlugins)

const TSLoader = {
  test: /\.ts$/,
  loader: 'awesome-typescript-loader',
  exclude: /node_modules/
}

const SASSLoader = {
  test: /\.scss$/,
  loader: ExtractTextPlugin.extract({
    fallbackLoader: 'style-loader',
    loader: 'css-loader?modules&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]' +
    '!postcss-loader' +
    '!sass-loader?outputStyle=expanded'
  })
}

const CSSLoader = {
  test: /\.css$/,
  loader: ExtractTextPlugin.extract({
    fallbackLoader: 'style-loader',
    loader: 'css-loader?modules&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]' +
    '!postcss-loader'
  }),
}

const ImageLoader = {
  test: /\.(jpe?g|png|gif|svg)$/i,
  loaders: [
    'file?hash=sha512&digest=hex&name=[hash].[ext]',
    'image-webpack?bypassOnDebug&optimizationLevel=7&interlaced=false',
  ],
}

const environmentOptions = process.env.BUILD_ENV === 'production'
  ? { }
  : {
   devtool: 'source-map',
  }

module.exports = {
  plugins,

  devtool: process.env.BUILD_ENV === DEV ? 'source-map': '',

  entry: [
    path.join(srcPath, 'app.ts'),
  ],

  output: {
    path: './dist',
    filename: 'bundle.js',
    publicPath: 'http://localhost:8080/',
  },

  devServer: {
    contentBase: path.resolve('./dist'),
    historyApiFallback: true,
  },

  output: {
    path: path.resolve('./dist'),
    filename: 'bundle.js',
    publicPath: 'http://localhost:8080/',
  },

  devServer: {
    contentBase: path.resolve('./dist'),
    historyApiFallback: true,
  },

  module: {
    loaders: [
      TSLoader,
      SASSLoader,
      CSSLoader,
      ImageLoader,
    ],
  },

  resolve: {
    extensions: ['.ts', '.js'],
    alias: {
      // You can not get in-editor typings with aliases
      // component: srcPath + '/component',
      // page: srcPath + '/page',
      // driver: srcPath + '/driver',
      // module: srcPath + '/module',
      // util: srcPath + '/util',
      // remote: srcPath + '/remote',
      // translation: srcPath + '/translation',
      // images: imagePath,
      // surface: vendorPath + '/surface',
    },
  },
}
<|endoftext|>