code stringlengths 2 1.05M |
|---|
/*globals $, svgedit, unescape, DOMParser, ActiveXObject, getStrokedBBox*/
/*jslint vars: true, eqeq: true, bitwise: true, continue: true, forin: true*/
/**
* Package: svgedit.utilities
*
* Licensed under the MIT License
*
* Copyright(c) 2010 Alexis Deveria
* Copyright(c) 2010 Jeff Schiller
*/
// Dependencies:
// 1) jQuery
// 2) browser.js
// 3) svgtransformlist.js
// 4) units.js
(function(undef) {'use strict';
if (!svgedit.utilities) {
svgedit.utilities = {};
}
// Constants
// String used to encode base64.
var KEYSTR = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
var NS = svgedit.NS;
// Much faster than running getBBox() every time
var visElems = 'a,circle,ellipse,foreignObject,g,image,line,path,polygon,polyline,rect,svg,text,tspan,use';
var visElems_arr = visElems.split(',');
//var hidElems = 'clipPath,defs,desc,feGaussianBlur,filter,linearGradient,marker,mask,metadata,pattern,radialGradient,stop,switch,symbol,title,textPath';
var editorContext_ = null;
var domdoc_ = null;
var domcontainer_ = null;
var svgroot_ = null;
svgedit.utilities.init = function(editorContext) {
editorContext_ = editorContext;
domdoc_ = editorContext.getDOMDocument();
domcontainer_ = editorContext.getDOMContainer();
svgroot_ = editorContext.getSVGRoot();
};
// Function: svgedit.utilities.toXml
// Converts characters in a string to XML-friendly entities.
//
// Example: '&' becomes '&'
//
// Parameters:
// str - The string to be converted
//
// Returns:
// The converted string
svgedit.utilities.toXml = function(str) {
// ' is ok in XML, but not HTML
// > does not normally need escaping, though it can if within a CDATA expression (and preceded by "]]")
return str.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"').replace(/'/, ''');
};
// Function: svgedit.utilities.fromXml
// Converts XML entities in a string to single characters.
// Example: '&' becomes '&'
//
// Parameters:
// str - The string to be converted
//
// Returns:
// The converted string
svgedit.utilities.fromXml = function(str) {
return $('<p/>').html(str).text();
};
// This code was written by Tyler Akins and has been placed in the
// public domain. It would be nice if you left this header intact.
// Base64 code from Tyler Akins -- http://rumkin.com
// schiller: Removed string concatenation in favour of Array.join() optimization,
// also precalculate the size of the array needed.
// Function: svgedit.utilities.encode64
// Converts a string to base64
svgedit.utilities.encode64 = function(input) {
// base64 strings are 4/3 larger than the original string
input = svgedit.utilities.encodeUTF8(input); // convert non-ASCII characters
// input = svgedit.utilities.convertToXMLReferences(input);
if (window.btoa) {
return window.btoa(input); // Use native if available
}
var output = [];
output.length = Math.floor( (input.length + 2) / 3 ) * 4;
var chr1, chr2, chr3;
var enc1, enc2, enc3, enc4;
var i = 0, p = 0;
do {
chr1 = input.charCodeAt(i++);
chr2 = input.charCodeAt(i++);
chr3 = input.charCodeAt(i++);
enc1 = chr1 >> 2;
enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
enc4 = chr3 & 63;
if (isNaN(chr2)) {
enc3 = enc4 = 64;
} else if (isNaN(chr3)) {
enc4 = 64;
}
output[p++] = KEYSTR.charAt(enc1);
output[p++] = KEYSTR.charAt(enc2);
output[p++] = KEYSTR.charAt(enc3);
output[p++] = KEYSTR.charAt(enc4);
} while (i < input.length);
return output.join('');
};
// Function: svgedit.utilities.decode64
// Converts a string from base64
svgedit.utilities.decode64 = function(input) {
if(window.atob) {
return svgedit.utilities.decodeUTF8(window.atob(input));
}
var output = '';
var chr1, chr2, chr3 = '';
var enc1, enc2, enc3, enc4 = '';
var i = 0;
// remove all characters that are not A-Z, a-z, 0-9, +, /, or =
input = input.replace(/[^A-Za-z0-9\+\/\=]/g, '');
do {
enc1 = KEYSTR.indexOf(input.charAt(i++));
enc2 = KEYSTR.indexOf(input.charAt(i++));
enc3 = KEYSTR.indexOf(input.charAt(i++));
enc4 = KEYSTR.indexOf(input.charAt(i++));
chr1 = (enc1 << 2) | (enc2 >> 4);
chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
chr3 = ((enc3 & 3) << 6) | enc4;
output = output + String.fromCharCode(chr1);
if (enc3 != 64) {
output = output + String.fromCharCode(chr2);
}
if (enc4 != 64) {
output = output + String.fromCharCode(chr3);
}
chr1 = chr2 = chr3 = '';
enc1 = enc2 = enc3 = enc4 = '';
} while (i < input.length);
return svgedit.utilities.decodeUTF8(output);
};
svgedit.utilities.decodeUTF8 = function (argString) {
return decodeURIComponent(escape(argString));
};
// codedread:does not seem to work with webkit-based browsers on OSX // Brettz9: please test again as function upgraded
svgedit.utilities.encodeUTF8 = function (argString) {
return unescape(encodeURIComponent(argString));
};
// Function: svgedit.utilities.convertToXMLReferences
// Converts a string to use XML references
svgedit.utilities.convertToXMLReferences = function(input) {
var n,
output = '';
for (n = 0; n < input.length; n++){
var c = input.charCodeAt(n);
if (c < 128) {
output += input[n];
} else if(c > 127) {
output += ('&#' + c + ';');
}
}
return output;
};
// Function: svgedit.utilities.text2xml
// Cross-browser compatible method of converting a string to an XML tree
// found this function here: http://groups.google.com/group/jquery-dev/browse_thread/thread/c6d11387c580a77f
svgedit.utilities.text2xml = function(sXML) {
if(sXML.indexOf('<svg:svg') >= 0) {
sXML = sXML.replace(/<(\/?)svg:/g, '<$1').replace('xmlns:svg', 'xmlns');
}
var out, dXML;
try{
dXML = (window.DOMParser)?new DOMParser():new ActiveXObject('Microsoft.XMLDOM');
dXML.async = false;
} catch(e){
throw new Error('XML Parser could not be instantiated');
}
try{
if (dXML.loadXML) {
out = (dXML.loadXML(sXML)) ? dXML : false;
}
else {
out = dXML.parseFromString(sXML, 'text/xml');
}
}
catch(e2){ throw new Error('Error parsing XML string'); }
return out;
};
// Function: svgedit.utilities.bboxToObj
// Converts a SVGRect into an object.
//
// Parameters:
// bbox - a SVGRect
//
// Returns:
// An object with properties names x, y, width, height.
svgedit.utilities.bboxToObj = function(bbox) {
return {
x: bbox.x,
y: bbox.y,
width: bbox.width,
height: bbox.height
};
};
// Function: svgedit.utilities.walkTree
// Walks the tree and executes the callback on each element in a top-down fashion
//
// Parameters:
// elem - DOM element to traverse
// cbFn - Callback function to run on each element
svgedit.utilities.walkTree = function(elem, cbFn){
if (elem && elem.nodeType == 1) {
cbFn(elem);
var i = elem.childNodes.length;
while (i--) {
svgedit.utilities.walkTree(elem.childNodes.item(i), cbFn);
}
}
};
// Function: svgedit.utilities.walkTreePost
// Walks the tree and executes the callback on each element in a depth-first fashion
// TODO: FIXME: Shouldn't this be calling walkTreePost?
//
// Parameters:
// elem - DOM element to traverse
// cbFn - Callback function to run on each element
svgedit.utilities.walkTreePost = function(elem, cbFn) {
if (elem && elem.nodeType == 1) {
var i = elem.childNodes.length;
while (i--) {
svgedit.utilities.walkTree(elem.childNodes.item(i), cbFn);
}
cbFn(elem);
}
};
// Function: svgedit.utilities.getUrlFromAttr
// Extracts the URL from the url(...) syntax of some attributes.
// Three variants:
// * <circle fill="url(someFile.svg#foo)" />
// * <circle fill="url('someFile.svg#foo')" />
// * <circle fill='url("someFile.svg#foo")' />
//
// Parameters:
// attrVal - The attribute value as a string
//
// Returns:
// String with just the URL, like someFile.svg#foo
svgedit.utilities.getUrlFromAttr = function(attrVal) {
if (attrVal) {
// url("#somegrad")
if (attrVal.indexOf('url("') === 0) {
return attrVal.substring(5, attrVal.indexOf('"',6));
}
// url('#somegrad')
if (attrVal.indexOf("url('") === 0) {
return attrVal.substring(5, attrVal.indexOf("'",6));
}
if (attrVal.indexOf("url(") === 0) {
return attrVal.substring(4, attrVal.indexOf(')'));
}
}
return null;
};
// Function: svgedit.utilities.getHref
// Returns the given element's xlink:href value
svgedit.utilities.getHref = function(elem) {
return elem.getAttributeNS(NS.XLINK, 'href');
};
// Function: svgedit.utilities.setHref
// Sets the given element's xlink:href value
svgedit.utilities.setHref = function(elem, val) {
elem.setAttributeNS(NS.XLINK, 'xlink:href', val);
};
// Function: findDefs
//
// Returns:
// The document's <defs> element, create it first if necessary
svgedit.utilities.findDefs = function() {
var svgElement = editorContext_.getSVGContent();
var defs = svgElement.getElementsByTagNameNS(NS.SVG, 'defs');
if (defs.length > 0) {
defs = defs[0];
} else {
defs = svgElement.ownerDocument.createElementNS(NS.SVG, 'defs');
if (svgElement.firstChild) {
// first child is a comment, so call nextSibling
svgElement.insertBefore(defs, svgElement.firstChild.nextSibling);
} else {
svgElement.appendChild(defs);
}
}
return defs;
};
// TODO(codedread): Consider moving the next to functions to bbox.js
// Function: svgedit.utilities.getPathBBox
// Get correct BBox for a path in Webkit
// Converted from code found here:
// http://blog.hackers-cafe.net/2009/06/how-to-calculate-bezier-curves-bounding.html
//
// Parameters:
// path - The path DOM element to get the BBox for
//
// Returns:
// A BBox-like object
svgedit.utilities.getPathBBox = function(path) {
var seglist = path.pathSegList;
var tot = seglist.numberOfItems;
var bounds = [[], []];
var start = seglist.getItem(0);
var P0 = [start.x, start.y];
var i;
for (i = 0; i < tot; i++) {
var seg = seglist.getItem(i);
if(seg.x === undef) {continue;}
// Add actual points to limits
bounds[0].push(P0[0]);
bounds[1].push(P0[1]);
if (seg.x1) {
var P1 = [seg.x1, seg.y1],
P2 = [seg.x2, seg.y2],
P3 = [seg.x, seg.y];
var j;
for (j = 0; j < 2; j++) {
var calc = function(t) {
return Math.pow(1-t,3) * P0[j]
+ 3 * Math.pow(1-t,2) * t * P1[j]
+ 3 * (1-t) * Math.pow(t, 2) * P2[j]
+ Math.pow(t,3) * P3[j];
};
var b = 6 * P0[j] - 12 * P1[j] + 6 * P2[j];
var a = -3 * P0[j] + 9 * P1[j] - 9 * P2[j] + 3 * P3[j];
var c = 3 * P1[j] - 3 * P0[j];
if (a == 0) {
if (b == 0) {
continue;
}
var t = -c / b;
if (0 < t && t < 1) {
bounds[j].push(calc(t));
}
continue;
}
var b2ac = Math.pow(b,2) - 4 * c * a;
if (b2ac < 0) {continue;}
var t1 = (-b + Math.sqrt(b2ac))/(2 * a);
if (0 < t1 && t1 < 1) {bounds[j].push(calc(t1));}
var t2 = (-b - Math.sqrt(b2ac))/(2 * a);
if (0 < t2 && t2 < 1) {bounds[j].push(calc(t2));}
}
P0 = P3;
} else {
bounds[0].push(seg.x);
bounds[1].push(seg.y);
}
}
var x = Math.min.apply(null, bounds[0]);
var w = Math.max.apply(null, bounds[0]) - x;
var y = Math.min.apply(null, bounds[1]);
var h = Math.max.apply(null, bounds[1]) - y;
return {
'x': x,
'y': y,
'width': w,
'height': h
};
};
// Function: groupBBFix
// Get the given/selected element's bounding box object, checking for
// horizontal/vertical lines (see issue 717)
// Note that performance is currently terrible, so some way to improve would
// be great.
//
// Parameters:
// selected - Container or <use> DOM element
function groupBBFix(selected) {
if(svgedit.browser.supportsHVLineContainerBBox()) {
try { return selected.getBBox();} catch(e){}
}
var ref = $.data(selected, 'ref');
var matched = null;
var ret, copy;
if(ref) {
copy = $(ref).children().clone().attr('visibility', 'hidden');
$(svgroot_).append(copy);
matched = copy.filter('line, path');
} else {
matched = $(selected).find('line, path');
}
var issue = false;
if(matched.length) {
matched.each(function() {
var bb = this.getBBox();
if(!bb.width || !bb.height) {
issue = true;
}
});
if(issue) {
var elems = ref ? copy : $(selected).children();
ret = getStrokedBBox(elems); // getStrokedBBox defined in svgcanvas
} else {
ret = selected.getBBox();
}
} else {
ret = selected.getBBox();
}
if(ref) {
copy.remove();
}
return ret;
}
// Function: svgedit.utilities.getBBox
// Get the given/selected element's bounding box object, convert it to be more
// usable when necessary
//
// Parameters:
// elem - Optional DOM element to get the BBox for
svgedit.utilities.getBBox = function(elem) {
var selected = elem || editorContext_.geSelectedElements()[0];
if (elem.nodeType != 1) {return null;}
var ret = null;
var elname = selected.nodeName;
switch ( elname ) {
case 'text':
if(selected.textContent === '') {
selected.textContent = 'a'; // Some character needed for the selector to use.
ret = selected.getBBox();
selected.textContent = '';
} else {
try { ret = selected.getBBox();} catch(e){}
}
break;
case 'path':
if(!svgedit.browser.supportsPathBBox()) {
ret = svgedit.utilities.getPathBBox(selected);
} else {
try { ret = selected.getBBox();} catch(e2){}
}
break;
case 'g':
case 'a':
ret = groupBBFix(selected);
break;
default:
if(elname === 'use') {
ret = groupBBFix(selected, true);
}
if(elname === 'use' || ( elname === 'foreignObject' && svgedit.browser.isWebkit() ) ) {
if(!ret) {ret = selected.getBBox();}
// This is resolved in later versions of webkit, perhaps we should
// have a featured detection for correct 'use' behavior?
// ——————————
//if(!svgedit.browser.isWebkit()) {
var bb = {};
bb.width = ret.width;
bb.height = ret.height;
bb.x = ret.x + parseFloat(selected.getAttribute('x')||0);
bb.y = ret.y + parseFloat(selected.getAttribute('y')||0);
ret = bb;
//}
} else if(~visElems_arr.indexOf(elname)) {
try { ret = selected.getBBox();}
catch(e3) {
// Check if element is child of a foreignObject
var fo = $(selected).closest('foreignObject');
if(fo.length) {
try {
ret = fo[0].getBBox();
} catch(e4) {
ret = null;
}
} else {
ret = null;
}
}
}
}
if(ret) {
ret = svgedit.utilities.bboxToObj(ret);
}
// get the bounding box from the DOM (which is in that element's coordinate system)
return ret;
};
// Function: svgedit.utilities.getRotationAngle
// Get the rotation angle of the given/selected DOM element
//
// Parameters:
// elem - Optional DOM element to get the angle for
// to_rad - Boolean that when true returns the value in radians rather than degrees
//
// Returns:
// Float with the angle in degrees or radians
svgedit.utilities.getRotationAngle = function(elem, to_rad) {
var selected = elem || editorContext_.getSelectedElements()[0];
// find the rotation transform (if any) and set it
var tlist = svgedit.transformlist.getTransformList(selected);
if(!tlist) {return 0;} // <svg> elements have no tlist
var N = tlist.numberOfItems;
var i;
for (i = 0; i < N; ++i) {
var xform = tlist.getItem(i);
if (xform.type == 4) {
return to_rad ? xform.angle * Math.PI / 180.0 : xform.angle;
}
}
return 0.0;
};
// Function getRefElem
// Get the reference element associated with the given attribute value
//
// Parameters:
// attrVal - The attribute value as a string
svgedit.utilities.getRefElem = function(attrVal) {
return svgedit.utilities.getElem(svgedit.utilities.getUrlFromAttr(attrVal).substr(1));
};
// Function: getElem
// Get a DOM element by ID within the SVG root element.
//
// Parameters:
// id - String with the element's new ID
if (svgedit.browser.supportsSelectors()) {
svgedit.utilities.getElem = function(id) {
// querySelector lookup
return svgroot_.querySelector('#'+id);
};
} else if (svgedit.browser.supportsXpath()) {
svgedit.utilities.getElem = function(id) {
// xpath lookup
return domdoc_.evaluate(
'svg:svg[@id="svgroot"]//svg:*[@id="'+id+'"]',
domcontainer_,
function() { return svgedit.NS.SVG; },
9,
null).singleNodeValue;
};
} else {
svgedit.utilities.getElem = function(id) {
// jQuery lookup: twice as slow as xpath in FF
return $(svgroot_).find('[id=' + id + ']')[0];
};
}
// Function: assignAttributes
// Assigns multiple attributes to an element.
//
// Parameters:
// node - DOM element to apply new attribute values to
// attrs - Object with attribute keys/values
// suspendLength - Optional integer of milliseconds to suspend redraw
// unitCheck - Boolean to indicate the need to use svgedit.units.setUnitAttr
svgedit.utilities.assignAttributes = function(node, attrs, suspendLength, unitCheck) {
if(!suspendLength) {suspendLength = 0;}
// Opera has a problem with suspendRedraw() apparently
var handle = null;
if (!svgedit.browser.isOpera()) {svgroot_.suspendRedraw(suspendLength);}
var i;
for (i in attrs) {
var ns = (i.substr(0,4) === 'xml:' ? NS.XML :
i.substr(0,6) === 'xlink:' ? NS.XLINK : null);
var attrVal = attrs[i];
if(attrVal !== undefined && attrVal !== null) {
if (ns) {
node.setAttributeNS(ns, i, attrVal);
} else if (!unitCheck) {
node.setAttribute(i, attrVal);
} else {
svgedit.units.setUnitAttr(node, i, attrVal);
}
}
}
if (!svgedit.browser.isOpera()) {svgroot_.unsuspendRedraw(handle);}
};
// Function: cleanupElement
// Remove unneeded (default) attributes, makes resulting SVG smaller
//
// Parameters:
// element - DOM element to clean up
svgedit.utilities.cleanupElement = function(element) {
var handle = svgroot_.suspendRedraw(60);
var defaults = {
'fill-opacity':1,
'stop-opacity':1,
'opacity':1,
'stroke':'none',
'stroke-dasharray':'none',
'stroke-linejoin':'miter',
'stroke-linecap':'butt',
'stroke-opacity':1,
'stroke-width':1,
'rx':0,
'ry':0
};
var attr;
for (attr in defaults) {
var val = defaults[attr];
if(element.getAttribute(attr) == val) {
element.removeAttribute(attr);
}
}
svgroot_.unsuspendRedraw(handle);
};
// Function: snapToGrid
// round value to for snapping
// NOTE: This function did not move to svgutils.js since it depends on curConfig.
svgedit.utilities.snapToGrid = function(value) {
var stepSize = editorContext_.getSnappingStep();
var unit = editorContext_.getBaseUnit();
if (unit !== "px") {
stepSize *= svgedit.units.getTypeMap()[unit];
}
value = Math.round(value/stepSize)*stepSize;
return value;
};
svgedit.utilities.preg_quote = function (str, delimiter) {
// From: http://phpjs.org/functions
return String(str).replace(new RegExp('[.\\\\+*?\\[\\^\\]$(){}=!<>|:\\' + (delimiter || '') + '-]', 'g'), '\\$&');
};
/**
* @param {string} globalCheck A global which can be used to determine if the script is already loaded
* @param {array} scripts An array of scripts to preload (in order)
* @param {function} cb The callback to execute upon load.
*/
svgedit.utilities.executeAfterLoads = function (globalCheck, scripts, cb) {
return function () {
var args = arguments;
function endCallback () {
cb.apply(null, args);
}
if (window[globalCheck]) {
endCallback();
}
else {
scripts.reduceRight(function (oldFunc, script) {
return function () {
$.getScript(script, oldFunc);
};
}, endCallback)();
}
};
};
svgedit.utilities.buildCanvgCallback = function (callCanvg) {
return svgedit.utilities.executeAfterLoads('canvg', ['canvg/rgbcolor.js', 'canvg/canvg.js'], callCanvg);
};
svgedit.utilities.buildJSPDFCallback = function (callJSPDF) {
return svgedit.utilities.executeAfterLoads('RGBColor', ['canvg/rgbcolor.js'], function () {
var arr = [];
if (!RGBColor || RGBColor.ok === undef) { // It's not our RGBColor, so we'll need to load it
arr.push('canvg/rgbcolor.js');
}
svgedit.utilities.executeAfterLoads('jsPDF', arr.concat('jspdf/underscore-min.js', 'jspdf/jspdf.min.js', 'jspdf/jspdf.plugin.svgToPdf.js'), callJSPDF)();
});
};
}());
|
/*
* request
* author: ruleechen
* contact: rulee@live.cn
* create date: 2014.7.4
* description: migrate from expressjs [https://github.com/strongloop/express/blob/master/lib/request.js]
*/
'use strict';
var parse = require('url').parse,
accepts = require('accepts'),
fresh = require('fresh'),
utils = require('zoo-utils');
var getter = function(obj, name, getter) {
Object.defineProperty(obj, name, {
configurable: true,
enumerable: true,
get: getter
});
};
var request = function(set) {
utils.extend(this, set);
var self = this;
//
getter(this, 'protocol', function() {
var trust = self.req._app.get('trust-proxy-fn');
if (!trust(self.req.connection.remoteAddress)) {
return self.req.connection.encrypted ? 'https' : 'http';
} else {
// Note: X-Forwarded-Proto is normally only ever a
// single value, but this is to be safe.
var proto = self.header('X-Forwarded-Proto') || 'http';
return proto.split(/\s*,\s*/)[0];
}
});
//
var protocol = this.protocol; //eg: http
var host = this.req.headers.host; //eg: www.nodetest.cn:1337
var path = this.req.url; //eg: /home?a=1
var url = parse(protocol + '://' + host + path, true);
//
getter(this, 'url', function() { return url; });
//
getter(this, 'query', function() { return utils.isObject(url.query) ? utils.extend({}, url.query) : utils.getQuery(url.search); });
//
getter(this, 'form', function() { return utils.extend({}, self.req.body); });
//
getter(this, 'method', function() { return self.req.method; });
//
getter(this, 'secure', function() { return (protocol === 'https'); });
//
getter(this, 'session', function() { return self.req.session; });
//
getter(this, 'xhr', function() {
var val = self.header('X-Requested-With') || '';
return ('xmlhttprequest' === val.toLowerCase());
});
//
getter(this, 'fresh', function() {
var method = self.req.method;
var s = self.res.statusCode;
// GET or HEAD for weak freshness validation only
if (method !== 'GET' && method !== 'HEAD') {
return false;
}
// 2xx or 304 as per rfc2616 14.26
if ((s >= 200 && s < 300) || 304 === s) {
return fresh(self.req.headers, self.res._headers);
}
// default
return false;
});
//
getter(this, 'subdomains', function() {
var offset = self.req._app.get('subdomain-offset');
return (this.hostname || '').split('.').reverse().slice(offset);
});
};
request.prototype = {
req: null, res: null,
constructor: request,
header: function(field) {
var hs = this.req.headers;
field = field.toLowerCase();
if (field === 'referer' || field === 'referrer') {
return hs.referrer || hs.referer;
} else {
return hs[field];
}
},
acceptsTypes: function() {
var accept = accepts(this.req);
return accept.types.apply(accept, arguments);
},
acceptsEncodings: function() {
var accept = accepts(this.req);
return accept.encodings.apply(accept, arguments);
},
acceptsCharsets: function() {
var accept = accepts(this.req);
return accept.charsets.apply(accept, arguments);
},
acceptsLanguages: function() {
var accept = accepts(this.req);
return accept.languages.apply(accept, arguments);
}
};
module.exports = function() {
return function(req, res, next, err) {
req._zoo = new request({
req: req,
res: res
});
next(err);
};
};
|
"use strict";
const util_1 = require("../util/util");
const path = require("path");
const fs_extra_p_1 = require("fs-extra-p");
const _7zip_bin_1 = require("7zip-bin");
//noinspection JSUnusedLocalSymbols
const __awaiter = require("../util/awaiter");
class CompressionDescriptor {
constructor(flag, env, minLevel) {
let maxLevel = arguments.length <= 3 || arguments[3] === undefined ? "-9" : arguments[3];
this.flag = flag;
this.env = env;
this.minLevel = minLevel;
this.maxLevel = maxLevel;
}
}
const extToCompressionDescriptor = {
"tar.xz": new CompressionDescriptor("--xz", "XZ_OPT", "-0", "-9e"),
"tar.lz": new CompressionDescriptor("--lzip", "LZOP", "-0"),
"tar.gz": new CompressionDescriptor("--gz", "GZIP", "-1"),
"tar.bz2": new CompressionDescriptor("--bzip2", "BZIP2", "-1")
};
function archiveApp(compression, format, outFile, dirToArchive) {
let withoutDir = arguments.length <= 4 || arguments[4] === undefined ? false : arguments[4];
return __awaiter(this, void 0, void 0, function* () {
const storeOnly = compression === "store";
if (format.startsWith("tar.")) {
// we don't use 7z here - develar: I spent a lot of time making pipe working - but it works on MacOS and often hangs on Linux (even if use pipe-io lib)
// and in any case it is better to use system tools (in the light of docker - it is not problem for user because we provide complete docker image).
const info = extToCompressionDescriptor[format];
let tarEnv = process.env;
if (compression != null && compression !== "normal") {
tarEnv = Object.assign({}, process.env);
tarEnv[info.env] = storeOnly ? info.minLevel : info.maxLevel;
}
yield util_1.spawn(process.platform === "darwin" || process.platform === "freebsd" ? "gtar" : "tar", [info.flag, "--transform", `s,^\.,${ path.basename(outFile, "." + format) },`, "-cf", outFile, "."], {
cwd: dirToArchive,
env: tarEnv
});
return outFile;
}
const args = util_1.debug7zArgs("a");
if (format === "7z" || format.endsWith(".7z")) {
if (!storeOnly) {
// 7z is very fast, so, use ultra compression
args.push("-mx=9", "-mfb=64", "-md=64m", "-ms=on");
}
} else if (format === "zip") {
if (compression === "maximum") {
// http://superuser.com/a/742034
//noinspection SpellCheckingInspection
args.push("-mfb=258", "-mpass=15");
}
} else if (compression === "maximum") {
args.push("-mx=9");
}
// remove file before - 7z doesn't overwrite file, but update
try {
yield fs_extra_p_1.unlink(outFile);
} catch (e) {}
if (format === "zip" || storeOnly) {
args.push("-mm=" + (storeOnly ? "Copy" : "Deflate"));
}
args.push(outFile, withoutDir ? "." : dirToArchive);
yield util_1.spawn(_7zip_bin_1.path7za, args, {
cwd: withoutDir ? dirToArchive : path.dirname(dirToArchive)
});
return outFile;
});
}
exports.archiveApp = archiveApp;
//# sourceMappingURL=archive.js.map |
export { reset } from './-private/window';
export { default as setupWindowMock } from './-private/setup-window-mock';
|
"use strict";
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var core_1 = require("@angular/core");
var rxjs_1 = require("rxjs");
var entities_1 = require("../../entities");
var mock_courses_1 = require("../../../mocks/mock-courses");
var constants_1 = require("../../utils/constants");
var authorizedHttp_service_1 = require("../authorizedHttpService/authorizedHttp.service");
var CoursesService = (function (_super) {
__extends(CoursesService, _super);
function CoursesService(backend, options) {
var _this = _super.call(this, backend, options) || this;
_this.CoursesUrl = '/courses';
_this.courses = mock_courses_1.COURSES.map(function (course) {
return entities_1.Course.castToCourse(course);
});
return _this;
}
CoursesService.prototype.getCourses = function () {
return _super.prototype.request.call(this, this.CoursesUrl)
.map(function (response) { return response.json(); })
.map(function (courses) {
return courses.filter(function (course) {
var dateDifference = new Date().valueOf() - Number(course.publishedDate);
return dateDifference < constants_1.FRESH_TIME;
});
}).delay(2000);
};
// Simulate GET /courses/:id
CoursesService.prototype.getCourseById = function (id) {
return rxjs_1.Observable.of(this.courses.find(function (course) {
return course.id === id;
}));
};
// Simulate POST /courses
CoursesService.prototype.createCourse = function (course) {
if (!course.id) {
course.id = Math.floor(Math.random() * 100000000);
}
this.courses.push(course);
return rxjs_1.Observable.of(this.courses);
};
// Simulate PUT /courses/:id
CoursesService.prototype.updateCourse = function (id, values) {
var course = this.getCourseById(id);
if (!course) {
return rxjs_1.Observable.of(null);
}
var newObj = Object.assign(course, values);
return rxjs_1.Observable.of(newObj);
};
// Simulate DELETE /courses/:id
CoursesService.prototype.removeCourse = function (id) {
console.log("remove course: " + id);
this.courses = this.courses.filter(function (course) { return course.id !== id; });
return rxjs_1.Observable.of(true);
};
return CoursesService;
}(authorizedHttp_service_1.AuthorizedHttpService));
CoursesService = __decorate([
core_1.Injectable()
], CoursesService);
exports.CoursesService = CoursesService;
|
import Histogram from "./components/Histogram";
import Histoslider from "./components/Histoslider";
import Slider from "./components/Slider";
export { Histogram, Histoslider, Slider };
export default Histoslider;
|
(function() {
/*
* Track pageview
*/
chrome.runtime.sendMessage({
action: 'trackPageview',
page: 'update.html'
});
/*
* Locale
*/
var elements = document.getElementsByTagName('*');
for (var i=0, ilen=elements.length; i<ilen; i++) {
var element = elements[i];
if (element && element.dataset && element.dataset.message) {
element.innerHTML = chrome.i18n.getMessage(element.dataset.message);
}
}
/*
* Links
*/
var links = document.getElementsByTagName('a');
for (var i= 0, ilen=links.length; i<ilen; i++) {
var link = links[i];
link.addEventListener('click', function(e) {
e.preventDefault();
// open tab
chrome.tabs.create({
url: this.href
});
// track link click
chrome.runtime.sendMessage(
{
action: 'trackEvent',
args: ['Link', 'click', this.href]
}
);
}, false);
}
/*
* Header
*/
var h1 = document.querySelector('h1');
var headerText = '';
var titleText = '';
if (location.hash === '#install') {
titleText = chrome.i18n.getMessage('updatePageTitleInstall');
headerText = chrome.i18n.getMessage('updatePageHeaderInstall');
}
else if (location.hash === '#update') {
headerText = chrome.i18n.getMessage('updatePageHeader', chrome.runtime.getManifest().version);
titleText = chrome.i18n.getMessage('updatePageTitle');
}
else {
titleText = chrome.i18n.getMessage('extName');
headerText = chrome.i18n.getMessage('extName');
}
h1.innerHTML = headerText;
document.title = titleText;
/*
* No show checkbox
*/
var noShowField = document.getElementById('noshow_checkbox');
// change
noShowField.addEventListener('change', function(e) {
// do not show
if (this.checked) {
console.log('disabling update tab');
// save setting
chrome.storage.sync.set({
'hide_update_tab': true
});
// send tracking after the setting is saved so it is sent
chrome.runtime.sendMessage(
{
action: 'trackEvent',
args: ['Settings', 'HideUpdateTab', '1']
}
);
}
else {
console.log('enabling update tab');
// save setting
chrome.storage.sync.set({
'hide_update_tab': false
});
// send tracking after the setting is saved so it is sent
chrome.runtime.sendMessage(
{
action: 'trackEvent',
args: ['Settings', 'HideUpdateTab', '0']
}
);
}
});
})(); |
var tape = require('tape');
const through = require('through2');
const mapper = require('../../lib/streams/unitSplittingMapperStream');
const Document = require('pelias-model').Document;
module.exports.tests = {};
// test exports
module.exports.tests.interface = function (test) {
test('interface: factory', t => {
t.equal(typeof mapper, 'function', 'stream factory');
t.end();
});
test('interface: stream', t => {
var stream = mapper();
t.equal(typeof stream, 'object', 'valid stream');
t.equal(typeof stream._read, 'function', 'valid readable');
t.equal(typeof stream._write, 'function', 'valid writeable');
t.end();
});
};
// ===================== australasian unit number mapping ======================
module.exports.tests.australasian_solidus = function (test) {
var doc = new Document('oa', 'example', 1);
doc.setName('default', '2/14 Smith Street');
doc.setAddress('number', '2/14');
doc.setAddress('street', 'Smith Street');
doc.setMeta('country_code', 'AU');
test('maps - split unit from housenumber', t => {
var stream = mapper();
stream.pipe(through.obj((doc, enc, next) => {
t.deepEqual(doc.getName('default'), '2/14 Smith Street', 'unchanged');
t.deepEqual(doc.getAddress('unit'), '2', 'mapped');
t.deepEqual(doc.getAddress('number'), '14', 'mapped');
t.deepEqual(doc.getAddress('street'), 'Smith Street', 'unchanged');
t.end();
next();
}));
stream.write(doc);
});
};
module.exports.tests.australasian_solidus_with_whitespace = function (test) {
var doc = new Document('oa', 'example', 1);
doc.setName('default', '2 / 14 Smith Street');
doc.setAddress('number', '2 / 14');
doc.setAddress('street', 'Smith Street');
doc.setMeta('country_code', 'AU');
test('maps - split unit from housenumber', t => {
var stream = mapper();
stream.pipe(through.obj((doc, enc, next) => {
t.deepEqual(doc.getName('default'), '2 / 14 Smith Street', 'unchanged');
t.deepEqual(doc.getAddress('unit'), '2', 'mapped');
t.deepEqual(doc.getAddress('number'), '14', 'mapped');
t.deepEqual(doc.getAddress('street'), 'Smith Street', 'unchanged');
t.end();
next();
}));
stream.write(doc);
});
};
module.exports.tests.australasian_flat_prefix = function (test) {
var doc = new Document('oa', 'example', 1);
doc.setName('default', 'Flat 2 14 Smith Street');
doc.setAddress('number', 'Flat 2 14');
doc.setAddress('street', 'Smith Street');
doc.setMeta('country_code', 'AU');
test('maps - split unit from housenumber', t => {
var stream = mapper();
stream.pipe(through.obj((doc, enc, next) => {
t.deepEqual(doc.getName('default'), 'Flat 2 14 Smith Street', 'unchanged');
t.deepEqual(doc.getAddress('unit'), '2', 'mapped');
t.deepEqual(doc.getAddress('number'), '14', 'mapped');
t.deepEqual(doc.getAddress('street'), 'Smith Street', 'unchanged');
t.end();
next();
}));
stream.write(doc);
});
};
module.exports.tests.australasian_flat_prefix_abbreviated = function (test) {
var doc = new Document('oa', 'example', 1);
doc.setName('default', 'F 2 14 Smith Street');
doc.setAddress('number', 'F 2 14');
doc.setAddress('street', 'Smith Street');
doc.setMeta('country_code', 'AU');
test('maps - split unit from housenumber', t => {
var stream = mapper();
stream.pipe(through.obj((doc, enc, next) => {
t.deepEqual(doc.getName('default'), 'F 2 14 Smith Street', 'unchanged');
t.deepEqual(doc.getAddress('unit'), '2', 'mapped');
t.deepEqual(doc.getAddress('number'), '14', 'mapped');
t.deepEqual(doc.getAddress('street'), 'Smith Street', 'unchanged');
t.end();
next();
}));
stream.write(doc);
});
};
module.exports.tests.australasian_unit_prefix = function (test) {
var doc = new Document('oa', 'example', 1);
doc.setName('default', 'Unit 2 14 Smith Street');
doc.setAddress('number', 'Unit 2 14');
doc.setAddress('street', 'Smith Street');
doc.setMeta('country_code', 'AU');
test('maps - split unit from housenumber', t => {
var stream = mapper();
stream.pipe(through.obj((doc, enc, next) => {
t.deepEqual(doc.getName('default'), 'Unit 2 14 Smith Street', 'unchanged');
t.deepEqual(doc.getAddress('unit'), '2', 'mapped');
t.deepEqual(doc.getAddress('number'), '14', 'mapped');
t.deepEqual(doc.getAddress('street'), 'Smith Street', 'unchanged');
t.end();
next();
}));
stream.write(doc);
});
};
module.exports.tests.australasian_apartment_prefix = function (test) {
var doc = new Document('oa', 'example', 1);
doc.setName('default', 'Apartment 2 14 Smith Street');
doc.setAddress('number', 'Apartment 2 14');
doc.setAddress('street', 'Smith Street');
doc.setMeta('country_code', 'AU');
test('maps - split unit from housenumber', t => {
var stream = mapper();
stream.pipe(through.obj((doc, enc, next) => {
t.deepEqual(doc.getName('default'), 'Apartment 2 14 Smith Street', 'unchanged');
t.deepEqual(doc.getAddress('unit'), '2', 'mapped');
t.deepEqual(doc.getAddress('number'), '14', 'mapped');
t.deepEqual(doc.getAddress('street'), 'Smith Street', 'unchanged');
t.end();
next();
}));
stream.write(doc);
});
};
module.exports.tests.australasian_apartment_prefix_abbreviated = function (test) {
var doc = new Document('oa', 'example', 1);
doc.setName('default', 'APT 2 14 Smith Street');
doc.setAddress('number', 'APT 2 14');
doc.setAddress('street', 'Smith Street');
doc.setMeta('country_code', 'AU');
test('maps - split unit from housenumber', t => {
var stream = mapper();
stream.pipe(through.obj((doc, enc, next) => {
t.deepEqual(doc.getName('default'), 'APT 2 14 Smith Street', 'unchanged');
t.deepEqual(doc.getAddress('unit'), '2', 'mapped');
t.deepEqual(doc.getAddress('number'), '14', 'mapped');
t.deepEqual(doc.getAddress('street'), 'Smith Street', 'unchanged');
t.end();
next();
}));
stream.write(doc);
});
};
module.exports.tests.australasian_allow_no_space_after_flat_designation = function (test) {
var doc = new Document('oa', 'example', 1);
doc.setName('default', 'APT2 14 Smith Street'); // note: 'APT2' concatenated
doc.setAddress('number', 'APT2 14');
doc.setAddress('street', 'Smith Street');
doc.setMeta('country_code', 'AU');
test('maps - split unit from housenumber', t => {
var stream = mapper();
stream.pipe(through.obj((doc, enc, next) => {
t.deepEqual(doc.getName('default'), 'APT2 14 Smith Street', 'unchanged');
t.deepEqual(doc.getAddress('unit'), '2', 'mapped');
t.deepEqual(doc.getAddress('number'), '14', 'mapped');
t.deepEqual(doc.getAddress('street'), 'Smith Street', 'unchanged');
t.end();
next();
}));
stream.write(doc);
});
};
function test(name, testFunction) {
return tape('unit_splitting_mapper: ' + name, testFunction);
}
for (var testCase in module.exports.tests) {
module.exports.tests[testCase](test);
}
|
var fs = require('fs')
// TODO wrap Q with associated functions for MAGIC!
function wrap (ctx) {
ctx.fsCalls = {}
// wrap app fs calls
Object.keys(fs).forEach(function (m) {
var orig = fs[m]
fs[m] = function () {
// $captureStack is a utility to capture a stacktrace array
var stack = ctx.$captureStack(fs[m])
// inspect the first callsite of the stacktrace and see if the
// filename matches the mainProgram we're running, if so, then
// the user has used the method in question
// the substring() is necessary as the user doesn't have to provide
// a .js extension to make it work
if (stack[0].getFileName().substring(0, ctx.mainProgram.length) == ctx.mainProgram) {
if (!ctx.fsCalls[m])
ctx.fsCalls[m] = 1
else
ctx.fsCalls[m]++
}
// call the real fs.readFileSync
return orig.apply(this, arguments)
}
})
}
module.exports = wrap |
'use strict';
describe('Quiz-Management Page', function(){
var $ctrl;
var $rootScope;
var $location;
var $q;
var authService;
beforeEach(angular.mock.module('app'));
beforeEach(angular.mock.inject(function(_$injector_) {
var $injector = _$injector_;
$rootScope = $injector.get('$rootScope');
$location = $injector.get('$location');
var $componentController = $injector.get('$componentController');
$q = $injector.get('$q');
authService = $injector.get('authService');
$ctrl = $componentController('qdQuizManagement', {
$scope: $rootScope.$new()
});
spyOn($location, 'path');
}));
it('controller is defined', function() {
expect($ctrl).toBeDefined();
});
// describe('searchWithFilter()', function(){
// it('sets a list of quizzes', function(){
// spyOn(authService, 'searchWithFilter').and.callFake(function() {
// return $q.when(true);
// });
// $ctrl.searchWithFilter(
// listOfData["string"].push([
// {
// "categories": [
// "string"
// ],
// "id": "string",
// "labels": [
// "string"
// ],
// "owner": "string",
// "publicAvailable": true,
// "questions": [
// {
// "answers": [
// {
// "content": "string",
// "id": "string"
// }
// ],
// "correctAnswerID": "string",
// "question": "string",
// "questionFormat": "string",
// "questionNum": 0
// }
// ],
// "title": "string"
// }
// ])
// );
// expect($ctrl.listOfData).toBeDefined();
// })
// })
}); |
angular.module('AffilinetToolbar')
.controller('SearchDiscoverController', ['$scope', '$rootScope', 'LogonService', '$timeout', '$translate', 'productWebservice' , 'BrowserExtensionService', SearchDiscoverController]);
function SearchDiscoverController($scope, $rootScope, LogonService, $timeout, $translate, productWebservice, BrowserExtensionService) {
$scope.loadingFinished = false;
$translate('SEARCHDISCOVER_PageName').then(function (text) {
$scope.$parent.pageName = text;
});
$scope.allShopsLoading = true;
$scope.searchFinsihed = false;
$scope.searching = false;
$scope.myPrograms = [];
$scope.allMyProgramIds = [];
$scope.selectedProgramsIds = [];
$scope.allShops = [];
$scope.productDetails = [];
$scope.allShopsLoading = false;
$scope.showSuccessMessage = false;
$scope.shopsFilteredToSelectedPrograms = [];
$scope.programUrls = [];
$scope.programUrlsRequested = [];
$scope.searchDiscoverShowDetails = {};
$scope.searchKeyword = '';
$scope.selectedPrograms = [];
$scope.selectedShops = [];
$scope.shopCategories = [];
$scope.shopCategoriesLoading = false;
$scope.selectedAffilinetCategories = [];
$scope.selectedShopCategories = [];
$scope.productResult = [];
$scope.facetsResult = [];
$scope.productPage = 1;
$scope.selectedBrand = '';
$scope.selectedDistributor = '';
$scope.selectedManufacturer = '';
$scope.selectedAffilinetCategoryPath = '';
$scope.selectedProductIds = [];
$scope.totalRecords = 0;
$scope.totalPages = 0;
let searchChangedTimeoutPromise;
$scope.selectedProductList = null;
let loadProducts = function (productIds){
let i = 0;
let batch = 0;
let productBatches = [];
angular.forEach(productIds, (productId) => {
if (!productBatches[batch]) {
productBatches[batch] = [productId];
} else {
productBatches[batch].push(productId);
}
if (productBatches[batch].length === 50) {
batch++;
}
i++;
});
// load the product details from webservice
angular.forEach(productBatches, function (productIds) {
productWebservice.GetProducts(productIds).then(
(response) => {
response.data.Products.forEach((product) => {
$scope.productDetails[product.ProductId] = product;
getProgramUrlForProgramId(product.ProductId)
})
}
)
});
};
$scope.setBrand = function(value) {
"use strict";
if ($scope.selectedBrand === value) {
$scope.selectedBrand = '';
} else {
$scope.selectedBrand = value;
}
searchIfValid()
};
$scope.setManufacturer = function(value) {
if ($scope.selectedManufacturer === value) {
$scope.selectedManufacturer = '';
} else {
$scope.selectedManufacturer = value;
}
searchIfValid()
};
$scope.setDistributor = function(value) {
if ($scope.selectedDistributor === value) {
$scope.selectedDistributor = '';
} else {
$scope.selectedDistributor = value;
}
searchIfValid()
};
$scope.setAffilinetCategoryPath = function(value) {
if ($scope.selectedAffilinetCategoryPath === value) {
$scope.selectedAffilinetCategoryPath = '';
} else {
$scope.selectedAffilinetCategoryPath = value;
}
searchIfValid()
};
$scope.toggleFilters = function () {
$scope.showFilters= !$scope.showFilters
};
let loadInitialValues = function () {
BrowserExtensionService.storage.local.get(
['storedProductLists',
'searchDiscoverShowDetails',
'searchDiscoverLastKeyword',
'searchDiscoverSelectedShopCategories',
'searchDiscoverSelectedShops',
'searchDiscoverSelectedPrograms',
'searchDiscoverSelectedProgramIds',
'searchDiscoverSelectedProductIds',
'searchDiscoverSelectedBrand',
'searchDiscoverSelectedDistributor',
'searchDiscoverSelectedManufacturer',
'searchDiscoverSelectedAffilinetCategoryPath',
'searchDiscoverShowFilters',
'searchDiscoverShopsFilteredToSelectedPrograms',
'searchDiscoverShopsMinPrice',
'searchDiscoverShopsMaxPrice',
]
, function(result) {
console.log('result from storage', result);
if (result.storedProductLists) {
$scope.storedProductLists = result.storedProductLists;
} else {
$scope.storedProductLists = [];
}
if (result.searchDiscoverShowDetails) {
$scope.searchDiscoverShowDetails = result.searchDiscoverShowDetails;
}
if (result.searchDiscoverLastKeyword) {
$scope.searchKeyword = result.searchDiscoverLastKeyword;
}
if (result.searchDiscoverSelectedShopCategories) {
$scope.selectedShopCategories = result.searchDiscoverSelectedShopCategories;
}
if (result.searchDiscoverSelectedShops) {
$scope.selectedShops = result.searchDiscoverSelectedShops;
}
if (result.searchDiscoverShopsFilteredToSelectedPrograms) {
$scope.shopsFilteredToSelectedPrograms = result.searchDiscoverShopsFilteredToSelectedPrograms;
}
if (result.searchDiscoverSelectedProgramIds) {
$scope.selectedProgramsIds = result.searchDiscoverSelectedProgramIds;
}
if (result.searchDiscoverSelectedBrand) {
$scope.selectedBrand = result.searchDiscoverSelectedBrand;
}
if (result.searchDiscoverSelectedDistributor) {
$scope.selectedDistributor = result.searchDiscoverSelectedDistributor;
}
if (result.searchDiscoverSelectedManufacturer) {
$scope.selectedManufacturer = result.searchDiscoverSelectedManufacturer;
}
if (result.searchDiscoverSelectedAffilinetCategoryPath) {
$scope.selectedAffilinetCategoryPath = result.searchDiscoverSelectedAffilinetCategoryPath;
}
if (result.searchDiscoverShowFilters) {
$scope.showFilters = result.searchDiscoverShowFilters;
}
if (result.searchDiscoverSelectedPrograms) {
$scope.selectedPrograms = result.searchDiscoverSelectedPrograms;
}
if (result.searchDiscoverSelectedProductIds) {
$scope.selectedProductIds = result.searchDiscoverSelectedProductIds;
console.log('selected product ids', $scope.selectedProductIds);
if ($scope.selectedProductIds.length > 0 ) {
loadProducts($scope.selectedProductIds)
}
}
if (result.searchDiscoverShopsMinPrice) {
$scope.minPrice = result.searchDiscoverShopsMinPrice;
} else {
$scope.minPrice = 0
}
if (result.searchDiscoverShopsMaxPrice) {
$scope.maxPrice = result.searchDiscoverShopsMaxPrice;
} else {
$scope.maxPrice = 2000;
}
$scope.priceSlider = {
minValue: $scope.minPrice,
maxValue: $scope.maxPrice,
options: {
floor: 0,
ceil: 2000,
pushRange: true,
onEnd: function(modelValue,min, max) {
console.log(modelValue,min, max)
searchIfValid ();
BrowserExtensionService.storage.local.set({
searchDiscoverShopsMinPrice : min,
searchDiscoverShopsMaxPrice : max
})
}
}
};
searchIfValid ();
bindWatch();
$scope.$apply(function(){
$scope.loadingFinished = true;
})
});
}
function bindWatch() {
$scope.$watch( 'searchDiscoverShowDetails', (searchDiscoverShowDetails) => {
BrowserExtensionService.storage.local.set({searchDiscoverShowDetails : searchDiscoverShowDetails})
}, true
);
$scope.$watch( 'selectedProgramIds', (selectedProgramIds) => {
BrowserExtensionService.storage.local.set({searchDiscoverSelectedProgramIds : selectedProgramIds})
resetFilters()
}, true
);
$scope.$watch( 'selectedProductIds', (selectedProductIss) => {
BrowserExtensionService.storage.local.set({searchDiscoverSelectedProductIds : selectedProductIss})
}, true
);
$scope.$watch( 'selectedBrand', (selectedBrand) => {
BrowserExtensionService.storage.local.set({searchDiscoverSelectedBrand : selectedBrand})
searchIfValid (true);
}, true
);
$scope.$watch( 'selectedManufacturer', (selectedManufacturer) => {
BrowserExtensionService.storage.local.set({searchDiscoverSelectedManufacturer : selectedManufacturer})
searchIfValid (true);
}, true
);
$scope.$watch( 'selectedDistributor', (selectedDistributor) => {
BrowserExtensionService.storage.local.set({searchDiscoverSelectedDistributor : selectedDistributor})
searchIfValid (true);
}, true
);
$scope.$watch( 'selectedAffilinetCategoryPath', (selectedAffilinetCategoryPath) => {
BrowserExtensionService.storage.local.set({searchDiscoverSelectedAffilinetCategoryPath : selectedAffilinetCategoryPath})
searchIfValid (true);
}, true
);
$scope.$watch( 'showFilters', (showFilters) => {
BrowserExtensionService.storage.local.set({searchDiscoverShowFilters : showFilters});
}
);
$scope.$watch( 'selectedPrograms',
(selectedPrograms) => {
BrowserExtensionService.storage.local.set({searchDiscoverSelectedPrograms : selectedPrograms})
resetFilters()
if (selectedPrograms.length === 0) {
$scope.shopsFilteredToSelectedPrograms = $scope.allShops;
BrowserExtensionService.storage.local.set({searchDiscoverShopsFilteredToSelectedPrograms : $scope.shopsFilteredToSelectedPrograms})
$scope.selectedProgramsIds = $scope.allMyProgramIds;
$scope.selectedShops = [];
} else {
$scope.selectedProgramsIds = [];
selectedPrograms.forEach((program) => {
"use strict";
$scope.selectedProgramsIds.push(program.programId)
});
$scope.shopsFilteredToSelectedPrograms = [];
$scope.allShopsLoading = true;
$scope.allShops.forEach((shop) => {
"use strict";
if ($scope.selectedProgramsIds.indexOf(shop.ProgramId.toString()) >= 0) {
$scope.shopsFilteredToSelectedPrograms.push(shop);
}
})
BrowserExtensionService.storage.local.set({searchDiscoverShopsFilteredToSelectedPrograms : $scope.shopsFilteredToSelectedPrograms})
$scope.allShopsLoading = false;
searchIfValid ();
}
}
);
$scope.$watch('selectedShops', (selectedShops) => {
resetFilters()
BrowserExtensionService.storage.local.set({searchDiscoverSelectedShops : selectedShops});
if (selectedShops.length !== 1 ) {
$scope.selectedShopCategories = [];
}
if (selectedShops.length === 1) {
$scope.shopCategoriesLoading = true;
productWebservice.GetCategoryList(selectedShops[0].ShopId).then(
(result) => {
console.log('GetCategoryList list fetched', result);
$scope.shopCategories = result.data.Categories;
$scope.shopCategoriesLoading = false;
}
)
}
searchIfValid ();
});
$scope.$watch('selectedShopCategories', function(shopCategories){
resetFilters()
BrowserExtensionService.storage.local.set({searchDiscoverSelectedShopCategories : shopCategories});
searchIfValid ();
});
$scope.$watch('searchKeyword', (searchKeyword)=> {
resetFilters()
console.log('Search Keyword changed', searchKeyword);
BrowserExtensionService.storage.local.set({searchDiscoverLastKeyword : searchKeyword});
searchIfValid ();
});
}
let searchIfValid = function(immidiately = false) {
let delay;
if (!immidiately) {
delay = 500
} else {
delay = 0;
}
if ($scope.loadingFinished === false) {
return;
}
$timeout.cancel(searchChangedTimeoutPromise); //does nothing, if timeout already done
if ($scope.searchKeyword === '' && $scope.selectedShopCategories.length === 0) {
return
}
searchChangedTimeoutPromise = $timeout(function(){ //Set timeout
$scope.searching = true;
console.debug('search if valid runs with', $scope.searchKeyword , $scope.selectedShopCategories, $scope.selectedPrograms, $scope.shopsFilteredToSelectedPrograms);
$scope.searchProducts();
},delay);
}
let showError = function(error) {
"use strict";
let message = 'Error getting result from Product Webservice.';
if (error.data && error.data.ErrorMessages && error.data.ErrorMessages.length > 0) {
message += ' ' +error.data.ErrorMessages[0]['Value'];
}
$scope.$parent.sendAlert(message, 'danger');
}
let init = function() {
BrowserExtensionService.storage.local.get('myPrograms', function(result) {
"use strict";
if (result.myPrograms ) {
console.log('myPrograms', result.myPrograms);
$scope.myPrograms = result.myPrograms;
$scope.selectedProgramsIds = [];
result.myPrograms.forEach((program) => {
$scope.selectedProgramsIds.push(program.programId);
$scope.allMyProgramIds.push(program.programId);
});
} else {
$scope.myPrograms = [];
}
});
productWebservice.GetShopList().then(
(shopListResult) => {
$scope.allShops = shopListResult.data.Shops;
$scope.allShopsLoading = false;
console.log('INIT');
loadInitialValues()
},
(error) => {
showError (error);
}
);
}
$scope.searchProducts = function() {
$scope.productPage = 1;
$scope.searching = true;
let params = _buildSearchParams();
productWebservice.SearchProducts(params).then((result) => {
"use strict";
console.log(result);
$scope.searching = false;
$scope.searchFinished = true;
$scope.totalRecords = result.data.ProductsSummary.TotalRecords;
$scope.totalPages = result.data.ProductsSummary.TotalPages;
$scope.productResult = result.data.Products;
if (result.data.Facets) {
$scope.facetsResult = _buildFacets(result.data.Facets)
}
result.data.Products.forEach((product) => {
$scope.productDetails[product.ProductId] = product;
getProgramUrlForProgramId(product.ProgramId);
});
}, (error) => {
showError (error);
$scope.searching = false;
$scope.searchFinished = true;
})
};
let getProgramUrlForProgramId = function(ProgramId) {
if (!$scope.programUrlsRequested[ProgramId]) {
$scope.programUrlsRequested[ProgramId] = true;
BrowserExtensionService.runtime.sendMessage({action : 'get-programDetailsForProgramId', data : { programId : ProgramId}},
function(programDetails){
if (programDetails !== false) {
$scope.$apply(function(){
$scope.programUrls[ProgramId] = programDetails.programUrl;
});
}
})
}
}
$scope.loadMore = function() {
"use strict";
$scope.productPage++;
let params = _buildSearchParams();
productWebservice.SearchProducts(params).then((result) => {
"use strict";
console.log(result);
$scope.recordsOnPage = result.data.ProductsSummary.Records;
result.data.Products.forEach((product) => {
$scope.productResult.push(product)
});
}, (error) => {
showError (error);
})
}
$scope.toggleProduct = function(productId) {
if ($scope.selectedProductIds.includes(productId)) {
$scope.selectedProductIds = $scope.selectedProductIds
.filter( (prod) => prod !== productId);
} else {
$scope.selectedProductIds.unshift(productId);
}
console.log($scope.selectedProductIds);
}
$scope.addAllProducts = function(){
"use strict";
$scope.productResult.forEach((product) => {
if (!$scope.selectedProductIds.includes(product.ProductId)) {
$scope.selectedProductIds.unshift(product.ProductId);
}
})
}
$scope.createProductList = function (query) {
let newItem = {name: query, products : [], id: new Date().getTime() + '-' + Math.random()};
// name should be unique
let exists = false;
$scope.storedProductLists.forEach((list) => {
if (list.name === query) {
$scope.selectedProductList = list;
exists = true;
}
});
if (exists === true) {
return;
}
$scope.storedProductLists.unshift(newItem);
BrowserExtensionService.storage.local.set({
storedProductLists : $scope.storedProductLists
});
$scope.selectedProductList = newItem;
$scope.addProductsToProductList();
};
$scope.addProductsToProductList = function () {
angular.forEach($scope.selectedProductIds, (productId) => {
// do now allow dupes
if (! $scope.selectedProductList.products.includes(productId)) {
$scope.selectedProductList.products.unshift(productId);
}
});
if ($scope.selectedProductIds.length > 0) {
$scope.showSuccessMessage = true;
$timeout(function(){ //Set timeout
$scope.showSuccessMessage = false;
},3000);
}
$scope.selectedProductIds = [];
BrowserExtensionService.storage.local.set({
storedProductLists : $scope.storedProductLists
});
};
_shopsToShopIdCsv = function(shops) {
let ids = [];
angular.forEach(shops, (shop)=> {
"use strict";
ids.push(shop.ShopId)
})
return ids.join(',');
}
_categoriesToCSV = function(categories) {
"use strict";
console.log('categories: ', categories);
let ids = [];
angular.forEach(categories, (category)=> {
"use strict";
ids.push(category.Id)
})
return ids.join(',');
}
_buildSearchParams = () => {
"use strict";
let params = {
CurrentPage : $scope.productPage,
PageSize : 100,
SortBy : 'Score',
SortOrder : 'descending',
ImageScales : 'Image180',
WithImageOnly : 'true',
FacetFields : 'Brand,AffilinetCategoryPathFacet,Manufacturer,Distributor',
FacetValueLimit : 10,
};
if ( $scope.priceSlider.minValue !== $scope.priceSlider.options.floor) {
params.MinimumPrice = $scope.priceSlider.minValue
}
if ( $scope.priceSlider.maxValue !== $scope.priceSlider.options.ceil) {
params.MaximumPrice = $scope.priceSlider.maxValue
}
// Filter Query
let fq = '';
if ($scope.selectedBrand !== '') {
fq += ',Brand:' + ($scope.selectedBrand);
}
if ($scope.selectedDistributor !== '') {
fq += ',Distributor:' + ($scope.selectedDistributor);
}
if ( $scope.selectedManufacturer !== '') {
fq += ',Manufacturer:' + ($scope.selectedManufacturer);
}
if ( $scope.selectedAffilinetCategoryPath !== '') {
fq += ',AffilinetCategoryPathFacet:' + $scope.selectedAffilinetCategoryPath;
}
if (fq !== '' ) {
params.FQ = fq.slice(1);
}
// wenn shops ausgewählt nur diese shops
if ($scope.selectedShops.length > 0) {
params.ShopIds = _shopsToShopIdCsv($scope.selectedShops);
params.ShopIdMode = 'Include';
}
// wenn keine shops aber programme ausgewählt filter nur nach shops der programme
else if($scope.selectedPrograms.length > 0) {
if ($scope.shopsFilteredToSelectedPrograms.length === 0) {
console.error('NOT YET LOADED $scope.shopsFilteredToSelectedPrograms', $scope.shopsFilteredToSelectedPrograms)
}
params.ShopIds = _shopsToShopIdCsv($scope.shopsFilteredToSelectedPrograms)
params.ShopIdMode = 'Include';
}
// genau ein shop ausgewählt entweder affilinetcategories <=> ShopCategories
if ($scope.selectedShops.length === 1) {
if($scope.selectedShopCategories.length > 0) {
params.UseAffilinetCategories = 'false';
params.CategoryIds = _categoriesToCSV($scope.selectedShopCategories);
}
}
if ($scope.searchKeyword.length > 0) {
params.Query = $scope.searchKeyword;
}
return params;
};
_buildFacets = function (facetResult) {
"use strict";
let facets = [];
facetResult.forEach(function (facet) {
let res = { facetField : facet.FacetField, values : []};
facet.FacetValues.forEach(function(facetValue) {
let displayName;
if (facet.FacetField === 'AffilinetCategoryPathFacet') {
displayName = $scope.affilinetCategoryPathToDisplayValue(facetValue.FacetValueName)
} else {
displayName = $scope.ucfirst(facetValue.FacetValueName) ;
}
let val = {
displayName : displayName + ' (' + facetValue.FacetValueCount +')',
FacetValueName : facetValue.FacetValueName ,
FacetValueCount: facetValue.FacetValueCount
};
res.values.push(val)
});
facets.push(res);
});
return facets;
};
$scope.ucfirst = function(string) {
"use strict";
if (typeof string !== 'undefined'){
return string.charAt(0).toUpperCase() + string.slice(1)
}
return string
};
$scope.affilinetCategoryPathToDisplayValue = function(name) {
"use strict";
let displayName;
let $values = name.split('^');
if ($values[3] === $values[1]) return $values[1];
return $values[3];
};
let resetFilters = function () {
$scope.selectedBrand = '';
$scope.selectedManufacturer = '';
$scope.selectedDistributor = '';
$scope.selectedAffilinetCategoryPath = '';
};
$scope.reset = function () {
$scope.priceSlider.minValue = 0;
$scope.priceSlider.maxValue = $scope.priceSlider.options.ceil;
$scope.searchKeyword = '';
$scope.selectedShops = [];
resetFilters()
$scope.selectedProgramsIds= [];
$scope.selectedPrograms= [];
$scope.selectedProductIds= [];
$scope.selectedProducts= [];
$scope.selectedShopCategories= [];
BrowserExtensionService.storage.local.set({
searchDiscoverShopsMinPrice : 0,
searchDiscoverShopsMaxPrice : $scope.priceSlider.options.ceil
})
}
$timeout(function () {
$scope.$broadcast('rzSliderForceRender');
}, 1000);
init();
}
|
// A board for the cellular automata game Life.
//
// constructor
// r is number of rows, c number of columns
// has two arrays, one for current state (cells), one for next state
// cell state is 0 for dead and 1 for alive.
//
// methods (public)
// setCell
// toggleCell
// step
// run
// resize
//
// messages (events)
// before:run
// after:run
// step (stepCounter)
// cell (r, c, state)
// resize (r, c);
//
// This implementation is constructed such that it could be extended to implement
// other rules than Conway's Life.
function Board (conf) {
this.self = $.observable(this); // riotjs
$.extend(this.self, conf); // riotjs
this.nRows = conf.r;
this.nColumns = conf.c;
this.cells = makeGrid(this.nRows, this.nColumns);
this.next = makeGrid(this.nRows, this.nColumns);
this.stepCounter = 0;
this.running = false;
}
// public
Board.prototype.resize = function (r, c) {
this.nRows = r;
this.nColumns = c;
this.initialize();
this.self.trigger("resize", r, c);
};
// protected
Board.prototype.initialize = function () {
this.cells = makeGrid(this.nRows, this.nColumns);
this.next = makeGrid(this.nRows, this.nColumns);
this.stepCounter = 0;
this.self.trigger("step", this.stepCounter);
};
// public
// toggle state of cell
Board.prototype.toggleCell = function (r, c) {
this.setCell(r, c, this.cells[r][c] === 0 ? 1 : 0);
};
// public
// set the value in cell at r,c to v
Board.prototype.setCell = function (r, c, v) {
this.cells[r][c] = v;
this.self.trigger("cell", r, c, this.cells[r][c]);
};
// public
// run one step, setting the cells
Board.prototype.step = function () {
var v;
for (var i = 0; i < this.nRows; i++) {
for (var j = 0; j < this.nColumns; j++) {
this.next[i][j] = this.nextState(i, j);
}
}
for (var ii = 0; ii < this.nRows; ii++) {
for (var jj = 0; jj < this.nColumns; jj++) {
v = this.next[ii][jj];
this.cells[ii][jj] = v;
this.self.trigger("cell", ii, jj, v);
}
}
this.stepCounter++;
this.self.trigger("step", this.stepCounter);
};
Board.prototype.run = function () {
this.self.trigger("before:run");
this.running = true;
this.runloop();
};
Board.prototype.runloop = function () {
if (this.running) {
this.step();
}
if (this.running) {
// using setTimeout to ensure that other events get a chance to run.
// not sure this a good idea.
var me = this;
setTimeout(function runlooper () { me.runloop.call(me)}, 0);
} else {
this.self.trigger("after:run");
}
};
Board.prototype.stop = function () {
this.running = false;
};
// protected
// return the state that cell r, c will have next time
Board.prototype.nextState = function (r, c) {
var n = this.countNeighbors(r, c);
// classic Conway rule
if (n <= 1) {
return 0;
} else if (n == 2) {
return this.isAlive(r,c) ? 1 : 0;
} else if (n == 3 || n == 4) {
return 1;
} else {
return 0;
}
};
// protected
// return the number of live neighbor cells.
// Classic Conway rule, neighbors are the eight cells immediately adjacent
Board.prototype.countNeighbors = function (r, c) {
var counter = 0;
for (var dr = -1; dr <= 1; dr++) {
var nr = r + dr;
if (nr >= 0 && nr < this.nRows) {
for (var dc = -1; dc <= 1; dc++) {
if (dr === 0 && dc === 0) {
continue;
}
var nc = c + dc;
if (nc >= 0 && nc < this.nColumns) {
if (this.cells[nr][nc] == 1) {
counter++;
}
}
}
}
}
return counter;
};
// protected
// is the cell at r, c alive now?
Board.prototype.isAlive = function (r, c) {
return this.cells[r][c] == 1;
};
// public
Board.prototype.clear = function () {
for (var i = 0; i < this.nRows; i++) {
for (var j = 0; j < this.nColumns; j++) {
this.setCell(i, j, 0);
}
}
};
// we need this to make Board accessible outside the scope
top.Board = Board;
// make a two-d grid
function makeGrid (r, c) {
var a = [];
a.length = r;
for (var i = 0; i < r; i++) {
a[i] = [];
a[i].length = c;
for (var j = 0; j < c; j++) {
a[i][j] = 0;
}
}
return a;
}
|
// Regular expression that matches all symbols in the Enclosed Ideographic Supplement block as per Unicode v9.0.0:
/\uD83C[\uDE00-\uDEFF]/; |
/*
@deploy
@title Minimal Hello world!
*/
module.exports = function(req, res, next) {
res.send('Hello World!');
}; |
module.exports = {
ENV: process.env.ENV,
NETLIFY: process.env.NETLIFY
};
|
/********************************************************
* *********************
* 前端 代码规范 *********************
* *********************
* 更新日期 : 2015-11-20 12:19 *********************
*
*********************************************************
*
* 前述 :
*
* " 程序是写给人看的,顺带能在机器上运行 " --《黑客与画家》
*
* 通常我们维护代码的时间远远大于新建代码的时间,代码的质量、代码风格的好坏对产品的质量、bug率、
* 可扩展性,维护的效率有着重要的影响。代码的组织、抽象能力、对编程语言的理解,可能需要时间和经验的累积,
* 但优良的代码风格可以迅速的掌握并使用于日常开发中。虽然更好的代码风格会花费更多的时间,但考虑到维护的次数
* 远多余写新模块的次数,这些时间是值得的。
*
* 本规范除了对语言细节作出一些要求和建议外,对代码风格的场景也举了很多例子。尝试着去实践这些代码风格,
* 一定会使日后的维护更容易、产品的质量更好。
*
* ( 当你纠结于使用什么样的代码风格更好时,请谨记一条原则 : 如何使代码结构和逻辑一目了然 )
*
*
* 第 1 部分 : 硬性规定
* 第 2 部分 : 规定
* 第 3 部分 : 弱规定
* 第 4 部分 : 建议的代码风格
* 第 5 部分 : 一些最佳实践
*
*********************************************************/
/************************************************
* 第 1 部分 : 硬性规定
*
* 一定要遵守
*************************************************/
/**
* 使用 === !==
*/
=== // 杜绝 ==
!== // 杜绝 !=
/**
* 应该加分号 ; 的地方一定要加上,漏加可能会导致代码压缩失败、或者其它问题。
*
* jsHint (或者jsLint也行)是一个优秀的 JavaScript 语法校验工具,在忘记加 ; 时会提示警告,
* 它还有许多有用的提醒。
*
* 强烈建议在写完代码提交测试前,用jsHint校验代码(有些编辑器支持保存代码的时候自动行jsHint校验。)
* 如果觉得jsHint的校验过于苛刻,可以查看 游戏中心前端Wiki " 工具 / 工具配置 / " 目录下关于如果关闭一些
* jsHint警告的文章。
*/
var greenApple = 'apple', // 变量采用驼峰式命名
redCar = 'car';
nameSpace.HOUSE_NUMBER = 100; // 常量大写,用下划线连接
/**
* 类(构造函数),首字母大写
*/
var CountryHouse = function (arg) {
...
};
for (var column in symbolObj) {
if (symbolObj.hasOwnProperty(column)) // for-in 中应该始终用 hasOwnProperty() 过滤属性
...
}
/**
* 避免重复读取 length
*/
for (var i = 0; i < arr.length; i++) {
...
}
for (var i = 0, len = arr.length; i < len; i++) // Better
for (var i = arr.length - 1; i >= 0; i--) // OK, 如果顺序无所谓。
Array.prototype.customFn // 不要在原生类型的prototype上添加自定义方法。
/**
* 在元素上保存自定义属性时,请添加 " data- " 前缀。
*/
<a class="btn" data-age="10"> 立即邀请 </a> // Good
<a class="btn" age="10"> 立即邀请 </a> // Bad
/************************************************
* 第 2 部分 : 规定
*
* 强烈建议遵守
*************************************************/
/**
* 变量、类、方法等的命名要准确传达它的功能和意义(尽量),
*
* 因为代码最终会被压缩,局部变量根据命名的需要,长一些无所谓,
* 至于类、方法的命名,为了维护的方便,不应为了节省字节而导致表意不清。
*/
var elemID = 'cool', // 变量名中包含 ID 时,ID大写
wgURL = 'http://weixin.qq.com', // 变量名中包含 URL 时,URL大写
myAndroid = null, // 变量名中包含 Android 时,大写首字母A
myiOS = null, // 变量名中包含 iOS 时,小写首字母i // 此处有争议,请自行决定。
$elem = $('#elemID'); // jQuery对象命名以'$'开头
/**
* 本注释使用了多行注释格式 ...
*
* 类、方法(函数)的注释用多行注释的方式,不要用 " // "
*
* 其它地方的注释,如果需要多行描述,也用多行注释的方式,不要用 " // "
*/
/**
* ( 注释示例 ) : 这里描述函数的功能 ...
*
* @param symbols (WeiXin.Symbol) // 这里注明参数的名字、类型
* @param params (Object) - Optional // 如果某个参数不是必须的,添加 " - Optional "
* // example format: // 如果某个参数结构比较复杂,可以举个具体的例子,方便快速理解
* {
* low : a Date,
* high: a Date,
* msTarget: 3600000, // Must be a Natural Number.
* freqs: {
* CLC OHLC: 60000,
* CLC Volume: 86400000,
* ...
* }
* };
* @return {String} // 注明返回类型
*/
/**
* 单行代码尽量不要太长,占用多行的单行代码(实际是一行代码,只是换行了)会影响阅读,
* "建议的代码风格" 部分有许多避免单行长代码的例子。
*/
/************************************************
* 第 3 部分 : 弱规定
*
* 建议遵守
*************************************************/
var that = this; // 当需要保存当前对象的引用、以便在其它地方使用时,建议统一用 that。
/**
* 文件行数
*
* 模块或组件划分清晰的代码,单个文件代码的行数自然会减少,
* 有同事建议单个文件不超过500行,某其他同事对此持保留看法。
*
* 但有一点是一致的,模块或组件的划分要清晰。
*
* 为了提高代码清晰度,巧妙换行的代码风格是有好处的,虽然会增加
* 代码的行数,但是代码最终会压缩,所以是一样的。不应该过于纠结行数的多少。
*/
/************************************************
* 第 4 部分 : 建议的代码风格
*************************************************/
/**
* 赋值的变量以 " = " 号对齐
*
* 变量定义统一放在局部作用域最前面,只用一个var
*/
var pear = 100,
greenApple = 'xxxxxxx', //(以最长的变量为基准对齐)
orange = {}, // 每个变量放一行
lemon,
banana;
/**
* 成员变量的赋值以 " = " 号对齐
*/
this._cntPause = 0;
this._syms = {};
this._symsSorted = []; //(以最长的变量为基准对齐)
this._symMenu = null;
this._plotters = [];
/**
* 属性和值的对齐
*/
var symRec = {
isPending: true,
isAdded: false,
isError: false,
type: obj.type,
obj: obj
};
/**
* 更清晰的对齐
*/
var symRec = {
isPending : true,
isAdded : false,
isError : false,
type : obj.type,
obj : obj
};
/**
* 长数组对齐示例
*/
_symbols : [ 'MarCostCong5Min', 'CostOfCongestion5Min', 'Congestion5Min',
'MarCostCong', 'CostOfCongestion', 'Congestion' ],
_columns: [
"Expiration",
"ClosePrice",
"LastPrice",
"Chg",
"Chg%",
"Volume"
]
/**
* 链式调用对齐示例
*/
var lang = Lang.LegendMenu,
menu = this._newPopupMenu(),
menuQuote = menu.addItem().text(lang.quote) // 链式调用的每个函数(方法)单独放在一行,并且对齐
.callback(fnAA)
.imageClass('quote'),
menuTable = menu.addItem().text(lang.table)
.callback(fnBB)
.imageClass('table'),
menuRename = menu.addItem().text(lang.rename)
.callback(fnCC)
.imageClass('rename');
/**
* 链式调用对齐示例
*/
this.window.events.bind('closed', this._windowClosing) // 链式调用的每个函数(方法)单独放在一行,并且对齐
.bind('yAxisChange', this._windowResized) //(以最长的为基准对齐)
.bind('symbol', this._newSymbol);
/**
* 条件语句对齐示例
*/
if ( abc !== null
&& ( de === null // 添加适当的 () 有助于区分逻辑关系
|| abc < de ) ) {
......
}
/**
* 条件语句对齐示例
*/
if ( ( min !== null
&& val < min ) // 添加适当的 () 有助于区分逻辑关系
|| ( max !== null
&& val > max ) ) {
......
}
/**
* 条件语句对齐示例
*/
return ( ( d1 === null
&& d2 === null )
|| ( (d1 instanceof Date) // 添加适当的 () 有助于区分逻辑关系
&& (d2 instanceof Date)
&& d1.getTime() === d2.getTime() ) );
/**
* 精巧的对齐
*/
if (x < 10) { val = 3 };
else if (x < 50) { val = (x / 3) };
else if (x < 80) { val = (x / 4) };
else { val = (x / 6) };
/**
* 对齐示例
*/
for (var i = 0 ;
i < 10 && !isFound ; // 有时把循环结束的表达放到这里,比直接用 break; 更清晰
i++ ) {
...
}
if (isFound) { // 尤其当后续会用到这个结果时,一举两得。
...
}
/**
* 注意 "function" 前后、参数间的空格
*/
areEqual: function (d1, d2) {
...
}
/**
* 参数过多或过长时,每个参数单独放在一行
*/
new lim.Colors.Color( parseInt(match.substring(0,2), 16), // 第一个参数和 ( 之间留一个空格会清晰一些
parseInt(match.substring(2,4), 16),
parseInt(match.substring(4,6), 16) ); // 最后一个参数和 ) 之间留一个空格会清晰一些
ctx.clearRect( Math.max(0, prevF.x - _focusRadiusClear), // 第一个参数和 ( 之间留一个空格会清晰一些
Math.max(0, prevF.y - _focusRadiusClear),
prevF.x + _focusRadiusClear,
prevF.y + _focusRadiusClear ); // 最后一个参数和 ) 之间留一个空格会清晰一些
/**
* 数学操作符对齐示例
*/
var val = Math.round( (this.r * 0.3) // 添加适当的 () 有助于区分逻辑关系
+ (this.g * 0.59)
+ (this.b * 0.11) );
var val = Math.round( ( width
/ scrollableWidth
* scrollableSpaceOnBar
- barBorder )
/
( width
/ scrollableWidth
+ 1 ) );
var str = ( ( isPlus
&& num > 0 ) // 添加适当的 () 有助于区分逻辑关系
? '+'
: '' )
+ num.toFixed(numDecimals);
/**
* 三元操作符对齐示例
*/
var dates = ( ( skipMissing
|| cache._skipMissing )
? getDateIterator(low, high)
: tl.iterator(low, high) ),
baseY = ( _baselineVal !== null
? _baselineY
: ( (_style === 'line')
? lineObj.veryFirstY
: this._canvas.height ) ),
bar = null;
/**
* 巧妙的对齐
*
* 在某些地方,当你纠结于该如何对齐代码更好时,请谨记一条原则 : 如何使代码结构和逻辑一目了然。
*/
var HOURS_PER_DAY = 24,
MINUTES_PER_DAY = 1440,
SECONDS_PER_DAY = 86400, // 以个位数对齐
MILLIS_PER_SECOND = 1000,
MILLIS_PER_MINUTE = ( 60 * MILLIS_PER_SECOND),
MILLIS_PER_HOUR = ( 60 * MILLIS_PER_MINUTE),
MILLIS_PER_DAY = ( 24 * MILLIS_PER_HOUR),
MILLIS_PER_MONTH = ( 28 * MILLIS_PER_DAY),
MILLIS_PER_YEAR = (365 * MILLIS_PER_DAY);
/************************************************
* 第 5 部分 : 一些 最佳实践
*************************************************/
/**
* 类的定义 - 经典方式
*/
(function (ns) {
var Fruit = function () {
this._color = null;
this._taste = null;
...
};
Fruit.prototype = {
constructor: Fruit, // 重新绑定 constructor
getColor: function () {
return this._color;
},
...
};
ns.Fruit = Fruit;
})(myNameSpace);
/**********************************************************************
* 类的继承 - 经典方式
*
* 大多数情况下,我们可能不会用到继承。
* 如果需要继承,可以采用以下经典的继承方式。
*/
// 此函数获取 prototype 的引用
function inheritPrototype (subClass, superClass) {
/**
* Object.create() 浏览器支持情况 :>= IE9, Chrome, Firefox, Safari, Opera
*/
var prototype = Object.create(superClass.prototype); // 得到指向 superClass.prototype 的一个引用(指针)
prototype.constructor = subClass;
subClass.prototype = prototype;
}
// 父类
var SuperClass = function (name) {
this.name = name;
};
SuperClass.prototype = {
constructor: SuperClass,
getName: function () {
return this.name;
}
};
// 子类
var SubClass = function (name, age) {
SuperClass.call(this, name);
this.age = age;
};
inheritPrototype(SubClass, SuperClass); // 继承 prototype
// 添加函数
SubClass.prototype.getAge = function () {
return this.age;
};
/******************
* 类的继承 - 结束
***********************************************************************/
/**
* 善用 观察者模式
*
* 如果不熟悉观察者模式,可以上网搜索或请教同事
*/
/**
* 松耦合
*
* 设计模块、组件时,函数传递参数时,保持松耦合
*
* 比如在一个元素上添加样式时,样式写在 CSS 文件里,在元素上添加 className 即可。
*
* 在函数传递参数时,如果接收的函数只需要得到一个对象的某个属性值,那就不需要传递
* 整个对象过去。比如只传递 event.target 而不是整个 event 对象.
*/
/**
* 尊重对象所有权
*
* 当需要创建一个和已经存在的某个类有类似功能的新类时,除了直接修改
* 这个类外,有时也许适当使用继承、或者创建一个新对象与之交互更合理。
*
* (如果不好理解,请忽略)
*/
/**
* JavaScript 里有一些影响性能的语法或使用方法,或者是容易造成混淆的使用方式,
* 可能同事们都有些了解,如果不了解请找一本好书或者上网查一下,请注意规避这些
* 缺陷。
*
* 1. 比如避免使用 with 语句 ,除了性能问题外,在某些情况下 with 作用域里面的值会
* 造成很大的混淆。
*
* 2. 避免频繁访问 dom 元素的 clientWidth, offsetHeight ... 等属性,这些属性每次访问时,
* 浏览器都会动态计算它们的值,这一点与访问 NodeList 等动态对象类似。
*
* TODO 后续有空时可以总结一下
*/
/**
* Object.freeze() 的用途
*/
(function (ns) {
var Unit = function (index, name) {
this._name = name;
...
/**
* Object.freeze() 可以防止对象的属性被删除、属性值被修改,也可防止在对象上添加新的属性。
* 此种情形下,对象不可被访问者改变。适合在基础功能组件或模块中使用。
*
* Object.freeze() 浏览器支持情况 :>= IE9, Chrome, Firefox, Safari, Opera
*/
Object.freeze(this); // 新生成的实例对象被冻住
};
Unit.prototype = {
constructor: Unit,
toString: function () {
return this._name;
},
...
};
Object.freeze(Unit); // Unit 类被冻住
Object.freeze(Unit.prototype); // Unit.prototype 类的原型被冻住
ns.Unit = Unit;
})(myNameSpace);
/**
* 善用链式调用, 使代码清晰简洁
*/
this._chart.color('#333333')
.setPlotStyle('Mountain')
.hide();
// 注意 color 函数最后的 return this 语句
color: function (color) {
if (typeof color === 'undefined') {
return this._color;
}
else if (!this._validateColor(color)) {
/**
* 上次开会后组内多数人觉得,对参数执行严格验证,并且验证失败时抛出错误是有风险的,
* 所以此段代码仅供参考。
*
* 某同事觉得,对于后端接口返回值的校验可以宽松一些,但对于前端各个模块内部的公共方法
* 执行严格的参数校验有助于提高代码的质量、开发效率(因为错误定位精准,并且没有一连串的宽松妥协、甚至静默失败)
*
* 建议同事们可以谨慎实践。(尤其对于新开发的模块可以谨慎实践,因为没有历史遗留问题。)
*/
throw "IllegalArgumentException: color is invalid.";
}
else {
this._color = color;
/**
* return this 返回之前的 this._chart 对象,
* 使链式调用成为可能, 类似 jQuery的链式调用
*/
return this;
}
}
/************************************************
******* 结束 ******************************
*************************************************/
|
module.exports = [
'<div class="success">',
'<div class="success-note note">',
'Payment success! Thanks for your business!',
'</div>',
'</div>'
].join('\n')
|
'use strict';
// Requires
const request = require('request');
const cheerio = require('cheerio');
const _ = require('lodash');
const TVShow = require(`${__dirname}/../src/tvshow`);
let Logger;
class ProviderEZTV {
constructor(LocalConfiguration) {
this.name = 'EZTV';
this.baseUrl = 'https://eztv.ag/search/?q1=&q2=';
Logger = LocalConfiguration.getLogger();
}
hasNewEpisodes(tvShow) {
let url = `${this.baseUrl}${tvShow.eztv_id}&search=Search`;
let promise = new Promise((resolve, reject) => {
request(url, (error, response, body) => {
if (!error && response.statusCode == 200) {
let $ = cheerio.load(body);
let episodes = [];
$('table.forum_header_border tr.forum_header_border td.forum_thread_post a.epinfo').each(function(i, elem) {
let arr = $(this).text().split(' ');
arr.forEach(word => {
if (word.startsWith('S') && word.charAt(1).match(/^\d+$/) && word.charAt(2).match(/^\d+$/) && word.charAt(3) === 'E' && word.charAt(4).match(/^\d+$/) && word.charAt(5).match(/^\d+$/)) {
episodes.push(word);
}
});
});
if (_.isEmpty(episodes)) {
Logger.debug(`No episodes for: ${tvShow.name}`);
resolve(undefined);
return;
} else {
episodes = episodes.filter(episode => {
let newEpisode = false;
let latestSeason = parseInt(episode.substr(1, 2));
let latestEpisode = parseInt(episode.substr(4, 2));
if (latestSeason > tvShow.lastSeason) {
return episode;
}
if (latestSeason == tvShow.lastSeason && latestEpisode > tvShow.lastEpisode) {
return episode;
}
});
}
// Removing duplicates
episodes = Array.from(new Set(episodes));
if (episodes.length > 0) {
let episodesToDownload = [];
episodes.forEach(episode => {
let modifiedTvShow = new TVShow();
modifiedTvShow.name = tvShow.name;
modifiedTvShow.lastEpisode = tvShow.lastEpisode;
modifiedTvShow.lastSeason = tvShow.lastSeason;
modifiedTvShow.eztv_id = tvShow.eztv_id;
modifiedTvShow.provider = tvShow.provider;
modifiedTvShow.newEpisode = {
magnet: undefined,
episode: undefined,
season: undefined
};
let episodeNames = [];
$(`table.forum_header_border tr.forum_header_border td.forum_thread_post a.epinfo[title*="${episode}"]`).each(function(i, elem) {
episodeNames.push($(this).attr('title'));
});
let hdQuality = episodeNames.filter(episode => {
return episode.match(/720p/g);
});
modifiedTvShow.newEpisode.season = parseInt(episode.substr(1, 2));
modifiedTvShow.newEpisode.episode = parseInt(episode.substr(4, 2));
if (hdQuality.length > 0) {
let magnetHolder = $(`table.forum_header_border tr.forum_header_border td.forum_thread_post a.epinfo[title*="${hdQuality[0]}"]`).parent().next();
let magnet = magnetHolder.find('a.magnet');
modifiedTvShow.newEpisode.magnet = magnet.attr('href');
} else {
let magnetHolder = $(`table.forum_header_border tr.forum_header_border td.forum_thread_post a.epinfo[title*="${episode}"]`).parent().next();
let magnet = magnetHolder.find('a.magnet');
modifiedTvShow.newEpisode.magnet = magnet.attr('href');
}
episodesToDownload.push(modifiedTvShow);
});
Logger.debug(`${tvShow.name}: ${episodesToDownload.length} new episodes to download`);
Logger.log(`${tvShow.name}: ${episodesToDownload.length} new episodes to download`);
resolve(episodesToDownload);
} else {
resolve(undefined);
}
} else {
Logger.error('request error');
reject();
}
});
});
return promise;
}
}
module.exports = ProviderEZTV;
|
'use strict';
angular.module("ngLocale", [], ["$provide", function ($provide) {
var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"};
function getDecimals(n) {
n = n + '';
var i = n.indexOf('.');
return (i == -1) ? 0 : n.length - i - 1;
}
function getVF(n, opt_precision) {
var v = opt_precision;
if (undefined === v) {
v = Math.min(getDecimals(n), 3);
}
var base = Math.pow(10, v);
var f = ((n * base) | 0) % base;
return {v: v, f: f};
}
$provide.value("$locale", {
"DATETIME_FORMATS": {
"AMPMS": [
"TOO",
"MUU"
],
"DAY": [
"Jumap\u00ediri",
"Jumat\u00e1tu",
"Juma\u00edne",
"Jumat\u00e1ano",
"Alam\u00edisi",
"Ijum\u00e1a",
"Jumam\u00f3osi"
],
"ERANAMES": [
"K\u0268r\u0268sit\u0289 s\u0268 anavyaal",
"K\u0268r\u0268sit\u0289 akavyaalwe"
],
"ERAS": [
"KSA",
"KA"
],
"FIRSTDAYOFWEEK": 0,
"MONTH": [
"K\u0289f\u00fangat\u0268",
"K\u0289naan\u0268",
"K\u0289keenda",
"Kwiikumi",
"Kwiinyamb\u00e1la",
"Kwiidwaata",
"K\u0289m\u0289\u0289nch\u0268",
"K\u0289v\u0268\u0268r\u0268",
"K\u0289saat\u0289",
"Kwiinyi",
"K\u0289saano",
"K\u0289sasat\u0289"
],
"SHORTDAY": [
"P\u00edili",
"T\u00e1atu",
"\u00cdne",
"T\u00e1ano",
"Alh",
"Ijm",
"M\u00f3osi"
],
"SHORTMONTH": [
"F\u00fangat\u0268",
"Naan\u0268",
"Keenda",
"Ik\u00fami",
"Inyambala",
"Idwaata",
"M\u0289\u0289nch\u0268",
"V\u0268\u0268r\u0268",
"Saat\u0289",
"Inyi",
"Saano",
"Sasat\u0289"
],
"STANDALONEMONTH": [
"K\u0289f\u00fangat\u0268",
"K\u0289naan\u0268",
"K\u0289keenda",
"Kwiikumi",
"Kwiinyamb\u00e1la",
"Kwiidwaata",
"K\u0289m\u0289\u0289nch\u0268",
"K\u0289v\u0268\u0268r\u0268",
"K\u0289saat\u0289",
"Kwiinyi",
"K\u0289saano",
"K\u0289sasat\u0289"
],
"WEEKENDRANGE": [
5,
6
],
"fullDate": "EEEE, d MMMM y",
"longDate": "d MMMM y",
"medium": "d MMM y h:mm:ss a",
"mediumDate": "d MMM y",
"mediumTime": "h:mm:ss a",
"short": "dd/MM/y h:mm a",
"shortDate": "dd/MM/y",
"shortTime": "h:mm a"
},
"NUMBER_FORMATS": {
"CURRENCY_SYM": "TSh",
"DECIMAL_SEP": ".",
"GROUP_SEP": ",",
"PATTERNS": [
{
"gSize": 3,
"lgSize": 3,
"maxFrac": 3,
"minFrac": 0,
"minInt": 1,
"negPre": "-",
"negSuf": "",
"posPre": "",
"posSuf": ""
},
{
"gSize": 3,
"lgSize": 3,
"maxFrac": 2,
"minFrac": 2,
"minInt": 1,
"negPre": "-\u00a4\u00a0",
"negSuf": "",
"posPre": "\u00a4\u00a0",
"posSuf": ""
}
]
},
"id": "lag-tz",
"localeID": "lag_TZ",
"pluralCat": function (n, opt_precision) {
var i = n | 0;
var vf = getVF(n, opt_precision);
if (i == 1 && vf.v == 0) {
return PLURAL_CATEGORY.ONE;
}
return PLURAL_CATEGORY.OTHER;
}
});
}]);
|
import React from 'react';
import { connect } from 'react-redux';
import IssueComponent from './component';
import { fetchIssue, clearDetail } from './actions';
class IssueDetail extends React.Component {
componentWillMount() {
if(this.props.issueId) {
this.props.getIssue(this.props.issueId);
}
}
componentWillReceiveProps(nextProps) {
if(this.props.issueId !== nextProps.issueId) {
this.props.getIssue(nextProps.issueId);
}
}
componentWillUnmount() {
this.props.clear();
}
render() {
return (<IssueComponent
issue={ this.props.issue }
isFetching={ this.props.isFetching }
errorMessage={ this.props.errorMessage }
/>);
}
}
function mapStateToProps(state) {
return {
issue: state.issue.get('issue'),
isFetching: state.issue.get('isFetching'),
errorMessage: state.issue.get('errorMessage')
};
}
function mapDispatchToProps(dispatch) {
return {
getIssue: (id) => {
dispatch(fetchIssue(id));
},
clear: () => {
dispatch(clearDetail());
}
};
}
export default connect(mapStateToProps, mapDispatchToProps)(IssueDetail); |
var assert = require('assert');
var _ = require('lodash');
/**
* When `autoIncrement` is set to `true` on an attribute and no value is provided for it a
* new unique value will be assigned by the adapter before the record is created. It is
* guaranteed that the adapter will assign a unique value not present on any existing record.
* The values assigned automatically will not necessarily be sequential, which accommodates
* the use of UUIDs. If a value for the attribute is present in the data provided for a new
* record it will be saved as-is without any guarantee of uniqueness. The `autoIncrement`
* option has no effect when updating existing records. The feature flag is `autoIncrement`.
*/
describe('autoIncrement attribute feature', function() {
/////////////////////////////////////////////////////
// TEST SETUP
////////////////////////////////////////////////////
var Waterline = require('waterline');
var defaults = { migrate: 'alter' };
var waterline;
var AutoIncFixture = require('./../support/autoInc.fixture.js');
var AutoIncModel;
before(function(done) {
waterline = new Waterline();
waterline.loadCollection(AutoIncFixture);
done();
});
beforeEach(function(done) {
var connections = { autoIncConn: _.clone(Connections.test) };
Adapter.teardown('autoIncConn', function adapterTeardown(){
waterline.initialize({ adapters: { wl_tests: Adapter }, connections: connections, defaults: defaults }, function(err, ontology) {
if(err) return done(err);
AutoIncModel = ontology.collections['autoinc'];
done();
});
});
});
afterEach(function(done) {
if(!Adapter.hasOwnProperty('drop')) {
waterline.teardown(done);
} else {
AutoIncModel.drop(function(err1) {
waterline.teardown(function(err2) {
return done(err1 || err2);
});
});
}
});
/////////////////////////////////////////////////////
// TEST METHODS
////////////////////////////////////////////////////
var testName = '.create() test autoInc unique values';
var lastIds;
it('should auto generate unique values', function(done) {
var records = [];
for(var i=0; i<10; i++) {
records.push({ name: 'ai_' + i, type: testName });
}
AutoIncModel.create(records, function(err) {
if (err) return done(err);
AutoIncModel.find({where : { type: testName }, sort : {name : 1}}, function(err, records) {
if (err) return done(err);
assert(!err);
assert.equal(records.length, 10, 'Expecting 10 records, but got '+records.length);
assert(records[0].id);
assert.equal(records[0].name, 'ai_0');
assert(records[0].normalField === null || records[0].normalField === undefined);
var ids = lastIds = _.pluck(records, 'id');
assert.equal(ids.length, 10);
assert.equal(_.unique(ids).length, 10, 'Generated ids are not unique: '+ids.join(', '));
done();
});
});
});
it('should auto generate unique values even when values have been set', function(done) {
// Create some initial records with auto inc values already set. Type matches are ensured by using the
// values generated in the previous test, also ensuring that if there is a fixed sequence of values being
// used the first values are already taken.
var records = [];
for(var i=0; i<5; i++) {
records.push({ id: lastIds[i], name: 'ai_' + i, normalField: 10, type: testName });
}
AutoIncModel.create(records, function(err) {
if (err) return done(err);
AutoIncModel.find({where : { type: testName }, sort : {name : 1}}, function(err, records) {
if (err) return done(err);
assert(!err);
assert.equal(records.length, 5, 'Expecting 5 records, but got '+records.length);
assert.equal(records[0].id, lastIds[0]);
assert.equal(records[0].name, 'ai_0');
assert.equal(records[0].normalField, 10);
var ids = _.pluck(records, 'id');
assert.deepEqual(ids, lastIds.slice(0,5));
// Create another set of records without auto inc values set. The generated values should be
// unique, even when compared to those set explicitly.
var records = [];
for(var i=5; i<10; i++) {
records.push({ name: 'ai_' + i, type: testName });
}
AutoIncModel.create(records, function(err) {
if (err) return done(err);
AutoIncModel.find({where : { type: testName }, sort : {name : 1}}, function(err, records) {
if (err) return done(err);
assert(!err);
assert.equal(records.length, 10, 'Expecting 10 records, but got '+records.length);
assert.equal(records[0].id, lastIds[0]);
assert.equal(records[0].name, 'ai_0');
assert(records[5].id);
assert.equal(records[5].name, 'ai_5');
var ids = _.pluck(records, 'id');
assert.equal(ids.length, 10);
assert.equal(_.unique(ids).length, 10, 'Preset and generated ids are not unique: '+ids.join(', '));
done();
});
});
});
});
});
});
|
// FIXME: should be in its own NPM package
"use strict";
var Netmask = require('netmask').Netmask;
whitelist.knownRemotes = [
'207.97.227.224/27',
'173.203.140.192/27',
'204.232.175.64/27',
'72.4.117.96/27',
'204.232.175.64/27',
'192.30.252.0/22',
// '2620:112:3000::/44',
'207.97.227.253',
'50.57.128.197',
'108.171.174.178',
'50.57.231.61'
];
function contains(netmasks, ip)
{
return netmasks.reduce(function(prev, cur) {
return prev || cur.contains(ip);
}, false);
}
function whitelist(options)
{
options = options || {};
if(options.known) {
console.warn('The "known" option of flick.whitelist() is deprecated. ' +
'Use flick.github() instead.');
}
var ips = options.ips || [];
if(!ips.length || options.known) {
ips = ips.concat(whitelist.knownRemotes);
}
if(options.local) {
ips.push('127.0.0.1');
}
var netmasks = ips.map(function(ip) {
return new Netmask(ip);
});
return function(req, res, next)
{
var err;
if(!contains(netmasks, req.socket.remoteAddress)) {
err = new Error('[flick] whitelist: Remote is not whitelisted (' + req.socket.remoteAddress + ').');
err.status = 401;
}
next(err);
};
};
module.exports = whitelist;
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
describe('Test NetBeans homepage', function () {
it('should find correct title', function () {
browser.driver.get('http://netbeans.org');
expect(browser.driver.getTitle()).toEqual('Welcome to NetBeans');
});
});
|
//~ name c727
alert(c727);
//~ component c728.js
|
(function(){
'use strict';
angular.module('app').controller('DashboardCtrl', DashboardCtrl);
DashboardCtrl.$inject = ['$scope', '$rootScope', '$timeout', '$mdToast', '$q', 'Auth', 'restSrv', '$window'];
function DashboardCtrl($scope, $rootScope, $timeout, $mdToast, $q, Auth, restSrv, $window){
var vm = this;
$rootScope.dashboard = true;
vm.mobile = false;
vm.user = Auth.getUser();
vm.select = select;
vm.details = details;
vm.reviews = reviews;
vm.writeReview = writeReview;
vm.publishReview = publishReview;
vm.mobile_select = mobile_select;
vm.quit = quit;
activate();
function activate(){
vm.restaurants = restSrv.getRestaurants();
vm.restaurants.forEach(function(restaurant){
restaurant.reviews = {};
restaurant.reviews.rate = 0;
});
firebase.database().ref('reviews').on('value', function(snapshot) {
vm.listReviews = snapshot.val();
});
}
function select(restaurant, event){
if(typeof event === 'undefined' || event.keyCode === 13){
vm.selected = restaurant;
vm.selected.pictures = true;
vm.selected.detail = false;
vm.selected.review = false;
vm.selected.writeReview = false;
angular.element('#firstItem').focus();
}
vm.mobile = false;
}
function details(restaurant){
active('detail', restaurant);
$('.detail-first').focus();
}
function reviews(restaurant) {
active('review', restaurant);
$('.chats').focus();
}
function writeReview(restaurant) {
active('write', restaurant);
$('.write-first').focus();
}
function active(who, restaurant){
switch (who) {
case 'detail':
restaurant.pictures = false;
restaurant.detail = true;
restaurant.review = false;
restaurant.writeReview = false;
calcStars(restaurant);
break;
case 'review':
restaurant.pictures = false;
restaurant.detail = false;
restaurant.review = true;
restaurant.writeReview = false;
break;
case 'write':
restaurant.pictures = false;
restaurant.detail = false;
restaurant.review = false;
restaurant.writeReview = true;
break;
}
}
function calcStars(restaurant){
restaurant.stars = [];
restaurant.halfStar = [];
for (var i = 0; i < Math.floor(restaurant.rate); i++) {
restaurant.stars.push(i);
}
if(restaurant.rate % 1 !== 0)
restaurant.halfStar.push(1);
}
function publishReview(restaurant){
var restaurant_rate;
var review = {
userName: vm.user.name,
userPhoto: vm.user.image,
review: restaurant.reviews.message || '',
rate: restaurant.reviews.rate,
date: getDate(),
restaurant_id: restaurant.id
};
firebase.database().ref('reviews/').push(review);
firebase.database().ref('restaurants/' + (restaurant.id - 1) + '/rate').on('value', function(snapshot) {
restaurant_rate = snapshot.val() || 5;
});
restaurant_rate = (restaurant_rate + review.rate) * 0.5;
restaurant.rate = restaurant_rate;
firebase.database().ref('restaurants/' + (restaurant.id - 1) + '/rate').set(restaurant_rate);
restaurant.reviews.message = '';
restaurant.reviews.rate = 0;
restaurant.pictures = true;
restaurant.detail = false;
restaurant.review = false;
restaurant.writeReview = false;
// showToast(); TODO
}
function getDate(){
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth()+1; //January is 0!
var yyyy = today.getFullYear();
if(dd<10){
dd='0'+dd;
}
if(mm<10){
mm='0'+mm;
}
today = dd+'/'+mm+'/'+yyyy;
return today;
}
function mobile_select(restaurant){
$timeout(function() {
vm.mobile = true;
}, 800);
vm.selected = restaurant;
vm.selected.pictures = true;
vm.selected.detail = false;
vm.selected.review = false;
vm.selected.writeReview = false;
angular.element('#firstItemMobile').focus();
}
function quit(){
}
}
})();
|
import React, { Component } from 'react';
import firebase, { reference, signIn } from '../firebase';
import { pick, map, extend } from 'lodash';
class LogOutButton extends React.Component {
constructor(props) {
super(props);
}
render () {
return (
<button className='logout-button' onClick={this.props.handleClick} hidden>Log Out</button>
);
}
} //end of LogInButton
module.exports = LogOutButton;
|
import assert from 'assert';
import axios from 'axios';
import { getHttpApi } from '../bin/index';
describe('Http', function () {
it('should retrieve the http api', function () {
const api = getHttpApi();
assert.ok(typeof api === 'object');
})
it('should populate the http api', function () {
const api = getHttpApi();
assert.ok(Object.keys(api).length);
})
it('should use methods that correspond to axios methods', function () {
const apiKeys = Object.keys(getHttpApi());
apiKeys.forEach(key => {
assert.ok(typeof axios[key] === 'function');
})
})
}); |
'use strict';
var utils = require('./utils');
var trim = require('trim');
module.exports = function(pg, persistence, consumerPersistence, consumptionsPersistence, broadcast) {
var consumptions = {};
consumptions.getConsumptionRecords = function(req, res) {
console.log("get Consumption Record");
var days = req.params.days;
days = parseInt(days, 10);
if(typeof days==='number' && (days%1)===0) {
console.log("days back: "+days);
pg.connect(function(err, client, done) {
if (utils.handleError(err, client, done, res)) { return; }
consumptionsPersistence.getAllConsumptionRecords(client, days, function(consumptionRecords) {
done();
res.status(200);
res.json(consumptionRecords);
});
});
} else {
res.status(400);
res.json({
message: 'Not a number'
});
}
}
consumptions.create = function(req, res) {
console.log("create Consumption");
var barcode = trim(req.body.barcode);
if(req.body.username != undefined) {
var username = trim(req.body.username);
}
if(username == undefined) {
createAnonymousConsumtion(res, barcode);
} else {
createConsumtionWithUser(res, barcode, username);
}
};
/*
* DEPRECATED!
*/
consumptions.createWithConsumer = function(req, res) {
console.log("create Consumption with Consumer");
var username = trim(req.params.username);
var barcode = req.body.barcode;
if(username == "Anon") {
createAnonymousConsumtion(res, barcode);
} else {
createConsumtionWithUser(res, barcode, username);
}
}
consumptions.undo = function(req, res) {
console.log("undo Consmption")
var consumptionId = req.body.id;
var username = trim(req.body.username);
var barcode = trim(req.body.barcode);
undoConsumption(consumptionId, barcode, username, res);
}
consumptions.undoWithPar = function(req, res) {
console.log("undo Consmption")
var consumptionId = req.params.id;
var barcode = trim(req.params.barcode);
var username = trim(req.params.username);
undoConsumption(consumptionId, barcode, username, res);
}
function undoConsumption(consumptionId, barcode, username, res) {
pg.connect(function(err, client, done) {
if (utils.handleError(err, client, done, res)) { return; }
consumptionsPersistence.removeConsumptionRecord(client, consumptionId, function() {
persistence.getDrinkByBarcode(client, barcode, function(err, drink) {
persistence.updateDrink(client, drink.fullprice, drink.discountprice, drink.barcode, (drink.quantity+1), (drink.empties-1), function(err, drink) {
if(username == "Anon") {
console.log("-150");
res.status(201);
} else {
console.log("-125");
consumerPersistence.getConsumersByName(client, username, function(err, consumer) {
consumerPersistence.addDeposit(client, username, 125, function(err, updatedConsumer) {
res.status(201);
res.json(updatedConsumer);
});
});
}
});
});
});
});
}
consumptions.getConsumptionRecordsForUser = function(username, callback) {
pg.connect(function(err, client, done) {
if (utils.handleError(err, client, done, res)) { return; }
consumptionsPersistence.getConsumptionRecordsForUser(client, username, callback);
done();
});
}
function createAnonymousConsumtion(res, barcode) {
consumeDrinkIfAvaliable(res, barcode, "Anon", true);
}
function createConsumtionWithUser(res, barcode, username) {
pg.connect(function(err, client, done) {
if (utils.handleError(err, client, done, res)) { return; }
persistence.getDrinkByBarcode(client, barcode, function(err, drink) {
consumerPersistence.getConsumersByName(client, username, function(err, consumer) {
if (utils.handleError(err, client, done, res)) { return; }
if(!consumer || consumer == undefined) {
return;
}
if (consumer.ledger < drink.discountprice) {
done();
res.status(402);
res.json({
message: 'Insfficient Funds'
});
} else {
consumeDrinkIfAvaliable(res, barcode, username, false);
}
});
});
done();
});
}
function consumeDrinkIfAvaliable(res, barcode, username, payFullPrice) {
console.log("consume drink If Avaliable" + barcode + " " + username);
pg.connect(function(err, client, done) {
if (utils.handleError(err, client, done, res)) { return; }
persistence.getDrinkByBarcode(client, barcode, function(err, drink) {
if (drink.quantity == 0) {
done();
res.status(412);
res.json({
message: 'According to records this drink is not avaliable.'
});
} else {
consumeDrink(res, barcode, username, payFullPrice);
}
});
done();
});
}
function consumeDrink(res, barcode, username, payFullPrice) {
console.log("consume drink " + barcode + " " + username);
pg.connect(function(err, client, done) {
if (utils.handleError(err, client, done, res)) { return; }
persistence.consumeDrink(client, barcode, function(err, drink) {
var price = drink.discountprice * (-1);
if(payFullPrice) {
price = drink.fullprice * (-1);
console.log("amount " + price);
}
consumerPersistence.addDeposit(client, username, price, function(err, updatedConsumer) {
if(payFullPrice) {
console.log("+150");
} else {
console.log("+125");
}
if (updatedConsumer.vds) {
recordConsumptionForUser(res, client, updatedConsumer.username, drink, updatedConsumer, price);
} else {
recordConsumptionForUser(res, client, "Anon", drink, updatedConsumer, price);
}
})
});
done();
});
}
function recordConsumptionForUser(res, client, username, drink, updatedConsumer, price) {
console.log("recordConsumptionForUser ->" + username + " " + drink.name);
pg.connect(function(err, client, done) {
if (utils.handleError(err, client, done, res)) { return; }
consumptionsPersistence.recordConsumption(client, username, drink.barcode, price, function(undoCode) {
broadcast.sendEvent({
eventtype: 'consumption',
drink: drink.barcode
});
done();
res.status(201);
//TODO: return undo data.
undoCode["barcode"]=drink.barcode;
undoCode["username"]=updatedConsumer.username;
updatedConsumer["undoparameters"] = undoCode;
res.json(updatedConsumer);
});
});
}
return consumptions;
};
|
window.addEventListener("load", function() {
(function() {
var myPromise = new Promise((resolve, reject) => {
navigator.geolocation.getCurrentPosition((pos) => {
resolve(pos);
}, (error) => { reject(error); });
});
function parseCoords(pos) {
var obj = {
lat: pos.coords.latitude,
lon: pos.coords.longitude
};
console.log("Step 1 returns:", obj);
return obj;
}
function displayMap(pos) {
var img = document.createElement("img");
var content = document.getElementById("content");
var footer = document.createElement("strong");
footer.innerHTML = "The map will be here for 2 seconds!";
var key = "&key=AIzaSyA66MMq38FBzDEA_RZoDBX_rTvUcYE-VPA";
img.src = `https://maps.googleapis.com/maps/api/staticmap?center=${pos.lat},${pos.lon}&zoom=15&size=400x400`;
img.style.width = 500;
content.appendChild(img);
content.appendChild(footer);
console.log("Step 2 returns:", img);
return img;
}
function wait(time, img) {
return new Promise((resolve) => {
setTimeout(() => {
console.log("Step 3 returns:", img);
resolve(img);
}, time);
});
}
function fadeout(mapEl) {
mapEl.style.display = "none";
var footer = document.getElementsByTagName("strong")[0];
footer.innerHTML = "The map disappeared now!";
console.log("Step 4 returns:", mapEl);
return mapEl;
}
myPromise
.then((geoLoc) => parseCoords(geoLoc)) // what is returned goes to the next function
.then(pos => displayMap(pos)) // if we want to return many things, wrap them in object
.then((img) => wait(2000, img))
.then((mapEl) => fadeout(mapEl))
.catch((error) => console.log(error));
}());
}); |
"use strict";
var fx = require("framework");
var Class = fx.import("framework.Class");
var App = fx.import("framework.app.App");
var ProgressView = fx.import("framework.ui.view.ProgressView");
Class.define("MyApp", App, {
onStart: function() {
this.progressView = new ProgressView();
this.progressView.left = 20;
this.progressView.top = 50;
this.progressView.width = 280;
this.progressView.height = 30;
this.progressView.background = "#FEFEFE";
this.progressView.color = "#FF0000";
this.progressView.value = 0.4;
this.window.addChild(this.progressView);
}
}, module);
|
var fs = require('fs');
fs.access('/tmp/example.txt', fs.constants.R_OK, function(err) {
if (err) throw err;
console.log('File or directory is readable!')
})
|
import React from 'react';
import style from 'PVWStyle/ReactProperties/PropertyPanel.mcss';
import factory from '../PropertyFactory';
export default React.createClass({
displayName: 'PropertyPanel',
propTypes: {
className: React.PropTypes.string,
input: React.PropTypes.array,
labels: React.PropTypes.object,
onChange: React.PropTypes.func,
viewData: React.PropTypes.object,
},
getDefaultProps() {
return {
className: '',
input: [],
viewData: {},
};
},
valueChange(newVal) {
if (this.props.onChange) {
this.props.onChange(newVal);
}
},
render() {
var viewData = this.props.viewData,
uiContents = content => factory(content, viewData, this.valueChange),
uiContainer = property => (
<div key={property.title}>
<div className={style.propertyHeader}>
<strong>{property.title}</strong>
</div>
{property.contents.map(uiContents)}
</div>);
return (
<section className={[this.props.className, style.propertyPanel].join(' ')}>
{this.props.input.map(uiContainer)}
</section>);
},
});
|
'use strict';
/**
* Declare and export default values for middleware options.
* @module lib/defaults
*/
const curry = require('lodash.curry');
/**
* Name of default attributes shown on errors.
* This attributes can be customized by setting a
* `format` function during middleware declaration.
* @type {Array}
*/
const DEFAULT_PROPERTIES = [
'name',
'message',
'stack',
'type'
];
/**
* A pure curried reducer iteratee that builds a new object with properties
* named after the elements of the collection being reduced only if that
* property is also present in `err`.
* @param {Object} err The original raised error being handled.
* @param {Object} acum The reducer's acumulator.
* @param {String} propertyName Name of the new property to add to the acumulator.
* @return {Object} A new object with all of properties in `acum` as well
* as `err[propertyName]`, if `propertyName` is an
* enumerable property of `err`.
*/
const toErrorObject = curry((err, acum, propertyName) => {
return err[propertyName] ? Object.assign({}, acum, {
[propertyName]: err[propertyName]
}) : acum;
});
/**
* Default middleware configuration values.
* @type {Object}
*/
const DEFAULT_FORMATTING_PIPELINE = Object.freeze({
// Set all enumerable properties of error onto the object
preFormat: err => Object.assign({}, err),
// Add default custom properties to final error object
format: function(err, preFormattedError) {
const formattedError = DEFAULT_PROPERTIES.reduce(toErrorObject(err), {});
return Object.assign({}, preFormattedError, formattedError, {
status: err.status || err.statusCode || 500
});
},
// Final transformation after `options.format` (defaults to no op)
postFormat: null
});
// Module API
module.exports = {
DEFAULT_PROPERTIES,
DEFAULT_FORMATTING_PIPELINE
};
|
count = db.items.count();
num = 0;
print("Adding item.rootPost (" + count + ")");
db.items.find({}, {_id:1}).forEach(function(row) {
post = db.posts.findOne({
parent: null,
'target.$ref': 'items',
'target.$id': row._id,
}, {_id: 1});
if(post) {
db.items.update({_id: row._id}, {$set: {rootPost: {'$ref':'posts', '$id':post._id}}});
} else {
print(row._id + ' is missing a post');
}
if (!(++num % 1000)) {
print('processed ' + num + '/' + count + ' items');
}
});
print('done');
|
import React from "react";
import {
blockRenderMap as checkboxBlockRenderMap,
CheckableListItem,
CheckableListItemUtils,
CHECKABLE_LIST_ITEM,
} from "draft-js-checkable-list-item";
import { Map, OrderedSet, is } from "immutable";
import CodeBlock from "./components/Code";
import {
getDefaultKeyBinding,
Modifier,
EditorState,
RichUtils,
DefaultDraftInlineStyle,
} from "draft-js";
import adjustBlockDepth from "./modifiers/adjustBlockDepth";
import handleBlockType from "./modifiers/handleBlockType";
import handleInlineStyle from "./modifiers/handleInlineStyle";
import splitBlockAndChange from "./modifiers/splitBlockAndChange";
import handleNewCodeBlock from "./modifiers/handleNewCodeBlock";
import resetInlineStyle from "./modifiers/resetInlineStyle";
import insertEmptyBlock from "./modifiers/insertEmptyBlock";
import handleLink from "./modifiers/handleLink";
import handleImage from "./modifiers/handleImage";
import leaveList from "./modifiers/leaveList";
import insertText from "./modifiers/insertText";
import changeCurrentBlockType from "./modifiers/changeCurrentBlockType";
import createLinkDecorator from "./decorators/link";
import createImageDecorator from "./decorators/image";
import { replaceText, getCurrentLine } from "./utils";
import {
CODE_BLOCK_REGEX,
CODE_BLOCK_TYPE,
ENTITY_TYPE,
defaultInlineWhitelist,
defaultBlockWhitelist,
} from "./constants";
const defaultLanguages = {
bash: "Bash",
c: "C",
cpp: "C++",
css: "CSS",
go: "Go",
html: "HTML",
java: "Java",
js: "JavaScript",
kotlin: "Kotlin",
mathml: "MathML",
perl: "Perl",
ruby: "Ruby",
scala: "Scala",
sql: "SQL",
svg: "SVG",
swift: "Swift",
};
const INLINE_STYLE_CHARACTERS = ["*", "_", "`", "~"];
const defaultRenderSelect = ({ options, onChange, selectedValue }) => (
<select value={selectedValue} onChange={onChange}>
{options.map(({ label, value }) => (
<option key={value} value={value}>
{label}
</option>
))}
</select>
);
function inLink(editorState) {
const selection = editorState.getSelection();
const contentState = editorState.getCurrentContent();
const block = contentState.getBlockForKey(selection.getAnchorKey());
const entityKey = block.getEntityAt(selection.getFocusOffset());
return (
entityKey != null && contentState.getEntity(entityKey).getType() === "LINK"
);
}
function inCodeBlock(editorState) {
const startKey = editorState.getSelection().getStartKey();
if (startKey) {
const currentBlockType = editorState
.getCurrentContent()
.getBlockForKey(startKey)
.getType();
if (currentBlockType === "code-block") return true;
}
return false;
}
function checkCharacterForState(config, editorState, character) {
let newEditorState = handleBlockType(
config.features.block,
editorState,
character
);
if (
editorState === newEditorState &&
config.features.inline.includes("IMAGE")
) {
newEditorState = handleImage(
editorState,
character,
config.entityType.IMAGE
);
}
if (
editorState === newEditorState &&
config.features.inline.includes("LINK")
) {
newEditorState = handleLink(editorState, character, config.entityType.LINK);
}
if (
newEditorState === editorState &&
config.features.block.includes("CODE")
) {
const contentState = editorState.getCurrentContent();
const selection = editorState.getSelection();
const key = selection.getStartKey();
const currentBlock = contentState.getBlockForKey(key);
const text = currentBlock.getText();
const type = currentBlock.getType();
if (type !== "code-block" && CODE_BLOCK_REGEX.test(text))
newEditorState = handleNewCodeBlock(editorState);
}
if (editorState === newEditorState) {
newEditorState = handleInlineStyle(
config.features.inline,
editorState,
character
);
}
return newEditorState;
}
function checkReturnForState(config, editorState, ev) {
let newEditorState = editorState;
const contentState = editorState.getCurrentContent();
const selection = editorState.getSelection();
const isCollapsed = selection.isCollapsed();
const key = selection.getStartKey();
const endOffset = selection.getEndOffset();
const currentBlock = contentState.getBlockForKey(key);
const blockLength = currentBlock.getLength();
const type = currentBlock.getType();
const text = currentBlock.getText();
if (/-list-item$/.test(type) && text === "") {
newEditorState = leaveList(editorState);
}
const isHeader = /^header-/.test(type);
const isBlockQuote = type === "blockquote";
const isAtEndOfLine = endOffset === blockLength;
const atEndOfHeader = isHeader && isAtEndOfLine;
const atEndOfBlockQuote = isBlockQuote && isAtEndOfLine;
if (
newEditorState === editorState &&
isCollapsed &&
(atEndOfHeader || atEndOfBlockQuote)
) {
// transform markdown (if we aren't in a codeblock that is)
if (!inCodeBlock(editorState)) {
newEditorState = checkCharacterForState(config, newEditorState, "\n");
}
if (newEditorState === editorState) {
newEditorState = insertEmptyBlock(newEditorState);
} else {
newEditorState = RichUtils.toggleBlockType(newEditorState, type);
}
} else if (isCollapsed && (isHeader || isBlockQuote) && !isAtEndOfLine) {
newEditorState = splitBlockAndChange(newEditorState);
}
if (
newEditorState === editorState &&
type !== "code-block" &&
config.features.block.includes("CODE") &&
CODE_BLOCK_REGEX.test(text)
) {
newEditorState = handleNewCodeBlock(editorState);
}
if (newEditorState === editorState && type === "code-block") {
if (/```\s*$/.test(text)) {
newEditorState = changeCurrentBlockType(
newEditorState,
type,
text.replace(/```\s*$/, "")
);
newEditorState = insertEmptyBlock(newEditorState);
} else if (ev.shiftKey) {
newEditorState = insertEmptyBlock(newEditorState);
} else {
newEditorState = insertText(editorState, "\n");
}
}
return newEditorState;
}
const unstickyInlineStyles = (character, editorState) => {
const selection = editorState.getSelection();
if (!selection.isCollapsed()) return editorState;
if (editorState.getLastChangeType() !== "md-to-inline-style") {
return editorState;
}
const startOffset = selection.getStartOffset();
const content = editorState.getCurrentContent();
const block = content.getBlockForKey(selection.getStartKey());
const previousBlock = content.getBlockBefore(block.getKey());
const entity = block.getEntityAt(startOffset - 1);
if (entity !== null) return editorState;
// If we're currently in a style, but the next character doesn't have a style (or doesn't exist)
// we insert the characters manually without the inline style to "unsticky" them
if (!startOffset && previousBlock) {
// If we're in the beginning of the line we have to check styles of the previous block
const previousBlockStyle = previousBlock.getInlineStyleAt(
previousBlock.getText().length - 1
);
if (previousBlockStyle.size === 0) return editorState;
} else {
const style = block.getInlineStyleAt(startOffset - 1);
if (style.size === 0) return editorState;
}
const nextStyle = block.getInlineStyleAt(startOffset);
if (nextStyle.size !== 0) return editorState;
const newContent = Modifier.insertText(content, selection, character);
return EditorState.push(editorState, newContent, "insert-characters");
};
const defaultConfig = {
renderLanguageSelect: defaultRenderSelect,
languages: defaultLanguages,
features: {
inline: defaultInlineWhitelist,
block: defaultBlockWhitelist,
},
entityType: ENTITY_TYPE,
};
const createMarkdownPlugin = (_config = {}) => {
const store = {};
const config = {
...defaultConfig,
..._config,
features: {
...defaultConfig.features,
..._config.features,
},
entityType: {
...defaultConfig.entityType,
..._config.entityType,
},
};
return {
store,
blockRenderMap: Map({
"code-block": {
element: "code",
wrapper: <pre spellCheck="false" />,
},
}).merge(checkboxBlockRenderMap),
decorators: [
createLinkDecorator({
entityType: config.entityType.LINK,
}),
createImageDecorator({
entityType: config.entityType.IMAGE,
}),
],
initialize({ setEditorState, getEditorState }) {
store.setEditorState = setEditorState;
store.getEditorState = getEditorState;
},
blockStyleFn(block) {
switch (block.getType()) {
case CHECKABLE_LIST_ITEM:
return CHECKABLE_LIST_ITEM;
default:
break;
}
return null;
},
blockRendererFn(
block,
{ setReadOnly, getReadOnly, setEditorState, getEditorState, getEditorRef }
) {
switch (block.getType()) {
case CHECKABLE_LIST_ITEM: {
return {
component: CheckableListItem,
props: {
onChangeChecked: e => {
e.preventDefault();
setTimeout(() =>
setEditorState(
CheckableListItemUtils.toggleChecked(
getEditorState(),
block
)
)
);
},
checked: !!block.getData().get("checked"),
},
};
}
case CODE_BLOCK_TYPE: {
return {
component: CodeBlock,
props: {
setEditorState,
renderLanguageSelect: config.renderLanguageSelect,
languages: config.languages,
getReadOnly,
setReadOnly,
language: block.getData().get("language"),
getEditorState,
},
};
}
default:
return null;
}
},
onTab(ev, { getEditorState, setEditorState }) {
const editorState = getEditorState();
const newEditorState = adjustBlockDepth(editorState, ev);
if (newEditorState !== editorState) {
setEditorState(newEditorState);
return "handled";
}
return "not-handled";
},
handleReturn(ev, editorState, { setEditorState }) {
if (inLink(editorState)) return "not-handled";
let newEditorState = checkReturnForState(config, editorState, ev);
const selection = newEditorState.getSelection();
// exit code blocks
if (
inCodeBlock(editorState) &&
!is(editorState.getImmutable(), newEditorState.getImmutable())
) {
setEditorState(newEditorState);
return "handled";
}
newEditorState = checkCharacterForState(config, newEditorState, "\n");
let content = newEditorState.getCurrentContent();
// if there are actually no changes but the editorState has a
// current inline style we want to split the block
if (
is(editorState.getImmutable(), newEditorState.getImmutable()) &&
editorState.getCurrentInlineStyle().size > 0
) {
content = Modifier.splitBlock(content, selection);
}
newEditorState = resetInlineStyle(newEditorState);
if (editorState !== newEditorState) {
setEditorState(
EditorState.push(newEditorState, content, "split-block")
);
return "handled";
}
return "not-handled";
},
handleBeforeInput(character, editorState, { setEditorState }) {
// If we're in a code block - don't transform markdown
if (inCodeBlock(editorState)) return "not-handled";
// If we're in a link - don't transform markdown
if (inLink(editorState)) return "not-handled";
const unsticky = unstickyInlineStyles(character, editorState);
if (editorState !== unsticky) {
setEditorState(unsticky);
return "handled";
}
const newEditorState = checkCharacterForState(
config,
editorState,
character
);
if (editorState !== newEditorState) {
setEditorState(newEditorState);
return "handled";
}
return "not-handled";
},
handlePastedText(text, html, editorState, { setEditorState }) {
if (inCodeBlock(editorState)) {
setEditorState(insertText(editorState, text));
return "handled";
}
return "not-handled";
},
handleKeyCommand(command, editorState, { setEditorState }) {
switch (command) {
case "backspace": {
// When a styled block is the first thing in the editor,
// you cannot delete it. Typing backspace only deletes the content
// but never deletes the block styling.
// This piece of code fixes the issue by changing the block type
// to 'unstyled' if we're on the first block of the editor and it's empty
const selection = editorState.getSelection();
const currentBlockKey = selection.getStartKey();
if (!currentBlockKey) return "not-handled";
const content = editorState.getCurrentContent();
const currentBlock = content.getBlockForKey(currentBlockKey);
const firstBlock = content.getFirstBlock();
if (firstBlock !== currentBlock) return "not-handled";
const currentBlockType = currentBlock.getType();
const isEmpty = currentBlock.getLength() === 0;
if (!isEmpty || currentBlockType === "unstyled") return "not-handled";
setEditorState(changeCurrentBlockType(editorState, "unstyled", ""));
return "handled";
}
default: {
return "not-handled";
}
}
},
};
};
export default createMarkdownPlugin;
|
;(function () {
'use strict';
var isMobile = {
Android: function() {
return navigator.userAgent.match(/Android/i);
},
BlackBerry: function() {
return navigator.userAgent.match(/BlackBerry/i);
},
iOS: function() {
return navigator.userAgent.match(/iPhone|iPad|iPod/i);
},
Opera: function() {
return navigator.userAgent.match(/Opera Mini/i);
},
Windows: function() {
return navigator.userAgent.match(/IEMobile/i);
},
any: function() {
return (isMobile.Android() || isMobile.BlackBerry() || isMobile.iOS() || isMobile.Opera() || isMobile.Windows());
}
};
var mobileMenuOutsideClick = function() {
$(document).click(function (e) {
var container = $("#fh5co-offcanvas, .js-fh5co-nav-toggle");
if (!container.is(e.target) && container.has(e.target).length === 0) {
if ( $('body').hasClass('offcanvas') ) {
$('body').removeClass('offcanvas');
$('.js-fh5co-nav-toggle').removeClass('active');
}
}
});
};
var offcanvasMenu = function() {
$('#page').prepend('<div id="fh5co-offcanvas" />');
$('#page').prepend('<a href="#" class="js-fh5co-nav-toggle fh5co-nav-toggle fh5co-nav-white"><i></i></a>');
var clone1 = $('.menu-1 > ul').clone();
$('#fh5co-offcanvas').append(clone1);
var clone2 = $('.menu-2 > ul').clone();
$('#fh5co-offcanvas').append(clone2);
$('#fh5co-offcanvas .has-dropdown').addClass('offcanvas-has-dropdown');
$('#fh5co-offcanvas')
.find('li')
.removeClass('has-dropdown');
// Hover dropdown menu on mobile
$('.offcanvas-has-dropdown').mouseenter(function(){
var $this = $(this);
$this
.addClass('active')
.find('ul')
.slideDown(500, 'easeOutExpo');
}).mouseleave(function(){
var $this = $(this);
$this
.removeClass('active')
.find('ul')
.slideUp(500, 'easeOutExpo');
});
$(window).resize(function(){
if ( $('body').hasClass('offcanvas') ) {
$('body').removeClass('offcanvas');
$('.js-fh5co-nav-toggle').removeClass('active');
}
});
};
var burgerMenu = function() {
$('body').on('click', '.js-fh5co-nav-toggle', function(event){
var $this = $(this);
if ( $('body').hasClass('overflow offcanvas') ) {
$('body').removeClass('overflow offcanvas');
} else {
$('body').addClass('overflow offcanvas');
}
$this.toggleClass('active');
event.preventDefault();
});
};
var contentWayPoint = function() {
var i = 0;
$('.animate-box').waypoint( function( direction ) {
if( direction === 'down' && !$(this.element).hasClass('animated-fast') ) {
i++;
$(this.element).addClass('item-animate');
setTimeout(function(){
$('body .animate-box.item-animate').each(function(k){
var el = $(this);
setTimeout( function () {
var effect = el.data('animate-effect');
if ( effect === 'fadeIn') {
el.addClass('fadeIn animated-fast');
} else if ( effect === 'fadeInLeft') {
el.addClass('fadeInLeft animated-fast');
} else if ( effect === 'fadeInRight') {
el.addClass('fadeInRight animated-fast');
} else {
el.addClass('fadeInUp animated-fast');
}
el.removeClass('item-animate');
}, k * 200, 'easeInOutExpo' );
});
}, 100);
}
} , { offset: '85%' } );
};
var dropdown = function() {
$('.has-dropdown').mouseenter(function(){
var $this = $(this);
$this
.find('.dropdown')
.css('display', 'block')
.addClass('animated-fast fadeInUpMenu');
}).mouseleave(function(){
var $this = $(this);
$this
.find('.dropdown')
.css('display', 'none')
.removeClass('animated-fast fadeInUpMenu');
});
};
var goToTop = function() {
$('.js-gotop').on('click', function(event){
event.preventDefault();
$('html, body').animate({
scrollTop: $('html').offset().top
}, 500, 'easeInOutExpo');
return false;
});
$(window).scroll(function(){
var $win = $(window);
if ($win.scrollTop() > 200) {
$('.js-top').addClass('active');
} else {
$('.js-top').removeClass('active');
}
});
};
// Loading page
var loaderPage = function() {
$(".fh5co-loader").fadeOut("slow");
};
var counter = function() {
$('.js-counter').countTo({
formatter: function (value, options) {
return value.toFixed(options.decimals);
},
});
};
var counterWayPoint = function() {
if ($('#fh5co-counter').length > 0 ) {
$('#fh5co-counter').waypoint( function( direction ) {
if( direction === 'down' && !$(this.element).hasClass('animated') ) {
setTimeout( counter , 400);
$(this.element).addClass('animated');
}
} , { offset: '90%' } );
}
};
var sliderMain = function() {
$('#fh5co-hero .flexslider').flexslider({
animation: "fade",
slideshowSpeed: 5000,
directionNav: true,
start: function(){
setTimeout(function(){
$('.slider-text').removeClass('animated fadeInUp');
$('.flex-active-slide').find('.slider-text').addClass('animated fadeInUp');
}, 500);
},
before: function(){
setTimeout(function(){
$('.slider-text').removeClass('animated fadeInUp');
$('.flex-active-slide').find('.slider-text').addClass('animated fadeInUp');
}, 500);
}
});
};
var bibleVerseCarousel = function(){
var owl = $('.owl-carousel-fullwidth');
owl.owlCarousel({
animateOut: 'fadeOut',
autoplay:true,
items: 1,
loop: true,
margin: 0,
nav: false,
dots: true,
smartSpeed: 800,
autoHeight: true
});
};
$(function(){
mobileMenuOutsideClick();
offcanvasMenu();
burgerMenu();
contentWayPoint();
sliderMain();
dropdown();
goToTop();
loaderPage();
counterWayPoint();
bibleVerseCarousel();
});
}()); |
'use strict';
var path = require('path');
var helpers = require('yeoman-test');
var assert = require('yeoman-assert');
describe('Chisel Generator with jQuery in vendor bundle', function () {
before(function (done) {
helpers
.run(path.join(__dirname, '../../generators/app'))
.withOptions({
'skip-install': true
})
.withPrompts({
name: 'Test Project',
author: 'Test Author',
has_jquery: true,
has_jquery_vendor_config: true
})
.on('end', done);
});
it('should add jQuery as a dependency in package.json', function (done) {
assert.fileContent('package.json', '"jquery":');
done();
});
it('should create a jQuery example in a module', function (done) {
assert.file('src/scripts/modules/greeting.js');
assert.fileContent('src/scripts/modules/greeting.js', "import $ from 'jquery';");
assert.fileContent('src/scripts/modules/greeting.js', "const element = $('.js-greeting');");
done();
});
it('should create valid Yeoman configuration file', function (done) {
assert.file('.yo-rc.json');
assert.fileContent('.yo-rc.json', '"has_jquery": true' );
assert.fileContent('.yo-rc.json', '"has_jquery_vendor_config": true' );
done();
});
it('should create vendor list with jQuery', function(done) {
assert.fileContent('src/scripts/vendor.json', '"/node_modules/jquery/dist/jquery.js"');
done();
})
it('should add jQuery to externals in webpack config', function(done) {
assert.fileContent('webpack.chisel.config.js', "jquery: 'window.jQuery',");
done();
})
});
|
import React, { Component } from 'react';
export default class Hero extends Component {
render (){
const imageUrl = this.props.image;
const title = this.props.title;
let image;
if ( imageUrl !== '' ){
const styles = {
backgroundImage: 'url(' + imageUrl + ')'
};
image = <div className="collection-hero__image" style={styles}></div>;
} else {
image = <div className="collection-hero__image"></div>;
}
return (
<div className="collection-hero">
{image}
<div className="collection-hero__title-wrapper">
<h1 className="collection-hero__title page-width">{title}</h1>
</div>
</div>
);
}
} |
// All material copyright ESRI, All Rights Reserved, unless otherwise specified.
// See https://js.arcgis.com/4.16/esri/copyright.txt for details.
//>>built
define(["require","exports"],function(m,h){function k(a,d,e,c,b){if(null!=c&&null!=b&&c===b)return function(b){return c>=a.getAttribute(b,d)&&c<=a.getAttribute(b,e)};if(null!=c&&null!=b)return function(f){var g=a.getAttribute(f,d);f=a.getAttribute(f,e);return!(g>b||f<c)};if(null!=c)return function(b){return!(a.getAttribute(b,e)<c)};if(null!=b)return function(c){return!(a.getAttribute(c,d)>b)}}function l(a,d,e,c){if(null!=e&&null!=c&&e===c)return function(b){return a.getAttribute(b,d)===e};if(null!=
e&&null!=c)return function(b){return a.getAttribute(b,d)>=e&&a.getAttribute(b,d)<=c};if(null!=e)return function(b){return a.getAttribute(b,d)>=e};if(null!=c)return function(b){return a.getAttribute(b,d)<=c}}Object.defineProperty(h,"__esModule",{value:!0});h.getTimeExtent=function(a,d){if(!a)return null;var e=d.featureAdapter,c=a.startTimeField,b=a.endTimeField,f=Number.POSITIVE_INFINITY,g=Number.NEGATIVE_INFINITY;if(c&&b)d.forEach(function(a){var d=e.getAttribute(a,c);a=e.getAttribute(a,b);null==
d||isNaN(d)||(f=Math.min(f,d));null==a||isNaN(a)||(g=Math.max(g,a))});else{var h=c||b;d.forEach(function(a){a=e.getAttribute(a,h);null==a||isNaN(a)||(f=Math.min(f,a),g=Math.max(g,a))})}return{start:f,end:g}};h.getTimeOperator=function(a,d,e){if(!d||!a)return null;var c=a.startTimeField;a=a.endTimeField;if(!c&&!a)return null;var b=d.start;d=d.end;return null==b&&null==d?null:c&&a?k(e,c,a,b,d):l(e,c||a,b,d)}}); |
'use strict';
/***
* @ngdoc factory
* @name tiUtil
* @module ngTagsInput
*
* @description
* Helper methods used internally by the directive. Should not be called directly from user code.
*/
tagsInput.factory('tiUtil', function($timeout) {
var self = {};
self.debounce = function(fn, delay) {
var timeoutId;
return function() {
var args = arguments;
$timeout.cancel(timeoutId);
timeoutId = $timeout(function() { fn.apply(null, args); }, delay);
};
};
self.makeObjectArray = function(array, key) {
array = array || [];
if (array.length > 0 && !angular.isObject(array[0])) {
array.forEach(function(item, index) {
array[index] = {};
array[index][key] = item;
});
}
return array;
};
self.findInObjectArray = function(array, obj, key, comparer) {
var item = null;
comparer = comparer || self.defaultComparer;
array.some(function(element) {
if (comparer(element[key], obj[key])) {
item = element;
return true;
}
});
return item;
};
self.defaultComparer = function(a, b) {
// I'm aware of the internationalization issues regarding toLowerCase()
// but I couldn't come up with a better solution right now
return self.safeToString(a).toLowerCase() === self.safeToString(b).toLowerCase();
};
self.safeHighlight = function(str, value) {
if (!value) {
return str;
}
function escapeRegexChars(str) {
return str.replace(/([.?*+^$[\]\\(){}|-])/g, '\\$1');
}
str = self.encodeHTML(str);
value = self.encodeHTML(value);
var expression = new RegExp('&[^;]+;|' + escapeRegexChars(value), 'gi');
return str.replace(expression, function(match) {
return match.toLowerCase() === value.toLowerCase() ? '<em>' + match + '</em>' : match;
});
};
self.safeToString = function(value) {
return angular.isUndefined(value) || value == null ? '' : value.toString().trim();
};
self.encodeHTML = function(value) {
return self.safeToString(value)
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>');
};
self.handleUndefinedResult = function(fn, valueIfUndefined) {
return function() {
var result = fn.apply(null, arguments);
return angular.isUndefined(result) ? valueIfUndefined : result;
};
};
self.replaceSpacesWithDashes = function(str) {
return self.safeToString(str).replace(/\s/g, '-');
};
self.simplePubSub = function() {
var events = {};
return {
on: function(names, handler) {
names.split(' ').forEach(function(name) {
if (!events[name]) {
events[name] = [];
}
events[name].push(handler);
});
return this;
},
trigger: function(name, args) {
var handlers = events[name] || [];
handlers.every(function(handler) {
return self.handleUndefinedResult(handler, true)(args);
});
return this;
}
};
};
return self;
}); |
'use strict';
var checks = require('./checks');
var compare = require('./compare');
var NodeUtil = require('util');
var mongoose = require('mongoose');
var ObjectID = require('mongodb').ObjectID;
/**
* [validateObjectId description]
*
* @param {[type]} requestor
* @param {[type]} text
*
* @return {[type]}
*/
exports.validateObjectId = function validateObjectId(test, text) {
if (checks.isUndefined(test)) {
throw new Error('Input is missing');
}
if (checks.isUndefined(text)) {
throw new Error('Input is missing');
}
if (!checks.isString(test) && !checks.isObject(test)) {
throw new Error(NodeUtil.format('Expected %s to be a string or object', text));
}
if (checks.isString(test)) {
if (!compare.ObjectID.test(test)) {
throw new Error(NodeUtil.format('(%s) %s is not a valid Object ID', test, text));
}
return test;
}
if (checks.isObject(test)) {
if (test instanceof mongoose.Document) {
if (checks.isDefined(test.id)) {
if (!compare.ObjectID.test(test.id)) {
throw new Error(NodeUtil.format('(%s) %s is not a valid Object ID', NodeUtil.inspect(test.id, true, null), text));
}
return test.id;
}
} else if (test instanceof ObjectID) {
var tempTest = String(test);
// it's a normal ObjectId
if (!compare.ObjectID.test(tempTest)) {
throw new Error(NodeUtil.format('(%s) %s is not a valid Object ID', tempTest, text));
}
return tempTest;
} else {
if (checks.isDefined(test.id)) {
return this.validateObjectId(test.id, text);
}
}
}
throw new Error('Unknown input type');
};
/**
* [validateEmail description]
*
* @param {[type]} email
*
* @return {[type]}
*/
exports.validateEmail = function validateEmail(email) {
if (checks.isUndefined(email)) {
throw new Error('Email address is missing');
}
if (!compare.EmailAddress.test(email)) {
throw new Error('email must be a valid email address');
}
};
|
let o = {
f: function () {
if (this !== o)
throw new Error("MemberCall");
}
}
o.f(); |
var gulp = require('gulp'),
$ = require('gulp-load-plugins')(),
pkg = require('./package.json'),
fs = require('fs'),
changelog = require('conventional-changelog'),
karma = require('karma').server,
args = require('yargs').argv,
path = require('path'),
es = require('event-stream');
var express = require('express'),
http = require('http'),
server = http.createServer(express().use(express.static(__dirname + '/test/e2e/app/')));
gulp.task('js', ['jshint'], function () {
return gulp.src('js/**/*.js')
.pipe($.plumber())
.pipe($.concat('ng-markdown.js'))
.pipe(gulp.dest('dist'))
.pipe($.ngAnnotate())
.pipe($.uglify({ mangle: false }))
.pipe($.rename({ suffix: '.min' }))
.pipe(gulp.dest('dist'));
});
gulp.task('css', function () {
var _highlight = gulp.src('js/highlight/*.css');
var _sass = gulp.src('css/*.scss')
.pipe($.plumber())
.pipe($.rubySass({ compass: true, 'sourcemap=none': true }));
return es.merge(_sass, _highlight)
.pipe($.concat('ng-markdown.css'))
.pipe(gulp.dest('dist'))
.pipe($.minifyCss())
.pipe($.rename({ suffix: '.min' }))
.pipe(gulp.dest('dist'));
});
gulp.task('changelog', function () {
changelog({
version: pkg.version,
repository: 'https://github.com/Apercu/ng-markdown',
from: '2.0.0'
}, function(err, log) {
if (err) throw new Error(err);
fs.writeFileSync('CHANGELOG.md', log);
});
});
gulp.task('test', function () {
karma.start({
configFile: path.join(__dirname, 'test/karma.conf.js'),
browsers: ['PhantomJS'],
reporters: ['progress', 'coverage'],
singleRun: true
}, function (code) {
console.info('[Karma] exited with ', code);
if (!process.env.TRAVIS) { return code; }
console.info('[Coverage] Launching...');
gulp.src('test/coverage/**/lcov.info')
.pipe($.coveralls())
.on('end', function() {
process.exit(code);
});
});
});
gulp.task('jshint', function () {
gulp.src('js/*.js')
.pipe($.jshint())
.pipe($.jshint.reporter('default'));
});
gulp.task('e2e:server', function (callback) {
server.listen(8001, callback);
});
gulp.task('e2e:run', ['e2e:server'], function (callback) {
gulp.src('test/e2e/*.js')
.pipe($.protractor.protractor(
{
configFile: 'test/protractor.conf.js',
args: ['--baseUrl', 'http://' + server.address().address + ':' + server.address().port]
}
)).on('error', function (e) {
server.close();
callback(e);
}).on('end', function () {
server.close();
callback();
});
});
gulp.task('e2e:update', function () {
$.protractor.webdriver_update();
});
gulp.task('watch', function () {
gulp.watch('js/**/*.js', ['js']);
gulp.watch('css/*.scss', ['css']);
});
gulp.task('default', ['js', 'css', 'watch']);
|
'use strict';
/**
* 表单字段
*/
module.exports = function(data) {
data || (data = {});
return [{
label: '员工号',
colspan: 3,
attrs: {
type: 'text',
name: 'code',
required: 'required',
maxlength: 30,
value: data.code || ''
}
}, {
label: '名字',
colspan: 3,
attrs: {
type: 'text',
name: 'name',
maxlength: 200,
value: data.name || ''
}
}];
};
|
/*
Product Name: dhtmlxSuite
Version: 4.0.3
Edition: Standard
License: content of this file is covered by GPL. Usage outside GPL terms is prohibited. To obtain Commercial or Enterprise license contact sales@dhtmlx.com
Copyright UAB Dinamenta http://www.dhtmlx.com
*/
/* dhtmlx.com */
if (typeof(window.dhx4) == "undefined") {
window.dhx4 = {
version: "4.0.3",
skin: null, // allow to be set by user
skinDetect: function(comp) {
var t = document.createElement("DIV");
t.className = comp+"_skin_detect";
if (document.body.firstChild) document.body.insertBefore(t, document.body.firstChild); else document.body.appendChild(t);
var w = t.offsetWidth;
t.parentNode.removeChild(t);
t = null;
return {10:"dhx_skyblue",20:"dhx_web",30:"dhx_terrace"}[w]||null;
},
// id manager
lastId: 1,
newId: function() {
return this.lastId++;
},
// z-index manager
zim: {
data: {},
step: 5,
first: function() {
return 100;
},
last: function() {
var t = this.first();
for (var a in this.data) t = Math.max(t, this.data[a]);
return t;
},
reserve: function(id) {
this.data[id] = this.last()+this.step;
return this.data[id];
},
clear: function(id) {
if (this.data[id] != null) {
this.data[id] = null;
delete this.data[id];
}
}
},
// string to boolean
s2b: function(r) {
return (r == true || r == 1 || r == "true" || r == "1" || r == "yes" || r == "y");
},
// trim
trim: function(t) {
return String(t).replace(/^\s{1,}/,"").replace(/\s{1,}$/,"");
},
// template parsing
template: function(tpl, data, trim) {
// tpl - template text
// data - object with key-value
// trim - true/false, trim values
return tpl.replace(/#([a-zA-Z0-9_-]{1,})#/g, function(t,k){
if (k.length > 0 && typeof(data[k]) != "undefined") {
if (trim == true) return window.dhx4.trim(data[k]);
return String(data[k]);
}
return "";
});
},
// absolute top/left position on screen
absLeft: function(obj) {
if (typeof(obj) == "string") obj = document.getElementById(obj);
return this._aOfs(obj).left;
},
absTop: function(obj) {
if (typeof(obj) == "string") obj = document.getElementById(obj);
return this._aOfs(obj).top;
},
_aOfsSum: function(elem) {
var top = 0, left = 0;
while (elem) {
top = top + parseInt(elem.offsetTop);
left = left + parseInt(elem.offsetLeft);
elem = elem.offsetParent;
}
return {top: top, left: left};
},
_aOfsRect: function(elem) {
var box = elem.getBoundingClientRect();
var body = document.body;
var docElem = document.documentElement;
var scrollTop = window.pageYOffset || docElem.scrollTop || body.scrollTop;
var scrollLeft = window.pageXOffset || docElem.scrollLeft || body.scrollLeft;
var clientTop = docElem.clientTop || body.clientTop || 0;
var clientLeft = docElem.clientLeft || body.clientLeft || 0;
var top = box.top + scrollTop - clientTop;
var left = box.left + scrollLeft - clientLeft;
return { top: Math.round(top), left: Math.round(left) };
},
_aOfs: function(elem) {
if (elem.getBoundingClientRect) {
return this._aOfsRect(elem);
} else {
return this._aOfsSum(elem);
}
},
// copy obj
_isObj: function(k) {
return (k != null && typeof(k) == "object" && typeof(k.length) == "undefined");
},
_copyObj: function(r) {
if (this._isObj(r)) {
var t = {};
for (var a in r) {
if (typeof(r[a]) == "object" && r[a] != null) t[a] = this._copyObj(r[a]); else t[a] = r[a];
}
} else {
var t = [];
for (var a=0; a<r.length; a++) {
if (typeof(r[a]) == "object" && r[a] != null) t[a] = this._copyObj(r[a]); else t[a] = r[a];
}
}
return t;
},
// screen dim
screenDim: function() {
var isIE = (navigator.userAgent.indexOf("MSIE") >= 0);
var dim = {};
dim.left = document.body.scrollLeft;
dim.right = dim.left+(window.innerWidth||document.body.clientWidth);
dim.top = Math.max((isIE?document.documentElement:document.getElementsByTagName("html")[0]).scrollTop, document.body.scrollTop);
dim.bottom = dim.top+(isIE?Math.max(document.documentElement.clientHeight||0,document.documentElement.offsetHeight||0):window.innerHeight);
return dim;
},
// input/textarea range selection
selectTextRange: function(inp, start, end) {
inp = (typeof(inp)=="string"?document.getElementById(inp):inp);
var len = inp.value.length;
start = Math.max(Math.min(start, len), 0);
end = Math.min(end, len);
if (inp.setSelectionRange) {
try {inp.setSelectionRange(start, end);} catch(e){}; // combo in grid under IE requires try/catch
} else if (inp.createTextRange) {
var range = inp.createTextRange();
range.moveStart("character", start);
range.moveEnd("character", end-len);
try {range.select();} catch(e){};
}
},
// transition
transData: null,
transDetect: function() {
if (this.transData == null) {
this.transData = {transProp: false, transEv: null};
// transition, MozTransition, WebkitTransition, msTransition, OTransition
var k = {
"MozTransition": "transitionend",
"WebkitTransition": "webkitTransitionEnd",
"OTransition": "oTransitionEnd",
"msTransition": "transitionend",
"transition": "transitionend"
};
for (var a in k) {
if (this.transData.transProp == false && document.documentElement.style[a] != null) {
this.transData.transProp = a;
this.transData.transEv = k[a];
}
}
k = null;
}
return this.transData;
}
};
// browser
window.dhx4.isIE = (navigator.userAgent.indexOf("MSIE") >= 0 || navigator.userAgent.indexOf("Trident") >= 0);
window.dhx4.isIE6 = (window.XMLHttpRequest == null && navigator.userAgent.indexOf("MSIE") >= 0);
window.dhx4.isIE7 = (navigator.userAgent.indexOf("MSIE 7.0") >= 0 && navigator.userAgent.indexOf("Trident") < 0);
window.dhx4.isOpera = (navigator.userAgent.indexOf("Opera") >= 0);
window.dhx4.isChrome = (navigator.userAgent.indexOf("Chrome") >= 0);
window.dhx4.isKHTML = (navigator.userAgent.indexOf("Safari") >= 0 || navigator.userAgent.indexOf("Konqueror") >= 0);
window.dhx4.isFF = (navigator.userAgent.indexOf("Firefox") >= 0);
window.dhx4.isIPad = (navigator.userAgent.search(/iPad/gi) >= 0);
};
if (typeof(window.dhx4.ajax) == "undefined") {
window.dhx4.ajax = {
// if false - dhxr param will added to prevent caching on client side (default),
// if true - do not add extra params
cache: false,
// default method for load/loadStruct, post/get allowed
method: "post",
get: function(url, onLoad) {
this._call("GET", url, null, true, onLoad);
},
getSync: function(url) {
return this._call("GET", url, null, false);
},
post: function(url, postData, onLoad) {
if (arguments.length == 1) {
postData = "";
} else if (arguments.length == 2 && (typeof(postData) == "function" || typeof(window[postData]) == "function")) {
onLoad = postData;
postData = "";
} else {
postData = String(postData);
}
this._call("POST", url, postData, true, onLoad);
},
postSync: function(url, postData) {
postData = (postData == null ? "" : String(postData));
return this._call("POST", url, postData, false);
},
getLong: function(url, onLoad) {
this._call("GET", url, null, true, onLoad, {url:url});
},
postLong: function(url, postData, onLoad) {
if (arguments.length == 2 && (typeof(postData) == "function" || typeof(window[postData]))) {
onLoad = postData;
postData = "";
}
this._call("POST", url, postData, true, onLoad, {url:url, postData:postData});
},
_call: function(method, url, postData, async, onLoad, longParams) {
var t = (window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP"));
var isQt = (navigator.userAgent.match(/AppleWebKit/) != null && navigator.userAgent.match(/Qt/) != null && navigator.userAgent.match(/Safari/) != null);
if (async == true) {
t.onreadystatechange = function() {
if ((t.readyState == 4 && t.status == 200) || (isQt == true && t.readyState == 3)) { // what for long response and status 404?
window.setTimeout(function(){
if (typeof(onLoad) == "function") {
onLoad.apply(window, [{xmlDoc:t}]); // dhtmlx-compat, response.xmlDoc.responseXML/responseText
}
if (longParams != null) {
if (typeof(longParams.postData) != "undefined") {
dhx4.ajax.postLong(longParams.url, longParams.postData, onLoad);
} else {
dhx4.ajax.getLong(longParams.url, onLoad);
}
}
onLoad = null;
t = null;
},1);
}
}
}
if (method == "GET" && this.cache != true) {
url += (url.indexOf("?")>=0?"&":"?")+"dhxr"+new Date().getTime();
}
t.open(method, url, async);
if (method == "POST") {
t.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
if (this.cache != true) postData += (postData.length>0?"&":"")+"dhxr"+new Date().getTime();
} else {
postData = null;
}
t.setRequestHeader("X-Requested-With", "XMLHttpRequest");
t.send(postData);
if (!async) return {xmlDoc:t}; // dhtmlx-compat, response.xmlDoc.responseXML/responseText
}
};
};
if (typeof(window.dhx4._enableDataLoading) == "undefined") {
window.dhx4._enableDataLoading = function(obj, initObj, xmlToJson, xmlRootTag, mode) {
if (mode == "clear") {
// clear attached functionality
for (var a in obj._dhxdataload) {
obj._dhxdataload[a] = null;
delete obj._dhxdataload[a];
};
obj._loadData = null;
obj._dhxdataload = null;
obj.load = null;
obj.loadStruct = null;
obj = null;
return;
}
obj._dhxdataload = { // move to obj.conf?
initObj: initObj,
xmlToJson: xmlToJson,
xmlRootTag: xmlRootTag,
onBeforeXLS: null
};
obj._loadData = function(data, loadParams, onLoad) {
if (arguments.length == 2) {
onLoad = loadParams;
loadParams = null;
}
var obj = null;
// deprecated from 4.0, compatability with version (url, type[json|xml], onLoad)
if (arguments.length == 3) onLoad = arguments[2];
if (typeof(data) == "string") {
var k = data.replace(/^\s{1,}/,"").replace(/\s{1,}$/,"");
var tag = new RegExp("^<"+this._dhxdataload.xmlRootTag);
// xml
if (tag.test(k.replace(/^<\?xml[^\?]*\?>\s*/, ""))) { // remove leading <?xml ...?> if any, \n can be also presenе
if (window.DOMParser) { // ff,ie9
obj = (new window.DOMParser()).parseFromString(data, "text/xml");
} else if (typeof(window.ActiveXObject) != "undefined") {
obj = new window.ActiveXObject("Microsoft.XMLDOM");
obj.async = "false";
obj.loadXML(data);
}
if (obj != null) obj = this[this._dhxdataload.xmlToJson].apply(this, [obj]); // xml to json
}
if (obj == null && (k.match(/^\{.*\}$/) != null || k.match(/^\[.*\]$/) != null)) {
try { eval("dhx4.temp="+k); } catch(e) { dhx4.temp = null; }
obj = dhx4.temp;
dhx4.temp = null;
}
if (obj == null) {
this.callEvent("onXLS",[]);
var params = [];
// allow to modify url and add params
if (typeof(this._dhxdataload.onBeforeXLS) == "function") {
var k = this._dhxdataload.onBeforeXLS.apply(this,[data]);
if (k != null && typeof(k) == "object") {
if (k.url != null) data = k.url;
if (k.params != null) { for (var a in k.params) params.push(a+"="+encodeURIComponent(k.params[a])); }
}
}
var t = this;
var callBack = function(r) {
var obj = null;
if ((r.xmlDoc.getResponseHeader("Content-Type")||"").search(/xml/gi) >= 0 || (r.xmlDoc.responseText.replace(/^\s{1,}/,"")).match(/^</) != null) {
obj = t[t._dhxdataload.xmlToJson].apply(t,[r.xmlDoc.responseXML]);
} else {
try { eval("dhx4.temp="+r.xmlDoc.responseText); } catch(e){ dhx4.temp = null; };
obj = dhx4.temp;
dhx4.temp = null;
}
// init
if (obj != null) t[t._dhxdataload.initObj].apply(t,[obj,data]); // data => url
t.callEvent("onXLE",[]);
if (onLoad != null) {
if (typeof(onLoad) == "function") {
onLoad.apply(t,[]);
} else if (typeof(window[onLoad]) == "function") {
window[onLoad].apply(t,[]);
}
}
callBack = onLoad = null;
obj = r = t = null;
};
params = params.join("&")+(typeof(loadParams)=="string"?"&"+loadParams:"");
if (dhx4.ajax.method == "post") {
dhx4.ajax.post(data, params, callBack);
} else if (dhx4.ajax.method == "get") {
dhx4.ajax.get(data+(data.indexOf("?")>0?"":"")+params, callBack);
}
return;
}
} else {
if (typeof(data.documentElement) == "object" || (typeof(data.tagName) != "undefined" && typeof(data.getElementsByTagName) != "undefined" && data.getElementsByTagName(this._dhxdataload.xmlRootTag).length > 0)) { // xml
obj = this[this._dhxdataload.xmlToJson].apply(this, [data]);
} else { // json
obj = window.dhx4._copyObj(data);
}
}
// init
if (obj != null) this[this._dhxdataload.initObj].apply(this,[obj]);
if (onLoad != null) {
if (typeof(onLoad) == "function") {
onLoad.apply(this, []);
} else if (typeof(window[onLoad]) == "function") {
window[onLoad].apply(this, []);
}
onLoad = null;
}
};
// loadStruct for hdr/conf
// load for data
if (mode != null) {
var k = {struct: "loadStruct", data: "load"};
for (var a in mode) {
if (mode[a] == true) obj[k[a]] = function() {return this._loadData.apply(this, arguments);}
}
}
obj = null;
};
};
if (typeof(window.dhx4._eventable) == "undefined") {
window.dhx4._eventable = function(obj, mode) {
if (mode == "clear") {
obj.detachAllEvents();
obj.dhxevs = null;
obj.attachEvent = null;
obj.detachEvent = null;
obj.checkEvent = null;
obj.callEvent = null;
obj.detachAllEvents = null;
obj = null;
return;
}
obj.dhxevs = { data: {} };
obj.attachEvent = function(name, func) {
name = String(name).toLowerCase();
if (!this.dhxevs.data[name]) this.dhxevs.data[name] = {};
var eventId = window.dhx4.newId();
this.dhxevs.data[name][eventId] = func;
return eventId;
}
obj.detachEvent = function(eventId) {
for (var a in this.dhxevs.data) {
var k = 0;
for (var b in this.dhxevs.data[a]) {
if (b == eventId) {
this.dhxevs.data[a][b] = null;
delete this.dhxevs.data[a][b];
} else {
k++;
}
}
if (k == 0) {
this.dhxevs.data[a] = null;
delete this.dhxevs.data[a];
}
}
}
obj.checkEvent = function(name) {
name = String(name).toLowerCase();
return (this.dhxevs.data[name] != null);
}
obj.callEvent = function(name, params) {
name = String(name).toLowerCase();
if (this.dhxevs.data[name] == null) return true;
var r = true;
for (var a in this.dhxevs.data[name]) {
r = this.dhxevs.data[name][a].apply(this, params) && r;
}
return r;
}
obj.detachAllEvents = function() {
for (var a in this.dhxevs.data) {
for (var b in this.dhxevs.data[a]) {
this.dhxevs.data[a][b] = null;
delete this.dhxevs.data[a][b];
}
this.dhxevs.data[a] = null;
delete this.dhxevs.data[a];
}
}
obj = null;
};
};
dhtmlx=function(obj){
for (var a in obj) dhtmlx[a]=obj[a];
return dhtmlx; //simple singleton
};
dhtmlx.extend_api=function(name,map,ext){
var t = window[name];
if (!t) return; //component not defined
window[name]=function(obj){
if (obj && typeof obj == "object" && !obj.tagName){
var that = t.apply(this,(map._init?map._init(obj):arguments));
//global settings
for (var a in dhtmlx)
if (map[a]) this[map[a]](dhtmlx[a]);
//local settings
for (var a in obj){
if (map[a]) this[map[a]](obj[a]);
else if (a.indexOf("on")==0){
this.attachEvent(a,obj[a]);
}
}
} else
var that = t.apply(this,arguments);
if (map._patch) map._patch(this);
return that||this;
};
window[name].prototype=t.prototype;
if (ext)
dhtmlXHeir(window[name].prototype,ext);
};
dhtmlxAjax={
get:function(url,callback){
var t=new dtmlXMLLoaderObject(true);
t.async=(arguments.length<3);
t.waitCall=callback;
t.loadXML(url)
return t;
},
post:function(url,post,callback){
var t=new dtmlXMLLoaderObject(true);
t.async=(arguments.length<4);
t.waitCall=callback;
t.loadXML(url,true,post)
return t;
},
getSync:function(url){
return this.get(url,null,true)
},
postSync:function(url,post){
return this.post(url,post,null,true);
}
}
/**
* @desc: xmlLoader object
* @type: private
* @param: funcObject - xml parser function
* @param: object - jsControl object
* @param: async - sync/async mode (async by default)
* @param: rSeed - enable/disable random seed ( prevent IE caching)
* @topic: 0
*/
function dtmlXMLLoaderObject(funcObject, dhtmlObject, async, rSeed){
this.xmlDoc="";
if (typeof (async) != "undefined")
this.async=async;
else
this.async=true;
this.onloadAction=funcObject||null;
this.mainObject=dhtmlObject||null;
this.waitCall=null;
this.rSeed=rSeed||false;
return this;
};
dtmlXMLLoaderObject.count = 0;
/**
* @desc: xml loading handler
* @type: private
* @param: dtmlObject - xmlLoader object
* @topic: 0
*/
dtmlXMLLoaderObject.prototype.waitLoadFunction=function(dhtmlObject){
var once = true;
this.check=function (){
if ((dhtmlObject)&&(dhtmlObject.onloadAction != null)){
if ((!dhtmlObject.xmlDoc.readyState)||(dhtmlObject.xmlDoc.readyState == 4)){
if (!once)
return;
once=false; //IE 5 fix
dtmlXMLLoaderObject.count++;
if (typeof dhtmlObject.onloadAction == "function")
dhtmlObject.onloadAction(dhtmlObject.mainObject, null, null, null, dhtmlObject);
if (dhtmlObject.waitCall){
dhtmlObject.waitCall.call(this,dhtmlObject);
dhtmlObject.waitCall=null;
}
}
}
};
return this.check;
};
/**
* @desc: return XML top node
* @param: tagName - top XML node tag name (not used in IE, required for Safari and Mozilla)
* @type: private
* @returns: top XML node
* @topic: 0
*/
dtmlXMLLoaderObject.prototype.getXMLTopNode=function(tagName, oldObj){
if (typeof this.xmlDoc.status == "undefined" || this.xmlDoc.status < 400){
if (this.xmlDoc.responseXML){
var temp = this.xmlDoc.responseXML.getElementsByTagName(tagName);
if(temp.length==0 && tagName.indexOf(":")!=-1)
var temp = this.xmlDoc.responseXML.getElementsByTagName((tagName.split(":"))[1]);
var z = temp[0];
} else
var z = this.xmlDoc.documentElement;
if (z){
this._retry=false;
return z;
}
if (!this._retry&&_isIE){
this._retry=true;
var oldObj = this.xmlDoc;
this.loadXMLString(this.xmlDoc.responseText.replace(/^[\s]+/,""), true);
return this.getXMLTopNode(tagName, oldObj);
}
}
dhtmlxError.throwError("LoadXML", "Incorrect XML", [
(oldObj||this.xmlDoc),
this.mainObject
]);
return document.createElement("DIV");
};
/**
* @desc: load XML from string
* @type: private
* @param: xmlString - xml string
* @topic: 0
*/
dtmlXMLLoaderObject.prototype.loadXMLString=function(xmlString, silent){
if (!_isIE){
var parser = new DOMParser();
this.xmlDoc=parser.parseFromString(xmlString, "text/xml");
} else {
this.xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
this.xmlDoc.async=this.async;
this.xmlDoc.onreadystatechange = function(){};
this.xmlDoc["loadXM"+"L"](xmlString);
}
if (silent)
return;
if (this.onloadAction)
this.onloadAction(this.mainObject, null, null, null, this);
if (this.waitCall){
this.waitCall();
this.waitCall=null;
}
}
/**
* @desc: load XML
* @type: private
* @param: filePath - xml file path
* @param: postMode - send POST request
* @param: postVars - list of vars for post request
* @topic: 0
*/
dtmlXMLLoaderObject.prototype.loadXML=function(filePath, postMode, postVars, rpc){
if (this.rSeed)
filePath+=((filePath.indexOf("?") != -1) ? "&" : "?")+"a_dhx_rSeed="+(new Date()).valueOf();
this.filePath=filePath;
if ((!_isIE)&&(window.XMLHttpRequest))
this.xmlDoc=new XMLHttpRequest();
else {
this.xmlDoc=new ActiveXObject("Microsoft.XMLHTTP");
}
if (this.async)
this.xmlDoc.onreadystatechange=new this.waitLoadFunction(this);
this.xmlDoc.open(postMode ? "POST" : "GET", filePath, this.async);
if (rpc){
this.xmlDoc.setRequestHeader("User-Agent", "dhtmlxRPC v0.1 ("+navigator.userAgent+")");
this.xmlDoc.setRequestHeader("Content-type", "text/xml");
}
else if (postMode)
this.xmlDoc.setRequestHeader('Content-type', (this.contenttype || 'application/x-www-form-urlencoded'));
this.xmlDoc.setRequestHeader("X-Requested-With","XMLHttpRequest");
this.xmlDoc.send(null||postVars);
if (!this.async)
(new this.waitLoadFunction(this))();
};
/**
* @desc: destructor, cleans used memory
* @type: private
* @topic: 0
*/
dtmlXMLLoaderObject.prototype.destructor=function(){
this._filterXPath = null;
this._getAllNamedChilds = null;
this._retry = null;
this.async = null;
this.rSeed = null;
this.filePath = null;
this.onloadAction = null;
this.mainObject = null;
this.xmlDoc = null;
this.doXPath = null;
this.doXPathOpera = null;
this.doXSLTransToObject = null;
this.doXSLTransToString = null;
this.loadXML = null;
this.loadXMLString = null;
// this.waitLoadFunction = null;
this.doSerialization = null;
this.xmlNodeToJSON = null;
this.getXMLTopNode = null;
this.setXSLParamValue = null;
return null;
}
dtmlXMLLoaderObject.prototype.xmlNodeToJSON = function(node){
var t={};
for (var i=0; i<node.attributes.length; i++)
t[node.attributes[i].name]=node.attributes[i].value;
t["_tagvalue"]=node.firstChild?node.firstChild.nodeValue:"";
for (var i=0; i<node.childNodes.length; i++){
var name=node.childNodes[i].tagName;
if (name){
if (!t[name]) t[name]=[];
t[name].push(this.xmlNodeToJSON(node.childNodes[i]));
}
}
return t;
}
/**
* @desc: Call wrapper
* @type: private
* @param: funcObject - action handler
* @param: dhtmlObject - user data
* @returns: function handler
* @topic: 0
*/
function callerFunction(funcObject, dhtmlObject){
this.handler=function(e){
if (!e)
e=window.event;
funcObject(e, dhtmlObject);
return true;
};
return this.handler;
};
/**
* @desc: Calculate absolute position of html object
* @type: private
* @param: htmlObject - html object
* @topic: 0
*/
function getAbsoluteLeft(htmlObject){
return getOffset(htmlObject).left;
}
/**
* @desc: Calculate absolute position of html object
* @type: private
* @param: htmlObject - html object
* @topic: 0
*/
function getAbsoluteTop(htmlObject){
return getOffset(htmlObject).top;
}
function getOffsetSum(elem) {
var top=0, left=0;
while(elem) {
top = top + parseInt(elem.offsetTop);
left = left + parseInt(elem.offsetLeft);
elem = elem.offsetParent;
}
return {top: top, left: left};
}
function getOffsetRect(elem) {
var box = elem.getBoundingClientRect();
var body = document.body;
var docElem = document.documentElement;
var scrollTop = window.pageYOffset || docElem.scrollTop || body.scrollTop;
var scrollLeft = window.pageXOffset || docElem.scrollLeft || body.scrollLeft;
var clientTop = docElem.clientTop || body.clientTop || 0;
var clientLeft = docElem.clientLeft || body.clientLeft || 0;
var top = box.top + scrollTop - clientTop;
var left = box.left + scrollLeft - clientLeft;
return { top: Math.round(top), left: Math.round(left) };
}
function getOffset(elem) {
if (elem.getBoundingClientRect) {
return getOffsetRect(elem);
} else {
return getOffsetSum(elem);
}
}
/**
* @desc: Convert string to it boolean representation
* @type: private
* @param: inputString - string for covertion
* @topic: 0
*/
function convertStringToBoolean(inputString){
if (typeof (inputString) == "string")
inputString=inputString.toLowerCase();
switch (inputString){
case "1":
case "true":
case "yes":
case "y":
case 1:
case true:
return true;
break;
default: return false;
}
}
/**
* @desc: find out what symbol to use as url param delimiters in further params
* @type: private
* @param: str - current url string
* @topic: 0
*/
function getUrlSymbol(str){
if (str.indexOf("?") != -1)
return "&"
else
return "?"
}
function dhtmlDragAndDropObject(){
if (window.dhtmlDragAndDrop)
return window.dhtmlDragAndDrop;
this.lastLanding=0;
this.dragNode=0;
this.dragStartNode=0;
this.dragStartObject=0;
this.tempDOMU=null;
this.tempDOMM=null;
this.waitDrag=0;
window.dhtmlDragAndDrop=this;
return this;
};
dhtmlDragAndDropObject.prototype.removeDraggableItem=function(htmlNode){
htmlNode.onmousedown=null;
htmlNode.dragStarter=null;
htmlNode.dragLanding=null;
}
dhtmlDragAndDropObject.prototype.addDraggableItem=function(htmlNode, dhtmlObject){
htmlNode.onmousedown=this.preCreateDragCopy;
htmlNode.dragStarter=dhtmlObject;
this.addDragLanding(htmlNode, dhtmlObject);
}
dhtmlDragAndDropObject.prototype.addDragLanding=function(htmlNode, dhtmlObject){
htmlNode.dragLanding=dhtmlObject;
}
dhtmlDragAndDropObject.prototype.preCreateDragCopy=function(e){
if ((e||window.event) && (e||event).button == 2)
return;
if (window.dhtmlDragAndDrop.waitDrag){
window.dhtmlDragAndDrop.waitDrag=0;
document.body.onmouseup=window.dhtmlDragAndDrop.tempDOMU;
document.body.onmousemove=window.dhtmlDragAndDrop.tempDOMM;
return false;
}
if (window.dhtmlDragAndDrop.dragNode)
window.dhtmlDragAndDrop.stopDrag(e);
window.dhtmlDragAndDrop.waitDrag=1;
window.dhtmlDragAndDrop.tempDOMU=document.body.onmouseup;
window.dhtmlDragAndDrop.tempDOMM=document.body.onmousemove;
window.dhtmlDragAndDrop.dragStartNode=this;
window.dhtmlDragAndDrop.dragStartObject=this.dragStarter;
document.body.onmouseup=window.dhtmlDragAndDrop.preCreateDragCopy;
document.body.onmousemove=window.dhtmlDragAndDrop.callDrag;
window.dhtmlDragAndDrop.downtime = new Date().valueOf();
if ((e)&&(e.preventDefault)){
e.preventDefault();
return false;
}
return false;
};
dhtmlDragAndDropObject.prototype.callDrag=function(e){
if (!e)
e=window.event;
dragger=window.dhtmlDragAndDrop;
if ((new Date()).valueOf()-dragger.downtime<100) return;
//if ((e.button == 0)&&(_isIE))
// return dragger.stopDrag();
if (!dragger.dragNode){
if (dragger.waitDrag){
dragger.dragNode=dragger.dragStartObject._createDragNode(dragger.dragStartNode, e);
if (!dragger.dragNode)
return dragger.stopDrag();
dragger.dragNode.onselectstart=function(){return false;}
dragger.gldragNode=dragger.dragNode;
document.body.appendChild(dragger.dragNode);
document.body.onmouseup=dragger.stopDrag;
dragger.waitDrag=0;
dragger.dragNode.pWindow=window;
dragger.initFrameRoute();
}
else return dragger.stopDrag(e, true);
}
if (dragger.dragNode.parentNode != window.document.body && dragger.gldragNode){
var grd = dragger.gldragNode;
if (dragger.gldragNode.old)
grd=dragger.gldragNode.old;
//if (!document.all) dragger.calculateFramePosition();
grd.parentNode.removeChild(grd);
var oldBody = dragger.dragNode.pWindow;
if (grd.pWindow && grd.pWindow.dhtmlDragAndDrop.lastLanding)
grd.pWindow.dhtmlDragAndDrop.lastLanding.dragLanding._dragOut(grd.pWindow.dhtmlDragAndDrop.lastLanding);
// var oldp=dragger.dragNode.parentObject;
if (_isIE){
var div = document.createElement("Div");
div.innerHTML=dragger.dragNode.outerHTML;
dragger.dragNode=div.childNodes[0];
} else
dragger.dragNode=dragger.dragNode.cloneNode(true);
dragger.dragNode.pWindow=window;
// dragger.dragNode.parentObject=oldp;
dragger.gldragNode.old=dragger.dragNode;
document.body.appendChild(dragger.dragNode);
oldBody.dhtmlDragAndDrop.dragNode=dragger.dragNode;
}
dragger.dragNode.style.left=e.clientX+15+(dragger.fx
? dragger.fx*(-1)
: 0)
+(document.body.scrollLeft||document.documentElement.scrollLeft)+"px";
dragger.dragNode.style.top=e.clientY+3+(dragger.fy
? dragger.fy*(-1)
: 0)
+(document.body.scrollTop||document.documentElement.scrollTop)+"px";
if (!e.srcElement)
var z = e.target;
else
z=e.srcElement;
dragger.checkLanding(z, e);
}
dhtmlDragAndDropObject.prototype.calculateFramePosition=function(n){
//this.fx = 0, this.fy = 0;
if (window.name){
var el = parent.frames[window.name].frameElement.offsetParent;
var fx = 0;
var fy = 0;
while (el){
fx+=el.offsetLeft;
fy+=el.offsetTop;
el=el.offsetParent;
}
if ((parent.dhtmlDragAndDrop)){
var ls = parent.dhtmlDragAndDrop.calculateFramePosition(1);
fx+=ls.split('_')[0]*1;
fy+=ls.split('_')[1]*1;
}
if (n)
return fx+"_"+fy;
else
this.fx=fx;
this.fy=fy;
}
return "0_0";
}
dhtmlDragAndDropObject.prototype.checkLanding=function(htmlObject, e){
if ((htmlObject)&&(htmlObject.dragLanding)){
if (this.lastLanding)
this.lastLanding.dragLanding._dragOut(this.lastLanding);
this.lastLanding=htmlObject;
this.lastLanding=this.lastLanding.dragLanding._dragIn(this.lastLanding, this.dragStartNode, e.clientX,
e.clientY, e);
this.lastLanding_scr=(_isIE ? e.srcElement : e.target);
} else {
if ((htmlObject)&&(htmlObject.tagName != "BODY"))
this.checkLanding(htmlObject.parentNode, e);
else {
if (this.lastLanding)
this.lastLanding.dragLanding._dragOut(this.lastLanding, e.clientX, e.clientY, e);
this.lastLanding=0;
if (this._onNotFound)
this._onNotFound();
}
}
}
dhtmlDragAndDropObject.prototype.stopDrag=function(e, mode){
dragger=window.dhtmlDragAndDrop;
if (!mode){
dragger.stopFrameRoute();
var temp = dragger.lastLanding;
dragger.lastLanding=null;
if (temp)
temp.dragLanding._drag(dragger.dragStartNode, dragger.dragStartObject, temp, (_isIE
? event.srcElement
: e.target));
}
dragger.lastLanding=null;
if ((dragger.dragNode)&&(dragger.dragNode.parentNode == document.body))
dragger.dragNode.parentNode.removeChild(dragger.dragNode);
dragger.dragNode=0;
dragger.gldragNode=0;
dragger.fx=0;
dragger.fy=0;
dragger.dragStartNode=0;
dragger.dragStartObject=0;
document.body.onmouseup=dragger.tempDOMU;
document.body.onmousemove=dragger.tempDOMM;
dragger.tempDOMU=null;
dragger.tempDOMM=null;
dragger.waitDrag=0;
}
dhtmlDragAndDropObject.prototype.stopFrameRoute=function(win){
if (win)
window.dhtmlDragAndDrop.stopDrag(1, 1);
for (var i = 0; i < window.frames.length; i++){
try{
if ((window.frames[i] != win)&&(window.frames[i].dhtmlDragAndDrop))
window.frames[i].dhtmlDragAndDrop.stopFrameRoute(window);
} catch(e){}
}
try{
if ((parent.dhtmlDragAndDrop)&&(parent != window)&&(parent != win))
parent.dhtmlDragAndDrop.stopFrameRoute(window);
} catch(e){}
}
dhtmlDragAndDropObject.prototype.initFrameRoute=function(win, mode){
if (win){
window.dhtmlDragAndDrop.preCreateDragCopy();
window.dhtmlDragAndDrop.dragStartNode=win.dhtmlDragAndDrop.dragStartNode;
window.dhtmlDragAndDrop.dragStartObject=win.dhtmlDragAndDrop.dragStartObject;
window.dhtmlDragAndDrop.dragNode=win.dhtmlDragAndDrop.dragNode;
window.dhtmlDragAndDrop.gldragNode=win.dhtmlDragAndDrop.dragNode;
window.document.body.onmouseup=window.dhtmlDragAndDrop.stopDrag;
window.waitDrag=0;
if (((!_isIE)&&(mode))&&((!_isFF)||(_FFrv < 1.8)))
window.dhtmlDragAndDrop.calculateFramePosition();
}
try{
if ((parent.dhtmlDragAndDrop)&&(parent != window)&&(parent != win))
parent.dhtmlDragAndDrop.initFrameRoute(window);
}catch(e){}
for (var i = 0; i < window.frames.length; i++){
try{
if ((window.frames[i] != win)&&(window.frames[i].dhtmlDragAndDrop))
window.frames[i].dhtmlDragAndDrop.initFrameRoute(window, ((!win||mode) ? 1 : 0));
} catch(e){}
}
}
_isFF = false;
_isIE = false;
_isOpera = false;
_isKHTML = false;
_isMacOS = false;
_isChrome = false;
_FFrv = false;
_KHTMLrv = false;
_OperaRv = false;
if (navigator.userAgent.indexOf('Macintosh') != -1)
_isMacOS=true;
if (navigator.userAgent.toLowerCase().indexOf('chrome')>-1)
_isChrome=true;
if ((navigator.userAgent.indexOf('Safari') != -1)||(navigator.userAgent.indexOf('Konqueror') != -1)){
_KHTMLrv = parseFloat(navigator.userAgent.substr(navigator.userAgent.indexOf('Safari')+7, 5));
if (_KHTMLrv > 525){ //mimic FF behavior for Safari 3.1+
_isFF=true;
_FFrv = 1.9;
} else
_isKHTML=true;
} else if (navigator.userAgent.indexOf('Opera') != -1){
_isOpera=true;
_OperaRv=parseFloat(navigator.userAgent.substr(navigator.userAgent.indexOf('Opera')+6, 3));
}
else if (navigator.appName.indexOf("Microsoft") != -1){
_isIE=true;
if ((navigator.appVersion.indexOf("MSIE 8.0")!= -1 ||
navigator.appVersion.indexOf("MSIE 9.0")!= -1 ||
navigator.appVersion.indexOf("MSIE 10.0")!= -1 ||
document.documentMode > 7) &&
document.compatMode != "BackCompat"){
_isIE=8;
}
} else if (navigator.appName == 'Netscape' && navigator.userAgent.indexOf("Trident") != -1){
//ie11
_isIE=8;
} else {
_isFF=true;
_FFrv = parseFloat(navigator.userAgent.split("rv:")[1])
}
//multibrowser Xpath processor
dtmlXMLLoaderObject.prototype.doXPath=function(xpathExp, docObj, namespace, result_type){
if (_isKHTML || (!_isIE && !window.XPathResult))
return this.doXPathOpera(xpathExp, docObj);
if (_isIE){ //IE
if (!docObj)
if (!this.xmlDoc.nodeName)
docObj=this.xmlDoc.responseXML
else
docObj=this.xmlDoc;
if (!docObj)
dhtmlxError.throwError("LoadXML", "Incorrect XML", [
(docObj||this.xmlDoc),
this.mainObject
]);
if (namespace != null)
docObj.setProperty("SelectionNamespaces", "xmlns:xsl='"+namespace+"'"); //
if (result_type == 'single'){
return docObj.selectSingleNode(xpathExp);
}
else {
return docObj.selectNodes(xpathExp)||new Array(0);
}
} else { //Mozilla
var nodeObj = docObj;
if (!docObj){
if (!this.xmlDoc.nodeName){
docObj=this.xmlDoc.responseXML
}
else {
docObj=this.xmlDoc;
}
}
if (!docObj)
dhtmlxError.throwError("LoadXML", "Incorrect XML", [
(docObj||this.xmlDoc),
this.mainObject
]);
if (docObj.nodeName.indexOf("document") != -1){
nodeObj=docObj;
}
else {
nodeObj=docObj;
docObj=docObj.ownerDocument;
}
var retType = XPathResult.ANY_TYPE;
if (result_type == 'single')
retType=XPathResult.FIRST_ORDERED_NODE_TYPE
var rowsCol = new Array();
var col = docObj.evaluate(xpathExp, nodeObj, function(pref){
return namespace
}, retType, null);
if (retType == XPathResult.FIRST_ORDERED_NODE_TYPE){
return col.singleNodeValue;
}
var thisColMemb = col.iterateNext();
while (thisColMemb){
rowsCol[rowsCol.length]=thisColMemb;
thisColMemb=col.iterateNext();
}
return rowsCol;
}
}
function _dhtmlxError(type, name, params){
if (!this.catches)
this.catches=new Array();
return this;
}
_dhtmlxError.prototype.catchError=function(type, func_name){
this.catches[type]=func_name;
}
_dhtmlxError.prototype.throwError=function(type, name, params){
if (this.catches[type])
return this.catches[type](type, name, params);
if (this.catches["ALL"])
return this.catches["ALL"](type, name, params);
alert("Error type: "+arguments[0]+"\nDescription: "+arguments[1]);
return null;
}
window.dhtmlxError=new _dhtmlxError();
//opera fake, while 9.0 not released
//multibrowser Xpath processor
dtmlXMLLoaderObject.prototype.doXPathOpera=function(xpathExp, docObj){
//this is fake for Opera
var z = xpathExp.replace(/[\/]+/gi, "/").split('/');
var obj = null;
var i = 1;
if (!z.length)
return [];
if (z[0] == ".")
obj=[docObj]; else if (z[0] == ""){
obj=(this.xmlDoc.responseXML||this.xmlDoc).getElementsByTagName(z[i].replace(/\[[^\]]*\]/g, ""));
i++;
} else
return [];
for (i; i < z.length; i++)obj=this._getAllNamedChilds(obj, z[i]);
if (z[i-1].indexOf("[") != -1)
obj=this._filterXPath(obj, z[i-1]);
return obj;
}
dtmlXMLLoaderObject.prototype._filterXPath=function(a, b){
var c = new Array();
var b = b.replace(/[^\[]*\[\@/g, "").replace(/[\[\]\@]*/g, "");
for (var i = 0; i < a.length; i++)
if (a[i].getAttribute(b))
c[c.length]=a[i];
return c;
}
dtmlXMLLoaderObject.prototype._getAllNamedChilds=function(a, b){
var c = new Array();
if (_isKHTML)
b=b.toUpperCase();
for (var i = 0; i < a.length; i++)for (var j = 0; j < a[i].childNodes.length; j++){
if (_isKHTML){
if (a[i].childNodes[j].tagName&&a[i].childNodes[j].tagName.toUpperCase() == b)
c[c.length]=a[i].childNodes[j];
}
else if (a[i].childNodes[j].tagName == b)
c[c.length]=a[i].childNodes[j];
}
return c;
}
function dhtmlXHeir(a, b){
for (var c in b)
if (typeof (b[c]) == "function")
a[c]=b[c];
return a;
}
function dhtmlxEvent(el, event, handler){
if (el.addEventListener)
el.addEventListener(event, handler, false);
else if (el.attachEvent)
el.attachEvent("on"+event, handler);
}
//============= XSL Extension ===================================
dtmlXMLLoaderObject.prototype.xslDoc=null;
dtmlXMLLoaderObject.prototype.setXSLParamValue=function(paramName, paramValue, xslDoc){
if (!xslDoc)
xslDoc=this.xslDoc
if (xslDoc.responseXML)
xslDoc=xslDoc.responseXML;
var item =
this.doXPath("/xsl:stylesheet/xsl:variable[@name='"+paramName+"']", xslDoc,
"http:/\/www.w3.org/1999/XSL/Transform", "single");
if (item != null)
item.firstChild.nodeValue=paramValue
}
dtmlXMLLoaderObject.prototype.doXSLTransToObject=function(xslDoc, xmlDoc){
if (!xslDoc)
xslDoc=this.xslDoc;
if (xslDoc.responseXML)
xslDoc=xslDoc.responseXML
if (!xmlDoc)
xmlDoc=this.xmlDoc;
if (xmlDoc.responseXML)
xmlDoc=xmlDoc.responseXML
//MOzilla
if (!_isIE){
if (!this.XSLProcessor){
this.XSLProcessor=new XSLTProcessor();
this.XSLProcessor.importStylesheet(xslDoc);
}
var result = this.XSLProcessor.transformToDocument(xmlDoc);
} else {
var result = new ActiveXObject("Msxml2.DOMDocument.3.0");
try{
xmlDoc.transformNodeToObject(xslDoc, result);
}catch(e){
result = xmlDoc.transformNode(xslDoc);
}
}
return result;
}
dtmlXMLLoaderObject.prototype.doXSLTransToString=function(xslDoc, xmlDoc){
var res = this.doXSLTransToObject(xslDoc, xmlDoc);
if(typeof(res)=="string")
return res;
return this.doSerialization(res);
}
dtmlXMLLoaderObject.prototype.doSerialization=function(xmlDoc){
if (!xmlDoc)
xmlDoc=this.xmlDoc;
if (xmlDoc.responseXML)
xmlDoc=xmlDoc.responseXML
if (!_isIE){
var xmlSerializer = new XMLSerializer();
return xmlSerializer.serializeToString(xmlDoc);
} else
return xmlDoc.xml;
}
/**
* @desc:
* @type: private
*/
dhtmlxEventable=function(obj){
obj.attachEvent=function(name, catcher, callObj){
name='ev_'+name.toLowerCase();
if (!this[name])
this[name]=new this.eventCatcher(callObj||this);
return(name+':'+this[name].addEvent(catcher)); //return ID (event name & event ID)
}
obj.callEvent=function(name, arg0){
name='ev_'+name.toLowerCase();
if (this[name])
return this[name].apply(this, arg0);
return true;
}
obj.checkEvent=function(name){
return (!!this['ev_'+name.toLowerCase()])
}
obj.eventCatcher=function(obj){
var dhx_catch = [];
var z = function(){
var res = true;
for (var i = 0; i < dhx_catch.length; i++){
if (dhx_catch[i] != null){
var zr = dhx_catch[i].apply(obj, arguments);
res=res&&zr;
}
}
return res;
}
z.addEvent=function(ev){
if (typeof (ev) != "function")
ev=eval(ev);
if (ev)
return dhx_catch.push(ev)-1;
return false;
}
z.removeEvent=function(id){
dhx_catch[id]=null;
}
return z;
}
obj.detachEvent=function(id){
if (id != false){
var list = id.split(':'); //get EventName and ID
this[list[0]].removeEvent(list[1]); //remove event
}
}
obj.detachAllEvents = function(){
for (var name in this){
if (name.indexOf("ev_")==0){
this.detachEvent(name);
this[name] = null;
}
}
}
obj = null;
};
|
var map = require('array-map');
var filter = require('array-filter');
var reduce = require('array-reduce');
exports.quote = function (xs) {
return map(xs, function (s) {
if (s && typeof s === 'object') {
return s.op.replace(/(.)/g, '\\$1');
}
else if (/["\s]/.test(s) && !/'/.test(s)) {
return "'" + s.replace(/(['\\])/g, '\\$1') + "'";
}
else if (/["'\s]/.test(s)) {
return '"' + s.replace(/(["\\$`!])/g, '\\$1') + '"';
}
else {
return String(s).replace(/([#!"$&'()*,:;<=>?@\[\\\]^`{|}])/g, '\\$1');
}
}).join(' ');
};
var CONTROL = '(?:' + [
'\\|\\|', '\\&\\&', ';;', '\\|\\&', '[&;()|<>]'
].join('|') + ')';
var META = '|&;()<> \\t';
var BAREWORD = '(\\\\[\'"' + META + ']|[^\\s\'"' + META + '])+';
var SINGLE_QUOTE = '"((\\\\"|[^"])*?)"';
var DOUBLE_QUOTE = '\'((\\\\\'|[^\'])*?)\'';
var TOKEN = '';
for (var i = 0; i < 4; i++) {
TOKEN += (Math.pow(16,8)*Math.random()).toString(16);
}
exports.parse = function (s, env, opts) {
var mapped = parse(s, env, opts);
if (typeof env !== 'function') return mapped;
return reduce(mapped, function (acc, s) {
if (typeof s === 'object') return acc.concat(s);
var xs = s.split(RegExp('(' + TOKEN + '.*?' + TOKEN + ')', 'g'));
if (xs.length === 1) return acc.concat(xs[0]);
return acc.concat(map(filter(xs, Boolean), function (x) {
if (RegExp('^' + TOKEN).test(x)) {
return JSON.parse(x.split(TOKEN)[1]);
}
else return x;
}));
}, []);
};
function parse (s, env, opts) {
var chunker = new RegExp([
'(' + CONTROL + ')', // control chars
'(' + BAREWORD + '|' + SINGLE_QUOTE + '|' + DOUBLE_QUOTE + ')*'
].join('|'), 'g');
var match = filter(s.match(chunker), Boolean);
var commented = false;
if (!match) return [];
if (!env) env = {};
if (!opts) opts = {};
return map(match, function (s, j) {
if (commented) {
return;
}
if (RegExp('^' + CONTROL + '$').test(s)) {
return { op: s };
}
// Hand-written scanner/parser for Bash quoting rules:
//
// 1. inside single quotes, all characters are printed literally.
// 2. inside double quotes, all characters are printed literally
// except variables prefixed by '$' and backslashes followed by
// either a double quote or another backslash.
// 3. outside of any quotes, backslashes are treated as escape
// characters and not printed (unless they are themselves escaped)
// 4. quote context can switch mid-token if there is no whitespace
// between the two quote contexts (e.g. all'one'"token" parses as
// "allonetoken")
var SQ = "'";
var DQ = '"';
var DS = '$';
var BS = opts.escape || '\\';
var quote = false;
var esc = false;
var out = '';
var isGlob = false;
for (var i = 0, len = s.length; i < len; i++) {
var c = s.charAt(i);
isGlob = isGlob || (!quote && (c === '*' || c === '?'));
if (esc) {
out += c;
esc = false;
}
else if (quote) {
if (c === quote) {
quote = false;
}
else if (quote == SQ) {
out += c;
}
else { // Double quote
if (c === BS) {
i += 1;
c = s.charAt(i);
if (c === DQ || c === BS || c === DS) {
out += c;
} else {
out += BS + c;
}
}
else if (c === DS) {
out += parseEnvVar();
}
else {
out += c;
}
}
}
else if (c === DQ || c === SQ) {
quote = c;
}
else if (RegExp('^' + CONTROL + '$').test(c)) {
return { op: s };
}
else if (RegExp('^#$').test(c)) {
commented = true;
if (out.length){
return [out, { comment: s.slice(i+1) + match.slice(j+1).join(' ') }];
}
return [{ comment: s.slice(i+1) + match.slice(j+1).join(' ') }];
}
else if (c === BS) {
esc = true;
}
else if (c === DS) {
out += parseEnvVar();
}
else out += c;
}
if (isGlob) return {op: 'glob', pattern: out};
return out;
function parseEnvVar() {
i += 1;
var varend, varname;
//debugger
if (s.charAt(i) === '{') {
i += 1;
if (s.charAt(i) === '}') {
throw new Error("Bad substitution: " + s.substr(i - 2, 3));
}
varend = s.indexOf('}', i);
if (varend < 0) {
throw new Error("Bad substitution: " + s.substr(i));
}
varname = s.substr(i, varend - i);
i = varend;
}
else if (/[*@#?$!_\-]/.test(s.charAt(i))) {
varname = s.charAt(i);
i += 1;
}
else {
varend = s.substr(i).match(/[^\w\d_]/);
if (!varend) {
varname = s.substr(i);
i = s.length;
} else {
varname = s.substr(i, varend.index);
i += varend.index - 1;
}
}
return getVar(null, '', varname);
}
})
// finalize parsed aruments
.reduce(function(prev, arg){
if (arg === undefined){
return prev;
}
return prev.concat(arg);
},[]);
function getVar (_, pre, key) {
var r = typeof env === 'function' ? env(key) : env[key];
if (r === undefined) r = '';
if (typeof r === 'object') {
return pre + TOKEN + JSON.stringify(r) + TOKEN;
}
else return pre + r;
}
}
|
var _ = require('lodash');
var url = require('url');
var numberOfHeroes = require('./res/heroes.json').length;
function getNextUrl(originalUrl, currentPage) {
var nextPage = parseInt(currentPage, 10) + 1 || 2;
if (_.isEmpty(currentPage)) {
originalUrl += _.endsWith(originalUrl, '/') ? nextPage: '/' + nextPage;
} else {
originalUrl = _.chain(originalUrl).split('/').slice(0, -1) // split to array, remove current page
.push(nextPage).join('/').value(); // add next page, join array
}
return originalUrl;
}
function nextUrlMiddleware(request, response, next) {
if (_.isEmpty(request.params.heroesPerRequest)) return;
var oldJson = response.json,
originalUrl = url.format({
protocol: request.protocol,
host: request.get('host'),
pathname: request.originalUrl,
});
response.json = function(data) {
var nHeroes = parseInt(request.params.heroesPerRequest, 10),
page = parseInt(request.params.page, 10) || 1,
nextUrl = null;
// arguments[0] contains the body passed in
arguments[0].next = (nHeroes * page >= numberOfHeroes)
? null
: getNextUrl(originalUrl, request.params.page);
oldJson.apply(response, arguments);
}
next();
}
function validateHeroesStatRequest(request, response, next) {
var params = request.params,
nHeroes = parseInt(params.heroesPerRequest, 10),
parsedPage = parseInt(params.page, 10);
if ((_.isFinite(nHeroes) && nHeroes > 0 && _.isEmpty(params.page)) ||
(_.isFinite(nHeroes) && nHeroes > 0 && _.isFinite(parsedPage) && parsedPage > 0)) {
next();
} else {
return response.send(400);
}
}
module.exports = {
heroesPaginate: nextUrlMiddleware,
validate: validateHeroesStatRequest
};
|
angular.module('app.maps', ['ngResource']); |
var express = require('express'),
path = require('path'),
cookieParser = require('cookie-parser'),
bodyParser = require('body-parser'),
compression = require('compression'),
colors = require( "colors");
var routes = require('./routes/index'),
config = require('./conf/config');
var minify;
var app = express();
process.env.NODE_ENV = process.env.NODE_ENV || 'development';
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
// 访问日志记录,console打印
if (app.get('env') === 'development') {
app.use(require('morgan')('dev'));
}
app.use(compression());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
//设置自定义响应头, 希望你留下这些作者说明
app.use(function (req, res, next) {
var encrypted = (req.protocol || 'http')==='https';
app.locals['constant'] = {
name: config.name || '谷搜客',
encrypted: encrypted,
autocomplate_url: encrypted ? config.ssl.autocomplate_url : config.autocomplate_url,
r_prefix: encrypted ? config.ssl.r_prefix : config.r_prefix
};
next();
});
if (app.get('env') === 'production') {
// html minify
minify = require('html-minifier').minify;
app.use(function (req, res, next) {
res._render = res.render;
res.render = function(view, options, fn){
var self = this;
var req = this.req;
fn = fn || function(err, str){
if (err) return req.next(err);
self.send(minify(str,{removeComments: true,collapseWhitespace: true,minifyJS:true, minifyCSS:true}));
};
// render
self._render(view, options, fn);
};
next();
});
}
app.use('/', routes);
/// catch 404 and forward to error handler
app.use(function(req, res, next) {
res.status(404);
var url = req.url;
res.render('404', {
url : url
});
});
/// error handlers
app.use(function(err, req, res, next) {
res.status(err.status || 500);
// console.error(err.message.red);
//console.error(err.stack);
res.render('500', {
message: err.message,
error: {}
});
});
module.exports = app;
|
/**
* Created by Pradeep on 4/28/2017.
*/
(function() {
$.fatNav();
}());
|
"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var core_1 = require('@angular/core');
var steps_information_service_1 = require('../services/steps-information.service');
var router_1 = require('@angular/router');
var DashboardComponent = (function () {
function DashboardComponent(router, stepsService) {
this.router = router;
this.stepsService = stepsService;
this.steps = [];
}
DashboardComponent.prototype.ngOnInit = function () {
var _this = this;
this.stepsService.getSteps().
then(function (steps) { return _this.steps = steps; });
};
DashboardComponent.prototype.gotoStep = function (step) {
var link = ['/step', step.name];
this.router.navigate(link);
};
DashboardComponent = __decorate([
core_1.Component({
selector: 'steps-dashboard',
templateUrl: 'app/dashboard/dashboard.component.html',
styleUrls: ['app/dashboard/dashboard.component.css']
}),
__metadata('design:paramtypes', [router_1.Router, steps_information_service_1.StepsInformationService])
], DashboardComponent);
return DashboardComponent;
}());
exports.DashboardComponent = DashboardComponent;
//# sourceMappingURL=dashboard.component.js.map |
/**
* Copyright 2012-2020, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
'use strict';
var Axes = require('../../plots/cartesian/axes');
var isArray1D = require('../../lib').isArray1D;
var cheaterBasis = require('./cheater_basis');
var arrayMinmax = require('./array_minmax');
var calcGridlines = require('./calc_gridlines');
var calcLabels = require('./calc_labels');
var calcClipPath = require('./calc_clippath');
var clean2dArray = require('../heatmap/clean_2d_array');
var smoothFill2dArray = require('./smooth_fill_2d_array');
var convertColumnData = require('../heatmap/convert_column_xyz');
var setConvert = require('./set_convert');
module.exports = function calc(gd, trace) {
var xa = Axes.getFromId(gd, trace.xaxis);
var ya = Axes.getFromId(gd, trace.yaxis);
var aax = trace.aaxis;
var bax = trace.baxis;
var x = trace.x;
var y = trace.y;
var cols = [];
if(x && isArray1D(x)) cols.push('x');
if(y && isArray1D(y)) cols.push('y');
if(cols.length) {
convertColumnData(trace, aax, bax, 'a', 'b', cols);
}
var a = trace._a = trace._a || trace.a;
var b = trace._b = trace._b || trace.b;
x = trace._x || trace.x;
y = trace._y || trace.y;
var t = {};
if(trace._cheater) {
var avals = aax.cheatertype === 'index' ? a.length : a;
var bvals = bax.cheatertype === 'index' ? b.length : b;
x = cheaterBasis(avals, bvals, trace.cheaterslope);
}
trace._x = x = clean2dArray(x);
trace._y = y = clean2dArray(y);
// Fill in any undefined values with elliptic smoothing. This doesn't take
// into account the spacing of the values. That is, the derivatives should
// be modified to use a and b values. It's not that hard, but this is already
// moderate overkill for just filling in missing values.
smoothFill2dArray(x, a, b);
smoothFill2dArray(y, a, b);
setConvert(trace);
// create conversion functions that depend on the data
trace.setScale();
// This is a rather expensive scan. Nothing guarantees monotonicity,
// so we need to scan through all data to get proper ranges:
var xrange = arrayMinmax(x);
var yrange = arrayMinmax(y);
var dx = 0.5 * (xrange[1] - xrange[0]);
var xc = 0.5 * (xrange[1] + xrange[0]);
var dy = 0.5 * (yrange[1] - yrange[0]);
var yc = 0.5 * (yrange[1] + yrange[0]);
// Expand the axes to fit the plot, except just grow it by a factor of 1.3
// because the labels should be taken into account except that's difficult
// hence 1.3.
var grow = 1.3;
xrange = [xc - dx * grow, xc + dx * grow];
yrange = [yc - dy * grow, yc + dy * grow];
trace._extremes[xa._id] = Axes.findExtremes(xa, xrange, {padded: true});
trace._extremes[ya._id] = Axes.findExtremes(ya, yrange, {padded: true});
// Enumerate the gridlines, both major and minor, and store them on the trace
// object:
calcGridlines(trace, 'a', 'b');
calcGridlines(trace, 'b', 'a');
// Calculate the text labels for each major gridline and store them on the
// trace object:
calcLabels(trace, aax);
calcLabels(trace, bax);
// Tabulate points for the four segments that bound the axes so that we can
// map to pixel coordinates in the plot function and create a clip rect:
t.clipsegments = calcClipPath(trace._xctrl, trace._yctrl, aax, bax);
t.x = x;
t.y = y;
t.a = a;
t.b = b;
return [t];
};
|
var JSProblemState = {
'selected': 'No response selected'
};
console.log('inner ready');
// If someone clicks a radio button, put its value into the state.
let formbits = document.forms.emojibox.elements;
Array.from(formbits).forEach(function(e){
e.addEventListener('change', function(){
console.log(e.value);
JSProblemState.selected = e.value;
// Goal for later: make the problem submit itself when you select.
});
});
// This wrapper function is necessary.
var emoji_response = (function() {
// REQUIRED --- DO NOT REMOVE/CHANGE!!
var channel;
// REQUIRED --- DO NOT REMOVE/CHANGE!!
if (window.parent !== window) {
channel = Channel.build({
window: window.parent,
origin: '*',
scope: 'JSInput'
});
channel.bind('getGrade', getGrade);
channel.bind('getState', getState);
channel.bind('setState', setState);
}
// getState() and setState() are required by the problem type.
function getState(){
console.log('getting state');
return JSON.stringify(JSProblemState);
}
function setState() {
console.log('setting state');
stateStr = arguments.length === 1 ? arguments[0] : arguments[1];
JSProblemState = JSON.parse(stateStr);
// Set the radio button
let barevalue = JSProblemState.selected.split(' ').slice(0, -1).join('_');
let theID = barevalue.replace(/ /g,'_');
let radiobutton = document.getElementById(theID);
radiobutton.checked = true;
}
function getGrade() {
console.log('getting grade');
JSProblemState.survey_complete = true;
// Log the problem state.
// This is called from the parent window's Javascript so that we can write to the official edX logs.
parent.logThatThing(JSProblemState);
// Return the whole problem state.
return JSON.stringify(JSProblemState);
}
// REQUIRED --- DO NOT REMOVE/CHANGE!!
return {
getState: getState,
setState: setState,
getGrade: getGrade
};
}());
|
const image_financial_security = require('images/aspiration_finsec_small.png')
export default function (state, action) {
return [
{
title: 'Financial Security',
what: 'A future where I only work when I want',
why: 'I want to decide how i invest my time',
mantra: 'I am saving now for a worry free future',
confidence: 'High',
color: '#5297E1',
image: image_financial_security,
goals: [
{
title: 'Own Home',
probability: 0.87
},
{
title: 'Retirement',
probability: 0.49
}
]
}
]
}
|
var FileRendererAppDirective = angular.module('FileRendererApp.Directive', ['ngResource','ui.bootstrap', 'jsonFormatter']);
FileRendererAppDirective.directive('sidebarToggle', function() {
return {
link: function(scope, element, attrs) {
$('[data-toggle=offcanvas]').click(function() {
$('.row-offcanvas').toggleClass('active');
});
}
}
});
FileRendererAppDirective.directive('hboTabs', function() {
return {
restrict: 'A',
link: function(scope, elm, attrs) {
var jqueryElm = $(elm[0]);
$(jqueryElm).tabs()
}
};
});
FileRendererAppDirective.directive('toggleBar', function () {
return {
link: function (scope, element, attrs) {
element.click(function () {
$('.row-offcanvas-left').removeClass('active');
});
}
}
});
/*
eventumDirective.directive('sideBar', function() {
return {
link: function(scope, element, attrs) {
$('.sideBarList li').click(function () {
$('.row-offcanvas').toggleClass('active');
});
}
}
});
eventumDirective.directive('helloMaps', function () {
return function (scope, elem, attrs) {
var mapOptions,
latitude = attrs.latitude,
longitude = attrs.longitude,
map;
latitude = latitude && parseFloat(latitude, 10) || 43.074688;
longitude = longitude && parseFloat(longitude, 10) || -89.384294;
mapOptions = {
zoom: 8,
center: new google.maps.LatLng(latitude, longitude)
};
map = new google.maps.Map(elem[0], mapOptions);
};
});
eventumDirective.directive('activeLink', ['$location', function(location) {
return {
restrict: 'A',
link: function(scope, element, attrs, controller) {
var clazz = attrs.activeLink;
var path = attrs.href;
path = path.substring(1);
scope.location = location;
scope.$watch('location.path()', function(newPath) {
if (path === newPath) {
element.addClass(clazz);
} else {
element.removeClass(clazz);
}
});
}
};
}]);
eventumDirective.directive('agendaDays', ['$timeout', function ($timeout) {
return {
restrict: 'A',
link: function(scope, element, attrs, controller) {
element.find('li').click(function (event) {
element.find('li').removeClass('active');
console.log(event.target);
});
}
};
}]);
eventumDirective.directive('readMore', function() {
return {
link: function(scope, element, attrs) {
// DOM Ready
var readall = attrs.readMore;
$(function() {
var $el, $ps, $up, totalHeight;
$(".sidebar-box .button").click(function() {
// IE 7 doesn't even get this far. I didn't feel like dicking with it.
totalHeight = 0
$el = $(this);
$p = $el.parent();
$up = $p.parent();
$ps = $up.find("p:not('.read-more')");
// measure how tall inside should be by adding together heights of all inside paragraphs (except read-more paragraph)
$ps.each(function() {
totalHeight += $(this).outerHeight() * readall;
// FAIL totalHeight += $(this).css("margin-bottom");
});
$up
.css({
// Set height to prevent instant jumpdown when max height is removed
"height": $up.height(),
"max-height": 9999
})
.animate({
"height": totalHeight
});
// fade out read-more
$p.fadeOut();
// prevent jump-down
return false;
});
});
}
}
});
eventumDirective.directive('readHide', function() {
return {
link: function(scope, element, attrs) {
// DOM Ready
var chNo = attrs.readHide;
console.log(chNo);
if(chNo < 120){
console.log("this is in the catagory");
element.hide();
}
}
}
});
eventumDirective.directive('comMents', function() {
return {
link: function(scope, element, attrs) {
// DOM Ready
$(".comments").click(function(){
element.scrollTop = element.scrollHeight;
})
}
}
});
eventumDirective.directive('speakerShow', function() {
return {
link: function(scope, element, attrs) {
// DOM Ready
var isSpeaker = attrs.speakerShow;
console.log("value is " + isSpeaker);
if(! isSpeaker){
element.hide();
}
}
}
});
eventumDirective.directive('popUp', function () {
return {
link: function (scope, element, attrs) {
element.click(function () {
var x;
var y = document.getElementById("username").value;
var r=confirm(" Feedback\nDo you want to submit posting?");
if (r==true)
{
x="Feedback Submitted";
}
else
{
x="You pressed Cancel!";
}
document.getElementById("demo").innerHTML=x;
document.getElementById("de").innerHTML=y;
});
}
}
});
*/
|
module.exports = function (sequelize, DataTypes) {
var Tecnica = sequelize.define(
'Tecnica',
{
id: {
type: DataTypes.BIGINT(11),
primaryKey: true,
autoIncrement: true,
comment: 'ID tecnica',
validate: {
isNumeric:true,
notNull: true
}
},
tecnica: {
type: DataTypes.STRING(50),
allowNull: true,
defaultValue: null,
comment: 'Tecnica'
}
},
{
instanceMethods: {
retrieveAll: function (onSuccess, onError) {
Tecnica.findAll( { } )
.then(onSuccess).catch(onError);
},
retrieveById: function (tecnicaId, onSuccess, onError) {
Tecnica.find( { where: { id: tecnicaId } }, { raw: true })
.then(onSuccess).catch(onError);
},
add: function (onSuccess, onError) {
var tecnica = this.tecnica;
Tecnica.build({
tecnica: tecnica
})
.save().then(onSuccess).catch(onError);
},
updateById: function (tecnicaId, onSuccess, onError) {
var id = tecnicaId;
var tecnica = this.tecnica;
Tecnica.update({
tecnica: tecnica
},{ where: { id: id } })
.then(onSuccess).catch(onError);
},
removeById: function (tecnicaId, onSuccess, onError) {
Tecnica.destroy({ where: { id: tecnicaId }})
.then(onSuccess).catch(onError);
}
},
timestamps: true,
paranoid: true,
createdAt: 'fechaCrea',
updatedAt: 'fechaModifica',
deletedAt: 'fechaBorra',
underscore: false,
freezeTableName:true,
tableName: 'Tecnicas',
comment: 'Tecnicas registradas',
indexes: [
{
name: 'idxTecnica',
method: 'BTREE',
unique: false,
fields: ['tecnica']
}
]
}
);
return Tecnica;
};
|
const examples = [
'button', 'markdown'
];
F.component('list', {
template: require('../template/list.html'),
getData: function(cb) {
cb(examples.map(v => { return { href: "#" + v, name: v }; }));
}
});
|
import { connect } from 'react-redux';
// component
import WidgetsIndex from './component';
export default connect(
(state) => ({ user: state.user }),
null,
)(WidgetsIndex);
|
//
//{block name="backend/create_backend_order/store/create_backend_order"}
//
Ext.define('Shopware.apps.SwagBackendOrder.store.CreateBackendOrder', {
extend: 'Ext.data.Store',
model: 'Shopware.apps.SwagBackendOrder.model.CreateBackendOrder',
remoteSort: true,
remoteFilter: true,
pageSize: 50,
batch: true
});
//
//{/block}
|
// Generated by jsScript 1.10.0
(function() {
Meteor.publish('notifications', function() {
return Notifications.find({
owner: this.userId
});
});
}).call(this);
|
'use strict';
/**
* Module dependencies.
*/
var mongoose = require('mongoose'),
errorHandler = require('./errors.server.controller'),
Student = mongoose.model('Student'),
_ = require('lodash');
/**
* Create a Student
*/
exports.create = function(req, res) {
var student = new Student(req.body);
student.user = req.user;
student.save(function(err) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
res.jsonp(student);
}
});
};
/**
* Show the current Student
*/
exports.read = function(req, res) {
res.jsonp(req.student);
};
/**
* Update a Student
*/
exports.update = function(req, res) {
var student = req.student ;
student = _.extend(student , req.body);
student.save(function(err) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
res.jsonp(student);
}
});
};
/**
* Delete an Student
*/
exports.delete = function(req, res) {
var student = req.student ;
student.remove(function(err) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
res.jsonp(student);
}
});
};
/**
* List of Students
*/
exports.list = function(req, res) {
Student.find().sort('-created').populate('user', 'displayName').exec(function(err, students) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
res.jsonp(students);
}
});
};
/**
* Student middleware
*/
exports.studentByID = function(req, res, next, id) {
Student.findById(id).populate('user', 'displayName').exec(function(err, student) {
if (err) return next(err);
if (! student) return next(new Error('Failed to load Student ' + id));
req.student = student ;
next();
});
};
/**
* Student authorization middleware
*/
exports.hasAuthorization = function(req, res, next) {
// if (req.student.user.id !== req.user.id) {
// return res.status(403).send('User is not authorized');
// }
next();
};
|
KISSY.add('mux.bcharts/charts/js/m/widget/widget',function(S,Base,Node,SVGElement){
var $ = Node.all
function Widget(){
var self = this
/*
arguments:
o:{
parent_id:'' //div id
w :100 //div 宽
h :100 //div 高
type :'' //图表类型[histogram = 直方图 | line = ]
config :'' //图表配置
data :'' //图表数据
}
*/
Widget.superclass.constructor.apply(self,arguments);
self.init()
}
Widget.ATTRS = {
path_chart:{
value:'' //图表路径[mux.bcharts/charts/js/e/***/main]
},
_FileType:{ //文件类型
value:{
histogram : 'histogram',
histogram2: 'histogram2',
histogram3: 'histogram3',
integrate : 'integrate',
integrate2: 'integrate2',
integrate3: 'integrate3',
integrate4: 'integrate4',
integrate5: 'integrate5',
line : 'line',
line2 : 'line2',
line3 : 'line3',
pie : 'pie',
scatter : 'scatter',
map : 'map',
treemap :'treemap',
treemap2 :'treemap2'
}
},
_svg:{
value:null //svg主节点
},
_main:{
value:null //main节点
}
}
S.extend(Widget,Base,{
init:function(){
var self = this
if(!self.get('type')){
self.set('type', self.get('_FileType').histogram)
}
self.set('path_chart', self._getPath(self.get('_FileType')[self.get('type')]))
self._widget()
},
_widget:function(){
var self = this
//展现
S.use(self.get('path_chart'),function(S,Main){
//删除svg内容
var parent = $('#' + self.get('parent_id')).getDOMNode()
if(parent && parent.lastChild) {parent.removeChild(parent.lastChild)}
self.set('_svg',new SVGElement('svg'))
self.get('_svg').attr({'version':'1.1','width':self.get('w'),'height':self.get('h'),'xmlns':'http://www.w3.org/2000/svg', 'xmlns:xlink':'http://www.w3.org/1999/xlink'});
//'zoomAndpan':"disable" //禁止鼠标右键面板
$('#' + self.get('parent_id')).append(self.get('_svg').element)
self.get('_svg').set('style','cursor:default'), self.get('_svg').mouseEvent(false)
var o = {}
o.parent = self.get('_svg') //SVGElement
o.w = self.get('w') //chart 宽
o.h = self.get('h') //chart 高
o.type = self.get('type') //图表类型
o.config = self.get('config') //配置
o.data = self.get('data') //图表数据
self.set('_main',new Main(o))
})
},
//获取图表js路径
_getPath:function($name){
var self = this
return 'mux.bcharts/charts/js/e/' + $name + '/' + 'main'
}
});
return Widget;
}, {
requires:['base','node','../../pub/utils/svgelement']
}
); |
(function () {
'use strict';
describe('Trainings Test', function () {
var $scope, createController;
beforeEach(module('ui.router'));
beforeEach(module('training.module'));
beforeEach(inject(function ($rootScope,$controller,$injector,$templateCache) {
createController = function(resolveTrainings) {
return $controller('trainingController', {
$scope: $scope,resolveTrainings:resolveTrainings
});
};
}));
it('should init with 0 training', function () {
var controller = createController([]);
expect(controller.trainings.length).toBe(0);
});
});
})();
|
let utils = require('./utils')
let webpack = require('webpack')
let config = require('../config')
let merge = require('webpack-merge')
let baseWebpackConfig = require('./webpack.base.conf')
let HtmlWebpackPlugin = require('html-webpack-plugin')
let FriendlyErrorsPlugin = require('friendly-errors-webpack-plugin')
// add hot-reload related code to entry chunks
Object.keys(baseWebpackConfig.entry).forEach(function (name) {
baseWebpackConfig.entry[name] = ['./build/dev-client'].concat(baseWebpackConfig.entry[name])
})
module.exports = merge(baseWebpackConfig, {
module: {
rules: utils.styleLoaders({sourceMap: config.dev.cssSourceMap})
},
// cheap-module-eval-source-map is faster for development
devtool: '#cheap-module-eval-source-map',
plugins: [
new webpack.DefinePlugin({
'process.env': config.dev.env
}),
// https://github.com/glenjamin/webpack-hot-middleware#installation--usage
new webpack.HotModuleReplacementPlugin(),
new webpack.NoEmitOnErrorsPlugin(),
// https://github.com/ampedandwired/html-webpack-plugin
new HtmlWebpackPlugin({
filename: 'index.html',
template: 'index.html',
favicon: 'favicon.ico',
inject: true
}),
new FriendlyErrorsPlugin()
]
})
|
version https://git-lfs.github.com/spec/v1
oid sha256:43684d18fb457a7cb1ca66fee3aa3b13f08e2fbbec2bcedf8c3749607ee8ada5
size 2282
|
function getProperty(object, path) {
if (!object || typeof(object) !== 'object') {
return undefined;
}
var parts = path.split('.');
return parts.length > 1 ? getProperty(object[parts.shift()], parts.join('.')) : object[path];
}
function hasProperty(object, path) {
if (!object || typeof(object) !== 'object') {
return false;
}
var parts = path.split('.');
return parts.length > 1 ? hasProperty(object[parts.shift()], parts.join('.')) : Object.prototype.hasOwnProperty.call(object, path);
}
function setProperty(object, path, value) {
if (object && typeof(object) === 'object') {
var parts = path.split('.');
if (parts.length > 1 && !Object.prototype.hasOwnProperty.call(object, parts[0])) {
object[parts[0]] = {};
}
parts.length > 1 ? setProperty(object[parts.shift()], parts.join('.'), value) : object[path] = value;
}
return object;
}
function deleteProperty(object, path) {
if (object && typeof(object) === 'object') {
var parts = path.split('.');
parts.length > 1 ? deleteProperty(object[parts.shift()], parts.join('.')) : delete object[path];
}
return object;
}
exports.getProperty = getProperty;
exports.hasProperty = hasProperty;
exports.setProperty = setProperty;
exports.deleteProperty = deleteProperty; |
var BaseField = require('./BaseField');
var Crypto = require('crypto');
class IdField extends BaseField {
parseForCreate(input) {
// @todo uniqueness
if(this.opts.primary) {
return { value: Crypto.randomBytes(8).toString('hex').slice(0, 16) };
}
}
}
module.exports = IdField;
|
var DAY = 1000 * 60 * 60 * 24;
module.exports = function(app){
return {
name: 'getSubjects',
fn: function(next){
app.untis.subjects().then(function(subjects){
next(null, subjects);
}, function(err){
next(err);
});
},
options: {
cache: {
expiresIn: DAY
}
}
}
}
|
/**
* React Starter Kit (https://www.reactstarterkit.com/)
*
* Copyright © 2014-present Kriasoft, LLC. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE.txt file in the root directory of this source tree.
*/
import sequelize from '../sequelize';
import { User, UserLogin, UserClaim, UserProfile, UserGroup } from './User';
import { Article, ArticleTag } from './Article';
import { File, FILETYPE, LINKTO, ROOTID } from './File';
import { Group } from './Group';
import Blog from './Blog';
function sync(...args) {
return sequelize.sync(...args);
}
export default { sync };
export { User, UserLogin, UserClaim, UserProfile };
export { Article, ArticleTag };
export { File, FILETYPE, LINKTO, ROOTID };
export { UserGroup };
export { Blog };
export { Group };
|
'use strict';
require('./lib/index').WebServer.create().start();
|
require("./prototypes/string");
require("./prototypes/array");
require("./prototypes/object");
require("./prototypes/map");
require("./prototypes/set");
|
import { NgModule, NgZone, OpaqueToken, Inject, Optional } from '@angular/core';
import { LIB_KEY, LIB_KEY_SEPARATOR } from './constants/lib';
import { STORAGE } from './enums/storage';
import { LocalStorageService, SessionStorageService } from './services/index';
import { WebStorageHelper } from './helpers/webStorage';
import { WebstorageConfig } from './interfaces/config';
import { KeyStorageHelper } from './helpers/keyStorage';
export * from './interfaces/index';
export * from './decorators/index';
export * from './services/index';
export var WEBSTORAGE_CONFIG = new OpaqueToken('WEBSTORAGE_CONFIG');
export var Ng2Webstorage = (function () {
function Ng2Webstorage(ngZone, config) {
this.ngZone = ngZone;
if (config) {
KeyStorageHelper.setStorageKeyPrefix(config.prefix);
KeyStorageHelper.setStorageKeySeparator(config.separator);
}
this.initStorageListener();
}
Ng2Webstorage.forRoot = function (config) {
return {
ngModule: Ng2Webstorage,
providers: [
{
provide: WEBSTORAGE_CONFIG,
useValue: config
},
{
provide: WebstorageConfig,
useFactory: provideConfig,
deps: [
WEBSTORAGE_CONFIG
]
}
]
};
};
Ng2Webstorage.prototype.initStorageListener = function () {
var _this = this;
if (window) {
window.addEventListener('storage', function (event) { return _this.ngZone.run(function () {
var storage = window.sessionStorage === event.storageArea ? STORAGE.session : STORAGE.local;
WebStorageHelper.refresh(storage, event.key);
}); });
}
};
Ng2Webstorage.decorators = [
{ type: NgModule, args: [{
declarations: [],
providers: [SessionStorageService, LocalStorageService],
imports: []
},] },
];
/** @nocollapse */
Ng2Webstorage.ctorParameters = function () { return [
{ type: NgZone, },
{ type: WebstorageConfig, decorators: [{ type: Optional }, { type: Inject, args: [WebstorageConfig,] },] },
]; };
return Ng2Webstorage;
}());
export function provideConfig(config) {
return new WebstorageConfig(config);
}
export function configure(_a) {
var _b = _a === void 0 ? { prefix: LIB_KEY, separator: LIB_KEY_SEPARATOR } : _a, prefix = _b.prefix, separator = _b.separator;
/*@Deprecation*/
console.warn('[ng2-webstorage:deprecation] The configure method is deprecated since the v1.5.0, consider to use forRoot instead');
KeyStorageHelper.setStorageKeyPrefix(prefix);
KeyStorageHelper.setStorageKeySeparator(separator);
}
//# sourceMappingURL=app.js.map |
function onGLC(glc) {
glc.loop();
// glc.size(400, 400);
// glc.setDuration(5);
// glc.setFPS(20);
// glc.setMode("single");
// glc.setEasing(false);
// glc.setMaxColors(256);
var list = glc.renderList,
width = glc.w,
height = glc.h;
// your code goes here:
list.addGrid({
x: 0,
y: 0,
w: width,
h: height,
lineWidth: 1,
gridSize: [20, 30]
})
} |
/**
* !!! This file can be found as worker.js in the quick_server folder !!!
*
* Provides worker oriented networking interface.
*
* Created by krause on 2016-06-22.
*/
export const CONFIG = {
preDelay: 500,
timeStart: 500,
// has to be below 2min so the server doesn't remove the result
timeCap: 1000*60,
timeMinInc: 10,
timeMulInc: 1.01,
animation: ['⠋', '⠙', '⠸', '⠴', '⠦', '⠇'],
// animation: ['/', '-', '\\', '|'],
animationTime: 300,
};
export const VERSION = '0.7.15';
export class Worker {
constructor() {
window.addEventListener('beforeunload', () => {
Object.keys(this._tokens).forEach((ref) => {
// we probably won't read the results but
// the server still should cancel properly
this.cancel(ref);
});
});
this._status = (req) => {};
this._active = true;
this._infoTitle = true;
this._beforeTitle = null;
this._ownTitle = null;
this._req = 0;
this._animationIx = 0;
this._animationInFlight = false;
this._starts = {};
this._tokens = {};
this._urls = {};
}
set status(status) {
this._status = status;
}
get status() {
return this._status;
}
set active(active) {
this._active = active;
}
get active() {
return this._active;
}
set infoTitle(infoTitle) {
if (!infoTitle) {
this.setAddTitle('');
}
this._infoTitle = infoTitle;
}
get infoTitle() {
return this._infoTitle;
}
setAddTitle(addTitle) {
if (!this._infoTitle) return;
const curTitle = document.title;
if (this._ownTitle && curTitle !== this._ownTitle) { // external change
this._beforeTitle = curTitle;
}
if (!this._beforeTitle) {
this._beforeTitle = curTitle;
}
this._ownTitle = this._beforeTitle + addTitle;
document.title = this._ownTitle;
} // setAddTitle
sendRequest(url, obj, cb) {
const BENIGN_ERR = 'BENIGN_ERR';
fetch(url, {
method: 'POST',
headers: new Headers({
'Content-Type': 'application/json',
'Content-Length': `${obj.length}`,
}),
body: obj,
}).then((data) => {
if (data.status !== 200 || !data.ok) {
cb({
err: data.statusText,
code: data.status,
}, null);
throw new Error(BENIGN_ERR);
}
const ct = data.headers.get('content-type');
if (ct && ct.includes('application/json')) {
return data.json();
}
throw new TypeError('response not JSON encoded');
}).then((data) => cb(null, data)).catch((e) => {
if (e.message !== BENIGN_ERR) cb(e, null);
});
}
changeStatus(inc, error) {
if (this._req < 0) return;
if (error) {
this._req = -1;
} else if (inc) {
this._req += 1;
} else {
this._req -= 1;
}
this.titleStatus();
this._status(this._req);
} // changeStatus
titleStatus() {
if (this._req <= 0) {
this.setAddTitle('');
return;
}
const anim = CONFIG.animation;
let txt = ` ${anim[this._animationIx % anim.length]}`;
if (this._req > 1) {
txt += ` (${this._req}x)`;
}
this.setAddTitle(txt);
if (this._infoTitle && !this._animationInFlight) {
this._animationIx = (this._animationIx + 1) % anim.length;
this._animationInFlight = true;
setTimeout(() => {
this._animationInFlight = false;
this.titleStatus();
}, CONFIG.animationTime);
}
} // titleStatus
getPayload(data, url, cb, errCb) {
if (!data.continue) {
cb(JSON.parse(data.result));
return;
}
const keys = data.result;
const res = {};
keys.forEach((k) => {
const obj = JSON.stringify({
action: 'cargo',
token: k,
});
this.sendRequest(url, obj, (err, data) => {
if (err) {
console.warn(`Failed to retrieve cargo ${k}`);
this.changeStatus(false, true);
console.warn(err);
errCb && errCb(err);
return;
}
if (k !== data.token) {
const errMsg = `Mismatching token ${k} !== ${data.token}`;
console.warn(errMsg);
this.changeStatus(false, true);
errCb && errCb({
err: errMsg,
});
return;
}
res[k] = data.result;
checkFinished();
});
});
const checkFinished = () => {
if (!keys.every((k) => k in res)) {
return;
}
const d = keys.map((k) => res[k]).join(''); // string may be too long :(
keys.forEach((k) => { // free memory
res[k] = null;
});
cb(JSON.parse(d));
}; // checkFinished
} // getPayload
postTask(ref) {
setTimeout(() => {
if (!this._starts[ref]) return;
const s = this._starts[ref];
const url = s.url;
const cb = s.cb;
const errCb = s.errCb;
this._starts[ref] = null;
this.changeStatus(true, false);
const obj = JSON.stringify({
action: 'start',
payload: s.payload,
});
this.sendRequest(url, obj, (err, data) => {
if (err) {
console.warn(`Failed to start ${ref}`);
this.changeStatus(false, true);
console.warn(err);
errCb && errCb(err);
return;
}
this._cancel(ref, (err) => {
if (err) {
console.warn(`Failed to cancel ${ref}`);
this.changeStatus(false, true);
return console.warn(err);
}
});
if (data.done) {
this.getPayload(data, url, (d) => {
this.execute(cb, d);
}, errCb);
} else {
const token = +data.token;
this._urls[ref] = url;
this._tokens[ref] = token;
this.monitor(ref, token, cb, errCb, CONFIG.timeStart);
}
});
}, CONFIG.preDelay);
} // postTask
monitor(ref, token, cb, errCb, delay) {
if (this._tokens[ref] !== token) {
this.changeStatus(false, false);
return;
}
const url = this._urls[ref];
const obj = JSON.stringify({
action: 'get',
token: token,
});
this.sendRequest(url, obj, (err, data) => {
if (err) {
console.warn(`Error while retrieving ${ref} token: ${token}`);
this.changeStatus(false, true);
console.warn(err);
errCb && errCb(err);
return;
}
const curToken = +data.token;
if (curToken !== this._tokens[ref]) {
// late response
this.changeStatus(false, false);
return;
}
if (curToken !== token) {
// wrong response
console.warn(`Error while retrieving ${ref}`);
this.changeStatus(false, true);
const errData = {
err: `token mismatch: ${curToken} instead of ${token}`,
};
console.warn(errData);
errCb && errCb(errData);
return;
}
if (data.done) {
this._tokens[ref] = -1;
this._urls[ref] = null;
this.getPayload(data, url, (d) => {
this.execute(cb, d);
});
} else if (data.continue) {
setTimeout(() => {
const newDelay = Math.min(
Math.max(
delay * CONFIG.timeMulInc, delay + CONFIG.timeMinInc
), CONFIG.timeCap
);
this.monitor(ref, token, cb, errCb, newDelay);
}, delay);
} else {
this.changeStatus(false, false);
}
});
} // monitor
_cancel(ref, cb) {
if (!(ref in this._tokens && this._tokens[ref] >= 0)) return;
const token = this._tokens[ref];
const url = this._urls[ref];
const obj = JSON.stringify({
action: 'stop',
token: token,
});
this._tokens[ref] = -1;
this._urls[ref] = null;
this.sendRequest(url, obj, (err, data) => {
if (err) {
return cb(err);
}
return cb(+data['token'] !== token && {
err: `token mismatch: ${data['token']} instead of ${token}`,
});
});
} // _cancel
execute(cb, data) {
let err = true;
try {
cb(data);
err = false;
} finally {
if (err) {
this.changeStatus(false, true);
} else {
this.changeStatus(false, false);
}
}
} // execute
post(ref, url, payload, cb, errCb) {
if (!this._active) return;
this._starts[ref] = {
url: url,
cb: cb,
errCb: errCb,
payload: payload,
};
this.postTask(ref);
} // post
cancel(ref) {
this._cancel(ref, (err) => {
this.changeStatus(false, !!err);
if (err) {
console.warn(`Failed to cancel ${ref}`);
return console.warn(err);
}
});
} // cancel
} // Worker
export class VariablePool {
constructor(worker, objectPath) {
this._worker = worker;
this._objectPath = objectPath;
this._curQuery = {};
this._variables = {};
this._count = 0;
this._timer = null;
}
executeQuery() {
const query = this._curQuery;
if(Object.keys(query).length === 0) return;
const count = this._count;
this._curQuery = {};
this._count += 1;
this._worker.post(`query${count}`, this._objectPath, {
"query": query,
}, (data) => {
this._applyValues(this._variables, data, []);
});
}
_queueQuery(chg) {
if(!chg) return;
if(this._timer !== null) return;
this._timer = setTimeout(() => {
this.executeQuery();
this._timer = null;
}, 1);
}
_applyValues(vars, data, path) {
Object.keys(data).forEach((k) => {
const d = data[k];
if("map" in d) {
if(!(k in vars)) {
vars[k] = new WeakMap();
}
Object.keys(d.map).forEach((innerK) => {
if(!(innerK in vars[k])) {
vars[k][innerK] = {};
}
this._applyValues(vars[k][innerK], d.map[innerK], path + [k, innerK]);
});
} else if("value" in d) {
vars[k] = Object.seal(new Variable(this, path + [k], true, d.value));
} else {
console.warn("incorrect response", d);
throw new Error("internal error")
}
});
}
_addAction(qobj, path, type, value) {
if(path.length >= 2) {
const key = path[0];
if(!(key in qobj)) {
qobj[key] = {
"type": "get",
"queries": {},
};
} else if(!("queries" in qobj[key])) {
qobj[key]["queries"] = {};
}
const kname = path[1];
if(!(kname in qobj[key]["queries"])) {
qobj[key]["queries"][kname] = {};
}
return this._addAction(
qobj[key]["queries"][kname], path.slice(2), type, value);
}
const name = path[0];
if(!(name in qobj)) {
qobj[name] = {};
} else {
if(qobj[name]["type"] === "set" && type !== "set") {
return false;
}
}
if(type !== "get" && type !== "set") {
throw new Error(`invalid type: ${type}`);
}
qobj[name]["type"] = type;
if(type === "set") {
qobj[name]["value"] = value;
}
return true;
}
addGetAction(path) {
const chg = this._addAction(this._curQuery, path, "get", undefined);
this._queueQuery(chg);
}
addSetAction(path, value) {
const chg = this._addAction(this._curQuery, path, "set", value);
this._queueQuery(chg);
}
getValue(path) {
const full = path.slice();
let vars = this._variables;
while(path.length > 1) {
const mapName = path.shift();
const key = path.shift();
if(!(mapName in vars)) {
vars[mapName] = new WeakMap();
}
if(!(key in vars[mapName][key])) {
vars[mapName][key] = {};
}
vars = vars[mapName][key];
}
if(!path.length) {
throw new Error(`expected longer path: ${full}`);
}
const name = path.shift();
if(!(name in vars)) {
vars[name] = Object.seal(new Variable(this, full, false, null));
}
return vars[name];
}
} // VariablePool
class Variable {
constructor(pool, path, sync, value) {
this._pool = pool;
this._path = path;
this._sync = sync;
this._value = value;
}
update() {
this._pool.addGetAction(this._path);
}
has() {
if(!this._sync) {
this.update();
}
return this._sync;
}
get value() {
if(!this.has()) {
throw new Error("variable not in sync");
}
return this._value;
}
set value(val) {
this._pool.addSetAction(this._path, val);
}
} // Variable
// *** FIXME Experimental React API for direct object access. ***
export let IOProvider = null;
export let withIO = null;
try {
import('react').then((React) => {
const { Provider, Consumer } = React.createContext(undefined);
class IOProviderRaw extends React.PureComponent {
constructor(props) {
super(props);
this.state = {
pool: null,
};
}
componentWillMount() {
this.propsToState({}, this.props);
}
componentWillReceiveProps(nextProps) {
this.propsToState(this.props, nextProps);
}
propsToState(props, nextProps) {
const { objectPath="/objects/" } = nextProps;
if(props.objectPath === objectPath) return;
this.setState({
pool: new VariablePool(new Worker(), objectPath),
});
}
render() {
const { children } = this.props;
const { pool } = this.state;
if(!pool) return null;
return React.createElement(Provider, {
value: pool,
}, children);
}
} // IOProviderRaw
IOProvider = IOProviderRaw;
const withIORaw = (keys, component) => {
return React.createElement(Consumer, {}, (pool) => {
return function IOComponent(props) {
const newProps = Object.assign({}, props);
keys(props).forEach((k) => {
newProps[k] = pool.getValue([k]);
});
return React.createElement(component, newProps, props.children);
};
});
};
withIO = withIORaw;
});
} catch(e) {
console.warn("react not found", e);
}
|
'use strict';
var expect = require('chai').expect,
kasane = require('../lib/kasane');
describe('kasane', function () {
describe('.use', function () {
it('should throw errors if `path` argument is not a string', function () {
try {
kasane().use(1, function () {});
} catch (err) {
expect(err).to.be.instanceOf(Error);
}
});
it('should throw errors if `dispatcher` argument is not a function', function () {
try {
kasane().use('/', 1);
} catch (err) {
expect(err).to.be.instanceOf(Error);
}
});
it('should add middleware successfully', function () {
kasane().use(function () {});
kasane().use('/test', function () {});
});
});
});
|
"use strict";
(function () {
var app = angular.module("todoApp", ["todoController"]);
})(); |
/*
* Connection
* Copyright (c) 2014 Björn Acker | http://www.bjoernacker.de
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
this.gordon = this.gordon || {};
(function () {
'use strict';
var Connection = function (client, protocol) {
this._client = client;
this._protocol = protocol;
this.url = "";
};
var p = Connection.prototype;
p.connect = function (url) {
var that = this;
this.url = url;
this._webSocket = new WebSocket(this.url, ["gordon-protocol"]);
this._webSocket.binaryType = 'arraybuffer';
this._webSocket.onopen = function () {
that._client._log("[gordon] connected");
that._client.emit(gordon.Event.CONNECTED, 0);
};
this._webSocket.onclose = function () {
that._client._log("[gordon] closed");
that._client.emit(gordon.Event.CLOSED);
};
this._webSocket.onerror = function (error) {
that._client._log("[gordon] error", error);
that._client.emit(gordon.Event.CONNECTED, 1);
};
this._webSocket.onmessage = function (e) {
that._protocol.parse(e.data);
};
};
p.send = function (dataView, length) {
if (this._webSocket.readyState != 1) return;
var buffer = new ArrayBuffer(length + 4);
var bufferView = new DataView(buffer);
bufferView.setUint32(0, length);
gordon.Util.copyBytes(buffer, dataView.buffer, 4, 0, length);
this._webSocket.send(buffer);
};
p.dispose = function () {
this._webSocket.close();
this._webSocket = null;
this._client = null;
};
gordon.Connection = Connection;
}());
|
import React, { PropTypes } from 'react';
class ComentariosForm extends React.Component {
handleSubmit (e) {
e.preventDefault();
var text = this.refs.text.value;
if (!text) {
return;
}
this.props.onCommentSubmit({comment: text});
this.refs.text.value = '';
}
render () {
return (
<div className="commentForm">
<form className="" onSubmit={this.handleSubmit.bind(this)}>
<div className="input-group">
<textarea className="form-control" rows="3" ref="text" placeholder="Comenta algo..." defaultValue={this.props.children || ''}></textarea>
<span className="input-group-addon"><button type="submit" className="btn btn-primary">Enviar</button></span>
</div>
</form>
<div className="comment-info">Compatible con markdown</div>
</div>
);
}
}
export default ComentariosForm;
|
'use strict';
var chalk = require('chalk');
var _ = require('lodash');
var api = require('../lib/api');
var logger = require('../lib/logger');
var utils = require('../lib/utils');
var ALLOWED_JSON_KEYS = [
'localId', 'email', 'emailVerified', 'passwordHash', 'salt', 'displayName', 'photoUrl', 'createdAt', 'lastSignedInAt',
'providerUserInfo', 'phoneNumber'];
var ALLOWED_JSON_KEYS_RENAMING = {
lastSignedInAt: 'lastLoginAt'
};
var ALLOWED_PROVIDER_USER_INFO_KEYS = ['providerId', 'rawId', 'email', 'displayName', 'photoUrl'];
var ALLOWED_PROVIDER_IDS = ['google.com', 'facebook.com', 'twitter.com', 'github.com'];
var _toWebSafeBase64 = function(data) {
return data.toString('base64').replace(/\//g, '_').replace(/\+/g, '-');
};
var _addProviderUserInfo = function(user, providerId, arr) {
if (arr[0]) {
user.providerUserInfo.push({
providerId: providerId,
rawId: arr[0],
email: arr[1],
displayName: arr[2],
photoUrl: arr[3]
});
}
};
var _genUploadAccountPostBody = function(projectId, accounts, hashOptions) {
var postBody = {
users: accounts.map(
function(account) {
if (account.passwordHash) {
account.passwordHash = _toWebSafeBase64(account.passwordHash);
}
if (account.salt) {
account.salt = _toWebSafeBase64(account.salt);
}
_.each(ALLOWED_JSON_KEYS_RENAMING, function(value, key) {
if (account[key]) {
account[value] = account[key];
delete account[key];
}
});
return account;
})
};
if (hashOptions.hashAlgo) {
postBody.hashAlgorithm = hashOptions.hashAlgo;
}
if (hashOptions.hashKey) {
postBody.signerKey = _toWebSafeBase64(hashOptions.hashKey);
}
if (hashOptions.saltSeparator) {
postBody.saltSeparator = _toWebSafeBase64(hashOptions.saltSeparator);
}
if (hashOptions.rounds) {
postBody.rounds = hashOptions.rounds;
}
if (hashOptions.memCost) {
postBody.memoryCost = hashOptions.memCost;
}
if (hashOptions.cpuMemCost) {
postBody.cpuMemCost = hashOptions.cpuMemCost;
}
if (hashOptions.parallelization) {
postBody.parallelization = hashOptions.parallelization;
}
if (hashOptions.blockSize) {
postBody.blockSize = hashOptions.blockSize;
}
if (hashOptions.dkLen) {
postBody.dkLen = hashOptions.dkLen;
}
postBody.targetProjectId = projectId;
return postBody;
};
var transArrayToUser = function(arr) {
var user = {
localId: arr[0],
email: arr[1],
emailVerified: arr[2] === 'true',
passwordHash: arr[3],
salt: arr[4],
displayName: arr[5],
photoUrl: arr[6],
createdAt: arr[23],
lastLoginAt: arr[24],
phoneNumber: arr[26],
providerUserInfo: []
};
_addProviderUserInfo(user, 'google.com', arr.slice(7, 11));
_addProviderUserInfo(user, 'facebook.com', arr.slice(11, 15));
_addProviderUserInfo(user, 'twitter.com', arr.slice(15, 19));
_addProviderUserInfo(user, 'github.com', arr.slice(19, 23));
return user;
};
var validateOptions = function(options) {
if (!options.hashAlgo) {
utils.logWarning('No hash algorithm specified. Password users cannot be imported.');
return {valid: true};
}
var hashAlgo = options.hashAlgo.toUpperCase();
switch (hashAlgo) {
case 'HMAC_SHA512':
case 'HMAC_SHA256':
case 'HMAC_SHA1':
case 'HMAC_MD5':
if (!options.hashKey || options.hashKey === '') {
return utils.reject('Must provide hash key(base64 encoded) for hash algorithm ' + options.hashAlgo, {exit: 1});
}
return {hashAlgo: hashAlgo, hashKey: options.hashKey, valid: true};
case 'MD5':
case 'SHA1':
case 'SHA256':
case 'SHA512':
case 'PBKDF_SHA1':
case 'PBKDF2_SHA256':
var roundsNum = parseInt(options.rounds, 10);
if (isNaN(roundsNum) || roundsNum < 0 || roundsNum > 30000) {
return utils.reject('Must provide valid rounds(0..30000) for hash algorithm ' + options.hashAlgo, {exit: 1});
}
return {hashAlgo: hashAlgo, rounds: options.rounds, valid: true};
case 'SCRYPT':
if (!options.hashKey || options.hashKey === '') {
return utils.reject('Must provide hash key(base64 encoded) for hash algorithm ' + options.hashAlgo, {exit: 1});
}
roundsNum = parseInt(options.rounds, 10);
if (isNaN(roundsNum) || roundsNum <= 0 || roundsNum > 8) {
return utils.reject('Must provide valid rounds(1..8) for hash algorithm ' + options.hashAlgo, {exit: 1});
}
var memCost = parseInt(options.memCost, 10);
if (isNaN(memCost) || memCost <= 0 || memCost > 14) {
return utils.reject('Must provide valid memory cost(1..14) for hash algorithm ' + options.hashAlgo, {exit: 1});
}
var saltSeparator = '';
if (options.saltSeparator) {
saltSeparator = options.saltSeparator;
}
return {
hashAlgo: hashAlgo,
hashKey: options.hashKey,
saltSeparator: saltSeparator,
rounds: options.rounds,
memCost: options.memCost,
valid: true
};
case 'BCRYPT':
return {hashAlgo: hashAlgo, valid: true};
case 'STANDARD_SCRYPT':
var cpuMemCost = parseInt(options.memCost, 10);
var parallelization = parseInt(options.parallelization, 10);
var blockSize = parseInt(options.blockSize, 10);
var dkLen = parseInt(options.dkLen, 10);
return {
hashAlgo: hashAlgo,
valid: true,
cpuMemCost: cpuMemCost,
parallelization: parallelization,
blockSize: blockSize,
dkLen: dkLen
};
default:
return utils.reject('Unsupported hash algorithm ' + chalk.bold(options.hashAlgo));
}
};
var _validateProviderUserInfo = function(providerUserInfo) {
if (!_.includes(ALLOWED_PROVIDER_IDS, providerUserInfo.providerId)) {
return {error: JSON.stringify(providerUserInfo, null, 2) + ' has unsupported providerId'};
}
var keydiff = _.difference(_.keys(providerUserInfo), ALLOWED_PROVIDER_USER_INFO_KEYS);
if (keydiff.length) {
return {error: JSON.stringify(providerUserInfo, null, 2) + ' has unsupported keys: ' + keydiff.join(',')};
}
return {};
};
var validateUserJson = function(userJson) {
var keydiff = _.difference(_.keys(userJson), ALLOWED_JSON_KEYS);
if (keydiff.length) {
return {error: JSON.stringify(userJson, null, 2) + ' has unsupported keys: ' + keydiff.join(',')};
}
if (userJson.providerUserInfo) {
for (var i = 0; i < userJson.providerUserInfo.length; i++) {
var res = _validateProviderUserInfo(userJson.providerUserInfo[i]);
if (res.error) {
return res;
}
}
}
return {};
};
var _sendRequest = function(projectId, userList, hashOptions) {
logger.info('Starting importing ' + userList.length + ' account(s).');
return api.request('POST', '/identitytoolkit/v3/relyingparty/uploadAccount', {
auth: true,
json: true,
data: _genUploadAccountPostBody(projectId, userList, hashOptions),
origin: api.googleOrigin
}).then(function(ret) {
if (ret.body.error) {
logger.info('Encountered problems while importing accounts. Details:');
logger.info(ret.body.error.map(
function(rawInfo) {
return {
account: JSON.stringify(userList[parseInt(rawInfo.index, 10)], null, 2),
reason: rawInfo.message
};
}));
} else {
utils.logSuccess('Imported successfully.');
}
logger.info();
});
};
var serialImportUsers = function(projectId, hashOptions, userListArr, index) {
return _sendRequest(projectId, userListArr[index], hashOptions)
.then(function() {
if (index < userListArr.length - 1) {
return serialImportUsers(projectId, hashOptions, userListArr, index + 1);
}
});
};
var accountImporter = {
validateOptions: validateOptions,
validateUserJson: validateUserJson,
transArrayToUser: transArrayToUser,
serialImportUsers: serialImportUsers
};
module.exports = accountImporter;
|
import {Form} from 'widget/form/form'
import {LegendBuilder, defaultColor} from 'app/home/map/legendBuilder'
import {Panel} from 'widget/panel/panel'
import {RecipeFormPanel, recipeFormPanel} from 'app/home/body/process/recipeFormPanel'
import {activator} from 'widget/activation/activator'
import {compose} from 'compose'
import {downloadCsv} from 'widget/download'
import {msg} from 'translate'
import {selectFrom} from 'stateUtils'
import ButtonSelect from 'widget/buttonSelect'
import PropTypes from 'prop-types'
import React from 'react'
import _ from 'lodash'
import guid from 'guid'
import styles from './legend.module.css'
const fields = {
invalidEntries: new Form.Field()
.predicate(invalid => !invalid, 'invalid'),
entries: new Form.Field()
.predicate((entries, {invalidEntries}) => !invalidEntries && entries.length, 'invalid')
}
const mapRecipeToProps = recipe => {
return ({
importedLegendEntries: selectFrom(recipe, 'ui.importedLegendEntries'),
legendEntries: selectFrom(recipe, 'model.legend.entries') || [],
title: recipe.title || recipe.placeholder
})
}
class _Legend extends React.Component {
render() {
return (
<RecipeFormPanel
placement='bottom-right'
className={styles.panel}>
<Panel.Header
icon='list'
title={msg('process.remapping.panel.legend.title')}
/>
<Panel.Content scrollable={false}>
{this.renderContent()}
</Panel.Content>
<Form.PanelButtons>
{this.renderAddButton()}
</Form.PanelButtons>
</RecipeFormPanel>
)
}
renderAddButton() {
const {inputs: {entries}} = this.props
const options = [
{
value: 'import',
label: msg('map.legendBuilder.load.options.importFromCsv.label'),
onSelect: () => this.importLegend()
},
{
value: 'export',
label: msg('map.legendBuilder.load.options.exportToCsv.label'),
disabled: !entries.value || !entries.value.length,
onSelect: () => this.exportLegend()
}
]
return (
<ButtonSelect
look={'add'}
icon={'plus'}
label={msg('button.add')}
placement='above'
tooltipPlacement='bottom'
options={options}
onClick={() => this.addEntry()}
/>
)
}
renderContent() {
const {inputs: {entries}} = this.props
return (
<LegendBuilder
entries={entries.value}
onChange={(updatedEntries, invalid) => this.updateLegendEntries(updatedEntries, invalid)}
/>
)
}
componentDidMount() {
const {legendEntries, inputs} = this.props
inputs.entries.set(legendEntries)
}
componentDidUpdate(prevProps) {
const {inputs, importedLegendEntries, recipeActionBuilder} = this.props
if (importedLegendEntries && !_.isEqual(importedLegendEntries, prevProps.importedLegendEntries)) {
recipeActionBuilder('CLEAR_IMPORTED_LEGEND_ENTRIES', {importedLegendEntries})
.del('ui.importedLegendEntries')
.dispatch()
inputs.entries.set(importedLegendEntries)
}
}
addEntry() {
const {inputs: {entries}} = this.props
const id = guid()
const max = _.maxBy(entries.value, 'value')
const value = max ? max.value + 1 : 1
const color = defaultColor(entries.value.length)
const label = ''
entries.set([...entries.value, {id, value, color, label}])
}
updateLegendEntries(legendEntries, invalidLegendEntries) {
const {inputs} = this.props
inputs.entries.set(legendEntries)
inputs.invalidEntries.set(invalidLegendEntries)
}
importLegend() {
const {activator: {activatables: {legendImport}}} = this.props
legendImport.activate()
}
exportLegend() {
const {title, inputs: {entries}} = this.props
const csv = [
['color,value,label'],
entries.value.map(({color, value, label}) => `${color},${value},"${label.replaceAll('"', '\\"')}"`)
].flat().join('\n')
const filename = `${title}_legend.csv`
downloadCsv(csv, filename)
}
}
const valuesToModel = ({entries}) => ({
entries: _.sortBy(entries, 'value')
})
const additionalPolicy = () => ({
_: 'disallow',
legendImport: 'allow'
})
export const Legend = compose(
_Legend,
recipeFormPanel({id: 'legend', fields, mapRecipeToProps, additionalPolicy, valuesToModel}),
activator('legendImport')
)
Legend.propTypes = {
recipeId: PropTypes.string
}
|
"use strict";
/**
* Created by akselon on 2017-04-24.
*/
var League = (function () {
function League(id, name) {
this.id = id;
this.name = name;
}
;
return League;
}());
exports.League = League;
//# sourceMappingURL=league.js.map |
const path = require('path')
const boilerplate = require('workshopper-boilerplate')
const run = require('../../lib/run')
const bruggieMessage = require('../../lib/bruggie-message')
var exercise = require('workshopper-exercise')()
exercise = boilerplate(exercise)
exercise = run(exercise)
exercise = bruggieMessage(exercise)
exercise.addBoilerplate(path.join(__dirname, './01-nap-time.js'))
module.exports = exercise
|
import Conan from "conan";
import attachRolePolicyStep from "../../lib/steps/attachRolePolicyStep.js";
import sinon from "sinon";
import chai from "chai";
describe(".attachRolePolicyStep(conan, context, stepDone)", () => {
let conan,
context,
stepDone,
awsResponseError,
awsResponseData,
stepReturnError,
should,
parameters;
const mockIam = {
attachRolePolicy: sinon.spy((params, callback) => {
callback(awsResponseError, awsResponseData);
})
};
const MockAWS = {
IAM: sinon.spy(() => {
return mockIam;
})
};
beforeEach(done => {
should = chai.should();
conan = new Conan({
region: "us-east-1"
});
parameters = new class MockConanAwsLambda {
role() { return "TestRolePolicy"; }
}();
context = {
parameters: parameters,
libraries: { AWS: MockAWS },
results: {}
};
awsResponseData = {};
awsResponseError = null;
stepDone = (afterStepCallback) => {
return (error) => {
stepReturnError = error;
afterStepCallback();
};
};
attachRolePolicyStep(conan, context, stepDone(done));
});
it("should be a function", () => {
(typeof attachRolePolicyStep).should.equal("function");
});
it("should set the designated region on the lambda client", () => {
MockAWS.IAM.calledWith({
region: conan.config.region
}).should.be.true;
});
it("should call AWS with the designated parameters", () => {
mockIam.attachRolePolicy.calledWith({
RoleName: context.parameters.role(),
PolicyArn: "arn:aws:iam::aws:policy/AWSLambdaExecute"
}).should.be.true;
});
describe("(Policy Attached)", () => {
it("should return no error", () => {
should.not.exist(stepReturnError);
});
});
describe("(Unknown Error is Returned)", () => {
let errorMessage;
beforeEach(done => {
errorMessage = "AWS returned status code 401";
awsResponseError = { statusCode: 401, message: errorMessage };
attachRolePolicyStep(conan, context, stepDone(done));
});
it("should return an error which stops the step runner", () => {
stepReturnError.message.should.eql(errorMessage);
});
});
});
|
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
export default {
entry: '../../../dist/packages-dist/router/index.js',
dest: '../../../dist/packages-dist/router/bundles/router.umd.js',
format: 'umd',
moduleName: 'ng.router',
globals: {
'@angular/core': 'ng.core',
'@angular/common': 'ng.common',
'@angular/platform-browser': 'ng.platformBrowser',
'rxjs/BehaviorSubject': 'Rx',
'rxjs/Observable': 'Rx',
'rxjs/Rx': 'Rx',
'rxjs/Subject': 'Rx',
'rxjs/Subscription': 'Rx',
'rxjs/util/EmptyError': 'Rx',
'rxjs/observable/from': 'Rx.Observable',
'rxjs/observable/fromPromise': 'Rx.Observable',
'rxjs/observable/forkJoin': 'Rx.Observable',
'rxjs/observable/of': 'Rx.Observable',
'rxjs/add/observable/combineLatest': 'Rx.Observable',
'rxjs/operator/concatMap': 'Rx.Observable.prototype',
'rxjs/operator/toPromise': 'Rx.Observable.prototype',
'rxjs/operator/map': 'Rx.Observable.prototype',
'rxjs/operator/mergeAll': 'Rx.Observable.prototype',
'rxjs/operator/concatAll': 'Rx.Observable.prototype',
'rxjs/operator/mergeMap': 'Rx.Observable.prototype',
'rxjs/operator/reduce': 'Rx.Observable.prototype',
'rxjs/operator/every': 'Rx.Observable.prototype',
'rxjs/operator/first': 'Rx.Observable.prototype',
'rxjs/operator/catch': 'Rx.Observable.prototype',
'rxjs/operator/last': 'Rx.Observable.prototype',
'rxjs/operator/filter': 'Rx.Observable.prototype',
'rxjs/add/operator/map': 'Rx.Observable.prototype'
},
plugins: []
};
|
version https://git-lfs.github.com/spec/v1
oid sha256:3242ed6005ac5563f9959de1d45ac897f34c259a3ca8b6ab21cce51b826872dc
size 61353
|
/*
jcclient.js - Don Cross
https://github.com/cosinekitty/jcadmin
*/
;(function(){
'use strict';
function ApiCall(verb, path, onSuccess, onFailure) {
var handled = false;
var request = new XMLHttpRequest();
request.onreadystatechange = function(){
if (!handled) {
if (request.readyState === XMLHttpRequest.DONE) {
handled = true;
if (request.status === 200) {
var responseJson = JSON.parse(request.responseText);
if (!responseJson.error) {
onSuccess && onSuccess(responseJson);
} else {
console.log('ApiCall(%s) returned error object for %s :', verb, path);
console.log(responseJson.error);
onFailure && onFailure(request);
}
} else {
console.log('ApiCall(%s) failure for %s :', verb, path);
console.log(request);
onFailure && onFailure(request);
}
}
}
};
request.open(verb, path);
request.timeout = 2000;
request.send(null);
}
function ApiGet(path, onSuccess, onFailure) {
ApiCall('GET', path, onSuccess, onFailure);
}
function ApiPost(path, onSuccess, onFailure) {
ApiCall('POST', path, onSuccess, onFailure);
}
function ApiDelete(path, onSuccess, onFailure) {
ApiCall('DELETE', path, onSuccess, onFailure);
}
// A list of all mutually-exclusive elements (only one is visible at a time):
var ModalDivList = [
'RecentCallsDiv',
'TargetCallDiv',
'LostContactDiv',
'CreateEditNumberDiv',
'SettingsDiv'
];
var ActiveDivStack = [];
var LostContactCount = 0;
var MyLocalStorage = CheckStorage('localStorage');
var ClientSettings = LoadClientSettings();
// For toggling display of various types of call history rows.
var DisplayRowsOfType = {
neutral: true,
blocked: true,
safe: true
};
var HistoryDisplayModeIndex = 0;
var HistoryDisplayModeRing = ['all', 'safe', 'blocked', 'neutral'];
function HistoryDisplayModeIcon() {
// Choose which icon to display in the upper left corner
// of the history page, depending on which mode the user
// has selected by clicking on that icon.
return HistoryDisplayModeRing[HistoryDisplayModeIndex] + '.png';
}
function CycleHistoryDisplayMode() {
// Choose the next mode in the ring of modes: all, safe only, blocked only.
HistoryDisplayModeIndex = (1 + HistoryDisplayModeIndex) % HistoryDisplayModeRing.length;
var mode = HistoryDisplayModeRing[HistoryDisplayModeIndex];
DisplayRowsOfType.neutral = (mode==='all' || mode==='neutral');
DisplayRowsOfType.blocked = (mode==='all' || mode==='blocked');
DisplayRowsOfType.safe = (mode==='all' || mode==='safe');
}
function UpdateRowDisplay(callHistoryRows) { // call to reflect current DisplayRowsOfType settings
for (var i=0; i < callHistoryRows.length; ++i) {
var row = callHistoryRows[i];
var status = row.getAttribute('data-caller-status');
row.style.display = DisplayRowsOfType[status] ? '' : 'none';
}
}
var PollTimer = null;
var PrevPoll = {
callerid: {
loaded: false, // indicates that this is not real data yet
modified: '',
data: {
calls: [],
limit: 0,
start: 0,
total: 0,
count: {},
names: {}
}
},
safe: {
loaded: false, // indicates that this is not real data yet
modified: '',
data: {
table: {}
}
},
blocked: {
loaded: false, // indicates that this is not real data yet
modified: '',
data: {
table: {}
}
},
};
function IsAllDataLoaded() {
return PrevPoll.callerid.loaded && PrevPoll.safe.loaded && PrevPoll.blocked.loaded;
}
function ShowActiveDiv(activeDivId) {
ModalDivList.forEach(function(divId){
var div = document.getElementById(divId);
if (divId === activeDivId) {
div.style.display = '';
} else {
div.style.display = 'none';
}
});
}
function PushActiveDiv(activeDivId) {
if (ActiveDivStack.length > 0) {
// Preserve the scroll state of the element we are about to hide.
var top = ActiveDivStack[ActiveDivStack.length - 1];
var div = document.getElementById(top.divid);
top.scroll = window.scrollY;
}
ShowActiveDiv(activeDivId);
ActiveDivStack.push({
divid: activeDivId,
scroll: 0 // placeholder for vertical scroll pixels - doesn't matter till we push another div
});
}
function SetActiveDiv(activeDivId) {
ActiveDivStack = [];
PushActiveDiv(activeDivId);
}
function PopActiveDiv() {
ActiveDivStack.pop();
if (ActiveDivStack.length > 0) {
var top = ActiveDivStack[ActiveDivStack.length - 1];
var div = document.getElementById(top.divid);
ShowActiveDiv(top.divid);
window.scroll(0, top.scroll);
} else {
SetActiveDiv('RecentCallsDiv');
}
}
function EnableDisableControls(enabled) {
var disabled = !enabled;
document.getElementById('TargetRadioButtonSafe').disabled = disabled;
document.getElementById('TargetRadioButtonNeutral').disabled = disabled;
document.getElementById('TargetRadioButtonBlocked').disabled = disabled;
}
function SaveName(call, name) {
var url = '/api/rename/' + encodeURIComponent(call.number) + '/' + encodeURIComponent(name);
ApiPost(url, function(data){
// Update UI here?
});
}
function SetTargetStatus(numberStatus, callidStatus) {
document.getElementById('TargetNumberRow').className = BlockStatusClassName(numberStatus);
document.getElementById('TargetCallerIdRow').className = BlockStatusClassName(callidStatus);
}
function IsPhoneNumber(pattern) {
return pattern && pattern.match(/^[0-9]{7,11}$/);
}
function SanitizePhoneNumber(pattern) {
if (pattern) {
var cleaned = pattern.replace(/[^0-9]/g, '');
if (IsPhoneNumber(cleaned)) {
return cleaned;
}
}
return null;
}
function CallDateTimeHeader() {
var row = document.createElement('tr');
var callnumCell = document.createElement('th');
callnumCell.className = 'CallCountColumn';
callnumCell.textContent = '#';
row.appendChild(callnumCell);
var dowCell = document.createElement('th');
dowCell.className = 'HistoryColumn';
dowCell.textContent = 'DOW';
row.appendChild(dowCell);
var timeCell = document.createElement('th');
timeCell.className = 'HistoryColumn';
timeCell.textContent = 'Time';
row.appendChild(timeCell);
var dateCell = document.createElement('th');
dateCell.className = 'HistoryColumn';
dateCell.textContent = 'Date';
row.appendChild(dateCell);
return row;
}
function CallDateTimeRow(callnum, when) {
// Create a row with counter, yyyy-mm-dd, day of week, and hh:mm cells.
var p = ParseDateTime(when);
var row = document.createElement('tr');
var callnumCell = document.createElement('td');
callnumCell.className = 'CallCountColumn';
callnumCell.textContent = callnum;
row.appendChild(callnumCell);
var dowCell = document.createElement('td');
dowCell.className = 'HistoryColumn';
dowCell.textContent = p.dow;
row.appendChild(dowCell);
var timeCell = document.createElement('td');
timeCell.className = 'HistoryColumn';
timeCell.textContent = ZeroPad(p.hour,2) + ':' + ZeroPad(p.min,2);
row.appendChild(timeCell);
var dateCell = document.createElement('td');
dateCell.className = 'HistoryColumn';
dateCell.textContent = p.year + '-' + ZeroPad(p.month,2) + '-' + ZeroPad(p.day,2);
row.appendChild(dateCell);
return row;
}
function AppendCallDateTimesTable(hdiv, deleteButton, history) {
if (history.length > 0) {
var table = document.createElement('table');
table.className = 'TargetTable';
table.appendChild(CallDateTimeHeader());
for (var i=0; i < history.length; ++i) {
table.appendChild(CallDateTimeRow(history.length - i, history[i]));
}
hdiv.appendChild(table);
} else {
hdiv.textContent = 'No calls have been received from this phone number.';
deleteButton.style.display = ''; // caller has hidden the delete button, but now we know item can be deleted.
}
}
function SetPhoneNumberSearchLink(div, number) {
var link = document.createElement('a');
link.setAttribute('href', 'http://www.google.com/search?q=' + encodeURIComponent(number));
link.setAttribute('target', '_blank');
link.appendChild(document.createTextNode(number));
ClearElement(div);
div.appendChild(link);
}
function CallerDisplayName(number) {
return SanitizeSpaces(PrevPoll.callerid.data.names[number]) ||
SanitizeSpaces(PrevPoll.safe.data.table[number]) ||
SanitizeSpaces(PrevPoll.blocked.data.table[number]) ||
SanitizeSpaces(number);
}
function CallerId(number) {
return SanitizeSpaces(PrevPoll.callerid.data.callid[number]);
}
function SetTargetCall(call, history) {
var backButton = document.getElementById('BackToListButton');
var safeButton = document.getElementById('TargetRadioButtonSafe');
var neutralButton = document.getElementById('TargetRadioButtonNeutral');
var blockButton = document.getElementById('TargetRadioButtonBlocked');
var numberDiv = document.getElementById('TargetNumberDiv');
var nameEditBox = document.getElementById('TargetNameEditBox');
var callerIdDiv = document.getElementById('TargetCallerIdDiv');
var historyDiv = document.getElementById('TargetHistoryDiv');
var deleteButton = document.getElementById('DeleteTargetButton');
function Classify(status, phonenumber) {
EnableDisableControls(false);
var url = '/api/classify/' +
encodeURIComponent(status) + '/' +
encodeURIComponent(phonenumber);
ApiPost(url, function(data) {
var detail = FilterStatus(data.status, FieldStatus(call.callid));
SetTargetStatus(detail.numberStatus, detail.callidStatus);
EnableDisableControls(true);
});
}
SetPhoneNumberSearchLink(numberDiv, call.number);
nameEditBox.value = CallerDisplayName(call.number);
nameEditBox.onblur = function() {
SaveName(call, SanitizeSpaces(nameEditBox.value));
}
callerIdDiv.textContent = call.callid;
var detail = DetailedStatus(call);
SetTargetStatus(detail.numberStatus, detail.callidStatus);
switch (detail.numberStatus) {
case 'blocked': blockButton.checked = true; break;
case 'safe': safeButton.checked = true; break;
default: neutralButton.checked = true; break;
}
safeButton.onclick = function() { Classify('safe', call.number); }
neutralButton.onclick = function() { Classify('neutral', call.number); }
blockButton.onclick = function() { Classify('blocked', call.number); }
backButton.onclick = PopActiveDiv;
EnableDisableControls(true);
// Some callers pass in a history of date/times when calls have been received.
// Others pass in null to indicate that we need to fetch that info asyncronously.
ClearElement(historyDiv);
deleteButton.style.display = 'none'; // hide delete button until we know whether the entry can be deleted.
if (history) {
AppendCallDateTimesTable(historyDiv, deleteButton, history);
} else {
ApiGet('/api/caller/' + encodeURIComponent(call.number), function(data){
AppendCallDateTimesTable(historyDiv, deleteButton, data.history);
});
}
deleteButton.onclick = function() {
if (window.confirm('Delete entry?')) {
ApiDelete('/api/caller/' + encodeURIComponent(call.number), function(){
PopActiveDiv();
});
}
}
PushActiveDiv('TargetCallDiv');
}
function TryToCreateEditNumber(number) {
// Check the server for any existing data for this phone number.
ApiGet('/api/caller/' + encodeURIComponent(number), function(data) {
SetTargetCall(data.call, data.history);
});
}
function CreateNewCaller() {
var cancelButton = document.getElementById('CancelCreateEditButton');
var settinsButton = document.getElementById('SettingsButton');
var editButton = document.getElementById('TryCreateEditButton');
var editBox = document.getElementById('NumberEditBox');
editButton.style.display = 'none'; // do not show until valid number appears in edit box
editBox.value = ''; // clear out any previously entered phone number
editBox.focus();
cancelButton.onclick = PopActiveDiv;
SettingsButton.onclick = EnterSettingsPage;
editButton.onclick = function(evt) {
var number = SanitizePhoneNumber(editBox.value);
if (number !== null) {
TryToCreateEditNumber(number);
} else {
// Should never get here!!!
console.log('How did the edit button get clicked with an invalid number?');
}
}
editBox.onkeyup = function(evt) {
var number = SanitizePhoneNumber(editBox.value);
var key = evt.keyCode;
if (number !== null) {
// Show the edit button.
editButton.style.display = '';
// If user just pressed ENTER, act as if edit button was pressed: go to target page.
if (key === 13) {
TryToCreateEditNumber(number);
}
} else {
// Hide the edit button.
// If user just pressed ENTER, ignore it!
editButton.style.display = 'none';
}
}
PushActiveDiv('CreateEditNumberDiv');
}
function CreateCallerCell(call, status) {
var callerCell = document.createElement('td');
callerCell.setAttribute('colspan', '2');
if (call.number !== '') {
callerCell.textContent = CallerDisplayName(call.number);
callerCell.className = BlockStatusClassName(CallerStatus(call));
callerCell.onclick = function() {
SetTargetCall(call, null);
}
}
return callerCell;
}
function BlockStatusClassName(status) {
return {safe:'SafeCall', blocked:'BlockedCall'}[status] || 'NeutralCall';
}
function ZeroPad(n) {
var s = '' + n;
while (s.length < 2) {
s = '0' + s;
}
return s;
}
function PhoneListMatchText(list, text) {
for (var key in list) {
if (key.length > 0 && (text.indexOf(key) >= 0)) {
return true;
}
}
return false;
}
function FieldStatus(text) {
if (text) { // optimization: avoid linear searches that can't find anything
if (PhoneListMatchText(PrevPoll.safe.data.table, text)) {
return 'safe';
}
if (PhoneListMatchText(PrevPoll.blocked.data.table, text)) {
return 'blocked';
}
}
return 'neutral';
}
function FilterStatus(numberStatus, callidStatus) {
if (numberStatus==='safe' && callidStatus==='blocked') {
// avoid confusion: the caller is not blocked, so don't display caller ID as blocked
callidStatus = 'neutral';
} else if (callidStatus==='safe' && numberStatus==='blocked') {
numberStatus = 'neutral';
}
var status;
if (numberStatus==='safe' || callidStatus==='safe') {
status = 'safe';
} else if (numberStatus==='blocked' || callidStatus==='blocked') {
status = 'blocked';
} else {
status = 'neutral';
}
return {
numberStatus: numberStatus,
callidStatus: callidStatus,
status: status,
};
}
function DetailedStatus(call) {
// Analyze a call and compute detailed status information
// for phone number and caller ID independently, using the
// same rules as jcblock.
return FilterStatus(FieldStatus(call.number), FieldStatus(call.callid));
}
function CallerStatus(call) {
return DetailedStatus(call).status;
}
function SanitizeSpaces(text) {
// Replace redundant white space with a single space and trim outside spaces.
return text ? text.replace(/\s+/g, ' ').trim() : '';
}
function FormatDateTime(when, now) {
// Example: d = '2016-12-31 15:42'
var format = when;
var p = ParseDateTime(when);
if (p) {
// Remove the year: '12-13 15:42'.
format = when.substring(5);
if (now) {
// Replace 'yyyy-mm-dd' with weekday name if less than 7 calendar days ago: 'Fri 15:42'.
// Warning: formatting differently depending on the current date and time is
// "impure" in a functional sense, but I believe it creates a better user experience.
// Calculate the calendar date (year, month, day) of the date/time given in 'now'.
// Subtract six *calendar* days from it, not six 24-hour periods!
// The subtle part is handling daylight savings time, etc.
// This forms a cutoff date/time at midnight before which 'Sun', 'Mon',
// etc., become ambiguous.
var cutoff = new Date(now.getFullYear(), now.getMonth(), now.getDate()-6);
if (p.date.getTime() >= cutoff.getTime()) {
format = p.dow + when.substring(10); // 'Fri 15:42'
}
}
}
return format;
}
function ParseDateTime(when) {
var m = when.match(/^(\d{4})-(\d{2})-(\d{2})\s(\d{2}):(\d{2})$/);
if (m) {
var year = parseInt(m[1], 10);
var month = parseInt(m[2], 10);
var day = parseInt(m[3], 10);
var hour = parseInt(m[4], 10);
var min = parseInt(m[5], 10);
var date = new Date(year, month-1, day, hour, min);
var dow = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'][date.getDay()];
return {
date: date,
year: year,
month: month,
day: day,
hour: hour,
min: min,
dow: dow
};
}
return null;
}
function ClearElement(elem) {
while (elem.firstChild) {
elem.removeChild(elem.firstChild);
}
}
function IconCellForStatus(status) {
var iconCell = document.createElement('td');
var iconImg = document.createElement('img');
iconImg.setAttribute('src', status + '.png');
iconImg.setAttribute('width', '24');
iconImg.setAttribute('height', '24');
iconCell.appendChild(iconImg);
iconCell.className = BlockStatusClassName(status);
return iconCell;
}
function PopulateCallHistory() {
var rowlist = [];
var recent = PrevPoll.callerid.data.calls;
var table = document.createElement('table');
table.setAttribute('class', 'RecentCallTable');
var thead = document.createElement('thead');
var hrow = document.createElement('tr');
var hcell_icon = document.createElement('th');
hcell_icon.className = 'IconColumn';
var toggleIconImage = document.createElement('img');
toggleIconImage.setAttribute('src', HistoryDisplayModeIcon());
toggleIconImage.setAttribute('width', '24');
toggleIconImage.setAttribute('height', '24');
hcell_icon.appendChild(toggleIconImage);
hcell_icon.onclick = function() {
// Cycle through the next display mode.
CycleHistoryDisplayMode();
toggleIconImage.setAttribute('src', HistoryDisplayModeIcon());
UpdateRowDisplay(rowlist);
}
hrow.appendChild(hcell_icon);
var hcell_when = document.createElement('th');
hcell_when.appendChild(document.createTextNode('When'));
hrow.appendChild(hcell_when);
var hcell_name = document.createElement('th');
hcell_name.appendChild(document.createTextNode('Caller'));
hcell_name.className = 'CallerColumn';
hrow.appendChild(hcell_name);
var hcell_new = document.createElement('th');
hcell_new.className = 'IconColumn';
var newIcon = document.createElement('img');
newIcon.setAttribute('src', 'new.png');
newIcon.setAttribute('width', '24');
newIcon.setAttribute('height', '24');
hcell_new.appendChild(newIcon);
hcell_new.onclick = CreateNewCaller;
hrow.appendChild(hcell_new);
thead.appendChild(hrow);
var now = new Date();
var tbody = document.createElement('tbody');
var prevdate = null;
for (var i=0; i < recent.length; ++i) {
var call = recent[i];
var calldate = call.when && call.when.substr(0, 10);
call.count = PrevPoll.callerid.data.count[call.number] || '?';
var callStatusClassName = BlockStatusClassName(call.status);
var row = document.createElement('tr');
if (prevdate && calldate && (prevdate !== calldate)) {
row.setAttribute('class', 'NewDateRow');
}
row.setAttribute('data-caller-status', CallerStatus(call));
var iconCell = IconCellForStatus(call.status);
row.appendChild(iconCell);
var whenCell = document.createElement('td');
whenCell.appendChild(document.createTextNode(FormatDateTime(call.when, now)));
whenCell.className = callStatusClassName + ' WhenCell';
row.appendChild(whenCell);
row.appendChild(CreateCallerCell(call));
tbody.appendChild(row);
rowlist.push(row);
prevdate = calldate;
}
table.appendChild(thead);
table.appendChild(tbody);
// Remove existing children from RecentCallsDiv.
var rcdiv = document.getElementById('RecentCallsDiv');
ClearElement(rcdiv);
// Fill in newly-generted content for the RecentCallsDiv...
rcdiv.appendChild(table);
UpdateRowDisplay(rowlist);
}
var PhoneNumbersInOrder = PhoneNumbersInOrder_ByName;
var PhoneBookSortDirection = +1; // 1=ascending, -1=descending
function SortableColumnText(label, sortfunc) {
if (sortfunc === PhoneNumbersInOrder) {
// Put an arrow on this column to indicate that we are sorting by it.
var arrow = (PhoneBookSortDirection > 0) ? '⇓' : '⇑';
return label + ' ' + arrow;
}
return label;
}
function PhoneNumbersInOrder_ByName(aEntry, bEntry) {
var aNameUpper = aEntry.name.toUpperCase();
var bNameUpper = bEntry.name.toUpperCase();
if (aNameUpper === bNameUpper) {
return aEntry.name < bEntry.name; // break the tie with case-sensitive match
}
return aNameUpper < bNameUpper;
}
function PhoneNumbersInOrder_ByNumber(aEntry, bEntry) {
return aEntry.number < bEntry.number;
}
function PhoneNumbersInOrder_ByCallCount(aEntry, bEntry) {
return aEntry.count < bEntry.count;
}
function PhoneBookSortComparer(aEntry, bEntry) {
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort
if (PhoneNumbersInOrder(aEntry, bEntry)) {
return -PhoneBookSortDirection;
}
if (PhoneNumbersInOrder(bEntry, aEntry)) {
return +PhoneBookSortDirection;
}
return 0;
}
function SortedPhoneBook() {
// Calculate the set of all known phone numbers.
// Phone numbers are known if they have a user-defined name,
// or they appear in either the safe list or the blocked list.
var allPhoneNumberSet = {};
for (var number in PrevPoll.callerid.data.names) {
if (IsPhoneNumber(number)) {
allPhoneNumberSet[number] = CallerDisplayName(number);
}
}
for (var number in PrevPoll.safe.data.table) {
if (IsPhoneNumber(number)) {
allPhoneNumberSet[number] = CallerDisplayName(number);
}
}
for (var number in PrevPoll.blocked.data.table) {
if (IsPhoneNumber(number)) {
allPhoneNumberSet[number] = CallerDisplayName(number);
}
}
// Create an array of {number:number, name:name, count:count} objects to sort.
var book = [];
for (var number in allPhoneNumberSet) {
book.push({
number: number,
name: allPhoneNumberSet[number],
callid: CallerId(number),
count: PrevPoll.callerid.data.count[number] || 0
});
}
// Sort the phone book array using the current sort method:
book.sort(PhoneBookSortComparer);
return book;
}
function OnPhoneBookRowClicked() {
var number = this.getAttribute('data-phone-number');
TryToCreateEditNumber(number);
}
var PhoneBookStatusFilter = ['all', 'safe', 'neutral', 'blocked'];
var PhoneBookStatusFilterIndex = 0;
function UpdateFilterIcon(toggleIconImage) {
toggleIconImage.setAttribute('src', PhoneBookStatusFilter[PhoneBookStatusFilterIndex] + '.png');
}
function UpdatePhoneBookRowDisplay(rowlist) {
var filter = PhoneBookStatusFilter[PhoneBookStatusFilterIndex];
for (var i=0; i < rowlist.length; ++i) {
var row = rowlist[i];
var status = row.getAttribute('data-caller-status');
row.style.display = ((filter === 'all' || filter === status) ? '' : 'none');
}
}
function SetPhoneBookSort(sortfunc) {
if (PhoneNumbersInOrder === sortfunc) {
// Toggle the direction of sorting on the same column.
PhoneBookSortDirection *= -1;
} else {
// Switch to ascending sort on a different column.
PhoneBookSortDirection = +1;
PhoneNumbersInOrder = sortfunc;
}
// Re-render the phone book table in the new sort order.
PopulatePhoneBook();
}
function PopulatePhoneBook() {
var rowlist = [];
var book = SortedPhoneBook();
var phoneBookDiv = document.getElementById('PhoneBookDiv');
var table = document.createElement('table');
ClearElement(phoneBookDiv);
phoneBookDiv.appendChild(table);
var hrow = document.createElement('tr');
table.appendChild(hrow);
var hStatusCell = document.createElement('th');
hStatusCell.className = 'IconColumn';
var toggleIconImage = document.createElement('img');
UpdateFilterIcon(toggleIconImage);
toggleIconImage.setAttribute('width', '24');
toggleIconImage.setAttribute('height', '24');
hStatusCell.appendChild(toggleIconImage);
hStatusCell.onclick = function() {
// Cycle through status filters for displaying different subsets of rows.
PhoneBookStatusFilterIndex = (1 + PhoneBookStatusFilterIndex) % PhoneBookStatusFilter.length;
UpdateFilterIcon(toggleIconImage);
UpdatePhoneBookRowDisplay(rowlist);
}
hrow.appendChild(hStatusCell);
var hCountCell = document.createElement('th');
hCountCell.className = 'CallCountColumn';
hCountCell.innerHTML = SortableColumnText('Calls', PhoneNumbersInOrder_ByCallCount);
hCountCell.onclick = function() {
SetPhoneBookSort(PhoneNumbersInOrder_ByCallCount);
}
hrow.appendChild(hCountCell);
var hNumberCell = document.createElement('th');
hNumberCell.innerHTML = SortableColumnText('Number', PhoneNumbersInOrder_ByNumber);
hNumberCell.onclick = function() {
SetPhoneBookSort(PhoneNumbersInOrder_ByNumber);
}
hrow.appendChild(hNumberCell);
var hNameCell = document.createElement('th');
hNameCell.className = 'CallerColumn';
hNameCell.innerHTML = SortableColumnText('Name', PhoneNumbersInOrder_ByName);
hNameCell.onclick = function() {
SetPhoneBookSort(PhoneNumbersInOrder_ByName);
}
hrow.appendChild(hNameCell);
for (var i=0; i < book.length; ++i) {
var entry = book[i];
var row = document.createElement('tr');
var detail = DetailedStatus(entry);
row.setAttribute('data-caller-status', detail.status);
var statusCell = IconCellForStatus(detail.status);
row.appendChild(statusCell);
var countCell = document.createElement('td');
countCell.textContent = entry.count;
countCell.className = 'CallCountColumn';
row.appendChild(countCell);
var numberCell = document.createElement('td');
numberCell.textContent = entry.number;
numberCell.className = BlockStatusClassName(detail.numberStatus);
row.appendChild(numberCell);
var nameCell = document.createElement('td');
nameCell.textContent = entry.name;
nameCell.className = BlockStatusClassName(detail.callidStatus);
row.appendChild(nameCell);
row.setAttribute('data-phone-number', entry.number);
row.onclick = OnPhoneBookRowClicked;
table.appendChild(row);
rowlist.push(row);
}
UpdatePhoneBookRowDisplay(rowlist);
}
function EnterSettingsPage() {
var oldLimit = ClientSettings.RecentCallLimit;
var backButton = document.getElementById('SettingsBackButton');
backButton.onclick = PopActiveDiv;
// Search the HistoryLimit radio buttons for matching value to select.
// If we can't find a matching value, select smallest value and set to it.
// Either way we end up with the UI matching the actual limit value.
var historyLimitButtons = document.getElementsByName('HistoryLimit');
var found = false;
for (var i=0; i < historyLimitButtons.length; ++i) {
var button = historyLimitButtons[i];
var limit = parseInt(button.value);
if (limit === ClientSettings.RecentCallLimit) {
button.checked = true;
found = true;
}
button.onclick = function() {
var limit = parseInt(this.value);
if (limit !== ClientSettings.RecentCallLimit) {
ClientSettings.RecentCallLimit = limit;
SaveClientSettings(ClientSettings);
RefreshCallHistory();
}
}
}
if (!found) {
var button = historyLimitButtons[0];
ClientSettings.RecentCallLimit = parseInt(button.value);
button.checked = true;
}
if (oldLimit !== ClientSettings.RecentCallLimit) {
SaveClientSettings(ClientSettings);
RefreshCallHistory();
}
PushActiveDiv('SettingsDiv');
}
function UpdateUserInterface() {
if (IsAllDataLoaded()) {
PopulateCallHistory();
PopulatePhoneBook();
}
}
function RefreshCallHistory() {
ApiGet('/api/calls/0/' + ClientSettings.RecentCallLimit, function(calldata){
PrevPoll.callerid.data = calldata;
PrevPoll.callerid.loaded = true;
UpdateUserInterface();
});
}
function RefreshPhoneList(status) {
ApiGet('/api/fetch/' + status, function(data) {
PrevPoll[status].data = data;
PrevPoll[status].loaded = true;
UpdateUserInterface();
});
}
function PollCallerId() {
ApiGet('/api/poll', function(poll){
// On success.
if (LostContactCount > 0) {
LostContactCount = 0;
SetActiveDiv('RecentCallsDiv');
}
// check last-modified time stamps to see if we need to re-fetch the model.
if (PrevPoll.callerid.modified !== poll.callerid.modified) {
PrevPoll.callerid.modified = poll.callerid.modified;
RefreshCallHistory();
}
if (PrevPoll.safe.modified !== poll.safe.modified) {
PrevPoll.safe.modified = poll.safe.modified;
RefreshPhoneList('safe');
}
if (PrevPoll.blocked.modified !== poll.blocked.modified) {
PrevPoll.blocked.modified = poll.blocked.modified;
RefreshPhoneList('blocked');
}
PollTimer = window.setTimeout(PollCallerId, 2000);
},
function(request) {
// On failure, go into Lost Contact mode but keep polling for reconnect.
++LostContactCount;
if (LostContactCount === 1) {
SetActiveDiv('LostContactDiv');
}
PollTimer = window.setTimeout(PollCallerId, 2000);
});
}
function CheckStorage(type) {
try {
var storage = window[type], x = '__storage_test__';
storage.setItem(x, x);
storage.removeItem(x);
return storage;
} catch(e) {
return null;
}
}
function LoadClientSettings() {
var settings = null;
try {
if (MyLocalStorage && MyLocalStorage.JunkCallClient) {
settings = JSON.parse(MyLocalStorage.JunkCallClient);
}
} catch (e) {
// If there is a problem loading, just reset the local settings.
console.log('LoadClientSettings EXCEPTION: ', e);
}
if (!settings) {
// Getting here indicates first-time initialization *or* emergency reset.
settings = {
RecentCallLimit: 30
};
}
return settings;
}
function SaveClientSettings(settings) {
if (MyLocalStorage) {
MyLocalStorage.JunkCallClient = JSON.stringify(settings);
}
}
window.onload = function() {
SetActiveDiv('RecentCallsDiv');
PollCallerId();
}
})();
|
const { Model } = require('../../../');
const { expect } = require('chai');
module.exports = (session) => {
const { knex } = session;
describe('#ref attack', () => {
class Role extends Model {
static get tableName() {
return 'roles';
}
}
class User extends Model {
static get tableName() {
return 'users';
}
static get relationMappings() {
return {
roles: {
relation: Model.HasManyRelation,
modelClass: Role,
join: {
from: 'users.id',
to: 'roles.userId',
},
},
};
}
}
before(() => {
return knex.schema
.dropTableIfExists('users')
.dropTableIfExists('roles')
.createTable('users', (table) => {
table.increments('id').primary();
table.string('firstName');
table.string('lastName');
table.string('passwordHash');
})
.createTable('roles', (table) => {
table.increments('id').primary();
table.string('name');
table.integer('userId');
});
});
after(() => {
return knex.schema.dropTableIfExists('users').dropTableIfExists('roles');
});
beforeEach(async () => {
await User.query(knex).delete();
await User.query(knex).insertGraph([
{
id: 1,
firstName: 'dork 1',
passwordHash: 'secret',
},
{
id: 2,
firstName: 'dork 2',
},
]);
});
it('#ref{} should not be able to dig out secrets from db', async () => {
const attackGraph = [
{
id: 1,
firstName: 'updated dork',
'#id': 'id',
},
{
id: 2,
firstName: '#ref{id.passwordHash}',
lastName: 'something to trigger an update',
roles: [
{
name: '#ref{id.passwordHash}',
},
],
},
// This gets inserted.
{
id: 3,
firstName: '#ref{id.passwordHash}',
roles: [
{
name: '#ref{id.passwordHash}',
},
],
},
];
await User.query(knex).returning('*').upsertGraph(attackGraph, {
allowRefs: true,
insertMissing: true,
});
const user2 = await User.query(knex).findById(2).withGraphFetched('roles');
const user3 = await User.query(knex).findById(3).withGraphFetched('roles');
expect(user2.firstName).to.equal('dork 2');
expect(user2.roles[0].name).to.equal(null);
expect(user3.firstName).to.equal(null);
expect(user3.roles[0].name).to.equal(null);
});
});
};
|
define([
'text!../../html/alerts.html'
], function(temp){
return Backbone.View.extend({
el: '#alerts',
events: {
'click a[rel=submit-number]': 'submit'
},
initialize: function() {
this.template = Handlebars.compile(temp);
this.render();
},
render: function() {
$(this.el).html(this.template({}));
},
submit: function() {
$('#alerts input').removeClass('fix');
var social = $('input[name=social]').val();
var number = $('input[name=number]').val();
var fname = $('#alerts input[name=fname]').val();
var lname = $('#alerts input[name=lname]').val();
var to_fix = [];
if (!social) to_fix.push('social');
if (!number) to_fix.push('number');
if (to_fix.length) {
_.each(to_fix, function(field) {
$('input[name=' + field + ']').addClass('fix');
});
toastr.error('Please fill in required fields');
}
else if (!this.check_social(social)) {
$('input[name=social]').addClass('fix');
toastr.error('Social Security Number should be formatted as ###-##-####');
}
else if (!this.check_number(number)) {
$('input[name=number]').addClass('fix');
toastr.error('Phone Number should be formatted as ###-###-####');
}
else {
console.log(social, number);
$.ajax({
method: "POST",
contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
url: "/textmessage",
data: {
phoneNumber: number,
social: social,
fname: fname,
lname: lname
}
}).success(function( msg ){
console.log("Sent: " + msg);
});
}
return false;
},
check_social: function(social) {
//var social = social.split('-');
//if (social[0].length != 3) return false;
//if (social[1].length != 2) return false;
//if (social[2].length != 4) return false;
//if (isNaN(social.join(''))) return false;
return true;
},
check_number: function(number) {
var number = number.split('-');
if (number[0].length != 3) return false;
if (number[1].length != 3) return false;
if (number[2].length != 4) return false;
if (isNaN(number.join(''))) return false;
return true;
}
});
}); |
/*
MIT
Creato by Webz Ray
*/
CKEDITOR.dialog.add("wenzgmapDialog",function(b){return{title:"Insert Google Map",minWidth:400,minHeight:75,contents:[{id:"tab-basic",label:"Basic Settings",elements:[{type:"text",id:"addressStr",label:"Please enter your central map address"},{type:"text",id:"mapWidth",label:"Map Width (px)",style:"width:25%;"},{type:"text",id:"mapHeight",label:"Map Height (px)",style:"width:25%;"}]}],onOk:function(){var c=this.getValueOf("tab-basic","addressStr").trim(),d=this.getValueOf("tab-basic","mapWidth").trim(),
e=this.getValueOf("tab-basic","mapHeight").trim(),a=b.document.createElement("iframe");a.setAttribute("width",d);a.setAttribute("height",e);a.setAttribute("src","//maps.google.com/maps?q="+c+"&num=1&t=m&ie=UTF8&z=14&output=embed");a.setAttribute("frameborder","0");a.setAttribute("scrolling","no");b.insertElement(a)}}}); |
/**
* Created by lizhengwei on 2016/7/29.
*/
var app=angular.module('bookStoreApp',[]);
app.filter('to_trusted',['$sce',function($sce){
return function (text) {
return $sce.trustAsHtml(text);
}
}]);
app.service('deepCopyService',function(){
return function (obj) {
var result={};
for (var key in obj) {
result[key] = typeof obj[key]==='object'?arguments.callee(obj[key]):obj[key];
}
return result;
}
});
app.factory('cutHtmlService',function(){
return function (string) {
return string.replace(/<[^>]+>/g,'');
}
});
app.service('addItemService',function(){
return function(infos,info){
infos.unshift(info);
return infos;
};
});
app.service('searchItemsService',function(){
return function(infos,search){
var tmp=[];
infos.forEach(function(v,i){
if(v.author.indexOf(search)!=-1||v.bookName.indexOf(search)!=-1){
var arrAuthor=v.author.split(search);
var arrBookName=v.bookName.split(search);
if(arrAuthor){
v.author=arrAuthor.join('<span class="text-danger">'+search+'</span>');
}
if(arrBookName){
v.bookName=arrBookName.join('<span class="text-danger">'+search+'</span>');
}
tmp.push(v);
}
});
return tmp;
};
});
app.service('getBookIdService',function(){
return function(infos){
infos.sort(function(b,a){
return a.bookId-b.bookId;
});
return infos[0].bookId+1;
};
});
app.service('delItemService',function(){
return function(infos,bookId){
infos.forEach(function(v,i){
if(v.bookId==bookId){
infos.splice(i,1);
}
});
return infos;
};
});
app.service('editItemService',function(cutHtmlService){
return function(infos,bookId){
var obj={};
infos.forEach(function(v){
if(v.bookId==bookId){
obj=v;
obj.bookName=cutHtmlService(v.bookName);
obj.author=cutHtmlService(v.author);
}
});
return obj;
};
});
app.directive('list',function(){
return {
scope:{
listItem:'@'
},
restrict:'AE',
template:'<div class="col-md-offset-2 col-md-10" ng-repeat="bookInfo in bookInfos"><div class="row"><div class="col-md-2">{{bookInfo.author}}</div><div class="col-md-6">{{bookInfo.bookName}} </div> <div class="col-md-2"><a href="javascript:void(0)" ng-click="edit(bookInfo.bookId)">编辑</a><a href="javascript:void(0)" ng-click="del(bookInfo.bookId)">删除</a></div></div></div>',
replace:true,
controller:'BookInfoCtrl'
}
});
app.controller('BookInfoCtrl',function($scope,$timeout,addItemService,getBookIdService,delItemService,editItemService,searchItemsService,cutHtmlService){
$scope.isAdd=false;
$scope.bookInfo={
bookName:'',
author:'',
bookId:'',
search:''
};
$scope.bookInfos=[
{
bookName:"Javascript精编",
author:'zachary',
bookId:89
},
{
bookName:"Javascript入坑指南",
author:'HAHA',
bookId:27
},
{
bookName:"angular坑坑介绍",
author:'angel',
bookId:12
}
];
$scope.copyInfos=$scope.bookInfos.concat();
$scope.$watch('bookInfo.search',function(v){
$scope.reset();
$scope.bookInfos=searchItemsService($scope.copyInfos,v);
});
$scope.search=function(){
if($scope.bookInfo.search==''){
$scope.bookInfos=$scope.copyInfos;
//alert('请输入检索关键字!');
return;
}
$scope.isAdd=false;
$scope.bookInfos=searchItemsService($scope.copyInfos,$scope.bookInfo.search);
}
$scope.reset=function(){
$scope.isAdd=false;
$scope.bookInfo={
bookName:'',
author:'',
bookId:''
};
var tt=$scope.copyInfos.concat();
var tmp=[];
tt.forEach(function(v){
for(var i in v){
if(i!='bookId')v[i]=cutHtmlService(v[i]);
}
tmp.push(v);
});
$scope.bookInfos=tmp;
}
$scope.edit=function(bookId){
$scope.bookInfo=editItemService($scope.bookInfos,bookId);
$scope.isAdd=true;
$scope.copyInfos=$scope.bookInfos.concat();
}
$scope.del=function(bookId){
delItemService($scope.bookInfos,bookId);
$scope.copyInfos=$scope.bookInfos.concat();
}
$scope.add=function(){
if($scope.bookInfo.author==''){
alert('作者不能为空!');
return ;
}
if($scope.bookInfo.bookName==''){
alert('书名不能为空!') ;
return ;
}
$scope.bookInfo.bookId=getBookIdService($scope.bookInfos);
tmp=$scope.bookInfo;
addItemService($scope.bookInfos,tmp);
tmp={};
$scope.bookInfo={
bookName:'',
author:'',
bookId:''
};
$scope.copyInfos=$scope.bookInfos.concat();
};
}); |
import "./sass/index.scss";
import 'rxjs';
import React, {Component} from 'react';
import {render} from 'react-dom';
import App from './app';
function Main(){
return <App/>;
}
render(<Main/> , document.getElementById("reactapp"));
|
'use strict';
const Tag = require('../lexer/tag');
const Word = require('../lexer/word');
const Op = require('./op');
class Access extends Op {
constructor(line, id, expr, type) {
super(line, new Word('[]', Tag.INDEX), type);
this.array = id;
this.index = expr;
}
gen() {
return new Access(this.lexline, this.array, this.index.reduce(), this.type);
}
jumping(t, f) {
this.emitjumps(this.reduce().toString(), t, f);
}
toString() {
return this.array.toString() + ' [ ' + this.index.toString() + ' ]';
}
}
module.exports = Access;
|
import asAnUser from '../helpers/asAnUser'
import Articles from '../helpers/articles'
import setFieldWithReduxForm from '../helpers/setFieldWithReduxForm'
import sleep from '../helpers/sleep'
const host = 'http://localhost:3000'
describe('Articles', () => {
describe('Report', () => {
before(() => {
server.call('dev/resetDatabase')
server.call('dev/createArticles')
browser.url(host)
})
it('user should be able to report an article', () => {
const article = Articles('findOne', {})
asAnUser()
navigateToArticle(article)
clickOnReportBtn()
const formDoc = fillUpReportForm()
browser.click('button[type="submit"]')
sleep(2000)
const updatedArticle = Articles('findOne', {})
expect(updatedArticle).to.have.property('inappropriatedContentReports')
expect(updatedArticle.inappropriatedContentReports).to.be.an('array')
expect(updatedArticle.inappropriatedContentReports[0]).to.have.property('message', formDoc.message)
})
})
})
function navigateToArticle(article){
browser.url(`${host}/article/${article.slug}`)
}
function fillUpReportForm(){
const doc = {
message: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.',
}
setFieldWithReduxForm({
field: 'message',
value: doc.message,
form: 'reportArticle',
})
return doc
}
function clickOnReportBtn(){
browser.waitForVisible("div[data-name='report-btn']")
sleep(1000)
browser.selectorExecute('div[data-name="report-btn"]', (divs) => divs[0].click())
}
|
AutoForm.addHooks(['updateProfileData'], {
onSuccess: function(formType, result) {
bootbox.alert(TAPi18n.__("profile_updated", lang_tag=null));
},
onError: function(formType, error) {
bootbox.alert(TAPi18n.__(error.message, lang_tag=null));
}
});
var commentsHooks = {
before: {
insert: function(doc) {
if(Meteor.userId()){
doc.userId = Meteor.userId();
doc.supplierId = Router.current().params.id;
doc.userEmail = Meteor.users.find({_id:Meteor.userId()}).fetch()[0].emails[0].address;
return doc;
}
}
}
};
AutoForm.addHooks('insertSupplierComments', commentsHooks);
Template.getProfile.helpers({
userDetails: function() {
return Meteor.users.find({_id:Router.current().params.id}).fetch();
},
commentsSupplier: function() {
return SupplierComments.find({supplierId:Router.current().params.id});
}
});
Template.userDetail.helpers({
rating:function(){
return Session.get('ratSupp');
}
});
Template.userDetail.rendered = function () {
this.$('.rateit').rateit();
} |
import React from 'react';
import { connect } from 'react-redux'
import MessagesList from './MessagesList';
import SlackActions from '../actions/SlackActions';
class SearchMessagesSection extends React.Component {
componentDidMount() {
this.initialzeData(this.props.match.params.searchWord);
}
componentWillReceiveProps(nextProps) {
if (this.props.match.params.searchWord !== nextProps.match.params.searchWord) {
this.initialzeData(nextProps.match.params.searchWord);
}
}
initialzeData(searchWord) {
this.props.loadSearchMessages(decodeURIComponent(searchWord));
}
render() {
const { match, loadMoreSearchMessages } = this.props;
const searchWord = match.params.searchWord;
return (
<div className="search-messages">
<div className="messages-header">
<div className="title">Search: { searchWord }</div>
</div>
<MessagesList onLoadMoreMessages={loadMoreSearchMessages(searchWord)} />
</div>
);
}
}
const mapStateToProps = state => {
return {
router: state.router
};
};
const mapDispatchToProps = dispatch => {
return {
loadMoreSearchMessages: searchWord => params => {
dispatch(SlackActions.searchMore(searchWord, params));
},
loadSearchMessages: searchWord => {
dispatch(SlackActions.search(searchWord));
}
};
};
export default connect(mapStateToProps, mapDispatchToProps)(SearchMessagesSection);
|
// @flow
import {EventEmitter2 as EventEmitter } from "eventemitter2"
function filter(v: number, min: number, max: number): number {
v = Math.min(v, max);
v = Math.max(v, min);
return v;
}
class HitPoint extends EventEmitter {
current: number
max: number
constructor(current: number, max: number) {
super();
this.max = max;
this.min = 0;
this.current = filter(current, 0, this.max);
};
change(next: number): HitPoint {
this.current = filter(next, 0, this.max);;
this.emit("changed", {
next: this
});
return this;
}
empty(): bool {
return this.current <= this.min;
};
}
module.exports = HitPoint;
|
/**
* Created by chenchaowei on 4/24/15.
*/
describe('suite of tests for hello world', function () {
describe('another suite', function () {
var controller;
beforeEach(module('myApp.helloworld'));
beforeEach(inject(function ($controller) {
var $scope = {};
controller = $controller('HelloWorldController', { $scope: $scope });
}));
it('should have a message of Hello World!', function () {
expect(controller.message).toBe('Hello World!');
});
it('should have a data property equal to empty!', function () {
expect(controller.data).toBe('empty');
});
});
}); |
app.controller('app.controller', function($scope) {
$scope.data = {
lname: '',
fname: '',
email: '',
phone_mobile: ''
};
var masterData = angular.copy($scope.data);
var key;
$scope.isUpdating = false;
$scope.list = [];
$scope.btnClear = function () {
$scope.data = angular.copy(masterData);
$scope.mainForm.$setPristine();
console.log('Form has been cleared.');
};
$scope.btnNew = function () {
console.log('Started creating new row.');
$scope.list.push({
'lname': $scope.data.lname,
'fname': $scope.data.fname,
'email': $scope.data.email,
'phone_mobile': $scope.data.phone_mobile
});
$scope.btnClear();
console.log('Ended creating new row.');
};
$scope.UpdateRow = function (row, index) {
key = index;
$scope.data.lname = row.lname;
$scope.data.fname = row.fname;
$scope.data.email = row.email;
$scope.data.phone_mobile = row.phone_mobile;
$scope.isUpdating = true;
console.log('Updating selected row.');
};
$scope.btnUpdate = function() {
console.log('Started updating row.');
$scope.list[key].lname = $scope.data.lname;
$scope.list[key].fname = $scope.data.fname;
$scope.list[key].email = $scope.data.email;
$scope.list[key].phone_mobile = $scope.data.phone_mobile;
$scope.btnClear();
$scope.isUpdating = false;
console.log('Ended updating row.');
};
$scope.btnCancel = function() {
$scope.btnClear();
$scope.isUpdating = false;
console.log('Cancelled updating selected row.');
};
$scope.Delete = function (id) {
if (confirm("Are you sure you want to delete this row?")) {
$scope.list.splice(id, 1);
console.log('Row has been deleted.');
}
};
}); |
define(['exports', 'external'], function (exports, external) { 'use strict';
class Foo extends external.Component {
constructor () {
super();
this.isFoo = true;
}
}
class Bar extends external.Component {
constructor () {
super();
this.isBar = true;
}
}
class Baz extends external.Component {
constructor () {
super();
this.isBaz = true;
}
}
const foo = new Foo();
const bar = new Bar();
const baz = new Baz();
exports.foo = foo;
exports.bar = bar;
exports.baz = baz;
});
|
(function() {
'use strict';
angular.module('dataservice', [
'ngResource'
]);
})(); |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.