code
stringlengths 2
1.05M
|
---|
const bodyParser = require("body-parser");
const cors = require("cors");
const db = require("../db/config");
const express = require("express");
const path = require("path");
const routes = require("./routes/index");
const $ = require("jquery");
const PORT = process.env.PORT || 3000;
const app = express()
.use(cors())
.use(bodyParser.urlencoded({ extended: true }))
.use(bodyParser.json())
.use(express.static(path.resolve(__dirname, "../client/public")))
.use("/api", routes);
app.get("/*", (req, res) => {
res.sendFile(path.join(__dirname, "../client/public/index.html"));
});
app.listen(PORT, err => {
if (err) {
console.log(`Error connecting to server ${err}`);
}
console.log(`Listening on PORT ${PORT}`);
});
|
/*********************************************************************************************************/
/* Global function and variable for panel/page com */
/*********************************************************************************************************/
/* Called for every canvasdesigner-over click */
var onClickCanvasdesignerItem = function (schema) {
var scope = angular.element($("#canvasdesignerPanel")).scope();
//if (scope.schemaFocus != schema.toLowerCase()) {
//var notFound = true;
$.each(scope.canvasdesignerModel.configs, function (indexConfig, config) {
if (config.schema && schema.toLowerCase() == config.schema.toLowerCase()) {
scope.currentSelected = config;
}
});
//}
scope.clearSelectedCategory();
scope.closeFloatPanels();
scope.$apply();
}
/* Called for every canvasdesigner-over rollover */
var onMouseoverCanvasdesignerItem = function (name) {
var scope = angular.element($("#canvasdesignerPanel")).scope();
$.each(scope.canvasdesignerModel.configs, function (indexConfig, config) {
config.highlighted = false;
if (config.name && name.toLowerCase() == config.name.toLowerCase()) {
config.highlighted = true;
}
});
scope.$apply();
}
/* Called when the iframe is first loaded */
var setFrameIsLoaded = function (canvasdesignerConfig, canvasdesignerPalette) {
var scope = angular.element($("#canvasdesignerPanel")).scope();
scope.canvasdesignerModel = canvasdesignerConfig;
scope.canvasdesignerPalette = canvasdesignerPalette;
scope.enableCanvasdesigner++;
scope.$apply();
}
/* Iframe body click */
var iframeBodyClick = function () {
var scope = angular.element($("#canvasdesignerPanel")).scope();
scope.closeFloatPanels();
}
/*********************************************************************************************************/
/* Canvasdesigner panel app and controller */
/*********************************************************************************************************/
var app = angular.module("Umbraco.canvasdesigner", ['colorpicker', 'ui.slider', 'umbraco.resources', 'umbraco.services'])
.controller("Umbraco.canvasdesignerController", function ($scope, $http, $window, $timeout, $location, dialogService) {
$scope.isOpen = false;
$scope.frameLoaded = false;
$scope.enableCanvasdesigner = 0;
$scope.googleFontFamilies = {};
$scope.pageId = $location.search().id;
$scope.pageUrl = "../dialogs/Preview.aspx?id=" + $location.search().id;
$scope.valueAreLoaded = false;
$scope.devices = [
{ name: "desktop", css: "desktop", icon: "icon-display", title: "Desktop" },
{ name: "laptop - 1366px", css: "laptop border", icon: "icon-laptop", title: "Laptop" },
{ name: "iPad portrait - 768px", css: "iPad-portrait border", icon: "icon-ipad", title: "Tablet portrait" },
{ name: "iPad landscape - 1024px", css: "iPad-landscape border", icon: "icon-ipad flip", title: "Tablet landscape" },
{ name: "smartphone portrait - 480px", css: "smartphone-portrait border", icon: "icon-iphone", title: "Smartphone portrait" },
{ name: "smartphone landscape - 320px", css: "smartphone-landscape border", icon: "icon-iphone flip", title: "Smartphone landscape" }
];
$scope.previewDevice = $scope.devices[0];
var apiController = "/Umbraco/Api/Canvasdesigner/";
/*****************************************************************************/
/* Preview devices */
/*****************************************************************************/
// Set preview device
$scope.updatePreviewDevice = function (device) {
$scope.previewDevice = device;
};
/*****************************************************************************/
/* UI designer managment */
/*****************************************************************************/
// Update all Canvasdesigner config's values from data
var updateConfigValue = function (data) {
var fonts = [];
$.each($scope.canvasdesignerModel.configs, function (indexConfig, config) {
if (config.editors) {
$.each(config.editors, function (indexItem, item) {
/* try to get value */
try {
if (item.values) {
angular.forEach(Object.keys(item.values), function (key, indexKey) {
if (key != "''") {
var propertyAlias = key.toLowerCase() + item.alias.toLowerCase();
var newValue = eval("data." + propertyAlias.replace("@", ""));
if (newValue == "''") {
newValue = "";
}
item.values[key] = newValue;
}
})
}
// TODO: special init for font family picker
if (item.type == "googlefontpicker") {
if (item.values.fontType == 'google' && item.values.fontFamily + item.values.fontWeight && $.inArray(item.values.fontFamily + ":" + item.values.fontWeight, fonts) < 0) {
fonts.splice(0, 0, item.values.fontFamily + ":" + item.values.fontWeight);
}
}
}
catch (err) {
console.info("Style parameter not found " + item.alias);
}
});
}
});
// Load google font
$.each(fonts, function (indexFont, font) {
loadGoogleFont(font);
loadGoogleFontInFront(font);
});
$scope.valueAreLoaded = true;
};
// Load parameters from GetLessParameters and init data of the Canvasdesigner config
$scope.initCanvasdesigner = function () {
$http.get(apiController + 'Load', { params: { pageId: $scope.pageId } })
.success(function (data) {
updateConfigValue(data);
$timeout(function () {
$scope.frameLoaded = true;
}, 200);
});
};
// Refresh all less parameters for every changes watching canvasdesignerModel
var refreshCanvasdesigner = function () {
var parameters = [];
if ($scope.canvasdesignerModel) {
angular.forEach($scope.canvasdesignerModel.configs, function (config, indexConfig) {
// Get currrent selected element
// TODO
//if ($scope.schemaFocus && angular.lowercase($scope.schemaFocus) == angular.lowercase(config.name)) {
// $scope.currentSelected = config.selector ? config.selector : config.schema;
//}
if (config.editors) {
angular.forEach(config.editors, function (item, indexItem) {
// Add new style
if (item.values) {
angular.forEach(Object.keys(item.values), function (key, indexKey) {
var propertyAlias = key.toLowerCase() + item.alias.toLowerCase();
var value = eval("item.values." + key);
parameters.splice(parameters.length + 1, 0, "'@" + propertyAlias + "':'" + value + "'");
})
}
});
}
});
// Refresh page style
refreshFrontStyles(parameters);
// Refresh layout of selected element
//$timeout(function () {
$scope.positionSelectedHide();
if ($scope.currentSelected) {
refreshOutlineSelected($scope.currentSelected);
}
//}, 200);
}
}
$scope.createStyle = function (){
$scope.saveLessParameters(false);
}
$scope.saveStyle = function () {
$scope.saveLessParameters(true);
}
// Save all parameter in CanvasdesignerParameters.less file
$scope.saveLessParameters = function (inherited) {
var parameters = [];
$.each($scope.canvasdesignerModel.configs, function (indexConfig, config) {
if (config.editors) {
$.each(config.editors, function (indexItem, item) {
if (item.values) {
angular.forEach(Object.keys(item.values), function (key, indexKey) {
var propertyAlias = key.toLowerCase() + item.alias.toLowerCase();
var value = eval("item.values." + key);
parameters.splice(parameters.length + 1, 0, "@" + propertyAlias + ":" + value + ";");
})
// TODO: special init for font family picker
if (item.type == "googlefontpicker" && item.values.fontFamily) {
var variant = item.values.fontWeight != "" || item.values.fontStyle != "" ? ":" + item.values.fontWeight + item.values.fontStyle : "";
var gimport = "@import url('https://fonts.googleapis.com/css?family=" + item.values.fontFamily + variant + "');";
if ($.inArray(gimport, parameters) < 0) {
parameters.splice(0, 0, gimport);
}
}
}
});
}
});
var resultParameters = { parameters: parameters.join(""), pageId: $scope.pageId, inherited: inherited };
var transform = function (result) {
return $.param(result);
}
$('.btn-default-save').attr("disabled", true);
$http.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded";
$http.post(apiController + 'Save', resultParameters, {
headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' },
transformRequest: transform
})
.success(function (data) {
$('.btn-default-save').attr("disabled", false);
$('#speechbubble').fadeIn('slow').delay(5000).fadeOut('slow');
});
}
// Delete current page Canvasdesigner
$scope.deleteCanvasdesigner = function () {
$('.btn-default-delete').attr("disabled", true);
$http.get(apiController + 'Delete', { params: { pageId: $scope.pageId } })
.success(function (data) {
location.reload();
})
}
/*****************************************************************************/
/* Preset design */
/*****************************************************************************/
// Refresh with selected Canvasdesigner palette
$scope.refreshCanvasdesignerByPalette = function (palette) {
updateConfigValue(palette.data);
refreshCanvasdesigner();
};
// Hidden botton to make preset from the current settings
$scope.makePreset = function () {
var parameters = [];
$.each($scope.canvasdesignerModel.configs, function (indexConfig, config) {
if (config.editors) {
$.each(config.editors, function (indexItem, item) {
if (item.values) {
angular.forEach(Object.keys(item.values), function (key, indexKey) {
var propertyAlias = key.toLowerCase() + item.alias.toLowerCase();
var value = eval("item.values." + key);
var value = (value != 0 && (value == undefined || value == "")) ? "''" : value;
parameters.splice(parameters.length + 1, 0, "\"" + propertyAlias + "\":" + " \"" + value + "\"");
})
}
});
}
});
$(".btn-group").append("<textarea>{name:\"\", color1:\"\", color2:\"\", color3:\"\", color4:\"\", color5:\"\", data:{" + parameters.join(",") + "}}</textarea>");
};
/*****************************************************************************/
/* Panel managment */
/*****************************************************************************/
$scope.openPreviewDevice = function () {
$scope.showDevicesPreview = true;
$scope.closeIntelCanvasdesigner();
}
$scope.closePreviewDevice = function(){
$scope.showDevicesPreview = false;
if ($scope.showStyleEditor) {
$scope.openIntelCanvasdesigner();
}
}
$scope.openPalettePicker = function () {
$scope.showPalettePicker = true;
$scope.showStyleEditor = false;
$scope.closeIntelCanvasdesigner();
};
$scope.openStyleEditor = function () {
$scope.showStyleEditor = true;
$scope.showPalettePicker = false;
$scope.outlineSelectedHide()
$scope.openIntelCanvasdesigner()
}
// Remove value from field
$scope.removeField = function (field) {
field.value = "";
};
// Check if category existe
$scope.hasEditor = function (editors, category) {
var result = false;
angular.forEach(editors, function (item, index) {
if (item.category == category) {
result = true;
}
});
return result;
};
$scope.closeFloatPanels = function () {
/* hack to hide color picker */
$(".spectrumcolorpicker input").spectrum("hide");
dialogService.close();
$scope.showPalettePicker = false;
$scope.$apply();
};
$scope.clearHighlightedItems = function () {
$.each($scope.canvasdesignerModel.configs, function (indexConfig, config) {
config.highlighted = false;
});
}
$scope.setCurrentHighlighted = function (item) {
$scope.clearHighlightedItems();
item.highlighted = true;
}
$scope.setCurrentSelected = function(item) {
$scope.currentSelected = item;
$scope.clearSelectedCategory();
refreshOutlineSelected($scope.currentSelected);
}
/* Editor categories */
$scope.getCategories = function (item) {
var propertyCategories = [];
$.each(item.editors, function (indexItem, editor) {
if (editor.category) {
if ($.inArray(editor.category, propertyCategories) < 0) {
propertyCategories.splice( propertyCategories.length + 1, 0, editor.category);
}
}
});
return propertyCategories;
}
$scope.setSelectedCategory = function (item) {
$scope.categoriesVisibility = $scope.categoriesVisibility || {};
$scope.categoriesVisibility[item] = !$scope.categoriesVisibility[item];
}
$scope.clearSelectedCategory = function () {
$scope.categoriesVisibility = null;
}
/*****************************************************************************/
/* Call function into the front-end */
/*****************************************************************************/
var loadGoogleFontInFront = function (font) {
if (document.getElementById("resultFrame").contentWindow.getFont)
document.getElementById("resultFrame").contentWindow.getFont(font);
};
var refreshFrontStyles = function (parameters) {
if (document.getElementById("resultFrame").contentWindow.refreshLayout)
document.getElementById("resultFrame").contentWindow.refreshLayout(parameters);
};
var hideUmbracoPreviewBadge = function () {
var iframe = (document.getElementById("resultFrame").contentWindow || document.getElementById("resultFrame").contentDocument);
if(iframe.document.getElementById("umbracoPreviewBadge"))
iframe.document.getElementById("umbracoPreviewBadge").style.display = "none";
};
$scope.openIntelCanvasdesigner = function () {
if (document.getElementById("resultFrame").contentWindow.initIntelCanvasdesigner)
document.getElementById("resultFrame").contentWindow.initIntelCanvasdesigner($scope.canvasdesignerModel);
};
$scope.closeIntelCanvasdesigner = function () {
if (document.getElementById("resultFrame").contentWindow.closeIntelCanvasdesigner)
document.getElementById("resultFrame").contentWindow.closeIntelCanvasdesigner($scope.canvasdesignerModel);
$scope.outlineSelectedHide();
};
var refreshOutlineSelected = function (config) {
var schema = config.selector ? config.selector : config.schema;
if (document.getElementById("resultFrame").contentWindow.refreshOutlineSelected)
document.getElementById("resultFrame").contentWindow.refreshOutlineSelected(schema);
}
$scope.outlineSelectedHide = function () {
$scope.currentSelected = null;
if (document.getElementById("resultFrame").contentWindow.outlineSelectedHide)
document.getElementById("resultFrame").contentWindow.outlineSelectedHide();
};
$scope.refreshOutlinePosition = function (config) {
var schema = config.selector ? config.selector : config.schema;
if (document.getElementById("resultFrame").contentWindow.refreshOutlinePosition)
document.getElementById("resultFrame").contentWindow.refreshOutlinePosition(schema);
}
$scope.positionSelectedHide = function () {
if (document.getElementById("resultFrame").contentWindow.outlinePositionHide)
document.getElementById("resultFrame").contentWindow.outlinePositionHide();
}
/*****************************************************************************/
/* Google font loader, TODO: put together from directive, front and back */
/*****************************************************************************/
var webFontScriptLoaded = false;
var loadGoogleFont = function (font) {
if (!webFontScriptLoaded) {
$.getScript('https://ajax.googleapis.com/ajax/libs/webfont/1/webfont.js')
.done(function () {
webFontScriptLoaded = true;
// Recursively call once webfont script is available.
loadGoogleFont(font);
})
.fail(function () {
console.log('error loading webfont');
});
}
else {
WebFont.load({
google: {
families: [font]
},
loading: function () {
//console.log('loading font' + font + ' in UI designer');
},
active: function () {
//console.log('loaded font ' + font + ' in UI designer');
},
inactive: function () {
//console.log('error loading font ' + font + ' in UI designer');
}
});
}
};
/*****************************************************************************/
/* Init */
/*****************************************************************************/
// Preload of the google font
$http.get(apiController + 'GetGoogleFont').success(function (data) {
$scope.googleFontFamilies = data;
});
// watch framLoaded, only if iframe page have enableCanvasdesigner()
$scope.$watch("enableCanvasdesigner", function () {
$timeout(function () {
if ($scope.enableCanvasdesigner > 0) {
$scope.$watch('ngRepeatFinished', function (ngRepeatFinishedEvent) {
$timeout(function () {
$scope.initCanvasdesigner();
}, 200);
});
$scope.$watch('canvasdesignerModel', function () {
refreshCanvasdesigner();
}, true);
}
}, 100);
}, true);
})
.directive('onFinishRenderFilters', function ($timeout) {
return {
restrict: 'A',
link: function (scope, element, attr) {
if (scope.$last === true) {
$timeout(function () {
scope.$emit('ngRepeatFinished');
});
}
}
};
})
.directive('iframeIsLoaded', function ($timeout) {
return {
restrict: 'A',
link: function (scope, element, attr) {
element.load(function () {
var iframe = (element.context.contentWindow || element.context.contentDocument);
if(iframe && iframe.document.getElementById("umbracoPreviewBadge"))
iframe.document.getElementById("umbracoPreviewBadge").style.display = "none";
if (!document.getElementById("resultFrame").contentWindow.refreshLayout) {
scope.frameLoaded = true;
scope.$apply();
}
});
}
};
})
/*********************************************************************************************************/
/* Background editor */
/*********************************************************************************************************/
angular.module("Umbraco.canvasdesigner")
.controller("Umbraco.canvasdesigner.background", function ($scope, dialogService) {
if (!$scope.item.values) {
$scope.item.values = {
imageorpattern: '',
color: ''
};
}
$scope.open = function (field) {
var config = {
template: "mediaPickerModal.html",
change: function (data) {
$scope.item.values.imageorpattern = data;
},
callback: function (data) {
$scope.item.values.imageorpattern = data;
},
cancel: function (data) {
$scope.item.values.imageorpattern = data;
},
dialogData: $scope.googleFontFamilies,
dialogItem: $scope.item.values.imageorpattern
};
dialogService.open(config);
};
})
.controller('canvasdesigner.mediaPickerModal', function ($scope, $http, mediaResource, umbRequestHelper, entityResource, mediaHelper) {
if (mediaHelper && mediaHelper.registerFileResolver) {
mediaHelper.registerFileResolver("Umbraco.UploadField", function (property, entity, thumbnail) {
if (thumbnail) {
if (mediaHelper.detectIfImageByExtension(property.value)) {
var thumbnailUrl = umbRequestHelper.getApiUrl(
"imagesApiBaseUrl",
"GetBigThumbnail",
[{ originalImagePath: property.value }]);
return thumbnailUrl;
}
else {
return null;
}
}
else {
return property.value;
}
});
}
var modalFieldvalue = $scope.dialogItem;
$scope.currentFolder = {};
$scope.currentFolder.children = [];
$scope.currentPath = [];
$scope.startNodeId = -1;
$scope.options = {
url: umbRequestHelper.getApiUrl("mediaApiBaseUrl", "PostAddFile"),
formData: {
currentFolder: $scope.startNodeId
}
};
//preload selected item
$scope.selectedMedia = undefined;
$scope.submitFolder = function (e) {
if (e.keyCode === 13) {
e.preventDefault();
$scope.$parent.data.showFolderInput = false;
if ($scope.$parent.data.newFolder && $scope.$parent.data.newFolder != "") {
mediaResource
.addFolder($scope.$parent.data.newFolder, $scope.currentFolder.id)
.then(function (data) {
$scope.$parent.data.newFolder = undefined;
$scope.gotoFolder(data);
});
}
}
};
$scope.gotoFolder = function (folder) {
if (!folder) {
folder = { id: $scope.startNodeId, name: "Media", icon: "icon-folder" };
}
if (folder.id > 0) {
var matches = _.filter($scope.currentPath, function (value, index) {
if (value.id == folder.id) {
value.indexInPath = index;
return value;
}
});
if (matches && matches.length > 0) {
$scope.currentPath = $scope.currentPath.slice(0, matches[0].indexInPath + 1);
}
else {
$scope.currentPath.push(folder);
}
}
else {
$scope.currentPath = [];
}
//mediaResource.rootMedia()
mediaResource.getChildren(folder.id)
.then(function (data) {
folder.children = data.items ? data.items : [];
angular.forEach(folder.children, function (child) {
child.isFolder = child.contentTypeAlias == "Folder" ? true : false;
if (!child.isFolder) {
angular.forEach(child.properties, function (property) {
if (property.alias == "umbracoFile" && property.value)
{
child.thumbnail = mediaHelper.resolveFile(child, true);
child.image = property.value;
}
})
}
});
$scope.options.formData.currentFolder = folder.id;
$scope.currentFolder = folder;
});
};
$scope.iconFolder = "glyphicons-icon folder-open"
$scope.selectMedia = function (media) {
if (!media.isFolder) {
//we have 3 options add to collection (if multi) show details, or submit it right back to the callback
$scope.selectedMedia = media;
modalFieldvalue = "url(" + $scope.selectedMedia.image + ")";
$scope.change(modalFieldvalue);
}
else {
$scope.gotoFolder(media);
}
};
//default root item
if (!$scope.selectedMedia) {
$scope.gotoFolder();
}
$scope.submitAndClose = function () {
if (modalFieldvalue != "") {
$scope.submit(modalFieldvalue);
} else {
$scope.cancel();
}
};
$scope.cancelAndClose = function () {
$scope.cancel();
}
})
/*********************************************************************************************************/
/* Background editor */
/*********************************************************************************************************/
angular.module("Umbraco.canvasdesigner")
.controller("Umbraco.canvasdesigner.border", function ($scope, dialogService) {
$scope.defaultBorderList = ["all", "left", "right", "top", "bottom"];
$scope.borderList = [];
$scope.bordertypes = ["solid", "dashed", "dotted"];
$scope.selectedBorder = {
name: "all",
size: 0,
color: '',
type: ''
};
$scope.setselectedBorder = function (bordertype) {
if (bordertype == "all") {
$scope.selectedBorder.name="all";
$scope.selectedBorder.size= $scope.item.values.bordersize;
$scope.selectedBorder.color= $scope.item.values.bordercolor;
$scope.selectedBorder.type= $scope.item.values.bordertype;
}
if (bordertype == "left") {
$scope.selectedBorder.name= "left";
$scope.selectedBorder.size= $scope.item.values.leftbordersize;
$scope.selectedBorder.color= $scope.item.values.leftbordercolor;
$scope.selectedBorder.type= $scope.item.values.leftbordertype;
}
if (bordertype == "right") {
$scope.selectedBorder.name= "right";
$scope.selectedBorder.size= $scope.item.values.rightbordersize;
$scope.selectedBorder.color= $scope.item.values.rightbordercolor;
$scope.selectedBorder.type= $scope.item.values.rightbordertype;
}
if (bordertype == "top") {
$scope.selectedBorder.name= "top";
$scope.selectedBorder.size= $scope.item.values.topbordersize;
$scope.selectedBorder.color= $scope.item.values.topbordercolor;
$scope.selectedBorder.type= $scope.item.values.topbordertype;
}
if (bordertype == "bottom") {
$scope.selectedBorder.name= "bottom";
$scope.selectedBorder.size= $scope.item.values.bottombordersize;
$scope.selectedBorder.color= $scope.item.values.bottombordercolor;
$scope.selectedBorder.type= $scope.item.values.bottombordertype;
}
}
if (!$scope.item.values) {
$scope.item.values = {
bordersize: '',
bordercolor: '',
bordertype: 'solid',
leftbordersize: '',
leftbordercolor: '',
leftbordertype: 'solid',
rightbordersize: '',
rightbordercolor: '',
rightbordertype: 'solid',
topbordersize: '',
topbordercolor: '',
topbordertype: 'solid',
bottombordersize: '',
bottombordercolor: '',
bottombordertype: 'solid',
};
}
if ($scope.item.enable) {
angular.forEach($scope.defaultBorderList, function (key, indexKey) {
if ($.inArray(key, $scope.item.enable) >= 0) {
$scope.borderList.splice($scope.borderList.length + 1, 0, key);
}
})
}
else {
$scope.borderList = $scope.defaultBorderList;
}
$scope.$watch("valueAreLoaded", function () {
$scope.setselectedBorder($scope.borderList[0]);
}, false);
$scope.$watch("selectedBorder", function () {
if ($scope.selectedBorder.name == "all") {
$scope.item.values.bordersize = $scope.selectedBorder.size;
$scope.item.values.bordertype = $scope.selectedBorder.type;
}
if ($scope.selectedBorder.name == "left") {
$scope.item.values.leftbordersize = $scope.selectedBorder.size;
$scope.item.values.leftbordertype = $scope.selectedBorder.type;
}
if ($scope.selectedBorder.name == "right") {
$scope.item.values.rightbordersize = $scope.selectedBorder.size;
$scope.item.values.rightbordertype = $scope.selectedBorder.type;
}
if ($scope.selectedBorder.name == "top") {
$scope.item.values.topbordersize = $scope.selectedBorder.size;
$scope.item.values.topbordertype = $scope.selectedBorder.type;
}
if ($scope.selectedBorder.name == "bottom") {
$scope.item.values.bottombordersize = $scope.selectedBorder.size;
$scope.item.values.bottombordertype = $scope.selectedBorder.type;
}
}, true)
})
/*********************************************************************************************************/
/* color editor */
/*********************************************************************************************************/
angular.module("Umbraco.canvasdesigner")
.controller("Umbraco.canvasdesigner.color", function ($scope) {
if (!$scope.item.values) {
$scope.item.values = {
color: ''
};
}
})
/*********************************************************************************************************/
/* google font editor */
/*********************************************************************************************************/
angular.module("Umbraco.canvasdesigner")
.controller("Umbraco.canvasdesigner.googlefontpicker", function ($scope, dialogService) {
if (!$scope.item.values) {
$scope.item.values = {
fontFamily: '',
fontType: '',
fontWeight: '',
fontStyle: '',
}
}
$scope.setStyleVariant = function () {
if ($scope.item.values != undefined) {
return {
'font-family': $scope.item.values.fontFamily,
'font-weight': $scope.item.values.fontWeight,
'font-style': $scope.item.values.fontStyle
}
}
};
$scope.open = function (field) {
var config = {
template: "googlefontdialog.html",
change: function (data) {
$scope.item.values = data;
},
callback: function (data) {
$scope.item.values = data;
},
cancel: function (data) {
$scope.item.values = data;
},
dialogData: $scope.googleFontFamilies,
dialogItem: $scope.item.values
};
dialogService.open(config);
};
})
.controller("googlefontdialog.controller", function ($scope) {
$scope.safeFonts = ["Arial, Helvetica", "Impact", "Lucida Sans Unicode", "Tahoma", "Trebuchet MS", "Verdana", "Georgia", "Times New Roman", "Courier New, Courier"];
$scope.fonts = [];
$scope.selectedFont = {};
var googleGetWeight = function (googleVariant) {
return (googleVariant != undefined && googleVariant != "") ? googleVariant.replace("italic", "") : "";
};
var googleGetStyle = function (googleVariant) {
var variantStyle = "";
if (googleVariant != undefined && googleVariant != "" && googleVariant.indexOf("italic") >= 0) {
variantWeight = googleVariant.replace("italic", "");
variantStyle = "italic";
}
return variantStyle;
};
angular.forEach($scope.safeFonts, function (value, key) {
$scope.fonts.push({
groupName: "Safe fonts",
fontType: "safe",
fontFamily: value,
fontWeight: "normal",
fontStyle: "normal",
});
});
angular.forEach($scope.dialogData.items, function (value, key) {
var variants = value.variants;
var variant = value.variants.length > 0 ? value.variants[0] : "";
var fontWeight = googleGetWeight(variant);
var fontStyle = googleGetStyle(variant);
$scope.fonts.push({
groupName: "Google fonts",
fontType: "google",
fontFamily: value.family,
variants: value.variants,
variant: variant,
fontWeight: fontWeight,
fontStyle: fontStyle
});
});
$scope.setStyleVariant = function () {
if ($scope.dialogItem != undefined) {
return {
'font-family': $scope.selectedFont.fontFamily,
'font-weight': $scope.selectedFont.fontWeight,
'font-style': $scope.selectedFont.fontStyle
}
}
};
$scope.showFontPreview = function (font, variant) {
if (!variant)
variant = font.variant;
if (font != undefined && font.fontFamily != "" && font.fontType == "google") {
// Font needs to be independently loaded in the iframe for live preview to work.
document.getElementById("resultFrame").contentWindow.getFont(font.fontFamily + ":" + variant);
WebFont.load({
google: {
families: [font.fontFamily + ":" + variant]
},
loading: function () {
console.log('loading');
},
active: function () {
$scope.selectedFont = font;
$scope.selectedFont.fontWeight = googleGetWeight(variant);
$scope.selectedFont.fontStyle = googleGetStyle(variant);
// If $apply isn't called, the new font family isn't applied until the next user click.
$scope.change({
fontFamily: $scope.selectedFont.fontFamily,
fontType: $scope.selectedFont.fontType,
fontWeight: $scope.selectedFont.fontWeight,
fontStyle: $scope.selectedFont.fontStyle,
});
}
});
}
else {
// Font is available, apply it immediately in modal preview.
$scope.selectedFont = font;
// If $apply isn't called, the new font family isn't applied until the next user click.
$scope.change({
fontFamily: $scope.selectedFont.fontFamily,
fontType: $scope.selectedFont.fontType,
fontWeight: $scope.selectedFont.fontWeight,
fontStyle: $scope.selectedFont.fontStyle,
});
}
}
$scope.cancelAndClose = function () {
$scope.cancel();
}
$scope.submitAndClose = function () {
$scope.submit({
fontFamily: $scope.selectedFont.fontFamily,
fontType: $scope.selectedFont.fontType,
fontWeight: $scope.selectedFont.fontWeight,
fontStyle: $scope.selectedFont.fontStyle,
});
};
if ($scope.dialogItem != undefined) {
angular.forEach($scope.fonts, function (value, key) {
if (value.fontFamily == $scope.dialogItem.fontFamily) {
$scope.selectedFont = value;
$scope.selectedFont.variant = $scope.dialogItem.fontWeight + $scope.dialogItem.fontStyle;
$scope.selectedFont.fontWeight = $scope.dialogItem.fontWeight;
$scope.selectedFont.fontStyle = $scope.dialogItem.fontStyle;
}
});
}
});
/*********************************************************************************************************/
/* grid row editor */
/*********************************************************************************************************/
angular.module("Umbraco.canvasdesigner")
.controller("Umbraco.canvasdesigner.gridRow", function ($scope) {
if (!$scope.item.values) {
$scope.item.values = {
fullsize: false
};
}
})
/*********************************************************************************************************/
/* Layout */
/*********************************************************************************************************/
angular.module("Umbraco.canvasdesigner")
.controller("Umbraco.canvasdesigner.layout", function ($scope) {
if (!$scope.item.values) {
$scope.item.values = {
layout: ""
}
}
})
/*********************************************************************************************************/
/* margin editor */
/*********************************************************************************************************/
angular.module("Umbraco.canvasdesigner")
.controller("Umbraco.canvasdesigner.margin", function ($scope, dialogService) {
$scope.defaultmarginList = ["all", "left", "right", "top", "bottom"];
$scope.marginList = [];
$scope.selectedmargin = {
name: "",
value: 0,
};
$scope.setSelectedmargin = function (margintype) {
if (margintype == "all") {
$scope.selectedmargin.name = "all";
$scope.selectedmargin.value = $scope.item.values.marginvalue;
}
if (margintype == "left") {
$scope.selectedmargin.name = "left";
$scope.selectedmargin.value = $scope.item.values.leftmarginvalue;
}
if (margintype == "right") {
$scope.selectedmargin.name = "right";
$scope.selectedmargin.value = $scope.item.values.rightmarginvalue;
}
if (margintype == "top") {
$scope.selectedmargin.name = "top";
$scope.selectedmargin.value = $scope.item.values.topmarginvalue;
}
if (margintype == "bottom") {
$scope.selectedmargin.name = "bottom";
$scope.selectedmargin.value = $scope.item.values.bottommarginvalue;
}
}
if (!$scope.item.values) {
$scope.item.values = {
marginvalue: $scope.item.defaultValue && $scope.item.defaultValue.length > 0 ? $scope.item.defaultValue[0] : '',
leftmarginvalue: $scope.item.defaultValue && $scope.item.defaultValue.length > 1 ? $scope.item.defaultValue[1] : '',
rightmarginvalue: $scope.item.defaultValue && $scope.item.defaultValue.length > 2 ? $scope.item.defaultValue[2] : '',
topmarginvalue: $scope.item.defaultValue && $scope.item.defaultValue.length > 3 ? $scope.item.defaultValue[3] : '',
bottommarginvalue: $scope.item.defaultValue && $scope.item.defaultValue.length > 4 ? $scope.item.defaultValue[4] : '',
};
}
if ($scope.item.enable) {
angular.forEach($scope.defaultmarginList, function (key, indexKey) {
if ($.inArray(key, $scope.item.enable) >= 0) {
$scope.marginList.splice($scope.marginList.length + 1, 0, key);
}
})
}
else {
$scope.marginList = $scope.defaultmarginList;
}
$scope.$watch("valueAreLoaded", function () {
$scope.setSelectedmargin($scope.marginList[0]);
}, false);
$scope.$watch("selectedmargin", function () {
if ($scope.selectedmargin.name == "all") {
$scope.item.values.marginvalue = $scope.selectedmargin.value;
}
if ($scope.selectedmargin.name == "left") {
$scope.item.values.leftmarginvalue = $scope.selectedmargin.value;
}
if ($scope.selectedmargin.name == "right") {
$scope.item.values.rightmarginvalue = $scope.selectedmargin.value;
}
if ($scope.selectedmargin.name == "top") {
$scope.item.values.topmarginvalue = $scope.selectedmargin.value;
}
if ($scope.selectedmargin.name == "bottom") {
$scope.item.values.bottommarginvalue = $scope.selectedmargin.value;
}
}, true)
})
/*********************************************************************************************************/
/* padding editor */
/*********************************************************************************************************/
angular.module("Umbraco.canvasdesigner")
.controller("Umbraco.canvasdesigner.padding", function ($scope, dialogService) {
$scope.defaultPaddingList = ["all", "left", "right", "top", "bottom"];
$scope.paddingList = [];
$scope.selectedpadding = {
name: "",
value: 0,
};
$scope.setSelectedpadding = function (paddingtype) {
if (paddingtype == "all") {
$scope.selectedpadding.name="all";
$scope.selectedpadding.value= $scope.item.values.paddingvalue;
}
if (paddingtype == "left") {
$scope.selectedpadding.name= "left";
$scope.selectedpadding.value= $scope.item.values.leftpaddingvalue;
}
if (paddingtype == "right") {
$scope.selectedpadding.name= "right";
$scope.selectedpadding.value= $scope.item.values.rightpaddingvalue;
}
if (paddingtype == "top") {
$scope.selectedpadding.name= "top";
$scope.selectedpadding.value= $scope.item.values.toppaddingvalue;
}
if (paddingtype == "bottom") {
$scope.selectedpadding.name= "bottom";
$scope.selectedpadding.value= $scope.item.values.bottompaddingvalue;
}
}
if (!$scope.item.values) {
$scope.item.values = {
paddingvalue: $scope.item.defaultValue && $scope.item.defaultValue.length > 0 ? $scope.item.defaultValue[0] : '',
leftpaddingvalue: $scope.item.defaultValue && $scope.item.defaultValue.length > 1 ? $scope.item.defaultValue[1] : '',
rightpaddingvalue: $scope.item.defaultValue && $scope.item.defaultValue.length > 2 ? $scope.item.defaultValue[2] : '',
toppaddingvalue: $scope.item.defaultValue && $scope.item.defaultValue.length > 3 ? $scope.item.defaultValue[3] : '',
bottompaddingvalue: $scope.item.defaultValue && $scope.item.defaultValue.length > 4 ? $scope.item.defaultValue[4] : '',
};
}
if ($scope.item.enable) {
angular.forEach($scope.defaultPaddingList, function (key, indexKey) {
if ($.inArray(key, $scope.item.enable) >= 0) {
$scope.paddingList.splice($scope.paddingList.length + 1, 0, key);
}
})
}
else {
$scope.paddingList = $scope.defaultPaddingList;
}
$scope.$watch("valueAreLoaded", function () {
$scope.setSelectedpadding($scope.paddingList[0]);
}, false);
$scope.$watch( "selectedpadding", function () {
if ($scope.selectedpadding.name == "all") {
$scope.item.values.paddingvalue = $scope.selectedpadding.value;
}
if ($scope.selectedpadding.name == "left") {
$scope.item.values.leftpaddingvalue = $scope.selectedpadding.value;
}
if ($scope.selectedpadding.name == "right") {
$scope.item.values.rightpaddingvalue = $scope.selectedpadding.value;
}
if ($scope.selectedpadding.name == "top") {
$scope.item.values.toppaddingvalue = $scope.selectedpadding.value;
}
if ($scope.selectedpadding.name == "bottom") {
$scope.item.values.bottompaddingvalue = $scope.selectedpadding.value;
}
}, true)
})
/*********************************************************************************************************/
/* radius editor */
/*********************************************************************************************************/
angular.module("Umbraco.canvasdesigner")
.controller("Umbraco.canvasdesigner.radius", function ($scope, dialogService) {
$scope.defaultRadiusList = ["all", "topleft", "topright", "bottomleft", "bottomright"];
$scope.radiusList = [];
$scope.selectedradius = {
name: "",
value: 0,
};
$scope.setSelectedradius = function (radiustype) {
if (radiustype == "all") {
$scope.selectedradius.name="all";
$scope.selectedradius.value= $scope.item.values.radiusvalue;
}
if (radiustype == "topleft") {
$scope.selectedradius.name = "topleft";
$scope.selectedradius.value = $scope.item.values.topleftradiusvalue;
}
if (radiustype == "topright") {
$scope.selectedradius.name = "topright";
$scope.selectedradius.value = $scope.item.values.toprightradiusvalue;
}
if (radiustype == "bottomleft") {
$scope.selectedradius.name = "bottomleft";
$scope.selectedradius.value = $scope.item.values.bottomleftradiusvalue;
}
if (radiustype == "bottomright") {
$scope.selectedradius.name = "bottomright";
$scope.selectedradius.value = $scope.item.values.bottomrightradiusvalue;
}
}
if (!$scope.item.values) {
$scope.item.values = {
radiusvalue: $scope.item.defaultValue && $scope.item.defaultValue.length > 0 ? $scope.item.defaultValue[0] : '',
topleftradiusvalue: $scope.item.defaultValue && $scope.item.defaultValue.length > 1 ? $scope.item.defaultValue[1] : '',
toprightradiusvalue: $scope.item.defaultValue && $scope.item.defaultValue.length > 2 ? $scope.item.defaultValue[2] : '',
bottomleftradiusvalue: $scope.item.defaultValue && $scope.item.defaultValue.length > 3 ? $scope.item.defaultValue[3] : '',
bottomrightradiusvalue: $scope.item.defaultValue && $scope.item.defaultValue.length > 4 ? $scope.item.defaultValue[4] : '',
};
}
if ($scope.item.enable) {
angular.forEach($scope.defaultRadiusList, function (key, indexKey) {
if ($.inArray(key, $scope.item.enable) >= 0) {
$scope.radiusList.splice($scope.radiusList.length + 1, 0, key);
}
})
}
else {
$scope.radiusList = $scope.defaultRadiusList;
}
$scope.$watch("valueAreLoaded", function () {
$scope.setSelectedradius($scope.radiusList[0]);
}, false);
$scope.$watch( "selectedradius", function () {
if ($scope.selectedradius.name == "all") {
$scope.item.values.radiusvalue = $scope.selectedradius.value;
}
if ($scope.selectedradius.name == "topleft") {
$scope.item.values.topleftradiusvalue = $scope.selectedradius.value;
}
if ($scope.selectedradius.name == "topright") {
$scope.item.values.toprightradiusvalue = $scope.selectedradius.value;
}
if ($scope.selectedradius.name == "bottomleft") {
$scope.item.values.bottomleftradiusvalue = $scope.selectedradius.value;
}
if ($scope.selectedradius.name == "bottomright") {
$scope.item.values.bottomrightradiusvalue = $scope.selectedradius.value;
}
}, true)
})
/*********************************************************************************************************/
/* shadow editor */
/*********************************************************************************************************/
angular.module("Umbraco.canvasdesigner")
.controller("Umbraco.canvasdesigner.shadow", function ($scope) {
if (!$scope.item.values) {
$scope.item.values = {
shadow: ''
}
}
})
/*********************************************************************************************************/
/* slider editor */
/*********************************************************************************************************/
angular.module("Umbraco.canvasdesigner")
.controller("Umbraco.canvasdesigner.slider", function ($scope) {
if (!$scope.item.values) {
$scope.item.values = {
slider: ''
}
}
})
/*********************************************************************************************************/
/* spectrum color picker directive */
/*********************************************************************************************************/
angular.module('colorpicker', ['spectrumcolorpicker'])
.directive('colorpicker', ['dialogService', function (dialogService) {
return {
restrict: 'EA',
scope: {
ngModel: '='
},
link: function (scope, $element) {
scope.openColorDialog = function () {
var config = {
template: "colorModal.html",
change: function (data) {
scope.ngModel = data;
},
callback: function (data) {
scope.ngModel = data;
},
cancel: function (data) {
scope.ngModel = data;
},
dialogItem: scope.ngModel,
scope: scope
};
dialogService.open(config);
}
scope.setColor = false;
scope.submitAndClose = function () {
if (scope.ngModel != "") {
scope.setColor = true;
scope.submit(scope.ngModel);
} else {
scope.cancel();
}
};
scope.cancelAndClose = function () {
scope.cancel();
}
},
template:
'<div>' +
'<div class="color-picker-preview" ng-click="openColorDialog()" style="background: {{ngModel}} !important;"></div>' +
'<script type="text/ng-template" id="colorModal.html">' +
'<div class="modal-header">' +
'<h1>Header</h1>' +
'</div>' +
'<div class="modal-body">' +
'<spectrum colorselected="ngModel" set-color="setColor" flat="true" show-palette="true"></spectrum>' +
'</div>' +
'<div class="right">' +
'<a class="btn" href="#" ng-click="cancelAndClose()">Cancel</a>' +
'<a class="btn btn-success" href="#" ng-click="submitAndClose()">Done</a>' +
'</div>' +
'</script>' +
'</div>',
replace: true
};
}])
/*********************************************************************************************************/
/* jQuery UI Slider plugin wrapper */
/*********************************************************************************************************/
angular.module("Umbraco.canvasdesigner").factory('dialogService', function ($rootScope, $q, $http, $timeout, $compile, $templateCache) {
function closeDialog(dialog, destroyScope) {
if (dialog.element) {
dialog.element.removeClass("selected");
dialog.element.html("");
if (destroyScope) {
dialog.scope.$destroy();
}
}
}
function open() {
}
return {
open: function (options) {
var defaults = {
template: "",
callback: undefined,
change: undefined,
cancel: undefined,
element: undefined,
dialogItem: undefined,
dialogData: undefined
};
var dialog = angular.extend(defaults, options);
var destroyScope = true;
if (options && options.scope) {
destroyScope = false;
}
var scope = (options && options.scope) || $rootScope.$new();
// Save original value for cancel action
var originalDialogItem = angular.copy(dialog.dialogItem);
dialog.element = $(".float-panel");
/************************************/
// Close dialog if the user clicks outside the dialog. (Not working well with colorpickers and datepickers)
$(document).mousedown(function (e) {
var container = dialog.element;
if (!container.is(e.target) && container.has(e.target).length === 0) {
closeDialog(dialog, destroyScope);
}
});
/************************************/
$q.when($templateCache.get(dialog.template) || $http.get(dialog.template, { cache: true }).then(function (res) { return res.data; }))
.then(function onSuccess(template) {
dialog.element.html(template);
$timeout(function () {
$compile(dialog.element)(scope);
});
dialog.element.addClass("selected")
scope.cancel = function () {
if (dialog.cancel) {
dialog.cancel(originalDialogItem);
}
closeDialog(dialog, destroyScope);
}
scope.change = function (data) {
if (dialog.change) {
dialog.change(data);
}
}
scope.submit = function (data) {
if (dialog.callback) {
dialog.callback(data);
}
closeDialog(dialog, destroyScope);
};
scope.close = function () {
closeDialog(dialog, destroyScope);
}
scope.dialogData = dialog.dialogData;
scope.dialogItem = dialog.dialogItem;
dialog.scope = scope;
});
return dialog;
},
close: function() {
var modal = $(".float-panel");
modal.removeClass("selected")
}
}
});
/*********************************************************************************************************/
/* jQuery UI Slider plugin wrapper */
/*********************************************************************************************************/
angular.module('ui.slider', []).value('uiSliderConfig', {}).directive('uiSlider', ['uiSliderConfig', '$timeout', function (uiSliderConfig, $timeout) {
uiSliderConfig = uiSliderConfig || {};
return {
require: 'ngModel',
template: '<div><div class="slider" /><input class="slider-input" style="display:none" ng-model="value"></div>',
replace: true,
compile: function () {
return function (scope, elm, attrs, ngModel) {
scope.value = ngModel.$viewValue;
function parseNumber(n, decimals) {
return (decimals) ? parseFloat(n) : parseInt(n);
};
var options = angular.extend(scope.$eval(attrs.uiSlider) || {}, uiSliderConfig);
// Object holding range values
var prevRangeValues = {
min: null,
max: null
};
// convenience properties
var properties = ['min', 'max', 'step'];
var useDecimals = (!angular.isUndefined(attrs.useDecimals)) ? true : false;
var init = function () {
// When ngModel is assigned an array of values then range is expected to be true.
// Warn user and change range to true else an error occurs when trying to drag handle
if (angular.isArray(ngModel.$viewValue) && options.range !== true) {
console.warn('Change your range option of ui-slider. When assigning ngModel an array of values then the range option should be set to true.');
options.range = true;
}
// Ensure the convenience properties are passed as options if they're defined
// This avoids init ordering issues where the slider's initial state (eg handle
// position) is calculated using widget defaults
// Note the properties take precedence over any duplicates in options
angular.forEach(properties, function (property) {
if (angular.isDefined(attrs[property])) {
options[property] = parseNumber(attrs[property], useDecimals);
}
});
elm.find(".slider").slider(options);
init = angular.noop;
};
// Find out if decimals are to be used for slider
angular.forEach(properties, function (property) {
// support {{}} and watch for updates
attrs.$observe(property, function (newVal) {
if (!!newVal) {
init();
elm.find(".slider").slider('option', property, parseNumber(newVal, useDecimals));
}
});
});
attrs.$observe('disabled', function (newVal) {
init();
elm.find(".slider").slider('option', 'disabled', !!newVal);
});
// Watch ui-slider (byVal) for changes and update
scope.$watch(attrs.uiSlider, function (newVal) {
init();
if (newVal != undefined) {
elm.find(".slider").slider('option', newVal);
elm.find(".ui-slider-handle").html("<span>" + ui.value + "px</span>")
}
}, true);
// Late-bind to prevent compiler clobbering
$timeout(init, 0, true);
// Update model value from slider
elm.find(".slider").bind('slidestop', function (event, ui) {
ngModel.$setViewValue(ui.values || ui.value);
scope.$apply();
});
elm.bind('slide', function (event, ui) {
event.stopPropagation();
elm.find(".slider-input").val(ui.value);
elm.find(".ui-slider-handle").html("<span>" + ui.value + "px</span>")
});
// Update slider from model value
ngModel.$render = function () {
init();
var method = options.range === true ? 'values' : 'value';
if (isNaN(ngModel.$viewValue) && !(ngModel.$viewValue instanceof Array))
ngModel.$viewValue = 0;
if (ngModel.$viewValue == '')
ngModel.$viewValue = 0;
scope.value = ngModel.$viewValue;
// Do some sanity check of range values
if (options.range === true) {
// Check outer bounds for min and max values
if (angular.isDefined(options.min) && options.min > ngModel.$viewValue[0]) {
ngModel.$viewValue[0] = options.min;
}
if (angular.isDefined(options.max) && options.max < ngModel.$viewValue[1]) {
ngModel.$viewValue[1] = options.max;
}
// Check min and max range values
if (ngModel.$viewValue[0] >= ngModel.$viewValue[1]) {
// Min value should be less to equal to max value
if (prevRangeValues.min >= ngModel.$viewValue[1])
ngModel.$viewValue[0] = prevRangeValues.min;
// Max value should be less to equal to min value
if (prevRangeValues.max <= ngModel.$viewValue[0])
ngModel.$viewValue[1] = prevRangeValues.max;
}
// Store values for later user
prevRangeValues.min = ngModel.$viewValue[0];
prevRangeValues.max = ngModel.$viewValue[1];
}
elm.find(".slider").slider(method, ngModel.$viewValue);
elm.find(".ui-slider-handle").html("<span>" + ngModel.$viewValue + "px</span>")
};
scope.$watch("value", function () {
ngModel.$setViewValue(scope.value);
}, true);
scope.$watch(attrs.ngModel, function () {
if (options.range === true) {
ngModel.$render();
}
}, true);
function destroy() {
elm.find(".slider").slider('destroy');
}
elm.find(".slider").bind('$destroy', destroy);
};
}
};
}]);
/*********************************************************************************************************/
/* spectrum color picker directive */
/*********************************************************************************************************/
angular.module('spectrumcolorpicker', [])
.directive('spectrum', function () {
return {
restrict: 'E',
transclude: true,
scope: {
colorselected: '=',
setColor: '=',
flat: '=',
showPalette: '='
},
link: function (scope, $element) {
var initColor;
$element.find("input").spectrum({
color: scope.colorselected,
allowEmpty: true,
preferredFormat: "hex",
showAlpha: true,
showInput: true,
flat: scope.flat,
localStorageKey: "spectrum.panel",
showPalette: scope.showPalette,
palette: [],
change: function (color) {
if (color) {
scope.colorselected = color.toRgbString();
}
else {
scope.colorselected = '';
}
scope.$apply();
},
move: function (color) {
scope.colorselected = color.toRgbString();
scope.$apply();
},
beforeShow: function (color) {
initColor = angular.copy(scope.colorselected);
$(this).spectrum("container").find(".sp-cancel").click(function (e) {
scope.colorselected = initColor;
scope.$apply();
});
},
});
scope.$watch('setcolor', function (setColor) {
if (scope.$eval(setColor) === true) {
$element.find("input").spectrum("set", scope.colorselected);
}
}, true);
},
template:
' <div class="spectrumcolorpicker"><div class="real-color-preview" style="background-color:{{colorselected}}"></div><input type=\'text\' ng-model=\'colorselected\' /></div>',
replace: true
};
})
|
joo.classLoader.prepare("package flash.events",/* {*/
/**
* An SharedObject object representing a remote shared object dispatches a SyncEvent object when the remote shared object has been updated by the server. There is only one type of <code>sync</code> event: <code>SyncEvent.SYNC</code>.
* @see flash.net.SharedObject
*
*/
"public class SyncEvent extends flash.events.Event",2,function($$private){;return[
/**
* An array of objects; each object contains properties that describe the changed members of a remote shared object. The properties of each object are <code>code</code>, <code>name</code>, and <code>oldValue</code>.
* <p>When you initially connect to a remote shared object that is persistent locally and/or on the server, all the properties of this object are set to empty strings.</p>
* <p>Otherwise, Flash sets <code>code</code> to <code>"clear"</code>, <code>"success"</code>, <code>"reject"</code>, <code>"change"</code>, or <code>"delete"</code>.</p>
* <ul>
* <li>A value of <code>"clear"</code> means either that you have successfully connected to a remote shared object that is not persistent on the server or the client, or that all the properties of the object have been deleted--for example, when the client and server copies of the object are so far out of sync that Flash Player resynchronizes the client object with the server object. In the latter case, <code>SyncEvent.SYNC</code> is dispatched and the "code" value is set to <code>"change"</code>.</li>
* <li>A value of <code>"success"</code> means the client changed the shared object.</li>
* <li>A value of <code>"reject"</code> means the client tried unsuccessfully to change the object; instead, another client changed the object.</li>
* <li>A value of <code>"change"</code> means another client changed the object or the server resynchronized the object.</li>
* <li>A value of <code>"delete"</code> means the attribute was deleted.</li></ul>
* <p>The <code>name</code> property contains the name of the property that has been changed.</p>
* <p>The <code>oldValue</code> property contains the former value of the changed property. This parameter is <code>null</code> unless code has a value of <code>"reject"</code> or <code>"change"</code>.</p>
* @see flash.net.NetConnection
* @see flash.net.NetStream
*
*/
"public native function get changeList"/*():Array*/,
/**
* @private
*/
"public native function set changeList"/*(value:Array):void*/,
/**
* Creates an Event object that contains information about <code>sync</code> events. Event objects are passed as parameters to event listeners.
* @param type The type of the event. Event listeners can access this information through the inherited <code>type</code> property. There is only one type of sync event: <code>SyncEvent.SYNC</code>.
* @param bubbles Determines whether the Event object participates in the bubbling stage of the event flow. Event listeners can access this information through the inherited <code>bubbles</code> property.
* @param cancelable Determines whether the Event object can be canceled. Event listeners can access this information through the inherited <code>cancelable</code> property.
* @param changeList An array of objects that describe the synchronization with the remote SharedObject. Event listeners can access this object through the <code>changeList</code> property.
*
* @see #changeList
*
*/
"public function SyncEvent",function SyncEvent$(type/*:String*/, bubbles/*:Boolean = false*/, cancelable/*:Boolean = false*/, changeList/*:Array = null*/) {if(arguments.length<4){if(arguments.length<3){if(arguments.length<2){bubbles = false;}cancelable = false;}changeList = null;}
flash.events.Event.call(this,type, bubbles, cancelable);
this.changeList = changeList;
},
/**
* Creates a copy of the SyncEvent object and sets the value of each property to match that of the original.
* @return A new SyncEvent object with property values that match those of the original.
*
*/
"override public function clone",function clone()/*:Event*/ {
return new flash.events.SyncEvent(this.type, this.bubbles, this.cancelable, this.changeList);
},
/**
* Returns a string that contains all the properties of the SyncEvent object. The string is in the following format:
* <p><code>[SyncEvent type=<i>value</i> bubbles=<i>value</i> cancelable=<i>value</i> changeList=<i>value</i>]</code></p>
* @return A string that contains all the properties of the SyncEvent object.
*
*/
"override public function toString",function toString()/*:String*/ {
return this.formatToString("SyncEvent", "type", "bubbles", "cancelable", "changeList");
},
/**
* Defines the value of the <code>type</code> property of a <code>sync</code> event object.
* <p>This event has the following properties:</p>
* <table>
* <tr><th>Property</th><th>Value</th></tr>
* <tr>
* <td><code>bubbles</code></td>
* <td><code>false</code></td></tr>
* <tr>
* <td><code>cancelable</code></td>
* <td><code>false</code>; there is no default behavior to cancel.</td></tr>
* <tr>
* <td><code>currentTarget</code></td>
* <td>The object that is actively processing the Event object with an event listener.</td></tr>
* <tr>
* <td><code>changeList</code></td>
* <td>An array with properties that describe the array's status.</td></tr>
* <tr>
* <td><code>target</code></td>
* <td>The SharedObject instance that has been updated by the server.</td></tr></table>
* @see flash.net.SharedObject#event:sync
*
*/
"public static const",{ SYNC/*:String*/ : "sync"},
];},[],["flash.events.Event"], "0.8.0", "0.9.6"
);
|
// activate touch action css
import 'ember-hammertime/components/component';
export default {
name: 'ember-hammertime',
initialize() {}
};
|
'use strict';
define(['utils'], function (Utils) {
'use strict';
var coreLoops = null;
var frame = 0;
var fps = 0;
var period = Math.floor(1000 / 60);
var nextTime = 0;
var lastCount = 0;
var frameCount = 0;
/**
* FUNCTION DEFINITIONS
*/
function loop(time) {
if (coreLoops) {
requestAnimationFrame(loop);
if (time <= Loop.time + period) {
return;
}
Loop.time = Math.floor(time / period) * period;
for (var i = 0; coreLoops && i < coreLoops.length; i++) {
coreLoops[i]();
}
frameCount++;
if (time - lastCount > 1000) {
fps = frameCount;
frameCount = 0;
lastCount = time;
}
}
}
function addLoop(callback) {
if (coreLoops === null) {
coreLoops = [];
beginLoop();
}
coreLoops.push(callback);
}
function removeLoop(callback) {
if (coreLoops) {
var index = coreLoops.indexOf(callback);
coreLoops.splice(index, 1);
if (coreLoops.length === 0) {
coreLoops = null;
}
}
}
function beginLoop() {
loop(0);
}
function loopTime() {
return performance.now() - Loop.time;
}
function destroyEverything() {
coreLoops = null;
frame = 0;
fps = 0;
period = Math.floor(1000 / 60);
nextTime = 0;
lastCount = 0;
frameCount = 0;
}
/**
* PUBLIC DECLARATIONS
*/
function Loop() {}
Loop.addLoop = addLoop;
Loop.removeLoop = removeLoop;
Utils.onDestroy(Loop);
Object.defineProperty(Loop, "fps", {
enumerable: false,
configurable: false,
get: function get() {
return fps;
},
set: function set(value) {
period = Math.floor(1000 / value);
}
});
/**
* PROCESSES
*/
Loop.time = 0;
return Loop;
});
//# sourceMappingURL=loop.js.map
|
var waitSeconds = 100;
var head = document.getElementsByTagName('head')[0];
// get all link tags in the page
var links = document.getElementsByTagName('link');
var linkHrefs = [];
for (var i = 0; i < links.length; i++) {
linkHrefs.push(links[i].href);
}
var isWebkit = !!window.navigator.userAgent.match(/AppleWebKit\/([^ ;]*)/);
var webkitLoadCheck = function(link, callback) {
setTimeout(function() {
for (var i = 0; i < document.styleSheets.length; i++) {
var sheet = document.styleSheets[i];
if (sheet.href == link.href)
return callback();
}
webkitLoadCheck(link, callback);
}, 10);
}
var noop = function() {}
var loadCSS = function(url) {
return new Promise(function(resolve, reject) {
var timeout = setTimeout(function() {
reject('Unable to load CSS');
}, waitSeconds * 1000);
var _callback = function() {
clearTimeout(timeout);
link.onload = noop;
setTimeout(resolve, 7);
}
var link = document.createElement('link') ;
link.type = 'text/css';
link.rel = 'stylesheet';
link.href = url;
if (!isWebkit)
link.onload = _callback;
else
webkitLoadCheck(link, _callback);
head.appendChild(link);
});
}
exports.fetch = function(load) {
// dont reload styles loaded in the head
for (var i = 0; i < linkHrefs.length; i++)
if (load.address == linkHrefs[i])
return callback();
return loadCSS(load.address);
}
|
<<<<<<< HEAD
<<<<<<< HEAD
module.exports = rimraf
rimraf.sync = rimrafSync
var assert = require("assert")
var path = require("path")
var fs = require("fs")
// for EMFILE handling
var timeout = 0
exports.EMFILE_MAX = 1000
exports.BUSYTRIES_MAX = 3
var isWindows = (process.platform === "win32")
function defaults (options) {
var methods = [
'unlink',
'chmod',
'stat',
'rmdir',
'readdir'
]
methods.forEach(function(m) {
options[m] = options[m] || fs[m]
m = m + 'Sync'
options[m] = options[m] || fs[m]
})
}
function rimraf (p, options, cb) {
if (typeof options === 'function') {
cb = options
options = {}
}
assert(p)
assert(options)
assert(typeof cb === 'function')
defaults(options)
if (!cb) throw new Error("No callback passed to rimraf()")
var busyTries = 0
rimraf_(p, options, function CB (er) {
if (er) {
if (isWindows && (er.code === "EBUSY" || er.code === "ENOTEMPTY") &&
busyTries < exports.BUSYTRIES_MAX) {
busyTries ++
var time = busyTries * 100
// try again, with the same exact callback as this one.
return setTimeout(function () {
rimraf_(p, options, CB)
}, time)
}
// this one won't happen if graceful-fs is used.
if (er.code === "EMFILE" && timeout < exports.EMFILE_MAX) {
return setTimeout(function () {
rimraf_(p, options, CB)
}, timeout ++)
}
// already gone
if (er.code === "ENOENT") er = null
}
timeout = 0
cb(er)
})
}
// Two possible strategies.
// 1. Assume it's a file. unlink it, then do the dir stuff on EPERM or EISDIR
// 2. Assume it's a directory. readdir, then do the file stuff on ENOTDIR
//
// Both result in an extra syscall when you guess wrong. However, there
// are likely far more normal files in the world than directories. This
// is based on the assumption that a the average number of files per
// directory is >= 1.
//
// If anyone ever complains about this, then I guess the strategy could
// be made configurable somehow. But until then, YAGNI.
function rimraf_ (p, options, cb) {
assert(p)
assert(options)
assert(typeof cb === 'function')
options.unlink(p, function (er) {
if (er) {
if (er.code === "ENOENT")
return cb(null)
if (er.code === "EPERM")
return (isWindows)
? fixWinEPERM(p, options, er, cb)
: rmdir(p, options, er, cb)
if (er.code === "EISDIR")
return rmdir(p, options, er, cb)
}
return cb(er)
})
}
function fixWinEPERM (p, options, er, cb) {
assert(p)
assert(options)
assert(typeof cb === 'function')
if (er)
assert(er instanceof Error)
options.chmod(p, 666, function (er2) {
if (er2)
cb(er2.code === "ENOENT" ? null : er)
else
options.stat(p, function(er3, stats) {
if (er3)
cb(er3.code === "ENOENT" ? null : er)
else if (stats.isDirectory())
rmdir(p, options, er, cb)
else
options.unlink(p, cb)
})
})
}
function fixWinEPERMSync (p, options, er) {
assert(p)
assert(options)
if (er)
assert(er instanceof Error)
try {
options.chmodSync(p, 666)
} catch (er2) {
if (er2.code === "ENOENT")
return
else
throw er
}
try {
var stats = options.statSync(p)
} catch (er3) {
if (er3.code === "ENOENT")
return
else
throw er
}
if (stats.isDirectory())
rmdirSync(p, options, er)
else
options.unlinkSync(p)
}
function rmdir (p, options, originalEr, cb) {
assert(p)
assert(options)
if (originalEr)
assert(originalEr instanceof Error)
assert(typeof cb === 'function')
// try to rmdir first, and only readdir on ENOTEMPTY or EEXIST (SunOS)
// if we guessed wrong, and it's not a directory, then
// raise the original error.
options.rmdir(p, function (er) {
if (er && (er.code === "ENOTEMPTY" || er.code === "EEXIST" || er.code === "EPERM"))
rmkids(p, options, cb)
else if (er && er.code === "ENOTDIR")
cb(originalEr)
else
cb(er)
})
}
function rmkids(p, options, cb) {
assert(p)
assert(options)
assert(typeof cb === 'function')
options.readdir(p, function (er, files) {
if (er)
return cb(er)
var n = files.length
if (n === 0)
return options.rmdir(p, cb)
var errState
files.forEach(function (f) {
rimraf(path.join(p, f), options, function (er) {
if (errState)
return
if (er)
return cb(errState = er)
if (--n === 0)
options.rmdir(p, cb)
})
})
})
}
// this looks simpler, and is strictly *faster*, but will
// tie up the JavaScript thread and fail on excessively
// deep directory trees.
function rimrafSync (p, options) {
options = options || {}
defaults(options)
assert(p)
assert(options)
try {
options.unlinkSync(p)
} catch (er) {
if (er.code === "ENOENT")
return
if (er.code === "EPERM")
return isWindows ? fixWinEPERMSync(p, options, er) : rmdirSync(p, options, er)
if (er.code !== "EISDIR")
throw er
rmdirSync(p, options, er)
}
}
function rmdirSync (p, options, originalEr) {
assert(p)
assert(options)
if (originalEr)
assert(originalEr instanceof Error)
try {
options.rmdirSync(p)
} catch (er) {
if (er.code === "ENOENT")
return
if (er.code === "ENOTDIR")
throw originalEr
if (er.code === "ENOTEMPTY" || er.code === "EEXIST" || er.code === "EPERM")
rmkidsSync(p, options)
}
}
function rmkidsSync (p, options) {
assert(p)
assert(options)
options.readdirSync(p).forEach(function (f) {
rimrafSync(path.join(p, f), options)
})
options.rmdirSync(p, options)
}
=======
module.exports = rimraf
rimraf.sync = rimrafSync
var assert = require("assert")
var path = require("path")
var fs = require("fs")
// for EMFILE handling
var timeout = 0
exports.EMFILE_MAX = 1000
exports.BUSYTRIES_MAX = 3
var isWindows = (process.platform === "win32")
function defaults (options) {
var methods = [
'unlink',
'chmod',
'stat',
'rmdir',
'readdir'
]
methods.forEach(function(m) {
options[m] = options[m] || fs[m]
m = m + 'Sync'
options[m] = options[m] || fs[m]
})
}
function rimraf (p, options, cb) {
if (typeof options === 'function') {
cb = options
options = {}
}
assert(p)
assert(options)
assert(typeof cb === 'function')
defaults(options)
if (!cb) throw new Error("No callback passed to rimraf()")
var busyTries = 0
rimraf_(p, options, function CB (er) {
if (er) {
if (isWindows && (er.code === "EBUSY" || er.code === "ENOTEMPTY") &&
busyTries < exports.BUSYTRIES_MAX) {
busyTries ++
var time = busyTries * 100
// try again, with the same exact callback as this one.
return setTimeout(function () {
rimraf_(p, options, CB)
}, time)
}
// this one won't happen if graceful-fs is used.
if (er.code === "EMFILE" && timeout < exports.EMFILE_MAX) {
return setTimeout(function () {
rimraf_(p, options, CB)
}, timeout ++)
}
// already gone
if (er.code === "ENOENT") er = null
}
timeout = 0
cb(er)
})
}
// Two possible strategies.
// 1. Assume it's a file. unlink it, then do the dir stuff on EPERM or EISDIR
// 2. Assume it's a directory. readdir, then do the file stuff on ENOTDIR
//
// Both result in an extra syscall when you guess wrong. However, there
// are likely far more normal files in the world than directories. This
// is based on the assumption that a the average number of files per
// directory is >= 1.
//
// If anyone ever complains about this, then I guess the strategy could
// be made configurable somehow. But until then, YAGNI.
function rimraf_ (p, options, cb) {
assert(p)
assert(options)
assert(typeof cb === 'function')
options.unlink(p, function (er) {
if (er) {
if (er.code === "ENOENT")
return cb(null)
if (er.code === "EPERM")
return (isWindows)
? fixWinEPERM(p, options, er, cb)
: rmdir(p, options, er, cb)
if (er.code === "EISDIR")
return rmdir(p, options, er, cb)
}
return cb(er)
})
}
function fixWinEPERM (p, options, er, cb) {
assert(p)
assert(options)
assert(typeof cb === 'function')
if (er)
assert(er instanceof Error)
options.chmod(p, 666, function (er2) {
if (er2)
cb(er2.code === "ENOENT" ? null : er)
else
options.stat(p, function(er3, stats) {
if (er3)
cb(er3.code === "ENOENT" ? null : er)
else if (stats.isDirectory())
rmdir(p, options, er, cb)
else
options.unlink(p, cb)
})
})
}
function fixWinEPERMSync (p, options, er) {
assert(p)
assert(options)
if (er)
assert(er instanceof Error)
try {
options.chmodSync(p, 666)
} catch (er2) {
if (er2.code === "ENOENT")
return
else
throw er
}
try {
var stats = options.statSync(p)
} catch (er3) {
if (er3.code === "ENOENT")
return
else
throw er
}
if (stats.isDirectory())
rmdirSync(p, options, er)
else
options.unlinkSync(p)
}
function rmdir (p, options, originalEr, cb) {
assert(p)
assert(options)
if (originalEr)
assert(originalEr instanceof Error)
assert(typeof cb === 'function')
// try to rmdir first, and only readdir on ENOTEMPTY or EEXIST (SunOS)
// if we guessed wrong, and it's not a directory, then
// raise the original error.
options.rmdir(p, function (er) {
if (er && (er.code === "ENOTEMPTY" || er.code === "EEXIST" || er.code === "EPERM"))
rmkids(p, options, cb)
else if (er && er.code === "ENOTDIR")
cb(originalEr)
else
cb(er)
})
}
function rmkids(p, options, cb) {
assert(p)
assert(options)
assert(typeof cb === 'function')
options.readdir(p, function (er, files) {
if (er)
return cb(er)
var n = files.length
if (n === 0)
return options.rmdir(p, cb)
var errState
files.forEach(function (f) {
rimraf(path.join(p, f), options, function (er) {
if (errState)
return
if (er)
return cb(errState = er)
if (--n === 0)
options.rmdir(p, cb)
})
})
})
}
// this looks simpler, and is strictly *faster*, but will
// tie up the JavaScript thread and fail on excessively
// deep directory trees.
function rimrafSync (p, options) {
options = options || {}
defaults(options)
assert(p)
assert(options)
try {
options.unlinkSync(p)
} catch (er) {
if (er.code === "ENOENT")
return
if (er.code === "EPERM")
return isWindows ? fixWinEPERMSync(p, options, er) : rmdirSync(p, options, er)
if (er.code !== "EISDIR")
throw er
rmdirSync(p, options, er)
}
}
function rmdirSync (p, options, originalEr) {
assert(p)
assert(options)
if (originalEr)
assert(originalEr instanceof Error)
try {
options.rmdirSync(p)
} catch (er) {
if (er.code === "ENOENT")
return
if (er.code === "ENOTDIR")
throw originalEr
if (er.code === "ENOTEMPTY" || er.code === "EEXIST" || er.code === "EPERM")
rmkidsSync(p, options)
}
}
function rmkidsSync (p, options) {
assert(p)
assert(options)
options.readdirSync(p).forEach(function (f) {
rimrafSync(path.join(p, f), options)
})
options.rmdirSync(p, options)
}
>>>>>>> b875702c9c06ab5012e52ff4337439b03918f453
=======
module.exports = rimraf
rimraf.sync = rimrafSync
var assert = require("assert")
var path = require("path")
var fs = require("fs")
// for EMFILE handling
var timeout = 0
exports.EMFILE_MAX = 1000
exports.BUSYTRIES_MAX = 3
var isWindows = (process.platform === "win32")
function defaults (options) {
var methods = [
'unlink',
'chmod',
'stat',
'rmdir',
'readdir'
]
methods.forEach(function(m) {
options[m] = options[m] || fs[m]
m = m + 'Sync'
options[m] = options[m] || fs[m]
})
}
function rimraf (p, options, cb) {
if (typeof options === 'function') {
cb = options
options = {}
}
assert(p)
assert(options)
assert(typeof cb === 'function')
defaults(options)
if (!cb) throw new Error("No callback passed to rimraf()")
var busyTries = 0
rimraf_(p, options, function CB (er) {
if (er) {
if (isWindows && (er.code === "EBUSY" || er.code === "ENOTEMPTY") &&
busyTries < exports.BUSYTRIES_MAX) {
busyTries ++
var time = busyTries * 100
// try again, with the same exact callback as this one.
return setTimeout(function () {
rimraf_(p, options, CB)
}, time)
}
// this one won't happen if graceful-fs is used.
if (er.code === "EMFILE" && timeout < exports.EMFILE_MAX) {
return setTimeout(function () {
rimraf_(p, options, CB)
}, timeout ++)
}
// already gone
if (er.code === "ENOENT") er = null
}
timeout = 0
cb(er)
})
}
// Two possible strategies.
// 1. Assume it's a file. unlink it, then do the dir stuff on EPERM or EISDIR
// 2. Assume it's a directory. readdir, then do the file stuff on ENOTDIR
//
// Both result in an extra syscall when you guess wrong. However, there
// are likely far more normal files in the world than directories. This
// is based on the assumption that a the average number of files per
// directory is >= 1.
//
// If anyone ever complains about this, then I guess the strategy could
// be made configurable somehow. But until then, YAGNI.
function rimraf_ (p, options, cb) {
assert(p)
assert(options)
assert(typeof cb === 'function')
options.unlink(p, function (er) {
if (er) {
if (er.code === "ENOENT")
return cb(null)
if (er.code === "EPERM")
return (isWindows)
? fixWinEPERM(p, options, er, cb)
: rmdir(p, options, er, cb)
if (er.code === "EISDIR")
return rmdir(p, options, er, cb)
}
return cb(er)
})
}
function fixWinEPERM (p, options, er, cb) {
assert(p)
assert(options)
assert(typeof cb === 'function')
if (er)
assert(er instanceof Error)
options.chmod(p, 666, function (er2) {
if (er2)
cb(er2.code === "ENOENT" ? null : er)
else
options.stat(p, function(er3, stats) {
if (er3)
cb(er3.code === "ENOENT" ? null : er)
else if (stats.isDirectory())
rmdir(p, options, er, cb)
else
options.unlink(p, cb)
})
})
}
function fixWinEPERMSync (p, options, er) {
assert(p)
assert(options)
if (er)
assert(er instanceof Error)
try {
options.chmodSync(p, 666)
} catch (er2) {
if (er2.code === "ENOENT")
return
else
throw er
}
try {
var stats = options.statSync(p)
} catch (er3) {
if (er3.code === "ENOENT")
return
else
throw er
}
if (stats.isDirectory())
rmdirSync(p, options, er)
else
options.unlinkSync(p)
}
function rmdir (p, options, originalEr, cb) {
assert(p)
assert(options)
if (originalEr)
assert(originalEr instanceof Error)
assert(typeof cb === 'function')
// try to rmdir first, and only readdir on ENOTEMPTY or EEXIST (SunOS)
// if we guessed wrong, and it's not a directory, then
// raise the original error.
options.rmdir(p, function (er) {
if (er && (er.code === "ENOTEMPTY" || er.code === "EEXIST" || er.code === "EPERM"))
rmkids(p, options, cb)
else if (er && er.code === "ENOTDIR")
cb(originalEr)
else
cb(er)
})
}
function rmkids(p, options, cb) {
assert(p)
assert(options)
assert(typeof cb === 'function')
options.readdir(p, function (er, files) {
if (er)
return cb(er)
var n = files.length
if (n === 0)
return options.rmdir(p, cb)
var errState
files.forEach(function (f) {
rimraf(path.join(p, f), options, function (er) {
if (errState)
return
if (er)
return cb(errState = er)
if (--n === 0)
options.rmdir(p, cb)
})
})
})
}
// this looks simpler, and is strictly *faster*, but will
// tie up the JavaScript thread and fail on excessively
// deep directory trees.
function rimrafSync (p, options) {
options = options || {}
defaults(options)
assert(p)
assert(options)
try {
options.unlinkSync(p)
} catch (er) {
if (er.code === "ENOENT")
return
if (er.code === "EPERM")
return isWindows ? fixWinEPERMSync(p, options, er) : rmdirSync(p, options, er)
if (er.code !== "EISDIR")
throw er
rmdirSync(p, options, er)
}
}
function rmdirSync (p, options, originalEr) {
assert(p)
assert(options)
if (originalEr)
assert(originalEr instanceof Error)
try {
options.rmdirSync(p)
} catch (er) {
if (er.code === "ENOENT")
return
if (er.code === "ENOTDIR")
throw originalEr
if (er.code === "ENOTEMPTY" || er.code === "EEXIST" || er.code === "EPERM")
rmkidsSync(p, options)
}
}
function rmkidsSync (p, options) {
assert(p)
assert(options)
options.readdirSync(p).forEach(function (f) {
rimrafSync(path.join(p, f), options)
})
options.rmdirSync(p, options)
}
>>>>>>> b875702c9c06ab5012e52ff4337439b03918f453
|
var path = require('path');
var webpack = require('webpack');
module.exports = {
devtool: 'eval',
entry: [
'webpack-dev-server/client?http://localhost:3000',
'webpack/hot/only-dev-server',
'./app/App'
],
output: {
path: path.join(__dirname, 'public'),
filename: 'bundle.js',
publicPath: '/static/'
},
plugins: [
new webpack.HotModuleReplacementPlugin()
],
module: {
loaders: [{
test: /\.js$/,
loaders: ['react-hot', 'babel'],
include: [
path.join(__dirname, 'app/components'),
path.join(__dirname, 'app')
]
},{
test: /\.css$/,
loader: "style!css",
include: [
path.join(__dirname, 'app/styles')
]
}]
}
};
|
import { expect } from 'chai';
import assignDeep from 'object-assign-deep';
import Console from 'winston/lib/winston/transports/console';
import File from 'winston/lib/winston/transports/file';
import { the, when, withScenario, should } from '../../testing/src';
import getWinston from '../src/core/winstonProvider';
const assertInstance = result => {
expect(result).to.not.be.undefined;
expect(typeof result.info).to.equal('function');
};
the('winstonProvider', () => {
const config = { shared: { appName: 'testapp' } };
when('instance requested', () => {
withScenario('local env config', () => {
const result = getWinston(assignDeep(config, { shared: { env: 'local' } }));
should('return a valid winston instance', () => {
assertInstance(result);
});
should('initialise console transport', () => {
const transport = result.transports[0];
expect(transport).to.not.be.undefined;
expect(transport instanceof Console).to.be.true;
});
});
withScenario('non-local env config', () => {
const result = getWinston(assignDeep(config, { shared: { env: 'some_other_env' } }));
const transport = result.transports[0];
should('return a valid winston instance', () => {
assertInstance(result);
});
should('initialise file transport', () => {
expect(transport).to.not.be.undefined;
expect(transport instanceof File).to.be.true;
});
should('include app name & env in logfile name', () => {
expect(transport.filename.length).to.be.above(0);
expect(transport.filename.includes('testapp')).to.equal(true);
expect(transport.filename.includes('some_other_env')).to.equal(true);
});
});
});
});
|
var b2World = Box2D.Dynamics.b2World;
var b2DebugDraw = Box2D.Dynamics.b2DebugDraw;
var b2Vec2 = Box2D.Common.Math.b2Vec2;
var b2Color = Box2D.Common.b2Color;
var b2AABB = Box2D.Collision.b2AABB;
var b2BodyDef = Box2D.Dynamics.b2BodyDef;
var b2Body = Box2D.Dynamics.b2Body;
var b2FixtureDef = Box2D.Dynamics.b2FixtureDef;
var b2Fixture = Box2D.Dynamics.b2Fixture;
var b2MassData = Box2D.Collision.Shapes.b2MassData;
var b2PolygonShape = Box2D.Collision.Shapes.b2PolygonShape;
var b2CircleShape = Box2D.Collision.Shapes.b2CircleShape;
var b2MouseJointDef = Box2D.Dynamics.Joints.b2MouseJointDef;
var b2ContactListener = Box2D.Dynamics.b2ContactListener;
|
(function ($, Drupal) {
Drupal.behaviors.reventlovtime = {
attach: function (context, settings) {
$('#edit-cronperiod').timepicker({
hourMin: 0,
hourMax: 0,
showHour: false,
stepMinute: 10,
});
$('#edit-crontime').timepicker({ });
var startTimeTextBox = $('#edit-cronstart');
var endTimeTextBox = $('#edit-cronend');
$.timepicker.timeRange(
startTimeTextBox,
endTimeTextBox,
{
minInterval: (1000*60*60), // 1hr
timeFormat: 'HH:mm',
stepHour: 1,
showMinute: false,
start: {}, // start picker options
end: {} // end picker options
});
}
}
}(jQuery, Drupal));
|
var Model = require("./base");
module.exports = Model.extend({
url: "/time"
});
module.exports.id = "Time";
|
var searchData=
[
['o',['O',['../namespace_lumengine.html#a72e1aee4161e394b4686c476f44b2722af186217753c37b9b9f958d906208506e',1,'Lumengine']]],
['offset',['offset',['../struct_lumengine_1_1_component.html#ae12d9c5762358d0fa5ff699b5f490ae2',1,'Lumengine::Component']]],
['operator_28_29',['operator()',['../class_lumengine_1_1_signal.html#aa979bd2da5bf28eaef222af2a56a6528',1,'Lumengine::Signal']]]
];
|
/*jslint browser: true*/
/*global $, jQuery, Backbone*/
var Excercise = Backbone.Model.extend({
initialize: function () {
"use strict";
},
defaults: {
data : [{
name: "",
pict: "",
answer: "",
isValid: null
}]
}
});
var ExcerciseCollection = Backbone.Collection.extend({
initialize : function () {
"use strict";
},
model : Excercise
});
var excercise = new Excercise({
data: [
{
name: "fogg",
pict: "img/exercise1/1.png",
isValid: null,
answer: "foggy"
},
{
name: "raining",
pict: "img/exercise1/2.png",
isValid: null,
answer: "raining"
},
{
name: "sunny",
pict: "img/exercise1/3.png",
isValid: null,
answer: "sunny"
},
{
name: "cloudy",
pict: "img/exercise1/4.png",
isValid: null,
answer: "cloudy"
},
{
name: "windy",
pict: "img/exercise1/5.png",
isValid: null,
answer: "windy"
},
{
name: "snowing",
pict: "img/exercise1/6.png",
isValid: null,
answer: "snowing"
}
]
});
|
'use strict';
var FormProxy = require('./FormProxy');
/**
* Updates all tagged form entries with a corresponding value from a model
* @param {FormProxy} proxy A proxy representing the form to update
* @param {Model} model A model object
*/
function updateForm(proxy, model) {
proxy.set(model.data);
}
/**
* Handles updating the model based on a form change
* @param {FormProxy} proxy A proxy representing the form that has changed
* @param {Model} model A model object
* @param {Event} evt A native event object
*/
function updateModel(proxy, model, evt) {
var key = evt.target.name;
evt.stopPropagation();
proxy.debounce(function(done) {
model.set(key, proxy.get(key));
done();
});
}
/**
* Creates a new form controller bound to the specified model
* @param {Element} element An element containing form elements
*/
function createFormController(model) {
return function(element) {
var proxy = new FormProxy(element);
// Model --> Form binding
model.addListener(updateForm.bind(this, proxy));
// Form --> model binding
proxy.on('change', updateModel.bind(this, proxy, model));
};
}
module.exports = createFormController;
|
'use strict';
/**
* Module dependencies.
*/
var should = require('should'),
mongoose = require('mongoose'),
User = mongoose.model('User'),
Softwareproductversion = mongoose.model('Softwareproductversion');
/**
* Globals
*/
var user, softwareproductversion;
/**
* Unit tests
*/
describe('Softwareproductversion Model Unit Tests:', function() {
beforeEach(function(done) {
user = new User({
firstName: 'Full',
lastName: 'Name',
displayName: 'Full Name',
email: 'test@test.com',
username: 'username',
password: 'password'
});
user.save(function() {
softwareproductversion = new Softwareproductversion({
name: 'Softwareproductversion Name',
user: user
});
done();
});
});
describe('Method Save', function() {
it('should be able to save without problems', function(done) {
return softwareproductversion.save(function(err) {
should.not.exist(err);
done();
});
});
it('should be able to show an error when try to save without name', function(done) {
softwareproductversion.name = '';
return softwareproductversion.save(function(err) {
should.exist(err);
done();
});
});
});
afterEach(function(done) {
Softwareproductversion.remove().exec();
User.remove().exec();
done();
});
});
|
/*function escalar() {
var sen = document.getElementById("hemi_sen");
console.log(sen);
sen.attr({
"width": function() {
return this.parentElement.clientWidth;
},
"height": function() {
var currentWidth = this.parentElement.clientWidth
return parseFloat(currentWidth * (parseFloat(height) / parseFloat(width)));
}
});
width = parseFloat(svg_sen.attr("width"));
height = parseFloat(svg_sen.attr("height"));
};*/
//scroll
function scrollaTo_sen(h) {
'use strict';
var top = document.getElementById(h).offsetTop;
window.scrollTo(0, top);
}
//pagination
/*function pagination_sen() {
'use strict';
var req_num_row = 8;
var $tr = jQuery(".trLista_sen");
var total_num_row = $tr.length;
var num_pages = 0;
if (total_num_row % req_num_row === 0) {
num_pages = total_num_row / req_num_row;
}
if (total_num_row % req_num_row >= 1) {
num_pages = total_num_row / req_num_row;
num_pages++;
num_pages = Math.floor(num_pages++);
}
for (var i = 1; i <= num_pages; i++) {
jQuery('#pagination_sen').append(" " + "<a>" + i + "</a>" + " ");
}
$tr.each(function(i) {
jQuery(this).hide();
if (i + 1 <= req_num_row) {
$tr.eq(i).show();
}
});
jQuery('#pagination_sen a').click(function(e) {
e.preventDefault();
$tr.hide();
var page = jQuery(this).text();
var temp = page - 1;
var start = temp * req_num_row;
//alert(start);
var i;
for (i = 0; i < req_num_row; i++) {
$tr.eq(start + i).show();
}
scrollaTo('ancla_bottom_sen');
});
}*/
//end pagination
//DATA
//Fuerza is a constructor function.
var Fuerza_sen = function Fuerza_sen(AFIRMATIVO, NEGATIVO, ABSTENCION, AUSENTE) {
/* "this" below is the new object that is being created (i.e., this = new Object();) */
'use strict';
this.AFIRMATIVO = AFIRMATIVO;
this.NEGATIVO = NEGATIVO;
this.ABSTENCION = ABSTENCION;
this.AUSENTE = AUSENTE;
/* when the function is called with the new keyword "this" is returned
instead of undefined */
};
// instantiate a Fuerza object named cambiemos
var CAMBIEMOS = new Fuerza_sen(0, 0, 0, 0);
var FPV_y_aliados = new Fuerza_sen(0, 0, 0, 0);
var IZQUIERDA = new Fuerza_sen(0, 0, 0, 0);
var OTROS = new Fuerza_sen(0, 0, 0, 0);
var PJ_DISIDENTE = new Fuerza_sen(0, 0, 0, 0);
var PROGRESISTAS = new Fuerza_sen(0, 0, 0, 0);
var UNA = new Fuerza_sen(0, 0, 0, 0);
// Combinar en objeto
var FUERZAS_sen = {
CAMBIEMOS: CAMBIEMOS,
FPV_y_aliados: FPV_y_aliados,
IZQUIERDA: IZQUIERDA,
OTROS: OTROS,
PJ_DISIDENTE: PJ_DISIDENTE,
PROGRESISTAS: PROGRESISTAS,
UNA: UNA
};
var totAfirmativos_sen = 0;
var totNegativos_sen = 0;
var totAusentes_sen = 0;
var totAbstenciones_sen = 0;
var totVotaron_sen = 0;
//Toggle
/*function toggleHidden_sen(id) {
'use strict';
var elem = document.getElementById(id);
if (elem.hasAttribute("hidden")) {
elem.removeAttribute("hidden");
setTimeout(function() {
elem.setAttribute("hidden", "hidden");
}, 60000);
} else {
elem.setAttribute("hidden", "hidden");
}
}*/
//Formatear con ceros
function pad_with_zeroes(number, length) {
'use strict';
var my_string = '' + number;
while (my_string.length < length) {
my_string = '0' + my_string;
}
return my_string;
}
function changeElements_sen(id) {
'use strict';
$(".AFIRMATIVO").css("fill", "url(#diagonalHatch_sen)");
$(".NEGATIVO").css("fill", "url(#diagonalHatch2_sen)");
$(".ABSTENCION").css("fill", "url(#diagonalHatch3_sen)");
$(".AUSENTE").css("fill", "url(#diagonalHatch4_sen)");
$(".AFIRMATIVO").css("stroke", "#FFF");
$(".NEGATIVO").css("stroke", "#FFF");
$(".ABSTENCION").css("stroke", "#FFF");
$(".AUSENTE").css("stroke", "#FFF");
var af = document.getElementById(id + "_AFIRMATIVO_sen");
af.style.fill = '#009BDB';
var neg = document.getElementById(id + "_NEGATIVO_sen");
neg.style.fill = '#DB002E';
var ab = document.getElementById(id + "_ABSTENCION_sen");
ab.style.fill = 'black';
var au = document.getElementById(id + "_AUSENTE_sen");
//if (au.style.fill!== undefined){ au.style.fill = "red"};
au.style.fill = '#808080';
document.getElementById("afirma_sen").innerHTML = FUERZAS_sen[id].AFIRMATIVO;
document.getElementById("negat_sen").innerHTML = FUERZAS_sen[id].NEGATIVO;
document.getElementById("absten_sen").innerHTML = FUERZAS_sen[id].ABSTENCION;
document.getElementById("ausen_sen").innerHTML = FUERZAS_sen[id].AUSENTE;
document.getElementById("tot_sen").innerHTML = FUERZAS_sen[id].AFIRMATIVO + FUERZAS_sen[id].NEGATIVO + FUERZAS_sen[id].ABSTENCION + FUERZAS_sen[id].AUSENTE;
setTimeout(function() {
$(".AFIRMATIVO").css("fill", "#009BDB");
$(".NEGATIVO").css("fill", "#DB002E");
$(".ABSTENCION").css("fill", "black");
$(".AUSENTE").css("fill", "#808080");
$(".AFIRMATIVO").css("stroke", "#009BDB");
$(".NEGATIVO").css("stroke", "#DB002E");
$(".ABSTENCION").css("stroke", "black");
$(".AUSENTE").css("stroke", "#808080");
af.style.fill = "#009BDB";
neg.style.fill = "#DB002E";
ab.style.fill = "black";
au.style.fill = "#808080";
document.getElementById("afirma_sen").innerHTML = totAfirmativos_sen;
document.getElementById("negat_sen").innerHTML = totNegativos_sen;
document.getElementById("absten_sen").innerHTML = totAbstenciones_sen;
document.getElementById("ausen_sen").innerHTML = totAusentes_sen;
document.getElementById("tot_sen").innerHTML = totVotaron_sen;
}, 60000);
}
function changeElementsOut_sen(id) {
'use strict';
$(".AFIRMATIVO").css("fill", "#009BDB");
$(".NEGATIVO").css("fill", "#DB002E");
$(".ABSTENCION").css("fill", "black");
$(".AUSENTE").css("fill", "#808080");
$(".AFIRMATIVO").css("stroke", "#009BDB");
$(".NEGATIVO").css("stroke", "#DB002E");
$(".ABSTENCION").css("stroke", "black");
$(".AUSENTE").css("stroke", "#808080");
var af = document.getElementById(id + "_AFIRMATIVO_sen");
var neg = document.getElementById(id + "_NEGATIVO_sen");
var ab = document.getElementById(id + "_ABSTENCION_sen");
var au = document.getElementById(id + "_AUSENTE_sen");
af.style.fill = "#009BDB";
neg.style.fill = "#DB002E";
ab.style.fill = "black";
au.style.fill = "#808080";
document.getElementById("afirma_sen").innerHTML = totAfirmativos_sen;
document.getElementById("negat_sen").innerHTML = totNegativos_sen;
document.getElementById("absten_sen").innerHTML = totAbstenciones_sen;
document.getElementById("ausen_sen").innerHTML = totAusentes_sen;
document.getElementById("tot_sen").innerHTML = totVotaron_sen;
}
//Request con d3
var archivo_sen = d3.csv("datos_senadores_16_03_2016.csv", function(dataFromCSV_sen) {
//var FUERZAS = {};
'use strict';
dataFromCSV_sen.forEach(function(sourceItem) {
FUERZAS_sen[sourceItem.fuerza][sourceItem.voto] = FUERZAS_sen[sourceItem.fuerza][sourceItem.voto] + 1;
});
//Arrays
function resultObject(obj, tvoto) {
var arr = [];
var prop;
for (prop in obj) {
if (obj.hasOwnProperty(prop)) {
arr.push({
forza: prop,
tVoto: tvoto,
value: obj[prop][tvoto]
});
}
}
return arr; // returns array
}
//Sumador de resultados
function resultSumador(obj) {
var tot = 0;
var i;
for (i = 0; i < obj.length; i++) {
tot = tot + parseFloat(obj[i].value);
}
//tot value: obj[prop][tvoto]
//console.log(tot);
return tot;
}
//Agrupar resultados
var afirmativos_sen = resultObject(FUERZAS_sen, "AFIRMATIVO");
var negativos_sen = resultObject(FUERZAS_sen, "NEGATIVO");
var abstenciones_sen = resultObject(FUERZAS_sen, "ABSTENCION");
var ausentes_sen = resultObject(FUERZAS_sen, "AUSENTE");
//Ordenar
afirmativos_sen = afirmativos_sen.sort(function(a, b) {
return d3.descending(a.value, b.value);
});
negativos_sen = negativos_sen.sort(function(a, b) {
return d3.descending(a.value, b.value);
});
abstenciones_sen = abstenciones_sen.sort(function(a, b) {
return d3.descending(a.value, b.value);
});
ausentes_sen = ausentes_sen.sort(function(a, b) {
return d3.descending(+a.value, +b.value);
});
//Unificar
var votaron_sen = afirmativos_sen.concat(negativos_sen).concat(abstenciones_sen).concat(ausentes_sen);
//Totales
totAfirmativos_sen = resultSumador(afirmativos_sen);
totNegativos_sen = resultSumador(negativos_sen);
totAusentes_sen = resultSumador(ausentes_sen);
totAbstenciones_sen = resultSumador(abstenciones_sen);
totVotaron_sen = resultSumador(votaron_sen);
//console.log(totVotaron_sen);
//ORDENAR DATOS CASE INSENSITIVE
dataFromCSV_sen.sort(function(a, b) {
return d3.ascending(a.senador.toLowerCase(), b.senador.toLowerCase());
});
var tabl_sen = d3.select("#div3_sen").append("table").attr('id', 'laLista_sen').attr('class', 'tablaLista').append("thead");
tabl_sen.append("tr");
tabl_sen.append("td").attr('class', 'listaHead').html("Nº");
tabl_sen.append("td").attr('class', 'listaHead').html("Senador");
tabl_sen.append("td").attr('class', 'listaHead').html("Fuerza");
tabl_sen.append("td").attr('class', 'listaHead').html("Partido/Bloque");
tabl_sen.append("td").attr('class', 'listaHead').html("Provincia");
tabl_sen.append("td").attr('class', 'listaHead').html("Voto");
var tabl2_sen = d3.select("#div3_sen").select("table").append("tbody");
var tr_sen = tabl2_sen.selectAll('tr').data(dataFromCSV_sen).enter().append("tr").attr('class', 'trLista_sen');
tr_sen.append("td").attr('class', 'index lista').html(function(d, i) {
return pad_with_zeroes(i + 1, 2);
});
tr_sen.append("td").attr('class', 'diput lista').html(function(d, i) {
return d.senador;
});
tr_sen.append("td").attr('class', 'fuer lista').html(function(d, i) {
return d.fuerza;
});
tr_sen.append("td").attr('class', 'bloqu lista').html(function(d, i) {
return d.partidoBloque;
});
tr_sen.append("td").attr('class', 'prov lista').html(function(d, i) {
return d.provincia;
});
tr_sen.append("td").attr('class', 'vot lista').html(function(d, i) {
return d.voto;
});
var width_sen = 480,
height_sen = 250,
radius_sen = width_sen / 2 - 16; //Math.min(width, height)/2;
var color_sen = d3.scale.ordinal()
.range(["#98abc5", "#8a89a6", "#7b6888", "#6b486b", "#a05d56", "#d0743c", "#ff8c00"]);
var arc_sen = d3.svg.arc()
.outerRadius(radius_sen + 5)
.innerRadius(radius_sen / 3 + 10);
var labelArc_sen = d3.svg.arc()
.outerRadius(radius_sen - 40)
.innerRadius(radius_sen - 40);
var pie_sen = d3.layout.pie()
.sort(null)
.startAngle(-Math.PI / 2)
.endAngle(Math.PI / 2)
.value(function(d) {
return d.value;
});
var svg_sen = d3.select("#divHemi_sen")
.append("svg")
.attr("width", width_sen)
.attr("height", height_sen)
.attr("id", "hemi_sen")
//.attr("viewBox", "750 0 2500 2500")
.append("g")
.attr("transform", "translate(" + width_sen / 2 + "," + (height_sen - 10) + ")");
svg_sen.append('defs')
.append('pattern')
.attr('id', 'diagonalHatch_sen')
.attr('patternUnits', 'userSpaceOnUse')
.attr('width', 4)
.attr('height', 4)
.append('path')
.attr('d', 'M-1,1 l2,-2 M0,4 l4,-4 M3,5 l2,-2')
.attr('stroke', '#009BDB')
.attr('stroke-width', 1);
svg_sen.append('defs')
.append('pattern')
.attr('id', 'diagonalHatch2_sen')
.attr('patternUnits', 'userSpaceOnUse')
.attr('width', 4)
.attr('height', 4)
.append('path')
.attr('d', 'M-1,1 l2,-2 M0,4 l4,-4 M3,5 l2,-2')
.attr('stroke', '#DB002E')
.attr('stroke-width', 1);
svg_sen.append('defs')
.append('pattern')
.attr('id', 'diagonalHatch3_sen')
.attr('patternUnits', 'userSpaceOnUse')
.attr('width', 4)
.attr('height', 4)
.append('path')
.attr('d', 'M-1,1 l2,-2 M0,4 l4,-4 M3,5 l2,-2')
.attr('stroke', 'black')
.attr('stroke-width', 1);
svg_sen.append('defs')
.append('pattern')
.attr('id', 'diagonalHatch4_sen')
.attr('patternUnits', 'userSpaceOnUse')
.attr('width', 4)
.attr('height', 4)
.append('path')
.attr('d', 'M-1,1 l2,-2 M0,4 l4,-4 M3,5 l2,-2')
.attr('stroke', '#808080')
.attr('stroke-width', 1);
var g_sen = svg_sen.selectAll(".arc")
.data(pie_sen(votaron_sen))
.enter().append("g")
.attr("class", function(d) {
return "arc" + " " + d.data.tVoto + " " + d.data.forza;
})
.attr("id", function(d) {
return d.data.forza + "_" + d.data.tVoto + "_sen";
});
g_sen.append("path")
.attr("d", arc_sen);
g_sen.append("text")
.attr("class", "svgText")
.attr("transform", "translate(" + -0 + "," + -30 + ")")
.text("Total");
g_sen.append("text")
.attr("class", "svgText2")
.attr("id","tot_sen")
.attr("transform", "translate(" + -30 + "," + -0 + ")")
.text("")
g_sen.append("text")
.attr("class", "svgText3")
.attr("transform", "translate(" + 30 + "," + -0 + ")")
.text("/ 72")
g_sen.append("line")
.attr("x1", "0")
.attr("y1", "-83")
.attr("x2", "0")
.attr("y2", "-120")
.attr("stroke", "white")
.attr("stroke-width", "1")
.attr("stroke-dasharray", "5,5");
document.getElementById("afirma_sen").innerHTML = totAfirmativos_sen;
document.getElementById("negat_sen").innerHTML = totNegativos_sen;
document.getElementById("absten_sen").innerHTML = totAbstenciones_sen;
document.getElementById("ausen_sen").innerHTML = totAusentes_sen;
document.getElementById("tot_sen").innerHTML = totVotaron_sen;
/*<line x1="0" y1="0" x2="200" y2="200" style="stroke:rgb(255,0,0);stroke-width:2" /> stroke-dasharray="5,5"*/
/*g.append("text")
//.attr("transform", "translate(" + -radius + "," + -radius + ")")
.attr("dx", "-30px")
.attr("dy", "0")
.attr("class","result")
.text("270");*/
//pagination request
/*jQuery('document').ready(function() {
pagination_sen();
});*/
//Botones
//Cambiemos
d3.select("#cam_sen")
.on("click", function() {
//filter
var dataB = dataFromCSV_sen.filter(function(d) {
if (d.fuerza === "CAMBIEMOS") {
return d;
}
})
renderTabla(dataB);
});
//FPV
d3.select("#fpv_sen")
.on("click", function() {
//filter
var dataB = dataFromCSV_sen.filter(function(d) {
if (d.fuerza === "FPV_y_aliados") {
return d;
}
});
renderTabla(dataB);
});
//UNA
d3.select("#una_sen")
.on("click", function() {
//filter
var dataB = dataFromCSV_sen.filter(function(d) {
if (d.fuerza === "UNA") {
return d;
}
});
renderTabla(dataB);
});
//PJ disidente
d3.select("#pjd_sen")
.on("click", function() {
//filter
var dataB = dataFromCSV_sen.filter(function(d) {
if (d.fuerza === "PJ_DISIDENTE") {
return d;
}
});
renderTabla(dataB);
});
//Progresistas
d3.select("#prg_sen")
.on("click", function() {
//filter
var dataB = dataFromCSV_sen.filter(function(d) {
if (d.fuerza === "PROGRESISTAS") {
return d;
}
});
renderTabla(dataB);
});
//Izquierda
d3.select("#izq_sen")
.on("click", function() {
//filter
var dataB = dataFromCSV_sen.filter(function(d) {
if (d.fuerza === "IZQUIERDA") {
return d;
}
});
renderTabla(dataB);
});
//Otros
d3.select("#otr_sen")
.on("click", function() {
//filter
var dataB = dataFromCSV_sen.filter(function(d) {
if (d.fuerza === "OTROS") {
return d;
}
});
renderTabla(dataB);
});
//Todos
d3.select("#all_sen")
.on("click", function() {
renderTabla(dataFromCSV_sen);
});
//Todos2
d3.select("#all2_sen")
.on("click", function() {
renderTabla(dataFromCSV_sen);
//scrollaTo_sen('ancla_bottom_sen');
});
//Afirmativos
d3.select("#afi_sen")
.on("click", function() {
//filter
var dataB = dataFromCSV_sen.filter(function(d) {
if (d.voto === "AFIRMATIVO") {
return d;
}
});
renderTabla(dataB);
//scrollaTo_sen('ancla_bottom_sen');
});
//Negat
d3.select("#neg_sen")
.on("click", function() {
//filter
var dataB = dataFromCSV_sen.filter(function(d) {
if (d.voto === "NEGATIVO") {
return d;
}
});
renderTabla(dataB);
//scrollaTo_sen('ancla_bottom_sen');
});
//Ausente
d3.select("#aus_sen")
.on("click", function() {
//filter
var dataB = dataFromCSV_sen.filter(function(d) {
if (d.voto === "AUSENTE") {
return d;
}
});
renderTabla(dataB);
//scrollaTo_sen('ancla_bottom_sen');
});
//Abstencion
d3.select("#abs_sen").on("click", function() {
//filter
var dataB = dataFromCSV_sen.filter(function(d) {
if (d.voto === "ABSTENCION") {
return d;
}
});
renderTabla(dataB);
//scrollaTo('ancla_bottom_sen');
});
function renderTabla(dataB) {
tabl_sen = d3.select("#div3_sen").select("table").remove();
tabl_sen = d3.select("#pagination_sen").selectAll("*").remove();
//UPDATE
var tabl_sen = d3.select("#div3_sen").append("table").attr('id', 'laLista_sen').attr('class', 'tablaLista').append("thead");
tabl_sen.append("tr");
tabl_sen.append("td").attr('class', 'listaHead').html("Nº");
tabl_sen.append("td").attr('class', 'listaHead').html("Senador");
tabl_sen.append("td").attr('class', 'listaHead').html("Fuerza");
tabl_sen.append("td").attr('class', 'listaHead').html("Partido/Bloque");
tabl_sen.append("td").attr('class', 'listaHead').html("Provincia");
tabl_sen.append("td").attr('class', 'listaHead').html("Voto");
var tabl2_sen = d3.select("#div3_sen").select("table").append("tbody");
var tr_sen = tabl2_sen.selectAll('tr').data(dataB).enter().append("tr").attr('class', 'trLista_sen');
tr_sen.append("td").attr('class', 'index lista').html(function(d, i) {
return pad_with_zeroes(i + 1, 2);
});
tr_sen.append("td").attr('class', 'diput lista').html(function(d, i) {
return d.senador;
});
tr_sen.append("td").attr('class', 'fuer lista').html(function(d, i) {
return d.fuerza;
});
tr_sen.append("td").attr('class', 'bloqu lista').html(function(d, i) {
return d.partidoBloque;
});
tr_sen.append("td").attr('class', 'prov lista').html(function(d, i) {
return d.provincia;
});
tr_sen.append("td").attr('class', 'vot lista').html(function(d, i) {
return d.voto;
});
//EXIT
//d3.selectAll('tr').data(dataNegat).exit().remove();
if (dataB.length === 0) {
tabl_sen.attr('style', 'width:478px;height:40em').append("tr").attr('class', 'trLista_sen').append("td").attr('style', 'width:475px;text-align:center').html("Sin datos");
}
/*jQuery('document').ready(function() {
pagination_sen();
});
tabl_sen = d3.select("#pagination_sen").append("a").attr('id', 'ancla_bottom_sen');*/
} //END renderTabla
//Resize svg * Juan Pablo Kutianski
var svg_sen = d3.select("svg#hemi_sen").attr({
"width": function() {
return this.clientWidth || this.parentElement.clientWidth;
},
"height": function() {
return this.clientHeight || this.parentElement.clientHeight;
},
"viewBox": function() {
return "0 0 " +
(this.clientWidth || this.parentElement.clientWidth) + " " +
(this.clientHeight || this.parentElement.clientHeight);
}
}),
width = parseFloat(svg_sen.attr("width")),
height = parseFloat(svg_sen.attr("height"));
window.addEventListener('load', function() {
svg_sen.attr({
"width": function() {
return this.parentElement.clientWidth;
},
"height": function() {
var currentWidth = this.parentElement.clientWidth;
return parseFloat(currentWidth * (parseFloat(height) / parseFloat(width)));
}
});
width = parseFloat(svg_sen.attr("width"));
height = parseFloat(svg_sen.attr("height"));
console.log("senad");
});
window.addEventListener('resize', function() {
svg_sen.attr({
"width": function() {
return this.parentElement.clientWidth;
},
"height": function() {
var currentWidth = this.parentElement.clientWidth
return parseFloat(currentWidth * (parseFloat(height) / parseFloat(width)));
}
});
width = parseFloat(svg_sen.attr("width"));
height = parseFloat(svg_sen.attr("height"));
});
});
|
module.exports = function(config) {
config.set({
// base path, that will be used to resolve files and exclude
basePath: '.',
frameworks: ['mocha', 'requirejs'],
// list of files / patterns to load in the browser
files: [
{ pattern: 'test/**/*.spec.js', included: false },
{ pattern: 'app/**/*.js', included: false },
{ pattern: 'components/**/*.js', included: false },
'test/test-main.js'
],
// list of files to exclude
exclude: ['app/main.js'],
// use dots reporter, as travis terminal does not support escaping sequences
// possible values: 'dots', 'progress'
// CLI --reporters progress
reporters: ['progress', 'junit'],
junitReporter: {
// will be resolved to basePath (in the same way as files/exclude patterns)
outputFile: 'test-results.xml'
},
// web server port
// CLI --port 9876
port: 9876,
// cli runner port
// CLI --runner-port 9100
runnerPort: 9100,
// enable / disable colors in the output (reporters and logs)
// CLI --colors --no-colors
colors: true,
// level of logging
// possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
// CLI --log-level debug
logLevel: config.LOG_INFO,
// enable / disable watching file and executing tests whenever any file changes
// CLI --auto-watch --no-auto-watch
autoWatch: true,
// Start these browsers, currently available:
// - Chrome
// - ChromeCanary
// - Firefox
// - Opera
// - Safari (only Mac)
// - PhantomJS
// - IE (only Windows)
// CLI --browsers Chrome,Firefox,Safari
browsers: [],
// If browser does not capture in given timeout [ms], kill it
// CLI --capture-timeout 5000
captureTimeout: 5000,
// Auto run tests on start (when browsers are captured) and exit
// CLI --single-run --no-single-run
singleRun: false,
// report which specs are slower than 500ms
// CLI --report-slower-than 500
reportSlowerThan: 500,
// Files that needs to be preprocessed
preprocessors: {
'app/**/*.js': 'coverage'
},
plugins: [
'karma-coverage',
'karma-phantomjs-launcher',
'karma-chrome-launcher',
'karma-mocha',
'karma-requirejs',
'karma-junit-reporter'
]
});
};
|
"use strict";
var child_process = require('child_process');
var os = require('os');
var cli_table_2_json_1 = require('cli-table-2-json');
var exec = child_process.exec;
var eol = os.EOL;
var extractResult = function (result) {
var extracterArray = [
{
re: / ls /,
run: function (resultp) {
var obj = JSON.parse(resultp.raw);
var lines = obj.split(eol);
resultp.machineList = cli_table_2_json_1.cliTable2Json(lines);
return resultp;
},
},
{
re: / config /,
run: function (resultp) {
var obj = JSON.parse(resultp.raw);
var str = obj;
var config = str.split(eol).join(' ');
var extractValue = function (strp, name, rep) {
var re = rep || new RegExp('--' + name + '="([\\S]*)"', 'i');
var m = re.exec(strp);
if (m !== null) {
if (m.index === re.lastIndex) {
re.lastIndex++;
}
}
return (m && m[1]) ? m[1] : null;
};
resultp.machine = {
config: config,
host: extractValue(str, null, /-H=tcp:\/\/(.*):/),
port: extractValue(str, null, /-H=tcp:\/\/.*:(\d*)/),
tlscacert: extractValue(str, 'tlscacert'),
tlscert: extractValue(str, 'tlscert'),
tlskey: extractValue(str, 'tlskey'),
tlsverify: function (strp) {
var re = /--tlsverify/;
var m = re.exec(strp);
if (m !== null) {
if (m.index === re.lastIndex) {
re.lastIndex++;
}
}
return (m && m[0] && m[0] === '--tlsverify') || false;
}(str),
};
return resultp;
},
},
{
re: / inspect /,
run: function (resultp) {
try {
var obj = JSON.parse(resultp.raw);
resultp.machine = JSON.parse(obj);
}
catch (e) {
}
return resultp;
},
},
{
re: / ip /,
run: function (resultp) {
try {
var obj = JSON.parse(resultp.raw.replace(/\\n/g, '').replace(os.EOL,''));
resultp.ip = obj;
}
catch (e) {
}
return resultp;
},
},
];
extracterArray.forEach(function (extracter) {
var re = extracter.re;
var str = result.command;
var m = re.exec(str);
if (m !== null) {
if (m.index === re.lastIndex) {
re.lastIndex++;
}
return extracter.run(result);
}
});
return result;
};
var DockerMachine = (function () {
function DockerMachine(options) {
if (options === void 0) { options = new Options(); }
this.options = options;
}
DockerMachine.prototype.command = function (command, callback) {
var dockerMachine = this;
var execCommand = 'docker-machine ' + command;
var promise = Promise.resolve().then(function () {
var params = dockerMachine.options.toParams();
execCommand += ' ' + params;
var execOptions = {
cwd: dockerMachine.options.currentWorkingDirectory,
env: {
DEBUG: '',
HOME: process.env.HOME,
PATH: process.env.PATH,
},
maxBuffer: 200 * 1024 * 1024,
};
return new Promise(function (resolve, reject) {
exec(execCommand, execOptions, function (error, stdout, stderr) {
if (error) {
var message = "error: '" + error + "' stdout = '" + stdout + "' stderr = '" + stderr + "'";
console.error(message);
reject(message);
}
resolve(stdout);
});
});
}).then(function (data) {
var result = {
command: execCommand,
raw: JSON.stringify(data),
};
return extractResult(result);
});
return promise;
};
return DockerMachine;
}());
exports.DockerMachine = DockerMachine;
var Options = (function () {
function Options(keyValueObject, currentWorkingDirectory) {
if (keyValueObject === void 0) { keyValueObject = {}; }
if (currentWorkingDirectory === void 0) { currentWorkingDirectory = null; }
this.keyValueObject = keyValueObject;
this.currentWorkingDirectory = currentWorkingDirectory;
}
Options.prototype.toParams = function () {
var _this = this;
var result = Object.keys(this.keyValueObject).reduce(function (previous, key) {
var value = _this.keyValueObject[key];
return previous + " --" + key + " " + value;
}, '');
return result;
};
return Options;
}());
exports.Options = Options;
|
module.exports = {
"env": {
"browser": true,
"commonjs": true,
"es6": true,
"node": true
},
"extends": "eslint:recommended",
"installedESLint": true,
"parserOptions": {
"ecmaFeatures": {
"experimentalObjectRestSpread": true,
"jsx": true
},
"sourceType": "module"
},
"plugins": [
"react"
],
"rules": {
"indent": [
"error",
4
],
"linebreak-style": [
"error",
"unix"
],
"quotes": [
"error",
"single"
],
"semi": [
"error",
"always"
]
}
};
|
require('dotenv').config()
var path = require('path')
var fs = require('fs')
var Q = require('bluebird')
var SABNZB = require('./sabnzb')
var readDir = require('readdir')
var watch = require('node-watch');
const exec = require('child_process').exec
console.log(process.env);
const SUPPORTED_FORMATS = [".mov", ".mpeg4", ".mp4", ".avi", ".wmv", ".mpegps", ".flv", ".3gpp", ".webm", ".mkv"]
const IGNORE_STRINGS = ["UNPACK", 'sample']
function uploadVideo(filePath) {
return new Q((yes, no) => {
const { PRIVACY, CLIENT_SECRETS, CLIENT_CREDENTIALS, DELETE_AFTER_UPLOAD } = process.env;
const credentials = CLIENT_CREDENTIALS ? `--credentials-file=${CLIENT_CREDENTIALS}` : ""
const { name, base } = path.parse(filePath)
const cmd = `youtube-upload --title="${name}" --privacy=${PRIVACY} ${credentials} --client-secrets=${CLIENT_SECRETS} "${filePath}"`
console.log(cmd);
exec(cmd, function(err, stdout, stderr) {
console.log(`youtube id ${stdout}`);
//a video id
if (stdout.indexOf(" ") < 0) {
yes(filePath)
SABNZB.next()
} else {
no(filePath)
}
});
})
}
let processing = {
}
function processTrigger(name) {
const ext = path.parse(name).ext;
const rootDir = name.replace(process.env.DOWNLOAD_DIR, "").split(path.sep)[1]
const containerFolder = path.join(process.env.DOWNLOAD_DIR, rootDir)
const dlFolder = path.parse(name).dir;
console.log("containerFolder", containerFolder);
console.log("dlFolder", dlFolder);
if(processing[dlFolder]) return
processing[dlFolder] = true
//if (fs.lstatSync(name).isDirectory()) {
const files = readDir.readSync(dlFolder, SUPPORTED_FORMATS.map(p => (`**${p}`)), readDir.ABSOLUTE_PATHS);
const ordered = files.map(f => ({
file: f,
stat: fs.lstatSync(f)
})).sort((a, b) => (b.stat.size > a.stat.size))
console.log(ordered);
console.log(`Got ${name}`);
function _uploadVideo(name) {
return uploadVideo(name)
.then(filePath => {
const { dir } = path.parse(filePath)
const { DELETE_AFTER_UPLOAD } = process.env;
if (Boolean(DELETE_AFTER_UPLOAD)) {
const fileToDelete = containerFolder || filePath
exec(`rm -rf "${fileToDelete}"`, function(err, stdout, stderr) {
console.log(`Deleted ${fileToDelete}`);
delete processing[dlFolder]
if (dlFolder) {
try {
fs.rmdir(dlFolder, function(err, data) {
console.log(`Deleted directory${fileToDelete}`);
})
} catch (e) {
}
}
})
}
})
.catch(err => {
})
}
if(ordered.length){
name = ordered[0].file
_uploadVideo(name)
}
}
let timeouts = {
}
watch(process.env.DOWNLOAD_DIR, { recursive: true }, function(evt, name) {
switch (evt) {
case 'update':
const { ext, base } = path.parse(name);
if (timeouts[base]) {
clearTimeout(timeouts[base])
}
if (SUPPORTED_FORMATS.indexOf(ext) === -1) {
console.log("rejected");
return
}
console.log(name);
if(name.indexOf('complete') < 0){
return
}
timeouts[base] = setTimeout(processTrigger, 10000, name)
break;
}
});
|
/**
* @licence MIT
* @author Louis Audeon <louis.audeon@mail.be>
*/
'use strict'
const chai = require('chai')
const expect = chai.expect
const sinon = require('sinon')
const Fieldformat = require('./../../../lib/field/fieldformat')
const Emailformat = require('./../../../lib/field/formats/email')
describe('Emailformat object', function () {
it('should herits Fieldformat', function () {
let email = new Emailformat()
expect(email).to.be.an.instanceOf(Fieldformat)
})
it('should repond to check method', function () {
let email = new Emailformat()
expect(email).to.respondTo('check')
})
describe('Emailformat check', function () {
it('should return true if the given string correspond to a email', function () {
let email = new Emailformat()
expect(email.check({ value: 'test@test.test' })).to.be.true
expect(email.error).to.be.null
})
it('should return false if the given string doesnt correspond to a email', function () {
let email = new Emailformat()
expect(email.check({ value: 'blabla@blabla' })).to.be.false
expect(email.check({ value: 'blabla@blabla.b' })).to.be.false
expect(email.check({ value: 'blabla.bla' })).to.be.false
})
it('should set the error string on error', function () {
let email = new Emailformat()
email.check({ value: 'notaemail' })
expect(email.error).to.be.not.null
})
})
})
|
var styleTest = document.createElement("div").style
, cssSupportMap = {}
, wordsRE = /\S+/g
, prefixes = "webkit O ms Moz css".match(wordsRE)
module.exports = function(name){
var index = -1
, length = prefixes.length
, property
if(property = cssSupportMap[name]) return property
if(typeof styleTest[name] == "string") {
cssSupportMap[name] = name
return name
}
name = name.charAt(0).toUpperCase() + name.slice(1)
while(++index < length) {
if(typeof styleTest[property = prefixes[index] + name] == "string") {
cssSupportMap[name] = property
return property
}
}
return null
}
|
/*
Copyright (c) 2004-2012, The Dojo Foundation All Rights Reserved.
Available via Academic Free License >= 2.1 OR the modified BSD license.
see: http://dojotoolkit.org/license for details
*/
if(!dojo._hasResource["dojox.widget.AnalogGauge"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
dojo._hasResource["dojox.widget.AnalogGauge"] = true;
dojo.provide("dojox.widget.AnalogGauge");
dojo.require("dojox.gfx");
dojo.require("dojox.widget.gauge._Gauge");
dojo.experimental("dojox.widget.AnalogGauge");
dojo.declare("dojox.widget.gauge.AnalogLineIndicator",[dojox.widget.gauge._Indicator],{
_getShapes: function(){
// summary:
// Private function for generating the shapes for this indicator. An indicator that behaves the
// same might override this one and simply replace the shapes (such as ArrowIndicator).
return [this._gauge.surface.createLine({x1: 0, y1: -this.offset,
x2: 0, y2: -this.length-this.offset})
.setStroke({color: this.color, width: this.width})];
},
draw: function(/*Boolean?*/ dontAnimate){
// summary:
// Override of dojox.widget.gauge._Indicator.draw
// dontAnimate: Boolean
// Indicates if the drawing should not be animated (vs. the default of doing an animation)
if(this.shapes){
this._move(dontAnimate);
}else{
if(this.text){
this._gauge.surface.rawNode.removeChild(this.text);
this.text = null;
}
var a = this._gauge._getAngle(Math.min(Math.max(this.value, this._gauge.min), this._gauge.max));
this.color = this.color || '#000000';
this.length = this.length || this._gauge.radius;
this.width = this.width || 1;
this.offset = this.offset || 0;
this.highlight = this.highlight || '#D0D0D0';
this.shapes = this._getShapes(this._gauge, this);
if(this.shapes){
for(var s = 0; s < this.shapes.length; s++){
this.shapes[s].setTransform([{dx:this._gauge.cx,dy:this._gauge.cy}, dojox.gfx.matrix.rotateg(a)]);
if(this.hover){
this.shapes[s].getEventSource().setAttribute('hover',this.hover);
}
if(this.onDragMove && !this.noChange){
//TODO
this._gauge.connect(this.shapes[s].getEventSource(), 'onmousedown', this._gauge.handleMouseDown);
this.shapes[s].getEventSource().style.cursor = 'pointer';
}
}
}
if(this.label){
var len=this.length+this.offset,
rad=this._gauge._getRadians(a),
x=this._gauge.cx+(len+5)*Math.sin(rad),
y=this._gauge.cy-(len+5)*Math.cos(rad),
align = 'start',
aa = Math.abs(a)
;
if(a <= -10){align = 'end';}
if(aa < 10){align='middle';}
var vAlign = 'bottom';
if(aa > 90){vAlign = 'top';}
this.text = this._gauge.drawText(''+this.label, x, y, align, vAlign, this.color, this.font);
}
this.currentValue = this.value;
}
},
_move: function(/*Boolean?*/ dontAnimate){
// summary:
// Moves this indicator (since it's already been drawn once)
// dontAnimate: Boolean
// Indicates if the drawing should not be animated (vs. the default of doing an animation)
var v = Math.min(Math.max(this.value, this._gauge.min), this._gauge.max),
c = this.currentValue
;
if(dontAnimate){
var angle = this._gauge._getAngle(v);
for(var i in this.shapes){
this.shapes[i].setTransform([{dx:this._gauge.cx,dy:this._gauge.cy}, dojox.gfx.matrix.rotateg(angle)]);
if(this.hover){
this.shapes[i].getEventSource().setAttribute('hover',this.hover);
}
}
}else{
if(c!=v){
var anim = new dojo.Animation({curve: [c, v], duration: this.duration, easing: this.easing});
dojo.connect(anim, "onAnimate", dojo.hitch(this, function(step){
for(var i in this.shapes){
this.shapes[i].setTransform([{dx:this._gauge.cx,dy:this._gauge.cy}, dojox.gfx.matrix.rotateg(this._gauge._getAngle(step))]);
if(this.hover){
this.shapes[i].getEventSource().setAttribute('hover',this.hover);
}
}
this.currentValue = step;
}));
anim.play();
}
}
}
});
dojo.declare("dojox.widget.AnalogGauge",dojox.widget.gauge._Gauge,{
// summary:
// a gauge built using the dojox.gfx package.
//
// description:
// using dojo.gfx (and thus either SVG or VML based on what is supported), this widget
// builds a gauge component, used to display numerical data in a familiar format
//
// usage:
// <script type="text/javascript">
// dojo.require("dojox.widget.AnalogGauge");
// dojo.require("dijit.util.parser");
// </script>
// ...
// <div dojoType="dojox.widget.AnalogGauge"
// id="testGauge"
// width="300"
// height="200"
// cx=150
// cy=175
// radius=125
// image="gaugeOverlay.png"
// imageOverlay="false"
// imageWidth="280"
// imageHeight="155"
// imageX="12"
// imageY="38">
// </div>
// startAngle: Number
// angle (in degrees) for start of gauge (default is -90)
startAngle: -90,
// endAngle: Number
// angle (in degrees) for end of gauge (default is 90)
endAngle: 90,
// cx: Number
// center of gauge x coordinate (default is gauge width / 2)
cx: 0,
// cy: Number
// center of gauge x coordinate (default is gauge height / 2)
cy: 0,
// radius: Number
// radius of gauge (default is smaller of cx-25 or cy-25)
radius: 0,
// _defaultIndicator: override of dojox.widget._Gauge._defaultIndicator
_defaultIndicator: dojox.widget.gauge.AnalogLineIndicator,
startup: function(){
// handle settings from HTML by making sure all the options are
// converted correctly to numbers and that we calculate defaults
// for cx, cy and radius
// also connects mouse handling events
if(this.getChildren){
dojo.forEach(this.getChildren(), function(child){ child.startup(); });
}
this.startAngle = Number(this.startAngle);
this.endAngle = Number(this.endAngle);
this.cx = Number(this.cx);
if(!this.cx){this.cx = this.width/2;}
this.cy = Number(this.cy);
if(!this.cy){this.cy = this.height/2;}
this.radius = Number(this.radius);
if(!this.radius){this.radius = Math.min(this.cx,this.cy) - 25;}
this._oppositeMiddle = (this.startAngle+this.endAngle)/2+180;
this.inherited(arguments);
},
_getAngle: function(/*Number*/value){
// summary:
// This is a helper function used to determine the angle that represents
// a given value on the gauge
// value: Number
// A value to be converted to an angle for this gauage.
return (value - this.min)/(this.max - this.min)*(this.endAngle - this.startAngle) + this.startAngle;
},
_getValueForAngle: function(/*Number*/angle){
// summary:
// This is a helper function used to determie the value represented by a
// given angle on the gauge
// angle: Number
// A angle to be converted to a value for this gauge.
if(angle > this._oppositeMiddle){ angle -= 360; }
return (angle - this.startAngle)*(this.max - this.min)/(this.endAngle - this.startAngle) + this.min;
},
_getRadians: function(/*Number*/angle){
// summary:
// This is a helper function than converts degrees to radians
// angle: Number
// An angle, in degrees, to be converted to radians.
return angle*Math.PI/180;
},
_getDegrees: function(/*Number*/radians){
// summary:
// This is a helper function that converts radians to degrees
// radians: Number
// An angle, in radians, to be converted to degrees.
return radians*180/Math.PI;
},
draw: function(){
// summary:
// This function is used to draw (or redraw) the gauge.
// description:
// Draws the gauge by drawing the surface, the ranges, and the indicators.
var i;
if(this._rangeData){
for(i=0; i<this._rangeData.length; i++){
this.drawRange(this._rangeData[i]);
}
if(this._img && this.image.overlay){
this._img.moveToFront();
}
}
if(this._indicatorData){
for(i=0; i<this._indicatorData.length; i++){
this._indicatorData[i].draw();
}
}
},
drawRange: function(/*Object*/range){
// summary:
// This function is used to draw (or redraw) a range
// description:
// Draws a range (colored area on the background of the gauge)
// based on the given arguments.
// range:
// A range is a dojox.widget.gauge.Range or an object
// with similar parameters (low, high, hover, etc.).
var path;
if(range.shape){
this.surface.remove(range.shape);
range.shape = null;
}
var a1, a2;
if((range.low == this.min) && (range.high == this.max) && ((this.endAngle - this.startAngle) == 360)){
path = this.surface.createCircle({cx: this.cx, cy: this.cy, r: this.radius});
}else{
a1 = this._getRadians(this._getAngle(range.low));
a2 = this._getRadians(this._getAngle(range.high));
var x1=this.cx+this.radius*Math.sin(a1),
y1=this.cy-this.radius*Math.cos(a1),
x2=this.cx+this.radius*Math.sin(a2),
y2=this.cy-this.radius*Math.cos(a2),
big=0
;
if((a2-a1)>Math.PI){big=1;}
path = this.surface.createPath();
if(range.size){
path.moveTo(this.cx+(this.radius-range.size)*Math.sin(a1),
this.cy-(this.radius-range.size)*Math.cos(a1));
}else{
path.moveTo(this.cx,this.cy);
}
path.lineTo(x1,y1);
path.arcTo(this.radius,this.radius,0,big,1,x2,y2);
if(range.size){
path.lineTo(this.cx+(this.radius-range.size)*Math.sin(a2),
this.cy-(this.radius-range.size)*Math.cos(a2));
path.arcTo((this.radius-range.size),(this.radius-range.size),0,big,0,
this.cx+(this.radius-range.size)*Math.sin(a1),
this.cy-(this.radius-range.size)*Math.cos(a1));
}
path.closePath();
}
if(dojo.isArray(range.color) || dojo.isString(range.color)){
path.setStroke({color: range.color});
path.setFill(range.color);
}else if(range.color.type){
// Color is a gradient
a1 = this._getRadians(this._getAngle(range.low));
a2 = this._getRadians(this._getAngle(range.high));
range.color.x1 = this.cx+(this.radius*Math.sin(a1))/2;
range.color.x2 = this.cx+(this.radius*Math.sin(a2))/2;
range.color.y1 = this.cy-(this.radius*Math.cos(a1))/2;
range.color.y2 = this.cy-(this.radius*Math.cos(a2))/2;
path.setFill(range.color);
path.setStroke({color: range.color.colors[0].color});
}else{
// We've defined a style rather than an explicit color
path.setStroke({color: "green"}); // Arbitrary color, just have to indicate
path.setFill("green"); // that we want it filled
path.getEventSource().setAttribute("class", range.color.style);
}
if(range.hover){
path.getEventSource().setAttribute('hover',range.hover);
}
range.shape = path;
},
getRangeUnderMouse: function(/*Object*/event){
// summary:
// Determines which range the mouse is currently over
// event: Object
// The event object as received by the mouse handling functions below.
var range = null,
pos = dojo.coords(this.gaugeContent),
x = event.clientX - pos.x,
y = event.clientY - pos.y,
r = Math.sqrt((y - this.cy)*(y - this.cy) + (x - this.cx)*(x - this.cx))
;
if(r < this.radius){
var angle = this._getDegrees(Math.atan2(y - this.cy, x - this.cx) + Math.PI/2),
//if(angle > this.endAngle){angle = angle - 360;}
value = this._getValueForAngle(angle)
;
if(this._rangeData){
for(var i=0; (i<this._rangeData.length) && !range; i++){
if((Number(this._rangeData[i].low) <= value) && (Number(this._rangeData[i].high) >= value)){
range = this._rangeData[i];
}
}
}
}
return range;
},
_dragIndicator: function(/*Object*/ widget, /*Object*/ event){
// summary:
// Handles the dragging of an indicator, including moving/re-drawing
// get angle for mouse position
var pos = dojo.coords(widget.gaugeContent),
x = event.clientX - pos.x,
y = event.clientY - pos.y,
angle = widget._getDegrees(Math.atan2(y - widget.cy, x - widget.cx) + Math.PI/2),
//if(angle > widget.endAngle){angle = angle - 360;}
// get value and restrict to our min/max
value = widget._getValueForAngle(angle)
;
value = Math.min(Math.max(value, widget.min), widget.max);
// update the indicator
widget._drag.value = widget._drag.currentValue = value;
// callback
widget._drag.onDragMove(widget._drag);
// rotate indicator
widget._drag.draw(true);
dojo.stopEvent(event);
}
});
}
|
/*global Devtools, Backbone, JST*/
Devtools.Views = Devtools.Views || {};
(function () {
'use strict';
Devtools.Views.Home = Devtools.Views.Page.extend({
template: JST['app/scripts/templates/Home.ejs'],
events: {
'click .btn-alert': 'handleAlertClick',
'click .btn-modal': 'handleModalClick',
'click .btn-tooltip': 'handleTooltipClick'
},
onRender: function () {
// initialize tooltips
$('[data-toggle="tooltip"]').tooltip();
},
handleAlertClick: function (ev) {
var alertWrapper = this.$('#alertWrapper');
var alert = new Devtools.Views.Alert({
model: new Backbone.Model({
title: 'Hooray!',
message: 'You\'ve successfully created a new alert box!'
})
});
alertWrapper.append(alert.render().el);
},
handleModalClick: function (ev) {
$('#modal').modal();
},
handleTooltipClick: function (ev) {
// body...
}
});
})();
|
const valueParser = require("postcss-value-parser");
const { stringify } = valueParser;
function getUrl(nodes) {
let url = "";
let urlEnd = 0;
for (let i = 0; i < nodes.length; i += 1) {
const node = nodes[i];
if (node.type === "string") {
if (i !== 0) {
throw Error(`Invalid "svg-load(${stringify(nodes)})" definition`);
}
url = node.value;
urlEnd = i + 1;
break;
}
if (node.type === "div" && node.value === ",") {
if (i === 0) {
throw Error(`Invalid "svg-load(${stringify(nodes)})" definition`);
}
urlEnd = i;
break;
}
url += stringify(node);
urlEnd += 1;
}
return {
url,
urlEnd,
};
}
function getParamChunks(nodes) {
const list = [];
const lastArg = nodes.reduce((arg, node) => {
if (node.type === "word" || node.type === "string") {
return arg + node.value;
}
if (node.type === "space") {
return arg + " ";
}
if (node.type === "div" && node.value === ",") {
list.push(arg);
return "";
}
return arg + stringify(node);
}, "");
return list.concat(lastArg);
}
function splitParams(list) {
const params = {};
list.reduce((sep, arg) => {
if (!arg) {
throw Error(`Expected parameter`);
}
if (!sep) {
if (arg.indexOf(":") !== -1) {
sep = ":";
} else if (arg.indexOf("=") !== -1) {
sep = "=";
} else {
throw Error(`Expected ":" or "=" separator in "${arg}"`);
}
}
const pair = arg.split(sep);
if (pair.length !== 2) {
throw Error(`Expected "${sep}" separator in "${arg}"`);
}
params[pair[0].trim()] = pair[1].trim();
return sep;
}, null);
return params;
}
function getLoader(parsedValue, valueNode) {
if (!valueNode.nodes.length) {
throw Error(`Invalid "svg-load()" statement`);
}
// parse url
const { url, urlEnd } = getUrl(valueNode.nodes);
// parse params
const paramsNodes = valueNode.nodes.slice(urlEnd + 1);
const params =
urlEnd !== valueNode.nodes.length
? splitParams(getParamChunks(paramsNodes))
: {};
return {
url,
params,
valueNode,
parsedValue,
};
}
function getInliner(parsedValue, valueNode) {
if (!valueNode.nodes.length) {
throw Error(`Invalid "svg-inline()" statement`);
}
const name = valueNode.nodes[0].value;
return {
name,
valueNode,
parsedValue,
};
}
module.exports = function parseDeclValue(value) {
const loaders = [];
const inliners = [];
const parsedValue = valueParser(value);
parsedValue.walk((valueNode) => {
if (valueNode.type === "function") {
if (valueNode.value === "svg-load") {
loaders.push(getLoader(parsedValue, valueNode));
} else if (valueNode.value === "svg-inline") {
inliners.push(getInliner(parsedValue, valueNode));
}
}
});
return {
loaders,
inliners,
};
};
|
export const ic_food_bank_outline = {"viewBox":"0 0 24 24","children":[{"name":"rect","attribs":{"fill":"none","height":"24","width":"24"},"children":[]},{"name":"path","attribs":{"d":"M12,5.5l6,4.5v9H6v-9L12,5.5 M12,3L4,9v12h16V9L12,3L12,3z M11.5,9.5v3H11v-3h-1v3H9.5v-3h-1v3c0,0.83,0.67,1.5,1.5,1.5v4h1 v-4c0.83,0,1.5-0.67,1.5-1.5v-3H11.5z M13,11.5v3h1V18h1V9.5C13.9,9.5,13,10.4,13,11.5z"},"children":[]}]};
|
import crypto from 'crypto'
import fs from 'fs'
import bcrypt from 'bcrypt'
import { promisify, promisifyAll } from 'bluebird'
import aws from 'aws-sdk'
import gm from 'gm'
import GraphemeBreaker from 'grapheme-breaker'
import _ from 'lodash'
import monitor from 'monitor-dog'
import validator from 'validator'
import uuid from 'uuid'
import { load as configLoader } from '../../config/config'
import { BadRequestException, ForbiddenException, NotFoundException, ValidationException } from '../support/exceptions'
import { Attachment, Comment, Post } from '../models'
promisifyAll(crypto)
promisifyAll(gm)
const config = configLoader()
export function addModel(dbAdapter) {
/**
* @constructor
*/
const User = function (params) {
let password = null
this.id = params.id
this.username = params.username
this.screenName = params.screenName
this.email = params.email
this.description = params.description || ''
this.frontendPreferences = params.frontendPreferences || {}
if (!_.isUndefined(params.hashedPassword)) {
this.hashedPassword = params.hashedPassword
} else {
password = params.password || ''
}
this.isPrivate = params.isPrivate
this.isVisibleToAnonymous = params.isVisibleToAnonymous
this.isProtected = params.isProtected
if (this.isPrivate === '1') {
this.isProtected = '1'
}
this.resetPasswordToken = params.resetPasswordToken
this.resetPasswordSentAt = params.resetPasswordSentAt
if (parseInt(params.createdAt, 10))
this.createdAt = params.createdAt
if (parseInt(params.updatedAt, 10))
this.updatedAt = params.updatedAt
this.type = 'user'
this.profilePictureUuid = params.profilePictureUuid || ''
this.subscribedFeedIds = params.subscribedFeedIds || []
this.privateMeta = params.privateMeta;
this.initPassword = async function () {
if (!_.isNull(password)) {
if (password.length === 0) {
throw new Error('Password cannot be blank')
}
this.hashedPassword = await bcrypt.hash(password, 10)
password = null
}
return this
}
}
User.className = User
User.namespace = 'user'
User.PROFILE_PICTURE_SIZE_LARGE = 75
User.PROFILE_PICTURE_SIZE_MEDIUM = 50
Reflect.defineProperty(User.prototype, 'username', {
get: function () { return this.username_ },
set: function (newValue) {
if (newValue)
this.username_ = newValue.trim().toLowerCase()
}
})
Reflect.defineProperty(User.prototype, 'screenName', {
get: function () { return this.screenName_ },
set: function (newValue) {
if (_.isString(newValue))
this.screenName_ = newValue.trim()
}
})
Reflect.defineProperty(User.prototype, 'email', {
get: function () { return _.isUndefined(this.email_) ? '' : this.email_ },
set: function (newValue) {
if (_.isString(newValue))
this.email_ = newValue.trim()
}
})
Reflect.defineProperty(User.prototype, 'isPrivate', {
get: function () { return this.isPrivate_ },
set: function (newValue) {
this.isPrivate_ = newValue || '0'
}
})
Reflect.defineProperty(User.prototype, 'isProtected', {
get: function () { return this.isProtected_ },
set: function (newValue) {
this.isProtected_ = newValue || '0'
}
})
Reflect.defineProperty(User.prototype, 'isVisibleToAnonymous', {
get: function () { return (this.isProtected_ === '1') ? '0' : '1' },
set: function (newValue) {
this.isProtected_ = (newValue === '0') ? '1' : '0'
}
})
Reflect.defineProperty(User.prototype, 'description', {
get: function () { return this.description_ },
set: function (newValue) {
if (_.isString(newValue))
this.description_ = newValue.trim()
}
})
Reflect.defineProperty(User.prototype, 'frontendPreferences', {
get: function () { return this.frontendPreferences_ },
set: function (newValue) {
if (_.isString(newValue)) {
newValue = JSON.parse(newValue)
}
this.frontendPreferences_ = newValue
}
})
User.stopList = (skipExtraList) => {
if (skipExtraList) {
return config.application.USERNAME_STOP_LIST
}
return config.application.USERNAME_STOP_LIST.concat(config.application.EXTRA_STOP_LIST)
}
User.getObjectsByIds = (objectIds) => {
return dbAdapter.getFeedOwnersByIds(objectIds)
}
User.prototype.isUser = function () {
return this.type === 'user'
}
User.prototype.newPost = async function (attrs) {
attrs.userId = this.id
if (!attrs.timelineIds || !attrs.timelineIds[0]) {
const timelineId = await this.getPostsTimelineId()
attrs.timelineIds = [timelineId]
}
return new Post(attrs)
}
User.prototype.updateResetPasswordToken = async function () {
const now = new Date().getTime()
const token = await this.generateResetPasswordToken()
const payload = {
'resetPasswordToken': token,
'resetPasswordSentAt': now
}
await dbAdapter.updateUser(this.id, payload)
this.resetPasswordToken = token
return this.resetPasswordToken
}
User.prototype.generateResetPasswordToken = async function () {
const buf = await crypto.randomBytesAsync(48)
return buf.toString('hex')
}
User.prototype.validPassword = function (clearPassword) {
return bcrypt.compare(clearPassword, this.hashedPassword)
}
User.prototype.isValidEmail = async function () {
return User.emailIsValid(this.email)
}
User.emailIsValid = async function (email) {
// email is optional
if (!email || email.length == 0) {
return true
}
if (!validator.isEmail(email)) {
return false
}
const exists = await dbAdapter.existsUserEmail(email)
if (exists) {
// email is taken
return false
}
return true
}
User.prototype.isValidUsername = function (skip_stoplist) {
const valid = this.username
&& this.username.length >= 3 // per the spec
&& this.username.length <= 25 // per the spec
&& this.username.match(/^[A-Za-z0-9]+$/)
&& !User.stopList(skip_stoplist).includes(this.username)
return valid
}
User.prototype.isValidScreenName = function () {
return this.screenNameIsValid(this.screenName)
}
User.prototype.screenNameIsValid = function (screenName) {
if (!screenName) {
return false
}
const len = GraphemeBreaker.countBreaks(screenName)
if (len < 3 || len > 25) {
return false
}
return true
}
User.prototype.isValidDescription = function () {
return User.descriptionIsValid(this.description)
}
User.descriptionIsValid = function (description) {
const len = GraphemeBreaker.countBreaks(description)
return (len <= 1500)
}
User.frontendPreferencesIsValid = function (frontendPreferences) {
// Check size
const prefString = JSON.stringify(frontendPreferences)
const len = GraphemeBreaker.countBreaks(prefString)
if (len > config.frontendPreferencesLimit) {
return false
}
// Check structure
// (for each key in preferences there must be an object value)
if (!_.isPlainObject(frontendPreferences)) {
return false
}
for (const prop in frontendPreferences) {
if (!frontendPreferences[prop] || typeof frontendPreferences[prop] !== 'object') {
return false
}
}
return true
}
User.prototype.validate = async function (skip_stoplist) {
if (!this.isValidUsername(skip_stoplist)) {
throw new Error('Invalid username')
}
if (!this.isValidScreenName()) {
throw new Error(`"${this.screenName}" is not a valid display name. Names must be between 3 and 25 characters long.`)
}
if (!await this.isValidEmail()) {
throw new Error('Invalid email')
}
if (!this.isValidDescription()) {
throw new Error('Description is too long')
}
}
User.prototype.validateUsernameUniqueness = async function () {
const res = await dbAdapter.existsUsername(this.username)
if (res !== 0)
throw new Error('Already exists')
}
User.prototype.validateOnCreate = async function (skip_stoplist) {
const promises = [
this.validate(skip_stoplist),
this.validateUsernameUniqueness()
];
await Promise.all(promises)
}
User.prototype.create = async function (skip_stoplist) {
this.createdAt = new Date().getTime()
this.updatedAt = new Date().getTime()
this.screenName = this.screenName || this.username
await this.validateOnCreate(skip_stoplist)
const timer = monitor.timer('users.create-time')
await this.initPassword()
const payload = {
'username': this.username,
'screenName': this.screenName,
'email': this.email,
'type': this.type,
'isPrivate': '0',
'isProtected': '0',
'description': '',
'createdAt': this.createdAt.toString(),
'updatedAt': this.updatedAt.toString(),
'hashedPassword': this.hashedPassword,
'frontendPreferences': JSON.stringify({})
}
this.id = await dbAdapter.createUser(payload)
await dbAdapter.createUserTimelines(this.id, ['RiverOfNews', 'Hides', 'Comments', 'Likes', 'Posts', 'Directs', 'MyDiscussions'])
timer.stop() // @todo finally {}
monitor.increment('users.creates')
return this
}
User.prototype.update = async function (params) {
const payload = {}
const changeableKeys = ['screenName', 'email', 'isPrivate', 'isProtected', 'description', 'frontendPreferences']
if (params.hasOwnProperty('screenName') && params.screenName != this.screenName) {
if (!this.screenNameIsValid(params.screenName)) {
throw new Error(`"${params.screenName}" is not a valid display name. Names must be between 3 and 25 characters long.`)
}
payload.screenName = params.screenName
}
if (params.hasOwnProperty('email') && params.email != this.email) {
if (!(await User.emailIsValid(params.email))) {
throw new Error('Invalid email')
}
payload.email = params.email
}
if (params.hasOwnProperty('isPrivate') && params.isPrivate != this.isPrivate) {
if (params.isPrivate != '0' && params.isPrivate != '1') {
// ???
throw new Error('bad input')
}
if (params.isPrivate === '1' && this.isPrivate === '0') {
// was public, now private
await this.unsubscribeNonFriends()
} else if (params.isPrivate === '0' && this.isPrivate === '1') {
// was private, now public
await this.subscribeNonFriends()
}
payload.isPrivate = params.isPrivate
}
// Compatibility with pre-isProtected clients:
// if there is only isPrivate param then isProtected becomes the same as isPrivate
if (params.hasOwnProperty('isPrivate') && (!params.hasOwnProperty('isProtected') || params.isPrivate === '1')) {
params.isProtected = params.isPrivate
}
if (params.hasOwnProperty('isProtected') && params.isProtected != this.isProtected) {
payload.isProtected = params.isProtected;
}
// isProtected have priority
if (params.hasOwnProperty('isVisibleToAnonymous') && !params.hasOwnProperty('isProtected') && params.isVisibleToAnonymous != this.isVisibleToAnonymous) {
payload.isProtected = (params.isVisibleToAnonymous === '0') ? '1' : '0';
}
if (params.hasOwnProperty('description') && params.description != this.description) {
if (!User.descriptionIsValid(params.description)) {
throw new Error('Description is too long')
}
payload.description = params.description
}
if (params.hasOwnProperty('frontendPreferences')) {
// Validate the input object
if (!User.frontendPreferencesIsValid(params.frontendPreferences)) {
throw new ValidationException('Invalid frontendPreferences')
}
const preferences = { ...this.frontendPreferences, ...params.frontendPreferences };
// Validate the merged object
if (!User.frontendPreferencesIsValid(preferences)) {
throw new ValidationException('Invalid frontendPreferences')
}
payload.frontendPreferences = preferences
}
if (_.intersection(Object.keys(payload), changeableKeys).length > 0) {
const preparedPayload = payload
payload.updatedAt = new Date().getTime()
preparedPayload.updatedAt = payload.updatedAt.toString()
if (_.has(payload, 'frontendPreferences')) {
preparedPayload.frontendPreferences = JSON.stringify(payload.frontendPreferences)
}
await dbAdapter.updateUser(this.id, preparedPayload)
for (const k in payload) {
this[k] = payload[k]
}
}
return this
}
User.prototype.subscribeNonFriends = async function () {
// NOTE: this method is super ineffective as it iterates all posts
// and then all comments in user's timeline, we could make it more
// efficient when introduce Entries table with meta column (post to
// timelines many-to-many over Entries)
/* eslint-disable babel/no-await-in-loop */
const timeline = await this.getPostsTimeline({ currentUser: this.id })
const posts = await timeline.getPosts(0, -1)
let fixedUsers = []
// first of all, let's revive likes
for (const post of posts) {
const actions = []
const [likes, comments] = await Promise.all([post.getLikes(), post.getComments()]);
for (const usersChunk of _.chunk(likes, 10)) {
const promises = usersChunk.map(async (user) => {
return user.getLikesTimelineIntId()
})
const likesFeedsIntIds = await Promise.all(promises)
actions.push(dbAdapter.insertPostIntoFeeds(likesFeedsIntIds, post.id))
}
const uniqueCommenterUids = _.uniq(comments.map((comment) => comment.userId))
const commenters = await dbAdapter.getUsersByIds(uniqueCommenterUids)
for (const usersChunk of _.chunk(commenters, 10)) {
const promises = usersChunk.map(async (user) => {
return user.getCommentsTimelineIntId()
})
const commentsFeedsIntIds = await Promise.all(promises)
actions.push(dbAdapter.insertPostIntoFeeds(commentsFeedsIntIds, post.id))
}
await Promise.all(actions)
fixedUsers = _.uniqBy(fixedUsers.concat(likes).concat(commenters), 'id')
}
for (const usersChunk of _.chunk(fixedUsers, 10)) {
const promises = usersChunk.map(async (user) => {
const [riverId, commentsTimelineId, likesTimelineId] = await Promise.all([
user.getRiverOfNewsTimelineIntId(),
user.getCommentsTimelineIntId(),
user.getLikesTimelineIntId()
])
await dbAdapter.createMergedPostsTimeline(riverId, [commentsTimelineId, likesTimelineId]);
})
await Promise.all(promises)
}
/* eslint-enable babel/no-await-in-loop */
}
User.prototype.unsubscribeNonFriends = async function () {
/* eslint-disable babel/no-await-in-loop */
const subscriberIds = await this.getSubscriberIds()
const timeline = await this.getPostsTimeline()
// users that I'm not following are ex-followers now
// var subscribers = await this.getSubscribers()
// await Promise.all(subscribers.map(function (user) {
// // this is not friend, let's unsubscribe her before going to private
// if (!subscriptionIds.includes(user.id)) {
// return user.unsubscribeFrom(timeline.id, { likes: true, comments: true })
// }
// }))
// we need to review post by post as some strangers that are not
// followers and friends could commented on or like my posts
// let's find strangers first
const posts = await timeline.getPosts(0, -1)
let allUsers = []
for (const post of posts) {
const timelines = await post.getTimelines()
const userPromises = timelines.map((timeline) => timeline.getUser())
const users = await Promise.all(userPromises)
allUsers = _.uniqBy(allUsers.concat(users), 'id')
}
// and remove all private posts from all strangers timelines
const users = _.filter(
allUsers,
(user) => (!subscriberIds.includes(user.id) && user.id != this.id)
)
for (const chunk of _.chunk(users, 10)) {
const actions = chunk.map((user) => user.unsubscribeFrom(timeline.id, { likes: true, comments: true, skip: true }))
await Promise.all(actions)
}
/* eslint-enable babel/no-await-in-loop */
}
User.prototype.updatePassword = async function (password, passwordConfirmation) {
if (password.length === 0) {
throw new Error('Password cannot be blank')
}
if (password !== passwordConfirmation) {
throw new Error('Passwords do not match')
}
const updatedAt = new Date().getTime()
const payload = {
updatedAt: updatedAt.toString(),
hashedPassword: await bcrypt.hash(password, 10)
}
await dbAdapter.updateUser(this.id, payload)
this.updatedAt = updatedAt
this.hashedPassword = payload.hashedPassword
return this
}
User.prototype.getAdministratorIds = async function () {
return [this.id]
}
User.prototype.getAdministrators = async function () {
return [this]
}
User.prototype.getMyDiscussionsTimeline = async function (params) {
const myDiscussionsTimelineId = await this.getMyDiscussionsTimelineIntId()
const feed = await dbAdapter.getTimelineByIntId(myDiscussionsTimelineId, params)
feed.posts = await feed.getPosts(feed.offset, feed.limit)
return feed
}
User.prototype.getGenericTimelineId = async function (name) {
const timelineId = await dbAdapter.getUserNamedFeedId(this.id, name);
if (!timelineId) {
console.log(`Timeline '${name}' not found for user`, this); // eslint-disable-line no-console
return null;
}
return timelineId;
};
User.prototype.getUnreadDirectsNumber = async function () {
const unreadDirectsNumber = await dbAdapter.getUnreadDirectsNumber(this.id);
return unreadDirectsNumber;
}
User.prototype.getGenericTimelineIntId = async function (name) {
const timelineIds = await this.getTimelineIds();
const intIds = await dbAdapter.getTimelinesIntIdsByUUIDs([timelineIds[name]]);
if (intIds.length === 0) {
return null;
}
return intIds[0];
}
User.prototype.getGenericTimeline = async function (name, params) {
const timelineId = await this[`get${name}TimelineId`](params)
const timeline = await dbAdapter.getTimelineById(timelineId, params)
timeline.posts = await timeline.getPosts(timeline.offset, timeline.limit)
return timeline
}
User.prototype.getMyDiscussionsTimelineIntId = function () {
return this.getGenericTimelineIntId('MyDiscussions')
}
User.prototype.getHidesTimelineId = function () {
return this.getGenericTimelineId('Hides')
}
User.prototype.getHidesTimelineIntId = function (params) {
return this.getGenericTimelineIntId('Hides', params)
}
User.prototype.getRiverOfNewsTimelineId = function () {
return this.getGenericTimelineId('RiverOfNews')
}
User.prototype.getRiverOfNewsTimelineIntId = function (params) {
return this.getGenericTimelineIntId('RiverOfNews', params)
}
User.prototype.getRiverOfNewsTimeline = async function (params) {
const [banIds, timelineId, hidesTimelineIntId] = await Promise.all([
this.getBanIds(),
this.getRiverOfNewsTimelineId(),
this.getHidesTimelineIntId(params)
]);
const riverOfNewsTimeline = await dbAdapter.getTimelineById(timelineId, params);
const posts = await riverOfNewsTimeline.getPosts(riverOfNewsTimeline.offset, riverOfNewsTimeline.limit);
riverOfNewsTimeline.posts = posts.map((post) => {
if (banIds.includes(post.userId)) {
return null;
}
if (post.feedIntIds.includes(hidesTimelineIntId)) {
post.isHidden = true;
}
return post;
});
return riverOfNewsTimeline;
};
User.prototype.getLikesTimelineId = function () {
return this.getGenericTimelineId('Likes')
}
User.prototype.getLikesTimelineIntId = function () {
return this.getGenericTimelineIntId('Likes')
}
User.prototype.getLikesTimeline = function (params) {
return this.getGenericTimeline('Likes', params)
}
User.prototype.getPostsTimelineId = function () {
return this.getGenericTimelineId('Posts')
}
User.prototype.getPostsTimelineIntId = function () {
return this.getGenericTimelineIntId('Posts')
}
User.prototype.getPostsTimeline = function (params) {
return this.getGenericTimeline('Posts', params)
}
User.prototype.getCommentsTimelineId = function () {
return this.getGenericTimelineId('Comments')
}
User.prototype.getCommentsTimelineIntId = function () {
return this.getGenericTimelineIntId('Comments')
}
User.prototype.getCommentsTimeline = function (params) {
return this.getGenericTimeline('Comments', params)
}
User.prototype.getDirectsTimelineId = function () {
return this.getGenericTimelineId('Directs')
}
User.prototype.getDirectsTimeline = function (params) {
return this.getGenericTimeline('Directs', params)
}
User.prototype.getTimelineIds = async function () {
const timelineIds = await dbAdapter.getUserTimelinesIds(this.id)
return timelineIds || {}
}
User.prototype.getTimelines = async function (params) {
const timelineIds = await this.getTimelineIds()
const timelines = await dbAdapter.getTimelinesByIds(_.values(timelineIds), params)
const timelinesOrder = ['RiverOfNews', 'Hides', 'Comments', 'Likes', 'Posts', 'Directs', 'MyDiscussions']
const sortedTimelines = _.sortBy(timelines, (tl) => {
return _.indexOf(timelinesOrder, tl.name)
})
return sortedTimelines
}
User.prototype.getPublicTimelineIds = function () {
return Promise.all([
this.getCommentsTimelineId(),
this.getLikesTimelineId(),
this.getPostsTimelineId()
])
}
User.prototype.getPublicTimelinesIntIds = function () {
return dbAdapter.getUserNamedFeedsIntIds(this.id, ['Posts', 'Likes', 'Comments'])
}
/**
* @return {Timeline[]}
*/
User.prototype.getSubscriptions = async function () {
this.subscriptions = await dbAdapter.getTimelinesByIntIds(this.subscribedFeedIds)
return this.subscriptions
}
User.prototype.getFriendIds = async function () {
return await dbAdapter.getUserFriendIds(this.id);
}
User.prototype.getFriends = async function () {
const userIds = await this.getFriendIds()
return await dbAdapter.getUsersByIds(userIds)
}
User.prototype.getSubscriberIds = async function () {
const postsFeedIntId = await this.getPostsTimelineIntId()
const timeline = await dbAdapter.getTimelineByIntId(postsFeedIntId)
this.subscriberIds = await timeline.getSubscriberIds()
return this.subscriberIds
}
User.prototype.getSubscribers = async function () {
const subscriberIds = await this.getSubscriberIds();
this.subscribers = await dbAdapter.getUsersByIds(subscriberIds);
return this.subscribers;
}
User.prototype.getBanIds = function () {
return dbAdapter.getUserBansIds(this.id)
}
User.prototype.ban = async function (username) {
const user = await dbAdapter.getUserByUsername(username)
if (null === user) {
throw new NotFoundException(`User "${username}" is not found`)
}
await dbAdapter.createUserBan(this.id, user.id);
const promises = [
user.unsubscribeFrom(await this.getPostsTimelineId())
]
// reject if and only if there is a pending request
const requestIds = await this.getSubscriptionRequestIds()
if (requestIds.includes(user.id))
promises.push(this.rejectSubscriptionRequest(user.id))
await Promise.all(promises)
monitor.increment('users.bans')
return 1
}
User.prototype.unban = async function (username) {
const user = await dbAdapter.getUserByUsername(username)
if (null === user) {
throw new NotFoundException(`User "${username}" is not found`)
}
await dbAdapter.deleteUserBan(this.id, user.id)
monitor.increment('users.unbans')
return 1;
}
// Subscribe to user-owner of a given `timelineId`
User.prototype.subscribeTo = async function (targetTimelineId) {
const targetTimeline = await dbAdapter.getTimelineById(targetTimelineId)
const targetTimelineOwner = await dbAdapter.getFeedOwnerById(targetTimeline.userId)
if (targetTimelineOwner.username == this.username)
throw new Error('Invalid')
const timelineIds = await targetTimelineOwner.getPublicTimelineIds()
const subscribedFeedsIntIds = await dbAdapter.subscribeUserToTimelines(timelineIds, this.id)
await dbAdapter.createMergedPostsTimeline(await this.getRiverOfNewsTimelineIntId(), [targetTimeline.intId]);
this.subscribedFeedIds = subscribedFeedsIntIds
await dbAdapter.statsSubscriptionCreated(this.id)
await dbAdapter.statsSubscriberAdded(targetTimelineOwner.id)
monitor.increment('users.subscriptions')
return this
}
// Subscribe this user to `username`
User.prototype.subscribeToUsername = async function (username) {
const user = await dbAdapter.getFeedOwnerByUsername(username)
if (null === user) {
throw new NotFoundException(`Feed "${username}" is not found`)
}
const timelineId = await user.getPostsTimelineId()
return this.subscribeTo(timelineId)
}
User.prototype.unsubscribeFrom = async function (timelineId, options = {}) {
const timeline = await dbAdapter.getTimelineById(timelineId)
const user = await dbAdapter.getFeedOwnerById(timeline.userId)
const wasSubscribed = await dbAdapter.isUserSubscribedToTimeline(this.id, timelineId)
// a user cannot unsubscribe from herself
if (user.username == this.username)
throw new Error('Invalid')
if (_.isUndefined(options.skip)) {
// remove timelines from user's subscriptions
const timelineIds = await user.getPublicTimelineIds()
const subscribedFeedsIntIds = await dbAdapter.unsubscribeUserFromTimelines(timelineIds, this.id)
this.subscribedFeedIds = subscribedFeedsIntIds
}
const promises = []
// remove all posts of The Timeline from user's River of News
promises.push(timeline.unmerge(await this.getRiverOfNewsTimelineIntId()))
// remove all posts of The Timeline from likes timeline of user
if (options.likes)
promises.push(timeline.unmerge(await this.getLikesTimelineIntId()))
// remove all post of The Timeline from comments timeline of user
if (options.comments)
promises.push(timeline.unmerge(await this.getCommentsTimelineIntId()))
await Promise.all(promises)
if (wasSubscribed) {
await dbAdapter.statsSubscriptionDeleted(this.id)
await dbAdapter.statsSubscriberRemoved(user.id)
}
monitor.increment('users.unsubscriptions')
return this
}
User.prototype.calculateStatsValues = async function () {
let res
try {
res = await dbAdapter.getUserStats(this.id)
} catch (e) {
res = { posts: 0, likes: 0, comments: 0, subscribers: 0, subscriptions: 0 }
}
return res
}
User.prototype.getStatistics = async function () {
if (!this.statsValues) {
this.statsValues = await this.calculateStatsValues()
}
return this.statsValues
}
User.prototype.newComment = function (attrs) {
attrs.userId = this.id
monitor.increment('users.comments')
return new Comment(attrs)
}
User.prototype.newAttachment = async function (attrs) {
attrs.userId = this.id
monitor.increment('users.attachments')
return new Attachment(attrs)
}
User.prototype.updateProfilePicture = async function (file) {
const image = promisifyAll(gm(file.path))
let originalSize
try {
originalSize = await image.sizeAsync()
} catch (err) {
throw new BadRequestException('Not an image file')
}
this.profilePictureUuid = uuid.v4()
const sizes = [
User.PROFILE_PICTURE_SIZE_LARGE,
User.PROFILE_PICTURE_SIZE_MEDIUM
]
const promises = sizes.map((size) => this.saveProfilePictureWithSize(file.path, this.profilePictureUuid, originalSize, size))
await Promise.all(promises)
this.updatedAt = new Date().getTime()
const payload = {
'profilePictureUuid': this.profilePictureUuid,
'updatedAt': this.updatedAt.toString()
}
return dbAdapter.updateUser(this.id, payload)
}
User.prototype.saveProfilePictureWithSize = async function (path, uuid, originalSize, size) {
const origWidth = originalSize.width
const origHeight = originalSize.height
const retinaSize = size * 2
let image = promisifyAll(gm(path))
if (origWidth > origHeight) {
const dx = origWidth - origHeight
image = image.crop(origHeight, origHeight, dx / 2, 0)
} else if (origHeight > origWidth) {
const dy = origHeight - origWidth
image = image.crop(origWidth, origWidth, 0, dy / 2)
}
image = image
.resize(retinaSize, retinaSize)
.profile(`${__dirname}/../../lib/assets/sRGB.icm`)
.autoOrient()
.quality(95)
if (config.profilePictures.storage.type === 's3') {
const tmpPictureFile = `${path}.resized.${size}`
const destPictureFile = this.getProfilePictureFilename(uuid, size)
await image.writeAsync(tmpPictureFile)
await this.uploadToS3(tmpPictureFile, destPictureFile, config.profilePictures)
return fs.unlinkAsync(tmpPictureFile)
}
const destPath = this.getProfilePicturePath(uuid, size)
return image.writeAsync(destPath)
}
// Upload profile picture to the S3 bucket
User.prototype.uploadToS3 = async function (sourceFile, destFile, subConfig) {
const s3 = new aws.S3({
'accessKeyId': subConfig.storage.accessKeyId || null,
'secretAccessKey': subConfig.storage.secretAccessKey || null
})
const putObject = promisify(s3.putObject, { context: s3 })
await putObject({
ACL: 'public-read',
Bucket: subConfig.storage.bucket,
Key: subConfig.path + destFile,
Body: fs.createReadStream(sourceFile),
ContentType: 'image/jpeg',
ContentDisposition: 'inline'
})
}
User.prototype.getProfilePicturePath = function (uuid, size) {
return config.profilePictures.storage.rootDir + config.profilePictures.path + this.getProfilePictureFilename(uuid, size)
}
User.prototype.getProfilePictureFilename = (uuid, size) => `${uuid}_${size}.jpg`;
// used by serializer
User.prototype.getProfilePictureLargeUrl = async function () {
if (_.isEmpty(this.profilePictureUuid)) {
return ''
}
return config.profilePictures.url
+ config.profilePictures.path
+ this.getProfilePictureFilename(this.profilePictureUuid, User.PROFILE_PICTURE_SIZE_LARGE)
}
// used by serializer
User.prototype.getProfilePictureMediumUrl = async function () {
if (_.isEmpty(this.profilePictureUuid)) {
return ''
}
return config.profilePictures.url
+ config.profilePictures.path
+ this.getProfilePictureFilename(this.profilePictureUuid, User.PROFILE_PICTURE_SIZE_MEDIUM)
}
Reflect.defineProperty(User.prototype, 'profilePictureLargeUrl', {
get: function () {
if (_.isEmpty(this.profilePictureUuid)) {
return '';
}
return config.profilePictures.url
+ config.profilePictures.path
+ this.getProfilePictureFilename(this.profilePictureUuid, User.PROFILE_PICTURE_SIZE_LARGE);
}
});
Reflect.defineProperty(User.prototype, 'profilePictureMediumUrl', {
get: function () {
if (_.isEmpty(this.profilePictureUuid)) {
return '';
}
return config.profilePictures.url
+ config.profilePictures.path
+ this.getProfilePictureFilename(this.profilePictureUuid, User.PROFILE_PICTURE_SIZE_MEDIUM);
}
});
/**
* Checks if the specified user can post to the timeline of this user.
*/
User.prototype.validateCanPost = async function (postingUser) {
// NOTE: when user is subscribed to another user she in fact is
// subscribed to her posts timeline
const [timelineIdA, timelineIdB] =
await Promise.all([postingUser.getPostsTimelineId(), this.getPostsTimelineId()])
const currentUserSubscribedToPostingUser = await dbAdapter.isUserSubscribedToTimeline(this.id, timelineIdA)
const postingUserSubscribedToCurrentUser = await dbAdapter.isUserSubscribedToTimeline(postingUser.id, timelineIdB)
if ((!currentUserSubscribedToPostingUser || !postingUserSubscribedToCurrentUser)
&& postingUser.username != this.username
) {
throw new ForbiddenException("You can't send private messages to friends that are not mutual")
}
}
User.prototype.updateLastActivityAt = async function () {
if (!this.isUser()) {
// update group lastActivity for all subscribers
const updatedAt = new Date().getTime()
const payload = { 'updatedAt': updatedAt.toString() }
await dbAdapter.updateUser(this.id, payload)
}
}
User.prototype.sendSubscriptionRequest = async function (userId) {
return await dbAdapter.createSubscriptionRequest(this.id, userId)
}
User.prototype.sendPrivateGroupSubscriptionRequest = async function (groupId) {
return await dbAdapter.createSubscriptionRequest(this.id, groupId)
}
User.prototype.acceptSubscriptionRequest = async function (userId) {
await dbAdapter.deleteSubscriptionRequest(this.id, userId)
const timelineId = await this.getPostsTimelineId()
const user = await dbAdapter.getUserById(userId)
return user.subscribeTo(timelineId)
}
User.prototype.rejectSubscriptionRequest = async function (userId) {
return await dbAdapter.deleteSubscriptionRequest(this.id, userId)
}
User.prototype.getPendingSubscriptionRequestIds = async function () {
this.pendingSubscriptionRequestIds = await dbAdapter.getUserSubscriptionPendingRequestsIds(this.id)
return this.pendingSubscriptionRequestIds
}
User.prototype.getPendingSubscriptionRequests = async function () {
const pendingSubscriptionRequestIds = await this.getPendingSubscriptionRequestIds()
return await dbAdapter.getUsersByIds(pendingSubscriptionRequestIds)
}
User.prototype.getSubscriptionRequestIds = async function () {
return await dbAdapter.getUserSubscriptionRequestsIds(this.id)
}
User.prototype.getSubscriptionRequests = async function () {
const subscriptionRequestIds = await this.getSubscriptionRequestIds()
return await dbAdapter.getUsersByIds(subscriptionRequestIds)
}
User.prototype.getFollowedGroups = async function () {
const timelinesIds = await dbAdapter.getUserSubscriptionsIds(this.id)
if (timelinesIds.length === 0)
return []
const timelines = await dbAdapter.getTimelinesByIds(timelinesIds)
if (timelines.length === 0)
return []
const timelineOwnerIds = _(timelines).map('userId').uniq().value()
if (timelineOwnerIds.length === 0)
return []
const timelineOwners = await dbAdapter.getFeedOwnersByIds(timelineOwnerIds)
if (timelineOwners.length === 0)
return []
const followedGroups = timelineOwners.filter((owner) => {
return 'group' === owner.type
})
return followedGroups
}
User.prototype.getManagedGroups = async function () {
const groupsIds = await dbAdapter.getManagedGroupIds(this.id);
return await dbAdapter.getUsersByIds(groupsIds);
}
User.prototype.pendingPrivateGroupSubscriptionRequests = async function () {
const managedGroups = await this.getManagedGroups()
const promises = managedGroups.map(async (group) => {
const unconfirmedFollowerIds = await group.getSubscriptionRequestIds()
return unconfirmedFollowerIds.length > 0
})
return _.some((await Promise.all(promises)), Boolean)
}
User.prototype.getPendingGroupRequests = function () {
return dbAdapter.userHavePendingGroupRequests(this.id);
}
return User
}
|
'use strict';
/* global angular, jasmine, describe, it, expect, module, inject, beforeEach, spyOn */
var demoOAuthSpecs = angular.module('dmeoOAuthSpecs', ['ngOAuth','ngMock']);
describe('The demoOAuth service provider', function(){
var demoOAuthProviderAlias;
beforeEach( function(){
var ngOAuthTest = angular.module('ngOAuthTest',['ngOAuth']);
ngOAuthTest.config(['demoOAuthProvider',function(demoOAuthProvider){
demoOAuthProviderAlias=demoOAuthProvider;
demoOAuthProviderAlias.users([{username:'admin', success:true}, {username:'guest',success:false}]);
}]);
module('ngOAuthTest');
inject(function () {});
});
it( 'should expose the users method, that configures the users for the service', function() {
expect(demoOAuthProviderAlias.users).toBeDefined();
});
it('should now provide a service with the configured users', inject(function(demoOAuth){
expect( demoOAuth.users.length).toEqual(2);
}));
});
describe('The demoOAuth service', function(){
beforeEach( module('ngOAuth') );
var demoOAuth;
var $rootScope;
beforeEach( inject( function(_$rootScope_, _demoOAuth_){
$rootScope = _$rootScope_;
demoOAuth = _demoOAuth_;
}));
it( 'should expose the authenticate method', function() {
expect(demoOAuth.authenticate).toBeDefined();
});
describe('The authenticate method', function() {
var OAuth;
var error = {
status:400,
data: {error:'invalid_grant', error_description : 'The user name or password is incorrect.' }
};
beforeEach( inject( function( _OAuth_ ){
OAuth = _OAuth_;
}));
it('should call the authentication method on OAuth.manager, with the promise to authenticate', function( done ) {
spyOn(OAuth.manager, 'authentication');
var promise = demoOAuth.authenticate('user@teste.com', 'correctPassword');
$rootScope.$digest();
expect(OAuth.manager.authentication).toHaveBeenCalledWith(promise, demoOAuth);
done();
});
it('should return a promise for a valid access Token when given username and password', function() {
var promise = demoOAuth.authenticate('user@teste.com', 'correctPassword');
expect( promise ).toBeDefined();
expect( promise.then ).toBeDefined();
expect( promise.catch ).toBeDefined();
expect( promise.success ).toBeDefined();
expect( promise.error ).toBeDefined();
});
it(' the promise should return a valid access token if authenticated,', function( done ) {
var promise = demoOAuth.authenticate('user@teste.com', 'correctPassword');
var handler = jasmine.createSpy('then');
promise.then(handler);
$rootScope.$digest();
expect(handler).toHaveBeenCalledWith({'access_token':'ANiceBearerToken'});
done();
});
it(' the promise should return 400 http status code if NOT authenticated,', function( done ) {
var promise = demoOAuth.authenticate('user@teste.com', 'incorrectPassword');
var handler = jasmine.createSpy('catch');
promise.catch( handler );
$rootScope.$digest();
expect(handler).toHaveBeenCalledWith(error);
done();
});
});
it( 'should expose the loadUser method', function() {
expect(demoOAuth.loadUser).toBeDefined();
});
describe('The loadUser method', function() {
var OAuth;
beforeEach( inject( function( _OAuth_ ){
OAuth = _OAuth_;
}));
it('should call the info method on OAuth.manager, if successfull', function( done ) {
spyOn(OAuth.manager, 'info');
var promise= demoOAuth.loadUser({'access_token':'ANiceBearerToken'});
$rootScope.$digest();
expect(OAuth.manager.info).toHaveBeenCalledWith(promise);
done();
});
it('should return a promise for a valid User when given an access Token', function() {
var promise = demoOAuth.loadUser({'access_token':'ANiceBearerToken'});
expect( promise ).toBeDefined();
expect( promise.then ).toBeDefined();
expect( promise.catch ).toBeDefined();
expect( promise.success ).toBeDefined();
expect( promise.error ).toBeDefined();
});
it(' the promise should return user info if successfull,', function( done ) {
var userInfo = {name:'Jonathan Doe', salutation: 'Mr.', username: 'joe'};
var promise = demoOAuth.loadUser({'access_token':'ANiceBearerToken'});
var handler = jasmine.createSpy('then');
promise.then(handler);
$rootScope.$digest();
expect(handler).toHaveBeenCalledWith(userInfo);
done();
});
it(' the promise should return an error if it fails,', function( done ) {
var promise = demoOAuth.loadUser({'access_token':'NotSoNiceBearerToken'});
var handler = jasmine.createSpy('catch');
promise.catch( handler );
$rootScope.$digest();
expect(handler).toHaveBeenCalledWith({code:'0001', message:'Could not load user'});
done();
});
});
});
describe('The demoLogin directive', function() {
var element;
var $rootScope;
beforeEach( module('ngOAuth') );
beforeEach(inject( function ( $compile, _$rootScope_ ) {
$rootScope = _$rootScope_;
var scope = $rootScope.$new();
element = $compile('<demo-login></demo-login>')( scope );
scope.$digest();
}));
it('should have an isolated scope', inject( function() {
var scope = element.isolateScope();
expect( scope ).toBeDefined();
}));
it('should replace the element with the appropriate content that', function() {
expect( $(element).prop('tagName') ).toEqual('FORM');
expect( $(element).attr('name') ).toEqual('loginForm');
expect( $(element).attr('novalidate') ).toEqual('');
});
it(' should include select user field', function() {
expect( $(element).find('select').length ).toBe(1);
});
it('should add an users array to the scope', function() {
var scope = element.isolateScope();
expect( scope.users ).toBeDefined();
});
it('should add an selectedUser object to the scope, with the firts item of the users array', function() {
var scope = element.isolateScope();
expect( scope.selectedUser ).toBeDefined();
expect( scope.selectedUser ).toBe( scope.users[0]);
});
it('should add a loginButton object to the scope, with the label', function() {
var scope = element.isolateScope();
expect( scope.loginButton ).toBeDefined();
expect( scope.loginButton.label ).toEqual('Sign in');
});
it('should add a login method to the scope', function() {
var scope = element.isolateScope();
expect( scope.login ).toBeDefined();
});
describe('The login method', function() {
it('should change the login button label while the login is in progress, then change it back', function(done) {
var scope = element.isolateScope();
scope.login();
expect( scope.loginButton.label ).toEqual('Signing in...');
$rootScope.$digest();
expect( scope.error ).toBeFalsy();
expect( scope.loginButton.label ).toEqual('Sign in');
done();
});
it('should change the login button label back if login faild, and add an error property to the scope', function(done) {
var scope = element.isolateScope();
scope.selectedUser = scope.users[2];
scope.login();
expect( scope.loginButton.label ).toEqual('Signing in...');
$rootScope.$digest();
expect( scope.error ).toBeTruthy();
expect( scope.loginButton.label ).toEqual('Sign in');
done();
});
});
});
|
import nock from 'nock';
import fs from 'fs-extra';
import HttpService, { getCacheFilePath, getFileModifiedTime } from './HttpService';
jest.mock('../../config.js', () => ({
defaults: {
cachePath: 'testBase',
maxCacheAge: 0,
},
}));
describe('getCacheFilePath', () => {
const getFilePath = (url, params) => getCacheFilePath({ url, params });
it('should output root to domain with index.html', () => {
expect(getFilePath('https://www.example.com')).toBe('testBase/example.com/index.html');
expect(getFilePath('https://www.example.com/test')).toBe('testBase/example.com/test/index.html');
});
it('should normalize url', () => {
const expectedOutput = 'testBase/example.com/index.html';
expect(getFilePath('https://www.example.com')).toBe(expectedOutput);
expect(getFilePath('https://www.example.com:80')).toBe(expectedOutput);
expect(getFilePath('http://www.example.com')).toBe(expectedOutput);
expect(getFilePath('http://example.com/')).toBe(expectedOutput);
expect(getFilePath('http://example.com/index.html')).toBe(expectedOutput);
expect(getFilePath('http://www.example.com/#context')).toBe(expectedOutput);
expect(getFilePath('http://example.com/', 'a=1&b=2'))
.toBe(getFilePath('http://example.com/', 'b=2&a=1'));
expect(getFilePath('http://example.com/?a=1', 'b=2'))
.toBe(getFilePath('http://example.com/?b=2', 'a=1'));
});
it('should output queries to file savable format', () => {
expect(getFilePath('https://www.example.com/', 'query="test"&x="test"'))
.toBe('testBase/example.com/query=test&x=test');
expect(getFilePath('https://www.example.com/', 'query=123'))
.toBe('testBase/example.com/query=123');
expect(getFilePath('https://www.example.com/', '<te>'))
.toBe('testBase/example.com/te=');
});
it('should split subpaths to many different subfolders', () => {
expect(getFilePath('https://www.example.com/test/', 'query="test"'))
.toBe('testBase/example.com/test/query=test');
expect(getFilePath('https://www.example.com/1/2/', 'query=123&x=5'))
.toBe('testBase/example.com/1/2/query=123&x=5');
expect(getFilePath('https://www.example.com/1/2/hex'))
.toBe('testBase/example.com/1/2/hex/index.html');
});
it('should throw when there is no valid filename', () => {
expect(() => getFilePath('')).toThrow();
});
});
describe('getFileModifiedTime', () => {
const mockFileSystemMeta = {
testFile: {
isFile: () => true,
mtime: 0,
},
testFolder: {
isFile: () => false,
mtime: 0,
},
};
beforeAll(() => {
fs.setMock({}, mockFileSystemMeta);
});
it('should output the modified time of a file', async () => {
expect(await getFileModifiedTime('testFile')).toBe(mockFileSystemMeta.testFile.mtime);
});
it('should output null if it is not a file', async () => {
expect(await getFileModifiedTime('testFolder')).toBe(null);
});
it('should output null if no file', async () => {
expect(await getFileModifiedTime('testNoFile')).toBe(null);
});
});
describe('HttpService', () => {
const HOST = 'http://example.com';
const EPOCH = new Date(0);
const cachedData = 'cached test';
const freshData = 'no cached test';
const mockFileSystem = {
'testBase/example.com/index.html': cachedData,
};
let mockFileSystemMeta;
beforeEach(() => {
mockFileSystemMeta = {
'testBase/example.com/index.html': {
isFile: () => true,
// Default should not be cached
// since file is 40+ years old
mtime: EPOCH,
},
};
fs.setMock(mockFileSystem, mockFileSystemMeta);
nock(HOST).get(/.*/).reply(200, freshData);
});
afterAll(() => {
nock.cleanAll();
});
describe('nock server', () => {
it('should return mock reponse', async () => {
const response = await HttpService.get(HOST);
expect(response.data).toBe(freshData);
});
});
describe('requestInterceptor', () => {
it('should intercept and return cache file if it exists', async () => {
mockFileSystemMeta['testBase/example.com/index.html'].mtime = Date.now() + 1000;
fs.setMock(mockFileSystem, mockFileSystemMeta);
const response = await HttpService.get(HOST);
expect(response.data).toBe(cachedData);
expect(response.config.isCached).toBeTruthy();
});
it('should not intercept if cache file has expired', async () => {
const response = await HttpService.get(HOST);
expect(response.data).toBe(freshData);
expect(response.config.isCached).toBeFalsy();
});
it('should not intercept if cache file does not exist', async () => {
const response = await HttpService.get(`${HOST}/noCached`);
expect(response.data).toBe(freshData);
expect(response.config.isCached).toBeFalsy();
});
it('should set if-modified-since if cache file has expired', async () => {
const response = await HttpService.get(`${HOST}`);
expect(response.config.headers['if-modified-since']).toBe(EPOCH.toUTCString());
});
});
describe('responseInterceptor', () => {
beforeEach(() => {
fs.outputFile = jest.fn();
});
it('should cache file if it is not already cached', async () => {
await HttpService.get(HOST);
expect(fs.outputFile).toBeCalled();
});
it('should not cache file if it is already cached', async () => {
mockFileSystemMeta['testBase/example.com/index.html'].mtime = Date.now() + 1000;
fs.setMock(mockFileSystem, mockFileSystemMeta);
await HttpService.get(HOST);
expect(fs.outputFile).not.toBeCalled();
});
it('should send cached file if server returns 304', async () => {
nock.cleanAll();
nock(HOST).get(/.*/).reply(304);
const response = await HttpService.get(HOST);
expect(fs.outputFile).not.toBeCalled();
expect(response.data).toBe(cachedData);
});
});
});
|
const bcrypt = require('bcrypt-nodejs');
const crypto = require('crypto');
const mongoose = require('mongoose');
const droneSchema = new mongoose.Schema({
fManuc: String,
fModel: String,
fFlyTime: String,
fAerial: Boolean ,
fOrtho: Boolean,
fVideo: Boolean,
fUser: String
});
const Drone = mongoose.model('Drone', droneSchema);
module.exports = Drone;
|
module.exports = (params) => {
return publish("page_view_events", {
...params.defaultConfig
}).query(ctx => `
select
${event_fields.DATE_TIME_FIELDS},
${event_fields.DATE_TIME_FIELDS},
${event_fields.EVENT_TRANSACTION_FIELDS},
${event_fields.SNOWPLOW_VERSION_FIELDS},
${event_fields.USER_FIELDS},
${event_fields.DEVICE_OS_FIELDS},
${event_fields.LOCATION_FIELDS},
${event_fields.IP_FIELDS},
${event_fields.METADATA_FIELDS},
${event_fields.PAGE_FIELDS},
${event_fields.DOCUMENT_FIELDS},
${event_fields.MARKETING_FIELDS},
${event_fields.BROWSER_FIELDS}
from
${ctx.ref(params.snowplowSchema, "events")}
where
platform = 'web'
and event_name = 'page_view'
`)
}
|
Youtube.Router.map(function () {
this.resource('app', function () {
this.route('video');
this.route('search');
});
});
Youtube.AppVideoIndexRoute = Ember.Route.extend({
redirect: function () {
this.transitionTo('video/23');
}
});
Youtube.IndexRoute = Ember.Route.extend({
redirect: function () {
this.transitionTo('app');
}
});
Youtube.AppIndexRoute = Ember.Route.extend({
redirect: function () {
this.transitionTo('app.video');
}
});
Youtube.AppRoute = Ember.Route.extend({
renderTemplate: function () {
this.render();
this.render('playlist', {
into: 'app',
outlet: 'playlist'
});
},
setupController: function (controller, model) {
this.controllerFor('playlist').send('load');
}
});
Youtube.AppSearchRoute = Em.Route.extend({
setupController: function (controller) {
controller.send('search');
},
controllerName: 'search'
});
|
import lodash from 'lodash';
const PROFILE_LAYOUT_TOP_DOWN = 'top-down';
const PROFILE_LAYOUT_NARROW_WIDE = 'narrow-wide';
const PROFILE_LAYOUT_HERO_SIDEBAR = 'hero-sidebar';
const VALID_PROFILE_LAYOUT_STYLES = [
PROFILE_LAYOUT_TOP_DOWN,
PROFILE_LAYOUT_NARROW_WIDE,
PROFILE_LAYOUT_HERO_SIDEBAR,
];
const localState = {
layoutStyles: {
profile: PROFILE_LAYOUT_TOP_DOWN,
},
};
const localGetters = {
profileLayoutStyle: state => state.layoutStyles.profile,
};
const UI_SET_PROFILE_LAYOUT_STYLE = 'UI:SET:PROFILE:LAYOUT_STYLE';
const localActions = {
setProfileLayoutStyle({ commit }, { layoutStyle }) {
const found = lodash.find(VALID_PROFILE_LAYOUT_STYLES, (item => item === layoutStyle));
commit(UI_SET_PROFILE_LAYOUT_STYLE, {
layoutStyle: found,
});
},
};
/* eslint-disable no-param-reassign */
const localMutations = {
[UI_SET_PROFILE_LAYOUT_STYLE](state, { layoutStyle = PROFILE_LAYOUT_TOP_DOWN }) {
state.layoutStyles.profile = layoutStyle;
},
};
/* eslint-disable no-param-reassign */
export default {
state: localState,
actions: localActions,
getters: localGetters,
mutations: localMutations,
};
|
// Copyright 2015-2021, University of Colorado Boulder
/**
* Given structured documentation output from extractDocumentation (and associated other metadata), this outputs both
* HTML meant for a collapsible documentation index and HTML content for all of the documentation.
*
* @author Jonathan Olson <jonathan.olson@colorado.edu>
*/
/* eslint-env browser, node */
( function() {
let typeURLs = {
// is replaced by every documentationToHTML() call
};
// borrowed from phet-core.
function escapeHTML( str ) {
// see https://www.owasp.org/index.php/XSS_(Cross_Site_Scripting)_Prevention_Cheat_Sheet
// HTML Entity Encoding
return str
.replace( /&/g, '&' )
.replace( /</g, '<' )
.replace( />/g, '>' )
.replace( /"/g, '"' )
.replace( /'/g, ''' )
.replace( /\//g, '/' );
}
/**
* Parses the HTML looking for examples (matching #begin and #end) that have embedded #on/#off to control where code
* examples are displayed. Breaks up everything into a concise paragraph structure (blank lines trigger the end of a
* paragraph).
* @private
*
* @param {string} string
* @returns {string}
*/
function descriptionHTML( string ) {
let result = '';
const lines = string.split( '\n' );
let inParagraph = false;
function insideParagraph() {
if ( !inParagraph ) {
result += '<p>\n';
inParagraph = true;
}
}
function outsideParagraph() {
if ( inParagraph ) {
result += '</p>\n';
inParagraph = false;
}
}
for ( let i = 0; i < lines.length; i++ ) {
const line = lines[ i ];
if ( line.indexOf( '#begin' ) === 0 ) {
const initialLine = lines[ i ];
const runLines = [];
const displayLines = [];
let isDisplayed = false;
for ( i++; i < lines.length; i++ ) {
if ( lines[ i ].indexOf( '#end' ) === 0 ) {
break;
}
else if ( lines[ i ].indexOf( '#on' ) === 0 ) {
isDisplayed = true;
}
else if ( lines[ i ].indexOf( '#off' ) === 0 ) {
isDisplayed = false;
}
else {
runLines.push( lines[ i ] );
if ( isDisplayed ) {
displayLines.push( lines[ i ] );
}
}
}
const runString = runLines.join( '\n' );
const displayString = displayLines.join( '\n' );
const canvasExampleMatch = initialLine.match( /^#begin canvasExample ([^ ]+) ([^x]+)x([^x]+)$/ );
if ( canvasExampleMatch ) {
outsideParagraph();
const name = canvasExampleMatch[ 1 ];
const width = canvasExampleMatch[ 2 ];
const height = canvasExampleMatch[ 3 ];
const exampleName = `example-${name}`;
result += `<canvas id="${exampleName}" class="exampleScene"></canvas>`;
result += '<script>(function(){';
result += `var canvas = document.getElementById( "${exampleName}" );`;
result += `canvas.width = ${width};`;
result += `canvas.height = ${height};`;
result += 'var context = canvas.getContext( "2d" );';
result += runString;
result += '})();</' + 'script>'; // eslint-disable-line no-useless-concat
result += '<pre class="brush: js">\n';
result += displayString;
result += '</pre>';
}
}
else {
if ( line.length === 0 ) {
outsideParagraph();
}
else {
insideParagraph();
result += `${line}\n`;
}
}
}
outsideParagraph();
return result;
}
function typeString( type ) {
const url = typeURLs[ type ];
if ( url ) {
return ` <a href="${url}" class="type">${escapeHTML( type )}</a>`;
}
else {
return ` <span class="type">${escapeHTML( type )}</span>`;
}
}
function inlineParameterList( object ) {
let result = '';
if ( object.parameters ) {
result += `( ${object.parameters.map( parameter => {
let name = parameter.name;
if ( parameter.optional ) {
name = `<span class="optional">${name}</span>`;
}
return `<span class="args">${typeString( parameter.type )} ${name}</span>`;
} ).join( ', ' )} )`;
}
else if ( object.type === 'function' ) {
result += '()';
}
return result;
}
function parameterDetailsList( object ) {
let result = '';
const parametersWithDescriptions = object.parameters ? object.parameters.filter( parameter => {
return !!parameter.description;
} ) : [];
if ( parametersWithDescriptions.length ) {
result += '<table class="params">\n';
parametersWithDescriptions.forEach( parameter => {
let name = parameter.name;
const description = parameter.description || '';
if ( parameter.optional ) {
name = `<span class="optional">${name}</span>`;
}
result += `<tr class="param"><td>${typeString( parameter.type )}</td><td>${name}</td><td> - </td><td>${description}</td></tr>\n`;
} );
result += '</table>\n';
}
return result;
}
function returnOrConstant( object ) {
let result = '';
if ( object.returns || object.constant ) {
const type = ( object.returns || object.constant ).type;
if ( object.returns ) {
result += ' :';
}
result += `<span class="return">${typeString( type )}</span>`;
}
return result;
}
function nameLookup( array, name ) {
for ( let i = 0; i < array.length; i++ ) {
if ( array[ i ].name === name ) {
return array[ i ];
}
}
return null;
}
/**
* For a given doc (extractDocumentation output) and a base name for the file (e.g. 'Vector2' for Vector2.js),
* collect top-level documentation (and public documentation for every type referenced in typeNmaes) and return an
* object: { indexHTML: {string}, contentHTML: {string} } which includes the HTML for the index (list of types and
* methods/fields/etc.) and content (the documentation itself).
*
* @param {Object} doc
* @param {string} baseName
* @param {Array.<string>} typeNames - Names of types from this file to include in the documentation.
* @param {Object} localTypeIds - Keys should be type names included in the same documentation output, and the values
* should be a prefix applied for hash URLs of the given type. This helps prefix
* things, so Vector2.angle will have a URL #vector2-angle.
* @param {Object} externalTypeURLs - Keys should be type names NOT included in the same documentation output, and
* values should be URLs for those types.
* @returns {Object} - With indexHTML and contentHTML fields, both strings of HTML.
*/
function documentationToHTML( doc, baseName, typeNames, localTypeIds, externalTypeURLs ) {
let indexHTML = '';
let contentHTML = '';
// Initialize typeURLs for the output
typeURLs = {};
Object.keys( externalTypeURLs ).forEach( typeId => {
typeURLs[ typeId ] = externalTypeURLs[ typeId ];
} );
Object.keys( localTypeIds ).forEach( typeId => {
typeURLs[ typeId ] = `#${localTypeIds[ typeId ]}`;
} );
const baseURL = typeURLs[ baseName ];
indexHTML += `<a class="navlink" href="${baseURL}" data-toggle="collapse" data-target="#collapse-${baseName}" onclick="$( '.collapse.in' ).collapse( 'toggle' ); return true;">${baseName}</a><br>\n`;
indexHTML += `<div id="collapse-${baseName}" class="collapse">\n`;
contentHTML += `<h3 id="${baseURL.slice( 1 )}" class="section">${baseName}</h3>\n`;
contentHTML += descriptionHTML( doc.topLevelComment.description );
typeNames.forEach( typeName => {
const baseObject = doc[ typeName ];
const baseURLPrefix = `${localTypeIds[ typeName ]}-`;
// constructor
if ( baseObject.type === 'type' ) {
// Add a target for #-links if we aren't the baseName.
if ( typeName !== baseName ) {
contentHTML += `<div id="${baseURLPrefix.slice( 0, baseURLPrefix.length - 1 )}"></div>`;
}
let constructorLine = typeName + inlineParameterList( baseObject.comment );
if ( baseObject.supertype ) {
constructorLine += ` <span class="inherit">extends ${typeString( baseObject.supertype )}</span>`;
}
contentHTML += `<h4 id="${baseURLPrefix}constructor" class="section">${constructorLine}</h4>`;
contentHTML += descriptionHTML( baseObject.comment.description );
contentHTML += parameterDetailsList( baseObject.comment );
}
const staticProperties = baseObject.staticProperties || baseObject.properties || [];
const staticNames = staticProperties.map( prop => prop.name ).sort();
staticNames.forEach( name => {
const object = nameLookup( staticProperties, name );
indexHTML += `<a class="sublink" href="#${baseURLPrefix}${object.name}">${object.name}</a><br>`;
let typeLine = `<span class="entryName">${typeName}.${object.name}</span>`;
typeLine += inlineParameterList( object );
typeLine += returnOrConstant( object );
contentHTML += `<h5 id="${baseURLPrefix}${object.name}" class="section">${typeLine}</h5>`;
if ( object.description ) {
contentHTML += descriptionHTML( object.description );
}
contentHTML += parameterDetailsList( object );
} );
if ( baseObject.type === 'type' ) {
const constructorNames = baseObject.constructorProperties.map( prop => prop.name ).sort();
constructorNames.forEach( name => {
const object = nameLookup( baseObject.constructorProperties, name );
indexHTML += `<a class="sublink" href="#${baseURLPrefix}${object.name}">${object.name}</a><br>`;
let typeLine = `<span class="entryName">${object.name}</span>`;
typeLine += ` <span class="property">${typeString( object.type )}</span>`;
contentHTML += `<h5 id="${baseURLPrefix}${object.name}" class="section">${typeLine}</h5>`;
if ( object.description ) {
contentHTML += descriptionHTML( object.description );
}
} );
}
if ( baseObject.type === 'type' ) {
const instanceNames = baseObject.instanceProperties.map( prop => prop.name ).sort();
instanceNames.forEach( name => {
const object = nameLookup( baseObject.instanceProperties, name );
indexHTML += `<a class="sublink" href="#${baseURLPrefix}${object.name}">${object.name}</a><br>`;
let typeLine = `<span class="entryName">${object.name}</span>`;
if ( object.explicitGetName ) {
typeLine += ` <span class="property">${typeString( object.returns.type )}</span>`;
typeLine += ` <span class="entryName explicitSetterGetter">${object.explicitGetName}`;
}
if ( object.explicitSetName ) {
typeLine += ` <span class="property">${typeString( object.returns.type )}</span>`;
typeLine += ` <span class="entryName explicitSetterGetter">${object.explicitSetName}`;
}
typeLine += inlineParameterList( object );
typeLine += returnOrConstant( object );
if ( object.explicitSetName || object.explicitGetName ) {
typeLine += '</span>';
}
contentHTML += `<h5 id="${baseURLPrefix}${object.name}" class="section">${typeLine}</h5>`;
contentHTML += descriptionHTML( object.description );
contentHTML += parameterDetailsList( object );
} );
}
} );
indexHTML += '</div>';
return {
indexHTML: indexHTML,
contentHTML: contentHTML
};
}
// Node.js-compatible definition
if ( typeof module !== 'undefined' ) {
module.exports = documentationToHTML;
}
// Browser direct definition (for testing)
if ( typeof window !== 'undefined' ) {
window.documentationToHTML = documentationToHTML;
}
} )();
|
var webpack = require('webpack');
module.exports = {
entry: './src/index.js',
module: {
loaders: [
{
test: /\.jsx?$/,
loader: 'babel-loader',
exclude: /node_modules/
},
]
},
externals: {
'react': 'React',
'react-dom': 'ReactDOM',
},
output: {
filename: 'dist/react-sanfona.js',
libraryTarget: 'umd',
library: 'ReactSanfona'
},
plugins: [
new webpack.optimize.DedupePlugin()
],
resolve: {
extensions: ['.jsx', '.js']
}
};
|
/* eslint-disable no-unused-expressions */
import {describe, it} from 'mocha';
import {expect} from 'chai';
import isString from '../../../src/utils/is-string';
describe('isstring', () => {
it('should return true if value is a string', () => {
expect(isString('ABC')).to.equal(true);
expect(isString(new String('def'))).to.equal(true);
});
it('should return false if value is not a string', () => {
expect(isString(['foo'])).to.equal(false);
expect(isString(function () {})).to.equal(false);
expect(isString(101)).to.equal(false);
expect(isString({})).to.equal(false);
expect(isString(/re/)).to.equal(false);
expect(isString(true)).to.equal(false);
expect(isString(null)).to.equal(false);
expect(isString(undefined)).to.equal(false);
expect(isString(new Number(101))).to.equal(false);
});
});
|
/*
*
* ViewSubreddits actions
*
*/
import {
DEFAULT_ACTION,
} from './constants';
export function defaultAction() {
return {
type: DEFAULT_ACTION,
};
}
|
var http = require("http").createServer(handler);
var io = require("socket.io").listen(http);
var fs = require("fs");
var firmata = require("firmata");
console.log("Start the code");
var board = new firmata.Board("/dev/ttyACM0", function(){ // ACM Abstract Control Model for serial communication with Arduino (could be USB)
console.log("Connecting to Arduino");
board.pinMode(0, board.MODES.ANALOG);
board.pinMode(1, board.MODES.ANALOG);
board.pinMode(2, board.MODES.OUTPUT);
board.pinMode(3, board.MODES.PWM);
board.pinMode(4, board.MODES.OUTPUT);
});
function handler(req,res){
fs.readFile(__dirname + "/ex16.html",
function(err, data){
if(err){
res.writeHead(500, {"Content-Type": "text/plain"});
return res.end("Error loading html page.");
}
res.writeHead(200);
res.end(data);
})
}
var desiredValue = 0;
var actualValue = 0;
var Kp = 0.55;
var Ki = 0.008;
var Kd = 0.15;
var factor = 0.3;
var pwm = 0;
var pwmLimit = 254;
var err = 0;
var errSum = 0;
var dErr = 0;
var lastErr = 0;
var controlAlgorithmStartedFlag = 0;
var intervalCtrl;
http.listen(8080);
var sendValueViaSocket = function(){};
var sendStaticMsgViaSocket = function(){};
board.on("ready", function(){
board.analogRead(0, function(value){
desiredValue = value;
});
board.analogRead(1, function(value){
actualValue = value;
});
io.sockets.on("connection", function(socket){
socket.emit("messageToClient", "Srv connected, brb OK");
socket.emit("staticMsgToClient", "Server connected, board ready.");
setInterval(sendValues, 40, socket);
socket.on("startControlAlgorithm", function(numberOfControlAlgorithm){
startControlAlgorithm(numberOfControlAlgorithm);
});
socket.on("stopControlAlgorithm", function(){
stopControlAlgorithm();
});
sendValueViaSocket = function (value) {
io.sockets.emit("messageToClient", value);
}
sendStaticMsgViaSocket = function (value) {
io.sockets.emit("staticMsgToClient", value);
}
});
});
function controlAlgorithm (parameters) {
if (parameters.ctrlAlgNo == 1) {
pwm = parameters.pCoeff*(desiredValue-actualValue);
if(pwm > pwmLimit) {pwm = pwmLimit};
if(pwm < -pwmLimit) {pwm = -pwmLimit};
if (pwm > 0) {board.digitalWrite(2,1); board.digitalWrite(4,0);};
if (pwm < 0) {board.digitalWrite(2,0); board.digitalWrite(4,1);};
board.analogWrite(3, Math.abs(pwm));
console.log(Math.round(pwm));
}
if (parameters.ctrlAlgNo == 2) {
err = desiredValue - actualValue;
errSum += err;
dErr = err - lastErr;
pwm = parameters.Kp1*err + parameters.Ki1*errSum + parameters.Kd1*dErr;
lastErr = err;
if(pwm > pwmLimit){pwm = pwmLimit};
if(pwm < -pwmLimit){pwm = -pwmLimit};
if(pwm > 0){board.digitalWrite(2, 1); board.digitalWrite(4, 0);};
if(pwm < 0){board.digitalWrite(2, 0); board.digitalWrite(4, 1);};
board.analogWrite(3, Math.abs(pwm));
}
if (parameters.ctrlAlgNo == 3) {
err = desiredValue - actualValue;
errSum += err;
dErr = err - lastErr;
pwm = parameters.Kp2*err + parameters.Ki2*errSum + parameters.Kd2*dErr;
lastErr = err;
if(pwm > pwmLimit){pwm = pwmLimit};
if(pwm < -pwmLimit){pwm = -pwmLimit};
if(pwm > 0){board.digitalWrite(2, 1); board.digitalWrite(4, 0);};
if(pwm < 0){board.digitalWrite(2, 0); board.digitalWrite(4, 1);};
board.analogWrite(3, Math.abs(pwm));
}
}
function startControlAlgorithm (parameters) {
if(controlAlgorithmStartedFlag == 0){
controlAlgorithmStartedFlag = 1;
intervalCtrl = setInterval(function() {controlAlgorithm(parameters); }, 30);
console.log("Control algorithm " + parameters.ctrlAlgNo + " started");
sendStaticMsgViaSocket("Control algorithm " + parameters.ctrlAlgNo + " started | " + json2txt(parameters));
}
}
function stopControlAlgorithm(){
clearInterval(intervalCtrl);
board.analogWrite(3, 0);
err=0;
errSum=0;
dErr=0;
lastErr=0;
controlAlgorithmStartedFlag = 0;
pwm = 0;
console.log("ctrlAlg STOPPED");
sendStaticMsgViaSocket("Stop");
}
function sendValues(socket){
socket.emit("clientReadValues",
{
"desiredValue": desiredValue,
"actualValue": actualValue,
"pwm": pwm
});
}
function json2txt(obj){
var txt = '';
var recurse = function(_obj) {
if ('object' != typeof(_obj)) {
txt += ' = ' + _obj + '\n';
}
else {
for (var key in _obj) {
if (_obj.hasOwnProperty(key)) {
txt += '.' + key;
recurse(_obj[key]);
}
}
}
}
recurse(obj);
return txt;
}
|
const express = require('express');
const logger = require('morgan');
const path = require('path');
const favicon = require('serve-favicon');
const cookieParser = require('cookie-parser');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const index = require('./routes/index');
const users = require('./routes/users');
const bookmarks = require('./routes/bookmarks.js');
const app = express();
const options = { promiseLibrary: require('bluebird') };
const mongodbUri = 'mongodb://admin:admin@ds143449.mlab.com:43449/fem';
// Configure conenction URL (only needs to happen once per app)
mongoose.connect(mongodbUri, options)
.then(() => console.log('connection succesful'))
.catch((err) => console.error(err));
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json({type:'appplication/vnd.api+json'}));
app.use(cookieParser());
app.use(morgan(':remote-addr - :remote-user [:date[clf]] ":method :url HTTP/:http-version" :status :res[content-length] :response-time ms'));
app.use(express.static(path.resolve(__dirname, '..', 'build')));
app.use(express.static(path.join(__dirname, 'stylesheets')));
app.use('/', index);
app.use('/users', users);
app.use('/bookmarks', bookmarks);
// 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 handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
app.get('*', (req, res) => {
res.sendFile(path.resolve(__dirname, '..', 'build', 'index.html'));
});
module.exports = app;
|
angular.module('chatApp.socket', [])
.factory('socket', function ($rootScope) {
var socket = io.connect();
function applyWrap(fn, scope) {
return function () {
var arg = [].slice.call(arguments);
scope.$apply(function () {
fn.apply(null, arg);
});
}
}
socket.ngOn = function (name, cb, scope) {
scope = scope || $rootScope;
var listener = applyWrap(cb, scope);
socket.on(name, listener);
scope.$on('$destroy', function() {
socket.removeListener(name, listener);
});
};
socket.ngEmit = function () {
var args, last
scope = $rootScope;
args = [].slice.call(arguments);
last = args.length - 1;
// if last argument is scope
if (args[last].$root) {
scope = args.splice(last)[0];
last--;
}
if (typeof args[last] === 'function') {
args[last] = applyWrap(args[last], scope);
}
socket.emit.apply(socket, args);
};
return socket;
})
|
version https://git-lfs.github.com/spec/v1
oid sha256:1ac41a50b126bf190db7fe147d285e0c66f52f009fa01202c919b3b363dd83a4
size 2507
|
/**
* @author delirium
*/
/**
* Basada en Prototype JavaScript framework, version 1.4.0
* para mas detalles, http://prototype.conio.net/
*
* Atajo para document.getElementById().
* @name $()
* @param {String, Array} ... uno o mas ids.
* @return {Array} Regresa un array del elemento(s) correspondientes as id(s) especificados.
*/
function $() {
var elements = new Array();
for (var i = 0; i < arguments.length; i++) {
var element = arguments[i];
if (typeof element == 'string'){
element = document.getElementById(element);
}
if (arguments.length == 1){
return element;
}
elements.push(element);
}
return elements;
}
function $TagNames(list,obj) {
if (!obj) var obj = document;
var tagNames = list.split(',');
var resultArray = new Array();
for (var i=0;i<tagNames.length;i++){
var tags = obj.getElementsByTagName(tagNames[i]);
for (var j=0;j<tags.length;j++){
resultArray.push(tags[j]);
}
}
var testNode = new Array();
testNode = resultArray[0];
if(typeof testNode == "undefined"){
return resultArray;
}
if (typeof testNode.sourceIndex != "undefined"){
resultArray.sort(function (a,b) {
return a.sourceIndex - b.sourceIndex;
});
}
else if (testNode.compareDocumentPosition){
resultArray.sort(function (a,b) {
return 3 - (a.compareDocumentPosition(b) & 6);
});
}
return resultArray;
}
function $value(id){
return $(id).value;
}
function $hide(){
for (var i = 0; i < arguments.length; i++) {
var element = arguments[i];
if (typeof element == 'string') {
element = $(element);
}
if(isNull(element)){
return false;
}
element.old_display = element.style.display!='' ? element.style.display : 'block';
element.style.display = 'none';
}
return true;
}
function $show(){
for (var i = 0; i < arguments.length; i++) {
var element = arguments[i];
if (typeof element == 'string') {
element = $(element);
}
if(isNull(element)){
return false;
}
element.style.display = '';
}
}
function $toggle(){
for (var i = 0; i < arguments.length; i++) {
var element = arguments[i];
if (typeof element == 'string') {
element = $(element);
}
if(isNull(element)){
return false;
}
element.style.display = element.style.display!='none' ? 'none' : '';
}
return true;
}
/**
* Converts the argument "iterable" into an Array object.
* @name $A()
* @param {Object} iterable Object to be converted to an Array.
* @return {Array} Returns an Array.
*/
var $A = Array.from = function(iterable) {
if (!iterable) return [];
if (iterable.toArray) {
return iterable.toArray();
} else {
var results = [];
for (var i = 0; i < iterable.length; i++)
results.push(iterable[i]);
return results;
}
}
Function.prototype.bind = function() {
var __method = this,
args = $A(arguments),
object = args.shift();
return function() {
return __method.apply(object, args.concat($A(arguments)));
}
}
function isset(obj){
return typeof obj=="undefined";
}
function isNull(val){
return (val==null);
}
// REmover espacios a la izquierda
function LTrim( value ) {
var re = /\s*((\S+\s*)*)/;
return value.replace(re, "$1");
}
// remover espacios a la derecha
function RTrim( value ) {
var re = /((\s*\S+)*)\s*/;
return value.replace(re, "$1");
}
// Remover espacios en blanco.
function trim( value ) {
return LTrim(RTrim(value));
}
function validate(data,type){
if(!type){
return [true,''];
}
for(x=0;x<type.length;x++){
switch(type[x]){
case "noempty":
if(trim(data)==""){
return [false,'%VALIDA_NO_PUEDE_ESTAR_VACIO%'];
}
break;
case "nospaces":
if(data.indexOf(" ")>-1){
return [false,'%VALIDA_NO_ESPACIOS%'];
}
break;
case "username":
if(trim(data)==""){
return [true,''];
}
re = /^\w+$/;
if(!re.test(data)) {
return [false, '%VALIDA_USUARIO_NO_ESPACIOS_NO_ESPECIALES%'];
}
break;
case "currency":
if(trim(data)==""){
return [true,''];
}
var OK = /^[0-9][0-9]{0,2}(,?[0-9]{3})*(\.[0-9]+)?$/.test(data);
if(!OK){
return [false, '%VALIDA_SOLO_MONEDA%'];
}
break;
case "number":
case "solonumeros":
if(trim(data)==""){
return [true,''];
}
var OK = /^[0-9][0-9]{0,2}(,?[0-9]{3})*(\.[0-9]+)?$/.test(data);
if(!OK){
return [false, '%VALIDA_SOLO_NUMEROS%'];
}
/*
if(isNaN(data)){
return [false,'%VALIDA_SOLO_NUMEROS%'];
}
*/
break;
case "noidzero":
if(trim(data)=="" || isNaN(data)){
return [true,''];
}
if(data==0){
return [false,'%VALIDA_SELECCIONE_OPCION%'];
}
break;
case "date":
case "fecha":
if(trim(data)==""){
return [true,''];
}
var V, DObj = NaN;
data=data.replace(/\//g,"-");
V = data.match(/^(\d\d)-(\d\d)-(\d{4})$/);
if (V) {
V = (DObj = new Date(V[3], --V[2], V[1])).getMonth() == V[2];
}
if(V=="null"){
V=false;
}
if(!V){
return [false, '%VALIDA_FECHA%.'];
}
break;
case "hora":
case "time":
if(trim(data)==""){
return [true,''];
}
var OK = /^\d{1,2}:\d{2}(\s)?([ap]m)?([AP]M)?$/.test(data);
if(!OK){
return [false, '%VALIDA_HORA%'];
}
break;
case "mysqldate":
case "fechamysql":
if(trim(data)==""){
return [true,''];
}
var V, DObj = NaN;
data=data.replace(/\//g,"-");
V = data.match(/^(\d{4})-(\d\d)-(\d\d)$/);
if (V) {
V = (DObj = new Date(V[1], --V[2], V[3])).getMonth() == V[2];
}
if(V=="null"){
V=false;
}
if(!V){
return [false, '%VALIDA_FECHA%'];
}
break;
case "email":
if(trim(data)==""){
return [true,''];
}
var emailReg = "^[\\w-_\.]*[\\w-_\.]\@[\\w]\.+[\\w]+[\\w]$";
var regex = new RegExp(emailReg);
var OKemail = regex.test(data);
if(!OKemail){
return [false, '%VALIDA_EMAIL%'];
}
break;
default:
validate_opt=type[x].split(",");
if(validate_opt.length>1){
if(validate_opt.length > 2){
fix_opt = type[x].split(",");
fix_opt.splice(0,1);
fix_opt = fix_opt.join();
validate_opt[1] = fix_opt.replace(/\$|\,/g,'');
//alert(validate_opt[1]);
//validate_opt[0] = opt;
}
try{
validate_to=eval(validate_opt[1].replace(/\,/g,''));
}catch(e){
validate_to=validate_opt[1];
}
switch(validate_opt[0]){
case ">":
case "gt":
validate_to=validate_to.toString().replace(/\$|\,/g,'');
data=data.toString().replace(/\$|\,/g,'');
if(!(Number(data)>validate_to)){
return [false,'%VALIDA_DATO_MAYOR% '+ validate_to +' .'];
}
break;
case ">=":
case "gteq":
validate_to=validate_to.toString().replace(/\$|\,/g,'');
data=data.toString().replace(/\$|\,/g,'');
if(!(Number(data)>=validate_to)){
return [false,'%VALIDA_MAYOR_IGUAL% '+ validate_to +' .'];
}
break;
case "<":
case "lt":
validate_to=validate_to.toString().replace(/\$|\,/g,'');
data=data.toString().replace(/\$|\,/g,'');
if(Number(data)>=validate_to ){
return [false,'%VALIDA_MENOR% '+ validate_to +' .'];
}
break;
case "<=":
case "lteq":
validate_to=validate_to.toString().replace(/\$|\,/g,'');
data=data.toString().replace(/\$|\,/g,'');
if(Number(data)>validate_to ){
return [false,'%VALIDA_MENOR_IGUAL% '+ validate_to +' .'];
}
break;
case "=":
case "eq":
if(!(data==validate_to)){
return [false,'%VALIDA_IGUAL% '+ validate_to +' .'];
}
break;
}
}
break;
}
}
return [true,''];
}
function validateForm(id){
var form=$(id);
var elements = form.elements;
var opts="";
for(var j=0;j<elements.length;j++){
var validar=null;
try{
validar=elements[j].getAttribute('validate').split("|");
}catch(x){}
if(opts!=''){
opts+="&";
}
switch(elements[j].type){
case "checkbox":
if(elements[j].checked){
opts+=elements[j].id+'='+elements[j].value;
}
break;
case "radio":
if(elements[j].checked){
opts+=elements[j].id+'='+elements[j].value;
}
break;
case "select":
var sel=elements[j];
if(elements[j].checked){
opts+=sel.id+'='+sel.options[sel.selectedIndex].value;
}
break;
default:
opts+=elements[j].id+'='+elements[j].value;
break;
}
var valida_result=validate(elements[j].value,validar);
if(!valida_result[0]){
alert(valida_result[1]);
elements[j].normal_border_color=elements[j].style.borderColor;
elements[j].style.borderColor='red';
elements[j].focus();
return false;
}else{
try{
elements[j].style.borderColor=elements[j].normal_border_color;
}catch(fsbc){}
}
}
return true;
}
function validateDiv(id){
var div=$(id);
var elements=$TagNames("input,select,textarea",div);
var opts="";
for(var j=0;j<elements.length;j++){
var validar=null;
try{
validar=elements[j].getAttribute('validate').split("|");
}catch(x){}
if(opts!=''){
opts+="&";
}
switch(elements[j].type){
case "checkbox":
if(elements[j].checked){
opts+=elements[j].id+'='+elements[j].value;
}
break;
case "radio":
if(elements[j].checked){
opts+=elements[j].id+'='+elements[j].value;
}
break;
case "select":
var sel=elements[j];
if(elements[j].checked){
opts+=sel.id+'='+sel.options[sel.selectedIndex].value;
}
break;
default:
opts+=elements[j].id+'='+elements[j].value;
break;
}
var valida_result=validate(elements[j].value,validar);
if(!valida_result[0]){
alert(valida_result[1]);
elements[j].normal_border_color=elements[j].style.borderColor;
elements[j].style.borderColor='red';
elements[j].focus();
return false;
}else{
try{
elements[j].style.borderColor=elements[j].normal_border_color;
}catch(fsbc){}
}
}
return true;
}
function bind(el, func){
return function() { func.call(el); }
}
function parseJson(jsonString){
return eval("("+jsonString+")");
}
function loadcssfile(filename){
var timestamp = new Date();
var fileref=document.createElement("link");
fileref.setAttribute("rel", "stylesheet");
fileref.setAttribute("type", "text/css");
fileref.setAttribute("href", filename+'?uid='+timestamp.getTime());
fileref.id=filename;
if($(filename)!=null){
$(filename).parentNode.replaceChild(fileref,$(filename));
}else{
if (typeof fileref != "undefined") {
document.getElementsByTagName("head")[0].appendChild(fileref);
}
}
}
function loadjsfile(filename){
var timestamp = new Date();
var fileref=document.createElement("script");
fileref.setAttribute("type", "text/javascript");
fileref.setAttribute("src", filename+'?uid='+timestamp.getTime());
fileref.id=filename;
if($(filename)!=null){
$(filename).parentNode.replaceChild(fileref,$(filename));
}else{
if (typeof fileref != "undefined") {
document.getElementsByTagName("head")[0].appendChild(fileref);
}
}
}
function form2query(form_id){
var elements = $(form_id).elements;
var opts="";
for(var j=0;j<elements.length;j++){
if(opts!=''){
opts+="&";
}
switch(elements[j].type){
case "checkbox":
if(elements[j].checked){
opts+=elements[j].id+'='+encode(elements[j].value);
}
break;
case "radio":
if(elements[j].checked){
opts+=elements[j].id+'='+encode(elements[j].value);
}
break;
case "select":
var sel=elements[j];
if(elements[j].checked){
opts+=sel.id+'='+encode(sel.options[sel.selectedIndex].value);
}
break;
default:
//opts+=elements[j].id+'='+encodeURIComponent(elements[j].value);
opts+=elements[j].id+'='+encode(elements[j].value);
break;
}
}
return opts;
}
function div2query(div_id){
var elements = $TagNames("input,textarea,checkbox,radio,select",$(div_id));
var opts="";
for(var j=0;j<elements.length;j++){
if(opts!=''){
opts+="&";
}
switch(elements[j].type){
case "checkbox":
if(elements[j].checked){
opts+=elements[j].id+'='+encode(elements[j].value);
}
break;
case "radio":
if(elements[j].checked){
opts+=elements[j].id+'='+encode(elements[j].value);
}
break;
case "select":
var sel=elements[j];
if(elements[j].checked){
opts+=sel.id+'='+encode(sel.options[sel.selectedIndex].value);
}
break;
default:
//opts+=elements[j].id+'='+encodeURIComponent(elements[j].value);
opts+=elements[j].id+'='+encode(elements[j].value);
break;
}
}
return opts;
}
function div2obj(div_id){
objs = $TagNames("input,textarea,checkbox,radio,select",$(div_id));
return objs;
}
//This prototype is provided by the Mozilla foundation and
//is distributed under the MIT license.
//http://www.ibiblio.org/pub/Linux/LICENSES/mit.license
if (!Array.prototype.filter)
{
Array.prototype.filter = function(fun /*, thisp*/)
{
var len = this.length;
if (typeof fun != "function")
throw new TypeError();
var res = new Array();
var thisp = arguments[1];
for (var i = 0; i < len; i++)
{
if (i in this)
{
var val = this[i]; // in case fun mutates this
if (fun.call(thisp, val, i, this))
res.push(val);
}
}
return res;
};
}
function encode(str){
if( typeof(str) == 'undefined' ){
str="";
}
str = str.replace(/\+/g,String.fromCharCode(8));
str = escape(str);
str = str.replace(/\%20/g,"+");
str = str.replace(/\%08/g,"%2B");
return str;
}
function decode(str) {
str = str.replace(/\+/g, ' ');
str = unescape(str);
return str;
}
function send_form(form){
var form = $(form);
var old_action = form.action;
form.action = 'raw.php?do='+form.getAttribute('_do').replace( /"/g, '' );
form.submit();
form.action = old_action;
}
function toNumber(str){
return Number(str.replace(/[^0-9\.]+/g,""));
}
function formatNumber(str, cents) {
num = str.toString().replace(/\$|\,/g,'');
if(isNaN(num)){
num = "0";
}
sign = (num == (num = Math.abs(num)));
num = Math.floor(num*100+0.50000000001);
cents = num%100;
num = Math.floor(num/100).toString();
if(cents<10){
cents = "0" + cents;
}
for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++){
num = num.substring(0,num.length-(4*i+3))+','+
num.substring(num.length-(4*i+3));
}
if(cents > 0){
return (((sign)?'':'-') + '$ ' + num + '.' + cents);
}else{
return (((sign)?'':'-') + '' + num);
}
}
function date2mysql(dtm_fecha){
if(dtm_fecha == ''){
return '';
}
var fecha = dtm_fecha.replace('-','/');
fecha = fecha.split('/');
fecha_mysql = fecha[2] + '/' + fecha[1] + '/' + fecha[0];
return fecha_mysql;
}
|
var mFichadas = require('../models/mFichadas');
var mAyuda = require('../models/mAyuda');
var mEmple = require('../models/mEmple');
var mSectores = require('../models/mSectores');
var mRelojes = require('../models/mRelojes');
module.exports = {
getLista: getLista,
getFichadas: getFichadas,
getVer: getVer
};
function changeDate(date){
// input: dd/mm/yyyy
fechaus = date.substring(6,10) + "/" + date.substring(3,5) + "/" + date.substring(0,2);
return fechaus;
// output: yyyy/mm/dd
}
function getLista(req, res) {
//req.session.nromenu = 11;
//mAyuda.getAyudaTexto(req.session.nromenu, function (ayuda){
mFichadas.getLastFicId(function (lastficid){
console.log(lastficid)
if(lastficid[0].maxfic_id == null)
lastficid = 0;
else
lastficid = lastficid[0].maxfic_id;
console.log(lastficid)
mFichadas.getLatestFic(lastficid, function (latestfic){
console.log(latestfic.length)
for (var i = 0; i < latestfic.length; i++ ){
mFichadas.insert(latestfic[i], function (){
console.log(i)
});
}
});
});
res.render('fichadaslista', {
pagename: 'Lista de Fichadas'
});
//});
}
function getFichadas(req, res){
params = req.params;
fecha= params.fecha;
fecha = changeDate(fecha);
mFichadas.getFichadas(fecha, function (fichadas){
console.log(fichadas)
res.send(fichadas);
});
}
function getAyuda(req, res){
params = req.params;
id = params.id;
mAyuda.getAyuda(id, function (ayuda){
res.send(ayuda);
});
}
function getVer(req, res){
params = req.params;
reloj = params.reloj;
fecha = params.fecha;
fecha = changeDate(fecha);
mFichadas.getFichada(reloj, fecha, function (fichada){
mEmple.getAllActivos(function (emples){
mSectores.getAllActivos(function (sectores){
mRelojes.getAll(function (relojes){
res.render("fichadasver", {
pagename: "Detalles de Fichada",
fichada: fichada,
relojes: relojes,
sectores: sectores,
emples: emples
});
});
});
});
});
}
|
'use strict';
angular.module('poslGodNew', [])
.controller('poslgodNewCtrl', function ($scope, $routeParams, $modal, $log, $location, $route, $modalInstance ) {
$scope.ok = function () {
$modalInstance.close({'selectedPoslGod':$scope.selectedPoslGod,
'action':'save'});
};
$scope.cancel = function () {
$modalInstance.dismiss('cancel');
};
$scope.selektujPreduzece = function (invoiceItem, size) {
var modalInstance = $modal.open({
templateUrl: 'views/preduzece-modal.html',
controller: 'preduzecaModalCtrl',
size: size,
scope: $scope ,
resolve: {
invoiceItem: function () {
return $scope.invoiceItem;
}
}
});
modalInstance.result.then(function (data) {
var selectedPreduzece = data.selectedPreduzece;
//ako stavka fakture nema id i ako je akcija 'save' znaci da je nova i dodaje se u listu. ako ima, svakako se manja u listi
if( data.action==='save')
$scope.selectedPoslGod.preduzece = selectedPreduzece;
},
function (response) {
if (response.status === 500) {
$scope.greska = "greska";
}
$route.reload();
//ako stavka treba da se obrise izbaci se iz niza
}, function () {
$log.info('Modal dismissed at: ' + new Date());
});}
});
|
import SuggestPage from './SuggestPage'
export default SuggestPage
|
var connectIP = $("#mainIP").html();
var ip =connectIP.split("|")[0];
var socketUrl=connectIP.split("|")[1];
// 主监听socket 用来控制 次监听socket
var mainSocket='';
var mainUrl= socketUrl +'mainsocket';
// 次监听socket
var socket = '';
var url = socketUrl+'tugofwar';
var host= window.location.host;
var wsCtor = window['MozWebSocket'] ? MozWebSocket : WebSocket;
var socket = new wsCtor(url);//, 'echo-protocol'
$(function() {
listen();
})
function listen() {
//打开连接时触发
socket.onopen = function() {
//log('OPEN: ' + socket.protocol);
};
//关闭连接时触发
socket.onclose = function(evt) {
//log('CLOSE: ' + evt);
};
//连接错误时触发
socket.onerror = function(evt) {
//log('CLOSE: ' + evt.code + ', ' + evt.reason);
};
};
//先判断设备是否支持HTML5摇一摇功能
if (window.DeviceMotionEvent) {
//获取移动速度,得到device移动时相对之前某个时间的差值比
window.addEventListener('devicemotion', deviceMotionHandler, false);
}else{
alert('您好,你目前所用的设置好像不支持重力感应哦!');
}
//设置临界值,这个值可根据自己的需求进行设定,默认就3000也差不多了
var shakeThreshold = 3000;
//设置最后更新时间,用于对比
var lastUpdate = 0;
//设置位置速率
var curShakeX=curShakeY=curShakeZ=lastShakeX=lastShakeY=lastShakeZ=0;
function deviceMotionHandler(event){
//获得重力加速
var acceleration =event.accelerationIncludingGravity;
//获得当前时间戳
var curTime = new Date().getTime();
if ((curTime - lastUpdate)> 100) {
//时间差
var diffTime = curTime -lastUpdate;
lastUpdate = curTime;
//x轴加速度
curShakeX = acceleration.x;
//y轴加速度
curShakeY = acceleration.y;
//z轴加速度
curShakeZ = acceleration.z;
var speed = Math.abs(curShakeX + curShakeY + curShakeZ - lastShakeX - lastShakeY - lastShakeZ) / diffTime * 10000;
if (speed > shakeThreshold) {
//TODO 相关方法,比如:
socket.send("1");
//播放音效
shakeAudio.play();
//播放动画
$('.shake_box').addClass('shake_box_focus');
clearTimeout(shakeTimeout);
var shakeTimeout = setTimeout(function(){
$('.shake_box').removeClass('shake_box_focus');
},1000)
}
lastShakeX = curShakeX;
lastShakeY = curShakeY;
lastShakeZ = curShakeZ;
}
}
//预加摇一摇声音
var shakeAudio = new Audio();
shakeAudio.src = '../../sound/shake_sound.mp3';
var shake_options = {
preload : 'auto'
}
for(var key in shake_options){
if(shake_options.hasOwnProperty(key) && (key in shakeAudio)){
shakeAudio[key] = shake_options[key];
}
}
|
'use strict';
// Init the application configuration module for AngularJS application
var ApplicationConfiguration = (function() {
// Init module configuration options
var applicationModuleName = 'mhacks2014';
var applicationModuleVendorDependencies = ['ngResource', 'ngCookies', 'ngAnimate', 'ngTouch', 'ngSanitize', 'ui.router', 'ui.bootstrap', 'ui.utils'];
// Add a new vertical module
var registerModule = function(moduleName, dependencies) {
// Create angular module
angular.module(moduleName, dependencies || []);
// Add the module to the AngularJS configuration file
angular.module(applicationModuleName).requires.push(moduleName);
};
return {
applicationModuleName: applicationModuleName,
applicationModuleVendorDependencies: applicationModuleVendorDependencies,
registerModule: registerModule
};
})();
|
'use strict';
var path = require('path');
var gulp = require('gulp');
var eslint = require('gulp-eslint');
var excludeGitignore = require('gulp-exclude-gitignore');
var mocha = require('gulp-mocha');
var istanbul = require('gulp-istanbul');
var nsp = require('gulp-nsp');
var plumber = require('gulp-plumber');
var coveralls = require('gulp-coveralls');
gulp.task('static', function () {
return gulp.src('**/*.js')
.pipe(excludeGitignore());
//.pipe(eslint())
//.pipe(eslint.format())
//.pipe(eslint.failAfterError());
});
//gulp.task('nsp', function (cb) {
// nsp('package.json', cb);
//});
gulp.task('pre-test', function () {
return gulp.src('lib/**/*.js')
.pipe(istanbul({
includeUntested: true
}))
.pipe(istanbul.hookRequire());
});
gulp.task('test', ['pre-test'], function (cb) {
var mochaErr;
gulp.src('test/**/*.js')
.pipe(plumber())
.pipe(mocha({reporter: 'spec'}))
.on('error', function (err) {
mochaErr = err;
console.error(err);
})
.pipe(istanbul.writeReports())
.on('end', function () {
cb(mochaErr);
});
});
gulp.task('coveralls', ['test'], function () {
if (!process.env.CI) {
return;
}
return gulp.src(path.join(__dirname, 'coverage/lcov.info'))
.pipe(coveralls());
});
gulp.task('prepublish', [/*'nsp'*/]);
gulp.task('default', ['static', 'test', 'coveralls']);
|
'use strict';
var angular = require('angular'),
removeFailedLocationLookups = require('./remove-failed-location-lookups');
module.exports = angular.module('app').factory('predefinedLocationsForecastService',
function ($http) {
var cachedWeatherForecastsPromise,
cachedWeatherForecasts;
cachedWeatherForecastsPromise = $http.get('/api/forecast/predefined/location/all')
.then(function (forecasts) {
cachedWeatherForecasts = removeFailedLocationLookups(forecasts.data);
}, function () {
console.error('Lookup of \'predefined locations forecast\' failed');
});
return {
forecastPromise: cachedWeatherForecastsPromise,
getAll: function () {
return cachedWeatherForecasts;
}
};
});
|
var platform = tabris.device.get("platform").toLowerCase();
function getIcon(name, size) {
var path = 'images/icons/' + platform + '/';
size = size || Math.floor( tabris.device.get("scaleFactor") );
//console.log(path + name + '@' + size + 'x.png');
return path + name + '@' + size + 'x.png';
};
function getIconSrc(name, size) {
size = size || Math.min(Math.floor( tabris.device.get("scaleFactor") ) , 2);
var uri = getIcon(name,size);
return {src: uri, scale: size * 2}
};
module.exports = {
getIcon : getIcon,
getIconSrc: getIconSrc
}
|
// karma config info: http://karma-runner.github.io/0.12/config/configuration-file.html
module.exports = function(config) {
function isCoverage(argument) {
return argument === '--coverage';
}
// possible values: 'dots', 'progress', 'junit', 'growl', 'coverage'
var reporters = ['spec'];
if(process.argv.some(isCoverage)){
reporters.push('coverage');
}
var testConfig = {
// If browser does not capture in given timeout [ms], kill it
captureTimeout: 60000,
// How long will Karma wait for a message from a browser before disconnecting from it (in ms)
browserNoActivityTimeout: 60000,
// enable / disable colors in the output (reporters and logs)
colors: true,
// web server port
port: 9876,
files: [
'./specs_support/spec_helper.js',
//'./js/**/*.spec.js' // Use webpack to build each test individually. If changed here, match the change in preprocessors
'./webpack.tests.js' // More performant but tests cannot be run individually
],
// Transpile tests with the karma-webpack plugin
preprocessors: {
//'./js/**/*.spec.js': ['webpack', 'sourcemap'] // Use webpack to build each test individually. If changed here, match the change in files
'./webpack.tests.js': ['webpack', 'sourcemap'] // More performant but tests cannot be run individually
},
// Run the tests using any of the following browsers
// - Chrome npm install --save-dev karma-chrome-launcher
// - ChromeCanary
// - Firefox npm install --save-dev karma-firefox-launcher
// - Opera npm install --save-dev karma-opera-launcher
// - Safari npm install --save-dev karma-safari-launcher (only Mac)
// - PhantomJS npm install --save-dev karma-phantomjs-launcher
// - IE npm install karma-ie-launcher (only Windows)
browsers: ['Chrome'],
// Exit the test runner as well when the test suite returns.
singleRun: false,
// enable / disable watching file and executing tests whenever any file changes
autoWatch: true,
// Use jasmine as the test framework
frameworks: ['jasmine-ajax', 'jasmine'],
reporters: reporters,
// karma-webpack configuration. Load and transpile js and jsx files.
// Use istanbul-transformer post loader to generate code coverage report.
webpack: {
devtool: 'eval',
module: {
loaders: [
{ test: /\.js$/, exclude: /node_modules/, loader: "babel-loader?stage=0" },
{ test: /\.jsx?$/, exclude: /node_modules/, loader: "babel-loader?stage=0" }
]
},
resolve: {
extensions: ['', '.js', '.jsx'],
modulesDirectories: ["node_modules", "web_modules", "vendor"]
}
},
// Reduce the noise to the console
webpackMiddleware: {
noInfo: true,
stats: {
colors: true
}
}
};
// Generate code coverage report if --coverage is specified
if(process.argv.some(isCoverage)) {
// Generate a code coverage report using `lcov` format. Result will be output to coverage/lcov.info
// run using `npm coveralls`
testConfig['webpack']['module']['postLoaders'] = [{
test: /\.jsx?$/,
exclude: /(test|node_modules)\//,
loader: 'istanbul-instrumenter'
}];
testConfig['coverageReporter'] = {
dir: 'coverage/',
reporters: [
{ type: 'lcovonly', subdir: '.', file: 'lcov.info' },
{ type: 'html', subdir: 'html' }
]
};
}
config.set(testConfig);
};
|
module.exports = {
addEmails: () => {}
}
|
/**
* @author Jordi Ros: shine.3p@gmail.com
*
*/
var MEntityManager = MEntityManager || {};
//--------------------------------------------------------------------------------------------------------
// MEntityManager
//--------------------------------------------------------------------------------------------------------
MEntityManager.create = function(world, params) {
var module = Module.create(world);
module.params = params;
module.entities = [];
module._isDead = function(entity) { return entity.dead; };
module.count = function() { return this.entities.length; }
// Init
module.init = function() {
for (var i = 0; i < this.entities.length; i++) {
this.entities[i].init();
}
}
// Reset
module.reset = function() {
if (this.params.resetClear) {
this.clear();
}
for (var i = 0; i < this.entities.length; i++) {
this.entities[i].reset();
}
// Remove dead entities
DeleteArray(this.entities, this._isDead);
}
// Update
module.update = function(time, delta) {
for (var i = 0; i < this.entities.length; i++) {
this.entities[i].update(time, delta);
}
// Remove dead entities
DeleteArray(this.entities, this._isDead);
}
// Render
module.render = function(fade) {
for (var i = 0; i < this.entities.length; i++) {
this.entities[i].render(fade);
}
}
// Clear
module.clear = function() {
for (var i = 0; i < this.entities.length; i++) {
this.entities[i] = null;
}
this.entities.length = 0;
}
// Destroy
module.destroy = function() {
this.clear();
this.entities = null;
}
// Add module
module.add = function(entity) {
this.entities.push(entity);
return entity;
}
return module;
}
|
'use strict'
const EventHandler = require('./EventHandler')
class ChannelEventHandler extends EventHandler {
getUser (evt) { return evt.message.author }
getGuild (evt) { return evt.message.guild }
getChannel (evt) { return evt.message.channel }
}
module.exports = ChannelEventHandler
|
/**
* The MIT License (MIT)
*
* Copyright (c) 2015 Arnaud Dezandee
*
* Authors:
* Arnaud Dezandee <dezandee.arnaud@gmail.com>
*/
var debug = require('debug')('mink:findStep');
var _ = require('lodash');
var LANG_WORDS = ['Given', 'When', 'Then', 'And', 'But', '*'];
// Sanitize input and trim first word if Gherkin lang
function trim(str) {
var input = str.replace(/\s\s+/g, ' ').trim();
var words = input.split(' ');
if (_.contains(LANG_WORDS, _.first(words))) {
return words.slice(1).join(' ');
}
return input;
}
/**
* Find a matching registered step and build a stepObj from Mink context
* @param {String} input
*/
module.exports = function findStep(input) {
var text = trim(input);
var step = _.find(this.steps, function(minkStep) {
return text.match(minkStep.pattern);
});
debug(text, '=>', step && step.pattern || null);
if (!step) {
throw new Error('Could not find matching step for text: ' + text);
}
return _.assign(step, {
input: text,
args: text.match(step.pattern).slice(1)
});
};
|
import { upload } from '@qgrid/core';
import { readFile } from './read';
export class ImportPlugin {
constructor(model, element) {
this.model = model;
this.element = element;
}
upload() {
upload(this.element);
}
load(e) {
const { files } = e.target;
for (let file of files) {
const reader = new FileReader();
reader.onload = e => readFile(e, file, this.model, this.options);
reader.readAsBinaryString(file);
}
}
}
|
'use strict';
retrospective.service('retroService', function ($http, $location) {
var service = {};
var url;
service.connect = function() {
if(service.ws) { service.ws.close(); }
var ws = new WebSocket(url);
ws.onopen = function() {};
ws.onerror = function() { service.callback("Failed to open a connection"); }
ws.onmessage = function(message) { service.callback(JSON.parse(message.data)); };
service.ws = ws;
}
service.subscribe = function(callback) { service.callback = callback; }
function setUrl(sufix){
url = "ws://"+$location.host()+":"+$location.port()+"/"+sufix;
}
function getAll() {
return $http.get('/retrospective');
}
function getById(retroId) {
return $http.get('/retrospective/'+retroId);
}
function add(retro) {
return $http.post('/retrospective', retro);
}
function addInput(retroId, input) {
return $http.post('/retrospective/'+retroId+'/input', input);
}
function removeInput(retroId, index){
return $http.delete('/retrospective/'+retroId+'/input/'+index);
}
function addVote(retroId, index){
return $http.get('/retrospective/'+retroId+'/input/'+index+"/vote");
}
return {
getAll : getAll,
getById: getById,
add : add,
addInput : addInput,
removeInput : removeInput,
addVote : addVote,
setUrl : setUrl,
service: service
}
});
|
$( '#watch7-sidebar' ).hide();
|
#! /usr/local/bin/node
require('./dist/app.js');
|
'use strict';
let db = require('../../config/db');
let Todo = db.define('todo', {
id: {
type: db.Sequelize.INTEGER,
primaryKey: true,
autoIncrement: true
},
text: {
type: db.Sequelize.STRING,
}
}, {
timestamps: false
});
module.exports = Todo;
|
(function () {
'use strict';
angular
.module('RetailPartners.authentication.controllers')
.controller('RegisterController', RegisterController);
RegisterController.$inject = ['$location', '$scope', 'Authentication'];
/**
* @namespace RegisterController
*/
function RegisterController($location, $scope, Authentication) {
var vm = this;
vm.register = register;
activate();
function activate() {
// If the user is authenticated, they should not be here.
if (Authentication.isAuthenticated()) {
$location.url('/emd');
}
}
/**
* @name register
* @desc Register a new user
* @memberOf RetailPartners.authentication.controllers.RegisterController
*/
function register() {
console.log(vm.email)
Authentication.register(vm.email, vm.password, vm.username);
}
}
})();
|
/*
Copyright (c) 2012 Nevins Bartolomeo <nevins.bartolomeo@gmail.com>
Copyright (c) 2012 Shane Girish <shaneGirish@gmail.com>
Copyright (c) 2013 Daniel Wirtz <dcode@dcode.io>
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. The name of the author may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* @license bcrypt.js (c) 2013 Daniel Wirtz <dcode@dcode.io>
* Released under the Apache License, Version 2.0
* see: https://github.com/dcodeIO/bcrypt.js for details
*/
(function(global) {
/**
* @type {Array.<string>}
* @const
* @private
**/
var BASE64_CODE = ['.', '/', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I',
'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V',
'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i',
'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8',
'9'];
/**
* @type {Array.<number>}
* @const
* @private
**/
var BASE64_INDEX = [-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 1,
54, 55, 56, 57, 58, 59, 60, 61, 62, 63, -1, -1, -1, -1, -1, -1, -1,
2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20,
21, 22, 23, 24, 25, 26, 27, -1, -1, -1, -1, -1, -1, 28, 29, 30, 31,
32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48,
49, 50, 51, 52, 53, -1, -1, -1, -1, -1];
/**
* Length-delimited base64 encoder and decoder.
* @type {Object.<string,function(string, number)>}
* @private
*/
var base64 = {};
/**
* Encodes a byte array to base64 with up to len bytes of input.
* @param {Array.<number>} b Byte array
* @param {number} len Maximum input length
* @returns {string}
* @private
*/
base64.encode = function(b, len) {
var off = 0;
var rs = [];
var c1;
var c2;
if (len <= 0 || len > b.length) {
throw(new Error("Invalid 'len': "+len));
}
while (off < len) {
c1 = b[off++] & 0xff;
rs.push(BASE64_CODE[(c1 >> 2) & 0x3f]);
c1 = (c1 & 0x03) << 4;
if (off >= len) {
rs.push(BASE64_CODE[c1 & 0x3f]);
break;
}
c2 = b[off++] & 0xff;
c1 |= (c2 >> 4) & 0x0f;
rs.push(BASE64_CODE[c1 & 0x3f]);
c1 = (c2 & 0x0f) << 2;
if (off >= len) {
rs.push(BASE64_CODE[c1 & 0x3f]);
break;
}
c2 = b[off++] & 0xff;
c1 |= (c2 >> 6) & 0x03;
rs.push(BASE64_CODE[c1 & 0x3f]);
rs.push(BASE64_CODE[c2 & 0x3f]);
}
return rs.join('');
};
/**
* Decodes a base64 encoded string to up to len bytes of output.
* @param {string} s String to decode
* @param {number} len Maximum output length
* @returns {Array.<number>}
* @private
*/
base64.decode = function(s, len) {
var off = 0;
var slen = s.length;
var olen = 0;
var rs = [];
var c1, c2, c3, c4, o, code;
if (len <= 0) throw(new Error("Illegal 'len': "+len));
while (off < slen - 1 && olen < len) {
code = s.charCodeAt(off++);
c1 = code < BASE64_INDEX.length ? BASE64_INDEX[code] : -1;
code = s.charCodeAt(off++);
c2 = code < BASE64_INDEX.length ? BASE64_INDEX[code] : -1;
if (c1 == -1 || c2 == -1) {
break;
}
o = (c1 << 2) >>> 0;
o |= (c2 & 0x30) >> 4;
rs.push(String.fromCharCode(o));
if (++olen >= len || off >= slen) {
break;
}
code = s.charCodeAt(off++);
c3 = code < BASE64_INDEX.length ? BASE64_INDEX[code] : -1;
if (c3 == -1) {
break;
}
o = ((c2 & 0x0f) << 4) >>> 0;
o |= (c3 & 0x3c) >> 2;
rs.push(String.fromCharCode(o));
if (++olen >= len || off >= slen) {
break;
}
code = s.charCodeAt(off++);
c4 = code < BASE64_INDEX.length ? BASE64_INDEX[code] : -1;
o = ((c3 & 0x03) << 6) >>> 0;
o |= c4;
rs.push(String.fromCharCode(o));
++olen;
}
var res = [];
for (off = 0; off<olen; off++) {
res.push(rs[off].charCodeAt(0));
}
return res;
};
/**
* bcrypt namespace.
* @type {Object.<string,*>}
*/
var bcrypt = {};
/**
* @type {number}
* @const
* @private
*/
var BCRYPT_SALT_LEN = 16;
/**
* @type {number}
* @const
* @private
*/
var GENSALT_DEFAULT_LOG2_ROUNDS = 10;
/**
* @type {number}
* @const
* @private
*/
var BLOWFISH_NUM_ROUNDS = 16;
/**
* @type {number}
* @const
* @private
*/
var MAX_EXECUTION_TIME = 100;
/**
* @type {Array.<number>}
* @const
* @private
*/
var P_ORIG = [
0x243f6a88, 0x85a308d3, 0x13198a2e, 0x03707344, 0xa4093822,
0x299f31d0, 0x082efa98, 0xec4e6c89, 0x452821e6, 0x38d01377,
0xbe5466cf, 0x34e90c6c, 0xc0ac29b7, 0xc97c50dd, 0x3f84d5b5,
0xb5470917, 0x9216d5d9, 0x8979fb1b
];
/**
* @type {Array.<number>}
* @const
* @private
*/
var S_ORIG = [
0xd1310ba6, 0x98dfb5ac, 0x2ffd72db, 0xd01adfb7, 0xb8e1afed,
0x6a267e96, 0xba7c9045, 0xf12c7f99, 0x24a19947, 0xb3916cf7,
0x0801f2e2, 0x858efc16, 0x636920d8, 0x71574e69, 0xa458fea3,
0xf4933d7e, 0x0d95748f, 0x728eb658, 0x718bcd58, 0x82154aee,
0x7b54a41d, 0xc25a59b5, 0x9c30d539, 0x2af26013, 0xc5d1b023,
0x286085f0, 0xca417918, 0xb8db38ef, 0x8e79dcb0, 0x603a180e,
0x6c9e0e8b, 0xb01e8a3e, 0xd71577c1, 0xbd314b27, 0x78af2fda,
0x55605c60, 0xe65525f3, 0xaa55ab94, 0x57489862, 0x63e81440,
0x55ca396a, 0x2aab10b6, 0xb4cc5c34, 0x1141e8ce, 0xa15486af,
0x7c72e993, 0xb3ee1411, 0x636fbc2a, 0x2ba9c55d, 0x741831f6,
0xce5c3e16, 0x9b87931e, 0xafd6ba33, 0x6c24cf5c, 0x7a325381,
0x28958677, 0x3b8f4898, 0x6b4bb9af, 0xc4bfe81b, 0x66282193,
0x61d809cc, 0xfb21a991, 0x487cac60, 0x5dec8032, 0xef845d5d,
0xe98575b1, 0xdc262302, 0xeb651b88, 0x23893e81, 0xd396acc5,
0x0f6d6ff3, 0x83f44239, 0x2e0b4482, 0xa4842004, 0x69c8f04a,
0x9e1f9b5e, 0x21c66842, 0xf6e96c9a, 0x670c9c61, 0xabd388f0,
0x6a51a0d2, 0xd8542f68, 0x960fa728, 0xab5133a3, 0x6eef0b6c,
0x137a3be4, 0xba3bf050, 0x7efb2a98, 0xa1f1651d, 0x39af0176,
0x66ca593e, 0x82430e88, 0x8cee8619, 0x456f9fb4, 0x7d84a5c3,
0x3b8b5ebe, 0xe06f75d8, 0x85c12073, 0x401a449f, 0x56c16aa6,
0x4ed3aa62, 0x363f7706, 0x1bfedf72, 0x429b023d, 0x37d0d724,
0xd00a1248, 0xdb0fead3, 0x49f1c09b, 0x075372c9, 0x80991b7b,
0x25d479d8, 0xf6e8def7, 0xe3fe501a, 0xb6794c3b, 0x976ce0bd,
0x04c006ba, 0xc1a94fb6, 0x409f60c4, 0x5e5c9ec2, 0x196a2463,
0x68fb6faf, 0x3e6c53b5, 0x1339b2eb, 0x3b52ec6f, 0x6dfc511f,
0x9b30952c, 0xcc814544, 0xaf5ebd09, 0xbee3d004, 0xde334afd,
0x660f2807, 0x192e4bb3, 0xc0cba857, 0x45c8740f, 0xd20b5f39,
0xb9d3fbdb, 0x5579c0bd, 0x1a60320a, 0xd6a100c6, 0x402c7279,
0x679f25fe, 0xfb1fa3cc, 0x8ea5e9f8, 0xdb3222f8, 0x3c7516df,
0xfd616b15, 0x2f501ec8, 0xad0552ab, 0x323db5fa, 0xfd238760,
0x53317b48, 0x3e00df82, 0x9e5c57bb, 0xca6f8ca0, 0x1a87562e,
0xdf1769db, 0xd542a8f6, 0x287effc3, 0xac6732c6, 0x8c4f5573,
0x695b27b0, 0xbbca58c8, 0xe1ffa35d, 0xb8f011a0, 0x10fa3d98,
0xfd2183b8, 0x4afcb56c, 0x2dd1d35b, 0x9a53e479, 0xb6f84565,
0xd28e49bc, 0x4bfb9790, 0xe1ddf2da, 0xa4cb7e33, 0x62fb1341,
0xcee4c6e8, 0xef20cada, 0x36774c01, 0xd07e9efe, 0x2bf11fb4,
0x95dbda4d, 0xae909198, 0xeaad8e71, 0x6b93d5a0, 0xd08ed1d0,
0xafc725e0, 0x8e3c5b2f, 0x8e7594b7, 0x8ff6e2fb, 0xf2122b64,
0x8888b812, 0x900df01c, 0x4fad5ea0, 0x688fc31c, 0xd1cff191,
0xb3a8c1ad, 0x2f2f2218, 0xbe0e1777, 0xea752dfe, 0x8b021fa1,
0xe5a0cc0f, 0xb56f74e8, 0x18acf3d6, 0xce89e299, 0xb4a84fe0,
0xfd13e0b7, 0x7cc43b81, 0xd2ada8d9, 0x165fa266, 0x80957705,
0x93cc7314, 0x211a1477, 0xe6ad2065, 0x77b5fa86, 0xc75442f5,
0xfb9d35cf, 0xebcdaf0c, 0x7b3e89a0, 0xd6411bd3, 0xae1e7e49,
0x00250e2d, 0x2071b35e, 0x226800bb, 0x57b8e0af, 0x2464369b,
0xf009b91e, 0x5563911d, 0x59dfa6aa, 0x78c14389, 0xd95a537f,
0x207d5ba2, 0x02e5b9c5, 0x83260376, 0x6295cfa9, 0x11c81968,
0x4e734a41, 0xb3472dca, 0x7b14a94a, 0x1b510052, 0x9a532915,
0xd60f573f, 0xbc9bc6e4, 0x2b60a476, 0x81e67400, 0x08ba6fb5,
0x571be91f, 0xf296ec6b, 0x2a0dd915, 0xb6636521, 0xe7b9f9b6,
0xff34052e, 0xc5855664, 0x53b02d5d, 0xa99f8fa1, 0x08ba4799,
0x6e85076a, 0x4b7a70e9, 0xb5b32944, 0xdb75092e, 0xc4192623,
0xad6ea6b0, 0x49a7df7d, 0x9cee60b8, 0x8fedb266, 0xecaa8c71,
0x699a17ff, 0x5664526c, 0xc2b19ee1, 0x193602a5, 0x75094c29,
0xa0591340, 0xe4183a3e, 0x3f54989a, 0x5b429d65, 0x6b8fe4d6,
0x99f73fd6, 0xa1d29c07, 0xefe830f5, 0x4d2d38e6, 0xf0255dc1,
0x4cdd2086, 0x8470eb26, 0x6382e9c6, 0x021ecc5e, 0x09686b3f,
0x3ebaefc9, 0x3c971814, 0x6b6a70a1, 0x687f3584, 0x52a0e286,
0xb79c5305, 0xaa500737, 0x3e07841c, 0x7fdeae5c, 0x8e7d44ec,
0x5716f2b8, 0xb03ada37, 0xf0500c0d, 0xf01c1f04, 0x0200b3ff,
0xae0cf51a, 0x3cb574b2, 0x25837a58, 0xdc0921bd, 0xd19113f9,
0x7ca92ff6, 0x94324773, 0x22f54701, 0x3ae5e581, 0x37c2dadc,
0xc8b57634, 0x9af3dda7, 0xa9446146, 0x0fd0030e, 0xecc8c73e,
0xa4751e41, 0xe238cd99, 0x3bea0e2f, 0x3280bba1, 0x183eb331,
0x4e548b38, 0x4f6db908, 0x6f420d03, 0xf60a04bf, 0x2cb81290,
0x24977c79, 0x5679b072, 0xbcaf89af, 0xde9a771f, 0xd9930810,
0xb38bae12, 0xdccf3f2e, 0x5512721f, 0x2e6b7124, 0x501adde6,
0x9f84cd87, 0x7a584718, 0x7408da17, 0xbc9f9abc, 0xe94b7d8c,
0xec7aec3a, 0xdb851dfa, 0x63094366, 0xc464c3d2, 0xef1c1847,
0x3215d908, 0xdd433b37, 0x24c2ba16, 0x12a14d43, 0x2a65c451,
0x50940002, 0x133ae4dd, 0x71dff89e, 0x10314e55, 0x81ac77d6,
0x5f11199b, 0x043556f1, 0xd7a3c76b, 0x3c11183b, 0x5924a509,
0xf28fe6ed, 0x97f1fbfa, 0x9ebabf2c, 0x1e153c6e, 0x86e34570,
0xeae96fb1, 0x860e5e0a, 0x5a3e2ab3, 0x771fe71c, 0x4e3d06fa,
0x2965dcb9, 0x99e71d0f, 0x803e89d6, 0x5266c825, 0x2e4cc978,
0x9c10b36a, 0xc6150eba, 0x94e2ea78, 0xa5fc3c53, 0x1e0a2df4,
0xf2f74ea7, 0x361d2b3d, 0x1939260f, 0x19c27960, 0x5223a708,
0xf71312b6, 0xebadfe6e, 0xeac31f66, 0xe3bc4595, 0xa67bc883,
0xb17f37d1, 0x018cff28, 0xc332ddef, 0xbe6c5aa5, 0x65582185,
0x68ab9802, 0xeecea50f, 0xdb2f953b, 0x2aef7dad, 0x5b6e2f84,
0x1521b628, 0x29076170, 0xecdd4775, 0x619f1510, 0x13cca830,
0xeb61bd96, 0x0334fe1e, 0xaa0363cf, 0xb5735c90, 0x4c70a239,
0xd59e9e0b, 0xcbaade14, 0xeecc86bc, 0x60622ca7, 0x9cab5cab,
0xb2f3846e, 0x648b1eaf, 0x19bdf0ca, 0xa02369b9, 0x655abb50,
0x40685a32, 0x3c2ab4b3, 0x319ee9d5, 0xc021b8f7, 0x9b540b19,
0x875fa099, 0x95f7997e, 0x623d7da8, 0xf837889a, 0x97e32d77,
0x11ed935f, 0x16681281, 0x0e358829, 0xc7e61fd6, 0x96dedfa1,
0x7858ba99, 0x57f584a5, 0x1b227263, 0x9b83c3ff, 0x1ac24696,
0xcdb30aeb, 0x532e3054, 0x8fd948e4, 0x6dbc3128, 0x58ebf2ef,
0x34c6ffea, 0xfe28ed61, 0xee7c3c73, 0x5d4a14d9, 0xe864b7e3,
0x42105d14, 0x203e13e0, 0x45eee2b6, 0xa3aaabea, 0xdb6c4f15,
0xfacb4fd0, 0xc742f442, 0xef6abbb5, 0x654f3b1d, 0x41cd2105,
0xd81e799e, 0x86854dc7, 0xe44b476a, 0x3d816250, 0xcf62a1f2,
0x5b8d2646, 0xfc8883a0, 0xc1c7b6a3, 0x7f1524c3, 0x69cb7492,
0x47848a0b, 0x5692b285, 0x095bbf00, 0xad19489d, 0x1462b174,
0x23820e00, 0x58428d2a, 0x0c55f5ea, 0x1dadf43e, 0x233f7061,
0x3372f092, 0x8d937e41, 0xd65fecf1, 0x6c223bdb, 0x7cde3759,
0xcbee7460, 0x4085f2a7, 0xce77326e, 0xa6078084, 0x19f8509e,
0xe8efd855, 0x61d99735, 0xa969a7aa, 0xc50c06c2, 0x5a04abfc,
0x800bcadc, 0x9e447a2e, 0xc3453484, 0xfdd56705, 0x0e1e9ec9,
0xdb73dbd3, 0x105588cd, 0x675fda79, 0xe3674340, 0xc5c43465,
0x713e38d8, 0x3d28f89e, 0xf16dff20, 0x153e21e7, 0x8fb03d4a,
0xe6e39f2b, 0xdb83adf7, 0xe93d5a68, 0x948140f7, 0xf64c261c,
0x94692934, 0x411520f7, 0x7602d4f7, 0xbcf46b2e, 0xd4a20068,
0xd4082471, 0x3320f46a, 0x43b7d4b7, 0x500061af, 0x1e39f62e,
0x97244546, 0x14214f74, 0xbf8b8840, 0x4d95fc1d, 0x96b591af,
0x70f4ddd3, 0x66a02f45, 0xbfbc09ec, 0x03bd9785, 0x7fac6dd0,
0x31cb8504, 0x96eb27b3, 0x55fd3941, 0xda2547e6, 0xabca0a9a,
0x28507825, 0x530429f4, 0x0a2c86da, 0xe9b66dfb, 0x68dc1462,
0xd7486900, 0x680ec0a4, 0x27a18dee, 0x4f3ffea2, 0xe887ad8c,
0xb58ce006, 0x7af4d6b6, 0xaace1e7c, 0xd3375fec, 0xce78a399,
0x406b2a42, 0x20fe9e35, 0xd9f385b9, 0xee39d7ab, 0x3b124e8b,
0x1dc9faf7, 0x4b6d1856, 0x26a36631, 0xeae397b2, 0x3a6efa74,
0xdd5b4332, 0x6841e7f7, 0xca7820fb, 0xfb0af54e, 0xd8feb397,
0x454056ac, 0xba489527, 0x55533a3a, 0x20838d87, 0xfe6ba9b7,
0xd096954b, 0x55a867bc, 0xa1159a58, 0xcca92963, 0x99e1db33,
0xa62a4a56, 0x3f3125f9, 0x5ef47e1c, 0x9029317c, 0xfdf8e802,
0x04272f70, 0x80bb155c, 0x05282ce3, 0x95c11548, 0xe4c66d22,
0x48c1133f, 0xc70f86dc, 0x07f9c9ee, 0x41041f0f, 0x404779a4,
0x5d886e17, 0x325f51eb, 0xd59bc0d1, 0xf2bcc18f, 0x41113564,
0x257b7834, 0x602a9c60, 0xdff8e8a3, 0x1f636c1b, 0x0e12b4c2,
0x02e1329e, 0xaf664fd1, 0xcad18115, 0x6b2395e0, 0x333e92e1,
0x3b240b62, 0xeebeb922, 0x85b2a20e, 0xe6ba0d99, 0xde720c8c,
0x2da2f728, 0xd0127845, 0x95b794fd, 0x647d0862, 0xe7ccf5f0,
0x5449a36f, 0x877d48fa, 0xc39dfd27, 0xf33e8d1e, 0x0a476341,
0x992eff74, 0x3a6f6eab, 0xf4f8fd37, 0xa812dc60, 0xa1ebddf8,
0x991be14c, 0xdb6e6b0d, 0xc67b5510, 0x6d672c37, 0x2765d43b,
0xdcd0e804, 0xf1290dc7, 0xcc00ffa3, 0xb5390f92, 0x690fed0b,
0x667b9ffb, 0xcedb7d9c, 0xa091cf0b, 0xd9155ea3, 0xbb132f88,
0x515bad24, 0x7b9479bf, 0x763bd6eb, 0x37392eb3, 0xcc115979,
0x8026e297, 0xf42e312d, 0x6842ada7, 0xc66a2b3b, 0x12754ccc,
0x782ef11c, 0x6a124237, 0xb79251e7, 0x06a1bbe6, 0x4bfb6350,
0x1a6b1018, 0x11caedfa, 0x3d25bdd8, 0xe2e1c3c9, 0x44421659,
0x0a121386, 0xd90cec6e, 0xd5abea2a, 0x64af674e, 0xda86a85f,
0xbebfe988, 0x64e4c3fe, 0x9dbc8057, 0xf0f7c086, 0x60787bf8,
0x6003604d, 0xd1fd8346, 0xf6381fb0, 0x7745ae04, 0xd736fccc,
0x83426b33, 0xf01eab71, 0xb0804187, 0x3c005e5f, 0x77a057be,
0xbde8ae24, 0x55464299, 0xbf582e61, 0x4e58f48f, 0xf2ddfda2,
0xf474ef38, 0x8789bdc2, 0x5366f9c3, 0xc8b38e74, 0xb475f255,
0x46fcd9b9, 0x7aeb2661, 0x8b1ddf84, 0x846a0e79, 0x915f95e2,
0x466e598e, 0x20b45770, 0x8cd55591, 0xc902de4c, 0xb90bace1,
0xbb8205d0, 0x11a86248, 0x7574a99e, 0xb77f19b6, 0xe0a9dc09,
0x662d09a1, 0xc4324633, 0xe85a1f02, 0x09f0be8c, 0x4a99a025,
0x1d6efe10, 0x1ab93d1d, 0x0ba5a4df, 0xa186f20f, 0x2868f169,
0xdcb7da83, 0x573906fe, 0xa1e2ce9b, 0x4fcd7f52, 0x50115e01,
0xa70683fa, 0xa002b5c4, 0x0de6d027, 0x9af88c27, 0x773f8641,
0xc3604c06, 0x61a806b5, 0xf0177a28, 0xc0f586e0, 0x006058aa,
0x30dc7d62, 0x11e69ed7, 0x2338ea63, 0x53c2dd94, 0xc2c21634,
0xbbcbee56, 0x90bcb6de, 0xebfc7da1, 0xce591d76, 0x6f05e409,
0x4b7c0188, 0x39720a3d, 0x7c927c24, 0x86e3725f, 0x724d9db9,
0x1ac15bb4, 0xd39eb8fc, 0xed545578, 0x08fca5b5, 0xd83d7cd3,
0x4dad0fc4, 0x1e50ef5e, 0xb161e6f8, 0xa28514d9, 0x6c51133c,
0x6fd5c7e7, 0x56e14ec4, 0x362abfce, 0xddc6c837, 0xd79a3234,
0x92638212, 0x670efa8e, 0x406000e0, 0x3a39ce37, 0xd3faf5cf,
0xabc27737, 0x5ac52d1b, 0x5cb0679e, 0x4fa33742, 0xd3822740,
0x99bc9bbe, 0xd5118e9d, 0xbf0f7315, 0xd62d1c7e, 0xc700c47b,
0xb78c1b6b, 0x21a19045, 0xb26eb1be, 0x6a366eb4, 0x5748ab2f,
0xbc946e79, 0xc6a376d2, 0x6549c2c8, 0x530ff8ee, 0x468dde7d,
0xd5730a1d, 0x4cd04dc6, 0x2939bbdb, 0xa9ba4650, 0xac9526e8,
0xbe5ee304, 0xa1fad5f0, 0x6a2d519a, 0x63ef8ce2, 0x9a86ee22,
0xc089c2b8, 0x43242ef6, 0xa51e03aa, 0x9cf2d0a4, 0x83c061ba,
0x9be96a4d, 0x8fe51550, 0xba645bd6, 0x2826a2f9, 0xa73a3ae1,
0x4ba99586, 0xef5562e9, 0xc72fefd3, 0xf752f7da, 0x3f046f69,
0x77fa0a59, 0x80e4a915, 0x87b08601, 0x9b09e6ad, 0x3b3ee593,
0xe990fd5a, 0x9e34d797, 0x2cf0b7d9, 0x022b8b51, 0x96d5ac3a,
0x017da67d, 0xd1cf3ed6, 0x7c7d2d28, 0x1f9f25cf, 0xadf2b89b,
0x5ad6b472, 0x5a88f54c, 0xe029ac71, 0xe019a5e6, 0x47b0acfd,
0xed93fa9b, 0xe8d3c48d, 0x283b57cc, 0xf8d56629, 0x79132e28,
0x785f0191, 0xed756055, 0xf7960e44, 0xe3d35e8c, 0x15056dd4,
0x88f46dba, 0x03a16125, 0x0564f0bd, 0xc3eb9e15, 0x3c9057a2,
0x97271aec, 0xa93a072a, 0x1b3f6d9b, 0x1e6321f5, 0xf59c66fb,
0x26dcf319, 0x7533d928, 0xb155fdf5, 0x03563482, 0x8aba3cbb,
0x28517711, 0xc20ad9f8, 0xabcc5167, 0xccad925f, 0x4de81751,
0x3830dc8e, 0x379d5862, 0x9320f991, 0xea7a90c2, 0xfb3e7bce,
0x5121ce64, 0x774fbe32, 0xa8b6e37e, 0xc3293d46, 0x48de5369,
0x6413e680, 0xa2ae0810, 0xdd6db224, 0x69852dfd, 0x09072166,
0xb39a460a, 0x6445c0dd, 0x586cdecf, 0x1c20c8ae, 0x5bbef7dd,
0x1b588d40, 0xccd2017f, 0x6bb4e3bb, 0xdda26a7e, 0x3a59ff45,
0x3e350a44, 0xbcb4cdd5, 0x72eacea8, 0xfa6484bb, 0x8d6612ae,
0xbf3c6f47, 0xd29be463, 0x542f5d9e, 0xaec2771b, 0xf64e6370,
0x740e0d8d, 0xe75b1357, 0xf8721671, 0xaf537d5d, 0x4040cb08,
0x4eb4e2cc, 0x34d2466a, 0x0115af84, 0xe1b00428, 0x95983a1d,
0x06b89fb4, 0xce6ea048, 0x6f3f3b82, 0x3520ab82, 0x011a1d4b,
0x277227f8, 0x611560b1, 0xe7933fdc, 0xbb3a792b, 0x344525bd,
0xa08839e1, 0x51ce794b, 0x2f32c9b7, 0xa01fbac9, 0xe01cc87e,
0xbcc7d1f6, 0xcf0111c3, 0xa1e8aac7, 0x1a908749, 0xd44fbd9a,
0xd0dadecb, 0xd50ada38, 0x0339c32a, 0xc6913667, 0x8df9317c,
0xe0b12b4f, 0xf79e59b7, 0x43f5bb3a, 0xf2d519ff, 0x27d9459c,
0xbf97222c, 0x15e6fc2a, 0x0f91fc71, 0x9b941525, 0xfae59361,
0xceb69ceb, 0xc2a86459, 0x12baa8d1, 0xb6c1075e, 0xe3056a0c,
0x10d25065, 0xcb03a442, 0xe0ec6e0e, 0x1698db3b, 0x4c98a0be,
0x3278e964, 0x9f1f9532, 0xe0d392df, 0xd3a0342b, 0x8971f21e,
0x1b0a7441, 0x4ba3348c, 0xc5be7120, 0xc37632d8, 0xdf359f8d,
0x9b992f2e, 0xe60b6f47, 0x0fe3f11d, 0xe54cda54, 0x1edad891,
0xce6279cf, 0xcd3e7e6f, 0x1618b166, 0xfd2c1d05, 0x848fd2c5,
0xf6fb2299, 0xf523f357, 0xa6327623, 0x93a83531, 0x56cccd02,
0xacf08162, 0x5a75ebb5, 0x6e163697, 0x88d273cc, 0xde966292,
0x81b949d0, 0x4c50901b, 0x71c65614, 0xe6c6c7bd, 0x327a140a,
0x45e1d006, 0xc3f27b9a, 0xc9aa53fd, 0x62a80f00, 0xbb25bfe2,
0x35bdd2f6, 0x71126905, 0xb2040222, 0xb6cbcf7c, 0xcd769c2b,
0x53113ec0, 0x1640e3d3, 0x38abbd60, 0x2547adf0, 0xba38209c,
0xf746ce76, 0x77afa1c5, 0x20756060, 0x85cbfe4e, 0x8ae88dd8,
0x7aaaf9b0, 0x4cf9aa7e, 0x1948c25c, 0x02fb8a8c, 0x01c36ae4,
0xd6ebe1f9, 0x90d4f869, 0xa65cdea0, 0x3f09252d, 0xc208e69f,
0xb74e6132, 0xce77e25b, 0x578fdfe3, 0x3ac372e6
];
/**
* @type {Array.<number>}
* @const
* @private
*/
var C_ORIG = [
0x4f727068, 0x65616e42, 0x65686f6c, 0x64657253, 0x63727944,
0x6f756274
];
/**
* @param {Array.<number>} lr
* @param {number} off
* @param {Array.<number>} P
* @param {Array.<number>} S
* @returns {Array.<number>}
* @private
*/
function _encipher(lr, off, P, S) { // This is our bottleneck: 1714/1905 ticks / 90% - see profile.txt
var n;
var l = lr[off];
var r = lr[off + 1];
l ^= P[0];
for (var i=0; i<=BLOWFISH_NUM_ROUNDS-2;) {
// Feistel substitution on left word
n = S[(l >> 24) & 0xff];
n += S[0x100 | ((l >> 16) & 0xff)];
n ^= S[0x200 | ((l >> 8) & 0xff)];
n += S[0x300 | (l & 0xff)];
r ^= n ^ P[++i];
// Feistel substitution on right word
n = S[(r >> 24) & 0xff];
n += S[0x100 | ((r >> 16) & 0xff)];
n ^= S[0x200 | ((r >> 8) & 0xff)];
n += S[0x300 | (r & 0xff)];
l ^= n ^ P[++i];
}
lr[off] = r ^ P[BLOWFISH_NUM_ROUNDS + 1];
lr[off + 1] = l;
return lr;
}
/**
* @param {Array.<number>} data
* @param {number} offp
* @returns {{key: number, offp: number}}
* @private
*/
function _streamtoword(data, offp) {
var i;
var word = 0;
for (i = 0; i < 4; i++) {
word = (word << 8) | (data[offp] & 0xff);
offp = (offp + 1) % data.length;
}
return { key: word, offp: offp };
}
/**
* @param {Array.<number>} key
* @param {Array.<number>} P
* @param {Array.<number>} S
* @private
*/
function _key(key, P, S) {
var offset = 0;
var lr = new Array(0x00000000, 0x00000000);
var plen = P.length;
var slen = S.length;
for (var i = 0; i < plen; i++) {
var sw = _streamtoword(key, offset);
offset = sw.offp;
P[i] = P[i] ^ sw.key;
}
for (i = 0; i < plen; i += 2) {
lr = _encipher(lr, 0, P, S);
P[i] = lr[0];
P[i + 1] = lr[1];
}
for (i = 0; i < slen; i += 2) {
lr = _encipher(lr, 0, P, S);
S[i] = lr[0];
S[i + 1] = lr[1];
}
}
/**
* Expensive key schedule Blowfish.
* @param {Array.<number>} data
* @param {Array.<number>} key
* @param {Array.<number>} P
* @param {Array.<number>} S
* @private
*/
function _ekskey(data, key, P, S) {
var offp = 0;
var lr = new Array(0x00000000, 0x00000000);
var plen = P.length;
var slen = S.length;
var sw;
for (var i = 0; i < plen; i++) {
sw = _streamtoword(key, offp);
offp = sw.offp;
P[i] = P[i] ^ sw.key;
}
offp = 0;
for (i = 0; i < plen; i += 2) {
sw = _streamtoword(data, offp);
offp = sw.offp;
lr[0] ^= sw.key;
sw = _streamtoword(data, offp);
offp = sw.offp;
lr[1] ^= sw.key;
lr = _encipher(lr, 0, P, S);
P[i] = lr[0];
P[i + 1] = lr[1];
}
for (i = 0; i < slen; i += 2) {
sw = _streamtoword(data, offp);
offp = sw.offp;
lr[0] ^= sw.key;
sw = _streamtoword(data, offp);
offp = sw.offp;
lr[1] ^= sw.key;
lr = _encipher(lr, 0, P, S);
S[i] = lr[0];
S[i + 1] = lr[1];
}
}
/**
* Continues with the callback on the next tick.
* @param {function(...[*])} callback Callback to execute
* @private
*/
function _nextTick(callback) {
if (typeof process !== 'undefined' && typeof process.nextTick === 'function') {
process.nextTick(callback);
} else {
setTimeout(callback, 0);
}
}
/**
* Internaly crypts a string.
* @param {Array.<number>} b Bytes to crypt
* @param {Array.<number>} salt Salt bytes to use
* @param {number} rounds Number of rounds
* @param {function(Error, Array.<number>)=} callback Callback receiving the error, if any, and the resulting bytes. If
* omitted, the operation will be performed synchronously.
* @returns {Array.<number>} Resulting bytes or if callback has been omitted, otherwise null
* @private
*/
function _crypt(b, salt, rounds, callback) {
var cdata = C_ORIG.slice();
var clen = cdata.length;
// Validate
if (rounds < 4 || rounds > 31) {
throw(new Error("Illegal number of rounds: "+rounds));
}
if (salt.length != BCRYPT_SALT_LEN) {
throw(new Error("Illegal salt length: "+salt.length+" != "+BCRYPT_SALT_LEN));
}
rounds = 1 << rounds;
var P = P_ORIG.slice();
var S = S_ORIG.slice();
_ekskey(salt, b, P, S);
var i = 0, j;
/**
* Calcualtes the next round.
* @returns {Array.<number>} Resulting array if callback has been omitted, otherwise null
* @private
*/
function next() {
if (i < rounds) {
var start = new Date();
for (; i < rounds;) {
i = i + 1;
_key(b, P, S);
_key(salt, P, S);
if (Date.now() - start > MAX_EXECUTION_TIME) { // TODO (dcode): Is this necessary?
break;
}
}
} else {
for (i = 0; i < 64; i++) {
for (j = 0; j < (clen >> 1); j++) {
_encipher(cdata, j << 1, P, S);
}
}
var ret = [];
for (i = 0; i < clen; i++) {
ret.push(((cdata[i] >> 24) & 0xff) >>> 0);
ret.push(((cdata[i] >> 16) & 0xff) >>> 0);
ret.push(((cdata[i] >> 8) & 0xff) >>> 0);
ret.push((cdata[i] & 0xff) >>> 0);
}
if (callback) {
callback(null, ret);
return null;
} else {
return ret;
}
}
if (callback) {
_nextTick(next);
}
return null;
}
// Async
if (typeof callback !== 'undefined') {
next();
return null;
// Sync
} else {
var res;
while (true) {
if ((res = next()) !== null) {
return res;
}
}
}
}
function _stringToBytes ( str ) {
var ch, st, re = [];
for (var i = 0; i < str.length; i++ ) {
ch = str.charCodeAt(i);
st = [];
do {
st.push( ch & 0xFF );
ch = ch >> 8;
} while (ch);
re = re.concat( st.reverse() );
}
return re;
}
/**
* Internally hashes a string.
* @param {string} s String to hash
* @param {?string} salt Salt to use, actually never null
* @param {function(Error, ?string)=} callback Callback receiving the error, if any, and the resulting hash. If omitted,
* hashing is perormed synchronously.
* @returns {?string} Resulting hash if callback has been omitted, else null
* @private
*/
function _hash(s, salt, callback) {
// Validate the salt
var minor, offset;
if (salt.charAt(0) != '$' || salt.charAt(1) != '2') {
throw(new Error("Invalid salt version: "+salt.substring(0,2)));
}
if (salt.charAt(2) == '$') {
minor = String.fromCharCode(0);
offset = 3;
} else {
minor = salt.charAt(2);
if (minor != 'a' || salt.charAt(3) != '$') {
throw(new Error("Invalid salt revision: "+salt.substring(2,4)));
}
offset = 4;
}
// Extract number of rounds
if (salt.charAt(offset + 2) > '$') {
throw(new Error("Missing salt rounds"));
}
var r1 = parseInt(salt.substring(offset, offset + 1), 10) * 10;
var r2 = parseInt(salt.substring(offset + 1, offset + 2), 10);
var rounds = r1 + r2;
var real_salt = salt.substring(offset + 3, offset + 25);
s += minor >= 'a' ? "\000" : "";
var passwordb = _stringToBytes(s);
var saltb = [];
saltb = base64.decode(real_salt, BCRYPT_SALT_LEN);
/**
* Finishs hashing.
* @param {Array.<number>} bytes Byte array
* @returns {string}
* @private
*/
function finish(bytes) {
var res = [];
res.push("$2");
if (minor >= 'a') res.push(minor);
res.push("$");
if (rounds < 10) res.push("0");
res.push(rounds.toString());
res.push("$");
res.push(base64.encode(saltb, saltb.length));
res.push(base64.encode(bytes, C_ORIG.length * 4 - 1));
return res.join('');
}
// Sync
if (typeof callback == 'undefined') {
return finish(_crypt(passwordb, saltb, rounds));
// Async
} else {
_crypt(passwordb, saltb, rounds, function(err, bytes) {
if (err) {
callback(err, null);
} else {
callback(null, finish(bytes));
}
});
return null;
}
}
/**
* Generates cryptographically secure random bytes.
* @param {number} len Number of bytes to generate
* @returns {Array.<number>}
* @private
*/
function _randomBytes(len) {
// node.js, see: http://nodejs.org/api/crypto.html
if (typeof module !== 'undefined' && module.exports) {
var crypto = require("crypto");
return crypto.randomBytes(len);
// Browser, see: http://www.w3.org/TR/WebCryptoAPI/
} else {
var array = new Uint32Array(len);
if (global.crypto && typeof global.crypto.getRandomValues === 'function') {
global.crypto.getRandomValues(array);
} else if (typeof _getRandomValues === 'function') {
_getRandomValues(array);
} else {
throw(new Error("Failed to generate random values: Web Crypto API not available / no polyfill set"));
}
return Array.prototype.slice.call(array);
}
}
/**
* Internally generates a salt.
* @param {number} rounds Number of rounds to use
* @returns {string} Salt
* @throws {Error} If anything goes wrong
* @private
*/
function _gensalt(rounds) {
rounds = rounds || 10;
if (rounds < 4 || rounds > 31) {
throw(new Error("Illegal number of rounds: "+rounds));
}
var salt = [];
salt.push("$2a$");
if (rounds < GENSALT_DEFAULT_LOG2_ROUNDS) salt.push("0");
salt.push(rounds.toString());
salt.push('$');
try {
salt.push(base64.encode(_randomBytes(BCRYPT_SALT_LEN), BCRYPT_SALT_LEN));
return salt.join('');
} catch(err) {
throw(err);
}
}
// crypto.getRandomValues polyfill to use
var _getRandomValues = null;
/**
* Sets the polyfill that should be used if window.crypto.getRandomValues is not available.
* @param {function(Uint32Array)} getRandomValues The actual implementation
* @expose
*/
bcrypt.setRandomPolyfill = function(getRandomValues) {
_getRandomValues = getRandomValues;
};
/**
* Synchronously generates a salt.
* @param {number=} rounds Number of rounds to use, defaults to 10 if omitted
* @param {number=} seed_length Not supported.
* @returns {string} Resulting salt
* @expose
*/
bcrypt.genSaltSync = function(rounds, seed_length) {
if (!rounds) rounds = 10;
return _gensalt(rounds);
};
/**
* Asynchronously generates a salt.
* @param {(number|function(Error, ?string))=} rounds Number of rounds to use, defaults to 10 if omitted
* @param {(number|function(Error, ?string))=} seed_length Not supported.
* @param {function(Error, ?string)=} callback Callback receiving the error, if any, and the resulting salt
* @expose
*/
bcrypt.genSalt = function(rounds, seed_length, callback) {
if (typeof seed_length == 'function') {
callback = seed_length;
seed_length = -1; // Not supported.
}
var rnd; // Hello closure
if (typeof rounds == 'function') {
callback = rounds;
rnd = GENSALT_DEFAULT_LOG2_ROUNDS;
} else {
rnd = parseInt(rounds, 10);
}
if (typeof callback != 'function') {
throw(new Error("Illegal or missing 'callback': "+callback));
}
_nextTick(function() { // Pretty thin, but salting is fast enough
try {
var res = bcrypt.genSaltSync(rnd);
callback(null, res);
} catch(err) {
callback(err, null);
}
});
};
/**
* Synchronously generates a hash for the given string.
* @param {string} s String to hash
* @param {(number|string)=} salt Salt length to generate or salt to use, default to 10
* @returns {?string} Resulting hash, actually never null
* @expose
*/
bcrypt.hashSync = function(s, salt) {
if (!salt) salt = GENSALT_DEFAULT_LOG2_ROUNDS;
if (typeof salt == 'number') {
salt = bcrypt.genSaltSync(salt);
}
return _hash(s, salt);
};
/**
* Asynchronously generates a hash for the given string.
* @param {string} s String to hash
* @param {number|string} salt Salt length to generate or salt to use
* @param {function(Error, ?string)} callback Callback receiving the error, if any, and the resulting hash
* @expose
*/
bcrypt.hash = function(s, salt, callback) {
if (typeof callback != 'function') {
throw(new Error("Illegal 'callback': "+callback));
}
if (typeof salt == 'number') {
bcrypt.genSalt(salt, function(err, salt) {
_hash(s, salt, callback);
});
} else {
_hash(s, salt, callback);
}
};
/**
* Synchronously tests a string against a hash.
* @param {string} s String to compare
* @param {string} hash Hash to test against
* @returns {boolean} true if matching, otherwise false
* @throws {Error} If an argument is illegal
* @expose
*/
bcrypt.compareSync = function(s, hash) {
if(typeof s != "string" || typeof hash != "string") {
throw(new Error("Illegal argument types: "+(typeof s)+', '+(typeof hash)));
}
if(hash.length != 60) {
throw(new Error("Illegal hash length: "+hash.length+" != 60"));
}
var comp = bcrypt.hashSync(s, hash.substr(0, hash.length-31));
var same = comp.length == hash.length;
var max_length = (comp.length < hash.length) ? comp.length : hash.length;
// to prevent timing attacks, should check entire string
// don't exit after found to be false
for (var i = 0; i < max_length; ++i) {
if (comp.length >= i && hash.length >= i && comp[i] != hash[i]) {
same = false;
}
}
return same;
};
/**
* Asynchronously compares the given data against the given hash.
* @param {string} s Data to compare
* @param {string} hash Data to be compared to
* @param {function(Error, boolean)} callback Callback receiving the error, if any, otherwise the result
* @throws {Error} If the callback argument is invalid
* @expose
*/
bcrypt.compare = function(s, hash, callback) {
if (typeof callback != 'function') {
throw(new Error("Illegal 'callback': "+callback));
}
bcrypt.hash(s, hash.substr(0, 29), function(err, comp) {
callback(err, hash === comp);
});
};
/**
* Gets the number of rounds used to encrypt the specified hash.
* @param {string} hash Hash to extract the used number of rounds from
* @returns {number} Number of rounds used
* @throws {Error} If hash is not a string
* @expose
*/
bcrypt.getRounds = function(hash) {
if(typeof hash != "string") {
throw(new Error("Illegal type of 'hash': "+(typeof hash)));
}
return parseInt(hash.split("$")[2], 10);
};
/**
* Gets the salt portion from a hash.
* @param {string} hash Hash to extract the salt from
* @returns {string} Extracted salt part portion
* @throws {Error} If `hash` is not a string or otherwise invalid
* @expose
*/
bcrypt.getSalt = function(hash) {
if (typeof hash != 'string') {
throw(new Error("Illegal type of 'hash': "+(typeof hash)));
}
if(hash.length != 60) {
throw(new Error("Illegal hash length: "+hash.length+" != 60"));
}
return hash.substring(0, 29);
};
// Enable module loading if available
if (typeof module != 'undefined' && module["exports"]) { // CommonJS
module["exports"] = bcrypt;
} else if (typeof define != 'undefined' && define["amd"]) { // AMD
define("bcrypt", function() { return bcrypt; });
} else { // Shim
if (!global["dcodeIO"]) {
global["dcodeIO"] = {};
}
global["dcodeIO"]["bcrypt"] = bcrypt;
}
})(this);
|
riot.tag2('rg-placeholdit', '<img riot-src="https://placeholdit.imgix.net/~text?bg={opts.placeholdit.background}&txtclr={opts.placeholdit.color}&txt={opts.placeholdit.text}&txtsize={opts.placeholdit.textsize}&w={opts.placeholdit.width}&h={opts.placeholdit.height}&fm={opts.placeholdit.format}">', '', '', function(opts) {
if (!opts.placeholdit) opts.placeholdit = {};
this.on("mount", () => this.update());
this.on('update', () => {
opts.placeholdit.width = opts.placeholdit.width || 450;
opts.placeholdit.height = opts.placeholdit.height || 250;
opts.placeholdit.background = opts.placeholdit.background || '000';
opts.placeholdit.color = opts.placeholdit.color || 'fff';
opts.placeholdit.text = opts.placeholdit.text || `${opts.placeholdit.width} x ${opts.placeholdit.height}`;
opts.placeholdit.textsize = opts.placeholdit.textsize || 30;
opts.placeholdit.format = opts.placeholdit.format || 'png';
});
});
|
"use strict";
var execToHtml = {};
var likeAr = require('like-ar');
var spawn = require("child_process").spawn;
var iconv = require('iconv-lite');
var fs = require('fs-promise');
var readYaml = require('read-yaml-promise');
var MiniTools = require('mini-tools');
var send = require('send');
var serveErr=MiniTools.serveErr;
var IDX_STDOUT = 1;// 001
var IDX_STDERR = 2;// 010
var BITMASK_END = 4;// 100
var Path = require('path');
var winOS = Path.sep==='\\';
function specialReject(message){
var p=Promise.reject(new Error(message));
return {
onLine:function(){ return p; },
then:function(f, fErr){ return p.then(f, fErr); },
'catch':function(fErr){ return p.catch(fErr); }
};
}
execToHtml.commands={
'npm':{shell:true},
'ls':{shell:true, win:'dir/b'},
'echo':{shell:true}
};
execToHtml.localYamlFile = './local-config.yaml';
execToHtml.addLocalCommands = function addLocalCommands(existingCommands) {
return Promise.resolve().then(function() {
return readYaml(execToHtml.localYamlFile);
}).then(function(yamlconf){
var cmds=yamlconf.commands;
if(cmds) {
/*jshint forin: false */
/*eslint-disable guard-for-in */
for(var cmd in cmds) {
existingCommands[cmd] = cmds[cmd];
}
/*jshint forin: true */
/*eslint-enable guard-for-in */
}
return existingCommands;
}).catch(function(){
return false;
});
};
execToHtml.run = function run(commandLines, opts){
if(!opts || !('echo' in opts)){
return specialReject('execToHtml.run ERROR: option echo is mandatory');
}
if(!('buffering' in opts)) {
opts.buffering = true;
}
if(!('error' in opts)) {
opts.error = true;
}
if(typeof commandLines==='string'){
commandLines=[commandLines];
}
var runner={
onLine:function(flush){
return Promise.resolve().then(function() {
if(! execToHtml.extraCommandsLoaded) {
execToHtml.extraCommandsLoaded = true;
return execToHtml.addLocalCommands(execToHtml.commands);
} else {
return true;
}
}).then(function() {
var streamer=function(resolve,reject){
var commandLine=commandLines[0];
commandLines=commandLines.slice(1);
var lineForEmit={origin:'unknown'}; // para que origin esté primero en la lista de propiedades
var commandInfo;
if(typeof commandLine === 'string'){
commandInfo={};
if(commandLine[0]==='!'){
commandInfo.shell=true;
commandLine=commandLine.substr(1);
}
commandInfo.params=commandLine.split(' ');
commandInfo.command=commandInfo.params[0];
commandInfo.params.splice(0, 1);
lineForEmit.text=commandLine;
}else{
commandInfo=commandLine;
lineForEmit.text=[commandLine.command].concat(commandLine.params.map(function(param){
if(/ /.test(param)){
return JSON.stringify(param);
}
return param;
})).join(' ');
}
var infoCommand;
if(!('shell' in commandInfo)){
infoCommand=execToHtml.commands[commandInfo.command];
if(infoCommand){
commandInfo.shell=!!infoCommand.shell;
if(winOS && infoCommand.win){
commandInfo.command=infoCommand.win;
lineForEmit.realCommand=infoCommand.win;
} else if(infoCommand.unix) {
commandInfo.command=infoCommand.unix;
lineForEmit.realCommand=infoCommand.unix;
}
}
}
if(commandInfo.shell){
lineForEmit.origin='shell';
/* coverage depends on OS */
/* istanbul ignore next */
if(winOS){
commandInfo.params.unshift(commandInfo.command);
commandInfo.params.unshift('/c');
commandInfo.command='cmd.exe';
} else {
// Ponemos comillas si hay espacios en el nombre
commandInfo.params = likeAr(commandInfo.params).map(function(e) {
return (e.match(/ /)) ? '"' + e + '"' : e;
});
commandInfo.params = [commandInfo.command+' '+ commandInfo.params.join(' ')];
commandInfo.params.unshift('-c');
commandInfo.command='sh';
}
}else{
lineForEmit.origin='command';
}
var spawnOpts={stdio: [ 'ignore', 'pipe', 'pipe']};
if(opts.cwd){
spawnOpts.cwd=Path.resolve(opts.cwd);
}
if(opts.echo){
flush(lineForEmit);
}
var remainSignals=IDX_STDOUT | IDX_STDERR | BITMASK_END;
var endFunctions={
exit: {resolveOrReject:resolve, flags:BITMASK_END },
error:{resolveOrReject:opts.throwError?reject:resolve , flags:remainSignals}
};
var eventNameForEnd = null;
var resultForEnd = null;
var finalizer=function(bitmask, result, eventName){
if(eventName){
eventNameForEnd = eventName;
resultForEnd = result;
}
remainSignals = remainSignals & ~bitmask;
if(remainSignals){
return;
}
if(executer.buffer && executer.buffer.length) {
flush({origin: executer.origin, text:executer.buffer});
}
if(opts[eventNameForEnd]){
if(resultForEnd===null){
resultForEnd='empty result';
}
flush({origin:eventNameForEnd, text:resultForEnd.toString()});
}
if(!commandLines.length){
endFunctions[eventNameForEnd].resolveOrReject(resultForEnd);
}else{
streamer(resolve,reject);
}
};
var executer=spawn(commandInfo.command, commandInfo.params, spawnOpts);
likeAr({stdout:1, stderr:2}).forEach(function(streamIndex, streamName){
executer.stdio[streamIndex].on('data', function(data){
/* NO BORRAR, QUIZÁS LO NECESITEMOS PARA DEDUCIR encoding
if(opts.encoding && false){
console.log('dentro','français');
['utf8','win1251','latin1','cp437'].forEach(function(encoding){
console.log(encoding, iconv.decode(data,encoding), encoding==opts.encoding, iconv.decode(data,opts.encoding));
});
console.log('saliendo',opts.encoding?iconv.decode(data,opts.encoding):data.toString());
}
*/
var rData = opts.encoding?iconv.decode(data,opts.encoding):data.toString();
if(! opts.buffering) {
flush({origin:streamName, text:rData});
} else {
if(!executer.buffer) {
executer.buffer = '';
executer.origin = streamName;
}
if(streamName !== executer.origin && executer.buffer.length) {
var buffer = executer.buffer;
executer.buffer = '';
flush({origin:executer.origin, text:buffer});
executer.origin = streamName;
}
executer.buffer += rData;
if(executer.buffer.match(/(\r\n|\r(?!\n|$)|\n)/)) {
var buffers = executer.buffer.split(/(\r\n|\r(?!\n|$)|\n)/);
for(var i=0; i<buffers.length-1; i+=2) {
flush({origin:streamName, text:buffers[i]+buffers[i+1]});
}
executer.buffer = buffers[i];
}
}
});
executer.stdio[streamIndex].on('end', function(){
finalizer(streamIndex);
});
});
likeAr(endFunctions).forEach(function(infoEvent, eventName){
executer.on(eventName, function(result){
finalizer(infoEvent.flags,result,eventName);
});
});
};
return new Promise(streamer);
});
}
};
if(opts.collect){
var result={};
return runner.onLine(function(lineInfo){
if(!(lineInfo.origin in result)){
result[lineInfo.origin]='';
}
result[lineInfo.origin]+=lineInfo.text;
}).then(function(exit){
if(exit){
result.exit=exit;
}
return result;
});
}
return runner;
};
execToHtml.actions = {
install:{
prepare:function(opts,projectName){
var dir=opts.baseDir+projectName;
return fs.stat(dir).then(function(stat){
if(!stat.isDirectory()){
throw new Error('invalid project name. Not a Directory');
}
return {runArgs:[[
'git pull',
'npm prune',
'npm install',
'npm test'
],{echo:true, exit:true, cwd:dir}]};
});
}
}
};
execToHtml.middleware = function execToHtmlMiddleware(opts){
return function(req,res,next){
var actionName;
Promise.resolve().then(function(){
var params=req.path.split('/');
actionName=params[1];
if(actionName==='controls'){
var pathFile;
if(params[2]==='resources'){
pathFile='/'+params.slice(3).join('/');
send(req, Path.join(__dirname, pathFile), {}).pipe(res);
}else{
pathFile=Path.resolve(__dirname,'exec-control');
MiniTools.serveJade(pathFile,false)(req,res,next);
}
}else{
var projectName;
return Promise.resolve().then(function(){
if(params.length!==3){
throw new Error('execToHtml.middleware expect /action/name');
}
projectName=params[2];
return execToHtml.actions[actionName].prepare(opts,projectName);
}).then(function(prepared){
if(req.xhr){
res.append('Content-Type', 'application/octet-stream'); // por chrome bug segun: http://stackoverflow.com/questions/3880381/xmlhttprequest-responsetext-while-loading-readystate-3-in-chrome
}
return execToHtml.run.apply(execToHtml,prepared.runArgs).onLine(function(lineInfo){
res.write(JSON.stringify(lineInfo)+'\n');
}).then(function(){
res.end();
});
});
}
}).catch(serveErr(req,res));
};
};
module.exports=execToHtml;
|
function sleep(delay)
{
var start = new Date().getTime();
while (new Date().getTime() < start + delay);
}
var map = null ;
var myMaps = [] ;
var infoW = null ;
var markerClusterer = null;
var myStyles = [{
url: 'img/m1.png',
height: 42,
width: 42
}, {
url: 'img/m2.png',
height: 44,
width: 44
}, {
url: 'img/m3.png',
height: 52,
width: 52
}, {
url: 'img/m4.png',
height: 62,
width: 62
}, {
url: 'img/m5.png',
height: 70,
width: 70
}] ;
function getMinimumArea()
{
var ne = map.getBounds().getNorthEast() ;
var sw = map.getBounds().getSouthWest() ;
var s = sw.lat() - ne.lat() ;
if( s < 0 )
s = -s ;
var a = (s * 20) / $("#map_canvas").height() ;
var path = [
new google.maps.LatLng(sw.lat(),sw.lng()),
new google.maps.LatLng(sw.lat()+a,sw.lng()),
new google.maps.LatLng(sw.lat()+a,sw.lng()+a),
new google.maps.LatLng(sw.lat(),sw.lng()+a),
];
return google.maps.geometry.spherical.computeArea( path ) / 1000000 ;
}
function showElements()
{
document.getElementById("zoomlevel").value = map.getZoom() ;
var bounds = map.getBounds() ;
var ne = bounds.getNorthEast() ;
var sw = bounds.getSouthWest() ;
var minArea = getMinimumArea() ;
var str = "bounds: " + ne.lat() + ',' + ne.lng() + '\n' +
" " + sw.lat() + ',' + sw.lng() + '\n' +
"div height: " + $("#map_canvas").height() + '\n' +
"area: " + minArea + '\n' ;
document.getElementById( "result" ).value = str ;
//simulate read from database
//sleep( 200 ) ;
if (markerClusterer)
markerClusterer.clearMarkers();
var markers = [];
var i ;
var o ;
for( i = 0; i < myMaps.length; ++i )
{
o = myMaps[i].show( map, minArea ) ;
if( o )
markers.push( o ) ;
}
markerClusterer = new MarkerClusterer(map, markers, {
gridSize: 40,
averageCenter: true,
imagePath: "img/m",
styles: myStyles
});
}
function initialize()
{
var homeLocation = new google.maps.LatLng(39.499903,-8.719593)
var mapOptions = {
center: homeLocation,
zoom: 6,
mapTypeId: google.maps.MapTypeId.TERRAIN,
panControl: false,
scaleControl: true,
streetViewControl: false
};
map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
google.maps.event.addListener( map, 'idle', showElements );
infoW = makeInfoWindow() ;
makeMaps( infoW ) ;
}
function showAll()
{
for( i = 0; i < myMaps.length; ++i )
{
myMaps[i].show( map, 1000.0 ) ;
}
}
function hideAll()
{
for( i = 0; i < myMaps.length; ++i )
{
myMaps[i].hide() ;
}
}
function loadGoogleMapsScript()
{
var key = decodeURIComponent((new RegExp('[?|&]key=' + '([^&;]+?)(&|#|;|$)').exec(location.search)||[,""])[1])||""
var keyStr ;
if( key != "" )
keyStr = 'key=' + key + '&' ;
else
keyStr = "" ;
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'http://maps.googleapis.com/maps/api/js?' + keyStr + 'libraries=geometry&callback=initialize';
document.body.appendChild(script);
}
function makeInfoWindow()
{
return new google.maps.InfoWindow({
content: "later"
});
}
function makeMaps( infoW )
{
myMaps = [] ;
var coords ;
var i ;
var j ;
var c ;
for( i = 0; i < mapsInfo.length; ++i )
{
c = mapsInfo[i].coords ;
coords = [] ;
for( j = 0; j < c.length; ++j )
{
coords.push( new google.maps.LatLng( c[j].lng, c[j].lat ) ) ;
}
myMaps.push( new OriMap( mapsInfo[i].name, coords, infoW ) ) ;
}
}
|
'use strict';
const LANG = 'cs_cz';
const BASE_URL = 'http://www.astro.cz/apod';
const handleError = require('../utils/handleError').common;
const notFoundError = require('../utils/handleError').notFound;
const request = require('request');
const cheerio = require('cheerio');
const decoder = require('../utils/utils').decoder;
function craw(baseData, callback) {
let date = baseData.date.replace(/-/g, '').slice(2);
request({
url: `${BASE_URL}/ap${date}.html`,
encoding: null
}, function(error, response, buf) {
if (handleError(error, response)) {
return callback(handleError(error, response));
}
let decoded = decoder(buf);
let $ = cheerio.load(decoded);
let title = $('.apod > header > h1').text().trim();
let explanation = $('article.apod > p').eq(1).text().trim().replace(/\r?\n/g, ' ');
if (!title || !explanation) {
return callback(notFoundError(baseData.date, LANG));
}
baseData.title = title;
baseData.explanation = explanation;
baseData.lang = LANG;
callback(null, baseData);
});
}
module.exports = craw;
|
describe("StateService", function() {
var StateService = require('../services/StateService');
var stateService = new StateService();
var stateAbbrevs = ["AL", "AK", "AZ", "AR", "CA", "CO", "CT", "DE", "FL", "GA", "HI",
"ID", "IL", "IN", "IA", "KS", "KY", "LA", "ME", "MD", "MA", "MI",
"MN", "MS", "MO", "MT", "NE", "NV", "NH", "NJ", "NM", "NY", "NC",
"ND", "OH", "OK", "OR", "PA", "RI", "SC", "SD", "TN", "TX", "UT",
"VT", "VA", "WA", "WV", "WI", "WY"];
var stateNames = ["Alabama", "Alaska", "Arizona", "Arkansas", "California", "Colorado",
"Connecticut", "Delaware", "Florida", "Georgia", "Hawaii", "Idaho",
"Illinois", "Indiana", "Iowa", "Kansas", "Kentucky", "Louisiana",
"Maine", "Maryland", "Massachusetts", "Michigan", "Minnesota",
"Mississippi", "Missouri", "Montana", "Nebraska", "Nevada",
"New Hampshire", "New Jersey", "New Mexico", "New York",
"North Carolina", "North Dakota", "Ohio", "Oklahoma", "Oregon",
"Pennsylvania", "Rhode Island", "South Carolina", "South Dakota",
"Tennessee", "Texas", "Utah", "Vermont", "Virginia", "Washington",
"West Virginia", "Wisconsin", "Wyoming"];
it("returns 50 states", function() {
expect(stateService.getAllStates().length).toBe(50);
});
it("returns a state by name, case-insensitive", function() {
expect(stateService.getStateByName('Alaska')).toBeTruthy();
expect(stateService.getStateByName('alaska')).toBeTruthy();
expect(stateService.getStateByName('aLaSka')).toBeTruthy();
});
it("returns a state by abbrev, case-insensitive", function() {
expect(stateService.getStateByAbbrev('AK')).toBeTruthy();
expect(stateService.getStateByAbbrev('Ak')).toBeTruthy();
expect(stateService.getStateByAbbrev('aK')).toBeTruthy();
expect(stateService.getStateByAbbrev('ak')).toBeTruthy();
});
it("returns falsy if state name or abbreviation isn't found", function() {
expect(stateService.getStateByAbbrev('ZA')).toBeFalsy();
expect(stateService.getStateByName('Cuzco')).toBeFalsy();
});
});
describe("StateService returns each state", function() {
var StateService = require('../services/StateService');
var stateService = new StateService();
var stateAbbrevs = ["AL", "AK", "AZ", "AR", "CA", "CO", "CT", "DE", "FL", "GA", "HI",
"ID", "IL", "IN", "IA", "KS", "KY", "LA", "ME", "MD", "MA", "MI",
"MN", "MS", "MO", "MT", "NE", "NV", "NH", "NJ", "NM", "NY", "NC",
"ND", "OH", "OK", "OR", "PA", "RI", "SC", "SD", "TN", "TX", "UT",
"VT", "VA", "WA", "WV", "WI", "WY"];
var stateNames = ["Alabama", "Alaska", "Arizona", "Arkansas", "California", "Colorado",
"Connecticut", "Delaware", "Florida", "Georgia", "Hawaii", "Idaho",
"Illinois", "Indiana", "Iowa", "Kansas", "Kentucky", "Louisiana",
"Maine", "Maryland", "Massachusetts", "Michigan", "Minnesota",
"Mississippi", "Missouri", "Montana", "Nebraska", "Nevada",
"New Hampshire", "New Jersey", "New Mexico", "New York",
"North Carolina", "North Dakota", "Ohio", "Oklahoma", "Oregon",
"Pennsylvania", "Rhode Island", "South Carolina", "South Dakota",
"Tennessee", "Texas", "Utah", "Vermont", "Virginia", "Washington",
"West Virginia", "Wisconsin", "Wyoming"];
stateAbbrevs.forEach(
function(abbrev) {
it("by its abbrev - " + abbrev, function() {
expect(stateService.getStateByAbbrev(abbrev)).toBeTruthy();
});
}
);
stateNames.forEach(
function(name) {
it("by its name - " + name, function() {
expect(stateService.getStateByName(name)).toBeTruthy();
});
}
);
});
describe("A state", function() {
var StateService = require('../services/StateService');
var stateService = new StateService();
var knownState = stateService.getStateByName('Alaska');
var statesList = stateService.getAllStates();
var stateTest = function(state) {
it("has a name - " + state.name, function() {
expect(state.name).toBeTruthy();
});
it("has an abbrev - " + state.name, function() {
expect(state.abbrev).toBeTruthy();
});
it("has a capital - " + state.name, function() {
expect(state.capital).toBeTruthy();
});
it("has multiple sample addresses - " + state.name, function() {
expect(state.addresses).toBeTruthy();
expect(state.addresses.length).toBeGreaterThan(0);
state.addresses.forEach(
function(address) {
expect(address).toBeTruthy();
}
);
});
describe("and each of its addresses - " + state.name, function() {
var addresses = state.addresses;
it("has a street, city, state, and zip" + state.name, function() {
addresses.forEach(function(address) {
expect(address.street).toBeTruthy();
expect(address.city).toBeTruthy();
expect(address.state).toBeTruthy();
expect(address.zip).toBeTruthy();
});
});
});
it("has a drivers license description - " + state.name, function() {
expect(state.driversLicenseDescription).toBeTruthy();
expect(state.driversLicenseDescription instanceof Array).toBe(true);
expect(state.driversLicenseDescription.length).toBeGreaterThan(0);
});
it("has a sample drivers license - " + state.name, function() {
expect(state.sampleLicense).toBeTruthy();
});
it("has a union admission date - " + state.name, function() {
var admissionDate = new Date(state.unionAdmissionDate);
expect(isNaN(admissionDate)).not.toBeTruthy();
});
};
describe("with known test values", function() {
stateTest(knownState);
});
describe("in the full list", function() {
statesList.forEach(function(stateToTest) {
stateTest(stateToTest);
});
});
});
|
(function(){
var helpers = angular.module('SwfHelpers',[])
helpers.factory('FileReader',['$q', function($q){
var onLoad = function(reader, deferred, scope) {
return function () {
scope.$apply(function () {
deferred.resolve(reader.result);
});
};
};
var onError = function (reader, deferred, scope) {
return function () {
scope.$apply(function () {
deferred.reject(reader.result);
});
};
};
var onProgress = function(reader, scope) {
return function (event) {
// scope.$broadcast("fileProgress",
// {
// total: event.total,
// loaded: event.loaded
// });
};
};
var getReader = function(deferred, scope) {
var reader = new FileReader();
reader.onload = onLoad(reader, deferred, scope);
reader.onerror = onError(reader, deferred, scope);
reader.onprogress = onProgress(reader, scope);
return reader;
};
var read = function (file, scope, method) {
var deferred = $q.defer();
var reader = getReader(deferred, scope);
reader[method](file);
return deferred.promise;
};
var readAsDataURL = function (file, scope){
return read(file, scope, 'readAsDataURL');
}
var readAsText = function (file, scope){
return read(file, scope, 'readAsText');
}
return {
readAsDataURL: readAsDataURL,
readAsText: readAsText
}
}]);
helpers.factory('HistoryTransformer',[function(){
var transform = function(obj) {
for (var key in obj) {
var value = obj[key];
if (angular.isArray(value) && value.length == 2 && typeof value[0] === 'string' ) {
obj[key] = transform(value[1]);
} else if (typeof value === 'object') {
transform(value);
}
}
return obj;
};
var fromJson = function(history){
var parsed = angular.fromJson(history);
return transform(parsed[1]);
}
return {
fromJson: fromJson
}
}]);
helpers.factory('EventTransformer',[function(){
var EVENT_TYPE = {
'ActivityTaskScheduled': 'activity',
'DecisionTaskScheduled': 'decision',
'TimerStarted': 'timer',
'WorkflowExecutionSignaled': 'signal'
};
var fromHistory = function(history){
// return an array of event objects that can be drawn on the screen
// events group multiple SWF events (at most three)
// they have start, end, type, parameters
var events = {};
if(angular.isArray(history)){
for(var e in history){
e = history[e];
var attributeName = e.eventType[0].toLowerCase() + e.eventType.slice(1) + "EventAttributes";
var attributes = e[attributeName] || {};
var event = null;
var eventDate = new Date(e.eventTimestamp);
if(/(scheduled|timerStarted)$/i.test(e.eventType)){
//event is scheduled add new event
events[e.eventId] = {startDate: eventDate, label: e.eventType, type: EVENT_TYPE[e.eventType], scheduled: e};
} else if(/started$/i.test(e.eventType)){
//event is started
event = events[attributes.scheduledEventId];
if(event){
event.endDate = eventDate;
event.started = e;
}
} else if(/(completed|timedout)$/i.test(e.eventType)){
event = events[attributes.scheduledEventId];
if(event){
event.endDate = eventDate;
event.completed = e;
}
} else if(/timer(fired|canceled)$/i.test(e.eventType)){
event = events[attributes.startedEventId];
if(event){
event.endDate = eventDate;
event.completed = e;
}
} else if(/workflowExecutionSignaled/i.test(e.eventType)){
events[e.eventId] = {startDate: eventDate, endDate: eventDate, label: e.eventType, type: EVENT_TYPE[e.eventType], scheduled: e};
}
}
}
var result = [];
for(var k in events){
result.push(events[k]);
}
result.sort(function(a, b) {
return a.endDate - b.endDate;
});
var endDate = result[result.length - 1].endDate || new Date();
result.sort(function(a, b) {
return a.startDate - b.startDate;
});
var lanes = [];
var taskNames = [];
for(var i in result){
var interval = result[i];
interval.endDate = interval.endDate || endDate;
var assigned = false;
for(var l = 0; l < lanes.length; l++){
if(interval.startDate > lanes[l]){
assigned = true;
interval.taskName = 'L' + (l + 1);
lanes[l] = interval.endDate;
break;
}
}
if(!assigned){
lanes.push(interval.endDate);
interval.taskName = 'L' + lanes.length;
taskNames.push(interval.taskName);
}
}
return {tasks: result, taskNames: taskNames, taskTypes: taskNames};
}
var merge = function(source, destination){
for(var attr in source){
destination[attr] = source[attr];
}
return destination;
}
var extractActivity = function(event){
var activity = {};
var scheduled = event.scheduled;
var attrs = null;
if(event.scheduled){
attrs = event.scheduled.activityTaskScheduledEventAttributes;
activity = merge(attrs, activity);
activity.scheduleDate = event.scheduled.eventTimestamp;
}
if(event.started){
attrs = event.started.activityTaskStartedEventAttributes;
activity = merge(attrs, activity);
activity.startDate = event.started.eventTimestamp;
}
if(event.completed){
attrs = event.completed.activityTaskCompletedEventAttributes;
activity = merge(attrs, activity);
activity.endDate = event.completed.eventTimestamp;
}
return activity;
}
var extractActivities = function(events){
var activities = [];
if(events && events.tasks.length > 0){
for(var i=0; i< events.tasks.length; i++){
var event = events.tasks[i];
if("activity" === event.type){
activities.push(extractActivity(event));
}
}
}
return activities;
}
return {
fromHistory: fromHistory,
extractActivities: extractActivities
}
}]);
helpers.filter('dateFormatter', function(){
return function(obj){
return new Date(obj).toGMTString();
}
});
helpers.directive('eventView', [function(){
var transform = function(obj) {
for (var key in obj) {
var value = obj[key];
if (value === null) {
delete obj[key];
} else if (typeof value === 'object') {
transform(value);
}
}
};
var syntaxHighlight = function(json) {
if (typeof json != 'string') {
json = JSON.stringify(json, undefined, 2);
}
if(!json){
return null;
}
json = json.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
return json.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, function (match) {
var cls = 'number';
if (/^"/.test(match)) {
if (/:$/.test(match)) {
cls = 'key';
} else {
cls = 'string';
}
} else if (/true|false/.test(match)) {
cls = 'boolean';
} else if (/null/.test(match)) {
cls = 'null';
}
return '<span class="js-' + cls + '">' + match + '</span>';
});
}
var linker = function(scope, elem, attrs){
scope.$watch('obj', function(newVal, oldVal){
if(newVal){
var copy = angular.copy(newVal);
transform(copy)
var html = syntaxHighlight(copy);
elem.html(html);
}
});
}
return {
restric: 'E',
replace: false,
scope: {obj: '='},
link: linker
};
}]);
})();
|
(function() {
var estraverse, recurse, lastFoundIdentifier;
estraverse = require("estraverse");
recurse = function(ast, declared, undeclared) {
var ast_fn, ast_fns, declared_copy, i, ids, len;
if (declared == null) {
declared = new Set
}
if (undeclared == null) {
undeclared = new Set
}
ids = new Set;
ast_fns = [];
estraverse.traverse(ast, {
enter: function(node, parent) {
var brokenLastId, lastPieceId;
if (lastFoundIdentifier) {
brokenLastId = lastFoundIdentifier.split(".")
lastPieceId = brokenLastId[brokenLastId.length - 1]
}
if (parent != null) {
if (parent.type != 'MemberExpression') {
lastFoundIdentifier = null;
}
if (node.type === "Identifier") {
if (parent.type === "VariableDeclarator") {
declared.add(node.name)
} else if (!parent.key && (parent.type !== "MemberExpression" || node.name !== parent.property.name)) {
ids.add(node.name)
lastFoundIdentifier = node.name
} else if (parent.type == "MemberExpression" && parent.object && parent.object.name == lastPieceId ||
parent.object && parent.object.object && parent.object.property.name === lastPieceId) {
ids.delete(lastFoundIdentifier)
if (lastFoundIdentifier) {
lastFoundIdentifier += "."
lastFoundIdentifier += node.name
} else {
lastFoundIdentifier = node.name
}
ids.add(lastFoundIdentifier)
}
} else if (node.type === "FunctionDeclaration" || node.type === "FunctionExpression" || node.type === "ArrowFunctionExpression") {
ast_fns.push(node);
if (node.id != null) {
declared.add(node.id.name)
}
this.skip()
}
}
},
leave: function(node) {
if (node.type == 'CallExpression') {
// prop.value.funcCall
var namedArgs = node
.arguments.map(function(a) { return a.type})
.filter(function(t) { return t != "FunctionExpression" && t!= "Literal" })
var lastId = Array.from(ids)[ids.size - namedArgs.length - 1]
if (lastId && node.callee.type === 'Identifier') {
// Root level constructor
// e.g. moment()
ids.delete(lastId)
} else if (lastId && node.callee.property.name == lastId.split('.')[lastId.split('.').length - 1]) {
// ensure that we're stripping the right thing
// e.g. abc.def.join('.').split('.')
ids.delete(lastId)
//prop.value
var strippedId = lastId.split('.').slice(0, lastId.split(',').length - 2).join('.')
ids.add(strippedId)
}
}
}
});
ids.forEach(function(id) {
var firstPiece = id.split(".")[0]
if (!declared.has(firstPiece)) {
undeclared.add(id)
}
});
for (i = 0, len = ast_fns.length; i < len; i++) {
ast_fn = ast_fns[i];
declared_copy = new Set;
declared.forEach(function(id) {
declared_copy.add(id)
});
ast_fn.params.forEach(function(param) {
declared_copy.add(param.name)
});
recurse(ast_fn, declared_copy, undeclared)
}
return undeclared
};
module.exports = recurse
}).call(this);
|
// jQuery(document).ready(function() {
$('section').attr('data-background','css/theme/images/bg_gray.png');
$('section.almbg').attr('data-background','css/theme/images/br_red_ALM.png');
// });
|
let serialise = function(obj) {
if (typeof obj != 'object') return obj;
let pairs = [];
for (let key in obj) {
if (null != obj[key]) {
pairs.push(encodeURIComponent(key)
+ '=' + encodeURIComponent(obj[key]));
}
}
return pairs.join('&');
}
let jsonp = function(request) {
// In case this is in nodejs, run without modifying request
if(typeof window == 'undefined') return request;
request.end = end.bind(request);
return request;
};
let callbackWrapper = function(data) {
let err = null;
let res = {
body: data
};
this._jsonp.callback.call(this, err, res);
};
let end = function(callback) {
this._jsonp = {
callbackParam: 'callback',
callbackName: 'superagentCallback', // + new Date().valueOf() + parseInt(Math.random() * 1000),
callback: callback
};
window[this._jsonp.callbackName] = callbackWrapper.bind(this);
let params = {
[this._jsonp.callbackParam]: this._jsonp.callbackName
};
this._query.push(serialise(params));
let queryString = this._query.join('&');
let s = document.createElement('script');
let separator = (this.url.indexOf('?') > -1) ? '&': '?';
let url = this.url + separator + queryString;
s.src = url;
document.getElementsByTagName('head')[0].appendChild(s);
};
// Prefer node/browserify style requires
if(typeof module !== 'undefined' && typeof module.exports !== 'undefined'){
module.exports = jsonp;
} else if (typeof window !== 'undefined'){
window.superagentJSONP = jsonp;
}
|
module.exports =
/******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId])
/******/ return installedModules[moduleId].exports;
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ exports: {},
/******/ id: moduleId,
/******/ loaded: false
/******/ };
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/ // Flag the module as loaded
/******/ module.loaded = true;
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "/dist/";
/******/ // Load entry module and return exports
/******/ return __webpack_require__(0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__(52);
/***/ }),
/* 1 */,
/* 2 */,
/* 3 */
/***/ (function(module, exports) {
/* globals __VUE_SSR_CONTEXT__ */
// this module is a runtime utility for cleaner component module output and will
// be included in the final webpack user bundle
module.exports = function normalizeComponent (
rawScriptExports,
compiledTemplate,
injectStyles,
scopeId,
moduleIdentifier /* server only */
) {
var esModule
var scriptExports = rawScriptExports = rawScriptExports || {}
// ES6 modules interop
var type = typeof rawScriptExports.default
if (type === 'object' || type === 'function') {
esModule = rawScriptExports
scriptExports = rawScriptExports.default
}
// Vue.extend constructor export interop
var options = typeof scriptExports === 'function'
? scriptExports.options
: scriptExports
// render functions
if (compiledTemplate) {
options.render = compiledTemplate.render
options.staticRenderFns = compiledTemplate.staticRenderFns
}
// scopedId
if (scopeId) {
options._scopeId = scopeId
}
var hook
if (moduleIdentifier) { // server build
hook = function (context) {
// 2.3 injection
context =
context || // cached call
(this.$vnode && this.$vnode.ssrContext) || // stateful
(this.parent && this.parent.$vnode && this.parent.$vnode.ssrContext) // functional
// 2.2 with runInNewContext: true
if (!context && typeof __VUE_SSR_CONTEXT__ !== 'undefined') {
context = __VUE_SSR_CONTEXT__
}
// inject component styles
if (injectStyles) {
injectStyles.call(this, context)
}
// register component module identifier for async chunk inferrence
if (context && context._registeredComponents) {
context._registeredComponents.add(moduleIdentifier)
}
}
// used by ssr in case component is cached and beforeCreate
// never gets called
options._ssrRegister = hook
} else if (injectStyles) {
hook = injectStyles
}
if (hook) {
var functional = options.functional
var existing = functional
? options.render
: options.beforeCreate
if (!functional) {
// inject component registration as beforeCreate hook
options.beforeCreate = existing
? [].concat(existing, hook)
: [hook]
} else {
// register for functioal component in vue file
options.render = function renderWithStyleInjection (h, context) {
hook.call(context)
return existing(h, context)
}
}
}
return {
esModule: esModule,
exports: scriptExports,
options: options
}
}
/***/ }),
/* 4 */,
/* 5 */,
/* 6 */,
/* 7 */,
/* 8 */,
/* 9 */
/***/ (function(module, exports) {
module.exports = require("element-ui/lib/input");
/***/ }),
/* 10 */
/***/ (function(module, exports) {
module.exports = require("element-ui/lib/utils/clickoutside");
/***/ }),
/* 11 */,
/* 12 */,
/* 13 */
/***/ (function(module, exports) {
module.exports = require("element-ui/lib/utils/vue-popper");
/***/ }),
/* 14 */
/***/ (function(module, exports) {
module.exports = require("element-ui/lib/mixins/emitter");
/***/ }),
/* 15 */,
/* 16 */,
/* 17 */,
/* 18 */,
/* 19 */,
/* 20 */,
/* 21 */,
/* 22 */,
/* 23 */,
/* 24 */,
/* 25 */,
/* 26 */,
/* 27 */,
/* 28 */,
/* 29 */,
/* 30 */,
/* 31 */,
/* 32 */,
/* 33 */,
/* 34 */,
/* 35 */,
/* 36 */,
/* 37 */,
/* 38 */,
/* 39 */,
/* 40 */,
/* 41 */,
/* 42 */,
/* 43 */,
/* 44 */,
/* 45 */,
/* 46 */,
/* 47 */,
/* 48 */,
/* 49 */,
/* 50 */,
/* 51 */,
/* 52 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
var _main = __webpack_require__(53);
var _main2 = _interopRequireDefault(_main);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/* istanbul ignore next */
_main2.default.install = function (Vue) {
Vue.component(_main2.default.name, _main2.default);
};
exports.default = _main2.default;
/***/ }),
/* 53 */
/***/ (function(module, exports, __webpack_require__) {
var Component = __webpack_require__(3)(
/* script */
__webpack_require__(54),
/* template */
__webpack_require__(64),
/* styles */
null,
/* scopeId */
null,
/* moduleIdentifier (server only) */
null
)
module.exports = Component.exports
/***/ }),
/* 54 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
var _vue = __webpack_require__(55);
var _vue2 = _interopRequireDefault(_vue);
var _menu = __webpack_require__(56);
var _menu2 = _interopRequireDefault(_menu);
var _input = __webpack_require__(9);
var _input2 = _interopRequireDefault(_input);
var _vuePopper = __webpack_require__(13);
var _vuePopper2 = _interopRequireDefault(_vuePopper);
var _clickoutside = __webpack_require__(10);
var _clickoutside2 = _interopRequireDefault(_clickoutside);
var _emitter = __webpack_require__(14);
var _emitter2 = _interopRequireDefault(_emitter);
var _locale = __webpack_require__(61);
var _locale2 = _interopRequireDefault(_locale);
var _locale3 = __webpack_require__(62);
var _debounce = __webpack_require__(63);
var _debounce2 = _interopRequireDefault(_debounce);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var popperMixin = {
props: {
placement: {
type: String,
default: 'bottom-start'
},
appendToBody: _vuePopper2.default.props.appendToBody,
offset: _vuePopper2.default.props.offset,
boundariesPadding: _vuePopper2.default.props.boundariesPadding,
popperOptions: _vuePopper2.default.props.popperOptions
},
methods: _vuePopper2.default.methods,
data: _vuePopper2.default.data,
beforeDestroy: _vuePopper2.default.beforeDestroy
}; //
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
exports.default = {
name: 'ElCascader',
directives: { Clickoutside: _clickoutside2.default },
mixins: [popperMixin, _emitter2.default, _locale2.default],
components: {
ElInput: _input2.default
},
props: {
options: {
type: Array,
required: true
},
props: {
type: Object,
default: function _default() {
return {
children: 'children',
label: 'label',
value: 'value',
disabled: 'disabled'
};
}
},
value: {
type: Array,
default: function _default() {
return [];
}
},
placeholder: {
type: String,
default: function _default() {
return (0, _locale3.t)('el.cascader.placeholder');
}
},
disabled: Boolean,
clearable: {
type: Boolean,
default: false
},
changeOnSelect: Boolean,
popperClass: String,
expandTrigger: {
type: String,
default: 'click'
},
filterable: Boolean,
size: String,
showAllLevels: {
type: Boolean,
default: true
},
debounce: {
type: Number,
default: 300
},
beforeFilter: {
type: Function,
default: function _default() {
return function () {};
}
}
},
data: function data() {
return {
currentValue: this.value || [],
menu: null,
debouncedInputChange: function debouncedInputChange() {},
menuVisible: false,
inputHover: false,
inputValue: '',
flatOptions: null
};
},
computed: {
labelKey: function labelKey() {
return this.props.label || 'label';
},
valueKey: function valueKey() {
return this.props.value || 'value';
},
childrenKey: function childrenKey() {
return this.props.children || 'children';
},
currentLabels: function currentLabels() {
var _this = this;
var options = this.options;
var labels = [];
this.currentValue.forEach(function (value) {
var targetOption = options && options.filter(function (option) {
return option[_this.valueKey] === value;
})[0];
if (targetOption) {
labels.push(targetOption[_this.labelKey]);
options = targetOption[_this.childrenKey];
}
});
return labels;
}
},
watch: {
menuVisible: function menuVisible(value) {
value ? this.showMenu() : this.hideMenu();
},
value: function value(_value) {
this.currentValue = _value;
},
currentValue: function currentValue(value) {
this.dispatch('ElFormItem', 'el.form.change', [value]);
},
options: {
deep: true,
handler: function handler(value) {
if (!this.menu) {
this.initMenu();
}
this.flatOptions = this.flattenOptions(this.options);
this.menu.options = value;
}
}
},
methods: {
initMenu: function initMenu() {
this.menu = new _vue2.default(_menu2.default).$mount();
this.menu.options = this.options;
this.menu.props = this.props;
this.menu.expandTrigger = this.expandTrigger;
this.menu.changeOnSelect = this.changeOnSelect;
this.menu.popperClass = this.popperClass;
this.popperElm = this.menu.$el;
this.menu.$on('pick', this.handlePick);
this.menu.$on('activeItemChange', this.handleActiveItemChange);
this.menu.$on('menuLeave', this.doDestroy);
},
showMenu: function showMenu() {
var _this2 = this;
if (!this.menu) {
this.initMenu();
}
this.menu.value = this.currentValue.slice(0);
this.menu.visible = true;
this.menu.options = this.options;
this.$nextTick(function (_) {
_this2.updatePopper();
_this2.menu.inputWidth = _this2.$refs.input.$el.offsetWidth - 2;
});
},
hideMenu: function hideMenu() {
this.inputValue = '';
this.menu.visible = false;
},
handleActiveItemChange: function handleActiveItemChange(value) {
var _this3 = this;
this.$nextTick(function (_) {
_this3.updatePopper();
});
this.$emit('active-item-change', value);
},
handlePick: function handlePick(value) {
var close = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
this.currentValue = value;
this.$emit('input', value);
this.$emit('change', value);
if (close) {
this.menuVisible = false;
} else {
this.$nextTick(this.updatePopper);
}
},
handleInputChange: function handleInputChange(value) {
var _this4 = this;
if (!this.menuVisible) return;
var flatOptions = this.flatOptions;
if (!value) {
this.menu.options = this.options;
this.$nextTick(this.updatePopper);
return;
}
var filteredFlatOptions = flatOptions.filter(function (optionsStack) {
return optionsStack.some(function (option) {
return new RegExp(value, 'i').test(option[_this4.labelKey]);
});
});
if (filteredFlatOptions.length > 0) {
filteredFlatOptions = filteredFlatOptions.map(function (optionStack) {
return {
__IS__FLAT__OPTIONS: true,
value: optionStack.map(function (item) {
return item[_this4.valueKey];
}),
label: _this4.renderFilteredOptionLabel(value, optionStack)
};
});
} else {
filteredFlatOptions = [{
__IS__FLAT__OPTIONS: true,
label: this.t('el.cascader.noMatch'),
value: '',
disabled: true
}];
}
this.menu.options = filteredFlatOptions;
this.$nextTick(this.updatePopper);
},
renderFilteredOptionLabel: function renderFilteredOptionLabel(inputValue, optionsStack) {
var _this5 = this;
return optionsStack.map(function (option, index) {
var label = option[_this5.labelKey];
var keywordIndex = label.toLowerCase().indexOf(inputValue.toLowerCase());
var labelPart = label.slice(keywordIndex, inputValue.length + keywordIndex);
var node = keywordIndex > -1 ? _this5.highlightKeyword(label, labelPart) : label;
return index === 0 ? node : [' / ', node];
});
},
highlightKeyword: function highlightKeyword(label, keyword) {
var _this6 = this;
var h = this._c;
return label.split(keyword).map(function (node, index) {
return index === 0 ? node : [h('span', { class: { 'el-cascader-menu__item__keyword': true } }, [_this6._v(keyword)]), node];
});
},
flattenOptions: function flattenOptions(options) {
var _this7 = this;
var ancestor = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
var flatOptions = [];
options.forEach(function (option) {
var optionsStack = ancestor.concat(option);
if (!option[_this7.childrenKey]) {
flatOptions.push(optionsStack);
} else {
if (_this7.changeOnSelect) {
flatOptions.push(optionsStack);
}
flatOptions = flatOptions.concat(_this7.flattenOptions(option[_this7.childrenKey], optionsStack));
}
});
return flatOptions;
},
clearValue: function clearValue(ev) {
ev.stopPropagation();
this.handlePick([], true);
},
handleClickoutside: function handleClickoutside() {
this.menuVisible = false;
},
handleClick: function handleClick() {
if (this.disabled) return;
if (this.filterable) {
this.menuVisible = true;
this.$refs.input.$refs.input.focus();
return;
}
this.menuVisible = !this.menuVisible;
}
},
created: function created() {
var _this8 = this;
this.debouncedInputChange = (0, _debounce2.default)(this.debounce, function (value) {
var before = _this8.beforeFilter(value);
if (before && before.then) {
_this8.menu.options = [{
__IS__FLAT__OPTIONS: true,
label: _this8.t('el.cascader.loading'),
value: '',
disabled: true
}];
before.then(function () {
_this8.$nextTick(function () {
_this8.handleInputChange(value);
});
});
} else if (before !== false) {
_this8.$nextTick(function () {
_this8.handleInputChange(value);
});
}
});
},
mounted: function mounted() {
this.flatOptions = this.flattenOptions(this.options);
}
};
/***/ }),
/* 55 */
/***/ (function(module, exports) {
module.exports = require("vue");
/***/ }),
/* 56 */
/***/ (function(module, exports, __webpack_require__) {
var Component = __webpack_require__(3)(
/* script */
__webpack_require__(57),
/* template */
null,
/* styles */
null,
/* scopeId */
null,
/* moduleIdentifier (server only) */
null
)
module.exports = Component.exports
/***/ }),
/* 57 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
var _babelHelperVueJsxMergeProps = __webpack_require__(58);
var _babelHelperVueJsxMergeProps2 = _interopRequireDefault(_babelHelperVueJsxMergeProps);
var _shared = __webpack_require__(59);
var _scrollIntoView = __webpack_require__(60);
var _scrollIntoView2 = _interopRequireDefault(_scrollIntoView);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var copyArray = function copyArray(arr, props) {
if (!arr || !Array.isArray(arr) || !props) return arr;
var result = [];
var configurableProps = ['__IS__FLAT__OPTIONS', 'label', 'value', 'disabled'];
var childrenProp = props.children || 'children';
arr.forEach(function (item) {
var itemCopy = {};
configurableProps.forEach(function (prop) {
var name = props[prop];
var value = item[name];
if (value === undefined) {
name = prop;
value = item[name];
}
if (value !== undefined) itemCopy[name] = value;
});
if (Array.isArray(item[childrenProp])) {
itemCopy[childrenProp] = copyArray(item[childrenProp], props);
}
result.push(itemCopy);
});
return result;
};
exports.default = {
name: 'ElCascaderMenu',
data: function data() {
return {
inputWidth: 0,
options: [],
props: {},
visible: false,
activeValue: [],
value: [],
expandTrigger: 'click',
changeOnSelect: false,
popperClass: ''
};
},
watch: {
visible: function visible(value) {
if (value) {
this.activeValue = this.value;
}
},
value: {
immediate: true,
handler: function handler(value) {
this.activeValue = value;
}
}
},
computed: {
activeOptions: {
cache: false,
get: function get() {
var _this = this;
var activeValue = this.activeValue;
var configurableProps = ['label', 'value', 'children', 'disabled'];
var formatOptions = function formatOptions(options) {
options.forEach(function (option) {
if (option.__IS__FLAT__OPTIONS) return;
configurableProps.forEach(function (prop) {
var value = option[_this.props[prop] || prop];
if (value !== undefined) option[prop] = value;
});
if (Array.isArray(option.children)) {
formatOptions(option.children);
}
});
};
var loadActiveOptions = function loadActiveOptions(options) {
var activeOptions = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
var level = activeOptions.length;
activeOptions[level] = options;
var active = activeValue[level];
if ((0, _shared.isDef)(active)) {
options = options.filter(function (option) {
return option.value === active;
})[0];
if (options && options.children) {
loadActiveOptions(options.children, activeOptions);
}
}
return activeOptions;
};
var optionsCopy = copyArray(this.options, this.props);
formatOptions(optionsCopy);
return loadActiveOptions(optionsCopy);
}
}
},
methods: {
select: function select(item, menuIndex) {
if (item.__IS__FLAT__OPTIONS) {
this.activeValue = item.value;
} else if (menuIndex) {
this.activeValue.splice(menuIndex, this.activeValue.length - 1, item.value);
} else {
this.activeValue = [item.value];
}
this.$emit('pick', this.activeValue.slice());
},
handleMenuLeave: function handleMenuLeave() {
this.$emit('menuLeave');
},
activeItem: function activeItem(item, menuIndex) {
var len = this.activeOptions.length;
this.activeValue.splice(menuIndex, len, item.value);
this.activeOptions.splice(menuIndex + 1, len, item.children);
if (this.changeOnSelect) {
this.$emit('pick', this.activeValue.slice(), false);
} else {
this.$emit('activeItemChange', this.activeValue);
}
},
scrollMenu: function scrollMenu(menu) {
(0, _scrollIntoView2.default)(menu, menu.getElementsByClassName('is-active')[0]);
},
handleMenuEnter: function handleMenuEnter() {
var _this2 = this;
this.$nextTick(function () {
return _this2.$refs.menus.forEach(function (menu) {
return _this2.scrollMenu(menu);
});
});
}
},
render: function render(h) {
var _this3 = this;
var activeValue = this.activeValue,
activeOptions = this.activeOptions,
visible = this.visible,
expandTrigger = this.expandTrigger,
popperClass = this.popperClass;
var menus = this._l(activeOptions, function (menu, menuIndex) {
var isFlat = false;
var items = _this3._l(menu, function (item) {
var events = {
on: {}
};
if (item.__IS__FLAT__OPTIONS) isFlat = true;
if (!item.disabled) {
if (item.children) {
var triggerEvent = {
click: 'click',
hover: 'mouseenter'
}[expandTrigger];
events.on[triggerEvent] = function () {
_this3.activeItem(item, menuIndex);
_this3.$nextTick(function () {
// adjust self and next level
_this3.scrollMenu(_this3.$refs.menus[menuIndex]);
_this3.scrollMenu(_this3.$refs.menus[menuIndex + 1]);
});
};
} else {
events.on.click = function () {
_this3.select(item, menuIndex);
_this3.$nextTick(function () {
return _this3.scrollMenu(_this3.$refs.menus[menuIndex]);
});
};
}
}
return h(
'li',
(0, _babelHelperVueJsxMergeProps2.default)([{
'class': {
'el-cascader-menu__item': true,
'el-cascader-menu__item--extensible': item.children,
'is-active': item.value === activeValue[menuIndex],
'is-disabled': item.disabled
}
}, events]),
[item.label]
);
});
var menuStyle = {};
if (isFlat) {
menuStyle.minWidth = _this3.inputWidth + 'px';
}
return h(
'ul',
{
'class': {
'el-cascader-menu': true,
'el-cascader-menu--flexible': isFlat
},
style: menuStyle,
refInFor: true,
ref: 'menus' },
[items]
);
});
return h(
'transition',
{
attrs: { name: 'el-zoom-in-top' },
on: {
'before-enter': this.handleMenuEnter,
'after-leave': this.handleMenuLeave
}
},
[h(
'div',
{
directives: [{
name: 'show',
value: visible
}],
'class': ['el-cascader-menus', popperClass],
ref: 'wrapper'
},
[menus]
)]
);
}
};
/***/ }),
/* 58 */
/***/ (function(module, exports) {
module.exports = require("babel-helper-vue-jsx-merge-props");
/***/ }),
/* 59 */
/***/ (function(module, exports) {
module.exports = require("element-ui/lib/utils/shared");
/***/ }),
/* 60 */
/***/ (function(module, exports) {
module.exports = require("element-ui/lib/utils/scroll-into-view");
/***/ }),
/* 61 */
/***/ (function(module, exports) {
module.exports = require("element-ui/lib/mixins/locale");
/***/ }),
/* 62 */
/***/ (function(module, exports) {
module.exports = require("element-ui/lib/locale");
/***/ }),
/* 63 */
/***/ (function(module, exports) {
module.exports = require("throttle-debounce/debounce");
/***/ }),
/* 64 */
/***/ (function(module, exports) {
module.exports={render:function (){var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;
return _c('span', {
directives: [{
name: "clickoutside",
rawName: "v-clickoutside",
value: (_vm.handleClickoutside),
expression: "handleClickoutside"
}],
ref: "reference",
staticClass: "el-cascader",
class: [{
'is-opened': _vm.menuVisible,
'is-disabled': _vm.disabled
},
_vm.size ? 'el-cascader--' + _vm.size : ''
],
on: {
"click": _vm.handleClick,
"mouseenter": function($event) {
_vm.inputHover = true
},
"mouseleave": function($event) {
_vm.inputHover = false
}
}
}, [_c('el-input', {
ref: "input",
attrs: {
"readonly": !_vm.filterable,
"placeholder": _vm.currentLabels.length ? undefined : _vm.placeholder,
"validate-event": false,
"size": _vm.size,
"disabled": _vm.disabled
},
on: {
"change": _vm.debouncedInputChange
},
model: {
value: (_vm.inputValue),
callback: function($$v) {
_vm.inputValue = $$v
},
expression: "inputValue"
}
}, [_c('template', {
attrs: {
"slot": "icon"
},
slot: "icon"
}, [(_vm.clearable && _vm.inputHover && _vm.currentLabels.length) ? _c('i', {
key: "1",
staticClass: "el-input__icon el-icon-circle-close el-cascader__clearIcon",
on: {
"click": _vm.clearValue
}
}) : _c('i', {
key: "2",
staticClass: "el-input__icon el-icon-caret-bottom",
class: {
'is-reverse': _vm.menuVisible
}
})])], 2), _c('span', {
directives: [{
name: "show",
rawName: "v-show",
value: (_vm.inputValue === ''),
expression: "inputValue === ''"
}],
staticClass: "el-cascader__label"
}, [(_vm.showAllLevels) ? [_vm._l((_vm.currentLabels), function(label, index) {
return [_vm._v("\n " + _vm._s(label) + "\n "), (index < _vm.currentLabels.length - 1) ? _c('span', [_vm._v(" / ")]) : _vm._e()]
})] : [_vm._v("\n " + _vm._s(_vm.currentLabels[_vm.currentLabels.length - 1]) + "\n ")]], 2)], 1)
},staticRenderFns: []}
/***/ })
/******/ ]);
|
'use strict';
var fs = require('fs');
var expect = require('chai').expect;
var bitmapReader = require('../lib/bitmapReader');
describe('bitmapReader.invert', function() {
before(function(){
testCleanup('./img/invertedbmp.bmp');
});
after(function(){
testCleanup('./img/invertedbmp.bmp');
});
it('should not equal the original bitmap file.', function() {
var original = fs.readFileSync('./img/test.bmp');
bitmapReader.invert();
var newbmp = fs.readFileSync('./img/invertedbmp.bmp');
expect(original).to.not.eql(newbmp);
});
});
describe("bitmapReader.invert", function() {
before(function(){
testCleanup('./img/invertedbmp.bmp');
});
after(function(){
testCleanup('./img/invertedbmp.bmp');
});
it("should modify the bitmap's color palette", function() {
var originalBmp = fs.readFileSync('./img/test.bmp');
var originalColorPalette = originalBmp.slice(54, 1078);
bitmapReader.invert();
var newBmp = fs.readFileSync('./img/invertedbmp.bmp');
var newBmpColorPalette = newBmp.slice(54, 1078);
expect(originalColorPalette).not.to.eql(newBmpColorPalette);
});
});
describe('bitmapReader.random', function() {
before(function(){
testCleanup('./img/randombmp.bmp');
});
after(function(){
testCleanup('./img/randombmp.bmp');
});
it('should not equal the original bitmap file.', function() {
var original = fs.readFileSync('./img/test.bmp');
bitmapReader.random();
var newbmp = fs.readFileSync('./img/randombmp.bmp');
expect(original).to.not.eql(newbmp);
});
});
describe("bitmapReader.random", function() {
before(function(){
testCleanup('./img/randombmp.bmp');
});
after(function(){
testCleanup('./img/randombmp.bmp');
});
it("should modify the bitmap's color palette", function() {
var originalBmp = fs.readFileSync('./img/test.bmp');
var originalColorPalette = originalBmp.slice(54, 1078);
bitmapReader.random();
var newBmp = fs.readFileSync('./img/randombmp.bmp');
var newBmpColorPalette = newBmp.slice(54, 1078);
expect(originalColorPalette).not.to.eql(newBmpColorPalette);
});
});
function testCleanup(dir){
try{
fs.unlinkSync(dir);
} catch(err) {}
}
|
import {esClient} from './client';
import {makebulk, indexall} from './bulkIndex';
export function create(products){
esClient.indices.create({
index: 'prod'
},(err,res,status) => {
if(err){
console.log(err);
}else {
console.log('create',res);
makebulk(products,function(response){
console.log("Bulk content prepared");
indexall(response,function(response){
console.log(response);
})
});
}
});
}
|
/**
* Creates a select box with all unit types in this world
* @param {string} id the DOM ID
* @param {string} select the currently selected unit
*/
function makeUnitBox(id, select) {
var box = "<select id=" + id + ">";
$.each(world_data.units, function (i, v) {
box += "<option value=" + i + (v == select ? " selected" : "") + ">" + trans.tw.units.names[v] + "</option>";
});
box += "</select>";
return box;
}
var menu = "<table width='100%' class='vis'>";
menu += "<tr>";
menu += "<th nowrap width='1%'>";
menu += "<input type=text size=5 id=filterAxeValue value='" + user_data.command.filterMinDefault + "'>";
menu += makeUnitBox("filterAxeType", user_data.command.filterMinDefaultType);
menu += "<input type=button id=filterAxe value='" + trans.sp.troopOverview.filterTroops + "'";
menu += " title='" + trans.sp.troopOverview.filterTroopsTooltip + "'> ";
menu += "</th><th nowrap width='1%'>";
menu += "<select id=filterPopValueType><option value=1>" + trans.sp.all.more + "</option>";
menu += "<option value=-1>" + trans.sp.all.less + "</option></select>";
menu += "<input type=text size=5 id=filterPopValue value='" + user_data.command.filterMinPopulation + "'>";
menu += "<input type=button id=filterPop value='" + trans.sp.troopOverview.filterPopulation + "' title='" + trans.sp.troopOverview.filterPopulationTooltip + "'> ";
menu += "</th><th nowrap width='1%'>";
menu += "<input type=text size=5 id=filterWalkingTimeValue>";
menu += "<input type=button id=filterWalkingTime value='" + trans.sp.troopOverview.filterWalkingTime + "' title='" + trans.sp.troopOverview.filterWalkingTimeTooltip + "'> ";
menu += "</th><th width='95%'>";
menu += "<input type=button id=snobFilter value='" + trans.sp.troopOverview.filterNoble + "' title='" + trans.sp.troopOverview.filterNobleTooltip + "'> ";
menu += "<input type=button id=attackFilter value='" + trans.sp.troopOverview.filterUnderAttack + "' title='" + trans.sp.troopOverview.filterUnderAttackTooltip + "'> ";
menu += "</th><th width='1%'>";
menu += "<input type=button id=calculateStack value='" + trans.sp.troopOverview.calcStack + "' title='" + trans.sp.troopOverview.calcStackTooltip + "'>";
menu += "</th>";
menu += "</tr></table>";
// second row
menu += "<table><tr><th width='1%' nowrap>";
menu += "<input type=checkbox id=defReverseFilter title='" + trans.sp.commands.filtersReverse + "'> " + trans.sp.commands.filtersReverseInfo + ": ";
menu += "</th><th width='1%' nowrap>";
menu += "<input type=text size=12 id=defFilterTextValue value=''>";
menu += "<input type=button id=defFilterText value='" + trans.sp.commands.freeTextFilter + "'>";
menu += "</th><th width='97%' nowrap>";
menu += "<input type=textbox size=3 id=defFilterContinentText maxlength=2><input type=button id=defFilterContinent value='" + trans.sp.commands.continentFilter + "'>";
menu += "</th>";
if (location.href.indexOf('type=there') > -1) {
menu += "<th width='1%'><input type=button id=defRestack value='" + trans.sp.troopOverview.restack + "'></th>";
}
menu += "<th nowrap width='1%' style='padding-right: 8px; padding-top: 3px;'>";
menu += "<input type=checkbox id=sortIt title='" + trans.sp.troopOverview.sortTooltip + "'"
+ (user_data.command.filterAutoSort ? " checked" : "") + "> "
+ trans.sp.troopOverview.sort;
menu += "</th></tr>";
menu += "</table>";
// Sangu filter menu
var sanguMenu = menu;
// Overview table menu
menu = "<tr id=units_table_header>";
menu += "<th>" + trans.sp.troopOverview.village + "</th>";
menu += "<th>" + trans.sp.troopOverview.nightBonus + "</th>";
$.each(world_data.units, function (i, v) {
menu += "<th><img src='/graphic/unit/unit_" + v + ".png' title=\"" + trans.sp.troopOverview.selectUnitSpeed.replace("{0}", trans.tw.units.names[v]) + "\" alt='' id=" + v + " /></th>";
});
if (world_config.hasMilitia) {
menu += "<th><img src='/graphic/unit/unit_militia.png' title='" + trans.tw.units.militia + "' alt='' id=militia /></th>";
}
menu += "<th>" + trans.sp.troopOverview.commandTitle + "</th>";
target = getVillageFromCoords(spTargetVillageCookie());
menu += "<th nowrap>" + trans.sp.all.targetEx
+ " <input type=text id=targetVillage name=targetVillage size=8 value='"
+ (target.isValid ? target.coord : "") + "'>"
+ "<input type=button class='btn' id=targetVillageButton value='"
+ trans.sp.troopOverview.setTargetVillageButton + "'></th>";
menu += "</tr>";
// function to replace the village rows
tableHandler.init("units_table", {
rowReplacer: function (row) {
//q($(row).html());
var mod = "row_a";
var newRow = "";
var finalRow = "";
var addThisRow = true;
var cells = $("td:gt(0)", row);
var units = {};
var villageCell = $("td:first", row);
var villageId = $("span.quickedit-vn", villageCell).attr("data-id");
cells.each(function (index, element) {
if (doFilter && index - 1 == unitIndex && parseInt(this.innerHTML, 10) < unitAmount) {
//q("index:" + index + ' == '+ unitIndex + " : " + row.html() + ' * 1 < ' + unitAmount);
addThisRow = false;
return false;
}
else if (index == rowSize) {
//q(index + "==" + rowSize);
newRow += "<td>";
newRow += "<img src='/graphic/dots/red.png' title='" + trans.sp.troopOverview.removeVillage + "' style='margin-bottom: 2px' /> ";
//newRow += "<img src='https://www.tribalwars.vodka/graphic/delete_small.png' style='margin-bottom: 3px; position: relative' title='" + trans.sp.troopOverview.removeVillage + "' /> ";
newRow += "<a href='" + $("a", element).attr('href').replace("mode=units", "") + "&sanguX=0&sanguY=0' class='attackLinks'>";
newRow += "<img src='/graphic/command/attack.png' title='" + trans.sp.troopOverview.toThePlace + "' style='margin-bottom: 1px' />";
// Works only with leftclick onclick='this.src=\"/graphic/command/return.png\";'
newRow += "</a>";
newRow += "</td>";
} else {
//q("units:" + world_data.units[index - 1]);
var cellDisplay = this.innerHTML;
if (cellDisplay === "0") {
cellDisplay = " ";
}
else if (cellDisplay.indexOf('="has_tooltip"') > -1) {
cellDisplay = cellDisplay.replace('="has_tooltip"', '="has_tooltip" title="'+trans.sp.troopOverview.cheapNobles+'"');
}
newRow += "<td>" + cellDisplay + "</td>";
if (index > 0) {
units[world_data.units[index - 1]] = parseInt(element.innerHTML, 10);
}
// innerHTML can contain a + sign for the nobles: "+" indicates nobles can be rebuild cheaply
// The snobs are not important here
}
});
if (addThisRow) {
var villageType = calcTroops(units);
if (doFilter) {
mod = villageCounter % 2 == 0 ? "row_a" : "row_b";
} else {
mod = !villageType.isDef ? "row_a" : "row_b";
}
var coord = getVillageFromCoords(villageCell.text());
//finalRow += "<tbody>";
finalRow += "<tr arrival='0' data-coord-x='" + coord.x + "' data-coord-y='" + coord.y + "' "
+ " class='row_marker " + mod + (game_data.village.id == villageId ? " selected" : "") + "'>";
finalRow += "<td>" + villageCell.html() + "</td>";
finalRow += newRow;
finalRow += "<td></td></tr>";
//finalRow += "</tbody>";
villageCounter++;
return finalRow;
}
return "";
}
});
var newTable = tableHandler.getReplacedVillageRows();
$("#units_table")
.html("<table width='100%' class='vis' id='units_table' target='false'>" + menu + newTable + "</table>")
.before(sanguMenu);
// Tooltips
$("#defReverseFilter").change( function () {
var isChecked = $(this).is(":checked");
var defTrans = trans.sp.troopOverview;
$("#defFilterContinent").attr("title", isChecked ? defTrans.continentFilterTooltip : defTrans.continentFilterTooltipReverse);
$("#defFilterText").attr("title", defTrans.freeTextFilterTooltip.replace("{filterType}", isChecked ? defTrans.freeTextFilterTooltipFilterTypeWith : defTrans.freeTextFilterTooltipFilterTypeWithout));
});
$("#defReverseFilter").change();
// Initial focus on target inputbox
$('#targetVillage').click(function () {
$(this).focus().select();
});
// "Attacks per page" -> change to # villages in the list
var pageSize = $("input[name='page_size']");
var villageAmountCell = $("#units_table tr:first th:first");
//assert(villageAmountCell.length === 1, "village cell Dorp (xxx) niet gevonden");
villageAmountCell.text(villageAmountCell.text() + " (0)");
function setVillageCount(amount) {
pageSize.val(amount);
villageAmountCell.text(villageAmountCell.text().replace(/\d+/, amount));
}
pageSize.parent().prev().text(trans.sp.overviews.totalVillages);
setVillageCount(villageCounter);
|
define(['backbone', 'Memo', 'MemoView', 'MemoListView', 'CreateView'],
function(Backbone, Memo, MemoView, MemoListView, CreateView) {
'use strict';
return Backbone.Router.extend({
routes: {
'': 'showList',
'show/:id': 'showMemo',
'create': 'createMemo'
},
showList: function () {
this.changeView(new MemoListView());
},
showMemo: function (id) {
var model = new Memo({id: id});
this.changeView(new MemoView({model: model}));
},
createMemo: function () {
this.changeView(new CreateView());
},
changeView: function(view) {
// Remove event handlers and dom from the current view.
if (this.view) {
this.view.undelegateEvents();
this.view.remove();
}
this.view = view;
}
});
});
|
var ccs_cc_args = ccs_cc_args || [];
(function() {
var o = ccs_cc_args; o.push(['_SKey', '730df480']); o.push(['_ZoneId', 'db1ee9db45']);
var o1 = ccs_cc_args; o1.push(['_SKey', '730df480']); o1.push(['_ZoneId', 'db1ee9db46']);
var sc = document.createElement('script');
sc.type = 'text/javascript';
sc.async = true;
sc.src = ('https:' == document.location.protocol ? 'https://' : 'http://') + 'cdn.cnetcontent.com/jsc/h.js';
var n = document.getElementsByTagName('script')[0];
n.parentNode.insertBefore(sc, n);
})();
|
(function(){
$( document ).ready(function() {
var selectedMenuItem = $('.selected-menu-item').val();
$('.top-nav li#' + selectedMenuItem).addClass('nav-active');
});
})();
|
const webpack = require("webpack");
const webpackMerge = require('webpack-merge');
const baseConfig = require('./webpack.base.config.js');
module.exports = function (env) {
return webpackMerge(baseConfig(), {
plugins: [
new webpack.LoaderOptionsPlugin({
minimize: true,
debug: false
}),
new webpack.DefinePlugin({
'process.env': {
'NODE_ENV': JSON.stringify('production')
}
}),
// separate all libs from node modules in a vendor file
new webpack.optimize.CommonsChunkPlugin({
name: 'vendor',
minChunks: function (module) {
// this assumes your vendor imports exist in the node_modules directory
return module.context && module.context.indexOf('node_modules') !== -1;
}
}),
new webpack.optimize.UglifyJsPlugin({
beautify: false,
mangle: {
screw_ie8: true,
keep_fnames: true
},
compress: {
screw_ie8: true
},
comments: false
})
]
})
};
|
const feathers = require('feathers');
const rest = require('feathers-rest');
const socketio = require('feathers-socketio');
const hooks = require('feathers-hooks');
const memory = require('feathers-memory');
const bodyParser = require('body-parser');
const errors = require('feathers-errors');
const errorHandler = require('feathers-errors/handler');
const local = require('feathers-authentication-local');
const jwt = require('feathers-authentication-jwt');
const auth = require('feathers-authentication');
const app = feathers();
app.configure(rest())
.configure(socketio())
.configure(hooks())
.use(bodyParser.json())
.use(bodyParser.urlencoded({ extended: true }))
.configure(auth({ secret: 'supersecret' }))
.configure(local())
.configure(jwt())
.use('/users', memory())
.use('/envelopes', memory())
.use('/', feathers.static(__dirname + '/public'))
.use(errorHandler());
app.service('authentication').hooks({
before: {
create: [
// You can chain multiple strategies
auth.hooks.authenticate(['jwt', 'local'])
],
remove: [
auth.hooks.authenticate('jwt')
]
}
});
app.service('envelopes').hooks({
before: {
create: [
auth.hooks.authenticate('jwt')
],
remove: [
auth.hooks.authenticate('jwt')
],
find: [
auth.hooks.authenticate('jwt')
],
}
});
// Add a hook to the user service that automatically replaces
// the password with a hash of the password before saving it.
app.service('users').hooks({
before: {
find: [
auth.hooks.authenticate('jwt')
],
create: [
local.hooks.hashPassword({ passwordField: 'password' })
]
}
});
// Create a user that we can use to log in
var User = {
'email': 'admin@feathersjs.com',
'password': 'admin',
permissions: ['*']
};
app.service('users').create(User).then(user => {
console.log('Created default user', user);
}).catch(console.error);
const port = 3030;
let server = app.listen(port);
server.on('listening', function () {
console.log(`Feathers application started on localhost:${port}`);
});
|
define("#widget/0.9.8/widget-debug", ["base","$","./daparser"], function(require, exports, module) {
// Widget
// ---------
// Widget 是与 DOM 元素相关联的非工具类组件,主要负责 View 层的管理。
// Widget 组件具有四个要素:描述状态的 attributes 和 properties,描述行为的 events
// 和 methods。Widget 基类约定了这四要素创建时的基本流程和最佳实践。
var Base = require('base');
var $ = require('$');
var DAParser = require('./daparser');
var Widget = Base.extend({
// config 中的这些键值会直接添加到实例上,转换成 properties
propsInAttrs: ['element', 'template', 'model', 'events'],
// 与 widget 关联的 DOM 元素
element: null,
// 默认模板
template: '<div></div>',
// 默认数据模型
model: null,
// 事件代理,格式为:
// {
// 'mousedown .title': 'edit',
// 'click {{attrs.saveButton}}': 'save'
// 'click .open': function(ev) { ... }
// }
events: null,
// 属性列表
attrs: {
// 组件的默认父节点
parentNode: document.body,
// 默认开启 data-api 解析
'data-api': true
},
// 初始化方法,确定组件创建时的基本流程:
// 初始化 attrs --》 初始化 properties --》 初始化 events --》 子类的初始化
initialize: function(config) {
this.cid = uniqueCid();
// 由 Base 提供
Widget.superclass.initialize.call(this, config);
// 由 Widget 提供
this.parseElement();
this._parseDataAttrs();
this.initProps();
this.delegateEvents();
// 由子类提供
this.setup();
},
// 构建 this.element
parseElement: function() {
var element = this.element;
if (element) {
this.element = $(element);
}
// 未传入 element 时,从 template 构建
else if (this.get('template')) {
this.parseElementFromTemplate();
}
// 如果对应的 DOM 元素不存在,则报错
if (!this.element || !this.element[0]) {
throw 'element is invalid';
}
},
// 从模板中构建 this.element
parseElementFromTemplate: function() {
this.element = $(this.get('template'));
},
// 解析 this.element 中的 data-* 配置,获得 this.dataset
// 并自动将 data-action 配置转换成事件代理
_parseDataAttrs: function() {
if (this.get('data-api')) {
this.dataset = DAParser.parse(this.element[0]);
var actions = this.dataset.action;
if (actions) {
var events = getEvents(this) || (this.events = {});
parseDataActions(actions, events);
}
}
},
// 负责 properties 的初始化,提供给子类覆盖
initProps: function() {
},
// 注册事件代理
delegateEvents: function(events, handler) {
events || (events = getEvents(this));
if (!events) return;
// 允许使用:widget.delegateEvents('click p', function(ev) { ... })
if (isString(events) && isFunction(handler)) {
var o = {};
o[events] = handler;
events = o;
}
// key 为 'event selector'
for (var key in events) {
var args = parseEventKey(key, this);
handler = bind(events[key], this);
this.element.on(args.type, args.selector, handler);
}
return this;
},
// 卸载事件代理
undelegateEvents: function(eventKey, handler) {
var cid = this.cid;
var args = {};
// 卸载所有
if (arguments.length === 0) {
args.type = DELEGATE_EVENT_NS + cid;
}
// 卸载特定事件:widget.undelegateEvents('click li', handler);
else {
args = parseEventKey(eventKey, this);
}
// 从 cache 里找到对应的 handler 封装函数
if (handler) {
var handleKey = getHandlerKey(handler, cid);
handler = handlerCache[handleKey];
}
this.element.off(args.type, args.selector, handler);
return this;
},
// 提供给子类覆盖的初始化方法
setup: function() {
},
// 将 widget 渲染到页面上
// 渲染不仅仅包括插入到 DOM 树中,还包括样式渲染等
// 约定:子类覆盖时,需保持 `return this`
render: function() {
// 让用户传入的 config 生效
this.change();
// 插入到文档流中
var parentNode = this.get('parentNode');
if (parentNode && !isInDocument(this.element[0])) {
this.element.appendTo(parentNode);
}
return this;
},
// 在 this.element 内寻找匹配节点
$: function(selector) {
return this.element.find(selector);
},
destroy: function() {
this.undelegateEvents();
Widget.superclass.destroy.call(this);
}
});
module.exports = Widget;
// Helpers
// ------
var toString = Object.prototype.toString;
var cidCounter = 0;
function uniqueCid() {
return 'widget-' + cidCounter++;
}
function isString(val) {
return toString.call(val) === '[object String]';
}
function isFunction(val) {
return toString.call(val) === '[object Function]';
}
function trim(s) {
return s.replace(/^\s*/, '').replace(/\s*$/, '');
}
function isInDocument(element) {
return $.contains(document.documentElement, element);
}
var handlerCache = {};
function bind(handler, widget) {
var handlerKey = getHandlerKey(handler, widget.cid);
var wrap;
if (wrap = handlerCache[handlerKey]) {
return wrap;
}
wrap = function(ev) {
if (isFunction(handler)) {
handler.call(widget, ev);
} else {
widget[handler](ev);
}
};
handlerCache[handlerKey] = wrap;
return wrap;
}
function getHandlerKey(handler, cid) {
var key;
if (isString(handler)) {
key = handler;
}
// 理论上会冲突,但实际上冲突的概率几乎为零
else if (isFunction(handler) && isFunction(handler.toString)) {
key = handler.toString().replace(/\s+/g, '');
}
if (key) {
// 加上 cid, 确保实例间不会冲突
return cid + '-' + key;
}
else {
throw '"handler" must be a string or a function';
}
}
// 解析 data-action,添加到 events 中
function parseDataActions(actions, events) {
for (var action in actions) {
// data-action 可以含有多个事件,比如:click x, mouseenter y
var parts = trim(action).split(/\s*,\s*/);
var selector = actions[action];
while (action = parts.shift()) {
var m = action.split(/\s+/);
var event = m[0];
var method = m[1];
// 默认是 click 事件
if (!method) {
method = event;
event = 'click';
}
events[event + ' ' + selector] = method;
}
}
}
var EVENT_KEY_SPLITTER = /^(\S+)\s*(.*)$/;
var DELEGATE_EVENT_NS = '.delegate-events-';
var EXPRESSION_FLAG = /\{\{([^\}]+)\}\}/g;
var INVALID_SELECTOR = 'INVALID_SELECTOR';
function getEvents(widget) {
if (isFunction(widget.events)) {
widget.events = widget.events();
}
return widget.events;
}
function parseEventKey(eventKey, widget) {
var match = eventKey.match(EVENT_KEY_SPLITTER);
var eventType = match[1] + DELEGATE_EVENT_NS + widget.cid;
var selector = match[2] || '';
if (selector.indexOf('{{') > -1) {
selector = parseEventExpression(selector, widget);
}
return {
type: eventType,
selector: selector
};
}
// 将 {{xx}}, {{yy}} 转换成 .daparser-n, .daparser-m
function parseEventExpression(selector, widget) {
return selector.replace(EXPRESSION_FLAG, function(m, name) {
var parts = name.split('.');
var point = widget, part;
while (part = parts.shift()) {
if (point === widget.attrs) {
point = widget.get(part);
} else {
point = point[part];
}
}
// 已经是 className,比如来自 dataset 的
if (isString(point)) {
return point;
}
// 看是否是 element
var element = $(point)[0];
if (element && element.nodeType === 1) {
return '.' + DAParser.stamp(element);
}
// 不能识别的,返回无效标识
return INVALID_SELECTOR;
});
}
});
|
define(function () {
var create = function (result, options) {
function PageItem(index, css, text) {
var
mode = function () {
if (css === "disabled") { return 1; }
if (css === "active") { return 2; }
return 0;
}();
return {
pageIndex: index,
css: css,
text: text,
mode: mode
}
}
var visibleGroupCount = options.visibleGroupCount || 10,
pagesUpdated = [],
groupIndex = Math.floor((result.pageIndex - 1) / visibleGroupCount),
minPage = groupIndex * visibleGroupCount + 1,
prevPage = minPage - 1,
maxPage = minPage + visibleGroupCount - 1,
nextPage = maxPage + 1;
if (maxPage > result.totalPages) {
maxPage = result.totalPages; nextPage = 0;
}
pagesUpdated.push(new PageItem(minPage, minPage === 1 ? 'disabled' : '', '««'));
pagesUpdated.push(new PageItem(prevPage, prevPage === 0 ? 'disabled' : "", '«'));
for (var i = minPage; i <= maxPage; i++) {
pagesUpdated.push(new PageItem(
i,
result.pageIndex === i ? 'active' : '', i));
}
pagesUpdated.push(new PageItem(nextPage, nextPage === 0 ? "disabled" : "", "»"));
pagesUpdated.push(new PageItem(maxPage, maxPage === result.totalPages ? "disabled" : "", '»»'));
return pagesUpdated;
},
factory = function (results, options) {
return new create(results, options);
}
return {
getInstance: function (results, options) {
return new factory(results, options);
}
};
});
|
// initialize the 2D array with an array in each element
var overworld = [
[[], []],
[[], []]
];
var overWBG = [
[], []
];
overworld[0][0] = [];
overworld[0][0].push("eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee");
overworld[0][0].push("e-----------eeee-------------------------ee----e");
overworld[0][0].push("e-----------eeee-------------------------------e");
overworld[0][0].push("e-----------eeee-------------------------------e");
overworld[0][0].push("e-----------eeee-----------------------eee-----e");
overworld[0][0].push("e-----------eeee------------------ee--e--------e");
overworld[0][0].push("e-----------eeeee-----------------eeee---------e");
overworld[0][0].push("e---------eeeeee-------eeee---eeeeeeee---------e");
overworld[0][0].push("e--------eeee------eeeeeeeeeeeeeeeeeee---------e");
overworld[0][0].push("e-------eeeee-----eeeee-------------eeee-------e");
overworld[0][0].push("e-------eeee-------eeee-------------eee------eee");
overworld[0][0].push("eeeeeeeeeeee--------eeee------------eee----eeeee");
overworld[0][0].push("eeeeee--------------eeee------------eeeeeeeeeeee");
overworld[0][0].push("eeeee---------------eeee------------eeeeeeeeeeee");
overworld[0][0].push("eeee---------------eeee------------------------e");
overworld[0][0].push("eeee---------C-----eeee------------------------e");
overworld[0][0].push("ee-----------------eeee------------------------e");
overworld[0][0].push("ee------------------eeee-----------------------e");
overworld[0][0].push("e-------------------eeee-----------------------e");
overworld[0][0].push("e------------------eeee------------------------e");
overworld[0][0].push("e-----------------eeee-------------------------e");
overworld[0][0].push("ee-----------------eeeee-----------------------e");
overworld[0][0].push("ee-----------------eeee------------------------e");
overworld[0][0].push("ee--eee--------e--eeee-------------------------e");
overworld[0][0].push("ee--eeeeee---eeeeeeee--------------------------e");
overworld[0][0].push("eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee");
overworld[0][0].push("eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee");
overWBG[0][0] = overWorldBG00;
//overworld[1][0] = [];
//overWBG[1][0] = overWorldBG10;
var cave = [
[[], []],
[[], []]
];
cave[0][0] = [];
cave[0][0].push("++++++++++++++++++++++++++++++++++++++++++++++++");
cave[0][0].push("+----------------------------------------------+");
cave[0][0].push("+----------------------------------------------+");
cave[0][0].push("+----------------------------------------------+");
cave[0][0].push("+------------o---------------------------------+");
cave[0][0].push("+-----------------------------o----------------+");
cave[0][0].push("+----------------------------------------------+");
cave[0][0].push("+----------------------------------------------+");
cave[0][0].push("+----------------------------------------------+");
cave[0][0].push("+--------^-------------------------------------+");
cave[0][0].push("+--------x----------------o-------o------------+");
cave[0][0].push("+-----------------------------------------------");
cave[0][0].push("+-----------------------------------------------");
cave[0][0].push("+-----------------------------------------------");
cave[0][0].push("+---------------------------------S-------------");
cave[0][0].push("+-----------------------------------------------");
cave[0][0].push("+----------------------------------------------+");
cave[0][0].push("+----------------------------------------------+");
cave[0][0].push("+----------------------------------------------+");
cave[0][0].push("+---------o------------------------------------+");
cave[0][0].push("+----------------------------------------------+");
cave[0][0].push("+---------------------------------^------------+");
cave[0][0].push("+---------------------------------x------------+");
cave[0][0].push("+----------------------------------------------+");
cave[0][0].push("+------S---------------------------------------+");
cave[0][0].push("+----------------------------------------------+");
cave[0][0].push("++++++++++++++++++++++++++++++++++++++++++++++++");
cave[1][0] = [];
cave[1][0].push("++++++++++++++++++++++++++++++++++++++++++++++++");
cave[1][0].push("+----------------------------------------------+");
cave[1][0].push("+-----------------------o--------------B-------+");
cave[1][0].push("+------o---------------------------------------+");
cave[1][0].push("+--------------------B-------------------------+");
cave[1][0].push("+-------------------------------------o--------+");
cave[1][0].push("+-----------o----------------------------------+");
cave[1][0].push("+------------------------------------------B---+");
cave[1][0].push("+----------------------------------------------+");
cave[1][0].push("+---------------o------------------------------+");
cave[1][0].push("+-------------------------o---------------o----+");
cave[1][0].push("-----------------------------------------------+");
cave[1][0].push("-----------------------------------------------+");
cave[1][0].push("-----------------------------------------------+");
cave[1][0].push("-------------o---------------------------------+");
cave[1][0].push("-----------------------------------------------+");
cave[1][0].push("+---------------------------o------------------+");
cave[1][0].push("+----------------o-----------------------------+");
cave[1][0].push("+----------------------------------------------+");
cave[1][0].push("+---------o------------------------------------+");
cave[1][0].push("+-------------o--------------------------------+");
cave[1][0].push("+---------------------B------------------------+");
cave[1][0].push("+----------------------------------------------+");
cave[1][0].push("+----------------------------------------------+");
cave[1][0].push("+---------o------------------o-----------------+");
cave[1][0].push("+----------------------------------------------+");
cave[1][0].push("+++++++++++++++++++++------+++++++++++++++++++++");
cave[0][1]= [];
cave[0][1].push("++++++++++++++++++++++++++++++++++++++++++++++++");
cave[0][1].push("+----------------------------------------------+");
cave[0][1].push("+----------------------------------------------+");
cave[0][1].push("+----------------------------------------------+");
cave[0][1].push("+----------------------------------------------+");
cave[0][1].push("+-------------------------------o--------------+");
cave[0][1].push("+----------------------------------------------+");
cave[0][1].push("+----------------------------------------------+");
cave[0][1].push("+----------------------------------------------+");
cave[0][1].push("+----------------------------------------------+");
cave[0][1].push("+----------^-----------------------------------+");
cave[0][1].push("+----------x------------------------------------");
cave[0][1].push("+-----------------------S-----------------------");
cave[0][1].push("+----------------------------------------S------");
cave[0][1].push("+-----------------------------------------------");
cave[0][1].push("+-----------------------------------------------");
cave[0][1].push("+----------------------------------------------+");
cave[0][1].push("+--------S-------------------------------------+");
cave[0][1].push("+----------------------------------------------+");
cave[0][1].push("+----------------------------------------------+");
cave[0][1].push("+----------------------------------^-----------+");
cave[0][1].push("+----------------------------------x-----------+");
cave[0][1].push("+----o-----------------------------------------+");
cave[0][1].push("+----------------------------------------------+");
cave[0][1].push("+---------------------------B------------------+");
cave[0][1].push("+----------------------------------------------+");
cave[0][1].push("++++++++++++++++++++++++++++++++++++++++++++++++");
cave[1][1]= [];
cave[1][1].push("+++++++++++++++++++++------+++++++++++++++++++++");
cave[1][1].push("+----------------------------------------------+");
cave[1][1].push("+--------------------------------------^-------+");
cave[1][1].push("+----------------------------o---------x-------+");
cave[1][1].push("+--------^-------------------------------------+");
cave[1][1].push("+--------x-------------------------------------+");
cave[1][1].push("+----------------------------------------------+");
cave[1][1].push("+--------------------------------S-------------+");
cave[1][1].push("+----------------------------------------------+");
cave[1][1].push("+----------------------------------------------+");
cave[1][1].push("+---------------o------------------------------+");
cave[1][1].push("-----------------------------------------------+");
cave[1][1].push("-----------------------------------------------+");
cave[1][1].push("-----------------------------------------------+");
cave[1][1].push("------------------------------------------o----+");
cave[1][1].push("---------------------------^-------------------+");
cave[1][1].push("+--------------------------x-------------------+");
cave[1][1].push("+----------------------------------------------+");
cave[1][1].push("+------S---------------------------------------+");
cave[1][1].push("+----------------------------------------------+");
cave[1][1].push("+----------------------------------------------+");
cave[1][1].push("+---------------------o------------------------+");
cave[1][1].push("+----------------------------------------------+");
cave[1][1].push("+--------------------------------------S-------+");
cave[1][1].push("+---------------^------------------------------+");
cave[1][1].push("+---------------x------------------------------+");
cave[1][1].push("++++++++++++++++++++++++++++++++++++++++++++++++");
var volcano = [
[[], []],
[[], []]
];
volcano[0][0] = [];
volcano[0][0].push("llllllllllllllllllllllllllllllllllllllllllllllll");
volcano[0][0].push("l----------------------------------------------l");
volcano[0][0].push("l----------------------------------------------l");
volcano[0][0].push("l----------------------------------------------l");
volcano[0][0].push("l------------o---------------------------------l");
volcano[0][0].push("l--------------------B--------o----------------l");
volcano[0][0].push("l----------------------------------------------l");
volcano[0][0].push("l----------------------------------------------l");
volcano[0][0].push("l----------------------------------------------l");
volcano[0][0].push("l----------------------------------------------l");
volcano[0][0].push("l---------------------------------o------------l");
volcano[0][0].push("l-----------------------------------------------");
volcano[0][0].push("l---------------o-------------------------------");
volcano[0][0].push("l-----------------------------------------------");
volcano[0][0].push("l---------------------------------B-------------");
volcano[0][0].push("l-----------------------------------------------");
volcano[0][0].push("l-----------------------------------------------");
volcano[0][0].push("l----------------------------------------------l");
volcano[0][0].push("l----------------------------------------------l");
volcano[0][0].push("l---------o------------------------------------l");
volcano[0][0].push("l----------------------------------------------l");
volcano[0][0].push("l----------------------------------------------l");
volcano[0][0].push("l----------------------------------------------l");
volcano[0][0].push("l----------------------------------------------l");
volcano[0][0].push("l----------------------------------------------l");
volcano[0][0].push("l----------------------------------------------l");
volcano[0][0].push("llllllllllllllllllllllllllllllllllllllllllllllll");
volcano[1][0].push("llllllllllllllllllllllllllllllllllllllllllllllll");
volcano[1][0].push("l----------------------------------------------l");
volcano[1][0].push("l---o------------------------------------------l");
volcano[1][0].push("l--------------------------------------o-------l");
volcano[1][0].push("l----------------------------------------------l");
volcano[1][0].push("l--------------------B-------------------------l");
volcano[1][0].push("l----------------------------------------------l");
volcano[1][0].push("l----------------------------------------------l");
volcano[1][0].push("l----------------------------------------------l");
volcano[1][0].push("l-----------o----------------------------------l");
volcano[1][0].push("l------------------------------------B---------l");
volcano[1][0].push("-----------------------------------------------l");
volcano[1][0].push("-----------------------------------------------l");
volcano[1][0].push("-----------------------------------------------l");
volcano[1][0].push("-----------------------------------------------l");
volcano[1][0].push("-----------------------------------------------l");
volcano[1][0].push("----o------------------------------------------l");
volcano[1][0].push("l----------------------------------------------l");
volcano[1][0].push("l----------------------------------------------l");
volcano[1][0].push("l----------------------------------------------l");
volcano[1][0].push("l--------------------o-------------------------l");
volcano[1][0].push("l----------------------------------------------l");
volcano[1][0].push("l-----------------------------------o----------l");
volcano[1][0].push("l----------------------------------------------l");
volcano[1][0].push("l----------------------------------------------l");
volcano[1][0].push("l----------------------------------------------l");
volcano[1][0].push("lllllllllllllllllllll------lllllllllllllllllllll");
volcano[1][1].push("lllllllllllllllllllll------lllllllllllllllllllll");
volcano[1][1].push("l----------------------------------------------l");
volcano[1][1].push("l----------------------------------------------l");
volcano[1][1].push("l-------o--------------------------------------l");
volcano[1][1].push("l----------------------------------------------l");
volcano[1][1].push("l----------------------------------------------l");
volcano[1][1].push("l------------B--------------------------o------l");
volcano[1][1].push("l----------------------------------------------l");
volcano[1][1].push("l----------------------------------------------l");
volcano[1][1].push("l-------------------o--------------------------l");
volcano[1][1].push("l----------------------------------------------l");
volcano[1][1].push("l----------------------------------------------l");
volcano[1][1].push("l----------------------------------------------l");
volcano[1][1].push("l----------------------------------------------l");
volcano[1][1].push("l----------------------------------------------l");
volcano[1][1].push("l----------------------------------------------l");
volcano[1][1].push("l--------------------------------o-------------l");
volcano[1][1].push("l--------B-------------------------------------l");
volcano[1][1].push("l----------------------------------------------l");
volcano[1][1].push("l----------------------------------------------l");
volcano[1][1].push("l----------------------------------------------l");
volcano[1][1].push("l----------------------------------------------l");
volcano[1][1].push("l----------------------------------------------l");
volcano[1][1].push("l--------------o-------------------------------l");
volcano[1][1].push("l----------------------------------------------l");
volcano[1][1].push("l----------------------------------------------l");
volcano[1][1].push("llllllllllllllllllllllllllllllllllllllllllllllll");
|
var e = {
name: 'e',
C: C,
D: D
};
|
'use strict';
/**
* Update a resource.
*
* @param {string}
* @param {object}
* @param {object}
* @param {object}
* @return {Promise}
*/
function update (id, updates, options, context = {}) {
updates = updates || {};
return context.request.put({
uri: context.uri,
body: updates
});
}
module.exports = update;
|
$(document).ready(function(){
//code here...
var code = $(".codemirror-textarea")[0];
var editor = CodeMirror.fromTextArea(code, {
lineNumbers : true,
theme: "eclipse",
mode: "text/x-java", //this is for JAVA
matchBrackets: true
});
});
function sendResposta() {
setTimeout("sendResposta()", 1600);
//console.log("aqui1");
//document.getElementById("resposta").value = "Fifth Avenue, New York City";
//var respos = document.getElementById("resposta");
var text = editor;
//var respos = document.getElementsByTagName("textarea");
console.log(text);
var code1 = code;
//var respos = document.getElementsByTagName("textarea");
console.log(code1);
//console.log
/* var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
response = this.responseText;
if (response != "randori-oficial.php") {
//console.log("if");
document.getElementById("msg").innerHTML = response;
} else {
console.log(response);
window.location.href = response;
//console.log("else");
//document.clear();
//document.write(response);
}
}
};
xhttp.open("POST", "resposta.php", true);
xhttp.send("new_resposta="+);*/
}
sendResposta();
|
// env
if (!process.env.MONGODB_CONNECTION) {
console.log('MONGODB_CONNECTION environment variable required.');
process.exit(1);
}
var mongoose = require('mongoose');
mongoose.connect(process.env.MONGODB_CONNECTION);
var Schema = mongoose.Schema;
var donorSchema = new Schema({
firstName: String,
lastName: String,
contactNumber: String,
emailAddress: String,
bloodGroup: String,
loc: [Number]
});
donorSchema.index({ loc: '2dsphere', bloodGroup: 1 });
// Static methods
/**
* Finds donors near a point.
*
* @param {[Number]} bottomLeft Bottom left corner coordinates.
* @param {[Number]} upperRight Upper right corner coordinates.
* @param {Function} fn Callback.
*/
donorSchema.statics.findDonors = function (bottomLeft, upperRight, fn) {
var query = {
loc: {
$geoWithin: {
$box: [
bottomLeft,
upperRight
]
}
}
};
this.find(query, fn);
};
module.exports = mongoose.model('Donor', donorSchema);
|
// Not rocket science but taken from:
// http://closure-library.googlecode.com/svn/trunk/closure/goog/string/string.js
'use strict';
var value = require('../../Object/valid-value')
, toUint = require('../../Number/to-uint');
module.exports = function (n) {
return new Array((isNaN(n) ? 1 : toUint(n)) + 1).join(String(value(this)));
};
|
'use strict';
/**
* Module dependencies.
*/
require('./config/lib/app').start();
|
import dateFormat from './date'
function toText (val, before, after) {
return Math.abs(val) + (val > 0 ? before : after)
}
function fromNow (date, scope, format) {
let ms = Date.now() - date.getTime()
// 误差修正
if (ms > 0) ms += 1000
else ms -= 1000
const minute = parseInt(ms / 1000 / 60)
const hour = parseInt(minute / 60)
const day = parseInt(hour / 24)
const month = parseInt(day / 30)
const year = parseInt(day / 365)
if (year) {
if (scope >= 6) return toText(year, '年前', '年后')
} else if (month) {
if (scope >= 5) return toText(month, '个月前', '个月后')
} else if (day) {
if (scope >= 4) return toText(day, '天前', '天后')
} else if (hour) {
if (scope >= 3) return toText(hour, '小时前', '小时后')
} else if (minute) {
if (scope >= 2) return toText(minute, '分钟前', '分钟后')
} else if (scope >= 1) return ms > 0 ? '刚刚' : '不到一分钟之后'
// if (year && scope >= 6) return toText(year, '年前', '年后')
// if (month && scope >= 5) return toText(month, '个月前', '个月后')
// if (day && scope >= 4) return toText(day, '天前', '天后')
// if (hour && scope >= 3) return toText(hour, '小时前', '小时后')
// if (minute && scope >= 2) return toText(minute, '分钟前', '分钟后')
// if (scope >= 1) return ms > 0 ? '刚刚' : '不到一分钟之后'
return dateFormat(date, format)
}
const scopeMap = {
'moment': 1,
'second': 1,
'minute': 2,
'hour': 3,
'day': 4,
'month': 5,
'year': 6
}
export default function (date, scope = 'year', format) {
if (typeof date === 'number' || typeof date === 'string' || date instanceof Date) date = new Date(date)
else return ''
if (typeof scope === 'string') scope = scopeMap[scope]
return fromNow(date, scope, format)
}
|
var shoe_data = require('../shoe_catalog.json');
exports.landing = function(req, res) {
res.render('landing', {
message: req.flash('log_out'),
'user': req.user
});
};
exports.search = function(req, res) {
res.render('search', {
'sizes': shoe_data["shoe_sizes"],
'brands': shoe_data["shoe_brands"],
'user': req.user
});
};
exports.alternateSearch = function(req, res) {
res.render('alternateSearch', {
message: req.flash('bad_brand'),
'sizes': shoe_data["shoe_sizes"],
'brands': shoe_data["shoe_brands"],
'user': req.user
});
};
exports.postAddShoe = function(req, res) {
req.flash('log_out', 'Thanks for submitting your brand, we got it :)');
res.redirect('/');
};
|
var co = require('co');
var tablebase = require('../lib').tablebase;
var dataType = require('../lib').dataType;
module.exports = class extends tablebase {
constructor() {
super('table2', 'id',
{
id: {type: dataType.BigInt(true), key: true}, // the auto-incrementing primary key
col2: {type: dataType.VarChar(20)},
col3: {type: dataType.Text()},
col4: {type: dataType.Char(20)},
});
}
};
|
/**
* Created by zhaoxiaoqiang on 2017/1/28.
*/
function p1() {
return new Promise(function (resolve, reject) {
setTimeout(function () {
reject('p1');
}, 2000);
});
}
function p2() {
return new Promise(function (resolve, reject) {
setTimeout(function () {
resolve('p2');
}, 1000);
});
}
Promise.all([p1(), p2()]).then(function (values) {
console.log(values[0] + ',' + values[1]);
}, function (value) {
console.log('reject:' + value);
}).catch(function () {
console.log('catch:' + value);
});
// 控制台输出结果: reject: p1
|
Core.registerModule("canvas",function(sb){
var languages = localConfig.languages;
curLanguage = window.navigator.language.toLocaleLowerCase().match(/zh/) ? languages['zh'] : languages['en'];
var anim_name = {
'none' : curLanguage.anim_slider,
"anim-scale":curLanguage.anim_sliderZoom,
"anim-ySpin":curLanguage.anim_rotateLeft,
"anim-xSpin":curLanguage.anim_rotateRight,
"anim-rightRotate":curLanguage.anim_reverse
},
ANIMATION_LABEL = curLanguage.anim_label,
SCREEN_SIZE_MAP = {
'16:9' : {x:960,y:540},
'8:5' : {x:960,y:600},
'6:5' : {x:600,y:500},
'5:3' : {x:600,y:360},
'4:3' : {x:800,y:600},
'2:1' : {x:1000,y:500},
'1:1' : {x:640,y:640}
},
DATASET_PRE = 'slider',
DEFAULT_SLIDE_TYPE = 'impress',
DEFAULT_SCREEN = '4:3',
canvasX = 1200,
canvasY = 600;
var editor = null,newContainerFunc=null,data_number=0,item,viewY = 80,header=20,isEditor = false,
sliders = new sb.ObjectLink(),currentSlider = null,slider_count = 0,slider_number = 0,
createSliderFunc=null,addSliderElementFunc = null,addSliderObjectFunc = null,moveInter = -1,curKeycode = -1,
SliderDataSet=new sb.ObjectLink(),zIndex_Number = 0,elementSet = new sb.ObjectLink(),editorContainer,
eom=null,easm = null,eomTout=-1,target = null,elementOpertateFunc = null,cancelElementOperateMenuFunc =null,
closeButton =null,easmCloseButton = null,setPositionFunc = null,showAnim = null,easmMove,
copyElem = null,pasteElem=null,addImageFunc = null,addTextFunc = null,copyParams = null,eomItems = null,
rgbSettingItems = null,defaultAtt,setSettingDefaultAttFunc,keyOperate,boxshadowsettingBut,boxshadowsetting,
bgsettingBut,bordersettingBut,bgsetting,bordersetting,settingElements;
var global = {},
rightMenuBtn; //右键选中标志
return {
init : function() {
global = this;
//初始设置幻灯片的长宽
var sMap = SCREEN_SIZE_MAP[DEFAULT_SCREEN];
canvasX = sMap.x;
canvasY = sMap.y;
document.onselectstart = function(){
return false;
}
sb.container.oncontextmenu = function(){
return false;
}
// sb.container.style["marginTop"] = ((window.innerHeight-canvasY-viewY-header)/2+header)+"px";
sb.data("mode", "editor");
defaultAtt = {
backgroundColor:"transparent",
border:"none",
borderColor:"rgb(0, 0, 0)",
borderStyle:"none",
borderWidth:"1px",
borderBottomLeftRadius:"0%",
borderTopLeftRadius:"0%",
borderBottomRightRadius:"0%",
borderTopRightRadius:"0%",
boxShadow:"rgb(0, 0, 0) 0px 0px 10px inset",
WebkitAnimation : "none",
WebkitTransform : "rotate(0deg)",
opacity:"1"
};
editorContainer = sb.find(".container");
sb.css(editorContainer,{
width: canvasX + "px",
height: canvasY + "px"
});
eom = sb.find("#element-operate-menu");
eomItems = sb.query(".elem-item", eom);
// sb.move(eom, eom);
easm = sb.find("#element-attrSetting-menu");
easmMove = sb.query(".move", easm)[0];
sb.css(easmMove,{
height:"20px",
width:"100%",
top:"0px",
left:"0px"
});
sb.move(easmMove,easm);
rgbSettingItems = sb.query(".rgbcolor",easm);
bgsetting = sb.find(".bgsetting",easm);
bordersetting = sb.find(".bordersetting",easm);
boxshadowsetting = sb.find(".boxshadowsetting",easm);
bgsettingBut = sb.find(".bgsetting-but",easm);
bordersettingBut = sb.find(".bordersetting-but",easm);
boxshadowsettingBut = sb.find(".boxshadowsetting-but",easm);
sb.bind(bgsettingBut, "click", function(){
$('.attr-setting-panel').css('display', 'none');
$('.setting-tag').removeClass('text-focus');
$('.bgsetting').css('display', 'block');
$('.bgsetting-but').addClass('text-focus');
});
sb.bind(bordersettingBut, "click", function(){
$('.attr-setting-panel').css('display', 'none')
$('.setting-tag').removeClass('text-focus');
$('.bordersetting').css('display', 'block');
$('.bordersetting-but').addClass('text-focus');
});
sb.bind(boxshadowsettingBut, "click", function(){
$('.attr-setting-panel').css('display', 'none');
$('.setting-tag').removeClass('text-focus');
$('.boxshadowsetting').css('display', 'block');
$('.boxshadowsetting-but').addClass('text-focus');
});
$('.transformsetting-but').on("click", function(){
$('.attr-setting-panel').css('display', 'none');
$('.setting-tag').removeClass('text-focus');
$('.transformsetting').css('display', 'block');
$('.transformsetting-but').addClass('text-focus');
});
settingElements = sb.query(".setting-element",easm);
for (var i = 0,item; item = settingElements[i]; i++) {
var inputType = item.getAttribute("data-input");
var inputElem = sb.find(".value-input",item);
var tar,parent,event,value,type,tarElem,pnumber;
switch(inputType){
case 'checkbox':
inputElem.onchange = function(e){
if(!target||!elementSet[target]) {
tarElem = sliders[currentSlider];
}else{
tarElem = elementSet[target]["container"];
}
tar = e.currentTarget;
parent = tar.parentNode;
event = parent.getAttribute("data-event");
type = parent.getAttribute("data-type");
value = tarElem.style[type];
if(!tar.checked||!value) value = parent.getAttribute("data-param");
sb.notify({
type:event,
data:{
key:type,
value:value
}
});
};
break;
item.getAttribute("data-type");
case 'range':
inputElem.onchange = function(e){
tar = e.currentTarget;
parent = tar.parentNode;
event = parent.getAttribute("data-event");
type = parent.getAttribute("data-type");
pnumber = parent.dataset.number;
var factor = parent.getAttribute("data-factor"),
unit = parent.getAttribute("data-unit");
var multi = parent.dataset.multi || '1';
value = tar.value/parseInt(factor)*parseInt(multi) + unit;
if(pnumber) {
var arr = defaultAtt[type].split(" ");
arr[pnumber] = value;
value = arr.join(" ");
}
sb.notify({
type:event,
data:{
key:type,
value:value
}
});
};
break;
case 'select':
inputElem.onchange = function(e){
tar = e.currentTarget;
parent = tar.parentNode;
event = parent.getAttribute("data-event");
type = parent.getAttribute("data-type");
value = tar.value;
sb.notify({
type:event,
data:{
key:type,
value:value
}
});
};
break;
default:
break;
}
}
closeButton = sb.find(".close-menu", eom);
easmCloseButton = sb.find(".close-menu", easm);
newContainerFunc = this.createElementContainer;
createSliderFunc = this.createSlider;
addSliderElementFunc = this.addSliderElement;
addSliderObjectFunc = this.addSliderObject;
elementOpertateFunc = this.elementOpertate;
addImageFunc = this.addImage;
addTextFunc = this.addText;
cancelElementOperateMenuFunc = this.cancelElementOperateMenu;
setPositionFunc = this.setPosition;
setSettingDefaultAttFunc = this.setSettingDefaultAtt;
currentSlider = currentSlider || this.createSlider("append").id;
editor = sliders[currentSlider];
var showAnim = document.createElement("div"),
showAnimContainer = document.createElement('div'),
label = document.createElement('div'),
$slideType = $(document.createElement("div"));
$(showAnimContainer).append(label).append(showAnim).css({
position : 'absolute',
zIndex : "2",
left : "-95px",
top : "50px"
})
$(label).addClass('showAnim-label').html(ANIMATION_LABEL);
$(showAnim).addClass("showAnim").addClass("blue-block").addClass('animation-setting')
.html(anim_name[$(editor).data("anim")])
.attr('data-title', sb.lang().notice_frameTransition)
.css({
width : "90px"
})
//
var sliderTypeChoosebox = window.ChooseBox.create([
{key : 'impress', value : 'impress'},
{key : 'shower', value : 'shower'},
{key : 'slide', value : 'slide'}
]);
window.ChooseBox.hide(sliderTypeChoosebox);
window.ChooseBox.listen(sliderTypeChoosebox, function (value) {
window.ChooseBox.hide(sliderTypeChoosebox);
$slideType.removeClass('on').html(value);
global._slideType = value;
});
$(sliderTypeChoosebox).find('.close-menu').hide();
$(document.body).append(sliderTypeChoosebox);
global._slideType = DEFAULT_SLIDE_TYPE;
$slideType.addClass("slideType").addClass("blue-block").html(DEFAULT_SLIDE_TYPE)
.css({
position : 'absolute',
backgroundColor : '#CCC',
width : "90px",
zIndex : "2",
left : "-95px",
top : "0px"
})
// .attr('title', '幻灯片的播放类型/左键点击修改')
.attr('data-title', sb.lang().notice_presentationType)
.on('click', function (e) {
if (window.ChooseBox.isHide(sliderTypeChoosebox)) {
$(this).addClass('on');
window.ChooseBox.show(sliderTypeChoosebox);
$(sliderTypeChoosebox).css({
top : e.clientY + 'px',
left : e.clientX + 'px'
});
} else {
$(this).removeClass('on');
window.ChooseBox.hide(sliderTypeChoosebox);
}
});
sb.move(showAnimContainer, showAnimContainer, {top : true});
sb.move($slideType[0], $slideType[0], {top : true});
$(editorContainer).append(showAnimContainer).append($slideType);
sb.bind(window, "keydown",this.keyOperate);
window.addEventListener("resize", function(){
sb.notify({
type:"windowResize",
data:null
});
},false);
closeButton.addEventListener("click", function(){
cancelElementOperateMenuFunc();
}, false);
easmCloseButton.addEventListener("click", function(){
easm.style.display = "none";
}, false);
//共享数据
sb.data("sliderDataSet",SliderDataSet);
sb.data("sliders",sliders);
sb.listen({
"onImportSlider" : this.readData,
'loadTemplFile' : this.loadTemplFile,
"enterEditorMode":this.enterEditorMode,
"enterSaveFile":this.enterSaveFile,
"addImage":this.addImage,
"addVideo" : this.addVideo,
"addText":this.addText,
"addCode":this.addCode,
"addSlider":this.createSlider,
"changeSlider":this.changeSlider,
"deleteSlider":this.deleteSlider,
"insertSlider":this.insertSlider,
"showOperateMenu":this.elementOpertate,
"deleteElement":this.deleteElement,
"moveToBottom":this.moveToBottom,
"moveToTop":this.moveToTop,
"moveDownward":this.moveDownward,
"moveUpward":this.moveUpward,
"copyElement":this.copyElement,
"cutElement":this.cutElement,
"pasteElement":this.pasteElement,
"changeSliderAnim":this.changeSliderAnim,
"elemAttrSetting":this.elemAttrSetting,
"setStyleAttr":this.setStyleAttr,
"changeShowAnim":this.changeShowAnim,
"changeSliderStyle":this.changeSliderStyle,
"windowResize":this.windowResize,
"showFileSystem" : this.hideSliderEditor,
"changeScreenScale" : this.changeScreenScale,
'changeElemBackground' : this.changeElemBackground,
"backgroundSetting" : this.backgroundSetting,
"codeboxSetting" : this.codeboxSetting,
"changeCodeType" : this.changeCodeType,
"codeboxThemeSetting" : this.codeboxThemeSetting,
"autoSaveTimer" : this.autoSaveTimer,
"playSlider" : this.playSlider,
"copySlider" : this.copySlider,
"pasteSlider" : this.pasteSlider,
"enterMapEdtingMode" : this.enterMapEdtingMode,
"updateSliderPositionData" : this.updateSliderPositionData
});
for (i = 0; item = eomItems[i]; i++) {
item.onclick = function(e){
if ( $(e.target).hasClass('menu-disabled') || $(e.target).parent().hasClass('menu-disabled') ) {
return;
}
var notify = e.currentTarget.getAttribute("data-event");
sb.notify({
type:notify,
data:e
});
}
}
for (i = 0; item = rgbSettingItems[i]; i++) {
item.onselectstart = function(){
return false;
};
var redSetting = sb.find(".red-setting",item),
greenSetting = sb.find(".green-setting",item),
blueSetting = sb.find(".blue-setting",item);
var settings = [redSetting,greenSetting,blueSetting],k,setting;
for (k = 0; setting = settings[k]; k++) {
sb.find(".value-input",setting).onchange = function(e){
var tar = e.currentTarget,ancestors = tar.parentNode.parentNode;
var event = ancestors.getAttribute("data-event"),attrName,
attrValue,rPreviewValue,gPreviewValue,bPreviewValue,
dataCheck = ancestors.getAttribute("data-check"),
valueType=ancestors.getAttribute("data-type"),
redSetting = sb.find(".red-setting",ancestors),
greenSetting = sb.find(".green-setting",ancestors),
blueSetting = sb.find(".blue-setting",ancestors),
preview = sb.find(".color-preview",ancestors),
rPreview = sb.find(".preview",redSetting),
gPreview = sb.find(".preview",greenSetting),
bPreview = sb.find(".preview",blueSetting),
rvalue = Math.round(sb.find(".value-input",redSetting).value*255/100),
gvalue = Math.round(sb.find(".value-input",greenSetting).value*255/100),
bvalue = Math.round(sb.find(".value-input",blueSetting).value*255/100);
attrName = valueType;
attrValue = "rgb("+rvalue+", "+gvalue+", "+bvalue+")";
rPreviewValue = "rgb("+(rvalue||0)+", "+(0)+", "+(0)+")";
gPreviewValue = "rgb("+(0)+", "+(gvalue||0)+", "+(0)+")";
bPreviewValue = "rgb("+(0)+", "+(0)+", "+(bvalue||0)+")";
preview.style["backgroundColor"] = attrValue;
rPreview.style["backgroundColor"] = rPreviewValue;
gPreview.style["backgroundColor"] = gPreviewValue;
bPreview.style["backgroundColor"] = bPreviewValue;
if(dataCheck=="true"){
var isAllowChange = sb.find(".value-input",sb.find(".for-"+valueType,easm)).checked;
if(!isAllowChange) return;
}
if(valueType=="boxShadow"){
var darr = defaultAtt[valueType].split(" ");
var varr = attrValue.split(" ");
darr[0] = varr[0];
darr[1] = varr[1];
darr[2] = varr[2];
attrValue = darr.join(" ");
}
else if (valueType=="WebkitTransform") {
attrValue = defaultAtt[valueType].replace(/^rotate\(/,'').replace(/deg\)$/,'');
}
sb.notify({
type:event,
data:{
key:attrName,
value:attrValue
}
});
}
}
}
global._imgSelector = ImageSelector.create(sb, function (dataUrl) {
sb.notify({
type : "changeElemBackground",
data : dataUrl
});
// $(global._imgSelector).boxHide();
}, function () {
sb.notify({
type : "changeElemBackground",
data : 'initial'
});
})
$(document.body).append(global._imgSelector);
sb.move(global._imgSelector, global._imgSelector);
$(global._imgSelector).boxHide();
//代码输入框的代码高亮类型
var choosebox = window.ChooseBox.create([
{key : 'C', value : 'text/x-csrc'},
{key : 'C++', value : 'text/x-c++src'},
{key : 'C#', value : 'text/x-csharp'},
{key : 'Clojure', value : 'text/x-clojure'},
{key : 'CSS', value : 'text/css'},
{key : 'Java', value : 'text/x-java'},
{key : 'Javascript',value : 'text/javascript'},
{key : 'XML/HTML', value : 'text/html'},
{key : 'Shell', value : 'text/x-sh'},
{key : 'SQL', value : 'text/x-sql'},
{key : 'Python', value : 'text/x-python'},
{key : 'Ruby', value : 'text/x-ruby'},
{key : 'PHP', value : 'application/x-httpd-php'},
{key : 'Erlang', value : 'text/x-erlang'},
{key : 'Velocity', value : 'text/velocity'},
{key : 'VB', value : 'text/vbscript'}
]);
//初始隐藏
window.ChooseBox.hide(choosebox);
window.ChooseBox.listen(choosebox, function (value) {
sb.notify({
type : 'changeCodeType',
data : {
key : 'mode',
value : value
}
})
window.ChooseBox.hide(choosebox);
});
$(document.body).append(choosebox);
sb.move(choosebox, choosebox);
global._choosebox = choosebox;
//代码输入框主题
var chooseThemebox = window.ChooseBox.create([
{key : 'default', value : 'default'},
{key : 'blackboard', value : 'blackboard'},
{key : 'cobalt', value : 'cobalt'},
{key : 'eclipse', value : 'eclipse'},
{key : 'elegant', value : 'elegant'},
{key : 'erlang-dark', value : 'erlang-dark'},
{key : 'monokai', value : 'monokai'},
{key : 'lesser-dark', value : 'lesser-dark'},
{key : 'neat', value : 'neat'},
{key : 'night', value : 'night'},
{key : 'rubyblue', value : 'rubyblue'},
{key : 'xq-dark', value : 'xq-dark'},
{key : 'twilight', value : 'twilight'},
{key : 'vibrant-ink', value : 'vibrant-ink'}
]);
//初始隐藏
window.ChooseBox.hide(chooseThemebox);
window.ChooseBox.listen(chooseThemebox, function (value) {
sb.notify({
type : 'changeCodeType',
data : {
key : 'theme',
value : value
}
})
window.ChooseBox.hide(chooseThemebox);
});
$(document.body).append(chooseThemebox);
sb.move(chooseThemebox, chooseThemebox);
global._chooseThemebox = chooseThemebox;
//窗口关闭前的保存文件操作
window.onbeforeunload = function () {
return sb.lang().notice_beforeClose;
}
function mapEditEnterHomePage () {
$('#mapEditingContainer').addClass('dp-none');
$('#mapEditingContainer').find('.impressContainer').html('');
$('#appContainer').removeClass('dp-none');
}
function previewEnterHomePage () {
global._playFrame && $(global._playFrame).remove();
$('#previewContainer').addClass('dp-none');
$('#appContainer').removeClass('dp-none');
}
window.onhashchange = function () {
if (window.location.hash === '') {
switch (global._mode) {
case 'previewMode' :
previewEnterHomePage();
break;
case 'mapEditingMode' :
mapEditEnterHomePage();
break;
default:break;
}
}
}
$('#previewContainer').find('.close-menu').on('click', function () {
window.location.hash = "";
})
$('#mapEditingContainer').find('.close-menu').on('click', function () {
window.location.hash = "";
})
$('#mapEditingContainer').find('.reset-btn').on('click', function () {
var impressContainer = $('#mapEditingContainer').find('.impressContainer')
window.ImpressRender.resetPosition(impressContainer);
});
$('#mapEditingContainer').find('.confirm-btn').on('click', function () {
var impressContainer = $('#mapEditingContainer').find('.impressContainer'),
impressPositionData = window.ImpressRender.readAttributes(impressContainer);
sb.notify({
type : 'updateSliderPositionData',
data : impressPositionData
})
window.location.hash = "";
})
},
//预览
playSlider : function () {
global._createSaveData(function (playHtml) {
window.location.hash = 'preview';
global._mode = 'previewMode';
var $previewContainer = $('#previewContainer'),
iframe = document.createElement('iframe'),
$appContainer = $('#appContainer');
iframe.src= 'about:_blank';
iframe.id = 'preview-frame';
$(iframe).on('load', function () {
var doc = iframe.contentWindow.document;
doc.write(playHtml);
iframe.contentWindow.focus();
})
global._playFrame = iframe;
$previewContainer.append(iframe).removeClass('dp-none');
$appContainer.addClass('dp-none');
})
},
enterMapEdtingMode : function () {
window.location.hash = "mapEditing";
global._mode = 'mapEditingMode';
var $mapEditor = $('#mapEditingContainer'),
$appContainer = $('#appContainer'),
$impressContainer = $mapEditor.find('.impressContainer');
$appContainer.addClass('dp-none');
$mapEditor.removeClass('dp-none');
var dataJson = global._createSliderJSONData(),
datas = {
cntConf : {
'height' : editorContainer.style.height,
'width' : editorContainer.style.width,
},
cntData : dataJson.data
}
window.ImpressRender.render(datas.cntData, datas.cntConf, $impressContainer[0], sb);
},
updateSliderPositionData : function (pData) {
_.each(pData, function (values, key) {
$(sliders[key]).data('x', values.x).data('y', values.y);
})
},
// 定时保存
autoSaveTimer : function () {
//一个定时器定时保存文件
window.setInterval( global.saveTempFile, 1000*5);
},
_hideChooseBox : function () {
window.ChooseBox.hide(global._choosebox);
window.ChooseBox.hide(global._chooseThemebox);
},
backgroundSetting : function () {
$(global._imgSelector).boxShow();
},
/**
* 显示编码语言选择框
**/
codeboxSetting : function () {
global.cancelElementOperateMenu();
ChooseBox.show(global._choosebox);
},
codeboxThemeSetting : function () {
global.cancelElementOperateMenu();
ChooseBox.show(global._chooseThemebox);
},
changeElemBackground : function (dataUrl) {
if (!rightMenuBtn || !dataUrl) return;
if (rightMenuBtn === 'panel') {
sb.notify({
type : "changeSliderStyle",
data : {
key : 'backgroundImage',
value : dataUrl
}
});
} else {
sb.notify({
type : "setStyleAttr",
data : {
key : "backgroundImage",
value : dataUrl
}
})
// var tar = SliderDataSet[currentSlider][rightMenuBtn];
// console.log(tar);
// tar && $(tar.container).css('backgroundImage', dataUrl);
}
},
changeCodeType : function (param) {
if (!rightMenuBtn || rightMenuBtn === 'panel') return;
var tarData = SliderDataSet[currentSlider][rightMenuBtn];
if (tarData.data.tagName !== 'CODE') return;
var codeMirror = tarData.file;
codeMirror.setOption(param.key, param.value)
},
changeScreenScale : function (value) {
var sMap;
sMap = SCREEN_SIZE_MAP[value];
if (!sMap) {
// throw new Error('Unmatched screen size');
sMap = SCREEN_SIZE_MAP[DEFAULT_SCREEN];
}
canvasX = sMap.x;
canvasY = sMap.y;
//更新幻灯片size
global.refreshScreesSize();
sb.notify({
type : "refleshpaintBoard",
data : null
})
},
refreshScreesSize : function () {
$('.container', sb.container).css('height', canvasY + 'px').css('width', canvasX + 'px')
},
//以一种非常恶心的hack手段去删除slider列表
removeSliderByArray : function (rmArray) {
_.each(rmArray , function (item) {
var idNum = item.key.replace(/[a-z]*/g, '');
sb.notify({
type : 'deleteSlider',
data : idNum
})
});
var showSliderNum = sliders.getFirstElement().replace(/[a-z]*/g, '')
sb.notify({
type : "changeSlider",
data : showSliderNum
});
sb.notify({
type : "changeFrame",
data : 'frame' + showSliderNum
})
$('#view').show();
},
renderSlider : function (data) {
var importData = JSON.parse(data),
slidersData = JSON.parse(importData.cntData),
slidersConf = importData.cntConf,
sliderArray = readAsArray(slidersData),
rmArray = sliders.toArray();
//计算比例数
var proportionArr = sb.reduce(parseInt(slidersConf.width), parseInt(slidersConf.height));
//更改屏幕大小
sb.notify({
type : 'changeScreenScale',
data : proportionArr.join(':')
})
render(sliderArray);
global.removeSliderByArray(rmArray);
function readAsArray(data) {
var sliders = [];
// imgCount = 0;
for(var s in data){
if ( data.hasOwnProperty(s) ) {
var elementArray = [];
var elements = data[s].element;
for (var e in elements) {
if(elements.hasOwnProperty(e)){
elementArray.push(elements[e]);
// if (elements[e].type === 'IMG') imgCount ++;
}
}
sliders.push({
data : data[s],
elements : elementArray
// imgCount : imgCount
});
}
}
return sliders;
}
function render(array) {
var slider = array.shift();
if (slider) {
renderElements(slider);
render(array);
}
}
function renderElements (slider, callback) {
var elements = slider.elements;
createSliderFunc('append', {
attr : slider.data['panelAttr'],
anim : slider.data['anim'],
x : slider.data.x,
y : slider.data.y,
});
sb.notify({
type:"importSlider",
data: 'append'
});
var count = 0;
for (var i = 0; i < elements.length; i++) {
var data = elements[i],elem;
global.renderElement(data);
}
}
},
renderElement : function (data) {
var elem;
if(data.type === "DIV"){
sb.notify({
type:"addText",
data: {
paste : true,
attr : data.cAttr,
elemAttr : data.eAttr,
value : decodeURIComponent(data.value)
}
});
}
else if(data.type === "IMG") {
sb.notify({
type:"addImage",
data: {
paste : true,
attr : data.cAttr,
elemAttr : data.eAttr,
pAttr : data.panelAtt,
value : data.value
}
});
}
else if (data.type === "VIDEO") {
global._addVideElement(data.value, {
isPaste : true,
eAttr : data.eAttr,
cAttr : data.cAttr,
value : data.value
})
}
if(data.type === "CODE"){
sb.notify({
type:"addCode",
data: {
paste : true,
attr : data.cAttr,
elemAttr : data.eAttr,
value : data.value,
theme : data.theme,
codeType : data.codeType
}
});
}
},
readData:function (inp) {
var reader = new FileReader();
var file = inp.files.item(0);
reader.readAsText(file, 'UTF-8');
reader.onloadend = function (event) {
// var datajson = reader.result.match(/\<script\ type\=\"text\/html\"\ id\=\"datajson\"\>.*\<\/script\>/);
var datajson = reader.result.match(/\<\!\-\-\[DATA_JSON_BEGIN\]\-\-\>.*\<\!\-\-\[DATA_JSON_END\]\-\-\>/);
if (datajson) {
var data = datajson[0]
.replace(/^\<\!\-\-\[DATA_JSON_BEGIN\]\-\-\>/,'')
.replace(/\<\!\-\-\[DATA_JSON_END\]\-\-\>/,'')
.replace(/^\<script[^\<\>]*\>/,'')
.replace(/\<\/script\>/,'');
global.renderSlider(data);
}
}
},
//恢复缓存文件
loadTemplFile : function (data) {
global.renderSlider(data);
},
destroy:function(){
editor = null;
},
windowResize:function(){
// sb.container.style["marginTop"] = ((window.innerHeight-canvasY-viewY-header)/2+header)+"px";
},
keyOperate:function(event){
if(isEditor) return;
if(!elementSet[target]){
if(event.keyCode ==37||event.keyCode ==39){
var preSlider = sliders.getSlider(event.keyCode ==37?"pre":"next", currentSlider, -1);
preSlider = preSlider||currentSlider;
var number = preSlider.substring("slider".length,preSlider.length);
sb.notify({
type:"changeSlider",
data:number
});
sb.notify({
type:"changeFrame",
data:"frame"+number
});
return;
}
}
// if(event.keyCode ==49){
// event.preventDefault();
// sb.notify({
// type:"enterSaveFile",
// data:null
// });
// }else if(event.keyCode ==50){
// event.preventDefault();
// sb.notify({
// type:"addSlider",
// data:"append"
// });
// }else if(event.keyCode ==51){
// event.preventDefault();
// sb.notify({
// type:"insertSlider",
// data:null
// });
// }
var tar,style,offset = 1;
if(!(tar =elementSet[target])) return;
style = tar.container.style;
var oralT = sb.subPX(style["top"]),oralL = sb.subPX(style["left"]);
if(event.keyCode ==37) {
style["left"] = (oralL-offset)+"px";
}
else if(event.keyCode==39) {
style["left"] = (oralL+offset)+"px";
}
else if(event.keyCode ==38){
style["top"] = (oralT-offset)+"px";
}
else if(event.keyCode ==40){
style["top"] = (oralT+offset)+"px";
}else if(event.keyCode ==27){
sb.removeClass(elementSet[target].container,"element-select");
var parts = sb.query(".element-container-apart", elementSet[target].container);
for (var i = 0; i < parts.length; i++) {
sb.removeClass(parts[i],"show-container-apart");
}
cancelElementOperateMenuFunc();
easm.style.display = "none";
target = null;
return;
}
},
enterEditorMode:function(){
window.location.hash = ''
sb.container.style.display = "block";
sb.bind(window, "keyup",keyOperate);
sb.notify({
type:"showStyleBar",
data:null
});
},
_createThumb : function (sliderIndex, callback) {
var renderElement = sliders[sliderIndex],
curSlider = sliders[currentSlider];
if ( sliderIndex !== currentSlider ) {
renderElement.style.display = 'block';
curSlider.style.display = 'none';
}
html2canvas( [ renderElement ], {
onrendered: function(canvas) {
if ( sliderIndex !== currentSlider ) {
renderElement.style.display = 'none'
curSlider.style.display = 'block';
}
callback && callback(canvas.toDataURL());
}
});
},
_createSliderJSONData : function () {
var json = new sb.ObjectLink(), isHasCode;
SliderDataSet.forEach(function(datasets, sliderIndex){
var readedSliderData = global._readSliderData(datasets, sliderIndex);
if (readedSliderData.isHasCode) isHasCode = true;
json[sliderIndex] = readedSliderData.data;
});
return {
data : json,
isHasCode : isHasCode
}
},
_readSliderData : function (sliderElementDataset, sliderIndex) {
var elementSet = new sb.ObjectLink(), isHasCode = false, slider = {};
sliderElementDataset.forEach(function(data, name){
var sliderElement = {};
sliderElement.type = data["data"].tagName;
sliderElement.cAttr = data["container"].getAttribute("style");
sliderElement.eAttr = data["data"].getAttribute("style");
sliderElement.zIndex = data["zIndex"];
//img.src||video-srouce.src||textbox.src
sliderElement.value = data["data"].src || $(data["data"]).find('.video-source').attr('src') || encodeURIComponent(data["data"].innerHTML);
if(sliderElement.type=="IMG") {
sliderElement.panelAtt = sb.find(".element-panel",data["container"]).getAttribute("style");
}
if (sliderElement.type === 'CODE') {
isHasCode = true;
//code mirror
var doc = data['file'].getDoc();
sliderElement.value = doc.getValue();
sliderElement.codeType = doc.getMode().name;
sliderElement.theme = data['file'].getOption('theme');
}
elementSet[name] = sliderElement;
});
slider["anim"] = sliders[sliderIndex].getAttribute("data-anim");
slider["panelAttr"] = sb.find(".panel", sliders[sliderIndex]).getAttribute("style");
slider["element"] = elementSet;
slider.x = $(sliders[sliderIndex]).data('x');
slider.y = $(sliders[sliderIndex]).data('y');
return {
data : slider,
isHasCode : isHasCode
};
},
_createSaveData : function (callback) {
global._createThumb(sliders.getFirstElement(), function (thumb) {
var sliderJson = global._createSliderJSONData(),
count = 0,
slideType = global._slideType || DEFAULT_SLIDE_TYPE,
datas;
datas = {
cntConf : {
'height' : editorContainer.style.height,
'width' : editorContainer.style.width,
'thumb' : thumb //缩略图
},
cntData : sliderJson.data.toJSONString()
}
var scriptBegin = '<script type="text/javascript">',
scriptEnd = '</script>',
styleBegin = '<style type="text/css">',
styleEnd = '</style>',
stream = JSON.stringify(datas),
header = window._sourceMap.header,
footer = window._sourceMap.footer,
blogHeader = window._sourceMap.blogHeader,
blogFooter = window._sourceMap.blogFooter,
//impress
impressHeader = window._sourceMap.impressHeader,
impressFooter = window._sourceMap.impressFooter,
impressReader = window._sourceMap.impressReader,
impressCSS = window._sourceMap.impressCSS,
impressJS = window._sourceMap.impressJS,
//shower
showerHeader = window._sourceMap.showerHeader,
showerFooter = window._sourceMap.showerFooter,
showerReader = window._sourceMap.showerReader,
showerCSS = window._sourceMap.showerCSS,
showerJS = window._sourceMap.showerJS,
//codeMirror
cmJS = window._sourceMap.cmJS,
cmThemeJS = window._sourceMap.cmThemeJS,
cmCss = window._sourceMap.cmCSS,
cmThemeCSS = window._sourceMap.cmThemeCSS,
//animation lib
animation = window._sourceMap.animationCSS,
drawJS = window._sourceMap.drawJS, //画板(用作批注)
zepto = window._sourceMap.zepto,
dataJsonMarkBegin = '<!--[DATA_JSON_BEGIN]-->',
dataJsonMarkEnd = '<!--[DATA_JSON_END]-->';
var dataHtml = dataJsonMarkBegin + '<script type="text/html" id="datajson">'
+ stream + scriptEnd + dataJsonMarkEnd,
combHTML;
if (slideType === 'impress') {
header = impressHeader, footer = impressFooter;
} else if (slideType === 'shower') {
header = showerHeader, footer = showerFooter;
}
//包含了高亮代码输入框
if (sliderJson.isHasCode) {
header += styleBegin + cmCss + styleEnd +
styleBegin + cmThemeCSS + styleEnd +
scriptBegin + cmJS + scriptEnd +
scriptBegin + cmThemeJS + scriptEnd;
}
switch (slideType) {
case 'impress' :
combHTML = header +
styleBegin + animation + styleEnd +
dataHtml +
styleBegin + impressCSS + styleEnd +
scriptBegin + impressJS + scriptEnd +
scriptBegin + zepto + scriptEnd +
scriptBegin + impressReader + scriptEnd +
footer;
break;
case 'shower' :
combHTML = header +
styleBegin + animation + styleEnd +
dataHtml +
styleBegin + showerCSS + styleEnd +
scriptBegin + zepto + scriptEnd +
scriptBegin + showerReader + scriptEnd +
scriptBegin + showerJS + scriptEnd +
footer;
break;
case 'blog' :;
case 'slide' :
combHTML = header +
styleBegin + animation + styleEnd +
dataHtml +
scriptBegin + zepto + scriptEnd +
scriptBegin + drawJS + scriptEnd +
footer;
break;
}
// if (isImpressSlider) {
// }
// else if (sliderJson.isHasCode) { //按需添加代码片段
// combHTML = header +
// styleBegin + cmCss + cmThemeCSS + animation + styleEnd +
// dataHtml +
// scriptBegin + cmJS + cmThemeJS + scriptEnd +
// scriptBegin + zepto + scriptEnd +
// scriptBegin + drawJS + scriptEnd +
// footer
// } else { //不需要添加codemirror的代码
// combHTML = header +
// styleBegin + animation + styleEnd +
// dataHtml +
// scriptBegin + zepto + scriptEnd +
// scriptBegin + drawJS + scriptEnd +
// footer
// }
callback && callback(combHTML)
});
},
enterSaveFile:function(){
global._createSaveData(function (data) {
sb.notify({
type : 'preSave',
data : data
})
});
},
//缓存文件
saveTempFile : function () {
var dataJson = global._createSliderJSONData(),
datas = {
cntConf : {
'height' : editorContainer.style.height,
'width' : editorContainer.style.width,
},
cntData : dataJson.data.toJSONString()
}
sb.notify({
type : "beforeCloseSave",
data : JSON.stringify(datas)
});
},
hideSliderEditor : function () {
sb.unbind(window, "keyup", keyOperate);
sb.container.style.display = "none";
$(global._imgSelector).boxHide();
sb.notify({
type:"hiddenStyleBar",
data:null
});
},
insertSlider:function(){
createSliderFunc("insert", currentSlider);
},
//新添加:sliderId
deleteSlider : function(delId){
delId = !_.isEmpty(delId) ? 'slider' + delId : delId;
var tarSlider = delId || currentSlider,
oralCur = currentSlider,
preSlider = sliders.getSlider("pre", tarSlider, -1) ||
sliders.getSlider("next", tarSlider, -1);
oralCur && ( sliders[oralCur].style.display = "none");
if(tarSlider){
//删除slider DOM 元素
editorContainer.removeChild(sliders[tarSlider]);
delete sliders[tarSlider];
delete SliderDataSet[tarSlider]
currentSlider = preSlider;
}
//如果之前显示的元素为显示,那么就隐藏它
//显示可能被隐藏的前slider
if(preSlider&&sliders[preSlider]) sliders[preSlider].style.display = "block";
else {
//如果前slider不存在,那么就创建新的
createSliderFunc("append");
}
},
createSlider:function(method, pasteObj){
var opDataId = null;
if ( method && ( typeof(method) === 'object' ) ) {
var param = method;
method = param.method;
opDataId = 'slider' + param.dataId;
}
var newSlider = document.createElement("div");
var panel = document.createElement("div");
if (pasteObj) {
panel.setAttribute("style", pasteObj.attr);
newSlider.setAttribute("data-anim", pasteObj.anim);
newSlider.setAttribute("data-anim", pasteObj.anim);
!_.isEmpty(pasteObj.x) && $(newSlider).data('x', pasteObj.x);
!_.isEmpty(pasteObj.y) && $(newSlider).data('y', pasteObj.y);
} else {
panel.setAttribute("style", "width:100%;height:100%;position:absolute;left:0;top:0;background-size:99.99% 100%;background-position:center;");
newSlider.setAttribute("data-anim", "none");
}
panel.className = "panel";
//左键点击取消选中
elementOpertateFunc("panel",panel);
newSlider.appendChild(panel);
newSlider.className = "editor";
newSlider.zIndex = 1;
if(currentSlider) sliders[currentSlider].style.display = "none";
slider_number++;
slider_count++;
var sliderID = "slider" + slider_number;
if(method == "insert"){
var curElemId = opDataId || currentSlider;
addSliderObjectFunc({
key : sliderID,
value : newSlider
}, method, curElemId);
addSliderElementFunc(newSlider, method, sliders[curElemId], editorContainer);
} else if(method == "append"){
addSliderObjectFunc({
key:sliderID,
value:newSlider
}, method, null);
addSliderElementFunc(newSlider, method, null, editorContainer);
}
currentSlider = sliderID;
editor = sliders[currentSlider];
sb.notify({
type : "changeShowAnim",
data : editor.getAttribute("data-anim")
});
return {
id:sliderID,
slider:newSlider
};
},
addSliderObject:function(slider,method,pos){
if(method=="insert") {
SliderDataSet.insert({
key:slider.key,
value:new sb.ObjectLink()
},"before",pos);
sliders.insert(slider,"before",pos);
}
else if(method=="append") {
SliderDataSet[slider.key] = new sb.ObjectLink();
sliders[slider.key] = slider.value;
}
else Core.log("wrong insert slider method!");
},
addSliderElement:function(elem,method,pos,container){
if(method=="insert") container.insertBefore(elem, pos);
else if(method=="append") container.appendChild(elem);
else Core.log("wrong insert slider-Element method!");
},
_addVideoConfig : function (container, video, options) {
video.setAttribute("draggable", false);
$(video).addClass('normalelement');
var partSize = 6,
dataID;
// sb.move(container, container);
if (options && options.isPaste) { //元素粘贴
$(container).attr('style', options.cAttr);
}
else
$(container).attr("style", "position:absolute;z-index:1;left:0px;top:0px;");
container.appendChild(video);
editor.appendChild(container);
var dataID = global._insetIntoDataset(container, video, null);
elementOpertateFunc(dataID, container, container);
return dataID;
},
_addVideElement : function (dataUrl, options) {
var video = document.createElement('video');
src = document.createElement('source');
preCont = document.createElement('div'),
isPaste = options && options.isPaste;
$(video).attr('controls', true).append(src);
$(src).attr('type','video/mp4').attr('src', dataUrl).addClass('video-source');
var dataId = global._addVideoConfig(preCont, video, options);
$(video).on('loadedmetadata', function () {
var sizeObj = {
height : video.clientHeight,
width : video.clientWidth
}
, partSize = 6
, con_obj=null
, type = null;
sizeObj = sb.fixedImgSize(sizeObj,canvasX,canvasY);
newContainerFunc(sizeObj, partSize, null, {
'container' : preCont,
'type' : type,
'isFixedSize' : !isPaste
});
video.style.height = '100%';
video.style.width = '100%';
global.refleshSliderFrame(currentSlider);
options && options.callback && options.callback.call(global, dataId);
})
},
addVideo : function (fileInp) {
sb.readFileData(fileInp, global._addVideElement);
},
addImage:function(obj, callback){
var img = null,file;
var preCont = document.createElement('div');
editor.appendChild(preCont);
//粘贴图片
if(obj["paste"]) {
img = new Image();
img.src= obj["value"];
file = null;
}
//添加图形
else if (obj['shape']) {
img = new Image();
img.src= obj["value"];
file = obj["value"];
}
//添加图片
else {
img = sb.addImage(obj);
file = obj.files.item(0);
}
if(!img) {
return;
}
var imgElementId = addImageConfig(preCont, img, obj);
img.onload = function(){
var sizeObj = {
height:img.height,
width:img.width
};
var partSize = 8,con_obj=null, type = obj.shape ? 'shape' : (obj.paste ? 'paste' : null)
sizeObj = sb.fixedImgSize(sizeObj,canvasX,canvasY);
newContainerFunc(sizeObj,partSize, null, {
'container' : preCont,
'type' : type,
'isFixedSize' : !obj.paste
});
img.style.height = '100%';
img.style.width = '100%';
global.refleshSliderFrame(currentSlider);
callback && callback(imgElementId)
}
function addImageConfig (container, img, obj) {
img.setAttribute("draggable", false);
img.className = "imgelement";
var panel = document.createElement("div");
panel.className = "element-panel";
if (obj.pAttr) {
$(panel).attr('style', obj.pAttr);
}
else {
sb.css(panel, {
position:"absolute",
top:"0px",
left:"0px",
width:"100%",
height:"100%"
});
}
var partSize = 8,dataID,maxZIndexElem,maxZIndex,cur;
sb.move(panel, container);
if(obj["paste"]) {
container.setAttribute("style", obj["attr"]);
img.setAttribute('style', obj["elemAttr"]);
}
else {
container.setAttribute("style", "position:absolute;z-index:1;left:0px;top:0px;background-position:center;background-size:99.99% 100%;");
}
container.appendChild(img);
container.appendChild(panel);
editor.appendChild(container);
var dataID = global._insetIntoDataset(container, img, file);
elementOpertateFunc(dataID, container, container);
return dataID;
}
return imgElementId;
},
addText:function(textObj){
var obj = {
height:50,
width:300
};
var partSize = 8,dataID;
var textBox = document.createElement("div");
textBox.className = "textboxelement";
var con_obj = newContainerFunc(obj, partSize,textBox);
var container = con_obj.container;
$(container).css({
font : 'initial',
color : 'initial',
lineHeight : 'initial',
letterSpacing : 'initial'
});
if(textObj["paste"]){
container.setAttribute("style", textObj["attr"]);
textBox.setAttribute("style", textObj["elemAttr"]);
textBox.innerHTML = textObj["value"];
}else{
container.setAttribute("style", "position:absolute;left:"+((canvasX-obj.width)/2)+"px;top:"+((canvasY-obj.height)/2)+"px;");
textBox.setAttribute("style", "height:"+obj.height+"px;width:"+obj.width+"px;overflow:hidden;outline: none;");
}
container.style.zIndex = global._getMaxZIndex(currentSlider);
textBox.setAttribute("contenteditable", "true");
container.appendChild(textBox);
editor.appendChild(container);
isEditor = true;
dataID = global._insetIntoDataset(container, textBox)
elementOpertateFunc(dataID,con_obj.container,con_obj.container);
// editorElem = textBox;
document.onselectstart = function(){
return true;
}
$(textBox).on('focus', function(e){
document.onselectstart = function(){
return true;
}
if(!isEditor) {
// $(".containerHeader").removeClass('dp-none')
isEditor = true;
}
})
$(textBox).on('click', function() {
global.setSelect(dataID);
});
$(textBox).on('blur', function(e){
document.onselectstart = function(){
return false;
}
if(isEditor) {
isEditor = false;
}
});
global.steTextEdit(textBox);
textBox.focus();
//选中
global.setSelect(dataID);
global.refleshSliderFrame(currentSlider);
return dataID;
},
steTextEdit : function (textbox) {
var isSelectDown = false;
textbox.onmousedown = function () {
// global.checkTextHighlighting ( textbox ) ;
}
$(document).on('mouseup', function( event ) {
global.checkTextHighlighting( textbox );
});
//Ctrl + A
textbox.onkeydown = function (e) {
if (e.keyCode === 65 && e.ctrlKey) {
isSelectDown = true
}
}
textbox.onkeyup = function () {
if (isSelectDown) {
global.checkTextHighlighting ( textbox ) ;
isSelectDown = false;
}
}
// $(textbox).on('blur', function () {
// $("#execCommand-detail").addClass('dp-none');
// })
},
onSelectorBlur : function () {
},
updateToolbarStates : function () {
if (global._currentNodeList) {
if (global._currentNodeList['I']) {
$("#execCommand-detail").find(".font-italic").addClass('active');
}
if (global._currentNodeList['B']) {
$("#execCommand-detail").find(".font-bold").addClass('active');
}
if (global._currentNodeList['U']) {
$("#execCommand-detail").find(".font-underline").addClass('active');
}
if (global._currentNodeList['STRIKE']) {
$("#execCommand-detail").find(".font-strike").addClass('active');
}
}
},
checkTextHighlighting : function (container) {
var selection = window.getSelection();
if (!selection.focusNode) return;
var offset = $(selection.focusNode.parentNode).offset();
global._currentNodeList = global.findNodes(selection.focusNode, container);
var range = selection.getRangeAt(0),
start = range.startOffset,
end = range.endOffset;
if (selection.isCollapsed && start === end) {
$("#execCommand-detail").addClass('dp-none')
}
else {
$("#execCommand-detail").find('.execCommand-item').removeClass('active');
$("#execCommand-detail").removeClass('dp-none')
setTimeout(function () {
var left = offset.left - $("#execCommand-detail").offset().width /2,
fixLeft = left < 0 ? 0 : left,
top = offset.top - $("#execCommand-detail").offset().height - 10,
fixTop = top < 0 ? offset.bottom + $("#execCommand-detail").offset().height : top;
$("#execCommand-detail").css({
left : fixLeft,
top : fixTop
});
});
global.updateToolbarStates();
}
},
findNodes : function( element, container ) {
var nodeNames = {};
while ( element && element.parentNode && element.parentNode !== container) {
nodeNames[element.nodeName] = true;
element = element.parentNode;
if ( element.nodeName === 'A' ) {
nodeNames.url = element.href;
}
}
return nodeNames;
},
addCode : function (pasteParam) {
pasteParam || (pasteParam = {});
var textArea = document.createElement('code'),
codeWrap = document.createElement('code'),
partSize = 8,
defaultValue = '',
defaultTheme = 'blackboard',
defaultMode = '',
containerDatas = newContainerFunc({
"height" : 400,
"width" : 500
}, partSize, null, {
"isFixedSize" : true
});
$(textArea).attr("contenteditable", "true").css({
height : "100%",
width : "100%",
position : 'relative'
})
$(codeWrap).css({
height : '100%',
width : '100%',
position : 'absolute'
}).addClass('normalelement');
/*paste code*/
if(pasteParam["paste"]){
containerDatas.container.setAttribute("style", pasteParam["attr"]);
codeWrap.setAttribute("style", pasteParam["elemAttr"]);
defaultValue = pasteParam["value"];
defaultTheme = pasteParam['theme'];
defaultMode = pasteParam['codeType'];
}
/**********/
codeWrap.appendChild(textArea)
$(containerDatas.container).append(codeWrap);
containerDatas.container.style.zIndex = global._getMaxZIndex(currentSlider);
$(containerDatas.container).css({
font : 'initial',
color : 'initial',
lineHeight : 'initial',
letterSpacing : 'initial'
});
editor.appendChild(containerDatas.container)
var codeMirror = CodeMirror(textArea, {
value: defaultValue,
mode: defaultMode,
theme : defaultTheme,
lineNumbers : true,
lineWrapping : true //长行换行,不滚动
});
codeMirror.on('focus', function () {
if(!isEditor) isEditor = true;
});
codeMirror.on('blur', function () {
isEditor = false;
});
var dataId = global._insetIntoDataset(containerDatas.container, codeWrap, codeMirror);
elementOpertateFunc(dataId, containerDatas.container, containerDatas.container);
global.refleshSliderFrame(currentSlider);
return dataId;
},
//添加svg矢量图
addSvg : function () {
//TODO
},
_getMaxZIndex : function (curSlider) {
var cur = SliderDataSet[currentSlider];
maxZIndexElemID = cur.getLastElement();
return (maxZIndexElemID == null ? 1 : cur[maxZIndexElemID]["zIndex"] + 1);
},
_insetIntoDataset : function (container, subElem, file) {
var dataID,
maxZIndex;
data_number ++;
zIndex_Number ++;
dataID = "data" + data_number; ///当前元素的序号
maxZIndex = global._getMaxZIndex(currentSlider);
container.style.zIndex = maxZIndex;
elementSet[dataID] = {
"container" : container,
"data" : subElem,
"zIndex" : maxZIndex,
"file" : file
}
SliderDataSet[currentSlider][dataID] = elementSet[dataID];
SliderDataSet[currentSlider].sortBy("zIndex");
return dataID;
},
elemAttrSetting:function(e){
var tar;
// eom.style.display = "none";
global.cancelElementOperateMenu();
easm.style.display = "block";
setPositionFunc(e,easm,-100,-100,-300,-200);
if(target && ( tar = elementSet[target])){
tar = elementSet[target].container;
}else{
/*设置slider的属性*/
tar = sb.find(".panel",editor);
}
for (var att in defaultAtt) {
if(tar.style.hasOwnProperty(att)&&tar.style[att].length!=0){
defaultAtt[att] = tar.style[att];
}
}
setSettingDefaultAttFunc();
},
setSettingDefaultAtt:function(){
var i,
type,
pnumber,
attrValue;
for (i = 0;item = rgbSettingItems[i];i++) {
var redSetting = sb.find(".red-setting",item),
greenSetting = sb.find(".green-setting",item),
blueSetting = sb.find(".blue-setting",item),
preview = sb.find(".color-preview",item),
rPreview = sb.find(".preview",redSetting),
gPreview = sb.find(".preview",greenSetting),
bPreview = sb.find(".preview",blueSetting),
rgbArr;
type = item.getAttribute("data-type");
if (rightMenuBtn === 'panel') {
attrValue = sliders[currentSlider].style[type] || defaultAtt[type];
} else {
attrValue = SliderDataSet[currentSlider][rightMenuBtn].container.style[type] || defaultAtt[type];
}
if(type=="boxShadow") {
var splitArr = defaultAtt[type].split(" ");
var rgbdivArr = [splitArr[0],splitArr[1],splitArr[2]];
rgbArr = sb.subrgb(rgbdivArr.join(" "));
}else{
rgbArr = sb.subrgb(defaultAtt[type]);
}
if(rgbArr){
var rv = Math.round(rgbArr[0]*100/255),
gv = Math.round(rgbArr[1]*100/255),
bv = Math.round(rgbArr[2]*100/255);
sb.find(".value-input",redSetting).value = rv;
sb.find(".value-input",greenSetting).value = gv;
sb.find(".value-input",blueSetting).value = bv;
rPreview.style["backgroundColor"] = "rgb("+rgbArr[0]+","+0+","+0+")";
gPreview.style["backgroundColor"] = "rgb("+0+","+rgbArr[1]+","+0+")";
bPreview.style["backgroundColor"] = "rgb("+0+","+0+","+rgbArr[2]+")";
preview.style["backgroundColor"] = "rgb("+rgbArr[0]+","+rgbArr[1]+","+rgbArr[2]+")";
}
}
for (i = 0,item; item = settingElements[i]; i++) {
var inputType = item.dataset.input;
var inputElem = sb.find(".value-input",item),
param,value;
switch(inputType){
case 'checkbox':
type = item.dataset.type;
value = defaultAtt[type];
param = item.dataset.param;
if(value===param) inputElem.checked = false;
else inputElem.checked = true;
break;
case 'range':
type = item.dataset.type;
pnumber = item.dataset.number;
var factor = item.dataset.factor,
unit = item.dataset.unit,
dvalue = defaultAtt[type];
if(pnumber) dvalue = dvalue.split(" ")[pnumber];
var multi = item.dataset.multi || '1';
inputElem.value = parseInt(dvalue)*factor/multi;
break;
case 'select':
type = item.dataset.type;
value = defaultAtt[type];
inputElem.value = value;
break;
default:
break;
}
}
},
setStyleAttr:function(params){
var key = params.key,value = params.value;
defaultAtt[key] = value;
var target = rightMenuBtn;
if(target && elementSet[target]){
var container = elementSet[target].container;
var img,elemAtt = {
borderTopLeftRadius:true,
borderBottomLeftRadius:true,
borderTopRightRadius:true,
borderBottomRightRadius:true,
boxShadow:true,
opacity : true
};
if((img = sb.find("img",container))&&elemAtt[key]) {
sb.find(".element-panel",container).style[key] = value;
img.style[key] = value;
}
else if (key === 'WebkitTransform') {
container.style[key] = 'rotate(' + value + 'deg)';
}
if (key === 'fontSize' && elementSet[target].data.tagName === 'CODE') {
elementSet[target].file.refresh();
}
if (key !== 'opacity' && key !== 'WebkitTransform') container.style[key] = value;
if (key === 'borderWidth' && !container.style.borderStyle) container.style.borderStyle = 'solid';
}else{
var compatibleAtt = {
backgroundColor:true,
opacity:true,
boxShadow:true
};
/*提供设置slider属性的接口*/
if(compatibleAtt[key]) {
sb.notify({
type:"changeSliderStyle",
data:{
key:key,
value:value
}
})
}
}
},
changeSliderStyle:function(data){
sb.find(".panel",editor)["style"][data.key] = data.value;
},
moveUpward:function(){
var target = rightMenuBtn;
var cur = SliderDataSet[currentSlider];
var maxElemID = cur.getLastElement(),tmp,forwardIndex = -1,forwardElemID,forwardElem,
targetIndex;
if(target && maxElemID !== target){
targetIndex = cur.findIndex(target);
forwardIndex = targetIndex+1;
forwardElemID = cur.getSlider(null, null, forwardIndex);
forwardElem = cur[forwardElemID];
tmp = forwardElem["zIndex"];
forwardElem["zIndex"] = cur[target]["zIndex"];
cur[target]["zIndex"] = tmp;
forwardElem["container"].style.zIndex = forwardElem["zIndex"];
cur[target]["container"].style.zIndex = cur[target]["zIndex"];
cur.sortBy("zIndex");
}
},
moveDownward:function(){
var target = rightMenuBtn;
var cur = SliderDataSet[currentSlider];
var minElemID = cur.getFirstElement(),tmp,backwardIndex = -1,backwardElemID,backwardElem,
targetIndex;
if(target && minElemID !== target){
targetIndex = cur.findIndex(target);
backwardIndex = targetIndex-1;
backwardElemID = cur.getSlider(null, null, backwardIndex);
backwardElem = cur[backwardElemID];
tmp = backwardElem["zIndex"];
backwardElem["zIndex"] = cur[target]["zIndex"];
cur[target]["zIndex"] = tmp;
backwardElem["container"].style.zIndex = backwardElem["zIndex"];
cur[target]["container"].style.zIndex = cur[target]["zIndex"];
cur.sortBy("zIndex");
}
},
moveToTop:function(){
var target = rightMenuBtn;
var maxElemID = SliderDataSet[currentSlider].getLastElement(),maxZIndex = 0,maxElem;
maxElem = SliderDataSet[currentSlider][maxElemID];
maxZIndex = maxElem.zIndex+1;
if(target && target!=maxElemID){
SliderDataSet[currentSlider][target]["zIndex"] = maxZIndex;
SliderDataSet[currentSlider][target]["container"].style.zIndex = maxZIndex;
SliderDataSet[currentSlider].sortBy("zIndex");
}
},
moveToBottom:function(){
var target = rightMenuBtn;
var minElemID = SliderDataSet[currentSlider].getFirstElement(),minZIndex = 0,minElem;
minElem = SliderDataSet[currentSlider][minElemID];
minZIndex = minElem.zIndex;
if(target && target!=minElemID){
SliderDataSet[currentSlider].forEach(function(a){
a["zIndex"]++;
a["container"].style.zIndex = a["zIndex"];
});
SliderDataSet[currentSlider][target]["zIndex"] = minZIndex;
SliderDataSet[currentSlider][target]["container"].style.zIndex = minZIndex;
SliderDataSet[currentSlider].sortBy("zIndex");
}
},
//元素的剪切
cutElement : function () {
sb.notify({
type : 'copyElement',
data : null
})
sb.notify({
type : 'deleteElement',
data : null
})
},
deleteElement:function(){
var globalTar = target;
delTarget = rightMenuBtn;
if(!delTarget) return;
var elemNum = delTarget;
if(elementSet[elemNum].container) sliders[currentSlider].removeChild(elementSet[elemNum].container);
delete elementSet[elemNum];
delete SliderDataSet[currentSlider][elemNum];
eom.style.display = "none";
//将左键选中的目标也删除
if(globalTar == rightMenuBtn) {
target = null;
}
},
copyElement:function(){
if(!rightMenuBtn) return;
//右键选中复制目标
copyElem = rightMenuBtn;
if(copyElem && elementSet[copyElem]){
var pasteElem = elementSet[copyElem];
var container = pasteElem.container,data = pasteElem.data,
value = data.src || data.innerHTML;
data.tagName === 'VIDEO' && ( value = $('.video-source', data).attr('src') );
// data.tagName === 'CODE' && (value = pasteElem.file.getDoc().getValue());
copyParams = {
paste : true,
type : data.tagName,
value : value,
attr : container.getAttribute("style"),
elemAttr: data.getAttribute("style"),
pAttr : data.tagName === 'IMG' ? $(container).find('.element-panel').attr("style") : ''
};
if ( data.tagName === 'CODE' ) {
copyParams.value = pasteElem.file.getDoc().getValue();
copyParams.theme = pasteElem.file.getOption('theme');
copyParams.codeType = pasteElem.file.getOption('mode');
}
}
},
pasteElement : function(){
if(copyParams){
//image
if(copyParams["type"]=="IMG") {
addImageFunc(copyParams, function (imgElementId) {
global.setSelect(imgElementId);
});
}
//textArea
else if(copyParams["type"]=="DIV") {
var textElementId = addTextFunc(copyParams);
global.setSelect(textElementId);
}
//video
else if (copyParams["type"] === 'VIDEO') {
global._addVideElement (copyParams.value, {
eAttr : copyParams.elemAttr,
cAttr : copyParams.attr,
isPaste : true,
type : copyParams.type,
callback : function (dataId) {
global.setSelect(dataId);
}
});
}
//code textarea inputbox
else if (copyParams["type"]=="CODE") {
var textElementId = global.addCode(copyParams);
global.setSelect(textElementId);
}
}
},
copySlider : function (sliderId) {
if (!sliderId) return;
var sliderData = global._readSliderData(SliderDataSet[DATASET_PRE + sliderId], DATASET_PRE + sliderId).data;
global._copySliderParam = sliderData;
},
pasteSlider : function (sliderId) {
global._copySliderParam && global.renderElements(global._copySliderParam, sliderId);
},
renderElements : function (slider, sliderId) {
var elements = slider.element;
global.createSlider({
'method' : 'insert',
'dataId' : sliderId
}, {
attr : slider['panelAttr'],
anim : slider['anim'],
x : slider.x,
y : slider.y
});
sb.notify({
type:"importSlider",
data: {
'method' : 'insert',
'dataId' : sliderId
}
});
elements.forEach(function (data, name) {
global.renderElement(data);
})
},
refleshSliderFrame : function (sliderId) {
var idNum = sliderId.replace('slider', '');
sb.notify({
type : "changeSlider",
data : idNum
});
sb.notify({
type : "changeFrame",
data : 'frame' + idNum
});
},
changeSlider:function(snum){
var sliderID = "slider" + snum;
if(!sliders[sliderID]) {
Core.log("Slider is not exist!");
return;
}
if(currentSlider&&sliders[currentSlider]){
sliders[currentSlider].style.display = "none";
}
sliders[sliderID].style.display = "block";
currentSlider = sliderID;
editor = sliders[currentSlider];
sb.notify({
type : "changeShowAnim",
data : editor.getAttribute("data-anim")
});
cancelElementOperateMenuFunc();
easm.style.display = "none";
if(target){
sb.removeClass(elementSet[target].container,"element-select");
var parts = sb.query(".element-container-apart", elementSet[target].container);
for (var i = 0; i < parts.length; i++) {
sb.removeClass(parts[i],"show-container-apart");
}
target = null;
}
},
//取消显示右键菜单
cancelElementOperateMenu:function(){
eom.style.display = "none";
$(global._imgSelector).boxHide();
global._hideChooseBox()
// ChooseBox.hide(global._choosebox);
},
changeSliderAnim:function(newAnim){
sliders[currentSlider].setAttribute("data-anim", newAnim);
sb.notify({
type:"changeShowAnim",
data:newAnim
});
},
changeShowAnim:function(anim){
$('.animation-setting').html(anim_name[anim]);
},
//选中效果
setSelect : function (elemID) {
if (!elemID || target === elemID ) return;
global.cancelRightMenu();
/*
* 离开编辑框选择时隐藏编辑工具
* blur事件会导致点击工具栏时会隐藏
*/
if (!isEditor) { $("#execCommand-detail").addClass('dp-none');}
//取消现有目标的效果
if(target && elementSet[target]) {
sb.removeClass(elementSet[target].container,"element-select");
var parts = sb.query(".element-container-apart", elementSet[target].container);
for (i = 0; i < parts.length; i++) {
sb.removeClass(parts[i],"show-container-apart");
}
}
if (elemID === 'panel') {
target = null;
return;
}
target = elemID;
var elementData = elementSet[target], container = elementData.container;
sb.addClass(container, "element-select");
var elements = sb.query(".element-container-apart", elementData.container);
for (i = 0; i < elements.length; i++) {
sb.addClass(elements[i],"show-container-apart");
}
},
cancelRightMenu : function () {
cancelElementOperateMenuFunc();
easm.style.display = "none";
},
elementOpertate:function(elemID,etar,container){
var i;
sb.click(etar, {isDown : false}, function (e) {
if ( target === elemID) return;
global.setSelect(elemID)
// if ( target === elemID) return;
// //取消现有目标的效果
// if(target && elementSet[target]) {
// sb.removeClass(elementSet[target].container,"element-select");
// var parts = sb.query(".element-container-apart", elementSet[target].container);
// for (i = 0; i < parts.length; i++) {
// sb.removeClass(parts[i],"show-container-apart");
// }
// }
// if (elemID === 'panel') {
// target = null;
// return;
// }
// target = elemID;
// sb.addClass(container, "element-select");
// var elements = sb.query(".element-container-apart", elementSet[target].container);
// for (i = 0; i < elements.length; i++) {
// sb.addClass(elements[i],"show-container-apart");
// }
})
sb.bind(etar,"mousedown",function(e){
//监听鼠标右键
if(e.button == 2){
//取消默认右键菜单
etar.oncontextmenu = function(){
return false;
}
//选择性显示菜单项
global._chooseMenuItem(elemID);
//如果触发了右键,隐藏菜单
if (elemID === rightMenuBtn) {
if(eom.style.display == "block"){
cancelElementOperateMenuFunc();
easm.style.display = "none";
return;
}
}
rightMenuBtn = elemID;
if(elemID == 'panel'){
//面板触发右键,则没有选择目标
// rightMenuBtn = null;
eom.style.display = "block";
setPositionFunc(e,eom,-50,-50,-100,-200);
return;
}
eom.style.display = "block";
setPositionFunc(e, eom, -50, -50, -100, -200);
}
});
},
_chooseMenuItem : function (elemId) {
var $codeboxItem = $(".codebox-setting-item", eom),
$textEditItem = $(".textedit-setting-item", eom),
$zIndexItem = $(".zIndex-setting-item", eom),
$elemItem = $(".elem-setting-item", eom),
$pasteItem = $(".paste-menu-item", eom);
var type = ( elemId === 'panel' ) ? 'panel' : SliderDataSet[currentSlider][elemId].data.tagName;
$('.menu-detect-item').addClass('dp-none');
//粘贴选项
if (copyParams) {
$pasteItem.removeClass('menu-disabled');
}
else {
$pasteItem.addClass('menu-disabled');
}
if (type === 'panel') { //面板没有复制粘贴之类的操作
$zIndexItem.addClass('menu-disabled')
$elemItem.addClass('menu-disabled')
} else {
$zIndexItem.removeClass('menu-disabled')
$elemItem.removeClass('menu-disabled')
}
if (type === 'CODE') { //高亮代码工具菜单
$codeboxItem.removeClass('dp-none');
}
else if (type === 'DIV'){ //文本框工具菜单
$textEditItem.removeClass('dp-none');
}
},
setPosition:function(event,elem,x1,y1,x2,y2,show){
var offsetX = event.screenX > (window.innerWidth + x2) ? x2 : x1,
offsetY = (event.screenY > window.innerHeight + y2) ? y2 : y1;
elem.style.left = (event.screenX + offsetX) + "px";
elem.style.top = (event.screenY + offsetY) + "px";
},
createElementContainer:function(sizeObj, partSize, elem, options){
/*
* @names:
* con_e container : east
* con_w container : west
* con_s container : south
* con_n container : north
*/
options = options || {};
var container = options.container || document.createElement("div"),
move_e = document.createElement("div"),
move_w = document.createElement("div"),
move_s = document.createElement("div"),
move_n = document.createElement("div"),
rotateCon = document.createElement("div"),
rotateLeft = document.createElement("div"),
rotateRight = document.createElement("div"),
centerValue = '-webkit-calc(50% - ' + partSize/2 + 'px)'
parts = {
"con_e":{
className:"con-part-e",
resizeHandle:sb.proxy(sb.resizeRX, sb),
style:"right:"+(-partSize)+"px;top:" + centerValue + ";"
},
"con_w":{
className:"con-part-w",
resizeHandle:sb.proxy(sb.resizeLX, sb),
style:"left:"+(-partSize)+"px;top:" + centerValue + ";"
},
"con_s":{
className:"con-part-s",
resizeHandle:sb.proxy(sb.resizeBY, sb),
style: "bottom:"+(-partSize)+"px;left:" + centerValue + ";"
},
"con_n":{
className:"con-part-n",
resizeHandle:sb.proxy(sb.resizeTY, sb),
style:"top:"+(-partSize)+"px;left:" + centerValue + ";"
},
"con_se":{
className:"con-part-se",
resizeHandle:sb.proxy(sb.resizeRB, sb),
style:"bottom:"+(-partSize)+"px;right:"+(-partSize)+"px;"
},
"con_ne":{
className:"con-part-ne",
resizeHandle:sb.proxy(sb.resizeRT, sb),
style:"top:"+(-partSize)+"px;right:"+(-partSize)+"px;"
},
"con_sw":{
className:"con-part-sw",
resizeHandle:sb.proxy(sb.resizeLB, sb),
style:"bottom:"+(-partSize)+"px;left:"+(-partSize)+"px;"
},
"con_nw":{
className:"con-part-nw",
resizeHandle:sb.proxy(sb.resizeLT, sb),
style:"top:"+(-partSize)+"px;left:"+(-partSize)+"px;"
}
};
container.style.WebkitTransformOrigin = 'center center';
// $(container).attr('title', '左键点击选中/右键打开菜单')
var frag = document.createDocumentFragment();
for (var item in parts) {
var element = sb.create("div");
element.className = "element-container-apart " + parts[item].className;
element.setAttribute("style", parts[item].style+"height:"+partSize+"px;width:"+partSize+"px;");
parts[item].element = element;
parts[item].resizeHandle([element,container,elem]);
frag.appendChild(element);
}
if (!options.container) {
container.setAttribute("style", "position:absolute;z-index:1;left:0px;top:0px;background-position:center;background-size:99.99% 100%;");
//图形库的图形大小为图片本身大小
}
if (options['isFixedSize']) {
container.style.height = sizeObj.height + 'px';
container.style.width = sizeObj.width + 'px';
}
//边框移动控件
$(move_e).addClass("element-container-apart-move con-move-e");
$(move_w).addClass("element-container-apart-move con-move-w");
$(move_s).addClass("element-container-apart-move con-move-s");
$(move_n).addClass("element-container-apart-move con-move-n");
//旋转控件
$(rotateCon).addClass('con-rotate').append(rotateLeft).append(rotateRight).attr('title', '拖拽旋转');
$(rotateLeft).addClass('con-rotate-elem con-rotate-left');
$(rotateRight).addClass('con-rotate-elem con-rotate-right');
//resize控件
$(move_w).attr("style", "left:-6px;top:0;height:100%;width:6px;");
$(move_e).attr("style", "right:-6px;top:0;height:100%;width:6px;");
$(move_s).attr("style", "bottom:-6px;left:0;height:6px;width:100%;");
$(move_n).attr("style", "top:-6px;left:0;height:6px;width:100%;");
$(container)
.addClass("element-container")
.append(move_w)
.append(move_e)
.append(move_s)
.append(move_n)
.append(rotateCon)
.append(frag)
.attr("draggable", false);
sb.move(move_w, container);
sb.move(move_e, container);
sb.move(move_s, container);
sb.move(move_n, container);
global._dragRotate(rotateCon, container)
global._rotate(rotateLeft, container, 'left')
global._rotate(rotateRight, container, 'right')
return {
container:container
}
},
_dragRotate : function (rotateBtn, tar) {
var initX=0,pInitW=0,
flag={ isInit:false, isDown:false };
sb.ondrag(rotateBtn, flag, function(event) {
if(flag.isDown){
var clientX = event.screenX;
var clientY = event.screenY;
if(!flag.isInit) {
initX = clientX;
initY = clientY
flag.isInit = true;
var transform = $(tar).css('WebkitTransform');
initRoate = transform ? parseFloat( transform.replace(/^rotate\(/,'').replace(/deg\)$/,'') ) : 0;
} else {
//
initRoate = initRoate % 360;
var trFnValue = initRoate*Math.PI/180;
var diffResize = (clientX - initX) * Math.cos(trFnValue) + (clientY - initY) * Math.sin(trFnValue);
initRoate += diffResize/100;
tar.style.WebkitTransform = 'rotate(' + initRoate + 'deg)';
}
}
});
},
_rotate : function (rotateBtn, tar, forward) {
$(rotateBtn).on('click', function () {
var transform = $(tar).css('WebkitTransform');
var rotateValue = transform ? parseFloat( transform.replace(/^rotate\(/,'').replace(/deg\)$/,'') ) : 0;
if (forward === 'left') rotateValue = rotateValue - 1;
else rotateValue = rotateValue + 1;
tar.style.WebkitTransform = 'rotate(' + rotateValue + 'deg)';
})
}
};
});
|
/* Import dependencies */
const async = require('async');
const db = require('./utils/db.js');
/* Load the indexes config */
const indexes = require('./config/indexes.json');
/* Attempt to get a database connection */
db( db => {
/* Loop through the list of required indexes and create them in the database */
async.each( indexes, ( item, callback ) => {
createDatabaseIndex( db, item, callback );
}, () => {
/* We have completed creating the indexes, close the database connection */
console.log( 'Completed all' );
db.close();
});
});
/* This function creates a database index with the specified information */
createDatabaseIndex = ( db, item, callback ) => {
const { collection, fields, name } = item;
console.log( `Creating index - ${name}` );
/* Create the index if it doesn't already exist */
db.collection(collection).ensureIndex( fields, { background: true }, () => {
console.log( `Created index - ${name}` );
callback();
});
}
|
'use strict';
/***** ASSETS ****/
//list all assets
scheduleControllers.controller('AssetListCtrl', ['$scope', '$firebase', 'globalFuncs',
function($scope, $firebase, globalFuncs) {
console.log('hi from the AssetListCtrl');
var sync = globalFuncs.getAssets($scope, $firebase);
sync.$bindTo($scope, 'assets');
//get products
$scope.products = globalFuncs.getProductsArray($scope, $firebase);
//artworks
$scope.artworksEls = globalFuncs.getArtworksArray($scope, $firebase);
}]);
|
export default (value, {regex = /.+/}) => {
value = value || null;
value = String(value);
return regex.test(value);
};
|
import merge from 'lodash/merge';
import { HYDRATE } from '../constants/session';
import { GET_SUBSCRIPTIONS_SUCCESS } from '../constants/subscriptions'
export default function subscriptions(state={
list: []
}, action={}) {
switch (action.type) {
case GET_SUBSCRIPTIONS_SUCCESS:
return merge({}, state, {
list: action.subscriptions
});
case HYDRATE:
if (!action.data.subscriptions) {
return state;
}
return merge({}, state, {
list: action.data.subscriptions
});
default:
return state;
}
}
|
const LANG_ROLES = require('../commands/languages').LANG_ROLES;
module.exports.name = 'reactionSelfAssignableRoles';
module.exports.events = ['REACT'];
module.exports.initialize = (json, server) => {
server.sars = {};
if (server.sticky) {
let stickied = server.guild.channels.cache.get(server.sticky);
if (stickied) stickied.messages.fetch(); // #server_rules
}
if (!json || !json['sars']) return;
server.sars = json['sars'];
};
module.exports.isAllowed = (message) => {
return (
message.author.id === '299335689558949888' &&
message.content.startsWith('React with')
); // Myself
};
//let rateLimit = new Array(3);
module.exports.process = async (reaction, user, added, server) => {
if (server.sars[reaction.emoji.toString()]) {
let roleID = server.sars[reaction.emoji.toString()];
let member = await server.guild.member(user);
if (!member) {
console.log('SAR failed: ' + user.id);
return;
}
if (added) {
if (
roleID === '384286851260743680' &&
!LANG_ROLES.some((r) => member.roles.cache.has(r))
) {
reaction.users.remove(user.id);
} else {
member.roles.add(roleID, 'self assigned');
}
} else {
member.roles.remove(roleID, 'self assigned');
}
}
};
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.