code stringlengths 2 1.05M |
|---|
import { getSettings } from 'app/reducers';
import save from 'app/storage/settings-storage';
import { SETTINGS_SAVE_RECEIVED, SETTINGS_SAVE_REJECT, SETTINGS_SAVE_REQUEST } from '../action-types';
export function requestSaveSettings() {
return {
type: SETTINGS_SAVE_REQUEST,
};
}
export function rejectSaveSettings() {
return {
type: SETTINGS_SAVE_REJECT,
};
}
export function receiveSaveSettings(settings) {
return {
settings,
type: SETTINGS_SAVE_RECEIVED,
};
}
export default function saveSettings(settings) {
return (dispatch, getState) => {
dispatch(requestSaveSettings());
const {
app,
data,
} = getSettings(getState());
const newSettings = {
app,
data,
...settings,
};
return save(newSettings)
.then((json) => {
dispatch(receiveSaveSettings(json));
})
.catch((error) => {
dispatch(rejectSaveSettings(error));
})
;
};
}
|
class ias_netdatastore_1 {
constructor() {
// IDataStoreObject Root () {get}
this.Root = undefined;
}
// void Initialize (string, string, string, bool)
Initialize(string, string, string, bool) {
}
// IDataStoreObject OpenObject (string)
OpenObject(string) {
}
// void Shutdown ()
Shutdown() {
}
}
module.exports = ias_netdatastore_1;
|
import { connect } from 'react-redux';
import { showOfficerModal, deleteOfficerModal } from 'common/actions';
import List from 'common/components/List';
import { getOfficers } from 'officers/actions';
import Officer from 'officers/components/Officer';
const order = new Map([
['President', 0],
['Vice President', 1],
['Treasurer', 2],
['Secretary', 3],
['Technology Head', 4], // dev only
]);
const sortPredicate = (officerA, officerB) => {
if (order.get(officerA.title) > order.get(officerB.title)) {
return 1;
}
return -1;
}
function mapStateToProps({ auth, officers }, { primary = false }) {
return {
item: Officer,
items: Object.values(officers)
.filter(({ primaryOfficer }) => primaryOfficer === primary)
.sort(sortPredicate),
itemProps: {
showActions: !!(auth.officer && auth.officer.primaryOfficer),
},
wrapperProps: {
className: 'row',
},
};
}
function mapDispatchToProps(dispatch) {
return {
getItems: () => dispatch(getOfficers()),
deleteItem: id => dispatch(deleteOfficerModal(id)),
editItem: id => dispatch(showOfficerModal(id)),
};
}
export default connect(mapStateToProps, mapDispatchToProps)(List);
|
import { app, ipcMain, BrowserWindow, Menu, shell, dialog, screen } from 'electron';
import configureStore from './shared/store/configureStore';
import pify from 'pify';
import jsonStorage from 'electron-json-storage';
let menu;
let template;
let mainWindow = null;
let moduleSelectWindow = null;
if (process.env.NODE_ENV === 'production') {
const sourceMapSupport = require('source-map-support'); // eslint-disable-line
sourceMapSupport.install();
}
if (process.env.NODE_ENV === 'development') {
require('electron-debug')(); // eslint-disable-line global-require
const path = require('path'); // eslint-disable-line
const p = path.join(__dirname, '..', 'app', 'node_modules'); // eslint-disable-line
require('module').globalPaths.push(p); // eslint-disable-line
}
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') app.quit();
});
const installExtensions = async () => {
if (process.env.NODE_ENV === 'development') {
const installer = require('electron-devtools-installer'); // eslint-disable-line global-require
const extensions = [
'REACT_DEVELOPER_TOOLS',
'REDUX_DEVTOOLS'
];
const forceDownload = !!process.env.UPGRADE_EXTENSIONS;
for (const name of extensions) { // eslint-disable-line
try {
await installer.default(installer[name], forceDownload);
} catch (e) {} // eslint-disable-line
}
}
};
const storage = pify(jsonStorage);
async function start() {
const store = configureStore(global.state, "main");
store.subscribe(async () => {
await storage.set("state", store.getState());
});
}
app.on('ready', async () => {
start().catch((err) => {
dialog.showErrorBox("There has been an error", err.message);
});
await installExtensions();
let primaryDisplay = screen.getPrimaryDisplay();
let screenSize = primaryDisplay.workAreaSize;
let bounds = primaryDisplay.bounds;
let mainWindowWidth = screenSize.width * 0.75;
let moduleWindowWidth = screenSize.width * 0.25;
mainWindow = new BrowserWindow({
show: false,
width: mainWindowWidth,
height: screenSize.height,
x: bounds.x,
y: bounds.y
});
mainWindow.loadURL(`file://${__dirname}/renderer/main/app.html`);
mainWindow.webContents.on('did-finish-load', () => {
mainWindow.show();
mainWindow.focus();
});
mainWindow.on('closed', () => {
mainWindow = null;
});
moduleSelectWindow = new BrowserWindow({
show: true,
width: moduleWindowWidth,
height: screenSize.height,
x: bounds.x + mainWindowWidth,
y: bounds.y
});
moduleSelectWindow.loadURL(`file://${__dirname}/renderer/moduleSelect/moduleSelect.html`);
moduleSelectWindow.on('did-finish-load', () => {
moduleSelectWindow.show();
});
moduleSelectWindow.on('closed', () => {
moduleSelectWindow = null;
});
if (process.env.NODE_ENV === 'development') {
mainWindow.openDevTools();
moduleSelectWindow.openDevTools();
mainWindow.webContents.on('context-menu', (e, props) => {
const { x, y } = props;
Menu.buildFromTemplate([{
label: 'Inspect element',
click() {
mainWindow.inspectElement(x, y);
}
}]).popup(mainWindow);
});
}
if (process.platform === 'darwin') {
template = [{
label: 'Electron',
submenu: [{
label: 'About ElectronReact',
selector: 'orderFrontStandardAboutPanel:'
}, {
type: 'separator'
}, {
label: 'Services',
submenu: []
}, {
type: 'separator'
}, {
label: 'Hide ElectronReact',
accelerator: 'Command+H',
selector: 'hide:'
}, {
label: 'Hide Others',
accelerator: 'Command+Shift+H',
selector: 'hideOtherApplications:'
}, {
label: 'Show All',
selector: 'unhideAllApplications:'
}, {
type: 'separator'
}, {
label: 'Quit',
accelerator: 'Command+Q',
click() {
app.quit();
}
}]
}, {
label: 'Edit',
submenu: [{
label: 'Undo',
accelerator: 'Command+Z',
selector: 'undo:'
}, {
label: 'Redo',
accelerator: 'Shift+Command+Z',
selector: 'redo:'
}, {
type: 'separator'
}, {
label: 'Cut',
accelerator: 'Command+X',
selector: 'cut:'
}, {
label: 'Copy',
accelerator: 'Command+C',
selector: 'copy:'
}, {
label: 'Paste',
accelerator: 'Command+V',
selector: 'paste:'
}, {
label: 'Select All',
accelerator: 'Command+A',
selector: 'selectAll:'
}]
}, {
label: 'View',
submenu: (process.env.NODE_ENV === 'development') ? [{
label: 'Reload',
accelerator: 'Command+R',
click() {
mainWindow.webContents.reload();
}
}, {
label: 'Toggle Full Screen',
accelerator: 'Ctrl+Command+F',
click() {
mainWindow.setFullScreen(!mainWindow.isFullScreen());
}
}, {
label: 'Toggle Developer Tools',
accelerator: 'Alt+Command+I',
click() {
mainWindow.toggleDevTools();
}
}] : [{
label: 'Toggle Full Screen',
accelerator: 'Ctrl+Command+F',
click() {
mainWindow.setFullScreen(!mainWindow.isFullScreen());
}
}]
}, {
label: 'Window',
submenu: [{
label: 'Minimize',
accelerator: 'Command+M',
selector: 'performMiniaturize:'
}, {
label: 'Close',
accelerator: 'Command+W',
selector: 'performClose:'
}, {
type: 'separator'
}, {
label: 'Bring All to Front',
selector: 'arrangeInFront:'
}]
}, {
label: 'Help',
submenu: [{
label: 'Learn More',
click() {
shell.openExternal('http://electron.atom.io');
}
}, {
label: 'Documentation',
click() {
shell.openExternal('https://github.com/atom/electron/tree/master/docs#readme');
}
}, {
label: 'Community Discussions',
click() {
shell.openExternal('https://discuss.atom.io/c/electron');
}
}, {
label: 'Search Issues',
click() {
shell.openExternal('https://github.com/atom/electron/issues');
}
}]
}];
menu = Menu.buildFromTemplate(template);
Menu.setApplicationMenu(menu);
} else {
template = [{
label: '&File',
submenu: [{
label: '&Open',
accelerator: 'Ctrl+O'
}, {
label: '&Close',
accelerator: 'Ctrl+W',
click() {
mainWindow.close();
}
}]
}, {
label: '&View',
submenu: (process.env.NODE_ENV === 'development') ? [{
label: '&Reload',
accelerator: 'Ctrl+R',
click() {
mainWindow.webContents.reload();
}
}, {
label: 'Toggle &Full Screen',
accelerator: 'F11',
click() {
mainWindow.setFullScreen(!mainWindow.isFullScreen());
}
}, {
label: 'Toggle &Developer Tools',
accelerator: 'Alt+Ctrl+I',
click() {
mainWindow.toggleDevTools();
}
}] : [{
label: 'Toggle &Full Screen',
accelerator: 'F11',
click() {
mainWindow.setFullScreen(!mainWindow.isFullScreen());
}
}]
}, {
label: 'Help',
submenu: [{
label: 'Learn More',
click() {
shell.openExternal('http://electron.atom.io');
}
}, {
label: 'Documentation',
click() {
shell.openExternal('https://github.com/atom/electron/tree/master/docs#readme');
}
}, {
label: 'Community Discussions',
click() {
shell.openExternal('https://discuss.atom.io/c/electron');
}
}, {
label: 'Search Issues',
click() {
shell.openExternal('https://github.com/atom/electron/issues');
}
}]
}];
menu = Menu.buildFromTemplate(template);
mainWindow.setMenu(menu);
}
});
app.on('uncaughtException', (error) => { dialog.showErrorBox(error.message) });
|
var findAddById = function(id){
var returnList = null;
$.ajax({
type: 'post',
dataType: 'json',
url: "/Index/getAddrListById",
async: false,
contentType: "application/x-www-form-urlencoded; charset=utf-8",
data: {id: id},
success: function (returnData){returnList = returnData;}
});
return returnList[0];
}
var findProNameAndParent = function(id){
var obj = {tid:id, name:"",isParent:false};
$.ajax({
type: 'post',
dataType: 'json',
url: "/Index/getAjaxAddrList",
async: false,
contentType: "application/x-www-form-urlencoded; charset=utf-8",
success: function (returnData){
for(var i = 0, l = returnData.length; i<l; ++i){
if(returnData[i].tid == id || returnData[i].parent_id == id){
obj.name = returnData[i].name;
obj.isParent = returnData[i].parent_id?true:false;
break;
}
}
}
});
if(!obj.name) obj = {tid:110000,name:'北京',isParent:true}
return obj;
}
var findListById = function(id,testId){
var obj = {};
$.ajax({
type: 'post',
dataType: 'json',
url: "/Index/getAddrListById",
async: false,
contentType: "application/x-www-form-urlencoded; charset=utf-8",
data: {id: id},
success: function (returnData){
for(var i = 0, l = returnData.length; i < l; ++i){
if(returnData[i].tid == testId){
obj.tid = testId;
obj.name = returnData[i].name;
}
}
}
});
return obj;
}
// 默认地址
var _one = findProNameAndParent($.cookie('cb_province_id')||110000);
var _two = $.cookie('cb_address_city')?findListById(_one['tid'],$.cookie('cb_address_city')):findAddById(_one['tid']);
var _three = $.cookie('cb_address_district')?findListById(_two['tid'],$.cookie('cb_address_district')):findAddById(_two['tid']);
var _four = $.cookie('cb_address_street')?findListById(_three['tid'],$.cookie('cb_address_street')):findAddById(_three['tid']);
var _textArr = [_one['name'],_one.isParent? _three['name']:_two['name'],_one.isParent?_four['name']:_three['name']];
var _addObj = {
one:_one,
two:_two,
three:_three,
four:_four,
text:$.cookie('cb_address_text')||_textArr.join(''),
isParent:_one.isParent
}
$('input[name="city"]').val(_addObj.two['tid']);
$('input[name="district"]').val(_addObj.three['tid']);
$('input[name="street"]').val(_addObj.four['tid']);
// 直辖市 134,省市县 123
(function (window) {
// 借用_addObj
function Address(isProduct,options) {
var that = this;
that.provinceListHTML = isProduct ? $('#product-address .provinceList') : $("#provinceList");
that.cityListHTML = isProduct ? $('#product-address .cityList') : $("#cityList");
that.districtListHTML = isProduct ? $('#product-address .districtList') : $("#districtList");
that.tabProvince = isProduct ? $('#product-address .tabProvince') : $("#tabProvince");
that.tabCity = isProduct ? $('#product-address .tabCity') : $("#tabCity");
that.tabDistrict = isProduct ? $('#product-address .tabDistrict') : $("#tabDistrict");
that.isProductPage = isProduct;
that.addressObj = {
isParent:options.isParent,
one:{tid: options.one['tid'], name: options.one['name']},
two:{tid: options.two['tid'], name: options.two['name']},
three:{tid: options.three['tid'], name: options.three['name']},
four:{tid: options.four['tid'], name: options.four['name']}
};
}
Address.prototype.setProductPage = function () {
this.isProductPage = true;
}
Address.prototype.loadAddressFromCookie = function () {
var that = this;
$.ajax({
type: 'post',
dataType: 'json',
url: "/Index/getAjaxAddrList",
contentType: "application/x-www-form-urlencoded; charset=utf-8",
success: function (returnData)
{
that.provinceListHTML.empty();
$.each(returnData, function (idx, province) {
var myClass = that.getCityNameClass(province.name);
that.provinceListHTML.append('<li class="' + myClass + '" data-province="' + province.tid + '" data-parent-id="' + province.parent_id + '" data-site-id="' + province.site_id + '"><span>' + province.name + '</span></li>');
});
that.bindProvinceListClick();
that.setAddressInfoFromCookie();
}
});
that.tabProvince.unbind("click").bind('click', function () {
that.showProvinceTab();
});
that.tabCity.unbind("click").bind('click', function () {
that.showCityTab();
});
that.tabDistrict.unbind("click").bind('click', function () {
that.showDistrictTab();
});
};
Address.prototype.bindProvinceListClick = function () {
var that = this;
that.provinceListHTML.find('li').each(function () {
var li = $(this);
li.unbind("click").bind('click', function () {
var provinceId = li.attr('data-province');
var parentId = li.attr('data-parent-id');
var siteId = li.attr('data-site-id');
var provinceName = li.find('span').text();
var isParent = that.checkIsParentId(parentId);
if(isParent){
that.addressObj.isParent = true
that.addressObj.one = {
tid: parentId,
name: provinceName
}
that.addressObj.two = {
tid: provinceId,
name: provinceName
}
}else{
that.addressObj.isParent = false
that.addressObj.one = {
tid: provinceId,
name: provinceName
}
}
if (isParent && !that.isProductPage) {
that.addressObj.three = {tid:'',name:''}
that.addressObj.four = {tid:'',name:''}
that.writeHotCityToCookie(siteId, provinceId, provinceName, parentId);
window.location.reload();
return;
}
else {
that.showCityTab();
that.tabProvince.find('span').text(li.text());
li.addClass('on').siblings().removeClass('on');
var cityList = that.getAddrListById(provinceId);
that.showCityList(cityList, provinceId);
that.tabCity.find('span').text('请选择');
}
});
});
};
Address.prototype.showProvinceTab = function () {
var that = this;
that.provinceListHTML.show();
that.cityListHTML.hide();
that.districtListHTML.hide();
that.tabProvince.addClass('on');
that.tabCity.removeClass('on');
that.tabDistrict.removeClass('on');
};
Address.prototype.showCityTab = function () {
var that = this;
that.provinceListHTML.hide();
that.cityListHTML.show();
that.districtListHTML.hide();
that.tabProvince.removeClass('on');
that.tabCity.show().addClass('on');
that.tabDistrict.removeClass('on');
};
Address.prototype.showDistrictTab = function () {
var that = this;
that.provinceListHTML.hide();
that.cityListHTML.hide();
that.districtListHTML.show();
that.tabProvince.removeClass('on');
that.tabCity.show().removeClass('on');
that.tabDistrict.show().addClass('on');
};
Address.prototype.showCityList = function (cityList, provinceId) {
var that = this;
that.cityListHTML.empty();
$.each(cityList, function (idx, city) {
var myClass = that.getCityNameClass(city.name);
that.cityListHTML.append('<li class="' + myClass + '" data-city="' + city.tid + '" data-site-id="' + city.site_id + '"><span>' + city.name + '</span></li>');
});
that.bindCityListClick(that.cityListHTML, provinceId);
};
Address.prototype.bindCityListClick = function (cityListHTML, provinceId) {
var that = this;
that.cityListHTML.find('li').each(function () {
var liCity = $(this);
liCity.unbind("click").bind('click', function () {
var siteId = liCity.attr('data-site-id');
var cityId = liCity.attr('data-city');
var cityName = liCity.text();
that.tabCity.find('span').text(cityName);
if(that.addressObj.isParent){
that.addressObj.three = {
tid: cityId,
name: cityName
}
}else{
that.addressObj.two = {
tid: cityId,
name: cityName
}
}
if (that.isProductPage) {
that.showDistrictTab();
that.tabDistrict.find('span').text('请选择');
var districtList = that.getAddrListById(cityId);
that.showDistrictList(districtList, cityId, provinceId);
}
else {
that.addressObj.four = {tid:'',name:''}
that.writeHotCityToCookie(siteId, cityId, cityName, provinceId);
window.location.reload();
}
});
});
};
Address.prototype.showDistrictList = function (districtList, cityId, provinceId) {
var that = this;
that.districtListHTML.empty();
$.each(districtList, function (idx, district) {
var myClass = that.getCityNameClass(district.name);
that.districtListHTML.append('<li class="' + myClass + '" data-district="' + district.tid + '" data-site-id="' + district.site_id + '"><span>' + district.name + '</span></li>');
});
that.bindDistrictListClick(that.districtListHTML, provinceId, cityId);
};
Address.prototype.bindDistrictListClick = function (districtListHTML, provinceId, cityId) {
var that = this;
that.districtListHTML.find('li').each(function () {
var liDistrict = $(this);
liDistrict.unbind("click").bind('click', function () {
var siteId = liDistrict.attr('data-site-id');
var districtId = liDistrict.attr('data-district');
var districtName = liDistrict.text();
that.tabDistrict.find('span').text(districtName);
if(that.addressObj.isParent){
that.addressObj.four = {
tid: districtId,
name: districtName
}
}else{
that.addressObj.three = {
tid: districtId,
name: districtName
}
}
//
$('#address-text span').text($('#product-address .tabProvince').text()+$('#product-address .tabCity').text()+districtName);
that.writeHotCityToCookie(siteId, cityId, districtName, provinceId, districtId);
window.location.reload();
});
});
};
Address.prototype.getCityNameClass = function (txt) {
var that = this;
var className = ' ';
if (txt.length > 6) {
className = 'mid-long';
}
if (txt.length > 12) {
className = 'big-long';
}
return className;
};
Address.prototype.setAddressInfoFromCookie = function () {
var that = this;
that.showProvinceTab();
var provinceId = $.cookie("cb_province_id");
if (!isNaN(provinceId) && provinceId > 0) {
var currentLiParent = that.provinceListHTML.find('li[data-parent-id="' + provinceId + '"]');
if (currentLiParent.length > 0) {//北京,上海等
currentLiParent.addClass('on');
currentLiParent.siblings().removeClass('on');
that.tabProvince.find('span').text(currentLiParent.text());
return;
}
else {
var currentLiProvince = that.provinceListHTML.find('li[data-province="' + provinceId + '"]');
currentLiProvince.addClass('on');
currentLiProvince.siblings().removeClass('on');
that.tabProvince.find('span').text(currentLiProvince.text());
}
that.showCityTab();
var cityId = $.cookie("cb_address_city");
if (!isNaN(cityId) && cityId > 0) {
that.setCityInfoFromCookie(provinceId, cityId);
if(that.isProductPage){
var districtId = $.cookie("cb_address_district");
if (!isNaN(districtId) && districtId > 0) {
that.setDistrictInfoFromCookie(provinceId,cityId,districtId);
}
}
}
}
};
Address.prototype.setCityInfoFromCookie = function (provinceId, cityId) {
var that = this;
var cityList = that.getAddrListById(provinceId);
that.showCityList(cityList, provinceId);
//设置
var currentLi = that.cityListHTML.find('li[data-city="' + cityId + '"]');
currentLi.addClass('on');
currentLi.siblings().removeClass('on');
that.tabCity.find('span').text(currentLi.text());
};
Address.prototype.setDistrictInfoFromCookie = function (provinceId,cityId, districtId) {
var that = this;
that.showDistrictTab();
var districtList = that.getAddrListById(cityId);
that.showDistrictList(districtList, cityId,provinceId);
//设置
var currentLi = that.districtListHTML.find('li[data-district="' + districtId + '"]');
currentLi.addClass('on');
currentLi.siblings().removeClass('on');
that.tabDistrict.find('span').text(currentLi.text());
};
Address.prototype.checkIsParentId = function (parentId) {
var that = this;
if (typeof parentId != 'undefined' && parentId > 0) {
return true;
}
return false;
};
Address.prototype.getAddrListById = function (id) {
var that = this;
var returnList = null;
$.ajax({
type: 'post',
dataType: 'json',
url: "/Index/getAddrListById",
async: false,
contentType: "application/x-www-form-urlencoded; charset=utf-8",
data: {id: id},
success: function (returnData)
{
returnList = returnData;
}
});
return returnList;
};
Address.prototype.setSelectHotCity = function () {
var that = this;
var cityId = $.cookie('cb_address_city');
if (cityId > 0) {
$('.hot-city-list').find('li').each(function () {
var liObj = $(this);
if (liObj.attr("data-city-id") == cityId) {
liObj.addClass('on');
}
});
}
};
Address.prototype.writeHotCityToCookie = function (siteId, cityId, cityName, provinceId, districtId) {
var that = this;
var cookieDomain = '.yejing.com';
if (siteId == null || siteId == 'null') {
siteId = 4;
}
var date_history = new Date();
date_history.setTime(date_history.getTime() + (365 * 24 * 60 * 60 * 1000));
if(!that.addressObj.isParent){
that.addressObj.four = {
tid: that.getAddrListById(that.addressObj.three.tid)[0]['tid'],
name: that.getAddrListById(that.addressObj.three.tid)[0]['name']
}
}
$.cookie("cb_site_id", siteId, {expires: date_history, path: "/", domain: cookieDomain});
$.cookie("cb_province_id", that.addressObj.one.tid, {expires: date_history, path: "/", domain: cookieDomain});
$.cookie("cb_site_name", (that.addressObj.isParent ? that.addressObj.one.name : that.addressObj.two.name), {expires: date_history, path: "/", domain: cookieDomain});
$.cookie("cb_address_city", that.addressObj.two.tid, {expires: date_history, path: "/", domain: cookieDomain});
$.cookie("cb_address_district", that.addressObj.three.tid, {expires: date_history, path: "/", domain: cookieDomain});
$.cookie("cb_address_street", that.addressObj.four.tid, {expires: date_history, path: "/", domain: cookieDomain});
// var streetList = 0;
// if(that.addressObj.isParent){
// streetList = that.addressObj.three.tid;
// }else{
// streetList = that.getAddrListById(that.addressObj.three.tid)[0]['tid'];
// }
$.cookie("cb_address_text", (that.addressObj.two.name+that.addressObj.three.name+that.addressObj.four.name), {expires: date_history, path: "/", domain: cookieDomain});
};
window.AddressSwitch = Address;
window.writeHotCityToCookiePolyfill = function(siteId, cityId, cityName, provinceId){
var cookieDomain = '.chunbo.com';
if (siteId == null || siteId == 'null') {
siteId = 4;
}
var date_history = new Date();
date_history.setTime(date_history.getTime() + (365 * 24 * 60 * 60 * 1000));
$.cookie("cb_address_city", cityId, {expires: date_history, path: "/", domain: cookieDomain});
$.cookie("cb_site_id", siteId, {expires: date_history, path: "/", domain: cookieDomain});
$.cookie("cb_site_name", cityName, {expires: date_history, path: "/", domain: cookieDomain});
if (typeof provinceId != 'undefined') {
$.cookie("cb_province_id", provinceId, {expires: date_history, path: "/", domain: cookieDomain});
}
$.cookie("cb_address_district", '', {expires: -1, path: "/", domain: cookieDomain});
$.cookie("cb_address_street", '', {expires: -1, path: "/", domain: cookieDomain});
$.cookie("cb_address_text", '', {expires: -1, path: "/", domain: cookieDomain});
}
})(window);
var s = new AddressSwitch(true,_addObj)
s.loadAddressFromCookie();
$('.content').removeClass('hide') |
import React, {Component, PropTypes} from 'react';
import {bindActionCreators} from 'redux';
import {connect} from 'react-redux';
import {Nav, NavItem} from 'react-bootstrap';
import * as Actions from '../actions';
import Toolbar from '../components/Toolbar';
import DivStyles from '../styles/DivStyles';
import FeelingsPieChart from '../components/charts/FeelingsPieChart';
import AnalyticsStyles from '../styles/AnalyticsStyles';
import EnergyPieChart from '../components/charts/EnergyPieChart';
import EmotionBarChart from '../components/charts/EmotionBarChart';
import SadBarChart from '../components/charts/SadBarChart';
import AngryBarChart from '../components/charts/AngryBarChart';
import AnxiousBarChart from '../components/charts/AnxiousBarChart';
import DisgustBarChart from '../components/charts/DisgustBarChart';
import EnvyBarChart from '../components/charts/EnvyBarChart';
import ExcitedBarChart from '../components/charts/ExcitedBarChart';
import FearBarChart from '../components/charts/FearBarChart';
import HopeBarChart from '../components/charts/HopeBarChart';
import JoyBarChart from '../components/charts/JoyBarChart';
import SurpriseBarChart from '../components/charts/SurpriseBarChart';
import CSPBarChart from '../components/charts/CSPBarChart';
require('../styles/style.css');
class Analytics2 extends Component {
constructor() {
super();
this.state = {
activeKey: 1,
displayedGraph: null
}
}
componentWillMount() {
var graph = this.createGraph('');
this.setState({displayedGraph: graph});
this.setState({activeKey: 1});
}
handleClick(type) {
var graph = this.createGraph(type);
this.setState({displayedGraph: graph})
}
createGraph(type) {
switch(type){
case 'FeelingsPieChart':
this.setState({activeKey: 1});
return (
<div style={AnalyticsStyles.pieChart}>
<h4 style={{textAlign: 'center', fontSize: '20px'}}>Emotions for All Events</h4>
<FeelingsPieChart events={this.props.event.events}></FeelingsPieChart>
</div>
);
case 'EnergyPieChart':
this.setState({activeKey: 2});
return (
<div style={AnalyticsStyles.pieChart}>
<h4 style={{textAlign: 'center', fontSize: '20px'}}>Energy Levels for All Events</h4>
<EnergyPieChart events={this.props.event.events}></EnergyPieChart>
<p>The percentage of time you have felt each energy level where 1 is least energetic and 5 is most energetic.</p>
</div>
);
case 'EmotionBarChart':
this.setState({activeKey: 3});
return (
<div style={AnalyticsStyles.barChart}>
<h4 style={{textAlign: 'center', fontSize: '20px'}}>All "Happy" Events</h4>
<EmotionBarChart events={this.props.event.events}></EmotionBarChart>
<p>These events made you happy for the week!</p>
</div>
);
case 'SadBarChart':
this.setState({activeKey: 4});
return (
<div style={AnalyticsStyles.barChart}>
<h4 style={{textAlign: 'center', fontSize: '20px'}}>All "Sad" Events</h4>
<SadBarChart events={this.props.event.events}></SadBarChart>
<p>These events made you sad for the week</p>
</div>
);
case 'AngryBarChart':
this.setState({activeKey: 5});
return (
<div style={AnalyticsStyles.barChart}>
<h4 style={{textAlign: 'center', fontSize: '20px'}}>All "Angry" Events</h4>
<AngryBarChart events={this.props.event.events}></AngryBarChart>
<p>These events made you angry for the week</p>
</div>
);
case 'AnxiousBarChart':
this.setState({activeKey: 5});
return (
<div style={AnalyticsStyles.barChart}>
<h4 style={{textAlign: 'center', fontSize: '20px'}}>All "Anxious" Events</h4>
<AnxiousBarChart events={this.props.event.events}></AnxiousBarChart>
<p>These events made you anxious for the week</p>
</div>
);
case 'DisgustBarChart':
this.setState({activeKey: 5});
return (
<div style={AnalyticsStyles.barChart}>
<h4 style={{textAlign: 'center', fontSize: '20px'}}>All "Disgust" Events</h4>
<DisgustBarChart events={this.props.event.events}></DisgustBarChart>
<p>These events made you disgusted for the week</p>
</div>
);
case 'EnvyBarChart':
this.setState({activeKey: 5});
return (
<div style={AnalyticsStyles.barChart}>
<h4 style={{textAlign: 'center', fontSize: '20px'}}>All "Envy" Events</h4>
<EnvyBarChart events={this.props.event.events}></EnvyBarChart>
<p>These events made you envious for the week</p>
</div>
);
case 'ExcitedBarChart':
this.setState({activeKey: 5});
return (
<div style={AnalyticsStyles.barChart}>
<h4 style={{textAlign: 'center', fontSize: '20px'}}>All "Excited" Events</h4>
<ExcitedBarChart events={this.props.event.events}></ExcitedBarChart>
<p>These events made you excited for the week</p>
</div>
);
case 'FearBarChart':
this.setState({activeKey: 5});
return (
<div style={AnalyticsStyles.barChart}>
<h4 style={{textAlign: 'center', fontSize: '20px'}}>All "Fear" Events</h4>
<FearBarChart events={this.props.event.events}></FearBarChart>
<p>These events made you fear for the week</p>
</div>
);
case 'HopeBarChart':
this.setState({activeKey: 5});
return (
<div style={AnalyticsStyles.barChart}>
<h4 style={{textAlign: 'center', fontSize: '20px'}}>All "Hope" Events</h4>
<HopeBarChart events={this.props.event.events}></HopeBarChart>
<p>These events made you hopeful for the week</p>
</div>
);
case 'JoyBarChart':
this.setState({activeKey: 5});
return (
<div style={AnalyticsStyles.barChart}>
<h4 style={{textAlign: 'center', fontSize: '20px'}}>All "Joy" Events</h4>
<JoyBarChart events={this.props.event.events}></JoyBarChart>
<p>These events made you joyful for the week</p>
</div>
);
case 'SurpriseBarChart':
this.setState({activeKey: 5});
return (
<div style={AnalyticsStyles.barChart}>
<h4 style={{textAlign: 'center', fontSize: '20px'}}>All "Surprise" Events</h4>
<SurpriseBarChart events={this.props.event.events}></SurpriseBarChart>
<p>These events made you surprised for the week</p>
</div>
);
case 'CSPBarChart':
this.setState({activeKey: 6});
return (
<div style={AnalyticsStyles.barChart}>
<h4 style={{textAlign: 'center', fontSize: '20px'}}>Average levels of Confidence, Satisfaciton, and Productivity</h4>
<CSPBarChart events={this.props.event.events}></CSPBarChart>
<p>Your average confidence, satisfaction, and productivity.</p>
</div>
);
default:
this.setState({activeKey: 1});
return (
<div>
<div style={AnalyticsStyles.pieChart}>
<h4 style={{textAlign: 'center', fontSize: '20px'}}>All Event Emotions</h4>
<FeelingsPieChart events={this.props.event.events}></FeelingsPieChart>
<p>The percentage of time that you have felt each emotion</p>
</div>
</div>
);
}
}
render() {
return(
<div>
<link
href='https://fonts.googleapis.com/css?family=Raleway'
rel='stylesheet'
type='text/css'
/>
<link
href='https://fonts.googleapis.com/css?family=Muli'
rel='stylesheet'
type='text/css'
/>
<link
href='https://fonts.googleapis.com/css?family=Montserrat'
rel='stylesheet'
type='text/css'
/>
<Toolbar
setModalOpen={this.props.actions.setModalOpen}
isAddOpen={this.props.event.isAddOpen}
addEvent={this.props.actions.addEvent}
notificationsOn={this.props.home.notificationsOn}
setNotifications={this.props.actions.setNotifications}
confirmedAddition={this.props.event.confirmedAddition}
setConfirmAddition={this.props.actions.setConfirmAddition}
activeEvent={this.props.event.activeEvent}
setActiveEvent={this.props.actions.setActiveEvent}
setNormalEvents={this.props.actions.setNormalEvents}
location={this.props.location}
analyticsTitle={'Your Emotions'}
secondaryRoute={'/home2'}
analyticsRoute={'/analytics2'}
/>
<h2 style={{textAlign: 'center', fontSize: '30px'}}>Your Emotions</h2>
<br></br>
<p></p><p></p>
<div style={DivStyles.twoColumnSettings}>
<h2>Available Graphs</h2>
<Nav activeKey={this.state.activeKey}>
<NavItem eventKey={1} onClick={this.handleClick.bind(this, 'FeelingsPieChart')}>All Emotions Pie Chart</NavItem>
<NavItem eventKey={2} onClick={this.handleClick.bind(this, 'EnergyPieChart')}>Energy Levels Pie Chart</NavItem>
<NavItem eventKey={3} onClick={this.handleClick.bind(this, 'EmotionBarChart')}>Happy Events Bar Chart</NavItem>
<NavItem eventKey={4} onClick={this.handleClick.bind(this, 'SadBarChart')}>Sad Events Bar Chart</NavItem>
<NavItem eventKey={5} onClick={this.handleClick.bind(this, 'AngryBarChart')}>Angry Events Bar Chart</NavItem>
<NavItem eventKey={6} onClick={this.handleClick.bind(this, 'AnxiousBarChart')}>Anxious Events Bar Chart</NavItem>
<NavItem eventKey={7} onClick={this.handleClick.bind(this, 'DisgustBarChart')}>Disgust Events Bar Chart</NavItem>
<NavItem eventKey={8} onClick={this.handleClick.bind(this, 'EnvyBarChart')}>Envy Events Bar Chart</NavItem>
<NavItem eventKey={9} onClick={this.handleClick.bind(this, 'ExcitedBarChart')}>Excited Events Bar Chart</NavItem>
<NavItem eventKey={10} onClick={this.handleClick.bind(this, 'FearBarChart')}>Fear Events Bar Chart</NavItem>
<NavItem eventKey={11} onClick={this.handleClick.bind(this, 'HopeBarChart')}>Hope Events Bar Chart</NavItem>
<NavItem eventKey={12} onClick={this.handleClick.bind(this, 'JoyBarChart')}>Joy Events Bar Chart</NavItem>
<NavItem eventKey={13} onClick={this.handleClick.bind(this, 'SurpriseBarChart')}>Surprise Events Bar Chart</NavItem>
<NavItem eventKey={14} onClick={this.handleClick.bind(this, 'CSPBarChart')}>Average Confidence, Satisfaction, Productivity Levels</NavItem>
</Nav>
</div>
<div style={DivStyles.twoColumnSettings}>
<div>{this.state.displayedGraph}</div>
</div>
</div>
);
}
}
function mapStateToProps(state) {
return {
home: state.default.home,
event: state.default.event
}
}
function mapDispatchToProps(dispatch) {
return {
actions: bindActionCreators(Actions, dispatch)
}
}
Analytics2.propTypes = {
analyticsTitle: PropTypes.string,
location: PropTypes.object.isRequired,
actions: PropTypes.shape({
setModalOpen: PropTypes.func.isRequired,
addEvent: PropTypes.func.isRequired,
setEventModal: PropTypes.func.isRequired,
setActiveEvent: PropTypes.func.isRequired,
deleteEvent: PropTypes.func.isRequired,
setEditModal: PropTypes.func.isRequired,
setNotifications: PropTypes.func.isRequired,
setConfirmModal: PropTypes.func.isRequired,
saveEdit: PropTypes.func.isRequired,
setConfirmAddition: PropTypes.func.isRequired,
setConfirmEdit: PropTypes.func.isRequired,
setNormalEvents: PropTypes.func.isRequired
}),
home: PropTypes.shape({
notificationsOn: PropTypes.bool
}),
event: PropTypes.shape({
isInfoOpen: PropTypes.bool.isRequired,
isAddOpen: PropTypes.bool.isRequired,
events: PropTypes.array.isRequired,
renderEvents: PropTypes.array.isRequired,
activeEvent: PropTypes.object.isRequired,
isEditOpen: PropTypes.bool.isRequired,
isConfirmOpen: PropTypes.bool.isRequired,
showingNormalEvents: PropTypes.bool.isRequired,
confirmedAddition: PropTypes.bool.isRequired,
confirmedEdit: PropTypes.bool.isRequired
})
}
export default connect(mapStateToProps,mapDispatchToProps)(Analytics2);
|
var photoSphere = document.getElementById('photo-sphere');
var width = photoSphere.offsetWidth;
height = photoSphere.offsetWidth*0.5625;
var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera(75, width / height, 1, 1000);
camera.position.x = 0.1;
var renderer = Detector.webgl ? new THREE.WebGLRenderer() : new THREE.CanvasRenderer();
renderer.setSize(width, height);
var sphere = new THREE.Mesh(
new THREE.SphereGeometry(100, 20, 20),
new THREE.MeshBasicMaterial({
map: THREE.ImageUtils.loadTexture('Photosphere.jpg')
})
);
sphere.scale.x = -1;
scene.add(sphere);
var controls = new THREE.OrbitControls(camera);
controls.noPan = true;
controls.noZoom = true;
controls.autoRotate = false;
controls.autoRotateSpeed = 1;
photoSphere.appendChild(renderer.domElement);
render();
function render() {
controls.update();
requestAnimationFrame(render);
renderer.render(scene, camera);
}
function onMouseWheel(event) {
event.preventDefault();
if (event.wheelDeltaY) { // WebKit
camera.fov -= event.wheelDeltaY * 0.05;
} else if (event.wheelDelta) { // Opera / IE9
camera.fov -= event.wheelDelta * 0.05;
} else if (event.detail) { // Firefox
camera.fov += event.detail * 1.0;
}
camera.fov = Math.max(40, Math.min(100, camera.fov));
camera.updateProjectionMatrix();
}
document.addEventListener('mousewheel', onMouseWheel, false);
document.addEventListener('DOMMouseScroll', onMouseWheel, false); |
import { Component, Input, Output, ElementRef, Renderer, EventEmitter } from '@angular/core';
import { AudioLoader } from '../providers/audio-loader';
import { AudioLoaderConfig } from '../providers/audio-loader-config';
var AudLoader = (function () {
function AudLoader(_element, _renderer, _audioLoader, _config) {
this._element = _element;
this._renderer = _renderer;
this._audioLoader = _audioLoader;
this._config = _config;
/**
* Fallback URL to load when the audio url fails to load or does not exist.
*/
this.fallbackUrl = this._config.fallbackUrl;
/**
* Whether to show a spinner while the audio loads
*/
this.spinner = this._config.spinnerEnabled;
/**
* Whether to show the fallback audio instead of a spinner while the audio loads
*/
this.fallbackAsPlaceholder = this._config.fallbackAsPlaceholder;
this._useImg = this._config.useImg;
/**
* Enable/Disable caching
* @type {boolean}
*/
this.cache = true;
/**
* Width of the audio. This will be ignored if using useImg.
*/
this.width = this._config.width;
/**
* Height of the audio. This will be ignored if using useImg.
*/
this.height = this._config.height;
/**
* Display type of the audio. This will be ignored if using useImg.
*/
this.display = this._config.display;
/**
* Background size. This will be ignored if using useImg.
*/
this.backgroundSize = this._config.backgroundSize;
/**
* Background repeat. This will be ignored if using useImg.
*/
this.backgroundRepeat = this._config.backgroundRepeat;
/**
* Name of the spinner
*/
this.spinnerName = this._config.spinnerName;
/**
* Color of the spinner
*/
this.spinnerColor = this._config.spinnerColor;
/**
* Notify on audio load..
*/
this.load = new EventEmitter();
/**
* Indicates if the audio is still loading
* @type {boolean}
*/
this.isLoading = true;
}
Object.defineProperty(AudLoader.prototype, "src", {
get: function () {
return this._src;
},
/**
* The URL of the audio to load.
*/
set: function (audioUrl) {
this._src = this.processAudioUrl(audioUrl);
this.updateAudio(this._src);
},
enumerable: true,
configurable: true
});
;
Object.defineProperty(AudLoader.prototype, "useImg", {
/**
* Use <img> tag
*/
set: function (val) {
this._useImg = val !== false;
},
enumerable: true,
configurable: true
});
Object.defineProperty(AudLoader.prototype, "noCache", {
/**
* Convenience attribute to disable caching
* @param val
*/
set: function (val) {
this.cache = val !== false;
},
enumerable: true,
configurable: true
});
AudLoader.prototype.ngOnInit = function () {
console.log('initializing audio-loader');
if (this.fallbackAsPlaceholder && this.fallbackUrl) {
this.setAudio(this.fallbackUrl, false);
}
if (!this.src) {
// audio url was not passed
// this can happen when [src] is set to a variable that turned out to be undefined
// one example could be a list of users with their profile pictures
// in this case, it would be useful to use the fallback audio instead
// if fallbackUrl was used as placeholder we do not need to set it again
if (!this.fallbackAsPlaceholder && this.fallbackUrl) {
// we're not going to cache the fallback audio since it should be locally saved
this.setAudio(this.fallbackUrl);
}
else {
this.isLoading = false;
}
}
};
AudLoader.prototype.updateAudio = function (audioUrl) {
var _this = this;
this._audioLoader.getAudioPath(audioUrl)
.then(function (audioUrl) { return _this.setAudio(audioUrl); })
.catch(function (error) { return _this.setAudio(_this.fallbackUrl || audioUrl); });
};
/**
* Gets the audio URL to be loaded and disables caching if necessary
* @returns {string}
*/
AudLoader.prototype.processAudioUrl = function (audioUrl) {
if (this.cache === false) {
// need to disable caching
if (audioUrl.indexOf('?') === -1) {
audioUrl += '?';
}
if (['&', '?'].indexOf(audioUrl.charAt(audioUrl.length)) === -1) {
audioUrl += '&';
}
// append timestamp at the end to make URL unique
audioUrl += 'cache_buster=' + Date.now();
}
console.log('processing audio url: ' + audioUrl);
return audioUrl;
};
/**
* Set the audio to be displayed
* @param audioUrl {string} audio src
* @param stopLoading {boolean} set to true to mark the audio as loaded
*/
AudLoader.prototype.setAudio = function (audioUrl, stopLoading) {
if (stopLoading === void 0) { stopLoading = true; }
this.isLoading = !stopLoading;
console.log('isLoading: ' + this.isLoading);
if (!this.element) {
// create img element if we dont have one
this.element = this._renderer.createElement(this._element.nativeElement, 'audio');
}
// set it's src
this._renderer.setElementAttribute(this.element, 'src', audioUrl);
this._renderer.setElementAttribute(this.element, 'controls', 'true');
if (this.fallbackUrl && !this._audioLoader.nativeAvailable) {
this._renderer.setElementAttribute(this.element, 'onerror', "this.src=\"" + this.fallbackUrl + "\"");
}
console.log('creating audio attribute');
console.log(this._element.nativeElement);
this.load.emit(this);
};
return AudLoader;
}());
export { AudLoader };
AudLoader.decorators = [
{ type: Component, args: [{
selector: 'audio-loader',
template: '<ion-spinner *ngIf="spinner && isLoading && !fallbackAsPlaceholder" [name]="spinnerName" [color]="spinnerColor"></ion-spinner>',
styles: ['ion-spinner { float: none; margin-left: auto; margin-right: auto; display: block; }']
},] },
];
/** @nocollapse */
AudLoader.ctorParameters = function () { return [
{ type: ElementRef, },
{ type: Renderer, },
{ type: AudioLoader, },
{ type: AudioLoaderConfig, },
]; };
AudLoader.propDecorators = {
'src': [{ type: Input },],
'fallbackUrl': [{ type: Input, args: ['fallback',] },],
'spinner': [{ type: Input },],
'fallbackAsPlaceholder': [{ type: Input },],
'useImg': [{ type: Input },],
'noCache': [{ type: Input },],
'cache': [{ type: Input },],
'width': [{ type: Input },],
'height': [{ type: Input },],
'display': [{ type: Input },],
'backgroundSize': [{ type: Input },],
'backgroundRepeat': [{ type: Input },],
'spinnerName': [{ type: Input },],
'spinnerColor': [{ type: Input },],
'load': [{ type: Output },],
};
//# sourceMappingURL=audio-loader.js.map |
import {
getGenericReducerInitialState,
makeGenericReducerHandlers
} from '../utils/reducers'
export const reducers = makeGenericReducerHandlers({
handlers: ['add', 'add many', 'delete', 'set', 'set many'],
name: {
singular: 'multi-site',
plural: 'multi-sites'
}
})
export const initialState = getGenericReducerInitialState()
|
/*******************************************************************************
* @license
* Copyright (c) 2012, 2013 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials are made
* available under the terms of the Eclipse Public License v1.0
* (http://www.eclipse.org/legal/epl-v10.html), and the Eclipse Distribution
* License v1.0 (http://www.eclipse.org/org/documents/edl-v10.html).
*
* Contributors: IBM Corporation - initial API and implementation
******************************************************************************/
/*eslint-env browser, amd*/
define(['orion/webui/littlelib'], function(lib) {
/**
* Attaches tooltip behavior to a given node. The tooltip will be assigned class "tooltip" which can be
* used to control appearance. Uses the "CSS Triangle Trick"
* http://css-tricks.com/snippets/css/css-triangle/
* for the tooltip shape and CSS transitions for fade in and fade out.
*
* Clients should destroy the tooltip if removing the node from the document.
*
* @param {Object} options The options object, which must minimally specify the tooltip dom node
* @param options.node The node showing the tooltip. Required.
* @param options.text The text in the tooltip. Optional. If not specified, the client is expected to add content
* to the tooltip prior to triggering it.
* @param options.trigger The event that triggers the tooltip. Optional. Defaults to "mouseover". Can be one of "mouseover",
* "click", "focus", or "none". If "none" then the creator will be responsible for showing, hiding, and destroying the tooltip.
* If "mouseover" then the aria attributes for tooltips will be set up.
* @param options.position An array specifying the preferred positions to try positioning the tooltip. Positions can be "left", "right",
* "above", or "below". If no position will fit on the screen, the first position specified is used. Optional. Defaults to
* ["right", "above", "below", "left"].
* @param options.showDelay Specifies the number of millisecond delay before the tooltip begins to appear.
* Optional. Valid only for "mouseover" trigger. Defaults to 1000.
* @param options.hideDelay Specifies the number of millisecond delay before the tooltip begins to disappear.
* Optional. Defaults to 200. Valid only for "mouseover" trigger.
* @param options.tailSize Specifies the number of pixels to allocate for the tail. Optional. Defaults to 10.
* @name orion.webui.tooltip.Tooltip
*
*/
function Tooltip(options) {
this._init(options);
}
Tooltip.prototype = /** @lends orion.webui.tooltip.Tooltip.prototype */ {
_init: function(options) {
this._node = lib.node(options.node);
if (!this._node) { throw "no dom node for tooltip found"; } //$NON-NLS-0$
this._position = options.position || ["right", "above", "below", "left"]; //$NON-NLS-3$ //$NON-NLS-2$ //$NON-NLS-1$ //$NON-NLS-0$
this._text = options.text;
this._hideDelay = options.hideDelay === undefined ? 200 : options.hideDelay;
this._tailSize = options.tailSize || 10;
this._trigger = options.trigger || "mouseover"; //$NON-NLS-0$
this._afterShowing = options.afterShowing;
this._afterHiding = options.afterHiding;
var self = this;
// set up events
if (this._trigger === "click") { //$NON-NLS-0$
this._showDelay = 0;
this._node.addEventListener("click", this._clickHandler = function(event) { //$NON-NLS-0$
if (event.target === self._node) {
self.show();
lib.stop(event);
}
}, false);
} else if (this._trigger === "mouseover") { //$NON-NLS-0$
this._showDelay = options.showDelay === undefined ? 500 : options.showDelay;
var leave = ["mouseout", "click"]; //$NON-NLS-1$ //$NON-NLS-0$
this._node.addEventListener("mouseover", this._mouseoverHandler = function(event) { //$NON-NLS-0$
if (lib.contains(self._node, event.target)) {
self.show();
lib.stop(event);
}
}, false);
this._leaveHandler = function(event) { //$NON-NLS-0$
if (lib.contains(self._node, event.target)) {
self.hide();
}
};
for (var i=0; i<leave.length; i++) {
this._node.addEventListener(leave[i], this._leaveHandler, false);
}
} else if (this._trigger === "focus") { //$NON-NLS-0$
this._showDelay = options.showDelay === undefined ? 0 : options.showDelay;
this._hideDelay = options.hideDelay === undefined ? 0 : options.hideDelay;
this._node.addEventListener("focus", this._focusHandler = function(event) { //$NON-NLS-0$
if (lib.contains(self._node, event.target)) {
self.show();
}
}, false);
this._blurHandler = function(event) { //$NON-NLS-0$
if (lib.contains(self._node, event.target)) {
self.hide();
}
};
this._node.addEventListener("blur", this._blurHandler, false); //$NON-NLS-0$
}
},
_makeTipNode: function() {
if (!this._tip) {
this._tip = document.createElement("span"); //$NON-NLS-0$
this._tip.classList.add("tooltipContainer"); //$NON-NLS-0$
this._tipInner = document.createElement("div"); //$NON-NLS-0$
this._tipInner.classList.add("tooltip"); //$NON-NLS-0$
if (this._text) {
this._tipTextContent = document.createElement("div"); //$NON-NLS-0$
this._tipTextContent.classList.add("textContent"); //$NON-NLS-0$
this._tipInner.appendChild(this._tipTextContent);
var textNode = document.createTextNode(this._text);
this._tipTextContent.appendChild(textNode);
}
this._tip.appendChild(this._tipInner);
document.body.appendChild(this._tip);
var self = this;
lib.addAutoDismiss([this._tip, this._node], function() {self.hide();});
if (this._trigger === "mouseover") { //$NON-NLS-0$
this._tipInner.role = "tooltip"; //$NON-NLS-0$
this._tipInner.id = "tooltip" + new Date().getTime().toString(); //$NON-NLS-0$
this._node.setAttribute("aria-describedby", this._tipInner.id); //$NON-NLS-0$
// see https://bugs.eclipse.org/bugs/show_bug.cgi?id=398960
// mousing over the tip itself will cancel any pending timeout to close it, but then we must
// also close it when we leave the tip.
this._tip.addEventListener("mouseover", function(event) { //$NON-NLS-0$
if (self._timeout) {
window.clearTimeout(self._timeout);
self._timeout = null;
}
self._tip.addEventListener("mouseout", function(event) { //$NON-NLS-0$
if (lib.contains(self._tip, event.target)) {
self.hide();
lib.stop(event);
}
}, false);
}, false);
}
}
return this._tip;
},
_positionTip: function(position, force) {
this._makeTipNode(); // lazy initialize
// special case for left tooltip to ensure inner span is adjacent to tail.
if (position === "left") { //$NON-NLS-0$
this._tipInner.classList.add("left"); //$NON-NLS-0$
} else {
this._tipInner.classList.remove("left"); //$NON-NLS-0$
}
// Sometimes _node is not visible (eg. if _node is a dropdown menu item in a closed menu), so find
// the nearest ancestor with a reasonable bound
var posNode = this._node;
var rect;
for (rect = lib.bounds(posNode); posNode && !rect.width && !rect.height; posNode = posNode.parentNode) {
rect = lib.bounds(posNode);
}
var tipRect = lib.bounds(this._tipInner);
var top, left;
switch (position) {
case "above": //$NON-NLS-0$
top = rect.top - tipRect.height - this._tailSize - 1;
left = rect.left - this._tailSize;
break;
case "below": //$NON-NLS-0$
top = rect.top + rect.height + this._tailSize + 1;
left = rect.left - this._tailSize;
break;
case "left": //$NON-NLS-0$
top = rect.top - this._tailSize / 2;
left = rect.left - tipRect.width - this._tailSize - 1;
break;
default: // right
top = rect.top - this._tailSize / 2;
left = rect.left + rect.width + this._tailSize + 1;
break;
}
var totalRect = lib.bounds(document.documentElement);
if (top + tipRect.height > totalRect.height) {
if (force) {
top = totalRect.height - tipRect.height - 1;
} else {
return false;
}
}
if (left + tipRect.width > totalRect.width) {
if (force) {
left = totalRect.width - tipRect.width - 1;
} else {
return false;
}
}
if (left < 0) {
if (force) {
left = 4;
} else {
return false;
}
}
if (top < 0) {
if (force) {
top = 4;
} else {
return false;
}
}
if (this._tail && (this._tail.previousPosition !== position)) {
//position has changed, tail needs to be modified
this._tip.removeChild(this._tail);
this._tail = null;
}
if (!this._tail) {
this._tail = document.createElement("span"); //$NON-NLS-0$
this._tail.classList.add("tooltipTailFrom"+position); //$NON-NLS-0$
if (position === "above" || position === "left") { //$NON-NLS-1$//$NON-NLS-0$
// tip goes after content
this._tip.appendChild(this._tail);
} else {
this._tip.insertBefore(this._tail, this._tipInner);
}
this._tail.previousPosition = position;
}
this._tip.style.top = top + "px"; //$NON-NLS-0$
this._tip.style.left = left + "px"; //$NON-NLS-0$
return true;
},
contentContainer: function() {
this._makeTipNode();
return this._tipInner;
},
/**
* @return True if this tooltip is visible, false otherwise
*/
isShowing: function() {
return this._tip && this._tip.classList.contains("tooltipShowing"); //$NON-NLS-0$
},
/**
* Show the tooltip.
*/
show: function() {
if (this.isShowing()) { //$NON-NLS-0$
return;
}
if (this._timeout) {
window.clearTimeout(this._timeout);
this._timeout = null;
}
if (this._showDelay) {
this._timeout = window.setTimeout(this._showImmediately.bind(this), this._showDelay);
} else {
this._showImmediately();
}
},
_showImmediately: function() {
var positioned = false;
var index = 0;
while (!positioned && index < this._position.length) {
positioned = this._positionTip(this._position[index]);
index++;
}
if (!positioned) {
this._positionTip(this._position[0], true); // force it in, it doesn't fit anywhere
}
this._tip.classList.add("tooltipShowing"); //$NON-NLS-0$
if (this._afterShowing) {
this._afterShowing();
}
},
/**
* Hide the tooltip.
*/
hide: function(hideDelay) {
if (this._timeout) {
window.clearTimeout(this._timeout);
this._timeout = null;
}
if (!this.isShowing()) { //$NON-NLS-0$
return;
}
if (hideDelay === undefined) {
hideDelay = this._hideDelay;
}
var self = this;
this._timeout = window.setTimeout(function() {
self._tip.classList.remove("tooltipShowing"); //$NON-NLS-0$
self._tip.removeAttribute("style"); //$NON-NLS-0$
if (self._afterHiding) {
self._afterHiding();
}
}, hideDelay);
},
destroy: function() {
if (this._timeout) {
window.clearTimeout(this._timeout);
this._timeout = null;
}
if (this._tip) {
document.body.removeChild(this._tip);
this._tip = null;
this._tipInner = null;
this._tipTextContent = null;
this._tail = null;
}
if (this._node) {
this._node.removeEventListener("click", this._clickHandler, false); //$NON-NLS-0$
this._node.removeEventListener("mouseover", this._mouseoverHandler, false); //$NON-NLS-0$
this._node.removeEventListener("focus", this._focusHandler, false); //$NON-NLS-0$
this._node.removeEventListener("blur", this._blurHandler, false); //$NON-NLS-0$
var leave = ["mouseout", "click"]; //$NON-NLS-1$ //$NON-NLS-0$
for (var i=0; i<leave.length; i++) {
this._node.removeEventListener(leave[i], this._leaveHandler, false);
}
}
}
};
Tooltip.prototype.constructor = Tooltip;
//return the module exports
return {Tooltip: Tooltip};
}); |
'use strict';
// FUNCTIONS //
var floor = Math.floor,
ln = Math.log;
// GENERATE GEOMETRIC RANDOM VARIATES //
/**
* FUNCTION random( p[, rand] )
* Generates a random draw from a geometric distribution with success probability `p`.
*
* @param {Number} p - success probability
* @param {Function} [rand=Math.random] - random number generator
* @returns {Number} random draw from the specified distribution
*/
function random( p, rand ) {
var u;
u = rand ? rand() : Math.random();
return floor( ln( u ) / ln( 1 - p) );
}
module.exports = random;
|
angular.module('MapDrawer').directive('mapDrawer', ['$interval', 'PlayerServive', function ($interval, PlayerServive) {
'use strict';
var elementSize;
var playerWasDrawn = false;
var GRID_MIN_SIZE = 400;
var CELL_SIZE = 60;
function getVisibleBoundaries(playerPosition) {
var playerVisibilityDistance = 2;
var visibleBoundaries = {
minX: playerPosition.x - 2,
minY: playerPosition.y - 2,
maxX: playerPosition.x + 2,
maxY: playerPosition.y + 2
};
return visibleBoundaries;
}
function buildData(data, cellSize) {
return data.map(function (arr, columnIndex) {
return arr.map(function (value, rowIndex) {
var valueStr;
if (value.block === undefined) {
valueStr = 'empty';
} else if (value.block === null) {
valueStr = 'no-match';
} else {
valueStr = value.block;
}
return {
mapX: value.x,
mapY: value.y,
x: rowIndex * cellSize,
y: columnIndex * cellSize,
value: valueStr
};
});
});
}
function lazyFn(d) {
return d;
}
function getUniqueId(val) {
return [val.value, val.x, val.y].join('_');
}
function drawMap(mapLayer, map, cellSize) {
var rows = mapLayer.selectAll('.row').data(map);
rows.enter()
.append('svg:g')
.attr('class', 'row');
var cells = rows.selectAll('.cell').data(lazyFn);
cells.enter()
.append('svg:image')
.attr('class', 'cell')
.attr('width', cellSize)
.attr('height', cellSize);
cells.exit().remove();
cells.attr('x', function (d) {
return d.x;
}).attr('y', function (d) {
return d.y;
}).attr('xlink:href', function (d) {
return 'img/tiles/{value}.png'.replace('{value}', d.value);
});
}
function updateMapVisibility(mapLayer, visibleBoundaries) {
var cells = mapLayer.selectAll('.cell');
cells.attr('opacity', function (d) {
var isVisible = d.mapX > visibleBoundaries.minX && d.mapX < visibleBoundaries.maxX && d.mapY > visibleBoundaries.minY && d.mapY < visibleBoundaries.maxY;
return isVisible ? 1 : 0.6;
});
}
function getNumberOfGridColumns(matrix) {
return matrix[0].length;
}
function calculateAvailableGridSpace(element) {
var parentElement = element.parent();
var parentWidth = parentElement.prop('offsetWidth');
var parentHeight = parentElement.prop('offsetHeight');
var elementSize = Math.min(parentWidth, parentHeight);
return elementSize;
}
function updateMainSvg(element, mainSvg, map, cellSize) {
var gridAvailableSpace = calculateAvailableGridSpace(element);
var gridWidth = getNumberOfGridColumns(map) * cellSize;
var gridHeight = map.length * cellSize;
var gridSize = Math.min(gridAvailableSpace, Math.max(gridWidth, gridHeight));
var viewBoxAttribute;
// borders
//gridWidth += 2;
//gridHeight += 2;
viewBoxAttribute = [0, 0, gridWidth, gridHeight].join(' ');
mainSvg
.attr('width', gridSize)
.attr('height', gridSize)
.attr('viewBox', viewBoxAttribute);
}
function mapWatch(element, mainSvg, mapLayer, playerLayer, newMap) {
var mapData;
var gridSize;
var playerCurrentPosition;
var visibleBoundaries;
if (angular.isObject(newMap)) {
updateMainSvg(element, mainSvg, newMap, CELL_SIZE);
mapData = buildData(newMap, CELL_SIZE);
drawMap(mapLayer, mapData, CELL_SIZE);
playerCurrentPosition = PlayerServive.getCurrentPosition();
visibleBoundaries = getVisibleBoundaries(playerCurrentPosition);
updateMapVisibility(mapLayer, visibleBoundaries);
/***** Player ******/
PlayerServive.setCurrentMap(newMap);
PlayerServive.setCurrentCellSize(CELL_SIZE);
if (!playerWasDrawn) {
PlayerServive.draw(playerLayer);
PlayerServive.enablePlayerControls();
playerWasDrawn = true;
}
PlayerServive.move(CELL_SIZE);
/*******************/
}
}
return {
restrict: 'A',
scope: {
map: '='
},
link: function (scope, element) {
var elementNode = element[0];
var mainSvg = d3.select(elementNode).append('svg');
var mapLayer = mainSvg.append('svg:g');
var playerLayer = mainSvg.append('svg:g');
scope.$watch('map', function (newMap) {
mapWatch(element, mainSvg, mapLayer, playerLayer, newMap);
}, true);
scope.$on('MapPlayerDrawer.move', function onPlayerMove() {
var playerCurrentPosition = PlayerServive.getCurrentPosition();
var visibleBoundaries = getVisibleBoundaries(playerCurrentPosition);
updateMapVisibility(mapLayer, visibleBoundaries);
});
}
};
}]);
|
module.exports = function (server, mountpoint, Message, acl) {
var Handler = new (require('../../server/simpleCRUD'))({model: Message});
// List all messages, no authentication needed
server.route({
method: 'GET',
path: mountpoint + '/messages',
config: {
handler: Handler.list
}
});
server.route({
method: 'POST',
path: mountpoint + '/messages',
config: {
handler: acl.hapiAllowed('messages', 'create', Handler.create),
auth: 'auth0'
}
});
server.route({
method: 'GET',
path: mountpoint + '/messages/{_id}',
config: {
handler: Handler.read
}
});
server.route({
method: 'PUT',
path: mountpoint + '/messages',
config: {
handler: acl.hapiAllowed('messages', 'update', Handler.update),
auth: 'auth0'
}
});
server.route({
method: 'DELETE',
path: mountpoint + '/messages/{_id}',
config: {
handler: acl.hapiAllowed('messages', 'delete', Handler.delete), // jshint ignore:line
auth: 'auth0'
}
});
};
|
import React, { Component, PropTypes } from 'react';
import { getCallbacks } from '../helper/helper';
import styles from '../../build/styles';
export default class Td extends Component {
static propTypes = {
children: PropTypes.any,
className: PropTypes.string,
isIcon: PropTypes.bool,
style: PropTypes.object,
};
static defaultProps = {
className: '',
};
createClassName() {
return [
styles.td,
this.props.isIcon ? styles.isIcon : '',
this.props.className,
].join(' ').trim();
}
render() {
return (
<td
{...getCallbacks(this.props)}
className={this.createClassName()}
style={this.props.style}
>
{this.props.children}
</td>
);
}
}
|
var staticHandler = require('../index.js');
var assert = require('assert');
var vows = require('vows');
staticHandler.globalSettings({
active : true,
inmemory : true,
pathJs : __dirname + '/data/jss',
pathCss : __dirname + '/data/cs',
locationCss : '/styles',
locationJs : '/javascript',
maxAgeCss : 3600,
maxAgeJs : 3600
});
var jsManager = staticHandler.getJsManager();
var cssManager = staticHandler.getCssManager();
vows.describe('Test suite for none-exist path').addBatch({
'When provide a none-exist path the js manager should throw an error' : function() {
assert.throws(function() {
jsManager.checkPath();
}, function(err) {
if(( err instanceof Error) && /Path does not exist/.test(err)) {
return true;
}
}, "Expected an error due to path doesn't exist");
},
'When provide a none-exist path the css manager should throw an error' : function() {
assert.throws(function() {
cssManager.checkPath();
}, function(err) {
if(( err instanceof Error) && /Path does not exist/.test(err)) {
return true;
}
}, "Expected an error due to path doesn't exist");
}
}).export(module);
|
/*
* Copyright 2016 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
'use strict';
(function() {
var Marzipano = window.Marzipano;
var bowser = window.bowser;
var screenfull = window.screenfull;
var data = window.data;
// Grab elements from DOM.
var panoElement = document.querySelector('#pano');
var sceneNameElement = document.querySelector('#titleBar .sceneName');
var sceneListElement = document.querySelector('#sceneList');
var sceneElements = document.querySelectorAll('#sceneList .scene');
var sceneListToggleElement = document.querySelector('#sceneListToggle');
var autorotateToggleElement = document.querySelector('#autorotateToggle');
var fullscreenToggleElement = document.querySelector('#fullscreenToggle');
// Detect desktop or mobile mode.
if (window.matchMedia) {
var setMode = function() {
if (mql.matches) {
document.body.classList.remove('desktop');
document.body.classList.add('mobile');
} else {
document.body.classList.remove('mobile');
document.body.classList.add('desktop');
}
};
var mql = matchMedia("(max-width: 500px), (max-height: 500px)");
setMode();
mql.addListener(setMode);
} else {
document.body.classList.add('desktop');
}
// Detect whether we are on a touch device.
document.body.classList.add('no-touch');
window.addEventListener('touchstart', function() {
document.body.classList.remove('no-touch');
document.body.classList.add('touch');
});
// Use tooltip fallback mode on IE < 11.
if (bowser.msie && parseFloat(bowser.version) < 11) {
document.body.classList.add('tooltip-fallback');
}
// Viewer options.
var viewerOpts = {
controls: {
mouseViewMode: data.settings.mouseViewMode
}
};
// Initialize viewer.
var viewer = new Marzipano.Viewer(panoElement, viewerOpts);
// Create scenes.
var scenes = data.scenes.map(function(sceneData) {
var urlPrefix = "../sample-tour/media";
var source = Marzipano.ImageUrlSource.fromString(
urlPrefix + "/" + sceneData.id + "/{z}/{f}/{y}/{x}.jpg",
{ cubeMapPreviewUrl: urlPrefix + "/" + sceneData.id + "/preview.jpg" });
var geometry = new Marzipano.CubeGeometry(sceneData.levels);
var limiter = Marzipano.RectilinearView.limit.traditional(sceneData.faceSize, 100*Math.PI/180, 120*Math.PI/180);
var view = new Marzipano.RectilinearView(sceneData.initialViewParameters, limiter);
var marzipanoScene = viewer.createScene({
source: source,
geometry: geometry,
view: view,
pinFirstLevel: true
});
// Create link hotspots.
sceneData.linkHotspots.forEach(function(hotspot) {
var element = createLinkHotspotElement(hotspot);
marzipanoScene.hotspotContainer().createHotspot(element, { yaw: hotspot.yaw, pitch: hotspot.pitch });
});
// Create info hotspots.
sceneData.infoHotspots.forEach(function(hotspot) {
var element = createInfoHotspotElement(hotspot);
marzipanoScene.hotspotContainer().createHotspot(element, { yaw: hotspot.yaw, pitch: hotspot.pitch });
});
return {
data: sceneData,
marzipanoObject: marzipanoScene
};
});
// Display the initial scene.
switchScene(scenes[0]);
// Set up autorotate, if enabled.
var autorotate = Marzipano.autorotate({ yawSpeed: 0.1, targetPitch: 0, targetFov: Math.PI/2 });
if (data.settings.autorotateEnabled) {
autorotateToggleElement.classList.add('enabled');
}
autorotateToggleElement.addEventListener('click', toggleAutorotate);
// Set up fullscreen mode, if supported.
if (screenfull.enabled && data.settings.fullscreenButton) {
document.body.classList.add('fullscreen-enabled');
fullscreenToggleElement.addEventListener('click', toggleFullscreen);
} else {
document.body.classList.add('fullscreen-disabled');
}
// Set handler for scene list toggle.
sceneListToggleElement.addEventListener('click', toggleSceneList);
// Start with the scene list open on desktop.
if (!document.body.classList.contains('mobile')) {
showSceneList();
}
// Set handler for scene switch.
scenes.forEach(function(scene) {
var el = document.querySelector('#sceneList .scene[data-id="' + scene.data.id + '"]');
el.addEventListener('click', function() {
switchScene(scene);
// On mobile, hide scene list after selecting a scene.
if (document.body.classList.contains('mobile')) {
hideSceneList();
}
});
});
// DOM elements for view controls.
var viewUpElement = document.querySelector('#viewUp');
var viewDownElement = document.querySelector('#viewDown');
var viewLeftElement = document.querySelector('#viewLeft');
var viewRightElement = document.querySelector('#viewRight');
var viewInElement = document.querySelector('#viewIn');
var viewOutElement = document.querySelector('#viewOut');
// Dynamic parameters for controls.
var velocity = 0.7;
var friction = 3;
// Associate view controls with elements.
var controls = viewer.controls();
controls.registerMethod('upElement', new Marzipano.ElementPressControlMethod(viewUpElement, 'y', velocity, friction), true);
controls.registerMethod('downElement', new Marzipano.ElementPressControlMethod(viewDownElement, 'y', -velocity, friction), true);
controls.registerMethod('leftElement', new Marzipano.ElementPressControlMethod(viewLeftElement, 'x', -velocity, friction), true);
controls.registerMethod('rightElement', new Marzipano.ElementPressControlMethod(viewRightElement, 'x', velocity, friction), true);
controls.registerMethod('inElement', new Marzipano.ElementPressControlMethod(viewInElement, 'zoom', -velocity, friction), true);
controls.registerMethod('outElement', new Marzipano.ElementPressControlMethod(viewOutElement, 'zoom', velocity, friction), true);
function sanitize(s) {
return s.replace('&', '&').replace('<', '<').replace('>', '>');
}
function switchScene(scene) {
stopAutorotate();
scene.marzipanoObject.switchTo();
startAutorotate();
updateSceneName(scene);
updateSceneList(scene);
}
function updateSceneName(scene) {
sceneNameElement.innerHTML = sanitize(scene.data.name);
}
function updateSceneList(scene) {
for (var i = 0; i < sceneElements.length; i++) {
var el = sceneElements[i];
if (el.getAttribute('data-id') === scene.data.id) {
el.classList.add('current');
} else {
el.classList.remove('current');
}
}
}
function showSceneList() {
sceneListElement.classList.add('enabled');
sceneListToggleElement.classList.add('enabled');
}
function hideSceneList() {
sceneListElement.classList.remove('enabled');
sceneListToggleElement.classList.remove('enabled');
}
function toggleSceneList() {
sceneListElement.classList.toggle('enabled');
sceneListToggleElement.classList.toggle('enabled');
}
function startAutorotate() {
if (!autorotateToggleElement.classList.contains('enabled')) {
return;
}
viewer.startMovement(autorotate);
viewer.setIdleMovement(3000, autorotate);
}
function stopAutorotate() {
viewer.stopMovement();
viewer.setIdleMovement(Infinity);
}
function toggleAutorotate() {
if (autorotateToggleElement.classList.contains('enabled')) {
autorotateToggleElement.classList.remove('enabled');
stopAutorotate();
} else {
autorotateToggleElement.classList.add('enabled');
startAutorotate();
}
}
function toggleFullscreen() {
screenfull.toggle();
if (screenfull.isFullscreen) {
fullscreenToggleElement.classList.add('enabled');
} else {
fullscreenToggleElement.classList.remove('enabled');
}
}
function createLinkHotspotElement(hotspot) {
// Create wrapper element to hold icon and tooltip.
var wrapper = document.createElement('div');
wrapper.classList.add('hotspot');
wrapper.classList.add('link-hotspot');
// Create image element.
var icon = document.createElement('img');
icon.src = 'img/link.png';
icon.classList.add('link-hotspot-icon');
// Set rotation transform.
var transformProperties = [ '-ms-transform', '-webkit-transform', 'transform' ];
for (var i = 0; i < transformProperties.length; i++) {
var property = transformProperties[i];
icon.style[property] = 'rotate(' + hotspot.rotation + 'rad)';
}
// Add click event handler.
wrapper.addEventListener('click', function() {
switchScene(findSceneById(hotspot.target));
});
// Prevent touch and scroll events from reaching the parent element.
// This prevents the view control logic from interfering with the hotspot.
stopTouchAndScrollEventPropagation(wrapper);
// Create tooltip element.
var tooltip = document.createElement('div');
tooltip.classList.add('hotspot-tooltip');
tooltip.classList.add('link-hotspot-tooltip');
tooltip.innerHTML = findSceneDataById(hotspot.target).name;
wrapper.appendChild(icon);
wrapper.appendChild(tooltip);
return wrapper;
}
function createInfoHotspotElement(hotspot) {
// Create wrapper element to hold icon and tooltip.
var wrapper = document.createElement('div');
wrapper.classList.add('hotspot');
wrapper.classList.add('info-hotspot');
// Create hotspot/tooltip header.
var header = document.createElement('div');
header.classList.add('info-hotspot-header');
// Create image element.
var iconWrapper = document.createElement('div');
iconWrapper.classList.add('info-hotspot-icon-wrapper');
var icon = document.createElement('img');
icon.src = 'img/info.png';
icon.classList.add('info-hotspot-icon');
iconWrapper.appendChild(icon);
// Create title element.
var titleWrapper = document.createElement('div');
titleWrapper.classList.add('info-hotspot-title-wrapper');
var title = document.createElement('div');
title.classList.add('info-hotspot-title');
title.innerHTML = hotspot.title;
titleWrapper.appendChild(title);
// Create close element.
var closeWrapper = document.createElement('div');
closeWrapper.classList.add('info-hotspot-close-wrapper');
var closeIcon = document.createElement('img');
closeIcon.src = 'img/close.png';
closeIcon.classList.add('info-hotspot-close-icon');
closeWrapper.appendChild(closeIcon);
// Construct header element.
header.appendChild(iconWrapper);
header.appendChild(titleWrapper);
header.appendChild(closeWrapper);
// Create text element.
var text = document.createElement('div');
text.classList.add('info-hotspot-text');
text.innerHTML = hotspot.text;
// Place header and text into wrapper element.
wrapper.appendChild(header);
wrapper.appendChild(text);
// Create a modal for the hotspot content to appear on mobile mode.
var modal = document.createElement('div');
modal.innerHTML = wrapper.innerHTML;
modal.classList.add('info-hotspot-modal');
document.body.appendChild(modal);
var toggle = function() {
wrapper.classList.toggle('visible');
modal.classList.toggle('visible');
};
// Show content when hotspot is clicked.
wrapper.querySelector('.info-hotspot-header').addEventListener('click', toggle);
// Hide content when close icon is clicked.
modal.querySelector('.info-hotspot-close-wrapper').addEventListener('click', toggle);
// Prevent touch and scroll events from reaching the parent element.
// This prevents the view control logic from interfering with the hotspot.
stopTouchAndScrollEventPropagation(wrapper);
return wrapper;
}
// Prevent touch and scroll events from reaching the parent element.
function stopTouchAndScrollEventPropagation(element, eventList) {
var eventList = [ 'touchstart', 'touchmove', 'touchend', 'touchcancel',
'wheel', 'mousewheel' ];
for (var i = 0; i < eventList.length; i++) {
element.addEventListener(eventList[i], function(event) {
event.stopPropagation();
});
}
}
function findSceneById(id) {
for (var i = 0; i < scenes.length; i++) {
if (scenes[i].data.id === id) {
return scenes[i];
}
}
return null;
}
function findSceneDataById(id) {
for (var i = 0; i < data.scenes.length; i++) {
if (data.scenes[i].id === id) {
return data.scenes[i];
}
}
return null;
}
})();
|
$( document ).ready(function() {
$('[data-includefile]').each(function(){
var file = $(this).attr("data-includefile");
$(this).load("/includes/"+$(this).attr("data-includefile")+".html", unWrapPlaceholder)
});
//write to local storage
$('form').storeForm();
//play back from local storage
$('.playback-container').getForm();
//clear storage
$('.clearStorage').click(function(){
localStorage.clear();
});
//uncheck inputs
$('input[type=checkbox]').removeAttr('checked');
$('input[type=radio]').removeAttr('checked');
(function($){
$(function(){
$('#country-selector').val('');
$("#countries").submit(function( event ) {
var selectValue = $('#country-selector').val();
if (_.includes(['Hong Kong', 'Japan', 'Malaysia', 'Singapore',
'Korea, Republic of', 'Taiwan', 'Brunei Darussalam', 'Israel', 'Canada', 'United States', 'Argentina',
'Belize', 'Brazil', 'Chile', 'El Salvador', 'Guatemala', 'Honduras', 'Mexico',
'Nicaragua', 'Panama', 'Paraguay', 'Uruguay', 'Australia', 'New Zealand'], selectValue)){
window.location.href = 'why-are-you-coming.html';
event.preventDefault();
} else if (_.includes([''], selectValue)){
$(".countryHint").show();
event.preventDefault();
} else {
window.location.href = 'ineligible.html';
event.preventDefault();
}
});
$('select').selectToAutocomplete();
});
})(jQuery);
});
|
class OperationButton {
constructor(selector, parent=document) {
this.btn = asElements(selector, parent);
}
start() {
if (this.btn && this.btn.length) {
for (let i = 0; i < this.btn.length; ++i) {
let btn = this.btn[i];
btn.setAttribute('disabled', 'disabled');
btn.classList.add('pending_operation');
}
}
}
stop() {
if (this.btn && this.btn.length) {
for (let i = 0; i < this.btn.length; ++i) {
let btn = this.btn[i];
btn.removeAttribute('disabled');
btn.classList.remove('pending_operation');
}
}
}
}
class FileUploader {
constructor(cont) {
this.fileId = 0;
this.filesCont = cont;
$(this.filesCont).on('click', '.attachment-delete', function (e) {
let id = this.parentNode.dataset['id'];
$(this.parentNode).remove();
});
}
loadend(reader, file) {
let hdl = ++this.fileId;
let tpl = Template.render('file_entry_tpl', {
name: file.name,
id: hdl
});
let entry = document.getElementById('file_entry');
entry.setAttribute('name', 'files');
entry.onchange = null;
let entryParent = entry.parentNode;
entry.removeAttribute('id');
tpl.querySelector('.attachment').appendChild(entry);
let newEntry = document.createElement('input');
newEntry.setAttribute('id', 'file_entry');
newEntry.setAttribute('hidden', 'hidden');
newEntry.setAttribute('type', 'file');
let uploader = this;
$(newEntry).on('change', function () {
uploader.readFiles(this.files);
});
entryParent.appendChild(newEntry);
this.filesCont.appendChild(tpl);
return hdl;
}
removeFile(hdl) {
this.files.erase(hdl);
}
readFiles(files) {
for (let i = 0; i < files.length; ++i) {
let file = files[i];
let reader = new FileReader();
if (file) {
reader.onloadend = this.loadend.bind(this, reader, file);
reader.readAsDataURL(file);
}
}
}
}
|
import React from "react";
import { graphql } from "gatsby";
import Layout from "../components/Layout";
import Seo from "../components/Seo";
const NotFoundPage = ({ data }) => {
const siteTitle = data.site.siteMetadata.title;
return (
<Layout title={siteTitle}>
<Seo title="404: Not Found" />
<h1>404: Not Found</h1>
</Layout>
);
};
export default NotFoundPage;
export const pageQuery = graphql`
query {
site {
siteMetadata {
title
}
}
}
`;
|
import moduleForAcceptance from '../../tests/helpers/module-for-acceptance';
import { test } from 'qunit';
moduleForAcceptance('Acceptance | keyboard interaction');
test('up arrow selects the previous visible tree item', function(assert) {
visit('/');
triggerEvent('[role="treeitem"]:contains("Fruits")', 'dblclick');
click('[role="treeitem"]:contains("Vegetables")');
keyEvent('[role="tree"]', 'keydown', 38);
andThen(function() {
assert.ok(findWithAssert('[role="treeitem"]:contains("Pears")').is('[aria-selected="true"]'));
});
keyEvent('[role="tree"]', 'keydown', 38);
andThen(function() {
assert.ok(findWithAssert('[role="treeitem"]:contains("Bananas")').is('[aria-selected="true"]'));
});
});
test('down arrow selects the next visible tree item', function(assert) {
visit('/');
keyEvent('[role="tree"]', 'keydown', 40);
andThen(function() {
assert.ok(findWithAssert('[role="treeitem"]:contains("Fruits")').is('[aria-selected="true"]'));
});
triggerEvent('[role="treeitem"]:contains("Vegetables")', 'dblclick');
click('[role="treeitem"]:contains("Fruits")');
keyEvent('[role="tree"]', 'keydown', 40);
andThen(function() {
assert.ok(findWithAssert('[role="treeitem"]:contains("Vegetables")').is('[aria-selected="true"]'));
});
keyEvent('[role="tree"]', 'keydown', 40);
andThen(function() {
assert.ok(findWithAssert('[role="treeitem"]:contains("Broccoli")').is('[aria-selected="true"]'));
});
});
test('left arrow moves to the previous parent node when the currently selected parent node is collapsed', function(assert) {
visit('/');
triggerEvent('[role="treeitem"]:contains("Vegetables")', 'dblclick');
click('[role="treeitem"]:contains("Lettuce")');
keyEvent('[role="tree"]', 'keydown', 37);
andThen(function() {
assert.ok(findWithAssert('[role="treeitem"]:contains("Vegetables")').is('[aria-selected="true"]'));
});
});
test('left arrow collapses the currently selected parent node if it is expanded', function(assert) {
visit('/');
click('[role="treeitem"]:contains("Fruits")');
triggerEvent('[role="treeitem"]:contains("Fruits")', 'dblclick');
keyEvent('[role="tree"]', 'keydown', 37);
andThen(function() {
assert.ok(findWithAssert('[role="treeitem"]:contains("Fruits")').is('[aria-expanded="false"]'));
});
});
test('right arrow expands the currently selected parent node and moves to its first child node', function(assert) {
visit('/');
click('[role="treeitem"]:contains("Fruits")');
keyEvent('[role="tree"]', 'keydown', 39);
andThen(function() {
assert.ok(findWithAssert('[role="treeitem"]:contains("Fruits")').is('[aria-expanded="true"]'));
assert.ok(findWithAssert('[role="treeitem"]:contains("Oranges")').is('[aria-selected="true"]'));
});
});
test('enter toggles the expanded or collapsed state of the selected parent node', function(assert) {
visit('/');
click('[role="treeitem"]:contains("Fruits")');
keyEvent('[role="tree"]', 'keydown', 13);
andThen(function() {
assert.ok(findWithAssert('[role="treeitem"]:contains("Fruits")').is('[aria-expanded="true"]'));
});
keyEvent('[role="tree"]', 'keydown', 13);
andThen(function() {
assert.ok(findWithAssert('[role="treeitem"]:contains("Fruits")').is('[aria-expanded="false"]'));
});
});
test('home selects the root parent node of the tree', function(assert) {
visit('/');
click('[role="treeitem"]:contains("Vegetables")');
keyEvent('[role="tree"]', 'keydown', 36);
andThen(function() {
assert.ok(findWithAssert('[role="treeitem"]:contains("Fruits")').is('[aria-selected="true"]'));
});
});
test('end selects the last visible node of the tree', function(assert) {
visit('/');
click('[role="treeitem"]:contains("Fruits")');
keyEvent('[role="tree"]', 'keydown', 35);
andThen(function() {
assert.ok(findWithAssert('[role="treeitem"]:contains("Vegetables")').is('[aria-selected="true"]'));
});
triggerEvent('[role="treeitem"]:contains("Vegetables")', 'dblclick');
keyEvent('[role="tree"]', 'keydown', 35);
andThen(function() {
assert.ok(findWithAssert('[role="treeitem"]:contains("Squash")').is('[aria-selected="true"]'));
});
});
test('asterisk expands all parent nodes', function(assert) {
visit('/');
triggerEvent('[role="tree"]', 'keydown', { keyCode: 56, shiftKey: true });
andThen(function() {
assert.equal(find('[role="treeitem"][aria-expanded="true"]').length, 6);
});
});
|
const assert = require('assert')
module.exports = {
listSheets,
getSheet,
createSheet,
renameSheet,
deleteSheet,
getColumns,
createColumn,
updateColumn,
deleteColumn,
getRows,
createRow,
updateRow,
deleteRow
}
function listSheets (db) {
return db
.select('tablename AS name')
.from('pg_tables')
.where('schemaname', 'public')
}
function getSheet (db, sheetName) {
return listSheets(db)
.where('tablename', sheetName)
.then((rows) => {
assert(rows.length > 0)
return rows[0]
})
}
function createSheet (db, { name }) {
return db.schema.createTable(name, (table) => {
table.increments('id')
})
}
function renameSheet (db, oldName, newName) {
return db.schema.renameTable(oldName, newName)
}
function deleteSheet (db, name) {
return db.schema.dropTable(name)
}
function getColumns (db, sheetName) {
return db.raw(`
SELECT
cols.column_name AS name,
cols.data_type AS db_type,
cols.character_maximum_length AS length,
cols.column_default AS default,
cols.is_nullable::boolean AS null,
constr.constraint_type AS constraint,
pg_catalog.col_description(cls.oid, cols.ordinal_position::int)::jsonb AS custom
FROM
pg_catalog.pg_class AS cls,
information_schema.columns AS cols
LEFT JOIN
information_schema.key_column_usage AS keys
ON keys.column_name = cols.column_name
AND keys.table_catalog = cols.table_catalog
AND keys.table_schema = cols.table_schema
AND keys.table_name = cols.table_name
LEFT JOIN
information_schema.table_constraints AS constr
ON constr.constraint_name = keys.constraint_name
WHERE
cols.table_schema = 'public' AND
cols.table_name = ? AND
cols.table_name = cls.relname;
`, sheetName).then((response) => response.rows)
}
function createColumn (db, sheetName, { name, dbType }) {
return db.schema.alterTable(sheetName, function (t) {
t.specificType(name, dbType)
})
}
function updateColumn (db, sheetName, columnName, { name, dbType }) {
return db.schema.alterTable(sheetName, function (t) {
if (name) t.renameColumn(columnName, name)
if (dbType) t.specificType(columnName, dbType).alter()
})
}
function deleteColumn (db, sheetName, columnName) {
return db.schema.alterTable(sheetName, function (t) {
t.dropColumn(columnName)
})
}
function getRows (db, sheetName) {
return db
.select()
.from(sheetName)
.orderByRaw(1) // first column
}
function createRow (db, sheetName, payload) {
return db
.insert(payload)
.into(sheetName)
.returning('*')
}
function updateRow (db, sheetName, conditions, payload) {
return db(sheetName)
.where(conditions)
.update(payload)
.returning('*')
}
function deleteRow (db, sheetName, conditions) {
return db(sheetName)
.where(conditions)
.del()
}
|
var R = require('../source/index.js');
var eq = require('./shared/eq.js');
describe('modify', function() {
it('creates a new object by applying the `transformation` function to the given `property` of the `object`', function() {
var object = {name: 'Tomato', elapsed: 100, remaining: 1400};
var expected = {name: 'Tomato', elapsed: 101, remaining: 1400};
eq(R.modify('elapsed', R.add(1), object), expected);
});
it('returns the original object if object does not contain the property', function() {
var object = {name: 'Tomato', elapsed: 100, remaining: 1400};
eq(R.modify('nonexistent', R.add(1), object), object);
});
it('is not destructive', function() {
var object = {name: 'Tomato', elapsed: 100, remaining: 1400};
var expected = {name: 'Tomato', elapsed: 100, remaining: 1400};
R.modify('elapsed', R.add(1), object);
eq(object, expected);
});
it('ignores primitive value transformations', function() {
var object = {n: 0, m: 1};
var expected = {n: 0, m: 1};
eq(R.modify('elapsed', 2, object), expected);
});
it('ignores null transformations', function() {
var object = {n: 0};
var expected = {n: 0};
eq(R.modify('elapsed', null, object), expected);
});
it('adjust if `array` at the given key with the `transformation` function', function() {
var object = [100, 1400];
var expected = [100, 1401];
eq(R.modify(1, R.add(1), object), expected);
});
it('ignores transformations if the input value is not Array and Object', function() {
eq(R.modify('a', R.add(1), 42), 42);
eq(R.modify('a', R.add(1), undefined), undefined);
eq(R.modify('a', R.add(1), null), null);
eq(R.modify('a', R.add(1), ''), '');
});
// TODO: check reference equality?
});
|
import { BORROWED_FETCHED } from './../actions/types';
// Declare the initial state for a single book
const initialState = {
borrow: {}
};
/**
* Singly Borrowed Book Reducer
*
* @description Return each action by its type
*
* @param {object} state - The state passed to the singleBorrowReducer
* @param {object} action - The action passed to the singleBorrowReducer
*
* @returns {object} // Borrowed book
*/
const singleBorrowReducer = (state = initialState, action = {}) => {
switch (action.type) {
case BORROWED_FETCHED: {
return { ...state, borrow: action.borrow };
}
default:
return state;
}
};
export default singleBorrowReducer;
|
import React from 'react';
import chai from 'chai';
import chaiEnzyme from 'chai-enzyme';
import { shallow } from 'enzyme';
import MainScreen from '../../src/app/components/layouts/MainScreen';
import Article from '../../src/app/components/Article';
import Sort from '../../src/app/components/Sort';
import * as data from '../testData';
chai.use(chaiEnzyme());
const expect = chai.expect;
describe('The MainScreen component', () => {
it('should be defined', () => {
expect(<MainScreen />).to.not.equal(undefined);
});
});
const wrapper = shallow(<MainScreen {...data}/>);
describe('After rendering, the mainscreen component', () => {
it('should have a div as the first child', () => {
expect(wrapper).to.have.tagName('div');
});
it('should have Article as its child component', () => {
expect(wrapper).to.have.descendants(Article);
});
it('should have an element with class name `main-headers`', () => {
expect(wrapper.find('.main-headers')).be.present();
});
it('should have a select tag with class name `styled-select`', () => {
expect(wrapper.find('select')).to.match('.styled-select');
});
it('should contain the text `News` in the h2 tag', () => {
expect(wrapper.find('h2')).to.contain.text('News');
});
it('should have the default value `sortby` for the select tag', () => {
expect(wrapper.find('select')).to.have.value('sortby');
});
it('should have option tags with attributes of `value`', () => {
expect(wrapper.find('option')).to.have.attr('value');
});
it('should have a state with key `defaultSort` and value `sortby`', () => {
expect(wrapper).to.have.state('defaultSort', 'sortby');
});
});
describe('The Article component, child of MainScreen,', () => {
it('should receives props named `article` from MainScreen', () => {
expect(wrapper.find(Article).first()).to.have.prop('article');
});
});
describe('The component', () => {
const children = wrapper.children();
it('should have two direct children of the top most div', () => {
expect(children).to.have.length(2);
});
it('should have a first child with an class of `main-headers`', () => {
expect(children.at(0)).to.have.className('main-headers');
});
it('should have a select tag with class of `styled-select`', () => {
expect(children.at(0).find('select')).to.have.className('styled-select');
});
it('should have a second child with an class name of `row`', () => {
expect(children.at(1)).to.have.className('row');
});
});
|
/**
* Groups all client side classes documentation and definition
* @module Client
*/
/**
* The client constructor
*
* @version {{VERSION}}
*
* @param {string} server - The APE Server domain name including port number if other than 80
* @param {object} [events] - Event handlers to be added to the client
* @param {object} [options] - Options to configure the client {@link APS#option}
*
* @returns {APS} An APS client instance
* @constructor
* @memberOf module:Client~
*/
function APS( server, events, options ){
/**
* The client options
*
* @type {{poll: number, debug: boolean, session: boolean, connectionArgs: {}, server: string, transport: Array, transport: string, secure: boolean, eventPush: boolean, addFrequency: boolean, autoUpdate: boolean}}
*
* @property {bool} [debug=false] - Enable and disable debugging features
* such as the log() function output
* @property {bool} [session=true] - Enable and disable user sessions
* @property {string} [transport] - Explicitly use a transport. ws = WebSocket, lp = LongPolling
* @property {Array} [transport=['ws','lp']] - Which transport to try
* and on what order
* @property {bool} [secure=false] - Whether the connection to the server should secure
* @property {string} [eventPush] - Path to a script to re-route all events to.
*/
this.option = {
poll: 25000,
debug: false,
session: true,
connectionArgs: {},
server: server,
transport: ["ws", "lp"],
//transport: "lp", //Should be the default transport option for APE Server v1.1.1
secure: false,
eventPush: false,
addFrequency: true,
autoUpdate: true
}
/**
* The client identifier
* @type {string}
*/
this.identifier = "APS";
/**
* The client version
* @type {string}
*/
this.version = '{{VERSION}}';
/**
* The state of the client: 0=disconnected, 1=connected, 2=connecting
* @type {number}
*/
this.state = 0;
/**
* The client events stack
* @type {Object}
* @private
*/
this._events = {};
/**
* The current user object
* @type {APS.CUser}
*/
this.user = {};
/**
* The collection of all objects on the client as pipes, both channels and users
* @type {Object}
* @private
*/
this.pipes = {};
/**
* The collection of all channel object on the client
* @type {Object}
*/
this.channels = {};
/**
* A second event stack to hold/cache the event of channels
* Use when reconnecting to the server and for channels that have been
* subscribe to yet
* @type {Object}
* @private
*/
this.eQueue = {};
//Add Events
if(!!events)
this.on(events);
//Update options
if(!!options){
for(var opt in options){
this.option[opt] = options[opt];
}
}
//IE9 crap - log function fix
if(navigator.appName == "Microsoft Internet Explorer"){
if(typeof window.console == "undefined"){
this.log = function(){};
}else{
this.log = function(){
if(this.option.debug == false) return;
var args = Array.prototype.slice.call(arguments);
args.unshift("["+this.identifier+"]");
window.console.log(args.join().replace(",",""));
}
}
}
/**
* The current user session object
* @type {APS.Session}
*/
this.session = new APS.Session(this);
return this;
}
/**
* Handles the initial connection to the server
*
* @param args Arguments to send with the initial connect request
* @private
*
* @return bool The client reference or false if the connection request has been canceled
*/
APS.prototype.connect = function(args){
var fserver = this.option.server;
function TransportError(e){
this.trigger("dead", [e]);
this.transport.close();
/*
* Destroys the session
*/
this.session.destroy();
this.state = 0;
}
var cb = {
'onmessage': this.onMessage.bind(this),
'onerror': TransportError.bind(this)
}
if(this.state == 1)
return this.log("Already Connected!");
var cmd = "CONNECT";
args = this.option.connectionArgs = args || this.option.connectionArgs;
var restore = this.session.restore();
//increase frequency
this.session.saveFreq();
//Handle sessions
if(this.option.session == true){
if(typeof restore == "object"){
args = restore;
//Change initial command CONNECT by RESTORE
cmd = "RESTORE";
}else{
//Fresh Connect
if(this.trigger("connect") == false)
return false;
}
}else{
//Fresh Connect
this.state = 0;
//this.session.id = "";
if(this.trigger("connect") == false)
return false;
}
//Apply frequency to the server
if(this.option.addFrequency)
fserver = this.session.getFreq() + "." + fserver;
//Handle transport
if(!!this.transport){
if(this.transport.state == 0){
this.transport = new APS.Transport(fserver, cb, this);
}else{
//Use current active transport
}
}else{
this.transport = new APS.Transport(fserver, cb, this);
}
//Attach version of client framework
args.version = this.version;
//Send seleced command and arguments
this.sendCmd(cmd, args);
return this;
}
/**
* Restore the connection to the server
* @returns {*}
*/
APS.prototype.reconnect = function(){
if(this.state > 0 && this.transport.state > 0)
return this.log("Client already connected!");
//Clear channels stack
this.channels = {};
this.connect();
}
/**
* Triggers events
*
* @param {string} ev - Name of the event to trigger, not case sensitive
* @param {Object} args - An array of arguments to passed to the event handler function
*
* @return {bool} False if any of the event handlers explicitly returns false, otherwise true
*/
APS.prototype.trigger = function(ev, args){
ev = ev.toLowerCase();
if(!(args instanceof Array)) args = [args];
//GLobal
if("_client" in this){
for(var i in this._client._events[ev]){
if(this._client._events[ev].hasOwnProperty(i)){
this.log("{{{ " + ev + " }}}["+i+"] on client ", this._client);
if(this._client._events[ev][i].apply(this, args) === false)
return false;
}
}
}
//Local
for(var i in this._events[ev]){
if(this._events[ev].hasOwnProperty(i)){
if(!this._client){
this.log("{{{ " + ev + " }}}["+i+"] on client ", this);
}else{
this.log("{{{ " + ev + " }}}["+i+"] ", this);
}
if(this._events[ev][i].apply(this, args) === false)
return false;
}
}
return true;
}
/**
* Add event handler(s) to the client
*
* Events added to the client are considered to be global event. For example
* if adding the **message** event handler on the client it will be triggered
* every time a channel receives a message event
*
* @param {string} ev Name of the event handler to add, not case sensitive
* @param {function} fn Function to handle the event
*
* @return {bool|APS} False if wrong parameters are passed, otherwise the client or parent object reference
*/
APS.prototype.on = function(ev, fn){
var Events = [];
if(typeof ev == 'string' && typeof fn == 'function'){
Events[ev] = fn;
}else if(typeof ev == "object"){
Events = ev;
}else{
this.log("Wrong parameters passed to on() method");
return false;
}
for(var e in Events){
if(!Events.hasOwnProperty(e)) continue;
var fn = Events[e];
e = e.toLowerCase();
if(!this._events[e])
this._events[e] = [];
this._events[e].push(fn);
}
return this;
}
/**
* Get any object by its unique publisher id, user or channel
*
* @param {string} pubid A string hash
* @return {bool|APS.User|APS.Channel}
*/
APS.prototype.getPipe = function( pubid ){
if(pubid in this.pipes){
return this.pipes[pubid];
}
return false;
}
/**
* Sends an event through a pipe/user/channel
* This function is not useful in this context
* Its real use is when bound to a user or channel
* objects. Consider using {@link APS.User#send user.send()} and
* {@link APS.Channel#send channel.send()} instead
*
* Although it could be useful if a developer has
* its own way of getting a user's or channels's pubid
* who object does not resides in the local client
*
* @param {string|object} pipe The pubid string or pipe object of user or channel
* @param {string} $event The name of the event to send
* @param {*} data The data to send with the event
* @param {bool} sync Weather to sync event across the user's session or not
* @param {function} callback Function to call after the event has been sent
*
* @return {APS} client or parent object reference
*/
APS.prototype.send = function(pipe, $event, data, sync, callback){
this.sendCmd("Event", {
event: $event,
data: data,
sync: sync
}, pipe, callback);
return this;
}
/**
* Internal method to wrap events and send them as commands to the server
*
* @param {string} cmd Name of command in the server which will handle the request
* @param {*} args The data to send with the command
* @param {string|object} pipe The pubid string or pipe object of user or channel
* @param {function} callback Function to after the event has been sent
* @private
*
* @return (object) client reference
*/
APS.prototype.sendCmd = function(cmd, args, pipe, callback){
var specialCmd = {CONNECT: 0, RESTORE:0};
if(this.state == 1 || cmd in specialCmd){
var tmp = {
'cmd': cmd,
'chl': this.transport.chl,
'freq': this.session.getFreq()
}
if(args) tmp.params = args;
if(pipe) {
tmp.params.pipe = typeof pipe == 'string' ? pipe : pipe.pubid;
}
if(this.session.getID()) tmp.sessid = this.session.getID();
this.log('<<<< ', cmd.toUpperCase() , " >>>> ", tmp);
if(typeof callback != "function") callback = function(){};
var data = [];
try {
data = JSON.stringify([tmp]);
}catch(e){
this.log(e);
this.log("Data Could not be strigify:", data);
this.quit();
}
//Send command
if(this.transport.send(data, callback, tmp) != "pushed"){
this.transport.chl++;
}
} else {
this.on('ready', this.sendCmd.bind(this, cmd, args));
}
return this;
}
/**
* Polls the server for information when using the Long Polling transport
* @private
*/
APS.prototype.poll = function(){
if(this.transport.id == 0){
clearTimeout(this.poller);
this.poller = setTimeout(this.check.bind(this), this.option.poll);
}
}
/**
* Sends a check command to the server
* @private
*/
APS.prototype.check = function(force){
if(this.transport.id == 0 || !!force){
this.sendCmd('CHECK');
this.poll();
}
}
/**
* Log the user out and kill the client
*
* Sends the QUIT command to the server and completely destroys the client instance
* and session
*/
APS.prototype.quit = function(){
this.sendCmd('QUIT');
this.transport.close();
this.trigger("dead");
//Clear session on 'quit'
this.session.destroy();
this.state = 0;
}
/**
* Subscribe to a channel
*
* @param {string} channel - Name of the channel to subscribe to
* @param {object} Events - List of event handlers to add to the channel
* @param {function} callback - Function to be called when a user successfully subscribes to the channel
*
* @return {APS} client reference
*/
APS.prototype.sub = function(channel, Events, callback){
//Handle the events
if(typeof Events == "object"){
if(typeof channel == "object"){
for(var chan in channel){
this.onChannel(channel[chan], Events);
}
}else{
this.onChannel(channel, Events);
}
}
//Handle callback
if(typeof callback == "function"){
if(typeof channel == "object"){
for(var chan in channel){
this.onChannel(channel[chan], "joined", callback);
}
}else{
this.onChannel(channel, "joined", callback);
}
}
//Join Channel
if(this.state == 0){
this.on("ready", this.sub.bind(this, channel));
this.connect({user: this.user});
}else{
//Logic to only send the JOIN request to only non-existing channels in the client object
if(typeof channel == "string"){
//Single Channel
channel = channel.toLowerCase();
if(typeof this.channels[channel] != "object"){
this.sendCmd('JOIN', {'channels': [channel]});
}else{
this.log("User already subscribed to [" + channel + "]");
}
}else{
//Multi Channel
var toJoin = [];
for(var x in channel){
if(typeof this.channels[channel[x].toLowerCase()] != "object")
toJoin.push(channel[x]);
}
if(toJoin.length > 0)
this.sendCmd('JOIN', {'channels': toJoin});
}
}
return this;
}
/**
* Alias for {@link APS#sub}
* @see APS#sub
* @methodOf APS
* @function
*/
APS.prototype.subscribe = APS.prototype.sub;
/**
* Publishes anything in a channel, a string, object, array or integer
*
* @param {string} channel The name of the channel
* @param {*} data Data to send to the channel
* @param {bool} sync Whether to to synchronize the event across the uer session
* @param {function} callback Function called after the event is sent
*/
APS.prototype.pub = function(channel, data, sync, callback){
var pipe = this.getChannel(channel);
if(!pipe && channel.length == 32) pipe = this.getPipe(channel);
if(pipe){
var $event = typeof data == "string" ? "message" : "data";
if($event == "message") data = encodeURIComponent(data);
pipe.send($event, data, sync, callback);
}else{
this.log("NO Channel " + channel);
}
};
/**
* Alias for {@link APS#pub}
* @see APS#pub
* @methodOf APS
* @function
*/
APS.prototype.publish = APS.prototype.pub;
/**
* Get a channel object by its name
*
* @param channel Name of the channel
* @return {bool|APS.Channel} Returns the channel object if it exists or false otherwise
*/
APS.prototype.getChannel = function(channel){
channel = channel.toLowerCase();
if(channel in this.channels){
return this.channels[channel];
}
return false;
}
/**
* Add event handler(s) to a channel
*
* With this method event handler(s) can be added to a channel event if the user is not subscribe to it yet.
* @param {string} channel The channel name
* @param {string|object} Events Either an event name or key pair of multiple events
* @param {function} [fn] The callback function if Events is a string
* @returns {bool|APS.Channel}
*/
APS.prototype.onChannel = function(channel, Events, fn){
channel = channel.toLowerCase();
if(channel in this.channels)
{
this.channels[channel].on(Events, fn);
}
else
{
if(typeof Events == "object"){
//add events to queue
if(typeof this.eQueue[channel] != "object")
this.eQueue[channel] = [];
//this.eQueue[channel].push(Events);
for(var $event in Events){
fn = Events[$event];
this.eQueue[channel].push([$event, fn]);
this.log("Adding ["+channel+"] event '"+$event+"' to queue");
}
}else{
var xnew = Object();
xnew[Events] = fn;
this.onChannel(channel,xnew);
}
}
}
/**
* Unsubscribe from a channel
*
* @param {string} channel - Name of the channel to unsubscribe
*/
APS.prototype.unSub = function(channel){
if(channel == "") return;
this.getChannel(channel).leave();
}
/**
* Alias of {@link APS#unSub}
* @see APS#unSub
* @methodOf APS
* @function
*/
APS.prototype.unSubscribe = APS.prototype.unSub;
/*
* Debug Function for Browsers console
*/
if(navigator.appName != "Microsoft Internet Explorer"){
/**
* Logs data to the browser console if debugging is enable
* @type {Function}
*/
APS.prototype.log = function(){
if(this.option.debug)
{
var args = Array.prototype.slice.call(arguments);
args.unshift("["+this.identifier+"]");
window.console.log.apply(console, args);
}
};
} |
import { h } from 'omi';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(h("path", {
d: "M9 4c0-1.11.89-2 2-2s2 .89 2 2-.89 2-2 2-2-.89-2-2zm7 9c-.01-1.34-.83-2.51-2-3 0-1.71-1.42-3.08-3.16-3C9.22 7.09 8 8.54 8 10.16V16c0 .55.45 1 1 1h1v3.5c0 .83.67 1.5 1.5 1.5s1.5-.67 1.5-1.5V17h2c.55 0 1-.45 1-1v-3z"
}), 'PregnantWomanRounded'); |
//Mangage mongodb process https://docs.mongodb.org/v3.0/tutorial/install-mongodb-on-windows/
'use strict';
var monkdb = require('monk')('localhost/koapp');
module.exports = {
monkdb: monkdb
} |
require('dotenv').load();
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var twitterAPI = require('node-twitter-api');
var fs = require('fs');
var twitter = new twitterAPI({
consumerKey: process.env.TWITTER_CONSUMER_KEY,
consumerSecret: process.env.TWITTER_CONSUMER_SECRET,
oauth_callback: 'http://localhost:3000/twitter-callback'
});
// console.log(twitter);
var routes = require('./routes/index');
var users = require('./routes/users');
var app = express();
var SparkPost = require('sparkpost');
var client = new SparkPost(process.env.SPARKPOST_API);
var cps = require('./node_modules/cps-api');
var conn = new cps.Connection('tcp://cloud-us-0.clusterpoint.com:9007', 'facetrax', process.env.DB_USERNAME, process.env.DB_PASSWORD, 'document', 'document/id', {account: 100322});
conn.debug = true;
// Get a list of domains that the Metrics API contains data on.
// var options = {
// uri: 'metrics/domains'
// };
// var id = 3,
// name = "Username";
// var insert_request = new cps.InsertRequest('<document><id>'+id+'</id>'+cps.Term(name, "name")+'</document>');
// conn.sendRequest(insert_request, function(err, insert_response) {
// if (err) return console.error(err);
// console.log('New user registered: ' + insert_response.document.id);
// });
// twitter.getRequestToken(function(error, requestToken, requestTokenSecret, results){
// if (error) {
// console.log("Error getting OAuth request token : " + error);
// console.log(results);
// } else {
// //store token and tokenSecret somewhere, you'll need them later; redirect user
// console.log(requestToken + ", " + requestTokenSecret);
// }
// });
// twitter.statuses("update", {
// status: "Hello world!"
// },
// process.env.TWITTER_ACCESS_TOKEN,
// process.env.TWITTER_ACCESS_TOKEN_SECRET,
// function(error, data, response) {
// if (error) {
// // something went wrong
// } else {
// // data contains the data sent by twitter
// }
// }
// );
function base64_encode(file) {
// read binary data
var bitmap = fs.readFileSync(file);
// convert binary data to base64 encoded string
return new Buffer(bitmap).toString('base64');
}
// twitter.uploadMedia({
// media: base64_encode("photo/family.jpg"),
// isBase64: true
// }, process.env.TWITTER_ACCESS_TOKEN, process.env.TWITTER_ACCESS_TOKEN_SECRET, function(err, data, res) {
// console.log(data.media_id);
// twitter.statuses("update", {
// status: "Test",
// media_ids: data.media_id_string
// }, process.env.TWITTER_ACCESS_TOKEN, process.env.TWITTER_ACCESS_TOKEN_SECRET, function(err, data, res) {
// // console.log(err);
// console.log(data);
// // console.log(res);
// // setTimeout(function() {
// // twitter.statuses("destroy", {
// // id: data.id
// // }, process.env.TWITTER_ACCESS_TOKEN, process.env.TWITTER_ACCESS_TOKEN_SECRET, function(err, data, res) {
// // console.log(err);
// // console.log(data);
// // console.log(res);
// // });
// // }, 10000);
// });
// });
// twitter.getRequestToken(function(error, requestToken, requestTokenSecret, results){
// if (error) {
// console.log(error);
// } else {
// //store token and tokenSecret somewhere, you'll need them later; redirect user
// console.log("https://twitter.com/oauth/authenticate?oauth_token=" + requestToken);
// console.log(requestToken);
// console.log(requestTokenSecret);
// }
// });
// twitter.getTimeline("user", {
// screen_name:"grandnexus"
// },
// process.env.TWITTER_ACCESS_TOKEN,
// process.env.TWITTER_ACCESS_TOKEN_SECRET,
// function(error, data, response) {
// if (error) {
// // something went wrong
// console.log(error);
// } else {
// // data contains the data sent by twitter
// console.log(data[0].user.profile_image_url);
// }
// }
// );
var trans = {
options: {
open_tracking: true,
click_tracking: true
},
campaign_id: "christmas_campaign",
return_path: "facetrax@chooyansheng.me",
metadata: {
user_type: "students"
},
substitution_data: {
sender: "Big Store Team"
},
recipients: [
{
return_path: "facetrax@chooyansheng.me",
address: {
email: "cys009@gmail.com",
name: "Ai Meili"
},
tags: [
"greeting",
"prehistoric",
"fred",
"flintstone"
],
metadata: {
place: "Bedrock"
},
substitution_data: {
customer_type: "Platinum"
}
}
],
content: {
from: {
name: "Facetrax",
email: "facetrax@chooyansheng.me"
},
subject: "Big Christmas savings!",
reply_to: "Christmas Sales <facetrax@chooyansheng.me>",
headers: {
"X-Customer-Campaign-ID": "christmas_campaign"
},
text: "Hi {{address.name}} \nSave big this Christmas in your area {{place}}! \nClick http://www.mysite.com and get huge discount\n Hurry, this offer is only to {{user_type}}\n {{sender}}",
html: "<p>Hi {{address.name}} \nSave big this Christmas in your area {{place}}! \nClick http://www.mysite.com and get huge discount\n</p><p>Hurry, this offer is only to {{user_type}}\n</p><p>{{sender}}</p>"
}
};
// client.transmissions.send({transmissionBody: trans}, function(err, res) {
// if (err) {
// console.log(err);
// } else {
// console.log(res.body);
// console.log("Congrats you can use our SDK!");
// }
// });
// client.sendingDomains.all(function(err, res) {
// if (err) {
// console.log(err);
// } else {
// console.log(res.body);
// console.log('Congrats you can use our SDK!');
// }
// });
//
// client.get(options, function(err, data) {
// if(err) {
// console.log(err);
// return;
// }
//
// console.log(data.body);
// });
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// uncomment after placing your favicon in /public
//app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json({limit: '5mb'}));
app.use(bodyParser.urlencoded({limit: '5mb', extended: true}));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', routes);
app.use('/users', users);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;
|
"use strict";
const Module = require('../../ts/index');
const nock = require('nock');
const Fixtures_1 = require('../fixtures/Fixtures');
const chai_1 = require('chai');
describe('Zips Class', () => {
const putioClient = new Module.Client('testToken');
describe('GET /zips/<zip_id>', () => {
it('Should return valid response if parameters are valid', (done) => {
const zipID = 1477908884;
const info = new Fixtures_1.Fixtures('../fixtures/zips/zips.id.get.response.json');
nock('https://api.put.io/v2')
.defaultReplyHeaders({ 'Content-Type': 'application/json' })
.get(`/zips/${zipID}`)
.query(true)
.reply(200, info.fixtureData);
putioClient.zips.getZipId(zipID).then((result) => {
chai_1.expect(result).to.equal(JSON.stringify(info.fixtureData));
done();
}).catch(err => {
chai_1.expect(err).to.contain('Error:');
done(err);
});
});
it('Should return an error if bad request', (done) => {
const zipID = 1477908884;
const info = new Fixtures_1.Fixtures('../fixtures/zips/zips.id.get.response.json');
nock('https://api.put.io/v2')
.defaultReplyHeaders({ 'Content-Type': 'application/json' })
.get(`/zips/${zipID}`)
.query(true)
.reply(400, 'Bad Request');
putioClient.zips.getZipId(zipID).then((result) => {
chai_1.expect(result).not.to.equal(JSON.stringify(info.fixtureData));
done();
}).catch(err => {
chai_1.expect(err).to.contain('Error:');
done();
});
});
});
describe('GET /zips/list', () => {
it('Should return valid response if parameters are valid', (done) => {
const info = new Fixtures_1.Fixtures('../fixtures/zips/zips.list.get.response.json');
nock('https://api.put.io/v2')
.defaultReplyHeaders({ 'Content-Type': 'application/json' })
.get('/zips/list')
.query(true)
.reply(200, info.fixtureData);
putioClient.zips.getZipsList().then((result) => {
chai_1.expect(result).to.equal(JSON.stringify(info.fixtureData));
done();
}).catch(err => {
chai_1.expect(err).to.contain('Error:');
done(err);
});
});
it('Should return an error if bad request', (done) => {
const info = new Fixtures_1.Fixtures('../fixtures/zips/zips.list.get.response.json');
nock('https://api.put.io/v2')
.defaultReplyHeaders({ 'Content-Type': 'application/json' })
.get('/zips/list')
.query(true)
.reply(400, 'Bad Request');
putioClient.zips.getZipsList().then((result) => {
chai_1.expect(result).not.to.equal(JSON.stringify(info.fixtureData));
done();
}).catch(err => {
chai_1.expect(err).to.contain('Error:');
done();
});
});
});
describe('POST /zips/create', () => {
it('Should return valid response if parameters are valid', (done) => {
const fileId = [36738408];
const info = new Fixtures_1.Fixtures('../fixtures/zips/zips.create.post.response.json');
nock('https://api.put.io/v2')
.defaultReplyHeaders({ 'Content-Type': 'application/json' })
.post('/zips/create')
.query(true)
.reply(200, info.fixtureData);
putioClient.zips.createZip(fileId).then((result) => {
chai_1.expect(result).to.equal(JSON.stringify(info.fixtureData));
done();
}).catch(err => {
chai_1.expect(err).to.contain('Error:');
done(err);
});
});
it('Should return an error if bad request', (done) => {
const fileId = [36738408];
const info = new Fixtures_1.Fixtures('../fixtures/zips/zips.create.post.response.json');
nock('https://api.put.io/v2')
.defaultReplyHeaders({ 'Content-Type': 'application/json' })
.post('/zips/create')
.query(true)
.reply(400, 'Bad Request');
putioClient.zips.createZip(fileId).then((result) => {
chai_1.expect(result).not.to.equal(JSON.stringify(info.fixtureData));
done();
}).catch(err => {
chai_1.expect(err).to.contain('Error:');
done();
});
});
});
});
//# sourceMappingURL=Zips.js.map |
module.exports = {
color1: '#ffae23',
emphasizeReflections: true,
floor: {
shininess: 20,
specularColor: '#ffffff'
},
lights: {
ambientColor: '#545454',
posX: -100,
posY: 100,
posZ: 100
},
reflectionsOn: true,
teapot: {
shininess: 1,
specularColor: '#E6E6E6'
}
}
|
define(function (require) {
return {
image: require('./wrapper/image')
};
});
|
version https://git-lfs.github.com/spec/v1
oid sha256:6840e412d9cb1ebc0d336ca25e306266cc1cdd9921fc5822c11e35a817b4f330
size 108265
|
Moksi.Object = {
isUndefined: function(object) {
return typeof object === "undefined";
},
isEmpty: function(object) {
if (Moksi.Object.isUndefined(object)) return true;
if (object == null) return true;
if (object.length > 0) {
return false;
} else {
for (property in object) { if (object.hasOwnProperty(property)) {
return false;
} }
}
return true;
},
isEqual: function(left, right) {
if (left == null && right == null) return true;
if (left && (typeof left == 'function')) {
return left == right;
} else if (left && (typeof left.length == 'number') && (typeof left != 'string')) {
return Moksi.Object.isEqualEnumerable(left, right);
} else if (typeof left == 'object') {
return Moksi.Object.isEqualObject(left, right);
} else {
return left == right;
}
},
isEqualEnumerable: function(left, right) {
if (Moksi.Object.isUndefined(left) || Moksi.Object.isUndefined(right)) return false;
if (left == null || right == null) return false;
if (left.length != right.length) return false;
var i = left.length;
while(i--) {
if (!this.isEqual(left[i], right[i])) return false;
}
return true;
},
isEqualObject: function(left, right) {
if (Moksi.Object.isUndefined(left) || Moksi.Object.isUndefined(right)) return false;
if (left == null || right == null) return false;
for (var key in left) {
if (!this.isEqual(left[key], right[key])) return false;
}
for (var key in right) {
if (!this.isEqual(left[key], right[key])) return false;
}
return true;
}
}; |
function solve(input) {
let pattern=/^([A-Z][a-zA-Z]*) - ([1-9][0-9]*) - ([a-zA-Z0-9 -]+)$/;
let result= [], match;
for (let person of input) {
let match=pattern.exec((person))
if(match){
let personInfo={
'name':match[1],
'salary':match[2],
'position':match[3]
};
result.push(personInfo);
}
}
for (let person of result) {
console.log(`Name: ${person.name}`);
console.log(`Position: ${person.position}`);
console.log(`Salary: ${person.salary}`)
}
} |
var db = require("../config/db"),
assert = require("assert");
function fetchTodos(callback) {
var collection = db.get().collection('todos');
var cursor = collection.find();
var result = [];
cursor.forEach(function(document, err) {
assert.equal(null, err);
result.push(document);
}, function() {
callback(result);
});
}
function addTodo(item) {
var collection = db.get().collection('todos');
collection.insertOne(item, function(err, result) {
assert.equal(null, err);
console.log("Item has inserted!");
//db.close();
});
}
module.exports = {
fetchTodos: fetchTodos,
addTodo: addTodo
}; |
var gm = require("gm");
var request = require("request");
exports.convert = function(imgBody, fileName, params) {
return new Promise(function(resolve, reject) {
var image = gm(imgBody).options({ imageMagick: true })
.strip()
.setFormat("jpg");
var gravity = params.gravity || "Center";
var quality = params.quality || "90";
image = image.gravity(gravity).quality(quality);
image.size(function(err, originalSize) {
if (resizedHeight(originalSize, params) < params.height) {
image = image.resize(null, params.height);
} else {
image = image.resize(params.width);
}
var extentWidth = params.width || originalSize.width;
var extentHeight = params.height || originalSize.height;
image = image.extent(extentWidth, extentHeight);
if (params.blur) {
image = image.blur(0, params.blur);
}
image.write("/tmp/" + fileName + ".jpg", function(err) {
return resolve();
});
});
});
};
exports.fetch = function (url) {
return new Promise(function(resolve) {
request.get({ url: url, encoding: null }, function(err, res) {
resolve(res);
});
});
};
function resizedHeight(originalSize, params) {
return (originalSize.height * params.width) / originalSize.width;
}
|
var PersonalizedStream = require('../api/personalized_stream');
var CursorData = require('../model/cursor_data');
var CursorValidator = require('../validator/cursor_validator');
function TimelineCursor(core, data, callback) {
this.core = core;
this.data = data;
this.callback = callback;
}
module.exports = TimelineCursor;
TimelineCursor.init = function init(core, resource, limit, startTime, callback) {
var data = new CursorData(resource, limit, startTime);
return new TimelineCursor(core, CursorValidator.validate(data), callback);
};
TimelineCursor.prototype.next = function next() {
var handler = function(err, cursor, result) {
if (err) {
return cursor.callback(err);
}
var c = result.meta.cursor;
cursor.data.next = c.hasNext;
cursor.data.previous = c.next != null;
if (cursor.data.previous) {
cursor.data.cursorTime = c.next;
}
cursor.callback(null, result);
};
PersonalizedStream.getTimelineStream(this, true, handler);
};
TimelineCursor.prototype.previous = function previous() {
var handler = function(err, cursor, result) {
if (err) {
return cursor.callback(err);
}
var c = result.meta.cursor;
cursor.data.previous = c.hasPrev;
cursor.data.next = c.prev != null;
if (cursor.data.next) {
cursor.data.cursorTime = c.prev;
}
cursor.callback(null, result);
};
PersonalizedStream.getTimelineStream(this, false, handler);
}; |
$(document).ready(function(){
$('.deleteEvent').on('click',function(e){
deleteId = $('.deleteEvent') .data('delete');
$.ajax({
url:'/events/delete/' + deleteId,
type:'DELETE',
success:function(result){
console.log("deleted");
}
});
window.location = '/events';
});
}); |
var _combine_input = function () {
// 開頭設定
_reset_result();
// ------------------------------------------
// 資料處理設定
var _csv = $("#input_data").val();
_load_csv_to_ct_json(_csv);
}; // var _combine_input = function () {
// ---------------------------------------
_data = {};
var _get_fix_precision = function (_number) {
var _precision = $("#input_precise").val();
_precision = eval(_precision);
return precision_string(_number, _precision);
};
// -----------------------------------------------------
tinyMCE.init({
mode : "specific_textareas",
editor_selector : "mceEditor",
plugins: [
'advlist autolink lists link image charmap print preview hr anchor pagebreak',
'searchreplace wordcount visualblocks visualchars code fullscreen',
'insertdatetime media nonbreaking save table contextmenu directionality',
'emoticons template paste textcolor colorpicker textpattern imagetools codesample toc'
],
toolbar1: 'undo redo | insert | styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image tableprops',
toolbar2: 'print preview media | forecolor backcolor emoticons | codesample code ',
setup:function(ed) {
ed.on('change', function(e) {
//console.log('the content ', ed.getContent());
_combine_input();
});
}
});
var _reset_result = function () {
var _panel = $(".file-process-framework");
var _input = _panel.find("#preview");
_input.val("");
_panel.find("#preview_html").empty();
};
// --------------------------
var _process_file = function(_input, _callback) {
_callback(_input);
};
var _output_filename_surffix="_output";
// -------------------------------------
var _load_file = function(evt) {
//console.log(1);
if(!window.FileReader) return; // Browser is not compatible
var _file_input = this;
var _selector = $(this).data("file-to-textarea");
_selector = $(_selector);
if (_selector.length === 0) {
return;
}
//console.log(_selector);
//return;
var reader = new FileReader();
var _result;
var _file_name = evt.target.files[0].name;
reader.onload = function(evt) {
if(evt.target.readyState !== 2) return;
if(evt.target.error) {
alert('Error while reading file');
return;
}
//filecontent = evt.target.result;
//document.forms['myform'].elements['text'].value = evt.target.result;
_result = evt.target.result;
_process_file(_result, function (_result) {
_selector.val(_result);
_selector.change();
$(_file_input).val("");
});
};
// var _pos = _file_name.lastIndexOf(".");
// _file_name = _file_name.substr(0, _pos)
// + _output_filename_surffix
// + _file_name.substring(_pos, _file_name.length);
//console.log(_file_name);
reader.readAsText(evt.target.files[0]);
};
var _load_textarea = function(evt) {
var _panel = $(".file-process-framework");
// --------------------------
var _result = _panel.find(".input-mode.textarea").val();
if (_result.trim() === "") {
return;
}
// ---------------------------
_panel.find(".loading").removeClass("hide");
// ---------------------------
var d = new Date();
var utc = d.getTime() - (d.getTimezoneOffset() * 60000);
var local = new Date(utc);
var _file_name = local.toJSON().slice(0,19).replace(/:/g, "-");
_file_name = "output_" + _file_name + ".txt";
// ---------------------------
_process_file(_result, function (_result) {
_panel.find(".preview").val(_result);
_panel.find(".filename").val(_file_name);
_panel.find(".loading").addClass("hide");
_panel.find(".display-result").show();
_panel.find(".display-result .encoding").hide();
var _auto_download = (_panel.find('[name="autodownload"]:checked').length === 1);
if (_auto_download === true) {
_panel.find(".download-file").click();
}
});
};
// ----------------------------------
var _download_file_button = function () {
var _panel = $(".file-process-framework");
var _file_name = _panel.find(".filename").val();
var _data = _panel.find(".preview").val();
_download_file(_data, _file_name, "txt");
};
var _download_file = function (data, filename, type) {
var a = document.createElement("a"),
file = new Blob([data], {type: type});
if (window.navigator.msSaveOrOpenBlob) // IE10+
window.navigator.msSaveOrOpenBlob(file, filename);
else { // Others
var url = URL.createObjectURL(file);
a.href = url;
a.download = filename;
document.body.appendChild(a);
a.click();
setTimeout(function() {
document.body.removeChild(a);
window.URL.revokeObjectURL(url);
}, 0);
}
};
var _load_google_spreadsheet = function () {
var _url = this.value.trim();
if (_url.indexOf('https://docs.google.com/spreadsheets/d/') !== 0
|| _url.indexOf('/pubhtml') === -1) {
return;
}
// https://docs.google.com/spreadsheets/d/1KL07qS2txPpnZSvLt0gBWJ2_lGsVTr51s5JkE4bg2tY/pubhtml?gid=539063364&single=true
// https://docs.google.com/spreadsheets/d/1zwOPqpkcX2YRDEXLQEd2eM8OVz24FEXT5WT5eFP6ZsA/pubhtml
// https://docs.google.com/spreadsheets/d/1zwOPqpkcX2YRDEXLQEd2eM8OVz24FEXT5WT5eFP6ZsA/pubhtml
// https://docs.google.com/spreadsheets/d/1zwOPqpkcX2YRDEXLQEd2eM8OVz24FEXT5WT5eFP6ZsA/pubhtml?gid=1213777536&single=true
//
// https://docs.google.com/spreadsheets/d/0AtMEoZDi5-pedElCS1lrVnp0Yk1vbFdPaUlOc3F3a2c/pubhtml
//
// https://spreadsheets.google.com/feeds/list/1zwOPqpkcX2YRDEXLQEd2eM8OVz24FEXT5WT5eFP6ZsA/data/public/values?alt=json-in-script&gid=1213777536&callback=a&
// https://spreadsheets.google.com/feeds/list/0AtMEoZDi5-pedElCS1lrVnp0Yk1vbFdPaUlOc3F3a2c/od6/public/values?alt=json-in-script&callback=a
// https://spreadsheets.google.com/feeds/list/1zwOPqpkcX2YRDEXLQEd2eM8OVz24FEXT5WT5eFP6ZsA/od6/public/values?alt=json&gid=1213777536&callback=a
// https://docs.google.com/spreadsheets/d/1zwOPqpkcX2YRDEXLQEd2eM8OVz24FEXT5WT5eFP6ZsA/pub?gid=1213777536&single=true&output=csv
// https://spreadsheets.google.com/feeds/list/1zwOPqpkcX2YRDEXLQEd2eM8OVz24FEXT5WT5eFP6ZsA/1/public/values?alt=json&gid=1213777536&callback=a
// https://docs.google.com/spreadsheets/d/1zwOPqpkcX2YRDEXLQEd2eM8OVz24FEXT5WT5eFP6ZsA/pubhtml
var _id = _url.substring(('https://docs.google.com/spreadsheets/d/').length, _url.length - ('/pubhtml').length);
console.log(_id);
var _input = this;
var _selector = $(_input).data("file-to-textarea");
_selector = $(_selector);
//var _json_url = 'https://spreadsheets.google.com/feeds/list/' + _id + '/od6/public/values?alt=json-in-script&callback=?';
var _json_url = 'https://spreadsheets.google.com/feeds/list/' + _id + '/1/public/values?alt=json-in-script&gid=1213777536&callback=?';
//console.log(_json_url);
$.getJSON(_json_url, function (_data) {
_data = _data.feed.entry;
var _text = [];
var _attr_list = [];
//console.log(_data);
for (var _i = 0; _i < _data.length; _i++) {
var _line = _data[_i].content.$t.split(", ");
for (var _j = 0; _j < _line.length; _j++) {
var _t = _line[_j].split(": ");
var _attr = _t[0];
var _value = _t[1];
if (_i === 0) {
_attr_list.push(_attr);
}
_line[_j] = _value;
}
_text.push(_line.join(','));
}
_text = _attr_list.join(",") + "\n" + _text.join("\n");
console.log(_text);
// ----------------------------
_selector.val(_text).change();
//console.log(_data);
});
// https://script.google.com/macros/s/AKfycbzGvKKUIaqsMuCj7-A2YRhR-f7GZjl4kSxSN1YyLkS01_CfiyE/exec
//console.log(_id);
};
// -----------------------
var _load_data_from_filepath = function (_selector, _file_path, _callback) {
$.get(_file_path, function (_data) {
$(_selector).val(_data);
_callback();
});
};
var _change_tirgger_input = function () {
var _selector = $(this).data("trigger-selector");
$(_selector).change();
};
// -----------------------
$(function () {
$('.menu .item').tab();
var _panel = $(".file-process-framework");
//_panel.find(".input-mode.textarea").click(_load_textarea).keyup(_load_textarea);
_panel.find(".download-file").click(_download_file_button);
_panel.find(".change-trigger").change(_combine_input);
_panel.find(".change-trigger-draw").change(_draw_result_table);
_panel.find(".key-up-trigger").keyup(_combine_input);
_panel.find(".focus_select").focus(function () {
$(this).select();
});
_panel.find(".file-change-trigger").change(_load_file);
_panel.find(".google-spreadsheet-trigger")
.change(_load_google_spreadsheet)
//.change();
_panel.find(".change-trigger-input").change(_change_tirgger_input);
//$('.menu .item').tab();
_load_data_from_filepath("#input_data", "data.csv", _combine_input);
$('#copy_source_code').click(function () {
PULI_UTIL.clipboard.copy($("#preview").val());
});
$('#copy_source_code_html').click(function () {
PULI_UTIL.clipboard.copy($("#preview_html_source").val());
});
/*
$( ".sortable" ).sortable({
beforeStop: function () {
_draw_result_table();
}
});
$( ".sortable" ).disableSelection();
*/
}); |
import path from 'path';
import fs from 'fs';
export const copyFileSync = (source, target) => {
let targetFile = target;
// if target is a directory a new file with the same name will be created
if (fs.existsSync(target)) {
if (fs.lstatSync(target).isDirectory()) {
targetFile = path.join(target, path.basename(source));
}
}
fs.writeFileSync(targetFile, fs.readFileSync(source));
};
export const copyFolderRecursiveSync = (source, target) => {
let files = [];
// check if folder needs to be created or integrated
const targetFolder = path.join(target, path.basename(source));
if (!fs.existsSync(targetFolder)) {
fs.mkdirSync(targetFolder);
}
// copy
if (fs.lstatSync(source).isDirectory()) {
files = fs.readdirSync(source);
files.forEach(file => {
const curSource = path.join(source, file);
if (fs.lstatSync(curSource).isDirectory()) {
copyFolderRecursiveSync(curSource, targetFolder);
} else {
copyFileSync(curSource, targetFolder);
}
});
}
};
|
// de-indent from https://github.com/yyx990803/de-indent
var splitRE = /\r?\n/g
var emptyRE = /^\s*$/
var needFixRE = /^(\r?\n)*[\t\s]/
module.exports = function deindent (str) {
if (!needFixRE.test(str)) {
return str
}
var lines = str.split(splitRE)
var min = Infinity
var type, cur, c
for (var i = 0; i < lines.length; i++) {
var line = lines[i]
if (!emptyRE.test(line)) {
if (!type) {
c = line.charAt(0)
if (c === ' ' || c === '\t') {
type = c
cur = count(line, type)
if (cur < min) {
min = cur
}
} else {
return str
}
} else {
cur = count(line, type)
if (cur < min) {
min = cur
}
}
}
}
return lines.map(function (line) {
return line.slice(min)
}).join('\n')
}
function count (line, type) {
var i = 0
while (line.charAt(i) === type) {
i++
}
return i
} |
import postcss from 'postcss';
function getImports(css) {
const imports = {};
css.each(importRule => {
const { selector } = importRule;
if (!selector || selector.indexOf(':import') === -1) return;
importRule.walkDecls(decl => imports[decl.prop] = decl.value);
});
return imports;
}
function connectExportsWithImports(css) {
css.each(importRule => {
const { selector } = importRule;
if (!selector || selector.indexOf(':import') === -1) return;
const exportRule = importRule.prev();
if (!exportRule || !exportRule.selector === ':export') return;
const exports = {};
exportRule.walkDecls(decl => exports[decl.prop] = decl.value);
importRule.walkDecls(decl => {
Object.keys(exports).forEach(key => {
if (decl.value === key) decl.value = exports[key];
});
});
});
}
function applyImports(css) {
connectExportsWithImports(css);
const imports = getImports(css);
const importedClasses = Object.keys(imports);
css.each(exportRule => {
if (exportRule.selector !== ':export') return;
exportRule.walkDecls(decl => {
const exportedClasses = decl.value.split(' ');
importedClasses.forEach(importedClass => {
const index = exportedClasses.indexOf(importedClass);
if (index > -1) {
exportedClasses[index] = imports[importedClass];
decl.value = exportedClasses.join(' ');
}
});
});
});
}
export default postcss.plugin('postcss-modules:applyImports', () => {
return applyImports;
});
|
const {describe, it} = global;
import {expect} from 'chai';
import {shallow} from 'enzyme';
import BuddyList from '../buddy_list';
describe('users.components.buddy_list', () => {
it('should do something');
});
|
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* Coerces a data-bound value (typically a string) to a boolean.
* @param {?} value
* @return {?}
*/
function coerceBooleanProperty(value) {
return value != null && `${value}` !== 'false';
}
/**
* Coerces a data-bound value (typically a string) to a number.
* @param {?} value
* @param {?=} fallbackValue
* @return {?}
*/
function coerceNumberProperty(value, fallbackValue = 0) {
// parseFloat(value) handles most of the cases we're interested in (it treats null, empty string,
// and other non-number values as NaN, where Number just uses 0) but it considers the string
// '123hello' to be a valid number. Therefore we also check if Number(value) is NaN.
return isNaN(parseFloat(/** @type {?} */ (value))) || isNaN(Number(value)) ? fallbackValue : Number(value);
}
/**
* Wraps the provided value in an array, unless the provided value is an array.
* @template T
* @param {?} value
* @return {?}
*/
function coerceArray(value) {
return Array.isArray(value) ? value : [value];
}
/**
* Generated bundle index. Do not edit.
*/
export { coerceBooleanProperty, coerceNumberProperty, coerceArray };
//# sourceMappingURL=coercion.js.map
|
/*********************************************
* app-src/js/ysandboxifc.js
* YeAPF 0.8.52-107 built on 2016-12-01 07:30 (-2 DST)
* Copyright (C) 2004-2016 Esteban Daniel Dortta - dortta@yahoo.com
* 2016-02-25 14:52:24 (-2 DST)
* First Version (C) 2014 - esteban daniel dortta - dortta@yahoo.com
* By security reasons, sometimes you cannot acces
* your restful interface from your webapp, so you need a bridge.
* sandboxIFC (IFC means InterFrameCommunications) lets you
* continue to use restful interface from a sandboxed iframe.
* It counterpart is yifc.js
*********************************************/
//# sourceURL=app-src/js/ysandboxifc.js
_setLogFlagLevel(1,2);
console.log("Sandbox stage2");
var sandboxIFCObj = function () {
that = {};
that.lastStatus=0;
that.Connected = function() {
if (that.lastStatus<=0) {
console.log("ONLINE------------");
that.lastStatus=1;
parent.postMessage({s:'yeapf',a:'online'},'*');
}
};
that.Offline = function () {
if (that.lastStatus>=0) {
console.log("OFFLINE------------");
that.lastStatus=-1;
parent.postMessage({s:'yeapf',a:'offline'},'*');
}
};
that.getConnParams = function() {
parent.postMessage({s:'yeapf', a:'getConnParams'}, '*');
};
that.receiveMessage = function(event) {
_dumpy(1,1,"SANDBOX: receiveMessage() from "+event.origin+" ("+typeof event+")");
if (typeof event == 'object') {
_dumpy(1,2, JSON.stringify(event.data));
var localData=event.data || {s: null, a:null};
var sa=localData.s+'.'+localData.a;
_dumpy(1,1,"SANDBOX: {0} ({1})".format(sa,event.origin));
switch (sa) {
case 'yeapf.connParams':
_dumpy(1,1,"SANDBOX: connParams");
var data=localData.limits.connParams;
if (data === null)
setTimeout(that.getConnParams, 2000);
else {
ycomm.pinger.stopPing();
ycomm.setDataLocation(data.server+'/rest.php');
ycomm.pinger.ping(that.Connected, that.Offline);
}
break;
case 'yeapf.plead':
_dumpy(1,1,"SANDBOX: plead");
var toCrave = localData.context;
ycomm.crave(toCrave.s, toCrave.a, toCrave.limits, 'sandboxIFC.dataPleaded', localData.queueId);
break;
}
} else
_dump("The event is not an object");
};
that.dataPleaded = function (status, error, aData, userMsg, context) {
_dumpy(1,1,"SANDBOX: dataPleaded()");
var msg = {
's': 'yeapf',
'a': 'dataPleaded',
'callbackId': context.callbackId,
'data': aData
};
parent.postMessage(msg, '*');
};
return that;
};
console.log("Sandbox stage3");
var sandboxIFC = {};
window.addEventListener("load", function() {
console.log("Sandbox stage4");
sandboxIFC = sandboxIFCObj();
console.log("Sandbox stage5");
ycomm.pinger.pingInterleave = 10000;
sandboxIFC.getConnParams();
window.addEventListener("message", sandboxIFC.receiveMessage, false);
console.log("Sandbox stage6");
});
|
module.exports = {
name: 'basis.data.dataset.MapFilter',
init: function(){
var MapFilter = basis.require('basis.data.dataset').MapFilter;
var Dataset = basis.require('basis.data').Dataset;
var DataObject = basis.require('basis.data').Object;
},
test: [
{
name: 'fullfil source dataset on set source (bug issue)',
test: function(){
var idx = 1;
function generateDataset() {
return new Dataset({
syncAction: function(data){
this.set([
new DataObject({ data: { views: idx++ } })
]);
}
});
}
var result = new MapFilter({
active: true
});
result.setSource(generateDataset());
assert([1], result.getValues('data.views'));
result.setSource(generateDataset());
assert([2], result.getValues('data.views'));
}
}
]
};
|
/* global describe, it, require */
'use strict';
// MODULES //
var // Expectation library:
chai = require( 'chai' ),
// Module to be tested:
mean = require( './../lib/deepset.js' );
// VARIABLES //
var expect = chai.expect,
assert = chai.assert;
// TESTS //
describe( 'deepset mean', function tests() {
it( 'should export a function', function test() {
expect( mean ).to.be.a( 'function' );
});
it( 'should compute the distribution mean and deep set', function test() {
var data, expected;
data = [
{'x':0.5},
{'x':1},
{'x':2},
{'x':4}
];
data = mean( data, 'x' );
expected = [
{'x':NaN},
{'x':NaN},
{'x':0},
{'x':0}
];
assert.deepEqual( data, expected );
// Custom separator...
data = [
{'x':[9,0.5]},
{'x':[9,1]},
{'x':[9,2]},
{'x':[9,4]}
];
data = mean( data, 'x/1', '/' );
expected = [
{'x':[9,NaN]},
{'x':[9,NaN]},
{'x':[9,0]},
{'x':[9,0]}
];
assert.deepEqual( data, expected, 'custom separator' );
});
it( 'should return an empty array if provided an empty array', function test() {
assert.deepEqual( mean( [], 'x' ), [] );
assert.deepEqual( mean( [], 'x', '/' ), [] );
});
it( 'should handle non-numeric values by setting the element to NaN', function test() {
var data, actual, expected;
data = [
{'x':true},
{'x':null},
{'x':[]},
{'x':{}}
];
actual = mean( data, 'x' );
expected = [
{'x':NaN},
{'x':NaN},
{'x':NaN},
{'x':NaN}
];
assert.deepEqual( data, expected );
});
});
|
var fb = "https://glaring-fire-5349.firebaseio.com";
var TodoCheck = React.createClass({displayName: "TodoCheck",
getInitialState: function() {
this.checked = false;
return {checked: this.checked};
},
componentWillUnmount: function() {
this.ref.off();
},
componentWillMount: function() {
this.ref = new Firebase(fb + "/react_todos/" + this.props.todoKey + "/checked");
// Update the checked state when it changes.
this.ref.on("value", function(snap) {
if (snap.val() !== null) {
this.checked = snap.val();
this.setState({
checked: this.checked
});
this.props.todo.setDone(this.checked);
} else {
this.ref.set(false);
this.props.todo.setDone(false);
}
}.bind(this));
},
toggleCheck: function(event) {
this.ref.set(!this.checked);
event.preventDefault();
},
render: function() {
return (
React.createElement("a", {
onClick: this.toggleCheck,
href: "#",
className: "pull-left todo-check"},
React.createElement("span", {
className: "todo-check-mark glyphicon glyphicon-ok",
"aria-hidden": "true"}
)
)
);
},
});
var TodoText = React.createClass({displayName: "TodoText",
componentWillUnmount: function() {
this.ref.off();
$("#" + this.props.todoKey + "-text").off('blur');
},
setText: function(text) {
this.text = text;
},
componentWillMount: function() {
this.ref = new Firebase(fb + "/react_todos/" + this.props.todoKey + "/text");
// TODO: why is this necessary? hitting the on value handler twice should
// do this.
//$("#" + this.props.todoKey + "-text").text("");
// Update the todo's text when it changes.
this.setText("");
this.ref.on("value", function(snap) {
if (snap.val() !== null) {
$("#" + this.props.todoKey + "-text").text(snap.val());
this.setText(snap.val());
} else {
this.ref.set("");
}
}.bind(this));
},
componentDidMount: function() {
$("#" + this.props.todoKey + "-text").text(this.text);
$("#" + this.props.todoKey + "-text").blur(this.onTextBlur);
},
componentWillReceiveProps: function(nextProps) {
console.log("componentWillReceiveProps");
console.log(nextProps);
},
onTextBlur: function(event) {
this.ref.set($(event.target).text());
},
render: function() {
return (
React.createElement("span", {
id: this.props.todoKey + "-text",
contentEditable: "plaintext-only",
"data-ph": "Todo",
className: "todo-text"}
)
);
},
});
var TodoDelete = React.createClass({displayName: "TodoDelete",
getInitialState: function() {
return {};
},
componentWillUnmount: function() {
this.ref.off();
},
componentWillMount: function() {
this.ref = new Firebase(fb + "/react_todos/" + this.props.todoKey + "/deleted");
},
onClick: function() {
this.ref.set(true);
},
render: function() {
if (this.props.isLast) {
return null;
}
return (
React.createElement("button", {
onClick: this.onClick, type: "button",
className: "close", "aria-label": "Close"},
React.createElement("span", {
"aria-hidden": "true",
dangerouslySetInnerHTML: {__html: '×'}})
)
);
},
});
var Todo = React.createClass({displayName: "Todo",
getInitialState: function() {
return {};
},
setDone: function(done) {
this.setState({
done: done
});
},
render: function() {
var doneClass = this.state.done ? "todo-done" : "todo-not-done";
return (
React.createElement("li", {
id: this.props.todoKey,
className: "list-group-item todo " + doneClass},
React.createElement(TodoCheck, {todo: this, todoKey: this.props.todoKey}),
React.createElement(TodoText, {todo: this, todoKey: this.props.todoKey}),
React.createElement(TodoDelete, {isLast: false, todoKey: this.props.todoKey})
)
);
}
});
var TodoList = React.createClass({displayName: "TodoList",
getInitialState: function() {
this.todos = [];
return {todos: this.todos};
},
componentWillMount: function() {
this.ref = new Firebase("https://glaring-fire-5349.firebaseio.com/react_todos/");
// Add an empty todo if none currently exist.
this.ref.on("value", function(snap) {
if (snap.val() === null) {
this.ref.push({
text: "",
});
return;
}
// Add a new todo if no undeleted ones exist.
var returnedTrue = snap.forEach(function(data) {
if (!data.val().deleted) {
return true;
}
});
if (!returnedTrue) {
this.ref.push({
text: "",
});
return;
}
}.bind(this));
// Add an added child to this.todos.
this.ref.on("child_added", function(childSnap) {
this.todos.push({
k: childSnap.key(),
val: childSnap.val()
});
this.replaceState({
todos: this.todos
});
}.bind(this));
this.ref.on("child_removed", function(childSnap) {
var key = childSnap.key();
var i;
for (i = 0; i < this.todos.length; i++) {
if (this.todos[i].k == key) {
break;
}
}
this.todos.splice(i, 1);
this.replaceState({
todos: this.todos,
});
}.bind(this));
this.ref.on("child_changed", function(childSnap) {
var key = childSnap.key();
for (var i = 0; i < this.todos.length; i++) {
if (this.todos[i].k == key) {
this.todos[i].val = childSnap.val();
this.replaceState({
todos: this.todos,
});
break;
}
}
}.bind(this));
},
componentWillUnmount: function() {
this.ref.off();
},
render: function() {
var todos = this.state.todos.map(function (todo) {
if (todo.val.deleted) {
return null;
}
return (
React.createElement(Todo, {todoKey: todo.k})
);
}).filter(function(todo) { return todo !== null; });
return (
React.createElement("div", null,
React.createElement("h1", {id: "list_title"}, this.props.title),
React.createElement("ul", {id: "todo-list", className: "list-group"},
todos
)
)
);
}
});
var ListPage = React.createClass({displayName: "ListPage",
render: function() {
return (
React.createElement("div", null,
React.createElement("div", {id: "list_page"},
React.createElement("a", {
onClick: this.props.app.navOnClick({page: "LISTS"}),
href: "/#/lists",
id: "lists_link",
className: "btn btn-primary"},
"Back to Lists"
)
),
React.createElement("div", {className: "page-header"},
this.props.children
)
)
);
}
});
var Nav = React.createClass({displayName: "Nav",
render: function() {
return (
React.createElement("nav", {className: "navbar navbar-default navbar-static-top"},
React.createElement("div", {className: "container"},
React.createElement("div", {className: "navbar-header"},
React.createElement("a", {onClick: this.props.app.navOnClick({page: "LISTS"}), className: "navbar-brand", href: "/#/lists"}, "Firebase Todo")
),
React.createElement("ul", {className: "nav navbar-nav"},
React.createElement("li", null, React.createElement("a", {onClick: this.props.app.navOnClick({page: "LISTS"}), href: "/#/lists"}, "Lists"))
)
)
)
);
},
});
var App = React.createClass({displayName: "App",
getInitialState: function() {
var state = this.getState();
this.setHistory(state, true);
return this.getState();
},
setHistory: function(state, replace) {
// Don't bother pushing a history entry if the latest state is
// the same.
if (_.isEqual(state, this.state)) {
return;
}
var histFunc = replace ?
history.replaceState.bind(history) :
history.pushState.bind(history);
if (state.page === "LIST") {
histFunc(state, "", "#/list/" + state.todoListKey);
} else if (state.page === "LISTS") {
histFunc(state, "", "#/lists");
} else {
console.log("Unknown page: " + state.page);
}
},
getState: function() {
var url = document.location.toString();
if (url.match(/#/)) {
var path = url.split("#")[1];
var res = path.match(/\/list\/([^\/]*)$/);
if (res) {
return {
page: "LIST",
todoListKey: res[1],
};
}
res = path.match(/lists$/);
if (res) {
return {
page: "LISTS"
}
}
}
return {
page: "LISTS"
}
},
componentWillMount: function() {
// Register history listeners.
var app = this;
window.onpopstate = function(event) {
app.replaceState(event.state);
};
},
navOnClick: function(state) {
return function(event) {
this.setHistory(state, false);
this.replaceState(state);
event.preventDefault();
}.bind(this);
},
getPage: function() {
if (this.state.page === "LIST") {
return (
React.createElement(ListPage, {app: this},
React.createElement(TodoList, {todoListKey: this.state.todoListKey})
)
);
} else if (this.state.page === "LISTS") {
return (
React.createElement("a", {onClick: this.navOnClick({page: "LIST", todoListKey: "-JjcFYgp1LyD5oDNNSe2"}), href: "/#/list/-JjcFYgp1LyD5oDNNSe2"}, "hi")
);
} else {
console.log("Unknown page: " + this.state.page);
}
},
render: function() {
return (
React.createElement("div", null,
React.createElement(Nav, {app: this}),
React.createElement("div", {className: "container", role: "main"},
this.getPage()
)
)
);
}
});
React.render(
React.createElement(App, null),
document.getElementById('content')
); |
'use strict';
const path = require('path');
const find = require('findit');
const Promise = require('promise');
const fs = require('fs-extra');
const mkdirp = require('mkdirp');
const extend = require('extend');
const jsonFormat = require('json-format');
const jsonConfig = {
type: 'space',
size: 2
};
const atomicLab = {};
const getDirName = path.dirname;
const processPath = process.cwd();
const defaultExts = 'html,ejs,jade,haml,pug,css,scss,less,txt,text';
const getFileInfo = dir => new Promise((resolve) => {
const finder = find(dir);
const files = [];
finder.on('file', (filePath) => {
files.push(filePath);
});
finder.on('end', () => {
resolve(files);
});
});
const getDoc = (source, parser) => {
let doc = source.match(parser.body);
if (!doc) {
return '';
}
doc = doc[0];
return doc
.replace(parser.start, '')
.replace(parser.end, '');
};
const getMark = (mark, source) => {
const pattern = `@${mark}(?:[\t ]+)(.*)`;
const regex = new RegExp(pattern, 'i');
const match = source.match(regex);
if (match && match[1]) {
return match[1];
}
return '';
};
const makeAtomicArray = (files, parser, exts) => {
const components = [];
let itemId = 0;
for (let i = 0, n = files.length; i < n; i += 1) {
const file = files[i];
const extName = path.extname(file).replace('.', '');
const pathName = file.replace(processPath, '');
let flag = false;
exts.forEach((ext) => {
if (extName === ext) {
flag = true;
}
});
if (!flag) {
continue;
}
const html = fs.readFileSync(file, 'utf8');
let css;
let js;
const doc = getDoc(html, parser);
if (!doc) {
continue;
}
const name = getMark('name', doc);
if (!name) {
continue;
}
const category = getMark('category', doc) || 'atom';
const cssMark = getMark('css', doc);
if (cssMark) {
const cssPath = path.resolve(file, '../', cssMark);
try {
css = fs.readFileSync(cssPath, 'utf8');
} catch (err) {
console.log(err);
}
}
const jsMark = getMark('js', doc);
if (jsMark) {
const jsPath = path.resolve(file, '../', jsMark);
try {
js = fs.readFileSync(jsPath, 'utf8');
} catch (err) {
console.log(err);
}
}
itemId += 1;
components.push({ category, name, html, css, js, itemId, path: pathName });
}
return components;
};
const writeFile = function (filePath, contents, cb) {
mkdirp(getDirName(filePath), (err) => {
if (err) {
return cb(err);
}
return fs.writeFile(filePath, contents, cb);
});
};
const copyPromise = (src, dist) => {
if (fs.pathExistsSync(dist)) {
return Promise.resolve();
}
return new Promise((resolve) => {
fs.copy(src, dist, () => {
resolve();
});
});
};
const overwritePromise = (src, dist) => new Promise((resolve) => {
fs.copy(src, dist, () => {
resolve();
});
});
atomicLab.build = ({ src, dist, exts = defaultExts, parser }) => {
const prs = extend({
start: /<!--@doc/g,
end: /-->/g,
body: /<!--@doc(([\n\r\t]|.)*?)-->/g
}, parser);
return atomicLab.init({ src, dist }).then(() => {
getFileInfo(path.resolve(processPath, src))
.then((files) => {
const components = makeAtomicArray(files, prs, exts.split(','));
const json = JSON.stringify({ components });
const pjson = new Promise((resolve) => {
writeFile(path.resolve(processPath, dist, './components.json'), json, (err) => {
if (err) {
console.log(err);
}
resolve();
});
});
return pjson;
});
});
};
atomicLab.init = (opt) => {
const dist = opt.dist;
const src = opt.src;
const promiseArray = [
copyPromise(`${__dirname}/index.html`, path.resolve(processPath, dist, './index.html')),
copyPromise(`${__dirname}/config.json`, path.resolve(processPath, dist, './config.json')),
copyPromise(`${__dirname}/bundle.js`, path.resolve(processPath, dist, './bundle.js')),
copyPromise(`${__dirname}/components.json`, path.resolve(processPath, dist, './components.json')),
copyPromise(`${__dirname}/components`, path.resolve(processPath, src))
];
return Promise.all(promiseArray);
};
atomicLab.update = (opt) => {
const dist = opt.dist;
const newConfig = require(`${__dirname}/config.json`);
const oldConfig = require(path.resolve(processPath, dist, './config.json'));
const config = extend({}, newConfig, oldConfig);
const str = jsonFormat(config, jsonConfig);
const writePromise = new Promise((resolve, reject) => {
writeFile(path.resolve(processPath, dist, './config.json'), str, (err) => {
if (err) {
reject(err);
}
resolve();
});
});
const promiseArray = [
overwritePromise(`${__dirname}/bundle.js`, path.resolve(processPath, dist, './bundle.js')),
overwritePromise(`${__dirname}/index.html`, path.resolve(processPath, dist, './index.html')),
writePromise
];
return Promise.all(promiseArray);
};
module.exports = atomicLab;
|
var base = require('./karma.base.conf');
module.exports = function(config) {
config.set(Object.assign(base, {
reporters: ['mocha']
}));
};
|
'use strict';
const venue = {
name: 'Anderson Mill Pub',
address: '10401 Anderson Mill Rd # 121',
city: 'Austin',
state: 'TX',
zipCode: 78750,
latitude: 30.446338,
longitude: -97.806843
};
module.exports = venue;
|
import * as Util from '../../../src/util/index'
import { clearFixture, getFixture } from '../../helpers/fixture'
describe('Util', () => {
let fixtureEl
beforeAll(() => {
fixtureEl = getFixture()
})
afterEach(() => {
clearFixture()
})
describe('getUID', () => {
it('should generate uid', () => {
const uid = Util.getUID('bs')
const uid2 = Util.getUID('bs')
expect(uid).not.toEqual(uid2)
})
})
describe('getSelectorFromElement', () => {
it('should get selector from data-bs-target', () => {
fixtureEl.innerHTML = [
'<div id="test" data-bs-target=".target"></div>',
'<div class="target"></div>'
].join('')
const testEl = fixtureEl.querySelector('#test')
expect(Util.getSelectorFromElement(testEl)).toEqual('.target')
})
it('should get selector from href if no data-bs-target set', () => {
fixtureEl.innerHTML = [
'<a id="test" href=".target"></a>',
'<div class="target"></div>'
].join('')
const testEl = fixtureEl.querySelector('#test')
expect(Util.getSelectorFromElement(testEl)).toEqual('.target')
})
it('should get selector from href if data-bs-target equal to #', () => {
fixtureEl.innerHTML = [
'<a id="test" data-bs-target="#" href=".target"></a>',
'<div class="target"></div>'
].join('')
const testEl = fixtureEl.querySelector('#test')
expect(Util.getSelectorFromElement(testEl)).toEqual('.target')
})
it('should return null if a selector from a href is a url without an anchor', () => {
fixtureEl.innerHTML = [
'<a id="test" data-bs-target="#" href="foo/bar.html"></a>',
'<div class="target"></div>'
].join('')
const testEl = fixtureEl.querySelector('#test')
expect(Util.getSelectorFromElement(testEl)).toBeNull()
})
it('should return the anchor if a selector from a href is a url', () => {
fixtureEl.innerHTML = [
'<a id="test" data-bs-target="#" href="foo/bar.html#target"></a>',
'<div id="target"></div>'
].join('')
const testEl = fixtureEl.querySelector('#test')
expect(Util.getSelectorFromElement(testEl)).toEqual('#target')
})
it('should return null if selector not found', () => {
fixtureEl.innerHTML = '<a id="test" href=".target"></a>'
const testEl = fixtureEl.querySelector('#test')
expect(Util.getSelectorFromElement(testEl)).toBeNull()
})
it('should return null if no selector', () => {
fixtureEl.innerHTML = '<div></div>'
const testEl = fixtureEl.querySelector('div')
expect(Util.getSelectorFromElement(testEl)).toBeNull()
})
})
describe('getElementFromSelector', () => {
it('should get element from data-bs-target', () => {
fixtureEl.innerHTML = [
'<div id="test" data-bs-target=".target"></div>',
'<div class="target"></div>'
].join('')
const testEl = fixtureEl.querySelector('#test')
expect(Util.getElementFromSelector(testEl)).toEqual(fixtureEl.querySelector('.target'))
})
it('should get element from href if no data-bs-target set', () => {
fixtureEl.innerHTML = [
'<a id="test" href=".target"></a>',
'<div class="target"></div>'
].join('')
const testEl = fixtureEl.querySelector('#test')
expect(Util.getElementFromSelector(testEl)).toEqual(fixtureEl.querySelector('.target'))
})
it('should return null if element not found', () => {
fixtureEl.innerHTML = '<a id="test" href=".target"></a>'
const testEl = fixtureEl.querySelector('#test')
expect(Util.getElementFromSelector(testEl)).toBeNull()
})
it('should return null if no selector', () => {
fixtureEl.innerHTML = '<div></div>'
const testEl = fixtureEl.querySelector('div')
expect(Util.getElementFromSelector(testEl)).toBeNull()
})
})
describe('getTransitionDurationFromElement', () => {
it('should get transition from element', () => {
fixtureEl.innerHTML = '<div style="transition: all 300ms ease-out;"></div>'
expect(Util.getTransitionDurationFromElement(fixtureEl.querySelector('div'))).toEqual(300)
})
it('should return 0 if the element is undefined or null', () => {
expect(Util.getTransitionDurationFromElement(null)).toEqual(0)
expect(Util.getTransitionDurationFromElement(undefined)).toEqual(0)
})
it('should return 0 if the element do not possess transition', () => {
fixtureEl.innerHTML = '<div></div>'
expect(Util.getTransitionDurationFromElement(fixtureEl.querySelector('div'))).toEqual(0)
})
})
describe('triggerTransitionEnd', () => {
it('should trigger transitionend event', done => {
fixtureEl.innerHTML = '<div></div>'
const el = fixtureEl.querySelector('div')
const spy = spyOn(el, 'dispatchEvent').and.callThrough()
el.addEventListener('transitionend', () => {
expect(spy).toHaveBeenCalled()
done()
})
Util.triggerTransitionEnd(el)
})
})
describe('isElement', () => {
it('should detect if the parameter is an element or not and return Boolean', () => {
fixtureEl.innerHTML = [
'<div id="foo" class="test"></div>',
'<div id="bar" class="test"></div>'
].join('')
const el = fixtureEl.querySelector('#foo')
expect(Util.isElement(el)).toBeTrue()
expect(Util.isElement({})).toBeFalse()
expect(Util.isElement(fixtureEl.querySelectorAll('.test'))).toBeFalse()
})
it('should detect jQuery element', () => {
fixtureEl.innerHTML = '<div></div>'
const el = fixtureEl.querySelector('div')
const fakejQuery = {
0: el,
jquery: 'foo'
}
expect(Util.isElement(fakejQuery)).toBeTrue()
})
})
describe('getElement', () => {
it('should try to parse element', () => {
fixtureEl.innerHTML = [
'<div id="foo" class="test"></div>',
'<div id="bar" class="test"></div>'
].join('')
const el = fixtureEl.querySelector('div')
expect(Util.getElement(el)).toEqual(el)
expect(Util.getElement('#foo')).toEqual(el)
expect(Util.getElement('#fail')).toBeNull()
expect(Util.getElement({})).toBeNull()
expect(Util.getElement([])).toBeNull()
expect(Util.getElement()).toBeNull()
expect(Util.getElement(null)).toBeNull()
expect(Util.getElement(fixtureEl.querySelectorAll('.test'))).toBeNull()
const fakejQueryObject = {
0: el,
jquery: 'foo'
}
expect(Util.getElement(fakejQueryObject)).toEqual(el)
})
})
describe('isVisible', () => {
it('should return false if the element is not defined', () => {
expect(Util.isVisible(null)).toBeFalse()
expect(Util.isVisible(undefined)).toBeFalse()
})
it('should return false if the element provided is not a dom element', () => {
expect(Util.isVisible({})).toBeFalse()
})
it('should return false if the element is not visible with display none', () => {
fixtureEl.innerHTML = '<div style="display: none;"></div>'
const div = fixtureEl.querySelector('div')
expect(Util.isVisible(div)).toBeFalse()
})
it('should return false if the element is not visible with visibility hidden', () => {
fixtureEl.innerHTML = '<div style="visibility: hidden;"></div>'
const div = fixtureEl.querySelector('div')
expect(Util.isVisible(div)).toBeFalse()
})
it('should return false if an ancestor element is display none', () => {
fixtureEl.innerHTML = [
'<div style="display: none;">',
' <div>',
' <div>',
' <div class="content"></div>',
' </div>',
' </div>',
'</div>'
].join('')
const div = fixtureEl.querySelector('.content')
expect(Util.isVisible(div)).toBeFalse()
})
it('should return false if an ancestor element is visibility hidden', () => {
fixtureEl.innerHTML = [
'<div style="visibility: hidden;">',
' <div>',
' <div>',
' <div class="content"></div>',
' </div>',
' </div>',
'</div>'
].join('')
const div = fixtureEl.querySelector('.content')
expect(Util.isVisible(div)).toBeFalse()
})
it('should return true if an ancestor element is visibility hidden, but reverted', () => {
fixtureEl.innerHTML = [
'<div style="visibility: hidden;">',
' <div style="visibility: visible;">',
' <div>',
' <div class="content"></div>',
' </div>',
' </div>',
'</div>'
].join('')
const div = fixtureEl.querySelector('.content')
expect(Util.isVisible(div)).toBeTrue()
})
it('should return true if the element is visible', () => {
fixtureEl.innerHTML = [
'<div>',
' <div id="element"></div>',
'</div>'
].join('')
const div = fixtureEl.querySelector('#element')
expect(Util.isVisible(div)).toBeTrue()
})
it('should return false if the element is hidden, but not via display or visibility', () => {
fixtureEl.innerHTML = [
'<details>',
' <div id="element"></div>',
'</details>'
].join('')
const div = fixtureEl.querySelector('#element')
expect(Util.isVisible(div)).toBeFalse()
})
})
describe('isDisabled', () => {
it('should return true if the element is not defined', () => {
expect(Util.isDisabled(null)).toBeTrue()
expect(Util.isDisabled(undefined)).toBeTrue()
expect(Util.isDisabled()).toBeTrue()
})
it('should return true if the element provided is not a dom element', () => {
expect(Util.isDisabled({})).toBeTrue()
expect(Util.isDisabled('test')).toBeTrue()
})
it('should return true if the element has disabled attribute', () => {
fixtureEl.innerHTML = [
'<div>',
' <div id="element" disabled="disabled"></div>',
' <div id="element1" disabled="true"></div>',
' <div id="element2" disabled></div>',
'</div>'
].join('')
const div = fixtureEl.querySelector('#element')
const div1 = fixtureEl.querySelector('#element1')
const div2 = fixtureEl.querySelector('#element2')
expect(Util.isDisabled(div)).toBeTrue()
expect(Util.isDisabled(div1)).toBeTrue()
expect(Util.isDisabled(div2)).toBeTrue()
})
it('should return false if the element has disabled attribute with "false" value, or doesn\'t have attribute', () => {
fixtureEl.innerHTML = [
'<div>',
' <div id="element" disabled="false"></div>',
' <div id="element1" ></div>',
'</div>'
].join('')
const div = fixtureEl.querySelector('#element')
const div1 = fixtureEl.querySelector('#element1')
expect(Util.isDisabled(div)).toBeFalse()
expect(Util.isDisabled(div1)).toBeFalse()
})
it('should return false if the element is not disabled ', () => {
fixtureEl.innerHTML = [
'<div>',
' <button id="button"></button>',
' <select id="select"></select>',
' <select id="input"></select>',
'</div>'
].join('')
const el = selector => fixtureEl.querySelector(selector)
expect(Util.isDisabled(el('#button'))).toBeFalse()
expect(Util.isDisabled(el('#select'))).toBeFalse()
expect(Util.isDisabled(el('#input'))).toBeFalse()
})
it('should return true if the element has disabled attribute', () => {
fixtureEl.innerHTML = [
'<div>',
' <input id="input" disabled="disabled"/>',
' <input id="input1" disabled="disabled"/>',
' <button id="button" disabled="true"></button>',
' <button id="button1" disabled="disabled"></button>',
' <button id="button2" disabled></button>',
' <select id="select" disabled></select>',
' <select id="input" disabled></select>',
'</div>'
].join('')
const el = selector => fixtureEl.querySelector(selector)
expect(Util.isDisabled(el('#input'))).toBeTrue()
expect(Util.isDisabled(el('#input1'))).toBeTrue()
expect(Util.isDisabled(el('#button'))).toBeTrue()
expect(Util.isDisabled(el('#button1'))).toBeTrue()
expect(Util.isDisabled(el('#button2'))).toBeTrue()
expect(Util.isDisabled(el('#input'))).toBeTrue()
})
it('should return true if the element has class "disabled"', () => {
fixtureEl.innerHTML = [
'<div>',
' <div id="element" class="disabled"></div>',
'</div>'
].join('')
const div = fixtureEl.querySelector('#element')
expect(Util.isDisabled(div)).toBeTrue()
})
it('should return true if the element has class "disabled" but disabled attribute is false', () => {
fixtureEl.innerHTML = [
'<div>',
' <input id="input" class="disabled" disabled="false"/>',
'</div>'
].join('')
const div = fixtureEl.querySelector('#input')
expect(Util.isDisabled(div)).toBeTrue()
})
})
describe('findShadowRoot', () => {
it('should return null if shadow dom is not available', () => {
// Only for newer browsers
if (!document.documentElement.attachShadow) {
expect().nothing()
return
}
fixtureEl.innerHTML = '<div></div>'
const div = fixtureEl.querySelector('div')
spyOn(document.documentElement, 'attachShadow').and.returnValue(null)
expect(Util.findShadowRoot(div)).toBeNull()
})
it('should return null when we do not find a shadow root', () => {
// Only for newer browsers
if (!document.documentElement.attachShadow) {
expect().nothing()
return
}
spyOn(document, 'getRootNode').and.returnValue(undefined)
expect(Util.findShadowRoot(document)).toBeNull()
})
it('should return the shadow root when found', () => {
// Only for newer browsers
if (!document.documentElement.attachShadow) {
expect().nothing()
return
}
fixtureEl.innerHTML = '<div></div>'
const div = fixtureEl.querySelector('div')
const shadowRoot = div.attachShadow({
mode: 'open'
})
expect(Util.findShadowRoot(shadowRoot)).toEqual(shadowRoot)
shadowRoot.innerHTML = '<button>Shadow Button</button>'
expect(Util.findShadowRoot(shadowRoot.firstChild)).toEqual(shadowRoot)
})
})
describe('noop', () => {
it('should be a function', () => {
expect(Util.noop).toEqual(jasmine.any(Function))
})
})
describe('reflow', () => {
it('should return element offset height to force the reflow', () => {
fixtureEl.innerHTML = '<div></div>'
const div = fixtureEl.querySelector('div')
const spy = spyOnProperty(div, 'offsetHeight')
Util.reflow(div)
expect(spy).toHaveBeenCalled()
})
})
describe('getjQuery', () => {
const fakejQuery = { trigger() {} }
beforeEach(() => {
Object.defineProperty(window, 'jQuery', {
value: fakejQuery,
writable: true
})
})
afterEach(() => {
window.jQuery = undefined
})
it('should return jQuery object when present', () => {
expect(Util.getjQuery()).toEqual(fakejQuery)
})
it('should not return jQuery object when present if data-bs-no-jquery', () => {
document.body.setAttribute('data-bs-no-jquery', '')
expect(window.jQuery).toEqual(fakejQuery)
expect(Util.getjQuery()).toBeNull()
document.body.removeAttribute('data-bs-no-jquery')
})
it('should not return jQuery if not present', () => {
window.jQuery = undefined
expect(Util.getjQuery()).toBeNull()
})
})
describe('onDOMContentLoaded', () => {
it('should execute callbacks when DOMContentLoaded is fired and should not add more than one listener', () => {
const spy = jasmine.createSpy()
const spy2 = jasmine.createSpy()
spyOn(document, 'addEventListener').and.callThrough()
spyOnProperty(document, 'readyState').and.returnValue('loading')
Util.onDOMContentLoaded(spy)
Util.onDOMContentLoaded(spy2)
document.dispatchEvent(new Event('DOMContentLoaded', {
bubbles: true,
cancelable: true
}))
expect(spy).toHaveBeenCalled()
expect(spy2).toHaveBeenCalled()
expect(document.addEventListener).toHaveBeenCalledTimes(1)
})
it('should execute callback if readyState is not "loading"', () => {
const spy = jasmine.createSpy()
Util.onDOMContentLoaded(spy)
expect(spy).toHaveBeenCalled()
})
})
describe('defineJQueryPlugin', () => {
const fakejQuery = { fn: {} }
beforeEach(() => {
Object.defineProperty(window, 'jQuery', {
value: fakejQuery,
writable: true
})
})
afterEach(() => {
window.jQuery = undefined
})
it('should define a plugin on the jQuery instance', () => {
const pluginMock = function () {}
pluginMock.NAME = 'test'
pluginMock.jQueryInterface = function () {}
Util.defineJQueryPlugin(pluginMock)
expect(fakejQuery.fn.test).toEqual(pluginMock.jQueryInterface)
expect(fakejQuery.fn.test.Constructor).toEqual(pluginMock)
expect(fakejQuery.fn.test.noConflict).toEqual(jasmine.any(Function))
})
})
describe('execute', () => {
it('should execute if arg is function', () => {
const spy = jasmine.createSpy('spy')
Util.execute(spy)
expect(spy).toHaveBeenCalled()
})
})
describe('executeAfterTransition', () => {
it('should immediately execute a function when waitForTransition parameter is false', () => {
const el = document.createElement('div')
const callbackSpy = jasmine.createSpy('callback spy')
const eventListenerSpy = spyOn(el, 'addEventListener')
Util.executeAfterTransition(callbackSpy, el, false)
expect(callbackSpy).toHaveBeenCalled()
expect(eventListenerSpy).not.toHaveBeenCalled()
})
it('should execute a function when a transitionend event is dispatched', () => {
const el = document.createElement('div')
const callbackSpy = jasmine.createSpy('callback spy')
spyOn(window, 'getComputedStyle').and.returnValue({
transitionDuration: '0.05s',
transitionDelay: '0s'
})
Util.executeAfterTransition(callbackSpy, el)
el.dispatchEvent(new TransitionEvent('transitionend'))
expect(callbackSpy).toHaveBeenCalled()
})
it('should execute a function after a computed CSS transition duration and there was no transitionend event dispatched', done => {
const el = document.createElement('div')
const callbackSpy = jasmine.createSpy('callback spy')
spyOn(window, 'getComputedStyle').and.returnValue({
transitionDuration: '0.05s',
transitionDelay: '0s'
})
Util.executeAfterTransition(callbackSpy, el)
setTimeout(() => {
expect(callbackSpy).toHaveBeenCalled()
done()
}, 70)
})
it('should not execute a function a second time after a computed CSS transition duration and if a transitionend event has already been dispatched', done => {
const el = document.createElement('div')
const callbackSpy = jasmine.createSpy('callback spy')
spyOn(window, 'getComputedStyle').and.returnValue({
transitionDuration: '0.05s',
transitionDelay: '0s'
})
Util.executeAfterTransition(callbackSpy, el)
setTimeout(() => {
el.dispatchEvent(new TransitionEvent('transitionend'))
}, 50)
setTimeout(() => {
expect(callbackSpy).toHaveBeenCalledTimes(1)
done()
}, 70)
})
it('should not trigger a transitionend event if another transitionend event had already happened', done => {
const el = document.createElement('div')
spyOn(window, 'getComputedStyle').and.returnValue({
transitionDuration: '0.05s',
transitionDelay: '0s'
})
Util.executeAfterTransition(() => {}, el)
// simulate a event dispatched by the browser
el.dispatchEvent(new TransitionEvent('transitionend'))
const dispatchSpy = spyOn(el, 'dispatchEvent').and.callThrough()
setTimeout(() => {
// setTimeout should not have triggered another transitionend event.
expect(dispatchSpy).not.toHaveBeenCalled()
done()
}, 70)
})
it('should ignore transitionend events from nested elements', done => {
fixtureEl.innerHTML = [
'<div class="outer">',
' <div class="nested"></div>',
'</div>'
].join('')
const outer = fixtureEl.querySelector('.outer')
const nested = fixtureEl.querySelector('.nested')
const callbackSpy = jasmine.createSpy('callback spy')
spyOn(window, 'getComputedStyle').and.returnValue({
transitionDuration: '0.05s',
transitionDelay: '0s'
})
Util.executeAfterTransition(callbackSpy, outer)
nested.dispatchEvent(new TransitionEvent('transitionend', {
bubbles: true
}))
setTimeout(() => {
expect(callbackSpy).not.toHaveBeenCalled()
}, 20)
setTimeout(() => {
expect(callbackSpy).toHaveBeenCalled()
done()
}, 70)
})
})
describe('getNextActiveElement', () => {
it('should return first element if active not exists or not given and shouldGetNext is either true, or false with cycling being disabled', () => {
const array = ['a', 'b', 'c', 'd']
expect(Util.getNextActiveElement(array, '', true, true)).toEqual('a')
expect(Util.getNextActiveElement(array, 'g', true, true)).toEqual('a')
expect(Util.getNextActiveElement(array, '', true, false)).toEqual('a')
expect(Util.getNextActiveElement(array, 'g', true, false)).toEqual('a')
expect(Util.getNextActiveElement(array, '', false, false)).toEqual('a')
expect(Util.getNextActiveElement(array, 'g', false, false)).toEqual('a')
})
it('should return last element if active not exists or not given and shouldGetNext is false but cycling is enabled', () => {
const array = ['a', 'b', 'c', 'd']
expect(Util.getNextActiveElement(array, '', false, true)).toEqual('d')
expect(Util.getNextActiveElement(array, 'g', false, true)).toEqual('d')
})
it('should return next element or same if is last', () => {
const array = ['a', 'b', 'c', 'd']
expect(Util.getNextActiveElement(array, 'a', true, true)).toEqual('b')
expect(Util.getNextActiveElement(array, 'b', true, true)).toEqual('c')
expect(Util.getNextActiveElement(array, 'd', true, false)).toEqual('d')
})
it('should return next element or first, if is last and "isCycleAllowed = true"', () => {
const array = ['a', 'b', 'c', 'd']
expect(Util.getNextActiveElement(array, 'c', true, true)).toEqual('d')
expect(Util.getNextActiveElement(array, 'd', true, true)).toEqual('a')
})
it('should return previous element or same if is first', () => {
const array = ['a', 'b', 'c', 'd']
expect(Util.getNextActiveElement(array, 'b', false, true)).toEqual('a')
expect(Util.getNextActiveElement(array, 'd', false, true)).toEqual('c')
expect(Util.getNextActiveElement(array, 'a', false, false)).toEqual('a')
})
it('should return next element or first, if is last and "isCycleAllowed = true"', () => {
const array = ['a', 'b', 'c', 'd']
expect(Util.getNextActiveElement(array, 'd', false, true)).toEqual('c')
expect(Util.getNextActiveElement(array, 'a', false, true)).toEqual('d')
})
})
})
|
jumplink.cms.controller('LayoutController', function($rootScope, $log, authenticated) {
$rootScope.authenticated = (authenticated === true);
$log.debug("[LayoutController] authenticated", $rootScope.authenticated, authenticated);
}); |
// LICENSE : MIT
"use strict";
/**
* @param {RuleContext} context
*/
module.exports = function(context, options) {
var exports = {};
exports[context.Syntax.Str] = function(node) {
var text = context.getSource(node);
context.report(node, new context.RuleError("found error message"));
};
return exports;
};
|
'use strict';
var path = require('path');
// var checker = require('ember-cli-version-checker');
// var mergeTrees = require('broccoli-merge-trees');
// var pickFiles = require('broccoli-static-compiler');
module.exports = {
name : 'ember-cli-easy-table'
};
|
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var UserPasswordV1_1 = require("./UserPasswordV1");
exports.UserPasswordV1 = UserPasswordV1_1.UserPasswordV1;
var UserPasswordInfoV1_1 = require("./UserPasswordInfoV1");
exports.UserPasswordInfoV1 = UserPasswordInfoV1_1.UserPasswordInfoV1;
var PasswordActivityTypeV1_1 = require("./PasswordActivityTypeV1");
exports.PasswordActivityTypeV1 = PasswordActivityTypeV1_1.PasswordActivityTypeV1;
//# sourceMappingURL=index.js.map |
export default function(canvas, callback) {
let image = new Image();
image.onload = callback;
image.src = canvas.node().toDataURL();
return image;
}
|
'use strict';
!function($) {
// Default set of media queries
const defaultQueries = {
'default' : 'only screen',
landscape : 'only screen and (orientation: landscape)',
portrait : 'only screen and (orientation: portrait)',
retina : 'only screen and (-webkit-min-device-pixel-ratio: 2),' +
'only screen and (min--moz-device-pixel-ratio: 2),' +
'only screen and (-o-min-device-pixel-ratio: 2/1),' +
'only screen and (min-device-pixel-ratio: 2),' +
'only screen and (min-resolution: 192dpi),' +
'only screen and (min-resolution: 2dppx)'
};
var MediaQuery = {
queries: [],
current: '',
/**
* Initializes the media query helper, by extracting the breakpoint list from the CSS and activating the breakpoint watcher.
* @function
* @private
*/
_init() {
var self = this;
var extractedStyles = $('.foundation-mq').css('font-family');
var namedQueries;
namedQueries = parseStyleToObject(extractedStyles);
for (var key in namedQueries) {
if(namedQueries.hasOwnProperty(key)) {
self.queries.push({
name: key,
value: `only screen and (min-width: ${namedQueries[key]})`
});
}
}
this.current = this._getCurrentSize();
this._watcher();
},
/**
* Checks if the screen is at least as wide as a breakpoint.
* @function
* @param {String} size - Name of the breakpoint to check.
* @returns {Boolean} `true` if the breakpoint matches, `false` if it's smaller.
*/
atLeast(size) {
var query = this.get(size);
if (query) {
return window.matchMedia(query).matches;
}
return false;
},
/**
* Gets the media query of a breakpoint.
* @function
* @param {String} size - Name of the breakpoint to get.
* @returns {String|null} - The media query of the breakpoint, or `null` if the breakpoint doesn't exist.
*/
get(size) {
for (var i in this.queries) {
if(this.queries.hasOwnProperty(i)) {
var query = this.queries[i];
if (size === query.name) return query.value;
}
}
return null;
},
/**
* Gets the current breakpoint name by testing every breakpoint and returning the last one to match (the biggest one).
* @function
* @private
* @returns {String} Name of the current breakpoint.
*/
_getCurrentSize() {
var matched;
for (var i = 0; i < this.queries.length; i++) {
var query = this.queries[i];
if (window.matchMedia(query.value).matches) {
matched = query;
}
}
if (typeof matched === 'object') {
return matched.name;
} else {
return matched;
}
},
/**
* Activates the breakpoint watcher, which fires an event on the window whenever the breakpoint changes.
* @function
* @private
*/
_watcher() {
$(window).on('resize.zf.mediaquery', () => {
var newSize = this._getCurrentSize(), currentSize = this.current;
if (newSize !== currentSize) {
// Change the current media query
this.current = newSize;
// Broadcast the media query change on the window
$(window).trigger('changed.zf.mediaquery', [newSize, currentSize]);
}
})
}
};
Foundation.MediaQuery = MediaQuery;
// matchMedia() polyfill - Test a CSS media type/query in JS.
// Authors & copyright (c) 2012: Scott Jehl, Paul Irish, Nicholas Zakas, David Knight. Dual MIT/BSD license
window.matchMedia || (window.matchMedia = function() {
'use strict';
// For browsers that support matchMedium api such as IE 9 and webkit
var styleMedia = (window.styleMedia || window.media);
// For those that don't support matchMedium
if (!styleMedia) {
var style = document.createElement('style'),
script = document.getElementsByTagName('script')[0],
info = null;
style.type = 'text/css';
style.id = 'matchmediajs-test';
script.parentNode.insertBefore(style, script);
// 'style.currentStyle' is used by IE <= 8 and 'window.getComputedStyle' for all other browsers
info = ('getComputedStyle' in window) && window.getComputedStyle(style, null) || style.currentStyle;
styleMedia = {
matchMedium(media) {
var text = `@media ${media}{ #matchmediajs-test { width: 1px; } }`;
// 'style.styleSheet' is used by IE <= 8 and 'style.textContent' for all other browsers
if (style.styleSheet) {
style.styleSheet.cssText = text;
} else {
style.textContent = text;
}
// Test if media query is true or false
return info.width === '1px';
}
}
}
return function(media) {
return {
matches: styleMedia.matchMedium(media || 'all'),
media: media || 'all'
};
}
}());
// Thank you: https://github.com/sindresorhus/query-string
function parseStyleToObject(str) {
var styleObject = {};
if (typeof str !== 'string') {
return styleObject;
}
str = str.trim().slice(1, -1); // browsers re-quote string style values
if (!str) {
return styleObject;
}
styleObject = str.split('&').reduce(function(ret, param) {
var parts = param.replace(/\+/g, ' ').split('=');
var key = parts[0];
var val = parts[1];
key = decodeURIComponent(key);
// missing `=` should be `null`:
// http://w3.org/TR/2012/WD-url-20120524/#collect-url-parameters
val = val === undefined ? null : decodeURIComponent(val);
if (!ret.hasOwnProperty(key)) {
ret[key] = val;
} else if (Array.isArray(ret[key])) {
ret[key].push(val);
} else {
ret[key] = [ret[key], val];
}
return ret;
}, {});
return styleObject;
}
Foundation.MediaQuery = MediaQuery;
}(jQuery);
|
import { appendIfMissing, rebind } from '@zambezi/d3-utils'
import { compose, isUndefined } from 'underscore'
import { dispatch as createDispatch } from 'd3-dispatch'
import { select, event } from 'd3-selection'
import { unwrap } from '@zambezi/grid'
import './edit-cell.css'
const append = appendIfMissing('span.edit-cell-input')
export function createEditCell () {
const rowToTemp = new WeakMap()
const dispatch = createDispatch('change', 'validationerror', 'editstart', 'editend')
const api = rebind().from(dispatch, 'on')
const internalDispatch = createDispatch('external-edit-request')
let gesture = 'dblclick'
let component
let validate = () => null
let editable = () => true
let silenceStartEditClicks = true
function editCellEach (d, i) {
const isEditable = editable.call(this, d, i)
const row = unwrap(d.row)
const column = d.column
const temp = rowToTemp.get(row)
const cellTarget = select(this)
cellTarget.classed('editable-cell', isEditable)
.on('click.quiet', (isEditable && silenceStartEditClicks) ? () => event.stopPropagation() : null)
.on(gesture + '.start', isEditable ? cell => startEdit(cell) : null)
internalDispatch.on(`external-edit-request.${column.id}`, startExternalEdit)
draw()
function startExternalEdit (cell, initValue) {
const eventColumn = cell.column
const isTargetRowEditable = editable.call(this, cell)
if (eventColumn.id !== column.id) return
if (!isTargetRowEditable) return
startEdit(cell, initValue)
}
function draw () {
if (isEditable && temp) {
d.tempInput = temp.value
d.isValidInput = !!temp.valid
component
.on('partialedit.cache', cacheTemp)
.on('cancel.clear', removeTmp)
.on('cancel.notify', notifyEditEnd)
.on('cancel.redraw', () => cellTarget.dispatch('redraw', { bubbles: true }))
.on('commit.process', compose(notifyEditEnd, validateChange))
.on('commit.redraw', () => cellTarget.dispatch('redraw', { bubbles: true }))
cellTarget.classed('is-editing', true)
.select(append)
.call(component)
} else {
cellTarget.classed('is-editing', false).select('.edit-cell-input').remove()
}
}
function cacheTemp (d) {
rowToTemp.set(unwrap(d.row), { value: this.value, valid: true })
}
function removeTmp (d) {
rowToTemp.delete(unwrap(d.row))
}
function notifyEditEnd (d) {
if (!d) return
dispatch.call('editend', this, unwrap(d))
}
function validateChange (d) {
const unwrappedRow = unwrap(d.row)
const reason = validate.call(this, d, this.value)
const isValid = !reason
if (isValid) {
removeTmp(d)
dispatch.call('change', this, unwrappedRow, this.value)
return d
} else {
rowToTemp.set(unwrappedRow, { value: this.value, valid: false })
dispatch.call('validationerror', this, reason)
return null
}
}
function startEdit (cell, initValue) {
const { row } = cell
const unwrappedRow = unwrap(row)
const isAlreadyEditing = (rowToTemp.get(unwrappedRow) !== undefined)
if (isAlreadyEditing) return
rowToTemp.set(
unwrappedRow,
{
value: isUndefined(initValue) ? cell.value : initValue,
valid: true
}
)
dispatch.call('editstart', this, unwrappedRow)
cellTarget.dispatch('redraw', { bubbles: true })
}
// Reconfigure row changed key function after first run
editCellEach.rowChangedKey = function (targetRow) {
const temp = rowToTemp.get(unwrap(targetRow))
const isEditing = !!temp
return !isEditing ? '-'
: temp.valid ? '★'
: '☆'
}
}
editCellEach.rowChangedKey = function (targetRow) {
return '-'
}
editCellEach.component = function (value) {
if (!arguments.length) return component
component = value
return editCellEach
}
editCellEach.validate = function (value) {
if (!arguments.length) return validate
validate = value
return editCellEach
}
editCellEach.editable = function (value) {
if (!arguments.length) return editable
editable = value
return editCellEach
}
editCellEach.gesture = function (value) {
if (!arguments.length) return gesture
gesture = value
return editCellEach
}
editCellEach.silenceStartEditClicks = function (value) {
if (!arguments.length) return silenceStartEditClicks
silenceStartEditClicks = value
return editCellEach
}
editCellEach.startEdit = function (cell, initValue) {
internalDispatch.call('external-edit-request', this, cell, initValue)
return editCellEach
}
return api(editCellEach)
}
|
const test = require('tape')
function calculateFirstRevisit(input) {
const initial = {
x: 0,
y: 0,
direction: { x: 0, y: 1 },
}
const visited = {}
let pos = initial
const directions = input
.split(',')
.map(d => d.trim())
for (d of directions) {
const turn = d.charAt(0)
const move = parseInt(d.slice(1))
const newDirection = turn === 'L'
? { x: -pos.direction.y, y: pos.direction.x }
: { x: pos.direction.y, y: -pos.direction.x }
for (let i = 1; i < move; i++) {
const x = pos.x + newDirection.x * i
const y = pos.y + newDirection.y * i
const key = `${x}-${y}`
if (key in visited) return visited[key]
visited[key] = Math.abs(x) + Math.abs(y)
}
pos = {
x: pos.x + newDirection.x * move,
y: pos.y + newDirection.y * move,
direction: newDirection,
}
}
return undefined
}
test('day1b - test1', t => {
const input = 'R8, R4, R4, R8'
const expected = 4
t.equal(calculateFirstRevisit(input), expected)
t.end()
})
const input = 'R2, L1, R2, R1, R1, L3, R3, L5, L5, L2, L1, R4, R1, R3, L5, L5, R3, L4, L4, R5, R4, R3, L1, L2, R5, R4, L2, R1, R4, R4, L2, L1, L1, R190, R3, L4, R52, R5, R3, L5, R3, R2, R1, L5, L5, L4, R2, L3, R3, L1, L3, R5, L3, L4, R3, R77, R3, L2, R189, R4, R2, L2, R2, L1, R5, R4, R4, R2, L2, L2, L5, L1, R1, R2, L3, L4, L5, R1, L1, L2, L2, R2, L3, R3, L4, L1, L5, L4, L4, R3, R5, L2, R4, R5, R3, L2, L2, L4, L2, R2, L5, L4, R3, R1, L2, R2, R4, L1, L4, L4, L2, R2, L4, L1, L1, R4, L1, L3, L2, L2, L5, R5, R2, R5, L1, L5, R2, R4, R4, L2, R5, L5, R5, R5, L4, R2, R1, R1, R3, L3, L3, L4, L3, L2, L2, L2, R2, L1, L3, R2, R5, R5, L4, R3, L3, L4, R2, L5, R5'
console.log('Day 1 B - Ans.', calculateFirstRevisit(input))
|
import Ora from 'ora';
import { CWD, NODE_ENV } from '../../../constants';
import { compile } from '../../compiler';
export async function build(useStrict: boolean = false): Promise<void> {
const spinner = new Ora({
text: 'Building your application...',
spinner: 'dots'
});
spinner.start();
await compile(CWD, NODE_ENV, {
useStrict
});
spinner.stop();
}
|
var cadence = require('..')
var fs = require('fs')
cadence(function (async) {
async(function () {
fs.readFile(__filename, async())
}, function () {
var d = require('domain').create()
d.on('error', function (error) {
console.log('captured')
throw error
})
d.run(function () {
throw new Error
})
})
})(function (error) {
console.log('called')
if (error) throw error
})
|
const test = require('tape')
const nlp = require('../_lib')
test('named-match-overlap', function (t) {
let doc = nlp('june the 5th, july the 7th, and sept the 12th.')
let m = doc.match('[<month>#Month]', 'month')
t.equal(m.length, 3, 'Should have 3 results')
t.equal(m.groups('month').length, 3, 'Should have 3 capture group results')
t.end()
})
test('named-match-or:', function (t) {
let arr = [
['the dog played again', 'the [<target>(#Noun|#Verb)] played [<0>(#Adverb)]', 'dog'],
['the dog played again', 'the [<target>(#Noun|#Verb)] played [<another>(#Adverb)]', 'dog'],
['the dog played', 'the [<target>(#Noun|#Verb)] played', 'dog'],
['the dog played', 'the [<target>(#Noun)] played', 'dog'],
]
arr.forEach(function (a) {
const doc = nlp(a[0]).match(a[1]).groups('target')
const msg = a[0] + ' matches ' + JSON.stringify(a[1]) + ' ' + a[2]
t.equal(doc.text(), a[2], msg)
})
t.end()
})
test('named-match-auto:', function (t) {
let arr = [
['the dog played', 'the [#Noun] played', 'dog'],
['the dog played', 'the [dog] played', 'dog'],
['the big dog played', 'the [big dog] played', 'big dog'],
['the dog played', 'the #Noun [played]', 'played'],
['the dog played', 'the dog [played]', 'played'],
['the big dog played', 'the big dog [played]', 'played'],
]
arr.forEach(function (a) {
const doc = nlp(a[0]).match(a[1])
const res = doc.groups(0)
const msg = a[0] + ' matches ' + JSON.stringify(a[1]) + ' ' + a[2]
t.equal(res.text(), a[2], msg)
})
t.end()
})
test('named-match-auto-multi:', function (t) {
let arr = [
['the dog played', 'the [#Noun] [played]', 'dog'],
['the dog played lots', 'the [dog] played [<0>lots]', 'dog lots'],
['the big dog played', 'the [big dog] [played]', 'big dog'],
]
arr.forEach(function (a) {
const doc = nlp(a[0]).match(a[1])
const res = doc.groups(0)
const msg = a[0] + ' matches ' + JSON.stringify(a[1]) + ' ' + a[2]
t.equal(res.text(), a[2], msg)
})
t.end()
})
test('named-match-group', function (t) {
const res = nlp('the dog played').match('the [<type>#Noun] played').groups()
t.equal(res['type'].text(), 'dog')
const doc2 = nlp('the big big big dog played').match('the [<size>#Adjective+] [<type>#Noun] played')
const res2 = doc2.groups()
t.equal(res2['type'].text(), 'dog')
t.equal(res2['size'].text(), 'big big big')
t.end()
})
test('named-match-to-json:', function (t) {
let arr = [
[
'the dog played',
'the [<target>#Noun] played',
'dog',
[{ text: 'dog', terms: [{ text: 'dog', tags: ['Noun', 'Singular'], pre: '', post: ' ' }] }],
],
[
'the dog played',
'the [<target>dog] played',
'dog',
[{ text: 'dog', terms: [{ text: 'dog', tags: ['Noun', 'Singular'], pre: '', post: ' ' }] }],
],
[
'the big dog played',
'the [<target>big dog] played',
'big dog',
[
{
text: 'big dog',
terms: [
{ text: 'big', tags: ['Comparable', 'Adjective'], pre: '', post: ' ' },
{ text: 'dog', tags: ['Noun', 'Singular'], pre: '', post: ' ' },
],
},
],
],
[
'the big dog played',
'the [<target>big] dog [<target>played]',
'big played',
[
{ text: 'big', terms: [{ text: 'big', tags: ['Comparable', 'Adjective'], pre: '', post: ' ' }] },
{ text: 'played', terms: [{ text: 'played', tags: ['PastTense', 'Verb'], pre: '', post: '' }] },
],
],
]
arr.forEach(function (a) {
const doc = nlp(a[0]).match(a[1])
const res = doc.groups()
t.ok(res['target'], "Should contain 'target' group")
const json = res.target.json()
const text = res.target.text()
t.equal(text, a[2])
t.deepEqual(json, a[3], a[0])
})
t.end()
})
test('named-match-overlap', function (t) {
const arr = [
{
input: 'the big dog played',
match: 'the [<target>#Adjective] [<type>#Noun] [<target>played]',
run: res => {
t.equal(res['type'].text(), 'dog')
t.equal(res['target'].text(), 'big played')
},
},
]
arr.forEach(a => a.run(nlp(a.input).match(a.match).groups()))
t.end()
})
test('named-object-match-quick:', function (t) {
let arr = [
['the dog played', [{ word: 'the' }, { tag: 'Noun', named: 'target' }, { word: 'played' }], 'dog'],
['the dog played', [{ word: 'dog', named: 'target' }], 'dog'],
['the dog played', [{ tag: 'Verb', named: 'target' }], 'played'],
]
arr.forEach(function (a) {
const doc = nlp(a[0]).match(a[1], 'target')
const msg = a[0] + ' matches ' + JSON.stringify(a[1]) + ' ' + a[2]
t.equal(doc.text(), a[2], msg)
})
t.end()
})
test('named-object-match:', function (t) {
let arr = [
['the dog played', [{ word: 'the' }, { tag: 'Noun', named: 'target' }, { word: 'played' }], 'dog'],
['the dog played', [{ word: 'dog', named: 'target' }], 'dog'],
['the dog played', [{ tag: 'Verb', named: 'target' }], 'played'],
]
arr.forEach(function (a) {
const doc = nlp(a[0]).match(a[1]).groups('target')
const msg = a[0] + ' matches ' + JSON.stringify(a[1]) + ' ' + a[2]
t.equal(doc.text(), a[2], msg)
})
t.end()
})
test('named-object-match-target:', function (t) {
let arr = [
['the dog played', [{ word: 'the' }, { tag: 'Noun', named: 'target' }, { word: 'played' }], 'dog'],
['the dog played', [{ word: 'dog', named: 'target' }], 'dog'],
['the dog played', [{ tag: 'Verb', named: 'target' }], 'played'],
['the dog played', [{ word: 'the' }, { tag: 'Noun', named: 'not-target' }, { word: 'played' }], ''],
['the dog played', [{ word: 'dog', named: 'not-target' }], ''],
['the dog played', [{ tag: 'Verb', named: 'not-target' }], ''],
]
arr.forEach(function (a) {
const doc = nlp(a[0]).match(a[1]).groups('target')
const msg = a[0] + ' matches ' + JSON.stringify(a[1]) + ' ' + a[2]
t.equal(doc.text(), a[2], msg)
})
t.end()
})
test('named-object-match-number:', function (t) {
let arr = [
['the dog played', [{ word: 'the' }, { tag: 'Noun', named: '0' }, { word: 'played' }], 'dog'],
['the dog played', [{ word: 'the' }, { tag: 'Noun', named: 0 }, { word: 'played' }], 'dog'],
['the dog played', [{ word: 'dog', named: 0 }], 'dog'],
['the dog played', [{ tag: 'Verb', named: 0 }], 'played'],
['the dog played', [{ word: 'the' }, { tag: 'Noun', named: 1 }, { word: 'played' }], ''],
['the dog played', [{ word: 'dog', named: 1 }], ''],
['the dog played', [{ tag: 'Verb', named: 1 }], ''],
]
arr.forEach(function (a) {
const doc = nlp(a[0]).match(a[1]).groups(0)
const msg = a[0] + ' matches ' + JSON.stringify(a[1]) + ' ' + a[2]
t.equal(doc.text(), a[2], msg)
})
t.end()
})
test('named-match:', function (t) {
let arr = [
['the dog played', 'the [<target>#Noun] played', 'dog'],
['the dog played', 'the [<target>dog] played', 'dog'],
['the big dog played', 'the [<target>big dog] played', 'big dog'],
['the big dog played', 'the [<target>big dog] played', 'big dog'],
['the dog played', 'the dog [<target>#Verb]', 'played'],
]
arr.forEach(function (a) {
const doc = nlp(a[0]).match(a[1]).groups('target')
const msg = a[0] + ' matches ' + JSON.stringify(a[1]) + ' ' + a[2]
t.equal(doc.text(), a[2], msg)
})
t.end()
})
test('named-match-target:', function (t) {
let arr = [
['the dog played', 'the [<target>#Noun] played', 'dog'],
['the dog played', 'the [<target>dog] played', 'dog'],
['the big dog played', 'the [<target>big dog] played', 'big dog'],
['the dog played', 'the [<not-target>#Noun] played', ''],
['the dog played', 'the [<not-target>dog] played', ''],
['the big dog played', 'the [<not-target>big dog] played', ''],
]
arr.forEach(function (a) {
const doc = nlp(a[0]).match(a[1]).groups('target')
const msg = a[0] + ' matches ' + JSON.stringify(a[1]) + ' ' + a[2]
t.equal(doc.text(), a[2], msg)
})
t.end()
})
test('named-match-number:', function (t) {
let arr = [
['the dog played', 'the [<0>#Noun] played', 'dog'],
['the dog played', 'the [<0>dog] played', 'dog'],
['the big dog played', 'the [<0>big dog] played', 'big dog'],
['the dog played', 'the [<1>#Noun] played', ''],
['the dog played', 'the [<1>dog] played', ''],
['the big dog played', 'the [<1>big dog] played', ''],
]
arr.forEach(function (a) {
const doc = nlp(a[0]).match(a[1]).groups(0)
const msg = a[0] + ' matches ' + JSON.stringify(a[1]) + ' ' + a[2]
t.equal(doc.text(), a[2], msg)
})
t.end()
})
|
import { Route } from "react-router";
import React from "react";
import AppHandler from "./components/AppHandler";
export default (
<Route handler={ AppHandler } path="/" />
);
|
module.exports = {
arrowParens: 'always',
singleQuote: true,
proseWrap: 'always',
trailingComma: 'all',
}; |
'use strict';
angular.module('fantasyGolfApp')
.factory('Tournament', function ($http, promiseCache) {
return {
getTournament: function () {
return promiseCache({
promise: function () {
return $http.get('/api/pga/setup');
},
ttl: 900000
});
},
getPlayers: function () {
return promiseCache({
promise: function () {
return $http.get('/api/pga/field');
},
ttl: 900000
});
},
updateTournament: function(tournamentId, tournament){
//bust cache
//promiseCache.remove('listTournaments', false);
return $http.put('/api/tournament/' + tournamentId, tournament);
},
deleteTournament: function(tournamentId){
return $http.del('/api/tournament/' + tournamentId);
},
runSetup: function(){
return $http.post('/api/admin/setup');
},
refreshSetup: function(){
return $http.post('/api/admin/refreshsetup');
},
calcPlayers: function(){
return $http.post('/api/admin/calcplayers');
},
calcTeams: function(){
return $http.post('/api/admin/calcteams');
},
calcLeagues: function(){
return $http.post('/api/admin/calcleagues');
},
listUsers: function(){
return $http.get('/api/admin/users');
},
deleteUser: function(userId){
return $http.delete('/api/admin/users/' + userId);
}
};
});
|
'use strict';
angular.module('myApp').directive('canvasDrv', ['$timeout', function ($timeout) {
function link(scope, element, attr) {
var canvas = $("#testCanvas");
var paper = Raphael("testCanvas", canvas.width(), canvas.height());
var circle = paper.circle(50, 40, 10);
var rect = paper.rect(0, 0, 300, 300);
rect.attr("fill", "#eee");
rect.attr("fill-opacity", 0);
circle.attr("fill", "#f00");
circle.attr("stroke", "#fff");
rect.click(function(e) {
console.log(e);
circle.animate({r : 10, fill : '#00f', cx: e.offsetX, cy:e.offsetY}, 200);
});
}
return {
restrict: 'E',
replace: true,
scope: true,
link: link,
template: '<div id="testCanvas" style="border: 1px solid #E0E0E0;"></div>'
}
}]); |
import React, { PropTypes, Component } from 'react';
import styles from './LoginPage.css';
import withStyles from '../../decorators/withStyles';
import Firebase from 'firebase';
import LoginModal from '../LoginModal';
import {
FlatButton,
Dialog,
RaisedButton,
Snackbar,
TextField
} from 'material-ui/lib';
const firebase = new Firebase('https://lumpenradio.firebaseio.com');
@withStyles(styles)
class LoginPage extends Component {
static contextTypes = {
onSetTitle: PropTypes.func.isRequired,
};
constructor(props, context) {
super(props, context);
this.state = {
isLoginButtonDisabled: false,
snackbarMessage: ''
};
}
render() {
const title = 'Log In';
this.context.onSetTitle(title);
const { isLoginButtonDisabled, snackbarMessage } = this.state;
let formChildren = (
<form onSubmit={(evt) => {evt.preventDefault()} }>
<TextField
ref="emailField"
style={{display:'block'}}
hintText="lumpen@magazine.com"
floatingLabelText="Email"
type="email" />
<TextField
ref="passwordField"
style={{display:'block'}}
hintText=",mA]@x[px#L\oj9E"
floatingLabelText="Password"
type="password" />
</form>
)
let customActions = [
<FlatButton
ref="cancelButton"
label="Cancel"
secondary={true}
onTouchTap={this._handleDismissModal.bind(this)} />,
<FlatButton
ref="loginButton"
label="Login"
primary={true}
disabled={isLoginButtonDisabled}
onTouchTap={this._handleLogin.bind(this)} />
];
return (
<div className="LoginPage">
<div className="LoginPage-container">
<h1>{title}</h1>
<RaisedButton
primary={true}
onTouchTap={this._handleShowModal.bind(this)}
label="Open Login Form" />
<Dialog
title="Firebase Login"
openImmediately={false}
actions={customActions}
ref="loginDialog">
Enter your Firebase login credentials.
<LoginModal>
{formChildren}
</LoginModal>
</Dialog>
<Snackbar
ref="snackbar"
message={snackbarMessage || "A message"}
autoHideDuration={3000} />
</div>
</div>
);
}
_handleShowModal() {
this.refs.loginDialog.show();
}
_handleDismissModal() {
this.refs.loginDialog.dismiss();
}
_handleLogin() {
const { loginButton, emailField, passwordField, snackbar } = this.refs;
let email = emailField.getValue();
let password = passwordField.getValue();
// TODO: Validate user input
// Disable login button while waiting for a response
this.setState({isLoginButtonDisabled: true});
firebase.authWithPassword({ email, password }, (error, authData) => {
if (error) {
this.setState({
isLoginButtonDisabled: false,
snackbarMessage: `Login Failed! ${error}`
});
snackbar.show();
console.log("Login Failed!", error);
} else {
this.setState({
isLoginButtonDisabled: false,
snackbarMessage: 'Authenticated successfully'
});
snackbar.show();
this._handleDismissModal()
console.log("Authenticated successfully with payload:", authData);
}
});
}
}
export default LoginPage;
|
<!DOCTYPE html>
<html>
<title>W3.CSS</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="/lib/w3.css">
<body>
<h2 class="w3-center">Manual Slideshow</h2>
<div class="w3-content w3-display-container">
<img class="mySlides" src="img_fjords.jpg" style="width:100%">
<img class="mySlides" src="img_lights.jpg" style="width:100%">
<img class="mySlides" src="img_mountains.jpg" style="width:100%">
<img class="mySlides" src="img_forest.jpg" style="width:100%">
<a class="w3-btn-floating w3-display-left" onclick="plusDivs(-1)">❮</a>
<a class="w3-btn-floating w3-display-right" onclick="plusDivs(1)">❯</a>
</div>
<script>
var slideIndex = 1;
showDivs(slideIndex);
function plusDivs(n) {
showDivs(slideIndex += n);
}
function showDivs(n) {
var i;
var x = document.getElementsByClassName("mySlides");
if (n > x.length) {slideIndex = 1}
if (n < 1) {slideIndex = x.length}
for (i = 0; i < x.length; i++) {
x[i].style.display = "none";
}
x[slideIndex-1].style.display = "block";
}
</script>
</body>
</html>
|
/*global expect*/
describe('expect.promise', function() {
it('should forward non-unexpected errors', function() {
var clonedExpect = expect
.clone()
.addAssertion('to foo', function(expect, subject, value) {
return expect.withError(
function() {
return expect.promise(function() {
return expect.promise.any([
expect.promise(function() {
expect(subject, 'to be', 24);
}),
expect.promise(function() {
throw new Error('wat');
})
]);
});
},
function(e) {
// success
}
);
});
expect(
function() {
clonedExpect(42, 'to foo');
},
'to throw',
'wat'
);
});
it('should return the fulfilled promise even if it is oathbreakable', function() {
var clonedExpect = expect
.clone()
.addAssertion('to foo', function(expect, subject, value) {
return expect.promise(function() {
expect(subject, 'to equal', 'foo');
return 'bar';
});
});
expect(clonedExpect('foo', 'to foo'), 'to be fulfilled with', 'bar');
});
it('should preserve the resolved value when an assertion contains a non-oathbreakable promise', function(done) {
var clonedExpect = expect
.clone()
.addAssertion('to foo', function(expect, subject, value) {
return expect.promise(function(resolve, reject) {
expect(subject, 'to equal', 'foo');
setTimeout(function() {
resolve('bar');
}, 1);
});
});
clonedExpect('foo', 'to foo').then(function(value) {
expect(value, 'to equal', 'bar');
done();
});
});
it('should return a promise fulfilled with the return value when an assertion returns a non-promise value', function() {
var clonedExpect = expect
.clone()
.addAssertion('to foo', function(expect, subject, value) {
expect(subject, 'to equal', 'foo');
return 'bar';
});
clonedExpect('foo', 'to foo').then(function(value) {
expect(value, 'to equal', 'bar');
});
});
describe('#and', function() {
describe('with a synchronous assertion', function() {
it('should succeed', function() {
return expect('foo', 'to equal', 'foo').and('to be a string');
});
it('should succeed when another clause is added', function() {
return expect('foo', 'to equal', 'foo')
.and('to be a string')
.and('to match', /^f/);
});
it('should work without returning the promise', function() {
expect('foo', 'to equal', 'foo').and('to be a string');
});
it('should fail with a diff', function() {
return expect(
function() {
return expect('foo', 'to equal', 'foo').and('to be a number');
},
'to error',
"expected 'foo' to be a number"
);
});
it('should fail with a diff even when the promise is not returned', function() {
return expect(
function() {
expect('foo', 'to equal', 'foo').and('to be a number');
},
'to error',
"expected 'foo' to be a number"
);
});
describe('with an expect.it as the second clause', function() {
it('should succeed', function() {
return expect('foo', 'to equal', 'foo').and(
expect.it('to be a string')
);
});
it('should fail with a diff', function() {
return expect(
function() {
return expect('foo', 'to equal', 'foo').and(
expect.it('to be a number')
);
},
'to error',
"expected 'foo' to be a number"
);
});
});
});
describe('with an asynchronous assertion anded with a synchronous one', function() {
it('should succeed', function() {
return expect('foo', 'when delayed', 5, 'to equal', 'foo').and(
'to be a string'
);
});
it('should succeed when another clause is added', function() {
return expect('foo', 'when delayed', 5, 'to equal', 'foo')
.and('when delayed', 5, 'to be a string')
.and('when delayed', 2, 'to be a string');
});
it('should fail with a diff when the asynchronous assertion fails', function() {
return expect(
function() {
return expect('foo', 'when delayed', 5, 'to equal', 'bar').and(
'to be a string'
);
},
'to error',
"expected 'foo' when delayed 5 to equal 'bar'\n" +
'\n' +
'-foo\n' +
'+bar'
);
});
it('should fail with a diff when the synchronous assertion fails', function() {
return expect(
function() {
return expect('foo', 'when delayed', 5, 'to equal', 'foo').and(
'to be a number'
);
},
'to error',
"expected 'foo' to be a number"
);
});
it('should fail with a diff when both assertions fail', function() {
return expect(
function() {
return expect('foo', 'when delayed', 5, 'to equal', 'bar').and(
'to be a number'
);
},
'to error',
"expected 'foo' when delayed 5 to equal 'bar'\n" +
'\n' +
'-foo\n' +
'+bar'
);
});
describe('with an expect.it as the second clause', function() {
it('should succeed', function() {
return expect('foo', 'when delayed', 5, 'to equal', 'foo').and(
expect.it('to be a string')
);
});
it('should succeed when more clauses are added', function() {
return expect('foo', 'when delayed', 5, 'to equal', 'foo')
.and(expect.it('to be a string'))
.and('to be a string')
.and('to be a string');
});
it('should fail with a diff', function() {
return expect(
function() {
return expect('foo', 'when delayed', 5, 'to equal', 'foo').and(
expect.it('to be a number')
);
},
'to error',
"expected 'foo' to be a number"
);
});
});
});
describe('with a nested asynchronous assertion', function() {
it('should mount the and method on a promise returned from a nested assertion', function() {
var clonedExpect = expect
.clone()
.addAssertion('to foo', function(expect, subject) {
return expect(subject, 'to bar').and('to equal', 'foo');
})
.addAssertion('to bar', function(expect, subject) {
return expect.promise(function(run) {
setTimeout(
run(function() {
expect(subject, 'to be truthy');
}),
1
);
});
});
return clonedExpect('foo', 'to foo');
});
});
});
it('should throw an exception if the argument was not a function', function() {
var expectedError = new TypeError(
'expect.promise(...) requires a function argument to be supplied.\n' +
'See http://unexpected.js.org/api/promise/ for more details.'
);
expect(
function() {
expect.promise();
},
'to throw',
expectedError
);
[undefined, null, '', [], {}].forEach(function(arg) {
expect(
function() {
expect.promise(arg);
},
'to throw',
expectedError
);
});
});
describe('#inspect', function() {
var originalDefaultFormat = expect.output.constructor.defaultFormat;
beforeEach(function() {
expect.output.constructor.defaultFormat = 'text';
});
afterEach(function() {
expect.output.constructor.defaultFormat = originalDefaultFormat;
});
it('should inspect a fulfilled promise without a value', function() {
expect(
expect
.promise(function() {
expect(2, 'to equal', 2);
})
.inspect(),
'to equal',
'Promise (fulfilled)'
);
});
it('should inspect a fulfilled promise with a value', function() {
expect(
expect
.promise(function() {
return 123;
})
.inspect(),
'to equal',
'Promise (fulfilled) => 123'
);
});
it('should inspect a pending promise', function() {
var asyncPromise = expect(
'foo',
'when delayed a little bit',
'to equal',
'foo'
);
expect(asyncPromise.inspect(), 'to equal', 'Promise (pending)');
return asyncPromise;
});
it('should inspect a rejected promise without a reason', function() {
var promise = expect.promise(function(resolve, reject) {
reject();
});
return promise.caught(function() {
expect(promise.inspect(), 'to equal', 'Promise (rejected)');
});
});
it('should inspect a rejected promise with a reason', function() {
var promise = expect.promise(function(resolve, reject) {
setTimeout(function() {
reject(new Error('argh'));
}, 0);
});
return promise.caught(function() {
expect(
promise.inspect(),
'to equal',
"Promise (rejected) => Error('argh')"
);
});
});
});
describe('#settle', function() {
it('should support non-Promise leaves', function() {
return expect.promise
.settle({
a: 123
})
.then(function(promises) {
expect(promises, 'to equal', []);
});
});
});
describe('called with a function that takes a single ("run") parameter', function() {
it('should allow providing an empty function', function() {
return expect.promise(function(run) {
setImmediate(run());
});
});
it('should not fulfill the promise until the outer function has returned', function() {
return expect(
expect.promise(function(run) {
run()();
throw new Error('foo');
}),
'to be rejected with',
'foo'
);
});
it('should provide a run function that preserves the return value of the supplied function', function() {
return expect.promise(function(run) {
var runner = run(function() {
return 123;
});
expect(runner(), 'to equal', 123);
});
});
});
});
|
//用户提示消息
function notifyUser(message){
toast.showShort(message);
}
//定义传输NFC数据的json对象 data。
//1、data.unlock为开门密码。对应的为一串密码字符串。
//2、data.add为添加用户。对应的为一个卡号的数组。
//3、data.modify为修改用户昵称。对应的一个为卡号为键,昵称为值的json对象。
//4、data.delete为删除选中的对象。对应的为一个卡号的数组。
//每次通信完都会删除该对象里面的数据。所以得到数据的时候,获取该对象的键为对应的操作数。
var data = {};
//清空所有的传输数据
function deleteData(){
for (var key in data){
delete data[key];
}
} |
var keystone = require('keystone');
var Organisation = keystone.list('Organisation');
exports = module.exports = function(req, res) {
var view = new keystone.View(req, res),
locals = res.locals;
locals.section = 'members';
view.query('organisations', Organisation.model.find().sort('name'), 'members');
view.render('organisations');
}
|
// Download the Node helper library from twilio.com/docs/node/install
// These identifiers are your accountSid and authToken from
// https://www.twilio.com/console
const accountSid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
const authToken = 'your_auth_token';
const client = require('twilio')(accountSid, authToken);
client.applications.each(app => console.log(app.smsUrl));
|
/*global __CLIENT__*/
import React, {PropTypes} from 'react';
import {connect} from 'redux/react';
if (__CLIENT__) {
require('../assets/InfoBar.scss');
}
class MiniInfoBar {
static propTypes = {
time: PropTypes.number
}
render() {
const {time} = this.props;
return (
<div className="mini-info-bar">
The info bar was last loaded at
{' '}
<span>{time && new Date(time).toString()}</span>
</div>
);
}
}
@connect(state => ({
time: state.info.data.time
}))
export default
class MiniInfoBarContainer {
static propTypes = {
time: PropTypes.number,
dispatch: PropTypes.func.isRequired
}
render() {
const { time, dispatch } = this.props;
return <MiniInfoBar time={time}/>;
// no bindActionCreators() because this component is display-only
}
}
|
var searchData=
[
['executionpolicy',['ExecutionPolicy',['../namespace_cubby_flow.html#afca17441ed562aa8c59856e36c532101',1,'CubbyFlow']]]
];
|
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
let configBase = require("./webpack.config.base.js");
let config = {
...configBase,
mode: "production",
entry: {
index: ["./index.js"]
},
optimization: {
minimize: true,
splitChunks: {
cacheGroups: {
async: {
chunks: "async",
minSize: 0,
minChunks: 2
}
}
}
},
module: {
...configBase.module,
rules: [
...configBase.module.rules,
{
test: /\.css$/,
use: [
MiniCssExtractPlugin.loader,
{
loader: "css-loader",
options: {
importLoaders: 1
}
},
"postcss-loader"
]
}
]
},
plugins: [...configBase.plugins, new MiniCssExtractPlugin()]
};
module.exports = config;
|
// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
//
// Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require jquery
//= require jquery_ujs
//= require jquery-ui
//= require chili_pepper
//= require_tree .
|
/**
* Object2D represents an object of the scene.
* An Object2D is a simple scene object which the main
* purpose is to render a texture at a position. More
* complex behaviors should be implemented by others
* objects that inherit from Object2D.
*
* @param {!Grape2D.Vector=} options.position The position of the shape
* @param {!boolean=} options.visible True to render the object, false
* otherwise.
* @param {!Grape2D.Texture} options.texture The texture of the object.
* @param {!Grape2D.Vector=} options.textureOffset The offset position
* of the texture relative to the objects position.
* @param {!Grape2D.Shape} options.boundingBox The primary use of the
* bounding box is to select the items to display in the renderer,
* other behaviors such as collision detection can be done with
* this property, in some simple cases. So the bounding box should
* bounded tightly to what's supposed to be seen.
* @param {!Grape2D.Vector=} options.boundingBoxOffset The offset
* position of the bounding box relative to the objects position.
* @param {!boolean=} options.castShadow Used by the IlluminatedRenderer
* to render this object shadow.
* @param {!boolean=} options.receiveLight Used by the IlluminatedRenderer
* to render the objects texture with a light overlay, if set to true.
*
* @constructor
*/
Grape2D.Object2D = function (options) {
/**
* Object's position.
*
* @type {!Grape2D.Vector}
* @private
*/
this.position = options.position || new Grape2D.Vector();
/**
* Visible property.
*
* @type {!boolean}
* @private
*/
this.visible = options.visible || true;
/**
* The texture of the object.
*
* @type {!Grape2D.Texture}
* @private
*/
this.texture = options.texture;
/**
* The offset of the texture.
*
* @type {!Grape2D.Vector}
* @private
*/
this.textureOffset = options.textureOffset || new Grape2D.Vector();
/**
* The position of the texture. It is computed from the object's position and the texture offset.
*
* @type {!Grape2D.Vector}
* @private
*/
this.texturePosition = new Grape2D.Vector();
//computes the texture position.
this.computeTexturePosition();
/**
* Object's bounding box.
*
* @type {!Grape2D.Shape}
* @private
*/
this.boundingBox = options.boundingBox;
/**
* Bounding box offset.
*
* @type {!Grape2D.Vector}
* @private
*/
this.boundingBoxOffset = options.boundingBoxOffset || new Grape2D.Vector();
this.computeBoundingBoxPosition();
/**
* Object cast shadow.
*
* @type {!boolean}
* @private
*/
this.castShadow = options.castShadow || false;
/**
* Object can receive light.
*
* @type {!boolean}
* @private
*/
this.receiveLight = options.receiveLight || false;
};
Grape2D.Object2D.prototype = {
constructor: Grape2D.Object2D,
/**
* Checks if the object should be rendered.
*
* @return {!boolean} True if it can be rendered.
* @public
*/
isVisible: function () {
return this.visible;
},
/**
* Sets if an object should be rendered.
*
* @param {!boolean} visible True, so that it renders, false
* otherwise.
* @public
*/
setVisible: function (visible) {
this.visible = visible;
return;
},
/**
* Gets the texture of the object.
*
* @return {!Grape2D.Texture} The texture of the object.
* @public
*/
getTexture: function () {
return this.texture;
},
/**
* Sets the texture of the object.
*
* @param {!Grape2D.Texture} texture The texture.
* @public
*/
setTexture: function (texture) {
this.texture = texture;
return;
},
/**
* Gets the bounding box of the object.
*
* @return {!Grape2D.Shape} The shape of the object.
* @public
*/
getBoundingBox: function () {
return this.boundingBox;
},
/**
* Sets the bounding box of the object.
* Also, the position of the new bounding box, will be transformed
* in the default offset of the bounding box.
*
* @param {!Grape2D.Shape} boundingBox The bounding box.
* @public
*/
setBoundingBox: function (boundingBox) {
this.boundingBox = boundingBox;
this.computeBoundingBoxPosition();
return;
},
/**
* Checks if the object can cast shadows.
*
* @return {!boolean} True if it cast shadows, false otherwise.
* @public
*/
canCastShadow: function () {
return this.castShadow;
},
/**
* Sets if an object can cast shadows.
*
* @param {!boolean} castShadow True to cast shadows, false
* otherwise.
* @public
*/
setCastShadow: function (castShadow) {
this.castShadow = castShadow;
return;
},
/**
* Checks if an object can receive light.
*
* @return {!boolean} True if it receives light.
* @public
*/
canReceiveLight: function () {
return this.receiveLight;
},
/**
* Sets if the object can receive light.
*
* @param {!boolean} receiveLight True if it receives light.
* @public
*/
setReceiveLight: function (receiveLight) {
this.receiveLight = receiveLight;
return;
},
/**
* Gets the object position. Be careful, because it returns the
* vector used by the object, and not a copy. Use it wisely.
*
* @return {!Grape2D.Vector} The position of the object.
* @public
*/
getPosition: function () {
return this.position;
},
/**
* Sets the object position.
*
* @param {!Grape2D.Vector} position The position of the object.
* @public
*/
setPosition: function (position) {
this.position.set(position);
this.computeBoundingBoxPosition();
this.computeTexturePosition();
},
/**
* Sets the texture offset.
*
* @param {!Grape2D.Vector} offset The offset of the texture, from
* the object's position.
* @public
*/
setTextureOffset: function (offset) {
this.textureOffset.set(offset);
this.computeTexturePosition();
},
/**
* Gets the texture offset
*
* @return {!Grape2D.Vector} The texture offset.
* @public
*/
getTextureOffset: function () {
return this.textureOffset;
},
/**
* Sets the bounding box offset.
*
* @param {!Grape2D.Vector} offset The offset of the bounding
* box, from the object's position.
* @public
*/
setBoundingBoxOffset: function (offset) {
this.boundingBoxOffset.set(offset);
this.computeBoundingBoxPosition();
},
/**
* Gets the bounding box offset
*
* @return {!Grape2D.Vector} The bounding box offset.
* @public
*/
getBoundingBoxOffset: function () {
return this.boundingBoxOffset;
},
/**
* Computes the bounding box position, from the object's position
* and bounding box offset.
* @protected
*/
computeBoundingBoxPosition: function () {
this.boundingBox.setPosition(this.position);
this.boundingBox.getPosition().add(this.boundingBoxOffset);
},
/**
* Gets the bounding box position.
*
* @return {!Grape2D.Vector} The center position of the bounding box.
* @public
*/
getBoundingBoxPosition: function () {
return this.boundingBox.getPosition();
},
/**
* Computes the texture position of the object, from the object's
* position and texture offset.
* @protected
*/
computeTexturePosition: function () {
this.texturePosition.set(this.position).add(this.textureOffset);
},
/**
* Gets the texture position.
*
* @return {!Grape2D.Vector} The position of the texture
* @public
*/
getTexturePosition: function () {
return this.texturePosition;
},
/**
* Renders the object to a renderer.
*
* @param {!Grape2D.Renderer} renderer The place to render the
* object.
* @param {!Grape2D.Camera} camera The camera, that will
* transform the positions.
* @public
*/
render: function (renderer, camera) {
renderer.renderObject2D(this, camera);
},
/**
* Updates the object. This method should be refined in further
* subclasses if needed be.
*
* @param {!number} dt Time interval.
* @param {!Grape2D.Scene} scene Scene where this object is.
* @public
*/
update: function (dt, scene) {},
/**
* Processes this object thought a processor. Same as a visitor
* pattern.
*
* @param {Grape2D.Object2DProcessor} processor A processor.
* @public
*/
process: function(processor) {
processor.processObject2D(this);
}
}; |
/**
* EditAttendanceController
* @namespace band-dash.attendance
*/
(function () {
'use strict';
angular
.module('band-dash.attendance')
.controller('EditAttendanceController', EditAttendanceController);
EditAttendanceController.$inject = [
'$location',
'$scope',
'$http',
'$stateParams',
'Attendance',
'Snackbar'
];
/**
* @namespace EditAttendanceController
*/
function EditAttendanceController(
$location,
$scope,
$http,
$stateParams,
Attendance,
Snackbar) {
var vm = this;
vm.submitOnTime = submitOnTime;
vm.submitLate = submitLate;
vm.submitAbsence = submitAbsence;
vm.addUnassignedMember = addUnassignedMember;
activate()
/**
* @name activate
* @desc Actions to be performed when this controller is instantiated
* @memberOf band-dash.attendance.EditAttendanceController
*/
function activate() {
vm.assignedAttendances = [];
vm.unassignedAttendances = [];
$http.get('/api/v1/attendance/event/?id=' + $stateParams.event).success(
function(response) {
vm.event = response[0];
$http.get('/api/v1/attendance/event_attendance/?event_id=' + $stateParams.event).success(
function(response) {
for (var i = 0; i < response.length; i++) {
if (response[i].check_in_time) {
response[i].check_in_time = new Date(response[i].check_in_time);
}
Attendance.determineAttendanceStatus(response[i], vm.event);
if (response[i].assigned) {
if (!response[i].unexcused) {
response[i].unexcused = false;
}
vm.assignedAttendances.push(response[i]);
} else {
vm.unassignedAttendances.push(response[i]);
}
}
}
);
}
);
$http.get('/api/v1/members/unassigned/?event_id=' + $stateParams.event).success(
function(response) {
vm.unassignedMembers = response;
}
);
}
function submitOnTime(attendance) {
attendance.unexcused = false;
attendance.is_absence = false;
if (!attendance.assigned) {
attendance.event_id = vm.event.id;
attendance.member_id = attendance.member.id;
}
Attendance.submitOnTime(attendance).then(submitOnTimeSuccessFn, submitOnTimeErrorFn);
/**
* @name submitOnTimeSuccessFn
* @desc Log that on time attendance has been submitted successfully
*/
function submitOnTimeSuccessFn(data, status, headers, config) {
var newAttendance = data.data;
if (newAttendance) {
attendance.check_in_time = null;
attendance.status = 'On time';
if (!attendance.id) {
attendance.id = newAttendance.id;
}
}
Snackbar.show('Attendance submitted successfully');
}
/**
* @name submitOnTimeErrorFn
* @desc Log that error occurred when submitting on time attendance
*/
function submitOnTimeErrorFn(data, status, headers, config) {
Snackbar.error(data.data.detail);
}
}
function submitLate(attendance) {
attendance.is_absence = false;
if (!attendance.assigned) {
attendance.event_id = vm.event.id;
attendance.member_id = attendance.member.id;
}
Attendance.submitLate(attendance).then(submitLateSuccessFn, submitLateErrorFn);
/**
* @name submitLateSuccessFn
* @desc Log that late attendance has been submitted successfully
*/
function submitLateSuccessFn(data, status, headers, config) {
var newAttendance = data.data;
if (newAttendance) {
attendance.check_in_time = new Date(newAttendance.check_in_time);
attendance.points = newAttendance.points;
Attendance.determineAttendanceStatus(attendance, vm.event);
if (!attendance.id) {
attendance.id = newAttendance.id;
}
}
Snackbar.show('Attendance submitted successfully');
}
/**
* @name submitLateErrorFn
* @desc Log that error occurred when submitting late attendance
*/
function submitLateErrorFn(data, status, headers, config) {
Snackbar.error(data.data.detail);
}
}
function submitAbsence(attendance) {
attendance.is_absence = true;
attendance.event_id = vm.event.id;
attendance.member_id = attendance.member.id;
Attendance.submitAbsence(attendance).then(submitAbsenceSuccessFn, submitAbsenceErrorFn);
/**
* @name submitAbsenceSuccessFn
* @desc Log that on time attendance has been submitted successfully
*/
function submitAbsenceSuccessFn(data, status, headers, config) {
var newAttendance = data.data;
if (newAttendance) {
attendance.check_in_time = null;
attendance.status = 'Absent';
if (!attendance.id) {
attendance.id = newAttendance.id;
}
}
Snackbar.show('Absence submitted successfully');
}
/**
* @name submitAbsenceErrorFn
* @desc Log that error occurred when submitting on time attendance
*/
function submitAbsenceErrorFn(data, status, headers, config) {
Snackbar.error(data.data.detail);
}
}
function addUnassignedMember() {
var unassignedAttendance = {};
unassignedAttendance.member = angular.copy(vm.unassignedMember);
unassignedAttendance.assigned = false;
vm.unassignedAttendances.push(unassignedAttendance);
var index = vm.unassignedMembers.indexOf(vm.unassignedMember);
vm.unassignedMembers.splice(index, 1);
}
}
})();
|
'use strict';
module.exports = {
app: {
title: 'Material',
description: 'Full-Stack JavaScript with MongoDB, Express, AngularJS, and Node.js',
keywords: 'MongoDB, Express, AngularJS, Node.js'
},
port: process.env.PORT || 3000,
templateEngine: 'swig',
sessionSecret: 'MEAN',
sessionCollection: 'sessions',
assets: {
lib: {
css: [
'public/lib/angular-material/angular-material.css'
],
js: [
'public/lib/angular/angular.js',
'public/lib/angular-aria/angular-aria.js',
'public/lib/angular-resource/angular-resource.js',
'public/lib/angular-cookies/angular-cookies.js',
'public/lib/angular-animate/angular-animate.js',
'public/lib/angular-touch/angular-touch.js',
'public/lib/angular-sanitize/angular-sanitize.js',
'public/lib/angular-material/angular-material.js',
'public/lib/angular-ui-router/release/angular-ui-router.js',
'public/lib/angular-ui-utils/ui-utils.js'
]
},
css: [
'public/modules/**/css/*.css',
'public/style/*.css'
],
js: [
'public/config.js',
'public/application.js',
'public/modules/*/*.js',
'public/modules/*/*[!tests]*/*.js'
],
tests: [
'public/lib/angular-mocks/angular-mocks.js',
'public/modules/*/tests/*.js'
]
}
}; |
var express = require('express');
var request = require('superagent');
var parse = require('csv-parse');
//var fs = require('fs');
var app = express();
// Define global variables
var server = app.listen(3000, function(){
var host = server.address().address;
var port = server.address().port;
console.log('Example app listening at http://%s:%s', host, port);
});
function daysInMonth(month,year) {
if(new Date(year, 2, 0).getDate() == 29 && month == 12){
return new Date(year, month, 0).getDate() -1;
}
return new Date(year, month, 0).getDate();
}
app.get('/search', function(req1, res1){
// GET variables lat, lon, start and end years
var lat = req1.query.lat;
var lon = req1.query.lon;
var years = req1.query.year;
var text;
var req = request.get('https://daymet.ornl.gov/data/send/saveData?lat='+
lat +'&lon='+ lon + '&year=' + years).buffer().end(function(err, res){
if(res.status != 200){
// Daymet server error
return(-1);
}
text = res.text;
//call back API of parse
parse(text, function(err, output){
output = output.slice(8); // get rid of header
var res = [];
var ptr = [0,0,0,0,0,0];
// process downloaded data to 3PG input
years = years.split(','); //how many years
var len = years.length;
for(yr =0; yr < len; yr ++){
var cumdays = 0;
for(m = 1; m <= 12; m++){
var dim = daysInMonth(m, Number(years[yr]));
ptr = [0,0,0,0,0,0];
for(j = 0; j < dim; j++ ){ // For a given month
ptr[0] += Number(output[yr*365 + cumdays + j][7]);
ptr[1] += Number(output[yr*365 + cumdays + j][6]);
var tdmean = Number(output[yr*365 + cumdays + j][8])/1000;
tdmean = (Math.log(tdmean/0.6108)*237.3)/(17.27 - Math.log(tdmean/0.6108));
ptr[2] += tdmean;
ptr[3] += Number(output[yr*365 + cumdays + j][3]);
ptr[4] += Number(output[yr*365 + cumdays + j][4]) *
Number(output[yr*365 + cumdays + j][2])/1e6;
ptr[5] += Number(output[yr*365 + cumdays + j][2])/3600;
}
// Update after reading one month data
cumdays += dim
ptr[0] /= dim;
ptr[1] /= dim;
ptr[2] /= dim;
ptr[4] /= dim;
ptr[5] /= dim;
res.push(ptr);
}
}
console.log(JSON.stringify(res)); // return JSON object
});
});
});
|
define(["js/ui/View", "js/core/Content", "js/ui/Button", "underscore"], function (View, Content, Button, _) {
var CLOSE_BEHAVIOR = {
OTHER: "other", // closes other menu buttons
NON_PARENT: "nonParent", // closes other menu buttons but not the parents
NONE: "none" // closes no other menu buttons
};
return View.inherit("js.ui.MenuButtonClass", {
defaults: {
/***
* The label of the button.
*
* @type String
*/
label: "",
componentClass: 'btn-group menu-button',
/**
* The class name of the menu.
*
* @type String
*/
menuClassName: "dropdown-menu",
/**
* Set's the menu visible.
*
* @type Boolean
*/
menuVisible: false,
/**
* The class of the inner span in the link element
*
* @type String
*/
labelClass: "",
/**
* The class of the inner link element
*
* @type String
*/
buttonClass: "btn",
/***
* the class name for the icon
* @type String
*/
iconClass: null,
/***
* The inner label for the icon
*
* @type String
*/
iconLabel: "",
closeBehavior: CLOSE_BEHAVIOR.OTHER,
tabIndex: null,
title: null
},
$defaultContentName: 'menu',
$instances: [],
addChild: function (child) {
this.callBase();
if (child instanceof Button) {
this._collectButton(child);
}
},
_collectButton: function (child) {
this.$button = child;
this.$toggleButton = child;
},
_renderType: function (type) {
this.$button.set({type: type});
},
_renderIconClass: function (iconClass) {
this.$button.set({iconClass: iconClass});
},
_renderLabel: function (label) {
if (this.$button) {
this.$button.set({label: label});
}
},
_renderMenuVisible: function (visible) {
if (visible === true) {
var closeBehavior = this.$.closeBehavior;
if (closeBehavior !== CLOSE_BEHAVIOR.NONE) {
for (var i = 0; i < this.$instances.length; i++) {
var instance = this.$instances[i],
close = (instance !== this && instance.$.menuVisible === true);
if (close && closeBehavior === CLOSE_BEHAVIOR.NON_PARENT) {
// check that the instance is not a parent
var parent = this.$parent;
while (parent) {
if (parent === instance) {
close = false;
break;
}
parent = parent.$parent;
}
}
if (close) {
instance.set({menuVisible: false});
}
}
}
this.addClass('open');
} else {
this.removeClass('open');
}
},
_bindDomEvents: function (el) {
this.callBase();
if (!_.contains(this.$instances, this)) {
this.$instances.push(this);
}
var self = this;
this.bindDomEvent('click', function () {
self.set({menuVisible: false});
});
this.$toggleButton.bind('on:click', function (e) {
if (self.$.enabled) {
e.stopPropagation();
e.preventDefault();
self.set({menuVisible: !self.$.menuVisible});
}
});
this.$button.bind('on:click', function (e) {
self.trigger('on:click', e, self);
});
this.dom(this.$stage.$document).bindDomEvent('click', function (e) {
if (e.which === 1) {
self.set({menuVisible: false});
}
});
},
_preventDefault: function (e) {
e.$.stopPropagation();
},
/***
* Closes the menu
*/
closeMenu: function () {
this.set('menuVisible', false);
},
/**
* Opens the menu
*/
openMenu: function () {
this.set('menuVisible', true);
},
/***
* Toggles the menu
*/
toggleMenu: function () {
this.set('menuVisible', !this.$.menuVisible);
}
});
}); |
const fastify = require('fastify')
const app = fastify();
app.register(require('fastify-cookie'));
app.register(require('fastify-csrf'));
app.route({
method: 'GET',
path: '/getter',
handler: async (req, reply) => { // OK
return 'hello';
}
})
// unprotected route
app.route({
method: 'POST',
path: '/',
handler: async (req, reply) => { // NOT OK - lacks CSRF protection
req.session.blah;
return req.body
}
})
app.route({
method: 'POST',
path: '/',
onRequest: app.csrfProtection,
handler: async (req, reply) => { // OK - has CSRF protection
return req.body
}
})
|
version https://git-lfs.github.com/spec/v1
oid sha256:e129014c062da6d1db792bc34673cb71b4fc809e603605472a3bec3c8fe4798a
size 6106
|
SystemJS.config({
baseURL: "/",
paths: {
"github:*": "jspm_packages/github/*",
"npm:*": "jspm_packages/npm/*",
"app/": "src/"
},
bundles: {
"build.js": [
"app/app.js",
"app/TestData.js",
"npm:react@15.0.1/react.js",
"npm:react@15.0.1.json",
"github:jspm/nodelibs-process@0.2.0-alpha/process.js",
"github:jspm/nodelibs-process@0.2.0-alpha.json",
"npm:react@15.0.1/lib/React.js",
"npm:fbjs@0.8.1/lib/warning.js",
"npm:fbjs@0.8.1.json",
"npm:fbjs@0.8.1/lib/emptyFunction.js",
"npm:react@15.0.1/lib/onlyChild.js",
"npm:fbjs@0.8.1/lib/invariant.js",
"npm:react@15.0.1/lib/ReactElement.js",
"npm:react@15.0.1/lib/canDefineProperty.js",
"npm:react@15.0.1/lib/ReactCurrentOwner.js",
"npm:object-assign@4.0.1/index.js",
"npm:object-assign@4.0.1.json",
"npm:react@15.0.1/lib/ReactVersion.js",
"npm:react@15.0.1/lib/ReactPropTypes.js",
"npm:react@15.0.1/lib/getIteratorFn.js",
"npm:react@15.0.1/lib/ReactPropTypeLocationNames.js",
"npm:react@15.0.1/lib/ReactElementValidator.js",
"npm:react@15.0.1/lib/ReactPropTypeLocations.js",
"npm:fbjs@0.8.1/lib/keyMirror.js",
"npm:react@15.0.1/lib/ReactDOMFactories.js",
"npm:fbjs@0.8.1/lib/mapObject.js",
"npm:react@15.0.1/lib/ReactClass.js",
"npm:fbjs@0.8.1/lib/keyOf.js",
"npm:fbjs@0.8.1/lib/emptyObject.js",
"npm:react@15.0.1/lib/ReactNoopUpdateQueue.js",
"npm:react@15.0.1/lib/ReactComponent.js",
"npm:react@15.0.1/lib/ReactInstrumentation.js",
"npm:react@15.0.1/lib/ReactDebugTool.js",
"npm:react@15.0.1/lib/ReactInvalidSetStateWarningDevTool.js",
"npm:react@15.0.1/lib/ReactChildren.js",
"npm:react@15.0.1/lib/traverseAllChildren.js",
"npm:react@15.0.1/lib/PooledClass.js",
"npm:systemjs-plugin-babel@0.0.9/babel-helpers/inherits.js",
"npm:systemjs-plugin-babel@0.0.9.json",
"npm:systemjs-plugin-babel@0.0.9/babel-helpers/possibleConstructorReturn.js",
"npm:systemjs-plugin-babel@0.0.9/babel-helpers/createClass.js",
"npm:systemjs-plugin-babel@0.0.9/babel-helpers/classCallCheck.js",
"app/LoginStatus.js",
"app/LoginForm.js",
"app/RegistrationForm.js",
"app/config.js",
"app/AuthService.js",
"npm:superlogin-client@0.2.0/lib/index.js",
"npm:superlogin-client@0.2.0.json",
"npm:events@1.1.0/events.js",
"npm:events@1.1.0.json",
"npm:debug-logger@0.4.1/debug-logger.js",
"npm:debug-logger@0.4.1.json",
"github:jspm/nodelibs-assert@0.2.0-alpha/assert.js",
"github:jspm/nodelibs-assert@0.2.0-alpha.json",
"github:jspm/nodelibs-util@0.2.0-alpha/util.js",
"github:jspm/nodelibs-util@0.2.0-alpha.json",
"github:jspm/nodelibs-util@0.2.0-alpha/isBufferBrowser.js",
"npm:debug-logger@0.4.1/stream-spy.js",
"npm:debug@2.2.0/browser.js",
"npm:debug@2.2.0.json",
"npm:debug@2.2.0/debug.js",
"npm:ms@0.7.1/index.js",
"npm:ms@0.7.1.json",
"npm:axios@0.9.1/index.js",
"npm:axios@0.9.1.json",
"npm:axios@0.9.1/lib/axios.js",
"npm:axios@0.9.1/lib/helpers/spread.js",
"npm:axios@0.9.1/lib/helpers/transformData.js",
"npm:axios@0.9.1/lib/utils.js",
"npm:axios@0.9.1/lib/helpers/bind.js",
"npm:axios@0.9.1/lib/helpers/combineURLs.js",
"npm:axios@0.9.1/lib/helpers/isAbsoluteURL.js",
"npm:axios@0.9.1/lib/core/InterceptorManager.js",
"npm:axios@0.9.1/lib/core/dispatchRequest.js",
"npm:axios@0.9.1/lib/adapters/xhr.js",
"npm:axios@0.9.1/lib/helpers/cookies.js",
"npm:axios@0.9.1/lib/helpers/btoa.js",
"npm:axios@0.9.1/lib/helpers/isURLSameOrigin.js",
"npm:axios@0.9.1/lib/helpers/parseHeaders.js",
"npm:axios@0.9.1/lib/helpers/buildURL.js",
"npm:axios@0.9.1/lib/defaults.js",
"github:jspm/nodelibs-events@0.2.0-alpha/events.js",
"github:jspm/nodelibs-events@0.2.0-alpha.json",
"github:pouchdb/pouchdb@5.3.2/dist/pouchdb.js",
"github:pouchdb/pouchdb@5.3.2.json",
"npm:react-dom@15.0.1/index.js",
"npm:react-dom@15.0.1.json",
"npm:react@15.0.1/lib/ReactDOM.js",
"npm:fbjs@0.8.1/lib/ExecutionEnvironment.js",
"npm:react@15.0.1/lib/renderSubtreeIntoContainer.js",
"npm:react@15.0.1/lib/ReactMount.js",
"npm:react@15.0.1/lib/shouldUpdateReactComponent.js",
"npm:react@15.0.1/lib/setInnerHTML.js",
"npm:react@15.0.1/lib/createMicrosoftUnsafeLocalFunction.js",
"npm:react@15.0.1/lib/instantiateReactComponent.js",
"npm:react@15.0.1/lib/ReactNativeComponent.js",
"npm:react@15.0.1/lib/ReactEmptyComponent.js",
"npm:react@15.0.1/lib/ReactCompositeComponent.js",
"npm:react@15.0.1/lib/ReactUpdateQueue.js",
"npm:react@15.0.1/lib/ReactUpdates.js",
"npm:react@15.0.1/lib/Transaction.js",
"npm:react@15.0.1/lib/ReactReconciler.js",
"npm:react@15.0.1/lib/ReactRef.js",
"npm:react@15.0.1/lib/ReactOwner.js",
"npm:react@15.0.1/lib/ReactPerf.js",
"npm:react@15.0.1/lib/ReactFeatureFlags.js",
"npm:react@15.0.1/lib/CallbackQueue.js",
"npm:react@15.0.1/lib/ReactInstanceMap.js",
"npm:react@15.0.1/lib/ReactNodeTypes.js",
"npm:react@15.0.1/lib/ReactErrorUtils.js",
"npm:react@15.0.1/lib/ReactComponentEnvironment.js",
"npm:react@15.0.1/lib/ReactMarkupChecksum.js",
"npm:react@15.0.1/lib/adler32.js",
"npm:react@15.0.1/lib/ReactDOMFeatureFlags.js",
"npm:react@15.0.1/lib/ReactDOMContainerInfo.js",
"npm:react@15.0.1/lib/validateDOMNesting.js",
"npm:react@15.0.1/lib/ReactDOMComponentTree.js",
"npm:react@15.0.1/lib/ReactDOMComponentFlags.js",
"npm:react@15.0.1/lib/DOMProperty.js",
"npm:react@15.0.1/lib/ReactBrowserEventEmitter.js",
"npm:react@15.0.1/lib/isEventSupported.js",
"npm:react@15.0.1/lib/getVendorPrefixedEventName.js",
"npm:react@15.0.1/lib/ViewportMetrics.js",
"npm:react@15.0.1/lib/ReactEventEmitterMixin.js",
"npm:react@15.0.1/lib/EventPluginHub.js",
"npm:react@15.0.1/lib/forEachAccumulated.js",
"npm:react@15.0.1/lib/accumulateInto.js",
"npm:react@15.0.1/lib/EventPluginUtils.js",
"npm:react@15.0.1/lib/EventConstants.js",
"npm:react@15.0.1/lib/EventPluginRegistry.js",
"npm:react@15.0.1/lib/DOMLazyTree.js",
"npm:react@15.0.1/lib/setTextContent.js",
"npm:react@15.0.1/lib/escapeTextContentForBrowser.js",
"npm:react@15.0.1/lib/getNativeComponentFromComposite.js",
"npm:react@15.0.1/lib/findDOMNode.js",
"npm:react@15.0.1/lib/ReactDefaultInjection.js",
"npm:react@15.0.1/lib/ReactDefaultPerf.js",
"npm:fbjs@0.8.1/lib/performanceNow.js",
"npm:fbjs@0.8.1/lib/performance.js",
"npm:react@15.0.1/lib/ReactDefaultPerfAnalysis.js",
"npm:react@15.0.1/lib/SimpleEventPlugin.js",
"npm:react@15.0.1/lib/getEventCharCode.js",
"npm:react@15.0.1/lib/SyntheticWheelEvent.js",
"npm:react@15.0.1/lib/SyntheticMouseEvent.js",
"npm:react@15.0.1/lib/getEventModifierState.js",
"npm:react@15.0.1/lib/SyntheticUIEvent.js",
"npm:react@15.0.1/lib/getEventTarget.js",
"npm:react@15.0.1/lib/SyntheticEvent.js",
"npm:react@15.0.1/lib/SyntheticTransitionEvent.js",
"npm:react@15.0.1/lib/SyntheticTouchEvent.js",
"npm:react@15.0.1/lib/SyntheticDragEvent.js",
"npm:react@15.0.1/lib/SyntheticKeyboardEvent.js",
"npm:react@15.0.1/lib/getEventKey.js",
"npm:react@15.0.1/lib/SyntheticFocusEvent.js",
"npm:react@15.0.1/lib/SyntheticClipboardEvent.js",
"npm:react@15.0.1/lib/SyntheticAnimationEvent.js",
"npm:react@15.0.1/lib/EventPropagators.js",
"npm:fbjs@0.8.1/lib/EventListener.js",
"npm:react@15.0.1/lib/SelectEventPlugin.js",
"npm:fbjs@0.8.1/lib/shallowEqual.js",
"npm:react@15.0.1/lib/isTextInputElement.js",
"npm:fbjs@0.8.1/lib/getActiveElement.js",
"npm:react@15.0.1/lib/ReactInputSelection.js",
"npm:fbjs@0.8.1/lib/focusNode.js",
"npm:fbjs@0.8.1/lib/containsNode.js",
"npm:fbjs@0.8.1/lib/isTextNode.js",
"npm:fbjs@0.8.1/lib/isNode.js",
"npm:react@15.0.1/lib/ReactDOMSelection.js",
"npm:react@15.0.1/lib/getTextContentAccessor.js",
"npm:react@15.0.1/lib/getNodeForCharacterOffset.js",
"npm:react@15.0.1/lib/SVGDOMPropertyConfig.js",
"npm:react@15.0.1/lib/ReactReconcileTransaction.js",
"npm:react@15.0.1/lib/ReactInjection.js",
"npm:react@15.0.1/lib/ReactEventListener.js",
"npm:fbjs@0.8.1/lib/getUnboundedScrollPosition.js",
"npm:react@15.0.1/lib/ReactDefaultBatchingStrategy.js",
"npm:react@15.0.1/lib/ReactDOMTextComponent.js",
"npm:react@15.0.1/lib/DOMChildrenOperations.js",
"npm:react@15.0.1/lib/ReactMultiChildUpdateTypes.js",
"npm:react@15.0.1/lib/Danger.js",
"npm:fbjs@0.8.1/lib/getMarkupWrap.js",
"npm:fbjs@0.8.1/lib/createNodesFromMarkup.js",
"npm:fbjs@0.8.1/lib/createArrayFromMixed.js",
"npm:react@15.0.1/lib/ReactDOMTreeTraversal.js",
"npm:react@15.0.1/lib/ReactDOMEmptyComponent.js",
"npm:react@15.0.1/lib/ReactDOMComponent.js",
"npm:react@15.0.1/lib/ReactMultiChild.js",
"npm:react@15.0.1/lib/flattenChildren.js",
"npm:react@15.0.1/lib/ReactChildReconciler.js",
"npm:react@15.0.1/lib/ReactDOMTextarea.js",
"npm:react@15.0.1/lib/LinkedValueUtils.js",
"npm:react@15.0.1/lib/DOMPropertyOperations.js",
"npm:react@15.0.1/lib/quoteAttributeValueForBrowser.js",
"npm:react@15.0.1/lib/ReactDOMInstrumentation.js",
"npm:react@15.0.1/lib/ReactDOMDebugTool.js",
"npm:react@15.0.1/lib/ReactDOMUnknownPropertyDevtool.js",
"npm:react@15.0.1/lib/ReactDOMSelect.js",
"npm:react@15.0.1/lib/ReactDOMOption.js",
"npm:react@15.0.1/lib/ReactDOMInput.js",
"npm:react@15.0.1/lib/ReactDOMButton.js",
"npm:react@15.0.1/lib/ReactComponentBrowserEnvironment.js",
"npm:react@15.0.1/lib/ReactDOMIDOperations.js",
"npm:react@15.0.1/lib/DOMNamespaces.js",
"npm:react@15.0.1/lib/CSSPropertyOperations.js",
"npm:fbjs@0.8.1/lib/memoizeStringOnly.js",
"npm:fbjs@0.8.1/lib/hyphenateStyleName.js",
"npm:fbjs@0.8.1/lib/hyphenate.js",
"npm:react@15.0.1/lib/dangerousStyleValue.js",
"npm:react@15.0.1/lib/CSSProperty.js",
"npm:fbjs@0.8.1/lib/camelizeStyleName.js",
"npm:fbjs@0.8.1/lib/camelize.js",
"npm:react@15.0.1/lib/AutoFocusUtils.js",
"npm:react@15.0.1/lib/HTMLDOMPropertyConfig.js",
"npm:react@15.0.1/lib/EnterLeaveEventPlugin.js",
"npm:react@15.0.1/lib/DefaultEventPluginOrder.js",
"npm:react@15.0.1/lib/ChangeEventPlugin.js",
"npm:react@15.0.1/lib/BeforeInputEventPlugin.js",
"npm:react@15.0.1/lib/SyntheticInputEvent.js",
"npm:react@15.0.1/lib/SyntheticCompositionEvent.js",
"npm:react@15.0.1/lib/FallbackCompositionState.js"
]
}
});
|
var config = require('../config');
var path = require('path');
module.exports = function (grunt) {
if (! config.theme) return;
var distPath = config.dist,
distThemePath = path.join(distPath, config.theme);
grunt.config('prettify', {
options: {
indent: 4,
indent_inner_html: false,
preserve_newlines: true,
max_preserve_newlines: 1,
brace_style: "condense",
unformatted: [ "a", "span", "i", "pre", "code" ]
},
all: {
expand: true,
cwd: distPath,
ext: '.html',
src: ['**/*.html'],
dest: distPath
},
theme: {
expand: true,
cwd: distThemePath,
ext: '.html',
src: ['**/*.html'],
dest: distThemePath
}
});
grunt.loadNpmTasks('grunt-prettify');
}; |
"use strict";
//recursive version of replaces
const replaces = require('./replaces');
module.exports = function(str, hash) {
var tmp = "";
do {
tmp = str;
str = replaces(str, hash);
} while(tmp != str);
return tmp;
};
|
define({
"_widgetLabel": "ネットワークのトレース",
"configError": "ウィジェットが適切に構成されていません。",
"geometryServiceURLNotFoundMSG": "ジオメトリ サービスの URL を取得できません",
"clearButtonValue": "解除",
"GPExecutionFailed": "トレースを完了できません。 もう一度お試しください。",
"backButtonValue": "戻る",
"exportToCSVSuccess": "CSV へのエクスポートが正常に完了しました。",
"lblInputLocTab": "入力ロケーション",
"lblBlockLocTab": "ブロック位置",
"lblInputLocation": "入力フィーチャ",
"lblBlockLocation": "ブロック フィーチャ",
"lblInputLocHeader": "入力位置 (0)",
"lblBlockLocHeader": "ブロック位置 (0)",
"inputTabTitle": "入力",
"outputTabTitle": "出力",
"exportSelectAllCheckBoxLabel": "すべて選択",
"lblSkipLocHeader": "スキップ位置 (0)",
"lblSkipLocation": "位置",
"lblSkipLocTab": "スキップ位置",
"skipAllLocationButtonLabel": "すべて位置をスキップ",
"confirmSkipAllLocationsMessage": "すべての位置がスキップされます。続行しますか?",
"locationAlreadySkippedMessage": "位置はすでにスキップされています",
"removeAllSkipLocationLabel": "すべて削除",
"newProjectOptionText": "新しいプロジェクト",
"selectProject": "プロジェクトの選択",
"saveButtonLabel": "保存",
"exportToCSVText": "CSV にエクスポート",
"editProjectAttributesToolTip": "プロジェクト属性の編集",
"projectNameLabel": "プロジェクト名",
"saveProjectPopupTitle": "保存",
"saveAsLabel": "名前を付けて保存",
"saveChangesMsg": "変更内容を <b>${loadProjectDropdownlabel} に保存するか、</b>新しいプロジェクトとして保存しますか?",
"creatingNewProjectErrorMessage": "新しいプロジェクトの作成中にエラーが発生しました。 もう一度お試しください。",
"projectNameFetchingErr": "既存のプロジェクト名の取得中にエラーが発生しました。 もう一度お試しください。",
"projectAttributeLoadingErr": "プロジェクト属性の読み込み中にエラーが発生しました。 もう一度お試しください。",
"attributeUpdatedMsg": "属性が正常に更新されました。",
"projectAttributeUpdatingErr": "プロジェクト属性の更新中にエラーが発生しました。",
"loadingProjectDetailsErrorMessage": "フラグ、バリア、スキップ位置の取得中にエラーが発生しました。 もう一度お試しください。",
"savingProjectDetailsErr": "プロジェクトの詳細の保存中にエラーが発生しました。 プロジェクトをもう一度保存してみてください。",
"updatingOutagePolygonErr": "停止ポリゴンの更新中にエラーが発生しました。 プロジェクトをもう一度保存してみてください。",
"deletingExistingPolygonErr": "既存の停止ポリゴンの削除中にエラーが発生しました。 プロジェクトをもう一度保存してみてください。",
"loadingProjectFeaturesErr": "プロジェクト フィーチャの読み込み中にエラーが発生しました。 プロジェクトをもう一度読み込んでください。",
"addingProjectFeaturesErr": "プロジェクト フィーチャの追加中にエラーが発生しました。 プロジェクトをもう一度保存してみてください。",
"deletingExistingProjectFeaturesErr": "既存のプロジェクト フィーチャの削除中にエラーが発生しました。 プロジェクトをもう一度保存してみてください。",
"projectNotFoundErr": "プロジェクトが見つかりません",
"projectLayersNotFound": "構成済みのプロジェクト設定レイヤーはマップ内で利用できません。 ウィジェットは「スケッチ モード」で読み込まれます。",
"fetchingOutagePolygonMessage": "停止ポリゴンの取得中にエラーが発生しました。 プロジェクトをもう一度読み込んでください。",
"projectNameExistsMessage": "プロジェクト名はすでに存在します。 一意のプロジェクト名を使用してください。",
"fetchingProjectNamesErrorMessage": "既存のプロジェクト名の取得中にエラーが発生しました。 プロジェクトをもう一度保存してみてください。",
"enterProjectNameMessage": "プロジェクト名を入力してください。",
"projectLengthErrorMessage": "プロジェクト名は次より大きくすることはできません",
"gpServiceNotAccessible": "このアカウントは、このトレースを実行するのに必要なサービスにアクセスできせん。",
"loadingClonedLayerErrorMessage": "クローン化されたフィーチャ レイヤーの読み込み中にエラーが発生しました。 もう一度お試しください。",
"addingFeatureInClonedLayerError": "クローン化されたフィーチャ レイヤーにグラフィックスを追加中にエラーが発生しました。 もう一度お試しください。",
"selectingFeatureInClonedLayerError": "クローン化されたフィーチャ レイヤー内のグラフィックスを選択中にエラーが発生しました。 もう一度お試しください。",
"filteredProjectError": "フィルター処理されたプロジェクトの詳細の取得を確認中にエラーが発生しました。 もう一度お試しください。",
"filteredProjectMessage": "選択したプロジェクト属性は、Web マップまたは別のウィジェットから適用されたフィルターのために利用できません。 フィルターを消去して、もう一度お試しください。",
"filteredProjectLoadMessage": "プロジェクトは使用できなくなりました。 アクティブなプロジェクトを選択してください。",
"defaultValueForRunButton": "実行",
"closeButtonLabel": "削除"
}); |
describe('ApplicationView', function(){
var view, model, $headerView;
beforeEach(function(){
$headerView = makeFakeHeader();
spyOn(window.NB, 'HeaderView').andReturn($headerView);
model = new window.NB.ApplicationModel();
view = new window.NB.ApplicationView({
model: model
});
});
it('should render a header', function(){
view.render();
expect($headerView.render).toHaveBeenCalled();
});
describe('setContent_', function(){
var $contentView, $fakeDiv;
beforeEach(function(){
$fakeDiv = document.createElement('div');
$fakeDiv.id = 'fake-div';
$contentView = jasmine.createSpyObj('ContentView', [
'render', 'remove'
]);
$contentView.render.andReturn($fakeDiv);
spyOn(model, 'set');
});
it('should update the content view', function(){
view.setContent_($contentView);
expect(view.contentView_).toBe($contentView);
expect(view.$('#fake-div')).not.toBeNull();
expect(model.set).toHaveBeenCalledWith({});
});
it('should remove the previous view', function(){
view.setContent_($contentView);
view.setContent_($contentView);
expect($contentView.remove.callCount).toEqual(1);
});
it('should update the app model with new attributes', function(){
var attrs = {'a': 1, 'b': 'test'};
view.setContent_($contentView, attrs);
expect(model.set).toHaveBeenCalledWith(attrs);
});
}); // describe('setContent_')
}); // describe('ApplicationView') |
"use strict";
define(['lib/cell', 'lib/utilities'],
function(cell) {
return function world(width, height) {
var that, tick_count, population,
population_grid, grid_width, grid_height;
that = this;
tick_count = 0;
population = [];
grid_width = width;
grid_height = height;
that.tickCount = function () {
return tick_count;
};
that.populationSize = function() {
var live_count = 0;
for(var i = 0; i < population.length; i++) {
if(population[i] != null && population[i].isAlive()) {
live_count += 1;
}
}
return live_count;
}
that.cellAge = function(x, y) {
return population_grid[x][y].age();
}
that.deadCellCount = function() {
var dead_count = 0;
for(var i = 0; i < population.length; i++) {
if(population[i] == null || !population[i].isAlive()) {
dead_count += 1;
}
}
return dead_count;
}
that.width = function() {
return width;
}
that.height = function() {
return height;
}
that.isCellDead = function(x, y) {
return population_grid[x][y] != null &&
!population_grid[x][y].isAlive();
}
that.isCellEmpty = function(x, y) {
return population_grid[x][y] == null;
}
that.isCellPopulated = function(x, y) {
return population_grid[x][y] != null &&
population_grid[x][y].isAlive();
}
that.populateCell = function(x, y) {
if(that.isCellEmpty(x, y)) {
var new_cell = cell(x, y);
population_grid[x][y] = new_cell;
population.push(new_cell);
} else if(that.isCellDead(x, y)) {
population_grid[x][y].resurrect();
}
}
that.reset = function() {
initialize();
};
that.killCell = function(x, y) {
population_grid[x][y].die();
}
that.seed = function(cells) {
for(var i = 0; i < cells.length; i++) {
var newX = cells[i].x;
var newY = cells[i].y;
population_grid[newX][newY].resurrect();
}
}
that.tick = function() {
var to_die = [];
var to_resurrect = [];
for(var i = 0; i < population.length; i++) {
population[i].tick();
var fate = decideCellFate(population[i]);
if(fate == 'resurrect') {
to_resurrect.push(population[i]);
} else if(fate == 'die') {
to_die.push(population[i]);
}
}
for(var i = 0; i < to_die.length; i++) {
to_die[i].die();
}
for(var i = 0; i < to_resurrect.length; i++) {
to_resurrect[i].resurrect();
}
tick_count += 1;
}
that.debug = function() {
printWorld();
}
// :: helper functions ::
var initialize = function initialize() {
tick_count = 0;
population = [];
initializeGrid();
}
var initializeGrid = function initializeGrid() {
population_grid = Array.matrix(grid_width, grid_height, null);
for(var i = 0; i < population_grid.length; i++) {
for(var j = 0; j < population_grid[0].length; j++) {
that.populateCell(i, j);
that.killCell(i, j);
}
}
}
var decideCellFate = function decideCellFate(c) {
var neighbour_count = 0;
if(hasLeftNeighbour(c)) neighbour_count += 1;
if(hasRightNeighbour(c)) neighbour_count += 1;
if(hasTopNeighbour(c)) neighbour_count += 1;
if(hasBottomNeighbour(c)) neighbour_count += 1;
if(hasBottomLeftNeighbour(c)) neighbour_count += 1;
if(hasBottomRightNeighbour(c)) neighbour_count += 1;
if(hasTopLeftNeighbour(c)) neighbour_count += 1;
if(hasTopRightNeighbour(c)) neighbour_count += 1;
if(!c.isAlive() && neighbour_count == 3) return 'resurrect';
if(!c.isAlive()) return 'die';
if(neighbour_count > 3) return 'die';
return neighbour_count >= 2 ? 'live' : 'die';
}
var hasTopLeftNeighbour = function hasTopLeftNeighbour(c) {
if(c.y() == 0) return false;
if(c.x() == 0) return false;
var neighbour = population_grid[c.x() - 1][c.y() - 1];
return neighbour.isAlive();
}
var hasTopRightNeighbour = function hasTopRightNeighbour(c) {
if(c.y() == 0) return false;
if(c.x() >= population_grid.length - 1) return false;
var neighbour = population_grid[c.x() + 1][c.y() - 1];
return neighbour.isAlive();
}
var hasBottomLeftNeighbour = function hasBottomLeftNeighbour(c) {
if(c.y() >= population_grid[0].length - 1) return false;
if(c.x() == 0) return false;
var neighbour = population_grid[c.x() - 1][c.y() + 1];
return neighbour.isAlive();
}
var hasBottomRightNeighbour = function hasBottomRightNeighbour(c) {
if(c.y() >= population_grid[0].length - 1) return false;
if(c.x() >= population_grid.length - 1) return false;
var neighbour = population_grid[c.x() + 1][c.y() + 1];
return neighbour.isAlive();
}
var hasLeftNeighbour = function hasLeftNeighbour(c) {
if(c.x() == 0) return false;
var neighbour = population_grid[c.x() - 1][c.y()];
return neighbour.isAlive();
}
var hasRightNeighbour = function hasRightNeighbour(c) {
if(c.x() >= population_grid.length - 1) return false;
var neighbour = population_grid[c.x() + 1][c.y()];
return neighbour.isAlive();
}
var hasBottomNeighbour = function hasBottomNeighbour(c) {
if(c.y() >= population_grid[0].length - 1) return false;
var neighbour = population_grid[c.x()][c.y() + 1];
return neighbour.isAlive();
}
var hasTopNeighbour = function hasTopNeighbour(c) {
if(c.y() == 0) return false;
var neighbour = population_grid[c.x()][c.y() - 1];
return neighbour.isAlive();
}
var printWorld = function printWorld() {
console.log('------------------the world----------------------');
console.log('tick: {t}'
.supplant({t: tick_count}));
console.log('population: {p}'
.supplant({p: populationSize()}));
for(var i = 0; i < population.length; i++) {
var c = population[i];
if(c.isAlive()) {
printCell(c);
}
}
console.log('------------------------------------------------');
}
var printNeighbours = function printNeighbours(c) {
console.log('has left neighbour? {v}'
.supplant({v: hasLeftNeighbour(c).toString()}));
console.log('has right neighbour? {v}'
.supplant({v: hasRightNeighbour(c).toString()}));
console.log('has bottom neighbour? {v}'
.supplant({v: hasBottomNeighbour(c).toString()}));
console.log('has top neighbour? {v}'
.supplant({v: hasTopNeighbour(c).toString()}));
}
var printCell = function printCell(c) {
console.log('cell ({x}, {y}) is alive? {a}'
.supplant({x: c.x(), y: c.y(), a: c.isAlive().toString()}));
}
// :: initialize state ::
initializeGrid();
return that;
}
});
|
// Open simple dialogs on top of an editor. Relies on dialog.css.
(function() {
function dialogDiv(cm, template, bottom) {
var wrap = cm.getWrapperElement();
var dialog;
dialog = wrap.appendChild(document.createElement("div"));
if (bottom) {
dialog.className = "CodeMirror-dialog CodeMirror-dialog-bottom";
} else {
dialog.className = "CodeMirror-dialog CodeMirror-dialog-top";
}
dialog.innerHTML = template;
return dialog;
}
CodeMirror.defineExtension("openDialog", function(template, callback, options) {
var dialog = dialogDiv(this, template, options && options.bottom);
var closed = false, me = this;
function close() {
if (closed) return;
closed = true;
dialog.parentNode.removeChild(dialog);
}
var inp = dialog.getElementsByTagName("input")[0], button;
if (inp) {
CodeMirror.on(inp, "keydown", function(e) {
if (options && options.onKeyDown && options.onKeyDown(e, inp.value, close)) { return; }
if (e.keyCode == 13 || e.keyCode == 27) {
CodeMirror.e_stop(e);
close();
me.focus();
if (e.keyCode == 13) callback(inp.value);
}
});
if (options && options.onKeyUp) {
CodeMirror.on(inp, "keyup", function(e) {options.onKeyUp(e, inp.value, close);});
}
if (options && options.value) inp.value = options.value;
inp.focus();
CodeMirror.on(inp, "blur", close);
} else if (button = dialog.getElementsByTagName("button")[0]) {
CodeMirror.on(button, "click", function() {
close();
me.focus();
});
button.focus();
CodeMirror.on(button, "blur", close);
}
return close;
});
CodeMirror.defineExtension("openConfirm", function(template, callbacks, options) {
var dialog = dialogDiv(this, template, options && options.bottom);
var buttons = dialog.getElementsByTagName("button");
var closed = false, me = this, blurring = 1;
function close() {
if (closed) return;
closed = true;
dialog.parentNode.removeChild(dialog);
me.focus();
}
buttons[0].focus();
for (var i = 0; i < buttons.length; ++i) {
var b = buttons[i];
(function(callback) {
CodeMirror.on(b, "click", function(e) {
CodeMirror.e_preventDefault(e);
close();
if (callback) callback(me);
});
})(callbacks[i]);
CodeMirror.on(b, "blur", function() {
--blurring;
setTimeout(function() { if (blurring <= 0) close(); }, 200);
});
CodeMirror.on(b, "focus", function() { ++blurring; });
}
});
})(); |
version https://git-lfs.github.com/spec/v1
oid sha256:18f79c814cedd90f003333f3ed44498abb9b5788bd81518436ebc9059d0afe94
size 657
|
import { PromiseObject } from "ember-data/system/promise-proxies";
import Errors from "ember-data/system/model/errors";
/**
@module ember-data
*/
var get = Ember.get;
function intersection (array1, array2) {
var result = [];
array1.forEach((element) => {
if (array2.indexOf(element) >= 0) {
result.push(element);
}
});
return result;
}
var RESERVED_MODEL_PROPS = [
'currentState', 'data', 'store'
];
var retrieveFromCurrentState = Ember.computed('currentState', function(key) {
return get(this._internalModel.currentState, key);
}).readOnly();
/**
The model class that all Ember Data records descend from.
This is the public API of Ember Data models. If you are using Ember Data
in your application, this is the class you should use.
If you are working on Ember Data internals, you most likely want to be dealing
with `InternalModel`
@class Model
@namespace DS
@extends Ember.Object
@uses Ember.Evented
*/
var Model = Ember.Object.extend(Ember.Evented, {
_recordArrays: undefined,
_relationships: undefined,
_internalModel: null,
store: null,
/**
If this property is `true` the record is in the `empty`
state. Empty is the first state all records enter after they have
been created. Most records created by the store will quickly
transition to the `loading` state if data needs to be fetched from
the server or the `created` state if the record is created on the
client. A record can also enter the empty state if the adapter is
unable to locate the record.
@property isEmpty
@type {Boolean}
@readOnly
*/
isEmpty: retrieveFromCurrentState,
/**
If this property is `true` the record is in the `loading` state. A
record enters this state when the store asks the adapter for its
data. It remains in this state until the adapter provides the
requested data.
@property isLoading
@type {Boolean}
@readOnly
*/
isLoading: retrieveFromCurrentState,
/**
If this property is `true` the record is in the `loaded` state. A
record enters this state when its data is populated. Most of a
record's lifecycle is spent inside substates of the `loaded`
state.
Example
```javascript
var record = store.createRecord('model');
record.get('isLoaded'); // true
store.find('model', 1).then(function(model) {
model.get('isLoaded'); // true
});
```
@property isLoaded
@type {Boolean}
@readOnly
*/
isLoaded: retrieveFromCurrentState,
/**
If this property is `true` the record is in the `dirty` state. The
record has local changes that have not yet been saved by the
adapter. This includes records that have been created (but not yet
saved) or deleted.
Example
```javascript
var record = store.createRecord('model');
record.get('isDirty'); // true
store.find('model', 1).then(function(model) {
model.get('isDirty'); // false
model.set('foo', 'some value');
model.get('isDirty'); // true
});
```
@property isDirty
@type {Boolean}
@readOnly
@deprecated
*/
isDirty: Ember.computed('currentState.isDirty', function() {
Ember.deprecate('DS.Model#isDirty has been deprecated please use hasDirtyAttributes instead');
return this.get('currentState.isDirty');
}),
/**
If this property is `true` the record is in the `dirty` state. The
record has local changes that have not yet been saved by the
adapter. This includes records that have been created (but not yet
saved) or deleted.
Example
```javascript
var record = store.createRecord('model');
record.get('hasDirtyAttributes'); // true
store.find('model', 1).then(function(model) {
model.get('hasDirtyAttributes'); // false
model.set('foo', 'some value');
model.get('hasDirtyAttributes'); // true
});
```
@property hasDirtyAttributes
@type {Boolean}
@readOnly
*/
hasDirtyAttributes: Ember.computed('currentState.isDirty', function() {
return this.get('currentState.isDirty');
}),
/**
If this property is `true` the record is in the `saving` state. A
record enters the saving state when `save` is called, but the
adapter has not yet acknowledged that the changes have been
persisted to the backend.
Example
```javascript
var record = store.createRecord('model');
record.get('isSaving'); // false
var promise = record.save();
record.get('isSaving'); // true
promise.then(function() {
record.get('isSaving'); // false
});
```
@property isSaving
@type {Boolean}
@readOnly
*/
isSaving: retrieveFromCurrentState,
/**
If this property is `true` the record is in the `deleted` state
and has been marked for deletion. When `isDeleted` is true and
`isDirty` is true, the record is deleted locally but the deletion
was not yet persisted. When `isSaving` is true, the change is
in-flight. When both `isDirty` and `isSaving` are false, the
change has persisted.
Example
```javascript
var record = store.createRecord('model');
record.get('isDeleted'); // false
record.deleteRecord();
// Locally deleted
record.get('isDeleted'); // true
record.get('isDirty'); // true
record.get('isSaving'); // false
// Persisting the deletion
var promise = record.save();
record.get('isDeleted'); // true
record.get('isSaving'); // true
// Deletion Persisted
promise.then(function() {
record.get('isDeleted'); // true
record.get('isSaving'); // false
record.get('isDirty'); // false
});
```
@property isDeleted
@type {Boolean}
@readOnly
*/
isDeleted: retrieveFromCurrentState,
/**
If this property is `true` the record is in the `new` state. A
record will be in the `new` state when it has been created on the
client and the adapter has not yet report that it was successfully
saved.
Example
```javascript
var record = store.createRecord('model');
record.get('isNew'); // true
record.save().then(function(model) {
model.get('isNew'); // false
});
```
@property isNew
@type {Boolean}
@readOnly
*/
isNew: retrieveFromCurrentState,
/**
If this property is `true` the record is in the `valid` state.
A record will be in the `valid` state when the adapter did not report any
server-side validation failures.
@property isValid
@type {Boolean}
@readOnly
*/
isValid: retrieveFromCurrentState,
/**
If the record is in the dirty state this property will report what
kind of change has caused it to move into the dirty
state. Possible values are:
- `created` The record has been created by the client and not yet saved to the adapter.
- `updated` The record has been updated by the client and not yet saved to the adapter.
- `deleted` The record has been deleted by the client and not yet saved to the adapter.
Example
```javascript
var record = store.createRecord('model');
record.get('dirtyType'); // 'created'
```
@property dirtyType
@type {String}
@readOnly
*/
dirtyType: retrieveFromCurrentState,
/**
If `true` the adapter reported that it was unable to save local
changes to the backend for any reason other than a server-side
validation error.
Example
```javascript
record.get('isError'); // false
record.set('foo', 'valid value');
record.save().then(null, function() {
record.get('isError'); // true
});
```
@property isError
@type {Boolean}
@readOnly
*/
isError: false,
/**
If `true` the store is attempting to reload the record form the adapter.
Example
```javascript
record.get('isReloading'); // false
record.reload();
record.get('isReloading'); // true
```
@property isReloading
@type {Boolean}
@readOnly
*/
isReloading: false,
/**
All ember models have an id property. This is an identifier
managed by an external source. These are always coerced to be
strings before being used internally. Note when declaring the
attributes for a model it is an error to declare an id
attribute.
```javascript
var record = store.createRecord('model');
record.get('id'); // null
store.find('model', 1).then(function(model) {
model.get('id'); // '1'
});
```
@property id
@type {String}
*/
id: null,
/**
@property currentState
@private
@type {Object}
*/
/**
When the record is in the `invalid` state this object will contain
any errors returned by the adapter. When present the errors hash
contains keys corresponding to the invalid property names
and values which are arrays of Javascript objects with two keys:
- `message` A string containing the error message from the backend
- `attribute` The name of the property associated with this error message
```javascript
record.get('errors.length'); // 0
record.set('foo', 'invalid value');
record.save().catch(function() {
record.get('errors').get('foo');
// [{message: 'foo should be a number.', attribute: 'foo'}]
});
```
The `errors` property us useful for displaying error messages to
the user.
```handlebars
<label>Username: {{input value=username}} </label>
{{#each model.errors.username as |error|}}
<div class="error">
{{error.message}}
</div>
{{/each}}
<label>Email: {{input value=email}} </label>
{{#each model.errors.email as |error|}}
<div class="error">
{{error.message}}
</div>
{{/each}}
```
You can also access the special `messages` property on the error
object to get an array of all the error strings.
```handlebars
{{#each model.errors.messages as |message|}}
<div class="error">
{{message}}
</div>
{{/each}}
```
@property errors
@type {DS.Errors}
*/
errors: Ember.computed(function() {
let errors = Errors.create();
errors.registerHandlers(this._internalModel,
function() {
this.send('becameInvalid');
},
function() {
this.send('becameValid');
});
return errors;
}).readOnly(),
/**
Create a JSON representation of the record, using the serialization
strategy of the store's adapter.
`serialize` takes an optional hash as a parameter, currently
supported options are:
- `includeId`: `true` if the record's ID should be included in the
JSON representation.
@method serialize
@param {Object} options
@return {Object} an object whose values are primitive JSON values only
*/
serialize: function(options) {
return this.store.serialize(this, options);
},
/**
Use [DS.JSONSerializer](DS.JSONSerializer.html) to
get the JSON representation of a record.
`toJSON` takes an optional hash as a parameter, currently
supported options are:
- `includeId`: `true` if the record's ID should be included in the
JSON representation.
@method toJSON
@param {Object} options
@return {Object} A JSON representation of the object.
*/
toJSON: function(options) {
// container is for lazy transform lookups
var serializer = this.store.serializerFor('-default');
var snapshot = this._internalModel.createSnapshot();
return serializer.serialize(snapshot, options);
},
/**
Fired when the record is ready to be interacted with,
that is either loaded from the server or created locally.
@event ready
*/
ready: Ember.K,
/**
Fired when the record is loaded from the server.
@event didLoad
*/
didLoad: Ember.K,
/**
Fired when the record is updated.
@event didUpdate
*/
didUpdate: Ember.K,
/**
Fired when a new record is commited to the server.
@event didCreate
*/
didCreate: Ember.K,
/**
Fired when the record is deleted.
@event didDelete
*/
didDelete: Ember.K,
/**
Fired when the record becomes invalid.
@event becameInvalid
*/
becameInvalid: Ember.K,
/**
Fired when the record enters the error state.
@event becameError
*/
becameError: Ember.K,
/**
Fired when the record is rolled back.
@event rolledBack
*/
rolledBack: Ember.K,
/**
@property data
@private
@type {Object}
*/
data: Ember.computed.readOnly('_internalModel._data'),
//TODO Do we want to deprecate these?
/**
@method send
@private
@param {String} name
@param {Object} context
*/
send: function(name, context) {
return this._internalModel.send(name, context);
},
/**
@method transitionTo
@private
@param {String} name
*/
transitionTo: function(name) {
return this._internalModel.transitionTo(name);
},
/**
Marks the record as deleted but does not save it. You must call
`save` afterwards if you want to persist it. You might use this
method if you want to allow the user to still `rollbackAttributes()`
after a delete it was made.
Example
```app/routes/model/delete.js
import Ember from 'ember';
export default Ember.Route.extend({
actions: {
softDelete: function() {
this.controller.get('model').deleteRecord();
},
confirm: function() {
this.controller.get('model').save();
},
undo: function() {
this.controller.get('model').rollbackAttributes();
}
}
});
```
@method deleteRecord
*/
deleteRecord: function() {
this._internalModel.deleteRecord();
},
/**
Same as `deleteRecord`, but saves the record immediately.
Example
```app/routes/model/delete.js
import Ember from 'ember';
export default Ember.Route.extend({
actions: {
delete: function() {
var controller = this.controller;
controller.get('model').destroyRecord().then(function() {
controller.transitionToRoute('model.index');
});
}
}
});
```
@method destroyRecord
@param {Object} options
@return {Promise} a promise that will be resolved when the adapter returns
successfully or rejected if the adapter returns with an error.
*/
destroyRecord: function(options) {
this.deleteRecord();
return this.save(options);
},
/**
@method unloadRecord
@private
*/
unloadRecord: function() {
if (this.isDestroyed) { return; }
this._internalModel.unloadRecord();
},
/**
@method _notifyProperties
@private
*/
_notifyProperties: function(keys) {
Ember.beginPropertyChanges();
var key;
for (var i = 0, length = keys.length; i < length; i++) {
key = keys[i];
this.notifyPropertyChange(key);
}
Ember.endPropertyChanges();
},
/**
Returns an object, whose keys are changed properties, and value is
an [oldProp, newProp] array.
Example
```app/models/mascot.js
import DS from 'ember-data';
export default DS.Model.extend({
name: attr('string')
});
```
```javascript
var mascot = store.createRecord('mascot');
mascot.changedAttributes(); // {}
mascot.set('name', 'Tomster');
mascot.changedAttributes(); // {name: [undefined, 'Tomster']}
```
@method changedAttributes
@return {Object} an object, whose keys are changed properties,
and value is an [oldProp, newProp] array.
*/
changedAttributes: function() {
var oldData = get(this._internalModel, '_data');
var newData = get(this._internalModel, '_attributes');
var diffData = Object.create(null);
var newDataKeys = Object.keys(newData);
for (let i = 0, length = newDataKeys.length; i < length; i++) {
let key = newDataKeys[i];
diffData[key] = [oldData[key], newData[key]];
}
return diffData;
},
//TODO discuss with tomhuda about events/hooks
//Bring back as hooks?
/**
@method adapterWillCommit
@private
adapterWillCommit: function() {
this.send('willCommit');
},
/**
@method adapterDidDirty
@private
adapterDidDirty: function() {
this.send('becomeDirty');
this.updateRecordArraysLater();
},
*/
/**
If the model `isDirty` this function will discard any unsaved
changes. If the model `isNew` it will be removed from the store.
Example
```javascript
record.get('name'); // 'Untitled Document'
record.set('name', 'Doc 1');
record.get('name'); // 'Doc 1'
record.rollback();
record.get('name'); // 'Untitled Document'
```
@method rollback
@deprecated Use `rollbackAttributes()` instead
*/
rollback: function() {
Ember.deprecate('Using model.rollback() has been deprecated. Use model.rollbackAttributes() to discard any unsaved changes to a model.');
this.rollbackAttributes();
},
/**
If the model `isDirty` this function will discard any unsaved
changes. If the model `isNew` it will be removed from the store.
Example
```javascript
record.get('name'); // 'Untitled Document'
record.set('name', 'Doc 1');
record.get('name'); // 'Doc 1'
record.rollbackAttributes();
record.get('name'); // 'Untitled Document'
```
@method rollbackAttributes
*/
rollbackAttributes: function() {
this._internalModel.rollbackAttributes();
},
/*
@method _createSnapshot
@private
*/
_createSnapshot: function() {
return this._internalModel.createSnapshot();
},
toStringExtension: function() {
return get(this, 'id');
},
/**
Save the record and persist any changes to the record to an
external source via the adapter.
Example
```javascript
record.set('name', 'Tomster');
record.save().then(function() {
// Success callback
}, function() {
// Error callback
});
```
@method save
@param {Object} options
@return {Promise} a promise that will be resolved when the adapter returns
successfully or rejected if the adapter returns with an error.
*/
save: function(options) {
return PromiseObject.create({
promise: this._internalModel.save(options).then(() => this)
});
},
/**
Reload the record from the adapter.
This will only work if the record has already finished loading
and has not yet been modified (`isLoaded` but not `isDirty`,
or `isSaving`).
Example
```app/routes/model/view.js
import Ember from 'ember';
export default Ember.Route.extend({
actions: {
reload: function() {
this.controller.get('model').reload().then(function(model) {
// do something with the reloaded model
});
}
}
});
```
@method reload
@return {Promise} a promise that will be resolved with the record when the
adapter returns successfully or rejected if the adapter returns
with an error.
*/
reload: function() {
return PromiseObject.create({
promise: this._internalModel.reload().then(() => this)
});
},
/**
Override the default event firing from Ember.Evented to
also call methods with the given name.
@method trigger
@private
@param {String} name
*/
trigger: function(name) {
var length = arguments.length;
var args = new Array(length - 1);
for (var i = 1; i < length; i++) {
args[i - 1] = arguments[i];
}
Ember.tryInvoke(this, name, args);
this._super(...arguments);
},
willDestroy: function() {
//TODO Move!
this._super(...arguments);
this._internalModel.clearRelationships();
this._internalModel.recordObjectWillDestroy();
//TODO should we set internalModel to null here?
},
// This is a temporary solution until we refactor DS.Model to not
// rely on the data property.
willMergeMixin: function(props) {
var constructor = this.constructor;
Ember.assert('`' + intersection(Ember.keys(props), RESERVED_MODEL_PROPS)[0] + '` is a reserved property name on DS.Model objects. Please choose a different property name for ' + constructor.toString(), !intersection(Ember.keys(props), RESERVED_MODEL_PROPS)[0]);
},
attr: function() {
Ember.assert("The `attr` method is not available on DS.Model, a DS.Snapshot was probably expected. Are you passing a DS.Model instead of a DS.Snapshot to your serializer?", false);
},
belongsTo: function() {
Ember.assert("The `belongsTo` method is not available on DS.Model, a DS.Snapshot was probably expected. Are you passing a DS.Model instead of a DS.Snapshot to your serializer?", false);
},
hasMany: function() {
Ember.assert("The `hasMany` method is not available on DS.Model, a DS.Snapshot was probably expected. Are you passing a DS.Model instead of a DS.Snapshot to your serializer?", false);
}
});
Model.reopenClass({
/**
Alias DS.Model's `create` method to `_create`. This allows us to create DS.Model
instances from within the store, but if end users accidentally call `create()`
(instead of `createRecord()`), we can raise an error.
@method _create
@private
@static
*/
_create: Model.create,
/**
Override the class' `create()` method to raise an error. This
prevents end users from inadvertently calling `create()` instead
of `createRecord()`. The store is still able to create instances
by calling the `_create()` method. To create an instance of a
`DS.Model` use [store.createRecord](DS.Store.html#method_createRecord).
@method create
@private
@static
*/
create: function() {
throw new Ember.Error("You should not call `create` on a model. Instead, call `store.createRecord` with the attributes you would like to set.");
},
/**
Represents the model's class name as a string. This can be used to look up the model through
DS.Store's modelFor method.
`modelName` is generated for you by Ember Data. It will be a lowercased, dasherized string.
For example:
```javascript
store.modelFor('post').modelName; // 'post'
store.modelFor('blog-post').modelName; // 'blog-post'
```
The most common place you'll want to access `modelName` is in your serializer's `payloadKeyFromModelName` method. For example, to change payload
keys to underscore (instead of dasherized), you might use the following code:
```javascript
export default var PostSerializer = DS.RESTSerializer.extend({
payloadKeyFromModelName: function(modelName) {
return Ember.String.underscore(modelName);
}
});
```
@property
@type String
@readonly
*/
modelName: null
});
export default Model;
|
var NAVTREEINDEX13 =
{
"group___c_m_s_i_s___s_c_b.html#ga58686b88f94f789d4e6f429fe1ff58cf":[2,12,2,246],
"group___c_m_s_i_s___s_c_b.html#ga58686b88f94f789d4e6f429fe1ff58cf":[2,12,2,247],
"group___c_m_s_i_s___s_c_b.html#ga58686b88f94f789d4e6f429fe1ff58cf":[2,12,2,249],
"group___c_m_s_i_s___s_c_b.html#ga58686b88f94f789d4e6f429fe1ff58cf":[4,0,0,1,0,10,46],
"group___c_m_s_i_s___s_c_b.html#ga58686b88f94f789d4e6f429fe1ff58cf":[2,12,2,248],
"group___c_m_s_i_s___s_c_b.html#ga58686b88f94f789d4e6f429fe1ff58cf":[2,12,2,250],
"group___c_m_s_i_s___s_c_b.html#ga58686b88f94f789d4e6f429fe1ff58cf":[4,0,0,1,0,11,48],
"group___c_m_s_i_s___s_c_b.html#ga58686b88f94f789d4e6f429fe1ff58cf":[4,0,0,1,0,12,226],
"group___c_m_s_i_s___s_c_b.html#ga58686b88f94f789d4e6f429fe1ff58cf":[4,0,0,1,0,13,229],
"group___c_m_s_i_s___s_c_b.html#ga58686b88f94f789d4e6f429fe1ff58cf":[4,0,0,1,0,15,284],
"group___c_m_s_i_s___s_c_b.html#ga58686b88f94f789d4e6f429fe1ff58cf":[4,0,0,1,0,19,46],
"group___c_m_s_i_s___s_c_b.html#ga58686b88f94f789d4e6f429fe1ff58cf":[4,0,0,1,0,20,226],
"group___c_m_s_i_s___s_c_b.html#ga5be00464e6789da9619947d67d2a1529":[2,12,2,306],
"group___c_m_s_i_s___s_c_b.html#ga5be00464e6789da9619947d67d2a1529":[4,0,0,1,0,15,304],
"group___c_m_s_i_s___s_c_b.html#ga5c97d4cc05972dc80963e74eb2332841":[4,0,0,1,0,15,197],
"group___c_m_s_i_s___s_c_b.html#ga5c97d4cc05972dc80963e74eb2332841":[2,12,2,2],
"group___c_m_s_i_s___s_c_b.html#ga5d2fc7c04a8aaedff19bd4ff6de187eb":[4,0,0,1,0,15,350],
"group___c_m_s_i_s___s_c_b.html#ga5d2fc7c04a8aaedff19bd4ff6de187eb":[2,12,2,514],
"group___c_m_s_i_s___s_c_b.html#ga6095a7acfbad66f52822b1392be88652":[2,12,2,635],
"group___c_m_s_i_s___s_c_b.html#ga6095a7acfbad66f52822b1392be88652":[2,12,2,636],
"group___c_m_s_i_s___s_c_b.html#ga6095a7acfbad66f52822b1392be88652":[2,12,2,637],
"group___c_m_s_i_s___s_c_b.html#ga6095a7acfbad66f52822b1392be88652":[2,12,2,638],
"group___c_m_s_i_s___s_c_b.html#ga6095a7acfbad66f52822b1392be88652":[2,12,2,639],
"group___c_m_s_i_s___s_c_b.html#ga6095a7acfbad66f52822b1392be88652":[2,12,2,640],
"group___c_m_s_i_s___s_c_b.html#ga6095a7acfbad66f52822b1392be88652":[2,12,2,641],
"group___c_m_s_i_s___s_c_b.html#ga6095a7acfbad66f52822b1392be88652":[4,0,0,1,0,10,77],
"group___c_m_s_i_s___s_c_b.html#ga6095a7acfbad66f52822b1392be88652":[4,0,0,1,0,11,79],
"group___c_m_s_i_s___s_c_b.html#ga6095a7acfbad66f52822b1392be88652":[4,0,0,1,0,12,293],
"group___c_m_s_i_s___s_c_b.html#ga6095a7acfbad66f52822b1392be88652":[4,0,0,1,0,13,296],
"group___c_m_s_i_s___s_c_b.html#ga6095a7acfbad66f52822b1392be88652":[4,0,0,1,0,15,381],
"group___c_m_s_i_s___s_c_b.html#ga6095a7acfbad66f52822b1392be88652":[4,0,0,1,0,19,77],
"group___c_m_s_i_s___s_c_b.html#ga6095a7acfbad66f52822b1392be88652":[4,0,0,1,0,20,293],
"group___c_m_s_i_s___s_c_b.html#ga609edf8f50bc49adb51ae28bcecefe1f":[4,0,0,1,0,12,233],
"group___c_m_s_i_s___s_c_b.html#ga609edf8f50bc49adb51ae28bcecefe1f":[4,0,0,1,0,13,236],
"group___c_m_s_i_s___s_c_b.html#ga609edf8f50bc49adb51ae28bcecefe1f":[2,12,2,307],
"group___c_m_s_i_s___s_c_b.html#ga609edf8f50bc49adb51ae28bcecefe1f":[2,12,2,308],
"group___c_m_s_i_s___s_c_b.html#ga609edf8f50bc49adb51ae28bcecefe1f":[2,12,2,309],
"group___c_m_s_i_s___s_c_b.html#ga609edf8f50bc49adb51ae28bcecefe1f":[2,12,2,310],
"group___c_m_s_i_s___s_c_b.html#ga609edf8f50bc49adb51ae28bcecefe1f":[4,0,0,1,0,15,305],
"group___c_m_s_i_s___s_c_b.html#ga609edf8f50bc49adb51ae28bcecefe1f":[4,0,0,1,0,20,233],
"group___c_m_s_i_s___s_c_b.html#ga634bb0b270954a68757c86c517de948b":[2,12,2,299],
"group___c_m_s_i_s___s_c_b.html#ga634bb0b270954a68757c86c517de948b":[4,0,0,1,0,15,297],
"group___c_m_s_i_s___s_c_b.html#ga634c0f69a233475289023ae5cb158fdf":[4,0,0,1,0,12,291],
"group___c_m_s_i_s___s_c_b.html#ga634c0f69a233475289023ae5cb158fdf":[4,0,0,1,0,13,294],
"group___c_m_s_i_s___s_c_b.html#ga634c0f69a233475289023ae5cb158fdf":[4,0,0,1,0,15,379],
"group___c_m_s_i_s___s_c_b.html#ga634c0f69a233475289023ae5cb158fdf":[4,0,0,1,0,20,291],
"group___c_m_s_i_s___s_c_b.html#ga634c0f69a233475289023ae5cb158fdf":[2,12,2,627],
"group___c_m_s_i_s___s_c_b.html#ga634c0f69a233475289023ae5cb158fdf":[2,12,2,628],
"group___c_m_s_i_s___s_c_b.html#ga634c0f69a233475289023ae5cb158fdf":[2,12,2,629],
"group___c_m_s_i_s___s_c_b.html#ga634c0f69a233475289023ae5cb158fdf":[2,12,2,630],
"group___c_m_s_i_s___s_c_b.html#ga6560d97ed043bc01152a7247bafa3157":[4,0,0,1,0,12,245],
"group___c_m_s_i_s___s_c_b.html#ga6560d97ed043bc01152a7247bafa3157":[4,0,0,1,0,13,248],
"group___c_m_s_i_s___s_c_b.html#ga6560d97ed043bc01152a7247bafa3157":[4,0,0,1,0,15,325],
"group___c_m_s_i_s___s_c_b.html#ga6560d97ed043bc01152a7247bafa3157":[2,12,2,363],
"group___c_m_s_i_s___s_c_b.html#ga6560d97ed043bc01152a7247bafa3157":[2,12,2,364],
"group___c_m_s_i_s___s_c_b.html#ga6560d97ed043bc01152a7247bafa3157":[2,12,2,365],
"group___c_m_s_i_s___s_c_b.html#ga6560d97ed043bc01152a7247bafa3157":[2,12,2,366],
"group___c_m_s_i_s___s_c_b.html#ga6560d97ed043bc01152a7247bafa3157":[4,0,0,1,0,20,245],
"group___c_m_s_i_s___s_c_b.html#ga677c23749c4d348f30fb471d1223e783":[4,0,0,1,0,12,279],
"group___c_m_s_i_s___s_c_b.html#ga677c23749c4d348f30fb471d1223e783":[4,0,0,1,0,13,282],
"group___c_m_s_i_s___s_c_b.html#ga677c23749c4d348f30fb471d1223e783":[4,0,0,1,0,15,367],
"group___c_m_s_i_s___s_c_b.html#ga677c23749c4d348f30fb471d1223e783":[4,0,0,1,0,20,279],
"group___c_m_s_i_s___s_c_b.html#ga677c23749c4d348f30fb471d1223e783":[2,12,2,579],
"group___c_m_s_i_s___s_c_b.html#ga677c23749c4d348f30fb471d1223e783":[2,12,2,580],
"group___c_m_s_i_s___s_c_b.html#ga677c23749c4d348f30fb471d1223e783":[2,12,2,581],
"group___c_m_s_i_s___s_c_b.html#ga677c23749c4d348f30fb471d1223e783":[2,12,2,582],
"group___c_m_s_i_s___s_c_b.html#ga685b4564a8760b4506f14ec4307b7251":[4,0,0,1,0,12,284],
"group___c_m_s_i_s___s_c_b.html#ga685b4564a8760b4506f14ec4307b7251":[4,0,0,1,0,13,287],
"group___c_m_s_i_s___s_c_b.html#ga685b4564a8760b4506f14ec4307b7251":[4,0,0,1,0,15,372],
"group___c_m_s_i_s___s_c_b.html#ga685b4564a8760b4506f14ec4307b7251":[4,0,0,1,0,20,284],
"group___c_m_s_i_s___s_c_b.html#ga685b4564a8760b4506f14ec4307b7251":[2,12,2,599],
"group___c_m_s_i_s___s_c_b.html#ga685b4564a8760b4506f14ec4307b7251":[2,12,2,600],
"group___c_m_s_i_s___s_c_b.html#ga685b4564a8760b4506f14ec4307b7251":[2,12,2,601],
"group___c_m_s_i_s___s_c_b.html#ga685b4564a8760b4506f14ec4307b7251":[2,12,2,602],
"group___c_m_s_i_s___s_c_b.html#ga68c96ad594af70c007923979085c99e0":[2,12,2,159],
"group___c_m_s_i_s___s_c_b.html#ga68c96ad594af70c007923979085c99e0":[2,12,2,160],
"group___c_m_s_i_s___s_c_b.html#ga68c96ad594af70c007923979085c99e0":[2,12,2,161],
"group___c_m_s_i_s___s_c_b.html#ga68c96ad594af70c007923979085c99e0":[2,12,2,162],
"group___c_m_s_i_s___s_c_b.html#ga68c96ad594af70c007923979085c99e0":[2,12,2,163],
"group___c_m_s_i_s___s_c_b.html#ga68c96ad594af70c007923979085c99e0":[2,12,2,164],
"group___c_m_s_i_s___s_c_b.html#ga68c96ad594af70c007923979085c99e0":[2,12,2,165],
"group___c_m_s_i_s___s_c_b.html#ga68c96ad594af70c007923979085c99e0":[4,0,0,1,0,10,41],
"group___c_m_s_i_s___s_c_b.html#ga68c96ad594af70c007923979085c99e0":[4,0,0,1,0,11,43],
"group___c_m_s_i_s___s_c_b.html#ga68c96ad594af70c007923979085c99e0":[4,0,0,1,0,12,213],
"group___c_m_s_i_s___s_c_b.html#ga68c96ad594af70c007923979085c99e0":[4,0,0,1,0,13,216],
"group___c_m_s_i_s___s_c_b.html#ga68c96ad594af70c007923979085c99e0":[4,0,0,1,0,15,253],
"group___c_m_s_i_s___s_c_b.html#ga68c96ad594af70c007923979085c99e0":[4,0,0,1,0,19,41],
"group___c_m_s_i_s___s_c_b.html#ga68c96ad594af70c007923979085c99e0":[4,0,0,1,0,20,213],
"group___c_m_s_i_s___s_c_b.html#ga6f7d14ca4c78b7fd64157d9f8110f188":[4,0,0,1,0,15,351],
"group___c_m_s_i_s___s_c_b.html#ga6f7d14ca4c78b7fd64157d9f8110f188":[2,12,2,515],
"group___c_m_s_i_s___s_c_b.html#ga705f68eaa9afb042ca2407dc4e4629ac":[4,0,0,1,0,10,48],
"group___c_m_s_i_s___s_c_b.html#ga705f68eaa9afb042ca2407dc4e4629ac":[4,0,0,1,0,11,50],
"group___c_m_s_i_s___s_c_b.html#ga705f68eaa9afb042ca2407dc4e4629ac":[2,12,2,258],
"group___c_m_s_i_s___s_c_b.html#ga705f68eaa9afb042ca2407dc4e4629ac":[2,12,2,259],
"group___c_m_s_i_s___s_c_b.html#ga705f68eaa9afb042ca2407dc4e4629ac":[2,12,2,260],
"group___c_m_s_i_s___s_c_b.html#ga705f68eaa9afb042ca2407dc4e4629ac":[2,12,2,261],
"group___c_m_s_i_s___s_c_b.html#ga705f68eaa9afb042ca2407dc4e4629ac":[2,12,2,262],
"group___c_m_s_i_s___s_c_b.html#ga705f68eaa9afb042ca2407dc4e4629ac":[2,12,2,263],
"group___c_m_s_i_s___s_c_b.html#ga705f68eaa9afb042ca2407dc4e4629ac":[2,12,2,264],
"group___c_m_s_i_s___s_c_b.html#ga705f68eaa9afb042ca2407dc4e4629ac":[4,0,0,1,0,12,228],
"group___c_m_s_i_s___s_c_b.html#ga705f68eaa9afb042ca2407dc4e4629ac":[4,0,0,1,0,13,231],
"group___c_m_s_i_s___s_c_b.html#ga705f68eaa9afb042ca2407dc4e4629ac":[4,0,0,1,0,15,286],
"group___c_m_s_i_s___s_c_b.html#ga705f68eaa9afb042ca2407dc4e4629ac":[4,0,0,1,0,19,48],
"group___c_m_s_i_s___s_c_b.html#ga705f68eaa9afb042ca2407dc4e4629ac":[4,0,0,1,0,20,228],
"group___c_m_s_i_s___s_c_b.html#ga70e80783c3bd7b11504c63b052b0c0b9":[2,12,2,294],
"group___c_m_s_i_s___s_c_b.html#ga70e80783c3bd7b11504c63b052b0c0b9":[4,0,0,1,0,15,292],
"group___c_m_s_i_s___s_c_b.html#ga7325b61ea0ec323ef2d5c893b112e546":[4,0,0,1,0,10,61],
"group___c_m_s_i_s___s_c_b.html#ga7325b61ea0ec323ef2d5c893b112e546":[4,0,0,1,0,11,63],
"group___c_m_s_i_s___s_c_b.html#ga7325b61ea0ec323ef2d5c893b112e546":[4,0,0,1,0,12,257],
"group___c_m_s_i_s___s_c_b.html#ga7325b61ea0ec323ef2d5c893b112e546":[4,0,0,1,0,13,260],
"group___c_m_s_i_s___s_c_b.html#ga7325b61ea0ec323ef2d5c893b112e546":[4,0,0,1,0,15,337],
"group___c_m_s_i_s___s_c_b.html#ga7325b61ea0ec323ef2d5c893b112e546":[4,0,0,1,0,19,61],
"group___c_m_s_i_s___s_c_b.html#ga7325b61ea0ec323ef2d5c893b112e546":[4,0,0,1,0,20,257],
"group___c_m_s_i_s___s_c_b.html#ga7325b61ea0ec323ef2d5c893b112e546":[2,12,2,435],
"group___c_m_s_i_s___s_c_b.html#ga7325b61ea0ec323ef2d5c893b112e546":[2,12,2,436],
"group___c_m_s_i_s___s_c_b.html#ga7325b61ea0ec323ef2d5c893b112e546":[2,12,2,437],
"group___c_m_s_i_s___s_c_b.html#ga7325b61ea0ec323ef2d5c893b112e546":[2,12,2,438],
"group___c_m_s_i_s___s_c_b.html#ga7325b61ea0ec323ef2d5c893b112e546":[2,12,2,439],
"group___c_m_s_i_s___s_c_b.html#ga7325b61ea0ec323ef2d5c893b112e546":[2,12,2,440],
"group___c_m_s_i_s___s_c_b.html#ga7325b61ea0ec323ef2d5c893b112e546":[2,12,2,441],
"group___c_m_s_i_s___s_c_b.html#ga7456a0b93710e8b9fa2b94c946e96c5c":[4,0,0,1,0,15,233],
"group___c_m_s_i_s___s_c_b.html#ga7456a0b93710e8b9fa2b94c946e96c5c":[2,12,2,109],
"group___c_m_s_i_s___s_c_b.html#ga750388e1509b36d35568a68a7a1e1ff7":[2,12,2,184],
"group___c_m_s_i_s___s_c_b.html#ga750388e1509b36d35568a68a7a1e1ff7":[4,0,0,1,0,15,260],
"group___c_m_s_i_s___s_c_b.html#ga750d4b52624a46d71356db4ea769573b":[4,0,0,1,0,10,58],
"group___c_m_s_i_s___s_c_b.html#ga750d4b52624a46d71356db4ea769573b":[4,0,0,1,0,11,60],
"group___c_m_s_i_s___s_c_b.html#ga750d4b52624a46d71356db4ea769573b":[4,0,0,1,0,12,254],
"group___c_m_s_i_s___s_c_b.html#ga750d4b52624a46d71356db4ea769573b":[4,0,0,1,0,13,257],
"group___c_m_s_i_s___s_c_b.html#ga750d4b52624a46d71356db4ea769573b":[4,0,0,1,0,15,334],
"group___c_m_s_i_s___s_c_b.html#ga750d4b52624a46d71356db4ea769573b":[4,0,0,1,0,19,58],
"group___c_m_s_i_s___s_c_b.html#ga750d4b52624a46d71356db4ea769573b":[4,0,0,1,0,20,254],
"group___c_m_s_i_s___s_c_b.html#ga750d4b52624a46d71356db4ea769573b":[2,12,2,414],
"group___c_m_s_i_s___s_c_b.html#ga750d4b52624a46d71356db4ea769573b":[2,12,2,415],
"group___c_m_s_i_s___s_c_b.html#ga750d4b52624a46d71356db4ea769573b":[2,12,2,416],
"group___c_m_s_i_s___s_c_b.html#ga750d4b52624a46d71356db4ea769573b":[2,12,2,417],
"group___c_m_s_i_s___s_c_b.html#ga750d4b52624a46d71356db4ea769573b":[2,12,2,418],
"group___c_m_s_i_s___s_c_b.html#ga750d4b52624a46d71356db4ea769573b":[2,12,2,419],
"group___c_m_s_i_s___s_c_b.html#ga750d4b52624a46d71356db4ea769573b":[2,12,2,420],
"group___c_m_s_i_s___s_c_b.html#ga75e395ed74042923e8c93edf50f0996c":[2,12,2,687],
"group___c_m_s_i_s___s_c_b.html#ga75e395ed74042923e8c93edf50f0996c":[2,12,2,688],
"group___c_m_s_i_s___s_c_b.html#ga75e395ed74042923e8c93edf50f0996c":[2,12,2,689],
"group___c_m_s_i_s___s_c_b.html#ga75e395ed74042923e8c93edf50f0996c":[2,12,2,690],
"group___c_m_s_i_s___s_c_b.html#ga75e395ed74042923e8c93edf50f0996c":[2,12,2,691],
"group___c_m_s_i_s___s_c_b.html#ga75e395ed74042923e8c93edf50f0996c":[4,0,0,1,0,12,305],
"group___c_m_s_i_s___s_c_b.html#ga75e395ed74042923e8c93edf50f0996c":[4,0,0,1,0,13,306],
"group___c_m_s_i_s___s_c_b.html#ga75e395ed74042923e8c93edf50f0996c":[4,0,0,1,0,15,393],
"group___c_m_s_i_s___s_c_b.html#ga75e395ed74042923e8c93edf50f0996c":[4,0,0,1,0,19,79],
"group___c_m_s_i_s___s_c_b.html#ga75e395ed74042923e8c93edf50f0996c":[4,0,0,1,0,20,305],
"group___c_m_s_i_s___s_c_b.html#ga7692042fbaab5852ca60f6c2d659f724":[2,12,2,302],
"group___c_m_s_i_s___s_c_b.html#ga7692042fbaab5852ca60f6c2d659f724":[4,0,0,1,0,15,300],
"group___c_m_s_i_s___s_c_b.html#ga76ce5adcbed2d2d8d425214a1e5d0579":[4,0,0,1,0,15,234],
"group___c_m_s_i_s___s_c_b.html#ga76ce5adcbed2d2d8d425214a1e5d0579":[2,12,2,110],
"group___c_m_s_i_s___s_c_b.html#ga770da9a88e66adb62645f625b0a095cb":[4,0,0,1,0,15,208],
"group___c_m_s_i_s___s_c_b.html#ga770da9a88e66adb62645f625b0a095cb":[2,12,2,13],
"group___c_m_s_i_s___s_c_b.html#ga778dd0ba178466b2a8877a6b8aa345ee":[2,12,2,683],
"group___c_m_s_i_s___s_c_b.html#ga778dd0ba178466b2a8877a6b8aa345ee":[2,12,2,684],
"group___c_m_s_i_s___s_c_b.html#ga778dd0ba178466b2a8877a6b8aa345ee":[4,0,0,1,0,12,303],
"group___c_m_s_i_s___s_c_b.html#ga778dd0ba178466b2a8877a6b8aa345ee":[4,0,0,1,0,20,303],
"group___c_m_s_i_s___s_c_b.html#ga77993da8de35adea7bda6a4475f036ab":[4,0,0,1,0,12,248],
"group___c_m_s_i_s___s_c_b.html#ga77993da8de35adea7bda6a4475f036ab":[4,0,0,1,0,13,251],
"group___c_m_s_i_s___s_c_b.html#ga77993da8de35adea7bda6a4475f036ab":[4,0,0,1,0,15,328],
"group___c_m_s_i_s___s_c_b.html#ga77993da8de35adea7bda6a4475f036ab":[2,12,2,375],
"group___c_m_s_i_s___s_c_b.html#ga77993da8de35adea7bda6a4475f036ab":[2,12,2,377],
"group___c_m_s_i_s___s_c_b.html#ga77993da8de35adea7bda6a4475f036ab":[4,0,0,1,0,20,248],
"group___c_m_s_i_s___s_c_b.html#ga77993da8de35adea7bda6a4475f036ab":[2,12,2,376],
"group___c_m_s_i_s___s_c_b.html#ga77993da8de35adea7bda6a4475f036ab":[2,12,2,378],
"group___c_m_s_i_s___s_c_b.html#ga77c06a69c63f4b3f6ec1032e911e18e7":[4,0,0,1,0,10,73],
"group___c_m_s_i_s___s_c_b.html#ga77c06a69c63f4b3f6ec1032e911e18e7":[4,0,0,1,0,11,75],
"group___c_m_s_i_s___s_c_b.html#ga77c06a69c63f4b3f6ec1032e911e18e7":[4,0,0,1,0,12,271],
"group___c_m_s_i_s___s_c_b.html#ga77c06a69c63f4b3f6ec1032e911e18e7":[4,0,0,1,0,13,274],
"group___c_m_s_i_s___s_c_b.html#ga77c06a69c63f4b3f6ec1032e911e18e7":[4,0,0,1,0,15,359],
"group___c_m_s_i_s___s_c_b.html#ga77c06a69c63f4b3f6ec1032e911e18e7":[4,0,0,1,0,19,73],
"group___c_m_s_i_s___s_c_b.html#ga77c06a69c63f4b3f6ec1032e911e18e7":[4,0,0,1,0,20,271],
"group___c_m_s_i_s___s_c_b.html#ga77c06a69c63f4b3f6ec1032e911e18e7":[2,12,2,535],
"group___c_m_s_i_s___s_c_b.html#ga77c06a69c63f4b3f6ec1032e911e18e7":[2,12,2,536],
"group___c_m_s_i_s___s_c_b.html#ga77c06a69c63f4b3f6ec1032e911e18e7":[2,12,2,537],
"group___c_m_s_i_s___s_c_b.html#ga77c06a69c63f4b3f6ec1032e911e18e7":[2,12,2,538],
"group___c_m_s_i_s___s_c_b.html#ga77c06a69c63f4b3f6ec1032e911e18e7":[2,12,2,539],
"group___c_m_s_i_s___s_c_b.html#ga77c06a69c63f4b3f6ec1032e911e18e7":[2,12,2,540],
"group___c_m_s_i_s___s_c_b.html#ga77c06a69c63f4b3f6ec1032e911e18e7":[2,12,2,541],
"group___c_m_s_i_s___s_c_b.html#ga789e41f45f59a8cd455fd59fa7652e5e":[2,12,2,177],
"group___c_m_s_i_s___s_c_b.html#ga789e41f45f59a8cd455fd59fa7652e5e":[2,12,2,178],
"group___c_m_s_i_s___s_c_b.html#ga789e41f45f59a8cd455fd59fa7652e5e":[2,12,2,179],
"group___c_m_s_i_s___s_c_b.html#ga789e41f45f59a8cd455fd59fa7652e5e":[2,12,2,180],
"group___c_m_s_i_s___s_c_b.html#ga789e41f45f59a8cd455fd59fa7652e5e":[4,0,0,1,0,12,216],
"group___c_m_s_i_s___s_c_b.html#ga789e41f45f59a8cd455fd59fa7652e5e":[4,0,0,1,0,13,219],
"group___c_m_s_i_s___s_c_b.html#ga789e41f45f59a8cd455fd59fa7652e5e":[4,0,0,1,0,15,256],
"group___c_m_s_i_s___s_c_b.html#ga789e41f45f59a8cd455fd59fa7652e5e":[4,0,0,1,0,20,216],
"group___c_m_s_i_s___s_c_b.html#ga79b099c3a4365b434aaf55ebbd534420":[4,0,0,1,0,15,319],
"group___c_m_s_i_s___s_c_b.html#ga79b099c3a4365b434aaf55ebbd534420":[2,12,2,351],
"group___c_m_s_i_s___s_c_b.html#ga7b67f900eb9c63b04e67f8fa6ddcd8ed":[2,12,2,681],
"group___c_m_s_i_s___s_c_b.html#ga7b67f900eb9c63b04e67f8fa6ddcd8ed":[4,0,0,1,0,15,391],
"group___c_m_s_i_s___s_c_b.html#ga7c856f79a75dcc1d1517b19a67691803":[4,0,0,1,0,12,282],
"group___c_m_s_i_s___s_c_b.html#ga7c856f79a75dcc1d1517b19a67691803":[4,0,0,1,0,13,285],
"group___c_m_s_i_s___s_c_b.html#ga7c856f79a75dcc1d1517b19a67691803":[4,0,0,1,0,15,370],
"group___c_m_s_i_s___s_c_b.html#ga7c856f79a75dcc1d1517b19a67691803":[4,0,0,1,0,20,282],
"group___c_m_s_i_s___s_c_b.html#ga7c856f79a75dcc1d1517b19a67691803":[2,12,2,591],
"group___c_m_s_i_s___s_c_b.html#ga7c856f79a75dcc1d1517b19a67691803":[2,12,2,592],
"group___c_m_s_i_s___s_c_b.html#ga7c856f79a75dcc1d1517b19a67691803":[2,12,2,593],
"group___c_m_s_i_s___s_c_b.html#ga7c856f79a75dcc1d1517b19a67691803":[2,12,2,594],
"group___c_m_s_i_s___s_c_b.html#ga7fac248cabee94546aa9530d27217772":[2,12,2,123],
"group___c_m_s_i_s___s_c_b.html#ga7fac248cabee94546aa9530d27217772":[4,0,0,1,0,15,241],
"group___c_m_s_i_s___s_c_b.html#ga86b58242b8286aba9318e2062d88f341":[4,0,0,1,0,15,356],
"group___c_m_s_i_s___s_c_b.html#ga86b58242b8286aba9318e2062d88f341":[2,12,2,520],
"group___c_m_s_i_s___s_c_b.html#ga89a28cc31cfc7d52d9d7a8fcc69c7eac":[4,0,0,1,0,12,205],
"group___c_m_s_i_s___s_c_b.html#ga89a28cc31cfc7d52d9d7a8fcc69c7eac":[4,0,0,1,0,13,208],
"group___c_m_s_i_s___s_c_b.html#ga89a28cc31cfc7d52d9d7a8fcc69c7eac":[4,0,0,1,0,15,239],
"group___c_m_s_i_s___s_c_b.html#ga89a28cc31cfc7d52d9d7a8fcc69c7eac":[4,0,0,1,0,20,205],
"group___c_m_s_i_s___s_c_b.html#ga89a28cc31cfc7d52d9d7a8fcc69c7eac":[2,12,2,115],
"group___c_m_s_i_s___s_c_b.html#ga89a28cc31cfc7d52d9d7a8fcc69c7eac":[2,12,2,116],
"group___c_m_s_i_s___s_c_b.html#ga89a28cc31cfc7d52d9d7a8fcc69c7eac":[2,12,2,117],
"group___c_m_s_i_s___s_c_b.html#ga89a28cc31cfc7d52d9d7a8fcc69c7eac":[2,12,2,118],
"group___c_m_s_i_s___s_c_b.html#ga8b71cf4c61803752a41c96deb00d26af":[4,0,0,1,0,12,288],
"group___c_m_s_i_s___s_c_b.html#ga8b71cf4c61803752a41c96deb00d26af":[4,0,0,1,0,13,291],
"group___c_m_s_i_s___s_c_b.html#ga8b71cf4c61803752a41c96deb00d26af":[4,0,0,1,0,15,376],
"group___c_m_s_i_s___s_c_b.html#ga8b71cf4c61803752a41c96deb00d26af":[4,0,0,1,0,20,288],
"group___c_m_s_i_s___s_c_b.html#ga8b71cf4c61803752a41c96deb00d26af":[2,12,2,615],
"group___c_m_s_i_s___s_c_b.html#ga8b71cf4c61803752a41c96deb00d26af":[2,12,2,616],
"group___c_m_s_i_s___s_c_b.html#ga8b71cf4c61803752a41c96deb00d26af":[2,12,2,617],
"group___c_m_s_i_s___s_c_b.html#ga8b71cf4c61803752a41c96deb00d26af":[2,12,2,618],
"group___c_m_s_i_s___s_c_b.html#ga8b72fb208ee772734e580911a8e522ce":[4,0,0,1,0,15,318],
"group___c_m_s_i_s___s_c_b.html#ga8b72fb208ee772734e580911a8e522ce":[2,12,2,350],
"group___c_m_s_i_s___s_c_b.html#ga8be60fff03f48d0d345868060dc6dae7":[4,0,0,1,0,12,192],
"group___c_m_s_i_s___s_c_b.html#ga8be60fff03f48d0d345868060dc6dae7":[4,0,0,1,0,13,195],
"group___c_m_s_i_s___s_c_b.html#ga8be60fff03f48d0d345868060dc6dae7":[4,0,0,1,0,15,220],
"group___c_m_s_i_s___s_c_b.html#ga8be60fff03f48d0d345868060dc6dae7":[4,0,0,1,0,20,192],
"group___c_m_s_i_s___s_c_b.html#ga8be60fff03f48d0d345868060dc6dae7":[2,12,2,37],
"group___c_m_s_i_s___s_c_b.html#ga8be60fff03f48d0d345868060dc6dae7":[2,12,2,38],
"group___c_m_s_i_s___s_c_b.html#ga8be60fff03f48d0d345868060dc6dae7":[2,12,2,39],
"group___c_m_s_i_s___s_c_b.html#ga8be60fff03f48d0d345868060dc6dae7":[2,12,2,40],
"group___c_m_s_i_s___s_c_b.html#ga8c014c9678bc9072f10459a1e14b973c":[2,12,2,296],
"group___c_m_s_i_s___s_c_b.html#ga8c014c9678bc9072f10459a1e14b973c":[4,0,0,1,0,15,294],
"group___c_m_s_i_s___s_c_b.html#ga9089551a75985fa7cf051062ed2d62b9":[2,12,2,193],
"group___c_m_s_i_s___s_c_b.html#ga9089551a75985fa7cf051062ed2d62b9":[4,0,0,1,0,15,269],
"group___c_m_s_i_s___s_c_b.html#ga90c7cf0c490e7ae55f9503a7fda1dd22":[4,0,0,1,0,10,34],
"group___c_m_s_i_s___s_c_b.html#ga90c7cf0c490e7ae55f9503a7fda1dd22":[4,0,0,1,0,11,36],
"group___c_m_s_i_s___s_c_b.html#ga90c7cf0c490e7ae55f9503a7fda1dd22":[4,0,0,1,0,12,198],
"group___c_m_s_i_s___s_c_b.html#ga90c7cf0c490e7ae55f9503a7fda1dd22":[4,0,0,1,0,13,201],
"group___c_m_s_i_s___s_c_b.html#ga90c7cf0c490e7ae55f9503a7fda1dd22":[4,0,0,1,0,15,226],
"group___c_m_s_i_s___s_c_b.html#ga90c7cf0c490e7ae55f9503a7fda1dd22":[4,0,0,1,0,19,34],
"group___c_m_s_i_s___s_c_b.html#ga90c7cf0c490e7ae55f9503a7fda1dd22":[4,0,0,1,0,20,198],
"group___c_m_s_i_s___s_c_b.html#ga90c7cf0c490e7ae55f9503a7fda1dd22":[2,12,2,73],
"group___c_m_s_i_s___s_c_b.html#ga90c7cf0c490e7ae55f9503a7fda1dd22":[2,12,2,74],
"group___c_m_s_i_s___s_c_b.html#ga90c7cf0c490e7ae55f9503a7fda1dd22":[2,12,2,75],
"group___c_m_s_i_s___s_c_b.html#ga90c7cf0c490e7ae55f9503a7fda1dd22":[2,12,2,76],
"group___c_m_s_i_s___s_c_b.html#ga90c7cf0c490e7ae55f9503a7fda1dd22":[2,12,2,77],
"group___c_m_s_i_s___s_c_b.html#ga90c7cf0c490e7ae55f9503a7fda1dd22":[2,12,2,78],
"group___c_m_s_i_s___s_c_b.html#ga90c7cf0c490e7ae55f9503a7fda1dd22":[2,12,2,79],
"group___c_m_s_i_s___s_c_b.html#ga9147fd4e1b12394ae26eadf900a023a3":[4,0,0,1,0,12,281],
"group___c_m_s_i_s___s_c_b.html#ga9147fd4e1b12394ae26eadf900a023a3":[4,0,0,1,0,13,284]
};
|
#!/usr/bin/env node
var nopt = require("nopt");
var Stream = require("stream").Stream;
var path = require("path");
var fs = require('fs');
var knownOpts = {
"version": Boolean,
"remux": Boolean,
"chapters": ["txt", "ogm", "xml"],
"input": String,
"output": String
}
var shortHands = {
"v" : ["--version"],
"i" : ["--input"],
"o" : ["--output"],
"ch" : ["--chapters"]
}
var parsed = nopt(knownOpts, shortHands, process.argv, 2);
//console.log(parsed);
// for first space
console.log('');
var rpav = require("./");
var mtool = new rpav({
bin_mediainfo: __dirname+'/bin/mediainfo/MediaInfo.exe',
bin_mplayer: __dirname+'/bin/mplayer/mplayer.exe',
bin_mp4box: __dirname+'/bin/GPAC/mp4box.exe',
bin_mkvmerge: __dirname+'/bin/mkvtoolnix/mkvmerge.exe'
});
if (parsed.version) {
var pk = require('./package.json');
console.log(' '+pk.name+': '+pk.version);
mtool.listTools(function(){
process.exit(0);
});
} else if (parsed.help) {
//usage();
process.exit(0);
}else if(parsed.remux){
if(parsed.input && parsed.output){
if(fs.existsSync(parsed.input)) {
var mux = path.extname(parsed.input).replace('.','')+' to '+path.extname(parsed.output).replace('.','');
if(mux=='m4v to mkv' || mux=='mp4 to mkv'){
mtool.m4v2mkv({
input: parsed.input,
output: parsed.output,
info: function(str){
process.stderr.write('\033[0G '+str); // \r
},
done: function(){
// Clean stderr line
var blank = new Array(process.stderr.columns + 1).join(' ');
process.stderr.write('\033[0G'+blank+'\033[0G'); // \r
console.log('Done!');
process.exit(0);
},
error: function(str){
}
});
}else{
console.log('Remuxing '+mux+' is not supported yet.');
}
}else{
console.log('Input not found.');
}
}else{
console.log('You must define an input and an output.');
}
}else if (parsed.chapters){
if(parsed.input){
if(fs.existsSync(parsed.input)){
mtool.getInfo(parsed.input, function(err, info) {
if (err) {
console.log(err);
}
mtool.genChapters({
template: parsed.chapters+'.txt',
file_info: info
}, function(chaps){
if(chaps){
if(parsed.output){
var chout = path.normalize(parsed.output);
fs.writeFileSync(chout, chaps);
console.log('Chapter file created at: '+chout);
}else{
console.log(chaps);
}
}else{
console.log('The file doesn\'t contain chapters.');
}
});
});
}else{
console.log('Input not found.');
}
}else{
console.log('You must define an input and an output.');
}
}else{
if(parsed.argv.cooked<1){
console.log('Action undefined, currenlty working on the man info.');
}
}
|
Object.assign(window, Sprinting)
let world = new World('#world')
let rect = new Rectangle
rect.stroke = 'transparent'
rect.fill = '#ffaa00'
rect.y = 450
rect.x = 450
rect.width = 10
rect.height = 10
let circ = new Circle(100, 100)
circ.stroke = 'transparent'
circ.fill = '#00aaff'
circ.x = 100
circ.y = 100
let trump = new Img('trump.jpg')
trump.width = 200
trump.height = 150
trump.x = 450
trump.y = 450
trump.rx = 1
trump.ry = 1
let i = 0
world
.add(rect)
.add(circ)
.add(trump)
.drawLoop(function() {
i++
trump.r++
}) |
// =====================================================================
// This file is part of the Microsoft Dynamics CRM SDK code samples.
//
// Copyright (C) Microsoft Corporation. All rights reserved.
//
// This source code is intended only as a supplement to Microsoft
// Development Tools and/or on-line documentation. See these other
// materials for detailed information regarding Microsoft code samples.
//
// THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY
// KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
// PARTICULAR PURPOSE.
// =====================================================================
"use strict";
(function ()
{
this.SetDataEncryptionKeyRequest = function (encryptionKey, changeEncryptionKey) {
///<summary>
/// Contains the data that is needed to set or restore the data encryption key.
///</summary>
///<param name="encryptionKey" type="String">
/// Sets the value of the data encryption key.
///</param>
///<param name="changeEncryptionKey" type="Boolean">
/// <para>Sets the operation to perform with the data encryption key.</para>
/// <para>true indicates to set (change) the data encryption key; otherwise, false indicates to restore the data encryption key. </para>
///</param>
if (!(this instanceof Sdk.SetDataEncryptionKeyRequest)) {
return new Sdk.SetDataEncryptionKeyRequest(encryptionKey, changeEncryptionKey);
}
Sdk.OrganizationRequest.call(this);
// Internal properties
var _encryptionKey = null;
var _changeEncryptionKey = null;
// internal validation functions
function _setValidEncryptionKey(value) {
if (typeof value == "string") {
_encryptionKey = value;
}
else {
throw new Error("Sdk.SetDataEncryptionKeyRequest EncryptionKey property is required and must be a String.")
}
}
function _setValidChangeEncryptionKey(value) {
if (typeof value == "boolean") {
_changeEncryptionKey = value;
}
else {
throw new Error("Sdk.SetDataEncryptionKeyRequest ChangeEncryptionKey property is required and must be a Boolean.")
}
}
//Set internal properties from constructor parameters
if (typeof encryptionKey != "undefined") {
_setValidEncryptionKey(encryptionKey);
}
if (typeof changeEncryptionKey != "undefined") {
_setValidChangeEncryptionKey(changeEncryptionKey);
}
function getRequestXml() {
return ["<d:request>",
"<a:Parameters>",
"<a:KeyValuePairOfstringanyType>",
"<b:key>EncryptionKey</b:key>",
(_encryptionKey == null) ? "<b:value i:nil=\"true\" />" :
["<b:value i:type=\"c:string\">", _encryptionKey, "</b:value>"].join(""),
"</a:KeyValuePairOfstringanyType>",
"<a:KeyValuePairOfstringanyType>",
"<b:key>ChangeEncryptionKey</b:key>",
(_changeEncryptionKey == null) ? "<b:value i:nil=\"true\" />" :
["<b:value i:type=\"c:boolean\">", _changeEncryptionKey, "</b:value>"].join(""),
"</a:KeyValuePairOfstringanyType>",
"</a:Parameters>",
"<a:RequestId i:nil=\"true\" />",
"<a:RequestName>SetDataEncryptionKey</a:RequestName>",
"</d:request>"].join("");
}
this.setResponseType(Sdk.SetDataEncryptionKeyResponse);
this.setRequestXml(getRequestXml());
// Public methods to set properties
this.setEncryptionKey = function (value) {
///<summary>
/// Sets the value of the data encryption key.
///</summary>
///<param name="value" type="String">
/// The value of the data encryption key.
///</param>
_setValidEncryptionKey(value);
this.setRequestXml(getRequestXml());
}
this.setChangeEncryptionKey = function (value) {
///<summary>
/// Sets the operation to perform with the data encryption key.
///</summary>
///<param name="value" type="Boolean">
/// <para>Sets the operation to perform with the data encryption key.</para>
/// <para>true indicates to set (change) the data encryption key; otherwise, false indicates to restore the data encryption key. </para>
///</param>
_setValidChangeEncryptionKey(value);
this.setRequestXml(getRequestXml());
}
}
this.SetDataEncryptionKeyRequest.__class = true;
this.SetDataEncryptionKeyResponse = function (responseXml) {
///<summary>
/// Response to SetDataEncryptionKeyRequest
///</summary>
if (!(this instanceof Sdk.SetDataEncryptionKeyResponse)) {
return new Sdk.SetDataEncryptionKeyResponse(responseXml);
}
Sdk.OrganizationResponse.call(this)
// This message returns no values
}
this.SetDataEncryptionKeyResponse.__class = true;
}).call(Sdk)
Sdk.SetDataEncryptionKeyRequest.prototype = new Sdk.OrganizationRequest();
Sdk.SetDataEncryptionKeyResponse.prototype = new Sdk.OrganizationResponse();
|
let hBookmark;
function warmUp() {
utils.include("btil.js");
let global = loadAutoloader("chrome://hatenabookmark/content/addPanel.xml");
hBookmark = global.hBookmark;
// EXPORT に含まれていないメンバもテストするため直接読み込む。
Components.classes["@mozilla.org/moz/jssubscript-loader;1"]
.getService(Components.interfaces.mozIJSSubScriptLoader)
.loadSubScript("chrome://hatenabookmark/content/addPanel/20-URLSuggestion.js", hBookmark);
}
function testEffectiveDomain() {
assert.isTrue(hBookmark.isSameEffectiveDomain(
"http://www.hatena.ne.jp/",
"http://b.hatena.ne.jp/"));
assert.isFalse(hBookmark.isSameEffectiveDomain(
"http://www.hatena.ne.jp/",
"http://www.goo.ne.jp/"));
}
function testMetaSuggestor() {
let suggestors = hBookmark.URLSuggestion.suggestors;
assert.equals(
"http://b.hatena.ne.jp/guide/staff_bookmark_04",
suggestors.meta("http://b.hatena.ne.jp/entry/http://b.hatena.ne.jp/guide/staff_bookmark_04", null))
assert.equals(
null,
suggestors.meta("http://b.hatena.ne.jp/entry/12345", null))
}
function testCanonicalResponseSuggestor() {
let suggestor = hBookmark.URLSuggestion.responseSuggestors.canonical;
let response = {
responseText: <html>
<head>
<link rel="canonical" href="http://example.org/canonical"/>
</head>
<body>
<p>Hello, world</p>
</body>
</html>.toXMLString()
}
assert.equals("http://example.org/canonical",
suggestor("http://example.org/", response));
response.responseText = <html>
<head>
<link href="canonical-url" rel="canonical"/>
</head>
<body>
<p>Hello, world</p>
</body>
</html>.toXMLString();
assert.equals("http://example.org/canonical-url",
suggestor("http://example.org/", response));
assert.equals("http://example.org/canonical-url#fragment",
suggestor("http://example.org/#fragment", response));
}
|
export { default } from 'ember-sparks-web/components/spark-page/spark-demo/try-code/component';
|
import { GET_USER_PROFILE, ADD_USER_ICEBOX, REMOVE_USER_ICEBOX } from '../constants/actions';
const INITIAL_STATE = {
name: null,
email: null,
household: [],
staples: [],
confirmations: null,
};
export default function (state = INITIAL_STATE, action) {
switch (action.type) {
case GET_USER_PROFILE:
return {
...state,
name: action.payload.profile.name,
email: action.payload.profile.email,
household: [...state.household, ...action.payload.household],
staples: [...state.staples, ...action.payload.staples],
};
case ADD_USER_ICEBOX:
return {
...state,
confirmations: action.payload,
};
case REMOVE_USER_ICEBOX:
return {
...state,
household: action.payload.household,
};
default:
return state;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.